Datasets:
AI4M
/

text
stringlengths
0
3.34M
I welcome any ship to dock on my port. Or not. Another frame I regret not paying more attention to. Completely ignored the silence. One shot I made. This one. Luck!
------------------------------------------------------------------------ -- Partial functions, computability ------------------------------------------------------------------------ open import Atom module Computability (atoms : χ-atoms) where open import Equality.Propositional.Cubical open import Logical-equivalence using (_⇔_) open import Prelude as P hiding (_∘_; Decidable) open import Tactic.By.Propositional open import Bool equality-with-J open import Bijection equality-with-J using (_↔_) open import Double-negation equality-with-J open import Equality.Decision-procedures equality-with-J import Equivalence equality-with-J as Eq open import Function-universe equality-with-J hiding (id; _∘_) open import H-level equality-with-J as H-level open import H-level.Closure equality-with-J open import H-level.Truncation.Propositional equality-with-paths as Trunc open import Injection equality-with-J using (Injective) open import Monad equality-with-J open import Chi atoms open import Coding atoms import Coding.Instances atoms as Dummy open import Deterministic atoms open import Free-variables atoms open import Propositional atoms open import Reasoning atoms open import Values atoms -- Partial functions for which the relation defining the partial -- function must be propositional. record _⇀_ {a b} (A : Type a) (B : Type b) : Type (lsuc (a ⊔ b)) where infix 4 _[_]=_ field -- The relation defining the partial function. _[_]=_ : A → B → Type (a ⊔ b) -- The relation must be deterministic and propositional. deterministic : ∀ {a b₁ b₂} → _[_]=_ a b₁ → _[_]=_ a b₂ → b₁ ≡ b₂ propositional : ∀ {a b} → Is-proposition (_[_]=_ a b) -- A simple lemma. ∃[]=-propositional : ∀ {a} → Is-proposition (∃ (_[_]=_ a)) ∃[]=-propositional (b₁ , [a]=b₁) (b₂ , [a]=b₂) = Σ-≡,≡→≡ (deterministic [a]=b₁ [a]=b₂) (propositional _ _) open _⇀_ public using (_[_]=_) -- Totality. The definition is parametrised by something which could -- be a modality. Total : ∀ {a b} {A : Type a} {B : Type b} → (Type (a ⊔ b) → Type (a ⊔ b)) → A ⇀ B → Type (a ⊔ b) Total P f = ∀ a → P (∃ λ b → f [ a ]= b) -- Totality with ∥_∥ as the modality implies totality with the -- identity function as the modality. total-with-∥∥→total : ∀ {a b} {A : Type a} {B : Type b} (f : A ⇀ B) → Total ∥_∥ f → Total id f total-with-∥∥→total f total a = Trunc.rec (_⇀_.∃[]=-propositional f) id (total a) -- If the codomain of a function is a set, then the function can be -- turned into a partial function. as-partial : ∀ {a b} {A : Type a} {B : Type b} → Is-set B → (A → B) → A ⇀ B as-partial {ℓa} B-set f = record { _[_]=_ = λ a b → ↑ ℓa (f a ≡ b) ; deterministic = λ {a b₁ b₂} fa≡b₁ fa≡b₂ → b₁ ≡⟨ sym (lower fa≡b₁) ⟩ f a ≡⟨ lower fa≡b₂ ⟩∎ b₂ ∎ ; propositional = ↑-closure 1 (+⇒≡ {n = 1} B-set) } -- Composition of partial functions. infixr 9 _∘_ _∘_ : ∀ {ℓ c} {A B : Type ℓ} {C : Type c} → B ⇀ C → A ⇀ B → A ⇀ C f ∘ g = record { _[_]=_ = λ a c → ∃ λ b → g [ a ]= b × f [ b ]= c ; deterministic = λ where (b₁ , g[a]=b₁ , f[b₁]=c₁) (b₂ , g[a]=b₂ , f[b₂]=c₂) → _⇀_.deterministic f (subst (f [_]= _) (_⇀_.deterministic g g[a]=b₁ g[a]=b₂) f[b₁]=c₁) f[b₂]=c₂ ; propositional = λ {a c} → $⟨ Σ-closure 1 (_⇀_.∃[]=-propositional g) (λ _ → _⇀_.propositional f) ⟩ Is-proposition (∃ λ (p : ∃ λ b → g [ a ]= b) → f [ proj₁ p ]= c) ↝⟨ H-level.respects-surjection (_↔_.surjection $ inverse Σ-assoc) 1 ⟩□ Is-proposition (∃ λ b → g [ a ]= b × f [ b ]= c) □ } -- If f is a partial function, g a function whose domain is a set, and -- f (g a) = c, then (f ∘ g) a = c. pre-apply : ∀ {ℓ c} {A B : Type ℓ} {C : Type c} (f : B ⇀ C) {g : A → B} {a c} (B-set : Is-set B) → f [ g a ]= c → f ∘ as-partial B-set g [ a ]= c pre-apply _ _ f[ga]=b = _ , lift refl , f[ga]=b -- If f is a function whose domain is a set, g a partial function, and -- g a = b, then (f ∘ g) a = f b. post-apply : ∀ {ℓ c} {A B : Type ℓ} {C : Type c} {f : B → C} (g : A ⇀ B) {a b} (C-set : Is-set C) → g [ a ]= b → as-partial C-set f ∘ g [ a ]= f b post-apply _ _ g[a]=b = _ , g[a]=b , lift refl -- Implements P p f means that p is an implementation of f. The -- definition is parametrised by P, which could be a modality. Implements : ∀ {a b} {A : Type a} {B : Type b} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → (Type (a ⊔ b) → Type (a ⊔ b)) → Exp → A ⇀ B → Type (a ⊔ b) Implements P p f = Closed p × (∀ x y → f [ x ]= y → apply p ⌜ x ⌝ ⇓ ⌜ y ⌝) × (∀ x y → apply p ⌜ x ⌝ ⇓ y → P (∃ λ y′ → f [ x ]= y′ × y ≡ ⌜ y′ ⌝)) -- If P maps propositions to propositions, then Implements P p f is a -- proposition. Implements-propositional : ∀ {a b} {A : Type a} {B : Type b} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → {P : Type (a ⊔ b) → Type (a ⊔ b)} {p : Exp} (f : A ⇀ B) → (∀ {A} → Is-proposition A → Is-proposition (P A)) → Is-proposition (Implements P p f) Implements-propositional f pres = ×-closure 1 Closed-propositional $ ×-closure 1 (Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → ⇓-propositional) (Π-closure ext 1 λ x → Π-closure ext 1 λ y → Π-closure ext 1 λ _ → pres $ H-level.respects-surjection (_↔_.surjection $ inverse Σ-assoc) 1 (Σ-closure 1 (_⇀_.∃[]=-propositional f) λ _ → Exp-set)) -- Computability. The definition is parametrised by something which -- could be a modality. Computable′ : ∀ {a b} {A : Type a} {B : Type b} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → (Type (a ⊔ b) → Type (a ⊔ b)) → A ⇀ B → Type (a ⊔ b) Computable′ P f = ∃ λ p → Implements P p f -- Computability. Computable : ∀ {a b} {A : Type a} {B : Type b} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → A ⇀ B → Type (a ⊔ b) Computable = Computable′ id -- If the partial function is total, then one part of the proof of -- computability can be omitted. total→almost-computable→computable : ∀ {a b} {A : Type a} {B : Type b} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ (P : Type (a ⊔ b) → Type (a ⊔ b)) → (∀ {X Y} → (X → Y) → P X → P Y) → (f : A ⇀ B) → Total P f → (∃ λ p → Closed p × (∀ x y → f [ x ]= y → apply p ⌜ x ⌝ ⇓ ⌜ y ⌝)) → Computable′ P f total→almost-computable→computable P map f total (p , cl-p , hyp) = p , cl-p , hyp , λ x y px⇓y → flip map (total x) λ where (y′ , f[x]=y′) → y′ , f[x]=y′ , ⇓-deterministic px⇓y (hyp x y′ f[x]=y′) -- The semantics of χ as a partial function. semantics : Closed-exp ⇀ Closed-exp semantics = record { _[_]=_ = _⇓_ on proj₁ ; deterministic = λ e⇓v₁ e⇓v₂ → closed-equal-if-expressions-equal (⇓-deterministic e⇓v₁ e⇓v₂) ; propositional = ⇓-propositional } -- Another definition of computability. Computable″ : ∀ {ℓ} {A B : Type ℓ} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → A ⇀ B → Type ℓ Computable″ f = ∃ λ (p : Closed-exp) → ∀ a → ∀ q → semantics [ apply-cl p ⌜ a ⌝ ]= q ⇔ as-partial Closed-exp-set ⌜_⌝ ∘ f [ a ]= q -- The two definitions of computability are logically equivalent. Computable⇔Computable″ : ∀ {ℓ} {A B : Type ℓ} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → (f : A ⇀ B) → Computable f ⇔ Computable″ f Computable⇔Computable″ f = record { to = to; from = from } where to : Computable f → Computable″ f to (p , cl , hyp₁ , hyp₂) = (p , cl) , λ { a (q , cl-q) → record { to = Σ-map id (Σ-map id (lift P.∘ closed-equal-if-expressions-equal P.∘ sym)) P.∘ hyp₂ a q ; from = λ { (b , f[a]=b , ⌜b⌝≡q) → apply p ⌜ a ⌝ ⇓⟨ hyp₁ a b f[a]=b ⟩ ⌜ b ⌝ ≡⟨ cong proj₁ (lower ⌜b⌝≡q) ⟩⟶ q ■⟨ subst Value (cong proj₁ (lower ⌜b⌝≡q)) (rep-value b) ⟩ } } } from : Computable″ f → Computable f from ((p , cl) , hyp) = p , cl , (λ a b f[a]=b → apply p ⌜ a ⌝ ⇓⟨ _⇔_.from (hyp a ⌜ b ⌝) (post-apply f Closed-exp-set f[a]=b) ⟩■ ⌜ b ⌝) , λ a q p⌜a⌝⇓q → let cl-q : Closed q cl-q = closed⇓closed p⌜a⌝⇓q (Closed′-closed-under-apply (Closed→Closed′ cl) (Closed→Closed′ (rep-closed a))) in Σ-map id (Σ-map id (cong proj₁ P.∘ sym P.∘ lower)) (_⇔_.to (hyp a (q , cl-q)) p⌜a⌝⇓q) -- Yet another definition of computability. Computable‴ : ∀ {a b} {A : Type a} {B : Type b} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → A ⇀ B → Type (a ⊔ b) Computable‴ f = ∃ λ (p : Closed-exp) → ∀ a → ∃ λ b → apply (proj₁ p) ⌜ a ⌝ ⇓ ⌜ b ⌝ × f [ a ]= b -- If a partial function is computable by the last definition of -- computability above, then it is also computable by the first one. Computable‴→Computable : ∀ {a b} {A : Type a} {B : Type b} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → (f : A ⇀ B) → Computable‴ f → Computable f Computable‴→Computable f ((p , cl-p) , hyp) = p , cl-p , (λ a b f[a]=b → case hyp a of λ where (b′ , p⌜a⌝⇓⌜b′⌝ , f[a]=b′) → apply p ⌜ a ⌝ ⇓⟨ p⌜a⌝⇓⌜b′⌝ ⟩ ⌜ b′ ⌝ ≡⟨ by (_⇀_.deterministic f f[a]=b f[a]=b′) ⟩⟶ ⌜ b ⌝ ■⟨ rep-value b ⟩) , (λ a v p⌜a⌝⇓v → case hyp a of λ where (b , p⌜a⌝⇓⌜b⌝ , f[a]=b) → b , f[a]=b , ⇓-deterministic p⌜a⌝⇓v p⌜a⌝⇓⌜b⌝) module _ {a b c d} {A : Type a} {B : Type b} {C : Type c} {D : Type d} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ ⦃ rC : Rep C Consts ⦄ ⦃ rD : Rep D Consts ⦄ where -- Reductions. Reduction : A ⇀ B → C ⇀ D → Type (a ⊔ b ⊔ c ⊔ d) Reduction f g = Computable g → Computable f -- If f can be reduced to g, and f is not computable, then g is not -- computable. Reduction→¬Computable→¬Computable : (f : A ⇀ B) (g : C ⇀ D) → Reduction f g → ¬ Computable f → ¬ Computable g Reduction→¬Computable→¬Computable _ _ red ¬f g = ¬f (red g) -- Total partial functions to the booleans. Note that totality is -- defined using the double-negation modality. _→Bool : ∀ {ℓ} → Type ℓ → Type (lsuc ℓ) A →Bool = ∃ λ (f : A ⇀ Bool) → Total (λ A → ¬¬ A) f -- One way to view a predicate as a total partial function to the -- booleans. as-function-to-Bool₁ : ∀ {a} {A : Type a} → (A → Type a) → A →Bool as-function-to-Bool₁ P = (record { _[_]=_ = λ a b → (P a → b ≡ true) × (¬ P a → b ≡ false) ; deterministic = λ where {b₁ = true} {b₂ = true} _ _ → refl {b₁ = false} {b₂ = false} _ _ → refl {b₁ = true} {b₂ = false} f₁ f₂ → proj₂ f₁ (Bool.true≢false P.∘ sym P.∘ proj₁ f₂) {b₁ = false} {b₂ = true} f₁ f₂ → sym (proj₂ f₂ (Bool.true≢false P.∘ sym P.∘ proj₁ f₁)) ; propositional = ×-closure 1 (Π-closure ext 1 λ _ → Bool-set) (Π-closure ext 1 λ _ → Bool-set) }) , λ a → [ (λ p → true , (λ _ → refl) , ⊥-elim P.∘ (_$ p)) , (λ ¬p → false , ⊥-elim P.∘ ¬p , (λ _ → refl)) ] ⟨$⟩ excluded-middle -- Another way to view a predicate as a total partial function to the -- booleans. as-function-to-Bool₂ : ∀ {a} {A : Type a} → (P : A → Type a) → (∀ {a} → Is-proposition (P a)) → A →Bool as-function-to-Bool₂ P P-prop = (record { _[_]=_ = λ a b → P a × b ≡ true ⊎ ¬ P a × b ≡ false ; deterministic = λ where (inj₁ (_ , refl)) (inj₁ (_ , refl)) → refl (inj₁ (p , _)) (inj₂ (¬p , _)) → ⊥-elim (¬p p) (inj₂ (¬p , _)) (inj₁ (p , _)) → ⊥-elim (¬p p) (inj₂ (_ , refl)) (inj₂ (_ , refl)) → refl ; propositional = λ {_ b} → ⊎-closure-propositional (λ { (_ , b≡true) (_ , b≡false) → Bool.true≢false ( true ≡⟨ sym b≡true ⟩ b ≡⟨ b≡false ⟩∎ false ∎) }) (×-closure 1 P-prop Bool-set) (×-closure 1 (¬-propositional ext) Bool-set) }) , λ a → [ (λ p → true , inj₁ (p , refl)) , (λ ¬p → false , inj₂ (¬p , refl)) ] ⟨$⟩ excluded-middle -- If a is mapped to b by as-function-to-Bool₂ P P-prop, then a is -- also mapped to b by as-function-to-Bool₁ P. to-Bool₂→to-Bool₁ : ∀ {a} {A : Type a} ⦃ rA : Rep A Consts ⦄ (P : A → Type a) (P-prop : ∀ {a} → Is-proposition (P a)) {a b} → proj₁ (as-function-to-Bool₂ P P-prop) [ a ]= b → proj₁ (as-function-to-Bool₁ P) [ a ]= b to-Bool₂→to-Bool₁ _ _ = λ where (inj₁ (Pa , refl)) → (λ _ → refl) , ⊥-elim P.∘ (_$ Pa) (inj₂ (¬Pa , refl)) → ⊥-elim P.∘ ¬Pa , λ _ → refl -- If a is mapped to b by as-function-to-Bool₁ P, then a is not not -- mapped to b by as-function-to-Bool₂ P P-prop. to-Bool₁→to-Bool₂ : ∀ {a} {A : Type a} ⦃ rA : Rep A Consts ⦄ (P : A → Type a) (P-prop : ∀ {a} → Is-proposition (P a)) {a b} → proj₁ (as-function-to-Bool₁ P) [ a ]= b → ¬¬ proj₁ (as-function-to-Bool₂ P P-prop) [ a ]= b to-Bool₁→to-Bool₂ _ _ (Pa→b≡true , ¬Pa→b≡false) = ⊎-map (λ Pa → Pa , Pa→b≡true Pa) (λ ¬Pa → ¬Pa , ¬Pa→b≡false ¬Pa) ⟨$⟩ excluded-middle -- If as-function-to-Bool₁ P is ¬¬-computable, then -- as-function-to-Bool₂ P P-prop is also ¬¬-computable. to-Bool₁-computable→to-Bool₂-computable : ∀ {a} {A : Type a} ⦃ rA : Rep A Consts ⦄ (P : A → Type a) (P-prop : ∀ {a} → Is-proposition (P a)) → Computable′ (λ A → ¬¬ A) (proj₁ (as-function-to-Bool₁ P)) → Computable′ (λ A → ¬¬ A) (proj₁ (as-function-to-Bool₂ P P-prop)) to-Bool₁-computable→to-Bool₂-computable P P-prop (p , cl-p , hyp₁ , hyp₂) = p , cl-p , (λ a b → proj₁ (as-function-to-Bool₂ P P-prop) [ a ]= b ↝⟨ to-Bool₂→to-Bool₁ P P-prop ⟩ proj₁ (as-function-to-Bool₁ P) [ a ]= b ↝⟨ hyp₁ a b ⟩□ apply p ⌜ a ⌝ ⇓ ⌜ b ⌝ □) , λ a e → apply p ⌜ a ⌝ ⇓ e ↝⟨ hyp₂ a e ⟩ ¬¬ (∃ λ b → proj₁ (as-function-to-Bool₁ P) [ a ]= b × e ≡ ⌜ b ⌝) ↝⟨ _>>= (λ { (b , =b , ≡⌜b⌝) → to-Bool₁→to-Bool₂ P P-prop =b >>= λ =b → return (b , =b , ≡⌜b⌝) }) ⟩□ ¬¬ (∃ λ b → proj₁ (as-function-to-Bool₂ P P-prop) [ a ]= b × e ≡ ⌜ b ⌝) □ -- A lemma related to as-function-to-Bool₂. ×≡true⊎¬×≡false⇔⇔T : ∀ {a} {A : Type a} (P : A → Type a) → ∀ {a b} → P a × b ≡ true ⊎ ¬ P a × b ≡ false ⇔ (P a ⇔ T b) ×≡true⊎¬×≡false⇔⇔T P {a} {b} = record { to = λ where (inj₁ (p , refl)) → record { from = λ _ → p } (inj₂ (¬p , refl)) → record { to = ¬p; from = ⊥-elim } ; from = helper b } where helper : ∀ b → P a ⇔ T b → P a × b ≡ true ⊎ ¬ P a × b ≡ false helper true hyp = inj₁ (_⇔_.from hyp _ , refl) helper false hyp = inj₂ (_⇔_.to hyp , refl) -- One way to view a predicate as a partial function to the booleans. as-partial-function-to-Bool₁ : ∀ {a} {A : Type a} → (A → Type a) → A ⇀ Bool as-partial-function-to-Bool₁ P = record { _[_]=_ = λ a b → (P a → b ≡ true) × ¬ ¬ P a ; deterministic = λ where {b₁ = true} {b₂ = true} _ _ → refl {b₁ = false} {b₂ = false} _ _ → refl {b₁ = true} {b₂ = false} _ f → ⊥-elim $ proj₂ f (Bool.true≢false P.∘ sym P.∘ proj₁ f) {b₁ = false} {b₂ = true} f _ → ⊥-elim $ proj₂ f (Bool.true≢false P.∘ sym P.∘ proj₁ f) ; propositional = ×-closure 1 (Π-closure ext 1 λ _ → Bool-set) (¬-propositional ext) } -- Another way to view a predicate as a partial function to the -- booleans. as-partial-function-to-Bool₂ : ∀ {a} {A : Type a} → (P : A → Type a) → (∀ {a} → Is-proposition (P a)) → A ⇀ Bool as-partial-function-to-Bool₂ P P-prop = record { _[_]=_ = λ a b → P a × b ≡ true ; deterministic = λ { (_ , refl) (_ , refl) → refl } ; propositional = ×-closure 1 P-prop Bool-set } -- One definition of what it means for a total partial function to the -- booleans to be decidable. Decidable : ∀ {a} {A : Type a} ⦃ rA : Rep A Consts ⦄ → A →Bool → Type a Decidable = Computable P.∘ proj₁ -- Another definition of what it means for a total partial function to -- the booleans to be decidable. Decidable′ : ∀ {a} {A : Type a} ⦃ rA : Rep A Consts ⦄ → A →Bool → Type a Decidable′ = Computable‴ P.∘ proj₁ -- Computable functions from a type to a set. record Computable-function {a b} (A : Type a) (B : Type b) (B-set : Is-set B) ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ : Type (a ⊔ b) where field function : A → B computable : Computable (as-partial B-set function) open Computable-function -- An unfolding lemma for Computable-function. Computable-function↔ : ∀ {a b} {A : Type a} {B : Type b} {B-set : Is-set B} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → Computable-function A B B-set ↔ ∃ λ (f : A → B) → Computable (as-partial B-set f) Computable-function↔ = record { surjection = record { logical-equivalence = record { to = λ f → function f , computable f } ; right-inverse-of = λ _ → refl } ; left-inverse-of = λ _ → refl } -- If two computable functions have equal implementations, then they -- are equal. equal-implementations→equal : ∀ {a b} {A : Type a} {B : Type b} {B-set : Is-set B} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ (f g : Computable-function A B B-set) → proj₁ (computable f) ≡ proj₁ (computable g) → function f ≡ function g equal-implementations→equal f g hyp = ⟨ext⟩ λ x → $⟨ proj₁ (proj₂ (proj₂ (computable f))) x (function f x) (lift refl) , proj₁ (proj₂ (proj₂ (computable g))) x (function g x) (lift refl) ⟩ apply (proj₁ (computable f)) ⌜ x ⌝ ⇓ ⌜ function f x ⌝ × apply (proj₁ (computable g)) ⌜ x ⌝ ⇓ ⌜ function g x ⌝ ↝⟨ Σ-map id (subst (λ e → apply e _ ⇓ _) (sym hyp)) ⟩ apply (proj₁ (computable f)) ⌜ x ⌝ ⇓ ⌜ function f x ⌝ × apply (proj₁ (computable f)) ⌜ x ⌝ ⇓ ⌜ function g x ⌝ ↝⟨ uncurry ⇓-deterministic ⟩ ⌜ function f x ⌝ ≡ ⌜ function g x ⌝ ↝⟨ rep-injective ⟩□ function f x ≡ function g x □ instance -- Representation functions for computable functions. rep-Computable-function : ∀ {a b} {A : Type a} {B : Type b} {B-set : Is-set B} ⦃ rA : Rep A Consts ⦄ ⦃ rB : Rep B Consts ⦄ → Rep (Computable-function A B B-set) Consts rep-Computable-function {A = A} {B = B} {B-set = B-set} = record { ⌜_⌝ = ⌜_⌝ P.∘ proj₁ P.∘ computable ; rep-injective = injective } where abstract injective : Injective {A = Computable-function A B B-set} {B = Consts} (⌜_⌝ P.∘ proj₁ P.∘ computable) injective {f} {g} = ⌜ proj₁ (computable f) ⌝ ≡ ⌜ proj₁ (computable g) ⌝ ↝⟨ rep-injective ⟩ proj₁ (computable f) ≡ proj₁ (computable g) ↝⟨ (λ hyp → cong₂ _,_ (equal-implementations→equal f g hyp) hyp) ⟩ (function f , proj₁ (computable f)) ≡ (function g , proj₁ (computable g)) ↔⟨ ignore-propositional-component $ Implements-propositional (as-partial B-set (function g)) id ⟩ ((function f , proj₁ (computable f)) , proj₂ (computable f)) ≡ ((function g , proj₁ (computable g)) , proj₂ (computable g)) ↔⟨ Eq.≃-≡ (Eq.↔⇒≃ Σ-assoc) ⟩ (function f , computable f) ≡ (function g , computable g) ↔⟨ Eq.≃-≡ (Eq.↔⇒≃ Computable-function↔) ⟩□ f ≡ g □
# -*- coding: utf-8 -*- # Copyright 2020 TensorFlowTTS Team # # 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. """Train Hifigan.""" import tensorflow as tf physical_devices = tf.config.list_physical_devices("GPU") for i in range(len(physical_devices)): tf.config.experimental.set_memory_growth(physical_devices[i], True) import sys sys.path.append(".") import argparse import logging import os import numpy as np import soundfile as sf import yaml from tqdm import tqdm import tensorflow_tts from examples.melgan.audio_mel_dataset import AudioMelDataset from examples.melgan.train_melgan import collater from examples.melgan_stft.train_melgan_stft import MultiSTFTMelganTrainer from tensorflow_tts.configs import ( HifiGANDiscriminatorConfig, HifiGANGeneratorConfig, MelGANDiscriminatorConfig, ) from tensorflow_tts.models import ( TFHifiGANGenerator, TFHifiGANMultiPeriodDiscriminator, TFMelGANMultiScaleDiscriminator, ) from tensorflow_tts.utils import return_strategy class TFHifiGANDiscriminator(tf.keras.Model): def __init__(self, multiperiod_dis, multiscale_dis, **kwargs): super().__init__(**kwargs) self.multiperiod_dis = multiperiod_dis self.multiscale_dis = multiscale_dis def call(self, x): outs = [] period_outs = self.multiperiod_dis(x) scale_outs = self.multiscale_dis(x) outs.extend(period_outs) outs.extend(scale_outs) return outs def main(): """Run training process.""" parser = argparse.ArgumentParser( description="Train Hifigan (See detail in examples/hifigan/train_hifigan.py)" ) parser.add_argument( "--train-dir", default=None, type=str, help="directory including training data. ", ) parser.add_argument( "--dev-dir", default=None, type=str, help="directory including development data. ", ) parser.add_argument( "--use-norm", default=1, type=int, help="use norm mels for training or raw." ) parser.add_argument( "--outdir", type=str, required=True, help="directory to save checkpoints." ) parser.add_argument( "--config", type=str, required=True, help="yaml format configuration file." ) parser.add_argument( "--resume", default="", type=str, nargs="?", help='checkpoint file path to resume training. (default="")', ) parser.add_argument( "--verbose", type=int, default=1, help="logging level. higher is more logging. (default=1)", ) parser.add_argument( "--generator_mixed_precision", default=0, type=int, help="using mixed precision for generator or not.", ) parser.add_argument( "--discriminator_mixed_precision", default=0, type=int, help="using mixed precision for discriminator or not.", ) parser.add_argument( "--pretrained", default="", type=str, nargs="?", help="path of .h5 melgan generator to load weights from", ) args = parser.parse_args() # return strategy STRATEGY = return_strategy() # set mixed precision config if args.generator_mixed_precision == 1 or args.discriminator_mixed_precision == 1: tf.config.optimizer.set_experimental_options({"auto_mixed_precision": True}) args.generator_mixed_precision = bool(args.generator_mixed_precision) args.discriminator_mixed_precision = bool(args.discriminator_mixed_precision) args.use_norm = bool(args.use_norm) # set logger if args.verbose > 1: logging.basicConfig( level=logging.DEBUG, stream=sys.stdout, format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s", ) elif args.verbose > 0: logging.basicConfig( level=logging.INFO, stream=sys.stdout, format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s", ) else: logging.basicConfig( level=logging.WARN, stream=sys.stdout, format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s", ) logging.warning("Skip DEBUG/INFO messages") # check directory existence if not os.path.exists(args.outdir): os.makedirs(args.outdir) # check arguments if args.train_dir is None: raise ValueError("Please specify --train-dir") if args.dev_dir is None: raise ValueError("Please specify either --valid-dir") # load and save config with open(args.config) as f: config = yaml.load(f, Loader=yaml.Loader) config.update(vars(args)) config["version"] = tensorflow_tts.__version__ with open(os.path.join(args.outdir, "config.yml"), "w") as f: yaml.dump(config, f, Dumper=yaml.Dumper) for key, value in config.items(): logging.info(f"{key} = {value}") # get dataset if config["remove_short_samples"]: mel_length_threshold = config["batch_max_steps"] // config[ "hop_size" ] + 2 * config["hifigan_generator_params"].get("aux_context_window", 0) else: mel_length_threshold = None if config["format"] == "npy": audio_query = "*-wave.npy" mel_query = "*-raw-feats.npy" if args.use_norm is False else "*-norm-feats.npy" audio_load_fn = np.load mel_load_fn = np.load else: raise ValueError("Only npy are supported.") # define train/valid dataset train_dataset = AudioMelDataset( root_dir=args.train_dir, audio_query=audio_query, mel_query=mel_query, audio_load_fn=audio_load_fn, mel_load_fn=mel_load_fn, mel_length_threshold=mel_length_threshold, ).create( is_shuffle=config["is_shuffle"], map_fn=lambda items: collater( items, batch_max_steps=tf.constant(config["batch_max_steps"], dtype=tf.int32), hop_size=tf.constant(config["hop_size"], dtype=tf.int32), ), allow_cache=config["allow_cache"], batch_size=config["batch_size"] * STRATEGY.num_replicas_in_sync * config["gradient_accumulation_steps"], ) valid_dataset = AudioMelDataset( root_dir=args.dev_dir, audio_query=audio_query, mel_query=mel_query, audio_load_fn=audio_load_fn, mel_load_fn=mel_load_fn, mel_length_threshold=mel_length_threshold, ).create( is_shuffle=config["is_shuffle"], map_fn=lambda items: collater( items, batch_max_steps=tf.constant( config["batch_max_steps_valid"], dtype=tf.int32 ), hop_size=tf.constant(config["hop_size"], dtype=tf.int32), ), allow_cache=config["allow_cache"], batch_size=config["batch_size"] * STRATEGY.num_replicas_in_sync, ) # define trainer trainer = MultiSTFTMelganTrainer( steps=0, epochs=0, config=config, strategy=STRATEGY, is_generator_mixed_precision=args.generator_mixed_precision, is_discriminator_mixed_precision=args.discriminator_mixed_precision, ) with STRATEGY.scope(): # define generator and discriminator generator = TFHifiGANGenerator( HifiGANGeneratorConfig(**config["hifigan_generator_params"]), name="hifigan_generator", ) multiperiod_discriminator = TFHifiGANMultiPeriodDiscriminator( HifiGANDiscriminatorConfig(**config["hifigan_discriminator_params"]), name="hifigan_multiperiod_discriminator", ) multiscale_discriminator = TFMelGANMultiScaleDiscriminator( MelGANDiscriminatorConfig( **config["melgan_discriminator_params"], name="melgan_multiscale_discriminator", ) ) discriminator = TFHifiGANDiscriminator( multiperiod_discriminator, multiscale_discriminator, name="hifigan_discriminator", ) # dummy input to build model. fake_mels = tf.random.uniform(shape=[1, 100, 80], dtype=tf.float32) y_hat = generator(fake_mels) discriminator(y_hat) if len(args.pretrained) > 1: generator.load_weights(args.pretrained) logging.info( f"Successfully loaded pretrained weight from {args.pretrained}." ) generator.summary() discriminator.summary() # define optimizer generator_lr_fn = getattr( tf.keras.optimizers.schedules, config["generator_optimizer_params"]["lr_fn"] )(**config["generator_optimizer_params"]["lr_params"]) discriminator_lr_fn = getattr( tf.keras.optimizers.schedules, config["discriminator_optimizer_params"]["lr_fn"], )(**config["discriminator_optimizer_params"]["lr_params"]) gen_optimizer = tf.keras.optimizers.Adam( learning_rate=generator_lr_fn, amsgrad=config["generator_optimizer_params"]["amsgrad"], ) dis_optimizer = tf.keras.optimizers.Adam( learning_rate=discriminator_lr_fn, amsgrad=config["discriminator_optimizer_params"]["amsgrad"], ) trainer.compile( gen_model=generator, dis_model=discriminator, gen_optimizer=gen_optimizer, dis_optimizer=dis_optimizer, ) # start training try: trainer.fit( train_dataset, valid_dataset, saved_path=os.path.join(config["outdir"], "checkpoints/"), resume=args.resume, ) except KeyboardInterrupt: trainer.save_checkpoint() logging.info(f"Successfully saved checkpoint @ {trainer.steps}steps.") if __name__ == "__main__": main()
// // request_handler.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_handler.h" #include <fstream> #include <sstream> #include <string> #include <boost/lexical_cast.hpp> #include "mime_types.h" #include "reply.h" #include "request.h" #include "wallet.h" #include "networktime.h" namespace http { namespace server3 { request_handler::request_handler(const std::string& doc_root) : doc_root_(doc_root) { } void request_handler::handle_request(const request& req, reply& rep) { // Decode url to path. std::string request_path; if (!url_decode(req.uri, request_path)) { rep = reply::stock_reply(reply::bad_request); return; } /* // Request path must be absolute and not contain "..". if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos) { rep = reply::stock_reply(reply::bad_request); return; } // If path ends in slash (i.e. is a directory) then add "index.html". if (request_path[request_path.size() - 1] == '/') { request_path += "index.html"; } // Determine the file extension. std::size_t last_slash_pos = request_path.find_last_of("/"); std::size_t last_dot_pos = request_path.find_last_of("."); std::string extension; if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) { extension = request_path.substr(last_dot_pos + 1); } // Open the file to send back. std::string full_path = doc_root_ + request_path; std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); if (!is) { rep = reply::stock_reply(reply::not_found); return; } // Fill out the reply to be sent to the client. rep.status = reply::ok; char buf[512]; while (is.read(buf, sizeof(buf)).gcount() > 0) rep.content.append(buf, is.gcount()); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); */ std::string line = "<br>"; std::string extension = "html"; // "txt"; std::stringstream ss; std::string responseContent = ""; ss << "Safire Client v0.0.1. " << line; ss << line; CWallet wallet; std::string privateKey; std::string publicKey; bool e = wallet.fileExists("wallet.dat"); if(e != 0){ wallet.read(privateKey, publicKey); ss << "Public Key: " << publicKey << line; } ss << "Balance " << 0 << line; ss << "My Transactions " << 0 << line; ss << line; ss << "Network Users " << 0 << line; ss << "Pending Users " << 0 << line; CNetworkTime netTime; ss << "Time " << netTime.getEpoch() << line; // Get Block time ss << "Block Time " << 0 << line; ss << "Block Creator Key " << "" << line; ss << line; // Blocks ss << "Blocks Stored " << 0 << line; ss << "Network Transactions " << 0 << line; ss << "Pending Transactions " << 0 << line; // Availability // network reward // currency outstanding. ss << "Request " << request_path << line; responseContent = ss.str(); rep.status = reply::ok; rep.content.append(responseContent.c_str(), responseContent.length()); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); } bool request_handler::url_decode(const std::string& in, std::string& out) { out.clear(); out.reserve(in.size()); for (std::size_t i = 0; i < in.size(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { int value; std::istringstream is(in.substr(i + 1, 2)); if (is >> std::hex >> value) { out += static_cast<char>(value); i += 2; } else { return false; } } else { return false; } } else if (in[i] == '+') { out += ' '; } else { out += in[i]; } } return true; } } // namespace server3 } // namespace http
# Autodiff: Calculus from another angle We know differentiation Then, how to differentiate using computer? ## 1. Numerical differentiation Finite Difference (FVM, FEM..) i.e. \begin{equation} f(x) = x^2 + 2x - 1 \end{equation} Then $\dfrac{df}{dx}$? we know the analytic solution is \begin{equation} f'(x) = 2x + 2 \end{equation} ```julia using Plots gr() #plotly() n = 100 @. f(x) = x^2 + 2x - 1 @. fp(x) = 2x + 2 x = range(-5, 5, length=n+1) u = f(x) up = fp(x[2:n]) dudx = [(u[i + 1] - u[i - 1]) / (2*(x[2] - x[1])) for i=2:n] plot(x[2:n], dudx, linewidth=8, alpha=0.5, label="FDM") plot!(x[2:n], up, linewidth=2, alpha=1, label="Analytic") ``` * Pros : Simple implmenetation * Cons : Not accurate if high order or few grid points ## 2. Symbolic Differentiation Mathematica way ```julia #import Pkg; Pkg.add("SymPy") using SymPy ``` ```julia @vars x diff(cos(x), x) ``` ```julia diff( x^2 + 2x - 1, x) ``` * Pros : Accurate * Cons : Very slow or even not applicable to complex function ## 3. Auto differentiation Let's start with $\sqrt{x}$ ## Babylonian sqrt 1. Make an initial guess. $x_0$ 2. Improve the guess. $x1 = (x0 + S / x0) / 2$ 3. Iterate until convergence. $x_{n+1} = (x_n + S / x_n) /2 $ More algorithmic way > Repeat $ t \leftarrow (t+x/t) / 2 $ until $t$ converges to $\sqrt{x}$. Next Each iteration has one add and two divides. For illustration purposes, 10 iterations suffice. ```julia function Babylonian(x; N = 10) t = (1+x)/2 for i = 2:N; t=(t + x/t)/2 end t end ``` Babylonian (generic function with 1 method) Check that it works: ```julia α = π Babylonian(α), √α ``` (1.7724538509055159, 1.7724538509055159) ```julia x=2; Babylonian(x),√x # Type \sqrt+<tab> to get the symbol ``` (1.414213562373095, 1.4142135623730951) ```julia using Plots gr() ``` Plots.GRBackend() ```julia ## Warning first plots load packages, takes time i = 0:.01:49 plot([x->Babylonian(x,N=i) for i=1:5],i,label=["Iteration $j" for i=1:1,j=1:5]) plot!(sqrt,i,c="black",label="sqrt", title = "Those Babylonians really knew how to √") ``` ## ...and now the derivative, almost by magic we have a derivatve of `sqrt(x)` \begin{equation} (\sqrt{x})' = (x^{\frac{1}{2}})' = \dfrac{1}{2 \sqrt{x}} \end{equation} Introduce Dual number, invented by the famous algebraist Clifford in 1873, as `D`. ```julia struct D <: Number # D is a function-derivative pair # D = (Number (func), Number (derivative)) f::Tuple{Float64,Float64} end ``` * Sum Rule \begin{equation} (x+y)' = x' + y' \end{equation} * Quotient Rule \begin{equation} (x/y)' = (yx'-xy') / y^2 \end{equation} ```julia import Base: +, /, convert, promote_rule +(x::D, y::D) = D(x.f .+ y.f) /(x::D, y::D) = D((x.f[1]/y.f[1], (y.f[1]*x.f[2] - x.f[1]*y.f[2])/y.f[1]^2)) convert(::Type{D}, x::Real) = D((x,zero(x))) promote_rule(::Type{D}, ::Type{<:Number}) = D ``` promote_rule (generic function with 160 methods) The same algorithm with no rewrite at all computes properly the derivative as the check shows. ```julia x=49; Babylonian(D((x,1))), (√x,.5/√x) ``` (D((7.0, 0.07142857142857142)), (7.0, 0.07142857142857142)) ```julia x=π; Babylonian(D((x,1))), (√x,.5/√x) ``` (D((1.7724538509055159, 0.28209479177387814)), (1.7724538509055159, 0.28209479177387814)) ## It just works! ## Symbolically We haven't yet explained how it works, but it may be of some value to understand that the below is mathematically equivalent, though not what the computation is doing. Notice in the below that Babylonian works on SymPy symbols. Note: Python and Julia are good friends. It's not a competition! Watch how nicely we can use the same code now with SymPy. ```julia #Pkg.add("SymPy") using SymPy ``` ```julia x = symbols("x") display("Iterations as a function of x") for k = 1:5 display( simplify(Babylonian(x,N=k))) end display("Derivatives as a function of x") for k = 1:5 display(simplify(diff(simplify(Babylonian(x,N=k)),x))) end ``` ## How autodiff is getting the answer 1. Create a basic rule (known rule) for Dual (Function & Derivate) 2. Let code works Let us by hand take the "derivative" of the Babylonian iteration wi th respect to x. Specifically t′=dt/dx. This is the old fashioned way of a human rewriting code. ```julia function dBabylonian(x; N = 10) t = (1+x)/2 t′ = 1/2 for i = 1:N; t = (t+x/t)/2; t′= (t′+(t-x*t′)/t^2)/2; end t′ end ``` dBabylonian (generic function with 1 method) See this rewritten code gets the right answer. So the trick is for the computer system to do it for you, and without any loss of speed or convenience. ```julia x = π; dBabylonian(x), .5/√x ``` (0.2820947917738782, 0.28209479177387814) What just happened? Answer: We created an iteration by hand for t′ given our iteration for t. Then we ran the iteration alongside the iteration for t. ```julia Babylonian(D((x,1))) ``` D((1.7724538509055159, 0.28209479177387814)) How did this work? It created the same derivative iteration that we did by hand, using very general rules that are set once and need not be written by hand. ## Dual Number Notation Instead of D(a,b) we can write a + b ϵ, where ϵ satisfies ϵ^2=0. The four rules are $ (a+b\epsilon) \pm (c+d\epsilon) = (a+c) \pm (b+d)\epsilon$ $ (a+b\epsilon) * (c+d\epsilon) = (ac) + (bc+ad)\epsilon$ $ (a+b\epsilon) / (c+d\epsilon) = (a/c) + (bc-ad)/d^2 \epsilon $ ```julia Base.show(io::IO,x::D) = print(io,x.f[1]," + ",x.f[2]," ϵ") ``` ```julia # Add the last two rules import Base: -,* -(x::D, y::D) = D(x.f .- y.f) *(x::D, y::D) = D((x.f[1]*y.f[1], (x.f[2]*y.f[1] + x.f[1]*y.f[2]))) ``` * (generic function with 394 methods) ```julia D((1,0)) ``` 1.0 + 0.0 ϵ ```julia D((0,1))^2 ``` 0.0 + 0.0 ϵ ```julia D((2,1)) ^2 ``` 4.0 + 4.0 ϵ ```julia ϵ * ϵ ``` 0.0 + 0.0 ϵ ```julia ϵ^2 ``` 0.0 + 0.0 ϵ ```julia 1/(1+ϵ) # Exact power series: 1-ϵ+ϵ²-ϵ³-... ``` 1.0 + -1.0 ϵ ```julia (1+ϵ)^5 ## Note this just works (we didn't train powers)!! ``` 1.0 + 5.0 ϵ ## Generalization to arbitrary roots ```julia function nthroot(x, n=2; t=1, N = 10) for i = 1:N; t += (x/t^(n-1)-t)/n; end t end ``` nthroot (generic function with 2 methods) ```julia nthroot(2,3), ∛2 # take a cube root ``` (1.2599210498948732, 1.2599210498948732) ```julia nthroot(2+ϵ,3) ``` 1.2599210498948732 + 0.20998684164914552 ϵ ```julia nthroot(7,12), 7^(1/12) ``` (1.1760474285795146, 1.1760474285795146) ```julia x = 2.0 nthroot( x+ϵ,3), ∛x, 1/x^(2/3)/3 ``` (1.2599210498948732 + 0.20998684164914552 ϵ, 1.2599210498948732, 0.20998684164914552) ## Forward Diff Now that you understand it, you can use the official package ```julia using ForwardDiff ``` ```julia ForwardDiff.derivative(sqrt, 2) ``` 0.35355339059327373 ```julia ForwardDiff.derivative(Babylonian, 2) ``` 0.35355339059327373 # How Frameworks compute this Let function $f$ as \begin{equation} f(x_1, x_2) = \cos{(x_1)} + x_1 \exp{(x_2)} \end{equation} ## Derivative Expression of $f$ \begin{align} w_1 &= x_1 \\ w_2 &= x_2 \\ w_3 &= \exp{(w_2)} \\ w_4 &= w_1 w_3 \\ w_5 &= \cos{(w_1)} \\ w_6 &= w_4 + w_5 \\ f(x_1, x_2) &= w_6 \end{align} ## Computation Graph for function \begin{align} w_1' &= \textrm{seed} \in {0, 1} \\ w_2' &= \textrm{seed} \in {0, 1} \\ w_3' &= \exp{(w_2)} w_2' \\ w_4' &= w_1' w_3 + w_1 w_3' \\ w_5' &= -\sin{(w_1)} w_1' \\ w_6' &= w_4' + w_5' \\ f'(x_1, x_2) &= w_6' \end{align} ## Computational Graph for derivatives ## LLVM Ecosystem ## Tensorflow Compiler Ecosystem # Conclusion 1. There is some different method to implement computational derivatives 2. Autodifferentiation is not only for machine learning, it could be used various way such as optimal control. 3. Knowing lower level is not manadatory, but this helps to understand whole architecture and create better code 4. Switching langauge is doesn't matter, but only applied for modern language. ## Reference * https://github.com/JuliaComputing/JuliaBoxTutorials/blob/master/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/20.%20Automatic%20Differentiation%20in%2010%20Minutes.ipynb * https://www.cs.usask.ca/~spiteri/CMPT898/notes/ad.pdf * https://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/slides/lec10.pdf
\documentclass{memoir} \usepackage{notestemplate} %\logo{~/School-Work/Auxiliary-Files/resources/png/logo.png} %\institute{Rice University} %\faculty{Faculty of Whatever Sciences} %\department{Department of Mathematics} %\title{Class Notes} %\subtitle{Based on MATH xxx} %\author{\textit{Author}\\Gabriel \textsc{Gress}} %\supervisor{Linus \textsc{Torvalds}} %\context{Well, I was bored...} %\date{\today} %\makeindex \begin{document} % \maketitle % Notes taken on \subsection{Riemann Sphere} \label{sub:riemann_sphere} %% ADD RIEMANN SPHERE Under construction \subsection{Linear Transformations} \label{sub:linear_transformations} \begin{defn}[Linear Fractional Transformation] A \textbf{linear fractional transformation} or \textbf{Möbius transformation} is a linear transformation of the complex plane given by \begin{align*} S(z) := \frac{az+b}{cz+d} \end{align*} for complex numbers \(a,b,c,d \in \C\) with one of \(c,d\) non-zero.\\ We extend \(S\) to \(\overline{\C}\) by defining the following values: \begin{align*} S(\infty) = \begin{cases} \sfrac{a}{c} & c\neq 0\\ \infty & c=0 \end{cases}\\ S(-\sfrac{d}{c}) = \infty \text{ if }c\neq 0. \end{align*} This extends the mapping so that \(S\) is a topological mapping of the extended plane onto itself, with the topology of distances on the Riemannian sphere. \end{defn} This is the generalized form of all linear transformations on \(\overline{\C}\)-- translations, reflections, rotations, and more can be represented as linear fractional transformations. \begin{anki} TARGET DECK Complex Qual::Complex Analysis START MathJaxCloze Text: A **linear fractional transformation** or **Möbius transformation** is a linear transformation of the complex plane given by {{c1::\(\begin{align*} S(z) := \frac{az+b}{cz+d} \end{align*}\)}} for complex numbers \(a,b,c,d \in \C\) with one of \(c,d\) non-zero. If we write \(z = \frac{z_1}{z_2}\), we can express \(S(z)\) as a matrix via {{c1::\(\begin{align*} \begin{pmatrix} a & b \\ c & d \end{pmatrix} \begin{pmatrix} z_1 \\ z_2 \end{pmatrix} = \begin{pmatrix} w_1 \\ w_2 \end{pmatrix} \end{align*}\)}} where \(w := \frac{w_1}{w_2} = S(z)\). If {{c1::\(ad-bc = 1\)}}, we say the linear fractional transformation is **normalized**. Extra: We extend \(S\) to \(\overline{\C}\) by defining the following values: \(\begin{align*} S(\infty) = \begin{cases} \sfrac{a}{c} & c\neq 0\\ \infty & c=0 \end{cases}\\ S(-\sfrac{d}{c}) = \infty \text{ if }c\neq 0. \end{align*}\) This extends the mapping so that \(S\) is a topological mapping of the extended plane onto itself, with the topology of distances on the Riemannian sphere. Tags: analysis complex_analysis complex_geometry defn <!--ID: 1624827134946--> END \end{anki} \begin{prop} Let \(S\) be a linear fractional transformation \begin{align*} S(z) = \frac{az+b}{c z + d} \end{align*} with \(ad-bc\neq 0\). Then \begin{align*} S:\overline{\C}\to \overline{\C} \end{align*} is an isomorphism. Furthermore, the inverse of \(S\) is given by \begin{align*} S^{-1}(z) = \frac{dz -b}{a-cz}. \end{align*} If \(ad-bc = 1\), then we say the linear fractional transformation is \textbf{normalized}. \end{prop} Every linear fractional transformation admits a normalized form. In fact, there are exactly two, which are obtained from each other by changing the sign of the coefficients. \begin{anki} START MathJaxCloze Text: Let \(S\) be a linear fractional transformation \(\begin{align*} S(z) = \frac{az+b}{c z + d} \end{align*}\) with \(ad-bc\neq 0\). Then {{c1::\(\begin{align*} S:\overline{\C}\to \overline{\C} \end{align*}\)}} is {{c1::an isomorphism}}. Furthermore, the inverse of \(S\) is given by {{c1::\(\begin{align*} S^{-1}(z) = \frac{dz -b}{a-cz}. \end{align*}\)}} If {{c1::\(ad-bc = 1\)}}, then we say the linear fractional transformation is \textbf{normalized}. Extra: Every linear fractional transformation admits a normalized form. In fact, there are exactly two, which are obtained from each other by changing the sign of the coefficients. Tags: analysis complex_analysis complex_geometry <!--ID: 1626152754001--> END \end{anki} \begin{general}[Matrix Formulation of Linear Fractional Transformations] Let \(z = \frac{z_1}{z_2}\) be an arbitrary complex number and \begin{align*} S(z) = \frac{az+b}{cz+d}. \end{align*} Then we can express this linear fractional translation by \begin{align*} \begin{pmatrix} a & b \\ c & d \end{pmatrix} \begin{pmatrix} z_1 \\ z_2 \end{pmatrix} = \begin{pmatrix} w_1 \\ w_2 \end{pmatrix} \end{align*} where \(w := \frac{w_1}{w_2} = S(z)\). This representation as matrices is useful as it satisfies the standard matrix operations when it comes to addition, composition, inversion, and so on.\\ Hence, the set of linear fractional transformations forms a (matrix) group. The identity transformation is given by the identity matrix. The rest of the group properties we leave to be checked by the reader.\\ In fact, if we restrict ourselves to normalized representations, this matrix group is isomorphic to \(SL(2,\C)\). If furthermore we form an equivalence class on normalized representations, then the group is isomorphic to the \textbf{projective special linear group} \(PSL_2(\C)\). \end{general} If \begin{align*} A = \begin{pmatrix} a & b \\ c & d \end{pmatrix} \end{align*} then we may denote the linear fractional transformation \begin{align*} S(z) = \frac{az+b}{cz+d} \end{align*} simply by \(S_A\). \begin{prop}[Equivalence of Fractional Linear Transformations] Let \(A,A' \in \C^{2\times 2}\) with \(\textrm{det}(A)\neq 0\) and \(\textrm{det}(A') \neq 0\). Then \begin{align*} S_A = S_{A'} \iff A' = \lambda A \end{align*} for some \(\lambda \in \C\) non-zero. \end{prop} \begin{anki} START MathJaxCloze Text: **Equivalence of Fractional Linear Transformations** Let \(A,A' \in \mathbb{C}^{2\times 2}\) with \(\textrm{det}(A)\neq 0\) and \(\textrm{det}(A') \neq 0\). Then {{c1::\(\begin{align*} S_A = S_{A'} \iff A' = \lambda A \end{align*} \)}} for some \(\lambda \in \C\) non-zero. Tags: analysis complex_analysis complex_geometry <!--ID: 1626152754018--> END \end{anki} \begin{defn}[Important Classes of Linear Transformations] The linear fractional transformations of the form \begin{align*} T_\alpha (z) := \begin{pmatrix} 1 & \alpha \\ 0 & 1 \end{pmatrix} \end{align*} for \(\alpha \in \C\) are called \textbf{parallel translations}, as they correspond to the transformation \(S(z) = z + \alpha \).\\ The linear fractional transformations of the form \begin{align*} R_\alpha (z) := \begin{pmatrix} \alpha & 0 \\ 0 & 1 \end{pmatrix} \end{align*} are referred to as \textbf{rotations} if \(\left| \alpha \right| = 1\), or a \textbf{homothetic transformation} if \(\alpha \) is real with \(\alpha >0\). For arbitrary complex \(\alpha \neq 0\), we can write \begin{align*} \alpha = \left| \alpha \right| \frac{\alpha }{\left| \alpha \right| } \end{align*} and hence the general form can be viewed as a composition of a homothetic transformation with a rotation.\\ The linear fractional transformation \begin{align*} (z)^{-1} := \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \end{align*} is referred to as an \textbf{inversion}, as it represents \(S(z) = \frac{1}{z}\). \end{defn} In some sense, we can view these classes of translations as the fundamental linear transformations. If \(S(z)\) is given by \begin{align*} \frac{az+b}{cz+d} \end{align*} with \(c\neq 0\), then we can write \begin{align*} S(z) &= \frac{az+b}{c z+d} = \frac{bc-ad}{c^2(z+\frac{d}{c})}+ \frac{a}{c}\\ &= T_{\sfrac{a}{c}}\circ R_{\frac{bc-ad}{c^2}}\circ (\cdot)^{-1} \circ T_{\sfrac{d}{c}} \end{align*} In the simpler case where \(c=0\), we have \begin{align*} S(z) &= \frac{az+b}{d}\\ &= T_{\sfrac{b}{d}}\circ R_{\sfrac{a}{d}} \end{align*} \begin{anki} START MathJaxCloze Text: The linear fractional transformations of the form {{c1::\(\begin{align*} T_\alpha (z) := \begin{pmatrix} 1 & \alpha \\ 0 & 1 \end{pmatrix} \end{align*}\)}} for \(\alpha \in \C\) are called **parallel translations**, as they correspond to the transformation {{c1::\(S(z) = z + \alpha \)}}. The linear fractional transformations of the form {{c2::\(\begin{align*} R_\alpha (z) := \begin{pmatrix} \alpha & 0 \\ 0 & 1 \end{pmatrix} \end{align*}\)}} are referred to as **rotations** if {{c2::\(\left| \alpha \right| = 1\)}}, or a **homothetic transformation** if {{c2::\(\alpha \) is real with \(\alpha >0\)}}. For arbitrary complex \(\alpha \neq 0\), we can write {{c2::\(\begin{align*} \alpha = \left| \alpha \right| \frac{\alpha }{\left| \alpha \right| } \end{align*}\)}} and hence the general form can be viewed as {{c2::a composition of a homothetic transformation with a rotation}}. The linear fractional transformation {{c3::\(\begin{align*} (z)^{-1} := \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \end{align*}\)}} is referred to as an **inversion**, as it represents {{c3::\(S(z) = \frac{1}{z}\)}} . Extra: If \(S(z)\) is given by \(\begin{align*} \frac{az+b}{cz+d} \end{align*}\) with \(c\neq 0\), then we can write \(\begin{align*} S(z) &= \frac{az+b}{c z+d} = \frac{bc-ad}{c^2(z+\frac{d}{c})}+ \frac{a}{c}\\ &= T_{\sfrac{a}{c}}\circ R_{\frac{bc-ad}{c^2}}\circ (\cdot)^{-1} \circ T_{\sfrac{d}{c}} \end{align*}\) In the simpler case where \(c=0\), we have \(\begin{align*} S(z) &= \frac{az+b}{d}\\ &= T_{\sfrac{b}{d}}\circ R_{\sfrac{a}{d}} \end{align*}\) Tags: analysis complex_analysis complex_geometry defn <!--ID: 1624827135038--> END \end{anki} \begin{thm} A fractional linear transformation maps straight lines and circles onto straight lines and circles. \end{thm} \begin{proof} \end{proof} \begin{anki} START MathJaxCloze Text: A fractional linear transformation \(S(z) = \frac{az+b}{c z + d}\), \(ac-bd\neq 0\) maps straight lines and circles onto {{c1::straight lines and circles}}. Tags: analysis complex_analysis complex_geometry <!--ID: 1626152754035--> END \end{anki} \begin{lemma} Let \(S\) be a fractional linear map. If \(S(\infty) = \infty\), then \begin{align*} S(z) = az+b \end{align*} for \(a,b \in \C\). \end{lemma} \begin{anki} START MathJaxCloze Text: Let \(S\) be a fractional linear map. If \(S(\infty) = \infty\), then {{c1::\(\begin{align*} S(z) = az+b \end{align*}\) for \(a,b \in \C\)}}. Tags: analysis complex_analysis complex_geometry <!--ID: 1626152754052--> END \end{anki} \begin{thm} Given any three distinct points \(\left\{ z_1,z_2,z_3 \right\} \) with \(z_i \in \overline{\C}\) and three distinct points \(\left\{ w_1,w_2,w_3 \right\} \) with \(w_i \in \overline{\C}\), there exists a unique fractional linear map \(S\) with \begin{align*} S(z_i) = w_i. \end{align*} If \(\left\{ w_1,w_2,w_3 \right\} = \left\{ 0,\infty,1 \right\} \) then the map is given by \begin{align*} S(z) = \frac{z-z_1}{z-z_2}\cdot \frac{z_3-z_2}{z_3-z_1}. \end{align*} We can apply this to the general case to get the relation \begin{align*} \frac{w-w_1}{w-w_2}\cdot \frac{w_3-w_2}{w_3-w_1} = \frac{z-z_1}{z-z_2}\cdot \frac{z_3-z_2}{z_3-z_1}. \end{align*} We can use this relation to derive an explicit formula for specific values. \end{thm} \begin{lemma} If \(S\) is a fractional linear map with three fixed points, then \(S\) is the identity map. \end{lemma} \begin{proof} \end{proof} \begin{anki} START MathJaxCloze Text: Given any three distinct points \(\left\{ z_1,z_2,z_3 \right\} \) with \(z_i \in \overline{\C}\) and three distinct points \(\left\{ w_1,w_2,w_3 \right\} \) with \(w_i \in \overline{\C}\), there exists a {{c1::unique fractional linear map \(S\)::map}} with {{c1::\(\begin{align*} S(z_i) = w_i. \end{align*}\)}} If \(\left\{ w_1,w_2,w_3 \right\} = \left\{ 0,\infty,1 \right\} \) then the map is given by {{c1::\(\begin{align*} S(z) = \frac{z-z_1}{z-z_2}\cdot \frac{z_3-z_2}{z_3-z_1}. \end{align*}\)}} We can apply this to the general case to get the relation {{c1::\(\begin{align*} \frac{w-w_1}{w-w_2}\cdot \frac{w_3-w_2}{w_3-w_1} = \frac{z-z_1}{z-z_2}\cdot \frac{z_3-z_2}{z_3-z_1}. \end{align*}\)}} We can use this relation to derive an explicit formula for specific values. Extra: If \(S\) is a fractional linear map with three fixed points, then \(S\) is the identity map. Tags: analysis complex_analysis complex_geometry <!--ID: 1626152754068--> END \end{anki} %% Lots more details can be filled here, TBD based on later content % \printindex \end{document}
Where beauty cannot keep her lustrous eyes ,
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9. Copyright (c) 2020, 2021, Oracle and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl -} open import LibraBFT.Prelude open import LibraBFT.ImplShared.Consensus.Types open import LibraBFT.ImplShared.Interface.Output -- This module defines the LBFT monad used by our (fake/simple, -- for now) "implementation", along with some utility functions -- to facilitate reasoning about it. module LibraBFT.ImplShared.Util.Util where open import Optics.All open import LibraBFT.ImplShared.Util.Dijkstra.Syntax public open import LibraBFT.ImplShared.Util.Dijkstra.RWS public open import LibraBFT.ImplShared.Util.Dijkstra.RWS.Syntax public open import LibraBFT.ImplShared.Util.Dijkstra.EitherD public open import LibraBFT.ImplShared.Util.Dijkstra.EitherD.Syntax public ---------------- -- LBFT Monad -- ---------------- -- Global 'LBFT'; works over the whole state. LBFT : Set → Set₁ LBFT = RWS Unit Output RoundManager LBFT-run : ∀ {A} → LBFT A → RoundManager → (A × RoundManager × List Output) LBFT-run m = RWS-run m unit LBFT-result : ∀ {A} → LBFT A → RoundManager → A LBFT-result m rm = proj₁ (LBFT-run m rm) LBFT-post : ∀ {A} → LBFT A → RoundManager → RoundManager LBFT-post m rm = proj₁ (proj₂ (LBFT-run m rm)) LBFT-outs : ∀ {A} → LBFT A → RoundManager → List Output LBFT-outs m rm = proj₂ (proj₂ (LBFT-run m rm)) LBFT-Pre = RoundManager → Set LBFT-Post = RWS-Post Output RoundManager LBFT-Post-True : ∀ {A} → LBFT-Post A → LBFT A → RoundManager → Set LBFT-Post-True Post m pre = let (x , post , outs) = LBFT-run m pre in Post x post outs LBFT-weakestPre : ∀ {A} (m : LBFT A) → LBFT-Post A → LBFT-Pre LBFT-weakestPre m Post pre = RWS-weakestPre m Post unit pre LBFT-Contract : ∀ {A} (m : LBFT A) → Set₁ LBFT-Contract{A} m = (Post : RWS-Post Output RoundManager A) → (pre : RoundManager) → LBFT-weakestPre m Post pre → LBFT-Post-True Post m pre LBFT-contract : ∀ {A} (m : LBFT A) → LBFT-Contract m LBFT-contract m Post pre pf = RWS-contract m Post unit pre pf LBFT-⇒ : ∀ {A} (P Q : LBFT-Post A) → (RWS-Post-⇒ P Q) → ∀ m pre → LBFT-weakestPre m P pre → LBFT-weakestPre m Q pre LBFT-⇒ Post₁ Post₂ f m pre pf = RWS-⇒ Post₁ Post₂ f m unit pre pf LBFT-⇒-bind : ∀ {A B} (P : LBFT-Post A) (Q : LBFT-Post B) (f : A → LBFT B) → (RWS-Post-⇒ P (RWS-weakestPre-bindPost unit f Q)) → ∀ m st → LBFT-weakestPre m P st → LBFT-weakestPre (m >>= f) Q st LBFT-⇒-bind Post Q f pf m st con = RWS-⇒-bind Post Q f unit pf m st con LBFT-⇒-ebind : ∀ {A B C} (P : LBFT-Post (Either C A)) (Q : LBFT-Post (Either C B)) → (f : A → LBFT (Either C B)) → RWS-Post-⇒ P (RWS-weakestPre-ebindPost unit f Q) → ∀ m st → LBFT-weakestPre m P st → LBFT-weakestPre (m ∙?∙ f) Q st LBFT-⇒-ebind Post Q f pf m st con = RWS-⇒-ebind Post Q f unit pf m st con
Formal statement is: lemma homotopy_eqv_trans [trans]: assumes 1: "X homotopy_equivalent_space Y" and 2: "Y homotopy_equivalent_space U" shows "X homotopy_equivalent_space U" Informal statement is: If $X$ is homotopy equivalent to $Y$ and $Y$ is homotopy equivalent to $U$, then $X$ is homotopy equivalent to $U$.
import .clause open tactic meta def trisect (m : nat) : list (list nat × term) → (list (list nat × term) × list (list nat × term) × list (list nat × term)) | [] := ([],[],[]) | ((p,t)::pts) := let (neg,zero,pos) := trisect pts in if t.snd.get m < 0 then ((p,t)::neg,zero,pos) else if t.snd.get m = 0 then (neg,(p,t)::zero,pos) else (neg,zero,(p,t)::pos) meta def elim_var_aux (m : nat) : ((list nat × term) × (list nat × term)) → tactic (list nat × term) | ((p1,t1), (p2,t2)) := let n := int.nat_abs (t1.snd.get m) in let o := int.nat_abs (t2.snd.get m) in let lcm := (nat.lcm n o) in let n' := lcm / n in let o' := lcm / o in return (list.add (n' *₁ p1) (o' *₁ p2), term.add (t1.mul n') (t2.mul o')) meta def elim_var (m) (neg pos : list (list nat × term)) : tactic (list (list nat × term)) := let pairs := list.product neg pos in monad.mapm (elim_var_aux m) pairs meta def find_contra : list (list nat × term) → tactic (list nat) | [] := failed | ((π,⟨c,_⟩)::l) := if c < 0 then return π else find_contra l meta def search_core : nat → list (list nat × term) → tactic (list nat) | 0 pts := find_contra pts | (m+1) pts := let (neg,zero,pos) := trisect m pts in do new ← elim_var m neg pos, search_core m (new ++ zero) meta def search (ts : list term) : tactic (list nat) := search_core (ts.map (λ t : term, t.snd.length)).max (ts.map_with_idx (λ m t, ([]{m ↦ 1}, t))) @[omega] def comb : list term → list nat → term | [] [] := ⟨0,[]⟩ | [] (_::_) := ⟨0,[]⟩ | (_::_) [] := ⟨0,[]⟩ | (t::ts) (n::ns) := term.add (t.mul ↑n) (comb ts ns) lemma comb_holds {v} : ∀ {ts} ns, (∀ t ∈ ts, 0 ≤ term.val v t) → (0 ≤ (comb ts ns).val v) | [] [] h := by simp_omega | [] (_::_) h := by simp_omega | (_::_) [] h := by simp_omega | (t::ts) (n::ns) h := begin simp_omega, apply add_nonneg, { apply mul_nonneg, apply int.coe_nat_nonneg, apply h _ (or.inl rfl) }, { apply comb_holds, apply list.forall_mem_of_forall_mem_cons h } end def unsat_comb (ts ns) : Prop := (comb ts ns).fst < 0 ∧ ∀ x ∈ (comb ts ns).snd, x = (0 : int) lemma unsat_comb_of (ts ns) : (comb ts ns).fst < 0 → (∀ x ∈ (comb ts ns).snd, x = (0 : int)) → unsat_comb ts ns := begin intros h1 h2, exact ⟨h1,h2⟩ end lemma unsat_of_unsat_comb (ns les) : (unsat_comb les ns) → clause.unsat ([], les) := begin intros h1 h2, cases h2 with v h2, have h3 := comb_holds ns h2.right, cases h1 with hl hr, cases (comb les ns) with b as, simp_omega at h3, rw [coeffs.val_eq_zero hr, add_zero, ← not_lt] at h3, apply h3 hl end #exit lemma unsat_of_unsat_comb' (ts : polytope) (ns : list nat) : (unsat_comb' ts ns) → ts.unsat := begin intro h1, apply unsat_of_unsat_comb ns, simp only [unsat_comb'] at h1, simp only [unsat_comb], rw if_pos h1, trivial end
(* Copyright 2018 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. *) theory task_list_pop_front_opt_mem imports tasks_opt begin text \<open>Up to two locales per function in the binary.\<close> locale task_list_pop_front_function = tasks_opt_context + fixes rsp\<^sub>0 rbp\<^sub>0 a task_list_pop_front_opt_ret :: \<open>64 word\<close> and v\<^sub>0 :: \<open>8 word\<close> and blocks :: \<open>(nat \<times> 64 word \<times> nat) set\<close> assumes seps: \<open>seps blocks\<close> and masters: \<open>master blocks (a, 1) 0\<close> \<open>master blocks (rsp\<^sub>0, 8) 1\<close> and ret_address: \<open>outside task_list_pop_front_opt_ret 126 188\<close> \<comment> \<open>Only works for non-recursive functions.\<close> begin text \<open> The Floyd invariant expresses for some locations properties that are invariably true. Simply expresses that a byte in the memory remains untouched. \<close> definition pp_\<Theta> :: \<open>_ \<Rightarrow> _ \<Rightarrow> _ \<Rightarrow> floyd_invar\<close> where \<open>pp_\<Theta> list first next \<equiv> [ \<comment> \<open>precondition\<close> boffset+126 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0 \<and> regs \<sigma> rbp = rbp\<^sub>0 \<and> regs \<sigma> rdi = list \<and> \<sigma> \<turnstile> *[list,8] = first \<and> \<sigma> \<turnstile> *[first + 0x58,8] = next \<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+task_list_pop_front_opt_ret \<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0, boffset+159 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0 \<and> regs \<sigma> rbp = rbp\<^sub>0 \<and> regs \<sigma> rax = first \<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+task_list_pop_front_opt_ret \<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0, \<comment> \<open>postcondition\<close> boffset+task_list_pop_front_opt_ret \<mapsto> \<lambda>\<sigma>. \<sigma> \<turnstile> *[a,1] = v\<^sub>0 \<and> regs \<sigma> rsp = rsp\<^sub>0+8 \<and> regs \<sigma> rbp = rbp\<^sub>0 ]\<close> text \<open>Adding some rules to the simplifier to simplify proofs.\<close> schematic_goal pp_\<Theta>_zero[simp]: \<open>pp_\<Theta> list first next boffset = ?x\<close> unfolding pp_\<Theta>_def by simp schematic_goal pp_\<Theta>_numeral_l[simp]: \<open>pp_\<Theta> list first next (n + boffset) = ?x\<close> unfolding pp_\<Theta>_def by simp schematic_goal pp_\<Theta>_numeral_r[simp]: \<open>pp_\<Theta> list first next (boffset + n) = ?x\<close> unfolding pp_\<Theta>_def by simp lemma rewrite_task_list_pop_front_opt_mem: assumes \<open>master blocks (list, 8) 2\<close> \<open>master blocks (list+8, 8) 3\<close> \<open>master blocks (first+0x58, 16) 4\<close> \<open>master blocks (next+0x60, 8) 5\<close> shows \<open>is_std_invar task_list_pop_front_opt_ret (floyd.invar task_list_pop_front_opt_ret (pp_\<Theta> list first next))\<close> proof - note masters = masters assms show ?thesis text \<open>Boilerplate code to start the VCG\<close> apply (rule floyd_invarI) apply (rewrite at \<open>floyd_vcs task_list_pop_front_opt_ret \<hole> _\<close> pp_\<Theta>_def) apply (intro floyd_vcsI) text \<open>Subgoal for rip = boffset+126\<close> subgoal premises prems for \<sigma> text \<open>Insert relevant knowledge\<close> apply (insert prems seps ret_address) text \<open>Apply VCG/symb.\ execution\<close> apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+ done text \<open>Subgoal for rip = boffset+159\<close> subgoal premises prems for \<sigma> text \<open>Insert relevant knowledge\<close> apply (insert prems seps ret_address) text \<open>Apply VCG/symb.\ execution\<close> apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+ done text \<open>Trivial ending subgoal.\<close> subgoal by simp done qed end end
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Reeased under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.star.spectrum import analysis.normed.group.quotient import analysis.normed_space.algebra import topology.continuous_function.units import topology.continuous_function.compact import topology.algebra.algebra import topology.continuous_function.stone_weierstrass /-! # Gelfand Duality The `gelfand_transform` is an algebra homomorphism from a topological `𝕜`-algebra `A` to `C(character_space 𝕜 A, 𝕜)`. In the case where `A` is a commutative complex Banach algebra, then the Gelfand transform is actually spectrum-preserving (`spectrum.gelfand_transform_eq`). Moreover, when `A` is a commutative C⋆-algebra over `ℂ`, then the Gelfand transform is a surjective isometry, and even an equivalence between C⋆-algebras. ## Main definitions * `ideal.to_character_space` : constructs an element of the character space from a maximal ideal in a commutative complex Banach algebra * `weak_dual.character_space.comp_continuous_map`: The functorial map taking `ψ : A →⋆ₐ[ℂ] B` to a continuous function `character_space ℂ B → character_space ℂ A` given by pre-composition with `ψ`. ## Main statements * `spectrum.gelfand_transform_eq` : the Gelfand transform is spectrum-preserving when the algebra is a commutative complex Banach algebra. * `gelfand_transform_isometry` : the Gelfand transform is an isometry when the algebra is a commutative (unital) C⋆-algebra over `ℂ`. * `gelfand_transform_bijective` : the Gelfand transform is bijective when the algebra is a commutative (unital) C⋆-algebra over `ℂ`. ## TODO * After `star_alg_equiv` is defined, realize `gelfand_transform` as a `star_alg_equiv`. * Prove that if `A` is the unital C⋆-algebra over `ℂ` generated by a fixed normal element `x` in a larger C⋆-algebra `B`, then `character_space ℂ A` is homeomorphic to `spectrum ℂ x`. * From the previous result, construct the **continuous functional calculus**. * Show that if `X` is a compact Hausdorff space, then `X` is (canonically) homeomorphic to `character_space ℂ C(X, ℂ)`. * Conclude using the previous fact that the functors `C(⬝, ℂ)` and `character_space ℂ ⬝` along with the canonical homeomorphisms described above constitute a natural contravariant equivalence of the categories of compact Hausdorff spaces (with continuous maps) and commutative unital C⋆-algebras (with unital ⋆-algebra homomoprhisms); this is known as **Gelfand duality**. ## Tags Gelfand transform, character space, C⋆-algebra -/ open weak_dual open_locale nnreal section complex_banach_algebra open ideal variables {A : Type*} [normed_comm_ring A] [normed_algebra ℂ A] [complete_space A] (I : ideal A) [ideal.is_maximal I] /-- Every maximal ideal in a commutative complex Banach algebra gives rise to a character on that algebra. In particular, the character, which may be identified as an algebra homomorphism due to `weak_dual.character_space.equiv_alg_hom`, is given by the composition of the quotient map and the Gelfand-Mazur isomorphism `normed_ring.alg_equiv_complex_of_complete`. -/ noncomputable def ideal.to_character_space : character_space ℂ A := character_space.equiv_alg_hom.symm $ ((@normed_ring.alg_equiv_complex_of_complete (A ⧸ I) _ _ (by { letI := quotient.field I, exact @is_unit_iff_ne_zero (A ⧸ I) _ }) _).symm : A ⧸ I →ₐ[ℂ] ℂ).comp (quotient.mkₐ ℂ I) lemma ideal.to_character_space_apply_eq_zero_of_mem {a : A} (ha : a ∈ I) : I.to_character_space a = 0 := begin unfold ideal.to_character_space, simpa only [character_space.equiv_alg_hom_symm_coe, alg_hom.coe_comp, alg_equiv.coe_alg_hom, quotient.mkₐ_eq_mk, function.comp_app, quotient.eq_zero_iff_mem.mpr ha, spectrum.zero_eq, normed_ring.alg_equiv_complex_of_complete_symm_apply] using set.eq_of_mem_singleton (set.singleton_nonempty (0 : ℂ)).some_mem, end /-- If `a : A` is not a unit, then some character takes the value zero at `a`. This is equivlaent to `gelfand_transform ℂ A a` takes the value zero at some character. -/ lemma weak_dual.character_space.exists_apply_eq_zero {a : A} (ha : ¬ is_unit a) : ∃ f : character_space ℂ A, f a = 0 := begin unfreezingI { obtain ⟨M, hM, haM⟩ := (span {a}).exists_le_maximal (span_singleton_ne_top ha) }, exact ⟨M.to_character_space, M.to_character_space_apply_eq_zero_of_mem (haM (mem_span_singleton.mpr ⟨1, (mul_one a).symm⟩))⟩, end lemma weak_dual.character_space.mem_spectrum_iff_exists {a : A} {z : ℂ} : z ∈ spectrum ℂ a ↔ ∃ f : character_space ℂ A, f a = z := begin refine ⟨λ hz, _, _⟩, { obtain ⟨f, hf⟩ := weak_dual.character_space.exists_apply_eq_zero hz, simp only [map_sub, sub_eq_zero, alg_hom_class.commutes, algebra.id.map_eq_id, ring_hom.id_apply] at hf, exact (continuous_map.spectrum_eq_range (gelfand_transform ℂ A a)).symm ▸ ⟨f, hf.symm⟩ }, { rintro ⟨f, rfl⟩, exact alg_hom.apply_mem_spectrum f a, } end /-- The Gelfand transform is spectrum-preserving. -/ lemma spectrum.gelfand_transform_eq (a : A) : spectrum ℂ (gelfand_transform ℂ A a) = spectrum ℂ a := begin ext z, rw [continuous_map.spectrum_eq_range, weak_dual.character_space.mem_spectrum_iff_exists], exact iff.rfl, end instance [nontrivial A] : nonempty (character_space ℂ A) := ⟨classical.some $ weak_dual.character_space.exists_apply_eq_zero $ zero_mem_nonunits.2 zero_ne_one⟩ end complex_banach_algebra section complex_cstar_algebra variables {A : Type*} [normed_comm_ring A] [normed_algebra ℂ A] [complete_space A] variables [star_ring A] [cstar_ring A] [star_module ℂ A] lemma gelfand_transform_map_star (a : A) : gelfand_transform ℂ A (star a) = star (gelfand_transform ℂ A a) := continuous_map.ext $ λ φ, map_star φ a variable (A) /-- The Gelfand transform is an isometry when the algebra is a C⋆-algebra over `ℂ`. -/ lemma gelfand_transform_isometry : isometry (gelfand_transform ℂ A) := begin nontriviality A, refine add_monoid_hom_class.isometry_of_norm (gelfand_transform ℂ A) (λ a, _), /- By `spectrum.gelfand_transform_eq`, the spectra of `star a * a` and its `gelfand_transform` coincide. Therefore, so do their spectral radii, and since they are self-adjoint, so also do their norms. Applying the C⋆-property of the norm and taking square roots shows that the norm is preserved. -/ have : spectral_radius ℂ (gelfand_transform ℂ A (star a * a)) = spectral_radius ℂ (star a * a), { unfold spectral_radius, rw spectrum.gelfand_transform_eq, }, simp only [map_mul, (is_self_adjoint.star_mul_self _).spectral_radius_eq_nnnorm, gelfand_transform_map_star a, ennreal.coe_eq_coe, cstar_ring.nnnorm_star_mul_self, ←sq] at this, simpa only [function.comp_app, nnreal.sqrt_sq] using congr_arg ((coe : ℝ≥0 → ℝ) ∘ ⇑nnreal.sqrt) this, end /-- The Gelfand transform is bijective when the algebra is a C⋆-algebra over `ℂ`. -/ lemma gelfand_transform_bijective : function.bijective (gelfand_transform ℂ A) := begin refine ⟨(gelfand_transform_isometry A).injective, _⟩, suffices : (gelfand_transform ℂ A).range = ⊤, { exact λ x, this.symm ▸ (gelfand_transform ℂ A).mem_range.mp (this.symm ▸ algebra.mem_top) }, /- Because the `gelfand_transform ℂ A` is an isometry, it has closed range, and so by the Stone-Weierstrass theorem, it suffices to show that the image of the Gelfand transform separates points in `C(character_space ℂ A, ℂ)` and is closed under `star`. -/ have h : (gelfand_transform ℂ A).range.topological_closure = (gelfand_transform ℂ A).range, from le_antisymm (subalgebra.topological_closure_minimal _ le_rfl (gelfand_transform_isometry A).closed_embedding.closed_range) (subalgebra.le_topological_closure _), refine h ▸ continuous_map.subalgebra_is_R_or_C_topological_closure_eq_top_of_separates_points _ (λ _ _, _) (λ f hf, _), /- Separating points just means that elements of the `character_space` which agree at all points of `A` are the same functional, which is just extensionality. -/ { contrapose!, exact λ h, subtype.ext (continuous_linear_map.ext $ λ a, h (gelfand_transform ℂ A a) ⟨gelfand_transform ℂ A a, ⟨a, rfl⟩, rfl⟩), }, /- If `f = gelfand_transform ℂ A a`, then `star f` is also in the range of `gelfand_transform ℂ A` using the argument `star a`. The key lemma below may be hard to spot; it's `map_star` coming from `weak_dual.star_hom_class`, which is a nontrivial result. -/ { obtain ⟨f, ⟨a, rfl⟩, rfl⟩ := subalgebra.mem_map.mp hf, refine ⟨star a, continuous_map.ext $ λ ψ, _⟩, simpa only [gelfand_transform_map_star a, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom] } end /-- The Gelfand transform as a `star_alg_equiv` between a commutative unital C⋆-algebra over `ℂ` and the continuous functions on its `character_space`. -/ @[simps] noncomputable def gelfand_star_transform : A ≃⋆ₐ[ℂ] C(character_space ℂ A, ℂ) := star_alg_equiv.of_bijective (show A →⋆ₐ[ℂ] C(character_space ℂ A, ℂ), from { map_star' := λ x, gelfand_transform_map_star x, .. gelfand_transform ℂ A }) (gelfand_transform_bijective A) end complex_cstar_algebra section functoriality namespace weak_dual namespace character_space variables {A B C : Type*} variables [normed_ring A] [normed_algebra ℂ A] [complete_space A] [star_ring A] variables [normed_ring B] [normed_algebra ℂ B] [complete_space B] [star_ring B] variables [normed_ring C] [normed_algebra ℂ C] [complete_space C] [star_ring C] /-- The functorial map taking `ψ : A →⋆ₐ[ℂ] B` to a continuous function `character_space ℂ B → character_space ℂ A` obtained by pre-composition with `ψ`. -/ @[simps] noncomputable def comp_continuous_map (ψ : A →⋆ₐ[ℂ] B) : C(character_space ℂ B, character_space ℂ A) := { to_fun := λ φ, equiv_alg_hom.symm ((equiv_alg_hom φ).comp (ψ.to_alg_hom)), continuous_to_fun := continuous.subtype_mk (continuous_of_continuous_eval $ λ a, map_continuous $ gelfand_transform ℂ B (ψ a)) _ } variables (A) /-- `weak_dual.character_space.comp_continuous_map` sends the identity to the identity. -/ @[simp] lemma comp_continuous_map_id : comp_continuous_map (star_alg_hom.id ℂ A) = continuous_map.id (character_space ℂ A) := continuous_map.ext $ λ a, ext $ λ x, rfl variables {A} /-- `weak_dual.character_space.comp_continuous_map` is functorial. -/ @[simp] lemma comp_continuous_map_comp (ψ₂ : B →⋆ₐ[ℂ] C) (ψ₁ : A →⋆ₐ[ℂ] B) : comp_continuous_map (ψ₂.comp ψ₁) = (comp_continuous_map ψ₁).comp (comp_continuous_map ψ₂) := continuous_map.ext $ λ a, ext $ λ x, rfl end character_space end weak_dual end functoriality
dat = read.table('{{i.infile}}', header = T, row.names = 1, sep="\t", check.names = F) sim = cor(t(dat), method = '{{args.method}}') p = sim n = ncol(dat) {% if args.pval %} {% if args.method == 'pearson' or args.method == 'spearman' %} t = sim / sqrt((1-sim*sim)/(n-2)) p = 2*pt(-abs(t), n-2) {% elif args.method == 'kendall' %} z = 3*sim * sqrt( n*(n-1)/2/(2*n+5) ) p = 2*pnorm(-abs(z)) {% endif %} {% endif %} write.table(format(sim, digits=4, scientific=F), '{{o.outfile}}', sep="\t", row.names=T, col.names=T, quote=F) write.table(format(p, digits=3, scientific=T) , '{{o.outpval}}', sep="\t", row.names=T, col.names=T, quote=F)
% All the installation instructions are in a separate .md file named vonBertalanffy.md in docs/source/installation % Setup the paths to the data, scripts and functions % Check if this COBRA toolbox extension is in the Matlab path stm_dir = which('setupThermoModel.m'); cc_dir = which('addThermoToModel.m'); % test if call to python2 works [status,result] = system('python2 --version'); if status~=0 disp(result) %check the current version of python that is running [status,result] = system('python --version'); disp('Current version of python that is running:') disp(result) %find out what python is running and change to another version of %python (after a new version of python is installe) % which python % ls -al /usr/bin/python % sudo rm -rf /usr/bin/python % sudo ln -s /usr/bin/python3.7 /usr/bin/python error('python2 should be installed') end %test if call to cxcalc is installed [status,result] = system('cxcalc'); if status ~= 0 if status==127 disp(result) error('Check that ChemAxon Marvin Beans is working licence is working and cxcalc is on the system path.') else disp(result) setenv('PATH', [getenv('PATH') ':/usr/local/bin/chemaxon/bin'])%RF setenv('PATH', [getenv('PATH') ':/opt/ChemAxon/MarvinBeans/bin/']) setenv('CHEMAXON_LICENSE_URL',[getenv('HOME') '/.chemaxon/license.cxl']) [status,result] = system('cxcalc'); if status ~= 0 disp(result) error('Check that ChemAxon Marvin Beans is installed, licence is working and cxcalc is on the system path.') end end end [FILEPATH,NAME,EXT] = fileparts(which('testVonBertalanffy.m')); %test if call to cxcalc is working [status,result] = system(['cxcalc pka -a 20 -b 20 -M false ' FILEPATH filesep 'test.inchi']); if contains(result,'FAILED') disp(result) error('Check that ChemAxon Marvin Beans is installed, but may not have a working licence.') else disp('ChemAxon Marvin Beans is installed and working.') end %check if call to babel works [status,result] = system('ldd /usr/bin/babel'); if ~isempty(strfind(result,'MATLAB')) disp(result) fprintf('%s\n','babel must depend on the system libstdc++.so.6 not the one from MATLAB') fprintf('%s\n','Trying to edit the ''LD_LIBRARY_PATH'' to make sure that it has the correct system path before the Matlab path!') setenv('LD_LIBRARY_PATH',['/usr/lib/x86_64-linux-gnu:' getenv('LD_LIBRARY_PATH')]); fprintf('%s\n','The solution will be arch dependent'); end [status,result] = system('babel'); if status ~= 0 setenv('LD_LIBRARY_PATH',['/usr/lib/x86_64-linux-gnu:' getenv('LD_LIBRARY_PATH')]); end [status,result] = system('babel'); if status ~= 0 error('Check that OpenBabel is installed and on the system path.') end % Add extension to path if it is not already there if isempty(stm_dir) || isempty(cc_dir) vonB_dir = pwd; c = {'ComponentContribution'; 'SetupThermoModel'; 'testing'}; % Check that current directory contains all necessary subdirectories d = dir; c_test = {d.name}'; if all(ismember(c,c_test)) addpath(genpath(vonB_dir)); % Add to path savepath; % Save new path else error(['Current directory must be */vonBertalanffy, which should contain the following files and directories:\n' sprintf('%s\n',c{:})]); end end
x = cor(c(15, 12, 8, 8, 7, 7, 7, 6, 5, 3), c(10, 25, 17, 11, 13, 17, 20, 13, 9, 15)) res = format(round(x, 3), nsmall = 3) physics_scores = c(15, 12, 8, 8, 7, 7, 7, 6, 5, 3) history_scores = c(10, 25, 17, 11, 13, 17, 20, 13, 9, 15) dF = data.frame(physics_scores, history_scores) # http://stackoverflow.com/questions/3443687/formatting-decimal-places-in-r printDecimal <- function(x, k) cat(format(round(x, k), nsmall=k)) cor.sp = cor(physics_scores, history_scores) printDecimal(cor.sp, 3) fit.lin = lm(history_scores~physics_scores, data = dF) coef = coef(fit.lin)[2] printDecimal(coef, 3) new <- data.frame(physics_scores = 10) res = predict(fit.lin, newdata = new) printDecimal(res, 1)
{-# LANGUAGE ScopedTypeVariables #-} module Main ( main ) where ------------------------------------------------------------------------------- import Data.Foldable as FT import Data.Ratio import Data.Sequence as Seq import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck ------------------------------------------------------------------------------- import Statistics.RollingAverage ------------------------------------------------------------------------------- main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "rolling-average" [ testProperty "window size of 0 always produces 0" $ \(samples :: [Int]) -> ravg (avgList 0 samples) === (0.0 :: Double) , testProperty "never grows samples larger than the limit" $ \(Positive lim) (samples :: [Int]) -> Seq.length (ravgSamples (avgList lim samples)) <= lim , testCase "can calculate rolling average as a Ratio" $ do ravg (avgList 3 ([0, 1, 2, 3, 4, 5] :: [Int])) @?= (((3 + 4 + 5) % 3) :: Rational) ] ------------------------------------------------------------------------------- avgList :: Num a => Int -> [a] -> RollingAvg a avgList lim samples = FT.foldl' ravgAdd (mkRavg lim) samples
library(ggplot2) library(tidyr) library(dplyr) library(rstan) library(data.table) library(lubridate) library(gdata) library(EnvStats) library(matrixStats) library(scales) library(gridExtra) library(bayesplot) library(cowplot) #--------------------------------------------------------------------------- format_data <- function(i, dates, states, estimated_cases_raw, estimated_deaths_raw, reported_cases, reported_deaths, out, forecast=0, deaths_predicted=estimated_deaths_raw){ N <- length(dates[[i]]) if(forecast > 0) { dates[[i]] = c(dates[[i]], max(dates[[i]]) + 1:forecast) N = N + forecast reported_cases[[i]] = c(reported_cases[[i]],rep(NA,forecast)) reported_deaths[[i]] = c(reported_deaths[[i]],rep(NA,forecast)) } state <- states[[i]] estimated_cases <- colMeans(estimated_cases_raw[,1:N,i]) estimated_cases_li <- colQuantiles(estimated_cases_raw[,1:N,i],prob=.025) estimated_cases_ui <- colQuantiles(estimated_cases_raw[,1:N,i],prob=.975) estimated_cases_li2 <- colQuantiles(estimated_cases_raw[,1:N,i],prob=.25) estimated_cases_ui2 <- colQuantiles(estimated_cases_raw[,1:N,i],prob=.75) estimated_deaths <- colMeans(estimated_deaths_raw[,1:N,i]) estimated_deaths_li <- colQuantiles(estimated_deaths_raw[,1:N,i],prob=.025) estimated_deaths_ui <- colQuantiles(estimated_deaths_raw[,1:N,i],prob=.975) estimated_deaths_li2 <- colQuantiles(estimated_deaths_raw[,1:N,i],prob=.25) estimated_deaths_ui2 <- colQuantiles(estimated_deaths_raw[,1:N,i],prob=.75) deaths_predicted_li <- colQuantiles(deaths_predicted[,1:N,i],prob=.025) deaths_predicted_ui <- colQuantiles(deaths_predicted[,1:N,i],prob=.975) deaths_predicted_li2 <- colQuantiles(deaths_predicted[,1:N,i],prob=.25) deaths_predicted_ui2 <- colQuantiles(deaths_predicted[,1:N,i],prob=.75) rt <- colMeans(out$Rt_adj[,1:N,i]) rt_li <- colQuantiles(out$Rt_adj[,1:N,i],prob=.025) rt_ui <- colQuantiles(out$Rt_adj[,1:N,i],prob=.975) rt_li2 <- colQuantiles(out$Rt_adj[,1:N,i],prob=.25) rt_ui2 <- colQuantiles(out$Rt_adj[,1:N,i],prob=.75) data_state_plotting <- data.frame("date" = dates[[i]], "state" = rep(state, length(dates[[i]])), "reported_cases" = reported_cases[[i]], "predicted_cases" = estimated_cases, "cases_min" = estimated_cases_li, "cases_max" = estimated_cases_ui, "cases_min2" = estimated_cases_li2, "cases_max2" = estimated_cases_ui2, "reported_deaths" = reported_deaths[[i]], "estimated_deaths" = estimated_deaths, "deaths_min" = estimated_deaths_li, "deaths_max"= estimated_deaths_ui, "deaths_min2" = estimated_deaths_li2, "deaths_max2"= estimated_deaths_ui2, "deaths_predicted_li"=deaths_predicted_li, "deaths_predicted_ui"=deaths_predicted_ui, "deaths_predicted_li2"=deaths_predicted_li2, "deaths_predicted_ui2"=deaths_predicted_ui2, "rt" = rt, "rt_min" = rt_li, "rt_max" = rt_ui, "rt_min2" = rt_li2, "rt_max2" = rt_ui2) return(data_state_plotting) }
# Col union # Form the union of columns in a and b. If there are columns of the same name in both a and b, take the column from a. # # @param data frame a # @param data frame b # @keyword internal cunion <- function(a, b) { if (length(a) == 0) return(b) if (length(b) == 0) return(a) cbind(a, b[setdiff(names(b), names(a))]) } # Interleave (or zip) multiple units into one vector interleave <- function(...) UseMethod("interleave") #' @export interleave.unit <- function(...) { do.call("unit.c", do.call("interleave.default", lapply(list(...), as.list))) } #' @export interleave.default <- function(...) { vectors <- list(...) # Check lengths lengths <- unique(setdiff(vapply(vectors, length, integer(1)), 1L)) if (length(lengths) == 0) lengths <- 1 if (length(lengths) > 1) { cli::cli_abort("vectors must have at least one element") } # Replicate elements of length one up to correct length singletons <- vapply(vectors, length, integer(1)) == 1L vectors[singletons] <- lapply(vectors[singletons], rep, lengths) # Interleave vectors n <- lengths p <- length(vectors) interleave <- rep(1:n, each = p) + seq(0, p - 1) * n unlist(vectors, recursive = FALSE)[interleave] }
(* * Copyright (C) BedRock Systems Inc. 2020-2023 * * This software is distributed under the terms of the BedRock Open-Source License. * See the LICENSE-BedRock file in the repository root for details. *) Require Export iris.algebra.lib.excl_auth. Require Export bedrock.prelude.base. Set Printing Coercions. (** * Extension to [excl_auth] *) (** Extend [iris.algebra.lib.excl_auth] with fractional authoritative elements [excl_auth_frac] (notation [●E{q} a]) such that - fraction [1] coincides with the existing [excl_auth_auth] (notation [●E a]) - the operation [⋅] on such elements is addition of fractions - [●E{q} a] valid implies fraction [q] valid - [●E{q1} a1 ⋅ ●E{q2} a2] valid implies [a1 ≡ a2] - [●E{q} a ⋅ ◯E b] valid implies [a ≡ b] This is entirely straightforward because the underlying authoritative construction supports such fractions. *) (** Fractional authoritative elements for [excl_auth]. *) Definition excl_auth_frac {A : ofe} (q : Qp) (a : A) : excl_authR A := ●{#q} (Excl' a). #[global] Instance: Params (@excl_auth_frac) 1 := {}. #[global] Hint Opaque excl_auth_frac : typeclass_instances. Notation "●E{ q } a" := (excl_auth_frac q a) (at level 10, format "●E{ q } a"). Section excl_auth_frac. Context {A : ofe}. Implicit Types a b : A. Import proofmode_classes. Lemma excl_auth_auth_frac a : ●E a = ●E{1} a. Proof. done. Qed. #[global] Instance excl_auth_frac_ne q : NonExpansive (@excl_auth_frac A q). Proof. solve_proper. Qed. #[global] Instance excl_auth_frac_proper q : Proper ((≡) ==> (≡)) (@excl_auth_frac A q). Proof. apply: ne_proper. Qed. #[global] Instance excl_auth_frac_discrete q a `{!Discrete a} : Discrete (●E{q} a). Proof. apply auth_auth_discrete. apply Some_discrete, _. apply _. Qed. Lemma excl_auth_frac_op p q a : ●E{p + q} a ≡ ●E{p} a ⋅ ●E{q} a. Proof. by rewrite -auth_auth_dfrac_op. Qed. #[global] Instance excl_auth_frac_is_op q q1 q2 a : IsOp q q1 q2 → IsOp' (●E{q} a) (●E{q1} a) (●E{q2} a). Proof. rewrite /excl_auth_frac. apply _. Qed. Lemma excl_auth_frac_validN n q a : ✓{n} (●E{q} a) ↔ (q ≤ 1)%Qp. Proof. rewrite /excl_auth_frac. by rewrite auth_auth_dfrac_validN right_id. Qed. Lemma excl_auth_frac_valid q a : ✓ (●E{q} a) ↔ (q ≤ 1)%Qp. Proof. rewrite /excl_auth_frac. by rewrite auth_auth_dfrac_valid right_id. Qed. Lemma excl_auth_auth_frac_op_validN n q1 q2 a1 a2 : ✓{n} (●E{q1} a1 ⋅ ●E{q2} a2) ↔ (q1 + q2 ≤ 1)%Qp ∧ a1 ≡{n}≡ a2. Proof. rewrite/excl_auth_frac. by rewrite auth_auth_dfrac_op_validN (inj_iff Some) (inj_iff Excl) right_id. Qed. Lemma excl_auth_auth_frac_op_valid q1 q2 a1 a2 : ✓ (●E{q1} a1 ⋅ ●E{q2} a2) ↔ (q1 + q2 ≤ 1)%Qp ∧ a1 ≡ a2. Proof. rewrite/excl_auth_frac. by rewrite auth_auth_dfrac_op_valid (inj_iff Some) (inj_iff Excl) right_id. Qed. Lemma excl_auth_auth_frac_op_valid_L `{!LeibnizEquiv A} q1 q2 a1 a2 : ✓ (●E{q1} a1 ⋅ ●E{q2} a2) ↔ (q1 + q2 ≤ 1)%Qp ∧ a1 = a2. Proof. unfold_leibniz. apply excl_auth_auth_frac_op_valid. Qed. Lemma excl_auth_frac_op_invN n p a q b : ✓{n} (●E{p} a ⋅ ●E{q} b) → a ≡{n}≡ b. Proof. rewrite /excl_auth_frac=>/auth_auth_dfrac_op_invN. by rewrite (inj_iff Some) (inj_iff Excl). Qed. Lemma excl_auth_frac_op_inv p a q b : ✓ (●E{p} a ⋅ ●E{q} b) → a ≡ b. Proof. rewrite/excl_auth_frac=>/auth_auth_dfrac_op_inv. by rewrite (inj_iff Some) (inj_iff Excl). Qed. Lemma excl_auth_frac_op_inv_L `{!LeibnizEquiv A} p a q b : ✓ (●E{p} a ⋅ ●E{q} b) → a = b. Proof. unfold_leibniz. apply excl_auth_frac_op_inv. Qed. Lemma excl_auth_frac_agreeN q n a b : ✓{n} (●E{q} a ⋅ ◯E b) → a ≡{n}≡ b. Proof. rewrite/excl_auth_frac=>/auth_both_dfrac_validN-[] _ []Hinc Hv. move: Hinc. move/Some_includedN_exclusive/(_ Hv){Hv}. by rewrite (inj_iff Excl). Qed. Lemma excl_auth_frac_agree q a b : ✓ (●E{q} a ⋅ ◯E b) → a ≡ b. Proof. intros. apply equiv_dist=>n. by apply (excl_auth_frac_agreeN q), cmra_valid_validN. Qed. Lemma excl_auth_frac_agree_L `{!LeibnizEquiv A} q a b : ✓ (●E{q} a ⋅ ◯E b) → a = b. Proof. unfold_leibniz. apply excl_auth_frac_agree. Qed. End excl_auth_frac.
! { dg-do compile } ! { dg-options -std=legacy } ! ! Test elimination of various segfaults and ICEs on error recovery. ! ! Contributed by Gerhard Steinmetz <[email protected]> ! module m1 type t end type interface write(formatted) module procedure s end interface contains subroutine s(dtv,unit,iotype,vlist,extra,iostat,iomsg) ! { dg-error "Too many dummy arguments" } class(t), intent(in) :: dtv integer, intent(in) :: unit character(len=*), intent(in) :: iotype integer, intent(in) :: vlist(:) integer, intent(out) :: iostat character(len=*), intent(inout) :: iomsg end end module m2 type t end type interface read(formatted) module procedure s end interface contains subroutine s(dtv,unit,iotype,vlist,iostat,iomsg,extra) ! { dg-error "Too many dummy arguments" } class(t), intent(inout) :: dtv integer, intent(in) :: unit character(len=*), intent(in) :: iotype integer, intent(in) :: vlist(:) integer, intent(out) :: iostat character(len=*), intent(inout) :: iomsg end end module m3 type t end type interface read(formatted) module procedure s end interface contains subroutine s(dtv,extra,unit,iotype,vlist,iostat,iomsg) ! { dg-error "Too many dummy arguments" } class(t), intent(inout) :: dtv integer, intent(in) :: unit character(len=*), intent(in) :: iotype integer, intent(in) :: vlist(:) integer, intent(out) :: iostat character(len=*), intent(inout) :: iomsg end end module m4 type t end type interface write(unformatted) module procedure s end interface contains subroutine s(*) ! { dg-error "Alternate return" } end end module m5 type t contains procedure :: s generic :: write(unformatted) => s end type contains subroutine s(dtv, *) ! { dg-error "Too few dummy arguments" } class(t), intent(out) :: dtv end end module m6 type t character(len=20) :: name integer(4) :: age contains procedure :: pruf generic :: read(unformatted) => pruf end type contains subroutine pruf (dtv,unit,*,iomsg) ! { dg-error "Alternate return" } class(t), intent(inout) :: dtv integer, intent(in) :: unit character(len=*), intent(inout) :: iomsg write (unit=unit, iostat=iostat, iomsg=iomsg) dtv%name, dtv%age end end module m7 type t character(len=20) :: name integer(4) :: age contains procedure :: pruf generic :: read(unformatted) => pruf end type contains subroutine pruf (dtv,unit,iostat) ! { dg-error "Too few dummy arguments" } class(t), intent(inout) :: dtv integer, intent(in) :: unit integer, intent(out) :: iostat character(len=1) :: iomsg write (unit=unit, iostat=iostat, iomsg=iomsg) dtv%name, dtv%age end end module m type t character(len=20) :: name integer(4) :: age contains procedure :: pruf generic :: read(unformatted) => pruf end type contains subroutine pruf (dtv,unit,iostat,iomsg) class(t), intent(inout) :: dtv integer, intent(in) :: unit integer, intent(out) :: iostat character(len=*), intent(inout) :: iomsg write (unit=unit, iostat=iostat, iomsg=iomsg) dtv%name, dtv%age end end program test use m character(3) :: a, b class(t) :: chairman ! { dg-error "must be dummy, allocatable or pointer" } open (unit=71, file='myunformatted_data.dat', form='unformatted') read (71) a, chairman, b close (unit=71) end
[STATEMENT] lemma type_to_set: assumes type_def: "\<exists>(Rep :: 'b \<Rightarrow> int) Abs. type_definition Rep Abs {0 ..< m :: int}" shows "class.nontriv (TYPE('b))" (is ?a) and "m = int CARD('b)" (is ?b) [PROOF STATE] proof (prove) goal (1 subgoal): 1. class.nontriv TYPE('b) &&& m = int CARD('b) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (2 subgoals): 1. class.nontriv TYPE('b) 2. m = int CARD('b) [PROOF STEP] from type_def [PROOF STATE] proof (chain) picking this: \<exists>Rep Abs. type_definition Rep Abs {0..<m} [PROOF STEP] obtain rep :: "'b \<Rightarrow> int" and abs :: "int \<Rightarrow> 'b" where t: "type_definition rep abs {0 ..< m}" [PROOF STATE] proof (prove) using this: \<exists>Rep Abs. type_definition Rep Abs {0..<m} goal (1 subgoal): 1. (\<And>rep abs. type_definition rep abs {0..<m} \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: type_definition rep abs {0..<m} goal (2 subgoals): 1. class.nontriv TYPE('b) 2. m = int CARD('b) [PROOF STEP] have "card (UNIV :: 'b set) = card {0 ..< m}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. CARD('b) = card {0..<m} [PROOF STEP] using t [PROOF STATE] proof (prove) using this: type_definition rep abs {0..<m} goal (1 subgoal): 1. CARD('b) = card {0..<m} [PROOF STEP] by (rule type_definition.card) [PROOF STATE] proof (state) this: CARD('b) = card {0..<m} goal (2 subgoals): 1. class.nontriv TYPE('b) 2. m = int CARD('b) [PROOF STEP] also [PROOF STATE] proof (state) this: CARD('b) = card {0..<m} goal (2 subgoals): 1. class.nontriv TYPE('b) 2. m = int CARD('b) [PROOF STEP] have "\<dots> = m" [PROOF STATE] proof (prove) goal (1 subgoal): 1. int (card {0..<m}) = m [PROOF STEP] using m1 [PROOF STATE] proof (prove) using this: 1 < m goal (1 subgoal): 1. int (card {0..<m}) = m [PROOF STEP] by auto [PROOF STATE] proof (state) this: int (card {0..<m}) = m goal (2 subgoals): 1. class.nontriv TYPE('b) 2. m = int CARD('b) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: int CARD('b) = m [PROOF STEP] show ?b [PROOF STATE] proof (prove) using this: int CARD('b) = m goal (1 subgoal): 1. m = int CARD('b) [PROOF STEP] .. [PROOF STATE] proof (state) this: m = int CARD('b) goal (1 subgoal): 1. class.nontriv TYPE('b) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: m = int CARD('b) [PROOF STEP] show ?a [PROOF STATE] proof (prove) using this: m = int CARD('b) goal (1 subgoal): 1. class.nontriv TYPE('b) [PROOF STEP] unfolding class.nontriv_def [PROOF STATE] proof (prove) using this: m = int CARD('b) goal (1 subgoal): 1. 1 < CARD('b) [PROOF STEP] using m1 [PROOF STATE] proof (prove) using this: m = int CARD('b) 1 < m goal (1 subgoal): 1. 1 < CARD('b) [PROOF STEP] by auto [PROOF STATE] proof (state) this: class.nontriv TYPE('b) goal: No subgoals! [PROOF STEP] qed
[STATEMENT] lemma bit_exp_iff [bit_simps]: \<open>bit (2 ^ m) n \<longleftrightarrow> possible_bit TYPE('a) n \<and> m = n\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. bit ((2::'a) ^ m) n = (possible_bit TYPE('a) n \<and> m = n) [PROOF STEP] by (auto simp add: bit_iff_odd exp_div_exp_eq possible_bit_def)
module RingProperties import Ring import Monoid import Group import Group_property %access public export |||Auxiliary function that provzs that if a+a=a thzn a=0 aplusaZ: (r: Type) -> (pfr: Ring r) -> (a: r) -> ((Ring_Add r pfr a a) =a) -> (a = (DPair.fst(RingAdditive_id r pfr))) aplusaZ r (MkRing r (+) (*) pfr) a prf = (Group_property_4 r (+) (Basics.fst (Basics.fst pfr)) a a z (trans prf (sym (Basics.fst (pfz a))) )) where z: r z = (DPair.fst(RingAdditive_id r (MkRing r (+) (*) pfr))) pfz: (a: r) -> (a+z=a, z+a=a) pfz = DPair.snd (RingAdditive_id r (MkRing r (+) (*) pfr)) |||Proof that 0*a = 0 Zmultleft: (r: Type) -> (pfr: Ring r) -> (a: r) -> ((Ring_Mult r pfr (DPair.fst(RingAdditive_id r pfr)) a) = (DPair.fst(RingAdditive_id r pfr))) Zmultleft r (MkRing r (+) (*) pfr) a = (aplusaZ r (MkRing r (+) (*) pfr) (z*a) ( trans (sym (pfd a z z)) (cong {f= \p => p*a} (pfz z)) ) ) where z: r z = (DPair.fst(RingAdditive_id r (MkRing r (+) (*) pfr))) pfz: (a: r) -> (a+z=a) pfz a = Basics.fst ((DPair.snd (RingAdditive_id r (MkRing r (+) (*) pfr))) a) pfd: (a: r) -> (b: r) -> (c: r) -> ((b+c)*a = (b*a) + (c*a)) pfd a b c = Basics.snd ((Basics.snd (Basics.snd pfr)) a b c) |||Proof that a*0 = 0 Zmultright: (r: Type) -> (pfr: Ring r) -> (a: r) -> ((Ring_Mult r pfr a (DPair.fst(RingAdditive_id r pfr))) = (DPair.fst(RingAdditive_id r pfr))) Zmultright r (MkRing r (+) (*) pfr) a = (aplusaZ r (MkRing r (+) (*) pfr) (a*z) ( trans (sym (pfd a z z)) (cong {f= \p => a*p} (pfz z)) ) ) where z: r z = (DPair.fst(RingAdditive_id r (MkRing r (+) (*) pfr))) pfz: (a: r) -> (a+z=a) pfz a = Basics.fst ((DPair.snd (RingAdditive_id r (MkRing r (+) (*) pfr))) a) pfd: (a: r) -> (b: r) -> (c: r) -> (a*(b+c) = (a*b) + (a*c)) pfd a b c = Basics.fst ((Basics.snd (Basics.snd pfr)) a b c)
theorem mul_eq_zero_iff (a b : ℕ): a * b = 0 ↔ a = 0 ∨ b = 0 := begin split, intro h, apply nat.eq_zero_of_mul_eq_zero, exact h, intro f, cases f with a b, rw a, rw nat.zero_mul, rw b, rw nat.mul_zero, end
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Johan Commelin -/ import topology.category.Top import ring_theory.graded_algebra.homogeneous_ideal /-! # Projective spectrum of a graded ring The projective spectrum of a graded commutative ring is the subtype of all homogenous ideals that are prime and do not contain the irrelevant ideal. It is naturally endowed with a topology: the Zariski topology. ## Notation - `R` is a commutative semiring; - `A` is a commutative ring and an `R`-algebra; - `𝒜 : ℕ → submodule R A` is the grading of `A`; ## Main definitions * `projective_spectrum 𝒜`: The projective spectrum of a graded ring `A`, or equivalently, the set of all homogeneous ideals of `A` that is both prime and relevant i.e. not containing irrelevant ideal. Henceforth, we call elements of projective spectrum *relevant homogeneous prime ideals*. * `projective_spectrum.zero_locus 𝒜 s`: The zero locus of a subset `s` of `A` is the subset of `projective_spectrum 𝒜` consisting of all relevant homogeneous prime ideals that contain `s`. * `projective_spectrum.vanishing_ideal t`: The vanishing ideal of a subset `t` of `projective_spectrum 𝒜` is the intersection of points in `t` (viewed as relevant homogeneous prime ideals). * `projective_spectrum.Top`: the topological space of `projective_spectrum 𝒜` endowed with the Zariski topology -/ noncomputable theory open_locale direct_sum big_operators pointwise open direct_sum set_like Top topological_space category_theory opposite variables {R A: Type*} variables [comm_semiring R] [comm_ring A] [algebra R A] variables (𝒜 : ℕ → submodule R A) [graded_algebra 𝒜] /-- The projective spectrum of a graded commutative ring is the subtype of all homogenous ideals that are prime and do not contain the irrelevant ideal. -/ @[nolint has_inhabited_instance] def projective_spectrum := {I : homogeneous_ideal 𝒜 // I.to_ideal.is_prime ∧ ¬(homogeneous_ideal.irrelevant 𝒜 ≤ I)} namespace projective_spectrum variable {𝒜} /-- A method to view a point in the projective spectrum of a graded ring as a homogeneous ideal of that ring. -/ abbreviation as_homogeneous_ideal (x : projective_spectrum 𝒜) : homogeneous_ideal 𝒜 := x.1 lemma as_homogeneous_ideal_def (x : projective_spectrum 𝒜) : x.as_homogeneous_ideal = x.1 := rfl instance is_prime (x : projective_spectrum 𝒜) : x.as_homogeneous_ideal.to_ideal.is_prime := x.2.1 @[ext] lemma ext {x y : projective_spectrum 𝒜} : x = y ↔ x.as_homogeneous_ideal = y.as_homogeneous_ideal := subtype.ext_iff_val variable (𝒜) /-- The zero locus of a set `s` of elements of a commutative ring `A` is the set of all relevant homogeneous prime ideals of the ring that contain the set `s`. An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`. At a point `x` (a homogeneous prime ideal) the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`. In this manner, `zero_locus s` is exactly the subset of `projective_spectrum 𝒜` where all "functions" in `s` vanish simultaneously. -/ def zero_locus (s : set A) : set (projective_spectrum 𝒜) := {x | s ⊆ x.as_homogeneous_ideal} @[simp] lemma mem_zero_locus (x : projective_spectrum 𝒜) (s : set A) : x ∈ zero_locus 𝒜 s ↔ s ⊆ x.as_homogeneous_ideal := iff.rfl @[simp] lemma zero_locus_span (s : set A) : zero_locus 𝒜 (ideal.span s) = zero_locus 𝒜 s := by { ext x, exact (submodule.gi _ _).gc s x.as_homogeneous_ideal.to_ideal } variable {𝒜} /-- The vanishing ideal of a set `t` of points of the prime spectrum of a commutative ring `R` is the intersection of all the prime ideals in the set `t`. An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`. At a point `x` (a homogeneous prime ideal) the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`. In this manner, `vanishing_ideal t` is exactly the ideal of `A` consisting of all "functions" that vanish on all of `t`. -/ def vanishing_ideal (t : set (projective_spectrum 𝒜)) : homogeneous_ideal 𝒜 := ⨅ (x : projective_spectrum 𝒜) (h : x ∈ t), x.as_homogeneous_ideal lemma coe_vanishing_ideal (t : set (projective_spectrum 𝒜)) : (vanishing_ideal t : set A) = {f | ∀ x : projective_spectrum 𝒜, x ∈ t → f ∈ x.as_homogeneous_ideal} := begin ext f, rw [vanishing_ideal, set_like.mem_coe, ← homogeneous_ideal.mem_iff, homogeneous_ideal.to_ideal_infi, submodule.mem_infi], apply forall_congr (λ x, _), rw [homogeneous_ideal.to_ideal_infi, submodule.mem_infi, homogeneous_ideal.mem_iff], end lemma mem_vanishing_ideal (t : set (projective_spectrum 𝒜)) (f : A) : f ∈ vanishing_ideal t ↔ ∀ x : projective_spectrum 𝒜, x ∈ t → f ∈ x.as_homogeneous_ideal := by rw [← set_like.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq] @[simp] lemma vanishing_ideal_singleton (x : projective_spectrum 𝒜) : vanishing_ideal ({x} : set (projective_spectrum 𝒜)) = x.as_homogeneous_ideal := by simp [vanishing_ideal] lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (projective_spectrum 𝒜)) (I : ideal A) : t ⊆ zero_locus 𝒜 I ↔ I ≤ (vanishing_ideal t).to_ideal := ⟨λ h f k, (mem_vanishing_ideal _ _).mpr (λ x j, (mem_zero_locus _ _ _).mpr (h j) k), λ h, λ x j, (mem_zero_locus _ _ _).mpr (le_trans h (λ f h, ((mem_vanishing_ideal _ _).mp h) x j))⟩ variable (𝒜) /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_ideal : @galois_connection (ideal A) (set (projective_spectrum 𝒜))ᵒᵈ _ _ (λ I, zero_locus 𝒜 I) (λ t, (vanishing_ideal t).to_ideal) := λ I t, subset_zero_locus_iff_le_vanishing_ideal t I /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_set : @galois_connection (set A) (set (projective_spectrum 𝒜))ᵒᵈ _ _ (λ s, zero_locus 𝒜 s) (λ t, vanishing_ideal t) := have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi A _).gc, by simpa [zero_locus_span, function.comp] using galois_connection.compose ideal_gc (gc_ideal 𝒜) lemma gc_homogeneous_ideal : @galois_connection (homogeneous_ideal 𝒜) (set (projective_spectrum 𝒜))ᵒᵈ _ _ (λ I, zero_locus 𝒜 I) (λ t, (vanishing_ideal t)) := λ I t, by simpa [show I.to_ideal ≤ (vanishing_ideal t).to_ideal ↔ I ≤ (vanishing_ideal t), from iff.rfl] using subset_zero_locus_iff_le_vanishing_ideal t I.to_ideal lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (projective_spectrum 𝒜)) (s : set A) : t ⊆ zero_locus 𝒜 s ↔ s ⊆ vanishing_ideal t := (gc_set _) s t lemma subset_vanishing_ideal_zero_locus (s : set A) : s ⊆ vanishing_ideal (zero_locus 𝒜 s) := (gc_set _).le_u_l s lemma ideal_le_vanishing_ideal_zero_locus (I : ideal A) : I ≤ (vanishing_ideal (zero_locus 𝒜 I)).to_ideal := (gc_ideal _).le_u_l I lemma homogeneous_ideal_le_vanishing_ideal_zero_locus (I : homogeneous_ideal 𝒜) : I ≤ vanishing_ideal (zero_locus 𝒜 I) := (gc_homogeneous_ideal _).le_u_l I lemma subset_zero_locus_vanishing_ideal (t : set (projective_spectrum 𝒜)) : t ⊆ zero_locus 𝒜 (vanishing_ideal t) := (gc_ideal _).l_u_le t lemma zero_locus_anti_mono {s t : set A} (h : s ⊆ t) : zero_locus 𝒜 t ⊆ zero_locus 𝒜 s := (gc_set _).monotone_l h lemma zero_locus_anti_mono_ideal {s t : ideal A} (h : s ≤ t) : zero_locus 𝒜 (t : set A) ⊆ zero_locus 𝒜 (s : set A) := (gc_ideal _).monotone_l h lemma zero_locus_anti_mono_homogeneous_ideal {s t : homogeneous_ideal 𝒜} (h : s ≤ t) : zero_locus 𝒜 (t : set A) ⊆ zero_locus 𝒜 (s : set A) := (gc_homogeneous_ideal _).monotone_l h lemma vanishing_ideal_anti_mono {s t : set (projective_spectrum 𝒜)} (h : s ⊆ t) : vanishing_ideal t ≤ vanishing_ideal s := (gc_ideal _).monotone_u h lemma zero_locus_bot : zero_locus 𝒜 ((⊥ : ideal A) : set A) = set.univ := (gc_ideal 𝒜).l_bot @[simp] lemma zero_locus_singleton_zero : zero_locus 𝒜 ({0} : set A) = set.univ := zero_locus_bot _ @[simp] lemma zero_locus_empty : zero_locus 𝒜 (∅ : set A) = set.univ := (gc_set 𝒜).l_bot @[simp] lemma vanishing_ideal_univ : vanishing_ideal (∅ : set (projective_spectrum 𝒜)) = ⊤ := by simpa using (gc_ideal _).u_top lemma zero_locus_empty_of_one_mem {s : set A} (h : (1:A) ∈ s) : zero_locus 𝒜 s = ∅ := set.eq_empty_iff_forall_not_mem.mpr $ λ x hx, (infer_instance : x.as_homogeneous_ideal.to_ideal.is_prime).ne_top $ x.as_homogeneous_ideal.to_ideal.eq_top_iff_one.mpr $ hx h @[simp] lemma zero_locus_singleton_one : zero_locus 𝒜 ({1} : set A) = ∅ := zero_locus_empty_of_one_mem 𝒜 (set.mem_singleton (1 : A)) @[simp] lemma zero_locus_univ : zero_locus 𝒜 (set.univ : set A) = ∅ := zero_locus_empty_of_one_mem _ (set.mem_univ 1) lemma zero_locus_sup_ideal (I J : ideal A) : zero_locus 𝒜 ((I ⊔ J : ideal A) : set A) = zero_locus _ I ∩ zero_locus _ J := (gc_ideal 𝒜).l_sup lemma zero_locus_sup_homogeneous_ideal (I J : homogeneous_ideal 𝒜) : zero_locus 𝒜 ((I ⊔ J : homogeneous_ideal 𝒜) : set A) = zero_locus _ I ∩ zero_locus _ J := (gc_homogeneous_ideal 𝒜).l_sup lemma zero_locus_union (s s' : set A) : zero_locus 𝒜 (s ∪ s') = zero_locus _ s ∩ zero_locus _ s' := (gc_set 𝒜).l_sup lemma vanishing_ideal_union (t t' : set (projective_spectrum 𝒜)) : vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' := by ext1; convert (gc_ideal 𝒜).u_inf lemma zero_locus_supr_ideal {γ : Sort*} (I : γ → ideal A) : zero_locus _ ((⨆ i, I i : ideal A) : set A) = (⋂ i, zero_locus 𝒜 (I i)) := (gc_ideal 𝒜).l_supr lemma zero_locus_supr_homogeneous_ideal {γ : Sort*} (I : γ → homogeneous_ideal 𝒜) : zero_locus _ ((⨆ i, I i : homogeneous_ideal 𝒜) : set A) = (⋂ i, zero_locus 𝒜 (I i)) := (gc_homogeneous_ideal 𝒜).l_supr lemma zero_locus_Union {γ : Sort*} (s : γ → set A) : zero_locus 𝒜 (⋃ i, s i) = (⋂ i, zero_locus 𝒜 (s i)) := (gc_set 𝒜).l_supr lemma zero_locus_bUnion (s : set (set A)) : zero_locus 𝒜 (⋃ s' ∈ s, s' : set A) = ⋂ s' ∈ s, zero_locus 𝒜 s' := by simp only [zero_locus_Union] lemma vanishing_ideal_Union {γ : Sort*} (t : γ → set (projective_spectrum 𝒜)) : vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) := homogeneous_ideal.to_ideal_injective $ by convert (gc_ideal 𝒜).u_infi; exact homogeneous_ideal.to_ideal_infi _ lemma zero_locus_inf (I J : ideal A) : zero_locus 𝒜 ((I ⊓ J : ideal A) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J := set.ext $ λ x, by simpa using x.2.1.inf_le lemma union_zero_locus (s s' : set A) : zero_locus 𝒜 s ∪ zero_locus 𝒜 s' = zero_locus 𝒜 ((ideal.span s) ⊓ (ideal.span s'): ideal A) := by { rw zero_locus_inf, simp } lemma zero_locus_mul_ideal (I J : ideal A) : zero_locus 𝒜 ((I * J : ideal A) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J := set.ext $ λ x, by simpa using x.2.1.mul_le lemma zero_locus_mul_homogeneous_ideal (I J : homogeneous_ideal 𝒜) : zero_locus 𝒜 ((I * J : homogeneous_ideal 𝒜) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J := set.ext $ λ x, by simpa using x.2.1.mul_le lemma zero_locus_singleton_mul (f g : A) : zero_locus 𝒜 ({f * g} : set A) = zero_locus 𝒜 {f} ∪ zero_locus 𝒜 {g} := set.ext $ λ x, by simpa using x.2.1.mul_mem_iff_mem_or_mem @[simp] lemma zero_locus_singleton_pow (f : A) (n : ℕ) (hn : 0 < n) : zero_locus 𝒜 ({f ^ n} : set A) = zero_locus 𝒜 {f} := set.ext $ λ x, by simpa using x.2.1.pow_mem_iff_mem n hn lemma sup_vanishing_ideal_le (t t' : set (projective_spectrum 𝒜)) : vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') := begin intros r, rw [← homogeneous_ideal.mem_iff, homogeneous_ideal.to_ideal_sup, mem_vanishing_ideal, submodule.mem_sup], rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩, erw mem_vanishing_ideal at hf hg, apply submodule.add_mem; solve_by_elim end lemma mem_compl_zero_locus_iff_not_mem {f : A} {I : projective_spectrum 𝒜} : I ∈ (zero_locus 𝒜 {f} : set (projective_spectrum 𝒜))ᶜ ↔ f ∉ I.as_homogeneous_ideal := by rw [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff]; refl /-- The Zariski topology on the prime spectrum of a commutative ring is defined via the closed sets of the topology: they are exactly those sets that are the zero locus of a subset of the ring. -/ instance zariski_topology : topological_space (projective_spectrum 𝒜) := topological_space.of_closed (set.range (projective_spectrum.zero_locus 𝒜)) (⟨set.univ, by simp⟩) begin intros Zs h, rw set.sInter_eq_Inter, let f : Zs → set _ := λ i, classical.some (h i.2), have hf : ∀ i : Zs, ↑i = zero_locus 𝒜 (f i) := λ i, (classical.some_spec (h i.2)).symm, simp only [hf], exact ⟨_, zero_locus_Union 𝒜 _⟩ end (by { rintros _ ⟨s, rfl⟩ _ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus 𝒜 s t).symm⟩ }) /-- The underlying topology of `Proj` is the projective spectrum of graded ring `A`. -/ def Top : Top := Top.of (projective_spectrum 𝒜) lemma is_open_iff (U : set (projective_spectrum 𝒜)) : is_open U ↔ ∃ s, Uᶜ = zero_locus 𝒜 s := by simp only [@eq_comm _ Uᶜ]; refl lemma is_closed_iff_zero_locus (Z : set (projective_spectrum 𝒜)) : is_closed Z ↔ ∃ s, Z = zero_locus 𝒜 s := by rw [← is_open_compl_iff, is_open_iff, compl_compl] lemma is_closed_zero_locus (s : set A) : is_closed (zero_locus 𝒜 s) := by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ } lemma zero_locus_vanishing_ideal_eq_closure (t : set (projective_spectrum 𝒜)) : zero_locus 𝒜 (vanishing_ideal t : set A) = closure t := begin apply set.subset.antisymm, { rintro x hx t' ⟨ht', ht⟩, obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus 𝒜 s, by rwa [is_closed_iff_zero_locus] at ht', rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht, exact set.subset.trans ht hx }, { rw (is_closed_zero_locus _ _).closure_subset_iff, exact subset_zero_locus_vanishing_ideal 𝒜 t } end lemma vanishing_ideal_closure (t : set (projective_spectrum 𝒜)) : vanishing_ideal (closure t) = vanishing_ideal t := begin have := (gc_ideal 𝒜).u_l_u_eq_u t, dsimp only at this, ext1, erw zero_locus_vanishing_ideal_eq_closure 𝒜 t at this, exact this, end section basic_open /-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/ def basic_open (r : A) : topological_space.opens (projective_spectrum 𝒜) := { val := { x | r ∉ x.as_homogeneous_ideal }, property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ } @[simp] lemma mem_basic_open (f : A) (x : projective_spectrum 𝒜) : x ∈ basic_open 𝒜 f ↔ f ∉ x.as_homogeneous_ideal := iff.rfl lemma mem_coe_basic_open (f : A) (x : projective_spectrum 𝒜) : x ∈ (↑(basic_open 𝒜 f): set (projective_spectrum 𝒜)) ↔ f ∉ x.as_homogeneous_ideal := iff.rfl lemma is_open_basic_open {a : A} : is_open ((basic_open 𝒜 a) : set (projective_spectrum 𝒜)) := (basic_open 𝒜 a).property @[simp] lemma basic_open_eq_zero_locus_compl (r : A) : (basic_open 𝒜 r : set (projective_spectrum 𝒜)) = (zero_locus 𝒜 {r})ᶜ := set.ext $ λ x, by simpa only [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff] @[simp] lemma basic_open_one : basic_open 𝒜 (1 : A) = ⊤ := topological_space.opens.ext $ by simp @[simp] lemma basic_open_mul (f g : A) : basic_open 𝒜 (f * g) = basic_open 𝒜 f ⊓ basic_open 𝒜 g := topological_space.opens.ext $ by {simp [zero_locus_singleton_mul]} lemma basic_open_mul_le_left (f g : A) : basic_open 𝒜 (f * g) ≤ basic_open 𝒜 f := by { rw basic_open_mul 𝒜 f g, exact inf_le_left } lemma basic_open_mul_le_right (f g : A) : basic_open 𝒜 (f * g) ≤ basic_open 𝒜 g := by { rw basic_open_mul 𝒜 f g, exact inf_le_right } @[simp] lemma basic_open_pow (f : A) (n : ℕ) (hn : 0 < n) : basic_open 𝒜 (f ^ n) = basic_open 𝒜 f := topological_space.opens.ext $ by simpa using zero_locus_singleton_pow 𝒜 f n hn lemma basic_open_eq_union_of_projection (f : A) : basic_open 𝒜 f = ⨆ (i : ℕ), basic_open 𝒜 (graded_algebra.proj 𝒜 i f) := topological_space.opens.ext $ set.ext $ λ z, begin erw [mem_coe_basic_open, topological_space.opens.mem_Sup], split; intros hz, { rcases show ∃ i, graded_algebra.proj 𝒜 i f ∉ z.as_homogeneous_ideal, begin contrapose! hz with H, classical, rw ←direct_sum.sum_support_decompose 𝒜 f, apply ideal.sum_mem _ (λ i hi, H i) end with ⟨i, hi⟩, exact ⟨basic_open 𝒜 (graded_algebra.proj 𝒜 i f), ⟨i, rfl⟩, by rwa mem_basic_open⟩ }, { obtain ⟨_, ⟨i, rfl⟩, hz⟩ := hz, exact λ rid, hz (z.1.2 i rid) }, end lemma is_topological_basis_basic_opens : topological_space.is_topological_basis (set.range (λ (r : A), (basic_open 𝒜 r : set (projective_spectrum 𝒜)))) := begin apply topological_space.is_topological_basis_of_open_of_nhds, { rintros _ ⟨r, rfl⟩, exact is_open_basic_open 𝒜 }, { rintros p U hp ⟨s, hs⟩, rw [← compl_compl U, set.mem_compl_eq, ← hs, mem_zero_locus, set.not_subset] at hp, obtain ⟨f, hfs, hfp⟩ := hp, refine ⟨basic_open 𝒜 f, ⟨f, rfl⟩, hfp, _⟩, rw [← set.compl_subset_compl, ← hs, basic_open_eq_zero_locus_compl, compl_compl], exact zero_locus_anti_mono 𝒜 (set.singleton_subset_iff.mpr hfs) } end end basic_open section order /-! ## The specialization order We endow `projective_spectrum 𝒜` with a partial order, where `x ≤ y` if and only if `y ∈ closure {x}`. -/ instance : partial_order (projective_spectrum 𝒜) := subtype.partial_order _ @[simp] lemma as_ideal_le_as_ideal (x y : projective_spectrum 𝒜) : x.as_homogeneous_ideal ≤ y.as_homogeneous_ideal ↔ x ≤ y := subtype.coe_le_coe @[simp] lemma as_ideal_lt_as_ideal (x y : projective_spectrum 𝒜) : x.as_homogeneous_ideal < y.as_homogeneous_ideal ↔ x < y := subtype.coe_lt_coe lemma le_iff_mem_closure (x y : projective_spectrum 𝒜) : x ≤ y ↔ y ∈ closure ({x} : set (projective_spectrum 𝒜)) := begin rw [← as_ideal_le_as_ideal, ← zero_locus_vanishing_ideal_eq_closure, mem_zero_locus, vanishing_ideal_singleton], simp only [coe_subset_coe, subtype.coe_le_coe, coe_coe], end end order end projective_spectrum
Require Import VST.veric.rmaps. Require Import VST.veric.compcert_rmaps. Require Import VST.progs.conclib. Require Import VST.progs.ghosts. Require Import VST.floyd.library. Require Import VST.floyd.sublist. Require Import VST.progs.invariants. Require Import VST.progs.fupd. Require Import atomics.general_atomics. Set Bullet Behavior "Strict Subproofs". (* To avoid carrying views with protocol assertions, we instead forbid them from appearing in invariants. *) Parameter objective : mpred -> Prop. Axiom emp_objective : objective emp. Axiom data_at_objective : forall {cs : compspecs} sh t v p, objective (data_at sh t v p). Axiom own_objective : forall {RA : Ghost} g (a : G) pp, objective (own g a pp). Axiom prop_objective : forall P, objective (!!P). Axiom andp_objective : forall P Q, objective P -> objective Q -> objective (P && Q). Axiom exp_objective : forall {A} P, (forall x, objective (P x)) -> objective (EX x : A, P x). Axiom sepcon_objective : forall P Q, objective P -> objective Q -> objective (P * Q). Lemma sepcon_list_objective : forall P, Forall objective P -> objective (fold_right sepcon emp P). Proof. induction P; simpl; intros. - apply emp_objective. - inv H; apply sepcon_objective; auto. Qed. Section inv. Context {inv_names : invG}. (* unsound without objective, until we redefine protocols to use thread-local info *) Axiom inv_alloc : forall N E P, objective P -> |> P |-- |={E}=> invariant N P. Corollary make_inv : forall N E P Q, P |-- Q -> objective Q -> P |-- |={E}=> invariant N Q. Proof. intros. eapply derives_trans, inv_alloc; auto. eapply derives_trans, now_later; auto. Qed. Ltac prove_objective := repeat match goal with | |-objective(if _ then _ else _) => if_tac | |-objective(exp _) => apply exp_objective; intro | |-objective(ghost_ref _ _) => apply exp_objective; intro | |-objective(_ * _) => apply sepcon_objective | |-objective(_ && _) => apply andp_objective | |-objective(!!_) => apply prop_objective | |-objective(own _ _ _) => apply own_objective | |-objective(data_at _ _ _ _) => apply data_at_objective | |-objective(data_at_ _ _ _) => rewrite data_at__eq; apply data_at_objective | |-objective(fold_right sepcon emp _) => apply sepcon_list_objective; rewrite ?Forall_map, Forall_forall; intros; simpl | _ => try apply own_objective end. Hint Resolve emp_objective data_at_objective own_objective prop_objective andp_objective exp_objective sepcon_objective sepcon_list_objective : objective. Section dup. Definition duplicable P := P |-- |==> P * P. Lemma emp_duplicable : duplicable emp. Proof. unfold duplicable. rewrite sepcon_emp; apply bupd_intro. Qed. Hint Resolve emp_duplicable : dup. Lemma sepcon_duplicable : forall P Q, duplicable P -> duplicable Q -> duplicable (P * Q). Proof. intros; unfold duplicable. rewrite <- sepcon_assoc, (sepcon_comm (_ * Q)), <- sepcon_assoc, sepcon_assoc. eapply derives_trans, bupd_sepcon. apply sepcon_derives; auto. Qed. Hint Resolve sepcon_duplicable : dup. Lemma sepcon_list_duplicable : forall lP, Forall duplicable lP -> duplicable (fold_right sepcon emp lP). Proof. induction 1; simpl; auto with dup. Qed. Lemma iter_sepcon_duplicable : forall {B} (f : B -> mpred) l, (forall a, duplicable (f a)) -> duplicable (iter_sepcon f l). Proof. induction l; simpl; auto with dup. Qed. Lemma list_duplicate : forall Q lP, duplicable Q -> fold_right sepcon emp lP * Q |-- |==> fold_right sepcon emp (map (sepcon Q) lP) * Q. Proof. induction lP; simpl; intros; [apply bupd_intro|]. rewrite sepcon_assoc; eapply derives_trans; [apply sepcon_derives; [apply derives_refl | apply IHlP]; auto|]. eapply derives_trans; [apply sepcon_derives, bupd_mono, sepcon_derives, H; apply derives_refl|]. eapply derives_trans; [apply bupd_frame_l|]. eapply derives_trans, bupd_trans. apply bupd_mono; cancel. eapply derives_trans; [apply bupd_frame_l|]. apply bupd_mono; cancel. Qed. (* Should all duplicables be of this form? *) Lemma invariant_duplicable' : forall N P, duplicable (invariant N P). Proof. unfold duplicable; intros. rewrite <- invariant_dup in *; apply bupd_intro. Qed. Hint Resolve invariant_duplicable' : dup. Lemma ghost_snap_duplicable : forall `{_ : PCM_order} (s : G) p, duplicable (ghost_snap s p). Proof. intros; unfold duplicable. erewrite ghost_snap_join; [apply bupd_intro|]. apply join_refl. Qed. Hint Resolve ghost_snap_duplicable : dup. Lemma prop_duplicable : forall P Q, duplicable Q -> duplicable (!!P && Q). Proof. intros; unfold duplicable. Intros. rewrite prop_true_andp; auto. Qed. Hint Resolve prop_duplicable : dup. Lemma exp_duplicable : forall {A} (P : A -> mpred), (forall x, duplicable (P x)) -> duplicable (exp P). Proof. unfold duplicable; intros. Intro x. eapply derives_trans; eauto. apply bupd_mono; Exists x x; auto. Qed. Definition weak_dup P := P -* |==> (P * P). End dup. End inv. Hint Resolve emp_duplicable sepcon_duplicable invariant_duplicable' ghost_snap_duplicable prop_duplicable : dup. Section atomics. Context {CS : compspecs}. Section protocols. Class protocol {state : Type} (Iread Ifull : state -> Z -> mpred) := { full_read s v : Ifull s v |-- |==> Ifull s v * Iread s v; read_dup s v : duplicable (Iread s v) }. Global Instance dup_protocol {state} (T : state -> Z -> mpred) (Ht : forall s v, duplicable (T s v)) : protocol T T. Proof. split; auto. Qed. Context {state : Type}. Parameter protocol_A : val -> state -> (state -> state -> Prop) -> ((state -> Z -> mpred) * (state -> Z -> mpred)) -> mpred. Context (ord : state -> state -> Prop) `{RelationClasses.PreOrder _ ord} (Tread Tfull : state -> Z -> mpred). Axiom protocol_A_nonexpansive : forall l s ord Tread1 Tfull1 Tread2 Tfull2, (ALL s : state, ALL v : Z, (Tread1 s v <=> Tread2 s v) && (Tfull1 s v <=> Tfull2 s v)) |-- protocol_A l s ord (Tread1, Tfull1) <=> protocol_A l s ord (Tread2, Tfull2). Lemma protocol_A_super_non_expansive : forall n l s ord Tread Tfull, approx n (protocol_A l s ord (Tread, Tfull)) = approx n (protocol_A l s ord (fun s v => approx n (Tread s v), fun s v => approx n (Tfull s v))). Proof. intros. apply approx_eq_i'. intros m ?. apply protocol_A_nonexpansive. intros ??; split; apply fash_equiv_approx; auto. Qed. Notation T := (Tread, Tfull). Axiom protocol_A_duplicable : forall l s, duplicable (protocol_A l s ord T). Axiom protocol_A_join' : forall l s1 s2, protocol_A l s1 ord T * protocol_A l s2 ord T |-- EX s : _, !!(ord s1 s /\ ord s2 s) && protocol_A l s ord T. Axiom make_protocol : forall {P : protocol Tread Tfull} sh l v s, writable_share sh -> repable_signed v -> data_at sh tint (vint v) l * |> Tfull s v |-- |==> protocol_A l s ord T. Axiom protocol_A_later : forall l s, protocol_A l s ord (|>Tread, |>Tfull) |-- |>protocol_A l s ord T. Axiom protocol_A_delay : forall l s, protocol_A l s ord T |-- protocol_A l s ord (|>Tread, |>Tfull). End protocols. Lemma approx_later : forall n P, approx (S n) (|> P) = |> approx n P. Proof. intros; apply predicates_hered.pred_ext. - intros ? []. change ((|> approx n P)%pred a); intros ??; split; auto. apply laterR_level in H1; omega. - intros ??. destruct (level a) eqn: Hl. + split; [omega|]. intros ??. apply laterR_level in H0; omega. + destruct (levelS_age _ _ (eq_sym Hl)) as (a' & ? & ?); subst. destruct (H a'). { constructor; auto. } split; [omega|]. intros ? HL; apply (H _ HL). Qed. Lemma approx_0 : forall P, approx 0 P = FF. Proof. intros; apply predicates_hered.pred_ext. - intros ? []; omega. - intros ??; contradiction. Qed. Definition OrdType s := ArrowType s (ArrowType s (ConstType Prop)). Definition PredType s := ArrowType s (ArrowType (ConstType Z) Mpred). Definition LA_type := ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ConstType val) (DependentType 0)) (OrdType (DependentType 0))) (ProdType (PredType (DependentType 0)) (PredType (DependentType 0)))) Mpred) (ConstType (iname -> Prop))) (PredType (DependentType 0))) (ConstType invG). Program Definition load_acq_spec := TYPE LA_type WITH l : val, s : _, st_ord : _ -> _ -> Prop, T : ((_ -> Z -> mpred) * (_ -> Z -> mpred)), P : mpred, E : Ensemble iname, Q : _ -> Z -> mpred, inv_names : invG PRE [ 1%positive OF tptr tint ] PROP () LOCAL (temp 1%positive l) SEP ((ALL s' : _, !!(st_ord s s') --> ALL v : _, (fst T s' v * P * protocol_A l s' st_ord T) -* |={E}=> Q s' v) && cored; P; protocol_A l s st_ord T) POST [ tint ] EX v : Z, EX s' : _, PROP (repable_signed v; st_ord s s') LOCAL (temp ret_temp (vint v)) SEP (Q s' v). Next Obligation. Proof. repeat intro. destruct x as (((((((?, s), ?), (?, ?)), P), ?), Q), ?); simpl. unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; f_equal; f_equal; rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem. rewrite protocol_A_super_non_expansive; f_equal. rewrite !approx_andp; f_equal. rewrite !approx_allp by auto; f_equal; extensionality. setoid_rewrite approx_imp; f_equal; f_equal. rewrite !(approx_allp _ _ _ 0); f_equal; extensionality. setoid_rewrite fview_shift_nonexpansive. rewrite !approx_sepcon, !approx_idem, protocol_A_super_non_expansive; auto. Qed. Next Obligation. Proof. repeat intro. destruct x as (((((((?, ?), ?), ?), ?), ?), ?), ?); simpl. rewrite !approx_exp; apply f_equal; extensionality. rewrite !approx_exp; apply f_equal; extensionality. unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 apply f_equal; rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem; auto. Qed. (*Definition SR_type := ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ConstType (val * Z)) (DependentType 0)) (DependentType 0)) (OrdType (DependentType 0))) (ProdType (PredType (DependentType 0)) (PredType (DependentType 0)))) Mpred) (ConstType (iname -> Prop))) Mpred. Program Definition store_rel_spec := TYPE SR_type WITH l : val, v : Z, s : _, s'' : _, st_ord : _ -> _ -> Prop, T : ((_ -> Z -> mpred) * (_ -> Z -> mpred)), P : mpred, II : Z -> mpred, lI : list Z, Q' : mpred, Q : mpred PRE [ 1%positive OF tptr tint, 2%positive OF tint ] PROP (repable_signed v; forall s', st_ord s' s''; view_shift (fold_right sepcon emp (map II lI) * P) (protocol_A l s st_ord T * snd T s'' v * Q')%logic; view_shift (protocol_A l s'' st_ord T * Q') (fold_right sepcon emp (map II lI) * Q)%logic) LOCAL (temp 1%positive l; temp 2%positive (vint v)) SEP (fold_right sepcon emp (map (fun p => invariant (II p)) lI); P) POST [ tvoid ] PROP () LOCAL () SEP (fold_right sepcon emp (map (fun p => invariant (II p)) lI); Q). Next Obligation. Proof. repeat intro. destruct x as ((((((((((?, ?), ?), ?), ?), (?, ?)), ?), ?), ?), ?), ?); simpl. unfold PROPx; simpl; rewrite !approx_andp; f_equal. - rewrite !prop_and, !approx_andp; f_equal; f_equal; f_equal; [|f_equal]. + rewrite view_shift_super_non_expansive. setoid_rewrite view_shift_super_non_expansive at 2; do 2 apply f_equal; f_equal. * rewrite !approx_sepcon, !approx_sepcon_list', approx_idem. erewrite !map_map, map_ext; eauto. intro; simpl; rewrite approx_idem; auto. * rewrite !approx_sepcon, !approx_idem, protocol_A_super_non_expansive; auto. + rewrite view_shift_super_non_expansive. setoid_rewrite view_shift_super_non_expansive at 2. rewrite !approx_sepcon, !approx_sepcon_list', protocol_A_super_non_expansive, !approx_idem. erewrite !map_map, map_ext; eauto. intro; simpl; rewrite approx_idem; auto. - unfold LOCALx; simpl; rewrite !approx_andp; apply f_equal. unfold SEPx; simpl; rewrite !sepcon_emp, !approx_sepcon, !approx_idem, !approx_sepcon_list'. erewrite !map_map, map_ext; eauto. intros; simpl; rewrite invariant_super_non_expansive; auto. Qed. Next Obligation. Proof. repeat intro. destruct x as ((((((((((?, ?), ?), ?), ?), ?), ?), ?), ?), ?), ?); simpl. unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 apply f_equal; rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem. rewrite !approx_sepcon_list'. erewrite !map_map, map_ext; eauto. intros; simpl; rewrite invariant_super_non_expansive; auto. Qed.*) (*Definition SR_type' := ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ConstType (val * Z)) (DependentType 0)) (OrdType (DependentType 0))) (ProdType (PredType (DependentType 0)) (PredType (DependentType 0)))) Mpred) (ArrowType (ConstType Z) Mpred)) (ConstType (list Z))) (ArrowType (DependentType 0) Mpred)) (ArrowType (DependentType 0) Mpred). (* The GPS/iGPS store_rel rule is only really useful when we have a single writer, only write once to a location, only really want to maintain an invariant, or otherwise aren't really doing anything with write-write races. The final-state restriction is partially to ensure that the target state is reachable, and partly to deal with the fact that the logic doesn't assume mo-coherence and thus a write may be placed "before" a write that's already been observed. This more relaxed rule is probably unsound. *) Program Definition store_rel_spec := TYPE SR_type' WITH l : val, v : Z, s : _, st_ord : _ -> _ -> Prop, T : ((_ -> Z -> mpred) * (_ -> Z -> mpred)), P : mpred, II : Z -> mpred, lI : list Z, Q' : _ -> mpred, Q : _ -> mpred PRE [ 1%positive OF tptr tint, 2%positive OF tint ] PROP (repable_signed v; view_shift (fold_right sepcon emp (map II lI) * P) (protocol_A l s st_ord T * P'); forall s' v', repable_signed v' -> st_ord s s' -> view_shift (P' * snd T s' v') (EX s'' : _, !!(st_ord s' s'') && snd T s'' v * Q' s'')%logic; forall s', st_ord s s' -> view_shift (protocol_A l s' st_ord T * Q' s') (fold_right sepcon emp (map II lI) * Q s')%logic) LOCAL (temp 1%positive l; temp 2%positive (vint v)) SEP (fold_right sepcon emp (map (fun p => invariant (II p)) lI); P) POST [ tvoid ] EX s' : _, PROP (st_ord s s') LOCAL () SEP (fold_right sepcon emp (map (fun p => invariant (II p)) lI); Q s'). Next Obligation. Proof. repeat intro. destruct x as (((((((((?, ?), s), ?), (?, ?)), ?), ?), ?), ?), ?); simpl. unfold PROPx; simpl; rewrite !approx_andp; f_equal. - rewrite !prop_and, !approx_andp; f_equal; f_equal; [|f_equal]. + rewrite !prop_forall, !(approx_allp _ _ _ s); apply f_equal; extensionality s'. rewrite !prop_impl; setoid_rewrite approx_imp; do 2 apply f_equal. rewrite view_shift_super_non_expansive. setoid_rewrite view_shift_super_non_expansive at 2; do 2 apply f_equal; f_equal. * rewrite !approx_sepcon, !approx_sepcon_list', approx_idem. erewrite !map_map, map_ext; eauto. intro; simpl; rewrite approx_idem; auto. * rewrite !approx_sepcon, protocol_A_super_non_expansive; apply f_equal. rewrite !approx_exp; apply f_equal; extensionality s''. rewrite !approx_sepcon, !approx_andp, !approx_idem; auto. + rewrite !prop_forall, !(approx_allp _ _ _ s); apply f_equal; extensionality s'. rewrite !prop_impl; setoid_rewrite approx_imp; do 2 apply f_equal. rewrite view_shift_super_non_expansive. setoid_rewrite view_shift_super_non_expansive at 2. do 2 apply f_equal; f_equal. * rewrite !approx_sepcon, !approx_idem, protocol_A_super_non_expansive; auto. * rewrite !approx_sepcon, !approx_sepcon_list', approx_idem. erewrite !map_map, map_ext; eauto. intro; simpl; rewrite approx_idem; auto. - unfold LOCALx; simpl; rewrite !approx_andp; apply f_equal. unfold SEPx; simpl; rewrite !sepcon_emp, !approx_sepcon, !approx_idem, !approx_sepcon_list'. erewrite !map_map, map_ext; eauto. intros; simpl; rewrite invariant_super_non_expansive; auto. Qed. Next Obligation. Proof. repeat intro. destruct x as (((((((((?, ?), ?), ?), ?), ?), ?), ?), ?), ?); simpl. rewrite !approx_exp; apply f_equal; extensionality s'. unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 apply f_equal; rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem. rewrite !approx_sepcon_list'. erewrite !map_map, map_ext; eauto. intros; simpl; rewrite invariant_super_non_expansive; auto. Qed.*) Definition CRA_type := ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ConstType (val * Z * Z)) (DependentType 0)) (OrdType (DependentType 0))) (ProdType (PredType (DependentType 0)) (PredType (DependentType 0)))) Mpred) (ConstType (iname -> Prop))) (ArrowType (DependentType 0) Mpred)) (PredType (DependentType 0))) (ConstType invG). Program Definition CAS_RA_spec := TYPE CRA_type WITH l : val, c : Z, v : Z, s : _, st_ord : _ -> _ -> Prop, T : ((_ -> Z -> mpred) * (_ -> Z -> mpred)), P : mpred, E : _, Q : _ -> mpred, R : _ -> Z -> mpred, inv_names : invG PRE [ 1%positive OF tptr tint, 2%positive OF tint, 3%positive OF tint ] PROP (repable_signed c; repable_signed v) LOCAL (temp 1%positive l; temp 2%positive (vint c); temp 3%positive (vint v)) SEP (ALL s' : _, !!(st_ord s s') --> ((snd T s' c * P) -* |={E}=> (EX s'' : _, !!(st_ord s' s'') && (protocol_A l s'' st_ord T) -* |={E}=> |> snd T s'' v * Q s'')) && cored; (* is this right? *) ALL s' : _, ALL v' : _, !!(st_ord s s' /\ repable_signed v' /\ v' <> c) --> ((|> fst T s' v' * protocol_A l s' st_ord T * P) -* |={E}=> (R s' v')) && cored; protocol_A l s st_ord T; P) POST [ tint ] EX v' : Z, EX s' : _, PROP (repable_signed v'; st_ord s s') LOCAL (temp ret_temp (Val.of_bool (if eq_dec v' c then true else false))) SEP (if eq_dec v' c then Q s' else R s' v'). Next Obligation. Proof. repeat intro. destruct x as ((((((((((?, ?), ?), s), ?), (?, ?)), ?), ?), ?), ?), ?); simpl. unfold PROPx; simpl; rewrite !approx_andp; f_equal. unfold LOCALx; simpl; rewrite !approx_andp; f_equal. unfold SEPx; simpl; rewrite !sepcon_emp, !approx_sepcon, !approx_idem. f_equal; [|rewrite protocol_A_super_non_expansive; f_equal]. - rewrite !approx_allp by auto; f_equal; extensionality. setoid_rewrite approx_imp; f_equal; f_equal. rewrite !approx_andp; f_equal. setoid_rewrite fview_shift_nonexpansive. rewrite !approx_sepcon, !approx_idem; f_equal; f_equal; f_equal. rewrite !approx_exp; f_equal; extensionality. rewrite wand_nonexpansive; setoid_rewrite wand_nonexpansive at 3; f_equal; f_equal. + rewrite !approx_andp, protocol_A_super_non_expansive; reflexivity. + rewrite fupd_nonexpansive; setoid_rewrite fupd_nonexpansive at 2; f_equal; f_equal. rewrite !approx_sepcon, approx_idem; f_equal. destruct n; [rewrite !approx_0; auto|]. setoid_rewrite approx_later. etransitivity; [rewrite <- approx_oo_approx' with (n' := S n)|]; auto. - rewrite !approx_allp by auto; f_equal; extensionality. rewrite !approx_allp by auto; f_equal; extensionality. setoid_rewrite approx_imp; f_equal; f_equal. rewrite !approx_andp; f_equal. setoid_rewrite fview_shift_nonexpansive. rewrite !approx_sepcon, !approx_idem; f_equal; f_equal. rewrite protocol_A_super_non_expansive; f_equal; f_equal. destruct n; [rewrite !approx_0; auto|]. setoid_rewrite approx_later. etransitivity; [rewrite <- approx_oo_approx' with (n' := S n)|]; auto. Qed. Next Obligation. Proof. repeat intro. destruct x as ((((((((((?, ?), ?), ?), ?), ?), ?), ?), ?), ?), ?); simpl. rewrite !approx_exp; apply f_equal; extensionality. rewrite !approx_exp; apply f_equal; extensionality. unfold PROPx; simpl; rewrite !approx_andp; f_equal. unfold LOCALx; simpl; rewrite !approx_andp; f_equal. unfold SEPx; simpl; rewrite !sepcon_emp; if_tac; rewrite approx_idem; auto. Qed. End atomics.
import Oceananigans.Fields: set! using Oceananigans.TimeSteppers: update_state! function set!(model::ShallowWaterModel; kwargs...) for (fldname, value) in kwargs if fldname ∈ propertynames(model.solution) ϕ = getproperty(model.solution, fldname) elseif fldname ∈ propertynames(model.tracers) ϕ = getproperty(model.tracers, fldname) else throw(ArgumentError("name $fldname not found in model.solution or model.tracers.")) end set!(ϕ, value) end update_state!(model) return nothing end
.ds TL "Character Driver" .NH "Example of a Character Driver" .PP This section gives an example driver for a character device: the \*(CO driver for the 8250-style asynchronous ports. It is described in the article .B asy in the \*(CO Lexicon. .PP In this driver, the minor-device number is a bit map that describes the features of the port, as follows: .DS 0x80 1 for NO modem control, `l' (lower-case ``el'') 0x40 1 for polled operation (no IRQ service), `p' 0x20 1 for RTS/CTS flow control, `f' 0x1F The channel number - 0 through 31 .DE Character-device line discipline, which includes such operations as processing backspaces entered and echoing input characters, is performed in the .B tty module in \*(CO 4.2. Source code is provided in the 4.2 Device-Driver Kit. Future releases of \*(CO will use a \*(ST-based line discipline. .SH "Preliminaries" .PP The following prefaces the body of the driver. .Sh "Header Files" .PP .B asy begins by including the following header files. .DM #include <sys/errno.h> #include <sys/stat.h> #include <termio.h> #include <poll.h> .DE .DM #include <sys/coherent.h> #include <kernel/trace.h> #include <sys/uproc.h> #include <sys/proc.h> #include <sys/tty.h> #include <sys/con.h> #include <sys/devices.h> #include <sys/sched.h> #include <sys/asy.h> #include <sys/ins8250.h> #include <sys/poll_clk.h> .DE .Sh "Manifest Constants" .PP The following gives manifest constants used throughout the driver. .DM #define IEN_USE_MSI (IE_RxI | IE_TxI | IE_LSI | IE_MSI) #define IEN_NO_MSI (IE_RxI | IE_TxI | IE_LSI) .DE .DM #define CTLQ 0021 #define CTLS 0023 .DE .DM .ta 2.0i 3.0i #define NUM_IRQ 16 /* PC allows irq numbers 0..15 */ #define BPB 8 /* 8 bits per byte */ #define DTRTMOUT 3 /* DTR seconds for close */ #define LOOP_LIMIT 100 /* safety valve on irq loops */ .DE .DM .ta 2.5i /* * For rawin silo (see poll_clk.h), use last element of si_buf to count * the number of characters in the silo. */ #define SILO_CHAR_COUNT si_buf[SI_BUFSIZ-1] #define SILO_HIGH_MARK (SI_BUFSIZ-SI_BUFSIZ/4) #define SILO_LOW_MARK (SI_BUFSIZ/4) #define MAX_SILO_INDEX (SI_BUFSIZ-2) #define MAX_SILO_CHARS (SI_BUFSIZ-1) .DE .Sh "Macros" .PP .B asy uses the following macros: .DM .ta 2.5i #define RAWIN_FLUSH(in_silo) { \e in_silo->si_ox = in_silo->si_ix; \e in_silo->SILO_CHAR_COUNT = 0; } #define RAWOUT_FLUSH(out_silo) { out_silo->si_ox = out_silo->si_ix; } #define channel(dev) (dev & 0x1F) #define IEN ((a0->a_nms)?IEN_NO_MSI:IEN_USE_MSI) .DE .DM .ta 2.0i 3.0i #define NW_OUTSILO 1 /* bits in need_wake[] entries */ .DE .DM typedef void (* VPTR)(); /* pointer to function returning void */ typedef int (* FPTR)(); /* pointer to function returning int */ .DE .Sh "Local Functions" .PP The following declares the functions used locally. .DM void asy_putchar(); .DE .DM /* Configuration functions (local) */ static void cinit(); .DE .DM /* Support functions (local) */ static void add_irq(); static void asy_irq(); static int asy_send(); static void asybreak(); static void asyclock(); static void asycycle(); static void asydump(); static int asyintr(); static void asyparam(); static void asysph(); static void asyspr(); static void asystart(); static void endbrk(); static void irqdummy(); static void upd_irq1(); .DE .DM static int p1(),p2(),p3(),p4(); .DE .DM extern int albaud[], alp_rate[]; .DE .Sh "Global Variables" .PP .B asy uses the following global variables: When the command .B asypatch patches the .B asy driver for your system's configuration of ports, it checks whether its internal value for .B ASY_VERSION matches this driver's value. This prevents the patch utility and the driver from getting out of synch. .DM int ASY_VER = ASY_VERSION; int ASY_HPCL = 1; int ASY_NUM = 0; int ASYGP_NUM = 0; asy0_t asy0[MAX_ASY] = { { 0 } }; asy_gp_t asy_gp[MAX_ASYGP] = { { 0 } }; .DE .Sh "Static Variables" .PP .B asy uses the following static variables. .DM .ta 3.0i static asy1_t * asy1; /* unused entries have type US_NONE */ static short dummy_port; /* used only during driver startup */ static int poll_divisor; /* set by asyspr(), read by asyclk() */ static char pptbl [MAX_ASY]; /* channel numbers of polled ports */ static int ppnum; /* number of channels in pptbl */ .DE Variables \fBirq0[\fIx\^\fB]\fR and \fBirq1[\fIx\^\fB]\fR are lists for IRQ number .IR x . .B irq0[] has nodes that may possibly cause an IRQ. .B irq1[] contains nodes for active devices. Whenever a device becomes active or inactive, .B irq1 is rebuilt from .BR irq0 . .PP .B nodespace is an array of the nodes that are available. .B nextnode points to the next free node. Nodes are taken from node space only when the driver is loaded. .DM static FPTR ptbl [PT_MAX] = { asyintr,p1,p2,p3,p4 }; static struct irqnode *irq0[NUM_IRQ], *irq1[NUM_IRQ]; static struct irqnode nodespace[MAX_ASY]; static char need_wake[MAX_ASY]; static char nextnode; static int initialized; /* for asy_putchar() */ .DE .SH "The Load Routine" .PP The first function is .BR asyload() . The kernel invokes this function when the driver is loaded into memory. Because \*(CO 4.2 does not support loadable drivers, this function is executed only when the kernel boots. .PP Field .B c_load in the .B CON structure contains a pointer to this function. .DM static void asyload() { int s, chan; asy0_t *a0; asy1_t *a1; TTY *tp; short port; char irq; char speed; char g; char sense_ct = 0; .DE .DM /* Allocate space for asy structs. Possible error return. */ asy1 = (asy1_t *)kalloc(ASY_NUM * sizeof(asy1_t)); if (asy1 == 0) { printf("asyload: can't allocate space for %d async devices\en", ASY_NUM); return; } kclear(asy1, ASY_NUM*sizeof(asy1_t)); .DE .DM /* * For each non-null port: * sense chip type * write baud rate to sgtty/termio structs * disable port interrupts * hang up port * set default baud rate (also resets UART) * hook "start" function into line discipline module * hook "param" function into line discipline module * hook CS into line discipline module * if port uses irq * if not in a port group * add to irq list */ .DE .DM for (chan = 0; chan < ASY_NUM; chan++) { a0 = asy0 + chan; a1 = asy1 + chan; tp = &a1->a_tty; speed = a0->a_speed; tp->t_sgttyb.sg_ispeed = tp->t_sgttyb.sg_ospeed = speed; tp->t_dispeed = tp->t_dospeed = speed; port = a0->a_port; .DE .DM /* * A port address of zero means a skipped entry in the table. * In this case a1->a_ut keeps its initial value of US_NONE. */ if (port) { dummy_port = port; .DE .DM /* * uart_sense() prints port info. * Do this four times per line. */ a1->a_ut = uart_sense(port); sense_ct++; if ((sense_ct & 1) == 0) putchar('\en'); else putchar('\et'); .DE .DM s = sphi(); outb(port+MCR, 0); outb(port+LCR, LC_DLAB); outb(port+DLL, albaud[speed]); outb(port+DLH, albaud[speed] >> 8); outb(port+LCR, LC_CS8); tp->t_start = asystart; /* leave tp->t_param at 0 */ tp->t_ddp = (char *) chan; spl(s); .DE .DM if (a0->a_irqno && a0->a_asy_gp == NO_ASYGP) add_irq (a0->a_irqno, asyintr, chan); } } .DE .DM if (sense_ct & 1) putchar('\en'); .DE .DM /* for each port group, add group to irq list */ for (g = 0 ; g < ASYGP_NUM ; g ++) add_irq (asy_gp [g].irq, ptbl [asy_gp [g].gp_type], g); .DE .DM /* Attach irq routines. */ for (irq = 0 ; irq < NUM_IRQ ; irq ++) { if (irq0 [irq]) setivec (irq, asy_irq); } } .DE .SH "The Unload Routine" .PP The kernel invokes function .B asyunload() when .B asy is unloaded from memory. As \*(CO 4.2 does not support loadable drivers, this function is never invoked. .PP Field .B c_uload in the .B CON structure contains a pointer to this function. .DM static void asyunload() { char chan, irq; .DE .DM /* * for each channel: * disable UART interrupts * hangup port * cancel timer */ for (chan = 0; chan < ASY_NUM; chan++) { asy0_t * a0 = asy0 + chan; asy1_t * a1 = asy1 + chan; short port = a0->a_port; TTY *tp = &a1->a_tty; .DE .DM outb(port+IER, 0); outb(port+MCR, 0); timeout (tp->t_rawtim, 0, NULL, 0); } .DE .DM /* for each irq, detach irq routine if one was attached */ for (irq = 0 ; irq < NUM_IRQ ; irq ++) if (irq0 [irq]) clrivec(irq); .DE .DM /* deallocate dynamic storage */ if (asy1) kfree (asy1); } .DE .SH "The Open Routine" .PP The kernel invokes function .B asyopen() when a user application invokes the system call .B open() to open a serial port. .PP Field .B c_open in the .B CON structure contains a pointer to this function. .DM static void asyopen(dev, mode) dev_t dev; int mode; { int s; char msr, mcr; char chan = channel(dev); asy0_t *a0 = asy0 + chan; asy1_t *a1 = asy1 + chan; TTY *tp = &a1->a_tty; short port = a0->a_port; .DE .DM /* chip not found */ if (a1->a_ut == US_NONE) { set_user_error (ENXIO); goto bad_open; } .DE .DM if ((tp->t_flags & T_EXCL) != 0 && ! super()) { set_user_error (ENODEV); goto bad_open; } .DE .DM /* Can't open for hardware flow control if modem status * interrupts are disallowed. */ if (a0->a_nms && (dev & CFLOW) != 0) { set_user_error (ENXIO); goto bad_open; } .DE .DM /* Can't open a polled port if another driver is using polling. */ if (dev & CPOLL && poll_owner & ~ POLL_ASY) { set_user_error (EBUSY); goto bad_open; } .DE .DM /* Can't have both com[13] or both com[24] IRQ at once. */ if (!(dev & CPOLL) && a0->a_ixc) { struct irqnode *np = irq1[a0->a_irqno]; while (np) { if (np->func != ptbl[0] || np->arg != chan) { set_user_error (EBUSY); goto bad_open; } np = np->next_actv; } } .DE .DM /* If port already in use, are new and old open modes compatible? */ if (a1->a_in_use) { int oldmode = 0, newmode = 0; /* mctl:1 irq:2 flow:4 */ .DE .DM if (a1->a_modc) oldmode += 1; if (a1->a_irq) oldmode += 2; if (a1->a_flc) oldmode += 4; if ((dev & NMODC) == 0) newmode += 1; if ((dev & CPOLL) == 0) newmode += 2; if (dev & CFLOW) newmode += 4; if (oldmode != newmode) { set_user_error (EBUSY); goto bad_open; } } .DE At this point, sleep if another process is opening or closing the port. This can happen if: .IP \(bu 0.3i Another process is trying a first open and awaiting CD. .IP \(bu 0.3i Another process is closing the port after losing CD. .IP \(bu 0.3i A remote process opened the port, spawned a daemon, and disconnected, yet the daemon ignored .B SIGHUP and is improperly keeping the port open. .PP Do not try to set .B tp->t_flags before this sleep! During the sleep, .B ttclose() may be called and clear the flags. .DM while (a1->a_in_use && (a1->a_hcls || ((dev & NMODC) == 0 && (inb (port + MSR) & MS_RLSD) == 0))) { .DE .DM if (x_sleep ((char *) & tp->t_open, pritty, slpriSigCatch, "asyblk") == PROCESS_SIGNALLED) { set_user_error (EINTR); goto bad_open; } } .DE .DM /* If channel not in use, mark it as such. */ if (a1->a_in_use == 0) { /* Save modes for this open attempt to avoid future conflicts. * Then start asycycle() for this port. */ if (dev & NMODC) { tp->t_flags &= ~T_MODC; a1->a_modc = 0; } else { tp->t_flags |= T_MODC; a1->a_modc = 1; } .DE .DM if (dev & CPOLL) a1->a_irq = 0; else a1->a_irq = 1; if (dev & CFLOW) { tp->t_flags |= T_CFLOW; a1->a_flc = 1; } else { tp->t_flags &= ~T_CFLOW; a1->a_flc = 0; } } a1->a_in_use++; .DE .DM /* From here, error exit is bad_open_u. */ if (tp->t_open == 0) { /* not already open */ silo_t * in_silo = &a1->a_in; .DE .DM if (!(dev & CPOLL)) { upd_irq1(a0->a_irqno); a1->a_has_irq = 1; } .DE .DM /* Need to start cycling to scan for CD. */ asycycle(chan); .DE .DM s = sphi(); /* Raise basic modem control lines even if modem * control hasn't been specified. * MC_OUT2 turns on NON-open-collector IRQ line from the UART. * since we can't have two UART's on same IRQ with MC_OUT2 on */ mcr = MC_RTS | MC_DTR; .DE .DM if (dev & CPOLL) { outb(port+MCR, mcr); } else { outb(port+MCR, mcr | a0->a_outs); outb(port+IER, IEN); } .DE .DM if ((dev & NMODC) == 0) { /* want modem control? */ tp->t_flags |= T_HOPEN | T_STOP; for (;;) { /* wait for carrier */ msr = inb(port+MSR); /* If carrier detect present * if port not already open * break out of loop and finish first open * else * do second (or third, etc.) open */ if (msr & MS_RLSD) break; .DE .DM /* wait for carrier */ if (x_sleep ((char *) & tp->t_open, pritty, slpriSigCatch, "need CD") == PROCESS_SIGNALLED) { outb(port + MCR, 0); outb(port + IER, 0); set_user_error (EINTR); tp->t_flags &= ~(T_HOPEN | T_STOP); spl(s); goto bad_open_u; } } .DE .DM /* Mark that we are no longer hanging in open. * Allow output over the port unless hardware flow * control says not to. */ tp->t_flags &= ~T_HOPEN; tp->t_flags &= ~T_STOP; if (!(tp->t_flags & T_CFLOW) || (msr & MS_CTS)) a1->a_ohlt = 0; else a1->a_ohlt = 1; .DE .DM /* Awaken any other opens on same device. */ wakeup((char *)(&tp->t_open)); } ttopen(tp); /* stty inits */ tp->t_flags |= T_CARR; if (ASY_HPCL) tp->t_flags |= T_HPCL; .DE .DM asyparam(tp); /* gimmick: do this while t_open is zero */ .DE .DM /* TO DO: flush UART input register(s) */ spl(s); .DE .DM /* Turn on polling for the port. */ if (dev & CPOLL) { a1->a_poll = 1; asyspr(); } } /* end of first-open case */ .DE .DM tp->t_open++; ttsetgrp(tp, dev, mode); return; .DE .DM bad_open_u: a1->a_in_use--; wakeup((char *)(&tp->t_open)); bad_open: return; } .DE .SH "The Close Routine" .PP The kernel invokes function .B asyclose() when a user application invokes the system call .B close() to close a serial port. .PP Field .B c_close in the .B CON structure contains a pointer to this function. .DM static void asyclose(dev, mode) dev_t dev; int mode; { int chan = channel(dev); asy0_t *a0 = asy0 + chan; asy1_t *a1 = asy1 + chan; TTY *tp = &a1->a_tty; silo_t *out_silo = &a1->a_out; silo_t *in_silo = &a1->a_in; int flags, maj; int s; short port = a0->a_port; char lsr; .DE .DM if (--tp->t_open) goto not_last_close; s = sphi(); .DE .DM a1->a_hcls = 1; /* disallow reopen till done closing */ flags = tp->t_flags; /* save flags - ttclose() zeroes them */ ttclose(tp); .DE .DM /* Wait for output silo and UART xmit buffer to empty. * Allow signal to break the sleep. */ for (;;) { int chipEmpty = 0, siloEmpty = 0; .DE .DM lsr = inb(port + LSR); chipEmpty = (lsr & LS_TxIDLE); siloEmpty = (out_silo->si_ix == out_silo->si_ox); .DE .DM if (chipEmpty && siloEmpty) break; need_wake[chan] |= NW_OUTSILO; if (x_sleep ((char *) out_silo, pritty, slpriSigCatch, "asyclose") == PROCESS_SIGNALLED) { RAWOUT_FLUSH(out_silo); break; } } need_wake[chan] &= ~NW_OUTSILO; .DE .DM /* If not hanging in open */ if ((flags & T_HOPEN) == 0) { /* Disable interrupts. */ outb(port+IER, 0); outb(port+MCR, inb(port+MCR) & ~MC_OUTS); } .DE .DM /* If hupcls */ if (flags & T_HPCL) { /* Hangup port - drop DTR and RTS. */ outb(port+MCR, inb(port+MCR) & MC_OUTS); .DE .DM /* Hold dtr low for timeout */ maj = major(dev); drvl[maj].d_time = 1; .DE .DM x_sleep ((char *) & drvl [maj].d_time, pritty, slpriNoSig, "drop DTR"); drvl[maj].d_time = 0; } .DE .DM a1->a_poll = 0; asyspr(); RAWIN_FLUSH(in_silo); a1->a_hcls = 0; /* allow reopen - done closing */ wakeup((char *)(&tp->t_open)); spl(s); a1->a_in_use--; .DE .DM if (!(dev & CPOLL)) upd_irq1(a0->a_irqno); return; .DE .DM not_last_close: a1->a_in_use--; wakeup((char *)(&tp->t_open)); return; } .DE .SH "The Read Routine" .PP The kernel invokes function .B asyread() when a user application invokes the system call .B read() to read data from a serial port. .PP Field .B c_read in the .B CON structure contains a pointer to this function. .DM static void asyread(dev, iop) dev_t dev; register IO * iop; { int chan = channel(dev); asy1_t *a1 = asy1 + chan; TTY *tp = &a1->a_tty; ttread(tp, iop); } .DE .SH "The Timeout Routine" .PP The kernel invokes function .B asytimer() when a timeout occurs. .PP Field .B c_timer in the .B CON structure contains a pointer to this function. .DM static void asytimer(dev) dev_t dev; { if (++drvl[major(dev)].d_time > DTRTMOUT) wakeup((char *)&drvl[major(dev)].d_time); } .DE .SH "The Write Routine" .PP The kernel invokes function .B asywrite() when a user application invokes the system call .B write() to write data to this port. .PP Field .B c_write in the .B CON structure contains a pointer to this function. .DM static void asywrite(dev, iop) dev_t dev; register IO * iop; { int chan = channel(dev); asy0_t *a0 = asy0 + chan; asy1_t *a1 = asy1 + chan; TTY *tp = &a1->a_tty; short port = a0->a_port; register int c; .DE .DM /* Treat user writes through tty driver. */ if (iop->io_seg != IOSYS) { ttwrite(tp, iop); return; } .DE .DM /* Treat kernel writes by blocking on transmit buffer. */ while ((c = iogetc(iop)) >= 0) { /* Wait until transmit buffer is empty. * Check twice to prevent critical race with interrupt handler. */ for (;;) { if (inb(port+LSR) & LS_TxRDY) if (inb(port+LSR) & LS_TxRDY) break; } .DE .DM /* Output the next character. */ outb(port+DREG, c); } } .DE .SH "The ioctl Routine" .PP The kernel invokes function .B asyioctl() when a user application invokes the system call .B ioctl() to manipulate a serial device. .PP Field .B c_open in the .B CON structure contains a pointer to this function. .DM static void asyioctl(dev, com, vec) dev_t dev; int com; struct sgttyb *vec; { int chan = channel(dev); asy0_t *a0 = asy0 + chan; asy1_t *a1 = asy1 + chan; TTY *tp = &a1->a_tty; int s; int temp; silo_t *out_silo = &a1->a_out; silo_t *in_silo = &a1->a_in; short port = a0->a_port; unsigned char msr, mcr, lcr, ier; char do_ttioctl = 0; char do_asyparam = 0; .DE .DM s = sphi(); ier = inb(port+IER); mcr = inb(port+MCR); /* get current MCR register status */ lcr = inb(port+LCR); /* get current LCR register status */ .DE .DM /* If command will drain output, do the drain now * before calling ttioctl(). * Don't do this for 286 kernel: we're running out of code space. */ switch(com) { .DE .DM case TCSETAW: case TCSETAF: case TCSBRK: case TIOCSETP: /* Wait for output silo and UART xmit buffer to empty. * Allow signal to break the sleep. */ for (;;) { if (! ttoutp (tp) && out_silo->si_ix == out_silo->si_ox && (inb (port + LSR) & LS_TxIDLE) != 0) break; need_wake[chan] |= NW_OUTSILO; .DE .DM if (x_sleep ((char *) out_silo, pritty, slpriSigCatch, "asydrain") == PROCESS_SIGNALLED) break; } need_wake [chan] &= ~NW_OUTSILO; } .DE .DM switch(com) { case TIOCSBRK: /* set BREAK */ outb (port + LCR, lcr | LC_SBRK); break; .DE .DM case TIOCCBRK: /* clear BREAK */ outb (port + LCR, lcr & ~ LC_SBRK); break; .DE .DM case TIOCSDTR: /* set DTR */ outb (port + MCR, mcr | MC_DTR); break; .DE .DM case TIOCCDTR: /* clear DTR */ outb (port + MCR, mcr & ~ MC_DTR); break; .DE .DM case TIOCSRTS: /* set RTS */ outb (port + MCR, mcr | MC_RTS); break; .DE .DM case TIOCCRTS: /* clear RTS */ outb (port + MCR, mcr & ~ MC_RTS); break; .DE .DM case TIOCRSPEED: /* set "raw" I/O speed divisor */ outb (port + LCR, lcr | LC_DLAB); /* set speed latch bit */ outb (port + DLL, (unsigned) vec); outb (port + DLH, (unsigned) vec >> 8); outb (port + LCR, lcr); /* reset latch bit */ break; .DE .DM case TIOCWORDL: /* set word length and stop bits */ outb (port + LCR, ((lcr & ~ 0x7) | ((unsigned) vec & 0x7))); break; .DE .DM case TIOCRMSR: /* get CTS/DSR/RI/RLSD (MSR) */ msr = inb (port + MSR); temp = msr >> 4; kucopy (& temp, (unsigned *) vec, sizeof (unsigned)); break; .DE .DM case TIOCFLUSH: /* Flush silos here, queues in tty.c */ RAWIN_FLUSH (in_silo); RAWOUT_FLUSH (out_silo); do_ttioctl = 1; break; .DE .DM /* If port parameters change, plan to call asyparam(). * Need to check now before structs are updated. */ case TCSETA: case TCSETAW: case TCSETAF: { struct termio trm; .DE .DM ukcopy (vec, & trm, sizeof (struct termio)); if (trm.c_cflag != tp->t_termio.c_cflag) do_asyparam = 1; } do_ttioctl = 1; break; .DE .DM case TIOCSETP: case TIOCSETN: { struct sgttyb sg; .DE .DM ukcopy(vec, &sg, sizeof(struct sgttyb)); if (sg.sg_ispeed != tp->t_sgttyb.sg_ispeed || ((sg.sg_flags ^ tp->t_sgttyb.sg_flags) & ANYP) != 0) do_asyparam = 1; } do_ttioctl = 1; break; .DE .DM default: do_ttioctl = 1; } .DE .DM outb (port + IER, ier); if (do_ttioctl) ttioctl (tp, com, vec); spl (s); if (do_asyparam) asyparam (tp); .DE .DM /* Things to be done after calling ttioctl(). */ switch(com) { case TCSBRK: /* Send 0.25 second break: * 1. Turn on break level. * 2. Set timer to turn off break level 0.25 sec later. * 3. Sleep till timer expires. * 4. Turn off break level. */ outb (port + LCR, lcr | LC_SBRK); a1->a_brk = 1; timeout (& tp->t_sbrk, HZ / 4, endbrk, chan); .DE .DM while (a1->a_brk) x_sleep (a1, pritty, slpriNoSig, "asybreak"); .DE .DM outb (port + LCR, lcr & ~ LC_SBRK); } } .DE .SH "Turn Off the Break Level" .PP Function .B endbrk() turns off the break level. Called from a timeout after the function .BR "ioctl(fd, TCSBRK, 0)" . .DM void endbrk(chan) int chan; { asy1_t *a1 = asy1 + chan; a1->a_brk = 0; wakeup (a1); } .DE .SH "Read Parameters" .PP Function .B asyparam() reads parameters from the port. .DM static void asyparam(tp) TTY * tp; { int chan = (int)tp->t_ddp; asy0_t *a0 = asy0 + chan; asy1_t *a1 = asy1 + chan; short port = a0->a_port; int s; int write_baud=1, write_lcr=1; unsigned char mcr, newlcr, speed, oldSpeed; unsigned short cflag = tp->t_termio.c_cflag; .DE .DM speed = cflag & CBAUD; switch (cflag & CSIZE) { case CS5: newlcr = LC_CS5; break; case CS6: newlcr = LC_CS6; break; case CS7: newlcr = LC_CS7; break; case CS8: newlcr = LC_CS8; break; } .DE .DM if (cflag & CSTOPB) newlcr |= LC_STOPB; if (cflag & PARENB) { newlcr |= LC_PARENB; if ((cflag & PARODD) == 0) newlcr |= LC_PAREVEN; } .DE .DM /* Don't bang on the UART needlessly. * Writing baud rate resets the port, which loses characters. * You want this on first open, NOT on later opens. */ oldSpeed = a0->a_speed; .DE .DM if (speed == oldSpeed && tp->t_open) { write_baud = 0; if (newlcr == a1->a_lcr) { write_lcr = 0; } } a0->a_speed = speed; a1->a_lcr = newlcr; .DE .DM if (write_lcr) { char ier_save; s = sphi(); ier_save = inb(port+IER); .DE .DM if (write_baud) { if (speed) { short divisor = albaud [speed]; .DE .DM if (oldSpeed == 0) { /* if previous baud rate was zero, * need to go off hook. */ mcr = inb(port+MCR) | (MC_RTS | MC_DTR); outb(port+MCR, mcr); } .DE .DM outb(port+LCR, LC_DLAB); outb(port+DLL, divisor); outb(port+DLH, divisor >> 8); } else { /* Baud rate of zero means hang up. */ mcr = inb(port+MCR) & ~(MC_RTS | MC_DTR); outb(port+MCR, mcr); } } .DE .DM outb(port+LCR, newlcr); if (a1->a_ut == US_16550A) outb(port+FCR, FC_ENABLE | FC_Rx_RST | FC_Rx_08); outb(port+IER, ier_save); spl(s); } .DE .DM if (write_baud) asyspr (); } .DE .SH "Start Processing" .PP Function .B asystart() starts processing of data. .DM static void asystart(tp) TTY * tp; { int chan = (int)tp->t_ddp; asy0_t *a0 = asy0 + chan; asy1_t *a1 = asy1 + chan; short port = a0->a_port; int s; int need_xmit = 1; /* True if should start sending data now. */ silo_t *out_silo = &a1->a_out; char lsr; .DE .DM /* Read line status register AFTER disabling interrupts. */ s = sphi (); lsr = inb (port + LSR); .DE .DM /* Process break indication. * NOTE: Break indication cleared when line status register was read. */ if (lsr & LS_BREAK) defer (asybreak, chan); .DE .DM /* If no output data, it may be time to finish closing the port; * but won't need another xmit interrupt. */ if (out_silo->si_ix == out_silo->si_ox) { if (need_wake[chan] & NW_OUTSILO) { need_wake[chan] &= ~NW_OUTSILO; wakeup((char *)out_silo); } need_xmit = 0; } .DE .DM /* Do nothing if output is stopped. */ if (tp->t_flags & T_STOP) need_xmit = 0; if (a1->a_ohlt) need_xmit = 0; .DE .DM /* Start data transmission by writing to UART xmit reg. */ if ((lsr & LS_TxRDY) && need_xmit) { int xmit_count; xmit_count = (a1->a_ut == US_16550A)?16:1; asy_send(out_silo, port+DREG, xmit_count); } spl(s); } .DE .SH "The Poll Routine" .PP The kernel invokes function .B asypoll() when a user application invokes the system call .B poll() to poll a serial port. .PP Field .B c_poll in the .B CON structure contains a pointer to this function. .DM static int asypoll(dev, ev, msec) dev_t dev; int ev; int msec; { int chan = channel(dev); asy1_t *a1 = asy1 + chan; TTY *tp = & a1->a_tty; return ttpoll(tp, ev, msec); } .DE .SH "Wake Up Sleeping Devices" .PP Function .B asycycle() wakes up of any sleeping ports at regular intervals. .DM static void asycycle(chan) int chan; { asy0_t *a0 = asy0 + chan; asy1_t *a1 = asy1 + chan; TTY *tp = &a1->a_tty; short port = a0->a_port; int s; char msr, mcr; silo_t *out_silo = &a1->a_out; silo_t *in_silo = &a1->a_in; int n, ch; int do_start = 1; unsigned char iir; .DE .DM /* Check Carrier Detect (RLSD). * Modem status interrupts were not enabled due to 8250 hardware bug. * Enabling modem status and receive interrupts may cause lockup * on older parts. */ if (tp->t_flags & T_MODC) { /* Get status */ msr = inb(port+MSR); .DE .DM /* Carrier changed. */ if ((msr & MS_RLSD) && !(tp->t_flags & T_CARR)) { /* Carrier is on - wakeup open. */ s = sphi(); tp->t_flags |= T_CARR; spl(s); wakeup((char *)(&tp->t_open)); } .DE .DM if (!(msr & MS_RLSD) && (tp->t_flags & T_CARR)) { s = sphi(); RAWIN_FLUSH(in_silo); RAWOUT_FLUSH(out_silo); tp->t_flags &= ~T_CARR; spl(s); tthup(tp); } } .DE .DM /* Empty raw input buffer. * The line discipline module (tty.c) will set T_ISTOP true when the * tt input queue is nearly full (tp->t_iq.cq_cc >= IHILIM), and make * T_ISTOP false when it's ready for more input. * When T_ISTOP is true, ttin() simply discards the character passed. */ if (!(tp->t_flags & T_ISTOP)) { while (in_silo->SILO_CHAR_COUNT > 0) { s = sphi(); ttin(tp, in_silo->si_buf[in_silo->si_ox]); if (in_silo->si_ox < MAX_SILO_INDEX) in_silo->si_ox++; else in_silo->si_ox = 0; in_silo->SILO_CHAR_COUNT--; spl(s); } } .DE .DM /* Hardware flow control. * Check CTS to see if we need to halt output. * (MS_INTR should have done this - repeat code here to be sure) * Check input silo to see if we need to raise RTS. */ if (tp->t_flags & T_CFLOW) { /* Get status */ msr = inb(port+MSR); s = sphi(); if (msr & MS_CTS) a1->a_ohlt = 0; else a1->a_ohlt = 1; spl(s); .DE .DM /* If using hardware flow control, see if we need to drop RTS. */ if ((tp->t_flags & T_CFLOW) && (in_silo->SILO_CHAR_COUNT > SILO_HIGH_MARK)) { s = sphi(); mcr = inb(port+MCR); if (mcr & MC_RTS) { outb(port+MCR, mcr & ~MC_RTS); } spl(s); } .DE .DM /* If input silo below low mark, assert RTS */ if (in_silo->SILO_CHAR_COUNT <= SILO_LOW_MARK) { s = sphi(); mcr = inb(port+MCR); .DE .DM if ((mcr & MC_RTS) == 0) { outb(port+MCR, mcr | MC_RTS); } spl(s); } } .DE .DM /* Calculate free output slot count. */ n = sizeof(out_silo->si_buf) - 1; n += out_silo->si_ox - out_silo->si_ix; n %= sizeof(out_silo->si_buf); .DE .DM /* Fill raw output buffer */ for (;;) { if (--n < 0) break; s = sphi(); ch = ttout(tp); spl(s); if (ch < 0) break; .DE .DM s = sphi(); out_silo->si_buf[out_silo->si_ix] = ch; if (out_silo->si_ix >= sizeof(out_silo->si_buf) - 1) out_silo->si_ix = 0; else out_silo->si_ix++; spl(s); } .DE .DM /* if port has an interrupt pending (probably missed an irq) * the following two loops should not be merged * - need ALL port irq's inactive at once * for each port on this irq line (use irq1 for this) * disable interrupts (clear IER) * for each port on this irq line * restore interrupts */ if (a1->a_has_irq && ((iir = inb (port + IIR)) & 1) == 0) { struct irqnode *ip; asy_gp_t *gp; int s; short p; char c, slot; .DE .DM do_start = 0; s = sphi (); ip = irq1 [a0->a_irqno]; .DE .DM while(ip) { if (ip->func == asyintr) { p = ip->arg; outb (p + IER, 0); } else { gp = asy_gp + ip->arg; for (slot = 0; slot < MAX_SLOTS; slot++) { if ((c = gp->chan_list [slot]) < MAX_ASY) { p = asy0 [c].a_port; outb (p + IER, 0); } } } ip = ip->next_actv; } .DE .DM /* Now, all ports on the offending irq line have irq off. */ ip = irq1 [a0->a_irqno]; while (ip) { if (ip->func == asyintr) { p = ip->arg; outb (p + IER, IEN); } else { gp = asy_gp + ip->arg; for (slot = 0; slot < MAX_SLOTS; slot++) { if ((c = gp->chan_list [slot]) < MAX_ASY){ p = asy0 [c].a_port; outb (p + IER, IEN); } } } ip = ip->next_actv; } spl (s); } .DE .DM if (do_start) ttstart (tp); .DE .DM /* Schedule next cycle. */ if (a1->a_in_use) timeout (& tp->t_rawtim, HZ / 10, asycycle, chan); } .DE .SH "Suppress Interrupts During Chip Sensing" .PP Function .B irqdummy() suppresses interrupts that may occur during chip sensing. .DM static void irqdummy() { /* Try to clear all pending interrupts. */ inb(dummy_port+IIR); inb(dummy_port+LSR); inb(dummy_port+MSR); inb(dummy_port+DREG); } .DE .SH "Add a Port Information to IRQ0 List" .PP Function .B add_irq() adds information about a port to the .B irq0 list. .DM static void add_irq(irq, func, arg) int irq; int (*func)(); int arg; { struct irqnode * np; .DE .DM /* Sanity check */ if (irq <= 0 || irq >= NUM_IRQ) return; .DE .DM if (nextnode < MAX_ASY) { np = nodespace + nextnode++; np->func = func; np->arg = arg; np->next = irq0[irq]; irq0[irq] = np; } else { printf("asy: too many irq nodes (%d)\en", nextnode); } } .DE .SH "Service an Interrupt" .PP Function .B asy_irq() services an async interrupt. .DM static void asy_irq (level) int level; { struct irqnode *ip = irq1 [level]; int doit; .DE .DM do { struct irqnode * here = ip; .DE .DM doit = 0; .DE .DM while (here != NULL) { doit |= (* here->func) (here->arg); here = here->next_actv; } } while (doit); } .DE .SH "Rebuild Links for Active Devices" .PP Function .B upd_irq1() rebuild the links for active devices. .DM static void upd_irq1(irq) int irq; { struct irqnode *np; asy1_t *a1; int chan; int s; .DE .DM /* Sanity check */ if (irq <= 0 || irq >= NUM_IRQ) return; .DE .DM /* For each node in the irq0 list * if node is for irq status port * for each channel using the status port * if channel in use, in irq mode * add node to irq1 list * skip rest of channels for this node * else - node is for simple UART * if channel in use, in irq mode * add node to irq1 list */ .DE .DM s = sphi(); np = irq0[irq]; irq1[irq] = 0; while (np) { if (np->func != asyintr) { char ix, loop = 1; asy_gp_t *gp = asy_gp + np->arg; .DE .DM for (ix = 0; ix < MAX_SLOTS && loop; ix++) { if ((chan = gp->chan_list[ix]) < MAX_ASY) { a1 = asy1 + chan; if (a1->a_in_use && a1->a_irq) { np->next_actv = irq1[irq]; irq1[irq] = np; loop = 0; } } } .DE .DM } else { a1 = asy1 + np->arg; if (a1->a_in_use && a1->a_irq) { np->next_actv = irq1[irq]; irq1[irq] = np; } } np = np->next; } spl(s); } .DE .SH "The Break Routine" .PP Function .B asybreak() breaks connection with a port. .DM static void asybreak(chan) int chan; { int s; asy1_t *a1 = asy1 + chan; silo_t *out_silo = &a1->a_out; silo_t *in_silo = &a1->a_in; TTY *tp = &a1->a_tty; .DE .DM s = sphi(); RAWIN_FLUSH(in_silo); RAWOUT_FLUSH(out_silo); spl(s); ttsignal(tp, SIGINT); } .DE .SH "Handle an Interrupt" .PP Function .B asyintr() handles an interrupt for a single channel. .DM static int asyintr(chan) int chan; { asy0_t *a0 = asy0 + chan; asy1_t *a1 = asy1 + chan; TTY *tp = &a1->a_tty; silo_t *out_silo = &a1->a_out; silo_t *in_silo = &a1->a_in; int c, xmit_count; int ret = 0; short port = a0->a_port; unsigned char msr, lsr; .DE .DM if (chan >= MAX_ASY) { printf("asy: irq on channel %d\en", chan); return 0; } .DE .DM rescan: switch (inb(port+IIR) & 0x07) { case LS_INTR: ret = 1; lsr = inb(port + LSR); if (lsr & LS_BREAK) defer(asybreak, chan); goto rescan; .DE .DM case Rx_INTR: ret = 1; c = inb(port+DREG); if (tp->t_open == 0) goto rescan; .DE .DM /* Must recognize XOFF quickly to avoid transmit overrun. * Recognize XON here as well to avoid race conditions. */ if (_IS_IXON_MODE (tp)) { /* XON */ if (_IS_START_CHAR (tp, c) || (_IS_IXANY_MODE (tp) && (tp->t_flags & T_STOP) != 0)) { tp->t_flags &= ~(T_STOP | T_XSTOP); goto rescan; } .DE .DM /* XOFF */ if (_IS_STOP_CHAR (tp, c)) { tp->t_flags |= T_STOP; goto rescan; } } .DE .DM /* Save char in raw input buffer. */ if (in_silo->SILO_CHAR_COUNT < MAX_SILO_CHARS) { in_silo->si_buf[in_silo->si_ix] = c; if (in_silo->si_ix < MAX_SILO_INDEX) in_silo->si_ix ++; else in_silo->si_ix = 0; in_silo->SILO_CHAR_COUNT ++; } .DE .DM /* If using hardware flow control, see if we need to drop RTS. */ if ((tp->t_flags & T_CFLOW) != 0 && in_silo->SILO_CHAR_COUNT > SILO_HIGH_MARK) { unsigned char mcr = inb (port + MCR); if (mcr & MC_RTS) { outb(port+MCR, mcr & ~MC_RTS); } } goto rescan; .DE .DM case Tx_INTR: ret = 1; /* Do nothing if output is stopped. */ if (tp->t_flags & T_STOP) { goto rescan; } if (a1->a_ohlt) goto rescan; .DE .DM /* Transmit next char in raw output buffer. */ xmit_count = (a1->a_ut == US_16550A)?16:1; asy_send(out_silo, port+DREG, xmit_count); goto rescan; .DE .DM case MS_INTR: ret = 1; /* Get status (and clear interrupt). */ msr = inb(port+MSR); .DE .DM /* Hardware flow control. * Check CTS to see if we need to halt output. */ if (tp->t_flags & T_CFLOW) { if (msr & MS_CTS) a1->a_ohlt = 0; else a1->a_ohlt = 1; } goto rescan; .DE .DM default: return ret; } /* endswitch */ } .DE .SH "Handle Timer Interrupts" .PP Function .B asyclk() is called every time .B T0 interrupts. If it returns zero, .B asy performs the usual system timer routines. It polls all pollable ports. .DM static int asyclk() { static int count; int ix; .DE .DM for (ix = 0; ix < ppnum; ix++) asysph(pptbl[ix]); count++; if (count >= poll_divisor) count = 0; return count; } .DE .SH "Set Polling Rate on a Port" .PP Function .B asyspr() sets the polling rate on a port. .B asy calls it when a port is opened, closed, or changes speed. It sets the polling rate only as fast as needed, and shuts off polling whenever possible. It updates the links in .BR irq1[0] , which lists the polled-mode ports. .DM static void asyspr() { asy0_t *a0; asy1_t *a1; int chan; int s; int ix, max_rate, port_rate; .DE .DM /* Rebuild table of pollable ports. */ s = sphi(); ppnum = 0; for (chan = 0; chan < ASY_NUM; chan++) { a1 = asy1 + chan; if (a1->a_poll) pptbl[ppnum++] = chan; } spl(s); .DE .DM /* If another driver has the polling clock, do nothing. */ if (poll_owner & ~ POLL_ASY) return; .DE .DM /* Find highest valid polling rate in units of HZ/10. * If using FIFO chip, can poll at 1/16 the usual rate. */ max_rate = 0; for (ix = 0; ix < ppnum; ix++) { chan = pptbl[ix]; a0 = asy0 + chan; a1 = asy1 + chan; port_rate = alp_rate[a0->a_speed]; if (a1->a_ut == US_16550A) { port_rate /= 16; if (port_rate % HZ) port_rate += HZ - (port_rate % HZ); } .DE .DM if (max_rate < port_rate) max_rate = port_rate; } .DE .DM /* if max_rate is not current rate, adjust the system clock */ if (max_rate != poll_rate) { poll_rate = max_rate; poll_divisor = poll_rate/HZ; /* used in asyclk() */ altclk_out(); /* stop previous polling */ poll_owner &= ~ POLL_ASY; .DE .DM if (poll_rate) { /* resume polling at new rate if needed */ poll_owner |= POLL_ASY; altclk_in(poll_rate, asyclk); } } } .DE .SH "Handle Polling" .PP Function .B asysph() handles the polling of serial ports. .DM static void asysph(chan) int chan; { asy0_t *a0 = asy0 + chan; asy1_t *a1 = asy1 + chan; TTY *tp = &a1->a_tty; silo_t *out_silo = &a1->a_out; silo_t *in_silo = &a1->a_in; int c, xmit_count; short port = a0->a_port; char lsr; .DE .DM /* Check for received break first. * This status is wiped out on reading the LSR. */ lsr = inb(port + LSR); if (lsr & LS_BREAK) defer(asybreak, chan); .DE .DM /* Handle all incoming characters. */ for (;;) { lsr = inb(port + LSR); if ((lsr & LS_RxRDY) == 0) break; c = inb(port+DREG); if (tp->t_open == 0) continue; .DE .DM /* Must recognize XOFF quickly to avoid transmit overrun. * Recognize XON here as well to avoid race conditions. */ if (_IS_IXON_MODE (tp)) { /* XOFF */ if (_IS_STOP_CHAR (tp, c)) { tp->t_flags |= T_STOP; continue; } .DE .DM /* XON */ if (_IS_START_CHAR (tp, c)) { tp->t_flags &= ~T_STOP; continue; } } .DE .DM /* Save char in raw input buffer. */ if (in_silo->SILO_CHAR_COUNT < MAX_SILO_CHARS) { in_silo->si_buf[in_silo->si_ix] = c; if (in_silo->si_ix < MAX_SILO_INDEX) in_silo->si_ix++; else in_silo->si_ix = 0; in_silo->SILO_CHAR_COUNT++; } .DE .DM /* If using hardware flow control, see if we need to drop RTS. */ if ((tp->t_flags & T_CFLOW) && (in_silo->SILO_CHAR_COUNT > SILO_HIGH_MARK)) { unsigned char mcr = inb(port+MCR); if (mcr & MC_RTS) { outb(port+MCR, mcr & ~MC_RTS); } } } .DE .DM /* Handle outgoing characters. Do nothing if output is stopped. */ lsr = inb(port + LSR); if ((lsr & LS_TxRDY) && !(tp->t_flags & T_STOP) && !(a1->a_ohlt)) { /* Transmit next char in raw output buffer. */ xmit_count = (a1->a_ut == US_16550A)?16:1; asy_send(out_silo, port+DREG, xmit_count); } .DE .DM /* Hardware flow control. * Check CTS to see if we need to halt output. */ if (tp->t_flags & T_CFLOW) { if (inb(port+MSR) & MS_CTS) a1->a_ohlt = 0; else a1->a_ohlt = 1; } } .DE .SH "Write to UART" .PP Function .B asy_send() write to the .B xmit data register of the UART. Assume all checking about whether it's time to send has been done already. This function is called by time-critical IRQ and polling routines! .PP Argument .I rawout is the output silo for the TTY structure that supplies data to the port. .I dreg is the I/O address of the UART .B xmit data register. .I xmit_count is the maximum number of characters we can write (16 for FIFO parts). .DM static int asy_send(rawout, dreg, xmit_count) register silo_t *rawout; int dreg, xmit_count; { /* Transmit next chars in raw output buffer. */ for (;(rawout->si_ix != rawout->si_ox) && xmit_count; xmit_count--) { outb(dreg, rawout->si_buf[rawout->si_ox]); /* Adjust raw output buffer output index. */ if (++rawout->si_ox >= sizeof(rawout->si_buf)) rawout->si_ox = 0; } return xmit_count; } .DE .SH "Interrupt Handler for Comtrol-Type Port Groups" .PP Function .B p1() is the interrupt handler for Comtrol-type port groups. The status register has one in bit positions for interrupting ports. .DM static int p1(g) int g; { asy_gp_t *gp = asy_gp + g; short port = gp->stat_port; unsigned char status, index, chan; int safety = LOOP_LIMIT; int ret = 0; .DE .DM /* while any port is active * call simple interrupt handler for active channel */ while (status = inb(port)) { ret = 1; index = 0; if (status & 0xf0) { status &= 0xf0; index +=4; } else status &= 0x0f; .DE .DM if (status & 0xcc) { status &= 0xcc; index +=2; } else status &= 0x33; .DE .DM if (status & 0xaa) index++; chan = gp->chan_list[index]; asyintr(chan); .DE .DM if (safety-- == 0) { printf("asy: p1 runaway - status %x\en", status); break; } } return ret; } .DE .SH "Interrupt Handler for Arnet-Type Port Groups" .PP Function .B p2() is the interrupt handler for Arnet-type port groups. The status register has zero in bit positions for interrupting ports. .DM static int p2(g) int g; { asy_gp_t *gp = asy_gp + g; short port = gp->stat_port; unsigned char status, index, chan; int safety = LOOP_LIMIT; int ret = 0; .DE .DM /* while any port is active * call simple interrupt handler for active channel */ while (status = ~inb(port)) { ret = 1; index = 0; if (status & 0xf0) { status &= 0xf0; index +=4; } else status &= 0x0f; .DE .DM if (status & 0xcc) { status &= 0xcc; index +=2; } else status &= 0x33; .DE .DM if (status & 0xaa) index++; chan = gp->chan_list[index]; asyintr(chan); if (safety-- == 0) { printf("asy: p2 runaway - status %x\en", status); break; } } return ret; } .DE .SH "Interrupt Handler for GTEK-Type Port Groups" .PP Function .B p3() is the interrupt handler for GTEK-type port groups. .DM static int p3(g) int g; { asy_gp_t *gp = asy_gp + g; short port = gp->stat_port; unsigned char index, chan; .DE .DM /* Call simple interrupt handler for active channel. */ index = inb(port) & 7; chan = gp->chan_list[index]; return asyintr(chan); } .DE .SH "Interrupt Handler for DigiBoard-Type Port Groups" .PP Function .B p4() is the interrupt handler for DigiBoard-type port groups. .DM static int p4(g) int g; { asy_gp_t *gp = asy_gp + g; short port = gp->stat_port; unsigned char index, chan; int ret = 0; int safety = LOOP_LIMIT; .DE .DM /* Status register has slot number for active port, * or 0xFF if no port is active. */ for (;;) { index = inb(port); if (index == 0xFF) break; .DE .DM if (safety-- == 0) { printf("asy: p4 runaway - status %x\en", index); break; } .DE .DM ret = 1; chan = gp->chan_list[index&0xF]; asyintr(chan); } return ret; } .DE .SH "The CON Structure" .PP Finally, the .B CON structure holds pointers to the driver's functions that are invoked by the kernel. .DM .ta 0.5i 2.5i CON asycon = { DFCHR|DFPOL, /* Flags */ ASY_MAJOR, /* Major index */ asyopen, /* Open */ asyclose, /* Close */ NULL, /* Block */ asyread, /* Read */ asywrite, /* Write */ asyioctl, /* Ioctl */ NULL, /* Powerfail */ asytimer, /* Timeout */ asyload, /* Load */ asyunload, /* Unload */ asypoll /* Poll */ }; .DE .SH "Where To Go From Here" .PP The Lexicon describes the functions invoked within this driver. The previous section gives an example of a driver for a block device.
function linpack_d_test18 ( ) %*****************************************************************************80 % %% TEST18 tests DPOFA and DPOSL. % % Discussion: % % DPOFA factors a positive definite symmetric matrix, % and DPOSL can solve a factored linear system. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 25 June 2009 % % Author: % % John Burkardt % n = 20; lda = n; fprintf ( 1, '\n' ); fprintf ( 1, 'TEST18\n' ); fprintf ( 1, ' For a positive definite symmetric matrix,\n' ); fprintf ( 1, ' DPOFA computes the LU factors.\n' ); fprintf ( 1, ' DPOSL solves a factored linear system.\n' ); fprintf ( 1, ' The matrix size is N = %d\n', n ); % % Set the matrix A. % a(1:n,1:n) = 0.0; for i = 1 : n a(i,i) = 2.0; if ( 1 < i ) a(i,i-1) = -1.0; end if ( i < n ) a(i,i+1) = -1.0; end end % % Set the right hand side. % x = zeros ( n, 1 ); for i = 1 : n x(i) = i; end b(1:n) = a(1:n,1:n) * x(1:n); % % Factor the matrix. % fprintf ( 1, '\n' ); fprintf ( 1, ' Factor the matrix.\n' ); [ a, info ] = dpofa ( a, lda, n ); if ( info ~= 0 ) fprintf ( 1, '\n' ); fprintf ( 1, ' Error, DPOFA returns INFO = %d\n', info ); return end % % Solve the linear system. % fprintf ( 1, '\n' ); fprintf ( 1, ' Solve the linear system.\n' ); b = dposl ( a, lda, n, b ); % % Print the result. % fprintf ( 1, '\n' ); fprintf ( 1, ' The first and last five entries of the solution:\n' ); fprintf ( 1, ' (Should be 1,2,3,4,5,...,n-1,n.)\n' ); fprintf ( 1, '\n' ); for i = 1 : n if ( i <= 5 | n-5 < i ) fprintf ( 1, ' %6d %14f\n', i, b(i) ); end if ( i == 5 ) fprintf ( 1, ' ...... ..............\n' ); end end return end
A probable source of the tale is Petrus Alfonsi 's Disciplina <unk> , which has the same three motifs : the rash promise of the husbandman ; the wolf mistaking the moon for cheese ; and the wolf that descends into the well via a bucket , thereby trapping himself and freeing the fox . However , the discussion of legality and the questioning of language that take place alongside these motifs are entirely Henryson 's invention . Whereas the moral of Alfonsi 's tale explains that the wolf lost both the oxen and the cheese because he " relinquished what was present for what was to come " ( Latin : pro <unk> quod <unk> erat dimisit ) , Henryson 's moralitas more fully involves the husbandman .
[STATEMENT] lemma exists_path_component_of_superset: assumes S: "path_connectedin X S" and ne: "topspace X \<noteq> {}" obtains C where "C \<in> path_components_of X" "S \<subseteq> C" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>C. \<lbrakk>C \<in> path_components_of X; S \<subseteq> C\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] proof (cases "S = {}") [PROOF STATE] proof (state) goal (2 subgoals): 1. \<lbrakk>\<And>C. \<lbrakk>C \<in> path_components_of X; S \<subseteq> C\<rbrakk> \<Longrightarrow> thesis; S = {}\<rbrakk> \<Longrightarrow> thesis 2. \<lbrakk>\<And>C. \<lbrakk>C \<in> path_components_of X; S \<subseteq> C\<rbrakk> \<Longrightarrow> thesis; S \<noteq> {}\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] case True [PROOF STATE] proof (state) this: S = {} goal (2 subgoals): 1. \<lbrakk>\<And>C. \<lbrakk>C \<in> path_components_of X; S \<subseteq> C\<rbrakk> \<Longrightarrow> thesis; S = {}\<rbrakk> \<Longrightarrow> thesis 2. \<lbrakk>\<And>C. \<lbrakk>C \<in> path_components_of X; S \<subseteq> C\<rbrakk> \<Longrightarrow> thesis; S \<noteq> {}\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] then [PROOF STATE] proof (chain) picking this: S = {} [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: S = {} goal (1 subgoal): 1. thesis [PROOF STEP] using ne path_components_of_eq_empty that [PROOF STATE] proof (prove) using this: S = {} topspace X \<noteq> {} (path_components_of ?X = {}) = (topspace ?X = {}) \<lbrakk>?C \<in> path_components_of X; S \<subseteq> ?C\<rbrakk> \<Longrightarrow> thesis goal (1 subgoal): 1. thesis [PROOF STEP] by fastforce [PROOF STATE] proof (state) this: thesis goal (1 subgoal): 1. \<lbrakk>\<And>C. \<lbrakk>C \<in> path_components_of X; S \<subseteq> C\<rbrakk> \<Longrightarrow> thesis; S \<noteq> {}\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<lbrakk>\<And>C. \<lbrakk>C \<in> path_components_of X; S \<subseteq> C\<rbrakk> \<Longrightarrow> thesis; S \<noteq> {}\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] case False [PROOF STATE] proof (state) this: S \<noteq> {} goal (1 subgoal): 1. \<lbrakk>\<And>C. \<lbrakk>C \<in> path_components_of X; S \<subseteq> C\<rbrakk> \<Longrightarrow> thesis; S \<noteq> {}\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] then [PROOF STATE] proof (chain) picking this: S \<noteq> {} [PROOF STEP] obtain a where "a \<in> S" [PROOF STATE] proof (prove) using this: S \<noteq> {} goal (1 subgoal): 1. (\<And>a. a \<in> S \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: a \<in> S goal (1 subgoal): 1. \<lbrakk>\<And>C. \<lbrakk>C \<in> path_components_of X; S \<subseteq> C\<rbrakk> \<Longrightarrow> thesis; S \<noteq> {}\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. thesis [PROOF STEP] proof [PROOF STATE] proof (state) goal (2 subgoals): 1. ?C \<in> path_components_of X 2. S \<subseteq> ?C [PROOF STEP] show "Collect (path_component_of X a) \<in> path_components_of X" [PROOF STATE] proof (prove) goal (1 subgoal): 1. path_component_of_set X a \<in> path_components_of X [PROOF STEP] by (meson \<open>a \<in> S\<close> S subsetD path_component_in_path_components_of path_connectedin_subset_topspace) [PROOF STATE] proof (state) this: path_component_of_set X a \<in> path_components_of X goal (1 subgoal): 1. S \<subseteq> path_component_of_set X a [PROOF STEP] show "S \<subseteq> Collect (path_component_of X a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. S \<subseteq> path_component_of_set X a [PROOF STEP] by (simp add: S \<open>a \<in> S\<close> path_component_of_maximal) [PROOF STATE] proof (state) this: S \<subseteq> path_component_of_set X a goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: thesis goal: No subgoals! [PROOF STEP] qed
{-# OPTIONS --rewriting --confluence-check #-} open import Agda.Builtin.Equality open import Agda.Builtin.Equality.Rewrite postulate A : Set a b : A f : (X : Set) → X → A g : (X : Set) → X rewf₁ : f (A → A) (λ _ → a) ≡ a rewf₂ : (X : Set) → f X (g X) ≡ b rewg : (x : A) → g (A → A) x ≡ a test = f (A → A) (λ x → g (A → A) x) {-# REWRITE rewf₁ rewg #-} foo : test ≡ a foo = refl {-# REWRITE rewf₂ #-} bar : test ≡ b bar = refl fails : a ≡ b fails = refl
function rs = predict2(s, dim, delay, len, nnr, mode, metric_lambda) %tstoolbox/@signal/predict2 % Syntax: % * rs = predict2(s, len, nnr, step, mode) % % Input arguments: % * len - length of prediction (number of output values) % * nnr - number of nearest neighbors to use (default is one) % * step - stepsize (in samples) (default is one) % * mode: % + 0 = Output vectors are the mean of the images of the nearest % neighbors % + 1 = Output vectors are the distance weighted mean of the % images of the nearest neighbors % + 2 = Output vectors are calculated based on the local flow % using the mean of the images of the neighbors % + 3 = Output vectors are calculated based on the local flow % using the weighted mean of the images of the neighbors % % Local constant iterative prediction for phase space data (e.g. data % stemming from a time delay reconstruction of a scalar time series), % using fast nearest neighbor search. Four methods of computing the % prediction output are possible. % % Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt narginchk(4,6); if nargin < 5, nnr = 1; end if nargin < 6, mode = 0; end if nargin < 7, metric_lambda = 1; end c = predict2(data(s), dim, delay, len, nnr, mode, metric_lambda); % do the prediction in phase space c = c(:,1); rs = signal(core(c), s); a = getaxis(rs, 1); rs = setaxis(rs, 1, a); rs = cut(rs, 1, dlens(s,1)+1, dlens(rs, 1)); rs = addhistory(rs, 'Local constant prediction for scalar time series'); rs = addcommandlines(rs, 's = predict2(s', dim, delay, len, nnr, mode);
Woodburn, OR - A man who killed four people, including a 9-month-old girl, in an Oregon home and was shot and killed by deputies as he was attempting to murder a child on Saturday, police said. The following Official Record of MARK LEO GREGORY GAGO is being redistributed by Mugshots.com and is protected by constitutional, publishing, and other legal rights. This Official Record was collected on 1/21/2019.
function C = gsp_jtv_mat2vec(C) %GSP_JTV_MAT2VEC vector to matrix transform % Usage: C = gsp_jtv_mat2vec(C); % % Input parameters: % C : Data % % Ouput parameter % C : Data % % Reshape the data from the matrix form to the vector form [N,T,Nf,Ns] = size(C); C = reshape(C,N*T*Nf,Ns); end
------------------------------------------------------------------------------- {- LANGUAGE CPP #-} -- specified in .cabal default-extensions #define USE_NFDATA_SUPERCLASS 0 ------------------------------------------------------------------------------- -- Later: I'm not so sure about this, actually; is the arithmetic -- on n actually not piling up thunks, without the bang-patterns? -- -- It would be easy to get rid of the bang-patterns. -- The Complex instance is done as an example. -- If you do go with the case's, probably want -fno-warn-name-shadowing. {-# LANGUAGE BangPatterns #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} ------------------------------------------------------------------------------- -- | -- Module : Control.DeepSeq.Bounded.NFDataN -- Copyright : Andrew G. Seniuk 2014-2015 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Andrew Seniuk <[email protected]> -- Stability : provisional -- Portability : portable -- -- This module provides an overloaded function, 'deepseqn', for partially -- (or fully) evaluating data structures to a given depth. -- ------------------------------------------------------------------------------- module Control.DeepSeq.Bounded.NFDataN ( -- * Depth-bounded analogues of 'deepseq' and 'force' deepseqn , forcen -- * Class of things that can be evaluated to an arbitrary finite depth #if JUST_ALIAS_GNFDATAN , rnfn #else , NFDataN(..) #endif ) where ------------------------------------------------------------------------------- --import qualified Data.Generics.Shape as S -- not actually used #if JUST_ALIAS_GNFDATAN import Generics.SOP ( Generic ) import Control.DeepSeq.Bounded.Generic.GNFDataN ( grnfn ) #endif #if USE_NFDATA_SUPERCLASS import Control.DeepSeq #endif --import Data.Data import Data.Int import Data.Word import Data.Ratio import Data.Complex import Data.Array import Data.Fixed import Data.Version ------------------------------------------------------------------------------- #if JUST_ALIAS_GNFDATAN type NFDataN = Generic #endif #if JUST_ALIAS_GNFDATAN rnfn = grnfn #endif ------------------------------------------------------------------------------- -- infixr 0 $!! ------------------------------------------------------------------------------- -- | @'deepseqn' n x y@ evaluates @x@ to depth n, before returning @y@. -- -- This is used when expression @x@ also appears in @y@, but mere -- evaluation of @y@ does not force the embedded @x@ subexpression -- as deeply as we wish. -- -- The name 'deepseqn' is used to illustrate the relationship to 'seq': -- where 'seq' is shallow in the sense that it only evaluates the top -- level of its argument, @'deepseqn' n@ traverses (evaluates) the entire -- top @n@ levels of the data structure. -- -- A typical use is to ensure any exceptions hidden within lazy -- fields of a data structure do not leak outside the scope of the -- exception handler; another is to force evaluation of a data structure in -- one thread, before passing it to another thread (preventing work moving -- to the wrong threads). Unlike <http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html DeepSeq>, potentially infinite values of coinductive -- data types are supported by principled bounding of deep evaluation. -- -- It is also useful for diagnostic purposes when trying to understand -- and manipulate space\/time trade-offs in lazy code, -- and as a less indiscriminate substitute for 'deepseq'. -- -- Furthermore, 'deepseqn' can sometimes be a better solution than -- using stict fields in your data structures, because the -- latter will behave strictly everywhere that its constructors -- are used, instead of just where its laziness is problematic. -- -- There may be possible applications to the prevention of resource leaks -- in lazy streaming, but I'm not certain. -- -- One of the special qualities of 'NFDataN' is shape oblivity: -- it doesn't care about any details of the shape of the term -- it's forcing, it only cares about stratifying levels of -- recursion depth. -- (I would say \"as contrasted with <http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html NFDataP>\" but cannot, because -- <http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html NFDataP> -- was extended to include -- <http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataN.html NFDataN> -- syntax\/capabilities, precisely to ammend this deficiency.) deepseqn :: NFDataN a => Int -> a -> b -> b deepseqn n a b = rnfn n a `seq` b #if 1 -- XXX Need to double-check that this makes sense; didn't think -- it through -- when b != a, things are not so simple. -- XXX Partially-applied; is that okay in GHC RULES? {-# RULES "deepseqn/composition" forall n1 n2 x. (.) (deepseqn n2) (deepseqn n1) x = deepseqn ( max n1 n2 ) x #-} #endif ------------------------------------------------------------------------------- #if 0 -- As per DeepSeq: -- | the deep analogue of '$!'. In the expression @f $!! x@, @x@ is -- fully evaluated before the function @f@ is applied to it. ($!!) :: NFData a => (a -> b) -> a -> b f $!! x = x `deepseq` f x #endif ------------------------------------------------------------------------------- -- | 'forcen' is a variant of 'deepseqn' that is useful in some circumstances. -- -- > forcen n x = deepseqn n x x -- -- @forcen n x@ evaluates @x@ to depth @n@, and then returns it. -- Recall that, in common with all Haskell functions, @forcen@ only -- performs evaluation when upstream demand actually occurs, -- so essentially it turns shallow evaluation into depth-@n@ evaluation. forcen :: NFDataN a => Int -> a -> a forcen n x = deepseqn n x x #if 1 {-# RULES "forcen/composition" forall n1 n2 x. (.) (forcen n2) (forcen n1) x = forcen ( max n1 n2 ) x #-} #endif ------------------------------------------------------------------------------- #if ! JUST_ALIAS_GNFDATAN -- | A class of types that can be evaluated to arbitrary depth. #if USE_NFDATA_SUPERCLASS class NFData a => NFDataN a where #else class NFDataN a where #endif #if 0 -- | rnf should reduce its argument to normal form (that is, fully -- evaluate all sub-components), and then return '()'. -- -- The default implementation of 'rnf' is -- -- > rnf a = a `seq` () -- -- which may be convenient when defining instances for data types with -- no unevaluated fields (e.g. enumerations). rnf :: a -> () rnf a = a `seq` () #endif rnfn :: Int -> a -> () #if USE_NFDATA_SUPERCLASS -- ?? not sure about this (whatever, we'll override it) #if 1 rnfn n a | n <= 0 = () -- case needed? (seems to be!) | otherwise = rnf a #else rnfn _ a = rnf a #endif #else #if 0 #elif 1 rnfn n x | n <= 0 = () | otherwise = x `seq` () #elif 0 rnfn _ x = x `seq` () #elif 0 rnfn _ _ = () #endif #endif #if 1 {-# RULES "rnfn/composition" forall n1 n2 x. (.) (rnfn n2) (rnfn n1) x = rnfn ( max n1 n2 ) x #-} -- "rnfp/composition" forall p1 p2 x. compose (rnfp p2) (rnfp p1) x = rnfp ( unionPat [p1, p2] ) x -- "rnfp/composition" forall p1 p2 x. ( rnfp p2 . rnfp p1 ) x = rnfp ( unionPat [p1, p2] ) x #endif ------------------------------------------------------------------------------- instance NFDataN Int instance NFDataN Word instance NFDataN Integer instance NFDataN Float instance NFDataN Double instance NFDataN Char instance NFDataN Bool instance NFDataN () instance NFDataN Int8 instance NFDataN Int16 instance NFDataN Int32 instance NFDataN Int64 instance NFDataN Word8 instance NFDataN Word16 instance NFDataN Word32 instance NFDataN Word64 instance NFDataN (Fixed a) -- [Quoted from deepseq:] -- This instance is for convenience and consistency with 'seq'. -- This assumes that WHNF is equivalent to NF for functions. instance NFDataN (a -> b) #if 0 instance NFDataN a => NFDataN (IO a) where rnfn !n x = () -- XXX ignore if in IO (cludge easing an experiment...) #endif -- not taken to be a level of depth instance (Integral a, NFDataN a) => NFDataN (Ratio a) where rnfn !n x = rnfn n (numerator x, denominator x) instance (RealFloat a, NFDataN a) => NFDataN (Complex a) where #if 1 rnfn n (x:+y) = case n of n | n <= 0 -> () _ -> let n' = -1+n in rnfn n' x `seq` rnfn n' y `seq` () #else rnfn !n (x:+y) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x `seq` rnfn n' y `seq` () #endif instance NFDataN a => NFDataN (Maybe a) where rnfn _ Nothing = () rnfn !n (Just x) | n <= 0 = () | otherwise = rnfn (-1+n) x instance (NFDataN a, NFDataN b) => NFDataN (Either a b) where rnfn !n (Left x) | n <= 0 = () | otherwise = rnfn (-1+n) x rnfn !n (Right y) | n <= 0 = () | otherwise = rnfn (-1+n) y instance NFDataN Data.Version.Version where rnfn !n (Data.Version.Version branch tags) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' branch `seq` rnfn n' tags instance NFDataN a => NFDataN [a] where rnfn _ [] = () rnfn !n (x:xs) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x `seq` rnfn n' xs -- not taken to be a level of depth instance (Ix a, NFDataN a, NFDataN b) => NFDataN (Array a b) where rnfn !n x = rnfn n (bounds x, Data.Array.elems x) instance (NFDataN a, NFDataN b) => NFDataN (a,b) where rnfn !n (x,y) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x `seq` rnfn n' y instance (NFDataN a, NFDataN b, NFDataN c) => NFDataN (a,b,c) where rnfn !n (x,y,z) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x `seq` rnfn n' y `seq` rnfn n' z instance (NFDataN a, NFDataN b, NFDataN c, NFDataN d) => NFDataN (a,b,c,d) where rnfn !n (x1,x2,x3,x4) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x1 `seq` rnfn n' x2 `seq` rnfn n' x3 `seq` rnfn n' x4 instance (NFDataN a1, NFDataN a2, NFDataN a3, NFDataN a4, NFDataN a5) => NFDataN (a1, a2, a3, a4, a5) where rnfn !n (x1,x2,x3,x4,x5) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x1 `seq` rnfn n' x2 `seq` rnfn n' x3 `seq` rnfn n' x4 `seq` rnfn n' x5 instance (NFDataN a1, NFDataN a2, NFDataN a3, NFDataN a4, NFDataN a5, NFDataN a6) => NFDataN (a1, a2, a3, a4, a5, a6) where rnfn !n (x1,x2,x3,x4,x5,x6) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x1 `seq` rnfn n' x2 `seq` rnfn n' x3 `seq` rnfn n' x4 `seq` rnfn n' x5 `seq` rnfn n' x6 instance (NFDataN a1, NFDataN a2, NFDataN a3, NFDataN a4, NFDataN a5, NFDataN a6, NFDataN a7) => NFDataN (a1, a2, a3, a4, a5, a6, a7) where rnfn !n (x1,x2,x3,x4,x5,x6,x7) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x1 `seq` rnfn n' x2 `seq` rnfn n' x3 `seq` rnfn n' x4 `seq` rnfn n' x5 `seq` rnfn n' x6 `seq` rnfn n' x7 instance (NFDataN a1, NFDataN a2, NFDataN a3, NFDataN a4, NFDataN a5, NFDataN a6, NFDataN a7, NFDataN a8) => NFDataN (a1, a2, a3, a4, a5, a6, a7, a8) where rnfn !n (x1,x2,x3,x4,x5,x6,x7,x8) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x1 `seq` rnfn n' x2 `seq` rnfn n' x3 `seq` rnfn n' x4 `seq` rnfn n' x5 `seq` rnfn n' x6 `seq` rnfn n' x7 `seq` rnfn n' x8 instance (NFDataN a1, NFDataN a2, NFDataN a3, NFDataN a4, NFDataN a5, NFDataN a6, NFDataN a7, NFDataN a8, NFDataN a9) => NFDataN (a1, a2, a3, a4, a5, a6, a7, a8, a9) where rnfn !n (x1,x2,x3,x4,x5,x6,x7,x8,x9) | n <= 0 = () | otherwise = let n' = -1+n in rnfn n' x1 `seq` rnfn n' x2 `seq` rnfn n' x3 `seq` rnfn n' x4 `seq` rnfn n' x5 `seq` rnfn n' x6 `seq` rnfn n' x7 `seq` rnfn n' x8 `seq` rnfn n' x9 #endif -------------------------------------------------------------------------------
# VARIABLES, TIPOS DE DATOS SIMPLES Y OPERADORES En programación este apartado aprenderas a utilizar los diferentes tipos de datos que se encuentran disponibles en python, asi como declarar variables y realizar operaciones. ## 1. Variables Una variable es un identificador que representa un espacio en la memoria. A este espacio se le puede asignar un valor para utilizarlo posteriormente como si se tratase de un valor literal, incluso se puede operar con otras variables y reasignarle otro valor en cualquier momento. **La variable me permite almacenar en la memoria de la computadora un valor (numero, texto, etc)** <center></center> #### 1.1 Declaración de variables en otros lenguajes 1. Se declara la variable con su tipo de dato 2. Se asigna un valor a la variable #### 1.2 Declaración de variables en Python 1. Se asigna un valor a una variable (no es necesario declarar tipo de dato) 2. Python por defecto interpreta el tipo de dato según el valor recibido ```python ## 1. Declaremos una variable para mejorar que nos ayude a enviar un mensaje al usuario print('Hola Mundo') ``` Hola Mundo ```python ## 2. Declarando una variable, la cual contiene un texto mensaje = "Hola Mundo" print(mensaje) ``` Hola Mundo ### Ejercicio Cree una variable llamada <code>msg</code> la cual almacene un mensaje. Luego imprima dicho mensaje ```python msg = 'hola a todos!!' ``` ```python print(msg) ``` hola a todos!! ## 2. Tipo de Datos En la programación todo se resume a datos que representan información. Dicha información en terminos simples la podemos ver como: - Cadenas de texto o strings - Números - fechas - imágenes - sonidos - vídeos - Etc. ### 2.2 Tipo de Dato texto Inmediatamente después de los números hay que echar un vistazo a las cadenas de texto, a fin de cuentas es la forma como las personas nos comunicamos de forma escrita. Las letras o caracteres son en definitiva símbolos de escritura y otro tipo de dato esencial. Siempre se definen entre comillas simples o dobles: ```python # Usando comillas simples 'Esta es una cadena de texto' ``` 'Esta es una cadena de texto' ```python # Cadena usando comillas dobles "Esta es otra cadena de texto" ``` 'Esta es otra cadena de texto' ```python # Cadena de más de una linea """ Esta cadena tiene más de una línea por lo que se usa 3 comillas dobles dasdas """ ``` '\nEsta cadena tiene más de una línea\npor lo que se usa\n3 comillas dobles\ndasdas\n' ```python print('hola\na todos') ``` hola a todos - Almacenando cadenas en variables ```python # Recuerda que podemos utilizar variables para almacenar una cadena de texto texto = "Este es un texto" ``` #### Algunas Operaciones Basicas de Cadena Una vez que ya conocemos que es una cadena veamos algunas operaciones básicas con las cadenas de texto ```python cad1 = "Hola" cad2 = "Mundo" ``` ```python ## Concadenar dos cadenas de texto print("Un divertido "+"programa "+"de "+ "radio") ## Usando variables # Esto es igual a : "HolaMundo" cad1 = "Un divertido " cad2 = "programa" print(cad1 + cad2) ``` Un divertido programa de radio Un divertido programa ```python ## Multiplicar una cadena print('Hola') print('Hola'*3) ``` Hola HolaHolaHola ```python ## Conocer largo de una cadena len('Hola') # cadena de 4 caracteres ``` 4 ```python len(cad1) ``` 13 ```python ## Identificando el tipo de dato y = 'h' type(y) ``` str ```python ## Convirtiendo a string str(3) ``` '3' ```python ``` ### 2.2.Tipos de Datos Numéricos Representan valores numéricos. - Enteros (int): Representan números enteros - Decimales (float): Representan valores decimales ```python # Int -> Valores enteros 3 ``` 3 ```python x = 5 print(x) ``` 5 ```python # Float -> Representan valores con coma decimal 3.14 ``` 3.14 ```python y = 8.17 print(y) ``` 8.17 #### Identificando los tipos de datos ```python type(8) ``` int ```python p = 12.34234 type(p) ``` float #### Operaciones sobre números Representan el conjunto de operaciones básicas de tipo numéricas ```python ## Indistintamente si un numero es "int" or "float" es posible realizar operaciones sobre ellos numero_1 = 12 numero_2 = 8.5 ``` ```python 7 // 3 # solo muestra la parte entera de la división ``` 2 ```python # sumando print(numero_1 + numero_2) # Restando print(numero_1 - numero_2) # Multiplicando: 12 * 2 = 24 print(numero_1 * 2) # Diviendo : 12 / 2 = 6 print(numero_1 / 2) # Potencia : 12 ** 2 = 144 print(numero_1 ** 2) ``` 20.5 3.5 24 6.0 144 ```python ## Módulo de un número -> Me brinda el residuo de la división entre dos numeros ## 7 = 3 * 2 + 1 (1 es el residuo de la división) 7 % 3 # -> 3 no es divisor de 7 ``` 1 #### Otras Operaciones Básicas ```python int(3.55) # int() -> convierte otro tipo de dato a entero ``` 3 ```python int('3') # Convierto String a entero ``` 3 ```python float(3) # Convierto "int" a float ``` 3.0 ```python float('3.245') # Convierto "String" a float ``` 3.245 ### Ejercicios 1. Escribir un programa que realice la siguiente operación aritmética (Usar variables) $$ ({3 +}\frac{2}{2 x 5}) {^2} $$ ```python a = 3 b = 2 / (2 * 5) r = (a + b) ** 2 print(int(r)) ``` 10 2. Calcular la Fuerza en Newtons de un cuerpo con masa m = 4 kg y una aceleracion a= 3 m/s \begin{equation} F = m * a \end{equation} ```python # 1. recupero valores de m y a m = 4 a = 3 # 2. realizo el calculo f = m * a # 3. muetro en pantalla print(f) ``` 12 ```python ``` ### 2.3 Tipo de Datos Booleanos Definen un valor de Verdadero o Falso según sea el caso Se representa: - verdadero = True - falso = False ```python True ``` True ```python # cualquier número excepto el 0 se interpreta como verdadero bool(1) ``` True ```python False ``` False ```python bool(0) ``` False ```python ## Conociendo el tipo de dato type(True) ``` bool #### 3.2 Operadores Relacionales (De comparación) Sirven para comparar dos valores, dependiendo del resultado de la comparación se devolverá: - Verdadero (True), si es cierta - Falso (False), si no es cierta ```python # Comparando dos valores a = 3 b ='s' # Comparando a y b a == b ``` False ```python a != b ``` True ```python c = 5 # Mayor que a > c ``` False ```python 's' > 5 ``` ```python ``` **Cuidado:** Tener en cuenta lo siguiente para implementar sus lógicas #### 3.3 Operadores Lógicos Encontramos 3 operadores especiales para realizar operaciones lógicas. Normalmente se utilizan para agrupar, excluir y negar expresiones. Puede ayudar echar un vistazo a esta explicación sobre las tablas de la verdad: - Not - And - Or ```python # Hallando el valor de verdad de la siguiente expresión (9 < 12) and (12 > 7) ``` ### Ejercicios 1. Expresión a evaluar: 2 > p para el valor p = 5 ```python p = 5 2 > p # 2 no es mayor que 5 ``` False 2. Expresión a evaluar: 8 == b and not b < 0 para el valor b = 0 ```python b = 0 (8 == b) and not(b<0) ``` False ```python True or not(True) ``` True # Notas Adicionales ```python # Jupyter Notebook no es necesario poner print numero =3 numero ``` 3 ```python ## Para este caso si es necesario el print numero = 7 numero x = 2 ``` ```python ## El valor que quiera imprimir debe estar al final de todo print(numero) ``` 7 #### Funcion Type() Nos ayudará a conocer el tipo de dato de la variable ```python # Conociendo el tipo de dato de la variable número type(numero) ``` int ```python # Pasando un numero como texto numero_texto ='3.14' numero_texto = float(numero_texto) # reasingacion de variable type(numero_texto) ``` float ```python ``` #### Operadores de Asignación Permiten la asignación de nuevos valores a las variables de forma rápida <b>Suma en asignación</b> <p>Nos ayuda sumar un número dado a la variable de forma rápida </p> ```python # Defino a como 5 a = 5 ``` ```python a = a + 2 print(a) ``` 7 ```python # Aumento dos a la variable a (a = a+2) a += 2 ``` ```python a ``` 9 ```python # a = a * 10 a *= 10 a ``` 90 ```python ``` ```python ```
theory maximum2 imports "~~/src/HOL/Hoare/Hoare_Logic" "~~/src/HOL/Hoare/List" begin (* ******************* *) (* ******************* *) (* ******************* *) definition maximum :: "nat list \<Rightarrow> nat" where "maximum l = foldr max l 0" value "maximum [1,3,5,4,2]" (* 5 *) value "maximum []" (* 0 *) lemma max_hdtl_eq [simp] : "l \<noteq> [] \<Longrightarrow> max (hd l) (maximum (tl l)) = maximum l" apply (induct l) apply auto by (simp add: maximum_def) (* ********* *) (* * lemma * *) (* ********* *) (* 3 subgoals, 1., 2., 3. *) (* 1. *) lemma l1 : "max (maximum x) y = maximum l \<Longrightarrow> x \<noteq> [] \<Longrightarrow> y \<le> hd x \<Longrightarrow> max (maximum (tl x)) (hd x) = maximum l" by (metis max.assoc max.commute max_def max_hdtl_eq) (* Sledgehammer *) (* 2. *) lemma l2 : "max (maximum x) y = maximum l \<Longrightarrow> x \<noteq> [] \<Longrightarrow> \<not> y \<le> hd x \<Longrightarrow> max (maximum (tl x)) y = maximum l" by (metis max.assoc max.commute max_def max_hdtl_eq) (* Sledgehammer *) (* 3. *) lemma l3 : "max (maximum []) y = maximum l \<Longrightarrow> y = maximum l" by (simp add: maximum_def) (* Sledgehammer *) (* ******** *) (* * main * *) (* ******** *) theorem "VARS x y l {x = l \<and> y = 0} y := 0; WHILE x \<noteq> [] INV {max (maximum x) y = maximum l} DO IF y \<le> hd x THEN y := hd x ELSE SKIP FI; x := tl x OD {y = maximum l}" apply vcg apply auto (* 3 subgoals, 1., 2., 3. *) by (simp_all add: l1 l2 l3) end (* END *)
%> @brief Convert a general cell array matrix to a string %> @author Eric Cousineau <[email protected]>, AMBER Lab, under Dr. %> Aaron Ames %> @param X cell array %> @param varargin Arguments to propagate to general2str() function [str] = cell2str(X, varargin) s = size(X); func = @(x) general2str(x, varargin{:}); raw = cellfun(func, X, 'UniformOutput', false); rows = cell(s(1), 1); for i = 1:s(1) rows{i} = implode(raw(i, :), ', '); end str = ['{\n', indent(strjoin(rows', ';\n'), '\t'), ';\n}']; end
install.packages("tidyverse") library(tidyverse) library(lubridate)
/************************************************* * @Description: file content * @Author: yuanquan * @Email: [email protected] * @Date: 2021-05-17 21:20:13 * @LastEditors: yuanquan * @LastEditTime: 2021-07-24 12:20:47 * @copyright: Copyright (c) yuanquan *************************************************/ #include <iostream> #include <vector> #include <set> #include <string> #include <gtest/gtest.h> #include <boost/array.hpp> #include <tuple> using namespace std; using namespace boost; using namespace testing; int strStr(string haystack, string needle) { if(needle.empty()) return 0; for(int i=0; i < haystack.size(); ++i) { for(int j=0; j < needle.size(); ++j) { if(i + j >= haystack.size()) return -1; if(haystack[i + j] != needle[j]) break; if(j==needle.size()-1) return i; } } return -1; } TEST(strStrTest, all) { using TestData = tuple<string, string, int>; vector<TestData> datas{ make_tuple("hello", "ll", 2), make_tuple("aaaaa", "bba", -1), make_tuple("", "", 0), }; for(auto& dat : datas) { auto [haystack, needle, position] = dat; EXPECT_EQ(position, strStr(haystack, needle)) << "str[" << haystack << "], sub str[" << needle << "]"; } }
/- This files provides the tactics hypo_analysis targets_analysis which output a string reflecting the lean expr for objects in the and in the target. The key function is analysis_expr_step that pattern matches an object to determine a short string reflecting its node (e.g., "INCLUSION"), and children (e.g. here, corresponding to the left and righ hand side of the inclusion property). The two tactics also provides the types of all intermediate objects. Authors: Frédéric Le Roux -/ import data.set import data.real.basic import tactic import parser_analysis_definitions import user_notations namespace tactic.interactive open lean.parser tactic interactive open interactive (loc.ns) open interactive.types open tactic expr local postfix *:9001 := many -- necessary for ident* set_option pp.width 1000 -- We do not want CR inside our strings def separator_object := "¿¿¿" def separator_comma := "¿, " def separator_equal := "¿= " def separator_slash := "¿/ " def open_paren := "¿(" def closed_paren := "¿)" def open_bra := "¿[" def closed_bra := "¿]" -- set_option trace.eqn_compiler.elim_match true /- When e is a pi or lambda expr, instanciate e returns a local constant a that stands for the first bound variable, and the body of a with the free variable replaced by a. The name of 'a' is enriched with suffix 'BoundVar'. -/ meta def instanciate (e : expr) : tactic (expr × expr) := match e with | (pi pp_name binder type body) := do let pp_name := mk_str_name pp_name "BoundVar", -- pp_name ← get_unused_name pp_name, -- does not do the job -- trace ("Instantiation name: " ++ to_string pp_name), a ← mk_local' pp_name binder type, let inst_body := instantiate_var body a, return (a , inst_body) | (lam pp_name binder type body) := do let pp_name := mk_str_name pp_name "BoundVar", -- trial -- pp_name ← get_unused_name pp_name, -- trace ("Instantiation name: " ++ to_string pp_name), a ← mk_local' pp_name binder type, let inst_body := instantiate_var body a, return (a , inst_body) | _ := return (e, e) end open set /- The key function. Decompose the root of an expression (just one step) General types should be at the end. -/ private meta def analysis_expr_step (e : expr) : tactic (string × (list expr)) := do S ← (tactic.pp e), let e_joli := to_string S, match e with ------------------------- LOGIC ------------------------- | `(%%p ∧ %%q) := return ("PROP_AND", [p,q]) | `(%%p ∨ %%q) := return ("PROP_OR", [p,q]) | `(%%p ↔ %%q) := return ("PROP_IFF", [p,q]) -- various negations | `(%%a ≠ %%b) := return ("PROP_EQUAL_NOT", [a,b]) | `(¬ %%a = %%b) := return ("PROP_EQUAL_NOT", [a,b]) | `(%%a ∉ %%A) := return ("PROP_NOT_BELONGS", [a,A]) | `(¬ %%p) := return ("PROP_NOT", [p]) | `(%%p → false) := return ("PROP_NOT", [p]) | `(false) := return ("PROP_FALSE",[]) ------------------------- SET THEORY ------------------------- | `(%%A ∩ %%B) := return ("SET_INTER", [A,B]) | `(%%A ∪ %%B) := return ("SET_UNION", [A,B]) | `(set.compl %%A) := do e_type ← infer_type e, match e_type with | `(_root_.set %%X) := return ("SET_COMPLEMENT", [X, A]) | _ := return ("", []) end -- | `(set.symmetric_difference %%A %%B) := return ("SET_DIFF_SYM", [A,B]) | `(%%A \ %%B) := return ("SET_DIFF", [A,B]) | `(%%A ⊆ %%B) := return ("PROP_INCLUDED", [A,B]) | `(%%a ∈ %%A) := return ("PROP_BELONGS", [a,A]) | `(@set.univ %%X) := return ("SET_UNIVERSE", [X]) | `(-%%A) := return ("MINUS", [A]) | `(set.Union %%A) := return ("SET_UNION+", [A]) | `(set.Inter %%A) := return ("SET_INTER+", [A]) | `(%%f '' %%A) := return ("SET_IMAGE", [f,A]) | `(%%f ⁻¹' %%A) := return ("SET_INVERSE", [f,A]) | `(∅) := return ("SET_EMPTY", []) | `({%%x, %%x', %%x''}) := return ("SET_EXTENSION3", [x, x', x'']) | `({%%x, %%x'}) := return ("SET_EXTENSION2", [x, x']) | `({%%x}) := return ("SET_EXTENSION1", [x]) -- | `(triplet %%x %%x' %%x'') := return ("SET_EXTENSION3", [x, x', x'']) | `(pair %%x %%x') := return ("SET_EXTENSION2", [x, x']) | `(sing %%x) := return ("SET_EXTENSION1", [x]) | `(_root_.set %%X) := return ("SET", [X]) | `(set.prod %%A %%B) := return ("SET_PRODUCT", [A, B]) | `(prod.mk %%x %%y) := return ("COUPLE", [x, y]) -- set in extension, e.g. A = {x | P x} or A = {x:X | P x} : | `(@set_of %%X %%P) := match P with | (lam name binder type body) := do (var_, inst_body) ← instanciate P, return ("SET_INTENSION",[X, var_, inst_body]) | _ := return ("SET_INTENSION", [X, P]) end | `(index_set) := return ("TYPE", []) | `(set_family %%I %%X) := return ("SET_FAMILY", [I, X]) -- | `(seq %%X) := return ("SEQUENCE", [X]) | (pi name binder type body) := do let is_arr := is_arrow e, if is_arr then do is_pro ← tactic.is_prop e, if is_pro then return ("PROP_IMPLIES", [type,body]) else match e with | `(%%X → %%Y) := match (X,Y) with -- | (`(ℕ), `(ℕ)) := return ("SEQUENCE", [X, Y]) -- | (`(ℕ), `(ℤ)) := return ("SEQUENCE", [X, Y]) -- | (`(ℕ), `(ℚ)) := return ("SEQUENCE", [X, Y]) -- | (`(ℕ), `(ℝ)) := return ("SEQUENCE", [X, Y]) | (`(ℕ), _) := return ("SEQUENCE", [X, Y]) | _ := do X_type ← infer_type X, match (X_type, Y) with -- A set family is when source is an index_set -- (just a type which is "tagged" for serving as index) -- and target is "set something" | (`(index_set), `(_root_.set %%Z)) := return ("SET_FAMILY", [X, Z]) | _ := return ("FUNCTION", [X, Y]) end end | _ := return ("ERROR", []) end else do (var_, inst_body) ← instanciate e, return ("QUANT_∀", [type, var_, inst_body]) | `(Exists %%p) := do match p with | (lam name binder type body) := do (var_, inst_body) ← instanciate p, is_pro ← is_prop type, if is_pro then return ("PROP_∃", [type, inst_body]) -- we do not care about var_ else return ("QUANT_∃", [type, var_, inst_body]) | _ := do p_type ← infer_type p, match p_type with | `(%%type → Prop) := do Q ← to_expr ``(λ x: %%type, (%%p x)), -- Do not work properly (var_, inst_body) ← instanciate Q, is_pro ← is_prop type, if is_pro then return ("PROP_∃", [type, inst_body]) -- we do not care about var_ else return ("QUANT_∃", [type, var_, inst_body]) | _ := return ("ERROR", []) end end | `(exists_unique %%P) := do match P with | (lam name binder type body) := do (var_, inst_body) ← instanciate P, return ("QUANT_∃!", [type, var_, inst_body]) | _ := return ("ERROR", []) end -- polymorphic | `(%%a = %%b) := return ("PROP_EQUAL", [a,b]) -- does not provide the type ----------- TOPOLOGY -------------- -- | `(B(%%x, %%r)) ------------ ORDER ---------------- | `(%%a < %%b) := return ("PROP_<", [a,b]) | `(%%a ≤ %%b) := return ("PROP_≤", [a,b]) | `(%%a > %%b) := return ("PROP_>", [a,b]) | `(%%a ≥ %%b) := return ("PROP_≥", [a,b]) ------------ ARITHMETIC ------------ | `(↑%%a) := return ("COE", [a]) | `(%%a + %%b) := return ("SUM", [a, b]) | `(%%a - %%b) := return ("DIFFERENCE", [a, b]) | `(has_mul.mul %%a %%b) := return ("MULT", [a, b]) -- TODO: distinguish types/numbers | `(%%a × %%b) := return ("PRODUCT", [a, b]) -- TODO: distinguish types/numbers | `(%%a / %%b) := return ("DIV", [a, b]) | `(%%a ^ %%b) := return ("POWER", [a, b]) | `(real.sqrt %%a) := return ("SQRT", [a]) ------------------------------ Leaves with data --------------------------- | (app function argument) := if is_numeral e then return ("NUMBER" ++ open_bra ++ "value: " ++ e_joli ++ closed_bra, []) else return("APPLICATION", [function,argument]) -- | `(%%I → _root_.set %%X) := return ("SET_FAMILY", [I,X]) -- | `(ℝ) := return ("TYPE_NUMBER" ++ open_bra -- ++ "name: ℝ" ++ closed_bra,[]) --| `(ℕ) := return ("TYPE_NUMBER"++ open_bra -- ++ "name: ℕ" ++ closed_bra,[]) | (const name list_level) := return ("CONSTANT" ++ open_bra ++ "name: " ++ e_joli ++ closed_bra, []) | (sort level.zero) := return ("PROP", []) | (sort level) := return ("TYPE", []) | (local_const name pretty_name bi type) := return ("LOCAL_CONSTANT" ++ open_bra ++ "name: " ++ to_string pretty_name ++ separator_slash ++ "identifier: " ++ to_string name ++ closed_bra, []) ---------------- Other structures ------------- | (var nat) := return ("VAR" ++ open_bra ++ to_string nat ++ closed_bra, []) | (mvar name pretty_name type) := return ("METAVAR" ++ open_bra ++ "name: " ++ to_string pretty_name ++ closed_bra, []) | (elet name_var type_var expr body) := return ("LET"++ open_bra ++ to_string name_var ++ closed_bra, [type_var,expr,body]) | (macro list something) := return ("MACRO", []) | (lam name binder type body) := do (var_, inst_body) ← instanciate e, return ("LAMBDA",[type, var_, inst_body]) end /- Recursively analyses an expression using analysis_expr_step, and provides a string with parentheses reflecting the mathematical object-/ private meta def analysis_rec : expr → tactic string | e := do ⟨string, list_expr⟩ ← analysis_expr_step(e), match list_expr with -- BEWARE, case of more than three arguments not implemented -- replace by a list.map |[e1] := do string1 ← analysis_rec e1, return(string ++ open_paren ++ string1 ++ closed_paren) |[e1,e2] := do string1 ← analysis_rec e1, string2 ← analysis_rec e2, return (string ++ open_paren ++ string1 ++ separator_comma ++ string2 ++ closed_paren) |[e1,e2,e3] := do string1 ← analysis_rec e1, string2 ← analysis_rec e2, string3 ← analysis_rec e3, return (string ++ open_paren ++ string1 ++ separator_comma ++ string2 ++ separator_comma ++ string3 ++ closed_paren) | _ := return(string) end meta def analysis_expr : expr → tactic string | e := do expr_t ← infer_type e, is_pro ← is_prop expr_t, if is_pro then do S ← (tactic.pp expr_t), let et_joli := to_string S, S1b ← analysis_rec e, S2 ← analysis_rec expr_t, let S3 := "PROPERTY" ++ open_bra ++ "identifier: " ++ S1b ++ separator_slash ++ "pp_type: " ++ et_joli ++ closed_bra ++ separator_equal ++ S2, return(S3) else do S1b ← analysis_rec e, S2 ← analysis_rec expr_t, let S3 := "OBJECT" ++ open_bra ++ S1b ++ closed_bra ++ separator_equal ++ S2, return(S3) /- Recursively analyses an expression using analysis_expr_step, and provides a string with parentheses reflecting the mathematical object, with types-/ private meta def analysis_rec_with_types : expr → tactic string | e := do ⟨string, list_expr⟩ ← analysis_expr_step(e), -- trace ("analysing e: " ++ to_string e), -- if is_local_constant e -- then return(string) -- else do e_type ← infer_type e, -- trace "analysing e_type", string_type ← analysis_rec e_type, let str_with_type := string ++ open_bra ++ "type: " ++ string_type ++ closed_bra, -- trace str_with_type, match list_expr with -- BEWARE, case of more than three arguments not implemented -- replace by a list.map |[e1] := do string1 ← analysis_rec_with_types e1, return(str_with_type ++ open_paren ++ string1 ++ closed_paren) |[e1,e2] := do string1 ← analysis_rec_with_types e1, string2 ← analysis_rec_with_types e2, return (str_with_type ++ open_paren ++ string1 ++ separator_comma ++ string2 ++ closed_paren) |[e1,e2,e3] := do string1 ← analysis_rec_with_types e1, string2 ← analysis_rec_with_types e2, string3 ← analysis_rec_with_types e3, return (str_with_type ++ open_paren ++ string1 ++ separator_comma ++ string2 ++ separator_comma ++ string3 ++ closed_paren) | _ := return(str_with_type) end -- set_option pp.all true meta def analysis_expr_with_types : expr → tactic string | e := do expr_t ← infer_type e, is_pro ← is_prop expr_t, if is_pro then do S ← (tactic.pp expr_t), -- insert something like -- (options := (options.set_nat pp.width 1000)) -- in let et_joli := to_string S, -- let et_joli := format.to_string (options.set_nat pp.width 1000) S, let et_joli := to_string S, S1b ← analysis_rec e, S2 ← analysis_rec_with_types expr_t, let S3 := separator_object ++ "property" ++ open_bra ++ "pp_type: " ++ et_joli ++ closed_bra ++ ": " ++ S1b ++ separator_equal ++ S2, return(S3) else do S1b ← analysis_rec e, S2 ← analysis_rec expr_t, let S3 := separator_object ++ "object: " ++ S1b ++ separator_equal ++ S2, return(S3) /- print a list of strings reflecting objects in the context -/ meta def hypo_analysis : tactic unit := do list_expr ← local_context, trace "context:", list_expr.mmap (λ h, analysis_expr_with_types h >>= trace), return () /- print the list of all targets -/ meta def targets_analysis : tactic unit := do list_expr ← get_goals, trace "targets:", list_expr.mmap (λ h, analysis_expr_with_types h >>= trace), return () /--------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- --------------------- DEBUG ------------------------ ---------------------------------------------------- ---------------------------------------------------- ----------------------------------------------------/ private meta def analyse_expr_step_brut (e : expr) : tactic (string × (list expr)) := match e with -- autres | (pi name binder type body ) := return ("pi (nom : " ++ to_string name ++ ")",[type,body]) | (app fonction argument) := return ("application", [fonction,argument]) | (const name list_level) := return ("constante :" ++ to_string name, []) -- name → list level → expr | (var nat) := return ("var_"++ to_string nat, []) -- nat → expr | (sort level) := return ("sort", []) -- level → expr | (mvar name pretty_name type) := return ("metavar", []) -- name → name → expr → expr | (local_const name pretty_name bi type) := return ("constante_locale :" ++ to_string pretty_name, []) -- name → name → binder_info → expr → expr | (lam name binder type body) := return ("lambda (nom : " ++ to_string name ++ ")", [type,body]) -- name → binder_info → expr → expr → expr | (elet name_var type_var expr body) := return ("let", []) --name → expr → expr → expr → expr | (macro liste pas_compris) := return ("macro", []) -- macro_def → list expr → expr end private meta def analyse_rec_brut : expr → tactic string | e := do ⟨string, liste_expr⟩ ← analyse_expr_step_brut e, match liste_expr with -- ATTENTION, cas de plus de trois arguiments non traité -- à remplacer par un list.map |[e1] := do string1 ← analyse_rec_brut e1, return(string ++ "(" ++ string1 ++ ")") |[e1,e2] := do string1 ← analyse_rec_brut e1, string2 ← analyse_rec_brut e2, return (string ++ "(" ++ string1 ++ "," ++ string2 ++ ")") |[e1,e2,e3] := do -- non utilisé string1 ← analyse_rec_brut e1, string2 ← analyse_rec_brut e2, string3 ← analyse_rec_brut e3, return (string ++ "(" ++ string1 ++ "," ++ string2 ++ "," ++ string3 ++ ")") | _ := return(string) end private meta def analyse_expr_brut : expr → tactic string | e := do expr_t ← infer_type e, expr_tt ← infer_type expr_t, if expr_tt = `(Prop) then do S ← (tactic.pp expr_t), let S1 := to_string S, S2 ← analyse_rec_brut expr_t, let S3 := "PROPRIETE : " ++ S1 ++ " : " ++ S2, return(S3) else do let S0 := "OBJET : ", let S1 := to_string e, S2 ← analyse_rec_brut e, let S3 := S0 ++ S1 ++ " : "++ S2, return(S3) /- Affiche la liste des objets du contexte, séparés par des retour chariots format : "OBJET" ou "PROPRIETE" : affichage Lean : structure -/ meta def analyse_contexte_brut : tactic unit := do liste_expr ← local_context, trace "Contexte :", liste_expr.mmap (λ h, analyse_expr_brut h >>= trace), return () /- Analyse brute de Lean (dans expr) -/ meta def analyse_raw (names : parse ident*) : tactic unit := match names with | [] := do goal ← tactic.target, trace $ to_raw_fmt goal | [nom] := do expr ← get_local nom, expr_t ← infer_type expr, trace $ to_raw_fmt expr_t | _ := skip end end tactic.interactive -- example (X Y: Type) (f: set X → set X) (I: set.index_set) (E: I → set X) -- (F: I → X) (G: I → set (X × Y)) (H: Y → set X): -- true := -- begin -- hypo_analysis, -- end
------------------------------------------------------------------------ -- The Agda standard library -- -- Properties, related to products, that rely on the K rule ------------------------------------------------------------------------ {-# OPTIONS --with-K --safe #-} module Data.Product.Properties.WithK where open import Data.Bool.Base open import Data.Product open import Data.Product.Properties using (,-injectiveˡ) open import Function open import Relation.Binary using (Decidable) open import Relation.Binary.PropositionalEquality open import Relation.Nullary.Reflects open import Relation.Nullary using (Dec; _because_; yes; no) open import Relation.Nullary.Decidable using (map′) ------------------------------------------------------------------------ -- Equality module _ {a b} {A : Set a} {B : Set b} where ,-injective : ∀ {a c : A} {b d : B} → (a , b) ≡ (c , d) → a ≡ c × b ≡ d ,-injective refl = refl , refl module _ {a b} {A : Set a} {B : A → Set b} where ,-injectiveʳ : ∀ {a} {b c : B a} → (Σ A B ∋ (a , b)) ≡ (a , c) → b ≡ c ,-injectiveʳ refl = refl -- Note: this is not an instance of `_×-dec_`, because we need `x` and `y` -- to have the same type before we can test them for equality. ≡-dec : Decidable _≡_ → (∀ {a} → Decidable {A = B a} _≡_) → Decidable {A = Σ A B} _≡_ ≡-dec dec₁ dec₂ (a , x) (b , y) with dec₁ a b ... | false because [a≢b] = no (invert [a≢b] ∘ ,-injectiveˡ) ... | yes refl = map′ (cong (a ,_)) ,-injectiveʳ (dec₂ x y)
[STATEMENT] lemma kruskal_exchange_spanning_inv_1: assumes "injective ((w \<sqinter> -q) \<squnion> (w \<sqinter> q)\<^sup>T)" and "regular (w \<sqinter> q)" and "components g \<le> forest_components w" shows "components g \<le> forest_components ((w \<sqinter> -q) \<squnion> (w \<sqinter> q)\<^sup>T)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] let ?p = "w \<sqinter> q" [PROOF STATE] proof (state) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] let ?w = "(w \<sqinter> -q) \<squnion> ?p\<^sup>T" [PROOF STATE] proof (state) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] have 1: "w \<sqinter> -?p \<le> forest_components ?w" [PROOF STATE] proof (prove) goal (1 subgoal): 1. w \<sqinter> - (w \<sqinter> q) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] by (metis forest_components_increasing inf_import_p le_supE) [PROOF STATE] proof (state) this: w \<sqinter> - (w \<sqinter> q) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] have "w \<sqinter> ?p \<le> ?w\<^sup>T" [PROOF STATE] proof (prove) goal (1 subgoal): 1. w \<sqinter> (w \<sqinter> q) \<le> (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T)\<^sup>T [PROOF STEP] by (simp add: conv_dist_sup) [PROOF STATE] proof (state) this: w \<sqinter> (w \<sqinter> q) \<le> (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T)\<^sup>T goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] also [PROOF STATE] proof (state) this: w \<sqinter> (w \<sqinter> q) \<le> (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T)\<^sup>T goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] have "... \<le> forest_components ?w" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T)\<^sup>T \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] by (metis assms(1) conv_isotone forest_components_equivalence forest_components_increasing) [PROOF STATE] proof (state) this: (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T)\<^sup>T \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: w \<sqinter> (w \<sqinter> q) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] have "w \<sqinter> (?p \<squnion> -?p) \<le> forest_components ?w" [PROOF STATE] proof (prove) using this: w \<sqinter> (w \<sqinter> q) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. w \<sqinter> (w \<sqinter> q \<squnion> - (w \<sqinter> q)) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] using 1 inf_sup_distrib1 [PROOF STATE] proof (prove) using this: w \<sqinter> (w \<sqinter> q) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) w \<sqinter> - (w \<sqinter> q) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) ?x \<sqinter> (?y \<squnion> ?z) = ?x \<sqinter> ?y \<squnion> ?x \<sqinter> ?z goal (1 subgoal): 1. w \<sqinter> (w \<sqinter> q \<squnion> - (w \<sqinter> q)) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] by simp [PROOF STATE] proof (state) this: w \<sqinter> (w \<sqinter> q \<squnion> - (w \<sqinter> q)) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] hence "w \<le> forest_components ?w" [PROOF STATE] proof (prove) using this: w \<sqinter> (w \<sqinter> q \<squnion> - (w \<sqinter> q)) \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. w \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] by (metis assms(2) inf_top_right stone) [PROOF STATE] proof (state) this: w \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] hence 2: "w\<^sup>\<star> \<le> forest_components ?w" [PROOF STATE] proof (prove) using this: w \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. w\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] using assms(1) star_isotone forest_components_star [PROOF STATE] proof (prove) using this: w \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) injective (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) ?x \<le> ?y \<Longrightarrow> ?x\<^sup>\<star> \<le> ?y\<^sup>\<star> injective ?x \<Longrightarrow> forest_components ?x\<^sup>\<star> = forest_components ?x goal (1 subgoal): 1. w\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] by force [PROOF STATE] proof (state) this: w\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] hence 3: "w\<^sup>T\<^sup>\<star> \<le> forest_components ?w" [PROOF STATE] proof (prove) using this: w\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. w\<^sup>T\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] using assms(1) conv_isotone conv_star_commute forest_components_equivalence [PROOF STATE] proof (prove) using this: w\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) injective (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) ?x \<le> ?y \<Longrightarrow> ?x\<^sup>T \<le> ?y\<^sup>T ?x\<^sup>\<star>\<^sup>T = ?x\<^sup>T\<^sup>\<star> injective ?x \<Longrightarrow> equivalence (forest_components ?x) goal (1 subgoal): 1. w\<^sup>T\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] by force [PROOF STATE] proof (state) this: w\<^sup>T\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] have "components g \<le> forest_components w" [PROOF STATE] proof (prove) goal (1 subgoal): 1. components g \<le> forest_components w [PROOF STEP] using assms(3) [PROOF STATE] proof (prove) using this: components g \<le> forest_components w goal (1 subgoal): 1. components g \<le> forest_components w [PROOF STEP] by simp [PROOF STATE] proof (state) this: components g \<le> forest_components w goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] also [PROOF STATE] proof (state) this: components g \<le> forest_components w goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] have "... \<le> forest_components ?w * forest_components ?w" [PROOF STATE] proof (prove) goal (1 subgoal): 1. forest_components w \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) * forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] using 2 3 mult_isotone [PROOF STATE] proof (prove) using this: w\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) w\<^sup>T\<^sup>\<star> \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) \<lbrakk>?w \<le> ?y; ?x \<le> ?z\<rbrakk> \<Longrightarrow> ?w * ?x \<le> ?y * ?z goal (1 subgoal): 1. forest_components w \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) * forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] by simp [PROOF STATE] proof (state) this: forest_components w \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) * forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] also [PROOF STATE] proof (state) this: forest_components w \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) * forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] have "... = forest_components ?w" [PROOF STATE] proof (prove) goal (1 subgoal): 1. idempotent (forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T)) [PROOF STEP] using assms(1) forest_components_equivalence preorder_idempotent [PROOF STATE] proof (prove) using this: injective (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) injective ?x \<Longrightarrow> equivalence (forest_components ?x) preorder ?x \<Longrightarrow> idempotent ?x goal (1 subgoal): 1. idempotent (forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T)) [PROOF STEP] by simp [PROOF STATE] proof (state) this: idempotent (forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T)) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal (1 subgoal): 1. components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) [PROOF STEP] by simp [PROOF STATE] proof (state) this: components g \<le> forest_components (w \<sqinter> - q \<squnion> (w \<sqinter> q)\<^sup>T) goal: No subgoals! [PROOF STEP] qed
{-# OPTIONS --without-K --exact-split #-} module 09-fundamental-theorem where import 08-contractible-types open 08-contractible-types public -- Section 8.1 Families of equivalences {- Any family of maps induces a map on the total spaces. -} tot : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → ((x : A) → B x → C x) → ( Σ A B → Σ A C) tot f t = pair (pr1 t) (f (pr1 t) (pr2 t)) {- We show that for any family of maps, the fiber of the induced map on total spaces are equivalent to the fibers of the maps in the family. -} fib-ftr-fib-tot : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → (f : (x : A) → B x → C x) → (t : Σ A C) → fib (tot f) t → fib (f (pr1 t)) (pr2 t) fib-ftr-fib-tot f .(pair x (f x y)) (pair (pair x y) refl) = pair y refl fib-tot-fib-ftr : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → (f : (x : A) → B x → C x) → (t : Σ A C) → fib (f (pr1 t)) (pr2 t) → fib (tot f) t fib-tot-fib-ftr F (pair a .(F a y)) (pair y refl) = pair (pair a y) refl issec-fib-tot-fib-ftr : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → (f : (x : A) → B x → C x) → (t : Σ A C) → ((fib-ftr-fib-tot f t) ∘ (fib-tot-fib-ftr f t)) ~ id issec-fib-tot-fib-ftr f (pair x .(f x y)) (pair y refl) = refl isretr-fib-tot-fib-ftr : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → (f : (x : A) → B x → C x) → (t : Σ A C) → ((fib-tot-fib-ftr f t) ∘ (fib-ftr-fib-tot f t)) ~ id isretr-fib-tot-fib-ftr f .(pair x (f x y)) (pair (pair x y) refl) = refl abstract is-equiv-fib-ftr-fib-tot : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → (f : (x : A) → B x → C x) → (t : Σ A C) → is-equiv (fib-ftr-fib-tot f t) is-equiv-fib-ftr-fib-tot f t = is-equiv-has-inverse ( fib-tot-fib-ftr f t) ( issec-fib-tot-fib-ftr f t) ( isretr-fib-tot-fib-ftr f t) abstract is-equiv-fib-tot-fib-ftr : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → (f : (x : A) → B x → C x) → (t : Σ A C) → is-equiv (fib-tot-fib-ftr f t) is-equiv-fib-tot-fib-ftr f t = is-equiv-has-inverse ( fib-ftr-fib-tot f t) ( isretr-fib-tot-fib-ftr f t) ( issec-fib-tot-fib-ftr f t) {- Now that we have shown that the fibers of the induced map on total spaces are equivalent to the fibers of the maps in the family, it follows that the induced map on total spaces is an equivalence if and only if each map in the family is an equivalence. -} is-fiberwise-equiv : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → ((x : A) → B x → C x) → UU (i ⊔ (j ⊔ k)) is-fiberwise-equiv f = (x : _) → is-equiv (f x) abstract is-equiv-tot-is-fiberwise-equiv : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → {f : (x : A) → B x → C x} → is-fiberwise-equiv f → is-equiv (tot f ) is-equiv-tot-is-fiberwise-equiv {f = f} H = is-equiv-is-contr-map ( λ t → is-contr-is-equiv _ ( fib-ftr-fib-tot f t) ( is-equiv-fib-ftr-fib-tot f t) ( is-contr-map-is-equiv (H _) (pr2 t))) abstract is-fiberwise-equiv-is-equiv-tot : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → (f : (x : A) → B x → C x) → is-equiv (tot f) → is-fiberwise-equiv f is-fiberwise-equiv-is-equiv-tot {A = A} {B} {C} f is-equiv-tot-f x = is-equiv-is-contr-map ( λ z → is-contr-is-equiv' ( fib (tot f) (pair x z)) ( fib-ftr-fib-tot f (pair x z)) ( is-equiv-fib-ftr-fib-tot f (pair x z)) ( is-contr-map-is-equiv is-equiv-tot-f (pair x z))) equiv-tot : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} → ((x : A) → B x ≃ C x) → (Σ A B) ≃ (Σ A C) equiv-tot e = pair ( tot (λ x → map-equiv (e x))) ( is-equiv-tot-is-fiberwise-equiv (λ x → is-equiv-map-equiv (e x))) {- In the second part of this section we show that any equivalence f on base types also induces an equivalence on total spaces. -} Σ-map-base-map : { l1 l2 l3 : Level} {A : UU l1} {B : UU l2} (f : A → B) (C : B → UU l3) → Σ A (λ x → C (f x)) → Σ B C Σ-map-base-map f C s = pair (f (pr1 s)) (pr2 s) {- The proof is similar to the previous part: we show that the fibers of f and Σ-kap-base-map f C are equivalent. -} fib-Σ-map-base-map-fib : { l1 l2 l3 : Level} {A : UU l1} {B : UU l2} (f : A → B) (C : B → UU l3) → ( t : Σ B C) → fib f (pr1 t) → fib (Σ-map-base-map f C) t fib-Σ-map-base-map-fib f C (pair .(f x) z) (pair x refl) = pair (pair x z) refl fib-fib-Σ-map-base-map : { l1 l2 l3 : Level} {A : UU l1} {B : UU l2} (f : A → B) (C : B → UU l3) → ( t : Σ B C) → fib (Σ-map-base-map f C) t → fib f (pr1 t) fib-fib-Σ-map-base-map f C .(pair (f x) z) (pair (pair x z) refl) = pair x refl issec-fib-fib-Σ-map-base-map : { l1 l2 l3 : Level} {A : UU l1} {B : UU l2} (f : A → B) (C : B → UU l3) → ( t : Σ B C) → ( (fib-Σ-map-base-map-fib f C t) ∘ (fib-fib-Σ-map-base-map f C t)) ~ id issec-fib-fib-Σ-map-base-map f C .(pair (f x) z) (pair (pair x z) refl) = refl isretr-fib-fib-Σ-map-base-map : { l1 l2 l3 : Level} {A : UU l1} {B : UU l2} (f : A → B) (C : B → UU l3) → ( t : Σ B C) → ( (fib-fib-Σ-map-base-map f C t) ∘ (fib-Σ-map-base-map-fib f C t)) ~ id isretr-fib-fib-Σ-map-base-map f C (pair .(f x) z) (pair x refl) = refl abstract is-equiv-fib-Σ-map-base-map-fib : { l1 l2 l3 : Level} {A : UU l1} {B : UU l2} (f : A → B) (C : B → UU l3) → ( t : Σ B C) → is-equiv (fib-Σ-map-base-map-fib f C t) is-equiv-fib-Σ-map-base-map-fib f C t = is-equiv-has-inverse ( fib-fib-Σ-map-base-map f C t) ( issec-fib-fib-Σ-map-base-map f C t) ( isretr-fib-fib-Σ-map-base-map f C t) abstract is-contr-map-Σ-map-base-map : {l1 l2 l3 : Level} {A : UU l1} {B : UU l2} (C : B → UU l3) (f : A → B) → is-contr-map f → is-contr-map (Σ-map-base-map f C) is-contr-map-Σ-map-base-map C f is-contr-f (pair y z) = is-contr-is-equiv' ( fib f y) ( fib-Σ-map-base-map-fib f C (pair y z)) ( is-equiv-fib-Σ-map-base-map-fib f C (pair y z)) ( is-contr-f y) abstract is-equiv-Σ-map-base-map : {l1 l2 l3 : Level} {A : UU l1} {B : UU l2} (C : B → UU l3) (f : A → B) → is-equiv f → is-equiv (Σ-map-base-map f C) is-equiv-Σ-map-base-map C f is-equiv-f = is-equiv-is-contr-map ( is-contr-map-Σ-map-base-map C f (is-contr-map-is-equiv is-equiv-f)) {- Now we combine the two parts of this section. -} toto : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : A → UU l3} (D : B → UU l4) (f : A → B) (g : (x : A) → C x → D (f x)) → Σ A C → Σ B D toto D f g t = pair (f (pr1 t)) (g (pr1 t) (pr2 t)) {- A special case of toto is the functoriality of the cartesian product. -} {- We construct the functoriality of cartesian products. -} functor-prod : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} (f : A → C) (g : B → D) → (A × B) → (C × D) functor-prod f g (pair a b) = pair (f a) (g b) functor-prod-pr1 : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} (f : A → C) (g : B → D) → (pr1 ∘ (functor-prod f g)) ~ (f ∘ pr1) functor-prod-pr1 f g (pair a b) = refl functor-prod-pr2 : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} (f : A → C) (g : B → D) → (pr2 ∘ (functor-prod f g)) ~ (g ∘ pr2) functor-prod-pr2 f g (pair a b) = refl {- For our convenience we show that the functorial action of cartesian products preserves identity maps, compositions, homotopies, and equivalences. -} functor-prod-id : {l1 l2 : Level} {A : UU l1} {B : UU l2} → (functor-prod (id {A = A}) (id {A = B})) ~ id functor-prod-id (pair a b) = refl functor-prod-comp : {l1 l2 l3 l4 l5 l6 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} {E : UU l5} {F : UU l6} (f : A → C) (g : B → D) (h : C → E) (k : D → F) → functor-prod (h ∘ f) (k ∘ g) ~ ((functor-prod h k) ∘ (functor-prod f g)) functor-prod-comp f g h k (pair a b) = refl functor-prod-htpy : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} {f f' : A → C} (H : f ~ f') {g g' : B → D} (K : g ~ g') → functor-prod f g ~ functor-prod f' g' functor-prod-htpy {f = f} {f'} H {g} {g'} K (pair a b) = eq-pair-triv (pair (H a) (K b)) abstract is-equiv-functor-prod : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} (f : A → C) (g : B → D) → is-equiv f → is-equiv g → is-equiv (functor-prod f g) is-equiv-functor-prod f g ( pair (pair sf issec-sf) (pair rf isretr-rf)) ( pair (pair sg issec-sg) (pair rg isretr-rg)) = pair ( pair ( functor-prod sf sg) ( ( htpy-inv (functor-prod-comp sf sg f g)) ∙h ( (functor-prod-htpy issec-sf issec-sg) ∙h functor-prod-id))) ( pair ( functor-prod rf rg) ( ( htpy-inv (functor-prod-comp f g rf rg)) ∙h ( (functor-prod-htpy isretr-rf isretr-rg) ∙h functor-prod-id))) {- triangle -} triangle-toto : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : A → UU l3} (D : B → UU l4) (f : A → B) (g : (x : A) → C x → D (f x)) → (toto D f g) ~ ((Σ-map-base-map f D) ∘ (tot g)) triangle-toto D f g t = refl abstract is-equiv-toto-is-fiberwise-equiv-is-equiv-base-map : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : A → UU l3} (D : B → UU l4) (f : A → B) (g : (x : A) → C x → D (f x)) → is-equiv f → (is-fiberwise-equiv g) → is-equiv (toto D f g) is-equiv-toto-is-fiberwise-equiv-is-equiv-base-map D f g is-equiv-f is-fiberwise-equiv-g = is-equiv-comp ( toto D f g) ( Σ-map-base-map f D) ( tot g) ( triangle-toto D f g) ( is-equiv-tot-is-fiberwise-equiv is-fiberwise-equiv-g) ( is-equiv-Σ-map-base-map D f is-equiv-f) equiv-toto : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : A → UU l3} (D : B → UU l4) (e : A ≃ B) (g : (x : A) → C x ≃ D (map-equiv e x)) → Σ A C ≃ Σ B D equiv-toto D e g = pair ( toto D (map-equiv e) (λ x → map-equiv (g x))) ( is-equiv-toto-is-fiberwise-equiv-is-equiv-base-map D ( map-equiv e) ( λ x → map-equiv (g x)) ( is-equiv-map-equiv e) ( λ x → is-equiv-map-equiv (g x))) abstract is-fiberwise-equiv-is-equiv-toto-is-equiv-base-map : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : A → UU l3} (D : B → UU l4) (f : A → B) (g : (x : A) → C x → D (f x)) → is-equiv f → is-equiv (toto D f g) → is-fiberwise-equiv g is-fiberwise-equiv-is-equiv-toto-is-equiv-base-map D f g is-equiv-f is-equiv-toto-fg = is-fiberwise-equiv-is-equiv-tot g ( is-equiv-right-factor ( toto D f g) ( Σ-map-base-map f D) ( tot g) ( triangle-toto D f g) ( is-equiv-Σ-map-base-map D f is-equiv-f) ( is-equiv-toto-fg)) -- Section 8.2 The fundamental theorem -- The general form of the fundamental theorem of identity types abstract fundamental-theorem-id : {i j : Level} {A : UU i} {B : A → UU j} (a : A) (b : B a) → is-contr (Σ A B) → (f : (x : A) → Id a x → B x) → is-fiberwise-equiv f fundamental-theorem-id {A = A} a b is-contr-AB f = is-fiberwise-equiv-is-equiv-tot f ( is-equiv-is-contr (tot f) (is-contr-total-path a) is-contr-AB) abstract fundamental-theorem-id' : {i j : Level} {A : UU i} {B : A → UU j} (a : A) (b : B a) (f : (x : A) → Id a x → B x) → is-fiberwise-equiv f → is-contr (Σ A B) fundamental-theorem-id' {A = A} {B = B} a b f is-fiberwise-equiv-f = is-contr-is-equiv' ( Σ A (Id a)) ( tot f) ( is-equiv-tot-is-fiberwise-equiv is-fiberwise-equiv-f) ( is-contr-total-path a) -- The canonical form of the fundamental theorem of identity types abstract fundamental-theorem-id-J : {i j : Level} {A : UU i} {B : A → UU j} (a : A) (b : B a) → is-contr (Σ A B) → is-fiberwise-equiv (ind-Id a (λ x p → B x) b) fundamental-theorem-id-J {i} {j} {A} {B} a b is-contr-AB = fundamental-theorem-id a b is-contr-AB (ind-Id a (λ x p → B x) b) -- The converse of the fundamental theorem of identity types abstract fundamental-theorem-id-J' : {i j : Level} {A : UU i} {B : A → UU j} (a : A) (b : B a) → (is-fiberwise-equiv (ind-Id a (λ x p → B x) b)) → is-contr (Σ A B) fundamental-theorem-id-J' {i} {j} {A} {B} a b H = is-contr-is-equiv' ( Σ A (Id a)) ( tot (ind-Id a (λ x p → B x) b)) ( is-equiv-tot-is-fiberwise-equiv H) ( is-contr-total-path a) -- As an application we show that equivalences are embeddings. is-emb : {i j : Level} {A : UU i} {B : UU j} (f : A → B) → UU (i ⊔ j) is-emb f = (x y : _) → is-equiv (ap f {x} {y}) _↪_ : {i j : Level} → UU i → UU j → UU (i ⊔ j) A ↪ B = Σ (A → B) is-emb map-emb : {i j : Level} {A : UU i} {B : UU j} → A ↪ B → A → B map-emb f = pr1 f is-emb-map-emb : { i j : Level} {A : UU i} {B : UU j} (f : A ↪ B) → is-emb (map-emb f) is-emb-map-emb f = pr2 f abstract is-emb-is-equiv : {i j : Level} {A : UU i} {B : UU j} (f : A → B) → is-equiv f → is-emb f is-emb-is-equiv {i} {j} {A} {B} f is-equiv-f x = fundamental-theorem-id x refl ( is-contr-equiv ( fib f (f x)) ( equiv-tot (λ y → equiv-inv (f x) (f y))) ( is-contr-map-is-equiv is-equiv-f (f x))) ( λ y p → ap f p) equiv-ap : {i j : Level} {A : UU i} {B : UU j} (e : A ≃ B) (x y : A) → (Id x y) ≃ (Id (map-equiv e x) (map-equiv e y)) equiv-ap e x y = pair ( ap (map-equiv e) {x} {y}) ( is-emb-is-equiv (map-equiv e) (is-equiv-map-equiv e) x y) -- Section 7.3 Identity systems IND-identity-system : {i j : Level} (k : Level) {A : UU i} (B : A → UU j) (a : A) (b : B a) → UU _ IND-identity-system k {A} B a b = ( P : (x : A) (y : B x) → UU k) → sec (λ (h : (x : A) (y : B x) → P x y) → h a b) fam-Σ : {i j k : Level} {A : UU i} {B : A → UU j} (C : (x : A) → B x → UU k) → Σ A B → UU k fam-Σ C (pair x y) = C x y abstract ind-identity-system : {i j k : Level} {A : UU i} {B : A → UU j} (a : A) (b : B a) → (is-contr-AB : is-contr (Σ A B)) (P : (x : A) → B x → UU k) → P a b → (x : A) (y : B x) → P x y ind-identity-system a b is-contr-AB P p x y = tr ( fam-Σ P) ( is-prop-is-contr' is-contr-AB (pair a b) (pair x y)) ( p) comp-identity-system : {i j k : Level} {A : UU i} {B : A → UU j} (a : A) (b : B a) → (is-contr-AB : is-contr (Σ A B)) → (P : (x : A) → B x → UU k) (p : P a b) → Id (ind-identity-system a b is-contr-AB P p a b) p comp-identity-system a b is-contr-AB P p = ap ( λ t → tr (fam-Σ P) t p) ( is-prop-is-contr' ( is-prop-is-contr is-contr-AB (pair a b) (pair a b)) ( is-prop-is-contr' is-contr-AB (pair a b) (pair a b)) ( refl)) Ind-identity-system : {i j : Level} (k : Level) {A : UU i} {B : A → UU j} (a : A) (b : B a) → (is-contr-AB : is-contr (Σ A B)) → IND-identity-system k B a b Ind-identity-system k a b is-contr-AB P = pair ( ind-identity-system a b is-contr-AB P) ( comp-identity-system a b is-contr-AB P) contraction-total-space-IND-identity-system : {i j : Level} {A : UU i} {B : A → UU j} (a : A) (b : B a) → IND-identity-system (i ⊔ j) B a b → (t : Σ A B) → Id (pair a b) t contraction-total-space-IND-identity-system a b ind (pair x y) = pr1 (ind (λ x' y' → Id (pair a b) (pair x' y'))) refl x y abstract is-contr-total-space-IND-identity-system : {i j : Level} {A : UU i} {B : A → UU j} (a : A) (b : B a) → IND-identity-system (i ⊔ j) B a b → is-contr (Σ A B) is-contr-total-space-IND-identity-system a b ind = pair ( pair a b) ( contraction-total-space-IND-identity-system a b ind) abstract fundamental-theorem-id-IND-identity-system : {i j : Level} {A : UU i} {B : A → UU j} (a : A) (b : B a) → IND-identity-system (i ⊔ j) B a b → (f : (x : A) → Id a x → B x) → (x : A) → is-equiv (f x) fundamental-theorem-id-IND-identity-system a b ind f = fundamental-theorem-id a b (is-contr-total-space-IND-identity-system a b ind) f -- Section 7.4 Disjointness of coproducts -- Raising universe levels postulate Raise : {l1 : Level} (l2 : Level) → (A : UU l1) → Σ (UU (l1 ⊔ l2)) (λ X → A ≃ X) abstract raise : {l1 : Level} (l2 : Level) → UU l1 → UU (l1 ⊔ l2) raise l2 A = pr1 (Raise l2 A) equiv-raise : {l1 : Level} (l2 : Level) (A : UU l1) → A ≃ raise l2 A equiv-raise l2 A = pr2 (Raise l2 A) map-raise : {l1 : Level} (l2 : Level) (A : UU l1) → A → raise l2 A map-raise l2 A = map-equiv (equiv-raise l2 A) is-equiv-map-raise : {l1 : Level} (l2 : Level) (A : UU l1) → is-equiv (map-raise l2 A) is-equiv-map-raise l2 A = is-equiv-map-equiv (equiv-raise l2 A) -- Lemmas about coproducts left-distributive-coprod-Σ-map : {l1 l2 l3 : Level} (A : UU l1) (B : UU l2) (C : coprod A B → UU l3) → Σ (coprod A B) C → coprod (Σ A (λ x → C (inl x))) (Σ B (λ y → C (inr y))) left-distributive-coprod-Σ-map A B C (pair (inl x) z) = inl (pair x z) left-distributive-coprod-Σ-map A B C (pair (inr y) z) = inr (pair y z) inv-left-distributive-coprod-Σ-map : {l1 l2 l3 : Level} (A : UU l1) (B : UU l2) (C : coprod A B → UU l3) → coprod (Σ A (λ x → C (inl x))) (Σ B (λ y → C (inr y))) → Σ (coprod A B) C inv-left-distributive-coprod-Σ-map A B C (inl (pair x z)) = pair (inl x) z inv-left-distributive-coprod-Σ-map A B C (inr (pair y z)) = pair (inr y) z issec-inv-left-distributive-coprod-Σ-map : {l1 l2 l3 : Level} (A : UU l1) (B : UU l2) (C : coprod A B → UU l3) → ( (left-distributive-coprod-Σ-map A B C) ∘ (inv-left-distributive-coprod-Σ-map A B C)) ~ id issec-inv-left-distributive-coprod-Σ-map A B C (inl (pair x z)) = refl issec-inv-left-distributive-coprod-Σ-map A B C (inr (pair y z)) = refl isretr-inv-left-distributive-coprod-Σ-map : {l1 l2 l3 : Level} (A : UU l1) (B : UU l2) (C : coprod A B → UU l3) → ( (inv-left-distributive-coprod-Σ-map A B C) ∘ (left-distributive-coprod-Σ-map A B C)) ~ id isretr-inv-left-distributive-coprod-Σ-map A B C (pair (inl x) z) = refl isretr-inv-left-distributive-coprod-Σ-map A B C (pair (inr y) z) = refl abstract is-equiv-left-distributive-coprod-Σ-map : {l1 l2 l3 : Level} (A : UU l1) (B : UU l2) (C : coprod A B → UU l3) → is-equiv (left-distributive-coprod-Σ-map A B C) is-equiv-left-distributive-coprod-Σ-map A B C = is-equiv-has-inverse ( inv-left-distributive-coprod-Σ-map A B C) ( issec-inv-left-distributive-coprod-Σ-map A B C) ( isretr-inv-left-distributive-coprod-Σ-map A B C) equiv-left-distributive-coprod-Σ : {l1 l2 l3 : Level} (A : UU l1) (B : UU l2) (C : coprod A B → UU l3) → Σ (coprod A B) C ≃ coprod (Σ A (λ x → C (inl x))) (Σ B (λ y → C (inr y))) equiv-left-distributive-coprod-Σ A B C = pair ( left-distributive-coprod-Σ-map A B C) ( is-equiv-left-distributive-coprod-Σ-map A B C) abstract is-equiv-map-to-empty : {l : Level} {A : UU l} (f : A → empty) → is-equiv f is-equiv-map-to-empty f = is-equiv-has-inverse ind-empty ind-empty ( λ x → ind-empty {P = λ t → Id (ind-empty (f x)) x} (f x)) map-Σ-empty-fam : {l : Level} (A : UU l) → Σ A (λ x → empty) → empty map-Σ-empty-fam A (pair x ()) abstract is-equiv-map-Σ-empty-fam : {l : Level} (A : UU l) → is-equiv (map-Σ-empty-fam A) is-equiv-map-Σ-empty-fam A = is-equiv-map-to-empty (map-Σ-empty-fam A) equiv-Σ-empty-fam : {l : Level} (A : UU l) → Σ A (λ x → empty) ≃ empty equiv-Σ-empty-fam A = pair (map-Σ-empty-fam A) (is-equiv-map-Σ-empty-fam A) -- The identity types of coproducts Eq-coprod : {l1 l2 : Level} (A : UU l1) (B : UU l2) → coprod A B → coprod A B → UU (l1 ⊔ l2) Eq-coprod {l1} {l2} A B (inl x) (inl y) = raise (l1 ⊔ l2) (Id x y) Eq-coprod {l1} {l2} A B (inl x) (inr y) = raise (l1 ⊔ l2) empty Eq-coprod {l1} {l2} A B (inr x) (inl y) = raise (l1 ⊔ l2) empty Eq-coprod {l1} {l2} A B (inr x) (inr y) = raise (l1 ⊔ l2) (Id x y) reflexive-Eq-coprod : {l1 l2 : Level} (A : UU l1) (B : UU l2) → (t : coprod A B) → Eq-coprod A B t t reflexive-Eq-coprod {l1} {l2} A B (inl x) = map-raise (l1 ⊔ l2) (Id x x) refl reflexive-Eq-coprod {l1} {l2} A B (inr x) = map-raise (l1 ⊔ l2) (Id x x) refl Eq-coprod-eq : {l1 l2 : Level} (A : UU l1) (B : UU l2) → (s t : coprod A B) → Id s t → Eq-coprod A B s t Eq-coprod-eq A B s .s refl = reflexive-Eq-coprod A B s abstract is-contr-total-Eq-coprod-inl : {l1 l2 : Level} (A : UU l1) (B : UU l2) (x : A) → is-contr (Σ (coprod A B) (Eq-coprod A B (inl x))) is-contr-total-Eq-coprod-inl A B x = is-contr-equiv ( coprod ( Σ A (λ y → Eq-coprod A B (inl x) (inl y))) ( Σ B (λ y → Eq-coprod A B (inl x) (inr y)))) ( equiv-left-distributive-coprod-Σ A B (Eq-coprod A B (inl x))) ( is-contr-equiv' ( coprod ( Σ A (Id x)) ( Σ B (λ y → empty))) ( equiv-functor-coprod ( equiv-tot (λ y → equiv-raise _ (Id x y))) ( equiv-tot (λ y → equiv-raise _ empty))) ( is-contr-equiv ( coprod (Σ A (Id x)) empty) ( equiv-functor-coprod ( equiv-id (Σ A (Id x))) ( equiv-Σ-empty-fam B)) ( is-contr-equiv' ( Σ A (Id x)) ( right-unit-law-coprod (Σ A (Id x))) ( is-contr-total-path x)))) abstract is-contr-total-Eq-coprod-inr : {l1 l2 : Level} (A : UU l1) (B : UU l2) (x : B) → is-contr (Σ (coprod A B) (Eq-coprod A B (inr x))) is-contr-total-Eq-coprod-inr A B x = is-contr-equiv ( coprod ( Σ A (λ y → Eq-coprod A B (inr x) (inl y))) ( Σ B (λ y → Eq-coprod A B (inr x) (inr y)))) ( equiv-left-distributive-coprod-Σ A B (Eq-coprod A B (inr x))) ( is-contr-equiv' ( coprod (Σ A (λ y → empty)) (Σ B (Id x))) ( equiv-functor-coprod ( equiv-tot (λ y → equiv-raise _ empty)) ( equiv-tot (λ y → equiv-raise _ (Id x y)))) ( is-contr-equiv ( coprod empty (Σ B (Id x))) ( equiv-functor-coprod ( equiv-Σ-empty-fam A) ( equiv-id (Σ B (Id x)))) ( is-contr-equiv' ( Σ B (Id x)) ( left-unit-law-coprod (Σ B (Id x))) ( is-contr-total-path x)))) abstract is-equiv-Eq-coprod-eq-inl : {l1 l2 : Level} (A : UU l1) (B : UU l2) (x : A) → is-fiberwise-equiv (Eq-coprod-eq A B (inl x)) is-equiv-Eq-coprod-eq-inl A B x = fundamental-theorem-id ( inl x) ( reflexive-Eq-coprod A B (inl x)) ( is-contr-total-Eq-coprod-inl A B x) ( Eq-coprod-eq A B (inl x)) abstract is-equiv-Eq-coprod-eq-inr : {l1 l2 : Level} (A : UU l1) (B : UU l2) (x : B) → is-fiberwise-equiv (Eq-coprod-eq A B (inr x)) is-equiv-Eq-coprod-eq-inr A B x = fundamental-theorem-id ( inr x) ( reflexive-Eq-coprod A B (inr x)) ( is-contr-total-Eq-coprod-inr A B x) ( Eq-coprod-eq A B (inr x)) abstract is-equiv-Eq-coprod-eq : {l1 l2 : Level} (A : UU l1) (B : UU l2) (s : coprod A B) → is-fiberwise-equiv (Eq-coprod-eq A B s) is-equiv-Eq-coprod-eq A B (inl x) = is-equiv-Eq-coprod-eq-inl A B x is-equiv-Eq-coprod-eq A B (inr x) = is-equiv-Eq-coprod-eq-inr A B x map-compute-eq-coprod-inl-inl : {l1 l2 : Level} {A : UU l1} {B : UU l2} (x x' : A) → Id (inl {B = B} x) (inl {B = B} x') → Id x x' map-compute-eq-coprod-inl-inl x x' = ( inv-is-equiv (is-equiv-map-raise _ (Id x x'))) ∘ ( Eq-coprod-eq _ _ (inl x) (inl x')) abstract is-equiv-map-compute-eq-coprod-inl-inl : {l1 l2 : Level} {A : UU l1} {B : UU l2} (x x' : A) → is-equiv (map-compute-eq-coprod-inl-inl {B = B} x x') is-equiv-map-compute-eq-coprod-inl-inl x x' = is-equiv-comp ( map-compute-eq-coprod-inl-inl x x') ( inv-is-equiv (is-equiv-map-raise _ (Id x x'))) ( Eq-coprod-eq _ _ (inl x) (inl x')) ( refl-htpy) ( is-equiv-Eq-coprod-eq _ _ (inl x) (inl x')) ( is-equiv-inv-is-equiv (is-equiv-map-raise _ (Id x x'))) compute-eq-coprod-inl-inl : {l1 l2 : Level} {A : UU l1} {B : UU l2} (x x' : A) → (Id (inl {B = B} x) (inl x')) ≃ (Id x x') compute-eq-coprod-inl-inl x x' = pair ( map-compute-eq-coprod-inl-inl x x') ( is-equiv-map-compute-eq-coprod-inl-inl x x') map-compute-eq-coprod-inl-inr : {l1 l2 : Level} {A : UU l1} {B : UU l2} (x : A) (y' : B) → Id (inl x) (inr y') → empty map-compute-eq-coprod-inl-inr x y' = ( inv-is-equiv (is-equiv-map-raise _ empty)) ∘ ( Eq-coprod-eq _ _ (inl x) (inr y')) abstract is-equiv-map-compute-eq-coprod-inl-inr : {l1 l2 : Level} {A : UU l1} {B : UU l2} (x : A) (y' : B) → is-equiv (map-compute-eq-coprod-inl-inr x y') is-equiv-map-compute-eq-coprod-inl-inr x y' = is-equiv-comp ( map-compute-eq-coprod-inl-inr x y') ( inv-is-equiv (is-equiv-map-raise _ empty)) ( Eq-coprod-eq _ _ (inl x) (inr y')) ( refl-htpy) ( is-equiv-Eq-coprod-eq _ _ (inl x) (inr y')) ( is-equiv-inv-is-equiv (is-equiv-map-raise _ empty)) compute-eq-coprod-inl-inr : {l1 l2 : Level} {A : UU l1} {B : UU l2} (x : A) (y' : B) → (Id (inl x) (inr y')) ≃ empty compute-eq-coprod-inl-inr x y' = pair ( map-compute-eq-coprod-inl-inr x y') ( is-equiv-map-compute-eq-coprod-inl-inr x y') map-compute-eq-coprod-inr-inl : {l1 l2 : Level} {A : UU l1} {B : UU l2} (y : B) (x' : A) → (Id (inr {A = A} y) (inl x')) → empty map-compute-eq-coprod-inr-inl y x' = ( inv-is-equiv (is-equiv-map-raise _ empty)) ∘ ( Eq-coprod-eq _ _ (inr y) (inl x')) abstract is-equiv-map-compute-eq-coprod-inr-inl : {l1 l2 : Level} {A : UU l1} {B : UU l2} (y : B) (x' : A) → is-equiv (map-compute-eq-coprod-inr-inl y x') is-equiv-map-compute-eq-coprod-inr-inl y x' = is-equiv-comp ( map-compute-eq-coprod-inr-inl y x') ( inv-is-equiv (is-equiv-map-raise _ empty)) ( Eq-coprod-eq _ _ (inr y) (inl x')) ( refl-htpy) ( is-equiv-Eq-coprod-eq _ _ (inr y) (inl x')) ( is-equiv-inv-is-equiv (is-equiv-map-raise _ empty)) compute-eq-coprod-inr-inl : {l1 l2 : Level} {A : UU l1} {B : UU l2} (y : B) (x' : A) → (Id (inr y) (inl x')) ≃ empty compute-eq-coprod-inr-inl y x' = pair ( map-compute-eq-coprod-inr-inl y x') ( is-equiv-map-compute-eq-coprod-inr-inl y x') map-compute-eq-coprod-inr-inr : {l1 l2 : Level} {A : UU l1} {B : UU l2} (y y' : B) → (Id (inr {A = A} y) (inr y')) → Id y y' map-compute-eq-coprod-inr-inr y y' = ( inv-is-equiv (is-equiv-map-raise _ (Id y y'))) ∘ ( Eq-coprod-eq _ _ (inr y) (inr y')) abstract is-equiv-map-compute-eq-coprod-inr-inr : {l1 l2 : Level} {A : UU l1} {B : UU l2} (y y' : B) → is-equiv (map-compute-eq-coprod-inr-inr {A = A} y y') is-equiv-map-compute-eq-coprod-inr-inr y y' = is-equiv-comp ( map-compute-eq-coprod-inr-inr y y') ( inv-is-equiv (is-equiv-map-raise _ (Id y y'))) ( Eq-coprod-eq _ _ (inr y) (inr y')) ( refl-htpy) ( is-equiv-Eq-coprod-eq _ _ (inr y) (inr y')) ( is-equiv-inv-is-equiv (is-equiv-map-raise _ (Id y y'))) compute-eq-coprod-inr-inr : {l1 l2 : Level} {A : UU l1} {B : UU l2} (y y' : B) → (Id (inr {A = A} y) (inr y')) ≃ (Id y y') compute-eq-coprod-inr-inr y y' = pair ( map-compute-eq-coprod-inr-inr y y') ( is-equiv-map-compute-eq-coprod-inr-inr y y') -- Exercises -- Exercise 7.1 abstract is-emb-empty : {i : Level} (A : UU i) → is-emb (ind-empty {P = λ x → A}) is-emb-empty A = ind-empty -- Exercise 7.2 path-adjointness-equiv : {i j : Level} {A : UU i} {B : UU j} (e : A ≃ B) (x : A) (y : B) → (Id (map-equiv e x) y) ≃ (Id x (inv-map-equiv e y)) path-adjointness-equiv e x y = ( inv-equiv (equiv-ap e x (inv-map-equiv e y))) ∘e ( equiv-concat' ( map-equiv e x) ( inv (issec-inv-is-equiv (is-equiv-map-equiv e) y))) -- Exercise 7.3 abstract is-equiv-top-is-equiv-left-square : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} (f : A → B) (g : C → D) (h : A → C) (i : B → D) (H : (i ∘ f) ~ (g ∘ h)) → is-equiv i → is-equiv f → is-equiv g → is-equiv h is-equiv-top-is-equiv-left-square f g h i H Ei Ef Eg = is-equiv-right-factor (i ∘ f) g h H Eg ( is-equiv-comp (i ∘ f) i f refl-htpy Ef Ei) abstract is-emb-htpy : {i j : Level} {A : UU i} {B : UU j} (f g : A → B) → (f ~ g) → is-emb g → is-emb f is-emb-htpy f g H is-emb-g x y = is-equiv-top-is-equiv-left-square ( ap g) ( concat' (f x) (H y)) ( ap f) ( concat (H x) (g y)) ( htpy-nat H) ( is-equiv-concat (H x) (g y)) ( is-emb-g x y) ( is-equiv-concat' (f x) (H y)) abstract is-emb-htpy' : {i j : Level} {A : UU i} {B : UU j} (f g : A → B) → (f ~ g) → is-emb f → is-emb g is-emb-htpy' f g H is-emb-f = is-emb-htpy g f (htpy-inv H) is-emb-f -- Exercise 7.4 abstract is-emb-comp : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → is-emb g → is-emb h → is-emb f is-emb-comp f g h H is-emb-g is-emb-h = is-emb-htpy f (g ∘ h) H ( λ x y → is-equiv-comp (ap (g ∘ h)) (ap g) (ap h) (ap-comp g h) ( is-emb-h x y) ( is-emb-g (h x) (h y))) abstract is-emb-right-factor : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → is-emb g → is-emb f → is-emb h is-emb-right-factor f g h H is-emb-g is-emb-f x y = is-equiv-right-factor ( ap (g ∘ h)) ( ap g) ( ap h) ( ap-comp g h) ( is-emb-g (h x) (h y)) ( is-emb-htpy (g ∘ h) f (htpy-inv H) is-emb-f x y) abstract is-emb-triangle-is-equiv : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (e : A → B) (H : f ~ (g ∘ e)) → is-equiv e → is-emb g → is-emb f is-emb-triangle-is-equiv f g e H is-equiv-e is-emb-g = is-emb-comp f g e H is-emb-g (is-emb-is-equiv e is-equiv-e) abstract is-emb-triangle-is-equiv' : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (e : A → B) (H : f ~ (g ∘ e)) → is-equiv e → is-emb f → is-emb g is-emb-triangle-is-equiv' f g e H is-equiv-e is-emb-f = is-emb-triangle-is-equiv g f ( inv-is-equiv is-equiv-e) ( triangle-section f g e H ( pair ( inv-is-equiv is-equiv-e) ( issec-inv-is-equiv is-equiv-e))) ( is-equiv-inv-is-equiv is-equiv-e) ( is-emb-f) -- Exercise 7.5 abstract is-emb-inl : {i j : Level} (A : UU i) (B : UU j) → is-emb (inl {A = A} {B = B}) is-emb-inl A B x = fundamental-theorem-id x refl ( is-contr-is-equiv ( Σ A (λ y → Eq-coprod A B (inl x) (inl y))) ( tot (λ y → Eq-coprod-eq A B (inl x) (inl y))) ( is-equiv-tot-is-fiberwise-equiv ( λ y → is-equiv-Eq-coprod-eq A B (inl x) (inl y))) ( is-contr-equiv' ( Σ A (Id x)) ( equiv-tot (λ y → equiv-raise _ (Id x y))) ( is-contr-total-path x))) ( λ y → ap inl) abstract is-emb-inr : {i j : Level} (A : UU i) (B : UU j) → is-emb (inr {A = A} {B = B}) is-emb-inr A B x = fundamental-theorem-id x refl ( is-contr-is-equiv ( Σ B (λ y → Eq-coprod A B (inr x) (inr y))) ( tot (λ y → Eq-coprod-eq A B (inr x) (inr y))) ( is-equiv-tot-is-fiberwise-equiv ( λ y → is-equiv-Eq-coprod-eq A B (inr x) (inr y))) ( is-contr-equiv' ( Σ B (Id x)) ( equiv-tot (λ y → equiv-raise _ (Id x y))) ( is-contr-total-path x))) ( λ y → ap inr) -- Exercise 7.6 -- Exercise 7.7 tot-htpy : {i j k : Level} {A : UU i} {B : A → UU j} {C : A → UU k} {f g : (x : A) → B x → C x} → (H : (x : A) → f x ~ g x) → tot f ~ tot g tot-htpy H (pair x y) = eq-pair refl (H x y) tot-id : {i j : Level} {A : UU i} (B : A → UU j) → (tot (λ x (y : B x) → y)) ~ id tot-id B (pair x y) = refl tot-comp : {i j j' j'' : Level} {A : UU i} {B : A → UU j} {B' : A → UU j'} {B'' : A → UU j''} (f : (x : A) → B x → B' x) (g : (x : A) → B' x → B'' x) → tot (λ x → (g x) ∘ (f x)) ~ ((tot g) ∘ (tot f)) tot-comp f g (pair x y) = refl -- Exercise 7.8 abstract fundamental-theorem-id-retr : {i j : Level} {A : UU i} {B : A → UU j} (a : A) → (i : (x : A) → B x → Id a x) → (R : (x : A) → retr (i x)) → is-fiberwise-equiv i fundamental-theorem-id-retr {_} {_} {A} {B} a i R = is-fiberwise-equiv-is-equiv-tot i ( is-equiv-is-contr (tot i) ( is-contr-retract-of (Σ _ (λ y → Id a y)) ( pair (tot i) ( pair (tot λ x → pr1 (R x)) ( ( htpy-inv (tot-comp i (λ x → pr1 (R x)))) ∙h ( ( tot-htpy λ x → pr2 (R x)) ∙h (tot-id B))))) ( is-contr-total-path a)) ( is-contr-total-path a)) abstract is-equiv-sec-is-equiv : {i j : Level} {A : UU i} {B : UU j} (f : A → B) (sec-f : sec f) → is-equiv (pr1 sec-f) → is-equiv f is-equiv-sec-is-equiv {A = A} {B = B} f (pair g issec-g) is-equiv-sec-f = let h : A → B h = inv-is-equiv is-equiv-sec-f in is-equiv-htpy h ( ( htpy-left-whisk f (htpy-inv (issec-inv-is-equiv is-equiv-sec-f))) ∙h ( htpy-right-whisk issec-g h)) ( is-equiv-inv-is-equiv is-equiv-sec-f) abstract fundamental-theorem-id-sec : {i j : Level} {A : UU i} {B : A → UU j} (a : A) (f : (x : A) → Id a x → B x) → ((x : A) → sec (f x)) → is-fiberwise-equiv f fundamental-theorem-id-sec {A = A} {B = B} a f sec-f x = let i : (x : A) → B x → Id a x i = λ x → pr1 (sec-f x) retr-i : (x : A) → retr (i x) retr-i = λ x → pair (f x) (pr2 (sec-f x)) is-fiberwise-equiv-i : is-fiberwise-equiv i is-fiberwise-equiv-i = fundamental-theorem-id-retr a i retr-i in is-equiv-sec-is-equiv (f x) (sec-f x) (is-fiberwise-equiv-i x) -- Exercise 7.9 abstract is-emb-sec-ap : {i j : Level} {A : UU i} {B : UU j} (f : A → B) → ((x y : A) → sec (ap f {x = x} {y = y})) → is-emb f is-emb-sec-ap f sec-ap-f x = fundamental-theorem-id-sec x (λ y → ap f {y = y}) (sec-ap-f x) -- Exercise 7.10 coherence-is-half-adjoint-equivalence : {l1 l2 : Level} {A : UU l1} {B : UU l2} (f : A → B) (g : B → A) (G : (f ∘ g) ~ id) (H : (g ∘ f) ~ id) → UU (l1 ⊔ l2) coherence-is-half-adjoint-equivalence f g G H = ( htpy-right-whisk G f) ~ (htpy-left-whisk f H) is-half-adjoint-equivalence : {l1 l2 : Level} {A : UU l1} {B : UU l2} → (A → B) → UU (l1 ⊔ l2) is-half-adjoint-equivalence {A = A} {B = B} f = Σ (B → A) ( λ g → Σ ((f ∘ g) ~ id) ( λ G → Σ ((g ∘ f) ~ id) (coherence-is-half-adjoint-equivalence f g G))) is-path-split : {l1 l2 : Level} {A : UU l1} {B : UU l2} → (A → B) → UU (l1 ⊔ l2) is-path-split {A = A} {B = B} f = sec f × ((x y : A) → sec (ap f {x = x} {y = y})) abstract is-path-split-is-equiv : {l1 l2 : Level} {A : UU l1} {B : UU l2} (f : A → B) → is-equiv f → is-path-split f is-path-split-is-equiv f is-equiv-f = pair (pr1 is-equiv-f) (λ x y → pr1 (is-emb-is-equiv f is-equiv-f x y)) abstract is-half-adjoint-equivalence-is-path-split : {l1 l2 : Level} {A : UU l1} {B : UU l2} (f : A → B) → is-path-split f → is-half-adjoint-equivalence f is-half-adjoint-equivalence-is-path-split {A = A} {B = B} f ( pair (pair g issec-g) sec-ap-f) = let φ : ((x : A) → fib (ap f) (issec-g (f x))) → Σ ((g ∘ f) ~ id) ( λ H → (htpy-right-whisk issec-g f) ~ (htpy-left-whisk f H)) φ = ( tot (λ H' → htpy-inv)) ∘ ( λ s → pair (λ x → pr1 (s x)) (λ x → pr2 (s x))) in pair g ( pair issec-g ( φ (λ x → pair ( pr1 (sec-ap-f (g (f x)) x) (issec-g (f x))) ( pr2 (sec-ap-f (g (f x)) x) (issec-g (f x)))))) abstract is-equiv-is-half-adjoint-equivalence : { l1 l2 : Level} {A : UU l1} {B : UU l2} (f : A → B) → is-half-adjoint-equivalence f → is-equiv f is-equiv-is-half-adjoint-equivalence f (pair g (pair G (pair H K))) = is-equiv-has-inverse g G H abstract is-equiv-is-path-split : {l1 l2 : Level} {A : UU l1} {B : UU l2} (f : A → B) → is-path-split f → is-equiv f is-equiv-is-path-split f = ( is-equiv-is-half-adjoint-equivalence f) ∘ ( is-half-adjoint-equivalence-is-path-split f) abstract is-half-adjoint-equivalence-is-equiv : {l1 l2 : Level} {A : UU l1} {B : UU l2} (f : A → B) → is-equiv f → is-half-adjoint-equivalence f is-half-adjoint-equivalence-is-equiv f = ( is-half-adjoint-equivalence-is-path-split f) ∘ (is-path-split-is-equiv f) -- Exercise 7.11 abstract is-equiv-top-is-equiv-bottom-square : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} (f : A → B) (g : C → D) (h : A → C) (i : B → D) (H : (i ∘ f) ~ (g ∘ h)) → (is-equiv f) → (is-equiv g) → (is-equiv i) → (is-equiv h) is-equiv-top-is-equiv-bottom-square f g h i H is-equiv-f is-equiv-g is-equiv-i = is-equiv-right-factor (i ∘ f) g h H is-equiv-g ( is-equiv-comp' i f is-equiv-f is-equiv-i) abstract is-equiv-bottom-is-equiv-top-square : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} (f : A → B) (g : C → D) (h : A → C) (i : B → D) (H : (i ∘ f) ~ (g ∘ h)) → (is-equiv f) → (is-equiv g) → (is-equiv h) → (is-equiv i) is-equiv-bottom-is-equiv-top-square f g h i H is-equiv-f is-equiv-g is-equiv-h = is-equiv-left-factor' i f ( is-equiv-comp (i ∘ f) g h H is-equiv-h is-equiv-g) is-equiv-f abstract is-equiv-left-is-equiv-right-square : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} (f : A → B) (g : C → D) (h : A → C) (i : B → D) (H : (i ∘ f) ~ (g ∘ h)) → (is-equiv h) → (is-equiv i) → (is-equiv g) → (is-equiv f) is-equiv-left-is-equiv-right-square f g h i H is-equiv-h is-equiv-i is-equiv-g = is-equiv-right-factor' i f is-equiv-i ( is-equiv-comp (i ∘ f) g h H is-equiv-h is-equiv-g) abstract is-equiv-right-is-equiv-left-square : {l1 l2 l3 l4 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {D : UU l4} (f : A → B) (g : C → D) (h : A → C) (i : B → D) (H : (i ∘ f) ~ (g ∘ h)) → (is-equiv h) → (is-equiv i) → (is-equiv f) → (is-equiv g) is-equiv-right-is-equiv-left-square f g h i H is-equiv-h is-equiv-i is-equiv-f = is-equiv-left-factor (i ∘ f) g h H ( is-equiv-comp' i f is-equiv-f is-equiv-i) ( is-equiv-h) fib-triangle : {i j k : Level} {X : UU i} {A : UU j} {B : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) (x : X) → (fib f x) → (fib g x) fib-triangle f g h H .(f a) (pair a refl) = pair (h a) (inv (H a)) square-tot-fib-triangle : {i j k : Level} {X : UU i} {A : UU j} {B : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → (h ∘ (Σ-fib-to-domain f)) ~ ((Σ-fib-to-domain g) ∘ (tot (fib-triangle f g h H))) square-tot-fib-triangle f g h H (pair .(f a) (pair a refl)) = refl abstract is-fiberwise-equiv-is-equiv-triangle : {i j k : Level} {X : UU i} {A : UU j} {B : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → (E : is-equiv h) → is-fiberwise-equiv (fib-triangle f g h H) is-fiberwise-equiv-is-equiv-triangle f g h H E = is-fiberwise-equiv-is-equiv-tot ( fib-triangle f g h H) ( is-equiv-top-is-equiv-bottom-square ( Σ-fib-to-domain f) ( Σ-fib-to-domain g) ( tot (fib-triangle f g h H)) ( h) ( square-tot-fib-triangle f g h H) ( is-equiv-Σ-fib-to-domain f) ( is-equiv-Σ-fib-to-domain g) ( E)) abstract is-equiv-triangle-is-fiberwise-equiv : {i j k : Level} {X : UU i} {A : UU j} {B : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → (E : is-fiberwise-equiv (fib-triangle f g h H)) → is-equiv h is-equiv-triangle-is-fiberwise-equiv f g h H E = is-equiv-bottom-is-equiv-top-square ( Σ-fib-to-domain f) ( Σ-fib-to-domain g) ( tot (fib-triangle f g h H)) ( h) ( square-tot-fib-triangle f g h H) ( is-equiv-Σ-fib-to-domain f) ( is-equiv-Σ-fib-to-domain g) ( is-equiv-tot-is-fiberwise-equiv E) -- Extra material {- In order to show that the total space of htpy-cone is contractible, we give a general construction that helps us characterize the identity type of a structure. This construction is called is-contr-total-Eq-structure. We first give some definitions that help us with the construction of is-contr-total-Eq-structure. -} swap-total-Eq-structure : {l1 l2 l3 l4 : Level} {A : UU l1} (B : A → UU l2) (C : A → UU l3) (D : (x : A) → B x → C x → UU l4) → Σ (Σ A B) (λ t → Σ (C (pr1 t)) (D (pr1 t) (pr2 t))) → Σ (Σ A C) (λ t → Σ (B (pr1 t)) (λ y → D (pr1 t) y (pr2 t))) swap-total-Eq-structure B C D (pair (pair a b) (pair c d)) = pair (pair a c) (pair b d) htpy-swap-total-Eq-structure : {l1 l2 l3 l4 : Level} {A : UU l1} (B : A → UU l2) (C : A → UU l3) (D : (x : A) → B x → C x → UU l4) → ( ( swap-total-Eq-structure B C D) ∘ ( swap-total-Eq-structure C B (λ x z y → D x y z))) ~ id htpy-swap-total-Eq-structure B C D (pair (pair a b) (pair c d)) = refl abstract is-equiv-swap-total-Eq-structure : {l1 l2 l3 l4 : Level} {A : UU l1} (B : A → UU l2) (C : A → UU l3) (D : (x : A) → B x → C x → UU l4) → is-equiv (swap-total-Eq-structure B C D) is-equiv-swap-total-Eq-structure B C D = is-equiv-has-inverse ( swap-total-Eq-structure C B (λ x z y → D x y z)) ( htpy-swap-total-Eq-structure B C D) ( htpy-swap-total-Eq-structure C B (λ x z y → D x y z)) abstract is-contr-Σ : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} → is-contr A → ((x : A) → is-contr (B x)) → is-contr (Σ A B) is-contr-Σ {A = A} {B = B} is-contr-A is-contr-B = is-contr-equiv' ( B (center is-contr-A)) ( left-unit-law-Σ B is-contr-A) ( is-contr-B (center is-contr-A)) abstract is-contr-Σ' : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} → is-contr A → (a : A) → is-contr (B a) → is-contr (Σ A B) is-contr-Σ' {A = A} {B} is-contr-A a is-contr-B = is-contr-is-equiv' ( B a) ( left-unit-law-Σ-map-gen B is-contr-A a) ( is-equiv-left-unit-law-Σ-map-gen B is-contr-A a) ( is-contr-B) abstract is-contr-total-Eq-structure : { l1 l2 l3 l4 : Level} { A : UU l1} {B : A → UU l2} {C : A → UU l3} ( D : (x : A) → B x → C x → UU l4) → ( is-contr-AC : is-contr (Σ A C)) → ( t : Σ A C) → is-contr (Σ (B (pr1 t)) (λ y → D (pr1 t) y (pr2 t))) → is-contr (Σ (Σ A B) (λ t → Σ (C (pr1 t)) (D (pr1 t) (pr2 t)))) is-contr-total-Eq-structure {A = A} {B = B} {C = C} D is-contr-AC t is-contr-BD = is-contr-is-equiv ( Σ (Σ A C) (λ t → Σ (B (pr1 t)) (λ y → D (pr1 t) y (pr2 t)))) ( swap-total-Eq-structure B C D) ( is-equiv-swap-total-Eq-structure B C D) ( is-contr-Σ' is-contr-AC t is-contr-BD) -- Characterizing the identity type of a fiber as the fiber of the action on -- paths fib-ap-eq-fib-fiberwise : {i j : Level} {A : UU i} {B : UU j} (f : A → B) {b : B} (s t : fib f b) (p : Id (pr1 s) (pr1 t)) → (Id (tr (λ (a : A) → Id (f a) b) p (pr2 s)) (pr2 t)) → (Id (ap f p) ((pr2 s) ∙ (inv (pr2 t)))) fib-ap-eq-fib-fiberwise f (pair .x' p) (pair x' refl) refl = inv ∘ (concat right-unit refl) abstract is-fiberwise-equiv-fib-ap-eq-fib-fiberwise : {i j : Level} {A : UU i} {B : UU j} (f : A → B) {b : B} (s t : fib f b) → is-fiberwise-equiv (fib-ap-eq-fib-fiberwise f s t) is-fiberwise-equiv-fib-ap-eq-fib-fiberwise f (pair x y) (pair .x refl) refl = is-equiv-comp ( fib-ap-eq-fib-fiberwise f (pair x y) (pair x refl) refl) ( inv) ( concat right-unit refl) ( refl-htpy) ( is-equiv-concat right-unit refl) ( is-equiv-inv (y ∙ refl) refl) fib-ap-eq-fib : {i j : Level} {A : UU i} {B : UU j} (f : A → B) {b : B} (s t : fib f b) → Id s t → fib (ap f {x = pr1 s} {y = pr1 t}) ((pr2 s) ∙ (inv (pr2 t))) fib-ap-eq-fib f s .s refl = pair refl (inv (right-inv (pr2 s))) triangle-fib-ap-eq-fib : {i j : Level} {A : UU i} {B : UU j} (f : A → B) {b : B} (s t : fib f b) → (fib-ap-eq-fib f s t) ~ ((tot (fib-ap-eq-fib-fiberwise f s t)) ∘ (pair-eq {s = s} {t})) triangle-fib-ap-eq-fib f (pair x refl) .(pair x refl) refl = refl abstract is-equiv-fib-ap-eq-fib : {i j : Level} {A : UU i} {B : UU j} (f : A → B) {b : B} (s t : fib f b) → is-equiv (fib-ap-eq-fib f s t) is-equiv-fib-ap-eq-fib f s t = is-equiv-comp ( fib-ap-eq-fib f s t) ( tot (fib-ap-eq-fib-fiberwise f s t)) ( pair-eq {s = s} {t}) ( triangle-fib-ap-eq-fib f s t) ( is-equiv-pair-eq s t) ( is-equiv-tot-is-fiberwise-equiv ( is-fiberwise-equiv-fib-ap-eq-fib-fiberwise f s t)) eq-fib-fib-ap : {i j : Level} {A : UU i} {B : UU j} (f : A → B) (x y : A) (q : Id (f x) (f y)) → Id (pair x q) (pair y (refl {x = f y})) → fib (ap f {x = x} {y = y}) q eq-fib-fib-ap f x y q = (tr (fib (ap f)) right-unit) ∘ (fib-ap-eq-fib f (pair x q) (pair y refl)) abstract is-equiv-eq-fib-fib-ap : {i j : Level} {A : UU i} {B : UU j} (f : A → B) (x y : A) (q : Id (f x) (f y)) → is-equiv (eq-fib-fib-ap f x y q) is-equiv-eq-fib-fib-ap f x y q = is-equiv-comp ( eq-fib-fib-ap f x y q) ( tr (fib (ap f)) right-unit) ( fib-ap-eq-fib f (pair x q) (pair y refl)) ( refl-htpy) ( is-equiv-fib-ap-eq-fib f (pair x q) (pair y refl)) ( is-equiv-tr (fib (ap f)) right-unit) -- Comparing fib and fib' fib'-fib : {i j : Level} {A : UU i} {B : UU j} (f : A → B) (y : B) → fib f y → fib' f y fib'-fib f y t = tot (λ x → inv) t abstract is-equiv-fib'-fib : {i j : Level} {A : UU i} {B : UU j} (f : A → B) → is-fiberwise-equiv (fib'-fib f) is-equiv-fib'-fib f y = is-equiv-tot-is-fiberwise-equiv (λ x → is-equiv-inv (f x) y)
[GOAL] R : Type u S : Type v A : Type w B : Type u₁ M : Type v₁ inst✝¹⁰ : CommSemiring R inst✝⁹ : CommSemiring S inst✝⁸ : Semiring A inst✝⁷ : Semiring B inst✝⁶ : Algebra R S inst✝⁵ : Algebra S A inst✝⁴ : Algebra R A inst✝³ : Algebra S B inst✝² : Algebra R B inst✝¹ : IsScalarTower R S A inst✝ : IsScalarTower R S B U : Subalgebra S A x : R ⊢ ↑(algebraMap R A) x ∈ U.carrier [PROOFSTEP] rw [algebraMap_apply R S A] [GOAL] R : Type u S : Type v A : Type w B : Type u₁ M : Type v₁ inst✝¹⁰ : CommSemiring R inst✝⁹ : CommSemiring S inst✝⁸ : Semiring A inst✝⁷ : Semiring B inst✝⁶ : Algebra R S inst✝⁵ : Algebra S A inst✝⁴ : Algebra R A inst✝³ : Algebra S B inst✝² : Algebra R B inst✝¹ : IsScalarTower R S A inst✝ : IsScalarTower R S B U : Subalgebra S A x : R ⊢ ↑(algebraMap S A) (↑(algebraMap R S) x) ∈ U.carrier [PROOFSTEP] exact U.algebraMap_mem _ [GOAL] R : Type u S : Type v A : Type w B : Type u₁ M : Type v₁ inst✝¹⁰ : CommSemiring R inst✝⁹ : CommSemiring S inst✝⁸ : Semiring A inst✝⁷ : Semiring B inst✝⁶ : Algebra R S inst✝⁵ : Algebra S A inst✝⁴ : Algebra R A inst✝³ : Algebra S B inst✝² : Algebra R B inst✝¹ : IsScalarTower R S A inst✝ : IsScalarTower R S B ⊢ ↑(restrictScalars R ⊤) = ↑⊤ [PROOFSTEP] dsimp -- porting note: why does `rfl` not work instead of `by dsimp`? [GOAL] R : Type u S : Type v A : Type w B : Type u₁ M : Type v₁ inst✝¹⁰ : CommSemiring R inst✝⁹ : CommSemiring S inst✝⁸ : Semiring A inst✝⁷ : Semiring B inst✝⁶ : Algebra R S inst✝⁵ : Algebra S A inst✝⁴ : Algebra R A inst✝³ : Algebra S B inst✝² : Algebra R B inst✝¹ : IsScalarTower R S A inst✝ : IsScalarTower R S B U V : Subalgebra S A H : restrictScalars R U = restrictScalars R V x : A ⊢ x ∈ U ↔ x ∈ V [PROOFSTEP] rw [← mem_restrictScalars R, H, mem_restrictScalars] [GOAL] R : Type u S✝ : Type v A : Type w B : Type u₁ M : Type v₁ inst✝² : CommSemiring R inst✝¹ : CommSemiring A inst✝ : Algebra R A S : Subalgebra R A ⊢ LinearMap.range (toAlgHom R { x // x ∈ S } A) = ↑toSubmodule S [PROOFSTEP] ext [GOAL] case h R : Type u S✝ : Type v A : Type w B : Type u₁ M : Type v₁ inst✝² : CommSemiring R inst✝¹ : CommSemiring A inst✝ : Algebra R A S : Subalgebra R A x✝ : A ⊢ x✝ ∈ LinearMap.range (toAlgHom R { x // x ∈ S } A) ↔ x✝ ∈ ↑toSubmodule S [PROOFSTEP] simp only [← Submodule.range_subtype (Subalgebra.toSubmodule S), LinearMap.mem_range, IsScalarTower.coe_toAlgHom', Subalgebra.mem_toSubmodule] [GOAL] case h R : Type u S✝ : Type v A : Type w B : Type u₁ M : Type v₁ inst✝² : CommSemiring R inst✝¹ : CommSemiring A inst✝ : Algebra R A S : Subalgebra R A x✝ : A ⊢ (∃ y, ↑(algebraMap { x // x ∈ S } A) y = x✝) ↔ ∃ y, ↑(Submodule.subtype (↑toSubmodule S)) y = x✝ [PROOFSTEP] rfl [GOAL] R : Type u S : Type v A : Type w B : Type u₁ M : Type v₁ inst✝⁶ : CommSemiring R inst✝⁵ : CommSemiring S inst✝⁴ : CommSemiring A inst✝³ : Algebra R S inst✝² : Algebra S A inst✝¹ : Algebra R A inst✝ : IsScalarTower R S A t : Set A z : A ⊢ z ∈ Subsemiring.closure (Set.range ↑(algebraMap { x // x ∈ AlgHom.range (toAlgHom R S A) } A) ∪ t) ↔ z ∈ Subsemiring.closure (Set.range ↑(algebraMap S A) ∪ t) [PROOFSTEP] suffices Set.range (algebraMap (toAlgHom R S A).range A) = Set.range (algebraMap S A) by rw [this] [GOAL] R : Type u S : Type v A : Type w B : Type u₁ M : Type v₁ inst✝⁶ : CommSemiring R inst✝⁵ : CommSemiring S inst✝⁴ : CommSemiring A inst✝³ : Algebra R S inst✝² : Algebra S A inst✝¹ : Algebra R A inst✝ : IsScalarTower R S A t : Set A z : A this : Set.range ↑(algebraMap { x // x ∈ AlgHom.range (toAlgHom R S A) } A) = Set.range ↑(algebraMap S A) ⊢ z ∈ Subsemiring.closure (Set.range ↑(algebraMap { x // x ∈ AlgHom.range (toAlgHom R S A) } A) ∪ t) ↔ z ∈ Subsemiring.closure (Set.range ↑(algebraMap S A) ∪ t) [PROOFSTEP] rw [this] [GOAL] R : Type u S : Type v A : Type w B : Type u₁ M : Type v₁ inst✝⁶ : CommSemiring R inst✝⁵ : CommSemiring S inst✝⁴ : CommSemiring A inst✝³ : Algebra R S inst✝² : Algebra S A inst✝¹ : Algebra R A inst✝ : IsScalarTower R S A t : Set A z : A ⊢ Set.range ↑(algebraMap { x // x ∈ AlgHom.range (toAlgHom R S A) } A) = Set.range ↑(algebraMap S A) [PROOFSTEP] ext z [GOAL] case h R : Type u S : Type v A : Type w B : Type u₁ M : Type v₁ inst✝⁶ : CommSemiring R inst✝⁵ : CommSemiring S inst✝⁴ : CommSemiring A inst✝³ : Algebra R S inst✝² : Algebra S A inst✝¹ : Algebra R A inst✝ : IsScalarTower R S A t : Set A z✝ z : A ⊢ z ∈ Set.range ↑(algebraMap { x // x ∈ AlgHom.range (toAlgHom R S A) } A) ↔ z ∈ Set.range ↑(algebraMap S A) [PROOFSTEP] exact ⟨fun ⟨⟨_, y, h1⟩, h2⟩ ↦ ⟨y, h2 ▸ h1⟩, fun ⟨y, hy⟩ ↦ ⟨⟨z, y, hy⟩, rfl⟩⟩
section \<open>Reduced Gr\"obner Bases\<close> theory Reduced_GB imports Groebner_Bases Auto_Reduction begin lemma (in gd_term) GB_image_monic: "is_Groebner_basis (monic ` G) \<longleftrightarrow> is_Groebner_basis G" by (simp add: GB_alt_1) subsection \<open>Definition and Uniqueness of Reduced Gr\"obner Bases\<close> context ordered_term begin definition is_reduced_GB :: "('t \<Rightarrow>\<^sub>0 'b::field) set \<Rightarrow> bool" where "is_reduced_GB B \<equiv> is_Groebner_basis B \<and> is_auto_reduced B \<and> is_monic_set B \<and> 0 \<notin> B" lemma reduced_GB_D1: assumes "is_reduced_GB G" shows "is_Groebner_basis G" using assms unfolding is_reduced_GB_def by simp lemma reduced_GB_D2: assumes "is_reduced_GB G" shows "is_auto_reduced G" using assms unfolding is_reduced_GB_def by simp lemma reduced_GB_D3: assumes "is_reduced_GB G" shows "is_monic_set G" using assms unfolding is_reduced_GB_def by simp lemma reduced_GB_D4: assumes "is_reduced_GB G" and "g \<in> G" shows "g \<noteq> 0" using assms unfolding is_reduced_GB_def by auto lemma reduced_GB_lc: assumes major: "is_reduced_GB G" and "g \<in> G" shows "lc g = 1" by (rule is_monic_setD, rule reduced_GB_D3, fact major, fact \<open>g \<in> G\<close>, rule reduced_GB_D4, fact major, fact \<open>g \<in> G\<close>) end (* ordered_term *) context gd_term begin lemma is_reduced_GB_subsetI: assumes Ared: "is_reduced_GB A" and BGB: "is_Groebner_basis B" and Bmon: "is_monic_set B" and *: "\<And>a b. a \<in> A \<Longrightarrow> b \<in> B \<Longrightarrow> a \<noteq> 0 \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> a - b \<noteq> 0 \<Longrightarrow> lt (a - b) \<in> keys b \<Longrightarrow> lt (a - b) \<prec>\<^sub>t lt b \<Longrightarrow> False" and id_eq: "pmdl A = pmdl B" shows "A \<subseteq> B" proof fix a assume "a \<in> A" have "a \<noteq> 0" by (rule reduced_GB_D4, fact Ared, fact \<open>a \<in> A\<close>) have lca: "lc a = 1" by (rule reduced_GB_lc, fact Ared, fact \<open>a \<in> A\<close>) have AGB: "is_Groebner_basis A" by (rule reduced_GB_D1, fact Ared) from \<open>a \<in> A\<close> have "a \<in> pmdl A" by (rule pmdl.span_base) also have "... = pmdl B" using id_eq by simp finally have "a \<in> pmdl B" . from BGB this \<open>a \<noteq> 0\<close> obtain b where "b \<in> B" and "b \<noteq> 0" and baddsa: "lt b adds\<^sub>t lt a" by (rule GB_adds_lt) from Bmon this(1) this(2) have lcb: "lc b = 1" by (rule is_monic_setD) from \<open>b \<in> B\<close> have "b \<in> pmdl B" by (rule pmdl.span_base) also have "... = pmdl A" using id_eq by simp finally have "b \<in> pmdl A" . have lt_eq: "lt b = lt a" proof (rule ccontr) assume "lt b \<noteq> lt a" from AGB \<open>b \<in> pmdl A\<close> \<open>b \<noteq> 0\<close> obtain a' where "a' \<in> A" and "a' \<noteq> 0" and a'addsb: "lt a' adds\<^sub>t lt b" by (rule GB_adds_lt) have a'addsa: "lt a' adds\<^sub>t lt a" by (rule adds_term_trans, fact a'addsb, fact baddsa) have "lt a' \<noteq> lt a" proof assume "lt a' = lt a" hence aaddsa': "lt a adds\<^sub>t lt a'" by (simp add: adds_term_refl) have "lt a adds\<^sub>t lt b" by (rule adds_term_trans, fact aaddsa', fact a'addsb) have "lt a = lt b" by (rule adds_term_antisym, fact+) with \<open>lt b \<noteq> lt a\<close> show False by simp qed hence "a' \<noteq> a" by auto with \<open>a' \<in> A\<close> have "a' \<in> A - {a}" by blast have is_red: "is_red (A - {a}) a" by (intro is_red_addsI, fact, fact, rule lt_in_keys, fact+) have "\<not> is_red (A - {a}) a" by (rule is_auto_reducedD, rule reduced_GB_D2, fact Ared, fact+) from this is_red show False .. qed have "a - b = 0" proof (rule ccontr) let ?c = "a - b" assume "?c \<noteq> 0" have "?c \<in> pmdl A" by (rule pmdl.span_diff, fact+) also have "... = pmdl B" using id_eq by simp finally have "?c \<in> pmdl B" . from \<open>b \<noteq> 0\<close> have "- b \<noteq> 0" by simp have "lt (-b) = lt a" unfolding lt_uminus by fact have "lc (-b) = - lc a" unfolding lc_uminus lca lcb .. from \<open>?c \<noteq> 0\<close> have "a + (-b) \<noteq> 0" by simp have "lt ?c \<in> keys ?c" by (rule lt_in_keys, fact) have "keys ?c \<subseteq> (keys a \<union> keys b)" by (fact keys_minus) with \<open>lt ?c \<in> keys ?c\<close> have "lt ?c \<in> keys a \<or> lt ?c \<in> keys b" by auto thus False proof assume "lt ?c \<in> keys a" from AGB \<open>?c \<in> pmdl A\<close> \<open>?c \<noteq> 0\<close> obtain a' where "a' \<in> A" and "a' \<noteq> 0" and a'addsc: "lt a' adds\<^sub>t lt ?c" by (rule GB_adds_lt) from a'addsc have "lt a' \<preceq>\<^sub>t lt ?c" by (rule ord_adds_term) also have "... = lt (a + (- b))" by simp also have "... \<prec>\<^sub>t lt a" by (rule lt_plus_lessI, fact+) finally have "lt a' \<prec>\<^sub>t lt a" . hence "lt a' \<noteq> lt a" by simp hence "a' \<noteq> a" by auto with \<open>a' \<in> A\<close> have "a' \<in> A - {a}" by blast have is_red: "is_red (A - {a}) a" by (intro is_red_addsI, fact, fact, fact+) have "\<not> is_red (A - {a}) a" by (rule is_auto_reducedD, rule reduced_GB_D2, fact Ared, fact+) from this is_red show False .. next assume "lt ?c \<in> keys b" with \<open>a \<in> A\<close> \<open>b \<in> B\<close> \<open>a \<noteq> 0\<close> \<open>b \<noteq> 0\<close> \<open>?c \<noteq> 0\<close> show False proof (rule *) have "lt ?c = lt ((- b) + a)" by simp also have "... \<prec>\<^sub>t lt (-b)" proof (rule lt_plus_lessI) from \<open>?c \<noteq> 0\<close> show "-b + a \<noteq> 0" by simp next from \<open>lt (-b) = lt a\<close> show "lt a = lt (-b)" by simp next from \<open>lc (-b) = - lc a\<close> show "lc a = - lc (-b)" by simp qed finally show "lt ?c \<prec>\<^sub>t lt b" unfolding lt_uminus . qed qed qed hence "a = b" by simp with \<open>b \<in> B\<close> show "a \<in> B" by simp qed lemma is_reduced_GB_unique': assumes Ared: "is_reduced_GB A" and Bred: "is_reduced_GB B" and id_eq: "pmdl A = pmdl B" shows "A \<subseteq> B" proof - from Bred have BGB: "is_Groebner_basis B" by (rule reduced_GB_D1) with assms(1) show ?thesis proof (rule is_reduced_GB_subsetI) from Bred show "is_monic_set B" by (rule reduced_GB_D3) next fix a b :: "'t \<Rightarrow>\<^sub>0 'b" let ?c = "a - b" assume "a \<in> A" and "b \<in> B" and "a \<noteq> 0" and "b \<noteq> 0" and "?c \<noteq> 0" and "lt ?c \<in> keys b" and "lt ?c \<prec>\<^sub>t lt b" from \<open>a \<in> A\<close> have "a \<in> pmdl B" by (simp only: id_eq[symmetric], rule pmdl.span_base) moreover from \<open>b \<in> B\<close> have "b \<in> pmdl B" by (rule pmdl.span_base) ultimately have "?c \<in> pmdl B" by (rule pmdl.span_diff) from BGB this \<open>?c \<noteq> 0\<close> obtain b' where "b' \<in> B" and "b' \<noteq> 0" and b'addsc: "lt b' adds\<^sub>t lt ?c" by (rule GB_adds_lt) from b'addsc have "lt b' \<preceq>\<^sub>t lt ?c" by (rule ord_adds_term) also have "... \<prec>\<^sub>t lt b" by fact finally have "lt b' \<prec>\<^sub>t lt b" unfolding lt_uminus . hence "lt b' \<noteq> lt b" by simp hence "b' \<noteq> b" by auto with \<open>b' \<in> B\<close> have "b' \<in> B - {b}" by blast have is_red: "is_red (B - {b}) b" by (intro is_red_addsI, fact, fact, fact+) have "\<not> is_red (B - {b}) b" by (rule is_auto_reducedD, rule reduced_GB_D2, fact Bred, fact+) from this is_red show False .. qed fact qed theorem is_reduced_GB_unique: assumes Ared: "is_reduced_GB A" and Bred: "is_reduced_GB B" and id_eq: "pmdl A = pmdl B" shows "A = B" proof from assms show "A \<subseteq> B" by (rule is_reduced_GB_unique') next from Bred Ared id_eq[symmetric] show "B \<subseteq> A" by (rule is_reduced_GB_unique') qed subsection \<open>Computing Reduced Gr\"obner Bases by Auto-Reduction\<close> subsubsection \<open>Minimal Bases\<close> lemma minimal_basis_is_reduced_GB: assumes "is_minimal_basis B" and "is_monic_set B" and "is_reduced_GB G" and "G \<subseteq> B" and "pmdl B = pmdl G" shows "B = G" using _ assms(3) assms(5) proof (rule is_reduced_GB_unique) from assms(3) have "is_Groebner_basis G" by (rule reduced_GB_D1) show "is_reduced_GB B" unfolding is_reduced_GB_def proof (intro conjI) show "0 \<notin> B" proof assume "0 \<in> B" with assms(1) have "0 \<noteq> (0::'t \<Rightarrow>\<^sub>0 'b)" by (rule is_minimal_basisD1) thus False by simp qed next from \<open>is_Groebner_basis G\<close> assms(4) assms(5) show "is_Groebner_basis B" by (rule GB_subset) next show "is_auto_reduced B" unfolding is_auto_reduced_def proof (intro ballI notI) fix b assume "b \<in> B" with assms(1) have "b \<noteq> 0" by (rule is_minimal_basisD1) assume "is_red (B - {b}) b" then obtain f where "f \<in> B - {b}" and "is_red {f} b" by (rule is_red_singletonI) from this(1) have "f \<in> B" and "f \<noteq> b" by simp_all from assms(1) \<open>f \<in> B\<close> have "f \<noteq> 0" by (rule is_minimal_basisD1) from \<open>f \<in> B\<close> have "f \<in> pmdl B" by (rule pmdl.span_base) hence "f \<in> pmdl G" by (simp only: assms(5)) from \<open>is_Groebner_basis G\<close> this \<open>f \<noteq> 0\<close> obtain g where "g \<in> G" and "g \<noteq> 0" and "lt g adds\<^sub>t lt f" by (rule GB_adds_lt) from \<open>g \<in> G\<close> \<open>G \<subseteq> B\<close> have "g \<in> B" .. have "g = f" proof (rule ccontr) assume "g \<noteq> f" with assms(1) \<open>g \<in> B\<close> \<open>f \<in> B\<close> have "\<not> lt g adds\<^sub>t lt f" by (rule is_minimal_basisD2) from this \<open>lt g adds\<^sub>t lt f\<close> show False .. qed with \<open>g \<in> G\<close> have "f \<in> G" by simp with \<open>f \<in> B - {b}\<close> \<open>is_red {f} b\<close> have red: "is_red (G - {b}) b" by (meson Diff_iff is_red_singletonD) from \<open>b \<in> B\<close> have "b \<in> pmdl B" by (rule pmdl.span_base) hence "b \<in> pmdl G" by (simp only: assms(5)) from \<open>is_Groebner_basis G\<close> this \<open>b \<noteq> 0\<close> obtain g' where "g' \<in> G" and "g' \<noteq> 0" and "lt g' adds\<^sub>t lt b" by (rule GB_adds_lt) from \<open>g' \<in> G\<close> \<open>G \<subseteq> B\<close> have "g' \<in> B" .. have "g' = b" proof (rule ccontr) assume "g' \<noteq> b" with assms(1) \<open>g' \<in> B\<close> \<open>b \<in> B\<close> have "\<not> lt g' adds\<^sub>t lt b" by (rule is_minimal_basisD2) from this \<open>lt g' adds\<^sub>t lt b\<close> show False .. qed with \<open>g' \<in> G\<close> have "b \<in> G" by simp from assms(3) have "is_auto_reduced G" by (rule reduced_GB_D2) from this \<open>b \<in> G\<close> have "\<not> is_red (G - {b}) b" by (rule is_auto_reducedD) from this red show False .. qed qed fact qed subsubsection \<open>Computing Minimal Bases\<close> lemma comp_min_basis_pmdl: assumes "is_Groebner_basis (set xs)" shows "pmdl (set (comp_min_basis xs)) = pmdl (set xs)" (is "pmdl (set ?ys) = _") using finite_set proof (rule pmdl_eqI_adds_lt_finite) from comp_min_basis_subset show *: "pmdl (set ?ys) \<subseteq> pmdl (set xs)" by (rule pmdl.span_mono) next fix f assume "f \<in> pmdl (set xs)" and "f \<noteq> 0" with assms obtain g where "g \<in> set xs" and "g \<noteq> 0" and 1: "lt g adds\<^sub>t lt f" by (rule GB_adds_lt) from this(1, 2) obtain g' where "g' \<in> set ?ys" and 2: "lt g' adds\<^sub>t lt g" by (rule comp_min_basis_adds) note this(1) moreover from this have "g' \<noteq> 0" by (rule comp_min_basis_nonzero) moreover from 2 1 have "lt g' adds\<^sub>t lt f" by (rule adds_term_trans) ultimately show "\<exists>g\<in>set ?ys. g \<noteq> 0 \<and> lt g adds\<^sub>t lt f" by blast qed lemma comp_min_basis_GB: assumes "is_Groebner_basis (set xs)" shows "is_Groebner_basis (set (comp_min_basis xs))" (is "is_Groebner_basis (set ?ys)") unfolding GB_alt_2_finite[OF finite_set] proof (intro ballI impI) fix f assume "f \<in> pmdl (set ?ys)" also from assms have "\<dots> = pmdl (set xs)" by (rule comp_min_basis_pmdl) finally have "f \<in> pmdl (set xs)" . moreover assume "f \<noteq> 0" ultimately have "is_red (set xs) f" using assms unfolding GB_alt_2_finite[OF finite_set] by blast thus "is_red (set ?ys) f" by (rule comp_min_basis_is_red) qed subsubsection \<open>Computing Reduced Bases\<close> lemma comp_red_basis_pmdl: assumes "is_Groebner_basis (set xs)" shows "pmdl (set (comp_red_basis xs)) = pmdl (set xs)" proof (rule, fact pmdl_comp_red_basis_subset, rule) fix f assume "f \<in> pmdl (set xs)" show "f \<in> pmdl (set (comp_red_basis xs))" proof (cases "f = 0") case True show ?thesis unfolding True by (rule pmdl.span_zero) next case False let ?xs = "comp_red_basis xs" have "(red (set ?xs))\<^sup>*\<^sup>* f 0" proof (rule is_red_implies_0_red_finite, fact finite_set, fact pmdl_comp_red_basis_subset) fix q assume "q \<noteq> 0" and "q \<in> pmdl (set xs)" with assms have "is_red (set xs) q" by (rule GB_imp_reducibility) thus "is_red (set (comp_red_basis xs)) q" unfolding comp_red_basis_is_red . qed fact thus ?thesis by (rule red_rtranclp_0_in_pmdl) qed qed lemma comp_red_basis_GB: assumes "is_Groebner_basis (set xs)" shows "is_Groebner_basis (set (comp_red_basis xs))" unfolding GB_alt_2_finite[OF finite_set] proof (intro ballI impI) fix f assume fin: "f \<in> pmdl (set (comp_red_basis xs))" hence "f \<in> pmdl (set xs)" unfolding comp_red_basis_pmdl[OF assms] . assume "f \<noteq> 0" from assms \<open>f \<noteq> 0\<close> \<open>f \<in> pmdl (set xs)\<close> show "is_red (set (comp_red_basis xs)) f" by (simp add: comp_red_basis_is_red GB_alt_2_finite) qed subsubsection \<open>Computing Reduced Gr\"obner Bases\<close> lemma comp_red_monic_basis_pmdl: assumes "is_Groebner_basis (set xs)" shows "pmdl (set (comp_red_monic_basis xs)) = pmdl (set xs)" unfolding set_comp_red_monic_basis pmdl_image_monic comp_red_basis_pmdl[OF assms] .. lemma comp_red_monic_basis_GB: assumes "is_Groebner_basis (set xs)" shows "is_Groebner_basis (set (comp_red_monic_basis xs))" unfolding set_comp_red_monic_basis GB_image_monic using assms by (rule comp_red_basis_GB) lemma comp_red_monic_basis_is_reduced_GB: assumes "is_Groebner_basis (set xs)" shows "is_reduced_GB (set (comp_red_monic_basis xs))" unfolding is_reduced_GB_def proof (intro conjI, rule comp_red_monic_basis_GB, fact assms, rule comp_red_monic_basis_is_auto_reduced, rule comp_red_monic_basis_is_monic_set, intro notI) assume "0 \<in> set (comp_red_monic_basis xs)" hence "0 \<noteq> (0::'t \<Rightarrow>\<^sub>0 'b)" by (rule comp_red_monic_basis_nonzero) thus False by simp qed lemma ex_finite_reduced_GB_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" obtains G where "G \<subseteq> dgrad_p_set d m" and "finite G" and "is_reduced_GB G" and "pmdl G = pmdl F" proof - from assms obtain G0 where G0_sub: "G0 \<subseteq> dgrad_p_set d m" and fin: "finite G0" and gb: "is_Groebner_basis G0" and pid: "pmdl G0 = pmdl F" by (rule ex_finite_GB_dgrad_p_set) from fin obtain xs where set: "G0 = set xs" using finite_list by blast let ?G = "set (comp_red_monic_basis xs)" show ?thesis proof from assms(1) have "dgrad_p_set_le d (set (comp_red_monic_basis xs)) G0" unfolding set by (rule comp_red_monic_basis_dgrad_p_set_le) from this G0_sub show "set (comp_red_monic_basis xs) \<subseteq> dgrad_p_set d m" by (rule dgrad_p_set_le_dgrad_p_set) next from gb show rgb: "is_reduced_GB ?G" unfolding set by (rule comp_red_monic_basis_is_reduced_GB) next from gb show "pmdl ?G = pmdl F" unfolding set pid[symmetric] by (rule comp_red_monic_basis_pmdl) qed (fact finite_set) qed theorem ex_unique_reduced_GB_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" shows "\<exists>!G. G \<subseteq> dgrad_p_set d m \<and> finite G \<and> is_reduced_GB G \<and> pmdl G = pmdl F" proof - from assms obtain G where "G \<subseteq> dgrad_p_set d m" and "finite G" and "is_reduced_GB G" and G: "pmdl G = pmdl F" by (rule ex_finite_reduced_GB_dgrad_p_set) hence "G \<subseteq> dgrad_p_set d m \<and> finite G \<and> is_reduced_GB G \<and> pmdl G = pmdl F" by simp thus ?thesis proof (rule ex1I) fix G' assume "G' \<subseteq> dgrad_p_set d m \<and> finite G' \<and> is_reduced_GB G' \<and> pmdl G' = pmdl F" hence "is_reduced_GB G'" and G': "pmdl G' = pmdl F" by simp_all note this(1) \<open>is_reduced_GB G\<close> moreover have "pmdl G' = pmdl G" by (simp only: G G') ultimately show "G' = G" by (rule is_reduced_GB_unique) qed qed corollary ex_unique_reduced_GB_dgrad_p_set': assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" shows "\<exists>!G. finite G \<and> is_reduced_GB G \<and> pmdl G = pmdl F" proof - from assms obtain G where "G \<subseteq> dgrad_p_set d m" and "finite G" and "is_reduced_GB G" and G: "pmdl G = pmdl F" by (rule ex_finite_reduced_GB_dgrad_p_set) hence "finite G \<and> is_reduced_GB G \<and> pmdl G = pmdl F" by simp thus ?thesis proof (rule ex1I) fix G' assume "finite G' \<and> is_reduced_GB G' \<and> pmdl G' = pmdl F" hence "is_reduced_GB G'" and G': "pmdl G' = pmdl F" by simp_all note this(1) \<open>is_reduced_GB G\<close> moreover have "pmdl G' = pmdl G" by (simp only: G G') ultimately show "G' = G" by (rule is_reduced_GB_unique) qed qed definition reduced_GB :: "('t \<Rightarrow>\<^sub>0 'b) set \<Rightarrow> ('t \<Rightarrow>\<^sub>0 'b::field) set" where "reduced_GB B = (THE G. finite G \<and> is_reduced_GB G \<and> pmdl G = pmdl B)" text \<open>@{const reduced_GB} returns the unique reduced Gr\"obner basis of the given set, provided its Dickson grading is bounded. Combining @{const comp_red_monic_basis} with any function for computing Gr\"obner bases, e.\,g. \<open>gb\<close> from theory "Buchberger", makes @{const reduced_GB} computable.\<close> lemma finite_reduced_GB_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" shows "finite (reduced_GB F)" unfolding reduced_GB_def by (rule the1I2, rule ex_unique_reduced_GB_dgrad_p_set', fact, fact, fact, elim conjE) lemma reduced_GB_is_GB_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" shows "is_Groebner_basis (reduced_GB F)" proof - from assms have "is_reduced_GB (reduced_GB F)" by (rule reduced_GB_is_reduced_GB_dgrad_p_set) thus ?thesis unfolding is_reduced_GB_def .. qed lemma reduced_GB_is_auto_reduced_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" shows "is_auto_reduced (reduced_GB F)" proof - from assms have "is_reduced_GB (reduced_GB F)" by (rule reduced_GB_is_reduced_GB_dgrad_p_set) thus ?thesis unfolding is_reduced_GB_def by simp qed lemma reduced_GB_is_monic_set_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" shows "is_monic_set (reduced_GB F)" proof - from assms have "is_reduced_GB (reduced_GB F)" by (rule reduced_GB_is_reduced_GB_dgrad_p_set) thus ?thesis unfolding is_reduced_GB_def by simp qed lemma reduced_GB_nonzero_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" shows "0 \<notin> reduced_GB F" proof - from assms have "is_reduced_GB (reduced_GB F)" by (rule reduced_GB_is_reduced_GB_dgrad_p_set) thus ?thesis unfolding is_reduced_GB_def by simp qed lemma reduced_GB_pmdl_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" shows "pmdl (reduced_GB F) = pmdl F" unfolding reduced_GB_def by (rule the1I2, rule ex_unique_reduced_GB_dgrad_p_set', fact, fact, fact, elim conjE) lemma reduced_GB_unique_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" and "is_reduced_GB G" and "pmdl G = pmdl F" shows "reduced_GB F = G" by (rule is_reduced_GB_unique, rule reduced_GB_is_reduced_GB_dgrad_p_set, fact+, simp only: reduced_GB_pmdl_dgrad_p_set[OF assms(1, 2, 3)] assms(5)) lemma reduced_GB_dgrad_p_set: assumes "dickson_grading d" and "finite (component_of_term ` Keys F)" and "F \<subseteq> dgrad_p_set d m" shows "reduced_GB F \<subseteq> dgrad_p_set d m" proof - from assms obtain G where G: "G \<subseteq> dgrad_p_set d m" and "is_reduced_GB G" and "pmdl G = pmdl F" by (rule ex_finite_reduced_GB_dgrad_p_set) from assms this(2, 3) have "reduced_GB F = G" by (rule reduced_GB_unique_dgrad_p_set) with G show ?thesis by simp qed lemma reduced_GB_unique: assumes "finite G" and "is_reduced_GB G" and "pmdl G = pmdl F" shows "reduced_GB F = G" proof - from assms have "finite G \<and> is_reduced_GB G \<and> pmdl G = pmdl F" by simp thus ?thesis unfolding reduced_GB_def proof (rule the_equality) fix G' assume "finite G' \<and> is_reduced_GB G' \<and> pmdl G' = pmdl F" hence "is_reduced_GB G'" and eq: "pmdl G' = pmdl F" by simp_all note this(1) moreover note assms(2) moreover have "pmdl G' = pmdl G" by (simp only: assms(3) eq) ultimately show "G' = G" by (rule is_reduced_GB_unique) qed qed lemma is_reduced_GB_empty: "is_reduced_GB {}" by (simp add: is_reduced_GB_def is_Groebner_basis_empty is_monic_set_def is_auto_reduced_def) lemma is_reduced_GB_singleton: "is_reduced_GB {f} \<longleftrightarrow> lc f = 1" proof assume "is_reduced_GB {f}" hence "is_monic_set {f}" and "f \<noteq> 0" by (rule reduced_GB_D3, rule reduced_GB_D4) simp from this(1) _ this(2) show "lc f = 1" by (rule is_monic_setD) simp next assume "lc f = 1" moreover from this have "f \<noteq> 0" by auto ultimately show "is_reduced_GB {f}" by (simp add: is_reduced_GB_def is_Groebner_basis_singleton is_monic_set_def is_auto_reduced_def not_is_red_empty) qed lemma reduced_GB_empty: "reduced_GB {} = {}" using finite.emptyI is_reduced_GB_empty refl by (rule reduced_GB_unique) lemma reduced_GB_singleton: "reduced_GB {f} = (if f = 0 then {} else {monic f})" proof (cases "f = 0") case True from finite.emptyI is_reduced_GB_empty have "reduced_GB {f} = {}" by (rule reduced_GB_unique) (simp add: True flip: pmdl.span_Diff_zero[of "{0}"]) with True show ?thesis by simp next case False have "reduced_GB {f} = {monic f}" proof (rule reduced_GB_unique) from False have "lc f \<noteq> 0" by (rule lc_not_0) thus "is_reduced_GB {monic f}" by (simp add: is_reduced_GB_singleton monic_def) next have "pmdl {monic f} = pmdl (monic ` {f})" by simp also have "\<dots> = pmdl {f}" by (fact pmdl_image_monic) finally show "pmdl {monic f} = pmdl {f}" . qed simp with False show ?thesis by simp qed lemma ex_unique_reduced_GB_finite: "finite F \<Longrightarrow> (\<exists>!G. finite G \<and> is_reduced_GB G \<and> pmdl G = pmdl F)" by (rule ex_unique_reduced_GB_dgrad_p_set', rule dickson_grading_dgrad_dummy, erule finite_imp_finite_component_Keys, erule dgrad_p_set_exhaust_expl) lemma finite_reduced_GB_finite: "finite F \<Longrightarrow> finite (reduced_GB F)" by (rule finite_reduced_GB_dgrad_p_set, rule dickson_grading_dgrad_dummy, erule finite_imp_finite_component_Keys, erule dgrad_p_set_exhaust_expl) lemma reduced_GB_is_reduced_GB_finite: "finite F \<Longrightarrow> is_reduced_GB (reduced_GB F)" by (rule reduced_GB_is_reduced_GB_dgrad_p_set, rule dickson_grading_dgrad_dummy, erule finite_imp_finite_component_Keys, erule dgrad_p_set_exhaust_expl) lemma reduced_GB_is_GB_finite: "finite F \<Longrightarrow> is_Groebner_basis (reduced_GB F)" by (rule reduced_GB_is_GB_dgrad_p_set, rule dickson_grading_dgrad_dummy, erule finite_imp_finite_component_Keys, erule dgrad_p_set_exhaust_expl) lemma reduced_GB_is_auto_reduced_finite: "finite F \<Longrightarrow> is_auto_reduced (reduced_GB F)" by (rule reduced_GB_is_auto_reduced_dgrad_p_set, rule dickson_grading_dgrad_dummy, erule finite_imp_finite_component_Keys, erule dgrad_p_set_exhaust_expl) lemma reduced_GB_is_monic_set_finite: "finite F \<Longrightarrow> is_monic_set (reduced_GB F)" by (rule reduced_GB_is_monic_set_dgrad_p_set, rule dickson_grading_dgrad_dummy, erule finite_imp_finite_component_Keys, erule dgrad_p_set_exhaust_expl) lemma reduced_GB_nonzero_finite: "finite F \<Longrightarrow> 0 \<notin> reduced_GB F" by (rule reduced_GB_nonzero_dgrad_p_set, rule dickson_grading_dgrad_dummy, erule finite_imp_finite_component_Keys, erule dgrad_p_set_exhaust_expl) lemma reduced_GB_pmdl_finite: "finite F \<Longrightarrow> pmdl (reduced_GB F) = pmdl F" by (rule reduced_GB_pmdl_dgrad_p_set, rule dickson_grading_dgrad_dummy, erule finite_imp_finite_component_Keys, erule dgrad_p_set_exhaust_expl) lemma reduced_GB_unique_finite: "finite F \<Longrightarrow> is_reduced_GB G \<Longrightarrow> pmdl G = pmdl F \<Longrightarrow> reduced_GB F = G" by (rule reduced_GB_unique_dgrad_p_set, rule dickson_grading_dgrad_dummy, erule finite_imp_finite_component_Keys, erule dgrad_p_set_exhaust_expl) end (* gd_term *) subsubsection \<open>Properties of the Reduced Gr\"obner Basis of an Ideal\<close> context gd_powerprod begin lemma ideal_eq_UNIV_iff_reduced_GB_eq_one_dgrad_p_set: assumes "dickson_grading d" and "F \<subseteq> punit.dgrad_p_set d m" shows "ideal F = UNIV \<longleftrightarrow> punit.reduced_GB F = {1}" proof - have fin: "finite (local.punit.component_of_term ` Keys F)" by simp show ?thesis proof assume "ideal F = UNIV" from assms(1) fin assms(2) show "punit.reduced_GB F = {1}" proof (rule punit.reduced_GB_unique_dgrad_p_set) show "punit.is_reduced_GB {1}" unfolding punit.is_reduced_GB_def proof (intro conjI, fact punit.is_Groebner_basis_singleton) show "punit.is_auto_reduced {1}" unfolding punit.is_auto_reduced_def by (rule ballI, simp add: remove_def punit.not_is_red_empty) next show "punit.is_monic_set {1}" by (rule punit.is_monic_setI, simp del: single_one add: single_one[symmetric]) qed simp next have "punit.pmdl {1} = ideal {1}" by simp also have "... = ideal F" proof (simp only: \<open>ideal F = UNIV\<close> ideal_eq_UNIV_iff_contains_one) have "1 \<in> {1}" .. with module_times show "1 \<in> ideal {1}" by (rule module.span_base) qed also have "... = punit.pmdl F" by simp finally show "punit.pmdl {1} = punit.pmdl F" . qed next assume "punit.reduced_GB F = {1}" hence "1 \<in> punit.reduced_GB F" by simp hence "1 \<in> punit.pmdl (punit.reduced_GB F)" by (rule punit.pmdl.span_base) also from assms(1) fin assms(2) have "... = punit.pmdl F" by (rule punit.reduced_GB_pmdl_dgrad_p_set) finally show "ideal F = UNIV" by (simp add: ideal_eq_UNIV_iff_contains_one) qed qed lemmas ideal_eq_UNIV_iff_reduced_GB_eq_one_finite = ideal_eq_UNIV_iff_reduced_GB_eq_one_dgrad_p_set[OF dickson_grading_dgrad_dummy punit.dgrad_p_set_exhaust_expl] end (* gd_powerprod *) subsubsection \<open>Context @{locale od_term}\<close> context od_term begin lemmas ex_unique_reduced_GB = ex_unique_reduced_GB_dgrad_p_set'[OF dickson_grading_zero _ subset_dgrad_p_set_zero] lemmas finite_reduced_GB = finite_reduced_GB_dgrad_p_set[OF dickson_grading_zero _ subset_dgrad_p_set_zero] lemmas reduced_GB_is_reduced_GB = reduced_GB_is_reduced_GB_dgrad_p_set[OF dickson_grading_zero _ subset_dgrad_p_set_zero] lemmas reduced_GB_is_GB = reduced_GB_is_GB_dgrad_p_set[OF dickson_grading_zero _ subset_dgrad_p_set_zero] lemmas reduced_GB_is_auto_reduced = reduced_GB_is_auto_reduced_dgrad_p_set[OF dickson_grading_zero _ subset_dgrad_p_set_zero] lemmas reduced_GB_is_monic_set = reduced_GB_is_monic_set_dgrad_p_set[OF dickson_grading_zero _ subset_dgrad_p_set_zero] lemmas reduced_GB_nonzero = reduced_GB_nonzero_dgrad_p_set[OF dickson_grading_zero _ subset_dgrad_p_set_zero] lemmas reduced_GB_pmdl = reduced_GB_pmdl_dgrad_p_set[OF dickson_grading_zero _ subset_dgrad_p_set_zero] lemmas reduced_GB_unique = reduced_GB_unique_dgrad_p_set[OF dickson_grading_zero _ subset_dgrad_p_set_zero] end (* od_term *) end (* theory *)
from __future__ import division import numpy as np import scipy import utils as ut import pairdict as pd import ppi import corum as co import cv import operator from Struct import Struct import itertools as it import sys from pandas import DataFrame cp_funcs = [ # ( function name, function, whether to use random mean/variance ) # 0 count of partially recovered gold cxs, first measure of havig/hart ("bader", lambda gold,cxs,cxppis: count_overlaps(gold, cxs, limit=0.25, func=bader_score), False), # 1 clustering-wise sensitivity, Brohee 2006 ("sensitivity", lambda gold,cxs,cxppis: avg_best(cxs, gold, sensitivity), True), # 2 clustering-wise ppv, Brohee 2006 ('ppv', lambda gold,cxs,cxppis: ppv(gold, cxs), True), # 3 geometric accuracy, Brohee 2006, third havig/hart ('accuracy', lambda gold,cxs,cxppis: geom_avg(avg_best(cxs, gold, sensitivity), ppv(gold, cxs)), True), # 4 geometric separation, Brohee 2006 ('separation', lambda gold,cxs,cxppis: geom_avg(separation(gold, cxs), separation(cxs, gold)), True), ('overlaps sens', lambda gold,cxs,cxppis: (count_overlaps(gold, cxs, limit=0.5, func=sensitivity)/len(gold)), True), ('overlaps sens rev', lambda gold,cxs,cxppis: (count_overlaps(cxs, gold, limit=0.5, func=sensitivity)/len(cxs)) if len(cxs)!=0 else 0, True), ('corr', lambda gold,cxs,cxppis: gold_corr(gold, cxs), True), #lambda gold,cxs,cxppis: avg_best(cxs, gold, sensitivity_adj) # 8 Nepusz 2012, second and optimized metric for havig/hart ('mmr',lambda gold,cxs,cxppis: max_match_ratio(gold, cxs), True), #('non_overlap', lambda gold,cxs,cxppis: 1-cxs_self_match_frac(cxs), False), False), #('auroc', lambda gold,cxs,cxppis: auroc(gold,cxppis), False), ('aupr', lambda gold,cxs,cxppis: aupr(gold, cxppis), False), ('nonov_iter', lambda gold,cxs,cxppis: 1-cxs_self_match_frac_iter(cxs), False), ('cliqueness_3_20', lambda gold,cxs,cxppis: cliqueness(filter_len(cxs, 3, 20), cxppis), False), #('ppi_pr', lambda gold,cxs,cxppis: prstats(gold, cxppis), False), ('sm_cxs_3', lambda gold,cxs,cxppis: 1/cxs_avg_size(filter_len(cxs, 3, None)), False), ('n_proteins', lambda gold,cxs,cxppis: count_uniques(cxs), False), ('n_complexes_3_20', lambda gold,cxs,cxppis: len(filter_len(cxs, 3, 20)), False) ] def stats(gold,cxs_list, cxppis_list=None, conv_to_sets=True, funcs=None): if conv_to_sets: gold = [set(c) for c in gold] cxs_list = [[set(c) for c in cxs] for cxs in cxs_list] funcs = funcs or ut.i0(cp_funcs) use_funcs = [f for f in cp_funcs if f[0] in funcs] print funcs arr = np.zeros(len(cxs_list),dtype=','.join(['f8']*len(funcs))) arr.dtype.names = funcs print '%s total maps.' % len(cxs_list) for i, (cxs, cxppis) in enumerate(zip(cxs_list, cxppis_list)): #sys.stdout.write(str(i)) print i arr[i] = np.array([f(gold, cxs, cxppis) for f in ut.i1(use_funcs)]) return arr def result_stats(sp, splits, cxstructs, nsp, funcs=None, split_inds=[0], cxs_sets=None, min_gold_size=3): """ split_inds: specifies which of the cxs_splits to use as gold--merges these indices. mar 2013 there are just two splits now, the train/cv set and the holdout set, so use index 0 for selection and 1 for testing. Note tree overfits and performs especially well on the training set. """ cxs_gold = result_gold(splits, sp, split_inds=split_inds, consv_sp=('Dm' if nsp==2 else '')) if min_gold_size>1: cxs_gold = [c for c in cxs_gold if len(c) >= min_gold_size] clstats = stats(cxs_gold, cxs_sets or [cstr.cxs for cstr in cxstructs], [cstr.cxppis for cstr in cxstructs], funcs=funcs) return Struct(cxstructs=cxstructs, stats=clstats) def select_best(clstruct, scorenames=['sensitivity','mmr','aupr','cliqueness_3_20','nonov_iter','n_proteins','n_complexes_3_20'], rfunc=operator.add, use_norm=False, dispn=15, score_factors=None, use_ranks=True, output_ranks=False, print_ranks=False, require_scores=None): cxstructs, stats = clstruct.cxstructs, clstruct.stats clusts = [cxstr.cxs for cxstr in cxstructs] scorenames = scorenames or list(stats.dtype.names) stats = stats[scorenames] ranks = rank_columns(stats) if use_ranks: stats = ranks else: if use_norm: stats = norm_columns(stats) if score_factors: stats = rescale_columns(stats, score_factors) inds = np.argsort(reduce(rfunc, [stats[n] for n in scorenames]))[::-1] if require_scores is not None: for req_name,thresh in require_scores: thresh = (np.median(clstruct.stats[req_name]) if thresh is None else thresh) inds = [i for i in inds if clstruct.stats[req_name][i] > thresh] nstats = len(stats) def filt_params(s): return " ".join([p[:2]+p.split('=')[1] for p in s.split(',')]) show_columns = (scorenames if require_scores is None else scorenames+ut.i0(require_scores)) d = DataFrame(clstruct.stats[inds[:dispn]][show_columns], index=["#%s: %sc %si %s" % (i,len(clusts[i]),len(cxstructs[i].cxppis), filt_params(cxstructs[i].params)) for i in inds[:dispn]]) print d.head(dispn) for i in inds[:dispn]: #print (i, ["%0.4f " % s for s in clstruct.stats[i]], len(clusts[i]), #len(cxstructs[i].cxppis), cxstructs[i].params) if print_ranks: print i, [nstats-s for s in ranks[i]] if output_ranks: return inds else: return clusts[inds[0]], cxstructs[inds[0]].cxppis, inds[0] def result_gold(splits, species, split_inds, make_unmerged=False, consv_sp='Dm'): if make_unmerged: print "Converting to unmerged using conserved:", (consv_sp if consv_sp else "None") ppi_corum,_,_ = ppi.load_training_complexes(species,'',consv_sp) splits = unmerged_splits_from_merged_splits(ut.i1(ppi_corum), [[ut.i1(s) for s in split] for split in splits]) gold = ut.i1(reduce(operator.add, [splits[i] for i in split_inds])) return gold def prstats(gold, ppis, prec=0.2): """ Pred_ints: list of pred_result.ppis, or clustering filtered predicted ppis. """ tested,ntest_pos = tested_ppis(gold, ppis) recalled = cv.preccheck(tested,pchecks=[prec],total_trues=ntest_pos)[0] return recalled def aupr(gold, ppis): """ Area under precision-recall. """ tested,ntest_pos = tested_ppis(gold, ppis) return cv.aupr(tested, ntest_pos) def unmerged_splits_from_merged_splits(unmerged, merged_splits): """ Unmerged: list of enumerated/named complex sets, usually from ppi.load_training_complexes. Merged_splits: A list of sets for each split (often 3 splits). """ merged_splits = [ut.i1(ms) for ms in merged_splits] unmerged = ut.i1(unmerged) usplits = [[] for ms in merged_splits] + [[]] # extra for non matches for u in unmerged: matches = [best_match(u, ms, sensitivity) for ms in merged_splits] which_split = np.argmax(matches) if max(matches) > 0 else -1 usplits[which_split].append(u) return usplits def gold_label_ppis(ppis, merged_splits, sp, gold_nsp): gold_consv = 'Dm' if gold_nsp>1 else '' ppi_cxs,_,_ = ppi.load_training_complexes(sp, '', gold_consv) train_cxs = unmerged_splits_from_merged_splits(ppi_cxs, merged_splits)[0] ppis = cv.gold_label_ppis(ppis, co.pairs_from_complexes(train_cxs)) return ppis def rescale_columns(arr, scale_factors): newarr = ut.arr_copy(arr) for i,n in enumerate(newarr.dtype.names): #newarr[n] = np.nan_to_num(newarr[n]/np.max(np.nan_to_num(newarr[n]))) newarr[n] = newarr[n] * scale_factors[i] return newarr def norm_columns(arr): newarr = ut.arr_copy(arr) for n in newarr.dtype.names: newarr[n] = scipy.stats.zscore(np.nan_to_num(newarr[n])) return newarr #def rescale_rand(arr, randarr): #newarr = ut.arr_copy(arr) #for n in newarr.dtype.names: #randmean = np.mean(randarr[n]) #datamean = np.mean(arr[n]) #newarr[n] = ( newarr[n] def rank_columns(arr): newarr = ut.arr_copy(arr) for n in newarr.dtype.names: newarr[n] = scipy.stats.rankdata(np.nan_to_num(newarr[n])) return newarr def max_match_ratio(gold, cxs): """ Nepusz 2012, deciding score used for c1 param choice in havig/hart. """ arr = arr_intersects(gold, cxs, func=bader_score) inds = zip(*np.where(arr>0)) # pairs of complexes that are matching at all. ind_scores = [(ind,arr[ind[0],ind[1]]) for ind in inds] ind_scores.sort(key=lambda x:x[1], reverse=True) x_used, y_used = set([]),set([]) scores = [] for (x,y),score in ind_scores: if x not in x_used and y not in y_used: x_used.add(x); y_used.add(y) scores.append(score) return sum(scores)/len(gold) def gold_corr(gold, cxs): """ gold: List of complexes from the gold standard cxs: List of complexes to compare against gold standard """ # Get list of all the proteins from the gold standard and make a nprots x # nprots array holding whether the proteins interact or not. Fill this in # with the gold standard, and with the cxs to test. Take the correlation # between these arrays. gold_prots = reduce(set.union, gold) gold_arr, cxs_arr = [complex_arr(c, gold_prots) for c in gold, cxs] return np.corrcoef(gold_arr.flat, cxs_arr.flat)[0,1] def geom_avg(a,b): return np.math.sqrt(a*b) def complex_arr(cxs, prots): arr = np.zeros((len(prots),len(prots))) ints_dict = co.corum_ints_duped([(i,ps) for i,ps in enumerate(cxs)]) p_inds = ut.list_inv_to_dict(prots) for p,partners in ints_dict.items(): if p in p_inds: for partner in partners: if partner in p_inds: arr[p_inds[p], p_inds[partner]] = 1 return arr def bader_score(a,b): # Bader/Hogue 2003 from Havig/Hart 2012 intersect = len(set.intersection(a,b)) return intersect**2/(len(a)*len(b)) def jaccard(a, b): return len(set.intersection(a,b))/len(set.union(a,b)) def sensitivity(a,b): # Brohee 2006 uses this as the criteria for 'sensitivity'. I had called it # asym_overlap previously. return len(set.intersection(a,b))/len(a) def ppv(setsa, setsb): # clustering-wise ppv from Brohee 2006 arr = arr_intersects(setsa, setsb) # Redundant steps in how their algo is presented were elminated but kept # here for clarity clust_ppvs = np.nan_to_num(np.max(arr, axis=0) / np.sum(arr, axis=0)) clust_sizes = [len(c) for c in setsb] overall_ppv = weighted_avg(clust_ppvs, clust_sizes) #return np.sum(np.max(arr, axis=0))/np.sum(arr) return overall_ppv def separation(setsa, setsb): # Row-wise separation. Brohee 2006. # Transpose arguments for col-wise separation. if len(setsa)==0 or len(setsb)==0: return 0 arr = arr_intersects(setsa, setsb) col_normed = np.nan_to_num(arr/np.sum(arr, axis=0)) row_normed = np.nan_to_num(np.array([arr[i,:]/np.sum(arr,axis=1)[i] for i in range(arr.shape[0])])) comb = col_normed * row_normed return np.mean(np.sum(comb, axis=1)) def arr_intersects(setsa, setsb, func=lambda a,b:len(set.intersection(a,b))): arr = np.zeros((len(setsa),len(setsb))) for i,a in enumerate(setsa): for j,b in enumerate(setsb): arr[i,j] = func(a,b) return arr def simpson(a,b): return len(set.intersection(a,b))/min([len(a),len(b)]) def subset_plus_one(a,b,minsize): if len(a)>=minsize and len(b)>=minsize: intersect = len(set.intersection(a,b)) if intersect > 0: if min(len(a),len(b)) <= intersect + 1: return 1 return 0 def sensitivity_adj(a,b): """ Tries to remove the issue that smaller complexes get biased towards high scores by subtracting the base case where just a single member overlaps. """ return (len(set.intersection(a,b))-1)/len(a) def best_match(a, setsb, func): return max([func(a, complexb) for complexb in setsb]) def best_match_item(a, setsb, func): return max(setsb, key=lambda b: func(a,b)) def best_match_index(a, setsb, func): return np.argmax([func(a, complexb) for complexb in setsb]) def avg_best(setsa, setsb, func, weighted=True): scores = [best_match(a, setsb, func) for a in setsa] if weighted: lengths = [len(c) for c in setsa] return weighted_avg(scores, lengths) else: return np.mean([scores]) def weighted_avg(scores, weights): return np.sum(np.array(scores)*np.array(weights)) / np.sum(weights) def first_match(a, setsb, limit, skip_self=False, func=ppv): if skip_self: newsetsb = list(setsb) newsetsb.remove(a) setsb = newsetsb for b in setsb: if func(a,b) > limit: return b def matches(a, setsb, limit=0.5): for b in setsb: if jaccard(a,b) > limit: yield b def overlaps(setsa, setsb, limit, **kwargs): #return [a for a in setsa if matches(a,setsb).next()] return [a for a in setsa if first_match(a,setsb, limit, **kwargs)] def count_overlaps(setsa, setsb, limit=0.5, **kwargs): return len(list(overlaps(setsa,setsb, limit,**kwargs))) def matchpairset(pair,losetpairs): for p in losetpairs: if (pair[0] in p[0] and pair[1] in p[1]) or (pair[1] in p[0] and pair[0] in p[1]): return True def ints_overlap(pairs_iterables): """ Provide a list: [pairsa, pairsb(, pairsc)] """ return pds_overlap([pd.PairDict(ppis) for ppis in pairs_iterables]) def pds_overlap(pds): """ pds: list of pairdicts """ return len(pds_intersect_pd(pds).d) def pds_intersect_pd(pds): """ pds: list of pairdicts """ return reduce(pd.pd_intersect_avals, pds) def pds_alloverlaps(named_pds): """ input: [(name, pairdict), ...] """ for num in range(2,len(named_pds)+1): for n_pd in it.combinations(named_pds, num): print ut.i0(n_pd), pds_overlap(ut.i1(n_pd)) def triple_venn(three_ppis, names=['a','b','c']): # Can send output to venn3(sizes, names) for plotting ppis_names = zip(three_ppis, names) full_sizes = [len(p) for p in three_ppis] print zip(names, full_sizes) trip = ints_overlap(three_ppis) print names, trip intersects_2 = [] for (a,namea),(b,nameb) in it.combinations(ppis_names,2): intersect = ints_overlap([a,b]) print namea, nameb, "--", intersect intersect_2 = intersect - trip print namea, nameb, "-only-", intersect_2 intersects_2.append((set([namea,nameb]), intersect_2)) only_singles = [] for i,(a,namea) in enumerate(ppis_names): #print namea, len(a), trip, intersects_2 #debug only_single = (len(a) - trip - sum([x[1] for x in intersects_2 if namea in x[0]])) print namea, "only:", only_single only_singles.append(only_single) # for output into matplotlib_venn format set_sizes = [0] * 7 set_sizes[6] = trip set_sizes[:2], set_sizes[3] = only_singles[:2], only_singles[2] set_sizes[2], set_sizes[4], set_sizes[5] = ut.i1(intersects_2) return set_sizes, names def cxs_avg_size(cxs): return np.mean([len(c) for c in cxs]) def cxs_self_match_frac(cxs, limit=.6, func=bader_score): return (len(overlaps(cxs,cxs,limit,func=func,skip_self=True))/len(cxs) if len(cxs)!=0 else 0) def cxs_self_match_frac_iter(cxs, ntests=10, func=bader_score): # should instead consider limit=1 rather than 0--1 is meaningful, 0 is not limits = np.arange(0,1,1/ntests) return np.mean([cxs_self_match_frac(cxs, limit=lim, func=func) for lim in limits]) def ints_overlap_orth(aints, bints, b2a): """ Make a list of orthogroup pair sets, instead of just pairs of genes, then query those for a given pair of genes in species A. """ def matchpairset(pair,losetpairs): for p in losetpairs: if ((pair[0] in p[0] and pair[1] in p[1]) or (pair[1] in p[0] and pair[0] in p[1])): return True bints_spa = [(b2a[g[0]],b2a[g[1]]) for g in bints if g[0] in b2a and g[1] in b2a] return len([pair for pair in aints if (matchpairset(pair,bints_spa))]) def consv_pairs(ints, odict): return [p for p in ints if p[0] in odict and p[1] in odict] def ints_overlap_consv(intlists, odict): """ Get the overlap just of the interactions for which each member of the pair has an ortholog in the given odict. """ return ints_overlap([consv_pairs(ints,odict) for ints in intlists]) def count_trues(ppis, gold, ncounts=10000): pdgold = pd.PairDict(gold) print "Total trues:", len(gold) count = 0 for n,p in enumerate(ppis): if pdgold.contains((p[0],p[1])): count += 1 if n % ncounts == 0: print "%s True of first %s" %(count, n) def combine_clstructs(ca, cb): return Struct(cxstructs = ca.cxstructs + cb.cxstructs, stats=np.concatenate((ca.stats, cb.stats))) def tested_ppis(gold_cxs, ppis): gold_ints = co.pairs_from_complexes(gold_cxs) ntest_pos = len(gold_ints) pdtrues = pd.PairDict(gold_ints) ppis = [(p[0],p[1],p[2],1 if pdtrues.contains(tuple(p[:2])) else 0) for p in ppis] return ppis, ntest_pos def auroc(gold_cxs, cxppis): cxppis, ntest_pos = tested_ppis(gold_cxs, cxppis) xs,ys = cv.roc(cxppis) return cv.auroc(xs,ys) def cliqueness(cxs, cxppis): pdints = pd.PairDict(cxppis) return np.mean([clique_score(c,pdints) for c in cxs]) def clique_score(cx, pdints): cx_ints = co.pairs_from_complexes([cx]) return len([1 for edge in cx_ints if pdints.contains(edge)])/len(cx_ints) def filter_len(lol, min_len=0, max_len=None): return [items for items in lol if len(items) >= min_len and (max_len is None or len(items) <= max_len)] def count_uniques(lol): return (len(reduce(set.union, [set(items) for items in lol])) if len(lol)>0 else 0)
[STATEMENT] lemma sum_component_iarray: assumes a: "\<forall>x\<in>S. i<IArray.length (f x)" and f: "finite S" and S: "S\<noteq>{}" \<comment> \<open>If S is empty, then the sum will return the empty iarray and it makes no sense to access the component i\<close> shows "sum f S !! i = (\<Sum>x\<in>S. f x !! i)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sum f S !! i = (\<Sum>x\<in>S. f x !! i) [PROOF STEP] using f a S [PROOF STATE] proof (prove) using this: finite S \<forall>x\<in>S. i < IArray.length (f x) S \<noteq> {} goal (1 subgoal): 1. sum f S !! i = (\<Sum>x\<in>S. f x !! i) [PROOF STEP] proof (induct S, simp) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x F. \<lbrakk>finite F; x \<notin> F; \<lbrakk>\<forall>x\<in>F. i < IArray.length (f x); F \<noteq> {}\<rbrakk> \<Longrightarrow> sum f F !! i = (\<Sum>x\<in>F. f x !! i); \<forall>x\<in>insert x F. i < IArray.length (f x); insert x F \<noteq> {}\<rbrakk> \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] case (insert x F) [PROOF STATE] proof (state) this: finite F x \<notin> F \<lbrakk>\<forall>x\<in>F. i < IArray.length (f x); F \<noteq> {}\<rbrakk> \<Longrightarrow> sum f F !! i = (\<Sum>x\<in>F. f x !! i) \<forall>x\<in>insert x F. i < IArray.length (f x) insert x F \<noteq> {} goal (1 subgoal): 1. \<And>x F. \<lbrakk>finite F; x \<notin> F; \<lbrakk>\<forall>x\<in>F. i < IArray.length (f x); F \<noteq> {}\<rbrakk> \<Longrightarrow> sum f F !! i = (\<Sum>x\<in>F. f x !! i); \<forall>x\<in>insert x F. i < IArray.length (f x); insert x F \<noteq> {}\<rbrakk> \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] have finite_F: "finite F" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite F [PROOF STEP] by (metis insert.hyps(1)) [PROOF STATE] proof (state) this: finite F goal (1 subgoal): 1. \<And>x F. \<lbrakk>finite F; x \<notin> F; \<lbrakk>\<forall>x\<in>F. i < IArray.length (f x); F \<noteq> {}\<rbrakk> \<Longrightarrow> sum f F !! i = (\<Sum>x\<in>F. f x !! i); \<forall>x\<in>insert x F. i < IArray.length (f x); insert x F \<noteq> {}\<rbrakk> \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] proof (cases "F={}") [PROOF STATE] proof (state) goal (2 subgoals): 1. F = {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) 2. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] case True [PROOF STATE] proof (state) this: F = {} goal (2 subgoals): 1. F = {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) 2. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] have "sum f (insert x F) !! i = f x !! i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sum f (insert x F) !! i = f x !! i [PROOF STEP] unfolding True [PROOF STATE] proof (prove) goal (1 subgoal): 1. sum f {x} !! i = f x !! i [PROOF STEP] by auto [PROOF STATE] proof (state) this: sum f (insert x F) !! i = f x !! i goal (2 subgoals): 1. F = {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) 2. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] also [PROOF STATE] proof (state) this: sum f (insert x F) !! i = f x !! i goal (2 subgoals): 1. F = {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) 2. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] have "... = (\<Sum>x\<in>insert x F. f x !! i)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. f x !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] unfolding True [PROOF STATE] proof (prove) goal (1 subgoal): 1. f x !! i = (\<Sum>x\<in>{x}. f x !! i) [PROOF STEP] by auto [PROOF STATE] proof (state) this: f x !! i = (\<Sum>x\<in>insert x F. f x !! i) goal (2 subgoals): 1. F = {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) 2. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) goal (1 subgoal): 1. sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] . [PROOF STATE] proof (state) this: sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] case False [PROOF STATE] proof (state) this: F \<noteq> {} goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] have hyp: "(sum f F !! i)=(\<Sum>x\<in>F. f x !! i)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sum f F !! i = (\<Sum>x\<in>F. f x !! i) [PROOF STEP] proof (rule insert.hyps) [PROOF STATE] proof (state) goal (2 subgoals): 1. \<forall>x\<in>F. i < IArray.length (f x) 2. F \<noteq> {} [PROOF STEP] show "\<forall>x\<in>F. i < IArray.length (f x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>x\<in>F. i < IArray.length (f x) [PROOF STEP] by (metis insert.prems(1) insertCI) [PROOF STATE] proof (state) this: \<forall>x\<in>F. i < IArray.length (f x) goal (1 subgoal): 1. F \<noteq> {} [PROOF STEP] show "F \<noteq> {}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. F \<noteq> {} [PROOF STEP] using False [PROOF STATE] proof (prove) using this: F \<noteq> {} goal (1 subgoal): 1. F \<noteq> {} [PROOF STEP] . [PROOF STATE] proof (state) this: F \<noteq> {} goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: sum f F !! i = (\<Sum>x\<in>F. f x !! i) goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] have "sum f (insert x F) !! i = (f x + sum f F) !! i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sum f (insert x F) !! i = (f x + sum f F) !! i [PROOF STEP] by (metis insert.hyps(1) insert.hyps(2) sum_clauses(2)) [PROOF STATE] proof (state) this: sum f (insert x F) !! i = (f x + sum f F) !! i goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] also [PROOF STATE] proof (state) this: sum f (insert x F) !! i = (f x + sum f F) !! i goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] have "... = (f x) !! i + (sum f F !! i)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (f x + sum f F) !! i = f x !! i + sum f F !! i [PROOF STEP] proof (rule plus_iarray_component) [PROOF STATE] proof (state) goal (2 subgoals): 1. i < IArray.length (f x) 2. i < IArray.length (sum f F) [PROOF STEP] obtain a where a: "a\<in>F" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>a. a \<in> F \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using False [PROOF STATE] proof (prove) using this: F \<noteq> {} goal (1 subgoal): 1. (\<And>a. a \<in> F \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: a \<in> F goal (2 subgoals): 1. i < IArray.length (f x) 2. i < IArray.length (sum f F) [PROOF STEP] have finite_C: "finite {IArray.length (f x) |x. x \<in> F}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite {IArray.length (f x) |x. x \<in> F} [PROOF STEP] using finite_F [PROOF STATE] proof (prove) using this: finite F goal (1 subgoal): 1. finite {IArray.length (f x) |x. x \<in> F} [PROOF STEP] by auto [PROOF STATE] proof (state) this: finite {IArray.length (f x) |x. x \<in> F} goal (2 subgoals): 1. i < IArray.length (f x) 2. i < IArray.length (sum f F) [PROOF STEP] have not_empty_C: "{IArray.length (f x) |x. x \<in> F} \<noteq>{}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. {IArray.length (f x) |x. x \<in> F} \<noteq> {} [PROOF STEP] using False [PROOF STATE] proof (prove) using this: F \<noteq> {} goal (1 subgoal): 1. {IArray.length (f x) |x. x \<in> F} \<noteq> {} [PROOF STEP] by simp [PROOF STATE] proof (state) this: {IArray.length (f x) |x. x \<in> F} \<noteq> {} goal (2 subgoals): 1. i < IArray.length (f x) 2. i < IArray.length (sum f F) [PROOF STEP] show "i < IArray.length (f x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. i < IArray.length (f x) [PROOF STEP] by (metis insert.prems(1) insertI1) [PROOF STATE] proof (state) this: i < IArray.length (f x) goal (1 subgoal): 1. i < IArray.length (sum f F) [PROOF STEP] show "i < IArray.length (sum f F)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. i < IArray.length (sum f F) [PROOF STEP] unfolding length_sum_iarray[OF finite_F False] [PROOF STATE] proof (prove) goal (1 subgoal): 1. i < Max {IArray.length (f x) |x. x \<in> F} [PROOF STEP] unfolding Max_gr_iff[OF finite_C not_empty_C] [PROOF STATE] proof (prove) goal (1 subgoal): 1. Bex {IArray.length (f x) |x. x \<in> F} ((<) i) [PROOF STEP] proof (rule bexI[of _ "IArray.length (f a)"]) [PROOF STATE] proof (state) goal (2 subgoals): 1. i < IArray.length (f a) 2. IArray.length (f a) \<in> {IArray.length (f x) |x. x \<in> F} [PROOF STEP] show "i < IArray.length (f a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. i < IArray.length (f a) [PROOF STEP] using insert.prems(1) a [PROOF STATE] proof (prove) using this: \<forall>x\<in>insert x F. i < IArray.length (f x) a \<in> F goal (1 subgoal): 1. i < IArray.length (f a) [PROOF STEP] by auto [PROOF STATE] proof (state) this: i < IArray.length (f a) goal (1 subgoal): 1. IArray.length (f a) \<in> {IArray.length (f x) |x. x \<in> F} [PROOF STEP] show "IArray.length (f a) \<in> {IArray.length (f x) |x. x \<in> F}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. IArray.length (f a) \<in> {IArray.length (f x) |x. x \<in> F} [PROOF STEP] using a [PROOF STATE] proof (prove) using this: a \<in> F goal (1 subgoal): 1. IArray.length (f a) \<in> {IArray.length (f x) |x. x \<in> F} [PROOF STEP] by auto [PROOF STATE] proof (state) this: IArray.length (f a) \<in> {IArray.length (f x) |x. x \<in> F} goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: i < IArray.length (sum f F) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: (f x + sum f F) !! i = f x !! i + sum f F !! i goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] also [PROOF STATE] proof (state) this: (f x + sum f F) !! i = f x !! i + sum f F !! i goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] have "...= (f x) !! i + (\<Sum>x\<in>F. f x !! i)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. f x !! i + sum f F !! i = f x !! i + (\<Sum>x\<in>F. f x !! i) [PROOF STEP] unfolding hyp [PROOF STATE] proof (prove) goal (1 subgoal): 1. f x !! i + (\<Sum>x\<in>F. f x !! i) = f x !! i + (\<Sum>x\<in>F. f x !! i) [PROOF STEP] .. [PROOF STATE] proof (state) this: f x !! i + sum f F !! i = f x !! i + (\<Sum>x\<in>F. f x !! i) goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] also [PROOF STATE] proof (state) this: f x !! i + sum f F !! i = f x !! i + (\<Sum>x\<in>F. f x !! i) goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] have "...= (\<Sum>x\<in>insert x F. f x !! i)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. f x !! i + (\<Sum>x\<in>F. f x !! i) = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] by (metis (mono_tags) insert.hyps(1) insert.hyps(2) sum_clauses(2)) [PROOF STATE] proof (state) this: f x !! i + (\<Sum>x\<in>F. f x !! i) = (\<Sum>x\<in>insert x F. f x !! i) goal (1 subgoal): 1. F \<noteq> {} \<Longrightarrow> sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] show "sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i)" [PROOF STATE] proof (prove) using this: sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) goal (1 subgoal): 1. sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) [PROOF STEP] . [PROOF STATE] proof (state) this: sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: sum f (insert x F) !! i = (\<Sum>x\<in>insert x F. f x !! i) goal: No subgoals! [PROOF STEP] qed
<a href="https://colab.research.google.com/github/culpritgene/biolearner/blob/main/Hopfeild_Basics.ipynb" target="_parent"></a> ```python import numpy as np from sympy import * import matplotlib.pyplot as plt import itertools import seaborn as sns sns.set_style('whitegrid') import plotly.express as px from plotly import graph_objects as go %config InlineBackend.figure_format = 'retina' ``` /usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead. import pandas.util.testing as tm Link to slides: https://docs.google.com/presentation/d/1f_OykdISf2Ik9vKKgW9mwbrdZuvxvbiBbiDpkITVWTw/edit?usp=sharing Link to talk: ... ### Similarities between Hopfield Networks and other algorithms 1. Small region of brain. Unipartite Graph where all neurons in principle can be connected with each other. 2. Phase space of the generalized coordinates with K* stable points. Any ball inserted into the phase space near a stable point k_i will fall into it. In HN we have additional features: we can put specific vectors inside each stable point. We have specific update rules for the generalized coordinates ... 3. Spinglass. A 3d array of magnetic dipoles (spins) which can take only two position +1/-1. 4. Coinsicion Matrix of a Random forest, each tree in which does only one split for the same feature. 5. V (features) matrix in SVD, but we additionally project each vector on the corner of a binary hypercube 1. Interactive example: http://faculty.etsu.edu/knisleyj/neural/neuralnet3.html 2. Math of binary HN (Hinton) https://www.youtube.com/watch?v=DS6k0PhBjpI 3. Math of binary HN (lecture) https://www.youtube.com/watch?v=yl8znINLXdg 4. Modern (binary) HN (krotov) https://www.youtube.com/watch?v=lvuAU_3t134 5. Modern HN example (MNIST classification) https://github.com/DimaKrotov/Dense_Associative_Memory/blob/master/Dense_Associative_Memory_training.ipynb ### Binary Hopfield Networks ```python # Quick Reminder: expression of the form 0.5*q.T@W@q (where q is vector [1,N]) bassically means that we sum up # all the interaction terms between elements of the q and weight them by coefficients stored in W. # We can think about it as a total innervation (total synaptic energy) of a biological neural network # given particular pattern of activations and particular connectome (synaptic strength for each pair of neurons) # although, importantly, here, unlike in real brains (afaik) when only one neuron in the strongly linked couple gets # activated - this decreases total Energy of the system. A = np.random.rand(100,100) c = np.random.rand(100) print(np.sum(np.outer(c,c)*A), c@A@c) ``` 1168.136713053695 1168.1367130536948 ```python ### Test V.T@M@V, where M is constructed with Hebbian rule v = np.array([-1,-1,1,1]) M = np.outer(v,v) v2 = np.array([1,-1,1,1]) v3 = np.array([1,1,-1,-1]) print('Memorized vector gives maximum energy:', v.T@M@v) print('Corrupted vector gives lower energy:', v2.T@M@v2) print('Fully inverted vector gives same energy:', v3.T@M@v3) ``` Memorized vector gives maximum energy: 16 Corrupted vector gives lower energy: 4 Fully inverted vector gives same energy: 16 ```python def generate_binary_Hopfield_Net(N: int, K: int, zero_diag=False): """ Generate {k1,k2,...,k_K} random binary vectors of length N. Obtain Hebbian 'coincision' matrices for each individual vector k. Sum Hebbian matrices to obtain final W matrix of the Hopfield Network. inputs: - N: length of each pattern (number of neurons representing one pattern) - K: number of 'memorized' patterns which will be placed in the local minima of the energy function E - zero_diag: if True, diagonal of W is set ot zero (classical HN) outputs: - W: Hopfield Net matrix with Hebbian weigths [N,N] - {k_i}: set of randomly generated and 'memorized' patterns of length N """ ks = np.random.normal(size=[K,N]) ks = np.sign(ks) W = ks.T@ks # same as: # W = np.array([np.outer(k,k) for k in ks]).sum(axis=0) if zero_diag: np.fill_diagonal(W,0) return W, ks.astype(int) ``` ```python # does not render in collab without TeX installed W, ks = generate_binary_Hopfield_Net(4,3) E = MatrixSymbol('-E',1,1) Eq(E, MatMul(Matrix(ks[0]).T, MatMul(Matrix(W), Matrix(ks[0])))) ## add final value ``` Eq(-E, Matrix([[-1, 1, 1, -1]])*(Matrix([ [ 3.0, -1.0, -1.0, -1.0], [-1.0, 3.0, 3.0, -1.0], [-1.0, 3.0, 3.0, -1.0], [-1.0, -1.0, -1.0, 3.0]])*Matrix([ [-1], [ 1], [ 1], [-1]]))) ## Energy Landscape ### plot Functions defined ```python def plot_Energy_Landscape(Es, Vs, kinds, mirrored=False, trajectory=None): """ Makes plotly interactive graph of an Energy function for a small Hopfield Network inputs: Es: vector of Energies ordered by Vs Vs: generated by permutations binary vectors kinds: indices of K vecots on which this Hopfiel Network was build (should have minimal energies) """ if W.shape[0]<8: tt = np.array([str(tuple(l)) for l in (Vs.T).tolist()]) # generate text vector representations else: tt = [] K_Es = Es[kinds] # select energies for K patterns ttk = tt[kinds] if len(tt)>0 else [] fig = go.Figure() fig.update_layout( height=450, title_text="Energy Landscape" + "<br>(hover to see vectors)" if W.shape[0]<8 else "", yaxis=dict(title_text="Energy")) fig.add_trace(go.Scatter(y=Es, text=tt, mode='lines+markers', name='E-landscape', hoverinfo='text+x+y')) fig.add_trace(go.Scatter(x=kinds, y=K_Es, text=ttk, mode='markers', name='K-patterns', hoverinfo='text+x+y')) if mirrored: kinds_star = np.mean(np.arange(len(Es)))-(kinds-np.mean(np.arange(len(Es)))) # flip off central axis fig.add_trace(go.Scatter(x=kinds_star, y=K_Es, text=ttk, mode='markers', name='K-mirrored', hoverinfo='text+x+y')) if trajectory: #trajectory[0] = np.mean(np.arange(len(Es)))-(trajectory[0]-np.mean(np.arange(len(Es)))) # flip off central axis fig.add_trace(go.Scatter(x=trajectory[0], y=trajectory[1], text=ttk, mode='markers', name='mirrored_traj', hoverinfo='text+x+y')) fig.show() ``` ```python def make_Energy_landscape(W: np.ndarray): """ Explicitely defines every possible binary vector and calculates Energy of the particular Hopfield Network for each. inputs: - W: Hopfield Net weigths Matrix [N,N] output: - Vs: array of generated binary vectors - Es: vector of scalar Energies of size [1,N] """ if W.shape[0]>10: raise ValueError('The dimension of the Hopfield Net is too large \n to generate all possible vecs by explicit permutations.') Vs = np.array(list(itertools.product([-1, 1], repeat=W.shape[0]))).T Es = -0.5*(Vs.T*(W@Vs).T).sum(axis=1) return Vs, Es def locale_any_vectors(Vs: np.ndarray, ks: np.ndarray): """ Locates positions of any k vectors [n1,N] in the array Vs of other vectors [N,n2] by elementwise comparison This should return unique indices as long as Vs contains unique vectors in its rows. NOTE: This method expects Vs to be *transposed* relative to 'locale_K_vectors' method! inputs: - Vs: array of vectors of size [N,n2] in which to search for specified vectors - k: query vectors of size [n1,N] output: - kinds: indices of k query vectors in the Vs array """ kinds = [] for k in ks: kinds.append(np.argmax((Vs==k).sum(axis=1))) return kinds def locale_K_vectors(Vs: np.ndarray, ks: np.ndarray): """ *This is only suitable for finding vectors with largest norms.* Locates positions of specified query vectors k [n1,N] in the array of other vectors [N,n2] using dot product as signal. inputs: - Vs: array of vectors of size [N,n2] in which to search for specified vectors - k: query vectors of size [n1,N] output: - kinds: indices of k query vectors in the Vs array """ kinds = (ks@Vs).argmax(axis=1) return kinds ``` ### operations ```python ### Lets check energy landscape. Here we can simply permute through all possible states of our neural network ('query' vectors) ### and calculate energy function for each. TODO: think how Energy can be projected onto 1/2 dimensional rep. of vectors Vs, Es = make_Energy_landscape(W) kinds = locale_any_vectors(Vs.T, ks) ``` ```python plot_Energy_Landscape(Es, Vs, kinds, mirrored=True) ``` <html> <head><meta charset="utf-8" /></head> <body> <div> <div id="585b471d-aa03-4dc7-903c-99ccf1073e5a" class="plotly-graph-div" style="height:450px; width:100%;"></div> </div> </body> </html> ```python ### Try changing N and K # 1. Generate Hopfield Net (W) with N neurons and K memorized patterns # 2. Make energy landscape for W by explicitly probing each 2**N vectors (I've set a limit N<12, in order to save colab's memory) # 3. Find memorized K vectors in the energy landscape # 4. Plot Energy landscape with marked positions of the memorized patterns W, ks = generate_binary_Hopfield_Net(N=5,K=5) print(ks) Vs, Es = make_Energy_landscape(W) kinds = locale_K_vectors(Vs, ks) plot_Energy_Landscape(Es, Vs, kinds, mirrored=False) ``` [[-1 -1 -1 1 1] [ 1 -1 -1 1 1] [-1 -1 1 1 -1] [-1 1 1 1 1] [-1 1 -1 1 -1]] <html> <head><meta charset="utf-8" /></head> <body> <div> <div id="b201f042-228f-4423-947e-cf3fe0e651a6" class="plotly-graph-div" style="height:450px; width:100%;"></div> </div> </body> </html> # Update Rule ### Functions defined ```python def update_rule_sync(q: np.ndarray, W: np.ndarray, eps=1e-6, bias=0): """ Simplest synchronous update rule for binary Hopfield Network If the 'field' acting on an element q_i has different sign (direction) than q_i: change q_i sign to the opposite. If q_i is aligned with the field - don't change it. Note: added eps because sometimes 0 values occured after update. """ return np.sign(W@q+bias+eps).astype(int) def update_rule_async_random(q: np.ndarray, W: np.ndarray, eps=1e-6, bias=0): """ Simplest Asynchronous update rule for binary Hopfield Network If the 'field' acting on an element q_i has different sign (direction) than q_i: change q_i sign to the opposite. If q_i is aligned with the field - don't change it. """ for qi in np.random.choice(np.arange(len(q)), size=len(q), replace=False): q[qi] = np.sign(W[qi,:]@q) return q.astype(int) def retrive_memorized(q: np.ndarray, W: np.ndarray, update_rule, bias=0, maxiteration=500): """ Update cycle which will drive query vector to one of the local minima of the binary Hopfield Network. If number of stored (in W) patterns K is below K* (K* << N^2) (memory limit for HN with a given update rule) it should guarantee to retrive one of this vectors. If K>K*, there is no guarantee that the retrived pattern will be among K. Note: TODO: This function will not converge if q* will fall into metastable state (subset of minimas transitioning into one another in cycle) inputs: - q: query vector - W: Hopfield Network weigths matrix - update_rule: function describing the update rule of the Hopfiel Network outputs: - q: retrived memorized vector closest to q - E_traj: Energy trajectory for q updates - q_traj: ordered list of updated q vectors with the final form on the right """ dE = np.inf Ef = lambda x: -0.5*x.T@[email protected](bias*x) E1, E0 = Ef(q), np.inf E_traj = [E1] q_traj = [q] itr = 0 while (E1<E0) and itr<maxiteration: q = update_rule(q,W,bias) E1,E0 = Ef(q), E1 E_traj.append(E1) q_traj.append(q) itr += 1 return q, E_traj, q_traj ``` ### operation ```python # Do optimization starting from the Energy maximum # Check if it converged to any stored pattern # Plot Energy landscape with the optimization trace # (Hm, something is wrong with the coordinates of the trace values, anyway they jump over the whole landscape) W, ks = generate_binary_Hopfield_Net(8, 5) Vs, Es = make_Energy_landscape(W) kinds = locale_any_vectors(Vs.T, ks) print('Memorized patterns:') print(ks) peak = Vs.T[np.argmax(Es)] q, E_traj, q_traj = retrive_memorized(peak, W, update_rule=update_rule_async_random) trajectory = (locale_any_vectors(Vs.T, q_traj), E_traj) print('Number of steps:', len(E_traj)) print('Energy trajectory:') print(E_traj) print('Updated query:') print(np.stack(q_traj)) print('Converged to minima?') print('Yes!' if ((ks==q).all(axis=1)|(ks==(-1)*q).all(axis=1)).any() else 'No!') plot_Energy_Landscape(Es, Vs, kinds, trajectory=trajectory) ``` Memorized patterns: [[ 1 -1 -1 1 1 -1 1 1] [ 1 -1 1 -1 -1 -1 1 1] [ 1 -1 1 1 -1 -1 -1 1] [ 1 -1 1 1 -1 -1 -1 -1] [ 1 -1 1 -1 1 -1 1 1]] Number of steps: 4 Energy trajectory: [-4.0, -54.5, -62.0, -62.0] Updated query: [[ 1 -1 1 0 -1 -1 -1 1] [ 1 -1 1 1 -1 -1 -1 1] [ 1 -1 1 1 -1 -1 -1 1] [ 1 -1 1 1 -1 -1 -1 1]] Converged to minima? Yes! <html> <head><meta charset="utf-8" /></head> <body> <div> <div id="a22d7bcd-c53a-4fb5-a820-7e33e3fc2430" class="plotly-graph-div" style="height:450px; width:100%;"></div> </div> </body> </html> # Simulations Here we conduct some simulations in order to empricially prove several statements about binary Hopfield Nets: 1. K* = 0.14*N (we can not reliably store more than 0.14*N patterns using Hebbian learning rule (outer product)) 2. Retrival capability drops with the distance from the memorized patterns (and does so unevenly for networks with different K/N) 3. Asynchronous update is more accurate than synchronous ### functions defined ```python def corrupt_vector(v, h): assert h<len(v), f'Number of corrupted bits can not be higher than the dimension of the vector {len(v)}' cind = np.random.choice(len(v), h, replace=False) v[cind] *= (-1) return v ``` ```python def retrival_rate_from_random(W, ks, update_rule, reps=40,): """ For a number of random pattern 'reps' of dimension [1,W.shape[0]] we run Hopfield updates and return number of converged results. inputs: - W: HN weights [N,N] - ks: HN stored patterns [K,N] - update_rule: function of the update rule (use lambda to specify parameters) - reps: number of replicates (R) outputs: - res: array of shape [R,K] """ K, N = ks.shape res = [] queries = np.random.choice([-1,1], size=[reps,N]) for q in queries: q, et, vt = retrive_memorized(q, W, update_rule) hits = ((ks==q).all(axis=1)|(ks==(-1)*q).all(axis=1)) res.append(hits.astype(int)) return np.array(res) def retrival_rate_vs_error(W, ks, update_rule, distances, reps=40, use_first_k=-1): """ This function repeatedly runs 'retrival operation' on the redacted (noised) stored patterns of the binary Hopfield Net W. For each Hammind distance (number of erronious bits introduced) it creates multiple replicates (randomly) and optimized each one, storing number of exact hits (complete convergence back to *one* of the stored patterns, but not necesserily the original one). inputs: - W: HN weights [N,N] - ks: HN stored patterns [K,N] - update_rule: function of the update rule (use lambda to specify parameters) - distances: array [1,D] containing Hamming distance values - reps: number of replicates (R) to check for each distance, for each original pattern used as seed - use_first_k: number of original patterns to use as seeds (K_th). if '-1' use all ks. outputs: - res: array of shape [K_th,D,R,K] containing hits for every replica. First dimension corresponds to the number of seeds used, second to the number of error thresholds used, third to the number of replicates, fourth - to the number of patterns (ks) exact correspondence with which was checked - meta: scalar values describing each optimization. Length - number of update steps, dE - energy decrease from the 0 step to the last step. """ res = [] meta = [] for i in range(len(ks[:use_first_k])): res.append([]) meta.append([]) for j in range(len(distances)): res[i].append([]) meta[i].append([]) for _ in range(reps): cv = corrupt_vector(ks[i], distances[j]) cv, et, vt = retrive_memorized(cv, W, update_rule) metas = (len(et), et[-1]-et[0]) meta[i][j].append(metas) hits = ((ks==cv).all(axis=1)|(ks==(-1)*cv).all(axis=1)) res[i][j].append(hits.astype(int)) res = np.array(res) meta = np.array(meta) return res, meta ``` ```python def check_retrival_over_N_and_K(Ns, Ks, update_rule): reses = [] for i,N in enumerate(Ns): reses.append([]) for K in Ks: W, ks = generate_binary_Hopfield_Net(N, K) res = retrival_rate_from_random(W, ks, update_rule, reps=100) reses[i].append(res.any(axis=-1)) return np.array(reses) ``` ### plot Functions defined ```python # We can see in that for a very small Hamming distance synchronous update performes significantly worse than asynchronous # (it also goes to a local minima in less steps. Not shown) def plot_Hamming_dist_vs_retival_rate(res, N, K, distances, save=False, suffix=''): """ use plot_Hamming_dist_vs_retival_rate_NEW instead. """ fig, ax = plt.subplots(1,1) for i in range(res.shape[0]): ax.plot(distances, res[i,...].any(axis=-1).mean(axis=1), label=f'k-{i}') ax.set_xlabel('Hamming Distance from stable pattern') ax.set_ylabel('Fraction of decorrupted') # plt.legend() plt.title(f'Retrival rate vs Hamming distance (N={N}, K={K})') if save: plt.savefig(f'Retrival_rate_vs_Hammim_distance_{suffix}.png', dpi=100) def plot_Hamming_dist_vs_retrival_rate_NEW(reses, Ns, Ks, distances, save=False, suffix=''): fig, ax = plt.subplots(1,1) for i,res in enumerate(reses): mu = res.any(axis=-1).mean(axis=-1).mean(0) sigma = res.any(axis=-1).std(axis=-1).mean(0) ax.plot(distances, mu, label=f'N={Ns[i]};K={Ks[i]}') ax.fill_between(distances, mu-sigma/np.sqrt(res.shape[2]), mu+sigma/res.shape[2], alpha=0.8) ax.set_xlabel('Hamming Distance from stable pattern') ax.set_ylabel('Fraction of converged to any from K') plt.legend() plt.title(f'Retrival rate vs Hamming distance for different K') if save: plt.savefig(f'Retrival_rate_vs_Hammim_distance_by_K_stored_{suffix}.png', dpi=100) def plot_Network_capacity_vs_N_for_two_update_rules(retrival_async, retrival_sync, Ns): fig, ax = plt.subplots(1,1) colors = ['firebrick', 'green', 'blue'] for i in range(retrival_async.shape[0]): mu1, mu2 = retrival_async[i].mean(axis=-1), retrival_sync[i].mean(axis=-1) plt.plot(Ks, mu1, color=colors[i], label=f'mu, async; N={Ns[i]}') plt.plot(Ks, mu2, color=colors[i], linestyle='--', label=f'mu, sync; N={Ns[i]}') plt.xlabel('K stored') plt.ylabel('Fraction of converged to any from K') plt.legend() plt.title('Network capacity K* vs N') plt.savefig('Network_capacity_vs_K_sync_vs_async.png', dpi=100) def plot_Network_capacity_vs_N(retrival_statistics, Ns): fig, ax = plt.subplots(1,1) for r, N in zip(retrival_statistics, Ns): mu, sigma = r.mean(axis=-1), r.std(axis=-1) plt.plot(Ks, mu, label=f'N={N}') plt.fill_between(Ks, mu-sigma/np.sqrt(100), mu+sigma/np.sqrt(100), alpha=0.8) plt.xlabel('K stored') plt.ylabel('Fraction of converged to any from K') plt.legend() plt.title('Network capacity K* vs N') plt.savefig('Network_capacity_vs_K.png', dpi=100) ``` ```python ``` ```python def make_heatmap(x,y,z, **kwargs): return go.Heatmap(x=x, y=y, z=z, xgap=1.5, ygap=1.5, zmin=0, zmax=res[0].mean(axis=0).max(), **kwargs) def make_heatmap_frame(step, **kwargs): return go.Frame(data=[go.Heatmap(**kwargs)], layout=go.Layout(title_text=title(step)) ) def make_animated_heatmap(res): """ Plots animated confusion matrix for stored patterns K. Main diagonal contains fraction of de-corrupted patterns which were aligned with their initial minima. Off-diagonal cells show de-corrupted patterns which ended up aligning with memorized stable minima different from their initial one (better when falling into spurious state, but still erroneous retirval) inputs: - res: np.array, output of the 'retrival_rate_vs_error' function """ title = lambda x: f"Confusion Matrix for updated vectors <br> Hamming Distance: {x}" xxs = np.arange(res.shape[0]) yys = np.arange(res.shape[0])[::-1] button_dict = dict(label="Play", method="animate", args=[None, {"frame": {"duration": 700}}]) fig = go.Figure(make_heatmap(xxs, yys, res[:,0,...].mean(axis=1))) fig.update_layout({'title':title(0), 'width':500, 'height':500, 'autosize':False}) fig.update_layout({'updatemenus':[{'type':"buttons", 'buttons':[button_dict]}] }) fig.frames = [make_heatmap_frame(step=i, x=xxs, y=yys, z=res[:,i,:,:].mean(axis=1)) for i in range(res.shape[1])] fig.show() ``` ### operations ### Compare Network capacity for the different K/N ratios ```python Ns, Ks = [50,100,150], [5, 8, 10, 12, 15, 17, 20, 25] retrival_async = check_retrival_over_N_and_K(Ns, Ks, update_rule=update_rule_async_random) retrival_sync = check_retrival_over_N_and_K(Ns, Ks, update_rule=update_rule_sync) ``` ```python plot_Network_capacity_vs_N(retrival_async, Ns) ``` ```python plot_Network_capacity_vs_N_for_two_update_rules(retrival_async, retrival_sync, Ns) ``` Here we plot retrival rate (to *any* stable point) vs Hamming distance from a given stable point. We observe that small deviations (e.g. 5 errors for 100 dimensional vector) are successfully linked to stored patterns even for K>K*=0.14*N. However, as we probe vectors with more errors (occupying unseen parts of the energy landscape), de-corruption ability of the Hopfield Networks with K>0.14*N drops much quicker. ```python ### Plot Hamming Distance (state of corruption) vs probability to retrive memorized state N, K = 30, 5 hammings = np.arange(15) W, ks = generate_binary_Hopfield_Net(N, K) res, meta = retrival_rate_vs_error(W, ks, update_rule_async_random, hammings,) plot_Hamming_dist_vs_retival_rate(res, N, K, hammings) ``` ```python make_animated_heatmap(res) ``` <html> <head><meta charset="utf-8" /></head> <body> <div> <div id="8faf6329-afb5-4cf4-ad2c-f7f21f774a10" class="plotly-graph-div" style="height:500px; width:500px;"></div> </div> </body> </html> ```python # This might take a while ~3 min Ns, Ks = [100]*7, [5, 8, 10, 12, 15, 17, 20] reses = [] for N,K in zip(Ns, Ks): W, ks = generate_binary_Hopfield_Net(N, K) hammings = np.arange(0, N//3, 3) res, meta = retrival_rate_vs_error(W, ks, update_rule_async_random, hammings, use_first_k=5) reses.append(res) ``` ```python plot_Hamming_dist_vs_retrival_rate_NEW(reses, Ns, Ks, hammings, save=True, suffix='combined') ``` ### Theoretical limitations of the binary Hopfield Net's storage capacity result from the Hebbian Rule: (TODO) ```python # If we build W from N vectors and every vector will be orthogonal - when *any* random vector will be stored (placed in local minima) # however it is tricky to make orthogonalization of binary vectors (at least I couldn't invent quick solution) ks = np.ones([30,30]) np.fill_diagonal(ks, -1) W = [email protected] ``` ```python q=np.random.choice([-1,1], 30) np.sign(W@q)==q ``` array([ True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]) ### Corrupt MNIST ```python from torchvision.datasets import MNIST from PIL import Image dt = MNIST(root='sample_data/', download=True) ``` Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to sample_data/MNIST/raw/train-images-idx3-ubyte.gz HBox(children=(FloatProgress(value=1.0, bar_style='info', max=1.0), HTML(value=''))) Extracting sample_data/MNIST/raw/train-images-idx3-ubyte.gz to sample_data/MNIST/raw Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to sample_data/MNIST/raw/train-labels-idx1-ubyte.gz HBox(children=(FloatProgress(value=1.0, bar_style='info', max=1.0), HTML(value=''))) Extracting sample_data/MNIST/raw/train-labels-idx1-ubyte.gz to sample_data/MNIST/raw Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to sample_data/MNIST/raw/t10k-images-idx3-ubyte.gz HBox(children=(FloatProgress(value=1.0, bar_style='info', max=1.0), HTML(value=''))) Extracting sample_data/MNIST/raw/t10k-images-idx3-ubyte.gz to sample_data/MNIST/raw Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to sample_data/MNIST/raw/t10k-labels-idx1-ubyte.gz HBox(children=(FloatProgress(value=1.0, bar_style='info', max=1.0), HTML(value=''))) Extracting sample_data/MNIST/raw/t10k-labels-idx1-ubyte.gz to sample_data/MNIST/raw Processing... /usr/local/lib/python3.6/dist-packages/torchvision/datasets/mnist.py:469: UserWarning: The given NumPy array is not writeable, and PyTorch does not support non-writeable tensors. This means you can write to the underlying (supposedly non-writeable) NumPy array using the tensor. You may want to copy the array to protect its data or make it writeable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at /pytorch/torch/csrc/utils/tensor_numpy.cpp:141.) Done! ```python images, classes = [], [] for i in range(3): m,c = dt[i] #m.save(f'Pictures/mnist_{i}.png') m = np.array(m) m = 2*((m > 20).astype(int))-1 images.append(m) classes.append(c) ``` ### Functions defined ```python def construct_Hopfield_Network_from_data(ks: np.ndarray, normalize=True, zero_diag=False): """ Construct Hopfield Network from K vectors of size [1,N]. input: - ks: binary vectors outputs: - W: Hopfield Net matrix with Hebbian weigths [N,N] """ W = ks.T@ks if normalize: W = W*(1/W.shape[0]) if zero_diag: np.fill_diagonal(W,0) return W ``` ```python def corrupt_image(img, p=0.1): eps = np.random.choice([-10,0,10], size=[28,28], p=[p*0.5,1-p, p*0.5]) img = np.clip(img + eps, -1, 1) return img ``` ### operations ```python data = np.stack([m.ravel() for m in images]) W = construct_Hopfield_Network_from_data(data, normalize=True, zero_diag=True) plt.imshow(W) ``` ```python ### Even for just a two MNIST digits we get convoluted memories - probably because the signal/background ratio is too low ### so every picture vector [1,784] looks very similar due to dark background assert len(images)<10, "Nope, human can not comprehend so many MNIST pictures at once!" fig, ax = plt.subplots(len(images),2, figsize=(5, len(images)*3)) for i in range(len(images)): query = corrupt_image(images[i], p=0.25).ravel() query_retrived, E_traj, q_traj = retrive_memorized(query.copy(), W, update_rule_async_random) ax[i,0].imshow(query.reshape([28,28])) ax[i,1].imshow(query_retrived.reshape([28,28])) #Image.fromarray(np.clip(255*(query+1), 0, 255).reshape([28,28]).astype(np.uint8)).save('Pictures/mnist_corrupted_5.png') ``` ```python # query = corrupt_image(images[0], p=0.25).ravel() # query_retrived, E_traj, q_traj = retrive_memorized(query.copy(), W, update_rule_async_random) # fig, ax = plt.subplots(1,2) # ax[0].imshow(query.reshape([28,28])) # ax[1].imshow(query_retrived.reshape([28,28])) # #Image.fromarray(np.clip(255*(query+1), 0, 255).reshape([28,28]).astype(np.uint8)).save('Pictures/mnist_corrupted_5.png') ``` ### Modern Hopfield Networks with better Energy Functions (TODO) ```python # Comparing power law and exponential for different constants from scipy.signal import find_peaks find_peaks(1/(Es+1e-5)) t = np.linspace(0,18,200) plt.plot(t, 2**t) plt.plot(t, 2.71**(0.65*t)) plt.plot(t, t**3) plt.plot(t, t**4) ```
\begin{document} \chapter{Appendix} \label{chapter:appendix} \section{Kinect BodyFrame Serialization Library} \label{sec:appendix_bodyframe_serialization} Serialized BodyFrame: \begin{itemize} \item Timestamp \item List of serialized Bodies \item Depth frame width \item Depth frame height \end{itemize} Serialized Body: \begin{itemize} \item Is tracked \item Tracking id \item Dictionary of joint types and serialized Joints \item Clipped edges \end{itemize} Serialized Joint: \begin{itemize} \item Joint tracking state \item Joint type \item Joint orientation \item Camera space point \item Depth space point \end{itemize} \section{Tasks} \label{sec:appendix_tasks} The instructions for each task as shown on the screen are: \begin{enumerate} \item Stationary \begin{enumerate} \item Ready \item Stand still \item Done \end{enumerate} \item Steps \begin{enumerate} \item Ready \item Move forward \item Move left \item Move right \item Move backward \item Move backward \item Move left \item Move backward \item Move right \item Done \end{enumerate} \item Walk \begin{enumerate} \item Ready \item Move to the starting position \item Go around the square (clockwise) \item Go to top right \item Go to bottom left \item Go to top left \item Go to bottom right \item Done \end{enumerate} \item Obstacle \begin{enumerate} \item Ready \item Go around the obstacle \item Done \end{enumerate} \item Interactions \begin{enumerate} \item Ready \item Person 1 walks past person 2 \item Person 1 goes around person 2 \item Ready \item Person 2 walks past person 1 \item Person 2 goes around person 1 \item Done \item Ready \item Exchange positions \item Done \end{enumerate} \end{enumerate} \section{Tracking Log} \label{sec:appendix_logging} Each tracking result contains: \begin{itemize} \item Study id (Participant id) \item Kinect configuration (The Kinect position, in angle, compared to the primary Kinect) \item Scenario (User task in the experiment) \item Tracker time \item Person id \item Skeleton id \item Skeleton time \item Skeleton initial angle \item Skeleton initial distance \item Kinect id \item Kinect tilt angle \item Kinect height \item Joint 1 (Ankle Left) X \item Joint 1 (Ankle Left) Y \item Joint 1 (Ankle Left) Z \item \ldots \item Last joint (Wrist Right) X \item Last joint (Wrist Right) Y \item Last joint (Wrist Right) Z \end{itemize} \end{document}
The measure of any set is less than or equal to the measure of the whole space.
# This code assumes you've downloaded and unzipped the file # exdata-data-NEI_data.zip in your working directory. If you haven't it's # easy enough to write the code to check using file.exists etc ## This first line will likely take a few seconds. Be patient! NEI <- readRDS("summarySCC_PM25.rds") SCC <- readRDS("Source_Classification_Code.rds") # Plot 4 # Subsetting... Combustion <- grepl("comb", SCC$SCC.Level.One, ignore.case = TRUE) Coal <- grepl("coal", SCC$SCC.Level.Four, ignore.case = TRUE) Coal.Comb <- (Coal & Combustion) ccSCC <- SCC[Coal.Comb,]$SCC ccNEI <- NEI[NEI$SCC %in% ccSCC,] library(ggplot2) png(filename = "plot4.png", width = 640, height = 480) ggplot(ccNEI,aes(factor(year), Emissions/10^3)) + geom_bar(stat = "identity", fill = "grey") + theme_bw() + guides(fill = FALSE) + labs(x = "Year", y = expression("Total PM"[2.5]*" Emission (Thousand Tons)")) + labs(title = expression("Plot 4: PM"[2.5]*" Coal-Combustion Related Source Emissions Across US from 1999-2008")) dev.off()
GetResponse is a well known email marketing service that simply does the job. Servicing companies in more than 180 nations with over 1 billion customers each month, GetResponse projects itself as the world’s easiest email marketing system. The platform makes it easy and hassle-free to produce professional-looking e-mails and landing pages with its editor. What makes GetResponse such a good business software solution? To begin, you do not need a technology background to use its marketing and e-mail automation tools to enhance your business. The vendor provides a beneficial 30-day totally free trial and flexible pricing bundles with lots of additional features. You do not need a credit card to register for the free trial which allows as much as 1,000 contacts. The GetReponse website hosts an in-depth Help Center where you can quickly find answers to typical inquiries. The vendor also offers 24/7 support through live chat and e-mail. The user experience is amazing and the third-party integrations permit you to quickly link the application with your existing company software application platforms. We give the thumbs up to GetResponse and invite you to check out its top rate email marketing functionalities. Marketing Automation – GetResponse’s marketing automation feature lets users develop scalable workflows based upon client journeys. Action-based autoresponders enable the production of messages that are set off by pertinent recipient actions – with personalized one-to-one responses. Additionally, GetResponse offers users with innovative segmentation tools that enable them to divide their contacts into subgroups and tailor emails accordingly. Landing Page Builder – GetResponse has an intuitive drag-and-drop landing page builder that permits users to develop one hundred percent responsive landing pages and web forms. Company online marketers can construct websites for sales, webinars, thank yous, opt-ins, about-me and downloads in simply a couple of minutes. Additionally, GetResponse lets users test, analyze and optimize their pages to boost conversion rates. Comprehensive Reporting – GetReponse has robust reporting capabilities. A couple of easy reports appear straight in the control panel, providing a quick summary of project success by means of raw numbers and pie chart. The E-mail Analytics area supplies more information, with line and bar graphs for clicks, unsubscribes, opens, complaints and bounces. Additionally, for each report, users can see which customers within their e-mail list carried out any provided action. Webinar Integration – The GetResponse webinar platform seamlessly integrates with GetResponse email marketing, allowing users to host product announcements, demonstrations and training sessions. Features include presentation sharing, chat moderation, polls, desktop sharing, attendee management and VoIP abilities. Furthermore, GetResponse lets users decide whether their webinar will be password-protected or open to everybody. On the whole, GetResponse is pretty straightforward to utilize. It is definitely simple enough to do all the basics: import contacts, create campaigns, set autoresponders and check statistics and the interface is pretty clean and intuitive. In terms of how it compares to its competitors in this regard, I would argue that Campaign Monitor is a little bit more easy to use however not as complete, and Mailchimp has a slicker user interface although one that makes finding certain functionality a little bit difficult sometimes). Whilst its drag and drop technique does in theory offer a very flexible way to create blocks of material and move them around an e-newsletter, in practice it is a bit clunky to utilize and can lead to unintentional deletion of material, or placement of it in the wrong part of the e-newsletter. If you can get your head around it, and practice using it a bit, it does make for a really helpful tool – it’s just that the implementation of it might be rather better which I was able to do rather fast! GetResponse provides a 30 day free trial for a list of up to 250 subscribers, no credit card required. Understand, nevertheless, that for the trial (and only the trial), if you add, erase, and then re-add a contact, it counts as 2 contacts. Once the trial has ended, there are various rate plans readily available. The pricing format is rather complicated, with more advanced plans appearing as your business’s list size grows. Pre-paying for a year’s worth of service will save you 18 percent. If you believe you’ll be using GetResponse for the foreseeable future, you can save 30 percent by pre-paying 2 years. Pro gets rid of the limitations on landing pages and allows you to make as many of them as you like. You’ll also have access to webinars (as much as 100 attendees). A Pro account can accommodate up to 3 users. The Max plan ups the number of users to five and the optimum webinar guests to 500. You will also get a custom-made domain and an account supervisor. Enterprise brings a whole host of brand-new features for bigger businesses trying to find extremely personalized features. You’ll need to arrange a demo prior to signing up. GetResponse provides an excellent 1 Gigabyte of image storage with each account. All users also have access to the company’s image library, which includes over 1000 images. Webinars –this feature is not available at all on the ‘Email’ plan and the variety of webinar participants is topped for the ‘Pro’ and ‘Max’ plans at 100, 500 respectively (it’s uncertain what the limit is on the ‘Enterprise’ plan). The 30-day totally free trial that Getresponse gives is fully functional (approximately 1,000 subscribers) and it’s not contingent upon supplying credit card details. We recognize that when you decide to purchase Marketing Software applications itis essential not just to see how specialists evaluate it in their evaluations, but likewise to discover if the genuine people and businesses that purchase it are in fact satisfied with the item. That’s why we’ve found a behavior-based Customer Satisfaction Algorithm that collects client reviews, comments and GetResponse reviews throughout a vast array of social media sites. The data is then presented in a simple to digest form showing how lots of people had positive and negative experience with GetResponse. With that information at hand you must be geared up to make a notified purchasing choice that you won’t regret. GetResponse has an award-winning customer support team, winning gold, silver and bronze Stevie Awards in 2013 and 2014. The company provides e-mail support in 7 languages and is the very first email service provider (ESP) to offer 24/7 live chat, including weekends. Consumers can reference the Help Center and Learning Center, which both feature resources to help solve any questions or concerns. These knowledge bases include FAQs, video tutorials, webinars, and downloadable documents like manuals, reports and whitepapers. Getresponse represents one of the more cheaper opportunities to host and communicate with an e-mail database; it’s priced rather competitively in its marketplace. It is also among the most fascinating products of its kind – because it gives email marketing, automation, landing pages, some CRM functionality and webinars all under one roofing. It is difficult to think about any other product that uses this ‘all round’ proposal, and it’s what continues to encourage us to utilize it for our businesses email marketing.
papi.utilization <- function(expr) { papi.check.ncounters(3L) ret <- .Call(papi_utilization_on) if (ret == -1L) stop("PAPI failed to initialize hardware counters.\nYour platform may not support floating point operation event.\n") eval(expr) ret <- .Call(papi_utilization_off) if (is.integer(ret) && ret == -1L) stop("There was a problem recovering the counter information.") return( ret ) } #' utilization #' #' CPU Utilization. #' #' We define processor utilization as:\cr #' #' \eqn{utilization = \frac{ins}{clockrate\ *\ real\_time\ *\ ncpus}} \cr #' #' where \code{ins} is the number of instructions measured by PAPI, #' \code{clockrate} is the clock frequency of the processor in Hz, #' \code{real_time} is the wall clock time, and \code{ncpus} is the number of #' "cores" (physical+logical) detected by PAPI. #' #' @param expr #' A valid R expression to be profiled. #' @param gcFirst #' logical; determines if garbage collection should be called #' before profiling. #' @param burnin #' logical; determines if the function should first be evaluated #' with an empty expression. #' #' @return The return is a list consisting of: #' \tabular{ll}{ #' \code{real_time} \tab real time spent evaluating expression \cr #' \code{proc_time} \tab total process time spent evaluating expression \cr #' \code{ins} \tab Number of instructions. \cr #' \code{ipc} \tab Instructions per cycle. \cr #' \code{utilization} \tab CPU utilization (proportion) \cr #' } #' #' @keywords programming #' #' @examples #' #' \dontrun{ #' library(pbdPAPI) #' #' system.flops(1+1) #' } #' #' @export system.utilization <- function(expr, gcFirst=TRUE, burnin=TRUE) { if (burnin) b <- system.utilization(gcFirst=gcFirst, burnin=FALSE) if (gcFirst) invisible(gc(FALSE)) if (missing(expr)) expr <- NULL events <- c("PAPI_TOT_INS", "PAPI_TOT_CYC") papi.avail.lookup(events=events, shorthand=FALSE) ret <- papi.utilization(expr=expr) if (burnin) { for (i in 3:(length(ret)-1)) ret[[i]] <- max(ret[[i]] - b[[i]], 0) } return( ret ) }
# 编译与调试 { # 编译 alias gob='CGO_ENABLED=0 go build -v -gcflags "all=-N -l" -o alertmanager cmd/alertmanager/main.go' # 调试 alias dlv='gob && dlv exec ./alertmanager --init .dbg/alertmanager.dlv -- --config.file=doc/examples/simple.yml' }
packages = c( 'https://cran.r-project.org/package=svglite&version=1.2.1', 'https://cran.r-project.org/package=ggridges&version=0.4.1' ) utils::install.packages(pkgs = packages, repos = NULL)
I've been intending to get out there and paint what I see as it gets warmer, but there just isn't much out there yet. Wet, brown grass, the old lavender stalks we never trimmed in fall, pine trees, and bittersweet. I don't care if it's pretty, I'm not painting bittersweet, because I'm convinced it wants to eat my yard and my house and me alive and I just don't like that. So that doesn't leave much yet, but thank god it's Skunk Cabbage to the rescue! And what better plant to start off with than something that literally heats itself out of the snow? Skunk cabbage is one of the first plants you'll see in Spring here in New England, especially if you have any moist, boggy areas near you. You'll see the liverish-colored protective buds shooting up through the snow before most other plants, because it won't take no for an answer--it produces it's own heat (60 degrees!) and melts its way through that white crap. Who needs Spring when you can make it yourself? Eventually you'll see the yellow clump of complex flowers and then all the cabbagey leaves. Of course, it gets its name because it smells like skunk. Or decaying flesh. Or both. I guess when you smell that bad it hardly matters.
/* Copyright 2014 Glen Joseph Fernandes ([email protected]) Distributed under the Boost Software License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_ALIGN_DETAIL_ALIGNMENT_OF_CLANG_HPP #define BOOST_ALIGN_DETAIL_ALIGNMENT_OF_CLANG_HPP #include <boost/align/detail/integral_constant.hpp> #include <cstddef> namespace boost { namespace alignment { namespace detail { template<class T> struct alignment_of : integral_constant<std::size_t, __alignof(T)> { }; } /* detail */ } /* alignment */ } /* boost */ #endif
[STATEMENT] lemma dom_contr': "\<lbrakk>is_subtree (Node r {|(t1,e1)|}) t; rank (rev (Dtree.root t1)) < rank (rev r); max_deg (Node r {|(t1,e1)|}) \<le> 1\<rbrakk> \<Longrightarrow> dom_children (Node r {|(t1,e1)|}) T" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>is_subtree (Node r {|(t1, e1)|}) t; rank (rev (dtree.root t1)) < rank (rev r); max_deg (Node r {|(t1, e1)|}) \<le> 1\<rbrakk> \<Longrightarrow> dom_children (Node r {|(t1, e1)|}) T [PROOF STEP] using dom_contr mdeg_ge_sub mdeg_singleton[of r t1] [PROOF STATE] proof (prove) using this: \<lbrakk>is_subtree (Node ?r {|(?t1.0, ?e1.0)|}) t; rank (rev (dtree.root ?t1.0)) < rank (rev ?r); max_deg (Node ?r {|(?t1.0, ?e1.0)|}) = 1\<rbrakk> \<Longrightarrow> dom_children (Node ?r {|(?t1.0, ?e1.0)|}) T is_subtree ?t1.0 ?t2.0 \<Longrightarrow> max_deg ?t1.0 \<le> max_deg ?t2.0 max_deg (Node r {|(t1, ?e1.0)|}) = max (max_deg t1) (fcard {|(t1, ?e1.0)|}) goal (1 subgoal): 1. \<lbrakk>is_subtree (Node r {|(t1, e1)|}) t; rank (rev (dtree.root t1)) < rank (rev r); max_deg (Node r {|(t1, e1)|}) \<le> 1\<rbrakk> \<Longrightarrow> dom_children (Node r {|(t1, e1)|}) T [PROOF STEP] by (simp add: fcard_single_1)
State Before: ι : Type ?u.449 V : Type u inst✝³ : Category V inst✝² : HasZeroMorphisms V A B C : V f : A ⟶ B inst✝¹ : HasImage f g : B ⟶ C inst✝ : HasKernel g w : f ≫ g = 0 ⊢ kernel.lift g f w ≫ kernel.ι g = f State After: no goals Tactic: simp
Formal statement is: lemma BfunE: assumes "Bfun f F" obtains B where "0 < B" and "eventually (\<lambda>x. norm (f x) \<le> B) F" Informal statement is: If $f$ is a bounded function on a filter $F$, then there exists a positive real number $B$ such that $|f(x)| \leq B$ for all $x$ in the filter.
! ################################################################################################################################## ! 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 WRITE_ELEM_STRESSES ( JSUB, NUM, IHDR, NUM_PTS, ITABLE ) ! Writes blocks of element stresses for one subcase and one element type for elements that do not have PCOMP properties, including ! all 1-D, 2-D, 3-D elements. USE PENTIUM_II_KIND, ONLY : BYTE, LONG, DOUBLE USE IOUNT1, ONLY : WRT_ERR, WRT_LOG, ANS, ERR, F04, F06, OP2 USE SCONTR, ONLY : BLNK_SUB_NAM, FATAL_ERR, BARTOR, INT_SC_NUM, MAX_NUM_STR, NDOFR, NUM_CB_DOFS, & NVEC, SOL_NAME USE TIMDAT, ONLY : TSEC USE CONSTANTS_1, ONLY : ZERO USE DEBUG_PARAMETERS, ONLY : DEBUG USE NONLINEAR_PARAMS, ONLY : LOAD_ISTEP USE SUBR_BEGEND_LEVELS, ONLY : WRITE_ELEM_STRESSES_BEGEND USE LINK9_STUFF, ONLY : EID_OUT_ARRAY, GID_OUT_ARRAY, OGEL, POLY_FIT_ERR, POLY_FIT_ERR_INDEX USE MODEL_STUF, ONLY : ELEM_ONAME, ELMTYP, LABEL, SCNUM, STITLE, TITLE, TYPE USE CC_OUTPUT_DESCRIBERS, ONLY : STRE_LOC, STRE_OPT USE WRITE_ELEM_STRESSES_USE_IFs IMPLICIT NONE CHARACTER(LEN=LEN(BLNK_SUB_NAM)):: SUBR_NAME = 'WRITE_ELEM_STRESSES' CHARACTER(LEN=*), INTENT(IN) :: IHDR ! Indicator of whether to write an output header ! Array of different notes to write regarding poly fit errors CHARACTER( 50*BYTE) :: ERR_INDEX_NOTE(MAX_NUM_STR) CHARACTER(128*BYTE) :: FILL ! Padding for output format CHARACTER(LEN=LEN(ELEM_ONAME)) :: ONAME ! Element name to write out in F06 file CHARACTER( 1*BYTE) :: WRITE_NOTES = 'N' ! Indicator of whether to write any WRT_ERR_INDEX_NOTE(i) ! Indicators of whether to write note on indices of POLY_FIT_ERR CHARACTER( 1*BYTE) :: WRT_ERR_INDEX_NOTE(MAX_NUM_STR) INTEGER(LONG), INTENT(IN) :: JSUB ! Solution vector number INTEGER(LONG), INTENT(IN) :: NUM ! The number of rows of OGEL to write out INTEGER(LONG), INTENT(IN) :: NUM_PTS ! Num diff stress points for one element (3rd dim in arrays SEi, STEi) INTEGER(LONG), INTENT(INOUT) :: ITABLE ! the current op2 subtable, should be -3, -5, ... INTEGER(LONG) :: BDY_COMP ! Component (1-6) for a boundary DOF in CB analyses INTEGER(LONG) :: BDY_GRID ! Grid for a boundary DOF in CB analyses INTEGER(LONG) :: BDY_DOF_NUM ! DOF number for BDY_GRID/BDY_COMP INTEGER(LONG) :: I,J,L ! DO loop indices INTEGER(LONG) :: K ! Counter INTEGER(LONG) :: NCOLS ! Num of cols to write out INTEGER(LONG), PARAMETER :: SUBR_BEGEND = WRITE_ELEM_STRESSES_BEGEND REAL(DOUBLE) :: ABS_ANS(11) ! Max ABS for all element output REAL(DOUBLE) :: MAX_ANS(11) ! Max for all element output REAL(DOUBLE) :: MIN_ANS(11) ! Min for all element output ! op2 info CHARACTER( 8*BYTE) :: TABLE_NAME ! the name of the op2 table INTEGER(LONG) :: NNODES ! number of nodes for the element ! table -3 info INTEGER(LONG) :: ANALYSIS_CODE ! static/modal/time/etc. flag INTEGER(LONG) :: ELEMENT_TYPE ! the OP2 flag for the element LOGICAL :: FIELD_5_INT_FLAG ! flag to trigger FIELD5_INT_MODE vs. FIELD5_FLOAT_TIME_FREQ INTEGER(LONG) :: FIELD5_INT_MODE ! int value for field 5 REAL(DOUBLE) :: FIELD5_FLOAT_TIME_FREQ ! float value for field 5 REAL(DOUBLE) :: FIELD6_EIGENVALUE ! float value for field 6 CHARACTER(LEN=128) :: TITLEI ! the model TITLE CHARACTER(LEN=128) :: STITLEI ! the subcase SUBTITLE CHARACTER(LEN=128) :: LABELI ! the subcase LABEL INTEGER(LONG) :: STRESS_CODE = 0 ! flag for type of stress; see GET_STRESS_CODE ! op2 specific flags INTEGER(LONG) :: DEVICE_CODE = 0 ! PLOT, PRINT, PUNCH flag; set as PLOT INTEGER(LONG) :: NUM_WIDE ! the number of "words" for an element INTEGER(LONG) :: NVALUES ! the number of "words" for all the elments INTEGER(LONG) :: NTOTAL ! the number of bytes for all NVALUES INTEGER(LONG) :: ISUBCASE ! the subcase ID INTEGER(LONG) :: NELEMENTS INTEGER(LONG) :: CID ! coordinate system CHARACTER(4*BYTE) :: CEN_WORD ! the word "CEN/" (we need to cast the length) ! ********************************************************************************************************************************** IF (WRT_LOG >= SUBR_BEGEND) THEN CALL OURTIM WRITE(F04,9001) SUBR_NAME,TSEC 9001 FORMAT(1X,A,' BEGN ',F10.3) ENDIF ! ********************************************************************************************************************************** ! Initialize 1 FORMAT("WRITE OES F06/OP2; ITABLE=",I8," (should be -4, -6, ...)") WRITE(ERR,1) ITABLE FILL(1:) = ' ' DO I=1,MAX_NUM_STR WRT_ERR_INDEX_NOTE(I) = 'N' ENDDO ERR_INDEX_NOTE(1) = ' (1): Polynomial fit error is in X normal stress' ERR_INDEX_NOTE(2) = ' (2): Polynomial fit error is in Y normal stress' ERR_INDEX_NOTE(3) = ' (3): Polynomial fit error is in XY shear stress' ERR_INDEX_NOTE(4) = ' (4): Polynomial fit error is in X bending stress' ERR_INDEX_NOTE(5) = ' (5): Polynomial fit error is in Y bending stress' ERR_INDEX_NOTE(6) = ' (6): Polynomial fit error is in XY twist stress' ERR_INDEX_NOTE(7) = ' (7): Polynomial fit error is in XZ shear stress ' ERR_INDEX_NOTE(8) = ' (8): Polynomial fit error is in YZ shear stress' ERR_INDEX_NOTE(9) = '' FILL(1:) = ' ' ! Get element output name ONAME(1:) = ' ' CALL GET_ELEM_ONAME ( ONAME ) ! Write output headers if this is not the first use of this subr. ANALYSIS_CODE = -1 FIELD_5_INT_FLAG = .TRUE. FIELD5_INT_MODE = 0 !FIELD5_FLOAT_TIME_FREQ = 0.0 FIELD6_EIGENVALUE = 0.0 IF (IHDR == 'Y') THEN WRITE(F06,*) ; IF (DEBUG(200) > 0) WRITE(ANS,*) WRITE(F06,*) ; IF (DEBUG(200) > 0) WRITE(ANS,*) ! -- F06 header: OUTPUT FOR SUBCASE, EIGENVECTOR or CRAIG-BAMPTON DOF ISUBCASE = SCNUM(JSUB) IF (SOL_NAME(1:7) == 'STATICS') THEN ANALYSIS_CODE = 1 FIELD5_INT_MODE = 1 ! temp FIELD5_INT_MODE = SCNUM(JSUB) WRITE(F06,101) SCNUM(JSUB) ; IF (DEBUG(200) > 0) WRITE(ANS,101) SCNUM(JSUB) ELSE IF (SOL_NAME(1:8) == 'NLSTATIC') THEN ANALYSIS_CODE = 10 FIELD5_INT_MODE = SCNUM(JSUB) WRITE(F06,101) SCNUM(JSUB) ; IF (DEBUG(200) > 0) WRITE(ANS,101) SCNUM(JSUB) ELSE IF ((SOL_NAME(1:8) == 'BUCKLING') .AND. (LOAD_ISTEP == 1)) THEN ANALYSIS_CODE = 1 FIELD5_INT_MODE = SCNUM(JSUB) WRITE(F06,101) SCNUM(JSUB) ELSE IF ((SOL_NAME(1:8) == 'BUCKLING') .AND. (LOAD_ISTEP == 2)) THEN ANALYSIS_CODE = 7 FIELD5_INT_MODE = JSUB ! FIELD6_EIGENVALUE = ???? WRITE(F06,102) JSUB ELSE IF (SOL_NAME(1:5) == 'MODES') THEN ANALYSIS_CODE = 2 FIELD5_INT_MODE = JSUB ! FIELD6_EIGENVALUE = ???? WRITE(F06,102) JSUB ; IF (DEBUG(200) > 0) WRITE(ANS,102) JSUB ELSE IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN IF ((JSUB <= NDOFR) .OR. (JSUB >= NDOFR+NVEC)) THEN IF (JSUB <= NDOFR) THEN BDY_DOF_NUM = JSUB ELSE BDY_DOF_NUM = JSUB-(NDOFR+NVEC) ENDIF CALL GET_GRID_AND_COMP ( 'R ', BDY_DOF_NUM, BDY_GRID, BDY_COMP ) ENDIF IF (JSUB <= NDOFR) THEN WRITE(F06,103) JSUB, NUM_CB_DOFS, 'acceleration', BDY_GRID, BDY_COMP ELSE IF ((JSUB > NDOFR) .AND. (JSUB <= NDOFR+NVEC)) THEN WRITE(F06,104) JSUB, NUM_CB_DOFS, JSUB-NDOFR ELSE WRITE(F06,103) JSUB, NUM_CB_DOFS, 'displacement', BDY_GRID, BDY_COMP ENDIF IF (DEBUG(200) > 0) THEN IF (JSUB <= NDOFR) THEN WRITE(ANS,103) JSUB, NUM_CB_DOFS, 'acceleration', BDY_GRID, BDY_COMP ELSE IF ((JSUB > NDOFR) .AND. (JSUB <= NDOFR+NVEC)) THEN WRITE(ANS,104) JSUB, NUM_CB_DOFS, JSUB-NDOFR ELSE WRITE(ANS,103) JSUB, NUM_CB_DOFS, 'displacement', BDY_GRID, BDY_COMP ENDIF ENDIF ENDIF ! -- F06 header for TITLE, SUBTITLE, LABEL (but only to F06) TITLEI = TITLE(INT_SC_NUM) STITLEI = STITLE(INT_SC_NUM) LABELI = LABEL(INT_SC_NUM) IF (TITLE(INT_SC_NUM)(1:) /= ' ') THEN WRITE(F06,201) TITLE(INT_SC_NUM) ENDIF IF (STITLE(INT_SC_NUM)(1:) /= ' ') THEN WRITE(F06,201) STITLE(INT_SC_NUM) ENDIF IF (LABEL(INT_SC_NUM)(1:) /= ' ') THEN WRITE(F06,201) LABEL(INT_SC_NUM) ENDIF WRITE(F06,*) ; IF (DEBUG(200) > 0) WRITE(ANS,*) ! -- F06 1st 2 header lines for stress output description IF ((TYPE(1:3) == 'BAR') .OR. (TYPE(1:4) == 'BEAM')) THEN IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN WRITE(F06,302) FILL(1: 20) ; IF (DEBUG(200) > 0) WRITE(ANS,302) FILL(1: 36) ELSE WRITE(F06,301) FILL(1: 13) ; IF (DEBUG(200) > 0) WRITE(ANS,301) FILL(1: 29) ENDIF WRITE(F06,401) FILL(1: 42), ONAME ; IF (DEBUG(200) > 0) WRITE(ANS,401) FILL(1: 58), ONAME ELSE IF (TYPE(1:4) == 'BUSH') THEN IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN WRITE(F06,302) FILL(1: 20) ; IF (DEBUG(200) > 0) WRITE(ANS,302) FILL(1: 36) ELSE WRITE(F06,301) FILL(1: 11) ; IF (DEBUG(200) > 0) WRITE(ANS,301) FILL(1: 27) ENDIF WRITE(F06,401) FILL(1: 40), ONAME ; IF (DEBUG(200) > 0) WRITE(ANS,401) FILL(1: 56), ONAME ELSE IF (TYPE(1:4) == 'ELAS') THEN IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN WRITE(F06,302) FILL(1: 20) ; IF (DEBUG(200) > 0) WRITE(ANS,302) FILL(1: 36) ELSE WRITE(F06,301) FILL(1: 11) ; IF (DEBUG(200) > 0) WRITE(ANS,301) FILL(1: 27) ENDIF WRITE(F06,401) FILL(1: 40), ONAME ; IF (DEBUG(200) > 0) WRITE(ANS,401) FILL(1: 56), ONAME ELSE IF ((TYPE(1:4) == 'HEXA') .OR. (TYPE(1:5) == 'PENTA') .OR. (TYPE(1:5) == 'TETRA')) THEN IF (STRE_OPT == 'VONMISES') THEN IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN WRITE(F06,302) FILL(1: 15) ; IF (DEBUG(200) > 0) WRITE(ANS,302) FILL(1: 15) ELSE WRITE(F06,301) FILL(1: 27) ; IF (DEBUG(200) > 0) WRITE(ANS,301) FILL(1: 27) ENDIF WRITE(F06,401) FILL(1: 55), ONAME ; IF (DEBUG(200) > 0) WRITE(ANS,401) FILL(1: 55), ONAME ELSE IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN WRITE(F06,302) FILL(1: 22) ; IF (DEBUG(200) > 0) WRITE(ANS,302) FILL(1: 22) ELSE WRITE(F06,301) FILL(1: 33) ; IF (DEBUG(200) > 0) WRITE(ANS,301) FILL(1: 33) ENDIF WRITE(F06,401) FILL(1: 61), ONAME ; IF (DEBUG(200) > 0) WRITE(ANS,401) FILL(1: 61), ONAME ENDIF ELSE IF (TYPE(1:5) == 'QUAD4') THEN IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN WRITE(F06,302) FILL(1: 20) ; IF (DEBUG(200) > 0) WRITE(ANS,302) FILL(1: 20) ELSE WRITE(F06,301) FILL(1: 42) ; IF (DEBUG(200) > 0) WRITE(ANS,301) FILL(1: 42) ENDIF WRITE(F06,401) FILL(1: 71), ONAME ; IF (DEBUG(200) > 0) WRITE(ANS,401) FILL(1: 71), ONAME ELSE IF (TYPE(1:3) == 'ROD') THEN IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN WRITE(F06,302) FILL(1: 20) ; IF (DEBUG(200) > 0) WRITE(ANS,302) FILL(1: 36) ELSE WRITE(F06,301) FILL(1: 13) ; IF (DEBUG(200) > 0) WRITE(ANS,301) FILL(1: 29) ENDIF WRITE(F06,401) FILL(1: 42), ONAME ; IF (DEBUG(200) > 0) WRITE(ANS,401) FILL(1: 58), ONAME ELSE IF (TYPE(1:5) == 'SHEAR') THEN IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN WRITE(F06,302) FILL(1: 20) ; IF (DEBUG(200) > 0) WRITE(ANS,302) FILL(1: 36) ELSE WRITE(F06,301) FILL(1: 13) ; IF (DEBUG(200) > 0) WRITE(ANS,301) FILL(1: 52) ENDIF WRITE(F06,401) FILL(1: 42), ONAME ; IF (DEBUG(200) > 0) WRITE(ANS,401) FILL(1: 81), ONAME ELSE IF (TYPE(1:5) == 'TRIA3') THEN IF (SOL_NAME(1:12) == 'GEN CB MODEL') THEN WRITE(F06,302) FILL(1: 20) ; IF (DEBUG(200) > 0) WRITE(ANS,302) FILL(1: 36) ELSE WRITE(F06,301) FILL(1: 36) ; IF (DEBUG(200) > 0) WRITE(ANS,301) FILL(1: 52) ENDIF WRITE(F06,401) FILL(1: 65), ONAME ; IF (DEBUG(200) > 0) WRITE(ANS,401) FILL(1: 81), ONAME ENDIF ! -- F06 header lines describing stress columns IF (TYPE == 'BAR ') THEN IF (BARTOR == 'Y') THEN WRITE(F06,1101) FILL(1:1), FILL(1:1) ; IF (DEBUG(200) > 0) WRITE(ANS,1101) FILL(1:16), FILL(1:16) ELSE WRITE(F06,1102) FILL(1:1), FILL(1:1) ; IF (DEBUG(200) > 0) WRITE(ANS,1102) FILL(1:16), FILL(1:16) ENDIF ELSE IF (TYPE(1:4) == 'ELAS') THEN WRITE(F06,1201) FILL(1:1), FILL(1:1) ; IF (DEBUG(200) > 0) WRITE(ANS,1201) FILL(1:16), FILL(1:16) ELSE IF((TYPE(1:4) == 'HEXA') .OR. (TYPE(1:5) == 'PENTA') .OR. (TYPE(1:5) == 'TETRA')) THEN IF (STRE_OPT == 'VONMISES') THEN WRITE(F06,1301) FILL(1:20), FILL(1:20) ; IF (DEBUG(200) > 0) WRITE(ANS,1301) FILL(1:17), FILL(1:17) ELSE WRITE(F06,1302) FILL(1:20), FILL(1:20) ; IF (DEBUG(200) > 0) WRITE(ANS,1302) FILL(1:17), FILL(1:17) ENDIF ELSE IF (TYPE(1:5) == 'QUAD4') THEN IF (STRE_OPT == 'VONMISES') THEN WRITE(F06,1401) FILL(1: 1), FILL(1: 1), FILL(1: 1) ; IF (DEBUG(200) > 0) WRITE(ANS,1401) FILL(1:16), FILL(1:16),& FILL(1:16) ELSE WRITE(F06,1402) FILL(1: 1), FILL(1: 1) ; IF (DEBUG(200) > 0) WRITE(ANS,1402) FILL(1:16), FILL(1:16) ENDIF ELSE IF (TYPE == 'ROD ') THEN WRITE(F06,1501) FILL(1: 1), FILL(1: 1) ; IF (DEBUG(200) > 0) WRITE(ANS,1501) FILL(1:16), FILL(1:16) ELSE IF (TYPE(1:5) == 'SHEAR') THEN WRITE(F06,1601) FILL(1: 1), FILL(1: 1) ; IF (DEBUG(200) > 0) WRITE(ANS,1601) FILL(1:16), FILL(1:16),& FILL(1:16) ELSE IF (TYPE(1:5) == 'TRIA3') THEN IF (STRE_OPT == 'VONMISES') THEN WRITE(F06,1701) FILL(1: 1), FILL(1: 1), FILL(1: 1) ; IF (DEBUG(200) > 0) WRITE(ANS,1701) FILL(1:16), FILL(1:16),& FILL(1:16) ELSE WRITE(F06,1702) FILL(1: 1), FILL(1: 1) ; IF (DEBUG(200) > 0) WRITE(ANS,1702) FILL(1:16), FILL(1:16) ENDIF ELSE IF (TYPE == 'BUSH ') THEN WRITE(F06,1801) FILL(1: 1), FILL(1: 1) ; IF (DEBUG(200) > 0) WRITE(ANS,1801) FILL(1:16), FILL(1:16) ELSE IF (TYPE == 'USERIN ') THEN WRITE(F06,1901) FILL(1: 1), FILL(1: 1) ; IF (DEBUG(200) > 0) WRITE(ANS,1901) FILL(1:16), FILL(1:16) ENDIF ENDIF ! Write the element stress output IF (TYPE == 'BAR ') THEN CALL WRITE_BAR ( NUM, FILL(1:1), FILL(1:16), ISUBCASE, ITABLE, TITLEI, STITLEI, LABELI, & FIELD5_INT_MODE, FIELD6_EIGENVALUE ) ELSE IF (TYPE(1:4) == 'ELAS') THEN CALL GET_SPRING_OP2_ELEMENT_TYPE(ELEMENT_TYPE) NUM_WIDE = 2 ! eid, spring_stress NVALUES = NUM_WIDE * NUM DEVICE_CODE = 1 ! PLOT !CALL GET_STRESS_CODE(STRESS_CODE, IS_VON_MISES, IS_STRAIN, IS_FIBER_DISTANCE) CALL GET_STRESS_CODE( STRESS_CODE, 1, 0, 0) CALL WRITE_OES3_STATIC(ITABLE, ISUBCASE, DEVICE_CODE, ELEMENT_TYPE, NUM_WIDE, STRESS_CODE, & TITLEI, STITLEI, LABELI, FIELD5_INT_MODE, FIELD6_EIGENVALUE) WRITE(OP2) NVALUES WRITE(OP2) (EID_OUT_ARRAY(I,1)*10+DEVICE_CODE, REAL(OGEL(I,1), 4), I=1,NUM) WRITE(F06,1103) (FILL(1:1), EID_OUT_ARRAY(I,1), OGEL(I,1),I=1,NUM) IF (DEBUG(200) > 0) THEN WRITE(ANS,1104) (FILL(1:16), EID_OUT_ARRAY(I,1),OGEL(I,1),I=1,NUM) ENDIF ELSE IF((TYPE(1:4) == 'HEXA') .OR. (TYPE(1:5) == 'PENTA') .OR. (TYPE(1:5) == 'TETRA')) THEN ! 12345 ! 39 : CTETRA ! 67 : CHEXA ! 68 : CPENTA IF (TYPE(1:4) == "HEXA") THEN ELEMENT_TYPE = 67 NNODES = 9 ELSE IF (TYPE(1:5) == "TETRA") THEN ELEMENT_TYPE = 39 NNODES = 5 ELSE IF (TYPE(1:5) == "PENTA") THEN ELEMENT_TYPE = 68 NNODES = 7 ENDIF NUM_WIDE = 4 + 21 * NNODES NVALUES = NUM_WIDE * NUM !CALL GET_STRESS_CODE(STRESS_CODE, IS_VON_MISES, IS_STRAIN, IS_FIBER_DISTANCE) CALL GET_STRESS_CODE( STRESS_CODE, 1, 0, 0) CALL WRITE_OES3_STATIC(ITABLE, ISUBCASE, DEVICE_CODE, ELEMENT_TYPE, NUM_WIDE, STRESS_CODE, & TITLEI, STITLEI, LABELI, FIELD5_INT_MODE, FIELD6_EIGENVALUE) WRITE(OP2) NVALUES CEN_WORD = "CEN/" ! See the CHEXA, CPENTA, or CTETRA entry for the definition of the element coordinate systems. ! The material coordinate system (CORDM) may be the basic system (0 or blank), any defined system ! (Integer > 0), or the standard internal coordinate system of the element designated as: ! -1: element coordinate system (-1) ! -2: element system based on eigenvalue techniques to insure non bias in the element formulation. ! TODO hardcoded CID = -1 ! setting: ! - CTETRA: [element_device, cid, 'CEN/', 4] ! - CPYRAM: [element_device, cid, 'CEN/', 5] ! - CPENTA: [element_device, cid, 'CEN/', 6] ! - CHEXA: [element_device, cid, 'CEN/', 8] ! 1 2 3 4 5 6 7 ! Element Sigma-xx Sigma-yy Sigma-zz Tau-xy Tau-yz Tau-zx von Mises ! ID ! TODO: we repeat the center node N times because the corner results have not been calculated WRITE(OP2) (EID_OUT_ARRAY(I,1)*10+DEVICE_CODE, CID, CEN_WORD, NNODES-1, & ! grid_id ! 21 (GID_OUT_ARRAY(I,J), & ! oxx txy s1 a1 a2 a3 p ovm REAL(OGEL(I,1),4), REAL(OGEL(I,4),4), REAL(OGEL(I,9), 4), 0., 0., 0., REAL(OGEL(I,12),4), REAL(OGEL(I,7),4), & ! syy tyz s2 b1 b2 b3 REAL(OGEL(I,2),4), REAL(OGEL(I,5),4), REAL(OGEL(I,10),4), 0., 0., 0., & ! szz txz s3 c1 c2 c3 REAL(OGEL(I,3),4), REAL(OGEL(I,6),4), REAL(OGEL(I,11),4), 0., 0., 0., & J=1,NNODES), I=1,NUM) IF (STRE_OPT == 'VONMISES') THEN NCOLS = 7 ELSE NCOLS = 8 ENDIF DO I=1,NUM WRITE(F06,1303) EID_OUT_ARRAY(I,1),(OGEL(I,J),J=1,NCOLS) ; IF (DEBUG(200) > 0) WRITE(ANS,1313) EID_OUT_ARRAY(I,1), & (OGEL(I,J),J=1,NCOLS) ENDDO CALL GET_MAX_MIN_ABS_STR ( NUM, NCOLS, 'N', MAX_ANS, MIN_ANS, ABS_ANS ) IF (STRE_OPT == 'VONMISES') THEN WRITE(F06,1304) (MAX_ANS(J),J=1,7), (MIN_ANS(J),J=1,7), (ABS_ANS(J),J=1,7) IF (DEBUG(200) > 0) THEN WRITE(ANS,1314) (MAX_ANS(J),J=1,7), (MIN_ANS(J),J=1,7), (ABS_ANS(J),J=1,7) ENDIF ELSE WRITE(F06,1305) (MAX_ANS(J),J=1,8), (MIN_ANS(J),J=1,8), (ABS_ANS(J),J=1,8) IF (DEBUG(200) > 0) THEN WRITE(ANS,1315) (MAX_ANS(J),J=1,8), (MIN_ANS(J),J=1,8), (ABS_ANS(J),J=1,8) ENDIF ENDIF ELSE IF (TYPE(1:5) == 'QUAD4') THEN !CALL WRITE_OES_CQUAD4 ( NUM, FILL, ISUBCASE, ITABLE, TITLEI, STITLEI, LABELI ) !CALL GET_STRESS_CODE(STRESS_CODE, IS_VON_MISES, IS_STRAIN, IS_FIBER_DISTANCE) CALL GET_STRESS_CODE( STRESS_CODE, 1, 0, 1) IF (STRE_LOC == 'CENTER ') THEN ! CQUAD4-33 2 FORMAT(' *DEBUG: WRITE_CQUAD4-33: NUM=',I4, " NUM_PTS=", I4, " STRE_LOC=",A,"ITABLE=",I4) WRITE(ERR,2) NUM,NUM_PTS,STRE_LOC,ITABLE !(eid_device, ! fd1, sx1, sy1, txy1, angle1, major1, minor1, vm1, ! fd2, sx2, sy2, txy2, angle2, major2, minor2, vm2,) = out; n=17 NUM_WIDE = 17 ELEMENT_TYPE = 33 NVALUES = NUM_WIDE * NUM CALL WRITE_OES3_STATIC(ITABLE, ISUBCASE, DEVICE_CODE, ELEMENT_TYPE, NUM_WIDE, STRESS_CODE, & TITLEI, STITLEI, LABELI, FIELD5_INT_MODE, FIELD6_EIGENVALUE) !NUM_PTS = 1 ! just a copy of the CTRIA3 code ! op2 version of the upper & lower layers all in one call, but without the transverse shear WRITE(OP2) NVALUES WRITE(OP2) (EID_OUT_ARRAY(I,1)*10+DEVICE_CODE, (REAL(OGEL(2*I-1,J),4), J=1,8), (REAL(OGEL(2*I,J),4), J=1,8), I=1,NUM) ELSE ! CQUAD4-144 3 FORMAT(' *DEBUG: WRITE_CQUAD4-144: NUM=',I4, " NUM_PTS=", I4, " STRE_LOC=",A,"ITABLE=",I4) WRITE(ERR,3) NUM,NUM_PTS,STRE_LOC,ITABLE ELEMENT_TYPE = 144 NUM_WIDE = 87 ! 2 + 17 * (4+1) ! 4 nodes + 1 centroid ! TODO: probably wrong...divide NUM by NUM_PTS? NELEMENTS = NUM / NUM_PTS NVALUES = NUM_WIDE * NELEMENTS ! NUM= 10 NUM_PTS= 5 !(eid_device, "CEN/", 4, # "CEN/4" ! fd1, sx1, sy1, txy1, angle1, major1, minor1, vm1, ! fd2, sx2, sy2, txy2, angle2, major2, minor2, vm2,) = n = 17+2 ! ! (grid, ! fd1, sx1, sy1, txy1, angle1, major1, minor1, vm1, ! fd2, sx2, sy2, txy2, angle2, major2, minor2, vm2,)*4 = n = 17*4 CALL WRITE_OES3_STATIC(ITABLE, ISUBCASE, DEVICE_CODE, ELEMENT_TYPE, NUM_WIDE, STRESS_CODE, & TITLEI, STITLE, LABELI, FIELD5_INT_MODE, FIELD6_EIGENVALUE) WRITE(OP2) NVALUES ! see the CQUAD4-33 stress/strain (the IF part of this IF-ELSE block) ! writing before trying to understand this... ! ! basically a one-liner version of the F06 writing ! we broke out the L=1,NUM_PTS-1 loop to 4 lines (the GID_OUT_ARRAY lines) ! to avoid an additional hard to write loop WRITE(OP2) (EID_OUT_ARRAY(5*I+1,1)*10+DEVICE_CODE, "CEN/", 4, & (REAL(OGEL(10*I+1,J),4), J=1,8), (REAL(OGEL(10*I+2, J),4), J=1,8), & GID_OUT_ARRAY(5*I+1,2), (REAL(OGEL(10*I+3,J),4), J=1,8), (REAL(OGEL(10*I+4, J),4), J=1,8), & GID_OUT_ARRAY(5*I+1,3), (REAL(OGEL(10*I+5,J),4), J=1,8), (REAL(OGEL(10*I+6, J),4), J=1,8), & GID_OUT_ARRAY(5*I+1,4), (REAL(OGEL(10*I+7,J),4), J=1,8), (REAL(OGEL(10*I+8, J),4), J=1,8), & GID_OUT_ARRAY(5*I+1,5), (REAL(OGEL(10*I+9,J),4), J=1,8), (REAL(OGEL(10*(I+1),J),4), J=1,8), & I=0,NELEMENTS-1) ENDIF K = 0 DO I=1,NUM,NUM_PTS 4 FORMAT(' *DEBUG: WRITE_CQUAD4-144: I=',I4, " K=", I4) K = K + 1 WRITE(ERR,4) I,K WRITE(F06,*) ; IF (DEBUG(200) > 0) WRITE(ANS,*) WRITE(F06,1403) FILL(1: 0), EID_OUT_ARRAY(I,1),(OGEL(K,J),J=1,10) ; IF (DEBUG(200) > 0) WRITE(ANS,1413) EID_OUT_ARRAY(I,1), & (OGEL(K,J),J=1,10) K = K + 1 WRITE(F06,1404) FILL(1: 0), (OGEL(K,J),J=1,8) ; IF (DEBUG(200) > 0) WRITE(ANS,1414) (OGEL(K,J),J=1,8) DO L=1,NUM_PTS-1 K = K + 1 WRITE(ERR,4) I,K WRITE(F06,*) ; IF (DEBUG(200) > 0) WRITE(ANS,*) IF (DABS(POLY_FIT_ERR(I+L)) >= 0.01D0) THEN WRITE(F06,1405) FILL(1: 0), GID_OUT_ARRAY(I,L+1),(OGEL(K,J),J=1,10), POLY_FIT_ERR(I+L), POLY_FIT_ERR_INDEX(I+L) WRT_ERR_INDEX_NOTE(POLY_FIT_ERR_INDEX(I+L)) = 'Y' ELSE WRITE(F06,1406) FILL(1: 0), GID_OUT_ARRAY(I,L+1),(OGEL(K,J),J=1,10), POLY_FIT_ERR(I+L) ENDIF IF (DEBUG(200) > 0) THEN WRITE(ANS,1415) GID_OUT_ARRAY(I,L+1),(OGEL(K,J),J=1,10), POLY_FIT_ERR(I+L), POLY_FIT_ERR_INDEX(I+L) ENDIF K = K + 1 WRITE(F06,1407) FILL(1: 0), (OGEL(K,J),J=1,8) ; IF (DEBUG(200) > 0) WRITE(ANS,1417) (OGEL(K,J),J=1,8) ENDDO ENDDO CALL GET_MAX_MIN_ABS_STR ( NUM, 10, 'Y', MAX_ANS, MIN_ANS, ABS_ANS ) MAX_ANS(11) = ZERO ! Get max POLY_FIT_ERR K = 0 DO I=1,NUM K = K + 1 IF (POLY_FIT_ERR(I) > MAX_ANS(11)) THEN MAX_ANS(11) = POLY_FIT_ERR(I) ENDIF K = K + 1 ENDDO MIN_ANS(11) = MAX_ANS(11) K = 0 ! Get min POLY_FIT_ERR DO I=1,NUM K = K + 1 IF (POLY_FIT_ERR(I) < MIN_ANS(11)) THEN MIN_ANS(11) = POLY_FIT_ERR(I) ENDIF K = K + 1 ENDDO ! Get abs POLY_FIT_ERR ABS_ANS(11) = MAX( DABS(MAX_ANS(11)), DABS(MIN_ANS(11)) ) IF (STRE_LOC == 'CORNER ') THEN WRITE(F06,1408) FILL(1: 0), FILL(1: 0), MAX_ANS(2),MAX_ANS(3),MAX_ANS(4),MAX_ANS(6),MAX_ANS(7),MAX_ANS(8),MAX_ANS(9), & MAX_ANS(10),MAX_ANS(11), & FILL(1: 0), MIN_ANS(2),MIN_ANS(3),MIN_ANS(4),MIN_ANS(6),MIN_ANS(7),MIN_ANS(8),MIN_ANS(9), & MIN_ANS(10),MIN_ANS(11), & FILL(1: 0), ABS_ANS(2),ABS_ANS(3),ABS_ANS(4),ABS_ANS(6),ABS_ANS(7),ABS_ANS(8),ABS_ANS(9), & ABS_ANS(10),ABS_ANS(11), FILL(1: 0) ELSE WRITE(F06,1408) FILL(1: 0), FILL(1: 0), MAX_ANS(2),MAX_ANS(3),MAX_ANS(4),MAX_ANS(6),MAX_ANS(7),MAX_ANS(8),MAX_ANS(9), & MAX_ANS(10),MAX_ANS(11), & FILL(1: 0), MIN_ANS(2),MIN_ANS(3),MIN_ANS(4),MIN_ANS(6),MIN_ANS(7),MIN_ANS(8),MIN_ANS(9), & MIN_ANS(10),MIN_ANS(11), & FILL(1: 0), ABS_ANS(2),ABS_ANS(3),ABS_ANS(4),ABS_ANS(6),ABS_ANS(7),ABS_ANS(8),ABS_ANS(9), & ABS_ANS(10),ABS_ANS(11), FILL(1: 0) ENDIF IF (DEBUG(200) > 0) THEN IF (STRE_LOC == 'CORNER ') THEN WRITE(ANS,1418)MAX_ANS(2),MAX_ANS(3),MAX_ANS(4),MAX_ANS(6),MAX_ANS(7),MAX_ANS(8),MAX_ANS(9),MAX_ANS(10),MAX_ANS(11),& MIN_ANS(2),MIN_ANS(3),MIN_ANS(4),MIN_ANS(6),MIN_ANS(7),MIN_ANS(8),MIN_ANS(9),MIN_ANS(10),MIN_ANS(11),& ABS_ANS(2),ABS_ANS(3),ABS_ANS(4),ABS_ANS(6),ABS_ANS(7),ABS_ANS(8),ABS_ANS(9),ABS_ANS(10) ELSE WRITE(ANS,1418)MAX_ANS(2),MAX_ANS(3),MAX_ANS(4),MAX_ANS(6),MAX_ANS(7),MAX_ANS(8),MAX_ANS(9),MAX_ANS(10),MAX_ANS(11),& MIN_ANS(2),MIN_ANS(3),MIN_ANS(4),MIN_ANS(6),MIN_ANS(7),MIN_ANS(8),MIN_ANS(9),MIN_ANS(10),MIN_ANS(11),& ABS_ANS(2),ABS_ANS(3),ABS_ANS(4),ABS_ANS(6),ABS_ANS(7),ABS_ANS(8),ABS_ANS(9),ABS_ANS(10),ABS_ANS(11) ENDIF ENDIF WRITE_NOTES = 'N' DO I=1,MAX_NUM_STR IF (WRT_ERR_INDEX_NOTE(I) == 'Y') THEN WRITE_NOTES = 'Y' ENDIF ENDDO IF (WRITE_NOTES == 'Y') THEN WRITE(F06,1498) DO I=1,MAX_NUM_STR IF (WRT_ERR_INDEX_NOTE(I) == 'Y') THEN WRITE(F06,1499) ERR_INDEX_NOTE(I) ENDIF ENDDO ENDIF ELSE IF (TYPE == 'ROD ') THEN CALL WRITE_ROD (ISUBCASE, NUM, FILL(1:1), FILL(1:16), ITABLE, TITLEI, STITLEI, LABELI, FIELD5_INT_MODE, FIELD6_EIGENVALUE ) ELSE IF (TYPE(1:5) == 'SHEAR') THEN CALL WRITE_OES_CSHEAR(NUM, FILL, ISUBCASE, ITABLE, TITLEI, STITLEI, LABELI, & FIELD5_INT_MODE, FIELD6_EIGENVALUE) ELSE IF (TYPE(1:5) == 'TRIA3') THEN CALL WRITE_OES_CTRIA3(NUM, FILL, ISUBCASE, ITABLE, TITLEI, STITLEI, LABELI, & FIELD5_INT_MODE, FIELD6_EIGENVALUE) ELSE IF (TYPE == 'BUSH ') THEN ELEMENT_TYPE = 102 ! CBUSH NUM_WIDE = 7 ! eid, tx, ty, tz, rx, ry, rz STRESS_CODE = 1 ! dunno NVALUES = NUM * NUM_WIDE CALL WRITE_OES3_STATIC(ITABLE, ISUBCASE, DEVICE_CODE, ELEMENT_TYPE, NUM_WIDE, STRESS_CODE, & TITLEI, STITLEI, LABELI, FIELD5_INT_MODE, FIELD6_EIGENVALUE) WRITE(OP2) NVALUES WRITE(OP2) (EID_OUT_ARRAY(I,1)*10+DEVICE_CODE,(REAL(OGEL(I,J),4),J=1,6), I=1,NUM) DO I=1,NUM WRITE(F06,1802) EID_OUT_ARRAY(I,1),(OGEL(I,J),J=1,6) ; IF (DEBUG(200) > 0) WRITE(ANS,1812) EID_OUT_ARRAY(I,1), & (OGEL(I,J),J=1,6) ENDDO ELSE IF (TYPE == 'USERIN ') THEN DO I=1,NUM WRITE(F06,1902) EID_OUT_ARRAY(I,1),(OGEL(I,J),J=1,6) ; IF (DEBUG(200) > 0) WRITE(ANS,1812) EID_OUT_ARRAY(I,1), & (OGEL(I,J),J=1,6) ENDDO ELSE WRITE(ERR,9300) SUBR_NAME,TYPE WRITE(F06,9300) SUBR_NAME,TYPE FATAL_ERR = FATAL_ERR + 1 CALL OUTA_HERE ( 'Y' ) ! Coding error (elem type not valid) , so quit ENDIF ! ********************************************************************************************************************************** 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(' OUTPUT FOR SUBCASE ',I8) 102 FORMAT(' OUTPUT FOR EIGENVECTOR ',I8) 103 FORMAT(' OUTPUT FOR CRAIG-BAMPTON DOF ',I8,' OF ',I8,' (boundary ',A,' for grid',I8,' component',I2,')') 104 FORMAT(' OUTPUT FOR CRAIG-BAMPTON DOF ',I8,' OF ',I8,' (modal acceleration for mode ',I8,')') 201 FORMAT(1X,A) 301 FORMAT(A,'E L E M E N T S T R E S S E S I N L O C A L E L E M E N T C O O R D I N A T E S Y S T E M') 302 FORMAT(A,'C B E L E M E N T S T R E S S E S O T M I N L O C A L E L E M E N T C O O R D I N A T E', & ' S Y S T E M') 401 FORMAT(A,'F O R E L E M E N T T Y P E ',A11) ! BAR >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1101 FORMAT( & 1X,A,'Element SA1 SA2 SA3 SA4 Axial SA-Max SA-Min M.S.-T'& ,' Torsional' & ,/,1X,A,' ID SB1 SB2 SB3 SB4 Stress SB-Max SB-Min M.S.-C'& ,' Stress/Margin') 1102 FORMAT( & 1X,A,'Element SA1 SA2 SA3 SA4 Axial SA-Max SA-Min M.S.-T' & ,/,1X,A,' ID SB1 SB2 SB3 SB4 Stress SB-Max SB-Min M.S.-C') ! ELAS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1201 FORMAT(1X,A,'Element Stress Element Stress Element Stress Element Stress Element Stress' & ,/,1X,A,' ID ID ID ID ID') 1103 FORMAT(5(A,I8,1ES14.6)) 1104 FORMAT(A,I8,1ES14.6) ! 3D Elems >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1301 FORMAT(A,'Element Sigma-xx Sigma-yy Sigma-zz Tau-xy Tau-yz Tau-zx von Mises' & ,/,A,' ID') 1302 FORMAT(A,'Element Sigma-xx Sigma-yy Sigma-zz Tau-xy Tau-yz Tau-zx ', & 'Octahedral Stress' & ,/,A,' ID',91X,'Direct Shear') 1303 FORMAT(19X,I8,8(1ES14.6)) 1304 FORMAT(28X,'------------- ------------- ------------- ------------- ------------- ------------- -------------',/, & 16X,'MAX* : ',7(ES14.6),/, & 16X,'MIN* : ',7(ES14.6),//, & 16X,'ABS* : ',7(ES14.6),/ & 16X,'* for output set') 1305 FORMAT(27X,' ------------- ------------- ------------- ------------- ------------- ------------- -------------', & ' -------------',/, & 16X,'MAX* : ',8(ES14.6),/, & 16X,'MIN* : ',8(ES14.6),//, & 16X,'ABS* : ',8(ES14.6),/ & 16X,'* for output set') 1313 FORMAT(16X,I8,8(1ES14.6)) 1314 FORMAT(28X,'------------- ------------- ------------- ------------- ------------- ------------- -------------',/, & 1X,'MAX (for output set): ',7(ES14.6),/, & 1X,'MIN (for output set): ',7(ES14.6),//, & 1X,'ABS (for output set): ',7(ES14.6),/, & 1X,'*for output set') 1315 FORMAT(28X,'------------- ------------- ------------- ------------- ------------- ------------- -------------', & ' -------------',/, & 1X,'MAX (for output set): ',8(ES14.6),/, & 1X,'MIN (for output set): ',8(ES14.6),//, & 1X,'ABS (for output set): ',8(ES14.6),/, & 1X,'*for output set') ! QUAD4 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1401 FORMAT(1X,A,' Elem Location Fibre Stresses In Element Coord System Principal Stresses (Zero Shear)', & ' Transverse Transverse % Poly',/,1X,A, & ' ID Distance Normal-X Normal-Y Shear-XY Angle Major Minor von Mises', & ' Shear-XZ Shear-YZ Fit Err',/,1X,A,119X,'(max through thickness)') 1402 FORMAT(1X,A,'Elem Location Fibre Stresses In Element Coord System Principal Stresses (Zero Shear)', & ' Max Transverse Transverse % Poly',/,1X,A, & ' ID Distance Normal-X Normal-Y Shear-XY Angle Major Minor Shear-XY', & ' Shear-XZ Shear-YZ Fit Err',/,1X,A,119X,'(max through thickness)') 1403 FORMAT(1X,A,I8,2X,'CENTER ',3X,1ES11.3,3(1ES13.5),0PF8.2,5(1ES13.5)) 1404 FORMAT(1X,A,21X,1ES11.3,3(1ES13.5),0PF8.2,3(1ES13.5)) 1405 FORMAT(1X,A,10X,'GRD',I8,1ES11.3,3(1ES13.5),0PF8.2,5(1ES13.5),E9.1,'(',I1,')') 1406 FORMAT(1X,A,10X,'GRD',I8,1ES11.3,3(1ES13.5),0PF8.2,5(1ES13.5),E9.1) 1407 FORMAT(1X,A,21X,1ES11.3,3(1ES13.5),0PF8.2,3(1ES13.5)) 1408 FORMAT(1X,A,32X,' ------------ ------------ ------------ ------------ ------------ ------------ ------------', & ' ------------ --------',/, & 1X,A,'MAX* : ',25x,3(ES13.5),8X,5(ES13.5),E9.1,/, & 1X,A,'MIN* : ',25x,3(ES13.5),8X,5(ES13.5),E9.1,//, & 1X,A,'ABS* : ',25x,3(ES13.5),8X,5(ES13.5),E9.1,/, & 1X,A,'*for output set') 1413 FORMAT(1X,I8,2X,'CENTER ',5X,4(1ES14.6),0PF14.3,5(1ES14.6)) 1414 FORMAT(9X,15X,4(1ES14.6),0PF14.3,3(1ES14.6)) 1415 FORMAT(21X,'GRID',I8,1X,4(1ES14.6),0PF9.3,5(1ES14.6),F13.2,'% (',I1,')') 1417 FORMAT(9X,15X,4(1ES14.6),0PF9.3,3(1ES14.6)) 1418 FORMAT(39X,'------------- ------------- ------------- ------------- ------------- ------------- -------------',& ' ------------- -------------',/, & 1X,'MAX (for output set): ',15X,3(ES14.6),14X,5(ES14.6),F14.2,/, & 1X,'MIN (for output set): ',15X,3(ES14.6),14X,5(ES14.6),F14.2,//, & 1X,'ABS (for output set): ',15X,3(ES14.6),14X,5(ES14.6),F14.2) 1498 FORMAT(' NOTE: Explanation of errors in the polynomial fit to extrapolate element corner point stresses from values at the', & ' Gauss points:') 1499 FORMAT(6X,A) ! ROD >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1501 FORMAT( & 1X,A,'Element Axial Safety Torsional Safety Element Axial Safety Torsional Safety' & ,/,1X,A,' ID Stress Margin Stress Margin ID Stress Margin Stress Margin') ! SHEAR ---------------------------------------------------------------------------------------------------------------------------- 1601 FORMAT(1X,A,'Element S t r e s s e s Element S t r e s s e s' & ,/,1X,A,' ID Normal-X Normal-Y Shear-XY ID Normal-X Normal-Y' & ,' Shear-XY') ! TRIA3 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1701 FORMAT(1X,A,'Element Location Fibre Stresses In Element Coord System Principal Stresses (Zero Shear)', & ' Transverse Transverse' & ,/,1X,A,' ID Distance Normal-X Normal-Y Shear-XY Angle Major Minor' & ,' von Mises Shear-XZ Shear-YZ' & ,/,1X,A,123X,'(max through thickness)') 1702 FORMAT(1X,A,'Element Location Fibre Stresses In Element Coord System Principal Stresses (Zero Shear)', & ' Max Transverse Transverse' & ,/,1X,A,' ID Distance Normal-X Normal-Y Shear-XY Angle Major Minor', & ' Shear-XY Shear-XZ Shear-YZ',/,1X,123X,'(max through thickness)') 1703 FORMAT(1X,I8,4X,'Anywhere',2X,4(1ES13.5),0PF9.3,5(1ES13.5)) 1704 FORMAT(13X,'in elem',3X,4(1ES13.5),0PF9.3,5(1ES13.5)) 1705 FORMAT(37X,'------------ ------------ ------------ ------------ ------------ ------------ ------------', & ' ------------',/, & 1X,'MAX* : ',28x,3(ES13.5),9X,5(ES13.5),/, & 1X,'MIN* : ',28x,3(ES13.5),9X,5(ES13.5),//, & 1X,'ABS* : ',28x,3(ES13.5),9X,5(ES13.5),/, & 1X,'*for output set') 1713 FORMAT(1X,I8,4X,'Anywhere',3X,4(1ES14.6),0PF14.3,5(1ES14.6)) 1714 FORMAT(13X,'in elem',4X,4(1ES14.6),0PF14.3,5(1ES14.6)) 1715 FORMAT(39X,'------------- ------------- ------------- ------------- ------------- ------------- ---------',/, & 1X,'MAX (for output set): ',15X,3(ES14.6),14X,5(ES14.6),/, & 1X,'MIN (for output set): ',15X,3(ES14.6),14X,5(ES14.6),//, & 1X,'ABS (for output set): ',15X,3(ES14.6),14X,5(ES14.6),/) ! BUSH >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1801 FORMAT(20X,A,'Element Stress-1 Stress-2 Stress-3 Stress-4 Stress-5 Stress-6' & ,/,20X,A,' ID') 1802 FORMAT(19X,I8,8(1ES14.6)) 1812 FORMAT(16X,I8,8(1ES14.6)) ! USERIN >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1901 FORMAT(20X,A,'Element Stress-1 Stress-2 Stress-3 Stress-4 Stress-5 Stress-6' & ,/,20X,A,' ID') 1902 FORMAT(19X,I8,8(1ES14.6)) 1912 FORMAT(17X,I8,8(1ES14.6)) ! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 9300 FORMAT(' *ERROR 9300: PROGRAMMING ERROR IN SUBROUTINE ',A & ,/,14X,' NO OUTPUT FORMAT AVAILABLE FOR ELEMENT TYPE = ',A) ! ********************************************************************************************************************************** END SUBROUTINE WRITE_ELEM_STRESSES !============================================================================== SUBROUTINE WRITE_OES_CSHEAR(NUM, FILL, ISUBCASE, ITABLE, TITLE, SUBTITLE, LABEL, & FIELD5_INT_MODE, FIELD6_EIGENVALUE ) ! TODO: calculate margin ! USE PENTIUM_II_KIND, ONLY : BYTE, LONG, DOUBLE USE IOUNT1, ONLY : F06, OP2, ERR USE LINK9_STUFF, ONLY : EID_OUT_ARRAY, OGEL USE, INTRINSIC :: IEEE_ARITHMETIC, ONLY: IEEE_Value, IEEE_QUIET_NAN USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: REAL32 IMPLICIT NONE ! INTEGER(LONG), INTENT(IN) :: NUM ! the number of elements INTEGER(LONG), INTENT(IN) :: ISUBCASE ! the current subcase CHARACTER(LEN=128), INTENT(IN) :: TITLE ! the model TITLE CHARACTER(LEN=128), INTENT(IN) :: SUBTITLE ! the subcase SUBTITLE CHARACTER(LEN=128), INTENT(IN) :: LABEL ! the subcase LABEL CHARACTER(128*BYTE) :: FILL ! Padding for output format INTEGER(LONG), INTENT(INOUT) :: ITABLE ! the current subtable number !LOGICAL :: FIELD_5_INT_FLAG ! flag to trigger FIELD5_INT_MODE vs. FIELD5_FLOAT_TIME_FREQ INTEGER(LONG) :: FIELD5_INT_MODE ! int value for field 5 !REAL(DOUBLE) :: FIELD5_FLOAT_TIME_FREQ ! float value for field 5 REAL(DOUBLE) :: FIELD6_EIGENVALUE ! float value for field 6 INTEGER(LONG), PARAMETER :: DEVICE_CODE = 1 ! PLOT, PRINT, PUNCH flag; plot INTEGER(LONG) :: NUM_WIDE = 4 ! the number of "words" for an element INTEGER(LONG) :: NVALUES ! the number of "words" for all the elments INTEGER(LONG) :: NTOTAL ! the number of bytes for all NVALUES INTEGER(LONG) :: ELEMENT_TYPE = 4 ! the OP2 flag for the element INTEGER(LONG) :: STRESS_CODE ! the OP2 flag for the stress REAL(DOUBLE) :: ABS_ANS(3) ! Max ABS for output REAL(DOUBLE) :: MAX_ANS(3) ! Max for output REAL(DOUBLE) :: MIN_ANS(3) ! Min for output INTEGER(LONG) :: I, J ! DO loop indices REAL(REAL32) :: NAN NAN = IEEE_VALUE(NAN, IEEE_QUIET_NAN) NVALUES = NUM * NUM_WIDE NTOTAL = NVALUES * 4 ! eid, max_shear, avg_shear, margin CALL WRITE_OES3_STATIC(ITABLE, ISUBCASE, DEVICE_CODE, ELEMENT_TYPE, NUM_WIDE, STRESS_CODE, & TITLE, SUBTITLE, LABEL, FIELD5_INT_MODE, FIELD6_EIGENVALUE) 100 FORMAT("*DEBUG: WRITE_CSHEAR ITABLE=",I8, "; NUM=",I8,"; NVALUES=",I8,"; NTOTAL=",I8) 101 FORMAT("*DEBUG: WRITE_CSHEAR ITABLE=",I8," (should be -5, -7,...)") NVALUES = NUM * NUM_WIDE NTOTAL = NVALUES * 4 WRITE(ERR,100) ITABLE,NUM,NVALUES,NTOTAL WRITE(OP2) NVALUES ! Nastran OP2 requires this write call be a one liner...so it's a little weird... ! translating: ! DO I=1,NUM ! WRITE(OP2) EID_OUT_ARRAY(I,1)*10+DEVICE_CODE ! Nastran is weird and requires scaling the ELEMENT_ID ! ! convert from float64 (double precision) to float32 (single precision) ! RE1 = REAL(OGEL(I,1), 4) ! RE2 = REAL(OGEL(I,2), 4) ! RE3 = REAL(OGEL(I,3), 4) ! ! write the max_shear, avg_shear, ! WRITE(OP2) RE1, RE2, RE3 ! ENDDO ! ! write the CSHEAR stress/strain data !Normal-X Normal-Y Shear-XY -> max_shear, avg_shear, margin WRITE(OP2) (EID_OUT_ARRAY(I,1)*10+DEVICE_CODE, REAL(OGEL(I,3), 4), REAL(OGEL(I,3), 4), & NAN, I=1,NUM) WRITE(ERR,100) ITABLE DO I=1,NUM,2 IF (I+1 <= NUM) THEN WRITE(F06,1603) FILL(1: 0), EID_OUT_ARRAY(I,1),(OGEL(I,J),J=1,3), EID_OUT_ARRAY(I+1,1),(OGEL(I+1,J),J=1,3) ELSE WRITE(F06,1603) FILL(1: 0), EID_OUT_ARRAY(I,1),(OGEL(I,J),J=1,3) ENDIF ENDDO CALL GET_MAX_MIN_ABS_STR ( NUM, 3, 'N', MAX_ANS, MIN_ANS, ABS_ANS ) WRITE(F06,1604) FILL(1: 0), FILL(1: 0), MAX_ANS(1),MAX_ANS(2),MAX_ANS(3), & FILL(1: 0), MIN_ANS(1),MIN_ANS(2),MIN_ANS(3), & FILL(1: 0), ABS_ANS(1),ABS_ANS(2),ABS_ANS(3) 1603 FORMAT(1X,A,I8,3(1ES14.6),13X,I8,3(1ES14.6)) 1604 FORMAT(1X,A,' ------------- ------------- ------------- ',20X,' ------------- ------------- ------------- ',/, & 1X,A,'MAX* : ',1X,3(ES14.6),/, & 1X,A,'MIN* : ',1X,3(ES14.6),//, & 1X,A,'ABS* : ',1X,3(ES14.6),/, & 1X,A,'*for output set') END SUBROUTINE WRITE_OES_CSHEAR !============================================================================== SUBROUTINE WRITE_OES_CTRIA3 ( NUM, FILL, ISUBCASE, ITABLE, TITLE, SUBTITLE, LABEL, & FIELD5_INT_MODE, FIELD6_EIGENVALUE ) USE PENTIUM_II_KIND, ONLY : BYTE, LONG, DOUBLE USE IOUNT1, ONLY : ANS, ERR, F06, OP2 USE LINK9_STUFF, ONLY : EID_OUT_ARRAY, OGEL USE DEBUG_PARAMETERS, ONLY : DEBUG IMPLICIT NONE ! INTEGER(LONG), INTENT(IN) :: NUM ! the number of elements INTEGER(LONG), INTENT(IN) :: ISUBCASE ! the current subcase CHARACTER(LEN=128), INTENT(IN) :: TITLE ! the model TITLE CHARACTER(LEN=128), INTENT(IN) :: SUBTITLE ! the subcase SUBTITLE CHARACTER(LEN=128), INTENT(IN) :: LABEL ! the subcase LABEL CHARACTER(128*BYTE) :: FILL ! Padding for output format INTEGER(LONG), INTENT(INOUT) :: ITABLE ! the current subtable number !LOGICAL :: FIELD_5_INT_FLAG ! flag to trigger FIELD5_INT_MODE vs. FIELD5_FLOAT_TIME_FREQ INTEGER(LONG) :: FIELD5_INT_MODE ! int value for field 5 !REAL(DOUBLE) :: FIELD5_FLOAT_TIME_FREQ ! float value for field 5 REAL(DOUBLE) :: FIELD6_EIGENVALUE ! float value for field 6 INTEGER(LONG) :: DEVICE_CODE = 1 ! PLOT, PRINT, PUNCH flag; set as PLOT INTEGER(LONG), PARAMETER :: NUM_WIDE = 17 ! the number of "words" for an element INTEGER(LONG) :: NVALUES ! the number of "words" for all the elments INTEGER(LONG) :: NTOTAL ! the number of bytes for all NVALUES INTEGER(LONG) :: ELEMENT_TYPE = 74 ! the OP2 flag for the element INTEGER(LONG) :: STRESS_CODE = 1 ! the OP2 flag for the stress; preallocate REAL(DOUBLE) :: ABS_ANS(11) ! Max ABS for output REAL(DOUBLE) :: MAX_ANS(11) ! Max for output REAL(DOUBLE) :: MIN_ANS(11) ! Min for output INTEGER(LONG) :: I, J, K ! DO loop indices ! [eid, fiber_dist/curvature, oxx, oyy, txy, angle, omax, omin, ovm/max_shear, ! upper ! fiber_dist/curvature, oxx, oyy, txy, angle, omax, omin, ovm/max_shear, ! lower !] NVALUES = NUM * NUM_WIDE K = 0 100 FORMAT("*DEBUG: WRITE_CTRIA3 ITABLE=",I8, "; NUM=",I8,"; NVALUES=",I8,"; NTOTAL=",I8) !101 FORMAT("*DEBUG: WRITE_CTRIA3 ITABLE=",I8," (should be -5, -7,...)") NVALUES = NUM * NUM_WIDE NTOTAL = NVALUES * 4 WRITE(ERR,100) ITABLE,NUM,NVALUES,NTOTAL !CALL GET_STRESS_CODE(STRESS_CODE, IS_VON_MISES, IS_STRAIN, IS_FIBER_DISTANCE) CALL GET_STRESS_CODE( STRESS_CODE, 1, 0, 1) CALL WRITE_OES3_STATIC(ITABLE, ISUBCASE, DEVICE_CODE, ELEMENT_TYPE, NUM_WIDE, STRESS_CODE, & TITLE, SUBTITLE, LABEL, FIELD5_INT_MODE, FIELD6_EIGENVALUE) WRITE(OP2) NVALUES ! 1702 FORMAT(1X,A,'Element Location Fibre Stresses In Element Coord System Principal Stresses (Zero Shear)', & ! ' Max Transverse Transverse' & ! ,/,1X,A,' ID Distance Normal-X Normal-Y Shear-XY Angle Major Minor', & ! ' Shear-XY Shear-XZ Shear-YZ',/,1X,123X,'(max through thickness)') ! op2 version of the upper & lower layers all in one call, but without the transverse shear WRITE(OP2) (EID_OUT_ARRAY(I,1)*10+DEVICE_CODE, (REAL(OGEL(2*I-1,J),4), J=1,8), (REAL(OGEL(2*I,J),4), J=1,8), I=1,NUM) 1703 FORMAT(1X,I8,4X,'Anywhere',2X,4(1ES13.5),0PF9.3,5(1ES13.5)) 1704 FORMAT(13X,'in elem',3X,4(1ES13.5),0PF9.3,5(1ES13.5)) 1705 FORMAT(37X,'------------ ------------ ------------ ------------ ------------ ------------ ------------', & ' ------------',/, & 1X,'MAX* : ',28x,3(ES13.5),9X,5(ES13.5),/, & 1X,'MIN* : ',28x,3(ES13.5),9X,5(ES13.5),//, & 1X,'ABS* : ',28x,3(ES13.5),9X,5(ES13.5),/, & 1X,'*for output set') 1713 FORMAT(1X,I8,4X,'Anywhere',3X,4(1ES14.6),0PF14.3,5(1ES14.6)) 1714 FORMAT(13X,'in elem',4X,4(1ES14.6),0PF14.3,5(1ES14.6)) 1715 FORMAT(39X,'------------- ------------- ------------- ------------- ------------- ------------- ---------',/, & 1X,'MAX (for output set): ',15X,3(ES14.6),14X,5(ES14.6),/, & 1X,'MIN (for output set): ',15X,3(ES14.6),14X,5(ES14.6),//, & 1X,'ABS (for output set): ',15X,3(ES14.6),14X,5(ES14.6),/) DO I=1,NUM K = K + 1 WRITE(F06,*) ; WRITE(ANS,*) ! the J=1,10 loop is the upper layer & 2 transverse shear WRITE(F06,1703) EID_OUT_ARRAY(I,1),(OGEL(K,J),J=1,10); IF (DEBUG(200) > 0) WRITE(ANS,1713) EID_OUT_ARRAY(I,1), & (OGEL(K,J),J=1,10) K = K + 1 ! the J=1,8 loop is the lower layer WRITE(F06,1704) (OGEL(K,J),J=1,8) ; IF (DEBUG(200) > 0) WRITE(ANS,1714) (OGEL(K,J),J=1,10) ENDDO CALL GET_MAX_MIN_ABS_STR ( NUM, 10, 'Y', MAX_ANS, MIN_ANS, ABS_ANS ) WRITE(F06,1705) MAX_ANS(2),MAX_ANS(3),MAX_ANS(4),MAX_ANS(6),MAX_ANS(7),MAX_ANS(8),MAX_ANS(9),MAX_ANS(10), & MIN_ANS(2),MIN_ANS(3),MIN_ANS(4),MIN_ANS(6),MIN_ANS(7),MIN_ANS(8),MIN_ANS(9),MIN_ANS(10), & ABS_ANS(2),ABS_ANS(3),ABS_ANS(4),ABS_ANS(6),ABS_ANS(7),ABS_ANS(8),ABS_ANS(9),ABS_ANS(10) IF (DEBUG(200) > 0) THEN WRITE(ANS,1715) MAX_ANS(2),MAX_ANS(3),MAX_ANS(4),MAX_ANS(6),MAX_ANS(7),MAX_ANS(8),MAX_ANS(9),MAX_ANS(10), & MIN_ANS(2),MIN_ANS(3),MIN_ANS(4),MIN_ANS(6),MIN_ANS(7),MIN_ANS(8),MIN_ANS(9),MIN_ANS(10), & ABS_ANS(2),ABS_ANS(3),ABS_ANS(4),ABS_ANS(6),ABS_ANS(7),ABS_ANS(8),ABS_ANS(9),ABS_ANS(10) ENDIF END SUBROUTINE WRITE_OES_CTRIA3 !============================================================================== SUBROUTINE GET_SPRING_OP2_ELEMENT_TYPE(ELEMENT_TYPE) USE PENTIUM_II_KIND, ONLY : BYTE, LONG, DOUBLE USE IOUNT1, ONLY : ERR USE MODEL_STUF, ONLY : TYPE IMPLICIT NONE INTEGER(LONG) :: ELEMENT_TYPE ! the OP2 flag for the element ! 12345 ! 11 : CELAS1 - ELAS1 ! 12 : CELAS2 ! 13 : CELAS3 ! 14 : CELAS4 IF (TYPE(5:5) == "1") THEN ELEMENT_TYPE = 11 ELSE IF (TYPE(5:5) == "2") THEN ELEMENT_TYPE = 12 ELSE IF (TYPE(5:5) == "3") THEN ELEMENT_TYPE = 13 ELSE IF (TYPE(5:5) == "4") THEN ELEMENT_TYPE = 14 ELSE 42 FORMAT("TYPE(4:4)=",A," TYPE(5:5)=",A," TYPE(6:6)=",A) WRITE(ERR,42) TYPE(4:4),TYPE(5:5),TYPE(6:6) ELEMENT_TYPE = -1 ENDIF END SUBROUTINE GET_SPRING_OP2_ELEMENT_TYPE
Nike created a signature shoe for him , called the Air Jordan . One of Jordan 's more popular commercials for the shoe involved Spike Lee playing the part of Mars Blackmon . In the commercials Lee , as Blackmon , attempted to find the source of Jordan 's abilities and became convinced that " it 's gotta be the shoes " . The hype and demand for the shoes even brought on a spate of " shoe @-@ <unk> " where people were robbed of their sneakers at gunpoint . Subsequently , Nike spun off the Jordan line into its own division named the " Jordan Brand " . The company features an impressive list of athletes and celebrities as endorsers . The brand has also sponsored college sports programs such as those of North Carolina , Cal , Georgetown , and Marquette .
module Lemmas import Data.Nat import Data.Vect import Decidable.Equality import Injection import Complex %default total export lemmaplusOneRight : (n : Nat) -> n + 1 = S n lemmaplusOneRight n = rewrite plusCommutative n 1 in Refl export lemmaPlusSRight : (n : Nat) -> (k : Nat) -> plus n (S k) = S (plus n k) lemmaPlusSRight Z k = Refl lemmaPlusSRight (S p) k = rewrite lemmaPlusSRight p k in Refl --LEMMAS ABOUT && export lemmaAndLeft : {a : Bool} -> {b : Bool} -> (a && b = True) -> (a = True) lemmaAndLeft {a = True} {b} p = Refl lemmaAndLeft {a = False} {b} p impossible export lemmaAndRight : {a : Bool} -> {b : Bool} -> (a && b = True) -> (b = True) lemmaAndRight {a} {b = True} p = Refl lemmaAndRight {a = True} {b = False} p impossible lemmaAndRight {a = False} {b = False} p impossible export lemmaAnd : {a : Bool} -> {b : Bool} -> (a = True) -> (b = True) -> (a && b = True) lemmaAnd {a = True} {b = True} p1 p2 = Refl --LEMMAS ABOUT <, >, =, /=, <=, >= : TRANSITIVITY export lemmaTransLTELT : (i : Nat) -> (n : Nat) -> (p : Nat) -> (i <= n) = True -> (n < p) = True -> (i < p) = True lemmaTransLTELT 0 0 (S k) _ _ = Refl lemmaTransLTELT 0 (S k) (S j) _ _ = Refl lemmaTransLTELT (S k) (S n) (S p) prf1 prf2 = rewrite lemmaTransLTELT k n p prf1 prf2 in Refl export lemmaTransLTLTE : (i : Nat) -> (n : Nat) -> (p : Nat) -> (i < n) = True -> (n <= p) = True -> (i < p) = True lemmaTransLTLTE 0 (S n) (S k) prf prf1 = Refl lemmaTransLTLTE (S k) (S n) (S p) prf prf1 = rewrite lemmaTransLTLTE k n p prf prf1 in Refl export lemmaTransitivity : (i : Nat) -> (n : Nat) -> (p : Nat) -> (i < n) = True -> (n < p) = True -> (i < p) = True lemmaTransitivity 0 (S k) (S m) prf prf1 = Refl lemmaTransitivity (S k) (S m) (S l) prf prf1 = lemmaTransitivity k m l prf prf1 --BASIC LEMMAS ABOUT <, >, =, /=, <=, >= export lemmaLTERefl : (n : Nat) -> (n <= n) = True lemmaLTERefl 0 = Refl lemmaLTERefl (S k) = lemmaLTERefl k export lemmaSymDiff : {x : Nat} -> {y : Nat} -> (x /= y) = True -> (y /= x) = True lemmaSymDiff {x = 0} {y = (S m)} _ = Refl lemmaSymDiff {x = (S k)} {y = 0} _ = Refl lemmaSymDiff {x = (S k)} {y = (S j)} prf = lemmaSymDiff {x = k} {y = j} prf export lemma0LTSucc : (k : Nat) -> 0 < S k = True lemma0LTSucc k = Refl export lemma1LTESucc : (k : Nat) -> 1 <= S k = True lemma1LTESucc 0 = Refl lemma1LTESucc (S k) = Refl export lemmaLTEAddR : (n : Nat) -> (p : Nat) -> n <= (n + p) = True lemmaLTEAddR Z 0 = Refl lemmaLTEAddR Z (S k) = Refl lemmaLTEAddR (S n) p = lemmaLTEAddR n p export lemmaLTEAddL : (n : Nat) -> (p : Nat) -> p <= (n + p) = True lemmaLTEAddL n p = rewrite plusCommutative n p in lemmaLTEAddR p n export lemmaDiffSuccPlus : (k : Nat) -> (p : Nat) -> (k /= S (p + k)) = True lemmaDiffSuccPlus 0 p = Refl lemmaDiffSuccPlus (S k) j = rewrite sym $ plusSuccRightSucc j k in lemmaDiffSuccPlus k j export lemmaLTSuccPlus : (k : Nat) -> (p : Nat) -> (k < S (k + p)) = True lemmaLTSuccPlus 0 p = Refl lemmaLTSuccPlus (S k) j = lemmaLTSuccPlus k j export lemmaLTSucc : (k : Nat) -> (k < S k) = True lemmaLTSucc 0 = Refl lemmaLTSucc (S k) = lemmaLTSucc k export lemmakLTSk : (k : Nat) -> (S k) < S (k + 1) = True lemmakLTSk k = rewrite lemmaplusOneRight k in lemmaLTSucc k export lemmaLTSuccLT : (k : Nat) -> (n : Nat) -> (S k) < n = True -> k < n = True lemmaLTSuccLT k 0 prf impossible lemmaLTSuccLT 0 (S j) prf = Refl lemmaLTSuccLT (S k) (S j) prf = lemmaLTSuccLT k j prf export lemmaLTESuccLT : (k : Nat) -> (n : Nat) -> (S k) <= n = True -> k < n = True lemmaLTESuccLT k 0 prf impossible lemmaLTESuccLT 0 (S j) prf = Refl lemmaLTESuccLT (S k) (S j) prf = lemmaLTESuccLT k j prf export lemmaLTESuccLTE : (k : Nat) -> (n : Nat) -> (S k) <= n = True -> k <= n = True lemmaLTESuccLTE k 0 prf impossible lemmaLTESuccLTE 0 (S j) prf = Refl lemmaLTESuccLTE (S k) (S j) prf = lemmaLTESuccLTE k j prf export lemmaSuccsLT : (k : Nat) -> (n : Nat) -> (S k) < (S n) = True -> k < n = True lemmaSuccsLT k n prf = prf export lemmaCompLT0 : (n : Nat) -> (j : Nat) -> {auto prf : j < n = True} -> 0 < n = True lemmaCompLT0 n 0 {prf} = prf lemmaCompLT0 (S p) (S k) = Refl --LEMMAS USED BY THE APPLY FUNCTION export indexInjectiveVect : (j : Nat) -> (n : Nat) -> (v : Vect i Nat) -> {prf : isInjective n v = True} -> {prf1 : j < i = True} -> (index j v < n) = True indexInjectiveVect Z n (x :: xs) {prf} = lemmaAndLeft (lemmaAndLeft prf) indexInjectiveVect (S k) n (x :: xs) {prf} = indexInjectiveVect k n xs {prf = lemmaAnd (lemmaAndRight (lemmaAndLeft prf)) (lemmaAndRight (lemmaAndRight prf))} export different' : (x : Nat) -> (m : Nat) -> (xs : Vect i Nat) -> {prf1 : m < i = True} -> {prf2 : isDifferent x xs = True} -> (x /= index m xs) = True different' x 0 (y :: xs) = lemmaAndLeft prf2 different' x (S k) (y :: xs) = different' x k xs {prf1} {prf2 = lemmaAndRight prf2} private different'' : (x : Nat) -> (m : Nat) -> (xs : Vect i Nat) -> {prf1 : m < i = True} -> {prf2 : isDifferent x xs = True} -> (index m xs /= x) = True different'' x m xs = lemmaSymDiff (different' x m xs {prf1} {prf2}) export differentIndexInjectiveVect : (c : Nat) -> (t : Nat) -> (n : Nat) -> {prf1 : (c /= t) = True} -> (v : Vect i Nat) -> {prf2 : isInjective n v = True} -> {prf3 : c < i = True} -> {prf4 : t < i = True} -> (index c v /= index t v) = True differentIndexInjectiveVect 0 (S m) n (x :: xs) = different' x m xs {prf1 = prf4} {prf2 = lemmaAndLeft (lemmaAndRight prf2)} differentIndexInjectiveVect (S k) 0 n (x :: xs) = different'' x k xs {prf1 = prf3} {prf2 = lemmaAndLeft (lemmaAndRight prf2)} differentIndexInjectiveVect (S k) (S j) n (x :: xs) = let p2 = lemmaAnd (lemmaAndRight (lemmaAndLeft prf2)) (lemmaAndRight (lemmaAndRight prf2)) in differentIndexInjectiveVect k j n {prf1} xs {prf2 = p2} {prf3} {prf4} --LEMMAS USED BY THE CONTROLLED FUNCTION export lemmaControlledInj : (n : Nat) -> (j : Nat) -> {auto prf : j < n = True} -> isInjective (S n) [0, S j] = True lemmaControlledInj 0 0 impossible lemmaControlledInj 0 (S k) {prf} = prf lemmaControlledInj (S k) 0 = Refl lemmaControlledInj (S p) (S k) {prf} = lemmaControlledInj p k {prf} export lemmaControlledInj2 : (n : Nat) -> (c : Nat) -> (t : Nat) -> {auto prf1 : (c < n) = True} -> {auto prf2 : (t < n) = True} -> {auto prf3 : (c /= t) = True} -> isInjective (S n) [0, S c, S t] = True lemmaControlledInj2 0 0 t impossible lemmaControlledInj2 0 (S k) t {prf1} = prf1 lemmaControlledInj2 (S k) 0 0 {prf3} = prf3 lemmaControlledInj2 (S k) 0 (S j) = lemmaAnd (lemmaAnd prf2 Refl) Refl lemmaControlledInj2 (S k) (S j) 0 = lemmaAnd (lemmaAnd prf1 Refl) Refl lemmaControlledInj2 (S k) (S j) (S i) = lemmaControlledInj2 k j i {prf1} {prf2} {prf3} --LEMMAS USED BY THE TENSOR FUNCTION export isDiffRangeVect : (k : Nat) -> (length : Nat) -> (p : Nat) -> isDifferent k (rangeVect (S (p + k)) length) = True isDiffRangeVect k 0 _ = Refl isDiffRangeVect k (S j) p = lemmaAnd (lemmaDiffSuccPlus k p) (isDiffRangeVect k j (S p)) export allDiffRangeVect : (startIndex : Nat) -> (length : Nat) -> allDifferent (rangeVect startIndex length) = True allDiffRangeVect startIndex 0 = Refl allDiffRangeVect startIndex (S k) = let p1 = isDiffRangeVect startIndex k 0 in lemmaAnd p1 (allDiffRangeVect (S startIndex) k) export allSmallerRangeVect : (startIndex : Nat) -> (length : Nat) -> allSmaller (rangeVect startIndex length) (startIndex + length) = True allSmallerRangeVect startIndex 0 = Refl allSmallerRangeVect startIndex (S k) = rewrite sym $ plusSuccRightSucc startIndex k in lemmaAnd (lemmaLTSuccPlus startIndex k) (allSmallerRangeVect (S startIndex) k) export allSmallerPlus : (n : Nat) -> (p : Nat) -> (v : Vect k Nat) -> allSmaller v n = True -> allSmaller v (n + p) = True allSmallerPlus n p [] prf = Refl allSmallerPlus n p (x :: xs) prf = let p1 = lemmaAndLeft prf p2 = lemmaTransLTLTE x n (n + p) p1 (lemmaLTEAddR n p) p3 = lemmaAndRight prf in lemmaAnd p2 (allSmallerPlus n p xs p3)
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Core import Init.NotationExtra universe u v /- Classical reasoning support -/ namespace Classical axiom choice {α : Sort u} : Nonempty α → α noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop) (h : ∃ x, p x) : {x // p x} := choice <| let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩ noncomputable def choose {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : α := (indefiniteDescription p h).val theorem chooseSpec {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : p (choose h) := (indefiniteDescription p h).property /- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/ theorem em (p : Prop) : p ∨ ¬p := let U (x : Prop) : Prop := x = True ∨ p; let V (x : Prop) : Prop := x = False ∨ p; have exU : ∃ x, U x := ⟨True, Or.inl rfl⟩; have exV : ∃ x, V x := ⟨False, Or.inl rfl⟩; let u : Prop := choose exU; let v : Prop := choose exV; have uDef : U u := chooseSpec exU; have vDef : V v := chooseSpec exV; have notUvOrP : u ≠ v ∨ p := match uDef, vDef with | Or.inr h, _ => Or.inr h | _, Or.inr h => Or.inr h | Or.inl hut, Or.inl hvf => have hne : u ≠ v := hvf.symm ▸ hut.symm ▸ trueNeFalse Or.inl hne have pImpliesUv : p → u = v := fun hp => have hpred : U = V := funext fun x => have hl : (x = True ∨ p) → (x = False ∨ p) := fun a => Or.inr hp; have hr : (x = False ∨ p) → (x = True ∨ p) := fun a => Or.inr hp; show (x = True ∨ p) = (x = False ∨ p) from propext (Iff.intro hl hr); have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV := hpred ▸ fun exU exV => rfl; show u = v from h₀ ..; match notUvOrP with | Or.inl hne => Or.inr (mt pImpliesUv hne) | Or.inr h => Or.inl h theorem existsTrueOfNonempty {α : Sort u} : Nonempty α → ∃ x : α, True | ⟨x⟩ => ⟨x, trivial⟩ noncomputable def inhabitedOfNonempty {α : Sort u} (h : Nonempty α) : Inhabited α := ⟨choice h⟩ noncomputable def inhabitedOfExists {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : Inhabited α := inhabitedOfNonempty (Exists.elim h (fun w hw => ⟨w⟩)) /- all propositions are Decidable -/ noncomputable scoped instance (priority := low) propDecidable (a : Prop) : Decidable a := choice <| match em a with | Or.inl h => ⟨isTrue h⟩ | Or.inr h => ⟨isFalse h⟩ noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) where default := inferInstance noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α := fun x y => inferInstance noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) := match (propDecidable (Nonempty α)) with | (isTrue hp) => PSum.inl (@arbitrary _ (inhabitedOfNonempty hp)) | (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn) noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop) (h : Nonempty α) : {x : α // (∃ y : α, p y) → p x} := @dite _ (∃ x : α, p x) (propDecidable _) (fun (hp : ∃ x : α, p x) => show {x : α // (∃ y : α, p y) → p x} from let xp := indefiniteDescription _ hp; ⟨xp.val, fun h' => xp.property⟩) (fun hp => ⟨choice h, fun h => absurd h hp⟩) /- the Hilbert epsilon Function -/ noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α := (strongIndefiniteDescription p h).val theorem epsilonSpecAux {α : Sort u} (h : Nonempty α) (p : α → Prop) : (∃ y, p y) → p (@epsilon α h p) := (strongIndefiniteDescription p h).property theorem epsilonSpec {α : Sort u} {p : α → Prop} (hex : ∃ y, p y) : p (@epsilon α (nonemptyOfExists hex) p) := epsilonSpecAux (nonemptyOfExists hex) p hex theorem epsilonSingleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x := @epsilonSpec α (fun y => y = x) ⟨x, rfl⟩ /- the axiom of choice -/ theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, ∃ y, r x y) : ∃ (f : ∀ x, β x), ∀ x, r x (f x) := ⟨_, fun x => chooseSpec (h x)⟩ theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} : (∀ x, ∃ y, p x y) ↔ ∃ (f : ∀ x, b x), ∀ x, p x (f x) := ⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩ theorem propComplete (a : Prop) : a = True ∨ a = False := by cases em a with | inl _ => apply Or.inl; apply propext; apply Iff.intro; { intros; apply True.intro }; { intro; assumption } | inr hn => apply Or.inr; apply propext; apply Iff.intro; { intro h; exact hn h }; { intro h; apply False.elim h } -- this supercedes byCases in Decidable theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q := Decidable.byCases (dec := propDecidable _) hpq hnpq -- this supercedes byContradiction in Decidable theorem byContradiction {p : Prop} (h : ¬p → False) : p := Decidable.byContradiction (dec := propDecidable _) h macro "byCases" h:ident ":" e:term : tactic => `(cases em $e:term with | inl $h:ident => _ | inr $h:ident => _) end Classical
[STATEMENT] lemma (in Ring) prod_n_principal_idealTr:"e \<in> {j. j\<le>n} \<rightarrow> {j. (0::nat)\<le>j} \<and> f \<in> {j. j\<le>n} \<rightarrow> carrier R \<and> (\<forall>k \<le> n. J k = (Rxa R (f k))\<^bsup>\<diamondsuit>R (e k)\<^esup>) \<longrightarrow> ideal_n_prod R n J = Rxa R (mprod_expR R e f n)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n [PROOF STEP] apply (induct_tac n) [PROOF STATE] proof (prove) goal (2 subgoals): 1. e \<in> {j. j \<le> 0} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> 0} \<rightarrow> carrier R \<and> (\<forall>k\<le>0. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,0\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f 0 2. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (rule impI) [PROOF STATE] proof (prove) goal (2 subgoals): 1. e \<in> {j. j \<le> 0} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> 0} \<rightarrow> carrier R \<and> (\<forall>k\<le>0. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<Longrightarrow> i\<Pi>\<^bsub>R,0\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f 0 2. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (erule conjE)+ [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>e \<in> {j. j \<le> 0} \<rightarrow> {j. 0 \<le> j}; f \<in> {j. j \<le> 0} \<rightarrow> carrier R; \<forall>k\<le>0. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>\<rbrakk> \<Longrightarrow> i\<Pi>\<^bsub>R,0\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f 0 2. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (simp add:mprod_expR_def) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup> = R \<diamondsuit>\<^sub>p (f 0^\<^bsup>R e 0\<^esup>) 2. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (subgoal_tac "J 0 = R \<diamondsuit>\<^sub>p (f 0) \<^bsup>\<diamondsuit>R (e 0)\<^esup>") [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup> = R \<diamondsuit>\<^sub>p (f 0^\<^bsup>R e 0\<^esup>) 2. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup> 3. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup> = R \<diamondsuit>\<^sub>p (f 0^\<^bsup>R e 0\<^esup>) 2. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup> 3. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (rule principal_ideal_n_pow[of "f 0" "R \<diamondsuit>\<^sub>p (f 0)"]) [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> f 0 \<in> carrier R 2. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p f 0 = R \<diamondsuit>\<^sub>p f 0 3. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup> 4. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (cut_tac n_in_Nsetn[of 0], simp add:Pi_def) [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p f 0 = R \<diamondsuit>\<^sub>p f 0 2. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup> 3. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>f 0 \<in> carrier R; J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup>\<rbrakk> \<Longrightarrow> J 0 = R \<diamondsuit>\<^sub>p f 0 \<^bsup>\<diamondsuit>R e 0\<^esup> 2. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (cut_tac n_in_Nsetn[of 0], simp) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n. e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<Longrightarrow> e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R \<and> (\<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (rule impI, (erule conjE)+) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n. \<lbrakk>e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j}; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>\<rbrakk> \<Longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (frule func_pre[of "e"], frule func_pre[of "f"]) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n. \<lbrakk>e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j} \<and> f \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>k\<le>n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>) \<longrightarrow> i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; e \<in> {j. j \<le> Suc n} \<rightarrow> {j. 0 \<le> j}; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; e \<in> {j. j \<le> n} \<rightarrow> {j. 0 \<le> j}; f \<in> {j. j \<le> n} \<rightarrow> carrier R\<rbrakk> \<Longrightarrow> i\<Pi>\<^bsub>R,Suc n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f (Suc n) [PROOF STEP] apply (cut_tac n = n in Nsetn_sub_mem1, simp add:mprodR_Suc) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (mprod_expR R e f n \<cdot>\<^sub>r f (Suc n)^\<^bsup>R e (Suc n)\<^esup>) [PROOF STEP] apply (cut_tac n = "Suc n" in n_in_Nsetn, simp) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (mprod_expR R e f n \<cdot>\<^sub>r f (Suc n)^\<^bsup>R e (Suc n)\<^esup>) [PROOF STEP] apply (frule_tac A = "{j. j \<le> Suc n}" and x = "Suc n" in funcset_mem[of "f" _ "carrier R"], simp) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (mprod_expR R e f n \<cdot>\<^sub>r f (Suc n)^\<^bsup>R e (Suc n)\<^esup>) [PROOF STEP] apply (frule_tac a = "f (Suc n)" and I = "R \<diamondsuit>\<^sub>p (f (Suc n))" and n = "e (Suc n)" in principal_ideal_n_pow) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p f (Suc n) = R \<diamondsuit>\<^sub>p f (Suc n) 2. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R; R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>)\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (mprod_expR R e f n \<cdot>\<^sub>r f (Suc n)^\<^bsup>R e (Suc n)\<^esup>) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R; R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>)\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (mprod_expR R e f n \<cdot>\<^sub>r f (Suc n)^\<^bsup>R e (Suc n)\<^esup>) [PROOF STEP] apply (subst prod_principal_ideal[THEN sym]) [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R; R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>)\<rbrakk> \<Longrightarrow> mprod_expR R e f n \<in> carrier R 2. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R; R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>)\<rbrakk> \<Longrightarrow> f (Suc n)^\<^bsup>R e (Suc n)\<^esup> \<in> carrier R 3. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R; R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>)\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>) [PROOF STEP] apply (simp add:mprod_expR_mem) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R; R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>)\<rbrakk> \<Longrightarrow> f (Suc n)^\<^bsup>R e (Suc n)\<^esup> \<in> carrier R 2. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R; R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>)\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>) [PROOF STEP] apply (rule npClose, assumption+) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n. \<lbrakk>i\<Pi>\<^bsub>R,n\<^esub> J = R \<diamondsuit>\<^sub>p mprod_expR R e f n; f \<in> {j. j \<le> Suc n} \<rightarrow> carrier R; \<forall>k\<le>Suc n. J k = R \<diamondsuit>\<^sub>p f k \<^bsup>\<diamondsuit>R e k\<^esup>; f \<in> {j. j \<le> n} \<rightarrow> carrier R; f (Suc n) \<in> carrier R; R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>)\<rbrakk> \<Longrightarrow> R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p f (Suc n) \<^bsup>\<diamondsuit>R e (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p mprod_expR R e f n \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p (f (Suc n)^\<^bsup>R e (Suc n)\<^esup>) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
[STATEMENT] lemma rel_gpv''_Grp: includes lifting_syntax shows "rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> = BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h)" (is "?lhs = ?rhs") [PROOF STATE] proof (prove) goal (1 subgoal): 1. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> = BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) [PROOF STEP] proof(intro ext GrpI iffI CollectI conjI subsetI) [PROOF STATE] proof (state) goal (4 subgoals): 1. \<And>x xa. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa \<Longrightarrow> map_gpv' f g h x = xa 2. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> results_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> A 3. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> outs_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> B 4. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] let ?\<I> = "\<I>_uniform UNIV (range h)" [PROOF STATE] proof (state) goal (4 subgoals): 1. \<And>x xa. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa \<Longrightarrow> map_gpv' f g h x = xa 2. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> results_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> A 3. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> outs_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> B 4. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] fix gpv gpv' [PROOF STATE] proof (state) goal (4 subgoals): 1. \<And>x xa. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa \<Longrightarrow> map_gpv' f g h x = xa 2. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> results_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> A 3. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> outs_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> B 4. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] assume *: "?lhs gpv gpv'" [PROOF STATE] proof (state) this: rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' goal (4 subgoals): 1. \<And>x xa. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa \<Longrightarrow> map_gpv' f g h x = xa 2. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> results_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> A 3. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> outs_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> B 4. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] then [PROOF STATE] proof (chain) picking this: rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' [PROOF STEP] show "map_gpv' f g h gpv = gpv'" [PROOF STATE] proof (prove) using this: rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' goal (1 subgoal): 1. map_gpv' f g h gpv = gpv' [PROOF STEP] by(coinduction arbitrary: gpv gpv') (drule rel_gpv''D , auto 4 5 simp add: spmf_rel_map generat.rel_map elim!: rel_spmf_mono generat.rel_mono_strong GrpE intro!: GrpI dest: rel_funD) [PROOF STATE] proof (state) this: map_gpv' f g h gpv = gpv' goal (3 subgoals): 1. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> results_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> A 2. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> outs_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> B 3. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] show "x \<in> A" if "x \<in> results_gpv ?\<I> gpv" for x [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<in> A [PROOF STEP] using that * [PROOF STATE] proof (prove) using this: x \<in> results_gpv (\<I>_uniform UNIV (range h)) gpv rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' goal (1 subgoal): 1. x \<in> A [PROOF STEP] proof(induction arbitrary: gpv') [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>gpv gpv'. \<lbrakk>Pure x \<in> set_spmf (the_gpv gpv); rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A 2. \<And>out c gpv input gpv'. \<lbrakk>IO out c \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (c input) gpv' \<Longrightarrow> x \<in> A; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A [PROOF STEP] case (Pure gpv) [PROOF STATE] proof (state) this: Pure x \<in> set_spmf (the_gpv gpv) rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' goal (2 subgoals): 1. \<And>gpv gpv'. \<lbrakk>Pure x \<in> set_spmf (the_gpv gpv); rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A 2. \<And>out c gpv input gpv'. \<lbrakk>IO out c \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (c input) gpv' \<Longrightarrow> x \<in> A; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A [PROOF STEP] have "pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] using Pure.prems[THEN rel_gpv''D] [PROOF STATE] proof (prove) using this: rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>)) (the_gpv gpv) (the_gpv gpv') goal (1 subgoal): 1. pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] unfolding spmf_Domainp_rel[symmetric] [PROOF STATE] proof (prove) using this: rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>)) (the_gpv gpv) (the_gpv gpv') goal (1 subgoal): 1. Domainp (rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] .. [PROOF STATE] proof (state) this: pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) goal (2 subgoals): 1. \<And>gpv gpv'. \<lbrakk>Pure x \<in> set_spmf (the_gpv gpv); rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A 2. \<And>out c gpv input gpv'. \<lbrakk>IO out c \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (c input) gpv' \<Longrightarrow> x \<in> A; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A [PROOF STEP] with Pure.hyps [PROOF STATE] proof (chain) picking this: Pure x \<in> set_spmf (the_gpv gpv) pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: Pure x \<in> set_spmf (the_gpv gpv) pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) goal (1 subgoal): 1. x \<in> A [PROOF STEP] by(simp add: generat.Domainp_rel pred_spmf_def pred_generat_def Domainp_Grp) [PROOF STATE] proof (state) this: x \<in> A goal (1 subgoal): 1. \<And>out c gpv input gpv'. \<lbrakk>IO out c \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (c input) gpv' \<Longrightarrow> x \<in> A; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>out c gpv input gpv'. \<lbrakk>IO out c \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (c input) gpv' \<Longrightarrow> x \<in> A; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A [PROOF STEP] case (IO out c gpv input) [PROOF STATE] proof (state) this: IO out c \<in> set_spmf (the_gpv gpv) input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input) rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (c input) ?gpv'1 \<Longrightarrow> x \<in> A rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' goal (1 subgoal): 1. \<And>out c gpv input gpv'. \<lbrakk>IO out c \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (c input) gpv' \<Longrightarrow> x \<in> A; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A [PROOF STEP] have "pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] using IO.prems[THEN rel_gpv''D] [PROOF STATE] proof (prove) using this: rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>)) (the_gpv gpv) (the_gpv gpv') goal (1 subgoal): 1. pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] unfolding spmf_Domainp_rel[symmetric] [PROOF STATE] proof (prove) using this: rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>)) (the_gpv gpv) (the_gpv gpv') goal (1 subgoal): 1. Domainp (rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] by(rule DomainPI) [PROOF STATE] proof (state) this: pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) goal (1 subgoal): 1. \<And>out c gpv input gpv'. \<lbrakk>IO out c \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (c input) gpv' \<Longrightarrow> x \<in> A; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> A [PROOF STEP] with IO.hyps [PROOF STATE] proof (chain) picking this: IO out c \<in> set_spmf (the_gpv gpv) input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input) pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: IO out c \<in> set_spmf (the_gpv gpv) input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out x \<in> results_gpv (\<I>_uniform UNIV (range h)) (c input) pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) goal (1 subgoal): 1. x \<in> A [PROOF STEP] by(auto simp add: generat.Domainp_rel pred_spmf_def pred_generat_def Grp_iff dest: rel_funD intro: IO.IH dest!: bspec) [PROOF STATE] proof (state) this: x \<in> A goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: ?x1 \<in> results_gpv (\<I>_uniform UNIV (range h)) gpv \<Longrightarrow> ?x1 \<in> A goal (2 subgoals): 1. \<And>x xa xb. \<lbrakk>rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa; xb \<in> outs_gpv (\<I>_uniform UNIV (range h)) x\<rbrakk> \<Longrightarrow> xb \<in> B 2. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] show "x \<in> B" if "x \<in> outs_gpv ?\<I> gpv" for x [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<in> B [PROOF STEP] using that * [PROOF STATE] proof (prove) using this: x \<in> outs_gpv (\<I>_uniform UNIV (range h)) gpv rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' goal (1 subgoal): 1. x \<in> B [PROOF STEP] proof(induction arbitrary: gpv') [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>c gpv gpv'. \<lbrakk>IO x c \<in> set_spmf (the_gpv gpv); rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B 2. \<And>out rpv gpv input gpv'. \<lbrakk>IO out rpv \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (rpv input) gpv' \<Longrightarrow> x \<in> B; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B [PROOF STEP] case (IO c gpv) [PROOF STATE] proof (state) this: IO x c \<in> set_spmf (the_gpv gpv) rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' goal (2 subgoals): 1. \<And>c gpv gpv'. \<lbrakk>IO x c \<in> set_spmf (the_gpv gpv); rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B 2. \<And>out rpv gpv input gpv'. \<lbrakk>IO out rpv \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (rpv input) gpv' \<Longrightarrow> x \<in> B; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B [PROOF STEP] have "pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] using IO.prems[THEN rel_gpv''D] [PROOF STATE] proof (prove) using this: rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>)) (the_gpv gpv) (the_gpv gpv') goal (1 subgoal): 1. pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] unfolding spmf_Domainp_rel[symmetric] [PROOF STATE] proof (prove) using this: rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>)) (the_gpv gpv) (the_gpv gpv') goal (1 subgoal): 1. Domainp (rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] by(rule DomainPI) [PROOF STATE] proof (state) this: pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) goal (2 subgoals): 1. \<And>c gpv gpv'. \<lbrakk>IO x c \<in> set_spmf (the_gpv gpv); rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B 2. \<And>out rpv gpv input gpv'. \<lbrakk>IO out rpv \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (rpv input) gpv' \<Longrightarrow> x \<in> B; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B [PROOF STEP] with IO.hyps [PROOF STATE] proof (chain) picking this: IO x c \<in> set_spmf (the_gpv gpv) pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: IO x c \<in> set_spmf (the_gpv gpv) pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) goal (1 subgoal): 1. x \<in> B [PROOF STEP] by(simp add: generat.Domainp_rel pred_spmf_def pred_generat_def Domainp_Grp) [PROOF STATE] proof (state) this: x \<in> B goal (1 subgoal): 1. \<And>out rpv gpv input gpv'. \<lbrakk>IO out rpv \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (rpv input) gpv' \<Longrightarrow> x \<in> B; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>out rpv gpv input gpv'. \<lbrakk>IO out rpv \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (rpv input) gpv' \<Longrightarrow> x \<in> B; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B [PROOF STEP] case (Cont out rpv gpv input) [PROOF STATE] proof (state) this: IO out rpv \<in> set_spmf (the_gpv gpv) input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input) rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (rpv input) ?gpv'1 \<Longrightarrow> x \<in> B rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' goal (1 subgoal): 1. \<And>out rpv gpv input gpv'. \<lbrakk>IO out rpv \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (rpv input) gpv' \<Longrightarrow> x \<in> B; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B [PROOF STEP] have "pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] using Cont.prems[THEN rel_gpv''D] [PROOF STATE] proof (prove) using this: rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>)) (the_gpv gpv) (the_gpv gpv') goal (1 subgoal): 1. pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] unfolding spmf_Domainp_rel[symmetric] [PROOF STATE] proof (prove) using this: rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>)) (the_gpv gpv) (the_gpv gpv') goal (1 subgoal): 1. Domainp (rel_spmf (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] by(rule DomainPI) [PROOF STATE] proof (state) this: pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) goal (1 subgoal): 1. \<And>out rpv gpv input gpv'. \<lbrakk>IO out rpv \<in> set_spmf (the_gpv gpv); input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out; x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input); \<And>gpv'. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> (rpv input) gpv' \<Longrightarrow> x \<in> B; rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv'\<rbrakk> \<Longrightarrow> x \<in> B [PROOF STEP] with Cont.hyps [PROOF STATE] proof (chain) picking this: IO out rpv \<in> set_spmf (the_gpv gpv) input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input) pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: IO out rpv \<in> set_spmf (the_gpv gpv) input \<in> responses_\<I> (\<I>_uniform UNIV (range h)) out x \<in> outs_gpv (\<I>_uniform UNIV (range h)) (rpv input) pred_spmf (Domainp (rel_generat (BNF_Def.Grp A f) (BNF_Def.Grp B g) ((BNF_Def.Grp UNIV h)\<inverse>\<inverse> ===> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse>))) (the_gpv gpv) goal (1 subgoal): 1. x \<in> B [PROOF STEP] by(auto simp add: generat.Domainp_rel pred_spmf_def pred_generat_def Grp_iff dest: rel_funD intro: Cont.IH dest!: bspec) [PROOF STATE] proof (state) this: x \<in> B goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: ?x1 \<in> outs_gpv (\<I>_uniform UNIV (range h)) gpv \<Longrightarrow> ?x1 \<in> B goal (1 subgoal): 1. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] fix gpv gpv' [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] assume "?rhs gpv gpv'" [PROOF STATE] proof (state) this: BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) gpv gpv' goal (1 subgoal): 1. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] then [PROOF STATE] proof (chain) picking this: BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) gpv gpv' [PROOF STEP] have gpv': "gpv' = map_gpv' f g h gpv" and *: "results_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> A" "outs_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> B" [PROOF STATE] proof (prove) using this: BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) gpv gpv' goal (1 subgoal): 1. gpv' = map_gpv' f g h gpv &&& results_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> A &&& outs_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> B [PROOF STEP] by(auto simp add: Grp_iff) [PROOF STATE] proof (state) this: gpv' = map_gpv' f g h gpv results_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> A outs_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> B goal (1 subgoal): 1. \<And>x xa. BNF_Def.Grp {x. results_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> A \<and> outs_gpv (\<I>_uniform UNIV (range h)) x \<subseteq> B} (map_gpv' f g h) x xa \<Longrightarrow> rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> x xa [PROOF STEP] show "?lhs gpv gpv'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' [PROOF STEP] using * [PROOF STATE] proof (prove) using this: results_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> A outs_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> B goal (1 subgoal): 1. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' [PROOF STEP] unfolding gpv' [PROOF STATE] proof (prove) using this: results_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> A outs_gpv (\<I>_uniform UNIV (range h)) gpv \<subseteq> B goal (1 subgoal): 1. rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv (map_gpv' f g h gpv) [PROOF STEP] by(coinduction arbitrary: gpv) (fastforce simp add: spmf_rel_map generat.rel_map Grp_iff intro!: rel_spmf_reflI generat.rel_refl_strong rel_funI elim!: generat.set_cases intro: results_gpv.intros outs_gpv.intros) [PROOF STATE] proof (state) this: rel_gpv'' (BNF_Def.Grp A f) (BNF_Def.Grp B g) (BNF_Def.Grp UNIV h)\<inverse>\<inverse> gpv gpv' goal: No subgoals! [PROOF STEP] qed
/- 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, Johan Commelin -/ import data.polynomial.algebra_map import data.polynomial.degree.lemmas import data.polynomial.div import ring_theory.localization.fraction_ring import algebra.polynomial.big_operators /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : R[X]} section variables [semiring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.nat_degree := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) lemma mod_by_monic_eq_of_dvd_sub (hq : q.monic) {p₁ p₂ : R[X]} (h : q ∣ (p₁ - p₂)) : p₁ %ₘ q = p₂ %ₘ q := begin nontriviality R, obtain ⟨f, sub_eq⟩ := h, refine (div_mod_by_monic_unique (p₂ /ₘ q + f) _ hq ⟨_, degree_mod_by_monic_lt _ hq⟩).2, rw [sub_eq_iff_eq_add.mp sub_eq, mul_add, ← add_assoc, mod_by_monic_add_div _ hq, add_comm] end lemma add_mod_by_monic (p₁ p₂ : R[X]) : (p₁ + p₂) %ₘ q = p₁ %ₘ q + p₂ %ₘ q := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (p₁ /ₘ q + p₂ /ₘ q) _ hq ⟨by rw [mul_add, add_left_comm, add_assoc, mod_by_monic_add_div _ hq, ← add_assoc, add_comm (q * _), mod_by_monic_add_div _ hq], (degree_add_le _ _).trans_lt (max_lt (degree_mod_by_monic_lt _ hq) (degree_mod_by_monic_lt _ hq))⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end lemma smul_mod_by_monic (c : R) (p : R[X]) : (c • p) %ₘ q = c • (p %ₘ q) := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (c • (p /ₘ q)) (c • (p %ₘ q)) hq ⟨by rw [mul_smul_comm, ← smul_add, mod_by_monic_add_div p hq], (degree_smul_le _ _).trans_lt (degree_mod_by_monic_lt _ hq)⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end /-- `_ %ₘ q` as an `R`-linear map. -/ @[simps] def mod_by_monic_hom (q : R[X]) : R[X] →ₗ[R] R[X] := { to_fun := λ p, p %ₘ q, map_add' := add_mod_by_monic, map_smul' := smul_mod_by_monic } end section variables [ring S] lemma aeval_mod_by_monic_eq_self_of_root [algebra R S] {p q : R[X]} (hq : q.monic) {x : S} (hx : aeval x q = 0) : aeval x (p %ₘ q) = aeval x p := -- `eval₂_mod_by_monic_eq_self_of_root` doesn't work here as it needs commutativity by rw [mod_by_monic_eq_sub_mul_div p hq, _root_.map_sub, _root_.map_mul, hx, zero_mul, sub_zero] end end comm_ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} instance : no_zero_divisors R[X] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], refine eq_zero_or_eq_zero_of_mul_eq_zero _, rw [← leading_coeff_zero, ← leading_coeff_mul, h], end } lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul] lemma trailing_degree_mul : (p * q).trailing_degree = p.trailing_degree + q.trailing_degree := begin by_cases hp : p = 0, { rw [hp, zero_mul, trailing_degree_zero, top_add] }, by_cases hq : q = 0, { rw [hq, mul_zero, trailing_degree_zero, add_top] }, rw [trailing_degree_eq_nat_trailing_degree hp, trailing_degree_eq_nat_trailing_degree hq, trailing_degree_eq_nat_trailing_degree (mul_ne_zero hp hq), nat_trailing_degree_mul hp hq, with_top.coe_add], end @[simp] lemma nat_degree_pow (p : R[X]) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma degree_le_mul_left (p : R[X]) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : R[X]} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end /-- This lemma is useful for working with the `int_degree` of a rational function. -/ lemma nat_degree_sub_eq_of_prod_eq {p₁ p₂ q₁ q₂ : polynomial R} (hp₁ : p₁ ≠ 0) (hq₁ : q₁ ≠ 0) (hp₂ : p₂ ≠ 0) (hq₂ : q₂ ≠ 0) (h_eq : p₁ * q₂ = p₂ * q₁) : (p₁.nat_degree : ℤ) - q₁.nat_degree = (p₂.nat_degree : ℤ) - q₂.nat_degree := begin rw sub_eq_sub_iff_add_eq_add, norm_cast, rw [← nat_degree_mul hp₁ hq₂, ← nat_degree_mul hp₂ hq₁, h_eq] end end no_zero_divisors section no_zero_divisors variables [comm_semiring R] [no_zero_divisors R] {p q : R[X]} lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h end no_zero_divisors section ring variables [ring R] [is_domain R] {p q : R[X]} instance : is_domain R[X] := { ..polynomial.no_zero_divisors, ..polynomial.nontrivial, } end ring section comm_ring variables [comm_ring R] [is_domain R] {p q : R[X]} section roots open multiset lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : R[X]) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : R[X]ˣ) : degree (u : R[X]) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ theorem prime_X_sub_C (r : R) : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C r, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : R[X]) := by { convert (prime_X_sub_C (0 : R)), simp } lemma monic.prime_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, this.symm ▸ prime_X_sub_C _ theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := (prime_X_sub_C r).irreducible theorem irreducible_X : irreducible (X : R[X]) := prime.irreducible prime_X lemma monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : irreducible p := (hm.prime_of_degree_eq_one hp1).irreducible theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q := begin obtain ⟨u, hu⟩ := hpq, unfold monic at hp hq, rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu, rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq, rwa [hq, C_1, mul_one] at hu, apply_instance, end lemma root_multiplicity_mul {p q : R[X]} {x : R} (hpq : p * q ≠ 0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := begin have hp : p ≠ 0 := left_ne_zero_of_mul hpq, have hq : q ≠ 0 := right_ne_zero_of_mul hpq, rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq, root_multiplicity_eq_multiplicity p, dif_neg hp, root_multiplicity_eq_multiplicity q, dif_neg hq, multiplicity.mul' (prime_X_sub_C x)], end lemma root_multiplicity_X_sub_C_self {x : R} : root_multiplicity x (X - C x) = 1 := by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x), multiplicity.get_multiplicity_self] lemma root_multiplicity_X_sub_C {x y : R} : root_multiplicity x (X - C y) = if x = y then 1 else 0 := begin split_ifs with hxy, { rw hxy, exact root_multiplicity_X_sub_C_self }, exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy)) end /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n := begin induction n with n hn, { refine root_multiplicity_eq_zero _, simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] }, have hzero := pow_ne_zero n.succ (X_sub_C_ne_zero a), rw pow_succ (X - C a) n at hzero ⊢, simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add] end /-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at least `n`. -/ lemma root_multiplicity_of_dvd {p : R[X]} {a : R} {n : ℕ} (hzero : p ≠ 0) (h : (X - C a) ^ n ∣ p) : n ≤ root_multiplicity a p := begin obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h, rw hq at hzero, simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow, ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right], end /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ lemma root_multiplicity_add {p q : R[X]} (a : R) (hzero : p + q ≠ 0) : min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) := begin refine root_multiplicity_of_dvd hzero _, have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a, have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a, exact min_pow_dvd_add hdivp hdivq end lemma exists_multiset_roots : ∀ {p : R[X]} (hp : p ≠ 0), ∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_multiset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)).1 $ not_lt.2 hdeg, ⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 : by exact_mod_cast card_cons _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add (le_refl (1 : with_bot ℕ)) htd, begin assume a, conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx }, rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0), root_multiplicity_X_sub_C, ← htr a], split_ifs with ha, { rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] }, { rw [count_cons_of_ne ha, zero_add] }, end⟩ else ⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ noncomputable def roots (p : R[X]) : multiset R := if h : p = 0 then ∅ else classical.some (exists_multiset_roots h) @[simp] lemma roots_zero : (0 : R[X]).roots = 0 := dif_pos rfl lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_multiset_roots hp0)).1 end lemma card_roots' (p : R[X]) : p.roots.card ≤ nat_degree p := begin by_cases hp0 : p = 0, { simp [hp0], }, exact with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) end lemma card_roots_sub_C {p : R[X]} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : R[X]} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma count_roots (p : R[X]) : p.roots.count a = root_multiplicity a p := begin by_cases hp : p = 0, { simp [hp], }, rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a end @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by rw [← count_pos, count_roots p, root_multiplicity_pos hp] theorem card_le_degree_of_subset_roots {p : R[X]} {Z : finset R} (h : Z.val ⊆ p.roots) : Z.card ≤ p.nat_degree := (multiset.card_le_of_le (finset.val_le_iff_val_subset.2 h)).trans (polynomial.card_roots' p) lemma finite_set_of_is_root {p : R[X]} (hp : p ≠ 0) : set.finite {x | is_root p x} := by simpa only [← finset.set_of_mem, mem_to_finset, mem_roots hp] using p.roots.to_finset.finite_to_set lemma eq_zero_of_infinite_is_root (p : R[X]) (h : set.infinite {x | is_root p x}) : p = 0 := not_imp_comm.mp finite_set_of_is_root h lemma exists_max_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x ≤ x₀ := set.exists_upper_bound_image _ _ $ finite_set_of_is_root hp lemma exists_min_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x₀ ≤ x := set.exists_lower_bound_image _ _ $ finite_set_of_is_root hp lemma eq_of_infinite_eval_eq (p q : R[X]) (h : set.infinite {x | eval x p = eval x q}) : p = q := begin rw [← sub_eq_zero], apply eq_zero_of_infinite_is_root, simpa only [is_root, eval_sub, sub_eq_zero] end lemma roots_mul {p q : R[X]} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots := multiset.ext.mpr $ λ r, by rw [count_add, count_roots, count_roots, count_roots, root_multiplicity_mul hpq] lemma roots.le_of_dvd (h : q ≠ 0) : p ∣ q → roots p ≤ roots q := begin rintro ⟨k, rfl⟩, exact multiset.le_iff_exists_add.mpr ⟨k.roots, roots_mul h⟩ end @[simp] lemma mem_roots_sub_C {p : R[X]} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := begin ext s, rw [count_roots, root_multiplicity_X_sub_C], split_ifs with h, { rw [h, count_singleton_self] }, { rw [singleton_eq_cons, count_cons_of_ne h, count_zero] } end @[simp] lemma roots_C (x : R) : (C x).roots = 0 := if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r, by rw [count_roots, count_zero, root_multiplicity_eq_zero (not_is_root_C _ _ H)] @[simp] lemma roots_one : (1 : R[X]).roots = ∅ := roots_C 1 lemma roots_smul_nonzero (p : R[X]) {r : R} (hr : r ≠ 0) : (r • p).roots = p.roots := begin by_cases hp : p = 0; simp [smul_eq_C_mul, roots_mul, hr, hp] end lemma roots_list_prod (L : list R[X]) : ((0 : R[X]) ∉ L) → L.prod.roots = (L : multiset R[X]).bind roots := list.rec_on L (λ _, roots_one) $ λ hd tl ih H, begin rw [list.mem_cons_iff, not_or_distrib] at H, rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2), ← multiset.cons_coe, multiset.cons_bind, ih H.2] end lemma roots_multiset_prod (m : multiset R[X]) : (0 : R[X]) ∉ m → m.prod.roots = m.bind roots := by { rcases m with ⟨L⟩, simpa only [coe_prod, quot_mk_to_coe''] using roots_list_prod L } lemma roots_prod {ι : Type*} (f : ι → R[X]) (s : finset ι) : s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) := begin rcases s with ⟨m, hm⟩, simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f) end lemma roots_prod_X_sub_C (s : finset R) : (s.prod (λ a, X - C a)).roots = s.val := (roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans (by simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id']) @[simp] lemma roots_multiset_prod_X_sub_C (s : multiset R) : (s.map (λ a, X - C a)).prod.roots = s := begin rw [roots_multiset_prod, multiset.bind_map], { simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id'] }, { rw [multiset.mem_map], rintro ⟨a, -, h⟩, exact X_sub_C_ne_zero a h }, end @[simp] lemma nat_degree_multiset_prod_X_sub_C_eq_card (s : multiset R): (s.map (λ a, X - C a)).prod.nat_degree = s.card := begin rw [nat_degree_multiset_prod_of_monic, multiset.map_map], { convert multiset.sum_repeat 1 _, { convert multiset.map_const _ 1, ext, apply nat_degree_X_sub_C }, { simp } }, { intros f hf, obtain ⟨a, ha, rfl⟩ := multiset.mem_map.1 hf, exact monic_X_sub_C a }, end lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : R[X]) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : R[X]) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : R[X]) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a section variables {A B : Type*} [comm_ring A] [comm_ring B] lemma le_root_multiplicity_map {p : A[X]} {f : A →+* B} (hmap : map f p ≠ 0) (a : A) : root_multiplicity a p ≤ root_multiplicity (f a) (map f p) := begin have hp0 : p ≠ 0 := λ h, hmap (h.symm ▸ polynomial.map_zero f), rw [root_multiplicity, root_multiplicity, dif_neg hp0, dif_neg hmap], simp only [not_not, nat.lt_find_iff, nat.le_find_iff], intros m hm, have := (map_ring_hom f).map_dvd (hm m le_rfl), simpa only [coe_map_ring_hom, map_pow, map_sub, map_X, map_C], end lemma eq_root_multiplicity_map {p : A[X]} {f : A →+* B} (hf : function.injective f) (a : A) : root_multiplicity a p = root_multiplicity (f a) (map f p) := begin by_cases hp0 : p = 0, { simp only [hp0, root_multiplicity_zero, polynomial.map_zero], }, have hmap : map f p ≠ 0, { simpa only [polynomial.map_zero] using (map_injective f hf).ne hp0, }, apply le_antisymm (le_root_multiplicity_map hmap a), rw [root_multiplicity, root_multiplicity, dif_neg hp0, dif_neg hmap], simp only [not_not, nat.lt_find_iff, nat.le_find_iff], intros m hm, rw ← map_dvd_map f hf ((monic_X_sub_C a).pow _), convert hm m le_rfl, simp only [polynomial.map_pow, polynomial.map_sub, map_pow, map_sub, map_X, map_C], end lemma count_map_roots [is_domain A] (p : A[X]) {f : A →+* B} (hf : function.injective f) (a : B) : count a (p.roots.map f) ≤ root_multiplicity a (map f p) := begin by_cases h : ∃ t, f t = a, { rcases h with ⟨h_w, rfl⟩, rw [multiset.count_map_eq_count' f _ hf, count_roots], exact (eq_root_multiplicity_map hf h_w).le }, { suffices : (multiset.map f p.roots).count a = 0, { rw this, exact zero_le _, }, rw [multiset.count_map, multiset.card_eq_zero, multiset.filter_eq_nil], rintro k hk rfl, exact h ⟨k, rfl⟩, }, end lemma roots_map_of_injective_card_eq_total_degree [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (hf : function.injective f) (hroots : p.roots.card = p.nat_degree) : p.roots.map f = (map f p).roots := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, multiset.map_zero, polynomial.map_zero], }, have hmap : map f p ≠ 0, { simpa only [polynomial.map_zero] using (map_injective f hf).ne hp0, }, apply multiset.eq_of_le_of_card_le, { simpa only [multiset.le_iff_count, count_roots] using count_map_roots p hf }, { simpa only [multiset.card_map, hroots] using (card_roots' _).trans (nat_degree_map_le f p) }, end end section nth_roots /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots (n : ℕ) (a : R) : multiset R := roots ((X : R[X]) ^ n - C a) @[simp] lemma mem_nth_roots {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero] @[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 := by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C] lemma card_nth_roots (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : R[X]) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by { rw [hn, pow_zero, ← C_1, ← ring_hom.map_sub ], exact degree_C_le })) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : finset R := multiset.to_finset (nth_roots n (1 : R)) @[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 := by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h] @[simp] lemma nth_roots_finset_zero : nth_roots_finset 0 R = ∅ := by simp [nth_roots_finset] end nth_roots lemma monic.comp (hp : p.monic) (hq : q.monic) (h : q.nat_degree ≠ 0) : (p.comp q).monic := by rw [monic.def, leading_coeff_comp h, monic.def.1 hp, monic.def.1 hq, one_pow, one_mul] lemma monic.comp_X_add_C (hp : p.monic) (r : R) : (p.comp (X + C r)).monic := begin refine hp.comp (monic_X_add_C _) (λ ha, _), rw [nat_degree_X_add_C] at ha, exact one_ne_zero ha end lemma monic.comp_X_sub_C (hp : p.monic) (r : R) : (p.comp (X - C r)).monic := by simpa using hp.comp_X_add_C (-r) @[simp] lemma nat_degree_coe_units (u : R[X]ˣ) : nat_degree (u : R[X]) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma comp_eq_zero_iff : p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) := begin split, { intro h, have key : p.nat_degree = 0 ∨ q.nat_degree = 0, { rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] }, replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key, cases key, { rw [key, C_comp] at h, exact or.inl (key.trans h) }, { rw [key, comp_C, C_eq_zero] at h, exact or.inr ⟨h, key⟩ }, }, { exact λ h, or.rec (λ h, by rw [h, zero_comp]) (λ h, by rw [h.2, comp_C, h.1, C_0]) h }, end lemma zero_of_eval_zero [infinite R] (p : R[X]) (h : ∀ x, p.eval x = 0) : p = 0 := by classical; by_contradiction hp; exact fintype.false ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩ lemma funext [infinite R] {p q : R[X]} (ext : ∀ r : R, p.eval r = q.eval r) : p = q := begin rw ← sub_eq_zero, apply zero_of_eval_zero, intro x, rw [eval_sub, sub_eq_zero, ext], end variables [comm_ring T] /-- The set of distinct roots of `p` in `E`. If you have a non-separable polynomial, use `polynomial.roots` for the multiset where multiple roots have the appropriate multiplicity. -/ def root_set (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : set S := (p.map (algebra_map T S)).roots.to_finset lemma root_set_def (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : p.root_set S = (p.map (algebra_map T S)).roots.to_finset := rfl @[simp] lemma root_set_zero (S) [comm_ring S] [is_domain S] [algebra T S] : (0 : T[X]).root_set S = ∅ := by rw [root_set_def, polynomial.map_zero, roots_zero, to_finset_zero, finset.coe_empty] @[simp] lemma root_set_C [comm_ring S] [is_domain S] [algebra T S] (a : T) : (C a).root_set S = ∅ := by rw [root_set_def, map_C, roots_C, multiset.to_finset_zero, finset.coe_empty] instance root_set_fintype (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : fintype (p.root_set S) := finset_coe.fintype _ lemma root_set_finite (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : (p.root_set S).finite := set.finite_of_fintype _ theorem mem_root_set_iff' {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] (hp : p.map (algebra_map T S) ≠ 0) (a : S) : a ∈ p.root_set S ↔ (p.map (algebra_map T S)).eval a = 0 := by { change a ∈ multiset.to_finset _ ↔ _, rw [mem_to_finset, mem_roots hp], refl } theorem mem_root_set_iff {p : T[X]} (hp : p ≠ 0) {S : Type*} [comm_ring S] [is_domain S] [algebra T S] [no_zero_smul_divisors T S] (a : S) : a ∈ p.root_set S ↔ aeval a p = 0 := begin rw [mem_root_set_iff', ←eval₂_eq_eval_map], { refl }, intro h, rw ←polynomial.map_zero (algebra_map T S) at h, exact hp (map_injective _ (no_zero_smul_divisors.algebra_map_injective T S) h) end end roots theorem is_unit_iff {f : R[X]} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f := ⟨λ hf, ⟨f.coeff 0, is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf, (eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩, λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩ lemma coeff_coe_units_zero_ne_zero (u : R[X]ˣ) : coeff (u : R[X]) 0 ≠ 0 := begin conv in (0) { rw [← nat_degree_coe_units u] }, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.is_unit_or_is_unit hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) /-- Division by a monic polynomial doesn't change the leading coefficient. -/ lemma leading_coeff_div_by_monic_of_monic {R : Type u} [comm_ring R] {p q : R[X]} (hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff := begin nontriviality, have h : q.leading_coeff * (p /ₘ q).leading_coeff ≠ 0, { simpa [div_by_monic_eq_zero_iff hmonic, hmonic.leading_coeff, nat.with_bot.one_le_iff_zero_lt] using hdegree }, nth_rewrite_rhs 0 ←mod_by_monic_add_div p hmonic, rw [leading_coeff_add_of_degree_lt, leading_coeff_monic_mul hmonic], rw [degree_mul' h, degree_add_div_by_monic hmonic hdegree], exact (degree_mod_by_monic_lt p hmonic).trans_le hdegree end lemma leading_coeff_div_by_monic_X_sub_C (p : R[X]) (hp : degree p ≠ 0) (a : R) : leading_coeff (p /ₘ (X - C a)) = leading_coeff p := begin nontriviality, cases hp.lt_or_lt with hd hd, { rw [degree_eq_bot.mp $ (nat.with_bot.lt_zero_iff _).mp hd, zero_div_by_monic] }, refine leading_coeff_div_by_monic_of_monic (monic_X_sub_C a) _, rwa [degree_X_sub_C, nat.with_bot.one_le_iff_zero_lt] end lemma eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = C q.leading_coeff * p := begin obtain ⟨r, hr⟩ := hdiv, obtain (rfl|hq) := eq_or_ne q 0, {simp}, have rzero : r ≠ 0 := λ h, by simpa [h, hq] using hr, rw [hr, nat_degree_mul'] at hdeg, swap, { rw [hp.leading_coeff, one_mul, leading_coeff_ne_zero], exact rzero }, rw [mul_comm, @eq_C_of_nat_degree_eq_zero _ _ r] at hr, { convert hr, convert leading_coeff_C _ using 1, rw [hr, leading_coeff_mul_monic hp] }, { exact (add_right_inj _).1 (le_antisymm hdeg $ nat.le.intro rfl) }, end lemma eq_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = p := begin convert eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le hp hdiv hdeg, rw [hq.leading_coeff, C_1, one_mul], end lemma is_coprime_X_sub_C_of_is_unit_sub {R} [comm_ring R] {a b : R} (h : is_unit (a - b)) : is_coprime (X - C a) (X - C b) := ⟨-C h.unit⁻¹.val, C h.unit⁻¹.val, by { rw [neg_mul_comm, ← left_distrib, neg_add_eq_sub, sub_sub_sub_cancel_left, ← C_sub, ← C_mul], convert C_1, exact h.coe_inv_mul }⟩ theorem pairwise_coprime_X_sub_C {K} [field K] {I : Type v} {s : I → K} (H : function.injective s) : pairwise (is_coprime on (λ i : I, X - C (s i))) := λ i j hij, is_coprime_X_sub_C_of_is_unit_sub (sub_ne_zero_of_ne $ H.ne hij).is_unit lemma monic_prod_multiset_X_sub_C : monic (p.roots.map (λ a, X - C a)).prod := monic_multiset_prod_of_monic _ _ (λ a _, monic_X_sub_C a) lemma prod_multiset_root_eq_finset_root : (p.roots.map (λ a, X - C a)).prod = p.roots.to_finset.prod (λ a, (X - C a) ^ root_multiplicity a p) := by simp only [count_roots, finset.prod_multiset_map_count] /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : R[X]) : (p.roots.map (λ a, X - C a)).prod ∣ p := begin rw ← map_dvd_map _ (is_fraction_ring.injective R $ fraction_ring R) monic_prod_multiset_X_sub_C, rw [prod_multiset_root_eq_finset_root, polynomial.map_prod], refine finset.prod_dvd_of_coprime (λ a _ b _ h, _) (λ a _, _), { simp_rw [polynomial.map_pow, polynomial.map_sub, map_C, map_X], exact (pairwise_coprime_X_sub_C (is_fraction_ring.injective R $ fraction_ring R) _ _ h).pow }, { exact polynomial.map_dvd _ (pow_root_multiplicity_dvd p a) }, end lemma exists_prod_multiset_X_sub_C_mul (p : R[X]) : ∃ q, (p.roots.map (λ a, X - C a)).prod * q = p ∧ p.roots.card + q.nat_degree = p.nat_degree ∧ q.roots = 0 := begin obtain ⟨q, he⟩ := prod_multiset_X_sub_C_dvd p, use [q, he.symm], obtain (rfl|hq) := eq_or_ne q 0, { rw mul_zero at he, subst he, simp }, split, { conv_rhs { rw he }, rw [monic_prod_multiset_X_sub_C.nat_degree_mul' hq, nat_degree_multiset_prod_X_sub_C_eq_card] }, { replace he := congr_arg roots he.symm, rw [roots_mul, roots_multiset_prod_X_sub_C] at he, exacts [add_right_eq_self.1 he, mul_ne_zero monic_prod_multiset_X_sub_C.ne_zero hq] }, end /-- A polynomial `p` that has as many roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C (hroots : p.roots.card = p.nat_degree) : C p.leading_coeff * (p.roots.map (λ a, X - C a)).prod = p := (eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le monic_prod_multiset_X_sub_C (prod_multiset_X_sub_C_dvd p) $ ((nat_degree_multiset_prod_X_sub_C_eq_card _).trans hroots).ge).symm /-- A monic polynomial `p` that has as many roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq (hp : p.monic) (hroots : p.roots.card = p.nat_degree) : (p.roots.map (λ a, X - C a)).prod = p := by { convert C_leading_coeff_mul_prod_multiset_X_sub_C hroots, rw [hp.leading_coeff, C_1, one_mul] } end comm_ring section variables [semiring R] [comm_ring S] [is_domain S] (φ : R →+* S) lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map {f : R[X]} (hf : is_unit f.leading_coeff) (H : is_unit (map φ f)) : is_unit f := begin have dz := degree_eq_zero_of_is_unit H, rw degree_map_eq_of_leading_coeff_ne_zero at dz, { rw eq_C_of_degree_eq_zero dz, refine is_unit.map C _, convert hf, rw (degree_eq_iff_nat_degree_eq _).1 dz, rintro rfl, simpa using H, }, { intro h, have u : is_unit (φ f.leading_coeff) := is_unit.map φ hf, rw h at u, simpa using u, } end end section variables [comm_ring R] [is_domain R] [comm_ring S] [is_domain S] (φ : R →+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ lemma monic.irreducible_of_irreducible_map (f : R[X]) (h_mon : monic f) (h_irr : irreducible (map φ f)) : irreducible f := begin refine ⟨h_irr.not_unit ∘ is_unit.map (map_ring_hom φ), λ a b h, _⟩, dsimp [monic] at h_mon, have q := (leading_coeff_mul a b).symm, rw [←h, h_mon] at q, refine (h_irr.is_unit_or_is_unit $ (congr_arg (map φ) h).trans (polynomial.map_mul φ)).imp _ _; apply is_unit_of_is_unit_leading_coeff_of_is_unit_map; apply is_unit_of_mul_eq_one, { exact q }, { rw mul_comm, exact q }, end end end polynomial
% Copyright (C) 1993-2017, by Peter I. Corke % % This file is part of The Robotics Toolbox for MATLAB (RTB). % % RTB is free software: you can redistribute it and/or modify % it under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % RTB 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 Lesser General Public License for more details. % % You should have received a copy of the GNU Leser General Public License % along with RTB. If not, see <http://www.gnu.org/licenses/>. % % http://www.petercorke.com theta = linspace(-pi, pi, 75); [Q2,Q3] = meshgrid(theta, theta); for i=1:numcols(Q2), for j=1:numcols(Q3); g = p560.gravload([0 Q2(i,j) Q3(i,j) 0 0 0]); g2(i,j) = g(2); g3(i,j) = g(3); end end surfl(Q2, Q3, g2); surfl(Q2, Q3, g3);
(****************************************************************************) (* Copyright 2020 The Project Oak Authors *) (* *) (* 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. *) (****************************************************************************) From Coq Require Import Bool.Bvector. From Coq Require Import NArith.Ndigits. From Coq Require Import ZArith. Require Import Omega Lia. Require Import Vector. (* An n-bit adder *) Local Open Scope N_scope. Definition vectorAdd {aWidth bWidth: nat} (cWidth: nat) (a: Bvector aWidth) (b: Bvector bWidth) : Bvector cWidth := let aN := Bv2N aWidth a in let bN := Bv2N bWidth b in let c := (aN + bN) mod 2^(N.of_nat cWidth) in N2Bv_sized cWidth c. Compute Bv2N (vectorAdd 8 (N2Bv_sized 8 5) (N2Bv_sized 8 12)). Compute Bv2N (vectorAdd 8 (N2Bv_sized 8 5) (N2Bv_sized 8 254)). Definition vectorAddGrowth {width: nat} (a: Bvector width) (b: Bvector width) : Bvector (1 + width) := let aN : N := Bv2N width a in let bN : N := Bv2N width b in let c : N := aN + bN in N2Bv_sized (1 + width) c. Definition vectorAdd4Growth {width: nat} (a: Bvector width) (b: Bvector width) (c: Bvector width) (d: Bvector width) : Bvector (2 + width) := let a_plus_b := vectorAddGrowth a b in let c_plus_d := vectorAddGrowth c d in vectorAddGrowth a_plus_b c_plus_d. Definition vectorAddGrowth2 {aWidth bWidth: nat} (a: Bvector aWidth) (b: Bvector bWidth) : Bvector (1 + max aWidth bWidth) := let aN : N := Bv2N aWidth a in let bN : N := Bv2N bWidth b in let c : N := aN + bN in N2Bv_sized (1 + max aWidth bWidth) c. Definition vectorAdd3Growth {aWidth bWidth cWidth: nat} (a: Bvector aWidth) (b: Bvector bWidth) (c: Bvector cWidth) : Bvector (1 + max (1 + max aWidth bWidth) cWidth) := let a_plus_b := vectorAddGrowth2 a b in vectorAddGrowth2 a_plus_b c. Local Open Scope vector_scope. Lemma bv_p_0 : forall n, Bvector (n + 0) = Bvector n . intros. f_equal. omega. Qed. Lemma v_p_0 : forall n T, Vector.t T (n + 0) = Vector.t T n . intros. f_equal. omega. Qed. Lemma bv_p_1 : forall a b, Bvector (a + S b) = Bvector (1 + (a + b)) . intros. f_equal. omega. Qed. Fixpoint adderTree {n w} (i: Vector.t (Bvector w) (2^n)) : Bvector (w + n). destruct n. - rewrite bv_p_0. exact (hd i). - refine ( let (a, b) := splitat (2 ^ n) i in _). rewrite v_p_0 in b. fold Nat.pow in b. refine ( let lhs := adderTree n _ a in let rhs := adderTree n _ b in _ ). rewrite bv_p_1. exact ( vectorAddGrowth lhs rhs ). Defined. Definition i0 : Bvector 8 := N2Bv_sized 8. Definition v0 : Vector.t (Bvector 8) 1 := [i0]. Compute adderTree v0.
(*** * Oqarina * Copyright 2021 Carnegie Mellon University. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR * IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF * FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS * OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT * MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, * TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * Released under a BSD (SEI)-style license, please see license.txt or * contact [email protected] for full terms. * * [DISTRIBUTION STATEMENT A] This material has been approved for public * release and unlimited distribution. Please see Copyright notice for * non-US Government use and distribution. * * This Software includes and/or makes use of the following Third-Party * Software subject to its own license: * * 1. Coq theorem prover (https://github.com/coq/coq/blob/master/LICENSE) * Copyright 2021 INRIA. * * 2. Coq JSON (https://github.com/liyishuai/coq-json/blob/comrade/LICENSE) * Copyright 2021 Yishuai Li. * * DM21-0762 ***) (*| .. coq:: none |*) (* Coq Library *) Require Import List. Import ListNotations. (* from List *) Require Import Coq.Relations.Relation_Definitions. Require Import Coq.Relations.Relation_Operators. Require Import Coq.Unicode.Utf8. Require Import Coq.Bool.Bool. Require Import Floats. Open Scope float_scope. (* Oqarina Library*) Require Import Oqarina.coq_utils.all. Require Import Oqarina.core.all. Require Import Oqarina.formalisms.FaultTrees.AbstractFaultTree. Require Import Oqarina.formalisms.FaultTrees.Merle_Algebra. Require Import Oqarina.formalisms.Expressions.Propositions. Set Implicit Arguments. Set Strict Implicit. (*| .. coq:: |*) (*| ******************* Dynamic Fault Trees ******************* In the following, we use the fornulation of Dynamic Fault Tree from :cite:t:`merle:tel-00502012`. One critical aspect is that this formulation assumes that events are non-repairable and that basic events are statistically independent. In addition, the NOT gate cannot be defined. |*) Section Dynamic_Fault_Tree. (*| .. coq:: |*) Variable basic_event : Set. Hypothesis basic_event_eq_dec : forall x y : basic_event, { x = y } + { x <> y }. Definition valid_dynamic_fault_tree_node (n : FT_Node basic_event) (l : list (fault_tree basic_event)) : Prop := match n with | INVALID _ => False | BASIC _ => l = [] | K_OUT_OF_N _ k => k <= (List.length l) | FDEP _ => True | SPARE _ => (List.length l) = 3%nat | PAND _ => True | AND _ | OR _ => True | NOT _ => False (* Cannot be defined using Merle's algebra *) end. Lemma valid_dynamic_fault_tree_node_dec: forall (n : FT_Node basic_event) (l : list (fault_tree basic_event)), { valid_dynamic_fault_tree_node n l } + { ~ valid_dynamic_fault_tree_node n l }. Proof. prove_dec. apply List.list_eq_dec, ltree_eq_dec, FT_Node_eq_dec. apply basic_event_eq_dec. apply PeanoNat.Nat.eq_dec. apply Compare_dec.le_dec. Qed. Definition valid_dynamic_fault_tree (dft : fault_tree basic_event) := ltree_fall valid_dynamic_fault_tree_node dft. Lemma valid_dynamic_fault_tree_dec: forall (dft : fault_tree basic_event), { valid_dynamic_fault_tree dft } + { ~ valid_dynamic_fault_tree dft }. Proof. apply ltree_fall_dec. apply valid_dynamic_fault_tree_node_dec. Qed. (*| Dynamic fault tree evaluation ============================== In this section, we build Dynamic Fault Tree, using Merle's Algebra operators for the fault tree evaluation :cite:t:`merle:tel-00502012`. |*) Definition d' : Set := Merle_Algebra.d basic_event. #[global] Instance Merle_Basic_Event_Operators : Basic_Event_Operators d' := { T := d_0 basic_event ; F := d_inf basic_event ; b_AND := D_AND basic_event ; b_ANDl := n_AND basic_event ; b_OR := D_OR basic_event ; b_ORl := n_OR basic_event ; b_NOT := fun x => d_inf basic_event ; b_PANDl := (fun x => Some (n_PAND basic_event x)); }. #[global] Instance Merle_Basic_Event_Operators_Facts : Basic_Event_Operators_Facts Merle_Basic_Event_Operators := { b_ANDl_singleton := Theorem_4 basic_event ; b_ANDl_concatenate := Theorem_8' basic_event ; b_ORl_concatenate := Theorem_9' basic_event ; }. Definition DFT := fault_tree d'. (*| From these definitions, one can directly built a fault tree, check it is correct, and evaluate it. |*) Example Basic_DFT : DFT := ltree_cons (PAND d') [ ltree_cons (BASIC (d_0 basic_event)) [] ; ltree_cons (BASIC (d_0 basic_event)) []]. (* Fact Basic_DFT_OK : valid_dynamic_fault_tree Basic_DFT. Proof. prove_valid_fault_tree. Qed. *) (*| .. coq:: none |*) (*| .. coq:: |*) (*| .. coq:: none |*) End Dynamic_Fault_Tree.
############# # This demonstrates the Triangle harmonic transform and inverse transform, # explaining precisely the normalization and points # # Note we use the duffy map # x == (s+1)/2 # y== (t+1)/2*(1-(s+1)/2) ############# using ApproxFun, FastTransforms jacobinorm(n,a,b) = if n ≠ 0 sqrt((2n+a+b+1))*exp((lgamma(n+a+b+1)+lgamma(n+1)-log(2)*(a+b+1)-lgamma(n+a+1)-lgamma(n+b+1))/2) else sqrt(exp(lgamma(a+b+2)-log(2)*(a+b+1)-lgamma(a+1)-lgamma(b+1))) end njacobip(n,a,b,x) = jacobinorm(n,a,b) * jacobip(n,a,b,x) P = (ℓ,m,x,y) -> (2*(1-x))^m*njacobip(ℓ-m,2m,0,2x-1)*njacobip(m,-0.5,-0.5,2y/(1-x)-1) p_T = chebyshevpoints(40) f = (x,y) -> exp(x + cos(y)) f̃ = (s,t) -> f((s+1)/2, (t+1)/2*(1-(s+1)/2)) F = f̃.(p_T, p_T') for j = 1:size(F,2) F[:,j] = chebyshevtransform(F[:,j]) end for k = 1:size(F,1) F[k,:] = chebyshevtransform(F[k,:]) end F̌ = cheb2tri(F, 0.0, -0.5, -0.5) f̃ = function(x,y) ret = 0.0 for j=1:size(F,2), k=1:size(F,1)-j+1 ret += F̌[k,j] * P(k+j-2,j-1,x,y) end ret end f̃(0.1,0.2) ≈ f(0.1,0.2)
#include <gsl/gsl_rng.h> #include <easy_rng.h> #include <time.h> #ifndef NRUNS #define NRUNS 10000000 #endif void run_test(const gsl_rng_type *gtype, const easy_rng_type *etype) { gsl_rng *grng = gsl_rng_alloc(gtype); easy_rng *erng = easy_rng_alloc(etype); clock_t gstart, gend; clock_t estart, eend; int i; gstart = clock(); for (i = 0 ; i < NRUNS ; i++) gsl_rng_get(grng); gend = clock(); estart = clock(); for (i = 0 ; i < NRUNS ; i++) easy_rng_get(erng); eend = clock(); gsl_rng_free(grng); easy_rng_free(erng); fprintf(stdout, "Comparing easyRNG's %s with GSL's %s\n", etype->name, gtype->name); fprintf(stdout, "easyRNG %g\n", ((double) (eend - estart))/CLOCKS_PER_SEC); fprintf(stdout, "GSL %g\n", ((double) (gend - gstart))/CLOCKS_PER_SEC); } int main(int argc, char *argv[]) { run_test(gsl_rng_mt19937, easy_rng_mt19937); run_test(gsl_rng_ranlux, easy_rng_ranlux24); run_test(gsl_rng_ranlux389, easy_rng_ranlux48); run_test(gsl_rng_minstd, easy_rng_minstd_rand0); run_test(gsl_rng_fishman20, easy_rng_minstd_rand); return 0; }
#ifndef BLUB_PROCEDURAL_VOXEL_EDIT_MESH_HPP #define BLUB_PROCEDURAL_VOXEL_EDIT_MESH_HPP #include "blub/log/global.hpp" #include "blub/core/map.hpp" #include "blub/core/pair.hpp" #include "blub/core/sharedPointer.hpp" #include "blub/core/vector.hpp" #include "blub/math/axisAlignedBox.hpp" #include "blub/math/intersection.hpp" #include "blub/math/plane.hpp" #include "blub/math/ray.hpp" #include "blub/math/transform.hpp" #include "blub/math/triangleVector3.hpp" #include "blub/procedural/voxel/edit/base.hpp" #include "blub/procedural/voxel/tile/container.hpp" #include <utility> #ifdef BLUB_USE_ASSIMP #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/material.h> #include <assimp/mesh.h> #include <assimp/scene.h> #endif #include <boost/geometry.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/geometry/index/rtree.hpp> namespace blub { namespace procedural { namespace voxel { namespace edit { /** * @brief convertes a mesh to voxel. Fills a boost::geometry::index::rtree with the polygons. * Initialization O(numTriangles). Voxel-generation O(numVoxel) */ template <class voxelType> class mesh : public base<voxelType> { public: typedef sharedPointer<mesh<voxelType> > pointer; typedef base<voxelType> t_base; typedef tile::container<voxelType> t_tileContainer; typedef boost::geometry::model::point<real, 3, boost::geometry::cs::cartesian> t_point; typedef boost::geometry::model::box<t_point> t_box; typedef boost::geometry::model::segment<t_point> t_segment; typedef std::pair<t_box, triangleVector3> t_value; typedef boost::geometry::index::rtree<t_value, boost::geometry::index::quadratic<16> > t_tree; /** * @brief creates an instance of the class. * @return a shared_ptr of an instance */ static pointer create() { return pointer(new mesh()); } /** * @brief ~mesh destructor */ virtual ~mesh() { for (t_trees::const_iterator it = m_trees.cbegin(); it != m_trees.cend(); ++it) { delete (*it); } } #ifdef BLUB_USE_ASSIMP /** * @brief loads an assimp scence from path * @param path has to be a valid path. Relative or absolute. * @return true if successfully read and loaded */ bool load(const blub::string &path, const blub::transform &trans) { Assimp::Importer* importer(new Assimp::Importer()); const aiScene *scene = importer->ReadFile(path.c_str(), aiProcess_Triangulate); if (scene == nullptr) { BLUB_PROCEDURAL_LOG_ERROR() << "scene == nullptr loader->GetErrorString():" << importer->GetErrorString(); delete importer; return false; } bool result(loadScene(*scene, trans)); delete importer; return result; } /** * @brief loads an assimp scene * @param scene Scene to load * @return true if successfully loaded */ virtual bool loadScene(const aiScene &scene, const blub::transform &trans) { if (!scene.HasMeshes()) { BLUB_PROCEDURAL_LOG_ERROR() << "!scene.HasMeshes()"; return false; } #ifdef BLUB_LOG_PROCEDURAL_VOXEL_EDIT_MESH BLUB_LOG_OUT() << "scene.mNumMeshes:" << scene.mNumMeshes << " scene.mRootNode->mNumChildren:" << scene.mRootNode->mNumChildren; #endif for(uint32 indMesh = 0; indMesh < scene.mNumMeshes; ++indMesh) { aiMesh *mesh(scene.mMeshes[indMesh]); loadMesh(*mesh, trans); // ignore result } return true; } /** * @brief loads an assimp mesh * @param mesh Mesh to load * @return true if successfully loaded */ virtual bool loadMesh(const aiMesh &mesh, const blub::transform &trans) { typedef vector<vector3> t_positions; #ifdef BLUB_LOG_PROCEDURAL_VOXEL_EDIT_MESH BLUB_PROCEDURAL_LOG_OUT() << "mesh.mName:" << blub::string(mesh.mName.C_Str(), mesh.mName.length); #endif if (!mesh.HasFaces()) { BLUB_PROCEDURAL_LOG_ERROR() << "!scene.mMeshes[indMesh]->HasFaces()"; return false; } if (!mesh.HasPositions()) { BLUB_PROCEDURAL_LOG_ERROR() << "!mesh.HasPositions()"; return false; } t_tree *tree = new t_tree(); m_trees.push_back(tree); t_positions positions; positions.resize(mesh.mNumVertices); for (blub::uint32 indVertex = 0; indVertex < mesh.mNumVertices; ++indVertex) { const aiVector3D &posToCast(mesh.mVertices[indVertex]); vector3 casted(posToCast.x, posToCast.y, posToCast.z); casted *= trans.scale; positions[indVertex] = casted; m_aabb.merge(casted); } for (blub::uint32 indFace = 0; indFace < mesh.mNumFaces; ++indFace) { const aiFace &faceToCast(mesh.mFaces[indFace]); BASSERT(faceToCast.mNumIndices == 3); if (faceToCast.mNumIndices != 3) { BLUB_PROCEDURAL_LOG_WARNING() << "faceToCast.mNumIndices != 3"; continue; } const triangleVector3 resultTriangle( positions[faceToCast.mIndices[0]], positions[faceToCast.mIndices[1]], positions[faceToCast.mIndices[2]]); const blub::axisAlignedBox &aabb(resultTriangle.getAxisAlignedBoundingBox()); const blub::vector3 &aabbMin(aabb.getMinimum()); const blub::vector3 &aabbMax(aabb.getMaximum()); t_box toInsert(t_point(aabbMin.x, aabbMin.y, aabbMin.z), t_point(aabbMax.x, aabbMax.y, aabbMax.z)); tree->insert(std::make_pair(toInsert, resultTriangle)); } return !tree->empty(); } #endif protected: /** * @brief mesh contructor */ mesh() { } /** * @brief getAxisAlignedBoundingBox returns the transformed bounding box that includes the mesh. * @param trans Transform of edit * @return */ blub::axisAlignedBox getAxisAlignedBoundingBox(const transform &trans) const override { BLUB_LOG_OUT() << "trans:" << trans; return blub::axisAlignedBox(m_aabb.getMinimum()*trans.scale + trans.position, m_aabb.getMaximum()*trans.scale + trans.position); } /** * @brief calculateVoxel The tree, which got generated in load() gets intersected for every voxel line. * @param voxelContainer Container where to set the voxel in. * @param voxelContainerOffset Absolut position of the voxelContainer. * @param trans Transform */ void calculateVoxel(t_tileContainer *voxelContainer, const vector3int32 &voxelContainerOffset, const transform &/*trans*/) const { const vector3int32 posContainerAbsolut(voxelContainerOffset*t_tileContainer::voxelLength); vector3int32 toLoop[] = {{1, t_tileContainer::voxelLength, t_tileContainer::voxelLength}, {t_tileContainer::voxelLength, 1, t_tileContainer::voxelLength}, {t_tileContainer::voxelLength, t_tileContainer::voxelLength, 1} }; vector3 rayDir[] = {{1., 0., 0.}, {0., 1., 0.}, {0., 0., 1.}}; for (uint32 indMesh = 0; indMesh < m_trees.size(); ++indMesh) { t_tree *tree(static_cast<t_tree*>(m_trees[indMesh])); for (int32 indAxis = 0; indAxis < 3; ++indAxis) { for (int32 indX = 0; indX < toLoop[indAxis].x; ++indX) { for (int32 indY = 0; indY < toLoop[indAxis].y; ++indY) { for (int32 indZ = 0; indZ < toLoop[indAxis].z; ++indZ) { const vector3int32 posVoxel(indX, indY, indZ); vector3 posAbsolut(posContainerAbsolut + posVoxel); // posAbsolut = posAbsolut / trans.scale; // posAbsolut -= trans.position; const ray test(posAbsolut, rayDir[indAxis]); const vector3 segmentStart (posAbsolut+rayDir[indAxis]*(-10000.)); // TODO: fix me after ray support for boost::geometry is of their todolist const vector3 segmentEnd (posAbsolut+rayDir[indAxis]*(+10000.)); t_segment segment(t_point(segmentStart.x, segmentStart.y, segmentStart.z), t_point(segmentEnd.x, segmentEnd.y, segmentEnd.z)); typedef std::vector<t_value> t_resultTriangles; t_resultTriangles resultTriangles; tree->query(boost::geometry::index::intersects(segment), std::back_inserter(resultTriangles)); typedef pair<real, blub::plane> t_cutPoint; typedef vector<t_cutPoint> t_cutPoints; t_cutPoints cutPoints; vector3 cutPoint; for (t_resultTriangles::const_iterator it = resultTriangles.cbegin(); it != resultTriangles.cend(); ++it) { const triangleVector3 &triangleWork(it->second); if (intersection::intersect(test, triangleWork, &cutPoint)) { bool insert(true); // if (!cutPoints.empty()) // { // const plane planeTriBefore(cutPoints.at(cutPoints.size()-1).second); // if (/*math::abs*/(planeTriBefore.normal.dotProduct(triangleWork.getPlane().normal)) < 0.) // { // insert = false; // } // } if (insert) { real cutPointStart = cutPoint[indAxis] - static_cast<real>(posContainerAbsolut[indAxis]); cutPoints.push_back(t_cutPoint(cutPointStart, triangleWork.getPlane())); } } } if(cutPoints.size() < 2) { continue; } typedef vector<t_cutPoint> t_cutPointsFiltered; t_cutPointsFiltered cutPointsFiltered; for (t_cutPoints::const_iterator it = cutPoints.cbegin(); it != cutPoints.cend(); ++it) { if (cutPointsFiltered.empty()) { cutPointsFiltered.push_back(*it); continue; } if (math::abs(cutPointsFiltered.back().first - it->first) < 1e-4f) { continue; } cutPointsFiltered.push_back(*it); } if(cutPointsFiltered.size()%2 != 0 && cutPointsFiltered.size() > 0) { BLUB_PROCEDURAL_LOG_WARNING() << "cutPointsFiltered.size()%2 != 0 cutPointsFiltered.size():" << cutPointsFiltered.size(); cutPointsFiltered.pop_back(); } for (t_cutPointsFiltered::const_iterator it = cutPointsFiltered.cbegin(); it != cutPointsFiltered.cend(); ++it) { real cutPointsSorted[2]; blub::plane cutPlanes[2]; cutPointsSorted[0] = it->first; cutPlanes[0] = it->second; ++it; BASSERT(it != cutPointsFiltered.cend()); cutPointsSorted[1] = it->first; cutPlanes[1] = it->second; const real length(cutPointsSorted[1]-cutPointsSorted[0]); if (length < 1.) { #ifdef BLUB_LOG_PROCEDURAL_VOXEL_EDIT_MESH // blub::BOUT("length < 1."); #endif // continue; } //BLUB_LOG_OUT() << "creating line length:" << length; switch (indAxis) { case 0: t_base::createLine(voxelContainer, posVoxel, cutPointsSorted[0], length, t_base::axis::x, cutPlanes[0], cutPlanes[1]); break; case 1: t_base::createLine(voxelContainer, posVoxel, cutPointsSorted[0], length, t_base::axis::y, cutPlanes[0], cutPlanes[1]); break; case 2: t_base::createLine(voxelContainer, posVoxel, cutPointsSorted[0], length, t_base::axis::z, cutPlanes[0], cutPlanes[1]); break; default: BASSERT(false); break; } } } } } } } } protected: typedef vector<t_tree*> t_trees; t_trees m_trees; blub::axisAlignedBox m_aabb; }; } } } } #endif // BLUB_PROCEDURAL_VOXEL_EDIT_MESH_HPP
(* This file is developed by Qinxiang Cao, Aquinas Hobor and Shengyi Wang in 2015. *) Require Export veric.base. Require Import veric.tycontext. Require Import veric.expr2. Lemma range_overlap_spec: forall l1 n1 l2 n2, n1 > 0 -> n2 > 0 -> (range_overlap l1 n1 l2 n2 <-> adr_range l1 n1 l2 \/ adr_range l2 n2 l1). Proof. intros. unfold range_overlap, adr_range. destruct l1, l2. split; intros. + destruct H1 as [[? ?] [[? ?] [? ?]]]. subst. destruct (zle z z0); [left | right]. - split; auto. omega. - split; auto. omega. + destruct H1 as [[? ?] | [? ?]]. - exists (b0, z0). repeat split; auto; omega. - exists (b, z). repeat split; auto; omega. Qed. Lemma range_overlap_comm: forall l1 n1 l2 n2, range_overlap l1 n1 l2 n2 -> range_overlap l2 n2 l1 n1. Proof. unfold range_overlap. intros. destruct H as [l ?]. exists l. tauto. Qed. Lemma range_overlap_non_zero: forall l1 n1 l2 n2, range_overlap l1 n1 l2 n2 -> n1 > 0 /\ n2 > 0. Proof. unfold range_overlap. intros. destruct H as [l [? ?]]. apply adr_range_non_zero in H. apply adr_range_non_zero in H0. auto. Qed. Definition pointer_range_overlap p n p' n' := exists l l', val2adr p l /\ val2adr p' l' /\ range_overlap l n l' n'. Lemma pointer_range_overlap_dec: forall p1 n1 p2 n2, {pointer_range_overlap p1 n1 p2 n2} + {~ pointer_range_overlap p1 n1 p2 n2}. Proof. unfold pointer_range_overlap. intros. destruct p1; try solve [right; intros [[? ?] [[? ?] [HH [_ _]]]]; inversion HH]. destruct p2; try solve [right; intros [[? ?] [[? ?] [_ [HH _]]]]; inversion HH]. destruct (zlt 0 n1); [| right; intros [[? ?] [[? ?] [_ [_ HH]]]]; apply range_overlap_non_zero in HH; omega]. destruct (zlt 0 n2); [| right; intros [[? ?] [[? ?] [_ [_ HH]]]]; apply range_overlap_non_zero in HH; omega]. destruct (Clight_lemmas.block_eq_dec b b0). + subst b0. unfold val2adr. forget (Int.unsigned i) as i1; forget (Int.unsigned i0) as i2; clear i i0. destruct (range_dec i1 i2 (i1 + n1)); [| destruct (range_dec i2 i1 (i2 + n2))]. - left. exists (b, i1), (b, i2); repeat split; auto. apply range_overlap_spec; try omega. left; simpl; auto. - left. exists (b, i1), (b, i2); repeat split; auto. apply range_overlap_spec; try omega. right; simpl; auto. - right. intros [[? ?] [[? ?] [? [? HH]]]]. inversion H; inversion H0; subst. apply range_overlap_spec in HH; [| omega | omega]. simpl in HH; omega. + right. intros [[? ?] [[? ?] [? [? HH]]]]. simpl in H, H0. inversion H; inversion H0; subst. apply range_overlap_spec in HH; [| omega | omega]. simpl in HH. pose proof @eq_sym _ b0 b. tauto. Qed. Lemma pointer_range_overlap_refl: forall p n1 n2, isptr p -> n1 > 0 -> n2 > 0 -> pointer_range_overlap p n1 p n2. Proof. intros. destruct p; try inversion H. exists (b, Int.unsigned i), (b, Int.unsigned i). repeat split; auto. apply range_overlap_spec; auto. left. simpl. split; auto; omega. Qed. Lemma pointer_range_overlap_comm: forall p1 n1 p2 n2, pointer_range_overlap p1 n1 p2 n2 <-> pointer_range_overlap p2 n2 p1 n1. Proof. cut (forall p1 n1 p2 n2, pointer_range_overlap p1 n1 p2 n2 -> pointer_range_overlap p2 n2 p1 n1). Focus 1. { intros. pose proof H p1 n1 p2 n2. pose proof H p2 n2 p1 n1. tauto. } Unfocus. unfold pointer_range_overlap. intros. destruct H as [l [l' [? [? ?]]]]. exists l', l. repeat split; auto. apply range_overlap_comm. auto. Qed. Lemma pointer_range_overlap_non_zero: forall p1 n1 p2 n2, pointer_range_overlap p1 n1 p2 n2 -> n1 > 0 /\ n2 > 0. Proof. intros. destruct H as [? [? [? [? ?]]]]. eapply range_overlap_non_zero; eauto. Qed. Lemma pointer_range_overlap_isptr: forall p1 n1 p2 n2, pointer_range_overlap p1 n1 p2 n2 -> isptr p1 /\ isptr p2. Proof. intros. destruct H as [? [? [? [? ?]]]]. destruct p1, p2; try solve [inversion H | inversion H0]. simpl; auto. Qed.
# Copyright 2021 Sony Semiconductors Israel, Inc. All rights reserved. # # 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 tensorflow as tf from tests.keras_tests.fw_hw_model_keras import get_quantization_disabled_keras_hw_model if tf.__version__ < "2.6": from tensorflow.python.keras.engine.functional import Functional from tensorflow.python.keras.engine.sequential import Sequential else: from keras.models import Functional, Sequential import model_compression_toolkit as mct import tensorflow as tf from tests.keras_tests.feature_networks_tests.base_keras_feature_test import BaseKerasFeatureNetworkTest import numpy as np from tests.common_tests.helpers.tensors_compare import cosine_similarity keras = tf.keras layers = keras.layers class NestedTest(BaseKerasFeatureNetworkTest): def __init__(self, unit_test, is_inner_functional=True): self.is_inner_functional = is_inner_functional super().__init__(unit_test, input_shape=(16,16,3)) def get_fw_hw_model(self): return get_quantization_disabled_keras_hw_model("nested_test") # Dummy model to test reader's recursively model parsing def dummy_model(self, input_shape): inputs = layers.Input(shape=input_shape[1:]) x = layers.Conv2D(3, 4)(inputs) x = layers.BatchNormalization()(x) outputs = layers.Activation('swish')(x) return keras.Model(inputs=inputs, outputs=outputs) def inner_functional_model(self, input_shape): inputs = layers.Input(shape=input_shape[1:]) x = layers.Conv2D(3, 4)(inputs) x = self.dummy_model(x.shape)(x) x = layers.BatchNormalization()(x) outputs = layers.Activation('swish')(x) return keras.Model(inputs=inputs, outputs=outputs) def inner_sequential_model(self, input_shape): model = keras.models.Sequential() model.add(layers.Conv2D(3, 4, input_shape=input_shape[1:])) model.add(layers.BatchNormalization()) model.add(layers.Activation('swish')) return model def create_networks(self): inputs = layers.Input(shape=self.get_input_shapes()[0][1:]) x = layers.Conv2D(3, 4)(inputs) x = layers.BatchNormalization()(x) x = layers.Activation('relu')(x) if self.is_inner_functional: x = self.inner_functional_model(x.shape)(x) else: x = self.inner_sequential_model(x.shape)(x) model = keras.Model(inputs=inputs, outputs=x) return model def compare(self, quantized_model, float_model, input_x=None, quantization_info=None): for l in quantized_model.layers: if hasattr(l, 'layer'): self.unit_test.assertFalse(isinstance(l.layer, Functional) or isinstance(l.layer, Sequential)) else: self.unit_test.assertFalse(isinstance(l, Functional) or isinstance(l, Sequential)) if self.is_inner_functional: num_layers = 8 else: num_layers = 5 self.unit_test.assertTrue(len(quantized_model.layers) == num_layers) y = float_model.predict(input_x) y_hat = quantized_model.predict(input_x) cs = cosine_similarity(y, y_hat) self.unit_test.assertTrue(np.isclose(cs, 1), msg=f'fail cosine similarity check:{cs}')
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.local_extr import Mathlib.analysis.calculus.deriv import Mathlib.PostPort universes u namespace Mathlib /-! # Local extrema of smooth functions ## Main definitions In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`. This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields. This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize [Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or [Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions). ## Main statements For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`, and `(f)deriv` instead of `has_fderiv`. * `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`. * `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both `y` and `-y` belong to the positive tangent cone, then `f' y = 0`. * `is_local_max.has_fderiv_at_eq_zero` : [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)), the derivative of a differentiable function at a local extremum point equals zero. * `exists_has_deriv_at_eq_zero` : [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`. ## Implementation notes For each mathematical fact we prove several versions of its formalization: * for maxima and minima; * using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`. For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions. ## References * [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)); * [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem); * [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone); ## Tags local extremum, Fermat's Theorem, Rolle's Theorem -/ /-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at` is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at` as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/ def pos_tangent_cone_at {E : Type u} [normed_group E] [normed_space ℝ E] (s : set E) (x : E) : set E := set_of fun (y : E) => ∃ (c : ℕ → ℝ), ∃ (d : ℕ → E), filter.eventually (fun (n : ℕ) => x + d n ∈ s) filter.at_top ∧ filter.tendsto c filter.at_top filter.at_top ∧ filter.tendsto (fun (n : ℕ) => c n • d n) filter.at_top (nhds y) theorem pos_tangent_cone_at_mono {E : Type u} [normed_group E] [normed_space ℝ E] {a : E} : monotone fun (s : set E) => pos_tangent_cone_at s a := sorry theorem mem_pos_tangent_cone_at_of_segment_subset {E : Type u} [normed_group E] [normed_space ℝ E] {s : set E} {x : E} {y : E} (h : segment x y ⊆ s) : y - x ∈ pos_tangent_cone_at s x := sorry theorem pos_tangent_cone_at_univ {E : Type u} [normed_group E] [normed_space ℝ E] {a : E} : pos_tangent_cone_at set.univ a = set.univ := sorry /-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ theorem is_local_max_on.has_fderiv_within_at_nonpos {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) : coe_fn f' y ≤ 0 := sorry /-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ theorem is_local_max_on.fderiv_within_nonpos {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {s : set E} (h : is_local_max_on f s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) : coe_fn (fderiv_within ℝ f s a) y ≤ 0 := sorry /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ theorem is_local_max_on.has_fderiv_within_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : coe_fn f' y = 0 := sorry /-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ theorem is_local_max_on.fderiv_within_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {s : set E} (h : is_local_max_on f s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : coe_fn (fderiv_within ℝ f s a) y = 0 := sorry /-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ theorem is_local_min_on.has_fderiv_within_at_nonneg {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≤ coe_fn f' y := sorry /-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ theorem is_local_min_on.fderiv_within_nonneg {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {s : set E} (h : is_local_min_on f s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≤ coe_fn (fderiv_within ℝ f s a) y := sorry /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ theorem is_local_min_on.has_fderiv_within_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : coe_fn f' y = 0 := sorry /-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ theorem is_local_min_on.fderiv_within_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {s : set E} (h : is_local_min_on f s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : coe_fn (fderiv_within ℝ f s a) y = 0 := sorry /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ theorem is_local_min.has_fderiv_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} (h : is_local_min f a) (hf : has_fderiv_at f f' a) : f' = 0 := sorry /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ theorem is_local_min.fderiv_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} (h : is_local_min f a) : fderiv ℝ f a = 0 := dite (differentiable_at ℝ f a) (fun (hf : differentiable_at ℝ f a) => is_local_min.has_fderiv_at_eq_zero h (differentiable_at.has_fderiv_at hf)) fun (hf : ¬differentiable_at ℝ f a) => fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ theorem is_local_max.has_fderiv_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} (h : is_local_max f a) (hf : has_fderiv_at f f' a) : f' = 0 := iff.mp neg_eq_zero (is_local_min.has_fderiv_at_eq_zero (is_local_max.neg h) (has_fderiv_at.neg hf)) /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ theorem is_local_max.fderiv_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} (h : is_local_max f a) : fderiv ℝ f a = 0 := dite (differentiable_at ℝ f a) (fun (hf : differentiable_at ℝ f a) => is_local_max.has_fderiv_at_eq_zero h (differentiable_at.has_fderiv_at hf)) fun (hf : ¬differentiable_at ℝ f a) => fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ theorem is_local_extr.has_fderiv_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} (h : is_local_extr f a) : has_fderiv_at f f' a → f' = 0 := is_local_extr.elim h is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ theorem is_local_extr.fderiv_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} (h : is_local_extr f a) : fderiv ℝ f a = 0 := is_local_extr.elim h is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ theorem is_local_min.has_deriv_at_eq_zero {f : ℝ → ℝ} {f' : ℝ} {a : ℝ} (h : is_local_min f a) (hf : has_deriv_at f f' a) : f' = 0 := sorry /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ theorem is_local_min.deriv_eq_zero {f : ℝ → ℝ} {a : ℝ} (h : is_local_min f a) : deriv f a = 0 := dite (differentiable_at ℝ f a) (fun (hf : differentiable_at ℝ f a) => is_local_min.has_deriv_at_eq_zero h (differentiable_at.has_deriv_at hf)) fun (hf : ¬differentiable_at ℝ f a) => deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ theorem is_local_max.has_deriv_at_eq_zero {f : ℝ → ℝ} {f' : ℝ} {a : ℝ} (h : is_local_max f a) (hf : has_deriv_at f f' a) : f' = 0 := iff.mp neg_eq_zero (is_local_min.has_deriv_at_eq_zero (is_local_max.neg h) (has_deriv_at.neg hf)) /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ theorem is_local_max.deriv_eq_zero {f : ℝ → ℝ} {a : ℝ} (h : is_local_max f a) : deriv f a = 0 := dite (differentiable_at ℝ f a) (fun (hf : differentiable_at ℝ f a) => is_local_max.has_deriv_at_eq_zero h (differentiable_at.has_deriv_at hf)) fun (hf : ¬differentiable_at ℝ f a) => deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ theorem is_local_extr.has_deriv_at_eq_zero {f : ℝ → ℝ} {f' : ℝ} {a : ℝ} (h : is_local_extr f a) : has_deriv_at f f' a → f' = 0 := is_local_extr.elim h is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ theorem is_local_extr.deriv_eq_zero {f : ℝ → ℝ} {a : ℝ} (h : is_local_extr f a) : deriv f a = 0 := is_local_extr.elim h is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero /-- A continuous function on a closed interval with `f a = f b` takes either its maximum or its minimum value at a point in the interior of the interval. -/ theorem exists_Ioo_extr_on_Icc (f : ℝ → ℝ) {a : ℝ} {b : ℝ} (hab : a < b) (hfc : continuous_on f (set.Icc a b)) (hfI : f a = f b) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), is_extr_on f (set.Icc a b) c := sorry /-- A continuous function on a closed interval with `f a = f b` has a local extremum at some point of the corresponding open interval. -/ theorem exists_local_extr_Ioo (f : ℝ → ℝ) {a : ℝ} {b : ℝ} (hab : a < b) (hfc : continuous_on f (set.Icc a b)) (hfI : f a = f b) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), is_local_extr f c := sorry /-- Rolle's Theorem `has_deriv_at` version -/ theorem exists_has_deriv_at_eq_zero (f : ℝ → ℝ) (f' : ℝ → ℝ) {a : ℝ} {b : ℝ} (hab : a < b) (hfc : continuous_on f (set.Icc a b)) (hfI : f a = f b) (hff' : ∀ (x : ℝ), x ∈ set.Ioo a b → has_deriv_at f (f' x) x) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), f' c = 0 := sorry /-- Rolle's Theorem `deriv` version -/ theorem exists_deriv_eq_zero (f : ℝ → ℝ) {a : ℝ} {b : ℝ} (hab : a < b) (hfc : continuous_on f (set.Icc a b)) (hfI : f a = f b) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), deriv f c = 0 := sorry theorem exists_has_deriv_at_eq_zero' {f : ℝ → ℝ} {f' : ℝ → ℝ} {a : ℝ} {b : ℝ} (hab : a < b) {l : ℝ} (hfa : filter.tendsto f (nhds_within a (set.Ioi a)) (nhds l)) (hfb : filter.tendsto f (nhds_within b (set.Iio b)) (nhds l)) (hff' : ∀ (x : ℝ), x ∈ set.Ioo a b → has_deriv_at f (f' x) x) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), f' c = 0 := sorry theorem exists_deriv_eq_zero' {f : ℝ → ℝ} {a : ℝ} {b : ℝ} (hab : a < b) {l : ℝ} (hfa : filter.tendsto f (nhds_within a (set.Ioi a)) (nhds l)) (hfb : filter.tendsto f (nhds_within b (set.Iio b)) (nhds l)) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), deriv f c = 0 := sorry
PROGRAM PGKEX03 C C Use inquiry functions to implement a subroutine (DRWTXT below) C that puts out text using Normalized Device Coordinates (NDC) C for positioning. Invoke Autograph to draw a linear/log plot C and then call DRWTXT two times to label the Autograph plot. C C Define the error file, the Fortran unit number, the workstation type, C and the workstation ID to be used in calls to GKS routines. C C PARAMETER (IERRF=6, LUNIT=2, IWTYPE=1, IWKID=1) ! NCGM C PARAMETER (IERRF=6, LUNIT=2, IWTYPE=8, IWKID=1) ! X Windows C PARAMETER (IERRF=6, LUNIT=2, IWTYPE=11, IWKID=1) ! PDF C PARAMETER (IERRF=6, LUNIT=2, IWTYPE=20, IWKID=1) ! PostScript C PARAMETER (IERRF=6, LUNIT=2, IWTYPE=1, IWKID=1) DIMENSION X(100),Y(100) C C Open GKS, open and activate a workstation. C CALL GOPKS (IERRF, ISZDUM) CALL GOPWK (IWKID, LUNIT, IWTYPE) CALL GACWK (IWKID) C C Define a small color table. C CALL GSCR(IWKID,0,1.,1.,1.) CALL GSCR(IWKID,1,0.,0.,1.) CALL GSCR(IWKID,2,1.,0.,0.) C C Generate a straight line with 100 points. C DO 1 I=1,100 X(I) = I Y(I) = 10.*I 1 CONTINUE C C Use SET to define normalization transformation 1 with linear C scaling in the X direction and log scaling in the Y direction. C CALL SET(.15,.85,.15,.85,1.,100.,10.,1000.,2) C C Set line color to red. C CALL GSPLCI(2) C C Initialize the AUTOGRAPH entry EZXY so that the frame is not C advanced and the Y axis is logarithmic. Turn off axis labels. C CALL DISPLA(2,0,2) CALL ANOTAT(' ',' ',0,0,0,0) C C Output the polyline (X,Y) using EZXY. C CALL EZXY(X,Y,100,' ') C C Put out a couple of labels (DRWTXT uses NDC space). C CALL DRWTXT(.50,.07,'The X axis is linear',-7,.025,0.) CALL DRWTXT(.07,.50,'The Y axis is log',-7,.025,90.) C C Terminate the picture, deactivate and close the CGM workstation, C and close GKS. C CALL FRAME CALL GDAWK(IWKID) CALL GCLWK(IWKID) CALL GCLKS C STOP END SUBROUTINE DRWTXT(X,Y,TXT,IFNT,CHGT,ANG) C C This subroutine draws the text string in TXT at position (X,Y) using C font IFNT with character height CHGT (specified in NDC) and text C angle ANG degrees. The position (X,Y) is in NDC. This subroutine C is isolated from any GKS attribute settings in the calling program C by using inquiry functions to save all settings on entry and restore C all settings on exit. The text is aligned as (center, half) and is C drawn in the foreground color. C INTEGER ERRIND DIMENSION CLRECT(4) CHARACTER*(*) TXT DATA PI /3.1415927/ C C Inquire and save the state of all attributes that will be used in C this subroutine. These will be restored on exit. C C Clipping CALL GQCLIP(ERRIND,ICLIPO,CLRECT) C C Character up vector. CALL GQCHUP(ERRIND,CHUPXO,CHUPYO) C C Text alignment. CALL GQTXAL(ERRIND,ILNHO,ILNVO) C C Text font. CALL GQTXFP(ERRIND,ITXFO,ITXPO) C C Character height. CALL GQCHH(ERRIND,CHHO) C C Get and save the existing normalization transformation information, C including the log scaling parameter.. C CALL GETSET(XV1,XV2,YV1,YV2,XW1,XW2,YW1,YW2,LS) C C Use NDC space for drawing TXT. C CALL GSELNT(0) C C Define the text font. C CALL GSTXFP(IFNT,2) C C Set the character height. C CALL GSCHH(CHGT) C C Set the text alignment to (center, half). C CALL GSTXAL(2,3) C C Select the foreground color. C CALL GSTXCI(1) C C Define the character up vector in accordance with ANG (recall that C the up vector is perpendicular to the text path). C RANG = (ANG+90.)*(2.*PI/360.) CALL GSCHUP(COS(RANG),SIN(RANG)) C C Draw the text string in TXT. C CALL GTX(X,Y,TXT) C C Restore the original normalization transformation. C CALL SET(XV1,XV2,YV1,YV2,XW1,XW2,YW1,YW2,LS) C C Restore all other attributes. C CALL GSCLIP(ICLIPO) CALL GSCHUP(CHUPXO,CHUPYO) CALL GSTXAL(ILNHO,ILNVO) CALL GSTXFP(ITXFO,ITXPO) CALL GSCHH (CHHO) C RETURN END
Require Import ReflParam.common. Require Import ReflParam.templateCoqMisc. Require Import String. Require Import List. Require Import Template.Ast. Require Import SquiggleEq.terms. Require Import ReflParam.paramDirect ReflParam.indType. Require Import SquiggleEq.substitution. Require Import ReflParam.PiTypeR. Import ListNotations. Open Scope string_scope. Inductive multInd (A I : Set) (B: I-> Set) (f: A-> I) (g: forall i, B i) : forall (i:I) (b:B i), Set := mlind : forall a, multInd A I B f g (f a) (g (f a)). Require Import SquiggleEq.UsefulTypes. (* (fun (A A₂ : Set) (A_R : A -> A₂ -> Prop) (I I₂ : Set) (I_R : I -> I₂ -> Prop) (B : I -> Set) (B₂ : I₂ -> Set) (B_R : forall (H : I) (H0 : I₂), I_R H H0 -> B H -> B₂ H0 -> Prop) (f : A -> I) (f₂ : A₂ -> I₂) (f_R : forall (H : A) (H0 : A₂), A_R H H0 -> I_R (f H) (f₂ H0)) (g : forall i : I, B i) (g₂ : forall i₂ : I₂, B₂ i₂) (g_R : forall (i : I) (i₂ : I₂) (i_R : I_R i i₂), B_R i i₂ i_R (g i) (g₂ i₂)) (a : A) (a₂ : A₂) (i_R : I_R (f a) (f₂ a₂)) (b_R : B_R (f a) (f₂ a₂) i_R (g (f a)) (g₂ (f₂ a₂))) (sigt_R : {a_R : A_R a a₂ & Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R}) (retTyp_R : forall (i_R0 : I_R (f a) (f₂ a₂)) (b_R0 : B_R (f a) (f₂ a₂) i_R0 (g (f a)) (g₂ (f₂ a₂))), {a_R : A_R a a₂ & Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0} -> Set) (rett_R : forall a_R : A_R a a₂, retTyp_R (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) (existT (fun a_R0 : A_R a a₂ => Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R0) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))) a_R (Top_multIndices2_multInd_pmtcty_RR0_indicesc A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))))) => sigT_rec (fun sigt_R0 : {a_R : A_R a a₂ & Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R} => retTyp_R i_R b_R sigt_R0) (fun a_R : A_R a a₂ => match sigt_R in (Top_multIndices2_multInd_pmtcty_RR0_indices _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ i_R0 b_R0) return (fun sigt_R1 : Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0 => retTyp_R i_R0 b_R0 (existT (fun a_R0 : A_R a a₂ => Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R0) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) i_R0 b_R0) a_R sigt_R1)) with | Top_multIndices2_multInd_pmtcty_RR0_indicesc _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ => rett_R a_R end)) *) Run TemplateProgram (genParamInd [] true true "Top.multIndices2.multInd"). (* (fix Top_multIndices2_multInd_pmtcty_RR0 (A A₂ : Set) (A_R : A -> A₂ -> Prop) (I I₂ : Set) (I_R : I -> I₂ -> Prop) (B : I -> Set) (B₂ : I₂ -> Set) (B_R : forall (H : I) (H0 : I₂), I_R H H0 -> B H -> B₂ H0 -> Prop) (f : A -> I) (f₂ : A₂ -> I₂) (f_R : forall (H : A) (H0 : A₂), A_R H H0 -> I_R (f H) (f₂ H0)) (g : forall i : I, B i) (g₂ : forall i₂ : I₂, B₂ i₂) (g_R : forall (i : I) (i₂ : I₂) (i_R : I_R i i₂), B_R i i₂ i_R (g i) (g₂ i₂)) (i : I) (i₂ : I₂) (i_R : I_R i i₂) (b : B i) (b₂ : B₂ i₂) (b_R : B_R i i₂ i_R b b₂) (H : multInd A I B f g i b) (H0 : multInd A₂ I₂ B₂ f₂ g₂ i₂ b₂) {struct H} : Prop := match H in (multInd _ _ _ _ _ i0 b0) return (forall i_R0 : I_R i0 i₂, B_R i0 i₂ i_R0 b0 b₂ -> Prop) with | mlind _ _ _ _ _ a => match H0 in (multInd _ _ _ _ _ i₂0 b₂0) return (forall i_R0 : I_R (f a) i₂0, B_R (f a) i₂0 i_R0 (g (f a)) b₂0 -> Prop) with | mlind _ _ _ _ _ a₂ => fun (i_R0 : I_R (f a) (f₂ a₂)) (b_R0 : B_R (f a) (f₂ a₂) i_R0 (g (f a)) (g₂ (f₂ a₂))) => {a_R : A_R a a₂ & Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0} end end i_R b_R) (fun (A A₂ : Set) (A_R : A -> A₂ -> Prop) (I I₂ : Set) (I_R : I -> I₂ -> Prop) (B : I -> Set) (B₂ : I₂ -> Set) (B_R : forall (H : I) (H0 : I₂), I_R H H0 -> B H -> B₂ H0 -> Prop) (f : A -> I) (f₂ : A₂ -> I₂) (f_R : forall (H : A) (H0 : A₂), A_R H H0 -> I_R (f H) (f₂ H0)) (g : forall i : I, B i) (g₂ : forall i₂ : I₂, B₂ i₂) (g_R : forall (i : I) (i₂ : I₂) (i_R : I_R i i₂), B_R i i₂ i_R (g i) (g₂ i₂)) (a : A) (a₂ : A₂) (i_R : I_R (f a) (f₂ a₂)) (b_R : B_R (f a) (f₂ a₂) i_R (g (f a)) (g₂ (f₂ a₂))) (sigt_R : {a_R : A_R a a₂ & Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R}) (retTyp_R : forall (i_R0 : I_R (f a) (f₂ a₂)) (b_R0 : B_R (f a) (f₂ a₂) i_R0 (g (f a)) (g₂ (f₂ a₂))), {a_R : A_R a a₂ & Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0} -> Set) (rett_R : forall a_R : A_R a a₂, retTyp_R (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) (existT (fun a_R0 : A_R a a₂ => Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R0) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))) a_R (Top_multIndices2_multInd_pmtcty_RR0_indicesc A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))))) => sigT_rec (fun sigt_R0 : {a_R : A_R a a₂ & Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R} => retTyp_R i_R b_R sigt_R0) (fun (a_R : A_R a a₂) (sigt_R0 : Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R) => match sigt_R0 as sigt_R1 in (Top_multIndices2_multInd_pmtcty_RR0_indices _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ i_R0 b_R0) return (retTyp_R i_R0 b_R0 (existT (fun a_R0 : A_R a a₂ => Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R0) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) i_R0 b_R0) a_R sigt_R1)) with | Top_multIndices2_multInd_pmtcty_RR0_indicesc _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ => rett_R a_R end) sigt_R) (fun (A A₂ : Set) (A_R : A -> A₂ -> Prop) (I I₂ : Set) (I_R : I -> I₂ -> Prop) (B : I -> Set) (B₂ : I₂ -> Set) (B_R : forall (H : I) (H0 : I₂), I_R H H0 -> B H -> B₂ H0 -> Prop) (f : A -> I) (f₂ : A₂ -> I₂) (f_R : forall (H : A) (H0 : A₂), A_R H H0 -> I_R (f H) (f₂ H0)) (g : forall i : I, B i) (g₂ : forall i₂ : I₂, B₂ i₂) (g_R : forall (i : I) (i₂ : I₂) (i_R : I_R i i₂), B_R i i₂ i_R (g i) (g₂ i₂)) (a : A) (a₂ : A₂) (a_R : A_R a a₂) => existT (fun a_R0 : A_R a a₂ => Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R0) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))) a_R (Top_multIndices2_multInd_pmtcty_RR0_indicesc A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)))) *) Print multInd_rect. Print nat_rect. Definition multInd_recs := fun (A I : Set) (B : I -> Set) (f : A -> I) (g : forall i : I, B i) (P : forall (i : I) (b : B i), multInd A I B f g i b -> Set) (ff : forall a : A, P (f a) (g (f a)) (mlind A I B f g a)) (i : I) (a : B i) (m : multInd A I B f g i a) => match m as m0 in (multInd _ _ _ _ _ i0 a0) return (P i0 a0 m0) with | mlind _ _ _ _ _ x => ff x end. (* Parametricity Recursive multInd_recs. *) Notation multInd_RR:=Top_multIndices2_multInd_pmtcty_RR0. SearchAbout multInd. Definition mlind_RR : forall (A₁ A₂ : Set) (A_R : A₁ -> A₂ -> Prop) (I₁ I₂ : Set) (I_R : I₁ -> I₂ -> Prop) (B₁ : I₁ -> Set) (B₂ : I₂ -> Set) (B_R : forall (H : I₁) (H0 : I₂), I_R H H0 -> B₁ H -> B₂ H0 -> Prop) (f₁ : A₁ -> I₁) (f₂ : A₂ -> I₂) (f_R : forall (H : A₁) (H0 : A₂), A_R H H0 -> I_R (f₁ H) (f₂ H0)) (g₁ : forall i : I₁, B₁ i) (g₂ : forall i : I₂, B₂ i) (g_R : forall (i₁ : I₁) (i₂ : I₂) (i_R : I_R i₁ i₂), B_R i₁ i₂ i_R (g₁ i₁) (g₂ i₂)) (a₁ : A₁) (a₂ : A₂) (a_R : A_R a₁ a₂), multInd_RR A₁ A₂ A_R I₁ I₂ I_R B₁ B₂ B_R f₁ f₂ f_R g₁ g₂ g_R (f₁ a₁) (f₂ a₂) (f_R a₁ a₂ a_R) (g₁ (f₁ a₁)) (g₂ (f₂ a₂)) (g_R (f₁ a₁) (f₂ a₂) (f_R a₁ a₂ a_R)) (mlind A₁ I₁ B₁ f₁ g₁ a₁) (mlind A₂ I₂ B₂ f₂ g₂ a₂):= Top_multIndices2_multInd_pmtcty_RR0_constr_0. Run TemplateProgram (mkIndEnv "indTransEnv" ["Top.multIndices2.multInd"]). Run TemplateProgram (genParam indTransEnv false true "multInd_recs"). (* success!*) Definition mutInd_CRRinv (A A₂ : Set) (A_R : A -> A₂ -> Prop) (I I₂ : Set) (I_R : I -> I₂ -> Prop) (B : I -> Set) (B₂ : I₂ -> Set) (B_R : forall (H : I) (H0 : I₂), I_R H H0 -> B H -> B₂ H0 -> Prop) (f : A -> I) (f₂ : A₂ -> I₂) (f_R : forall (H : A) (H0 : A₂), A_R H H0 -> I_R (f H) (f₂ H0)) (g : forall i : I, B i) (g₂ : forall i₂ : I₂, B₂ i₂) (g_R : forall (i : I) (i₂ : I₂) (i_R : I_R i i₂), B_R i i₂ i_R (g i) (g₂ i₂)) (a : A) (a₂ : A₂) (i_R : I_R (f a) (f₂ a₂)) (b_R : B_R (f a) (f₂ a₂) i_R (g (f a)) (g₂ (f₂ a₂))) (sigt_R : {a_R : A_R a a₂ & Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R}) (retTyp_R : forall (i_R0 : I_R (f a) (f₂ a₂)) (b_R0 : B_R (f a) (f₂ a₂) i_R0 (g (f a)) (g₂ (f₂ a₂))), {a_R : A_R a a₂ & Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0} -> Set) (ff : forall a_R : A_R a a₂, retTyp_R (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) (existT (fun a_R0 : A_R a a₂ => Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R0) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))) a_R (Top_multIndices2_multInd_pmtcty_RR0_indicesc A A₂ A_R I I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))))) : (retTyp_R i_R b_R sigt_R). Proof. Show Proof. revert sigt_R. Show Proof. apply sigT_rec. Show Proof. Arguments sigT_rec : clear implicits. Show Proof. intros a_R. intros peq. destruct peq. exact (ff a_R). Print sigT_rec. Defined. Arguments existT {A} {P} x p. Arguments sigT_rec {A} {P} P0 f s. Definition multIndices_recs: forall (A₁ A₂ : Set) (A_R : A₁ -> A₂ -> Prop) (I₁ I₂ : Set) (I_R : I₁ -> I₂ -> Prop) (B₁ : I₁ -> Set) (B₂ : I₂ -> Set) (B_R : forall (H : I₁) (H0 : I₂), I_R H H0 -> B₁ H -> B₂ H0 -> Prop) (f₁ : A₁ -> I₁) (f₂ : A₂ -> I₂) (f_R : forall (H : A₁) (H0 : A₂), A_R H H0 -> I_R (f₁ H) (f₂ H0)) (g₁ : forall i : I₁, B₁ i) (g₂ : forall i : I₂, B₂ i) (g_R : forall (i₁ : I₁) (i₂ : I₂) (i_R : I_R i₁ i₂), B_R i₁ i₂ i_R (g₁ i₁) (g₂ i₂)) (P₁ : forall (i : I₁) (b : B₁ i), multInd A₁ I₁ B₁ f₁ g₁ i b -> Set) (P₂ : forall (i : I₂) (b : B₂ i), multInd A₂ I₂ B₂ f₂ g₂ i b -> Set) (P_R : forall (i₁ : I₁) (i₂ : I₂) (i_R : I_R i₁ i₂) (b₁ : B₁ i₁) (b₂ : B₂ i₂) (b_R : B_R i₁ i₂ i_R b₁ b₂) (H : multInd A₁ I₁ B₁ f₁ g₁ i₁ b₁) (H0 : multInd A₂ I₂ B₂ f₂ g₂ i₂ b₂), multInd_RR A₁ A₂ A_R I₁ I₂ I_R B₁ B₂ B_R f₁ f₂ f_R g₁ g₂ g_R i₁ i₂ i_R b₁ b₂ b_R H H0 -> P₁ i₁ b₁ H -> P₂ i₂ b₂ H0 -> Prop) (f0₁ : forall a : A₁, P₁ (f₁ a) (g₁ (f₁ a)) (mlind A₁ I₁ B₁ f₁ g₁ a)) (f0₂ : forall a : A₂, P₂ (f₂ a) (g₂ (f₂ a)) (mlind A₂ I₂ B₂ f₂ g₂ a)), (forall (a₁ : A₁) (a₂ : A₂) (a_R : A_R a₁ a₂), P_R (f₁ a₁) (f₂ a₂) (f_R a₁ a₂ a_R) (g₁ (f₁ a₁)) (g₂ (f₂ a₂)) (g_R (f₁ a₁) (f₂ a₂) (f_R a₁ a₂ a_R)) (mlind A₁ I₁ B₁ f₁ g₁ a₁) (mlind A₂ I₂ B₂ f₂ g₂ a₂) (mlind_RR A₁ A₂ A_R I₁ I₂ I_R B₁ B₂ B_R f₁ f₂ f_R g₁ g₂ g_R a₁ a₂ a_R) (f0₁ a₁) (f0₂ a₂)) -> forall (i₁ : I₁) (i₂ : I₂) (i_R : I_R i₁ i₂) (a₁ : B₁ i₁) (a₂ : B₂ i₂) (a_R : B_R i₁ i₂ i_R a₁ a₂) (m₁ : multInd A₁ I₁ B₁ f₁ g₁ i₁ a₁) (m₂ : multInd A₂ I₂ B₂ f₂ g₂ i₂ a₂) (m_R : multInd_RR A₁ A₂ A_R I₁ I₂ I_R B₁ B₂ B_R f₁ f₂ f_R g₁ g₂ g_R i₁ i₂ i_R a₁ a₂ a_R m₁ m₂), P_R i₁ i₂ i_R a₁ a₂ a_R m₁ m₂ m_R (multInd_recs A₁ I₁ B₁ f₁ g₁ P₁ f0₁ i₁ a₁ m₁) (multInd_recs A₂ I₂ B₂ f₂ g₂ P₂ f0₂ i₂ a₂ m₂) := multInd_recs_pmtcty_RR. (* Proof using. intros. apply multInd_recs_RR. rename a_R into b_R. revert m_R. destruct m₁. destruct m₂. intros ?. simpl in *. unfold mlind_RR in H. destruct m_R as [a_R peq]. (* do the remaining in a separate C_RRinv construct? *) specialize (H _ _ a_R). (* here, peq needs to change to eq_refl *) generalize peq. generalize b_R. generalize i_R. apply eq_rect_sigtI. simpl. exact H. Defined. *) (* see the exact below exact ( eq_rect_sigt (I_R (f₁ a) (f₂ a0)) (fun ir : I_R (f₁ a) (f₂ a0) => B_R (f₁ a) (f₂ a0) ir (g₁ (f₁ a)) (g₂ (f₂ a0))) (existT (f_R a a0 a_R) (g_R (f₁ a) (f₂ a0) (f_R a a0 a_R))) (fun (a1 : I_R (f₁ a) (f₂ a0)) (p : B_R (f₁ a) (f₂ a0) a1 (g₁ (f₁ a)) (g₂ (f₂ a0))) (e : existT (f_R a a0 a_R) (g_R (f₁ a) (f₂ a0) (f_R a a0 a_R)) = existT a1 p) => P_R (f₁ a) (f₂ a0) a1 (g₁ (f₁ a)) (g₂ (f₂ a0)) p (mlind A₁ I₁ B₁ f₁ g₁ a) (mlind A₂ I₂ B₂ f₂ g₂ a0) (existT a_R e) (f0₁ a) (f0₂ a0)) (H _ _ a_R) i_R b_R peq). *)
Require Import References. Require Import RefSets. Require Import Capabilities. Require Import Indices. Require Import Objects. Require Import SystemState. Require Import SemanticsDefinitions. Require Import Semantics. Require Import List. Require Import Semantics_Conv. Require Import Semantics_ConvImpl. (* type_remove *) Require Import Execution. Module SimpleExecution (Ref:ReferenceType) (RefS: RefSetType Ref) (Cap:CapabilityType Ref) (Ind:IndexType) (Obj:ObjectType Ref Cap Ind) (Sys:SystemStateType Ref Cap Ind Obj) (SemDefns: SemanticsDefinitionsType Ref Cap Ind Obj Sys) (Sem:SemanticsType Ref RefS Cap Ind Obj Sys SemDefns) : ExecutionType Ref RefS Cap Ind Obj Sys SemDefns Sem. Module SemConv := MakeSemanticsConv Ref RefS Cap Ind Obj Sys SemDefns Sem. Inductive execute_def s: list Sem.operation -> Sys.t -> Prop := | execute_nil: forall s', Sys.eq s s' -> execute_def s nil s' | execute_cons : forall op tail s', execute_def s tail s' -> forall s'', Sys.eq (Sem.do_op op s') s'' -> execute_def s (op :: tail) s''. Definition execute s op_list := (List.fold_right Sem.do_op s op_list). Theorem execute_spec_1 : forall s s' op_list, execute_def s op_list s' -> Sys.eq (execute s op_list) s'. Proof. intros. unfold execute. induction H; simpl; auto. eapply Sys.eq_trans. eapply SemConv.do_op_eq; eauto. assumption. Qed. Theorem execute_spec_2 : forall s op_list s', Sys.eq (execute s op_list) s' -> execute_def s op_list s'. Proof. intros s op_list. induction op_list; intros. constructor; simpl in *; auto. simpl in H. constructor 2 with (execute s op_list); auto; apply IHop_list; apply Sys.eq_refl. Qed. Theorem execute_spec : forall s s' op_list, execute_def s op_list s' <-> Sys.eq (execute s op_list) s'. Proof. intros. split; intros; [apply execute_spec_1|apply execute_spec_2]; auto. Qed. End SimpleExecution.
\chapter{Circumbinary Planets and White Dwarfs in Kepler Eclipsing Binaries Catalog?} \section{some text here}
! This exercise is based on Exercise 9 on p. 66 from Chirila & Lohmann (2015). ! ! Try with two different compiler set-ups, with no optimization ! ! $ gfortran -g -O0 -fcheck=all -fbacktrace time_array_add.f90 ! ! and with full optimization ! ! $ gfortran -O3 -ffast-math -funroll-loops -mtune=native time_array_add.f90 ! ! Don't show correct randomization of arrays, setting the seed is technical and ! hard to explain to students, better skip it. ! ! Might be useful to change the declaration of arrays to a static form to show ! that compiler complains about the default stack size not being enough to ! accomodate them so big. program time_array_add implicit none integer, parameter :: N_REPS = 8 integer, parameter :: N = 256 real, dimension(:, :, :), allocatable :: a, b integer :: i, j, k, r real :: t1, t2 !integer :: seed_size !integer, allocatable :: seed(:) allocate(a(N, N, N)) allocate(b(N, N, N)) !call random_seed(size=seed_size) !allocate(seed(seed_size), source=0) !call random_seed(put=seed) !deallocate(seed) call random_number(a) call random_number(b) call cpu_time(t1) kji: do r = 1, N_REPS do i = 1, N do j = 1, N do k = 1, N a(i, j, k) = a(i, j, k) + b(i, j, k) end do ! k end do ! j end do ! i end do kji call cpu_time(t2) print "(a, f6.3, a)", "Order k-j-i took ", (t2 - t1) / N_REPS, " s." call cpu_time(t1) ijk: do r = 1, N_REPS do k = 1, N do j = 1, N do i = 1, N a(i, j, k) = a(i, j, k) + b(i, j, k) end do ! i end do ! j end do ! k end do ijk call cpu_time(t2) print "(a, f6.3, a)", "Order i-j-k took ", (t2 - t1) / N_REPS, " s." call cpu_time(t1) vector: do r = 1, N_REPS a(:, :, :) = a(:, :, :) + b(:, :, :) ! Equivalent to `a = a + b`. end do vector call cpu_time(t2) print '(a, f6.3, a)', "Vector sum took ", (t2 - t1) / N_REPS, " s." deallocate(a, b) end program time_array_add
! -*- f90 -*- ! **************************************** ! Routine to Check for Convergence SUBROUTINE convergence_check(m, n, converged, accepted, counter, C, Cnew, x, fvec, fjac, lam, xnew, & & nfev, maxfev, njev, maxjev, naev, maxaev, maxlam, minlam, artol, Cgoal, gtol, xtol, xrtol, ftol, frtol,cos_alpha) IMPLICIT NONE INTEGER m,n, converged, accepted, counter, nfev, maxfev, njev, maxjev, naev, maxaev REAL (KIND=8) C, Cnew, x(n), fvec(m), fjac(m,n), xnew(n), grad(n), lam, rpar(m) REAL (KIND=8) maxlam, minlam, artol, Cgoal, gtol, xtol, xrtol, ftol, frtol, cos_alpha INTEGER i ! The first few criteria should be checked every iteration, since ! they depend on counts and the Jacobian but not the proposed step. ! nfev IF(maxfev .GT. 0) THEN IF(nfev.GE.maxfev) THEN converged = -2 counter = 0 RETURN ENDIF ENDIF ! njev IF(maxjev .GT. 0) THEN IF(njev.GE.maxjev) THEN converged = -3 RETURN ENDIF ENDIF ! naev IF(maxaev .GT. 0) THEN IF(naev.GE.maxaev) THEN converged = -4 RETURN END IF ENDIF ! maxlam IF(maxlam .GT. 0.0d+0) THEN IF(lam .GE. maxlam) THEN converged = -5 RETURN END IF END IF ! minlam IF(minlam .GT. 0.0d+0 .AND. lam .GT. 0.0d+0) THEN IF(lam .LE. minlam) THEN counter = counter + 1 IF(counter .GE. 3) THEN converged = -6 RETURN END IF RETURN END IF END IF ! artol -- angle between residual vector and tangent plane IF( artol .GT. 0.0d+0) THEN !! Only calculate the projection if artol > 0 !! CALL projection(m,n,fvec, fjac, rpar,eps) !! cos_alpha = SQRT(DOT_PRODUCT(rpar,rpar)/DOT_PRODUCT(fvec,fvec)) IF( cos_alpha .LE. artol) THEN converged = 1 RETURN END IF END IF ! If gradient is small grad = -1.0d+0*MATMUL(fvec, fjac) IF(SQRT(DOT_PRODUCT(grad,grad)).LE.gtol) THEN converged = 3 RETURN ENDIF ! If cost is sufficiently small IF (C .LT. Cgoal) THEN !! Check every iteration in order to catch a cost small on the first iteration converged = 2 RETURN END IF ! If step is not accepted, then don't check remaining criteria IF(accepted.LT.0) THEN counter = 0 converged = 0 RETURN ENDIF ! If step size is small if(SQRT(DOT_PRODUCT(x-xnew,x-xnew)).LT. xtol) THEN converged = 4 RETURN ENDIF ! If each parameter is moving relatively small xrtolcheck: DO i = 1,n converged = 5 IF( ABS(x(i) - xnew(i)) .GT. xrtol*ABS(x(i)) .OR. (xnew(i) .NE. xnew(i)) ) converged = 0 !! continue if big step or nan in xnew IF( converged .EQ. 0) EXIT xrtolcheck END DO xrtolcheck IF(converged .EQ. 5) RETURN ! If cost is not decreasing -- this can happen by accident, so we require that it occur three times in a row IF( (C - Cnew).LE. ftol .AND.(C-Cnew).GE.0.) THEN counter = counter + 1 IF(counter .GE. 3) THEN converged = 6 RETURN END IF RETURN ENDIF ! If cost is not decreasing relatively -- again can happen by accident so require three times in a row IF( (C - Cnew).LE.(frtol*C).AND.(C-Cnew).GE.0.) THEN counter = counter + 1 IF(counter .GE. 3) THEN converged = 7 RETURN ENDIF RETURN ENDIF ! If none of the above: continue counter = 0 converged = 0 END SUBROUTINE convergence_check
-- FNF, 2017-06-13, issue # 2592 reported by Manuel Bärenz -- The .in file loads Issue2592/B.agda and Issue2592/C.agda that both -- imports Issue2592/A.agda.
# Use baremodule to shave off a few KB from the serialized `.ji` file baremodule libbluray_jll using Base using Base: UUID import JLLWrappers JLLWrappers.@generate_main_file_header("libbluray") JLLWrappers.@generate_main_file("libbluray", UUID("4a6b8444-0b90-5145-9aa0-b7d88b695d06")) end # module libbluray_jll
@testset "package issues" begin @test isempty(detect_ambiguities(Optim)) end
State Before: R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x M₅ : Type ?u.543558 M₆ : Type ?u.543561 inst✝⁴ : Ring R N : Type u_1 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : AddCommGroup N inst✝ : Module R N f : M × N →ₗ[R] M i : Injective ↑f n : ℕ ⊢ Disjoint (tailing f i n) (↑OrderDual.ofDual (↑(tunnel f i) (n + 1))) State After: R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x M₅ : Type ?u.543558 M₆ : Type ?u.543561 inst✝⁴ : Ring R N : Type u_1 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : AddCommGroup N inst✝ : Module R N f : M × N →ₗ[R] M i : Injective ↑f n : ℕ ⊢ tailing f i n ⊓ ↑OrderDual.ofDual (↑(tunnel f i) (n + 1)) = ⊥ Tactic: rw [disjoint_iff] State Before: R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x M₅ : Type ?u.543558 M₆ : Type ?u.543561 inst✝⁴ : Ring R N : Type u_1 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : AddCommGroup N inst✝ : Module R N f : M × N →ₗ[R] M i : Injective ↑f n : ℕ ⊢ tailing f i n ⊓ ↑OrderDual.ofDual (↑(tunnel f i) (n + 1)) = ⊥ State After: R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x M₅ : Type ?u.543558 M₆ : Type ?u.543561 inst✝⁴ : Ring R N : Type u_1 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : AddCommGroup N inst✝ : Module R N f : M × N →ₗ[R] M i : Injective ↑f n : ℕ ⊢ Submodule.map (tunnelAux f (tunnel' f i n)) (Submodule.snd R M N) ⊓ Submodule.map (tunnelAux f (tunnel' f i (n + 0))) (Submodule.fst R M N) = ⊥ Tactic: dsimp [tailing, tunnel, tunnel'] State Before: R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x M₅ : Type ?u.543558 M₆ : Type ?u.543561 inst✝⁴ : Ring R N : Type u_1 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : AddCommGroup N inst✝ : Module R N f : M × N →ₗ[R] M i : Injective ↑f n : ℕ ⊢ Submodule.map (tunnelAux f (tunnel' f i n)) (Submodule.snd R M N) ⊓ Submodule.map (tunnelAux f (tunnel' f i (n + 0))) (Submodule.fst R M N) = ⊥ State After: no goals Tactic: erw [Submodule.map_inf_eq_map_inf_comap, Submodule.comap_map_eq_of_injective (tunnelAux_injective _ i _), inf_comm, Submodule.fst_inf_snd, Submodule.map_bot]
c **************************************************************** c * * c * subroutine ousthd * c * * c * written by : bh * c * * c * last modified : 03/11/13 rhd * c * * c * prints the headers on a new page of output * c * put for output of stress or strain and their related * c * quantities. * c * * c **************************************************************** c c c subroutine ousthd( pgnum, lnum, hedtyp, loctyp, strlbl, newhed, & nitm, nl, nstrou, fmtyp, noheader ) use global_data ! old common.main implicit integer (a-z) logical newhed, noheader character(len=8) :: strlbl(*) character(len=*) :: hedtyp character(len=4) :: loctyp character(len=1) :: formfeed c if ( noheader ) then newhed = .false. return end if formfeed = char(12) c c check to see if the page is full. c if( lnum .gt. 55 ) then c c the page is full. reset line number and page c number. c newhed = .true. lnum = 0 pgnum = pgnum+1 c c print page headers. c if(fmtyp.eq.1.or.fmtyp.eq.3) then write(out,900) formfeed,stname,pgnum,ltmstp,lsldnm,hedtyp else if(fmtyp.eq.2.or.fmtyp.eq.4) then write(out,905) formfeed,stname,pgnum,ltmstp,lsldnm,hedtyp end if c c if(nitm.gt.nstrou) then fnsh= nstrou else fnsh= nitm end if c if(fmtyp.eq.1) then write(out,910) loctyp,(strlbl(i),i=1,fnsh) else if(fmtyp.eq.2) then write(out,915) loctyp,(strlbl(i),i=1,fnsh) else if(fmtyp.eq.3) then write(out,920) loctyp,(strlbl(i),i=1,fnsh) else if(fmtyp.eq.4) then write(out,925) loctyp,(strlbl(i),i=1,fnsh) end if c cl= 2 10 if(cl.gt.nl) go to 15 c strt= (cl-1)*nitm+1 if(cl*nitm.gt.nstrou) then fnsh= nstrou else fnsh= cl*nitm end if c if(fmtyp.eq.1) then write(out,911) (strlbl(i),i=strt,fnsh) else if(fmtyp.eq.2) then write(out,916) (strlbl(i),i=strt,fnsh) else if(fmtyp.eq.3) then write(out,921) (strlbl(i),i=strt,fnsh) else if(fmtyp.eq.4) then write(out,926) (strlbl(i),i=strt,fnsh) end if c cl= cl+1 go to 10 c 15 lnum= lnum+10+(nl-1) c c else c c no new headers needed. c newhed = .false. c end if c c 900 format(a1,///8x,'structure ',a8,51x,'page no. ',i4/8x, & 'step no. ',i7,24x,'loading ',a8//8x,a) c 905 format(a1,///8x,'structure ',a8,23x,'page no. ',i4/8x, & 'step no. ',i7,24x,'loading ',a8//8x,a) c 910 format(///6x,'elem',2x,a4,16x,a8,3(23x,a8)) 911 format(9x,4(23x,a8)) c 915 format(///6x,'elem',2x,a4,16x,a8,23x,a8) 916 format(9x,2(23x,a8)) c 920 format(///6x,'elem',2x,a4,9x,a8,5(12x,a8)) 921 format(13x,6(12x,a8)) c 925 format(///6x,'elem',2x,a4,9x,a8,2(12x,a8)) 926 format(13x,3(12x,a8)) c return end
/** * @file likelihood.c * @brief base functions to calculate the likelihood for general multitype OU processes on a phylogenetic tree * @author Carl Boettiger <[email protected]> * @version 0.1 * @date 2011-04-22 * * @section LICENSE * * Copyright (C) * 2011 - Carl Boettiger * This program 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 2 * of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_errno.h> #include "optimizers.h" #include "mvn.h" typedef struct { int n_nodes; size_t n_regimes; int * ancestor; int * regimes; double * branch_length; double * traits; double * alpha; double * theta; double * sigma; double * Xo; int * lca_matrix; } tree; int get_lca (int i, int j, int n_nodes, const int * ancestor, const double * branch_length, double * sep); void simulate (const gsl_rng * rng, tree * mytree); void calc_lik (const double *Xo, const double alpha[], const double theta[], const double sigma[], const int regimes[], const int ancestor[], const double branch_length[], const double traits[], int *n_nodes, int lca_matrix[], double *llik);
import numpy as np import matplotlib.pyplot as plt import config.pytorch_rnn_config as rnn_data_config def get_pytorch_rnn_data(start): time_steps = np.linspace(start * np.pi, (start + 1) * np.pi, rnn_data_config.num + 1) data = np.sin(time_steps) data = data.reshape((rnn_data_config.num + 1, 1)) # 因为是监督数据,所以要划分X y X = data[0: rnn_data_config.num, :] y = data[1: rnn_data_config.num + 1, :] plot_data(time_steps, X, y) return X, y def plot_data(time_steps, X, y): plt.figure(figsize=(8, 5)) # 利用matplotlib绘制生成的数据 plt.plot(time_steps[1:rnn_data_config.num + 1], X, 'r.', label='input_x') plt.plot(time_steps[1:rnn_data_config.num + 1], y, 'b.', label='output_y') plt.legend(loc='best') plt.show()
(* * Copyright 2022, Proofcraft Pty Ltd * * SPDX-License-Identifier: BSD-2-Clause *) (* Tactics/methods related to instantiating variables in multiple thms - Examples *) theory Rules_Tac_Test imports Lib.Rules_Tac begin experiment begin lemmas thms = bexI exI (* instantiating a variable in multiple thms *) lemma "P n \<Longrightarrow> \<exists>x. P x" apply (rules_tac x=n in thms) (* combined thms *) apply assumption done lemma "P n \<Longrightarrow> \<exists>x. P x" apply (rules_tac x=n in bexI exI) (* thms listed separately *) apply assumption done lemma "P n \<Longrightarrow> \<exists>x. P x" apply (rules_tac x=n and P=k for z k in thms) (* irrelevant "for" fixes *) apply assumption done lemma "P n \<Longrightarrow> \<exists>x. P x" apply (rules_tac x="P n" for P in exI) (* used for fixes *) oops (* single-variable instantiation using single_instantiate_tac *) lemma "P n \<Longrightarrow> \<exists>x. P x" apply (tactic \<open> let val v = Token.explode (Thy_Header.get_keywords' @{context}) Position.none "n" |> Parse.embedded_inner_syntax |> #1 in Multi_Rule_Insts.single_instantiate_tac Rule_Insts.res_inst_tac "x" v [] @{thms thms} @{context} [] end\<close>) apply assumption done (* single-variable instantiation using single_instantiate_tac via a method *) method_setup inst_x_exI_tac = \<open>Multi_Rule_Insts.single_instantiate_method Rule_Insts.res_inst_tac "x" @{thms thms}\<close> \<open>instantiate "x" in thms and apply the result with rule_tac\<close> lemma "P n \<Longrightarrow> \<exists>x. P x" apply (inst_x_exI_tac n) apply assumption done (* instantiation of same variable with a different type in each theorem *) lemma assumes a: "\<And>x P. Z x \<Longrightarrow> P (x::nat)" assumes b: "\<And>x P. Y x \<Longrightarrow> P (x::int)" shows "P (2::nat)" apply (rules_tac x=2 in b a) oops end end
------------------------------------------------------------------------ -- The two big-step semantics given by Leroy and Grall in "Coinductive -- big-step operational semantics" ------------------------------------------------------------------------ module Lambda.Substitution.TwoSemantics where open import Codata.Musical.Notation open import Lambda.Syntax open WHNF open import Lambda.Substitution -- Big-step semantics for terminating computations. infix 4 _⇓_ data _⇓_ {n} : Tm n → Value n → Set where val : ∀ {v} → ⌜ v ⌝ ⇓ v app : ∀ {t₁ t₂ t v v′} (t₁⇓ : t₁ ⇓ ƛ t) (t₂⇓ : t₂ ⇓ v) (t₁t₂⇓ : t / sub ⌜ v ⌝ ⇓ v′) → t₁ · t₂ ⇓ v′ -- Big-step semantics for non-terminating computations. infix 4 _⇑ data _⇑ {n} : Tm n → Set where ·ˡ : ∀ {t₁ t₂} (t₁⇑ : ∞ (t₁ ⇑)) → t₁ · t₂ ⇑ ·ʳ : ∀ {t₁ t₂ v} (t₁⇓ : t₁ ⇓ v) (t₂⇑ : ∞ (t₂ ⇑)) → t₁ · t₂ ⇑ app : ∀ {t₁ t₂ t v} (t₁⇓ : t₁ ⇓ ƛ t) (t₂⇓ : t₂ ⇓ v) (t₁t₂⇓ : ∞ (t / sub ⌜ v ⌝ ⇑)) → t₁ · t₂ ⇑
//---------------------------------------------------------------------------- /** @file GtpEngine.cpp See GtpEngine.h */ //---------------------------------------------------------------------------- #include "GtpEngine.h" #include <iomanip> #include <cassert> #include <cctype> #include <fstream> #if GTPENGINE_PONDER || GTPENGINE_INTERRUPT #include <boost/thread/barrier.hpp> #include <boost/thread/condition.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/xtime.hpp> using boost::barrier; using boost::condition; using boost::mutex; using boost::thread; using boost::xtime; using boost::xtime_get; #endif using namespace std; #if WIN32 // Disable Visual C++ 2005 warning 4355 ('this' : used in base member // initializer list). The constructors of ReadThread and PonderThread store a // reference of 'this', which is allowed as long as 'this' is not used yet #pragma warning( disable : 4355 ) #endif //---------------------------------------------------------------------------- /** Utility functions. */ namespace { void Trim(string& str); /** Check, if line contains a command. @param line The line to check. @return True, if command does not contain only whitespaces and is not a comment line. */ bool IsCommandLine(const string& line) { string trimmedLine = line; Trim(trimmedLine); return (! trimmedLine.empty() && trimmedLine[0] != '#'); } #if ! GTPENGINE_INTERRUPT /** Read next command from stream. @param in The input stream. @param[out] cmd The command (reused for efficiency) @return @c false on end-of-stream or read error. */ bool ReadCommand(GtpCommand& cmd, GtpInputStream& in) { string line; while (in.GetLine(line) && ! IsCommandLine(line)) { } if (in.EndOfInput()) return false; Trim(line); cmd.Init(line); return true; } #endif /** Replace empty lines in a multi-line string by lines containing a single space. @param text The input string. @return The input string with all occurrences of "\n\n" replaced by "\n \n". */ string ReplaceEmptyLines(const string& text) { if (text.find("\n\n") == string::npos) return text; istringstream in(text); ostringstream result; bool lastWasNewLine = false; char c; while (in.get(c)) { bool isNewLine = (c == '\n'); if (isNewLine && lastWasNewLine) result.put(' '); result.put(c); lastWasNewLine = isNewLine; } return result.str(); } /** Remove leading and trailing whitespaces from a string. Whitespaces are tab, carriage return and space. @param str The input string. */ void Trim(string& str) { char const* whiteSpace = " \t\r"; size_t pos = str.find_first_not_of(whiteSpace); str.erase(0, pos); pos = str.find_last_not_of(whiteSpace); str.erase(pos + 1); } } // namespace //---------------------------------------------------------------------------- #if GTPENGINE_PONDER || GTPENGINE_INTERRUPT /** Utility functions for Boost.Thread. */ namespace { void Notify(boost::mutex& aMutex, condition& aCondition) { boost::mutex::scoped_lock lock(aMutex); aCondition.notify_all(); } } // namespace #endif // GTPENGINE_PONDER || GTPENGINE_INTERRUPT //---------------------------------------------------------------------------- #if GTPENGINE_PONDER namespace { /** Ponder thread used by GtpEngine::MainLoop(). This thread calls GtpEngine::Ponder() while the engine is waiting for the next command. @see GtpEngine::Ponder() */ class PonderThread { public: PonderThread(GtpEngine& engine); void StartPonder(); void StopPonder(); void Quit(); private: class Function { public: Function(PonderThread& ponderThread); void operator()(); private: PonderThread& m_ponderThread; }; friend class PonderThread::Function; GtpEngine& m_engine; barrier m_threadReady; boost::mutex m_startPonderMutex; boost::mutex m_ponderFinishedMutex; condition m_startPonder; condition m_ponderFinished; boost::mutex::scoped_lock m_ponderFinishedLock; /** The thread to run the ponder function. Order dependency: must be constructed as the last member, because the constructor starts the thread. */ boost::thread m_thread; }; PonderThread::Function::Function(PonderThread& ponderThread) : m_ponderThread(ponderThread) { } void PonderThread::Function::operator()() { boost::mutex::scoped_lock lock(m_ponderThread.m_startPonderMutex); m_ponderThread.m_threadReady.wait(); while (true) { m_ponderThread.m_startPonder.wait(lock); GtpEngine& engine = m_ponderThread.m_engine; if (engine.IsQuitSet()) return; engine.Ponder(); Notify(m_ponderThread.m_ponderFinishedMutex, m_ponderThread.m_ponderFinished); } } PonderThread::PonderThread(GtpEngine& engine) : m_engine(engine), m_threadReady(2), m_ponderFinishedLock(m_ponderFinishedMutex), m_thread(Function(*this)) { m_threadReady.wait(); } void PonderThread::StartPonder() { m_engine.InitPonder(); Notify(m_startPonderMutex, m_startPonder); } void PonderThread::StopPonder() { m_engine.StopPonder(); m_ponderFinished.wait(m_ponderFinishedLock); } void PonderThread::Quit() { Notify(m_startPonderMutex, m_startPonder); m_thread.join(); } } // namespace #endif // GTPENGINE_PONDER //---------------------------------------------------------------------------- #if GTPENGINE_INTERRUPT namespace { /** Thread for reading the next command line. This thread is used instead of the simple function ReadCommand(GtpCommand&), if GtpEngine is compiled with interrupt support. @see GtpEngine::Interrupt() */ class ReadThread { public: ReadThread(GtpInputStream& in, GtpEngine& engine); bool ReadCommand(GtpCommand& cmd); void JoinThread(); private: class Function { public: Function(ReadThread& readThread); void operator()(); private: ReadThread& m_readThread; void ExecuteSleepLine(const string& line); }; friend class ReadThread::Function; GtpInputStream& m_in; GtpEngine& m_engine; string m_line; bool m_isStreamGood; barrier m_threadReady; boost::mutex m_waitCommandMutex; condition m_waitCommand; boost::mutex m_commandReceivedMutex; condition m_commandReceived; boost::mutex::scoped_lock m_commandReceivedLock; /** The thread to run the read command function. Order dependency: must be constructed as the last member, because the constructor starts the thread. */ boost::thread m_thread; }; ReadThread::Function::Function(ReadThread& readThread) : m_readThread(readThread) { } void ReadThread::Function::operator()() { boost::mutex::scoped_lock lock(m_readThread.m_waitCommandMutex); m_readThread.m_threadReady.wait(); GtpEngine& engine = m_readThread.m_engine; GtpInputStream& in = m_readThread.m_in; string line; while (true) { while (in.GetLine(line)) { Trim(line); if (line == "# interrupt") engine.Interrupt(); else if (line.find("# gtpengine-sleep ") == 0) ExecuteSleepLine(line); else if (IsCommandLine(line)) break; } m_readThread.m_waitCommand.wait(lock); m_readThread.m_isStreamGood = ! in.EndOfInput(); m_readThread.m_line = line; Notify(m_readThread.m_commandReceivedMutex, m_readThread.m_commandReceived); if (in.EndOfInput()) return; // See comment at GtpEngine::SetQuit GtpCommand cmd(line); if (cmd.Name() == "quit") return; } } void ReadThread::Function::ExecuteSleepLine(const string& line) { istringstream buffer(line); string s; buffer >> s; assert(s == "#"); buffer >> s; assert(s == "gtpengine-sleep"); int seconds; buffer >> seconds; if (seconds > 0) { cerr << "GtpEngine: sleep " << seconds << '\n'; xtime time; xtime_get(&time, boost::TIME_UTC_); time.sec += seconds; thread::sleep(time); cerr << "GtpEngine: sleep done\n"; } } void ReadThread::JoinThread() { m_thread.join(); } ReadThread::ReadThread(GtpInputStream& in, GtpEngine& engine) : m_in(in), m_engine(engine), m_threadReady(2), m_commandReceivedLock(m_commandReceivedMutex), m_thread(Function(*this)) { m_threadReady.wait(); } bool ReadThread::ReadCommand(GtpCommand& cmd) { Notify(m_waitCommandMutex, m_waitCommand); m_commandReceived.wait(m_commandReceivedLock); if (! m_isStreamGood) return false; cmd.Init(m_line); return true; } } // namespace #endif // GTPENGINE_INTERRUPT //---------------------------------------------------------------------------- GtpFailure::GtpFailure() { } GtpFailure::GtpFailure(const GtpFailure& failure) { m_response << failure.Response(); m_response.copyfmt(failure.m_response); } GtpFailure::GtpFailure(const string& response) { m_response << response; } GtpFailure::~GtpFailure() throw() { } //---------------------------------------------------------------------------- GtpCommand::Argument::Argument(const string& value, std::size_t end) : m_value(value), m_end(end) { } //---------------------------------------------------------------------------- ostringstream GtpCommand::s_dummy; const string& GtpCommand::Arg(std::size_t number) const { size_t index = number + 1; if (number >= NuArg()) throw GtpFailure() << "missing argument " << index; return m_arguments[index].m_value; } const string& GtpCommand::Arg() const { CheckNuArg(1); return Arg(0); } std::string GtpCommand::ArgLine() const { string result = m_line.substr(m_arguments[0].m_end); Trim(result); return result; } string GtpCommand::ArgToLower(std::size_t number) const { string value = Arg(number); for (size_t i = 0; i < value.length(); ++i) value[i] = tolower(value[i]); return value; } bool GtpCommand::BoolArg(std::size_t number) const { string value = Arg(number); if (value == "1") return true; if (value == "0") return false; throw GtpFailure() << "argument " << (number + 1) << " must be 0 or 1"; } void GtpCommand::CheckNuArg(std::size_t number) const { if (NuArg() == number) return; if (number == 0) throw GtpFailure() << "no arguments allowed"; else if (number == 1) throw GtpFailure() << "command needs one argument"; else throw GtpFailure() << "command needs " << number << " arguments"; } void GtpCommand::CheckNuArgLessEqual(std::size_t number) const { if (NuArg() <= number) return; if (number == 1) throw GtpFailure() << "command needs at most one argument"; else throw GtpFailure() << "command needs at most " << number << " arguments"; } double GtpCommand::FloatArg(std::size_t number) const { istringstream in(Arg(number)); double result; in >> result; if (! in) throw GtpFailure() << "argument " << (number + 1) << " must be a float"; return result; } int GtpCommand::IntArg(std::size_t number) const { istringstream in(Arg(number)); int result; in >> result; if (! in) throw GtpFailure() << "argument " << (number + 1) << " must be a number"; return result; } int GtpCommand::IntArg(std::size_t number, int min) const { int result = IntArg(number); if (result < min) throw GtpFailure() << "argument " << (number + 1) << " must be greater or equal " << min; return result; } int GtpCommand::IntArg(std::size_t number, int min, int max) const { int result = IntArg(number); if (result < min) throw GtpFailure() << "argument " << (number + 1) << " must be greater or equal " << min; if (result > max) throw GtpFailure() << "argument " << (number + 1) << " must be less or equal " << max; return result; } void GtpCommand::Init(const string& line) { m_line = line; Trim(m_line); SplitLine(m_line); assert(m_arguments.size() > 0); ParseCommandId(); assert(m_arguments.size() > 0); m_response.str(""); m_response.copyfmt(s_dummy); } void GtpCommand::ParseCommandId() { m_id = ""; if (m_arguments.size() < 2) return; istringstream in(m_arguments[0].m_value); int id; in >> id; if (in) { m_id = m_arguments[0].m_value; m_arguments.erase(m_arguments.begin()); } } string GtpCommand::RemainingLine(std::size_t number) const { size_t index = number + 1; if (number >= NuArg()) throw GtpFailure() << "missing argument " << index; string result = m_line.substr(m_arguments[index].m_end); Trim(result); return result; } void GtpCommand::SetResponse(const string& response) { m_response.str(response); } void GtpCommand::SetResponseBool(bool value) { m_response.str(value ? "true" : "false"); } std::size_t GtpCommand::SizeTypeArg(std::size_t number) const { string arg = Arg(number); // Workaround for bug in standard library of some GCC versions (e.g. GCC // 4.4.1 on Ubuntu 9.10): negative numbers are parsed without error as // size_t, which should be unsigned bool fail = (! arg.empty() && arg[0] == '-'); std::size_t result; if (! fail) { istringstream in(arg); in >> result; fail = ! in; } if (fail) throw GtpFailure() << "argument " << (number + 1) << " must be a number"; return result; } std::size_t GtpCommand::SizeTypeArg(std::size_t number, std::size_t min) const { std::size_t result = SizeTypeArg(number); if (result < min) throw GtpFailure() << "argument " << (number + 1) << " must be greater or equal " << min; return result; } /** Split line into arguments. Arguments are words separated by whitespaces. Arguments with whitespaces can be quoted with quotation marks ('"'). Characters can be escaped with a backslash ('\'). @param line The line to split. */ void GtpCommand::SplitLine(const string& line) { m_arguments.clear(); bool escape = false; bool inString = false; ostringstream element; for (size_t i = 0; i < line.size(); ++i) { char c = line[i]; if (c == '"' && ! escape) { if (inString) { m_arguments.push_back(Argument(element.str(), i + 1)); element.str(""); } inString = ! inString; } else if (isspace(c) && ! inString) { if (! element.str().empty()) { m_arguments.push_back(Argument(element.str(), i + 1)); element.str(""); } } else element << c; escape = (c == '\\' && ! escape); } if (! element.str().empty()) m_arguments.push_back(Argument(element.str(), line.size())); } //---------------------------------------------------------------------------- GtpCallbackBase::~GtpCallbackBase() throw() { } //---------------------------------------------------------------------------- GtpEngine::GtpEngine(GtpInputStream& in, GtpOutputStream& out) : m_quit(false), m_in(in), m_out(out) { Register("known_command", &GtpEngine::CmdKnownCommand, this); Register("list_commands", &GtpEngine::CmdListCommands, this); Register("name", &GtpEngine::CmdName, this); Register("protocol_version", &GtpEngine::CmdProtocolVersion, this); Register("quit", &GtpEngine::CmdQuit, this); Register("version", &GtpEngine::CmdVersion, this); } GtpEngine::~GtpEngine() { typedef CallbackMap::iterator Iterator; for (Iterator i = m_callbacks.begin(); i != m_callbacks.end(); ++i) { delete i->second; #ifndef NDEBUG i->second = 0; #endif } } void GtpEngine::BeforeHandleCommand() { // Default implementation does nothing } void GtpEngine::BeforeWritingResponse() { // Default implementation does nothing } /** Return @c true if command is known, @c false otherwise. */ void GtpEngine::CmdKnownCommand(GtpCommand& cmd) { cmd.CheckNuArg(1); cmd.SetResponseBool(IsRegistered(cmd.Arg(0))); } /** List all known commands. */ void GtpEngine::CmdListCommands(GtpCommand& cmd) { cmd.CheckArgNone(); typedef CallbackMap::const_iterator Iterator; for (Iterator i = m_callbacks.begin(); i != m_callbacks.end(); ++i) cmd << i->first << '\n'; } /** Return name. */ void GtpEngine::CmdName(GtpCommand& cmd) { cmd.CheckArgNone(); cmd << "Unknown"; } /** Return protocol version. */ void GtpEngine::CmdProtocolVersion(GtpCommand& cmd) { cmd.CheckArgNone(); cmd << "2"; } /** Quit command loop. */ void GtpEngine::CmdQuit(GtpCommand& cmd) { cmd.CheckArgNone(); SetQuit(); } /** Return empty version string. The GTP standard says to return empty string, if no meaningful reponse is available. */ void GtpEngine::CmdVersion(GtpCommand& cmd) { cmd.CheckArgNone(); } string GtpEngine::ExecuteCommand(const string& cmdline, ostream& log) { if (! IsCommandLine(cmdline)) throw GtpFailure() << "Bad command: " << cmdline; GtpCommand cmd; cmd.Init(cmdline); log << cmd.Line() << '\n'; GtpOutputStream gtpLog(log); bool status = HandleCommand(cmd, gtpLog); string response = cmd.Response(); if (! status) throw GtpFailure() << "Executing " << cmd.Line() << " failed"; return response; } void GtpEngine::ExecuteFile(const string& name, ostream& log) { ifstream in(name.c_str()); if (! in) throw GtpFailure() << "Cannot read " << name; string line; GtpCommand cmd; GtpOutputStream gtpLog(log); while (getline(in, line)) { if (! IsCommandLine(line)) continue; cmd.Init(line); log << cmd.Line() << '\n'; bool status = HandleCommand(cmd, gtpLog); if (! status) throw GtpFailure() << "Executing " << cmd.Line() << " failed"; } } bool GtpEngine::HandleCommand(GtpCommand& cmd, GtpOutputStream& out) { BeforeHandleCommand(); bool status = true; string response; try { CallbackMap::const_iterator pos = m_callbacks.find(cmd.Name()); if (pos == m_callbacks.end()) { status = false; response = "unknown command: " + cmd.Name(); } else { GtpCallbackBase* callback = pos->second; (*callback)(cmd); response = cmd.Response(); } } catch (const GtpFailure& failure) { status = false; response = failure.Response(); } response = ReplaceEmptyLines(response); BeforeWritingResponse(); ostringstream ostr; ostr << (status ? '=' : '?') << cmd.ID() << ' ' << response; size_t size = response.size(); if (size == 0 || response[size - 1] != '\n') ostr << '\n'; ostr << '\n' << flush; out.Write(ostr.str()); out.Flush(); return status; } bool GtpEngine::IsRegistered(const string& command) const { return (m_callbacks.find(command) != m_callbacks.end()); } void GtpEngine::MainLoop() { m_quit = false; #if GTPENGINE_PONDER PonderThread ponderThread(*this); #endif #if GTPENGINE_INTERRUPT ReadThread readThread(m_in, *this); #endif GtpCommand cmd; while (true) { #if GTPENGINE_PONDER ponderThread.StartPonder(); #endif #if GTPENGINE_INTERRUPT bool isStreamGood = readThread.ReadCommand(cmd); #else bool isStreamGood = ReadCommand(cmd, m_in); #endif #if GTPENGINE_PONDER ponderThread.StopPonder(); #endif if (isStreamGood) HandleCommand(cmd, m_out); else SetQuit(); if (m_quit) { #if GTPENGINE_PONDER ponderThread.Quit(); #endif #if GTPENGINE_INTERRUPT readThread.JoinThread(); #endif break; } } } void GtpEngine::Register(const string& command, GtpCallbackBase* callback) { CallbackMap::iterator pos = m_callbacks.find(command); if (pos != m_callbacks.end()) { delete pos->second; #ifndef NDEBUG pos->second = 0; #endif m_callbacks.erase(pos); } m_callbacks.insert(make_pair(command, callback)); } void GtpEngine::SetQuit() { m_quit = true; } bool GtpEngine::IsQuitSet() const { return m_quit; } #if GTPENGINE_PONDER void GtpEngine::Ponder() { // Default implementation does nothing #ifdef GTPENGINE_TEST cerr << "GtpEngine::Ponder()\n"; #endif } void GtpEngine::StopPonder() { // Default implementation does nothing #ifdef GTPENGINE_TEST cerr << "GtpEngine::StopPonder()\n"; #endif } void GtpEngine::InitPonder() { // Default implementation does nothing #ifdef GTPENGINE_TEST cerr << "GtpEngine::InitPonder()\n"; #endif } #endif // GTPENGINE_PONDER #if GTPENGINE_INTERRUPT void GtpEngine::Interrupt() { // Default implementation does nothing #ifdef GTPENGINE_TEST cerr << "GtpEngine::Interrupt()\n"; #endif } #endif // GTPENGINE_INTERRUPT //---------------------------------------------------------------------------- #ifdef GTPENGINE_MAIN /** Main routine for testing and standalone compilation. */ int main() { try { GtpEngine engine(cin, cout); engine.MainLoop(); } catch (const exception& e) { cerr << e.what() << '\n'; return 1; } return 0; } #endif // GTPENGINE_MAIN //----------------------------------------------------------------------------
(************************************************************************) (* v * The Coq Proof Assistant / The Coq Development Team *) (* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011 *) (* \VV/ **************************************************************) (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (*i $Id: JMeq.v 14641 2011-11-06 11:59:10Z herbelin $ i*) (** John Major's Equality as proposed by Conor McBride Reference: [McBride] Elimination with a Motive, Proceedings of TYPES 2000, LNCS 2277, pp 197-216, 2002. *) Set Implicit Arguments. Unset Elimination Schemes. Inductive JMeq (A:Type) (x:A) : forall B:Type, B -> Prop := JMeq_refl : JMeq x x. Set Elimination Schemes. Hint Resolve JMeq_refl. Lemma JMeq_sym : forall (A B:Type) (x:A) (y:B), JMeq x y -> JMeq y x. Proof. destruct 1; trivial. Qed. Hint Immediate JMeq_sym. Lemma JMeq_trans : forall (A B C:Type) (x:A) (y:B) (z:C), JMeq x y -> JMeq y z -> JMeq x z. Proof. destruct 2; trivial. Qed. Axiom JMeq_eq : forall (A:Type) (x y:A), JMeq x y -> x = y. Lemma JMeq_ind : forall (A:Type) (x:A) (P:A -> Prop), P x -> forall y, JMeq x y -> P y. Proof. intros A x P H y H'; case JMeq_eq with (1 := H'); trivial. Qed. Lemma JMeq_rec : forall (A:Type) (x:A) (P:A -> Set), P x -> forall y, JMeq x y -> P y. Proof. intros A x P H y H'; case JMeq_eq with (1 := H'); trivial. Qed. Lemma JMeq_rect : forall (A:Type) (x:A) (P:A->Type), P x -> forall y, JMeq x y -> P y. Proof. intros A x P H y H'; case JMeq_eq with (1 := H'); trivial. Qed. Lemma JMeq_ind_r : forall (A:Type) (x:A) (P:A -> Prop), P x -> forall y, JMeq y x -> P y. Proof. intros A x P H y H'; case JMeq_eq with (1 := JMeq_sym H'); trivial. Qed. Lemma JMeq_rec_r : forall (A:Type) (x:A) (P:A -> Set), P x -> forall y, JMeq y x -> P y. Proof. intros A x P H y H'; case JMeq_eq with (1 := JMeq_sym H'); trivial. Qed. Lemma JMeq_rect_r : forall (A:Type) (x:A) (P:A -> Type), P x -> forall y, JMeq y x -> P y. Proof. intros A x P H y H'; case JMeq_eq with (1 := JMeq_sym H'); trivial. Qed. Lemma JMeq_congr : forall (A:Type) (x:A) (B:Type) (f:A->B) (y:A), JMeq x y -> f x = f y. Proof. intros A x B f y H; case JMeq_eq with (1 := H); trivial. Qed. (** [JMeq] is equivalent to [eq_dep Type (fun X => X)] *) Require Import Eqdep. Lemma JMeq_eq_dep_id : forall (A B:Type) (x:A) (y:B), JMeq x y -> eq_dep Type (fun X => X) A x B y. Proof. destruct 1. apply eq_dep_intro. Qed. Lemma eq_dep_id_JMeq : forall (A B:Type) (x:A) (y:B), eq_dep Type (fun X => X) A x B y -> JMeq x y. Proof. destruct 1. apply JMeq_refl. Qed. (** [eq_dep U P p x q y] is strictly finer than [JMeq (P p) x (P q) y] *) Lemma eq_dep_JMeq : forall U P p x q y, eq_dep U P p x q y -> JMeq x y. Proof. destruct 1. apply JMeq_refl. Qed. Lemma eq_dep_strictly_stronger_JMeq : exists U, exists P, exists p, exists q, exists x, exists y, JMeq x y /\ ~ eq_dep U P p x q y. Proof. exists bool. exists (fun _ => True). exists true. exists false. exists I. exists I. split. trivial. intro H. assert (true=false) by (destruct H; reflexivity). discriminate. Qed. (** However, when the dependencies are equal, [JMeq (P p) x (P q) y] is as strong as [eq_dep U P p x q y] (this uses [JMeq_eq]) *) Lemma JMeq_eq_dep : forall U (P:U->Prop) p q (x:P p) (y:P q), p = q -> JMeq x y -> eq_dep U P p x q y. Proof. intros. destruct H. apply JMeq_eq in H0 as ->. reflexivity. Qed. (* Compatibility *) Notation sym_JMeq := JMeq_sym (only parsing). Notation trans_JMeq := JMeq_trans (only parsing).
open import Type module Graph.Walk.Functions.Proofs {ℓ₁ ℓ₂} {V : Type{ℓ₁}} where import Data.Either as Either open import Data.Either.Proofs open import Logic.Propositional import Lvl open import Graph{ℓ₁}{ℓ₂}(V) open import Graph.Properties open import Graph.Walk{ℓ₁}{ℓ₂}{V} open import Graph.Walk.Properties{ℓ₁}{ℓ₂}{V} open import Graph.Walk.Functions{ℓ₁}{ℓ₂}{V} open import Numeral.Natural open import Numeral.Natural.Oper open import Numeral.Natural.Oper.Proofs open import Relator.Equals open import Relator.Equals.Proofs open import Structure.Relator.Properties open import Syntax.Function open import Type.Dependent open import Type.Dependent.Functions module _ (_⟶_ : Graph) where at-path-length : ∀{a} → length{_⟶_}(at{x = a}) ≡ 0 at-path-length = reflexivity(_≡_) edge-path-length : ∀{a b}{e : a ⟶ b} → length{_⟶_}(edge e) ≡ 1 edge-path-length = reflexivity(_≡_) join-path-length : ∀{a b c}{e₁ : a ⟶ b}{e₂ : b ⟶ c} → length{_⟶_}(join e₁ e₂) ≡ 2 join-path-length = reflexivity(_≡_) prepend-path-length : ∀{a b c}{e : a ⟶ b}{w : Walk(_⟶_) b c} → length(prepend e w) ≡ 𝐒(length w) prepend-path-length {w = at} = reflexivity(_≡_) prepend-path-length {w = prepend e w} = [≡]-with(𝐒) (prepend-path-length{e = e}{w = w}) [++]-identityᵣ : ∀{a b}{w : Walk(_⟶_) a b} → (w ++ at ≡ w) [++]-identityᵣ {w = at} = reflexivity(_≡_) [++]-identityᵣ {w = prepend x w} = [≡]-with(prepend x) ([++]-identityᵣ {w = w}) {-# REWRITE [++]-identityᵣ #-} [++]-path-length : ∀{a b c}{w₁ : Walk(_⟶_) a b}{w₂ : Walk(_⟶_) b c} → length(w₁ ++ w₂) ≡ length w₁ + length w₂ [++]-path-length {a} {.a} {.a} {at} {at} = reflexivity(_≡_) [++]-path-length {a} {.a} {c} {at} {prepend e w} = prepend-path-length {e = e}{w = w} [++]-path-length {a} {b} {c} {prepend e₁ w₁} {w₂} = [≡]-with(𝐒) ([++]-path-length {w₁ = w₁}{w₂ = w₂}) {-# REWRITE [++]-path-length #-} at-visits : ∀{v} → Visits(_⟶_) v (at{x = v}) at-visits = current edge-visits-left : ∀{a b}{e : a ⟶ b} → Visits(_⟶_) a (edge e) edge-visits-left = current edge-visits-right : ∀{a b}{e : a ⟶ b} → Visits(_⟶_) b (edge e) edge-visits-right = skip current join-visits-1 : ∀{a b c}{e₁ : a ⟶ b}{e₂ : b ⟶ c} → Visits(_⟶_) a (join e₁ e₂) join-visits-1 = current join-visits-2 : ∀{a b c}{e₁ : a ⟶ b}{e₂ : b ⟶ c} → Visits(_⟶_) b (join e₁ e₂) join-visits-2 = skip current join-visits-3 : ∀{a b c}{e₁ : a ⟶ b}{e₂ : b ⟶ c} → Visits(_⟶_) c (join e₁ e₂) join-visits-3 = skip (skip current) prepend-visitsᵣ-left : ∀{a b c}{e : a ⟶ b}{w : Walk(_⟶_) b c} → Visits(_⟶_) a (prepend e w) prepend-visitsᵣ-left = current prepend-visitsᵣ-right : ∀{v b c}{w : Walk(_⟶_) b c} → Visits(_⟶_) v w → ∀{a}{e : a ⟶ b} → Visits(_⟶_) v (prepend e w) prepend-visitsᵣ-right p = skip p prepend-visitsₗ : ∀{v a b c}{e : a ⟶ b}{w : Walk(_⟶_) b c} → Visits(_⟶_) v (prepend e w) → ((v ≡ a) ∨ Visits(_⟶_) v w) prepend-visitsₗ current = [∨]-introₗ(reflexivity(_≡_)) prepend-visitsₗ (skip p) = [∨]-introᵣ p [++]-visitsᵣ : ∀{v a b c}{w₁ : Walk(_⟶_) a b}{w₂ : Walk(_⟶_) b c} → (Visits(_⟶_) v w₁) ∨ (Visits(_⟶_) v w₂) → Visits(_⟶_) v (w₁ ++ w₂) [++]-visitsᵣ ([∨]-introₗ current) = current [++]-visitsᵣ {w₂ = w₂} ([∨]-introₗ (skip {rest = rest} p)) = skip ([++]-visitsᵣ {w₁ = rest}{w₂ = w₂} ([∨]-introₗ p)) [++]-visitsᵣ {w₁ = at} ([∨]-introᵣ p) = p [++]-visitsᵣ {w₁ = prepend x w₁} {w₂ = w₂} ([∨]-introᵣ p) = skip ([++]-visitsᵣ {w₁ = w₁}{w₂ = w₂} ([∨]-introᵣ p)) [++]-visitsₗ : ∀{v a b c}{w₁ : Walk(_⟶_) a b}{w₂ : Walk(_⟶_) b c} → (Visits(_⟶_) v w₁) ∨ (Visits(_⟶_) v w₂) ← Visits(_⟶_) v (w₁ ++ w₂) [++]-visitsₗ {v} {a} {.a} {.a} {at} {at} p = [∨]-introₗ p [++]-visitsₗ {v} {a} {.a} {c} {at} {prepend x w₂} p = [∨]-introᵣ p [++]-visitsₗ {v} {a} {b} {c} {prepend e w₁} {w₂} p with prepend-visitsₗ p [++]-visitsₗ {v} {a} {b} {c} {prepend e w₁} {w₂} p | [∨]-introₗ eq = [∨]-introₗ ([≡]-substitutionₗ eq (Visits.current {path = prepend e w₁})) [++]-visitsₗ {v} {a} {b} {c} {prepend e w₁} {w₂} _ | [∨]-introᵣ p = Either.mapLeft skip ([++]-visitsₗ {w₁ = w₁} {w₂ = w₂} p)
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import analysis.convex.basic import topology.algebra.order.basic /-! # Strictly convex sets This file defines strictly convex sets. A set is strictly convex if the open segment between any two distinct points lies in its interior. -/ open set open_locale convex pointwise variables {𝕜 𝕝 E F β : Type*} open function set open_locale convex section ordered_semiring variables [ordered_semiring 𝕜] [topological_space E] [topological_space F] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] section has_scalar variables (𝕜) [has_scalar 𝕜 E] [has_scalar 𝕜 F] (s : set E) /-- A set is strictly convex if the open segment between any two distinct points lies is in its interior. This basically means "convex and not flat on the boundary". -/ def strict_convex : Prop := s.pairwise $ λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ interior s variables {𝕜 s} {x y : E} {a b : 𝕜} lemma strict_convex_iff_open_segment_subset : strict_convex 𝕜 s ↔ s.pairwise (λ x y, open_segment 𝕜 x y ⊆ interior s) := forall₅_congr $ λ x hx y hy hxy, (open_segment_subset_iff 𝕜).symm lemma strict_convex.open_segment_subset (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : open_segment 𝕜 x y ⊆ interior s := strict_convex_iff_open_segment_subset.1 hs hx hy h lemma strict_convex_empty : strict_convex 𝕜 (∅ : set E) := pairwise_empty _ lemma strict_convex_univ : strict_convex 𝕜 (univ : set E) := begin intros x hx y hy hxy a b ha hb hab, rw interior_univ, exact mem_univ _, end protected lemma strict_convex.eq (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) (h : a • x + b • y ∉ interior s) : x = y := hs.eq hx hy $ λ H, h $ H ha hb hab protected lemma strict_convex.inter {t : set E} (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s ∩ t) := begin intros x hx y hy hxy a b ha hb hab, rw interior_inter, exact ⟨hs hx.1 hy.1 hxy ha hb hab, ht hx.2 hy.2 hxy ha hb hab⟩, end lemma directed.strict_convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed (⊆) s) (hs : ∀ ⦃i : ι⦄, strict_convex 𝕜 (s i)) : strict_convex 𝕜 (⋃ i, s i) := begin rintro x hx y hy hxy a b ha hb hab, rw mem_Union at hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact interior_mono (subset_Union s k) (hs (hik hx) (hjk hy) hxy ha hb hab), end lemma directed_on.strict_convex_sUnion {S : set (set E)} (hdir : directed_on (⊆) S) (hS : ∀ s ∈ S, strict_convex 𝕜 s) : strict_convex 𝕜 (⋃₀ S) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).strict_convex_Union (λ s, hS _ s.2), end end has_scalar section module variables [module 𝕜 E] [module 𝕜 F] {s : set E} protected lemma strict_convex.convex (hs : strict_convex 𝕜 s) : convex 𝕜 s := convex_iff_pairwise_pos.2 $ λ x hx y hy hxy a b ha hb hab, interior_subset $ hs hx hy hxy ha hb hab /-- An open convex set is strictly convex. -/ protected lemma convex.strict_convex (h : is_open s) (hs : convex 𝕜 s) : strict_convex 𝕜 s := λ x hx y hy _ a b ha hb hab, h.interior_eq.symm ▸ hs hx hy ha.le hb.le hab lemma is_open.strict_convex_iff (h : is_open s) : strict_convex 𝕜 s ↔ convex 𝕜 s := ⟨strict_convex.convex, convex.strict_convex h⟩ lemma strict_convex_singleton (c : E) : strict_convex 𝕜 ({c} : set E) := pairwise_singleton _ _ lemma set.subsingleton.strict_convex (hs : s.subsingleton) : strict_convex 𝕜 s := hs.pairwise _ lemma strict_convex.linear_image [semiring 𝕝] [module 𝕝 E] [module 𝕝 F] [linear_map.compatible_smul E F 𝕜 𝕝] (hs : strict_convex 𝕜 s) (f : E →ₗ[𝕝] F) (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := begin rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ hxy a b ha hb hab, refine hf.image_interior_subset _ ⟨a • x + b • y, hs hx hy (ne_of_apply_ne _ hxy) ha hb hab, _⟩, rw [map_add, f.map_smul_of_tower a, f.map_smul_of_tower b] end lemma strict_convex.is_linear_image (hs : strict_convex 𝕜 s) {f : E → F} (h : is_linear_map 𝕜 f) (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := hs.linear_image (h.mk' f) hf lemma strict_convex.linear_preimage {s : set F} (hs : strict_convex 𝕜 s) (f : E →ₗ[𝕜] F) (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (s.preimage f) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage hf _, rw [mem_preimage, f.map_add, f.map_smul, f.map_smul], exact hs hx hy (hfinj.ne hxy) ha hb hab, end lemma strict_convex.is_linear_preimage {s : set F} (hs : strict_convex 𝕜 s) {f : E → F} (h : is_linear_map 𝕜 f) (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (s.preimage f) := hs.linear_preimage (h.mk' f) hf hfinj section linear_ordered_cancel_add_comm_monoid variables [topological_space β] [linear_ordered_cancel_add_comm_monoid β] [order_topology β] [module 𝕜 β] [ordered_smul 𝕜 β] lemma strict_convex_Iic (r : β) : strict_convex 𝕜 (Iic r) := begin rintro x (hx : x ≤ r) y (hy : y ≤ r) hxy a b ha hb hab, refine (subset_interior_iff_subset_of_open is_open_Iio).2 Iio_subset_Iic_self _, rw ←convex.combo_self hab r, obtain rfl | hx := hx.eq_or_lt, { exact add_lt_add_left (smul_lt_smul_of_pos (hy.lt_of_ne hxy.symm) hb) _ }, obtain rfl | hy := hy.eq_or_lt, { exact add_lt_add_right (smul_lt_smul_of_pos hx ha) _ }, { exact add_lt_add (smul_lt_smul_of_pos hx ha) (smul_lt_smul_of_pos hy hb) } end lemma strict_convex_Ici (r : β) : strict_convex 𝕜 (Ici r) := @strict_convex_Iic 𝕜 βᵒᵈ _ _ _ _ _ _ r lemma strict_convex_Icc (r s : β) : strict_convex 𝕜 (Icc r s) := (strict_convex_Ici r).inter $ strict_convex_Iic s lemma strict_convex_Iio (r : β) : strict_convex 𝕜 (Iio r) := (convex_Iio r).strict_convex is_open_Iio lemma strict_convex_Ioi (r : β) : strict_convex 𝕜 (Ioi r) := (convex_Ioi r).strict_convex is_open_Ioi lemma strict_convex_Ioo (r s : β) : strict_convex 𝕜 (Ioo r s) := (strict_convex_Ioi r).inter $ strict_convex_Iio s lemma strict_convex_Ico (r s : β) : strict_convex 𝕜 (Ico r s) := (strict_convex_Ici r).inter $ strict_convex_Iio s lemma strict_convex_Ioc (r s : β) : strict_convex 𝕜 (Ioc r s) := (strict_convex_Ioi r).inter $ strict_convex_Iic s lemma strict_convex_interval (r s : β) : strict_convex 𝕜 (interval r s) := strict_convex_Icc _ _ end linear_ordered_cancel_add_comm_monoid end module end add_comm_monoid section add_cancel_comm_monoid variables [add_cancel_comm_monoid E] [has_continuous_add E] [module 𝕜 E] {s : set E} /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.preimage_add_right (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, z + x) ⁻¹' s) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage (continuous_add_left _) _, have h := hs hx hy ((add_right_injective _).ne hxy) ha hb hab, rwa [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul] at h, end /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.preimage_add_left (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, x + z) ⁻¹' s) := by simpa only [add_comm] using hs.preimage_add_right z end add_cancel_comm_monoid section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] section continuous_add variables [has_continuous_add E] {s t : set E} lemma strict_convex.add (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s + t) := begin rintro _ ⟨v, w, hv, hw, rfl⟩ _ ⟨x, y, hx, hy, rfl⟩ h a b ha hb hab, rw [smul_add, smul_add, add_add_add_comm], obtain rfl | hvx := eq_or_ne v x, { refine interior_mono (add_subset_add (singleton_subset_iff.2 hv) subset.rfl) _, rw [convex.combo_self hab, singleton_add], exact (is_open_map_add_left _).image_interior_subset _ (mem_image_of_mem _ $ ht hw hy (ne_of_apply_ne _ h) ha hb hab) }, exact subset_interior_add_left (add_mem_add (hs hv hx hvx ha hb hab) $ ht.convex hw hy ha.le hb.le hab) end lemma strict_convex.add_left (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, z + x) '' s) := by simpa only [singleton_add] using (strict_convex_singleton z).add hs lemma strict_convex.add_right (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, x + z) '' s) := by simpa only [add_comm] using hs.add_left z /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.vadd (hs : strict_convex 𝕜 s) (x : E) : strict_convex 𝕜 (x +ᵥ s) := hs.add_left x end continuous_add section continuous_smul variables [linear_ordered_field 𝕝] [module 𝕝 E] [has_continuous_const_smul 𝕝 E] [linear_map.compatible_smul E E 𝕜 𝕝] {s : set E} {x : E} lemma strict_convex.smul (hs : strict_convex 𝕜 s) (c : 𝕝) : strict_convex 𝕜 (c • s) := begin obtain rfl | hc := eq_or_ne c 0, { exact (subsingleton_zero_smul_set _).strict_convex }, { exact hs.linear_image (linear_map.lsmul _ _ c) (is_open_map_smul₀ hc) } end lemma strict_convex.affinity [has_continuous_add E] (hs : strict_convex 𝕜 s) (z : E) (c : 𝕝) : strict_convex 𝕜 (z +ᵥ c • s) := (hs.smul c).vadd z end continuous_smul end add_comm_group end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring 𝕜] [topological_space E] section add_comm_group variables [add_comm_group E] [module 𝕜 E] [no_zero_smul_divisors 𝕜 E] [has_continuous_const_smul 𝕜 E] {s : set E} lemma strict_convex.preimage_smul (hs : strict_convex 𝕜 s) (c : 𝕜) : strict_convex 𝕜 ((λ z, c • z) ⁻¹' s) := begin classical, obtain rfl | hc := eq_or_ne c 0, { simp_rw [zero_smul, preimage_const], split_ifs, { exact strict_convex_univ }, { exact strict_convex_empty } }, refine hs.linear_preimage (linear_map.lsmul _ _ c) _ (smul_right_injective E hc), unfold linear_map.lsmul linear_map.mk₂ linear_map.mk₂' linear_map.mk₂'ₛₗ, exact continuous_const_smul _, end end add_comm_group end ordered_comm_semiring section ordered_ring variables [ordered_ring 𝕜] [topological_space E] [topological_space F] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s t : set E} {x y : E} lemma strict_convex.eq_of_open_segment_subset_frontier [nontrivial 𝕜] [densely_ordered 𝕜] (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (h : open_segment 𝕜 x y ⊆ frontier s) : x = y := begin obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one, classical, by_contra hxy, exact (h ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, rfl⟩).2 (hs hx hy hxy ha₀ (sub_pos_of_lt ha₁) $ add_sub_cancel'_right _ _), end lemma strict_convex.add_smul_mem (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hxy : x + y ∈ s) (hy : y ≠ 0) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : x + t • y ∈ interior s := begin have h : x + t • y = (1 - t) • x + t • (x + y), { rw [smul_add, ←add_assoc, ←add_smul, sub_add_cancel, one_smul] }, rw h, refine hs hx hxy (λ h, hy $ add_left_cancel _) (sub_pos_of_lt ht₁) ht₀ (sub_add_cancel _ _), exact x, rw [←h, add_zero], end lemma strict_convex.smul_mem_of_zero_mem (hs : strict_convex 𝕜 s) (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) (hx₀ : x ≠ 0) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : t • x ∈ interior s := by simpa using hs.add_smul_mem zero_mem (by simpa using hx) hx₀ ht₀ ht₁ lemma strict_convex.add_smul_sub_mem (h : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : x + t • (y - x) ∈ interior s := begin apply h.open_segment_subset hx hy hxy, rw open_segment_eq_image', exact mem_image_of_mem _ ⟨ht₀, ht₁⟩, end /-- The preimage of a strictly convex set under an affine map is strictly convex. -/ lemma strict_convex.affine_preimage {s : set F} (hs : strict_convex 𝕜 s) {f : E →ᵃ[𝕜] F} (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (f ⁻¹' s) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage hf _, rw [mem_preimage, convex.combo_affine_apply hab], exact hs hx hy (hfinj.ne hxy) ha hb hab, end /-- The image of a strictly convex set under an affine map is strictly convex. -/ lemma strict_convex.affine_image (hs : strict_convex 𝕜 s) {f : E →ᵃ[𝕜] F} (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := begin rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ hxy a b ha hb hab, exact hf.image_interior_subset _ ⟨a • x + b • y, ⟨hs hx hy (ne_of_apply_ne _ hxy) ha hb hab, convex.combo_affine_apply hab⟩⟩, end variables [topological_add_group E] lemma strict_convex.neg (hs : strict_convex 𝕜 s) : strict_convex 𝕜 (-s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg continuous_id.neg neg_injective lemma strict_convex.sub (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s - t) := (sub_eq_add_neg s t).symm ▸ hs.add ht.neg end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] [topological_space E] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E} {x : E} /-- Alternative definition of set strict convexity, using division. -/ lemma strict_convex_iff_div : strict_convex 𝕜 s ↔ s.pairwise (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → (a / (a + b)) • x + (b / (a + b)) • y ∈ interior s) := ⟨λ h x hx y hy hxy a b ha hb, begin apply h hx hy hxy (div_pos ha $ add_pos ha hb) (div_pos hb $ add_pos ha hb), rw ←add_div, exact div_self (add_pos ha hb).ne', end, λ h x hx y hy hxy a b ha hb hab, by convert h hx hy hxy ha hb; rw [hab, div_one] ⟩ lemma strict_convex.mem_smul_of_zero_mem (hs : strict_convex 𝕜 s) (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) (hx₀ : x ≠ 0) {t : 𝕜} (ht : 1 < t) : x ∈ t • interior s := begin rw mem_smul_set_iff_inv_smul_mem₀ (zero_lt_one.trans ht).ne', exact hs.smul_mem_of_zero_mem zero_mem hx hx₀ (inv_pos.2 $ zero_lt_one.trans ht) (inv_lt_one ht), end end add_comm_group end linear_ordered_field /-! #### Convex sets in an ordered space Relates `convex` and `set.ord_connected`. -/ section variables [topological_space E] /-- A set in a linear ordered field is strictly convex if and only if it is convex. -/ @[simp] lemma strict_convex_iff_convex [linear_ordered_field 𝕜] [topological_space 𝕜] [order_topology 𝕜] {s : set 𝕜} : strict_convex 𝕜 s ↔ convex 𝕜 s := begin refine ⟨strict_convex.convex, λ hs, strict_convex_iff_open_segment_subset.2 (λ x hx y hy hxy, _)⟩, obtain h | h := hxy.lt_or_lt, { refine (open_segment_subset_Ioo h).trans _, rw ←interior_Icc, exact interior_mono (Icc_subset_segment.trans $ hs.segment_subset hx hy) }, { rw open_segment_symm, refine (open_segment_subset_Ioo h).trans _, rw ←interior_Icc, exact interior_mono (Icc_subset_segment.trans $ hs.segment_subset hy hx) } end lemma strict_convex_iff_ord_connected [linear_ordered_field 𝕜] [topological_space 𝕜] [order_topology 𝕜] {s : set 𝕜} : strict_convex 𝕜 s ↔ s.ord_connected := strict_convex_iff_convex.trans convex_iff_ord_connected alias strict_convex_iff_ord_connected ↔ strict_convex.ord_connected _ end
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifdef _WIN32 #include "blas.c" #else #include "blas.c" // #include <cblas.h> #endif #include <moss.h> #include <objects/string.h> #include <objects/list.h> #include <modules/bs.h> #include <modules/la.h> double mf_float(mt_object* x, int* e); extern mt_table* mv_type_array; void mf_array_delete(mt_array* a){ if(a->data->refcount==1){ mf_free(a->data); }else{ a->data->refcount--; } mf_free(a); } void mf_array_dec_refcount(mt_array* a){ if(a->refcount==1){ mf_array_delete(a); }else{ a->refcount--; } } static mt_array* mf_new_array(long size, int type){ mt_array* a = mf_malloc(sizeof(mt_array)); if(type==mv_array_float){ a->data = mf_malloc(sizeof(mt_array_data)+size*sizeof(double)); }else{ abort(); } a->data->refcount = 1; a->data->type = type; a->base = a->data->a; a->refcount = 1; a->size = size; return a; } static mt_array* mf_array_copy(mt_array* a){ mt_array* b; if(a->n==2){ if(a->plain){ goto plain; }else{ unsigned long m=a->shape[0]; unsigned long n=a->shape[1]; long si=a->stride[0]; long sj=a->stride[1]; b = mf_new_array(m*n,mv_array_float); b->n = a->n; b->plain = 1; b->shape[0] = m; b->shape[1] = n; b->stride[0] = 1; b->stride[1] = m; double* pa = (double*)a->base; double* pb = (double*)b->base; unsigned long i,j,mj; long sjj; for(j=0; j<n; j++){ mj=m*j; sjj=sj*j; for(i=0; i<m; i++){ pb[i+mj]=pa[si*i+sjj]; } } return b; } }else if(a->n==1){ b = mf_new_array(a->shape[0],mv_array_float); b->n = 1; b->shape[0] = a->shape[0]; b->stride[0] = 1; cblas_dcopy(a->shape[0],(double*)a->base,a->stride[0],(double*)b->base,1); return b; }else{ if(a->plain) goto plain; abort(); } plain: b = mf_new_array(a->size,mv_array_float); b->n = a->n; b->plain = 1; unsigned long i; for(i=0; i<a->n; i++){ b->shape[i] = a->shape[i]; b->stride[i] = a->stride[i]; } cblas_dcopy(a->size,(double*)a->base,1,(double*)b->base,1); return b; } void mf_ensure_plain(mt_array* a){ if(a->n==2){ if(a->plain) return; mt_array_data* data = mf_malloc(sizeof(mt_array_data)+a->size*sizeof(double)); data->refcount = 1; data->type = mv_array_float; double* pa = (double*)a->base; double* pb = (double*)data->a; unsigned long m = a->shape[0]; unsigned long n = a->shape[1]; long si = a->stride[0]; long sj = a->stride[1]; unsigned long i,j,mj; long sjj; for(j=0; j<n; j++){ mj = m*j; sjj = sj*j; for(i=0; i<m; i++){ pb[i+mj] = pa[si*i+sjj]; } } if(a->data->refcount==1){ mf_free(a->data); }else{ a->data->refcount--; } a->stride[0] = 1; a->stride[1] = m; a->data = data; a->base = data->a; a->plain = 1; }else if(a->n==1){ abort(); }else{ if(a->plain) return; abort(); } } static mt_array* mf_array_map_dd(mt_array* a, double(*f)(double)){ mt_array* b; if(a->n==2){ if(a->plain){ goto plain; }else{ unsigned long m = a->shape[0]; unsigned long n = a->shape[1]; long si = a->stride[0]; long sj = a->stride[1]; b = mf_new_array(m*n,mv_array_float); b->n = a->n; b->plain = 1; b->shape[0] = m; b->shape[1] = n; b->stride[0] = 1; b->stride[1] = m; double* pa = (double*)a->base; double* pb = (double*)b->base; unsigned long i,j,mj; long sjj; for(j=0; j<n; j++){ mj = m*j; sjj = sj*j; for(i=0; i<m; i++){ pb[i+mj] = f(pa[si*i+sjj]); } } return b; } }else if(a->n==1){ unsigned long n=a->shape[0]; b = mf_new_array(n,mv_array_float); b->n = 1; b->shape[0] = n; b->stride[0] = 1; long s = a->stride[0]; unsigned long k; double* pa = (double*)a->base; double* pb = (double*)b->base; for(k=0; k<n; k++){ pb[k] = f(pa[k*s]); } return b; }else{ if(a->plain) goto plain; abort(); } plain: b = mf_new_array(a->size,mv_array_float); b->n = a->n; b->plain = 1; unsigned long i; for(i=0; i<a->n; i++){ b->shape[i] = a->shape[i]; b->stride[i] = a->stride[i]; } double* pa = (double*)a->base; double* pb = (double*)b->base; unsigned long size = a->size; unsigned long k; for(k=0; k<size; k++){ pb[k] = f(pa[k]); } return b; } long mf_array_size(mt_array* a){ long p; unsigned long k; switch(a->n){ case 1: return a->shape[0]; case 2: return a->shape[0]*a->shape[1]; default: p=1; for(k=0; k<a->n; k++){ p = p*a->shape[k]; } return p; } } mt_array* mf_array(long size, mt_object* v){ mt_array* a; if(size>0 && v[0].type==mv_list){ long i,j; mt_list* list = (mt_list*)v[0].value.p; long n = list->size; a = mf_new_array(size*n,mv_array_float); a->n = 2; a->shape[0] = size; a->shape[1] = n; a->stride[0] = 1; a->stride[1] = size; a->plain = 1; double* b = (double*)a->base; int e=0; for(i=0; i<size; i++){ if(v[i].type!=mv_list) abort(); list = (mt_list*)v[i].value.p; if(list->size!=n) abort(); for(j=0; j<n; j++){ b[i+size*j] = mf_float(list->a+j,&e); if(e) abort(); } } }else{ a = mf_new_array(size,mv_array_float); a->n = 1; a->shape[0] = size; a->stride[0] = 1; long i; double* b = (double*)a->base; int e=0; for(i=0; i<size; i++){ b[i] = mf_float(v+i,&e); } } return a; } int la_array(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"array"); return 1; } if(v[1].type!=mv_list){ mf_type_error1("in array(a): a (type: %s) is not a list.",v+1); return 1; } mt_list* list = (mt_list*)v[1].value.p; mt_array* a = mf_array(list->size, list->a); if(a==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } int la_vector(mt_object* x, int argc, mt_object* v){ mt_array* a = mf_array(argc,v+1); if(a==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } int la_matrix(mt_object* x, int argc, mt_object* v){ mt_array* a = mf_array(argc,v+1); if(a==NULL) return 1; if(a->n==1){ a->n = 2; unsigned long size = a->shape[0]; a->shape[0] = size; a->shape[1] = 1; a->stride[0] = 1; a->stride[1] = size; a->plain = 0; } x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } static void vector_str(mt_bs* bs, mt_array* T){ char buffer[100]; unsigned long i; double* a = (double*)T->base; unsigned long size = T->shape[0]; long step = T->stride[0]; mf_bs_push_cstr(bs,"["); for(i=0; i<size; i++){ snprintf(buffer,100,i==0?"%.4g":", %.4g",a[step*i]); mf_bs_push_cstr(bs,buffer); } mf_bs_push_cstr(bs,"]"); } static void matrix_str(mt_bs* bs, mt_array* T){ char buffer[100]; unsigned long i,j; double* a = (double*)T->base; unsigned long m,n,is,js; m = T->shape[0]; n = T->shape[1]; is = T->stride[0]; js = T->stride[1]; int max = 0; int size; for(i=0; i<m; i++){ for(j=0; j<n; j++){ size = snprintf(buffer,100,"%.4g",a[i*is+j*js]); if(size>max) max=size; } } mf_bs_push_cstr(bs,"["); for(i=0; i<m; i++){ mf_bs_push_cstr(bs,i==0? "[": ",\n ["); for(j=0; j<n; j++){ snprintf(buffer,100,j==0?"%*.4g":", %*.4g",max,a[i*is+j*js]); mf_bs_push_cstr(bs,buffer); } mf_bs_push_cstr(bs,"]"); } mf_bs_push_cstr(bs,"]"); } static int array_str(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"array.type.str"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.str(): a (type: %s) is not an array.",&v[0]); return 1; } mt_array* T = (mt_array*)v[0].value.p; mt_bs bs; mf_bs_init(&bs); if(T->n==1){ vector_str(&bs,T); }else if(T->n==2){ matrix_str(&bs,T); }else{ abort(); } x->type = mv_string; x->value.p = (mt_basic*)mf_str_new(bs.size,(const char*)bs.a); mf_free(bs.a); return 0; } static int array_list(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"array.type.list"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.list(): a (type: %s) is not an array.",&v[0]); return 1; } mt_array* T = (mt_array*)v[0].value.p; mt_list* list = mf_raw_list(T->size); unsigned long i; double* a = (double*)T->base; unsigned long size = T->shape[0]; long step = T->stride[0]; for(i=0; i<size; i++){ list->a[i].type = mv_float; list->a[i].value.f = a[step*i]; } x->type = mv_list; x->value.p = (mt_basic*)list; return 0; } double addc; double add(double x){ return x+addc; } double subc; double sub(double x){ return x-subc; } static int array_add(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.add"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a+b: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_array* c; if(v[1].type!=mv_array){ int e = 0; addc = mf_float(&v[1],&e); if(e){ mf_type_error1("in a+r: cannot convert r (type: %s) to float.",&v[1]); return 1; } c = mf_array_map_dd(a,add); if(c==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } mt_array* b = (mt_array*)v[1].value.p; if(a->n!=b->n){ mf_value_error("value error in a+b: a and b have unequal order."); return 1; } if(a->n==1){ unsigned long size=a->shape[0]; if(size!=b->shape[0]){ mf_value_error("Value error in a+b: a and b have unequal shape."); return 1; } c = mf_new_array(size,mv_array_float); c->n = 1; c->stride[0] = 1; c->shape[0] = size; cblas_dcopy(size,(double*)a->base,a->stride[0],(double*)c->base,1); cblas_daxpy(size,1,(double*)b->base,b->stride[0],(double*)c->base,1); }else{ unsigned long i; for(i=0; i<a->n; i++){ if(a->shape[i]!=b->shape[i]) abort(); } c = mf_array_copy(a); mf_ensure_plain(b); cblas_daxpy(c->size,1,(double*)b->base,1,(double*)c->base,1); } x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } static int array_radd(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.radd"); return 1; } if(v[1].type!=mv_array){ mf_type_error1("in r*a: a (type: %s) is not an array.",&v[1]); return 1; } int e = 0; addc = mf_float(&v[0],&e); if(e){ mf_type_error1("in r+a: cannot convert r (type: %s) to float.",&v[0]); return 1; } mt_array* a = (mt_array*)v[1].value.p; mt_array* y = mf_array_map_dd(a,add); if(y==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)y; return 0; } static int array_sub(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.sub"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a-b: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_array* c; if(v[1].type!=mv_array){ int e = 0; subc = mf_float(&v[1],&e); if(e){ mf_type_error1("in a-r: cannot convert r (type: %s) to float.",&v[1]); return 1; } c = mf_array_map_dd(a,sub); if(c==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } mt_array* b = (mt_array*)v[1].value.p; if(a->n==1){ unsigned long size = a->shape[0]; if(size!=b->shape[0]){ mf_value_error("Value error in a-b: a and b have unequal shape."); return 1; } c = mf_new_array(size,mv_array_float); c->n = 1; c->shape[0] = size; c->stride[0] = 1; cblas_dcopy(size,(double*)a->base,a->stride[0],(double*)c->base,1); cblas_daxpy(size,-1,(double*)b->base,b->stride[0],(double*)c->base,1); }else{ unsigned long i; for(i=0; i<a->n; i++){ if(a->shape[i]!=b->shape[i]) abort(); } c = mf_array_copy(a); mf_ensure_plain(b); cblas_daxpy(c->size,-1,(double*)b->base,1,(double*)c->base,1); } x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } static mt_array* mf_array_scal(double r, mt_array* a){ mt_array* b; if(a->n==1){ unsigned long size = a->shape[0]; b = mf_new_array(size,mv_array_float); b->n = 1; b->shape[0] = size; b->stride[0] = 1; cblas_dcopy(size,(double*)a->base,a->stride[0],(double*)b->base,1); }else{ b = mf_array_copy(a); } cblas_dscal(b->size,r,(double*)b->base,1); return b; } static mt_array* array_mpy_array(mt_array* a, mt_array* b){ if(b->n==1){ unsigned long m = a->shape[0]; unsigned long n = a->shape[1]; if(n!=b->shape[0]){ mf_value_error("Value error in A*x: shape does not match."); return NULL; } if(a->stride[0]!=1){ mf_ensure_plain(a); } mt_array* c = mf_new_array(m,mv_array_float); c->n = 1; c->shape[0] = m; c->stride[0] = 1; cblas_dgemv(CblasColMajor,CblasNoTrans,m,n,1, (double*)a->base, a->stride[1], (double*)b->base, b->stride[0], 0,(double*)c->base,1 ); return c; }else if(b->n==2){ if(a->n==2){ if(a->shape[1]!=b->shape[0]){ mf_value_error("Value error in A*B: incompatible matrices."); return NULL; } if(a->stride[0]!=1){ mf_ensure_plain(a); } if(b->stride[0]!=1){ mf_ensure_plain(b); } unsigned long m = a->shape[0]; unsigned long k = a->shape[1]; unsigned long n = b->shape[1]; mt_array* c = mf_new_array(m*n,mv_array_float); c->n = 2; c->shape[0] = m; c->shape[1] = n; c->stride[0] = 1; c->stride[1] = m; c->plain = 1; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1, (double*)a->base, a->stride[1], (double*)b->base, b->stride[1], 0, (double*)c->base, m ); return c; }else{ abort(); } }else{ abort(); } } static mt_array* matrix_identity(unsigned long n){ mt_array* a = mf_new_array(n*n,mv_array_float); a->n = 2; a->plain = 1; a->shape[0] = n; a->shape[1] = n; a->stride[0] = 1; a->stride[1] = n; double* b = (double*)a->base; unsigned long i,j,nj; for(j=0; j<n; j++){ nj = n*j; for(i=0; i<n; i++){ b[i+nj] = i==j? 1: 0; } } return a; } static mt_array* square_matrix_mpy(mt_array* a, mt_array* b){ if(a->stride[0]!=1){ mf_ensure_plain(a); } if(b->stride[0]!=1){ mf_ensure_plain(b); } unsigned long n = a->shape[0]; mt_array* c = mf_new_array(n*n,mv_array_float); c->n = 2; c->shape[0] = n; c->shape[1] = n; c->stride[0] = 1; c->stride[1] = n; c->plain = 1; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1, (double*)a->base, a->stride[1], (double*)b->base, b->stride[1], 0, (double*)c->base, n ); return c; } static mt_array* square_matrix_pow(mt_array* a, unsigned long n){ if(n==0){ return matrix_identity(a->shape[0]); } mt_array *p,*h; p = mf_array_copy(a); a = p; a->refcount++; n--; while(n){ if(n&1){ h = p; p = square_matrix_mpy(p,a); mf_array_dec_refcount(h); } n>>=1; if(n==0) break; h = a; a = square_matrix_mpy(a,a); mf_array_dec_refcount(h); } mf_array_dec_refcount(a); return p; } static int array_mul(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.mul"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a*b: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_array* b; double r; if(v[1].type==mv_array){ b=(mt_array*)v[1].value.p; if(a->n==2){ if(b->n==2 && a->shape[0]==1 && b->shape[1]==1){ if(a->shape[1]!=b->shape[0]){ mf_value_error("Value error in a*b: incompatible matrices."); return 1; } // todo: strides r = cblas_ddot(a->shape[1], (double*)a->base,a->stride[1], (double*)b->base,b->stride[0] ); x->type = mv_float; x->value.f = r; return 0; } mt_array* c = array_mpy_array(a,b); if(c==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } if(a->n!=1){ mf_value_error("Value error in a*b: a and b have incompatible shape."); return 1; } if(b->n==2){ mt_array* c = array_mpy_array(b,a); if(c==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } if(a->shape[0]!=b->shape[0]){ mf_value_error("Value error in a*b: a and b have unequal shape."); return 1; } r = cblas_ddot(a->shape[0], (double*)a->base,a->stride[0], (double*)b->base,b->stride[0] ); x->type = mv_float; x->value.f = r; return 0; }else{ int e = 0; r = mf_float(&v[1],&e); if(e){ mf_type_error1("in a*r: cannot convert r (type: %s) to float.",&v[1]); return 1; } x->type = mv_array; x->value.p = (mt_basic*)mf_array_scal(r,a); return 0; } } static int array_pow(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.pow"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a^n: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; double r; if(a->n!=1){ if(a->n==2 && v[1].type==mv_int){ long n = v[1].value.i; if(a->shape[0]!=a->shape[1]){ mf_value_error("Value error in A^n: A is not a square matrix"); return 1; } x->type = mv_array; x->value.p = (mt_basic*)square_matrix_pow(a,(unsigned long)n); return 0; } mf_value_error("Value error in a^n: a is not a vector."); return 1; } r = cblas_ddot(a->shape[0], (double*)a->base,a->stride[0], (double*)a->base,a->stride[0] ); x->type = mv_float; if(v[1].type==mv_int && v[1].value.i==2){ x->value.f = r; }else{ int e = 0; double n = mf_float(&v[1],&e); if(e){ mf_type_error1("in a^n: cannot convert n (type: %s) to float.",&v[1]); return 1; } x->value.f = pow(r,n); } return 0; } static int array_rmul(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.rmul"); return 1; } if(v[1].type!=mv_array){ mf_type_error1("in r*a: a (type: %s) is not an array.",&v[1]); return 1; } int e=0; double r = mf_float(&v[0],&e); if(e){ mf_type_error1("in r*a: cannot convert r (type: %s) to float.",&v[0]); return 1; } mt_array* a = (mt_array*)v[1].value.p; x->type = mv_array; x->value.p = (mt_basic*)mf_array_scal(r,a);; return 0; } static int array_neg(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"Array.neg"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in -a: a (type: %s) is not an array.",&v[1]); return 1; } mt_array* a = (mt_array*)v[0].value.p; x->type = mv_array; x->value.p = (mt_basic*)mf_array_scal(-1,a);; return 0; } static int array_div(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.div"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a/r: a (type: %s) is not an array.",&v[1]); return 1; } int e = 0; double r = mf_float(&v[1],&e); if(e){ mf_type_error1("in a/r: cannot convert r (type: %s) to float.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; x->type = mv_array; x->value.p = (mt_basic*)mf_array_scal(1/r,a);; return 0; } static int array_T(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"array.type.T"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.T(): a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; if(a->n==2){ mt_array* b = mf_malloc(sizeof(mt_array)); b->refcount = 1; b->n = 2; a->data->refcount++; b->data = a->data; b->base = a->base; b->size = a->size; b->plain = 0; b->shape[0] = a->shape[1]; b->shape[1] = a->shape[0]; b->stride[0] = a->stride[1]; b->stride[1] = a->stride[0]; x->type = mv_array; x->value.p = (mt_basic*)b; }else{ a->refcount++; x->type = mv_array; x->value.p = (mt_basic*)a; } return 0; } static int array_plain(mt_object* x, int argc, mt_object* v){ if(v[0].type!=mv_array) abort(); mt_array* a = (mt_array*)v[0].value.p; mf_ensure_plain(a); a->refcount++; x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } static int array_copy(mt_object* x, int argc, mt_object* v){ if(v[0].type!=mv_array) abort(); mt_array* a = (mt_array*)v[0].value.p; x->type = mv_array; x->value.p = (mt_basic*)mf_array_copy(a); return 0; } static mt_array* vector_slice(mt_array* a, mt_range* r){ long i,j; if(r->a.type!=mv_int || r->b.type!=mv_int){ mf_type_error("Type error in a[r]: r is not an integer range."); return NULL; } i = r->a.value.i; j = r->b.value.i; unsigned long n = a->shape[0]; if(i<0 || j<0){ mf_value_error("Value error in a[r]: range with negative values."); return NULL; } if((unsigned long)i>=n || (unsigned long)j>=n){ mf_value_error("Value error in a[r]: range is out of bounds."); return NULL; } mt_array* b = mf_malloc(sizeof(mt_array)); b->refcount = 1; b->size = a->size; a->data->refcount++; b->data = a->data; a->data = b->data; b->n = 1; b->base = (unsigned char*)((double*)a->base+a->stride[0]*i); b->shape[0] = j-i+1; b->stride[0] = a->stride[0]; return b; } static int array_get(mt_object* x, int argc, mt_object* v){ if(v[0].type!=mv_array){ mf_type_error1("in a[i]: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; if(argc==1){ if(a->n!=1){ mf_value_error("Value error in a[i]: a is not a vector."); return 1; } if(v[1].type!=mv_int){ if(v[1].type==mv_range){ mt_array* b = vector_slice(a,(mt_range*)v[1].value.p); if(b==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)b; return 0; } mf_type_error1("in a[i]: i (type: %s) is not an integer.",&v[1]); return 1; } long index = v[1].value.i; unsigned long n = a->shape[0]; if(index<0 || (unsigned long)index>=n){ mf_value_error("Value error in a[i]: i is out of bounds."); return 1; } double* b = (double*)a->base; double t = b[index*a->stride[0]]; x->type = mv_float; x->value.f = t; return 0; }else{ mf_argc_error(argc,1,1,"Array.get"); return 1; } } static int la_idm(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"idm"); return 1; } if(v[1].type!=mv_int){ mf_type_error1("in idm(n): n (type: %s) is not an integer.",v+1); return 1; } long n = v[1].value.i; x->type = mv_array; x->value.p = (mt_basic*)matrix_identity(n); return 0; } static mt_array* diag(mt_array* v){ if(v->n!=1){ mf_value_error("Value error in diag(v): v is not a vector."); return NULL; } unsigned long n = v->shape[0]; mt_array* a = mf_new_array(n*n,mv_array_float); a->n = 2; a->plain = 1; a->shape[0] = n; a->shape[1] = n; a->stride[0] = 1; a->stride[1] = n; double* b = (double*)a->base; double* vb = (double*)v->base; long vs = v->stride[0]; unsigned long i,j,nj; for(j=0; j<n; j++){ nj = n*j; for(i=0; i<n; i++){ b[i+nj] = i==j? vb[i*vs]: 0; } } return a; } static int la_diag(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"diag"); return 1; } if(v[1].type!=mv_array){ mf_type_error1("in diag(a): a is not an array.",v+1); return 1; } mt_array* u = (mt_array*)v[1].value.p; mt_array* a = diag(u); if(a==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } static mt_array* diag_slice(mt_array* a){ if(a->n!=2 || a->shape[0]!=a->shape[1]){ mf_value_error("Value error in a.diag(): a is not an quadratic matrix."); return NULL; } if(a->stride[1]!=1){ mf_ensure_plain(a); } mt_array* v = mf_malloc(sizeof(mt_array)); v->refcount = 1; v->n = 1; a->data->refcount++; v->data = a->data; v->base = a->base; v->shape[0] = a->shape[0]; v->stride[0] = (a->shape[0]+1)*a->stride[0]; return v; } static int array_diag(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"diag"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.diag(): a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_array* u = diag_slice(a); if(u==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)u; return 0; } int mf_array_map(mt_array* a, mt_function* f){ mt_object argv[2]; argv[0].type = mv_null; double* ba = (double*)a->base; long size = a->size; long i; mt_object x; int e = 0; for(i=0; i<size; i++){ argv[1].type = mv_float; argv[1].value.f = ba[i]; if(mf_call(f,&x,1,argv)){ mf_traceback("map"); return 1; } ba[i] = mf_float(&x,&e); if(e){ mf_type_error1("in a.map(f): cannot convert f(a[k]) (type: %s) to float.",&x); return 1; } } return 0; } static int array_map(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"map"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.map(f): a (type: %s) is not an array.",&v[0]); return 1; } if(v[1].type!=mv_function){ mf_type_error1("in a.map(f): f (type: %s) is not a function.",&v[1]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_function* f = (mt_function*)v[1].value.p; mt_array* b = mf_array_copy(a); if(mf_array_map(b,f)) return 1; x->type = mv_array; x->value.p = (mt_basic*)b; return 0; } static int mf_trace(mt_object* x, mt_array* a){ if(a->n!=2 || a->shape[0]!=a->shape[1]){ mf_value_error("Value error in trace(a): a is not a quadratic matrix."); return 1; } double s = 0; long n = a->shape[0]; double* ba = (double*)a->base; long i,m; m = a->stride[0]+a->stride[1]; for(i=0; i<n; i++){ s+=ba[i*m]; } x->type = mv_float; x->value.f = s; return 0; } static int la_trace(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"trace"); return 1; } if(v[1].type!=mv_array){ mf_type_error1("in la.trace(a): a (type: %s) is not an array.",&v[1]); return 1; } mt_array* a = (mt_array*)v[1].value.p; if(mf_trace(x,a)) return 1; return 0; } mt_table* mf_la_load(){ mt_map* m = mv_type_array->m; mf_insert_function(m,0,0,"str",array_str); mf_insert_function(m,0,0,"list",array_list); mf_insert_function(m,1,1,"add",array_add); mf_insert_function(m,1,1,"radd",array_radd); mf_insert_function(m,1,1,"sub",array_sub); mf_insert_function(m,1,1,"mul",array_mul); mf_insert_function(m,1,1,"rmul",array_rmul); mf_insert_function(m,0,0,"neg",array_neg); mf_insert_function(m,1,1,"div",array_div); mf_insert_function(m,1,1,"pow",array_pow); mf_insert_function(m,1,-1,"get",array_get); mf_insert_function(m,0,0,"T",array_T); mf_insert_function(m,0,0,"plain",array_plain); mf_insert_function(m,0,0,"copy",array_copy); mf_insert_function(m,0,0,"diag",array_diag); mf_insert_function(m,1,1,"map",array_map); mt_table* la = mf_table(NULL); la->name = mf_cstr_to_str("module la"); la->m = mf_empty_map(); m = la->m; mf_insert_function(m,1,1,"array",la_array); mf_insert_function(m,1,1,"vector",la_vector); mf_insert_function(m,1,1,"matrix",la_matrix); mf_insert_function(m,1,1,"idm",la_idm); mf_insert_function(m,1,1,"diag",la_diag); mf_insert_function(m,1,1,"trace",la_trace); m->frozen = 1; return la; }
## Thanks: Colin O'Rourke <[email protected]> require(Hmisc) d = data.frame( CaseNum = 1:20, Status = c("Dead", "Dead", "Dead", "Dead", "Alive", "Alive", "Alive", "Dead", "Dead", "Dead", "Dead", "Dead", "Alive", "Alive", "Alive", "Dead", "Dead", "Dead", "Alive", "Dead"), Cause1 = c("Bloating", "Heart", "Age", "Sepsis", NA, NA, NA, "Age", "Bloating", "Sepsis", "Heart", "Heart", NA, NA, NA, "Cancer", "Sepsis", "Heart", NA, "Age"), Cause2 = c("", "Age", "Bloating", "Dog bite", NA, NA, NA, "Fright", "Sepsis", "Age", "Bloating", "Cancer", NA, NA, NA, "Heart", "Dog bite", "", NA, "Dog bite"), Cause3 = c("", "", "", "Trauma", NA, NA, NA, "", "Trauma", "", "Trauma", "", NA, NA, NA, "", "", "", NA, "")) # The data created from the R code above has patient status (alive/dead) and # if dead, what the cause or causes of death are. Patients who are alive have a # causes set to missing. # Turn the causes of death in a variable of class “mChoice”. d$Cause = with(d, mChoice(Cause1, Cause2, Cause3, label="Cause of death")) sum(is.na(d$Cause)) summary(~ Cause, data=d) summary(~ Cause, data=subset(d, Status == 'Dead')) # Notice how NA is tabulated as part of the summary, and how it appears as # the most common combination of causes. Now, I would like to summarise the # frequency of each cause, marginal on the other causes. # This gives the following summary table (output in table 1): # Not only is NA tabulated in the summary, but the percentages are out of the # full 20 patients, rather than only the 13 patient who died. # FH response: mChoice intended for the NA to be something like "none" or "", and to get the proportions # you want you need to subset the data as above on Status == 'Dead'
module Signal where import Data.Complex as C import FFT import Utils -- Hann window function. -- scipy.signal.hann -- https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.hann.html hann :: (Floating a) => Int -> [a] hann n = [0.5 - 0.5 * cos ((2 * pi * i) / (n' - 1)) | i <- map fromIntegral [0..n-1]] where n' = fromIntegral n -- Welch Power Spectral Density (PSD) Estimation. -- scipy.signal.welch -- https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.welch.html -- -- xs: Timeseries data -- windowSize: Length of each window to compute FFT. -- overlap: Number of points to overlap between windows. -- Returns a tuple of sample frequencies and the power spectral density of xs -- -- Unlike the scipy implementation, returns PSD corresponding to all frequencies -- (including those of the negative frequencies, which are simply duplicates of -- the positive frequencies for real data). welch :: (RealFloat a) => [a] -> Int -> Int -> ([a], [a]) welch xs windowSize overlap = (fftfreq windowSize 1.0, welchPsd) where welchPsd = map (/ norm) $ sumFrequencies $ magnitudeSquared <$> rfft <$> applyHann <$> windows norm = hannWindowNorm * (fromIntegral . length $ windows) -- sum powers over all windows correponding to the frequency bins sumFrequencies = foldr (zipWith (+)) (repeat 0) -- compute square magnitude of frequencies computed by FFT for a given window magnitudeSquared fs = (^2) . C.magnitude <$> fs -- multiply by Hann windowing function for a given data window applyHann window = zipWith (*) hannWindow window -- create windows of size exactly `windowSize` with the specified overlap windows = filter (\w -> length w == windowSize) [slice start windowSize xs | start <- [0,stride..n-1]] slice start len = drop start . take (start + len) n = length xs stride = windowSize - overlap -- Hann window function of length `windowSize` hannWindow = hann windowSize hannWindowNorm = sum $ (^2) <$> hannWindow