Datasets:
AI4M
/

text
stringlengths
0
3.34M
# clear workspace rm(list=ls()) # load libraries library(ggplot2) library(ggthemes) library(plyr) library(cowplot) # working directory setwd("D:/Projects/Boids/Assets/R") # data 5 dfA5 <- data.frame(dfA5 <- read.table("5/A.csv",sep=",",header = TRUE)) dfA5 <- cbind(dfA5, type="Naivno iskanje") dfKD5 <- data.frame(dfKD5 <- read.table("5/KD.csv",sep=",",header = TRUE)) dfKD5 <- cbind(dfKD5, type="KD Drevo") dfSP5 <- data.frame(dfSP5 <- read.table("5/SP.csv",sep=",",header = TRUE)) dfSP5 <- cbind(dfSP5, type="Razdelitev prostora") # data 10 dfA10 <- data.frame(dfA10 <- read.table("10/A.csv",sep=",",header = TRUE)) dfA10 <- cbind(dfA10, type="Naivno iskanje") dfKD10 <- data.frame(dfKD10 <- read.table("10/KD.csv",sep=",",header = TRUE)) dfKD10 <- cbind(dfKD10, type="KD Drevo") dfSP10 <- data.frame(dfSP10 <- read.table("10/SP.csv",sep=",",header = TRUE)) dfSP10 <- cbind(dfSP10, type="Razdelitev prostora") # toss first X frames X = 15; dfA5 <- dfA5[dfA5$frame > X,] dfSP5 <- dfSP5[dfSP5$frame > X,] dfKD5 <- dfKD5[dfKD5$frame > X,] dfA10 <- dfA10[dfA10$frame > X,] dfSP10 <- dfSP10[dfSP10$frame > X,] dfKD10 <- dfKD10[dfKD10$frame > X,] # merge df df5 <- rbind(dfA5,dfKD5) df5 <- rbind(df5,dfSP5) df10 <- rbind(dfA10,dfKD10) df10 <- rbind(df10,dfSP10) # CI5 dfCI5 <- ddply(df5, .(N,type), summarize, mean=mean(fps), l=quantile(fps, 0.025), h=quantile(fps, c(0.975))) p1 <- ggplot(data=dfCI5,aes(x=N,y=mean,colour=type,fill=type)) + geom_smooth(se = TRUE, size = .5, show.legend=FALSE, method = "gam", formula = y ~ s(log(x))) + geom_smooth(se = FALSE, size = .5, method = "gam", formula = y ~ s(log(x))) + theme_minimal() + labs(title = expression(paste(r[c], " = 5 m")), x = "Number of agents", y = "FPS") + theme(legend.title=element_blank(), legend.position="bottom") + theme(plot.title = element_text(hjust = 0.5)) + scale_y_continuous(breaks=c(0, 30, 60, 90, 120)) + scale_colour_colorblind() + scale_fill_colorblind() + coord_cartesian(ylim=c(0, 120)) # CI10 dfCI10 <- ddply(df10, .(N,type), summarize, mean=mean(fps), l=quantile(fps, 0.025), h=quantile(fps, c(0.975))) p2 <- ggplot(data=dfCI10,aes(x=N,y=mean,colour=type,fill=type)) + geom_smooth(se = TRUE, size = .5, show.legend=FALSE, method = "gam", formula = y ~ s(log(x))) + geom_smooth(se = FALSE, size = .5, method = "gam", formula = y ~ s(log(x))) + theme_minimal() + labs(title = expression(paste(r[c], " = 10 m")), x = "Number of agents", y = "FPS") + theme(legend.title=element_blank(), legend.position="bottom") + theme(plot.title = element_text(hjust = 0.5)) + scale_y_continuous(breaks=c(0, 30, 60, 90, 120)) + scale_colour_colorblind() + scale_fill_colorblind() + coord_cartesian(ylim=c(0, 120)) p_grid <- plot_grid(p1 + theme(legend.position="none"), p2 + theme(legend.position="none"), ncol = 1, nrow = 2, scale = 0.9) legend <- get_legend(p1) p <- plot_grid(p_grid, legend, ncol = 1, rel_heights = c(1, .1)) ggsave("figResults.pdf", p, width = 16, height = 12, units = "cm")
Free download Helicopter With Lightning Plane HD Wallpaper in hd resolution from World Wide Wallpapers. Click on above wallpaper to see its full size. You can download Helicopter With Lightning Plane HD Wallpaper by clicking on "Download Original" button and make this wallpaper as background for your desktop pc, laptop, mac or tablet.
module Issue308a where data D : Set where d : D → D syntax d x = d d x f : D → D f x = d d x
open import Data.Product using (∃; ∃-syntax; _×_; _,_) open import DeBruijn open import Parallel open import Beta open import Takahashi par-triangle : ∀ {n} {M N : Term n} → M ⇉ N ------- → N ⇉ M * par-triangle {M = # x} ⇉-c = ⇉-c par-triangle {M = ƛ M} (⇉-ƛ M⇉N) = ⇉-ƛ (par-triangle M⇉N) par-triangle {M = (ƛ M) · N} (⇉-β M⇉M′ N⇉N′) = sub-par (par-triangle M⇉M′) (par-triangle N⇉N′) par-triangle {M = # _ · N} (⇉-ξ M⇉M′ N⇉N′) = ⇉-ξ (par-triangle M⇉M′) (par-triangle N⇉N′) par-triangle {M = _ · _ · N} (⇉-ξ M⇉M′ N⇉N′) = ⇉-ξ (par-triangle M⇉M′) (par-triangle N⇉N′) par-triangle {M = (ƛ _) · N} (⇉-ξ (⇉-ƛ M⇉M′) N⇉N′) = ⇉-β (par-triangle M⇉M′) (par-triangle N⇉N′) par-diamond : ∀ {n} {M A B : Term n} → M ⇉ A → M ⇉ B ---------------------- → ∃[ N ] (A ⇉ N × B ⇉ N) par-diamond {M = M} M⇉A M⇉B = M * , par-triangle M⇉A , par-triangle M⇉B strip : ∀ {n} {M A B : Term n} → M ⇉ A → M ⇉* B ------------------------ → ∃[ N ] (A ⇉* N × B ⇉ N) strip {A = A} M⇉A (M ∎) = A , (A ∎) , M⇉A strip {A = A} M⇉A (M ⇉⟨ M⇉M′ ⟩ M′⇉*B) with par-diamond M⇉A M⇉M′ ... | N , A⇉N , M′⇉N with strip M′⇉N M′⇉*B ... | N′ , N⇉*N′ , B⇉N′ = N′ , (A ⇉⟨ A⇉N ⟩ N⇉*N′) , B⇉N′ par-confluence : ∀ {n} {M A B : Term n} → M ⇉* A → M ⇉* B ------------------------ → ∃[ N ] (A ⇉* N × B ⇉* N) par-confluence {B = B} (M ∎) M⇉*B = B , M⇉*B , (B ∎) par-confluence {B = B} (M ⇉⟨ M⇉A ⟩ A⇉*A′) M⇉*B with strip M⇉A M⇉*B ... | N , A⇉*N , B⇉N with par-confluence A⇉*A′ A⇉*N ... | N′ , A′⇉*N′ , N⇉*N′ = N′ , A′⇉*N′ , (B ⇉⟨ B⇉N ⟩ N⇉*N′) confluence : ∀ {n} {M A B : Term n} → M —↠ A → M —↠ B ------------------------ → ∃[ N ] (A —↠ N × B —↠ N) confluence M—↠A M—↠B with par-confluence (betas-pars M—↠A) (betas-pars M—↠B) ... | N , A⇉*N , B⇉*N = N , pars-betas A⇉*N , pars-betas B⇉*N
\section{The installation procedure} \label{instproc} In order to install a system the following steps are to be performed: \begin{enumerate} \item Go in the {\tt make} directory. \item {\bf [optional]} Edit the file {\tt host.lsp} and set the values of host-dependent variables. \item Run the Common Lisp you are provided of. \item Load the file {\tt install.lsp}. \item {\bf [optional]} If you didn't edit the file {\tt host.lsp} (step 2), call the form: % \begin{itemize} \item {\tt (configure)} \end{itemize} % to set the values of host-dependent variables. \item At LISP prompt type one of the following three forms: % \begin{itemize} \item {\tt (MAKE-HGKM)} \item {\tt (MAKE-GETFOL)} \item {\tt (MAKE-AGETFOL)} \end{itemize} % if you want to install {\tt HGKM}, {\tt GETFOL} or {\tt AGETFOL} respectively. \item After all the files have been successfully loaded type at the LISP prompt the following form: % \begin{itemize} \item {\tt (SYSTEM-SAVE {\it filename})} \end{itemize} % This saves the {\it image} of the whole environment onto a file named {\it filename}\footnote{ {\it filename} must be a string. }: this allows you to recall the system simply by running the executable file stored in {\it filename} without the need of reloading all the object files into the Common Lisp environment. \end{enumerate} The configuration files for the {\tt HGKM}, {\tt GETFOL} and {\tt AGETFOL} systems are provided in a standard form. Before altering the configuration file of a system or a module we recommend that you read section~\ref{sysmod} of this manual carefully.
-- | Data structure of compiler. https://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/ module LispVal ( LispVal(..) , Env , unwordsList ) where import Data.Complex import Data.IORef import Data.Ratio (denominator, numerator) import ErrorCheckingAndExceptions import System.IO (Handle) data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Integer | Float Double | Ratio Rational | Complex (Complex Double) | Character Char | String String | Bool Bool | PrimitiveFunc ([LispVal] -> ThrowsError LispVal) | Func { params :: [String], vararg :: Maybe String, body :: [LispVal], closure :: Env} | IOFunc ([LispVal] -> IOThrowsError LispVal) | Port Handle showVal :: LispVal -> String showVal (Atom x) = x showVal (Bool True) = "#t" showVal (Bool False) = "#f" showVal (Ratio x) = show (numerator x) ++ ('/' : show (denominator x)) showVal (Complex x) = show (realPart x) ++ ('+' : show (imagPart x) ++ "i") showVal (Float x) = show x showVal (Number x) = show x showVal (Character x) = "#\\" ++ show x showVal (String x) = "\"" ++ x ++ "\"" showVal (List x) = "(" ++ unwordsList x ++ ")" showVal (DottedList first rest)= "(" ++ unwordsList first ++ " . " ++ showVal rest ++ ")" showVal (PrimitiveFunc _) = "<primitive>" showVal (Func {params = args, vararg = varargs, body = body, closure = env}) = "(lambda (" ++ unwords (map show args) ++ (case varargs of Nothing -> "" Just arg -> " . " ++ arg) ++ ") ...)" showVal (Port _) = "<IO port>" showVal (IOFunc _) = "<IO primitive>" unwordsList :: [LispVal] -> String unwordsList = unwords . map showVal instance Show LispVal where show = showVal type Env = IORef [(String, IORef LispVal)]
lemma has_integral_contour_integral_subpath: assumes "f contour_integrable_on g" "valid_path g" "u \<in> {0..1}" "v \<in> {0..1}" "u \<le> v" shows "(((\<lambda>x. f(g x) * vector_derivative g (at x))) has_integral contour_integral (subpath u v g) f) {u..v}"
In 1946 , W.F. Streeter examined the results of 5 @,@ 598 games played in 45 international chess tournaments between 1851 and 1932 . Streeter found that overall White scored 53 @.@ 4 % ( W : 38 @.@ 12 ; D : 30 @.@ 56 ; L : 31 @.@ 31 ) . White scored 52 @.@ 55 % in 1851 – 78 ( W : 45 @.@ 52 ; D : 14 @.@ 07 ; L : 40 @.@ 41 ) , 52 @.@ 77 % in 1881 – 1914 ( W : 36 @.@ 89 ; D : 31 @.@ 76 ; L : 31 @.@ 35 ) , and 55 @.@ 47 % in 1919 – 32 ( W : 36 @.@ 98 ; D : 36 @.@ 98 ; L : 26 @.@ 04 ) . Streeter concluded , " It thus appears that it is becoming increasingly difficult to win with Black , but somewhat easier to draw . "
Set Implicit Arguments. Require Import List Syntax.Experiment Syntax.Name Tactics.Tactics. Inductive wf_treatment : experiment -> treatment -> Prop := | WF_treatment : forall e t ts, ts = exp_treatments e -> In t ts -> wf_treatment e t. Hint Constructors wf_treatment. Inductive wf_experimental_object : experiment -> experimental_object -> Prop := | WF_object : forall e o os, os = exp_objects e -> In o os -> wf_experimental_object e o. Hint Constructors wf_experimental_object. Inductive wf_dependent_variable : experiment -> dependent_variable -> Prop := | WF_variable : forall e v vs, vs = exp_variables e -> In v vs -> wf_dependent_variable e v. Hint Constructors wf_dependent_variable. Inductive wf_experimental_design : experiment -> experimental_design -> Prop := | WF_design : forall e d ts os f, ts = exp_treatments e -> d = exp_design e -> os = exp_objects e -> f = des_function d -> Forall (fun t => Exists (fun o => In o os /\ In (t,o) f) os) ts -> wf_experimental_design e d. Hint Constructors wf_experimental_design. Inductive wf_research_hypothesis : experiment -> research_hypothesis -> Prop := | WF_hypothesis : forall e n rh rhs t1 t2 op dv, n = hyp_name rh -> rhs = exp_hypothesis e -> t1 = hyp_treatment1 rh -> t2 = hyp_treatment2 rh -> op = hyp_operator rh -> dv = hyp_variable rh -> In rh rhs -> wf_treatment e t1 -> wf_treatment e t2 -> wf_dependent_variable e dv -> t1 <> t2 -> wf_research_hypothesis e rh. Hint Constructors wf_research_hypothesis. Inductive wf_experiment : experiment -> Prop := | WF_experiment : forall e rhs d ts os vs, rhs = exp_hypothesis e -> d = exp_design e -> ts = exp_treatments e -> os = exp_objects e -> vs = exp_variables e -> Forall (fun rh => wf_research_hypothesis e rh) rhs -> Forall (fun t => wf_treatment e t) ts -> Forall (fun o => wf_experimental_object e o) os -> Forall (fun v => wf_dependent_variable e v) vs -> wf_experimental_design e d -> NoDup ts -> NoDup vs -> NoDup os -> NoDup (names rhs) -> wf_experiment e. Hint Constructors wf_experiment.
-- New feature by Jesper Cockx in commit be89d4a8b264dd2719cb8c601a2c7f45a95ba220 : -- disabling the universe check for a data or record type. -- Andreas, 2018-10-27, re issue #3327: restructured test cases. module _ where -- Pragma is naturally attached to definition. module DataDef where data U : Set T : U → Set {-# NO_UNIVERSE_CHECK #-} data U where pi : (A : Set)(b : A → U) → U T (pi A b) = (x : A) → T (b x) -- Pragma can also be attached to signature. module DataSig where {-# NO_UNIVERSE_CHECK #-} data U : Set T : U → Set data U where pi : (A : Set)(b : A → U) → U T (pi A b) = (x : A) → T (b x) -- Works also for explicit mutual blocks. module Mutual where {-# NO_UNIVERSE_CHECK #-} data U : Set where pi : (A : Set)(b : A → U) → U T : U → Set T (pi A b) = (x : A) → T (b x) -- Records: module Records where {-# NO_UNIVERSE_CHECK #-} record R : Set where field out : Set {-# NO_UNIVERSE_CHECK #-} record S : Set record S where field out : Set
------------------------------------------------------------------------------ -- Simple example of a nested recursive function ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} -- From: Ana Bove and Venanzio Capretta. Nested general recursion and -- partiality in type theory. Vol. 2152 of LNCS. 2001. module FOTC.Program.Nest.Nest where open import FOTC.Base ------------------------------------------------------------------------------ -- The nest function. postulate nest : D → D nest-0 : nest zero ≡ zero nest-S : ∀ n → nest (succ₁ n) ≡ nest (nest n) {-# ATP axioms nest-0 nest-S #-}
lemma Reals_inverse_iff [simp]: "inverse x \<in> \<real> \<longleftrightarrow> x \<in> \<real>" for x :: "'a::{real_div_algebra,division_ring}"
theory s184235_2 imports SeCaV begin \<comment> \<open>Please keep each line shorter than 100 characters and do not modify the above "imports" at all\<close> (* Solutions must be entered directly in this file instead of $$$$$ such that there are no errors. IT IS ONLY ALLOWED TO REPLACE $$$$$ WITH LEMMA/PROOF - ABSOLUTELY NO OTHER CHANGES ARE ALLOWED. This comment can be removed and of course the theory name should be changed to your student id. *) abbreviation \<open>P \<equiv> Pre 0 []\<close> abbreviation \<open>Q \<equiv> Pre 1 []\<close> section \<open>Problem 1\<close> proposition \<open>p \<and> q \<longrightarrow> q \<and> p\<close> by metis lemma \<open>\<tturnstile> [ Imp (Con P Q) (Con Q P) ] \<close> proof - from AlphaImp have ?thesis if \<open>\<tturnstile> [ Neg (Con P Q), (Con Q P) ] \<close> using that by simp with AlphaCon have ?thesis if \<open>\<tturnstile> [ Neg P, Neg Q, Con Q P ] \<close> using that by simp with Ext have ?thesis if \<open>\<tturnstile> [ Con Q P, Neg P, Neg Q ] \<close> using that by simp with BetaCon have ?thesis if \<open>\<tturnstile> [ Q, Neg P, Neg Q ] \<close> and \<open>\<tturnstile> [ P, Neg P, Neg Q ] \<close> using that by simp with Ext have ?thesis if \<open>\<tturnstile> [ Q, Neg Q ] \<close> and \<open>\<tturnstile> [ P, Neg P ] \<close> using that by simp with Basic show ?thesis by simp qed \<comment> \<open>Please keep the "end" command and ensure that Isabelle2020 does not indicate any errors at all\<close> end
{-# OPTIONS --without-K #-} module Coinduction where infix 1000 ♯_ postulate ∞ : ∀ {i} (A : Set i) → Set i ♯_ : ∀ {i} {A : Set i} → A → ∞ A ♭ : ∀ {i} {A : Set i} → ∞ A → A {-# BUILTIN INFINITY ∞ #-} {-# BUILTIN SHARP ♯_ #-} {-# BUILTIN FLAT ♭ #-}
# An infinite number of mathematicians walk into a bar... using Colors using Compat colors = distinguishable_colors(9) box(w, h, n) = empty |> fillcolor(colors[n % 9 + 1]) |> size(w, h) cut(w, h, ::@compat Tuple{Escher.Vertical, Bool}) = (w, h/2) cut(w, h, ::Any) = (w/2, h) stack(w, h, d, n) = n == 0 ? empty : flow(d[1][1], [ box(cut(w, h, d[1])..., n), stack(cut(w, h, d[1])..., vcat(d[2:end], d[1]), n-1)], reverse=d[1][2]) directions = [ (vertical, false), (horizontal, true), (vertical, true), (horizontal, false) ] main(win) = inset(Escher.middle, size(100vw, 100vh, empty), stack(80vmin, 80vmin, directions, 24) |> paper(2))
import data.finset import algebra.group.defs import to_mathlib import data.mv_polynomial import Rings.Notation import field_theory.subfield import data.mv_polynomial.rename import data.equiv.fin import data.polynomial.algebra_map import data.list import Rings.ToMathlib.fin universes u v lemma with_bot.succ_lt_succ_succ {n : ℕ} : (n + 1 : with_bot ℕ) < ↑n.succ + 1 := by tidy -- More general version of monoid.has_pow -- instance has_pow_of_has_one_has_mul (A : Type u) [has_one A] [has_mul A] : -- has_pow A ℕ := ⟨ λ t k, npow_rec k t ⟩ namespace mv_polynomial variables {A B : Type*} [comm_ring A] [comm_ring B] [algebra A B] {σ : Type*} open dvector noncomputable instance coe_mv_poly_A_to_mv_poly_B : has_coe (mv_polynomial σ A) (mv_polynomial σ B) := ⟨ mv_polynomial.map (algebra_map A B)⟩ noncomputable instance coe_mv_poly_Z_to_mv_poly_A : has_coe (mv_polynomial σ ℤ) (mv_polynomial σ A) := ⟨ mv_polynomial.map (int.cast_ring_hom A) ⟩ noncomputable instance coe_mv_poly_A_to_mv_poly_poly_A : has_coe (mv_polynomial σ A) (mv_polynomial σ (polynomial A)) := ⟨ @mv_polynomial.map A (polynomial A) σ _ _ polynomial.C ⟩ @[simp] lemma coe_mv_poly_X {k : σ} : ↑(mv_polynomial.X k : mv_polynomial σ ℤ) = (mv_polynomial.X k : mv_polynomial σ A) := begin unfold_coes, simp, end @[simp] lemma coe_mv_poly_one : ↑ (1 : mv_polynomial σ ℤ) = (1 : mv_polynomial σ A) := begin unfold_coes, simp, end @[simp] lemma coe_mv_poly_neg {t}: ↑ - (t : mv_polynomial σ ℤ) = - (↑t : mv_polynomial σ A) := begin unfold_coes, simp, end @[simp] noncomputable def to_polynomial {n} (val : fin n → A) (p : mv_polynomial (fin n.succ) A) : polynomial A := mv_polynomial.eval (fin.x_val polynomial.X (polynomial.C ∘ val)) p lemma eval_eq_poly_eval_mv_coeffs_X {n : ℕ} {val : fin n → A} (x : A) : Π {k}, @mv_polynomial.eval A (fin n.succ) _ (fin.x_val x val) (mv_polynomial.X k) = polynomial.eval x (to_polynomial val (mv_polynomial.X k)) := @fin.cases n (λ k, @mv_polynomial.eval A (fin n.succ) _ (fin.x_val x val) (mv_polynomial.X k) = polynomial.eval x (to_polynomial val (mv_polynomial.X k))) (begin simp only [mv_polynomial.eval_X, fin.cases_zero, function.comp_app, fin.x_val, to_polynomial], unfold_coes, simp, end) (begin simp only [mv_polynomial.eval_X, fin.cases_succ, function.comp_app, fin.x_val, to_polynomial], unfold_coes, simp, end) lemma eval_eq_poly_eval_mv_coeffs {n : ℕ} {p : mv_polynomial (fin n.succ) A} {val : fin n → A} (x : A) : @mv_polynomial.eval A (fin n.succ) _ (fin.x_val x val) p = polynomial.eval x (to_polynomial val p) := @mv_polynomial.induction_on A (fin n.succ) _ (λ q, @mv_polynomial.eval A (fin n.succ) _ (fin.x_val x val) q = polynomial.eval x (to_polynomial val q)) p (begin intro a, simp only [mv_polynomial.eval_C, function.comp_app, fin.x_val, to_polynomial], unfold_coes, simp, end) (begin intros p q, simp only [to_polynomial], intros hp hq, unfold_coes, simp only [ring_hom.map_add, ring_hom.to_fun_eq_coe, function.comp_app, fin.x_val, polynomial.eval_add], simp only [ring_hom.to_fun_eq_coe, function.comp_app, fin.x_val] at hp hq, rw [hp, hq], refl, end) (begin intros p k, simp only [to_polynomial], unfold_coes, simp only [mv_polynomial.eval_X, ring_hom.to_fun_eq_coe, function.comp_app, polynomial.eval_mul, fin.x_val, mv_polynomial.eval_map, ring_hom.map_mul, mv_polynomial.map_X], intro hp, rw ← hp, have hx := @mv_polynomial.eval_eq_poly_eval_mv_coeffs_X _ _ _ val x k, simp only [mv_polynomial.eval_X, function.comp_app, fin.x_val, to_polynomial] at hx, rw hx, unfold_coes, simp, end) lemma eval_add {val : σ → A} {p q : mv_polynomial σ A} : mv_polynomial.eval val (p + q) = mv_polynomial.eval val p + mv_polynomial.eval val q := by simp -- section equiv /-- The algebra isomorphism between multivariable polynomials in no variables and the ground ring. -/ -- LIBRARY ---- mv_polynomial.rename_equiv -- -- variables {R : Type u} [comm_semiring R] -- @[simp] noncomputable def var_equiv {σ τ : Type v} (hequiv : equiv σ τ) : -- mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R := -- let f : mv_polynomial σ R →+* mv_polynomial τ R := -- ring_hom.of (eval₂ C (λ s,X (hequiv.to_fun s))), -- g : mv_polynomial τ R →+* mv_polynomial σ R := -- ring_hom.of (eval₂ C (λ s, X (hequiv.inv_fun s))) -- in -- { to_fun := eval₂ C (λ s, X (hequiv.to_fun s)), -- inv_fun := eval₂ C (λ t, X (hequiv.inv_fun t)), -- left_inv := -- begin -- show ∀ p, g.comp f p = p, -- apply is_id, -- { intro a, simp }, -- { intro n, simp } -- end, -- right_inv := -- begin -- show ∀ p, f.comp g p = p, -- apply is_id, -- { intro a, simp }, -- { intro n, simp } -- end, -- map_mul' := λ _ _, eval₂_mul _ _, -- map_add' := λ _ _, eval₂_add _ _, -- commutes' := λ _, eval₂_C _ _ _ } -- end equiv lemma is_empty {R : Type u} {σ : Type v} [comm_ring R] (h : is_empty σ) (f : mv_polynomial σ R) (as : σ → R) : f = mv_polynomial.C (mv_polynomial.eval as f) := @mv_polynomial.induction_on R σ _ (λ p, p = mv_polynomial.C (mv_polynomial.eval as p)) f (begin intro a, rw (mv_polynomial.C_inj R), simp, end) (begin intros p q hp hq, rw [hp, hq], simp, end) ( begin intros p n hp, apply is_empty.elim h n, end ) end mv_polynomial namespace zorn open classical local attribute [instance] prop_decidable lemma fin_range_sub_mem_chain_of_sub_union {α : Type u} {c : set (set α)} (hchain : zorn.chain has_subset.subset c) (hc0 : c.nonempty) : Π {n : ℕ} (F : fin n → α), (Π k, F k ∈ ⋃₀ c) → ∃ (Y : set α), Y ∈ c ∧ (Π k, F k ∈ Y) | nat.zero := begin intros F hF, cases hc0 with Y hY, use Y, split, {exact hY}, {exact is_empty.elim fin.is_empty} end | (nat.succ n) := begin intros Fsucc hFsucc, have F : fin n → α := λ k, Fsucc (k.succ), have hF : Π (k : fin n), Fsucc k.succ ∈ ⋃₀ c := λ k, hFsucc (fin.succ k), cases fin_range_sub_mem_chain_of_sub_union (λk, Fsucc (k.succ)) hF with Y hY, have h0cup : Fsucc 0 ∈ ⋃₀ c := hFsucc 0, rw set.mem_sUnion at h0cup, cases h0cup with Y0 hY0, cases hY0 with hY0c hY0, cases hY with hYc hY, by_cases hYY0 : Y = Y0, { use Y, split, {exact hYc}, { intro k, apply @fin.cases n (λ l, Fsucc l ∈ Y), {rw hYY0, exact hY0}, {intro i, apply hY i}, } }, { cases hchain Y hYc Y0 hY0c hYY0 with hsub hsub, { use Y0, split, {exact hY0c}, { intro k, apply @fin.cases n (λ l, Fsucc l ∈ Y0), {exact hY0}, {intro i, apply hsub, apply hY i}, } }, { use Y, split, {exact hYc}, { intro k, apply @fin.cases n (λ l, Fsucc l ∈ Y), {apply hsub, exact hY0}, {intro i, apply hY i}, }, }, } end lemma fin_sub_mem_chain_of_sub_union {α : Type u} {c : set (set α)} (hchain : zorn.chain has_subset.subset c) (hc0 : c.nonempty) : Π (F : finset α), (↑F ⊆ ⋃₀ c) → ∃ (Y : set α), Y ∈ c ∧ ↑F ⊆ Y := @finset.induction α (λ (F : finset α), (↑F ⊆ ⋃₀ c) → ∃ (Y : set α), Y ∈ c ∧ ↑F ⊆ Y) _ (begin intro h0sub, cases hc0 with Y hY, use Y, split, exact hY, simp, end) (begin intros a F haF hind hFasub, have hacup : a ∈ ⋃₀ c, {apply hFasub, simp}, rw set.mem_sUnion at hacup, cases hacup with Z hZ, cases hZ with hZc haZ, have hFsub : ↑F ⊆ ⋃₀ c, {apply set.subset.trans _ hFasub, simp}, have Y := (hind hFsub), cases Y with Y hY, by_cases hYZ : Y = Z, { use Y, split, {exact hY.1}, { simp only [finset.coe_insert, set.insert_subset], split, {rw hYZ, exact haZ,}, {exact hY.2} } }, cases hY with hYc hFY, cases hchain Y hYc Z hZc hYZ with hl hr, { use Z, split, {exact hZc}, simp only [finset.coe_insert, set.insert_subset], split, {exact haZ}, {exact set.subset.trans hFY hl}, }, { use Y, split, {exact hYc}, { simp only [finset.coe_insert, set.insert_subset], split, {exact hr haZ}, {exact hFY} }, } end) end zorn namespace set lemma union_sdiff {α : Type u} {B : set α} {x y} : ¬x = y → (B ∪ {x}) \ {y} = B \ {y} ∪ {x} := begin intro hxy, apply set.ext, intro b, split, { intro hb, by_cases hbx : b = x, { right, simpa, }, { left, split, cases hb with hl hr, cases hl, {exact hl}, {exfalso, apply hbx, simpa using hl}, {exact hb.2}, }, }, { intro hb, cases hb, { split, {left, exact hb.1}, {simpa using hb.2}, }, { split, {right, exact hb}, {intro hbot, apply hxy, tidy}, }, }, end lemma remove_insert {α : Type u} {B : set α} {y} : y ∈ B → B \ {y} ∪ {y} = B := begin intro hyB, apply set.ext, intro b, split, { intro hb, cases hb, {exact hb.1}, {rw set.mem_singleton_iff at hb, rw hb, exact hyB}, }, { intro hbB, by_cases hby : b = y, { rw hby, right, simp, }, { left, split, {exact hbB}, {simpa using hby}, }, }, end lemma remove_insert_not_mem {α : Type u} {B : set α} {x} : x ∉ B → B = (B ∪ {x}) \ {x} := begin intro hxB, simp only [set.mem_singleton, set.insert_diff_of_mem, set.union_singleton], apply set.ext, intro b, split, { intro hb, split, {exact hb}, {intro hbot, rw set.mem_singleton_iff at hbot, rw hbot at hb, exact hxB hb,} }, {intro hb, cases hb, cc}, end end set namespace subfield variables (L : Type u) [field L] -- lemma closure_subset (U V : set L) (hUV : U ⊆ V) : -- (subfield.closure U : set L) ⊆ subfield.closure V := -- begin -- simp only [set_like.coe_subset_coe, closure_le], -- apply set.subset.trans hUV subset_closure, -- end end subfield -- couldn't find in the library def big_add {A : Type u} [has_add A] [has_zero A] : Π {n : ℕ}, (fin n → A) → A | nat.zero := 0 | (nat.succ n) := λ as, (big_add (λ k : fin n, as k)) + as n def big_mul {A : Type u} [has_mul A] [has_one A] : Π {n : ℕ}, (fin n → A) → A | nat.zero := 1 | (nat.succ n) := λ as, (big_mul (λ k : fin n, as k)) * as n
lemma divide_poly_main_0: "divide_poly_main 0 0 r d dr n = 0"
Require Import Autosubst.Autosubst. Require Import Relations. From Metatheories Require Import ARS Term Reduction. Inductive leftmost : relation term := | leftmost_appabs t11 t2 : leftmost (tapp (tabs t11) t2) (t11.[t2/]) | leftmost_appl t1 t1' t2 : neutral t1 -> leftmost t1 t1' -> leftmost (tapp t1 t2) (tapp t1' t2) | leftmost_appr t1 t2 t2' : neutral t1 -> in_normal_form _ red t1 -> leftmost t2 t2' -> leftmost (tapp t1 t2) (tapp t1 t2') | leftmost_abs t t' : leftmost t t' -> leftmost (tabs t) (tabs t'). Hint Constructors leftmost. Local Hint Constructors clos_refl_trans. Lemma leftmost_abs_multi t t' : clos_refl_trans _ leftmost t t' -> clos_refl_trans _ leftmost (tabs t) (tabs t'). Proof. induction 1; eauto. Qed. Lemma leftmost_appr_multi t1 t2 t2' : neutral t1 -> in_normal_form _ red t1 -> clos_refl_trans _ leftmost t2 t2' -> clos_refl_trans _ leftmost (tapp t1 t2) (tapp t1 t2'). Proof. induction 3; eauto. Qed. Lemma leftmost_abs_multi_inv t t' : clos_refl_trans _ leftmost t t' -> forall t1, t = tabs t1 -> exists t1', t' = tabs t1'. Proof. induction 1; intros ? ?; subst; eauto. - inversion H; subst; eauto. - destruct (IHclos_refl_trans1 _ eq_refl); subst. destruct (IHclos_refl_trans2 _ eq_refl); subst. eauto. Qed. Lemma leftmost_appl_multi t1 t1' t2 : neutral t1 -> neutral t1' -> clos_refl_trans _ leftmost t1 t1' -> clos_refl_trans _ leftmost (tapp t1 t2) (tapp t1' t2). Proof. induction 3; eauto. destruct (neutral_dec y) as [[]|]; subst; eauto. destruct (leftmost_abs_multi_inv _ _ H1_0 _ eq_refl); subst; simpl in *. eauto. Qed. Lemma leftmost_red t t' : leftmost t t' -> red t t'. Proof. induction 1; eauto. Qed. Corollary leftmost_multi_red_multi t t' : clos_refl_trans _ leftmost t t' -> clos_refl_trans _ red t t'. Proof. apply clos_rt_impl. apply leftmost_red. Qed. Hint Resolve leftmost_abs_multi leftmost_red leftmost_multi_red_multi. Lemma leftmost_det t t' : leftmost t t' -> forall t'', leftmost t t'' -> t' = t''. Proof. induction 1; intros ? Hleftmost; inversion Hleftmost; subst; simpl in *; unfold in_normal_form in *; unfold not in *; f_equal; solve [ eauto | exfalso; eauto ]. Qed.
[GOAL] α : Type u_1 S : Set (Set α) cond : FiniteInter S F : Finset (Set α) ⊢ ↑F ⊆ S → ⋂₀ ↑F ∈ S [PROOFSTEP] classical refine' Finset.induction_on F (fun _ => _) _ · simp [cond.univ_mem] · intro a s _ h1 h2 suffices a ∩ ⋂₀ ↑s ∈ S by simpa exact cond.inter_mem (h2 (Finset.mem_insert_self a s)) (h1 fun x hx => h2 <| Finset.mem_insert_of_mem hx) [GOAL] α : Type u_1 S : Set (Set α) cond : FiniteInter S F : Finset (Set α) ⊢ ↑F ⊆ S → ⋂₀ ↑F ∈ S [PROOFSTEP] refine' Finset.induction_on F (fun _ => _) _ [GOAL] case refine'_1 α : Type u_1 S : Set (Set α) cond : FiniteInter S F : Finset (Set α) x✝ : ↑∅ ⊆ S ⊢ ⋂₀ ↑∅ ∈ S [PROOFSTEP] simp [cond.univ_mem] [GOAL] case refine'_2 α : Type u_1 S : Set (Set α) cond : FiniteInter S F : Finset (Set α) ⊢ ∀ ⦃a : Set α⦄ {s : Finset (Set α)}, ¬a ∈ s → (↑s ⊆ S → ⋂₀ ↑s ∈ S) → ↑(insert a s) ⊆ S → ⋂₀ ↑(insert a s) ∈ S [PROOFSTEP] intro a s _ h1 h2 [GOAL] case refine'_2 α : Type u_1 S : Set (Set α) cond : FiniteInter S F : Finset (Set α) a : Set α s : Finset (Set α) a✝ : ¬a ∈ s h1 : ↑s ⊆ S → ⋂₀ ↑s ∈ S h2 : ↑(insert a s) ⊆ S ⊢ ⋂₀ ↑(insert a s) ∈ S [PROOFSTEP] suffices a ∩ ⋂₀ ↑s ∈ S by simpa [GOAL] α : Type u_1 S : Set (Set α) cond : FiniteInter S F : Finset (Set α) a : Set α s : Finset (Set α) a✝ : ¬a ∈ s h1 : ↑s ⊆ S → ⋂₀ ↑s ∈ S h2 : ↑(insert a s) ⊆ S this : a ∩ ⋂₀ ↑s ∈ S ⊢ ⋂₀ ↑(insert a s) ∈ S [PROOFSTEP] simpa [GOAL] case refine'_2 α : Type u_1 S : Set (Set α) cond : FiniteInter S F : Finset (Set α) a : Set α s : Finset (Set α) a✝ : ¬a ∈ s h1 : ↑s ⊆ S → ⋂₀ ↑s ∈ S h2 : ↑(insert a s) ⊆ S ⊢ a ∩ ⋂₀ ↑s ∈ S [PROOFSTEP] exact cond.inter_mem (h2 (Finset.mem_insert_self a s)) (h1 fun x hx => h2 <| Finset.mem_insert_of_mem hx) [GOAL] α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P : Set α H : P ∈ finiteInterClosure (insert A S) ⊢ P ∈ S ∨ ∃ Q, Q ∈ S ∧ P = A ∩ Q [PROOFSTEP] induction' H with S h T1 T2 _ _ h1 h2 [GOAL] case basic α : Type u_1 S✝ : Set (Set α) A : Set α cond : FiniteInter S✝ P S : Set α h : S ∈ insert A S✝ ⊢ S ∈ S✝ ∨ ∃ Q, Q ∈ S✝ ∧ S = A ∩ Q [PROOFSTEP] cases h [GOAL] case basic.inl α : Type u_1 S✝ : Set (Set α) A : Set α cond : FiniteInter S✝ P S : Set α h✝ : S = A ⊢ S ∈ S✝ ∨ ∃ Q, Q ∈ S✝ ∧ S = A ∩ Q [PROOFSTEP] exact Or.inr ⟨Set.univ, cond.univ_mem, by simpa⟩ [GOAL] α : Type u_1 S✝ : Set (Set α) A : Set α cond : FiniteInter S✝ P S : Set α h✝ : S = A ⊢ S = A ∩ Set.univ [PROOFSTEP] simpa [GOAL] case basic.inr α : Type u_1 S✝ : Set (Set α) A : Set α cond : FiniteInter S✝ P S : Set α h✝ : S ∈ S✝ ⊢ S ∈ S✝ ∨ ∃ Q, Q ∈ S✝ ∧ S = A ∩ Q [PROOFSTEP] exact Or.inl (by assumption) [GOAL] α : Type u_1 S✝ : Set (Set α) A : Set α cond : FiniteInter S✝ P S : Set α h✝ : S ∈ S✝ ⊢ S ∈ S✝ [PROOFSTEP] assumption [GOAL] case univ α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P : Set α ⊢ Set.univ ∈ S ∨ ∃ Q, Q ∈ S ∧ Set.univ = A ∩ Q [PROOFSTEP] exact Or.inl cond.univ_mem [GOAL] case inter α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P T1 T2 : Set α a✝¹ : finiteInterClosure (insert A S) T1 a✝ : finiteInterClosure (insert A S) T2 h1 : T1 ∈ S ∨ ∃ Q, Q ∈ S ∧ T1 = A ∩ Q h2 : T2 ∈ S ∨ ∃ Q, Q ∈ S ∧ T2 = A ∩ Q ⊢ T1 ∩ T2 ∈ S ∨ ∃ Q, Q ∈ S ∧ T1 ∩ T2 = A ∩ Q [PROOFSTEP] rcases h1 with (h | ⟨Q, hQ, rfl⟩) [GOAL] case inter.inl α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P T1 T2 : Set α a✝¹ : finiteInterClosure (insert A S) T1 a✝ : finiteInterClosure (insert A S) T2 h2 : T2 ∈ S ∨ ∃ Q, Q ∈ S ∧ T2 = A ∩ Q h : T1 ∈ S ⊢ T1 ∩ T2 ∈ S ∨ ∃ Q, Q ∈ S ∧ T1 ∩ T2 = A ∩ Q [PROOFSTEP] rcases h2 with (i | ⟨R, hR, rfl⟩) [GOAL] case inter.inr.intro.intro α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P T2 : Set α a✝¹ : finiteInterClosure (insert A S) T2 h2 : T2 ∈ S ∨ ∃ Q, Q ∈ S ∧ T2 = A ∩ Q Q : Set α hQ : Q ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ Q) ⊢ A ∩ Q ∩ T2 ∈ S ∨ ∃ Q_1, Q_1 ∈ S ∧ A ∩ Q ∩ T2 = A ∩ Q_1 [PROOFSTEP] rcases h2 with (i | ⟨R, hR, rfl⟩) [GOAL] case inter.inl.inl α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P T1 T2 : Set α a✝¹ : finiteInterClosure (insert A S) T1 a✝ : finiteInterClosure (insert A S) T2 h : T1 ∈ S i : T2 ∈ S ⊢ T1 ∩ T2 ∈ S ∨ ∃ Q, Q ∈ S ∧ T1 ∩ T2 = A ∩ Q [PROOFSTEP] exact Or.inl (cond.inter_mem h i) [GOAL] case inter.inl.inr.intro.intro α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P T1 : Set α a✝¹ : finiteInterClosure (insert A S) T1 h : T1 ∈ S R : Set α hR : R ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ R) ⊢ T1 ∩ (A ∩ R) ∈ S ∨ ∃ Q, Q ∈ S ∧ T1 ∩ (A ∩ R) = A ∩ Q [PROOFSTEP] exact Or.inr ⟨T1 ∩ R, cond.inter_mem h hR, by simp only [← Set.inter_assoc, Set.inter_comm _ A]⟩ [GOAL] α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P T1 : Set α a✝¹ : finiteInterClosure (insert A S) T1 h : T1 ∈ S R : Set α hR : R ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ R) ⊢ T1 ∩ (A ∩ R) = A ∩ (T1 ∩ R) [PROOFSTEP] simp only [← Set.inter_assoc, Set.inter_comm _ A] [GOAL] case inter.inr.intro.intro.inl α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P T2 : Set α a✝¹ : finiteInterClosure (insert A S) T2 Q : Set α hQ : Q ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ Q) i : T2 ∈ S ⊢ A ∩ Q ∩ T2 ∈ S ∨ ∃ Q_1, Q_1 ∈ S ∧ A ∩ Q ∩ T2 = A ∩ Q_1 [PROOFSTEP] exact Or.inr ⟨Q ∩ T2, cond.inter_mem hQ i, by simp only [Set.inter_assoc]⟩ [GOAL] α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P T2 : Set α a✝¹ : finiteInterClosure (insert A S) T2 Q : Set α hQ : Q ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ Q) i : T2 ∈ S ⊢ A ∩ Q ∩ T2 = A ∩ (Q ∩ T2) [PROOFSTEP] simp only [Set.inter_assoc] [GOAL] case inter.inr.intro.intro.inr.intro.intro α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P Q : Set α hQ : Q ∈ S a✝¹ : finiteInterClosure (insert A S) (A ∩ Q) R : Set α hR : R ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ R) ⊢ A ∩ Q ∩ (A ∩ R) ∈ S ∨ ∃ Q_1, Q_1 ∈ S ∧ A ∩ Q ∩ (A ∩ R) = A ∩ Q_1 [PROOFSTEP] exact Or.inr ⟨Q ∩ R, cond.inter_mem hQ hR, by ext x constructor <;> simp (config := { contextual := true })⟩ [GOAL] α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P Q : Set α hQ : Q ∈ S a✝¹ : finiteInterClosure (insert A S) (A ∩ Q) R : Set α hR : R ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ R) ⊢ A ∩ Q ∩ (A ∩ R) = A ∩ (Q ∩ R) [PROOFSTEP] ext x [GOAL] case h α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P Q : Set α hQ : Q ∈ S a✝¹ : finiteInterClosure (insert A S) (A ∩ Q) R : Set α hR : R ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ R) x : α ⊢ x ∈ A ∩ Q ∩ (A ∩ R) ↔ x ∈ A ∩ (Q ∩ R) [PROOFSTEP] constructor [GOAL] case h.mp α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P Q : Set α hQ : Q ∈ S a✝¹ : finiteInterClosure (insert A S) (A ∩ Q) R : Set α hR : R ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ R) x : α ⊢ x ∈ A ∩ Q ∩ (A ∩ R) → x ∈ A ∩ (Q ∩ R) [PROOFSTEP] simp (config := { contextual := true }) [GOAL] case h.mpr α : Type u_1 S : Set (Set α) A : Set α cond : FiniteInter S P Q : Set α hQ : Q ∈ S a✝¹ : finiteInterClosure (insert A S) (A ∩ Q) R : Set α hR : R ∈ S a✝ : finiteInterClosure (insert A S) (A ∩ R) x : α ⊢ x ∈ A ∩ (Q ∩ R) → x ∈ A ∩ Q ∩ (A ∩ R) [PROOFSTEP] simp (config := { contextual := true })
lemma measure_of_of_measure: "measure_of (space M) (sets M) (emeasure M) = M"
State Before: ι : Type ?u.386687 α : Type u_1 inst✝ : OrderedAddCommGroup α s t : Interval α a : α x✝ : Interval α ⊢ length (⊥ + x✝) ≤ length ⊥ + length x✝ State After: no goals Tactic: simp State Before: ι : Type ?u.386687 α : Type u_1 inst✝ : OrderedAddCommGroup α s t : Interval α a : α x✝ : Interval α ⊢ length (x✝ + ⊥) ≤ length x✝ + length ⊥ State After: no goals Tactic: simp
module Examples.CSS.Balls import Data.Vect import Examples.CSS.Colors import public Examples.CSS.Core import Rhone.JS import Text.CSS -------------------------------------------------------------------------------- -- IDs -------------------------------------------------------------------------------- public export out : ElemRef HTMLCanvasElement out = Id Canvas "balls_out" public export btnRun : ElemRef HTMLButtonElement btnRun = Id Button "balls_run" public export txtCount : ElemRef HTMLInputElement txtCount = Id Input "balls_numballs" public export log : ElemRef HTMLDivElement log = Id Div "balls_log" -------------------------------------------------------------------------------- -- Rules -------------------------------------------------------------------------------- export ballsContent : String ballsContent = "balls_content" export lblCount : String lblCount = "balls_lblcount" data Tag = LNum | INum | BRun | LFPS | Anim | Dot AreaTag Tag where showTag LNum = "LNum" showTag INum = "INum" showTag BRun = "BRun" showTag LFPS = "LFPS" showTag Anim = "Anim" showTag Dot = "." export css : List (Rule 1) css = [ Media "min-width: 300px" [ class ballsContent !! [ Display .= Area (replicate 4 MinContent) [MaxContent, MaxContent] [ [LNum, INum] , [Dot, BRun] , [LFPS, LFPS] , [Anim, Anim] ] , ColumnGap .= px 10 , RowGap .= px 10 , Padding .= VH (px 20) (px 10) ] ] , Media "min-width: 800px" [ class ballsContent !! [ Display .= Area (replicate 4 MinContent) [MaxContent, MaxContent, fr 1] [ [LNum, INum, Anim] , [Dot, BRun, Anim] , [LFPS, LFPS, Anim] , [Dot, Dot, Anim] ] , ColumnGap .= px 10 , RowGap .= px 10 , Padding .= VH (px 20) (px 10) ] ] , class lblCount !! [ GridArea .= LNum ] , idRef txtCount !! [ GridArea .= INum , TextAlign .= End ] , idRef btnRun !! [ GridArea .= BRun ] , idRef log !! [ GridArea .= LFPS ] , idRef out !! [ JustifySelf .= Center , GridArea .= Anim , MaxWidth .= px 500 , Width .= px 500 ] ]
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #ifndef NT2_TOOLBOX_EULER_FUNCTION_SCALAR_GAMMALN_HPP_INCLUDED #define NT2_TOOLBOX_EULER_FUNCTION_SCALAR_GAMMALN_HPP_INCLUDED #include <nt2/toolbox/euler/details/math.hpp> #include <boost/math/special_functions/gamma.hpp> #include <nt2/sdk/constant/real.hpp> #include <nt2/sdk/constant/digits.hpp> ///////////////////////////////////////////////////////////////////////////// // Implementation when type is fundamental_ ///////////////////////////////////////////////////////////////////////////// NT2_REGISTER_DISPATCH(tag::gammaln_, tag::cpu_, (A0), (fundamental_<A0>) ) namespace nt2 { namespace ext { template<class Dummy> struct call<tag::gammaln_(tag::fundamental_), tag::cpu_, Dummy> : callable { template<class Sig> struct result; template<class This,class A0> struct result<This(A0)> : std::tr1::result_of<meta::floating(A0)>{}; NT2_FUNCTOR_CALL(1) { if (a0 < Zero<A0>()) return Nan<A0>(); typedef typename NT2_RETURN_TYPE(1)::type type; #ifdef NT2_TOOLBOX_EULER_HAS_LGAMMA return ::lgamma(type(a0)); #else return boost::math::lgamma(type(a0)); #endif } }; } } ///////////////////////////////////////////////////////////////////////////// // Implementation when type is float_ ///////////////////////////////////////////////////////////////////////////// NT2_REGISTER_DISPATCH(tag::gammaln_, tag::cpu_, (A0), (float_<A0>) ) namespace nt2 { namespace ext { template<class Dummy> struct call<tag::gammaln_(tag::float_), tag::cpu_, Dummy> : callable { template<class Sig> struct result; template<class This,class A0> struct result<This(A0)> : std::tr1::result_of<meta::floating(A0)>{}; NT2_FUNCTOR_CALL(1) { if (a0 < Zero<A0>()) return Nan<A0>(); typedef typename NT2_RETURN_TYPE(1)::type type; #ifdef NT2_TOOLBOX_EULER_HAS_LGAMMAF return ::lgammaf(type(a0)); #else return boost::math::lgamma(type(a0)); #endif } }; } } #endif // modified by jt the 26/12/2010
%!TEX program = lualatex \documentclass[aspectratio=169,handout]{beamer} % add 'handout' to beamer options for printout \usepackage{multimedia} \usepackage[backend=biber,style=ieee]{biblatex} \usetheme{AVThesis} \title{The Art of Robotics:\\\vspace{0.2em}\huge{Toward a Holistic Approach}} \subtitle{Master of Science in Robotics\\Thesis Defense} \author{Alexander Volkov Jr.} \date{July 31, 2018} \bibliography{refs/thesis-slides.bib} % Change frame margins \addtobeamertemplate{frametitle}{\vspace*{1cm}}{\vspace*{0cm}} \setcounter{showSlideNumbers}{1} \begin{document} \setcounter{showProgressBar}{0} \setcounter{showSlideNumbers}{0} \frame{\titlepage} \begin{frame} \frametitle{Talk Agenda} \begin{enumerate} \setlength{\itemsep}{4mm} \item Background \textcolor{AVThesisGrey}{\footnotesize\hspace{1em} The BFD; how I ended up here} % \item Other Things % \textcolor{AVThesisGrey}{\footnotesize\hspace{1em} Warm up the crowd with a quick review of some other things I've done.} \item The Big Picture \textcolor{AVThesisGrey}{\footnotesize\hspace{1em} Cover the central themes of this talk.} \item A Unifying Framework \textcolor{AVThesisGrey}{\footnotesize\hspace{1em} An old framework, revived.} % \item Brushless PMSM Motors % \textcolor{AVThesisGrey}{\footnotesize\hspace{1em} Operating limits, thermal management, liquid cooling.} % \item Touching Robots % \textcolor{AVThesisGrey}{\footnotesize\hspace{1em} Tactile sensing, contact modeling, whiskers, robot pain.} % \item Conclusions \textcolor{AVThesisGrey}{\footnotesize\hspace{1em} Review key points and propose some future work.} \item Acknowledgments \& Questions \textcolor{AVThesisGrey}{\footnotesize\hspace{1em} \emph{``Please clap...''}} \end{enumerate} \end{frame} \setcounter{framenumber}{0} \setcounter{showProgressBar}{1} \setcounter{showSlideNumbers}{1} \section{Background} \begin{frame} \frametitle{The BFD} \begin{itemize} \item \textbf{End Game:} Develop a Unified Framework for Understanding Robotics \pause \begin{itemize} \item \textbf{Thesis Purpose:} Reflect on and organize \emph{my} understanding of robotics \pause \begin{itemize} \item \textbf{Talk Purpose:} Provide an overview of my thesis dissertation for the committee \end{itemize} \end{itemize} \end{itemize} \end{frame} \begin{frame} \frametitle{Talk Title Etymology I} \begin{tikzpicture}[overlay, remember picture] \node[anchor=east] (taoe) at ($(current page.east)+(-3mm,-1mm)$) {\includegraphics[width=5.5cm]{media/the-art-of-electronics.png}}; \end{tikzpicture} \begin{itemize} \item ``The Art of Electronics'', by \emph{Horowitz \& Hill}\pause \begin{itemize} \item Literally the electrical engineering bible \item Incredibly thorough \item Perfect balance of practicality and rigor \end{itemize} \end{itemize} \end{frame} \begin{frame} \frametitle{Talk Title Etymology II} \begin{tikzpicture}[overlay, remember picture] \node[anchor=east] (taoe) at ($(current page.east)+(-10mm,-1mm)$) {\includegraphics[width=4cm]{media/mason-manip-book.jpg}}; \end{tikzpicture} \begin{itemize} \item ``Mechanics of Robotic Manipulation'', by \emph{Mason}\footnotemark~\autocite{mason2001mechanics} \pause \begin{itemize} \item ``Manipulation is an art\dots'' (p.1) \end{itemize} \end{itemize} \footnotetext{Matt, I'll take my referral payments by mail.} \end{frame} % \begin{frame} % \frametitle{Talk (Sub)Title Etymology III} % \begin{tikzpicture}[overlay, remember picture] % \fontsize{18}{15} % \node[anchor=center] (subtitle) at (current page.center) {``Toward a Holistic Approach''}; % \end{tikzpicture} % \end{frame} % % \begin{frame} % \addtocounter{framenumber}{-1} % \frametitle{Talk (Sub)Title Etymology III} % \begin{tikzpicture}[overlay, remember picture] % \fontsize{18}{15} % \node[anchor=center] (subtitle) at (current page.center) {``\highlight{toward}{Toward} a Holistic Approach''}; % \fontsize{10}{12} % \node[anchor=south west, fill=red!20,rounded corners, text width=3cm, outer sep=3pt, inner sep=3pt] (toward-note) at ($(current page.south west) + (10mm,10mm)$) {When you concede falling short of a goal in academia.}; % \draw [->, line width=0.3mm] (toward-note) -- (toward); % \end{tikzpicture} % \end{frame} \begin{frame} % \addtocounter{framenumber}{-1} \frametitle{Talk (Sub)Title Etymology III} \begin{tikzpicture}[overlay, remember picture] \fontsize{18}{15} \only<1>{\node[anchor=center] (subtitle) at (current page.center) {``Toward a Holistic Approach''};} \only<2>{\node[anchor=center] (subtitle) at (current page.center) {``\highlight{toward}{Toward} a Holistic Approach''}; \fontsize{10}{12} \node[anchor=south west, fill=red!20,rounded corners, text width=5cm, outer sep=3pt, inner sep=3pt] (toward-note) at ($(current page.south west) + (10mm,10mm)$) {When you concede falling short of a goal in academia. Example: Mason's Annual Review ``Toward Robotic Manipulation'' \autocite{Mason2018}}; \draw [->, line width=0.3mm] (toward-note) -- (toward);} \onslide<3->{\node[anchor=center] (subtitle) at (current page.center) {``\highlight{toward}{Toward} a \highlight{holistic}{Holistic} Approach''}; \fontsize{10}{12} \node[anchor=south west, fill=red!20,rounded corners, text width=5cm, outer sep=3pt, inner sep=3pt] (toward-note) at ($(current page.south west) + (10mm,10mm)$) {When you concede falling short of a goal in academia. Example: Mason's Annual Review ``Toward Robotic Manipulation'' \autocite{Mason2018}}; \draw [->, line width=0.3mm] (toward-note) -- (toward); \node[anchor=south east, fill=red!20,rounded corners, text width=7cm, outer sep=3pt, inner sep=3pt] (holistic-note) at ($(current page.south east) + (-10mm,10mm)$) {From the mechatronics/systems engineering community. Chhabra and Emami provide an excellent summary in \autocite{Chhabra2011}.}; \draw [->, line width=0.3mm] (holistic-note) -- (holistic);} \end{tikzpicture} \end{frame} \begin{frame} \frametitle{How I Ended Up Here (Some Context) I} \vspace{-0.5em} \begin{itemize} \item \textbf{Hobby robotics} $\Rightarrow$ self-taught basic electronics, programming, CAD\pause \begin{itemize} \item ``Keep it cheap'' \item ``Keep it open-source'' \item ``Keep it useful (or, at least, artistic)'' \end{itemize}\pause \vspace{0.5em} \item \textbf{Cornell Undergrad} $\Rightarrow$ ECE major, ME/CS minors\pause \begin{itemize} \item \textbf{ECE:} \begin{itemize} \item ``Everything is an impedance (or an admittance)'' \item ``What's the system bandwidth?'' \end{itemize} \item \textbf{ME:}\pause \begin{itemize} \item ``At the end of the day, everything is mechanical'' \item ``Everything is a model, and every model is wrong'' \end{itemize}\pause \item \textbf{CS:} \begin{itemize} \item ``90\% of solving a problem is finding the right representation'' \item ``Everything breaks at the interfaces'' \end{itemize} \end{itemize} \end{itemize} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) II} \begin{tikzpicture}[overlay, remember picture] \node[anchor=center] (ri-logo) at (current page.center) {\includegraphics[width=30mm]{assets/ri-logo.eps}}; \node[minimum width=2cm, below=5mm of ri-logo] {``Time to become a robotics master...''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) III} \begin{tikzpicture}[overlay, remember picture] \node[anchor=south east] (ri-logo) at ($(current page.south east)+(-5mm,10mm)$) {\includegraphics[width=16mm]{assets/ri-logo.eps}}; \fontsize{12}{10} \node[anchor=south west] (me) at ($(current page.south west)+(5mm,10mm)$) {\includegraphics[width=2cm]{media/me.jpg}}; \node[minimum width=2cm, right=3mm of me] {``Legged locomotion is cool...''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) IV} \begin{tikzpicture}[overlay, remember picture] \node[anchor=south east] (ri-logo) at ($(current page.south east)+(-5mm,10mm)$) {\includegraphics[width=16mm]{assets/ri-logo.eps}}; \fontsize{12}{10} \node[anchor=south west] (me) at ($(current page.south west)+(5mm,10mm)$) {\includegraphics[width=2cm]{media/me.jpg}}; \node[minimum width=2cm, right=3mm of me] {\color{gray}``Legged locomotion is cool...''}; \node[anchor=north east] (hartmut) at ($(current page.north east)+(-5mm,-15mm)$) {\includegraphics[width=2cm]{media/hartmut.jpg}}; \node[anchor=north east] (travers) at ($(current page.north east)+(-28mm,-15mm)$) {\includegraphics[width=2cm]{media/travers.jpg}}; \node[anchor=north east] (koushil) at ($(current page.north east)+(-51mm,-15mm)$) {\includegraphics[width=2cm]{media/koushil.jpg}}; \node[anchor=east, minimum width=2cm, left=3mm of koushil] {``Great! Here's absolutely no funding.''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) V} \begin{tikzpicture}[overlay, remember picture] \node[anchor=south east] (ri-logo) at ($(current page.south east)+(-5mm,10mm)$) {\includegraphics[width=16mm]{assets/ri-logo.eps}}; \fontsize{12}{10} \node[anchor=south west] (me) at ($(current page.south west)+(5mm,10mm)$) {\includegraphics[width=2cm]{media/me.jpg}}; \node[minimum width=2cm, right=3mm of me] {``Umm...''}; \node[anchor=north east] (hartmut) at ($(current page.north east)+(-5mm,-15mm)$) {\includegraphics[width=2cm]{media/hartmut.jpg}}; \node[anchor=north east] (travers) at ($(current page.north east)+(-28mm,-15mm)$) {\includegraphics[width=2cm]{media/travers.jpg}}; \node[anchor=north east] (koushil) at ($(current page.north east)+(-51mm,-15mm)$) {\includegraphics[width=2cm]{media/koushil.jpg}}; \node[anchor=east, minimum width=2cm, left=3mm of koushil] {\color{gray}``Great! Here's absolutely no funding.''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) VI} \begin{tikzpicture}[overlay, remember picture] \node[anchor=south east] (ri-logo) at ($(current page.south east)+(-5mm,10mm)$) {\includegraphics[width=16mm]{assets/ri-logo.eps}}; \fontsize{12}{10} \node[anchor=south west] (me) at ($(current page.south west)+(5mm,10mm)$) {\includegraphics[width=2cm]{media/me.jpg}}; \node[minimum width=2cm, right=3mm of me] {\color{gray}``Umm...''}; \node[anchor=north east] (ross) at ($(current page.north east)+(-5mm,-15mm)$) {\includegraphics[width=2cm]{media/ross.jpg}}; \node[anchor=east, minimum width=2cm, left=3mm of ross] {``Wait! Go talk to Matt Mason!''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) VII} \begin{tikzpicture}[overlay, remember picture] \node[anchor=south east] (ri-logo) at ($(current page.south east)+(-5mm,10mm)$) {\includegraphics[width=16mm]{assets/ri-logo.eps}}; \fontsize{12}{10} \node[anchor=south west] (me) at ($(current page.south west)+(5mm,10mm)$) {\includegraphics[width=2cm]{media/me.jpg}}; \node[minimum width=2cm, right=3mm of me] {``(skeptical) Okay...''}; \node[anchor=north east] (ross) at ($(current page.north east)+(-5mm,-15mm)$) {\includegraphics[width=2cm]{media/ross.jpg}}; \node[anchor=east, minimum width=2cm, left=3mm of ross] {\color{gray}``Wait! Go talk to Matt Mason!''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) VIII} \begin{tikzpicture}[overlay, remember picture] \node[anchor=south east] (ri-logo) at ($(current page.south east)+(-5mm,10mm)$) {\includegraphics[width=16mm]{assets/ri-logo.eps}}; \fontsize{12}{15} \node[anchor=south west] (me) at ($(current page.south west)+(5mm,10mm)$) {\includegraphics[width=2cm]{media/me.jpg}}; \node[minimum width=2cm, right=3mm of me] {\color{gray}``(skeptical) Okay...''}; \node[anchor=north east] (matt) at ($(current page.north east)+(-5mm,-15mm)$) {\includegraphics[width=2cm]{media/mason.jpg}}; \node[anchor=east, text width=5cm, left=3mm of matt, align=right] {``Manipulation is awesome! \\And I have money! \\And I don't micromanage!''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) IX} \begin{tikzpicture}[overlay, remember picture] \node[anchor=south east] (ri-logo) at ($(current page.south east)+(-5mm,10mm)$) {\includegraphics[width=16mm]{assets/ri-logo.eps}}; \fontsize{12}{15} \node[anchor=south west] (me) at ($(current page.south west)+(5mm,10mm)$) {\includegraphics[width=2cm]{media/me.jpg}}; \node[minimum width=2cm, right=3mm of me] {``(excited) Works for me!''}; \node[anchor=north east] (matt) at ($(current page.north east)+(-5mm,-15mm)$) {\includegraphics[width=2cm]{media/mason.jpg}}; \node[anchor=east, text width=5cm, left=3mm of matt, align=right] {\color{gray}``Manipulation is awesome! \\And I have money! \\And I don't micromanage!''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) X} \begin{tikzpicture}[overlay, remember picture] \node[anchor=south east] (ri-logo) at ($(current page.south east)+(-5mm,10mm)$) {\includegraphics[width=16mm]{assets/ri-logo.eps}}; \fontsize{12}{15} \node[anchor=south west] (me) at ($(current page.south west)+(5mm,10mm)$) {\includegraphics[width=2cm]{media/me.jpg}}; \node[minimum width=2cm, right=3mm of me] {\color{gray}``(excited) Works for me!''}; \node[anchor=north east] (matt) at ($(current page.north east)+(-5mm,-15mm)$) {\includegraphics[width=2cm]{media/mason.jpg}}; \node[anchor=east, minimum width=2cm, left=3mm of matt, align=right] {``Fantastic, go forth and prosper!''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) XI} \begin{tikzpicture}[overlay, remember picture] \node[anchor=south east] (ri-logo) at ($(current page.south east)+(-5mm,10mm)$) {\includegraphics[width=16mm]{assets/ri-logo.eps}}; \fontsize{12}{15} \node[anchor=south west] (me) at ($(current page.south west)+(5mm,10mm)$) {\includegraphics[width=2cm]{media/me.jpg}}; \node[text width=8cm, right=3mm of me, align=left] {``I've been meaning to read Hogan's famous \emph{Impedance Control}~\autocite{hogan1985impedance} paper, I guess I'll start there...''}; \end{tikzpicture} \end{frame} \begin{frame} \addtocounter{framenumber}{-1} \frametitle{How I Ended Up Here (Some Context) XII} \begin{tikzpicture}[overlay, remember picture] \fontsize{18}{15} \node[anchor=center, minimum width=2cm] at (current page.center) {\dots~Two Years Later \dots}; \end{tikzpicture} \end{frame} \begin{frame} \frametitle{Me, circa July 2018} \begin{tikzpicture}[overlay, remember picture] \node[anchor=center] (paranoid) at (current page.center) {\includegraphics[width=8cm]{media/charlie-paranoid}}; \node[anchor=center, below=0mm of paranoid] {``So it's all about causality\dots~and feedback!''}; \end{tikzpicture} \end{frame} \section{The Big Picture} \begin{frame} \frametitle{Back to Basics} \begin{itemize}[<+->] \item Want a concise \emph{theory of robotics}\dots \item Interested in the \emph{physics} common to robotics problems \item Not worried about SLAM, POMDPs, etc\dots~there are bigger fish to fry (we're skimming over the basics!) \begin{itemize} \item i.e. Moravec's paradox \autocite{moravec1988mind} \end{itemize} \item Inherently a \emph{breadth-first} approach, since we're looking for a unifying framework \end{itemize} \end{frame} \begin{frame} \frametitle{Problem 1: What is a Robot?} \begin{itemize} \item I know it's a cliché to bring this up\dots \pause~but I must! \pause \begin{itemize} \item Does the ambiguity really matter? \pause \item Maybe not, but some unifying \emph{theme} would be useful! \end{itemize} \end{itemize} \end{frame} \begin{frame} \frametitle{Problem 2: What is Manipulation?} \begin{itemize} \item To be honest, I had a very shallow understanding of manipulation until I met Matt \pause \begin{itemize} \item I imagined it was just factory robot stuff \pause \item It took some reflection to appreciate the depth of ``manipulation'' \end{itemize} \end{itemize} \end{frame} \begin{frame} \frametitle{Problem 2: What is Manipulation?} \begin{tikzpicture}[overlay, remember picture] \fontsize{15}{12} \node[anchor=center, text width=0.8\textwidth,align=center] (manip-def) at ($(current page.center)+(0,-3mm)$) {``Manipulation refers to an agent’s control of its environment through selective contact.''}; \small \node[anchor=south east, align=right] at ($(current page.south east)+(-1cm,1cm)$) {--- \emph{Matt Mason}, ``Toward Robotic Manipulation'' \autocite{Mason2018}}; \end{tikzpicture} \end{frame} \begin{frame} \frametitle{Problem 3: Locomotion and Manipulation, Segregated} \begin{itemize} \item Locomotion and manipulation are studied separately in robotics\pause \begin{itemize} \item \dots~and biomechanics, for that matter \item Seems quite natural at first, we all talk about the two as separate specializations in robotics \end{itemize}\pause \item Eventually, the notion of \emph{``duality''} comes up\dots \begin{itemize}\pause \item Locomotion and manipulation sometimes overlap \begin{itemize} \item Pai et al.'s \emph{Platonic Beasts} \autocite{pai1994platonic} \item Mason et al.'s \emph{Mobipulator} \autocite{MasonMobileManipulator1999} \autocite{MasonDesktopMobileManipulators2000} \item Also, literally everywhere in biology \end{itemize} \item Perhaps it just comes down to a change of reference? \begin{itemize} \item Just a matter of ``what pushes off of what?'' \item Locomotion is ``self-manipulation'', e.g. Aaron Johnson's PhD thesis \autocite{johnson2014self} and related works \autocite{johnson2012standing}\autocite{johnson2016hybrid} \end{itemize} \end{itemize} \end{itemize} \end{frame} \begin{frame} \frametitle{Problem 3: Locomotion and Manipulation, United} \vspace{-6em} \begin{itemize} \item The ``self-manipulation'' view of locomotion is consistent with our definition of ``manipulation'': \begin{itemize} \item An agent may control its environment through selective contact (i.e. ``manipulation'') by moving about in it (i.e. ``locomotion''). \footnotemark \end{itemize} \end{itemize} \footnotetext{It helps to take on an egocentric point of view to visualize this.} \pause \begin{tikzpicture}[overlay, remember picture] \fontsize{15}{12} \node[anchor=center,text width=0.8\textwidth,align=center] (loco-manip) at ($(current page.center)+(0,-10mm)$) {So locomotion is just a subset of manipulation!}; \end{tikzpicture} \end{frame} \begin{frame} \frametitle{Problem 3: Locomotion and Manipulation, United} \begin{itemize} \item Not a terribly practical insight\dots \pause~but thinking back to \emph{Problem 1}\dots \end{itemize} \begin{tikzpicture}[overlay, remember picture] \node[anchor=center,text width=0.8\textwidth,align=center] (manip-is-king) at ($(current page.center)+(0,-10mm)$) {\Large \color{red} Manipulation \emph{is} the central theme in robotics!}; \end{tikzpicture} \end{frame} \begin{frame} \frametitle{Embodiment \& Hogan's Physical-Equivalence ``Postulate''} \begin{itemize}[<+->] \item Embodiment \begin{itemize} \item Vaguely, the idea that robots exist in the real world and are inherently tied to their environment \item Presently resides in the cognitive science community (as in ``embodied \emph{cognition}'') \end{itemize} \item \emph{Hogan's} Physical-Equivalent Principle \begin{itemize} \item ``It is impossible tO devise a controller which will cause a physical system to present an apparent behavior 10 its environment which is distinguishable from that of a purely physical system'' \autocite{hogan1985impedance} \item Basic argument for this is ``you can't break thermodynamic laws'' \item But more intuitively, the robot is a real thing, you can't make it do not real things \end{itemize} \end{itemize} \end{frame} \section{A Unifying Framework} \begin{frame} \frametitle{Port-Hamiltonian Systems Theory} \begin{itemize}[<+->] \item The symbiosis of: \begin{itemize}[<+->] \item Bond graph theory (\emph{Paynter, Hogan, Breedveld, van Dijk}) \item Hamiltonian dynamics on manifolds (i.e. ``geometric mechanics'') \item Poisson / Dirac structures \end{itemize} \item Principal contributors include \emph{Stramigioli, van der Schaft, Maschke} \end{itemize} \end{frame} \begin{frame} \frametitle{Port-Hamiltonian Systems Theory} \begin{itemize} \item Port-based Analysis \begin{itemize} \item Inherits the bond-graph notion of power ports \item Treats systems in terms of power flow between components \item Each bond represents the conjugate pair of an effort and flow \end{itemize} \end{itemize} \end{frame} \begin{frame} \frametitle{Port-Hamiltonian Systems Theory} \begin{itemize} \item Hamiltonian Dynamics \begin{itemize} \item Provides a fully geometric (intrinsic, coordinate free) description of system dynamics \item Equivalent to (and convertible from/to) Lagrangian formulation, but better! \begin{itemize} \item Riemannian geometry of Lagrangian dynamics replaced with symplectic geometry, in which fundamental invariants are preserved \item Configuration space of Lagrangian dynamics replaced with state space \item Hamiltonian formulation directly yields a system of first order differential equations \end{itemize} \item Avoiding nonholonomic constraints yields explicit ODE\footnote{May be a stiff explicit ODE! So, soften your intermittent contacts!} \end{itemize} \end{itemize} \end{frame} \begin{frame} \frametitle{Port-Hamiltonian Systems Theory} \begin{itemize} \item System fully defined by: \begin{itemize} \item Energy function captures all energy storage elements in system \item Resistive structure captures all dissipative elements in system \item Poisson or Dirac interconnection structure defines power flow within system \begin{itemize} \item \emph{Storage port} connects to energy storage \item \emph{Dissipative port} connects to resistive structure \item \emph{Interaction port} connects to environment (\textbf{dynamic system} not known a-priori or directly controlled) \item \emph{Controller port} connects to controller (\textbf{dynamic system} that the designer has control over) \end{itemize} \end{itemize} \end{itemize} \end{frame} \begin{frame} \frametitle{Working Through an Example} \end{frame} \section{Closing Thoughts} \begin{frame} \frametitle{Closing Thoughts} \begin{itemize} \item Manipulation is the common theme in robotics \item Embodiment \Leftrightarrow Hogan's Physical Equivalence Principle \autocite{hogan1985impedance} \item Port-Hamiltonian Systems Theory is the framework to unify robotics \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \setcounter{showProgressBar}{0} \setcounter{showSlideNumbers}{0} \appendix \backupbegin \section{Acknowledgments} % \begin{frame} % \frametitle{Teaching with CMU's Gelfand Outreach Center} % \begin{tikzpicture}[overlay, remember picture] % \node[anchor=south east] (gelfand-logo) at ($(current page.south east) + (-8mm, 8mm)$) {\includegraphics[width=4cm]{media/gelfand-logo.jpg}}; % \end{tikzpicture} % \vspace{9em} % \begin{itemize} % \item Introduction to Robotics with the Finch Platform % \begin{itemize} % \item Each session is 5 days, 3 hrs/day % \item 4\textsuperscript{th} and 5\textsuperscript{th} graders % \item 1 session Summer 2017 + 2 sessions Summer 2018 % \end{itemize} % \end{itemize} %\end{frame} % %\begin{frame} %\frametitle{Teaching with CMU's Gelfand Outreach Center} %\begin{tikzpicture}[overlay, remember picture] %\node[anchor=south east] (gelfand-logo) at ($(current page.south east) + (-8mm, 8mm)$) {\includegraphics[width=4cm]{media/gelfand-logo.jpg}}; %\end{tikzpicture} %\vspace{9em} %\begin{itemize} %\item Saturday Series LEGO WeDo Robotics %\begin{itemize} % \item 3 hour course % \item 2\textsuperscript{nd} and 3\textsuperscript{rd} graders % \item 1 session Spring 2018 %\end{itemize} %\end{itemize} %\end{frame} % %\begin{frame} %\frametitle{Robotics Institute Meme Facebook Page} %\begin{tikzpicture}[overlay, remember picture] %\node[anchor=center] (ri-meme-screenshot) at (current page.center) {\includegraphics[width=\textwidth]{media/ri-memes.jpg}}; %\end{tikzpicture} %\end{frame} % %\begin{frame} %\frametitle{Robotics Institute Meme Facebook Page} %\vspace{9em} %\begin{itemize} %\item Some statistics: %\begin{itemize} %\item The RI's first and only meme page %\item Formed in March 2018 %\item 170 members %\item 30 memes, 23 original contributions! %\end{itemize} %\end{itemize} %\begin{tikzpicture}[overlay, remember picture] %\node[anchor=south east] (ri-meme-3) at ($(current page.south east) + (2mm,5mm)$) {\includegraphics[width=7.5cm]{media/ri-meme-manifold-optimization.jpg}}; %\end{tikzpicture} %\begin{tikzpicture}[overlay, remember picture] %\node[anchor=north east] (ri-meme-1) at ($(current page.north east) + (-45mm,-12mm)$) {\includegraphics[width=3.5cm]{media/ri-meme-thesis-anxiety.jpg}}; %\end{tikzpicture} %\begin{tikzpicture}[overlay, remember picture] %\node[anchor=north west] (ri-meme-2) at ($(current page.north west) + (10mm,-12mm)$) {\includegraphics[width=5cm]{media/ri-meme-ros-sleep.jpg}}; %\end{tikzpicture} %\end{frame} \begin{frame} \frametitle{Cheers} \begin{itemize} \item Matt Mason \item Aaron Johnson \& Will Martin \item The MLab \item Ross Knepper, Hod Lipson, Ephrahim Garcia, Boris Kogan, Mike Meller \item Jean Harpley \item Cameron \item Malcolm X, Nina Simone, and George Harrison \item Parents \end{itemize} \end{frame} \section{Questions?} \section{Bibliography} \nocite{*} \begin{frame}[allowframebreaks] \frametitle{Bibliography} \printbibliography[heading=none] \end{frame} \backupend \end{document}
! time.f90 ! ! Example that calls POSIX time functions. ! ! Author: Philipp Engel ! Licence: ISC program main use, intrinsic :: iso_c_binding use :: unix implicit none character(len=24) :: str ! Date and time string. integer(kind=8) :: ts ! UNIX timestamp. type(c_tm) :: tm ! Broken-down time. type(c_ptr) :: ptr ! C pointer to char. ! Print UNIX timestamp. ts = c_time(int(0, kind=8)) print '("UNIX Timestamp: ", i0)', ts ! Print date and time string (of 2020-10-01 12:00:00). tm = c_tm(0, 0, 12, 1, 9, 2020 - 1900, 4, 0, 0) ptr = c_asctime(tm) call c_f_str_ptr(ptr, str) print '("Date and Time.: ", a)', str end program main
[STATEMENT] lemma polysubst0_I: "Ipoly (b # bs) (polysubst0 a t) = Ipoly ((Ipoly (b # bs) a) # bs) t" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lparr>polysubst0 a t\<rparr>\<^sub>p\<^bsup>b # bs\<^esup> = \<lparr>t\<rparr>\<^sub>p\<^bsup>\<lparr>a\<rparr>\<^sub>p\<^bsup>b # bs\<^esup> # bs\<^esup> [PROOF STEP] by (induct t) simp_all
{-# OPTIONS --without-K --safe #-} -- This module provides the basic expression type for polynomials. module Polynomial.Expr where open import Data.Nat using (ℕ) open import Data.Fin using (Fin) infixl 6 _⊕_ infixl 7 _⊗_ infixr 8 _⊛_ data Expr {ℓ} (A : Set ℓ) (n : ℕ) : Set ℓ where Κ : A → Expr A n Ι : Fin n → Expr A n _⊕_ : Expr A n → Expr A n → Expr A n _⊗_ : Expr A n → Expr A n → Expr A n _⊛_ : Expr A n → ℕ → Expr A n ⊝_ : Expr A n → Expr A n open import Polynomial.Parameters module Eval {c r₁ r₂ r₃} (homo : Homomorphism c r₁ r₂ r₃) where open Homomorphism homo open import Polynomial.Exponentiation rawRing open import Data.Vec as Vec using (Vec) ⟦_⟧ : ∀ {n} → Expr Raw.Carrier n → Vec Carrier n → Carrier ⟦ Κ x ⟧ ρ = ⟦ x ⟧ᵣ ⟦ Ι x ⟧ ρ = Vec.lookup ρ x ⟦ x ⊕ y ⟧ ρ = ⟦ x ⟧ ρ + ⟦ y ⟧ ρ ⟦ x ⊗ y ⟧ ρ = ⟦ x ⟧ ρ * ⟦ y ⟧ ρ ⟦ ⊝ x ⟧ ρ = - ⟦ x ⟧ ρ ⟦ x ⊛ i ⟧ ρ = ⟦ x ⟧ ρ ^ i
/** * \file cmdline.cpp * \author Justin Too <[email protected]> * \date April 4, 2012 */ /*----------------------------------------------------------------------------- * Dependencies *---------------------------------------------------------------------------*/ #include "sage3basic.h" #include "cmdline.h" #include "keep_going.h" #include "FileUtility.h" #include "Diagnostics.h" // Rose::Diagnostics #include <boost/foreach.hpp> #include <boost/algorithm/string/replace.hpp> #include <Sawyer/CommandLine.h> using namespace Rose; // temporary, until this file lives in namespace Rose #include <inttypes.h> /* for %" PRIuPTR " vs. %Iu handling */ /*----------------------------------------------------------------------------- * Variable Definitions *---------------------------------------------------------------------------*/ ROSE_DLL_API int Rose::Cmdline::verbose = 0; ROSE_DLL_API bool Rose::Cmdline::Java::Ecj::batch_mode = false; ROSE_DLL_API std::list<std::string> Rose::Cmdline::Fortran::Ofp::jvm_options; ROSE_DLL_API std::list<std::string> Rose::Cmdline::Java::Ecj::jvm_options; std::list<std::string> Rose::Cmdline::X10::X10c::jvm_options; /*----------------------------------------------------------------------------- * namespace Rose::Cmdline { * namespace Cmdline { *---------------------------------------------------------------------------*/ void Rose::Cmdline:: makeSysIncludeList(const Rose_STL_Container<string>& dirs, Rose_STL_Container<string>& result, bool using_nostdinc_option) { #if 0 std::string argString_result_top = CommandlineProcessing::generateStringFromArgList(result,false,false); printf ("In makeSysIncludeList(): top: argString_result_top = %s \n",argString_result_top.c_str()); #endif string includeBase = findRoseSupportPathFromBuild("include-staging", "include/edg"); for (Rose_STL_Container<string>::const_iterator i = dirs.begin(); i != dirs.end(); ++i) { ROSE_ASSERT (!i->empty()); string fullPath = (*i)[0] == '/' ? *i : (includeBase + "/" + *i); #if 1 // DQ (11/8/2011): We want to exclude the /usr/include directory since it will be search automatically by EDG. // If we include it here it will become part of the -sys_include directories and that will cause it to // be searched before the -I<directory> options (which is incorrect). if ( SgProject::get_verbose() > 1 ) { printf ("In makeSysIncludeList(): Building commandline: --sys_include %s fullPath = %s \n",(*i).c_str(),fullPath.c_str()); } if (*i == "/usr/include") { if ( SgProject::get_verbose() > 1 ) { printf ("Filtering out from the sys_include paths: *i = %s \n",(*i).c_str()); } } else { // DQ (2/1/2015): Adding support for optional use of gnu nostdinc option. This causes system // directories to not be searched, however, we still need to reference at least one ROSE // specific directory. This is required for compiling some kernel level applications. // result.push_back("--sys_include"); // result.push_back(fullPath); if (using_nostdinc_option == true) { if (*i == "gcc_HEADERS" || *i == "g++_HEADERS") { #if 0 printf ("In makeSysIncludeList(): Where using_nostdinc_option == true: detected either gcc_HEADERS or g++_HEADERS ROSE specific directories \n"); #endif result.push_back("--sys_include"); result.push_back(fullPath); } else { #if 0 printf ("In makeSysIncludeList(): Where using_nostdinc_option == true: ignoring specific system directories (except either gcc_HEADERS or g++_HEADERS ROSE specific directories) \n"); #endif } } else { result.push_back("--sys_include"); result.push_back(fullPath); } } #else // Old code that would include the "/usr/include" path as an -sys_include entry. // This whole include paths issue is complex enough that I would like to leave this // code in place for a while. result.push_back("--sys_include"); result.push_back(fullPath); #endif #if 0 std::string argString_result = CommandlineProcessing::generateStringFromArgList(result,false,false); printf ("In makeSysIncludeList(): bottom of loop: argString_result = %s \n",argString_result.c_str()); #endif } #if 0 std::string argString_result = CommandlineProcessing::generateStringFromArgList(result,false,false); printf ("In makeSysIncludeList(): bottom of function: argString_result = %s \n",argString_result.c_str()); #endif } /*----------------------------------------------------------------------------- * namespace CommandlineProcessing { *---------------------------------------------------------------------------*/ #define CASE_SENSITIVE_SYSTEM 1 bool CommandlineProcessing::isOptionWithParameter ( vector<string> & argv, string optionPrefix, string option, string & optionParameter, bool removeOption ) { // I could not make this work cleanly with valgrind withouth allocatting memory twice string localString =""; // printf ("Calling sla for string! removeOption = %s \n",removeOption ? "true" : "false"); //printf (" argv %d optionPrefix %s option %s localString %s \n",argv.size(), optionPrefix.c_str(), option.c_str() , localString.c_str() ); int optionCount = sla(argv, optionPrefix, "($)^", option, &localString, removeOption ? 1 : -1); // printf ("DONE: Calling sla for string! optionCount = %d localString = %s \n",optionCount,localString.c_str()); // optionCount = sla(argv, optionPrefix, "($)^", option, &localString, removeOption ? 1 : -1); // printf ("DONE: Calling sla for string! optionCount = %d localString = %s \n",optionCount,localString.c_str()); if (optionCount > 0) optionParameter = localString; return (optionCount > 0); } // Note that moving this function from commandline_processing.C to this file (sageSupport.C) // permitted the validExecutableFileSuffixes to be initialized properly! void CommandlineProcessing::initExecutableFileSuffixList ( ) { static bool first_call = true; if ( first_call == true ) { // DQ (1/5/2008): For a binary (executable) file, no suffix is a valid suffix, so allow this case validExecutableFileSuffixes.push_back(""); // printf ("CASE_SENSITIVE_SYSTEM = %d \n",CASE_SENSITIVE_SYSTEM); #if(CASE_SENSITIVE_SYSTEM == 1) validExecutableFileSuffixes.push_back(".exe"); #else // it is a case insensitive system validExecutableFileSuffixes.push_back(".EXE"); #endif first_call = false; } } // DQ (1/16/2008): This function was moved from the commandling_processing.C file to support the debugging specific to binary analysis /* This function not only looks at the file name, but also checks that the file exists, can be opened for reading, and has * specific values for its first two bytes. Checking the first two bytes here means that each time we add support for a new * magic number in the binary parsers we have to remember to update this list also. Another problem is that the binary * parsers understand a variety of methods for neutering malicious binaries -- transforming them in ways that make them * unrecognized by the operating system on which they're intended to run (and thus unrecongizable also by this function). * Furthermore, CommandlineProcessing::isBinaryExecutableFile() contains similar magic number checking. [RPM 2010-01-15] */ bool CommandlineProcessing::isExecutableFilename ( string name ) { initExecutableFileSuffixList(); if (SgProject::get_verbose() > 0) { printf ("CommandlineProcessing::isExecutableFilename(): name = %s validExecutableFileSuffixes.size() = %" PRIuPTR " \n",name.c_str(),validExecutableFileSuffixes.size()); } ROSE_ASSERT(validExecutableFileSuffixes.empty() == false); int length = name.size(); for ( Rose_STL_Container<string>::iterator j = validExecutableFileSuffixes.begin(); j != validExecutableFileSuffixes.end(); j++ ) { int jlength = (*j).size(); // printf ("jlength = %d *j = %s \n",jlength,(*j).c_str()); if ( (length > jlength) && (name.compare(length - jlength, jlength, *j) == 0) ) { bool returnValue = false; // printf ("passed test (length > jlength) && (name.compare(length - jlength, jlength, *j) == 0): opening file to double check \n"); // Open file for reading bool firstBase = isValidFileWithExecutableFileSuffixes(name); if (firstBase == true) { FILE* f = fopen(name.c_str(), "rb"); ROSE_ASSERT(f != NULL); // Check for if this is a binary executable file! int character0 = fgetc(f); int character1 = fgetc(f); // Note that there may be more executable formats that this simple test will not catch. // The first character of an ELF binary is '\177' and for a PE binary it is 'M' // if (character0 == 127) // if ((character0 == 0x7F && character1 == 0x45) || // (character0 == 0x4D && character1 == 0x5A)) bool secondBase = ( (character0 == 0x7F && character1 == 0x45) || (character0 == 0x4D && character1 == 0x5A) ); if (secondBase == true) { // printf ("Found a valid executable file! \n"); returnValue = true; } // printf ("First character in file: character0 = %d (77 == %c) \n",character0,'\77'); fclose(f); } if (returnValue) return true; } } return false; } bool CommandlineProcessing::isValidFileWithExecutableFileSuffixes ( string name ) { // DQ (8/20/2008): // There may be files that are marked as appearing as an executable but are not // (we want to process them so that they fail in the binary file format tests // rather then here). so we need to add them to the list of sourceFiles (executable // counts as source for binary analysis in ROSE). initExecutableFileSuffixList(); // printf ("CommandlineProcessing::isValidFileWithExecutableFileSuffixes(): name = %s validExecutableFileSuffixes.size() = %" PRIuPTR " \n",name.c_str(),validExecutableFileSuffixes.size()); ROSE_ASSERT(validExecutableFileSuffixes.empty() == false); int length = name.size(); for ( Rose_STL_Container<string>::iterator j = validExecutableFileSuffixes.begin(); j != validExecutableFileSuffixes.end(); j++ ) { int jlength = (*j).size(); // printf ("jlength = %d *j = %s \n",jlength,(*j).c_str()); if ( (length > jlength) && (name.compare(length - jlength, jlength, *j) == 0) ) { bool returnValue = false; // printf ("passed test (length > jlength) && (name.compare(length - jlength, jlength, *j) == 0): opening file to double check \n"); #if 0 printf ("In CommandlineProcessing::isValidFileWithExecutableFileSuffixes(): name = %s \n",name.c_str()); #endif // Open file for reading if ( boost::filesystem::exists(name.c_str()) ) { returnValue = true; // printf ("This is a valid file: %s \n",name.c_str()); } else { printf ("Could not open specified input file: %s \n\n",name.c_str()); // DQ (8/20/2008): We need to allow this to pass, since Qing's command line processing // mistakenly treats all the arguments as filenames (and most do not exist as valid files). // If we can't open the file then I think we should end in an error! // ROSE_ASSERT(false); // DQ (1/21/2009): This fails for ./binaryReader /home/dquinlan/ROSE/svn-rose/developersScratchSpace/Dan/Disassembler_tests//home/dquinlan/ROSE/svn-rose/developersScratchSpace/Dan/Disassembler_tests/arm-ctrlaltdel ROSE_ASSERT(false); } if (returnValue) return true; } } return false; } // DQ (1/16/2008): This function was moved from the commandling_processing.C file to support the debugging specific to binary analysis // bool CommandlineProcessing::isOptionTakingFileName( string argument ) bool CommandlineProcessing::isOptionTakingSecondParameter( string argument ) { bool result = false; // printf ("In CommandlineProcessing::isOptionTakingFileName(): argument = %s \n",argument.c_str()); // List any rose options that take source filenames here, so that they can avoid // being confused with the source file name that is to be read by EDG and translated. // DQ (1/6/2008): Added another test for a rose option that takes a filename if ( argument == "-o" || // Used to specify output file to compiler argument == "-opt" || // Used in loopProcessor // DQ (1/13/2009): This option should only have a single leading "-", not two. // argument == "--include" || // Used for preinclude list (to include some header files before all others, common requirement for compiler) argument == "-include" || // Used for preinclude file list (to include some header files before all others, common requirement for compiler) argument == "-isystem" || // Used for preinclude directory list (to specify include paths to be search before all others, common requirement for compiler) // Darwin options argument == "-dylib_file" || // -dylib_file <something>:<something> argument == "-framework" || // -iframeworkdir (see man page for Apple GCC) // ROSE options argument == "-rose:output" || // Used to specify output file to ROSE argument == "-rose:o" || // Used to specify output file to ROSE (alternative to -rose:output) argument == "-rose:compilationPerformanceFile" || // Use to output performance information about ROSE compilation phases argument == "-rose:verbose" || // Used to specify output of internal information about ROSE phases argument == "-rose:log" || // Used to conntrol Rose::Diagnostics argument == "-rose:assert" || // Controls behavior of failed assertions argument == "-rose:test" || argument == "-rose:backendCompileFormat" || argument == "-rose:outputFormat" || #if 0 // DQ (1/21/2017): Moved to be an option that has three parameters (rose option, edg option, and edg option's parameter). argument == "-edg_parameter:" || argument == "--edg_parameter:" || #endif argument == "-rose:generateSourcePositionCodes" || argument == "-rose:embedColorCodesInGeneratedCode" || argument == "-rose:instantiation" || argument == "-rose:includeCommentsAndDirectives" || argument == "-rose:includeCommentsAndDirectivesFrom" || argument == "-rose:excludeCommentsAndDirectives" || argument == "-rose:excludeCommentsAndDirectivesFrom" || argument == "-rose:includePath" || argument == "-rose:excludePath" || argument == "-rose:includeFile" || argument == "-rose:excludeFile" || argument == "-rose:astMergeCommandFile" || argument == "-rose:projectSpecificDatabaseFile" || // TOO1 (2/13/2014): Starting to refactor CLI handling into separate namespaces Rose::Cmdline::Unparser::OptionRequiresArgument(argument) || Rose::Cmdline::Fortran::OptionRequiresArgument(argument) || Rose::Cmdline::Java::OptionRequiresArgument(argument) || // negara1 (08/16/2011) argument == "-rose:unparseHeaderFilesRootFolder" || // DQ (11/6/2018): Adding support to specify the root directory of an application for header file unparsing and token based unparsing). argument == "-rose:applicationRootDirectory" || // DQ (8/20/2008): Add support for Qing's options! argument == "-annot" || argument == "-bs" || isOptionTakingThirdParameter(argument) || // DQ (9/30/2008): Added support for java class specification required for Fortran use of OFP. argument == "--class" || // AS (02/20/08): When used with -M or -MM, -MF specifies a file to write // the dependencies to. Need to tell ROSE to ignore that output paramater argument == "-MF" || argument == "-MT" || argument == "-MQ" || argument == "-outputdir" || // FMZ (12/22/1009) added for caf compiler // DQ (9/19/2010): UPC support for upc_threads to define the "THREADS" variable. argument == "-rose:upc_threads" || // DQ (9/26/2011): Added support for detection of dangling pointers within translators built using ROSE. argument == "-rose:detect_dangling_pointers" || // Used to specify level of debugging support for optional detection of dangling pointers // DQ (1/16/2012): Added all of the currently defined dot file options. argument == "-rose:dotgraph:asmFileFormatFilter" || argument == "-rose:dotgraph:asmTypeFilter" || argument == "-rose:dotgraph:binaryExecutableFormatFilter" || argument == "-rose:dotgraph:commentAndDirectiveFilter" || argument == "-rose:dotgraph:ctorInitializerListFilter" || argument == "-rose:dotgraph:defaultColorFilter" || argument == "-rose:dotgraph:defaultFilter" || argument == "-rose:dotgraph:edgeFilter" || argument == "-rose:dotgraph:emptySymbolTableFilter" || // DQ (7/22/2012): Added support to ignore some specific empty IR nodes. argument == "-rose:dotgraph:emptyBasicBlockFilter" || argument == "-rose:dotgraph:emptyFunctionParameterListFilter" || argument == "-rose:dotgraph:expressionFilter" || argument == "-rose:dotgraph:fileInfoFilter" || argument == "-rose:dotgraph:frontendCompatibilityFilter" || argument == "-rose:dotgraph:symbolFilter" || argument == "-rose:dotgraph:typeFilter" || argument == "-rose:dotgraph:variableDeclarationFilter" || argument == "-rose:dotgraph:noFilter" || // DQ (1/8/2014): We need the "-x" option which takes a single option to specify the language "c" or "c++". // This is required where within the "git" build system the input file is "/dev/null" which does not have // a suffix from which to compute the associated language. argument == "-x" || // DQ (1/20/2014): Adding support for gnu's -undefined option. argument == "-u" || argument == "-undefined" || // DQ (1/26/2014): Support for usage such as -version-info 8:9:8 argument == "-version-info" || // DQ (1/30/2014): Support for usage such as -rose:unparse_tokens_testing 4 argument == "-rose:unparse_tokens_testing" || // DQ (12/10/2016): This does not take a parameter on any later version compiler that I know of. // DQ (1/26/2014): Support for make dependence option -MM <file name for dependence info> // argument == "-MM" || // DQ (3/25/2014): We need the icpc/icc [-fp-model <arg>] command-line compiler option to be // passed to the backend compiler properly. The [-fp-model] option always has a single argument. argument == "-fp-model" || // DQ (1/21/2015): -diag-disable can take a collection of optional parameters: e.g. cpu-dispatch argument == "-diag-enable" || argument == "-diag-disable" || argument == "-diag-error" || argument == "-diag-warning" || argument == "-diag-remark" || // TOO1 (5/14/2015): Add support for GCC --param, e.g. "--param inline-unit-growth=900" found in Valgrind argument == "--param" || // --param variable=value false) { result = true; } // printf ("In CommandlineProcessing::isOptionTakingFileName(): argument = %s result = %s \n",argument.c_str(),result ? "true" : "false"); return result; } bool CommandlineProcessing::isOptionTakingThirdParameter( string argument ) { bool result = false; // printf ("In CommandlineProcessing::isOptionTakingFileName(): argument = %s \n",argument.c_str()); // List any rose options that take source filenames here, so that they can avoid // being confused with the source file name that is to be read by EDG and translated. // DQ (1/6/2008): Added another test for a rose option that takes a filename if ( false || // Used to specify yet another parameter // DQ (8/20/2008): Add support for Qing's options! argument == "-unroll" || #if 1 // DQ (1/21/2017): Allow this to take the edg option plus it's parameter (3 paramters with the rose option wrapper, not two). argument == "-edg_parameter:" || argument == "--edg_parameter:" || #endif false ) { result = true; } // printf ("In CommandlineProcessing::isOptionTakingFileName(): argument = %s result = %s \n",argument.c_str(),result ? "true" : "false"); return result; } // DQ (1/16/2008): This function was moved from the commandling_processing.C file to support the debugging specific to binary analysis Rose_STL_Container<string> CommandlineProcessing::generateSourceFilenames ( Rose_STL_Container<string> argList, bool binaryMode ) { Rose_STL_Container<string> sourceFileList; #ifdef ROSE_BUILD_JAVA_LANGUAGE_SUPPORT // DQ (1/10/2019): This is an issue when using ROSE for non Java language support in some environment. // This was the cause of a bug that contaminated the backend compiler command line for an installation // or ROSE for a specific sponsor. { // Expand Javac's @argfile since it may contain filenames argList = Rose::Cmdline::Java::ExpandArglist(argList); } #endif bool isSourceCodeCompiler = false; { //Find out if the command line is a source code compile line Rose_STL_Container<string>::iterator j = argList.begin(); // skip the 0th entry since this is just the name of the program (e.g. rose) ROSE_ASSERT(argList.size() > 0); j++; while ( j != argList.end() ) { if ( (*j).size() ==2 && (((*j)[0] == '-') && ( ((*j)[1] == 'o') ) ) ) { isSourceCodeCompiler = true; //std::cout << "Set isSourceCodeCompiler " << *j << std::endl; break; } j++; } } Rose_STL_Container<string>::iterator i = argList.begin(); if (SgProject::get_verbose() > 1) { printf ("######################### Inside of CommandlineProcessing::generateSourceFilenames() ############################ \n"); } // skip the 0th entry since this is just the name of the program (e.g. rose) ROSE_ASSERT(argList.size() > 0); i++; while ( i != argList.end() ) { // Count up the number of filenames (if it is ZERO then this is likely a // link line called using the compiler (required for template processing // in C++ with most compilers)) if there is at least ONE then this is the // source file. Currently their can be up to maxFileNames = 256 files // specified. // most options appear as -<option> // have to process +w2 (warnings option) on some compilers so include +<option> // DQ (1/5/2008): Ignore things that would be obvious options using a "-" or "+" prefix. // if ( ((*i)[0] != '-') || ((*i)[0] != '+') ) if ( (*i).empty() || (((*i)[0] != '-') && ((*i)[0] != '+')) ) { // printf ("In CommandlineProcessing::generateSourceFilenames(): Look for file names: argv[%d] = %s length = %" PRIuPTR " \n",counter,(*i).c_str(),(*i).size()); if (!isSourceFilename(*i) && (binaryMode || !isObjectFilename(*i)) && (binaryMode || isExecutableFilename(*i))) { // printf ("This is an executable file: *i = %s \n",(*i).c_str()); // executableFileList.push_back(*i); if(isSourceCodeCompiler == false || binaryMode == true) sourceFileList.push_back(*i); goto incrementPosition; } // PC (4/27/2006): Support for custom source file suffixes // if ( isSourceFilename(*i) ) if ( isObjectFilename(*i) == false && isSourceFilename(*i) == true ) { // printf ("This is a source file: *i = %s \n",(*i).c_str()); // foundSourceFile = true; sourceFileList.push_back(*i); goto incrementPosition; } #if 1 // cout << "second call " << endl; if ( isObjectFilename(*i) == false && isSourceFilename(*i) == false && isValidFileWithExecutableFileSuffixes(*i) == true ) { // printf ("This is at least an existing file of some kind: *i = %s \n",(*i).c_str()); // foundSourceFile = true; if(isSourceCodeCompiler == false || binaryMode == true) sourceFileList.push_back(*i); goto incrementPosition; } #endif #if 0 if ( isObjectFilename(*i) ) { objectFileList.push_back(*i); } #endif } // DQ (12/8/2007): Looking for rose options that take filenames that would accidentally be considered as source files. // if (isOptionTakingFileName(*i) == true) if (isOptionTakingSecondParameter(*i) == true) { if (isOptionTakingThirdParameter(*i) == true) { // Jump over the next argument when such options are identified. i++; } // Jump over the next argument when such options are identified. i++; } incrementPosition: i++; } if (SgProject::get_verbose() > 1) { printf ("sourceFileList = %s \n",StringUtility::listToString(sourceFileList).c_str()); printf ("######################### Leaving of CommandlineProcessing::generateSourceFilenames() ############################ \n"); } return sourceFileList; } /*----------------------------------------------------------------------------- * namespace SgProject { *---------------------------------------------------------------------------*/ void SgProject::processCommandLine(const vector<string>& input_argv) { // This functions only copies the command line and extracts information from the // command line which is useful at the SgProject level (other information useful // at the SgFile level is not extracted). // Specifically: // 1) --help is processed (along with -help, to be friendly) // 2) -o <filename> is processed (since both the compilation and the linking // phases must know the output file name and it makes sense to process that once). // 3) Lists of files and libraries are processed (sense they too are required in // both compilation and linking). (e.g. -l<libname>, -L <directory>, <libname>.a, // <filename>.C, <filename>.c, -I<directory name>, <filename>.h // NOTE: there is no side-effect to argc and argv. Thus the original ROSE translator can // see all options. Any ROSE or EDG specific options can be striped by calling the // appropriate functions to strip them out. // This function now makes an internal copy of the command line parameters to // allow the originals to remain unmodified (SLA modifies the command line). #if 0 printf ("Inside of SgProject::processCommandLine() \n"); #endif // local copies of argc and argv variables // The purpose of building local copies is to avoid // the modification of the command line by SLA (to save the original command line) vector<string> local_commandLineArgumentList = input_argv; { // Perform normalization on CLI before processing and storing // Turn "-I <path>" into "-I<path>" for subsequent processing local_commandLineArgumentList = Rose::Cmdline::NormalizeIncludePathOptions( local_commandLineArgumentList); } #ifdef ROSE_BUILD_JAVA_LANGUAGE_SUPPORT // DQ (1/10/2019): This is an issue when using ROSE for non Java language support in some environment. // This was the cause of a bug that contaminated the backend compiler command line for an installation // or ROSE for a specific sponsor. { // Expand Javac's @argfile before CLI processing local_commandLineArgumentList = Rose::Cmdline::Java::ExpandArglist( local_commandLineArgumentList); } #endif // Add "-D_REENTRANT" if "-pthread" is present before we save the command-line or do any other processing. vector<string>::iterator pthread = find(local_commandLineArgumentList.begin(), local_commandLineArgumentList.end(), "-pthread"); if (pthread != local_commandLineArgumentList.end()) local_commandLineArgumentList.insert(++pthread, "-D_REENTRANT"); // Save a deep copy fo the original command line input the the translator // pass in out copies of the argc and argv to make clear that we don't modify argc and argv set_originalCommandLineArgumentList( local_commandLineArgumentList ); // printf ("DONE with copy of command line in SgProject constructor! \n"); #if 0 printf ("SgProject::processCommandLine(): local_commandLineArgumentList.size() = %" PRIuPTR " \n",local_commandLineArgumentList.size()); printf ("SgProject::processCommandLine(): local_commandLineArgumentList = %s \n",StringUtility::listToString(local_commandLineArgumentList).c_str()); #endif #if 0 // DQ (4/13/2015): The value of get_verbose() has not yet been set, so this is always the default value (zero). if (SgProject::get_verbose() > 1) { printf ("SgProject::processCommandLine(): local_commandLineArgumentList = %s \n",StringUtility::listToString(local_commandLineArgumentList).c_str()); printf ("Exiting as a test! \n"); ROSE_ASSERT(false); } #endif // Build the empty STL lists #if ROSE_USING_OLD_PROJECT_FILE_LIST_SUPPORT p_fileList.clear(); #else ROSE_ASSERT(p_fileList_ptr != NULL); p_fileList_ptr->get_listOfFiles().clear(); #endif // return value for calls to SLA int optionCount = 0; #if 0 // DQ (11/1/2009): To be consistant with other tools disable -h and -help options (use --h and --help instead). // This is a deprecated option // // help option (allows alternative -h or -help instead of just -rose:help) // // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of agrc // optionCount = sla(&argc, argv, "-", "($)", "(h|help)",1); optionCount = sla_none(local_commandLineArgumentList, "-", "($)", "(h|help)",1); if( optionCount > 0 ) { // printf ("option -help found \n"); printf ("This is a deprecated option in ROSE (use --h or --help instead).\n"); // Default cout << version_message() << endl; // Rose::usage(0); SgFile::usage(0); exit(0); } // printf ("After SgProject processing -help option argc = %d \n",argc); #endif // // help option (allows alternative --h or --help) // // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of agrc // optionCount = sla(&argc, argv, "--", "($)", "(h|help)",1); optionCount = sla_none(local_commandLineArgumentList, "--", "($)", "(h|help)",1); if( optionCount > 0 ) { // printf ("option --help found \n"); // printf ("\nROSE (pre-release alpha version: %s) \n",VERSION); // version(); // Rose::usage(0); cout << version_message() << endl; SgFile::usage(0); exit(0); } // // version option (allows alternative --version or --V) // // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of agrc // optionCount = sla(&argc, argv, "--", "($)", "(V|version)",1); optionCount = sla_none(local_commandLineArgumentList, "--", "($)", "(V|version)",1); if ( optionCount > 0 ) { // printf ("SgProject::processCommandLine(): option --version found \n"); // printf ("\nROSE (pre-release alpha version: %s) \n",VERSION); cout << version_message() << endl; exit(0); } #if 0 // DQ (11/1/2009): To be consistant with other tools disable -h and -help options (use --h and --help instead). // This is a deprecated option // // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of agrc // optionCount = sla(&argc, argv, "--", "($)", "(V|version)",1); optionCount = sla_none(local_commandLineArgumentList, "-rose:", "($)", "(V|version)",1); if ( optionCount > 0 ) { // printf ("SgProject::processCommandLine(): option --version found \n"); // printf ("\nROSE (pre-release alpha version: %s) \n",VERSION); printf ("This is a deprecated option in ROSE (use --V or --version instead).\n"); cout << version_message() << endl; exit(0); } #endif #if 0 // DQ (8/6/2006): Not sure that I want this here! // // version option (using -rose:version) // if ( CommandlineProcessing::isOption(argc,argv,"-rose:","(V|version)",true) == true ) { // function in SAGE III to access version number of EDG extern std::string edgVersionString(); // printf ("\nROSE (pre-release alpha version: %s) \n",VERSION); cout << version_message() << endl; printf (" Using C++ and C frontend from EDG (version %s) internally \n",edgVersionString().c_str()); } #endif // DQ (10/15/2005): Added because verbose was not set when the number of files (source files) was zero (case for linking only) // // specify verbose setting for projects (should be set even for linking where there are no source files // // DQ (3/9/2009): valid initial range is 0 ... 10. ROSE_ASSERT (get_verbose() >= 0); ROSE_ASSERT (get_verbose() <= 10); int integerOptionForVerbose = 0; // if ( CommandlineProcessing::isOptionWithParameter(argc,argv,"-rose:","(v|verbose)",integerOptionForVerbose,true) == true ) if ( CommandlineProcessing::isOptionWithParameter(local_commandLineArgumentList,"-rose:","(v|verbose)",integerOptionForVerbose,true) == true ) { // set_verbose(true); set_verbose(integerOptionForVerbose); Rose::Cmdline::verbose = integerOptionForVerbose; if ( SgProject::get_verbose() >= 1 ) printf ("verbose mode ON (for SgProject)\n"); } Rose::Cmdline::ProcessKeepGoing(this, local_commandLineArgumentList); // // Standard compiler options (allows specification of language -x option to just run compiler without /dev/null as input file) // // DQ (1/8/2014): This configuration is used by the git application to specify the C language with the input file is /dev/null. // This is a slightly bizare corner case of our command line processing. string tempLanguageSpecificationName; optionCount = sla(local_commandLineArgumentList, "-", "($)^", "x", &tempLanguageSpecificationName, 1); if (optionCount > 0) { // Make our own copy of the language specification name string // p_language_specification = tempLanguageSpecificationName; // printf ("option -x <option> found language_specification = %s \n",p_language_specification.c_str()); printf ("option -x <option> found language_specification = %s \n",tempLanguageSpecificationName.c_str()); // -x <language> Specify the language of the following input files // Permissible languages include: c c++ assembler none // 'none' means revert to the default behavior of // guessing the language based on the file's extension if (tempLanguageSpecificationName == "c") { set_C_only(true); } else { if (tempLanguageSpecificationName == "c++") { set_Cxx_only(true); } else { if (tempLanguageSpecificationName == "none") { // Language specification is set using filename specification (nothing to do here). } else { printf ("Error: -x <option> implementation in ROSE only permits specification of \"c\" or \"c++\" or \"none\" as supported languages \n"); ROSE_ASSERT(false); } } } #if 0 printf ("Exiting as a test in SgProject::processCommandLine() \n"); ROSE_ASSERT(false); #endif } // // Standard compiler options (allows alternative -E option to just run CPP) // // if ( CommandlineProcessing::isOption(argc,argv,"-","(E)",false) == true ) if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-","(E)",false) == true ) { #if 0 printf ("/* In SgProject::processCommandLine(): option -E found (just run backend compiler with -E to call CPP) */ \n"); #endif p_C_PreprocessorOnly = true; } // DQ (1/19/2014): Adding support for gnu "-S" option, which means: // Stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler input file specified. // By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s. // Input files that don't require compilation are ignored. // // Standard compiler options (allows alternative -S option to just run gcc directly) // if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-","(S)",false) == true ) { // printf ("/* option -S found (just run backend compiler with -S to gcc) */ \n"); p_stop_after_compilation_do_not_assemble_file = true; } // DQ (1/20/2014): Adding support for gnu -undefined option to ROSE command line. // -u SYMBOL, --undefined SYMBOL Start with undefined reference to SYMBOL string stringOptionForUndefinedSymbol; if ( CommandlineProcessing::isOptionWithParameter(local_commandLineArgumentList,"-","(u|undefined)",stringOptionForUndefinedSymbol,true) == true ) { printf ("Found -u -undefined option specified on command line: stringOptionForUndefinedSymbol = %s \n",stringOptionForUndefinedSymbol.c_str()); p_gnuOptionForUndefinedSymbol = stringOptionForUndefinedSymbol; if ( SgProject::get_verbose() >= 1 ) printf ("-undefined option specified on command line (for SgFile)\n"); #if 0 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif } #if 0 // DQ (12/10/2016): This does not take a parameter on any later version compiler that I know of. // DQ (1/26/2014): Adding support for gnu -MM option to ROSE command line. string stringOptionForMakeDepenenceFile; if ( CommandlineProcessing::isOptionWithParameter(local_commandLineArgumentList,"-","(MM)",stringOptionForMakeDepenenceFile,true) == true ) { printf ("Found -MM dependence information option specified on command line: stringOptionForMakeDepenenceFile = %s \n",stringOptionForMakeDepenenceFile.c_str()); // p_dependenceFilename = stringOptionForMakeDepenenceFile; if ( SgProject::get_verbose() >= 1 ) printf ("-MM dependence file specification specified on command line (for SgFile)\n"); #if 0 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif } #else // DQ (12/10/2016): Areas build system appears to use the "-MM" option on the command line and this is a problem for ROSE when not specified using a parameter. if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-","(MM)",false) == true ) { // The support for this should just be to call the backend compiler with the "-MM" option. printf ("NOTE: The use of the -MM option to ROSE is not recoreded internally (simple call to backend compiler using -MM option not implemented). \n"); if ( SgProject::get_verbose() >= 0 ) printf ("-MM dependence file specification specified on command line (for SgFile)\n"); } #endif // DQ (1/26/2014): Adding support for gnu -version-info option to ROSE command line. string stringOptionForVersionSpecification; if ( CommandlineProcessing::isOptionWithParameter(local_commandLineArgumentList,"-","(version-info)",stringOptionForVersionSpecification,true) == true ) { printf ("Found -version-info option specified on command line: stringOptionForVersionSpecification = %s \n",stringOptionForVersionSpecification.c_str()); // p_gnuOptionForVersionSpecification = stringOptionForVersionSpecification; if ( SgProject::get_verbose() >= 1 ) printf ("-version-info option specified on command line (for SgFile)\n"); #if 0 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif } // DQ (1/20/2014): Adding support for "-m32" option for 32-bit mode on 64-bit systems. // The 32-bit environment sets int, long and pointer to 32 bits. // The 64-bit environment sets int to 32 bits and long and pointer to 64 bits (ROSE does not support the -m64 command line option). // // Standard compiler options (allows alternative -m32 option) // if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-","(m32)",false) == true ) { #if 0 printf ("detected use of -m32 mode (will be passed to backend compiler) \n"); #endif p_mode_32_bit = true; } // DQ (3/19/2014): This option causes the output of source code to an existing file to be an error. // // noclobber_output_file // if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","noclobber_output_file",false) == true ) { #if 0 printf ("detected use of noclobber_output_file mode \n"); #endif p_noclobber_output_file = true; } // DQ (3/19/2014): This option causes the output of source code to an existing file to be an error if it results in a different file. // // noclobber_if_different_output_file // if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","noclobber_if_different_output_file",false) == true ) { #if 0 printf ("detected use of noclobber_if_different_output_file mode \n"); #endif p_noclobber_if_different_output_file = true; // Make it an error to specify both of these noclobber options. if (p_noclobber_output_file == true) { printf ("Error: options -rose:noclobber_output_file and -rose:noclobber_if_different_output_file are mutually exclusive \n"); ROSE_ASSERT(false); } } // Pei-Hung (8/6/2014): This option appends PID into the output name to avoid file collision in parallel compilation. // // appendPID // if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","appendPID",false) == true ) { #if 0 printf ("detected use of appendPID mode \n"); #endif set_appendPID(true); } // DQ (9/8/2016): Adding support to optionally unparse template declarations from the AST // // unparseTemplateDeclarationsFromAST // if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","unparseTemplateDeclarationsFromAST",false) == true ) { #if 1 printf ("detected use of unparseTemplateDeclarationsFromAST mode \n"); #endif p_unparseTemplateDeclarationsFromAST = true; } // // specify compilation only option (new style command line processing) // // if ( CommandlineProcessing::isOption(argc,argv,"-","c",false) == true ) if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-","c",false) == true ) { #if 0 printf ("Option -c found (compile only)! \n"); #endif set_compileOnly(true); } // DQ (4/7/2010): This is useful when using ROSE translators as a linker, this permits the SgProject // to know what backend compiler to call to do the linking. This is required when there are no SgFile // objects to get this information from. set_C_only(false); ROSE_ASSERT (get_C_only() == false); if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","(c|C)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("In SgProject: C mode ON \n"); set_C_only(true); } // DQ (4/7/2010): This is useful when using ROSE translators as a linker, this permits the SgProject // to know what backend compiler to call to do the linking. This is required when there are no SgFile // objects to get this information from. set_Cxx_only(false); ROSE_ASSERT (get_Cxx_only() == false); if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","(cxx|Cxx)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("In SgProject: C++ mode ON \n"); set_Cxx_only(true); } #if 0 printf ("In SgProject: before processing option: (get_wave() == %s) \n",get_wave() ? "true" : "false"); #endif if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","wave",false) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Option -rose:wave found! (get_wave() == %s) \n",get_wave() ? "true" : "false"); set_wave(true); if ( SgProject::get_verbose() >= 1 ) printf (" --- after calling set_wave(true) (get_wave() == %s) \n",get_wave() ? "true" : "false"); } // Liao 6/29/2012: support linking flags for OpenMP lowering when no SgFile is available set_openmp_linking(false); if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:OpenMP:","lowering",true) == true || CommandlineProcessing::isOption(local_commandLineArgumentList,"--rose:OpenMP:","lowering",true) == true || CommandlineProcessing::isOption(local_commandLineArgumentList,"--rose:openmp:","lowering",true) == true ||CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:openmp:","lowering",true) == true) { if ( SgProject::get_verbose() >= 1 ) printf ("In SgProject: openmp_linking mode ON \n"); set_openmp_linking(true); } Rose::Cmdline::Unparser::Process(this, local_commandLineArgumentList); Rose::Cmdline::Fortran::Process(this, local_commandLineArgumentList); Rose::Cmdline::Java::Process(this, local_commandLineArgumentList); Rose::Cmdline::Gnu::Process(this, local_commandLineArgumentList); Rose::Cmdline::X10::Process(this, local_commandLineArgumentList); // DQ (9/14/2013): Adding option to copy the location of the input file as the position for the generated output file. // This is now demonstrated to be important in the case of ffmpeg-1.2 for the file "file.c" where it is specified as // "libavutil/file.c" on the command line and we by default put it into the current directory (top level directory // in the directory structure). But it is a subtle and difficult to reproduce error that the generated file will // not compile properly from the top level directory (even when the "-I<absolute path>/libavutil" is specified). // We need an option to put the generated file back into the original directory where the input source files is // located, so that when the generated rose_*.c file is compiled (with the backend compiler, e.g. gcc) it can use // the identical rules for resolving head files as it would have for the original input file (had it been compiled // using the backend compiler instead). set_unparse_in_same_directory_as_input_file(false); if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","unparse_in_same_directory_as_input_file",false) == true ) { // printf ("Option -c found (compile only)! \n"); // set_copy_generated_source_to_same_location_as_input_file(true); // set_build_generated_file_in_same_directory_as_input_file(true); set_unparse_in_same_directory_as_input_file(true); } #if 1 // DQ (10/3/2010): Adding support for CPP directives to be optionally a part of the AST as declarations // in global scope instead of handled similar to comments. set_addCppDirectivesToAST(false); ROSE_ASSERT (get_addCppDirectivesToAST() == false); if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","addCppDirectivesToAST",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("In SgProject: addCppDirectivesToAST mode ON \n"); set_addCppDirectivesToAST(true); } #else printf ("Warning: command line CPP directives not processed \n"); #endif // // prelink option // // if ( CommandlineProcessing::isOption(argc,argv,"-rose:","(prelink)",true) == true ) if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","(prelink)",true) == true ) { // printf ("prelink mode ON \n"); set_prelink(true); } else { // printf ("-rose:prelink not found: prelink mode OFF \n"); set_prelink(false); } // // specify output file option // // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of argc string tempOutputFilename; // optionCount = sla(&argc, argv, "-", "($)^", "(o|output)", &tempOutputFilename ,1); optionCount = sla(local_commandLineArgumentList, "-", "($)^", "(o|output)", &tempOutputFilename ,1); if( optionCount > 0 ) { // Make our own copy of the filename string p_outputFileName = tempOutputFilename; #if 0 printf ("option -o|output found outputFileName = %s \n",p_outputFileName.c_str()); #endif } else { // Usual default for output executables (comes from the default name for // assembler output a long long time ago, way way back in the 1970's). // For history of why "a.out" is the default see: // http://cm.bell-labs.com/cm/cs/who/dmr/chist.html p_outputFileName = "a.out"; } // DQ (1/16/2008): Added include/exclude path lists for use internally by translators. // For example in Compass this is the basis of a mechanism to exclude processing of // header files from specific directorys (where messages about the properties of the // code there are not meaningful since they cannot be changed by the user). These // are ment to be used by ROSE translators and as a result have unspecificed semantics // in ROSE, it is just a common requirement of many uses of ROSE. // // DQ (1/16/2008): Added include/exclude path lists for use internally by translators. // specify exclude path option string tempIncludePath; vector<string>::iterator iter = local_commandLineArgumentList.begin(); while ( iter != local_commandLineArgumentList.end() ) { if ( *iter == "-rose:includePath") { iter++; tempIncludePath = *iter; // printf ("Adding tempIncludePath = %s to p_includePathList \n",tempIncludePath.c_str()); p_includePathList.push_back(tempIncludePath); } iter++; } // DQ (1/16/2008): Added include/exclude path lists for use internally by translators. // specify exclude path option string tempExcludePath; iter = local_commandLineArgumentList.begin(); while ( iter != local_commandLineArgumentList.end() ) { if ( *iter == "-rose:excludePath") { iter++; tempExcludePath = *iter; // printf ("Adding tempExcludePath = %s to p_excludePathList \n",tempExcludePath.c_str()); p_excludePathList.push_back(tempExcludePath); } iter++; } // DQ (1/16/2008): Added include/exclude file lists for use internally by translators. // specify exclude path option string tempIncludeFile; iter = local_commandLineArgumentList.begin(); while ( iter != local_commandLineArgumentList.end() ) { if ( *iter == "-rose:includeFile") { iter++; tempIncludeFile = *iter; // DQ (1/17/2008): filename matching should be only done on the filename and not the path string filenameWithoutPath = StringUtility::stripPathFromFileName(tempIncludeFile); // printf ("Adding tempIncludeFile = %s filenameWithoutPath = %s to p_includeFileList \n",tempIncludeFile.c_str(),filenameWithoutPath.c_str()); p_includeFileList.push_back(filenameWithoutPath); } iter++; } // DQ (1/16/2008): Added include/exclude file lists for use internally by translators. // specify exclude path option string tempExcludeFile; iter = local_commandLineArgumentList.begin(); while ( iter != local_commandLineArgumentList.end() ) { if ( *iter == "-rose:excludeFile") { iter++; tempExcludeFile = *iter; // DQ (1/17/2008): filename matching should be only done on the filename and not the path string filenameWithoutPath = StringUtility::stripPathFromFileName(tempExcludeFile); // printf ("Adding tempExcludeFile = %s filenameWithoutPath = %s to p_excludeFileList \n",tempExcludeFile.c_str(),filenameWithoutPath.c_str()); p_excludeFileList.push_back(filenameWithoutPath); } iter++; } // // DQ (5/20/2005): specify template handling options (e.g. -rose:instantiation none) // // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of argc string tempTemplateHandling; // optionCount = sla(&argc, argv, "-rose:", "($)^", "(instantiation)", &tempTemplateHandling ,1); optionCount = sla(local_commandLineArgumentList, "-rose:", "($)^", "(instantiation)", &tempTemplateHandling ,1); if ( optionCount > 0 ) { std::string templateHandlingString = tempTemplateHandling; if (templateHandlingString == "none") p_template_instantiation_mode = e_none; if (templateHandlingString == "used") p_template_instantiation_mode = e_used; if (templateHandlingString == "all") p_template_instantiation_mode = e_all; if (templateHandlingString == "local") p_template_instantiation_mode = e_local; // printf ("option -rose:instantiation found tempTemplateHandling = %s \n",tempTemplateHandling); } else { // usual default for template handling // printf ("option -rose:instantiation NOT found setting p_template_instantiation_mode = e_default \n"); p_template_instantiation_mode = e_default; } // DQ (1/13/2009): Added support for GNU -include <header_file> option (include this file before all others). string tempHeaderFile; iter = local_commandLineArgumentList.begin(); while ( iter != local_commandLineArgumentList.end() ) { if ( *iter == "-include") { iter++; tempHeaderFile = *iter; #if 0 printf ("In processCommandLine(): Adding tempHeaderFile = %s to p_preincludeFileList \n",tempHeaderFile.c_str()); #endif p_preincludeFileList.push_back(tempHeaderFile); } iter++; } // DQ (1/13/2009): Added support for GNU -isystem <directory> option (include this directory before all others). string tempDirectory; iter = local_commandLineArgumentList.begin(); while ( iter != local_commandLineArgumentList.end() ) { if ( SgProject::get_verbose() > 1 ) printf ("Searching for -isystem options iter = %s \n",(*iter).c_str()); if ( *iter == "-isystem") { iter++; tempDirectory = *iter; if ( SgProject::get_verbose() > 1 ) printf ("Adding tempHeaderFile = %s to p_preincludeDirectoryList \n",tempDirectory.c_str()); p_preincludeDirectoryList.push_back(tempDirectory); } iter++; } // DQ (10/16/2005): // Build versions of argc and argv that are separate from the input_argc and input_argv // (so that we can be clear that there are no side-effects to the original argc and argv // that come from the user's ROSE translator. Mostly we want to use the short names // (e.g. "argc" and "argv"). vector<string> argv = get_originalCommandLineArgumentList(); ROSE_ASSERT(argv.size() > 0); // DQ (12/22/2008): This should only be called once (outside of the loop over all command line arguments! // DQ (12/8/2007): This leverages existing support in commandline processing // printf ("In SgProject::processCommandLine(): Calling CommandlineProcessing::generateSourceFilenames(argv) \n"); // Note that we need to process this option before the interpretation of the filenames (below). // DQ (2/4/2009): Data member was moved to SgProject from SgFile. // DQ (12/27/2007): Allow defaults to be set based on filename extension. if ( CommandlineProcessing::isOption(argv,"-rose:","(binary|binary_only)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Binary mode ON \n"); set_binary_only(true); } // DQ (2/4/2009): The specification of "-rose:binary" causes filenames to be interpreted // differently if they are object files or libary archive files. // p_sourceFileNameList = CommandlineProcessing::generateSourceFilenames(argv); p_sourceFileNameList = CommandlineProcessing::generateSourceFilenames(argv,get_binary_only()); // Build a list of source, object, and library files on the command line // int sourceFileNameCounter = 0; for (unsigned int i = 1; i < argv.size(); i++) { // find the source code filenames and modify them to be the output filenames unsigned int length = argv[i].size(); // printf ("assemble compiler command line option: argv[%d] = %s length = %d \n",i,argv[i],length); // printf ("Rose::sourceFileNamesWithoutPath[%d] = \n",sourceFileNameCounter, // Rose::sourceFileNamesWithoutPath[sourceFileNameCounter]); // ROSE_ASSERT (Rose::sourceFileNamesWithoutPath[sourceFileNameCounter] != NULL); // DQ (12/8/2007): This leverages existing support in commandline processing // p_sourceFileNameList = CommandlineProcessing::generateSourceFilenames(argv); // printf ("In SgProject::processCommandLine(): p_sourceFileNameList.size() = %" PRIuPTR " \n",p_sourceFileNameList.size()); // DQ (2/4/2009): Only put *.o files into the objectFileNameList is they are not being // processed as binary source files (targets for analysis, as opposed to linking). // DQ (1/16/2008): This is a better (simpler) implementation // if (CommandlineProcessing::isObjectFilename(argv[i]) == true) // printf ("get_binary_only() = %s \n",get_binary_only() ? "true" : "false"); if ( (get_binary_only() == false) && (CommandlineProcessing::isObjectFilename(argv[i]) == true) ) { // printf ("Adding argv[%u] = %s to p_objectFileNameList \n",i,argv[i].c_str()); p_objectFileNameList.push_back(argv[i]); } // look only for .a files (library files) if ( (length > 2) && ( (argv[i][0] != '-') && (argv[i][0] != '+') ) && ( (argv[i][length-2] == '.') && (argv[i][length-1] == 'a') ) ) { std::string libraryFile = argv[i]; p_libraryFileList.push_back(libraryFile); // DQ (2/4/2009): Make sure that this is not handled incorrectly is we wanted it to be a target for binary analysis. // If so, then is should end up on the source code list (target list for analysis). if (get_binary_only() == true) { printf ("This may be an error, since the library archive should be treated as a source file for binary analysis. \n"); //ROSE_ASSERT(false); } } // TOO1 (11/23/2013): // (Darwin linker) -dylib_file <library_name.dylib>:<library_name.dylib> if (argv[i].compare("-dylib_file") == 0) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] [Cmdline] " << "Processing -dylib_file" << std::endl; } if (argv.size() == (i+1)) { throw std::runtime_error("Missing required argument to -dylib_file"); } else { // TODO: Save library argument; for now just skip over the argument ++i; if (SgProject::get_verbose() > 1) { std::cout << "[INFO] [Cmdline] " << "Processing -dylib_file: argument=" << "'" << argv[i] << "'" << std::endl; } ROSE_ASSERT(! "Not implemented yet"); } } // TOO1 (01/22/2014): // (Darwin linker) -framework dir if (argv[i].compare("-framework") == 0) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] [Cmdline] " << "Processing -framework" << std::endl; } if (argv.size() == (i+1)) { throw std::runtime_error("Missing required argument to -framework"); } else { // TODO: Save framework argument; for now just skip over the argument ++i; if (SgProject::get_verbose() > 1) { std::cout << "[INFO] [Cmdline] " << "Processing -framework argument=" << "'" << argv[i] << "'" << std::endl; } ROSE_ASSERT(! "Not implemented yet"); } } // look only for -l library files (library files) if ( (length > 2) && (argv[i][0] == '-') && (argv[i][1] == 'l') ) { std::string librarySpecifier = argv[i].substr(2); // librarySpecifier = std::string("lib") + librarySpecifier; p_librarySpecifierList.push_back(librarySpecifier); } // look only for -L directories (directories where -lxxx libraries will be found) if ( (length > 2) && (argv[i][0] == '-') && (argv[i][1] == 'L') ) { // AS Changed source code to support absolute paths std::string libraryDirectorySpecifier = argv[i].substr(2); libraryDirectorySpecifier = StringUtility::getAbsolutePathFromRelativePath(libraryDirectorySpecifier); p_libraryDirectorySpecifierList.push_back(libraryDirectorySpecifier); } // look only for -I include directories (directories where #include<filename> will be found) if ((length > 2) && (argv[i][0] == '-') && (argv[i][1] == 'I')) { std::string include_path = argv[i].substr(2); { include_path = StringUtility::getAbsolutePathFromRelativePath(include_path); } p_includeDirectorySpecifierList.push_back("-I" + include_path); std::string include_path_no_quotes = boost::replace_all_copy(include_path, "\"", ""); try { bool is_directory = boost::filesystem::is_directory(include_path_no_quotes); if (false == is_directory) { // DQ (3/15/2017): Fixed to use mlog message logging. if (Rose::ir_node_mlog[Rose::Diagnostics::DEBUG]) { std::cout << "[WARN] " << "Invalid argument to -I; path does not exist: " << "'" << include_path_no_quotes << "'" << std::endl; } } } catch (const boost::filesystem::filesystem_error& ex) { std::cout << "[ERROR] " << "Exception processing argument to -I: " << "'" << include_path_no_quotes << "'" << std::endl; std::cout << ex.what() << std::endl; } } // DQ (10/18/2010): Added support to collect "-D" options (assume no space between the "-D" and the option (e.g. "-DmyMacro=8"). // Note that we want to collect these because we have to process "-D" options more explicitly for Fortran (they are not required // for C/C++ because they are processed by the forontend directly. if ( (length > 2) && (argv[i][0] == '-') && (argv[i][1] == 'D') ) { std::string macroSpecifier = argv[i].substr(2); // librarySpecifier = std::string("lib") + librarySpecifier; p_macroSpecifierList.push_back(macroSpecifier); } } // DQ (6/17/2005): Added support for AST merging (sharing common parts of the AST most often represented in common header files of a project) // // specify AST merge option // // if ( CommandlineProcessing::isOption(argc,argv,"-rose:","(astMerge)",true) == true ) if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","(astMerge)",true) == true ) { // printf ("-rose:astMerge option found \n"); // set something not yet defined! p_astMerge = true; } // DQ (9/15/2018): Adding support for output of report on the header file unparsing (for debugging). if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","(headerFileUnparsingReport)",true) == true ) { #if 0 printf ("-rose:headerFileUnparsingReport option found \n"); #endif set_reportOnHeaderFileUnparsing(true); } // DQ (6/17/2005): Added support for AST merging (sharing common parts of the AST most often represented in common header files of a project) // // specify AST merge command file option // std::string astMergeFilenameParameter; if ( CommandlineProcessing::isOptionWithParameter(local_commandLineArgumentList, "-rose:","(astMergeCommandFile)",astMergeFilenameParameter,true) == true ) { printf ("-rose:astMergeCommandFile %s \n",astMergeFilenameParameter.c_str()); // Make our own copy of the filename string // set_astMergeCommandLineFilename(xxx); p_astMergeCommandFile = astMergeFilenameParameter; } // Milind Chabbi (9/9/2013): Added an option to store all files compiled by a project. // When we need to have a unique id for the same file used acroos different compilation units, this file provides such capability. std::string projectSpecificDatabaseFileParamater; if ( CommandlineProcessing::isOptionWithParameter(local_commandLineArgumentList, "-rose:","(projectSpecificDatabaseFile)",projectSpecificDatabaseFileParamater,true) == true ) { printf ("-rose:projectSpecificDatabaseFile %s \n",projectSpecificDatabaseFileParamater.c_str()); // Make our own copy of the filename string // set_astMergeCommandLineFilename(xxx); p_projectSpecificDatabaseFile = projectSpecificDatabaseFileParamater; } // DQ (8/29/2006): Added support for accumulation of performance data into CSV data file (for later processing to build performance graphs) std::string compilationPerformanceFilenameParameter; if ( CommandlineProcessing::isOptionWithParameter(local_commandLineArgumentList, "-rose:","(compilationPerformanceFile)",compilationPerformanceFilenameParameter,true) == true ) { // printf ("-rose:compilationPerformanceFile = %s \n",compilationPerformanceFilenameParameter.c_str()); p_compilationPerformanceFile = compilationPerformanceFilenameParameter; } // DQ (1/30/2014): Added support to supress constant folding post-processing step (a performance problem on specific file of large applications). set_suppressConstantFoldingPostProcessing(false); ROSE_ASSERT (get_suppressConstantFoldingPostProcessing() == false); if ( CommandlineProcessing::isOption(local_commandLineArgumentList,"-rose:","(suppressConstantFoldingPostProcessing)",true) == true ) { printf ("Using -rose:suppressConstantFoldingPostProcessing \n"); p_suppressConstantFoldingPostProcessing = true; ROSE_ASSERT (get_suppressConstantFoldingPostProcessing() == true); } #if 1 if ( get_verbose() > 1 ) { // Find out what file we are doing transformations upon printf ("In SgProject::processCommandLine() (verbose mode ON): \n"); display ("In SgProject::processCommandLine()"); } #endif #if 0 printf ("Leaving SgProject::processCommandLine() \n"); display("At base of SgProject::processCommandLine()"); #endif #if 0 printf ("Exiting as a test at base of SgProject::processCommandLine() \n"); ROSE_ASSERT(false); #endif } //------------------------------------------------------------------------------ // Cmdline //------------------------------------------------------------------------------ std::vector<std::string> Rose::Cmdline:: NormalizeIncludePathOptions (std::vector<std::string>& argv) { std::vector<std::string> r_argv; bool looking_for_include_path_arg = false; BOOST_FOREACH(std::string arg, argv) { // Must be first since there could be, for example, "-I -I", // in which case, the else if branch checking for -I would // be entered. if (looking_for_include_path_arg) { looking_for_include_path_arg = false; // reset for next iteration // Sanity check bool is_directory = boost::filesystem::is_directory(arg); if (false == is_directory) { // DQ (3/15/2017): Fixed to use mlog message logging. if (Rose::ir_node_mlog[Rose::Diagnostics::DEBUG]) { std::cout << "[WARN] " << "Invalid argument to -I; path does not exist: " << "'" << arg << "'" << std::endl; } } #ifdef _MSC_VER // ensure that the path is quoted on Windows. r_argv.push_back("-I\"" + arg + "\""); #else r_argv.push_back("-I" + arg + ""); #endif } else if ((arg.size() >= 2) && (arg[0] == '-') && (arg[1] == 'I')) { // -I <path>: There is a space between the option and the argument... // ^ // // ...meaning this current argument is exactly "-I". // if (arg.size() == 2) { looking_for_include_path_arg = true; continue; // next iteration should be the path argument } else { // no normalization required for -I<path>, but ensure // that the path is quoted on Windows. #ifdef _MSC_VER if (arg[2] != '"') { arg.insert(2, "\""); arg.append("\""); } #endif r_argv.push_back(arg); } } else // not an include path option { r_argv.push_back(arg); } }//argv.each // Found -I option but no accompanying <path> argument if (looking_for_include_path_arg == true) { std::cout << "[FATAL] " << "Missing required argument to -I; expecting '-I<path>'" << std::endl; exit(1); } else { return r_argv; } }//NormalizeIncludePathOptions (std::vector<std::string>& argv) void Rose::Cmdline:: StripRoseOptions (std::vector<std::string>& argv) { Cmdline::Unparser::StripRoseOptions(argv); Cmdline::Fortran::StripRoseOptions(argv); Cmdline::Java::StripRoseOptions(argv); }// Cmdline::StripRoseOptions void Rose::Cmdline:: ProcessKeepGoing (SgProject* project, std::vector<std::string>& argv) { bool keep_going = CommandlineProcessing::isOption( argv, "-rose:keep_going", "", true); if (keep_going) { if (SgProject::get_verbose() >= 1) std::cout << "[INFO] [Cmdline] [-rose:keep_going]" << std::endl; #if 0 printf ("detected -rose:keep_going option \n"); #endif project->set_keep_going(true); Rose::KeepGoing::g_keep_going = true; } #if 0 printf ("In ProcessKeepGoing(): project->get_keep_going() = %s \n",project->get_keep_going() ? "true" : "false"); #endif #if 0 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif } //------------------------------------------------------------------------------ // Unparser //------------------------------------------------------------------------------ bool Rose::Cmdline::Unparser:: OptionRequiresArgument (const std::string& option) { return // ROSE Options option == "-rose:unparser:some_option_taking_argument"; }// ::Rose::Cmdline:Unparser:::OptionRequiresArgument void Rose::Cmdline::Unparser:: StripRoseOptions (std::vector<std::string>& argv) { std::string argument; // TOO1 (3/20/2014): TODO: Refactor Unparser specific CLI handling here // (1) Options WITHOUT an argument // Example: sla(argv, "-rose:", "($)", "(unparser)",1); sla(argv, "-rose:unparser:", "($)", "(clobber_input_file)",1); // // (2) Options WITH an argument // // Remove Unparser options with ROSE-unparser prefix; option arguments removed // by generateOptionWithNameParameterList. // // For example, // // BEFORE: argv = [-rose:unparser:clobber_input_file, -rose:verbose, "3"] // AFTER: argv = [-rose:verbose, "3"] // unparser_options = [-clobber_input_file] // std::vector<std::string> unparser_options = // CommandlineProcessing::generateOptionWithNameParameterList( // argv, // Remove ROSE-Unparser options from here // Cmdline::Unparser::option_prefix, // Current prefix, e.g. "-rose:unparser:" // "-"); // New prefix, e.g. "-" }// ::Rose::Cmdline::Unparser::StripRoseOptions void Rose::Cmdline::Unparser:: Process (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Unparser commandline options" << std::endl; ProcessClobberInputFile(project, argv); }// ::Rose::Cmdline::Unparser::Process void Rose::Cmdline::Unparser:: ProcessClobberInputFile (SgProject* project, std::vector<std::string>& argv) { bool has_clobber_input_file = CommandlineProcessing::isOption( argv, Cmdline::Unparser::option_prefix, "clobber_input_file", Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_clobber_input_file) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] **CAUTION** Turning on the Unparser's destructive clobber mode =O" << std::endl; project->set_unparser__clobber_input_file(true); } else { project->set_unparser__clobber_input_file(false); } }// ::Rose::Cmdline::Unparser::ProcessClobberInputFile //------------------------------------------------------------------------------ // Fortran //------------------------------------------------------------------------------ bool Rose::Cmdline::Fortran:: OptionRequiresArgument (const std::string& option) { return // ROSE Options option == "-rose:fortran:ofp:jvm_options"; }// Cmdline:Fortran:::OptionRequiresArgument void Rose::Cmdline::Fortran:: StripRoseOptions (std::vector<std::string>& argv) { std::string argument; // TOO1 (2/13/2014): TODO: Refactor Fortran specific CLI handling here // (1) Options WITHOUT an argument // Example: sla(argv, "-rose:", "($)", "(f|F|fortran|Fortran)",1); // // (2) Options WITH an argument // // Remove Fortran options with ROSE-Fortran prefix; option arguments removed // by generateOptionWithNameParameterList. // // For example, // // BEFORE: argv = [-rose:fortran:ofp:jvm_options, "-Xss3m", -rose:verbose, "3"] // AFTER: argv = [-rose:verbose, "3"] // fortran_options = [-ofp:jvm_options, "-Xss3m"] std::vector<std::string> fortran_options = CommandlineProcessing::generateOptionWithNameParameterList( argv, // Remove ROSE-Fortran options from here Cmdline::Fortran::option_prefix, // Current prefix, e.g. "-rose:fortran:" "-"); // New prefix, e.g. "-" BOOST_FOREACH(std::string fortran_option, fortran_options) { // TOO1 (2/13/2014): There are no ROSE-specific Fortran options yet. // Skip ROSE-specific Fortran options // // "-ds": source destination directory for unparsed code is specific to ROSE. //if (fortran_option == "-ds") // continue; //else argv.push_back(fortran_option); } Cmdline::Fortran::Ofp::StripRoseOptions(argv); }// Cmdline::Fortran::StripRoseOptions std::string Rose::Cmdline::Fortran::Ofp:: GetRoseClasspath () { string classpath = "-Djava.class.path="; // CER (6/6/2011): Added support for OFP version 0.8.3 which requires antlr-3.3-complete.jar. // CER (2/12/2019): Added support for OFP version 0.8.5 requiring antlr-3.5.2-complete.jar. ROSE_ASSERT(ROSE_OFP_MAJOR_VERSION_NUMBER >= 0); ROSE_ASSERT(ROSE_OFP_MINOR_VERSION_NUMBER >= 8); if (ROSE_OFP_PATCH_VERSION_NUMBER >= 5) { classpath += findRoseSupportPathFromSource( "src/3rdPartyLibraries/antlr-jars/antlr-3.5.2-complete.jar", "lib/antlr-3.5.2-complete.jar"); classpath += ":"; } else { classpath += findRoseSupportPathFromSource( "src/3rdPartyLibraries/antlr-jars/antlr-3.2.jar", "lib/antlr-3.2.jar" ); classpath += ":"; } // Open Fortran Parser (OFP) support (this is the jar file) // CER (10/4/2011): Switched to using date-based version for OFP jar file. // string ofp_jar_file_name = string("OpenFortranParser-") + ROSE_OFP_VERSION_STRING + string(".jar"); string ofp_class_path = "src/3rdPartyLibraries/fortran-parser/" + ofp_jar_file_name; classpath += findRoseSupportPathFromBuild(ofp_class_path, string("lib/") + ofp_jar_file_name) + ":"; // Everything else? classpath += "."; return classpath; } // -rose:fortran:ofp options have already been transformed by Cmdline::Fortran::StripRoseOptions. // Therefore, for example, // // -rose:fortran:ofp:jvm_options // // is now actually: // // -ofp:jvm_options // void Rose::Cmdline::Fortran::Ofp:: StripRoseOptions (std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] " << "Stripping ROSE Fortran OFP commandline options" << std::endl; } // Remove OFP options with ROSE-OFP prefix; option arguments removed // by generateOptionWithNameParameterList. std::vector<std::string> ofp_options = CommandlineProcessing::generateOptionWithNameParameterList( argv, // Remove ROSE-Fortran options from here "-ofp:", // Current prefix "-"); // New prefix // TOO1 (2/13/2014): Skip ALL ROSE-specific OFP options; // at this stage, we only have "-rose:fortran:ofp:jvm_options", // and this is only inteded for the OFP frontend's JVM. BOOST_FOREACH(std::string ofp_option, ofp_options) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] " << "Stripping OFP JVM commandline argument '" << ofp_option << "'" << std::endl; } } }// Cmdline::Fortran::StripRoseOptions void Rose::Cmdline::Fortran:: Process (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Fortran commandline options" << std::endl; ProcessFortranOnly(project, argv); Cmdline::Fortran::Ofp::Process(project, argv); } void Rose::Cmdline::Fortran:: ProcessFortranOnly (SgProject* project, std::vector<std::string>& argv) { bool is_fortran_only = CommandlineProcessing::isOption( argv, "-rose:fortran", "", true); if (is_fortran_only) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Turning on Fortran only mode" << std::endl; project->set_Fortran_only(true); } } void Rose::Cmdline::Fortran::Ofp:: Process (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Fortran's OFP frontend commandline options" << std::endl; ProcessJvmOptions(project, argv); ProcessEnableRemoteDebugging(project, argv); } void Rose::Cmdline::Fortran::Ofp:: ProcessJvmOptions (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Fortran's ofp frontend JVM commandline options" << std::endl; std::string ofp_jvm_options = ""; bool has_ofp_jvm_options = // -rose:fortran:ofp:jvm_options CommandlineProcessing::isOptionWithParameter( argv, Fortran::option_prefix, "ofp:jvm_options", ofp_jvm_options, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_ofp_jvm_options) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] Processing ofp JVM options: " << "'" << ofp_jvm_options << "'" << std::endl; } std::list<std::string> ofp_jvm_options_list = StringUtility::tokenize(ofp_jvm_options, ' '); project->set_Fortran_ofp_jvm_options(ofp_jvm_options_list); Cmdline::Fortran::Ofp::jvm_options.insert( Cmdline::Fortran::Ofp::jvm_options.begin(), ofp_jvm_options_list.begin(), ofp_jvm_options_list.end()); }// has_ofp_jvm_options }// Cmdline::Fortran::ProcessJvmOptions void Rose::Cmdline::Fortran::Ofp:: ProcessEnableRemoteDebugging (SgProject* project, std::vector<std::string>& argv) { bool has_fortran_remote_debug = // -rose:fortran:remoteDebug CommandlineProcessing::isOption( argv, Fortran::option_prefix, "ofp:enable_remote_debugging", Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_fortran_remote_debug) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Fortran remote debugging option" << std::endl; #ifdef ROSE_BUILD_FORTRAN_LANGUAGE_SUPPORT Cmdline::Fortran::Ofp::jvm_options.push_back( "-agentlib:jdwp=transport=dt_socket,server=y,address=8000"); #else std::cout << "[FATAL] " << "JVM remote debugging cannot be enabled since ROSE-Fortran " << "support is turned off" << std::endl; ROSE_ASSERT(false); #endif }// has_fortran_remote_debug }// Cmdline::Fortran::Ofp::ProcessEnableRemoteDebugging //------------------------------------------------------------------------------ // Gnu //------------------------------------------------------------------------------ // bool Rose::Cmdline::Gnu:: OptionRequiresArgument (const std::string& option) { return option == "--param" || // --param variable=value false; }// Cmdline:Java:::OptionRequiresArgument void Rose::Cmdline::Gnu:: Process (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing GNU commandline options" << std::endl; ProcessParam(project, argv); } void Rose::Cmdline::Gnu:: ProcessParam (SgProject* project, std::vector<std::string>& argv) { std::string param; bool has_param = CommandlineProcessing::isOptionWithParameter( argv, "--", "(param)", param, true); if (has_param) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Detected GNU --param " << param << std::endl; } } //------------------------------------------------------------------------------ // Java //------------------------------------------------------------------------------ bool Rose::Cmdline::Java:: OptionRequiresArgument (const std::string& option) { return // Javac Options option == "-bootclasspath" || option == "-classpath" || option == "-cp" || option == "-sourcepath" || option == "-d" || option == "-source" || option == "-target" || option == "-encoding" || option == "-s" || // ROSE Options option == "-rose:java:cp" || option == "-rose:java:classpath" || option == "-rose:java:sourcepath" || option == "-rose:java:d" || option == "-rose:java:ds" || option == "-rose:java:source" || option == "-rose:java:target" || option == "-rose:java:encoding" || option == "-rose:java:ecj:jvm_options"; }// Cmdline:Java:::OptionRequiresArgument void Rose::Cmdline::Java:: StripRoseOptions (std::vector<std::string>& argv) { std::string argument; // (1) Options WITHOUT an argument sla(argv, "-rose:", "($)", "(j|J|java|Java)",1); // // (2) Options WITH an argument // Cmdline::Java::Ecj::StripRoseOptions(argv); // Remove Java options with ROSE-Java prefix; option arguments removed // by generateOptionWithNameParameterList. // // For example, // // BEFORE: argv = [-rose:java:classpath, "/some/class/path", -rose:verbose, "3"] // AFTER: argv = [-rose:verbose, "3"] // java_options = [-classpath, "/some/class/path"] std::vector<std::string> java_options = CommandlineProcessing::generateOptionWithNameParameterList( argv, // Remove ROSE-Java options from here Cmdline::Java::option_prefix, // Current prefix "-"); // New prefix for (std::vector<std::string>::iterator it = java_options.begin(); it != java_options.end(); ++it) { std::string java_option = *it; // Skip ROSE-specific Java options // // "-ds": source destination directory for unparsed code is specific to ROSE. if (java_option == "-ds") ++it; // skip over argument, i.e. "-ds <argument>"; TODO: add argument verification else argv.push_back(java_option); } }// Cmdline::Java::StripRoseOptions void Rose::Cmdline::Java:: Process (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] Processing Java commandline options: " << CommandlineProcessing::generateStringFromArgList(argv, true, false) << std::endl; } Cmdline::Java::ProcessJavaOnly(project, argv); Cmdline::Java::ProcessClasspath(project, argv); Cmdline::Java::ProcessSourcepath(project, argv); Cmdline::Java::ProcessDestdir(project, argv); Cmdline::Java::ProcessSourceDestdir(project, argv); Cmdline::Java::ProcessS(project, argv); Cmdline::Java::ProcessSource(project, argv); Cmdline::Java::ProcessTarget(project, argv); Cmdline::Java::ProcessEncoding(project, argv); Cmdline::Java::ProcessG(project, argv); Cmdline::Java::ProcessNoWarn(project, argv); Cmdline::Java::ProcessVerbose(project, argv); Cmdline::Java::ProcessDeprecation(project, argv); Cmdline::Java::ProcessBootclasspath(project, argv); Cmdline::Java::Ecj::Process(project, argv); } void Rose::Cmdline::Java:: ProcessJavaOnly (SgProject* project, std::vector<std::string>& argv) { project->set_Java_only(false); bool is_java_only = CommandlineProcessing::isOption(argv,"-rose:java","",true); if (is_java_only) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Turning on Java only mode" << std::endl; // Java code is only compiled, not linked as is C/C++ and Fortran. project->set_compileOnly(true); project->set_Java_only(true); } } void Rose::Cmdline::Java:: ProcessClasspath (SgProject* project, std::vector<std::string>& argv) { std::string classpath = ""; bool has_java_classpath = // -rose:java:classpath CommandlineProcessing::isOptionWithParameter( argv, Java::option_prefix, "classpath", classpath, Cmdline::REMOVE_OPTION_FROM_ARGV) || // -rose:java:cp CommandlineProcessing::isOptionWithParameter( argv, Java::option_prefix, "cp", classpath, Cmdline::REMOVE_OPTION_FROM_ARGV) || // -classpath CommandlineProcessing::isOptionWithParameter( argv, "-classpath", "", classpath, Cmdline::REMOVE_OPTION_FROM_ARGV) || // -cp CommandlineProcessing::isOptionWithParameter( argv, "-cp", "", classpath, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_classpath) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java classpath option" << std::endl; // Parse and register the Java classpath in the project std::list<std::string> classpath_list = StringUtility::tokenize(classpath, ':'); project->set_Java_classpath(classpath_list); // Sanity check: Check existence of paths in Classpath BOOST_FOREACH(std::string path, classpath_list) { bool path_exists = boost::filesystem::exists(path); if (!path_exists) { std::cout << "[WARN] " << "Invalid path specified in -classpath; path does not exist: " << "'" << path << "'" << std::endl; } }// sanity check }// has_java_classpath }// Cmdline::Java::ProcessClasspath void Rose::Cmdline::Java:: ProcessBootclasspath (SgProject* project, std::vector<std::string>& argv) { std::string bootclasspath = ""; bool has_java_bootclasspath = // -bootclasspath CommandlineProcessing::isOptionWithParameter( argv, "-bootclasspath", "", bootclasspath, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_bootclasspath) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java -bootclasspath option" << std::endl; // Parse and register the Java bootclasspath in the project std::list<std::string> bootclasspath_list = StringUtility::tokenize(bootclasspath, ':'); project->set_Java_bootclasspath(bootclasspath_list); // Sanity check: Check existence of paths in Bootbootclasspath BOOST_FOREACH(std::string path, bootclasspath_list) { bool path_exists = boost::filesystem::exists(path); if (!path_exists) { std::cout << "[WARN] " << "Invalid path specified in -bootclasspath; path does not exist: " << "'" << path << "'" << std::endl; } }// sanity check }// has_java_bootclasspath }// Cmdline::Java::ProcessBootclasspath void Rose::Cmdline::Java:: ProcessSourcepath (SgProject* project, std::vector<std::string>& argv) { std::string sourcepath = ""; bool has_java_sourcepath = // -rose:java:sourcepath CommandlineProcessing::isOptionWithParameter( argv, Java::option_prefix, "sourcepath", sourcepath, Cmdline::REMOVE_OPTION_FROM_ARGV) || // -sourcepath CommandlineProcessing::isOptionWithParameter( argv, "-sourcepath", "", sourcepath, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_sourcepath) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java sourcepath option" << std::endl; // Parse and register the Java sourcepath in the project std::list<std::string> sourcepath_list = StringUtility::tokenize(sourcepath, ':'); project->set_Java_sourcepath(sourcepath_list); // Sanity check: Check existence of paths in sourcepath BOOST_FOREACH(std::string path, sourcepath_list) { bool path_exists = boost::filesystem::exists(path); if (!path_exists) { std::cout << "[WARN] " << "Invalid path specified in -sourcepath; path does not exist: " << "'" << path << "'" << std::endl; } }// sanity check }// has_java_sourcepath }// Cmdline::Java::ProcessSourcepath void Rose::Cmdline::Java:: ProcessDestdir (SgProject* project, std::vector<std::string>& argv) { std::string destdir = ""; bool has_java_destdir = // -rose:java:d CommandlineProcessing::isOptionWithParameter( argv, Java::option_prefix, "destdir", destdir, Cmdline::REMOVE_OPTION_FROM_ARGV) || // -d CommandlineProcessing::isOptionWithParameter( argv, "-d", "", destdir, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_destdir) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java destdir option" << std::endl; project->set_Java_destdir(destdir); // Sanity check: Check existence of destdir path { bool directory_exists = boost::filesystem::is_directory(destdir); if (!directory_exists) { std::cout << "[WARN] " << "Invalid -destdir directory path; path does not exist: " << "'" << destdir << "'" << std::endl; } }// sanity check }// has_java_destdir }// Cmdline::Java::ProcessDestdir void Rose::Cmdline::Java:: ProcessSourceDestdir (SgProject* project, std::vector<std::string>& argv) { std::string source_destdir = ""; bool has_java_source_destdir = // -rose:java:ds CommandlineProcessing::isOptionWithParameter( argv, Java::option_prefix, "ds", source_destdir, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_source_destdir) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing ROSE-Java source destdir option" << std::endl; project->set_Java_source_destdir(source_destdir); // Sanity check: Check existence of source destdir path { bool directory_exists = boost::filesystem::is_directory(source_destdir); if (!directory_exists) { std::cout << "[WARN] " << "Invalid source destdir directory path; path does not exist: " << "'" << source_destdir << "'" << std::endl; } }// sanity check }// has_java_source_destdir }// Cmdline::Java::ProcessSourceDestdir void Rose::Cmdline::Java:: ProcessS (SgProject* project, std::vector<std::string>& argv) { std::string generate_source_file_dir = ""; bool has_java_source_destdir = // -s CommandlineProcessing::isOptionWithParameter( argv, "-s", "", generate_source_file_dir, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_source_destdir) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing javac -s option" << std::endl; project->set_Java_s(generate_source_file_dir); // Sanity check: Check existence of source destdir path { bool directory_exists = boost::filesystem::is_directory(generate_source_file_dir); if (!directory_exists) { std::cout << "[WARN] " << "Invalid javac -s directory path; path does not exist: " << "'" << generate_source_file_dir << "'" << std::endl; } }// sanity check }// has_java_source_destdir }// Cmdline::Java::ProcessSourceDestdir void Rose::Cmdline::Java:: ProcessSource (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java -source " << std::endl; std::string source = ""; bool has_java_source = // -source CommandlineProcessing::isOptionWithParameter( argv, "-source", "", source, Cmdline::REMOVE_OPTION_FROM_ARGV) || // -rose:java:source CommandlineProcessing::isOptionWithParameter( argv, Java::option_prefix, "source", source, Cmdline::REMOVE_OPTION_FROM_ARGV); // DQ (3/25/2017): Eliminate warning of unused variable via a trivial use. ROSE_ASSERT(has_java_source == true || has_java_source == false); // Default //if (has_java_source == false) //{ // source = "1.6"; //} project->set_Java_source(source); }// Cmdline::Java::ProcessSource void Rose::Cmdline::Java:: ProcessTarget (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java -target " << std::endl; std::string target = ""; #if 0 // DQ (9/20/2018): This is an unused variable now (and a compiler warning). bool has_java_target = // -target CommandlineProcessing::isOptionWithParameter( argv, "-target", "", target, Cmdline::REMOVE_OPTION_FROM_ARGV) || // -rose:java:target CommandlineProcessing::isOptionWithParameter( argv, Java::option_prefix, "target", target, Cmdline::REMOVE_OPTION_FROM_ARGV); // Default //if (has_java_target == false) //{ // target = "1.6"; //} #endif project->set_Java_target(target); }// Cmdline::Java::Processtarget void Rose::Cmdline::Java:: ProcessEncoding (SgProject* project, std::vector<std::string>& argv) { std::string encoding = ""; bool has_java_encoding = // -encoding CommandlineProcessing::isOptionWithParameter( argv, "-encoding", "", encoding, Cmdline::REMOVE_OPTION_FROM_ARGV) || // -rose:java:encoding CommandlineProcessing::isOptionWithParameter( argv, Java::option_prefix, "encoding", encoding, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_encoding) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java -encoding " << encoding << std::endl; project->set_Java_encoding(encoding); }// has_java_encoding }// Cmdline::Java::Processencoding void Rose::Cmdline::Java:: ProcessG (SgProject* project, std::vector<std::string>& argv) { std::string g = ""; bool has_java_g = // -g CommandlineProcessing::isOptionWithParameter( argv, "-g", "", g, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_g) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java -g[:none,source,lines,vars] " << g << std::endl; project->set_Java_g(g); }// has_java_g }// Cmdline::Java::Processg void Rose::Cmdline::Java:: ProcessNoWarn (SgProject* project, std::vector<std::string>& argv) { bool has_java_nowarn = // -nowarn CommandlineProcessing::isOption( argv, "-nowarn", "", Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_nowarn) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java -nowarn " << std::endl; }// has_java_nowarn project->set_Java_nowarn(has_java_nowarn); }// Cmdline::Java::Processnowarn void Rose::Cmdline::Java:: ProcessVerbose (SgProject* project, std::vector<std::string>& argv) { bool has_java_verbose = // -verbose CommandlineProcessing::isOption( argv, "-verbose", "", Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_verbose) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java -verbose " << std::endl; }// has_java_verbose project->set_Java_verbose(has_java_verbose); }// Cmdline::Java::ProcessVerbose void Rose::Cmdline::Java:: ProcessDeprecation (SgProject* project, std::vector<std::string>& argv) { bool has_deprecation = // -deprecation CommandlineProcessing::isOption( argv, "-deprecation", "", Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_deprecation) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java -deprecation " << std::endl; } project->set_Java_deprecation(has_deprecation); }// ::Rose::Cmdline::Java::ProcessDeprecation Rose_STL_Container<std::string> Rose::Cmdline::Java:: ExpandArglist (const std::string& arglist_string) { ROSE_ASSERT(!arglist_string.empty()); ROSE_ASSERT(arglist_string[0] == '@'); // @filename Rose_STL_Container<std::string> arglist; if (arglist_string.size() < 2) { std::cout << "[FATAL] No filename found after @ symbol " << "on the command line. Should be @<filename>." << std::endl; ROSE_ASSERT(false); } else { std::string filename = arglist_string.substr(1); ROSE_ASSERT(filename.empty() == false); arglist = Rose::Cmdline::Java::GetListFromFile(filename); if (SgProject::get_verbose() > 2) { printf ("[INFO] " "Expanded @%s = '%s'\n", filename.c_str(), StringUtility::listToString(arglist).c_str()); } return arglist; } }// Cmdline::Java::ExpandArglist // TODO: should we validate that '@arglist' is only // passed once on the commandline? Rose_STL_Container<std::string> Rose::Cmdline::Java:: ExpandArglist (const Rose_STL_Container<std::string>& p_argv) { Rose_STL_Container<std::string> argv = p_argv; Rose_STL_Container<std::string>::iterator i = argv.begin(); while (i != argv.end()) { std::string argument = *i; if (argument[0] == '@') { Rose_STL_Container<std::string> arglist = Rose::Cmdline::Java::ExpandArglist(argument); // Insert actual list of arguments in-place where @filename was found int i_offset = std::distance(argv.begin(), i); argv.erase(i); argv.insert(argv.end(), arglist.begin(), arglist.end()); i = argv.begin() + i_offset; } else { ++i; // next commandline argument } } return argv; } std::vector<std::string> Rose::Cmdline::Java:: GetListFromFile (const std::string& filename) { ROSE_ASSERT(! filename.empty()); std::vector<std::string> list; std::ifstream file(filename.c_str()); std::string line; while (!file.fail() && std::getline(file, line)) { // TOO1 (3/4/2014): Strip quotes surrounding arguments; this is specific // to how Maven utilizes javac @argfiles, e.g.: // // "javac" // "-target 1.6" // "-source 1.6" // "File.java" // // TODO: Re-implement since this will not handle the case // where file paths contain spaces and require quotations: // // "javac" // "C:\ Program Files\Foo Bar Workspace\File.java" line.erase( std::remove(line.begin(), line.end(), '\"'), line.end()); list.push_back(line); } file.close(); if (list.empty()) { std::cout << "[FATAL] No arguments found in file " << "'" << filename << "'" << std::endl; ROSE_ASSERT(false); } return list; } // -rose:java:ecj options have already been transformed by Cmdline::Java::StripRoseOptions. // Therefore, for example, // // -rose:java:ecj:jvm_options // // is now actually: // // -ecj:jvm_options // void Rose::Cmdline::Java::Ecj:: StripRoseOptions (std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] " << "Stripping ROSE Java ECJ commandline options" << std::endl; } // (1) Options WITHOUT an argument sla(argv, "-rose:java:ecj:", "($)", "batch_mode", 1); // // (2) Options WITH an argument // // Remove ECJ options with ROSE-ECJ prefix; option arguments removed // by generateOptionWithNameParameterList. std::vector<std::string> ecj_options = CommandlineProcessing::generateOptionWithNameParameterList( argv, // Remove ROSE-Java options from here "-ecj:", // Current prefix "-"); // New prefix // TOO1 (2/11/2014): Skip ALL ROSE-specific ECJ options; // at this stage, we only have "-rose:java:ecj:jvm_options", // and this is only inteded for the ECJ frontend's JVM. BOOST_FOREACH(std::string ecj_option, ecj_options) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] " << "Stripping ECJ JVM commandline argument '" << ecj_option << "'" << std::endl; } } }// Cmdline::Java::StripRoseOptions std::string Rose::Cmdline::Java::Ecj:: GetRoseClasspath () { #ifdef _MSC_VER std::string separator = ";"; #else std::string separator = ":"; #endif std::string classpath = "-Djava.class.path="; // Java (ECJ front-end) support (adding specific jar file) std::string ecj_jar_file_name = std::string("ecj-3.8.2.jar"); std::string ecj_class_path_jarfile = "src/3rdPartyLibraries/java-parser/" + ecj_jar_file_name; classpath += findRoseSupportPathFromBuild( ecj_class_path_jarfile, std::string("lib/") + ecj_jar_file_name ); classpath += separator; // Java (ECJ front-end) support (adding path to source tree for the jar file). // This allows us to avoid copying the jar file to the build tree which is // write protected in the execution of the "make distcheck" rule. std::string ecj_class_path = "src/3rdPartyLibraries/java-parser/"; classpath += findRoseSupportPathFromBuild( ecj_class_path, std::string("lib/")); classpath += separator; // Everything else? classpath += "."; return classpath; } void Rose::Cmdline::Java::Ecj:: ProcessBatchMode (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java -rose:java:ecj:batch_mode " << std::endl; bool has_batch_mode = // -rose:java:ecj:batch_mode CommandlineProcessing::isOption( argv, Java::option_prefix, "ecj:batch_mode", Cmdline::REMOVE_OPTION_FROM_ARGV); if (SgProject::get_verbose() > 1) std::cout << "[INFO] -rose:java:ecj:batch_mode=" << has_batch_mode << std::endl; Rose::Cmdline::Java::Ecj::batch_mode = has_batch_mode; project->set_Java_batch_mode(has_batch_mode); }// ::Rose::Cmdline::Java::Ecj::ProcessBatchMode void Rose::Cmdline::Java::Ecj:: Process (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java's ECJ frontend commandline options" << std::endl; ProcessBatchMode(project, argv); ProcessJvmOptions(project, argv); ProcessEnableRemoteDebugging(project, argv); } void Rose::Cmdline::Java::Ecj:: ProcessJvmOptions (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java's ECJ frontend JVM commandline options" << std::endl; std::string ecj_jvm_options = ""; bool has_ecj_jvm_options = // -rose:java:ecj:jvm_options CommandlineProcessing::isOptionWithParameter( argv, Java::option_prefix, "ecj:jvm_options", ecj_jvm_options, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_ecj_jvm_options) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] Processing ECJ JVM options: " << "'" << ecj_jvm_options << "'" << std::endl; } std::list<std::string> ecj_jvm_options_list = StringUtility::tokenize(ecj_jvm_options, ' '); project->set_Java_ecj_jvm_options(ecj_jvm_options_list); Cmdline::Java::Ecj::jvm_options.insert( Cmdline::Java::Ecj::jvm_options.begin(), ecj_jvm_options_list.begin(), ecj_jvm_options_list.end()); }// has_ecj_jvm_options }// Cmdline::Java::ProcessJvmOptions void Rose::Cmdline::Java::Ecj:: ProcessEnableRemoteDebugging (SgProject* project, std::vector<std::string>& argv) { bool has_java_remote_debug = // -rose:java:remoteDebug CommandlineProcessing::isOption( argv, Java::option_prefix, "ecj:enable_remote_debugging", Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_java_remote_debug) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing Java remote debugging option" << std::endl; #ifdef ROSE_BUILD_JAVA_LANGUAGE_SUPPORT Cmdline::Java::Ecj::jvm_options.push_back( "-agentlib:jdwp=transport=dt_socket,server=y,address=8000"); #else std::cout << "[FATAL] " << "JVM remote debugging cannot be enabled since ROSE-Java " << "support is turned off" << std::endl; ROSE_ASSERT(false); #endif }// has_java_remote_debug }// Cmdline::Java::Ecj::ProcessEnableRemoteDebugging //------------------------------------------------------------------------------ // X10 //------------------------------------------------------------------------------ void Rose::Cmdline::X10:: Process (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing X10 commandline options" << std::endl; ProcessX10Only(project, argv); } void Rose::Cmdline::X10:: ProcessX10Only (SgProject* project, std::vector<std::string>& argv) { bool is_x10_only = CommandlineProcessing::isOption( argv, X10::option_prefix, "", true); if (is_x10_only) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Turning on X10 only mode" << std::endl; // X10 code is only compiled, not linked as is C/C++ and Fortran. project->set_compileOnly(true); project->set_X10_only(true); } } void Rose::Cmdline::X10::X10c:: Process (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing X10 compiler frontend commandline options" << std::endl; ProcessJvmOptions(project, argv); } void Rose::Cmdline::X10::X10c:: ProcessJvmOptions (SgProject* project, std::vector<std::string>& argv) { if (SgProject::get_verbose() > 1) std::cout << "[INFO] Processing X10 compiler frontend JVM commandline options" << std::endl; std::string x10c_jvm_options = ""; bool has_x10c_jvm_options = CommandlineProcessing::isOptionWithParameter( argv, X10::option_prefix, "x10c:jvm_options", x10c_jvm_options, Cmdline::REMOVE_OPTION_FROM_ARGV); if (has_x10c_jvm_options) { if (SgProject::get_verbose() > 1) { std::cout << "[INFO] Processing X10 compiler options: " << "'" << x10c_jvm_options << "'" << std::endl; } std::list<std::string> x10c_jvm_options_list = StringUtility::tokenize(x10c_jvm_options, ' '); Cmdline::X10::X10c::jvm_options.insert( Cmdline::X10::X10c::jvm_options.begin(), x10c_jvm_options_list.begin(), x10c_jvm_options_list.end()); }// has_x10c_jvm_options }// Cmdline::X10::ProcessJvmOptions std::string Rose::Cmdline::X10::X10c:: GetRoseClasspath () { std::string classpath = "-Djava.class.path="; #ifdef ROSE_BUILD_X10_LANGUAGE_SUPPORT classpath += std::string(X10_INSTALL_PATH) + "/lib/x10c.jar" + ":" + std::string(X10_INSTALL_PATH) + "/lib/lpg.jar" + ":" + std::string(X10_INSTALL_PATH) + "/lib/com.ibm.wala.cast.java_1.0.0.201101071300.jar" + ":" + std::string(X10_INSTALL_PATH) + "/lib/com.ibm.wala.cast_1.0.0.201101071300.jar" + ":" + std::string(X10_INSTALL_PATH) + "/lib/com.ibm.wala.core_1.1.3.201101071300.jar" + ":" + std::string(X10_INSTALL_PATH) + "/lib/com.ibm.wala.shrike_1.3.1.201101071300.jar" + ":" + std::string(X10_INSTALL_PATH) + "/lib/x10wala.jar" + ":" + std::string(X10_INSTALL_PATH) + "/lib/org.eclipse.equinox.common_3.6.0.v20100503.jar"; #endif // ROSE_BUILD_X10_LANGUAGE_SUPPORT classpath += ":"; // Everything else? classpath += "."; return classpath; } /*----------------------------------------------------------------------------- * namespace SgFile { *---------------------------------------------------------------------------*/ void SgFile::usage ( int status ) { if (status != 0) fprintf (stderr,"Try option `--help' for more information.\n"); else { // it would be nice to insert the version of ROSE being used (using the VERSION macro) fputs( "\n" "This ROSE translator provides a means for operating on C, C++, Fortran and Java\n" "source code; as well as on x86, ARM, and PowerPC executable code (plus object files \n" "and libraries).\n" "\n" "Usage: rose [OPTION]... FILENAME...\n" "\n" "If a long option shows a mandatory argument, it is mandatory for the equivalent\n" "short option as well, and similarly for optional arguments.\n" "\n" "Main operation mode:\n" " -rose:(o|output) FILENAME\n" " file containing final unparsed C++ code\n" " (relative or absolute paths are supported)\n" " -rose:keep_going\n" " Similar to GNU Make's --keep-going option.\n" "\n" " If ROSE encounters an error while processing your\n" " input code, ROSE will simply run your backend compiler on\n" " your original source code file, as is, without modification.\n" "\n" " This is useful for compiler tests. For example,\n" " when compiling a 100K LOC application, you can\n" " try to compile as much as possible, ignoring failures,\n" " in order to gauage the overall status of your translator,\n" " with respect to that application.\n" "\n" "Operation modifiers:\n" " -rose:output_warnings compile with warnings mode on\n" " -rose:C_only, -rose:C follow C89 standard, disable C++\n" " -rose:C89_only, -rose:C89\n" " follow C89 standard, disable C++\n" " -rose:C99_only, -rose:C99\n" " follow C99 standard, disable C++\n" " -rose:C11_only, -rose:C11\n" " follow C11 standard, disable C++\n" " -rose:C14_only, -rose:C14\n" " follow C14 standard, disable C++\n" " -rose:Cxx_only, -rose:Cxx\n" " follow C++89 standard\n" " -rose:Cxx11_only, -rose:Cxx11\n" " follow C++11 standard\n" " -rose:Cxx14_only, -rose:Cxx14\n" " follow C++14 standard\n" " -rose:java\n" " compile Java code (work in progress)\n" " -rose:java:cp, -rose:java:classpath, -cp, -classpath\n" " Classpath to look for java classes\n" " -rose:java:sourcepath, -sourcepath\n" " Sourcepath to look for java sources\n" " -rose:java:d, -d\n" " Specifies generated classes destination dir\n" " -rose:java:ds\n" " Specifies translated sources destination dir\n" " -rose:java:source\n" " Specifies java sources version (default=1.6)\n" " -rose:java:target\n" " Specifies java classes target version (default=1.6)\n" " -rose:java:encoding\n" " Specifies the character encoding\n" " -rose:java:ecj:jvm_options\n" " Specifies the JVM startup options\n" // " -rose:java:Xms<size>\n" // " Set initial Java heap size\n" // " -rose:java:Xmx<size>\n" // " Set maximum Java heap size\n" // " -rose:java:Xss<size>\n" // " Set java thread stack size\n" " -rose:Python, -rose:python, -rose:py\n" " compile Python code\n" " -rose:OpenMP, -rose:openmp\n" " follow OpenMP 3.0 specification for C/C++ and Fortran, perform one of the following actions:\n" " -rose:OpenMP:parse_only, -rose:openmp:parse_only\n" " parse OpenMP directives to OmpAttributes, no further actions (default behavior now)\n" " -rose:OpenMP:ast_only, -rose:openmp:ast_only\n" " on top of -rose:openmp:parse_only, build OpenMP AST nodes from OmpAttributes, no further actions\n" " -rose:OpenMP:lowering, -rose:openmp:lowering\n" " on top of -rose:openmp:ast_only, transform AST with OpenMP nodes into multithreaded code \n" " targeting GCC GOMP runtime library\n" " -rose:UPC_only, -rose:UPC\n" " follow Unified Parallel C 1.2 specification\n" " -rose:UPCxx_only, -rose:UPCxx\n" " allows C++ within UPC (follows UPC 1.2 but simpily allows \n" " using C++ as the base language) (not a legitimate language, \n" " since there is no backend compiler to support this).\n" " -rose:upc_threads n Enable UPC static threads compilation with n threads\n" " n>=1: static threads; dynamic(default) otherwise\n" " -rose:fortran\n" " compile Fortran code, determining version of\n" " Fortran from file suffix)\n" " -rose:CoArrayFortran, -rose:CAF, -rose:caf\n" " compile Co-Array Fortran code (extension of Fortran 2003)\n" " -rose:CAF2.0, -rose:caf2.0\n" " compile Co-Array Fortran 2.0 code (Rice CAF extension)\n" " -rose:Fortran2003, -rose:F2003, -rose:f2003\n" " compile Fortran 2003 code\n" " -rose:Fortran95, -rose:F95, -rose:f95\n" " compile Fortran 95 code\n" " -rose:Fortran90, -rose:F90, -rose:f90\n" " compile Fortran 90 code\n" " -rose:Fortran77, -rose:F77, -rose:f77\n" " compile Fortran 77 code\n" " -rose:Fortran66, -rose:F66, -rose:f66\n" " compile Fortran 66 code\n" " -rose:FortranIV, -rose:FIV, -rose:fIV\n" " compile Fortran IV code\n" " -rose:FortranII, -rose:FII, -rose:fII\n" " compile Fortran II code (not implemented yet)\n" " -rose:FortranI, -rose:FI, -rose:fI\n" " compile Fortran I code (not implemented yet)\n" " -rose:fortran:ofp:jvm_options\n" " Specifies the JVM startup options\n" " -rose:x10\n" " compile X10 code (work in progress)\n" " -rose:strict strict enforcement of ANSI/ISO standards\n" " -rose:binary, -rose:binary_only\n" " assume input file is for binary analysis (this avoids\n" " ambiguity when ROSE might want to assume linking instead)\n" " -rose:FailSafe, -rose:failsafe\n" " Enable experimental processing of resilience directives defined by FAIL-SAFE annotation language specification.\n" " -rose:astMerge merge ASTs from different files\n" " -rose:astMergeCommandFile FILE\n" " filename where compiler command lines are stored\n" " for later processing (using AST merge mechanism)\n" " -rose:projectSpecificDatabaseFile FILE\n" " filename where a database of all files used in a project are stored\n" " for producing unique trace ids and retrieving the reverse mapping from trace to files" " -rose:compilationPerformanceFile FILE\n" " filename where compiler performance for internal\n" " phases (in CSV form) is placed for later\n" " processing (using script/graphPerformance)\n" " -rose:exit_after_parser just call the parser (C, C++, and fortran only)\n" " -rose:skip_syntax_check skip Fortran syntax checking (required for F2003 and Co-Array Fortran code\n" " when using gfortran versions greater than 4.1)\n" " -rose:relax_syntax_check skip Fortran syntax checking (required for some F90 code\n" " when using gfortran based syntax checking)\n" " -rose:skip_translation_from_edg_ast_to_rose_ast\n" " skip the translation of the EDG AST into the ROSE AST\n" " (an SgProject, SgFile, and empty SgGlobal will be constructed)\n" " -rose:skip_transformation\n" " read input file and skip all transformations\n" " -rose:skip_unparse read and process input file but skip generation of\n" " final C++ output file\n" " -rose:skipfinalCompileStep\n" " read and process input file, \n" " but skip invoking the backend compiler\n" " -rose:collectAllCommentsAndDirectives\n" " store all comments and CPP directives in header\n" " files into the AST\n" " -rose:unparseHeaderFiles\n" " unparse all directly or indirectly modified\n" " header files\n" " -rose:excludeCommentsAndDirectives PATH\n" " provide path to exclude when using the\n" " collectAllCommentsAndDirectives option\n" " -rose:excludeCommentsAndDirectivesFrom FILENAME\n" " provide filename to file with paths to exclude\n" " when using the collectAllCommentsAndDirectives\n" " option\n" " -rose:includeCommentsAndDirectives PATH\n" " provide path to include when using the\n" " collectAllCommentsAndDirectives option\n" " -rose:includeCommentsAndDirectivesFrom FILENAME\n" " provide filename to file with paths to include\n" " when using the collectAllCommentsAndDirectives\n" " option\n" " -rose:skip_commentsAndDirectives\n" " ignore all comments and CPP directives (can\n" " generate (unparse) invalid code if not used with\n" " -rose:unparse_includes)\n" " -rose:prelink activate prelink mechanism to force instantiation\n" " of templates and assignment to files\n" " -rose:instantiation XXX control template instantiation\n" " XXX is one of (none, used, all, local)\n" " -rose:read_executable_file_format_only\n" " ignore disassemble of instructions (helps debug binary \n" " file format for binaries)\n" " -rose:skipAstConsistancyTests\n" " skip AST consitancy testing (for better performance)\n" " -rose:no_optimize_flag_for_frontend\n" " ignore use of __builtin functions in frontend processing\n" " all optimization specified is still done on ROSE generated code\n" "\n" "Plugin Mode:\n" " -rose:plugin_lib <shared_lib_filename>\n" " Specify the file path to a shared library built from plugin source files \n" " This option can repeat multiple times to load multiple libraries \n" " -rose:plugin_action <act_name>\n" " Specify the plugin action to be executed\n" " This option can repeat multiple times to execute multiple actions \n" " in the order shown up in command line \n" " -rose:plugin_arg_<act_name> <option>\n" " Specify one option to be passed to a plugin named act_name\n" " This option can repeat multiple times to provide multiple options to a plugin \n" "\n" "GNU g++ options recognized:\n" " -ansi equivalent to -rose:strict\n" " -fno-implicit-templates disable output of template instantiations in\n" " generated source\n" " -fno-implicit-inline-templates\n" " disable output of inlined template instantiations\n" " in generated source\n" " -S gnu option trivial\n" " -u (-undefined) gnu option trivial\n" " -version-info <name> gnu option trivial (option not passed on to linker yet, \n" " incomplete implementation)\n" " -MM <filename> gnu Makefile dependence generation (option not passed \n" " on to compiler yet, incomplete implementation)\n" "\n" "Informative output:\n" " -rose:help, --help, -help, --h\n" " print this help, then exit\n" " -rose:version, --version, --V\n" " print ROSE program version number, then exit\n" " -rose:markGeneratedFiles\n" " add \"#define ROSE_GENERATED_CODE\" to top of all\n" " generated code\n" " -rose:verbose [LEVEL] verbosely list internal processing (default=0)\n" " Higher values generate more output (can be\n" " applied to individual files and to the project\n" " separately).\n" " -rose:log WHAT\n" " Control diagnostic output. See '-rose:log help' for\n" " more information.\n" " -rose:assert HOW\n" " Determines how a failed assertion is handled. The value\n" " for HOW should be 'abort', 'exit' with non-zero status, or\n" " 'throw' a Rose::Diagnostics::FailedAssertion exception. Only\n" " assertions that use the Sawyer mechanism are affected.\n" " -rose:output_parser_actions\n" " call parser with --dump option (fortran only)\n" " -rose:embedColorCodesInGeneratedCode LEVEL\n" " embed color codes into generated output for\n" " visualization of highlighted text using tview\n" " tool for constructs specified by LEVEL\n" " LEVEL is one of:\n" " 1: missing position information\n" " 2: compiler-generated code\n" " 3: other code\n" " -rose:generateSourcePositionCodes LEVEL\n" " generate separate file of source position\n" " information for highlighting original source\n" " file using tview tool for constructs specified\n" " by LEVEL\n" " LEVEL is one of:\n" " 1: statements, preprocessor directives and\n" " comments\n" " 2: expressions\n" "\n" "Control EDG frontend processing:\n" " -edg:new_frontend force use of external EDG front end (disables use\n" " of rest of ROSE/SAGE)\n" " -edg:KCC_frontend for use of KCC (with -c option) as new frontend\n" " (must be specified with -edg:new_frontend)\n" " -edg:XXX pass -XXX to EDG front-end\n" " --edg:XXX pass --XXX to EDG front-end\n" " -edg_parameter: XXX YYY pass -XXX YYY to EDG front-end (note: space after colon is required)\n" " --edg_parameter: XXX YYY pass --XXX YYY to EDG front-end (note: space after colon is required)\n" "\n" "Control Fortran frontend processing:\n" " -rose:cray_pointer_support\n" " turn on internal support for cray pointers\n" " (Note: not implemented in front-end (OFP) yet.)\n" " -fortran:XXX pass -XXX to independent semantic analysis\n" " (useful for turning on specific warnings in front-end)\n" "\n" "Control code generation:\n" " -rose:unparser:clobber_input_file\n" " **CAUTION**RED*ALERT**CAUTION**\n" " If you don't know what this option does, don't use it!\n" " We are not responsible for any mental or physical damage\n" " that you will incur with the use of this option :)\n" "\n" " Note: This option breaks parallel builds, so make sure\n" " that with this option you use ROSE, and run your build\n" " system, sequentially.\n" " **CAUTION**RED*ALERT**CAUTION**\n" " -rose:unparse_line_directives\n" " unparse statements using #line directives with\n" " reference to the original file and line number\n" " to support view of original source in debuggers\n" " and external tools\n" " -rose:unparse_function_calls_using_operator_syntax\n" " unparse overloaded operators using operator syntax\n" " relevant to C++ only (default is to reproduce use\n" " defined by the input code).\n" " -rose:unparse_function_calls_using_operator_names\n" " unparse overloaded operators using operator names \n" " (not operator syntax) relevant to C++ only (default\n" " is to reproduce use defined by the input code).\n" " -rose:unparse_instruction_addresses\n" " Outputs the addresses in left column (output\n" " inappropriate as input to assembler)\n" " -rose:unparse_raw_memory_contents\n" " Outputs memory contents in left column\n" " -rose:unparse_binary_file_format\n" " Outputs binary executable file format information\n" " -rose:unparse_includes\n" " unparse all include files into the source file.\n" " This is a backup option for fail-safe processing\n" " of CPP directives (which can be tricky)\n" " -rose:C_output_language\n" " force use of C as output language (currently\n" " generates C/C++)\n" " -rose:Cxx_output_language\n" " force use of C++ as output language\n" " -rose:Fortran_output_language\n" " force use of Fortran as output language\n" " -rose:Promela_output_language\n" " force use of Promela as output language (not\n" " supported)\n" " -rose:PHP_output_language\n" " force use of PHP as output language\n" " -rose:outputFormat generate code in either fixed/free format (fortran only)\n" " options are: fixedOutput|fixedFormatOutput or \n" " freeOutput|freeFormatOutput\n" " -rose:backendCompileFormat\n" " use backend compiler option to compile generated code\n" " in either fixed/free format (fortran only)\n" " options are: fixedOutput|fixedFormatOutput or \n" " freeOutput|freeFormatOutput\n" " -rose:unparseHeaderFilesRootFolder FOLDERNAME\n" " A relative or an absolute path to the root folder,\n" " in which unparsed header files are stored.\n" " Note that the folder must be empty (or does not exist).\n" " If not specified, the default relative location _rose_ \n" " is used.\n" " -rose:applicationRootDirectory DIRECTORYNAME\n" " A relative or an absolute path to the root folder,\n" " in which all application files will use for the unparsing \n" " of source files and header files. If not specified, the default \n" " location is the current directory. \n" " -rose:unparse_in_same_directory_as_input_file\n" " Build the generated source file (unparse) in the same directory as \n" " the input source file. This allows the backend compiler \n" " to compile the generated file exactly the same as the \n" " input would have been compiled (following original header file \n" " source path lookup rules precisely (this is rarely required)). \n" " -rose:suppressConstantFoldingPostProcessing\n" " Optimization to avoid postprocessing phase in C code only\n" " This option has only shown an effect on the 2.5 million line\n" " wireshark application\n" " (not presently compatable with OpenMP or C++ code)\n" " -rose:noclobber_output_file\n" " force error on rewrite of existing output file (default: false).\n" " -rose:noclobber_if_different_output_file\n" " force error on rewrite of existing output file only if result\n" " if a different output file (default: false). \n" " -rose:appendPID\n" " append PID into the temporary output name. \n" " This can avoid issues in parallel compilation (default: false). \n" " -rose:unparse_tokens\n" " Unparses code using original token stream where possible.\n" " Only C/C++ are supported now. Fortran support is under development \n" " -rose:unparse_using_leading_and_trailing_token_mappings \n" " unparses code using original token stream and forces the output \n" " of two files representing the unparsing of each statement using \n" " the token stream mapping to the AST. The token_leading_* file \n" " uses the mapping and the leading whitespace mapping between \n" " statements, where as the token_trailing_* file uses the mapping \n" " and the trailing whitespace mapping between statements. Both \n" " files should be identical, and the same as the input file. \n" " -rose:unparse_template_ast\n" " unparse C++ templates from their AST, not from strings stored by EDG. \n" " -rose:unparseTemplateDeclarationsFromAST\n" " (experimental) option to permit unparsing template declarations \n" " from the AST (default: false). \n" "\n" "Debugging options:\n" " -rose:detect_dangling_pointers LEVEL \n" " detects references to previously deleted IR nodes in the AST\n" " (part of AST consistancy tests, default is false since some codes fail this test)\n" " LEVEL is one of:\n" " 0: off (does not issue warning)\n" " 1: on (issues warning with information)\n" " 2: on (issues error and exists)\n" "\n" "Testing Options:\n" " -rose:negative_test test ROSE using input that is expected to fail\n" " (returns 0 if input test failed, else error if\n" " passed)\n" " -rose:test LEVEL limit parts of ROSE which are run\n" " LEVEL is one of:\n" " 0: transparent (ROSE translator does nothing)\n" " 1: run the KCC front end only (assumes it is in\n" " path)\n" " 2: run the newer version of EDG (compiled\n" " separately from SAGE) 'edgFrontEnd'\n" " (see\n" " src/frontend/EDG/EDG_3.3/src/Makefile.am\n" " for instructions on how to build EDG\n" " without SAGE III)\n" " 3: run internal (older) version of edg front end\n" " (deprecated option)\n" " 4: same as 3 plus parse into Sage III program\n" " tree\n" " 5: same as 4 plus unparse untransformed source\n" " code\n" " 6: same as 5 plus compile generated source code\n" " 7: same as 5 plus build higher level grammars\n" " before unparsing\n" " 8: same as 6 plus run midend (transformations)\n" " before unparsing\n" "\n" "Report bugs to <[email protected]>.\n" , stdout); // Obsolete options // -sage:sage_backend have EDG call the sage backend // -sage:disable_cp_backend prevent EDG from calling the cp backend // -rose:outputGrammarTreeFiles write out program tree representation in C++ grammar (useful for internal debugging) // -rose:outputGrammarTreeFilesForHeaderFiles (include header files in above option (must be specified after above option) // DQ (5/20/2005): More obsolete options // -edg:disable_edg_backend prevent EDG from calling the sage backend // -sage:disable_sage_backend prevent EDG from calling the sage backend // -sage:enable_cp_backend have EDG call the cp backend // -sage:preinit_il do a preinit stage between the front-end and } #if 1 // Comment this out for now while we test! exit (status); #endif } void SgFile::processRoseCommandLineOptions ( vector<string> & argv ) { // Strip out the rose specific command line options // then search for all filenames (options without the "-" prefix) // the assume all other arguments are to be passed onto the C or C++ compiler // int optionCount = 0; // int i = 0; // DQ (1/17/2006): test this // ROSE_ASSERT(get_fileInfo() != NULL); // Split out the ROSE options first // printf ("Before processing ROSE options argc = %d \n",argc); // // help option (allows alternative -h or -help instead of just -rose:help) // This is the only rose options that does not require the "-rose:" prefix // if ( CommandlineProcessing::isOption(argv,"-rose:","(h|help)",true) == true || CommandlineProcessing::isOption(argv,"--", "(h|help)",true) == true || CommandlineProcessing::isOption(argv,"-","(h|help)",true) == true ) { // printf ("\nROSE (pre-release alpha version: %s) \n",VERSION); // Rose::usage(0); cout << version_message() << endl; usage(0); // exit(0); } // // version option // if ( CommandlineProcessing::isOption(argv,"-rose:","(V|version)",true) == true ) { // function in SAGE III to access version number of EDG extern std::string edgVersionString(); // printf ("\nROSE (pre-release alpha version: %s) \n",VERSION); cout << version_message() << endl; printf (" Using C++ and C frontend from EDG (version %s) internally \n",edgVersionString().c_str()); } // // Diagnostic logging. We need all of the '-rose:log WHAT' command-line switches in the order they appear, which seems to // mean that we need to parse the argv vector ourselves. CommandlineParsing doesn't have a suitable function, and the sla // code in sla++.C is basically unreadable and its minimal documentation doesn't seem to match its macro-hidden API, // specifically the part about being able to return an array of values. // Rose::initialize(NULL); static const std::string removalString = "(--REMOVE_ME--)"; for (size_t i=0; i<argv.size(); ++i) { if ((0==strcmp(argv[i].c_str(), "-rose:log")) && i+1 < argv.size()) { argv[i] = removalString; std::string switchValue = argv[++i]; argv[i] = removalString; // This is a bit of a roundabout way to do this, but it supports "help", "list", etc and keeps ROSE's capabilities // up to date with the latest documentation in Sawyer. using namespace Sawyer::CommandLine; SwitchGroup switches; switches.insert(Switch("rose:log") .resetLongPrefixes("-") // ROSE switches only support single hyphens .action(configureDiagnostics("rose:log", Diagnostics::mfacilities)) .argument("config")); std::vector<std::string> args; args.push_back("-rose:log"); args.push_back(switchValue); Parser parser; parser.with(switches).parse(args).apply(); // causes configureDiagnostics to be called } } argv.erase(std::remove(argv.begin(), argv.end(), removalString), argv.end()); // // -rose:assert abort|exit|throw // for (size_t i=0; i<argv.size(); ++i) { if (argv[i] == std::string("-rose:assert") && i+1 < argv.size()) { std::string switchValue = argv[i+1]; Sawyer::Assert::AssertFailureHandler handler = NULL; if (switchValue == "abort") { handler = Rose::abortOnFailedAssertion; } else if (switchValue == "exit") { handler = Rose::exitOnFailedAssertion; } else if (switchValue == "throw") { handler = Rose::throwOnFailedAssertion; } if (handler != NULL) { argv[i] = argv[i+1] = removalString; Rose::failedAssertionBehavior(handler); } } } argv.erase(std::remove(argv.begin(), argv.end(), removalString), argv.end()); // // markGeneratedFiles option // set_markGeneratedFiles(false); if ( CommandlineProcessing::isOption(argv,"-rose:","(markGeneratedFiles)",true) == true ) { // Optionally mark the generated files with "#define ROSE_GENERATED_CODE" set_markGeneratedFiles(true); } // // embedColorCodesInGeneratedCode option // int integerOptionForEmbedColorCodesInGeneratedCode = 0; if ( CommandlineProcessing::isOptionWithParameter(argv,"-rose:","(embedColorCodesInGeneratedCode)",integerOptionForEmbedColorCodesInGeneratedCode,true) == true ) { printf ("Calling set_embedColorCodesInGeneratedCode(%d) \n",integerOptionForEmbedColorCodesInGeneratedCode); set_embedColorCodesInGeneratedCode(integerOptionForEmbedColorCodesInGeneratedCode); } // // generateSourcePositionCodes option // int integerOptionForGenerateSourcePositionCodes = 0; if ( CommandlineProcessing::isOptionWithParameter(argv,"-rose:","(generateSourcePositionCodes)",integerOptionForGenerateSourcePositionCodes,true) == true ) { printf ("Calling set_generateSourcePositionCodes(%d) \n",integerOptionForGenerateSourcePositionCodes); set_generateSourcePositionCodes(integerOptionForGenerateSourcePositionCodes); } // // verbose option // // DQ (4/20/2006): This can already be set (to none zero value) if the SgProject was previously build already (see tutorial/selectedFileTranslation.C) // ROSE_ASSERT (get_verbose() == 0); // if ( CommandlineProcessing::isOption(argv,"-rose:","(v|verbose)",true) ) int integerOptionForVerbose = 0; if ( CommandlineProcessing::isOptionWithParameter(argv,"-rose:","(v|verbose)",integerOptionForVerbose,true) == true ) { // set_verbose(true); set_verbose(integerOptionForVerbose); // DQ (8/12/2004): The semantics is to set the global concept of a value // for verbose to the maximum of that from the individual files. if (SgProject::get_verbose() < integerOptionForVerbose) SgProject::set_verbose(integerOptionForVerbose); if ( SgProject::get_verbose() >= 1 ) printf ("verbose mode ON (for SgFile)\n"); } // // Turn on warnings (turns on warnings in fronend, for Fortran support this turns on detection of // warnings in initial syntax checking using gfortran before passing control to Open Fortran Parser). // set_output_warnings(false); ROSE_ASSERT (get_output_warnings() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(output_warnings)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("output warnings mode ON \n"); set_output_warnings(true); } // // Turn on warnings (turns on warnings in fronend, for Fortran support this turns on detection of // warnings in initial syntax checking using gfortran before passing control to Open Fortran Parser). // set_cray_pointer_support(false); ROSE_ASSERT (get_cray_pointer_support() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(cray_pointer_support)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("cray pointer mode ON \n"); set_cray_pointer_support(true); } // // Turn on the output of the parser actions for the parser (only applies to Fortran support). // set_output_parser_actions(false); ROSE_ASSERT (get_output_parser_actions() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(output_parser_actions)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("output parser actions mode ON \n"); set_output_parser_actions(true); } // // Turn on the output of the parser actions for the parser (only applies to Fortran support). // set_exit_after_parser(false); ROSE_ASSERT (get_exit_after_parser() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(exit_after_parser)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("exit after parser mode ON \n"); set_exit_after_parser(true); } if ( CommandlineProcessing::isOption(argv,"-rose:","(skip_parser)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("skip parser mode ON \n"); set_skip_parser(true); } // // DQ (11/20/2010): Added token handling support. // Turn on the output of the tokens from the parser (only applies to C and Fortran support). // set_unparse_tokens(false); ROSE_ASSERT (get_unparse_tokens() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(unparse_tokens)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("unparse tokens mode ON \n"); set_unparse_tokens(true); } // // DQ (12/14/2015): Added more token handling support to improve the source position infor stored in the AST Sg_File_Info objects. // Turn on the output of the tokens from the parser (only applies to C and Fortran support). // set_use_token_stream_to_improve_source_position_info(false); ROSE_ASSERT (get_use_token_stream_to_improve_source_position_info() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(use_token_stream_to_improve_source_position_info)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("use_token_stream_to_improve_source_position_info mode ON \n"); set_use_token_stream_to_improve_source_position_info(true); } // // DQ (12/23/2015): Suppress long-standing normalization of variable declarations with multiple // variables to be converted to individual variable declarations. // set_suppress_variable_declaration_normalization(false); ROSE_ASSERT (get_suppress_variable_declaration_normalization() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(suppress_variable_declaration_normalization)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("suppress_variable_declaration_normalization mode ON \n"); set_suppress_variable_declaration_normalization(true); } // // DQ (1/30/2014): Added more token handling support (internal testing). // set_unparse_tokens_testing(0); ROSE_ASSERT (get_unparse_tokens_testing() == 0); int integerOptionForUnparseTokensTesting = 0; if ( CommandlineProcessing::isOptionWithParameter(argv,"-rose:","(unparse_tokens_testing)",integerOptionForUnparseTokensTesting,true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("unparse tokens testing mode ON: integerOptionForUnparseTokensTesting = %d \n",integerOptionForUnparseTokensTesting); set_unparse_tokens_testing(integerOptionForUnparseTokensTesting); } // // DQ (11/20/2010): Added testing for mappings of tokens to the AST (using both leading and trailing whitespace mappings). // Turn on the output of the testing files for the token unparsing (intenal use only). // set_unparse_using_leading_and_trailing_token_mappings(false); ROSE_ASSERT (get_unparse_using_leading_and_trailing_token_mappings() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(unparse_using_leading_and_trailing_token_mappings)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("unparse_using_leading_and_trailing_token_mappings mode ON \n"); set_unparse_using_leading_and_trailing_token_mappings(true); } // Liao 12/15/2016, support unparsing template AST set_unparse_template_ast (false); ROSE_ASSERT (get_unparse_template_ast() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","unparse_template_ast",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("unparse template AST mode ON \n"); set_unparse_template_ast(true); } // // Turn on the output of the parser actions for the parser (only applies to Fortran support). // set_skip_syntax_check(false); ROSE_ASSERT (get_skip_syntax_check() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(skip_syntax_check)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("skip syntax check mode ON \n"); set_skip_syntax_check(true); } // // Turn on relaxed syntax checking mode (only applies to Fortran support). // set_relax_syntax_check(false); ROSE_ASSERT (get_relax_syntax_check() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(relax_syntax_check)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("relax syntax check mode ON \n"); set_relax_syntax_check(true); } // TV (04/11/2018): Turn on generation of GraphViz representation of EDG's internal representation set_edg_il_to_graphviz(false); ROSE_ASSERT (get_edg_il_to_graphviz() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","edg_il_to_graphviz",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("EDG IL to GraphViz ON \n"); set_edg_il_to_graphviz(true); } // TV (10/01/2018): ROSE-1424 set_no_optimize_flag_for_frontend(false); if ( CommandlineProcessing::isOption(argv,"-rose:","no_optimize_flag_for_frontend",true) == true ) { set_no_optimize_flag_for_frontend(true); } // TV (10/08/2018): ROSE-1392 set_unparse_edg_normalized_method_ROSE_1392(false); if ( CommandlineProcessing::isOption(argv,"-rose:","unparse_edg_normalized_method_ROSE_1392",true) == true ) { set_unparse_edg_normalized_method_ROSE_1392(true); } // DQ (5/24/2015): Record type of optimization (-Os, -O, -O1, -O2, -O3, -O4, -O5), note -O0 means no optimization. // This is required so that when optimization is specified we can turn on the __OPTIMIE__ macro. // See test2015_153.c. // if ( CommandlineProcessing::isOption(argv,"-O","(' '|0|1|2|3|4|5|s)",true) == true ) if ( CommandlineProcessing::isOption(argv,"-O","(1|2|3|4|5|s)",true) == true ) { // printf ("optimizaztion specified on commend line (specific level provided) \n"); set_optimization(true); } else { if ( CommandlineProcessing::isOption(argv,"-O","",true) == true ) { // printf ("optimizaztion specified on commend line (default level specified: -O) \n"); set_optimization(true); } else { // printf ("optimization not specified on commend line (-O0 or no optimization specified) \n"); set_optimization(false); } } //////////////////////////////////////////////////////////////////////// // START parsing standard specifications for C/C++/Fortran (ROSE-1529) // Parsing ROSE's C dialect specification if ( CommandlineProcessing::isOption(argv,"-rose:","(C|C_only)",true) == true ) { printf ("WARNING: Command line option -rose:C is deprecated!\n"); set_C_only(true); set_Cxx_only(false); } if ( CommandlineProcessing::isOption(argv,"-rose:","(C89|C89_only)",true) == true ) { printf ("WARNING: Command line option -rose:C89 is deprecated!\n"); set_C89_only(); } if ( CommandlineProcessing::isOption(argv,"-rose:","(C99|C99_only)",true) == true ) { printf ("WARNING: Command line option -rose:C99 is deprecated!\n"); set_C99_gnu_only(); } if ( CommandlineProcessing::isOption(argv,"-rose:","(C11|C11_only)",true) == true ) { printf ("WARNING: Command line option -rose:C11 is deprecated!\n"); set_C11_gnu_only(); } if ( CommandlineProcessing::isOption(argv,"-rose:","(C14|C14_only)",true) == true ) { printf ("WARNING: Command line option -rose:C14 is deprecated!\n"); set_C14_gnu_only(); } if ( CommandlineProcessing::isOption(argv,"-rose:","(UPC|UPC_only)",true) || CommandlineProcessing::isOption(argv,"--edg:","(upc)",true) || CommandlineProcessing::isOption(argv,"-edg:","(upc)",true) ) { printf ("WARNING: Command line option -rose:UPC is deprecated!\n"); set_UPC_only(); } // Parsing ROSE's C++ dialect specification if ( CommandlineProcessing::isOption(argv,"-rose:","(Cxx|Cxx_only)",true) == true ) { printf ("WARNING: Command line option -rose:Cxx is deprecated!\n"); set_C_only(false); set_Cxx_only(true); } if ( CommandlineProcessing::isOption(argv,"-rose:","(Cxx11|Cxx11_only)",true) == true ) { printf ("WARNING: Command line option -rose:Cxx11 is deprecated!\n"); set_Cxx11_gnu_only(); } if ( CommandlineProcessing::isOption(argv,"-rose:","(Cxx14|Cxx14_only)",true) == true ) { printf ("WARNING: Command line option -rose:Cxx14 is deprecated!\n"); set_Cxx14_gnu_only(); } if (CommandlineProcessing::isOption(argv,"-rose:","(UPCxx|UPCxx_only)",true)) { printf ("WARNING: Command line option -rose:UPCxx is deprecated!\n"); set_UPCxx_only(); } // Parsing ROSE's Fortran dialect specification if ( CommandlineProcessing::isOption(argv,"-rose:","(f|F|Fortran)",true) == true ) { printf ("WARNING: Command line option -rose:Fortran is deprecated! Use -std=fortran instead.\n"); set_Fortran_only(true); } if ( CommandlineProcessing::isOption(argv,"-rose:","(f77|F77|Fortran77)",true) == true ) { printf ("WARNING: Command line option -rose:Fortran77 is deprecated! Use -std=f77 instead.\n"); set_F77_only(); } if ( CommandlineProcessing::isOption(argv,"-rose:","(f90|F90|Fortran90)",true) == true ) { printf ("WARNING: Command line option -rose:Fortran90 is deprecated! Use -std=f90 instead.\n"); set_F90_only(); } if ( CommandlineProcessing::isOption(argv,"-rose:","(f95|F95|Fortran95)",true) == true ) { printf ("WARNING: Command line option -rose:Fortran95 is deprecated! Use -std=f95 instead.\n"); set_F95_only(); } if ( CommandlineProcessing::isOption(argv,"-rose:","(f2003|F2003|Fortran2003)",true) == true ) { printf ("WARNING: Command line option -rose:Fortran2003 is deprecated! Use -std=f2003 instead.\n"); set_F2003_only(); } if ( CommandlineProcessing::isOption(argv,"-rose:","(f2008|F2008|Fortran2008)",true) == true ) { printf ("WARNING: Command line option -rose:Fortran2008 is deprecated! Use -std=f2008 instead.\n"); set_F2008_only(); // DQ (1/25/2016): We might want to skip the syntax checking. set_skip_syntax_check(true); } if ( CommandlineProcessing::isOption(argv,"-rose:","(caf|CAF|CoArrayFortran)",true) == true ) { set_CoArrayFortran_only(true); // Set this as also being F2003 code since Co-Array Fortran is an extension of Fortran 2003 set_F2003_only(); // DQ (12/2/2010): I agree with setting this to true. // It is requested (by Laksono at Rice) that CoArray Fortran defaults be to skip the syntax checking // Laksono 2009.01.27: I think we should put the boolean to 'true' instead of 'false' set_skip_syntax_check(true); } // Parsing GNU-style dialect specification for (unsigned int i = 1; i < argv.size(); i++) { if ( argv[i] == "-std=c" ) { set_C_only(true); } else if ( argv[i] == "-std=gnu" ) { set_C_only(true); set_gnu_standard(); } else if ( argv[i] == "-std=c++" ) { set_Cxx_only(true); } else if ( argv[i] == "-std=gnu++" ) { set_Cxx_only(true); set_gnu_standard(); } else if ( argv[i] == "-std=upc" ) { set_UPC_only(); } else if ( argv[i] == "-std=upcxx" ) { set_UPCxx_only(); } else if ( argv[i] == "-std=fortran" ) { set_Fortran_only(true); } else if ( argv[i] == "-std=c89" ) { set_C89_only(); } else if ( argv[i] == "-std=gnu89" ) { set_C89_gnu_only(); } else if ( argv[i] == "-std=c90" || argv[i] == "-std=iso9899:1990" || argv[i] == "-std=iso9899:199409" ) { set_C90_only(); if ( argv[i] == "-std=iso9899:199409" ) { printf ( "WARNING: Requested standard ISO C90 as modified in amendment 1. ROSE will pass -std=c90 to the backend.\n" ); } } else if ( argv[i] == "-std=gnu90" ) { set_C90_gnu_only(); } else if ( argv[i] == "-std=c99" || argv[i] == "-std=c9x" || argv[i] == "-std=iso9899:1999" || argv[i] == "-std=iso9899:199x" ) { set_C99_only(); } else if ( argv[i] == "-std=gnu99" || argv[i] == "-std=gnu9x" ) { set_C99_gnu_only(); } else if ( argv[i] == "-std=c11" || argv[i] == "-std=c1x" || argv[i] == "-std=iso9899:2011" ) { set_C11_only(); } else if ( argv[i] == "-std=gnu11" || argv[i] == "-std=gnu1x" ) { set_C11_gnu_only(); } else if ( argv[i] == "-std=c17" || argv[i] == "-std=c18" || argv[i] == "-std=iso9899:2017" || argv[i] == "-std=iso9899:2018" ) { set_C14_only(); } else if ( argv[i] == "-std=gnu17" || argv[i] == "-std=gnu18" ) { set_C14_gnu_only(); } else if ( argv[i] == "-std=c++98" ) { set_Cxx98_only(); } else if ( argv[i] == "-std=gnu++98" ) { set_Cxx98_gnu_only(); } else if ( argv[i] == "-std=c++03" ) { set_Cxx03_only(); } else if ( argv[i] == "-std=gnu++03" ) { set_Cxx03_gnu_only(); } else if ( argv[i] == "-std=c++11" || argv[i] == "-std=c++0x" ) { set_Cxx11_only(); } else if ( argv[i] == "-std=gnu++11" || argv[i] == "-std=gnu++0x" ) { set_Cxx11_gnu_only(); } else if ( argv[i] == "-std=c++14" || argv[i] == "-std=c++1y" ) { set_Cxx14_only(); } else if ( argv[i] == "-std=gnu++14" || argv[i] == "-std=gnu++1y" ) { set_Cxx14_gnu_only(); } else if ( argv[i] == "-std=c++17" || argv[i] == "-std=c++1z" ) { set_Cxx17_only(); } else if ( argv[i] == "-std=gnu++17" || argv[i] == "-std=gnu++1z" ) { set_Cxx17_gnu_only(); } else if ( argv[i] == "-std=c++20" || argv[i] == "-std=c++2a" ) { set_Cxx20_only(); } else if ( argv[i] == "-std=gnu++20" || argv[i] == "-std=gnu++2a" ) { set_Cxx20_gnu_only(); } else if ( argv[i] == "-std=f77" ) { set_F77_only(); } else if ( argv[i] == "-std=f90" ) { set_F90_only(); } else if ( argv[i] == "-std=f95" ) { set_F95_only(); } else if ( argv[i] == "-std=f2003" ) { set_F2003_only(); } else if ( argv[i] == "-std=f2008" ) { set_F2008_only(); // DQ (1/25/2016): We might want to skip the syntax checking. set_skip_syntax_check(true); } else if ( argv[i] == "-std=f2018" || argv[i] == "-std=f2008ts" ) { set_F2018_only(); } } // Matching selected dialect with file extension switch (get_standard()) { case e_default_standard: { if (get_Fortran_only() && get_sourceFileUsesFortranFileExtension() == false) { printf ("WARNING: Non Fortran source file name specificed with explicit -rose:Fortran Fortran language option! \n"); set_Fortran_only(false); } if (get_C_only() && get_sourceFileUsesCppFileExtension() == false) { printf ("WARNING: C++ source file name specificed with explicit selection of a C dialect (-rose:C or -std=c)\n"); set_C_only(false); set_Cxx_only(true); set_default_standard(); } break; } case e_c89_standard: case e_c90_standard: case e_c99_standard: case e_c11_standard: case e_c14_standard: case e_c18_standard: { if (get_sourceFileUsesCppFileExtension() == true) { printf ("WARNING: C++ source file name specificed with explicit selection of a C dialect (-rose:C or -std=c)\n"); set_C_only(false); set_Cxx_only(true); set_default_standard(); } break; } case e_upc_standard: { break; // TODO } case e_cxx98_standard: case e_cxx03_standard: case e_cxx11_standard: case e_cxx14_standard: case e_cxx17_standard: case e_cxx20_standard: { break; // NOP } case e_upcxx_standard: { break; // TODO } case e_f77_standard: { if (get_sourceFileUsesFortran77FileExtension() == false) { printf ("WARNING: Non Fortran77 source file name specificed with explicit -rose:Fortran77 Fortran 77 language option! \n"); set_default_standard(); } break; } case e_f90_standard: { if (get_sourceFileUsesFortran90FileExtension() == false) { printf ("WARNING: Non Fortran90 source file name specificed with explicit -rose:Fortran90 Fortran 90 language option! \n"); set_default_standard(); } break; } case e_f95_standard: { if (get_sourceFileUsesFortran95FileExtension() == false) { printf ("WARNING: Non Fortran95 source file name specificed with explicit -rose:Fortran95 Fortran 95 language option! \n"); set_default_standard(); } break; } case e_f03_standard: { if (get_sourceFileUsesFortran2003FileExtension() == false && get_sourceFileUsesCoArrayFortranFileExtension() == false) { printf ("WARNING: Non Fortran2003 source file name specificed with explicit -rose:Fortran2003 Fortran 2003 language option! \n"); set_default_standard(); } if (get_CoArrayFortran_only() == true && get_sourceFileUsesCoArrayFortranFileExtension() == false) { printf ("WARNING: Non Co-Array Fortran source file name specificed with explicit -rose:CoArrayFortran language option! \n"); set_CoArrayFortran_only(false); } break; } case e_f08_standard: { if (get_sourceFileUsesFortran2008FileExtension() == false) { printf ("WARNING: Non Fortran2008 source file name specificed with explicit -rose:Fortran2008 Fortran 2008 language option! \n"); set_default_standard(); } break; } case e_f18_standard: { #if 0 if (get_sourceFileUsesFortran2018FileExtension() == false) { printf ("Warning, Non Fortran2018 source file name specificed with explicit -rose:Fortran2018 Fortran 2018 language option! \n"); set_default_standard(); } #endif break; } } if ( get_standard() == e_default_standard ) { // TV (11/16/2018): ROSE-1530: Figure out the default standard for each backend compiler (including version) // GNU : TODO ??? // INTEL: https://software.intel.com/en-us/cpp-compiler-developer-guide-and-reference-conformance-to-the-c-c-standards // CLANG: https://clang.llvm.org/compatibility.html if (get_C_only()) { #if defined(BACKEND_CXX_IS_GNU_COMPILER) // TODO ?? #elif defined(BACKEND_CXX_IS_INTEL_COMPILER) set_C99_only(); #elif defined(BACKEND_CXX_IS_CLANG_COMPILER) set_C11_only(); #endif } else if (get_Cxx_only()) { #if defined(BACKEND_CXX_IS_GNU_COMPILER) // TODO ?? #elif defined(BACKEND_CXX_IS_INTEL_COMPILER) set_Cxx11_only(); #elif defined(BACKEND_CXX_IS_CLANG_COMPILER) set_Cxx11_only(); #endif } else if (get_Fortran_only()) { set_F2003_only(); } } if ( SgProject::get_verbose() >= 1 ) { switch (get_standard()) { case e_default_standard: break; // NOP case e_c89_standard: { printf ("C89 mode ON \n"); break; } case e_c90_standard: { printf ("C90 mode ON \n"); break; } case e_c99_standard: { printf ("C99 mode ON \n"); break; } case e_c11_standard: { printf ("C11 mode ON \n"); break; } case e_c14_standard: { printf ("C14 mode ON \n"); break; } case e_c18_standard: { printf ("C18 mode ON \n"); break; } case e_upc_standard: { printf ("UPC mode ON \n"); break; } case e_cxx98_standard: { printf ("C++98 mode ON \n"); break; } case e_cxx03_standard: { printf ("C++03 mode ON \n"); break; } case e_cxx11_standard: { printf ("C++11 mode ON \n"); break; } case e_cxx14_standard: { printf ("C++14 mode ON \n"); break; } case e_cxx17_standard: { printf ("C++17 mode ON \n"); break; } case e_cxx20_standard: { printf ("C++20 mode ON \n"); break; } case e_upcxx_standard: { printf ("UPCxx mode ON \n"); break; } case e_f77_standard: { printf ("Fortran77 mode ON \n"); break; } case e_f90_standard: { printf ("Fortran90 mode ON \n"); break; } case e_f95_standard: { printf ("Fortran95 mode ON \n"); break; } case e_f03_standard: { printf ("Fortran2003 mode ON \n"); break; } case e_f08_standard: { printf ("Fortran2008 mode ON \n"); break; } case e_f18_standard: { printf ("Fortran2018 mode ON \n"); break; } } if (is_gnu_standard()) { printf ("GNU compatibility mode ON \n"); } } // UPC: remove edg:restrict since we will add it back in SgFile::build_EDG_CommandLine() if (get_UPC_only() || get_UPCxx_only()) { CommandlineProcessing::isOption(argv,"-edg:","(restrict)",true); CommandlineProcessing::isOption(argv,"--edg:","(restrict)",true); } // END parsing standard specifications for C/C++/Fortran (ROSE-1529) //////////////////////////////////////////////////////////////////////// // two situations: either of -rose:upc_threads n and --edg:upc_threads n appears. // set flags and remove both. int integerOptionForUPCThreads = 0; int integerOptionForUPCThreads2 = 0; bool hasRoseUpcThreads = CommandlineProcessing::isOptionWithParameter(argv,"-rose:","(upc_threads)", integerOptionForUPCThreads,true); bool hasEDGUpcThreads = CommandlineProcessing::isOptionWithParameter(argv,"--edg:","(upc_threads)", integerOptionForUPCThreads2,true); integerOptionForUPCThreads = (integerOptionForUPCThreads != 0) ? integerOptionForUPCThreads : integerOptionForUPCThreads2; if (hasRoseUpcThreads||hasEDGUpcThreads) { // set ROSE SgFile::upc_threads value, done for ROSE set_upc_threads(integerOptionForUPCThreads); if ( SgProject::get_verbose() >= 1 ) printf ("upc_threads is set to %d\n",integerOptionForUPCThreads); } #if 0 printf ("After part 2 detection of Intel compiler: get_C_only() = %s \n",get_C_only() ? "true" : "false"); printf ("After part 2 detection of Intel compiler: get_Cxx_only() = %s \n",get_Cxx_only() ? "true" : "false"); #endif #if 0 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif // DQ (2/5/2009): We now have one at the SgProject and the SgFile levels. // DQ (2/4/2009): Moved to SgProject. // DQ (12/27/2007): Allow defaults to be set based on filename extension. if ( CommandlineProcessing::isOption(argv,"-rose:","(binary|binary_only)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Binary mode ON \n"); set_binary_only(true); if (get_sourceFileUsesBinaryFileExtension() == false) { printf ("Warning, Non binary file name specificed with explicit -rose:binary option! \n"); set_binary_only(false); } } // DQ (10/11/2010): Adding initial Java support. if ( CommandlineProcessing::isOption(argv,"-rose:","(j|J|Java)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Java mode ON \n"); set_Java_only(true); if (get_sourceFileUsesJavaFileExtension() == false) { printf ("Warning, Non Java source file name specified with explicit -rose:Java Java language option! \n"); set_Java_only(false); // DQ (4/2/2011): Java code is only compiled, not linked as is C/C++ and Fortran. set_compileOnly(true); } } // driscoll6 (8/8/11): python support if ( CommandlineProcessing::isOption(argv,"-rose:","(py|python|Python)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Python mode ON \n"); set_Python_only(true); if (get_sourceFileUsesPythonFileExtension() == false) { printf ("Warning, Non Python source file name specificed with explicit -rose:python Python language option! \n"); set_Python_only(false); } } // DQ (28/8/17): Csharp support if ( CommandlineProcessing::isOption(argv,"-rose:","(cs|csharp|Csharp)",true) == true ) { if ( SgProject::get_verbose() >= 0 ) printf ("Csharp mode ON \n"); set_Csharp_only(true); if (get_sourceFileUsesCsharpFileExtension() == false) { printf ("Warning, Non Csharp source file name specificed with explicit -rose:csharp Csharp language option! \n"); set_Csharp_only(false); } // DQ (30/8/2017): For Csharp we need to only compile and not link (as best I understand csharp presently). printf ("NOTE: For Csharp support disable link step, since it is not a part of the languages the way it is with C/C++ (calling set_compileOnly(true)). \n"); set_compileOnly(true); ROSE_ASSERT(get_compileOnly() == true); } // DQ (28/8/17): Ada support if ( CommandlineProcessing::isOption(argv,"-rose:","(ada|Ada)",true) == true ) { if ( SgProject::get_verbose() >= 0 ) printf ("Ada mode ON \n"); set_Ada_only(true); if (get_sourceFileUsesAdaFileExtension() == false) { printf ("Warning, Non Ada source file name specificed with explicit -rose:ada Ada language option! \n"); set_Ada_only(false); } // DQ (30/8/2017): For Ada we need to only compile and not link (at least while debugging initial support). printf ("NOTE: For Ada support disable link step, at least while debugging initial support \n"); set_compileOnly(true); ROSE_ASSERT(get_compileOnly() == true); } // DQ (28/8/17): Jovial support if ( CommandlineProcessing::isOption(argv,"-rose:","(jovial|Jovial)",true) == true ) { if ( SgProject::get_verbose() >= 0 ) printf ("Jovial mode ON \n"); set_Jovial_only(true); if (get_sourceFileUsesJovialFileExtension() == false) { printf ("Warning, Non Jovial source file name specificed with explicit -rose:jovial Jovial language option! \n"); set_Jovial_only(false); } // DQ (30/8/2017): For Jovial we need to only compile and not link (at least while debugging initial support). printf ("NOTE: For Jovial support disable link step, at least while debugging initial support \n"); set_compileOnly(true); ROSE_ASSERT(get_compileOnly() == true); } // DQ (28/8/17): Cobol support if ( CommandlineProcessing::isOption(argv,"-rose:","(cobol|Cobol)",true) == true ) { if ( SgProject::get_verbose() >= 0 ) printf ("Cobol mode ON \n"); set_Cobol_only(true); if (get_sourceFileUsesCobolFileExtension() == false) { printf ("Warning, Non Cobol source file name specificed with explicit -rose:cobol Cobol language option! \n"); set_Cobol_only(false); } // DQ (30/8/2017): For Cobol we need to only compile and not link (at least while debugging initial support). printf ("NOTE: For Cobol support disable link step, at least while debugging initial support \n"); set_compileOnly(true); ROSE_ASSERT(get_compileOnly() == true); } // Fixed format v.s. free format option handling (ROSE defaults to fix or free format, depending on the file extension). // F77 default is fixed format, F90 and later default is free format. // Fortran source file format options for different compilers(for IBM/XL,Intel,Portland,GNU): // IBM/XL Intel Portland GNU // -qfixed -fixed -Mfixed -ffixed-form // -qfree -free -Mfree -free-form // GNU gfortran also supports -fno-fixed-form (we could use this to turn off all fixed form // formatting independent of the input source). // DQ (12/10/2007): Set the defaul value depending on the version of fortran being used. if (get_F77_only() == true) { // For F77 and older versions of Fortran assume fixed format. // set_fixedFormat(true); // set_freeFormat (false); // Use the setting get_F77_only() == true as a default means to set this value set_inputFormat(SgFile::e_fixed_form_output_format); set_outputFormat(SgFile::e_fixed_form_output_format); set_backendCompileFormat(SgFile::e_fixed_form_output_format); } else { // For F90 and later versions of Fortran assume free format. // set_fixedFormat(false); // set_freeFormat (true); // Use the setting get_F77_only() == true as a default means to set this value set_inputFormat(SgFile::e_free_form_output_format); set_outputFormat(SgFile::e_free_form_output_format); set_backendCompileFormat(SgFile::e_free_form_output_format); } // Make sure that only one is true // ROSE_ASSERT (get_freeFormat() == false || get_fixedFormat() == false); // ROSE_ASSERT (get_freeFormat() == true || get_fixedFormat() == true); // set_fixedFormat(false); // ROSE_ASSERT (get_fixedFormat() == false); if ( CommandlineProcessing::isOption(argv,"-","(ffixed-form|fixed|Mfixed|qfixed)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Fortran fixed format mode explicitly set: ON \n"); // set_fixedFormat(true); set_inputFormat(SgFile::e_fixed_form_output_format); if (get_sourceFileUsesFortranFileExtension() == false) { printf ("Error, Non Fortran source file name specificed with explicit fixed format code generation (unparser) option! \n"); // set_fixedFormat(false); ROSE_ASSERT(false); } } // set_freeFormat(false); // ROSE_ASSERT (get_freeFormat() == false); if ( CommandlineProcessing::isOption(argv,"-","(ffree-form|free|Mfree|qfree)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Fortran free format mode explicitly set: ON \n"); // set_freeFormat(true); set_inputFormat(SgFile::e_free_form_output_format); if (get_sourceFileUsesFortranFileExtension() == false) { printf ("Error, Non Fortran source file name specificed with explicit free format code generation (unparser) option! \n"); // set_freeFormat(false); ROSE_ASSERT(false); } } // DQ (8/19/2007): This option only controls the output format (unparsing) of Fortran code (free or fixed format). // It has no effect on C/C++ code generation (unparsing). // printf ("########################### Setting the outputFormat ########################### \n"); // DQ (12/27/2007) These have been assigned default values based on the filename suffix, we only want to override // them if the commandline options are explicitly specified. // set_outputFormat(SgFile::e_unknown_output_format); // ROSE_ASSERT (get_outputFormat() == SgFile::e_unknown_output_format); if ( CommandlineProcessing::isOption(argv,"-rose:","(fixedOutput|fixedFormatOutput)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Fortran fixed format output specified \n"); set_outputFormat(SgFile::e_fixed_form_output_format); if (get_sourceFileUsesFortranFileExtension() == false) { printf ("Warning, Non Fortran source file name specificed with code generation option: free format! \n"); ROSE_ASSERT(false); } } if ( CommandlineProcessing::isOption(argv,"-rose:","(freeOutput|freeFormatOutput)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Fortran free format mode explicitly set: ON \n"); set_outputFormat(SgFile::e_free_form_output_format); if (get_sourceFileUsesFortranFileExtension() == false) { printf ("Warning, Non Fortran source file name specificed with code generation option: fixed format! \n"); ROSE_ASSERT(false); } } // DQ (8/19/2007): This option only controls the output format (unparsing) of Fortran code (free or fixed format). // It has no effect on C/C++ code generation (unparsing). // printf ("########################### Setting the backendCompileFormat ########################### \n"); // DQ (12/27/2007) These have been assigned default values based on the filename suffix, we only want to override // them if the commandline options are explicitly specified. // set_backendCompileFormat(SgFile::e_unknown_output_format); // ROSE_ASSERT (get_backendCompileFormat() == SgFile::e_unknown_output_format); if ( CommandlineProcessing::isOption(argv,"-rose:","(compileFixed|backendCompileFixedFormat)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Fortran fixed format output specified \n"); set_backendCompileFormat(SgFile::e_fixed_form_output_format); if (get_sourceFileUsesFortranFileExtension() == false) { printf ("Warning, Non Fortran source file name specificed with code generation option: free format! \n"); ROSE_ASSERT(false); } } if ( CommandlineProcessing::isOption(argv,"-rose:","(compileFree|backendCompileFreeFormat)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Fortran free format mode explicitly set: ON \n"); set_backendCompileFormat(SgFile::e_free_form_output_format); if (get_sourceFileUsesFortranFileExtension() == false) { printf ("Warning, Non Fortran source file name specificed with code generation option: fixed format! \n"); ROSE_ASSERT(false); } } set_fortran_implicit_none(false); ROSE_ASSERT (get_fortran_implicit_none() == false); if ( CommandlineProcessing::isOption(argv,"-","fimplicit_none",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Fortran free format mode explicitly set: ON \n"); set_fortran_implicit_none(true); if (get_sourceFileUsesFortranFileExtension() == false) { printf ("Warning, Non Fortran source file name specificed with explicit free format code generation (unparser) option! \n"); set_fortran_implicit_none(false); } } // Liao 10/28/2008: I changed it to a more generic flag to indicate support for either Fortran or C/C++ // DQ (8/19/2007): I have added the option here so that we can start to support OpenMP for Fortran. // Allows handling of OpenMP "!$omp" directives in free form and "c$omp", *$omp and "!$omp" directives in fixed form, enables "!$" conditional // compilation sentinels in free form and "c$", "*$" and "!$" sentinels in fixed form and when linking arranges for the OpenMP runtime library // to be linked in. (Not implemented yet). set_openmp(false); //string ompmacro="-D_OPENMP="+ boost::to_string(OMPVERSION); // Mac OS complains this function does not exist! string ompmacro="-D_OPENMP="+ StringUtility::numberToString(OMPVERSION); ROSE_ASSERT (get_openmp() == false); // We parse OpenMP and then stop now since Building OpenMP AST nodes is a work in progress. // so the default behavior is to turn on them all // TODO turn them to false when parsing-> AST creation -> translation are finished ROSE_ASSERT (get_openmp_parse_only() == true); ROSE_ASSERT (get_openmp_ast_only() == false); ROSE_ASSERT (get_openmp_lowering() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(OpenMP|openmp)",true) == true ||CommandlineProcessing::isOption(argv,"-","(openmp|fopenmp)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("OpenMP option specified \n"); set_openmp(true); /* if (get_sourceFileUsesFortranFileExtension() == false) { printf ("Warning, Non Fortran source file name specified with explicit OpenMP option! \n"); set_fortran_openmp(false); } */ //side effect for enabling OpenMP, define the macro as required //This new option does not reach the backend compiler //But it is enough to reach EDG only. //We can later on back end option to turn on their OpenMP handling flags, //like -fopenmp for GCC, depending on the version of gcc //which will define this macro for GCC argv.push_back(ompmacro); } // Process sub-options for OpenMP handling, Liao 5/31/2009 // We want to turn on OpenMP if any of its suboptions is used. Liao , 8/11/2009 if ( CommandlineProcessing::isOption(argv,"-rose:OpenMP:","parse_only",true) == true ||CommandlineProcessing::isOption(argv,"-rose:openmp:","parse_only",true) == true ||CommandlineProcessing::isOption(argv,"--rose:openmp:","parse_only",true) == true ||CommandlineProcessing::isOption(argv,"--rose:OpenMP:","parse_only",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("OpenMP sub option for parsing specified \n"); set_openmp_parse_only(true); // turn on OpenMP if not set explicitly by standalone -rose:OpenMP if (!get_openmp()) { set_openmp(true); argv.push_back(ompmacro); } } if ( CommandlineProcessing::isOption(argv,"-rose:OpenMP:","ast_only",true) == true ||CommandlineProcessing::isOption(argv,"-rose:openmp:","ast_only",true) == true ||CommandlineProcessing::isOption(argv,"--rose:openmp:","ast_only",true) == true ||CommandlineProcessing::isOption(argv,"--rose:OpenMP:","ast_only",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("OpenMP option for AST construction specified \n"); set_openmp_ast_only(true); // we don't want to stop after parsing if we want to proceed to ast creation before stopping set_openmp_parse_only(false); // turn on OpenMP if not set explicitly by standalone -rose:OpenMP if (!get_openmp()) { set_openmp(true); argv.push_back(ompmacro); } } if ( CommandlineProcessing::isOption(argv,"-rose:OpenMP:","lowering",true) == true ||CommandlineProcessing::isOption(argv,"-rose:openmp:","lowering",true) == true ||CommandlineProcessing::isOption(argv,"--rose:openmp:","lowering",true) == true ||CommandlineProcessing::isOption(argv,"--rose:OpenMP:","lowering",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("OpenMP sub option for AST lowering specified \n"); set_openmp_lowering(true); // we don't want to stop after parsing or ast construction set_openmp_parse_only(false); set_openmp_ast_only(false); // turn on OpenMP if not set explicitly by standalone -rose:OpenMP if (!get_openmp()) { set_openmp(true); argv.push_back(ompmacro); } } // Liao, 1/30/2014 // recognize -rose:failsafe option to turn on handling of failsafe directives for resilience work set_failsafe(false); ROSE_ASSERT (get_failsafe() == false); if ( CommandlineProcessing::isOption(argv,"-rose:","(FailSafe|failsafe)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("FailSafe option specified \n"); set_failsafe(true); //side effect for enabling failsafe, define the macro as required // argv.push_back("-D_FAILSAFE"); } // // strict ANSI/ISO mode option // // set_strict_language_handling(false); if ( CommandlineProcessing::isOption(argv,"-rose:","(strict)",true) == true ) { // Optionally specify strict language handling set_strict_language_handling(true); } // // specify output file option // // DQ (10/15/2005): There is a valid default value here, but we want to overwrite it! std::string stringParameter; if ( CommandlineProcessing::isOptionWithParameter(argv,"-rose:","(o|output)",stringParameter,true) == true ) { // printf ("-rose:output %s \n",stringParameter.c_str()); if (get_unparse_output_filename().empty() == false) { printf ("Overwriting value in get_unparse_output_filename() = %s \n",get_unparse_output_filename().c_str()); } // DQ (10/15/2005): This is so much simpler! p_unparse_output_filename = stringParameter; } // // skip_translation_from_edg_ast_to_rose_ast option: This variable is checked in the EDG frontend (4.3) // and if set it will cause the translation from the EDG AST to the ROSE AST to be skipped. A valid // SgProject and/or SgFile with with SgGlobal (empty) will be built (as I recall). // if ( CommandlineProcessing::isOption(argv,"-rose:","(skip_translation_from_edg_ast_to_rose_ast)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("option -rose:skip_translation_from_edg_ast_to_rose_ast found \n"); set_skip_translation_from_edg_ast_to_rose_ast(true); } // // skip_transformation option: if transformations of the AST check this variable then the // resulting translators can skip the transformatios via this command-line specified option. // if ( CommandlineProcessing::isOption(argv,"-rose:","(skip_transformation)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("option -rose:skip_transformation found \n"); set_skip_transformation(true); } // // skip_unparse option: if analysis only (without transformatio is required, then this can significantly // improve the performance since it will also skip the backend compilation, as I recall) // if ( CommandlineProcessing::isOption(argv,"-rose:","(skip_unparse)",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("option -rose:skip_unparse found \n"); set_skip_unparse(true); } // unparser language option // DQ (8/27/2007): This option controls the output language (which language unparser is to be used). // This allows the code generation of one language to be tested using input of another langauge. It is // mostly a mechanism to test the unparser in the early stages of their development. Unshared language // constructs are not supported and would have the be translated. This step does none of this sort of // translation, which might be difficult debendingon the input and output languages selected. // Supported options are: // e_default_output_language // e_C_output_language // e_Cxx_output_language // e_Fortran_output_language // e_Promela_output_language // set_outputLanguage(SgFile::e_default_output_language); // ROSE_ASSERT (get_outputLanguage() == SgFile::e_default_output_language); if ( CommandlineProcessing::isOption(argv,"-rose:","C_output_language",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Use the C language code generator (unparser) \n"); set_outputLanguage(SgFile::e_C_language); } if ( CommandlineProcessing::isOption(argv,"-rose:","Cxx_output_language",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Use the C++ language code generator (unparser) \n"); set_outputLanguage(SgFile::e_Cxx_language); } if ( CommandlineProcessing::isOption(argv,"-rose:","Fortran_output_language",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Use the Fortran language code generator (unparser) \n"); set_outputLanguage(SgFile::e_Fortran_language); } if ( CommandlineProcessing::isOption(argv,"-rose:","Promela_output_language",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Use the Promela language code generator (unparser) \n"); set_outputLanguage(SgFile::e_Promela_language); } if ( CommandlineProcessing::isOption(argv,"-rose:","PHP_output_language",true) == true ) { if ( SgProject::get_verbose() >= 1 ) printf ("Use the PHP language code generator (unparser) \n"); set_outputLanguage(SgFile::e_PHP_language); } #if 0 // DQ (29/8/2017): Add a note to fix this. printf ("In cmdline.cpp: Need to add support for other languages here! \n"); #endif // // unparse_includes option // if ( CommandlineProcessing::isOption(argv,"-rose:","(unparse_includes)",true) == true ) { // printf ("option -rose:unparse_includes found \n"); set_unparse_includes(true); } // // unparse_line_directives option (added 12/4/2007). // if ( CommandlineProcessing::isOption(argv,"-rose:","(unparse_line_directives)",true) == true ) { // printf ("option -rose:unparse_line_directives found \n"); set_unparse_line_directives(true); } // // unparse_function_calls_using_operator_syntax option (added 4/14/2013). // if ( CommandlineProcessing::isOption(argv,"-rose:","(unparse_function_calls_using_operator_syntax)",true) == true ) { printf ("option -rose:unparse_function_calls_using_operator_syntax found \n"); set_unparse_function_calls_using_operator_syntax(true); } // // unparse_function_calls_using_operator_names option (added 4/14/2013). // if ( CommandlineProcessing::isOption(argv,"-rose:","(unparse_function_calls_using_operator_names)",true) == true ) { printf ("option -rose:unparse_function_calls_using_operator_names found \n"); set_unparse_function_calls_using_operator_names(true); } // // unparse_instruction_addresses option (added 8/30/2008). // if ( CommandlineProcessing::isOption(argv,"-rose:","(unparse_instruction_addresses)",true) == true ) { // printf ("option -rose:unparse_instruction_addresses found \n"); set_unparse_instruction_addresses(true); } // // unparse_raw_memory_contents option (added 8/30/2008). // if ( CommandlineProcessing::isOption(argv,"-rose:","(unparse_raw_memory_contents)",true) == true ) { // printf ("option -rose:unparse_raw_memory_contents found \n"); set_unparse_raw_memory_contents(true); } // // unparse_binary_file_format option (added 8/30/2008). // if ( CommandlineProcessing::isOption(argv,"-rose:","(unparse_binary_file_format)",true) == true ) { // printf ("option -rose:unparse_binary_file_format found \n"); set_unparse_binary_file_format(true); } // // collectAllCommentsAndDirectives option: operates across all files (include files) and significantly slows the compilation. // if ( CommandlineProcessing::isOption(argv,"-rose:","(collectAllCommentsAndDirectives)",true) == true ) { // printf ("option -rose:collectAllCommentsAndDirectives found \n"); set_collectAllCommentsAndDirectives(true); } // negara1 (07/08/2011): Made unparsing of header files optional. if ( CommandlineProcessing::isOption(argv,"-rose:","(unparseHeaderFiles)",true) == true ) { set_unparseHeaderFiles(true); //To support header files unparsing, it is always needed to collect all directives. set_collectAllCommentsAndDirectives(true); } // negara1 (08/16/2011): A user may optionally specify the root folder for the unparsed header files. if (CommandlineProcessing::isOptionWithParameter(argv, "-rose:", "(unparseHeaderFilesRootFolder)", stringParameter, true) == true) { // Although it is specified per file, it should be the same for the whole project. get_project()->set_unparseHeaderFilesRootFolder(stringParameter); } // DQ (11/6/2018): Added to support a specification of the application directory for source file and header file unparsing. if (CommandlineProcessing::isOptionWithParameter(argv, "-rose:", "(applicationRootDirectory)", stringParameter, true) == true) { // Although it is specified per file, it should be the same for the whole project. #if 0 printf ("Found option: -rose:applicationRootDirectory: stringParameter = %s \n",stringParameter.c_str()); #endif get_project()->set_applicationRootDirectory(stringParameter); get_project()->set_usingApplicationRootDirectory(true); } // // skip_commentsAndDirectives option: if analysis that does not use comments or CPP directives is required // then this option can improve the performance of the compilation. // if ( CommandlineProcessing::isOption(argv,"-rose:","(skip_commentsAndDirectives)",true) == true ) { // printf ("option -rose:skip_commentsAndDirectives found \n"); set_skip_commentsAndDirectives(true); // If we are skipping comments then we should not be collecting all comments (does not make sense) ROSE_ASSERT(get_collectAllCommentsAndDirectives() == false); // set_collectAllCommentsAndDirectives(false); } // DQ (3/24/2019): Adding support to translate comments and CPP directives into explicit IR nodes in the AST. // This can simplify how transformations are done when intended to be a part of the token-baed unparsing. // // This translateCommentsAndDirectivesIntoAST option: When using the token based unparsing, and soemtime even // if not, a greater degree of precisison in the unparsing is possible if new directives can be positioned into // the AST with more precission relative to other directives that are already present. This option adds the // comments and CPP directives as explicit IR nodes in each scope where they can be added as such. // This also has the advantage of making them more trivially availalbe in the analysis as well. // This is however, not the default in ROSE, and it an experimental option that may be adopted more // formally later if it can be demonstraed to be robust. // if ( CommandlineProcessing::isOption(argv,"-rose:","(translateCommentsAndDirectivesIntoAST)",true) == true ) { printf ("option -rose:translateCommentsAndDirectivesIntoAST found \n"); set_translateCommentsAndDirectivesIntoAST(true); } // DQ (8/16/2008): parse binary executable file format only (some uses of ROSE may only do analysis of // the binary executable file format and not the instructions). This is also useful for testing. if ( CommandlineProcessing::isOption(argv,"-rose:","(read_executable_file_format_only)",true) == true ) { // printf ("option -rose:read_executable_file_format_only found \n"); set_read_executable_file_format_only(true); } // DQ (11/11/2008): parse binary executable file format only and add attributes to the symbols so that // they will not be output in the generation of DOT files. They will still be present for all other // forms of analysis. if ( CommandlineProcessing::isOption(argv,"-rose:","(visualize_executable_file_format_skip_symbols)",true) == true ) { // printf ("option -rose:visualize_executable_file_format_skip_symbols found \n"); set_visualize_executable_file_format_skip_symbols(true); } // DQ (11/11/2008): parse binary executable file format only and add attributes to the symbols and most // other binary file format IR nodes so that they will not be output in the generation of DOT files. // They will still be present for all other forms of analysis. if ( CommandlineProcessing::isOption(argv,"-rose:","(visualize_dwarf_only)",true) == true ) { // printf ("option -rose:visualize_dwarf_only found \n"); set_visualize_dwarf_only(true); } // DQ (1/10/2009): The C language ASM statements are providing significant trouble, they are // frequently machine specific and we are compiling then on architectures for which they were // not designed. This option allows then to be read, constructed in the AST to support analysis // but not unparsed in the code given to the backend compiler, since this can fail. (See // test2007_20.C from Linux Kernel for an example). if ( CommandlineProcessing::isOption(argv,"-rose:","(skip_unparse_asm_commands)",true) == true ) { // printf ("option -rose:skip_unparse_asm_commands found \n"); set_skip_unparse_asm_commands(true); } // DQ (6/7/2013): Added support for alternatively calling the experimental fortran frontend. set_experimental_fortran_frontend(false); if ( CommandlineProcessing::isOption(argv,"-rose:","experimental_fortran_frontend",true) == true ) { if ( SgProject::get_verbose() >= 0 ) printf ("Using experimental fortran frontend (explicitly set: ON) \n"); set_experimental_fortran_frontend(true); } // Added support the experimental fortran frontend using the Flang parser [Rasmussen 2019.08.30] if ( CommandlineProcessing::isOption(argv,"-rose:","experimental_flang_frontend",true) == true ) { if ( SgProject::get_verbose() >= 0 ) { printf ("also: experimental Flang frontend (explicitly set: ON) \n"); } set_experimental_flang_frontend(true); } // Rasmussen (3/12/2018): Added support for CUDA Fortran within the experimental fortran frontend. if ( CommandlineProcessing::isOption(argv,"-rose:","experimental_cuda_fortran_frontend",true) == true ) { if ( SgProject::get_verbose() >= 0 ) { printf ("Using experimental CUDA fortran frontend (explicitly set: ON) \n"); printf ("also: experimental fortran frontend (explicitly set: ON) \n"); } set_experimental_fortran_frontend(true); set_experimental_cuda_fortran_frontend(true); } // DQ (1/23/2016): Added support for OFP parsing and pretty printing of generated Aterm // (this is part of the internal testing of the new (experimental) Fortran support). set_experimental_fortran_frontend_OFP_test(false); if ( CommandlineProcessing::isOption(argv,"-rose:","experimental_fortran_frontend_OFP_test",true) == true ) { if ( SgProject::get_verbose() >= 0 ) printf ("Using experimental fortran frontend_OFP_test (explicitly set: ON) \n"); set_experimental_fortran_frontend_OFP_test(true); } // DQ (1/25/2016): we want to enforce that we only use F08 with the new experimental mode. if (get_experimental_fortran_frontend() == false && get_experimental_flang_frontend() == false) { // We only want to allow Fortran 2008 mode to work with the new experimental fortran frontend. if (get_F2008_only() == true) { printf ("ERROR: Fortran 2008 mode is only supported with the -rose:experimental_fortran_frontend option \n"); exit(1); // ROSE_ASSERT(false); } } // DQ (9/26/2011): Adding options to support internal debugging of ROSE based tools and language support. // **************** // DEBUGING SUPPORT // **************** // // Support for detecting dangling pointers // This is the first level of this sort of support. This level will be fooled by any reuse of // the memory (from new allocations) previously deleted. A later leve of this option will disable // reuse of previously deleted memory for IR nodes; but it will consume more memory for translators // that delete a lot of IR nodes as part of there functionality. I expect this to only seriously // make a difference for the AST merge operations which allocate and delete large parts of ASTs // frequently. // Note: this detects only dangling pointers to ROSE IR nodes, nothing more. // #if 0 // Test ROSE using default level 2 (error that will cause assertion) when not specified via the command line. set_detect_dangling_pointers(2); #endif int integerDebugOption = 0; if ( CommandlineProcessing::isOptionWithParameter(argv,"-rose:","detect_dangling_pointers",integerDebugOption,true) == true ) { // If this was set and a parameter was not specified or the value set to zero, then let the value be 1. // I can't seem to detect if the option was specified without a parameter. if (integerDebugOption == 0) { integerDebugOption = 1; if ( SgProject::get_verbose() >= 1 ) printf ("option -rose:detect_dangling_pointers found but value not specified or set to 0 default (reset integerDebugOption = %d) \n",integerDebugOption); } else { if ( SgProject::get_verbose() >= 1 ) printf ("option -rose:detect_dangling_pointers found with level (integerDebugOption = %d) \n",integerDebugOption); } // Set the level of the debugging to support. set_detect_dangling_pointers(integerDebugOption); } // // skipAstConsistancyTests option (added 2/17/2013). // // DQ (2/17/2013): This option allows performance evaluations using HPCToolKit (using binary instrumentation) // to be focusd on the AST construction phase and not the AST consistancy test phase (which can be about 30% // of the performance of ROSE for large files). if ( CommandlineProcessing::isOption(argv,"-rose:","(skipAstConsistancyTests)",true) == true ) { // printf ("option -rose:skipAstConsistancyTests found \n"); set_skipAstConsistancyTests(true); } // // internal testing option (for internal use only, these may disappear at some point) // int integerOption = 0; if ( CommandlineProcessing::isOptionWithParameter(argv,"-rose:","test",integerOption,true) == true ) { // printf ("option -rose:test %d found \n",integerOption); p_testingLevel = integerOption; switch (integerOption) { case 0 : // transparent mode (does nothing) // p_skip_buildHigherLevelGrammars = true; p_disable_edg_backend = true; // This variable should be called frontend NOT backend??? p_skip_transformation = true; p_skip_unparse = true; p_skipfinalCompileStep = true; break; case 1 : // run the KCC front end only (can't unparse or compile output) // p_skip_buildHigherLevelGrammars = true; p_new_frontend = true; p_KCC_frontend = true; p_skip_transformation = true; p_skip_unparse = true; p_skipfinalCompileStep = true; break; case 2 : // run the newer version of EDG (compiled separately from SAGE) "edgFrontEnd" // (can't unparse or compile output) // p_skip_buildHigherLevelGrammars = true; p_new_frontend = true; p_skip_transformation = true; p_skip_unparse = true; p_skipfinalCompileStep = true; break; case 3 : // run internal (older) version of edg front end (compiled with SAGE) // p_skip_buildHigherLevelGrammars = true; p_skip_transformation = true; p_skip_unparse = true; p_skipfinalCompileStep = true; break; case 4 : // all of 3 (above) plus parse into SAGE program tree // p_skip_buildHigherLevelGrammars = true; p_skip_transformation = true; p_skip_unparse = true; p_skipfinalCompileStep = true; break; case 5 : // all of 4 (above) plus unparse to generate (untransformed source code) // p_skip_buildHigherLevelGrammars = true; p_skip_transformation = true; p_skipfinalCompileStep = true; break; case 6 : // all of 4 (above) plus compile generated source code // p_skip_buildHigherLevelGrammars = true; p_skip_transformation = true; break; case 7 : // all of 5 (above) plus parse into higher level grammars before unparsing p_skip_transformation = true; p_skipfinalCompileStep = true; break; case 8 : // all of 7 (above) plus compile resulting unparsed code (without transformations) p_skip_transformation = true; break; case 9 : // all of 8 (above) plus run transformations before unparsing (do everything) break; default: // default mode is an error printf ("Default reached in processing -rose:test # option (use 0-6, input option = %d) \n",integerOption); ROSE_ABORT(); break; } } #if 0 printf ("Exiting after test of test option! \n"); exit (0); #endif // printf ("After processing -rose:test # option argc = %d \n",argc); // // new_unparser option // if ( CommandlineProcessing::isOption(argv,"-rose:","(skipfinalCompileStep)",true) == true ) { if (get_verbose()>0) // Liao, 8/29/2008, Only show it in verbose mode. printf ("option -rose:skipfinalCompileStep found \n"); set_skipfinalCompileStep(true); } // // Standard compiler options (allows alternative -E option to just run CPP) // if ( CommandlineProcessing::isOption(argv,"-","(E)",true) == true ) { #if 0 printf ("/* In SgFile::processRoseCommandLineOptions() option -E found (just run backend compiler with -E to call CPP) */ \n"); #endif p_useBackendOnly = true; // p_skip_buildHigherLevelGrammars = true; p_disable_edg_backend = true; // This variable should be called frontend NOT backend??? p_skip_transformation = true; p_skip_unparse = true; p_skipfinalCompileStep = false; // DQ (8/22/2009): Verify that this was set when the command line was processed at the SgProject level. SgProject* project = this->get_project(); ROSE_ASSERT(project != NULL); ROSE_ASSERT(project->get_C_PreprocessorOnly() == true); } // DQ (1/19/2014): This option "-S" is required for some build systems (e.g. valgrind). // // Standard compiler options (allows alternative -S option to just run with gcc) // if ( CommandlineProcessing::isOption(argv,"-","(S)",true) == true ) { // printf ("/* option -S found (just run backend compiler with -S to call gcc) */ \n"); p_useBackendOnly = true; // p_skip_buildHigherLevelGrammars = true; p_disable_edg_backend = true; // This variable should be called frontend NOT backend??? p_skip_transformation = true; p_skip_unparse = true; p_skipfinalCompileStep = false; // DQ (8/22/2009): Verify that this was set when the command line was processed at the SgProject level. SgProject* project = this->get_project(); ROSE_ASSERT(project != NULL); ROSE_ASSERT(project->get_stop_after_compilation_do_not_assemble_file() == true); } // // Standard compiler options (allows alternative -H option to just output header file info) // if ( CommandlineProcessing::isOption(argv,"-","(H)",true) == true ) { // DQ (1/23/2018): Note, we can call the backend compiler using -H or call edg with -H. // This option will call the backend compiler with -H, if we want to call edg with -H // then we use -edg:H as the option to ROSE. #if 0 printf ("option -H found (just run backend compiler with -H to call CPP) \n"); #endif p_useBackendOnly = true; // p_skip_buildHigherLevelGrammars = true; p_disable_edg_backend = true; // This variable should be called frontend NOT backend??? p_skip_transformation = true; p_skip_unparse = true; p_skipfinalCompileStep = false; } #if 0 // DQ (1/20/2014): This option is only be be processed global (in SgProject support) and not on a file by file basis (SgFile support). // DQ (1/20/2014): Adding support for gnu -undefined option to ROSE command line. // -u SYMBOL, --undefined SYMBOL Start with undefined reference to SYMBOL string stringOptionForUndefinedSymbol; if ( CommandlineProcessing::isOptionWithParameter(argv,"-","(u|undefined)",stringOptionForUndefinedSymbol,true) == true ) { printf ("Found -u -undefined option specified on command line: stringOptionForUndefinedSymbol = %s \n",stringOptionForUndefinedSymbol.c_str()); if ( SgProject::get_verbose() >= 1 ) printf ("-undefined option specified on command line (for SgFile)\n"); #if 1 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif } #endif // // negative_test option: allows passing all tests to be treated as an error! // if ( CommandlineProcessing::isOption(argv,"-rose:","(negative_test)",true) == true ) { printf ("option -rose:negative_test found \n"); set_negative_test(true); } #if 1 // // We have processed all rose supported command line options. // Anything left in argv now should be a typo or option for either EDG or the C or C++ compiler. // if ( get_verbose() > 1 ) { cout << "The remaining non-rose options will be passed onto either the parser/front-end or the backend (vendor) the compiler: " << endl; for (unsigned int i = 1; i < argv.size(); i++) { cout << " argv[" << i << "]= " << argv[i] << endl; } } #endif #if 0 // debugging aid display("SgFile::processRoseCommandLineOptions()"); #endif } void SgFile::stripRoseCommandLineOptions ( vector<string> & argv ) { // Strip out the rose specific commandline options // the assume all other arguments are to be passed onto the C or C++ compiler // DQ (12/9/2016): Eliminating a warning that we want to be an error: -Werror=unused-but-set-variable. int optionCount = 0; // int i = 0; // #if ROSE_INTERNAL_DEBUG #if 1 // printf ("ROSE_DEBUG = %d \n",ROSE_DEBUG); // printf ("get_verbose() = %s value = %d \n",(get_verbose() > 1) ? "true" : "false",get_verbose()); if ( (ROSE_DEBUG >= 1) || (SgProject::get_verbose() > 2 )) { printf ("In stripRoseCommandLineOptions (TOP): List ALL arguments: argc = %" PRIuPTR " \n",argv.size()); for (size_t i=0; i < argv.size(); i++) printf (" argv[%" PRIuPTR "] = %s \n",i,argv[i].c_str()); } #endif // Split out the ROSE options first //---------------------------------------------------------------------------- // // TOO1 (2/13/2014): Refactor all of this into the Rose::Cmdline namespace // //---------------------------------------------------------------------------- Rose::Cmdline::StripRoseOptions(argv); //---------------------------------------------------------------------------- // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of agrc optionCount = sla(argv, "-" , "($)", "(h|help)",1); optionCount = sla(argv, "-rose:", "($)", "(h|help)",1); optionCount = sla(argv, "-rose:", "($)", "(V|version)", 1); // optionCount = sla(argv, "-rose:", "($)", "(v|verbose)",1); char *loggingSpec = NULL; optionCount = sla(argv, "-rose:", "($)^", "(log)", loggingSpec, 1); optionCount = sla(argv, "-rose:", "($)", "(keep_going)",1); int integerOption = 0; optionCount = sla(argv, "-rose:", "($)^", "(v|verbose)", &integerOption, 1); optionCount = sla(argv, "-rose:", "($)^", "(upc_threads)", &integerOption, 1); optionCount = sla(argv, "-rose:", "($)", "(C|C_only)",1); optionCount = sla(argv, "-rose:", "($)", "(UPC|UPC_only)",1); optionCount = sla(argv, "-rose:", "($)", "(OpenMP|openmp)",1); optionCount = sla(argv, "-rose:", "($)", "(openmp:parse_only|OpenMP:parse_only)",1); optionCount = sla(argv, "-rose:", "($)", "(openmp:ast_only|OpenMP:ast_only)",1); optionCount = sla(argv, "-rose:", "($)", "(openmp:lowering|OpenMP:lowering)",1); // support --rose:openmp variants optionCount = sla(argv, "--rose:", "($)", "(openmp:parse_only|OpenMP:parse_only)",1); optionCount = sla(argv, "--rose:", "($)", "(openmp:ast_only|OpenMP:ast_only)",1); optionCount = sla(argv, "--rose:", "($)", "(openmp:lowering|OpenMP:lowering)",1); optionCount = sla(argv, "-rose:", "($)", "(C89|C89_only)",1); optionCount = sla(argv, "-rose:", "($)", "(C99|C99_only)",1); optionCount = sla(argv, "-rose:", "($)", "(Cxx|Cxx_only)",1); optionCount = sla(argv, "-rose:", "($)", "(C11|C11_only)",1); optionCount = sla(argv, "-rose:", "($)", "(C14|C14_only)",1); optionCount = sla(argv, "-rose:", "($)", "(Cxx0x|Cxx0x_only)",1); optionCount = sla(argv, "-rose:", "($)", "(Cxx11|Cxx11_only)",1); optionCount = sla(argv, "-rose:", "($)", "(Cxx14|Cxx14_only)",1); optionCount = sla(argv, "-rose:", "($)", "(FailSafe|failsafe)",1); optionCount = sla(argv, "-rose:", "($)", "(output_warnings)",1); optionCount = sla(argv, "-rose:", "($)", "(cray_pointer_support)",1); optionCount = sla(argv, "-rose:", "($)", "(output_parser_actions)",1); optionCount = sla(argv, "-rose:", "($)", "(unparse_tokens)",1); // DQ (9/7/2016): remove this from the backend compiler command line (adding more support for it's use). // optionCount = sla(argv, "-rose:", "($)", "(unparse_headers)",1); // DQ (12/14/2015): Strip out the new option (so it will not be used on the backend compiler). optionCount = sla(argv, "-rose:", "($)", "(use_token_stream_to_improve_source_position_info)",1); optionCount = sla(argv, "-rose:", "($)", "(unparse_template_ast)",1); // DQ (12/23/2015): Suppress variable declaration normalizations optionCount = sla(argv, "-rose:", "($)", "(suppress_variable_declaration_normalization)",1); int integerOption_token_tests = 0; optionCount = sla(argv, "-rose:", "($)^", "(unparse_tokens_testing)", &integerOption_token_tests, 1); optionCount = sla(argv, "-rose:", "($)", "(unparse_using_leading_and_trailing_token_mappings)",1); optionCount = sla(argv, "-rose:", "($)", "(exit_after_parser)",1); optionCount = sla(argv, "-rose:", "($)", "(skip_syntax_check)",1); optionCount = sla(argv, "-rose:", "($)", "(relax_syntax_check)",1); optionCount = sla(argv, "-rose:", "($)", "(relax_syntax_check)",1); // DQ (8/11/2007): Support for Fortran and its different flavors optionCount = sla(argv, "-rose:", "($)", "(f|F|Fortran)",1); optionCount = sla(argv, "-rose:", "($)", "(f77|F77|Fortran77)",1); optionCount = sla(argv, "-rose:", "($)", "(f90|F90|Fortran90)",1); optionCount = sla(argv, "-rose:", "($)", "(f95|F95|Fortran95)",1); optionCount = sla(argv, "-rose:", "($)", "(f2003|F2003|Fortran2003)",1); optionCount = sla(argv, "-rose:", "($)", "(caf|CAF|CoArrayFortran)",1); // DQ (8/27/2007):Support for Fortran language output format optionCount = sla(argv, "-rose:", "($)", "(fixedOutput|fixedFormatOutput)",1); optionCount = sla(argv, "-rose:", "($)", "(freeOutput|freeFormatOutput)",1); optionCount = sla(argv, "-rose:", "($)", "(compileFixed|backendCompileFixedFormat)",1); optionCount = sla(argv, "-rose:", "($)", "(compileFree|backendCompileFreeFormat)",1); optionCount = sla(argv, "-rose:", "($)", "(C_output_language|Cxx_output_language|Fortran_output_language|Promela_output_language|PHP_output_language)",1); // DQ (5/19/2005): The output file name is constructed from the input source name (as I recall) // optionCount = sla(argv, "-rose:", "($)^", "(o|output)", &p_unparse_output_filename ,1); optionCount = sla(argv, "-rose:", "($)", "(skip_translation_from_edg_ast_to_rose_ast)",1); optionCount = sla(argv, "-rose:", "($)", "(skip_transformation)",1); optionCount = sla(argv, "-rose:", "($)", "(skip_unparse)",1); optionCount = sla(argv, "-rose:", "($)", "(skip_parser)",1); optionCount = sla(argv, "-rose:", "($)", "(unparse_includes)",1); optionCount = sla(argv, "-rose:", "($)", "(unparse_line_directives)",1); optionCount = sla(argv, "-rose:", "($)", "(unparse_function_calls_using_operator_syntax)",1); optionCount = sla(argv, "-rose:", "($)", "(unparse_function_calls_using_operator_names)",1); optionCount = sla(argv, "-rose:", "($)", "(unparse_instruction_addresses)",1); optionCount = sla(argv, "-rose:", "($)", "(unparse_raw_memory_contents)",1); optionCount = sla(argv, "-rose:", "($)", "(unparse_binary_file_format)",1); optionCount = sla(argv, "-rose:", "($)", "(collectAllCommentsAndDirectives)",1); optionCount = sla(argv, "-rose:", "($)", "(unparseHeaderFiles)",1); optionCount = sla(argv, "-rose:", "($)", "(skip_commentsAndDirectives)",1); optionCount = sla(argv, "-rose:", "($)", "(skipfinalCompileStep)",1); optionCount = sla(argv, "-rose:", "($)", "(prelink)",1); optionCount = sla(argv, "-" , "($)", "(ansi)",1); optionCount = sla(argv, "-rose:", "($)", "(markGeneratedFiles)",1); optionCount = sla(argv, "-rose:", "($)", "(wave)",1); optionCount = sla(argv, "-rose:", "($)", "(negative_test)",1); integerOption = 0; optionCount = sla(argv, "-rose:", "($)^", "(embedColorCodesInGeneratedCode)", &integerOption, 1); optionCount = sla(argv, "-rose:", "($)^", "(generateSourcePositionCodes)", &integerOption, 1); optionCount = sla(argv, "-rose:", "($)", "(outputGrammarTreeFiles)",1); optionCount = sla(argv, "-rose:", "($)", "(outputGrammarTreeFilesForHeaderFiles)",1); optionCount = sla(argv, "-rose:", "($)", "(outputGrammarTreeFilesForEDG)",1); optionCount = sla(argv, "-rose:", "($)", "(new_unparser)",1); optionCount = sla(argv, "-rose:", "($)", "(negative_test)",1); optionCount = sla(argv, "-rose:", "($)", "(strict)",1); integerOption = 0; optionCount = sla(argv, "-rose:", "($)^", "test", &integerOption, 1); optionCount = sla(argv, "-rose:", "($)", "(skipfinalCompileStep)",1); optionCount = sla(argv, "-rose:", "($)", "(prelink)",1); char* unparseHeaderFilesRootFolderOption = NULL; optionCount = sla(argv, "-rose:", "($)^", "(unparseHeaderFilesRootFolder)", unparseHeaderFilesRootFolderOption, 1); // DQ (11/6/2018): Added to support specification of application root directory to support source file and header file unparsing. char* applicationRootDirectoryOption = NULL; optionCount = sla(argv, "-rose:", "($)^", "(applicationRootDirectory)", applicationRootDirectoryOption, 1); char* templateInstationationOption = NULL; optionCount = sla(argv, "-rose:", "($)^", "(instantiation)",templateInstationationOption,1); // DQ (6/17/2005): Added support for AST merging (sharing common parts of the AST most often represented in common header files of a project) optionCount = sla(argv, "-rose:", "($)", "(astMerge)",1); char* filename = NULL; optionCount = sla(argv, "-rose:", "($)^", "(astMergeCommandFile)",filename,1); optionCount = sla(argv, "-rose:", "($)^", "(projectSpecificDatabaseFile)",filename,1); optionCount = sla(argv, "-rose:", "($)^", "(compilationPerformanceFile)",filename,1); //AS(093007) Remove paramaters relating to excluding and include comments and directives optionCount = sla(argv, "-rose:", "($)^", "(excludeCommentsAndDirectives)", &integerOption, 1); optionCount = sla(argv, "-rose:", "($)^", "(excludeCommentsAndDirectivesFrom)", &integerOption, 1); optionCount = sla(argv, "-rose:", "($)^", "(includeCommentsAndDirectives)", &integerOption, 1); optionCount = sla(argv, "-rose:", "($)^", "(includeCommentsAndDirectivesFrom)", &integerOption, 1); // DQ (12/8/2007): Strip use of the "-rose:output <filename> option. optionCount = sla(argv, "-rose:", "($)^", "(o|output)", filename, 1); // Liao 2/26/2009: strip use of -rose:excludePath <pathname> , -rose:excludeFile <filename> ,etc // which are introduced in Compass::commandLineProcessing() char* pathname = NULL; optionCount = sla(argv, "-rose:", "($)^", "(excludePath)", pathname,1); optionCount = sla(argv, "-rose:", "($)^", "(excludeFile)", filename,1); optionCount = sla(argv, "-rose:", "($)^", "(includeFile)", filename,1); // DQ (8/16/2008): parse binary executable file format only (some uses of ROSE may only do analysis of // the binary executable file format and not the instructions). This is also useful for testing. optionCount = sla(argv, "-rose:", "($)", "(read_executable_file_format_only)",1); optionCount = sla(argv, "-rose:", "($)", "(visualize_executable_file_format_skip_symbols)",1); optionCount = sla(argv, "-rose:", "($)", "(visualize_dwarf_only)",1); // DQ (10/18/2009): Sometimes we need to skip the parsing of the file format optionCount = sla(argv, "-rose:", "($)", "(read_instructions_only)",1); optionCount = sla(argv, "-rose:", "($)", "(skip_unparse_asm_commands)",1); // DQ (8/26/2007): Disassembly support from segments (true) instead of sections (false, default). optionCount = sla(argv, "-rose:", "($)", "(aggressive)",1); // DQ (2/5/2009): Remove use of "-rose:binary" to prevent it being passed on. optionCount = sla(argv, "-rose:", "($)", "(binary|binary_only)",1); // DQ (10/3/2010): Adding support for having CPP directives explicitly in the AST (as IR nodes instead of handled similar to comments). optionCount = sla(argv, "-rose:", "($)^", "(addCppDirectivesToAST)",filename,1); // DQ (9/26/2011): Added support for different levesl of detection for dangling pointers. optionCount = sla(argv, "-rose:", "($)^", "detect_dangling_pointers",&integerOption,1); // DQ (1/16/2012): Added all of the currently defined dot file options. optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(asmFileFormatFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(asmTypeFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(binaryExecutableFormatFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(commentAndDirectiveFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(ctorInitializerListFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(defaultColorFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(defaultFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(edgeFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(emptySymbolTableFilter)",&integerOption,1); // DQ (7/22/2012): Added support to igmore some specific empty IR nodes. optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(emptyBasicBlockFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(emptyFunctionParameterListFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(expressionFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(fileInfoFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(frontendCompatibilityFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(symbolFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(typeFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(variableDeclarationFilter)",&integerOption,1); optionCount = sla(argv, "-rose:dotgraph:", "($)^", "(noFilter)",&integerOption,1); // DQ (2/17/2013): Added support for skipping AST consistancy testing (for performance evaluation). optionCount = sla(argv, "-rose:", "($)", "(skipAstConsistancyTests)",1); // DQ (6/8/2013): Added support for experimental fortran frontend. optionCount = sla(argv, "-rose:", "($)", "(experimental_fortran_frontend)",1); // Rasmussen (8/30/2019): Added support for experimental Flang parser for Fortran optionCount = sla(argv, "-rose:", "($)", "(experimental_flang_frontend)",1); // Rasmussen (3/12/2018): Added support for CUDA Fortran within the experimental fortran frontend. optionCount = sla(argv, "-rose:", "($)", "(experimental_cuda_fortran_frontend)",1); // DQ (1/23/2016): Added support for OFP testing within new experimental Fortran support. optionCount = sla(argv, "-rose:", "($)", "(experimental_fortran_frontend_OFP_test)",1); // DQ (9/15/2013): Remove this from being output to the backend compiler. optionCount = sla(argv, "-rose:", "($)", "(unparse_in_same_directory_as_input_file)",1); // DQ (1/26/2014): Remove this from being output to the backend compiler. // This also likely means that we are not passing it on to the backend (linker). // At the moment, this fixes a problem where the version number is being treated as a file // and causing ROSE to crash in the command line handling. char* version_string = NULL; // optionCount = sla(argv, "-", "($)^", "(version-info)",filename,1); optionCount = sla(argv, "-", "($)^", "(version-info)",version_string,1); // DQ (2/5/2014): Remove this option from the command line that will be handed to the backend compiler (typically GNU gcc or g++). optionCount = sla(argv, "-rose:", "($)", "(suppressConstantFoldingPostProcessing)",1); // DQ (3/19/2014): This option causes the output of source code to an existing file to be an error. optionCount = sla(argv, "-rose:", "($)", "noclobber_output_file",1); // DQ (3/19/2014): This option causes the output of source code to an existing file to be an error if it results in a different file. optionCount = sla(argv, "-rose:", "($)", "noclobber_if_different_output_file",1); // Pei-Hung (8/6/2014): This option appends PID into the output name to avoid file collision in parallel compilation. optionCount = sla(argv, "-rose:", "($)", "appendPID",1); // DQ (9/8/2016): Adding support to optionally unparse template declarations from the AST optionCount = sla(argv, "-rose:", "($)", "unparseTemplateDeclarationsFromAST",1); // DQ (30/8/2017): Removing option to specify Csharp language support. optionCount = sla(argv, "-rose:", "($)", "(cs|cs_only)",1); // DQ (30/8/2017): Removing option to specify Ada language support. optionCount = sla(argv, "-rose:", "($)", "(ada|ada_only)",1); // DQ (30/8/2017): Removing option to specify Jovial language support. optionCount = sla(argv, "-rose:", "($)", "(joval|jovial_only)",1); // DQ (30/8/2017): Removing option to specify Cobol language support. optionCount = sla(argv, "-rose:", "($)", "(cobol|cobol_only)",1); // DQ (9/20/2018): Removing option to specify support for header file unparsing report. optionCount = sla(argv, "-rose:", "($)", "(headerFileUnparsingReport)",1); // TV (04/11/2018): Generates GraphViz from EDG internal representation optionCount = sla(argv, "-rose:", "($)", "edg_il_to_graphviz",1); // TV (10/04/2018): Do not pass -D__OPTIMIZE__ to EDG frontend (ROSE-1424) optionCount = sla(argv, "-rose:", "($)", "no_optimize_flag_for_frontend",1); // TV (10/09/2018): ROSE-1392 optionCount = sla(argv, "-rose:", "($)", "unparse_edg_normalized_method_ROSE_1392",1); // TV (11/20/2018): ROSE-1529: removed non-standard standard selection // Rasmussen (11/17/2018): ROSE-1584: separated "++" into single characters [+][+] for regex handling. optionCount = sla(argv, "-std=", "($)", "(c|c[+][+]|gnu|gnu[+][+]|fortran|upc|upcxx)",1); // DQ (12/9/2016): Eliminating a warning that we want to be an error: -Werror=unused-but-set-variable. ROSE_ASSERT(optionCount >= 0); #if 1 if ( (ROSE_DEBUG >= 1) || (SgProject::get_verbose() > 2 )) { printf ("In stripRoseCommandLineOptions (BOTTOM): List ALL arguments: argc = %" PRIuPTR " \n",argv.size()); for (size_t i=0; i < argv.size(); i++) printf (" argv[%" PRIuPTR "] = %s \n",i,argv[i].c_str()); } #endif } void SgFile::stripEdgCommandLineOptions ( vector<string> & argv ) { // Strip out the EDG specific commandline options the assume all // other arguments are to be passed onto the C or C++ compiler #if 0 if ( (ROSE_DEBUG >= 0) || (get_verbose() > 1) ) { Rose_STL_Container<string> l = CommandlineProcessing::generateArgListFromArgcArgv (argc,argv); printf ("In SgFile::stripEdgCommandLineOptions: argv = \n%s \n",StringUtility::listToString(l).c_str()); } #endif // Split out the EDG options (ignore the returned Rose_STL_Container<string> object) CommandlineProcessing::removeArgs (argv,"-edg:"); CommandlineProcessing::removeArgs (argv,"--edg:"); CommandlineProcessing::removeArgsWithParameters (argv,"-edg_parameter:"); CommandlineProcessing::removeArgsWithParameters (argv,"--edg_parameter:"); // DQ (2/20/2010): Remove this option when building the command line for the vendor compiler. // DQ (12/9/2016): Eliminating a warning that we want to be an error: -Werror=unused-but-set-variable. int optionCount = 0; optionCount = sla(argv, "--edg:", "($)", "(no_warnings)",1); // DQ (12/9/2016): Eliminating a warning that we want to be an error: -Werror=unused-but-set-variable. ROSE_ASSERT(optionCount >= 0); #if 0 Rose_STL_Container<string> l = CommandlineProcessing::generateArgListFromArgcArgv (argc,argv); printf ("In SgFile::stripEdgCommandLineOptions: argv = \n%s \n",StringUtility::listToString(l).c_str()); #endif } void SgFile::stripFortranCommandLineOptions ( vector<string> & argv ) { // Strip out the OFP specific commandline options the assume all // other arguments are to be passed onto the vendor Fortran compiler #if 0 if ( (ROSE_DEBUG >= 0) || (get_verbose() > 1) ) { Rose_STL_Container<string> l = CommandlineProcessing::generateArgListFromArgcArgv (argc,argv); printf ("In SgFile::stripFortranCommandLineOptions: argv = \n%s \n",StringUtility::listToString(l).c_str()); } #endif // No OFP options that we currently filter out. #if 0 Rose_STL_Container<string> l = CommandlineProcessing::generateArgListFromArgcArgv (argc,argv); printf ("In SgFile::stripFortranCommandLineOptions: argv = \n%s \n",StringUtility::listToString(l).c_str()); #endif } Rose_STL_Container<string> CommandlineProcessing::generateOptionListWithDeclaredParameters (const Rose_STL_Container<string> & argList, string inputPrefix ) { // This function returns a list of options using the inputPrefix (with the inputPrefix stripped off). Rose_STL_Container<string> optionList; unsigned int prefixLength = inputPrefix.length(); for (Rose_STL_Container<string>::const_iterator i = argList.begin(); i != argList.end(); i++) { if ( (*i).substr(0,prefixLength) == inputPrefix ) { // get the rest of the string as the option string option = (*i).substr(prefixLength); optionList.push_back(option); if (isOptionTakingSecondParameter(*i)) { i++; optionList.push_back(*i); } } } return optionList; } void SgFile::processBackendSpecificCommandLineOptions ( const vector<string>& argvOrig ) { // DQ (6/21/2005): This function processes commandline options that are specific to the backend // but which the front-end or ROSE should know about. Examples include template options that // would influence how ROSE instantiates or outputs templates in the code generation phase. // This function leaves all commandline options in place (for use by the backend) // DQ (1/17/2006): test this // ROSE_ASSERT(get_fileInfo() != NULL); vector<string> argv = argvOrig; // // -ansi option (fairly general option name across a number of compilers, I think) // if ( CommandlineProcessing::isOption(argv,"-","ansi",true) == true ) { set_strict_language_handling(true); } // // -fno-implicit-templates option // p_no_implicit_templates = false; if ( CommandlineProcessing::isOption(argv,"-f","no-implicit-templates",true) == true ) { // don't instantiate any inline templates printf ("ROSE sees use of -fno-implicit-templates option for use by g++ \n"); // printf ("ERROR: This g++ specific option is not yet supported \n"); // ROSE_ASSERT(false); p_no_implicit_templates = true; } // // -fno-implicit-inline-templates option // p_no_implicit_inline_templates = false; if ( CommandlineProcessing::isOption(argv,"-f","no-implicit-inline-templates",true) == true ) { // don't instantiate any inline templates printf ("ROSE sees use of -fno-implicit-inline-templates option for use by g++ \n"); p_no_implicit_inline_templates = true; } } void SgFile::build_CLANG_CommandLine ( vector<string> & inputCommandLine, vector<string> & argv, int fileNameIndex ) { // It filters Rose and Edg specific parameters and fixes the pathes. std::vector<std::string> inc_dirs_list; std::vector<std::string> define_list; std::string input_file; for (size_t i = 0; i < argv.size(); i++) { std::string current_arg(argv[i]); if (current_arg.find("-I") == 0) { if (current_arg.length() > 2) { inc_dirs_list.push_back(current_arg.substr(2)); } else { i++; if (i < argv.size()) inc_dirs_list.push_back(current_arg); else break; } } else if (current_arg.find("-D") == 0) { if (current_arg.length() > 2) { define_list.push_back(current_arg.substr(2)); } else { i++; if (i < argv.size()) define_list.push_back(current_arg); else break; } } else if (current_arg.find("-c") == 0) {} else if (current_arg.find("-o") == 0) { if (current_arg.length() == 2) { i++; if (i >= argv.size()) break; } } else if (current_arg.find("-rose") == 0) {} else { input_file = current_arg; } } std::vector<std::string>::iterator it_str; for (it_str = define_list.begin(); it_str != define_list.end(); it_str++) inputCommandLine.push_back("-D" + *it_str); for (it_str = inc_dirs_list.begin(); it_str != inc_dirs_list.end(); it_str++) inputCommandLine.push_back("-I" + StringUtility::getAbsolutePathFromRelativePath(*it_str)); std::string input_file_path = StringUtility::getPathFromFileName(input_file); input_file = StringUtility::stripPathFromFileName(input_file); if (input_file_path == "" ) input_file_path = "./"; input_file_path = StringUtility::getAbsolutePathFromRelativePath(input_file_path); input_file = input_file_path + "/" + input_file; inputCommandLine.push_back(input_file); } void SgFile::build_EDG_CommandLine ( vector<string> & inputCommandLine, vector<string> & argv, int fileNameIndex ) { // This function builds the command line input for the edg_main (the EDG C++ Front-End) // There are numerous options that must be set for different architectures. We can find // a more general setup of these options within something like Duct-Tape. In this function // argv and argc are the parameters from the user's commandline, and inputCommandLine and // numberOfCommandLineArguments are parameters for the new command line that will be build // for EDG. #if 0 printf ("##### Inside of SgFile::build_EDG_CommandLine file = %s \n",get_file_info()->get_filenameString().c_str()); printf ("##### Inside of SgFile::build_EDG_CommandLine file = %s = %s \n",get_file_info()->get_filenameString().c_str(),get_sourceFileNameWithPath().c_str()); #endif ROSE_ASSERT(get_file_info()->get_filenameString() == get_sourceFileNameWithPath()); // ROSE_ASSERT (p_useBackendOnly == false); // DQ (4/21/2006): I think we can now assert this! ROSE_ASSERT(fileNameIndex == 0); // printf ("Inside of SgFile::build_EDG_CommandLine(): fileNameIndex = %d \n",fileNameIndex); #if !defined(CXX_SPEC_DEF) // Output an error and exit cout << "ERROR: The preprocessor definition CXX_SPEC_DEF should have been defined by the configure process!!" << endl; ROSE_ABORT(); #endif // const char* alternativeCxx_Spec_Def[] = CXX_SPEC_DEF; // printf ("alternativeCxx_Spec_Def = %s \n",CXX_SPEC_DEF); // string alternativeCxx_Spec_Def = CXX_SPEC_DEF; // printf ("alternativeCxx_Spec_Def = %s \n",*alternativeCxx_Spec_Def); const char* configDefsArray[] = CXX_SPEC_DEF; const char* Cxx_ConfigIncludeDirsRaw[] = CXX_INCLUDE_STRING; const char* C_ConfigIncludeDirsRaw[] = C_INCLUDE_STRING; Rose_STL_Container<string> configDefs(configDefsArray, configDefsArray + sizeof(configDefsArray) / sizeof(*configDefsArray)); Rose_STL_Container<string> Cxx_ConfigIncludeDirs(Cxx_ConfigIncludeDirsRaw, Cxx_ConfigIncludeDirsRaw + sizeof(Cxx_ConfigIncludeDirsRaw) / sizeof(const char*)); Rose_STL_Container<string> C_ConfigIncludeDirs(C_ConfigIncludeDirsRaw, C_ConfigIncludeDirsRaw + sizeof(C_ConfigIncludeDirsRaw) / sizeof(const char*)); #if 0 // printf ("CXX_INCLUDE_STRING = %s \n",CXX_INCLUDE_STRING); // printf ("CXX_INCLUDE_STRING = %s \n",Cxx_ConfigIncludeDirsRaw); printf ("CXX_INCLUDE_STRING = %s \n",Cxx_ConfigIncludeDirsRaw[0]); #endif #if 0 for (size_t i=0; i < Cxx_ConfigIncludeDirs.size(); i++) { printf ("Cxx_ConfigIncludeDirs[%" PRIuPTR "] = %s \n",i,Cxx_ConfigIncludeDirs[i].c_str()); } #endif #if 0 for (size_t i=0; i < configDefs.size(); i++) { printf ("configDefs[%" PRIuPTR "] = %s \n",i,configDefs[i].c_str()); } #endif #if 0 // DQ (7/3/2013): This is a work around to support a bug in EDG 4.7 which causes test2013_246.C to fail (boost example code). #if __GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ > 3 || (__GNUC_MINOR__ == 3 && __GNUC_PATCHLEVEL__ >= 0))) // DQ (7/3/2013): For this to let EDG think we have a GNU 4.2 compiler. ROSE_ASSERT(configDefs.size() >= 3); configDefs[0] = "-D__GNUG__=4"; configDefs[1] = "-D__GNUC__=4"; configDefs[2] = "-D__GNUC_MINOR__=2"; // DQ (7/3/2013): This macro is used in rose_edg_required_macros_and_functions.h.in (temporary work about for EDG 4.7). #define LIE_ABOUT_GNU_VERSION_TO_EDG #endif #else // printf ("In SgFile::build_EDG_CommandLine(): TURNED OFF MACRO LIE_ABOUT_GNU_VERSION_TO_EDG \n"); #endif // const char* boostPath[] = ROSE_BOOST_PATH; // Removed reference to __restrict__ so it could be placed into the preinclude vendor specific header file for ROSE. // DQ (9/10/2004): Attept to add support for restrict (but I think this just sets it to true, using "-Dxxx=" works) // const string roseSpecificDefs = "-DUSE_RESTRICT_POINTERS_IN_ROSE_TRANSFORMATIONS -DUSE_ROSE -D__restrict__="; vector<string> roseSpecificDefs; // Communicate that ROSE transformation can use the restrict keyword. roseSpecificDefs.push_back("-DUSE_RESTRICT_POINTERS_IN_ROSE_TRANSFORMATIONS"); // Communicate to the generated program that we are using ROSE (in case there are specific options that the user wants to to invoke. roseSpecificDefs.push_back("-DUSE_ROSE"); ROSE_ASSERT(configDefs.empty() == false); ROSE_ASSERT(Cxx_ConfigIncludeDirs.empty() == false); ROSE_ASSERT(C_ConfigIncludeDirs.empty() == false); #if 0 printf ("configDefsString = %s \n",CommandlineProcessing::generateStringFromArgList(configDefs).c_str()); // printf ("Cxx_ConfigIncludeString = %s \n",Cxx_ConfigIncludeString.c_str()); // printf ("C_ConfigIncludeString = %s \n",C_ConfigIncludeString.c_str()); #endif #if 0 std::string tmp5_translatorCommandLineString = CommandlineProcessing::generateStringFromArgList(inputCommandLine,false,true); printf ("tmp5_translatorCommandLineString = %s \n",tmp5_translatorCommandLineString.c_str()); #endif vector<string> commandLine; #if 0 // DQ (8/17/2015): Moved this specification of the boost path to after the generation of the -I include_dirs // to handle the case where a different version of boost is explicitly specified in the -I include_dirs. // This allows ROSE to reproduce the behavior of the GNU g++ and Intel icpc compilers. // TOO1 (2014-10-09): Use the correct Boost version that ROSE was configured --with-boost #ifdef ROSE_BOOST_PATH // Search dir for header files, after all directories specified by -I but before the standard system directories. #if 0 printf ("Adding boost path = %s \n",ROSE_BOOST_PATH); #endif commandLine.push_back("--sys_include"); commandLine.push_back(std::string(ROSE_BOOST_PATH) + "/include"); #endif #endif #ifdef ROSE_USE_MICROSOFT_EXTENSIONS // DQ (4/21/2014): Add Microsoft specific options: // --microsoft // --microsoft_16 // --microsoft_version version-number // --microsoft_build_number build-number // Not all of these are required, the simplest usage is to use "--microsoft". // DQ (4/21/2014): Use the simple option to turn on microsoft mode. commandLine.push_back("--microsoft"); #if 0 // EDG 4.9 permits emulation modes for specific MSVC versions. Not clear what version of MSVC we should be emulating. // This is the version number for MSVC 5.0, but we need to get a later version. int emulate_msvc_version_number = 1100; // printf ("emulate_msvc_version_number = %d \n",emulate_msvc_version_number); commandLine.push_back("--microsoft_version"); commandLine.push_back(StringUtility::numberToString(emulate_msvc_version_number)); #endif #endif #ifndef ROSE_USE_MICROSOFT_EXTENSIONS #ifndef _MSC_VER // DQ (4/13/2016): This must use the values of __GNUC__, __GNUC_MINOR__, and __GNUC_PATCHLEVEL__ // from the backend compiler. Note that we don't save the __GNUC_PATCHLEVEL__ for the backend // compiler, but we can assume it is zero (I think this should work well). // DQ (7/3/2013): We don't have to lie to EDG about the version of GNU that it should emulate // (only to the parts of Boost the read the GNU compiler version number information). // DQ (7/3/2013): Adding option to specify the version of GNU to emulate. // int emulate_gnu_version_number = __GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__; // int emulate_gnu_version_number = BACKEND_CXX_COMPILER_MAJOR_VERSION_NUMBER*10000 + BACKEND_CXX_COMPILER_MINOR_VERSION_NUMBER*100 + 0; int emulate_backend_compiler_version_number = BACKEND_CXX_COMPILER_MAJOR_VERSION_NUMBER*10000 + BACKEND_CXX_COMPILER_MINOR_VERSION_NUMBER*100 + 0; // #ifdef __INTEL_COMPILER #ifdef BACKEND_CXX_IS_INTEL_COMPILER // DQ (9/6/2015): Reset to specific version of GNU for Intel v14 compiler. // emulate_backend_compiler_version_number = 4*10000 + 8*100 + 3; // DQ (12/13/2016): Test tis for Intel v16. emulate_backend_compiler_version_number = 6*10000 + 1*100 + 0; #endif // DQ (7/3/2014): Testing if we emulate a different version of GNU g++. // emulate_backend_compiler_version_number = 4*10000 + 8*100 + 1; if (SgProject::get_verbose() > 0) { printf ("In SgFile::build_EDG_CommandLine(): emulate_backend_compiler_version_number = %d \n",emulate_backend_compiler_version_number); } // DQ (4/26/2019): NOTE: this option appears to be incompatable with use of gnu_version. if (get_strict_language_handling() == false) { #ifdef BACKEND_CXX_IS_INTEL_COMPILER commandLine.push_back("--gnu_version"); #endif #ifdef BACKEND_CXX_IS_GNU_COMPILER commandLine.push_back("--gnu_version"); #else #ifdef USE_CMAKE // DQ (4/20/2016): When using CMAKE the BACKEND_CXX_IS_GNU_COMPILER is not defiled. commandLine.push_back("--gnu_version"); #endif #endif #ifdef BACKEND_CXX_IS_CLANG_COMPILER #if 0 printf ("For clang support in ROSE: __GNUC__ = %d __GNUC_MINOR__ = %d __GNUC_PATCHLEVEL__ = %d \n",(int)__GNUC__, (int)__GNUC_MINOR__, (int)__GNUC_PATCHLEVEL__); // DQ (4/13/2016): Using Clang we should not be able to generate this number unless it is incorrect. // if (__GNUC__ == 4 && __GNUC_MINOR__ == 2) if (emulate_backend_compiler_version_number == 40200) { printf ("Clang support is setting compiler version incorrectly \n"); ROSE_ASSERT(false); } // DQ (4/13/2016): In the case of Clang we can catch an interesting bug where the values of the // compiler used to compile ROSE are used to compute the version of GNU that we want the backend // compiler to emulated. In fact the compiler used to compile ROSE can have NOTHING to with the // version of the compiler used to compiler the ROSE generated code (the backend compiler). // We need to use the values of __GNUC__, __GNUC_MINOR__, and __GNUC_PATCHLEVEL__ from the // backend compiler to compute the version of GNU (or clang) that we will emulate. #if 0 #if ((__GNUC__ == 4) && (__GNUC_MINOR__ == 2)) #error "Error incorrect computation of Clang emulated version: ((__GNUC__ == 4) && (__GNUC_MINOR__ == 2))" #endif #endif #endif commandLine.push_back("--clang"); commandLine.push_back("--clang_version"); // DQ (1/16/2017): If this is the Clang backend, then assume we want to use C++11 support (default for later versions of Clang (3.7 and later)). // commandLine.push_back("--c++11"); #endif commandLine.push_back(StringUtility::numberToString(emulate_backend_compiler_version_number)); } // #endif for ROSE_USE_MICROSOFT_EXTENSIONS #endif // #endif for _MSC_VER #endif #ifdef LIE_ABOUT_GNU_VERSION_TO_EDG // DQ (7/3/2013): define this so that the rose_edg_required_macros_and_functions.h header file can make // some builtin function available (required to compile test2013_246.C). commandLine.push_back("-DLIE_ABOUT_GNU_VERSION_TO_EDG"); #endif #if 0 printf ("commandLine = %s \n",CommandlineProcessing::generateStringFromArgList(commandLine).c_str()); #endif #if 0 printf ("Exiting after output of configDefs \n"); ROSE_ASSERT(false); #endif #if 0 // DQ (4/11/2014): This can be accomplished by using --edg:dump_configuration on the ROSE command line. commandLine.push_back("--dump_configuration"); #endif // display("Called from SgFile::build_EDG_CommandLine"); // DQ (6/13/2013): This was wrong, the parent of the SgFile is the SgFileList IR node and it is better to call the function to get the SgProject. // SgProject* project = isSgProject(this->get_parent()); SgProject* project = TransformationSupport::getProject(this); ROSE_ASSERT (project != NULL); // AS(063006) Changed implementation so that real paths can be found later vector<string> includePaths; // DQ (1.20/2014): Adding support for -m32 and associated macro to ROSE to force size_t to be defined to be 32-bit instead of 64-bit. if (project->get_mode_32_bit() == true) { #if 0 printf ("Setting ROSE_M32BIT mode! \n"); #endif roseSpecificDefs.push_back("-DROSE_M32BIT"); #if 0 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif } // skip the 0th entry since this is just the name of the program (e.g. rose) for (unsigned int i=1; i < argv.size(); i++) { // most options appear as -<option> // have to process +w2 (warnings option) on some compilers so include +<option> if ( argv[i].size() >= 2 && (argv[i][0] == '-') && (argv[i][1] == 'I') ) { // int length = strlen(argv[i]); // printf ("Look for include path: argv[%d] = %s length = %d \n",i,argv[i],length); // AS: Did changes to get absolute path std::string includeDirectorySpecifier = argv[i].substr(2); includeDirectorySpecifier = StringUtility::getAbsolutePathFromRelativePath(includeDirectorySpecifier ); includePaths.push_back(includeDirectorySpecifier); } } #ifndef ROSE_USE_MICROSOFT_EXTENSIONS commandLine.insert(commandLine.end(), configDefs.begin(), configDefs.end()); #else // DQ (4/21/2014): The preinclude file we generate for ROSE is specific to the backend and for Windows code might be too specific to Linux. // But we certainly don't want the -D options: e.g "-D__GNUG__=4 -D__GNUC__=4 -D__GNUC_MINOR__=4 -D__GNUC_PATCHLEVEL__=7" #if 0 // DQ (8/18/2014): Supress this output, I think we do want to include the rose_edg_required_macros_and_functions.h // (but we might want to use it to specify different or additional builtin functions in the future). printf ("Note for advanced microsoft windows support using MSVC: Not clear if we need a specific --preinclude rose_edg_required_macros_and_functions.h for windows \n"); #endif // commandLine.insert(commandLine.end(), configDefs.begin(), configDefs.end()); commandLine.push_back("--preinclude"); commandLine.push_back("rose_edg_required_macros_and_functions.h"); // DQ (4/23/2017): Add something to permit use to detect when Microsoft extensions are being supported. commandLine.push_back("-DROSE_USE_MICROSOFT_EXTENSIONS"); #endif // DQ (5/24/2015): Adding support for specification of optimization to trigger use of __OPTIMIZE__ macro (required for compatability with GNU gcc API). if (get_optimization() == true && get_no_optimize_flag_for_frontend() == false) { #if 0 printf ("Adding -D__OPTIMIZE__ flag to EDG command line \n"); #endif commandLine.push_back("-D__OPTIMIZE__"); } #if 0 printf ("In SgFile::build_EDG_CommandLine(): includePaths.size() = %zu \n",includePaths.size()); #endif #if 1 // DQ (3/14/2015): This has been moved to before the compiler and system specific include and // sys_include paths so that header files with names that match compiler and system header // files will be used instead from the directories specified using the -I and sys_include options. // Note that this bug fix is required to support Xen (which uses it's own header files that have // the same name as system and compiler specific header files). // Add the -I definitions to the command line for (vector<string>::const_iterator i = includePaths.begin(); i != includePaths.end(); ++i) { // inputCommandLine.push_back("-I" + *i); commandLine.push_back("-I" + *i); } // PL (4/15/2014): In GCC's document about system headers (http://gcc.gnu.org/onlinedocs/cpp/System-Headers.html): // All directories named by -isystem are searched after all directories named by -I, no matter what their order was on the command line. // DQ (4/14/2014): Experiment with placing this here (after "-I" options). This is part of the // fix to supress redundant output of all "-i" paths as "-sys_include" options to EDG. if ( SgProject::get_verbose() > 1 ) { printf ("project->get_preincludeDirectoryList().size() = %" PRIuPTR " \n",project->get_preincludeDirectoryList().size()); } // This is the list of directories that have been referenced as "-isystem <directory>" on the original command line to the ROSE // translator. We translate these to "-sys_include <directory>" options to pass to EDG (since that is how EDG understands them). for (SgStringList::iterator i = project->get_preincludeDirectoryList().begin(); i != project->get_preincludeDirectoryList().end(); i++) { // Build the preinclude directory list if ( SgProject::get_verbose() > 1 ) { printf ("Building commandline: --sys_include %s \n",(*i).c_str()); } // inputCommandLine.push_back("--sys_include"); // inputCommandLine.push_back(*i); commandLine.push_back("--sys_include"); commandLine.push_back(*i); } #endif // DQ (1/13/2009): The preincludeFileList was built if the -include <file> option was used // George Vulov (12/8/2010) Include the file rose_edg_required_macros_and_functions.h first, then the other preincludes for (SgStringList::iterator i = project->get_preincludeFileList().begin(); i != project->get_preincludeFileList().end(); i++) { // Build the preinclude file list ROSE_ASSERT(project->get_preincludeFileList().empty() == false); #if 0 printf ("In build_EDG_CommandLine(): Building commandline: --preinclude %s \n",(*i).c_str()); #endif commandLine.push_back("--preinclude"); commandLine.push_back(*i); } // DQ (12/2/2006): Both GNU and EDG determine the language mode from the source file name extension. // In ROSE we also require that C files be explicitly specified to use the C language mode. Thus // C++ source files will be treated as C++ even if the C language rules are specified, however they // are restricted to the C subset of C++. // bool treatAsCSourceFile = ((get_C_only() == true || get_C99_only() == true) && (get_sourceFileUsesCppFileExtension() == false)); // if (treatAsCSourceFile == true) // Find the C++ sys include path for the rose_edg_required_macros_and_functions.h vector<string> roseHeaderDirCPP(1, "--sys_include"); #if 0 printf ("roseHeaderDirCPP.size() = %zu \n",roseHeaderDirCPP.size()); printf ("Cxx_ConfigIncludeDirs.size() = %zu \n",Cxx_ConfigIncludeDirs.size()); #endif // This includes a generated header file that defines the __builtin functions and a number // of predefined macros obtained from the backend compiler. The new EDG/Sage interface // does not require this function and I think that the file is not generated in this case // which is why there is a test for it's existence to see if it should be include. I would // rather see a more direct test. for (Rose_STL_Container<string>::iterator i = Cxx_ConfigIncludeDirs.begin(); i != Cxx_ConfigIncludeDirs.end(); i++) { string file = (*i) + "/rose_edg_required_macros_and_functions.h"; FILE* testIfFileExist = fopen(file.c_str(),"r"); #if 0 printf ("Cxx_ConfigIncludeDirs: testIfFileExist = %s file = %s \n",testIfFileExist ? "true" : "false",file.c_str()); #endif if (testIfFileExist) { roseHeaderDirCPP.push_back(*i); fclose(testIfFileExist); break; } } // Find the C sys include path for the rose_edg_required_macros_and_functions.h (see comment above for --sys_include use in CPP). vector<string> roseHeaderDirC(1, "--sys_include"); #if 0 printf ("roseHeaderDirC.size() = %zu \n",roseHeaderDirCPP.size()); printf ("C_ConfigIncludeDirs.size() = %zu \n",C_ConfigIncludeDirs.size()); #endif for (Rose_STL_Container<string>::iterator i = C_ConfigIncludeDirs.begin(); i != C_ConfigIncludeDirs.end(); i++) { string file = (*i) + "/rose_edg_required_macros_and_functions.h"; FILE* testIfFileExist = fopen(file.c_str(),"r"); // std::cout << file << std::endl; #if 0 printf ("C_ConfigIncludeDirs: testIfFileExist = %s file = %s \n",testIfFileExist ? "true" : "false",file.c_str()); #endif if (testIfFileExist) { roseHeaderDirC.push_back(*i); fclose(testIfFileExist); break; } } // TV (05/07/2010): OpenCL and CUDA mode (Caution: we may need both C++ language mode and Cuda) bool enable_cuda = CommandlineProcessing::isOption(argv,"-","cuda",true) || get_Cuda_only(); bool enable_opencl = CommandlineProcessing::isOption(argv,"-","opencl",true) || get_OpenCL_only(); // string header_path = findRoseSupportPathFromBuild("include-staging", "include-staging"); string header_path = findRoseSupportPathFromBuild("include-staging", "include/edg"); #if 0 if (enable_cuda || enable_opencl) { Rose::Cmdline::makeSysIncludeList(C_ConfigIncludeDirs, commandLine); if (enable_cuda && !enable_opencl) { commandLine.push_back("--preinclude"); commandLine.push_back(header_path + "/cuda_HEADERS/preinclude-cuda.h"); #endif #if 0 printf ("In build_EDG_CommandLine(): enable_cuda = %s enable_opencl = %s \n",enable_cuda ? "true" : "false",enable_opencl ? "true" : "false"); #endif if (enable_cuda || enable_opencl) { if (enable_cuda && !enable_opencl) { commandLine.push_back("--preinclude"); commandLine.push_back(header_path + "/cuda_HEADERS/preinclude-cuda.h"); #ifdef CUDA_INC_DIR commandLine.push_back(std::string("--sys_include")); commandLine.push_back(std::string(CUDA_INC_DIR)); #endif // CUDA is a C++ extention, add default C++ options commandLine.push_back("-DROSE_LANGUAGE_MODE=1"); Rose::Cmdline::makeSysIncludeList(Cxx_ConfigIncludeDirs, commandLine); // DQ (4/13/2016): If we are going to set this, set it to a more reasonable value. // Try letting EDG specify the value of this internal variable. // commandLine.push_back("-D__cplusplus=1"); // commandLine.push_back("-D__cplusplus=199711L"); } else { if (enable_opencl && !enable_cuda) { commandLine.push_back("--preinclude"); commandLine.push_back(header_path + "/opencl_HEADERS/preinclude-opencl.h"); #ifdef OPENCL_INC_DIR commandLine.push_back(std::string("--sys_include")); commandLine.push_back(std::string(OPENCL_INC_DIR)); #endif // OpenCL is a C extention, add default C options commandLine.push_back("-DROSE_LANGUAGE_MODE=0"); Rose::Cmdline::makeSysIncludeList(C_ConfigIncludeDirs, commandLine); #ifndef ROSE_USE_CLANG_FRONTEND commandLine.push_back("-DSKIP_OPENCL_SPECIFIC_DEFINITION"); #endif } else { printf ("Error: CUDA and OpenCL are mutually exclusive.\n"); ROSE_ASSERT(false); } } } else { #if 0 // display("SgFile::buildCompilerCommandLineOptions()"); printf ("In build_EDG_CommandLine(): this = %p \n",this); printf (" --- C compiler = %s \n",BACKEND_C_COMPILER_NAME_WITH_PATH); printf (" --- C++ compiler = %s \n",BACKEND_CXX_COMPILER_NAME_WITH_PATH); printf (" --- Fortran compiler = %s \n",BACKEND_FORTRAN_COMPILER_NAME_WITH_PATH); printf (" --- Java compiler = %s \n",BACKEND_JAVA_COMPILER_NAME_WITH_PATH); printf (" --- Python interpreter = %s \n",BACKEND_PYTHON_INTERPRETER_NAME_WITH_PATH); printf (" --- get_C_only() = %s \n",(get_C_only() == true) ? "true" : "false"); printf (" --- get_C99_only() = %s \n",(get_C99_only() == true) ? "true" : "false"); printf (" --- get_C11_only() = %s \n",(get_C11_only() == true) ? "true" : "false"); printf (" --- get_C14_only() = %s \n",(get_C14_only() == true) ? "true" : "false"); printf (" --- get_Cxx_only() = %s \n",(get_Cxx_only() == true) ? "true" : "false"); printf (" --- get_Cxx11_only() = %s \n",(get_Cxx11_only() == true) ? "true" : "false"); printf (" --- get_Cxx14_only() = %s \n",(get_Cxx14_only() == true) ? "true" : "false"); printf (" --- get_Fortran_only() = %s \n",(get_Fortran_only() == true) ? "true" : "false"); printf (" --- get_F77_only() = %s \n",(get_F77_only() == true) ? "true" : "false"); printf (" --- get_F90_only() = %s \n",(get_F90_only() == true) ? "true" : "false"); printf (" --- get_F95_only() = %s \n",(get_F95_only() == true) ? "true" : "false"); printf (" --- get_F2003_only() = %s \n",(get_F2003_only() == true) ? "true" : "false"); printf (" --- get_F2008_only() = %s \n",(get_F2008_only() == true) ? "true" : "false"); printf (" --- get_CoArrayFortran_only() = %s \n",(get_CoArrayFortran_only() == true) ? "true" : "false"); printf (" --- get_Java_only() = %s \n",(get_Java_only() == true) ? "true" : "false"); printf (" --- get_Python_only() = %s \n",(get_Python_only() == true) ? "true" : "false"); #endif // if (get_C_only() == true || get_C99_only() == true) // if (get_C_only() == true || get_C99_only() == true || get_C11_only() == true) // if (get_C_only() == true || get_C89_only() == true || get_C99_only() == true || get_C11_only() == true) if (get_C_only() == true || get_C89_only() == true || get_C99_only() == true || get_C11_only() == true || get_C14_only() == true) { #if 0 printf ("input file is either C file or commandline is marked explicitly to compile input file as C file \n"); #endif // AS(02/21/07) Add support for the gcc 'nostdinc' and 'nostdinc++' options // DQ (11/29/2006): if required turn on the use of the __cplusplus macro // if (get_requires_cplusplus_macro() == true) if (get_sourceFileUsesCppFileExtension() == true) { // The value here should be 1 to match that of GNU gcc (the C++ standard requires this to be "199711L") // initString += " -D__cplusplus=0 "; // DQ (4/13/2016): If we are going to set this, set it to a more reasonable value. // Try letting EDG specify the value of this internal variable. // commandLine.push_back("-D__cplusplus=1"); // commandLine.push_back("-D__cplusplus=199711L"); if ( CommandlineProcessing::isOption(argv,"-","nostdinc",false) == true ) { #if 0 printf ("Handling option (test 1): nostdinc \n"); printf (" --- roseHeaderDirC.size() = %zu \n",roseHeaderDirC.size()); #endif // DQ (2/1/2015): This is incorrect, since it just inserts a "-sys_include" option without a parameter. // commandLine.insert(commandLine.end(), roseHeaderDirC.begin(), roseHeaderDirC.end()); // no standard includes when -nostdinc is specified // DQ (2/1/2015): We still need the ROSE specific default sys_includes (to find the required rose_edg_required_macros_and_functions.h file, for example. bool using_nostdinc_option = true; Rose::Cmdline::makeSysIncludeList(C_ConfigIncludeDirs, commandLine, using_nostdinc_option); } else { if ( CommandlineProcessing::isOption(argv,"-","nostdinc++",false) == true ) { // DQ (2/1/2015): This is incorrect, since it just inserts a "-sys_include" option without a parameter. // commandLine.insert(commandLine.end(), roseHeaderDirCPP.begin(), roseHeaderDirCPP.end()); // DQ (2/1/2015): We still need the ROSE specific default sys_includes (to find the required rose_edg_required_macros_and_functions.h file, for example. bool using_nostdinc_option = true; Rose::Cmdline::makeSysIncludeList(C_ConfigIncludeDirs, commandLine, using_nostdinc_option); } else { Rose::Cmdline::makeSysIncludeList(Cxx_ConfigIncludeDirs, commandLine); } } // DQ (11/29/2006): Specify C++ mode for handling in rose_edg_required_macros_and_functions.h commandLine.push_back("-DROSE_LANGUAGE_MODE=1"); } else { if ( CommandlineProcessing::isOption(argv,"-","nostdinc",false) == true ) { #if 0 printf ("Handling option (test 2): nostdinc \n"); printf (" --- roseHeaderDirC.size() = %zu \n",roseHeaderDirC.size()); std::string argString_roseHeaderDirC = CommandlineProcessing::generateStringFromArgList(roseHeaderDirC,false,false); printf (" --- argString_roseHeaderDirC = %s \n",argString_roseHeaderDirC.c_str()); std::string argString_commandLine = CommandlineProcessing::generateStringFromArgList(commandLine,false,false); printf (" --- argString_commandLine = %s \n",argString_commandLine.c_str()); #endif // DQ (2/1/2015): This is incorrect, since it just inserts a "-sys_include" option without a parameter. // commandLine.insert(commandLine.end(), roseHeaderDirC.begin(), roseHeaderDirC.end()); // no standard includes when -nostdinc is specified #if 0 std::string argString_commandLine_before = CommandlineProcessing::generateStringFromArgList(commandLine,false,false); printf (" --- after makeSysIncludeList(): argString_commandLine_before = %s \n",argString_commandLine_before.c_str()); #endif // DQ (2/1/2015): We still need the ROSE specific default sys_includes (to find the required rose_edg_required_macros_and_functions.h file, for example. bool using_nostdinc_option = true; Rose::Cmdline::makeSysIncludeList(C_ConfigIncludeDirs, commandLine, using_nostdinc_option); #if 0 std::string argString_commandLine_after = CommandlineProcessing::generateStringFromArgList(commandLine,false,false); printf (" --- after makeSysIncludeList(): argString_commandLine_after = %s \n",argString_commandLine_after.c_str()); #endif } else { #if 0 printf ("Handling option (test 2): without nostdinc \n"); printf (" --- roseHeaderDirC.size() = %zu \n",roseHeaderDirC.size()); std::string argString_roseHeaderDirC = CommandlineProcessing::generateStringFromArgList(roseHeaderDirC,false,false); printf (" --- argString_roseHeaderDirC = %s \n",argString_roseHeaderDirC.c_str()); std::string argString_commandLine = CommandlineProcessing::generateStringFromArgList(commandLine,false,false); printf (" --- argString_commandLine = %s \n",argString_commandLine.c_str()); #endif Rose::Cmdline::makeSysIncludeList(C_ConfigIncludeDirs, commandLine); } // DQ (11/29/2006): Specify C mode for handling in rose_edg_required_macros_and_functions.h commandLine.push_back("-DROSE_LANGUAGE_MODE=0"); } } else { #if 0 printf ("input file is either NOT a C file or commandline is NOT marked explicitly to compile input file as C file \n"); #endif if ( CommandlineProcessing::isOption(argv,"-","nostdinc",false) == true ) { #if 0 printf ("Handling option (test 3): nostdinc++ \n"); printf (" --- roseHeaderDirC.size() = %zu \n",roseHeaderDirC.size()); printf (" --- roseHeaderDirCPP.size() = %zu \n",roseHeaderDirCPP.size()); std::string argString_roseHeaderDirC = CommandlineProcessing::generateStringFromArgList(roseHeaderDirC,false,false); std::string argString_roseHeaderDirCPP = CommandlineProcessing::generateStringFromArgList(roseHeaderDirCPP,false,false); printf (" --- argString_roseHeaderDirC = %s \n",argString_roseHeaderDirC.c_str()); printf (" --- argString_roseHeaderDirCPP = %s \n",argString_roseHeaderDirCPP.c_str()); std::string argString_commandLine = CommandlineProcessing::generateStringFromArgList(commandLine,false,false); printf (" --- argString_commandLine = %s \n",argString_commandLine.c_str()); #endif // DQ (2/1/2015): This is incorrect, since it just inserts a "-sys_include" option without a parameter. // commandLine.insert(commandLine.end(), roseHeaderDirCPP.begin(), roseHeaderDirCPP.end()); // no standard includes when -nostdinc is specified // DQ (2/1/2015): We still need the ROSE specific default sys_includes (to find the required rose_edg_required_macros_and_functions.h file, for example. bool using_nostdinc_option = true; Rose::Cmdline::makeSysIncludeList(Cxx_ConfigIncludeDirs, commandLine, using_nostdinc_option); #if 0 std::string argString_commandLine_after = CommandlineProcessing::generateStringFromArgList(commandLine,false,false); printf (" --- after makeSysIncludeList(): argString_commandLine_after = %s \n",argString_commandLine_after.c_str()); #endif } else { if ( CommandlineProcessing::isOption(argv,"-","nostdinc\\+\\+",false) == true ) // Option name is a RE { #if 0 printf ("Handling option (test 4): nostdinc++ \n"); printf (" --- roseHeaderDirCPP.size() = %zu \n",roseHeaderDirCPP.size()); #endif // DQ (2/1/2015): This is incorrect, since it just inserts a "-sys_include" option without a parameter. // commandLine.insert(commandLine.end(), roseHeaderDirCPP.begin(), roseHeaderDirCPP.end()); // DQ (2/1/2015): We still need the ROSE specific default sys_includes (to find the required rose_edg_required_macros_and_functions.h file, for example. bool using_nostdinc_option = true; Rose::Cmdline::makeSysIncludeList(Cxx_ConfigIncludeDirs, commandLine, using_nostdinc_option); } else { Rose::Cmdline::makeSysIncludeList(Cxx_ConfigIncludeDirs, commandLine); } } // DQ (11/29/2006): Specify C++ mode for handling in rose_edg_required_macros_and_functions.h commandLine.push_back("-DROSE_LANGUAGE_MODE=1"); // #ifdef __INTEL_COMPILER #ifdef BACKEND_CXX_IS_INTEL_COMPILER // DQ (9/9/2015): The Intel compiler sets this to an old value (likely to match the MS Visual Studio C++ compiler). // This is not consistant with GNU, but required for Intel header file compatablity (or is is that Intel is using // the GNU header files and it is required for GNU compatability?). I think that setting this predefined macro is // not allowed by EDG in MSVC mode. // commandLine.push_back("-D__cplusplus=199711L"); #if 0 printf ("In build_EDG_CommandLine(): setting __cplusplus: this = %p get_Cxx11_only() = %s \n",this,get_Cxx11_only() ? "true" : "false"); #endif // DQ (5/9/2016): This is a fix for the Intel specific C++11 support. if (get_Cxx11_only() == true) { // DQ (5/10/2016): This allows some C++11 specific header files to work with the Intel compiler (see Cxx11_tests/test2016_32.C). // commandLine.push_back("-D__cplusplus=199711L"); commandLine.push_back("-D__cplusplus=201103L"); // DQ (5/10/2016): Added to support Intel v16 C++11 mode. commandLine.push_back("-D__SSE4_2__"); commandLine.push_back("-D__SSE4_1__"); commandLine.push_back("-D__SSSE3__"); commandLine.push_back("-D__SSE3__"); } else { if (get_Cxx14_only() == true) { #if 0 // DQ (2/21/2017): Not is is going into place, so we don't need this assertion. printf ("C++14 support for Intel compiler not implemented in ROSE yet! \n"); ROSE_ASSERT(false); #endif commandLine.push_back("-D__cplusplus=201400L"); } else { commandLine.push_back("-D__cplusplus=199711L"); } } #endif #ifdef BACKEND_CXX_IS_CLANG_COMPILER // DQ (4/13/2016): We need to define this explicitly for the Clang compiler. // Try letting EDG specify the value of this internal variable. // commandLine.push_back("-D__cplusplus=199711L"); #endif } #if 0 printf ("Exting as a test! \n"); ROSE_ASSERT(false); #endif } #if 1 // DQ (8/17/2015): Moved this specification of the boost path to after the generation of the -I include_dirs // to handle the case where a different version of boost is explicitly specified in the -I include_dirs. // This allows ROSE to reproduce the behavior of the GNU g++ and Intel icpc compilers. #ifdef ROSE_BOOST_PATH // Search dir for header files, after all directories specified by -I but before the standard system directories. #if 0 printf ("Adding (after -I include dirs) boost path = %s \n",ROSE_BOOST_PATH); #endif commandLine.push_back("--sys_include"); commandLine.push_back(std::string(ROSE_BOOST_PATH) + "/include"); #endif #endif #ifdef BACKEND_CXX_IS_GNU_COMPILER #if (ROSE_BOOST_VERSION >= 105800) // DQ (5/6/2016): Adding macro to control use of Boost in later versions of Bosot (1.58 and later). // Not clear if this is specific to GNU, but lets initially be conservative. commandLine.push_back("-DBOOST_NO_ALIGNMENT"); #endif #endif #if 0 printf ("Exting as a test! \n"); ROSE_ASSERT(false); #endif #ifdef ROSE_USE_EDG_QUAD_FLOAT commandLine.push_back("-DROSE_USE_EDG_QUAD_FLOAT"); #endif commandLine.insert(commandLine.end(), roseSpecificDefs.begin(), roseSpecificDefs.end()); // DQ (9/17/2006): We should be able to build a version of this code which hands a std::string to StringUtility::splitStringIntoStrings() // Separate the string into substrings consistent with the structure of argv command line input inputCommandLine = commandLine; #if 0 std::string tmp6_translatorCommandLineString = CommandlineProcessing::generateStringFromArgList(inputCommandLine,false,true); printf ("tmp6_translatorCommandLineString = %s \n",tmp6_translatorCommandLineString.c_str()); #endif // DQ (11/1/2011): Do we need this for the new EDG 4.3 work? inputCommandLine.insert(inputCommandLine.begin(), "dummy_argv0_for_edg"); if (get_C_only() == true) { // Add option to indicate use of C code (not C++) to EDG frontend, default will be C99 (changed 3/28/2013). inputCommandLine.push_back("--c"); } if (get_strict_language_handling() == true) { // DQ (4/26/2019): NOTE: this option appears to be incompatable with use of gnu_version. inputCommandLine.push_back("--strict"); } switch (get_standard()) { case e_default_standard: { break; // NOP } case e_c89_standard: { inputCommandLine.push_back("--c89"); break; } case e_c90_standard: { inputCommandLine.push_back("--c90"); break; } case e_c99_standard: { inputCommandLine.push_back("--c99"); break; } case e_c11_standard: { inputCommandLine.push_back("--c11"); break; } case e_c14_standard: { inputCommandLine.push_back("--c14"); break; } case e_c18_standard: { inputCommandLine.push_back("--c17"); break; } case e_upc_standard: { inputCommandLine.push_back("--upc"); break; } case e_cxx98_standard: // EDG does not provide an option to specify the C++ 98 standard, we specify the C++ 03 standard instead case e_cxx03_standard: { inputCommandLine.push_back("--c++03"); break; } case e_cxx11_standard: { inputCommandLine.push_back("--c++11"); break; } case e_cxx14_standard: { inputCommandLine.push_back("--c++14"); break; } case e_cxx17_standard: { inputCommandLine.push_back("--c++17"); break; } case e_cxx20_standard: { inputCommandLine.push_back("--c++20"); break; } case e_upcxx_standard: { inputCommandLine.push_back("--c++03"); break; } case e_f77_standard: case e_f90_standard: case e_f95_standard: case e_f03_standard: case e_f08_standard: case e_f18_standard: { break; // NOP (should not happen) } } if (get_Cxx_only() && is_gnu_standard()) { inputCommandLine.push_back("--g++"); } // // edg_new_frontend option // if ( CommandlineProcessing::isOption(argv,"-edg:","(new_frontend)",true) == true || (get_new_frontend() == true) ) { // printf ("option -edg:new_frontend found \n"); set_new_frontend(true); // if we use the new EDG frontend (not connected to SAGE) then we can't // generate C++ code so we don't want to call the C++ compiler // set_skipfinalCompileStep(true); } // // edg_KCC_frontend option // if ( CommandlineProcessing::isOption(argv,"-edg:","(KCC_frontend)",true) == true || (get_KCC_frontend() == true) ) { // printf ("option -edg:KCC_frontend found \n"); set_KCC_frontend(true); // if we use the new EDG frontend (not connected to SAGE) then we can't // generate C++ code so we don't want to call the C++ compiler set_skipfinalCompileStep(true); } // // edg_backend option // if ( CommandlineProcessing::isOption(argv,"-edg:","(disable_edg_backend)",true) == true || (get_disable_edg_backend() == true) ) { // printf ("option -edg:disable_edg_backend found \n"); set_disable_edg_backend(true); } #if 0 // // sage_backend option // if ( CommandlineProcessing::isOption(argv,"-edg:","(disable_edg_backend)",true) == true || (get_disable_edg_backend() == true) ) { // printf ("option -edg:disable_edg_backend found \n"); set_disable_edg_backend(true); } #endif #if 0 // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of argc optionCount = sla(&argc, argv, "-sage:", "($)", "(disable_sage_backend)",1); if( optionCount > 0 || (get_disable_sage_backend() == true) == true ) { printf ("option -sage:disable_sage_backend found \n"); set_disable_sage_backend(true); inputCommandLine.push_back("--disable_sage_backend"); // We we aren't going to process the code through the backend then there is nothing to compile set_skipfinalCompileStep(true); } // printf ("After processing -sage:disable_sage_backend option argc = %d \n",argc); #endif #if 0 // // cp_backend option // // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of agrc optionCount = sla(&argc, argv, "-sage:", "($)", "(enable_cp_backend)",1); if ( optionCount > 0 || (get_enable_cp_backend() == true) ) { // printf ("option -sage:enable_cp_backend found \n"); set_enable_cp_backend(true); inputCommandLine.push_back("--enable_cp_backend"); } // printf ("After processing -sage:enable_cp_backend option argc = %d \n",argc); // // preinit_il option // // Use 1 at end of argument list to SLA to force removal of option from argv and decrement of agrc optionCount = sla(&argc, argv, "-sage:", "($)", "(preinit_il)",1); if( optionCount > 0 || (get_preinit_il() == true)) { printf ("option -sage:preinit_il found \n"); set_preinit_il(true); inputCommandLine.push_back("--preinit_il"); } // printf ("After processing -sage:preinit_il option argc = %" PRIuPTR " \n",argv.size()); #endif // *********************************************************************** // Now process the -D options, -I options and the filenames so that these // can also be used for the command line passed to the EDG frontend. // *********************************************************************** // ******************************* // Add all input macro definitions // ******************************* vector<string> macroDefineOptions; // DQ (9/25/2006): Fixed handling of "-D DEFINE_ERROR_WITH_SPACE -DDEFINE_OK_WITHOUT_SPACE" // skip the 0th entry since this is just the name of the program (e.g. rose) unsigned int argIndex = 1; while (argIndex < argv.size()) { // most options appear as -<option> // have to process +w2 (warnings option) on some compilers so include +<option> if ( (argv[argIndex][0] == '-') && (argv[argIndex][1] == 'D') ) { unsigned int length = argv[argIndex].size(); // printf ("Look for include path: argv[%d] = %s length = %d \n",argIndex,argv[argIndex],length); macroDefineOptions.push_back(argv[argIndex]); // DQ (9/19/2006): There must be an option string associated with each "-D" option // ROSE_ASSERT(length > 2); if (length == 2) { printf ("Handling the case of \"-D\" with orphened option (unclear if this is legal) \n"); macroDefineOptions.push_back("-D" + argv[argIndex + 1]); ++argIndex; } } else { // DQ (8/27/2010): Added support for -U to undefine macros (same code as for -D option). if ( (argv[argIndex][0] == '-') && (argv[argIndex][1] == 'U') ) { unsigned int length = argv[argIndex].size(); // printf ("Look for include path: argv[%d] = %s length = %d \n",argIndex,argv[argIndex],length); macroDefineOptions.push_back(argv[argIndex]); if (length == 2) { printf ("Handling the case of \"-U\" with orphened option (unclear if this is legal) \n"); macroDefineOptions.push_back("-U" + argv[argIndex + 1]); ++argIndex; } } } argIndex++; } #if 0 for (int i=0; i < macroDefineOptionCounter; i++) { printf (" macroDefineOptions[%d] = %s \n",i,macroDefineOptions[i]); } #endif // Add filenames (of source files) to so that the EDG front end will know what files to process inputCommandLine.insert(inputCommandLine.end(), macroDefineOptions.begin(), macroDefineOptions.end()); // DQ (9/24/2006): Add -D option so that we can know when to turn on vendor compiler specific macros for ANSI/ISO compatability. if (get_strict_language_handling() == true) { inputCommandLine.push_back("-DROSE_STRICT_LANGUAGE_HANDLING"); } // ******************************************************************************************** // Now add the include paths to the end so that EDG knows where to find header files to process // ******************************************************************************************** // Now add the include paths to the end so that EDG knows where to find head files to process // Add all input include paths so that the EDG front end will know where to find headers #if 0 printf ("Include paths specified: \n"); int counter = 0; for (vector<string>::const_iterator i = includePaths.begin(); i != includePaths.end(); ++i) { printf (" includePaths[%d] = %s \n",counter++,(*i).c_str()); } #endif #if 0 // DQ (3/14/2015): This must be moved to before the compiler and system specific include and // sys_include paths so that header files with names that match compiler and system header // files will be used instead from the directories specified using the -I and sys_include options. // Add the -I definitions to the command line for (vector<string>::const_iterator i = includePaths.begin(); i != includePaths.end(); ++i) { inputCommandLine.push_back("-I" + *i); } #if 1 // PL (4/15/2014): In GCC's document about system headers (http://gcc.gnu.org/onlinedocs/cpp/System-Headers.html): // All directories named by -isystem are searched after all directories named by -I, no matter what their order was on the command line. // DQ (4/14/2014): Experiment with placing this here (after "-I" options). This is part of the // fix to supress redundant output of all "-i" paths as "-sys_include" options to EDG. if ( SgProject::get_verbose() > 1 ) { printf ("project->get_preincludeDirectoryList().size() = %" PRIuPTR " \n",project->get_preincludeDirectoryList().size()); } // This is the list of directories that have been referenced as "-isystem <directory>" on the original command line to the ROSE // translator. We translate these to "-sys_include <directory>" options to pass to EDG (since that is how EDG understands them). for (SgStringList::iterator i = project->get_preincludeDirectoryList().begin(); i != project->get_preincludeDirectoryList().end(); i++) { // Build the preinclude directory list if ( SgProject::get_verbose() > 1 ) { printf ("Building commandline: --sys_include %s \n",(*i).c_str()); } inputCommandLine.push_back("--sys_include"); inputCommandLine.push_back(*i); } #endif #endif // DQ (7/3/2013): Where are we in the command line. // inputCommandLine.push_back("--XXXXX"); // ******************************************************************* // Handle general edg options (-xxx) // ******************************************************************* // Strip out all the -edg:xxx options and put them into the edg command line as -xxx // Resets modifiedArgc and allocates memory to modifiedArgv Rose_STL_Container<string> edgOptionList = CommandlineProcessing::generateOptionList (argv,"-edg:"); CommandlineProcessing::addListToCommandLine(inputCommandLine,"-",edgOptionList); // DQ (7/3/2013): Where are we in the command line. // inputCommandLine.push_back("--AAA"); // DQ (12/18/2016): Add support to use the EDG frontend within ROSE to process the inout file and output the preprocessed version. // However, we want to suppress the output of declarations from our ROSE preinclude file, so that the output can be processed by ROSE. // In the case of the Intel comiler, we also want to include "-D__INTEL_CLANG_COMPILER" so that we take the simple trip through the // Intel comiler's header files that avoids complex builtin function handling (builtin functions that reference types defined in the // header files and which we could not define in our ROSE preinclude file). Rose_STL_Container<string>::iterator j = edgOptionList.begin(); while (j != edgOptionList.end()) { if (*j == "E") { // This is the EDG option "-E" obtained from the ROSE "-edg:E" option // We want to add the USE_ROSE_CPP_PROCESSING // CommandlineProcessing::addListToCommandLine(inputCommandLine,"-",edgOptionList); // Specify that we are using ROSE to process the input file using CPP (so that in our preinclude file we can skip all ROSE specific declarations. inputCommandLine.push_back("-DUSE_ROSE_CPP_PROCESSING"); #ifdef BACKEND_CXX_IS_INTEL_COMPILER // DQ (12/18/2016): In the case of using "-E" with the Intel backend compiler we need to // add -D__INTEL_CLANG_COMPILER so that we can take a path through the Intel header files // that avoids editing header Intel specific header files to handle builtin functions that // use types defined in the header files. inputCommandLine.push_back("-D__INTEL_CLANG_COMPILER"); #endif #if 0 printf ("Detected use of -edg:E option to enable the EDG CPP mode \n"); ROSE_ASSERT(false); #endif } j++; } // ******************************************************************* // Handle general edg options (--xxx) // ******************************************************************* // Strip out all the -edg:xxx options and put them into the edg command line as --xxx // Resets modifiedArgc and allocates memory to modifiedArgv edgOptionList = CommandlineProcessing::generateOptionList (argv,"--edg:"); // DQ (7/3/2013): Where are we in the command line. // inputCommandLine.push_back("--BBB"); // DQ (8/6/2006): there are a number of options that when specified in their EDG forms // should turn on ROSE mechanisms. "--edg:c" should turn on C mode in ROSE. // printf ("--edg option processing: edgOptionList.size() = %" PRIuPTR " \n",edgOptionList.size()); Rose_STL_Container<string>::iterator i = edgOptionList.begin(); while (i != edgOptionList.end()) { // fprintf (stderr, "edgOptionList: i = %s \n",i->c_str()); if (*i == "c" || *i == "old_c") { // This is the EDG option "--c" obtained from the ROSE "--edg:c" option set_C_only(true); } // DQ (3/28/2013): Added support for specify C89 behavior so that default could be C99 (as in EDG3x branch). if (*i == "c89") { // This is the EDG option "--c89" obtained from the ROSE "--edg:c89" option set_C89_only(); } if (*i == "c99") { // This is the EDG option "--c99" obtained from the ROSE "--edg:c99" option set_C99_only(); } i++; } // DQ (7/3/2013): Where are we in the command line. // inputCommandLine.push_back("--CCC"); // Note: this is where options such as "--no_warnings --restrict" are added. CommandlineProcessing::addListToCommandLine(inputCommandLine,"--",edgOptionList); // DQ (3/6/2017): Adding support to read the ROSE options data structure to trigger suppression of warnings. // printf ("In build_EDG_CommandLine(): get_output_warnings() = %s \n",get_output_warnings() ? "true" : "false"); if (Rose::global_options.get_frontend_warnings()) { // The EDG default is to output warnings (so we need not do anything to adjust the command line). set_output_warnings(true); } else { // Turn off all warnings. inputCommandLine.push_back("--no_warnings"); } #if 0 std::string tmp0_argString = CommandlineProcessing::generateStringFromArgList(inputCommandLine,false,false); printf ("In build_EDG_CommandLine(): Input Command Line Arguments: \n%s \n",tmp0_argString.c_str()); printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif // DQ (7/3/2013): Where are we in the command line. // inputCommandLine.push_back("--DDD"); // ******************************************************************* // Handle general edg options (-xxx abc) // ******************************************************************* // Handle edg options taking a parameter (string or integer) edgOptionList = CommandlineProcessing::generateOptionWithNameParameterList (argv,"-edg_parameter:"); CommandlineProcessing::addListToCommandLine(inputCommandLine,"-",edgOptionList); // ******************************************************************* // Handle general edg options (--xxx abc) // ******************************************************************* #if 0 std::string tmp1_argString = CommandlineProcessing::generateStringFromArgList(inputCommandLine,false,false); printf ("In build_EDG_CommandLine(): Input Command Line Arguments (BEFORE): \n%s \n",tmp1_argString.c_str()); #endif // Handle edg options taking a parameter (string or integer) edgOptionList = CommandlineProcessing::generateOptionWithNameParameterList (argv,"--edg_parameter:"); #if 0 for (size_t i = 0; i < edgOptionList.size(); i++) { printf ("edgOptionList[%zu] = %s \n",i,edgOptionList[i].c_str()); } #endif CommandlineProcessing::addListToCommandLine(inputCommandLine,"--",edgOptionList); #if 0 std::string tmp2_argString = CommandlineProcessing::generateStringFromArgList(inputCommandLine,false,false); printf ("In build_EDG_CommandLine(): Input Command Line Arguments (AFTER): \n%s \n",tmp2_argString.c_str()); #endif #if 0 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif #if 0 // DQ (1/21/2017): This does not appear to work since EDG reports: Command-line error: invalid option: --error_limit 200 printf ("Increase the number of errors that we permit to be output \n"); // inputCommandLine.push_back("--error_limit 20"); // inputCommandLine.push_back("-e 20"); // inputCommandLine.push_back("--error_limit 200"); #endif // ******************************************************************* // Handle UPC modes // ******************************************************************* // DQ (9/19/2010): Added UPC++ mode (UPC (C modes) should have UPC++ == false. // Liao, 6/20/2008, handle UPC specific EDG options. // Generate --upc // if (get_UPC_only()) if ((get_UPC_only() == true) && (get_UPCxx_only() == false)) { inputCommandLine.push_back("--upc"); inputCommandLine.push_back("--restrict"); } // DQ (9/19/2010): Added support for UPC++. Previously the UPC used the C++ language internally this had to // be put back to C to provide less strict type-checking and so the new UPC++ option allows us to continue // to play with UPC++ as an idea for future work. This modes will also have (UPC == true). // Generate --upc++ if (get_UPCxx_only() == true) { // DQ (9/19/2010): Testing use of newly added EDG option to control use // of C_dialect to allow C++ with UPC (which defines initial UPC++ work). inputCommandLine.push_back("--upc++"); inputCommandLine.push_back("--restrict"); } // Generate --upc_threads n int intOptionUpcThreads = get_upc_threads(); if (intOptionUpcThreads > 0) { stringstream ss; ss << intOptionUpcThreads; inputCommandLine.push_back("--upc_threads"); inputCommandLine.push_back(ss.str()); } // DQ (7/3/2013): Where are we in the command line. // inputCommandLine.push_back("--YYYYY"); // ******************************************************************* // Some EDG options have to turn on mechanism in ROSE // ******************************************************************* #if 0 printf ("Some EDG options have to turn on mechanims in ROSE edgOptionList.size() = %ld \n",edgOptionList.size()); Rose_STL_Container<string>::iterator j = edgOptionList.begin(); while (j != edgOptionList.end()) { printf ("edgOptionList: j = %s \n",j->c_str()); j++; } #endif // ******************************************************************* // Handle specific edg options (-c) // ******************************************************************* // // specify compilation only option (new style command line processing) // bool autoInstantiation = false; if ( CommandlineProcessing::isOption(argv,"-","c",false) == true ) { #if 0 printf ("In build_EDG_CommandLine(): Option -c found (compile only)! \n"); #endif set_compileOnly(true); } else { // printf ("In build_EDG_CommandLine(): Option -c not found (compile AND link) set autoInstantiation = true ... \n"); autoInstantiation = true; } if ( CommandlineProcessing::isOption(argv,"-rose:","wave",ROSE_WAVE_DEFAULT) == true ) { // printf ("Option -rose:wave found (use of Boost wave library)! \n"); set_wave(true); } if (isPrelinkPhase() == true) { printf ("In build_EDG_CommandLine(): isPrelinkPhase() == true set autoInstantiation = true ... \n"); autoInstantiation = true; } // DQ (10/15/2005): Trap out case of C programs where it is an EDG error to specify template instantiation details // if (get_C_only() == true || get_C99_only() == true ) if (get_C_only() == true || get_C89_only() == true || get_C99_only() == true || get_C11_only() == true ) { // printf ("In build_EDG_CommandLine(): compiling input as C program so turn off all template instantiation details \n"); autoInstantiation = false; } Rose_STL_Container<string> additionalOptions_a; Rose_STL_Container<string> additionalOptions_b; if (autoInstantiation == true) { // printf ("In build_EDG_CommandLine(): autoInstantiation = true adding --auto_instantiation -tused ... \n"); // Even though this is not an error to EDG, it does not appear to force instantiation of all templates (because we need "-tused") additionalOptions_a.push_back("auto_instantiation"); CommandlineProcessing::addListToCommandLine(inputCommandLine,"--",additionalOptions_a); // DQ (5/12/05): Set the instantiation mode to "used" for specify what sort of templates to instantiate automatically // (generate "-tused" instead of "--instantiate used" since EDG does not seems to accept options containing white space). additionalOptions_b.push_back("tused"); CommandlineProcessing::addListToCommandLine(inputCommandLine, "-",additionalOptions_b); } else { // There are additional cases where we want to force instantiation of all used templates. // DQ (5/20/2005): Force instantiation of all used templated unless it is specified to instantiate no templates (explicitly to ROSE) bool instantiateAll = false; if (get_project() != NULL) { instantiateAll = (get_project()->get_template_instantiation_mode() == SgProject::e_default) || (get_project()->get_template_instantiation_mode() == SgProject::e_used) || (get_project()->get_template_instantiation_mode() == SgProject::e_all) || (get_project()->get_template_instantiation_mode() == SgProject::e_local); } // printf ("get_project()->get_template_instantiation_mode() = %d \n",get_project()->get_template_instantiation_mode()); // printf ("In build_EDG_CommandLine(): instantiateAll = %s if true then adding --auto_instantiation -tlocal ... \n", // instantiateAll ? "true" : "false"); // DQ (6/1/2005): This is the case of explicitly specifying the complation of C code and // not C++ code (EDG reports an error if auto_instantiation is specified for this case). if (get_C_only() == true || get_C99_only() == true) { // printf ("In build_EDG_CommandLine(): compiling input as C program so turn off all template instantiation details \n"); instantiateAll = false; } #if 1 // DQ (7/3/2013): COMMENTED OUT: Trying to debug Boost handling when EDG is configured to support GNU g++ version 4.4.5. if (instantiateAll == true) { // printf ("In build_EDG_CommandLine(): autoInstantiation = true adding --auto_instantiation -tlocal ... \n"); additionalOptions_a.push_back("auto_instantiation"); CommandlineProcessing::addListToCommandLine(inputCommandLine,"--",additionalOptions_a); // additionalOptions_b.push_back("tused"); additionalOptions_b.push_back("tlocal"); CommandlineProcessing::addListToCommandLine(inputCommandLine, "-",additionalOptions_b); } #else printf ("In build_EDG_CommandLine(): ######### TURNED OFF autoInstantiation ########## \n"); #endif } #if 0 // DQ (5/20/05): Set the instantiation mode to "used" for specify what sort of templates to instantiate automatically // (generate "-tused" instead of "--instantiate used" since EDG does not seems to accept options containing white space). printf ("In build_EDG_CommandLine(): autoInstantiation = true adding --auto_instantiation -tused ... \n"); // Even though this is not an error to EDG, it does not appear to force instantiation of all templates (because we need "-tused") additionalOptions_a.push_back("auto_instantiation"); CommandlineProcessing::addListToCommandLine(inputCommandLine,"--",additionalOptions_a); additionalOptions_b.push_back("tused"); CommandlineProcessing::addListToCommandLine(inputCommandLine, "-",additionalOptions_b); #endif // printf ("###### Located source filename = %s \n",get_sourceFileNameWithPath().c_str()); // ROSE_ASSERT ( get_numberOfSourceFileNames() > 0 ); ROSE_ASSERT ( get_sourceFileNameWithPath().empty() == false); //AS Added support for absolute paths Rose_STL_Container<string> fileList; std::string sourceFile = get_sourceFileNameWithPath(); std::string sourceFilePath = StringUtility::getPathFromFileName(sourceFile); //Liao, 5/15/2009 //the file name already has absolute path, the following code may be redundant. sourceFile = StringUtility::stripPathFromFileName(sourceFile); if(sourceFilePath == "" ) sourceFilePath = "./"; sourceFilePath = StringUtility::getAbsolutePathFromRelativePath(sourceFilePath); #ifndef _MSC_VER fileList.push_back(sourceFilePath+"/"+sourceFile); #else fileList.push_back(sourceFilePath+"\\"+sourceFile); #endif CommandlineProcessing::addListToCommandLine(inputCommandLine,"",fileList); // Liao, replaceRelativePath #if 0 for (size_t i = 0; i< inputCommandLine.size(); i++) { string cur_string = inputCommandLine[i]; string::size_type pos = cur_string.find("-I..",0); string::size_type pos2 = cur_string.find("-I.",0); // replace -I.. -I../path to -I/absolutepath/.. and -I/absolutepath/../path // replace -I. -I./path to -I/absolutepath/. and -I/absolutepath/./path if ((pos ==0) || (pos2 ==0 )) { string orig_path = cur_string.substr(2); // get .. ../path . ./path cur_string = "-I"+sourceFilePath+"/"+orig_path; } inputCommandLine[i] = cur_string; } #endif //Liao, 5/15/2009 // macro -D__GNUG__ should not be defined for C only code, // some code relies on this macro to tell if bool type is allowed // vector<string> & inputCommandLine if (get_C_only() || get_C99_only()) { vector<string>::iterator iter; for (iter = inputCommandLine.begin(); iter!=inputCommandLine.end(); iter++) { string cur_str = *iter; string::size_type pos = cur_str.find("-D__GNUG__=",0); if (pos != string::npos) break; } if (iter != inputCommandLine.end()) { inputCommandLine.erase(iter); } } // Debugging (verbose) output // if ( (get_verbose() >= 0) ) if ( (get_verbose() > 1) ) { std::string argString = CommandlineProcessing::generateStringFromArgList(inputCommandLine,false,false); printf ("In build_EDG_CommandLine(): Input Command Line Arguments: \n%s \n",argString.c_str()); // Alternative way of displaying the commandline parameters for (unsigned int i=0; i < inputCommandLine.size(); i++) printf ("inputCommandLine[%u] = %s \n",i,inputCommandLine[i].c_str()); } // display("at base of build_EDG_CommandLine()"); #if 0 std::string tmp7_translatorCommandLineString = CommandlineProcessing::generateStringFromArgList(inputCommandLine,false,true); printf ("Leaving build_EDG_CommandLine(): tmp7_translatorCommandLineString = %s \n",tmp7_translatorCommandLineString.c_str()); #endif #if 0 printf ("Exiting at base of build_EDG_CommandLine() \n"); ROSE_ABORT(); #endif } vector<string> SgFile::buildCompilerCommandLineOptions ( vector<string> & argv, int fileNameIndex, const string& compilerName ) { // This function assembles the commandline that will be passed to the backend (vendor) C++/C, Fortran, or Java compiler // (using the new generated source code from the ROSE unparser). // DQ (4/21/2006): I think we can now assert this! ROSE_ASSERT(fileNameIndex == 0); // display("Data in SgFile in buildCompilerCommandLineOptions()"); #define DEBUG_COMPILER_COMMAND_LINE 0 #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions(): compilerName = %s \n",compilerName.c_str()); #endif if ( SgProject::get_verbose() > 0 ) { printf ("In buildCompilerCommandLineOptions(): compilerName = %s \n",compilerName.c_str()); } // To use rose in place of a C or C++ compiler specify the compiler name using // rose -compiler <originalCompilerName> ... // the default value of "originalCompilerName" is "CC" vector<string> compilerNameString; compilerNameString.push_back(compilerName); // TOO1 (2014-10-09): Use the correct Boost version that ROSE was configured --with-boost #ifdef ROSE_BOOST_PATH // DQ (4/13/2015): Only add boost path for C++ applications, never for C applications // (though this does not to have ever caused an error that I know of). // if (get_C_only() || get_Cxx_only()) // TV (01/08/2019): with ubuntu 18.04 using default boost, this causes an issue if (get_Cxx_only() == true && std::string(ROSE_BOOST_PATH) != "/usr") { // Search dir for header files, after all directories specified by -I but // before the standard system directories. compilerNameString.push_back("-isystem"); compilerNameString.push_back(std::string(ROSE_BOOST_PATH) + "/include"); } #endif // DQ (1/17/2006): test this // ROSE_ASSERT(get_fileInfo() != NULL); #if 0 display("SgFile::buildCompilerCommandLineOptions()"); #endif #if 0 printf ("In buildCompilerCommandLineOptions(): compilerName = %s \n",compilerName.c_str()); printf (" --- C compiler = %s \n",BACKEND_C_COMPILER_NAME_WITH_PATH); printf (" --- C++ compiler = %s \n",BACKEND_CXX_COMPILER_NAME_WITH_PATH); printf (" --- Fortran compiler = %s \n",BACKEND_FORTRAN_COMPILER_NAME_WITH_PATH); printf (" --- Java compiler = %s \n",BACKEND_JAVA_COMPILER_NAME_WITH_PATH); printf (" --- Python interpreter = %s \n",BACKEND_PYTHON_INTERPRETER_NAME_WITH_PATH); printf (" --- get_C_only() = %s \n",(get_C_only() == true) ? "true" : "false"); printf (" --- get_C99_only() = %s \n",(get_C99_only() == true) ? "true" : "false"); printf (" --- get_C11_only() = %s \n",(get_C11_only() == true) ? "true" : "false"); printf (" --- get_C14_only() = %s \n",(get_C14_only() == true) ? "true" : "false"); printf (" --- get_Cxx_only() = %s \n",(get_Cxx_only() == true) ? "true" : "false"); printf (" --- get_Cxx11_only() = %s \n",(get_Cxx11_only() == true) ? "true" : "false"); printf (" --- get_Cxx14_only() = %s \n",(get_Cxx14_only() == true) ? "true" : "false"); printf (" --- get_Fortran_only() = %s \n",(get_Fortran_only() == true) ? "true" : "false"); printf (" --- get_F77_only() = %s \n",(get_F77_only() == true) ? "true" : "false"); printf (" --- get_F90_only() = %s \n",(get_F90_only() == true) ? "true" : "false"); printf (" --- get_F95_only() = %s \n",(get_F95_only() == true) ? "true" : "false"); printf (" --- get_F2003_only() = %s \n",(get_F2003_only() == true) ? "true" : "false"); printf (" --- get_F2008_only() = %s \n",(get_F2008_only() == true) ? "true" : "false"); printf (" --- get_CoArrayFortran_only() = %s \n",(get_CoArrayFortran_only() == true) ? "true" : "false"); printf (" --- get_Java_only() = %s \n",(get_Java_only() == true) ? "true" : "false"); printf (" --- get_Python_only() = %s \n",(get_Python_only() == true) ? "true" : "false"); #endif // For now let's enforce this, for internal testing, but translators will fail for this assertion in the future. if (get_inputLanguage() != get_outputLanguage()) { printf ("Error: In buildCompilerCommandLineOptions(): get_inputLanguage() = %d get_outputLanguage() = %d \n",get_inputLanguage(),get_outputLanguage()); printf ("Error: In buildCompilerCommandLineOptions(): get_inputLanguage() = %s get_outputLanguage() = %s \n", get_outputLanguageOptionName(get_inputLanguage()).c_str(),get_outputLanguageOptionName(get_outputLanguage()).c_str()); } ROSE_ASSERT(get_inputLanguage() == get_outputLanguage()); #if 0 printf ("In buildCompilerCommandLineOptions(): before switch: get_outputLanguage() = %s \n",get_outputLanguageOptionName(get_outputLanguage()).c_str()); #endif switch (get_outputLanguage()) { case SgFile::e_error_language: { printf ("Error: SgFile::e_error_language detected in SgFile::buildCompilerCommandLineOptions() \n"); ROSE_ASSERT(false); } case SgFile::e_default_language: { #if 0 // DQ (11/13/2017): This fails for the case of binaries. printf ("Error: SgFile::e_default_language detected in SgFile::buildCompilerCommandLineOptions() \n"); ROSE_ASSERT(false); #endif } case SgFile::e_C_language: { compilerNameString[0] = BACKEND_C_COMPILER_NAME_WITH_PATH; #if 0 printf ("In buildCompilerCommandLineOptions(): get_C99_only() = %s \n",get_C99_only() ? "true" : "false"); #endif if (get_Cuda_only() || get_OpenCL_only()) { std::cerr << "[WARN] No backend compiler for CUDA and OpenCL." << std::endl; } break; } case SgFile::e_Cxx_language: { #if 0 printf ("Error: SgFile::e_C_language or SgFile::e_Cxx_language detected in SgFile::buildCompilerCommandLineOptions() (unparser not implemented, unparsing ignored) \n"); #endif compilerNameString[0] = BACKEND_CXX_COMPILER_NAME_WITH_PATH; break; } // DQ (11/15/2017): Added case to support binary handling, but there is no tool that we run the output code through for a binary that is disassembled (I think). case SgFile::e_Binary_language: { // DQ (11/15/2017): Perhaps we should run the output through the gnu assembler? #if 0 printf ("SgFile::e_Binary_language detected in SgFile::buildCompilerCommandLineOptions(): nothing to do here! \n"); #endif break; } case SgFile::e_Fortran_language: { #if 0 printf ("Error: SgFile::e_Fortran_language detected in SgFile::buildCompilerCommandLineOptions() \n"); #endif compilerNameString[0] = ROSE_GFORTRAN_PATH; if (get_backendCompileFormat() == e_fixed_form_output_format) { // If backend compilation is specificed to be fixed form, then allow any line length (to simplify code generation for now) // compilerNameString += "-ffixed-form "; // compilerNameString += "-ffixed-line-length- "; // -ffixed-line-length-<n> compilerNameString.push_back("-ffixed-line-length-none"); } else { if (get_backendCompileFormat() == e_free_form_output_format) { // If backend compilation is specificed to be free form, then // allow any line length (to simplify code generation for now) // compilerNameString += "-ffree-form "; // compilerNameString += "-ffree-line-length-<n> "; // -ffree-line-length-<n> // compilerNameString.push_back("-ffree-line-length-none"); #if USE_GFORTRAN_IN_ROSE // DQ (9/16/2009): This option is not available in gfortran version 4.0.x (wonderful). if ((BACKEND_FORTRAN_COMPILER_MAJOR_VERSION_NUMBER >= 4) && (BACKEND_FORTRAN_COMPILER_MINOR_VERSION_NUMBER >= 1)) { compilerNameString.push_back("-ffree-line-length-none"); } #endif } else { // Do nothing (don't specify any option to control compilation of a specific format, assume defaults) // Make this the default if (SgProject::get_verbose() >= 1) { printf ("Compiling generated code using gfortran -ffixed-line-length-none to avoid 72 column limit in code generation\n"); } compilerNameString.push_back("-ffixed-line-length-none"); } } break; } case SgFile::e_Java_language: { printf ("Error: SgFile::e_Java_language detected in SgFile::buildCompilerCommandLineOptions() \n"); compilerNameString[0] = BACKEND_JAVA_COMPILER_NAME_WITH_PATH; break; } case SgFile::e_X10_language: { printf ("Error: SgFile::e_X10_language detected in SgFile::buildCompilerCommandLineOptions() \n"); compilerNameString[0] = BACKEND_X10_COMPILER_NAME_WITH_PATH; break; } case SgFile::e_Promela_language: { printf ("Error: SgFile::e_Promela_language detected in SgFile::buildCompilerCommandLineOptions() \n"); ROSE_ASSERT(false); break; } case SgFile::e_PHP_language: { printf ("Error: SgFile::e_PHP_language detected in SgFile::buildCompilerCommandLineOptions() \n"); ROSE_ASSERT(false); break; } case SgFile::e_Python_language: { printf ("Error: SgFile::e_Python_language detected in SgFile::buildCompilerCommandLineOptions() \n"); compilerNameString[0] = BACKEND_PYTHON_INTERPRETER_NAME_WITH_PATH; ROSE_ASSERT(false); break; } case SgFile::e_Csharp_language: { printf ("Error: SgFile::e_Csharp_language detected in SgFile::buildCompilerCommandLineOptions() \n"); // Rasmussen (11/14/2017): Added check to ensure that C# is configured #ifdef ROSE_EXPERIMENTAL_CSHARP_ROSE_CONNECTION compilerNameString[0] = BACKEND_CSHARP_COMPILER_NAME_WITH_PATH; #else ROSE_ASSERT(false); #endif break; } case SgFile::e_Ada_language: { printf ("Error: SgFile::e_Ada_language detected in SgFile::buildCompilerCommandLineOptions() \n"); // Rasmussen (11/14/2017): Added check to ensure that Ada is configured #ifdef ROSE_EXPERIMENTAL_ADA_ROSE_CONNECTION compilerNameString[0] = BACKEND_ADA_COMPILER_NAME_WITH_PATH; // DQ (9/12/2017): We need to add the "compile" option to the "gnat" command line ahead of the rest of the command line. compilerNameString.push_back("compile"); #else ROSE_ASSERT(false); #endif break; } case SgFile::e_Jovial_language: { // Rasmussen (11/14/2017): Added check to ensure that JOVIAL is configured #ifdef ROSE_EXPERIMENTAL_JOVIAL_ROSE_CONNECTION compilerNameString[0] = BACKEND_JOVIAL_COMPILER_NAME_WITH_PATH; #else ROSE_ASSERT(false); #endif break; } case SgFile::e_Cobol_language: { printf ("Error: SgFile::e_Cobol_language detected in SgFile::buildCompilerCommandLineOptions() \n"); // Rasmussen (11/14/2017): Added check to ensure that COBOL is configured #ifdef ROSE_EXPERIMENTAL_COBOL_ROSE_CONNECTION compilerNameString[0] = BACKEND_COBOL_COMPILER_NAME_WITH_PATH; #else ROSE_ASSERT(false); #endif break; } case SgFile::e_last_language: { printf ("Error: SgFile::e_last_language detected in SgFile::buildCompilerCommandLineOptions() \n"); ROSE_ASSERT(false); break; } default: { printf ("Error: default reached in SgFile::buildCompilerCommandLineOptions() (unknown output language specified) \n"); std::cerr << "[FATAL] Unknown backend compiler '" << compilerName << "', or not implemented." << std::endl; ROSE_ASSERT(! "Unknown backend compiler"); break; } } // TV (11/16/2018): ROSE-1529: new handling of standard specification switch (get_standard()) { case e_default_standard: { break; // NOP } case e_c89_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu89"); } else { compilerNameString.push_back("-std=c89"); } break; } case e_c90_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu90"); } else { compilerNameString.push_back("-std=c90"); } break; } case e_c99_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu99"); } else { compilerNameString.push_back("-std=c99"); } break; } case e_c11_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu11"); } else { compilerNameString.push_back("-std=c11"); } break; } case e_c14_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu14"); } else { compilerNameString.push_back("-std=c14"); } break; } // DQ (1/10/2019): Added support for C18 (newest C language standard). case e_c18_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu18"); } else { compilerNameString.push_back("-std=c18"); } break; } case e_cxx98_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu++98"); } else { compilerNameString.push_back("-std=c++98"); } break; } case e_cxx03_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu++03"); } else { compilerNameString.push_back("-std=c++03"); } break; } case e_cxx11_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu++11"); } else { compilerNameString.push_back("-std=c++11"); } break; } case e_cxx14_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu++14"); } else { compilerNameString.push_back("-std=c++14"); } break; } case e_cxx17_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu++17"); } else { compilerNameString.push_back("-std=c++17"); } break; } case e_cxx20_standard: { if (is_gnu_standard()) { compilerNameString.push_back("-std=gnu++20"); } else { compilerNameString.push_back("-std=c++20"); } break; } case e_f77_standard: case e_f90_standard: case e_f95_standard: case e_f03_standard: case e_f08_standard: case e_f18_standard: { break; // FIXME Does the Fortran frontend support -std option? } // DQ (1/10/2019): Added supporting case for UPC. case e_upc_standard: { #if 0 printf ("Case of UPC not supported in -std option mechanism \n"); #endif break; } // DQ (1/10/2019): Added supporting case for UPC++. case e_upcxx_standard: { #if 0 printf ("Case of UPC++ not supported in -std option mechanism \n"); #endif break; } // DQ (1/10/2019): Please add a default for your switch. // Plus there is no such thing as C17 (it is C18, as I recall). default: { printf ("Unhandled case in switch: get_standard() = %d = %s \n",get_standard(),display_standard(get_standard()).c_str()); ROSE_ASSERT(false); } } // printf ("compilerName = %s \n",compilerName); // printf ("compilerNameString = %s \n",compilerNameString.c_str()); // DQ (3/15/2017): This is the wrong way to handl this since the compiler name can be anything. // Note: ROSE Matrix Testing using "icpc-16.03" instead of "icpc" (and so was a problem for this code below). // tps (28 Aug 2008) : changed this so it does not pick up mpicc for icc // string name = StringUtility::stripPathFromFileName(compilerNameString[0]); // if (name == "icc") // { // This is the Intel C compiler: icc, we need to add the -restrict option // compilerNameString.push_back("-restrict"); // } // if (name == "icpc") // { // This is the Intel C++ compiler: icc, we need to add the -restrict option // compilerNameString.push_back("-restrict"); // } // DQ (3/15/2017): This is the correct way to handle compiler vendor specific details within ROSE. #if defined(BACKEND_CXX_IS_GNU_COMPILER) // Nothing is required for restrict pointer handling on the GNU compiler command line. #endif #if defined(BACKEND_CXX_IS_CLANG_COMPILER) // Nothing is required for restrict pointer handling on the Clang compiler command line. #endif #if defined(BACKEND_CXX_IS_INTEL_COMPILER) // DQ (3/16/2017): Only turn this on for C and C++ modes (not for Fortran (or anything else). // DQ (3/15/2017): The intel compiler requires the use of the "-restrict" option to support the "restrict" keyword. if (get_C_only() == true || get_Cxx_only() == true) { compilerNameString.push_back("-restrict"); } else { // DQ (3/17/2017): It was a problem that C++11 was turned on for Fortran when using the Intel and Clang compilers (this code checks this). ROSE_ASSERT(get_C11_only() == false); ROSE_ASSERT(get_C14_only() == false); ROSE_ASSERT(get_Cxx11_only() == false); ROSE_ASSERT(get_Cxx14_only() == false); } #endif // DQ (9/24/2006): Not clear if we want this, if we just skip stripping it out then it will be passed to the backend directly! // But we have to add it in the case of "-rose:strict", so we have to add it uniformally and strip it from the input. if (get_strict_language_handling() == true) { // Check if it is appears as "-ansi" on the original commandline if ( CommandlineProcessing::isOption(argv,"-","ansi",false) == true ) { printf ("Option -ansi detected on the original commandline \n"); } else { // This is might be specific to GNU compilerNameString.push_back("-ansi"); } } #if DEBUG_COMPILER_COMMAND_LINE printf ("Selected compilerNameString.size() = %" PRIuPTR " compilerNameString = %s \n",compilerNameString.size(),StringUtility::listToString(compilerNameString).c_str()); #endif // Since we need to do this often, support is provided in the utility_functions.C // and we can simplify this code. std::string currentDirectory = getWorkingDirectory(); // printf ("In buildCompilerCommandLineOptions(): currentDirectory = %s \n",currentDirectory); if (get_C_only() || get_Cxx_only() || get_Fortran_only()) { // specify compilation only option (new style command line processing) if ( CommandlineProcessing::isOption(argv,"-","c",false) == true ) { #if DEBUG_COMPILER_COMMAND_LINE printf ("Option -c found (compile only)! \n"); #endif set_compileOnly(true); } else { // printf ("Option -c not found (compile AND link) ... \n"); // compilerNameString += " -c "; } // Liao, 2/13/2009. I think we should pass this macro to the backend compiler also // User programs may have rose-specific tweaks to enable ROSE translators to compile them // Part of solution to bug 316 : // https://outreach.scidac.gov/tracker/index.php?func=detail&aid=316&group_id=24&atid=185 compilerNameString.push_back("-DUSE_ROSE"); // DQ (1/29/2014): I think this still makes since when we want to make sure that the this is code that might be // special to the backend (e.g. #undef <some macros>). So make this active once again. // DQ (9/14/2013): We need to at times distinguish between the use of USE_ROSE and that this is the backend compilation. // This allows for code to be placed into input source code to ROSE and preserved (oops, this would not work since // any code in the macro that was not active in the frontend would not survive to be put into the generated code for // the backend). I don't think there is a way to not see code in the front-end, yet see it in the backend. compilerNameString.push_back("-DUSE_ROSE_BACKEND"); // Liao, 9/4/2009. If OpenMP lowering is activated. -D_OPENMP=OMPVERSION should be added // since we don't remove condition compilation preprocessing info. during OpenMP lowering if (get_openmp_lowering()||get_openmp()) { string ompmacro="-D_OPENMP="+ StringUtility::numberToString(OMPVERSION); compilerNameString.push_back(ompmacro); } } // DQ (3/31/2004): New cleaned up source file handling Rose_STL_Container<string> argcArgvList = argv; #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: After initialization: argcArgvList.size() = %" PRIuPTR " argcArgvList = %s \n",argcArgvList.size(),StringUtility::listToString(argcArgvList).c_str()); #endif // DQ (11/7/2018): I need to add some additional include directories to the generate backed compiler command line. // This is to support where #include "../file.h" are used and we need to specify the directory of the original source // file (is we don't unparse the header file) or the directory where we are putting the generated source file, if we // are unparsing the header file. Not that nested header file using a similar specification may require the output of // additional include file specifications (is this true? If so then we need an example of this). #if 0 printf ("get_project()->get_includeDirectorySpecifierList().size() = %zu \n",get_project()->get_includeDirectorySpecifierList().size()); #endif // DQ (11/8/2018): Adding extra include paths identified as being required in the unparsing of headers, either for the source file or for otehr included headers (nested headers). const SgSourceFile* sourceFile = isSgSourceFile(this); // DQ (12/12/2018): This step to insert extra include paths only applies to source files, not binary files (caught in Jenkins testing). // ROSE_ASSERT(sourceFile != NULL); if (sourceFile != NULL) { #if 0 printf ("sourceFile->get_extraIncludeDirectorySpecifierList().size() = %zu \n",sourceFile->get_extraIncludeDirectorySpecifierList().size()); #endif argcArgvList.reserve(argcArgvList.size()+sourceFile->get_extraIncludeDirectorySpecifierList().size()); // argcArgvList = sourceFile->get_extraIncludeDirectorySpecifierList(); argcArgvList.insert(argcArgvList.end(),sourceFile->get_extraIncludeDirectorySpecifierList().begin(),sourceFile->get_extraIncludeDirectorySpecifierList().end()); } #if 0 printf ("@@@@@@@@@@@@@@@@@@@@ In buildCompilerCommandLineOptions: After initialization: argcArgvList.size() = %" PRIuPTR " argcArgvList = %s \n",argcArgvList.size(),StringUtility::listToString(argcArgvList).c_str()); #endif #if 0 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif // DQ (9/25/2007): Moved to std::vector from std::list uniformly within ROSE. // Remove the first argument (argv[0]) // argcArgvList.pop_front(); argcArgvList.erase(argcArgvList.begin()); #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: After argcArgvList.erase(argcArgvList.begin()): argcArgvList.size() = %" PRIuPTR " argcArgvList = %s \n",argcArgvList.size(),StringUtility::listToString(argcArgvList).c_str()); #endif #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: test 1: compilerNameString = \n%s\n",CommandlineProcessing::generateStringFromArgList(compilerNameString,false,false).c_str()); #endif #if DEBUG_COMPILER_COMMAND_LINE // DQ (1/24/2010): Moved this inside of the true branch below. // SgProject* project = isSgProject(this->get_parent()); SgProject* project = SageInterface::getProject(this); ROSE_ASSERT (project != NULL); Rose_STL_Container<string> sourceFilenames = project->get_sourceFileNameList(); printf ("sourceFilenames.size() = %" PRIuPTR " sourceFilenames = %s \n",sourceFilenames.size(),StringUtility::listToString(sourceFilenames).c_str()); #endif // DQ (4/20/2006): Modified to only do this when generating code and compiling it // Remove the source names from the argcArgvList (translated versions of these will be inserted later) // if (get_skip_unparse() == true && get_skipfinalCompileStep() == false) if (get_skip_unparse() == false) { // DQ (1/24/2010): Now that we have directory support, the parent of a SgFile does not have to be a SgProject. // SgProject* project = isSgProject(this->get_parent()) SgProject* project = TransformationSupport::getProject(this); ROSE_ASSERT (project != NULL); Rose_STL_Container<string> sourceFilenames = project->get_sourceFileNameList(); #if DEBUG_COMPILER_COMMAND_LINE printf ("sourceFilenames.size() = %" PRIuPTR " sourceFilenames = %s \n",sourceFilenames.size(),StringUtility::listToString(sourceFilenames).c_str()); #endif for (Rose_STL_Container<string>::iterator i = sourceFilenames.begin(); i != sourceFilenames.end(); i++) { #if DEBUG_COMPILER_COMMAND_LINE printf ("Removing sourceFilenames list element i = %s \n",(*i).c_str()); #endif #if USE_ABSOLUTE_PATHS_IN_SOURCE_FILE_LIST #error "USE_ABSOLUTE_PATHS_IN_SOURCE_FILE_LIST is not supported yet" // DQ (9/1/2006): Check for use of absolute path and convert filename to absolute path if required bool usesAbsolutePath = ((*i)[0] == '/'); if (usesAbsolutePath == false) { string targetSourceFileToRemove = StringUtility::getAbsolutePathFromRelativePath(*i); printf ("Converting source file to absolute path to search for it and remove it! targetSourceFileToRemove = %s \n",targetSourceFileToRemove.c_str()); argcArgvList.remove(targetSourceFileToRemove); } else { // printf ("This source file used the absolute path so no conversion to absolute path is required! \n"); argcArgvList.remove(*i); } #else // DQ (9/25/2007): Moved to std::vector from std::list uniformally within ROSE. // printf ("Skipping test for absolute path removing the source filename as it appears in the source file name list file = % \n",i->c_str()); // argcArgvList.remove(*i); // The if here is to skip binaries that don't appear on the command line for those cases when a single project has both binaries and source code if (find(argcArgvList.begin(),argcArgvList.end(),*i) != argcArgvList.end()) { argcArgvList.erase(find(argcArgvList.begin(),argcArgvList.end(),*i)); } #endif } } #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: After removing source file name: argcArgvList.size() = %" PRIuPTR " argcArgvList = %s \n",argcArgvList.size(),StringUtility::listToString(argcArgvList).c_str()); // ROSE_ASSERT(false); #endif // DQ (3/6/2017): Adding support to read the ROSE options data structure to trigger suppression of warnings. // printf ("In build_EDG_CommandLine(): get_output_warnings() = %s \n",get_output_warnings() ? "true" : "false"); if (Rose::global_options.get_backend_warnings()) { // The EDG default is to output warnings (so we need not do anything to adjust the command line). // set_output_warnings(true); } else { // Turn off all warnings. #if 0 printf ("Build -w option for some backend language compilers \n"); #endif // DQ (9/7/2017): Avoid use of "-w" on other language compilers as well. // DQ (3/7/2017): Avoid use of "-w" on X10 compiler. // if (get_X10_only() == false) if (get_X10_only() == false && get_Csharp_only() == false && get_Ada_only() == false && get_Jovial_only() == false && get_Cobol_only() == false) { // This is a portable way to turn off warnings in the backend compilers (GNU, Intel, Clang). argcArgvList.push_back("-w"); } else { // X10 command line generation using "-w" will cause X10 compiler to fail. } } #if 0 printf ("In buildCompilerCommandLineOptions(): After adding options from Rose::global_options: argcArgvList.size() = %" PRIuPTR " argcArgvList = %s \n", argcArgvList.size(),StringUtility::listToString(argcArgvList).c_str()); #endif #if 0 printf ("Exitng as a test! \n"); ROSE_ASSERT(false); #endif bool objectNameSpecified = false; for (Rose_STL_Container<string>::iterator i = argcArgvList.begin(); i != argcArgvList.end(); i++) { if (i->substr(0,2) == "-o") { // DQ (6/12/2005): Added error checking! if (objectNameSpecified == true) { // Error: "-o" has been specified twice printf ("Error: In SgFile::buildCompilerCommandLineOptions: \"-o \" has been specified twice \n"); ROSE_ASSERT(false); } else { // argcArgvList.erase(find(argcArgvList.begin(),argcArgvList.end(),*i)); Rose_STL_Container<string>::iterator j = i; j++; ROSE_ASSERT(j != argcArgvList.end()); #if DEBUG_COMPILER_COMMAND_LINE printf ("In SgFile::buildCompilerCommandLineOptions: Found object file as specified = %s \n",(*j).c_str()); #endif set_objectFileNameWithPath(*j); } ROSE_ASSERT(objectNameSpecified == false); objectNameSpecified = true; } } #if DEBUG_COMPILER_COMMAND_LINE printf ("get_objectFileNameWithPath().length() = %zu \n",get_objectFileNameWithPath().length()); #endif if (get_objectFileNameWithPath().length() > 0) { // Liao 5/5/2015, handle single and multiple files the same way // This is needed only if we see the combined compilation and linking (without -c specified) if (!get_compileOnly()) // if (get_multifile_support() == true) { // Strip the -o <file> option and subsitute a *.o file based on the source file name. #if DEBUG_COMPILER_COMMAND_LINE printf ("get_objectFileNameWithPath() = %s: get_multifile_support() == true: Strip the -o <file> option and subsitute a *.o file based on the source file name \n",get_objectFileNameWithPath().c_str()); #endif // DQ (5/27/2015): We need to save the strings instead of the iterators that reference the strings. // The more direct use of strings instead of iterator values that reference the strings will eliminate // the iterator invalidation that occurse in the loop over the deleteList to remove the strings from // the argcArgvList. // std::vector<Rose_STL_Container<string>::iterator> deleteList; std::vector<string> deleteList; for (Rose_STL_Container<string>::iterator i = argcArgvList.begin(); i != argcArgvList.end(); i++) { if (i->substr(0,2) == "-o") { // argcArgvList.erase(find(argcArgvList.begin(),argcArgvList.end(),*i)); #if 0 printf ("Add to delete list: *i = %s \n",(*i).c_str()); #endif // deleteList.push_back(i); deleteList.push_back(*i); #if 0 for (size_t k = 0; k < deleteList.size(); k++) { // printf ("deleteList[k=%zu] = %s \n",k,(*deleteList[k]).c_str()); printf ("deleteList[k=%zu] = %s \n",k,deleteList[k].c_str()); } #endif Rose_STL_Container<string>::iterator j = i; j++; #if 0 printf ("Add to delete list: *j = %s \n",(*j).c_str()); #endif // deleteList.push_back(j); deleteList.push_back(*j); #if 0 for (size_t k = 0; k < deleteList.size(); k++) { // printf ("deleteList[k=%zu] = %s \n",k,(*deleteList[k]).c_str()); printf ("deleteList[k=%zu] = %s \n",k,deleteList[k].c_str()); } #endif } } // for (std::vector<Rose_STL_Container<string>::iterator>::iterator i = deleteList.begin(); i != deleteList.end(); i++) for (std::vector<string>::iterator i = deleteList.begin(); i != deleteList.end(); i++) { #if 0 // printf ("Deleting *i = %s \n",(*(*i)).c_str()); printf ("Deleting *i = %s \n",(*i).c_str()); #endif // argcArgvList.erase(find(argcArgvList.begin(),argcArgvList.end(),*(*i))); argcArgvList.erase(find(argcArgvList.begin(),argcArgvList.end(),*i)); } // Next we add a new object file specification based on the source file name. A later step will // build the link line using the executable name from the original -o <file> specification. } #if 0 //Liao 5/5/2015, handle single and multiple files the same way else { #if DEBUG_COMPILER_COMMAND_LINE printf ("get_objectFileNameWithPath() = %s: get_multifile_support() == false: leaving the originally specified -o output option in place \n",get_objectFileNameWithPath().c_str()); #endif } #endif } #if DEBUG_COMPILER_COMMAND_LINE || 0 printf ("In buildCompilerCommandLineOptions: After processing executable specification: argcArgvList.size() = %" PRIuPTR " argcArgvList = %s \n",argcArgvList.size(),StringUtility::listToString(argcArgvList).c_str()); // ROSE_ASSERT(false); #endif #if 0 printf ("Exiting as a test! \n"); ROSE_ASSERT(false); #endif #if 0 // AS(080704) Fix so that if user specifies name of -o file rose do not specify another in addition bool objectNameSpecified = false; for (Rose_STL_Container<string>::iterator i = argcArgvList.begin(); i != argcArgvList.end(); i++) { // printf ("In SgFile::buildCompilerCommandLineOptions(): Loop over commandline arguments i = %s \n",i->c_str()); // DQ (8/17/2006): This fails for directories such as "ROSE/projects/OpenMP_Translator/tests/npb2.3-omp-c" // which can be repeated in the specification of include directives on the commandline. // We need to check for the leading characters and nothing else. // if (i->find("-o") != std::string::npos) // if (i->find("-o ") != std::string::npos) // printf ("i->substr(0,2) = %s \n",i->substr(0,2).c_str()); if (i->substr(0,2) == "-o") { // DQ (6/12/2005): Added error checking! if (objectNameSpecified == true) { // Error: "-o" has been specified twice printf ("Error: In buildCompilerCommandLineOptions: \"-o \" has been specified twice \n"); } ROSE_ASSERT(objectNameSpecified == false); objectNameSpecified = true; } } #endif #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: objectNameSpecified = %s \n",objectNameSpecified ? "true" : "false"); #endif Rose_STL_Container<string> tempArgcArgv; for (Rose_STL_Container<string>::iterator i = argcArgvList.begin(); i != argcArgvList.end(); i++) { // Liao, 11/19/2009 // We now only handles compilation for SgFile::compileOutput(), // so we need to remove linking related flags such as '-lxx' from the original command line // Otherwise gcc will complain: -lm: linker input file unused because linking not done if (i->substr(0,2) != "-l") { tempArgcArgv.push_back(*i); } } argcArgvList.swap(tempArgcArgv); // DQ (4/14/2005): Fixup quoted strings in args fix "-DTEST_STRING_MACRO="Thu Apr 14 08:18:33 PDT 2005" // to be -DTEST_STRING_MACRO=\""Thu Apr 14 08:18:33 PDT 2005"\" This is a problem in the compilation of // a Kull file (version.cc), when the backend is specified as /usr/apps/kull/tools/mpig++-3.4.1. The // problem is that /usr/apps/kull/tools/mpig++-3.4.1 is a wrapper for a shell script /usr/local/bin/mpiCC // which does not tend to observe quotes well. The solution is to add additional escaped quotes. for (Rose_STL_Container<string>::iterator i = argcArgvList.begin(); i != argcArgvList.end(); i++) { #if 0 printf ("sizeof(std::string::size_type) = %d \n",sizeof(std::string::size_type)); printf ("sizeof(std::string::iterator) = %d \n",sizeof(std::string::iterator)); printf ("sizeof(unsigned int) = %d \n",sizeof(unsigned int)); printf ("sizeof(unsigned long) = %d \n",sizeof(unsigned long)); #endif // DQ (1/26/2006): Fix for 64 bit support. // unsigned int startingQuote = i->find("\""); std::string::size_type startingQuote = i->find("\""); if (startingQuote != std::string::npos) { // This string at least has a quote // unsigned int endingQuote = i->rfind("\""); std::string::size_type endingQuote = i->rfind("\""); #if 0 printf ("startingQuote = %" PRIuPTR " endingQuote = %" PRIuPTR " \n",startingQuote,endingQuote); #endif // There should be a double quote on both ends of the string ROSE_ASSERT (endingQuote != std::string::npos); // DQ (11/1/2012): Fixed bug in use of STL string::substr() function (2nd parameter should be the size, not the end position). // std::string quotedSubstring = i->substr(startingQuote,endingQuote); // printf ("quotedSubstring = %s \n",quotedSubstring.c_str()); // std::string quotedSubstringWithoutQuotes = i->substr(startingQuote,endingQuote); std::string::size_type substringWithoutQuotesSize = ((endingQuote-1) - (startingQuote+1)) + 1; #if 0 printf ("substringWithoutQuotesSize = %" PRIuPTR " \n",substringWithoutQuotesSize); #endif // Generate the string without quotes so that we can rebuild the quoted string. // This is more critical if there were escpes before the quotes in the original string. std::string quotedSubstringWithoutQuotes = i->substr(startingQuote+1,substringWithoutQuotesSize); #if 0 printf ("quotedSubstringWithoutQuotes = %s \n",quotedSubstringWithoutQuotes.c_str()); #endif // DQ (11/1/2012): Robb has suggested using single quote instead of double quotes here. // This is a problem for the processing of mutt (large C application). But I didn't have // to do this to get it to work properly. It still might be a good alternative. // std::string fixedQuotedSubstring = std::string("\\\"") + quotedSubstring + std::string("\\\""); // std::string fixedQuotedSubstring = std::string("\\\'") + quotedSubstring + std::string("\\\'"); // std::string fixedQuotedSubstring = std::string("\'") + quotedSubstring + std::string("\'"); // std::string fixedQuotedSubstring = std::string("\\'") + quotedSubstring + std::string("\\'"); // std::string fixedQuotedSubstring = std::string("\\") + quotedSubstringWithoutQuotes + std::string("\\"); // std::string fixedQuotedSubstring = std::string("\\\"") + quotedSubstringWithoutQuotes + std::string("\\\""); std::string fixedQuotedSubstring = std::string("\"") + quotedSubstringWithoutQuotes + std::string("\""); #if 0 printf ("fixedQuotedSubstring = %s \n",fixedQuotedSubstring.c_str()); #endif // Now replace the quotedSubstring with the fixedQuotedSubstring // i->replace(startingQuote,endingQuote,fixedQuotedSubstring); i->replace(startingQuote,endingQuote,fixedQuotedSubstring); #if 0 printf ("Modified argument = %s \n",(*i).c_str()); #endif } } #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: test 2: compilerNameString = \n%s\n",CommandlineProcessing::generateStringFromArgList(compilerNameString,false,false).c_str()); printf ("argcArgvList.size() = %" PRIuPTR " \n",argcArgvList.size()); printf ("In buildCompilerCommandLineOptions: test 2: argcArgvList = \n%s\n",CommandlineProcessing::generateStringFromArgList(argcArgvList,false,false).c_str()); #endif // Add any options specified by the user (and add space at the end) compilerNameString.insert(compilerNameString.end(), argcArgvList.begin(), argcArgvList.end()); // printf ("buildCompilerCommandLineOptions() #1: compilerNameString = \n%s \n",compilerNameString.c_str()); std::string sourceFileName = get_sourceFileNameWithPath(); std::string oldFileNamePathOnly = Rose::getPathFromFileName(sourceFileName.c_str()); std::string oldFileName = Rose::utility_stripPathFromFileName(sourceFileName.c_str()); #if 0 printf ("oldFileNamePathOnly = %s \n",oldFileNamePathOnly.c_str()); printf ("oldFileName = %s \n",oldFileName.c_str()); #endif // DQ (4/13/2014): Added support to avoid output of a specified include path twice. bool oldFileNamePathOnlyAlreadySpecifiedAsIncludePath = false; for (vector<string>::iterator i = argcArgvList.begin(); i != argcArgvList.end(); i++) { string s = std::string("-I") + oldFileNamePathOnly; if (s == *i) { #if 0 printf ("Identified oldFileNamePathOnly as already specified as include path (avoid redundant specification of -I paths) \n"); #endif oldFileNamePathOnlyAlreadySpecifiedAsIncludePath = true; } } #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: test 3: compilerNameString = \n%s\n",CommandlineProcessing::generateStringFromArgList(compilerNameString,false,false).c_str()); #endif // DQ (4/2/2011): Java does not have -I as an accepted option. if (get_C_only() || get_Cxx_only()) { // DQ (12/8/2004): Add -Ipath option so that source file's directory will be searched for any // possible headers. This is especially important when we are compiling the generated file // located in a different directory! (When the original source file included header files // in the source directory!) This is only important when get_useBackendOnly() == false // since otherwise the source file is the original source file and the compiler will search // its directory for header files. Be sure the put the oldFile's source directory last in the // list of -I options so that it will be searched last (preserving the semantics of #include "..."). // Only add the path if it is a valid name (not an empty name, in which case skip it since the oldFile // is in the current directory (likely a generated file itself; e.g. swig or ROSE applied recursively, etc.)). // printf ("oldFileNamePathOnly.length() = %d \n",oldFileNamePathOnly.length()); // if (oldFileNamePathOnly.empty() == false) if (oldFileNamePathOnly.empty() == false && oldFileNamePathOnlyAlreadySpecifiedAsIncludePath == false) { vector<string>::iterator iter; // find the very first -Ixxx option's position for (iter = compilerNameString.begin(); iter != compilerNameString.end(); iter++) { string cur_string = *iter; string::size_type pos = cur_string.find("-I",0); if (pos==0) break; } // Liao, 5/15/2009 // the input source file's path has to be the first one to be searched for header! // This is required since one of the SPEC CPU 2006 benchmarks: gobmk relies on this to be compiled. // insert before the position // negara1 (07/14/2011): The functionality of header files unparsing takes care of this, so this is needed // only when header files unparsing is not enabled. // if (!this -> get_unparseHeaderFiles()) if (this->get_unparseHeaderFiles() == false) { // DQ (11/7/2018): This might be the better way to get at the SgProject IR node. ROSE_ASSERT(this->get_project() != NULL); // DQ (9/15/2013): Added support for generated file to be placed into the same directory as the source file. // When (get_unparse_in_same_directory_as_input_file() == true) we don't want to add the include // path to the source directory. // compilerNameString.insert(iter, std::string("-I") + oldFileNamePathOnly); SgProject* project = TransformationSupport::getProject(this); // ROSE_ASSERT(project != NULL); if (project != NULL) { #if 0 printf ("In SgFile::buildCompilerCommandLineOptions(): project->get_unparse_in_same_directory_as_input_file() = %s \n",project->get_unparse_in_same_directory_as_input_file() ? "true" : "false"); #endif if (project->get_unparse_in_same_directory_as_input_file() == false) { #if 0 printf ("In buildCompilerCommandLineOptions(): BEFORE adding -I options of source file directory: compilerNameString = \n%s\n",CommandlineProcessing::generateStringFromArgList(compilerNameString,false,false).c_str()); #endif compilerNameString.insert(iter, std::string("-I") + oldFileNamePathOnly); #if 0 printf ("In buildCompilerCommandLineOptions(): AFTER adding -I options of source file directory: compilerNameString = \n%s\n",CommandlineProcessing::generateStringFromArgList(compilerNameString,false,false).c_str()); #endif } } else { printf ("ERROR: In SgFile::buildCompilerCommandLineOptions(): file = %p has no associated project \n",this); ROSE_ASSERT(false); } } } } #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: test 4: compilerNameString = \n%s\n",CommandlineProcessing::generateStringFromArgList(compilerNameString,false,false).c_str()); #endif // Liao 3/30/2011. the search path for the installation path should be the last one, after paths inside // source trees, such as -I../../../../sourcetree/src/frontend/SageIII and // -I../../../../sourcetree/src/midend/programTransformation/ompLowering if (get_openmp_lowering()) { vector<string>::iterator iter, iter_last_inc=compilerNameString.begin(); // find the very last -Ixxx option's position // This for loop cannot be merged with the previous one due to iterator invalidation rules. for (iter = compilerNameString.begin(); iter != compilerNameString.end(); iter++) { string cur_string =*iter; string::size_type pos = cur_string.find("-I",0); if (pos==0) { iter_last_inc = iter; } } if (iter_last_inc != compilerNameString.end()) iter_last_inc ++; // accommodate the insert-before-an-iterator semantics used in vector::insert() // Liao 7/14/2014. Justin changed installation path of headers to install/rose, // Liao, 9/22/2009, we also specify the search path for libgomp_g.h, libxomp.h etc, which are installed under $ROSE_INS/include // and the path to libgomp.a/libgomp.so, which are located in $GCC_GOMP_OPENMP_LIB_PATH // Header should always be available // the conditional compilation is necessary to pass make distcheck, // where only a minimum configuration options are used and not all macros are defined. #ifdef ROSE_INSTALLATION_PATH string include_path(ROSE_INSTALLATION_PATH); include_path += "/include/rose"; compilerNameString.insert(iter_last_inc, "-I"+include_path); #endif } // DQ (4/20/2006): This allows the ROSE translator to be just a wrapper for the backend (vendor) compiler. // compilerNameString += get_unparse_output_filename(); if (get_skip_unparse() == false) { // Generate the name of the ROSE generated source file (instead of the original source file) // this file will be compiled by the backend (vendor) compiler. ROSE_ASSERT(get_unparse_output_filename().empty() == false); compilerNameString.push_back(get_unparse_output_filename()); } else { // In this case the compilerNameString already has the original file name since it was not removed // compilerNameString += get_unparse_output_filename(); // printf ("Case of skip_unparse() == true: original source file name should be present compilerNameString = %s \n",compilerNameString.c_str()); } #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: test 5: compilerNameString = \n%s\n",CommandlineProcessing::generateStringFromArgList(compilerNameString,false,false).c_str()); #endif #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: get_compileOnly() = %s \n",get_compileOnly() ? "true" : "false"); #endif if ( get_compileOnly() == true ) { std::string objectFileName = generateOutputFileName(); #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: objectNameSpecified = %s objectFileName = %s \n",objectNameSpecified ? "true" : "false",objectFileName.c_str()); #endif // DQ (4/2/2011): Java does not have -o as an accepted option, though the "-d <dir>" can be used to specify where class files are put. // Currently we explicitly output "-d ." so that generated class files will be put into the current directory (build tree), but this // is not standard semantics for Java (though it makes the Java support in ROSE consistent with other languages supported in ROSE). if (get_C_only() || get_Cxx_only() || get_Fortran_only()) { // DQ (7/14/2004): Suggested fix from Andreas, make the object file name explicit if (objectNameSpecified == false) { // cout<<"making object file explicit for compilation only mode without -o options"<<endl; compilerNameString.push_back("-o"); compilerNameString.push_back(currentDirectory + "/" + objectFileName); } else { #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: get_compileOnly() == true: get_multifile_support() = %s \n",get_multifile_support() ? "true" : "false"); #endif if (get_multifile_support() == true) { // printf ("In buildCompilerCommandLineOptions: Need to suppress the generation of object file specification in backend compiler link line \n"); // For multi-file handling we have to build a output (object file) using the name of the source file. compilerNameString.push_back("-c"); std::string objectFileName = generateOutputFileName(); compilerNameString.push_back("-o"); compilerNameString.push_back(currentDirectory + "/" + objectFileName); } else { // compilation only, object name is already specified, single file case, nothing else to tweak for the command line #if DEBUG_COMPILER_COMMAND_LINE // DQ (11/8/2015): Put this in #if to avoid output spew. printf ("get_compileOnly() == true: get_multifile_support() == false: \n"); #endif } } } } else { // the case for both compiling and linking // Liao 11/19/2009, changed to support linking multiple source files within one command line // We change the compilation mode for each individual file to compile-only even // when the original command line is to generate the final executable. // We generate the final executable at the SgProject level from object files of each source file if (get_C_only() || get_Cxx_only() || get_Fortran_only()) { #if DEBUG_COMPILER_COMMAND_LINE printf ("In buildCompilerCommandLineOptions: get_compileOnly() == false: get_multifile_support() = %s \n",get_multifile_support() ? "true" : "false"); #endif #if 0 // Liao if (get_multifile_support() == true) { printf ("In buildCompilerCommandLineOptions: Need to suppress the generation of object file specification in backend compiler link line \n"); #if 1 // For multi-file handling we have to build a output (object file) using the name of the source file. compilerNameString.push_back("-c"); std::string objectFileName = generateOutputFileName(); compilerNameString.push_back("-o"); compilerNameString.push_back(currentDirectory + "/" + objectFileName); #else // DQ (4/13/2015): Only output a -c and -o option to specify the executable if one has not already been specified. // Liao 5/1/2015: for the case of doing both compiling and linking, and with multiple files, // we remove the original -o options. We compose our own -o originalfilename.o options // if (objectNameSpecified == false) { // cout<<"turn on compilation only at the file compilation level"<<endl; compilerNameString.push_back("-c"); // For compile+link mode, -o is used for the final executable, if it exists // We make -o objectfile explicit std::string objectFileName = generateOutputFileName(); #error "DEAD CODE!" compilerNameString.push_back("-o"); compilerNameString.push_back(currentDirectory + "/" + objectFileName); } #endif #if 0 // OLD CODE // DQ (4/13/2015): If the compilation only is not specified, then never output an explicit -o option to specify the output file. #error "DEAD CODE!" // DQ (4/13/2015): Only output a -c and -o option to specify the executable if one has not already been specified. if (objectNameSpecified == false) { // cout<<"turn on compilation only at the file compilation level"<<endl; compilerNameString.push_back("-c"); // For compile+link mode, -o is used for the final executable, if it exists // We make -o objectfile explicit std::string objectFileName = generateOutputFileName(); compilerNameString.push_back("-o"); compilerNameString.push_back(currentDirectory + "/" + objectFileName); } #endif } #endif #if 0 printf ("In SgFile::buildCompilerCommandLineOptions(): Adding \"-c\" to backend command line! \n"); #endif // Liao 5/1/2015: support both single and multiple files like: identityTranslator main.c // introduce -c to compile this single file first. // the linking step will happen when handling SgProject compilerNameString.push_back("-c"); // compilation step of the two (compile + link) steps std::string objectFileName = generateOutputFileName(); compilerNameString.push_back("-o"); compilerNameString.push_back(currentDirectory + "/" + objectFileName); } } #if DEBUG_COMPILER_COMMAND_LINE || 0 printf ("\n\nAt base of buildCompilerCommandLineOptions: test 6: compilerNameString = \n\n%s\n\n",CommandlineProcessing::generateStringFromArgList(compilerNameString,false,false).c_str()); #endif #if 0 printf ("\n\nExiting at base of buildCompilerCommandLineOptions() ... \n"); ROSE_ASSERT (false); #endif #if 0 cout<<"Debug: SgFile::buildCompilerCommandLineOptions() compilerNameString is "<<endl; for (vector<string>::iterator iter = compilerNameString.begin(); iter != compilerNameString.end(); iter++) { std::string str = *iter; cout<<"\t"<<str<<endl; } #endif return compilerNameString; } // end of SgFile::buildCompilerCommandLineOptions()
{-# OPTIONS --allow-unsolved-metas --universe-polymorphism #-} module Issue203 where postulate Level : Set zero : Level suc : Level → Level max : Level → Level → Level {-# BUILTIN LEVEL Level #-} {-# BUILTIN LEVELZERO zero #-} {-# BUILTIN LEVELSUC suc #-} {-# BUILTIN LEVELMAX max #-} -- Should work but give unsolved metas (type of b) data ↓ {a b} (A : Set a) : Set a where [_] : (x : A) → ↓ A mutual -- avoid freezing -- Shouldn't instantiate the level of Σ to a data Σ {a b} (A : Set a) (B : A → Set b) : Set _ where _,_ : (x : A) (y : B x) → Σ A B instantiateToMax : ∀ {a b}(A : Set a)(B : A → Set b) → Set (max a b) instantiateToMax = Σ
function raw_terminal(f, terminal=terminal, hide_cursor=true) cur_enabled = _enable_raw_terminal(terminal) hide_cursor &= cur_enabled hide_cursor && _cursor_hide(terminal.out_stream) try f() finally cur_enabled && _disable_raw_terminal(terminal) hide_cursor && _cursor_show(terminal.out_stream) end end function _enable_raw_terminal(terminal) try REPL.Terminals.raw!(terminal, true) return true catch err warn("TerminalMenus: Unable to enable raw mode: $err") end false end function _disable_raw_terminal(terminal) try REPL.Terminals.raw!(terminal, false) return true catch err warn("TerminalMenus: Unable to disable raw mode: $err") end false end _cursor_hide(cur_buffer::IO=STDOUT) = print(cur_buffer, "\x1b[?25l") _cursor_show(cur_buffer::IO=STDOUT) = print(cur_buffer, "\x1b[?25h")
If $W$ is a measurable set with infinite measure, then there exists a measurable subset $Z$ of $W$ with finite measure greater than $C$.
\section{Experimental Setup}\label{sec:experimental_setup} As has also been mentioned, all problem instances were extracted from the ITC 2007 examination timetabling benchmark set \cite{mccollum2010setting} (available at \url{www.cs.qub.ac.uk/itc2007/examtrack/exam_track_index_files/outputformat.htm}). From the benchmark set \cite{mccollum2010setting} two early, two late and two hidden problem instances were used to run experiments on. These instances were comprised of \emph{exam\_comp\_set1.exam}, \emph{exam\_comp\_set4.exam}, \emph{exam\_comp\_set6.exam}, \emph{exam\_comp\_set8.exam}, \emph{exam\_comp\_set9.exam} and \emph{exam\_comp\_set12.exam}. A total of 10 test runs were run on each problem instance for both the single and multi-point search approaches. In addition, the machine used for development and testing purposes was a 2015 15-inch Macbook Pro with a 2.5 GHz Quad-Core Intel Core i7 processor, 16GB of memory and 500GB of storage. At the time of experimentation the machine had a battery cycle count of 684. Finally, all of the code and data necessary to reproduce the results is available at \url{https://github.com/marcus-bornman/cos_790_assignment_2}.
text \<open>Authors: Anthony Bordg and Lawrence Paulson, with some contributions from Wenda Li\<close> theory Comm_Ring imports "Group_Extras" "Topological_Space" "Jacobson_Basic_Algebra.Ring_Theory" "Set_Extras" begin (*Suppresses the built-in plus sign, but why does no_notation minus (infixl "-" 65) cause errors with monoid subtraction below? --LCP *) no_notation plus (infixl "+" 65) lemma (in monoid_homomorphism) monoid_preimage: "Group_Theory.monoid (\<eta> \<^sup>\<inverse> M M') (\<cdot>) \<one>" by (simp add: Int_absorb1 source.monoid_axioms subsetI) lemma (in group_homomorphism) group_preimage: "Group_Theory.group (\<eta> \<^sup>\<inverse> G G') (\<cdot>) \<one>" by (simp add: Int_absorb1 source.group_axioms subsetI) lemma (in ring_homomorphism) ring_preimage: "ring (\<eta> \<^sup>\<inverse> R R') (+) (\<cdot>) \<zero> \<one>" by (simp add: Int_absorb2 Int_commute source.ring_axioms subset_iff) section \<open>Commutative Rings\<close> subsection \<open>Commutative Rings\<close> locale comm_ring = ring + assumes comm_mult: "\<lbrakk> a \<in> R; b \<in> R \<rbrakk> \<Longrightarrow> a \<cdot> b = b \<cdot> a" text \<open>The zero ring is a commutative ring.\<close> lemma invertible_0: "monoid.invertible {0} (\<lambda>n m. 0) 0 0" using Group_Theory.monoid.intro monoid.unit_invertible by force interpretation ring0: ring "{0::nat}" "\<lambda>n m. 0" "\<lambda>n m. 0" 0 0 using invertible_0 by unfold_locales auto declare ring0.additive.left_unit [simp del] ring0.additive.invertible [simp del] declare ring0.additive.invertible_left_inverse [simp del] ring0.right_zero [simp del] interpretation cring0: comm_ring "{0::nat}" "\<lambda>n m. 0" "\<lambda>n m. 0" 0 0 by (metis comm_ring_axioms_def comm_ring_def ring0.ring_axioms) (* def 0.13 *) definition (in ring) zero_divisor :: "'a \<Rightarrow> 'a \<Rightarrow> bool" where "zero_divisor x y \<equiv> (x \<noteq> \<zero>) \<and> (y \<noteq> \<zero>) \<and> (x \<cdot> y = \<zero>)" subsection \<open>Entire Rings\<close> (* def 0.14 *) locale entire_ring = comm_ring + assumes units_neq: "\<one> \<noteq> \<zero>" and no_zero_div: "\<lbrakk> x \<in> R; y \<in> R\<rbrakk> \<Longrightarrow> \<not>(zero_divisor x y)" subsection \<open>Ideals\<close> context comm_ring begin lemma mult_left_assoc: "\<lbrakk> a \<in> R; b \<in> R; c \<in> R \<rbrakk> \<Longrightarrow> b \<cdot> (a \<cdot> c) = a \<cdot> (b \<cdot> c)" using comm_mult multiplicative.associative by auto lemmas ring_mult_ac = comm_mult multiplicative.associative mult_left_assoc (* ex. 0.16 *) lemma ideal_R_R: "ideal R R (+) (\<cdot>) \<zero> \<one>" proof qed auto lemma ideal_0_R: "ideal {\<zero>} R (+) (\<cdot>) \<zero> \<one>" proof show "monoid.invertible {\<zero>} (+) \<zero> u" if "u \<in> {\<zero>}" for u :: 'a proof (rule monoid.invertibleI) show "Group_Theory.monoid {\<zero>} (+) \<zero>" proof qed (use that in auto) qed (use that in auto) qed auto definition ideal_gen_by_prod :: "'a set \<Rightarrow> 'a set \<Rightarrow> 'a set" where "ideal_gen_by_prod \<aa> \<bb> \<equiv> additive.subgroup_generated {x. \<exists>a b. x = a \<cdot> b \<and> a \<in> \<aa> \<and> b \<in> \<bb>}" lemma ideal_zero: "ideal A R add mult zero unit \<Longrightarrow> zero \<in> A" by (simp add: ideal_def subgroup_of_additive_group_of_ring_def subgroup_def submonoid_def submonoid_axioms_def) lemma ideal_implies_subset: assumes "ideal A R add mult zero unit" shows "A \<subseteq> R" by (meson assms ideal_def subgroup_def subgroup_of_additive_group_of_ring_def submonoid_axioms_def submonoid_def) lemma ideal_inverse: assumes "a \<in> A" "ideal A R (+) mult zero unit" shows "additive.inverse a \<in> A" by (meson additive.invertible assms comm_ring.ideal_implies_subset comm_ring_axioms ideal_def subgroup.subgroup_inverse_iff subgroup_of_additive_group_of_ring_def subsetD) lemma ideal_add: assumes "a \<in> A" "b \<in> A" "ideal A R add mult zero unit" shows "add a b \<in> A" by (meson Group_Theory.group_def assms ideal_def monoid.composition_closed subgroup_def subgroup_of_additive_group_of_ring_def) lemma ideal_mult_in_subgroup_generated: assumes \<aa>: "ideal \<aa> R (+) (\<cdot>) \<zero> \<one>" and \<bb>: "ideal \<bb> R (+) (\<cdot>) \<zero> \<one>" and "a \<in> \<aa>" "b \<in> \<bb>" shows "a \<cdot> b \<in> ideal_gen_by_prod \<aa> \<bb>" proof - have "\<exists>x y. a \<cdot> b = x \<cdot> y \<and> x \<in> \<aa> \<and> y \<in> \<bb>" using assms ideal_implies_subset by blast with ideal_implies_subset show ?thesis unfolding additive.subgroup_generated_def ideal_gen_by_prod_def using assms ideal_implies_subset by (blast intro: additive.generate.incl) qed subsection \<open>Ideals generated by an Element\<close> definition gen_ideal:: "'a \<Rightarrow> 'a set" ("\<langle>_\<rangle>") where "\<langle>x\<rangle> \<equiv> {y. \<exists>r\<in>R. y = r \<cdot> x}" lemma zero_in_gen_ideal: assumes "x \<in> R" shows "\<zero> \<in> \<langle>x\<rangle>" proof - have "\<exists>a. a \<in> R \<and> \<zero> = a \<cdot> x" by (metis (lifting) additive.unit_closed assms left_zero) then show ?thesis using gen_ideal_def by blast qed lemma add_in_gen_ideal: "\<lbrakk>x \<in> R; a \<in> \<langle>x\<rangle>; b \<in> \<langle>x\<rangle>\<rbrakk> \<Longrightarrow> a + b \<in> \<langle>x\<rangle>" apply (clarsimp simp : gen_ideal_def) by (metis (no_types) additive.composition_closed distributive(2)) lemma gen_ideal_subset: assumes "x \<in> R" shows "\<langle>x\<rangle> \<subseteq> R" using assms comm_ring.gen_ideal_def local.comm_ring_axioms by fastforce lemma gen_ideal_monoid: assumes "x \<in> R" shows "Group_Theory.monoid \<langle>x\<rangle> (+) \<zero>" proof show "a + b \<in> \<langle>x\<rangle>" if "a \<in> \<langle>x\<rangle>" "b \<in> \<langle>x\<rangle>" for a b by (simp add: add_in_gen_ideal assms that) qed (use assms zero_in_gen_ideal gen_ideal_def in auto) lemma gen_ideal_group: assumes "x \<in> R" shows "Group_Theory.group \<langle>x\<rangle> (+) \<zero>" proof fix a b c assume "a \<in> \<langle>x\<rangle>" "b \<in> \<langle>x\<rangle>" "c \<in> \<langle>x\<rangle>" then show "a + b + c = a + (b + c)" by (meson assms gen_ideal_monoid monoid.associative) next fix a assume a: "a \<in> \<langle>x\<rangle>" show "\<zero> + a = a" by (meson a assms gen_ideal_monoid monoid.left_unit) show "a + \<zero> = a" by (meson a assms gen_ideal_monoid monoid.right_unit) interpret M: monoid "\<langle>x\<rangle>" "(+)" \<zero> by (simp add: assms gen_ideal_monoid) obtain r where r: "r\<in>R" "a = r \<cdot> x" using a gen_ideal_def by auto show "monoid.invertible \<langle>x\<rangle> (+) \<zero> a" proof (rule M.invertibleI) have "\<exists>r\<in>R. - a = r \<cdot> x" by (metis assms ideal_R_R ideal_inverse local.left_minus r) then show "-a \<in> \<langle>x\<rangle>" by (simp add: gen_ideal_def) qed (use a r assms in auto) qed (auto simp: zero_in_gen_ideal add_in_gen_ideal assms) lemma gen_ideal_ideal: assumes "x \<in> R" shows "ideal \<langle>x\<rangle> R (+) (\<cdot>) \<zero> \<one>" proof intro_locales show "submonoid_axioms \<langle>x\<rangle> R (+) \<zero>" by (simp add: add_in_gen_ideal assms gen_ideal_subset submonoid_axioms.intro zero_in_gen_ideal) show "Group_Theory.group_axioms \<langle>x\<rangle> (+) \<zero>" by (meson Group_Theory.group_def assms gen_ideal_group) show "ideal_axioms \<langle>x\<rangle> R (\<cdot>)" proof fix a b assume "a \<in> R" "b \<in> \<langle>x\<rangle>" then obtain r where r: "r\<in>R" "b = r \<cdot> x" by (auto simp add: gen_ideal_def) have "a \<cdot> (r \<cdot> x) = (a \<cdot> r) \<cdot> x" using \<open>a \<in> R\<close> \<open>r \<in> R\<close> assms multiplicative.associative by presburger then show "a \<cdot> b \<in> \<langle>x\<rangle>" using \<open>a \<in> R\<close> r gen_ideal_def by blast then show "b \<cdot> a \<in> \<langle>x\<rangle>" by (simp add: \<open>a \<in> R\<close> assms comm_mult r) qed qed (auto simp add: assms gen_ideal_monoid) subsection \<open>Exercises\<close> lemma in_ideal_gen_by_prod: assumes \<aa>: "ideal \<aa> R (+) (\<cdot>) \<zero> \<one>" and \<bb>: "ideal \<bb> R (+) (\<cdot>) \<zero> \<one>" and "a \<in> R" and b: "b \<in> ideal_gen_by_prod \<aa> \<bb>" shows "a \<cdot> b \<in> ideal_gen_by_prod \<aa> \<bb>" using b \<open>a \<in> R\<close> unfolding additive.subgroup_generated_def ideal_gen_by_prod_def proof (induction arbitrary: a) case unit then show ?case by (simp add: additive.generate.unit) next case (incl x u) with \<aa> \<bb> have "\<And>a b. \<lbrakk>a \<cdot> b \<in> R; a \<in> \<aa>; b \<in> \<bb>\<rbrakk> \<Longrightarrow> \<exists>x y. u \<cdot> (a \<cdot> b) = x \<cdot> y \<and> x \<in> \<aa> \<and> y \<in> \<bb>" by simp (metis ideal.ideal(1) ideal_implies_subset multiplicative.associative subset_iff) then show ?case using additive.generate.incl incl.hyps incl.prems by force next case (inv u v) then show ?case proof clarsimp fix a b assume "v \<in> R" "a \<cdot> b \<in> R" "a \<in> \<aa>" "b \<in> \<bb>" then have "v \<cdot> (- a \<cdot> b) = v \<cdot> a \<cdot> (- b) \<and> v \<cdot> a \<in> \<aa> \<and> - b \<in> \<bb>" by (metis \<aa> \<bb> ideal.ideal(1) ideal_implies_subset ideal_inverse in_mono local.right_minus multiplicative.associative) then show "v \<cdot> (- a \<cdot> b) \<in> additive.generate (R \<inter> {a \<cdot> b |a b. a \<in> \<aa> \<and> b \<in> \<bb>})" using \<aa> \<bb> additive.subgroup_generated_def ideal_mult_in_subgroup_generated unfolding ideal_gen_by_prod_def by presburger qed next case (mult u v) then show ?case using additive.generate.mult additive.generate_into_G distributive(1) by force qed (* ex. 0.12 *) lemma ideal_subgroup_generated: assumes "ideal \<aa> R (+) (\<cdot>) \<zero> \<one>" and "ideal \<bb> R (+) (\<cdot>) \<zero> \<one>" shows "ideal (ideal_gen_by_prod \<aa> \<bb>) R (+) (\<cdot>) \<zero> \<one>" proof show "ideal_gen_by_prod \<aa> \<bb> \<subseteq> R" by (simp add: additive.subgroup_generated_is_subset ideal_gen_by_prod_def) show "a + b \<in> ideal_gen_by_prod \<aa> \<bb>" if "a \<in> ideal_gen_by_prod \<aa> \<bb>" "b \<in> ideal_gen_by_prod \<aa> \<bb>" for a b using that additive.subgroup_generated_is_monoid monoid.composition_closed by (fastforce simp: ideal_gen_by_prod_def) show "\<zero> \<in> ideal_gen_by_prod \<aa> \<bb>" using additive.generate.unit additive.subgroup_generated_def ideal_gen_by_prod_def by presburger show "a + b + c = a + (b + c)" if "a \<in> ideal_gen_by_prod \<aa> \<bb>" "b \<in> ideal_gen_by_prod \<aa> \<bb>" "c \<in> ideal_gen_by_prod \<aa> \<bb>" for a b c using that additive.subgroup_generated_is_subset unfolding ideal_gen_by_prod_def by blast show "\<zero> + a = a" "a + \<zero> = a" if "a \<in> ideal_gen_by_prod \<aa> \<bb>" for a using that additive.subgroup_generated_is_subset unfolding ideal_gen_by_prod_def by blast+ show "monoid.invertible (ideal_gen_by_prod \<aa> \<bb>) (+) \<zero> u" if "u \<in> ideal_gen_by_prod \<aa> \<bb>" for u using that additive.subgroup_generated_is_subgroup group.invertible unfolding ideal_gen_by_prod_def subgroup_def by fastforce show "a \<cdot> b \<in> ideal_gen_by_prod \<aa> \<bb>" if "a \<in> R" "b \<in> ideal_gen_by_prod \<aa> \<bb>" for a b using that by (simp add: assms in_ideal_gen_by_prod) then show "b \<cdot> a \<in> ideal_gen_by_prod \<aa> \<bb>" if "a \<in> R" "b \<in> ideal_gen_by_prod \<aa> \<bb>" for a b using that by (metis \<open>ideal_gen_by_prod \<aa> \<bb> \<subseteq> R\<close> comm_mult in_mono) qed lemma ideal_gen_by_prod_is_inter: assumes "ideal \<aa> R (+) (\<cdot>) \<zero> \<one>" and "ideal \<bb> R (+) (\<cdot>) \<zero> \<one>" shows "ideal_gen_by_prod \<aa> \<bb> = \<Inter> {I. ideal I R (+) (\<cdot>) \<zero> \<one> \<and> {a \<cdot> b |a b. a \<in> \<aa> \<and> b \<in> \<bb>} \<subseteq> I}" (is "?lhs = ?rhs") proof have "x \<in> ?rhs" if "x \<in> ?lhs" for x using that unfolding ideal_gen_by_prod_def additive.subgroup_generated_def by induction (force simp: ideal_zero ideal_inverse ideal_add)+ then show "?lhs \<subseteq> ?rhs" by blast show "?rhs \<subseteq> ?lhs" using assms ideal_subgroup_generated by (force simp: ideal_mult_in_subgroup_generated) qed end (* comm_ring *) text \<open>def. 0.18, see remark 0.20\<close> locale pr_ideal = comm:comm_ring R "(+)" "(\<cdot>)" "\<zero>" "\<one>" + ideal I R "(+)" "(\<cdot>)" "\<zero>" "\<one>" for R and I and addition (infixl "+" 65) and multiplication (infixl "\<cdot>" 70) and zero ("\<zero>") and unit ("\<one>") + assumes carrier_neq: "I \<noteq> R" and absorbent: "\<lbrakk>x \<in> R; y \<in> R\<rbrakk> \<Longrightarrow> (x \<cdot> y \<in> I) \<Longrightarrow> (x \<in> I \<or> y \<in> I)" begin text \<open> Note that in the locale prime ideal the order of I and R is reversed with respect to the locale ideal, so that we can introduce some syntactic sugar later. \<close> text \<open>remark 0.21\<close> lemma not_1 [simp]: shows "\<one> \<notin> I" proof assume "\<one> \<in> I" then have "\<And>x. \<lbrakk>\<one> \<in> I; x \<in> R\<rbrakk> \<Longrightarrow> x \<in> I" by (metis ideal(1) comm.multiplicative.right_unit) with \<open>\<one> \<in> I\<close> have "I = R" by auto then show False using carrier_neq by blast qed lemma not_invertible: assumes "x \<in> I" shows "\<not> comm.multiplicative.invertible x" using assms ideal(2) not_1 by blast text \<open>ex. 0.22\<close> lemma submonoid_notin: assumes "S = {x \<in> R. x \<notin> I}" shows "submonoid S R (\<cdot>) \<one>" proof show "S \<subseteq> R" using assms by force show "a \<cdot> b \<in> S" if "a \<in> S" and "b \<in> S" for a :: 'a and b :: 'a using that using absorbent assms by blast show "\<one> \<in> S" using assms carrier_neq ideal(1) by fastforce qed end (* pr_ideal *) section \<open>Spectrum of a ring\<close> subsection \<open>The Zariski Topology\<close> context comm_ring begin text \<open>Notation 1\<close> definition closed_subsets :: "'a set \<Rightarrow> ('a set) set" ("\<V> _" [900] 900) where "\<V> \<aa> \<equiv> {I. pr_ideal R I (+) (\<cdot>) \<zero> \<one> \<and> \<aa> \<subseteq> I}" text \<open>Notation 2\<close> definition spectrum :: "('a set) set" ("Spec") where "Spec \<equiv> {I. pr_ideal R I (+) (\<cdot>) \<zero> \<one>}" lemma cring0_spectrum_eq [simp]: "cring0.spectrum = {}" unfolding cring0.spectrum_def pr_ideal_def by (metis (no_types, lifting) Collect_empty_eq cring0.ideal_zero pr_ideal.intro pr_ideal.not_1) text \<open>remark 0.11\<close> lemma closed_subsets_R [simp]: shows "\<V> R = {}" using ideal_implies_subset by (auto simp: closed_subsets_def pr_ideal_axioms_def pr_ideal_def) lemma closed_subsets_zero [simp]: shows "\<V> {\<zero>} = Spec" unfolding closed_subsets_def spectrum_def pr_ideal_def pr_ideal_axioms_def by (auto dest: ideal_zero) lemma closed_subsets_ideal_aux: assumes \<aa>: "ideal \<aa> R (+) (\<cdot>) \<zero> \<one>" and \<bb>: "ideal \<bb> R (+) (\<cdot>) \<zero> \<one>" and prime: "pr_ideal R x (+) (\<cdot>) \<zero> \<one>" and disj: "\<aa> \<subseteq> x \<or> \<bb> \<subseteq> x" shows "ideal_gen_by_prod \<aa> \<bb> \<subseteq> x" unfolding ideal_gen_by_prod_def additive.subgroup_generated_def proof fix u assume u: "u \<in> additive.generate (R \<inter> {a \<cdot> b |a b. a \<in> \<aa> \<and> b \<in> \<bb>})" have "\<aa> \<subseteq> R" "\<bb> \<subseteq> R" using \<aa> \<bb> ideal_implies_subset by auto show "u \<in> x" using u proof induction case unit then show ?case by (meson comm_ring.ideal_zero prime pr_ideal_def) next case (incl a) then have "a \<in> R" by blast with incl pr_ideal.axioms [OF prime] show ?case by clarsimp (metis \<open>\<aa> \<subseteq> R\<close> \<open>\<bb> \<subseteq> R\<close> disj ideal.ideal subset_iff) next case (inv a) then have "a \<in> R" by blast with inv pr_ideal.axioms [OF prime] show ?case by clarsimp (metis \<open>\<aa> \<subseteq> R\<close> \<open>\<bb> \<subseteq> R\<close> disj ideal.ideal ideal_inverse subset_iff) next case (mult a b) then show ?case by (meson prime comm_ring.ideal_add pr_ideal_def) qed qed text \<open>ex. 0.13\<close> lemma closed_subsets_ideal_iff: assumes "ideal \<aa> R (+) (\<cdot>) \<zero> \<one>" and "ideal \<bb> R (+) (\<cdot>) \<zero> \<one>" shows "\<V> (ideal_gen_by_prod \<aa> \<bb>) = (\<V> \<aa>) \<union> (\<V> \<bb>)" (is "?lhs = ?rhs") proof show "?lhs \<subseteq> ?rhs" unfolding closed_subsets_def by clarsimp (meson assms ideal_implies_subset ideal_mult_in_subgroup_generated in_mono pr_ideal.absorbent) show "?rhs \<subseteq> ?lhs" unfolding closed_subsets_def using closed_subsets_ideal_aux [OF assms] by auto qed abbreviation finsum:: "'b set \<Rightarrow> ('b \<Rightarrow> 'a) \<Rightarrow> 'a" where "finsum I f \<equiv> additive.finprod I f" lemma finsum_empty [simp]: "finsum {} f = \<zero>" by (simp add: additive.finprod_def) lemma finsum_insert: assumes "finite I" "i \<notin> I" and R: "f i \<in> R" "\<And>j. j \<in> I \<Longrightarrow> f j \<in> R" shows "finsum (insert i I) f = f i + finsum I f" unfolding additive.finprod_def proof (subst LCD.foldD_insert [where B = "insert i I"]) show "LCD (insert i I) R ((+) \<circ> f)" proof show "((+) \<circ> f) x (((+) \<circ> f) y z) = ((+) \<circ> f) y (((+) \<circ> f) x z)" if "x \<in> insert i I" "y \<in> insert i I" "z \<in> R" for x y z using that additive.associative additive.commutative R by auto show "((+) \<circ> f) x y \<in> R" if "x \<in> insert i I" "y \<in> R" for x y using that R by force qed qed (use assms in auto) lemma finsum_singleton [simp]: assumes "f i \<in> R" shows "finsum {i} f = f i" by (metis additive.right_unit assms finite.emptyI finsum_empty finsum_insert insert_absorb insert_not_empty) (* ex. 0.15 *) lemma ex_15: fixes J :: "'b set" and \<aa> :: "'b \<Rightarrow> 'a set" assumes "J \<noteq> {}" and J: "\<And>j. j\<in>J \<Longrightarrow> ideal (\<aa> j) R (+) (\<cdot>) \<zero> \<one>" shows "\<V> ({x. \<exists>I f. x = finsum I f \<and> I \<subseteq> J \<and> finite I \<and> (\<forall>i. i\<in>I \<longrightarrow> f i \<in> \<aa> i)}) = (\<Inter>j\<in>J. \<V> (\<aa> j))" proof - have "y \<in> U" if j: "j \<in> J" "y \<in> \<aa> j" and "pr_ideal R U (+) (\<cdot>) \<zero> \<one>" and U: "{finsum I f |I f. I \<subseteq> J \<and> finite I \<and> (\<forall>i. i \<in> I \<longrightarrow> f i \<in> \<aa> i)} \<subseteq> U" for U j y proof - have "y \<in> R" using J j ideal_implies_subset by blast then have y: "y = finsum {j} (\<lambda>_. y)" by simp then have "y \<in> {finsum I f |I f. I \<subseteq> J \<and> finite I \<and> (\<forall>i. i \<in> I \<longrightarrow> f i \<in> \<aa> i)}" using that by blast then show ?thesis by (rule subsetD [OF U]) qed moreover have PI: "pr_ideal R x (+) (\<cdot>) \<zero> \<one>" if "\<forall>j\<in>J. pr_ideal R x (+) (\<cdot>) \<zero> \<one> \<and> \<aa> j \<subseteq> x" for x using that assms(1) by fastforce moreover have "finsum I f \<in> U" if "finite I" and "\<forall>j\<in>J. pr_ideal R U (+) (\<cdot>) \<zero> \<one> \<and> \<aa> j \<subseteq> U" and "I \<subseteq> J" "\<forall>i. i \<in> I \<longrightarrow> f i \<in> \<aa> i" for U I f using that proof (induction I rule: finite_induct) case empty then show ?case using PI assms ideal_zero by fastforce next case (insert i I) then have "finsum (insert i I) f = f i + finsum I f" by (metis assms(2) finsum_insert ideal_implies_subset insertCI subset_iff) also have "... \<in> U" using insert by (metis ideal_add insertCI pr_ideal.axioms(2) subset_eq) finally show ?case . qed ultimately show ?thesis by (auto simp: closed_subsets_def) qed (* ex 0.16 *) definition is_zariski_open:: "'a set set \<Rightarrow> bool" where "is_zariski_open U \<equiv> generated_topology Spec {U. (\<exists>\<aa>. ideal \<aa> R (+) (\<cdot>) \<zero> \<one> \<and> U = Spec - \<V> \<aa>)} U" lemma is_zariski_open_empty [simp]: "is_zariski_open {}" using UNIV is_zariski_open_def generated_topology_is_topology topological_space.open_empty by simp lemma is_zariski_open_Spec [simp]: "is_zariski_open Spec" by (simp add: UNIV is_zariski_open_def) lemma is_zariski_open_Union [intro]: "(\<And>x. x \<in> F \<Longrightarrow> is_zariski_open x) \<Longrightarrow> is_zariski_open (\<Union> F)" by (simp add: UN is_zariski_open_def) lemma is_zariski_open_Int [simp]: "\<lbrakk>is_zariski_open U; is_zariski_open V\<rbrakk> \<Longrightarrow> is_zariski_open (U \<inter> V)" using Int is_zariski_open_def by blast lemma zariski_is_topological_space [iff]: shows "topological_space Spec is_zariski_open" unfolding is_zariski_open_def using generated_topology_is_topology by blast lemma zariski_open_is_subset: assumes "is_zariski_open U" shows "U \<subseteq> Spec" using assms zariski_is_topological_space topological_space.open_imp_subset by auto lemma cring0_is_zariski_open [simp]: "cring0.is_zariski_open = (\<lambda>U. U={})" using cring0.cring0_spectrum_eq cring0.is_zariski_open_empty cring0.zariski_open_is_subset by blast subsection \<open>Standard Open Sets\<close> definition standard_open:: "'a \<Rightarrow> 'a set set" ("\<D>'(_')") where "\<D>(x) \<equiv> (Spec \<setminus> \<V>(\<langle>x\<rangle>))" lemma standard_open_is_zariski_open: assumes "x \<in> R" shows "is_zariski_open \<D>(x)" unfolding is_zariski_open_def standard_open_def using assms gen_ideal_ideal generated_topology.simps by fastforce lemma standard_open_is_subset: assumes "x \<in> R" shows "\<D>(x) \<subseteq> Spec" by (simp add: assms standard_open_is_zariski_open zariski_open_is_subset) lemma belongs_standard_open_iff: assumes "x \<in> R" and "\<pp> \<in> Spec" shows "x \<notin> \<pp> \<longleftrightarrow> \<pp> \<in> \<D>(x)" using assms apply (auto simp: standard_open_def closed_subsets_def spectrum_def gen_ideal_def subset_iff) apply (metis pr_ideal.absorbent) by (meson ideal.ideal(1) pr_ideal_def) end (* comm_ring *) subsection \<open>Presheaves of Rings\<close> (* def 0.17 *) locale presheaf_of_rings = Topological_Space.topological_space + fixes \<FF>:: "'a set \<Rightarrow> 'b set" and \<rho>:: "'a set \<Rightarrow> 'a set \<Rightarrow> ('b \<Rightarrow> 'b)" and b:: "'b" and add_str:: "'a set \<Rightarrow> ('b \<Rightarrow> 'b \<Rightarrow> 'b)" ("+\<^bsub>_\<^esub>") and mult_str:: "'a set \<Rightarrow> ('b \<Rightarrow> 'b \<Rightarrow> 'b)" ("\<cdot>\<^bsub>_\<^esub>") and zero_str:: "'a set \<Rightarrow> 'b" ("\<zero>\<^bsub>_\<^esub>") and one_str:: "'a set \<Rightarrow> 'b" ("\<one>\<^bsub>_\<^esub>") assumes is_ring_morphism: "\<And>U V. is_open U \<Longrightarrow> is_open V \<Longrightarrow> V \<subseteq> U \<Longrightarrow> ring_homomorphism (\<rho> U V) (\<FF> U) (+\<^bsub>U\<^esub>) (\<cdot>\<^bsub>U\<^esub>) \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub> (\<FF> V) (+\<^bsub>V\<^esub>) (\<cdot>\<^bsub>V\<^esub>) \<zero>\<^bsub>V\<^esub> \<one>\<^bsub>V\<^esub>" and ring_of_empty: "\<FF> {} = {b}" and identity_map [simp]: "\<And>U. is_open U \<Longrightarrow> (\<And>x. x \<in> \<FF> U \<Longrightarrow> \<rho> U U x = x)" and assoc_comp: "\<And>U V W. is_open U \<Longrightarrow> is_open V \<Longrightarrow> is_open W \<Longrightarrow> V \<subseteq> U \<Longrightarrow> W \<subseteq> V \<Longrightarrow> (\<And>x. x \<in> (\<FF> U) \<Longrightarrow> \<rho> U W x = (\<rho> V W \<circ> \<rho> U V) x)" begin lemma is_ring_from_is_homomorphism: shows "\<And>U. is_open U \<Longrightarrow> ring (\<FF> U) (+\<^bsub>U\<^esub>) (\<cdot>\<^bsub>U\<^esub>) \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub>" using is_ring_morphism ring_homomorphism.axioms(2) by fastforce lemma is_map_from_is_homomorphism: assumes "is_open U" and "is_open V" and "V \<subseteq> U" shows "Set_Theory.map (\<rho> U V) (\<FF> U) (\<FF> V)" using assms by (meson is_ring_morphism ring_homomorphism.axioms(1)) lemma eq_\<rho>: assumes "is_open U" and "is_open V" and "is_open W" and "W \<subseteq> U \<inter> V" and "s \<in> \<FF> U" and "t \<in> \<FF> V" and "\<rho> U W s = \<rho> V W t" and "is_open W'" and "W' \<subseteq> W" shows "\<rho> U W' s = \<rho> V W' t" by (metis Int_subset_iff assms assoc_comp comp_apply) end (* presheaf_of_rings *) locale morphism_presheaves_of_rings = source: presheaf_of_rings X is_open \<FF> \<rho> b add_str mult_str zero_str one_str + target: presheaf_of_rings X is_open \<FF>' \<rho>' b' add_str' mult_str' zero_str' one_str' for X and is_open and \<FF> and \<rho> and b and add_str ("+\<^bsub>_\<^esub>") and mult_str ("\<cdot>\<^bsub>_\<^esub>") and zero_str ("\<zero>\<^bsub>_\<^esub>") and one_str ("\<one>\<^bsub>_\<^esub>") and \<FF>' and \<rho>' and b' and add_str' ("+''\<^bsub>_\<^esub>") and mult_str' ("\<cdot>''\<^bsub>_\<^esub>") and zero_str' ("\<zero>''\<^bsub>_\<^esub>") and one_str' ("\<one>''\<^bsub>_\<^esub>") + fixes fam_morphisms:: "'a set \<Rightarrow> ('b \<Rightarrow> 'c)" assumes is_ring_morphism: "\<And>U. is_open U \<Longrightarrow> ring_homomorphism (fam_morphisms U) (\<FF> U) (+\<^bsub>U\<^esub>) (\<cdot>\<^bsub>U\<^esub>) \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub> (\<FF>' U) (+'\<^bsub>U\<^esub>) (\<cdot>'\<^bsub>U\<^esub>) \<zero>'\<^bsub>U\<^esub> \<one>'\<^bsub>U\<^esub>" and comm_diagrams: "\<And>U V. is_open U \<Longrightarrow> is_open V \<Longrightarrow> V \<subseteq> U \<Longrightarrow> (\<And>x. x \<in> \<FF> U \<Longrightarrow> (\<rho>' U V \<circ> fam_morphisms U) x = (fam_morphisms V \<circ> \<rho> U V) x)" begin lemma fam_morphisms_are_maps: assumes "is_open U" shows "Set_Theory.map (fam_morphisms U) (\<FF> U) (\<FF>' U)" using assms is_ring_morphism by (simp add: ring_homomorphism_def) end (* morphism_presheaves_of_rings *) (* Identity presheaf *) lemma (in presheaf_of_rings) id_is_mor_pr_rngs: shows "morphism_presheaves_of_rings S is_open \<FF> \<rho> b add_str mult_str zero_str one_str \<FF> \<rho> b add_str mult_str zero_str one_str (\<lambda>U. identity (\<FF> U))" proof (intro morphism_presheaves_of_rings.intro morphism_presheaves_of_rings_axioms.intro) show "\<And>U. is_open U \<Longrightarrow> ring_homomorphism (identity (\<FF> U)) (\<FF> U) (add_str U) (mult_str U) (zero_str U) (one_str U) (\<FF> U) (add_str U) (mult_str U) (zero_str U) (one_str U)" by (metis identity_map is_map_from_is_homomorphism is_ring_morphism restrict_ext restrict_on_source subset_eq) show "\<And>U V. \<lbrakk>is_open U; is_open V; V \<subseteq> U\<rbrakk> \<Longrightarrow> (\<And>x. x \<in> (\<FF> U) \<Longrightarrow> (\<rho> U V \<circ> identity (\<FF> U)) x = (identity (\<FF> V) \<circ> \<rho> U V) x)" using map.map_closed by (metis comp_apply is_map_from_is_homomorphism restrict_apply') qed (use presheaf_of_rings_axioms in auto) lemma comp_ring_morphisms: assumes "ring_homomorphism \<eta> A addA multA zeroA oneA B addB multB zeroB oneB" and "ring_homomorphism \<theta> B addB multB zeroB oneB C addC multC zeroC oneC" shows "ring_homomorphism (compose A \<theta> \<eta>) A addA multA zeroA oneA C addC multC zeroC oneC" using comp_monoid_morphisms comp_group_morphisms assms by (metis monoid_homomorphism_def ring_homomorphism_def) (* Composition of presheaves *) lemma comp_of_presheaves: assumes 1: "morphism_presheaves_of_rings X is_open \<FF> \<rho> b add_str mult_str zero_str one_str \<FF>' \<rho>' b' add_str' mult_str' zero_str' one_str' \<phi>" and 2: "morphism_presheaves_of_rings X is_open \<FF>' \<rho>' b' add_str' mult_str' zero_str' one_str' \<FF>'' \<rho>'' b'' add_str'' mult_str'' zero_str'' one_str'' \<phi>'" shows "morphism_presheaves_of_rings X is_open \<FF> \<rho> b add_str mult_str zero_str one_str \<FF>'' \<rho>'' b'' add_str'' mult_str'' zero_str'' one_str'' (\<lambda>U. (\<phi>' U \<circ> \<phi> U \<down> \<FF> U))" proof (intro morphism_presheaves_of_rings.intro morphism_presheaves_of_rings_axioms.intro) show "ring_homomorphism (\<phi>' U \<circ> \<phi> U \<down> \<FF> U) (\<FF> U) (add_str U) (mult_str U) (zero_str U) (one_str U) (\<FF>'' U) (add_str'' U) (mult_str'' U) (zero_str'' U) (one_str'' U)" if "is_open U" for U :: "'a set" using that by (metis assms comp_ring_morphisms morphism_presheaves_of_rings.is_ring_morphism) next show "\<And>x. x \<in> (\<FF> U) \<Longrightarrow> (\<rho>'' U V \<circ> (\<phi>' U \<circ> \<phi> U \<down> \<FF> U)) x = (\<phi>' V \<circ> \<phi> V \<down> \<FF> V \<circ> \<rho> U V) x" if "is_open U" "is_open V" "V \<subseteq> U" for U V using that using morphism_presheaves_of_rings.comm_diagrams [OF 1] using morphism_presheaves_of_rings.comm_diagrams [OF 2] using presheaf_of_rings.is_map_from_is_homomorphism [OF morphism_presheaves_of_rings.axioms(1) [OF 1]] by (metis "1" comp_apply compose_eq map.map_closed morphism_presheaves_of_rings.fam_morphisms_are_maps) qed (use assms in \<open>auto simp: morphism_presheaves_of_rings_def\<close>) locale iso_presheaves_of_rings = mor:morphism_presheaves_of_rings + assumes is_inv: "\<exists>\<psi>. morphism_presheaves_of_rings X is_open \<FF>' \<rho>' b' add_str' mult_str' zero_str' one_str' \<FF> \<rho> b add_str mult_str zero_str one_str \<psi> \<and> (\<forall>U. is_open U \<longrightarrow> (\<forall>x \<in> (\<FF>' U). (fam_morphisms U \<circ> \<psi> U) x = x) \<and> (\<forall>x \<in> (\<FF> U). (\<psi> U \<circ> fam_morphisms U) x = x))" subsection \<open>Sheaves of Rings\<close> (* def 0.19 *) locale sheaf_of_rings = presheaf_of_rings + assumes locality: "\<And>U I V s. open_cover_of_open_subset S is_open U I V \<Longrightarrow> (\<And>i. i\<in>I \<Longrightarrow> V i \<subseteq> U) \<Longrightarrow> s \<in> \<FF> U \<Longrightarrow> (\<And>i. i\<in>I \<Longrightarrow> \<rho> U (V i) s = \<zero>\<^bsub>(V i)\<^esub>) \<Longrightarrow> s = \<zero>\<^bsub>U\<^esub>" and glueing: "\<And>U I V s. open_cover_of_open_subset S is_open U I V \<Longrightarrow> (\<forall>i. i\<in>I \<longrightarrow> V i \<subseteq> U \<and> s i \<in> \<FF> (V i)) \<Longrightarrow> (\<And>i j. i\<in>I \<Longrightarrow> j\<in>I \<Longrightarrow> \<rho> (V i) (V i \<inter> V j) (s i) = \<rho> (V j) (V i \<inter> V j) (s j)) \<Longrightarrow> (\<exists>t. t \<in> \<FF> U \<and> (\<forall>i. i\<in>I \<longrightarrow> \<rho> U (V i) t = s i))" (* def. 0.20 *) locale morphism_sheaves_of_rings = morphism_presheaves_of_rings locale iso_sheaves_of_rings = iso_presheaves_of_rings (* ex. 0.21 *) locale ind_sheaf = sheaf_of_rings + fixes U:: "'a set" assumes is_open_subset: "is_open U" begin interpretation it: ind_topology S is_open U by (simp add: ind_topology.intro ind_topology_axioms.intro is_open_subset open_imp_subset topological_space_axioms) definition ind_sheaf:: "'a set \<Rightarrow> 'b set" where "ind_sheaf V \<equiv> \<FF> (U \<inter> V)" definition ind_ring_morphisms:: "'a set \<Rightarrow> 'a set \<Rightarrow> ('b \<Rightarrow> 'b)" where "ind_ring_morphisms V W \<equiv> \<rho> (U \<inter> V) (U \<inter> W)" definition ind_add_str:: "'a set \<Rightarrow> ('b \<Rightarrow> 'b \<Rightarrow> 'b)" where "ind_add_str V \<equiv> \<lambda>x y. +\<^bsub>(U \<inter> V)\<^esub> x y" definition ind_mult_str:: "'a set \<Rightarrow> ('b \<Rightarrow> 'b \<Rightarrow> 'b)" where "ind_mult_str V \<equiv> \<lambda>x y. \<cdot>\<^bsub>(U \<inter> V)\<^esub> x y" definition ind_zero_str:: "'a set \<Rightarrow> 'b" where "ind_zero_str V \<equiv> \<zero>\<^bsub>(U\<inter>V)\<^esub>" definition ind_one_str:: "'a set \<Rightarrow> 'b" where "ind_one_str V \<equiv> \<one>\<^bsub>(U\<inter>V)\<^esub>" lemma ind_is_open_imp_ring: "\<And>U. it.ind_is_open U \<Longrightarrow> ring (ind_sheaf U) (ind_add_str U) (ind_mult_str U) (ind_zero_str U) (ind_one_str U)" unfolding ind_add_str_def it.ind_is_open_def ind_mult_str_def ind_one_str_def ind_sheaf_def ind_zero_str_def using is_open_subset is_ring_from_is_homomorphism it.is_subset open_inter by force lemma ind_sheaf_is_presheaf: shows "presheaf_of_rings U (it.ind_is_open) ind_sheaf ind_ring_morphisms b ind_add_str ind_mult_str ind_zero_str ind_one_str" proof - have "topological_space U it.ind_is_open" by (simp add: it.ind_space_is_top_space) moreover have "ring_homomorphism (ind_ring_morphisms W V) (ind_sheaf W) (ind_add_str W) (ind_mult_str W) (ind_zero_str W) (ind_one_str W) (ind_sheaf V) (ind_add_str V) (ind_mult_str V) (ind_zero_str V) (ind_one_str V)" if "it.ind_is_open W" "it.ind_is_open V" "V \<subseteq> W" for W V proof (intro ring_homomorphism.intro ind_is_open_imp_ring) show "Set_Theory.map (ind_ring_morphisms W V) (ind_sheaf W) (ind_sheaf V)" unfolding ind_ring_morphisms_def ind_sheaf_def by (metis that it.ind_is_open_def inf.left_idem is_open_subset is_ring_morphism open_inter ring_homomorphism_def) from that obtain o: "is_open (U \<inter> V)" "is_open (U \<inter> W)" "U \<inter> V \<subseteq> U \<inter> W" by (metis (no_types) it.ind_is_open_def inf.absorb_iff2 is_open_subset open_inter) then show "group_homomorphism (ind_ring_morphisms W V) (ind_sheaf W) (ind_add_str W) (ind_zero_str W) (ind_sheaf V) (ind_add_str V) (ind_zero_str V)" unfolding ind_ring_morphisms_def ind_sheaf_def ind_zero_str_def by (metis ind_sheaf.ind_add_str_def ind_sheaf_axioms is_ring_morphism ring_homomorphism.axioms(4)) show "monoid_homomorphism (ind_ring_morphisms W V) (ind_sheaf W) (ind_mult_str W) (ind_one_str W) (ind_sheaf V) (ind_mult_str V) (ind_one_str V)" using o by (metis ind_mult_str_def ind_one_str_def ind_ring_morphisms_def ind_sheaf_def is_ring_morphism ring_homomorphism_def) qed (use that in auto) moreover have "ind_sheaf {} = {b}" by (simp add: ring_of_empty ind_sheaf_def) moreover have "\<And>U. it.ind_is_open U \<Longrightarrow> (\<And>x. x \<in> (ind_sheaf U) \<Longrightarrow> ind_ring_morphisms U U x = x)" by (simp add: Int_absorb1 it.ind_is_open_def ind_ring_morphisms_def ind_sheaf_def it.is_open_from_ind_is_open is_open_subset) moreover have "\<And>U V W. it.ind_is_open U \<Longrightarrow> it.ind_is_open V \<Longrightarrow> it.ind_is_open W \<Longrightarrow> V \<subseteq> U \<Longrightarrow> W \<subseteq> V \<Longrightarrow> (\<And>x. x \<in> (ind_sheaf U) \<Longrightarrow> ind_ring_morphisms U W x = (ind_ring_morphisms V W \<circ> ind_ring_morphisms U V) x)" by (metis Int_absorb1 assoc_comp it.ind_is_open_def ind_ring_morphisms_def ind_sheaf_def it.is_open_from_ind_is_open is_open_subset) ultimately show ?thesis unfolding presheaf_of_rings_def presheaf_of_rings_axioms_def by blast qed lemma ind_sheaf_is_sheaf: shows "sheaf_of_rings U it.ind_is_open ind_sheaf ind_ring_morphisms b ind_add_str ind_mult_str ind_zero_str ind_one_str" proof (intro sheaf_of_rings.intro sheaf_of_rings_axioms.intro) show "presheaf_of_rings U it.ind_is_open ind_sheaf ind_ring_morphisms b ind_add_str ind_mult_str ind_zero_str ind_one_str" using ind_sheaf_is_presheaf by blast next fix V I W s assume oc: "open_cover_of_open_subset U it.ind_is_open V I W" and WV: "\<And>i. i \<in> I \<Longrightarrow> W i \<subseteq> V" and s: "s \<in> ind_sheaf V" and eq: "\<And>i. i \<in> I \<Longrightarrow> ind_ring_morphisms V (W i) s = ind_zero_str (W i)" have "it.ind_is_open V" using oc open_cover_of_open_subset.is_open_subset by blast then have "s \<in> \<FF> V" by (metis ind_sheaf.ind_sheaf_def ind_sheaf_axioms it.ind_is_open_def inf.absorb2 s) then have "s = \<zero>\<^bsub>V\<^esub>" by (metis Int_absorb1 Int_subset_iff WV ind_sheaf.ind_zero_str_def ind_sheaf_axioms eq it.ind_is_open_def ind_ring_morphisms_def is_open_subset locality oc it.open_cover_from_ind_open_cover open_cover_of_open_subset.is_open_subset) then show "s = ind_zero_str V" by (metis Int_absorb1 it.ind_is_open_def ind_zero_str_def oc open_cover_of_open_subset.is_open_subset) next fix V I W s assume oc: "open_cover_of_open_subset U it.ind_is_open V I W" and WV: "\<forall>i. i \<in> I \<longrightarrow> W i \<subseteq> V \<and> s i \<in> ind_sheaf (W i)" and eq: "\<And>i j. \<lbrakk>i \<in> I; j \<in> I\<rbrakk> \<Longrightarrow> ind_ring_morphisms (W i) (W i \<inter> W j) (s i) = ind_ring_morphisms (W j) (W i \<inter> W j) (s j)" have "is_open V" using it.is_open_from_ind_is_open is_open_subset oc open_cover_of_open_subset.is_open_subset by blast moreover have "open_cover_of_open_subset S is_open V I W" using it.open_cover_from_ind_open_cover oc ind_topology.intro ind_topology_axioms_def is_open_subset it.is_subset topological_space_axioms by blast moreover have "\<rho> (W i) (W i \<inter> W j) (s i) = \<rho> (W j) (W i \<inter> W j) (s j)" if "i\<in>I" "j\<in>I" for i j proof - have "U \<inter> W i = W i" and "U \<inter> W j = W j" by (metis Int_absorb1 WV it.ind_is_open_def oc open_cover_of_open_subset.is_open_subset subset_trans that)+ then show ?thesis using eq[unfolded ind_ring_morphisms_def,OF that] by (metis inf_sup_aci(2)) qed moreover have "\<forall>i. i\<in>I \<longrightarrow> W i \<subseteq> V \<and> s i \<in> \<FF> (W i)" by (metis WV it.ind_is_open_def ind_sheaf_def inf.orderE inf_idem inf_aci(3) oc open_cover_of_open_subset.is_open_subset) ultimately obtain t where "t \<in> (\<FF> V) \<and> (\<forall>i. i\<in>I \<longrightarrow> \<rho> V (W i) t = s i)" using glueing by blast then have "t \<in> ind_sheaf V" unfolding ind_sheaf_def using oc by (metis Int_absorb1 cover_of_subset_def open_cover_of_open_subset_def open_cover_of_subset_def) moreover have "\<forall>i. i\<in>I \<longrightarrow> ind_ring_morphisms V (W i) t = s i" unfolding ind_ring_morphisms_def by (metis oc Int_absorb1 \<open>t \<in> \<FF> V \<and> (\<forall>i. i \<in> I \<longrightarrow> \<rho> V (W i) t = s i)\<close> cover_of_subset_def open_cover_of_open_subset_def open_cover_of_subset_def) ultimately show "\<exists>t. t \<in> (ind_sheaf V) \<and> (\<forall>i. i\<in>I \<longrightarrow> ind_ring_morphisms V (W i) t = s i)" by blast qed end (* ind_sheaf *) (* construction 0.22 *) locale im_sheaf = sheaf_of_rings + continuous_map begin (* def 0.24 *) definition im_sheaf:: "'c set => 'b set" where "im_sheaf V \<equiv> \<FF> (f\<^sup>\<inverse> S V)" definition im_sheaf_morphisms:: "'c set \<Rightarrow> 'c set \<Rightarrow> ('b \<Rightarrow> 'b)" where "im_sheaf_morphisms U V \<equiv> \<rho> (f\<^sup>\<inverse> S U) (f\<^sup>\<inverse> S V)" definition add_im_sheaf:: "'c set \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b" where "add_im_sheaf \<equiv> \<lambda>V x y. +\<^bsub>(f\<^sup>\<inverse> S V)\<^esub> x y" definition mult_im_sheaf:: "'c set \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b" where "mult_im_sheaf \<equiv> \<lambda>V x y. \<cdot>\<^bsub>(f\<^sup>\<inverse> S V)\<^esub> x y" definition zero_im_sheaf:: "'c set \<Rightarrow> 'b" where "zero_im_sheaf \<equiv> \<lambda>V. \<zero>\<^bsub>(f\<^sup>\<inverse> S V)\<^esub>" definition one_im_sheaf:: "'c set \<Rightarrow> 'b" where "one_im_sheaf \<equiv> \<lambda>V. \<one>\<^bsub>(f\<^sup>\<inverse> S V)\<^esub>" lemma im_sheaf_is_presheaf: "presheaf_of_rings S' (is_open') im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf" proof (intro presheaf_of_rings.intro presheaf_of_rings_axioms.intro) show "topological_space S' is_open'" by (simp add: target.topological_space_axioms) show "\<And>U V. \<lbrakk>is_open' U; is_open' V; V \<subseteq> U\<rbrakk> \<Longrightarrow> ring_homomorphism (im_sheaf_morphisms U V) (im_sheaf U) (add_im_sheaf U) (mult_im_sheaf U) (zero_im_sheaf U) (one_im_sheaf U) (im_sheaf V) (add_im_sheaf V) (mult_im_sheaf V) (zero_im_sheaf V) (one_im_sheaf V)" unfolding add_im_sheaf_def mult_im_sheaf_def zero_im_sheaf_def one_im_sheaf_def by (metis Int_commute Int_mono im_sheaf_def im_sheaf_morphisms_def is_continuous is_ring_morphism subset_refl vimage_mono) show "im_sheaf {} = {b}" using im_sheaf_def ring_of_empty by simp show "\<And>U. is_open' U \<Longrightarrow> (\<And>x. x \<in> (im_sheaf U) \<Longrightarrow> im_sheaf_morphisms U U x = x)" using im_sheaf_morphisms_def by (simp add: im_sheaf_def is_continuous) show "\<And>U V W. \<lbrakk>is_open' U; is_open' V; is_open' W; V \<subseteq> U; W \<subseteq> V\<rbrakk> \<Longrightarrow> (\<And>x. x \<in> (im_sheaf U) \<Longrightarrow> im_sheaf_morphisms U W x = (im_sheaf_morphisms V W \<circ> im_sheaf_morphisms U V) x)" by (metis Int_mono assoc_comp im_sheaf_def im_sheaf_morphisms_def ind_topology.is_subset is_continuous ind_topology_is_open_self vimage_mono) qed (* ex 0.23 *) lemma im_sheaf_is_sheaf: shows "sheaf_of_rings S' (is_open') im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf" proof (intro sheaf_of_rings.intro sheaf_of_rings_axioms.intro) show "presheaf_of_rings S' is_open' im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf" using im_sheaf_is_presheaf by force next fix U I V s assume oc: "open_cover_of_open_subset S' is_open' U I V" and VU: "\<And>i. i \<in> I \<Longrightarrow> V i \<subseteq> U" and s: "s \<in> im_sheaf U" and eq0: "\<And>i. i \<in> I \<Longrightarrow> im_sheaf_morphisms U (V i) s =zero_im_sheaf (V i)" have "open_cover_of_open_subset S is_open (f\<^sup>\<inverse> S U) I (\<lambda>i. f\<^sup>\<inverse> S (V i))" by (simp add: oc open_cover_of_open_subset_from_target_to_source) then show "s = zero_im_sheaf U" using zero_im_sheaf_def by (smt VU im_sheaf_def im_sheaf_morphisms_def eq0 inf.absorb_iff2 inf_le2 inf_sup_aci(1) inf_sup_aci(3) locality s vimage_Int) next fix U I V s assume oc: "open_cover_of_open_subset S' is_open' U I V" and VU: "\<forall>i. i \<in> I \<longrightarrow> V i \<subseteq> U \<and> s i \<in> im_sheaf (V i)" and eq: "\<And>i j. \<lbrakk>i \<in> I; j \<in> I\<rbrakk> \<Longrightarrow> im_sheaf_morphisms (V i) (V i \<inter> V j) (s i) = im_sheaf_morphisms (V j) (V i \<inter> V j) (s j)" have "\<exists>t. t \<in> \<FF> (f \<^sup>\<inverse> S U) \<and> (\<forall>i. i \<in> I \<longrightarrow> \<rho> (f \<^sup>\<inverse> S U) (f \<^sup>\<inverse> S (V i)) t = s i)" proof (rule glueing) show "open_cover_of_open_subset S is_open (f \<^sup>\<inverse> S U) I (\<lambda>i. f \<^sup>\<inverse> S (V i))" using oc open_cover_of_open_subset_from_target_to_source by presburger show "\<forall>i. i \<in> I \<longrightarrow> f \<^sup>\<inverse> S (V i) \<subseteq> f \<^sup>\<inverse> S U \<and> s i \<in> \<FF> (f \<^sup>\<inverse> S (V i))" using VU im_sheaf_def by blast show "\<rho> (f \<^sup>\<inverse> S (V i)) (f \<^sup>\<inverse> S (V i) \<inter> f \<^sup>\<inverse> S (V j)) (s i) = \<rho> (f \<^sup>\<inverse> S (V j)) (f \<^sup>\<inverse> S (V i) \<inter> f \<^sup>\<inverse> S (V j)) (s j)" if "i \<in> I" "j \<in> I" for i j using im_sheaf_morphisms_def eq that by (smt Int_commute Int_left_commute inf.left_idem vimage_Int) qed then obtain t where "t \<in> \<FF> (f\<^sup>\<inverse> S U) \<and> (\<forall>i. i\<in>I \<longrightarrow> \<rho> (f\<^sup>\<inverse> S U) (f\<^sup>\<inverse> S (V i)) t = s i)" .. then show "\<exists>t. t \<in> im_sheaf U \<and> (\<forall>i. i \<in> I \<longrightarrow> im_sheaf_morphisms U (V i) t = s i)" using im_sheaf_def im_sheaf_morphisms_def by auto qed sublocale sheaf_of_rings S' is_open' im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf using im_sheaf_is_sheaf . end (* im_sheaf *) lemma (in sheaf_of_rings) id_to_iso_of_sheaves: shows "iso_sheaves_of_rings S is_open \<FF> \<rho> b add_str mult_str zero_str one_str (im_sheaf.im_sheaf S \<FF> (identity S)) (im_sheaf.im_sheaf_morphisms S \<rho> (identity S)) b (\<lambda>V. +\<^bsub>identity S \<^sup>\<inverse> S V\<^esub>) (\<lambda>V. \<cdot>\<^bsub>identity S \<^sup>\<inverse> S V\<^esub>) (\<lambda>V. \<zero>\<^bsub>identity S \<^sup>\<inverse> S V\<^esub>) (\<lambda>V. \<one>\<^bsub>identity S \<^sup>\<inverse> S V\<^esub>) (\<lambda>U. identity (\<FF> U))" (is "iso_sheaves_of_rings S is_open \<FF> \<rho> b _ _ _ _ _ _ b ?add ?mult ?zero ?one ?F") proof- have preq[simp]: "\<And>V. V \<subseteq> S \<Longrightarrow> (identity S \<^sup>\<inverse> S V) = V" by auto interpret id: im_sheaf S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open "identity S" by intro_locales (auto simp add: Set_Theory.map_def continuous_map_axioms_def open_imp_subset) have 1[simp]: "\<And>V. V \<subseteq> S \<Longrightarrow> im_sheaf.im_sheaf S \<FF> (identity S) V = \<FF> V" by (simp add: id.im_sheaf_def) have 2[simp]: "\<And>U V. \<lbrakk>U \<subseteq> S; V \<subseteq> S\<rbrakk> \<Longrightarrow> im_sheaf.im_sheaf_morphisms S \<rho> (identity S) U V \<equiv> \<rho> U V" using id.im_sheaf_morphisms_def by auto show ?thesis proof intro_locales have rh: "\<And>U. is_open U \<Longrightarrow> ring_homomorphism (identity (\<FF> U)) (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub> (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub>" using id_is_mor_pr_rngs morphism_presheaves_of_rings.is_ring_morphism by fastforce show "morphism_presheaves_of_rings_axioms is_open \<FF> \<rho> add_str mult_str zero_str one_str id.im_sheaf id.im_sheaf_morphisms ?add ?mult ?zero ?one ?F" unfolding morphism_presheaves_of_rings_axioms_def by (auto simp: rh open_imp_subset intro: is_map_from_is_homomorphism map.map_closed) have \<rho>: "\<And>U V W x. \<lbrakk>is_open U; is_open V; is_open W; V \<subseteq> U; W \<subseteq> V; x \<in> \<FF> U\<rbrakk> \<Longrightarrow> \<rho> V W (\<rho> U V x) = \<rho> U W x" by (metis assoc_comp comp_def) show "presheaf_of_rings_axioms is_open id.im_sheaf id.im_sheaf_morphisms b ?add ?mult ?zero ?one" by (auto simp: \<rho> presheaf_of_rings_axioms_def is_ring_morphism open_imp_subset ring_of_empty) then have "presheaf_of_rings S is_open id.im_sheaf id.im_sheaf_morphisms b ?add ?mult ?zero ?one" by (metis id.im_sheaf_is_presheaf presheaf_of_rings_def) moreover have "morphism_presheaves_of_rings_axioms is_open id.im_sheaf id.im_sheaf_morphisms ?add ?mult ?zero ?one \<FF> \<rho> add_str mult_str zero_str one_str (\<lambda>U. \<lambda>x\<in>\<FF> U. x)" unfolding morphism_presheaves_of_rings_axioms_def by (auto simp: rh open_imp_subset intro: is_map_from_is_homomorphism map.map_closed) ultimately show "iso_presheaves_of_rings_axioms S is_open \<FF> \<rho> b add_str mult_str zero_str one_str id.im_sheaf id.im_sheaf_morphisms b ?add ?mult ?zero ?one ?F" by (auto simp: presheaf_of_rings_axioms iso_presheaves_of_rings_axioms_def morphism_presheaves_of_rings_def open_imp_subset) qed qed subsection \<open>Quotient Ring\<close> (*Probably for Group_Theory*) context group begin lemma cancel_imp_equal: "\<lbrakk> u \<cdot> inverse v = \<one>; u \<in> G; v \<in> G \<rbrakk> \<Longrightarrow> u = v" by (metis invertible invertible_inverse_closed invertible_right_cancel invertible_right_inverse) end (*Probably for Ring_Theory*) context ring begin lemma inverse_distributive: "\<lbrakk> a \<in> R; b \<in> R; c \<in> R \<rbrakk> \<Longrightarrow> a \<cdot> (b - c) = a \<cdot> b - a \<cdot> c" "\<lbrakk> a \<in> R; b \<in> R; c \<in> R \<rbrakk> \<Longrightarrow> (b - c) \<cdot> a = b \<cdot> a - c \<cdot> a" using additive.invertible additive.invertible_inverse_closed distributive local.left_minus local.right_minus by presburger+ end locale quotient_ring = comm:comm_ring R "(+)" "(\<cdot>)" "\<zero>" "\<one>" + submonoid S R "(\<cdot>)" "\<one>" for S and R and addition (infixl "+" 65) and multiplication (infixl "\<cdot>" 70) and zero ("\<zero>") and unit ("\<one>") begin lemmas comm_ring_simps = comm.multiplicative.associative comm.additive.associative comm.comm_mult comm.additive.commutative right_minus definition rel:: "('a \<times> 'a) \<Rightarrow> ('a \<times> 'a) \<Rightarrow> bool" (infix "\<sim>" 80) where "x \<sim> y \<equiv> \<exists>s1. s1 \<in> S \<and> s1 \<cdot> (snd y \<cdot> fst x - snd x \<cdot> fst y) = \<zero>" lemma rel_refl: "\<And>x. x \<in> R \<times> S \<Longrightarrow> x \<sim> x" by (auto simp: rel_def) lemma rel_sym: assumes "x \<sim> y" "x \<in> R \<times> S" "y \<in> R \<times> S" shows "y \<sim> x" proof - obtain rx sx ry sy s where \<section>: "rx \<in> R" "sx \<in> S" "ry \<in> R" "s \<in> S" "sy \<in> S" "s \<cdot> (sy \<cdot> rx - sx \<cdot> ry) = \<zero>" "x = (rx,sx)" "y = (ry,sy)" using assms by (auto simp: rel_def) then have "s \<cdot> (sx \<cdot> ry - sy \<cdot> rx) = \<zero>" by (metis sub comm.additive.cancel_imp_equal comm.inverse_distributive(1) comm.multiplicative.composition_closed) with \<section> show ?thesis by (auto simp: rel_def) qed lemma rel_trans: assumes "x \<sim> y" "y \<sim> z" "x \<in> R \<times> S" "y \<in> R \<times> S" "z \<in> R \<times> S" shows "x \<sim> z" using assms proof (clarsimp simp: rel_def) fix r s r2 s2 r1 s1 sx sy assume \<section>: "r \<in> R" "s \<in> S" "r1 \<in> R" "s1 \<in> S" "sx \<in> S" "r2 \<in> R" "s2 \<in> S" "sy \<in> S" and sx0: "sx \<cdot> (s1 \<cdot> r2 - s2 \<cdot> r1) = \<zero>" and sy0: "sy \<cdot> (s2 \<cdot> r - s \<cdot> r2) = \<zero>" show "\<exists>u. u \<in> S \<and> u \<cdot> (s1 \<cdot> r - s \<cdot> r1) = \<zero>" proof (intro exI conjI) show "sx \<cdot> sy \<cdot> s1 \<cdot> s2 \<in> S" using \<section> by blast have sx: "sx \<cdot> s1 \<cdot> r2 = sx \<cdot> s2 \<cdot> r1" and sy: "sy \<cdot> s2 \<cdot> r = sy \<cdot> s \<cdot> r2" using sx0 sy0 \<section> comm.additive.cancel_imp_equal comm.inverse_distributive(1) comm.multiplicative.associative comm.multiplicative.composition_closed sub by metis+ then have "sx \<cdot> sy \<cdot> s1 \<cdot> s2 \<cdot> (s1 \<cdot> r - s \<cdot> r1) = sx \<cdot> sy \<cdot> s1 \<cdot> s2 \<cdot> s1 \<cdot> r - sx \<cdot> sy \<cdot> s1 \<cdot> s2 \<cdot> s \<cdot> r1" using "\<section>" \<open>sx \<cdot> sy \<cdot> s1 \<cdot> s2 \<in> S\<close> comm.inverse_distributive(1) comm.multiplicative.associative comm.multiplicative.composition_closed sub by presburger also have "... = sx \<cdot> sy \<cdot> s1 \<cdot> s \<cdot> s1 \<cdot> r2 - sx \<cdot> sy \<cdot> s1 \<cdot> s2 \<cdot> s \<cdot> r1" using \<section> by (smt sy comm.comm_mult comm.multiplicative.associative comm.multiplicative.composition_closed sub) also have "... = sx \<cdot> sy \<cdot> s1 \<cdot> s \<cdot> s1 \<cdot> r2 - sx \<cdot> sy \<cdot> s1 \<cdot> s1 \<cdot> s \<cdot> r2" using \<section> by (smt sx comm.comm_mult comm.multiplicative.associative comm.multiplicative.composition_closed sub) also have "... = \<zero>" using \<section> by (simp add: comm.ring_mult_ac) finally show "sx \<cdot> sy \<cdot> s1 \<cdot> s2 \<cdot> (s1 \<cdot> r - s \<cdot> r1) = \<zero>" . qed qed interpretation rel: equivalence "R \<times> S" "{(x,y) \<in> (R\<times>S)\<times>(R\<times>S). x \<sim> y}" by (blast intro: equivalence.intro rel_refl rel_sym rel_trans) notation equivalence.Partition (infixl "'/" 75) definition frac:: "'a \<Rightarrow> 'a \<Rightarrow> ('a \<times> 'a) set" (infixl "'/" 75) where "r / s \<equiv> rel.Class (r, s)" lemma frac_Pow:"(r, s) \<in> R \<times> S \<Longrightarrow> frac r s \<in> Pow (R \<times> S) " using local.frac_def rel.Class_closed2 by auto lemma frac_eqI: assumes "s1\<in>S" and "(r, s) \<in> R \<times> S" "(r', s') \<in> R \<times> S" and eq:"s1 \<cdot> s' \<cdot> r = s1 \<cdot> s \<cdot> r'" shows "frac r s = frac r' s'" unfolding frac_def proof (rule rel.Class_eq) have "s1 \<cdot> (s' \<cdot> r - s \<cdot> r') = \<zero>" using assms comm.inverse_distributive(1) comm.multiplicative.associative by auto with \<open>s1\<in>S\<close> have "(r, s) \<sim> (r', s')" unfolding rel_def by auto then show "((r, s), r', s') \<in> {(x, y). (x, y) \<in> (R \<times> S) \<times> R \<times> S \<and> x \<sim> y}" using assms(2,3) by auto qed lemma frac_eq_Ex: assumes "(r, s) \<in> R \<times> S" "(r', s') \<in> R \<times> S" "frac r s = frac r' s'" obtains s1 where "s1\<in>S" "s1 \<cdot> (s' \<cdot> r - s \<cdot> r') = \<zero>" proof - have "(r, s) \<sim> (r', s')" using \<open>frac r s = frac r' s'\<close> rel.Class_equivalence[OF assms(1,2)] unfolding frac_def by auto then show ?thesis unfolding rel_def by (metis fst_conv snd_conv that) qed lemma frac_cancel: assumes "s1\<in>S" and "(r, s) \<in> R \<times> S" shows "frac (s1\<cdot>r) (s1\<cdot>s) = frac r s" apply (rule frac_eqI[of \<one>]) using assms comm_ring_simps by auto lemma frac_eq_obtains: assumes "(r,s) \<in> R \<times> S" and x_def:"x=(SOME x. x\<in>(frac r s))" obtains s1 where "s1\<in>S" "s1 \<cdot> s \<cdot> fst x = s1 \<cdot> snd x \<cdot> r" and "x \<in> R \<times> S" proof - have "x\<in>(r/s)" unfolding x_def apply (rule someI[of _ "(r,s)"]) using assms(1) local.frac_def by blast from rel.ClassD[OF this[unfolded frac_def] \<open>(r,s) \<in> R \<times> S\<close>] have x_RS:"x\<in>R \<times> S" and "x \<sim> (r,s)" by auto from this(2) obtain s1 where "s1\<in>S" and "s1 \<cdot> (s \<cdot> fst x - snd x \<cdot> r) = \<zero>" unfolding rel_def by auto then have x_eq:"s1 \<cdot> s \<cdot> fst x = s1 \<cdot> snd x \<cdot> r" using comm.distributive x_RS assms(1) by (smt comm.additive.group_axioms group.cancel_imp_equal comm.inverse_distributive(1) mem_Sigma_iff comm.multiplicative.associative comm.multiplicative.composition_closed prod.collapse sub) then show ?thesis using that x_RS \<open>s1\<in>S\<close> by auto qed definition valid_frac::"('a \<times> 'a) set \<Rightarrow> bool" where "valid_frac X \<equiv> \<exists>r\<in>R. \<exists>s\<in>S. r / s = X" lemma frac_non_empty[simp]:"(a,b) \<in> R \<times> S \<Longrightarrow> valid_frac (frac a b)" unfolding frac_def valid_frac_def by blast definition add_rel_aux:: "'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> ('a \<times> 'a) set" where "add_rel_aux r s r' s' \<equiv> (r\<cdot>s' + r'\<cdot>s) / (s\<cdot>s')" definition add_rel:: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set" where "add_rel X Y \<equiv> let x = (SOME x. x \<in> X) in let y = (SOME y. y \<in> Y) in add_rel_aux (fst x) (snd x) (fst y) (snd y)" lemma add_rel_frac: assumes "(r,s) \<in> R \<times> S" "(r',s')\<in> R \<times> S" shows "add_rel (r/s) (r'/s') = (r\<cdot>s' + r'\<cdot>s) / (s\<cdot>s')" proof - define x where "x=(SOME x. x\<in>(r/s))" define y where "y=(SOME y. y\<in>(r'/s'))" obtain s1 where [simp]:"s1 \<in> S" and x_eq:"s1 \<cdot> s \<cdot> fst x = s1 \<cdot> snd x \<cdot> r" and x_RS:"x \<in> R \<times> S" using frac_eq_obtains[OF \<open>(r,s) \<in> R \<times> S\<close> x_def] by auto obtain s2 where [simp]:"s2 \<in> S" and y_eq:"s2 \<cdot> s' \<cdot> fst y = s2 \<cdot> snd y \<cdot> r'" and y_RS:"y \<in> R \<times> S" using frac_eq_obtains[OF \<open>(r',s') \<in> R \<times> S\<close> y_def] by auto have "add_rel (r/s) (r'/s') = (fst x \<cdot> snd y + fst y \<cdot> snd x) / (snd x \<cdot> snd y)" unfolding add_rel_def add_rel_aux_def x_def y_def Let_def by auto also have "... = (r\<cdot>s' + r'\<cdot>s) / (s\<cdot>s')" proof (rule frac_eqI[of "s1 \<cdot> s2"]) have "snd y \<cdot> s' \<cdot> s2 \<cdot> (s1 \<cdot> s \<cdot> fst x) = snd y \<cdot> s' \<cdot> s2 \<cdot> (s1 \<cdot> snd x \<cdot> r)" using x_eq by simp then have "s1 \<cdot> s2 \<cdot> s \<cdot> s' \<cdot> fst x \<cdot> snd y = s1 \<cdot> s2 \<cdot> snd x \<cdot> snd y \<cdot> r \<cdot> s'" using comm.multiplicative.associative assms x_RS y_RS comm.comm_mult by auto moreover have "snd x \<cdot> s \<cdot>s1 \<cdot> (s2 \<cdot> s' \<cdot> fst y) = snd x \<cdot> s \<cdot>s1 \<cdot> (s2 \<cdot> snd y \<cdot> r')" using y_eq by simp then have "s1 \<cdot> s2 \<cdot> s \<cdot> s' \<cdot> fst y \<cdot> snd x = s1 \<cdot> s2 \<cdot> snd x \<cdot> snd y \<cdot> r' \<cdot> s" using comm.multiplicative.associative assms x_RS y_RS comm.comm_mult by auto ultimately show "s1 \<cdot> s2 \<cdot> (s \<cdot> s') \<cdot> (fst x \<cdot> snd y + fst y \<cdot> snd x) = s1 \<cdot> s2 \<cdot> (snd x \<cdot> snd y) \<cdot> (r \<cdot> s' + r' \<cdot> s)" using comm.multiplicative.associative assms x_RS y_RS comm.distributive by auto show "s1 \<cdot> s2 \<in> S" "(fst x \<cdot> snd y + fst y \<cdot> snd x, snd x \<cdot> snd y) \<in> R \<times> S" "(r \<cdot> s' + r' \<cdot> s, s \<cdot> s') \<in> R \<times> S" using assms x_RS y_RS by auto qed finally show ?thesis by auto qed lemma valid_frac_add[intro,simp]: assumes "valid_frac X" "valid_frac Y" shows "valid_frac (add_rel X Y)" proof - obtain r s r' s' where "r\<in>R" "s\<in>S" "r'\<in>R" "s'\<in>S" and *:"add_rel X Y = (r\<cdot>s' + r'\<cdot>s) / (s\<cdot>s')" proof - define x where "x=(SOME x. x\<in>X)" define y where "y=(SOME y. y\<in>Y)" have "x\<in>X" "y\<in>Y" using assms unfolding x_def y_def valid_frac_def some_in_eq local.frac_def by blast+ then obtain "x \<in> R \<times> S" "y \<in> R \<times> S" using assms by (simp add: valid_frac_def x_def y_def) (metis frac_eq_obtains mem_Sigma_iff) moreover have "add_rel X Y = (fst x \<cdot> snd y + fst y \<cdot> snd x) / (snd x \<cdot> snd y)" unfolding add_rel_def add_rel_aux_def x_def y_def Let_def by auto ultimately show ?thesis using that by auto qed from this(1-4) have "(r\<cdot>s' + r'\<cdot>s,s\<cdot>s') \<in> R \<times> S" by auto with * show ?thesis by auto qed definition uminus_rel:: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set" where "uminus_rel X \<equiv> let x = (SOME x. x \<in> X) in (comm.additive.inverse (fst x) / snd x)" lemma uminus_rel_frac: assumes "(r,s) \<in> R \<times> S" shows "uminus_rel (r/s) = (comm.additive.inverse r) / s" proof - define x where "x=(SOME x. x\<in>(r/s))" obtain s1 where [simp]:"s1 \<in> S" and x_eq:"s1 \<cdot> s \<cdot> fst x = s1 \<cdot> snd x \<cdot> r" and x_RS:"x \<in> R \<times> S" using frac_eq_obtains[OF \<open>(r,s) \<in> R \<times> S\<close> x_def] by auto have "uminus_rel (r/s)= (comm.additive.inverse (fst x)) / (snd x )" unfolding uminus_rel_def x_def Let_def by auto also have "... = (comm.additive.inverse r) / s" apply (rule frac_eqI[of s1]) using x_RS assms x_eq by (auto simp add: comm.right_minus) finally show ?thesis . qed lemma valid_frac_uminus[intro,simp]: assumes "valid_frac X" shows "valid_frac (uminus_rel X)" proof - obtain r s where "r\<in>R" "s\<in>S" and *:"uminus_rel X = (comm.additive.inverse r) / s" proof - define x where "x=(SOME x. x\<in>X)" have "x\<in>X" using assms unfolding x_def valid_frac_def some_in_eq local.frac_def by blast then have "x\<in> R \<times> S" using assms valid_frac_def by (metis frac_eq_obtains mem_Sigma_iff x_def) moreover have "uminus_rel X = (comm.additive.inverse (fst x) ) / (snd x)" unfolding uminus_rel_def x_def Let_def by auto ultimately show ?thesis using that by auto qed from this(1-3) have "(comm.additive.inverse r,s) \<in> R \<times> S" by auto with * show ?thesis by auto qed definition mult_rel_aux:: "'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> ('a \<times> 'a) set" where "mult_rel_aux r s r' s' \<equiv> (r\<cdot>r') / (s\<cdot>s')" definition mult_rel:: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set" where "mult_rel X Y \<equiv> let x = (SOME x. x \<in> X) in let y = (SOME y. y \<in> Y) in mult_rel_aux (fst x) (snd x) (fst y) (snd y)" lemma mult_rel_frac: assumes "(r,s) \<in> R \<times> S" "(r',s')\<in> R \<times> S" shows "mult_rel (r/s) (r'/s') = (r\<cdot> r') / (s\<cdot>s')" proof - define x where "x=(SOME x. x\<in>(r/s))" define y where "y=(SOME y. y\<in>(r'/s'))" obtain s1 where [simp]:"s1 \<in> S" and x_eq:"s1 \<cdot> s \<cdot> fst x = s1 \<cdot> snd x \<cdot> r" and x_RS:"x \<in> R \<times> S" using frac_eq_obtains[OF \<open>(r,s) \<in> R \<times> S\<close> x_def] by auto obtain s2 where [simp]:"s2 \<in> S" and y_eq:"s2 \<cdot> s' \<cdot> fst y = s2 \<cdot> snd y \<cdot> r'" and y_RS:"y \<in> R \<times> S" using frac_eq_obtains[OF \<open>(r',s') \<in> R \<times> S\<close> y_def] by auto have "mult_rel (r/s) (r'/s') = (fst x \<cdot> fst y ) / (snd x \<cdot> snd y)" unfolding mult_rel_def mult_rel_aux_def x_def y_def Let_def by auto also have "... = (r\<cdot> r') / (s\<cdot>s')" proof (rule frac_eqI[of "s1 \<cdot> s2"]) have "(s1 \<cdot> s \<cdot> fst x) \<cdot> (s2 \<cdot> s' \<cdot> fst y) = (s1 \<cdot> snd x \<cdot> r) \<cdot> (s2 \<cdot> snd y \<cdot> r')" using x_eq y_eq by auto then show "s1 \<cdot> s2 \<cdot> (s \<cdot> s') \<cdot> (fst x \<cdot> fst y) = s1 \<cdot> s2 \<cdot> (snd x \<cdot> snd y) \<cdot> (r \<cdot> r')" using comm.multiplicative.associative assms x_RS y_RS comm.distributive comm.comm_mult by auto show "s1 \<cdot> s2 \<in> S" "(fst x \<cdot> fst y, snd x \<cdot> snd y) \<in> R \<times> S" "(r \<cdot> r', s \<cdot> s') \<in> R \<times> S" using assms x_RS y_RS by auto qed finally show ?thesis by auto qed lemma valid_frac_mult[intro,simp]: assumes "valid_frac X" "valid_frac Y" shows "valid_frac (mult_rel X Y)" proof - obtain r s r' s' where "r\<in>R" "s\<in>S" "r'\<in>R" "s'\<in>S" and *:"mult_rel X Y = (r\<cdot> r') / (s\<cdot>s')" proof - define x where "x=(SOME x. x\<in>X)" define y where "y=(SOME y. y\<in>Y)" have "x\<in>X" "y\<in>Y" using assms unfolding x_def y_def valid_frac_def some_in_eq local.frac_def by blast+ then obtain "x \<in> R \<times> S" "y \<in> R \<times> S" using assms by (simp add: valid_frac_def x_def y_def) (metis frac_eq_obtains mem_Sigma_iff) moreover have "mult_rel X Y = (fst x \<cdot> fst y) / (snd x \<cdot> snd y)" unfolding mult_rel_def mult_rel_aux_def x_def y_def Let_def by auto ultimately show ?thesis using that by auto qed from this(1-4) have "(r\<cdot>r',s\<cdot>s') \<in> R \<times> S" by auto with * show ?thesis by auto qed definition zero_rel::"('a \<times> 'a) set" where "zero_rel = frac \<zero> \<one>" definition one_rel::"('a \<times> 'a) set" where "one_rel = frac \<one> \<one>" lemma valid_frac_zero[simp]: "valid_frac zero_rel" unfolding zero_rel_def valid_frac_def by blast lemma valid_frac_one[simp]: "valid_frac one_rel" unfolding one_rel_def valid_frac_def by blast definition carrier_quotient_ring:: "('a \<times> 'a) set set" where "carrier_quotient_ring \<equiv> rel.Partition" lemma carrier_quotient_ring_iff[iff]: "X \<in> carrier_quotient_ring \<longleftrightarrow> valid_frac X " unfolding valid_frac_def carrier_quotient_ring_def using local.frac_def rel.natural.map_closed rel.representant_exists by fastforce lemma frac_from_carrier: assumes "X \<in> carrier_quotient_ring" obtains r s where "r \<in> R" "s \<in> S" "X = rel.Class (r,s)" using assms carrier_quotient_ring_def by (metis (no_types, lifting) SigmaE rel.representant_exists) lemma add_minus_zero_rel: assumes "valid_frac a" shows "add_rel a (uminus_rel a) = zero_rel" proof - obtain a1 a2 where a_RS:"(a1, a2)\<in>R \<times> S" and a12:"a = a1 / a2 " using \<open>valid_frac a\<close> unfolding valid_frac_def by auto have "add_rel a (uminus_rel a) = \<zero> / (a2 \<cdot> a2)" unfolding a12 using comm_ring_simps a_RS by (simp add:add_rel_frac uminus_rel_frac comm.right_minus) also have "... = \<zero> / \<one>" apply (rule frac_eqI[of \<one>]) using a_RS by auto also have "... = zero_rel" unfolding zero_rel_def .. finally show "add_rel a (uminus_rel a) = zero_rel" . qed (* ex. 0.26 *) sublocale comm_ring carrier_quotient_ring add_rel mult_rel zero_rel one_rel proof (unfold_locales; unfold carrier_quotient_ring_iff) show add_assoc:"add_rel (add_rel a b) c = add_rel a (add_rel b c)" and mult_assoc:"mult_rel (mult_rel a b) c = mult_rel a (mult_rel b c)" and distr:"mult_rel a (add_rel b c) = add_rel (mult_rel a b) (mult_rel a c)" if "valid_frac a" and "valid_frac b" and "valid_frac c" for a b c proof - obtain a1 a2 where a_RS:"(a1, a2)\<in>R \<times> S" and a12:"a = a1 / a2 " using \<open>valid_frac a\<close> unfolding valid_frac_def by auto obtain b1 b2 where b_RS:"(b1, b2)\<in>R \<times> S" and b12:"b = b1 / b2 " using \<open>valid_frac b\<close> unfolding valid_frac_def by auto obtain c1 c2 where c_RS:"(c1, c2)\<in>R \<times> S" and c12:"c = c1 / c2" using \<open>valid_frac c\<close> unfolding valid_frac_def by auto have "add_rel (add_rel a b) c = add_rel (add_rel (a1/a2) (b1/b2)) (c1/c2)" using a12 b12 c12 by auto also have "... = ((a1 \<cdot> b2 + b1 \<cdot> a2) \<cdot> c2 + c1 \<cdot> (a2 \<cdot> b2)) / (a2 \<cdot> b2 \<cdot> c2)" using a_RS b_RS c_RS by (simp add:add_rel_frac) also have "... = add_rel (a1/a2) (add_rel (b1/b2) (c1/c2))" using a_RS b_RS c_RS comm.distributive comm_ring_simps by (auto simp add:add_rel_frac) also have "... = add_rel a (add_rel b c)" using a12 b12 c12 by auto finally show "add_rel (add_rel a b) c = add_rel a (add_rel b c)" . show "mult_rel (mult_rel a b) c = mult_rel a (mult_rel b c)" unfolding a12 b12 c12 using comm_ring_simps a_RS b_RS c_RS by (auto simp add:mult_rel_frac) have "mult_rel a (add_rel b c) = (a1 \<cdot> (b1 \<cdot> c2 + c1 \<cdot> b2)) / (a2 \<cdot> (b2 \<cdot> c2))" unfolding a12 b12 c12 using a_RS b_RS c_RS by (simp add:mult_rel_frac add_rel_frac) also have "... = (a2 \<cdot> (a1 \<cdot> (b1 \<cdot> c2 + c1 \<cdot> b2))) / (a2 \<cdot> (a2 \<cdot> (b2 \<cdot> c2)))" using a_RS b_RS c_RS by (simp add:frac_cancel) also have "... = add_rel (mult_rel a b) (mult_rel a c)" unfolding a12 b12 c12 using comm_ring_simps a_RS b_RS c_RS comm.distributive by (auto simp add:mult_rel_frac add_rel_frac) finally show "mult_rel a (add_rel b c) = add_rel (mult_rel a b) (mult_rel a c)" . qed show add_0:"add_rel zero_rel a = a" and mult_1:"mult_rel one_rel a = a" if "valid_frac a" for a proof - obtain a1 a2 where a_RS:"(a1, a2)\<in>R \<times> S" and a12:"a = a1 / a2 " using \<open>valid_frac a\<close> unfolding valid_frac_def by auto have "add_rel zero_rel a = add_rel zero_rel (a1/a2)" using a12 by simp also have "... = (a1/a2)" using a_RS comm_ring_simps comm.distributive zero_rel_def by (auto simp add:add_rel_frac) also have "... = a" using a12 by auto finally show "add_rel zero_rel a = a" . show "mult_rel one_rel a = a" unfolding a12 one_rel_def using a_RS by (auto simp add:mult_rel_frac) qed show add_commute:"add_rel a b = add_rel b a" and mult_commute:"mult_rel a b = mult_rel b a" if "valid_frac a" and "valid_frac b" for a b proof - obtain a1 a2 where a_RS:"(a1, a2)\<in>R \<times> S" and a12:"a = a1 / a2 " using \<open>valid_frac a\<close> unfolding valid_frac_def by auto obtain b1 b2 where b_RS:"(b1, b2)\<in>R \<times> S" and b12:"b = b1 / b2 " using \<open>valid_frac b\<close> unfolding valid_frac_def by auto show "add_rel a b = add_rel b a" "mult_rel a b = mult_rel b a" unfolding a12 b12 using comm_ring_simps a_RS b_RS by (auto simp add:mult_rel_frac add_rel_frac) qed show "add_rel a zero_rel = a" if "valid_frac a" for a using that add_0 add_commute by auto show "mult_rel a one_rel = a" if "valid_frac a" for a using that mult_commute mult_1 by auto show "monoid.invertible carrier_quotient_ring add_rel zero_rel a" if "valid_frac a" for a proof - have "Group_Theory.monoid carrier_quotient_ring add_rel zero_rel" apply (unfold_locales) using add_0 add_assoc add_commute by simp_all moreover have "add_rel a (uminus_rel a) = zero_rel" "add_rel (uminus_rel a) a = zero_rel" using add_minus_zero_rel add_commute that by auto ultimately show "monoid.invertible carrier_quotient_ring add_rel zero_rel a" unfolding monoid.invertible_def apply (rule monoid.invertibleI) using add_commute \<open>valid_frac a\<close> by auto qed show "mult_rel (add_rel b c) a = add_rel (mult_rel b a) (mult_rel c a)" if "valid_frac a" and "valid_frac b" and "valid_frac c" for a b c using that mult_commute add_commute distr by (simp add: valid_frac_add) qed auto end (* quotient_ring *) notation quotient_ring.carrier_quotient_ring ("(_ \<^sup>\<inverse> _/ \<^bsub>(2_ _ _))\<^esub>" [60,1000,1000,1000,1000]1000) subsection \<open>Local Rings at Prime Ideals\<close> context pr_ideal begin lemma submonoid_pr_ideal: shows "submonoid (R \<setminus> I) R (\<cdot>) \<one>" proof show "a \<cdot> b \<in> R\<setminus>I" if "a \<in> R\<setminus>I" "b \<in> R\<setminus>I" for a b using that by (metis Diff_iff absorbent comm.multiplicative.composition_closed) show "\<one> \<in> R\<setminus>I" using ideal.ideal(2) ideal_axioms pr_ideal.carrier_neq pr_ideal_axioms by fastforce qed auto interpretation local:quotient_ring "(R \<setminus> I)" R "(+)" "(\<cdot>)" \<zero> \<one> by intro_locales (meson submonoid_def submonoid_pr_ideal) (* definition 0.28 *) definition carrier_local_ring_at:: "('a \<times> 'a) set set" where "carrier_local_ring_at \<equiv> (R \<setminus> I)\<^sup>\<inverse> R\<^bsub>(+) (\<cdot>) \<zero>\<^esub>" definition add_local_ring_at:: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set" where "add_local_ring_at \<equiv> local.add_rel " definition mult_local_ring_at:: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set" where "mult_local_ring_at \<equiv> local.mult_rel " definition uminus_local_ring_at:: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set" where "uminus_local_ring_at \<equiv> local.uminus_rel " definition zero_local_ring_at:: "('a \<times> 'a) set" where "zero_local_ring_at \<equiv> local.zero_rel" definition one_local_ring_at:: "('a \<times> 'a) set" where "one_local_ring_at \<equiv> local.one_rel" sublocale comm_ring carrier_local_ring_at add_local_ring_at mult_local_ring_at zero_local_ring_at one_local_ring_at by (simp add: add_local_ring_at_def carrier_local_ring_at_def local.local.comm_ring_axioms mult_local_ring_at_def one_local_ring_at_def zero_local_ring_at_def) lemma frac_from_carrier_local: assumes "X \<in> carrier_local_ring_at" obtains r s where "r \<in> R" "s \<in> R" "s \<notin> I" "X = local.frac r s" proof- have "X \<in> (R \<setminus> I)\<^sup>\<inverse> R\<^bsub>(+) (\<cdot>) \<zero>\<^esub>" using assms by (simp add: carrier_local_ring_at_def) then have "X \<in> quotient_ring.carrier_quotient_ring (R \<setminus> I) R (+) (\<cdot>) \<zero>" by blast then obtain r s where "r \<in> R" "s \<in> (R \<setminus> I)" "X = local.frac r s" using local.frac_from_carrier by (metis local.frac_def) thus thesis using that by blast qed lemma eq_from_eq_frac: assumes "local.frac r s = local.frac r' s'" and "s \<in> (R \<setminus> I)" and "s' \<in> (R \<setminus> I)" and "r \<in> R" "r' \<in> R" obtains h where "h \<in> (R \<setminus> I)" "h \<cdot> (s' \<cdot> r - s \<cdot> r') = \<zero>" using local.frac_eq_Ex[of r s r' s'] assms by blast end (* pr_ideal *) abbreviation carrier_of_local_ring_at:: "'a set \<Rightarrow> 'a set \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> 'a) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> ('a \<times> 'a) set set" ("_ \<^bsub>_ _ _ _\<^esub>" [1000]1000) where "R \<^bsub>I add mult zero\<^esub> \<equiv> pr_ideal.carrier_local_ring_at R I add mult zero" subsection \<open>Spectrum of a Ring\<close> (* construction 0.29 *) context comm_ring begin interpretation zariski_top_space: topological_space Spec is_zariski_open unfolding is_zariski_open_def using generated_topology_is_topology by blast lemma spectrum_imp_cxt_quotient_ring: "\<pp> \<in> Spec \<Longrightarrow> quotient_ring (R \<setminus> \<pp>) R (+) (\<cdot>) \<zero> \<one>" apply (intro_locales) using pr_ideal.submonoid_pr_ideal spectrum_def submonoid_def by fastforce lemma spectrum_imp_pr: "\<pp> \<in> Spec \<Longrightarrow> pr_ideal R \<pp> (+) (\<cdot>) \<zero> \<one>" unfolding spectrum_def by auto lemma frac_in_carrier_local: assumes "\<pp> \<in> Spec" and "r \<in> R" and "s \<in> R" and "s \<notin> \<pp>" shows "(quotient_ring.frac (R \<setminus> \<pp>) R (+) (\<cdot>) \<zero> r s) \<in> R\<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" proof - interpret qr:quotient_ring "R \<setminus> \<pp>" R "(+)" "(\<cdot>)" \<zero> \<one> using spectrum_imp_cxt_quotient_ring[OF \<open>\<pp> \<in> Spec\<close>] . interpret pi:pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> using spectrum_imp_pr[OF \<open>\<pp> \<in> Spec\<close>] . show ?thesis unfolding pi.carrier_local_ring_at_def using assms(2-) by (auto intro:qr.frac_non_empty) qed definition is_locally_frac:: "('a set \<Rightarrow> ('a \<times> 'a) set) \<Rightarrow> 'a set set \<Rightarrow> bool" where "is_locally_frac s V \<equiv> (\<exists>r f. r \<in> R \<and> f \<in> R \<and> (\<forall>\<qq> \<in> V. f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R \<setminus> \<qq>) R (+) (\<cdot>) \<zero> r f))" lemma is_locally_frac_subset: assumes "is_locally_frac s U" "V \<subseteq> U" shows "is_locally_frac s V" using assms unfolding is_locally_frac_def by (meson subsetD) lemma is_locally_frac_cong: assumes "\<And>x. x\<in>U \<Longrightarrow> f x=g x" shows "is_locally_frac f U = is_locally_frac g U" unfolding is_locally_frac_def using assms by simp definition is_regular:: "('a set \<Rightarrow> ('a \<times> 'a) set) \<Rightarrow> 'a set set \<Rightarrow> bool" where "is_regular s U \<equiv> \<forall>\<pp>. \<pp> \<in> U \<longrightarrow> (\<exists>V. is_zariski_open V \<and> V \<subseteq> U \<and> \<pp> \<in> V \<and> (is_locally_frac s V))" lemma map_on_empty_is_regular: fixes s:: "'a set \<Rightarrow> ('a \<times> 'a) set" shows "is_regular s {}" by (simp add: is_regular_def) lemma cring0_is_regular [simp]: "cring0.is_regular x = (\<lambda>U. U={})" unfolding cring0.is_regular_def cring0_is_zariski_open by blast definition sheaf_spec:: "'a set set \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set) set" ("\<O> _" [90]90) where "\<O> U \<equiv> {s\<in>(\<Pi>\<^sub>E \<pp>\<in>U. (R\<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)). is_regular s U}" lemma cring0_sheaf_spec_empty [simp]: "cring0.sheaf_spec {} = {\<lambda>x. undefined}" by (simp add: cring0.sheaf_spec_def) lemma sec_has_right_codom: assumes "s \<in> \<O> U" and "\<pp> \<in> U" shows "s \<pp> \<in> (R\<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" using assms sheaf_spec_def by auto lemma is_regular_has_right_codom: assumes "U \<subseteq> Spec" "\<pp> \<in> U" "is_regular s U" shows "s \<pp> \<in> R\<setminus>\<pp> \<^sup>\<inverse> R\<^bsub>(+) (\<cdot>) \<zero>\<^esub>" proof - interpret qr:quotient_ring "(R \<setminus> \<pp>)" R "(+)" "(\<cdot>)" \<zero> \<one> using spectrum_imp_cxt_quotient_ring assms by auto show ?thesis using assms by (smt frac_in_carrier_local is_locally_frac_def is_regular_def pr_ideal.carrier_local_ring_at_def spectrum_imp_pr subset_eq) qed lemma sec_is_extensional: assumes "s \<in> \<O> U" shows "s \<in> extensional U" using assms sheaf_spec_def by (simp add: PiE_iff) definition \<O>b::"'a set \<Rightarrow> ('a \<times> 'a) set" where "\<O>b = (\<lambda>\<pp>. undefined)" lemma \<O>_on_emptyset: "\<O> {} = {\<O>b}" unfolding sheaf_spec_def \<O>b_def by (auto simp:Set_Theory.map_def map_on_empty_is_regular) lemma sheaf_spec_of_empty_is_singleton: fixes U:: "'a set set" assumes "U = {}" and "s \<in> extensional U" and "t \<in> extensional U" shows "s = t" using assms by (simp add: Set_Theory.map_def) definition add_sheaf_spec:: "('a set) set \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set) \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set) \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set)" where "add_sheaf_spec U s s' \<equiv> \<lambda>\<pp>\<in>U. quotient_ring.add_rel (R \<setminus> \<pp>) R (+) (\<cdot>) \<zero> (s \<pp>) (s' \<pp>)" lemma is_regular_add_sheaf_spec: assumes "is_regular s U" and "is_regular s' U" and "U \<subseteq> Spec" shows "is_regular (add_sheaf_spec U s s') U" proof - have "add_sheaf_spec U s s' \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" if "\<pp> \<in> U" for \<pp> proof - interpret pi: pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> using \<open>U \<subseteq> Spec\<close>[unfolded spectrum_def] \<open>\<pp> \<in> U\<close> by blast have "s \<pp> \<in> pi.carrier_local_ring_at" "s' \<pp> \<in> pi.carrier_local_ring_at" using \<open>is_regular s U\<close> \<open>is_regular s' U\<close> unfolding is_regular_def is_locally_frac_def using that using assms(3) frac_in_carrier_local by fastforce+ then show ?thesis unfolding add_sheaf_spec_def using that by (simp flip:pi.add_local_ring_at_def) qed moreover have "(\<exists>V\<subseteq>U. is_zariski_open V \<and> \<pp> \<in> V \<and> is_locally_frac (add_sheaf_spec U s s') V)" if "\<pp> \<in> U" for \<pp> proof - obtain V1 r1 f1 where "V1 \<subseteq>U" "is_zariski_open V1" "\<pp> \<in> V1" "r1 \<in> R" "f1 \<in> R" and q_V1:"(\<forall>\<qq>. \<qq> \<in> V1 \<longrightarrow> f1 \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r1 f1)" using \<open>is_regular s U\<close>[unfolded is_regular_def] \<open>\<pp> \<in> U\<close> unfolding is_locally_frac_def by auto obtain V2 r2 f2 where "V2 \<subseteq>U" "is_zariski_open V2" "\<pp> \<in> V2" "r2 \<in> R" "f2 \<in> R" and q_V2:"(\<forall>\<qq>. \<qq> \<in> V2 \<longrightarrow> f2 \<notin> \<qq> \<and> s' \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r2 f2)" using \<open>is_regular s' U\<close>[unfolded is_regular_def] \<open>\<pp> \<in> U\<close> unfolding is_locally_frac_def by auto define V3 where "V3 = V1 \<inter> V2" define r3 where "r3 = r1 \<cdot> f2 + r2 \<cdot> f1 " define f3 where "f3 = f1 \<cdot> f2" have "V3 \<subseteq>U" "\<pp> \<in> V3" "r3 \<in> R" "f3 \<in> R" unfolding V3_def r3_def f3_def using \<open>V1 \<subseteq> U\<close> \<open>\<pp> \<in> V1\<close> \<open>V2 \<subseteq> U\<close> \<open>\<pp> \<in> V2\<close> \<open>f1 \<in> R\<close> \<open>f2 \<in> R\<close> \<open>r1 \<in> R\<close> \<open>r2 \<in> R\<close> by blast+ moreover have "is_zariski_open V3" using \<open>is_zariski_open V1\<close> \<open>is_zariski_open V2\<close> topological_space.open_inter by (simp add: V3_def) moreover have "f3 \<notin> \<qq>" "add_sheaf_spec U s s' \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r3 f3" if "\<qq> \<in> V3" for \<qq> proof - interpret q:quotient_ring "R\<setminus>\<qq>" R "(+)" "(\<cdot>)" \<zero> using \<open>U \<subseteq> Spec\<close> \<open>V3 \<subseteq> U\<close> \<open>\<qq> \<in> V3\<close> quotient_ring_def local.comm_ring_axioms pr_ideal.submonoid_pr_ideal spectrum_def by fastforce have "f1 \<notin> \<qq>" "s \<qq> = q.frac r1 f1" using q_V1 \<open>\<qq> \<in> V3\<close> unfolding V3_def by auto have "f2 \<notin> \<qq>" "s' \<qq> = q.frac r2 f2" using q_V2 \<open>\<qq> \<in> V3\<close> unfolding V3_def by auto have "q.add_rel (q.frac r1 f1) (q.frac r2 f2) = q.frac (r1 \<cdot> f2 + r2 \<cdot> f1) (f1 \<cdot> f2)" apply (rule q.add_rel_frac) subgoal by (simp add: \<open>f1 \<in> R\<close> \<open>f1 \<notin> \<qq>\<close> \<open>r1 \<in> R\<close> \<open>r2 \<in> R\<close>) subgoal using \<open>f2 \<in> R\<close> \<open>f2 \<notin> \<qq>\<close> \<open>r2 \<in> R\<close> by blast done then have "q.add_rel (s \<qq>) (s' \<qq>) = q.frac r3 f3" unfolding r3_def f3_def using \<open>s \<qq> = q.frac r1 f1\<close> \<open>s' \<qq> = q.frac r2 f2\<close> by auto then show "add_sheaf_spec U s s' \<qq> = q.frac r3 f3" unfolding add_sheaf_spec_def using \<open>V3 \<subseteq> U\<close> \<open>\<qq> \<in> V3\<close> by auto show "f3 \<notin> \<qq>" using that unfolding V3_def f3_def using \<open>f1 \<in> R\<close> \<open>f1 \<notin> \<qq>\<close> \<open>f2 \<in> R\<close> \<open>f2 \<notin> \<qq>\<close> q.sub_composition_closed by auto qed ultimately show ?thesis using is_locally_frac_def by metis qed ultimately show ?thesis unfolding is_regular_def is_locally_frac_def by meson qed lemma add_sheaf_spec_in_sheaf_spec: assumes "s \<in> \<O> U" and "t \<in> \<O> U" and "U \<subseteq> Spec" shows "add_sheaf_spec U s t \<in> \<O> U" proof - have "add_sheaf_spec U s t \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" if "\<pp> \<in> U" for \<pp> proof - interpret qr:quotient_ring "(R\<setminus>\<pp>)" R "(+)" "(\<cdot>)" \<zero> \<one> apply (rule spectrum_imp_cxt_quotient_ring) using that \<open>U \<subseteq> Spec\<close> by auto interpret pi:pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> using that \<open>U \<subseteq> Spec\<close> by (auto intro:spectrum_imp_pr) have "qr.valid_frac (s \<pp>)" "qr.valid_frac (t \<pp>)" using sec_has_right_codom[OF _ that] \<open>s \<in> \<O> U\<close> \<open>t \<in> \<O> U\<close> by (auto simp:pi.carrier_local_ring_at_def) then show ?thesis using that unfolding add_sheaf_spec_def pi.carrier_local_ring_at_def by auto qed moreover have "is_regular (add_sheaf_spec U s t) U" using \<open>s \<in> \<O> U\<close> \<open>t \<in> \<O> U\<close> \<open>U \<subseteq> Spec\<close> is_regular_add_sheaf_spec unfolding sheaf_spec_def by auto moreover have "add_sheaf_spec U s t \<in> extensional U" unfolding add_sheaf_spec_def by auto ultimately show ?thesis unfolding sheaf_spec_def by (simp add: PiE_iff) qed definition mult_sheaf_spec:: "('a set) set \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set) \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set) \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set)" where "mult_sheaf_spec U s s' \<equiv> \<lambda>\<pp>\<in>U. quotient_ring.mult_rel (R \<setminus> \<pp>) R (+) (\<cdot>) \<zero> (s \<pp>) (s' \<pp>)" lemma is_regular_mult_sheaf_spec: assumes "is_regular s U" and "is_regular s' U" and "U \<subseteq> Spec" shows "is_regular (mult_sheaf_spec U s s') U" proof - have "mult_sheaf_spec U s s' \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" if "\<pp> \<in> U" for \<pp> proof - interpret pi: pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> using \<open>U \<subseteq> Spec\<close>[unfolded spectrum_def] \<open>\<pp> \<in> U\<close> by blast have "s \<pp> \<in> pi.carrier_local_ring_at" "s' \<pp> \<in> pi.carrier_local_ring_at" using \<open>is_regular s U\<close> \<open>is_regular s' U\<close> unfolding is_regular_def using that using assms(3) frac_in_carrier_local in_mono is_locally_frac_def by fastforce+ then show ?thesis unfolding mult_sheaf_spec_def using that by (simp flip:pi.mult_local_ring_at_def) qed moreover have "(\<exists>V\<subseteq>U. is_zariski_open V \<and> \<pp> \<in> V \<and> is_locally_frac (mult_sheaf_spec U s s') V)" if "\<pp> \<in> U" for \<pp> proof - obtain V1 r1 f1 where "V1 \<subseteq>U" "is_zariski_open V1" "\<pp> \<in> V1" "r1 \<in> R" "f1 \<in> R" and q_V1:"(\<forall>\<qq>. \<qq> \<in> V1 \<longrightarrow> f1 \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r1 f1)" using \<open>is_regular s U\<close>[unfolded is_regular_def] \<open>\<pp> \<in> U\<close> unfolding is_locally_frac_def by auto obtain V2 r2 f2 where "V2 \<subseteq>U" "is_zariski_open V2" "\<pp> \<in> V2" "r2 \<in> R" "f2 \<in> R" and q_V2:"(\<forall>\<qq>. \<qq> \<in> V2 \<longrightarrow> f2 \<notin> \<qq> \<and> s' \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r2 f2)" using \<open>is_regular s' U\<close>[unfolded is_regular_def] \<open>\<pp> \<in> U\<close> unfolding is_locally_frac_def by auto define V3 where "V3 = V1 \<inter> V2" define r3 where "r3 = r1 \<cdot> r2 " define f3 where "f3 = f1 \<cdot> f2" have "V3 \<subseteq>U" "\<pp> \<in> V3" "r3 \<in> R" "f3 \<in> R" unfolding V3_def r3_def f3_def using \<open>V1 \<subseteq> U\<close> \<open>\<pp> \<in> V1\<close> \<open>\<pp> \<in> V2\<close> \<open>f1 \<in> R\<close> \<open>f2 \<in> R\<close> \<open>r1 \<in> R\<close> \<open>r2 \<in> R\<close> by blast+ moreover have "is_zariski_open V3" using topological_space.open_inter by (simp add: V3_def \<open>is_zariski_open V1\<close> \<open>is_zariski_open V2\<close>) moreover have "f3 \<notin> \<qq>" "mult_sheaf_spec U s s' \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r3 f3" if "\<qq> \<in> V3" for \<qq> proof - interpret q:quotient_ring "R\<setminus>\<qq>" R "(+)" "(\<cdot>)" \<zero> using \<open>U \<subseteq> Spec\<close> \<open>V3 \<subseteq> U\<close> \<open>\<qq> \<in> V3\<close> quotient_ring_def local.comm_ring_axioms pr_ideal.submonoid_pr_ideal spectrum_def by fastforce have "f1 \<notin> \<qq>" "s \<qq> = q.frac r1 f1" using q_V1 \<open>\<qq> \<in> V3\<close> unfolding V3_def by auto have "f2 \<notin> \<qq>" "s' \<qq> = q.frac r2 f2" using q_V2 \<open>\<qq> \<in> V3\<close> unfolding V3_def by auto have "q.mult_rel (q.frac r1 f1) (q.frac r2 f2) = q.frac (r1 \<cdot> r2 ) (f1 \<cdot> f2)" apply (rule q.mult_rel_frac) subgoal by (simp add: \<open>f1 \<in> R\<close> \<open>f1 \<notin> \<qq>\<close> \<open>r1 \<in> R\<close> \<open>r2 \<in> R\<close>) subgoal using \<open>f2 \<in> R\<close> \<open>f2 \<notin> \<qq>\<close> \<open>r2 \<in> R\<close> by blast done then have "q.mult_rel (s \<qq>) (s' \<qq>) = q.frac r3 f3" unfolding r3_def f3_def using \<open>s \<qq> = q.frac r1 f1\<close> \<open>s' \<qq> = q.frac r2 f2\<close> by auto then show "mult_sheaf_spec U s s' \<qq> = q.frac r3 f3" unfolding mult_sheaf_spec_def using \<open>V3 \<subseteq> U\<close> \<open>\<qq> \<in> V3\<close> by auto show "f3 \<notin> \<qq>" using that unfolding V3_def f3_def using \<open>f1 \<in> R\<close> \<open>f1 \<notin> \<qq>\<close> \<open>f2 \<in> R\<close> \<open>f2 \<notin> \<qq>\<close> q.sub_composition_closed by auto qed ultimately show ?thesis using is_locally_frac_def by metis qed ultimately show ?thesis unfolding is_regular_def is_locally_frac_def by meson qed lemma mult_sheaf_spec_in_sheaf_spec: assumes "s \<in> \<O> U" and "t \<in> \<O> U" and "U \<subseteq> Spec" shows "mult_sheaf_spec U s t \<in> \<O> U" proof - have "mult_sheaf_spec U s t \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" if "\<pp> \<in> U" for \<pp> proof - interpret qr:quotient_ring "(R\<setminus>\<pp>)" R "(+)" "(\<cdot>)" \<zero> \<one> apply (rule spectrum_imp_cxt_quotient_ring) using that \<open>U \<subseteq> Spec\<close> by auto interpret pi:pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> using that \<open>U \<subseteq> Spec\<close> by (auto intro:spectrum_imp_pr) have "qr.valid_frac (s \<pp>)" "qr.valid_frac (t \<pp>)" using sec_has_right_codom[OF _ that] \<open>s \<in> \<O> U\<close> \<open>t \<in> \<O> U\<close> by (auto simp:pi.carrier_local_ring_at_def) then show ?thesis using that unfolding mult_sheaf_spec_def pi.carrier_local_ring_at_def by auto qed moreover have "is_regular (mult_sheaf_spec U s t) U" using \<open>s \<in> \<O> U\<close> \<open>t \<in> \<O> U\<close> \<open>U \<subseteq> Spec\<close> is_regular_mult_sheaf_spec unfolding sheaf_spec_def by auto moreover have "mult_sheaf_spec U s t \<in> extensional U" unfolding mult_sheaf_spec_def by auto ultimately show ?thesis unfolding sheaf_spec_def by (simp add: PiE_iff) qed definition uminus_sheaf_spec::"('a set) set \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set) \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set)" where "uminus_sheaf_spec U s \<equiv> \<lambda>\<pp>\<in>U. quotient_ring.uminus_rel (R \<setminus> \<pp>) R (+) (\<cdot>) \<zero> (s \<pp>) " lemma is_regular_uminus_sheaf_spec: assumes "is_regular s U" and "U \<subseteq> Spec" shows "is_regular (uminus_sheaf_spec U s) U" proof - have "uminus_sheaf_spec U s \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" if "\<pp> \<in> U" for \<pp> proof - interpret pi: pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> using \<open>U \<subseteq> Spec\<close>[unfolded spectrum_def] \<open>\<pp> \<in> U\<close> by blast interpret qr:quotient_ring "(R\<setminus>\<pp>)" by (simp add: quotient_ring_def local.comm_ring_axioms pi.submonoid_pr_ideal) have "s \<pp> \<in> pi.carrier_local_ring_at" using \<open>is_regular s U\<close> unfolding is_regular_def using that using assms(2) frac_in_carrier_local in_mono is_locally_frac_def by fastforce then show ?thesis unfolding uminus_sheaf_spec_def pi.carrier_local_ring_at_def using that by simp qed moreover have "(\<exists>V\<subseteq>U. is_zariski_open V \<and> \<pp> \<in> V \<and> is_locally_frac (uminus_sheaf_spec U s) V)" if "\<pp> \<in> U" for \<pp> proof - obtain V1 r1 f1 where "V1 \<subseteq>U" "is_zariski_open V1" "\<pp> \<in> V1" "r1 \<in> R" "f1 \<in> R" and q_V1:"(\<forall>\<qq>. \<qq> \<in> V1 \<longrightarrow> f1 \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r1 f1)" using \<open>is_regular s U\<close>[unfolded is_regular_def] \<open>\<pp> \<in> U\<close> unfolding is_locally_frac_def by auto define V3 where "V3 = V1 " define r3 where "r3 = additive.inverse r1" define f3 where "f3 = f1" have "V3 \<subseteq>U" "\<pp> \<in> V3" "r3 \<in> R" "f3 \<in> R" unfolding V3_def r3_def f3_def using \<open>V1 \<subseteq> U\<close> \<open>\<pp> \<in> V1\<close> \<open>f1 \<in> R\<close> \<open>r1 \<in> R\<close> by blast+ moreover have "is_zariski_open V3" using topological_space.open_inter by (simp add: V3_def \<open>is_zariski_open V1\<close>) moreover have "f3 \<notin> \<qq>" "uminus_sheaf_spec U s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r3 f3" if "\<qq> \<in> V3" for \<qq> proof - interpret q:quotient_ring "R\<setminus>\<qq>" R "(+)" "(\<cdot>)" \<zero> using \<open>U \<subseteq> Spec\<close> \<open>V3 \<subseteq> U\<close> \<open>\<qq> \<in> V3\<close> quotient_ring_def local.comm_ring_axioms pr_ideal.submonoid_pr_ideal spectrum_def by fastforce have "f1 \<notin> \<qq>" "s \<qq> = q.frac r1 f1" using q_V1 \<open>\<qq> \<in> V3\<close> unfolding V3_def by auto have "q.uminus_rel (q.frac r1 f1) = q.frac (additive.inverse r1) f1" apply (rule q.uminus_rel_frac) by (simp add: \<open>f1 \<in> R\<close> \<open>f1 \<notin> \<qq>\<close> \<open>r1 \<in> R\<close>) then have "q.uminus_rel (s \<qq>) = q.frac r3 f3" unfolding r3_def f3_def using \<open>s \<qq> = q.frac r1 f1\<close> by auto then show "uminus_sheaf_spec U s \<qq> = q.frac r3 f3" unfolding uminus_sheaf_spec_def using \<open>V3 \<subseteq> U\<close> \<open>\<qq> \<in> V3\<close> by auto show "f3 \<notin> \<qq>" using that unfolding V3_def f3_def using \<open>f1 \<in> R\<close> \<open>f1 \<notin> \<qq>\<close> q.sub_composition_closed by auto qed ultimately show ?thesis using is_locally_frac_def by metis qed ultimately show ?thesis unfolding is_regular_def is_locally_frac_def by meson qed lemma uminus_sheaf_spec_in_sheaf_spec: assumes "s \<in> \<O> U" and "U \<subseteq> Spec" shows "uminus_sheaf_spec U s \<in> \<O> U" proof - have "uminus_sheaf_spec U s \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" if "\<pp> \<in> U" for \<pp> proof - interpret qr:quotient_ring "(R\<setminus>\<pp>)" R "(+)" "(\<cdot>)" \<zero> \<one> apply (rule spectrum_imp_cxt_quotient_ring) using that \<open>U \<subseteq> Spec\<close> by auto interpret pi:pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> using that \<open>U \<subseteq> Spec\<close> by (auto intro:spectrum_imp_pr) have "qr.valid_frac (s \<pp>)" using sec_has_right_codom[OF _ that] \<open>s \<in> \<O> U\<close> by (auto simp:pi.carrier_local_ring_at_def) then show ?thesis using that unfolding uminus_sheaf_spec_def pi.carrier_local_ring_at_def by auto qed moreover have "is_regular (uminus_sheaf_spec U s) U" using \<open>s \<in> \<O> U\<close> \<open>U \<subseteq> Spec\<close> is_regular_uminus_sheaf_spec unfolding sheaf_spec_def by auto moreover have "uminus_sheaf_spec U s \<in> extensional U" unfolding uminus_sheaf_spec_def by auto ultimately show ?thesis unfolding sheaf_spec_def by (simp add: PiE_iff) qed definition zero_sheaf_spec:: "'a set set \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set)" where "zero_sheaf_spec U \<equiv> \<lambda>\<pp>\<in>U. quotient_ring.zero_rel (R \<setminus> \<pp>) R (+) (\<cdot>) \<zero> \<one>" lemma is_regular_zero_sheaf_spec: assumes "is_zariski_open U" shows "is_regular (zero_sheaf_spec U) U" proof - have "zero_sheaf_spec U \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" if "\<pp> \<in> U" for \<pp> unfolding zero_sheaf_spec_def using assms comm_ring.frac_in_carrier_local local.comm_ring_axioms pr_ideal.not_1 quotient_ring.zero_rel_def spectrum_imp_cxt_quotient_ring spectrum_imp_pr subsetD that zariski_top_space.open_imp_subset by fastforce moreover have "(\<exists>V\<subseteq>U. is_zariski_open V \<and> \<pp> \<in> V \<and> is_locally_frac (zero_sheaf_spec U) V)" if "\<pp> \<in> U" for \<pp> proof - define V3 where "V3 = U" define r3 where "r3 = \<zero> " define f3 where "f3 = \<one>" have "V3 \<subseteq>U" "\<pp> \<in> V3" "r3 \<in> R" "f3 \<in> R" unfolding V3_def r3_def f3_def using that by auto moreover have "is_zariski_open V3" using assms by (simp add: V3_def) moreover have "f3 \<notin> \<qq>" "zero_sheaf_spec U \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r3 f3" if "\<qq> \<in> V3" for \<qq> subgoal using V3_def assms f3_def pr_ideal.submonoid_pr_ideal spectrum_def submonoid.sub_unit_closed that zariski_open_is_subset by fastforce subgoal proof - interpret q:quotient_ring "R\<setminus>\<qq>" R using V3_def assms quotient_ring_def local.comm_ring_axioms pr_ideal.submonoid_pr_ideal spectrum_def that zariski_open_is_subset by fastforce show ?thesis unfolding zero_sheaf_spec_def using V3_def f3_def q.zero_rel_def r3_def that by auto qed done ultimately show ?thesis using is_locally_frac_def by metis qed ultimately show ?thesis unfolding is_regular_def is_locally_frac_def by meson qed lemma zero_sheaf_spec_in_sheaf_spec: assumes "is_zariski_open U" shows "zero_sheaf_spec U \<in> \<O> U" proof - have "zero_sheaf_spec U \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>"if "\<pp> \<in> U" for \<pp> proof - interpret qr:quotient_ring "(R\<setminus>\<pp>)" R "(+)" "(\<cdot>)" \<zero> \<one> by (meson assms comm_ring.zariski_open_is_subset local.comm_ring_axioms spectrum_imp_cxt_quotient_ring subsetD that) interpret pi:pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> by (meson assms spectrum_imp_pr subsetD that zariski_open_is_subset) show ?thesis unfolding zero_sheaf_spec_def pi.carrier_local_ring_at_def using that by auto qed moreover have "is_regular (zero_sheaf_spec U) U" using is_regular_zero_sheaf_spec assms by auto moreover have "zero_sheaf_spec U \<in> extensional U" by (simp add: zero_sheaf_spec_def) ultimately show ?thesis unfolding sheaf_spec_def by (simp add: PiE_iff) qed definition one_sheaf_spec:: "'a set set \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set)" where "one_sheaf_spec U \<equiv> \<lambda>\<pp>\<in>U. quotient_ring.one_rel (R \<setminus> \<pp>) R (+) (\<cdot>) \<zero> \<one>" lemma is_regular_one_sheaf_spec: assumes "is_zariski_open U" shows "is_regular (one_sheaf_spec U) U" proof - have "one_sheaf_spec U \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" if "\<pp> \<in> U" for \<pp> unfolding one_sheaf_spec_def by (smt assms closed_subsets_zero comm_ring.closed_subsets_def quotient_ring.carrier_quotient_ring_iff quotient_ring.valid_frac_one quotient_ring_def local.comm_ring_axioms mem_Collect_eq pr_ideal.carrier_local_ring_at_def pr_ideal.submonoid_pr_ideal restrict_apply subsetD that zariski_open_is_subset) moreover have "(\<exists>V\<subseteq>U. is_zariski_open V \<and> \<pp> \<in> V \<and> is_locally_frac (one_sheaf_spec U) V)" if "\<pp> \<in> U" for \<pp> proof - define V3 where "V3 = U" define r3 where "r3 = \<one>" define f3 where "f3 = \<one>" have "V3 \<subseteq>U" "\<pp> \<in> V3" "r3 \<in> R" "f3 \<in> R" unfolding V3_def r3_def f3_def using that by auto moreover have "is_zariski_open V3" using assms by (simp add: V3_def) moreover have "f3 \<notin> \<qq>" "one_sheaf_spec U \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r3 f3" if "\<qq> \<in> V3" for \<qq> subgoal using V3_def assms f3_def pr_ideal.submonoid_pr_ideal spectrum_def submonoid.sub_unit_closed that zariski_open_is_subset by fastforce subgoal proof - interpret q:quotient_ring "R\<setminus>\<qq>" R using V3_def assms quotient_ring_def local.comm_ring_axioms pr_ideal.submonoid_pr_ideal spectrum_def that zariski_open_is_subset by fastforce show ?thesis unfolding one_sheaf_spec_def using V3_def f3_def q.one_rel_def r3_def that by auto qed done ultimately show ?thesis using is_locally_frac_def by metis qed ultimately show ?thesis unfolding is_regular_def is_locally_frac_def by meson qed lemma one_sheaf_spec_in_sheaf_spec: assumes "is_zariski_open U" shows "one_sheaf_spec U \<in> \<O> U" proof - have "one_sheaf_spec U \<pp> \<in> R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>"if "\<pp> \<in> U" for \<pp> proof - interpret qr:quotient_ring "(R\<setminus>\<pp>)" R "(+)" "(\<cdot>)" \<zero> \<one> by (meson assms comm_ring.zariski_open_is_subset local.comm_ring_axioms spectrum_imp_cxt_quotient_ring subsetD that) interpret pi:pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> by (meson assms spectrum_imp_pr subsetD that zariski_open_is_subset) show ?thesis unfolding one_sheaf_spec_def pi.carrier_local_ring_at_def using that by auto qed moreover have "is_regular (one_sheaf_spec U) U" using is_regular_one_sheaf_spec assms by auto moreover have "one_sheaf_spec U \<in> extensional U" by (simp add: one_sheaf_spec_def) ultimately show ?thesis unfolding sheaf_spec_def by (simp add: PiE_iff) qed lemma zero_sheaf_spec_extensional[simp]: "zero_sheaf_spec U \<in> extensional U" unfolding zero_sheaf_spec_def by simp lemma one_sheaf_spec_extensional[simp]: "one_sheaf_spec U \<in> extensional U" unfolding one_sheaf_spec_def by simp lemma add_sheaf_spec_extensional[simp]: "add_sheaf_spec U a b \<in> extensional U" unfolding add_sheaf_spec_def by simp lemma mult_sheaf_spec_extensional[simp]: "mult_sheaf_spec U a b \<in> extensional U" unfolding mult_sheaf_spec_def by simp lemma sheaf_spec_extensional[simp]: "a \<in> \<O> U \<Longrightarrow> a \<in> extensional U" unfolding sheaf_spec_def by (simp add: PiE_iff Set_Theory.map_def) lemma sheaf_spec_on_open_is_comm_ring: assumes "is_zariski_open U" shows "comm_ring (\<O> U) (add_sheaf_spec U) (mult_sheaf_spec U) (zero_sheaf_spec U) (one_sheaf_spec U)" proof unfold_locales show add_\<O>:"add_sheaf_spec U a b \<in> \<O> U" and "mult_sheaf_spec U a b \<in> \<O> U" if "a \<in> \<O> U" "b \<in> \<O> U" for a b subgoal by (simp add: add_sheaf_spec_in_sheaf_spec assms that(1,2) zariski_open_is_subset) subgoal by (simp add: assms mult_sheaf_spec_in_sheaf_spec that(1,2) zariski_open_is_subset) done show "zero_sheaf_spec U \<in> \<O> U" "one_sheaf_spec U \<in> \<O> U" subgoal by (simp add: assms zero_sheaf_spec_in_sheaf_spec) subgoal by (simp add: assms one_sheaf_spec_in_sheaf_spec) done have imp_qr:"quotient_ring (R\<setminus>\<pp>) R (+) (\<cdot>) \<zero> \<one>" if "\<pp> \<in> U" for \<pp> using that by (meson assms comm_ring.spectrum_imp_cxt_quotient_ring in_mono local.comm_ring_axioms zariski_open_is_subset) have qr_valid_frac:"quotient_ring.valid_frac (R\<setminus>\<pp>) R (+) (\<cdot>) \<zero> (s \<pp>)" if "s \<in> \<O> U" "\<pp> \<in> U" for s \<pp> using assms comm_ring.zariski_open_is_subset quotient_ring.carrier_quotient_ring_iff imp_qr local.comm_ring_axioms pr_ideal.carrier_local_ring_at_def sec_has_right_codom spectrum_imp_pr that(1) that(2) by fastforce show add_zero:"add_sheaf_spec U (zero_sheaf_spec U) a = a" if "a \<in> \<O> U" for a proof - have "add_sheaf_spec U (zero_sheaf_spec U) a \<pp> = a \<pp>" if "\<pp> \<in> U" for \<pp> proof - interpret cq:quotient_ring "R\<setminus>\<pp>" R "(+)" "(\<cdot>)" \<zero> \<one> using imp_qr that by auto show ?thesis unfolding add_sheaf_spec_def zero_sheaf_spec_def using that by (simp add: \<open>a \<in> \<O> U\<close> qr_valid_frac) qed then show "add_sheaf_spec U (zero_sheaf_spec U) a = a" using that by(auto intro: extensionalityI[where A=U]) qed show add_assoc:"add_sheaf_spec U (add_sheaf_spec U a b) c = add_sheaf_spec U a (add_sheaf_spec U b c)" if "a \<in> \<O> U" and "b \<in> \<O> U" and "c \<in> \<O> U" for a b c proof (rule extensionalityI) fix \<pp> assume "\<pp> \<in> U" interpret cq:quotient_ring "R\<setminus>\<pp>" R "(+)" "(\<cdot>)" \<zero> \<one> using \<open>\<pp> \<in> U\<close> imp_qr by auto show "add_sheaf_spec U (add_sheaf_spec U a b) c \<pp> = add_sheaf_spec U a (add_sheaf_spec U b c) \<pp>" unfolding add_sheaf_spec_def using \<open>\<pp> \<in> U\<close> by (simp add: cq.additive.associative qr_valid_frac that(1) that(2) that(3)) qed (auto simp add:add_sheaf_spec_def) show add_comm:"add_sheaf_spec U x y = add_sheaf_spec U y x" if "x \<in> \<O> U" and "y \<in> \<O> U" for x y proof (rule extensionalityI) fix \<pp> assume "\<pp> \<in> U" interpret cq:quotient_ring "R\<setminus>\<pp>" R "(+)" "(\<cdot>)" \<zero> \<one> using \<open>\<pp> \<in> U\<close> imp_qr by auto show " add_sheaf_spec U x y \<pp> = add_sheaf_spec U y x \<pp>" unfolding add_sheaf_spec_def using \<open>\<pp> \<in> U\<close> by (simp add: cq.additive.commutative qr_valid_frac that(1) that(2)) qed auto show mult_comm:"mult_sheaf_spec U x y = mult_sheaf_spec U y x" if "x \<in> \<O> U" and "y \<in> \<O> U" for x y proof (rule extensionalityI) fix \<pp> assume "\<pp> \<in> U" interpret cq:quotient_ring "R\<setminus>\<pp>" R "(+)" "(\<cdot>)" \<zero> \<one> using \<open>\<pp> \<in> U\<close> imp_qr by auto show "mult_sheaf_spec U x y \<pp> = mult_sheaf_spec U y x \<pp>" unfolding mult_sheaf_spec_def using \<open>\<pp> \<in> U\<close> by (simp add: cq.comm_mult qr_valid_frac that(1) that(2)) qed auto show add_zero:"add_sheaf_spec U a (zero_sheaf_spec U) = a" if "a \<in> \<O> U" for a using add_zero add_comm that by (simp add: \<open>zero_sheaf_spec U \<in> \<O> U\<close>) show "mult_sheaf_spec U (mult_sheaf_spec U a b) c = mult_sheaf_spec U a (mult_sheaf_spec U b c)" if "a \<in> \<O> U" and "b \<in> \<O> U" and "c \<in> \<O> U" for a b c proof (rule extensionalityI) fix \<pp> assume "\<pp> \<in> U" interpret cq:quotient_ring "R\<setminus>\<pp>" R "(+)" "(\<cdot>)" \<zero> \<one> using \<open>\<pp> \<in> U\<close> imp_qr by auto show "mult_sheaf_spec U (mult_sheaf_spec U a b) c \<pp> = mult_sheaf_spec U a (mult_sheaf_spec U b c) \<pp>" unfolding mult_sheaf_spec_def using \<open>\<pp> \<in> U\<close> by (simp add: cq.multiplicative.associative qr_valid_frac that(1) that(2) that(3)) qed (auto simp add:add_sheaf_spec_def) show "mult_sheaf_spec U (one_sheaf_spec U) a = a" if "a \<in> \<O> U" for a proof (rule extensionalityI) fix \<pp> assume "\<pp> \<in> U" interpret cq:quotient_ring "R\<setminus>\<pp>" R "(+)" "(\<cdot>)" \<zero> \<one> using \<open>\<pp> \<in> U\<close> imp_qr by auto show "mult_sheaf_spec U (one_sheaf_spec U) a \<pp> = a \<pp>" unfolding mult_sheaf_spec_def using \<open>\<pp> \<in> U\<close> by (simp add: one_sheaf_spec_def qr_valid_frac that) qed (auto simp add: \<open>a \<in> \<O> U\<close>) then show "mult_sheaf_spec U a (one_sheaf_spec U) = a" if "a \<in> \<O> U" for a by (simp add: \<open>one_sheaf_spec U \<in> \<O> U\<close> mult_comm that) show "mult_sheaf_spec U a (add_sheaf_spec U b c) = add_sheaf_spec U (mult_sheaf_spec U a b) (mult_sheaf_spec U a c)" if "a \<in> \<O> U" and "b \<in> \<O> U" and "c \<in> \<O> U" for a b c proof (rule extensionalityI) fix \<pp> assume "\<pp> \<in> U" interpret cq:quotient_ring "R\<setminus>\<pp>" R "(+)" "(\<cdot>)" \<zero> \<one> using \<open>\<pp> \<in> U\<close> imp_qr by auto show "mult_sheaf_spec U a (add_sheaf_spec U b c) \<pp> = add_sheaf_spec U (mult_sheaf_spec U a b) (mult_sheaf_spec U a c) \<pp>" unfolding mult_sheaf_spec_def add_sheaf_spec_def by (simp add: cq.distributive(1) qr_valid_frac that(1) that(2) that(3)) qed auto then show "mult_sheaf_spec U (add_sheaf_spec U b c) a = add_sheaf_spec U (mult_sheaf_spec U b a) (mult_sheaf_spec U c a)" if "a \<in> \<O> U" and "b \<in> \<O> U" and "c \<in> \<O> U" for a b c by (simp add: add_\<O> mult_comm that(1) that(2) that(3)) show "monoid.invertible (\<O> U) (add_sheaf_spec U) (zero_sheaf_spec U) u" if "u \<in> \<O> U" for u proof (rule monoid.invertibleI) show "Group_Theory.monoid (\<O> U) (add_sheaf_spec U) (zero_sheaf_spec U)" apply unfold_locales using add_\<O> \<open>zero_sheaf_spec U \<in> \<O> U\<close> add_assoc \<open>zero_sheaf_spec U \<in> \<O> U\<close> add_comm add_zero add_zero by simp_all show "add_sheaf_spec U u (uminus_sheaf_spec U u) = zero_sheaf_spec U" proof (rule extensionalityI) fix \<pp> assume "\<pp> \<in> U" interpret cq:quotient_ring "R\<setminus>\<pp>" R "(+)" "(\<cdot>)" \<zero> \<one> using \<open>\<pp> \<in> U\<close> imp_qr by auto have "cq.add_rel (u \<pp>) (cq.uminus_rel (u \<pp>)) = cq.zero_rel" by (simp add: \<open>\<pp> \<in> U\<close> cq.add_minus_zero_rel qr_valid_frac that) then show "add_sheaf_spec U u (uminus_sheaf_spec U u) \<pp> = zero_sheaf_spec U \<pp>" unfolding add_sheaf_spec_def uminus_sheaf_spec_def zero_sheaf_spec_def using \<open>\<pp> \<in> U\<close> by simp qed auto then show "add_sheaf_spec U (uminus_sheaf_spec U u) u = zero_sheaf_spec U" by (simp add: add_comm assms comm_ring.zariski_open_is_subset local.comm_ring_axioms that uminus_sheaf_spec_in_sheaf_spec) show "u \<in> \<O> U" using that . show "uminus_sheaf_spec U u \<in> \<O> U" by (simp add: assms comm_ring.zariski_open_is_subset local.comm_ring_axioms that uminus_sheaf_spec_in_sheaf_spec) qed qed definition sheaf_spec_morphisms:: "'a set set \<Rightarrow> 'a set set \<Rightarrow> (('a set \<Rightarrow> ('a \<times> 'a) set) \<Rightarrow> ('a set \<Rightarrow> ('a \<times> 'a) set))" where "sheaf_spec_morphisms U V \<equiv> \<lambda>s\<in>(\<O> U). restrict s V" lemma sheaf_morphisms_sheaf_spec: assumes "s \<in> \<O> U" shows "sheaf_spec_morphisms U U s = s" using assms sheaf_spec_def restrict_on_source sheaf_spec_morphisms_def by auto lemma sheaf_spec_morphisms_are_maps: assumes (*this assumption seems redundant: "is_zariski_open U" and*) "is_zariski_open V" and "V \<subseteq> U" shows "Set_Theory.map (sheaf_spec_morphisms U V) (\<O> U) (\<O> V)" proof - have "sheaf_spec_morphisms U V \<in> extensional (\<O> U)" unfolding sheaf_spec_morphisms_def by auto moreover have "sheaf_spec_morphisms U V \<in> (\<O> U) \<rightarrow> (\<O> V)" unfolding sheaf_spec_morphisms_def proof fix s assume "s \<in> \<O> U" then have "s \<in> (\<Pi>\<^sub>E \<pp>\<in>U. R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" and p:"\<forall>\<pp>. \<pp> \<in> U \<longrightarrow> (\<exists>V. is_zariski_open V \<and> V \<subseteq> U \<and> \<pp> \<in> V \<and> is_locally_frac s V)" unfolding sheaf_spec_def is_regular_def by auto have "restrict s V \<in> (\<Pi>\<^sub>E \<pp>\<in>V. R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" using \<open>s \<in> (\<Pi>\<^sub>E \<pp>\<in>U. R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)\<close> using \<open>V \<subseteq> U\<close> by auto moreover have "(\<exists>Va. is_zariski_open Va \<and> Va \<subseteq> V \<and> \<pp> \<in> Va \<and> is_locally_frac (restrict s V) Va)" if "\<pp> \<in> V" for \<pp> proof - obtain U1 where "is_zariski_open U1" "U1 \<subseteq> U" "\<pp> \<in> U1" "is_locally_frac s U1" using p[rule_format, of \<pp>] that \<open>V \<subseteq> U\<close> \<open>\<pp> \<in> V\<close> by auto define V1 where "V1 = U1 \<inter> V" have "is_zariski_open V1" using \<open>is_zariski_open V\<close> \<open>is_zariski_open U1\<close> by (simp add: V1_def) moreover have "is_locally_frac s V1" using is_locally_frac_subset[OF \<open>is_locally_frac s U1\<close>] unfolding V1_def by simp then have "is_locally_frac (restrict s V) V1" unfolding restrict_def V1_def using is_locally_frac_cong by (smt in_mono inf_le2) moreover have "V1 \<subseteq> V" "\<pp> \<in> V1" unfolding V1_def using \<open>V \<subseteq> U\<close> \<open>\<pp> \<in> U1\<close> that by auto ultimately show ?thesis by auto qed ultimately show "restrict s V \<in> \<O> V" unfolding sheaf_spec_def is_regular_def by auto qed ultimately show ?thesis by (simp add: extensional_funcset_def map.intro) qed lemma sheaf_spec_morphisms_are_ring_morphisms: assumes U: "is_zariski_open U" and V: "is_zariski_open V" and "V \<subseteq> U" shows "ring_homomorphism (sheaf_spec_morphisms U V) (\<O> U) (add_sheaf_spec U) (mult_sheaf_spec U) (zero_sheaf_spec U) (one_sheaf_spec U) (\<O> V) (add_sheaf_spec V) (mult_sheaf_spec V) (zero_sheaf_spec V) (one_sheaf_spec V)" proof intro_locales show "Set_Theory.map (sheaf_spec_morphisms U V) (\<O> U) (\<O> V)" by (simp add: assms sheaf_spec_morphisms_are_maps) show "Group_Theory.monoid (\<O> U) (add_sheaf_spec U) (zero_sheaf_spec U)" using sheaf_spec_on_open_is_comm_ring [OF U] by (auto simp: comm_ring_def ring_def abelian_group_def commutative_monoid_def) show "Group_Theory.group_axioms (\<O> U) (add_sheaf_spec U) (zero_sheaf_spec U)" using sheaf_spec_on_open_is_comm_ring [OF U] by (auto simp: comm_ring_def ring_def abelian_group_def commutative_monoid_def group_def) show "commutative_monoid_axioms (\<O> U) (add_sheaf_spec U)" using sheaf_spec_on_open_is_comm_ring [OF U] by (auto simp: comm_ring_def ring_def abelian_group_def commutative_monoid_def group_def) show "Group_Theory.monoid (\<O> U) (mult_sheaf_spec U) (one_sheaf_spec U)" by (meson U comm_ring_def ring_def sheaf_spec_on_open_is_comm_ring) show "ring_axioms (\<O> U) (add_sheaf_spec U) (mult_sheaf_spec U)" by (meson U comm_ring.axioms(1) ring_def sheaf_spec_on_open_is_comm_ring) show "Group_Theory.monoid (\<O> V) (add_sheaf_spec V) (zero_sheaf_spec V)" using sheaf_spec_on_open_is_comm_ring [OF V] by (auto simp: comm_ring_def ring_def abelian_group_def commutative_monoid_def) show "Group_Theory.group_axioms (\<O> V) (add_sheaf_spec V) (zero_sheaf_spec V)" using sheaf_spec_on_open_is_comm_ring [OF V] by (auto simp: comm_ring_def ring_def abelian_group_def commutative_monoid_def group_def) show "commutative_monoid_axioms (\<O> V) (add_sheaf_spec V)" using sheaf_spec_on_open_is_comm_ring [OF V] by (auto simp: comm_ring_def ring_def abelian_group_def commutative_monoid_def group_def) show "Group_Theory.monoid (\<O> V) (mult_sheaf_spec V) (one_sheaf_spec V)" by (meson V comm_ring.axioms(1) ring_def sheaf_spec_on_open_is_comm_ring) show "ring_axioms (\<O> V) (add_sheaf_spec V) (mult_sheaf_spec V)" by (meson V comm_ring_def ring_def sheaf_spec_on_open_is_comm_ring) show "monoid_homomorphism_axioms (sheaf_spec_morphisms U V) (\<O> U) (add_sheaf_spec U) (zero_sheaf_spec U) (add_sheaf_spec V) (zero_sheaf_spec V)" proof fix x y assume xy: "x \<in> \<O> U" "y \<in> \<O> U" have "sheaf_spec_morphisms U V (add_sheaf_spec U x y) = restrict (add_sheaf_spec U x y) V" by (simp add: U add_sheaf_spec_in_sheaf_spec comm_ring.zariski_open_is_subset local.comm_ring_axioms sheaf_spec_morphisms_def xy) also have "... = add_sheaf_spec V (restrict x V) (restrict y V)" using add_sheaf_spec_def \<open>V \<subseteq> U\<close> by force also have "... = add_sheaf_spec V (sheaf_spec_morphisms U V x) (sheaf_spec_morphisms U V y)" by (simp add: sheaf_spec_morphisms_def xy) finally show "sheaf_spec_morphisms U V (add_sheaf_spec U x y) = add_sheaf_spec V (sheaf_spec_morphisms U V x) (sheaf_spec_morphisms U V y)" . next have "sheaf_spec_morphisms U V (zero_sheaf_spec U) = restrict (zero_sheaf_spec U) V" by (simp add: U comm_ring.sheaf_spec_morphisms_def local.comm_ring_axioms zero_sheaf_spec_in_sheaf_spec) also have "... = zero_sheaf_spec V" by (metis FuncSet.restrict_restrict assms(3) inf.absorb_iff2 zero_sheaf_spec_def) finally show "sheaf_spec_morphisms U V (zero_sheaf_spec U) = zero_sheaf_spec V" . qed show "monoid_homomorphism_axioms (sheaf_spec_morphisms U V) (\<O> U) (mult_sheaf_spec U) (one_sheaf_spec U) (mult_sheaf_spec V) (one_sheaf_spec V)" proof fix x y assume xy: "x \<in> \<O> U" "y \<in> \<O> U" have "sheaf_spec_morphisms U V (mult_sheaf_spec U x y) = restrict (mult_sheaf_spec U x y) V" by (simp add: U mult_sheaf_spec_in_sheaf_spec comm_ring.zariski_open_is_subset local.comm_ring_axioms sheaf_spec_morphisms_def xy) also have "... = mult_sheaf_spec V (restrict x V) (restrict y V)" using mult_sheaf_spec_def \<open>V \<subseteq> U\<close> by force also have "... = mult_sheaf_spec V (sheaf_spec_morphisms U V x) (sheaf_spec_morphisms U V y)" by (simp add: sheaf_spec_morphisms_def xy) finally show "sheaf_spec_morphisms U V (mult_sheaf_spec U x y) = mult_sheaf_spec V (sheaf_spec_morphisms U V x) (sheaf_spec_morphisms U V y)" . next have "sheaf_spec_morphisms U V (one_sheaf_spec U) = restrict (one_sheaf_spec U) V" by (simp add: U comm_ring.sheaf_spec_morphisms_def local.comm_ring_axioms one_sheaf_spec_in_sheaf_spec) also have "... = one_sheaf_spec V" by (metis FuncSet.restrict_restrict assms(3) inf.absorb_iff2 one_sheaf_spec_def) finally show "sheaf_spec_morphisms U V (one_sheaf_spec U) = one_sheaf_spec V" . qed qed lemma sheaf_spec_is_presheaf: shows "presheaf_of_rings Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec" proof intro_locales have "sheaf_spec {} = {\<O>b}" proof show "{\<O>b} \<subseteq> \<O> {}" using undefined_is_map_on_empty map_on_empty_is_regular sheaf_spec_def \<O>_on_emptyset by auto thus "\<O> {} \<subseteq> {\<O>b}" using sheaf_spec_def sheaf_spec_of_empty_is_singleton by auto qed moreover have "\<And>U. is_zariski_open U \<Longrightarrow> (\<And>s. s \<in> (\<O> U) \<Longrightarrow> sheaf_spec_morphisms U U s = s)" using sheaf_spec_morphisms_def sheaf_morphisms_sheaf_spec by simp moreover have "sheaf_spec_morphisms U W s = (sheaf_spec_morphisms V W \<circ> sheaf_spec_morphisms U V) s" if "is_zariski_open U" "is_zariski_open V" "is_zariski_open W" "V \<subseteq> U" "W \<subseteq> V" and "s \<in> \<O> U" for U V W s proof - have "restrict s V \<in> \<O> V" using that by (smt map.map_closed restrict_apply sheaf_spec_morphisms_are_maps sheaf_spec_morphisms_def) with that show ?thesis by (simp add: sheaf_spec_morphisms_def inf_absorb2) qed ultimately show "presheaf_of_rings_axioms is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec" unfolding presheaf_of_rings_def presheaf_of_rings_axioms_def using sheaf_spec_morphisms_are_ring_morphisms by blast qed (* ex. 0.30 *) lemma sheaf_spec_is_sheaf: shows "sheaf_of_rings Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec" proof (intro sheaf_of_rings.intro sheaf_of_rings_axioms.intro) show "presheaf_of_rings Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec" using sheaf_spec_is_presheaf by simp next fix U I V s assume H: "open_cover_of_open_subset Spec is_zariski_open U I V" "\<And>i. i \<in> I \<Longrightarrow> V i \<subseteq> U" "s \<in> \<O> U" "\<And>i. i \<in> I \<Longrightarrow> sheaf_spec_morphisms U (V i) s = zero_sheaf_spec (V i)" then have "s \<pp> = zero_sheaf_spec U \<pp>" if "\<pp> \<in> U" for \<pp> proof - from that obtain i where F: "i \<in> I" "\<pp> \<in> (V i)" "is_zariski_open (V i)" using H(1) unfolding open_cover_of_subset_def open_cover_of_open_subset_def by (metis cover_of_subset.cover_of_select_index cover_of_subset.select_index_belongs open_cover_of_subset_axioms_def) then have "sheaf_spec_morphisms U (V i) s \<pp> = quotient_ring.zero_rel (R \<setminus> \<pp>) R (+) (\<cdot>) \<zero> \<one>" using H(2,4) F by (simp add: zero_sheaf_spec_def) thus "s \<pp> = zero_sheaf_spec U \<pp>" using sheaf_spec_morphisms_def zero_sheaf_spec_def F(2) by (simp add: H(3) \<open>\<pp> \<in> U\<close>) qed moreover have "s \<in> extensional U" " zero_sheaf_spec U \<in> extensional U" by (simp_all add: H(3)) ultimately show "s = zero_sheaf_spec U" using extensionalityI by blast next fix U I V s assume H: "open_cover_of_open_subset Spec is_zariski_open U I V" "\<forall>i. i \<in> I \<longrightarrow> V i \<subseteq> U \<and> s i \<in> \<O> (V i)" "\<And>i j. i \<in> I \<Longrightarrow> j \<in> I \<Longrightarrow> sheaf_spec_morphisms (V i) (V i \<inter> V j) (s i) = sheaf_spec_morphisms (V j) (V i \<inter> V j) (s j)" define t where D: "t \<equiv> \<lambda>\<pp>\<in>U. s (cover_of_subset.select_index I V \<pp>) \<pp>" then have F1: "s i \<pp> = s j \<pp>" if "i \<in> I" "j \<in> I" "\<pp> \<in> V i" "\<pp> \<in> V j" for \<pp> i j proof - have "s i \<pp> = sheaf_spec_morphisms (V i) (V i \<inter> V j) (s i) \<pp>" using that sheaf_spec_morphisms_def by (simp add: H(2)) moreover have "\<dots> = sheaf_spec_morphisms (V j) (V i \<inter> V j) (s j) \<pp>" using H(3) that by fastforce moreover have "\<dots> = s j \<pp>" using sheaf_spec_morphisms_def that by (simp add: H(2)) ultimately show "s i \<pp> = s j \<pp>" by blast qed have "t \<in> \<O> U" proof- have "t \<pp> \<in> (R\<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" if "\<pp>\<in>U" for \<pp> using D H(1) H(2) cover_of_subset.cover_of_select_index cover_of_subset.select_index_belongs open_cover_of_open_subset.axioms(1) open_cover_of_subset_def sec_has_right_codom that by fastforce moreover have "t \<in> extensional U" using D by blast moreover have "is_regular t U" unfolding is_regular_def proof (intro strip conjI) fix \<pp> assume "\<pp> \<in> U" show "\<exists>V. is_zariski_open V \<and> V \<subseteq> U \<and> \<pp> \<in> V \<and> is_locally_frac t V" proof - have cov_in_I: "cover_of_subset.select_index I V \<pp> \<in> I" by (meson H(1) \<open>\<pp> \<in> U\<close> cover_of_subset.select_index_belongs open_cover_of_open_subset_def open_cover_of_subset_def) have V: "V (cover_of_subset.select_index I V \<pp>) \<subseteq> U" using H(2) by (meson H(1) \<open>\<pp> \<in> U\<close> cover_of_subset.select_index_belongs open_cover_of_open_subset_def open_cover_of_subset_def) have V2: "\<exists>V'. is_zariski_open V' \<and> V'\<subseteq> V (cover_of_subset.select_index I V \<pp>) \<and> \<pp> \<in> V' \<and> is_locally_frac (s (cover_of_subset.select_index I V \<pp>)) V'" using H(1,2) unfolding sheaf_spec_def open_cover_of_open_subset_def open_cover_of_subset_def is_regular_def using \<open>\<pp> \<in> U\<close> cov_in_I cover_of_subset.cover_of_select_index by fastforce have "\<And>V' \<qq>. is_zariski_open V' \<and> V' \<subseteq> V (cover_of_subset.select_index I V \<pp>) \<Longrightarrow> \<qq> \<in> V' \<Longrightarrow> t \<qq> = s (cover_of_subset.select_index I V \<pp>) \<qq>" by (smt D F1 H(1) V \<open>\<pp> \<in> U\<close> cover_of_subset.cover_of_select_index cover_of_subset.select_index_belongs open_cover_of_open_subset_def open_cover_of_subset_def restrict_apply subsetD) with V V2 show ?thesis unfolding is_locally_frac_def by (smt subset_trans) qed qed ultimately show ?thesis unfolding sheaf_spec_def by (simp add:PiE_iff) qed have "sheaf_spec_morphisms U (V i) t = s i" if "i \<in> I" for i proof fix \<pp> have "sheaf_spec_morphisms U (V i) t \<pp> = s i \<pp>" if "\<pp> \<in> U" proof- from that H(1) obtain j where "j \<in> I \<and> \<pp> \<in> V j \<and> t \<pp> = s j \<pp>" unfolding D open_cover_of_subset_def open_cover_of_open_subset_def by (meson cover_of_subset.cover_of_select_index cover_of_subset.select_index_belongs restrict_apply') thus "sheaf_spec_morphisms U (V i) t \<pp> = s i \<pp>" using \<open>t \<in> \<O> U\<close> \<open>i \<in> I\<close> H(2) that unfolding sheaf_spec_morphisms_def apply (simp add: D split: if_split_asm) by (metis (mono_tags, opaque_lifting) F1 extensional_arb [OF sec_is_extensional]) qed thus "sheaf_spec_morphisms U (V i) t \<pp> = s i \<pp>" using sheaf_spec_morphisms_def D F1 by (smt H(2) \<open>i \<in> I\<close> \<open>t \<in> \<O> U\<close> comm_ring.sheaf_morphisms_sheaf_spec local.comm_ring_axioms restrict_apply subsetD) qed thus "\<exists>t. t \<in> (\<O> U) \<and> (\<forall>i. i \<in> I \<longrightarrow> sheaf_spec_morphisms U (V i) t = s i)" using \<open>t \<in> \<O> U\<close> by blast qed lemma shrinking: assumes "is_zariski_open U" and "\<pp> \<in> U" and "s \<in> \<O> U" and "t \<in> \<O> U" obtains V a f b g where "is_zariski_open V" "V \<subseteq> U" "\<pp> \<in> V" "a \<in> R" "f \<in> R" "b \<in> R" "g \<in> R" "f \<notin> \<pp>" "g \<notin> \<pp>" "\<And>\<qq>. \<qq> \<in> V \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f" "\<And>\<qq>. \<qq> \<in> V \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g" proof- obtain Vs a f where "is_zariski_open Vs" "Vs \<subseteq> U" "\<pp> \<in> Vs" "a \<in> R" "f \<in> R" "\<And>\<qq>. \<qq> \<in> Vs \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f" using assms(2,3) sheaf_spec_def is_regular_def is_locally_frac_def by auto obtain Vt b g where "is_zariski_open Vt" "Vt \<subseteq> U" "\<pp> \<in> Vt" "b \<in> R" "g \<in> R" "\<And>\<qq>. \<qq> \<in> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g" using assms(2,4) sheaf_spec_def is_regular_def is_locally_frac_def by auto then have "is_zariski_open (Vs \<inter> Vt)" "Vs \<inter> Vt \<subseteq> U" "\<pp> \<in> Vs \<inter> Vt" "\<And>\<qq>. \<qq> \<in> (Vs \<inter> Vt) \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f" "\<And>\<qq>. \<qq> \<in> (Vs \<inter> Vt) \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g" using topological_space.open_inter apply (simp add: \<open>is_zariski_open Vs\<close>) using \<open>Vs \<subseteq> U\<close> apply auto[1] apply (simp add: \<open>\<pp> \<in> Vs\<close> \<open>\<pp> \<in> Vt\<close>) apply (simp add: \<open>\<And>\<qq>. \<qq> \<in> Vs \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f\<close>) by (simp add: \<open>\<And>\<qq>. \<qq> \<in> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g\<close>) thus ?thesis using \<open>a \<in> R\<close> \<open>b \<in> R\<close> \<open>f \<in> R\<close> \<open>g \<in> R\<close> that by presburger qed end (* comm_ring *) section \<open>Schemes\<close> subsection \<open>Ringed Spaces\<close> (* definition 0.32 *) locale ringed_space = sheaf_of_rings context comm_ring begin lemma spec_is_ringed_space: shows "ringed_space Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec" proof (intro ringed_space.intro) show "sheaf_of_rings Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec" using sheaf_spec_is_sheaf by simp qed end (* comm_ring *) (* definition 0.33 *) locale morphism_ringed_spaces = im_sheaf X is_open\<^sub>X \<O>\<^sub>X \<rho>\<^sub>X b add_str\<^sub>X mult_str\<^sub>X zero_str\<^sub>X one_str\<^sub>X Y is_open\<^sub>Y f + codom: ringed_space Y is_open\<^sub>Y \<O>\<^sub>Y \<rho>\<^sub>Y d add_str\<^sub>Y mult_str\<^sub>Y zero_str\<^sub>Y one_str\<^sub>Y for X and is_open\<^sub>X and \<O>\<^sub>X and \<rho>\<^sub>X and b and add_str\<^sub>X and mult_str\<^sub>X and zero_str\<^sub>X and one_str\<^sub>X and Y and is_open\<^sub>Y and \<O>\<^sub>Y and \<rho>\<^sub>Y and d and add_str\<^sub>Y and mult_str\<^sub>Y and zero_str\<^sub>Y and one_str\<^sub>Y and f + fixes \<phi>\<^sub>f:: "'c set \<Rightarrow> ('d \<Rightarrow> 'b)" assumes is_morphism_of_sheaves: "morphism_sheaves_of_rings Y is_open\<^sub>Y \<O>\<^sub>Y \<rho>\<^sub>Y d add_str\<^sub>Y mult_str\<^sub>Y zero_str\<^sub>Y one_str\<^sub>Y im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf \<phi>\<^sub>f" subsection \<open>Direct Limits of Rings\<close> (* construction 0.34 *) locale direct_lim = sheaf_of_rings + fixes I:: "'a set set" assumes subset_of_opens: "\<And>U. U \<in> I \<Longrightarrow> is_open U" and has_lower_bound: "\<And>U V. \<lbrakk> U\<in>I; V\<in>I \<rbrakk> \<Longrightarrow> \<exists>W\<in>I. W \<subseteq> U \<inter> V" begin definition get_lower_bound:: "'a set \<Rightarrow> 'a set \<Rightarrow> 'a set" where "get_lower_bound U V= (SOME W. W \<in> I \<and> W \<subseteq> U \<and> W \<subseteq> V)" lemma get_lower_bound[intro]: assumes "U \<in> I" "V \<in> I" shows "get_lower_bound U V \<in> I" "get_lower_bound U V \<subseteq> U" "get_lower_bound U V \<subseteq> V" proof - have "\<exists>W. W \<in> I \<and> W \<subseteq> U \<and> W \<subseteq> V" using has_lower_bound[OF assms] by auto from someI_ex[OF this] show "get_lower_bound U V \<in> I" "get_lower_bound U V \<subseteq> U" "get_lower_bound U V \<subseteq> V" unfolding get_lower_bound_def by auto qed lemma obtain_lower_bound_finite: assumes "finite Us" "Us \<noteq> {}" "Us \<subseteq> I" obtains W where "W \<in> I" "\<forall>U\<in>Us. W \<subseteq> U" using assms proof (induct Us arbitrary:thesis) case (insert U F) have ?case when "F={}" using insert.prems(1) insert.prems(3) that by blast moreover have ?case when "F\<noteq>{}" proof - obtain W where "W \<in> I" "\<forall>U\<in>F. W \<subseteq> U" using insert.hyps(3) insert.prems(3) by auto obtain W1 where "W1 \<in>I" "W1 \<subseteq> U" "W1 \<subseteq> W" by (meson \<open>W \<in> I\<close> get_lower_bound(1) get_lower_bound(2) get_lower_bound(3) insert.prems(3) insert_subset) then have "\<forall>a\<in>insert U F. W1 \<subseteq> a" using \<open>\<forall>U\<in>F. W \<subseteq> U\<close> by auto with \<open>W1 \<in>I\<close> show ?thesis using insert(4) by auto qed ultimately show ?case by auto qed simp definition principal_subs :: "'a set set \<Rightarrow> 'a set \<Rightarrow> 'a set filter" where "principal_subs As A = Abs_filter (\<lambda>P. \<forall>x. (x\<in>As \<and> x \<subseteq> A) \<longrightarrow> P x)" lemma eventually_principal_subs: "eventually P (principal_subs As A) \<longleftrightarrow> (\<forall>x. x\<in>As \<and> x\<subseteq>A \<longrightarrow> P x)" unfolding principal_subs_def by (rule eventually_Abs_filter, rule is_filter.intro) auto lemma principal_subs_UNIV[simp]: "principal_subs UNIV UNIV = top" by (auto simp: filter_eq_iff eventually_principal_subs) lemma principal_subs_empty[simp]: "principal_subs {} s = bot" (*"principal_subs ss {} = bot"*) by (auto simp: filter_eq_iff eventually_principal_subs) lemma principal_subs_le_iff[iff]: "principal_subs As A \<le> principal_subs As' A' \<longleftrightarrow> {x. x\<in>As \<and> x \<subseteq> A} \<subseteq> {x. x\<in>As' \<and> x \<subseteq> A'}" unfolding le_filter_def eventually_principal_subs by blast lemma principal_subs_eq_iff[iff]: "principal_subs As A = principal_subs As' A' \<longleftrightarrow>{x. x\<in>As \<and> x \<subseteq> A} = {x. x\<in>As' \<and> x \<subseteq> A'}" unfolding eq_iff by simp lemma principal_subs_inj_on[simp]:"inj_on (principal_subs As) As" unfolding inj_on_def by auto definition lbound :: "'a set set \<Rightarrow> ('a set) filter" where "lbound Us = (INF S\<in>{S. S\<in>I \<and> (\<forall>u\<in>Us. S \<subseteq> u)}. principal_subs I S)" lemma eventually_lbound_finite: assumes "finite A" "A\<noteq>{}" "A\<subseteq>I" shows "(\<forall>\<^sub>F w in lbound A. P w) \<longleftrightarrow> (\<exists>w0. w0 \<in> I \<and> (\<forall>a\<in>A. w0 \<subseteq> a) \<and> (\<forall>w. (w\<subseteq>w0 \<and> w\<in>I) \<longrightarrow> P w))" proof - have "\<exists>x. x \<in> I \<and> (\<forall>xa\<in>A. x \<subseteq> xa)" by (metis Int_iff assms inf.order_iff obtain_lower_bound_finite) moreover have " \<exists>x. x \<in> I \<and> Ball A ((\<subseteq>) x) \<and> {xa \<in> I. xa \<subseteq> x} \<subseteq> {x \<in> I. x \<subseteq> a} \<and> {xa \<in> I. xa \<subseteq> x} \<subseteq> {x \<in> I. x \<subseteq> b}" if "a \<in> I \<and> (\<forall>x\<in>A. a \<subseteq> x)" "b \<in> I \<and> (\<forall>x\<in>A. b \<subseteq> x)" for a b apply (rule exI[where x="get_lower_bound a b"]) using that apply auto subgoal using get_lower_bound(2) by blast subgoal by (meson get_lower_bound(2) subsetD) subgoal by (meson get_lower_bound(3) subsetD) done moreover have "(\<exists>b\<in>{S \<in> I. Ball A ((\<subseteq>) S)}. eventually P (principal_subs I b)) = (\<exists>w0. w0 \<in> I \<and> Ball A ((\<subseteq>) w0) \<and> (\<forall>w. w \<subseteq> w0 \<and> w \<in> I \<longrightarrow> P w))" unfolding eventually_principal_subs by force ultimately show ?thesis unfolding lbound_def by (subst eventually_INF_base) auto qed lemma lbound_eq: assumes A:"finite A" "A\<noteq>{}" "A\<subseteq>I" assumes B:"finite B" "B\<noteq>{}" "B\<subseteq>I" shows "lbound A = lbound B" proof - have "eventually P (lbound A')" if "eventually P (lbound B')" and A':"finite A'" "A'\<noteq>{}" "A' \<subseteq> I" and B':"finite B'" "B'\<noteq>{}" "B' \<subseteq> I" for P A' B' proof - obtain w0 where w0:"w0 \<in> I" "(\<forall>a\<in>B'. w0 \<subseteq> a)" "(\<forall>w. w \<subseteq> w0 \<and> w \<in> I \<longrightarrow> P w)" using \<open>eventually P (lbound B')\<close> unfolding eventually_lbound_finite[OF B',of P] by auto obtain w1 where w1:"w1 \<in> I" "\<forall>U\<in>A'. w1 \<subseteq> U" using obtain_lower_bound_finite[OF A'] by auto define w2 where "w2=get_lower_bound w0 w1" have "w2 \<in> I" using \<open>w0 \<in> I\<close> \<open>w1 \<in> I\<close> unfolding w2_def by auto moreover have "\<forall>a\<in>A'. w2 \<subseteq> a" unfolding w2_def by (meson dual_order.trans get_lower_bound(3) w0(1) w1(1) w1(2)) moreover have "\<forall>w. w \<subseteq> w2 \<and> w \<in> I \<longrightarrow> P w" unfolding w2_def by (meson dual_order.trans get_lower_bound(2) w0(1) w0(3) w1(1)) ultimately show ?thesis unfolding eventually_lbound_finite[OF A',of P] by auto qed then have "eventually P (lbound A) = eventually P (lbound B)" for P using A B by auto then show ?thesis unfolding filter_eq_iff by auto qed lemma lbound_leq: assumes "A \<subseteq> B" shows "lbound A \<le>lbound B" unfolding lbound_def apply (rule Inf_superset_mono) apply (rule image_mono) using assms by auto definition llbound::"('a set) filter" where "llbound = lbound {SOME a. a\<in>I}" lemma llbound_not_bot: assumes "I\<noteq> {}" shows "llbound \<noteq> bot" unfolding trivial_limit_def llbound_def apply (subst eventually_lbound_finite) using assms by (auto simp add: some_in_eq) lemma llbound_lbound: assumes "finite A" "A\<noteq>{}" "A\<subseteq>I" shows "lbound A = llbound" unfolding llbound_def apply (rule lbound_eq) using assms by (auto simp add: some_in_eq) definition rel:: "('a set \<times> 'b) \<Rightarrow> ('a set \<times> 'b) \<Rightarrow> bool" (infix "\<sim>" 80) where "x \<sim> y \<equiv> (fst x \<in> I \<and> fst y \<in> I) \<and> (snd x \<in> \<FF> (fst x) \<and> snd y \<in> \<FF> (fst y)) \<and> (\<exists>W. (W \<in> I) \<and> (W \<subseteq> fst x \<inter> fst y) \<and> \<rho> (fst x) W (snd x) = \<rho> (fst y) W (snd y))" lemma rel_is_equivalence: shows "equivalence (Sigma I \<FF>) {(x, y). x \<sim> y}" unfolding equivalence_def proof (intro conjI strip) show "(a, c) \<in> {(x, y). x \<sim> y}" if "(a, b) \<in> {(x, y). x \<sim> y}" "(b, c) \<in> {(x, y). x \<sim> y}" for a b c proof - obtain W1 where W1:"fst a \<in> I" "fst b \<in> I" "snd a \<in> \<FF> (fst a)" "snd b \<in> \<FF> (fst b)" "W1 \<in> I" "W1 \<subseteq> fst a" "W1 \<subseteq> fst b" "\<rho> (fst a) W1 (snd a) = \<rho> (fst b) W1 (snd b)" using \<open>(a, b) \<in> {(x, y). x \<sim> y}\<close> unfolding rel_def by auto obtain W2 where W2:"fst b \<in> I" "fst c \<in> I" "snd b \<in> \<FF> (fst b)" "snd c \<in> \<FF> (fst c)" "W2 \<in> I" "W2 \<subseteq> fst b" "W2 \<subseteq> fst c" "\<rho> (fst b) W2 (snd b) = \<rho> (fst c) W2 (snd c)" using \<open>(b, c) \<in> {(x, y). x \<sim> y}\<close> unfolding rel_def by auto obtain W3 where W3:"W3 \<in>I" "W3 \<subseteq> W1 \<inter> W2" using has_lower_bound[OF \<open>W1\<in>I\<close> \<open>W2\<in>I\<close>] by auto from \<open>W3 \<subseteq> W1 \<inter> W2\<close> have "W3 \<subseteq> fst a \<inter> fst c" using W1(6) W2(7) by blast moreover have "\<rho> (fst a) W3 (snd a) = \<rho> (fst c) W3 (snd c)" using W1 W2 by (metis W3(1) W3(2) eq_\<rho> le_inf_iff subset_of_opens) moreover note \<open>W3 \<in>I\<close> W1 W2 ultimately show ?thesis unfolding rel_def by auto qed qed (auto simp: rel_def Int_commute) interpretation rel:equivalence "(Sigma I \<FF>)" "{(x, y). x \<sim> y}" using rel_is_equivalence . definition class_of:: "'a set \<Rightarrow> 'b \<Rightarrow> ('a set \<times> 'b) set" ("\<lfloor>(_,/ _)\<rfloor>") where "\<lfloor>U,s\<rfloor> \<equiv> rel.Class (U, s)" lemma class_of_eqD: assumes "\<lfloor>U1,s1\<rfloor> = \<lfloor>U2,s2\<rfloor>" "(U1,s1) \<in> Sigma I \<FF>" "(U2,s2) \<in> Sigma I \<FF>" obtains W where "W \<in> I" "W \<subseteq> U1 \<inter> U2" "\<rho> U1 W s1 = \<rho> U2 W s2" using rel.Class_equivalence[OF assms(2,3)] assms(1) unfolding class_of_def rel_def by auto lemma class_of_eqI: assumes "(U1,s1) \<in> Sigma I \<FF>" "(U2,s2) \<in> Sigma I \<FF>" assumes "W \<in> I" "W \<subseteq> U1 \<inter> U2" "\<rho> U1 W s1 = \<rho> U2 W s2" shows "\<lfloor>U1,s1\<rfloor> = \<lfloor>U2,s2\<rfloor>" unfolding class_of_def apply (rule rel.Class_eq) using assms by (auto simp: rel_def) lemma class_of_0_in: assumes "U \<in> I" shows "\<zero>\<^bsub>U\<^esub> \<in> \<FF> U" proof - have "ring (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub>" using assms subset_of_opens is_ring_from_is_homomorphism by blast then show ?thesis unfolding ring_def abelian_group_def Group_Theory.group_def by (meson monoid.unit_closed) qed lemma rel_Class_iff: "x \<sim> y \<longleftrightarrow> y \<in> Sigma I \<FF> \<and> x \<in> rel.Class y" by blast lemma class_of_0_eq: assumes "U \<in> I" "U' \<in> I" shows "\<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor> = \<lfloor>U', \<zero>\<^bsub>U'\<^esub>\<rfloor>" proof - obtain W where W: "W \<in> I" "W \<subseteq> U" "W \<subseteq> U'" by (metis Int_subset_iff assms has_lower_bound) then have "is_open W" "is_open U" "is_open U'" by (auto simp add: assms subset_of_opens) then have "\<rho> U W \<zero>\<^bsub>U\<^esub> = \<rho> U' W \<zero>\<^bsub>U'\<^esub>" using W is_ring_morphism [of U W] is_ring_morphism [of U' W] by (simp add: ring_homomorphism_def group_homomorphism_def monoid_homomorphism_def monoid_homomorphism_axioms_def) with W have "\<exists>W. W \<in> I \<and> W \<subseteq> U \<and> W \<subseteq> U' \<and> \<rho> U W \<zero>\<^bsub>U\<^esub> = \<rho> U' W \<zero>\<^bsub>U'\<^esub>" by blast moreover have "\<zero>\<^bsub>U\<^esub> \<in> \<FF> U" "\<zero>\<^bsub>U'\<^esub> \<in> \<FF> U'" by (auto simp add: assms class_of_0_in) ultimately have "(U, \<zero>\<^bsub>U\<^esub>) \<sim> (U', \<zero>\<^bsub>U'\<^esub>)" using assms by (auto simp: rel_def) then show ?thesis unfolding class_of_def by (simp add: rel.Class_eq) qed lemma class_of_1_in: assumes "U \<in> I" shows "\<one>\<^bsub>U\<^esub> \<in> \<FF> U" proof - have "ring (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub>" using assms subset_of_opens is_ring_from_is_homomorphism by blast then show ?thesis unfolding ring_def by (meson monoid.unit_closed) qed lemma class_of_1_eq: assumes "U \<in> I" and "U' \<in> I" shows "\<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor> = \<lfloor>U', \<one>\<^bsub>U'\<^esub>\<rfloor>" proof - obtain W where W: "W \<in> I" "W \<subseteq> U" "W \<subseteq> U'" by (metis Int_subset_iff assms has_lower_bound) then have "is_open W" "is_open U" "is_open U'" by (auto simp add: assms subset_of_opens) then have "\<rho> U W \<one>\<^bsub>U\<^esub> = \<rho> U' W \<one>\<^bsub>U'\<^esub>" using W is_ring_morphism [of U W] is_ring_morphism [of U' W] by (simp add: ring_homomorphism_def group_homomorphism_def monoid_homomorphism_def monoid_homomorphism_axioms_def) with W have "\<exists>W. W \<in> I \<and> W \<subseteq> U \<and> W \<subseteq> U' \<and> \<rho> U W \<one>\<^bsub>U\<^esub> = \<rho> U' W \<one>\<^bsub>U'\<^esub>" by blast moreover have "\<one>\<^bsub>U\<^esub> \<in> \<FF> U" "\<one>\<^bsub>U'\<^esub> \<in> \<FF> U'" by (auto simp add: assms class_of_1_in) ultimately have "(U, \<one>\<^bsub>U\<^esub>) \<sim> (U', \<one>\<^bsub>U'\<^esub>)" using assms by (auto simp: rel_def) then show ?thesis unfolding class_of_def by (simp add: rel.Class_eq) qed definition add_rel :: "('a set \<times> 'b) set \<Rightarrow> ('a set \<times> 'b) set \<Rightarrow> ('a set \<times> 'b) set" where "add_rel X Y \<equiv> let x = (SOME x. x \<in> X); y = (SOME y. y \<in> Y); w = get_lower_bound (fst x) (fst y) in \<lfloor>w, add_str w (\<rho> (fst x) w (snd x)) (\<rho> (fst y) w (snd y))\<rfloor>" definition mult_rel :: "('a set \<times> 'b) set \<Rightarrow> ('a set \<times> 'b) set \<Rightarrow> ('a set \<times> 'b) set" where "mult_rel X Y \<equiv> let x = (SOME x. x \<in> X); y = (SOME y. y \<in> Y); w = get_lower_bound (fst x) (fst y) in \<lfloor>w, mult_str w (\<rho> (fst x) w (snd x)) (\<rho> (fst y) w (snd y))\<rfloor>" definition carrier_direct_lim:: "('a set \<times> 'b) set set" where "carrier_direct_lim \<equiv> rel.Partition" lemma zero_rel_carrier[intro]: assumes "U \<in> I" shows "\<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor> \<in> carrier_direct_lim" unfolding carrier_direct_lim_def class_of_def proof (rule rel.Block_closed) interpret ring "(\<FF> U)" "+\<^bsub>U\<^esub>" "\<cdot>\<^bsub>U\<^esub>" "\<zero>\<^bsub>U\<^esub>" "\<one>\<^bsub>U\<^esub>" by (simp add: assms is_ring_from_is_homomorphism subset_of_opens) show "(U, \<zero>\<^bsub>U\<^esub>) \<in> Sigma I \<FF>" by (simp add: assms) qed lemma one_rel_carrier[intro]: assumes "U \<in> I" shows "\<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor> \<in> carrier_direct_lim" unfolding carrier_direct_lim_def class_of_def apply (rule rel.Block_closed) by (simp add: assms class_of_1_in) lemma rel_carrier_Eps_in: fixes X :: "('a set \<times> 'b) set" defines "a\<equiv>(SOME x. x \<in> X)" assumes "X \<in> carrier_direct_lim" shows "a \<in> X" "a \<in>Sigma I \<FF>" "X = \<lfloor>fst a, snd a\<rfloor>" proof - have "\<exists>a\<in>Sigma I \<FF>. a \<in> X \<and> X = rel.Class a" using rel.representant_exists[OF \<open>X \<in> carrier_direct_lim\<close>[unfolded carrier_direct_lim_def]] by simp then have "a \<in> X \<and> a \<in>Sigma I \<FF> \<and> X = \<lfloor>fst a, snd a\<rfloor>" unfolding class_of_def by (metis a_def assms(2) carrier_direct_lim_def ex_in_conv prod.collapse rel.Block_self rel.Class_closed some_in_eq) then show "a \<in> X" "a \<in>Sigma I \<FF>" "X = \<lfloor>fst a, snd a\<rfloor>" by auto qed lemma add_rel_carrier[intro]: assumes "X \<in> carrier_direct_lim" "Y \<in> carrier_direct_lim" shows "add_rel X Y \<in> carrier_direct_lim" proof - define x where "x=(SOME x. x \<in> X)" define y where "y=(SOME y. y \<in> Y)" define z where "z=get_lower_bound (fst x) (fst y)" have "x\<in>X" "x\<in>Sigma I \<FF>" using rel_carrier_Eps_in[OF \<open>X \<in> carrier_direct_lim\<close>] unfolding x_def by auto have "y\<in>Y" "y \<in> Sigma I \<FF>" using rel_carrier_Eps_in[OF \<open>Y \<in> carrier_direct_lim\<close>] unfolding y_def by auto have "add_rel X Y = \<lfloor>z, add_str z (\<rho> (fst x) z (snd x)) (\<rho> (fst y) z (snd y))\<rfloor>" unfolding add_rel_def Let_def by (fold x_def y_def z_def,rule) also have "... \<in> carrier_direct_lim" unfolding carrier_direct_lim_def class_of_def proof (rule rel.Block_closed) have "z\<in>I" using \<open>x\<in>Sigma I \<FF>\<close> \<open>y\<in>Sigma I \<FF>\<close> unfolding z_def by auto then interpret ring "(\<FF> z)" "+\<^bsub>z\<^esub>" "\<cdot>\<^bsub>z\<^esub>" "\<zero>\<^bsub>z\<^esub>" "\<one>\<^bsub>z\<^esub>" using is_ring_from_is_homomorphism subset_of_opens by auto show "(z, +\<^bsub>z\<^esub> (\<rho> (fst x) z (snd x)) (\<rho> (fst y) z (snd y))) \<in> Sigma I \<FF>" using \<open>z\<in>I\<close> apply simp by (metis \<open>x \<in> Sigma I \<FF>\<close> \<open>y \<in> Sigma I \<FF>\<close> additive.composition_closed direct_lim.subset_of_opens direct_lim_axioms get_lower_bound(2) get_lower_bound(3) is_map_from_is_homomorphism map.map_closed mem_Sigma_iff prod.exhaust_sel z_def) qed finally show ?thesis . qed lemma rel_eventually_llbound: assumes "x \<sim> y" shows "\<forall>\<^sub>F w in llbound. \<rho> (fst x) w (snd x) = \<rho> (fst y) w (snd y)" proof - have xy:"fst x \<in> I" "fst y \<in> I" "snd x \<in> \<FF> (fst x)" "snd y \<in> \<FF> (fst y)" using \<open>x \<sim> y\<close> unfolding rel_def by auto obtain w0 where w0:"w0 \<in> I" "w0 \<subseteq> fst x \<inter> fst y" "\<rho> (fst x) w0 (snd x) = \<rho> (fst y) w0 (snd y)" using \<open>x \<sim> y\<close> unfolding rel_def by auto interpret xw0:ring_homomorphism "\<rho> (fst x) w0" "\<FF> (fst x)" "+\<^bsub>fst x\<^esub>" "\<cdot>\<^bsub>fst x\<^esub>" "\<zero>\<^bsub>fst x\<^esub>" "\<one>\<^bsub>fst x\<^esub>" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" by (meson is_ring_morphism le_inf_iff subset_of_opens w0 xy(1)) interpret yw0:ring_homomorphism "\<rho> (fst y) w0" "\<FF> (fst y)" "+\<^bsub>fst y\<^esub>" "\<cdot>\<^bsub>fst y\<^esub>" "\<zero>\<^bsub>fst y\<^esub>" "\<one>\<^bsub>fst y\<^esub>" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" using w0 by (metis is_ring_morphism le_inf_iff subset_of_opens xy(2)) have "\<rho> (fst x) w (snd x) = \<rho> (fst y) w (snd y)" if "w \<subseteq> w0" "w \<in> I" for w proof - interpret w0w:ring_homomorphism "\<rho> w0 w" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" "\<FF> w" "+\<^bsub>w\<^esub>" "\<cdot>\<^bsub>w\<^esub>" "\<zero>\<^bsub>w\<^esub>" "\<one>\<^bsub>w\<^esub>" using is_ring_morphism subset_of_opens that w0(1) by presburger have "\<rho> (fst x) w (snd x) = (\<rho> w0 w \<circ> \<rho> (fst x) w0) (snd x)" by (meson assoc_comp le_inf_iff subset_of_opens that w0 xy) also have "... = (\<rho> w0 w \<circ> \<rho> (fst y) w0) (snd y)" unfolding comp_def using w0(3) by auto also have "... = \<rho> (fst y) w (snd y)" using w0 xy by (metis Int_subset_iff assoc_comp subset_of_opens that) finally show ?thesis . qed with w0 have "\<exists>w0. w0 \<in> I \<and> w0 \<subseteq> fst x \<inter> fst y \<and> (\<forall>w. (w\<subseteq>w0 \<and> w\<in>I) \<longrightarrow> \<rho> (fst x) w (snd x) = \<rho> (fst y) w (snd y))" by auto then have "\<forall>\<^sub>F w in lbound {fst x,fst y}. \<rho> (fst x) w (snd x) = \<rho> (fst y) w (snd y)" apply (subst eventually_lbound_finite) using xy(1,2) by auto then show ?thesis using llbound_lbound[of "{fst x,fst y}"] xy(1,2) by auto qed lemma fixes x y:: "'a set \<times> 'b" and z z':: "'a set" assumes xy:"x \<in> Sigma I \<FF>" "y \<in> Sigma I \<FF>" assumes z:"z\<in>I" "z \<subseteq> fst x" "z \<subseteq> fst y" assumes z':"z'\<in>I" "z' \<subseteq> fst x" "z' \<subseteq> fst y" shows add_rel_well_defined:"\<lfloor>z, add_str z (\<rho> (fst x) z (snd x)) (\<rho> (fst y) z (snd y))\<rfloor> = \<lfloor>z', add_str z' (\<rho> (fst x) z' (snd x)) (\<rho> (fst y) z' (snd y))\<rfloor>" (is "?add") and mult_rel_well_defined: "\<lfloor>z, mult_str z (\<rho> (fst x) z (snd x)) (\<rho> (fst y) z (snd y))\<rfloor> = \<lfloor>z', mult_str z' (\<rho> (fst x) z' (snd x)) (\<rho> (fst y) z' (snd y))\<rfloor>" (is "?mult") proof - interpret xz:ring_homomorphism "(\<rho> (fst x) z)" "(\<FF> (fst x))" "+\<^bsub>fst x\<^esub>" "\<cdot>\<^bsub>fst x\<^esub>" "\<zero>\<^bsub>fst x\<^esub>" "\<one>\<^bsub>fst x\<^esub>" "(\<FF> z)" "+\<^bsub>z\<^esub>" "\<cdot>\<^bsub>z\<^esub>" "\<zero>\<^bsub>z\<^esub>" "\<one>\<^bsub>z\<^esub>" using is_ring_morphism \<open>x \<in> Sigma I \<FF>\<close> z subset_of_opens by force interpret yz:ring_homomorphism "(\<rho> (fst y) z)" "(\<FF> (fst y))" "+\<^bsub>fst y\<^esub>" "\<cdot>\<^bsub>fst y\<^esub>" "\<zero>\<^bsub>fst y\<^esub>" "\<one>\<^bsub>fst y\<^esub>" "(\<FF> z)" "+\<^bsub>z\<^esub>" "\<cdot>\<^bsub>z\<^esub>" "\<zero>\<^bsub>z\<^esub>" "\<one>\<^bsub>z\<^esub>" using is_ring_morphism \<open>y \<in> Sigma I \<FF>\<close> z subset_of_opens by force interpret xz':ring_homomorphism "(\<rho> (fst x) z')" "(\<FF> (fst x))" "+\<^bsub>fst x\<^esub>" "\<cdot>\<^bsub>fst x\<^esub>" "\<zero>\<^bsub>fst x\<^esub>" "\<one>\<^bsub>fst x\<^esub>" "(\<FF> z')" "+\<^bsub>z'\<^esub>" "\<cdot>\<^bsub>z'\<^esub>" "\<zero>\<^bsub>z'\<^esub>" "\<one>\<^bsub>z'\<^esub>" using is_ring_morphism \<open>x \<in> Sigma I \<FF>\<close> z' subset_of_opens by force interpret yz':ring_homomorphism "(\<rho> (fst y) z')" "(\<FF> (fst y))" "+\<^bsub>fst y\<^esub>" "\<cdot>\<^bsub>fst y\<^esub>" "\<zero>\<^bsub>fst y\<^esub>" "\<one>\<^bsub>fst y\<^esub>" "(\<FF> z')" "+\<^bsub>z'\<^esub>" "\<cdot>\<^bsub>z'\<^esub>" "\<zero>\<^bsub>z'\<^esub>" "\<one>\<^bsub>z'\<^esub>" using is_ring_morphism \<open>y \<in> Sigma I \<FF>\<close> z' subset_of_opens by force obtain w where w:"w \<in> I" "w \<subseteq> z \<inter> z'" using has_lower_bound \<open>z\<in>I\<close> \<open>z'\<in>I\<close> by meson interpret zw:ring_homomorphism "\<rho> z w" "(\<FF> z)" "+\<^bsub>z\<^esub>" "\<cdot>\<^bsub>z\<^esub>" "\<zero>\<^bsub>z\<^esub>" "\<one>\<^bsub>z\<^esub>" "\<FF> w" "+\<^bsub>w\<^esub>" "\<cdot>\<^bsub>w\<^esub>" "\<zero>\<^bsub>w\<^esub>" "\<one>\<^bsub>w\<^esub>" using w by (meson is_ring_morphism le_inf_iff subset_of_opens z(1)) interpret z'w:ring_homomorphism "\<rho> z' w" "(\<FF> z')" "+\<^bsub>z'\<^esub>" "\<cdot>\<^bsub>z'\<^esub>" "\<zero>\<^bsub>z'\<^esub>" "\<one>\<^bsub>z'\<^esub>" "\<FF> w" "+\<^bsub>w\<^esub>" "\<cdot>\<^bsub>w\<^esub>" "\<zero>\<^bsub>w\<^esub>" "\<one>\<^bsub>w\<^esub>" using \<open>w \<in> I\<close> \<open>w \<subseteq> z \<inter> z'\<close> z' by (meson is_ring_morphism le_inf_iff subset_of_opens) show ?add proof (rule class_of_eqI[OF _ _ \<open>w \<in> I\<close> \<open>w \<subseteq> z \<inter> z'\<close>]) define xz yz where "xz = \<rho> (fst x) z (snd x)" and "yz = \<rho> (fst y) z (snd y)" define xz' yz' where "xz' = \<rho> (fst x) z' (snd x)" and "yz' = \<rho> (fst y) z' (snd y)" show "(z, +\<^bsub>z\<^esub> xz yz) \<in> Sigma I \<FF>" "(z', +\<^bsub>z'\<^esub> xz' yz') \<in> Sigma I \<FF>" subgoal using assms(1) assms(2) xz_def yz_def z(1) by fastforce subgoal using assms(1) assms(2) xz'_def yz'_def z'(1) by fastforce done have "\<rho> z w (+\<^bsub>z\<^esub> xz yz) = +\<^bsub>w\<^esub> (\<rho> z w xz) (\<rho> z w yz)" apply (rule zw.additive.commutes_with_composition) using assms(1,2) xz_def yz_def by force+ also have "... = +\<^bsub>w\<^esub> (\<rho> (fst x) w (snd x)) (\<rho> (fst y) w (snd y))" unfolding xz_def yz_def using assoc_comp w z subset_of_opens assms by (metis SigmaE le_inf_iff o_def prod.sel) also have "... = +\<^bsub>w\<^esub> (\<rho> z' w xz') (\<rho> z' w yz')" unfolding xz'_def yz'_def using assoc_comp w z' subset_of_opens assms by (metis SigmaE le_inf_iff o_def prod.sel) also have "... = \<rho> z' w (+\<^bsub>z'\<^esub> xz' yz')" using assms(2) xy(1) xz'_def yz'_def z'w.additive.commutes_with_composition by force finally show "\<rho> z w (+\<^bsub>z\<^esub> xz yz) = \<rho> z' w (+\<^bsub>z'\<^esub> xz' yz')" . qed show ?mult proof (rule class_of_eqI[OF _ _ \<open>w \<in> I\<close> \<open>w \<subseteq> z \<inter> z'\<close>]) define xz yz where "xz = \<rho> (fst x) z (snd x)" and "yz = \<rho> (fst y) z (snd y)" define xz' yz' where "xz' = \<rho> (fst x) z' (snd x)" and "yz' = \<rho> (fst y) z' (snd y)" show "(z, \<cdot>\<^bsub>z\<^esub> xz yz) \<in> Sigma I \<FF>" "(z', \<cdot>\<^bsub>z'\<^esub> xz' yz') \<in> Sigma I \<FF>" unfolding xz_def yz_def xz'_def yz'_def using assms by auto have "\<rho> z w (\<cdot>\<^bsub>z\<^esub> xz yz) = \<cdot>\<^bsub>w\<^esub> (\<rho> z w xz) (\<rho> z w yz)" apply (rule zw.multiplicative.commutes_with_composition) using xy xz_def yz_def by force+ also have "... = \<cdot>\<^bsub>w\<^esub> (\<rho> (fst x) w (snd x)) (\<rho> (fst y) w (snd y))" unfolding xz_def yz_def using xy w z assoc_comp by (metis SigmaE fst_conv le_inf_iff o_def snd_conv subset_of_opens) also have "... = \<cdot>\<^bsub>w\<^esub> (\<rho> z' w xz') (\<rho> z' w yz')" unfolding xz'_def yz'_def using xy w z' assoc_comp by (metis SigmaE fst_conv le_inf_iff o_def snd_conv subset_of_opens) also have "... = \<rho> z' w (\<cdot>\<^bsub>z'\<^esub> xz' yz')" unfolding xz'_def yz'_def using monoid_homomorphism.commutes_with_composition xy z'w.multiplicative.monoid_homomorphism_axioms by fastforce finally show "\<rho> z w (\<cdot>\<^bsub>z\<^esub> xz yz) = \<rho> z' w (\<cdot>\<^bsub>z'\<^esub> xz' yz')" . qed qed lemma add_rel_well_defined_llbound: fixes x y:: "'a set \<times> 'b" and z z':: "'a set" assumes "x \<in> Sigma I \<FF>" "y \<in> Sigma I \<FF>" assumes z:"z\<in>I" "z \<subseteq> fst x" "z \<subseteq> fst y" shows "\<forall>\<^sub>F w in llbound. \<lfloor>z, add_str z (\<rho> (fst x) z (snd x)) (\<rho> (fst y) z (snd y))\<rfloor> = \<lfloor>w, add_str w (\<rho> (fst x) w (snd x)) (\<rho> (fst y) w (snd y))\<rfloor>" (is "\<forall>\<^sub>F w in _. ?P w") proof - have "\<forall>w. w \<subseteq> z \<and> w \<in> I \<longrightarrow>?P w " by (meson add_rel_well_defined assms(1) assms(2) dual_order.trans z(1) z(2) z(3)) then have "\<forall>\<^sub>F w in lbound {fst x,fst y}. ?P w" apply (subst eventually_lbound_finite) using assms by auto then show ?thesis using llbound_lbound[of "{fst x,fst y}"] assms(1,2) by auto qed lemma mult_rel_well_defined_llbound: fixes x y:: "'a set \<times> 'b" and z z':: "'a set" assumes "x \<in> Sigma I \<FF>" "y \<in> Sigma I \<FF>" assumes z:"z\<in>I" "z \<subseteq> fst x" "z \<subseteq> fst y" shows "\<forall>\<^sub>F w in llbound. \<lfloor>z, mult_str z (\<rho> (fst x) z (snd x)) (\<rho> (fst y) z (snd y))\<rfloor> = \<lfloor>w, mult_str w (\<rho> (fst x) w (snd x)) (\<rho> (fst y) w (snd y))\<rfloor>" (is "\<forall>\<^sub>F w in _. ?P w") proof - have "\<forall>w. w \<subseteq> z \<and> w \<in> I \<longrightarrow>?P w " by (meson mult_rel_well_defined assms(1) assms(2) dual_order.trans z(1) z(2) z(3)) then have "\<forall>\<^sub>F w in lbound {fst x,fst y}. ?P w" apply (subst eventually_lbound_finite) using assms by auto then show ?thesis using llbound_lbound[of "{fst x,fst y}"] assms(1,2) by auto qed lemma add_rel_class_of: fixes U V W :: "'a set" and x y :: 'b assumes uv_sigma:"(U, x) \<in> Sigma I \<FF>" "(V, y) \<in> Sigma I \<FF>" assumes w:"W \<in> I" "W \<subseteq> U" "W \<subseteq> V" shows "add_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>W, +\<^bsub>W\<^esub> (\<rho> U W x) (\<rho> V W y)\<rfloor>" proof - define ux where "ux = (SOME ux. ux \<in> \<lfloor>U, x\<rfloor>)" define vy where "vy = (SOME ux. ux \<in> \<lfloor>V, y\<rfloor>)" have "ux \<in> \<lfloor>U, x\<rfloor>" "vy \<in> \<lfloor>V, y\<rfloor> " unfolding ux_def vy_def using uv_sigma class_of_def some_in_eq by blast+ then have "ux \<in> Sigma I \<FF>" "vy \<in> Sigma I \<FF>" using class_of_def uv_sigma by blast+ then have "fst ux \<in> I" "fst vy \<in> I" by auto define w1 where "w1 = get_lower_bound (fst ux) (fst vy)" have w1:"w1 \<in> I" "w1 \<subseteq> fst ux" "w1 \<subseteq> fst vy" using get_lower_bound[OF \<open>fst ux \<in> I\<close> \<open>fst vy \<in> I\<close>] unfolding w1_def by auto have "add_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>w1, +\<^bsub>w1\<^esub> (\<rho> (fst ux) w1 (snd ux)) (\<rho> (fst vy) w1 (snd vy))\<rfloor>" unfolding add_rel_def apply (fold ux_def vy_def) by (simp add:Let_def w1_def) moreover have "\<forall>\<^sub>F w in llbound. ... = \<lfloor>w, add_str w (\<rho> (fst ux) w (snd ux)) (\<rho> (fst vy) w (snd vy))\<rfloor>" apply (rule add_rel_well_defined_llbound) using \<open>ux \<in> Sigma I \<FF>\<close> \<open>vy \<in> Sigma I \<FF>\<close> w1 by auto ultimately have "\<forall>\<^sub>F w in llbound. add_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>w, add_str w (\<rho> (fst ux) w (snd ux)) (\<rho> (fst vy) w (snd vy))\<rfloor>" by simp moreover have "\<forall>\<^sub>F w in llbound. \<rho> (fst ux) w (snd ux) = \<rho> (fst (U, x)) w (snd (U, x))" "\<forall>\<^sub>F w in llbound. \<rho> (fst vy) w (snd vy) = \<rho> (fst (V, y)) w (snd (V, y))" subgoal apply (rule rel_eventually_llbound) using \<open>ux \<in> \<lfloor>U, x\<rfloor>\<close> class_of_def uv_sigma(1) by auto subgoal apply (rule rel_eventually_llbound) using \<open>vy \<in> \<lfloor>V, y\<rfloor>\<close> class_of_def uv_sigma(2) by auto done ultimately have "\<forall>\<^sub>F w in llbound. add_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>w, add_str w (\<rho> U w x) (\<rho> V w y)\<rfloor>" apply eventually_elim by auto moreover have "\<forall>\<^sub>F w in llbound. \<lfloor>W, +\<^bsub>W\<^esub> (\<rho> U W x) (\<rho> V W y)\<rfloor> = \<lfloor>w, +\<^bsub>w\<^esub> (\<rho> U w x) (\<rho> V w y)\<rfloor>" apply (rule add_rel_well_defined_llbound[of "(U,x)" "(V,y)" W,simplified]) using w uv_sigma by auto ultimately have "\<forall>\<^sub>F w in llbound. add_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>W, +\<^bsub>W\<^esub> (\<rho> U W x) (\<rho> V W y)\<rfloor>" apply eventually_elim by auto moreover have "llbound\<noteq>bot" using llbound_not_bot w(1) by blast ultimately show ?thesis by auto qed lemma mult_rel_class_of: fixes U V W :: "'a set" and x y :: 'b assumes uv_sigma:"(U, x) \<in> Sigma I \<FF>" "(V, y) \<in> Sigma I \<FF>" assumes w:"W \<in> I" "W \<subseteq> U" "W \<subseteq> V" shows "mult_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>W, \<cdot>\<^bsub>W\<^esub> (\<rho> U W x) (\<rho> V W y)\<rfloor>" proof - define ux where "ux = (SOME ux. ux \<in> \<lfloor>U, x\<rfloor>)" define vy where "vy = (SOME ux. ux \<in> \<lfloor>V, y\<rfloor>)" have "ux \<in> \<lfloor>U, x\<rfloor>" "vy \<in> \<lfloor>V, y\<rfloor> " unfolding ux_def vy_def using uv_sigma class_of_def some_in_eq by blast+ then have "ux \<in> Sigma I \<FF>" "vy \<in> Sigma I \<FF>" using class_of_def uv_sigma by blast+ then have "fst ux \<in> I" "fst vy \<in> I" by auto define w1 where "w1 = get_lower_bound (fst ux) (fst vy)" have w1:"w1 \<in> I" "w1 \<subseteq> fst ux" "w1 \<subseteq> fst vy" using get_lower_bound[OF \<open>fst ux \<in> I\<close> \<open>fst vy \<in> I\<close>] unfolding w1_def by auto have "mult_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>w1, \<cdot>\<^bsub>w1\<^esub> (\<rho> (fst ux) w1 (snd ux)) (\<rho> (fst vy) w1 (snd vy))\<rfloor>" unfolding mult_rel_def apply (fold ux_def vy_def) by (simp add:Let_def w1_def) moreover have "\<forall>\<^sub>F w in llbound. ... = \<lfloor>w, mult_str w (\<rho> (fst ux) w (snd ux)) (\<rho> (fst vy) w (snd vy))\<rfloor>" apply (rule mult_rel_well_defined_llbound) using \<open>ux \<in> Sigma I \<FF>\<close> \<open>vy \<in> Sigma I \<FF>\<close> w1 by auto ultimately have "\<forall>\<^sub>F w in llbound. mult_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>w, mult_str w (\<rho> (fst ux) w (snd ux)) (\<rho> (fst vy) w (snd vy))\<rfloor>" by simp moreover have "\<forall>\<^sub>F w in llbound. \<rho> (fst ux) w (snd ux) = \<rho> (fst (U, x)) w (snd (U, x))" "\<forall>\<^sub>F w in llbound. \<rho> (fst vy) w (snd vy) = \<rho> (fst (V, y)) w (snd (V, y))" subgoal apply (rule rel_eventually_llbound) using \<open>ux \<in> \<lfloor>U, x\<rfloor>\<close> class_of_def uv_sigma(1) by auto subgoal apply (rule rel_eventually_llbound) using \<open>vy \<in> \<lfloor>V, y\<rfloor>\<close> class_of_def uv_sigma(2) by auto done ultimately have "\<forall>\<^sub>F w in llbound. mult_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>w, mult_str w (\<rho> U w x) (\<rho> V w y)\<rfloor>" apply eventually_elim by auto moreover have "\<forall>\<^sub>F w in llbound. \<lfloor>W, \<cdot>\<^bsub>W\<^esub> (\<rho> U W x) (\<rho> V W y)\<rfloor> = \<lfloor>w, \<cdot>\<^bsub>w\<^esub> (\<rho> U w x) (\<rho> V w y)\<rfloor>" apply (rule mult_rel_well_defined_llbound[of "(U,x)" "(V,y)" W,simplified]) using w uv_sigma by auto ultimately have "\<forall>\<^sub>F w in llbound. mult_rel \<lfloor>U, x\<rfloor> \<lfloor>V, y\<rfloor> = \<lfloor>W, \<cdot>\<^bsub>W\<^esub> (\<rho> U W x) (\<rho> V W y)\<rfloor>" apply eventually_elim by auto moreover have "llbound\<noteq>bot" using llbound_not_bot w(1) by blast ultimately show ?thesis by auto qed lemma mult_rel_carrier[intro]: assumes "X \<in> carrier_direct_lim" "Y \<in> carrier_direct_lim" shows "mult_rel X Y \<in> carrier_direct_lim" proof - define x where "x=(SOME x. x \<in> X)" define y where "y=(SOME y. y \<in> Y)" have "x\<in>X" "x\<in>Sigma I \<FF>" using rel_carrier_Eps_in[OF \<open>X \<in> carrier_direct_lim\<close>] unfolding x_def by auto have "y\<in>Y" "y \<in> Sigma I \<FF>" using rel_carrier_Eps_in[OF \<open>Y \<in> carrier_direct_lim\<close>] unfolding y_def by auto define z where "z=get_lower_bound (fst x) (fst y)" have "z \<in> I" "z \<subseteq> fst x" "z \<subseteq> fst y" proof - have "fst x \<in> I" "fst y \<in> I" using \<open>x \<in> Sigma I \<FF>\<close> \<open>y \<in> Sigma I \<FF>\<close> by auto then show "z \<in> I" "z \<subseteq> fst x" "z \<subseteq> fst y" using get_lower_bound[of "fst x" "fst y",folded z_def] by auto qed have "mult_rel X Y = \<lfloor>z, mult_str z (\<rho> (fst x) z (snd x)) (\<rho> (fst y) z (snd y))\<rfloor>" unfolding mult_rel_def Let_def by (fold x_def y_def z_def,rule) also have "... \<in> carrier_direct_lim" unfolding carrier_direct_lim_def class_of_def proof (rule rel.Block_closed) interpret ring "(\<FF> z)" "+\<^bsub>z\<^esub>" "\<cdot>\<^bsub>z\<^esub>" "\<zero>\<^bsub>z\<^esub>" "\<one>\<^bsub>z\<^esub>" by (simp add: \<open>z \<in> I\<close> is_ring_from_is_homomorphism subset_of_opens) show "(z, \<cdot>\<^bsub>z\<^esub> (\<rho> (fst x) z (snd x)) (\<rho> (fst y) z (snd y))) \<in> Sigma I \<FF>" by (metis SigmaE SigmaI \<open>x \<in> Sigma I \<FF>\<close> \<open>y \<in> Sigma I \<FF>\<close> \<open>z \<in> I\<close> \<open>z \<subseteq> fst x\<close> \<open>z \<subseteq> fst y\<close> direct_lim.subset_of_opens direct_lim_axioms fst_conv is_map_from_is_homomorphism map.map_closed multiplicative.composition_closed snd_conv) qed finally show ?thesis . qed (* exercise 0.35 *) lemma direct_lim_is_ring: assumes "U \<in> I" shows "ring carrier_direct_lim add_rel mult_rel \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor> \<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor>" proof unfold_locales show add_rel: "add_rel a b \<in> carrier_direct_lim" and mult_rel: "mult_rel a b \<in> carrier_direct_lim" if "a \<in> carrier_direct_lim" "b \<in> carrier_direct_lim" for a b using \<open>U \<in> I\<close> that by auto show zero_rel: "\<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor> \<in> carrier_direct_lim" and one_rel: "\<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor> \<in> carrier_direct_lim" using \<open>U \<in> I\<close> by auto show add_rel_0: "add_rel \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor> X = X" and "mult_rel \<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor> X = X" and "mult_rel X \<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor> = X" if "X \<in> carrier_direct_lim" for X proof - define x where "x=(SOME x. x \<in> X)" have x:"x\<in>X" "x\<in>Sigma I \<FF>" "fst x\<in>I" and X_alt:"X= \<lfloor>fst x, snd x\<rfloor>" using rel_carrier_Eps_in[OF \<open>X \<in> carrier_direct_lim\<close>] unfolding x_def by auto obtain w0 where w0:"w0\<in>I" "w0 \<subseteq> U" "w0 \<subseteq> fst x" using has_lower_bound[OF \<open>U\<in>I\<close> \<open>fst x\<in>I\<close>] by blast interpret uw0:ring_homomorphism "\<rho> U w0" "\<FF> U" "+\<^bsub>U\<^esub>" "\<cdot>\<^bsub>U\<^esub>" "\<zero>\<^bsub>U\<^esub>" "\<one>\<^bsub>U\<^esub>" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" using is_ring_morphism \<open>U\<in>I\<close> w0 subset_of_opens by auto interpret xw0:ring_homomorphism "\<rho> (fst x) w0" "\<FF> (fst x)" "+\<^bsub>fst x\<^esub>" "\<cdot>\<^bsub>fst x\<^esub>" "\<zero>\<^bsub>fst x\<^esub>" "\<one>\<^bsub>fst x\<^esub>" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" using is_ring_morphism \<open>fst x\<in>I\<close> w0 subset_of_opens by auto have "add_rel \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor> X = \<lfloor>w0, +\<^bsub>w0\<^esub> (\<rho> U w0 \<zero>\<^bsub>U\<^esub>) (\<rho> (fst x) w0 (snd x))\<rfloor>" unfolding X_alt apply (subst add_rel_class_of) using \<open>U \<in> I\<close> w0 x by simp_all also have "... = \<lfloor>w0, +\<^bsub>w0\<^esub> \<zero>\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x))\<rfloor>" by (simp add:uw0.additive.commutes_with_unit ) also have "... = \<lfloor>w0, \<rho> (fst x) w0 (snd x)\<rfloor>" apply (subst uw0.target.additive.left_unit) using carrier_direct_lim_def rel.block_closed that x(1) by auto also have "... = X" unfolding X_alt apply (rule class_of_eqI[where W=w0]) using w0 x subset_of_opens by auto finally show "add_rel \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor> X = X" . have "mult_rel \<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor> X = \<lfloor>w0, \<cdot>\<^bsub>w0\<^esub> (\<rho> U w0 \<one>\<^bsub>U\<^esub>) (\<rho> (fst x) w0 (snd x))\<rfloor>" unfolding X_alt apply (subst mult_rel_class_of) using \<open>U \<in> I\<close> w0 x by simp_all also have "... = \<lfloor>w0, \<cdot>\<^bsub>w0\<^esub> \<one>\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x))\<rfloor>" by (simp add: uw0.multiplicative.commutes_with_unit) also have "... = \<lfloor>w0, \<rho> (fst x) w0 (snd x)\<rfloor>" apply (subst uw0.target.multiplicative.left_unit) using carrier_direct_lim_def rel.block_closed that x(1) by auto also have "... = X" using X_alt \<open>\<lfloor>w0, \<rho> (fst x) w0 (snd x)\<rfloor> = X\<close> by force finally show "mult_rel \<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor> X = X" . have "mult_rel X \<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor> = \<lfloor>w0, \<cdot>\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) (\<rho> U w0 \<one>\<^bsub>U\<^esub>)\<rfloor>" unfolding X_alt apply (subst mult_rel_class_of) using \<open>U \<in> I\<close> w0 x by simp_all also have "... = \<lfloor>w0, \<cdot>\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) \<one>\<^bsub>w0\<^esub> \<rfloor>" by (simp add: uw0.multiplicative.commutes_with_unit) also have "... = \<lfloor>w0, \<rho> (fst x) w0 (snd x)\<rfloor>" apply (subst uw0.target.multiplicative.right_unit) using carrier_direct_lim_def rel.block_closed that x(1) by auto also have "... = X" using X_alt \<open>\<lfloor>w0, \<rho> (fst x) w0 (snd x)\<rfloor> = X\<close> by force finally show "mult_rel X \<lfloor>U, \<one>\<^bsub>U\<^esub>\<rfloor> = X" . qed show add_rel_commute: "add_rel X Y = add_rel Y X" if "X \<in> carrier_direct_lim" "Y \<in> carrier_direct_lim" for X Y proof - define x where "x=(SOME x. x \<in> X)" define y where "y=(SOME y. y \<in> Y)" have x:"x\<in>X" "x\<in>Sigma I \<FF>" using rel_carrier_Eps_in[OF \<open>X \<in> carrier_direct_lim\<close>] unfolding x_def by auto have y:"y\<in>Y" "y \<in> Sigma I \<FF>" using rel_carrier_Eps_in[OF \<open>Y \<in> carrier_direct_lim\<close>] unfolding y_def by auto define z where "z=get_lower_bound (fst x) (fst y)" have z:"z \<in> I" "z \<subseteq> fst x" "z \<subseteq> fst y" and z_alt:"z=get_lower_bound (fst y) (fst x) " proof - have "fst x \<in> I" "fst y \<in> I" using \<open>x \<in> Sigma I \<FF>\<close> \<open>y \<in> Sigma I \<FF>\<close> by auto then show "z \<in> I" "z \<subseteq> fst x" "z \<subseteq> fst y" using get_lower_bound[of "fst x" "fst y",folded z_def] by auto show "z=get_lower_bound (fst y) (fst x) " by (metis (no_types, lifting) Eps_cong get_lower_bound_def z_def) qed interpret xz:ring_homomorphism "(\<rho> (fst x) z)" "(\<FF> (fst x))" "+\<^bsub>fst x\<^esub>" "\<cdot>\<^bsub>fst x\<^esub>" "\<zero>\<^bsub>fst x\<^esub>" "\<one>\<^bsub>fst x\<^esub>" "(\<FF> z)" "+\<^bsub>z\<^esub>" "\<cdot>\<^bsub>z\<^esub>" "\<zero>\<^bsub>z\<^esub>" "\<one>\<^bsub>z\<^esub>" using is_ring_morphism z x subset_of_opens by force interpret yz:ring_homomorphism "(\<rho> (fst y) z)" "(\<FF> (fst y))" "+\<^bsub>fst y\<^esub>" "\<cdot>\<^bsub>fst y\<^esub>" "\<zero>\<^bsub>fst y\<^esub>" "\<one>\<^bsub>fst y\<^esub>" "(\<FF> z)" "+\<^bsub>z\<^esub>" "\<cdot>\<^bsub>z\<^esub>" "\<zero>\<^bsub>z\<^esub>" "\<one>\<^bsub>z\<^esub>" using is_ring_morphism z y subset_of_opens by auto have "add_rel X Y = \<lfloor>z, add_str z (\<rho> (fst x) z (snd x)) (\<rho> (fst y) z (snd y))\<rfloor>" unfolding add_rel_def Let_def by (fold x_def y_def z_def,rule) also have "... = add_rel Y X" unfolding add_rel_def Let_def apply (fold x_def y_def z_alt) using \<open>x \<in> Sigma I \<FF>\<close> \<open>y \<in> Sigma I \<FF>\<close> xz.target.additive.commutative by auto finally show "add_rel X Y = add_rel Y X" . qed show add_assoc:"add_rel (add_rel X Y) Z = add_rel X (add_rel Y Z)" "mult_rel (mult_rel X Y) Z = mult_rel X (mult_rel Y Z)" "mult_rel X (add_rel Y Z) = add_rel (mult_rel X Y) (mult_rel X Z)" "mult_rel (add_rel Y Z) X = add_rel (mult_rel Y X) (mult_rel Z X)" if "X \<in> carrier_direct_lim" "Y \<in> carrier_direct_lim" "Z \<in> carrier_direct_lim" for X Y Z proof - define x where "x=(SOME x. x \<in> X)" define y where "y=(SOME y. y \<in> Y)" define z where "z=(SOME z. z \<in> Z)" have x:"x\<in>X" "x\<in>Sigma I \<FF>" and x_alt:"X = \<lfloor>fst x,snd x\<rfloor>" using rel_carrier_Eps_in[OF \<open>X \<in> carrier_direct_lim\<close>] unfolding x_def by auto have y:"y\<in>Y" "y \<in> Sigma I \<FF>" and y_alt:"Y = \<lfloor>fst y,snd y\<rfloor>" using rel_carrier_Eps_in[OF \<open>Y \<in> carrier_direct_lim\<close>] unfolding y_def by auto have z:"z\<in>Z" "z \<in> Sigma I \<FF>" and z_alt:"Z = \<lfloor>fst z,snd z\<rfloor>" using rel_carrier_Eps_in[OF \<open>Z \<in> carrier_direct_lim\<close>] unfolding z_def by auto obtain w0 where w0:"w0 \<in> I" "w0 \<subseteq> fst x" "w0 \<subseteq> fst y" "w0 \<subseteq> fst z" using obtain_lower_bound_finite[of "{fst x,fst y,fst z}"] x y z by force interpret xw0:ring_homomorphism "\<rho> (fst x) w0" "\<FF> (fst x)" "+\<^bsub>fst x\<^esub>" "\<cdot>\<^bsub>fst x\<^esub>" "\<zero>\<^bsub>fst x\<^esub>" "\<one>\<^bsub>fst x\<^esub>" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" using is_ring_morphism x w0 subset_of_opens by auto interpret yw0:ring_homomorphism "\<rho> (fst y) w0" "\<FF> (fst y)" "+\<^bsub>fst y\<^esub>" "\<cdot>\<^bsub>fst y\<^esub>" "\<zero>\<^bsub>fst y\<^esub>" "\<one>\<^bsub>fst y\<^esub>" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" using is_ring_morphism y w0 subset_of_opens by auto interpret zw0:ring_homomorphism "\<rho> (fst z) w0" "\<FF> (fst z)" "+\<^bsub>fst z\<^esub>" "\<cdot>\<^bsub>fst z\<^esub>" "\<zero>\<^bsub>fst z\<^esub>" "\<one>\<^bsub>fst z\<^esub>" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" using is_ring_morphism z w0 subset_of_opens by auto have "add_rel (add_rel X Y) Z = \<lfloor>w0, +\<^bsub>w0\<^esub> ((+\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) (\<rho> (fst y) w0 (snd y)))) (\<rho> (fst z) w0 (snd z))\<rfloor>" unfolding x_alt y_alt z_alt using x y z w0 subset_of_opens add_rel_class_of by (force simp add: add_rel_class_of) also have "... = \<lfloor>w0, +\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) (+\<^bsub>w0\<^esub> (\<rho> (fst y) w0 (snd y)) (\<rho> (fst z) w0 (snd z)))\<rfloor>" using x(2) xw0.target.additive.associative y(2) z(2) by force also have "... = add_rel X (add_rel Y Z)" unfolding x_alt y_alt z_alt using x y z w0 add_rel_class_of subset_of_opens by force finally show "add_rel (add_rel X Y) Z = add_rel X (add_rel Y Z)" . have "mult_rel (mult_rel X Y) Z = \<lfloor>w0, \<cdot>\<^bsub>w0\<^esub> ((\<cdot>\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) (\<rho> (fst y) w0 (snd y)))) (\<rho> (fst z) w0 (snd z))\<rfloor>" unfolding x_alt y_alt z_alt using x y z w0 mult_rel_class_of subset_of_opens by force also have "... = \<lfloor>w0, \<cdot>\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) (\<cdot>\<^bsub>w0\<^esub> (\<rho> (fst y) w0 (snd y)) (\<rho> (fst z) w0 (snd z)))\<rfloor>" apply (subst xw0.target.multiplicative.associative) using w0 x y z by auto also have "... = mult_rel X (mult_rel Y Z)" unfolding x_alt y_alt z_alt using x y z w0 mult_rel_class_of subset_of_opens by force finally show "mult_rel (mult_rel X Y) Z = mult_rel X (mult_rel Y Z)" . have "mult_rel X (add_rel Y Z) = \<lfloor>w0, \<cdot>\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) (+\<^bsub>w0\<^esub> (\<rho> (fst y) w0 (snd y)) (\<rho> (fst z) w0 (snd z)))\<rfloor>" unfolding x_alt y_alt z_alt using x y z w0 add_rel_class_of mult_rel_class_of subset_of_opens by force also have "... = \<lfloor>w0, +\<^bsub>w0\<^esub> (\<cdot>\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) (\<rho> (fst y) w0 (snd y))) (\<cdot>\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) (\<rho> (fst z) w0 (snd z)))\<rfloor>" apply (subst xw0.target.distributive) using w0 x y z by auto also have "... = add_rel (mult_rel X Y) (mult_rel X Z)" unfolding x_alt y_alt z_alt using x y z w0 add_rel_class_of mult_rel_class_of subset_of_opens by force finally show "mult_rel X (add_rel Y Z) = add_rel (mult_rel X Y) (mult_rel X Z)" . have "mult_rel (add_rel Y Z) X = \<lfloor>w0, \<cdot>\<^bsub>w0\<^esub> (+\<^bsub>w0\<^esub> (\<rho> (fst y) w0 (snd y)) (\<rho> (fst z) w0 (snd z))) (\<rho> (fst x) w0 (snd x))\<rfloor>" unfolding x_alt y_alt z_alt using x y z w0 add_rel_class_of mult_rel_class_of subset_of_opens by force also have "... = \<lfloor>w0, +\<^bsub>w0\<^esub> (\<cdot>\<^bsub>w0\<^esub> (\<rho> (fst y) w0 (snd y)) (\<rho> (fst x) w0 (snd x))) (\<cdot>\<^bsub>w0\<^esub> (\<rho> (fst z) w0 (snd z)) (\<rho> (fst x) w0 (snd x)))\<rfloor>" apply (subst xw0.target.distributive) using w0 x y z by auto also have "... = add_rel (mult_rel Y X) (mult_rel Z X)" unfolding x_alt y_alt z_alt using x y z w0 add_rel_class_of mult_rel_class_of subset_of_opens by force finally show "mult_rel (add_rel Y Z) X = add_rel (mult_rel Y X) (mult_rel Z X)" . qed show add_rel_0':"\<And>a. a \<in> carrier_direct_lim \<Longrightarrow> add_rel a \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor> = a" using add_rel_0 add_rel_commute zero_rel by force interpret Group_Theory.monoid carrier_direct_lim add_rel "\<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor>" apply unfold_locales by (simp_all add: zero_rel add_rel_carrier add_assoc add_rel_0 add_rel_0') show "monoid.invertible carrier_direct_lim add_rel \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor> X" if "X \<in> carrier_direct_lim" for X proof - define x where "x=(SOME x. x \<in> X)" have x:"x\<in>X" "x\<in>Sigma I \<FF>" "fst x\<in>I" and X_alt:"X= \<lfloor>fst x, snd x\<rfloor>" using rel_carrier_Eps_in[OF \<open>X \<in> carrier_direct_lim\<close>] unfolding x_def by auto obtain w0 where w0: "w0 \<in> I" "w0 \<subseteq> U" "w0 \<subseteq> fst x" using has_lower_bound[OF \<open>U\<in>I\<close> \<open>fst x\<in>I\<close>] by blast interpret uw0:ring_homomorphism "\<rho> U w0" "\<FF> U" "+\<^bsub>U\<^esub>" "\<cdot>\<^bsub>U\<^esub>" "\<zero>\<^bsub>U\<^esub>" "\<one>\<^bsub>U\<^esub>" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" using is_ring_morphism \<open>U\<in>I\<close> w0 subset_of_opens by auto interpret xw0:ring_homomorphism "\<rho> (fst x) w0" "\<FF> (fst x)" "+\<^bsub>fst x\<^esub>" "\<cdot>\<^bsub>fst x\<^esub>" "\<zero>\<^bsub>fst x\<^esub>" "\<one>\<^bsub>fst x\<^esub>" "\<FF> w0" "+\<^bsub>w0\<^esub>" "\<cdot>\<^bsub>w0\<^esub>" "\<zero>\<^bsub>w0\<^esub>" "\<one>\<^bsub>w0\<^esub>" using is_ring_morphism \<open>fst x\<in>I\<close> w0 subset_of_opens by auto define Y where "Y=\<lfloor>fst x, xw0.source.additive.inverse (snd x)\<rfloor>" have "add_rel X Y = \<lfloor>w0, +\<^bsub>w0\<^esub> (\<rho> (fst x) w0 (snd x)) (\<rho> (fst x) w0 (xw0.source.additive.inverse (snd x)))\<rfloor>" unfolding X_alt Y_def proof (subst add_rel_class_of) show "(fst x, xw0.source.additive.inverse (snd x)) \<in> Sigma I \<FF>" using x(2) xw0.source.additive.invertible xw0.source.additive.invertible_inverse_closed by force qed (use x w0 in auto) also have "... = \<lfloor>w0, \<zero>\<^bsub>w0\<^esub>\<rfloor>" apply (subst xw0.additive.invertible_image_lemma) subgoal using x(2) xw0.source.additive.invertible by force using x(2) by auto also have "... = \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor>" by (simp add: assms class_of_0_eq w0(1)) finally have "add_rel X Y = \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor>" . moreover have "Y \<in> carrier_direct_lim" using Group_Theory.group_def Y_def carrier_direct_lim_def class_of_def monoid.invertible_inverse_closed x(2) xw0.source.additive.group_axioms xw0.source.additive.invertible by fastforce moreover have "add_rel Y X = \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor>" using \<open>Y \<in> carrier_direct_lim\<close> \<open>add_rel X Y = \<lfloor>U, \<zero>\<^bsub>U\<^esub>\<rfloor>\<close> by (simp add: add_rel_commute that) ultimately show ?thesis unfolding invertible_def[OF that] by auto qed qed (* The canonical function from \<FF> U into lim \<FF> for U \<in> I:*) definition canonical_fun:: "'a set \<Rightarrow> 'b \<Rightarrow> ('a set \<times> 'b) set" where "canonical_fun U x = \<lfloor>U, x\<rfloor>" lemma rel_I1: assumes "s \<in> \<FF> U" "x \<in> \<lfloor>U, s\<rfloor>" "U \<in> I" shows "(U, s) \<sim> x" proof - have Us: "\<lfloor>U, s\<rfloor> \<in> carrier_direct_lim" using assms unfolding carrier_direct_lim_def class_of_def by (simp add: equivalence.Class_in_Partition rel_is_equivalence) then show ?thesis using rel_Class_iff assms by (metis carrier_direct_lim_def class_of_def mem_Sigma_iff rel.Block_self rel.Class_self rel.block_closed) qed lemma rel_I2: assumes "s \<in> \<FF> U" "x \<in> \<lfloor>U, s\<rfloor>" "U \<in> I" shows "(U, s) \<sim> (SOME x. x \<in> \<lfloor>U, s\<rfloor>)" using carrier_direct_lim_def class_of_def rel_carrier_Eps_in(2) rel_carrier_Eps_in(3) assms by fastforce lemma carrier_direct_limE: assumes "X \<in> carrier_direct_lim" obtains U s where "U \<in> I" "s \<in> \<FF> U" "X = \<lfloor>U,s\<rfloor>" using assms carrier_direct_lim_def class_of_def by auto end (* direct_lim *) abbreviation "dlim \<equiv> direct_lim.carrier_direct_lim" subsubsection \<open>Universal property of direct limits\<close> proposition (in direct_lim) universal_property: fixes A:: "'c set" and \<psi>:: "'a set \<Rightarrow> ('b \<Rightarrow> 'c)" and add:: "'c \<Rightarrow> 'c \<Rightarrow> 'c" and mult:: "'c \<Rightarrow> 'c \<Rightarrow> 'c" and zero:: "'c" and one:: "'c" assumes "ring A add mult zero one" and r_hom: "\<And>U. U \<in> I \<Longrightarrow> ring_homomorphism (\<psi> U) (\<FF> U) (+\<^bsub>U\<^esub>) (\<cdot>\<^bsub>U\<^esub>) \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub> A add mult zero one" and eq: "\<And>U V x. \<lbrakk>U \<in> I; V \<in> I; V \<subseteq> U; x \<in> (\<FF> U)\<rbrakk> \<Longrightarrow> (\<psi> V \<circ> \<rho> U V) x = \<psi> U x" shows "\<forall>V\<in>I. \<exists>!u. ring_homomorphism u carrier_direct_lim add_rel mult_rel \<lfloor>V,\<zero>\<^bsub>V\<^esub>\<rfloor> \<lfloor>V,\<one>\<^bsub>V\<^esub>\<rfloor> A add mult zero one \<and> (\<forall>U\<in>I. \<forall>x\<in>(\<FF> U). (u \<circ> canonical_fun U) x = \<psi> U x)" proof fix V assume "V \<in> I" interpret ring_V: ring carrier_direct_lim add_rel mult_rel "\<lfloor>V, \<zero>\<^bsub>V\<^esub>\<rfloor>" "\<lfloor>V, \<one>\<^bsub>V\<^esub>\<rfloor>" using \<open>V \<in> I\<close> direct_lim_is_ring by blast interpret ring_\<psi>V: ring_homomorphism "\<psi> V" "\<FF> V" "+\<^bsub>V\<^esub>" "\<cdot>\<^bsub>V\<^esub>" "\<zero>\<^bsub>V\<^esub>" "\<one>\<^bsub>V\<^esub>" A add mult zero one using \<open>V \<in> I\<close> r_hom by presburger define u where "u \<equiv> \<lambda>X \<in> carrier_direct_lim. let x = (SOME x. x \<in> X) in \<psi> (fst x) (snd x)" \<comment>\<open>The proposition below proves that @{term u} is well defined.\<close> have \<psi>_eqI: "\<psi> x1 x2 = \<psi> y1 y2" if "(x1,x2) \<sim> (y1,y2)" for x1 x2 y1 y2 by (smt (verit, best) Int_subset_iff assms(3) comp_apply fst_conv rel_def snd_conv that) have u_eval: "u \<lfloor>U,s\<rfloor> = \<psi> U s" if "U \<in> I" "s \<in> \<FF> U" for U s proof - have Us: "\<lfloor>U, s\<rfloor> \<in> carrier_direct_lim" using that unfolding carrier_direct_lim_def class_of_def by (simp add: equivalence.Class_in_Partition rel_is_equivalence) with that show ?thesis apply (simp add: u_def Let_def) by (metis \<psi>_eqI prod.exhaust_sel rel_I2 rel_carrier_Eps_in(1)) qed have u_PiE: "u \<in> carrier_direct_lim \<rightarrow>\<^sub>E A" proof fix X assume "X \<in> carrier_direct_lim" then show "u X \<in> A" by (metis carrier_direct_limE map.map_closed r_hom ring_homomorphism_def u_eval) qed (auto simp: u_def) have hom_u: "ring_homomorphism u carrier_direct_lim add_rel mult_rel \<lfloor>V, \<zero>\<^bsub>V\<^esub>\<rfloor> \<lfloor>V, \<one>\<^bsub>V\<^esub>\<rfloor> A add mult zero one" proof have "u (add_rel \<lfloor>U,s\<rfloor> \<lfloor>V,t\<rfloor>) = add (u \<lfloor>U,s\<rfloor>) (u \<lfloor>V,t\<rfloor>)" if "U \<in> I" "V \<in> I" "s \<in> \<FF> U" "t \<in> \<FF> V" for U V s t proof - obtain W where "W \<in> I" and Wsub: "W \<subseteq> U \<inter> V" using assms has_lower_bound by (metis \<open>U \<in> I\<close> \<open>V \<in> I\<close>) interpret ring_\<psi>W: ring_homomorphism "\<psi> W" "\<FF> W" "+\<^bsub>W\<^esub>" "\<cdot>\<^bsub>W\<^esub>" "\<zero>\<^bsub>W\<^esub>" "\<one>\<^bsub>W\<^esub>" A add mult zero one using \<open>W \<in> I\<close> r_hom by presburger have "u (add_rel \<lfloor>U,s\<rfloor> \<lfloor>V,t\<rfloor>) = u (\<lfloor>W, +\<^bsub>W\<^esub> (\<rho> U W s) (\<rho> V W t)\<rfloor>)" using Wsub \<open>W \<in> I\<close> add_rel_class_of that by force also have "\<dots> = \<psi> W (+\<^bsub>W\<^esub> (\<rho> U W s) (\<rho> V W t))" by (metis Wsub \<open>W \<in> I\<close> direct_lim.subset_of_opens direct_lim_axioms is_map_from_is_homomorphism le_infE map.map_closed ring_\<psi>W.source.additive.composition_closed that u_eval) also have "\<dots> = add (\<psi> W ((\<rho> U W s))) (\<psi> W ((\<rho> V W t)))" using that by (meson \<open>W \<in> I\<close> \<open>W \<subseteq> U \<inter> V\<close> inf.bounded_iff is_ring_morphism map.map_closed ring_\<psi>W.additive.commutes_with_composition ring_homomorphism_def subset_of_opens) also have "\<dots> = add (\<psi> U s) (\<psi> V t)" using \<open>W \<in> I\<close> \<open>W \<subseteq> U \<inter> V\<close> eq that by force also have "... = add (u \<lfloor>U,s\<rfloor>) (u \<lfloor>V,t\<rfloor>)" by (simp add: that u_eval) finally show "u (add_rel \<lfloor>U,s\<rfloor> \<lfloor>V,t\<rfloor>) = add (u \<lfloor>U,s\<rfloor>) (u \<lfloor>V,t\<rfloor>)" . qed then show "u (add_rel X Y) = add (u X) (u Y)" if "X \<in> carrier_direct_lim" and "Y \<in> carrier_direct_lim" for X Y by (metis (no_types, lifting) carrier_direct_limE that) show "u \<lfloor>V, \<zero>\<^bsub>V\<^esub>\<rfloor> = zero" using \<open>V \<in> I\<close> ring_\<psi>V.additive.commutes_with_unit ring_\<psi>V.source.additive.unit_closed u_eval by presburger have "u (mult_rel \<lfloor>U,s\<rfloor> \<lfloor>V,t\<rfloor>) = mult (u \<lfloor>U,s\<rfloor>) (u \<lfloor>V,t\<rfloor>)" if "U \<in> I" "V \<in> I" "s \<in> \<FF> U" "t \<in> \<FF> V" for U V s t proof - obtain W where "W \<in> I" and Wsub: "W \<subseteq> U \<inter> V" by (meson \<open>U \<in> I\<close> \<open>V \<in> I\<close> has_lower_bound) interpret ring_\<psi>W: ring_homomorphism "\<psi> W" "\<FF> W" "+\<^bsub>W\<^esub>" "\<cdot>\<^bsub>W\<^esub>" "\<zero>\<^bsub>W\<^esub>" "\<one>\<^bsub>W\<^esub>" A add mult zero one using \<open>W \<in> I\<close> r_hom by presburger have "u (mult_rel \<lfloor>U,s\<rfloor> \<lfloor>V,t\<rfloor>) = u (\<lfloor>W, \<cdot>\<^bsub>W\<^esub> (\<rho> U W s) (\<rho> V W t)\<rfloor>)" using Wsub \<open>W \<in> I\<close> mult_rel_class_of that by force also have "\<dots> = \<psi> W (\<cdot>\<^bsub>W\<^esub> (\<rho> U W s) (\<rho> V W t))" by (metis Wsub \<open>W \<in> I\<close> direct_lim.subset_of_opens direct_lim_axioms is_map_from_is_homomorphism le_infE map.map_closed ring_\<psi>W.source.multiplicative.composition_closed that u_eval) also have "\<dots> = mult (\<psi> W ((\<rho> U W s))) (\<psi> W ((\<rho> V W t)))" by (meson Wsub \<open>W \<in> I\<close> inf.boundedE is_ring_morphism map.map_closed ring_\<psi>W.multiplicative.commutes_with_composition ring_homomorphism_def subset_of_opens that) also have "\<dots> = mult (\<psi> U s) (\<psi> V t)" using Wsub \<open>W \<in> I\<close> eq that by force also have "... = mult (u \<lfloor>U,s\<rfloor>) (u \<lfloor>V,t\<rfloor>)" using that u_eval by presburger finally show "u (mult_rel \<lfloor>U,s\<rfloor> \<lfloor>V,t\<rfloor>) = mult (u \<lfloor>U,s\<rfloor>) (u \<lfloor>V,t\<rfloor>)" . qed then show "u (mult_rel X Y) = mult (u X) (u Y)" if "X \<in> carrier_direct_lim" and "Y \<in> carrier_direct_lim" for X Y by (metis (no_types, lifting) carrier_direct_limE that) show "u (\<lfloor>V, \<one>\<^bsub>V\<^esub>\<rfloor>) = one" by (simp add: \<open>V \<in> I\<close> ring_\<psi>V.multiplicative.commutes_with_unit u_eval) qed (simp add: u_PiE) show "\<exists>!u. ring_homomorphism u carrier_direct_lim add_rel mult_rel \<lfloor>V, \<zero>\<^bsub>V\<^esub>\<rfloor> \<lfloor>V, \<one>\<^bsub>V\<^esub>\<rfloor> A add mult zero one \<and> (\<forall>U\<in>I. \<forall>x\<in>\<FF> U. (u \<circ> canonical_fun U) x = \<psi> U x)" proof show "ring_homomorphism u carrier_direct_lim add_rel mult_rel \<lfloor>V, \<zero>\<^bsub>V\<^esub>\<rfloor> \<lfloor>V, \<one>\<^bsub>V\<^esub>\<rfloor> A add mult zero one \<and> (\<forall>U\<in>I. \<forall>x\<in>\<FF> U. (u \<circ> canonical_fun U) x = \<psi> U x)" by (simp add: canonical_fun_def hom_u u_eval) fix v assume v: "ring_homomorphism v carrier_direct_lim add_rel mult_rel \<lfloor>V, \<zero>\<^bsub>V\<^esub>\<rfloor> \<lfloor>V, \<one>\<^bsub>V\<^esub>\<rfloor> A add mult zero one \<and> (\<forall>U\<in>I. \<forall>x\<in>\<FF> U. (v \<circ> canonical_fun U) x = \<psi> U x)" have "u X = v X" if "X \<in> carrier_direct_lim" for X by (metis v canonical_fun_def carrier_direct_limE comp_apply that u_eval) moreover have "v \<in> carrier_direct_lim \<rightarrow>\<^sub>E A" by (metis v Set_Theory.map_def ring_homomorphism_def) ultimately show "v = u" using PiE_ext u_PiE by blast qed qed subsection \<open>Locally Ringed Spaces\<close> subsubsection \<open>Stalks of a Presheaf\<close> locale stalk = direct_lim + fixes x:: "'a" assumes is_elem: "x \<in> S" and index: "I = {U. is_open U \<and> x \<in> U}" begin (* definition 0.37 *) definition carrier_stalk:: "('a set \<times> 'b) set set" where "carrier_stalk \<equiv> dlim \<FF> \<rho> (neighborhoods x)" lemma neighborhoods_eq:"neighborhoods x = I" unfolding index neighborhoods_def by simp definition add_stalk:: "('a set \<times> 'b) set \<Rightarrow> ('a set \<times> 'b) set \<Rightarrow> ('a set \<times> 'b) set" where "add_stalk \<equiv> add_rel" definition mult_stalk:: "('a set \<times> 'b) set \<Rightarrow> ('a set \<times> 'b) set \<Rightarrow> ('a set \<times> 'b) set" where "mult_stalk \<equiv> mult_rel" definition zero_stalk:: "'a set \<Rightarrow> ('a set \<times> 'b) set" where "zero_stalk V \<equiv> class_of V \<zero>\<^bsub>V\<^esub>" definition one_stalk:: "'a set \<Rightarrow> ('a set \<times> 'b) set" where "one_stalk V \<equiv> class_of V \<one>\<^bsub>V\<^esub>" lemma class_of_in_stalk: assumes "A \<in> (neighborhoods x)" and "z \<in> \<FF> A" shows "class_of A z \<in> carrier_stalk" proof - interpret equivalence "Sigma I \<FF>" "{(x, y). x \<sim> y}" using rel_is_equivalence by blast show ?thesis using assms unfolding carrier_stalk_def neighborhoods_def by (metis (no_types, lifting) carrier_direct_lim_def class_of_def index mem_Sigma_iff natural.map_closed) qed lemma stalk_is_ring: assumes "is_open V" and "x \<in> V" shows "ring carrier_stalk add_stalk mult_stalk (zero_stalk V) (one_stalk V)" proof - interpret r: ring carrier_direct_lim add_rel mult_rel "\<lfloor>V, \<zero>\<^bsub>V\<^esub>\<rfloor>" "\<lfloor>V, \<one>\<^bsub>V\<^esub>\<rfloor>" using assms direct_lim_is_ring index by blast show ?thesis using r.additive.monoid_axioms unfolding zero_stalk_def one_stalk_def add_stalk_def mult_stalk_def carrier_stalk_def using index neighborhoods_def r.ring_axioms by metis qed lemma in_zero_stalk [simp]: assumes "V \<in> I" shows "(V, zero_str V) \<in> zero_stalk V" by (simp add: assms zero_stalk_def class_of_def class_of_0_in equivalence.Class_self rel_is_equivalence) lemma in_one_stalk [simp]: assumes "V \<in> I" shows "(V, one_str V) \<in> one_stalk V" by (simp add: assms one_stalk_def class_of_def class_of_1_in equivalence.Class_self rel_is_equivalence) lemma universal_property_for_stalk: fixes A:: "'c set" and \<psi>:: "'a set \<Rightarrow> ('b \<Rightarrow> 'c)" assumes ringA: "ring A add mult zero one" and hom: "\<And>U. U \<in> neighborhoods x \<Longrightarrow> ring_homomorphism (\<psi> U) (\<FF> U) (+\<^bsub>U\<^esub>) (\<cdot>\<^bsub>U\<^esub>) \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub> A add mult zero one" and eq: "\<And>U V s. \<lbrakk>U \<in> neighborhoods x; V \<in> neighborhoods x; V\<subseteq>U; s \<in> \<FF> U\<rbrakk> \<Longrightarrow> (\<psi> V \<circ> \<rho> U V) s = \<psi> U s" shows "\<forall>V\<in>(neighborhoods x). \<exists>!u. ring_homomorphism u carrier_stalk add_stalk mult_stalk (zero_stalk V) (one_stalk V) A add mult zero one \<and> (\<forall>U\<in>(neighborhoods x). \<forall>s\<in>(\<FF> U). (u \<circ> canonical_fun U) s = \<psi> U s)" proof - note neighborhoods_eq [simp] have "\<forall>V\<in>I. \<exists>!u. ring_homomorphism u carrier_direct_lim add_rel mult_rel \<lfloor>V, \<zero>\<^bsub>V\<^esub>\<rfloor> \<lfloor>V, \<one>\<^bsub>V\<^esub>\<rfloor> A add mult zero one \<and> (\<forall>U\<in>I. \<forall>x\<in>\<FF> U. (u \<circ> canonical_fun U) x = \<psi> U x)" apply (rule universal_property[OF ringA hom]) using eq by simp_all then show ?thesis unfolding carrier_stalk_def add_stalk_def mult_stalk_def zero_stalk_def one_stalk_def by simp qed end (* stalk *) sublocale stalk \<subseteq> direct_lim by (simp add: direct_lim_axioms) subsubsection \<open>Maximal Ideals\<close> (* definition 0.38 *) locale max_ideal = comm_ring R "(+)" "(\<cdot>)" "\<zero>" "\<one>" + ideal I R "(+)" "(\<cdot>)" "\<zero>" "\<one>" for R and I and addition (infixl "+" 65) and multiplication (infixl "\<cdot>" 70) and zero ("\<zero>") and unit ("\<one>") + assumes neq_ring: "I \<noteq> R" and is_max: "\<And>\<aa>. ideal \<aa> R (+) (\<cdot>) \<zero> \<one> \<Longrightarrow> \<aa> \<noteq> R \<Longrightarrow> I \<subseteq> \<aa> \<Longrightarrow> I = \<aa>" begin lemma psubset_ring: "I \<subset> R" using neq_ring by blast lemma shows "\<not> (\<exists>\<aa>. ideal \<aa> R (+) (\<cdot>) \<zero> \<one> \<and> \<aa> \<noteq> R \<and> I \<subset> \<aa>)" using is_max by blast text \<open>A maximal ideal is prime\<close> proposition is_pr_ideal: "pr_ideal R I (+) (\<cdot>) \<zero> \<one>" proof show "I \<noteq> R" using neq_ring by fastforce fix x y assume "x \<in> R" "y \<in> R" and dot: "x \<cdot> y \<in> I" then show "x \<in> I \<or> y \<in> I" proof- have "False" if "x \<notin> I" "y \<notin> I" proof- define J where "J \<equiv> {i + r \<cdot> x |i r. i \<in> I \<and> r \<in> R}" have "J \<subseteq> R" using \<open>x \<in> R\<close> by (auto simp: J_def) have "x \<in> J" apply (simp add: J_def) by (metis \<open>x \<in> R\<close> additive.left_unit additive.sub_unit_closed multiplicative.left_unit multiplicative.unit_closed) interpret monJ: monoid J "(+)" \<zero> proof have "\<zero> = \<zero> + \<zero> \<cdot> x" by (simp add: \<open>x \<in> R\<close>) then show "\<zero> \<in> J" by (auto simp: J_def) next fix a b assume "a \<in> J" and "b \<in> J" then obtain ia ra ib rb where a: "a = ia + ra \<cdot> x" "ia \<in> I" "ra \<in> R" and b: "b = ib + rb \<cdot> x" "ib \<in> I" "rb \<in> R" by (auto simp: J_def) then have "ia + ra \<cdot> x + (ib + rb \<cdot> x) = ia + ib + (ra + rb) \<cdot> x" by (smt (verit, del_insts) \<open>x \<in> R\<close> additive.associative additive.commutative additive.composition_closed additive.submonoid_axioms distributive(2) multiplicative.composition_closed submonoid.sub) with a b show "a + b \<in> J" by (auto simp add: J_def) next fix a b c assume "a \<in> J" and "b \<in> J" and "c \<in> J" then show "a + b + c = a + (b + c)" by (meson \<open>J \<subseteq> R\<close> additive.associative subsetD) next fix a assume "a \<in> J" then show "\<zero> + a = a" "a + \<zero> = a" using \<open>J \<subseteq> R\<close> additive.left_unit additive.right_unit by blast+ qed interpret idJ: ideal J R "(+)" "(\<cdot>)" \<zero> \<one> proof fix u assume "u \<in> J" then obtain i r where "u = i + r \<cdot> x" "i \<in> I" "r \<in> R" by (auto simp: J_def) then have "-u = -i + (-r) \<cdot> x" by (simp add: \<open>x \<in> R\<close> additive.commutative additive.inverse_composition_commute local.left_minus) with \<open>i \<in> I\<close> \<open>r \<in> R\<close> have "-u \<in> J" by (auto simp: J_def) with \<open>u \<in> J\<close> show "monoid.invertible J (+) \<zero> u" using monoid.invertibleI [where v = "-u"] by (simp add: \<open>u \<in> J\<close> monJ.monoid_axioms \<open>i \<in> I\<close> \<open>r \<in> R\<close> \<open>u = i + r \<cdot> x\<close> \<open>x \<in> R\<close>) next fix a b assume "a \<in> R" and "b \<in> J" then obtain i r where ir: "b = i + r \<cdot> x" "i \<in> I" "r \<in> R" by (auto simp: J_def) then have "a \<cdot> (i + r \<cdot> x) = a \<cdot> i + a \<cdot> r \<cdot> x" by (simp add: \<open>a \<in> R\<close> \<open>x \<in> R\<close> distributive(1) multiplicative.associative) then show "a \<cdot> b \<in> J" using \<open>a \<in> R\<close> ideal(1) ir by (force simp add: J_def) have "b \<cdot> a = i \<cdot> a + r \<cdot> a \<cdot> x" by (simp add: \<open>a \<in> R\<close> \<open>x \<in> R\<close> comm_mult distributive(1) ir mult_left_assoc) then show "b \<cdot> a \<in> J" by (metis \<open>J \<subseteq> R\<close> \<open>a \<cdot> b \<in> J\<close> \<open>a \<in> R\<close> \<open>b \<in> J\<close> comm_mult subsetD) qed (auto simp: \<open>J \<subseteq> R\<close>) have "I \<subset> J" proof show "I \<subseteq> J" unfolding J_def apply clarify by (metis \<open>x \<in> R\<close> additive.sub.right_unit additive.unit_closed left_zero) show "I \<noteq> J" using \<open>x \<in> J\<close> \<open>x \<notin> I\<close> by blast qed hence "J = R" using idJ.ideal_axioms is_max by auto hence "\<one> \<in> J" by fastforce then obtain a r where "a \<in> I" "r \<in> R" "\<one> = a + r\<cdot>x" unfolding J_def by blast then have "y = (a + r\<cdot>x) \<cdot> y" using \<open>y \<in> R\<close> multiplicative.left_unit by presburger also have "\<dots> = a \<cdot> y + r\<cdot>x\<cdot>y" by (simp add: \<open>a \<in> I\<close> \<open>r \<in> R\<close> \<open>x \<in> R\<close> \<open>y \<in> R\<close> distributive(2)) also have "\<dots> \<in> I" by (simp add: \<open>a \<in> I\<close> \<open>r \<in> R\<close> \<open>x \<in> R\<close> \<open>y \<in> R\<close> dot ideal multiplicative.associative) finally have "y \<in> I" . thus ?thesis using that(2) by auto qed thus ?thesis by auto qed qed end (* locale max_ideal *) subsubsection \<open>Maximal Left Ideals\<close> locale lideal = subgroup_of_additive_group_of_ring + assumes lideal: "\<lbrakk> r \<in> R; a \<in> I \<rbrakk> \<Longrightarrow> r \<cdot> a \<in> I" begin lemma has_one_imp_equal: assumes "\<one> \<in> I" shows "I = R" by (metis assms lideal subset multiplicative.right_unit subsetI subset_antisym) end lemma (in comm_ring) ideal_iff_lideal: "ideal I R (+) (\<cdot>) \<zero> \<one> \<longleftrightarrow> lideal I R (+) (\<cdot>) \<zero> \<one>" (is "?lhs = ?rhs") proof assume ?lhs then interpret I: ideal I R "(+)" "(\<cdot>)" \<zero> \<one> . show ?rhs proof qed (use I.ideal in presburger) next assume ?rhs then interpret I: lideal I R "(+)" "(\<cdot>)" \<zero> \<one> . show ?lhs proof fix r a assume "r \<in> R" "a \<in> I" then show "r \<cdot> a \<in> I" using I.lideal by blast then show "a \<cdot> r \<in> I" by (simp add: \<open>a \<in> I\<close> \<open>r \<in> R\<close> comm_mult) qed qed locale max_lideal = lideal + assumes neq_ring: "I \<noteq> R" and is_max: "\<And>\<aa>. lideal \<aa> R (+) (\<cdot>) \<zero> \<one> \<Longrightarrow> \<aa> \<noteq> R \<Longrightarrow> I \<subseteq> \<aa> \<Longrightarrow> I = \<aa>" (**WHY ARE THE ARGUMENT ORDERS OF max_ideal vs max_lideal INCONSISTENT?**) lemma (in comm_ring) max_ideal_iff_max_lideal: "max_ideal R I (+) (\<cdot>) \<zero> \<one> \<longleftrightarrow> max_lideal I R (+) (\<cdot>) \<zero> \<one>" (is "?lhs = ?rhs") proof assume ?lhs then interpret I: max_ideal R I "(+)" "(\<cdot>)" \<zero> \<one> . show ?rhs proof intro_locales show "lideal_axioms I R (\<cdot>)" by (simp add: I.ideal(1) lideal_axioms.intro) show "max_lideal_axioms I R (+) (\<cdot>) \<zero> \<one>" by (simp add: I.is_max I.neq_ring ideal_iff_lideal max_lideal_axioms.intro) qed next assume ?rhs then interpret I: max_lideal I R "(+)" "(\<cdot>)" \<zero> \<one> . show ?lhs proof intro_locales show "ideal_axioms I R (\<cdot>)" by (meson I.lideal_axioms ideal_def ideal_iff_lideal) show "max_ideal_axioms R I (+) (\<cdot>) \<zero> \<one>" by (meson I.is_max I.neq_ring ideal_iff_lideal max_ideal_axioms.intro) qed qed subsubsection \<open>Local Rings\<close> (* definition 0.39 *) locale local_ring = ring + assumes is_unique: "\<And>I J. max_lideal I R (+) (\<cdot>) \<zero> \<one> \<Longrightarrow> max_lideal J R (+) (\<cdot>) \<zero> \<one> \<Longrightarrow> I = J" and has_max_lideal: "\<exists>\<ww>. max_lideal \<ww> R (+) (\<cdot>) \<zero> \<one>" (*Can this be proved from the analogous result for left, right ideals?*) lemma im_of_ideal_is_ideal: assumes I: "ideal I A addA multA zeroA oneA" and f: "ring_epimorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "ideal (f ` I) B addB multB zeroB oneB" proof - interpret IA: ideal I A addA multA zeroA oneA using I by blast interpret fepi: ring_epimorphism f A addA multA zeroA oneA B addB multB zeroB oneB using f by force show ?thesis proof intro_locales show sma: "submonoid_axioms (f ` I) B addB zeroB" proof show "f ` I \<subseteq> B" by blast have "zeroA \<in> I" by simp then show "zeroB \<in> f ` I" using fepi.additive.commutes_with_unit by blast next fix b1 b2 assume "b1 \<in> f ` I" and "b2 \<in> f ` I" then show "addB b1 b2 \<in> f ` I" unfolding image_iff by (metis IA.additive.sub IA.additive.sub_composition_closed fepi.additive.commutes_with_composition) qed show "Group_Theory.monoid (f ` I) addB zeroB" proof fix a b assume "a \<in> f ` I" "b \<in> f ` I" then show "addB a b \<in> f ` I" by (meson sma submonoid_axioms_def) next show "zeroB \<in> f ` I" using fepi.additive.commutes_with_unit by blast qed auto show "Group_Theory.group_axioms (f ` I) addB zeroB" proof fix b assume "b \<in> f ` I" then obtain i where "b = f i" "i \<in> I" by blast then obtain j where "addA i j = zeroA" "j \<in> I" using IA.additive.sub.invertible_right_inverse by blast then show "monoid.invertible (f ` I) addB zeroB b" by (metis IA.additive.commutative IA.additive.sub \<open>Group_Theory.monoid (f ` I) addB zeroB\<close> \<open>b = f i\<close> \<open>i \<in> I\<close> fepi.additive.commutes_with_composition fepi.additive.commutes_with_unit image_eqI monoid.invertibleI) qed show "ideal_axioms (f ` I) B multB" proof fix b fi assume "b \<in> B" and "fi \<in> f ` I" then obtain i where i: "fi = f i" "i \<in> I" by blast obtain a where a: "a \<in> A" "f a = b" using \<open>b \<in> B\<close> fepi.surjective by blast then show "multB b fi \<in> f ` I" by (metis IA.additive.submonoid_axioms IA.ideal(1) \<open>fi = f i\<close> \<open>i \<in> I\<close> fepi.multiplicative.commutes_with_composition image_iff submonoid.sub) then show "multB fi b \<in> f ` I" by (metis IA.additive.sub IA.ideal(2) a i fepi.multiplicative.commutes_with_composition imageI) qed qed qed lemma im_of_lideal_is_lideal: assumes I: "lideal I A addA multA zeroA oneA" and f: "ring_epimorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "lideal (f ` I) B addB multB zeroB oneB" proof - interpret IA: lideal I A addA multA zeroA oneA using I by blast interpret fepi: ring_epimorphism f A addA multA zeroA oneA B addB multB zeroB oneB using f by force show ?thesis proof intro_locales show sma: "submonoid_axioms (f ` I) B addB zeroB" proof show "f ` I \<subseteq> B" by blast have "zeroA \<in> I" by simp then show "zeroB \<in> f ` I" using fepi.additive.commutes_with_unit by blast next fix b1 b2 assume "b1 \<in> f ` I" and "b2 \<in> f ` I" then show "addB b1 b2 \<in> f ` I" unfolding image_iff by (metis IA.additive.sub IA.additive.sub_composition_closed fepi.additive.commutes_with_composition) qed show "Group_Theory.monoid (f ` I) addB zeroB" proof fix a b assume "a \<in> f ` I" "b \<in> f ` I" then show "addB a b \<in> f ` I" by (meson sma submonoid_axioms_def) next show "zeroB \<in> f ` I" using fepi.additive.commutes_with_unit by blast qed auto show "Group_Theory.group_axioms (f ` I) addB zeroB" proof fix b assume "b \<in> f ` I" then obtain i where "b = f i" "i \<in> I" by blast then obtain j where "addA i j = zeroA" "j \<in> I" using IA.additive.sub.invertible_right_inverse by blast then show "monoid.invertible (f ` I) addB zeroB b" by (metis IA.additive.commutative IA.additive.sub \<open>Group_Theory.monoid (f ` I) addB zeroB\<close> \<open>b = f i\<close> \<open>i \<in> I\<close> fepi.additive.commutes_with_composition fepi.additive.commutes_with_unit image_eqI monoid.invertibleI) qed show "lideal_axioms (f ` I) B multB" proof fix b fi assume "b \<in> B" and "fi \<in> f ` I" then obtain i where i: "fi = f i" "i \<in> I" by blast obtain a where a: "a \<in> A" "f a = b" using \<open>b \<in> B\<close> fepi.surjective by blast then show "multB b fi \<in> f ` I" by (metis IA.additive.submonoid_axioms IA.lideal(1) \<open>fi = f i\<close> \<open>i \<in> I\<close> fepi.multiplicative.commutes_with_composition image_iff submonoid.sub) qed qed qed lemma im_of_max_lideal_is_max: assumes I: "max_lideal I A addA multA zeroA oneA" and f: "ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "max_lideal (f ` I) B addB multB zeroB oneB" proof - interpret maxI: max_lideal I A addA multA zeroA oneA using I by blast interpret fiso: ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB using f by force interpret fIB: lideal "f ` I" B addB multB zeroB oneB proof intro_locales show "submonoid_axioms (f ` I) B addB zeroB" proof show "addB a b \<in> f ` I" if "a \<in> f ` I" "b \<in> f ` I" for a b using that by (clarsimp simp: image_iff) (metis fiso.additive.commutes_with_composition maxI.additive.sub maxI.additive.sub_composition_closed) qed (use fiso.additive.commutes_with_unit in auto) then show "Group_Theory.monoid (f ` I) addB zeroB" using fiso.target.additive.monoid_axioms unfolding submonoid_axioms_def monoid_def by (meson subsetD) then show "Group_Theory.group_axioms (f ` I) addB zeroB" apply (clarsimp simp: Group_Theory.group_axioms_def image_iff monoid.invertible_def) by (metis fiso.additive.commutes_with_composition fiso.additive.commutes_with_unit maxI.additive.sub maxI.additive.sub.invertible maxI.additive.sub.invertible_def) have "\<And>r x. \<lbrakk>r \<in> B; x \<in> I\<rbrakk> \<Longrightarrow> \<exists>xa\<in>I. multB r (f x) = f xa" by (metis (no_types, lifting) fiso.multiplicative.commutes_with_composition fiso.surjective image_iff maxI.additive.sub maxI.lideal) then show "lideal_axioms (f ` I) B multB" by (force intro!: lideal_axioms.intro) qed show ?thesis proof unfold_locales show "f ` I \<noteq> B" using maxI.neq_ring fiso.bijective maxI.additive.submonoid_axioms unfolding submonoid_axioms_def submonoid_def by (metis bij_betw_imp_inj_on fiso.surjective inj_on_image_eq_iff subset_iff) next fix J assume "lideal J B addB multB zeroB oneB" and "J \<noteq> B" and fim: "f ` I \<subseteq> J" then interpret JB: lideal J B addB multB zeroB oneB by blast have \<section>: "lideal (f \<^sup>\<inverse> A J) A addA multA zeroA oneA" proof intro_locales show sma: "submonoid_axioms (f \<^sup>\<inverse> A J) A addA zeroA" proof show "addA a b \<in> f \<^sup>\<inverse> A J" if "a \<in> f \<^sup>\<inverse> A J" and "b \<in> f \<^sup>\<inverse> A J" for a b using that apply clarsimp using JB.additive.sub_composition_closed fiso.additive.commutes_with_composition by presburger qed blast+ show "Group_Theory.monoid (f \<^sup>\<inverse> A J) addA zeroA" by (smt (verit, ccfv_threshold) Group_Theory.monoid.intro IntD2 sma maxI.additive.associative maxI.additive.left_unit maxI.additive.right_unit submonoid_axioms_def) show "Group_Theory.group_axioms (f \<^sup>\<inverse> A J) addA zeroA" proof fix x assume "x \<in> f \<^sup>\<inverse> A J" then show "monoid.invertible (f \<^sup>\<inverse> A J) addA zeroA x" apply clarify by (smt (verit, best) JB.additive.sub.invertible JB.additive.submonoid_inverse_closed IntI \<open>Group_Theory.monoid (f \<^sup>\<inverse> A J) addA zeroA\<close> fiso.additive.invertible_commutes_with_inverse maxI.additive.inverse_equality maxI.additive.invertible maxI.additive.invertibleE monoid.invertible_def vimageI) qed show "lideal_axioms (f \<^sup>\<inverse> A J) A multA" proof fix a j assume \<section>: "a \<in> A" "j \<in> f \<^sup>\<inverse> A J" then show "multA a j \<in> f \<^sup>\<inverse> A J" using JB.lideal(1) fiso.map_closed fiso.multiplicative.commutes_with_composition by simp qed qed have "I = f \<^sup>\<inverse> A J" proof (rule maxI.is_max [OF \<section>]) show "f \<^sup>\<inverse> A J \<noteq> A" using JB.additive.sub \<open>J \<noteq> B\<close> fiso.surjective by blast show "I \<subseteq> f \<^sup>\<inverse> A J" by (meson fim image_subset_iff_subset_vimage inf_greatest maxI.additive.sub subset_iff) qed then have "J \<subseteq> f ` I" using JB.additive.sub fiso.surjective by blast with fim show "f ` I = J" .. qed qed lemma im_of_max_ideal_is_max: assumes I: "max_ideal A I addA multA zeroA oneA" and f: "ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "max_ideal B (f ` I) addB multB zeroB oneB" proof - interpret maxI: max_ideal A I addA multA zeroA oneA using I by blast interpret fiso: ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB using f by force interpret fIB: ideal "f ` I" B addB multB zeroB oneB using maxI.ideal_axioms fiso.ring_homomorphism_axioms by (meson fiso.ring_epimorphism_axioms im_of_ideal_is_ideal) show ?thesis proof intro_locales show "comm_ring_axioms B multB" proof fix b1 b2 assume "b1 \<in> B" and "b2 \<in> B" then obtain a1 a2 where a1: "a1 \<in> A" "f a1 = b1" and a2: "a2 \<in> A" "f a2 = b2" using fiso.surjective by blast then have "multA a1 a2 = multA a2 a1" using maxI.comm_mult by presburger then show "multB b1 b2 = multB b2 b1" by (metis a1 a2 fiso.multiplicative.commutes_with_composition) qed show "max_ideal_axioms B (f ` I) addB multB zeroB oneB" proof obtain i where "i \<in> A" "i \<notin> I" using maxI.neq_ring by blast then have "f i \<notin> f ` I" unfolding image_iff by (metis fiso.injective inj_on_def maxI.additive.sub) then show "f ` I \<noteq> B" using \<open>i \<in> A\<close> fiso.map_closed by blast next fix J assume "ideal J B addB multB zeroB oneB" and "J \<noteq> B" and fim: "f ` I \<subseteq> J" then interpret JB: ideal J B addB multB zeroB oneB by blast have \<section>: "ideal (f \<^sup>\<inverse> A J) A addA multA zeroA oneA" proof intro_locales show sma: "submonoid_axioms (f \<^sup>\<inverse> A J) A addA zeroA" proof show "addA a b \<in> f \<^sup>\<inverse> A J" if "a \<in> f \<^sup>\<inverse> A J" and "b \<in> f \<^sup>\<inverse> A J" for a b using that apply clarsimp using JB.additive.sub_composition_closed fiso.additive.commutes_with_composition by presburger qed blast+ show "Group_Theory.monoid (f \<^sup>\<inverse> A J) addA zeroA" by (smt (verit, ccfv_threshold) Group_Theory.monoid.intro IntD2 sma maxI.additive.associative maxI.additive.left_unit maxI.additive.right_unit submonoid_axioms_def) show "Group_Theory.group_axioms (f \<^sup>\<inverse> A J) addA zeroA" proof fix x assume "x \<in> f \<^sup>\<inverse> A J" then show "monoid.invertible (f \<^sup>\<inverse> A J) addA zeroA x" apply clarify by (smt (verit, best) JB.additive.sub.invertible JB.additive.submonoid_inverse_closed IntI \<open>Group_Theory.monoid (f \<^sup>\<inverse> A J) addA zeroA\<close> fiso.additive.invertible_commutes_with_inverse maxI.additive.inverse_equality maxI.additive.invertible maxI.additive.invertibleE monoid.invertible_def vimageI) qed show "ideal_axioms (f \<^sup>\<inverse> A J) A multA" proof fix a j assume \<section>: "a \<in> A" "j \<in> f \<^sup>\<inverse> A J" then show "multA a j \<in> f \<^sup>\<inverse> A J" using JB.ideal(1) fiso.map_closed fiso.multiplicative.commutes_with_composition by simp then show "multA j a \<in> f \<^sup>\<inverse> A J" by (metis Int_iff \<section> maxI.comm_mult) qed qed have "I = f \<^sup>\<inverse> A J" by (metis "\<section>" JB.additive.sub \<open>J \<noteq> B\<close> fim fiso.surjective image_subset_iff_subset_vimage le_inf_iff maxI.is_max maxI.psubset_ring psubsetE subsetI subset_antisym) then show "f ` I = J" using JB.additive.sub fiso.surjective by blast qed qed qed lemma preim_of_ideal_is_ideal: fixes f :: "'a\<Rightarrow>'b" assumes J: "ideal J B addB multB zeroB oneB" and "ring_homomorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "ideal (f\<^sup>\<inverse> A J) A addA multA zeroA oneA" proof - interpret JB: ideal J B addB multB zeroB oneB using J by blast interpret f: ring_homomorphism f A addA multA zeroA oneA B addB multB zeroB oneB using assms by force interpret preB: ring "f \<^sup>\<inverse> A B" addA multA zeroA oneA using f.ring_preimage by blast show ?thesis proof intro_locales show "submonoid_axioms (f \<^sup>\<inverse> A J) A addA zeroA" by (auto simp add: submonoid_axioms_def f.additive.commutes_with_composition f.additive.commutes_with_unit) then show grp_fAJ: "Group_Theory.monoid (f \<^sup>\<inverse> A J) addA zeroA" by (auto simp: submonoid_axioms_def Group_Theory.monoid_def) show "Group_Theory.group_axioms (f \<^sup>\<inverse> A J) addA zeroA" unfolding group_def proof fix x assume x: "x \<in> f \<^sup>\<inverse> A J" then have "f x \<in> J" "x \<in> A" by auto then obtain v where "f v \<in> J \<and> v \<in> A \<and> addA x v = zeroA" by (metis JB.additive.sub.invertible JB.additive.submonoid_inverse_closed f.additive.invertible_commutes_with_inverse f.source.additive.invertible f.source.additive.invertible_inverse_closed f.source.additive.invertible_right_inverse) then show "monoid.invertible (f \<^sup>\<inverse> A J) addA zeroA x" by (metis Int_iff f.source.additive.commutative grp_fAJ monoid.invertibleI vimageI x) qed show "ideal_axioms (f \<^sup>\<inverse> A J) A multA" proof fix a j assume \<section>: "a \<in> A" "j \<in> f \<^sup>\<inverse> A J" then show "multA j a \<in> f \<^sup>\<inverse> A J" "multA a j \<in> f \<^sup>\<inverse> A J" using JB.ideal f.map_closed f.multiplicative.commutes_with_composition by force+ qed qed qed lemma preim_of_max_ideal_is_max: fixes f:: "'a \<Rightarrow> 'b" assumes J: "max_ideal B J addB multB zeroB oneB" and f: "ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "max_ideal A (f\<^sup>\<inverse> A J) addA multA zeroA oneA" proof - interpret maxJ: max_ideal B J addB multB zeroB oneB using J by blast interpret fiso: ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB using f by force interpret fAJ: ideal "f\<^sup>\<inverse> A J" A addA multA zeroA oneA using maxJ.ideal_axioms fiso.ring_homomorphism_axioms by (blast intro: preim_of_ideal_is_ideal) show ?thesis proof intro_locales show "comm_ring_axioms A multA" proof fix a b assume "a \<in> A" and "b \<in> A" then have "multB (f a) (f b) = multB (f b) (f a)" using fiso.map_closed maxJ.comm_mult by presburger then show "multA a b = multA b a" by (metis bij_betw_iff_bijections \<open>a \<in> A\<close> \<open>b \<in> A\<close> fiso.bijective fiso.multiplicative.commutes_with_composition fiso.source.multiplicative.composition_closed) qed show "max_ideal_axioms A (f \<^sup>\<inverse> A J) addA multA zeroA oneA" proof show "f \<^sup>\<inverse> A J \<noteq> A" using fiso.surjective maxJ.additive.sub maxJ.neq_ring by blast fix I assume "ideal I A addA multA zeroA oneA" and "I \<noteq> A" and "f \<^sup>\<inverse> A J \<subseteq> I" then interpret IA: ideal I A addA multA zeroA oneA by blast have mon_fI: "Group_Theory.monoid (f ` I) addB zeroB" proof fix a b assume "a \<in> f ` I" "b \<in> f ` I" then show "addB a b \<in> f ` I" unfolding image_iff by (metis IA.additive.sub IA.additive.sub_composition_closed fiso.additive.commutes_with_composition) next show "zeroB \<in> f ` I" using fiso.additive.commutes_with_unit by blast qed blast+ have ideal_fI: "ideal (f ` I) B addB multB zeroB oneB" proof show "f ` I \<subseteq> B" by blast show "zeroB \<in> f ` I" using fiso.additive.commutes_with_unit by blast next fix a b assume "a \<in> f ` I" and "b \<in> f ` I" then show "addB a b \<in> f ` I" unfolding image_iff by (metis IA.additive.sub IA.additive.sub_composition_closed fiso.additive.commutes_with_composition) next fix b assume "b \<in> f ` I" then obtain i where i: "b = f i" "i \<in> I" by blast then obtain j where "addA i j = zeroA" "j \<in> I" by (meson IA.additive.sub.invertible IA.additive.sub.invertibleE) then have "addB b (f j) = zeroB" by (metis IA.additive.sub i fiso.additive.commutes_with_composition fiso.additive.commutes_with_unit) then show "monoid.invertible (f ` I) addB zeroB b" by (metis IA.additive.sub i \<open>j \<in> I\<close> fiso.map_closed imageI maxJ.additive.commutative mon_fI monoid.invertibleI) next fix a b assume "a \<in> B" and "b \<in> f ` I" with IA.ideal show "multB a b \<in> f ` I" "multB b a \<in> f ` I" by (smt (verit, best) IA.additive.sub fiso.multiplicative.commutes_with_composition fiso.surjective image_iff)+ qed blast+ have "J = f ` I" proof (rule maxJ.is_max [OF ideal_fI]) show "f ` I \<noteq> B" by (metis IA.additive.sub \<open>I \<noteq> A\<close> fiso.injective fiso.surjective inj_on_image_eq_iff subsetI) show "J \<subseteq> f ` I" unfolding image_def apply clarify by (smt (verit, ccfv_threshold) Int_iff \<open>f \<^sup>\<inverse> A J \<subseteq> I\<close> fiso.surjective imageE maxJ.additive.sub subset_eq vimageI) qed then show "f \<^sup>\<inverse> A J = I" using \<open>f \<^sup>\<inverse> A J \<subseteq> I\<close> by blast qed qed qed lemma preim_of_lideal_is_lideal: assumes "lideal I B addB multB zeroB oneB" and "ring_homomorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "lideal (f \<^sup>\<inverse> A I) (f \<^sup>\<inverse> A B) addA multA zeroA oneA" proof - interpret A: ring A addA multA zeroA oneA by (meson assms ring_homomorphism_def) interpret B: ring B addB multB zeroB oneB by (meson assms ring_homomorphism_def) interpret f: ring_homomorphism f A addA multA zeroA oneA B addB multB zeroB oneB using assms by blast interpret preB: ring "f \<^sup>\<inverse> A B" addA multA zeroA oneA using f.ring_preimage by blast interpret IB: lideal I B addB multB zeroB oneB by (simp add: assms) show ?thesis proof intro_locales show "submonoid_axioms (f \<^sup>\<inverse> A I) (f \<^sup>\<inverse> A B) addA zeroA" by (auto simp add: submonoid_axioms_def f.additive.commutes_with_composition f.additive.commutes_with_unit) have "(A.additive.inverse u) \<in> f \<^sup>\<inverse> A I" if "f u \<in> I" and "u \<in> A" for u proof - have "f (A.additive.inverse u) = B.additive.inverse (f u)" using A.additive.invertible f.additive.invertible_commutes_with_inverse that by presburger then show ?thesis using A.additive.invertible_inverse_closed that by blast qed moreover have "addA (A.additive.inverse u) u = zeroA" "addA u (A.additive.inverse u) = zeroA" if "u \<in> A" for u by (auto simp add: that) moreover show "Group_Theory.monoid (f \<^sup>\<inverse> A I) addA zeroA" by (auto simp: monoid_def f.additive.commutes_with_composition f.additive.commutes_with_unit) ultimately show "Group_Theory.group_axioms (f \<^sup>\<inverse> A I) addA zeroA" unfolding group_axioms_def by (metis IntE monoid.invertibleI vimage_eq) show "lideal_axioms (f \<^sup>\<inverse> A I) (f \<^sup>\<inverse> A B) multA" unfolding lideal_axioms_def using IB.lideal f.map_closed f.multiplicative.commutes_with_composition by force qed qed lemma preim_of_max_lideal_is_max: assumes "max_lideal I B addB multB zeroB oneB" and "ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "max_lideal (f \<^sup>\<inverse> A I) (f \<^sup>\<inverse> A B) addA multA zeroA oneA" proof - interpret f: ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB using assms by blast interpret MI: max_lideal I B addB multB zeroB oneB by (simp add: assms) interpret pre: lideal "f \<^sup>\<inverse> A I" "f \<^sup>\<inverse> A B" addA multA zeroA oneA by (meson preim_of_lideal_is_lideal MI.lideal_axioms f.ring_homomorphism_axioms) show ?thesis proof intro_locales show "max_lideal_axioms (f \<^sup>\<inverse> A I) (f \<^sup>\<inverse> A B) addA multA zeroA oneA" proof show "f \<^sup>\<inverse> A I \<noteq> f \<^sup>\<inverse> A B" using MI.neq_ring MI.subset f.surjective by blast fix \<aa> assume "lideal \<aa> (f \<^sup>\<inverse> A B) addA multA zeroA oneA" and "\<aa> \<noteq> f \<^sup>\<inverse> A B" and "f \<^sup>\<inverse> A I \<subseteq> \<aa>" then interpret lideal \<aa> "f \<^sup>\<inverse> A B" addA multA zeroA oneA by metis have "f ` \<aa> \<noteq> B" by (metis Int_absorb1 \<open>\<aa> \<noteq> f \<^sup>\<inverse> A B\<close> f.injective f.surjective image_subset_iff_subset_vimage inj_on_image_eq_iff subset subset_iff) moreover have "I \<subseteq> f ` \<aa>" by (smt (verit, ccfv_threshold) Int_iff MI.subset \<open>f \<^sup>\<inverse> A I \<subseteq> \<aa>\<close> f.surjective image_iff subset_iff vimageI) moreover have "lideal (f ` \<aa>) B addB multB zeroB oneB" by (metis f.multiplicative.image.subset f.ring_epimorphism_axioms im_of_lideal_is_lideal image_subset_iff_subset_vimage inf.orderE inf_sup_aci(1) lideal_axioms) ultimately show "f \<^sup>\<inverse> A I = \<aa>" by (metis MI.is_max \<open>f \<^sup>\<inverse> A I \<subseteq> \<aa>\<close> image_subset_iff_subset_vimage le_inf_iff subset subset_antisym) qed qed qed lemma isomorphic_to_local_is_local: assumes lring: "local_ring B addB multB zeroB oneB" and iso: "ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "local_ring A addA multA zeroA oneA" proof intro_locales interpret ring A addA multA zeroA oneA by (meson iso ring_homomorphism.axioms(2) ring_isomorphism.axioms(1)) show "Group_Theory.monoid A addA zeroA" by (simp add: additive.monoid_axioms) show "Group_Theory.group_axioms A addA zeroA" by (meson Group_Theory.group_def additive.group_axioms) show "commutative_monoid_axioms A addA" by (simp add: additive.commutative commutative_monoid_axioms_def) show "Group_Theory.monoid A multA oneA" by (simp add: multiplicative.monoid_axioms) show "ring_axioms A addA multA" by (meson local.ring_axioms ring.axioms(3)) have hom: "monoid_homomorphism f A multA oneA B multB oneB" by (meson iso ring_homomorphism_def ring_isomorphism.axioms(1)) have "bij_betw f A B" using iso map.graph by (simp add: bijective.bijective ring_isomorphism_def bijective_map_def) show "local_ring_axioms A addA multA zeroA oneA" proof fix I J assume I: "max_lideal I A addA multA zeroA oneA" and J: "max_lideal J A addA multA zeroA oneA" show "I = J" proof- have "max_lideal (f ` I) B addB multB zeroB oneB" by (meson I im_of_max_lideal_is_max iso) moreover have "max_lideal (f ` J) B addB multB zeroB oneB" by (meson J im_of_max_lideal_is_max iso) ultimately have "f ` I = f ` J" by (meson local_ring.is_unique lring) thus ?thesis using bij_betw_imp_inj_on [OF \<open>bij_betw f A B\<close>] by (meson I J inj_on_image_eq_iff lideal.subset max_lideal.axioms(1)) qed next show "\<exists>\<ww>. max_lideal \<ww> A addA multA zeroA oneA" by (meson im_of_max_lideal_is_max iso local_ring.has_max_lideal lring ring_isomorphism.inverse_ring_isomorphism) qed qed (* ex. 0.40 *) lemma (in pr_ideal) local_ring_at_is_local: shows "local_ring carrier_local_ring_at add_local_ring_at mult_local_ring_at zero_local_ring_at one_local_ring_at" proof- interpret cq: quotient_ring "R\<setminus>I" R "(+)" "(\<cdot>)" \<zero> \<one> by (simp add: Comm_Ring.quotient_ring_def comm.comm_ring_axioms submonoid_pr_ideal) define \<ww> where "\<ww> \<equiv> {quotient_ring.frac (R\<setminus>I) R (+) (\<cdot>) \<zero> r s| r s. r \<in> I \<and> s \<in> (R \<setminus> I)}" \<comment>\<open>Now every proper ideal of @{term "R\<setminus>I"} is included in @{term \<ww>}, and the result follows trivially\<close> have maximal: "\<aa> \<subseteq> \<ww>" if "lideal \<aa> carrier_local_ring_at add_local_ring_at mult_local_ring_at zero_local_ring_at one_local_ring_at" and ne: "\<aa> \<noteq> carrier_local_ring_at" for \<aa> proof fix x interpret \<aa>: lideal \<aa> carrier_local_ring_at add_local_ring_at mult_local_ring_at zero_local_ring_at one_local_ring_at using that by blast assume "x \<in> \<aa>" have "False" if "x \<notin> \<ww>" proof - obtain r s where "r \<in> R" "s \<in> R" "s \<notin> I" "r \<notin> I" "x = cq.frac r s" using frac_from_carrier_local \<open>x \<in> \<aa>\<close> \<open>x \<notin> \<ww>\<close> [unfolded \<ww>_def, simplified] by (metis \<aa>.additive.sub) then have sr: "cq.frac s r \<in> carrier_local_ring_at" by (simp add: \<open>r \<in> R\<close> \<open>s \<in> R\<close> carrier_local_ring_at_def) have [simp]: "r \<cdot> s \<notin> I" using \<open>r \<in> R\<close> \<open>r \<notin> I\<close> \<open>s \<in> R\<close> \<open>s \<notin> I\<close> absorbent by blast have "one_local_ring_at = cq.frac \<one> \<one>" by (simp add: one_local_ring_at_def cq.one_rel_def) also have "... = cq.frac (s \<cdot> r) (r \<cdot> s)" using \<open>r \<in> R\<close> \<open>r \<notin> I\<close> \<open>s \<in> R\<close> \<open>s \<notin> I\<close> by (intro cq.frac_eqI [of \<one>]) (auto simp: comm.comm_mult) also have "... = cq.mult_rel (cq.frac s r) (cq.frac r s)" using \<open>r \<in> R\<close> \<open>r \<notin> I\<close> \<open>s \<in> R\<close> \<open>s \<notin> I\<close> by (simp add: cq.mult_rel_frac) also have "\<dots> = mult_local_ring_at (cq.frac s r) (cq.frac r s)" using mult_local_ring_at_def by force also have "... \<in> \<aa>" using \<aa>.lideal \<open>x = cq.frac r s\<close> \<open>x \<in> \<aa>\<close> sr by blast finally have "one_local_ring_at \<in> \<aa>" . thus ?thesis using ne \<aa>.has_one_imp_equal by force qed thus "x \<in> \<ww>" by auto qed have uminus_closed: "uminus_local_ring_at u \<in> \<ww>" if "u \<in> \<ww>" for u using that by (force simp: \<ww>_def cq.uminus_rel_frac uminus_local_ring_at_def) have add_closed: "add_local_ring_at a b \<in> \<ww>" if "a \<in> \<ww>" "b \<in> \<ww>" for a b proof - obtain ra sa rb sb where ab: "a = cq.frac ra sa" "b = cq.frac rb sb" and "ra \<in> I" "rb \<in> I" "sa \<in> R" "sa \<notin> I" "sb \<in> R" "sb \<notin> I" using \<open>a \<in> \<ww>\<close> \<open>b \<in> \<ww>\<close> by (auto simp: \<ww>_def) then have "add_local_ring_at (cq.frac ra sa) (cq.frac rb sb) = cq.frac (ra \<cdot> sb + rb \<cdot> sa) (sa \<cdot> sb)" by (force simp add: cq.add_rel_frac add_local_ring_at_def) moreover have "ra \<cdot> sb + rb \<cdot> sa \<in> I" by (simp add: \<open>ra \<in> I\<close> \<open>rb \<in> I\<close> \<open>sa \<in> R\<close> \<open>sb \<in> R\<close> ideal(2)) ultimately show ?thesis unfolding \<ww>_def using \<open>sa \<in> R\<close> \<open>sa \<notin> I\<close> \<open>sb \<in> R\<close> \<open>sb \<notin> I\<close> ab absorbent by blast qed interpret \<ww>: lideal \<ww> carrier_local_ring_at add_local_ring_at mult_local_ring_at zero_local_ring_at one_local_ring_at proof intro_locales show subm: "submonoid_axioms \<ww> carrier_local_ring_at add_local_ring_at zero_local_ring_at" proof show "\<ww> \<subseteq> carrier_local_ring_at" using \<ww>_def comm.comm_ring_axioms comm.frac_in_carrier_local comm_ring.spectrum_def pr_ideal_axioms by fastforce show "zero_local_ring_at \<in> \<ww>" using \<ww>_def comm.spectrum_def comm.spectrum_imp_cxt_quotient_ring not_1 pr_ideal_axioms quotient_ring.zero_rel_def zero_local_ring_at_def by fastforce qed (auto simp: add_closed) show mon: "Group_Theory.monoid \<ww> add_local_ring_at zero_local_ring_at" proof show "zero_local_ring_at \<in> \<ww>" by (meson subm submonoid_axioms_def) next fix a b c assume "a \<in> \<ww>" "b \<in> \<ww>" "c \<in> \<ww>" then show "add_local_ring_at (add_local_ring_at a b) c = add_local_ring_at a (add_local_ring_at b c)" by (meson additive.associative in_mono subm submonoid_axioms_def) next fix a assume "a \<in> \<ww>" show "add_local_ring_at zero_local_ring_at a = a" by (meson \<open>a \<in> \<ww>\<close> subm additive.left_unit in_mono submonoid_axioms_def) show "add_local_ring_at a zero_local_ring_at = a" by (meson \<open>a \<in> \<ww>\<close> additive.right_unit in_mono subm submonoid_axioms_def) qed (auto simp: add_closed) show "Group_Theory.group_axioms \<ww> add_local_ring_at zero_local_ring_at" proof unfold_locales fix u assume "u \<in> \<ww>" show "monoid.invertible \<ww> add_local_ring_at zero_local_ring_at u" proof (rule monoid.invertibleI [OF mon]) show "add_local_ring_at u (uminus_local_ring_at u) = zero_local_ring_at" using \<open>u \<in> \<ww>\<close> apply (clarsimp simp add: \<ww>_def add_local_ring_at_def zero_local_ring_at_def uminus_local_ring_at_def) by (metis Diff_iff additive.submonoid_axioms cq.add_minus_zero_rel cq.valid_frac_def submonoid.sub) then show "add_local_ring_at (uminus_local_ring_at u) u = zero_local_ring_at" using subm unfolding submonoid_axioms_def by (simp add: \<open>u \<in> \<ww>\<close> additive.commutative subset_iff uminus_closed) qed (use \<open>u \<in> \<ww>\<close> uminus_closed in auto) qed show "lideal_axioms \<ww> carrier_local_ring_at mult_local_ring_at" proof fix a b assume a: "a \<in> carrier_local_ring_at" then obtain ra sa where a: "a = cq.frac ra sa" and "ra \<in> R" and sa: "sa \<in> R" "sa \<notin> I" by (meson frac_from_carrier_local) then have "a \<in> carrier_local_ring_at" by (simp add: comm.frac_in_carrier_local comm.spectrum_def pr_ideal_axioms) assume "b \<in> \<ww>" then obtain rb sb where b: "b = cq.frac rb sb" and "rb \<in> I" and sb: "sb \<in> R" "sb \<notin> I" using \<ww>_def by blast have "cq.mult_rel (cq.frac ra sa) (cq.frac rb sb) = cq.frac (ra \<cdot> rb) (sa \<cdot> sb)" using \<open>ra \<in> R\<close> sa \<open>rb \<in> I\<close> sb by (force simp: cq.mult_rel_frac) then show "mult_local_ring_at a b \<in> \<ww>" apply (clarsimp simp add: mult_local_ring_at_def \<ww>_def a b) by (metis Diff_iff \<open>ra \<in> R\<close> \<open>rb \<in> I\<close> cq.sub_composition_closed ideal(1) sa sb) qed qed have max: "max_lideal \<ww> carrier_local_ring_at add_local_ring_at mult_local_ring_at zero_local_ring_at one_local_ring_at" proof have False if "s \<in> R\<setminus>I" "r \<in> I" and eq: "cq.frac \<one> \<one> = cq.frac r s" for r s using that eq_from_eq_frac [OF eq] \<open>r \<in> I\<close> comm.additive.abelian_group_axioms unfolding abelian_group_def by (metis Diff_iff absorbent additive.sub comm.additive.cancel_imp_equal comm.inverse_distributive(1) comm.multiplicative.composition_closed cq.sub_unit_closed ideal(1)) then have "cq.frac \<one> \<one> \<notin> \<ww>" using \<ww>_def by blast moreover have "cq.frac \<one> \<one> \<in> carrier_local_ring_at" using carrier_local_ring_at_def cq.multiplicative.unit_closed cq.one_rel_def by force ultimately show "\<ww> \<noteq> carrier_local_ring_at" by blast qed (use maximal in blast) have "\<And>J. max_lideal J carrier_local_ring_at add_local_ring_at mult_local_ring_at zero_local_ring_at one_local_ring_at \<Longrightarrow> J = \<ww>" by (metis maximal max max_lideal.axioms(1) max_lideal.is_max max_lideal.neq_ring) with max show ?thesis by (metis local.ring_axioms local_ring_axioms_def local_ring_def) qed definition (in stalk) is_local:: "'a set \<Rightarrow> bool" where "is_local U \<equiv> local_ring carrier_stalk add_stalk mult_stalk (zero_stalk U) (one_stalk U)" (* def. 0.41 *) locale local_ring_morphism = source: local_ring A "(+)" "(\<cdot>)" \<zero> \<one> + target: local_ring B "(+')" "(\<cdot>')" "\<zero>'" "\<one>'" + ring_homomorphism f A "(+)" "(\<cdot>)" "\<zero>" "\<one>" B "(+')" "(\<cdot>')" "\<zero>'" "\<one>'" for f and A and addition (infixl "+" 65) and multiplication (infixl "\<cdot>" 70) and zero ("\<zero>") and unit ("\<one>") and B and addition' (infixl "+''" 65) and multiplication' (infixl "\<cdot>''" 70) and zero' ("\<zero>''") and unit' ("\<one>''") + assumes preimage_of_max_lideal: "\<And>\<ww>\<^sub>A \<ww>\<^sub>B. max_lideal \<ww>\<^sub>A A (+) (\<cdot>) \<zero> \<one> \<Longrightarrow> max_lideal \<ww>\<^sub>B B (+') (\<cdot>') \<zero>' \<one>' \<Longrightarrow> (f\<^sup>\<inverse> A \<ww>\<^sub>B) = \<ww>\<^sub>A" lemma id_is_local_ring_morphism: assumes "local_ring A add mult zero one" shows "local_ring_morphism (identity A) A add mult zero one A add mult zero one" proof - interpret local_ring A add mult zero one by (simp add: assms) show ?thesis proof intro_locales show "Set_Theory.map (identity A) A A" by (simp add: Set_Theory.map_def) show "monoid_homomorphism_axioms (identity A) A add zero add zero" by (simp add: monoid_homomorphism_axioms_def) show "monoid_homomorphism_axioms (identity A) A mult one mult one" by (simp add: monoid_homomorphism_axioms_def) show "local_ring_morphism_axioms (identity A) A add mult zero one A add mult zero one" proof fix \<ww>\<^sub>A \<ww>\<^sub>B assume "max_lideal \<ww>\<^sub>A A add mult zero one" "max_lideal \<ww>\<^sub>B A add mult zero one" then have "\<ww>\<^sub>B \<inter> A = \<ww>\<^sub>A" by (metis Int_absorb2 is_unique lideal.subset max_lideal.axioms(1)) then show "identity A \<^sup>\<inverse> A \<ww>\<^sub>B = \<ww>\<^sub>A" by (simp add: preimage_identity_self) qed qed qed lemma (in ring_epimorphism) preim_subset_imp_subset: assumes "\<eta> \<^sup>\<inverse> R I \<subseteq> \<eta> \<^sup>\<inverse> R J" and "I \<subseteq> R'" shows "I \<subseteq> J" using Int_absorb1 assms surjective by blast lemma iso_is_local_ring_morphism: assumes "local_ring A addA multA zeroA oneA" and "ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB" shows "local_ring_morphism f A addA multA zeroA oneA B addB multB zeroB oneB" proof - interpret A: local_ring A addA multA zeroA oneA using assms(1) by blast interpret B: ring B addB multB zeroB oneB by (meson assms(2) ring_homomorphism_def ring_isomorphism_def) interpret f: ring_isomorphism f A addA multA zeroA oneA B addB multB zeroB oneB by (simp add: assms) interpret preB: ring "f \<^sup>\<inverse> A B" addA multA zeroA oneA by (metis (no_types) A.ring_axioms f.multiplicative.image.subset image_subset_iff_subset_vimage inf.absorb2) show ?thesis proof fix I J assume "max_lideal I B addB multB zeroB oneB" then interpret MI: max_lideal I B addB multB zeroB oneB by simp assume "max_lideal J B addB multB zeroB oneB" then interpret MJ: max_lideal J B addB multB zeroB oneB by simp interpret GI: subgroup I B addB zeroB by unfold_locales have "max_lideal (f \<^sup>\<inverse> A I) (f \<^sup>\<inverse> A B) addA multA zeroA oneA" by (metis (no_types) MI.max_lideal_axioms f.ring_isomorphism_axioms preim_of_max_lideal_is_max) moreover have "max_lideal (f \<^sup>\<inverse> A J) (f \<^sup>\<inverse> A B) addA multA zeroA oneA" by (meson MJ.max_lideal_axioms f.ring_isomorphism_axioms preim_of_max_lideal_is_max) ultimately have "f \<^sup>\<inverse> A I = f \<^sup>\<inverse> A J" by (metis A.is_unique Int_absorb1 f.multiplicative.image.subset image_subset_iff_subset_vimage) then show "I = J" by (metis MI.lideal_axioms MI.neq_ring MJ.max_lideal_axioms MJ.subset f.preim_subset_imp_subset max_lideal.is_max subset_refl) next show "\<exists>\<ww>. max_lideal \<ww> B addB multB zeroB oneB" by (meson A.has_max_lideal assms(2) im_of_max_lideal_is_max) next fix \<ww>\<^sub>A \<ww>\<^sub>B assume "max_lideal \<ww>\<^sub>A A addA multA zeroA oneA" and "max_lideal \<ww>\<^sub>B B addB multB zeroB oneB" then show "f \<^sup>\<inverse> A \<ww>\<^sub>B = \<ww>\<^sub>A" by (metis A.is_unique f.multiplicative.image.subset f.ring_isomorphism_axioms image_subset_iff_subset_vimage inf.absorb2 preim_of_max_lideal_is_max) qed qed (*these epimorphism aren't actually used*) lemma (in monoid_homomorphism) monoid_epimorphism_image: "monoid_epimorphism \<eta> M (\<cdot>) \<one> (\<eta> ` M) (\<cdot>') \<one>'" proof - interpret monoid "\<eta> ` M" "(\<cdot>')" "\<one>'" using image.sub.monoid_axioms by force show ?thesis proof qed (auto simp: bij_betw_def commutes_with_unit commutes_with_composition) qed lemma (in group_homomorphism) group_epimorphism_image: "group_epimorphism \<eta> G (\<cdot>) \<one> (\<eta> ` G) (\<cdot>') \<one>'" proof - interpret group "\<eta> ` G" "(\<cdot>')" "\<one>'" using image.sub.group_axioms by blast show ?thesis proof qed (auto simp: bij_betw_def commutes_with_composition) qed lemma (in ring_homomorphism) ring_epimorphism_preimage: "ring_epimorphism \<eta> R (+) (\<cdot>) \<zero> \<one> (\<eta> ` R) (+') (\<cdot>') \<zero>' \<one>'" proof - interpret ring "\<eta> ` R" "(+')" "(\<cdot>')" "\<zero>'" "\<one>'" proof qed (auto simp add: target.distributive target.additive.commutative) show ?thesis proof qed (auto simp: additive.commutes_with_composition additive.commutes_with_unit multiplicative.commutes_with_composition multiplicative.commutes_with_unit) qed lemma comp_of_local_ring_morphisms: assumes "local_ring_morphism f A addA multA zeroA oneA B addB multB zeroB oneB" and "local_ring_morphism g B addB multB zeroB oneB C addC multC zeroC oneC" shows "local_ring_morphism (compose A g f) A addA multA zeroA oneA C addC multC zeroC oneC" proof - interpret f: local_ring_morphism f A addA multA zeroA oneA B addB multB zeroB oneB by (simp add: assms) interpret g: local_ring_morphism g B addB multB zeroB oneB C addC multC zeroC oneC by (simp add: assms) interpret gf: ring_homomorphism "compose A g f" A addA multA zeroA oneA C addC multC zeroC oneC using comp_ring_morphisms f.ring_homomorphism_axioms g.ring_homomorphism_axioms by fastforce obtain \<ww>\<^sub>B where \<ww>\<^sub>B: "max_lideal \<ww>\<^sub>B B addB multB zeroB oneB" using f.target.has_max_lideal by force show ?thesis proof intro_locales show "local_ring_morphism_axioms (compose A g f) A addA multA zeroA oneA C addC multC zeroC oneC" proof fix \<ww>\<^sub>A \<ww>\<^sub>C assume max: "max_lideal \<ww>\<^sub>A A addA multA zeroA oneA" "max_lideal \<ww>\<^sub>C C addC multC zeroC oneC" interpret maxA: max_lideal \<ww>\<^sub>A A addA multA zeroA oneA using max by blast interpret maxC: max_lideal \<ww>\<^sub>C C addC multC zeroC oneC using max by blast have "B \<subseteq> g -` C" by blast with max interpret maxg: max_lideal "g \<^sup>\<inverse> B \<ww>\<^sub>C" "g \<^sup>\<inverse> B C" addB multB zeroB oneB by (metis Int_absorb1 \<ww>\<^sub>B g.preimage_of_max_lideal) interpret maxgf: Group_Theory.monoid "(g \<circ> f \<down> A) \<^sup>\<inverse> A \<ww>\<^sub>C" addA zeroA by (simp add: monoid_def vimage_def gf.additive.commutes_with_composition gf.additive.commutes_with_unit f.source.additive.associative) show "(g \<circ> f \<down> A) \<^sup>\<inverse> A \<ww>\<^sub>C = \<ww>\<^sub>A" proof (rule maxA.is_max [symmetric]) show "lideal ((g \<circ> f \<down> A) \<^sup>\<inverse> A \<ww>\<^sub>C) A addA multA zeroA oneA" proof fix u assume u: "u \<in> (g \<circ> f \<down> A) \<^sup>\<inverse> A \<ww>\<^sub>C" then have "u \<in> A" by auto show "maxgf.invertible u" proof (rule maxgf.invertibleI) show "addA u (f.source.additive.inverse u) = zeroA" using f.source.additive.invertible_right_inverse \<open>u \<in> A\<close> by blast have "(g \<circ> f \<down> A) (f.source.additive.inverse u) = g.target.additive.inverse (g (f u))" by (metis f.source.additive.invertible \<open>u \<in> A\<close> compose_eq gf.additive.invertible_commutes_with_inverse) then show "(f.source.additive.inverse u) \<in> (g \<circ> f \<down> A) \<^sup>\<inverse> A \<ww>\<^sub>C" by (metis f.source.additive.invertible f.source.additive.invertible_inverse_closed g.target.additive.group_axioms Int_iff compose_eq maxC.additive.subgroup_inverse_iff f.map_closed g.map_axioms group.invertible map.map_closed u vimage_eq) qed (use u \<open>u \<in> A\<close> in auto) next fix r a assume "r \<in> A" and "a \<in> (g \<circ> f \<down> A) \<^sup>\<inverse> A \<ww>\<^sub>C" then show "multA r a \<in> (g \<circ> f \<down> A) \<^sup>\<inverse> A \<ww>\<^sub>C" by (simp add: maxC.lideal gf.multiplicative.commutes_with_composition) qed (use maxgf.unit_closed maxgf.composition_closed in auto) have "\<And>x. x \<in> \<ww>\<^sub>A \<Longrightarrow> g (f x) \<in> \<ww>\<^sub>C" by (metis IntD1 \<ww>\<^sub>B f.preimage_of_max_lideal g.preimage_of_max_lideal max vimageD) then show "\<ww>\<^sub>A \<subseteq> (g \<circ> f \<down> A) \<^sup>\<inverse> A \<ww>\<^sub>C" by (auto simp: compose_eq) have "oneB \<notin> g -` \<ww>\<^sub>C" using maxg.has_one_imp_equal maxg.neq_ring by force then have "g oneB \<notin> \<ww>\<^sub>C" by blast then show "(g \<circ> f \<down> A) \<^sup>\<inverse> A \<ww>\<^sub>C \<noteq> A" by (metis Int_iff compose_eq f.multiplicative.commutes_with_unit f.source.multiplicative.unit_closed vimage_eq) qed qed qed qed subsubsection \<open>Locally Ringed Spaces\<close> (* The key map from the stalk at a prime ideal \<pp> to the local ring at \<pp> *) locale key_map = comm_ring + fixes \<pp>:: "'a set" assumes is_prime: "\<pp> \<in> Spec" begin interpretation pi:pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> by (simp add: is_prime spectrum_imp_pr) interpretation top: topological_space Spec is_zariski_open by simp interpretation pr:presheaf_of_rings Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec by (fact local.sheaf_spec_is_presheaf) interpretation local:quotient_ring "(R \<setminus> \<pp>)" R "(+)" "(\<cdot>)" \<zero> \<one> using is_prime spectrum_imp_cxt_quotient_ring by presburger interpretation st: stalk "Spec" is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec "{U. is_zariski_open U \<and> \<pp>\<in>U}" \<pp> proof fix U I V s assume "open_cover_of_open_subset Spec is_zariski_open U I V" and "\<And>i. i \<in> I \<Longrightarrow> V i \<subseteq> U" and "s \<in> \<O> U" and "\<And>i. i \<in> I \<Longrightarrow> sheaf_spec_morphisms U (V i) s = zero_sheaf_spec (V i)" then show "s = zero_sheaf_spec U" by (metis sheaf_of_rings.locality sheaf_spec_is_sheaf) next fix U I V s assume "open_cover_of_open_subset Spec is_zariski_open U I V" and "\<forall>i. i \<in> I \<longrightarrow> V i \<subseteq> U \<and> s i \<in> \<O> V i" and "\<And>i j. \<lbrakk>i \<in> I; j \<in> I\<rbrakk> \<Longrightarrow> sheaf_spec_morphisms (V i) (V i \<inter> V j) (s i) = sheaf_spec_morphisms (V j) (V i \<inter> V j) (s j)" then show "\<exists>t. t \<in> \<O> U \<and> (\<forall>i. i \<in> I \<longrightarrow> sheaf_spec_morphisms U (V i) t = s i)" by (smt (verit, ccfv_threshold) sheaf_of_rings.glueing sheaf_spec_is_sheaf) qed (use is_prime in auto) declare st.subset_of_opens [simp del, rule del] \<comment>\<open>because it loops!\<close> definition key_map:: "'a set set \<Rightarrow> (('a set \<Rightarrow> ('a \<times> 'a) set) \<Rightarrow> ('a \<times> 'a) set)" where "key_map U \<equiv> \<lambda>s\<in>(\<O> U). s \<pp>" lemma key_map_is_map: assumes "\<pp> \<in> U" shows "Set_Theory.map (key_map U) (\<O> U) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" proof have "\<And>s. s \<in> \<O> U \<Longrightarrow> s \<pp> \<in> (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" using sheaf_spec_def assms is_regular_def by blast thus "key_map U \<in> (\<O> U) \<rightarrow>\<^sub>E (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" using key_map_def extensional_funcset_def by simp qed lemma key_map_is_ring_morphism: assumes "\<pp> \<in> U" and "is_zariski_open U" shows "ring_homomorphism (key_map U) (\<O> U) (add_sheaf_spec U) (mult_sheaf_spec U) (zero_sheaf_spec U) (one_sheaf_spec U) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.mult_local_ring_at) (pi.zero_local_ring_at) (pi.one_local_ring_at)" proof (intro ring_homomorphism.intro) show "Set_Theory.map (key_map U) (\<O> U) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" using key_map_is_map assms(1) by simp next show "ring (\<O> U) (add_sheaf_spec U) (mult_sheaf_spec U) (zero_sheaf_spec U) (one_sheaf_spec U)" using \<open>is_zariski_open U\<close> pr.is_ring_from_is_homomorphism by blast next show "ring (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.mult_local_ring_at) (pi.zero_local_ring_at) (pi.one_local_ring_at)" by (simp add: pi.ring_axioms) next show "group_homomorphism (key_map U) (\<O> U) (add_sheaf_spec U) (zero_sheaf_spec U) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.zero_local_ring_at)" proof intro_locales show "Set_Theory.map (local.key_map U) (\<O> U) pi.carrier_local_ring_at" by (simp add: assms(1) key_map_is_map) show "Group_Theory.monoid (\<O> U) (add_sheaf_spec U) (zero_sheaf_spec U)" "Group_Theory.group_axioms (\<O> U) (add_sheaf_spec U) (zero_sheaf_spec U)" using pr.is_ring_from_is_homomorphism [OF \<open>is_zariski_open U\<close>] unfolding ring_def Group_Theory.group_def abelian_group_def by blast+ have 1: "(key_map U) (zero_sheaf_spec U) = pi.zero_local_ring_at" using assms unfolding key_map_def pi.zero_local_ring_at_def by (metis (no_types, lifting) restrict_apply' zero_sheaf_spec_def zero_sheaf_spec_in_sheaf_spec) have 2: "\<And>x y. \<lbrakk>x \<in> \<O> U; y \<in> \<O> U\<rbrakk> \<Longrightarrow> (key_map U) (add_sheaf_spec U x y) = pi.add_local_ring_at (key_map U x) (key_map U y)" using add_sheaf_spec_in_sheaf_spec key_map_def assms pi.add_local_ring_at_def add_sheaf_spec_def spectrum_def zariski_open_is_subset by fastforce show "monoid_homomorphism_axioms (local.key_map U) (\<O> U) (add_sheaf_spec U) (zero_sheaf_spec U) pi.add_local_ring_at pi.zero_local_ring_at" unfolding monoid_homomorphism_axioms_def by (auto simp: 1 2) qed next have "(key_map U) (one_sheaf_spec U) = pi.one_local_ring_at" using one_sheaf_spec_def key_map_def pi.one_local_ring_at_def assms one_sheaf_spec_in_sheaf_spec spectrum_def by fastforce moreover have "\<And>x y. \<lbrakk>x \<in> \<O> U; y \<in> \<O> U\<rbrakk> \<Longrightarrow> (key_map U) (mult_sheaf_spec U x y) = pi.mult_local_ring_at (key_map U x) (key_map U y)" using mult_sheaf_spec_in_sheaf_spec key_map_def assms pi.mult_local_ring_at_def mult_sheaf_spec_def spectrum_def zariski_open_is_subset by fastforce ultimately show "monoid_homomorphism (key_map U) (\<O> U) (mult_sheaf_spec U) (one_sheaf_spec U) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.mult_local_ring_at) (pi.one_local_ring_at)" using pr.is_ring_from_is_homomorphism [OF \<open>is_zariski_open U\<close>] \<open>\<pp> \<in> U\<close> unfolding monoid_homomorphism_def monoid_homomorphism_axioms_def ring_def using key_map_is_map pi.multiplicative.monoid_axioms by presburger qed lemma key_map_is_coherent: assumes "V \<subseteq> U" and "is_zariski_open U" and "is_zariski_open V" and "\<pp> \<in> V" and "s \<in> \<O> U" shows "(key_map V \<circ> sheaf_spec_morphisms U V) s = key_map U s" proof- have "sheaf_spec_morphisms U V s \<in> \<O> V" using assms sheaf_spec_morphisms_are_maps map.map_closed by (metis (mono_tags, opaque_lifting)) thus "(key_map V \<circ> sheaf_spec_morphisms U V) s = key_map U s" by (simp add: \<open>s \<in> \<O> U\<close> assms(4) key_map_def sheaf_spec_morphisms_def) qed lemma key_ring_morphism: assumes "is_zariski_open V" and "\<pp> \<in> V" shows "\<exists>\<phi>. ring_homomorphism \<phi> st.carrier_stalk st.add_stalk st.mult_stalk (st.zero_stalk V) (st.one_stalk V) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.mult_local_ring_at) (pi.zero_local_ring_at) (pi.one_local_ring_at) \<and> (\<forall>U\<in>(top.neighborhoods \<pp>). \<forall>s\<in>\<O> U. (\<phi> \<circ> st.canonical_fun U) s = key_map U s)" proof - have "ring (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.mult_local_ring_at) (pi.zero_local_ring_at) (pi.one_local_ring_at)" by (simp add: pi.ring_axioms) moreover have "V \<in> top.neighborhoods \<pp>" using assms top.neighborhoods_def sheaf_spec_is_presheaf by fastforce moreover have "\<And>U. U \<in> top.neighborhoods \<pp> \<Longrightarrow> ring_homomorphism (key_map U) (\<O> U) (add_sheaf_spec U) (mult_sheaf_spec U) (zero_sheaf_spec U) (one_sheaf_spec U) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.mult_local_ring_at) (pi.zero_local_ring_at) (pi.one_local_ring_at)" using key_map_is_ring_morphism top.neighborhoods_def sheaf_spec_is_presheaf by force moreover have "\<And>U V x. \<lbrakk>U \<in> top.neighborhoods \<pp>; V \<in> top.neighborhoods \<pp>; V \<subseteq> U; x \<in> \<O> U\<rbrakk> \<Longrightarrow> (key_map V \<circ> sheaf_spec_morphisms U V) x = key_map U x" using key_map_is_coherent by (metis (no_types, lifting) mem_Collect_eq top.neighborhoods_def) ultimately show ?thesis using assms local.sheaf_spec_is_presheaf zariski_open_is_subset st.universal_property_for_stalk[of "R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>" "pi.add_local_ring_at" "pi.mult_local_ring_at" "pi.zero_local_ring_at" "pi.one_local_ring_at" "key_map"] by auto qed lemma class_from_belongs_stalk: assumes "s \<in> st.carrier_stalk" obtains U s' where "is_zariski_open U" "\<pp> \<in> U" "s' \<in> \<O> U" "s = st.class_of U s'" proof - interpret dl: direct_lim Spec is_zariski_open sheaf_spec sheaf_spec_morphisms "\<O>b" add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec "top.neighborhoods \<pp>" by (simp add: st.direct_lim_axioms top.neighborhoods_def) interpret eq: equivalence "Sigma (top.neighborhoods \<pp>) sheaf_spec" "{(x, y). dl.rel x y}" using dl.rel_is_equivalence by force note dl.subset_of_opens [simp del] obtain U s' where seq: "s = eq.Class (U, s')" and U: "U \<in> top.neighborhoods \<pp>" and s': "s' \<in> \<O> U" using assms unfolding st.carrier_stalk_def dl.carrier_direct_lim_def by (metis SigmaD1 SigmaD2 eq.representant_exists old.prod.exhaust) show thesis proof show "is_zariski_open U" using U dl.subset_of_opens by blast show "\<pp> \<in> U" using U top.neighborhoods_def by force show "s' \<in> \<O> U" using s' by blast show "s = st.class_of U s'" using seq st.class_of_def top.neighborhoods_def by presburger qed qed lemma same_class_from_restrict: assumes "is_zariski_open U" "is_zariski_open V" "U \<subseteq> V" "s \<in> \<O> V" "\<pp> \<in> U" shows "st.class_of V s = st.class_of U (sheaf_spec_morphisms V U s)" proof - interpret eq: equivalence "Sigma {U. is_zariski_open U \<and> \<pp> \<in> U} sheaf_spec" "{(x, y). st.rel x y}" using st.rel_is_equivalence by blast show ?thesis unfolding st.class_of_def proof (rule eq.Class_eq) have \<section>:"sheaf_spec_morphisms V U s \<in> \<O> U" using assms map.map_closed pr.is_map_from_is_homomorphism by fastforce then have "\<exists>W. is_zariski_open W \<and> \<pp> \<in> W \<and> W \<subseteq> V \<and> W \<subseteq> U \<and> sheaf_spec_morphisms V W s = sheaf_spec_morphisms U W (sheaf_spec_morphisms V U s)" using assms(1) assms(3) assms(5) by auto then show "((V, s), U, sheaf_spec_morphisms V U s) \<in> {(x, y). st.rel x y}" using \<section> assms by (auto simp: st.rel_def) qed qed lemma shrinking_from_belong_stalk: assumes "s \<in> st.carrier_stalk" and "t \<in> st.carrier_stalk" obtains U s' t' where "is_zariski_open U" "\<pp> \<in> U" "s' \<in> \<O> U" "s = st.class_of U s'" "t' \<in> \<O> U" "t = st.class_of U t'" proof - obtain U s' where HU:"is_zariski_open U" "\<pp> \<in> U" "s' \<in> \<O> U" "s = st.class_of U s'" using assms(1) class_from_belongs_stalk by blast obtain V t' where HV:"is_zariski_open V" "\<pp> \<in> V" "t' \<in> \<O> V" "t = st.class_of V t'" using assms(2) class_from_belongs_stalk by blast show thesis proof have "U \<inter> V \<subseteq> Spec" using zariski_open_is_subset HU(1) by blast show "\<pp> \<in> U \<inter> V" by (simp add: \<open>\<pp> \<in> U\<close> \<open>\<pp> \<in> V\<close>) show UV: "is_zariski_open (U \<inter> V)" using topological_space.open_inter by (simp add: \<open>is_zariski_open U\<close> \<open>is_zariski_open V\<close>) show "s = st.class_of (U \<inter> V) (sheaf_spec_morphisms U (U \<inter> V) s')" using HU UV \<open>\<pp> \<in> U \<inter> V\<close> same_class_from_restrict by blast show "t = st.class_of (U \<inter> V) (sheaf_spec_morphisms V (U \<inter> V) t')" using HV UV \<open>\<pp> \<in> U \<inter> V\<close> same_class_from_restrict by blast show "sheaf_spec_morphisms U (U \<inter> V) s' \<in> \<O> (U \<inter> V)" using HU(3) UV map.map_closed sheaf_spec_morphisms_are_maps by fastforce show "sheaf_spec_morphisms V (U \<inter> V) t' \<in> \<O> (U \<inter> V)" using HV(3) UV map.map_closed sheaf_spec_morphisms_are_maps by fastforce qed qed lemma stalk_at_prime_is_iso_to_local_ring_at_prime_aux: assumes "is_zariski_open V" and "\<pp> \<in> V" and \<phi>: "ring_homomorphism \<phi> st.carrier_stalk st.add_stalk st.mult_stalk (st.zero_stalk V) (st.one_stalk V) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.mult_local_ring_at) (pi.zero_local_ring_at) (pi.one_local_ring_at)" and all_eq: "\<forall>U\<in>(top.neighborhoods \<pp>). \<forall>s\<in>\<O> U. (\<phi> \<circ> st.canonical_fun U) s = key_map U s" shows "ring_isomorphism \<phi> st.carrier_stalk st.add_stalk st.mult_stalk (st.zero_stalk V) (st.one_stalk V) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.mult_local_ring_at) (pi.zero_local_ring_at) (pi.one_local_ring_at)" proof (intro ring_isomorphism.intro bijective_map.intro bijective.intro) show "ring_homomorphism \<phi> st.carrier_stalk st.add_stalk st.mult_stalk (st.zero_stalk V) (st.one_stalk V) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.mult_local_ring_at) (pi.zero_local_ring_at) (pi.one_local_ring_at)" using assms(3) by simp next show "Set_Theory.map \<phi> st.carrier_stalk (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" using assms(3) by (simp add: ring_homomorphism_def) next show "bij_betw \<phi> st.carrier_stalk (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" proof- have "inj_on \<phi> st.carrier_stalk" proof fix s t assume "s \<in> st.carrier_stalk" "t \<in> st.carrier_stalk" "\<phi> s = \<phi> t" obtain U s' t' a f b g where FU [simp]: "is_zariski_open U" "\<pp> \<in> U" "s' \<in> \<O> U" "t' \<in> \<O> U" and s: "s = st.class_of U s'" "t = st.class_of U t'" and s': "s' = (\<lambda>\<qq>\<in>U. quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f)" and t': "t' = (\<lambda>\<qq>\<in>U. quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g)" and "a \<in> R" "b \<in> R" "f \<in> R" "g \<in> R" "f \<notin> \<pp>" "g \<notin> \<pp>" proof- obtain V s' t' where HV: "s = st.class_of V s'" "t = st.class_of V t'" "s' \<in> \<O> V" "t' \<in> \<O> V" "is_zariski_open V" "\<pp> \<in> V" using shrinking_from_belong_stalk by (metis (no_types, lifting) \<open>s \<in> st.carrier_stalk\<close> \<open>t \<in> st.carrier_stalk\<close>) then obtain U a f b g where HU: "is_zariski_open U" "U \<subseteq> V" "\<pp> \<in> U" "a \<in> R" "f \<in> R" "b \<in> R" "g \<in> R" "f \<notin> \<pp>" "g \<notin> \<pp>" "\<And>\<qq>. \<qq> \<in> U \<Longrightarrow> f \<notin> \<qq> \<and> s' \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f" "\<And>\<qq>. \<qq> \<in> U \<Longrightarrow> g \<notin> \<qq> \<and> t' \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g" using shrinking[of V \<pp> s' t'] by blast show ?thesis proof show "sheaf_spec_morphisms V U s' \<in> \<O> U" by (metis (mono_tags, opaque_lifting) HU(1,2) HV(3) map.map_closed sheaf_spec_morphisms_are_maps) show "sheaf_spec_morphisms V U t' \<in> \<O> U" by (metis (mono_tags, opaque_lifting) HU(1,2) HV(4) map.map_closed sheaf_spec_morphisms_are_maps) show "s = st.class_of U (sheaf_spec_morphisms V U s')" by (simp add: HU(1-3) HV same_class_from_restrict) show "t = st.class_of U (sheaf_spec_morphisms V U t')" by (simp add: HU(1-3) HV same_class_from_restrict) show "sheaf_spec_morphisms V U s' = (\<lambda>\<qq>\<in>U. quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f)" using HV(3) sheaf_spec_morphisms_def HU(10) by fastforce show "sheaf_spec_morphisms V U t' = (\<lambda>\<qq>\<in>U. quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g)" using HV(4) HU(11) sheaf_spec_morphisms_def by fastforce qed (use HU in auto) qed hence fact:"local.frac a f = local.frac b g" proof- have "local.frac a f = key_map U s'" using key_map_def \<open>\<pp> \<in> U\<close> \<open>s' = (\<lambda>\<qq>\<in>U. quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f)\<close> \<open>s' \<in> \<O> U\<close> by auto also have "\<dots> = \<phi> (st.canonical_fun U s')" using \<open>\<pp> \<in> U\<close> \<open>is_zariski_open U\<close> \<open>s' \<in> \<O> U\<close> assms(4) pr.presheaf_of_rings_axioms top.neighborhoods_def by fastforce also have "\<dots> = \<phi> (st.class_of U s')" using direct_lim.canonical_fun_def is_prime st.canonical_fun_def st.class_of_def by fastforce also have "\<dots> = \<phi> s" by (simp add: \<open>s = st.class_of U s'\<close>) also have "\<dots> = \<phi> t" using \<open>\<phi> s = \<phi> t\<close> by simp also have "\<dots> = \<phi> (st.class_of U t')" using \<open>t = st.class_of U t'\<close> by auto also have "\<dots> = \<phi> (st.canonical_fun U t')" using direct_lim.canonical_fun_def is_prime st.canonical_fun_def st.class_of_def by fastforce also have "\<dots> = key_map U t'" using \<open>\<pp> \<in> U\<close> \<open>is_zariski_open U\<close> \<open>t' \<in> \<O> U\<close> assms(4) top.neighborhoods_def by auto also have "\<dots> = local.frac b g" using FU(4) local.key_map_def t' by force finally show ?thesis . qed then obtain h where Hh: "h \<in> R" "h \<notin> \<pp>" "h \<cdot> (g \<cdot> a - f \<cdot> b) = \<zero>" using pi.eq_from_eq_frac by (metis Diff_iff \<open>a \<in> R\<close> \<open>b \<in> R\<close> \<open>f \<in> R\<close> \<open>f \<notin> \<pp>\<close> \<open>g \<in> R\<close> \<open>g \<notin> \<pp>\<close>) have izo: "is_zariski_open (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h))" using local.standard_open_is_zariski_open by (simp add: Hh(1) \<open>f \<in> R\<close> \<open>g \<in> R\<close> standard_open_is_zariski_open) have ssm_s': "sheaf_spec_morphisms U (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) s' \<in> \<O> (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h))" by (metis (no_types, opaque_lifting) FU(3) Int_assoc inf_le1 izo map.map_closed sheaf_spec_morphisms_are_maps) have ssm_t': "sheaf_spec_morphisms U (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) t' \<in> \<O> (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h))" by (metis (no_types, opaque_lifting) FU(4) Int_assoc inf_le1 izo map.map_closed sheaf_spec_morphisms_are_maps) have [simp]: "\<pp> \<in> \<D>(f)" "\<pp> \<in> \<D>(g)" "\<pp> \<in> \<D>(h)" using Hh \<open>f \<in> R\<close> \<open>f \<notin> \<pp>\<close> \<open>g \<in> R\<close> \<open>g \<notin> \<pp>\<close> belongs_standard_open_iff st.is_elem by blast+ have eq: "s' \<qq> = t' \<qq>" if "\<qq> \<in> U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)" for \<qq> proof - have "\<qq> \<in> Spec" using standard_open_def that by auto then interpret q: quotient_ring "R\<setminus>\<qq>" R "(+)" "(\<cdot>)" \<zero> using spectrum_imp_cxt_quotient_ring by force note local.q.sub [simp del] \<comment>\<open>Because it definitely loops\<close> define RR where "RR \<equiv> {(x, y). (x, y) \<in> (R \<times> (R\<setminus>\<qq>)) \<times> R \<times> (R\<setminus>\<qq>) \<and> q.rel x y}" interpret eq: equivalence "R \<times> (R\<setminus>\<qq>)" "RR" unfolding RR_def by (blast intro: equivalence.intro q.rel_refl q.rel_sym q.rel_trans) have Fq [simp]: "f \<notin> \<qq>" "g \<notin> \<qq>" "h \<notin> \<qq>" using belongs_standard_open_iff that apply (meson Int_iff \<open>\<qq> \<in> Spec\<close> \<open>f \<in> R\<close>) apply (meson Int_iff \<open>\<qq> \<in> Spec\<close> \<open>g \<in> R\<close> belongs_standard_open_iff that) by (meson Hh(1) IntD2 \<open>\<qq> \<in> Spec\<close> belongs_standard_open_iff that) moreover have "eq.Class (a, f) = eq.Class (b, g)" proof (rule eq.Class_eq) have "\<exists>s1. s1 \<in> R \<and> s1 \<notin> \<qq> \<and> s1 \<cdot> (g \<cdot> a - f \<cdot> b) = \<zero>" using Hh \<open>h \<notin> \<qq>\<close> by blast then show "((a,f), b,g) \<in> RR" by (simp add: RR_def q.rel_def \<open>a \<in> R\<close> \<open>b \<in> R\<close> \<open>f \<in> R\<close> \<open>g \<in> R\<close>) qed ultimately have "q.frac a f = q.frac b g" using RR_def q.frac_def by metis thus "s' \<qq> = t' \<qq>" by (simp add: s' t') qed show "s = t" proof- have "s = st.class_of (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (sheaf_spec_morphisms U (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) s')" using \<open>\<pp> \<in> \<D>(f)\<close> \<open>\<pp> \<in> \<D>(g)\<close> \<open>\<pp> \<in> \<D>(h)\<close> by (smt (verit, ccfv_threshold) FU(1-3) IntE IntI izo s(1) same_class_from_restrict subsetI) also have "\<dots> = st.class_of (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (sheaf_spec_morphisms U (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) t')" proof (rule local.st.class_of_eqI) show "sheaf_spec_morphisms (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (sheaf_spec_morphisms U (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) s') = sheaf_spec_morphisms (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (sheaf_spec_morphisms U (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) t')" proof (rule local.pr.eq_\<rho>) show "sheaf_spec_morphisms (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (sheaf_spec_morphisms U (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) s') = sheaf_spec_morphisms (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) (sheaf_spec_morphisms U (U \<inter> \<D>(f) \<inter> \<D>(g) \<inter> \<D>(h)) t')" using eq FU(3) FU(4) apply (simp add: sheaf_spec_morphisms_def) apply (metis eq restrict_ext) done qed (use izo ssm_s' ssm_t' in auto) qed (auto simp: izo ssm_s' ssm_t') also have "\<dots> = t" using \<open>\<pp> \<in> \<D>(f)\<close> \<open>\<pp> \<in> \<D>(g)\<close> \<open>\<pp> \<in> \<D>(h)\<close> by (smt (verit, ccfv_threshold) FU(1-4) IntE IntI izo s(2) same_class_from_restrict subsetI) finally show ?thesis . qed qed moreover have "\<phi> ` st.carrier_stalk = (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" proof show "\<phi> ` st.carrier_stalk \<subseteq> pi.carrier_local_ring_at" using assms(3) by (simp add: image_subset_of_target ring_homomorphism_def) next show "pi.carrier_local_ring_at \<subseteq> \<phi> ` st.carrier_stalk" proof fix x assume H:"x \<in> (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>)" obtain a f where F:"a \<in> R" "f \<in> R" "f \<notin> \<pp>" "x = local.frac a f" using pi.frac_from_carrier_local H by blast define s where sec_def:"s \<equiv> \<lambda>\<qq>\<in>\<D>(f). quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f" then have sec:"s \<in> \<O>(\<D>(f))" proof- have "s \<qq> \<in> (R\<^bsub>\<qq> (+) (\<cdot>) \<zero>\<^esub>)" if "\<qq> \<in> \<D>(f)" for \<qq> proof - have "f \<notin> \<qq>" using that belongs_standard_open_iff F(2) standard_open_is_subset by blast then have "quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f \<in> (R\<^bsub>\<qq> (+) (\<cdot>) \<zero>\<^esub>)" using F(1,2) frac_in_carrier_local \<open>\<qq> \<in> \<D>(f)\<close> standard_open_is_subset by blast thus "s \<qq> \<in> (R\<^bsub>\<qq> (+) (\<cdot>) \<zero>\<^esub>)" using sec_def by (simp add: \<open>\<qq> \<in> \<D>(f)\<close>) qed moreover have "s \<in> extensional (\<D>(f))" using sec_def by auto moreover have "is_regular s \<D>(f)" using F(1,2) standard_open_is_subset belongs_standard_open_iff is_regular_def[of s "\<D>(f)"] standard_open_is_zariski_open by (smt is_locally_frac_def restrict_apply sec_def subsetD subsetI) ultimately show ?thesis unfolding sheaf_spec_def[of "\<D>(f)"] by (simp add:PiE_iff) qed then have im:"\<phi> (st.class_of \<D>(f) s) = local.frac a f" proof- have "\<phi> (st.class_of \<D>(f) s) = \<phi> (st.canonical_fun \<D>(f) s)" using st.canonical_fun_def direct_lim.canonical_fun_def st.class_of_def is_prime by fastforce also have "\<dots> = key_map \<D>(f) s" using all_eq st.is_elem F(2) F(3) sec apply (simp add: top.neighborhoods_def) by (meson belongs_standard_open_iff standard_open_is_zariski_open) also have "... = local.frac a f" by (metis (mono_tags, lifting) F(2,3) belongs_standard_open_iff is_prime key_map_def restrict_apply sec sec_def) finally show ?thesis . qed thus "x \<in> \<phi> ` st.carrier_stalk" proof- have "st.class_of \<D>(f) s \<in> st.carrier_stalk" proof- have "\<pp> \<in> Spec" using is_prime by simp also have "\<D>(f) \<in> (top.neighborhoods \<pp>)" using top.neighborhoods_def belongs_standard_open_iff F(2,3) is_prime standard_open_is_zariski_open standard_open_is_subset by (metis (no_types, lifting) mem_Collect_eq) moreover have "s \<in> \<O> \<D>(f)" using sec by simp ultimately show ?thesis using st.class_of_in_stalk by auto qed thus ?thesis using F(4) im by blast qed qed qed ultimately show ?thesis by (simp add: bij_betw_def) qed qed lemma stalk_at_prime_is_iso_to_local_ring_at_prime: assumes "is_zariski_open V" and "\<pp> \<in> V" shows "\<exists>\<phi>. ring_isomorphism \<phi> st.carrier_stalk st.add_stalk st.mult_stalk (st.zero_stalk V) (st.one_stalk V) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pi.add_local_ring_at) (pi.mult_local_ring_at) (pi.zero_local_ring_at) (pi.one_local_ring_at)" using key_ring_morphism stalk_at_prime_is_iso_to_local_ring_at_prime_aux assms by meson end (* key_map *) (* def. 0.42 *) locale locally_ringed_space = ringed_space + assumes stalks_are_local: "\<And>x U. x \<in> U \<Longrightarrow> is_open U \<Longrightarrow> stalk.is_local is_open \<FF> \<rho> add_str mult_str zero_str one_str (neighborhoods x) x U" context comm_ring begin interpretation pr: presheaf_of_rings "Spec" is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec by (simp add: comm_ring.sheaf_spec_is_presheaf local.comm_ring_axioms) (* ex. 0.43 *) lemma spec_is_locally_ringed_space: shows "locally_ringed_space Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec" proof (intro locally_ringed_space.intro locally_ringed_space_axioms.intro) interpret sh: sheaf_of_rings Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec using sheaf_spec_is_sheaf . show "ringed_space Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec" using spec_is_ringed_space by simp show "stalk.is_local is_zariski_open sheaf_spec sheaf_spec_morphisms add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec (pr.neighborhoods \<pp>) \<pp> U" if "\<pp> \<in> U" "is_zariski_open U" for \<pp> U proof - interpret st: stalk Spec is_zariski_open sheaf_spec sheaf_spec_morphisms \<O>b add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec "pr.neighborhoods \<pp>" \<pp> proof show "\<pp> \<in> Spec" by (meson in_mono that zariski_open_is_subset) qed (auto simp: pr.neighborhoods_def) interpret pri: pr_ideal R \<pp> "(+)" "(\<cdot>)" \<zero> \<one> by (simp add: spectrum_imp_pr st.is_elem) interpret km: key_map R "(+)" "(\<cdot>)" \<zero> \<one> \<pp> proof qed (simp add: st.is_elem) have "ring st.carrier_stalk st.add_stalk st.mult_stalk (st.zero_stalk U) (st.one_stalk U)" using st.stalk_is_ring sheaf_spec_is_presheaf \<open>is_zariski_open U\<close> \<open>\<pp> \<in> U\<close> by blast also have "local_ring pri.carrier_local_ring_at pri.add_local_ring_at pri.mult_local_ring_at pri.zero_local_ring_at pri.one_local_ring_at" using pr_ideal.local_ring_at_is_local by (simp add: pr_ideal.local_ring_at_is_local spectrum_imp_pr st.is_elem) moreover note st.subset_of_opens [simp del] have "\<exists>f. ring_isomorphism f st.carrier_stalk st.add_stalk st.mult_stalk (st.zero_stalk U) (st.one_stalk U) (R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>) (pr_ideal.add_local_ring_at R \<pp> (+) (\<cdot>) \<zero>) (pr_ideal.mult_local_ring_at R \<pp> (+) (\<cdot>) \<zero>) (pr_ideal.zero_local_ring_at R \<pp> (+) (\<cdot>) \<zero> \<one>) (pr_ideal.one_local_ring_at R \<pp> (+) (\<cdot>) \<zero> \<one>)" by (simp add: km.stalk_at_prime_is_iso_to_local_ring_at_prime st.index that) ultimately show "stalk.is_local is_zariski_open sheaf_spec sheaf_spec_morphisms add_sheaf_spec mult_sheaf_spec zero_sheaf_spec one_sheaf_spec (pr.neighborhoods \<pp>) \<pp> U" using isomorphic_to_local_is_local \<open>\<pp> \<in> U\<close> \<open>is_zariski_open U\<close> st.is_local_def by fastforce qed qed end (* comm_ring *) (* Construction 0.44: induced morphism between direct limits *) locale ind_mor_btw_stalks = morphism_ringed_spaces + fixes x::"'a" assumes is_elem: "x \<in> X" begin interpretation stx:stalk X is_open\<^sub>X \<O>\<^sub>X \<rho>\<^sub>X b add_str\<^sub>X mult_str\<^sub>X zero_str\<^sub>X one_str\<^sub>X "{U. is_open\<^sub>X U \<and> x \<in> U}" "x" proof qed (auto simp: is_elem) interpretation stfx: stalk Y is_open\<^sub>Y \<O>\<^sub>Y \<rho>\<^sub>Y d add_str\<^sub>Y mult_str\<^sub>Y zero_str\<^sub>Y one_str\<^sub>Y "{U. is_open\<^sub>Y U \<and> (f x) \<in> U}" "f x" proof qed (auto simp: is_elem) definition induced_morphism:: "('c set \<times> 'd) set \<Rightarrow> ('a set \<times> 'b) set" where "induced_morphism \<equiv> \<lambda>C \<in> stfx.carrier_stalk. let r = (SOME r. r \<in> C) in stx.class_of (f\<^sup>\<inverse> X (fst r)) (\<phi>\<^sub>f (fst r) (snd r))" (* One should think of fst r as a V in index, and snd r as a d in \<O>\<^sub>Y V. *) lemma phi_in_O: assumes "is_open\<^sub>Y V" "q \<in> \<O>\<^sub>Y V" shows "\<phi>\<^sub>f V q \<in> \<O>\<^sub>X (f \<^sup>\<inverse> X (V))" using is_morphism_of_sheaves morphism_presheaves_of_rings.fam_morphisms_are_maps unfolding morphism_sheaves_of_rings_def by (metis assms local.im_sheaf_def map.map_closed) lemma induced_morphism_is_well_defined: assumes "stfx.rel (V,q) (V',q')" shows "stx.class_of (f\<^sup>\<inverse> X V) (\<phi>\<^sub>f V q) = stx.class_of (f\<^sup>\<inverse> X V') (\<phi>\<^sub>f V' q')" proof - obtain W where W: "is_open\<^sub>Y W" "f x \<in> W" "W \<subseteq> V" "W \<subseteq> V'" and eq: "\<rho>\<^sub>Y V W q = \<rho>\<^sub>Y V' W q'" using assms stfx.rel_def by auto show ?thesis proof (rule stx.class_of_eqI) show "(f \<^sup>\<inverse> X V, \<phi>\<^sub>f V q) \<in> Sigma {U. is_open\<^sub>X U \<and> x \<in> U} \<O>\<^sub>X" using is_continuous phi_in_O assms stfx.rel_def stx.is_elem by auto show "(f \<^sup>\<inverse> X V', \<phi>\<^sub>f V' q') \<in> Sigma {U. is_open\<^sub>X U \<and> x \<in> U} \<O>\<^sub>X" using is_continuous phi_in_O assms stfx.rel_def stx.is_elem by auto show "f \<^sup>\<inverse> X W \<in> {U. is_open\<^sub>X U \<and> x \<in> U}" using W is_continuous stx.is_elem by auto show "f \<^sup>\<inverse> X W \<subseteq> f \<^sup>\<inverse> X V \<inter> f \<^sup>\<inverse> X V'" using W by blast interpret Y: morphism_sheaves_of_rings Y is_open\<^sub>Y \<O>\<^sub>Y \<rho>\<^sub>Y d add_str\<^sub>Y mult_str\<^sub>Y zero_str\<^sub>Y one_str\<^sub>Y local.im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf \<phi>\<^sub>f by (rule is_morphism_of_sheaves) have "\<rho>\<^sub>X (f\<^sup>\<inverse> X V) (f\<^sup>\<inverse> X W) (\<phi>\<^sub>f V q) = \<phi>\<^sub>f W (\<rho>\<^sub>Y V W q)" using assms Y.comm_diagrams W by (simp add: stfx.rel_def im_sheaf_morphisms_def o_def) also have "\<dots> = \<phi>\<^sub>f W (\<rho>\<^sub>Y V' W q')" by (simp add: eq) also have "\<dots> = \<rho>\<^sub>X (f\<^sup>\<inverse> X V') (f\<^sup>\<inverse> X W) (\<phi>\<^sub>f V' q')" using assms Y.comm_diagrams W by (simp add: stfx.rel_def im_sheaf_morphisms_def o_def) finally show "\<rho>\<^sub>X (f \<^sup>\<inverse> X V) (f \<^sup>\<inverse> X W) (\<phi>\<^sub>f V q) = \<rho>\<^sub>X (f \<^sup>\<inverse> X V') (f \<^sup>\<inverse> X W) (\<phi>\<^sub>f V' q')" . qed qed lemma induced_morphism_eq: assumes "C \<in> stfx.carrier_stalk" obtains V q where "(V,q) \<in> C" "induced_morphism C = stx.class_of (f\<^sup>\<inverse> X V) (\<phi>\<^sub>f V q)" by (metis (mono_tags, lifting) assms induced_morphism_def prod.exhaust_sel restrict_apply stfx.carrier_stalk_def stfx.neighborhoods_eq stfx.rel_carrier_Eps_in(1)) lemma induced_morphism_eval: assumes "C \<in> stfx.carrier_stalk" and "r \<in> C" shows "induced_morphism C = stx.class_of (f\<^sup>\<inverse> X (fst r)) (\<phi>\<^sub>f (fst r) (snd r))" by (smt (verit, best) assms induced_morphism_eq induced_morphism_is_well_defined prod.exhaust_sel stfx.carrier_direct_limE stfx.carrier_stalk_def stfx.neighborhoods_eq stfx.rel_I1) proposition ring_homomorphism_induced_morphism: assumes "is_open\<^sub>Y V" and "f x \<in> V" shows "ring_homomorphism induced_morphism stfx.carrier_stalk stfx.add_stalk stfx.mult_stalk (stfx.zero_stalk V) (stfx.one_stalk V) stx.carrier_stalk stx.add_stalk stx.mult_stalk (stx.zero_stalk (f\<^sup>\<inverse> X V)) (stx.one_stalk (f\<^sup>\<inverse> X V))" proof intro_locales interpret phif: ring_homomorphism "\<phi>\<^sub>f V" "\<O>\<^sub>Y V" "add_str\<^sub>Y V" "mult_str\<^sub>Y V" "zero_str\<^sub>Y V" "one_str\<^sub>Y V" "local.im_sheaf V" "add_im_sheaf V" "mult_im_sheaf V" "zero_im_sheaf V" "one_im_sheaf V" by (metis assms(1) is_morphism_of_sheaves morphism_presheaves_of_rings.is_ring_morphism morphism_sheaves_of_rings_def) interpret V: ring stfx.carrier_direct_lim stfx.add_rel stfx.mult_rel "stfx.class_of V (zero_str\<^sub>Y V)" "stfx.class_of V (one_str\<^sub>Y V)" using assms stfx.direct_lim_is_ring by force interpret X: ring stx.carrier_direct_lim stx.add_rel stx.mult_rel "stx.class_of X (zero_str\<^sub>X X)" "stx.class_of X (one_str\<^sub>X X)" using stx.direct_lim_is_ring stx.is_elem by auto interpret dlY: direct_lim Y is_open\<^sub>Y \<O>\<^sub>Y \<rho>\<^sub>Y d add_str\<^sub>Y mult_str\<^sub>Y zero_str\<^sub>Y one_str\<^sub>Y "target.neighborhoods (f x)" using stfx.direct_lim_axioms stfx.neighborhoods_eq by force interpret eqY: equivalence "Sigma {U. is_open\<^sub>Y U \<and> f x \<in> U} \<O>\<^sub>Y" "{(x, y). stfx.rel x y}" using stfx.rel_is_equivalence by blast interpret morphY: morphism_sheaves_of_rings Y is_open\<^sub>Y \<O>\<^sub>Y \<rho>\<^sub>Y d add_str\<^sub>Y mult_str\<^sub>Y zero_str\<^sub>Y one_str\<^sub>Y local.im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf \<phi>\<^sub>f by (rule is_morphism_of_sheaves) have 0 [iff]: "stfx.zero_stalk V \<in> stfx.carrier_stalk" using stfx.carrier_stalk_def stfx.neighborhoods_eq stfx.zero_stalk_def by auto have 1 [iff]: "stfx.one_stalk V \<in> stfx.carrier_stalk" using stfx.carrier_stalk_def stfx.neighborhoods_eq stfx.one_stalk_def by auto show "Set_Theory.map induced_morphism stfx.carrier_stalk stx.carrier_stalk" proof show "induced_morphism \<in> stfx.carrier_stalk \<rightarrow>\<^sub>E stx.carrier_stalk" proof fix C assume C: "C \<in> stfx.carrier_stalk" then obtain r where "r \<in> C" by (metis stfx.carrier_stalk_def stfx.rel_carrier_Eps_in(1) target.neighborhoods_def) moreover have "is_open\<^sub>X (f \<^sup>\<inverse> X (fst r))" by (metis (no_types, lifting) C SigmaD1 \<open>r \<in> C\<close> eqY.block_closed is_continuous prod.exhaust_sel stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq stfx.subset_of_opens) ultimately have "stx.class_of (f \<^sup>\<inverse> X (fst r)) (\<phi>\<^sub>f (fst r) (snd r)) \<in> stx.carrier_stalk" by (smt (verit, best) C IntI dlY.carrier_direct_limE mem_Collect_eq phi_in_O stfx.carrier_stalk_def stfx.neighborhoods_eq stfx.rel_I1 stfx.rel_def stx.class_of_in_stalk stx.is_elem stx.neighborhoods_eq vimage_def) then show "induced_morphism C \<in> stx.carrier_stalk" using C \<open>r \<in> C\<close> induced_morphism_eval by presburger qed (simp add: induced_morphism_def) qed show "Group_Theory.monoid stfx.carrier_stalk stfx.add_stalk (stfx.zero_stalk V)" by (simp add: V.additive.monoid_axioms stfx.add_stalk_def stfx.carrier_stalk_def stfx.neighborhoods_eq stfx.zero_stalk_def) show "Group_Theory.group_axioms stfx.carrier_stalk stfx.add_stalk (stfx.zero_stalk V)" using Group_Theory.group_def V.additive.group_axioms stfx.add_stalk_def stfx.carrier_stalk_def stfx.zero_stalk_def target.neighborhoods_def by fastforce show "commutative_monoid_axioms stfx.carrier_stalk stfx.add_stalk" using V.additive.commutative_monoid_axioms commutative_monoid_def stfx.add_stalk_def stfx.carrier_stalk_def target.neighborhoods_def by fastforce show "Group_Theory.monoid stfx.carrier_stalk stfx.mult_stalk (stfx.one_stalk V)" by (simp add: V.multiplicative.monoid_axioms stfx.carrier_stalk_def stfx.mult_stalk_def stfx.neighborhoods_eq stfx.one_stalk_def) show "ring_axioms stfx.carrier_stalk stfx.add_stalk stfx.mult_stalk" by (metis (no_types, lifting) V.additive.unit_closed mem_Collect_eq ring_def stfx.carrier_direct_limE stfx.stalk_is_ring) show "Group_Theory.monoid stx.carrier_stalk stx.add_stalk (stx.zero_stalk (f \<^sup>\<inverse> X V))" using abelian_group_def assms commutative_monoid_def is_continuous ring_def stx.is_elem stx.stalk_is_ring by fastforce show "Group_Theory.group_axioms stx.carrier_stalk stx.add_stalk (stx.zero_stalk (f \<^sup>\<inverse> X V))" using Group_Theory.group_def abelian_group_def assms is_continuous ring_def stx.is_elem stx.stalk_is_ring by fastforce show "commutative_monoid_axioms stx.carrier_stalk stx.add_stalk" using X.additive.commutative_monoid_axioms commutative_monoid_def neighborhoods_def stx.add_stalk_def stx.carrier_stalk_def by fastforce show "Group_Theory.monoid stx.carrier_stalk stx.mult_stalk (stx.one_stalk (f \<^sup>\<inverse> X V))" using assms is_continuous ring_def stx.is_elem stx.stalk_is_ring by fastforce show "ring_axioms stx.carrier_stalk stx.add_stalk stx.mult_stalk" using X.ring_axioms ring_def stx.add_stalk_def stx.carrier_stalk_def stx.mult_stalk_def stx.neighborhoods_eq by fastforce show "monoid_homomorphism_axioms induced_morphism stfx.carrier_stalk stfx.add_stalk (stfx.zero_stalk V) stx.add_stalk (stx.zero_stalk (f \<^sup>\<inverse> X V))" proof fix C C' assume CC: "C \<in> stfx.carrier_stalk" "C' \<in> stfx.carrier_stalk" show "induced_morphism (stfx.add_stalk C C') = stx.add_stalk (induced_morphism C) (induced_morphism C')" proof - obtain U q U' q' where Uq: "(U,q) \<in> C" "(U',q') \<in> C'" and eq: "induced_morphism C = stx.class_of (f\<^sup>\<inverse> X U) (\<phi>\<^sub>f U q)" and eq': "induced_morphism C' = stx.class_of (f\<^sup>\<inverse> X U') (\<phi>\<^sub>f U' q')" by (metis (no_types, lifting) CC induced_morphism_eq) then obtain cc [simp]: "is_open\<^sub>Y (U \<inter> U')" "f x \<in> U" "f x \<in> U'" using CC eqY.block_closed stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq target.open_inter by force then interpret cc_rh: ring_homomorphism "\<phi>\<^sub>f (U \<inter> U')" "\<O>\<^sub>Y (U \<inter> U')" "add_str\<^sub>Y (U \<inter> U')" "mult_str\<^sub>Y (U \<inter> U')" "zero_str\<^sub>Y (U \<inter> U')" "one_str\<^sub>Y (U \<inter> U')" "local.im_sheaf (U \<inter> U')" "add_im_sheaf (U \<inter> U')" "mult_im_sheaf (U \<inter> U')" "zero_im_sheaf (U \<inter> U')" "one_im_sheaf (U \<inter> U')" by (metis is_morphism_of_sheaves morphism_presheaves_of_rings.is_ring_morphism morphism_sheaves_of_rings_def) obtain opeU [simp]: "is_open\<^sub>Y U" "is_open\<^sub>Y U'" by (metis (no_types, lifting) CC SigmaD1 Uq dlY.subset_of_opens eqY.block_closed stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq) obtain [simp]: "q \<in> \<O>\<^sub>Y U" "q' \<in> \<O>\<^sub>Y U'" using CC Uq stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq by auto define add where "add \<equiv> add_str\<^sub>Y (U \<inter> U') (\<rho>\<^sub>Y U (U \<inter> U') q) (\<rho>\<^sub>Y U' (U \<inter> U') q')" have add_stalk_eq_class: "stfx.add_stalk C C' = stfx.class_of (U \<inter> U') add" using CC unfolding add_def stfx.add_stalk_def stfx.carrier_stalk_def dlY.carrier_direct_lim_def by (smt (verit, best) IntI Int_commute Uq cc eqY.Block_self eqY.block_closed inf.cobounded1 mem_Collect_eq stfx.add_rel_class_of stfx.class_of_def stfx.neighborhoods_eq) then have C: "(stfx.class_of (U \<inter> U') add) \<in> stfx.carrier_stalk" using CC \<open>Group_Theory.monoid stfx.carrier_stalk stfx.add_stalk (stfx.zero_stalk V)\<close> monoid.composition_closed by fastforce have add_in: "add \<in> \<O>\<^sub>Y (U \<inter> U')" apply (simp add: add_def) using cc_rh.source.additive.composition_closed\<open>q \<in> \<O>\<^sub>Y U\<close> \<open>q' \<in> \<O>\<^sub>Y U'\<close> by (metis Int_commute cc(1) codom.is_map_from_is_homomorphism inf.cobounded1 map.map_closed opeU) obtain V r where Vr: "(V,r) \<in> stfx.add_stalk C C'" and eq: "induced_morphism (stfx.add_stalk C C') = stx.class_of (f \<^sup>\<inverse> X V) (\<phi>\<^sub>f V r)" using induced_morphism_eq add_stalk_eq_class C by auto have "is_open\<^sub>Y V" by (smt (verit, best) C SigmaD1 Vr add_stalk_eq_class dlY.subset_of_opens eqY.block_closed stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq) have "r \<in> \<O>\<^sub>Y V" by (smt (verit, best) IntI Vr add_stalk_eq_class add_in cc fst_conv mem_Collect_eq snd_conv stfx.rel_I1 stfx.rel_def) have fxV: "f x \<in> V" using C Vr add_stalk_eq_class stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq by auto have fXUU: "is_open\<^sub>X (f\<^sup>\<inverse> X (U \<inter> U'))" using cc(1) is_continuous by presburger have "(U \<inter> U', add) \<in> stfx.class_of V r" by (metis (no_types, lifting) IntI Vr add_stalk_eq_class add_in cc mem_Collect_eq stfx.class_of_def stfx.rel_Class_iff stfx.rel_I1) then have "stfx.rel (V, r) (U \<inter> U', add)" by (simp add: fxV \<open>is_open\<^sub>Y V\<close> \<open>r \<in> \<O>\<^sub>Y V\<close> stfx.rel_I1) then have "induced_morphism (stfx.add_stalk C C') = stx.class_of (f\<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f (U \<inter> U') add)" using eq induced_morphism_is_well_defined by presburger moreover have "stx.add_stalk (induced_morphism C) (induced_morphism C') = stx.add_stalk (stx.class_of (f \<^sup>\<inverse> X U) (\<phi>\<^sub>f U q)) (stx.class_of (f \<^sup>\<inverse> X U') (\<phi>\<^sub>f U' q'))" using CC(1) Uq(1) eq' induced_morphism_eval by auto moreover have "\<dots> = stx.class_of (f\<^sup>\<inverse> X (U \<inter> U')) (add_str\<^sub>X (f\<^sup>\<inverse> X (U \<inter> U')) (\<rho>\<^sub>X (f\<^sup>\<inverse> X (U)) (f\<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f (U) (q))) (\<rho>\<^sub>X (f\<^sup>\<inverse> X (U')) (f\<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f (U') (q'))) )" unfolding stx.add_stalk_def using is_continuous phi_in_O stx.is_elem fXUU by (intro stx.add_rel_class_of) auto moreover have "\<phi>\<^sub>f (U \<inter> U') add = add_str\<^sub>X (f\<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f (U \<inter> U') (\<rho>\<^sub>Y (U) (U \<inter> U') (q))) (\<phi>\<^sub>f (U \<inter> U') (\<rho>\<^sub>Y (U') (U \<inter> U') (q')))" unfolding add_def proof (subst cc_rh.additive.commutes_with_composition) show "\<rho>\<^sub>Y U (U \<inter> U') q \<in> \<O>\<^sub>Y (U \<inter> U')" by (metis \<open>q \<in> \<O>\<^sub>Y U\<close> cc(1) codom.is_map_from_is_homomorphism inf.cobounded1 map.map_closed opeU(1)) show "\<rho>\<^sub>Y U' (U \<inter> U') q' \<in> \<O>\<^sub>Y (U \<inter> U')" by (metis \<open>q' \<in> \<O>\<^sub>Y U'\<close> cc(1) codom.is_map_from_is_homomorphism inf.commute inf_le1 map.map_closed opeU(2)) qed (auto simp: add_im_sheaf_def) moreover have "\<dots> = add_str\<^sub>X (f\<^sup>\<inverse> X (U \<inter> U')) (\<rho>\<^sub>X (f\<^sup>\<inverse> X (U)) (f\<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f (U) (q))) (\<rho>\<^sub>X (f\<^sup>\<inverse> X U') (f\<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f (U') (q')))" using assms apply (simp add: stfx.rel_def morphY.comm_diagrams [symmetric, unfolded o_def]) using im_sheaf_morphisms_def by fastforce ultimately show ?thesis by simp qed next have "induced_morphism (stfx.zero_stalk V) = stx.class_of (f\<^sup>\<inverse> X V) (\<phi>\<^sub>f V (zero_str\<^sub>Y V))" using induced_morphism_eval [OF 0, where r = "(V, zero_str\<^sub>Y V)"] assms by force also have "\<dots> = stx.zero_stalk (f \<^sup>\<inverse> X V)" by (simp add: phif.additive.commutes_with_unit zero_im_sheaf_def stx.zero_stalk_def) finally show "induced_morphism (stfx.zero_stalk V) = stx.zero_stalk (f \<^sup>\<inverse> X V)" . qed show "monoid_homomorphism_axioms induced_morphism stfx.carrier_stalk stfx.mult_stalk (stfx.one_stalk V) stx.mult_stalk (stx.one_stalk (f \<^sup>\<inverse> X V))" proof fix C C' assume CC: "C \<in> stfx.carrier_stalk" "C' \<in> stfx.carrier_stalk" show "induced_morphism (stfx.mult_stalk C C') = stx.mult_stalk (induced_morphism C) (induced_morphism C')" proof - obtain U q U' q' where Uq: "(U,q) \<in> C" "(U',q') \<in> C'" and eq: "induced_morphism C = stx.class_of (f\<^sup>\<inverse> X U) (\<phi>\<^sub>f U q)" and eq': "induced_morphism C' = stx.class_of (f\<^sup>\<inverse> X U') (\<phi>\<^sub>f U' q')" by (metis (no_types, lifting) CC induced_morphism_eq) then obtain cc [simp]: "is_open\<^sub>Y (U \<inter> U')" "f x \<in> U" "f x \<in> U'" using CC eqY.block_closed stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq target.open_inter by force then interpret cc_rh: ring_homomorphism "\<phi>\<^sub>f (U \<inter> U')" "\<O>\<^sub>Y (U \<inter> U')" "add_str\<^sub>Y (U \<inter> U')" "mult_str\<^sub>Y (U \<inter> U')" "zero_str\<^sub>Y (U \<inter> U')" "one_str\<^sub>Y (U \<inter> U')" "local.im_sheaf (U \<inter> U')" "add_im_sheaf (U \<inter> U')" "mult_im_sheaf (U \<inter> U')" "zero_im_sheaf (U \<inter> U')" "one_im_sheaf (U \<inter> U')" by (metis is_morphism_of_sheaves morphism_presheaves_of_rings.is_ring_morphism morphism_sheaves_of_rings_def) obtain opeU [simp]: "is_open\<^sub>Y U" "is_open\<^sub>Y U'" by (metis (no_types, lifting) CC SigmaD1 Uq dlY.subset_of_opens eqY.block_closed stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq) obtain [simp]: "q \<in> \<O>\<^sub>Y U" "q' \<in> \<O>\<^sub>Y U'" using CC Uq stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq by auto define mult where "mult \<equiv> mult_str\<^sub>Y (U \<inter> U') (\<rho>\<^sub>Y U (U \<inter> U') q) (\<rho>\<^sub>Y U' (U \<inter> U') q')" have mult_stalk_eq_class: "stfx.mult_stalk C C' = stfx.class_of (U \<inter> U') mult" using CC unfolding mult_def stfx.mult_stalk_def stfx.carrier_stalk_def dlY.carrier_direct_lim_def by (smt (verit, best) IntI Int_commute Uq cc eqY.Block_self eqY.block_closed inf.cobounded1 mem_Collect_eq stfx.mult_rel_class_of stfx.class_of_def stfx.neighborhoods_eq) then have C: "(stfx.class_of (U \<inter> U') mult) \<in> stfx.carrier_stalk" by (metis CC V.multiplicative.monoid_axioms monoid.composition_closed stfx.carrier_stalk_def stfx.mult_stalk_def stfx.neighborhoods_eq) have mult_in: "mult \<in> \<O>\<^sub>Y (U \<inter> U')" apply (simp add: mult_def) using cc_rh.source.additive.composition_closed\<open>q \<in> \<O>\<^sub>Y U\<close> \<open>q' \<in> \<O>\<^sub>Y U'\<close> by (meson cc(1) cc_rh.source.multiplicative.composition_closed codom.is_map_from_is_homomorphism inf_le1 inf_le2 map.map_closed opeU) obtain V r where Vr: "(V,r) \<in> stfx.mult_stalk C C'" and eq: "induced_morphism (stfx.mult_stalk C C') = stx.class_of (f \<^sup>\<inverse> X V) (\<phi>\<^sub>f V r)" using induced_morphism_eq mult_stalk_eq_class C by auto have "is_open\<^sub>Y V" by (smt (verit, best) C SigmaD1 Vr mult_stalk_eq_class dlY.subset_of_opens eqY.block_closed stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq) have "r \<in> \<O>\<^sub>Y V" by (smt (verit, best) IntI Vr mult_stalk_eq_class mult_in cc fst_conv mem_Collect_eq snd_conv stfx.rel_I1 stfx.rel_def) have fxV: "f x \<in> V" using C Vr mult_stalk_eq_class stfx.carrier_direct_lim_def stfx.carrier_stalk_def stfx.neighborhoods_eq by auto have fXUU: "is_open\<^sub>X (f\<^sup>\<inverse> X (U \<inter> U'))" using cc(1) is_continuous by presburger have "(U \<inter> U', mult) \<in> stfx.class_of V r" by (metis (no_types, lifting) IntI Vr mult_stalk_eq_class mult_in cc mem_Collect_eq stfx.class_of_def stfx.rel_Class_iff stfx.rel_I1) then have "stfx.rel (V, r) (U \<inter> U', mult)" by (simp add: fxV \<open>is_open\<^sub>Y V\<close> \<open>r \<in> \<O>\<^sub>Y V\<close> stfx.rel_I1) then have "induced_morphism (stfx.mult_stalk C C') = stx.class_of (f\<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f (U \<inter> U') mult)" using eq induced_morphism_is_well_defined by presburger moreover have "stx.mult_stalk (induced_morphism C) (induced_morphism C') = stx.mult_stalk (stx.class_of (f \<^sup>\<inverse> X U) (\<phi>\<^sub>f U q)) (stx.class_of (f \<^sup>\<inverse> X U') (\<phi>\<^sub>f U' q'))" using CC(1) Uq(1) eq' induced_morphism_eval by auto moreover have "\<dots> = stx.class_of (f\<^sup>\<inverse> X (U \<inter> U')) (mult_str\<^sub>X (f\<^sup>\<inverse> X (U \<inter> U')) (\<rho>\<^sub>X (f \<^sup>\<inverse> X U) (f \<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f U q)) (\<rho>\<^sub>X (f \<^sup>\<inverse> X U') (f \<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f U' q')))" unfolding stx.mult_stalk_def using is_continuous phi_in_O stx.is_elem fXUU by (intro stx.mult_rel_class_of) auto moreover have "\<phi>\<^sub>f (U \<inter> U') mult = mult_str\<^sub>X (f\<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f (U \<inter> U') (\<rho>\<^sub>Y U (U \<inter> U') q)) (\<phi>\<^sub>f (U \<inter> U') (\<rho>\<^sub>Y U' (U \<inter> U') q'))" unfolding mult_def proof (subst cc_rh.multiplicative.commutes_with_composition) show "\<rho>\<^sub>Y U (U \<inter> U') q \<in> \<O>\<^sub>Y (U \<inter> U')" by (metis \<open>q \<in> \<O>\<^sub>Y U\<close> cc(1) codom.is_map_from_is_homomorphism inf.cobounded1 map.map_closed opeU(1)) show "\<rho>\<^sub>Y U' (U \<inter> U') q' \<in> \<O>\<^sub>Y (U \<inter> U')" by (metis \<open>q' \<in> \<O>\<^sub>Y U'\<close> cc(1) codom.is_map_from_is_homomorphism inf.commute inf_le1 map.map_closed opeU(2)) qed (auto simp: mult_im_sheaf_def) moreover have "\<dots> = mult_str\<^sub>X (f\<^sup>\<inverse> X (U \<inter> U')) (\<rho>\<^sub>X (f \<^sup>\<inverse> X U) (f \<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f U q)) (\<rho>\<^sub>X (f \<^sup>\<inverse> X U') (f \<^sup>\<inverse> X (U \<inter> U')) (\<phi>\<^sub>f U' q'))" using assms im_sheaf_morphisms_def by (fastforce simp: stfx.rel_def morphY.comm_diagrams [symmetric, unfolded o_def]) ultimately show ?thesis by simp qed next have "induced_morphism (stfx.one_stalk V) = stx.class_of (f\<^sup>\<inverse> X V) (\<phi>\<^sub>f V (one_str\<^sub>Y V))" using induced_morphism_eval [OF 1, where r = "(V, one_str\<^sub>Y V)"] assms by force also have "\<dots> = stx.one_stalk (f \<^sup>\<inverse> X V)" by (simp add: phif.multiplicative.commutes_with_unit one_im_sheaf_def stx.one_stalk_def) finally show "induced_morphism (stfx.one_stalk V) = stx.one_stalk (f \<^sup>\<inverse> X V)" . qed qed definition is_local:: "'c set \<Rightarrow> (('c set \<times> 'd) set \<Rightarrow> ('a set \<times> 'b) set) \<Rightarrow> bool" where "is_local V \<phi> \<equiv> local_ring_morphism \<phi> stfx.carrier_stalk stfx.add_stalk stfx.mult_stalk (stfx.zero_stalk V) (stfx.one_stalk V) stx.carrier_stalk stx.add_stalk stx.mult_stalk (stx.zero_stalk (f\<^sup>\<inverse> X V)) (stx.one_stalk (f\<^sup>\<inverse> X V))" end (* ind_mor_btw_stalks *) notation ind_mor_btw_stalks.induced_morphism ("\<phi>\<^bsub>(3_ _ _ _/ _ _ _/ _ _ _)\<^esub>" [1000,1000,1000,1000,1000,1000,1000,1000,1000,1000]1000) lemma (in sheaf_of_rings) induced_morphism_with_id_is_id: assumes "x \<in> S" shows "\<phi>\<^bsub>S is_open \<FF> \<rho> is_open \<FF> \<rho> (identity S) (\<lambda>U. identity (\<FF> U)) x\<^esub> = (\<lambda>C\<in>(stalk.carrier_stalk is_open \<FF> \<rho> x). C)" proof - interpret im_sheaf S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open "identity S" by (metis homeomorphism.axioms(3) id_is_homeomorphism im_sheaf_def inverse_map_identity sheaf_of_rings_axioms) interpret codom: ringed_space S is_open \<FF> \<rho> b add_str mult_str zero_str one_str by (meson im_sheaf.axioms(1) im_sheaf_axioms ringed_space_def) interpret ind_mor_btw_stalks S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open \<FF> \<rho> b add_str mult_str zero_str one_str "identity S" "\<lambda>U. identity (\<FF> U)" x apply intro_locales subgoal proof - have "ring_homomorphism (identity (\<FF> U)) (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub> (local.im_sheaf U) (add_im_sheaf U) (mult_im_sheaf U) (zero_im_sheaf U) (one_im_sheaf U)" if "is_open U" for U by (smt (verit, best) id_is_mor_pr_rngs im_sheaf.add_im_sheaf_def im_sheaf.im_sheaf_def im_sheaf.mult_im_sheaf_def im_sheaf_axioms local.topological_space_axioms morphism_presheaves_of_rings.is_ring_morphism one_im_sheaf_def that topological_space.open_preimage_identity zero_im_sheaf_def) moreover have "\<forall>U V. is_open U \<longrightarrow> is_open V \<longrightarrow> V \<subseteq> U \<longrightarrow> (\<forall>x. x \<in> \<FF> U \<longrightarrow> (im_sheaf_morphisms U V \<circ> identity (\<FF> U)) x = (identity (\<FF> V) \<circ> \<rho> U V) x)" by (smt (verit, best) comp_apply im_sheaf_morphisms_def is_map_from_is_homomorphism local.im_sheaf_def map.map_closed open_preimage_identity restrict_apply') ultimately have "morphism_presheaves_of_rings_axioms is_open \<FF> \<rho> add_str mult_str zero_str one_str local.im_sheaf im_sheaf_morphisms add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf (\<lambda>U. identity (\<FF> U))" unfolding morphism_presheaves_of_rings_axioms_def by auto then show ?thesis unfolding morphism_ringed_spaces_axioms_def by intro_locales qed subgoal by (meson assms ind_mor_btw_stalks_axioms.intro) done have "(let r = SOME r. r \<in> C in direct_lim.class_of \<FF> \<rho> (neighborhoods x) (identity S \<^sup>\<inverse> S (fst r)) (identity (\<FF> (fst r)) (snd r))) = C" (is "?L= _") if "C\<in>stalk.carrier_stalk is_open \<FF> \<rho> x" for C proof - interpret stk:stalk S is_open \<FF> \<rho> b add_str mult_str zero_str one_str "neighborhoods x" x apply unfold_locales using is_elem neighborhoods_def by auto define r where "r=(SOME x. x \<in> C)" have r:"r \<in> C" "r \<in> Sigma (neighborhoods x) \<FF>" and "C = stk.class_of (fst r) (snd r)" using stk.rel_carrier_Eps_in[OF that[unfolded stk.carrier_stalk_def]] unfolding r_def by auto have "?L = stk.class_of (identity S \<^sup>\<inverse> S (fst r)) (identity (\<FF> (fst r)) (snd r))" unfolding r_def Let_def by simp also have "... = stk.class_of (fst r) (snd r)" by (metis open_preimage_identity r(1) restrict_apply stk.carrier_direct_limE stk.carrier_stalk_def stk.rel_I1 stk.rel_def stk.subset_of_opens that) also have "... = C" using \<open>C = stk.class_of (fst r) (snd r)\<close> by simp finally show ?thesis . qed then show ?thesis unfolding induced_morphism_def using is_elem neighborhoods_def by fastforce qed lemma (in locally_ringed_space) induced_morphism_with_id_is_local: assumes "x \<in> S" and V: "x \<in> V" "is_open V" shows "ind_mor_btw_stalks.is_local S is_open \<FF> \<rho> add_str mult_str zero_str one_str is_open \<FF> \<rho> add_str mult_str zero_str one_str (identity S) x V (\<phi>\<^bsub>S is_open \<FF> \<rho> is_open \<FF> \<rho> (identity S) (\<lambda>U. identity (\<FF> U)) x\<^esub>)" proof- have [simp]: "(identity S)\<^sup>\<inverse> S V = V" using assms by auto interpret stfx: stalk S is_open \<FF> \<rho> b add_str mult_str zero_str one_str "{U. is_open U \<and> (identity S x) \<in> U}" "identity S x" proof qed (use assms in auto) have "local_ring stfx.carrier_stalk stfx.add_stalk stfx.mult_stalk (stfx.zero_stalk V) (stfx.one_stalk V)" by (smt (verit, best) assms restrict_apply' stalks_are_local stfx.is_local_def stfx.neighborhoods_eq) interpret stx: stalk S is_open \<FF> \<rho> b add_str mult_str zero_str one_str "{U. is_open U \<and> x \<in> U}" "x" using \<open>x \<in> S\<close> stfx.stalk_axioms by fastforce interpret local_ring stx.carrier_stalk stx.add_stalk stx.mult_stalk "stx.zero_stalk ((identity S)\<^sup>\<inverse> S V)" "stx.one_stalk ((identity S)\<^sup>\<inverse> S V)" using V stalks_are_local stx.is_local_def stx.neighborhoods_eq by fastforce interpret imS: im_sheaf S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open "identity S" by (metis homeomorphism.axioms(3) id_is_homeomorphism im_sheaf_def inverse_map_identity sheaf_of_rings_axioms) have rh: "\<And>U. is_open U \<Longrightarrow> ring_homomorphism (identity (\<FF> U)) (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub> (imS.im_sheaf U) (imS.add_im_sheaf U) (imS.mult_im_sheaf U) (imS.zero_im_sheaf U) (imS.one_im_sheaf U)" unfolding imS.add_im_sheaf_def imS.mult_im_sheaf_def imS.one_im_sheaf_def imS.zero_im_sheaf_def imS.im_sheaf_def using id_is_mor_pr_rngs morphism_presheaves_of_rings.is_ring_morphism by fastforce interpret ind_mor_btw_stalks S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open \<FF> \<rho> b add_str mult_str zero_str one_str "identity S" "\<lambda>U. identity (\<FF> U)" x proof intro_locales show "morphism_ringed_spaces_axioms S \<FF> \<rho> b add_str mult_str zero_str one_str S is_open \<FF> \<rho> b add_str mult_str zero_str one_str (identity S) (\<lambda>U. identity (\<FF> U))" unfolding morphism_ringed_spaces_axioms_def morphism_sheaves_of_rings_def morphism_presheaves_of_rings_def morphism_presheaves_of_rings_axioms_def using rh by (auto simp add: presheaf_of_rings_axioms imS.presheaf_of_rings_axioms map.map_closed [OF is_map_from_is_homomorphism] imS.im_sheaf_morphisms_def) show "ind_mor_btw_stalks_axioms S x" by (simp add: assms(1) ind_mor_btw_stalks_axioms_def) qed have "\<phi>\<^bsub>S is_open \<FF> \<rho> is_open \<FF> \<rho> (identity S) (\<lambda>U. identity (\<FF> U)) x\<^esub> = identity stx.carrier_stalk" using induced_morphism_with_id_is_id stx.is_elem by simp then show ?thesis using id_is_local_ring_morphism is_local_def local_ring_axioms stx.is_elem by fastforce qed (* definition 0.45 *) locale morphism_locally_ringed_spaces = morphism_ringed_spaces + assumes are_local_morphisms: "\<And>x V. \<lbrakk>x \<in> X; is_open\<^sub>Y V; f x \<in> V\<rbrakk> \<Longrightarrow> ind_mor_btw_stalks.is_local X is_open\<^sub>X \<O>\<^sub>X \<rho>\<^sub>X add_str\<^sub>X mult_str\<^sub>X zero_str\<^sub>X one_str\<^sub>X is_open\<^sub>Y \<O>\<^sub>Y \<rho>\<^sub>Y add_str\<^sub>Y mult_str\<^sub>Y zero_str\<^sub>Y one_str\<^sub>Y f x V \<phi>\<^bsub>X is_open\<^sub>X \<O>\<^sub>X \<rho>\<^sub>X is_open\<^sub>Y \<O>\<^sub>Y \<rho>\<^sub>Y f \<phi>\<^sub>f x\<^esub>" lemma (in locally_ringed_space) id_to_mor_locally_ringed_spaces: shows "morphism_locally_ringed_spaces S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open \<FF> \<rho> b add_str mult_str zero_str one_str (identity S) (\<lambda>U. identity (\<FF> U))" proof intro_locales interpret idim: im_sheaf S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open "identity S" proof fix U assume "is_open U" then show "is_open (identity S \<^sup>\<inverse> S U)" by (simp add: open_inter preimage_identity_self) qed auto show "Set_Theory.map (identity S) S S" by (simp add: Set_Theory.map_def) show "continuous_map_axioms S is_open is_open (identity S)" by (simp add: continuous_map_axioms_def open_inter preimage_identity_self) have gh: "group_homomorphism (identity (\<FF> U)) (\<FF> U) +\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> (idim.im_sheaf U) (idim.add_im_sheaf U) (idim.zero_im_sheaf U)" if "is_open U" for U using that id_is_mor_pr_rngs idim.add_im_sheaf_def idim.im_sheaf_def idim.zero_im_sheaf_def morphism_presheaves_of_rings.is_ring_morphism ring_homomorphism_def by fastforce have "morphism_presheaves_of_rings_axioms is_open \<FF> \<rho> add_str mult_str zero_str one_str idim.im_sheaf idim.im_sheaf_morphisms idim.add_im_sheaf idim.mult_im_sheaf idim.zero_im_sheaf idim.one_im_sheaf (\<lambda>U. identity (\<FF> U))" unfolding morphism_presheaves_of_rings_axioms_def proof (intro conjI strip) fix U assume "is_open U" then show "ring_homomorphism (identity (\<FF> U)) (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub> (idim.im_sheaf U) (idim.add_im_sheaf U) (idim.mult_im_sheaf U) (idim.zero_im_sheaf U) (idim.one_im_sheaf U)" using id_is_mor_pr_rngs idim.add_im_sheaf_def idim.im_sheaf_def idim.mult_im_sheaf_def idim.one_im_sheaf_def idim.zero_im_sheaf_def morphism_presheaves_of_rings.is_ring_morphism by fastforce fix V x assume "is_open V" and "V \<subseteq> U" and "x \<in> \<FF> U" then show "(idim.im_sheaf_morphisms U V \<circ> identity (\<FF> U)) x = (identity (\<FF> V) \<circ> \<rho> U V) x" using \<open>is_open U\<close> by (simp add: idim.im_sheaf_morphisms_def map.map_closed [OF is_map_from_is_homomorphism]) qed then show mrs: "morphism_ringed_spaces_axioms S \<FF> \<rho> b add_str mult_str zero_str one_str S is_open \<FF> \<rho> b add_str mult_str zero_str one_str (identity S) (\<lambda>U. identity (\<FF> U))" by (simp add: idim.im_sheaf_is_presheaf morphism_presheaves_of_rings_def morphism_ringed_spaces_axioms.intro morphism_sheaves_of_rings.intro presheaf_of_rings_axioms) show "morphism_locally_ringed_spaces_axioms S is_open \<FF> \<rho> add_str mult_str zero_str one_str is_open \<FF> \<rho> add_str mult_str zero_str one_str (identity S) (\<lambda>U. identity (\<FF> U))" using induced_morphism_with_id_is_local by (simp add: morphism_locally_ringed_spaces_axioms_def) qed locale iso_locally_ringed_spaces = morphism_locally_ringed_spaces + assumes is_homeomorphism: "homeomorphism X is_open\<^sub>X Y is_open\<^sub>Y f" and is_iso_of_sheaves: "iso_sheaves_of_rings Y is_open\<^sub>Y \<O>\<^sub>Y \<rho>\<^sub>Y d add_str\<^sub>Y mult_str\<^sub>Y zero_str\<^sub>Y one_str\<^sub>Y im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf \<phi>\<^sub>f" lemma (in locally_ringed_space) id_to_iso_locally_ringed_spaces: shows "iso_locally_ringed_spaces S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open \<FF> \<rho> b add_str mult_str zero_str one_str (identity S) (\<lambda>U. identity (\<FF> U))" proof - interpret morphism_ringed_spaces S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open \<FF> \<rho> b add_str mult_str zero_str one_str "identity S" "\<lambda>U. identity (\<FF> U)" by (metis id_to_mor_locally_ringed_spaces morphism_locally_ringed_spaces_def) show ?thesis proof intro_locales show "morphism_locally_ringed_spaces_axioms S is_open \<FF> \<rho> add_str mult_str zero_str one_str is_open \<FF> \<rho> add_str mult_str zero_str one_str (identity S) (\<lambda>U. identity (\<FF> U))" by (metis id_to_mor_locally_ringed_spaces morphism_locally_ringed_spaces_def) show "iso_locally_ringed_spaces_axioms S is_open \<FF> \<rho> b add_str mult_str zero_str one_str S is_open \<FF> \<rho> b add_str mult_str zero_str one_str (identity S) (\<lambda>U. identity (\<FF> U))" unfolding iso_locally_ringed_spaces_axioms_def iso_sheaves_of_rings_def iso_presheaves_of_rings_def iso_presheaves_of_rings_axioms_def proof (intro conjI) show "homeomorphism S is_open S is_open (identity S)" using id_is_homeomorphism by blast show mor:"morphism_presheaves_of_rings S is_open \<FF> \<rho> b add_str mult_str zero_str one_str local.im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf (\<lambda>U. identity (\<FF> U))" by (simp add: is_morphism_of_sheaves morphism_sheaves_of_rings.axioms) have "morphism_presheaves_of_rings S is_open local.im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf \<FF> \<rho> b add_str mult_str zero_str one_str (\<lambda>U. identity (\<FF> U))" unfolding morphism_presheaves_of_rings_def morphism_presheaves_of_rings_axioms_def proof (intro conjI strip) show "presheaf_of_rings S is_open local.im_sheaf im_sheaf_morphisms b add_im_sheaf mult_im_sheaf zero_im_sheaf one_im_sheaf" using im_sheaf_is_presheaf by blast show "presheaf_of_rings S is_open \<FF> \<rho> b add_str mult_str zero_str one_str" by (metis mor morphism_presheaves_of_rings_def) next fix U assume "is_open U" then have "ring_homomorphism (identity (\<FF> U)) (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub> (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub>" by (smt (verit, best) im_sheaf.add_im_sheaf_def im_sheaf.mult_im_sheaf_def im_sheaf_axioms local.im_sheaf_def mor morphism_presheaves_of_rings.is_ring_morphism one_im_sheaf_def open_preimage_identity zero_im_sheaf_def) then show "ring_homomorphism (identity (\<FF> U)) (local.im_sheaf U) (add_im_sheaf U) (mult_im_sheaf U) (zero_im_sheaf U) (one_im_sheaf U) (\<FF> U) +\<^bsub>U\<^esub> \<cdot>\<^bsub>U\<^esub> \<zero>\<^bsub>U\<^esub> \<one>\<^bsub>U\<^esub>" using \<open>is_open U \<close> im_sheaf.add_im_sheaf_def im_sheaf_axioms local.im_sheaf_def mult_im_sheaf_def one_im_sheaf_def zero_im_sheaf_def by fastforce fix V x assume "is_open V" and "V \<subseteq> U" and "x \<in> local.im_sheaf U" then show "(\<rho> U V \<circ> identity (\<FF> U)) x = (identity (\<FF> V) \<circ> im_sheaf_morphisms U V) x" using map.map_closed [OF is_map_from_is_homomorphism] \<open>is_open U\<close> by (simp add: im_sheaf_morphisms_def local.im_sheaf_def) qed then show "\<exists>\<psi>. morphism_presheaves_of_rings S is_open (im_sheaf.im_sheaf S \<FF> (identity S)) (im_sheaf.im_sheaf_morphisms S \<rho> (identity S)) b (im_sheaf.add_im_sheaf S add_str (identity S)) (im_sheaf.mult_im_sheaf S mult_str (identity S)) (im_sheaf.zero_im_sheaf S zero_str (identity S)) (im_sheaf.one_im_sheaf S one_str (identity S)) \<FF> \<rho> b add_str mult_str zero_str one_str \<psi> \<and> (\<forall>U. is_open U \<longrightarrow> (\<forall>x\<in>im_sheaf.im_sheaf S \<FF> (identity S) U. (identity (\<FF> U) \<circ> \<psi> U) x = x) \<and> (\<forall>x\<in>\<FF> U. (\<psi> U \<circ> identity (\<FF> U)) x = x))" using local.im_sheaf_def by auto qed qed qed end
[GOAL] α : Type u x : Tree α ⊢ numLeaves x = numNodes x + 1 [PROOFSTEP] induction x [GOAL] case nil α : Type u ⊢ numLeaves nil = numNodes nil + 1 [PROOFSTEP] simp [*, Nat.add_comm, Nat.add_assoc, Nat.add_left_comm] [GOAL] case node α : Type u a✝² : α a✝¹ a✝ : Tree α a_ih✝¹ : numLeaves a✝¹ = numNodes a✝¹ + 1 a_ih✝ : numLeaves a✝ = numNodes a✝ + 1 ⊢ numLeaves (node a✝² a✝¹ a✝) = numNodes (node a✝² a✝¹ a✝) + 1 [PROOFSTEP] simp [*, Nat.add_comm, Nat.add_assoc, Nat.add_left_comm] [GOAL] α : Type u x : Tree α ⊢ 0 < numLeaves x [PROOFSTEP] rw [numLeaves_eq_numNodes_succ] [GOAL] α : Type u x : Tree α ⊢ 0 < numNodes x + 1 [PROOFSTEP] exact x.numNodes.zero_lt_succ [GOAL] α : Type u h : nil ≠ nil ⊢ node () (left nil) (right nil) = nil [PROOFSTEP] trivial
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel ! This file was ported from Lean 3 source module topology.fiber_bundle.trivialization ! leanprover-community/mathlib commit f2ce6086713c78a7f880485f7917ea547a215982 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Bundle import Mathlib.Topology.Algebra.Order.Field import Mathlib.Topology.LocalHomeomorph /-! # Trivializations ## Main definitions ### Basic definitions * `Trivialization F p` : structure extending local homeomorphisms, defining a local trivialization of a topological space `Z` with projection `p` and fiber `F`. * `Pretrivialization F proj` : trivialization as a local equivalence, mainly used when the topology on the total space has not yet been defined. ### Operations on bundles We provide the following operations on `Trivialization`s. * `Trivialization.compHomeomorph`: given a local trivialization `e` of a fiber bundle `p : Z → B` and a homeomorphism `h : Z' ≃ₜ Z`, returns a local trivialization of the fiber bundle `p ∘ h`. ## Implementation notes Previously, in mathlib, there was a structure `topological_vector_bundle.trivialization` which extended another structure `topological_fibre_bundle.trivialization` by a linearity hypothesis. As of PR leanprover-community/mathlib#17359, we have changed this to a single structure `Trivialization` (no namespace), together with a mixin class `trivialization.is_linear`. This permits all the *data* of a vector bundle to be held at the level of fibre bundles, so that the same trivializations can underlie an object's structure as (say) a vector bundle over `ℂ` and as a vector bundle over `ℝ`, as well as its structure simply as a fibre bundle. This might be a little surprising, given the general trend of the library to ever-increased bundling. But in this case the typical motivation for more bundling does not apply: there is no algebraic or order structure on the whole type of linear (say) trivializations of a bundle. Indeed, since trivializations only have meaning on their base sets (taking junk values outside), the type of linear trivializations is not even particularly well-behaved. -/ open TopologicalSpace Filter Set Function Bundle Topology open scoped Classical variable {ι : Type _} {B : Type _} {F : Type _} {E : B → Type _} variable (F) {Z : Type _} [TopologicalSpace B] [TopologicalSpace F] {proj : Z → B} /-- This structure contains the information left for a local trivialization (which is implemented below as `Trivialization F proj`) if the total space has not been given a topology, but we have a topology on both the fiber and the base space. Through the construction `topological_fiber_prebundle F proj` it will be possible to promote a `Pretrivialization F proj` to a `Trivialization F proj`. -/ structure Pretrivialization (proj : Z → B) extends LocalEquiv Z (B × F) where open_target : IsOpen target baseSet : Set B open_baseSet : IsOpen baseSet source_eq : source = proj ⁻¹' baseSet target_eq : target = baseSet ×ˢ univ proj_toFun : ∀ p ∈ source, (toFun p).1 = proj p #align pretrivialization Pretrivialization namespace Pretrivialization variable {F} variable (e : Pretrivialization F proj) {x : Z} /-- Coercion of a pretrivialization to a function. We don't use `e.toFun` in the `CoeFun` instance because it is actually `e.toLocalEquiv.toFun`, so `simp` will apply lemmas about `toLocalEquiv`. While we may want to switch to this behavior later, doing it mid-port will break a lot of proofs. -/ @[coe] def toFun' : Z → (B × F) := e.toFun instance : CoeFun (Pretrivialization F proj) fun _ => Z → B × F := ⟨toFun'⟩ @[ext] lemma ext' (e e' : Pretrivialization F proj) (h₁ : e.toLocalEquiv = e'.toLocalEquiv) (h₂ : e.baseSet = e'.baseSet) : e = e' := by cases e; cases e'; congr #align pretrivialization.ext Pretrivialization.ext' -- porting note: todo: move `ext` here? lemma ext {e e' : Pretrivialization F proj} (h₁ : ∀ x, e x = e' x) (h₂ : ∀ x, e.toLocalEquiv.symm x = e'.toLocalEquiv.symm x) (h₃ : e.baseSet = e'.baseSet) : e = e' := by ext1 <;> [ext1, exact h₃] · apply h₁ · apply h₂ · rw [e.source_eq, e'.source_eq, h₃] /-- If the fiber is nonempty, then the projection to -/ lemma toLocalEquiv_injective [Nonempty F] : Injective (toLocalEquiv : Pretrivialization F proj → LocalEquiv Z (B × F)) := fun e e' h => by refine ext' _ _ h ?_ simpa only [fst_image_prod, univ_nonempty, target_eq] using congr_arg (Prod.fst '' LocalEquiv.target ·) h @[simp, mfld_simps] theorem coe_coe : ⇑e.toLocalEquiv = e := rfl #align pretrivialization.coe_coe Pretrivialization.coe_coe @[simp, mfld_simps] theorem coe_fst (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_toFun x ex #align pretrivialization.coe_fst Pretrivialization.coe_fst theorem mem_source : x ∈ e.source ↔ proj x ∈ e.baseSet := by rw [e.source_eq, mem_preimage] #align pretrivialization.mem_source Pretrivialization.mem_source theorem coe_fst' (ex : proj x ∈ e.baseSet) : (e x).1 = proj x := e.coe_fst (e.mem_source.2 ex) #align pretrivialization.coe_fst' Pretrivialization.coe_fst' protected theorem eqOn : EqOn (Prod.fst ∘ e) proj e.source := fun _ hx => e.coe_fst hx #align pretrivialization.eq_on Pretrivialization.eqOn theorem mk_proj_snd (ex : x ∈ e.source) : (proj x, (e x).2) = e x := Prod.ext (e.coe_fst ex).symm rfl #align pretrivialization.mk_proj_snd Pretrivialization.mk_proj_snd theorem mk_proj_snd' (ex : proj x ∈ e.baseSet) : (proj x, (e x).2) = e x := Prod.ext (e.coe_fst' ex).symm rfl #align pretrivialization.mk_proj_snd' Pretrivialization.mk_proj_snd' /-- Composition of inverse and coercion from the subtype of the target. -/ def setSymm : e.target → Z := e.target.restrict e.toLocalEquiv.symm #align pretrivialization.set_symm Pretrivialization.setSymm theorem mem_target {x : B × F} : x ∈ e.target ↔ x.1 ∈ e.baseSet := by rw [e.target_eq, prod_univ, mem_preimage] #align pretrivialization.mem_target Pretrivialization.mem_target theorem proj_symm_apply {x : B × F} (hx : x ∈ e.target) : proj (e.toLocalEquiv.symm x) = x.1 := by have := (e.coe_fst (e.map_target hx)).symm rwa [← e.coe_coe, e.right_inv hx] at this #align pretrivialization.proj_symm_apply Pretrivialization.proj_symm_apply theorem proj_symm_apply' {b : B} {x : F} (hx : b ∈ e.baseSet) : proj (e.toLocalEquiv.symm (b, x)) = b := e.proj_symm_apply (e.mem_target.2 hx) #align pretrivialization.proj_symm_apply' Pretrivialization.proj_symm_apply' theorem proj_surjOn_baseSet [Nonempty F] : Set.SurjOn proj e.source e.baseSet := fun b hb => let ⟨y⟩ := ‹Nonempty F› ⟨e.toLocalEquiv.symm (b, y), e.toLocalEquiv.map_target <| e.mem_target.2 hb, e.proj_symm_apply' hb⟩ #align pretrivialization.proj_surj_on_base_set Pretrivialization.proj_surjOn_baseSet theorem apply_symm_apply {x : B × F} (hx : x ∈ e.target) : e (e.toLocalEquiv.symm x) = x := e.toLocalEquiv.right_inv hx #align pretrivialization.apply_symm_apply Pretrivialization.apply_symm_apply theorem apply_symm_apply' {b : B} {x : F} (hx : b ∈ e.baseSet) : e (e.toLocalEquiv.symm (b, x)) = (b, x) := e.apply_symm_apply (e.mem_target.2 hx) #align pretrivialization.apply_symm_apply' Pretrivialization.apply_symm_apply' theorem symm_apply_apply {x : Z} (hx : x ∈ e.source) : e.toLocalEquiv.symm (e x) = x := e.toLocalEquiv.left_inv hx #align pretrivialization.symm_apply_apply Pretrivialization.symm_apply_apply @[simp, mfld_simps] theorem symm_apply_mk_proj {x : Z} (ex : x ∈ e.source) : e.toLocalEquiv.symm (proj x, (e x).2) = x := by rw [← e.coe_fst ex, Prod.mk.eta, ← e.coe_coe, e.left_inv ex] #align pretrivialization.symm_apply_mk_proj Pretrivialization.symm_apply_mk_proj @[simp, mfld_simps] theorem preimage_symm_proj_baseSet : e.toLocalEquiv.symm ⁻¹' (proj ⁻¹' e.baseSet) ∩ e.target = e.target := by refine' inter_eq_right_iff_subset.mpr fun x hx => _ simp only [mem_preimage, LocalEquiv.invFun_as_coe, e.proj_symm_apply hx] exact e.mem_target.mp hx #align pretrivialization.preimage_symm_proj_base_set Pretrivialization.preimage_symm_proj_baseSet @[simp, mfld_simps] theorem preimage_symm_proj_inter (s : Set B) : e.toLocalEquiv.symm ⁻¹' (proj ⁻¹' s) ∩ e.baseSet ×ˢ univ = (s ∩ e.baseSet) ×ˢ univ := by ext ⟨x, y⟩ suffices x ∈ e.baseSet → (proj (e.toLocalEquiv.symm (x, y)) ∈ s ↔ x ∈ s) by simpa only [prod_mk_mem_set_prod_eq, mem_inter_iff, and_true_iff, mem_univ, and_congr_left_iff] intro h rw [e.proj_symm_apply' h] #align pretrivialization.preimage_symm_proj_inter Pretrivialization.preimage_symm_proj_inter theorem target_inter_preimage_symm_source_eq (e f : Pretrivialization F proj) : f.target ∩ f.toLocalEquiv.symm ⁻¹' e.source = (e.baseSet ∩ f.baseSet) ×ˢ univ := by rw [inter_comm, f.target_eq, e.source_eq, f.preimage_symm_proj_inter] #align pretrivialization.target_inter_preimage_symm_source_eq Pretrivialization.target_inter_preimage_symm_source_eq theorem trans_source (e f : Pretrivialization F proj) : (f.toLocalEquiv.symm.trans e.toLocalEquiv).source = (e.baseSet ∩ f.baseSet) ×ˢ univ := by rw [LocalEquiv.trans_source, LocalEquiv.symm_source, e.target_inter_preimage_symm_source_eq] #align pretrivialization.trans_source Pretrivialization.trans_source theorem symm_trans_symm (e e' : Pretrivialization F proj) : (e.toLocalEquiv.symm.trans e'.toLocalEquiv).symm = e'.toLocalEquiv.symm.trans e.toLocalEquiv := by rw [LocalEquiv.trans_symm_eq_symm_trans_symm, LocalEquiv.symm_symm] #align pretrivialization.symm_trans_symm Pretrivialization.symm_trans_symm theorem symm_trans_source_eq (e e' : Pretrivialization F proj) : (e.toLocalEquiv.symm.trans e'.toLocalEquiv).source = (e.baseSet ∩ e'.baseSet) ×ˢ univ := by rw [LocalEquiv.trans_source, e'.source_eq, LocalEquiv.symm_source, e.target_eq, inter_comm, e.preimage_symm_proj_inter, inter_comm] #align pretrivialization.symm_trans_source_eq Pretrivialization.symm_trans_source_eq variable (e' : Pretrivialization F (π E)) {x' : TotalSpace E} {b : B} {y : E b} theorem coe_mem_source : ↑y ∈ e'.source ↔ b ∈ e'.baseSet := e'.mem_source #align pretrivialization.coe_mem_source Pretrivialization.coe_mem_source @[simp, mfld_simps] theorem coe_coe_fst (hb : b ∈ e'.baseSet) : (e' y).1 = b := e'.coe_fst (e'.mem_source.2 hb) #align pretrivialization.coe_coe_fst Pretrivialization.coe_coe_fst theorem mk_mem_target {x : B} {y : F} : (x, y) ∈ e'.target ↔ x ∈ e'.baseSet := e'.mem_target #align pretrivialization.mk_mem_target Pretrivialization.mk_mem_target theorem symm_coe_proj {x : B} {y : F} (e' : Pretrivialization F (π E)) (h : x ∈ e'.baseSet) : (e'.toLocalEquiv.symm (x, y)).1 = x := e'.proj_symm_apply' h #align pretrivialization.symm_coe_proj Pretrivialization.symm_coe_proj section Zero variable [∀ x, Zero (E x)] /-- A fiberwise inverse to `e`. This is the function `F → E b` that induces a local inverse `B × F → total_space E` of `e` on `e.baseSet`. It is defined to be `0` outside `e.baseSet`. -/ protected noncomputable def symm (e : Pretrivialization F (π E)) (b : B) (y : F) : E b := if hb : b ∈ e.baseSet then cast (congr_arg E (e.proj_symm_apply' hb)) (e.toLocalEquiv.symm (b, y)).2 else 0 #align pretrivialization.symm Pretrivialization.symm theorem symm_apply (e : Pretrivialization F (π E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : e.symm b y = cast (congr_arg E (e.symm_coe_proj hb)) (e.toLocalEquiv.symm (b, y)).2 := dif_pos hb #align pretrivialization.symm_apply Pretrivialization.symm_apply theorem symm_apply_of_not_mem (e : Pretrivialization F (π E)) {b : B} (hb : b ∉ e.baseSet) (y : F) : e.symm b y = 0 := dif_neg hb #align pretrivialization.symm_apply_of_not_mem Pretrivialization.symm_apply_of_not_mem theorem coe_symm_of_not_mem (e : Pretrivialization F (π E)) {b : B} (hb : b ∉ e.baseSet) : (e.symm b : F → E b) = 0 := funext fun _ => dif_neg hb #align pretrivialization.coe_symm_of_not_mem Pretrivialization.coe_symm_of_not_mem theorem mk_symm (e : Pretrivialization F (π E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : totalSpaceMk b (e.symm b y) = e.toLocalEquiv.symm (b, y) := by rw [e.symm_apply hb, TotalSpace.mk_cast (e.proj_symm_apply' hb), TotalSpace.eta] #align pretrivialization.mk_symm Pretrivialization.mk_symm theorem symm_proj_apply (e : Pretrivialization F (π E)) (z : TotalSpace E) (hz : z.proj ∈ e.baseSet) : e.symm z.proj (e z).2 = z.2 := by rw [e.symm_apply hz, cast_eq_iff_heq, e.mk_proj_snd' hz, e.symm_apply_apply (e.mem_source.mpr hz)] #align pretrivialization.symm_proj_apply Pretrivialization.symm_proj_apply theorem symm_apply_apply_mk (e : Pretrivialization F (π E)) {b : B} (hb : b ∈ e.baseSet) (y : E b) : e.symm b (e (totalSpaceMk b y)).2 = y := e.symm_proj_apply (totalSpaceMk b y) hb #align pretrivialization.symm_apply_apply_mk Pretrivialization.symm_apply_apply_mk theorem apply_mk_symm (e : Pretrivialization F (π E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : e (totalSpaceMk b (e.symm b y)) = (b, y) := by rw [e.mk_symm hb, e.apply_symm_apply (e.mk_mem_target.mpr hb)] #align pretrivialization.apply_mk_symm Pretrivialization.apply_mk_symm end Zero end Pretrivialization variable [TopologicalSpace Z] [TopologicalSpace (TotalSpace E)] /-- A structure extending local homeomorphisms, defining a local trivialization of a projection `proj : Z → B` with fiber `F`, as a local homeomorphism between `Z` and `B × F` defined between two sets of the form `proj ⁻¹' baseSet` and `baseSet × F`, acting trivially on the first coordinate. -/ -- porting note: todo: was @[nolint has_nonempty_instance] structure Trivialization (proj : Z → B) extends LocalHomeomorph Z (B × F) where baseSet : Set B open_baseSet : IsOpen baseSet source_eq : source = proj ⁻¹' baseSet target_eq : target = baseSet ×ˢ univ proj_toFun : ∀ p ∈ source, (toLocalHomeomorph p).1 = proj p #align trivialization Trivialization namespace Trivialization variable {F} variable (e : Trivialization F proj) {x : Z} @[ext] lemma ext' (e e' : Trivialization F proj) (h₁ : e.toLocalHomeomorph = e'.toLocalHomeomorph) (h₂ : e.baseSet = e'.baseSet) : e = e' := by cases e; cases e'; congr #align trivialization.ext Trivialization.ext' /-- Coercion of a trivialization to a function. We don't use `e.toFun` in the `CoeFun` instance because it is actually `e.toLocalEquiv.toFun`, so `simp` will apply lemmas about `toLocalEquiv`. While we may want to switch to this behavior later, doing it mid-port will break a lot of proofs. -/ @[coe] def toFun' : Z → (B × F) := e.toFun /-- Natural identification as a `Pretrivialization`. -/ def toPretrivialization : Pretrivialization F proj := { e with } #align trivialization.to_pretrivialization Trivialization.toPretrivialization instance : CoeFun (Trivialization F proj) fun _ => Z → B × F := ⟨toFun'⟩ instance : Coe (Trivialization F proj) (Pretrivialization F proj) := ⟨toPretrivialization⟩ theorem toPretrivialization_injective : Function.Injective fun e : Trivialization F proj => e.toPretrivialization := fun e e' h => by ext1 exacts [LocalHomeomorph.toLocalEquiv_injective (congr_arg Pretrivialization.toLocalEquiv h), congr_arg Pretrivialization.baseSet h] #align trivialization.to_pretrivialization_injective Trivialization.toPretrivialization_injective @[simp, mfld_simps] theorem coe_coe : ⇑e.toLocalHomeomorph = e := rfl #align trivialization.coe_coe Trivialization.coe_coe @[simp, mfld_simps] theorem coe_fst (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_toFun x ex #align trivialization.coe_fst Trivialization.coe_fst protected theorem eqOn : EqOn (Prod.fst ∘ e) proj e.source := fun _x hx => e.coe_fst hx #align trivialization.eq_on Trivialization.eqOn theorem mem_source : x ∈ e.source ↔ proj x ∈ e.baseSet := by rw [e.source_eq, mem_preimage] #align trivialization.mem_source Trivialization.mem_source theorem coe_fst' (ex : proj x ∈ e.baseSet) : (e x).1 = proj x := e.coe_fst (e.mem_source.2 ex) #align trivialization.coe_fst' Trivialization.coe_fst' theorem mk_proj_snd (ex : x ∈ e.source) : (proj x, (e x).2) = e x := Prod.ext (e.coe_fst ex).symm rfl #align trivialization.mk_proj_snd Trivialization.mk_proj_snd theorem mk_proj_snd' (ex : proj x ∈ e.baseSet) : (proj x, (e x).2) = e x := Prod.ext (e.coe_fst' ex).symm rfl #align trivialization.mk_proj_snd' Trivialization.mk_proj_snd' theorem source_inter_preimage_target_inter (s : Set (B × F)) : e.source ∩ e ⁻¹' (e.target ∩ s) = e.source ∩ e ⁻¹' s := e.toLocalHomeomorph.source_inter_preimage_target_inter s #align trivialization.source_inter_preimage_target_inter Trivialization.source_inter_preimage_target_inter @[simp, mfld_simps] theorem coe_mk (e : LocalHomeomorph Z (B × F)) (i j k l m) (x : Z) : (Trivialization.mk e i j k l m : Trivialization F proj) x = e x := rfl #align trivialization.coe_mk Trivialization.coe_mk theorem mem_target {x : B × F} : x ∈ e.target ↔ x.1 ∈ e.baseSet := e.toPretrivialization.mem_target #align trivialization.mem_target Trivialization.mem_target theorem map_target {x : B × F} (hx : x ∈ e.target) : e.toLocalHomeomorph.symm x ∈ e.source := e.toLocalHomeomorph.map_target hx #align trivialization.map_target Trivialization.map_target theorem proj_symm_apply {x : B × F} (hx : x ∈ e.target) : proj (e.toLocalHomeomorph.symm x) = x.1 := e.toPretrivialization.proj_symm_apply hx #align trivialization.proj_symm_apply Trivialization.proj_symm_apply theorem proj_symm_apply' {b : B} {x : F} (hx : b ∈ e.baseSet) : proj (e.toLocalHomeomorph.symm (b, x)) = b := e.toPretrivialization.proj_symm_apply' hx #align trivialization.proj_symm_apply' Trivialization.proj_symm_apply' theorem proj_surjOn_baseSet [Nonempty F] : Set.SurjOn proj e.source e.baseSet := e.toPretrivialization.proj_surjOn_baseSet #align trivialization.proj_surj_on_base_set Trivialization.proj_surjOn_baseSet theorem apply_symm_apply {x : B × F} (hx : x ∈ e.target) : e (e.toLocalHomeomorph.symm x) = x := e.toLocalHomeomorph.right_inv hx #align trivialization.apply_symm_apply Trivialization.apply_symm_apply theorem apply_symm_apply' {b : B} {x : F} (hx : b ∈ e.baseSet) : e (e.toLocalHomeomorph.symm (b, x)) = (b, x) := e.toPretrivialization.apply_symm_apply' hx #align trivialization.apply_symm_apply' Trivialization.apply_symm_apply' @[simp, mfld_simps] theorem symm_apply_mk_proj (ex : x ∈ e.source) : e.toLocalHomeomorph.symm (proj x, (e x).2) = x := e.toPretrivialization.symm_apply_mk_proj ex #align trivialization.symm_apply_mk_proj Trivialization.symm_apply_mk_proj theorem symm_trans_source_eq (e e' : Trivialization F proj) : (e.toLocalEquiv.symm.trans e'.toLocalEquiv).source = (e.baseSet ∩ e'.baseSet) ×ˢ univ := Pretrivialization.symm_trans_source_eq e.toPretrivialization e' #align trivialization.symm_trans_source_eq Trivialization.symm_trans_source_eq theorem symm_trans_target_eq (e e' : Trivialization F proj) : (e.toLocalEquiv.symm.trans e'.toLocalEquiv).target = (e.baseSet ∩ e'.baseSet) ×ˢ univ := Pretrivialization.symm_trans_target_eq e.toPretrivialization e' #align trivialization.symm_trans_target_eq Trivialization.symm_trans_target_eq theorem coe_fst_eventuallyEq_proj (ex : x ∈ e.source) : Prod.fst ∘ e =ᶠ[𝓝 x] proj := mem_nhds_iff.2 ⟨e.source, fun _y hy => e.coe_fst hy, e.open_source, ex⟩ #align trivialization.coe_fst_eventually_eq_proj Trivialization.coe_fst_eventuallyEq_proj theorem coe_fst_eventuallyEq_proj' (ex : proj x ∈ e.baseSet) : Prod.fst ∘ e =ᶠ[𝓝 x] proj := e.coe_fst_eventuallyEq_proj (e.mem_source.2 ex) #align trivialization.coe_fst_eventually_eq_proj' Trivialization.coe_fst_eventuallyEq_proj' theorem map_proj_nhds (ex : x ∈ e.source) : map proj (𝓝 x) = 𝓝 (proj x) := by rw [← e.coe_fst ex, ← map_congr (e.coe_fst_eventuallyEq_proj ex), ← map_map, ← e.coe_coe, e.map_nhds_eq ex, map_fst_nhds] #align trivialization.map_proj_nhds Trivialization.map_proj_nhds theorem preimage_subset_source {s : Set B} (hb : s ⊆ e.baseSet) : proj ⁻¹' s ⊆ e.source := fun _p hp => e.mem_source.mpr (hb hp) #align trivialization.preimage_subset_source Trivialization.preimage_subset_source theorem image_preimage_eq_prod_univ {s : Set B} (hb : s ⊆ e.baseSet) : e '' (proj ⁻¹' s) = s ×ˢ univ := Subset.antisymm (image_subset_iff.mpr fun p hp => ⟨(e.proj_toFun p (e.preimage_subset_source hb hp)).symm ▸ hp, trivial⟩) fun p hp => let hp' : p ∈ e.target := e.mem_target.mpr (hb hp.1) ⟨e.invFun p, mem_preimage.mpr ((e.proj_symm_apply hp').symm ▸ hp.1), e.apply_symm_apply hp'⟩ #align trivialization.image_preimage_eq_prod_univ Trivialization.image_preimage_eq_prod_univ /-- The preimage of a subset of the base set is homeomorphic to the product with the fiber. -/ def preimageHomeomorph {s : Set B} (hb : s ⊆ e.baseSet) : proj ⁻¹' s ≃ₜ s × F := (e.toLocalHomeomorph.homeomorphOfImageSubsetSource (e.preimage_subset_source hb) (e.image_preimage_eq_prod_univ hb)).trans ((Homeomorph.Set.prod s univ).trans ((Homeomorph.refl s).prodCongr (Homeomorph.Set.univ F))) #align trivialization.preimage_homeomorph Trivialization.preimageHomeomorph @[simp] theorem preimageHomeomorph_apply {s : Set B} (hb : s ⊆ e.baseSet) (p : proj ⁻¹' s) : e.preimageHomeomorph hb p = (⟨proj p, p.2⟩, (e p).2) := Prod.ext (Subtype.ext (e.proj_toFun p (e.mem_source.mpr (hb p.2)))) rfl #align trivialization.preimage_homeomorph_apply Trivialization.preimageHomeomorph_apply @[simp] theorem preimageHomeomorph_symm_apply {s : Set B} (hb : s ⊆ e.baseSet) (p : s × F) : (e.preimageHomeomorph hb).symm p = ⟨e.symm (p.1, p.2), ((e.preimageHomeomorph hb).symm p).2⟩ := rfl #align trivialization.preimage_homeomorph_symm_apply Trivialization.preimageHomeomorph_symm_apply /-- The source is homeomorphic to the product of the base set with the fiber. -/ def sourceHomeomorphBaseSetProd : e.source ≃ₜ e.baseSet × F := (Homeomorph.setCongr e.source_eq).trans (e.preimageHomeomorph subset_rfl) #align trivialization.source_homeomorph_base_set_prod Trivialization.sourceHomeomorphBaseSetProd @[simp] theorem sourceHomeomorphBaseSetProd_apply (p : e.source) : e.sourceHomeomorphBaseSetProd p = (⟨proj p, e.mem_source.mp p.2⟩, (e p).2) := e.preimageHomeomorph_apply subset_rfl ⟨p, e.mem_source.mp p.2⟩ #align trivialization.source_homeomorph_base_set_prod_apply Trivialization.sourceHomeomorphBaseSetProd_apply @[simp] theorem sourceHomeomorphBaseSetProd_symm_apply (p : e.baseSet × F) : e.sourceHomeomorphBaseSetProd.symm p = ⟨e.symm (p.1, p.2), (e.sourceHomeomorphBaseSetProd.symm p).2⟩ := rfl #align trivialization.source_homeomorph_base_set_prod_symm_apply Trivialization.sourceHomeomorphBaseSetProd_symm_apply /-- Each fiber of a trivialization is homeomorphic to the specified fiber. -/ def preimageSingletonHomeomorph {b : B} (hb : b ∈ e.baseSet) : proj ⁻¹' {b} ≃ₜ F := .trans (e.preimageHomeomorph (Set.singleton_subset_iff.mpr hb)) <| .trans (.prodCongr (Homeomorph.homeomorphOfUnique ({b} : Set B) PUnit.{1}) (Homeomorph.refl F)) (Homeomorph.punitProd F) #align trivialization.preimage_singleton_homeomorph Trivialization.preimageSingletonHomeomorph @[simp] theorem preimageSingletonHomeomorph_apply {b : B} (hb : b ∈ e.baseSet) (p : proj ⁻¹' {b}) : e.preimageSingletonHomeomorph hb p = (e p).2 := rfl #align trivialization.preimage_singleton_homeomorph_apply Trivialization.preimageSingletonHomeomorph_apply @[simp] theorem preimageSingletonHomeomorph_symm_apply {b : B} (hb : b ∈ e.baseSet) (p : F) : (e.preimageSingletonHomeomorph hb).symm p = ⟨e.symm (b, p), by rw [mem_preimage, e.proj_symm_apply' hb, mem_singleton_iff]⟩ := rfl #align trivialization.preimage_singleton_homeomorph_symm_apply Trivialization.preimageSingletonHomeomorph_symm_apply /-- In the domain of a bundle trivialization, the projection is continuous-/ theorem continuousAt_proj (ex : x ∈ e.source) : ContinuousAt proj x := (e.map_proj_nhds ex).le #align trivialization.continuous_at_proj Trivialization.continuousAt_proj /-- Composition of a `Trivialization` and a `Homeomorph`. -/ protected def compHomeomorph {Z' : Type _} [TopologicalSpace Z'] (h : Z' ≃ₜ Z) : Trivialization F (proj ∘ h) where toLocalHomeomorph := h.toLocalHomeomorph.trans e.toLocalHomeomorph baseSet := e.baseSet open_baseSet := e.open_baseSet source_eq := by simp [source_eq, preimage_preimage, (· ∘ ·)] target_eq := by simp [target_eq] proj_toFun p hp := by have hp : h p ∈ e.source := by simpa using hp simp [hp] #align trivialization.comp_homeomorph Trivialization.compHomeomorph /-- Read off the continuity of a function `f : Z → X` at `z : Z` by transferring via a trivialization of `Z` containing `z`. -/ theorem continuousAt_of_comp_right {X : Type _} [TopologicalSpace X] {f : Z → X} {z : Z} (e : Trivialization F proj) (he : proj z ∈ e.baseSet) (hf : ContinuousAt (f ∘ e.toLocalEquiv.symm) (e z)) : ContinuousAt f z := by have hez : z ∈ e.toLocalEquiv.symm.target := by rw [LocalEquiv.symm_target, e.mem_source] exact he rwa [e.toLocalHomeomorph.symm.continuousAt_iff_continuousAt_comp_right hez, LocalHomeomorph.symm_symm] #align trivialization.continuous_at_of_comp_right Trivialization.continuousAt_of_comp_right /-- Read off the continuity of a function `f : X → Z` at `x : X` by transferring via a trivialization of `Z` containing `f x`. -/ theorem continuousAt_of_comp_left {X : Type _} [TopologicalSpace X] {f : X → Z} {x : X} (e : Trivialization F proj) (hf_proj : ContinuousAt (proj ∘ f) x) (he : proj (f x) ∈ e.baseSet) (hf : ContinuousAt (e ∘ f) x) : ContinuousAt f x := by rw [e.continuousAt_iff_continuousAt_comp_left] · exact hf rw [e.source_eq, ← preimage_comp] exact hf_proj.preimage_mem_nhds (e.open_baseSet.mem_nhds he) #align trivialization.continuous_at_of_comp_left Trivialization.continuousAt_of_comp_left variable (e' : Trivialization F (π E)) {x' : TotalSpace E} {b : B} {y : E b} protected theorem continuousOn : ContinuousOn e' e'.source := e'.continuous_toFun #align trivialization.continuous_on Trivialization.continuousOn theorem coe_mem_source : ↑y ∈ e'.source ↔ b ∈ e'.baseSet := e'.mem_source #align trivialization.coe_mem_source Trivialization.coe_mem_source @[deprecated LocalHomeomorph.open_target] theorem open_target' : IsOpen e'.target := e'.open_target #align trivialization.open_target Trivialization.open_target' @[simp, mfld_simps] theorem coe_coe_fst (hb : b ∈ e'.baseSet) : (e' y).1 = b := e'.coe_fst (e'.mem_source.2 hb) #align trivialization.coe_coe_fst Trivialization.coe_coe_fst theorem mk_mem_target {y : F} : (b, y) ∈ e'.target ↔ b ∈ e'.baseSet := e'.toPretrivialization.mem_target #align trivialization.mk_mem_target Trivialization.mk_mem_target theorem symm_apply_apply {x : TotalSpace E} (hx : x ∈ e'.source) : e'.toLocalHomeomorph.symm (e' x) = x := e'.toLocalEquiv.left_inv hx #align trivialization.symm_apply_apply Trivialization.symm_apply_apply @[simp, mfld_simps] theorem symm_coe_proj {x : B} {y : F} (e : Trivialization F (π E)) (h : x ∈ e.baseSet) : (e.toLocalHomeomorph.symm (x, y)).1 = x := e.proj_symm_apply' h #align trivialization.symm_coe_proj Trivialization.symm_coe_proj section Zero variable [∀ x, Zero (E x)] /-- A fiberwise inverse to `e'`. The function `F → E x` that induces a local inverse `B × F → total_space E` of `e'` on `e'.baseSet`. It is defined to be `0` outside `e'.baseSet`. -/ protected noncomputable def symm (e : Trivialization F (π E)) (b : B) (y : F) : E b := e.toPretrivialization.symm b y #align trivialization.symm Trivialization.symm theorem symm_apply (e : Trivialization F (π E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : e.symm b y = cast (congr_arg E (e.symm_coe_proj hb)) (e.toLocalHomeomorph.symm (b, y)).2 := dif_pos hb #align trivialization.symm_apply Trivialization.symm_apply theorem symm_apply_of_not_mem (e : Trivialization F (π E)) {b : B} (hb : b ∉ e.baseSet) (y : F) : e.symm b y = 0 := dif_neg hb #align trivialization.symm_apply_of_not_mem Trivialization.symm_apply_of_not_mem theorem mk_symm (e : Trivialization F (π E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : totalSpaceMk b (e.symm b y) = e.toLocalHomeomorph.symm (b, y) := e.toPretrivialization.mk_symm hb y #align trivialization.mk_symm Trivialization.mk_symm theorem symm_proj_apply (e : Trivialization F (π E)) (z : TotalSpace E) (hz : z.proj ∈ e.baseSet) : e.symm z.proj (e z).2 = z.2 := e.toPretrivialization.symm_proj_apply z hz #align trivialization.symm_proj_apply Trivialization.symm_proj_apply theorem symm_apply_apply_mk (e : Trivialization F (π E)) {b : B} (hb : b ∈ e.baseSet) (y : E b) : e.symm b (e (totalSpaceMk b y)).2 = y := e.symm_proj_apply (totalSpaceMk b y) hb #align trivialization.symm_apply_apply_mk Trivialization.symm_apply_apply_mk theorem apply_mk_symm (e : Trivialization F (π E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : e (totalSpaceMk b (e.symm b y)) = (b, y) := e.toPretrivialization.apply_mk_symm hb y #align trivialization.apply_mk_symm Trivialization.apply_mk_symm theorem continuousOn_symm (e : Trivialization F (π E)) : ContinuousOn (fun z : B × F => totalSpaceMk z.1 (e.symm z.1 z.2)) (e.baseSet ×ˢ univ) := by have : ∀ z ∈ e.baseSet ×ˢ (univ : Set F), totalSpaceMk z.1 (e.symm z.1 z.2) = e.toLocalHomeomorph.symm z := by rintro x ⟨hx : x.1 ∈ e.baseSet, _⟩ rw [e.mk_symm hx] refine' ContinuousOn.congr _ this rw [← e.target_eq] exact e.toLocalHomeomorph.continuousOn_symm #align trivialization.continuous_on_symm Trivialization.continuousOn_symm end Zero /-- If `e` is a `Trivialization` of `proj : Z → B` with fiber `F` and `h` is a homeomorphism `F ≃ₜ F'`, then `e.trans_fiber_homeomorph h` is the trivialization of `proj` with the fiber `F'` that sends `p : Z` to `((e p).1, h (e p).2)`. -/ def transFiberHomeomorph {F' : Type _} [TopologicalSpace F'] (e : Trivialization F proj) (h : F ≃ₜ F') : Trivialization F' proj where toLocalHomeomorph := e.toLocalHomeomorph.transHomeomorph <| (Homeomorph.refl _).prodCongr h baseSet := e.baseSet open_baseSet := e.open_baseSet source_eq := e.source_eq target_eq := by simp [target_eq, prod_univ, preimage_preimage] proj_toFun := e.proj_toFun #align trivialization.trans_fiber_homeomorph Trivialization.transFiberHomeomorph @[simp] theorem transFiberHomeomorph_apply {F' : Type _} [TopologicalSpace F'] (e : Trivialization F proj) (h : F ≃ₜ F') (x : Z) : e.transFiberHomeomorph h x = ((e x).1, h (e x).2) := rfl #align trivialization.trans_fiber_homeomorph_apply Trivialization.transFiberHomeomorph_apply /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations. See also `Trivialization.coordChangeHomeomorph` for a version bundled as `F ≃ₜ F`. -/ def coordChange (e₁ e₂ : Trivialization F proj) (b : B) (x : F) : F := (e₂ <| e₁.toLocalHomeomorph.symm (b, x)).2 #align trivialization.coord_change Trivialization.coordChange theorem mk_coordChange (e₁ e₂ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) (x : F) : (b, e₁.coordChange e₂ b x) = e₂ (e₁.toLocalHomeomorph.symm (b, x)) := by refine' Prod.ext _ rfl rw [e₂.coe_fst', ← e₁.coe_fst', e₁.apply_symm_apply' h₁] · rwa [e₁.proj_symm_apply' h₁] · rwa [e₁.proj_symm_apply' h₁] #align trivialization.mk_coord_change Trivialization.mk_coordChange theorem coordChange_apply_snd (e₁ e₂ : Trivialization F proj) {p : Z} (h : proj p ∈ e₁.baseSet) : e₁.coordChange e₂ (proj p) (e₁ p).snd = (e₂ p).snd := by rw [coordChange, e₁.symm_apply_mk_proj (e₁.mem_source.2 h)] #align trivialization.coord_change_apply_snd Trivialization.coordChange_apply_snd theorem coordChange_same_apply (e : Trivialization F proj) {b : B} (h : b ∈ e.baseSet) (x : F) : e.coordChange e b x = x := by rw [coordChange, e.apply_symm_apply' h] #align trivialization.coord_change_same_apply Trivialization.coordChange_same_apply theorem coordChange_same (e : Trivialization F proj) {b : B} (h : b ∈ e.baseSet) : e.coordChange e b = id := funext <| e.coordChange_same_apply h #align trivialization.coord_change_same Trivialization.coordChange_same theorem coordChange_coordChange (e₁ e₂ e₃ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) (x : F) : e₂.coordChange e₃ b (e₁.coordChange e₂ b x) = e₁.coordChange e₃ b x := by rw [coordChange, e₁.mk_coordChange _ h₁ h₂, ← e₂.coe_coe, e₂.left_inv, coordChange] rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] #align trivialization.coord_change_coord_change Trivialization.coordChange_coordChange theorem continuous_coordChange (e₁ e₂ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) : Continuous (e₁.coordChange e₂ b) := by refine' continuous_snd.comp (e₂.toLocalHomeomorph.continuousOn.comp_continuous (e₁.toLocalHomeomorph.continuousOn_symm.comp_continuous _ _) _) · exact continuous_const.prod_mk continuous_id · exact fun x => e₁.mem_target.2 h₁ · intro x rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] #align trivialization.continuous_coord_change Trivialization.continuous_coordChange /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations, as a homeomorphism. -/ protected def coordChangeHomeomorph (e₁ e₂ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) : F ≃ₜ F where toFun := e₁.coordChange e₂ b invFun := e₂.coordChange e₁ b left_inv x := by simp only [*, coordChange_coordChange, coordChange_same_apply] right_inv x := by simp only [*, coordChange_coordChange, coordChange_same_apply] continuous_toFun := e₁.continuous_coordChange e₂ h₁ h₂ continuous_invFun := e₂.continuous_coordChange e₁ h₂ h₁ #align trivialization.coord_change_homeomorph Trivialization.coordChangeHomeomorph @[simp] theorem coordChangeHomeomorph_coe (e₁ e₂ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) : ⇑(e₁.coordChangeHomeomorph e₂ h₁ h₂) = e₁.coordChange e₂ b := rfl #align trivialization.coord_change_homeomorph_coe Trivialization.coordChangeHomeomorph_coe variable {B' : Type _} [TopologicalSpace B'] theorem isImage_preimage_prod (e : Trivialization F proj) (s : Set B) : e.toLocalHomeomorph.IsImage (proj ⁻¹' s) (s ×ˢ univ) := fun x hx => by simp [e.coe_fst', hx] #align trivialization.is_image_preimage_prod Trivialization.isImage_preimage_prod /-- Restrict a `Trivialization` to an open set in the base. `-/ protected def restrOpen (e : Trivialization F proj) (s : Set B) (hs : IsOpen s) : Trivialization F proj where toLocalHomeomorph := ((e.isImage_preimage_prod s).symm.restr (IsOpen.inter e.open_target (hs.prod isOpen_univ))).symm baseSet := e.baseSet ∩ s open_baseSet := IsOpen.inter e.open_baseSet hs source_eq := by simp [source_eq] target_eq := by simp [target_eq, prod_univ] proj_toFun p hp := e.proj_toFun p hp.1 #align trivialization.restr_open Trivialization.restrOpen section Piecewise theorem frontier_preimage (e : Trivialization F proj) (s : Set B) : e.source ∩ frontier (proj ⁻¹' s) = proj ⁻¹' (e.baseSet ∩ frontier s) := by rw [← (e.isImage_preimage_prod s).frontier.preimage_eq, frontier_prod_univ_eq, (e.isImage_preimage_prod _).preimage_eq, e.source_eq, preimage_inter] #align trivialization.frontier_preimage Trivialization.frontier_preimage /-- Given two bundle trivializations `e`, `e'` of `proj : Z → B` and a set `s : Set B` such that the base sets of `e` and `e'` intersect `frontier s` on the same set and `e p = e' p` whenever `proj p ∈ e.baseSet ∩ frontier s`, `e.piecewise e' s Hs Heq` is the bundle trivialization over `Set.ite s e.baseSet e'.baseSet` that is equal to `e` on `proj ⁻¹ s` and is equal to `e'` otherwise. -/ noncomputable def piecewise (e e' : Trivialization F proj) (s : Set B) (Hs : e.baseSet ∩ frontier s = e'.baseSet ∩ frontier s) (Heq : EqOn e e' <| proj ⁻¹' (e.baseSet ∩ frontier s)) : Trivialization F proj where toLocalHomeomorph := e.toLocalHomeomorph.piecewise e'.toLocalHomeomorph (proj ⁻¹' s) (s ×ˢ univ) (e.isImage_preimage_prod s) (e'.isImage_preimage_prod s) (by rw [e.frontier_preimage, e'.frontier_preimage, Hs]) (by rwa [e.frontier_preimage]) baseSet := s.ite e.baseSet e'.baseSet open_baseSet := e.open_baseSet.ite e'.open_baseSet Hs source_eq := by simp [source_eq] target_eq := by simp [target_eq, prod_univ] proj_toFun p := by rintro (⟨he, hs⟩ | ⟨he, hs⟩) -- porting note: was `<;> simp [*]` · simp [piecewise_eq_of_mem _ _ _ hs, *] · simp [piecewise_eq_of_not_mem _ _ _ hs, *] #align trivialization.piecewise Trivialization.piecewise /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.baseSet ∩ e'.baseSet` such that `e` equals `e'` on `proj ⁻¹' {a}`, `e.piecewise_le_of_eq e' a He He' Heq` is the bundle trivialization over `Set.ite (Iic a) e.baseSet e'.baseSet` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `e'` otherwise. -/ noncomputable def piecewiseLeOfEq [LinearOrder B] [OrderTopology B] (e e' : Trivialization F proj) (a : B) (He : a ∈ e.baseSet) (He' : a ∈ e'.baseSet) (Heq : ∀ p, proj p = a → e p = e' p) : Trivialization F proj := e.piecewise e' (Iic a) (Set.ext fun x => and_congr_left_iff.2 fun hx => by obtain rfl : x = a := mem_singleton_iff.1 (frontier_Iic_subset _ hx) simp [He, He']) fun p hp => Heq p <| frontier_Iic_subset _ hp.2 #align trivialization.piecewise_le_of_eq Trivialization.piecewiseLeOfEq /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.baseSet ∩ e'.baseSet`, `e.piecewise_le e' a He He'` is the bundle trivialization over `Set.ite (Iic a) e.baseSet e'.baseSet` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `((e' p).1, h (e' p).2)` otherwise, where `h = `e'.coord_change_homeomorph e _ _` is the homeomorphism of the fiber such that `h (e' p).2 = (e p).2` whenever `e p = a`. -/ noncomputable def piecewiseLe [LinearOrder B] [OrderTopology B] (e e' : Trivialization F proj) (a : B) (He : a ∈ e.baseSet) (He' : a ∈ e'.baseSet) : Trivialization F proj := e.piecewiseLeOfEq (e'.transFiberHomeomorph (e'.coordChangeHomeomorph e He' He)) a He He' <| by rintro p rfl ext1 · simp [e.coe_fst', e'.coe_fst', *] · simp [coordChange_apply_snd, *] #align trivialization.piecewise_le Trivialization.piecewiseLe /-- Given two bundle trivializations `e`, `e'` over disjoint sets, `e.disjoint_union e' H` is the bundle trivialization over the union of the base sets that agrees with `e` and `e'` over their base sets. -/ noncomputable def disjointUnion (e e' : Trivialization F proj) (H : Disjoint e.baseSet e'.baseSet) : Trivialization F proj where toLocalHomeomorph := e.toLocalHomeomorph.disjointUnion e'.toLocalHomeomorph (by rw [e.source_eq, e'.source_eq] exact H.preimage _) (by rw [e.target_eq, e'.target_eq, disjoint_iff_inf_le] intro x hx exact H.le_bot ⟨hx.1.1, hx.2.1⟩) baseSet := e.baseSet ∪ e'.baseSet open_baseSet := IsOpen.union e.open_baseSet e'.open_baseSet source_eq := congr_arg₂ (· ∪ ·) e.source_eq e'.source_eq target_eq := (congr_arg₂ (· ∪ ·) e.target_eq e'.target_eq).trans union_prod.symm proj_toFun := by rintro p (hp | hp') · show (e.source.piecewise e e' p).1 = proj p rw [piecewise_eq_of_mem, e.coe_fst] <;> exact hp · show (e.source.piecewise e e' p).1 = proj p rw [piecewise_eq_of_not_mem, e'.coe_fst hp'] simp only [source_eq] at hp' ⊢ exact fun h => H.le_bot ⟨h, hp'⟩ #align trivialization.disjoint_union Trivialization.disjointUnion end Piecewise end Trivialization
lemma dropWhile_replicate_append: "dropWhile ((=) a) (replicate n a @ ys) = dropWhile ((=) a) ys"
%% FUNCTION Logistic_iMSF % Incompletet Multi-Source Learning with Logistic Loss (interface). This % code generates structural information for MultiSource_LogisticR and % performs the optimization. % %% OBJECTIVE % see manual. % %% INPUT % A_Set: {n * d} * t - input. The cell array of data. Each cell should be % n by p_i, with missing samples denoted by a whole row of NaNs. % Y_set: {n * 1} * t - output. Y_i \in {-1, 1}. % z: group sparsity regularization parameter (a relative value, [0,1]) % %% OUTPUT % Sol: {struct} solution struct array. % For task i: model: struct{i}.x, bais: struct{i}.c % funVal: objective function values at each iteration. % %% LICENSE % 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 3 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, see <http://www.gnu.org/licenses/>. % % Copyright (C) 2011 - 2012 Lei Yuan, Jiayu Zhou, and Jieping Ye % % You are suggested to first read the Manual. % For any problem, please contact with Jiayu Zhou via [email protected] % % Last modified on June 12, 2012. % %% RELATED PAPERS % [1] Lei Yuan, Yalin Wang, Paul M. Thompson, Vaibhav A. Narayan and Jieping % Ye, Multi-Source Learning for Joint Analysis of Incomplete % Multi-Modality Neuroimaging Data, KDD 2012 % [2] Lei Yuan, Yalin Wang, Paul M. Thompson, Vaibhav A. Narayan and Jieping % Ye, for the Alzheimer's Disease Neuroimaging Initiative, Multi-source % Feature Learning for Joint Analysis of Incomplete Multiple Heterogeneous % Neuroimaging Data, NeuroImage 2012 Jul 2; 61(3):622-632. % %% RELATED FUNCTIONS % init_opts, Construct_iMSF, MultiSource_LogisticR function [Sol, funVal] = Logistic_iMSF(X_Set, Y, lambda, opts) if nargin< 4 opts = []; end [A_Set, Y_Set, W, G, ind] = Construct_iMSF(X_Set, Y); [Sol, funVal] = MultiSource_LogisticR(A_Set, Y_Set, lambda, G, W, ind, opts);
#include "bio/pssm_bayesian_binding_model.h" #include "bio/biobase_binding_model.h" #include "bio/biobase_score.h" #include "bio/model_2_factor.h" #include "bio/serialisable.h" #include "bio/biobase_filter.h" USING_BIO_NS #include <boost/test/unit_test.hpp> #include <boost/test/parameterized_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include <boost/assign/list_of.hpp> using namespace boost; using namespace boost::assign; using boost::unit_test::test_suite; namespace fs = boost::filesystem; #include <iostream> using namespace std; //#define VERBOSE_CHECKING const std::vector< TableLink > pssm_links = list_of ( TableLink( MATRIX_DATA, 328 ) ) ; const SeqList sequences = list_of ( "TGACTCATGCGTAGAGAT" ) ; template< typename It > void check_strict_weak_ordering( It begin, It end ) { for( It i1 = begin; end != i1; ++i1 ) { BOOST_CHECK( ! ( *i1 < *i1 ) ); //Irreflexivity for( It i2 = begin; end != i2; ++i2 ) { if ( *i1 < *i2 ) { BOOST_CHECK( ! ( *i2 < *i1 ) ); //Antisymmetry for( It i3 = begin; end != i3; ++i3 ) { if ( *i2 < *i3 ) { BOOST_CHECK( *i1 < *i3 ); //Transitivity } } } } } } template< typename Binder > void check_strict_weak_ordering( const typename BindingHitSet< Binder >::type & hits ) { check_strict_weak_ordering( hits.get< typename BindingHitSet< Binder >::position >().begin(), hits.get< 0 >().end() ); check_strict_weak_ordering( hits.get< typename BindingHitSet< Binder >::binder >().begin(), hits.get< 1 >().end() ); check_strict_weak_ordering( hits.get< typename BindingHitSet< Binder >::prob >().begin(), hits.get< 2 >().end() ); } template< typename Binder > void display_hits( const typename BindingHitSet< Binder >::type & hits ) { std::copy( hits.get< typename BindingHitSet< Binder >::binder >().begin(), hits.get< typename BindingHitSet< Binder >::binder >().end(), std::ostream_iterator< typename BindingHitSet< Binder >::type::value_type >( std::cout, "\n" ) ); std::cout << "\n\n"; } void check_model_2_factor( const BindingModel::hit_set_t & hits ) { TF::hit_set_t factor_hits; model_hits_2_factor_hits( hits, factor_hits ); #ifdef VERBOSE_CHECKING display_hits< TF >( factor_hits ); #endif //VERBOSE_CHECKING } struct CheckEqual { template< typename T > void operator()( const T & t1, const T & t2 ) const { BOOST_CHECK_EQUAL( t1, t2 ); } }; void check_serialisation( const BindingModel::hit_set_t & hits ) { #ifndef _DEBUG check_strict_weak_ordering< BindingModel >( hits ); #endif fs::path test_file( "hit_serialisation_test.txt" ); serialise< BindingModel, false >( hits, test_file ); BindingModel::hit_set_t copy_of_hits; deserialise< BindingModel, false >( copy_of_hits, test_file ); BOOST_REQUIRE( copy_of_hits.size() == hits.size() ); BOOST_CHECK( std::equal( hits.begin(), hits.end(), copy_of_hits.begin() ) ); std::pair< BindingModel::hit_set_t::const_iterator, BindingModel::hit_set_t::const_iterator > mm = std::mismatch( hits.begin(), hits.end(), copy_of_hits.begin() ); } void check_deaf_binding_model() { cout << "******* check_deaf_binding_model()\n"; const seq_t sequence = "NNNNNNNNNNNNNNNNNNNNNNNNN"; BindingModel * deaf_model = BiobaseBindingModel::parameter_t( TableLink( MATRIX_DATA, 1001 ) ).get_model(); BindingModel::hit_set_t hits; make_sequence_scorer( sequence.begin(), sequence.end(), 1e-5, std::inserter( hits, hits.begin() ) ) ( deaf_model ); } void check_pssm_bayesian_binding_model( TableLink link ) { cout << "******* check_pssm_bayesian_binding_model(): " << link << "\n"; const seq_t sequence = "TGACTCATGCGTAGAGAT"; BindingModel::hit_set_t hits; make_sequence_scorer( sequence.begin(), sequence.end(), 1e-5, std::inserter( hits, hits.begin() ) ) ( BiobaseBindingModel::parameter_t( link ).get_model() ); #ifdef VERBOSE_CHECKING display_hits< BindingModel >( hits ); #endif check_serialisation( hits ); check_model_2_factor( hits ); } /** Jerome had problem with this binding site and matrix 962. */ void check_ar_binding_model( ) { cout << "******* check_ar_biobase_binding_model()\n"; const seq_t sequence = "AGAGCATGG" ; const TableLink link( MATRIX_DATA, 962 ); BindingModel::hit_set_t hits; BindingModel * model = BiobaseBindingModel::parameter_t( link ).get_model() ; make_sequence_scorer( sequence.begin(), sequence.end(), 1e-5, std::inserter( hits, hits.begin() ) ) ( model ); #ifdef VERBOSE_CHECKING display_hits< BindingModel >( hits ); #endif } void check_biobase_binding_model( const seq_t & sequence ) { cout << "******* check_biobase_binding_model(): " << sequence << "\n"; BindingModel::hit_set_t hits; score_all_biobase_pssms( make_sequence_scorer( sequence.begin(), sequence.end(), 1e-5, std::inserter( hits, hits.begin() ) ), BiobasePssmFilter(), Link2BiobaseBindingModel() ); #ifdef VERBOSE_CHECKING display_hits< BindingModel >( hits ); #endif check_serialisation( hits ); check_model_2_factor( hits ); } void check_binding_hit_less_than() { cout << "******* check_binding_hit_less_than()\n"; BindingModel::hit_set_t hits; for( int binder = 0; 2 != binder; ++binder ) { for( unsigned c = 0; 2 != c; ++c ) { for( int p = 0; 2 != p; ++p ) { for( unsigned l = 10; 30 != l; l += 10 ) { for( double b = 0.0; 1.0 > b; b += 0.4 ) { hits.insert( BindingModel::hit_t( 0 == binder ? BiobaseBindingModel::parameter_t( TableLink( MATRIX_DATA, 328 ) ).get_model() : BiobaseBindingModel::parameter_t( TableLink( MATRIX_DATA, 621 ) ).get_model(), b, p, l, 1 == c ) ); } } } } } check_serialisation( hits ); check_strict_weak_ordering< BindingModel >( hits ); } void register_binding_model_tests(boost::unit_test::test_suite * test) { test->add( BOOST_TEST_CASE( &check_ar_binding_model ), 0 ); test->add( BOOST_TEST_CASE( &check_deaf_binding_model ), 0 ); test->add( BOOST_TEST_CASE( &check_binding_hit_less_than ), 0 ); test->add( BOOST_PARAM_TEST_CASE( &check_pssm_bayesian_binding_model, pssm_links.begin(), pssm_links.end() ), 0 ); test->add( BOOST_PARAM_TEST_CASE( &check_biobase_binding_model, sequences.begin(), sequences.end() ), 0 ); }
(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *) Require Import ssreflect. Require Import ssrnat. Require Import seq. Require Import cfmap. Require Import cfreducible. Require Import configurations. Lemma red502to506 : reducible_in_range 502 506 the_configs. Proof. CheckReducible. Qed.
[GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s : ι → Set Ω hf : ∀ (i : ι), StronglyMeasurable (f i) hfi : iIndepFun (fun x => mβ) f hij : i < j ⊢ Indep (MeasurableSpace.comap (f j) mβ) (↑(Filtration.natural f hf) i) [PROOFSTEP] suffices Indep (⨆ k ∈ ({ j } : Set ι), MeasurableSpace.comap (f k) mβ) (⨆ k ∈ {k | k ≤ i}, MeasurableSpace.comap (f k) mβ) μ by rwa [iSup_singleton] at this [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s : ι → Set Ω hf : ∀ (i : ι), StronglyMeasurable (f i) hfi : iIndepFun (fun x => mβ) f hij : i < j this : Indep (⨆ (k : ι) (_ : k ∈ {j}), MeasurableSpace.comap (f k) mβ) (⨆ (k : ι) (_ : k ∈ {k | k ≤ i}), MeasurableSpace.comap (f k) mβ) ⊢ Indep (MeasurableSpace.comap (f j) mβ) (↑(Filtration.natural f hf) i) [PROOFSTEP] rwa [iSup_singleton] at this [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s : ι → Set Ω hf : ∀ (i : ι), StronglyMeasurable (f i) hfi : iIndepFun (fun x => mβ) f hij : i < j ⊢ Indep (⨆ (k : ι) (_ : k ∈ {j}), MeasurableSpace.comap (f k) mβ) (⨆ (k : ι) (_ : k ∈ {k | k ≤ i}), MeasurableSpace.comap (f k) mβ) [PROOFSTEP] exact indep_iSup_of_disjoint (fun k => (hf k).measurable.comap_le) hfi (by simpa) [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s : ι → Set Ω hf : ∀ (i : ι), StronglyMeasurable (f i) hfi : iIndepFun (fun x => mβ) f hij : i < j ⊢ Disjoint {j} {k | k ≤ i} [PROOFSTEP] simpa [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s : ι → Set Ω hsm : ∀ (n : ι), MeasurableSet (s n) hs : iIndepSet s hij : i < j ⊢ μ[Set.indicator (s j) fun x => 1|↑(filtrationOfSet hsm) i] =ᵐ[μ] fun x => ENNReal.toReal (↑↑μ (s j)) [PROOFSTEP] rw [Filtration.filtrationOfSet_eq_natural (β := ℝ) hsm] [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s : ι → Set Ω hsm : ∀ (n : ι), MeasurableSet (s n) hs : iIndepSet s hij : i < j ⊢ μ[Set.indicator (s j) fun x => 1|↑(Filtration.natural (fun i => Set.indicator (s i) fun x => 1) (_ : ∀ (i : ι), StronglyMeasurable (Set.indicator (s i) 1))) i] =ᵐ[μ] fun x => ENNReal.toReal (↑↑μ (s j)) [PROOFSTEP] refine' (iIndepFun.condexp_natural_ae_eq_of_lt _ hs.iIndepFun_indicator hij).trans _ [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s : ι → Set Ω hsm : ∀ (n : ι), MeasurableSet (s n) hs : iIndepSet s hij : i < j ⊢ (fun x => ∫ (x : Ω), Set.indicator (s j) (fun _ω => 1) x ∂μ) =ᵐ[μ] fun x => ENNReal.toReal (↑↑μ (s j)) [PROOFSTEP] simp only [integral_indicator_const _ (hsm _), Algebra.id.smul_eq_mul, mul_one] [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s : ι → Set Ω hsm : ∀ (n : ι), MeasurableSet (s n) hs : iIndepSet s hij : i < j ⊢ (fun x => ENNReal.toReal (↑↑μ (s j))) =ᵐ[μ] fun x => ENNReal.toReal (↑↑μ (s j)) [PROOFSTEP] rfl [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ ⊢ ↑↑μ (limsup s atTop) = 1 [PROOFSTEP] rw [measure_congr (eventuallyEq_set.2 (ae_mem_limsup_atTop_iff μ <| measurableSet_filtrationOfSet' hsm) : (limsup s atTop : Set Ω) =ᵐ[μ] {ω | Tendsto (fun n => ∑ k in Finset.range n, (μ[(s (k + 1)).indicator (1 : Ω → ℝ)|filtrationOfSet hsm k]) ω) atTop atTop})] [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ ⊢ ↑↑μ {ω | Tendsto (fun n => ∑ k in Finset.range n, (μ[Set.indicator (s (k + 1)) 1|↑(filtrationOfSet hsm) k]) ω) atTop atTop} = 1 [PROOFSTEP] suffices {ω | Tendsto (fun n => ∑ k in Finset.range n, (μ[(s (k + 1)).indicator (1 : Ω → ℝ)|filtrationOfSet hsm k]) ω) atTop atTop} =ᵐ[μ] Set.univ by rw [measure_congr this, measure_univ] [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : {ω | Tendsto (fun n => ∑ k in Finset.range n, (μ[Set.indicator (s (k + 1)) 1|↑(filtrationOfSet hsm) k]) ω) atTop atTop} =ᵐ[μ] Set.univ ⊢ ↑↑μ {ω | Tendsto (fun n => ∑ k in Finset.range n, (μ[Set.indicator (s (k + 1)) 1|↑(filtrationOfSet hsm) k]) ω) atTop atTop} = 1 [PROOFSTEP] rw [measure_congr this, measure_univ] [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ ⊢ {ω | Tendsto (fun n => ∑ k in Finset.range n, (μ[Set.indicator (s (k + 1)) 1|↑(filtrationOfSet hsm) k]) ω) atTop atTop} =ᵐ[μ] Set.univ [PROOFSTEP] have : ∀ᵐ ω ∂μ, ∀ n, (μ[(s (n + 1)).indicator (1 : Ω → ℝ)|filtrationOfSet hsm n]) ω = _ := ae_all_iff.2 fun n => hs.condexp_indicator_filtrationOfSet_ae_eq hsm n.lt_succ_self [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ⊢ {ω | Tendsto (fun n => ∑ k in Finset.range n, (μ[Set.indicator (s (k + 1)) 1|↑(filtrationOfSet hsm) k]) ω) atTop atTop} =ᵐ[μ] Set.univ [PROOFSTEP] filter_upwards [this] with ω hω [GOAL] case h Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) ⊢ setOf (fun ω => Tendsto (fun n => ∑ k in Finset.range n, (μ[Set.indicator (s (k + 1)) 1|↑(filtrationOfSet hsm) k]) ω) atTop atTop) ω = Set.univ ω [PROOFSTEP] refine' eq_true (_ : Tendsto _ _ _) [GOAL] case h Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) ⊢ Tendsto (fun n => ∑ k in Finset.range n, (μ[Set.indicator (s (k + 1)) 1|↑(filtrationOfSet hsm) k]) ω) atTop atTop [PROOFSTEP] simp_rw [hω] [GOAL] case h Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) ⊢ Tendsto (fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) atTop atTop [PROOFSTEP] have htends : Tendsto (fun n => ∑ k in Finset.range n, μ (s (k + 1))) atTop (𝓝 ∞) := by rw [← ENNReal.tsum_add_one_eq_top hs' (measure_ne_top _ _)] exact ENNReal.tendsto_nat_tsum _ [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) ⊢ Tendsto (fun n => ∑ k in Finset.range n, ↑↑μ (s (k + 1))) atTop (𝓝 ⊤) [PROOFSTEP] rw [← ENNReal.tsum_add_one_eq_top hs' (measure_ne_top _ _)] [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) ⊢ Tendsto (fun n => ∑ k in Finset.range n, ↑↑μ (s (k + 1))) atTop (𝓝 (∑' (n : ℕ), ↑↑μ (s (n + 1)))) [PROOFSTEP] exact ENNReal.tendsto_nat_tsum _ [GOAL] case h Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : Tendsto (fun n => ∑ k in Finset.range n, ↑↑μ (s (k + 1))) atTop (𝓝 ⊤) ⊢ Tendsto (fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) atTop atTop [PROOFSTEP] rw [ENNReal.tendsto_nhds_top_iff_nnreal] at htends [GOAL] case h Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) ⊢ Tendsto (fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) atTop atTop [PROOFSTEP] refine' tendsto_atTop_atTop_of_monotone' _ _ [GOAL] case h.refine'_1 Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) ⊢ Monotone fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1))) [PROOFSTEP] refine' monotone_nat_of_le_succ fun n => _ [GOAL] case h.refine'_1 Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) n : ℕ ⊢ ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1))) ≤ ∑ x in Finset.range (n + 1), ENNReal.toReal (↑↑μ (s (x + 1))) [PROOFSTEP] rw [← sub_nonneg, Finset.sum_range_succ_sub_sum] [GOAL] case h.refine'_1 Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) n : ℕ ⊢ 0 ≤ ENNReal.toReal (↑↑μ (s (n + 1))) [PROOFSTEP] exact ENNReal.toReal_nonneg [GOAL] case h.refine'_2 Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) ⊢ ¬BddAbove (Set.range fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) [PROOFSTEP] rintro ⟨B, hB⟩ [GOAL] case h.refine'_2.intro Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ hB : B ∈ upperBounds (Set.range fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) ⊢ False [PROOFSTEP] refine' not_eventually.2 (frequently_of_forall fun n => _) (htends B.toNNReal) [GOAL] case h.refine'_2.intro Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ hB : B ∈ upperBounds (Set.range fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) n : ℕ ⊢ ¬↑(Real.toNNReal B) < ∑ k in Finset.range n, ↑↑μ (s (k + 1)) [PROOFSTEP] rw [mem_upperBounds] at hB [GOAL] case h.refine'_2.intro Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ hB : ∀ (x : ℝ), (x ∈ Set.range fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) → x ≤ B n : ℕ ⊢ ¬↑(Real.toNNReal B) < ∑ k in Finset.range n, ↑↑μ (s (k + 1)) [PROOFSTEP] specialize hB (∑ k : ℕ in Finset.range n, μ (s (k + 1))).toReal _ [GOAL] case h.refine'_2.intro Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ hB : ∀ (x : ℝ), (x ∈ Set.range fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) → x ≤ B n : ℕ ⊢ ENNReal.toReal (∑ k in Finset.range n, ↑↑μ (s (k + 1))) ∈ Set.range fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1))) [PROOFSTEP] refine' ⟨n, _⟩ [GOAL] case h.refine'_2.intro Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ hB : ∀ (x : ℝ), (x ∈ Set.range fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) → x ≤ B n : ℕ ⊢ (fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) n = ENNReal.toReal (∑ k in Finset.range n, ↑↑μ (s (k + 1))) [PROOFSTEP] rw [ENNReal.toReal_sum] [GOAL] case h.refine'_2.intro Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ hB : ∀ (x : ℝ), (x ∈ Set.range fun n => ∑ x in Finset.range n, ENNReal.toReal (↑↑μ (s (x + 1)))) → x ≤ B n : ℕ ⊢ ∀ (a : ℕ), a ∈ Finset.range n → ↑↑μ (s (a + 1)) ≠ ⊤ [PROOFSTEP] exact fun _ _ => measure_ne_top _ _ [GOAL] case h.refine'_2.intro Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ n : ℕ hB : ENNReal.toReal (∑ k in Finset.range n, ↑↑μ (s (k + 1))) ≤ B ⊢ ¬↑(Real.toNNReal B) < ∑ k in Finset.range n, ↑↑μ (s (k + 1)) [PROOFSTEP] rw [not_lt, ← ENNReal.toReal_le_toReal (ENNReal.sum_lt_top _).ne ENNReal.coe_ne_top] [GOAL] case h.refine'_2.intro Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ n : ℕ hB : ENNReal.toReal (∑ k in Finset.range n, ↑↑μ (s (k + 1))) ≤ B ⊢ ENNReal.toReal (∑ a in Finset.range n, ↑↑μ (s (a + 1))) ≤ ENNReal.toReal ↑(Real.toNNReal B) [PROOFSTEP] exact hB.trans (by simp) [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ n : ℕ hB : ENNReal.toReal (∑ k in Finset.range n, ↑↑μ (s (k + 1))) ≤ B ⊢ B ≤ ENNReal.toReal ↑(Real.toNNReal B) [PROOFSTEP] simp [GOAL] Ω : Type u_1 m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : IsProbabilityMeasure μ ι : Type u_2 β : Type u_3 inst✝² : LinearOrder ι mβ : MeasurableSpace β inst✝¹ : NormedAddCommGroup β inst✝ : BorelSpace β f : ι → Ω → β i j : ι s✝ : ι → Set Ω s : ℕ → Set Ω hsm : ∀ (n : ℕ), MeasurableSet (s n) hs : iIndepSet s hs' : ∑' (n : ℕ), ↑↑μ (s n) = ⊤ this : ∀ᵐ (ω : Ω) ∂μ, ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = (fun x => ENNReal.toReal (↑↑μ (s (n + 1)))) ω ω : Ω hω : ∀ (n : ℕ), (μ[Set.indicator (s (n + 1)) 1|↑(filtrationOfSet hsm) n]) ω = ENNReal.toReal (↑↑μ (s (n + 1))) htends : ∀ (x : NNReal), ∀ᶠ (a : ℕ) in atTop, ↑x < ∑ k in Finset.range a, ↑↑μ (s (k + 1)) B : ℝ n : ℕ hB : ENNReal.toReal (∑ k in Finset.range n, ↑↑μ (s (k + 1))) ≤ B ⊢ ∀ (a : ℕ), a ∈ Finset.range n → ↑↑μ (s (a + 1)) ≠ ⊤ [PROOFSTEP] exact fun _ _ => measure_ne_top _ _
[STATEMENT] lemma compact_flat_lub [cont_intro]: "ccpo.compact (flat_lub x) (flat_ord x) y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ccpo.compact (flat_lub x) (flat_ord x) y [PROOF STEP] using flat_interpretation[THEN ccpo] [PROOF STATE] proof (prove) using this: class.ccpo (flat_lub ?b1) (flat_ord ?b1) (mk_less (flat_ord ?b1)) goal (1 subgoal): 1. ccpo.compact (flat_lub x) (flat_ord x) y [PROOF STEP] proof(rule ccpo.compactI[OF _ ccpo.admissibleI]) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] fix A [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] assume chain: "Complete_Partial_Order.chain (flat_ord x) A" and A: "A \<noteq> {}" and *: "\<forall>z\<in>A. \<not> flat_ord x y z" [PROOF STATE] proof (state) this: Complete_Partial_Order.chain (flat_ord x) A A \<noteq> {} \<forall>z\<in>A. \<not> flat_ord x y z goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] from A [PROOF STATE] proof (chain) picking this: A \<noteq> {} [PROOF STEP] obtain z where "z \<in> A" [PROOF STATE] proof (prove) using this: A \<noteq> {} goal (1 subgoal): 1. (\<And>z. z \<in> A \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: z \<in> A goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] with * [PROOF STATE] proof (chain) picking this: \<forall>z\<in>A. \<not> flat_ord x y z z \<in> A [PROOF STEP] have z: "\<not> flat_ord x y z" [PROOF STATE] proof (prove) using this: \<forall>z\<in>A. \<not> flat_ord x y z z \<in> A goal (1 subgoal): 1. \<not> flat_ord x y z [PROOF STEP] .. [PROOF STATE] proof (state) this: \<not> flat_ord x y z goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] hence y: "x \<noteq> y" "y \<noteq> z" [PROOF STATE] proof (prove) using this: \<not> flat_ord x y z goal (1 subgoal): 1. x \<noteq> y &&& y \<noteq> z [PROOF STEP] by(auto simp add: flat_ord_def) [PROOF STATE] proof (state) this: x \<noteq> y y \<noteq> z goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] { [PROOF STATE] proof (state) this: x \<noteq> y y \<noteq> z goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] assume "\<not> A \<subseteq> {x}" [PROOF STATE] proof (state) this: \<not> A \<subseteq> {x} goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<not> A \<subseteq> {x} [PROOF STEP] obtain z' where "z' \<in> A" "z' \<noteq> x" [PROOF STATE] proof (prove) using this: \<not> A \<subseteq> {x} goal (1 subgoal): 1. (\<And>z'. \<lbrakk>z' \<in> A; z' \<noteq> x\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: z' \<in> A z' \<noteq> x goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: z' \<in> A z' \<noteq> x [PROOF STEP] have "(THE z. z \<in> A - {x}) = z'" [PROOF STATE] proof (prove) using this: z' \<in> A z' \<noteq> x goal (1 subgoal): 1. (THE z. z \<in> A - {x}) = z' [PROOF STEP] by(intro the_equality)(auto dest: chainD[OF chain] simp add: flat_ord_def) [PROOF STATE] proof (state) this: (THE z. z \<in> A - {x}) = z' goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] moreover [PROOF STATE] proof (state) this: (THE z. z \<in> A - {x}) = z' goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] have "z' \<noteq> y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. z' \<noteq> y [PROOF STEP] using \<open>z' \<in> A\<close> * [PROOF STATE] proof (prove) using this: z' \<in> A \<forall>z\<in>A. \<not> flat_ord x y z goal (1 subgoal): 1. z' \<noteq> y [PROOF STEP] by(auto simp add: flat_ord_def) [PROOF STATE] proof (state) this: z' \<noteq> y goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: (THE z. z \<in> A - {x}) = z' z' \<noteq> y [PROOF STEP] have "y \<noteq> (THE z. z \<in> A - {x})" [PROOF STATE] proof (prove) using this: (THE z. z \<in> A - {x}) = z' z' \<noteq> y goal (1 subgoal): 1. y \<noteq> (THE z. z \<in> A - {x}) [PROOF STEP] by simp [PROOF STATE] proof (state) this: y \<noteq> (THE z. z \<in> A - {x}) goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> A \<subseteq> {x} \<Longrightarrow> y \<noteq> (THE z. z \<in> A - {x}) goal (1 subgoal): 1. \<And>A. \<lbrakk>Complete_Partial_Order.chain (flat_ord x) A; A \<noteq> {}; \<forall>xa\<in>A. \<not> flat_ord x y xa\<rbrakk> \<Longrightarrow> \<not> flat_ord x y (flat_lub x A) [PROOF STEP] with z [PROOF STATE] proof (chain) picking this: \<not> flat_ord x y z \<not> A \<subseteq> {x} \<Longrightarrow> y \<noteq> (THE z. z \<in> A - {x}) [PROOF STEP] show "\<not> flat_ord x y (flat_lub x A)" [PROOF STATE] proof (prove) using this: \<not> flat_ord x y z \<not> A \<subseteq> {x} \<Longrightarrow> y \<noteq> (THE z. z \<in> A - {x}) goal (1 subgoal): 1. \<not> flat_ord x y (flat_lub x A) [PROOF STEP] by(simp add: flat_ord_def flat_lub_def) [PROOF STATE] proof (state) this: \<not> flat_ord x y (flat_lub x A) goal: No subgoals! [PROOF STEP] qed
test_that("condense always returns a rowwise", { df <- tibble(x = 1) gf <- group_by(df, x) rf <- rowwise(df) expect_s3_class(condense(df, y = 1), "rowwise_df") expect_s3_class(condense(gf, y = 1), "rowwise_df") expect_s3_class(condense(rf, y = 1), "rowwise_df") })
Require Import Coq.ZArith.ZArith. Require Export Fiat.Common.Coq__8_4__8_5__Compat. #[global] Hint Rewrite <- nat_compare_lt : hints. #[global] Hint Rewrite <- nat_compare_gt : hints. #[global] Hint Rewrite Nat.compare_eq_iff : hints. #[global] Hint Rewrite <- Nat.compare_eq_iff : hints. Ltac autorewrite_nat_compare := autorewrite with hints. Lemma nat_compare_eq_refl : forall x, Nat.compare x x = Eq. intros; apply Nat.compare_eq_iff; trivial. Qed. Lemma nat_compare_consistent : forall n0 n1, { Nat.compare n0 n1 = Lt /\ Nat.compare n1 n0 = Gt } + { Nat.compare n0 n1 = Eq /\ Nat.compare n1 n0 = Eq } + { Nat.compare n0 n1 = Gt /\ Nat.compare n1 n0 = Lt }. Proof. intros n0 n1; destruct (lt_eq_lt_dec n0 n1) as [ [_lt | _eq] | _lt ]; [ constructor 1; constructor 1 | constructor 1; constructor 2 | constructor 2 ]; split; autorewrite_nat_compare; intuition. Qed.
Theorem plus_O_n : forall n : nat, 0 + n = n. Proof. intro n. reflexivity. Qed. Theorem plus_1_l : forall n:nat, 1 + n = S n. Proof. intros n. reflexivity. Qed. Theorem plus_id_example : forall n m:nat, n = m -> n + n = m + m. Proof. intros n. intros m. intros N1. rewrite -> N1. reflexivity. Qed. Theorem plus_id_exercise : forall n m o : nat, n = m -> m = o -> n + m = m + o. Proof. intros n m o. intros M N. rewrite M. rewrite N. reflexivity. Qed. Theorem mult_0_plus : forall n m : nat, (0 + n) * m = n * m. Proof. intros n m. rewrite -> plus_O_n. reflexivity. Qed. Theorem mult_S_1 : forall n m : nat, m = S n -> m * (1 + n) = m * m. Proof. intros n m. intros H. rewrite -> H. reflexivity. Qed. Fixpoint beq_nat (n m : nat) : bool := match n with | O => match m with | O => true | S m' => false end | S n' => match m with | O => false | S m' => beq_nat n' m' end end. Eval compute in (beq_nat 0 0). Eval compute in (beq_nat 0 1). Theorem plus_1_neq_0_firsttry : forall n : nat, beq_nat (n + 1) 0 = false. Proof. intros n. destruct n as [| n']. reflexivity. reflexivity. Qed. Theorem zero_nbeq_plus_1 : forall n : nat, beq_nat 0 (n + 1) = false. Proof. intros n. destruct n as [ | n']. reflexivity. reflexivity. Qed. Definition andb (a b : bool) : bool := match a with | true => b | false => false end. Definition orb (a b : bool) : bool := match a with | false => b | true => true end. Theorem andb_false : forall b c : bool, c = false -> (andb b c) = false. Proof. intros b c. intros H. rewrite -> H. destruct b. reflexivity. reflexivity. Qed. Theorem andb_true : forall b c : bool, c = true -> (andb b c) = b. Proof. intros b c. intros H. rewrite -> H. destruct b. reflexivity. reflexivity. Qed. Theorem orb_true : forall b c : bool, c = true -> (orb b c) = true. Proof. intros b c. intros H. rewrite -> H. destruct b. reflexivity. reflexivity. Qed. Theorem orb_false : forall b c : bool, c = false -> (orb b c) = b. Proof. intros b c. intros H. rewrite -> H. destruct b. reflexivity. reflexivity. Qed. Theorem andb_eq_true : forall b : bool, (andb b true) = (orb b true) -> b = true. Proof. intros b. destruct b. reflexivity. simpl. intros H. rewrite -> H. reflexivity. Qed. Theorem andb_eq_c_true : forall b c : bool, c = true -> (andb b c) = (orb b c) -> b = true. Proof. intros b c. simpl. intros H. rewrite -> H. destruct b. reflexivity. simpl. intros L. rewrite -> L. reflexivity. Qed. Theorem andb_eq_orb : forall (b c : bool), (andb b c = orb b c) -> b = c. Proof. intros b c. destruct b. destruct c. (* b - true, c - true *) reflexivity. (* b - true, c - false *) simpl. intro H. rewrite -> H. reflexivity. (* b - false, c - true *) simpl. intro H. rewrite -> H. reflexivity. Qed. Theorem identity_fn_applied_twice : forall (f : bool -> bool), (forall (x : bool), f x = x) -> forall (b : bool), f (f b) = b. Proof. intros f. intros H. intros b. rewrite -> H. rewrite -> H. reflexivity. Qed.
Formal statement is: lemma complex_is_Int_iff: "z \<in> \<int> \<longleftrightarrow> Im z = 0 \<and> (\<exists>i. Re z = of_int i)" Informal statement is: A complex number $z$ is an integer if and only if its imaginary part is zero and its real part is an integer.
[STATEMENT] lemma max_word_less_eq_iff [simp]: \<open>- 1 \<le> w \<longleftrightarrow> w = - 1\<close> for w :: \<open>'a::len word\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. (- 1 \<le> w) = (w = - 1) [PROOF STEP] by (fact word_order.extremum_unique)
#' Read & combine HILDA files #' #' This function reads in any HILDA file (SAS, Stata and SPSS included) and merges #' the files where appropriate. This function works best with HILDA's TAB files as #' they allow for parsing of individual columns, not the entire dataset. This function #' is designed for HILDA 16 general and restricted and may not function correctly with #' other versions of HILDA. #' #' @param paths a character vector of file paths to HILDA files #' @param variables a character vector variables names to parse. These can use #' #' @return data.table #' @export #' #' @examples #'\dontrun{ #' dt1 <- read.hilda("Eperson_n160u.dta") #' dt2 <- read.hilda( #' paths = c("Combined p160c.tab", "Combined o160c.tab"), #' variables = c("XHHRAID","_alopmt", "hhwte") #' ) #' } read.hilda <- function(paths, variables = NULL){ if (Sys.info()["sysname"] == "Windows"){ pbapply::pboptions(type = "win", title = "Parsing HILDA files") hilda_list <- pbapply::pblapply(paths, parse_switch, vars = variables) } else { hilda_list <- lapply(paths, parse_switch, vars = variables) } message(paste0(crayon::green(cli::symbol$tick), " ", crayon::white("Files parsed"))) hilda_list <- lapply(hilda_list, function(dt){ names(dt) <- match_vars(names(dt)) return(dt) }) message(paste0(crayon::green(cli::symbol$tick), " ", crayon::white("Headers cleaned"))) if(length(hilda_list) == 1){ return(hilda_list[[1]]) } else { hilda_list <- data.table::rbindlist(hilda_list, use.names = TRUE, fill = TRUE) message(paste0(crayon::green(cli::symbol$tick), " ", crayon::white("Datasets merged"))) return(hilda_list) } }
import Base: # types Array, CartesianIndices, Vector, # symbols +, -, *, /, ==, <, >, # functions adjoint, axes, complex, convert, copy, copyto!, deepcopy, deleteat!, eachindex, eltype, fill!, getindex, hash, isapprox, isempty, isless, iterate, keys, lastindex, length, map, map!, ndims, push!, resize!, setindex!, show, similar, size, summary, truncate, zero import Base.Broadcast: # types AbstractArrayStyle, Broadcasted, BroadcastStyle, DefaultArrayStyle, Style, # functions _broadcast_getindex, broadcasted, broadcastable, instantiate import ITensors.ContractionSequenceOptimization: optimized_contraction_sequence import HDF5: read, write import LinearAlgebra: axpby!, axpy!, dot, eigen, exp, factorize, lmul!, mul!, norm, normalize!, qr, rmul!, svd, tr import NDTensors: # Modules Strided, # to control threading # Methods array, blockdim, blockoffsets, contract, dense, dim, dims, disable_tblis, eachnzblock, enable_tblis, ind, inds, insertblock!, matrix, #maxdim, mindim, nblocks, nnz, nnzblocks, nzblock, nzblocks, outer, permuteblocks, polar, scale!, setblockdim!, sim, store, sum, tensor, truncate!, using_tblis, vector, # Deprecated addblock! import Random: randn!
section \<open>Exception-Aware Relational Framework\<close> theory Run imports "HOL-Imperative_HOL.Imperative_HOL" begin text \<open> With Imperative HOL comes a relational framework. However, this can only be used if exception freeness is already assumed. This results in some proof duplication, because exception freeness and correctness need to be shown separately. In this theory, we develop a relational framework that is aware of exceptions, and makes it possible to show correctness and exception freeness in one run. \<close> text \<open> There are two types of states: \begin{enumerate} \item A normal (Some) state contains the current heap. \item An exception state is None \end{enumerate} The two states exactly correspond to the option monad in Imperative HOL. \<close> type_synonym state = "Heap.heap option" primrec is_exn where "is_exn (Some _) = False" | "is_exn None = True" primrec the_state where "the_state (Some h) = h" \<comment> \<open>The exception-aware, relational semantics\<close> inductive run :: "'a Heap \<Rightarrow> state \<Rightarrow> state \<Rightarrow> 'a \<Rightarrow> bool" where push_exn: "is_exn \<sigma> \<Longrightarrow> run c \<sigma> \<sigma> r " | new_exn: "\<lbrakk>\<not> is_exn \<sigma>; execute c (the_state \<sigma>) = None\<rbrakk> \<Longrightarrow> run c \<sigma> None r" | regular: "\<lbrakk>\<not> is_exn \<sigma>; execute c (the_state \<sigma>) = Some (r, h')\<rbrakk> \<Longrightarrow> run c \<sigma> (Some h') r" subsubsection "Link with \<open>effect\<close> and \<open>success\<close>" lemma run_effectE: assumes "run c \<sigma> \<sigma>' r" assumes "\<not>is_exn \<sigma>'" obtains h h' where "\<sigma>=Some h" "\<sigma>' = Some h'" "effect c h h' r" using assms unfolding effect_def apply (cases \<sigma>) by (auto simp add: run.simps) lemma run_effectI: assumes "run c (Some h) (Some h') r" shows "effect c h h' r" using run_effectE[OF assms] by auto lemma effect_run: assumes "effect c h h' r" shows "run c (Some h) (Some h') r" using assms unfolding effect_def by (auto intro: run.intros) lemma success_run: assumes "success f h" obtains h' r where "run f (Some h) (Some h') r" proof - from assms obtain r h' where "Heap_Monad.execute f h = Some (r, h')" unfolding success_def by auto then show thesis by (rule that[OF regular[of "Some h", simplified]]) qed text \<open>run always yields a result\<close> lemma run_complete: obtains \<sigma>' r where "run c \<sigma> \<sigma>' r" apply (cases "is_exn \<sigma>") apply (auto intro: run.intros) apply (cases "execute c (the_state \<sigma>)") by (auto intro: run.intros) lemma run_detE: assumes "run c \<sigma> \<sigma>' r" "run c \<sigma> \<tau> s" "\<not>is_exn \<sigma>" obtains "is_exn \<sigma>'" "\<sigma>' = \<tau>" | "\<not> is_exn \<sigma>'" "\<sigma>' = \<tau>" "r = s" using assms by (auto simp add: run.simps) lemma run_detI: assumes "run c (Some h) (Some h') r" "run c (Some h) \<sigma> s" shows "\<sigma> = Some h' \<and> r = s" using assms by (auto simp add: run.simps) subsubsection \<open>Elimination Rules for Basic Combinators\<close> named_theorems run_elims "elemination rules for run" lemma runE[run_elims]: assumes "run (f \<bind> g) \<sigma> \<sigma>'' r" obtains \<sigma>' r' where "run f \<sigma> \<sigma>' r'" "run (g r') \<sigma>' \<sigma>'' r" using assms apply (cases "is_exn \<sigma>") apply (simp add: run.simps) apply (cases "execute f (the_state \<sigma>)") apply (simp add: run.simps bind_def) by (auto simp add: bind_def run.simps) lemma runE'[run_elims]: assumes "run (f \<then> g) \<sigma> \<sigma>'' res" obtains \<sigma>t rt where "run f \<sigma> \<sigma>t rt" "run g \<sigma>t \<sigma>'' res" using assms by (rule_tac runE) lemma run_return[run_elims]: assumes "run (return x) \<sigma> \<sigma>' r" obtains "r = x" "\<sigma>' = \<sigma>" "\<not> is_exn \<sigma>" | "\<sigma> = None" using assms apply (cases \<sigma>) apply (simp add: run.simps) by (auto simp add: run.simps execute_simps) lemma run_raise_iff: "run (raise s) \<sigma> \<sigma>' r \<longleftrightarrow> (\<sigma>'=None)" apply (cases \<sigma>) by (auto simp add: run.simps execute_simps) lemma run_raise[run_elims]: assumes "run (raise s) \<sigma> \<sigma>' r" obtains "\<sigma>' = None" using assms by (simp add: run_raise_iff) lemma run_raiseI: "run (raise s) \<sigma> None r" by (simp add: run_raise_iff) lemma run_if[run_elims]: assumes "run (if c then t else e) h h' r" obtains "c" "run t h h' r" | "\<not>c" "run e h h' r" using assms by (auto split: if_split_asm) lemma run_case_option[run_elims]: assumes "run (case x of None \<Rightarrow> n | Some y \<Rightarrow> s y) \<sigma> \<sigma>' r" "\<not>is_exn \<sigma>" obtains "x = None" "run n \<sigma> \<sigma>' r" | y where "x = Some y" "run (s y) \<sigma> \<sigma>' r" using assms by (cases x) simp_all lemma run_heap[run_elims]: assumes "run (Heap_Monad.heap f) \<sigma> \<sigma>' res" "\<not>is_exn \<sigma>" obtains "\<sigma>' = Some (snd (f (the_state \<sigma>)))" and "res = (fst (f (the_state \<sigma>)))" using assms apply (cases \<sigma>) apply simp apply (auto simp add: run.simps) apply (simp add: execute_simps) apply (simp only: execute_simps) apply hypsubst_thin subgoal premises prems for a h' proof - from prems(2) have "h' = snd (f a)" "res = fst (f a)" by simp_all from prems(1)[OF this] show ?thesis . qed done subsection \<open>Array Commands\<close> lemma run_length[run_elims]: assumes "run (Array.len a) \<sigma> \<sigma>' r" "\<not>is_exn \<sigma>" obtains "\<not>is_exn \<sigma>" "\<sigma>' = \<sigma>" "r = Array.length (the_state \<sigma>) a" using assms apply (cases \<sigma>) by (auto simp add: run.simps execute_simps) lemma run_new_array[run_elims]: assumes "run (Array.new n x) \<sigma> \<sigma>' r" "\<not>is_exn \<sigma>" obtains "\<sigma>' = Some (snd (Array.alloc (replicate n x) (the_state \<sigma>)))" and "r = fst (Array.alloc (replicate n x) (the_state \<sigma>))" and "Array.get (the_state \<sigma>') r = replicate n x" using assms apply (cases \<sigma>) apply simp apply (auto simp add: run.simps) apply (simp add: execute_simps) apply (simp add: Array.get_alloc) apply hypsubst_thin subgoal premises prems for a h' proof - from prems(2) have "h' = snd (Array.alloc (replicate n x) a)" "r = fst (Array.alloc (replicate n x) a)" by (auto simp add: execute_simps) then show ?thesis by (rule prems(1)) qed done lemma run_make[run_elims]: assumes "run (Array.make n f) \<sigma> \<sigma>' r" "\<not>is_exn \<sigma>" obtains "\<sigma>' = Some (snd (Array.alloc (map f [0 ..< n]) (the_state \<sigma>)))" "r = fst (Array.alloc (map f [0 ..< n]) (the_state \<sigma>))" "Array.get (the_state \<sigma>') r = (map f [0 ..< n])" using assms apply (cases \<sigma>) subgoal by simp subgoal by (simp add: run.simps execute_simps Array.get_alloc; fastforce) done lemma run_upd[run_elims]: assumes "run (Array.upd i x a) \<sigma> \<sigma>' res" "\<not>is_exn \<sigma>" obtains "\<not> i < Array.length (the_state \<sigma>) a" "\<sigma>' = None" | "i < Array.length (the_state \<sigma>) a" "\<sigma>' = Some (Array.update a i x (the_state \<sigma>))" "res = a" using assms apply (cases \<sigma>) apply simp apply (cases "i < Array.length (the_state \<sigma>) a") apply (auto simp add: run.simps) apply (simp_all only: execute_simps) prefer 3 apply auto[2] apply hypsubst_thin subgoal premises prems for aa h' proof - from prems(3) have "h' = Array.update a i x aa" "res = a" by auto then show ?thesis by (rule prems(1)) qed done lemma run_nth[run_elims]: assumes "run (Array.nth a i) \<sigma> \<sigma>' r" "\<not>is_exn \<sigma>" obtains "\<not>is_exn \<sigma>" "i < Array.length (the_state \<sigma>) a" "r = (Array.get (the_state \<sigma>) a) ! i" "\<sigma>' = \<sigma>" | "\<not> i < Array.length (the_state \<sigma>) a" "\<sigma>' = None" using assms apply (cases \<sigma>) apply simp apply (cases "i < Array.length (the_state \<sigma>) a") apply (auto simp add: run.simps) apply (simp_all only: execute_simps) prefer 3 apply auto[2] apply hypsubst_thin subgoal premises prems for aa h' proof - from prems(3) have "r = Array.get aa a ! i" "h' = aa" by auto then show ?thesis by (rule prems(1)) qed done lemma run_of_list[run_elims]: assumes "run (Array.of_list xs) \<sigma> \<sigma>' r" "\<not>is_exn \<sigma>" obtains "\<sigma>' = Some (snd (Array.alloc xs (the_state \<sigma>)))" "r = fst (Array.alloc xs (the_state \<sigma>))" "Array.get (the_state \<sigma>') r = xs" using assms apply (cases \<sigma>) apply simp apply (auto simp add: run.simps) apply (simp add: execute_simps) apply (simp add: Array.get_alloc) apply hypsubst_thin subgoal premises prems for a h' proof - from prems(2) have "h' = snd (Array.alloc xs a)" "r = fst (Array.alloc xs a)" by (auto simp add: execute_simps) then show ?thesis by (rule prems(1)) qed done lemma run_freeze[run_elims]: assumes "run (Array.freeze a) \<sigma> \<sigma>' r" "\<not>is_exn \<sigma>" obtains "\<sigma>' = \<sigma>" "r = Array.get (the_state \<sigma>) a" using assms apply (cases \<sigma>) by (auto simp add: run.simps execute_simps) subsection \<open>Reference Commands\<close> lemma run_new_ref[run_elims]: assumes "run (ref x) \<sigma> \<sigma>' r" "\<not>is_exn \<sigma>" obtains "\<sigma>' = Some (snd (Ref.alloc x (the_state \<sigma>)))" "r = fst (Ref.alloc x (the_state \<sigma>))" "Ref.get (the_state \<sigma>') r = x" using assms apply (cases \<sigma>) apply simp apply (auto simp add: run.simps) apply (simp add: execute_simps) apply hypsubst_thin subgoal premises prems for a h' proof - from prems(2) have "h' = snd (Ref.alloc x a)" "r = fst (Ref.alloc x a)" by (auto simp add: execute_simps) then show ?thesis by (rule prems(1)) qed done lemma "fst (Ref.alloc x h) = Ref (lim h)" unfolding alloc_def by (simp add: Let_def) lemma run_update[run_elims]: assumes "run (p := x) \<sigma> \<sigma>' r" "\<not>is_exn \<sigma>" obtains "\<sigma>' = Some (Ref.set p x (the_state \<sigma>))" "r = ()" using assms unfolding Ref.update_def by (auto elim: run_heap) lemma run_lookup[run_elims]: assumes "run (!p) \<sigma> \<sigma>' r" "\<not> is_exn \<sigma>" obtains "\<not>is_exn \<sigma>" "\<sigma>' = \<sigma>" "r = Ref.get (the_state \<sigma>) p" using assms apply (cases \<sigma>) by (auto simp add: run.simps execute_simps) end
# Example of vOptSpecific, for the 2LAP # when the numerical instance is read on a file, according to the LAP format # July 2017 using vOptSpecific m = load2LAP("2ap03.dat") # comment: set up the path to the file if required z1, z2, S = vSolve( m )
[STATEMENT] lemma brouwer_weak: fixes f :: "'a::euclidean_space \<Rightarrow> 'a" assumes "compact S" and "convex S" and "interior S \<noteq> {}" and "continuous_on S f" and "f ` S \<subseteq> S" obtains x where "x \<in> S" and "f x = x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>x. \<lbrakk>x \<in> S; f x = x\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<And>x. \<lbrakk>x \<in> S; f x = x\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] let ?U = "cbox 0 One :: 'a set" [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<And>x. \<lbrakk>x \<in> S; f x = x\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] have "\<Sum>Basis /\<^sub>R 2 \<in> interior ?U" [PROOF STATE] proof (prove) goal (1 subgoal): 1. One /\<^sub>R 2 \<in> interior (cbox (0::'a) One) [PROOF STEP] proof (rule interiorI) [PROOF STATE] proof (state) goal (3 subgoals): 1. open ?T 2. One /\<^sub>R 2 \<in> ?T 3. ?T \<subseteq> cbox (0::'a) One [PROOF STEP] let ?I = "(\<Inter>i\<in>Basis. {x::'a. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1})" [PROOF STATE] proof (state) goal (3 subgoals): 1. open ?T 2. One /\<^sub>R 2 \<in> ?T 3. ?T \<subseteq> cbox (0::'a) One [PROOF STEP] show "open ?I" [PROOF STATE] proof (prove) goal (1 subgoal): 1. open (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) [PROOF STEP] by (intro open_INT finite_Basis ballI open_Int, auto intro: open_Collect_less simp: continuous_on_inner) [PROOF STATE] proof (state) this: open (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) goal (2 subgoals): 1. One /\<^sub>R 2 \<in> (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) 2. (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) \<subseteq> cbox (0::'a) One [PROOF STEP] show "\<Sum>Basis /\<^sub>R 2 \<in> ?I" [PROOF STATE] proof (prove) goal (1 subgoal): 1. One /\<^sub>R 2 \<in> (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) [PROOF STEP] by simp [PROOF STATE] proof (state) this: One /\<^sub>R 2 \<in> (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) goal (1 subgoal): 1. (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) \<subseteq> cbox (0::'a) One [PROOF STEP] show "?I \<subseteq> cbox 0 One" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) \<subseteq> cbox (0::'a) One [PROOF STEP] unfolding cbox_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) \<subseteq> {x. \<forall>i\<in>Basis. (0::'a) \<bullet> i \<le> x \<bullet> i \<and> x \<bullet> i \<le> One \<bullet> i} [PROOF STEP] by force [PROOF STATE] proof (state) this: (\<Inter>i\<in>Basis. {x. 0 < x \<bullet> i} \<inter> {x. x \<bullet> i < 1}) \<subseteq> cbox (0::'a) One goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: One /\<^sub>R 2 \<in> interior (cbox (0::'a) One) goal (1 subgoal): 1. (\<And>x. \<lbrakk>x \<in> S; f x = x\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] then [PROOF STATE] proof (chain) picking this: One /\<^sub>R 2 \<in> interior (cbox (0::'a) One) [PROOF STEP] have *: "interior ?U \<noteq> {}" [PROOF STATE] proof (prove) using this: One /\<^sub>R 2 \<in> interior (cbox (0::'a) One) goal (1 subgoal): 1. interior (cbox (0::'a) One) \<noteq> {} [PROOF STEP] by fast [PROOF STATE] proof (state) this: interior (cbox (0::'a) One) \<noteq> {} goal (1 subgoal): 1. (\<And>x. \<lbrakk>x \<in> S; f x = x\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] have *: "?U homeomorphic S" [PROOF STATE] proof (prove) goal (1 subgoal): 1. cbox (0::'a) One homeomorphic S [PROOF STEP] using homeomorphic_convex_compact[OF convex_box(1) compact_cbox * assms(2,1,3)] [PROOF STATE] proof (prove) using this: cbox (0::'a) One homeomorphic S goal (1 subgoal): 1. cbox (0::'a) One homeomorphic S [PROOF STEP] . [PROOF STATE] proof (state) this: cbox (0::'a) One homeomorphic S goal (1 subgoal): 1. (\<And>x. \<lbrakk>x \<in> S; f x = x\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] have "\<forall>f. continuous_on ?U f \<and> f ` ?U \<subseteq> ?U \<longrightarrow> (\<exists>x\<in>?U. f x = x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>f. continuous_on (cbox (0::'a) One) f \<and> f ` cbox (0::'a) One \<subseteq> cbox (0::'a) One \<longrightarrow> (\<exists>x\<in>cbox (0::'a) One. f x = x) [PROOF STEP] using brouwer_cube [PROOF STATE] proof (prove) using this: \<lbrakk>continuous_on (cbox (0::?'a) One) ?f; ?f ` cbox (0::?'a) One \<subseteq> cbox (0::?'a) One\<rbrakk> \<Longrightarrow> \<exists>x\<in>cbox (0::?'a) One. ?f x = x goal (1 subgoal): 1. \<forall>f. continuous_on (cbox (0::'a) One) f \<and> f ` cbox (0::'a) One \<subseteq> cbox (0::'a) One \<longrightarrow> (\<exists>x\<in>cbox (0::'a) One. f x = x) [PROOF STEP] by auto [PROOF STATE] proof (state) this: \<forall>f. continuous_on (cbox (0::'a) One) f \<and> f ` cbox (0::'a) One \<subseteq> cbox (0::'a) One \<longrightarrow> (\<exists>x\<in>cbox (0::'a) One. f x = x) goal (1 subgoal): 1. (\<And>x. \<lbrakk>x \<in> S; f x = x\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<forall>f. continuous_on (cbox (0::'a) One) f \<and> f ` cbox (0::'a) One \<subseteq> cbox (0::'a) One \<longrightarrow> (\<exists>x\<in>cbox (0::'a) One. f x = x) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<forall>f. continuous_on (cbox (0::'a) One) f \<and> f ` cbox (0::'a) One \<subseteq> cbox (0::'a) One \<longrightarrow> (\<exists>x\<in>cbox (0::'a) One. f x = x) goal (1 subgoal): 1. thesis [PROOF STEP] unfolding homeomorphic_fixpoint_property[OF *] [PROOF STATE] proof (prove) using this: \<forall>g. continuous_on S g \<and> g ` S \<subseteq> S \<longrightarrow> (\<exists>y\<in>S. g y = y) goal (1 subgoal): 1. thesis [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: \<forall>g. continuous_on S g \<and> g ` S \<subseteq> S \<longrightarrow> (\<exists>y\<in>S. g y = y) compact S convex S interior S \<noteq> {} continuous_on S f f ` S \<subseteq> S goal (1 subgoal): 1. thesis [PROOF STEP] by (auto intro: that) [PROOF STATE] proof (state) this: thesis goal: No subgoals! [PROOF STEP] qed
[STATEMENT] lemma bigo_const [simp]: "(\<lambda>_. c) \<in> O[F](\<lambda>_. 1)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<lambda>_. c) \<in> O[F](\<lambda>_. 1::'b) [PROOF STEP] by (rule bigoI[of _ "norm c"]) simp
#ifndef SETTINGSWIDGET_H #define SETTINGSWIDGET_H #include <QWidget> #include "utilities/usersettings.h" #include <gsl/gsl> #include <memory> class QDoubleSpinBox; namespace Ui { class DisparitySettingsWidget; } class DisparitySettingsWidget : public QWidget { Q_OBJECT public: explicit DisparitySettingsWidget(QWidget* parent = 0); ~DisparitySettingsWidget() override; void setUserSettings(gsl::not_null<UserSettings*> settings); UserSettings getUserSettings(); void conditionalAutoUpdate(); signals: void settingsUpdated(UserSettings updatedSettings); void accepted(); void rejected(); private: void ensureMinSmallerThanMax(gsl::not_null<QDoubleSpinBox*> min, gsl::not_null<QDoubleSpinBox*> max); void ensureMaxLargerThanMin(gsl::not_null<QDoubleSpinBox*> min, gsl::not_null<QDoubleSpinBox*> max); std::unique_ptr<Ui::DisparitySettingsWidget> ui; }; #endif // SETTINGSWIDGET_H
lemma open_superdiagonal: "open {(x,y) | x y. x > (y::'a::{linorder_topology})}"
import tactic.linarith example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) : v0 + 5 + (v1 - 3) + (c - 2) = 10 := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε := by linarith example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0) (h3 : 12*y - z < 0) : false := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε := by linarith example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith {discharger := `[ring SOP]} example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false := by linarith {restrict_type := ℚ} example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0) (h5 : 0 ≤ c) (h6 : c < 1) : v ≤ V := by linarith example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z)) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) : ¬ 12*y - 4* z < 0 := by linarith example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0) (h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false := by linarith example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10) (h4 : a + b - c < 3) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : ¬ b ≥ 0) : false := by linarith example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 := by linarith {exfalso := ff} example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false := by linarith using [rat.num_pos_iff_pos.mpr hx] example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℕ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℚ) (hx : ¬ x > 3*y) (h2 : ¬ y > 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (h1 : (1 : ℕ) < 1) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 := by linarith example (a b c : ℕ) : a + b ≥ a := by linarith example (a b c : ℕ) : ¬ a + b < a := by linarith example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0) (h'' : (6 + 3 * y) * y ≥ 0) : false := by linarith example (x y : ℕ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) : false := by linarith example (a b i : ℕ) (h1 : ¬ a < i) (h2 : b < i) (h3 : a ≤ b) : false := by linarith example (n : ℕ) (h1 : n ≤ 3) (h2 : n > 2) : n = 3 := by linarith example (z : ℕ) (hz : ¬ z ≥ 2) (h2 : ¬ z + 1 ≤ 2) : false := by linarith example (z : ℕ) (hz : ¬ z ≥ 2) : z + 1 ≤ 2 := by linarith example (a b c : ℚ) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c := by linarith example (N : ℕ) (n : ℕ) (Hirrelevant : n > N) (A : ℚ) (l : ℚ) (h : A - l ≤ -(A - l)) (h_1 : ¬A ≤ -A) (h_2 : ¬l ≤ -l) (h_3 : -(A - l) < 1) : A < l + 1 := by linarith example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) : d ≤ ((q : ℚ) - 1)*n := by linarith example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) : ((q : ℚ) - 1)*n - d = 1/3 * (((q : ℚ) - 1)*n) := by linarith example (a : ℚ) (ha : 0 ≤ a): 0 * 0 ≤ 2 * a := by linarith
If $p$ divides $q$, then $ap$ divides $q$.
lemma bounded_linear_right: "bounded_linear (\<lambda>b. a ** b)"
Scholes International Airport at Galveston ( IATA : GLS , ICAO : <unk> ) is a two @-@ runway airport in Galveston ; the airport is primarily used for general aviation , offshore energy transportation , and some limited military operations . The nearest commercial airline service for the city is operated out of Houston through William P. Hobby Airport and George Bush Intercontinental Airport . The University of Texas Medical Branch has two heliports , one for Ewing Hall and one for its emergency room .
module Main -- where main : IO () main = do let x = 69.0 case x of 69.0 => print $ 2.0 _ => print $ 4.0
function draw_mandelbrot(x0, x1, y0, y1) n_grid = 1000; [x,y] = meshgrid(linspace(x0,x1,n_grid), linspace(y0,y1,n_grid)); c = x + 1i*y; z = c; n_iter = 100; M = zeros(size(c)); for i = 1:n_iter z = z.^2 + c; M(M==0 & abs(z)>2) = n_iter-i; end imagesc(x(1,:), y(:,1),M) colormap jet
module Progress where open import Prelude open import T ---- progress module Progress where -- Define a datatype representing that a term satisfies progress data TProgress : ∀{A} → TCExp A → Set where prog-val : ∀{A} {e : TCExp A} → (D : TVal e) → TProgress e prog-step : ∀{A} {e e' : TCExp A} → (D : e ~> e') → TProgress e -- prove that all terms satisfy progress progress : ∀{A} (e : TCExp A) → TProgress e progress (var ()) progress (Λ e) = prog-val val-lam progress (e₁ $ e₂) with progress e₁ progress (e₁ $ e₂) | prog-step D = prog-step (step-app-l D) progress (.(Λ e) $ e₂) | prog-val (val-lam {_} {_} {e}) = prog-step step-beta progress zero = prog-val val-zero progress (suc e) with progress e ... | prog-val D = prog-val (val-suc D) ... | prog-step D' = prog-step (step-suc D') progress (rec e e₀ es) with progress e progress (rec .zero e₀ es) | prog-val val-zero = prog-step step-rec-z progress (rec .(suc _) e₀ es) | prog-val (val-suc y) = prog-step (step-rec-s y) ... | prog-step D = prog-step (step-rec D) open Progress public
{-| Type aliases for activation functions and their derivative. -} module ML.NN.ActivationFunction (ActivationFunction, ActivationFunctionDerivative) where import Numeric.LinearAlgebra (R) -- | An activation function for a neuron. type ActivationFunction = R -> R -- | The derivative of a neuron activation function. type ActivationFunctionDerivative = R -> R
module DataStream function getDataSet(file) stream = open(file); end function getDataSetCount(file) dataset = getDataSet(file) line=0; for i in enumerate(eachline(dataset)) #println(i) line+=1 end closeDataSet(dataset) return line; end function getFeatureCount(file, delimiter=",") dataset = getDataSet(file) line=readline(dataset); closeDataSet(dataset) return length(split(line,delimiter)); end function resetStream(stream) seekstart(stream) end function closeDataSet(stream) close(stream) end end
from Cython.Build import cythonize from setuptools import setup, find_packages from setuptools.extension import Extension import numpy as np ext_modules = [ Extension("tsdf.TSDFVolume", ["src/tsdf/TSDFVolume.pyx"], include_dirs=[np.get_include()]) ] setup(name='tsdf', version='0.1dev', packages=find_packages('src'), package_dir={'': 'src'}, ext_modules=cythonize(ext_modules, language_level = "3"))
import ..list.map_accum_lemmas import .zero_length_lemmas universe variables u namespace vector variable {α : Type u} variable {n : ℕ} local infix `++`:65 := vector.append -- Simplify map_accumr₂ over empty lists @[simp] theorem map_accumr₂_nil {α β γ φ : Type} (f : α → β → γ → γ × φ) (x : vector α 0) (y : vector β 0) (i₀ : γ) : map_accumr₂ f x y i₀ = (i₀, nil) := begin simp [length_zero_vector_is_nil x, length_zero_vector_is_nil y , nil, map_accumr₂, list.map_accumr₂], apply congr_arg, apply vector.eq, simp, end -- Simplify map_accumr₂ over appending single element to end of lists @[simp] theorem map_accumr₂_append1 {n : ℕ} {α β γ φ : Type} (f : α → β → γ → γ × φ) (x : vector α n) (a : α) (y : vector β n) (b : β) (c : γ) : map_accumr₂ f (x ++ cons a nil) (y ++ cons b nil) c = let r := f a b c in let z := map_accumr₂ f x y (r.fst) in ⟨ z.fst, z.snd ++ cons r.snd nil⟩ := begin -- Reduce to proof about list.map_accumr₂ and use corresponding theorem cases x with xv xp, cases y with yv yp, have len_pr : xv^.length = yv^.length, { simp [xp, yp] }, simp [vector.cons, vector.nil, vector.append, map_accumr₂], simp [list.map_accumr₂_append1 f _ _ len_pr], end end vector
# Goal: To do sorting. # # The approach here needs to be explained. If `i' is a vector of # integers, then the data frame D[i,] picks up rows from D based # on the values found in `i'. # # The order() function makes an integer vector which is a correct # ordering for the purpose of sorting. D <- data.frame(x=c(1,2,3,1), y=c(7,19,2,2)) D # Sort on x indexes <- order(D$x) D[indexes,] # Print out sorted dataset, sorted in reverse by y D[rev(order(D$y)),]
\subsection{Binary functions} \subsubsection{Properties of binary functions} Binary functions can be written as: \(f(a,b)=a\oplus b\) A function is commutative if: \(x\oplus y = y\oplus x\) A function is associative if: \((x\oplus y)\oplus z = x\oplus (y\oplus z)\) A function \(\otimes \) is left distributive over \(\oplus \) if: \(x\otimes (y\oplus z)=(x\otimes y) \oplus (x\otimes z)\) Alternatively, function \(\otimes \) is right distributive over \(\oplus \) if: \((x\oplus y)\otimes z=(x\otimes z) \oplus (y\oplus z)\) A function is distributive over another function if it both left and right distributive over it.
Formal statement is: lemma polynomial_function_diff [intro]: "\<lbrakk>polynomial_function f; polynomial_function g\<rbrakk> \<Longrightarrow> polynomial_function (\<lambda>x. f x - g x)" Informal statement is: If $f$ and $g$ are polynomial functions, then so is $f - g$.
Formal statement is: lemma homeomorphic_to_disc: assumes S: "S \<noteq> {}" and prev: "S = UNIV \<or> (\<exists>f g. f holomorphic_on S \<and> g holomorphic_on ball 0 1 \<and> (\<forall>z \<in> S. f z \<in> ball 0 1 \<and> g(f z) = z) \<and> (\<forall>z \<in> ball 0 1. g z \<in> S \<and> f(g z) = z))" (is "_ \<or> ?P") shows "S homeomorphic ball (0::complex) 1" Informal statement is: If $S$ is a nonempty set and either $S = \mathbb{C}$ or there exist holomorphic functions $f$ and $g$ such that $f$ maps $S$ into the unit disc, $g$ maps the unit disc into $S$, and $g \circ f$ and $f \circ g$ are the identity maps on $S$ and the unit disc, respectively, then $S$ is homeomorphic to the unit disc.
subroutine JOB_CTL( lin, & lout, & jobctl ) implicit none !----------------------------------------------------------------------- ! ... Dummy arguments !----------------------------------------------------------------------- integer, intent(in) :: lin, lout character(len=16), intent(out) :: jobctl(8) ! job control variables !----------------------------------------------------------------------- ! ... Local variables !----------------------------------------------------------------------- integer :: kpar, nchar, k integer :: parsw(8) real :: time character(len=80) :: buff character(len=80) :: buffh character(len=20) :: parkey(8), keywrd logical :: found integer :: LENOF parkey(1) = 'SIMULATIONTIMESTEP' parkey(2) = 'CRAYTIMELIMIT' parkey(3) = 'SIMULATIONLENGTH' parkey(4) = 'CRAYMEMORY' parkey(5) = 'ACCOUNT' parkey(6) = 'CASE' parkey(7) = 'RESTART' parkey(8) = 'CRAYQUE' parsw = 0 !----------------------------------------------------------------------- ! ... Scan for valid option keyword !----------------------------------------------------------------------- do call CARDIN( lin, buff, nchar ) buffh = buff call UPCASE ( buffh ) if( buffh == 'ENDJOBCONTROL' ) then exit end if k = INDEX( buffh(:nchar), '=' ) if( k /= 0 ) then keywrd = buffh(:k-1) found = .false. do kpar = 1,8 if( keywrd == parkey(kpar) ) then found = .true. exit end if end do else !----------------------------------------------------------------------- ! ... Invalid parameter keyword; terminate the program !----------------------------------------------------------------------- call ERRMES ( ' job ctl specification has no = operator@', lout, buff, 1, buff ) end if if( .not. found) then call ERRMES ( ' # is an invalid job control parameter keyword@', & lout, & keywrd, & LENOF(20,keywrd), & buffh ) end if !----------------------------------------------------------------------- ! ... Valid parameter keyword; now check for duplicate keyword !----------------------------------------------------------------------- if( parsw(kpar) /= 0 ) then call ERRMES( '0 *** # has already been specified@', lout, parkey(kpar), k, ' ' ) end if !----------------------------------------------------------------------- ! ... Set individual options !----------------------------------------------------------------------- if( kpar <= 3 ) then if( kpar == 3 ) then if( buffh(nchar-4:nchar) == 'STEPS' ) then jobctl(3) = buff(k+1:nchar-5) else call TIMCON( buff(k+1:nchar), time, lout ) jobctl(3) = buff(k+1:nchar) end if else call TIMCON( buff(k+1:nchar), time, lout ) jobctl(kpar) = buff(k+1:nchar) end if else jobctl(kpar) = buff(k+1:nchar) end if parsw(kpar) = 1 end do end subroutine JOB_CTL
{-# OPTIONS --irrelevant-projections #-} data _≡_ {A : Set} : A → A → Set where refl : (x : A) → x ≡ x module Erased where record Erased (A : Set) : Set where constructor [_] field @0 erased : A open Erased record _↔_ (A B : Set) : Set where field to : A → B from : B → A to∘from : ∀ x → to (from x) ≡ x from∘to : ∀ x → from (to x) ≡ x postulate A : Set P : (B : Set) → (Erased A → B) → Set p : (B : Set) (f : Erased A ↔ B) → P B (_↔_.to f) fails : P (Erased (Erased A)) (λ (x : Erased A) → [ x ]) fails = p _ (record { from = λ ([ x ]) → [ erased x ] ; to∘from = refl ; from∘to = λ _ → refl _ }) module Irrelevant where record Irrelevant (A : Set) : Set where constructor [_] field .irr : A open Irrelevant record _↔_ (A B : Set) : Set where field to : A → B from : B → A to∘from : ∀ x → to (from x) ≡ x from∘to : ∀ x → from (to x) ≡ x postulate A : Set P : (B : Set) → (Irrelevant A → B) → Set p : (B : Set) (f : Irrelevant A ↔ B) → P B (_↔_.to f) fails : P (Irrelevant (Irrelevant A)) (λ (x : Irrelevant A) → [ x ]) fails = p _ (record { from = λ ([ x ]) → [ irr x ] ; to∘from = refl ; from∘to = λ _ → refl _ })
[STATEMENT] lemma not_FinalAllow: "foo \<noteq> Decision FinalAllow \<longleftrightarrow> foo = Decision FinalDeny \<or> foo = Undecided" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (foo \<noteq> Decision FinalAllow) = (foo = Decision FinalDeny \<or> foo = Undecided) [PROOF STEP] apply(cases foo) [PROOF STATE] proof (prove) goal (2 subgoals): 1. foo = Undecided \<Longrightarrow> (foo \<noteq> Decision FinalAllow) = (foo = Decision FinalDeny \<or> foo = Undecided) 2. \<And>x2. foo = Decision x2 \<Longrightarrow> (foo \<noteq> Decision FinalAllow) = (foo = Decision FinalDeny \<or> foo = Undecided) [PROOF STEP] apply simp_all [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x2. foo = Decision x2 \<Longrightarrow> (x2 \<noteq> FinalAllow) = (x2 = FinalDeny) [PROOF STEP] apply(rename_tac x2) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x2. foo = Decision x2 \<Longrightarrow> (x2 \<noteq> FinalAllow) = (x2 = FinalDeny) [PROOF STEP] apply(case_tac x2) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>x2. \<lbrakk>foo = Decision x2; x2 = FinalAllow\<rbrakk> \<Longrightarrow> (x2 \<noteq> FinalAllow) = (x2 = FinalDeny) 2. \<And>x2. \<lbrakk>foo = Decision x2; x2 = FinalDeny\<rbrakk> \<Longrightarrow> (x2 \<noteq> FinalAllow) = (x2 = FinalDeny) [PROOF STEP] apply(simp_all) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
/** * \copyright * Copyright (c) 2012-2018, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #pragma once /// The LinearSolverLibrarySetup takes care of proper initialization and /// shutting down of an external linear solver library. The concrete /// implementation is chosen by the build system. /// An object of this class must be created at the begining of the scope where /// it is used. When the scope closes (or the object is destroyed explicitly) /// library shutting down functions are automatically called. /// The default implementation is empty providing polymorphic behaviour when /// using this class. #include "NumLib/DOF/GlobalMatrixProviders.h" #if defined(USE_PETSC) #include <petsc.h> #include <mpi.h> namespace ApplicationsLib { struct LinearSolverLibrarySetup final { LinearSolverLibrarySetup(int argc, char* argv[]) { MPI_Init(&argc, &argv); char help[] = "ogs6 with PETSc \n"; PetscInitialize(&argc, &argv, nullptr, help); } ~LinearSolverLibrarySetup() { NumLib::cleanupGlobalMatrixProviders(); PetscFinalize(); MPI_Finalize(); } }; } // ApplicationsLib #elif defined(USE_LIS) #include <lis.h> namespace ApplicationsLib { struct LinearSolverLibrarySetup final { LinearSolverLibrarySetup(int argc, char* argv[]) { lis_initialize(&argc, &argv); } ~LinearSolverLibrarySetup() { NumLib::cleanupGlobalMatrixProviders(); lis_finalize(); } }; } // ApplicationsLib #else namespace ApplicationsLib { struct LinearSolverLibrarySetup final { LinearSolverLibrarySetup(int /*argc*/, char* /*argv*/[]) {} ~LinearSolverLibrarySetup() { NumLib::cleanupGlobalMatrixProviders(); } }; } // ApplicationsLib #endif
module heat_juafem_examples using FinEtools using FinEtools.MeshExportModule using Compat.Test function heat_juafem_example() println("""Heat conduction example from JuAFEM.""") t0 = time() A = 2.0 thermal_conductivity = [i==j ? one(FFlt) : zero(FFlt) for i=1:2, j=1:2]; # conductivity matrix function getsource!(forceout::FFltVec, XYZ::FFltMat, tangents::FFltMat, fe_label::FInt) forceout[1] = 1.0; #heat source end N = 1000; println("Mesh generation") @time fens,fes = Q4block(A, A, N, N) fens.xyz[:,1] .-= A/2 fens.xyz[:,2] .-= A/2 geom = NodalField(fens.xyz) Temp = NodalField(zeros(size(fens.xyz,1),1)) println("Searching nodes for BC") @time l1 = selectnode(fens; box=[-A/2 -A/2 -A/2 A/2], inflate = 1.0/N/100.0) @time l2 = selectnode(fens; box=[A/2 A/2 -A/2 A/2], inflate = 1.0/N/100.0) @time l3 = selectnode(fens; box=[-A/2 A/2 -A/2 -A/2], inflate = 1.0/N/100.0) @time l4 = selectnode(fens; box=[-A/2 A/2 A/2 A/2], inflate = 1.0/N/100.0) List = vcat(l1, l2, l3, l4); setebc!(Temp, List, true, 1, 0.0) applyebc!(Temp) numberdofs!(Temp) t1 = time() m = MatHeatDiff(thermal_conductivity) femm = FEMMHeatDiff(IntegData(fes, GaussRule(2, 2)), m) println("Conductivity") @time K=conductivity(femm, geom, Temp) println("Internal heat generation") fi = ForceIntensity(FFlt, 1, getsource!); @time F1 = distribloads(femm, geom, Temp, fi, 3); println("Factorization") @time K = cholesky(K) println("Solution of the factorized system") @time U = K\(F1) scattersysvec!(Temp, U[:]) println("Total time elapsed = $(time() - t0) [s]") println("Solution time elapsed = $(time() - t1) [s]") println("Maximum temperature = $(maximum(Temp.values)) ") # using MeshExportModule # File = "a.vtk" # MeshExportModule.vtkexportmesh(File, fes.conn, hcat(geom.values, Temp.values), MeshExportModule.Q4; scalars=[("Temperature", Temp.values)]) # @async run(`"paraview.exe" $File`) end # heat_juafem_example function allrun() #println("#####################################################") println("# heat_juafem_example ") heat_juafem_example() return true end # function allrun end # module heat_juafem_examples
[STATEMENT] lemma match_overlapping: assumes "linear t\<^sub>1" "linear t\<^sub>2" assumes "match t\<^sub>1 u = Some env\<^sub>1" "match t\<^sub>2 u = Some env\<^sub>2" shows "overlapping t\<^sub>1 t\<^sub>2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. overlapping t\<^sub>1 t\<^sub>2 [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. overlapping t\<^sub>1 t\<^sub>2 [PROOF STEP] define env\<^sub>1' where "env\<^sub>1' = (fmmap convert_term env\<^sub>1 :: (name, term) fmap)" [PROOF STATE] proof (state) this: env\<^sub>1' = fmmap convert_term env\<^sub>1 goal (1 subgoal): 1. overlapping t\<^sub>1 t\<^sub>2 [PROOF STEP] define env\<^sub>2' where "env\<^sub>2' = (fmmap convert_term env\<^sub>2 :: (name, term) fmap)" [PROOF STATE] proof (state) this: env\<^sub>2' = fmmap convert_term env\<^sub>2 goal (1 subgoal): 1. overlapping t\<^sub>1 t\<^sub>2 [PROOF STEP] from assms [PROOF STATE] proof (chain) picking this: linear t\<^sub>1 linear t\<^sub>2 match t\<^sub>1 u = Some env\<^sub>1 match t\<^sub>2 u = Some env\<^sub>2 [PROOF STEP] have "match t\<^sub>1 (convert_term u :: term) = Some env\<^sub>1'" "match t\<^sub>2 (convert_term u :: term) = Some env\<^sub>2'" [PROOF STATE] proof (prove) using this: linear t\<^sub>1 linear t\<^sub>2 match t\<^sub>1 u = Some env\<^sub>1 match t\<^sub>2 u = Some env\<^sub>2 goal (1 subgoal): 1. match t\<^sub>1 (convert_term u) = Some env\<^sub>1' &&& match t\<^sub>2 (convert_term u) = Some env\<^sub>2' [PROOF STEP] unfolding env\<^sub>1'_def env\<^sub>2'_def [PROOF STATE] proof (prove) using this: linear t\<^sub>1 linear t\<^sub>2 match t\<^sub>1 u = Some env\<^sub>1 match t\<^sub>2 u = Some env\<^sub>2 goal (1 subgoal): 1. match t\<^sub>1 (convert_term u) = Some (fmmap convert_term env\<^sub>1) &&& match t\<^sub>2 (convert_term u) = Some (fmmap convert_term env\<^sub>2) [PROOF STEP] by (metis convert_term_match)+ [PROOF STATE] proof (state) this: match t\<^sub>1 (convert_term u) = Some env\<^sub>1' match t\<^sub>2 (convert_term u) = Some env\<^sub>2' goal (1 subgoal): 1. overlapping t\<^sub>1 t\<^sub>2 [PROOF STEP] with assms [PROOF STATE] proof (chain) picking this: linear t\<^sub>1 linear t\<^sub>2 match t\<^sub>1 u = Some env\<^sub>1 match t\<^sub>2 u = Some env\<^sub>2 match t\<^sub>1 (convert_term u) = Some env\<^sub>1' match t\<^sub>2 (convert_term u) = Some env\<^sub>2' [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: linear t\<^sub>1 linear t\<^sub>2 match t\<^sub>1 u = Some env\<^sub>1 match t\<^sub>2 u = Some env\<^sub>2 match t\<^sub>1 (convert_term u) = Some env\<^sub>1' match t\<^sub>2 (convert_term u) = Some env\<^sub>2' goal (1 subgoal): 1. overlapping t\<^sub>1 t\<^sub>2 [PROOF STEP] by (metis overlappingI match_matches) [PROOF STATE] proof (state) this: overlapping t\<^sub>1 t\<^sub>2 goal: No subgoals! [PROOF STEP] qed
Toward $\pi$-calculus in idris ============================== _WIP by [Dan Connolly][dckc], Apr 2018_ _This is a [literate idris][lp] document, with idris code ..._ > module picalc2 > > %access export > %default total _... interspersed with text from ..._ * Milner, Robin. _[The polyadic π-calculus: a tutorial.][RM93]_ In Logic and algebra of specification, pp. 203-246. Springer, Berlin, Heidelberg, 1993. _We're having some fun with [KaTeX][] while we're at it._ [dckc]: http://www.madmode.com/contact/ [RM93]: https://pdfs.semanticscholar.org/5d25/0a3a14f68abb1ae0111d35b8220b4472b277.pdf [lp]: http://docs.idris-lang.org/en/latest/tutorial/miscellany.html#literate-programming [KaTeX]: https://khan.github.io/KaTeX/ 2.1 Basic ideas --------------- The most primitive entity in $\pi$-calculus is a _name_. Names, infinitely many, are $x, y, ... \in \mathcal{X}$; they have no structure. In the basic version of $\pi$-calculus which we begin with, there is only one other kind of entity; a _process_. Processes are $P, Q, ... \in \mathcal{P}$ and are built from names by this syntax $$P ::= \Sigma_{i\in I}\pi_i.P_i \;|\; P|Q \;|\; !P \;|\; (\nu x)P$$ > {- `mutual` lets us forward reference Action from Process.-} > > syntax [p] "|" [q] = Par p q; > syntax "!" [p] = (Replicated p); > > mutual > ||| Processes are built from names, so `Process` is a > ||| type constructor from names. > data Process : {name: Type} -> Type where The summation form represents a process able to take part in one -- but only one -- of several alternatives for communication. > Sum: (List (Action {name}, Process {name})) -> Process {name} $P | Q$ -- "$P$ par $Q$" -- simply means that $P$ and $Q$ are concurrently active. > Par: (P: Process {name}) -> (Q: Process {name}) -> Process {name} $!P$ -- "bang $P$" means $P|P|...$ as many copies as you wish. > Replicated: (P: Process {name}) -> Process {name} $(\nu x)P$ -- "new $x$ in $P$" -- restricts the use of the name $x$ to $P$. > New: (x: name) -> (P: Process {name}) -> Process {name} In a summand $\pi.P$ the prefix $\pi$ represents an _atomic action_, the first action performed by $\pi.P$. > data Action : {name: Type} -> Type where There are two basic forms of prefix: - $x(y)$, which binds $y$ in the prefix process, means "input some name -- call it $y$ -- along the link named $x$" > Input: (x: name) -> (y: name) -> Action {name} - $\bar{x}y$ , which does not bind $y$, means "output the name $y$ along the link named $x$". > Output: (x: name) -> (y: name) -> Action {name} > In the case $I = \emptyset$, we write the sum as $0$. > zero: Process > zero = Sum [] We call $x$ the _subject_ ... > subject: Action {name} -> name > subject (Input x y) = x > subject (Output x y) = x We call ... $y$ the _object_ > object: Action {name} -> name > object (Input x y) = y > object (Output x y) = y 2.2 Some simple examples ------------------------ _typo?_ Note that $R$ has become $\bar{y}v$ or $\bar{z}v$; ... _should be:_ Note that $Q$ has become $\bar{y}v$ or $\bar{z}v$; ... _no?_ 2.3 Structural Congruence ------------------------- _Note: In order to convince idris of the [totality][] of `fn` and `bn`, we use `assert_smaller` to help it understand that `(Sum rest)` is structurally smaller than `(Sum ((pi, P) :: rest))`._ [totality]: http://docs.idris-lang.org/en/latest/reference/misc.html?highlight=assert_smaller#totality-checking-assertions > mutual > ||| free names of a process > fn: Eq name => (Process {name}) -> (List name) > fn (Sum []) = [] > fn (Sum ((pi, P) :: rest)) = union (fna pi) (union (fn P) > (fn (assert_smaller (Sum ((pi, P) :: rest)) (Sum rest))) ) > fn (P | Q) = union (fn P) (fn Q) > fn (Replicated P) = fn P > fn (New x P) = delete x (fn P) > > ||| free names of an action > fna: (Action {name}) -> (List name) > fna (Input x y) = [x] > fna (Output x y) = [x, y] > > mutual > ||| _names_ of a process > n: Eq name => Process {name} -> (List name) > n (Sum []) = [] > n (Sum ((pi, P) :: rest)) = union (n' pi) (union (n P) > (n (assert_smaller (Sum ((pi, P) :: rest)) (Sum rest))) ) > where > n': (Action {name}) -> (List name) > n' (Input x y) = [x, y] > n' (Output x y) = [x, y] > n (P | Q) = union (n P) (n Q) > n (Replicated P) = n P > n (New x P) = union [x] (n P) > > ||| bound names of a process > bn: Eq name => (Process {name}) -> (List name) > bn P = (n P) \\ (fn P) _Yay... idris can now compute:_ ``` λΠ> bn (Sum [((Output "x" "y"), zero)]) [] : List String λΠ> fn (Sum [((Output "x" "y"), zero)]) ["x", "y"] : List String ``` _next step(s): use techniques from [rhocaml](https://github.com/leithaus/rhocaml) to define structural equivalence and then prove the laws._ <style type="text/css"> .sourceCode { background: azure } </style>
lemma (in finite_measure) finite_measure_distr: assumes f: "f \<in> measurable M M'" shows "finite_measure (distr M M' f)"
Regional airports , such as Edinburgh Airport , have experienced strong growth in CAT operations in recent years . These operations are commercially and operationally incompatible with GA , and although there is no evidence of deliberate discrimination , the effect has been to discourage or exclude it . GA aircraft are being subject to significant increases in charges , including the imposition of handling fees in some cases . Some airports restrict or deny GA parking , and others limit or refuse certain GA activity . As a result , light GA aircraft are now rarely or never seen at large , busy international airports such as Heathrow , Stansted , Gatwick and Manchester .
/* Copyright 2003-2016 Joaquin M Lopez Munoz. * 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) * * See http://www.boost.org/libs/multi_index for library home page. */ #include <boost/config.hpp> #if defined(BOOST_GCC)&&(BOOST_GCC>=4*10000+6*100) #if !defined(BOOST_MULTI_INDEX_DETAIL_RESTORE_WSTRICT_ALIASING) #pragma GCC diagnostic push // #pragma GCC diagnostic ignored "-Wstrict-aliasing" #else #pragma GCC diagnostic pop #endif #endif
!*** Copyright (c) 1998, NVIDIA CORPORATION. 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. ! ! Test pointer assignments and associated function ! integer,parameter::n=15 integer result(n),expect(n) integer,pointer :: ap,bp,cp,dp integer,target :: a,b a = 1 b = 1 expect(:) = 1 result(:) = 1 ap => a bp => b if( .not.associated(ap) ) then result(1) = 0 print *,'ap should be associated' endif if( .not.associated(ap,a) ) then result(2) = 0 print *,'ap should be associated with a' endif if( .not.associated(bp) ) then result(3) = 0 print *,'bp should be associated' endif if( .not.associated(bp,b) ) then result(4) = 0 print *,'bp should be associated with b' endif if( associated(bp,a) ) then result(5) = 0 print *,'bp should not be associated with a' endif if( associated(ap,b) ) then result(6) = 0 print *,'ap should not be associated with b' endif if( associated(ap,bp) ) then result(7) = 0 print *,'ap should not be associated with bp' endif cp => a if( .not.associated(cp,a) ) then result(8) = 0 print *,'cp should be associated with a' endif if( associated(cp,b) ) then result(9) = 0 print *,'cp should not be associated with b' endif if( .not.associated(cp,ap) ) then result(10) = 0 print *,'cp should be associated with ap' endif if( associated(cp,bp) ) then result(11) = 0 print *,'cp should not be associated with bp' endif nullify(dp) nullify(cp) if( associated(cp) ) then result(12) = 0 print *,'cp should not be associated' endif if( associated(dp) ) then result(13) = 0 print *,'dp should not be associated' endif if( associated(dp,a) ) then result(14) = 0 print *,'dp should not be associated with a' endif if( associated(dp,cp) ) then result(15) = 0 print *,'dp should not be associated with cp' endif call check(result,expect,n) end
There is insufficient historical evidence to support the claim he knew any skills beyond archery . Contemporary records never once mention Zhou teaching Yue boxing . Despite this , various wuxia novels and folk legends have attributed many different military and supernatural skills to Zhou . These range from mastery of the bow , double swords and Chinese spear to that of <unk> hard qigong , Chuojiao boxing and even X @-@ ray vision . Wang Shaotang 's folktale even represents him as a master of Drunken Eight Immortals boxing .
Formal statement is: lemma norm_of_int [simp]: "norm (of_int z::'a::real_normed_algebra_1) = \<bar>of_int z\<bar>" Informal statement is: The norm of an integer is the absolute value of the integer.
State Before: n : ℕ ⊢ ∑ m in filter (fun x => x ∣ n) (range (succ n)), φ m = n State After: case h.e'_2 n : ℕ ⊢ ∑ m in filter (fun x => x ∣ n) (range (succ n)), φ m = Finset.sum (divisors n) φ Tactic: convert sum_totient _ using 1 State Before: case h.e'_2 n : ℕ ⊢ ∑ m in filter (fun x => x ∣ n) (range (succ n)), φ m = Finset.sum (divisors n) φ State After: case h.e'_2 n : ℕ ⊢ (∑ a in Ico 0 (succ n), if a ∣ n then φ a else 0) = ∑ a in Ico 1 (n + 1), if a ∣ n then φ a else 0 Tactic: simp only [Nat.divisors, sum_filter, range_eq_Ico] State Before: case h.e'_2 n : ℕ ⊢ (∑ a in Ico 0 (succ n), if a ∣ n then φ a else 0) = ∑ a in Ico 1 (n + 1), if a ∣ n then φ a else 0 State After: no goals Tactic: rw [sum_eq_sum_Ico_succ_bot] <;> simp
The Coldrum Stones are named after a nearby farm , Coldrum Lodge , which has since been demolished . The monument lies in a " rather isolated site " north @-@ east of the nearby village of Trottiscliffe , about 500 metres from a prehistoric track known as the Pilgrim 's Way . The tomb can be reached along a pathway known as Coldrum Lane , which is only accessible on foot . The nearest car park to Coldrum Lane can be found off of <unk> Lane in Trottiscliffe . Another nearby village is Addington , which is located one and a quarter miles away .
Require Import Coq.Classes.Morphisms. Require Import Coq.ZArith.ZArith Coq.micromega.Lia. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.ZUtil.Definitions. Require Import Crypto.Util.ZUtil.Hints.PullPush. Require Import Crypto.Util.ZUtil.ZSimplify.Core. Require Import Crypto.Util.ZUtil.ZSimplify.Simple. Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem. Require Import Crypto.Util.ZUtil.Tactics.ZeroBounds. Require Import Crypto.Util.ZUtil.Tactics.LtbToLt. Local Open Scope Z_scope. Module Z. Hint Rewrite Z.log2_pow2 Z.pow_1_r using solve [auto using Z.log2_nonneg with zarith] : push_Zpow. Lemma cc_m_eq_full : forall s x, Z.cc_m s x = if (s =? 1) then x * 2 else x / (s / 2). Proof. intros; cbv [Z.cc_m]. destruct (Decidable.dec (2 < s)). { assert (1 <= Z.log2 s) by (rewrite <-Z.log2_2; auto using Z.log2_le_mono with lia). break_match; Z.ltb_to_lt; try lia; []. match goal with H : _ = s |- _ => rewrite <-H end. autorewrite with Zshift_to_pow push_Zpow. reflexivity. } { assert (s < 0 \/ s = 0 \/ s = 1 \/ s = 2) by lia. destruct_head'_or; (subst s || destruct s); try reflexivity; try (cbn; autorewrite with zsimplify_const; lia). change (Z.log2 1 - 1) with (-1). rewrite (Z.shiftr_opp_r _ 1), Z.shiftl_mul_pow2 by lia. reflexivity. } Qed. Lemma cc_m_eq : forall s x, 2 < s -> Z.cc_m s x = x / (s / 2). Proof. intros; rewrite cc_m_eq_full; break_match; Z.ltb_to_lt; lia. Qed. Lemma cc_m_small : forall s x, s mod 2 = 0 -> 0 <= x < s -> 0 <= Z.cc_m s x < 2. Proof. intros. rewrite cc_m_eq_full. repeat match goal with | _ => break_innermost_match_step | _ => progress Z.ltb_to_lt | _ => split | _ => apply Z.div_lt_upper_bound | _ => solve [Z.zero_bounds] end. Z.div_mod_to_quot_rem_in_goal; lia. Qed. Lemma cc_m_Proper_le_r_gen s : (0 <= s /\ Proper (Z.le ==> Z.le) (Definitions.Z.cc_m s)) \/ (s < 0 /\ Proper (Basics.flip Z.le ==> Z.le) (Definitions.Z.cc_m s)). Proof. cbv [Basics.flip]. destruct (Z_lt_le_dec s 0); [ right | left ]; (split; [ assumption | ]). all: intros x0 x1 H; rewrite !cc_m_eq_full; break_innermost_match; Z.ltb_to_lt; [ nia | ]. all: Z.div_mod_to_quot_rem; nia. Qed. Hint Resolve cc_m_Proper_le_r_gen : zarith. Lemma cc_m_Proper_le_r s : Proper (Z.le ==> Z.le) (Definitions.Z.cc_m s) \/ Proper (Basics.flip Z.le ==> Z.le) (Definitions.Z.cc_m s). Proof. pose proof (cc_m_Proper_le_r_gen s); tauto. Qed. Hint Resolve cc_m_Proper_le_r : zarith. Lemma cc_m_Proper_le_r_pos s : Proper (Z.le ==> Z.le) (Definitions.Z.cc_m (Z.pos s)). Proof. pose proof (cc_m_Proper_le_r_gen (Z.pos s)); intuition lia. Qed. Hint Resolve cc_m_Proper_le_r_pos : zarith. Lemma cc_m_Proper_le_r_neg s : Proper (Basics.flip Z.le ==> Z.le) (Definitions.Z.cc_m (Z.neg s)). Proof. pose proof (cc_m_Proper_le_r_gen (Z.neg s)); intuition lia. Qed. Hint Resolve cc_m_Proper_le_r_neg : zarith. Lemma cc_m_Proper_le_r_0 : Proper (Z.le ==> Z.le) (Definitions.Z.cc_m 0). Proof. pose proof (cc_m_Proper_le_r_gen 0); intuition lia. Qed. Hint Resolve cc_m_Proper_le_r_0 : zarith. End Z.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_integration.h> #include "ccl.h" typedef struct{ double l; ccl_cosmology *cosmo; ccl_cl_tracer_collection_t *trc1; ccl_cl_tracer_collection_t *trc2; ccl_f2d_t *psp; int *status; } integ_cl_par; typedef struct{ int chipow; double l1; double l2; ccl_cosmology *cosmo; ccl_cl_tracer_collection_t *trc1; ccl_cl_tracer_collection_t *trc2; ccl_cl_tracer_collection_t *trc3; ccl_cl_tracer_collection_t *trc4; ccl_f3d_t *tsp; ccl_f1d_t *ker_extra; ccl_a_finder *finda; int *status; } integ_cov_par; static void update_chi_limits(ccl_cl_tracer_collection_t *trc, double *chimin, double *chimax, int is_union) { int itr; double chimin_h=1E15; double chimax_h=-1E15; for(itr=0; itr < trc->n_tracers; itr++) { if (trc->ts[itr]->chi_min < chimin_h) chimin_h = trc->ts[itr]->chi_min; if (trc->ts[itr]->chi_max > chimax_h) chimax_h = trc->ts[itr]->chi_max; } if(is_union) { if(chimin_h < *chimin) *chimin = chimin_h; if(chimax_h > *chimax) *chimax = chimax_h; } else { if(chimin_h > *chimin) *chimin = chimin_h; if(chimax_h < *chimax) *chimax = chimax_h; } } static void get_k_interval(ccl_cosmology *cosmo, ccl_cl_tracer_collection_t *trc1, ccl_cl_tracer_collection_t *trc2, double l, double *lkmin, double *lkmax) { int itr; // Loop through all tracers and find distance bounds double chi_min1 = 1E15; double chi_max1 = -1E15; for (itr=0; itr < trc1->n_tracers; itr++) { if (trc1->ts[itr]->chi_min < chi_min1) chi_min1 = trc1->ts[itr]->chi_min; if (trc1->ts[itr]->chi_max > chi_max1) chi_max1 = trc1->ts[itr]->chi_max; } double chi_min2 = 1E15; double chi_max2 = -1E15; for (itr=0; itr < trc2->n_tracers; itr++) { if (trc2->ts[itr]->chi_min < chi_min2) chi_min2 = trc2->ts[itr]->chi_min; if (trc2->ts[itr]->chi_max > chi_max2) chi_max2 = trc2->ts[itr]->chi_max; } // Find maximum of minima and minimum of maxima // (i.e. edges where the product of both kernels will have support). double chi_min = fmax(chi_min1, chi_min2); double chi_max = fmin(chi_max1, chi_max2); if (chi_min <= 0) chi_min = 0.5*(l+0.5)/cosmo->spline_params.K_MAX; // Don't go beyond kmax *lkmax = log(fmin(cosmo->spline_params.K_MAX, 2*(l+0.5)/chi_min)); *lkmin = log(fmax(cosmo->spline_params.K_MIN, (l+0.5)/chi_max)); } static double transfer_limber_single(ccl_cl_tracer_t *tr, double l, double lk, double k, double chi_l, double a_l, ccl_cosmology *cosmo, ccl_f2d_t *psp, int ignore_jbes_deriv, int *status) { double dd = 0; // Kernel and transfer evaluated at chi_l double w = ccl_cl_tracer_t_get_kernel(tr, chi_l, status); double t = ccl_cl_tracer_t_get_transfer(tr, lk,a_l, status); double fl = ccl_cl_tracer_t_get_f_ell(tr, l, status); if (tr->der_bessel < 1) { //We don't need l+1 dd = w*t; if (tr->der_bessel == -1) { //If we divide by (chi*k)^2 double lp1h = l+0.5; dd /= (lp1h*lp1h); } } else { // We will need l+1 if(ignore_jbes_deriv) dd = 0; else { // Compute chi_{l+1} and a_{l+1} double lp1h = l+0.5; double lp3h = l+1.5; double chi_lp = lp3h/k; double a_lp = ccl_scale_factor_of_chi(cosmo, chi_lp, status); // Compute power spectrum ratio there double pk_ratio = fabs(ccl_f2d_t_eval(psp, lk, a_lp, cosmo, status) / ccl_f2d_t_eval(psp, lk, a_l, cosmo, status)); // Compute kernel and trasfer at chi_{l+1} double w_p = ccl_cl_tracer_t_get_kernel(tr, chi_lp, status); double t_p = ccl_cl_tracer_t_get_transfer(tr, lk,a_lp, status); // sqrt(2l+1/2l+3) double sqell = sqrt(lp1h*pk_ratio/lp3h); if (tr->der_bessel == 1) dd = l*w*t/lp1h-sqell*w_p*t_p; else //we assume der_bessel=2 here to avoid extra if clause dd = sqell*2*w_p*t_p/lp3h - (0.25+2*l)*w*t/(lp1h*lp1h); } } return dd*fl; } static double transfer_limber_wrap(double l,double lk, double k, double chi, double a, ccl_cl_tracer_collection_t *trc, ccl_cosmology *cosmo,ccl_f2d_t *psp, int ignore_jbes_deriv, int *status) { int itr; double transfer = 0; for (itr=0; itr < trc->n_tracers; itr++) { transfer += transfer_limber_single( trc->ts[itr], l, lk, k, chi, a, cosmo, psp, ignore_jbes_deriv, status); if (*status != 0) return -1; } return transfer; } static double cl_integrand(double lk, void *params) { double d1, d2; integ_cl_par *p = (integ_cl_par *)params; double k = exp(lk); double chi = (p->l+0.5)/k; double a = ccl_scale_factor_of_chi(p->cosmo, chi, p->status); d1 = transfer_limber_wrap(p->l, lk, k, chi, a, p->trc1, p->cosmo, p->psp, 0, p->status); if (d1 == 0) return 0; d2 = transfer_limber_wrap(p->l, lk, k, chi, a, p->trc2, p->cosmo, p->psp, 0, p->status); if (d2 == 0) return 0; double pk = ccl_f2d_t_eval(p->psp, lk, a, p->cosmo, p->status); return k*pk*d1*d2; } static void integ_cls_limber_spline(ccl_cosmology *cosmo, integ_cl_par *ipar, double lkmin, double lkmax, double *result, int *status) { int ik; int nk = (int)(fmax((lkmax - lkmin) / cosmo->spline_params.DLOGK_INTEGRATION + 0.5, 1))+1; double *fk_arr = NULL; double *lk_arr = NULL; lk_arr = ccl_linear_spacing(lkmin, lkmax, nk); if(lk_arr == NULL) *status = CCL_ERROR_LOGSPACE; if(*status == 0) { fk_arr = malloc(nk * sizeof(double)); if(fk_arr == NULL) *status = CCL_ERROR_MEMORY; } if(*status == 0) { for(ik=0; ik<nk; ik++) { fk_arr[ik] = cl_integrand(lk_arr[ik], ipar); if(*(ipar->status)) { *status = *(ipar->status); break; } } } if(*status == 0) { ccl_integ_spline(1, nk, lk_arr, &fk_arr, 1, -1, result, gsl_interp_akima, status); } free(fk_arr); free(lk_arr); } static void integ_cls_limber_qag_quad(ccl_cosmology *cosmo, gsl_function *F, double lkmin, double lkmax, gsl_integration_workspace *w, double *result, double *eresult, int *status) { int gslstatus; size_t nevals; gsl_integration_cquad_workspace *w_cquad = NULL; // Integrate gslstatus = gsl_integration_qag(F, lkmin, lkmax, 0, cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL, cosmo->gsl_params.N_ITERATION, cosmo->gsl_params.INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS, w, result, eresult); // Test if a round-off error occured in the evaluation of the integral // If so, try another integration function, more robust but potentially slower if (gslstatus == GSL_EROUND) { ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: integ_cls_limber_qag_quad(): " "Default GSL integration failure, attempting backup method."); w_cquad = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w_cquad == NULL) *status = CCL_ERROR_MEMORY; if (*status == 0) { nevals = 0; gslstatus = gsl_integration_cquad(F, lkmin, lkmax, 0, cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL, w_cquad, result, eresult, &nevals); } } gsl_integration_cquad_workspace_free(w_cquad); if(*status == 0) *status = gslstatus; } void ccl_angular_cls_limber(ccl_cosmology *cosmo, ccl_cl_tracer_collection_t *trc1, ccl_cl_tracer_collection_t *trc2, ccl_f2d_t *psp, int nl_out, double *l_out, double *cl_out, ccl_integration_t integration_method, int *status) { // make sure to init core things for safety if (!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cls_limber(): distance splines have not been precomputed!"); return; } #pragma omp parallel shared(cosmo, trc1, trc2, l_out, cl_out, \ nl_out, status, psp, integration_method) \ default(none) { int clastatus, lind; integ_cl_par ipar; gsl_integration_workspace *w = NULL; int local_status = *status; gsl_function F; double lkmin, lkmax, l, result, eresult; if (local_status == 0) { // Set up integrating function parameters ipar.cosmo = cosmo; ipar.trc1 = trc1; ipar.trc2 = trc2; ipar.psp = psp; ipar.status = &clastatus; } if(integration_method == ccl_integration_qag_quad) { if (local_status == 0) { w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w == NULL) { local_status = CCL_ERROR_MEMORY; } } if (local_status == 0) { // Set up integrating function F.function = &cl_integrand; F.params = &ipar; } } #pragma omp for schedule(dynamic) for (lind=0; lind < nl_out; ++lind) { if (local_status == 0) { l = l_out[lind]; clastatus = 0; ipar.l = l; // Get integration limits get_k_interval(cosmo, trc1, trc2, l, &lkmin, &lkmax); // Integrate if(integration_method == ccl_integration_qag_quad) { integ_cls_limber_qag_quad(cosmo, &F, lkmin, lkmax, w, &result, &eresult, &local_status); } else if(integration_method == ccl_integration_spline) { integ_cls_limber_spline(cosmo, &ipar, lkmin, lkmax, &result, &local_status); } else local_status = CCL_ERROR_NOT_IMPLEMENTED; if ((*ipar.status == 0) && (local_status == 0)) { cl_out[lind] = result / (l+0.5); } else { ccl_raise_gsl_warning(local_status, "ccl_cls.c: ccl_angular_cls_limber():"); cl_out[lind] = NAN; local_status = CCL_ERROR_INTEG; } } } gsl_integration_workspace_free(w); if (local_status) { #pragma omp atomic write *status = local_status; } } if (*status) { ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cls_limber(); integration error\n"); } } void ccl_angular_cls_nonlimber(ccl_cosmology *cosmo, ccl_cl_tracer_collection_t *trc1, ccl_cl_tracer_collection_t *trc2, ccl_f2d_t *psp, int nl_out, int *l_out, double *cl_out, int *status) { *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cls_nonlimber(); non-Limber integrator not implemented yet\n"); } static double cov_integrand(double chi, void *params) { double d1, d2, d3, d4, tkk, ker=1; integ_cov_par *p = (integ_cov_par *)params; double k1=(p->l1+0.5)/chi; double k2=(p->l2+0.5)/chi; double lk1=log(k1); double lk2=log(k2); double a = ccl_scale_factor_of_chi(p->cosmo, chi, p->status); d1 = transfer_limber_wrap(p->l1, lk1, k1, chi, a, p->trc1, p->cosmo, NULL, 1, p->status); if (d1 == 0) return 0; d2 = transfer_limber_wrap(p->l1, lk1, k1, chi, a, p->trc2, p->cosmo, NULL, 1, p->status); if (d2 == 0) return 0; d3 = transfer_limber_wrap(p->l2, lk2, k2, chi, a, p->trc3, p->cosmo, NULL, 1, p->status); if (d3 == 0) return 0; d4 = transfer_limber_wrap(p->l2, lk2, k2, chi, a, p->trc4, p->cosmo, NULL, 1, p->status); if (d4 == 0) return 0; tkk = ccl_f3d_t_eval(p->tsp, lk1, lk2, a, p->finda, p->cosmo, p->status); if(p->ker_extra!=NULL) ker = ccl_f1d_t_eval(p->ker_extra, chi); return d1*d2*d3*d4*tkk*ker/pow(chi, p->chipow); } static void integ_cov_limber_spline(ccl_cosmology *cosmo, integ_cov_par *ipar, double chimin, double chimax, double *result, int *status) { int ichi; int nchi = (int)(fmax((chimax - chimin) / cosmo->spline_params.DCHI_INTEGRATION + 0.5, 1))+1; double *fchi_arr = NULL; double *chi_arr = NULL; chi_arr = ccl_linear_spacing(chimin, chimax, nchi); if(chi_arr == NULL) *status = CCL_ERROR_LOGSPACE; if(*status == 0) { fchi_arr = malloc(nchi * sizeof(double)); if(fchi_arr == NULL) *status = CCL_ERROR_MEMORY; } if(*status == 0) { for(ichi=0; ichi<nchi; ichi++) { fchi_arr[ichi] = cov_integrand(chi_arr[ichi], ipar); if(*(ipar->status)) { *status = *(ipar->status); break; } } } if(*status == 0) { ccl_integ_spline(1, nchi, chi_arr, &fchi_arr, 1, -1, result, gsl_interp_akima, status); } free(fchi_arr); free(chi_arr); } static void integ_cov_limber_qag_quad(ccl_cosmology *cosmo, gsl_function *F, double chimin, double chimax, gsl_integration_workspace *w, double *result, double *eresult, int *status) { int gslstatus; size_t nevals; gsl_integration_cquad_workspace *w_cquad = NULL; // Integrate gslstatus = gsl_integration_qag(F, chimin, chimax, 0, cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL, cosmo->gsl_params.N_ITERATION, cosmo->gsl_params.INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS, w, result, eresult); // Test if a round-off error occured in the evaluation of the integral // If so, try another integration function, more robust but potentially slower if (gslstatus == GSL_EROUND) { ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: ccl_angular_cov_limber(): " "Default GSL integration failure, attempting backup method."); w_cquad = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w_cquad == NULL) *status = CCL_ERROR_MEMORY; if (*status == 0) { nevals = 0; gslstatus = gsl_integration_cquad(F, chimin, chimax, 0, cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL, w_cquad, result, eresult, &nevals); } } gsl_integration_cquad_workspace_free(w_cquad); if(*status == 0) *status = gslstatus; } void ccl_angular_cl_covariance(ccl_cosmology *cosmo, ccl_cl_tracer_collection_t *trc1, ccl_cl_tracer_collection_t *trc2, ccl_cl_tracer_collection_t *trc3, ccl_cl_tracer_collection_t *trc4, ccl_f3d_t *tsp, int nl1_out, double *l1_out, int nl2_out, double *l2_out, double *cov_out, ccl_integration_t integration_method, int chi_exponent, ccl_f1d_t *kernel_extra, double prefactor_extra, int *status) { if(!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cl_limber(): distance splines have not been precomputed!"); return; } #pragma omp parallel shared(cosmo, trc1, trc2, trc3, trc4, tsp, \ nl1_out, l1_out, nl2_out, l2_out, cov_out, \ integration_method, chi_exponent, \ kernel_extra, prefactor_extra, status) \ default(none) { int clastatus, lind1,lind2; integ_cov_par ipar; gsl_integration_workspace *w = NULL; int local_status = *status; gsl_function F; double chimin, chimax; double l1, l2, result, eresult; ccl_a_finder *finda = ccl_a_finder_new_from_f3d(tsp); // Find integration limits chimin = 1E15; chimax = -1E15; update_chi_limits(trc1, &chimin, &chimax, 1); update_chi_limits(trc2, &chimin, &chimax, 0); update_chi_limits(trc3, &chimin, &chimax, 0); update_chi_limits(trc4, &chimin, &chimax, 0); if (local_status == 0) { // Set up integrating function parameters ipar.cosmo = cosmo; ipar.trc1 = trc1; ipar.trc2 = trc2; ipar.trc3 = trc3; ipar.trc4 = trc4; ipar.tsp = tsp; ipar.ker_extra = kernel_extra; ipar.finda = finda; ipar.status = &clastatus; ipar.chipow = chi_exponent; } if(integration_method == ccl_integration_qag_quad) { if (local_status == 0) { w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w == NULL) { local_status = CCL_ERROR_MEMORY; } } if (local_status == 0) { // Set up integrating function F.function = &cov_integrand; F.params = &ipar; } } #pragma omp for schedule(dynamic) for (lind1=0; lind1 < nl1_out; ++lind1) { l1 = l1_out[lind1]; ipar.l1 = l1; for (lind2=0; lind2 < nl2_out; ++lind2) { if (local_status == 0) { l2 = l2_out[lind2]; clastatus = 0; ipar.l2 = l2; // Integrate if(integration_method == ccl_integration_qag_quad) { integ_cov_limber_qag_quad(cosmo, &F, chimin, chimax, w, &result, &eresult, &local_status); } else if(integration_method == ccl_integration_spline) { integ_cov_limber_spline(cosmo, &ipar, chimin, chimax, &result, &local_status); } else local_status = CCL_ERROR_NOT_IMPLEMENTED; if ((*ipar.status == 0) && (local_status == 0)) { cov_out[lind1+nl1_out*lind2] = result * prefactor_extra; } else { ccl_raise_gsl_warning(local_status, "ccl_cls.c: ccl_angular_cov_limber():"); cov_out[lind1+nl1_out*lind2] = NAN; local_status = CCL_ERROR_INTEG; } } } } gsl_integration_workspace_free(w); if (local_status) { #pragma omp atomic write *status = local_status; } ccl_a_finder_free(finda); } if (*status) { ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cov_limber(); integration error\n"); } }
Require Import Category.Lib. Require Import Category.Theory.Category. Require Import Category.Theory.Isomorphism. Require Import Category.Theory.Functor. Require Import Category.Theory.Natural.Transformation. Require Import Category.Functor.Bifunctor. Require Import Category.Structure.Monoidal. Require Import Category.Functor.Structure.Monoidal. Generalizable All Variables. Section MonoidalFunctors. Context {C : Category}. Context `{@Monoidal C}. Context {D : Category}. Context `{@Monoidal D}. Context {G : C ⟶ D}. Context {E : Category}. Context `{@Monoidal E}. Context {F : D ⟶ E}. #[local] Obligation Tactic := program_simpl. #[export] Program Instance Id_MonoidalFunctor : @MonoidalFunctor C C _ _ Id[C] := { pure_iso := iso_id; ap_functor_iso := {| to := {| transform := fun _ => _ |} ; from := {| transform := fun _ => _ |} |} }. Next Obligation. simpl; intros. destruct H0; simpl. exact id. Defined. Next Obligation. simpl; intros; simplify; cat. Qed. Next Obligation. simpl; intros; simplify; cat. Qed. Next Obligation. simpl; intros. destruct H1; simpl. exact id. Defined. Next Obligation. simpl; intros; simplify; cat. Qed. Next Obligation. simpl; intros; simplify; cat. Qed. Next Obligation. cat. Qed. Next Obligation. cat. Qed. Next Obligation. apply tensor_assoc. Qed. Next Obligation. rewrite bimap_id_id; cat. Qed. Next Obligation. rewrite bimap_id_id; cat. Qed. Next Obligation. rewrite !bimap_id_id; cat. Qed. #[export] Program Instance Id_LaxMonoidalFunctor : @LaxMonoidalFunctor C C _ _ Id[C] := { lax_pure := id; ap_functor_nat := {| transform := fun _ => _ |} }. Next Obligation. simpl; intros. destruct H0; simpl. exact id. Defined. Next Obligation. simpl; intros; simplify; cat. Qed. Next Obligation. simpl; intros; simplify; cat. Qed. Next Obligation. apply tensor_assoc. Qed. Next Obligation. rewrite bimap_id_id; cat. Qed. Next Obligation. rewrite bimap_id_id; cat. Qed. Next Obligation. rewrite !bimap_id_id; cat. Qed. End MonoidalFunctors.
> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python. # 15.1. Diving into symbolic computing with SymPy SymPy is a pure Python package for symbolic mathematics. First, we import SymPy, and enable rich display LaTeX-based printing in the IPython notebook (using the MathJax Javascript library). ```python from sympy import * init_printing() ``` With NumPy and the other packages we have been using so far, we were dealing with numbers and numerical arrays. With SymPy, we deal with symbolic variables. It's a radically different shift of paradigm, which mathematicians may be more familiar with. To deal with symbolic variables, we need to declare them. ```python var('x y') ``` The var function creates symbols and injects them into the namespace. This function should only be used in interactive mode. In a Python module, it is better to use the symbol function which returns the symbols. ```python x, y = symbols('x y') ``` We can create mathematical expressions with these symbols. ```python expr1 = (x + 1)**2 expr2 = x**2 + 2*x + 1 ``` Are these expressions equal? ```python expr1 == expr2 ``` These expressions are mathematically equal, but not syntactically identical. To test whether they are equal, we can ask SymPy to simplify the difference algebraically. ```python simplify(expr1-expr2) ``` A very common operation with symbolic expressions is substitution of a symbol by another symbol, expression, or a number. ```python expr1.subs(x, expr1) ``` ```python expr1.subs(x, pi) ``` A rational number cannot be written simply as "1/2" as this Python expression evaluates to 0. A possibility is to use a SymPy object for 1, for example using the function S. ```python expr1.subs(x, S(1)/2) ``` Exactly-represented numbers can be evaluated numerically with evalf: ```python _.evalf() ``` We can transform this *symbolic* function into an actual Python function that can be evaluated on NumPy arrays, using the `lambdify` function. ```python f = lambdify(x, expr1) ``` ```python import numpy as np f(np.linspace(-2., 2., 5)) ``` > You'll find all the explanations, figures, references, and much more in the book (to be released later this summer). > [IPython Cookbook](http://ipython-books.github.io/), by [Cyrille Rossant](http://cyrille.rossant.net), Packt Publishing, 2014 (500 pages).
------------------------------------------------------------------------ -- INCREMENTAL λ-CALCULUS -- -- Dependently typed changes with the Nehemiah plugin. ------------------------------------------------------------------------ module Nehemiah.Change.Validity where open import Nehemiah.Syntax.Type open import Nehemiah.Denotation.Value import Parametric.Change.Validity ⟦_⟧Base as Validity open import Nehemiah.Change.Type open import Nehemiah.Change.Value open import Data.Integer open import Structure.Bag.Nehemiah open import Base.Change.Algebra open import Level change-algebra-base : ∀ ι → ChangeAlgebra ⟦ ι ⟧Base change-algebra-base base-int = GroupChanges.changeAlgebraGroup _ {{abelian-int}} change-algebra-base base-bag = GroupChanges.changeAlgebraGroup _ {{abelian-bag}} instance change-algebra-base-family : ChangeAlgebraFamily ⟦_⟧Base change-algebra-base-family = family change-algebra-base open Validity.Structure {{change-algebra-base-family}} public
Require Import VST.floyd.proofauto. Require Import mk_acc. From SSL_VST Require Import core. Instance CompSpecs : compspecs. make_compspecs prog. Defined. Definition Vprog : varspecs. mk_varspecs prog. Defined. Definition malloc_spec := DECLARE _malloc WITH t: type PRE [ tuint ] PROP() PARAMS(Vint (Int.repr (sizeof t))) SEP() POST [tptr tvoid] EX p:_, PROP() RETURN(p) SEP(data_at_ Tsh t p). Inductive account_card : Set := | account_card_0 : account_card. Fixpoint account (x: val) (id: Z) (bal: Z) (self_card: account_card) {struct self_card} : mpred := match self_card with | account_card_0 => !!(is_true true) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr id)) : val)); (inl ((Vint (Int.repr bal)) : val))] (x : val)) end. Definition mk_acc_spec := DECLARE _mk_acc WITH r: val, id: val, bal: Z PRE [ (tptr (Tunion _sslval noattr)), tint ] PROP( is_pointer_or_null((r : val)); ssl_is_valid_int((id : val)) ) PARAMS(r; id) SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inl ((Vint (Int.repr bal)) : val))] (r : val))) POST[ tvoid ] EX x: val, EX _alpha_513: account_card, PROP( is_pointer_or_null((x : val)) ) LOCAL() SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (x : val))] (r : val)); (account (x : val) (force_signed_int (id : val)) (bal : Z) (_alpha_513 : account_card))). Lemma account_x_valid_pointerP x id bal self_card: account x id bal self_card |-- valid_pointer x. Proof. destruct self_card; simpl; entailer; entailer!; eauto. Qed. Hint Resolve account_x_valid_pointerP : valid_pointer. Lemma account_local_factsP x id bal self_card : account x id bal self_card|-- !!((((is_true true)) -> (self_card = account_card_0))/\is_pointer_or_null((x : val))). Proof. destruct self_card; simpl; entailer; saturate_local; apply prop_right; eauto. Qed. Hint Resolve account_local_factsP : saturate_local. Lemma unfold_account_card_0 (x: val) (id: Z) (bal: Z) : account x id bal (account_card_0 ) = !!(is_true true) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr id)) : val)); (inl ((Vint (Int.repr bal)) : val))] (x : val)). Proof. auto. Qed. Definition Gprog : funspecs := ltac:(with_library prog [mk_acc_spec; malloc_spec]). Lemma body_mk_acc : semax_body Vprog Gprog f_mk_acc mk_acc_spec. Proof. start_function. ssl_open_context. assert_PROP (isptr r). { entailer!. } try rename bal into bal2. forward. forward_call (tarray (Tunion _sslval noattr) 2). Intros x2. assert_PROP (isptr x2). { entailer!. } forward. forward. forward. forward; entailer!. Exists (x2 : val). Exists (account_card_0 : account_card). ssl_entailer. rewrite (unfold_account_card_0 ) at 1. ssl_entailer. Qed.
import .formula open list def remove_neg : atom_dlo → formula_dlo | (t <' s) := (A' (t =' s) ∨' A' (s <' t)) | (t =' s) := (A' (t <' s) ∨' A' (s <' t)) lemma eval_remove_neg : ∀ (a : atom_dlo) (xs : list rat), (remove_neg a).eval xs ↔ (¬ (a.eval xs)) | (t <' s) xs := begin simp [formula_dlo.eval, atom_dlo.eval, remove_neg, le_iff_lt_or_eq, or.comm, eq.symm'] end | (t =' s) xs := begin simp [formula_dlo.eval, atom_dlo.eval, remove_neg, le_antisymm_iff], rw [imp_iff_not_or, not_le, or.comm], end #exit simp only [remove_neg, atom_dlo.eval], apply calc (1 - i ≤ znum.dot_prod (map_neg ks) xs) ↔ (-(znum.dot_prod (map_neg ks) xs) ≤ -(1 - i)) : begin apply iff.intro, apply (@neg_le_neg znum _), apply (@le_of_neg_le_neg znum _) end ... ↔ (znum.dot_prod ks xs ≤ -(1 - i)) : begin rw [znum.map_neg_dot_prod], simp, end ... ↔ (znum.dot_prod ks xs ≤ i - 1) : by rewrite neg_sub ... ↔ (znum.dot_prod ks xs < i) : begin apply iff.intro, apply znum.lt_of_le_sub_one, apply znum.le_sub_one_of_lt end ... ↔ ¬i ≤ znum.dot_prod ks xs : begin apply iff.intro, apply not_le_of_gt, apply lt_of_not_ge end end | (atom_dlo.dvd d i ks) xs := by refl | (atom_dlo.ndvd d i ks) xs := by apply not_not_iff.symm
Formal statement is: lemma coeff_add [simp]: "coeff (p + q) n = coeff p n + coeff q n" Informal statement is: The coefficient of $x^n$ in the sum of two polynomials is the sum of the coefficients of $x^n$ in each polynomial.
-- calculates nash equilibriums, does related backend stuff {-# LANGUAGE OverloadedStrings #-} module Game ( gameSimplePartial, gameSimplePartialOpts, gameSimple , calcPureEVs, calcEVSimpleCore, calcVarSimpleCore, calcSDSimpleCore , gameComplex, resultComplex , solvePure, solvePureBy, solvePureOn, solvePureZeroSum , solvePureOptimal, solvePureOptimalZeroSum , solveSimpleCoreNaive , calcEVSimpleCoreNaive , solveSimple, solveComplex , resultComplex , Game (Game, gameCName, attCName, defCName, gameData, outcomesC) , Result (Result, evc, evr, sdc, sdr, weightsAtts, weightsDefs) , ResultSimple (ResultSimple, evSimpleCol, evSimpleRow, sdSimpleCol, sdSimpleRow, weightsColsSimple, weightsRowsSimple) ) where import GameData import Data.List import Data.List.Split import Data.Function import Data.Maybe import Data.Text (Text, unpack) import Numeric.LinearAlgebra import Numeric.LinearAlgebra.Data import Data.Map (Map) import qualified Data.Map as Map import Safe type EV = Double type Var = Double type SD = Double type Weights = [Double] type Coord = (Int,Int) type RemovedElements = [Int] type WeightedOption = (Opt, Opt, Double) type BiWeightedOption = (Opt, Opt, Double, Double) type PayoffsRaw = [[Double]] type Payoffs = Matrix Double gameSimplePartial :: PayoffsRaw -> Payoffs gameSimplePartial = fromLists gameSimplePartialOpts :: [WeightedOption] -> PayoffsRaw gameSimplePartialOpts opts = let fst3 (x,_,_) = x snd3 (_,x,_) = x thd3 (_,_,x) = x cols = nub . map (fst . fst3) $ opts rows = nub . map (fst . snd3) $ opts grid = map (map thd3) . transpose . chunksOf (length rows) $ opts in grid gameSimple :: Text -> [Text] -> [Text] -> PayoffsRaw -> PayoffsRaw -> GameSimple gameSimple n c r m1 m2 = GameSimple n c r (fromLists m1) (fromLists m2) $ solveSimple m1 m2 calcPureEVs :: Payoffs -> Weights -> [EV] calcPureEVs m cols = concat . toLists $ m Numeric.LinearAlgebra.<> (col (fmap (/ sum cols) cols)) calcEVSimpleCore :: Payoffs -> Weights -> Weights -> EV calcEVSimpleCore m cols rows = (head . head . toLists $ (row rows) Numeric.LinearAlgebra.<> m Numeric.LinearAlgebra.<> (col cols)) calcVarSimpleCore :: Payoffs -> Weights -> Weights -> Var calcVarSimpleCore mat cols rows = calcEVSimpleCore (cmap (\x -> (x - calcEVSimpleCore mat cols rows)**2) mat) cols rows calcSDSimpleCore :: Payoffs -> Weights -> Weights -> SD calcSDSimpleCore a b = sqrt . calcVarSimpleCore a b gameComplex :: Text -> Text -> Text -> [BiWeightedOption] -> Game gameComplex t1 t2 t3 m = Game t1 t2 t3 (sort m) . resultComplex m $ solveComplex m resultComplex :: [(Opt, Opt, Double, Double)] -> ResultSimple -> Result resultComplex opts (ResultSimple evc evr sdc sdr cw rw) = do let colnames = nub . map (fst . fst4) $ opts let rownames = nub . map (fst . snd4) $ opts Result evc evr sdc sdr (zip colnames cw) (zip rownames rw) -- from here on out, stuff for solving games -- the fundamental algorithm, given some ordering method to know which values are better solvePureBy :: (Eq a) => (a -> a -> Ordering) -> [[a]] -> [[a]] -> [Coord] solvePureBy f mc mr = let width = length . head $ mc height = length mc -- column player: picks the highest columns for each row mcIsBestResponse = map (\col -> map (== maximumBy f col) col) mc -- row player: picks the highest rows for each coloumn mrIsBestResponse = transpose . map (\row -> map (== maximumBy f row) row) . transpose $ mr bestResponses = map (uncurry zip) $ zip mcIsBestResponse mrIsBestResponse coords = map (\r -> map (\c -> (c,r)) [0..width-1]) [0..height-1] zipped = map (uncurry zip) $ zip coords bestResponses zippedFiltered = map fst . filter (\((x,y),(c,r)) -> and[c,r]) . concat $ zipped in zippedFiltered -- solvePureBy applied to mapped values solvePureOn :: (Ord c) => (a -> c) -> (b -> c) -> [[a]] -> [[b]] -> [Coord] solvePureOn f g mc mr = solvePureBy compare (map (map f) mc) (map (map g) mr) solvePure :: (Ord a) => [[a]] -> [[a]] -> [Coord] solvePure mc mr = solvePureOn id id mc mr solvePureZeroSum :: (Ord a, Num a) => [[a]] -> [Coord] solvePureZeroSum m = solvePureOn id negate m m evPure :: [[a]] -> Coord -> a evPure m (c,r) = (m!!c)!!r solvePureOptimalBy :: (Ord a) => (a -> a -> Ordering) -> ([[a]] -> Coord -> a) -> [[a]] -> [[a]] -> Maybe Coord solvePureOptimalBy f ev mc mr = let pures = solvePureBy f mc mr -- note that we have already optimised the row choice per column choice, as these are all, by definition, nash equilibria -- thus, simply choose the optimal nash equilibrium for column ev bestPure = maximumByMay (compare `on` (\p -> ev mc p)) pures in bestPure solvePureOptimalOn :: (Ord c) => (a -> c) -> (b -> c) -> ([[c]] -> Coord -> c) -> [[a]] -> [[b]] -> Maybe Coord solvePureOptimalOn f g ev mc mr = solvePureOptimalBy compare ev (map (map f) mc) (map (map g) mr) solvePureOptimal :: (Ord a) => [[a]] -> [[a]] -> Maybe Coord solvePureOptimal mc mr = solvePureOptimalOn id id evPure mc mr solvePureOptimalZeroSum :: (Ord a, Num a) => [[a]] -> Maybe Coord solvePureOptimalZeroSum m = solvePureOptimal m . map (map negate) $ m solveSimpleCoreNaive :: Matrix Double -> Maybe Weights solveSimpleCoreNaive m = do case (rows m, cols m) of -- not really much choice (_,1) -> return [1] -- they only have one option, so zip your options to their position, get the best option's position, and pad a [1] with zeroes as appropriate to the position (1,c) -> return . (\n -> ((take n (repeat 0)) ++ [1] ++ (take (c - n - 1) (repeat 0)))) . fst . maximumBy (compare `on` snd) . zip [0..] . concat . toLists $ m -- use linear algebra to find the weights such that unexploitable play is achieved, ie, the ev of each of the opponent's options is equal _ -> let weights = normalise . concat . toLists $ ((pinv m) Numeric.LinearAlgebra.<> (((rows m)><1) (repeat (fromInteger 1)))) in if all (>=0) weights then return weights else Nothing where normalise :: (Fractional a) => [a] -> [a] normalise xs = map (/ (sum xs)) xs calcEVSimpleCoreNaive :: Matrix Double -> Maybe EV calcEVSimpleCoreNaive m = do wc <- solveSimpleCoreNaive m wr <- solveSimpleCoreNaive . tr' $ m return $ calcEVSimpleCore m wc wr gameSupports :: (Ord a, Num a) => [[a]] -> [[a]] -> [[((RemovedElements, RemovedElements), ([[a]], [[a]]))]] gameSupports m1 m2 = let widther = length . head heighter = length w = widther m1 - 1 h = heighter m1 - 1 removeIndexes :: RemovedElements -> [a] -> [a] removeIndexes [] xs = xs removeIndexes _ [] = error "Can't remove from an empty list!" removeIndexes [0] (x:xs) = xs removeIndexes [n] (x:xs) = x:(removeIndexes [n-1] xs) removeIndexes (n:ns) xs = removeIndexes (fmap (subtract 1) ns) (removeIndexes [n] xs) subm :: (RemovedElements,RemovedElements) -> [[a]] -> [[a]] subm coords = map (removeIndexes (fst coords)) . removeIndexes (snd coords) supportsColsRaw = zip [0..] . init . subsequences $ [0..w] -- [[],[0],[1],...,[n],[0,1],[0,2],...,[0,n],[0,1,2],...] supportsRowsRaw = zip [0..] . init . subsequences $ [0..h] supportsPairs = map (\(x,c) -> map (\(y,r) -> ((c,r), (subm (c,r) m1, subm (c,r) m2))) supportsRowsRaw) supportsColsRaw in supportsPairs gameSupportsZeroSum :: (Ord a, Num a) => [[a]] -> [[((RemovedElements, RemovedElements), ([[a]], [[a]]))]] gameSupportsZeroSum m = gameSupports m (map (map negate) m) supportIntoValidatedWeightsEVsSDs :: ((RemovedElements, RemovedElements), ([[Double]], [[Double]])) -> Maybe ((Weights, Weights), ((EV, EV), (SD, SD))) supportIntoValidatedWeightsEVsSDs ((sc,sr), (mc,mr)) = do let (g1,g2) = (gameSimplePartial mc, tr' $ gameSimplePartial mr) w1 <- solveSimpleCoreNaive g1 w2 <- solveSimpleCoreNaive g2 let ws = (addIndexes 0 sc w1, addIndexes 0 sr w2) let evs = (calcEVSimpleCore g1 w1 w2, calcEVSimpleCore g2 w2 w1) let sds = (calcSDSimpleCore g1 w1 w2, calcSDSimpleCore g2 w2 w1) return (ws, (evs, sds)) where addIndexes :: a -> [Int] -> [a] -> [a] addIndexes _ [] xs = xs addIndexes def [0] xs = def:xs addIndexes _ _ [] = error "Add index out of bounds" addIndexes def [n] (x:xs) = x:(addIndexes def [n-1] xs) addIndexes def (n:ns) xs = addIndexes def ns (addIndexes def [n] xs) supportsIntoValidatedWeightsEVsSDs :: [[((RemovedElements, RemovedElements), ([[Double]], [[Double]]))]] -> [[Maybe ((Weights, Weights), ((EV, EV), (SD, SD)))]] supportsIntoValidatedWeightsEVsSDs = map (map supportIntoValidatedWeightsEVsSDs) solveSimple :: [[Double]] -> [[Double]] -> ResultSimple solveSimple mc mr = let sups = gameSupports mc mr strats = supportsIntoValidatedWeightsEVsSDs sups maximumOn f = maximumBy (compare `on` f) colEv = fmap (fst . fst . snd) rowEv = fmap (snd . fst . snd) stratsBestResponses = map (maximumOn rowEv) strats stratsBest = maximumOn colEv stratsBestResponses res (Just ((wc,wr),((evc,evr),(sdc,sdr)))) = ResultSimple evc evr sdc sdr wc wr in res stratsBest solveComplex :: Ord a => [((a, Maybe Double), (a, Maybe Double), Double, Double)] -> ResultSimple solveComplex gdata = let typeCheck ((_,c), (_,r), _, _) = (fromEnum . isNothing $ c) + ((2*) . fromEnum . isNothing $ r) pureStrategy :: Int -> Int -> [Double] pureStrategy l x = take l ((take (x-1) . repeat $ 0) ++ (1:[0..])) -- get all the subgame data and split it according to type: neither = Nothing, col = Nothing, row = Nothing, both = Nothing -- evs :: [[((Text, Maybe Double), (Text, Maybe Double), Double)]] evs = map (\i -> filter (\outcome -> typeCheck outcome == i) $ gdata) [0..3] in case evs of [both, [], [], []] -> do -- both are fixed, so we just copy the weights into the ResultSimple let rows = nub . map (fst . fst4) $ both let cols = nub . map (fst . snd4) $ both let grid = transpose . chunksOf (length rows) $ both let outsc = map (map thd4) grid let outsr = map (map fth4) grid let gc = fromLists outsc let gr = fromLists outsr let cw = map (maybe (error "???") id . snd) . nub . map fst4 $ both let rw = map (maybe (error "???") id . snd) . nub . map snd4 $ both ResultSimple (calcEVSimpleCore gc cw rw) (calcEVSimpleCore gr cw rw) (calcSDSimpleCore gc cw rw) (calcSDSimpleCore gr cw rw) cw rw [[], c, [], []] -> do -- typeCheck 1 -> columns unfixed, rows fixed, evaluate columns let cols = nub . map (fst . fst4) $ c -- each column option, in the form of name::Text let rows = map (\(a, Just b) -> (a,b)) . nub . map snd4 $ c -- each row option, in the form of (name, weight)::(Text, Double) let grid = transpose . chunksOf (length rows) $ c let outsc = map (map thd4) grid let outsr = map (map fth4) grid let gc = fromLists outsc let gr = fromLists outsr let colStrats = map (pureStrategy . length $ cols) [0..length cols] -- every pure strategy to try against the fixed row strategy let evs = map (\strat -> calcEVSimpleCore gc strat (map snd rows)) colStrats -- every ev let (cw, ev) = maximumBy (compare `on` snd) . zip colStrats $ evs -- get the optimal pure strategy for the column player let rw = map snd rows ResultSimple ev (calcEVSimpleCore gr cw rw) (calcSDSimpleCore gc cw rw) (calcSDSimpleCore gr cw rw) cw rw [[], [], r, []] -> do -- the same as above, but cols fixed rows unfixed let cols = map (\(a, Just b) -> (a,b)) . nub . map fst4 $ r let rows = nub . map (fst . snd4) $ r let grid = transpose . chunksOf (length rows) $ r let outsc = map (map thd4) grid let outsr = map (map fth4) grid let gc = fromLists outsc let gr = fromLists outsr let rowStrats = map (pureStrategy . length $ rows) [0..length rows] let evs = map (\strat -> calcEVSimpleCore gr (map snd cols) strat) rowStrats let cw = map snd cols let (rw, ev) = minimumBy (compare `on` snd) . zip rowStrats $ evs -- the defender wants to minimise the ev ResultSimple (calcEVSimpleCore gc cw rw) ev (calcSDSimpleCore gc cw rw) (calcSDSimpleCore gr cw rw) cw rw [[], [], [], neither] -> do -- both are unfixed, so we just calculate it as a normal GameSimple let cols = nub . map (fst . fst4) $ neither let rows = nub . map (fst . snd4) $ neither let grid = transpose . chunksOf (length rows) $ neither let outsc = map (map thd4) grid let outsr = map (map fth4) grid solveSimple outsc outsr _ -> error "both fixed and unfixed options for a single player" -- no. don't. this makes no sense!!! the only reason i can even think you'd want to try is equivalent to just nesting in another mixup, so just do that. fst4 (x,_,_,_) = x snd4 (_,x,_,_) = x thd4 (_,_,x,_) = x fth4 (_,_,_,x) = x
[STATEMENT] lemma securessel2: assumes "ssel (STMap TAddr (STValue (TUInt 256))) (STR ''balance'') [SENDER] ep env cd st = Normal ((loc, type), st')" and "fmlookup (storage st) (STR ''Victim'') = Some s" and "ReadL\<^sub>i\<^sub>n\<^sub>t (accessBalance (accounts st) (STR ''Victim'')) - SUMM s \<ge> bal \<and> POS s" obtains s' where "loc = sender env + (STR ''.'' + STR ''balance'')" and "type = STValue (TUInt 256)" and "fmlookup (storage st') (STR ''Victim'') = Some s'" and "ReadL\<^sub>i\<^sub>n\<^sub>t (accessBalance (accounts st') (STR ''Victim'')) - SUMM s' \<ge> bal \<and> POS s'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>s'. \<lbrakk>loc = sender env + (STR ''.'' + STR ''balance''); type = STValue (TUInt 256); fmlookup (storage st') STR ''Victim'' = Some s'; bal \<le> \<lceil>accessBalance (accounts st') STR ''Victim''\<rceil> - SUMM s' \<and> (\<forall>ad x. fmlookup s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<And>s'. \<lbrakk>loc = sender env + (STR ''.'' + STR ''balance''); type = STValue (TUInt 256); fmlookup (storage st') STR ''Victim'' = Some s'; bal \<le> \<lceil>accessBalance (accounts st') STR ''Victim''\<rceil> - SUMM s' \<and> (\<forall>ad x. fmlookup s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] from assms(1) [PROOF STATE] proof (chain) picking this: local.ssel (STMap TAddr (STValue (TUInt 256))) STR ''balance'' [SENDER] ep env cd st = Normal ((loc, type), st') [PROOF STEP] obtain v t st'' st''' x where *: "expr SENDER ep env cd st = Normal ((KValue v, t), st'')" and **: "ssel (STValue (TUInt 256)) (hash (STR ''balance'') v) [] ep env cd st'' = Normal (x,st''')" and "st' = st'''" [PROOF STATE] proof (prove) using this: local.ssel (STMap TAddr (STValue (TUInt 256))) STR ''balance'' [SENDER] ep env cd st = Normal ((loc, type), st') goal (1 subgoal): 1. (\<And>v t st'' x st'''. \<lbrakk>local.expr SENDER ep env cd st = Normal ((KValue v, t), st''); local.ssel (STValue (TUInt 256)) (hash STR ''balance'' v) [] ep env cd st'' = Normal (x, st'''); st' = st'''\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (auto split:if_split_asm) [PROOF STATE] proof (state) this: local.expr SENDER ep env cd st = Normal ((KValue v, t), st'') local.ssel (STValue (TUInt 256)) (hash STR ''balance'' v) [] ep env cd st'' = Normal (x, st''') st' = st''' goal (1 subgoal): 1. (\<And>s'. \<lbrakk>loc = sender env + (STR ''.'' + STR ''balance''); type = STValue (TUInt 256); fmlookup (storage st') STR ''Victim'' = Some s'; bal \<le> \<lceil>accessBalance (accounts st') STR ''Victim''\<rceil> - SUMM s' \<and> (\<forall>ad x. fmlookup s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] moreover [PROOF STATE] proof (state) this: local.expr SENDER ep env cd st = Normal ((KValue v, t), st'') local.ssel (STValue (TUInt 256)) (hash STR ''balance'' v) [] ep env cd st'' = Normal (x, st''') st' = st''' goal (1 subgoal): 1. (\<And>s'. \<lbrakk>loc = sender env + (STR ''.'' + STR ''balance''); type = STValue (TUInt 256); fmlookup (storage st') STR ''Victim'' = Some s'; bal \<le> \<lceil>accessBalance (accounts st') STR ''Victim''\<rceil> - SUMM s' \<and> (\<forall>ad x. fmlookup s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] obtain s'' where "v =sender env" and "t = Value TAddr" and ***:"fmlookup (storage st'') (STR ''Victim'') = Some s''" and ****: "ReadL\<^sub>i\<^sub>n\<^sub>t (accessBalance (accounts st'') (STR ''Victim'')) - SUMM s'' \<ge> bal \<and> POS s''" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>s''. \<lbrakk>v = sender env; t = Value TAddr; fmlookup (storage st'') STR ''Victim'' = Some s''; bal \<le> \<lceil>accessBalance (accounts st'') STR ''Victim''\<rceil> - SUMM s'' \<and> (\<forall>ad x. fmlookup s'' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using securesender[OF * assms(2,3)] [PROOF STATE] proof (prove) using this: (\<And>s'. \<lbrakk>v = sender env; t = Value TAddr; fmlookup (storage st'') STR ''Victim'' = Some s'; bal \<le> \<lceil>accessBalance (accounts st'') STR ''Victim''\<rceil> - SUMM s' \<and> (\<forall>ad x. fmlookup s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis goal (1 subgoal): 1. (\<And>s''. \<lbrakk>v = sender env; t = Value TAddr; fmlookup (storage st'') STR ''Victim'' = Some s''; bal \<le> \<lceil>accessBalance (accounts st'') STR ''Victim''\<rceil> - SUMM s'' \<and> (\<forall>ad x. fmlookup s'' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: v = sender env t = Value TAddr fmlookup (storage st'') STR ''Victim'' = Some s'' bal \<le> \<lceil>accessBalance (accounts st'') STR ''Victim''\<rceil> - SUMM s'' \<and> (\<forall>ad x. fmlookup s'' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>) goal (1 subgoal): 1. (\<And>s'. \<lbrakk>loc = sender env + (STR ''.'' + STR ''balance''); type = STValue (TUInt 256); fmlookup (storage st') STR ''Victim'' = Some s'; bal \<le> \<lceil>accessBalance (accounts st') STR ''Victim''\<rceil> - SUMM s' \<and> (\<forall>ad x. fmlookup s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] moreover [PROOF STATE] proof (state) this: v = sender env t = Value TAddr fmlookup (storage st'') STR ''Victim'' = Some s'' bal \<le> \<lceil>accessBalance (accounts st'') STR ''Victim''\<rceil> - SUMM s'' \<and> (\<forall>ad x. fmlookup s'' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>) goal (1 subgoal): 1. (\<And>s'. \<lbrakk>loc = sender env + (STR ''.'' + STR ''balance''); type = STValue (TUInt 256); fmlookup (storage st') STR ''Victim'' = Some s'; bal \<le> \<lceil>accessBalance (accounts st') STR ''Victim''\<rceil> - SUMM s' \<and> (\<forall>ad x. fmlookup s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] obtain s''' where "x = (hash (STR ''balance'') v, STValue (TUInt 256))" and "fmlookup (storage st''') (STR ''Victim'') = Some s'''" and "ReadL\<^sub>i\<^sub>n\<^sub>t (accessBalance (accounts st''') (STR ''Victim'')) - SUMM s''' \<ge> bal \<and> POS s'''" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>s'''. \<lbrakk>x = (hash STR ''balance'' v, STValue (TUInt 256)); fmlookup (storage st''') STR ''Victim'' = Some s'''; bal \<le> \<lceil>accessBalance (accounts st''') STR ''Victim''\<rceil> - SUMM s''' \<and> (\<forall>ad x. fmlookup s''' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using securessel[OF ** *** ****] [PROOF STATE] proof (prove) using this: (\<And>s'. \<lbrakk>x = (hash STR ''balance'' v, STValue (TUInt 256)); fmlookup (storage st''') STR ''Victim'' = Some s'; bal \<le> \<lceil>accessBalance (accounts st''') STR ''Victim''\<rceil> - SUMM s' \<and> (\<forall>ad x. fmlookup s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis goal (1 subgoal): 1. (\<And>s'''. \<lbrakk>x = (hash STR ''balance'' v, STValue (TUInt 256)); fmlookup (storage st''') STR ''Victim'' = Some s'''; bal \<le> \<lceil>accessBalance (accounts st''') STR ''Victim''\<rceil> - SUMM s''' \<and> (\<forall>ad x. fmlookup s''' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: x = (hash STR ''balance'' v, STValue (TUInt 256)) fmlookup (storage st''') STR ''Victim'' = Some s''' bal \<le> \<lceil>accessBalance (accounts st''') STR ''Victim''\<rceil> - SUMM s''' \<and> (\<forall>ad x. fmlookup s''' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>) goal (1 subgoal): 1. (\<And>s'. \<lbrakk>loc = sender env + (STR ''.'' + STR ''balance''); type = STValue (TUInt 256); fmlookup (storage st') STR ''Victim'' = Some s'; bal \<le> \<lceil>accessBalance (accounts st') STR ''Victim''\<rceil> - SUMM s' \<and> (\<forall>ad x. fmlookup s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: local.expr SENDER ep env cd st = Normal ((KValue v, t), st'') local.ssel (STValue (TUInt 256)) (hash STR ''balance'' v) [] ep env cd st'' = Normal (x, st''') st' = st''' v = sender env t = Value TAddr fmlookup (storage st'') STR ''Victim'' = Some s'' bal \<le> \<lceil>accessBalance (accounts st'') STR ''Victim''\<rceil> - SUMM s'' \<and> (\<forall>ad x. fmlookup s'' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>) x = (hash STR ''balance'' v, STValue (TUInt 256)) fmlookup (storage st''') STR ''Victim'' = Some s''' bal \<le> \<lceil>accessBalance (accounts st''') STR ''Victim''\<rceil> - SUMM s''' \<and> (\<forall>ad x. fmlookup s''' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: local.expr SENDER ep env cd st = Normal ((KValue v, t), st'') local.ssel (STValue (TUInt 256)) (hash STR ''balance'' v) [] ep env cd st'' = Normal (x, st''') st' = st''' v = sender env t = Value TAddr fmlookup (storage st'') STR ''Victim'' = Some s'' bal \<le> \<lceil>accessBalance (accounts st'') STR ''Victim''\<rceil> - SUMM s'' \<and> (\<forall>ad x. fmlookup s'' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>) x = (hash STR ''balance'' v, STValue (TUInt 256)) fmlookup (storage st''') STR ''Victim'' = Some s''' bal \<le> \<lceil>accessBalance (accounts st''') STR ''Victim''\<rceil> - SUMM s''' \<and> (\<forall>ad x. fmlookup s''' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>) goal (1 subgoal): 1. thesis [PROOF STEP] using assms(1) that [PROOF STATE] proof (prove) using this: local.expr SENDER ep env cd st = Normal ((KValue v, t), st'') local.ssel (STValue (TUInt 256)) (hash STR ''balance'' v) [] ep env cd st'' = Normal (x, st''') st' = st''' v = sender env t = Value TAddr fmlookup (storage st'') STR ''Victim'' = Some s'' bal \<le> \<lceil>accessBalance (accounts st'') STR ''Victim''\<rceil> - SUMM s'' \<and> (\<forall>ad x. fmlookup s'' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>) x = (hash STR ''balance'' v, STValue (TUInt 256)) fmlookup (storage st''') STR ''Victim'' = Some s''' bal \<le> \<lceil>accessBalance (accounts st''') STR ''Victim''\<rceil> - SUMM s''' \<and> (\<forall>ad x. fmlookup s''' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>) local.ssel (STMap TAddr (STValue (TUInt 256))) STR ''balance'' [SENDER] ep env cd st = Normal ((loc, type), st') \<lbrakk>loc = sender env + (STR ''.'' + STR ''balance''); type = STValue (TUInt 256); fmlookup (storage st') STR ''Victim'' = Some ?s'; bal \<le> \<lceil>accessBalance (accounts st') STR ''Victim''\<rceil> - SUMM ?s' \<and> (\<forall>ad x. fmlookup ?s' (ad + (STR ''.'' + STR ''balance'')) = Some x \<longrightarrow> 0 \<le> \<lceil>x\<rceil>)\<rbrakk> \<Longrightarrow> thesis goal (1 subgoal): 1. thesis [PROOF STEP] by simp [PROOF STATE] proof (state) this: thesis goal: No subgoals! [PROOF STEP] qed
[STATEMENT] lemma Dag_unique_ex_conjI: "\<lbrakk>Dag p l r t; P t\<rbrakk> \<Longrightarrow> (\<exists>t. Dag p l r t \<and> P t)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>Dag p l r t; P t\<rbrakk> \<Longrightarrow> \<exists>t. Dag p l r t \<and> P t [PROOF STEP] by simp
import algebra.ring #check add_comm #check zero_add #check add_left_neg namespace my_ring variables {R : Type*} [ring R] theorem add_zero (a : R) : a + 0 = a := begin rw add_comm, rw zero_add, end -- A shorter proof example (a : R) : a + 0 = a := by rw [add_comm, zero_add] /- Multiple rewrites can be combined using the notation rw [t_1, ..., t_n], which is just shorthand for rewrite t_1, ..., rewrite t_n. -/ theorem add_right_neg (a : R) : a + -a = 0 := begin sorry, end end my_ring #check add_zero #check add_right_neg
The image of a circle path is a sphere.
% Basic Gene Finding % % A replacement for the overlong ORF prediction subsection \subsection{Basic Gene Finding} \begin{frame} \frametitle{Basic Gene Finding} \begin{itemize} \item We could use Artemis to identify the longest coding region in each ORF, lots of manual steps \item This is the most basic gene finding, and can easily be automated, e.g. EMBOSS \texttt{getorf} \item Dedicated gene finders usually more appropriate... \end{itemize} \end{frame} \begin{frame} \frametitle{Finding Open Reading Frames} \begin{itemize} \item<1-> ORF finding is naive, does not consider: \begin{itemize} \item Start codon \item Splicing \item Promoter/RBS motifs \item Wider context (e.g. overlapping genes) \end{itemize} \end{itemize} \end{frame}
From iris.algebra Require Export cmra. From iris.algebra Require Import local_updates. From iris.base_logic Require Import base_logic. From iris Require Import options. Local Arguments pcore _ _ !_ /. Local Arguments cmra_pcore _ !_ /. Local Arguments validN _ _ _ !_ /. Local Arguments valid _ _ !_ /. Local Arguments cmra_validN _ _ !_ /. Local Arguments cmra_valid _ !_ /. Inductive csum (A B : Type) := | Cinl : A → csum A B | Cinr : B → csum A B | CsumBot : csum A B. Arguments Cinl {_ _} _. Arguments Cinr {_ _} _. Arguments CsumBot {_ _}. Instance: Params (@Cinl) 2 := {}. Instance: Params (@Cinr) 2 := {}. Instance: Params (@CsumBot) 2 := {}. Instance maybe_Cinl {A B} : Maybe (@Cinl A B) := λ x, match x with Cinl a => Some a | _ => None end. Instance maybe_Cinr {A B} : Maybe (@Cinr A B) := λ x, match x with Cinr b => Some b | _ => None end. Section cofe. Context {A B : ofeT}. Implicit Types a : A. Implicit Types b : B. (* Cofe *) Inductive csum_equiv : Equiv (csum A B) := | Cinl_equiv a a' : a ≡ a' → Cinl a ≡ Cinl a' | Cinr_equiv b b' : b ≡ b' → Cinr b ≡ Cinr b' | CsumBot_equiv : CsumBot ≡ CsumBot. Existing Instance csum_equiv. Inductive csum_dist : Dist (csum A B) := | Cinl_dist n a a' : a ≡{n}≡ a' → Cinl a ≡{n}≡ Cinl a' | Cinr_dist n b b' : b ≡{n}≡ b' → Cinr b ≡{n}≡ Cinr b' | CsumBot_dist n : CsumBot ≡{n}≡ CsumBot. Existing Instance csum_dist. Global Instance Cinl_ne : NonExpansive (@Cinl A B). Proof. by constructor. Qed. Global Instance Cinl_proper : Proper ((≡) ==> (≡)) (@Cinl A B). Proof. by constructor. Qed. Global Instance Cinl_inj : Inj (≡) (≡) (@Cinl A B). Proof. by inversion_clear 1. Qed. Global Instance Cinl_inj_dist n : Inj (dist n) (dist n) (@Cinl A B). Proof. by inversion_clear 1. Qed. Global Instance Cinr_ne : NonExpansive (@Cinr A B). Proof. by constructor. Qed. Global Instance Cinr_proper : Proper ((≡) ==> (≡)) (@Cinr A B). Proof. by constructor. Qed. Global Instance Cinr_inj : Inj (≡) (≡) (@Cinr A B). Proof. by inversion_clear 1. Qed. Global Instance Cinr_inj_dist n : Inj (dist n) (dist n) (@Cinr A B). Proof. by inversion_clear 1. Qed. Definition csum_ofe_mixin : OfeMixin (csum A B). Proof. split. - intros mx my; split. + by destruct 1; constructor; try apply equiv_dist. + intros Hxy; feed inversion (Hxy 0); subst; constructor; try done; apply equiv_dist=> n; by feed inversion (Hxy n). - intros n; split. + by intros [|a|]; constructor. + by destruct 1; constructor. + destruct 1; inversion_clear 1; constructor; etrans; eauto. - by inversion_clear 1; constructor; apply dist_S. Qed. Canonical Structure csumO : ofeT := OfeT (csum A B) csum_ofe_mixin. Program Definition csum_chain_l (c : chain csumO) (a : A) : chain A := {| chain_car n := match c n return _ with Cinl a' => a' | _ => a end |}. Next Obligation. intros c a n i ?; simpl. by destruct (chain_cauchy c n i). Qed. Program Definition csum_chain_r (c : chain csumO) (b : B) : chain B := {| chain_car n := match c n return _ with Cinr b' => b' | _ => b end |}. Next Obligation. intros c b n i ?; simpl. by destruct (chain_cauchy c n i). Qed. Definition csum_compl `{Cofe A, Cofe B} : Compl csumO := λ c, match c 0 with | Cinl a => Cinl (compl (csum_chain_l c a)) | Cinr b => Cinr (compl (csum_chain_r c b)) | CsumBot => CsumBot end. Global Program Instance csum_cofe `{Cofe A, Cofe B} : Cofe csumO := {| compl := csum_compl |}. Next Obligation. intros ?? n c; rewrite /compl /csum_compl. feed inversion (chain_cauchy c 0 n); first auto with lia; constructor. + rewrite (conv_compl n (csum_chain_l c a')) /=. destruct (c n); naive_solver. + rewrite (conv_compl n (csum_chain_r c b')) /=. destruct (c n); naive_solver. Qed. Global Instance csum_ofe_discrete : OfeDiscrete A → OfeDiscrete B → OfeDiscrete csumO. Proof. by inversion_clear 3; constructor; apply (discrete _). Qed. Global Instance csum_leibniz : LeibnizEquiv A → LeibnizEquiv B → LeibnizEquiv csumO. Proof. by destruct 3; f_equal; apply leibniz_equiv. Qed. Global Instance Cinl_discrete a : Discrete a → Discrete (Cinl a). Proof. by inversion_clear 2; constructor; apply (discrete _). Qed. Global Instance Cinr_discrete b : Discrete b → Discrete (Cinr b). Proof. by inversion_clear 2; constructor; apply (discrete _). Qed. (** Internalized properties *) Lemma csum_equivI {M} (x y : csum A B) : x ≡ y ⊣⊢@{uPredI M} match x, y with | Cinl a, Cinl a' => a ≡ a' | Cinr b, Cinr b' => b ≡ b' | CsumBot, CsumBot => True | _, _ => False end. Proof. uPred.unseal; do 2 split; first by destruct 1. by destruct x, y; try destruct 1; try constructor. Qed. End cofe. Arguments csumO : clear implicits. (* Functor on COFEs *) Definition csum_map {A A' B B'} (fA : A → A') (fB : B → B') (x : csum A B) : csum A' B' := match x with | Cinl a => Cinl (fA a) | Cinr b => Cinr (fB b) | CsumBot => CsumBot end. Instance: Params (@csum_map) 4 := {}. Lemma csum_map_id {A B} (x : csum A B) : csum_map id id x = x. Proof. by destruct x. Qed. Lemma csum_map_compose {A A' A'' B B' B''} (f : A → A') (f' : A' → A'') (g : B → B') (g' : B' → B'') (x : csum A B) : csum_map (f' ∘ f) (g' ∘ g) x = csum_map f' g' (csum_map f g x). Proof. by destruct x. Qed. Lemma csum_map_ext {A A' B B' : ofeT} (f f' : A → A') (g g' : B → B') x : (∀ x, f x ≡ f' x) → (∀ x, g x ≡ g' x) → csum_map f g x ≡ csum_map f' g' x. Proof. by destruct x; constructor. Qed. Instance csum_map_cmra_ne {A A' B B' : ofeT} n : Proper ((dist n ==> dist n) ==> (dist n ==> dist n) ==> dist n ==> dist n) (@csum_map A A' B B'). Proof. intros f f' Hf g g' Hg []; destruct 1; constructor; by apply Hf || apply Hg. Qed. Definition csumO_map {A A' B B'} (f : A -n> A') (g : B -n> B') : csumO A B -n> csumO A' B' := OfeMor (csum_map f g). Instance csumO_map_ne A A' B B' : NonExpansive2 (@csumO_map A A' B B'). Proof. by intros n f f' Hf g g' Hg []; constructor. Qed. Section cmra. Context {A B : cmraT}. Implicit Types a : A. Implicit Types b : B. (* CMRA *) Instance csum_valid : Valid (csum A B) := λ x, match x with | Cinl a => ✓ a | Cinr b => ✓ b | CsumBot => False end. Instance csum_validN : ValidN (csum A B) := λ n x, match x with | Cinl a => ✓{n} a | Cinr b => ✓{n} b | CsumBot => False end. Instance csum_pcore : PCore (csum A B) := λ x, match x with | Cinl a => Cinl <$> pcore a | Cinr b => Cinr <$> pcore b | CsumBot => Some CsumBot end. Instance csum_op : Op (csum A B) := λ x y, match x, y with | Cinl a, Cinl a' => Cinl (a ⋅ a') | Cinr b, Cinr b' => Cinr (b ⋅ b') | _, _ => CsumBot end. Lemma Cinl_op a a' : Cinl (a ⋅ a') = Cinl a ⋅ Cinl a'. Proof. done. Qed. Lemma Cinr_op b b' : Cinr (b ⋅ b') = Cinr b ⋅ Cinr b'. Proof. done. Qed. Lemma csum_included x y : x ≼ y ↔ y = CsumBot ∨ (∃ a a', x = Cinl a ∧ y = Cinl a' ∧ a ≼ a') ∨ (∃ b b', x = Cinr b ∧ y = Cinr b' ∧ b ≼ b'). Proof. split. - unfold included. intros [[a'|b'|] Hy]; destruct x as [a|b|]; inversion_clear Hy; eauto 10. - intros [->|[(a&a'&->&->&c&?)|(b&b'&->&->&c&?)]]. + destruct x; exists CsumBot; constructor. + exists (Cinl c); by constructor. + exists (Cinr c); by constructor. Qed. Lemma Cinl_included a a' : Cinl a ≼ Cinl a' ↔ a ≼ a'. Proof. rewrite csum_included. naive_solver. Qed. Lemma Cinr_included b b' : Cinr b ≼ Cinr b' ↔ b ≼ b'. Proof. rewrite csum_included. naive_solver. Qed. Lemma csum_includedN n x y : x ≼{n} y ↔ y = CsumBot ∨ (∃ a a', x = Cinl a ∧ y = Cinl a' ∧ a ≼{n} a') ∨ (∃ b b', x = Cinr b ∧ y = Cinr b' ∧ b ≼{n} b'). Proof. split. - unfold includedN. intros [[a'|b'|] Hy]; destruct x as [a|b|]; inversion_clear Hy; eauto 10. - intros [->|[(a&a'&->&->&c&?)|(b&b'&->&->&c&?)]]. + destruct x; exists CsumBot; constructor. + exists (Cinl c); by constructor. + exists (Cinr c); by constructor. Qed. Lemma csum_cmra_mixin : CmraMixin (csum A B). Proof. split. - intros [] n; destruct 1; constructor; by ofe_subst. - intros ???? [n a a' Ha|n b b' Hb|n] [=]; subst; eauto. + destruct (pcore a) as [ca|] eqn:?; simplify_option_eq. destruct (cmra_pcore_ne n a a' ca) as (ca'&->&?); auto. exists (Cinl ca'); by repeat constructor. + destruct (pcore b) as [cb|] eqn:?; simplify_option_eq. destruct (cmra_pcore_ne n b b' cb) as (cb'&->&?); auto. exists (Cinr cb'); by repeat constructor. - intros ? [a|b|] [a'|b'|] H; inversion_clear H; ofe_subst; done. - intros [a|b|]; rewrite /= ?cmra_valid_validN; naive_solver eauto using O. - intros n [a|b|]; simpl; auto using cmra_validN_S. - intros [a1|b1|] [a2|b2|] [a3|b3|]; constructor; by rewrite ?assoc. - intros [a1|b1|] [a2|b2|]; constructor; by rewrite 1?comm. - intros [a|b|] ? [=]; subst; auto. + destruct (pcore a) as [ca|] eqn:?; simplify_option_eq. constructor; eauto using cmra_pcore_l. + destruct (pcore b) as [cb|] eqn:?; simplify_option_eq. constructor; eauto using cmra_pcore_l. - intros [a|b|] ? [=]; subst; auto. + destruct (pcore a) as [ca|] eqn:?; simplify_option_eq. feed inversion (cmra_pcore_idemp a ca); repeat constructor; auto. + destruct (pcore b) as [cb|] eqn:?; simplify_option_eq. feed inversion (cmra_pcore_idemp b cb); repeat constructor; auto. - intros x y ? [->|[(a&a'&->&->&?)|(b&b'&->&->&?)]]%csum_included [=]. + exists CsumBot. rewrite csum_included; eauto. + destruct (pcore a) as [ca|] eqn:?; simplify_option_eq. destruct (cmra_pcore_mono a a' ca) as (ca'&->&?); auto. exists (Cinl ca'). rewrite csum_included; eauto 10. + destruct (pcore b) as [cb|] eqn:?; simplify_option_eq. destruct (cmra_pcore_mono b b' cb) as (cb'&->&?); auto. exists (Cinr cb'). rewrite csum_included; eauto 10. - intros n [a1|b1|] [a2|b2|]; simpl; eauto using cmra_validN_op_l; done. - intros n [a|b|] y1 y2 Hx Hx'. + destruct y1 as [a1|b1|], y2 as [a2|b2|]; try by exfalso; inversion Hx'. destruct (cmra_extend n a a1 a2) as (z1&z2&?&?&?); [done|apply (inj Cinl), Hx'|]. exists (Cinl z1), (Cinl z2). by repeat constructor. + destruct y1 as [a1|b1|], y2 as [a2|b2|]; try by exfalso; inversion Hx'. destruct (cmra_extend n b b1 b2) as (z1&z2&?&?&?); [done|apply (inj Cinr), Hx'|]. exists (Cinr z1), (Cinr z2). by repeat constructor. + by exists CsumBot, CsumBot; destruct y1, y2; inversion_clear Hx'. Qed. Canonical Structure csumR := CmraT (csum A B) csum_cmra_mixin. Global Instance csum_cmra_discrete : CmraDiscrete A → CmraDiscrete B → CmraDiscrete csumR. Proof. split; first apply _. by move=>[a|b|] HH /=; try apply cmra_discrete_valid. Qed. Global Instance Cinl_core_id a : CoreId a → CoreId (Cinl a). Proof. rewrite /CoreId /=. inversion_clear 1; by repeat constructor. Qed. Global Instance Cinr_core_id b : CoreId b → CoreId (Cinr b). Proof. rewrite /CoreId /=. inversion_clear 1; by repeat constructor. Qed. Global Instance Cinl_exclusive a : Exclusive a → Exclusive (Cinl a). Proof. by move=> H[]? =>[/H||]. Qed. Global Instance Cinr_exclusive b : Exclusive b → Exclusive (Cinr b). Proof. by move=> H[]? =>[|/H|]. Qed. Global Instance Cinl_cancelable a : Cancelable a → Cancelable (Cinl a). Proof. move=> ?? [y|y|] [z|z|] ? EQ //; inversion_clear EQ. constructor. by eapply (cancelableN a). Qed. Global Instance Cinr_cancelable b : Cancelable b → Cancelable (Cinr b). Proof. move=> ?? [y|y|] [z|z|] ? EQ //; inversion_clear EQ. constructor. by eapply (cancelableN b). Qed. Global Instance Cinl_id_free a : IdFree a → IdFree (Cinl a). Proof. intros ? [] ? EQ; inversion_clear EQ. by eapply id_free0_r. Qed. Global Instance Cinr_id_free b : IdFree b → IdFree (Cinr b). Proof. intros ? [] ? EQ; inversion_clear EQ. by eapply id_free0_r. Qed. (** Interaction with [option] *) Lemma Some_csum_includedN x y n : Some x ≼{n} Some y ↔ y = CsumBot ∨ (∃ a a', x = Cinl a ∧ y = Cinl a' ∧ Some a ≼{n} Some a') ∨ (∃ b b', x = Cinr b ∧ y = Cinr b' ∧ Some b ≼{n} Some b'). Proof. repeat setoid_rewrite Some_includedN. rewrite csum_includedN. split. - intros [Hxy|?]; [inversion Hxy|]; naive_solver. - naive_solver by f_equiv. Qed. Lemma Some_csum_included x y : Some x ≼ Some y ↔ y = CsumBot ∨ (∃ a a', x = Cinl a ∧ y = Cinl a' ∧ Some a ≼ Some a') ∨ (∃ b b', x = Cinr b ∧ y = Cinr b' ∧ Some b ≼ Some b'). Proof. repeat setoid_rewrite Some_included. rewrite csum_included. split. - intros [Hxy|?]; [inversion Hxy|]; naive_solver. - naive_solver by f_equiv. Qed. (** Internalized properties *) Lemma csum_validI {M} (x : csum A B) : ✓ x ⊣⊢@{uPredI M} match x with | Cinl a => ✓ a | Cinr b => ✓ b | CsumBot => False end. Proof. uPred.unseal. by destruct x. Qed. (** Updates *) Lemma csum_update_l (a1 a2 : A) : a1 ~~> a2 → Cinl a1 ~~> Cinl a2. Proof. intros Ha n [[a|b|]|] ?; simpl in *; auto. - by apply (Ha n (Some a)). - by apply (Ha n None). Qed. Lemma csum_update_r (b1 b2 : B) : b1 ~~> b2 → Cinr b1 ~~> Cinr b2. Proof. intros Hb n [[a|b|]|] ?; simpl in *; auto. - by apply (Hb n (Some b)). - by apply (Hb n None). Qed. Lemma csum_updateP_l (P : A → Prop) (Q : csum A B → Prop) a : a ~~>: P → (∀ a', P a' → Q (Cinl a')) → Cinl a ~~>: Q. Proof. intros Hx HP n mf Hm. destruct mf as [[a'|b'|]|]; try by destruct Hm. - destruct (Hx n (Some a')) as (c&?&?); naive_solver. - destruct (Hx n None) as (c&?&?); naive_solver eauto using cmra_validN_op_l. Qed. Lemma csum_updateP_r (P : B → Prop) (Q : csum A B → Prop) b : b ~~>: P → (∀ b', P b' → Q (Cinr b')) → Cinr b ~~>: Q. Proof. intros Hx HP n mf Hm. destruct mf as [[a'|b'|]|]; try by destruct Hm. - destruct (Hx n (Some b')) as (c&?&?); naive_solver. - destruct (Hx n None) as (c&?&?); naive_solver eauto using cmra_validN_op_l. Qed. Lemma csum_updateP'_l (P : A → Prop) a : a ~~>: P → Cinl a ~~>: λ m', ∃ a', m' = Cinl a' ∧ P a'. Proof. eauto using csum_updateP_l. Qed. Lemma csum_updateP'_r (P : B → Prop) b : b ~~>: P → Cinr b ~~>: λ m', ∃ b', m' = Cinr b' ∧ P b'. Proof. eauto using csum_updateP_r. Qed. Lemma csum_local_update_l (a1 a2 a1' a2' : A) : (a1,a2) ~l~> (a1',a2') → (Cinl a1,Cinl a2) ~l~> (Cinl a1',Cinl a2'). Proof. intros Hup n mf ? Ha1; simpl in *. destruct (Hup n (mf ≫= maybe Cinl)); auto. { by destruct mf as [[]|]; inversion_clear Ha1. } split. done. by destruct mf as [[]|]; inversion_clear Ha1; constructor. Qed. Lemma csum_local_update_r (b1 b2 b1' b2' : B) : (b1,b2) ~l~> (b1',b2') → (Cinr b1,Cinr b2) ~l~> (Cinr b1',Cinr b2'). Proof. intros Hup n mf ? Ha1; simpl in *. destruct (Hup n (mf ≫= maybe Cinr)); auto. { by destruct mf as [[]|]; inversion_clear Ha1. } split. done. by destruct mf as [[]|]; inversion_clear Ha1; constructor. Qed. End cmra. Arguments csumR : clear implicits. (* Functor *) Instance csum_map_cmra_morphism {A A' B B' : cmraT} (f : A → A') (g : B → B') : CmraMorphism f → CmraMorphism g → CmraMorphism (csum_map f g). Proof. split; try apply _. - intros n [a|b|]; simpl; auto using cmra_morphism_validN. - move=> [a|b|]=>//=; rewrite -cmra_morphism_pcore; by destruct pcore. - intros [xa|ya|] [xb|yb|]=>//=; by rewrite cmra_morphism_op. Qed. Program Definition csumRF (Fa Fb : rFunctor) : rFunctor := {| rFunctor_car A _ B _ := csumR (rFunctor_car Fa A B) (rFunctor_car Fb A B); rFunctor_map A1 _ A2 _ B1 _ B2 _ fg := csumO_map (rFunctor_map Fa fg) (rFunctor_map Fb fg) |}. Next Obligation. by intros Fa Fb A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply csumO_map_ne; try apply rFunctor_map_ne. Qed. Next Obligation. intros Fa Fb A ? B ? x. rewrite /= -{2}(csum_map_id x). apply csum_map_ext=>y; apply rFunctor_map_id. Qed. Next Obligation. intros Fa Fb A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x. rewrite /= -csum_map_compose. apply csum_map_ext=>y; apply rFunctor_map_compose. Qed. Instance csumRF_contractive Fa Fb : rFunctorContractive Fa → rFunctorContractive Fb → rFunctorContractive (csumRF Fa Fb). Proof. intros ?? A1 ? A2 ? B1 ? B2 ? n f g Hfg. by apply csumO_map_ne; try apply rFunctor_map_contractive. Qed.
Definition p := true. Obligation Tactic := idtac. Require Import Program. Unset Program Cases. Time Program Fixpoint f (n : nat) {struct n} : nat := match p with false => n | _ => match p with false => n | _ => match p with false => n | _ => match p with false => n | _ => match p with false => n | _ => match p with false => n | _ => match p with false => n | _ => match p with false => n | _ => match p with false => n | _ => match n with | 0 => 0 | S n => S (f n) end end end end end end end end end end. Require Import Lia. Require Import Omega. Require Import ssreflect. Inductive limitedNat {n} : Type := | lim i : i < n -> limitedNat. Definition test i j (H: (i < j) /\ True) : @limitedNat (S j). Proof. refine (lim (S i) _). omega. Defined. ltac:(lazymatch goal with H : ?i < ?j |- _ => idtac H end) end)). refine (lim (S i) (match H with conj IJ _ => ltac:(lazymatch goal with H : ?i < ?j |- _ => idtac H end) end)). lia. (match H with conj IJ _ => ltac:(lia) end). := lim (S i) _. (match H with conj IJ _ => ltac:(lia) end). Lemma test (n: nat) : nat. Proof. Fail idtac n. destruct n eqn:B. Fail idtac B. Fail idtac n. match goal with | H : _ = _ |- _ => idtac H end. destruct n eqn:B. idtac B. exact 0. Defined. exact 0. Defined. From Coq Require Import String. From Coq Require Import List. Import ListNotations. Inductive Expression : Type := | EEmptyList | EVar (s : string) | EMap (l : list (Expression * Expression)). Fixpoint variables (e : Expression) : list string := match e with | EEmptyList => [] | EVar x => [x] | EMap l => fold_right (fun '(a, b) r => app (app (variables a) (variables b)) r) [] l end. Lemma equiv l : fold_right (fun '(a, b) r => app (app (variables a) (variables b)) r) [] l = (fix fp l := match l with | [] => [] | (a,b)::xs => app (app (variables a) (variables b)) (fp xs) end) l. Proof. now induction l; [|destruct a; rewrite <-IHl]. Qed. Require Import iris.algebra.base. Lemma foo : ∀ {A : Set} {P : A → Prop} (a : A), (∀ x, ¬ (P x)) → ¬ (∀ x, P x). intros * a H Hn. eapply (H a), Hn. intros. firstorder. intuition. tauto. Goal let f := plus in f (0 + 0) 0 = 0. cbv beta delta. cbv iota beta. intro f. cbv delta. (* let f := (fix add ...) in f ((fix add ...) 0 0) 0 = 0 *) intro f. cbv delta;clear f. Require Import Lia. From Coq Require Export ZArith NPeano. Lemma foo2 : forall (z:Z), (z >=0)%Z -> { n : nat | Z.of_nat n = z }. Proof. intros z. exists (Z.to_nat z). apply Z2Nat.id. lia. Qed. From Coq.ssr Require Import ssreflect. From Coq Require Export EqdepFacts PArith NArith ZArith NPeano. Lemma foo : forall (z:Z), (z >=0)%Z -> exists n : nat , Z.of_nat n = z. Proof. intros z. exists (Z.to_nat z). apply Z2Nat.id. lia. Qed. Lemma to_nat2 : Z -> nat. intros z. Fail destruct (foo z). Abort. Lemma to_nat2 (z : Z) (H : (z >= 0)%Z): nat. destruct (foo2 z H) as [n _]. exact n. Defined. About Z. From mathcomp.ssreflect Require Import ssrnat. Search _ (forall (z:Z), (z >=0)%Z -> { n : nat | Z.to_nat z = n }). Search _ (forall (z:Z), (z >=0)%Z -> exists n : nat , Z.to_nat z = n). Search _ (_ >= 0 -> Z.abs _ = _). Require Import Lia. Inductive foo := . Inductive bar := . Require Import Lia. From Coq.ssr Require Import ssreflect. Lemma baz : 1 = 2 -> 3 = 4. move => Hi. have {Hi} -Hi: 2 = 3 by lia. lia. Qed. Lemma foo (H:True) : True -> True. Proof. move => {H} -H. exact I. Qed.