text
stringlengths 0
3.34M
|
---|
lemma convex_differences: assumes "convex S" "convex T" shows "convex (\<Union>x\<in> S. \<Union>y \<in> T. {x - y})"
|
# We've now learned some of the basic tools for building a shiny app. Now complete the tasks to add additional bells and whistles to the shiny app.
# After you have finished with your app, you can deploy it to the world to see. There are a number of options for this, which I won't go into detail because it depends on your personal preference for how you want the data shared (See https://shiny.rstudio.com/tutorial/lesson7/)
library(shiny) #First load shiny library
load("../pcas.RDATA") #Load data
#Define the overall UI
shinyUI(
#Use a fluid Bootstrap layout
fluidPage(
#Give the page a title
titlePanel("PCA of Metrics"),
#Define page with a sidebar panel and main panel
sidebarLayout(
#Sidebar Panel
sidebarPanel(
#Create drop-down menu to select Variable to plot PCA for
selectInput(inputId='var', label = h3('Variable'),
choices = c(
"Colless" = "colless",
"Species Pool Size" = "numsp",
"Spatially Contiguous" = "spatial"
)
),
#Check box group, contingent upon previous drop-down menu selection
uiOutput(outputId="paramchkbxgrp"),
#Create a slider that will adjust the cex value of the text displayed called "cexSlider".
sliderInput(inputId = "cexSlider", label=h4("Adjust cex"),
min = 0, max=5, value=1)
),
#Create a spot for the plot
mainPanel(
plotOutput("pcaplot")
)
)
)
)
#TASKS:
#1. Create the ability to zoom in or out of the plots. Create two sliderInput objects to adjust the x- and y-axes of the plot depending on the Variable selected. To do so:
# a. Within the sidebarPanel of the ui.R script, add two uiOutput objects, containing the outputId names of "sliderX" and "sliderY"
# b. In script.R, create the output$sliderX and output$sliderY objects with the function renderUI. (see script.R)
#2. Change the plot width. For plotOutput(outputId="pcaplot"), add width (width = "750px") and height (height = "650px") parameters
#HINTS:
#1.a.
# sidebarPanel(
# selectInput(inputId='var', ...),
# uiOutput(outputId="paramchkbxgrp"),
# sliderInput(inputId = "cexSlider", ...),
# #********ADD THIS SCRIPT********
# uiOutput(outputId="sliderX"),
# uiOutput(outputId="sliderY")
# #*******************************
# )
#2. plotOutput(outputId="pcaplot", width="750px",height="750px")
|
[STATEMENT]
lemma real_minus: "- Abs_Real(realrel``{(x,y)}) = Abs_Real(realrel `` {(y,x)})"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. - Abs_Real (Dedekind_Real.realrel `` {(x, y)}) = Abs_Real (Dedekind_Real.realrel `` {(y, x)})
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. - Abs_Real (Dedekind_Real.realrel `` {(x, y)}) = Abs_Real (Dedekind_Real.realrel `` {(y, x)})
[PROOF STEP]
have "(\<lambda>(x,y). {Abs_Real (realrel``{(y,x)})}) respects realrel"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<lambda>(x, y). {Abs_Real (Dedekind_Real.realrel `` {(y, x)})}) respects Dedekind_Real.realrel
[PROOF STEP]
by (auto simp: congruent_def add.commute)
[PROOF STATE]
proof (state)
this:
(\<lambda>(x, y). {Abs_Real (Dedekind_Real.realrel `` {(y, x)})}) respects Dedekind_Real.realrel
goal (1 subgoal):
1. - Abs_Real (Dedekind_Real.realrel `` {(x, y)}) = Abs_Real (Dedekind_Real.realrel `` {(y, x)})
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
(\<lambda>(x, y). {Abs_Real (Dedekind_Real.realrel `` {(y, x)})}) respects Dedekind_Real.realrel
goal (1 subgoal):
1. - Abs_Real (Dedekind_Real.realrel `` {(x, y)}) = Abs_Real (Dedekind_Real.realrel `` {(y, x)})
[PROOF STEP]
by (simp add: real_minus_def UN_equiv_class [OF equiv_realrel])
[PROOF STATE]
proof (state)
this:
- Abs_Real (Dedekind_Real.realrel `` {(x, y)}) = Abs_Real (Dedekind_Real.realrel `` {(y, x)})
goal:
No subgoals!
[PROOF STEP]
qed
|
Formal statement is: lemma set_coeffs_subset_singleton_0_iff [simp]: "set (coeffs p) \<subseteq> {0} \<longleftrightarrow> p = 0" Informal statement is: The set of coefficients of a polynomial is a subset of $\{0\}$ if and only if the polynomial is zero.
|
-- | Simple linear regression example for the README.
import Lib(someFunc)
import Control.Monad (replicateM, replicateM_, zipWithM)
import System.Random (randomIO)
import Test.HUnit (assertBool)
import qualified TensorFlow.Core as TF
import qualified TensorFlow.GenOps.Core as TF
import qualified TensorFlow.Gradient as TF
import qualified TensorFlow.Ops as TF
import qualified Data.Random.Normal as Normal
import qualified Statistics.Sample as Stat
import qualified Data.Vector as Vector
import Text.Printf
-- | R² of the model Ŷ = aX+b
-- Note that 'TF.gradient' doesn't support Double
linearModelRSquared :: [Float] -> [Float] -> Float -> Float
-> Float
linearModelRSquared xs ys a b = 1 - ssRes / ssTot
where
es = zipWith (-) ys yHats
yHats = [ a*x+b | x <- xs ]
-- realToFrac is only ok in this situation
yMean = realToFrac $ Stat.mean $ Vector.fromList $ (map realToFrac ys)
ssTot = sum [ (y - yMean) ^ 2 | y <- ys ]
ssReg = sum [ (y - yMean) ^ 2 | y <- yHats ]
ssRes = sum [ e ^ 2 | e <- es ]
main :: IO ()
main = do
-- Generate a list of Gaussian errors
noise <- replicateM 100 (Normal.normalIO' (0, 0.1))
let xData = tail [0,0.01..1]
yData = [ 3*x + 8 + e | (x,e) <- zip xData noise]
-- Fit the linear regression model.
(w, b) <- fit xData yData
-- Calculate and print the R-squared for the model
let rSquared = linearModelRSquared xData yData w b
printf "R^2 = %f\n" rSquared
fit :: [Float] -> [Float] -> IO (Float, Float)
fit xData yData = TF.runSession $ do
-- Create tensorflow constants for x and y.
let x = TF.vector xData
y = TF.vector yData
-- Create scalar variables for slope and intercept.
w <- TF.initializedVariable 0
b <- TF.initializedVariable 0
-- Define the loss function.
let yHat = (x `TF.mul` w) `TF.add` b
loss = TF.square (yHat `TF.sub` y)
-- Optimize with gradient descent.
trainStep <- gradientDescent 0.001 loss [w, b]
replicateM_ 1000 (TF.run trainStep)
-- Return the learned parameters.
(TF.Scalar w', TF.Scalar b') <- TF.run (w, b)
return (w', b')
gradientDescent :: Float
-> TF.Tensor TF.Build Float
-> [TF.Tensor TF.Ref Float]
-> TF.Session TF.ControlNode
gradientDescent alpha loss params = do
let applyGrad param grad =
TF.assign param (param `TF.sub` (TF.scalar alpha `TF.mul` grad))
TF.group =<< zipWithM applyGrad params =<< TF.gradients loss params
|
function [out, param] = pid_loop(y_c, y, dy, kp, ki, kd, limit, Ts, tau, param)
integrator = param.int;
differentiator = param.diff;
error_prev = param.error_prev;
y_c_prev = param.y_c_prev;
% Update error
error = y_c - y;
% Update integrator
if isfinite(dy)
integrator = integrator + Ts*(error + dy/2);
else
integrator = integrator + (Ts/2)*(error + error_prev);
end
% Update differentiator
if isfinite(1/kd)
if isfinite(dy)
dy_c = y_c - y_c_prev; % Compute command diff
derror = dy_c - dy; % Compute error diff
y_c_prev = y_c; % Update the command for next step
else
derror = error - error_prev; % Compute error diff
error_prev = error; % Update the error for next step
end
differentiator = (2*tau-Ts)/(2*tau+Ts)*differentiator...
+ 2/(2*tau+Ts)*(derror);
end
% Update output before considering saturation
out_unsat = kp*error + ki*integrator + kd*differentiator;
% Check saturation
out = saturate(out_unsat, limit);
% Implement integrator anti-windup
if ki~=0
integrator = integrator + Ts/ki * (out - out_unsat);
end
param.int = integrator;
param.diff = differentiator;
param.error_prev = error_prev;
param.y_c_prev = y_c_prev;
end
function out = saturate(out_unsat, limit)
if out_unsat > limit
out = limit;
elseif out_unsat < -limit
out = -limit;
else
out = out_unsat;
end
end
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury Kudryashov
! This file was ported from Lean 3 source module data.real.ennreal
! leanprover-community/mathlib commit 8631e2d5ea77f6c13054d9151d82b83069680cb1
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Hata.MathlibPort.Data.Real.Nnreal
import Mathlib.Algebra.Order.Sub.WithTop
import Mathlib.Algebra.Order.Group.Instances
import Mathlib.Algebra.Order.Monoid.WithTop
import Mathlib.Algebra.Order.Group.WithTop
import Mathlib.Algebra.Order.Sub.WithTop
import Mathlib.Order.WithBot
/-!
# Extended non-negative reals
We define `ennreal = ℝ≥0∞ := with_top ℝ≥0` to be the type of extended nonnegative real numbers,
i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`,
and of the extended distance `edist` in a `emetric_space`.
In this file we define some algebraic operations and a linear order on `ℝ≥0∞`
and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`.
## Main definitions
* `ℝ≥0∞`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is
equipped with the following structures:
- coercion from `ℝ≥0` defined in the natural way;
- the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`;
- `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`;
- `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a *
∞ = ∞ * a = ∞` for `a ≠ 0`;
- `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have
`↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only
subtraction;
- `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for
`p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`.
- `a / b` is defined as `a * b⁻¹`.
The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn
`ℝ≥0∞` into a canonically ordered commutative semiring of characteristic zero.
* Coercions to/from other types:
- coercion `ℝ≥0 → ℝ≥0∞` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that
expects `a : ℝ≥0∞`, and Lean will apply `coe` automatically;
- `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`;
- `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`;
- `ennreal.of_real := coe ∘ real.to_nnreal` sends `x : ℝ` to `↑⟨max x 0, _⟩`
- `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ℝ≥0∞ // a ≠ 0}` and `ℝ≥0`.
## Implementation notes
We define a `can_lift ℝ≥0∞ ℝ≥0` instance, so one of the ways to prove theorems about an `ℝ≥0∞`
number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha`
in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the
context, or if we have `(f : α → ℝ≥0∞) (hf : ∀ x, f x ≠ ∞)`.
## Notations
* `ℝ≥0∞`: the type of the extended nonnegative real numbers;
* `ℝ≥0`: the type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`;
* `∞`: a localized notation in `ℝ≥0∞` for `⊤ : ℝ≥0∞`.
-/
open Classical Set
open Classical Nnreal -- BigOperators Nnreal
variable {α : Type _} {β : Type _}
/-- The extended nonnegative real numbers. This is usually denoted [0, ∞],
and is relevant as the codomain of a measure. -/
def Ennreal :=
WithTop ℝ≥0 deriving AddCommMonoidWithOne, SemilatticeSup, DistribLattice,
Nontrivial
-- CanonicallyOrderedCommSemiring
#align ennreal Ennreal
section
example : DenselyOrdered Nnreal := inferInstance
example : NoMaxOrder Nnreal := inferInstance
instance : Zero Ennreal := inferInstance
noncomputable instance : Sub Ennreal := WithTop.hasSub
noncomputable instance : OrderedSub Ennreal := WithTop.orderedSub
instance : DenselyOrdered Ennreal := WithTop.denselyOrdered
instance : OrderBot Ennreal := WithTop.orderBot
instance : BoundedOrder Ennreal := WithTop.boundedOrder
noncomputable instance : ConditionallyCompleteLinearOrderBot Nnreal := inferInstance
noncomputable instance : CompleteLinearOrder Ennreal := WithTop.completeLinearOrder
noncomputable instance : LinearOrderedAddCommMonoidWithTop Ennreal := WithTop.linearOrderedAddCommMonoidWithTop
noncomputable instance : OrderedAddCommMonoid Ennreal := inferInstance
noncomputable instance : Bot Ennreal := inferInstance
instance : CanonicallyOrderedAddMonoid Ennreal := WithTop.canonicallyOrderedAddMonoid
--
-- TODO: It seems like we might need to show this?
-- instance : CanonicallyOrderedCommSemiring Ennreal :=
--
end
-- mathport name: ennreal
scoped[Ennreal] notation "ℝ≥0∞" => Ennreal
-- mathport name: ennreal.top
scoped[Ennreal] notation "∞" => (⊤ : Ennreal)
namespace Ennreal
variable {a b c d : ℝ≥0∞} {r p q : ℝ≥0}
/-
-- TODO: why are the two covariant instances necessary? why aren't they inferred?
instance covariantClass_mul_le : CovariantClass ℝ≥0∞ ℝ≥0∞ (· * ·) (· ≤ ·) :=
CanonicallyOrderedCommSemiring.toCovariantClassMulLE
#align ennreal.covariant_class_mul_le Ennreal.covariantClass_mul_le
instance covariantClass_add_le : CovariantClass ℝ≥0∞ ℝ≥0∞ (· + ·) (· ≤ ·) :=
OrderedAddCommMonoid.to_covariantClass_left ℝ≥0∞
#align ennreal.covariant_class_add_le Ennreal.covariantClass_add_le
noncomputable instance : LinearOrderedCommMonoidWithZero ℝ≥0∞ :=
{ Ennreal.linearOrderedAddCommMonoidWithTop,
show CommSemiring ℝ≥0∞ from
inferInstance with
mul_le_mul_left := fun a b => mul_le_mul_left'
zero_le_one := zero_le 1 }
-/
instance : Inhabited ℝ≥0∞ :=
⟨0⟩
instance : Coe ℝ≥0 ℝ≥0∞ :=
⟨Option.some⟩
/-
instance canLift : CanLift ℝ≥0∞ ℝ≥0 coe fun r => r ≠ ∞
where prf x hx := ⟨Option.get <| Option.ne_none_iff_isSome.1 hx, Option.some_get _⟩
#align ennreal.can_lift Ennreal.canLift
@[simp]
theorem none_eq_top : (none : ℝ≥0∞) = ∞ :=
rfl
#align ennreal.none_eq_top Ennreal.none_eq_top
@[simp]
theorem some_eq_coe (a : ℝ≥0) : (choose a : ℝ≥0∞) = (↑a : ℝ≥0∞) :=
rfl
#align ennreal.some_eq_coe Ennreal.some_eq_coe
-/
/-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/
protected noncomputable def toNnreal : ℝ≥0∞ → ℝ≥0 :=
WithTop.untop' 0
#align ennreal.to_nnreal Ennreal.toNnreal
/-- `to_real x` returns `x` if it is real, `0` otherwise. -/
protected noncomputable def toReal (a : ℝ≥0∞) : Real :=
Coe.coe a.toNnreal
#align ennreal.to_real Ennreal.toReal
/-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/
protected noncomputable def ofReal (r : Real) : ℝ≥0∞ :=
Coe.coe (Real.toNnreal r)
#align ennreal.of_real Ennreal.ofReal
/-
@[simp, norm_cast]
theorem toNnreal_coe : (r : ℝ≥0∞).toNnreal = r :=
rfl
#align ennreal.to_nnreal_coe Ennreal.toNnreal_coe
@[simp]
theorem coe_toNnreal : ∀ {a : ℝ≥0∞}, a ≠ ∞ → ↑a.toNnreal = a
| some r, h => rfl
| none, h => (h rfl).elim
#align ennreal.coe_to_nnreal Ennreal.coe_toNnreal
@[simp]
theorem ofReal_toReal {a : ℝ≥0∞} (h : a ≠ ∞) : Ennreal.ofReal a.toReal = a := by
simp [Ennreal.toReal, Ennreal.ofReal, h]
#align ennreal.of_real_to_real Ennreal.ofReal_toReal
@[simp]
theorem toReal_ofReal {r : ℝ} (h : 0 ≤ r) : Ennreal.toReal (Ennreal.ofReal r) = r := by
simp [Ennreal.toReal, Ennreal.ofReal, Real.coe_toNnreal _ h]
#align ennreal.to_real_of_real Ennreal.toReal_ofReal
theorem toReal_of_real' {r : ℝ} : Ennreal.toReal (Ennreal.ofReal r) = max r 0 :=
rfl
#align ennreal.to_real_of_real' Ennreal.toReal_of_real'
theorem coe_toNnreal_le_self : ∀ {a : ℝ≥0∞}, ↑a.toNnreal ≤ a
| some r => by rw [some_eq_coe, to_nnreal_coe] <;> exact le_rfl
| none => le_top
#align ennreal.coe_to_nnreal_le_self Ennreal.coe_toNnreal_le_self
theorem coe_nnreal_eq (r : ℝ≥0) : (r : ℝ≥0∞) = Ennreal.ofReal r :=
by
rw [Ennreal.ofReal, Real.toNnreal]
cases' r with r h
congr
dsimp
rw [max_eq_left h]
#align ennreal.coe_nnreal_eq Ennreal.coe_nnreal_eq
theorem ofReal_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) :
Ennreal.ofReal x = @coe ℝ≥0 ℝ≥0∞ _ (⟨x, h⟩ : ℝ≥0) :=
by
rw [coe_nnreal_eq]
rfl
#align ennreal.of_real_eq_coe_nnreal Ennreal.ofReal_eq_coe_nnreal
@[simp]
theorem ofReal_coe_nnreal : Ennreal.ofReal p = p :=
(coe_nnreal_eq p).symm
#align ennreal.of_real_coe_nnreal Ennreal.ofReal_coe_nnreal
@[simp, norm_cast]
theorem coe_zero : ↑(0 : ℝ≥0) = (0 : ℝ≥0∞) :=
rfl
#align ennreal.coe_zero Ennreal.coe_zero
@[simp, norm_cast]
theorem coe_one : ↑(1 : ℝ≥0) = (1 : ℝ≥0∞) :=
rfl
#align ennreal.coe_one Ennreal.coe_one
@[simp]
theorem toReal_nonneg {a : ℝ≥0∞} : 0 ≤ a.toReal := by simp [Ennreal.toReal]
#align ennreal.to_real_nonneg Ennreal.toReal_nonneg
@[simp]
theorem top_toNnreal : ∞.toNnreal = 0 :=
rfl
#align ennreal.top_to_nnreal Ennreal.top_toNnreal
@[simp]
theorem top_toReal : ∞.toReal = 0 :=
rfl
#align ennreal.top_to_real Ennreal.top_toReal
@[simp]
theorem one_toReal : (1 : ℝ≥0∞).toReal = 1 :=
rfl
#align ennreal.one_to_real Ennreal.one_toReal
@[simp]
theorem one_toNnreal : (1 : ℝ≥0∞).toNnreal = 1 :=
rfl
#align ennreal.one_to_nnreal Ennreal.one_toNnreal
@[simp]
theorem coe_toReal (r : ℝ≥0) : (r : ℝ≥0∞).toReal = r :=
rfl
#align ennreal.coe_to_real Ennreal.coe_toReal
@[simp]
theorem zero_toNnreal : (0 : ℝ≥0∞).toNnreal = 0 :=
rfl
#align ennreal.zero_to_nnreal Ennreal.zero_toNnreal
@[simp]
theorem zero_toReal : (0 : ℝ≥0∞).toReal = 0 :=
rfl
#align ennreal.zero_to_real Ennreal.zero_toReal
@[simp]
theorem ofReal_zero : Ennreal.ofReal (0 : ℝ) = 0 := by simp [Ennreal.ofReal] <;> rfl
#align ennreal.of_real_zero Ennreal.ofReal_zero
@[simp]
theorem ofReal_one : Ennreal.ofReal (1 : ℝ) = (1 : ℝ≥0∞) := by simp [Ennreal.ofReal]
#align ennreal.of_real_one Ennreal.ofReal_one
theorem ofReal_toReal_le {a : ℝ≥0∞} : Ennreal.ofReal a.toReal ≤ a :=
if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (ofReal_toReal ha)
#align ennreal.of_real_to_real_le Ennreal.ofReal_toReal_le
theorem forall_ennreal {p : ℝ≥0∞ → Prop} : (∀ a, p a) ↔ (∀ r : ℝ≥0, p r) ∧ p ∞ :=
⟨fun h => ⟨fun r => h _, h _⟩, fun ⟨h₁, h₂⟩ a =>
match a with
| some r => h₁ _
| none => h₂⟩
#align ennreal.forall_ennreal Ennreal.forall_ennreal
/- ./././Mathport/Syntax/Translate/Basic.lean:632:2: warning: expanding binder collection (a «expr ≠ » ennreal.top()) -/
theorem forall_ne_top {p : ℝ≥0∞ → Prop} : (∀ (a) (_ : a ≠ ∞), p a) ↔ ∀ r : ℝ≥0, p r :=
Option.ball_ne_none
#align ennreal.forall_ne_top Ennreal.forall_ne_top
/- ./././Mathport/Syntax/Translate/Basic.lean:632:2: warning: expanding binder collection (a «expr ≠ » ennreal.top()) -/
theorem exists_ne_top {p : ℝ≥0∞ → Prop} : (∃ (a : _)(_ : a ≠ ∞), p a) ↔ ∃ r : ℝ≥0, p r :=
Option.bex_ne_none
#align ennreal.exists_ne_top Ennreal.exists_ne_top
theorem toNnreal_eq_zero_iff (x : ℝ≥0∞) : x.toNnreal = 0 ↔ x = 0 ∨ x = ∞ :=
⟨by
cases x
· simp [none_eq_top]
· rintro (rfl : x = 0)
exact Or.inl rfl, by rintro (h | h) <;> simp [h]⟩
#align ennreal.to_nnreal_eq_zero_iff Ennreal.toNnreal_eq_zero_iff
theorem toReal_eq_zero_iff (x : ℝ≥0∞) : x.toReal = 0 ↔ x = 0 ∨ x = ∞ := by
simp [Ennreal.toReal, to_nnreal_eq_zero_iff]
#align ennreal.to_real_eq_zero_iff Ennreal.toReal_eq_zero_iff
theorem toNnreal_eq_one_iff (x : ℝ≥0∞) : x.toNnreal = 1 ↔ x = 1 :=
by
refine' ⟨fun h => _, congr_arg _⟩
cases x
· exact False.elim (zero_ne_one <| ennreal.top_to_nnreal.symm.trans h)
· exact congr_arg _ h
#align ennreal.to_nnreal_eq_one_iff Ennreal.toNnreal_eq_one_iff
theorem toReal_eq_one_iff (x : ℝ≥0∞) : x.toReal = 1 ↔ x = 1 := by
rw [Ennreal.toReal, Nnreal.coe_eq_one, Ennreal.toNnreal_eq_one_iff]
#align ennreal.to_real_eq_one_iff Ennreal.toReal_eq_one_iff
@[simp]
theorem coe_ne_top : (r : ℝ≥0∞) ≠ ∞ :=
WithTop.coe_ne_top
#align ennreal.coe_ne_top Ennreal.coe_ne_top
@[simp]
theorem top_ne_coe : ∞ ≠ (r : ℝ≥0∞) :=
WithTop.top_ne_coe
#align ennreal.top_ne_coe Ennreal.top_ne_coe
@[simp]
theorem ofReal_ne_top {r : ℝ} : Ennreal.ofReal r ≠ ∞ := by simp [Ennreal.ofReal]
#align ennreal.of_real_ne_top Ennreal.ofReal_ne_top
@[simp]
theorem ofReal_lt_top {r : ℝ} : Ennreal.ofReal r < ∞ :=
lt_top_iff_ne_top.2 ofReal_ne_top
#align ennreal.of_real_lt_top Ennreal.ofReal_lt_top
@[simp]
theorem top_ne_ofReal {r : ℝ} : ∞ ≠ Ennreal.ofReal r := by simp [Ennreal.ofReal]
#align ennreal.top_ne_of_real Ennreal.top_ne_ofReal
@[simp]
theorem zero_ne_top : 0 ≠ ∞ :=
coe_ne_top
#align ennreal.zero_ne_top Ennreal.zero_ne_top
@[simp]
theorem top_ne_zero : ∞ ≠ 0 :=
top_ne_coe
#align ennreal.top_ne_zero Ennreal.top_ne_zero
@[simp]
theorem one_ne_top : 1 ≠ ∞ :=
coe_ne_top
#align ennreal.one_ne_top Ennreal.one_ne_top
@[simp]
theorem top_ne_one : ∞ ≠ 1 :=
top_ne_coe
#align ennreal.top_ne_one Ennreal.top_ne_one
@[simp, norm_cast]
theorem coe_eq_coe : (↑r : ℝ≥0∞) = ↑q ↔ r = q :=
WithTop.coe_eq_coe
#align ennreal.coe_eq_coe Ennreal.coe_eq_coe
@[simp, norm_cast]
theorem coe_le_coe : (↑r : ℝ≥0∞) ≤ ↑q ↔ r ≤ q :=
WithTop.coe_le_coe
#align ennreal.coe_le_coe Ennreal.coe_le_coe
@[simp, norm_cast]
theorem coe_lt_coe : (↑r : ℝ≥0∞) < ↑q ↔ r < q :=
WithTop.coe_lt_coe
#align ennreal.coe_lt_coe Ennreal.coe_lt_coe
theorem coe_mono : Monotone (coe : ℝ≥0 → ℝ≥0∞) := fun _ _ => coe_le_coe.2
#align ennreal.coe_mono Ennreal.coe_mono
@[simp, norm_cast]
theorem coe_eq_zero : (↑r : ℝ≥0∞) = 0 ↔ r = 0 :=
coe_eq_coe
#align ennreal.coe_eq_zero Ennreal.coe_eq_zero
@[simp, norm_cast]
theorem zero_eq_coe : 0 = (↑r : ℝ≥0∞) ↔ 0 = r :=
coe_eq_coe
#align ennreal.zero_eq_coe Ennreal.zero_eq_coe
@[simp, norm_cast]
theorem coe_eq_one : (↑r : ℝ≥0∞) = 1 ↔ r = 1 :=
coe_eq_coe
#align ennreal.coe_eq_one Ennreal.coe_eq_one
@[simp, norm_cast]
theorem one_eq_coe : 1 = (↑r : ℝ≥0∞) ↔ 1 = r :=
coe_eq_coe
#align ennreal.one_eq_coe Ennreal.one_eq_coe
@[simp]
theorem coe_nonneg : 0 ≤ (↑r : ℝ≥0∞) :=
coe_le_coe.2 <| zero_le _
#align ennreal.coe_nonneg Ennreal.coe_nonneg
@[simp, norm_cast]
theorem coe_pos : 0 < (↑r : ℝ≥0∞) ↔ 0 < r :=
coe_lt_coe
#align ennreal.coe_pos Ennreal.coe_pos
theorem coe_ne_zero : (r : ℝ≥0∞) ≠ 0 ↔ r ≠ 0 :=
not_congr coe_eq_coe
#align ennreal.coe_ne_zero Ennreal.coe_ne_zero
@[simp, norm_cast]
theorem coe_add : ↑(r + p) = (r + p : ℝ≥0∞) :=
WithTop.coe_add
#align ennreal.coe_add Ennreal.coe_add
@[simp, norm_cast]
theorem coe_mul : ↑(r * p) = (r * p : ℝ≥0∞) :=
WithTop.coe_mul
#align ennreal.coe_mul Ennreal.coe_mul
@[simp, norm_cast]
theorem coe_bit0 : (↑(bit0 r) : ℝ≥0∞) = bit0 r :=
coe_add
#align ennreal.coe_bit0 Ennreal.coe_bit0
@[simp, norm_cast]
theorem coe_bit1 : (↑(bit1 r) : ℝ≥0∞) = bit1 r := by simp [bit1]
#align ennreal.coe_bit1 Ennreal.coe_bit1
theorem coe_two : ((2 : ℝ≥0) : ℝ≥0∞) = 2 := by norm_cast
#align ennreal.coe_two Ennreal.coe_two
theorem toNnreal_eq_toNnreal_iff (x y : ℝ≥0∞) :
x.toNnreal = y.toNnreal ↔ x = y ∨ x = 0 ∧ y = ⊤ ∨ x = ⊤ ∧ y = 0 :=
by
cases x
·
simp only [@eq_comm ℝ≥0 _ y.to_nnreal, @eq_comm ℝ≥0∞ _ y, to_nnreal_eq_zero_iff, none_eq_top,
top_to_nnreal, top_ne_zero, false_and_iff, eq_self_iff_true, true_and_iff, false_or_iff,
or_comm' (y = ⊤)]
· cases y <;> simp
#align ennreal.to_nnreal_eq_to_nnreal_iff Ennreal.toNnreal_eq_toNnreal_iff
theorem toReal_eq_toReal_iff (x y : ℝ≥0∞) :
x.toReal = y.toReal ↔ x = y ∨ x = 0 ∧ y = ⊤ ∨ x = ⊤ ∧ y = 0 := by
simp only [Ennreal.toReal, Nnreal.coe_eq, to_nnreal_eq_to_nnreal_iff]
#align ennreal.to_real_eq_to_real_iff Ennreal.toReal_eq_toReal_iff
theorem toNnreal_eq_toNnreal_iff' {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) :
x.toNnreal = y.toNnreal ↔ x = y := by
simp only [Ennreal.toNnreal_eq_toNnreal_iff x y, hx, hy, and_false_iff, false_and_iff,
or_false_iff]
#align ennreal.to_nnreal_eq_to_nnreal_iff' Ennreal.toNnreal_eq_toNnreal_iff'
theorem toReal_eq_toReal_iff' {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) :
x.toReal = y.toReal ↔ x = y := by
simp only [Ennreal.toReal, Nnreal.coe_eq, to_nnreal_eq_to_nnreal_iff' hx hy]
#align ennreal.to_real_eq_to_real_iff' Ennreal.toReal_eq_toReal_iff'
protected theorem zero_lt_one : 0 < (1 : ℝ≥0∞) :=
zero_lt_one
#align ennreal.zero_lt_one Ennreal.zero_lt_one
@[simp]
theorem one_lt_two : (1 : ℝ≥0∞) < 2 :=
coe_one ▸ coe_two ▸ by exact_mod_cast (one_lt_two : 1 < 2)
#align ennreal.one_lt_two Ennreal.one_lt_two
@[simp]
theorem zero_lt_two : (0 : ℝ≥0∞) < 2 :=
lt_trans zero_lt_one one_lt_two
#align ennreal.zero_lt_two Ennreal.zero_lt_two
theorem two_ne_zero : (2 : ℝ≥0∞) ≠ 0 :=
(ne_of_lt zero_lt_two).symm
#align ennreal.two_ne_zero Ennreal.two_ne_zero
theorem two_ne_top : (2 : ℝ≥0∞) ≠ ∞ :=
coe_two ▸ coe_ne_top
#align ennreal.two_ne_top Ennreal.two_ne_top
/-- `(1 : ℝ≥0∞) ≤ 1`, recorded as a `fact` for use with `Lp` spaces. -/
instance fact_one_le_one_ennreal : Fact ((1 : ℝ≥0∞) ≤ 1) :=
⟨le_rfl⟩
#align fact_one_le_one_ennreal fact_one_le_one_ennreal
/-- `(1 : ℝ≥0∞) ≤ 2`, recorded as a `fact` for use with `Lp` spaces. -/
instance fact_one_le_two_ennreal : Fact ((1 : ℝ≥0∞) ≤ 2) :=
⟨one_le_two⟩
#align fact_one_le_two_ennreal fact_one_le_two_ennreal
/-- `(1 : ℝ≥0∞) ≤ ∞`, recorded as a `fact` for use with `Lp` spaces. -/
instance fact_one_le_top_ennreal : Fact ((1 : ℝ≥0∞) ≤ ∞) :=
⟨le_top⟩
#align fact_one_le_top_ennreal fact_one_le_top_ennreal
/-- The set of numbers in `ℝ≥0∞` that are not equal to `∞` is equivalent to `ℝ≥0`. -/
def neTopEquivNnreal : { a | a ≠ ∞ } ≃ ℝ≥0
where
toFun x := Ennreal.toNnreal x
invFun x := ⟨x, coe_ne_top⟩
left_inv := fun ⟨x, hx⟩ => Subtype.eq <| coe_toNnreal hx
right_inv x := toNnreal_coe
#align ennreal.ne_top_equiv_nnreal Ennreal.neTopEquivNnreal
theorem cinfi_ne_top [InfSet α] (f : ℝ≥0∞ → α) : (⨅ x : { x // x ≠ ∞ }, f x) = ⨅ x : ℝ≥0, f x :=
Eq.symm <| neTopEquivNnreal.symm.Surjective.infi_congr _ fun x => rfl
#align ennreal.cinfi_ne_top Ennreal.cinfi_ne_top
/- ./././Mathport/Syntax/Translate/Basic.lean:632:2: warning: expanding binder collection (x «expr ≠ » ennreal.top()) -/
theorem infᵢ_ne_top [CompleteLattice α] (f : ℝ≥0∞ → α) :
(⨅ (x) (_ : x ≠ ∞), f x) = ⨅ x : ℝ≥0, f x := by rw [infᵢ_subtype', cinfi_ne_top]
#align ennreal.infi_ne_top Ennreal.infᵢ_ne_top
theorem csupr_ne_top [SupSet α] (f : ℝ≥0∞ → α) : (⨆ x : { x // x ≠ ∞ }, f x) = ⨆ x : ℝ≥0, f x :=
@cinfi_ne_top αᵒᵈ _ _
#align ennreal.csupr_ne_top Ennreal.csupr_ne_top
/- ./././Mathport/Syntax/Translate/Basic.lean:632:2: warning: expanding binder collection (x «expr ≠ » ennreal.top()) -/
theorem supᵢ_ne_top [CompleteLattice α] (f : ℝ≥0∞ → α) :
(⨆ (x) (_ : x ≠ ∞), f x) = ⨆ x : ℝ≥0, f x :=
@infᵢ_ne_top αᵒᵈ _ _
#align ennreal.supr_ne_top Ennreal.supᵢ_ne_top
theorem infᵢ_ennreal {α : Type _} [CompleteLattice α] {f : ℝ≥0∞ → α} :
(⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ :=
le_antisymm (le_inf (le_infᵢ fun i => infᵢ_le _ _) (infᵢ_le _ _))
(le_infᵢ <| forall_ennreal.2 ⟨fun r => inf_le_of_left_le <| infᵢ_le _ _, inf_le_right⟩)
#align ennreal.infi_ennreal Ennreal.infᵢ_ennreal
theorem supᵢ_ennreal {α : Type _} [CompleteLattice α] {f : ℝ≥0∞ → α} :
(⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ :=
@infᵢ_ennreal αᵒᵈ _ _
#align ennreal.supr_ennreal Ennreal.supᵢ_ennreal
@[simp]
theorem add_top : a + ∞ = ∞ :=
add_top _
#align ennreal.add_top Ennreal.add_top
@[simp]
theorem top_add : ∞ + a = ∞ :=
top_add _
#align ennreal.top_add Ennreal.top_add
/-- Coercion `ℝ≥0 → ℝ≥0∞` as a `ring_hom`. -/
def ofNnrealHom : ℝ≥0 →+* ℝ≥0∞ :=
⟨coe, coe_one, fun _ _ => coe_mul, coe_zero, fun _ _ => coe_add⟩
#align ennreal.of_nnreal_hom Ennreal.ofNnrealHom
@[simp]
theorem coe_ofNnrealHom : ⇑of_nnreal_hom = coe :=
rfl
#align ennreal.coe_of_nnreal_hom Ennreal.coe_ofNnrealHom
section Actions
/-- A `mul_action` over `ℝ≥0∞` restricts to a `mul_action` over `ℝ≥0`. -/
noncomputable instance {M : Type _} [MulAction ℝ≥0∞ M] : MulAction ℝ≥0 M :=
MulAction.compHom M ofNnrealHom.toMonoidHom
theorem smul_def {M : Type _} [MulAction ℝ≥0∞ M] (c : ℝ≥0) (x : M) : c • x = (c : ℝ≥0∞) • x :=
rfl
#align ennreal.smul_def Ennreal.smul_def
instance {M N : Type _} [MulAction ℝ≥0∞ M] [MulAction ℝ≥0∞ N] [SMul M N] [IsScalarTower ℝ≥0∞ M N] :
IsScalarTower ℝ≥0 M N where smul_assoc r := (smul_assoc (r : ℝ≥0∞) : _)
instance sMulCommClass_left {M N : Type _} [MulAction ℝ≥0∞ N] [SMul M N] [SMulCommClass ℝ≥0∞ M N] :
SMulCommClass ℝ≥0 M N where smul_comm r := (smul_comm (r : ℝ≥0∞) : _)
#align ennreal.smul_comm_class_left Ennreal.sMulCommClass_left
instance sMulCommClass_right {M N : Type _} [MulAction ℝ≥0∞ N] [SMul M N] [SMulCommClass M ℝ≥0∞ N] :
SMulCommClass M ℝ≥0 N where smul_comm m r := (smul_comm m (r : ℝ≥0∞) : _)
#align ennreal.smul_comm_class_right Ennreal.sMulCommClass_right
/-- A `distrib_mul_action` over `ℝ≥0∞` restricts to a `distrib_mul_action` over `ℝ≥0`. -/
noncomputable instance {M : Type _} [AddMonoid M] [DistribMulAction ℝ≥0∞ M] :
DistribMulAction ℝ≥0 M :=
DistribMulAction.compHom M ofNnrealHom.toMonoidHom
/-- A `module` over `ℝ≥0∞` restricts to a `module` over `ℝ≥0`. -/
noncomputable instance {M : Type _} [AddCommMonoid M] [Module ℝ≥0∞ M] : Module ℝ≥0 M :=
Module.compHom M ofNnrealHom
/-- An `algebra` over `ℝ≥0∞` restricts to an `algebra` over `ℝ≥0`. -/
noncomputable instance {A : Type _} [Semiring A] [Algebra ℝ≥0∞ A] : Algebra ℝ≥0 A
where
smul := (· • ·)
commutes' r x := by simp [Algebra.commutes]
smul_def' r x := by simp [← Algebra.smul_def (r : ℝ≥0∞) x, smul_def]
toRingHom := (algebraMap ℝ≥0∞ A).comp (ofNnrealHom : ℝ≥0 →+* ℝ≥0∞)
-- verify that the above produces instances we might care about
noncomputable example : Algebra ℝ≥0 ℝ≥0∞ :=
inferInstance
noncomputable example : DistribMulAction ℝ≥0ˣ ℝ≥0∞ :=
inferInstance
theorem coe_smul {R} (r : R) (s : ℝ≥0) [SMul R ℝ≥0] [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0 ℝ≥0]
[IsScalarTower R ℝ≥0 ℝ≥0∞] : (↑(r • s) : ℝ≥0∞) = r • ↑s := by
rw [← smul_one_smul ℝ≥0 r (s : ℝ≥0∞), smul_def, smul_eq_mul, ← Ennreal.coe_mul, smul_mul_assoc,
one_mul]
#align ennreal.coe_smul Ennreal.coe_smul
end Actions
@[simp, norm_cast]
theorem coe_indicator {α} (s : Set α) (f : α → ℝ≥0) (a : α) :
((s.indicator f a : ℝ≥0) : ℝ≥0∞) = s.indicator (fun x => f x) a :=
(ofNnrealHom : ℝ≥0 →+ ℝ≥0∞).map_indicator _ _ _
#align ennreal.coe_indicator Ennreal.coe_indicator
@[simp, norm_cast]
theorem coe_pow (n : ℕ) : (↑(r ^ n) : ℝ≥0∞) = r ^ n :=
ofNnrealHom.map_pow r n
#align ennreal.coe_pow Ennreal.coe_pow
@[simp]
theorem add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ :=
WithTop.add_eq_top
#align ennreal.add_eq_top Ennreal.add_eq_top
@[simp]
theorem add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ :=
WithTop.add_lt_top
#align ennreal.add_lt_top Ennreal.add_lt_top
theorem toNnreal_add {r₁ r₂ : ℝ≥0∞} (h₁ : r₁ ≠ ∞) (h₂ : r₂ ≠ ∞) :
(r₁ + r₂).toNnreal = r₁.toNnreal + r₂.toNnreal :=
by
lift r₁ to ℝ≥0 using h₁
lift r₂ to ℝ≥0 using h₂
rfl
#align ennreal.to_nnreal_add Ennreal.toNnreal_add
theorem not_lt_top {x : ℝ≥0∞} : ¬x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not]
#align ennreal.not_lt_top Ennreal.not_lt_top
theorem add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top
#align ennreal.add_ne_top Ennreal.add_ne_top
theorem mul_top : a * ∞ = if a = 0 then 0 else ∞ := by split_ifs; · simp [h];
· exact WithTop.mul_top h
#align ennreal.mul_top Ennreal.mul_top
theorem top_mul : ∞ * a = if a = 0 then 0 else ∞ := by split_ifs; · simp [h];
· exact WithTop.top_mul h
#align ennreal.top_mul Ennreal.top_mul
@[simp]
theorem top_mul_top : ∞ * ∞ = ∞ :=
WithTop.top_mul_top
#align ennreal.top_mul_top Ennreal.top_mul_top
theorem top_pow {n : ℕ} (h : 0 < n) : ∞ ^ n = ∞ :=
Nat.le_induction (pow_one _) (fun m hm hm' => by rw [pow_succ, hm', top_mul_top]) _
(Nat.succ_le_of_lt h)
#align ennreal.top_pow Ennreal.top_pow
theorem mul_eq_top : a * b = ∞ ↔ a ≠ 0 ∧ b = ∞ ∨ a = ∞ ∧ b ≠ 0 :=
WithTop.mul_eq_top_iff
#align ennreal.mul_eq_top Ennreal.mul_eq_top
theorem mul_lt_top : a ≠ ∞ → b ≠ ∞ → a * b < ∞ :=
WithTop.mul_lt_top
#align ennreal.mul_lt_top Ennreal.mul_lt_top
theorem mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using mul_lt_top
#align ennreal.mul_ne_top Ennreal.mul_ne_top
theorem lt_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a < ∞ :=
lt_top_iff_ne_top.2 fun ha => h <| mul_eq_top.2 (Or.inr ⟨ha, hb⟩)
#align ennreal.lt_top_of_mul_ne_top_left Ennreal.lt_top_of_mul_ne_top_left
theorem lt_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b < ∞ :=
lt_top_of_mul_ne_top_left (by rwa [mul_comm]) ha
#align ennreal.lt_top_of_mul_ne_top_right Ennreal.lt_top_of_mul_ne_top_right
theorem mul_lt_top_iff {a b : ℝ≥0∞} : a * b < ∞ ↔ a < ∞ ∧ b < ∞ ∨ a = 0 ∨ b = 0 :=
by
constructor
· intro h
rw [← or_assoc', or_iff_not_imp_right, or_iff_not_imp_right]
intro hb ha
exact ⟨lt_top_of_mul_ne_top_left h.ne hb, lt_top_of_mul_ne_top_right h.ne ha⟩
· rintro (⟨ha, hb⟩ | rfl | rfl) <;> [exact mul_lt_top ha.ne hb.ne, simp, simp]
#align ennreal.mul_lt_top_iff Ennreal.mul_lt_top_iff
theorem mul_self_lt_top_iff {a : ℝ≥0∞} : a * a < ⊤ ↔ a < ⊤ :=
by
rw [Ennreal.mul_lt_top_iff, and_self_iff, or_self_iff, or_iff_left_iff_imp]
rintro rfl
norm_num
#align ennreal.mul_self_lt_top_iff Ennreal.mul_self_lt_top_iff
theorem mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b :=
CanonicallyOrderedCommSemiring.mul_pos
#align ennreal.mul_pos_iff Ennreal.mul_pos_iff
theorem mul_pos (ha : a ≠ 0) (hb : b ≠ 0) : 0 < a * b :=
mul_pos_iff.2 ⟨pos_iff_ne_zero.2 ha, pos_iff_ne_zero.2 hb⟩
#align ennreal.mul_pos Ennreal.mul_pos
@[simp]
theorem pow_eq_top_iff {n : ℕ} : a ^ n = ∞ ↔ a = ∞ ∧ n ≠ 0 :=
by
induction' n with n ihn; · simp
rw [pow_succ, mul_eq_top, ihn]
fconstructor
· rintro (⟨-, rfl, h0⟩ | ⟨rfl, h0⟩) <;> exact ⟨rfl, n.succ_ne_zero⟩
· rintro ⟨rfl, -⟩
exact Or.inr ⟨rfl, pow_ne_zero n top_ne_zero⟩
#align ennreal.pow_eq_top_iff Ennreal.pow_eq_top_iff
theorem pow_eq_top (n : ℕ) (h : a ^ n = ∞) : a = ∞ :=
(pow_eq_top_iff.1 h).1
#align ennreal.pow_eq_top Ennreal.pow_eq_top
theorem pow_ne_top (h : a ≠ ∞) {n : ℕ} : a ^ n ≠ ∞ :=
mt (pow_eq_top n) h
#align ennreal.pow_ne_top Ennreal.pow_ne_top
theorem pow_lt_top : a < ∞ → ∀ n : ℕ, a ^ n < ∞ := by
simpa only [lt_top_iff_ne_top] using pow_ne_top
#align ennreal.pow_lt_top Ennreal.pow_lt_top
@[simp, norm_cast]
theorem coe_finset_sum {s : Finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = (∑ a in s, f a : ℝ≥0∞) :=
ofNnrealHom.map_sum f s
#align ennreal.coe_finset_sum Ennreal.coe_finset_sum
@[simp, norm_cast]
theorem coe_finset_prod {s : Finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = (∏ a in s, f a : ℝ≥0∞) :=
ofNnrealHom.map_prod f s
#align ennreal.coe_finset_prod Ennreal.coe_finset_prod
section Order
@[simp]
theorem bot_eq_zero : (⊥ : ℝ≥0∞) = 0 :=
rfl
#align ennreal.bot_eq_zero Ennreal.bot_eq_zero
@[simp]
theorem coe_lt_top : coe r < ∞ :=
WithTop.coe_lt_top r
#align ennreal.coe_lt_top Ennreal.coe_lt_top
@[simp]
theorem not_top_le_coe : ¬∞ ≤ ↑r :=
WithTop.not_top_le_coe r
#align ennreal.not_top_le_coe Ennreal.not_top_le_coe
@[simp, norm_cast]
theorem one_le_coe_iff : (1 : ℝ≥0∞) ≤ ↑r ↔ 1 ≤ r :=
coe_le_coe
#align ennreal.one_le_coe_iff Ennreal.one_le_coe_iff
@[simp, norm_cast]
theorem coe_le_one_iff : ↑r ≤ (1 : ℝ≥0∞) ↔ r ≤ 1 :=
coe_le_coe
#align ennreal.coe_le_one_iff Ennreal.coe_le_one_iff
@[simp, norm_cast]
theorem coe_lt_one_iff : (↑p : ℝ≥0∞) < 1 ↔ p < 1 :=
coe_lt_coe
#align ennreal.coe_lt_one_iff Ennreal.coe_lt_one_iff
@[simp, norm_cast]
theorem one_lt_coe_iff : 1 < (↑p : ℝ≥0∞) ↔ 1 < p :=
coe_lt_coe
#align ennreal.one_lt_coe_iff Ennreal.one_lt_coe_iff
@[simp, norm_cast]
theorem coe_nat (n : ℕ) : ((n : ℝ≥0) : ℝ≥0∞) = n :=
WithTop.coe_nat n
#align ennreal.coe_nat Ennreal.coe_nat
@[simp]
theorem ofReal_coe_nat (n : ℕ) : Ennreal.ofReal n = n := by simp [Ennreal.ofReal]
#align ennreal.of_real_coe_nat Ennreal.ofReal_coe_nat
@[simp]
theorem nat_ne_top (n : ℕ) : (n : ℝ≥0∞) ≠ ∞ :=
WithTop.nat_ne_top n
#align ennreal.nat_ne_top Ennreal.nat_ne_top
@[simp]
theorem top_ne_nat (n : ℕ) : ∞ ≠ n :=
WithTop.top_ne_nat n
#align ennreal.top_ne_nat Ennreal.top_ne_nat
@[simp]
theorem one_lt_top : 1 < ∞ :=
coe_lt_top
#align ennreal.one_lt_top Ennreal.one_lt_top
@[simp, norm_cast]
theorem toNnreal_nat (n : ℕ) : (n : ℝ≥0∞).toNnreal = n := by
conv_lhs => rw [← Ennreal.coe_nat n, Ennreal.toNnreal_coe]
#align ennreal.to_nnreal_nat Ennreal.toNnreal_nat
@[simp, norm_cast]
theorem toReal_nat (n : ℕ) : (n : ℝ≥0∞).toReal = n := by
conv_lhs => rw [← Ennreal.ofReal_coe_nat n, Ennreal.toReal_ofReal (Nat.cast_nonneg _)]
#align ennreal.to_real_nat Ennreal.toReal_nat
theorem le_coe_iff : a ≤ ↑r ↔ ∃ p : ℝ≥0, a = p ∧ p ≤ r :=
WithTop.le_coe_iff
#align ennreal.le_coe_iff Ennreal.le_coe_iff
theorem coe_le_iff : ↑r ≤ a ↔ ∀ p : ℝ≥0, a = p → r ≤ p :=
WithTop.coe_le_iff
#align ennreal.coe_le_iff Ennreal.coe_le_iff
theorem lt_iff_exists_coe : a < b ↔ ∃ p : ℝ≥0, a = p ∧ ↑p < b :=
WithTop.lt_iff_exists_coe
#align ennreal.lt_iff_exists_coe Ennreal.lt_iff_exists_coe
theorem toReal_le_coe_of_le_coe {a : ℝ≥0∞} {b : ℝ≥0} (h : a ≤ b) : a.toReal ≤ b :=
show ↑a.toNnreal ≤ ↑b
by
have : ↑a.to_nnreal = a := Ennreal.coe_toNnreal (lt_of_le_of_lt h coe_lt_top).Ne
rw [← this] at h
exact_mod_cast h
#align ennreal.to_real_le_coe_of_le_coe Ennreal.toReal_le_coe_of_le_coe
@[simp, norm_cast]
theorem coe_finset_sup {s : Finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup fun x => (f x : ℝ≥0∞) :=
Finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl
#align ennreal.coe_finset_sup Ennreal.coe_finset_sup
theorem pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
by
cases a
· cases m
· rw [eq_bot_iff.mpr h]
exact le_rfl
· rw [none_eq_top, top_pow (Nat.succ_pos m)]
exact le_top
· rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe]
exact pow_le_pow (by simpa using ha) h
#align ennreal.pow_le_pow Ennreal.pow_le_pow
theorem one_le_pow_of_one_le (ha : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by
simpa using pow_le_pow ha (zero_le n)
#align ennreal.one_le_pow_of_one_le Ennreal.one_le_pow_of_one_le
@[simp]
theorem max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by
simp only [nonpos_iff_eq_zero.symm, max_le_iff]
#align ennreal.max_eq_zero_iff Ennreal.max_eq_zero_iff
@[simp]
theorem max_zero_left : max 0 a = a :=
max_eq_right (zero_le a)
#align ennreal.max_zero_left Ennreal.max_zero_left
@[simp]
theorem max_zero_right : max a 0 = a :=
max_eq_left (zero_le a)
#align ennreal.max_zero_right Ennreal.max_zero_right
@[simp]
theorem sup_eq_max : a ⊔ b = max a b :=
rfl
#align ennreal.sup_eq_max Ennreal.sup_eq_max
protected theorem pow_pos : 0 < a → ∀ n : ℕ, 0 < a ^ n :=
CanonicallyOrderedCommSemiring.pow_pos
#align ennreal.pow_pos Ennreal.pow_pos
protected theorem pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a ^ n ≠ 0 := by
simpa only [pos_iff_ne_zero] using Ennreal.pow_pos
#align ennreal.pow_ne_zero Ennreal.pow_ne_zero
@[simp]
theorem not_lt_zero : ¬a < 0 := by simp
#align ennreal.not_lt_zero Ennreal.not_lt_zero
protected theorem le_of_add_le_add_left : a ≠ ∞ → a + b ≤ a + c → b ≤ c :=
WithTop.le_of_add_le_add_left
#align ennreal.le_of_add_le_add_left Ennreal.le_of_add_le_add_left
protected theorem le_of_add_le_add_right : a ≠ ∞ → b + a ≤ c + a → b ≤ c :=
WithTop.le_of_add_le_add_right
#align ennreal.le_of_add_le_add_right Ennreal.le_of_add_le_add_right
protected theorem add_lt_add_left : a ≠ ∞ → b < c → a + b < a + c :=
WithTop.add_lt_add_left
#align ennreal.add_lt_add_left Ennreal.add_lt_add_left
protected theorem add_lt_add_right : a ≠ ∞ → b < c → b + a < c + a :=
WithTop.add_lt_add_right
#align ennreal.add_lt_add_right Ennreal.add_lt_add_right
protected theorem add_le_add_iff_left : a ≠ ∞ → (a + b ≤ a + c ↔ b ≤ c) :=
WithTop.add_le_add_iff_left
#align ennreal.add_le_add_iff_left Ennreal.add_le_add_iff_left
protected theorem add_le_add_iff_right : a ≠ ∞ → (b + a ≤ c + a ↔ b ≤ c) :=
WithTop.add_le_add_iff_right
#align ennreal.add_le_add_iff_right Ennreal.add_le_add_iff_right
protected theorem add_lt_add_iff_left : a ≠ ∞ → (a + b < a + c ↔ b < c) :=
WithTop.add_lt_add_iff_left
#align ennreal.add_lt_add_iff_left Ennreal.add_lt_add_iff_left
protected theorem add_lt_add_iff_right : a ≠ ∞ → (b + a < c + a ↔ b < c) :=
WithTop.add_lt_add_iff_right
#align ennreal.add_lt_add_iff_right Ennreal.add_lt_add_iff_right
protected theorem add_lt_add_of_le_of_lt : a ≠ ∞ → a ≤ b → c < d → a + c < b + d :=
WithTop.add_lt_add_of_le_of_lt
#align ennreal.add_lt_add_of_le_of_lt Ennreal.add_lt_add_of_le_of_lt
protected theorem add_lt_add_of_lt_of_le : c ≠ ∞ → a < b → c ≤ d → a + c < b + d :=
WithTop.add_lt_add_of_lt_of_le
#align ennreal.add_lt_add_of_lt_of_le Ennreal.add_lt_add_of_lt_of_le
instance contravariantClass_add_lt : ContravariantClass ℝ≥0∞ ℝ≥0∞ (· + ·) (· < ·) :=
WithTop.contravariantClass_add_lt
#align ennreal.contravariant_class_add_lt Ennreal.contravariantClass_add_lt
theorem lt_add_right (ha : a ≠ ∞) (hb : b ≠ 0) : a < a + b := by
rwa [← pos_iff_ne_zero, ← Ennreal.add_lt_add_iff_left ha, add_zero] at hb
#align ennreal.lt_add_right Ennreal.lt_add_right
theorem le_of_forall_pos_le_add : ∀ {a b : ℝ≥0∞}, (∀ ε : ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b
| a, none, h => le_top
| none, some a, h =>
by
have : ∞ ≤ ↑a + ↑(1 : ℝ≥0) := h 1 zero_lt_one coe_lt_top
rw [← coe_add] at this <;> exact (not_top_le_coe this).elim
| some a, some b, h => by
simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_imp_iff] at
* <;>
exact Nnreal.le_of_forall_pos_le_add h
#align ennreal.le_of_forall_pos_le_add Ennreal.le_of_forall_pos_le_add
theorem lt_iff_exists_rat_btwn :
a < b ↔ ∃ q : ℚ, 0 ≤ q ∧ a < Real.toNnreal q ∧ (Real.toNnreal q : ℝ≥0∞) < b :=
⟨fun h => by
rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩
rcases exists_between h with ⟨c, pc, cb⟩
rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩
rcases(Nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩
exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩, fun ⟨q, q0, qa, qb⟩ =>
lt_trans qa qb⟩
#align ennreal.lt_iff_exists_rat_btwn Ennreal.lt_iff_exists_rat_btwn
theorem lt_iff_exists_real_btwn :
a < b ↔ ∃ r : ℝ, 0 ≤ r ∧ a < Ennreal.ofReal r ∧ (Ennreal.ofReal r : ℝ≥0∞) < b :=
⟨fun h =>
let ⟨q, q0, aq, qb⟩ := Ennreal.lt_iff_exists_rat_btwn.1 h
⟨q, Rat.cast_nonneg.2 q0, aq, qb⟩,
fun ⟨q, q0, qa, qb⟩ => lt_trans qa qb⟩
#align ennreal.lt_iff_exists_real_btwn Ennreal.lt_iff_exists_real_btwn
theorem lt_iff_exists_nnreal_btwn : a < b ↔ ∃ r : ℝ≥0, a < r ∧ (r : ℝ≥0∞) < b :=
WithTop.lt_iff_exists_coe_btwn
#align ennreal.lt_iff_exists_nnreal_btwn Ennreal.lt_iff_exists_nnreal_btwn
theorem lt_iff_exists_add_pos_lt : a < b ↔ ∃ r : ℝ≥0, 0 < r ∧ a + r < b :=
by
refine' ⟨fun hab => _, fun ⟨r, rpos, hr⟩ => lt_of_le_of_lt le_self_add hr⟩
cases a
· simpa using hab
rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩
let d : ℝ≥0 := ⟨c, c_nonneg⟩
have ad : a < d := by
rw [of_real_eq_coe_nnreal c_nonneg] at ac
exact coe_lt_coe.1 ac
refine' ⟨d - a, tsub_pos_iff_lt.2 ad, _⟩
rw [some_eq_coe, ← coe_add]
convert cb
have : Real.toNnreal c = d :=
by
rw [← Nnreal.coe_eq, Real.coe_toNnreal _ c_nonneg]
rfl
rw [add_comm, this]
exact tsub_add_cancel_of_le ad.le
#align ennreal.lt_iff_exists_add_pos_lt Ennreal.lt_iff_exists_add_pos_lt
theorem coe_nat_lt_coe {n : ℕ} : (n : ℝ≥0∞) < r ↔ ↑n < r :=
Ennreal.coe_nat n ▸ coe_lt_coe
#align ennreal.coe_nat_lt_coe Ennreal.coe_nat_lt_coe
theorem coe_lt_coe_nat {n : ℕ} : (r : ℝ≥0∞) < n ↔ r < n :=
Ennreal.coe_nat n ▸ coe_lt_coe
#align ennreal.coe_lt_coe_nat Ennreal.coe_lt_coe_nat
@[simp, norm_cast]
theorem coe_nat_lt_coe_nat {m n : ℕ} : (m : ℝ≥0∞) < n ↔ m < n :=
Ennreal.coe_nat n ▸ coe_nat_lt_coe.trans Nat.cast_lt
#align ennreal.coe_nat_lt_coe_nat Ennreal.coe_nat_lt_coe_nat
theorem coe_nat_mono : StrictMono (coe : ℕ → ℝ≥0∞) := fun _ _ => coe_nat_lt_coe_nat.2
#align ennreal.coe_nat_mono Ennreal.coe_nat_mono
@[simp, norm_cast]
theorem coe_nat_le_coe_nat {m n : ℕ} : (m : ℝ≥0∞) ≤ n ↔ m ≤ n :=
coe_nat_mono.le_iff_le
#align ennreal.coe_nat_le_coe_nat Ennreal.coe_nat_le_coe_nat
instance : CharZero ℝ≥0∞ :=
⟨coe_nat_mono.Injective⟩
protected theorem exists_nat_gt {r : ℝ≥0∞} (h : r ≠ ∞) : ∃ n : ℕ, r < n :=
by
lift r to ℝ≥0 using h
rcases exists_nat_gt r with ⟨n, hn⟩
exact ⟨n, coe_lt_coe_nat.2 hn⟩
#align ennreal.exists_nat_gt Ennreal.exists_nat_gt
@[simp]
theorem unionᵢ_iio_coe_nat : (⋃ n : ℕ, Iio (n : ℝ≥0∞)) = {∞}ᶜ :=
by
ext x
rw [mem_Union]
exact ⟨fun ⟨n, hn⟩ => ne_top_of_lt hn, Ennreal.exists_nat_gt⟩
#align ennreal.Union_Iio_coe_nat Ennreal.unionᵢ_iio_coe_nat
@[simp]
theorem unionᵢ_iic_coe_nat : (⋃ n : ℕ, Iic (n : ℝ≥0∞)) = {∞}ᶜ :=
Subset.antisymm (Union_subset fun n x hx => ne_top_of_le_ne_top (nat_ne_top n) hx) <|
Union_Iio_coe_nat ▸ unionᵢ_mono fun n => Iio_subset_Iic_self
#align ennreal.Union_Iic_coe_nat Ennreal.unionᵢ_iic_coe_nat
@[simp]
theorem unionᵢ_ioc_coe_nat : (⋃ n : ℕ, Ioc a n) = Ioi a \ {∞} := by
simp only [← Ioi_inter_Iic, ← inter_Union, Union_Iic_coe_nat, diff_eq]
#align ennreal.Union_Ioc_coe_nat Ennreal.unionᵢ_ioc_coe_nat
@[simp]
theorem unionᵢ_ioo_coe_nat : (⋃ n : ℕ, Ioo a n) = Ioi a \ {∞} := by
simp only [← Ioi_inter_Iio, ← inter_Union, Union_Iio_coe_nat, diff_eq]
#align ennreal.Union_Ioo_coe_nat Ennreal.unionᵢ_ioo_coe_nat
@[simp]
theorem unionᵢ_icc_coe_nat : (⋃ n : ℕ, Icc a n) = Ici a \ {∞} := by
simp only [← Ici_inter_Iic, ← inter_Union, Union_Iic_coe_nat, diff_eq]
#align ennreal.Union_Icc_coe_nat Ennreal.unionᵢ_icc_coe_nat
@[simp]
theorem unionᵢ_ico_coe_nat : (⋃ n : ℕ, Ico a n) = Ici a \ {∞} := by
simp only [← Ici_inter_Iio, ← inter_Union, Union_Iio_coe_nat, diff_eq]
#align ennreal.Union_Ico_coe_nat Ennreal.unionᵢ_ico_coe_nat
@[simp]
theorem interᵢ_ici_coe_nat : (⋂ n : ℕ, Ici (n : ℝ≥0∞)) = {∞} := by
simp only [← compl_Iio, ← compl_Union, Union_Iio_coe_nat, compl_compl]
#align ennreal.Inter_Ici_coe_nat Ennreal.interᵢ_ici_coe_nat
@[simp]
theorem interᵢ_ioi_coe_nat : (⋂ n : ℕ, Ioi (n : ℝ≥0∞)) = {∞} := by
simp only [← compl_Iic, ← compl_Union, Union_Iic_coe_nat, compl_compl]
#align ennreal.Inter_Ioi_coe_nat Ennreal.interᵢ_ioi_coe_nat
theorem add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d :=
by
lift a to ℝ≥0 using ne_top_of_lt ac
lift b to ℝ≥0 using ne_top_of_lt bd
cases c; · simp; cases d; · simp
simp only [← coe_add, some_eq_coe, coe_lt_coe] at *
exact add_lt_add ac bd
#align ennreal.add_lt_add Ennreal.add_lt_add
@[norm_cast]
theorem coe_min : ((min r p : ℝ≥0) : ℝ≥0∞) = min r p :=
coe_mono.map_min
#align ennreal.coe_min Ennreal.coe_min
@[norm_cast]
theorem coe_max : ((max r p : ℝ≥0) : ℝ≥0∞) = max r p :=
coe_mono.map_max
#align ennreal.coe_max Ennreal.coe_max
theorem le_of_top_imp_top_of_toNnreal_le {a b : ℝ≥0∞} (h : a = ⊤ → b = ⊤)
(h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.toNnreal ≤ b.toNnreal) : a ≤ b :=
by
by_cases ha : a = ⊤
· rw [h ha]
exact le_top
by_cases hb : b = ⊤
· rw [hb]
exact le_top
rw [← coe_to_nnreal hb, ← coe_to_nnreal ha, coe_le_coe]
exact h_nnreal ha hb
#align ennreal.le_of_top_imp_top_of_to_nnreal_le Ennreal.le_of_top_imp_top_of_toNnreal_le
end Order
section CompleteLattice
theorem coe_supₛ {s : Set ℝ≥0} : BddAbove s → (↑(supₛ s) : ℝ≥0∞) = ⨆ a ∈ s, ↑a :=
WithTop.coe_supₛ
#align ennreal.coe_Sup Ennreal.coe_supₛ
theorem coe_infₛ {s : Set ℝ≥0} : s.Nonempty → (↑(infₛ s) : ℝ≥0∞) = ⨅ a ∈ s, ↑a :=
WithTop.coe_infₛ
#align ennreal.coe_Inf Ennreal.coe_infₛ
@[simp]
theorem top_mem_upperBounds {s : Set ℝ≥0∞} : ∞ ∈ upperBounds s := fun x hx => le_top
#align ennreal.top_mem_upper_bounds Ennreal.top_mem_upperBounds
theorem coe_mem_upperBounds {s : Set ℝ≥0} :
↑r ∈ upperBounds ((coe : ℝ≥0 → ℝ≥0∞) '' s) ↔ r ∈ upperBounds s := by
simp (config := { contextual := true }) [upperBounds, ball_image_iff, -mem_image, *]
#align ennreal.coe_mem_upper_bounds Ennreal.coe_mem_upperBounds
end CompleteLattice
section Mul
@[mono]
theorem mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d :=
mul_le_mul'
#align ennreal.mul_le_mul Ennreal.mul_le_mul
@[mono]
theorem mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d :=
by
rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩
lift a to ℝ≥0 using ne_top_of_lt aa'
rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩
lift b to ℝ≥0 using ne_top_of_lt bb'
norm_cast at *
calc
↑(a * b) < ↑(a' * b') :=
coe_lt_coe.2 (mul_lt_mul' aa'.le bb' (zero_le _) ((zero_le a).trans_lt aa'))
_ = ↑a' * ↑b' := coe_mul
_ ≤ c * d := mul_le_mul a'c.le b'd.le
#align ennreal.mul_lt_mul Ennreal.mul_lt_mul
theorem mul_left_mono : Monotone ((· * ·) a) := fun b c => mul_le_mul le_rfl
#align ennreal.mul_left_mono Ennreal.mul_left_mono
theorem mul_right_mono : Monotone fun x => x * a := fun b c h => mul_le_mul h le_rfl
#align ennreal.mul_right_mono Ennreal.mul_right_mono
theorem pow_strictMono {n : ℕ} (hn : n ≠ 0) : StrictMono fun x : ℝ≥0∞ => x ^ n :=
by
intro x y hxy
obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hn
induction' n with n IH
· simp only [hxy, pow_one]
· simp only [pow_succ _ n.succ, mul_lt_mul hxy (IH (Nat.succ_pos _).ne')]
#align ennreal.pow_strict_mono Ennreal.pow_strictMono
theorem max_mul : max a b * c = max (a * c) (b * c) :=
mul_right_mono.map_max
#align ennreal.max_mul Ennreal.max_mul
theorem mul_max : a * max b c = max (a * b) (a * c) :=
mul_left_mono.map_max
#align ennreal.mul_max Ennreal.mul_max
theorem mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) := by
cases a <;> cases b <;> cases c <;>
simp (config := { contextual := true }) [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul,
coe_mul.symm, Nnreal.mul_eq_mul_left]
#align ennreal.mul_eq_mul_left Ennreal.mul_eq_mul_left
theorem mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) :=
mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left
#align ennreal.mul_eq_mul_right Ennreal.mul_eq_mul_right
theorem mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) :=
by
cases a <;> cases b <;> cases c <;>
simp (config := { contextual := true }) [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul,
coe_mul.symm]
intro h; exact mul_le_mul_left (pos_iff_ne_zero.2 h)
#align ennreal.mul_le_mul_left Ennreal.mul_le_mul_left
theorem mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) :=
mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left
#align ennreal.mul_le_mul_right Ennreal.mul_le_mul_right
theorem mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) := fun h0 ht => by
simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le]
#align ennreal.mul_lt_mul_left Ennreal.mul_lt_mul_left
theorem mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) :=
mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left
#align ennreal.mul_lt_mul_right Ennreal.mul_lt_mul_right
end Mul
section Cancel
/-- An element `a` is `add_le_cancellable` if `a + b ≤ a + c` implies `b ≤ c` for all `b` and `c`.
This is true in `ℝ≥0∞` for all elements except `∞`. -/
theorem addLECancellable_iff_ne {a : ℝ≥0∞} : AddLECancellable a ↔ a ≠ ∞ :=
by
constructor
· rintro h rfl
refine' zero_lt_one.not_le (h _)
simp
· rintro h b c hbc
apply Ennreal.le_of_add_le_add_left h hbc
#align ennreal.add_le_cancellable_iff_ne Ennreal.addLECancellable_iff_ne
/-- This lemma has an abbreviated name because it is used frequently. -/
theorem cancel_of_ne {a : ℝ≥0∞} (h : a ≠ ∞) : AddLECancellable a :=
addLECancellable_iff_ne.mpr h
#align ennreal.cancel_of_ne Ennreal.cancel_of_ne
/-- This lemma has an abbreviated name because it is used frequently. -/
theorem cancel_of_lt {a : ℝ≥0∞} (h : a < ∞) : AddLECancellable a :=
cancel_of_ne h.Ne
#align ennreal.cancel_of_lt Ennreal.cancel_of_lt
/-- This lemma has an abbreviated name because it is used frequently. -/
theorem cancel_of_lt' {a b : ℝ≥0∞} (h : a < b) : AddLECancellable a :=
cancel_of_ne h.ne_top
#align ennreal.cancel_of_lt' Ennreal.cancel_of_lt'
/-- This lemma has an abbreviated name because it is used frequently. -/
theorem cancel_coe {a : ℝ≥0} : AddLECancellable (a : ℝ≥0∞) :=
cancel_of_ne coe_ne_top
#align ennreal.cancel_coe Ennreal.cancel_coe
theorem add_right_inj (h : a ≠ ∞) : a + b = a + c ↔ b = c :=
(cancel_of_ne h).inj
#align ennreal.add_right_inj Ennreal.add_right_inj
theorem add_left_inj (h : a ≠ ∞) : b + a = c + a ↔ b = c :=
(cancel_of_ne h).inj_left
#align ennreal.add_left_inj Ennreal.add_left_inj
end Cancel
section Sub
theorem sub_eq_infₛ {a b : ℝ≥0∞} : a - b = infₛ { d | a ≤ d + b } :=
le_antisymm (le_infₛ fun c => tsub_le_iff_right.mpr) <| infₛ_le le_tsub_add
#align ennreal.sub_eq_Inf Ennreal.sub_eq_infₛ
/-- This is a special case of `with_top.coe_sub` in the `ennreal` namespace -/
theorem coe_sub : (↑(r - p) : ℝ≥0∞) = ↑r - ↑p :=
WithTop.coe_sub
#align ennreal.coe_sub Ennreal.coe_sub
/-- This is a special case of `with_top.top_sub_coe` in the `ennreal` namespace -/
theorem top_sub_coe : ∞ - ↑r = ∞ :=
WithTop.top_sub_coe
#align ennreal.top_sub_coe Ennreal.top_sub_coe
/-- This is a special case of `with_top.sub_top` in the `ennreal` namespace -/
theorem sub_top : a - ∞ = 0 :=
WithTop.sub_top
#align ennreal.sub_top Ennreal.sub_top
theorem sub_eq_top_iff : a - b = ∞ ↔ a = ∞ ∧ b ≠ ∞ := by
cases a <;> cases b <;> simp [← WithTop.coe_sub]
#align ennreal.sub_eq_top_iff Ennreal.sub_eq_top_iff
theorem sub_ne_top (ha : a ≠ ∞) : a - b ≠ ∞ :=
mt sub_eq_top_iff.mp <| mt And.left ha
#align ennreal.sub_ne_top Ennreal.sub_ne_top
@[simp, norm_cast]
theorem nat_cast_sub (m n : ℕ) : ↑(m - n) = (m - n : ℝ≥0∞) := by
rw [← coe_nat, Nat.cast_tsub, coe_sub, coe_nat, coe_nat]
#align ennreal.nat_cast_sub Ennreal.nat_cast_sub
protected theorem sub_eq_of_eq_add (hb : b ≠ ∞) : a = c + b → a - b = c :=
(cancel_of_ne hb).tsub_eq_of_eq_add
#align ennreal.sub_eq_of_eq_add Ennreal.sub_eq_of_eq_add
protected theorem eq_sub_of_add_eq (hc : c ≠ ∞) : a + c = b → a = b - c :=
(cancel_of_ne hc).eq_tsub_of_add_eq
#align ennreal.eq_sub_of_add_eq Ennreal.eq_sub_of_add_eq
protected theorem sub_eq_of_eq_add_rev (hb : b ≠ ∞) : a = b + c → a - b = c :=
(cancel_of_ne hb).tsub_eq_of_eq_add_rev
#align ennreal.sub_eq_of_eq_add_rev Ennreal.sub_eq_of_eq_add_rev
theorem sub_eq_of_add_eq (hb : b ≠ ∞) (hc : a + b = c) : c - b = a :=
Ennreal.sub_eq_of_eq_add hb hc.symm
#align ennreal.sub_eq_of_add_eq Ennreal.sub_eq_of_add_eq
@[simp]
protected theorem add_sub_cancel_left (ha : a ≠ ∞) : a + b - a = b :=
(cancel_of_ne ha).add_tsub_cancel_left
#align ennreal.add_sub_cancel_left Ennreal.add_sub_cancel_left
@[simp]
protected theorem add_sub_cancel_right (hb : b ≠ ∞) : a + b - b = a :=
(cancel_of_ne hb).add_tsub_cancel_right
#align ennreal.add_sub_cancel_right Ennreal.add_sub_cancel_right
protected theorem lt_add_of_sub_lt_left (h : a ≠ ∞ ∨ b ≠ ∞) : a - b < c → a < b + c :=
by
obtain rfl | hb := eq_or_ne b ∞
· rw [top_add, lt_top_iff_ne_top]
exact fun _ => h.resolve_right (not_not.2 rfl)
· exact (cancel_of_ne hb).lt_add_of_tsub_lt_left
#align ennreal.lt_add_of_sub_lt_left Ennreal.lt_add_of_sub_lt_left
protected theorem lt_add_of_sub_lt_right (h : a ≠ ∞ ∨ c ≠ ∞) : a - c < b → a < b + c :=
add_comm c b ▸ Ennreal.lt_add_of_sub_lt_left h
#align ennreal.lt_add_of_sub_lt_right Ennreal.lt_add_of_sub_lt_right
theorem le_sub_of_add_le_left (ha : a ≠ ∞) : a + b ≤ c → b ≤ c - a :=
(cancel_of_ne ha).le_tsub_of_add_le_left
#align ennreal.le_sub_of_add_le_left Ennreal.le_sub_of_add_le_left
theorem le_sub_of_add_le_right (hb : b ≠ ∞) : a + b ≤ c → a ≤ c - b :=
(cancel_of_ne hb).le_tsub_of_add_le_right
#align ennreal.le_sub_of_add_le_right Ennreal.le_sub_of_add_le_right
protected theorem sub_lt_of_lt_add (hac : c ≤ a) (h : a < b + c) : a - c < b :=
((cancel_of_lt' <| hac.trans_lt h).tsub_lt_iff_right hac).mpr h
#align ennreal.sub_lt_of_lt_add Ennreal.sub_lt_of_lt_add
protected theorem sub_lt_iff_lt_right (hb : b ≠ ∞) (hab : b ≤ a) : a - b < c ↔ a < c + b :=
(cancel_of_ne hb).tsub_lt_iff_right hab
#align ennreal.sub_lt_iff_lt_right Ennreal.sub_lt_iff_lt_right
protected theorem sub_lt_self (ha : a ≠ ∞) (ha₀ : a ≠ 0) (hb : b ≠ 0) : a - b < a :=
(cancel_of_ne ha).tsub_lt_self (pos_iff_ne_zero.2 ha₀) (pos_iff_ne_zero.2 hb)
#align ennreal.sub_lt_self Ennreal.sub_lt_self
protected theorem sub_lt_self_iff (ha : a ≠ ∞) : a - b < a ↔ 0 < a ∧ 0 < b :=
(cancel_of_ne ha).tsub_lt_self_iff
#align ennreal.sub_lt_self_iff Ennreal.sub_lt_self_iff
theorem sub_lt_of_sub_lt (h₂ : c ≤ a) (h₃ : a ≠ ∞ ∨ b ≠ ∞) (h₁ : a - b < c) : a - c < b :=
Ennreal.sub_lt_of_lt_add h₂ (add_comm c b ▸ Ennreal.lt_add_of_sub_lt_right h₃ h₁)
#align ennreal.sub_lt_of_sub_lt Ennreal.sub_lt_of_sub_lt
theorem sub_sub_cancel (h : a ≠ ∞) (h2 : b ≤ a) : a - (a - b) = b :=
(cancel_of_ne <| sub_ne_top h).tsub_tsub_cancel_of_le h2
#align ennreal.sub_sub_cancel Ennreal.sub_sub_cancel
theorem sub_right_inj {a b c : ℝ≥0∞} (ha : a ≠ ∞) (hb : b ≤ a) (hc : c ≤ a) :
a - b = a - c ↔ b = c :=
(cancel_of_ne ha).tsub_right_inj (cancel_of_ne <| ne_top_of_le_ne_top ha hb)
(cancel_of_ne <| ne_top_of_le_ne_top ha hc) hb hc
#align ennreal.sub_right_inj Ennreal.sub_right_inj
theorem sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c :=
by
cases' le_or_lt a b with hab hab; · simp [hab, mul_right_mono hab]
rcases eq_or_lt_of_le (zero_le b) with (rfl | hb); · simp
exact (cancel_of_ne <| mul_ne_top hab.ne_top (h hb hab)).tsub_mul
#align ennreal.sub_mul Ennreal.sub_mul
theorem mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c :=
by
simp only [mul_comm a]
exact sub_mul h
#align ennreal.mul_sub Ennreal.mul_sub
end Sub
section Sum
open Finset
/-- A product of finite numbers is still finite -/
theorem prod_lt_top {s : Finset α} {f : α → ℝ≥0∞} (h : ∀ a ∈ s, f a ≠ ∞) : (∏ a in s, f a) < ∞ :=
WithTop.prod_lt_top h
#align ennreal.prod_lt_top Ennreal.prod_lt_top
/-- A sum of finite numbers is still finite -/
theorem sum_lt_top {s : Finset α} {f : α → ℝ≥0∞} (h : ∀ a ∈ s, f a ≠ ∞) : (∑ a in s, f a) < ∞ :=
WithTop.sum_lt_top h
#align ennreal.sum_lt_top Ennreal.sum_lt_top
/-- A sum of finite numbers is still finite -/
theorem sum_lt_top_iff {s : Finset α} {f : α → ℝ≥0∞} : (∑ a in s, f a) < ∞ ↔ ∀ a ∈ s, f a < ∞ :=
WithTop.sum_lt_top_iff
#align ennreal.sum_lt_top_iff Ennreal.sum_lt_top_iff
/-- A sum of numbers is infinite iff one of them is infinite -/
theorem sum_eq_top_iff {s : Finset α} {f : α → ℝ≥0∞} : (∑ x in s, f x) = ∞ ↔ ∃ a ∈ s, f a = ∞ :=
WithTop.sum_eq_top_iff
#align ennreal.sum_eq_top_iff Ennreal.sum_eq_top_iff
theorem lt_top_of_sum_ne_top {s : Finset α} {f : α → ℝ≥0∞} (h : (∑ x in s, f x) ≠ ∞) {a : α}
(ha : a ∈ s) : f a < ∞ :=
sum_lt_top_iff.1 h.lt_top a ha
#align ennreal.lt_top_of_sum_ne_top Ennreal.lt_top_of_sum_ne_top
/-- seeing `ℝ≥0∞` as `ℝ≥0` does not change their sum, unless one of the `ℝ≥0∞` is
infinity -/
theorem toNnreal_sum {s : Finset α} {f : α → ℝ≥0∞} (hf : ∀ a ∈ s, f a ≠ ∞) :
Ennreal.toNnreal (∑ a in s, f a) = ∑ a in s, Ennreal.toNnreal (f a) :=
by
rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr rfl]
· intro x hx
exact (coe_to_nnreal (hf x hx)).symm
· exact (sum_lt_top hf).Ne
#align ennreal.to_nnreal_sum Ennreal.toNnreal_sum
/-- seeing `ℝ≥0∞` as `real` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/
theorem toReal_sum {s : Finset α} {f : α → ℝ≥0∞} (hf : ∀ a ∈ s, f a ≠ ∞) :
Ennreal.toReal (∑ a in s, f a) = ∑ a in s, Ennreal.toReal (f a) :=
by
rw [Ennreal.toReal, to_nnreal_sum hf, Nnreal.coe_sum]
rfl
#align ennreal.to_real_sum Ennreal.toReal_sum
theorem ofReal_sum_of_nonneg {s : Finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) :
Ennreal.ofReal (∑ i in s, f i) = ∑ i in s, Ennreal.ofReal (f i) :=
by
simp_rw [Ennreal.ofReal, ← coe_finset_sum, coe_eq_coe]
exact Real.toNnreal_sum_of_nonneg hf
#align ennreal.of_real_sum_of_nonneg Ennreal.ofReal_sum_of_nonneg
theorem sum_lt_sum_of_nonempty {s : Finset α} (hs : s.Nonempty) {f g : α → ℝ≥0∞}
(Hlt : ∀ i ∈ s, f i < g i) : (∑ i in s, f i) < ∑ i in s, g i :=
by
induction' hs using Finset.Nonempty.cons_induction with a a s as hs IH
· simp [Hlt _ (Finset.mem_singleton_self _)]
· simp only [as, Finset.sum_cons, not_false_iff]
exact
Ennreal.add_lt_add (Hlt _ (Finset.mem_cons_self _ _))
(IH fun i hi => Hlt _ (Finset.mem_cons.2 <| Or.inr hi))
#align ennreal.sum_lt_sum_of_nonempty Ennreal.sum_lt_sum_of_nonempty
theorem exists_le_of_sum_le {s : Finset α} (hs : s.Nonempty) {f g : α → ℝ≥0∞}
(Hle : (∑ i in s, f i) ≤ ∑ i in s, g i) : ∃ i ∈ s, f i ≤ g i :=
by
contrapose! Hle
apply Ennreal.sum_lt_sum_of_nonempty hs Hle
#align ennreal.exists_le_of_sum_le Ennreal.exists_le_of_sum_le
end Sum
section Interval
variable {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : Set ℝ≥0∞}
protected theorem ico_eq_iio : Ico 0 y = Iio y :=
Ico_bot
#align ennreal.Ico_eq_Iio Ennreal.ico_eq_iio
theorem mem_iio_self_add : x ≠ ∞ → ε ≠ 0 → x ∈ Iio (x + ε) := fun xt ε0 => lt_add_right xt ε0
#align ennreal.mem_Iio_self_add Ennreal.mem_iio_self_add
theorem mem_ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → ε₁ ≠ 0 → ε₂ ≠ 0 → x ∈ Ioo (x - ε₁) (x + ε₂) :=
fun xt x0 ε0 ε0' => ⟨Ennreal.sub_lt_self xt x0 ε0, lt_add_right xt ε0'⟩
#align ennreal.mem_Ioo_self_sub_add Ennreal.mem_ioo_self_sub_add
end Interval
section Bit
@[mono]
theorem bit0_strictMono : StrictMono (bit0 : ℝ≥0∞ → ℝ≥0∞) := fun a b h => add_lt_add h h
#align ennreal.bit0_strict_mono Ennreal.bit0_strictMono
theorem bit0_injective : Function.Injective (bit0 : ℝ≥0∞ → ℝ≥0∞) :=
bit0_strictMono.Injective
#align ennreal.bit0_injective Ennreal.bit0_injective
@[simp]
theorem bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b :=
bit0_strictMono.lt_iff_lt
#align ennreal.bit0_lt_bit0 Ennreal.bit0_lt_bit0
@[simp, mono]
theorem bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b :=
bit0_strictMono.le_iff_le
#align ennreal.bit0_le_bit0 Ennreal.bit0_le_bit0
@[simp]
theorem bit0_inj : bit0 a = bit0 b ↔ a = b :=
bit0_injective.eq_iff
#align ennreal.bit0_inj Ennreal.bit0_inj
@[simp]
theorem bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 :=
bit0_injective.eq_iff' bit0_zero
#align ennreal.bit0_eq_zero_iff Ennreal.bit0_eq_zero_iff
@[simp]
theorem bit0_top : bit0 ∞ = ∞ :=
add_top
#align ennreal.bit0_top Ennreal.bit0_top
@[simp]
theorem bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ :=
bit0_injective.eq_iff' bit0_top
#align ennreal.bit0_eq_top_iff Ennreal.bit0_eq_top_iff
@[mono]
theorem bit1_strictMono : StrictMono (bit1 : ℝ≥0∞ → ℝ≥0∞) := fun a b h =>
Ennreal.add_lt_add_right one_ne_top (bit0_strictMono h)
#align ennreal.bit1_strict_mono Ennreal.bit1_strictMono
theorem bit1_injective : Function.Injective (bit1 : ℝ≥0∞ → ℝ≥0∞) :=
bit1_strictMono.Injective
#align ennreal.bit1_injective Ennreal.bit1_injective
@[simp]
theorem bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b :=
bit1_strictMono.lt_iff_lt
#align ennreal.bit1_lt_bit1 Ennreal.bit1_lt_bit1
@[simp, mono]
theorem bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b :=
bit1_strictMono.le_iff_le
#align ennreal.bit1_le_bit1 Ennreal.bit1_le_bit1
@[simp]
theorem bit1_inj : bit1 a = bit1 b ↔ a = b :=
bit1_injective.eq_iff
#align ennreal.bit1_inj Ennreal.bit1_inj
@[simp]
theorem bit1_ne_zero : bit1 a ≠ 0 := by simp [bit1]
#align ennreal.bit1_ne_zero Ennreal.bit1_ne_zero
@[simp]
theorem bit1_top : bit1 ∞ = ∞ := by rw [bit1, bit0_top, top_add]
#align ennreal.bit1_top Ennreal.bit1_top
@[simp]
theorem bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ :=
bit1_injective.eq_iff' bit1_top
#align ennreal.bit1_eq_top_iff Ennreal.bit1_eq_top_iff
@[simp]
theorem bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 :=
bit1_injective.eq_iff' bit1_zero
#align ennreal.bit1_eq_one_iff Ennreal.bit1_eq_one_iff
end Bit
section Inv
noncomputable section
instance : Inv ℝ≥0∞ :=
⟨fun a => infₛ { b | 1 ≤ a * b }⟩
instance : DivInvMonoid ℝ≥0∞ :=
{ (inferInstance : Monoid ℝ≥0∞) with inv := Inv.inv }
theorem div_eq_inv_mul : a / b = b⁻¹ * a := by rw [div_eq_mul_inv, mul_comm]
#align ennreal.div_eq_inv_mul Ennreal.div_eq_inv_mul
@[simp]
theorem inv_zero : (0 : ℝ≥0∞)⁻¹ = ∞ :=
show infₛ { b : ℝ≥0∞ | 1 ≤ 0 * b } = ∞ by simp <;> rfl
#align ennreal.inv_zero Ennreal.inv_zero
@[simp]
theorem inv_top : ∞⁻¹ = 0 :=
bot_unique <|
le_of_forall_le_of_dense fun a (h : a > 0) => infₛ_le <| by simp [*, ne_of_gt h, top_mul]
#align ennreal.inv_top Ennreal.inv_top
theorem coe_inv_le : (↑r⁻¹ : ℝ≥0∞) ≤ (↑r)⁻¹ :=
le_infₛ fun b (hb : 1 ≤ ↑r * b) =>
coe_le_iff.2 <| by
rintro b rfl
apply Nnreal.inv_le_of_le_mul
rwa [← coe_mul, ← coe_one, coe_le_coe] at hb
#align ennreal.coe_inv_le Ennreal.coe_inv_le
@[simp, norm_cast]
theorem coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ℝ≥0∞) = (↑r)⁻¹ :=
coe_inv_le.antisymm <| infₛ_le <| le_of_eq <| by rw [← coe_mul, mul_inv_cancel hr, coe_one]
#align ennreal.coe_inv Ennreal.coe_inv
@[norm_cast]
theorem coe_inv_two : ((2⁻¹ : ℝ≥0) : ℝ≥0∞) = 2⁻¹ := by rw [coe_inv _root_.two_ne_zero, coe_two]
#align ennreal.coe_inv_two Ennreal.coe_inv_two
@[simp, norm_cast]
theorem coe_div (hr : r ≠ 0) : (↑(p / r) : ℝ≥0∞) = p / r := by
rw [div_eq_mul_inv, div_eq_mul_inv, coe_mul, coe_inv hr]
#align ennreal.coe_div Ennreal.coe_div
theorem div_zero (h : a ≠ 0) : a / 0 = ∞ := by simp [div_eq_mul_inv, h]
#align ennreal.div_zero Ennreal.div_zero
instance : DivInvOneMonoid ℝ≥0∞ :=
{ Ennreal.divInvMonoid with
inv_one := by simpa only [coe_inv one_neZero, coe_one] using coe_eq_coe.2 inv_one }
protected theorem inv_pow {n : ℕ} : (a ^ n)⁻¹ = a⁻¹ ^ n :=
by
cases n; · simp only [pow_zero, inv_one]
induction a using WithTop.recTopCoe; · simp [top_pow n.succ_pos]
rcases eq_or_ne a 0 with (rfl | ha); · simp [top_pow, zero_pow, n.succ_pos]
rw [← coe_inv ha, ← coe_pow, ← coe_inv (pow_ne_zero _ ha), ← inv_pow, coe_pow]
#align ennreal.inv_pow Ennreal.inv_pow
protected theorem mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 :=
by
lift a to ℝ≥0 using ht
norm_cast at *
exact mul_inv_cancel h0
#align ennreal.mul_inv_cancel Ennreal.mul_inv_cancel
protected theorem inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 :=
mul_comm a a⁻¹ ▸ Ennreal.mul_inv_cancel h0 ht
#align ennreal.inv_mul_cancel Ennreal.inv_mul_cancel
protected theorem div_mul_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : b / a * a = b := by
rw [div_eq_mul_inv, mul_assoc, Ennreal.inv_mul_cancel h0 hI, mul_one]
#align ennreal.div_mul_cancel Ennreal.div_mul_cancel
protected theorem mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by
rw [mul_comm, Ennreal.div_mul_cancel h0 hI]
#align ennreal.mul_div_cancel' Ennreal.mul_div_cancel'
instance : InvolutiveInv ℝ≥0∞ where
inv := Inv.inv
inv_inv a := by
by_cases a = 0 <;> cases a <;> simp_all [none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm]
@[simp]
theorem inv_eq_top : a⁻¹ = ∞ ↔ a = 0 :=
inv_zero ▸ inv_inj
#align ennreal.inv_eq_top Ennreal.inv_eq_top
theorem inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp
#align ennreal.inv_ne_top Ennreal.inv_ne_top
@[simp]
theorem inv_lt_top {x : ℝ≥0∞} : x⁻¹ < ∞ ↔ 0 < x := by
simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero]
#align ennreal.inv_lt_top Ennreal.inv_lt_top
theorem div_lt_top {x y : ℝ≥0∞} (h1 : x ≠ ∞) (h2 : y ≠ 0) : x / y < ∞ :=
mul_lt_top h1 (inv_ne_top.mpr h2)
#align ennreal.div_lt_top Ennreal.div_lt_top
@[simp]
protected theorem inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ :=
inv_top ▸ inv_inj
#align ennreal.inv_eq_zero Ennreal.inv_eq_zero
protected theorem inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp
#align ennreal.inv_ne_zero Ennreal.inv_ne_zero
protected theorem mul_inv {a b : ℝ≥0∞} (ha : a ≠ 0 ∨ b ≠ ∞) (hb : a ≠ ∞ ∨ b ≠ 0) :
(a * b)⁻¹ = a⁻¹ * b⁻¹ := by
induction b using WithTop.recTopCoe
· replace ha : a ≠ 0 := ha.neg_resolve_right rfl
simp [ha]
induction a using WithTop.recTopCoe
· replace hb : b ≠ 0 := coe_ne_zero.1 (hb.neg_resolve_left rfl)
simp [hb]
by_cases h'a : a = 0
·
simp only [h'a, WithTop.top_mul, Ennreal.inv_zero, Ennreal.coe_ne_top, zero_mul, Ne.def,
not_false_iff, Ennreal.coe_zero, Ennreal.inv_eq_zero]
by_cases h'b : b = 0
·
simp only [h'b, Ennreal.inv_zero, Ennreal.coe_ne_top, WithTop.mul_top, Ne.def, not_false_iff,
mul_zero, Ennreal.coe_zero, Ennreal.inv_eq_zero]
rw [← Ennreal.coe_mul, ← Ennreal.coe_inv, ← Ennreal.coe_inv h'a, ← Ennreal.coe_inv h'b, ←
Ennreal.coe_mul, mul_inv_rev, mul_comm]
simp [h'a, h'b]
#align ennreal.mul_inv Ennreal.mul_inv
protected theorem mul_div_mul_left (a b : ℝ≥0∞) (hc : c ≠ 0) (hc' : c ≠ ⊤) :
c * a / (c * b) = a / b := by
rw [div_eq_mul_inv, div_eq_mul_inv, Ennreal.mul_inv (Or.inl hc) (Or.inl hc'), mul_mul_mul_comm,
Ennreal.mul_inv_cancel hc hc', one_mul]
#align ennreal.mul_div_mul_left Ennreal.mul_div_mul_left
protected theorem mul_div_mul_right (a b : ℝ≥0∞) (hc : c ≠ 0) (hc' : c ≠ ⊤) :
a * c / (b * c) = a / b := by
rw [div_eq_mul_inv, div_eq_mul_inv, Ennreal.mul_inv (Or.inr hc') (Or.inr hc), mul_mul_mul_comm,
Ennreal.mul_inv_cancel hc hc', mul_one]
#align ennreal.mul_div_mul_right Ennreal.mul_div_mul_right
protected theorem sub_div (h : 0 < b → b < a → c ≠ 0) : (a - b) / c = a / c - b / c :=
by
simp_rw [div_eq_mul_inv]
exact Ennreal.sub_mul (by simpa using h)
#align ennreal.sub_div Ennreal.sub_div
@[simp]
protected theorem inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ :=
pos_iff_ne_zero.trans Ennreal.inv_ne_zero
#align ennreal.inv_pos Ennreal.inv_pos
theorem inv_strictAnti : StrictAnti (Inv.inv : ℝ≥0∞ → ℝ≥0∞) :=
by
intro a b h
lift a to ℝ≥0 using h.ne_top
induction b using WithTop.recTopCoe; · simp
rw [coe_lt_coe] at h
rcases eq_or_ne a 0 with (rfl | ha); · simp [h]
rw [← coe_inv h.ne_bot, ← coe_inv ha, coe_lt_coe]
exact Nnreal.inv_lt_inv ha h
#align ennreal.inv_strict_anti Ennreal.inv_strictAnti
@[simp]
protected theorem inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a :=
inv_strictAnti.lt_iff_lt
#align ennreal.inv_lt_inv Ennreal.inv_lt_inv
theorem inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by
simpa only [inv_inv] using @Ennreal.inv_lt_inv a b⁻¹
#align ennreal.inv_lt_iff_inv_lt Ennreal.inv_lt_iff_inv_lt
theorem lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by
simpa only [inv_inv] using @Ennreal.inv_lt_inv a⁻¹ b
#align ennreal.lt_inv_iff_lt_inv Ennreal.lt_inv_iff_lt_inv
-- higher than le_inv_iff_mul_le
@[simp]
protected theorem inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
inv_strictAnti.le_iff_le
#align ennreal.inv_le_inv Ennreal.inv_le_inv
theorem inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by
simpa only [inv_inv] using @Ennreal.inv_le_inv a b⁻¹
#align ennreal.inv_le_iff_inv_le Ennreal.inv_le_iff_inv_le
theorem le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by
simpa only [inv_inv] using @Ennreal.inv_le_inv a⁻¹ b
#align ennreal.le_inv_iff_le_inv Ennreal.le_inv_iff_le_inv
@[simp]
protected theorem inv_le_one : a⁻¹ ≤ 1 ↔ 1 ≤ a := by rw [inv_le_iff_inv_le, inv_one]
#align ennreal.inv_le_one Ennreal.inv_le_one
protected theorem one_le_inv : 1 ≤ a⁻¹ ↔ a ≤ 1 := by rw [le_inv_iff_le_inv, inv_one]
#align ennreal.one_le_inv Ennreal.one_le_inv
@[simp]
protected theorem inv_lt_one : a⁻¹ < 1 ↔ 1 < a := by rw [inv_lt_iff_inv_lt, inv_one]
#align ennreal.inv_lt_one Ennreal.inv_lt_one
@[simp]
protected theorem one_lt_inv : 1 < a⁻¹ ↔ a < 1 := by rw [lt_inv_iff_lt_inv, inv_one]
#align ennreal.one_lt_inv Ennreal.one_lt_inv
/-- The inverse map `λ x, x⁻¹` is an order isomorphism between `ℝ≥0∞` and its `order_dual` -/
@[simps apply]
def OrderIso.invEnnreal : ℝ≥0∞ ≃o ℝ≥0∞ᵒᵈ
where
map_rel_iff' a b := Ennreal.inv_le_inv
toEquiv := (Equiv.inv ℝ≥0∞).trans OrderDual.toDual
#align order_iso.inv_ennreal OrderIso.invEnnreal
@[simp]
theorem OrderIso.invEnnreal_symm_apply : OrderIso.invEnnreal.symm a = (OrderDual.ofDual a)⁻¹ :=
rfl
#align order_iso.inv_ennreal_symm_apply OrderIso.invEnnreal_symm_apply
protected theorem pow_le_pow_of_le_one {n m : ℕ} (ha : a ≤ 1) (h : n ≤ m) : a ^ m ≤ a ^ n :=
by
rw [← inv_inv a, ← Ennreal.inv_pow, ← @Ennreal.inv_pow a⁻¹, Ennreal.inv_le_inv]
exact pow_le_pow (Ennreal.one_le_inv.2 ha) h
#align ennreal.pow_le_pow_of_le_one Ennreal.pow_le_pow_of_le_one
@[simp]
theorem div_top : a / ∞ = 0 := by rw [div_eq_mul_inv, inv_top, mul_zero]
#align ennreal.div_top Ennreal.div_top
@[simp]
theorem top_div_coe : ∞ / p = ∞ := by simp [div_eq_mul_inv, top_mul]
#align ennreal.top_div_coe Ennreal.top_div_coe
theorem top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ :=
by
lift a to ℝ≥0 using h
exact top_div_coe
#align ennreal.top_div_of_ne_top Ennreal.top_div_of_ne_top
theorem top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ :=
top_div_of_ne_top h.Ne
#align ennreal.top_div_of_lt_top Ennreal.top_div_of_lt_top
theorem top_div : ∞ / a = if a = ∞ then 0 else ∞ := by
by_cases a = ∞ <;> simp [top_div_of_ne_top, *]
#align ennreal.top_div Ennreal.top_div
@[simp]
protected theorem zero_div : 0 / a = 0 :=
zero_mul a⁻¹
#align ennreal.zero_div Ennreal.zero_div
theorem div_eq_top : a / b = ∞ ↔ a ≠ 0 ∧ b = 0 ∨ a = ∞ ∧ b ≠ ∞ := by
simp [div_eq_mul_inv, Ennreal.mul_eq_top]
#align ennreal.div_eq_top Ennreal.div_eq_top
protected theorem le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) :
a ≤ c / b ↔ a * b ≤ c := by
induction b using WithTop.recTopCoe
· lift c to ℝ≥0 using ht.neg_resolve_left rfl
rw [div_top, nonpos_iff_eq_zero, mul_top]
rcases eq_or_ne a 0 with (rfl | ha) <;> simp [*]
rcases eq_or_ne b 0 with (rfl | hb)
· have hc : c ≠ 0 := h0.neg_resolve_left rfl
simp [div_zero hc]
· rw [← coe_ne_zero] at hb
rw [← Ennreal.mul_le_mul_right hb coe_ne_top, Ennreal.div_mul_cancel hb coe_ne_top]
#align ennreal.le_div_iff_mul_le Ennreal.le_div_iff_mul_le
protected theorem div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) :
a / b ≤ c ↔ a ≤ c * b :=
by
suffices a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹ by simpa [div_eq_mul_inv]
refine' (Ennreal.le_div_iff_mul_le _ _).symm <;> simpa
#align ennreal.div_le_iff_le_mul Ennreal.div_le_iff_le_mul
protected theorem lt_div_iff_mul_lt (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) :
c < a / b ↔ c * b < a :=
lt_iff_lt_of_le_iff_le (Ennreal.div_le_iff_le_mul hb0 hbt)
#align ennreal.lt_div_iff_mul_lt Ennreal.lt_div_iff_mul_lt
theorem div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b :=
by
by_cases h0 : c = 0
· have : a = 0 := by simpa [h0] using h
simp [*]
by_cases hinf : c = ∞; · simp [hinf]
exact (Ennreal.div_le_iff_le_mul (Or.inl h0) (Or.inl hinf)).2 h
#align ennreal.div_le_of_le_mul Ennreal.div_le_of_le_mul
theorem div_le_of_le_mul' (h : a ≤ b * c) : a / b ≤ c :=
div_le_of_le_mul <| mul_comm b c ▸ h
#align ennreal.div_le_of_le_mul' Ennreal.div_le_of_le_mul'
theorem mul_le_of_le_div (h : a ≤ b / c) : a * c ≤ b :=
by
rw [← inv_inv c]
exact div_le_of_le_mul h
#align ennreal.mul_le_of_le_div Ennreal.mul_le_of_le_div
theorem mul_le_of_le_div' (h : a ≤ b / c) : c * a ≤ b :=
mul_comm a c ▸ mul_le_of_le_div h
#align ennreal.mul_le_of_le_div' Ennreal.mul_le_of_le_div'
protected theorem div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b :=
lt_iff_lt_of_le_iff_le <| Ennreal.le_div_iff_mul_le h0 ht
#align ennreal.div_lt_iff Ennreal.div_lt_iff
theorem mul_lt_of_lt_div (h : a < b / c) : a * c < b :=
by
contrapose! h
exact Ennreal.div_le_of_le_mul h
#align ennreal.mul_lt_of_lt_div Ennreal.mul_lt_of_lt_div
theorem mul_lt_of_lt_div' (h : a < b / c) : c * a < b :=
mul_comm a c ▸ mul_lt_of_lt_div h
#align ennreal.mul_lt_of_lt_div' Ennreal.mul_lt_of_lt_div'
theorem inv_le_iff_le_mul (h₁ : b = ∞ → a ≠ 0) (h₂ : a = ∞ → b ≠ 0) : a⁻¹ ≤ b ↔ 1 ≤ a * b :=
by
rw [← one_div, Ennreal.div_le_iff_le_mul, mul_comm]
exacts[or_not_of_imp h₁, not_or_of_imp h₂]
#align ennreal.inv_le_iff_le_mul Ennreal.inv_le_iff_le_mul
@[simp]
theorem le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := by
rw [← one_div, Ennreal.le_div_iff_mul_le] <;>
· right
simp
#align ennreal.le_inv_iff_mul_le Ennreal.le_inv_iff_mul_le
protected theorem div_le_div (hab : a ≤ b) (hdc : d ≤ c) : a / c ≤ b / d :=
div_eq_mul_inv b d ▸ div_eq_mul_inv a c ▸ Ennreal.mul_le_mul hab (Ennreal.inv_le_inv.mpr hdc)
#align ennreal.div_le_div Ennreal.div_le_div
protected theorem div_le_div_left (h : a ≤ b) (c : ℝ≥0∞) : c / b ≤ c / a :=
Ennreal.div_le_div le_rfl h
#align ennreal.div_le_div_left Ennreal.div_le_div_left
protected theorem div_le_div_right (h : a ≤ b) (c : ℝ≥0∞) : a / c ≤ b / c :=
Ennreal.div_le_div h le_rfl
#align ennreal.div_le_div_right Ennreal.div_le_div_right
protected theorem eq_inv_of_mul_eq_one_left (h : a * b = 1) : a = b⁻¹ :=
by
rw [← mul_one a, ← Ennreal.mul_inv_cancel (right_ne_zero_of_mul_eq_one h), ← mul_assoc, h,
one_mul]
rintro rfl
simpa [left_ne_zero_of_mul_eq_one h] using h
#align ennreal.eq_inv_of_mul_eq_one_left Ennreal.eq_inv_of_mul_eq_one_left
theorem mul_le_iff_le_inv {a b r : ℝ≥0∞} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : r * a ≤ b ↔ a ≤ r⁻¹ * b := by
rw [← @Ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, Ennreal.mul_inv_cancel hr₀ hr₁,
one_mul]
#align ennreal.mul_le_iff_le_inv Ennreal.mul_le_iff_le_inv
theorem le_of_forall_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y :=
by
refine' le_of_forall_ge_of_dense fun r hr => _
lift r to ℝ≥0 using ne_top_of_lt hr
exact h r hr
#align ennreal.le_of_forall_nnreal_lt Ennreal.le_of_forall_nnreal_lt
theorem le_of_forall_pos_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, 0 < r → ↑r < x → ↑r ≤ y) : x ≤ y :=
le_of_forall_nnreal_lt fun r hr =>
(zero_le r).eq_or_lt.elim (fun h => h ▸ zero_le _) fun h0 => h r h0 hr
#align ennreal.le_of_forall_pos_nnreal_lt Ennreal.le_of_forall_pos_nnreal_lt
theorem eq_top_of_forall_nnreal_le {x : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r ≤ x) : x = ∞ :=
top_unique <| le_of_forall_nnreal_lt fun r hr => h r
#align ennreal.eq_top_of_forall_nnreal_le Ennreal.eq_top_of_forall_nnreal_le
protected theorem add_div : (a + b) / c = a / c + b / c :=
right_distrib a b c⁻¹
#align ennreal.add_div Ennreal.add_div
protected theorem div_add_div_same {a b c : ℝ≥0∞} : a / c + b / c = (a + b) / c :=
Ennreal.add_div.symm
#align ennreal.div_add_div_same Ennreal.div_add_div_same
protected theorem div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 :=
Ennreal.mul_inv_cancel h0 hI
#align ennreal.div_self Ennreal.div_self
theorem mul_div_le : a * (b / a) ≤ b :=
mul_le_of_le_div' le_rfl
#align ennreal.mul_div_le Ennreal.mul_div_le
-- TODO: add this lemma for an `is_unit` in any `division_monoid`
theorem eq_div_iff (ha : a ≠ 0) (ha' : a ≠ ∞) : b = c / a ↔ a * b = c :=
⟨fun h => by rw [h, Ennreal.mul_div_cancel' ha ha'], fun h => by
rw [← h, mul_div_assoc, Ennreal.mul_div_cancel' ha ha']⟩
#align ennreal.eq_div_iff Ennreal.eq_div_iff
protected theorem div_eq_div_iff (ha : a ≠ 0) (ha' : a ≠ ∞) (hb : b ≠ 0) (hb' : b ≠ ∞) :
c / b = d / a ↔ a * c = b * d := by
rw [eq_div_iff ha ha']
conv_rhs => rw [eq_comm]
rw [← eq_div_iff hb hb', mul_div_assoc, eq_comm]
#align ennreal.div_eq_div_iff Ennreal.div_eq_div_iff
theorem div_eq_one_iff {a b : ℝ≥0∞} (hb₀ : b ≠ 0) (hb₁ : b ≠ ∞) : a / b = 1 ↔ a = b :=
⟨fun h => by rw [← (eq_div_iff hb₀ hb₁).mp h.symm, mul_one], fun h =>
h.symm ▸ Ennreal.div_self hb₀ hb₁⟩
#align ennreal.div_eq_one_iff Ennreal.div_eq_one_iff
theorem inv_two_add_inv_two : (2 : ℝ≥0∞)⁻¹ + 2⁻¹ = 1 := by
rw [← two_mul, ← div_eq_mul_inv, Ennreal.div_self two_neZero two_ne_top]
#align ennreal.inv_two_add_inv_two Ennreal.inv_two_add_inv_two
theorem inv_three_add_inv_three : (3 : ℝ≥0∞)⁻¹ + 3⁻¹ + 3⁻¹ = 1 := by
rw [show (3 : ℝ≥0∞)⁻¹ + 3⁻¹ + 3⁻¹ = 3 * 3⁻¹ by ring, ← div_eq_mul_inv, Ennreal.div_self] <;> simp
#align ennreal.inv_three_add_inv_three Ennreal.inv_three_add_inv_three
@[simp]
protected theorem add_halves (a : ℝ≥0∞) : a / 2 + a / 2 = a := by
rw [div_eq_mul_inv, ← mul_add, inv_two_add_inv_two, mul_one]
#align ennreal.add_halves Ennreal.add_halves
@[simp]
theorem add_thirds (a : ℝ≥0∞) : a / 3 + a / 3 + a / 3 = a := by
rw [div_eq_mul_inv, ← mul_add, ← mul_add, inv_three_add_inv_three, mul_one]
#align ennreal.add_thirds Ennreal.add_thirds
@[simp]
theorem div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_eq_mul_inv]
#align ennreal.div_zero_iff Ennreal.div_zero_iff
@[simp]
theorem div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ := by simp [pos_iff_ne_zero, not_or]
#align ennreal.div_pos_iff Ennreal.div_pos_iff
protected theorem half_pos (h : a ≠ 0) : 0 < a / 2 := by simp [h]
#align ennreal.half_pos Ennreal.half_pos
protected theorem one_half_lt_one : (2⁻¹ : ℝ≥0∞) < 1 :=
Ennreal.inv_lt_one.2 <| one_lt_two
#align ennreal.one_half_lt_one Ennreal.one_half_lt_one
protected theorem half_lt_self (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a :=
by
lift a to ℝ≥0 using ht
rw [coe_ne_zero] at hz
rw [← coe_two, ← coe_div, coe_lt_coe]
exacts[Nnreal.half_lt_self hz, two_ne_zero' _]
#align ennreal.half_lt_self Ennreal.half_lt_self
protected theorem half_le_self : a / 2 ≤ a :=
le_add_self.trans_eq <| Ennreal.add_halves _
#align ennreal.half_le_self Ennreal.half_le_self
theorem sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 :=
by
lift a to ℝ≥0 using h
exact sub_eq_of_add_eq (mul_ne_top coe_ne_top <| by simp) (Ennreal.add_halves a)
#align ennreal.sub_half Ennreal.sub_half
@[simp]
theorem one_sub_inv_two : (1 : ℝ≥0∞) - 2⁻¹ = 2⁻¹ := by
simpa only [div_eq_mul_inv, one_mul] using sub_half one_ne_top
#align ennreal.one_sub_inv_two Ennreal.one_sub_inv_two
/-- The birational order isomorphism between `ℝ≥0∞` and the unit interval `set.Iic (1 : ℝ≥0∞)`. -/
@[simps apply_coe]
def orderIsoIicOneBirational : ℝ≥0∞ ≃o Iic (1 : ℝ≥0∞) :=
by
refine'
StrictMono.orderIsoOfRightInverse (fun x => ⟨(x⁻¹ + 1)⁻¹, Ennreal.inv_le_one.2 <| le_add_self⟩)
(fun x y hxy => _) (fun x => (x⁻¹ - 1)⁻¹) fun x => Subtype.ext _
· simpa only [Subtype.mk_lt_mk, Ennreal.inv_lt_inv, Ennreal.add_lt_add_iff_right one_ne_top]
· have : (1 : ℝ≥0∞) ≤ x⁻¹ := Ennreal.one_le_inv.2 x.2
simp only [inv_inv, Subtype.coe_mk, tsub_add_cancel_of_le this]
#align ennreal.order_iso_Iic_one_birational Ennreal.orderIsoIicOneBirational
@[simp]
theorem orderIsoIicOneBirational_symm_apply (x : Iic (1 : ℝ≥0∞)) :
orderIsoIicOneBirational.symm x = (x⁻¹ - 1)⁻¹ :=
rfl
#align ennreal.order_iso_Iic_one_birational_symm_apply Ennreal.orderIsoIicOneBirational_symm_apply
/-- Order isomorphism between an initial interval in `ℝ≥0∞` and an initial interval in `ℝ≥0`. -/
@[simps apply_coe]
def orderIsoIicCoe (a : ℝ≥0) : Iic (a : ℝ≥0∞) ≃o Iic a :=
OrderIso.symm
{ toFun := fun x => ⟨x, coe_le_coe.2 x.2⟩
invFun := fun x => ⟨Ennreal.toNnreal x, coe_le_coe.1 <| coe_toNnreal_le_self.trans x.2⟩
left_inv := fun x => Subtype.ext <| to_nnreal_coe
right_inv := fun x => Subtype.ext <| coe_toNnreal (ne_top_of_le_ne_top coe_ne_top x.2)
map_rel_iff' := fun x y => by
simp only [Equiv.coeFn_mk, Subtype.mk_le_mk, coe_coe, coe_le_coe, Subtype.coe_le_coe] }
#align ennreal.order_iso_Iic_coe Ennreal.orderIsoIicCoe
@[simp]
theorem orderIsoIicCoe_symm_apply_coe (a : ℝ≥0) (b : Iic a) :
((orderIsoIicCoe a).symm b : ℝ≥0∞) = b :=
rfl
#align ennreal.order_iso_Iic_coe_symm_apply_coe Ennreal.orderIsoIicCoe_symm_apply_coe
/-- An order isomorphism between the extended nonnegative real numbers and the unit interval. -/
def orderIsoUnitIntervalBirational : ℝ≥0∞ ≃o Icc (0 : ℝ) 1 :=
orderIsoIicOneBirational.trans <| (orderIsoIicCoe 1).trans <| (Nnreal.orderIsoIccZeroCoe 1).symm
#align ennreal.order_iso_unit_interval_birational Ennreal.orderIsoUnitIntervalBirational
@[simp]
theorem orderIsoUnitIntervalBirational_apply_coe (x : ℝ≥0∞) :
(orderIsoUnitIntervalBirational x : ℝ) = (x⁻¹ + 1)⁻¹.toReal :=
rfl
#align ennreal.order_iso_unit_interval_birational_apply_coe Ennreal.orderIsoUnitIntervalBirational_apply_coe
theorem exists_inv_nat_lt {a : ℝ≥0∞} (h : a ≠ 0) : ∃ n : ℕ, (n : ℝ≥0∞)⁻¹ < a :=
inv_inv a ▸ by simp only [Ennreal.inv_lt_inv, Ennreal.exists_nat_gt (inv_ne_top.2 h)]
#align ennreal.exists_inv_nat_lt Ennreal.exists_inv_nat_lt
theorem exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a :=
by
have : b / a ≠ ∞ := mul_ne_top hb (inv_ne_top.2 ha)
refine' (Ennreal.exists_nat_gt this).imp fun n hn => _
have : ↑0 < (n : ℝ≥0∞) := lt_of_le_of_lt (by simp) hn
refine' ⟨coe_nat_lt_coe_nat.1 this, _⟩
rwa [← Ennreal.div_lt_iff (Or.inl ha) (Or.inr hb)]
#align ennreal.exists_nat_pos_mul_gt Ennreal.exists_nat_pos_mul_gt
theorem exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a :=
(exists_nat_pos_mul_gt ha hb).imp fun n => Exists.snd
#align ennreal.exists_nat_mul_gt Ennreal.exists_nat_mul_gt
theorem exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ℝ≥0∞)⁻¹ * a < b :=
by
rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩
have : (n : ℝ≥0∞) ≠ 0 := Nat.cast_ne_zero.2 npos.lt.ne'
use n, npos
rwa [← one_mul b, ← Ennreal.inv_mul_cancel this (nat_ne_top n), mul_assoc,
mul_lt_mul_left (Ennreal.inv_ne_zero.2 <| nat_ne_top _) (inv_ne_top.2 this)]
#align ennreal.exists_nat_pos_inv_mul_lt Ennreal.exists_nat_pos_inv_mul_lt
theorem exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b :=
by
rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩
use (n : ℝ≥0)⁻¹
simp [*, npos.ne', zero_lt_one]
#align ennreal.exists_nnreal_pos_mul_lt Ennreal.exists_nnreal_pos_mul_lt
theorem exists_inv_two_pow_lt (ha : a ≠ 0) : ∃ n : ℕ, 2⁻¹ ^ n < a :=
by
rcases exists_inv_nat_lt ha with ⟨n, hn⟩
refine' ⟨n, lt_trans _ hn⟩
rw [← Ennreal.inv_pow, Ennreal.inv_lt_inv]
norm_cast
exact n.lt_two_pow
#align ennreal.exists_inv_two_pow_lt Ennreal.exists_inv_two_pow_lt
@[simp, norm_cast]
theorem coe_zpow (hr : r ≠ 0) (n : ℤ) : (↑(r ^ n) : ℝ≥0∞) = r ^ n :=
by
cases n
· simp only [Int.ofNat_eq_coe, coe_pow, zpow_ofNat]
· have : r ^ n.succ ≠ 0 := pow_ne_zero (n + 1) hr
simp only [zpow_negSucc, coe_inv this, coe_pow]
#align ennreal.coe_zpow Ennreal.coe_zpow
theorem zpow_pos (ha : a ≠ 0) (h'a : a ≠ ∞) (n : ℤ) : 0 < a ^ n :=
by
cases n
· exact Ennreal.pow_pos ha.bot_lt n
·
simp only [h'a, pow_eq_top_iff, zpow_negSucc, Ne.def, not_false_iff, Ennreal.inv_pos,
false_and_iff]
#align ennreal.zpow_pos Ennreal.zpow_pos
theorem zpow_lt_top (ha : a ≠ 0) (h'a : a ≠ ∞) (n : ℤ) : a ^ n < ∞ :=
by
cases n
· exact Ennreal.pow_lt_top h'a.lt_top _
· simp only [Ennreal.pow_pos ha.bot_lt (n + 1), zpow_negSucc, inv_lt_top]
#align ennreal.zpow_lt_top Ennreal.zpow_lt_top
theorem exists_mem_ico_zpow {x y : ℝ≥0∞} (hx : x ≠ 0) (h'x : x ≠ ∞) (hy : 1 < y) (h'y : y ≠ ⊤) :
∃ n : ℤ, x ∈ Ico (y ^ n) (y ^ (n + 1)) :=
by
lift x to ℝ≥0 using h'x
lift y to ℝ≥0 using h'y
have A : y ≠ 0 := by simpa only [Ne.def, coe_eq_zero] using (zero_lt_one.trans hy).ne'
obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) :=
by
refine' Nnreal.exists_mem_ico_zpow _ (one_lt_coe_iff.1 hy)
simpa only [Ne.def, coe_eq_zero] using hx
refine' ⟨n, _, _⟩
· rwa [← Ennreal.coe_zpow A, Ennreal.coe_le_coe]
· rwa [← Ennreal.coe_zpow A, Ennreal.coe_lt_coe]
#align ennreal.exists_mem_Ico_zpow Ennreal.exists_mem_ico_zpow
theorem exists_mem_ioc_zpow {x y : ℝ≥0∞} (hx : x ≠ 0) (h'x : x ≠ ∞) (hy : 1 < y) (h'y : y ≠ ⊤) :
∃ n : ℤ, x ∈ Ioc (y ^ n) (y ^ (n + 1)) :=
by
lift x to ℝ≥0 using h'x
lift y to ℝ≥0 using h'y
have A : y ≠ 0 := by simpa only [Ne.def, coe_eq_zero] using (zero_lt_one.trans hy).ne'
obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) :=
by
refine' Nnreal.exists_mem_ioc_zpow _ (one_lt_coe_iff.1 hy)
simpa only [Ne.def, coe_eq_zero] using hx
refine' ⟨n, _, _⟩
· rwa [← Ennreal.coe_zpow A, Ennreal.coe_lt_coe]
· rwa [← Ennreal.coe_zpow A, Ennreal.coe_le_coe]
#align ennreal.exists_mem_Ioc_zpow Ennreal.exists_mem_ioc_zpow
theorem ioo_zero_top_eq_unionᵢ_ico_zpow {y : ℝ≥0∞} (hy : 1 < y) (h'y : y ≠ ⊤) :
Ioo (0 : ℝ≥0∞) (∞ : ℝ≥0∞) = ⋃ n : ℤ, Ico (y ^ n) (y ^ (n + 1)) :=
by
ext x
simp only [mem_Union, mem_Ioo, mem_Ico]
constructor
· rintro ⟨hx, h'x⟩
exact exists_mem_Ico_zpow hx.ne' h'x.ne hy h'y
· rintro ⟨n, hn, h'n⟩
constructor
· apply lt_of_lt_of_le _ hn
exact Ennreal.zpow_pos (zero_lt_one.trans hy).ne' h'y _
· apply lt_trans h'n _
exact Ennreal.zpow_lt_top (zero_lt_one.trans hy).ne' h'y _
#align ennreal.Ioo_zero_top_eq_Union_Ico_zpow Ennreal.ioo_zero_top_eq_unionᵢ_ico_zpow
theorem zpow_le_of_le {x : ℝ≥0∞} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b :=
by
induction' a with a a <;> induction' b with b b
· simp only [Int.ofNat_eq_coe, zpow_ofNat]
exact pow_le_pow hx (Int.le_of_ofNat_le_ofNat h)
· apply absurd h (not_le_of_gt _)
exact lt_of_lt_of_le (Int.negSucc_lt_zero _) (Int.ofNat_nonneg _)
· simp only [zpow_negSucc, Int.ofNat_eq_coe, zpow_ofNat]
refine' (Ennreal.inv_le_one.2 _).trans _ <;> exact Ennreal.one_le_pow_of_one_le hx _
· simp only [zpow_negSucc, Ennreal.inv_le_inv]
apply pow_le_pow hx
simpa only [← Int.ofNat_le, neg_le_neg_iff, Int.ofNat_add, Int.ofNat_one, Int.negSucc_eq] using
h
#align ennreal.zpow_le_of_le Ennreal.zpow_le_of_le
theorem monotone_zpow {x : ℝ≥0∞} (hx : 1 ≤ x) : Monotone ((· ^ ·) x : ℤ → ℝ≥0∞) := fun a b h =>
zpow_le_of_le hx h
#align ennreal.monotone_zpow Ennreal.monotone_zpow
protected theorem zpow_add {x : ℝ≥0∞} (hx : x ≠ 0) (h'x : x ≠ ∞) (m n : ℤ) :
x ^ (m + n) = x ^ m * x ^ n := by
lift x to ℝ≥0 using h'x
replace hx : x ≠ 0; · simpa only [Ne.def, coe_eq_zero] using hx
simp only [← coe_zpow hx, zpow_add₀ hx, coe_mul]
#align ennreal.zpow_add Ennreal.zpow_add
end Inv
section Real
theorem toReal_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a + b).toReal = a.toReal + b.toReal :=
by
lift a to ℝ≥0 using ha
lift b to ℝ≥0 using hb
rfl
#align ennreal.to_real_add Ennreal.toReal_add
theorem toReal_sub_of_le {a b : ℝ≥0∞} (h : b ≤ a) (ha : a ≠ ∞) :
(a - b).toReal = a.toReal - b.toReal :=
by
lift b to ℝ≥0 using ne_top_of_le_ne_top ha h
lift a to ℝ≥0 using ha
simp only [← Ennreal.coe_sub, Ennreal.coe_toReal, Nnreal.coe_sub (ennreal.coe_le_coe.mp h)]
#align ennreal.to_real_sub_of_le Ennreal.toReal_sub_of_le
theorem le_toReal_sub {a b : ℝ≥0∞} (hb : b ≠ ∞) : a.toReal - b.toReal ≤ (a - b).toReal :=
by
lift b to ℝ≥0 using hb
induction a using WithTop.recTopCoe
· simp
· simp only [← coe_sub, Nnreal.sub_def, Real.coe_to_nnreal', coe_to_real]
exact le_max_left _ _
#align ennreal.le_to_real_sub Ennreal.le_toReal_sub
theorem toReal_add_le : (a + b).toReal ≤ a.toReal + b.toReal :=
if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg]
else
if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg]
else le_of_eq (toReal_add ha hb)
#align ennreal.to_real_add_le Ennreal.toReal_add_le
theorem ofReal_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) :
Ennreal.ofReal (p + q) = Ennreal.ofReal p + Ennreal.ofReal q := by
rw [Ennreal.ofReal, Ennreal.ofReal, Ennreal.ofReal, ← coe_add, coe_eq_coe,
Real.toNnreal_add hp hq]
#align ennreal.of_real_add Ennreal.ofReal_add
theorem ofReal_add_le {p q : ℝ} : Ennreal.ofReal (p + q) ≤ Ennreal.ofReal p + Ennreal.ofReal q :=
coe_le_coe.2 Real.toNnreal_add_le
#align ennreal.of_real_add_le Ennreal.ofReal_add_le
@[simp]
theorem toReal_le_toReal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.toReal ≤ b.toReal ↔ a ≤ b :=
by
lift a to ℝ≥0 using ha
lift b to ℝ≥0 using hb
norm_cast
#align ennreal.to_real_le_to_real Ennreal.toReal_le_toReal
theorem toReal_mono (hb : b ≠ ∞) (h : a ≤ b) : a.toReal ≤ b.toReal :=
(toReal_le_toReal (h.trans_lt (lt_top_iff_ne_top.2 hb)).Ne hb).2 h
#align ennreal.to_real_mono Ennreal.toReal_mono
@[simp]
theorem toReal_lt_toReal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.toReal < b.toReal ↔ a < b :=
by
lift a to ℝ≥0 using ha
lift b to ℝ≥0 using hb
norm_cast
#align ennreal.to_real_lt_to_real Ennreal.toReal_lt_toReal
theorem toReal_strict_mono (hb : b ≠ ∞) (h : a < b) : a.toReal < b.toReal :=
(toReal_lt_toReal (h.trans (lt_top_iff_ne_top.2 hb)).Ne hb).2 h
#align ennreal.to_real_strict_mono Ennreal.toReal_strict_mono
theorem toNnreal_mono (hb : b ≠ ∞) (h : a ≤ b) : a.toNnreal ≤ b.toNnreal := by
simpa [← Ennreal.coe_le_coe, hb, (h.trans_lt hb.lt_top).Ne]
#align ennreal.to_nnreal_mono Ennreal.toNnreal_mono
@[simp]
theorem toNnreal_le_toNnreal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.toNnreal ≤ b.toNnreal ↔ a ≤ b :=
⟨fun h => by rwa [← coe_to_nnreal ha, ← coe_to_nnreal hb, coe_le_coe], toNnreal_mono hb⟩
#align ennreal.to_nnreal_le_to_nnreal Ennreal.toNnreal_le_toNnreal
theorem toNnreal_strict_mono (hb : b ≠ ∞) (h : a < b) : a.toNnreal < b.toNnreal := by
simpa [← Ennreal.coe_lt_coe, hb, (h.trans hb.lt_top).Ne]
#align ennreal.to_nnreal_strict_mono Ennreal.toNnreal_strict_mono
@[simp]
theorem toNnreal_lt_toNnreal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.toNnreal < b.toNnreal ↔ a < b :=
⟨fun h => by rwa [← coe_to_nnreal ha, ← coe_to_nnreal hb, coe_lt_coe], toNnreal_strict_mono hb⟩
#align ennreal.to_nnreal_lt_to_nnreal Ennreal.toNnreal_lt_toNnreal
theorem toReal_max (hr : a ≠ ∞) (hp : b ≠ ∞) :
Ennreal.toReal (max a b) = max (Ennreal.toReal a) (Ennreal.toReal b) :=
(le_total a b).elim
(fun h => by simp only [h, (Ennreal.toReal_le_toReal hr hp).2 h, max_eq_right]) fun h => by
simp only [h, (Ennreal.toReal_le_toReal hp hr).2 h, max_eq_left]
#align ennreal.to_real_max Ennreal.toReal_max
theorem toReal_min {a b : ℝ≥0∞} (hr : a ≠ ∞) (hp : b ≠ ∞) :
Ennreal.toReal (min a b) = min (Ennreal.toReal a) (Ennreal.toReal b) :=
(le_total a b).elim (fun h => by simp only [h, (Ennreal.toReal_le_toReal hr hp).2 h, min_eq_left])
fun h => by simp only [h, (Ennreal.toReal_le_toReal hp hr).2 h, min_eq_right]
#align ennreal.to_real_min Ennreal.toReal_min
theorem toReal_sup {a b : ℝ≥0∞} : a ≠ ∞ → b ≠ ∞ → (a ⊔ b).toReal = a.toReal ⊔ b.toReal :=
to_real_max
#align ennreal.to_real_sup Ennreal.toReal_sup
theorem toReal_inf {a b : ℝ≥0∞} : a ≠ ∞ → b ≠ ∞ → (a ⊓ b).toReal = a.toReal ⊓ b.toReal :=
to_real_min
#align ennreal.to_real_inf Ennreal.toReal_inf
theorem toNnreal_pos_iff : 0 < a.toNnreal ↔ 0 < a ∧ a < ∞ := by
induction a using WithTop.recTopCoe <;> simp
#align ennreal.to_nnreal_pos_iff Ennreal.toNnreal_pos_iff
theorem toNnreal_pos {a : ℝ≥0∞} (ha₀ : a ≠ 0) (ha_top : a ≠ ∞) : 0 < a.toNnreal :=
toNnreal_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr ha₀, lt_top_iff_ne_top.mpr ha_top⟩
#align ennreal.to_nnreal_pos Ennreal.toNnreal_pos
theorem toReal_pos_iff : 0 < a.toReal ↔ 0 < a ∧ a < ∞ :=
Nnreal.coe_pos.trans toNnreal_pos_iff
#align ennreal.to_real_pos_iff Ennreal.toReal_pos_iff
theorem toReal_pos {a : ℝ≥0∞} (ha₀ : a ≠ 0) (ha_top : a ≠ ∞) : 0 < a.toReal :=
toReal_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr ha₀, lt_top_iff_ne_top.mpr ha_top⟩
#align ennreal.to_real_pos Ennreal.toReal_pos
theorem ofReal_le_ofReal {p q : ℝ} (h : p ≤ q) : Ennreal.ofReal p ≤ Ennreal.ofReal q := by
simp [Ennreal.ofReal, Real.toNnreal_le_toNnreal h]
#align ennreal.of_real_le_of_real Ennreal.ofReal_le_ofReal
theorem ofReal_le_of_le_toReal {a : ℝ} {b : ℝ≥0∞} (h : a ≤ Ennreal.toReal b) :
Ennreal.ofReal a ≤ b :=
(ofReal_le_ofReal h).trans ofReal_toReal_le
#align ennreal.of_real_le_of_le_to_real Ennreal.ofReal_le_of_le_toReal
@[simp]
theorem ofReal_le_ofReal_iff {p q : ℝ} (h : 0 ≤ q) : Ennreal.ofReal p ≤ Ennreal.ofReal q ↔ p ≤ q :=
by rw [Ennreal.ofReal, Ennreal.ofReal, coe_le_coe, Real.toNnreal_le_toNnreal_iff h]
#align ennreal.of_real_le_of_real_iff Ennreal.ofReal_le_ofReal_iff
@[simp]
theorem ofReal_eq_ofReal_iff {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) :
Ennreal.ofReal p = Ennreal.ofReal q ↔ p = q := by
rw [Ennreal.ofReal, Ennreal.ofReal, coe_eq_coe, Real.toNnreal_eq_toNnreal_iff hp hq]
#align ennreal.of_real_eq_of_real_iff Ennreal.ofReal_eq_ofReal_iff
@[simp]
theorem ofReal_lt_ofReal_iff {p q : ℝ} (h : 0 < q) : Ennreal.ofReal p < Ennreal.ofReal q ↔ p < q :=
by rw [Ennreal.ofReal, Ennreal.ofReal, coe_lt_coe, Real.toNnreal_lt_toNnreal_iff h]
#align ennreal.of_real_lt_of_real_iff Ennreal.ofReal_lt_ofReal_iff
theorem ofReal_lt_ofReal_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) :
Ennreal.ofReal p < Ennreal.ofReal q ↔ p < q := by
rw [Ennreal.ofReal, Ennreal.ofReal, coe_lt_coe, Real.toNnreal_lt_toNnreal_iff_of_nonneg hp]
#align ennreal.of_real_lt_of_real_iff_of_nonneg Ennreal.ofReal_lt_ofReal_iff_of_nonneg
@[simp]
theorem ofReal_pos {p : ℝ} : 0 < Ennreal.ofReal p ↔ 0 < p := by simp [Ennreal.ofReal]
#align ennreal.of_real_pos Ennreal.ofReal_pos
@[simp]
theorem ofReal_eq_zero {p : ℝ} : Ennreal.ofReal p = 0 ↔ p ≤ 0 := by simp [Ennreal.ofReal]
#align ennreal.of_real_eq_zero Ennreal.ofReal_eq_zero
@[simp]
theorem zero_eq_ofReal {p : ℝ} : 0 = Ennreal.ofReal p ↔ p ≤ 0 :=
eq_comm.trans ofReal_eq_zero
#align ennreal.zero_eq_of_real Ennreal.zero_eq_ofReal
alias of_real_eq_zero ↔ _ of_real_of_nonpos
#align ennreal.of_real_of_nonpos Ennreal.ofReal_of_nonpos
theorem ofReal_sub (p : ℝ) {q : ℝ} (hq : 0 ≤ q) :
Ennreal.ofReal (p - q) = Ennreal.ofReal p - Ennreal.ofReal q :=
by
obtain h | h := le_total p q
· rw [of_real_of_nonpos (sub_nonpos_of_le h), tsub_eq_zero_of_le (of_real_le_of_real h)]
refine' Ennreal.eq_sub_of_add_eq of_real_ne_top _
rw [← of_real_add (sub_nonneg_of_le h) hq, sub_add_cancel]
#align ennreal.of_real_sub Ennreal.ofReal_sub
theorem ofReal_le_iff_le_toReal {a : ℝ} {b : ℝ≥0∞} (hb : b ≠ ∞) :
Ennreal.ofReal a ≤ b ↔ a ≤ Ennreal.toReal b :=
by
lift b to ℝ≥0 using hb
simpa [Ennreal.ofReal, Ennreal.toReal] using Real.toNnreal_le_iff_le_coe
#align ennreal.of_real_le_iff_le_to_real Ennreal.ofReal_le_iff_le_toReal
theorem ofReal_lt_iff_lt_toReal {a : ℝ} {b : ℝ≥0∞} (ha : 0 ≤ a) (hb : b ≠ ∞) :
Ennreal.ofReal a < b ↔ a < Ennreal.toReal b :=
by
lift b to ℝ≥0 using hb
simpa [Ennreal.ofReal, Ennreal.toReal] using Real.toNnreal_lt_iff_lt_coe ha
#align ennreal.of_real_lt_iff_lt_to_real Ennreal.ofReal_lt_iff_lt_toReal
theorem le_ofReal_iff_toReal_le {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) :
a ≤ Ennreal.ofReal b ↔ Ennreal.toReal a ≤ b :=
by
lift a to ℝ≥0 using ha
simpa [Ennreal.ofReal, Ennreal.toReal] using Real.le_toNnreal_iff_coe_le hb
#align ennreal.le_of_real_iff_to_real_le Ennreal.le_ofReal_iff_toReal_le
theorem toReal_le_of_le_ofReal {a : ℝ≥0∞} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ Ennreal.ofReal b) :
Ennreal.toReal a ≤ b :=
have ha : a ≠ ∞ := ne_top_of_le_ne_top ofReal_ne_top h
(le_ofReal_iff_toReal_le ha hb).1 h
#align ennreal.to_real_le_of_le_of_real Ennreal.toReal_le_of_le_ofReal
theorem lt_ofReal_iff_toReal_lt {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) :
a < Ennreal.ofReal b ↔ Ennreal.toReal a < b :=
by
lift a to ℝ≥0 using ha
simpa [Ennreal.ofReal, Ennreal.toReal] using Real.lt_toNnreal_iff_coe_lt
#align ennreal.lt_of_real_iff_to_real_lt Ennreal.lt_ofReal_iff_toReal_lt
theorem ofReal_mul {p q : ℝ} (hp : 0 ≤ p) :
Ennreal.ofReal (p * q) = Ennreal.ofReal p * Ennreal.ofReal q := by
simp only [Ennreal.ofReal, ← coe_mul, Real.toNnreal_mul hp]
#align ennreal.of_real_mul Ennreal.ofReal_mul
theorem ofReal_mul' {p q : ℝ} (hq : 0 ≤ q) :
Ennreal.ofReal (p * q) = Ennreal.ofReal p * Ennreal.ofReal q := by
rw [mul_comm, of_real_mul hq, mul_comm]
#align ennreal.of_real_mul' Ennreal.ofReal_mul'
theorem ofReal_pow {p : ℝ} (hp : 0 ≤ p) (n : ℕ) : Ennreal.ofReal (p ^ n) = Ennreal.ofReal p ^ n :=
by rw [of_real_eq_coe_nnreal hp, ← coe_pow, ← of_real_coe_nnreal, Nnreal.coe_pow, Nnreal.coe_mk]
#align ennreal.of_real_pow Ennreal.ofReal_pow
theorem ofReal_nsmul {x : ℝ} {n : ℕ} : Ennreal.ofReal (n • x) = n • Ennreal.ofReal x := by
simp only [nsmul_eq_mul, ← of_real_coe_nat n, ← of_real_mul n.cast_nonneg]
#align ennreal.of_real_nsmul Ennreal.ofReal_nsmul
theorem ofReal_inv_of_pos {x : ℝ} (hx : 0 < x) : (Ennreal.ofReal x)⁻¹ = Ennreal.ofReal x⁻¹ := by
rw [Ennreal.ofReal, Ennreal.ofReal, ← @coe_inv (Real.toNnreal x) (by simp [hx]), coe_eq_coe,
real.to_nnreal_inv.symm]
#align ennreal.of_real_inv_of_pos Ennreal.ofReal_inv_of_pos
theorem ofReal_div_of_pos {x y : ℝ} (hy : 0 < y) :
Ennreal.ofReal (x / y) = Ennreal.ofReal x / Ennreal.ofReal y := by
rw [div_eq_mul_inv, div_eq_mul_inv, of_real_mul' (inv_nonneg.2 hy.le), of_real_inv_of_pos hy]
#align ennreal.of_real_div_of_pos Ennreal.ofReal_div_of_pos
@[simp]
theorem toNnreal_mul {a b : ℝ≥0∞} : (a * b).toNnreal = a.toNnreal * b.toNnreal :=
WithTop.untop'_zero_mul a b
#align ennreal.to_nnreal_mul Ennreal.toNnreal_mul
theorem toNnreal_mul_top (a : ℝ≥0∞) : Ennreal.toNnreal (a * ∞) = 0 := by simp
#align ennreal.to_nnreal_mul_top Ennreal.toNnreal_mul_top
theorem toNnreal_top_mul (a : ℝ≥0∞) : Ennreal.toNnreal (∞ * a) = 0 := by simp
#align ennreal.to_nnreal_top_mul Ennreal.toNnreal_top_mul
@[simp]
theorem smul_toNnreal (a : ℝ≥0) (b : ℝ≥0∞) : (a • b).toNnreal = a * b.toNnreal :=
by
change ((a : ℝ≥0∞) * b).toNnreal = a * b.to_nnreal
simp only [Ennreal.toNnreal_mul, Ennreal.toNnreal_coe]
#align ennreal.smul_to_nnreal Ennreal.smul_toNnreal
/-- `ennreal.to_nnreal` as a `monoid_hom`. -/
def toNnrealHom : ℝ≥0∞ →* ℝ≥0 where
toFun := Ennreal.toNnreal
map_one' := toNnreal_coe
map_mul' _ _ := toNnreal_mul
#align ennreal.to_nnreal_hom Ennreal.toNnrealHom
@[simp]
theorem toNnreal_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).toNnreal = a.toNnreal ^ n :=
toNnrealHom.map_pow a n
#align ennreal.to_nnreal_pow Ennreal.toNnreal_pow
@[simp]
theorem toNnreal_prod {ι : Type _} {s : Finset ι} {f : ι → ℝ≥0∞} :
(∏ i in s, f i).toNnreal = ∏ i in s, (f i).toNnreal :=
toNnrealHom.map_prod _ _
#align ennreal.to_nnreal_prod Ennreal.toNnreal_prod
/-- `ennreal.to_real` as a `monoid_hom`. -/
def toRealHom : ℝ≥0∞ →* ℝ :=
(Nnreal.toRealHom : ℝ≥0 →* ℝ).comp toNnrealHom
#align ennreal.to_real_hom Ennreal.toRealHom
@[simp]
theorem toReal_mul : (a * b).toReal = a.toReal * b.toReal :=
toRealHom.map_mul a b
#align ennreal.to_real_mul Ennreal.toReal_mul
@[simp]
theorem toReal_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).toReal = a.toReal ^ n :=
toRealHom.map_pow a n
#align ennreal.to_real_pow Ennreal.toReal_pow
@[simp]
theorem toReal_prod {ι : Type _} {s : Finset ι} {f : ι → ℝ≥0∞} :
(∏ i in s, f i).toReal = ∏ i in s, (f i).toReal :=
toRealHom.map_prod _ _
#align ennreal.to_real_prod Ennreal.toReal_prod
theorem toReal_ofReal_mul (c : ℝ) (a : ℝ≥0∞) (h : 0 ≤ c) :
Ennreal.toReal (Ennreal.ofReal c * a) = c * Ennreal.toReal a := by
rw [Ennreal.toReal_mul, Ennreal.toReal_ofReal h]
#align ennreal.to_real_of_real_mul Ennreal.toReal_ofReal_mul
theorem toReal_mul_top (a : ℝ≥0∞) : Ennreal.toReal (a * ∞) = 0 := by
rw [to_real_mul, top_to_real, mul_zero]
#align ennreal.to_real_mul_top Ennreal.toReal_mul_top
theorem toReal_top_mul (a : ℝ≥0∞) : Ennreal.toReal (∞ * a) = 0 :=
by
rw [mul_comm]
exact to_real_mul_top _
#align ennreal.to_real_top_mul Ennreal.toReal_top_mul
theorem toReal_eq_toReal (ha : a ≠ ∞) (hb : b ≠ ∞) : Ennreal.toReal a = Ennreal.toReal b ↔ a = b :=
by
lift a to ℝ≥0 using ha
lift b to ℝ≥0 using hb
simp only [coe_eq_coe, Nnreal.coe_eq, coe_to_real]
#align ennreal.to_real_eq_to_real Ennreal.toReal_eq_toReal
theorem toReal_smul (r : ℝ≥0) (s : ℝ≥0∞) : (r • s).toReal = r • s.toReal :=
by
rw [Ennreal.smul_def, smul_eq_mul, to_real_mul, coe_to_real]
rfl
#align ennreal.to_real_smul Ennreal.toReal_smul
protected theorem trichotomy (p : ℝ≥0∞) : p = 0 ∨ p = ∞ ∨ 0 < p.toReal := by
simpa only [or_iff_not_imp_left] using to_real_pos
#align ennreal.trichotomy Ennreal.trichotomy
protected theorem trichotomy₂ {p q : ℝ≥0∞} (hpq : p ≤ q) :
p = 0 ∧ q = 0 ∨
p = 0 ∧ q = ∞ ∨
p = 0 ∧ 0 < q.toReal ∨
p = ∞ ∧ q = ∞ ∨
0 < p.toReal ∧ q = ∞ ∨ 0 < p.toReal ∧ 0 < q.toReal ∧ p.toReal ≤ q.toReal :=
by
rcases eq_or_lt_of_le (bot_le : 0 ≤ p) with ((rfl : 0 = p) | (hp : 0 < p))
· simpa using q.trichotomy
rcases eq_or_lt_of_le (le_top : q ≤ ∞) with (rfl | hq)
· simpa using p.trichotomy
repeat' right
have hq' : 0 < q := lt_of_lt_of_le hp hpq
have hp' : p < ∞ := lt_of_le_of_lt hpq hq
simp [Ennreal.toReal_le_toReal hp'.ne hq.ne, Ennreal.toReal_pos_iff, hpq, hp, hp', hq', hq]
#align ennreal.trichotomy₂ Ennreal.trichotomy₂
protected theorem dichotomy (p : ℝ≥0∞) [Fact (1 ≤ p)] : p = ∞ ∨ 1 ≤ p.toReal :=
haveI : p = ⊤ ∨ 0 < p.to_real ∧ 1 ≤ p.to_real := by
simpa using Ennreal.trichotomy₂ (Fact.out _ : 1 ≤ p)
this.imp_right fun h => h.2
#align ennreal.dichotomy Ennreal.dichotomy
theorem toReal_pos_iff_ne_top (p : ℝ≥0∞) [Fact (1 ≤ p)] : 0 < p.toReal ↔ p ≠ ∞ :=
⟨fun h hp =>
let this : (0 : ℝ) ≠ 0 := top_to_real ▸ (hp ▸ h.Ne : 0 ≠ ∞.toReal)
this rfl,
fun h => zero_lt_one.trans_le (p.dichotomy.resolve_left h)⟩
#align ennreal.to_real_pos_iff_ne_top Ennreal.toReal_pos_iff_ne_top
theorem toNnreal_inv (a : ℝ≥0∞) : a⁻¹.toNnreal = a.toNnreal⁻¹ :=
by
induction a using WithTop.recTopCoe; · simp
rcases eq_or_ne a 0 with (rfl | ha); · simp
rw [← coe_inv ha, to_nnreal_coe, to_nnreal_coe]
#align ennreal.to_nnreal_inv Ennreal.toNnreal_inv
theorem toNnreal_div (a b : ℝ≥0∞) : (a / b).toNnreal = a.toNnreal / b.toNnreal := by
rw [div_eq_mul_inv, to_nnreal_mul, to_nnreal_inv, div_eq_mul_inv]
#align ennreal.to_nnreal_div Ennreal.toNnreal_div
theorem toReal_inv (a : ℝ≥0∞) : a⁻¹.toReal = a.toReal⁻¹ :=
by
simp_rw [Ennreal.toReal]
norm_cast
exact to_nnreal_inv a
#align ennreal.to_real_inv Ennreal.toReal_inv
theorem toReal_div (a b : ℝ≥0∞) : (a / b).toReal = a.toReal / b.toReal := by
rw [div_eq_mul_inv, to_real_mul, to_real_inv, div_eq_mul_inv]
#align ennreal.to_real_div Ennreal.toReal_div
theorem ofReal_prod_of_nonneg {s : Finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) :
Ennreal.ofReal (∏ i in s, f i) = ∏ i in s, Ennreal.ofReal (f i) :=
by
simp_rw [Ennreal.ofReal, ← coe_finset_prod, coe_eq_coe]
exact Real.toNnreal_prod_of_nonneg hf
#align ennreal.of_real_prod_of_nonneg Ennreal.ofReal_prod_of_nonneg
@[simp]
theorem toNnreal_bit0 {x : ℝ≥0∞} : (bit0 x).toNnreal = bit0 x.toNnreal :=
by
induction x using WithTop.recTopCoe
· simp
· exact to_nnreal_add coe_ne_top coe_ne_top
#align ennreal.to_nnreal_bit0 Ennreal.toNnreal_bit0
@[simp]
theorem toNnreal_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) : (bit1 x).toNnreal = bit1 x.toNnreal := by
simp [bit1, bit1, to_nnreal_add (by rwa [Ne.def, bit0_eq_top_iff]) Ennreal.one_ne_top]
#align ennreal.to_nnreal_bit1 Ennreal.toNnreal_bit1
@[simp]
theorem toReal_bit0 {x : ℝ≥0∞} : (bit0 x).toReal = bit0 x.toReal := by simp [Ennreal.toReal]
#align ennreal.to_real_bit0 Ennreal.toReal_bit0
@[simp]
theorem toReal_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) : (bit1 x).toReal = bit1 x.toReal := by
simp [Ennreal.toReal, hx_top]
#align ennreal.to_real_bit1 Ennreal.toReal_bit1
@[simp]
theorem ofReal_bit0 (r : ℝ) : Ennreal.ofReal (bit0 r) = bit0 (Ennreal.ofReal r) := by
simp [Ennreal.ofReal]
#align ennreal.of_real_bit0 Ennreal.ofReal_bit0
@[simp]
theorem ofReal_bit1 {r : ℝ} (hr : 0 ≤ r) : Ennreal.ofReal (bit1 r) = bit1 (Ennreal.ofReal r) :=
(ofReal_add (by simp [hr]) zero_le_one).trans (by simp [Real.toNnreal_one, bit1])
#align ennreal.of_real_bit1 Ennreal.ofReal_bit1
end Real
section infᵢ
variable {ι : Sort _} {f g : ι → ℝ≥0∞}
theorem infᵢ_add : infᵢ f + a = ⨅ i, f i + a :=
le_antisymm (le_infᵢ fun i => add_le_add (infᵢ_le _ _) <| le_rfl)
(tsub_le_iff_right.1 <| le_infᵢ fun i => tsub_le_iff_right.2 <| infᵢ_le _ _)
#align ennreal.infi_add Ennreal.infᵢ_add
theorem supᵢ_sub : (⨆ i, f i) - a = ⨆ i, f i - a :=
le_antisymm (tsub_le_iff_right.2 <| supᵢ_le fun i => tsub_le_iff_right.1 <| le_supᵢ _ i)
(supᵢ_le fun i => tsub_le_tsub (le_supᵢ _ _) (le_refl a))
#align ennreal.supr_sub Ennreal.supᵢ_sub
theorem sub_infᵢ : (a - ⨅ i, f i) = ⨆ i, a - f i :=
by
refine' eq_of_forall_ge_iff fun c => _
rw [tsub_le_iff_right, add_comm, infi_add]
simp [tsub_le_iff_right, sub_eq_add_neg, add_comm]
#align ennreal.sub_infi Ennreal.sub_infᵢ
theorem infₛ_add {s : Set ℝ≥0∞} : infₛ s + a = ⨅ b ∈ s, b + a := by simp [infₛ_eq_infᵢ, infi_add]
#align ennreal.Inf_add Ennreal.infₛ_add
theorem add_infᵢ {a : ℝ≥0∞} : a + infᵢ f = ⨅ b, a + f b := by
rw [add_comm, infi_add] <;> simp [add_comm]
#align ennreal.add_infi Ennreal.add_infᵢ
/- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (a a') -/
theorem infᵢ_add_infᵢ (h : ∀ i j, ∃ k, f k + g k ≤ f i + g j) : infᵢ f + infᵢ g = ⨅ a, f a + g a :=
suffices (⨅ a, f a + g a) ≤ infᵢ f + infᵢ g from
le_antisymm (le_infᵢ fun a => add_le_add (infᵢ_le _ _) (infᵢ_le _ _)) this
calc
(⨅ a, f a + g a) ≤ ⨅ (a) (a'), f a + g a' :=
le_infᵢ fun a =>
le_infᵢ fun a' =>
let ⟨k, h⟩ := h a a'
infᵢ_le_of_le k h
_ = infᵢ f + infᵢ g := by simp [add_infi, infi_add]
#align ennreal.infi_add_infi Ennreal.infᵢ_add_infᵢ
theorem infᵢ_sum {f : ι → α → ℝ≥0∞} {s : Finset α} [Nonempty ι]
(h : ∀ (t : Finset α) (i j : ι), ∃ k, ∀ a ∈ t, f k a ≤ f i a ∧ f k a ≤ f j a) :
(⨅ i, ∑ a in s, f i a) = ∑ a in s, ⨅ i, f i a :=
by
induction' s using Finset.induction_on with a s ha ih
· simp
have : ∀ i j : ι, ∃ k : ι, (f k a + ∑ b in s, f k b) ≤ f i a + ∑ b in s, f j b :=
by
intro i j
obtain ⟨k, hk⟩ := h (insert a s) i j
exact
⟨k,
add_le_add (hk a (Finset.mem_insert_self _ _)).left <|
Finset.sum_le_sum fun a ha => (hk _ <| Finset.mem_insert_of_mem ha).right⟩
simp [ha, ih.symm, infi_add_infi this]
#align ennreal.infi_sum Ennreal.infᵢ_sum
/-- If `x ≠ 0` and `x ≠ ∞`, then right multiplication by `x` maps infimum to infimum.
See also `ennreal.infi_mul` that assumes `[nonempty ι]` but does not require `x ≠ 0`. -/
theorem infᵢ_mul_of_ne {ι} {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h0 : x ≠ 0) (h : x ≠ ∞) :
infᵢ f * x = ⨅ i, f i * x :=
le_antisymm mul_right_mono.map_infi_le
((Ennreal.div_le_iff_le_mul (Or.inl h0) <| Or.inl h).mp <|
le_infᵢ fun i => (Ennreal.div_le_iff_le_mul (Or.inl h0) <| Or.inl h).mpr <| infᵢ_le _ _)
#align ennreal.infi_mul_of_ne Ennreal.infᵢ_mul_of_ne
/-- If `x ≠ ∞`, then right multiplication by `x` maps infimum over a nonempty type to infimum. See
also `ennreal.infi_mul_of_ne` that assumes `x ≠ 0` but does not require `[nonempty ι]`. -/
theorem infᵢ_mul {ι} [Nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) :
infᵢ f * x = ⨅ i, f i * x := by
by_cases h0 : x = 0
· simp only [h0, mul_zero, infᵢ_const]
· exact infi_mul_of_ne h0 h
#align ennreal.infi_mul Ennreal.infᵢ_mul
/-- If `x ≠ ∞`, then left multiplication by `x` maps infimum over a nonempty type to infimum. See
also `ennreal.mul_infi_of_ne` that assumes `x ≠ 0` but does not require `[nonempty ι]`. -/
theorem mul_infᵢ {ι} [Nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) :
x * infᵢ f = ⨅ i, x * f i := by simpa only [mul_comm] using infi_mul h
#align ennreal.mul_infi Ennreal.mul_infᵢ
/-- If `x ≠ 0` and `x ≠ ∞`, then left multiplication by `x` maps infimum to infimum.
See also `ennreal.mul_infi` that assumes `[nonempty ι]` but does not require `x ≠ 0`. -/
theorem mul_infᵢ_of_ne {ι} {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h0 : x ≠ 0) (h : x ≠ ∞) :
x * infᵢ f = ⨅ i, x * f i := by simpa only [mul_comm] using infi_mul_of_ne h0 h
#align ennreal.mul_infi_of_ne Ennreal.mul_infᵢ_of_ne
/-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/
end infᵢ
section supᵢ
@[simp]
theorem supᵢ_eq_zero {ι : Sort _} {f : ι → ℝ≥0∞} : (⨆ i, f i) = 0 ↔ ∀ i, f i = 0 :=
supᵢ_eq_bot
#align ennreal.supr_eq_zero Ennreal.supᵢ_eq_zero
@[simp]
theorem supᵢ_zero_eq_zero {ι : Sort _} : (⨆ i : ι, (0 : ℝ≥0∞)) = 0 := by simp
#align ennreal.supr_zero_eq_zero Ennreal.supᵢ_zero_eq_zero
theorem sup_eq_zero {a b : ℝ≥0∞} : a ⊔ b = 0 ↔ a = 0 ∧ b = 0 :=
sup_eq_bot_iff
#align ennreal.sup_eq_zero Ennreal.sup_eq_zero
theorem supᵢ_coe_nat : (⨆ n : ℕ, (n : ℝ≥0∞)) = ∞ :=
(supᵢ_eq_top _).2 fun b hb => Ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb)
#align ennreal.supr_coe_nat Ennreal.supᵢ_coe_nat
end supᵢ
end Ennreal
namespace Set
namespace OrdConnected
variable {s : Set ℝ} {t : Set ℝ≥0} {u : Set ℝ≥0∞}
theorem preimage_coe_nnreal_ennreal (h : u.OrdConnected) : (coe ⁻¹' u : Set ℝ≥0).OrdConnected :=
h.preimage_mono Ennreal.coe_mono
#align set.ord_connected.preimage_coe_nnreal_ennreal Set.OrdConnected.preimage_coe_nnreal_ennreal
theorem image_coe_nnreal_ennreal (h : t.OrdConnected) : (coe '' t : Set ℝ≥0∞).OrdConnected :=
by
refine' ⟨ball_image_iff.2 fun x hx => ball_image_iff.2 fun y hy z hz => _⟩
rcases Ennreal.le_coe_iff.1 hz.2 with ⟨z, rfl, hzy⟩
exact mem_image_of_mem _ (h.out hx hy ⟨Ennreal.coe_le_coe.1 hz.1, Ennreal.coe_le_coe.1 hz.2⟩)
#align set.ord_connected.image_coe_nnreal_ennreal Set.OrdConnected.image_coe_nnreal_ennreal
theorem preimage_ennreal_ofReal (h : u.OrdConnected) : (Ennreal.ofReal ⁻¹' u).OrdConnected :=
h.preimage_coe_nnreal_ennreal.preimage_real_to_nnreal
#align set.ord_connected.preimage_ennreal_of_real Set.OrdConnected.preimage_ennreal_ofReal
theorem image_ennreal_ofReal (h : s.OrdConnected) : (Ennreal.ofReal '' s).OrdConnected := by
simpa only [image_image] using h.image_real_to_nnreal.image_coe_nnreal_ennreal
#align set.ord_connected.image_ennreal_of_real Set.OrdConnected.image_ennreal_ofReal
end OrdConnected
end Set
namespace Tactic
open Positivity
private theorem nnreal_coe_pos {r : ℝ≥0} : 0 < r → 0 < (r : ℝ≥0∞) :=
Ennreal.coe_pos.2
#align tactic.nnreal_coe_pos tactic.nnreal_coe_pos
/-- Extension for the `positivity` tactic: cast from `ℝ≥0` to `ℝ≥0∞`. -/
@[positivity]
unsafe def positivity_coe_nnreal_ennreal : expr → tactic strictness
| q(@coe _ _ $(inst) $(a)) => do
unify inst q(@coeToLift _ _ <| @coeBase _ _ Ennreal.hasCoe)
let positive p ← core a
-- We already know `0 ≤ r` for all `r : ℝ≥0∞`
positive <$>
mk_app `` nnreal_coe_pos [p]
| e =>
pp e >>=
fail ∘ format.bracket "The expression " " is not of the form `(r : ℝ≥0∞)` for `r : ℝ≥0`"
#align tactic.positivity_coe_nnreal_ennreal tactic.positivity_coe_nnreal_ennreal
private theorem ennreal_of_real_pos {r : ℝ} : 0 < r → 0 < Ennreal.ofReal r :=
Ennreal.ofReal_pos.2
#align tactic.ennreal_of_real_pos tactic.ennreal_of_real_pos
/-- Extension for the `positivity` tactic: `ennreal.of_real` is positive if its input is. -/
@[positivity]
unsafe def positivity_ennreal_of_real : expr → tactic strictness
| q(Ennreal.ofReal $(r)) => do
let positive p ← core r
positive <$> mk_app `` ennreal_of_real_pos [p]
|-- This case is handled by `tactic.positivity_canon`
e =>
pp e >>= fail ∘ format.bracket "The expression `" "` is not of the form `ennreal.of_real r`"
#align tactic.positivity_ennreal_of_real tactic.positivity_ennreal_of_real
end Tactic
-/
|
module Imports where
import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.Cont
import Control.Monad.Fix
import Control.Monad.Identity
import Control.Monad.RWS
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer
import Data.Bits
import Data.Bool
import Data.Char
import Data.Complex
import Data.Dynamic
import Data.Either
import Data.Eq
import Data.Fixed
import Data.Function
import Data.Graph
import Data.Int
import Data.Ix
import Data.List
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import Data.Tree
import Data.Tuple
import Data.Typeable
import Data.Word
import Prelude hiding (IO,putStr,putStrLn,getLine,readLn,print,readIO,readFile,writeFile,appendFile)
import PureIO as IO
import ShowFun
import Test.QuickCheck
import Text.Printf
-- | Run the given command and then show the output. This constraint
-- is to aid communication between mueval and tryhaskell.
runTryHaskellIO :: (Read b,Show b)
=> ([String],[(FilePath,String)])
-> IO b
-> Either (Interrupt,([String],[(FilePath,String)]))
(String,([String],[(FilePath,String)]))
runTryHaskellIO (is,fs) m =
case runIO (Input is (M.fromList fs)) m of
(Left i,out) -> Left (i,convert out)
(Right r,out) -> Right (show r,convert out)
where convert (Output os fs) = (os,M.toList fs)
|
import group_theory.subgroup data.set.finite
noncomputable theory
open set classical
local attribute [instance] prop_decidable
structure partition (S : Type*) :=
(blocks : set (set S))
(nonempty : ∀ block ∈ blocks, block ≠ ∅)
(covers : univ = ⋃ (s ∈ blocks), s)
(disj : ∀ s t ∈ blocks, s ∩ t ≠ ∅ → s = t)
private lemma not_empty {α} {S : set α} (h : S ≠ ∅) : ∃ s : α, s ∈ S :=
begin
by_contra hs, push_neg at hs,
exact (push_neg.not_eq _ _).1 h (set.eq_empty_iff_forall_not_mem.2 hs)
end
namespace action
structure laction (G : Type*) [group G] (S : Type*) :=
(to_fun : G → S → S) (map_one : ∀ s : S, to_fun 1 s = s)
(map_assoc : ∀ g h : G, ∀ s : S, to_fun g (to_fun h s) = to_fun (g * h) s)
variables {G : Type*} [group G] {S : Type*}
variables {μ : laction G S}
-- Example of a left action - The natural left action of a group acting on itself
def natural_self_laction : laction G G :=
{ to_fun := λ g h, g * h,
map_one := one_mul,
map_assoc := λ _ _ _, (mul_assoc _ _ _).symm }
lemma laction_mul_inv_cancel {g h : G} {s : S} :
μ.1 g s = μ.1 h s ↔ s = μ.1 (g⁻¹ * h) s :=
begin
split; intro hgh,
{ conv_lhs { rw ←μ.2 s },
rw [←(mul_inv_self g⁻¹), ←μ.3, ←μ.3, ←hgh, inv_inv] },
{ conv_lhs { rw [hgh, μ.3, ←mul_assoc, mul_inv_self, one_mul] } }
end
lemma laction_mul_inv {g : G} {s t : S} : μ.1 g s = t ↔ s = μ.1 g⁻¹ t :=
begin
split; intro h,
rw [←h, μ.3, mul_left_inv, μ.2],
rw [h, μ.3, mul_right_inv, μ.2]
end
@[reducible] def orbit (μ : laction G S) (s : S) : set S :=
{ m : S | ∃ g : G, m = μ.1 g s }
/-- An element of `G` is in its own orbit -/
lemma self_mem_orbit (s : S) : s ∈ orbit μ s := ⟨1, (μ.2 s).symm⟩
/-- The set of orbits of a set forms a partition -/
def orbit_partition : partition S :=
{ blocks := { o : set S | ∃ s : S, o = orbit μ s },
nonempty := λ B hB hemp, by { rcases hB with ⟨s, rfl⟩,
exact (eq_empty_iff_forall_not_mem.1 hemp s) (self_mem_orbit s) },
covers := ext $ λ x,
⟨ λ hx, mem_Union.2 ⟨orbit μ x, mem_Union.2 ⟨⟨x, rfl⟩, ⟨1, (μ.2 _).symm⟩⟩⟩,
λ hx, mem_univ x ⟩,
disj :=
begin
rintros _ _ ⟨s₁, rfl⟩ ⟨s₂, rfl⟩ hndisj,
rcases not_empty hndisj with ⟨x, hxs, hxt⟩,
ext y, split,
all_goals { intro hy,
cases hxs with g₁ hg₁, cases hxt with g₂ hg₂, cases hy with g hg },
{ have : μ.1 g₁⁻¹ (μ.1 g₁ s₁) = μ.1 g₁⁻¹ (μ.1 g₂ s₂),
rwa [eq.trans hg₁.symm hg₂],
rw [μ.3, μ.3, inv_mul_self _, μ.2] at this,
refine ⟨g * (g₁⁻¹ * g₂), _⟩,
rw [hg, ←μ.3, this] },
{ have : μ.1 g₂⁻¹ (μ.1 g₂ s₂) = μ.1 g₂⁻¹ (μ.1 g₁ s₁),
rwa [eq.trans hg₁.symm hg₂],
rw [μ.3, μ.3, inv_mul_self _, μ.2] at this,
refine ⟨g * (g₂⁻¹ * g₁), _⟩,
rw [hg, ←μ.3, this] }
end }
/- We define the stabilizer of an action is as a subgroup -/
@[reducible]
def stabilizer (μ : laction G S) (s : S) : subgroup G :=
{ carrier := { g : G | μ.1 g s = s },
one_mem' := μ.2 _,
mul_mem' := λ _ _ hg hh, by { rw mem_set_of_eq at *, rw [←μ.3, hh, hg] },
inv_mem' := λ x hx,
begin
rw mem_set_of_eq at *,
conv_lhs { rw ←hx },
rw [μ.3, inv_mul_self _, μ.2]
end }
-- Some lemmas about orbits that are useful
lemma in_orbit_of_in_same_orbit {s₁ s₂ s₃ : S} :
s₁ ∈ orbit μ s₃ ∧ s₂ ∈ orbit μ s₃ → s₁ ∈ orbit μ s₂ :=
begin
rintro ⟨⟨g₁, hg₁⟩, ⟨g₂, hg₂⟩⟩,
refine ⟨g₁ * g₂⁻¹, _⟩,
rw [hg₁, hg₂, μ.3, mul_assoc, inv_mul_self, mul_one]
end
lemma in_orbit_of_inv {s₁ s₂ : S} {g : G} (h : s₁ = μ.1 g s₂) :
s₂ = μ.1 g⁻¹ s₁ := by rw [h, μ.3, inv_mul_self, μ.2]
@[reducible]
def is_conjugate (H K : subgroup G) :=
∃ g : G, { c | ∃ h ∈ H, c = g⁻¹ * h * g } = K
/-- If `H` is the conjugate of `K`, then `K` is the conjugate of `H` -/
lemma is_conjugate_comm {H K : subgroup G} (h : is_conjugate H K) :
is_conjugate K H :=
begin
cases h with g hg, refine ⟨g⁻¹, _⟩,
ext, split; intro hx,
{ rcases hx with ⟨h, hh₀, hh₁⟩,
change h ∈ (K : set G) at hh₀,
rw ←hg at hh₀,
rcases hh₀ with ⟨k, hk₀, hk₁⟩,
rw [hh₁, hk₁], simp [mul_assoc, hk₀] },
{ rw mem_set_of_eq,
refine ⟨g⁻¹ * x * g, _, by simp [mul_assoc]⟩,
show g⁻¹ * x * g ∈ (K : set G),
rw ←hg, exact ⟨x, hx, rfl⟩ }
end
/-- If two elements are in the same orbit, then their stabilizers are conjugates -/
theorem conjugate_stabilizer_of_in_same_orbit {s₁ s₂ s₃ : S}
(h : s₁ ∈ orbit μ s₃ ∧ s₂ ∈ orbit μ s₃) :
is_conjugate (stabilizer μ s₁) (stabilizer μ s₂) :=
begin
cases in_orbit_of_in_same_orbit h with g hg,
refine ⟨g, _⟩,
ext, split; intro hx,
{ show x ∈ (stabilizer μ s₂).carrier, dsimp,
rcases hx with ⟨h, hh₀, hh₁⟩,
rw [hh₁, ←μ.3, ←μ.3, ←hg,
(show μ.to_fun h s₁ = s₁, by exact hh₀), hg, μ.3, inv_mul_self, μ.2] },
{ change x ∈ (stabilizer μ s₂).carrier at hx, dsimp at hx,
exact ⟨g * x * g⁻¹, show g * x * g⁻¹ ∈ (stabilizer μ s₁).carrier, by dsimp;
rw [←μ.3, ←(in_orbit_of_inv hg), ←μ.3, hx, hg], by simp [mul_assoc]⟩ }
end
end action
namespace order
-- We need Lagrange's theorem for Orbit-Stabilizer
/- We will use the cardinality function `fintype.card` defined for fintypes.
While we will prove most theorems in this section for general groups, we will
only consider finite groups when considering the cardinality of the group in
question. This is reflected by the [fintype G] tag in theorems regarding
cardinality.
TODO : refactor the card stuff -/
open function fintype
variables {G : Type*} [group G]
variables {H : subgroup G}
@[reducible]
def lcoset (g : G) (H : subgroup G) : set G :=
{ k : G | ∃ h ∈ H, k = g * h }
notation g ` • ` : 70 H : 70 := lcoset g H
lemma self_mem_coset (a : G) (H : subgroup G): a ∈ a • H :=
⟨1, H.one_mem, (mul_one a).symm⟩
/-- Two cosets `a • H`, `b • H` are equal if and only if `b⁻¹ * a ∈ H` -/
theorem lcoset_eq {a b : G} :
a • H = b • H ↔ b⁻¹ * a ∈ H :=
begin
split; intro h,
{ replace h : a ∈ b • H, rw ←h, exact self_mem_coset a H,
rcases h with ⟨g, hg₀, hg₁⟩,
rw hg₁, simp [hg₀] },
{ ext, split; intro hx,
{ rcases hx with ⟨g, hg₀, hg₁⟩, rw hg₁,
exact ⟨b⁻¹ * a * g, H.mul_mem h hg₀, by simp [mul_assoc]⟩ },
{ rcases hx with ⟨g, hg₀, hg₁⟩, rw hg₁,
refine ⟨a⁻¹ * b * g, H.mul_mem _ hg₀, by simp [mul_assoc]⟩,
convert H.inv_mem h, simp } }
end
-- A corollary of this is a • H = H iff a ∈ H
/-- The coset of `H`, `1 • H` equals `H` -/
theorem lcoset_of_one : 1 • H = H :=
begin
ext, split; intro hx,
{ rcases hx with ⟨h, hh₀, hh₁⟩,
rwa [hh₁, one_mul] },
{ exact ⟨x, hx, (one_mul x).symm⟩ }
end
/-- A left coset `a • H` equals `H` if and only if `a ∈ H` -/
theorem lcoset_of_mem {a : G} :
a • H = H ↔ a ∈ H := by rw [←lcoset_of_one, lcoset_eq]; simp
/-- Two left cosets `a • H` and `b • H` are equal if they are not disjoint -/
theorem lcoset_digj {a b c : G} (ha : c ∈ a • H) (hb : c ∈ b • H) :
a • H = b • H :=
begin
rcases ha with ⟨g₀, hg₀, hca⟩,
rcases hb with ⟨g₁, hg₁, hcb⟩,
rw lcoset_eq, rw (show a = c * g₀⁻¹, by simp [hca, mul_assoc]),
rw (show b⁻¹ = g₁ * c⁻¹,
by rw (show b = c * g₁⁻¹, by simp [hcb, mul_assoc]); simp),
suffices : g₁ * g₀⁻¹ ∈ H, simp [mul_assoc, this],
exact H.mul_mem hg₁ (H.inv_mem hg₀)
end
-- Now we would like to prove that all lcosets have the same order
private def aux_map (a : G) (H : subgroup G) : H → a • H :=
λ h, ⟨a * h, h, h.2, rfl⟩
private lemma aux_map_biject {a : G} : bijective $ aux_map a H :=
begin
split,
{ intros x y hxy,
suffices : (x : G) = y,
{ ext, assumption },
{ simp [aux_map] at hxy, assumption } },
{ rintro ⟨y, y_prop⟩,
rcases y_prop with ⟨h, hh₀, hh₁⟩,
refine ⟨⟨h, hh₀⟩, by simp [aux_map, hh₁]⟩ }
end
/-- There is a bijection between `H` and its left cosets -/
theorem lcoset_equiv {a : G} : H ≃ a • H :=
equiv.of_bijective (aux_map a H) aux_map_biject
/-- The cardinality of `H` equals its left cosets-/
lemma eq_card_of_lcoset {a : G} [fintype G] : card H = card (a • H) :=
begin
rw card_eq, by_contra h,
exact not_nonempty_iff_imp_false.1 h lcoset_equiv
end
/-- The cardinality of all left cosets are equal -/
theorem card_of_lcoset_eq {a b : G} [fintype G] :
card (a • H) = card (b • H) := by iterate 2 { rw ←eq_card_of_lcoset }
/-- The left cosets of a subgroup `H` form a partition -/
def lcoset_partition (G : Type*) [group G] (H : subgroup G) : partition G :=
{ blocks := { B | ∃ g : G, B = g • H },
nonempty := λ B hB, let ⟨g, hg⟩ := hB in
λ h, by rw [←(mem_empty_eq g), ←h, hg]; exact self_mem_coset g H,
covers := ext $ λ x,
⟨λ _, mem_Union.2 ⟨x • H, mem_Union.2 ⟨⟨x, rfl⟩, self_mem_coset x H⟩⟩,
λ _, mem_univ x⟩,
disj := λ s t hs ht hndisj,
let ⟨g₀, hg₀⟩ := hs in
let ⟨g₁, hg₁⟩ := ht in
let ⟨k, hks, hkt⟩ := not_empty hndisj in
begin
rw [hg₀, hg₁],
rw hg₀ at hks, rw hg₁ at hkt,
exact lcoset_digj hks hkt,
end }
-- Now we prove that the card of a set equals the sum of the card of blocks
private def aux_map' {α} [fintype α] (p : partition α) :
α → ⋃ (b ∈ p.blocks), b := λ a, ⟨a, p.3 ▸ mem_univ _⟩
private lemma aux_map'_biject {α} [fintype α] (p : partition α) :
bijective $ aux_map' p :=
⟨λ _ _ _, by finish [aux_map'], λ ⟨y, y_prop⟩, ⟨y, by unfold aux_map'⟩⟩
lemma Union_blocks_equiv {α} [fintype α] (p : partition α) :
α ≃ ⋃ (b ∈ p.blocks), b :=
equiv.of_bijective (aux_map' p) (aux_map'_biject p)
/-- The cardinality of a fintype `α` equals the cardinality of its partition -/
theorem eq_card_of_partition {α} [fintype α] (p : partition α) :
card α = card ⋃ (b ∈ p.blocks), b :=
begin
rw card_eq, by_contra h,
refine not_nonempty_iff_imp_false.1 h (Union_blocks_equiv p)
end
-- Thanks to Carl for these proofs!
lemma bind_of_partition_eq_univ {α} [fintype α] (p : partition α) :
p.blocks.to_finset.bind (λ s, s.to_finset) = finset.univ :=
begin
ext, split; intro ha,
{ exact finset.mem_univ _ },
{ rw finset.mem_bind,
have := mem_univ a, rw [p.3, mem_Union] at this,
cases this with s hs,
rw mem_Union at hs,
cases hs with hs₀ hs₁,
refine ⟨s, mem_to_finset.2 hs₀, mem_to_finset.2 hs₁⟩
}
end
lemma disjoint_finset_of_disjoint {α} [fintype α] {s t : set α}
(h : disjoint s t) : disjoint s.to_finset t.to_finset :=
begin
intros a hinter,
have hset : a ∈ ∅,
{ rw [←bot_eq_empty, ←le_bot_iff.mp h],
apply (mem_inter_iff a s t).mpr ,
split,
exact mem_to_finset.mp (finset.mem_of_mem_inter_left hinter),
exact mem_to_finset.mp (finset.mem_of_mem_inter_right hinter) },
exfalso, exact not_mem_empty a hset
end
/-- The cardinality of a fintype `α` equals the sum of cardinalities of blocks
in its partition -/
theorem card_eq_sum_partition {α} [fintype α] (p : partition α) :
card α = p.blocks.to_finset.sum (λ s, card s) :=
begin
suffices : card α = p.blocks.to_finset.sum (λ s, s.to_finset.card),
{ finish [this] },
conv_rhs { congr, skip, funext, rw finset.card_eq_sum_ones },
rw [←finset.sum_bind _, ←finset.card_eq_sum_ones,
bind_of_partition_eq_univ p],
exact finset.card_univ.symm,
intros s hs t ht hst,
apply disjoint_finset_of_disjoint,
suffices : s ∩ t = ∅, simp [disjoint, subset_empty_iff, this],
by_contra hemp,
exact hst (p.4 s t (mem_to_finset.mp hs) (mem_to_finset.mp ht) hemp)
end
/-- Let `H` be a subgroup of the finite group `G`, then the cardinality of `G`
equals the cardinality of `H` multiplied with the number of left cosets of `H` -/
theorem lagrange [fintype G] :
card G = card { B | ∃ g : G, B = g • H } * card H :=
begin
rw card_eq_sum_partition (lcoset_partition G H),
dsimp [lcoset_partition],
convert finset.sum_const_nat _, exact (to_finset_card _).symm,
intros _ hx,
rcases mem_to_finset.1 hx with ⟨g, rfl⟩,
exact (@eq_card_of_lcoset _ _ H g _).symm
end
end order
namespace action
open function fintype
variables {G : Type*} [group G] {S : Type*}
variables {μ : laction G S}
-- For the Orbit-Stabilizer theorem, the general idea is to show that there is a
-- bijection between the orbit of some g ∈ G and the left cosets of its stabilizer.
-- With that it the theorem follows from Lagrange's theorem
private structure extract_struct {μ : laction G S} {a : S} (s : orbit μ a) :=
(val : G) (prop : s.1 = μ.to_fun val a)
@[reducible] private def extract {μ : laction G S} {a : S} (s : orbit μ a) :
extract_struct s := ⟨some s.2, some_spec s.2⟩
@[reducible] private def aux_map (μ : laction G S) (a : S) :
orbit μ a → { s | ∃ h : G, s = h • stabilizer μ a } :=
λ s, ⟨(extract s).1 • stabilizer μ a, (extract s).1, rfl⟩
private lemma aux_map_biject {a : S} : bijective $ aux_map μ a :=
begin
split,
{ rintro ⟨x, hx⟩ ⟨y, hy⟩ hxy,
rw [subtype.mk.inj_eq, order.lcoset_eq] at hxy,
change ((extract ⟨y, hy⟩).val)⁻¹ * (extract ⟨x, hx⟩).val ∈
{ g : G | μ.1 g a = a } at hxy,
rw [mem_set_of_eq, ←μ.3, ←(extract ⟨x, hx⟩).2,
@laction_mul_inv _ _ _ μ _ x a, inv_inv, ←(extract ⟨y, hy⟩).2] at hxy,
simp only [hxy] },
{ rintro ⟨_, g, hg⟩, refine ⟨⟨μ.1 g a, g, rfl⟩, _⟩,
rw [subtype.mk.inj_eq, hg, order.lcoset_eq],
show g⁻¹ * (extract ⟨μ.to_fun g a, _⟩).val ∈ { g : G | μ.1 g a = a },
rw [mem_set_of_eq, ←μ.3, ←(extract ⟨μ.to_fun g a, _⟩).2,
μ.3, mul_left_inv, μ.2] }
end
-- With this function defined, we see that the cardinality of orbit s equals
-- the number of left cosets of stabilizer s
lemma finite_orbit [fintype G] {a : S} : finite (orbit μ a) :=
begin
split, split,
swap,
{ apply finset.image,
exact λ g, ⟨μ.1 g a, g, rfl⟩,
exact (univ : set G).to_finset },
{ simp, -- Nonterminating simp! I promise I will fix it!
rintro x ⟨g, rfl⟩,
refine ⟨g, rfl⟩ }
end
lemma card_orbit_eq_num_lcoset [fintype G] {a : S} :
@card (orbit μ a) finite_orbit.fintype = card { s | ∃ h : G, s = h • stabilizer μ a } :=
begin
rw card_eq, by_contra h,
refine not_nonempty_iff_imp_false.1 h
(equiv.of_bijective (aux_map μ a) aux_map_biject)
end
/-- Orbit-Stabilizer : The cardinality of a finite group `G` given a laction `μ`
on some `S` equals the cardinality of the orbit of `s` multiplied by the
cardinality of the stabilizer of `s` for any `s : S` -/
theorem orbit_stabilizer [fintype G] {a : S} (μ : laction G S) :
card G = @card (orbit μ a) finite_orbit.fintype * card (stabilizer μ a) :=
by rw card_orbit_eq_num_lcoset; exact order.lagrange
-- Let's define the centralizer
/-- A group (left) acts on itself by conjugation -/
def conj_laction : laction G G :=
{ to_fun := λ g h, g * h * g⁻¹,
map_one := by simp,
map_assoc := λ g h k, by simp [mul_assoc] }
/-- The centralizer of `g` is the stabilizer of `g` with the conjugate action -/
@[reducible] def centralizer (g : G) : subgroup G := stabilizer conj_laction g
/-- Elements of the centralizer of `g : G` commutes with `g` -/
theorem comm_of_mem_centralizer {g h : G} (hc : h ∈ centralizer g) :
g * h = h * g :=
begin
change h * g * h⁻¹ = g at hc,
conv_lhs { rw [←hc] }, simp
end
-- The conjugate class of `g` is the orbit of `g` with the conjugate action
-- the class equation of groups
def center (G : Type*) [group G] : set G := { x : G | ∀ y : G, x * y = y * x }
def conj_class (g : G) : set G := orbit conj_laction g
def index_subgroup [fintype G] (H : subgroup G) : ℕ := card G / card H
lemma comm_of_mem_center {g h : G} (hc : g ∈ center G) : g * h = h * g :=
begin
rw center at hc,
rw mem_set_of_eq at hc,
exact hc h
end
lemma mem_conj_class_self {g : G} : g ∈ conj_class g :=
begin
simp only [conj_class, conj_laction, mem_set_of_eq],
use g,
rw [mul_assoc, mul_right_inv, mul_one],
end
lemma orbit_card_one_of_mem_center [fintype G] (g : G) :
g ∈ (center G) → card (conj_class g) = 1 :=
begin
intro h,
apply finset.card_eq_one.mpr,
use g,
{ exact mem_conj_class_self },
ext ⟨a, ha⟩, split,
{ simp only [forall_prop_of_true, finset.mem_univ, finset.mem_singleton],
congr,
rcases ha with ⟨x, rfl⟩,
simp only [conj_laction],
rw [←comm_of_mem_center h, mul_assoc, mul_right_inv, mul_one] },
exact λ _, finset.mem_univ _,
end
theorem card_set_eq_sum_card_orbits [fintype S]
(μ : laction G S) (reprs : finset S)
(hcover : reprs.bind (λ s, (orbit μ s).to_finset) = finset.univ)
(hdisjoint : ∀ x y ∈ reprs, x ≠ y → disjoint (orbit μ x) (orbit μ y)):
card S = reprs.sum (λ s, card (orbit μ s)) :=
begin
change finset.univ.card = _,
conv_rhs begin congr, skip, funext, rw ← to_finset_card, end,
rw [←hcover, finset.card_bind],
exact λ x hx y hy hxyne, order.disjoint_finset_of_disjoint
(hdisjoint x y hx hy hxyne),
end
lemma card_pos_of_mem {α : Type*} {s : finset α} {e : α} : e ∈ s → s.card > 0 :=
λ h, finset.card_pos.mpr $ finset.nonempty_of_ne_empty $ finset.ne_empty_of_mem h
lemma index_centralizer (G : Type*) (s : G) [group G] [fintype G] :
index_subgroup (centralizer s) = card (conj_class s) :=
begin
rw [←to_finset_card, index_subgroup, centralizer,
orbit_stabilizer conj_laction, set.to_finset_card, nat.mul_div_cancel],
congr,
exact card_pos_of_mem (finset.mem_univ 1),
end
theorem group_class_equation [fintype G] (reprs : finset G)
(hcover : reprs.bind (λ s, (conj_class s).to_finset) =
finset.univ \ (center G).to_finset)
(hdisjoint : ∀ x y ∈ reprs, x ≠ y →
disjoint (conj_class x) (conj_class y)) :
card G = card (center G) + reprs.sum (λ s, index_subgroup (centralizer s)) :=
begin
conv_rhs begin congr, skip, congr, skip, funext,
rw [index_centralizer, conj_class] end,
change finset.univ.card = _,
rw [← to_finset_card, ←finset.sdiff_union_of_subset
(center G).to_finset.subset_univ,
finset.card_disjoint_union (finset.sdiff_disjoint),
add_comm, add_right_inj, ←hcover,
finset.card_bind],
{ conv_lhs begin congr, skip, funext, rw conj_class end,
conv_rhs begin congr, skip, funext, rw ←to_finset_card end },
{ intros x hx y hy hxyne,
exact order.disjoint_finset_of_disjoint (hdisjoint x y hx hy hxyne) },
end
end action
|
State Before: n : ℕ
i : Fin (n + 1)
h0 : i ≠ 0
⊢ IsCycle (cycleRange i) State After: case mk
n i : ℕ
hi : i < n + 1
h0 : { val := i, isLt := hi } ≠ 0
⊢ IsCycle (cycleRange { val := i, isLt := hi }) Tactic: cases' i with i hi State Before: case mk
n i : ℕ
hi : i < n + 1
h0 : { val := i, isLt := hi } ≠ 0
⊢ IsCycle (cycleRange { val := i, isLt := hi }) State After: case mk.zero
n : ℕ
hi : Nat.zero < n + 1
h0 : { val := Nat.zero, isLt := hi } ≠ 0
⊢ IsCycle (cycleRange { val := Nat.zero, isLt := hi })
case mk.succ
n n✝ : ℕ
hi : Nat.succ n✝ < n + 1
h0 : { val := Nat.succ n✝, isLt := hi } ≠ 0
⊢ IsCycle (cycleRange { val := Nat.succ n✝, isLt := hi }) Tactic: cases i State Before: case mk.succ
n n✝ : ℕ
hi : Nat.succ n✝ < n + 1
h0 : { val := Nat.succ n✝, isLt := hi } ≠ 0
⊢ IsCycle (cycleRange { val := Nat.succ n✝, isLt := hi }) State After: no goals Tactic: exact isCycle_finRotate.extendDomain _ State Before: case mk.zero
n : ℕ
hi : Nat.zero < n + 1
h0 : { val := Nat.zero, isLt := hi } ≠ 0
⊢ IsCycle (cycleRange { val := Nat.zero, isLt := hi }) State After: no goals Tactic: exact (h0 rfl).elim
|
function [data] = convertSeperateTsToArrayTs(debug_slow)
% Author: Salih Guemues Date: 06-06-2020
%
% Description:
% merges the set of timeseries of scalars belonging to array dimensional
% signal from the logs resulting from the Scope Debugging
% mechanism of Simulink. The output is a struct including a set of timeseries.
%
% Input:
% debug_slow: Log data struct, with vector-signals being seperated in
% to scalar timeseries
% Output:
% data: Struct with all timeseries in there (merged vectors)
% define struct for output
data = struct();
% get signal names of logs
names = fieldnames(debug_slow);
same_signal = 0;
for i=1:1:numel(names)
% check if last charakter of fieldname is a number (--> array signal)
if isnan(str2double(names{i}(end)))
% last charakter not a number, scalar signal can be copied
% extend signal name by "slow" for the output-struct
data.(insertAfter(names{i},"debug_","slow_")) = debug_slow.(names{i});
same_signal = 0;
else
% last charakter is number --> array signal has to be merged
% if next entry does not belong to same signal (same_signal==0) or
% if current entry is first array-signal-entry, create new
% struct-entry corresponding to the array-signal
if ~same_signal
% get signal name without increment (get "a" instead of "a_1")
tmp_name = names{i}(1:end-2);
len_tmp_name = numel(tmp_name);
% extend signal name by "slow" for the output-struct
tmp_name_slow = insertAfter(tmp_name,"debug_","slow_");
tmp_TS = debug_slow.(names{i});
tmp_TS.name = tmp_name_slow; % rename timeseries to array-signal-name
data.(tmp_name_slow) = tmp_TS; % store timeseries in output
else
% concatenate signals back to array and store in output-struct
data.(tmp_name_slow).Data = [data.(tmp_name_slow).Data, debug_slow.(names{i}).Data(:)];
end
if i<(numel(names)-same_signal)
% get signal-name of next logged signal
tmp_name_next = names{i+1}(1:end-2);
len_tmp_name_next = numel(tmp_name_next);
% check if next signal-name is shorter, if yes, not same signal
if len_tmp_name > len_tmp_name_next
same_signal = 0;
elseif strcmp(names{i}(1:len_tmp_name), names{i+1}(1:len_tmp_name))
% if next signal-name is equal to current -> belongs to same
% array-signal (check necessary, since two array signals with
% the same name-length could have been logged in succession)
% e.g. a_1; a_2; a_3; b_1; b_2; b_3
same_signal = 1;
else
same_signal = 0;
end
end
end
end
end
|
From Coq Require List.
From Tactical Require Import Misc.
Require Import SepLogic.Reification.Varmap.
Require Import SepLogic.Reification.Sorting.
Require Import SepLogic.Mem.
Require Export SepLogic.Pred.
Import PredNotations.
Local Open Scope pred.
Set Implicit Arguments.
(*! Setting up reified syntax *)
Global Instance pred_def A V : Default (pred A V) := @emp A V.
Section Mem.
Context (A V:Type).
Notation pred := (pred A V).
Notation emp := (@emp A V).
(* non-recursive part of reification *)
Inductive op_element :=
| Leaf (x:pred)
| Atom (i:varmap.I)
| LiftedProp (P:Prop)
| ConstEmp
.
Definition interpret_e (vm: varmap.t pred) (e: op_element) : pred :=
match e with
| Leaf x => x
| Atom i => varmap.find i vm
| LiftedProp P => lift P
| ConstEmp => emp
end.
Inductive op_tree :=
| Element (e: op_element)
| StarNode (l r: op_tree)
.
Fixpoint interpret (vm: varmap.t pred) t : pred :=
match t with
| Element e => interpret_e vm e
| StarNode l r => star (interpret vm l) (interpret vm r)
end.
End Mem.
(*! Boilerplate for doing reification *)
Local Ltac reify_helper A V term ctx :=
let reify_rec term ctx := reify_helper A V term ctx in
lazymatch ctx with
| context[varmap.cons ?i term _] =>
constr:( (ctx, Element (Atom A V i)) )
| _ =>
lazymatch term with
| @emp _ _ => constr:( (ctx, Element (ConstEmp A V)) )
| lift ?P => constr:( (ctx, Element (LiftedProp A V P)) )
| star ?x ?y =>
let ctx_x := reify_rec x ctx in
let ctx_y := reify_rec y (fst ctx_x) in
let r := (eval cbv [fst snd] in
(fst ctx_y, @StarNode A V (snd ctx_x) (snd ctx_y))) in
constr:(r)
| _ =>
let v' := (eval cbv [varmap.length] in (varmap.length ctx)) in
let ctx' := constr:( varmap.cons v' term ctx ) in
constr:( (ctx', Element (Atom A V v')) )
end
end.
Local Ltac with_reified A V ctx x rx :=
let ctx_t := reify_helper A V x ctx in
let ctx := (eval cbv [fst] in (fst ctx_t)) in
let t := (eval cbv [snd] in (snd ctx_t)) in
rx ctx t.
Local Ltac init_reify A V x rx :=
with_reified A V (varmap.empty (pred A V)) x rx.
Ltac quote_impl :=
match goal with
| |- @pimpl ?A ?V ?x ?y =>
let init := init_reify A V in
let then_do := with_reified A V in
init x
ltac:(
fun ctx xt =>
then_do ctx y
ltac:(
fun ctx' yt =>
change (interpret ctx' xt ===> interpret ctx' yt)))
end.
Ltac quote_eqn :=
match goal with
| |- @piff ?A ?V ?x ?y =>
let init := init_reify A V in
let then_do := with_reified A V in
init x
ltac:(
fun ctx xt =>
then_do ctx y
ltac:(
fun ctx' yt =>
change (interpret ctx' xt === interpret ctx' yt)))
end.
Ltac quote_impl_hyp H :=
match type of H with
| ?lhs ===> ?rhs =>
match goal with
| |- @pimpl ?A ?V ?x ?y =>
let init := init_reify A V in
let then_do := with_reified A V in
init lhs ltac:(
fun ctx _ =>
then_do ctx rhs ltac:(
fun ctx _ =>
then_do ctx x ltac:(
fun ctx xt =>
then_do ctx y ltac:(
fun ctx' yt =>
change (interpret ctx' xt ===> interpret ctx' yt)))))
end
end.
Ltac quote_eqn_hyp H :=
match type of H with
| ?lhs === ?rhs =>
match goal with
| |- @pimpl ?A ?V ?x ?y =>
let init := init_reify A V in
let then_do := with_reified A V in
init lhs ltac:(
fun ctx _ =>
then_do ctx rhs ltac:(
fun ctx _ =>
then_do ctx x ltac:(
fun ctx xt =>
then_do ctx y ltac:(
fun ctx' yt =>
change (interpret ctx' xt === interpret ctx' yt)))))
end
end.
Ltac quote_app_hyp H :=
match type of H with
| @predApply ?A ?V ?x ?m =>
let init := init_reify A V in
init x ltac:(
fun ctx xt =>
change x with (interpret ctx xt) in H
)
end.
Theorem reify_test A V (p1 p2 p3: pred A V) :
p1 * p2 * p3 ===> p1 * (p2 * p3).
Proof.
quote_impl.
Abort.
Theorem reify_with_hyp_test A V (p1 p2 p3: pred A V) :
p3 * p2 ===> p2 ->
p1 * p2 * p3 ===> p1 * (p2 * p3).
Proof.
intros.
quote_impl_hyp H.
Abort.
Theorem reify_app_test A V (p1: pred A V) m
(H: p1 m) : True.
Proof.
quote_app_hyp H.
Abort.
(*! Proving theorems on reified syntax *)
Module Norm.
Section Mem.
Context (A V:Type).
Notation pred := (pred A V).
Notation emp := (@emp A V).
Notation op_tree := (op_tree A V).
Notation op_element := (op_element A V).
Import List.ListNotations.
Lemma equiv_refl : forall (p:pred), p === p.
Proof. reflexivity. Qed.
Hint Resolve equiv_refl : core.
Fixpoint flatten (t:op_tree) : list op_element :=
match t with
| Element e => match e with
| ConstEmp _ _ => []
| _ => [e]
end
| StarNode l r => flatten l ++ flatten r
end.
Fixpoint int_l vm (l: list op_element) : pred :=
match l with
| [] => emp
| e::es => star (interpret_e vm e) (int_l vm es)
end.
Fixpoint int_l' vm (acc:pred) (l: list op_element) : pred :=
match l with
| [] => acc
| e::es => int_l' vm (acc * interpret_e vm e) es
end.
Definition interpret_l vm (l: list op_element) : pred :=
match l with
| [] => emp
| e::es => int_l' vm (interpret_e vm e) es
end.
Theorem int_l'_to_int_l vm l acc :
int_l' vm acc l === acc * int_l vm l.
Proof.
gen acc.
induction l; intros; simpl.
- rewrite star_emp_r; auto.
- rewrite IHl.
rewrite star_assoc; auto.
Qed.
Theorem interpret_l_to_int_l vm l :
interpret_l vm l === int_l vm l.
Proof.
destruct l; simpl; auto.
rewrite int_l'_to_int_l; auto.
Qed.
(* use a simple recursive definition using the above proof *)
Ltac simplify :=
rewrite ?interpret_l_to_int_l.
Theorem int_l_app vm l1 l2 :
int_l vm (l1 ++ l2) === int_l vm l1 * int_l vm l2.
Proof.
induction l1; simpl.
rewrite star_emp_l; auto.
rewrite <- star_assoc.
rewrite IHl1; auto.
Qed.
Theorem interpret_flatten vm t :
interpret vm t === interpret_l vm (flatten t).
Proof.
simplify.
induction t; simpl.
destruct e; simpl;
try rewrite star_emp_r; auto.
rewrite int_l_app.
rewrite IHt1, IHt2; auto.
Qed.
Theorem int_l_perm vm l1 l2:
Permutation l1 l2 ->
int_l vm l1 === int_l vm l2.
Proof.
induction 1; simpl; auto.
- rewrite IHPermutation; auto.
- rewrite ?star_assoc.
apply star_respects_iff; auto.
rewrite star_comm; auto.
- rewrite IHPermutation1, IHPermutation2; auto.
Qed.
Definition get_key (e:op_element) : option nat :=
match e with
| Atom _ _ i => Some (S i)
| LiftedProp _ _ _ => Some 0
| _ => None
end.
Theorem interpret_l_sort vm l :
interpret_l vm l === interpret_l vm (sortBy get_key l).
Proof.
simplify.
apply int_l_perm.
apply sortBy_permutation.
Qed.
Theorem interpret_l_sort_impl vm l1 l2 :
interpret_l vm (sortBy get_key l1) ===> interpret_l vm (sortBy get_key l2) ->
interpret_l vm l1 ===> interpret_l vm l2.
Proof.
rewrite <- ?interpret_l_sort; auto.
Qed.
Theorem interpret_l_sort_iff vm l1 l2 :
interpret_l vm (sortBy get_key l1) === interpret_l vm (sortBy get_key l2) ->
interpret_l vm l1 === interpret_l vm l2.
Proof.
rewrite <- ?interpret_l_sort; auto.
Qed.
Local Fixpoint flatten_props (l: list Prop) : Prop :=
match l with
| [] => True
| P::Ps => P /\ flatten_props Ps
end.
Fixpoint flatten_props1 (l: list Prop) : Prop :=
match l with
| [] => True
| [P]%list => P
| P::Ps => P /\ flatten_props1 Ps
end.
Theorem flatten_props1_ok l :
flatten_props l <-> flatten_props1 l.
Proof.
destruct l.
- firstorder.
- induction l; simpl.
firstorder.
destruct l; firstorder.
Qed.
Fixpoint grab_props (l:list op_element) : list Prop * list op_element :=
match l with
| [] => ([], [])
| e::es => let (acc, es') := grab_props es in
match e with
| LiftedProp _ _ P =>
(P::acc, es')
| _ => (acc, e::es')
end
end.
Definition int_props vm (x: list Prop * list op_element) : pred :=
let '(P, es) := x in
lift (flatten_props1 P) * interpret_l vm es.
Local Definition int_props' vm (x: list Prop * list op_element) : pred :=
let '(P, es) := x in
lift (flatten_props P) * int_l vm es.
Local Theorem int_props'_ok vm x :
int_props vm x === int_props' vm x.
Proof.
unfold int_props, int_props'.
destruct x.
simplify.
rewrite flatten_props1_ok.
auto.
Qed.
Local Lemma abc_to_bac (p1 p2 p3:pred) :
p1 * p2 * p3 === p2 * p1 * p3.
Proof.
apply star_respects_iff; auto.
apply star_comm.
Qed.
Theorem interpret_grab_props vm l :
interpret_l vm l === int_props vm (grab_props l).
Proof.
simplify.
rewrite int_props'_ok.
induction l; simpl.
rewrite star_emp_r.
apply emp_to_lift; auto.
destruct_with_eqn (grab_props l).
rewrite IHl.
destruct a; simpl in *;
rewrite ?star_assoc;
try solve [ apply abc_to_bac] .
rewrite lift_star; auto.
Qed.
Local Lemma impl_with_lifts (P Q:Prop) (p q: pred) :
(P -> p ===> q /\ Q) ->
lift P * p ===> lift Q * q.
Proof.
intros.
apply impl_with_lift; intuition idtac.
rewrite H.
rewrite <- emp_to_lift; auto.
rewrite star_emp_l; reflexivity.
Qed.
Local Lemma iff_with_lifts (P Q:Prop) (p q: pred) :
(P -> p ===> q /\ Q) ->
lift P * p ===> lift Q * q.
Proof.
intros.
apply impl_with_lift; intuition idtac.
rewrite H.
rewrite <- emp_to_lift; auto.
rewrite star_emp_l; reflexivity.
Qed.
Theorem grab_props_impl vm l1 l2 :
(let (P, p) := grab_props l1 in
let (Q, q) := grab_props l2 in
flatten_props1 P ->
interpret_l vm p ===> interpret_l vm q /\ flatten_props1 Q) ->
interpret_l vm l1 ===> interpret_l vm l2.
Proof.
intros.
rewrite ?interpret_grab_props.
destruct (grab_props l1) as [P p].
destruct (grab_props l2) as [Q q].
simpl.
apply impl_with_lifts; eauto.
Qed.
Theorem grab_props_iff vm l1 l2 :
(let (P, p) := grab_props l1 in
let (Q, q) := grab_props l2 in
match P, Q with
| nil, nil =>
interpret_l vm p === interpret_l vm q
| _, _ => False
end) ->
interpret_l vm l1 === interpret_l vm l2.
Proof.
intros.
rewrite ?interpret_grab_props.
destruct (grab_props l1) as [P p].
destruct (grab_props l2) as [Q q].
simpl.
destruct P, Q; intros; try contradiction.
simpl.
rewrite H; auto.
Qed.
Theorem empty_props_optimization Ps Q :
match Ps with
| nil => Q
| _ => flatten_props1 Ps /\ Q
end <-> flatten_props1 Ps /\ Q.
Proof.
destruct Ps; simpl; firstorder.
Qed.
Theorem grab_props_apply vm l m :
predApply (int_props vm (grab_props l)) m ->
let (P, p) := grab_props l in
let remaining_pred := predApply (interpret_l vm p) m in
match P with
| nil => remaining_pred
| _ => flatten_props1 P /\ remaining_pred
end.
Proof.
intros.
destruct (grab_props l) as [P p].
cbn [int_props] in H.
cbv zeta.
apply empty_props_optimization.
apply lift_applied in H; auto.
Qed.
End Mem.
End Norm.
Ltac norm_reified :=
rewrite ?Norm.interpret_flatten;
apply Norm.interpret_l_sort_impl;
apply Norm.grab_props_impl.
Ltac norm_reified_iff :=
rewrite ?Norm.interpret_flatten;
apply Norm.interpret_l_sort_iff;
apply Norm.grab_props_iff.
(* for a predApply hypothesis with reified predicate *)
Ltac norm_reified_hyp H :=
rewrite Norm.interpret_flatten in H;
rewrite Norm.interpret_l_sort in H;
rewrite Norm.interpret_grab_props in H;
apply Norm.grab_props_apply in H.
Local Ltac destruct_ands_in H :=
try match type of H with
| _ /\ _ => let H' := fresh in
destruct H as [H H'];
destruct_ands_in H'
end.
Ltac cleanup_normed_app H :=
cbn [Norm.int_props
Norm.flatten Norm.flatten_props1 Norm.interpret_l
Norm.int_l' interpret_e Varmap.varmap.find
PeanoNat.Nat.eqb
app Sorting.sortBy Sorting.sort Sorting.insert_sort Sorting.insert
Norm.get_key PeanoNat.Nat.leb
Norm.grab_props] in H;
try match type of H with
| _ /\ _ =>
let H' := fresh in
destruct H as [H' H];
destruct_ands_in H'
end.
Ltac cleanup_normed_goal :=
match goal with
| |- True -> _ => intros _
| _ => intros
end;
try match goal with
| |- _ /\ True => split; [ | exact I ]
end;
repeat match goal with
| [ H: _ /\ _ |- _ ] => destruct H
end.
Ltac norm :=
intros;
match goal with
| |- _ ===> _ =>
quote_impl; norm_reified
| |- _ === _ =>
quote_eqn; norm_reified_iff
end; simpl;
cleanup_normed_goal.
Ltac norm_with H :=
intros;
quote_impl_hyp H;
norm_reified; simpl;
cleanup_normed_goal.
Ltac norm_hyp H :=
quote_app_hyp H;
norm_reified_hyp H;
cleanup_normed_app H.
Ltac normed_cancellation :=
try match goal with
| |- _ /\ _ => split
end;
try match goal with
| |- ?p ===> ?p => reflexivity
| |- ?p === ?p => reflexivity
| [ H: ?P |- ?P ] => exact H
end.
Ltac cancel :=
norm; normed_cancellation.
Module Demo.
Ltac norm :=
intros;
quote_impl;
norm_reified.
Ltac simpl_flatten :=
cbn [Norm.flatten app].
Ltac simpl_sorting :=
cbn [Sorting.sortBy Sorting.sort Sorting.insert_sort Sorting.insert
Norm.get_key PeanoNat.Nat.leb].
Ltac simpl_grab_props :=
cbn [Norm.grab_props].
End Demo.
|
[STATEMENT]
lemma "merge_overlap (1:: 16 word,2) [(2, 7)] = [(1, 7)]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. merge_overlap (1, 2) [(2, 7)] = [(1, 7)]
[PROOF STEP]
by eval
|
#pragma once
#include "BufferView.h"
#include "Enum.h"
#include "Error.h"
#include "parsers/Parsing.h"
#include <boost/hana/define_struct.hpp>
#include <gsl/span>
namespace gltfpp {
inline namespace v1 {
BETTER_ENUM(AccessorComponentType,
int,
BYTE = 5120,
UNSIGNED_BYTE = 5121,
SHORT = 5122,
UNSIGNED_SHORT = 5123,
UNSIGNED_INT = 5125,
FLOAT = 5126)
BETTER_ENUM(AccessorType, int, SCALAR, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4)
constexpr auto AccessorTypeComponentCount =
boost::hana::make_map(boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::SCALAR>, 1),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC2>, 2),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC3>, 3),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC4>, 4),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT2>, 4),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT3>, 9),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT4>, 16));
struct Accessor {
BOOST_HANA_DEFINE_STRUCT(Accessor,
(bool, normalized),
(std::vector<double>, min),
(std::vector<double>, max),
(option<std::string>, name),
(option<nlohmann::json>, sparse),
(option<nlohmann::json>, extensions),
(option<nlohmann::json>, extras),
(ptrdiff_t, byteOffset),
(size_t, count),
(AccessorComponentType, componentType));
BufferView const *bufferView;
};
auto parse(Accessor &) noexcept;
} // namespace v1
} // namespace gltfpp
|
module Elab3
import BC
import public Language.Reflection.Utils
%language ElabReflection
quicksort : List Nat -> List Nat
quicksort [] = []
quicksort (x::xs) =
quicksort (filter (< x) xs) ++
x :: quicksort (filter (>= x) xs)
--%runElab bc `{quicksort} `{{qs'}} `{{QSAcc}}
-- %runElab bc' `{quicksort} `{{qs'}} `{{qs2}} `{{QSAcc}} `{{Elab3.qsProof}}
-- elab3.qsProof = ?todo
mkHole : String -> Raw -> Elab TTName
mkHole n ty =
do s <- gensym n
claim s ty
pure s
auto : Elab ()
auto = do g <- goalType
case g of
`(() : Type) =>
exact `(() : ())
`((~A, ~B) : Type) =>
do a <- mkHole "A" A
b <- mkHole "B" B
exact `(MkPair {A=~A} {B=~B}
~(Var a) ~(Var b))
focus a; auto
focus b; auto
goal : ((), ((), ()))
goal = %runElab auto
partial
auto' : Elab ()
auto' = do compute
attack
try intros
hs <- map fst <$> getEnv
for_ hs $
\ih => try (rewriteWith (Var ih))
hypothesis <|> search' 100 []
solve
|
import util.classical
import util.predicate
import util.data.option
import util.control.applicative
import util.meta.tactic
import tactic.basic
import tactic
import temporal_logic.basic
import temporal_logic.persistent
import temporal_logic.pair
open predicate
/-
The auto quotation currently supports two classes of tactics: tactic and smt_tactic.
To add a new class Tac, we have to
1) Make sure it is a monad. That is, we have an instance for (monad Tac)
2) There is a namespace Tac.interactive
3) There is a definition: Tac.step {α : Type} (t : Tac α) : Tac unit
4) (Optional) Tac.istep {α : Type} (line0 col0 : nat) (line col : nat) (tac : Tac α) : Tac unit
Similar to step but it should scope trace messages at the given line/col,
and ensure that the exception position is after (line0, col0)
6) There is a definition Tac.save_info (line col : nat) : Tac unit
7) There is a definition Tac.execute (tac : Tac unit) : tactic unit
8) There is a definition Tac.execute_with (cfg : config) (tac : Tac unit) : tactic unit
where config is an arbitrary type.
TODO(Leo): improve the "recipe" above. It is too ad hoc.
-/
meta def temporal : Type → Type :=
tactic
open format
meta def format.intercalate (x : format) : list format → format :=
format.join ∘ list.intersperse x
meta def unlines : list format → format :=
format.intercalate line
meta instance : monad temporal :=
by { dunfold temporal, apply_instance }
meta instance : monad_fail temporal :=
by { dunfold temporal, apply_instance }
meta instance : alternative temporal :=
by { dunfold temporal, apply_instance }
meta instance andthen_seq : has_andthen (temporal unit) (temporal unit) (temporal unit) :=
by { dunfold temporal, apply_instance }
meta instance andthen_seq_focus : has_andthen (temporal unit) (list (temporal unit)) (temporal unit) :=
by { dunfold temporal, apply_instance }
namespace temporal
open tactic applicative
open interactive
open tactic.interactive (resetI rw_rules rw_rules_t rw_rule get_rule_eqn_lemmas to_expr'
unfreezeI solve_by_elim)
open has_to_tactic_format
open functor list (filter)
section expr
open expr
variable {elab : bool}
meta def get_app_args_aux' : list (expr elab) → expr elab → list (expr elab)
| r (app f a) := get_app_args_aux' (a::r) f
| r e := r
meta def get_app_args' : (expr elab) → list (expr elab) :=
get_app_args_aux' []
end expr
meta def guarded {α β} : list (tactic α × tactic β) → tactic β
| [] := failed
| ((x,y) :: xs) :=
do x ← try_core x,
if x.is_some then
y
else guarded xs
meta def check_scope (e : expr) : tactic unit :=
do mmap' (get_local ∘ expr.local_pp_name) e.list_local_consts
meta def type_check_result (msg : format) : tactic unit :=
result >>= type_check <|> fail msg
meta def mk_tmp_app {α} [has_to_pexpr α] (e₀ : expr) (e₁ : α) : temporal expr :=
do t ← infer_type e₀,
(do e' ← to_expr (to_pexpr e₁), e₀ e' <$ type_check (e₀ e'))
<|> to_expr ``(p_impl_revert %%e₀ %%e₁)
<|> to_expr ``(henceforth_deduction %%e₀ %%e₁)
<|> to_expr ``(p_forall_revert %%e₀ %%e₁)
meta def t_to_expr' : pexpr → temporal expr
| e@(expr.app e₀ e₁) :=
to_expr e <|>
do e' ← t_to_expr' e₀,
mk_tmp_app e' e₁
| e := to_expr e
meta def t_to_expr (q : pexpr) : temporal expr :=
do p ← t_to_expr' q <|> to_expr q,
check_scope p,
return p
meta def t_to_expr_for_apply (q : pexpr) : temporal expr :=
let aux (n : name) : tactic expr := do
p ← resolve_name n,
match p with
| (expr.const c []) := do r ← mk_const c, save_type_info r q, return r
| _ := t_to_expr p
end
in match q with
| (expr.const c []) := aux c
| (expr.local_const c _ _ _) := aux c
| _ := t_to_expr q
end
meta def beta_reduction' (eta := ff) : expr → temporal expr
| (expr.app e₀ e₁) :=
do e₁ ← beta_reduction' e₁,
e₀ ← beta_reduction' e₀,
head_beta $ expr.app e₀ e₁
| e := do z ← expr.traverse beta_reduction' e,
if eta then head_eta z
else return z
meta def beta_reduction (e : expr) (eta := ff) : temporal expr :=
instantiate_mvars e >>= beta_reduction' eta
meta def succeeds {α} (tac : temporal α) : temporal bool :=
tt <$ tac <|> pure ff
meta def decl_to_fmt (s : tactic_state) (vs : list expr) : expr × option expr → format
| (t,val) :=
let vs := map s.format_expr vs,
t := s.format_expr t,
vs' := format.join $ vs.intersperse " " in
match val with
| (some val) :=
format!"{vs'} : {t} := {s.format_expr val}"
| none := format!"{vs'} : {t}"
end
meta def get_assumptions : temporal (list expr) :=
do `(%%Γ ⊢ _) ← target,
ls ← local_context,
mfilter (λ l, succeeds $
do `(%%Γ' ⊢ %%e) ← infer_type l,
is_def_eq Γ Γ') ls
meta def asm_stmt (Γ e : expr) : temporal (expr × expr × option expr) :=
do t ← infer_type e,
val ← get_local_value e,
`(%%Γ' ⊢ %%p) ← return t | return (e,t,val),
( do (e,p,val) <$ is_def_eq Γ Γ' ) <|> return (e,t,val)
def compact {α β : Type*} [decidable_eq β] : list (α × β) → list (list α × β)
| [] := []
| ( (x,y) :: xs ) :=
match compact xs with
| [] := [ ([x],y) ]
| ( (x',y') :: ys ) :=
if y = y' then (x::x', y) :: ys
else ([x],y) :: (x',y') :: ys
end
meta def temp_to_fmt (g : expr) : temporal (thunk format) :=
do set_goals [g],
`(%%Γ ⊢ %%p) ← target | (λ s _, to_fmt s) <$> read,
hs ← local_context,
hs' ← mmap (asm_stmt Γ) hs,
hs' ← mfilter (λ x : _ × _, bnot <$> succeeds (is_def_eq Γ x.1)) hs',
s ← read,
let x := decl_to_fmt s ,
return $ λ _, format.intercalate line [format.intercalate (","++line) $ mapp (decl_to_fmt s) ∘ compact $ hs',format!"⊢ {s.format_expr p}"]
meta def save_info (p : pos) : temporal unit :=
do cleanup,
gs ← get_goals,
let gs' := gs.pw_filter (≠),
fmt ← mmap temp_to_fmt gs',
set_goals gs,
tactic.save_info_thunk p (λ _,
let header := if fmt.length > 1 then format!"{fmt.length} goals\n" else "",
eval : thunk format → format := λ f, f () in
if fmt.empty
then "no goals"
else header ++ format.join ((fmt.map eval).intersperse $ line ++ line))
meta def step {α : Type} (c : temporal α) : temporal unit :=
c >>[tactic] cleanup
meta def istep {α : Type} (line0 col0 line col : nat) (c : temporal α) : temporal unit :=
tactic.istep line0 col0 line col c
meta def show_tags :=
get_goals >>= mmap' (λ g, get_tag g >>= (trace : list name → tactic unit))
meta def uniform_assumptions' (Γ : expr)
: expr → expr → temporal (option (expr × expr))
| h t := do
t ← head_beta t,
match t with
| (expr.pi n bi t' e) :=
do l ← mk_local' n bi t',
(some (p,t)) ← uniform_assumptions' (h l) (e.instantiate_var l) | return none,
let abs := t.lambdas [l],
let p' := p.lambdas [l],
p ← some <$> (prod.mk <$> to_expr ``( (p_forall_to_fun %%Γ %%abs).mpr %%p' )
<*> to_expr ``( p_forall %%abs )),
return p
| `(%%Γ' ⊢ %%p) := (is_def_eq Γ Γ' >> some (h,p) <$ guard (¬ Γ.occurs p))
| p := none <$ guard (¬ Γ.occurs p) <|> none <$ match_expr ``(persistent %%Γ) p
end
meta def protect_tags {α : Sort*} (tac : temporal α) : temporal α :=
with_enable_tags $
do t ← get_main_tag,
tac <* set_main_tag t
/-- `fix_assumptions Γ h` takes assumptions and reformulate it so that its type is
`Γ ⊢ _`. It replaces `∀ _, Γ ⊢ _` with `Γ ⊢ ∀∀ _, _` and `_ → Γ ⊢ _` with
`Γ ⊢ _ ⟶ _`.
-/
meta def fix_assumptions (Γ h : expr) : temporal expr :=
do t ← infer_type h,
(some r) ← try_core (uniform_assumptions' Γ h t),
match r with
| (some (pr,t)) :=
do p ← to_expr ``(%%Γ ⊢ %%t),
protect_tags (
assertv h.local_pp_name p pr
<* clear h)
| none := return h
end
meta def fix_or_clear_assumption (Γ h : expr) : temporal unit :=
() <$ fix_assumptions Γ h <|> tactic.clear h
meta def semantic_assumption (τ h : expr) : temporal ℕ :=
do `(%%τ' ⊨ _) ← infer_type h | return 0,
(do is_def_eq τ τ',
revert h, `[rw ← eq_judgement],
return 1)
<|> return 0
meta def sem_to_syntactic : tactic unit :=
do `(%%τ ⊨ _) ← target,
α ← infer_type τ,
`[rw ← eq_judgement],
r ← local_context >>= mfoldl (λ a h, (+) a <$> semantic_assumption τ h) 0,
tactic.interactive.generalize none () (``(↑(eq %%τ) : pred' %%α), `Γ),
intron r
meta def execute (c : temporal unit) : tactic unit :=
do intros,
t ← target,
t' ← whnf t,
match t' with
| `(⊩ _) := () <$ tactic.intro `Γ
| `(_ ⟹ _) := () <$ tactic.intro `Γ
| `(∀ Γ : pred' _, Γ ⊢ _) := () <$ tactic.intro `Γ
| `(%%Γ ⊢ _) := local_context >>= mmap' (fix_or_clear_assumption Γ)
| _ := to_expr ``(⊩ _) >>= tactic.change >> () <$ tactic.intro `Γ
<|> refine ``(@id (_ ⊨ _) _) >> sem_to_syntactic
<|> fail "expecting a goal of the form `_ ⊢ _` or `⊩ _ `"
end,
target >>= whnf >>= unsafe_change,
c
meta def revert (e : expr) : tactic unit :=
do `(%%Γ ⊢ _) ← target >>= instantiate_mvars,
t ← infer_type e,
match t with
| `(%%Γ' ⊢ _) :=
do ppΓ ← pp Γ, ppΓ' ← pp Γ',
is_def_eq Γ Γ' <|> fail format!"{ppΓ'} does not match {ppΓ'}",
tactic.revert e, applyc `predicate.p_impl_revert
| _ := tactic.revert e >> refine ``((p_forall_to_fun %%Γ _).mp _)
end
section
open tactic.interactive interactive.types
meta def interactive.strengthening (tac : itactic) : temporal unit :=
do lmms ← attribute.get_instances `strengthening,
`(%%Γ ⊢ _) ← target,
p ← infer_type Γ >>= mk_meta_var,
lmms.any_of $ λ l, do
r ← tactic.mk_app l [p,Γ],
tactic.refine ``(p_impl_revert %%r _ ),
tac
meta def interactive.apply' (q : parse texpr) : temporal unit :=
do l ← t_to_expr_for_apply q,
() <$ tactic.apply l <|> interactive.strengthening (() <$ tactic.apply l)
<|> () <$ tactic.apply l -- we try `tactic.apply l` again
-- knowing that if we go back to
-- it, it will fail and we'll have
-- a proper error message
end
meta def split : temporal unit :=
do `(%%Γ ⊢ %%p ⋀ %%q) ← target,
interactive.apply ``(p_and_intro %%p %%q %%Γ _ _)
meta def consequent (e : expr) : temporal expr :=
do `(_ ⊢ %%p) ← infer_type e,
return p
lemma to_antecendent (xs : list (cpred))
(H : list_persistent xs)
(p : cpred)
(h : ◻ xs.foldr (⋀) True ⊢ p)
: ∀ Γ, with_h_asms Γ xs p :=
begin
intro,
replace h := λ h', judgement_trans Γ _ _ h' h,
induction H with x xs,
{ simp at h, simp [with_h_asms,h] with tl_simp, },
{ simp at h, simp_intros [with_h_asms], resetI,
apply H_ih , intros,
apply h,
rw henceforth_and,
simp [is_persistent],
begin [temporal]
split,
assumption,
assumption,
end }
end
inductive entails_all {β} (Γ : pred' β) : list (pred' β) → Prop
| nil : entails_all []
| cons (x : pred' β) (xs : list $ pred' β)
: Γ ⊢ x → entails_all xs →
entails_all (x :: xs)
lemma entails_all_subst_left {β}
(p q : pred' β)
(rs : list $ pred' β)
(h : p ⟹ q)
(h' : entails_all q rs)
: entails_all p rs :=
begin
induction h'
; constructor,
{ revert h'_a,
apply revert_p_imp' h },
{ assumption, }
end
lemma to_antecendent' (xs : list (cpred)) (p : cpred)
(ps : list_persistent xs)
(h : ∀ Γ [persistent Γ], with_h_asms Γ xs p)
: ∀ Γ, with_h_asms Γ xs p :=
begin
apply to_antecendent _ ps,
have : entails_all (◻list.foldr p_and True xs) xs,
{ clear h ps,
induction xs with x xs ; constructor,
{ apply indirect_judgement,
simp_intros Γ h [henceforth_and],
apply henceforth_str x Γ h.left, },
{ revert xs_ih, apply entails_all_subst_left,
simp [henceforth_and] } },
specialize h (◻list.foldr p_and True xs),
revert this h, generalize : ◻list.foldr p_and True xs = Γ,
intros h' h,
induction ps with x xs,
{ simp [with_h_asms] at h,
apply h },
{ apply_assumption ; cases h', assumption,
simp [with_h_asms] at h,
solve_by_elim, }
end
open tactic tactic.interactive (unfold_coes unfold itactic assert_or_rule)
open interactive interactive.types lean lean.parser
open applicative (mmap₂ lift₂)
open functor
local postfix `?`:9001 := optional
section persistently
meta def is_henceforth (e : expr) : temporal bool :=
do `(_ ⊢ %%t) ← infer_type e | return tt,
succeeds $
to_expr ``(persistent %%t) >>= mk_instance
private meta def mk_type_list (Γ pred_t : expr) : list expr → temporal (expr × expr)
| [] := do
lift₂ prod.mk (to_expr ``(@list.nil cpred))
(to_expr ``(temporal.list_persistent.nil_persistent))
| (x :: xs) :=
do (es,is) ← mk_type_list xs,
v ← mk_meta_var pred_t,
`(_ ⊢ %%c) ← infer_type x, c' ← pp c,
ls ← to_expr ``(list.cons %%c %%es),
inst₀ ← to_expr ``(persistent %%c) >>= mk_instance,
inst ← tactic.mk_mapp `temporal.list_persistent.cons_persistent [c,es,inst₀,is],
return (ls,inst)
meta def is_context_persistent : temporal bool :=
do `(%%Γ ⊢ _) ← target | return ff,
(tt <$ (to_expr ``(persistent %%Γ) >>= mk_instance)) <|>
return ff
open list
meta def create_persistent_context : temporal unit :=
do b ← is_context_persistent,
when (¬ b) $ do
asms ← get_assumptions,
`(%%Γ ⊢ %%p) ← target >>= instantiate_mvars,
pred_t ← infer_type Γ,
Γ ← get_local Γ.local_pp_name,
(asms',inst) ← mk_type_list Γ pred_t asms,
r ← tactic.revert_lst (Γ :: asms : list _).reverse,
guard (r = asms.length + 1) <|> fail format!"wrong use of context {Γ}",
ts ← mmap consequent asms,
hnm ← mk_fresh_name,
h ← to_expr ``(@to_antecendent' %%asms' %%p %%inst) >>= note hnm none,
tactic.interactive.simp none tt [simp_arg_type.expr ``(temporal.with_h_asms)] [] (loc.ns [hnm]),
h ← get_local hnm,
refine ``(%%h _),
-- -- `[simp only [temporal.with_h_asms]],
intro_lst $ Γ.local_pp_name :: `_ :: asms.map expr.local_pp_name,
resetI,
get_local hnm >>= tactic.clear
meta def interactive.persistent (excp : parse without_ident_list) : temporal unit :=
do b ← is_context_persistent,
when (¬ b) $ do
hs ← get_assumptions,
hs' ← hs.mfilter (map bnot ∘ is_henceforth),
excp' ← mmap get_local excp,
mmap' tactic.clear (hs'.diff excp'),
when excp.empty
create_persistent_context
meta def persistently (tac : itactic) : temporal unit :=
focus1 $
do create_persistent_context,
-- calling tac
x ← focus1 tac,
-- restore context to Γ
done <|> (do
to_expr ```(_ ⊢ _) >>= change)
<|> (do
to_expr ```(⊩ _) >>= change,
`(⊩ %%q) ← target,
() <$ intro `Γ)
end persistently
section lemmas
open list
lemma judgement_congr {Γ p q : cpred}
(h : Γ ⊢ p ≡ q)
: Γ ⊢ p = Γ ⊢ q :=
by { apply iff.to_eq, split ; intro h' ;
lifted_pred using h h' ; cc }
def with_asms {β} (Γ : pred' β) : Π (xs : list (string × pred' β)) (x : pred' β), Prop
| [] x := Γ ⊢ x
| ((h,x) :: xs) y := Γ ⊢ x → with_asms xs y
def tl_seq {β} (xs : list (string × pred' β)) (x : pred' β) : Prop :=
∀ Γ, with_asms Γ xs x
lemma p_forall_intro_asms_aux {β t} (ps : list (string × pred' β))
(φ : pred' β) (q : t → pred' β)
(h : ∀ x Γ, Γ ⊢ φ → with_asms Γ ps (q x))
(Γ : pred' β)
(h' : Γ ⊢ φ )
: with_asms Γ ps (p_forall q) :=
begin
induction ps generalizing φ,
case list.nil
{ simp [with_asms] at h ⊢,
rw p_forall_to_fun,
introv, apply h _ , exact h', },
case list.cons : p ps
{ cases p with n p,
simp [with_asms] at h ⊢,
intro hp,
have h_and := (p_and_intro φ p Γ) h' hp,
revert h_and,
apply ps_ih,
intros, apply_assumption,
apply p_and_elim_left φ p Γ_1 a,
apply p_and_elim_right φ p Γ_1 a, }
end
lemma p_forall_intro_asms {t β} (ps : list (string × pred' β)) (q : t → pred' β)
(h : ∀ x, tl_seq ps (q x))
: tl_seq ps (p_forall q) :=
begin
intro,
apply p_forall_intro_asms_aux _ True,
{ intros, apply h },
simp
end
lemma p_imp_intro_asms_aux {β} (ps : list (string × pred' β))
(φ q r : pred' β) (n : string)
(h : ∀ Γ, Γ ⊢ φ → with_asms Γ (ps ++ [(n,q)]) r)
(Γ : pred' β)
(h' : Γ ⊢ φ )
: with_asms Γ ps (q ⟶ r) :=
begin
induction ps generalizing φ,
case list.nil
{ simp [with_asms] at h ⊢,
apply p_imp_intro _,
{ introv h₀, apply h _ , exact h₀, },
solve_by_elim, },
case list.cons : p ps
{ cases p with n p,
simp [with_asms] at h ⊢,
intro hp,
have h_and := (p_and_intro φ p Γ) h' hp,
revert h_and,
apply ps_ih,
intros, apply_assumption,
apply p_and_elim_left φ p Γ_1 a,
apply p_and_elim_right φ p Γ_1 a, }
end
lemma p_imp_intro_asms {β} (ps : list (string × pred' β))
(q r : pred' β) (n : string)
(h : tl_seq (ps ++ [(n,q)]) r)
: tl_seq ps (q ⟶ r) :=
begin
intro, apply p_imp_intro_asms_aux _ True,
{ intros, apply h },
simp
end
-- lemma canonical_sequent {β} (Γ p : pred' β)
-- : Γ ⊢ p ↔ (∀ Γ', Γ' ⊢ Γ → Γ' ⊢ p) :=
-- begin
-- split ; intro,
-- { intros, transitivity ; assumption },
-- apply_assumption, refl
-- end
end lemmas
private meta def mk_type_list : list expr → temporal expr
| [] := to_expr ``(list.nil)
| (x :: xs) :=
do es ← mk_type_list xs,
`(_ ⊢ %%t) ← infer_type x,
let n := x.local_pp_name.to_string,
to_expr ``(list.cons (%%(reflect n), %%t) %%es)
open list (cons)
private meta def parse_list : expr → temporal (list (name × expr))
| `([]) := pure []
| `( list.cons (%%n,%%e) %%es ) :=
do n' ← eval_expr _ n,
(::) (mk_simple_name n',e) <$> parse_list es
| _ := pure []
private meta def enter_list_state : temporal (expr × list expr × expr) :=
do `(%%Γ ⊢ %%p) ← target,
ls ← get_assumptions,
ls' ← mk_type_list ls,
r ← revert_lst (Γ :: ls : list _).reverse,
let k := ls.length + 1,
guard (r = k)
<|> fail format!"wrong use of context {Γ}: {r} ≠ {k}",
to_expr ``(tl_seq %%ls' %%p) >>= unsafe_change,
return (Γ, ls, ls')
private meta def exit_list_state : temporal (list expr) :=
do `(tl_seq %%ps %%g) ← target | return [],
tactic.interactive.unfold
[ `has_append.append
, `list.append] (loc.ns [none]),
`(tl_seq %%ps %%g) ← target,
ps' ← parse_list ps,
tactic.interactive.unfold
[ `temporal.tl_seq
, `temporal.with_asms ] (loc.ns [none]),
tactic.intro_lst (`Γ :: ps'.map prod.fst)
private meta def within_list_state {α} (tac : expr → temporal α) : temporal α :=
do (Γ,ls,ls') ← enter_list_state,
tac ls' <* do
tactic.interactive.unfold
[ `temporal.with_asms
, `temporal.tl_seq
, `has_append.append
, `list.append] (loc.ns [none]),
tactic.intro_lst ((Γ :: ls : list _).map expr.local_pp_name)
meta def intro_aux (n : option name) : temporal (expr ⊕ name) :=
do ( to_expr ``(tl_seq _ (_ ⟶ _)) >>= change
<|> to_expr ``(tl_seq _ (p_forall _)) >>= change ),
`(tl_seq %%ps %%g) ← target >>= instantiate_mvars,
match g with
| `(%%p ⟶ %%q) :=
do let h := n.get_or_else `_,
tactic.refine ``(p_imp_intro_asms %%ps %%p %%q %%(reflect h.to_string) _),
return $ sum.inr h
| `(p_forall %%P) :=
do let h := n.get_or_else `_,
tactic.refine ``(p_forall_intro_asms %%ps %%P _),
x ← intro h,
P' ← head_beta (P x),
to_expr ``(tl_seq %%ps %%P') >>= unsafe_change ,
return $ sum.inl x
| _ := fail "expecting `_ ⟶ _` or `∀∀ _, _`"
end
def cons_opt {α β} : α ⊕ β → list α × list β → list α × list β
| (sum.inr y) (xs,ys) := (xs, y::ys)
| (sum.inl x) (xs,ys) := (x::xs, ys )
meta def intro_lst : option (list name) → temporal (list expr × list name)
| none := (cons_opt <$> intro_aux none <*> intro_lst none) <|> pure ([],[])
| (some []) := return ([],[])
| (some (x::xs)) := cons_opt <$> intro_aux (some x) <*> intro_lst (some xs)
meta def get_one_name : option (list name) → option (name × option (list name))
| none := some (`_, none)
| (some []) := none
| (some (x::xs)) := some (x, some xs)
open list (hiding map)
meta def intros : option (list name) → temporal (list expr)
| ns :=
do some (n,ns') ← pure (get_one_name ns) | return [],
mcond (succeeds $ to_expr ``(_ ⊢ _ ⟶ _) >>= change <|>
to_expr ``(_ ⊢ p_forall _) >>= change)
(do g ← target,
match g with
| `(%%Γ ⊢ %%p ⟶ %%q) := do
try (to_expr ``(persistent %%Γ) >>= mk_instance >>= clear),
(es,ls') ← within_list_state (λ _, intro_lst ns),
(++) es <$> tactic.intro_lst ls'
| `(%%Γ ⊢ p_forall (λ _, %%P)) := do
refine ``((p_forall_to_fun %%Γ (λ _, %%P)).mpr _),
n ← tactic.intro n,
to_expr ``(%%Γ ⊢ %%(P.instantiate_var n)) >>= change,
cons n <$> intros ns'
| _ := fail "expecting `_ ⟶ _` or `∀∀ _, _`"
end)
(return [])
meta def intro1 (n : option name) : temporal expr :=
do to_expr ``(_ ⊢ _ ⟶ _) >>= change <|>
to_expr ``(_ ⊢ p_forall _) >>= change <|>
fail "expecting `_ ⟶ _` or `∀∀ _, _`",
g ← target,
match g with
| `(%%Γ ⊢ %%p ⟶ %%q) := do
try (to_expr ``(persistent %%Γ) >>= mk_instance >>= clear),
let h := n.get_or_else `_,
within_list_state (λ ps, tactic.refine ``(p_imp_intro_asms %%ps %%p %%q %%(reflect h.to_string) _)),
intro h
| `(%%Γ ⊢ p_forall (λ _, %%P)) := do
refine ``((p_forall_to_fun %%Γ (λ _, %%P)).mpr _),
n ← tactic.intro $ n.get_or_else `_,
n <$ (to_expr ``(%%Γ ⊢ %%(P.instantiate_var n)) >>= change)
| _ := fail "expecting `_ ⟶ _` or `∀∀ _, _`"
end
/-- Introduces new hypotheses with forward dependencies -/
meta def intros_dep : tactic (list expr) :=
do g ← target | return [],
match g with
| `(_ ⊢ p_forall _) := lift₂ (::) (intro1 none) intros_dep
| `(tl_seq %%ps (p_forall %%P)) :=
do tactic.refine ``(p_forall_intro_asms %%ps %%P _),
x ← intro P.binding_name,
P' ← head_beta (P x),
to_expr ``(tl_seq %%ps %%P') >>= unsafe_change ,
cons x <$> intros_dep
| _ := return []
end
@[user_attribute]
meta def lifted_congr_attr : user_attribute :=
{ name := `lifted_congr
, descr := "congruence lemmas for temporal logic" }
@[user_attribute]
meta def timeless_congr_attr : user_attribute :=
{ name := `timeless_congr
, descr := "congruence lemmas for temporal logic" }
meta def apply_lifted_congr : tactic unit :=
do xs ← attribute.get_instances `lifted_congr,
xs.any_of (λ thm, do l ← resolve_name thm >>= to_expr, apply l),
return ()
meta def apply_timeless_congr : tactic unit :=
do xs ← attribute.get_instances `timeless_congr,
xs.any_of (λ thm, do l ← resolve_name thm >>= to_expr, () <$ apply l) <|> apply_lifted_congr
meta def force (p : pexpr) (e : expr) : tactic expr :=
do p' ← to_expr p,
unify e p',
instantiate_mvars p' <* cleanup
meta def app_ctx_aux (g : expr → expr)
: list (expr → expr) → list expr → expr → list ( (expr → expr) × expr )
| r₀ r₁ (expr.app f a) := app_ctx_aux ((λ e, g $ f.mk_app (e :: r₁)) :: r₀) (a :: r₁) f
| r₀ r₁ e := list.zip r₀ r₁
meta def app_ctx (g : expr → expr)
: expr → list ( (expr → expr) × expr ) :=
app_ctx_aux g [] []
meta def match_context_core : pattern → list ((expr → expr) × expr) → tactic (expr → expr)
| p [] := failed
| p ((f,e)::es) :=
f <$ match_pattern p e
<|>
match_context_core p es
<|>
if e.is_app
then match_context_core p (app_ctx f e)
else failed
meta def match_context (p : pexpr) (e : expr) : tactic (expr → expr) :=
do new_p ← pexpr_to_pattern p,
match_context_core new_p [(id,e)]
lemma v_eq_symm_h {α} {Γ : cpred} {v₀ v₁ : tvar α}
(h : Γ ⊢ ◻(v₁ ≃ v₀))
: Γ ⊢ ◻(v₀ ≃ v₁) :=
begin
revert h, apply p_impl_revert,
revert Γ, change (_ ⟹ _),
mono,
lifted_pred, intro h, rw h
end
meta def temporal_eq_proof (Γ h' x' y' t : expr) (hence : bool) (cfg : rewrite_cfg := {})
: tactic (expr × expr × list expr) :=
do let (x,y) := if cfg.symm then (y',x')
else (x',y'),
err ← pp x,
ctx ← match_context (to_pexpr x) t <|> fail format!"no instance of {err} found",
let t' := ctx y,
p ← to_expr ``(%%Γ ⊢ %%t ≃ %%t'),
((),prf) ← solve_aux p (do
if hence then do
h ← if cfg.symm then to_expr ``(v_eq_symm_h %%h')
else return h',
h' ← mk_fresh_name,
note h' none h,
interactive.persistent [],
h ← get_local h',
`(%%Γ ⊢ _) ← target,
rule ← to_expr ``(predicate.p_impl_revert (henceforth_str _ %%Γ) %%h) <|> pure h,
repeat (() <$ apply rule <|> refine ``(v_eq_refl _ _) <|> apply_timeless_congr),
all_goals $
exact rule,
return ()
else do
h ← if cfg.symm then to_expr ``(v_eq_symm %%h')
else return h',
repeat (() <$ apply h <|> refine ``(v_eq_refl _ _) <|> apply_lifted_congr),
done),
prf' ← to_expr ``(judgement_congr %%prf),
new_t ← to_expr ``(%%Γ ⊢ %%t'),
return (new_t,prf',[])
meta def tmp_head : expr → temporal expr | e :=
do t ← infer_type e >>= whnf,
match t with
| (expr.pi v bi e₀ e₁) :=
do v ← mk_meta_var e₀,
tmp_head (e v)
| `(_ ⊢ _) :=
do v ← mk_mvar,
t_to_expr ``(%%e %%v) >>= tmp_head <|> return e
| _ := return e
end
-- this is to justify using `whnf` before pattern matching when dealing w
-- with sequents
run_cmd do
v₀ ← mk_local_def `v `(cpred),
e ← to_expr ``(%%v₀ ⊢ %%v₀ ⟶ %%v₀),
e' ← whnf e,
guard (e' = e) <|> fail "_ ⊢ _ ⟶ _ does not reduce to itself"
/--
Must distinguish between three cases on the shape of assumptions:
h : Γ ⊢ ◽(x ≡ y)
h : x = y
h : x ↔ y
two cases on the shape of target:
e: f x
e: Γ ⊢ f x
two cases on the shape of target:
h : Γ ⊢ ◽(x ≡ y) → Γ ⊢ f x = f y
h : Γ ⊢ ◽(x ≡ y) → Γ ⊢ f x = Γ ⊢ f y
h : Γ ⊢ ◽(x ≡ y) → Γ ⊢ f x ≡ f y
h : Γ ⊢ ◽(x ≡ y) ⟶ f x ≡ f y
h : ⊩ ◽(x ≡ y) ⟶ f x ≡ f y
-/
meta def rewrite_tmp (Γ h : expr) (e : expr) (cfg : rewrite_cfg := {}) : tactic (expr × expr × list expr) :=
do e ← instantiate_mvars e >>= whnf,
match e with
| e'@`(%%Γt ⊢ %%e) :=
do h ← tmp_head h,
ht ← infer_type h >>= whnf,
match ht with
| `(%%Γr ⊢ ◻%%p) :=
do `(%%x ≃ %%y) ← force ``(_ ≃ _) p,
temporal_eq_proof Γ h x y e tt cfg
| `(%%Γr ⊢ %%p) :=
do `(%%x ≃ %%y) ← force ``(_ ≃ _) p,
b ← try_core $ to_expr ``(persistent %%Γr) >>= mk_instance,
temporal_eq_proof Γ h x y e b.is_some cfg
| _ :=
do (new_t, prf, metas) ← rewrite_core h e cfg,
prf' ← to_expr ``(congr_arg (judgement %%Γt) %%prf),
new_t' ← to_expr ``(judgement %%Γt %%new_t),
try_apply_opt_auto_param cfg.to_apply_cfg metas,
(new_t', prf', metas) <$ is_def_eq Γ Γt <|> pure (new_t,prf,metas)
end
| _ := do
(new_t, prf, metas) ← rewrite_core h e cfg,
try_apply_opt_auto_param cfg.to_apply_cfg metas,
return (new_t, prf, metas)
end
meta def rewrite_target (Γ h : expr) (cfg : rewrite_cfg := {}) : tactic unit :=
do t ← target,
(new_t, prf, _) ← rewrite_tmp Γ h t cfg,
e ← to_expr ``(%%t = %%new_t),
replace_target new_t prf
meta def rewrite_hyp (Γ h : expr) (hyp : expr) (cfg : rewrite_cfg := {}) : tactic expr :=
do hyp_type ← infer_type hyp,
(new_hyp_type, prf, _) ← rewrite_tmp Γ h hyp_type cfg,
replace_hyp hyp new_hyp_type prf
meta def rw_goal (Γ : expr) (cfg : rewrite_cfg) (rs : list rw_rule) : temporal unit :=
rs.mmap' $ λ r, do
save_info r.pos,
eq_lemmas ← get_rule_eqn_lemmas r,
orelse'
(do e ← to_expr' r.rule, rewrite_target Γ e {symm := r.symm, ..cfg})
(eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target Γ e {symm := r.symm, ..cfg})
(eq_lemmas.empty)
private meta def uses_hyp (e : expr) (h : expr) : bool :=
e.fold ff $ λ t _ r, r || to_bool (t = h)
meta def rw_hyp (Γ : expr) (cfg : rewrite_cfg) : list rw_rule → expr → temporal unit
| [] hyp := skip
| (r::rs) hyp := do
save_info r.pos,
eq_lemmas ← get_rule_eqn_lemmas r,
orelse'
(do e ← to_expr' r.rule,
when (not (uses_hyp e hyp)) $
rewrite_hyp Γ e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)
(eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp Γ e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)
(eq_lemmas.empty)
meta def rewrite (rs : rw_rules_t) (loca : loc) (cfg : rewrite_cfg) : temporal unit :=
do `(%%Γ ⊢ _) ← target,
match loca with
| loc.wildcard := loca.try_apply (rw_hyp Γ cfg rs.rules) (rw_goal Γ cfg rs.rules)
| _ := loca.apply (rw_hyp Γ cfg rs.rules) (rw_goal Γ cfg rs.rules)
end,
try (reflexivity reducible : temporal _),
(returnopt rs.end_pos >>= save_info <|> skip)
meta def solve1 : temporal unit → temporal unit :=
tactic.interactive.solve1
protected meta def note (h : name) : option expr → expr → temporal expr
| none pr :=
do p ← infer_type pr >>= beta_reduction,
assertv h p pr
| (some p) pr := assertv h p pr
/-- bind the initial value of state-dependent expression
`e` to global (through time) name `n`
-/
meta def bind_name (e : expr) (n h : name) : temporal expr :=
do refine ``(one_point_elim _ _ %%e _),
x ← tactic.intro n,
temporal.intros (some [h]),
return x
meta def existsi (e : expr) (id : name) : temporal unit :=
do `(%%Γ ⊢ ∃∃ _ : %%t, %%intl) ← target,
infer_type Γ >>= match_expr ``(cpred),
let r := e.get_app_fn,
let v := if r.is_constant
then update_name (λ s, s ++ "₀") (strip_prefix r.const_name)
else if r.is_local_constant
then update_name (λ s, s ++ "₀") r.local_pp_name
else `v₀,
t' ← infer_type e,
w ← (match_expr ``(tvar %%t) t' >> (bind_name e v id) <|> return e),
refine ``(p_exists_to_fun %%w _)
meta def specialized_apply (t : expr) : expr → temporal unit
| e :=
do t' ← infer_type e,
type_check e,
if sizeof t' < sizeof t then () <$ tactic.apply e
else
() <$ tactic.apply e <|>
do
v ← mk_mvar,
e' ← mk_tmp_app e v,
specialized_apply e'
meta def apply (e : expr) : temporal unit :=
do g :: gs ← get_goals,
t ← target,
specialized_apply t e
<|> interactive.strengthening (specialized_apply t e)
<|> () <$ tactic.apply e, -- we try `tactic.apply l` again
-- knowing that if we go back to
-- it, it will fail and we'll have
-- a proper error message
gs' ← get_goals, set_goals gs',
all_goals (try (execute (pure ()))),
gs' ← get_goals, set_goals (gs' ++ gs)
namespace interactive
open lean.parser interactive interactive.types lean
open expr -- tactic.interactive (rcases_parse rcases_parse.invert)
local postfix `?`:9001 := optional
local postfix *:9001 := many
precedence `[|`:1024
precedence `|]`:0
meta def abstract_names_p (f : name → option ℕ) : ℕ → pexpr → pexpr
| k e@(expr.local_const _ n _ _) := option.cases_on (f n) e (λ i, expr.var $ i + k)
| k e@(expr.const n _) := option.cases_on (f n) e expr.var
| k e@(var n) := e
| k e@(sort l) := e
| k e@(mvar n m t) := e
| k (app e₀ e₁) := app (abstract_names_p k e₀) (abstract_names_p k e₁)
| k (lam n bi e t) := lam n bi (abstract_names_p k e) (abstract_names_p (k+1) t)
| k (pi n bi e t) := pi n bi (abstract_names_p k e) (abstract_names_p (k+1) t)
| k (elet n g e b) := elet n (abstract_names_p k g) (abstract_names_p k e) (abstract_names_p (k+1) b)
| k (macro d args) := macro d $ args.map (abstract_names_p k)
meta def var_type : pexpr → pexpr
| (app _ t) := t
| t := t
meta def lambdas_p_aux : list pexpr → pexpr → pexpr
| (local_const _ n bi t :: ts) e := lambdas_p_aux ts $ lam n bi (var_type t) e
| _ e := e
def index_of {α} [decidable_eq α] (xs : list α) (x : α) : option ℕ :=
let r := list.index_of x xs in
if r < xs.length then r
else none
meta def lambdas_p (vs : list pexpr) (e : pexpr) : pexpr :=
lambdas_p_aux vs (abstract_names_p (index_of (vs.map expr.local_pp_name)) 0 e)
meta def mk_app_p : pexpr → list pexpr → pexpr
| e (e' :: es) := mk_app_p ``(var_seq %%e %%e') es
| e [] := e
@[user_notation]
meta def scoped_var (_ : parse $ tk "[|")
(ls : parse $ ident* <* tk ",")
(e : parse $ texpr <* tk "|]") : lean.parser pexpr :=
do vs ← ls.mmap (λ pp_n, do (e,_) ← with_input texpr pp_n.to_string,
return e ),
let r := mk_app_p ``( ⟪ ℕ, %%(lambdas_p vs.reverse e) ⟫ ) vs,
return r
meta def skip : temporal unit :=
tactic.skip
meta def done : temporal unit :=
tactic.done
meta def itactic : Type :=
temporal unit
meta def timetac (s : string) (tac : itactic) : temporal unit :=
tactic.timetac s tac
meta def solve1 : itactic → temporal unit :=
tactic.interactive.solve1
meta def clear : parse ident* → tactic unit :=
tactic.clear_lst
meta def explicit
(st : parse (ident <|> pure `σ))
(tac : tactic.interactive.itactic) : temporal unit :=
do `(%%Γ ⊢ _) ← target,
asms ← get_assumptions,
constructor,
st ← tactic.intro st,
hΓ ← tactic.intro `hΓ,
asms.for_each (λ h, do
e ← to_expr ``(judgement.apply %%h %%st %%hΓ),
note h.local_pp_name none e,
tactic.clear h),
try $ tactic.interactive.simp none ff
(map simp_arg_type.expr [``(function.comp),``(temporal.init)]) []
(loc.ns $ none :: map (some ∘ expr.local_pp_name) asms),
done <|> solve1 (do
tactic.clear hΓ,
try (to_expr ``(temporal.persistent %%Γ) >>= mk_instance >>= tactic.clear),
tactic.clear Γ,
tac)
meta def list_state_vars (t : expr) : tactic (list expr) :=
do ls ← local_context,
pat ← pexpr_to_pattern ``(var %%t _),
ls.mfilter (λ v, do t ← infer_type v,
tt <$ match_pattern pat t <|> pure ff)
meta def reverting {α} (h : expr → tactic bool) (tac : tactic α) : tactic α :=
do ls ← local_context,
hs ← ls.mfilter h,
tactic.revert_lst hs,
tac <* tactic.intro_lst (hs.map expr.local_pp_name)
meta def rename' (curr : expr) (new : name) : tactic expr :=
do n ← tactic.revert curr,
tactic.intro new
<* tactic.intron (n - 1)
structure explicit_opts :=
(verbose := ff)
meta def subst_state_variables (σ : expr) (p : explicit_opts) : tactic unit :=
do vs ← list_state_vars `(ℕ),
let ns := name_set.of_list (vs.map expr.local_uniq_name),
vs' ← reverting (λ h, do t ← infer_type h, return $ t.has_local_in ns) (do
vs.mmap $ λ v, do
let n := v.local_pp_name,
let n_primed := update_name (λ s, s ++ "'") v.local_pp_name,
n' ← mk_fresh_name,
v ← rename v.local_pp_name n' >> get_local n',
p ← to_expr ``(%%σ ⊨ %%v),
try (generalize p n >> tactic.intro1),
p' ← to_expr ``(nat.succ %%σ ⊨ %%v),
try (generalize p' n_primed >> tactic.intro1),
return v),
-- ls ← local_context >>= mfilter (λ h, do t ← infer_type h, return $ σ.occurs t),
when p.verbose trace_state,
tactic.clear σ,
mmap' tactic.clear vs'.reverse
meta def resetI : temporal unit := tactic.interactive.resetI
open function
meta def explicit'
(iota : parse (tk "!")?)
(keep_all : parse (tk "*")?)
(rs : parse simp_arg_list)
(hs : parse with_ident_list)
(tac : tactic.interactive.itactic)
(opt : explicit_opts := {})
: temporal unit :=
solve1 $
do hs ← hs.mmap get_local,
`(%%Γ ⊢ _) ← target >>= instantiate_mvars,
let st := `σ,
when keep_all.is_none (do
asms ← get_assumptions,
(asms.diff hs).mmap' tactic.clear),
asms ← get_assumptions,
asms.mmap'
(λ h, do b ← is_henceforth h,
when b $ do
to_expr ``(p_impl_revert (henceforth_str _ _) %%h)
>>= note h.local_pp_name none,
tactic.clear h),
asms ← get_assumptions,
constructor,
st ← tactic.intro st,
hΓ ← tactic.intro `hΓ,
asms.for_each (λ h, do
e ← to_expr ``(judgement.apply %%h %%st %%hΓ),
note h.local_pp_name none e,
tactic.clear h),
let rs' := map simp_arg_type.expr
[``(function.comp),``(on_fun),``(prod.map),``(prod.map_left),``(prod.map_right)
,``(coe),``(lift_t),``(has_lift_t.lift),``(coe_t),``(has_coe_t.coe)
,``(coe_b),``(has_coe.coe)
,``(coe_fn), ``(has_coe_to_fun.coe), ``(coe_sort), ``(has_coe_to_sort.coe)
] ++
rs,
let l := (loc.ns $ none :: map (some ∘ expr.local_pp_name) asms),
tactic.interactive.simp iota ff rs' [`predicate] l
{ fail_if_unchanged := ff },
done <|> solve1 (do
tactic.clear hΓ,
try (to_expr ``(temporal.persistent %%Γ) >>= mk_instance >>= tactic.clear),
tactic.clear Γ,
subst_state_variables st opt,
tac)
-- `[rw [models_to_fun_var']]
meta def same_type (e₀ e₁ : expr) : temporal unit :=
do t₀ ← infer_type e₀,
t₁ ← infer_type e₁,
is_def_eq t₀ t₁
meta def «let» := tactic.interactive.«let»
meta def «have» (h : parse ident?)
(q₁ : parse (tk ":" *> texpr)?)
(q₂ : parse $ (tk ":=" *> texpr)?)
: tactic expr :=
let h := h.get_or_else `this in
match q₁, q₂ with
| some e, some p := do
`(%%Γ ⊢ _) ← target,
t ← i_to_expr e,
t' ← to_expr ``(%%Γ ⊢ %%t),
p ← t_to_expr p,
v ← to_expr ``(%%p : %%t'),
tactic.assertv h t' v
| none, some p := do
`(%%Γ ⊢ _) ← target,
p ← t_to_expr p,
h ← temporal.note h none p,
(fix_assumptions Γ h) <|> return h
| some e, none := do
`(%%Γ ⊢ _) ← target,
e' ← i_to_expr e,
p ← i_to_expr ``(%%Γ ⊢ %%e),
tactic.assert h p
| none, none := do
`(%%Γ ⊢ _) ← target,
t ← infer_type Γ >>= beta_reduction,
e ← mk_meta_var t,
i_to_expr ``(%%Γ ⊢ %%e) >>= tactic.assert h
end
meta def strengthen_to (e : parse texpr) : temporal unit :=
strengthening (to_expr ``(_ ⊢ %%e) >>= change)
meta def intro (n : parse ident_?) : temporal unit :=
() <$ temporal.intros (some [n.get_or_else `_])
meta def intros : parse ident_* → temporal unit
| [] := () <$ temporal.intros none
| xs := () <$ temporal.intros (some xs)
meta def introv' : parse ident_* → temporal (list expr)
| [] := intros_dep
| (n::ns) := do hs ← intros_dep,
try (enter_list_state),
h ← intro_aux n,
hs' ← introv ns,
return (hs ++ hs')
meta def introv (ls : parse ident_*) : temporal (list expr) :=
(++) <$> introv' ls <*> exit_list_state
meta def revert (ns : parse ident*) : temporal unit :=
mmap get_local ns >>= mmap' temporal.revert
meta def exact (e : parse texpr) : temporal unit :=
t_to_expr e >>= tactic.exact
meta def refine (e : parse texpr) : temporal unit :=
do t ← target,
to_expr ``(%%e : %%t) >>= tactic.exact
meta def apply (q : parse texpr) : temporal unit :=
t_to_expr_for_apply q >>= temporal.apply
meta def trivial : temporal unit :=
`[apply of_eq_true (True_eq_true _)]
meta def rw (rs : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := { }) : temporal unit :=
rewrite rs l cfg ; (trivial <|> solve_by_elim <|> reflexivity <|> return ())
meta def rewrite (rs : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := { }) : temporal unit :=
rw rs l cfg
private meta def cases_arg_p : lean.parser (option name × pexpr) :=
with_desc "(id :)? expr" $ do
t ← texpr,
match t with
| (local_const x _ _ _) :=
(tk ":" *> do t ← texpr, pure (some x, t)) <|> pure (none, t)
| _ := pure (none, t)
end
meta def sequent_type (p : expr) : tactic (option (expr × expr × expr)) :=
do t ← infer_type p,
`(%%Γ ⊢ _) ← target,
match t with
| `(%%Γ ⊢ %%q) := return (some (Γ,p,q))
| `(⊩ %%q) := return (some (Γ,p Γ, q))
| _ := return none
end
meta def break_conj (Γ p p' a b : expr) (ids : list name) : temporal unit :=
do let h₀ : name := (ids.nth 0).get_or_else `a,
let h₁ : name := (ids.nth 1).get_or_else `a,
h₀ ← to_expr ``(p_and_elim_left %%a %%b %%Γ %%p') >>= note h₀ none,
h₁ ← to_expr ``(p_and_elim_right %%a %%b %%Γ %%p') >>= note h₁ none,
when p.is_local_constant (tactic.clear p),
revert_lst [h₀,h₁],
intron 2
meta def break_disj (Γ p p' a b : expr) (ids : list name) : temporal unit :=
do let h₀ : name := (ids.nth 0).get_or_else `a,
let h₁ : name := (ids.nth 1).get_or_else `a,
g ← target,
note `h none p',
revert [`h],
when p.is_local_constant (tactic.clear p),
apply ``(@p_or_entails_of_entails' _ %%Γ %%a %%b _ _)
; [ intros [h₀] , intros [h₁] ],
tactic.swap
meta def cases_dt (e : parse cases_arg_p) (ids : parse with_ident_list) : temporal unit :=
do e' ← to_expr e.2,
t ← infer_type e',
let h₀ : name := (ids.nth 0).get_or_else `a,
let h₁ : name := (ids.nth 1).get_or_else `a,
(do match_expr ``(tvar (_ × _)) t,
reverting (λ h, do t ← infer_type h, return $ e'.occurs t) $ do
h ← to_expr ``(eta_pair %%e') >>= note `h none,
tactic.revert h,
e' ← if e'.is_local_constant
then mk_fresh_name >>= rename' e'
else return e',
to_expr ``(pair.fst ! %%e') >>= λ e, tactic.generalize e h₀ >> tactic.intro1,
to_expr ``(pair.snd ! %%e') >>= λ e, tactic.generalize e h₁ >> tactic.intro1,
h ← tactic.intro1,
z ← if e'.is_local_constant then return e'
else tactic.generalize e' `z >> tactic.intro1,
tactic.subst z )
<|>
tactic.interactive.cases e ids
meta def match_pexpr (p : pexpr) (e : expr) : temporal unit :=
to_expr p >>= unify e
meta def cases (e : parse cases_arg_p) (ids : parse with_ident_list) : temporal unit :=
do p' ← to_expr e.2,
(some (Γ,p,q)) ← sequent_type p' | cases_dt e ids,
a ← mk_mvar, b ← mk_mvar,
(do match_pexpr ``(◻(%%a ⋀ %%b)) q,
p₁ ← to_expr ``(eq.mp (congr_arg (judgement %%Γ) (henceforth_and %%a %%b)) %%p),
a ← to_expr ``(◻%%a),
b ← to_expr ``(◻%%b),
-- p' ← mk_app `eq.mp [p₀,p],
break_conj Γ p' p₁ a b ids) <|>
(do match_pexpr ``(%%a ⋀ %%b) q,
break_conj Γ p p a b ids) <|>
(do match_pexpr ``(%%a ⋁ %%b) q,
break_disj Γ p p a b ids) <|>
(do match_pexpr ``(◇(%%a ⋁ %%b)) q,
p₁ ← to_expr ``(eq.mp (congr_arg (judgement %%Γ) (eventually_or %%a %%b)) %%p),
a ← to_expr ``(◇%%a),
b ← to_expr ``(◇%%b),
break_disj Γ p' p₁ a b ids) <|>
(do match_pexpr ``(p_exists %%b) q,
let h₀ : name := (ids.nth 0).get_or_else `_,
let h₁ : name := (ids.nth 1).get_or_else `_,
h ← note `h none p',
when p'.is_local_constant (tactic.clear p'),
revert [`h], h ← to_expr ``(p_exists_imp_eq_p_forall_imp _ _),
tactic.rewrite_target h, intros [h₀,h₁]) <|>
(do q ← pp q, fail format!"case expression undefined on {q}")
private meta def cases_core (p : expr) : tactic unit :=
() <$ cases (none,to_pexpr p) []
meta def by_cases : parse cases_arg_p → tactic unit
| (n, q) := do
`(%%Γ ⊢ _) ← target,
p ← t_to_expr q,
let ids : list _ := n.to_monad,
cases (none,``(predicate.em %%p %%Γ)) $ ids ++ ids
private meta def find_matching_hyp (ps : list pattern) : tactic expr :=
any_hyp $ λ h, do
type ← infer_type h,
ps.mfirst $ λ p, do
match_pattern p type,
return h
open temporal.interactive (rename')
meta def select (h : parse $ ident <* tk ":") (p : parse texpr) : temporal unit :=
do `(%%Γ ⊢ _) ← target,
p₀ ← pexpr_to_pattern ``(%%Γ ⊢ %%p),
p₁ ← pexpr_to_pattern p,
any_hyp (λ h', infer_type h' >>= match_pattern p₀ >> () <$ rename' h' h)
<|> any_hyp (λ h', infer_type h' >>= match_pattern p₁ >> () <$ rename' h' h)
meta def cases_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : temporal unit :=
do ps ← lift₂ (++) (ps.mmap pexpr_to_pattern)
(ps.mmap $ λ p, pexpr_to_pattern ``(_ ⊢ %%p)),
if rec.is_none
then find_matching_hyp ps >>= cases_core
else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core
/-- Shorthand for `cases_matching` -/
meta def casesm (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : temporal unit :=
cases_matching rec ps
-- meta def rcases (e : parse cases_arg_p)
-- (ids : parse (tk "with" *> rcases_parse)?)
-- : temporal unit :=
-- do let patts := rcases_parse.invert $ ids.get_or_else [default _],
-- _
meta def assume_negation (n : parse (tk "with" *> ident)?) : temporal unit :=
do `(_ ⊢ %%t) ← target,
let h := n.get_or_else `h,
cases (none, ``(predicate.em %%t)) [h,h],
solve1 (do h ← get_local h, tactic.exact h)
meta def induction
(obj : parse interactive.cases_arg_p)
(rec_name : parse using_ident)
(ids : parse with_ident_list)
(revert : parse $ (tk "generalizing" *> ident*)?)
: tactic unit :=
do `(%%Γ ⊢ _) ← target,
(tactic.interactive.induction obj rec_name ids revert) ;
(local_context >>= mmap' (fix_or_clear_assumption Γ))
meta def case (ctor : parse ident*) (ids) (tac : itactic) : tactic unit :=
tactic.interactive.case ctor ids tac
meta def focus_left' (id : option name) : temporal expr :=
do `(%%Γ ⊢ _ ⋁ _) ← target | fail "expecting `_ ⋁ _`",
`[rw [p_or_comm,← p_not_p_imp]],
temporal.intro1 id
meta def focus_left (ids : parse with_ident_list) : temporal unit :=
() <$ focus_left' ids.head'
meta def focusing_left (ids : parse with_ident_list) (tac : itactic) : temporal unit :=
do x ← focus_left' ids.head',
focus1 (do
tac,
get_local x.local_pp_name >>= temporal.revert,
`[rw [p_not_p_imp,← p_or_comm]])
meta def focus_right' (id : option name) : temporal expr :=
do `(%%Γ ⊢ _ ⋁ _) ← target | fail "expecting `_ ⋁ _`",
`[rw [← p_not_p_imp]],
temporal.intro1 id
meta def focus_right (ids : parse with_ident_list) : temporal unit :=
() <$ focus_right' ids.head'
meta def focusing_right (ids : parse with_ident_list) (tac : itactic) : temporal unit :=
do x ← focus_right' ids.head',
focus1 (do
tac,
get_local x.local_pp_name >>= temporal.revert,
`[rw [p_not_p_imp]])
meta def split (greedy : parse $ (tk "!")?) (rec : parse $ (tk "*")?) : temporal unit :=
let goal := if greedy.is_some
then target >>= force ``(_ ⊢ _ ⋀ _)
else target in
if rec.is_some then
focus1 $ repeat $ do
`(%%Γ ⊢ %%p ⋀ %%q) ← goal,
temporal.interactive.exact ``(p_and_intro %%p %%q %%Γ _ _)
else do
`(%%Γ ⊢ %%p ⋀ %%q) ← target >>= force ``(_ ⊢ _ ⋀ _),
temporal.interactive.exact ``(p_and_intro %%p %%q %%Γ _ _)
meta def existsi : parse pexpr_list_or_texpr → parse with_ident_list → temporal unit
| [] _ := return ()
| (p::ps) xs :=
do e ← i_to_expr p,
have h : inhabited name, from ⟨ `_ ⟩,
temporal.existsi e (@list.head _ h xs),
existsi ps xs.tail
meta def clear_except :=
tactic.interactive.clear_except
meta def action (ids : parse with_ident_list) (tac : tactic.interactive.itactic) : temporal unit :=
do `[ try { simp only [predicate.p_not_comp,temporal.next_eq_action,temporal.next_eq_action',temporal.not_action] },
try { simp only [predicate.p_not_comp,temporal.init_eq_action,temporal.init_eq_action',temporal.not_action
,temporal.action_and_action,predicate.models_pred
,predicate.models_prop] },
repeat { rw ← temporal.action_imp } ],
get_assumptions >>= list.mmap' tactic.clear,
`(%%Γ ⊢ temporal.action %%A %%v ) ← target,
refine ``(temporal.unlift_action %%A %%v _),
tactic.intro_lst [`σ,`σ'],
mmap' tactic.intro ids,
solve1 tac
meta def print := tactic.print
meta def repeat (tac : itactic) : temporal unit :=
tactic.repeat tac
meta def lifted_pred
(no_dflt : parse only_flag)
(rs : parse simp_arg_list)
(us : parse using_idents)
: temporal unit :=
tactic.interactive.lifted_pred ff no_dflt rs us
meta def propositional : temporal unit :=
tactic.interactive.propositional
meta def match_head (e : expr) : expr → tactic unit
| e' :=
unify e e'
<|> (do `(_ → %%e') ← whnf e',
v ← mk_mvar,
match_head (e'.instantiate_var v))
<|> (do `(%%Γ ⊢ _ ⟶ %%e') ← whnf e',
e'' ← to_expr ``(%%Γ ⊢ %%e'),
match_head e'')
<|> (do `(%%Γ ⊢ p_forall %%(expr.lam _ _ t e')) ← whnf e',
v ← mk_meta_var t,
e'' ← to_expr ``(%%Γ ⊢ %%(e'.instantiate_var v)),
match_head e'')
meta def find_matching_head : expr → list expr → tactic (list expr)
| e [] := return []
| e (H :: Hs) :=
do t ← infer_type H,
(list.cons H <$ match_head e t <|> pure id) <*> find_matching_head e Hs
meta def apply_assumption
(asms : option (list expr) := none)
(tac : temporal unit := return ()) : tactic unit :=
do { ctx ← asms.to_monad <|> local_context,
t ← target,
hs ← find_matching_head t ctx,
hs.any_of (λ H, (() <$ temporal.apply H ; tac : temporal unit)) } <|>
do { exfalso,
ctx ← asms.to_monad <|> local_context,
t ← target,
hs ← find_matching_head t ctx,
hs.any_of (λ H, (() <$ temporal.apply H ; tac : temporal unit)) }
<|> fail "assumption tactic failed"
/- TODO(Simon) Use -/
meta def assumption (tac : temporal unit := return ()) : temporal unit :=
do `(_ ⊢ _) ← target | tactic.interactive.apply_assumption local_context tac,
apply_assumption none tac <|> strengthening (apply_assumption none tac)
meta def try (tac : itactic) : temporal unit :=
tactic.try tac
meta def refl :=
do try (to_expr ``(ctx_impl _ _ _) >>= change),
tactic.reflexivity
meta def reflexivity :=
do try (to_expr ``(ctx_impl _ _ _) >>= change),
tactic.reflexivity
meta def ac_refl :=
do refine ``(entails_of_eq _ _ _ _) <|> refine ``(equiv_of_eq _ _ _ _),
tactic.ac_refl
meta def unfold_coes (ids : parse ident *) (l : parse location) (cfg : unfold_config := { }) : temporal unit :=
tactic.interactive.unfold_coes l >>
tactic.interactive.unfold ids l cfg
meta def unfold :=
tactic.interactive.unfold
meta def dunfold :=
tactic.interactive.dunfold
meta def dsimp :=
tactic.interactive.dsimp
meta def simp (use_iota_eqn : parse (parser.tk "!")?)
(no_dflt : parse only_flag)
(hs : parse simp_arg_list)
(attr_names : parse with_ident_list)
(locat : parse location)
(cfg : simp_config_ext := {}) : temporal unit :=
-- if locat.include_goal
-- then strengthening $ tactic.interactive.simp no_dflt hs attr_names locat cfg
do let attr_names :=
if no_dflt
then attr_names
else (`tl_simp :: attr_names),
tactic.interactive.simp use_iota_eqn no_dflt hs attr_names locat cfg,
try refl
meta def simp_coes
(iota : parse (tk "!")?)
(no_dflt : parse only_flag)
(hs : parse simp_arg_list)
(attr_names : parse with_ident_list)
(locat : parse location)
(cfg : simp_config_ext := {}) : temporal unit :=
do let attr_names :=
if no_dflt
then attr_names
else (`tl_simp :: attr_names),
tactic.interactive.simp_coes iota no_dflt hs attr_names locat cfg,
try refl
meta def exfalso : temporal unit :=
do `(%%Γ ⊢ %%p) ← target,
`[apply False_entails %%p %%Γ _]
meta def admit : temporal unit :=
tactic.admit
meta def left : temporal unit :=
do `(%%Γ ⊢ %%p ⋁ %%q) ← target,
apply ``(p_or_intro_left %%p %%q %%Γ _)
meta def right : temporal unit :=
do `(%%Γ ⊢ %%p ⋁ %%q) ← target,
apply ``(p_or_intro_right %%p %%q %%Γ _)
meta def solve_by_elim : temporal unit :=
assumption $ assumption $ assumption done
meta def tauto (greedy : parse (tk "!")?) : temporal unit :=
() <$ intros [] ;
casesm (some ()) [``(_ ⋀ _),``(_ ⋁ _)] ;
split greedy (some ()) ;
solve_by_elim
meta def specialize (h : parse texpr) : temporal unit :=
tactic.interactive.specialize h
meta def type_check
(e : parse texpr)
: tactic unit :=
do e ← t_to_expr e, tactic.type_check e, infer_type e >>= trace
def with_defaults {α} : list α → list α → list α
| [] xs := xs
| (x :: xs) (_ :: ys) := x :: with_defaults xs ys
| xs [] := xs
meta def rename_bound (n : name) : expr → expr
| (expr.app e₀ e₁) := expr.app e₀ (rename_bound e₁)
| (expr.lam _ bi t e) := expr.lam n bi t e
| e := e
meta def henceforth (pers : parse (tk "!")?) (l : parse location) : temporal unit :=
do when l.include_goal (do
when pers.is_some $ persistent [],
persistently $
refine ``(persistent_to_henceforth _)),
soft_apply l
(λ h, do b ← is_henceforth h,
when (¬ b) $ fail format!"{h} is not of the shape `□ _`",
to_expr ``(p_impl_revert (henceforth_str _ _) %%h)
>>= note h.local_pp_name none,
tactic.clear h)
(pure ())
meta def t_induction
(pers : parse $ (tk "!") ?)
(p : parse texpr?)
(specs : parse $ (tk "using" *> ident*) <|> pure [])
(ids : parse with_ident_list)
: tactic unit :=
do `(%%Γ ⊢ %%g) ← target,
match g with
| `(◻%%p) :=
do let xs := (with_defaults ids [`ih]).take 1,
ih ← to_expr ``(%%Γ ⊢ ◻(%%p ⟶ ⊙%%p)) >>= assert `ih,
b ← is_context_persistent,
when (b ∨ pers.is_some) $
focus1 (do
interactive.henceforth (some ()) (loc.ns [none]),
intros xs),
interactive.henceforth none (loc.ns $ specs.map some),
tactic.swap,
h₀ ← to_expr ``(%%Γ ⊢ %%p) >>= assert `this,
tactic.swap,
t_to_expr ``(temporal.induct %%p %%ih %%h₀) >>=
tactic.exact
| `(◇%%q ⋁ ◻%%p) :=
do let xs := (with_defaults ids [`ih]).take 1,
ih ← to_expr ``(%%Γ ⊢ ◻(%%p ⟶ -%%q ⟶ ⊙(%%p ⋁ %%q))) >>= assert `ih,
b ← is_context_persistent,
when (b ∨ pers.is_some) $
focus1 (do
interactive.henceforth (some ()) (loc.ns [none]),
intros xs),
tactic.swap,
h₀ ← to_expr ``(%%Γ ⊢ %%p) >>= assert `this,
tactic.swap,
t_to_expr ``(temporal.induct_evt %%p %%q %%ih %%h₀) >>= tactic.exact
| _ := fail "expecting goal of the form `◻p` or `◇q ⋁ ◻p`"
end
meta def wf_induction
(p : parse texpr)
(rec_name : parse (tk "using" *> texpr)?)
(ids : parse with_ident_list)
: tactic unit :=
do rec_name ← (↑rec_name : tactic pexpr) <|> return ``(has_well_founded.wf _),
to_expr ``(well_founded.induction %%rec_name %%p) >>= tactic.apply,
try $ to_expr p >>= tactic.clear,
ids' ← tactic.intro_lst $ (with_defaults ids [`x,`ih_1]).take 2 ,
h ← ids'.nth 1,
hp ← to_expr ``((p_forall_subtype_to_fun _ _ _).mpr %%h),
p ← rename_bound `y <$> infer_type hp,
assertv h.local_pp_name p hp,
tactic.clear h,
return ()
private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit
| [] r := fail "show tactic failed"
| (g::gs) r := do
do { set_goals [g],
g_ty ← target,
ty ← i_to_expr p,
unify g_ty ty,
set_goals (g :: r.reverse ++ gs),
tactic.change ty}
<|>
show_aux gs (g::r)
meta def «show» (q : parse $ texpr <* tk ",") (tac : tactic.interactive.itactic) : tactic unit :=
do gs ← get_goals,
show_aux q gs [],
solve1 tac
meta def rename (n₀ n₁ : parse ident) : temporal unit :=
tactic.rename n₀ n₁
meta def replace (n : parse ident)
: parse (parser.tk ":" *> texpr)? → parse (parser.tk ":=" *> texpr)? → temporal unit
| none (some prf) :=
do prf ← t_to_expr prf,
tactic.interactive.replace n none (to_pexpr prf) >> try (simp none tt [] [] (loc.ns [some n]))
| none none :=
tactic.interactive.replace n none none
| (some t) (some prf) :=
do t' ← to_expr t >>= infer_type,
tl ← tt <$ match_expr ``(pred' _) t' <|> pure ff,
if tl then do
`(%%Γ ⊢ _) ← target,
prf' ← t_to_expr prf,
tactic.interactive.replace n ``(%%Γ ⊢ %%t) (to_pexpr prf')
else tactic.interactive.replace n t prf
| (some t) none :=
do t' ← to_expr t >>= infer_type,
match_expr ``(pred' _) t' ,
`(%%Γ ⊢ _) ← target,
tactic.interactive.replace n ``(%%Γ ⊢ %%t) none
meta def transitivity : parse texpr? → temporal unit
| none := apply ``(predicate.p_imp_trans )
| (some p) := apply ``(@predicate.p_imp_trans _ _ _ %%p _ _ _)
lemma nonempty_of_tvar (α) {β} {Γ p : pred' α}
(v : tvar β)
(h' : Π [nonempty β], Γ ⊢ p)
: Γ ⊢ p :=
by { lifted_pred keep,
have inst := nonempty.intro (0 ⊨ v),
apply (@h' inst).apply _ a, }
lemma nonempty_of_p_exists (α) {β} {Γ p : pred' α} {q : β → pred' α}
(h : Γ ⊢ p_exists q)
(h' : Π [nonempty β], Γ ⊢ p)
: Γ ⊢ p :=
by { lifted_pred keep using h,
have inst := nonempty_of_exists h,
apply (@h' inst).apply _ a, }
meta def nonempty (t : parse texpr) : temporal unit :=
do `(%%Γ ⊢ %%p) ← target,
q ← mk_mvar,
do { v ← to_expr ``(%%Γ ⊢ @p_exists _ %%t %%q) >>= find_assumption,
refine ``(@nonempty_of_p_exists _ %%t %%Γ %%p %%q %%v _) } <|>
do { v ← to_expr ``(tvar %%t) >>= find_assumption,
refine ``(@nonempty_of_tvar _ %%t %%Γ %%p %%v _) },
tactic.intro1,
resetI,
return ()
section historyI
variable {α : Sort*}
-- variable [nonempty α]
variable {Γ : cpred}
-- variables I N : cpred
variables J HI : tvar (α → Prop)
open classical nat
variables HN : tvar (act α)
-- variables Γ : cpred
variable h_HI : Γ ⊢ ∃∃ h : α, HI h ⋀ J h
variable h_HN : Γ ⊢ ◻(∀∀ h : α, J h ⟶ ∃∃ h' : α, HN h h' ⋀ ⊙J h')
-- private def w : ℕ → α
-- | 0 := i ⊨ x₀
-- | (succ j) := (i + j ⊨ f) (w j)
include h_HI h_HN
lemma historyI
: Γ ⊢ ∃∃ w : tvar α, HI w ⋀ ◻HN w (⊙w) ⋀ ◻J w :=
begin [temporal]
nonempty α,
let x₀ : tvar α := ⟨ λ i, ε x, i ⊨ HI x ∧ i ⊨ J x ⟩,
let f : tvar (α → α) := ⟨ λ i x, ε x', i ⊨ HN x x' ∧ succ i ⊨ J x' ⟩ ,
have := fwd_witness x₀ f Γ,
cases this with w H, cases H with H₀ Hnext,
existsi w,
have : ◻J w,
{ t_induction,
explicit' [x₀] with H₀ h_HI
{ subst w, apply_epsilon_spec, },
henceforth! at *,
explicit' [f] with Hnext h_HN
{ subst w', intro, apply_epsilon_spec, } },
split*,
explicit' with this H₀ h_HI
{ revert this, subst w,
apply_epsilon_spec, },
{ henceforth! at *,
explicit' [f] with this Hnext h_HN
{ subst w', apply_epsilon_spec, }, },
assumption
end
-- variable (HN' : tvar α → tvar α → cpred)
lemma witness_elim' {P : cpred}
(J' : tvar α → cpred)
(HI' : tvar α → cpred)
(HN' : tvar α → tvar α → cpred)
(hJ : ∀ w, J w = J' w)
(hHI : ∀ w, HI w = HI' w)
(hHN : ∀ w, HN w (⊙w) = HN' w (⊙w))
(h : Γ ⊢ ∀∀ w, HI' w ⋀ ◻HN' w (⊙w) ⟶ ◻J' w ⟶ P)
: Γ ⊢ P :=
begin [temporal]
have := historyI J HI HN h_HI h_HN,
revert this,
simp [hJ,hHI,hHN] at ⊢ h,
exact h,
end
end historyI
lemma witness_elim {α} {P : tvar α → cpred} {Γ : cpred}
(x₀ : tvar α)
(f : tvar (α → α))
(h : Γ ⊢ ∀∀ w, w ≃ x₀ ⋀ ◻( ⊙w ≃ f w ) ⟶ P w)
: Γ ⊢ ∃∃ w, P w :=
begin [temporal]
have := fwd_witness x₀ f Γ,
revert this,
apply p_exists_p_imp_p_exists,
solve_by_elim
end
meta def lam_kabstract (e p : expr) (v : name := `_) : tactic expr :=
do t ← infer_type p,
lam v binder_info.default t <$> kabstract e p
-- do gs ← get_goals,
-- mv ← to_expr ``(%%e = %%e) >>= mk_meta_var,
-- set_goals [mv],
-- t ← infer_type p,
-- tactic.generalize p v,
-- v ← tactic.intro1,
-- tgt ← target,
-- (e,_) ← is_eq tgt,
-- lambdas' [v] e <* set_goals gs
-- run_cmd do
-- v ← mk_local_def `v `(ℕ),
-- v' ← mk_local_def `v `(ℕ),
-- f ← mk_local_def `f `(ℕ → ℕ → ℕ),
-- e ← to_expr ``(%%f (%%v + 1) (%%v + 2)),
-- p ← to_expr ``(%%v + 1),
-- p' ← to_expr ``(%%v + 2),
-- timetac "abstract_pattern" $ do
-- e' ← lam_kabstract e p `x,
-- e' ← lam_kabstract e' p' `y,
-- trace $ e',
-- timetac "kabstract" $ do
-- e' ← kabstract e p,
-- e' ← kabstract (e'.instantiate_var v') p',
-- trace $ e'.instantiate_var v
meta def brack_expr : lean.parser (name ⊕ pexpr) :=
sum.inl <$> ident <|> sum.inr <$> brackets "(" ")" texpr
/-- select_witness w : P w
with h₀ h₁
using inv
-/
meta def select_witness
(w : parse $ ident_ <* tk ":")
(p : parse texpr)
(asm : parse $ (tk "with" *> prod.mk <$> ident <*> ident?)?)
(inv : parse $ ((tk "using" *> texpr) <|> pure (``(True))) <* tk ",")
(tac : tactic.interactive.itactic)
: temporal unit :=
do `(%%Γ ⊢ %%q) ← target,
u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
u ← mk_app `temporal.tvar [t],
t' ← to_expr ``(%%u → cpred),
(_,p) ← solve_aux t' (do
tactic.intro w
<* (to_expr p >>= tactic.exact)),
-- <|> fail
-- "in tactic `select_witness w : P w`, `P w` should be of the form
-- `w ≃ x₀ ⋀ ◻(⊙w ≃ f w)`, where `x₀ : tvar α`, `f : tvar (α → α)`",
t' ← to_expr ``(tvar %%t → cpred),
(_,J) ← solve_aux t' (do
-- refine ``(to_fun_var _),
tactic.intro w,
to_expr inv >>= tactic.exact ),
v ← mk_local_def w u,
p' ← head_beta (p v),
-- q' ← head_beta (q v),
J' ← head_beta (J v),
(HI,HN) ← (do
mv ← mk_mvar,
init ← mk_mvar,
pat ← to_expr ``(%%init ⋀ ◻ %%mv),
unify p' pat,
init ← instantiate_mvars init,
mv ← instantiate_mvars mv,
nx_v ← to_expr ``(⊙ %%v),
v' ← infer_type v >>= mk_local_def v.local_pp_name,
mv ← lam_kabstract mv nx_v v.local_pp_name,
return (init.lambdas [v], mv.lambdas [v]) ),
new_g ← to_expr ``(%%p' ⟶ ◻%%J' ⟶ %%q),
new_g ← to_expr ``(%%Γ ⊢ p_forall %%(new_g.lambdas [v])) >>= mk_meta_var,
h₀ ← mk_mvar,h₁ ← mk_mvar,h₂ ← mk_mvar,h₃ ← mk_mvar,h₄ ← mk_mvar,
let (asm₀,asm₁) := asm.get_or_else (`_,`_),
let asm₁ := asm₁.get_or_else `_,
-- tactic.swap,
focus1 $ do
-- (hJ : ∀ w, J w = J' w)
-- (hHI : ∀ w, HI w = HI' w)
-- (hHN : ∀ w w', HN w w' = HN' w w')
-- (h : Γ ⊢ ∀∀ w, HI' w ⋀ ◻HN' w (⊙w) ⟶ ◻J' w ⟶ P)
refine ``(temporal.interactive.witness_elim'
(to_fun_var %%J) (to_fun_var %%HI) (to_fun_var' %%HN)
-- %%h₀ %%h₁ %%J %%HI %%h₂ %%h₃ %%new_g),
%%h₀ %%h₁ %%J %%HI %%HN %%h₂ %%h₃ %%h₄ %%new_g),
set_goals [h₁],
henceforth (some ()) loc.wildcard <|> fail "foo",
h₁::_ ← get_goals,
set_goals [new_g],
temporal.interactive.intros [w,asm₀,asm₁],
new_g::_ ← get_goals,
hs ← [h₂,h₃,h₄].mmap (λ h, do
set_goals [h],
focus1 `[intros, simp! only with lifted_fn],
get_goals ),
set_goals hs.join >> trace_state >> tac >> done,
set_goals [new_g]
#check witness_elim'
end interactive
/- end monotonicity -/
section
open tactic tactic.interactive (unfold_coes unfold itactic assert_or_rule)
open interactive interactive.types lean lean.parser
open applicative (mmap₂ lift₂)
open functor
local postfix `?`:9001 := optional
meta def mono1 (only_pers : parse (tk "!")?) : temporal unit :=
do ex ← (if ¬ only_pers.is_some then do
asms ← get_assumptions,
list.band <$> asms.mmap is_henceforth
else tt <$ interactive.persistent []),
if ex
then persistently $ do
to_expr ``(ctx_impl _ _ _) >>= change,
tactic.interactive.mono none interactive.mono_selection.both []
else do
to_expr ``(ctx_impl _ _ _) >>= change,
tactic.interactive.mono none interactive.mono_selection.both []
meta def mono_n (n : ℕ) (only_pers : parse (tk "!")?)
(dir : parse interactive.side) : temporal unit :=
do ex ← (if ¬ only_pers.is_some then do
asms ← get_assumptions,
list.band <$> asms.mmap is_henceforth
else tt <$ interactive.persistent []),
if ex
then persistently $ do
to_expr ``(ctx_impl _ _ _) >>= change,
tactic.iterate_exactly n (tactic.interactive.mono none dir [])
else do
to_expr ``(ctx_impl _ _ _) >>= change,
tactic.iterate_exactly n (tactic.interactive.mono none dir [])
meta def mk_assert : pexpr ⊕ pexpr → tactic expr
| (sum.inl h) := to_expr h
| (sum.inr p) := to_expr p >>= mk_meta_var
meta def mono
(only_pers : parse (tk "!")?)
(many : parse (tk "*")?)
(dir : parse interactive.side)
(e : parse assert_or_rule?) : temporal unit :=
do ex ← (if ¬ only_pers.is_some then do
asms ← get_assumptions,
list.band <$> asms.mmap is_henceforth
else tt <$ interactive.persistent []),
-- trace ex,
if ex
then persistently $ do
-- trace "foo",
to_expr ``(ctx_impl _ _ _) >>= change,
-- trace "bar",
-- h ← mk_assert e,
tactic.interactive.mono many dir []
else do
to_expr ``(ctx_impl _ _ _) >>= change,
tactic.interactive.mono many dir []
meta def interactive.apply_mono (f e : parse ident) : temporal unit :=
do get_local e >>= temporal.revert,
f ← get_local f,
b ← is_henceforth f,
if b then do
interactive.persistent [],
persistently $ do
to_expr ``(ctx_impl _ _ _) >>= change,
tactic.interactive.ac_mono interactive.rep_arity.many (some $ sum.inl ``(%%f))
else tactic.interactive.ac_mono interactive.rep_arity.many (some $ sum.inl ``(%%f))
private meta def goal_flag := optional $ tk "⊢" <|> tk "|-"
meta def interactive.guard_target
(e : parse texpr) : temporal unit :=
do `(_ ⊢ %%t) ← target,
e ← to_expr e,
guard (t =ₐ e)
meta def interactive.iterate
(n : parse small_nat)
(tac : temporal.interactive.itactic) : temporal unit :=
do iterate_exactly n tac
meta def interactive.eventually (h : parse ident) (goal : parse goal_flag) : temporal unit :=
do `(%%Γ ⊢ %%p) ← target,
h' ← get_local h,
`(%%Γ' ⊢ ◇%%q) ← infer_type h' | fail format!"{h} should be a temporal formula of the form ◇_",
is_def_eq Γ Γ',
revert h',
if goal.is_some then do
`(◇ %%p) ← pure p | fail format!"expecting a goal of the form `◇ _`",
mono1 (some ())
else
interactive.persistent [] >>
persistently (do `(%%Γ ⊢ ◇%%q ⟶ %%p) ← target, refine ``(p_imp_postpone %%Γ %%q %%p _)),
() <$ intro1 (some h)
meta def timeless (h : expr) : temporal (option name) :=
do try $ interactive.henceforth none (loc.ns [some h.local_pp_name]),
h ← get_local h.local_pp_name,
`(%%Γ' ⊢ %%p) ← infer_type h | return none,
`(@coe Prop cpred _ %%p) ← return p | none <$ clear h,
some h.local_pp_name <$ temporal.revert h
meta def interactive.note
(h : parse ident?)
(q₁ : parse (tk ":" *> texpr))
(_ : parse $ tk ",")
(tac : tactic.interactive.itactic)
: tactic expr :=
do `(%%Γ ⊢ _) ← target,
h' ← temporal.interactive.«have» h q₁ none,
solve1 (do
xs ← local_context >>= mmap timeless,
let n := xs.filter_map id,
tactic.revert Γ,
refine ``(ew_wk _),
τ ← tactic.intro1,
try $ temporal.interactive.simp none tt [] [`predicate] (loc.ns [none]) ,
try $ tactic.interactive.TL_unfold [`init] (loc.ns [none]),
try $ tactic.interactive.generalize none () (``(%%τ 0),`σ),
target >>= (λ e, beta_reduction e tt) >>= change,
intro_lst n,
tac),
tactic.revert h',
refine ``(lifting_prop_asm %%Γ _),
tactic.intro h'.local_pp_name
open tactic.interactive (rw_rules rw_rules_t rw_rule get_rule_eqn_lemmas to_expr')
open temporal.interactive (rw)
meta def interactive.rw_using
(p : parse cur_pos)
(q₁ : parse (tk ":" *> texpr))
(l : parse location)
(_ : parse $ tk ",")
(tac : tactic.interactive.itactic)
: tactic unit :=
do h ← mk_fresh_name,
h ← temporal.interactive.note h q₁ () tac,
let rs : rw_rules_t := ⟨[{ rw_rule
. pos := p
, symm := ff
, rule := to_pexpr h }],none⟩,
rw rs l,
try (tactic.clear h)
meta def interactive.«suffices» (h : parse ident?) (t : parse (tk ":" *> texpr)?) : tactic unit :=
interactive.«have» h t none >> tactic.swap
meta def interactive.congr := tactic.interactive.congr
meta def interactive.ext := tactic.interactive.ext
run_cmd do
let ls := [``mono,``mono1,``persistently],
ls.for_each $ λ l, do
env ← get_env,
d_name ← resolve_constant l,
(declaration.defn _ ls ty val hints trusted) ← env.get d_name,
(name.mk_string h _) ← return d_name,
let new_name := `temporal.interactive <.> h,
add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted)
end
end temporal
|
State Before: α : Type u_1
β : Type ?u.82701
γ : Type ?u.82704
ι : Sort ?u.82707
π : α → Type ?u.82712
δ : α → Sort u_2
s : Set α
f g : (i : α) → δ i
inst✝¹ : (j : α) → Decidable (j ∈ s)
i j : α
h : i ≠ j
inst✝ : (i : α) → Decidable (i ∈ insert j s)
⊢ piecewise (insert j s) f g i = piecewise s f g i State After: no goals Tactic: simp [piecewise, h]
|
// Base Class for all image decoder classes
#ifndef GTL_IMAGEDECODERBASE_HPP
#define GTL_IMAGEDECODERBASE_HPP
#include <boost/shared_ptr.hpp>
#include "GameTextureLoader.hpp"
//#include "GTLUserDecoder.hpp"
namespace Decoders
{
class IDecoderBase
{
public:
IDecoderBase(GameTextureLoader3::loaderData data, GameTextureLoader3::ImgOrigin origin, GameTextureLoader3::ImagePtr image)
: data(data.data), datasize(data.size), origin(origin), image(image)
{};
void Decode() {DecodeImpl();};
private:
virtual void DecodeImpl() = 0;
protected:
GameTextureLoader3::DecoderImageData data;
int datasize;
GameTextureLoader3::ImgOrigin origin;
GameTextureLoader3::ImagePtr image;
};
typedef boost::shared_ptr<IDecoderBase> IDecoderBasePtr;
}
#endif
|
import data.real.irrational
import topology.basic
import algebra.order.floor
--OUTPUT 1
theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=
begin
-- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$.
have h1 : ∀ (i j : ℤ), (i ≠ j) → (int.fract (α * ↑i)) ≠ (int.fract (α * ↑j)), from by auto [int.fract_eq_iff, hα_irrat],
-- If this were not true, then
-- $$
-- i \alpha-\lfloor i \alpha\rfloor=\{i \alpha\}=\{j \alpha\}=j \alpha-\lfloor j \alpha\rfloor,
-- $$
-- which yields the false statement $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$.
have h2 : ∀ (i j : ℤ), (i ≠ j) → (int.fract (α * ↑i)) = (int.fract (α * ↑j)) → α ∈ ℚ, from by auto [int.fract_eq_iff, hα_irrat, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int.coe_nat_le_coe_nat_iff, int.coe_nat_lt_coe_nat_iff, int
end --Needs more than 2000 tokens!
--OUTPUT 2
theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=
begin
-- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$.
-- If this were not true, then
-- $$
-- i \alpha-\lfloor i \alpha\rfloor=\{i \alpha\}=\{j \alpha\}=j \alpha-\lfloor j \alpha\rfloor,
-- $$
-- which yields the false statement $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$.
-- Hence,
-- $$
-- S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}
-- $$
-- is an infinite subset of $\left[0,1\right]$.
have h1 : ∀ i j : ℤ, (int.fract (α * ↑i)) ≠ (int.fract (α * ↑j)) → i ≠ j, from
begin
assume (i j : ℤ) (h2 : int.fract (α * ↑i) ≠ int.fract (α * ↑j)),
assume h3 : i = j,
have h4 : (α * ↑i) - (int.floor (α * ↑i)) = int.fract (α * ↑i), from by auto [int.fract_eq_of_nonneg, int.fract_nonneg],
have h5 : (α * ↑j) - (int.floor (α * ↑j)) = int.fract (α * ↑j), from by auto [int.fract_eq_of_nonneg, int.fract_nonneg],
have h6 : (α * ↑i) - (int.floor (α * ↑i)) = (α * ↑j) - (int.floor (α * ↑j)), from by auto [h3, h4, h5],
have h7 : α = (int.floor (α * ↑i) - int.floor (α * ↑j)) / (i - j), from by auto [mul_sub, sub_eq_iff_eq_add, add_sub_cancel, sub_sub, mul_sub_left_distrib, mul_sub_right_distrib, mul_assoc, mul_comm, sub_mul, sub_sub, sub_eq_add_neg, neg_sub, sub_self, add_zero, mul_zero, div_eq_iff_mul_eq, mul_comm, mul_eq_zero, eq_comm, h6, h2, h3],
have h8 : (int.floor (α * ↑i) - int.floor (α * ↑j)) / (i - j) ∈ ℚ, from by auto [rat.mk_eq_div, int.cast_coe_nat, int.cast_coe_int, int.cast_coe_nat, int.cast_coe_int, int.cast_coe_nat, int.cast_coe_int],
have h9 : α ∈ ℚ, from by auto [h7, h8],
have h10 : irrational α, from hα_irrat,
show false, from by auto [h10, h9],
end,
have h2 : ∀ i j : ℤ, (int.fract (α * ↑i)) ≠ (int.fract (α * ↑j)) ↔ i ≠ j, from by auto [h1],
have h3 : ∀ i j : ℤ, i ≠ j → (int.fract (α * ↑i)) ≠ (int.fract (α * ↑j)), from by auto [h2],
have h4 : ∀ i : ℤ, (int.fract (α * ↑i)) ∈ set.Icc 0 1, from by auto [int.fract_nonneg, int.fract_lt_one],
have h5 : ∀ i : ℤ, (int.fract (α * ↑i)) ∈ (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ), from by auto [h4],
have h6 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h7 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h8 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h9 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h10 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h11 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h12 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h13 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h14 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h15 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h16 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h17 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h18 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h19 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h20 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h21 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h22 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h23 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have h24 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h4],
have
end --Needs more than 2000 tokens!
--OUTPUT 3
theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=
begin
-- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then
have h1 : ∀ i j : ℤ, i ≠ j → int.fract (α * ↑i) ≠ int.fract (α * ↑j),
from by auto [int.fract_eq_iff_eq, hα_irrat, int.fract_mul],
-- Hence, $S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}$ is an infinite subset of $\left[0,1\right]$.
have h2 : ∀ i : ℤ, int.fract (α * ↑i) ∈ set.Icc 0 1, from by auto [int.fract_nonneg, int.fract_lt_one],
have h3 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h2],
have h4 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ≠ ∅, from by auto [set.univ_ne_empty],
have h5 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [h2],
have h6 : (λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ) ≠ ∅, from by auto [set.univ_ne_empty],
have h7 : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1, from by auto [closure_eq_of_is_closed, is_closed_Icc, h5, h6],
show closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1, from by auto [h7],
end
--OUTPUT 4
theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=
begin
-- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then
-- $i \alpha-\lfloor i \alpha\rfloor=\{i \alpha\}=\{j \alpha\}=j \alpha-\lfloor j \alpha\rfloor$,
-- which yields the false statement $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$.
have h1 : ∀ i j : ℤ, i ≠ j → int.fract (α * ↑i) ≠ int.fract (α * ↑j),
from by auto [int.fract_eq_iff_of_ne_zero, hα_irrat],
-- Hence,
-- $S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}$
-- is an infinite subset of $\left[0,1\right]$.
have h2 : (λ m : ℤ, int.fract (α * ↑m)) '' univ ⊆ set.Icc 0 1,
from by auto [int.fract_nonneg, int.fract_lt_one],
-- By the Bolzano-Weierstrass theorem, $S$ has a limit point in $[0, 1]$.
have h3 : ∃ x, x ∈ closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)),
from by auto [closure_eq_of_is_closed, is_closed_Icc],
-- One can thus find pairs of elements of $S$ that are arbitrarily close.
have h4 : ∀ ε > 0, ∃ x y, x ≠ y ∧ x ∈ (λ m : ℤ, int.fract (α * ↑m)) '' univ ∧ y ∈ (λ m : ℤ, int.fract (α * ↑m)) '' univ ∧ |x - y| < ε,
from by auto [h3, closure_eq_of_is_closed, is_closed_Icc],
-- Since (the absolute value of) the difference of any two elements of $S$ is also an element of $S$, it follows that $0$ is a limit point of $S$.
have h5 : ∀ ε > 0, ∃ x, x ∈ (λ m : ℤ, int.fract (α * ↑m)) '' univ ∧ |0 - x| < ε,
from by auto [h4, abs_of_nonneg, int.fract_nonneg],
-- To show that $S$ is dense in $[0, 1]$, consider $y \in[0,1]$, and $\epsilon>0$. Then by selecting $x \in S$ such that $\{x\}<\epsilon$ (which exists as $0$ is a limit point), and $N$ such that $N \cdot\{x\} \leq y<(N+1) \cdot\{x\}$, we get: $|y-\{N x\}|<\epsilon$.
have h6 : ∀ y ∈ set.Icc 0 1, ∀ ε > 0, ∃ x, x ∈ (λ m : ℤ, int.fract (α * ↑m)) '' univ ∧ |y - x| < ε,
from by auto [h5, int.fract_nonneg, int.fract_lt_one, int.fract_add, int.fract_mul],
show closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1,
from by auto [closure_eq_of_is_closed, is_closed_Icc, h6],
end
--OUTPUT 5
theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=
begin
-- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$.
have h1 : ∀ (i j : ℤ), (i ≠ j) → (int.fract (α * ↑i) ≠ int.fract (α * ↑j)),
from by auto [irrational.def, int.fract_eq_iff_of_int_mul_eq_int],
-- If this were not true, then
-- $$
-- i \alpha-\lfloor i \alpha\rfloor=\{i \alpha\}=\{j \alpha\}=j \alpha-\lfloor j \alpha\rfloor,
-- $$
-- which yields the false statement $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$.
have h2 : ∀ (i j : ℤ), (i ≠ j) → (∀ (x : ℤ), (int.fract (α * ↑i) = int.fract (α * ↑j)) → (α = (int.fract (α * ↑i) + ↑x) / ↑(i - j) → irrational α)),
from by auto [irrational.def, int.fract_eq_iff_of_int_mul_eq_int, int.fract_add_int_div],
-- Hence,
-- $$
-- S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}
-- $$
-- is an infinite subset of $\left[0,1\right]$.
have h3 : ∃ (x : ℤ), (int.fract (α * ↑x) ∈ ((λ (m : ℤ), int.fract (α * ↑m)) '' (@set.univ ℤ))),
from by auto [int.fract_eq_iff_of_int_mul_eq_int],
-- By the Bolzano-Weierstrass theorem, $S$ has a limit point in $[0, 1]$.
have h4 : ∃ (x : ℤ), (int.fract (α * ↑x) ∈ closure ((λ (m : ℤ), int.fract (α * ↑m)) '' (@set.univ ℤ))),
from by auto [int.fract_eq_iff_of_int_mul_eq_int, closure_eq_nhds_of_is_closed, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_open_Iic, is_closed_Iio, is_open_Iio, is_closed_Iic, is_
end --Needs more than 2000 tokens!
--OUTPUT 6
theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=
begin
-- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then
-- $i \alpha-\lfloor i \alpha\rfloor=\{i \alpha\}=\{j \alpha\}=j \alpha-\lfloor j \alpha\rfloor$,
-- which yields the false statement $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$. Hence,
-- $S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}$
-- is an infinite subset of $\left[0,1\right]$.
have h1 : ∀ i j : ℤ, i ≠ j → (int.fract (α * ↑i)) ≠ (int.fract (α * ↑j)), from
begin
assume (i : ℤ) (j : ℤ) (hij : i ≠ j),
assume h2 : int.fract (α * ↑i) = int.fract (α * ↑j),
have h3 : α = (((int.fract (α * ↑i)) + (int.floor (α * ↑i))) - ((int.fract (α * ↑j)) + (int.floor (α * ↑j)))) / (i - j),
from by auto [h2, int.fract_add],
have h4 : (i - j) ≠ 0, from by auto [hij],
have h5 : (α * ↑i) - (int.floor (α * ↑i)) = (α * ↑j) - (int.floor (α * ↑j)), from by auto [h3, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub, mul_sub
end --Needs more than 2000 tokens!
/- FEW SHOT PROMPTS TO CODEX(START)
/--`theorem`
Power Set is Closed under Intersection
Let $S$ be a set.
Let $\powerset S$ be the power set of $S$.
Then:
:$\forall A, B \in \powerset S: A \cap B \in \powerset S$
`proof`
Let $A, B \in \powerset S$.
Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$.
From Intersection is Subset we have that $A \cap B \subseteq A$.
It follows from Subset Relation is Transitive that $A \cap B \subseteq S$.
Thus $A \cap B \in \powerset S$ and closure is proved.
{{qed}}
-/
theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S :=
begin
-- $A$ and $B$ are sets. $A$ and $B$ belong to power set of $S$
assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S),
-- Then $A ⊆ S$ and $B ⊆ S$, by power set definition
have h1 : (A ⊆ S) ∧ (B ⊆ S), from by auto [set.subset_of_mem_powerset, set.subset_of_mem_powerset],
-- Then $(A ∩ B) ⊆ A$, by intersection of set is a subset
have h2 : (A ∩ B) ⊆ A, from by auto [set.inter_subset_left],
-- Then $(A ∩ B) ⊆ S$, by subset relation is transitive
have h3 : (A ∩ B) ⊆ S, from by auto [set.subset.trans],
-- Hence $(A ∩ B) ∈ 𝒫 S$, by power set definition
show (A ∩ B) ∈ 𝒫 S, from by auto [set.mem_powerset],
end
/--`theorem`
Square of Sum
:$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$
`proof`
Follows from the distribution of multiplication over addition:
{{begin-eqn}}
{{eqn | l = \left({x + y}\right)^2
| r = \left({x + y}\right) \cdot \left({x + y}\right)
}}
{{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right)
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x^2 + 2xy + y^2
| c =
}}
{{end-eqn}}
{{qed}}
-/
theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) :=
begin
-- expand the power
calc (x + y)^2 = (x+y)*(x+y) : by auto [sq]
-- distributive property of multiplication over addition gives:
... = x*(x+y) + y*(x+y) : by auto [add_mul]
-- applying the above property further gives:
... = x*x + x*y + y*x + y*y : by auto [mul_comm, add_mul] using [ring]
-- rearranging the terms using commutativity and adding gives:
... = x^2 + 2*x*y + y^2 : by auto [sq, mul_comm] using [ring]
end
/--`theorem`
Identity of Group is Unique
Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$.
`proof`
From Group has Latin Square Property, there exists a unique $x \in G$ such that:
:$a x = b$
and there exists a unique $y \in G$ such that:
:$y a = b$
Setting $b = a$, this becomes:
There exists a unique $x \in G$ such that:
:$a x = a$
and there exists a unique $y \in G$ such that:
:$y a = a$
These $x$ and $y$ are both $e$, by definition of identity element.
{{qed}}
-/
theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a :=
begin
-- Group has Latin Square Property
have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by auto using [use (a⁻¹ * b)],
have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by auto using [use b * a⁻¹],
-- Setting $b = a$, this becomes:
have h3 : ∀ a : G, ∃! x : G, a * x = a, from by auto [h1],
have h4 : ∀ a : G, ∃! y : G, y * a = a, from by auto [h2],
-- These $x$ and $y$ are both $(1 : G)$, by definition of identity element
have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from by auto [exists_unique.unique, h3, classical.some_spec, exists_unique.exists, mul_one],
have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from by auto [exists_unique.unique, h4, classical.some_spec, exists_unique.exists, one_mul],
show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by auto [h3, h4, exists_unique.unique, classical.some_spec, exists_unique.exists] using [use (1 : G)],
end
/--`theorem`
Squeeze Theorem for Real Numbers
Let $\sequence {x_n}$, $\sequence {y_n}$ and $\sequence {z_n}$ be sequences in $\R$.
Let $\sequence {y_n}$ and $\sequence {z_n}$ both be convergent to the following limit:
:$\ds \lim_{n \mathop \to \infty} y_n = l, \lim_{n \mathop \to \infty} z_n = l$
Suppose that:
:$\forall n \in \N: y_n \le x_n \le z_n$
Then:
:$x_n \to l$ as $n \to \infty$
that is:
:$\ds \lim_{n \mathop \to \infty} x_n = l$
`proof`
From Negative of Absolute Value:
:$\size {x - l} < \epsilon \iff l - \epsilon < x < l + \epsilon$
Let $\epsilon > 0$.
We need to prove that:
:$\exists N: \forall n > N: \size {x_n - l} < \epsilon$
As $\ds \lim_{n \mathop \to \infty} y_n = l$ we know that:
:$\exists N_1: \forall n > N_1: \size {y_n - l} < \epsilon$
As $\ds \lim_{n \mathop \to \infty} z_n = l$ we know that:
:$\exists N_2: \forall n > N_2: \size {z_n - l} < \epsilon$
Let $N = \max \set {N_1, N_2}$.
Then if $n > N$, it follows that $n > N_1$ and $n > N_2$.
So:
:$\forall n > N: l - \epsilon < y_n < l + \epsilon$
:$\forall n > N: l - \epsilon < z_n < l + \epsilon$
But:
:$\forall n \in \N: y_n \le x_n \le z_n$
So:
:$\forall n > N: l - \epsilon < y_n \le x_n \le z_n < l + \epsilon$
and so:
:$\forall n > N: l - \epsilon < x_n < l + \epsilon$
So:
:$\forall n > N: \size {x_n - l} < \epsilon$
Hence the result.
{{qed}}
-/
theorem squeeze_theorem_real_numbers (x y z : ℕ → ℝ) (l : ℝ) :
let seq_limit : (ℕ → ℝ) → ℝ → Prop := λ (u : ℕ → ℝ) (l : ℝ), ∀ ε > 0, ∃ N, ∀ n > N, |u n - l| < ε in
seq_limit y l → seq_limit z l → (∀ n : ℕ, (y n) ≤ (x n) ∧ (x n) ≤ (z n)) → seq_limit x l :=
begin
assume seq_limit (h2 : seq_limit y l) (h3 : seq_limit z l) (h4 : ∀ (n : ℕ), y n ≤ x n ∧ x n ≤ z n) (ε),
--From Negative of Absolute Value: $\size {x - l} < \epsilon \iff l - \epsilon < x < l + \epsilon$
have h5 : ∀ x, |x - l| < ε ↔ (((l - ε) < x) ∧ (x < (l + ε))),
from by auto [abs_sub_lt_iff] using [linarith],
--Let $\epsilon > 0$.
assume (h7 : ε > 0),
--As $\ds \lim_{n \mathop \to \infty} y_n = l$ we know that $\exists N_1: \forall n > N_1: \size {y_n - l} < \epsilon$
cases h2 ε h7 with N1 h8,
--As $\ds \lim_{n \mathop \to \infty} z_n = l$ we know that $\exists N_2: \forall n > N_2: \size {z_n - l} < \epsilon$
cases h3 ε h7 with N2 h9,
--Let $N = \max \set {N_1, N_2}$.
let N := max N1 N2,
use N,
--Then if $n > N$, it follows that $n > N_1$ and $n > N_2$.
have h10 : ∀ n > N, n > N1 ∧ n > N2 := by auto [lt_of_le_of_lt, le_max_left, le_max_right],
--$\forall n > N: l - \epsilon < y_n < l + \epsilon$
--$\forall n > N: l - \epsilon < z_n < l + \epsilon$
--$\forall n \in \N: y_n \le x_n \le z_n$
--So $\forall n > N: l - \epsilon < y_n \le x_n \le z_n < l + \epsilon$
have h11 : ∀ n > N, (((l - ε) < (y n)) ∧ ((y n) ≤ (x n))) ∧ (((x n) ≤ (z n)) ∧ ((z n) < l+ε)),
from by auto [h8, h10, h5, h9],
--$\forall n > N: l - \epsilon < x_n < l + \epsilon$
have h15 : ∀ n > N, ((l - ε) < (x n)) ∧ ((x n) < (l+ε)),
from by auto [h11] using [linarith],
--So $\forall n > N: \size {x_n - l} < \epsilon$
--Hence the result
show ∀ (n : ℕ), n > N → |x n - l| < ε,
from by auto [h5, h15],
end
/--`theorem`
Density of irrational orbit
The fractional parts of the integer multiples of an irrational number form a dense subset of the unit interval
`proof`
Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then
$$
i \alpha-\lfloor i \alpha\rfloor=\{i \alpha\}=\{j \alpha\}=j \alpha-\lfloor j \alpha\rfloor,
$$
which yields the false statement $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$. Hence,
$$
S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}
$$
is an infinite subset of $\left[0,1\right]$.
By the Bolzano-Weierstrass theorem, $S$ has a limit point in $[0, 1]$. One can thus find pairs of elements of $S$ that are arbitrarily close. Since (the absolute value of) the difference of any two elements of $S$ is also an element of $S$, it follows that $0$ is a limit point of $S$.
To show that $S$ is dense in $[0, 1]$, consider $y \in[0,1]$, and $\epsilon>0$. Then by selecting $x \in S$ such that $\{x\}<\epsilon$ (which exists as $0$ is a limit point), and $N$ such that $N \cdot\{x\} \leq y<(N+1) \cdot\{x\}$, we get: $|y-\{N x\}|<\epsilon$.
QED
-/
theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=
FEW SHOT PROMPTS TO CODEX(END)-/
|
Comfortable, solid-coloured jogging trousers made from a high quality cotton and lycra mix.
Care instructions: Machine wash at 30°. Wash separately inside out.
|
(**
論理としてのProlog
========================
@suharahiromichi
2022/12/18
2022/12/19 ``ex_intro _`` を使うように修正した。
2023/1/21 変数名を1文字にした。
*)
(**
# はじめに
Prologは、第1階述語論理の構文的なサブセットである「ホーン節」Horn Clauseの自動証明を
動作原理とするプログラミング言語です。
ここで使われる自動証明のことを「導出原理」Resolution Principleと呼びます。
ここでは、Prologのプログラムを論理式として証明してみましょう。
手で証明するのも大変なので、定理証明系(Coq/MathComp)を使ってみます。
すると、Prologと論理学や、Coqとの関係が見えてくるとおもいます。
この記事のソースコードは以下にありますが、実行にはCoq/MathCompは必要です。
https://github.com/suharahiromichi/coq/blob/master/ssr/ssr_prolog_in_logic.v
まず、対象とする論理式を明確にしてみます。
*)
(**
# Prologのプログラムとしての論理式
ホーン節ということで間違いないのですが、後述する理由で、
「ホーン節」と「ゴール節」のふたつに分けて説明します。
いずれも定義は見たままのものなので、説明は省略します。
ここで、$ k,l,m,n \ge 0 $ とします。
- ホーン節
P、Qは原始論理式(∧、∨、〜、∀、∃などの論理記号を含まない論理式)
で、False(⊥)でないものとします。
論理記号の使い方の次のような文法的な制限を加えた論理式をホーン節といいます。
```math
\forall x_{1}~\forall x_{2}~ …\forall x_{n}~[(P_{1}~\land~P_{2}~\land~…~\land~P_{m})~\to~Q]
```
```coq
forall x1 x2 ... xn, P1 P2 ... Pm -> Q.
```
Prologのプログラムでは、次のように表します。
```Prolog
Q :- P1, P2, ... Pm.
```
量化子の変数は大文字で書き、``∀x``は書きません。
また、``:- true.``は省略します。
- ゴール節
Rは原始論理式で、False(⊥)でないものとします。
次の文法的な制限を加えた論理式をゴール節といいます。
```math
\exists x_{1}~\exists x_{2}~ …\exists x_{l}~[R]
```
```coq
exists x1 x2 ... xl, R.
```
Prologのプログラムでは、次のように表します。
```Prolog
?-R.
```
量化子の変数は大文字で書き、``∃x``は書きません。
- Prologのプログラムの論理式
複数のホーン節 $ H_{i} $ とひとつのゴール節 $ G $ からなります。
```math
(H_{1}~\land~H_{2}~\land~…\land~H_{k})~\to~G
```
Prologのプログラムは、ホーン節を並べたものです。
並べ方の順番は自動証明(導出原理)における選択の順番に反映されます。
ゴール節は対話形式で入力したり
コマンドラインの引数で与える場合が多いので``?-``はあまり使わないかもしれません。
この後、Prologで定数やデータ構造扱うためには、スコーレム関数(Skolem function)の説明が
必要ですが、多少本題からずれるので、省略させてください。
ここでは、PrologもCoqも同様の定数や、リストのデータ構造が使えることを前提とします。
*)
(**
# Prologのプログラムの例
例によって、リストの反転を考えてみます。
```
rev(L, R) :-
rev3(L, [], R).
rev3([X|L], A, R) :-
rev3(L, [X|A], R).
rev3([], R, R).
```
これに対して、ふたつのゴール、ゴール1
```
?- rev([1, 2, 3], R).
```
と、ゴール2について
```
?- rev(L, [9, 8, 7]).
```
実行してみます。
なお、λPrologの文法だと次のようになります。
この場合は、述語の引数の指定の方法が違うだけですね。
```
pred rev i:list A, o:list A.
rev L R :-
rev3 L [] R.
rev3 [X|L] A R :-
rev3 L [X|A] R.
rev3 [] R R.
```
ホーン節の部分を論理式で表すと
```math
\forall L~\forall R~[rev3(L, [], R)~\to~rev(L, R)]
\\\land\\
\forall X~\forall L~\forall A~\forall R~[rev3(L, [X|A], R~\to~rev3([X|L],A,R)]
\\\land\\
\forall R~[true~\to~rev3([], R, R)]
```
ゴール1は
```math
\exists R~[rev([1, 2, 3], R)]
```
ゴール2は
```math
\exists L~[rev(L, [9, 8, 7])]
```
*)
From mathcomp Require Import all_ssreflect.
Variable rev : list nat -> list nat -> Prop.
Variable rev3 : list nat -> list nat -> list nat -> Prop.
(**
ホーン節の部分は以下のようになります。
ここでは便宜的にDefinitionでまとめていますが、論理式としての意味は変わりません。
*)
Definition prog0 :=
(forall L R, rev3 L [::] R -> rev L R)
/\
(forall X L A R, rev3 L (X :: A) R -> rev3 (X :: L) A R)
/\
(forall R, rev3 [::] R R).
(**
ゴールの部分は
*)
Definition goal1 := exists R, rev [:: 1; 2; 3] R.
Definition goal2 := exists L, rev L [:: 9; 8; 7].
(**
Coqで証明してみます。
Coqにも導出原理に基づく自動証明のタクティク``auto``があるのでそれを使ってみます。
``apply: (ex_intro _)`` で、``∃ R``の``R``を Coq のメタ変数(``_``、
表示上は``?Goal``になる)に割り当てています。
*)
Goal prog0 -> goal1.
Proof.
rewrite /prog0 /goal1.
case=> [H [Hcons Hnil]].
apply: (ex_intro _).
apply: (H).
apply: (Hcons).
apply: (Hcons).
apply: (Hcons).
apply: (Hnil).
Restart.
rewrite /prog0 /goal1.
case=> [H [Hcons Hnil]].
apply: (ex_intro _).
debug auto.
Qed.
Goal prog0 -> goal2.
Proof.
rewrite /prog0 /goal2.
case=> [H [Hcons Hnil]].
apply: (ex_intro _).
debug auto.
Qed.
(**
以上から、Prologのプログラムは、Coqの``auto``タクティクで証明できる(場合もある)ことが
わかりました。
*)
(**
# 補足説明
## Prologは古典論理か?
まず、ゴール節の否定を考えます。$ (\lnot~R) \Leftrightarrow (R~\to~False) $
なので、ホーン節の``→``の右をFalseにしたものになります。
```math
\lnot(\exists x_{1}~\exists x_{2}~ …\exists x_{l}~[R])
\\
\forall x_{1}~\forall x_{2}~ …\forall x_{l}~[\lnot~R]
\\
\forall x_{1}~\forall x_{2}~ …\forall x_{l}~[R~\to~False]
```
Prologのプログラムの論理式を否定します。さらに、含意を論理和と否定のかたち
$ (H~\to~G) \Leftrightarrow (\lnot~H~\lor~G) $ にします。
すると、ホーン節とゴール節の否定を連言になります。
上でみたように、ゴール節の否定は(特別な)ホーン節ですから、
Prologのプログラムは、ホーン節の連言ということができます。
```math
\lnot~(H_{1}~\land~H_{2}~\land~…\land~H_{k}~\to~G)
\\
\lnot~(\lnot~(H_{1}~\land~H_{2}~\land~…\land~H_{k})~\lor~G)
\\
\lnot(\lnot H_{1}~\lor~\lnot H_{2}~\lor~…\lor~\lnot H_{k}~\lor~G)
\\
H_{1}~\land~H_{2}~\land~…\land~H_{k}~\land~\lnot~G
```
最初にPrologのプログラムの論理式を否定を考えたのは、
導出原理は、論理式の反駁(はんばく)を導くことだからです。
教科書ではこのように説明されるのが通常ですが、
お気づきのとおり、上記の論理式を導くには
古典論理が必要になります。
これに対して、ホーン節とゴール節を別々に定義すれば、Prologの
論理式の意味を直観主義論理の範囲で示すことができ、
同じく、直観主義論理を使用するCoqの上で証明することができるわけです。
そして、おそらく大多数のPrologプログラマにとっては、
Prologプログラムの動作の理解は「直観的」なのではないかと思います。
ここで「Coqと同様に」と書きたいところなのですが…
## Prologの不完全性
実は、Prologでgoal2に対して実行すると無限ループになります。
なぜなら、最初のrev3の実行``rev3 L [] [9,8,7]``に対して、*節をならべた順番に従って*
``rev3 [X|L] A R :- rev3 L [X|A] R.``が選ばれます。
これは、第3引数は再帰呼び出しに対して、リストの分解が行われないため、
(コンストラクタが構造的に減っていかないため)再帰呼び出しの終了判定ができず、
無限ループになってしまうわけです。
これは、証明できるべき命題が証明できないという意味で、定理証明系としての
Prologの「不完全性」の一例になっています。
これに対して、Coqの完全性はタクティク(証明戦略)の停止性とは無関係です。
(この項は、あとで追記するかもしれません。)
## cut述語について
Prologにはcut述語、別名、カットオペレータ(``!``)があります。
これは、Prologの自動証明において、
ホーン節のしらみつぶしの選択を木構造の検索と見立てた場合、
バックトラックが生じた際に、ツリーの検索の一部をカット(枝を刈る)して、
検索せずにただちに失敗(fail)とする、ということからこの名前があります。
cut述語は、論理式としてもProlog言語ではなく、手続言語の側面を実現するものなので、
本資料では触れませんでした。
Coqにもcutタクティクがありますが、証明論におけるカット除去定理
(``A -> C`` かつ ``C -> B``なら``C``を除去して``A -> B``を導ける)
の逆のことを行うもので、Coqのゴール``A -> B`` を ``C -> B`` に置き換えることをします。
もちろん、そのあとに、``A -> C``を証明させられることになります。
このふたつは全く別の概念なので、注意してください。
*)
(* END *)
|
from typing import Optional
import allel
import dask.array as da
import numpy as np
import numpy.testing as npt
import pytest
from dask.dataframe import DataFrame
from hypothesis import Phase, example, given, settings
from hypothesis import strategies as st
from hypothesis.extra.numpy import arrays
from sgkit import variables, window
from sgkit.stats.ld import (
ld_matrix,
ld_prune,
maximal_independent_set,
rogers_huff_r2_between,
rogers_huff_r_between,
)
from sgkit.testing import simulate_genotype_call_dataset
from sgkit.typing import ArrayLike
def test_rogers_huff_r_between():
gna = np.array([[0, 1, 2]])
gnb = np.array([[0, 1, 2]])
npt.assert_allclose(rogers_huff_r_between(gna[0], gnb[0]), 1.0, rtol=1e-06)
npt.assert_allclose(rogers_huff_r2_between(gna[0], gnb[0]), 1.0, rtol=1e-06)
npt.assert_allclose(
allel.rogers_huff_r_between(gna, gnb),
rogers_huff_r_between(gna[0], gnb[0]),
rtol=1e-06,
)
gna = np.array([[0, 1, 2]])
gnb = np.array([[2, 1, 0]])
npt.assert_allclose(rogers_huff_r_between(gna[0], gnb[0]), -1.0, rtol=1e-06)
npt.assert_allclose(rogers_huff_r2_between(gna[0], gnb[0]), 1.0, rtol=1e-06)
npt.assert_allclose(
allel.rogers_huff_r_between(gna, gnb),
rogers_huff_r_between(gna[0], gnb[0]),
rtol=1e-06,
)
gna = np.array([[0, 0, 0]])
gnb = np.array([[1, 1, 1]])
assert np.isnan(rogers_huff_r_between(gna[0], gnb[0]))
assert np.isnan(rogers_huff_r2_between(gna[0], gnb[0]))
assert np.isnan(allel.rogers_huff_r_between(gna, gnb))
# a case where scikit-allel is different due to its use of float32
gna = np.full((1, 49), 2)
gnb = np.full((1, 49), 2)
npt.assert_allclose(rogers_huff_r_between(gna[0], gnb[0]), 1.0, rtol=1e-06)
npt.assert_allclose(rogers_huff_r2_between(gna[0], gnb[0]), 1.0, rtol=1e-06)
assert np.isnan(allel.rogers_huff_r_between(gna, gnb))
def ldm_df(
x: ArrayLike,
size: int,
step: Optional[int] = None,
threshold: Optional[float] = None,
diag: bool = False,
) -> DataFrame:
ds = simulate_genotype_call_dataset(n_variant=x.shape[0], n_sample=x.shape[1])
ds["dosage"] = (["variants", "samples"], x)
ds = window(ds, size=size, step=step)
df = ld_matrix(ds, threshold=threshold).compute()
if not diag:
df = df.pipe(lambda df: df[df["i"] != df["j"]])
df = df[~df["value"].isnull()]
return df
@pytest.mark.parametrize("n", [2, 10, 16, 22])
def test_window(n):
# Create zero row vectors except for 1st and 11th
# (make them have non-zero variance)
x = np.zeros((n, 10), dtype="uint8")
x[0, :-1] = 1
x[n // 2, :-1] = 1
# All non-self comparisons are nan except for the above two
df = ldm_df(x, size=n, step=n)
assert len(df) == 1
assert df.iloc[0].tolist() == [0, n // 2, 1.0]
def test_threshold():
# Create zero row vectors except for 1st and 11th
# (make them have non-zero variance)
x = np.zeros((10, 10), dtype="uint8")
# Make 3rd and 4th perfectly correlated
x[2, :-1] = 1
x[3, :-1] = 1
# Make 8th and 9th partially correlated with 3/4
x[7, :-5] = 1
x[8, :-5] = 1
df = ldm_df(x, size=10)
# Should be 6 comparisons (2->3,7,8 3->7,8 7->8)
assert len(df) == 6
# Only 2->3 and 7->8 are perfectly correlated
assert len(df[abs(df["value"] - 1.0) < 1e-06]) == 2
# Do the same with a threshold
df = ldm_df(x, size=10, threshold=0.5)
assert len(df) == 2
@pytest.mark.parametrize(
"dtype",
[dtype for k, v in np.sctypes.items() for dtype in v if k in ["int", "uint"]], # type: ignore
)
def test_dtypes(dtype):
# Input matrices should work regardless of integer type
x = np.zeros((5, 10), dtype=dtype)
df = ldm_df(x, size=5, diag=True)
assert len(df) == 5
def test_ld_matrix__raise_on_no_windows():
x = np.zeros((5, 10))
ds = simulate_genotype_call_dataset(n_variant=x.shape[0], n_sample=x.shape[1])
ds["dosage"] = (["variants", "samples"], x)
with pytest.raises(ValueError, match="Dataset must be windowed for ld_matrix"):
ld_matrix(ds)
@st.composite
def ld_prune_args(draw):
# Note that n_cols is kept relatively small, to avoid differences in precision
# with scikit-allel, which uses float32 for the Rogers Huff function.
# See case in test_rogers_huff_r_between test.
n_rows, n_cols = draw(st.integers(2, 100)), draw(st.integers(2, 40))
x = draw(arrays(np.uint8, shape=(n_rows, n_cols), elements=st.integers(0, 2)))
assert x.ndim == 2
window = draw(st.integers(1, x.shape[0]))
step = draw(st.integers(1, window))
threshold = draw(st.floats(0, 1))
chunks = draw(st.integers(10, window * 3)) if window > 10 else -1
return x, window, step, threshold, chunks
# Phases setting without shrinking for complex, conditional draws in
# which shrinking wastes time and adds little information
# (see https://hypothesis.readthedocs.io/en/latest/settings.html#hypothesis.settings.phases)
PHASES_NO_SHRINK = (Phase.explicit, Phase.reuse, Phase.generate, Phase.target)
@given(args=ld_prune_args()) # pylint: disable=no-value-for-parameter
@settings(max_examples=50, deadline=None, phases=PHASES_NO_SHRINK)
@example(args=(np.array([[1, 1], [1, 1]], dtype="uint8"), 1, 1, 0.0, -1))
def test_vs_skallel(args):
x, size, step, threshold, chunks = args
ds = simulate_genotype_call_dataset(n_variant=x.shape[0], n_sample=x.shape[1])
ds["dosage"] = (["variants", "samples"], da.asarray(x).rechunk({0: chunks}))
ds = window(ds, size, step)
ldm = ld_matrix(ds, threshold=threshold)
has_duplicates = ldm.compute().duplicated(subset=["i", "j"]).any()
assert not has_duplicates
idx_drop_ds = maximal_independent_set(ldm)
idx_drop = np.sort(idx_drop_ds.ld_prune_index_to_drop.data)
m = allel.locate_unlinked(x, size=size, step=step, threshold=threshold)
idx_drop_ska = np.sort(np.argwhere(~m).squeeze(axis=1))
npt.assert_equal(idx_drop_ska, idx_drop)
def test_scores():
# Create zero row vectors except for 1st and 11th
# (make them have non-zero variance)
x = np.zeros((10, 10), dtype="uint8")
# Make 3rd and 4th perfectly correlated
x[2, :-1] = 1
x[3, :-1] = 1
# Make 8th and 9th partially correlated with 3/4
x[7, :-5] = 1
x[8, :-5] = 1
ds = simulate_genotype_call_dataset(n_variant=x.shape[0], n_sample=x.shape[1])
ds["dosage"] = (["variants", "samples"], x)
ds = window(ds, size=10)
ldm = ld_matrix(ds, threshold=0.2)
idx_drop_ds = maximal_independent_set(ldm)
idx_drop = np.sort(idx_drop_ds.ld_prune_index_to_drop.data)
npt.assert_equal(idx_drop, [3, 8])
# check ld_prune removes correct variants
pruned_ds = ld_prune(ds, threshold=0.2)
npt.assert_equal(pruned_ds.variant_position.values, [0, 1, 2, 4, 5, 6, 7, 9])
# break tie between 3rd and 4th so 4th wins
scores = np.ones(10, dtype="float32")
scores[2] = 0
scores[3] = 2
ds[variables.variant_score] = (["variants"], scores)
ldm = ld_matrix(ds, threshold=0.2, variant_score=variables.variant_score)
idx_drop_ds = maximal_independent_set(ldm)
idx_drop = np.sort(idx_drop_ds.ld_prune_index_to_drop.data)
npt.assert_equal(idx_drop, [2, 8])
# check ld_prune removes correct variants
pruned_ds = ld_prune(ds, threshold=0.2, variant_score=variables.variant_score)
npt.assert_equal(pruned_ds.variant_position.values, [0, 1, 3, 4, 5, 6, 7, 9])
|
section \<open>Equality Test\<close>
theory Equality Test
imports Main
begin
lemma "
|
Formal statement is: lemma measurable_gfp: fixes F :: "('a \<Rightarrow> 'b) \<Rightarrow> ('a \<Rightarrow> 'b::{complete_lattice, countable})" assumes F: "inf_continuous F" assumes *: "\<And>A. A \<in> measurable M (count_space UNIV) \<Longrightarrow> F A \<in> measurable M (count_space UNIV)" shows "gfp F \<in> measurable M (count_space UNIV)" Informal statement is: If $F$ is an inf-continuous function from the set of measurable functions to itself, then the greatest fixed point of $F$ is measurable.
|
[STATEMENT]
lemma tt_gr:
assumes "\<And>u. u \<in> keys p \<Longrightarrow> v \<prec>\<^sub>t u" and "p \<noteq> 0"
shows "v \<prec>\<^sub>t tt p"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. v \<prec>\<^sub>t tt p
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. v \<prec>\<^sub>t tt p
[PROOF STEP]
from \<open>p \<noteq> 0\<close>
[PROOF STATE]
proof (chain)
picking this:
p \<noteq> 0
[PROOF STEP]
have "keys p \<noteq> {}"
[PROOF STATE]
proof (prove)
using this:
p \<noteq> 0
goal (1 subgoal):
1. keys p \<noteq> {}
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
keys p \<noteq> {}
goal (1 subgoal):
1. v \<prec>\<^sub>t tt p
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. v \<prec>\<^sub>t tt p
[PROOF STEP]
by (rule assms(1), rule tt_in_keys, fact \<open>p \<noteq> 0\<close>)
[PROOF STATE]
proof (state)
this:
v \<prec>\<^sub>t tt p
goal:
No subgoals!
[PROOF STEP]
qed
|
! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
! Copyright by The HDF Group. *
! Copyright by the Board of Trustees of the University of Illinois. *
! All rights reserved. *
! *
! This file is part of HDF5. The full HDF5 copyright notice, including *
! terms governing use, modification, and redistribution, is contained in *
! the COPYING file, which can be found at the root of the source code *
! distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
! If you do not have access to either file, you may request a copy from *
! [email protected]. *
! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
!
!
! This file contains FORTRAN interfaces for H5TB functions
!
!
! NOTES
!
! _____ __ __ _____ ____ _____ _______ _ _ _______
! |_ _| \/ | __ \ / __ \| __ \__ __|/\ | \ | |__ __|
! **** | | | \ / | |__) | | | | |__) | | | / \ | \| | | | ****
! **** | | | |\/| | ___/| | | | _ / | | / /\ \ | . ` | | | ****
! **** _| |_| | | | | | |__| | | \ \ | |/ ____ \| |\ | | | ****
! |_____|_| |_|_| \____/|_| \_\ |_/_/ \_\_| \_| |_|
!
! If you add a new function here then you MUST add the function name to the
! Windows dll file 'hdf5_hl_fortrandll.def.in' in the hl/fortran/src directory.
! This is needed for Windows based operating systems.
!
#include "H5config_f.inc"
MODULE h5tb_CONST
USE, INTRINSIC :: ISO_C_BINDING
USE h5fortran_types
USE hdf5
INTERFACE h5tbwrite_field_name_f
MODULE PROCEDURE h5tbwrite_field_name_f_int
MODULE PROCEDURE h5tbwrite_field_name_f_string
END INTERFACE
INTERFACE h5tbread_field_name_f
MODULE PROCEDURE h5tbread_field_name_f_int
MODULE PROCEDURE h5tbread_field_name_f_string
END INTERFACE
INTERFACE h5tbwrite_field_index_f
MODULE PROCEDURE h5tbwrite_field_index_f_int
MODULE PROCEDURE h5tbwrite_field_index_f_string
END INTERFACE
INTERFACE h5tbread_field_index_f
MODULE PROCEDURE h5tbread_field_index_f_int
MODULE PROCEDURE h5tbread_field_index_f_string
END INTERFACE
INTERFACE h5tbinsert_field_f
MODULE PROCEDURE h5tbinsert_field_f_int
MODULE PROCEDURE h5tbinsert_field_f_string
END INTERFACE
INTERFACE h5tbmake_table_f
MODULE PROCEDURE h5tbmake_table_f90
MODULE PROCEDURE h5tbmake_table_ptr_f
END INTERFACE
INTERFACE
INTEGER FUNCTION h5tbwrite_field_name_c(loc_id,namelen,dset_name,namelen1,field_name,&
start,nrecords,type_size,buf) &
BIND(C,NAME='h5tbwrite_field_name_c')
IMPORT :: C_CHAR, C_PTR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: field_name ! name of the field
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
TYPE(C_PTR), VALUE :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
END FUNCTION h5tbwrite_field_name_c
END INTERFACE
INTERFACE
INTEGER FUNCTION h5tbread_field_name_c(loc_id,namelen,dset_name,namelen1,field_name, &
start,nrecords,type_size,buf) &
BIND(C,NAME='h5tbread_field_name_c')
IMPORT :: C_CHAR, C_PTR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: field_name ! name of the field
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
TYPE(C_PTR), VALUE :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
END FUNCTION h5tbread_field_name_c
END INTERFACE
INTERFACE
INTEGER FUNCTION h5tbwrite_field_index_c(loc_id,namelen,dset_name,field_index,&
start,nrecords,type_size,buf) &
BIND(C,NAME='h5tbwrite_field_index_c')
IMPORT :: C_CHAR, C_PTR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: dset_name ! name of the dataset
INTEGER, INTENT(in) :: field_index ! index
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
TYPE(C_PTR), VALUE :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
END FUNCTION h5tbwrite_field_index_c
END INTERFACE
INTERFACE
INTEGER FUNCTION h5tbread_field_index_c(loc_id,namelen,dset_name,field_index,&
start,nrecords,type_size,buf) &
BIND(C,NAME='h5tbread_field_index_c')
IMPORT :: C_CHAR, C_PTR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: dset_name ! name of the dataset
INTEGER, INTENT(in) :: field_index ! index
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
TYPE(C_PTR), VALUE :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
END FUNCTION h5tbread_field_index_c
END INTERFACE
INTERFACE
INTEGER FUNCTION h5tbinsert_field_c(loc_id,namelen,dset_name,namelen1,field_name,&
field_type,field_index,buf) &
BIND(C,NAME='h5tbinsert_field_c')
IMPORT :: C_CHAR, C_PTR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: field_name ! name of the field
INTEGER(hid_t), INTENT(in) :: field_type ! field type
INTEGER, INTENT(in) :: field_index ! field_index
TYPE(C_PTR), VALUE :: buf ! data buffer
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length length
END FUNCTION h5tbinsert_field_c
END INTERFACE
CONTAINS
!-------------------------------------------------------------------------
! Function: h5tbmake_table_f90
!
! Purpose: Make a table
!
! Return: Success: 0, Failure: -1
!
! Programmer: [email protected]
!
! Date: October 06, 2004
!
! Comments:
!
! Modifications:
!
!-------------------------------------------------------------------------
SUBROUTINE h5tbmake_table_f90(table_title,&
loc_id,&
dset_name,&
nfields,&
nrecords,&
type_size,&
field_names,&
field_offset,&
field_types,&
chunk_size,&
compress,&
errcode )
IMPLICIT NONE
CHARACTER(LEN=*), INTENT(in) :: table_title ! name of the dataset
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
INTEGER(hsize_t), INTENT(in) :: nfields ! fields
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
CHARACTER(LEN=*), DIMENSION(1:nfields), INTENT(in) :: field_names ! field names
INTEGER(size_t), DIMENSION(1:nfields), INTENT(in) :: field_offset ! field offset
INTEGER(hid_t), DIMENSION(1:nfields), INTENT(in) :: field_types ! field types
INTEGER(hsize_t), INTENT(in) :: chunk_size ! chunk size
INTEGER, INTENT(in) :: compress ! compress
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
INTEGER :: errcode ! error code
INTEGER(size_t), DIMENSION(1:nfields) :: char_len_field_names ! field name lengths
INTEGER(size_t) :: max_char_size_field_names ! character len of field names
INTEGER(hsize_t) :: i ! general purpose integer
INTERFACE
INTEGER FUNCTION h5tbmake_table_c(namelen1,&
table_title,&
loc_id,&
namelen,&
dset_name,&
nfields,&
nrecords,&
type_size,&
field_offset,&
field_types,&
chunk_size,&
compress,&
char_len_field_names,&
max_char_size_field_names,&
field_names) &
BIND(C,NAME='h5tbmake_table_c')
IMPORT :: C_CHAR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: table_title ! name of the dataset
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: dset_name ! name of the dataset
INTEGER(hsize_t), INTENT(in) :: nfields ! fields
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
CHARACTER(KIND=C_CHAR), DIMENSION(nfields), INTENT(in) :: field_names ! field names
INTEGER(size_t), DIMENSION(nfields), INTENT(in) :: field_offset ! field offset
INTEGER(hid_t), DIMENSION(nfields), INTENT(in) :: field_types ! field types
INTEGER(hsize_t), INTENT(in) :: chunk_size ! chunk size
INTEGER, INTENT(in) :: compress ! compress
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
INTEGER(size_t), DIMENSION(nfields) :: char_len_field_names ! field name's lengths
INTEGER(size_t) :: max_char_size_field_names ! character len of field names
END FUNCTION h5tbmake_table_c
END INTERFACE
namelen = LEN(dset_name)
namelen1 = LEN(table_title)
! Find the size of each character string in the array
DO i = 1, nfields
char_len_field_names(i) = LEN_TRIM(field_names(i))
END DO
max_char_size_field_names = LEN(field_names(1))
errcode = h5tbmake_table_c(namelen1, table_title, loc_id, namelen, dset_name, nfields, nrecords,&
type_size, field_offset, field_types, chunk_size, compress, char_len_field_names, &
max_char_size_field_names, field_names)
END SUBROUTINE h5tbmake_table_f90
SUBROUTINE h5tbmake_table_ptr_f(table_title,&
loc_id,&
dset_name,&
nfields,&
nrecords,&
type_size,&
field_names,&
field_offset,&
field_types,&
chunk_size,&
fill_data,&
compress,&
data,&
errcode )
USE ISO_C_BINDING
IMPLICIT NONE
CHARACTER(LEN=*), INTENT(in) :: table_title ! name of the dataset
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
INTEGER(hsize_t), INTENT(in) :: nfields ! fields
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
CHARACTER(LEN=*), DIMENSION(1:nfields), INTENT(in) :: field_names ! field names
INTEGER(size_t), DIMENSION(1:nfields), INTENT(in) :: field_offset ! field offset
INTEGER(hid_t), DIMENSION(1:nfields), INTENT(in) :: field_types ! field types
INTEGER(hsize_t), INTENT(in) :: chunk_size ! chunk size
TYPE(C_PTR), INTENT(in) :: fill_data ! Fill values data
INTEGER, INTENT(in) :: compress ! compress
TYPE(C_PTR), INTENT(in) :: data ! Buffer with data to be written to the table
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
INTEGER :: errcode ! error code
INTEGER(size_t), DIMENSION(1:nfields) :: char_len_field_names ! field name lengths
INTEGER(size_t) :: max_char_size_field_names ! character len of field names
INTEGER(hsize_t) :: i ! general purpose integer
INTERFACE
INTEGER FUNCTION h5tbmake_table_ptr_c(namelen1,&
table_title,&
loc_id,&
namelen,&
dset_name,&
nfields,&
nrecords,&
type_size,&
field_offset,&
field_types,&
chunk_size,&
fill_data,&
compress,&
char_len_field_names,&
max_char_size_field_names,&
field_names,&
data) &
BIND(C,NAME='h5tbmake_table_ptr_c')
IMPORT :: C_CHAR, C_PTR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: table_title ! name of the dataset
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: dset_name ! name of the dataset
INTEGER(hsize_t), INTENT(in) :: nfields ! fields
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
CHARACTER(KIND=C_CHAR), DIMENSION(nfields), INTENT(in) :: field_names ! field names
INTEGER(size_t), DIMENSION(nfields), INTENT(in) :: field_offset ! field offset
INTEGER(hid_t), DIMENSION(nfields), INTENT(in) :: field_types ! field types
INTEGER(hsize_t), INTENT(in) :: chunk_size ! chunk size
TYPE(C_PTR), INTENT(in), VALUE :: fill_data ! Fill values data
INTEGER, INTENT(in) :: compress ! compress
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
INTEGER(size_t), DIMENSION(nfields) :: char_len_field_names ! field name's lengths
INTEGER(size_t) :: max_char_size_field_names ! character len of field names
TYPE(C_PTR), INTENT(in), VALUE :: data
END FUNCTION h5tbmake_table_ptr_c
END INTERFACE
namelen = LEN(dset_name)
namelen1 = LEN(table_title)
! Find the size of each character string in the array
DO i = 1, nfields
char_len_field_names(i) = LEN_TRIM(field_names(i))
END DO
max_char_size_field_names = LEN(field_names(1))
errcode = h5tbmake_table_ptr_c(namelen1, table_title, loc_id, namelen, dset_name, nfields, nrecords,&
type_size, field_offset, field_types, chunk_size, fill_data, compress, char_len_field_names, &
max_char_size_field_names, field_names, data)
END SUBROUTINE h5tbmake_table_ptr_f
SUBROUTINE h5tbread_table_f(loc_id, table_name, nfields, dst_size, dst_offset, &
dst_sizes, dst_buf, errcode)
USE ISO_C_BINDING
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! An array containing the sizes of the fields
CHARACTER(LEN=*), INTENT(in) :: table_name ! The name of the dataset to read
INTEGER(hsize_t), INTENT(in) :: nfields ! number of fields
INTEGER(size_t), INTENT(in) :: dst_size ! The size of the structure type
INTEGER(size_t), DIMENSION(1:nfields), INTENT(in) :: dst_offset ! An array containing the offsets of the fields
INTEGER(size_t), DIMENSION(1:nfields), INTENT(in) :: dst_sizes ! An array containing the sizes of the fields
TYPE(C_PTR) :: dst_buf ! Buffer with data !! do not use INTENT, causes NAG
! to segfault in C APIs
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
INTERFACE
INTEGER FUNCTION h5tbread_table_c(loc_id,&
table_name,&
namelen,&
nfields,&
dst_size,&
dst_offset, &
dst_sizes, &
dst_buf) &
BIND(C,NAME='h5tbread_table_c')
IMPORT :: C_PTR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=1), INTENT(in) :: table_name ! name of the dataset
INTEGER(hsize_t), INTENT(in) :: nfields
INTEGER(size_t), INTENT(in) :: dst_size ! type size
INTEGER(size_t), DIMENSION(1:nfields), INTENT(in) :: dst_offset ! An array containing the sizes of the fields
INTEGER(size_t), DIMENSION(1:nfields), INTENT(in) :: dst_sizes ! An array containing the sizes of the fields
INTEGER(size_t) :: namelen ! name length
TYPE(C_PTR), VALUE :: dst_buf
END FUNCTION h5tbread_table_c
END INTERFACE
namelen = LEN(table_name)
errcode = h5tbread_table_c(loc_id,&
table_name,&
namelen, &
nfields, &
dst_size,&
dst_offset, &
dst_sizes, &
dst_buf)
END SUBROUTINE h5tbread_table_f
!-------------------------------------------------------------------------
! Function: h5tbwrite_field_name_f_int
!
! Purpose: Writes one field
!
! Programmer: [email protected]
!
! Date: October 12, 2004
!
! Comments:
!
! Modifications:
!
!-------------------------------------------------------------------------
SUBROUTINE h5tbwrite_field_name_f_int(loc_id,&
dset_name,&
field_name,&
start,&
nrecords,&
type_size,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(LEN=*), INTENT(in) :: field_name ! name of the field
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
INTEGER, INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1))
namelen = LEN(dset_name)
namelen1 = LEN(field_name)
errcode = h5tbwrite_field_name_c(loc_id,namelen,dset_name,namelen1,field_name,&
start,nrecords,type_size,f_ptr)
END SUBROUTINE h5tbwrite_field_name_f_int
SUBROUTINE h5tbwrite_field_name_f_string(loc_id,&
dset_name,&
field_name,&
start,&
nrecords,&
type_size,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(LEN=*), INTENT(in) :: field_name ! name of the field
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
CHARACTER(LEN=*), INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1)(1:1))
namelen = LEN(dset_name)
namelen1 = LEN(field_name)
errcode = h5tbwrite_field_name_c(loc_id,namelen,dset_name,namelen1,field_name,&
start,nrecords,type_size,f_ptr)
END SUBROUTINE h5tbwrite_field_name_f_string
!-------------------------------------------------------------------------
! Function: h5tbread_field_name_f_int
!
! Purpose: Reads one field
!
! Programmer: [email protected]
!
! Date: October 12, 2004
!
! Comments:
!
! Modifications:
!
!-------------------------------------------------------------------------
SUBROUTINE h5tbread_field_name_f_int(loc_id,&
dset_name,&
field_name,&
start,&
nrecords,&
type_size,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(LEN=*), INTENT(in) :: field_name ! name of the field
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
INTEGER, INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1)) ! name length
namelen = LEN(dset_name)
namelen1 = LEN(field_name)
errcode = h5tbread_field_name_c(loc_id,namelen,dset_name,namelen1,field_name,&
start,nrecords,type_size,f_ptr)
END SUBROUTINE h5tbread_field_name_f_int
SUBROUTINE h5tbread_field_name_f_string(loc_id,&
dset_name,&
field_name,&
start,&
nrecords,&
type_size,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(LEN=*), INTENT(in) :: field_name ! name of the field
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
CHARACTER(LEN=*), INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1)(1:1))
namelen = LEN(dset_name)
namelen1 = LEN(field_name)
errcode = h5tbread_field_name_c(loc_id,namelen,dset_name,namelen1,field_name,&
start,nrecords,type_size,f_ptr)
END SUBROUTINE h5tbread_field_name_f_string
!-------------------------------------------------------------------------
! Function: h5tbwrite_field_index_f_int
!
! Purpose: Writes one field
!
! Programmer: [email protected]
!
! Date: October 12, 2004
!
! Comments:
!
! Modifications:
!
!-------------------------------------------------------------------------
SUBROUTINE h5tbwrite_field_index_f_int(loc_id,&
dset_name,&
field_index,&
start,&
nrecords,&
type_size,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
INTEGER, INTENT(in) :: field_index ! index
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
INTEGER, INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1))
namelen = LEN(dset_name)
errcode = h5tbwrite_field_index_c(loc_id,namelen,dset_name,field_index,&
start,nrecords,type_size,f_ptr)
END SUBROUTINE h5tbwrite_field_index_f_int
SUBROUTINE h5tbwrite_field_index_f_string(loc_id,&
dset_name,&
field_index,&
start,&
nrecords,&
type_size,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
INTEGER, INTENT(in) :: field_index ! index
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
CHARACTER(LEN=*), INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1)(1:1))
namelen = LEN(dset_name)
errcode = h5tbwrite_field_index_c(loc_id,namelen,dset_name,field_index,&
start,nrecords,type_size,f_ptr)
END SUBROUTINE h5tbwrite_field_index_f_string
!-------------------------------------------------------------------------
! Function: h5tbread_field_index_f_int
!
! Purpose: Reads one field
!
! Programmer: [email protected]
!
! Date: October 12, 2004
!
! Comments:
!
! Modifications:
!
!-------------------------------------------------------------------------
SUBROUTINE h5tbread_field_index_f_int(loc_id,&
dset_name,&
field_index,&
start,&
nrecords,&
type_size,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
INTEGER, INTENT(in) :: field_index ! index
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
INTEGER, INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1))
namelen = LEN(dset_name)
errcode = h5tbread_field_index_c(loc_id,namelen,dset_name,field_index,&
start,nrecords,type_size,f_ptr)
END SUBROUTINE h5tbread_field_index_f_int
SUBROUTINE h5tbread_field_index_f_string(loc_id,&
dset_name,&
field_index,&
start,&
nrecords,&
type_size,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
INTEGER, INTENT(in) :: field_index ! index
INTEGER(hsize_t), INTENT(in) :: start ! start record
INTEGER(hsize_t), INTENT(in) :: nrecords ! records
INTEGER(size_t), INTENT(in) :: type_size ! type size
CHARACTER(LEN=*), INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1)(1:1))
namelen = LEN(dset_name)
errcode = h5tbread_field_index_c(loc_id,namelen,dset_name,field_index,&
start,nrecords,type_size,f_ptr)
END SUBROUTINE h5tbread_field_index_f_string
!-------------------------------------------------------------------------
! Function: h5tbinsert_field_f
!
! Purpose: Inserts one field
!
! Programmer: [email protected]
!
! Date: October 13, 2004
!
! Comments:
!
! Modifications:
!
!-------------------------------------------------------------------------
SUBROUTINE h5tbinsert_field_f_int(loc_id,&
dset_name,&
field_name,&
field_type,&
field_index,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(LEN=*), INTENT(in) :: field_name ! name of the field
INTEGER(hid_t), INTENT(in) :: field_type ! field type
INTEGER, INTENT(in) :: field_index ! field_index
INTEGER, INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
INTEGER :: errcode ! error code
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1))
namelen = LEN(dset_name)
namelen1 = LEN(field_name)
errcode = h5tbinsert_field_c(loc_id,namelen,dset_name,namelen1,field_name,&
field_type,field_index,f_ptr)
END SUBROUTINE h5tbinsert_field_f_int
SUBROUTINE h5tbinsert_field_f_string(loc_id,&
dset_name,&
field_name,&
field_type,&
field_index,&
buf,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(LEN=*), INTENT(in) :: field_name ! name of the field
INTEGER(hid_t), INTENT(in) :: field_type ! field type
INTEGER, INTENT(in) :: field_index ! field_index
CHARACTER(LEN=*), INTENT(in), DIMENSION(*), TARGET :: buf ! data buffer
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
INTEGER :: errcode ! error code
TYPE(C_PTR) :: f_ptr
f_ptr = C_LOC(buf(1)(1:1))
namelen = LEN(dset_name)
namelen1 = LEN(field_name)
errcode = h5tbinsert_field_c(loc_id,namelen,dset_name,namelen1,field_name,&
field_type,field_index,f_ptr)
END SUBROUTINE h5tbinsert_field_f_string
!-------------------------------------------------------------------------
! Function: h5tbdelete_field_f
!
! Purpose: Inserts one field
!
! Programmer: [email protected]
!
! Date: October 13, 2004
!
! Comments:
!
! Modifications:
!
!-------------------------------------------------------------------------
SUBROUTINE h5tbdelete_field_f(loc_id,&
dset_name,&
field_name,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
CHARACTER(LEN=*), INTENT(in) :: field_name ! name of the field
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length
INTEGER :: errcode ! error code
INTERFACE
INTEGER FUNCTION h5tbdelete_field_c(loc_id,namelen,dset_name,namelen1,field_name) &
BIND(C,NAME='h5tbdelete_field_c')
IMPORT :: C_CHAR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
INTEGER(HID_T), INTENT(IN) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(IN) :: dset_name ! name of the dataset
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(IN) :: field_name ! name of the field
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: namelen1 ! name length length
END FUNCTION h5tbdelete_field_c
END INTERFACE
namelen = LEN(dset_name)
namelen1 = LEN(field_name)
errcode = h5tbdelete_field_c(loc_id,namelen,dset_name,namelen1,field_name)
END SUBROUTINE h5tbdelete_field_f
!-------------------------------------------------------------------------
! Function: h5tbget_table_info_f
!
! Purpose: Gets the number of records and fields of a table
!
! Return: Success: 0, Failure: -1
!
! Programmer: [email protected]
!
! Date: October 13, 2004
!
! Comments:
!
! Modifications:
!
!-------------------------------------------------------------------------
SUBROUTINE h5tbget_table_info_f(loc_id,&
dset_name,&
nfields,&
nrecords,&
errcode )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
INTEGER(hsize_t), INTENT(inout):: nfields ! nfields
INTEGER(hsize_t), INTENT(inout):: nrecords ! nrecords
INTEGER :: errcode ! error code
INTEGER(size_t) :: namelen ! name length
INTERFACE
INTEGER FUNCTION h5tbget_table_info_c(loc_id,namelen,dset_name,nfields,nrecords) &
BIND(C,NAME='h5tbget_table_info_c')
IMPORT :: C_CHAR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: dset_name ! name of the dataset
INTEGER(hsize_t), INTENT(inout):: nfields ! nfields
INTEGER(hsize_t), INTENT(inout):: nrecords ! nrecords
INTEGER(size_t) :: namelen ! name length
END FUNCTION h5tbget_table_info_c
END INTERFACE
namelen = LEN(dset_name)
errcode = h5tbget_table_info_c(loc_id,namelen,dset_name,nfields,nrecords)
END SUBROUTINE h5tbget_table_info_f
!-------------------------------------------------------------------------
! Function: h5tbget_field_info_f
!
! Purpose: Get information about fields
!
! Return: Success: 0, Failure: -1
!
! Programmer: [email protected]
!
! Date: October 13, 2004
!
! Comments:
!
! Modifications:
! Added optional parameter for returning the maximum character length
! in the field name array. March 3, 2011
!
!-------------------------------------------------------------------------
SUBROUTINE h5tbget_field_info_f(loc_id,&
dset_name,&
nfields,&
field_names,&
field_sizes,&
field_offsets,&
type_size,&
errcode, maxlen_out )
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(LEN=*), INTENT(in) :: dset_name ! name of the dataset
INTEGER(hsize_t), INTENT(in) :: nfields ! nfields
CHARACTER(LEN=*), DIMENSION(nfields), INTENT(inout) :: field_names ! field names
INTEGER(size_t), DIMENSION(nfields), INTENT(inout) :: field_sizes ! field sizes
INTEGER(size_t), DIMENSION(nfields), INTENT(inout) :: field_offsets ! field offsets
INTEGER(size_t), INTENT(inout):: type_size ! type size
INTEGER :: errcode ! error code
INTEGER, OPTIONAL :: maxlen_out ! maximum character len of the field names
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t), DIMENSION(nfields) :: namelen2 ! name lengths
INTEGER(hsize_t) :: i ! general purpose integer
INTEGER(size_t) :: maxlen
INTEGER(size_t) :: c_maxlen_out
INTERFACE
INTEGER FUNCTION h5tbget_field_info_c(loc_id,namelen,dset_name,nfields,&
field_sizes,field_offsets,type_size,namelen2, maxlen, field_names, c_maxlen_out) &
BIND(C,NAME='h5tbget_field_info_c')
IMPORT :: C_CHAR
IMPORT :: HID_T, SIZE_T, HSIZE_T
IMPLICIT NONE
INTEGER(hid_t), INTENT(in) :: loc_id ! file or group identifier
CHARACTER(KIND=C_CHAR), DIMENSION(*), INTENT(in) :: dset_name ! name of the dataset
INTEGER(hsize_t), INTENT(in):: nfields ! nfields
CHARACTER(KIND=C_CHAR), DIMENSION(1:nfields), INTENT(inout) :: field_names ! field names
INTEGER(size_t), DIMENSION(1:nfields), INTENT(inout) :: field_sizes ! field sizes
INTEGER(size_t), DIMENSION(1:nfields), INTENT(inout) :: field_offsets ! field offsets
INTEGER(size_t), INTENT(inout):: type_size ! type size
INTEGER(size_t) :: namelen ! name length
INTEGER(size_t) :: maxlen ! maxiumum length of input field names
INTEGER(size_t), DIMENSION(1:nfields) :: namelen2 ! name lengths
INTEGER(size_t) :: c_maxlen_out ! maximum character length of a field array element
END FUNCTION h5tbget_field_info_c
END INTERFACE
namelen = LEN(dset_name)
DO i = 1, nfields
namelen2(i) = LEN_TRIM(field_names(i))
END DO
maxlen = LEN(field_names(1))
c_maxlen_out = 0
errcode = h5tbget_field_info_c(loc_id, namelen,dset_name, nfields, &
field_sizes, field_offsets, type_size, namelen2, maxlen, field_names, c_maxlen_out)
IF(PRESENT(maxlen_out)) maxlen_out = c_maxlen_out
END SUBROUTINE h5tbget_field_info_f
END MODULE H5TB_CONST
|
import sys
import math
import os
from os.path import isfile, join
from tkinter import Image
import numpy as np
import cv2
import scipy
from scipy import fft, ifft
from numpy import histogram_bin_edges, linalg as LA
import matplotlib.pyplot as plt
from PIL import Image
def Histogram(input):
histogram_list = list()
for i in range(256):
search_idx = np.where(input == i)
histogram_list.append( [ i , len(search_idx[0]) ] )
return histogram_list
def histogramEqualization(frame):
# Appling BGR2HSV on each frame
image_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
#Extracting V Channel
v_channel = image_hsv[:,:,2]
height,width = v_channel.shape
histogram = Histogram(v_channel)
# normalizing by N pixels with intessities <= i
cumulative_dist = list()
zx = 0
for i in range(len(histogram)):
zx = zx + (histogram[i][1]/(height * width))
cumulative_dist.append(round(zx*255))
new_histogram = np.asarray(cumulative_dist)
# Image processing via equalization
image_hsv[:,:,2] = new_histogram[image_hsv[:,:,2]]
hsv_bgr_image = cv2.cvtColor(image_hsv, cv2.COLOR_HSV2BGR)
return histogram, hsv_bgr_image
def adaptiveHistogramEqualization(frame):
# Splitting images in tiles 5*5
# Applying histogram for every tile
img_height=int(frame.shape[0]/5)
img_width=int(frame.shape[1]/5)
for i in range(0,5):
for j in range(0,5):
tile = frame[int(i*img_height):int((i+1)*img_height),int(j*img_width):int((j+1)*img_width)]
_, adaptive_tile = histogramEqualization(tile)
frame[int(i*img_height):int((i+1)*img_height),int(j*img_width):int((j+1)*img_width)]= adaptive_tile
return frame
# Video Generating function
def generate_video():
image_folder = './Data/' # make sure to use your folder
video_name = 'input_problem1.avi'
os.chdir("/Users/sumedhreddy/Desktop/LanePrediction/")
images = [frame for frame in os.listdir(image_folder)
if frame.endswith(".jpg") or
frame.endswith(".jpeg") or
frame.endswith("png")]
# Array images should only consider
# the image files ignoring others if any
frame = cv2.imread(os.path.join(image_folder, images[0]))
# setting the frame width, height width
# the width, height of first image
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 1, (width, height))
# Appending the images to the video one by one
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
# Deallocating memories taken for window creation
cv2.destroyAllWindows()
video.release()
# Implementation of Histogram equalization - Normal and Adaptive
# Program to enhance the contrast and improve the visual appearance of the video sequence
# Problem 1 a: Normal historgram equalization
# Folder which contains all the images
# from which video is to be generated
os.chdir("/Users/sumedhreddy/Desktop/LanePrediction/Data")
path = "/Users/sumedhreddy/Desktop/LanePrediction/Data" # set path depending on your OS
mean_height = 0
mean_width = 0
num_of_images = len(os.listdir('.'))
print('Total number of images in the Folder:',num_of_images)
for file in os.listdir('.'):
im = Image.open(os.path.join(path, file))
width, height = im.size
mean_width += width
mean_height += height
# Finding the mean height and width of all images.
# This is required because the video frame needs
# to be set with same width and height. Otherwise
# images not equal to that width height will not get
# embedded into the video
mean_width = int(mean_width / num_of_images)
mean_height = int(mean_height / num_of_images)
# print(mean_height)
# print(mean_width)
# Resizing of the images to give
# them same width and height
for file in os.listdir('.'):
if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith("png"):
# opening image using PIL Image
im = Image.open(os.path.join(path, file))
# im.size includes the height and width of image
width, height = im.size
# resizing
imResize = im.resize((mean_width, mean_height), Image.ANTIALIAS)
imResize.save( file, 'JPEG', quality = 95) # setting quality
# printing each resized image name
# print(im.filename.split('\\')[-1], " is resized")
# Calling the generate_video function
print("Processing Images into video")
generate_video()
input_=cv2.VideoCapture('input_problem1.avi')
input_.set(1,1)
output_histogram = cv2.VideoWriter("histogram_problem_1a.avi", cv2.VideoWriter_fourcc(*'XVID'), 20, (1224, 370))
adapt_histogram = cv2.VideoWriter("adaptive_problem_1b.avi", cv2.VideoWriter_fourcc(*'XVID'), 20, (1224, 370))
if (input_.isOpened() == False):
print('Error opening the file!')
count = 0
while (input_.isOpened()):
count+=1
success, image = input_.read()
if success:
print("Performing Histogram equalization")
img = image.copy()
img1 = image.copy()
histogram, histogram_image=histogramEqualization(img)
for i in range(0,24):
output_histogram.write(histogram_image)
print("Performing Adaptive Histogram equalization")
hist_adapt = adaptiveHistogramEqualization(img1)
for i in range(0,24):
adapt_histogram.write(hist_adapt)
if count == 5:
print("Applying and Displaying Histogram on Frame 5")
plt.hist(histogram_image.ravel(),256,[0,256])
plt.savefig('histogram_plot.png')
print("Histogram Graph saved as: ", 'histogram_plot.png')
# Comparing input image with histogram image
compare_images = np.vstack((image, histogram_image))
cv2.imwrite("Histogram_frame.jpg" , histogram_image)
cv2.imwrite("Histogram_Compare.jpg", compare_images)
print("Histogram Equalization Complete!!!'")
########################################################
# Problem 1b: Adaptive historgram equalization
plt.hist(hist_adapt.ravel(),256,[0,256])
plt.savefig('Adaptive_histogram_plot.png')
print("Histogram Frame 5 saved as: ", 'Adaptive_histogram_plot.png')
# Comparing input image with histogram image
compare_images = np.vstack((image, histogram_image, hist_adapt))
cv2.imwrite("Adaptive_Histogram_frame.jpg" , hist_adapt)
cv2.imwrite("Adaptive_Histogram_Compare.jpg", compare_images)
print("Adaptive Histogram Equalization Complete!!!'")
break
input_.release()
adapt_histogram.release()
output_histogram.release()
cv2.destroyAllWindows()
|
lemma filterlim_inverse_at_iff: fixes g :: "'a \<Rightarrow> 'b::{real_normed_div_algebra, division_ring}" shows "(LIM x F. inverse (g x) :> at 0) \<longleftrightarrow> (LIM x F. g x :> at_infinity)"
|
# 04 dimension reduction
# using the libraries
using UMAP, XLSX, VegaDatasets, DataFrames, MultivariateStats, RDatasets, StatsBase, Statistics, LinearAlgebra, Plots, ScikitLearn, MLBase, Distances
# import the data
C = DataFrame(VegaDatasets.dataset("cars"));
describe(C);
# clean the data
dropmissing!(C);
M = Matrix{Float64}(C[!, 2:7]);
n = names(C)[2:end];
# For MLBase and label map
# USA -> 1
# Europe -> 2 etc...
car_origin = C[!, :Origin];
unique(car_origin);
carmap = labelmap(car_origin);
uniqueids = labelencode(carmap, car_origin)
# PCA approximate the matrix
# Center and standardize the data
data = M;
data = (data .- mean(data, dims=1)) ./ std(data, dims=1);
# fit the data
p = fit(PCA, data', maxoutdim=2)
# projection
P = projection(p);
P' * (data[1, :] - mean(p))
#
Yte = P' * data'
Yte = MultivariateStats.transform(p, data')
# reconstruct the matrix
Xr = reconstruct(p, Yte);
data' - Xr;
@show norm(data' - Xr)
# the approximation gets better when more maxoutdims are used.
# plotting
scatter(Yte[1,:],Yte[2,:])
scatter(Yte[1,car_origin.=="USA"],Yte[2,car_origin.=="USA"],color=1,label="USA")
scatter!(Yte[1,car_origin.=="Japan"],Yte[2,car_origin.=="Japan"],color=2,label="Japan")
scatter!(Yte[1,car_origin.=="Europe"],Yte[2,car_origin.=="Europe"],color=3,label="Europe")
xlabel!("pca component1")
ylabel!("pca component2")
# three dim maxxout
p = fit(PCA,data',maxoutdim=3)
Yte = MultivariateStats.transform(p, data')
scatter3d(Yte[1,:],Yte[2,:],Yte[3,:],color=uniqueids,legend=false)
# tsne
# @sk_import manifold : TSNE
tfn = TSNE(n_components=3 ,perplexity=20.0,early_exaggeration=50)
Y2 = tfn.fit_transform(data);
scatter(Y2[:,1],Y2[:,2],Y2[:,3],color=uniqueids,legend=false,size=(400,300),markersize=3)
# umap
L = cor(data,data,dims=2)
@time embedding = umap(L, )
scatter(embedding[1,:],embedding[2,:],color=uniqueids)
# different distance
@time L2 = pairwise(Euclidean(), data, data,dims=1)
embedding = umap(-L, 2)
scatter(embedding[1,:],embedding[2,:],color=uniqueids)
|
function P = subGFM(PopObj,Center,R,FrontNo)
% PF modeling for each subregion
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------
K = size(Center,1);
[N,M] = size(PopObj);
% Normalize the population
fmin = min(PopObj,[],1);
fmax = max(PopObj,[],1);
Obj = (PopObj-repmat(fmin,N,1))./repmat(fmax-fmin,N,1);
% PF modeling
if K == 1
P = GFM(Obj(FrontNo==1,:));
else
P = ones(K,M);
% Allocation
transformation = Allocation(Obj,Center,R);
subFirstFront = false(N,1);
% Non-dominated sorting od each subregion
for i = 1 : K
current = find(transformation == i);
if ~isempty(current)
[FNo,MFNo] = NDSort(PopObj(current,:),length(current));
subFirstFront(current(FNo<MFNo|FNo==1)) = true;
end
end
FTransformation = transformation(subFirstFront);
PopObj = PopObj(subFirstFront,:);
RemainObj = Obj(subFirstFront,:);
% GFM of each subregion
if size(PopObj,1) > M
for i = 1 : K
current = find(FTransformation==i);
if ~isempty(current)
if length(current) < M+1
[~,sDis] = sort(pdist2(RemainObj ,Center(i,:)));
current = sDis(1:M+1);
end
p = GFM(Obj(current,:));
P(i,:) = p;
end
end
end
end
end
function P = GFM(X)
% Generic front modeling
[N,M] = size(X);
X = max(X,1e-12);
P = ones(1,M);
lamda = 1;
E = sum(X.^repmat(P,N,1),2) - 1;
MSE = mean(E.^2);
for epoch = 1 : 1000
% Calculate the Jacobian matrix
J = X.^repmat(P,N,1).*log(X);
% Update the value of each weight
while true
Delta = -(J'*J+lamda*eye(size(J,2)))^-1*J'*E;
newP = P + Delta(1:end)';
newE = sum(X.^repmat(newP,N,1),2) - 1;
newMSE = mean(newE.^2);
if newMSE < MSE && all(newP>1e-3)
P = newP;
E = newE;
MSE = newMSE;
lamda = lamda/1.08;
break;
elseif lamda > 1e8
return;
else
lamda = lamda*1.08;
end
end
end
end
|
theory ExF004
imports Main
begin
theorem "(\<forall>x. \<exists>y. P x y) \<or> (\<exists>x. \<forall>y. \<not>P x y)"
proof -
{
assume a:"\<not>((\<forall>x. \<exists>y. P x y) \<or> (\<exists>x. \<forall>y. \<not>P x y) )"
{
assume "\<forall>x. \<exists>y. P x y"
hence "(\<forall>x. \<exists>y. P x y) \<or> (\<exists>x. \<forall>y. \<not>P x y)" ..
with a have False ..
}
hence b:"\<not>(\<forall>x. \<exists>y. P x y)" by (rule notI)
{
assume c:"\<not>(\<exists>x. \<forall>y. \<not>P x y)"
{
fix aa
{
assume d:"\<not>(\<exists>y. P aa y)"
{
fix bb
{
assume "P aa bb"
hence "\<exists>y. P aa y" by (rule exI)
with d have False by contradiction
}
hence "\<not>P aa bb" by (rule notI)
}
hence "\<forall>y. \<not>P aa y" by (rule allI)
hence "\<exists>x. \<forall>y. \<not>P x y" by (rule exI)
with c have False by contradiction
}
hence "\<not>\<not>(\<exists>y. P aa y)" by (rule notI)
hence "\<exists>y. P aa y" by (rule notnotD)
}
hence "\<forall>x. \<exists>y. P x y" by (rule allI)
with b have False by contradiction
}
hence "\<not>\<not>(\<exists>x. \<forall>y. \<not>P x y)" by (rule notI)
hence "\<exists>x. \<forall>y. \<not>P x y" by (rule notnotD)
hence "(\<forall>x. \<exists>y. P x y) \<or> (\<exists>x. \<forall>y. \<not>P x y)" by (rule disjI2)
with a have False by contradiction
}
hence "\<not>\<not>((\<forall>x. \<exists>y. P x y) \<or> (\<exists>x. \<forall>y. \<not>P x y))" by (rule notI)
thus ?thesis by (rule notnotD)
qed
|
{-
module Solve
( Ord
, DoubleMap
, innerKeys
, toMatrix
, toMatrix'
, trans
, solve
, smartSolve ) where
-}
module Solve where
import Data.List (elemIndex, nub, sort, union, (\\))
import Data.List.Extra (groupSortOn)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe (catMaybes, mapMaybe)
import Data.Tuple (swap)
import Numeric.LinearAlgebra
type DoubleMap k l a = Map k (Map l a)
pullMaybe :: Monad m => (m a, m b) -> m (a, b)
pullMaybe = (>>= (fmap swap . sequence . swap)) . sequence
innerKeys :: Eq l => DoubleMap k l a -> [l]
innerKeys = nub . concatMap M.keys . M.elems
keyToInt :: Ord k => k -> DoubleMap k l a -> Maybe Int
keyToInt n = elemIndex n . sort . M.keys
innerKeyToInt :: Ord l => l -> DoubleMap k l a -> Maybe Int
innerKeyToInt n = elemIndex n . sort . innerKeys
toAssocList :: DoubleMap k l a -> [((k, l), a)]
toAssocList = fmap f . concatMap sequence . M.toList . fmap M.toList
where f (n, (i, a)) = ((n, i), a)
toAssocInt :: (Ord k, Ord l) => DoubleMap k l a -> [((Int, Int), a)]
toAssocInt b = mapMaybe f . toAssocList $ b
where
f ((n, i), a) = pullMaybe (pullMaybe (keyToInt n b, innerKeyToInt i b), Just a)
fromAssocList :: (Ord k, Ord l) => [((k, l), a)] -> DoubleMap k l a
fromAssocList = fmap M.fromList . M.fromList . fmap shift . groupSortOn fst . fmap f
where
shift xs = (fst . head $ xs, fmap snd xs)
f ((k, l), a) = (k, (l, a))
trans :: (Ord k, Ord l) => DoubleMap k l a -> DoubleMap l k a
trans = fromAssocList . fmap f . toAssocList
where f ((l, k), a) = ((k, l), a)
-- Outer keys are rows
toMatrix :: (Container Vector a, Num a, Ord k, Ord l)
=> DoubleMap k l a -> Matrix a
toMatrix b = assoc (M.size b, length $ innerKeys b) 0 (toAssocInt b)
-- Column matrix from a Map
toMatrix' :: (Container Vector a, Num a, Ord k) => Map k a -> Matrix a
toMatrix' = toMatrix . fmap (M.fromList . pure . ((),))
-- Are the rows independent?
isInd :: (Field a, Ord k, Ord l) => DoubleMap k l a -> Bool
isInd m = rank (toMatrix m) == M.size m
-- Choices of n elements from a list, fast algorithm from stack overflow.
-- https://stackoverflow.com/questions/21265454/subsequences-of-length-n-from-list-performance/21288092#21288092
choices :: Int -> [a] -> [[a]]
choices n xs =
let l = length xs
in if n>l then [] else subsequencesBySize xs !! (l-n)
where
subsequencesBySize [] = [[[]]]
subsequencesBySize (y:ys) =
let next = subsequencesBySize ys
in zipWith (++) ([]:next) (map (map (y:)) next ++ [[]])
-- SubMaps with n keys, excluding some.
allSizeNSub :: Ord k => Int -> Map k v -> [Map k v]
allSizeNSub n m =
[ M.filterWithKey (\k _ -> k `elem` keyList) m
| keyList <- choices n . M.keys $ m ]
-- The max rank submatricies with independent rows, excluding some.
allMaxInd :: (Field a, Ord k, Ord l)
=> DoubleMap k l a -> [DoubleMap k l a]
allMaxInd m = filter isInd . allSizeNSub (rank $ toMatrix m) $ m
-- The max rank submatricies with independent rows,
-- including or excluding certain rows.
chooseInd :: (Field a, Ord k, Ord l)
=> [k] -> [k] -> DoubleMap k l a -> [DoubleMap k l a]
chooseInd fixedKeys free m = filter hasKeys . allMaxInd $ m'
where
hasKeys b = null $ fixedKeys \\ M.keys b
m' = M.filterWithKey (\k _ -> k `notElem` free) m
-- Maximal sets of independent columns.
chooseCols :: (Field a, Ord k, Ord l) => DoubleMap k l a -> [DoubleMap k l a]
chooseCols = fmap trans . allMaxInd . trans
-- All submatricies with independent rows and columns, respecting row preferences.
chooseBoth :: (Field a, Ord k, Ord l)
=> [k] -> [k] -> DoubleMap k l a -> [DoubleMap k l a]
chooseBoth fixedKeys free m = concatMap chooseCols (chooseInd fixedKeys free m)
-- All legal constraints where extra terms to zero.
allExtraZero :: (Field a, Ord k, Num v, Ord l)
=> Map k v -> [k] -> DoubleMap k l a -> [Map k v]
allExtraZero fixed free = fmap (M.union fixed . fmap (const 0))
. chooseInd (M.keys fixed) free
-- Solve Ax = B, where B is a column matrix.
innerSolver :: (Field a, Ord l, Ord k)
=> DoubleMap k l a -> Map k a -> Maybe (Map l a)
innerSolver b c
| M.keys b == M.keys c = fromCol <$> linearSolve (toMatrix b) (toMatrix' c)
| otherwise = Nothing
where
fromCol = M.fromList . zip (sort . innerKeys $ b) . concat . toLists
-- Takes a list of fixed values, a list of free values,
-- and a DoubleMap, and attempts to solve.
solve :: (Eq a, Field a, Ord k, Ord l)
=> Map k a -> [k] -> DoubleMap k l a -> [Map l a]
solve fixed free m = nub . catMaybes $
[ innerSolver x y
| x <- chooseBoth (M.keys fixed) free m
, y <- allExtraZero fixed free m ]
-- Rows with a unique nonzero entry.
looseEnds :: (Eq a, Ord k, Num a) => DoubleMap k l a -> [k]
looseEnds m =
[ k
| k <- M.keys m
, let rowK = M.findWithDefault M.empty k m
, (== 1) . M.size . M.filter (/= 0) $ rowK ]
-- Tries setting loose ends to be free,
-- excluding those already declared to be fixed.
smartSolve :: (Field a, Ord k, Ord l, Ord a)
=> Map k a -> [k] -> DoubleMap k l a -> [Map l a]
smartSolve fixed free m = case filter (all (>= 0)) . solve fixed free' $ m of
[] -> solve fixed free m
xs -> xs
where
free' = union free $ looseEnds m \\ M.keys fixed
|
/-
Copyright (c) 2022 David Kurniadi Angdinata. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Kurniadi Angdinata
! This file was ported from Lean 3 source module ring_theory.dedekind_domain.S_integer
! leanprover-community/mathlib commit 00ab77614e085c9ef49479babba1a7d826d3232e
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.RingTheory.DedekindDomain.AdicValuation
/-!
# `S`-integers and `S`-units of fraction fields of Dedekind domains
Let `K` be the field of fractions of a Dedekind domain `R`, and let `S` be a set of prime ideals in
the height one spectrum of `R`. An `S`-integer of `K` is defined to have `v`-adic valuation at most
one for all primes ideals `v` away from `S`, whereas an `S`-unit of `Kˣ` is defined to have `v`-adic
valuation exactly one for all prime ideals `v` away from `S`.
This file defines the subalgebra of `S`-integers of `K` and the subgroup of `S`-units of `Kˣ`, where
`K` can be specialised to the case of a number field or a function field separately.
## Main definitions
* `set.integer`: `S`-integers.
* `set.unit`: `S`-units.
* TODO: localised notation for `S`-integers.
## Main statements
* `set.unit_equiv_units_integer`: `S`-units are units of `S`-integers.
* TODO: proof that `S`-units is the kernel of a map to a product.
* TODO: proof that `∅`-integers is the usual ring of integers.
* TODO: finite generation of `S`-units and Dirichlet's `S`-unit theorem.
## References
* [D Marcus, *Number Fields*][marcus1977number]
* [J W S Cassels, A Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [J Neukirch, *Algebraic Number Theory*][Neukirch1992]
## Tags
S integer, S-integer, S unit, S-unit
-/
namespace Set
noncomputable section
open IsDedekindDomain
open nonZeroDivisors
universe u v
variable {R : Type u} [CommRing R] [IsDomain R] [IsDedekindDomain R]
(S : Set <| HeightOneSpectrum R) (K : Type v) [Field K] [Algebra R K] [IsFractionRing R K]
/-! ## `S`-integers -/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (v «expr ∉ » S) -/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (v «expr ∉ » S) -/
/-- The `R`-subalgebra of `S`-integers of `K`. -/
@[simps]
def integer : Subalgebra R K :=
{
(⨅ (v) (_ : v ∉ S), (v : HeightOneSpectrum R).Valuation.ValuationSubring.toSubring).copy
{ x : K | ∀ (v) (_ : v ∉ S), (v : HeightOneSpectrum R).Valuation x ≤ 1 } <|
Set.ext fun _ => by simpa only [SetLike.mem_coe, Subring.mem_infᵢ] with
algebraMap_mem' := fun x v _ => v.valuation_le_one x }
#align set.integer Set.integer
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (v «expr ∉ » S) -/
theorem integer_eq :
(S.integer K).toSubring =
⨅ (v) (_ : v ∉ S), (v : HeightOneSpectrum R).Valuation.ValuationSubring.toSubring :=
SetLike.ext' <| by simpa only [integer, Subring.copy_eq]
#align set.integer_eq Set.integer_eq
theorem integer_valuation_le_one (x : S.integer K) {v : HeightOneSpectrum R} (hv : v ∉ S) :
v.Valuation (x : K) ≤ 1 :=
x.property v hv
#align set.integer_valuation_le_one Set.integer_valuation_le_one
/-! ## `S`-units -/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (v «expr ∉ » S) -/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (v «expr ∉ » S) -/
/-- The subgroup of `S`-units of `Kˣ`. -/
@[simps]
def unit : Subgroup Kˣ :=
(⨅ (v) (_ : v ∉ S), (v : HeightOneSpectrum R).Valuation.ValuationSubring.unitGroup).copy
{ x : Kˣ | ∀ (v) (_ : v ∉ S), (v : HeightOneSpectrum R).Valuation (x : K) = 1 } <|
Set.ext fun _ => by simpa only [SetLike.mem_coe, Subgroup.mem_infᵢ, Valuation.mem_unitGroup_iff]
#align set.unit Set.unit
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (v «expr ∉ » S) -/
theorem unit_eq :
S.Unit K = ⨅ (v) (_ : v ∉ S), (v : HeightOneSpectrum R).Valuation.ValuationSubring.unitGroup :=
Subgroup.copy_eq _ _ _
#align set.unit_eq Set.unit_eq
theorem unit_valuation_eq_one (x : S.Unit K) {v : HeightOneSpectrum R} (hv : v ∉ S) :
v.Valuation (x : K) = 1 :=
x.property v hv
#align set.unit_valuation_eq_one Set.unit_valuation_eq_one
/-- The group of `S`-units is the group of units of the ring of `S`-integers. -/
@[simps]
def unitEquivUnitsInteger : S.Unit K ≃* (S.integer K)ˣ
where
toFun x :=
⟨⟨x, fun v hv => (x.property v hv).le⟩, ⟨↑x⁻¹, fun v hv => (x⁻¹.property v hv).le⟩,
Subtype.ext x.val.val_inv, Subtype.ext x.val.inv_val⟩
invFun x :=
⟨Units.mk0 x fun hx => x.NeZero ((Subring.coe_eq_zero_iff _).mp hx), fun v hv =>
eq_one_of_one_le_mul_left (x.val.property v hv) (x.inv.property v hv) <|
Eq.ge <| by
rw [← map_mul]
convert v.valuation.map_one
exact subtype.mk_eq_mk.mp x.val_inv⟩
left_inv _ := by
ext
rfl
right_inv _ := by
ext
rfl
map_mul' _ _ := by
ext
rfl
#align set.unit_equiv_units_integer Set.unitEquivUnitsInteger
end Set
|
\par
\subsection{{\tt I2OP} :
{\tt (int, int, void*, pointer)} singly linked-list methods}
\label{subsection:Utilities:proto:I2OP}
\par
\hspace{0.5 in}
\begin{minipage}{2.5 in}
\begin{verbatim}
typedef struct _I2OP I2OP ;
struct _I2OP {
int value0 ;
int value1 ;
void value2 ;
I2OP *next ;
} ;
\end{verbatim}
\end{minipage}
\par
%=======================================================================
\begin{enumerate}
%-----------------------------------------------------------------------
\item
\begin{verbatim}
I2OP * I2OP_init ( int n, int flag ) ;
\end{verbatim}
\index{I2OP_init@{\tt I2OP\_init()}}
This is the allocator and initializer method for a vector of
{\tt I2OP} structures.
Storage for an array with size {\tt n} is found.
A pointer to an array {\tt ips[]} is returned
with {\tt ips[i].val = 0} for {\tt 0 <= i < n}.
The {\tt flag} parameter determines how the {\tt next} field
is filled.
\begin{itemize}
\item
If {\tt flag = I2OP\_NULL}, the elements are not linked,
i.e., {\tt ips[i].next = NULL}
for {\tt 0 <= i < n}.
\item
If {\tt flag = I2OP\_FORWARD},
the elements are linked in a forward manner,
i.e., {\tt ips[i].next = \&ips[i+1]}
for {\tt 0 <= i < n-1} and {\tt ips[n-1].next = NULL}.
\item
If {\tt flag = I2OP\_BACKWARD},
the elements are linked in a backward manner,
i.e., {\tt ips[i].next = \&ips[i-1]}
for {\tt 0 < i < n} and {\tt ips[0].next = NULL}.
\end{itemize}
%-----------------------------------------------------------------------
\item
\begin{verbatim}
I2OP * I2OP_initStorage ( int n, int flag, I2OP *base ) ;
\end{verbatim}
\index{I2OP_initStorage@{\tt I2OP\_initStorage()}}
This is an initializer method for a vector of
{\tt I2OP} structures.
We set {\tt base[i].value0 = base[i].value1 = -1}.
The {\tt flag} parameter determines how the {\tt next} field
is filled.
\begin{itemize}
\item
If {\tt flag = I2OP\_NULL}, the elements are not linked,
i.e., {\tt ips[i].next = NULL}
for {\tt 0 <= i < n}.
\item
If {\tt flag = I2OP\_FORWARD},
the elements are linked in a forward manner,
i.e., {\tt ips[i].next = \&ips[i+1]}
for {\tt 0 <= i < n-1} and {\tt ips[n-1].next = NULL}.
\item
If {\tt flag = I2OP\_BACKWARD},
the elements are linked in a backward manner,
i.e., {\tt ips[i].next = \&ips[i-1]}
for {\tt 0 < i < n} and {\tt ips[0].next = NULL}.
\end{itemize}
%-----------------------------------------------------------------------
\item
\begin{verbatim}
void I2OP_free ( I2OP *i2op ) ;
\end{verbatim}
\index{I2OP_free@{\tt I2OP\_free()}}
This method releases the storage based at {\tt *i2op}.
%-----------------------------------------------------------------------
\item
\begin{verbatim}
void I2OP_fprintf ( FILE *fp, I2OP *i2op ) ;
\end{verbatim}
\index{I2OP_fprintf@{\tt I2OP\_fprintf()}}
This method prints the singly linked list that starts with {\tt i2op}.
%-----------------------------------------------------------------------
\end{enumerate}
|
SUBROUTINE CLEARE
C CLEAR REDUCE- AND SHIFT-ITEMS
C 2005-03-29: demingle STASTRS
C GF 16.07.1980
C GF 04.04.1981: DO NOT 'CLEARE' ITEMS FOR IDENTIFIERS/KEYWORDS
C
C ALL ITEMS FOR THE 1ST REDUCTION ARE DELETED FROM THE STATES
C AND REPLACED BY AN ITEM WITH DUMMY LOOK-AHEAD 'EOP'
C (EVEN THE 1ST MAY NOT EXIST, OR MAY BE THE ONLY ONE)
C
C FOR SHIFT-ITEMS FOR THE SAME SYMBOL ALL BUT THE 1ST
C MARKED PRODUCTION ARE DELETED, IF PARAMETER 'CLEASH' = 1
C
INCLUDE 'PARS.f'
INCLUDE 'ITES.f'
INCLUDE 'MEMS.f'
INCLUDE 'PROS.f'
INCLUDE 'STAS.f'
INCLUDE 'STRS.f'
INCLUDE 'SYMS.f'
INTEGER*2 PARASK
INTEGER*2 ZZCR
INTEGER*2 I1,I2 ! -> 2 SUCCESSIVE ITEMS
= ,CLEASH ! = 'SHIFT' (0) IFF SHIFT-ITEMS ARE (NOT) TO BE CLEARED
= ,DERED ! NUMBER OF DELETED REDUCE-ITEMS
= ,DESHI ! ... SHIFT-ITEMS
= ,GOT ! RESULT OF 'ITEMA2'
= ,MAXITE ! MAX. NO. OF ITEMS IN A STATE BEFORE DELETION
= ,NUMITE ! NUMBER OF ITEMS IN A PARITCULAR STATE
INTEGER*2 POS ! -> 1ST CHARACTER OF 'SYMBOL'
= ,RED ! THE 1ST REDUCTION
= ,RED2 ! AN EVENTUALLY PRESENT 2ND REDUCTION
= ,STATE ! ONE OF ALL STATES IN THE PARSING TABLE
= ,STATEA ! A SUCCESSOR OF 'STATE'
= ,SUMITE ! NUMBER OF ITEMS IN ALL STATES BEFORE DELETION
= ,SYMBOL ! IS THIS SYMBOL A KEYWORD OR IDENTIFIER ?
C
DERED = 0
DESHI = 0
MAXITE = 0
SUMITE = 0
CLEASH = PARASK ('CLEASH',1,6,1) ! 1 => CLEASH = SHIFT
DO 1 STATE = 2,FSTA
IF (STAITE(STATE) .EQ. 0) GOTO 2 ! STATE EXISTS
NUMITE = 0
RED = 0 ! 1ST DOES NOT EXIST
RED2 = 0 ! 2ND DOES NOT EXIST
STATEA=0 ! SUCCESSOR DOES NOT YET EXIST
CALL ITEMA2 (STATE, I1,I2,GOT)
3 IF(I2 .GE. ITEHIB) GOTO 4 ! FOR ALL ITEMS 'I2'
NUMITE = NUMITE + 1
IF (ITEACT(I2) .NE. REDUCE) GOTO 5
SYMBOL = ITESYM(I2) ! <---- was ITEM???
POS = SYMPOS(SYMBOL)
IF (ZZCR (STRNG,POS,POS,'A',1,1) .GE. 0) GOTO 5
C HERE IT IS NO IDENTIFIER OR KEYWORD
IF (RED .NE. 0) GOTO 6 ! 1ST RED IN THE STATE
RED = ITESUC(I2)
6 CONTINUE
IF (ITESUC(I2) .NE. RED)
= GOTO 100 ! KEEP
DERED = DERED + 1 ! WILL BE DELETED
GOTO 7
5 CONTINUE ! .NE. REDUCE
IF (ITEACT(I2) .NE. CLEASH) GOTO 8
IF (ITESUC(I2) .EQ. STATEA) GOTO 9
STATEA = ITESUC(I2)
GOTO 100 ! KEEP
9 CONTINUE
DESHI = DESHI + 1 ! WILL BE DELETED
GOTO 7
8 CONTINUE
GOTO 100 ! KEEP
7 CONTINUE
C
101 CONTINUE ! DELETE:
ITE(I1) = ITE(I2)
ITE(I2) = FITE
FITE = I2
I2 = I1
C
100 CONTINUE ! KEEP:
I1 = I2
I2 = ITE(I1)
GOTO 3
4 CONTINUE ! ALL ITEMS
C
IF (NUMITE .GT. MAXITE) MAXITE = NUMITE
SUMITE = SUMITE + NUMITE
C
IF (RED .EQ. 0) GOTO 10
C INSERT 'RED' WITH DUMMY LA 'EOP'
DERED = DERED - 1
I1 = 1
I2 = ITE(I1)
CALL ITEALL (EOP,PROMON(RED)+PROLNG(RED),REDUCE,RED, I1,I2)
IF (RED2 .EQ. 0) GOTO 11
CALL ASSERT(60,STATE,RED2)
C STATE @ CONTAINS AT LEAST A 2ND REDUCTION @
11 CONTINUE
10 CONTINUE ! RED .NE. 0
CALL ITEMA9 (STATE,GOT)
2 CONTINUE ! STATE EXISTS
1 CONTINUE ! ALL STATES
C
CALL INFSTO (6,MAXITE,SUMITE)
CALL ASSERT (130,DERED,DESHI)
C @ REDUCE- AND @ SHIFT-ITEMS DELETED
RETURN
END
|
-- Andreas, 2019-03-28, issue #3248, reported by guillaumebrunerie
{-# OPTIONS --sized-types --show-implicit #-}
-- {-# OPTIONS -v tc:10 #-}
-- {-# OPTIONS -v tc.term:20 #-}
-- {-# OPTIONS -v tc.conv.size:45 #-}
-- {-# OPTIONS -v tc.conv.coerce:45 #-}
-- {-# OPTIONS -v tc.term.args.target:45 #-}
{-# BUILTIN SIZEUNIV SizeUniv #-} -- SizeUniv : SizeUniv
{-# BUILTIN SIZE Size #-} -- Size : SizeUniv
{-# BUILTIN SIZELT Size<_ #-} -- Size<_ : ..Size → SizeUniv
{-# BUILTIN SIZESUC ↑_ #-} -- ↑_ : Size → Size
{-# BUILTIN SIZEINF ∞ #-} -- ∞ : Size
{-# BUILTIN SIZEMAX _⊔ˢ_ #-} -- _⊔ˢ_ : Size → Size → Size
data D (i : Size) : Set where
c : {j : Size< i} → D j → D i
f : {i : Size} → D i → D i → D i
f (c {j₁} l1)
(c {j₂} l2) = c {j = j₁ ⊔ˢ j₂} (f {j₁ ⊔ˢ j₂} l1 l2)
-- The problem was that the new "check target first" logic
-- e49d1ca276e5adbf2eb9f6cd33926b786cef78f7
-- for checking applications does not work for Size<.
--
-- Checking target types first
-- inferred = Size
-- expected = Size< i
--
-- It is not the case that Size <= Size< i, however, coerce succeeds,
-- since e.g. j : Size <= Size< i if j : Size< i.
--
-- The solution is to switch off the check target first logic
-- if the target type of a (possibly empty) application is Size< _.
|
function evaluate_clustering(name, embedding_dimension, distance)
if nargin < 1
name = 'liftedstructsim_softmax_pair_m128_multilabel';
end
if nargin < 2
embedding_dimension = 64;
end
if nargin < 3
distance = 'euclidean';
end
K = 11316;
filename = sprintf('idx_kmeans_googlenet_%s_embed%d_%s.mat', name, embedding_dimension, distance);
if exist(filename, 'file')
object = load(filename);
idx = object.idx;
else
% compute similarity
load(sprintf('validation_googlenet_feat_matrix_%s_embed%d_baselr_1E4_gaussian2k.mat', ...
name, embedding_dimension), 'fc_embedding');
X = double(fc_embedding');
% kmeans clustering
fprintf('2d kmeans %d\n', K);
opts = struct('maxiters', 1000, 'mindelta', eps, 'verbose', 1);
[center, sse] = vgg_kmeans(X, K, opts);
[idx_kmeans, d] = vgg_nearest_neighbour(X, center);
% construct idx
num = size(X, 2);
idx = zeros(num, 1);
for i = 1:K
index = find(idx_kmeans == i);
[~, ind] = min(d(index));
cid = index(ind);
idx(index) = cid;
end
fprintf('Number of clusters: %d\n', length(unique(idx)));
save(sprintf('idx_kmeans_googlenet_%s_embed%d_%s.mat', name, embedding_dimension, distance), 'idx');
end
% evaluation
num_validation_classes = K;
% load ground truth from filenames
[image_ids, class_ids, superclass_ids, path_list] = ...
textread('/cvgl/group/Ebay_Dataset/Ebay_test.txt', '%d %d %d %s',...
'headerlines', 1);
num = numel(class_ids);
item_ids = cell(num,1);
for i = 1:num
class_id = class_ids(i);
item_ids{i} = num2str(class_id);
end
assert(length(unique(item_ids)) == num_validation_classes);
% Given cluster assignment and the class names
% Compute the three clustering metrics.
[NMI, RI, F1] = compute_clutering_metric(idx, item_ids);
fprintf('[method: %s, distance: %s] NMI: %.3f, RI: %.3f, F1: %.3f\n\n', ...
name, distance, NMI, RI, F1);
|
module AmbiguousName where
module A where
postulate X : Set
module B where
module A where
postulate X : Set
open A renaming (X to Y)
open B
Z = A.X
|
-- This file is auto-generated. Do not edit directly.
-- |
-- Stability: Experimental
--
-- Generic interface to Blas using unsafe foreign calls. Refer to the GHC
-- documentation for more information regarding appropriate use of safe and unsafe
-- foreign calls.
--
-- The functions here are named in a similar fashion to the original Blas interface, with
-- the type-dependent letter(s) removed. Some functions have been merged with
-- others to allow the interface to work on both real and complex numbers. If you can't a
-- particular function, try looking for its corresponding complex equivalent (e.g.
-- @symv@ is a special case of 'hemv' applied to real numbers).
--
-- Note: although complex versions of @rot@ and @rotg@ exist in many implementations,
-- they are not part of the official Blas standard and therefore not included here. If
-- you /really/ need them, submit a ticket so we can try to come up with a solution.
--
-- The documentation here is still incomplete. Consult the
-- <http://netlib.org/blas/#_blas_routines official documentation> for more
-- information.
--
-- Notation:
--
-- * @⋅@ denotes dot product (without any conjugation).
-- * @*@ denotes complex conjugation.
-- * @⊤@ denotes transpose.
-- * @†@ denotes conjugate transpose (Hermitian conjugate).
--
-- Conventions:
--
-- * All scalars are denoted with lowercase Greek letters
-- * All vectors are denoted with lowercase Latin letters and are
-- assumed to be column vectors (unless transposed).
-- * All matrices are denoted with uppercase Latin letters.
--
-- /Since: 0.1.1/
module Blas.Specialized.ComplexDouble.Unsafe (
-- * Level 1: vector-vector operations
-- ** Basic operations
swap
, scal
, copy
, axpy
, dotu
, dotc
-- ** Norm operations
, nrm2
, asum
, iamax
-- * Level 2: matrix-vector operations
-- ** Multiplication
, gemv
, gbmv
, hemv
, hbmv
, hpmv
-- ** Triangular operations
, trmv
, tbmv
, tpmv
, trsv
, tbsv
, tpsv
-- ** Rank updates
, geru
, gerc
, her
, hpr
, her2
, hpr2
-- * Level 3: matrix-matrix operations
-- ** Multiplication
, gemm
, symm
, hemm
-- ** Rank updates
, syrk
, herk
, syr2k
, her2k
-- ** Triangular operations
, trmm
, trsm
) where
import Prelude (Double, Int, IO)
import Foreign (Ptr)
import Data.Complex (Complex((:+)))
import FFI (getReturnValue)
import Blas.Primitive.Types (Order, Transpose, Uplo, Diag, Side)
import qualified Blas.Primitive.Unsafe as C
-- | Swap two vectors:
--
-- > (x, y) ← (y, x)
swap :: Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
swap = C.zswap
-- | Multiply a vector by a scalar.
--
-- > x ← α x
scal :: Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> IO ()
scal n (alpha :+ 0) = C.zdscal n alpha
scal n alpha = C.zscal n alpha
-- | Copy a vector into another vector:
--
-- > y ← x
copy :: Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
copy = C.zcopy
-- | Add a scalar-vector product to a vector.
--
-- > y ← α x + y
axpy :: Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
axpy = C.zaxpy
-- | Calculate the bilinear dot product of two vectors:
--
-- > x ⋅ y ≡ ∑[i] x[i] y[i]
dotu :: Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO (Complex Double)
dotu a b c d e = getReturnValue (C.zdotu_sub a b c d e)
-- | Calculate the sesquilinear dot product of two vectors.
--
-- > x* ⋅ y ≡ ∑[i] x[i]* y[i]
dotc :: Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO (Complex Double)
dotc a b c d e = getReturnValue (C.zdotc_sub a b c d e)
-- | Calculate the Euclidean (L²) norm of a vector:
--
-- > ‖x‖₂ ≡ √(∑[i] x[i]²)
nrm2 :: Int
-> Ptr (Complex Double)
-> Int
-> IO Double
nrm2 = C.dznrm2
-- | Calculate the Manhattan (L¹) norm, equal to the sum of the magnitudes of the elements:
--
-- > ‖x‖₁ = ∑[i] |x[i]|
asum :: Int
-> Ptr (Complex Double)
-> Int
-> IO Double
asum = C.dzasum
-- | Calculate the index of the element with the maximum magnitude (absolute value).
iamax :: Int
-> Ptr (Complex Double)
-> Int
-> IO Int
iamax = C.izamax
-- | Perform a general matrix-vector update.
--
-- > y ← α T(A) x + β y
gemv :: Order
-> Transpose
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> IO ()
gemv = C.zgemv
-- | Perform a general banded matrix-vector update.
--
-- > y ← α T(A) x + β y
gbmv :: Order
-> Transpose
-> Int
-> Int
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> IO ()
gbmv = C.zgbmv
-- | Perform a hermitian matrix-vector update.
--
-- > y ← α A x + β y
hemv :: Order
-> Uplo
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> IO ()
hemv = C.zhemv
-- | Perform a hermitian banded matrix-vector update.
--
-- > y ← α A x + β y
hbmv :: Order
-> Uplo
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> IO ()
hbmv = C.zhbmv
-- | Perform a hermitian packed matrix-vector update.
--
-- > y ← α A x + β y
hpmv :: Order
-> Uplo
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Ptr (Complex Double)
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> IO ()
hpmv = C.zhpmv
-- | Multiply a triangular matrix by a vector.
--
-- > x ← T(A) x
trmv :: Order
-> Uplo
-> Transpose
-> Diag
-> Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
trmv = C.ztrmv
-- | Multiply a triangular banded matrix by a vector.
--
-- > x ← T(A) x
tbmv :: Order
-> Uplo
-> Transpose
-> Diag
-> Int
-> Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
tbmv = C.ztbmv
-- | Multiply a triangular packed matrix by a vector.
--
-- > x ← T(A) x
tpmv :: Order
-> Uplo
-> Transpose
-> Diag
-> Int
-> Ptr (Complex Double)
-> Ptr (Complex Double)
-> Int
-> IO ()
tpmv = C.ztpmv
-- | Multiply an inverse triangular matrix by a vector.
--
-- > x ← T(A⁻¹) x
trsv :: Order
-> Uplo
-> Transpose
-> Diag
-> Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
trsv = C.ztrsv
-- | Multiply an inverse triangular banded matrix by a vector.
--
-- > x ← T(A⁻¹) x
tbsv :: Order
-> Uplo
-> Transpose
-> Diag
-> Int
-> Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
tbsv = C.ztbsv
-- | Multiply an inverse triangular packed matrix by a vector.
--
-- > x ← T(A⁻¹) x
tpsv :: Order
-> Uplo
-> Transpose
-> Diag
-> Int
-> Ptr (Complex Double)
-> Ptr (Complex Double)
-> Int
-> IO ()
tpsv = C.ztpsv
-- | Perform an unconjugated rank-1 update of a general matrix.
--
-- > A ← α x y⊤ + A
geru :: Order
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
geru = C.zgeru
-- | Perform a conjugated rank-1 update of a general matrix.
--
-- > A ← α x y† + A
gerc :: Order
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
gerc = C.zgerc
-- | Perform a rank-1 update of a Hermitian matrix.
--
-- > A ← α x y† + A
her :: Order
-> Uplo
-> Int
-> Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
her = C.zher
-- | Perform a rank-1 update of a Hermitian packed matrix.
--
-- > A ← α x y† + A
hpr :: Order
-> Uplo
-> Int
-> Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> IO ()
hpr = C.zhpr
-- | Perform a rank-2 update of a Hermitian matrix.
--
-- > A ← α x y† + y (α x)† + A
her2 :: Order
-> Uplo
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
her2 = C.zher2
-- | Perform a rank-2 update of a Hermitian packed matrix.
--
-- > A ← α x y† + y (α x)† + A
hpr2 :: Order
-> Uplo
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> IO ()
hpr2 = C.zhpr2
-- | Perform a general matrix-matrix update.
--
-- > C ← α T(A) U(B) + β C
gemm :: Order -- ^ Layout of all the matrices.
-> Transpose -- ^ The operation @T@ to be applied to @A@.
-> Transpose -- ^ The operation @U@ to be applied to @B@.
-> Int -- ^ Number of rows of @T(A)@ and @C@.
-> Int -- ^ Number of columns of @U(B)@ and @C@.
-> Int -- ^ Number of columns of @T(A)@ and number of rows of @U(B)@.
-> Complex Double -- ^ Scaling factor @α@ of the product.
-> Ptr (Complex Double) -- ^ Pointer to a matrix @A@.
-> Int -- ^ Stride of the major dimension of @A@.
-> Ptr (Complex Double) -- ^ Pointer to a matrix @B@.
-> Int -- ^ Stride of the major dimension of @B@.
-> Complex Double -- ^ Scaling factor @β@ of the original @C@.
-> Ptr (Complex Double) -- ^ Pointer to a mutable matrix @C@.
-> Int -- ^ Stride of the major dimension of @C@.
-> IO ()
gemm = C.zgemm
-- | Perform a symmetric matrix-matrix update.
--
-- > C ← α A B + β C or C ← α B A + β C
--
-- where @A@ is symmetric. The matrix @A@ must be in an unpacked format, although the
-- routine will only access half of it as specified by the @'Uplo'@ argument.
symm :: Order -- ^ Layout of all the matrices.
-> Side -- ^ Side that @A@ appears in the product.
-> Uplo -- ^ The part of @A@ that is used.
-> Int -- ^ Number of rows of @C@.
-> Int -- ^ Number of columns of @C@.
-> Complex Double -- ^ Scaling factor @α@ of the product.
-> Ptr (Complex Double) -- ^ Pointer to a symmetric matrix @A@.
-> Int -- ^ Stride of the major dimension of @A@.
-> Ptr (Complex Double) -- ^ Pointer to a matrix @B@.
-> Int -- ^ Stride of the major dimension of @B@.
-> Complex Double -- ^ Scaling factor @α@ of the original @C@.
-> Ptr (Complex Double) -- ^ Pointer to a mutable matrix @C@.
-> Int -- ^ Stride of the major dimension of @C@.
-> IO ()
symm = C.zsymm
-- | Perform a Hermitian matrix-matrix update.
--
-- > C ← α A B + β C or C ← α B A + β C
--
-- where @A@ is Hermitian. The matrix @A@ must be in an unpacked format, although the
-- routine will only access half of it as specified by the @'Uplo'@ argument.
hemm :: Order -- ^ Layout of all the matrices.
-> Side -- ^ Side that @A@ appears in the product.
-> Uplo -- ^ The part of @A@ that is used.
-> Int -- ^ Number of rows of @C@.
-> Int -- ^ Number of columns of @C@.
-> Complex Double -- ^ Scaling factor @α@ of the product.
-> Ptr (Complex Double) -- ^ Pointer to a Hermitian matrix @A@.
-> Int -- ^ Stride of the major dimension of @A@.
-> Ptr (Complex Double) -- ^ Pointer to a matrix @B@.
-> Int -- ^ Stride of the major dimension of @B@.
-> Complex Double -- ^ Scaling factor @α@ of the original @C@.
-> Ptr (Complex Double) -- ^ Pointer to a mutable matrix @C@.
-> Int -- ^ Stride of the major dimension of @C@.
-> IO ()
hemm = C.zhemm
-- | Perform a symmetric rank-k update.
--
-- > C ← α A A⊤ + β C or C ← α A⊤ A + β C
syrk :: Order
-> Uplo
-> Transpose
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> IO ()
syrk = C.zsyrk
-- | Perform a Hermitian rank-k update.
--
-- > C ← α A A† + β C or C ← α A† A + β C
herk :: Order
-> Uplo
-> Transpose
-> Int
-> Int
-> Double
-> Ptr (Complex Double)
-> Int
-> Double
-> Ptr (Complex Double)
-> Int
-> IO ()
herk = C.zherk
-- | Perform a symmetric rank-2k update.
--
-- > C ← α A B⊤ + α* B A⊤ + β C or C ← α A⊤ B + α* B⊤ A + β C
syr2k :: Order
-> Uplo
-> Transpose
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> IO ()
syr2k = C.zsyr2k
-- | Perform a Hermitian rank-2k update.
--
-- > C ← α A B† + α* B A† + β C or C ← α A† B + α* B† A + β C
her2k :: Order
-> Uplo
-> Transpose
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> Double
-> Ptr (Complex Double)
-> Int
-> IO ()
her2k = C.zher2k
-- | Perform a triangular matrix-matrix multiplication.
--
-- > B ← α T(A) B or B ← α B T(A)
--
-- where @A@ is triangular.
trmm :: Order
-> Side
-> Uplo
-> Transpose
-> Diag
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
trmm = C.ztrmm
-- | Perform an inverse triangular matrix-matrix multiplication.
--
-- > B ← α T(A⁻¹) B or B ← α B T(A⁻¹)
--
-- where @A@ is triangular.
trsm :: Order
-> Side
-> Uplo
-> Transpose
-> Diag
-> Int
-> Int
-> Complex Double
-> Ptr (Complex Double)
-> Int
-> Ptr (Complex Double)
-> Int
-> IO ()
trsm = C.ztrsm
|
Require Export euclidean__axioms.
Require Export euclidean__defs.
Require Export euclidean__tactics.
Require Export lemma__Playfairhelper2.
Require Export lemma__betweennotequal.
Require Export lemma__crisscross.
Require Export lemma__inequalitysymmetric.
Require Export lemma__parallelflip.
Require Export logic.
Definition lemma__Playfair : forall A B C D E, (euclidean__defs.Par A B C D) -> ((euclidean__defs.Par A B C E) -> (euclidean__axioms.Col C D E)).
Proof.
intro A.
intro B.
intro C.
intro D.
intro E.
intro H.
intro H0.
assert (* Cut *) (euclidean__axioms.neq A B) as H1.
- assert (exists U V u v X, (euclidean__axioms.neq A B) /\ ((euclidean__axioms.neq C E) /\ ((euclidean__axioms.Col A B U) /\ ((euclidean__axioms.Col A B V) /\ ((euclidean__axioms.neq U V) /\ ((euclidean__axioms.Col C E u) /\ ((euclidean__axioms.Col C E v) /\ ((euclidean__axioms.neq u v) /\ ((~(euclidean__defs.Meet A B C E)) /\ ((euclidean__axioms.BetS U X v) /\ (euclidean__axioms.BetS u X V))))))))))) as H1 by exact H0.
assert (exists U V u v X, (euclidean__axioms.neq A B) /\ ((euclidean__axioms.neq C E) /\ ((euclidean__axioms.Col A B U) /\ ((euclidean__axioms.Col A B V) /\ ((euclidean__axioms.neq U V) /\ ((euclidean__axioms.Col C E u) /\ ((euclidean__axioms.Col C E v) /\ ((euclidean__axioms.neq u v) /\ ((~(euclidean__defs.Meet A B C E)) /\ ((euclidean__axioms.BetS U X v) /\ (euclidean__axioms.BetS u X V))))))))))) as __TmpHyp by exact H1.
destruct __TmpHyp as [x H2].
destruct H2 as [x0 H3].
destruct H3 as [x1 H4].
destruct H4 as [x2 H5].
destruct H5 as [x3 H6].
destruct H6 as [H7 H8].
destruct H8 as [H9 H10].
destruct H10 as [H11 H12].
destruct H12 as [H13 H14].
destruct H14 as [H15 H16].
destruct H16 as [H17 H18].
destruct H18 as [H19 H20].
destruct H20 as [H21 H22].
destruct H22 as [H23 H24].
destruct H24 as [H25 H26].
assert (exists U V u v X, (euclidean__axioms.neq A B) /\ ((euclidean__axioms.neq C D) /\ ((euclidean__axioms.Col A B U) /\ ((euclidean__axioms.Col A B V) /\ ((euclidean__axioms.neq U V) /\ ((euclidean__axioms.Col C D u) /\ ((euclidean__axioms.Col C D v) /\ ((euclidean__axioms.neq u v) /\ ((~(euclidean__defs.Meet A B C D)) /\ ((euclidean__axioms.BetS U X v) /\ (euclidean__axioms.BetS u X V))))))))))) as H27 by exact H.
assert (exists U V u v X, (euclidean__axioms.neq A B) /\ ((euclidean__axioms.neq C D) /\ ((euclidean__axioms.Col A B U) /\ ((euclidean__axioms.Col A B V) /\ ((euclidean__axioms.neq U V) /\ ((euclidean__axioms.Col C D u) /\ ((euclidean__axioms.Col C D v) /\ ((euclidean__axioms.neq u v) /\ ((~(euclidean__defs.Meet A B C D)) /\ ((euclidean__axioms.BetS U X v) /\ (euclidean__axioms.BetS u X V))))))))))) as __TmpHyp0 by exact H27.
destruct __TmpHyp0 as [x4 H28].
destruct H28 as [x5 H29].
destruct H29 as [x6 H30].
destruct H30 as [x7 H31].
destruct H31 as [x8 H32].
destruct H32 as [H33 H34].
destruct H34 as [H35 H36].
destruct H36 as [H37 H38].
destruct H38 as [H39 H40].
destruct H40 as [H41 H42].
destruct H42 as [H43 H44].
destruct H44 as [H45 H46].
destruct H46 as [H47 H48].
destruct H48 as [H49 H50].
destruct H50 as [H51 H52].
exact H33.
- assert (* Cut *) (euclidean__axioms.neq C D) as H2.
-- assert (exists U V u v X, (euclidean__axioms.neq A B) /\ ((euclidean__axioms.neq C E) /\ ((euclidean__axioms.Col A B U) /\ ((euclidean__axioms.Col A B V) /\ ((euclidean__axioms.neq U V) /\ ((euclidean__axioms.Col C E u) /\ ((euclidean__axioms.Col C E v) /\ ((euclidean__axioms.neq u v) /\ ((~(euclidean__defs.Meet A B C E)) /\ ((euclidean__axioms.BetS U X v) /\ (euclidean__axioms.BetS u X V))))))))))) as H2 by exact H0.
assert (exists U V u v X, (euclidean__axioms.neq A B) /\ ((euclidean__axioms.neq C E) /\ ((euclidean__axioms.Col A B U) /\ ((euclidean__axioms.Col A B V) /\ ((euclidean__axioms.neq U V) /\ ((euclidean__axioms.Col C E u) /\ ((euclidean__axioms.Col C E v) /\ ((euclidean__axioms.neq u v) /\ ((~(euclidean__defs.Meet A B C E)) /\ ((euclidean__axioms.BetS U X v) /\ (euclidean__axioms.BetS u X V))))))))))) as __TmpHyp by exact H2.
destruct __TmpHyp as [x H3].
destruct H3 as [x0 H4].
destruct H4 as [x1 H5].
destruct H5 as [x2 H6].
destruct H6 as [x3 H7].
destruct H7 as [H8 H9].
destruct H9 as [H10 H11].
destruct H11 as [H12 H13].
destruct H13 as [H14 H15].
destruct H15 as [H16 H17].
destruct H17 as [H18 H19].
destruct H19 as [H20 H21].
destruct H21 as [H22 H23].
destruct H23 as [H24 H25].
destruct H25 as [H26 H27].
assert (exists U V u v X, (euclidean__axioms.neq A B) /\ ((euclidean__axioms.neq C D) /\ ((euclidean__axioms.Col A B U) /\ ((euclidean__axioms.Col A B V) /\ ((euclidean__axioms.neq U V) /\ ((euclidean__axioms.Col C D u) /\ ((euclidean__axioms.Col C D v) /\ ((euclidean__axioms.neq u v) /\ ((~(euclidean__defs.Meet A B C D)) /\ ((euclidean__axioms.BetS U X v) /\ (euclidean__axioms.BetS u X V))))))))))) as H28 by exact H.
assert (exists U V u v X, (euclidean__axioms.neq A B) /\ ((euclidean__axioms.neq C D) /\ ((euclidean__axioms.Col A B U) /\ ((euclidean__axioms.Col A B V) /\ ((euclidean__axioms.neq U V) /\ ((euclidean__axioms.Col C D u) /\ ((euclidean__axioms.Col C D v) /\ ((euclidean__axioms.neq u v) /\ ((~(euclidean__defs.Meet A B C D)) /\ ((euclidean__axioms.BetS U X v) /\ (euclidean__axioms.BetS u X V))))))))))) as __TmpHyp0 by exact H28.
destruct __TmpHyp0 as [x4 H29].
destruct H29 as [x5 H30].
destruct H30 as [x6 H31].
destruct H31 as [x7 H32].
destruct H32 as [x8 H33].
destruct H33 as [H34 H35].
destruct H35 as [H36 H37].
destruct H37 as [H38 H39].
destruct H39 as [H40 H41].
destruct H41 as [H42 H43].
destruct H43 as [H44 H45].
destruct H45 as [H46 H47].
destruct H47 as [H48 H49].
destruct H49 as [H50 H51].
destruct H51 as [H52 H53].
exact H36.
-- assert (* Cut *) (~(~((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)))) as H3.
--- intro H3.
assert (* Cut *) (euclidean__defs.Par A B D C) as H4.
---- assert (* Cut *) ((euclidean__defs.Par B A C D) /\ ((euclidean__defs.Par A B D C) /\ (euclidean__defs.Par B A D C))) as H4.
----- apply (@lemma__parallelflip.lemma__parallelflip A B C D H).
----- destruct H4 as [H5 H6].
destruct H6 as [H7 H8].
exact H7.
---- assert (* Cut *) (euclidean__defs.CR A C D B) as H5.
----- apply (@lemma__crisscross.lemma__crisscross A D B C H4).
------intro H5.
apply (@H3).
-------left.
exact H5.
----- assert (exists p, (euclidean__axioms.BetS A p C) /\ (euclidean__axioms.BetS D p B)) as H6 by exact H5.
destruct H6 as [p H7].
destruct H7 as [H8 H9].
assert (* Cut *) (euclidean__axioms.neq D B) as H10.
------ assert (* Cut *) ((euclidean__axioms.neq p B) /\ ((euclidean__axioms.neq D p) /\ (euclidean__axioms.neq D B))) as H10.
------- apply (@lemma__betweennotequal.lemma__betweennotequal D p B H9).
------- destruct H10 as [H11 H12].
destruct H12 as [H13 H14].
exact H14.
------ assert (* Cut *) (euclidean__axioms.neq B D) as H11.
------- apply (@lemma__inequalitysymmetric.lemma__inequalitysymmetric D B H10).
------- assert (* Cut *) (euclidean__axioms.BetS B p D) as H12.
-------- apply (@euclidean__axioms.axiom__betweennesssymmetry D p B H9).
-------- assert (* Cut *) (euclidean__defs.CR A C B D) as H13.
--------- exists p.
split.
---------- exact H8.
---------- exact H12.
--------- apply (@H3).
----------right.
exact H13.
--- assert (* Cut *) (euclidean__axioms.Col C D E) as H4.
---- assert (* Cut *) ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)) as H4.
----- apply (@euclidean__tactics.NNPP ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D))).
------intro H4.
assert (* Cut *) (False) as H5.
------- apply (@H3 H4).
------- assert (* Cut *) ((euclidean__defs.CR A D B C) -> False) as H6.
-------- intro H6.
apply (@H4).
---------left.
exact H6.
-------- assert (* Cut *) ((euclidean__defs.CR A C B D) -> False) as H7.
--------- intro H7.
apply (@H4).
----------right.
exact H7.
--------- contradiction H5.
----- assert ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)) as H5 by exact H4.
assert ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)) as __TmpHyp by exact H5.
destruct __TmpHyp as [H6|H6].
------ assert (* Cut *) (euclidean__axioms.Col C D E) as H7.
------- assert (* Cut *) ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)) as H7.
-------- apply (@euclidean__tactics.NNPP ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)) H3).
-------- apply (@euclidean__tactics.not__nCol__Col C D E).
---------intro H8.
apply (@euclidean__tactics.Col__nCol__False C D E H8).
----------apply (@lemma__Playfairhelper2.lemma__Playfairhelper2 A B C D E H H0 H6).
------- exact H7.
------ assert (exists p, (euclidean__axioms.BetS A p C) /\ (euclidean__axioms.BetS B p D)) as H7 by exact H6.
destruct H7 as [p H8].
destruct H8 as [H9 H10].
assert (* Cut *) (euclidean__defs.CR B D A C) as H11.
------- assert (* Cut *) ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)) as H11.
-------- apply (@euclidean__tactics.NNPP ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)) H3).
-------- exists p.
split.
--------- exact H10.
--------- exact H9.
------- assert (* Cut *) (euclidean__defs.Par B A C D) as H12.
-------- assert (* Cut *) ((euclidean__defs.Par B A C D) /\ ((euclidean__defs.Par A B D C) /\ (euclidean__defs.Par B A D C))) as H12.
--------- apply (@lemma__parallelflip.lemma__parallelflip A B C D H).
--------- destruct H12 as [H13 H14].
destruct H14 as [H15 H16].
exact H13.
-------- assert (* Cut *) (euclidean__defs.Par B A C E) as H13.
--------- assert (* Cut *) ((euclidean__defs.Par B A C E) /\ ((euclidean__defs.Par A B E C) /\ (euclidean__defs.Par B A E C))) as H13.
---------- apply (@lemma__parallelflip.lemma__parallelflip A B C E H0).
---------- destruct H13 as [H14 H15].
destruct H15 as [H16 H17].
exact H14.
--------- assert (* Cut *) (euclidean__axioms.Col C D E) as H14.
---------- assert (* Cut *) ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)) as H14.
----------- apply (@euclidean__tactics.NNPP ((euclidean__defs.CR A D B C) \/ (euclidean__defs.CR A C B D)) H3).
----------- apply (@euclidean__tactics.not__nCol__Col C D E).
------------intro H15.
apply (@euclidean__tactics.Col__nCol__False C D E H15).
-------------apply (@lemma__Playfairhelper2.lemma__Playfairhelper2 B A C D E H12 H13 H11).
---------- exact H14.
---- exact H4.
Qed.
|
\documentclass[a4paper,man,natbib]{apa6}
\usepackage[english]{babel}
\usepackage[cache=false]{minted}
\usemintedstyle{vs}
\usepackage{xcolor}
\definecolor{bg}{rgb}{.95,.95,.95}
\graphicspath{ {./images/} }
\usepackage{graphicx}
\usepackage{caption}
\usepackage{setspace}
%\usepackage{titlesec}
%\titleformat{\subsection}[runin]% runin puts it in the same paragraph
% {\normalfont\bfseries}% formatting commands to apply to the whole heading
% {\thesubsection}% the label and number
% {0.5em}% space between label/number and subsection title
% {}% formatting commands applied just to subsection title
% []% punctuation or other commands following subsection title
% End Packages %
\title{Advanced Statistical Methods Homework 3}
\shorttitle{DAT 530 HW2}
\author{Brandon Hosley}
\date{\today}
\affiliation{University of Illinois - Springfield}
%\abstract{}
\begin{document}
\maketitle
\singlespacing
\section{Introduction to Statistical Learning \\ Chapter : Problem }
\begin{minted}[bgcolor=bg]{r}
\end{minted}
\subsection{(a)}
\emph{ }
%\includegraphics[width=\linewidth]{}
\begin{minted}[bgcolor=bg]{r}
\end{minted}
\subsection{(b)}
\emph{ }
%\includegraphics[width=\linewidth]{}
\begin{minted}[bgcolor=bg]{r}
\end{minted}
\subsection{(c)}
\emph{ }
%\includegraphics[width=\linewidth]{}
\begin{minted}[bgcolor=bg]{r}
\end{minted}
\end{document}
|
/******************************************************************************
Prácticas de cálculo matricial de estructuras
https://github.com/ingmec-ual/practicas-calculo-matricial-estructuras
Copyright 2017 - Jose Luis Blanco Claraco <[email protected]>
University of Almeria
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
Complete BSD-3-clause License: https://opensource.org/licenses/BSD-3-Clause
******************************************************************************/
#include <Eigen/Dense> // Libreria Eigen (matrices)
#include "eigen_indexing.h" // Funcion indexing(MAT, idxs_rows, idxs_cols)
#include <iostream> // Para std::cout
int main()
{
Eigen::Matrix3d M = Eigen::Matrix3d::Identity();
std::cout << "Matriz identidad I_3:" << std::endl << M << std::endl;
// Modificamos la matriz:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
M(i, j) += i+j;
}
}
std::cout << "Matriz M:" << std::endl << M << std::endl;
std::cout << "Inversa de la matriz M:" << std::endl << M.inverse() << std::endl;
return 0; // el programa finaliza sin errores
}
|
type $RR <class {@e1 i32, @e2 f32, @e3 f64}>
type $SS <class <$RR> { &method1(agg)agg,
&method2(void)void}>
func $foo (
var %x <$SS>) i32 {
dassign %x 2 ( constval i32 32 )
virtualcall &method2(addrof ptr %x)
superclasscall &method2(addrof ptr %x)
interfacecall &method2(addrof ptr %x)
return ( dread i32 %x 2 ) }
# EXEC: %irbuild Main.mpl
# EXEC: %irbuild Main.irb.mpl
# EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
|
function rob(nums::Array{T,1}) where T
table = Dict{T,UInt64}()
function inner(nums, start, len, table)
try
return table[start]
catch end
if start == len
table[start] = nums[start]
return nums[start]
elseif start == len + 1
table[start] = 0
return 0
end
a = max(
maximum([inner(nums, x, len, table) for x in start+1:len]),
nums[start] + inner(nums, start+2, len, table)
)
table[start] = a
a
end
inner(nums, 1, length(nums), table)
end
using Test
@test rob([183, 219, 57, 193, 94, 233, 202, 154, 65, 240, 97, 234, 100, 249, 186, 66, 90, 238, 168, 128, 177, 235, 50, 81, 185, 165, 217, 207, 88, 80, 112, 78, 135, 62, 228, 247, 211]) == UInt64(3365)
@test rob([9, 297, 196, 336, 435, 2, 343, 159, 146, 359, 45, 470, 265, 131, 17, 271, 74, 242, 448, 402, 55, 423, 414, 240, 430, 135, 322, 468, 422, 351, 441, 463, 30, 399, 132, 439, 463, 260, 399, 32, 374, 383, 276, 166, 104, 315, 314, 445, 458, 422, 104, 251, 382, 230, 484, 127, 355, 332, 317, 362, 257, 493, 474, 401, 40, 93, 433, 464, 136, 342, 98, 159, 223, 110, 89, 47, 53, 179, 219, 314, 486, 301, 307, 453, 37, 366, 334, 355, 26, 484, 124, 408, 346, 133, 420, 280, 124, 210, 358, 140]) == UInt64(15632)
# use this to test time
# @time rob([9, 297, 196, 336, 435, 2, 343, 159, 146, 359, 45, 470, 265, 131, 17, 271, 74, 242, 448, 402, 55, 423, 414, 240, 430, 135, 322, 468, 422, 351, 441, 463, 30, 399, 132, 439, 463, 260, 399, 32, 374, 383, 276, 166, 104, 315, 314, 445, 458, 422, 104, 251, 382, 230, 484, 127, 355, 332, 317, 362, 257, 493, 474, 401, 40, 93, 433, 464, 136, 342, 98, 159, 223, 110, 89, 47, 53, 179, 219, 314, 486, 301, 307, 453, 37, 366, 334, 355, 26, 484, 124, 408, 346, 133, 420, 280, 124, 210, 358, 140, 9, 297, 196, 336, 435, 2, 343, 159, 146, 359, 45, 470, 265, 131, 17, 271, 74, 242, 448, 402, 55, 423, 414, 240, 430, 135, 322, 468, 422, 351, 441, 463, 30, 399, 132, 439, 463, 260, 399, 32, 374, 383, 276, 166, 104, 315, 314, 445, 458, 422, 104, 251, 382, 230, 484, 127, 355, 332, 317, 362, 257, 493, 474, 401, 40, 93, 433, 464, 136, 342, 98, 159, 223, 110, 89, 47, 53, 179, 219, 314, 486, 301, 307, 453, 37, 366, 334, 355, 26, 484, 124, 408, 346, 133, 420, 280, 124, 210, 358, 140, 9, 297, 196, 336, 435, 2, 343, 159, 146, 359, 45, 470, 265, 131, 17, 271, 74, 242, 448, 402, 55, 423, 414, 240, 430, 135, 322, 468, 422, 351, 441, 463, 30, 399, 132, 439, 463, 260, 399, 32, 374, 383, 276, 166, 104, 315, 314, 445, 458, 422, 104, 251, 382, 230, 484, 127, 355, 332, 317, 362, 257, 493, 474, 401, 40, 93, 433, 464, 136, 342, 98, 159, 223, 110, 89, 47, 53, 179, 219, 314, 486, 301, 307, 453, 37, 366, 334, 355, 26, 484, 124, 408, 346, 133, 420, 280, 124, 210, 358, 140])
|
/-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
! This file was ported from Lean 3 source module ring_theory.power_basis
! leanprover-community/mathlib commit d1d69e99ed34c95266668af4e288fc1c598b9a7f
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.FieldTheory.Minpoly.Field
/-!
# Power basis
This file defines a structure `power_basis R S`, giving a basis of the
`R`-algebra `S` as a finite list of powers `1, x, ..., x^n`.
For example, if `x` is algebraic over a ring/field, adjoining `x`
gives a `power_basis` structure generated by `x`.
## Definitions
* `power_basis R A`: a structure containing an `x` and an `n` such that
`1, x, ..., x^n` is a basis for the `R`-algebra `A` (viewed as an `R`-module).
* `finrank (hf : f ≠ 0) : finite_dimensional.finrank K (adjoin_root f) = f.nat_degree`,
the dimension of `adjoin_root f` equals the degree of `f`
* `power_basis.lift (pb : power_basis R S)`: if `y : S'` satisfies the same
equations as `pb.gen`, this is the map `S →ₐ[R] S'` sending `pb.gen` to `y`
* `power_basis.equiv`: if two power bases satisfy the same equations, they are
equivalent as algebras
## Implementation notes
Throughout this file, `R`, `S`, `A`, `B` ... are `comm_ring`s, and `K`, `L`, ... are `field`s.
`S` is an `R`-algebra, `B` is an `A`-algebra, `L` is a `K`-algebra.
## Tags
power basis, powerbasis
-/
open Polynomial
open Polynomial
variable {R S T : Type _} [CommRing R] [Ring S] [Algebra R S]
variable {A B : Type _} [CommRing A] [CommRing B] [IsDomain B] [Algebra A B]
variable {K : Type _} [Field K]
/-- `pb : power_basis R S` states that `1, pb.gen, ..., pb.gen ^ (pb.dim - 1)`
is a basis for the `R`-algebra `S` (viewed as `R`-module).
This is a structure, not a class, since the same algebra can have many power bases.
For the common case where `S` is defined by adjoining an integral element to `R`,
the canonical power basis is given by `{algebra,intermediate_field}.adjoin.power_basis`.
-/
@[nolint has_nonempty_instance]
structure PowerBasis (R S : Type _) [CommRing R] [Ring S] [Algebra R S] where
gen : S
dim : ℕ
Basis : Basis (Fin dim) R S
basis_eq_pow : ∀ i, Basis i = gen ^ (i : ℕ)
#align power_basis PowerBasis
-- this is usually not needed because of `basis_eq_pow` but can be needed in some cases;
-- in such circumstances, add it manually using `@[simps dim gen basis]`.
initialize_simps_projections PowerBasis (-Basis)
namespace PowerBasis
@[simp]
theorem coe_basis (pb : PowerBasis R S) : ⇑pb.Basis = fun i : Fin pb.dim => pb.gen ^ (i : ℕ) :=
funext pb.basis_eq_pow
#align power_basis.coe_basis PowerBasis.coe_basis
/-- Cannot be an instance because `power_basis` cannot be a class. -/
theorem finiteDimensional [Algebra K S] (pb : PowerBasis K S) : FiniteDimensional K S :=
FiniteDimensional.of_fintype_basis pb.Basis
#align power_basis.finite_dimensional PowerBasis.finiteDimensional
theorem finrank [Algebra K S] (pb : PowerBasis K S) : FiniteDimensional.finrank K S = pb.dim := by
rw [FiniteDimensional.finrank_eq_card_basis pb.basis, Fintype.card_fin]
#align power_basis.finrank PowerBasis.finrank
theorem mem_span_pow' {x y : S} {d : ℕ} :
y ∈ Submodule.span R (Set.range fun i : Fin d => x ^ (i : ℕ)) ↔
∃ f : R[X], f.degree < d ∧ y = aeval x f :=
by
have : (Set.range fun i : Fin d => x ^ (i : ℕ)) = (fun i : ℕ => x ^ i) '' ↑(Finset.range d) :=
by
ext n
simp_rw [Set.mem_range, Set.mem_image, Finset.mem_coe, Finset.mem_range]
exact ⟨fun ⟨⟨i, hi⟩, hy⟩ => ⟨i, hi, hy⟩, fun ⟨i, hi, hy⟩ => ⟨⟨i, hi⟩, hy⟩⟩
simp only [this, Finsupp.mem_span_image_iff_total, degree_lt_iff_coeff_zero,
exists_iff_exists_finsupp, coeff, aeval, eval₂_ring_hom', eval₂_eq_sum, Polynomial.sum, support,
Finsupp.mem_supported', Finsupp.total, Finsupp.sum, Algebra.smul_def, eval₂_zero, exists_prop,
LinearMap.id_coe, eval₂_one, id.def, not_lt, Finsupp.coe_lsum, LinearMap.coe_smulRight,
Finset.mem_range, AlgHom.coe_mks, Finset.mem_coe]
simp_rw [@eq_comm _ y]
exact Iff.rfl
#align power_basis.mem_span_pow' PowerBasis.mem_span_pow'
theorem mem_span_pow {x y : S} {d : ℕ} (hd : d ≠ 0) :
y ∈ Submodule.span R (Set.range fun i : Fin d => x ^ (i : ℕ)) ↔
∃ f : R[X], f.natDegree < d ∧ y = aeval x f :=
by
rw [mem_span_pow']
constructor <;>
· rintro ⟨f, h, hy⟩
refine' ⟨f, _, hy⟩
by_cases hf : f = 0
· simp only [hf, nat_degree_zero, degree_zero] at h⊢
first |exact lt_of_le_of_ne (Nat.zero_le d) hd.symm|exact WithBot.bot_lt_coe d
simpa only [degree_eq_nat_degree hf, WithBot.coe_lt_coe] using h
#align power_basis.mem_span_pow PowerBasis.mem_span_pow
theorem dim_ne_zero [h : Nontrivial S] (pb : PowerBasis R S) : pb.dim ≠ 0 := fun h =>
not_nonempty_iff.mpr (h.symm ▸ Fin.isEmpty : IsEmpty (Fin pb.dim)) pb.Basis.index_nonempty
#align power_basis.dim_ne_zero PowerBasis.dim_ne_zero
theorem dim_pos [Nontrivial S] (pb : PowerBasis R S) : 0 < pb.dim :=
Nat.pos_of_ne_zero pb.dim_ne_zero
#align power_basis.dim_pos PowerBasis.dim_pos
theorem exists_eq_aeval [Nontrivial S] (pb : PowerBasis R S) (y : S) :
∃ f : R[X], f.natDegree < pb.dim ∧ y = aeval pb.gen f :=
(mem_span_pow pb.dim_ne_zero).mp (by simpa using pb.basis.mem_span y)
#align power_basis.exists_eq_aeval PowerBasis.exists_eq_aeval
theorem exists_eq_aeval' (pb : PowerBasis R S) (y : S) : ∃ f : R[X], y = aeval pb.gen f :=
by
nontriviality S
obtain ⟨f, _, hf⟩ := exists_eq_aeval pb y
exact ⟨f, hf⟩
#align power_basis.exists_eq_aeval' PowerBasis.exists_eq_aeval'
theorem algHom_ext {S' : Type _} [Semiring S'] [Algebra R S'] (pb : PowerBasis R S)
⦃f g : S →ₐ[R] S'⦄ (h : f pb.gen = g pb.gen) : f = g :=
by
ext x
obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x
rw [← Polynomial.aeval_algHom_apply, ← Polynomial.aeval_algHom_apply, h]
#align power_basis.alg_hom_ext PowerBasis.algHom_ext
section minpoly
open BigOperators
variable [Algebra A S]
/-- `pb.minpoly_gen` is the minimal polynomial for `pb.gen`. -/
noncomputable def minpolyGen (pb : PowerBasis A S) : A[X] :=
X ^ pb.dim - ∑ i : Fin pb.dim, C (pb.Basis.repr (pb.gen ^ pb.dim) i) * X ^ (i : ℕ)
#align power_basis.minpoly_gen PowerBasis.minpolyGen
theorem aeval_minpolyGen (pb : PowerBasis A S) : aeval pb.gen (minpolyGen pb) = 0 :=
by
simp_rw [minpoly_gen, AlgHom.map_sub, AlgHom.map_sum, AlgHom.map_mul, AlgHom.map_pow, aeval_C, ←
Algebra.smul_def, aeval_X]
refine' sub_eq_zero.mpr ((pb.basis.total_repr (pb.gen ^ pb.dim)).symm.trans _)
rw [Finsupp.total_apply, Finsupp.sum_fintype] <;>
simp only [pb.coe_basis, zero_smul, eq_self_iff_true, imp_true_iff]
#align power_basis.aeval_minpoly_gen PowerBasis.aeval_minpolyGen
theorem minpolyGen_monic (pb : PowerBasis A S) : Monic (minpolyGen pb) :=
by
nontriviality A
apply (monic_X_pow _).sub_of_left _
rw [degree_X_pow]
exact degree_sum_fin_lt _
#align power_basis.minpoly_gen_monic PowerBasis.minpolyGen_monic
theorem dim_le_natDegree_of_root (pb : PowerBasis A S) {p : A[X]} (ne_zero : p ≠ 0)
(root : aeval pb.gen p = 0) : pb.dim ≤ p.natDegree :=
by
refine' le_of_not_lt fun hlt => NeZero _
rw [p.as_sum_range' _ hlt, Finset.sum_range]
refine' Fintype.sum_eq_zero _ fun i => _
simp_rw [aeval_eq_sum_range' hlt, Finset.sum_range, ← pb.basis_eq_pow] at root
have := Fintype.linearIndependent_iff.1 pb.basis.linear_independent _ root
dsimp only at this
rw [this, monomial_zero_right]
#align power_basis.dim_le_nat_degree_of_root PowerBasis.dim_le_natDegree_of_root
theorem dim_le_degree_of_root (h : PowerBasis A S) {p : A[X]} (ne_zero : p ≠ 0)
(root : aeval h.gen p = 0) : ↑h.dim ≤ p.degree :=
by
rw [degree_eq_nat_degree NeZero, WithBot.coe_le_coe]
exact h.dim_le_nat_degree_of_root NeZero root
#align power_basis.dim_le_degree_of_root PowerBasis.dim_le_degree_of_root
theorem degree_minpolyGen [Nontrivial A] (pb : PowerBasis A S) : degree (minpolyGen pb) = pb.dim :=
by
unfold minpoly_gen
rw [degree_sub_eq_left_of_degree_lt] <;> rw [degree_X_pow]
apply degree_sum_fin_lt
#align power_basis.degree_minpoly_gen PowerBasis.degree_minpolyGen
theorem natDegree_minpolyGen [Nontrivial A] (pb : PowerBasis A S) :
natDegree (minpolyGen pb) = pb.dim :=
natDegree_eq_of_degree_eq_some pb.degree_minpolyGen
#align power_basis.nat_degree_minpoly_gen PowerBasis.natDegree_minpolyGen
@[simp]
theorem minpolyGen_eq (pb : PowerBasis A S) : pb.minpolyGen = minpoly A pb.gen :=
by
nontriviality A
refine'
minpoly.unique' A _ pb.minpoly_gen_monic pb.aeval_minpoly_gen fun q hq =>
or_iff_not_imp_left.2 fun hn0 h0 => _
exact (pb.dim_le_degree_of_root hn0 h0).not_lt (pb.degree_minpoly_gen ▸ hq)
#align power_basis.minpoly_gen_eq PowerBasis.minpolyGen_eq
theorem isIntegral_gen (pb : PowerBasis A S) : IsIntegral A pb.gen :=
⟨minpolyGen pb, minpolyGen_monic pb, aeval_minpolyGen pb⟩
#align power_basis.is_integral_gen PowerBasis.isIntegral_gen
@[simp]
theorem degree_minpoly [Nontrivial A] (pb : PowerBasis A S) : degree (minpoly A pb.gen) = pb.dim :=
by rw [← minpoly_gen_eq, degree_minpoly_gen]
#align power_basis.degree_minpoly PowerBasis.degree_minpoly
@[simp]
theorem natDegree_minpoly [Nontrivial A] (pb : PowerBasis A S) :
(minpoly A pb.gen).natDegree = pb.dim := by rw [← minpoly_gen_eq, nat_degree_minpoly_gen]
#align power_basis.nat_degree_minpoly PowerBasis.natDegree_minpoly
protected theorem leftMulMatrix (pb : PowerBasis A S) :
Algebra.leftMulMatrix pb.Basis pb.gen =
Matrix.of fun i j =>
if ↑j + 1 = pb.dim then -pb.minpolyGen.coeff ↑i else if ↑i = ↑j + 1 then 1 else 0 :=
by
cases subsingleton_or_nontrivial A; · apply Subsingleton.elim
rw [Algebra.leftMulMatrix_apply, ← LinearEquiv.eq_symm_apply, LinearMap.toMatrix_symm]
refine' pb.basis.ext fun k => _
simp_rw [Matrix.toLin_self, Matrix.of_apply, pb.basis_eq_pow]
apply (pow_succ _ _).symm.trans
split_ifs with h h
· simp_rw [h, neg_smul, Finset.sum_neg_distrib, eq_neg_iff_add_eq_zero]
convert pb.aeval_minpoly_gen
rw [add_comm, aeval_eq_sum_range, Finset.sum_range_succ, ← leading_coeff,
pb.minpoly_gen_monic.leading_coeff, one_smul, nat_degree_minpoly_gen, Finset.sum_range]
· rw [Fintype.sum_eq_single (⟨↑k + 1, lt_of_le_of_ne k.2 h⟩ : Fin pb.dim), if_pos, one_smul]
· rfl
· rfl
intro x hx
rw [if_neg, zero_smul]
apply mt Fin.ext hx
#align power_basis.left_mul_matrix PowerBasis.leftMulMatrix
end minpoly
section Equiv
variable [Algebra A S] {S' : Type _} [Ring S'] [Algebra A S']
theorem constr_pow_aeval (pb : PowerBasis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0)
(f : A[X]) : pb.Basis.constr A (fun i => y ^ (i : ℕ)) (aeval pb.gen f) = aeval y f :=
by
cases subsingleton_or_nontrivial A
· rw [(Subsingleton.elim _ _ : f = 0), aeval_zero, map_zero, aeval_zero]
rw [← aeval_mod_by_monic_eq_self_of_root (minpoly.monic pb.is_integral_gen) (minpoly.aeval _ _), ←
@aeval_mod_by_monic_eq_self_of_root _ _ _ _ _ f _ (minpoly.monic pb.is_integral_gen) y hy]
by_cases hf : f %ₘ minpoly A pb.gen = 0
· simp only [hf, AlgHom.map_zero, LinearMap.map_zero]
have : (f %ₘ minpoly A pb.gen).natDegree < pb.dim :=
by
rw [← pb.nat_degree_minpoly]
apply nat_degree_lt_nat_degree hf
exact degree_mod_by_monic_lt _ (minpoly.monic pb.is_integral_gen)
rw [aeval_eq_sum_range' this, aeval_eq_sum_range' this, LinearMap.map_sum]
refine' Finset.sum_congr rfl fun i (hi : i ∈ Finset.range pb.dim) => _
rw [Finset.mem_range] at hi
rw [LinearMap.map_smul]
congr
rw [← Fin.val_mk hi, ← pb.basis_eq_pow ⟨i, hi⟩, Basis.constr_basis]
#align power_basis.constr_pow_aeval PowerBasis.constr_pow_aeval
theorem constr_pow_gen (pb : PowerBasis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) :
pb.Basis.constr A (fun i => y ^ (i : ℕ)) pb.gen = y := by
convert pb.constr_pow_aeval hy X <;> rw [aeval_X]
#align power_basis.constr_pow_gen PowerBasis.constr_pow_gen
theorem constr_pow_algebraMap (pb : PowerBasis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0)
(x : A) : pb.Basis.constr A (fun i => y ^ (i : ℕ)) (algebraMap A S x) = algebraMap A S' x := by
convert pb.constr_pow_aeval hy (C x) <;> rw [aeval_C]
#align power_basis.constr_pow_algebra_map PowerBasis.constr_pow_algebraMap
theorem constr_pow_mul (pb : PowerBasis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0)
(x x' : S) :
pb.Basis.constr A (fun i => y ^ (i : ℕ)) (x * x') =
pb.Basis.constr A (fun i => y ^ (i : ℕ)) x * pb.Basis.constr A (fun i => y ^ (i : ℕ)) x' :=
by
obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x
obtain ⟨g, rfl⟩ := pb.exists_eq_aeval' x'
simp only [← aeval_mul, pb.constr_pow_aeval hy]
#align power_basis.constr_pow_mul PowerBasis.constr_pow_mul
/-- `pb.lift y hy` is the algebra map sending `pb.gen` to `y`,
where `hy` states the higher powers of `y` are the same as the higher powers of `pb.gen`.
See `power_basis.lift_equiv` for a bundled equiv sending `⟨y, hy⟩` to the algebra map.
-/
noncomputable def lift (pb : PowerBasis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) :
S →ₐ[A] S' :=
{
pb.Basis.constr A fun i =>
y ^
(i :
ℕ) with
map_one' := by convert pb.constr_pow_algebra_map hy 1 using 2 <;> rw [RingHom.map_one]
map_zero' := by convert pb.constr_pow_algebra_map hy 0 using 2 <;> rw [RingHom.map_zero]
map_mul' := pb.constr_pow_mul hy
commutes' := pb.constr_pow_algebraMap hy }
#align power_basis.lift PowerBasis.lift
@[simp]
theorem lift_gen (pb : PowerBasis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) :
pb.lift y hy pb.gen = y :=
pb.constr_pow_gen hy
#align power_basis.lift_gen PowerBasis.lift_gen
@[simp]
theorem lift_aeval (pb : PowerBasis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) (f : A[X]) :
pb.lift y hy (aeval pb.gen f) = aeval y f :=
pb.constr_pow_aeval hy f
#align power_basis.lift_aeval PowerBasis.lift_aeval
/-- `pb.lift_equiv` states that roots of the minimal polynomial of `pb.gen` correspond to
maps sending `pb.gen` to that root.
This is the bundled equiv version of `power_basis.lift`.
If the codomain of the `alg_hom`s is an integral domain, then the roots form a multiset,
see `lift_equiv'` for the corresponding statement.
-/
@[simps]
noncomputable def liftEquiv (pb : PowerBasis A S) :
(S →ₐ[A] S') ≃ { y : S' // aeval y (minpoly A pb.gen) = 0 }
where
toFun f := ⟨f pb.gen, by rw [aeval_alg_hom_apply, minpoly.aeval, f.map_zero]⟩
invFun y := pb.lift y y.2
left_inv f := pb.algHom_ext <| lift_gen _ _ _
right_inv y := Subtype.ext <| lift_gen _ _ y.Prop
#align power_basis.lift_equiv PowerBasis.liftEquiv
/-- `pb.lift_equiv'` states that elements of the root set of the minimal
polynomial of `pb.gen` correspond to maps sending `pb.gen` to that root. -/
@[simps (config := { fullyApplied := false })]
noncomputable def liftEquiv' (pb : PowerBasis A S) :
(S →ₐ[A] B) ≃ { y : B // y ∈ ((minpoly A pb.gen).map (algebraMap A B)).roots } :=
pb.liftEquiv.trans
((Equiv.refl _).subtypeEquiv fun x =>
by
rw [mem_roots, is_root.def, Equiv.refl_apply, ← eval₂_eq_eval_map, ← aeval_def]
exact map_monic_ne_zero (minpoly.monic pb.is_integral_gen))
#align power_basis.lift_equiv' PowerBasis.liftEquiv'
/-- There are finitely many algebra homomorphisms `S →ₐ[A] B` if `S` is of the form `A[x]`
and `B` is an integral domain. -/
noncomputable def AlgHom.fintype (pb : PowerBasis A S) : Fintype (S →ₐ[A] B) :=
letI := Classical.decEq B
Fintype.ofEquiv _ pb.lift_equiv'.symm
#align power_basis.alg_hom.fintype PowerBasis.AlgHom.fintype
/-- `pb.equiv_of_root pb' h₁ h₂` is an equivalence of algebras with the same power basis,
where "the same" means that `pb` is a root of `pb'`s minimal polynomial and vice versa.
See also `power_basis.equiv_of_minpoly` which takes the hypothesis that the
minimal polynomials are identical.
-/
@[simps (config := { attrs := [] }) apply]
noncomputable def equivOfRoot (pb : PowerBasis A S) (pb' : PowerBasis A S')
(h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) :
S ≃ₐ[A] S' :=
AlgEquiv.ofAlgHom (pb.lift pb'.gen h₂) (pb'.lift pb.gen h₁)
(by
ext x
obtain ⟨f, hf, rfl⟩ := pb'.exists_eq_aeval' x
simp)
(by
ext x
obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval' x
simp)
#align power_basis.equiv_of_root PowerBasis.equivOfRoot
@[simp]
theorem equivOfRoot_aeval (pb : PowerBasis A S) (pb' : PowerBasis A S')
(h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0)
(f : A[X]) : pb.equivOfRoot pb' h₁ h₂ (aeval pb.gen f) = aeval pb'.gen f :=
pb.lift_aeval _ h₂ _
#align power_basis.equiv_of_root_aeval PowerBasis.equivOfRoot_aeval
@[simp]
theorem equivOfRoot_gen (pb : PowerBasis A S) (pb' : PowerBasis A S')
(h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) :
pb.equivOfRoot pb' h₁ h₂ pb.gen = pb'.gen :=
pb.lift_gen _ h₂
#align power_basis.equiv_of_root_gen PowerBasis.equivOfRoot_gen
@[simp]
theorem equivOfRoot_symm (pb : PowerBasis A S) (pb' : PowerBasis A S')
(h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) :
(pb.equivOfRoot pb' h₁ h₂).symm = pb'.equivOfRoot pb h₂ h₁ :=
rfl
#align power_basis.equiv_of_root_symm PowerBasis.equivOfRoot_symm
/-- `pb.equiv_of_minpoly pb' h` is an equivalence of algebras with the same power basis,
where "the same" means that they have identical minimal polynomials.
See also `power_basis.equiv_of_root` which takes the hypothesis that each generator is a root of the
other basis' minimal polynomial; `power_basis.equiv_root` is more general if `A` is not a field.
-/
@[simps (config := { attrs := [] }) apply]
noncomputable def equivOfMinpoly (pb : PowerBasis A S) (pb' : PowerBasis A S')
(h : minpoly A pb.gen = minpoly A pb'.gen) : S ≃ₐ[A] S' :=
pb.equivOfRoot pb' (h ▸ minpoly.aeval _ _) (h.symm ▸ minpoly.aeval _ _)
#align power_basis.equiv_of_minpoly PowerBasis.equivOfMinpoly
@[simp]
theorem equivOfMinpoly_aeval (pb : PowerBasis A S) (pb' : PowerBasis A S')
(h : minpoly A pb.gen = minpoly A pb'.gen) (f : A[X]) :
pb.equivOfMinpoly pb' h (aeval pb.gen f) = aeval pb'.gen f :=
pb.equivOfRoot_aeval pb' _ _ _
#align power_basis.equiv_of_minpoly_aeval PowerBasis.equivOfMinpoly_aeval
@[simp]
theorem equivOfMinpoly_gen (pb : PowerBasis A S) (pb' : PowerBasis A S')
(h : minpoly A pb.gen = minpoly A pb'.gen) : pb.equivOfMinpoly pb' h pb.gen = pb'.gen :=
pb.equivOfRoot_gen pb' _ _
#align power_basis.equiv_of_minpoly_gen PowerBasis.equivOfMinpoly_gen
@[simp]
theorem equivOfMinpoly_symm (pb : PowerBasis A S) (pb' : PowerBasis A S')
(h : minpoly A pb.gen = minpoly A pb'.gen) :
(pb.equivOfMinpoly pb' h).symm = pb'.equivOfMinpoly pb h.symm :=
rfl
#align power_basis.equiv_of_minpoly_symm PowerBasis.equivOfMinpoly_symm
end Equiv
end PowerBasis
open PowerBasis
/-- Useful lemma to show `x` generates a power basis:
the powers of `x` less than the degree of `x`'s minimal polynomial are linearly independent. -/
theorem linearIndependent_pow [Algebra K S] (x : S) :
LinearIndependent K fun i : Fin (minpoly K x).natDegree => x ^ (i : ℕ) :=
by
by_cases IsIntegral K x; swap
· rw [minpoly.eq_zero h, nat_degree_zero]
exact linearIndependent_empty_type
refine' Fintype.linearIndependent_iff.2 fun g hg i => _
simp only at hg
simp_rw [Algebra.smul_def, ← aeval_monomial, ← map_sum] at hg
apply (fun hn0 => (minpoly.degree_le_of_ne_zero K x (mt (fun h0 => _) hn0) hg).not_lt).mtr
· simp_rw [← C_mul_X_pow_eq_monomial]
exact (degree_eq_nat_degree <| minpoly.ne_zero h).symm ▸ degree_sum_fin_lt _
· apply_fun lcoeff K i at h0
simp_rw [map_sum, lcoeff_apply, coeff_monomial, Fin.val_eq_val, Finset.sum_ite_eq'] at h0
exact (if_pos <| Finset.mem_univ _).symm.trans h0
#align linear_independent_pow linearIndependent_pow
theorem IsIntegral.mem_span_pow [Nontrivial R] {x y : S} (hx : IsIntegral R x)
(hy : ∃ f : R[X], y = aeval x f) :
y ∈ Submodule.span R (Set.range fun i : Fin (minpoly R x).natDegree => x ^ (i : ℕ)) :=
by
obtain ⟨f, rfl⟩ := hy
apply mem_span_pow'.mpr _
have := minpoly.monic hx
refine' ⟨f %ₘ minpoly R x, (degree_mod_by_monic_lt _ this).trans_le degree_le_nat_degree, _⟩
conv_lhs => rw [← mod_by_monic_add_div f this]
simp only [add_zero, MulZeroClass.zero_mul, minpoly.aeval, aeval_add, AlgHom.map_mul]
#align is_integral.mem_span_pow IsIntegral.mem_span_pow
namespace PowerBasis
section Map
variable {S' : Type _} [CommRing S'] [Algebra R S']
/-- `power_basis.map pb (e : S ≃ₐ[R] S')` is the power basis for `S'` generated by `e pb.gen`. -/
@[simps dim gen Basis]
noncomputable def map (pb : PowerBasis R S) (e : S ≃ₐ[R] S') : PowerBasis R S'
where
dim := pb.dim
Basis := pb.Basis.map e.toLinearEquiv
gen := e pb.gen
basis_eq_pow i := by rw [Basis.map_apply, pb.basis_eq_pow, e.to_linear_equiv_apply, e.map_pow]
#align power_basis.map PowerBasis.map
variable [Algebra A S] [Algebra A S']
@[simp]
theorem minpolyGen_map (pb : PowerBasis A S) (e : S ≃ₐ[A] S') :
(pb.map e).minpolyGen = pb.minpolyGen :=
by
dsimp only [minpoly_gen, map_dim]
-- Turn `fin (pb.map e).dim` into `fin pb.dim`
simp only [LinearEquiv.trans_apply, map_basis, Basis.map_repr, map_gen,
AlgEquiv.toLinearEquiv_apply, e.to_linear_equiv_symm, AlgEquiv.map_pow,
AlgEquiv.symm_apply_apply, sub_right_inj]
#align power_basis.minpoly_gen_map PowerBasis.minpolyGen_map
@[simp]
theorem equivOfRoot_map (pb : PowerBasis A S) (e : S ≃ₐ[A] S') (h₁ h₂) :
pb.equivOfRoot (pb.map e) h₁ h₂ = e := by
ext x
obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x
simp [aeval_alg_equiv]
#align power_basis.equiv_of_root_map PowerBasis.equivOfRoot_map
@[simp]
theorem equivOfMinpoly_map (pb : PowerBasis A S) (e : S ≃ₐ[A] S')
(h : minpoly A pb.gen = minpoly A (pb.map e).gen) : pb.equivOfMinpoly (pb.map e) h = e :=
pb.equivOfRoot_map _ _ _
#align power_basis.equiv_of_minpoly_map PowerBasis.equivOfMinpoly_map
end Map
section Adjoin
open Algebra
theorem adjoin_gen_eq_top (B : PowerBasis R S) : adjoin R ({B.gen} : Set S) = ⊤ :=
by
rw [← to_submodule_eq_top, _root_.eq_top_iff, ← B.basis.span_eq, Submodule.span_le]
rintro x ⟨i, rfl⟩
rw [B.basis_eq_pow i]
exact Subalgebra.pow_mem _ (subset_adjoin (Set.mem_singleton _)) _
#align power_basis.adjoin_gen_eq_top PowerBasis.adjoin_gen_eq_top
theorem adjoin_eq_top_of_gen_mem_adjoin {B : PowerBasis R S} {x : S}
(hx : B.gen ∈ adjoin R ({x} : Set S)) : adjoin R ({x} : Set S) = ⊤ :=
by
rw [_root_.eq_top_iff, ← B.adjoin_gen_eq_top]
refine' adjoin_le _
simp [hx]
#align power_basis.adjoin_eq_top_of_gen_mem_adjoin PowerBasis.adjoin_eq_top_of_gen_mem_adjoin
end Adjoin
end PowerBasis
|
% prtUtilSumExp(x)
% returns log(sum(exp(x),1)) while avoiding underflow issues
%
% Notes: This only sums down, thus the sum( * , 1)
% This only accepts real doubles
% If there is a large spread between the min and max values
% some underflow is still possible. Although unlikely to
% matter in the end due to the large spread in your values.
%
% Error checking is minimal and seg faults are possible
|
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE TypeApplications #-}
module NQS.Internal.BLAS
( AXPY(..)
, COPY(..)
, DOTC(..)
, DOTU(..)
, NRM2(..)
, SCAL(..)
, GEMV(..)
, HERK(..)
, fill
, testGemv
) where
import Control.Monad.Primitive
import Control.Exception (assert)
import Data.Complex (Complex)
import Data.Proxy
import Foreign.Storable
import Foreign.Ptr
-- import Foreign.Marshal.Alloc
import Data.Semigroup((<>))
import Numerical.HBLAS.BLAS.FFI ( CBLAS_ORDERT(..)
, CBLAS_UPLOT(..)
, CBLAS_TRANSPOSET(..)
)
import Numerical.HBLAS.BLAS.FFI.Level1
import Numerical.HBLAS.BLAS.FFI.Level2
import Numerical.HBLAS.BLAS.FFI.Level3
import Numerical.HBLAS.Constants
import Numerical.HBLAS.UtilsFFI
import Data.Vector.Storable (Vector, MVector)
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Mutable as MV
import Data.Singletons
import Lens.Micro((^.))
import NQS.Internal.Types
import NQS.Internal.FFI
instance ToNative Transpose CBLAS_TRANSPOSET where
encode NoTranspose = CBLAS_TransposeT 111
encode Transpose = CBLAS_TransposeT 112
encode ConjTranspose = CBLAS_TransposeT 113
encode ConjNoTranspose = CBLAS_TransposeT 114
instance ToNative Orientation CBLAS_ORDERT where
encode Row = CBOInt 101
encode Column = CBOInt 102
instance ToNative MatUpLo CBLAS_UPLOT where
{-# INLINE encode #-}
encode MatUpper = CBlasUPLO 121
encode MatLower = CBlasUPLO 122
type ScalFun scale el m = scale -> MDenseVector 'Direct (PrimState m) el -> m ()
type AxpyFun el m = el -> MDenseVector 'Direct (PrimState m) el
-> MDenseVector 'Direct (PrimState m) el -> m ()
type DotFun el m res = MDenseVector 'Direct (PrimState m) el
-> MDenseVector 'Direct (PrimState m) el
-> m res
type CopyFun el m = MDenseVector 'Direct (PrimState m) el
-> MDenseVector 'Direct (PrimState m) el
-> m ()
type Nrm2Fun el m res = MDenseVector 'Direct (PrimState m) el -> m res
type GemvFun orient el m = Transpose
-> el -> MDenseMatrix orient (PrimState m) el
-> MDenseVector 'Direct (PrimState m) el
-> el -> MDenseVector 'Direct (PrimState m) el
-> m ()
type HerkFun scale el orient m
= MatUpLo
-> Transpose
-> scale -> MDenseMatrix orient (PrimState m) el
-> scale -> MDenseMatrix orient (PrimState m) el
-> m ()
-- | Fills a vector with a given value.
fill ::
(PrimMonad m, Storable el, COPY (MDenseVector 'Direct) el)
=> MDenseVector 'Direct (PrimState m) el -> el -> m ()
fill v x =
V.unsafeThaw (V.singleton x) >>= \t -> copy (MDenseVector (v ^. dim) 0 t) v
{-
SCAL
================
-}
class SCAL scale v el where
scal :: PrimMonad m => scale -> v (PrimState m) el -> m ()
{-# SPECIALISE scal :: PrimMonad m => ScalFun Float Float m #-}
{-# SPECIALISE scal :: PrimMonad m => ScalFun Float (Complex Float) m #-}
{-# SPECIALISE scal :: PrimMonad m => ScalFun (Complex Float) (Complex Float) m #-}
{-# SPECIALISE scal :: PrimMonad m => ScalFun Double Double m #-}
{-# SPECIALISE scal :: PrimMonad m => ScalFun Double (Complex Double) m #-}
{-# SPECIALISE scal :: PrimMonad m => ScalFun (Complex Double) (Complex Double) m #-}
scalAbstraction ::
(Storable el, PrimMonad m, Show el)
=> String
-> ScalFunFFI scale el
-> ScalFunFFI scale el
-> (scaleplain -> (scale -> m ()) -> m ())
-> ScalFun scaleplain el m
{-# NOINLINE scalAbstraction #-}
scalAbstraction scalName scalSafeFFI scalUnsafeFFI constHandler = doScal
where
shouldCallFast :: Int -> Bool
shouldCallFast !n = flopsThreshold >= fromIntegral n
doScal alpha (MDenseVector dim stride buffer)
| not (isValidVector dim stride (MV.length buffer)) = error $!
badVectorInfo scalName "X" dim stride (MV.length buffer)
| otherwise =
unsafeWithPrim buffer $ \xPtr ->
constHandler alpha $ \alphaPtr -> do
unsafePrimToPrim $!
(if shouldCallFast dim
then scalUnsafeFFI
else scalSafeFFI)
(fromIntegral dim)
alphaPtr
xPtr (fromIntegral stride)
instance SCAL Float (MDenseVector 'Direct) Float where
scal = scalAbstraction "sscal" cblas_sscal_safe cblas_sscal_unsafe (\x f -> f x)
instance SCAL Float (MDenseVector 'Direct) (Complex Float) where
scal = scalAbstraction "csscal" cblas_csscal_safe cblas_csscal_unsafe (\x f -> f x)
instance SCAL (Complex Float) (MDenseVector 'Direct) (Complex Float) where
scal = scalAbstraction "cscal" cblas_cscal_safe cblas_cscal_unsafe withRStorable_
instance SCAL Double (MDenseVector 'Direct) Double where
scal = scalAbstraction "dscal" cblas_dscal_safe cblas_dscal_unsafe (\x f -> f x)
instance SCAL Double (MDenseVector 'Direct) (Complex Double) where
scal = scalAbstraction "zdscal" cblas_zdscal_safe cblas_zdscal_unsafe (\x f -> f x)
instance SCAL (Complex Double) (MDenseVector 'Direct) (Complex Double) where
scal = scalAbstraction "zscal" cblas_zscal_safe cblas_zscal_unsafe withRStorable_
{-
AXPY
================
-}
class AXPY v el where
axpy :: PrimMonad m => el -> v (PrimState m) el -> v (PrimState m) el -> m ()
{-# SPECIALISE axpy :: PrimMonad m => AxpyFun Float m #-}
{-# SPECIALISE axpy :: PrimMonad m => AxpyFun (Complex Float) m #-}
{-# SPECIALISE axpy :: PrimMonad m => AxpyFun Double m #-}
{-# SPECIALISE axpy :: PrimMonad m => AxpyFun (Complex Double) m #-}
axpyAbstraction ::
(PrimMonad m, Storable el, Show el)
=> String
-> AxpyFunFFI scale el
-> AxpyFunFFI scale el
-> (el -> (scale -> m ()) -> m ())
-> AxpyFun el m
{-# NOINLINE axpyAbstraction #-}
axpyAbstraction axpyName axpySafeFFI axpyUnsafeFFI constHandler = doAxpy
where
shouldCallFast :: Int -> Bool
shouldCallFast !n = flopsThreshold >= 2 * (fromIntegral n) -- n for a*x, and n for +y
doAxpy alpha (MDenseVector xDim xStride xBuff)
(MDenseVector yDim yStride yBuff)
| not (isValidVector xDim xStride (MV.length xBuff)) = error $!
badVectorInfo axpyName "X" xDim xStride (MV.length xBuff)
| not (isValidVector yDim yStride (MV.length yBuff)) = error $!
badVectorInfo axpyName "Y" yDim yStride (MV.length yBuff)
| xDim /= yDim = error $! axpyName <> ": Inconsistent dimensions: " <>
show xDim <> " != " <> show yDim <> "."
| otherwise =
unsafeWithPrim xBuff $ \xPtr ->
unsafeWithPrim yBuff $ \yPtr ->
constHandler alpha $ \alphaPtr -> do
unsafePrimToPrim $!
(if shouldCallFast xDim
then axpyUnsafeFFI
else axpySafeFFI)
(fromIntegral xDim)
alphaPtr
xPtr (fromIntegral xStride)
yPtr (fromIntegral yStride)
instance AXPY (MDenseVector 'Direct) Float where
axpy = axpyAbstraction "saxpy" cblas_saxpy_safe cblas_saxpy_unsafe (\x f -> f x)
instance AXPY (MDenseVector 'Direct) Double where
axpy = axpyAbstraction "daxpy" cblas_daxpy_safe cblas_daxpy_unsafe (\x f -> f x)
instance AXPY (MDenseVector 'Direct) (Complex Float) where
axpy = axpyAbstraction "caxpy" cblas_caxpy_safe cblas_caxpy_unsafe withRStorable_
instance AXPY (MDenseVector 'Direct) (Complex Double) where
axpy = axpyAbstraction "zaxpy" cblas_zaxpy_safe cblas_zaxpy_unsafe withRStorable_
{-
CDOT
================
-}
class DOTU v el res where
dotu :: PrimMonad m => v (PrimState m) el -> v (PrimState m) el -> m res
{-# SPECIALISE dotu :: PrimMonad m => DotFun Float m Float #-}
{-# SPECIALISE dotu :: PrimMonad m => DotFun Float m Double #-}
{-# SPECIALISE dotu :: PrimMonad m => DotFun Double m Double #-}
{-# SPECIALISE dotu :: PrimMonad m => DotFun (Complex Float) m (Complex Float) #-}
{-# SPECIALISE dotu :: PrimMonad m => DotFun (Complex Double) m (Complex Double) #-}
class DOTC v el res where
dotc :: PrimMonad m => v (PrimState m) el -> v (PrimState m) el -> m res
{-# SPECIALISE dotc :: PrimMonad m => DotFun Float m Float #-}
{-# SPECIALISE dotc :: PrimMonad m => DotFun Float m Double #-}
{-# SPECIALISE dotc :: PrimMonad m => DotFun Double m Double #-}
{-# SPECIALISE dotc :: PrimMonad m => DotFun (Complex Float) m (Complex Float) #-}
{-# SPECIALISE dotc :: PrimMonad m => DotFun (Complex Double) m (Complex Double) #-}
realDotAbstraction ::
(PrimMonad m, Storable el, Num el, Show el)
=> String
-> NoScalarDotFunFFI el res
-> NoScalarDotFunFFI el res
-> DotFun el m res
{-# NOINLINE realDotAbstraction #-}
realDotAbstraction dotName dotSafeFFI dotUnsafeFFI = doDot
where
shouldCallFast :: Int -> Bool
shouldCallFast n = flopsThreshold >= fromIntegral n
doDot (MDenseVector xDim xStride xBuff)
(MDenseVector yDim yStride yBuff)
| not (isValidVector xDim xStride (MV.length xBuff)) = error $!
badVectorInfo dotName "X" xDim xStride (MV.length xBuff)
| not (isValidVector yDim yStride (MV.length yBuff)) = error $!
badVectorInfo dotName "Y" yDim yStride (MV.length yBuff)
| xDim /= yDim = error $! dotName <> ": Inconsistent dimensions: " <>
show xDim <> " != " <> show yDim <> "."
| otherwise =
unsafeWithPrim xBuff $ \xPtr ->
unsafeWithPrim yBuff $ \yPtr ->
unsafePrimToPrim $!
(if shouldCallFast xDim
then dotUnsafeFFI
else dotSafeFFI)
(fromIntegral xDim)
xPtr (fromIntegral xStride)
yPtr (fromIntegral yStride)
complexDotAbstraction ::
(PrimMonad m, Storable el, Num el, Show el)
=> String
-> ComplexDotFunFFI el
-> ComplexDotFunFFI el
-> DotFun el m el
{-# NOINLINE complexDotAbstraction #-}
complexDotAbstraction dotName dotSafeFFI dotUnsafeFFI = doDot
where
shouldCallFast :: Int -> Bool
shouldCallFast n = flopsThreshold >= fromIntegral n
doDot (MDenseVector xDim xStride xBuff)
(MDenseVector yDim yStride yBuff)
| not (isValidVector xDim xStride (MV.length xBuff)) = error $!
badVectorInfo dotName "X" xDim xStride (MV.length xBuff)
| not (isValidVector yDim yStride (MV.length yBuff)) = error $!
badVectorInfo dotName "Y" yDim yStride (MV.length yBuff)
| xDim /= yDim = error $! dotName <> ": Inconsistent dimensions: " <>
show xDim <> " != " <> show yDim <> "."
| otherwise =
unsafeWithPrim xBuff $ \xPtr ->
unsafeWithPrim yBuff $ \yPtr ->
unsafePrimToPrim $!
alloca $ \outPtr -> do
poke outPtr 0
(if shouldCallFast xDim
then dotUnsafeFFI
else dotSafeFFI)
(fromIntegral xDim)
xPtr (fromIntegral xStride)
yPtr (fromIntegral yStride)
outPtr
peek outPtr
instance DOTC (MDenseVector 'Direct) Float Float where
dotc = realDotAbstraction "sdot" cblas_sdot_safe cblas_sdot_unsafe
instance DOTC (MDenseVector 'Direct) Double Double where
dotc = realDotAbstraction "ddot" cblas_ddot_safe cblas_ddot_unsafe
instance DOTC (MDenseVector 'Direct) Float Double where
dotc = realDotAbstraction "dsdot" cblas_dsdot_safe cblas_dsdot_unsafe
instance DOTC (MDenseVector 'Direct) (Complex Float) (Complex Float) where
dotc = complexDotAbstraction "cdotc" cblas_cdotc_safe cblas_cdotc_unsafe
instance DOTC (MDenseVector 'Direct) (Complex Double) (Complex Double) where
dotc = complexDotAbstraction "zdotc" cblas_zdotc_safe cblas_zdotc_unsafe
instance DOTU (MDenseVector 'Direct) Float Float where
dotu = realDotAbstraction "sdot" cblas_sdot_safe cblas_sdot_unsafe
instance DOTU (MDenseVector 'Direct) Double Double where
dotu = realDotAbstraction "ddot" cblas_ddot_safe cblas_ddot_unsafe
instance DOTU (MDenseVector 'Direct) Float Double where
dotu = realDotAbstraction "dsdot" cblas_dsdot_safe cblas_dsdot_unsafe
instance DOTU (MDenseVector 'Direct) (Complex Float) (Complex Float) where
dotu = complexDotAbstraction "cdotu" cblas_cdotu_safe cblas_cdotu_unsafe
instance DOTU (MDenseVector 'Direct) (Complex Double) (Complex Double) where
dotu = complexDotAbstraction "zdotu" cblas_zdotu_safe cblas_zdotu_unsafe
class COPY v el where
copy :: PrimMonad m => v (PrimState m) el -> v (PrimState m) el -> m ()
{-# SPECIALISE copy :: PrimMonad m => CopyFun Float m #-}
{-# SPECIALISE copy :: PrimMonad m => CopyFun Double m #-}
{-# SPECIALISE copy :: PrimMonad m => CopyFun (Complex Float) m #-}
{-# SPECIALISE copy :: PrimMonad m => CopyFun (Complex Double) m #-}
copyAbstraction ::
(PrimMonad m, Storable el, Num el, Show el)
=> String
-> CopyFunFFI el
-> CopyFunFFI el
-> CopyFun el m
{-# NOINLINE copyAbstraction #-}
copyAbstraction copyName copySafeFFI copyUnsafeFFI = doCopy
where
shouldCallFast :: Int -> Bool
shouldCallFast _ = True
doCopy (MDenseVector xDim xStride xBuff)
(MDenseVector yDim yStride yBuff)
| not (isValidVector xDim xStride (MV.length xBuff)) = error $!
badVectorInfo copyName "X" xDim xStride (MV.length xBuff)
| not (isValidVector yDim yStride (MV.length yBuff)) = error $!
badVectorInfo copyName "Y" yDim yStride (MV.length yBuff)
| xDim /= yDim = error $! copyName <> ": Inconsistent dimensions: " <>
show xDim <> " != " <> show yDim <> "."
| otherwise =
unsafeWithPrim xBuff $ \xPtr ->
unsafeWithPrim yBuff $ \yPtr ->
unsafePrimToPrim $!
(if shouldCallFast xDim
then copyUnsafeFFI
else copySafeFFI)
(fromIntegral xDim)
xPtr (fromIntegral xStride)
yPtr (fromIntegral yStride)
instance COPY (MDenseVector 'Direct) Float where
copy = copyAbstraction "scopy" cblas_scopy_safe cblas_scopy_unsafe
instance COPY (MDenseVector 'Direct) Double where
copy = copyAbstraction "dcopy" cblas_dcopy_safe cblas_dcopy_unsafe
instance COPY (MDenseVector 'Direct) (Complex Float) where
copy = copyAbstraction "ccopy" cblas_ccopy_safe cblas_ccopy_unsafe
instance COPY (MDenseVector 'Direct) (Complex Double) where
copy = copyAbstraction "zcopy" cblas_zcopy_safe cblas_zcopy_unsafe
class NRM2 v el res | v el -> res where
nrm2 :: PrimMonad m => v (PrimState m) el -> m res
{-# SPECIALISE nrm2 :: PrimMonad m => Nrm2Fun Float m Float #-}
{-# SPECIALISE nrm2 :: PrimMonad m => Nrm2Fun Double m Double #-}
{-# SPECIALISE nrm2 :: PrimMonad m => Nrm2Fun (Complex Float) m Float #-}
{-# SPECIALISE nrm2 :: PrimMonad m => Nrm2Fun (Complex Double) m Double #-}
nrm2Abstraction ::
(PrimMonad m, Storable el, Num el, Show el)
=> String
-> Nrm2FunFFI el res
-> Nrm2FunFFI el res
-> Nrm2Fun el m res
{-# NOINLINE nrm2Abstraction #-}
nrm2Abstraction nrm2Name nrm2SafeFFI nrm2UnsafeFFI = doNrm2
where
shouldCallFast :: Int -> Bool
shouldCallFast n = fromIntegral n <= flopsThreshold
doNrm2 (MDenseVector xDim xStride xBuff)
| not (isValidVector xDim xStride (MV.length xBuff)) = error $!
badVectorInfo nrm2Name "X" xDim xStride (MV.length xBuff)
| otherwise =
unsafeWithPrim xBuff $ \xPtr ->
unsafePrimToPrim $!
(if shouldCallFast xDim
then nrm2UnsafeFFI
else nrm2SafeFFI) (fromIntegral xDim) xPtr (fromIntegral xStride)
instance NRM2 (MDenseVector 'Direct) Float Float where
nrm2 = nrm2Abstraction "snrm2" cblas_snrm2_safe cblas_snrm2_unsafe
instance NRM2 (MDenseVector 'Direct) Double Double where
nrm2 = nrm2Abstraction "dnrm2" cblas_dnrm2_safe cblas_dnrm2_unsafe
instance NRM2 (MDenseVector 'Direct) (Complex Float) Float where
nrm2 = nrm2Abstraction "scnrm2" cblas_scnrm2_safe cblas_scnrm2_unsafe
instance NRM2 (MDenseVector 'Direct) (Complex Double) Double where
nrm2 = nrm2Abstraction "dznrm2" cblas_dznrm2_safe cblas_dznrm2_unsafe
class GEMV mat v el where
gemv :: PrimMonad m
=> Transpose
-> el -> mat (PrimState m) el -> v (PrimState m) el
-> el -> v (PrimState m) el -> m ()
gemvAbstraction :: forall m el scale orient.
(PrimMonad m, Storable el, Show el, SingI orient)
=> String
-> GemvFunFFI scale el
-> GemvFunFFI scale el
-> (el -> (scale -> m ()) -> m ())
-> GemvFun orient el m
{-# NOINLINE gemvAbstraction #-}
gemvAbstraction gemvName gemvSafeFFI gemvUnsafeFFI constHandler = doGemv
where
shouldCallFast :: Int -> Int -> Bool
shouldCallFast !n !m = flopsThreshold >= (fromIntegral n) * (fromIntegral m)
doGemv trans alpha a@(MDenseMatrix aRows aCols aStride aBuff)
x@(MDenseVector xDim xStride xBuff)
beta y@(MDenseVector yDim yStride yBuff) =
assertValid gemvName "A" a $
assertValid gemvName "X" x $
assertValid gemvName "Y" y $
unsafeWithPrim aBuff $ \aPtr ->
unsafeWithPrim xBuff $ \xPtr ->
unsafeWithPrim yBuff $ \yPtr ->
constHandler alpha $ \alphaPtr ->
constHandler beta $ \betaPtr ->
do
unsafePrimToPrim $!
(if shouldCallFast xDim yDim then gemvUnsafeFFI else gemvSafeFFI)
(encode (orientationOf a)) (encode trans)
(fromIntegral aRows) (fromIntegral aCols)
alphaPtr
aPtr (fromIntegral aStride)
xPtr (fromIntegral xStride)
betaPtr
yPtr (fromIntegral yStride)
instance SingI orient =>
GEMV (Mutable (DenseMatrix orient)) (MDenseVector 'Direct) Float where
gemv = gemvAbstraction "sgemv" cblas_sgemv_safe cblas_sgemv_unsafe (\x f -> f x)
instance SingI orient =>
GEMV (Mutable (DenseMatrix orient)) (MDenseVector 'Direct) Double where
gemv = gemvAbstraction "dgemv" cblas_dgemv_safe cblas_dgemv_unsafe (\x f -> f x)
instance SingI orient =>
GEMV (Mutable (DenseMatrix orient)) (MDenseVector 'Direct) (Complex Float) where
gemv = gemvAbstraction "cgemv" cblas_cgemv_safe cblas_cgemv_unsafe withRStorable_
instance SingI orient =>
GEMV (Mutable (DenseMatrix orient)) (MDenseVector 'Direct) (Complex Double) where
gemv = gemvAbstraction "zgemv" cblas_zgemv_safe cblas_zgemv_unsafe withRStorable_
testGemv :: IO ()
testGemv = do
aBuff <- newVectorAligned 12 64 :: IO (MV.IOVector Double)
V.copy aBuff (V.fromList [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
let a = MDenseMatrix @'Row 4 3 3 aBuff
print (orientationOf a)
xBuff <- newVectorAligned 4 64 :: IO (MV.IOVector Double)
V.copy xBuff (V.fromList [1, 2, 3, 4])
let x = MDenseVector @'Direct 3 1 xBuff
yBuff <- newVectorAligned 3 64 :: IO (MV.IOVector Double)
-- V.copy yBuff (V.fromList [1, 2, 3])
let y = MDenseVector @'Direct 3 1 yBuff
gemv Transpose 1.0 a x 0.0 y
print =<< V.unsafeFreeze yBuff
class HERK mat scale el where
herk :: PrimMonad m
=> MatUpLo -> Transpose
-> scale -> mat (PrimState m) el
-> scale -> mat (PrimState m) el
-> m ()
herkAbstraction
:: forall m el scale scalePtr. (Storable el, PrimMonad m)
=> String
-> HerkFunFFI scalePtr el
-> HerkFunFFI scalePtr el
-> (scale -> (scalePtr -> m ()) -> m ())
-> (forall orient . SingI orient => HerkFun scale el orient m)
{-# NOINLINE herkAbstraction #-}
herkAbstraction herkName herkSafeFFI herkUnsafeFFI constHandler = doHerk
where
isBadHerk :: Transpose -> Int -> Int -> Int -> Int -> Bool
isBadHerk NoTranspose ax ay cx cy = (ax /= cx)
isBadHerk ConjTranspose ax ay cx cy = (ay /= cx)
isBadHerk trans _ _ _ _ =
error $! herkName <> ": trans " <> show trans <> " is not supported."
doHerk :: forall orient. (SingI orient) => HerkFun scale el orient m
doHerk uplo trans alpha a@(MDenseMatrix ax ay astride abuff) beta c@(MDenseMatrix cx cy cstride cbuff)
| cx /= cy = error $!
herkName <> ": C must be a square matrix, but has dimensions " <> show (cx, cy) <> "."
| isBadHerk trans ax ay cx cy = error $!
herkName <> ": Incompatible dimensions: ax ay cx cy trans: " <> show [ax, ay, cx, cy]
<> " " <> show trans
| MV.overlaps abuff cbuff = error $! herkName <> ": Input and output buffers overlap."
| otherwise =
withMatrixFFI a $ \layout aRows aCols aPtr aStride ->
withMatrixFFI c $ \_ cRows _ cPtr cStride ->
constHandler alpha $ \alphaPtr ->
constHandler beta $ \betaPtr ->
let k = if (trans == NoTranspose) then aCols else aRows
in unsafePrimToPrim $!
herkSafeFFI ((encode . fromSing) (sing :: Sing orient))
(encode uplo)
(encode trans)
cRows
k
alphaPtr
aPtr
aStride
betaPtr
cPtr
cStride
instance SingI orient => HERK (Mutable (DenseMatrix orient)) Float (Complex Float) where
herk = herkAbstraction "cherk" cblas_cherk_safe cblas_cherk_unsafe (\x f -> f x)
instance SingI orient => HERK (Mutable (DenseMatrix orient)) Double (Complex Double) where
herk = herkAbstraction "zherk" cblas_zherk_safe cblas_zherk_unsafe (\x f -> f x)
|
/-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.WF
import Init.Data.Nat.Basic
namespace Nat
private def div_rec_lemma {x y : Nat} : 0 < y ∧ y ≤ x → x - y < x :=
fun ⟨ypos, ylex⟩ => sub_lt (Nat.lt_of_lt_of_le ypos ylex) ypos
private def div.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat :=
if h : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma h) y + 1 else zero
@[extern "lean_nat_div"]
protected def div (a b : @& Nat) : Nat :=
WellFounded.fix (measure id).wf div.F a b
instance : Div Nat := ⟨Nat.div⟩
private theorem div_eq_aux (x y : Nat) : x / y = if h : 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 :=
congrFun (WellFounded.fix_eq (measure id).wf div.F x) y
theorem div_eq (x y : Nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 :=
dif_eq_if (0 < y ∧ y ≤ x) ((x - y) / y + 1) 0 ▸ div_eq_aux x y
private theorem div.induction.F.{u}
(C : Nat → Nat → Sort u)
(ind : ∀ x y, 0 < y ∧ y ≤ x → C (x - y) y → C x y)
(base : ∀ x y, ¬(0 < y ∧ y ≤ x) → C x y)
(x : Nat) (f : ∀ (x₁ : Nat), x₁ < x → ∀ (y : Nat), C x₁ y) (y : Nat) : C x y :=
if h : 0 < y ∧ y ≤ x then ind x y h (f (x - y) (div_rec_lemma h) y) else base x y h
theorem div.inductionOn.{u}
{motive : Nat → Nat → Sort u}
(x y : Nat)
(ind : ∀ x y, 0 < y ∧ y ≤ x → motive (x - y) y → motive x y)
(base : ∀ x y, ¬(0 < y ∧ y ≤ x) → motive x y)
: motive x y :=
WellFounded.fix (measure id).wf (div.induction.F motive ind base) x y
private def mod.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat :=
if h : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma h) y else x
@[extern "lean_nat_mod"]
protected def mod (a b : @& Nat) : Nat :=
WellFounded.fix (measure id).wf mod.F a b
instance : Mod Nat := ⟨Nat.mod⟩
private theorem mod_eq_aux (x y : Nat) : x % y = if h : 0 < y ∧ y ≤ x then (x - y) % y else x :=
congrFun (WellFounded.fix_eq (measure id).wf mod.F x) y
theorem mod_eq (x y : Nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x :=
dif_eq_if (0 < y ∧ y ≤ x) ((x - y) % y) x ▸ mod_eq_aux x y
theorem mod.inductionOn.{u}
{motive : Nat → Nat → Sort u}
(x y : Nat)
(ind : ∀ x y, 0 < y ∧ y ≤ x → motive (x - y) y → motive x y)
(base : ∀ x y, ¬(0 < y ∧ y ≤ x) → motive x y)
: motive x y :=
div.inductionOn x y ind base
theorem mod_zero (a : Nat) : a % 0 = a :=
have : (if 0 < 0 ∧ 0 ≤ a then (a - 0) % 0 else a) = a :=
have h : ¬ (0 < 0 ∧ 0 ≤ a) := fun ⟨h₁, _⟩ => absurd h₁ (Nat.lt_irrefl _)
if_neg h
(mod_eq a 0).symm ▸ this
theorem mod_eq_of_lt {a b : Nat} (h : a < b) : a % b = a :=
have : (if 0 < b ∧ b ≤ a then (a - b) % b else a) = a :=
have h' : ¬(0 < b ∧ b ≤ a) := fun ⟨_, h₁⟩ => absurd h₁ (Nat.not_le_of_gt h)
if_neg h'
(mod_eq a b).symm ▸ this
theorem mod_eq_sub_mod {a b : Nat} (h : a ≥ b) : a % b = (a - b) % b :=
match eq_zero_or_pos b with
| Or.inl h₁ => h₁.symm ▸ (Nat.sub_zero a).symm ▸ rfl
| Or.inr h₁ => (mod_eq a b).symm ▸ if_pos ⟨h₁, h⟩
theorem mod_lt (x : Nat) {y : Nat} : y > 0 → x % y < y := by
induction x, y using mod.inductionOn with
| base x y h₁ =>
intro h₂
have h₁ : ¬ 0 < y ∨ ¬ y ≤ x := Iff.mp (Decidable.not_and_iff_or_not _ _) h₁
match h₁ with
| Or.inl h₁ => exact absurd h₂ h₁
| Or.inr h₁ =>
have hgt : y > x := gt_of_not_le h₁
have heq : x % y = x := mod_eq_of_lt hgt
rw [← heq] at hgt
exact hgt
| ind x y h h₂ =>
intro h₃
have ⟨_, h₁⟩ := h
rw [mod_eq_sub_mod h₁]
exact h₂ h₃
theorem mod_le (x y : Nat) : x % y ≤ x := by
match Nat.lt_or_ge x y with
| Or.inl h₁ => rw [mod_eq_of_lt h₁]; apply Nat.le_refl
| Or.inr h₁ => match eq_zero_or_pos y with
| Or.inl h₂ => rw [h₂, Nat.mod_zero x]; apply Nat.le_refl
| Or.inr h₂ => exact Nat.le_trans (Nat.le_of_lt (mod_lt _ h₂)) h₁
@[simp] theorem zero_mod (b : Nat) : 0 % b = 0 := by
rw [mod_eq]
have : ¬ (0 < b ∧ b ≤ 0) := by
intro ⟨h₁, h₂⟩
exact absurd (Nat.lt_of_lt_of_le h₁ h₂) (Nat.lt_irrefl 0)
simp [this]
@[simp] theorem mod_self (n : Nat) : n % n = 0 := by
rw [mod_eq_sub_mod (Nat.le_refl _), Nat.sub_self, zero_mod]
theorem mod_one (x : Nat) : x % 1 = 0 := by
have h : x % 1 < 1 := mod_lt x (by decide)
have : (y : Nat) → y < 1 → y = 0 := by
intro y
cases y with
| zero => intro h; rfl
| succ y => intro h; apply absurd (Nat.lt_of_succ_lt_succ h) (Nat.not_lt_zero y)
exact this _ h
end Nat
|
\chapter*{Conclusion}
\addcontentsline{toc}{chapter}{Conclusion}
To conclude our thesis, we will revisit the goals we set in the introduction chapter in section \ref{chap:intro:goals}
\begin{enumerate}
\item \textit{Implement SPICE-like simulation library }
\begin{enumerate}
\item \textit{Target .NET Standard for maximum portability} -- Our library requires .NET Standard 2.0, which makes it available on all major platforms running one of the newer version of .NET runtime.
\item \textit{Support performing time-domain simulation of the circuit, and allow changing parameters of circuit devices between individual timesteps.} -- We designed our simulator in such a way that users of our library decide when next circuit state is computed and how big the timestep should be. Between the individual timesteps, users can modify parameters of the devices in the simulated circuit, and have the changes affect the next calculated circuit state.
\item \textit{Support following set of devices
\begin{enumerate}
\item Ideal resistor
\item Ideal voltage source
\item Ideal current source
\item Ideal inductor
\item Ideal capacitor
\item SPICE diode
\item SPICE BJT transistor
\end{enumerate}}
We successfully implemented all circuit devices listed above. In addition, we also implemented linear controlled sources: voltage controlled voltage source, voltage controlled current source, current controlled voltage source and current controlled current source.
\item \textit{Allow new types of circuit analyses and circuit devices to be added to the simulator without modifying the library's source code.} -- We have written a guide on how to add new devices in library's user documentation in chapter \ref{chap:exteding} and provided an example of adding new device in section \ref{chap:userdocs:diode-tutorial}.
\item \textit{Implement SPICE netlist parser to allow importing circuits and macromodels from standard SPICE netlist files.} -- Our parser supports sufficient subset of the SPICE3 netlist syntax to allow importing circuits and subcircuits (macromodels) containing devices implemented in our simulator. We have tested our parser on existing SPICE netlists with success. However, because the parser implementation present in the library implements only the data statements (devices, subcircuits and device models), it is necessary to remove any control statements from the netlist file before parsing them in NextGen SPICE.
\item \textit{Allow users of the library to choose between double, double-double, and quad-double precision types and compare the library's performance with respect to speed and accuracy for each listed precision type.} -- Users can compile our library themselves and choose the precision type to be used by defining a certain conditional compilation symbol. We compared the simulator performance for each precision type and found out that the double-double type currently provides the best combination of convergence and simulation speed for our library.
\end{enumerate}
\item \textit{Use the simulation library to implement SPICE-like console application for .NET Core, which would accept implemented subset of SPICE netlist syntax.} -- Our \texttt{NextGenSpice} application targets .NET Core 2.0 and provides the desired functionality by extending the library's parser to handle \texttt{.TRAN} \texttt{.OP} and \texttt{.PRINT} statements. We then used the library's functionality to run the simulations and print the requested data to standard output.
\end{enumerate}
\subsubsection{Future Work}
The NextGen SPICE library offers only a narrow subset of the SPICE-like simulators used today. Following list contains features which we consider most beneficial for the next version of the library.
\begin{itemize}
\item \textit{Sparse matrix representation} -- As discussed in the \ref{chap:results-precision}, the Gauss-Jordan elimination and full matrix representation proved to be a performance bottleneck when simulating larger circuits. Using sparse matrix methods which are used by the standard SPICE implementations would significantly speed up the simulation.
\item \textit{Dynamic timestep} -- Current implementation of the transient analysis algorithm relies on the user to choose a fixed timestep. As discussed in the analysis \ref{chap:analysis-timestep}, dynamic timestep mechanism can speedup simulation in regions where the capacitor charges and inductor fluxes do not change quickly.
\item \textit{Implementing \texttt{.INCLUDE} statement} -- Currently all used models and subcircuits need to be defined in the netlist file. SPICE3's \texttt{.INCLUDE} statement works similarly to the \texttt{\#include} directive in C or C++ languages: the contents of the included file are treated as if they were copied and pasted in place of the \texttt{.INCLUDE} statement. This allows better reuse of the subcircuits and defined models.
\item \textit{Interactive console application} -- Current \texttt{NextGenSpice} console application offers limited interaction with the user. Also, when the user wants to run the same simulation with different parameters, the netlist file must be edited and the application run again. SPICE3 introduced an interactive mode, in which the program reads only the circuit description from the netlist file. The simulation statements and other control statements are then supplied on the standard input by the user.
\item \textit{More devices and analysis types} -- Last but not least, the NextGen SPICE library as implemented in this thesis offers only a fraction of circuit analysis types and circuit devices. Examples of devices which are completely missing are switches (voltage and current controlled), other types of transistors (JFET, MOSFET), transmission lines, coupled inductors and semiconductor versions of resistor and capacitor devices. From the analysis types, the NextGenSpice library is missing e.g. the AC frequency sweep analysis, which requires small-signal models of the simulated devices.
\end{itemize}
|
header{* Pseudo-Hoops *}
theory PseudoHoops
imports RightComplementedMonoid
begin
lemma drop_assumption:
"p \<Longrightarrow> True"
by simp
class pseudo_hoop_algebra = left_complemented_monoid_algebra + right_complemented_monoid_nole_algebra +
assumes left_right_impl_times: "(a l\<rightarrow> b) * a = a * (a r\<rightarrow> b)"
begin
definition
"inf_rr a b = a * (a r\<rightarrow> b)"
definition
"lesseq_r a b = (a r\<rightarrow> b = 1)"
definition
"less_r a b = (lesseq_r a b \<and> \<not> lesseq_r b a)"
end
(*
sublocale pseudo_hoop_algebra < right!: right_complemented_monoid_algebra lesseq_r less_r 1 "op *" inf_rr "op r\<rightarrow>";
apply unfold_locales;
apply simp_all;
apply (simp add: less_r_def);
apply (simp add: inf_rr_def);
apply (rule right_impl_times, rule right_impl_ded);
by (simp add: lesseq_r_def);
*)
context pseudo_hoop_algebra begin
lemma inf_rr_inf [simp]: "inf_rr = op \<sqinter>"
by (unfold fun_eq_iff, simp add: inf_rr_def inf_l_def left_right_impl_times)
lemma lesseq_lesseq_r: "lesseq_r a b = (a \<le> b)"
proof -
interpret A!: right_complemented_monoid_algebra lesseq_r less_r 1 "op *" inf_rr "op r\<rightarrow>"
by (rule right_complemented_monoid_algebra)
(*
find_theorems name: le_iff_inf
thm A.dual_algebra.le_iff_inf
have "\<And>x y. lesseq_r x y = (inf_rr x y = x)" by fact
note `\<And>x y. lesseq_r x y = (inf_rr x y = x)`
*)
show "lesseq_r a b = (a \<le> b)"
apply (subst le_iff_inf)
apply (subst `lesseq_r a b = (inf_rr a b = a)`)
apply (unfold inf_rr_inf [THEN sym])
by simp
qed
lemma [simp]: "less_r = op <"
by (unfold fun_eq_iff, simp add: less_r_def less_le_not_le)
subclass right_complemented_monoid_algebra
apply (cut_tac right_complemented_monoid_algebra)
by simp
end
sublocale pseudo_hoop_algebra <
pseudo_hoop_dual!: pseudo_hoop_algebra "\<lambda> a b . b * a" "op \<sqinter>" "op r\<rightarrow>" "op \<le>" "op <" 1 "op l\<rightarrow>"
apply unfold_locales
apply (simp add: inf_l_def)
apply simp
apply (simp add: left_impl_times)
apply (simp add: left_impl_ded)
by (simp add: left_right_impl_times)
context pseudo_hoop_algebra begin
lemma commutative_ps: "(\<forall> a b . a * b = b * a) = ((op l\<rightarrow>) = (op r\<rightarrow>))"
apply (simp add: fun_eq_iff)
apply safe
apply (rule antisym)
apply (simp add: right_residual [THEN sym])
apply (subgoal_tac "x * (x l\<rightarrow> xa) = (x l\<rightarrow> xa) * x")
apply (drule drop_assumption)
apply simp
apply (simp add: left_residual)
apply simp
apply (simp add: left_residual [THEN sym])
apply (simp add: right_residual)
apply (rule antisym)
apply (simp add: left_residual)
apply (simp add: right_residual [THEN sym])
apply (simp add: left_residual)
by (simp add: right_residual [THEN sym])
lemma lemma_2_4_5: "a l\<rightarrow> b \<le> (c l\<rightarrow> a) l\<rightarrow> (c l\<rightarrow> b)"
apply (simp add: left_residual [THEN sym] mult.assoc)
apply (rule_tac y = "(a l\<rightarrow> b) * a" in order_trans)
apply (rule mult_left_mono)
by (simp_all add: left_residual)
end
context pseudo_hoop_algebra begin
lemma lemma_2_4_6: "a r\<rightarrow> b \<le> (c r\<rightarrow> a) r\<rightarrow> (c r\<rightarrow> b)"
by (rule pseudo_hoop_dual.lemma_2_4_5)
primrec
imp_power_l:: "'a => nat \<Rightarrow> 'a \<Rightarrow> 'a" ("(_) l-(_)\<rightarrow> (_)" [65,0,65] 65) where
"a l-0\<rightarrow> b = b" |
"a l-(Suc n)\<rightarrow> b = (a l\<rightarrow> (a l-n\<rightarrow> b))"
primrec
imp_power_r:: "'a => nat \<Rightarrow> 'a \<Rightarrow> 'a" ("(_) r-(_)\<rightarrow> (_)" [65,0,65] 65) where
"a r-0\<rightarrow> b = b" |
"a r-(Suc n)\<rightarrow> b = (a r\<rightarrow> (a r-n\<rightarrow> b))"
lemma lemma_2_4_7_a: "a l-n\<rightarrow> b = a ^ n l\<rightarrow> b"
apply (induct_tac n)
by (simp_all add: left_impl_ded)
lemma lemma_2_4_7_b: "a r-n\<rightarrow> b = a ^ n r\<rightarrow> b"
apply (induct_tac n)
by (simp_all add: right_impl_ded [THEN sym] power_commutes)
lemma lemma_2_5_8_a [simp]: "a * b \<le> a"
by (rule dual_algebra.H)
lemma lemma_2_5_8_b [simp]: "a * b \<le> b"
by (rule H)
lemma lemma_2_5_9_a: "a \<le> b l\<rightarrow> a"
by (simp add: left_residual [THEN sym] dual_algebra.H)
lemma lemma_2_5_9_b: "a \<le> b r\<rightarrow> a"
by (simp add: right_residual [THEN sym] H)
lemma lemma_2_5_11: "a * b \<le> a \<sqinter> b"
by simp
lemma lemma_2_5_12_a: "a \<le> b \<Longrightarrow> c l\<rightarrow> a \<le> c l\<rightarrow> b"
apply (subst left_residual [THEN sym])
apply (subst left_impl_times)
apply (rule_tac y = "(a l\<rightarrow> c) * b" in order_trans)
apply (simp add: mult_left_mono)
by (rule H)
lemma lemma_2_5_13_a: "a \<le> b \<Longrightarrow> b l\<rightarrow> c \<le> a l\<rightarrow> c"
apply (simp add: left_residual [THEN sym])
apply (rule_tac y = "(b l\<rightarrow> c) * b" in order_trans)
apply (simp add: mult_left_mono)
by (simp add: left_residual)
lemma lemma_2_5_14: "(b l\<rightarrow> c) * (a l\<rightarrow> b) \<le> a l\<rightarrow> c"
apply (simp add: left_residual [THEN sym])
apply (simp add: mult.assoc)
apply (subst left_impl_times)
apply (subst mult.assoc [THEN sym])
apply (subst left_residual)
by (rule dual_algebra.H)
lemma lemma_2_5_16: "(a l\<rightarrow> b) \<le> (b l\<rightarrow> c) r\<rightarrow> (a l\<rightarrow> c)"
apply (simp add: right_residual [THEN sym])
by (rule lemma_2_5_14)
lemma lemma_2_5_18: "(a l\<rightarrow> b) \<le> a * c l\<rightarrow> b * c"
apply (simp add: left_residual [THEN sym])
apply (subst mult.assoc [THEN sym])
apply (rule mult_right_mono)
apply (subst left_impl_times)
by (rule H)
end
context pseudo_hoop_algebra begin
lemma lemma_2_5_12_b: "a \<le> b \<Longrightarrow> c r\<rightarrow> a \<le> c r\<rightarrow> b"
by (rule pseudo_hoop_dual.lemma_2_5_12_a)
lemma lemma_2_5_13_b: "a \<le> b \<Longrightarrow> b r\<rightarrow> c \<le> a r\<rightarrow> c"
by (rule pseudo_hoop_dual.lemma_2_5_13_a)
lemma lemma_2_5_15: "(a r\<rightarrow> b) * (b r\<rightarrow> c) \<le> a r\<rightarrow> c"
by (rule pseudo_hoop_dual.lemma_2_5_14)
lemma lemma_2_5_17: "(a r\<rightarrow> b) \<le> (b r\<rightarrow> c) l\<rightarrow> (a r\<rightarrow> c)"
by (rule pseudo_hoop_dual.lemma_2_5_16)
lemma lemma_2_5_19: "(a r\<rightarrow> b) \<le> c * a r\<rightarrow> c * b"
by (rule pseudo_hoop_dual.lemma_2_5_18)
definition
"lower_bound A = {a . \<forall> x \<in> A . a \<le> x}"
definition
"infimum A = {a \<in> lower_bound A . (\<forall> x \<in> lower_bound A . x \<le> a)}"
lemma infimum_unique: "(infimum A = {x}) = (x \<in> infimum A)"
apply safe
apply simp
apply (rule antisym)
by (simp_all add: infimum_def)
lemma lemma_2_6_20:
"a \<in> infimum A \<Longrightarrow> b l\<rightarrow> a \<in> infimum ((op l\<rightarrow> b)`A)"
apply (subst infimum_def)
apply safe
apply (simp add: infimum_def lower_bound_def lemma_2_5_12_a)
by (simp add: infimum_def lower_bound_def left_residual [THEN sym])
end
context pseudo_hoop_algebra begin
lemma lemma_2_6_21:
"a \<in> infimum A \<Longrightarrow> b r\<rightarrow> a \<in> infimum ((op r\<rightarrow> b)`A)"
by (rule pseudo_hoop_dual.lemma_2_6_20)
lemma infimum_pair: "a \<in> infimum {x . x = b \<or> x = c} = (a = b \<sqinter> c)"
apply (simp add: infimum_def lower_bound_def)
apply safe
apply (rule antisym)
by simp_all
lemma lemma_2_6_20_a:
"a l\<rightarrow> (b \<sqinter> c) = (a l\<rightarrow> b) \<sqinter> (a l\<rightarrow> c)"
apply (subgoal_tac "b \<sqinter> c \<in> infimum {x . x = b \<or> x = c}")
apply (drule_tac b = a in lemma_2_6_20)
apply (case_tac "(op l\<rightarrow> a) ` {x . ((x = b) \<or> (x = c))} = {x . x = a l\<rightarrow> b \<or> x = a l\<rightarrow> c}")
apply (simp_all add: infimum_pair)
by auto
end
context pseudo_hoop_algebra begin
lemma lemma_2_6_21_a:
"a r\<rightarrow> (b \<sqinter> c) = (a r\<rightarrow> b) \<sqinter> (a r\<rightarrow> c)"
by (rule pseudo_hoop_dual.lemma_2_6_20_a)
lemma mult_mono: "a \<le> b \<Longrightarrow> c \<le> d \<Longrightarrow> a * c \<le> b * d"
apply (rule_tac y = "a * d" in order_trans)
by (simp_all add: mult_right_mono mult_left_mono)
lemma lemma_2_7_22: "(a l\<rightarrow> b) * (c l\<rightarrow> d) \<le> (a \<sqinter> c) l\<rightarrow> (b \<sqinter> d)"
apply (rule_tac y = "(a \<sqinter> c l\<rightarrow> b) * (a \<sqinter> c l\<rightarrow> d)" in order_trans)
apply (rule mult_mono)
apply (simp_all add: lemma_2_5_13_a)
apply (rule_tac y = "(a \<sqinter> c l\<rightarrow> b) \<sqinter> (a \<sqinter> c l\<rightarrow> d)" in order_trans)
apply (rule lemma_2_5_11)
by (simp add: lemma_2_6_20_a)
end
context pseudo_hoop_algebra begin
lemma lemma_2_7_23: "(a r\<rightarrow> b) * (c r\<rightarrow> d) \<le> (a \<sqinter> c) r\<rightarrow> (b \<sqinter> d)"
apply (rule_tac y = "(c \<sqinter> a) r\<rightarrow> (d \<sqinter> b)" in order_trans)
apply (rule pseudo_hoop_dual.lemma_2_7_22)
by (simp add: inf_commute)
definition
"upper_bound A = {a . \<forall> x \<in> A . x \<le> a}"
definition
"supremum A = {a \<in> upper_bound A . (\<forall> x \<in> upper_bound A . a \<le> x)}"
lemma supremum_unique:
"a \<in> supremum A \<Longrightarrow> b \<in> supremum A \<Longrightarrow> a = b"
apply (simp add: supremum_def upper_bound_def)
apply (rule antisym)
by auto
lemma lemma_2_8_i:
"a \<in> supremum A \<Longrightarrow> a l\<rightarrow> b \<in> infimum ((\<lambda> x . x l\<rightarrow> b)`A)"
apply (subst infimum_def)
apply safe
apply (simp add: supremum_def upper_bound_def lower_bound_def lemma_2_5_13_a)
apply (simp add: supremum_def upper_bound_def lower_bound_def left_residual [THEN sym])
by (simp add: right_residual)
end
context pseudo_hoop_algebra begin
lemma lemma_2_8_i1:
"a \<in> supremum A \<Longrightarrow> a r\<rightarrow> b \<in> infimum ((\<lambda> x . x r\<rightarrow> b)`A)"
by (rule pseudo_hoop_dual.lemma_2_8_i, simp)
definition
times_set :: "'a set \<Rightarrow> 'a set \<Rightarrow> 'a set" (infixl "**" 70) where
"(A ** B) = {a . \<exists> x \<in> A . \<exists> y \<in> B . a = x * y}"
lemma times_set_assoc: "A ** (B ** C) = (A ** B) ** C"
apply (simp add: times_set_def)
apply safe
apply (rule_tac x = "xa * xb" in exI)
apply safe
apply (rule_tac x = xa in bexI)
apply (rule_tac x = xb in bexI)
apply simp_all
apply (subst mult.assoc)
apply (rule_tac x = ya in bexI)
apply simp_all
apply (rule_tac x = xb in bexI)
apply simp_all
apply (rule_tac x = "ya * y" in exI)
apply (subst mult.assoc)
apply simp
by auto
primrec power_set :: "'a set \<Rightarrow> nat \<Rightarrow> 'a set" (infixr "*^" 80) where
power_set_0: "(A *^ 0) = {1}"
| power_set_Suc: "(A *^ (Suc n)) = (A ** (A *^ n))"
lemma infimum_singleton [simp]: "infimum {a} = {a}"
apply (simp add: infimum_def lower_bound_def)
by auto
lemma lemma_2_8_ii:
"a \<in> supremum A \<Longrightarrow> (a ^ n) l\<rightarrow> b \<in> infimum ((\<lambda> x . x l\<rightarrow> b)`(A *^ n))"
apply (induct_tac n)
apply simp
apply (simp add: left_impl_ded)
apply (drule_tac a = "a ^ n l\<rightarrow> b" and b = a in lemma_2_6_20)
apply (simp add: infimum_def lower_bound_def times_set_def)
apply safe
apply (drule_tac b = "y l\<rightarrow> b" in lemma_2_8_i)
apply (simp add: infimum_def lower_bound_def times_set_def left_impl_ded)
apply (rule_tac y = "a l\<rightarrow> y l\<rightarrow> b" in order_trans)
apply simp_all
apply (subgoal_tac "(\<forall>xa \<in> A *^ n. x \<le> a l\<rightarrow> xa l\<rightarrow> b)")
apply simp
apply safe
apply (drule_tac b = "xa l\<rightarrow> b" in lemma_2_8_i)
apply (simp add: infimum_def lower_bound_def)
apply safe
apply (subgoal_tac "(\<forall>xb \<in> A. x \<le> xb l\<rightarrow> xa l\<rightarrow> b)")
apply simp
apply safe
apply (subgoal_tac "x \<le> xb * xa l\<rightarrow> b")
apply (simp add: left_impl_ded)
apply (subgoal_tac "(\<exists>x \<in> A. \<exists>y \<in> A *^ n. xb * xa = x * y)")
by auto
lemma power_set_Suc2:
"A *^ (Suc n) = A *^ n ** A"
apply (induct_tac n)
apply (simp add: times_set_def)
apply simp
apply (subst times_set_assoc)
by simp
lemma power_set_add:
"A *^ (n + m) = (A *^ n) ** (A *^ m)"
apply (induct_tac m)
apply simp
apply (simp add: times_set_def)
apply simp
apply (subst times_set_assoc)
apply (subst times_set_assoc)
apply (subst power_set_Suc2 [THEN sym])
by simp
end
context pseudo_hoop_algebra begin
lemma lemma_2_8_ii1:
"a \<in> supremum A \<Longrightarrow> (a ^ n) r\<rightarrow> b \<in> infimum ((\<lambda> x . x r\<rightarrow> b)`(A *^ n))"
apply (induct_tac n)
apply simp
apply (subst power_Suc2)
apply (subst power_set_Suc2)
apply (simp add: right_impl_ded)
apply (drule_tac a = "a ^ n r\<rightarrow> b" and b = a in lemma_2_6_21)
apply (simp add: infimum_def lower_bound_def times_set_def)
apply safe
apply (drule_tac b = "xa r\<rightarrow> b" in lemma_2_8_i1)
apply (simp add: infimum_def lower_bound_def times_set_def right_impl_ded)
apply (rule_tac y = "a r\<rightarrow> xa r\<rightarrow> b" in order_trans)
apply simp_all
apply (subgoal_tac "(\<forall>xa \<in> A *^ n. x \<le> a r\<rightarrow> xa r\<rightarrow> b)")
apply simp
apply safe
apply (drule_tac b = "xa r\<rightarrow> b" in lemma_2_8_i1)
apply (simp add: infimum_def lower_bound_def)
apply safe
apply (subgoal_tac "(\<forall>xb \<in> A. x \<le> xb r\<rightarrow> xa r\<rightarrow> b)")
apply simp
apply safe
apply (subgoal_tac "x \<le> xa * xb r\<rightarrow> b")
apply (simp add: right_impl_ded)
apply (subgoal_tac "(\<exists>x \<in> A *^ n. \<exists>y \<in> A . xa * xb = x * y)")
by auto
lemma lemma_2_9_i:
"b \<in> supremum A \<Longrightarrow> a * b \<in> supremum (op * a ` A)"
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (simp add: mult_left_mono)
by (simp add: right_residual)
lemma lemma_2_9_i1:
"b \<in> supremum A \<Longrightarrow> b * a \<in> supremum ((\<lambda> x . x * a) ` A)"
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (simp add: mult_right_mono)
by (simp add: left_residual)
lemma lemma_2_9_ii:
"b \<in> supremum A \<Longrightarrow> a \<sqinter> b \<in> supremum (op \<sqinter> a ` A)"
apply (subst supremum_def)
apply safe
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (rule_tac y = x in order_trans)
apply simp_all
apply (subst inf_commute)
apply (subst inf_l_def)
apply (subst left_right_impl_times)
apply (frule_tac a = "(b r\<rightarrow> a)" in lemma_2_9_i1)
apply (simp add: right_residual)
apply (simp add: supremum_def upper_bound_def)
apply (simp add: right_residual)
apply safe
apply (subgoal_tac "(\<forall>xa \<in> A. b r\<rightarrow> a \<le> xa r\<rightarrow> x)")
apply simp
apply safe
apply (simp add: inf_l_def)
apply (simp add: left_right_impl_times)
apply (rule_tac y = "xa r\<rightarrow> b * (b r\<rightarrow> a)" in order_trans)
apply simp
apply (rule lemma_2_5_12_b)
apply (subst left_residual)
apply (subgoal_tac "(\<forall>xa\<in>A. xa \<le> (b r\<rightarrow> a) l\<rightarrow> x)")
apply simp
apply safe
apply (subst left_residual [THEN sym])
apply (rule_tac y = "xaa * (xaa r\<rightarrow> a)" in order_trans)
apply (rule mult_left_mono)
apply (rule lemma_2_5_13_b)
apply simp
apply (subst right_impl_times)
by simp
lemma lemma_2_10_24:
"a \<le> (a l\<rightarrow> b) r\<rightarrow> b"
by (simp add: right_residual [THEN sym] inf_l_def [THEN sym])
lemma lemma_2_10_25:
"a \<le> (a l\<rightarrow> b) r\<rightarrow> a"
by (rule lemma_2_5_9_b)
end
context pseudo_hoop_algebra begin
lemma lemma_2_10_26:
"a \<le> (a r\<rightarrow> b) l\<rightarrow> b"
by (rule pseudo_hoop_dual.lemma_2_10_24)
lemma lemma_2_10_27:
"a \<le> (a r\<rightarrow> b) l\<rightarrow> a"
by (rule lemma_2_5_9_a)
lemma lemma_2_10_28:
"b l\<rightarrow> ((a l\<rightarrow> b) r\<rightarrow> a) = b l\<rightarrow> a"
apply (rule antisym)
apply (subst left_residual [THEN sym])
apply (rule_tac y = "((a l\<rightarrow> b) r\<rightarrow> a) \<sqinter> a" in order_trans)
apply (subst inf_l_def)
apply (rule_tac y = "(((a l\<rightarrow> b) r\<rightarrow> a) l\<rightarrow> b) * ((a l\<rightarrow> b) r\<rightarrow> a)" in order_trans)
apply (subst left_impl_times)
apply simp_all
apply (rule mult_right_mono)
apply (rule_tac y = "a l\<rightarrow> b" in order_trans)
apply (rule lemma_2_5_13_a)
apply (fact lemma_2_10_25)
apply (fact lemma_2_10_26)
apply (rule lemma_2_5_12_a)
by (fact lemma_2_10_25)
end
context pseudo_hoop_algebra begin
lemma lemma_2_10_29:
"b r\<rightarrow> ((a r\<rightarrow> b) l\<rightarrow> a) = b r\<rightarrow> a"
by (rule pseudo_hoop_dual.lemma_2_10_28)
lemma lemma_2_10_30:
"((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> a = b l\<rightarrow> a"
apply (rule antisym)
apply (simp_all add: lemma_2_10_26)
apply (rule lemma_2_5_13_a)
by (rule lemma_2_10_24)
end
context pseudo_hoop_algebra begin
lemma lemma_2_10_31:
"((b r\<rightarrow> a) l\<rightarrow> a) r\<rightarrow> a = b r\<rightarrow> a"
by (rule pseudo_hoop_dual.lemma_2_10_30)
lemma lemma_2_10_32:
"(((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> b) l\<rightarrow> (b l\<rightarrow> a) = b l\<rightarrow> a"
proof -
have "((((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> b) l\<rightarrow> (b l\<rightarrow> a) = (((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> b) l\<rightarrow> (((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> a))"
by (simp add: lemma_2_10_30)
also have "\<dots> = ((((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> b) * ((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> a)"
by (simp add: left_impl_ded)
also have "\<dots> = (((b l\<rightarrow> a) r\<rightarrow> a) \<sqinter> b) l\<rightarrow> a"
by (simp add: inf_l_def)
also have "\<dots> = b l\<rightarrow> a" apply (subgoal_tac "((b l\<rightarrow> a) r\<rightarrow> a) \<sqinter> b = b", simp, rule antisym)
by (simp_all add: lemma_2_10_24)
finally show ?thesis .
qed
end
context pseudo_hoop_algebra begin
lemma lemma_2_10_33:
"(((b r\<rightarrow> a) l\<rightarrow> a) r\<rightarrow> b) r\<rightarrow> (b r\<rightarrow> a) = b r\<rightarrow> a"
by (rule pseudo_hoop_dual.lemma_2_10_32)
end
class pseudo_hoop_sup_algebra = pseudo_hoop_algebra + sup +
assumes
sup_comute: "a \<squnion> b = b \<squnion> a"
and sup_le [simp]: "a \<le> a \<squnion> b"
and le_sup_equiv: "(a \<le> b) = (a \<squnion> b = b)"
begin
lemma sup_le_2 [simp]:
"b \<le> a \<squnion> b"
by (subst sup_comute, simp)
lemma le_sup_equiv_r:
"(a \<squnion> b = b) = (a \<le> b)"
by (simp add: le_sup_equiv)
lemma sup_idemp [simp]:
"a \<squnion> a = a"
by (simp add: le_sup_equiv_r)
end
class pseudo_hoop_sup1_algebra = pseudo_hoop_algebra + sup +
assumes
sup_def: "a \<squnion> b = ((a l\<rightarrow> b) r\<rightarrow> b) \<sqinter> ((b l\<rightarrow> a) r\<rightarrow> a)"
begin
lemma sup_comute1: "a \<squnion> b = b \<squnion> a"
apply (simp add: sup_def)
apply (rule antisym)
by simp_all
lemma sup_le1 [simp]: "a \<le> a \<squnion> b"
by (simp add: sup_def lemma_2_10_24 lemma_2_5_9_b)
lemma le_sup_equiv1: "(a \<le> b) = (a \<squnion> b = b)"
apply safe
apply (simp add: left_lesseq)
apply (rule antisym)
apply (simp add: sup_def)
apply (simp add: sup_def)
apply (simp_all add: lemma_2_10_24)
apply (simp add: le_iff_inf)
apply (subgoal_tac "(a \<sqinter> b = a \<sqinter> (a \<squnion> b)) \<and> (a \<sqinter> (a \<squnion> b) = a)")
apply simp
apply safe
apply simp
apply (rule antisym)
apply simp
apply (drule drop_assumption)
by (simp add: sup_comute1)
subclass pseudo_hoop_sup_algebra
apply unfold_locales
apply (simp add: sup_comute1)
apply simp
by (simp add: le_sup_equiv1)
end
class pseudo_hoop_sup2_algebra = pseudo_hoop_algebra + sup +
assumes
sup_2_def: "a \<squnion> b = ((a r\<rightarrow> b) l\<rightarrow> b) \<sqinter> ((b r\<rightarrow> a) l\<rightarrow> a)"
context pseudo_hoop_sup1_algebra begin end
sublocale pseudo_hoop_sup2_algebra < sup1_dual!: pseudo_hoop_sup1_algebra "op \<squnion>" "\<lambda> a b . b * a" "op \<sqinter>" "op r\<rightarrow>" "op \<le>" "op <" 1 "op l\<rightarrow>"
apply unfold_locales
by (simp add: sup_2_def)
context pseudo_hoop_sup2_algebra begin
lemma sup_comute_2: "a \<squnion> b = b \<squnion> a"
by (rule sup1_dual.sup_comute)
lemma sup_le2 [simp]: "a \<le> a \<squnion> b"
by (rule sup1_dual.sup_le)
lemma le_sup_equiv2: "(a \<le> b) = (a \<squnion> b = b)"
by (rule sup1_dual.le_sup_equiv)
subclass pseudo_hoop_sup_algebra
apply unfold_locales
apply (simp add: sup_comute_2)
apply simp
by (simp add: le_sup_equiv2)
end
class pseudo_hoop_lattice_a = pseudo_hoop_sup_algebra +
assumes sup_inf_le_distr: "a \<squnion> (b \<sqinter> c) \<le> (a \<squnion> b) \<sqinter> (a \<squnion> c)"
begin
lemma sup_lower_upper_bound [simp]:
"a \<le> c \<Longrightarrow> b \<le> c \<Longrightarrow> a \<squnion> b \<le> c"
apply (subst le_iff_inf)
apply (subgoal_tac "(a \<squnion> b) \<sqinter> c = (a \<squnion> b) \<sqinter> (a \<squnion> c) \<and> a \<squnion> (b \<sqinter> c) \<le> (a \<squnion> b) \<sqinter> (a \<squnion> c) \<and> a \<squnion> (b \<sqinter> c) = a \<squnion> b")
apply (rule antisym)
apply simp
apply safe
apply auto[1]
apply (simp add: le_sup_equiv)
apply (rule sup_inf_le_distr)
by (simp add: le_iff_inf)
end
sublocale pseudo_hoop_lattice_a < lattice "op \<sqinter>" "op \<le>" "op <" "op \<squnion>"
by (unfold_locales, simp_all)
class pseudo_hoop_lattice_b = pseudo_hoop_sup_algebra +
assumes le_sup_cong: "a \<le> b \<Longrightarrow> a \<squnion> c \<le> b \<squnion> c"
begin
lemma sup_lower_upper_bound_b [simp]:
"a \<le> c \<Longrightarrow> b \<le> c \<Longrightarrow> a \<squnion> b \<le> c"
proof -
assume A: "a \<le> c"
assume B: "b \<le> c"
have "a \<squnion> b \<le> c \<squnion> b" by (cut_tac A, simp add: le_sup_cong)
also have "\<dots> = b \<squnion> c" by (simp add: sup_comute)
also have "\<dots> \<le> c \<squnion> c" by (cut_tac B, rule le_sup_cong, simp)
also have "\<dots> = c" by simp
finally show ?thesis .
qed
lemma sup_inf_le_distr_b:
"a \<squnion> (b \<sqinter> c) \<le> (a \<squnion> b) \<sqinter> (a \<squnion> c)"
apply (rule sup_lower_upper_bound_b)
apply simp
apply simp
apply safe
apply (subst sup_comute)
apply (rule_tac y = "b" in order_trans)
apply simp_all
apply (rule_tac y = "c" in order_trans)
by simp_all
end
context pseudo_hoop_lattice_a begin end
sublocale pseudo_hoop_lattice_b < pseudo_hoop_lattice_a "op \<squnion>" "op *" "op \<sqinter>" "op l\<rightarrow>" "op \<le>" "op <" 1 "op r\<rightarrow>"
by (unfold_locales, rule sup_inf_le_distr_b)
class pseudo_hoop_lattice = pseudo_hoop_sup_algebra +
assumes sup_assoc_1: "a \<squnion> (b \<squnion> c) = (a \<squnion> b) \<squnion> c"
begin
lemma le_sup_cong_c:
"a \<le> b \<Longrightarrow> a \<squnion> c \<le> b \<squnion> c"
proof -
assume A: "a \<le> b"
have "a \<squnion> c \<squnion> (b \<squnion> c) = a \<squnion> (c \<squnion> (b \<squnion> c))" by (simp add: sup_assoc_1)
also have "\<dots> = a \<squnion> ((b \<squnion> c) \<squnion> c)" by (simp add: sup_comute)
also have "\<dots> = a \<squnion> (b \<squnion> (c \<squnion> c))" by (simp add: sup_assoc_1 [THEN sym])
also have "\<dots> = (a \<squnion> b) \<squnion> c" by (simp add: sup_assoc_1)
also have "\<dots> = b \<squnion> c" by (cut_tac A, simp add: le_sup_equiv)
finally show ?thesis by (simp add: le_sup_equiv)
qed
end
sublocale pseudo_hoop_lattice < pseudo_hoop_lattice_b "op \<squnion>" "op *" "op \<sqinter>" "op l\<rightarrow>" "op \<le>" "op <" 1 "op r\<rightarrow>"
by (unfold_locales, rule le_sup_cong_c)
sublocale pseudo_hoop_lattice < semilattice_sup "op \<squnion>" "op \<le>" "op <"
by (unfold_locales, simp_all)
sublocale pseudo_hoop_lattice < lattice "op \<sqinter>" "op \<le>" "op <" "op \<squnion>"
by unfold_locales
lemma (in pseudo_hoop_lattice_a) supremum_pair [simp]:
"supremum {a, b} = {a \<squnion> b}"
apply (simp add: supremum_def upper_bound_def)
apply safe
apply simp_all
apply (rule antisym)
by simp_all
sublocale pseudo_hoop_lattice < distrib_lattice "op \<sqinter>" "op \<le>" "op <" "op \<squnion>"
apply unfold_locales
apply (rule distrib_imp1)
apply (case_tac "xa \<sqinter> (ya \<squnion> za) \<in> supremum (op \<sqinter> xa ` {ya, za})")
apply (simp add: supremum_pair)
apply (erule notE)
apply (rule lemma_2_9_ii)
by (simp add: supremum_pair)
class bounded_semilattice_inf_top = semilattice_inf + order_top
begin
lemma inf_eq_top_iff [simp]:
"(inf x y = top) = (x = top \<and> y = top)"
by (simp add: eq_iff)
end
sublocale pseudo_hoop_algebra < bounded_semilattice_inf_top "op \<sqinter>" "op \<le>" "op <" "1"
by unfold_locales simp
definition (in pseudo_hoop_algebra)
sup1::"'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "\<squnion>1" 70) where
"a \<squnion>1 b = ((a l\<rightarrow> b) r\<rightarrow> b) \<sqinter> ((b l\<rightarrow> a) r\<rightarrow> a)"
sublocale pseudo_hoop_algebra < sup1!: pseudo_hoop_sup1_algebra "op \<squnion>1" "op *" "op \<sqinter>" "op l\<rightarrow>" "op \<le>" "op <" 1 "op r\<rightarrow>"
apply unfold_locales
by (simp add: sup1_def)
definition (in pseudo_hoop_algebra)
sup2::"'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "\<squnion>2" 70) where
"a \<squnion>2 b = ((a r\<rightarrow> b) l\<rightarrow> b) \<sqinter> ((b r\<rightarrow> a) l\<rightarrow> a)"
sublocale pseudo_hoop_algebra < sup2!: pseudo_hoop_sup2_algebra "op \<squnion>2" "op *" "op \<sqinter>" "op l\<rightarrow>" "op \<le>" "op <" 1 "op r\<rightarrow>"
apply unfold_locales
by (simp add: sup2_def)
context pseudo_hoop_algebra
begin
lemma lemma_2_15_i:
"1 \<in> supremum {a, b} \<Longrightarrow> a * b = a \<sqinter> b"
apply (rule antisym)
apply (rule lemma_2_5_11)
apply (simp add: inf_l_def)
apply (subst left_impl_times)
apply (rule mult_right_mono)
apply (subst right_lesseq)
apply (subgoal_tac "a \<squnion>1 b = 1")
apply (simp add: sup1_def)
apply (rule antisym)
apply simp
by (simp add: supremum_def upper_bound_def)
lemma lemma_2_15_ii:
"1 \<in> supremum {a, b} \<Longrightarrow> a \<le> c \<Longrightarrow> b \<le> d \<Longrightarrow> 1 \<in> supremum {c, d}"
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (drule_tac x = x in spec)
apply safe
by simp_all
lemma sup_union:
"a \<in> supremum A \<Longrightarrow> b \<in> supremum B \<Longrightarrow> supremum {a, b} = supremum (A \<union> B)"
apply safe
apply (simp_all add: supremum_def upper_bound_def)
apply safe
apply auto
apply (subgoal_tac "(\<forall>x \<in> A \<union> B. x \<le> xa)")
by auto
lemma sup_singleton [simp]: "a \<in> supremum {a}"
by (simp add: supremum_def upper_bound_def)
lemma sup_union_singleton: "a \<in> supremum X \<Longrightarrow> supremum {a, b} = supremum (X \<union> {b})"
apply (rule_tac B = "{b}" in sup_union)
by simp_all
lemma sup_le_union [simp]: "a \<le> b \<Longrightarrow> supremum (A \<union> {a, b}) = supremum (A \<union> {b})"
apply (simp add: supremum_def upper_bound_def)
by auto
lemma sup_sup_union: "a \<in> supremum A \<Longrightarrow> b \<in> supremum (B \<union> {a}) \<Longrightarrow> b \<in> supremum (A \<union> B)"
apply (simp add: supremum_def upper_bound_def)
by auto
end
(*
context monoid_mult
begin
lemma "a ^ 2 = a * a"
by (simp add: local.power2_eq_square)
end
*)
lemma [simp]:
"n \<le> 2 ^ n"
apply (induct_tac n)
apply auto
apply (rule_tac y = "1 + 2 ^ n" in order_trans)
by auto
context pseudo_hoop_algebra
begin
lemma sup_le_union_2:
"a \<le> b \<Longrightarrow> a \<in> A \<Longrightarrow> b \<in> A \<Longrightarrow> supremum A = supremum ((A - {a}) \<union> {b})"
apply (case_tac "supremum ((A - {a , b}) \<union> {a, b}) = supremum ((A - {a, b}) \<union> {b})")
apply (case_tac "((A - {a, b}) \<union> {a, b} = A) \<and> ((A - {a, b}) \<union> {b} = (A - {a}) \<union> {b})")
apply safe[1]
apply simp
apply simp
apply (erule notE)
apply safe [1]
apply (erule notE)
apply (rule sup_le_union)
by simp
lemma lemma_2_15_iii_0:
"1 \<in> supremum {a, b} \<Longrightarrow> 1 \<in> supremum {a ^ 2, b ^ 2}"
apply (frule_tac a = a in lemma_2_9_i)
apply simp
apply (frule_tac a = a and b = b in sup_union_singleton)
apply (subgoal_tac "supremum ({a * a, a * b} \<union> {b}) = supremum ({a * a, b})")
apply simp_all
apply (frule_tac a = b in lemma_2_9_i)
apply simp
apply (drule_tac a = b and A = "{b * (a * a), b * b}" and b = 1 and B = "{a * a}" in sup_sup_union)
apply simp
apply (case_tac "{a * a, b} = {b, a * a}")
apply simp
apply auto [1]
apply simp
apply (subgoal_tac "supremum {a * a, b * (a * a), b * b} = supremum {a * a, b * b}")
apply(simp add: power2_eq_square)
apply (case_tac "b * (a * a) = b * b")
apply auto[1]
apply (cut_tac A = "{a * a, b * (a * a), b * b}" and a = "b * (a * a)" and b = "a * a" in sup_le_union_2)
apply simp
apply simp
apply simp
apply (subgoal_tac "({a * a, b * (a * a), b * b} - {b * (a * a)} \<union> {a * a}) = {a * a, b * b}")
apply simp
apply auto[1]
apply (case_tac "a * a = a * b")
apply (subgoal_tac "{b, a * a, a * b} = {a * a, b}")
apply simp
apply auto[1]
apply (cut_tac A = "{b, a * a, a * b}" and a = "a * b" and b = "b" in sup_le_union_2)
apply simp
apply simp
apply simp
apply (subgoal_tac "{b, a * a, a * b} - {a * b} \<union> {b} = {a * a, b}")
apply simp
by auto
lemma [simp]: "m \<le> n \<Longrightarrow> a ^ n \<le> a ^ m"
apply (subgoal_tac "a ^ n = (a ^ m) * (a ^ (n-m))")
apply simp
apply (cut_tac a = a and m = "m" and n = "n - m" in power_add)
by simp
lemma [simp]: "a ^ (2 ^ n) \<le> a ^ n"
by simp
lemma lemma_2_15_iii_1: "1 \<in> supremum {a, b} \<Longrightarrow> 1 \<in> supremum {a ^ (2 ^ n), b ^ (2 ^ n)}"
apply (induct_tac n)
apply auto[1]
apply (drule drop_assumption)
apply (drule lemma_2_15_iii_0)
apply (subgoal_tac "!a . (a ^ (2\<Colon>nat) ^ n)\<^sup>2 = a ^ (2\<Colon>nat) ^ Suc n")
apply simp
apply safe
apply (cut_tac a = aa and m = "2 ^ n" and n = 2 in power_mult)
apply auto
apply (subgoal_tac "((2\<Colon>nat) ^ n * (2\<Colon>nat)) = ((2\<Colon>nat) * (2\<Colon>nat) ^ n)")
by simp_all
lemma lemma_2_15_iii:
"1 \<in> supremum {a, b} \<Longrightarrow> 1 \<in> supremum {a ^ n, b ^ n}"
apply (drule_tac n = n in lemma_2_15_iii_1)
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (drule_tac x = x in spec)
apply safe
apply (rule_tac y = "a ^ n" in order_trans)
apply simp_all
apply (rule_tac y = "b ^ n" in order_trans)
by simp_all
end
end
|
module tide_module
implicit none
logical, save :: setup = .false.
contains
subroutine setup_tide(time_input, water_level, wl_size)
integer, intent(in out) :: wl_size
real(kind=8), dimension (:), allocatable, intent(in out) :: time_input, water_level
integer :: iunit, i, istat
logical :: foundFile
character(len=255) :: wl_input
real(kind=8), dimension (:,:), allocatable :: data_array
real(kind=8) :: tmp
if (.not. setup) then
iunit = 40
wl_input = '../tide.data'
inquire(file=trim(adjustl(wl_input)), exist=foundFile)
if (.not. foundFile) then
write(*,*) 'Missing water level data file ...'
write(*,*) 'Looking for ', trim(adjustl(wl_input)),' file'
stop
endif
open(iunit, file=trim(adjustl(wl_input)), status='old', iostat=istat)
rewind(iunit)
wl_size = 0
do
read(iunit, *, iostat=istat) tmp
if (is_iostat_end(istat)) exit
wl_size = wl_size + 1
end do
allocate(data_array(wl_size, 2))
allocate(time_input(wl_size))
allocate(water_level(wl_size))
rewind(iunit)
do i= 1, wl_size
read(iunit, *, iostat=istat) data_array(i,:)
end do
close(unit=iunit, iostat=istat)
time_input(:) = data_array(:,1)
water_level(:) = data_array(:,2)
deallocate(data_array)
setup = .true.
end if
end subroutine setup_tide
subroutine parabola_val2(ndata, tdata, ydata, left, tval, yval)
!*****************************************************************************80
!
!! PARABOLA_VAL2 evaluates a parabolic interpolant through tabular data.
!
! Discussion:
!
! This routine is a utility routine used by OVERHAUSER_SPLINE_VAL.
! It constructs the parabolic interpolant through the data in
! 3 consecutive entries of a table and evaluates this interpolant
! at a given abscissa value.
!
! Licensing:
!
! This code is distributed under the GNU LGPL license.
!
! Modified:
!
! 26 January 2004
!
! Author:
!
! John Burkardt
!
! Parameters:
!
! Input, integer(kind=4) :: NDATA, the number of data points.
! NDATA must be at least 3.
!
! Input, real(kind=8) :: TDATA(NDATA), the abscissas of the data
! points. The values in TDATA must be in strictly ascending order.
!
! Input, real(kind=8) :: YDATA(DIM_NUM,NDATA), the data points
! corresponding to the abscissas.
!
! Input, integer(kind=4) :: LEFT, the location of the first of the three
! consecutive data points through which the parabolic interpolant
! must pass. 1 <= LEFT <= NDATA - 2.
!
! Input, real(kind=8) :: TVAL, the value of T at which the parabolic
! interpolant is to be evaluated. Normally, TDATA(1) <= TVAL <= T(NDATA),
! and the data will be interpolated. For TVAL outside this range,
! extrapolation will be used.
!
! Output, real(kind=8) :: YVAL(DIM_NUM), the value of the parabolic
! interpolant at TVAL.
!
implicit none
integer(kind=4) :: ndata
real(kind=8) :: dif1
real(kind=8) :: dif2
integer(kind=4) :: left
real(kind=8) :: t1
real(kind=8) :: t2
real(kind=8) :: t3
real(kind=8) :: tval
real(kind=8) :: tdata(ndata)
real(kind=8) :: ydata(ndata)
real(kind=8) :: y1
real(kind=8) :: y2
real(kind=8) :: y3
real(kind=8) :: yval
!
! Check.
!
if (left < 1) then
write (*, '(a)') ' '
write (*, '(a)') 'PARABOLA_VAL2 - Fatal error!'
write (*, '(a)') ' LEFT < 1.'
write (*, '(a,i8)') ' LEFT = ', left
stop 1
end if
if (ndata-2 < left) then
write (*, '(a)') ' '
write (*, '(a)') 'PARABOLA_VAL2 - Fatal error!'
write (*, '(a)') ' NDATA-2 < LEFT.'
write (*, '(a,i8)') ' NDATA = ', ndata
write (*, '(a,i8)') ' LEFT = ', left
stop 1
end if
!
! Copy out the three abscissas.
!
t1 = tdata(left)
t2 = tdata(left+1)
t3 = tdata(left+2)
if (t2 <= t1 .or. t3 <= t2) then
write(*, '(a)') ' '
write(*, '(a)') 'PARABOLA_VAL2 - Fatal error!'
write(*, '(a)') ' T2 <= T1 or T3 <= T2.'
stop 1
end if
!
! Construct and evaluate a parabolic interpolant for the data
! in each dimension.
!
y1 = ydata(left)
y2 = ydata(left+1)
y3 = ydata(left+2)
dif1 = (y2 - y1) / (t2 - t1)
dif2 = ((y3 - y1) / (t3 - t1) &
- (y2 - y1) / (t2 - t1)) / (t3 - t2)
yval = y1 + (tval - t1) * (dif1 + (tval - t2) * dif2)
return
end subroutine parabola_val2
subroutine linear_val2(y, t, y1, y2, t1, t2)
implicit none
real(kind=8), intent(in) :: t, y1, y2, t1, t2
real(kind=8), intent(out) :: y
if (t1 > t2) then
print *, 'Fatal error, t1 > t2'
stop
end if
y = y1 + (y2 - y1) / (t2 - t1) * (t - t1)
return
end subroutine linear_val2
end module tide_module
|
"""This module handles the data science operations on email lists."""
import io
import os
import json
import asyncio
from collections import OrderedDict
from datetime import datetime, timedelta, timezone
from billiard import current_process # pylint: disable=no-name-in-module
import requests
from requests.exceptions import ConnectionError as ConnError
import pandas as pd
from pandas.io.json import json_normalize
import numpy as np
from aiohttp import ClientSession, BasicAuth
import iso8601
from celery.utils.log import get_task_logger
def do_async_import(coroutine):
"""Generic wrapper function to run async imports.
Args:
coroutine: the coroutine to be run asynchronously
"""
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(coroutine)
loop.run_until_complete(future)
class MailChimpImportError(ConnectionError):
"""A custom exception raised when async imports fail."""
def __init__(self, message, error_details):
super().__init__(message)
self.error_details = error_details
class MailChimpList(): # pylint: disable=too-many-instance-attributes
"""A class representing a MailChimp list."""
# The max size of a request to the MailChimp API
# This is for direct requests to the members endpoint
CHUNK_SIZE = 5000
# The number of simultaneous connections we'll make to the API
# The API limit is 10
# But we want to make sure we don't interrupt other tasks
MAX_CONNECTIONS = 4
# The number of simultanous connections for the activity import phase
# This number is lower than MAX_CONNECTIONS
# Otherwise MailChimp will flag as too many requests
# (Each request takes very little time to complete)
MAX_ACTIVITY_CONNECTIONS = 2
# The http status codes we'd like to retry in case of a connection issue
HTTP_STATUS_CODES_TO_RETRY = [429, 504]
# The number of times to retry an http request in case of a timeout
MAX_RETRIES = 3
# The base backoff time in seconds
BACKOFF_INTERVAL = 5
# The approximate amount of seconds it takes to cold boot a proxy
PROXY_BOOT_TIME = 30
def __init__(self, id, count, api_key, data_center): # pylint: disable=redefined-builtin
"""Initializes a MailCimp list.
Args:
id: the list's unique MailChimp id.
count: the total size of the list, including subscribed,
unsubscribed, pending, and cleaned.
api_key: a MailChimp api key associated with the list.
data_center: the data center where the list is stored,
e.g. 'us2'. Used in MailChimp api calls.
Other class variables:
proxy: the proxy to use for making MailChimp API requests.
df: the pandas dataframe to perform calculations on.
frequency: how often a campaign is sent on average.
subscribers: the number of active subscribers.
open_rate: the list's open rate.
hist_bin_counts: a list containing the percentage of subscribers
with open rates in each decile.
subscribed_pct: the percentage of list members who are subscribers.
unsubscribed_pct: the percentage of list members who unsubscibed.
cleaned_pct: the percentage of list members whose addresses have
been cleaned.
pending_pct: the percentage of list members who are pending, i.e.
haven't completed double opt-in.
high_open_rt_pct: the percentage of list members who open more
than 80% of emails.
cur_yr_active_pct: the percentage of list members who registered
an 'open' event in the past 365 days.
"""
self.id = id # pylint: disable=invalid-name
self.count = int(count)
self.api_key = api_key
self.data_center = data_center
self.logger = get_task_logger(__name__)
self.proxy = None
self.df = None # pylint: disable=invalid-name
self.frequency = None
self.subscribers = None
self.open_rate = None
self.hist_bin_counts = None
self.subscribed_pct = None
self.unsubscribed_pct = None
self.cleaned_pct = None
self.pending_pct = None
self.high_open_rt_pct = None
self.cur_yr_inactive_pct = None
async def enable_proxy(self):
"""Enables a proxy server.
Requests are proxied through US Proxies to prevent MailChimp
blocks. This is an accepted technique among integrators and
does not violate MailChimp's Terms of Service.
"""
# Don't use a proxy if environment variable is set, e.g. in development
if os.environ.get('NO_PROXY'):
self.logger.info(
'NO_PROXY environment variable set. Not using a proxy.')
return
# Get the worker number for this Celery worker
# We want each worker to control its corresponding proxy process
# Note that workers are zero-indexed, proxy procceses are not
process = current_process()
# Fall back to proxy #1 if we can't ascertain the worker index
# e.g. anyone hacking with this app on windows
try:
proxy_process_number = str(process.index + 1)
except AttributeError:
proxy_process_number = '1'
# Use the US Proxies API to get the proxy info
proxy_request_uri = 'http://us-proxies.com/api.php'
proxy_params = (
('api', ''),
('uid', '9557'),
('pwd', os.environ.get('PROXY_AUTH_PWD')),
('cmd', 'rotate'),
('process', proxy_process_number),
)
try:
proxy_response = requests.get(proxy_request_uri,
params=proxy_params)
proxy_response_vars = proxy_response.text.split(':')
# Set the proxy for requests from this worker
# Keep as None (i.e, use the server's IP)
# Only if we have an issue with the proxy provider
if proxy_response_vars[0] != 'ERROR':
self.proxy = ('http://{}:{}'.format(
proxy_response_vars[1], proxy_response_vars[2]))
# If proxy provider is unreachable, don't use a proxy
except ConnError:
proxy_response_vars = None
# Allow some time for the proxy server to boot up
# We don't need to wait if we're not using a proxy
if self.proxy:
self.logger.info('Using proxy: %s', self.proxy)
await asyncio.sleep(self.PROXY_BOOT_TIME)
else:
self.logger.warning('Not using a proxy. Reason: %s.',
proxy_response_vars[2] if
proxy_response_vars else
'ConnectionError: proxy provider down.')
async def make_async_request(self, url, params, session, retry=0):
"""Makes an async request using aiohttp.
Makes a get request.
If successful, returns the response text future.
If the request times out, or returns a status code
that we want to retry, recursively retry the request
up to MAX_RETRIES times using exponential backoff.
Args:
url: The url to make the request to.
params: The HTTP GET parameters.
session: The aiohttp ClientSession to make requests with.
retry: The number of previous attempts at this individual
request.
Returns:
An asyncio future, which, when awaited,
contains the request response.
Throws:
MailChimpImportError: The request keeps returning a bad HTTP status
code and/or timing out with no response.
"""
try:
# Make the async request with aiohttp
async with session.get(url, params=params,
auth=BasicAuth('shorenstein',
self.api_key),
proxy=self.proxy) as response:
# If we got a 200 OK, return the request response
if response.status == 200:
return await response.text()
# Always log the bad response
self.logger.warning('Received invalid response code: '
'%s. URL: %s. API key: %s. '
'Response: %s.', response.status,
url, self.api_key,
response.reason)
# Retry if we got an error
# And we haven't already retried a few times
if (response.status in self.HTTP_STATUS_CODES_TO_RETRY
and retry < self.MAX_RETRIES):
# Increment retry count, log, sleep and then retry
retry += 1
self.logger.info('Retrying (%s)', retry)
await asyncio.sleep(self.BACKOFF_INTERVAL ** retry)
return await self.make_async_request(
url, params, session, retry)
# Prepare some details for the user
error_details = OrderedDict([
('err_desc', 'An error occurred when '
'trying to import your data '
'from MailChimp.'),
('mailchimp_err_code', response.status),
('mailchimp_url', url),
('api_key', self.api_key),
('mailchimp_err_reason', response.reason)])
# Log the error and raise an exception
self.logger.exception('Invalid response code from MailChimp')
raise MailChimpImportError(
'Invalid response code from MailChimp',
error_details)
# Catch proxy problems as well as potential asyncio timeouts/disconnects
except Exception as e: # pylint: disable=invalid-name
exception_type = type(e).__name__
# If we're just catching the exception raised above
# don't need to do anything else
if exception_type == 'MailChimpImportError':
raise
# Otherwise, log what happened as appropriate
if exception_type == 'ClientHttpProxyError':
self.logger.warning('Failed to connect to proxy! Proxy: %s',
self.proxy)
elif exception_type == 'ServerDisconnectedError':
self.logger.warning('Server disconnected! URL: %s. API key: '
'%s.', url, self.api_key)
elif exception_type == 'TimeoutError':
self.logger.warning('Asyncio request timed out! URL: %s. '
'API key: %s.', url, self.api_key)
else:
self.logger.warning('An unforseen error type occurred. '
'Error type: %s. URL: %s. API Key: %s.',
exception_type, url, self.api_key)
# Retry if we haven't already retried a few times
if retry < self.MAX_RETRIES:
# Increment retry count, log, sleep, and then retry
retry += 1
self.logger.info('Retrying (%s)', retry)
await asyncio.sleep(self.BACKOFF_INTERVAL ** retry)
return await self.make_async_request(
url, params, session, retry)
# Prepare some details for the user
error_details = OrderedDict([
('err_desc', 'An error occurred when '
'trying to import your data from MailChimp.'),
('application_exception', exception_type),
('mailchimp_url', url),
('api_key', self.api_key)])
# Log the error and raise an exception
self.logger.exception('Error in async request to MailChimp (%s)',
exception_type)
raise MailChimpImportError(
'Error in async request to MailChimp ({})'.format(
exception_type),
error_details)
async def make_async_requests(self, sem, url, params, session):
"""Makes a number of async requests using a semaphore.
Args:
sem: A semaphore to limit the number of concurrent async
requests.
url: See make_async_request().
params: See make_async_request().
session: See make_async_request().
Returns:
An asyncio future resolved into a dictionary containing
request results.
"""
async with sem:
res = await self.make_async_request(url, params, session)
return json.loads(res)
async def import_list_members(self):
"""Requests basic information about MailChimp list members in chunks.
This includes the member status, member stats, etc.
Requests are made asynchronously (up to CHUNK_SIZE members
per requests) using aiohttp. This speeds up the process
significantly and prevents timeouts.
After the requests have completed, parses the results and turns
them into a pandas dataframe.
"""
# Enable a proxy
await self.enable_proxy()
# MailChimp API endpoint for requests
request_uri = ('https://{}.api.mailchimp.com/3.0/lists/{}/'
'members'.format(self.data_center, self.id))
# List of async tasks to do
tasks = []
# Placeholder for async responses
responses = None
# Semaphore to limit max simultaneous connections to MailChimp API
sem = asyncio.Semaphore(self.MAX_CONNECTIONS)
# The total number of chunks, i.e. requests to make to MailChimp
# If list is smaller than CHUNK_SIZE, this is 1 request
number_of_chunks = (1 if self.count < self.CHUNK_SIZE
else self.count // self.CHUNK_SIZE + 1)
# Make requests with a single session
async with ClientSession() as session:
for chunk_num in range(number_of_chunks):
# Calculate the number of members in this request
chunk = (str(self.count % self.CHUNK_SIZE
if chunk_num == number_of_chunks - 1
else self.CHUNK_SIZE))
# Calculate where to begin request from
offset = str(chunk_num * self.CHUNK_SIZE)
params = (
('fields', 'members.status,'
'members.timestamp_opt,'
'members.timestamp_signup,'
'members.stats,members.id'),
('count', chunk),
('offset', offset),
)
# Add a new import task to the queue for each chunk
task = asyncio.ensure_future(
self.make_async_requests(
sem, request_uri, params, session))
tasks.append(task)
# Await completion of all requests and gather results
responses = await asyncio.gather(*tasks)
# Flatten the responses into a single list of dicts
list_data = [response
for response_dict in responses
for v in response_dict.values()
for response in v]
# Create a pandas dataframe to store the results
self.df = pd.DataFrame(list_data) # pylint: disable=invalid-name
async def import_sub_activity(self): # pylint: disable=too-many-locals
"""Requests each subscriber's recent activity.
First, gets a list of subscribers.
Then makes the requests one-by-one using aiohttp (MailChimp's API is
very inefficient and you cannot request multiple subscribers' activity
at the same time).
After the requests have completed, parses the results, turns them into
a pandas dataframe, and merges this dataframe with the members
dataframe created by import_list_members().
"""
params = (
('fields', 'activity.action,activity.timestamp,email_id'),
('exclude_fields', 'total_items,_links')
)
request_uri = ('https://{}.api.mailchimp.com/3.0/lists/{}/members/'
'{}/activity'.format(self.data_center, self.id, '{}'))
# List of async tasks to do
tasks = []
# Placeholder for async responses
responses = None
# Semaphore to limit max simultaneous connections to MailChimp API
sem = asyncio.Semaphore(self.MAX_ACTIVITY_CONNECTIONS)
# Get a list of unique subscriber ids
subscriber_list = self.get_list_ids()
# Store the number of subscribers for later
self.subscribers = len(subscriber_list)
# Create a session with which to make requests
async with ClientSession() as session:
for subscriber_id in subscriber_list:
# Format the request string
request_string = request_uri.format(subscriber_id)
# Add a new import task to the queue for each list subscriber
task = asyncio.ensure_future(
self.make_async_requests(
sem, request_string, params, session))
tasks.append(task)
# Await completion of all requests and gather results
responses = await asyncio.gather(*tasks)
# Calculate timestamp for one year ago
now = datetime.now(timezone.utc)
one_year_ago = now - timedelta(days=365)
# Flatten responses
# Filter out activity older than one year
activities = [{**{'id': response['email_id']},
**{'recent_open': d['timestamp']
for d in response['activity']
if d['action'] == 'open' and
iso8601.parse_date(d['timestamp']) > one_year_ago}}
for response in responses]
# Convert results to a dataframe
subscriber_activities = pd.DataFrame(activities)
# Merge dataframes if any subscribers have recently opened
# Else add an empty recent_open column to dataframe
# This allows us to assume that a 'recent open' column exists
if 'recent_open' in subscriber_activities:
self.df = pd.merge(self.df,
subscriber_activities,
on='id',
how='left')
else:
self.df['recent_open'] = np.NaN
def get_list_ids(self):
"""Returns a list of md5-hashed email ids for subscribers only."""
return self.df[self.df['status'] == 'subscribed']['id'].tolist()
def flatten(self):
"""Removes nested jsons from the dataframe."""
# Extract member stats from nested json
# Then store them in a flattened dataframe
stats = json_normalize(self.df['stats'].tolist())
# Merge the dataframes
self.df = (self.df[['status', 'timestamp_opt', 'timestamp_signup',
'id', 'recent_open']].join(stats))
def calc_list_breakdown(self):
"""Calculates the list breakdown."""
statuses = self.df.status.unique()
self.subscribed_pct = (
0 if 'subscribed' not in statuses
else self.df.status.value_counts()['subscribed'] /
self.count)
self.unsubscribed_pct = (
0 if 'unsubscribed' not in statuses
else self.df.status.value_counts()['unsubscribed'] /
self.count)
self.cleaned_pct = (
0 if 'cleaned' not in statuses
else self.df.status.value_counts()['cleaned'] /
self.count)
self.pending_pct = (
0 if 'pending' not in statuses
else self.df.status.value_counts()['pending'] /
self.count)
def calc_open_rate(self, open_rate):
"""Calculates the open rate as a decimal."""
self.open_rate = float(open_rate) / 100
def calc_frequency(self, date_created, campaign_count):
"""Calculates the average number of days per campaign sent. Automatically
zero if fewer than 10 campaigns have been sent total."""
campaign_count = int(campaign_count)
if campaign_count < 10:
self.frequency = 0
else:
now = datetime.now(timezone.utc)
created = (iso8601.parse_date(date_created)
if isinstance(date_created, str)
else date_created)
list_age = now - created
self.frequency = list_age.days / campaign_count
def calc_histogram(self):
"""Calculates the distribution for subscriber open rate."""
bin_boundaries = np.linspace(0, 1, num=11)
bins = (pd.cut(
self.df.loc[self.df['status'] == 'subscribed', 'avg_open_rate'],
bin_boundaries, include_lowest=True))
self.hist_bin_counts = (pd.value_counts(bins, sort=False).tolist())
def calc_high_open_rate_pct(self):
"""Calcuates the percentage of subscribers who open >80% of emails."""
# Sum the number of rows where average open rate exceeds 0.8
# And the member is a subscriber
# Then divide by the total number of rows
self.high_open_rt_pct = (
sum(x > 0.8 for x in self.df[self.df['status'] == 'subscribed']
['avg_open_rate']) / self.subscribers)
def calc_cur_yr_stats(self):
"""Calculates metrics related to activity
that occured in the previous year."""
# Total number of subsribers without an open within the last year
cur_yr_inactive_subs = (self.subscribers -
int(self.df['recent_open'].count()))
# Percent of such subscribers
self.cur_yr_inactive_pct = cur_yr_inactive_subs / self.subscribers
def get_list_as_csv(self):
"""Returns a string buffer containing a CSV of the list data."""
csv_buffer = io.StringIO()
self.df.to_csv(csv_buffer, index=False)
csv_buffer.seek(0)
return csv_buffer
|
/// @file
///
/// Base class for handling extraction of image data corresponding to a source
///
/// @copyright (c) 2017 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// [email protected]
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Matthew Whiting <[email protected]>
///
#include <extraction/SourceDataExtractor.h>
#include <askap_analysis.h>
#include <askap/AskapLogging.h>
#include <askap/AskapError.h>
#include <string>
#include <sourcefitting/RadioSource.h>
#include <casainterface/CasaInterface.h>
#include <imageaccess/ImageAccessFactory.h>
#include <catalogues/CasdaComponent.h>
#include <catalogues/CasdaIsland.h>
#include <casacore/casa/Arrays/Array.h>
#include <casacore/casa/Arrays/Slicer.h>
#include <casacore/casa/BasicSL/String.h>
#include <casacore/images/Images/ImageInterface.h>
#include <casacore/images/Images/ImageOpener.h>
#include <casacore/images/Images/FITSImage.h>
#include <casacore/images/Images/MIRIADImage.h>
#include <casacore/lattices/Lattices/LatticeBase.h>
#include <casacore/coordinates/Coordinates/DirectionCoordinate.h>
#include <casacore/casa/Quanta/Unit.h>
#include <Common/ParameterSet.h>
#include <casacore/measures/Measures/Stokes.h>
#include <boost/shared_ptr.hpp>
#include <utils/PolConverter.h>
ASKAP_LOGGER(logger, ".sourcedataextractor");
namespace askap {
namespace analysis {
SourceDataExtractor::SourceDataExtractor(const LOFAR::ParameterSet& parset):
itsParset(parset)
{
itsSource = 0;
itsComponent = 0;
itsInputCube = ""; // start off with this blank. Needs to be
// set before calling openInput()
itsInputCubeList = parset.getStringVector("spectralCube",
std::vector<std::string>(0));
// Take the following from SynthesisParamsHelper.cc in Synthesis
// there could be many ways to define stokes, e.g. ["XX YY"] or
// ["XX","YY"] or "XX,YY" to allow some flexibility we have to
// concatenate all elements first and then allow the parser from
// PolConverter to take care of extracting the products.
const std::vector<std::string>
stokesVec = parset.getStringVector("polarisation",
std::vector<std::string>(1, "I"));
std::string stokesStr;
for (size_t i = 0; i < stokesVec.size(); ++i) {
stokesStr += stokesVec[i];
}
itsStokesList = scimath::PolConverter::fromString(stokesStr);
this->verifyInputs();
openInput();
itsOutputUnits = itsInputUnits;
}
SourceDataExtractor::~SourceDataExtractor()
{
itsInputCubePtr.reset();
}
casa::Vector<Quantum<Double> > SourceDataExtractor::inputBeam()
{
casa::Vector<Quantum<Double> > inputBeam(3, 0.);
if (this->openInput()) {
inputBeam = itsInputCubePtr->imageInfo().restoringBeam().toVector();
}
return inputBeam;
}
casa::IPosition SourceDataExtractor::getShape(std::string image)
{
itsInputCube = image;
casa::IPosition shape;
if (this->openInput()) {
shape = itsInputCubePtr->shape();
this->closeInput();
}
return shape;
}
//---------------
template <class T> double SourceDataExtractor::getRA(T &object)
{
return object.ra();
}
template double SourceDataExtractor::getRA<CasdaComponent>(CasdaComponent &object);
template double SourceDataExtractor::getRA<CasdaIsland>(CasdaIsland &object);
template <> double SourceDataExtractor::getRA<RadioSource>(RadioSource &object)
{
return object.getRA();
}
//---------------
template <class T> double SourceDataExtractor::getDec(T &object)
{
return object.dec();
}
template double SourceDataExtractor::getDec<CasdaComponent>(CasdaComponent &object);
template double SourceDataExtractor::getDec<CasdaIsland>(CasdaIsland &object);
template <> double SourceDataExtractor::getDec<RadioSource>(RadioSource &object)
{
return object.getDec();
}
//---------------
template <class T> std::string SourceDataExtractor::getID(T &obj)
{
int ID = obj.getID();
std::stringstream ss;
ss << ID;
return ss.str();
}
template std::string SourceDataExtractor::getID<RadioSource>(RadioSource &obj);
template <> std::string SourceDataExtractor::getID<CasdaComponent>(CasdaComponent &obj)
{
return obj.componentID();
}
template <> std::string SourceDataExtractor::getID<CasdaIsland>(CasdaIsland &obj)
{
return obj.id();
}
//---------------
template <class T>
void SourceDataExtractor::setSourceLoc(T* src)
{
itsSourceID = getID(*src);
std::stringstream ss;
ss << itsOutputFilenameBase << "_" << itsSourceID;
itsOutputFilename = ss.str();
casa::DirectionCoordinate dc = itsInputCoords.directionCoordinate();
casa::Vector<casa::Double> pix(2);
MDirection refDir(casa::Quantity(getRA(*src), "deg"),
casa::Quantity(getDec(*src), "deg"),
dc.directionType());
dc.toPixel(pix, refDir);
itsXloc = pix[0];
itsYloc = pix[1];
}
template void SourceDataExtractor::setSourceLoc<CasdaComponent>(CasdaComponent* src);
template void SourceDataExtractor::setSourceLoc<RadioSource>(RadioSource* src);
void SourceDataExtractor::setSource(RadioSource* src)
{
itsSource = src;
if (itsSource) {
setSourceLoc(src);
}
}
void SourceDataExtractor::setSource(CasdaComponent* src)
{
itsComponent = src;
setSourceLoc(src);
}
//---------------
bool SourceDataExtractor::checkPol(std::string image,
casa::Stokes::StokesTypes stokes)
{
itsInputCube = image;
std::vector<casa::Stokes::StokesTypes> stokesvec(1, stokes);
std::string polstring = scimath::PolConverter::toString(stokesvec)[0];
bool haveMatch = false;
if (this->openInput()) {
int stokeCooNum = itsInputCubePtr->coordinates().polarizationCoordinateNumber();
if (stokeCooNum > -1) {
const casa::StokesCoordinate
stokeCoo = itsInputCubePtr->coordinates().stokesCoordinate(stokeCooNum);
if (stokeCooNum == -1 || itsStkAxis == -1) {
ASKAPCHECK(polstring == "I", "Extraction: Input cube " << image <<
" has no polarisation axis, but you requested " << polstring);
} else {
int nstoke = itsInputCubePtr->shape()[itsStkAxis];
for (int i = 0; i < nstoke && !haveMatch; i++) {
haveMatch = haveMatch || (stokeCoo.stokes()[i] == stokes);
}
}
} else {
ASKAPLOG_WARN_STR(logger, "Input cube has no Stokes axis - assuming it is Stokes I");
// No Stokes axis - assume it is Stokes I
haveMatch = (stokes == casa::Stokes::I);
}
this->closeInput();
} else ASKAPLOG_ERROR_STR(logger, "Could not open image");
return haveMatch;
}
void SourceDataExtractor::verifyInputs()
{
std::vector<std::string>::iterator im;
std::vector<std::string> pollist = scimath::PolConverter::toString(itsStokesList);
casa::Stokes stokes;
ASKAPCHECK(itsInputCubeList.size() > 0,
"Extraction: You have not provided a spectralCube input");
ASKAPCHECK(itsStokesList.size() > 0,
"Extraction: You have not provided a list of Stokes parameters " <<
"(input parameter \"polarisation\")");
if (itsInputCubeList.size() > 1) { // multiple input cubes provided
// check they are all the same shape
casa::IPosition refShape = this->getShape(itsInputCubeList[0]);
for (size_t i = 1; i < itsInputCubeList.size(); i++) {
ASKAPCHECK(refShape == this->getShape(itsInputCubeList[i]),
"Extraction: shapes of " << itsInputCubeList[0] <<
" and " << itsInputCubeList[i] << " do not match");
}
for (im = itsInputCubeList.begin(); im < itsInputCubeList.end(); im++) {
for (size_t i = 0; i < itsStokesList.size(); i++) {
if (checkPol(*im, itsStokesList[i])) {
ASKAPLOG_DEBUG_STR(logger, "Stokes " << stokes.name(itsStokesList[i]) << " has image " << *im);
itsCubeStokesMap.insert(
std::pair<casa::Stokes::StokesTypes, std::string>(itsStokesList[i], *im));
}
}
}
} else {
// only have a single input cube
if (itsInputCubeList[0].find("%p") != std::string::npos) {
// the filename has a "%p" string, meaning
// polarisation substitution is possible
for (size_t i = 0; i < itsStokesList.size(); i++) {
casa::String stokesname(stokes.name(itsStokesList[i]));
stokesname.downcase();
std::string input = itsInputCubeList[0];
ASKAPLOG_DEBUG_STR(logger, "Input cube name: replacing \"%p\" with " <<
stokesname.c_str() << " in " << input);
input.replace(input.find("%p"), 2, stokesname.c_str());
if (checkPol(input, itsStokesList[i])) {
ASKAPLOG_DEBUG_STR(logger, "Stokes " << stokes.name(itsStokesList[i]) << " has image " << input);
itsCubeStokesMap.insert(
std::pair<casa::Stokes::StokesTypes, std::string>(itsStokesList[i], input));
}
}
} else {
// We aren't using the %p wildcard - does its polarisation match one of the ones provided?
bool hasMatch = false;
for (size_t i = 0; i < itsStokesList.size(); i++) {
hasMatch = checkPol(itsInputCubeList[0], itsStokesList[i]);
if (hasMatch) {
ASKAPLOG_DEBUG_STR(logger, "Stokes " << stokes.name(itsStokesList[i]) << " has image " << itsInputCubeList[0]);
itsCubeStokesMap.insert(
std::pair<casa::Stokes::StokesTypes, std::string>(itsStokesList[i],
itsInputCubeList[0]));
}
}
ASKAPCHECK(hasMatch,
"Image " << itsInputCubeList[0] << " does not match any requested Stokes");
}
}
ASKAPLOG_DEBUG_STR(logger, "CubeStokesMap: " << itsCubeStokesMap);
}
void SourceDataExtractor::writeBeam(std::string &filename)
{
casa::Vector<Quantum<Double> >
inputBeam = itsInputCubePtr->imageInfo().restoringBeam().toVector();
if (inputBeam.size() > 0) {
boost::shared_ptr<accessors::IImageAccess> ia = accessors::imageAccessFactory(itsParset);
ia->setBeamInfo(filename,
inputBeam[0].getValue("rad"),
inputBeam[1].getValue("rad"),
inputBeam[2].getValue("rad"));
} else {
ASKAPLOG_WARN_STR(logger,
"Input cube has no restoring beam, so cannot write to output image.");
}
}
casa::Unit SourceDataExtractor::bunit()
{
casa::Unit bunits;
if (openInput()) {
bunits = itsInputCubePtr->units();
closeInput();
}
return bunits;
}
bool SourceDataExtractor::openInput()
{
bool isOK = (itsInputCube != "");
if (!isOK) {
ASKAPLOG_ERROR_STR(logger, "Image name is empty - cannot open!");
} else {
itsInputCubePtr.reset();
itsInputCubePtr = analysisutilities::openImage(itsInputCube);
isOK = (itsInputCubePtr.get() != 0); // make sure it worked.
if (isOK) {
itsInputCoords = itsInputCubePtr->coordinates();
itsLngAxis = itsInputCoords.directionAxesNumbers()[0];
itsLatAxis = itsInputCoords.directionAxesNumbers()[1];
itsSpcAxis = itsInputCoords.spectralAxisNumber();
itsStkAxis = itsInputCoords.polarizationAxisNumber();
itsInputUnits = itsInputCubePtr->units();
}
}
return isOK;
}
void SourceDataExtractor::closeInput()
{
itsInputCubePtr.reset();
}
}
}
|
Of Keats 's six major odes of 1819 , " Ode to Psyche " , was probably written first and " To Autumn " written last . Sometime between these two , he wrote " Ode to a Nightingale " . It is possible that " Ode to a Nightingale " was written between 26 April and 18 May 1819 , based on weather conditions and similarities between images in the poem and those in a letter sent to Fanny Keats on May Day . The poem was composed at the Hampstead house Keats shared with Brown , possibly while sitting beneath a plum tree in the garden . According to Keats ' friend Brown , Keats finished the ode in just one morning : " In the spring of 1819 a nightingale had built her nest near my house . Keats felt a tranquil and continual joy in her song ; and one morning he took his chair from the breakfast @-@ table to the grass @-@ plot under a plum @-@ tree , where he sat for two or three hours . When he came into the house , I perceived he had some scraps of paper in his hand , and these he was quietly thrusting behind the books . On inquiry , I found those scraps , four or five in number , contained his poetic feelings on the song of the nightingale . " Brown 's account is personal , as he claimed the poem was directly influenced by his house and preserved by his own doing . However , Keats relied on both his own imagination and other literature as sources for his depiction of the nightingale .
|
from scipy.sparse import data
import tensorflow_hub as hub
import tensorflow as tf
import numpy as np
import tensorflow_datasets as tfds
import pandas as pd
import downloader
import os
import model_trainer_sentiment_task as model_trainer
import deduplicator as deduplicator
import blocker
import indexer
from scipy.spatial import distance
from sklearn.model_selection import train_test_split
def run_on_model_1():
"""Here, we use the w2v_wiki500_yelp_embed_nontrainable mdoel to build indexes
of block then save it to disk for further usage.
"""
model_path = 'models'
# Define block size
block_size_x = 10000
block_size_y = 50
# Build block indexes on nnlm_en_dim128_yelp_embed_trainable
m1 = tf.keras.models.load_model(os.path.join(model_path, 'nnlm_en_dim128_yelp_embed_trainable.h5'),
custom_objects={'KerasLayer':hub.KerasLayer})
m1_ms = blocker.block_model_2d(m1, block_size_x=block_size_x, block_size_y=block_size_y)
# Create indexer
blocks_indexer = indexer.Indexer(block_size_x=block_size_x, block_size_y=block_size_y)
blocks_indexer.build_index(m1_ms, 'm1')
blocks_indexer.save('hetero_model_exp1_blocks_indexer_1.npy')
def run_on_model_2(method):
"""Here, we perform the deduplication to nnlm_en_dim50_imdb_embed_trainable model,
it first reload the indexes pre-saved from the first step, then performing a deduplication.
For the not-deduplicated blocks, it will be treated as unique blocks and gets updated to
indexer and saved to disk.
Please use the correct commented out code to evaluate different approaches.
"""
model_path = 'models'
# Define block size
block_size_x = 10000
block_size_y = 50
# Create indexer
blocks_indexer = indexer.Indexer(block_size_x=block_size_x, block_size_y=block_size_y)
blocks_indexer.load('hetero_model_exp1_blocks_indexer_1.npy')
m2 = tf.keras.models.load_model(os.path.join(model_path, 'nnlm_en_dim50_imdb_embed_trainable.h5'),
custom_objects={'KerasLayer':hub.KerasLayer})
m2_ms = blocker.block_model_2d(m2, block_size_x=block_size_x, block_size_y=block_size_y)
m2.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Load dataset for imdb
x, y = model_trainer.load_dataset(dataset="imdb_reviews")
x_train, x_test, y_train, y_test = train_test_split(
x, y, test_size=0.2, random_state=0)
if method == 'enhanced_pairwise':
# Run deduplication (enhanced-pairwise)
result_df = deduplicator.deduplicate_model(m2, m2_ms, x_test, y_test,
blocks_indexer, fp=0.01, sim=0.1, stop_acc_drop=0.035,
use_lsh=False)
elif method == 'proposed_wo_finetune':
# Run deduplication (proposed w/o fine-tune)
result_df = deduplicator.deduplicate_model(m2, m2_ms, x_test, y_test,
blocks_indexer, fp=0.01, sim=0, stop_acc_drop=0.035,
use_lsh=True)
elif method == 'proposed_w_finetune':
# Run deduplication (proposed w/ fine-tune)
result_df = deduplicator.deduplicate_model(m2, m2_ms, x_test, y_test,
blocks_indexer, fp=0.01, sim=0.1, stop_acc_drop=0.035,
use_lsh=True, x_train=x_train, y_train=y_train,
finetune=True)
detector_output, num_unique_blocks = deduplicator.generate_detector_output(result_df, m2_ms, blocks_indexer.num_total)
result_df.to_csv('hetero_model_exp1_2.csv', index=False)
np.save('hetero_model_exp1_2.npy', detector_output)
# Update index
blocks_indexer.update_index(m2_ms, result_df)
# Save to disk
blocks_indexer.save('hetero_model_exp1_blocks_indexer_2.npy')
def run_on_model_3(method):
"""Here, we perform the deduplication to w2v_wiki250_civil_comment_embed_trainable model,
it first reload the indexes pre-saved from the first step, then performing a deduplication.
For the not-deduplicated blocks, it will be treated as unique blocks and gets updated to
indexer and saved to disk.
Please use the correct commented out code to evaluate different approaches.
"""
model_path = 'models'
# Define block size
block_size_x = 10000
block_size_y = 50
# Create indexer
blocks_indexer = indexer.Indexer(block_size_x=block_size_x, block_size_y=block_size_y)
blocks_indexer.load('hetero_model_exp1_blocks_indexer_2.npy')
# Load model
m2 = tf.keras.models.load_model(os.path.join(model_path, 'w2v_wiki250_civil_comment_embed_trainable.h5'),
custom_objects={'KerasLayer':hub.KerasLayer})
m2_ms = blocker.block_model_2d(m2, block_size_x=block_size_x, block_size_y=block_size_y)
m2.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Load dataset for civil
x, y = model_trainer.load_dataset(dataset="civil_comment")
x_train, x_test, y_train, y_test = train_test_split(
np.array(x), y, test_size=0.2, random_state=0)
if method == 'enhanced_pairwise':
# Run deduplication (enhanced-pairwise)
result_df = deduplicator.deduplicate_model(m2, m2_ms, x_test, y_test,
blocks_indexer, fp=0.01, sim=0.1, stop_acc_drop=0.035,
use_lsh=False)
elif method == 'proposed_wo_finetune':
# Run deduplication (proposed w/o fine-tune)
result_df = deduplicator.deduplicate_model(m2, m2_ms, x_test, y_test,
blocks_indexer, fp=0.01, sim=0, stop_acc_drop=0.035,
use_lsh=True)
elif method == 'proposed_w_finetune':
# Run deduplication (proposed w/ fine-tune)
result_df = deduplicator.deduplicate_model(m2, m2_ms, x_test, y_test,
blocks_indexer, fp=0.01, sim=0.1, stop_acc_drop=0.035,
use_lsh=True, x_train=x_train, y_train=y_train,
finetune=True)
detector_output, num_unique_blocks = deduplicator.generate_detector_output(result_df, m2_ms, blocks_indexer.num_total)
result_df.to_csv('hetero_model_exp1_3.csv', index=False)
np.save('hetero_model_exp1_3.npy', detector_output)
# Update index
blocks_indexer.update_index(m2_ms, result_df)
# Save to disk
blocks_indexer.save('hetero_model_exp1_blocks_indexer_3.npy')
def run_on_model_4(method):
"""Here, we perform the deduplication to w2v_wiki500_yelp_embed_trainable model,
it first reload the indexes pre-saved from the first step, then performing a deduplication.
For the not-deduplicated blocks, it will be treated as unique blocks and gets updated to
indexer and saved to disk.
Please use the correct commented out code to evaluate different approaches.
"""
model_path = 'models'
# Define block size
block_size_x = 10000
block_size_y = 50
# Create indexer
blocks_indexer = indexer.Indexer(block_size_x=block_size_x, block_size_y=block_size_y)
blocks_indexer.load('hetero_model_exp1_blocks_indexer_3.npy')
# Load model
m2 = tf.keras.models.load_model(os.path.join(model_path, 'w2v_wiki500_yelp_embed_trainable.h5'),
custom_objects={'KerasLayer':hub.KerasLayer})
m2_ms = blocker.block_model_2d(m2, block_size_x=block_size_x, block_size_y=block_size_y)
m2.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Load dataset for yelp
x, y = model_trainer.load_dataset(dataset="yelp_reviews")
x_train, x_test, y_train, y_test = train_test_split(
np.array(x), y, test_size=0.2, random_state=0)
if method == 'enhanced_pairwise':
# Run deduplication (enhanced-pairwise)
result_df = deduplicator.deduplicate_model(m2, m2_ms, x_test, y_test,
blocks_indexer, fp=0.01, sim=0.1, stop_acc_drop=0.035,
use_lsh=False)
elif method == 'proposed_wo_finetune':
# Run deduplication (proposed w/o fine-tune)
result_df = deduplicator.deduplicate_model(m2, m2_ms, x_test, y_test,
blocks_indexer, fp=0.01, sim=0, stop_acc_drop=0.035,
use_lsh=True)
elif method == 'proposed_w_finetune':
# Run deduplication (proposed w/ fine-tune)
result_df = deduplicator.deduplicate_model(m2, m2_ms, x_test, y_test,
blocks_indexer, fp=0.01, sim=0.1, stop_acc_drop=0.035,
use_lsh=True, x_train=x_train, y_train=y_train,
finetune=True)
detector_output, num_unique_blocks = deduplicator.generate_detector_output(result_df, m2_ms, blocks_indexer.num_total)
result_df.to_csv('hetero_model_exp1_4.csv', index=False)
np.save('hetero_model_exp1_4.npy', detector_output)
# Update index
blocks_indexer.update_index(m2_ms, result_df)
# Save to disk
blocks_indexer.save('hetero_model_exp1_blocks_indexer_4.npy')
def main():
# FIXME Code cleaning is NEEDED
# Run on CPU/GPU
run_on_cpu = False
model_trainer.run_device(run_on_cpu=run_on_cpu)
# Method: enhanced_pairwise, proposed_wo_finetune, or proposed_w_finetune
method = 'proposed_wo_finetune'
run_on_model_1()
run_on_model_2(method)
run_on_model_3(method)
run_on_model_4(method)
if __name__ == "__main__":
main()
|
# Linear transformations with images
In this module we will work with linearly aligning images. We'll apply transformations to images, and estimate optimal transformations. Here problems will be nonlinear, and we'll need to use iterative methods.
```python
import numpy as np
%matplotlib notebook
import matplotlib as mpl
import matplotlib.pyplot as plt
import nibabel as nib
import os
import summerschool as ss
import scipy.interpolate as spi
```
## Load some data
```python
fname = os.path.join('mouse_images','PMD2052_orig_target_STS_clean.img')
img = nib.load(fname)
# load the image
I = img.get_data()[:,:,:,0] # note last axes is time, we'd like to remove it
# downsample so it can run on people's laptops
down = 3
I = ss.downsample_image(I,down)
# get voxeldx = img.header['pixdim'][1:4]*down voxel size and number of voxels
# note all the images in this dataset are in MNI space and are the same size and shape
nx = I.shape
dx = img.header['pixdim'][1:4]*down
# set up a domain
x0 = np.arange(nx[0])*dx[0]
x1 = np.arange(nx[1])*dx[1]
x2 = np.arange(nx[2])*dx[2]
# lets define the origin to be in the middle of our image
# linear transformations will be more reasonable this way
x0 = x0 - np.mean(x0)
x1 = x1 - np.mean(x1)
x2 = x2 - np.mean(x2)
X0,X1,X2 = np.meshgrid(x0,x1,x2,indexing='ij')
```
```python
ss.imshow_slices(x0,x1,x2,I)
```
<IPython.core.display.Javascript object>
[<matplotlib.image.AxesImage at 0x7f2653a43518>,
<matplotlib.image.AxesImage at 0x7f2653a43860>,
<matplotlib.image.AxesImage at 0x7f2653a43b38>]
## Transformations act on images through their inverse
## Images are deformed by sampling them at new points: interpolation
```python
interp_args = {
'method':'linear', # this says how we'd like to do interpolation, linear is fast and smooth
'bounds_error':False, # if we try to sample outside the image, do not raise an error
'fill_value':0 # if we try to sample outside the image, we'll return the value 0
}
```
```python
# A 2D example image
I2d = np.array(I[:,:,I.shape[-1]//2])
X02d = X0[:,:,0]
X12d = X1[:,:,0]
```
```python
# make a figure
nplots = 5
f,ax = plt.subplots(2, nplots, sharex=True, sharey=True)
for i in range(nplots):
ax_ = ax[:,i]
# choose a transformation
if i == 0:
A = np.eye(3)
titlestring = 'identity'
elif i == 1:
T = np.random.randn(2)*2.0
A = np.array([[1,0,T[0]],[0,1,T[1]],[0,0,1]])
titlestring = 'translation'
elif i == 2:
theta = np.random.rand()*2.0*np.pi/6.0
A = np.eye(3)
A[:2,:2]= [[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]
titlestring = 'rotation'
elif i==3:
s = np.random.randn()*0.1 + 1.0
A = np.eye(3)
A[:2,:2] = np.eye(2)*s
titlestring = 'scale'
elif i == 4:
A = np.eye(3)
A[:2,:2] += np.random.randn(2,2)*0.2
titlestring = 'linear'
# make a transformed grid
AX0 = A[0,0]*X02d + A[0,1]*X12d + A[0,2]
AX1 = A[1,0]*X02d + A[1,1]*X12d + A[1,2]
stride = 5
ss.plot_grid(AX1, AX0, ax=ax_[0],
rstride=stride, cstride=stride,
color='r', linewidth=0.5, alpha=0.5)
# make a transformed image
B = np.linalg.inv(A)
X0s = B[0,0]*X02d + B[0,1]*X12d + B[0,2]
X1s = B[1,0]*X02d + B[1,1]*X12d + B[1,2]
AI = spi.interpn([x0,x1],I2d,np.stack([X0s,X1s],axis=-1),**interp_args)
ax_[0].imshow(AI, cmap='gray',
extent=[x1[1],x1[-1],x0[0],x0[-1]], origin='lower') # make sure you set extent and origin!
ax_[0].set_aspect('equal')
ax_[0].set_title(titlestring)
# let's show the vector field
ax_[1].quiver(X12d[::stride,::stride], X02d[::stride,::stride],
AX1[::stride,::stride]-X12d[::stride,::stride],
AX0[::stride,::stride]-X02d[::stride,::stride])
ax_[1].set_aspect('equal')
ax_[1].set_title('vector field')
f.suptitle('Illustration of several matrix transformations in 2D')
```
<IPython.core.display.Javascript object>
Text(0.5,0.98,'Illustration of several matrix transformations in 2D')
```python
# construct a transformation
A = np.eye(4)
A[:3,:3] += np.random.randn(3,3)*0.05 # a random deformation
A[:3,-1] += np.random.randn(3)*1.0 # a random shift
def sample_points_from_affine(X0,X1,X2,A):
# find its inverse, using homogeneous coordinates
B = np.linalg.inv(A)
# get the sample points by matrix multiplication
X0s = B[0,0]*X0 + B[0,1]*X1 + B[0,2]*X2 + B[0,3]
X1s = B[1,0]*X0 + B[1,1]*X1 + B[1,2]*X2 + B[1,3]
X2s = B[2,0]*X0 + B[2,1]*X1 + B[2,2]*X2 + B[2,3]
return X0s,X1s,X2s
# this is defined in the summer school module
X0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A)
AI = spi.interpn(
[x0,x1,x2], # this labels where in space each voxel is
I, # this says the intensity of our image at each voxel
np.stack([X0s,X1s,X2s],axis=-1), # this says where we'd like to evaluate the image
**interp_args # some more arguments that we defined above
)
f,ax=plt.subplots(2,3)
plt.subplots_adjust(wspace=0.45,hspace=0.35)
ss.imshow_slices(x0,x1,x2,I,ax[0])
for a in ax[0]:
a.set_title('before')
a.set_xlabel('')
ss.imshow_slices(x0,x1,x2,AI,ax[1])
for a in ax[1]: a.set_title('random transform')
Irandom = AI
```
<IPython.core.display.Javascript object>
## Computing optimal transformations
As with points, we will write down a sum of square error cost
\begin{align*}
E(A) = \int_X \frac{1}{2}(I(A^{-1}x) - J(x))^2 dx
\end{align*}
And as before we'll take it's gradient with respect to $A$. Since $A$ is a matrix, we'll consider an arbitrary perturbation to $A$, $A\mapsto A + \epsilon \delta A$, and take the gradient with respect to $\epsilon$ for any perturbation.
\begin{align*}
E(\epsilon) = \int_X \frac{1}{2}(I( (A + \epsilon \delta A)^{-1}x) - J(x))^2 dx
\end{align*}
We will use the fact that
\begin{align}
\frac{d}{d\epsilon}E(\epsilon) \bigg|_{\epsilon = 0} = \text{trace} \nabla E^T \delta A
\end{align}
This is just the definition of the directional derivative, as the gradient dot the directoin.
We are interested in
\begin{align*}
\frac{d}{d\epsilon}E(\epsilon) \bigg|_{\epsilon = 0}
\end{align*}
Let's attack this expression using the chain rule, first attack the square term
\begin{align*}
&= \int_X (I((A + \epsilon \delta A)^{-1}x) - J(x)) \frac{d}{d\epsilon} I((A + \epsilon \delta A)^{-1}x)dx \bigg|_{\epsilon = 0}\\
&=\int_X (I(A^{-1}x) - J(x)) \frac{d}{d\epsilon} I((A + \epsilon \delta A)^{-1}x)dx \bigg|_{\epsilon = 0}\\
\end{align*}
Now attack the image
\begin{align*}
&= \int_X (I(A^{-1}x) - J(x)) DI((A + \epsilon \delta A)^{-1}x) \frac{d}{d\epsilon} (A + \epsilon \delta A)^{-1}x dx \bigg|_{\epsilon = 0}\\
&= \int_X (I(A^{-1}x) - J(x)) DI(A^{-1}x) \frac{d}{d\epsilon} (A + \epsilon \delta A)^{-1}\bigg|_{\epsilon = 0} x dx \\
\end{align*}
Now the final term depends on taking the derivative of the inverse of a matrix. Consider an arbitrary matrix $M$ that is a function of a parameter $t$. We can work out the derivative of the inverse by
\begin{align*}
\frac{d}{dt}M^{-1}(t) &=\frac{d}{dt}\left( M^{-1}(t)M(t)M^{-1}(t) \right)\\
&= \frac{d}{dt}M^{-1}(t) M(t) M^{-1}(t) + M^{-1}(t) \frac{d}{dt}M(t) M^{-1}(t) + M^{-1}(t)M(t) \frac{d}{dt}M^{-1}(t)\\
&=\frac{d}{dt}\left( M^{-1}(t)M(t)M^{-1}(t) \right)\\
&= \frac{d}{dt}M^{-1}(t) + M^{-1}(t) \frac{d}{dt}M(t) M^{-1}(t) + \frac{d}{dt}M^{-1}(t)\\
\end{align*}
Rearranging gives
\begin{align*}
\frac{d}{dt}M^{-1}(t) = - M^{-1}(t) \frac{d}{dt}M(t) M^{-1}(t)
\end{align*}
So in our problem we have
\begin{align*}
\frac{d}{dt}(A + \epsilon \delta A)^{-1} &= -(A + \epsilon \delta A)^{-1} \delta A (A + \epsilon \delta A)^{-1}
\end{align*}
Plugging this in with $\epsilon = 0$ gives the result
\begin{align*}
\frac{d}{d\epsilon}E(\epsilon) \bigg|_{\epsilon = 0} = -\int_X (I(A^{-1}x) - J(x)) DI(A^{-1}x) A^{-1}\delta A A^{-1} x dx
\end{align*}
Finally we can simplify this by recalling that $D[I(A^{-1}x)] = DI(A^{-1}x)A^{-1}$, giving
\begin{align*}
= -\int_X (I(A^{-1}x) - J(x)) D[I(A^{-1}x)]\delta A A^{-1} x dx
\end{align*}
Finally to work out the gradient with respect to $A$, we have to write this expression as a gradient, dot $\delta A$. Taking the dot product on matrices using the trace gives
\begin{align*}
&= -\int_X \text{trace}(I(A^{-1}x) - J(x)) D[I(A^{-1}x)]\delta A A^{-1} x dx \\
&= -\int_X \text{trace}A^{-1} x (I(A^{-1}x) - J(x)) D[I(A^{-1}x)] dx \delta A
\end{align*}
which gives a gradient of
\begin{align*}
-\int_X (I(A^{-1}x)-J) \nabla[I(A^{-1}x)](A^{-1}x)^Tdx
\end{align*}
We will use this to build a gradient descent algorithm. This is an iterative method, where we update date our current guess of $A$ by taking a "small step downhill", i.e. a small step in the direction opposite to the gradient.
```python
# load a second image to map to
fname = os.path.join('mouse_images','PMD3097_orig_target_STS_clean.img')
img = nib.load(fname)
J = img.get_data()[:,:,:,0] # note last axes is time, we'd like to remove it
J = ss.downsample_image(J,down)
f,ax = plt.subplots(2,3)
ss.imshow_slices(x0,x1,x2,J,ax[0])
'''
# note that these human MRI images have already been affine aligned into MNI space
# let's add a small affine transformation and then try to recover it
A = np.eye(4)
A[:3,:3] += np.random.randn(3,3)*0.05 # a random deformation
A[:3,-1] += np.random.randn(3)*2.0 # a random shift
X0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A)
J = spi.interpn([x0,x1,x2],J,np.stack([X0s,X1s,X2s],axis=-1),**interp_args)
ss.imshow_slices(x0,x1,x2,J,ax[1])
'''
```
<IPython.core.display.Javascript object>
"\n# note that these human MRI images have already been affine aligned into MNI space\n# let's add a small affine transformation and then try to recover it\nA = np.eye(4)\nA[:3,:3] += np.random.randn(3,3)*0.05 # a random deformation\nA[:3,-1] += np.random.randn(3)*2.0 # a random shift\nX0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A)\nJ = spi.interpn([x0,x1,x2],J,np.stack([X0s,X1s,X2s],axis=-1),**interp_args)\nss.imshow_slices(x0,x1,x2,J,ax[1])\n"
```python
# initialize a transformation
A = np.eye(4)
# choose a gradient descent step size
# note that the linear part and the translation part often need to be on very different scales
# for human
epsilonL = 1.0e-12
epsilonT = 1.0e-9
# for mouse
epsilonL = 1.0e-8
epsilonT = 1.0e-7
niter = 50
EAll = []
f,ax = plt.subplots(3,3)
plt.subplots_adjust(wspace=0.45,hspace=0.45)
for it in range(niter):
# find the deformed image
X0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A)
AI = spi.interpn([x0,x1,x2],I,np.stack([X0s,X1s,X2s],axis=-1),**interp_args)
ss.imshow_slices(x0,x1,x2,AI,ax[0])
# get the error
err = AI-J
ss.imshow_slices(x0,x1,x2,err,ax[1])
for a in ax[1]: a.set_xlabel('')
# find the gradient
AI_0,AI_1,AI_2 = np.gradient(AI,dx[0],dx[1],dx[2])
# calculate energy
E = np.sum(err**2*0.5)*np.prod(dx)
EAll.append(E)
ax[2,0].cla()
ax[2,0].plot(EAll)
ax[2,0].set_title('cost')
ax[2,0].set_xlabel('iteration')
# find the gradient of the linear part
gradL = np.empty((3,3))
for i,AI_i in enumerate([AI_0,AI_1,AI_2]):
for j,AX_j in enumerate([X0s,X1s,X2s]):
gradL[i,j] = -np.sum(err*AI_i*AX_j)*np.prod(dx)
# find the gradient of the translation part
gradT = np.empty(3)
for i,AI_i in enumerate([AI_0,AI_1,AI_2]):
gradT[i] = -np.sum(err*AI_i)*np.prod(dx)
# update
A[:3,:3] -= epsilonL*gradL
A[:3,-1] -= epsilonT*gradT
f.canvas.draw()
# let's write out the transformation for the next tutorial
with open('affine.txt','wt') as f:
for i in range(4):
for j in range(4):
f.write('{} '.format(A[i,j]))
f.write('\n')
```
<IPython.core.display.Javascript object>
## Rigid transformations
Above we considered perturbations of the form $A \mapsto \epsilon \delta A$.
With rigid transforms we cannot add like this.
But we know that small perturbations to the rotation group correspond to antisymmetric matrices. We can write
\begin{align*}
A \mapsto \exp(\epsilon \delta A) A \simeq (Id + \epsilon \delta A)A
\end{align*}
where $\exp$ is the matrix exponential. Repeating the above derivations with this analysis can tell us how to optimize over the rotation group.
|
Away ! away ! for I will fly to thee ,
|
module NatTree
import Data.Fin
% access public export
data NatTree : Type where
Leaf : Nat -> NatTree
Node : NatTree -> NatTree -> NatTree
tsum : NatTree -> Nat
tsum (Leaf k) = k
tsum (Node x y) = (tsum x) + (tsum y)
recNT : (x: Type) -> (Nat -> x) -> (NatTree -> x -> NatTree -> x -> x)
-> (NatTree -> x)
recNT x f g (Leaf k) = f k
recNT x f g (Node y z) = g y yValue z zValue where
yValue = recNT x f g y
zValue = recNT x f g z
tsumTheHardWay : NatTree -> Nat
tsumTheHardWay = recNT Nat leafCase nodeCase where
leafCase = \k : Nat => k
nodeCase = \t1 => \n1 => \t2 => \n2 => n1 + n2
flattenTree : NatTree -> List Nat
flattenTree = recNT (List Nat) leafCase nodeCase where
leafCase = \k => k :: []
nodeCase = \t1 => \l1 => \t2 => \l2 => (l1 ++ l2)
data FinNatTree : Type where
FLeaf : Nat -> FinNatTree
FNode : (n: Nat) -> ((Fin (S n)) -> FinNatTree) -> FinNatTree
sumFinNat : (n: Nat) -> (Fin n -> Nat) -> Nat
sumFinNat Z f = Z
sumFinNat (S k) f = (f FZ) + tailsum where
tailsum = sumFinNat k (\ x : (Fin k) => f (FS x))
finSum : FinNatTree -> Nat
finSum (FLeaf k) = k
finSum (FNode n f) = sumFinNat (S n) treeSums where
treeSums = \index : Fin (S n) => finSum (f index)
data Evil : Type where
Diag : (Evil -> Bool) -> Evil
evil : Evil -> Bool
evil (Diag f) = not (f (Diag f))
contra : Bool
contra = evil (Diag evil)
|
/-
Copyright (c) 2021 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import topology.algebra.nonarchimedean.bases
import topology.algebra.uniform_filter_basis
import ring_theory.valuation.basic
/-!
# The topology on a valued ring
In this file, we define the non archimedean topology induced by a valuation on a ring.
The main definition is a `valued` type class which equips a ring with a valuation taking
values in a group with zero. Other instances are then deduced from this.
-/
open_locale classical topological_space uniformity
open set valuation
noncomputable theory
universes v u
variables {R : Type u} [ring R] {Γ₀ : Type v} [linear_ordered_comm_group_with_zero Γ₀]
namespace valuation
variables (v : valuation R Γ₀)
/-- The basis of open subgroups for the topology on a ring determined by a valuation. -/
lemma subgroups_basis :
ring_subgroups_basis (λ γ : Γ₀ˣ, (v.lt_add_subgroup γ : add_subgroup R)) :=
{ inter := begin
rintros γ₀ γ₁,
use min γ₀ γ₁,
simp [valuation.lt_add_subgroup] ; tauto
end,
mul := begin
rintros γ,
cases exists_square_le γ with γ₀ h,
use γ₀,
rintro - ⟨r, s, r_in, s_in, rfl⟩,
calc (v (r*s) : Γ₀) = v r * v s : valuation.map_mul _ _ _
... < γ₀*γ₀ : mul_lt_mul₀ r_in s_in
... ≤ γ : by exact_mod_cast h
end,
left_mul := begin
rintros x γ,
rcases group_with_zero.eq_zero_or_unit (v x) with Hx | ⟨γx, Hx⟩,
{ use (1 : Γ₀ˣ),
rintros y (y_in : (v y : Γ₀) < 1),
change v (x * y) < _,
rw [valuation.map_mul, Hx, zero_mul],
exact units.zero_lt γ },
{ simp only [image_subset_iff, set_of_subset_set_of, preimage_set_of_eq, valuation.map_mul],
use γx⁻¹*γ,
rintros y (vy_lt : v y < ↑(γx⁻¹ * γ)),
change (v (x * y) : Γ₀) < γ,
rw [valuation.map_mul, Hx, mul_comm],
rw [units.coe_mul, mul_comm] at vy_lt,
simpa using mul_inv_lt_of_lt_mul₀ vy_lt }
end,
right_mul := begin
rintros x γ,
rcases group_with_zero.eq_zero_or_unit (v x) with Hx | ⟨γx, Hx⟩,
{ use 1,
rintros y (y_in : (v y : Γ₀) < 1),
change v (y * x) < _,
rw [valuation.map_mul, Hx, mul_zero],
exact units.zero_lt γ },
{ use γx⁻¹*γ,
rintros y (vy_lt : v y < ↑(γx⁻¹ * γ)),
change (v (y * x) : Γ₀) < γ,
rw [valuation.map_mul, Hx],
rw [units.coe_mul, mul_comm] at vy_lt,
simpa using mul_inv_lt_of_lt_mul₀ vy_lt }
end }
end valuation
/-- A valued ring is a ring that comes equipped with a distinguished valuation. The class `valued`
is designed for the situation that there is a canonical valuation on the ring.
TODO: show that there always exists an equivalent valuation taking values in a type belonging to
the same universe as the ring.
See Note [forgetful inheritance] for why we extend `uniform_space`, `uniform_add_group`. -/
class valued (R : Type u) [ring R] (Γ₀ : out_param (Type v))
[linear_ordered_comm_group_with_zero Γ₀] extends uniform_space R, uniform_add_group R :=
(v : valuation R Γ₀)
(is_topological_valuation : ∀ s, s ∈ 𝓝 (0 : R) ↔ ∃ (γ : Γ₀ˣ), { x : R | v x < γ } ⊆ s)
/-- The `dangerous_instance` linter does not check whether the metavariables only occur in
arguments marked with `out_param`, so in this instance it gives a false positive. -/
attribute [nolint dangerous_instance] valued.to_uniform_space
namespace valued
/-- Alternative `valued` constructor for use when there is no preferred `uniform_space`
structure. -/
def mk' (v : valuation R Γ₀) : valued R Γ₀ :=
{ v := v,
to_uniform_space := @topological_add_group.to_uniform_space R _ v.subgroups_basis.topology _,
to_uniform_add_group := @topological_add_group_is_uniform _ _ v.subgroups_basis.topology _,
is_topological_valuation :=
begin
letI := @topological_add_group.to_uniform_space R _ v.subgroups_basis.topology _,
intros s,
rw filter.has_basis_iff.mp v.subgroups_basis.has_basis_nhds_zero s,
exact exists_congr (λ γ, by simpa),
end }
variables (R Γ₀) [_i : valued R Γ₀]
include _i
lemma has_basis_nhds_zero :
(𝓝 (0 : R)).has_basis (λ _, true) (λ (γ : Γ₀ˣ), { x | v x < (γ : Γ₀) }) :=
by simp [filter.has_basis_iff, is_topological_valuation]
lemma has_basis_uniformity :
(𝓤 R).has_basis (λ _, true) (λ (γ : Γ₀ˣ), { p : R × R | v (p.2 - p.1) < (γ : Γ₀) }) :=
begin
rw uniformity_eq_comap_nhds_zero,
exact (has_basis_nhds_zero R Γ₀).comap _,
end
lemma to_uniform_space_eq :
to_uniform_space = @topological_add_group.to_uniform_space R _ v.subgroups_basis.topology _ :=
uniform_space_eq
((has_basis_uniformity R Γ₀).eq_of_same_basis $ v.subgroups_basis.has_basis_nhds_zero.comap _)
variables {R Γ₀}
lemma mem_nhds {s : set R} {x : R} :
(s ∈ 𝓝 x) ↔ ∃ (γ : Γ₀ˣ), {y | (v (y - x) : Γ₀) < γ } ⊆ s :=
by simp only [← nhds_translation_add_neg x, ← sub_eq_add_neg, preimage_set_of_eq, exists_true_left,
((has_basis_nhds_zero R Γ₀).comap (λ y, y - x)).mem_iff]
lemma mem_nhds_zero {s : set R} :
(s ∈ 𝓝 (0 : R)) ↔ ∃ γ : Γ₀ˣ, {x | v x < (γ : Γ₀) } ⊆ s :=
by simp only [mem_nhds, sub_zero]
lemma loc_const {x : R} (h : (v x : Γ₀) ≠ 0) : {y : R | v y = v x} ∈ 𝓝 x :=
begin
rw mem_nhds,
rcases units.exists_iff_ne_zero.mpr h with ⟨γ, hx⟩,
use γ,
rw hx,
intros y y_in,
exact valuation.map_eq_of_sub_lt _ y_in
end
@[priority 100]
instance : topological_ring R :=
(to_uniform_space_eq R Γ₀).symm ▸ v.subgroups_basis.to_ring_filter_basis.is_topological_ring
lemma cauchy_iff {F : filter R} :
cauchy F ↔ F.ne_bot ∧ ∀ γ : Γ₀ˣ, ∃ M ∈ F, ∀ x y ∈ M, (v (y - x) : Γ₀) < γ :=
begin
rw [to_uniform_space_eq, add_group_filter_basis.cauchy_iff],
apply and_congr iff.rfl,
simp_rw valued.v.subgroups_basis.mem_add_group_filter_basis_iff,
split,
{ intros h γ,
exact h _ (valued.v.subgroups_basis.mem_add_group_filter_basis _) },
{ rintros h - ⟨γ, rfl⟩,
exact h γ }
end
end valued
|
[STATEMENT]
lemma Join_Stable_rel_le_giv:
"[| Client \<squnion> G \<in> Increasing giv; G \<in> preserves rel |]
==> Client \<squnion> G \<in> Stable {s. rel s \<le> giv s}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>Client \<squnion> G \<in> Increasing giv; G \<in> preserves rel\<rbrakk> \<Longrightarrow> Client \<squnion> G \<in> Stable {s. rel s \<le> giv s}
[PROOF STEP]
by (rule stable_rel_le_giv [THEN Increasing_preserves_Stable], auto)
|
import .brown
universes v u
open category_theory
local notation f ` ∘ `:80 g:80 := g ≫ f
namespace homotopy_theory.cofibrations
open precofibration_category cofibration_category
open homotopy_theory.weak_equivalences
variables {C : Type u} [category.{v} C] [cofibration_category.{v} C]
[has_initial_object.{v} C]
-- Following Rădulescu-Banu, Cofibrations in Homotopy Theory, Lemma 1.4.1
variables {a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : C}
{f₁₂ : a₁ ⟶ a₂} {f₁₃ : a₁ ⟶ a₃} {f₂₄ : a₂ ⟶ a₄} {f₃₄ : a₃ ⟶ a₄}
(po_f : Is_pushout f₁₂ f₁₃ f₂₄ f₃₄)
{g₁₂ : b₁ ⟶ b₂} {g₁₃ : b₁ ⟶ b₃} {g₂₄ : b₂ ⟶ b₄} {g₃₄ : b₃ ⟶ b₄}
(po_g : Is_pushout g₁₂ g₁₃ g₂₄ g₃₄)
{u₁ : a₁ ⟶ b₁} {u₂ : a₂ ⟶ b₂} {u₃ : a₃ ⟶ b₃} -- u₄ will be the induced map of pushouts
(ha₁ : cofibrant a₁) (ha₃ : cofibrant a₃) (hb₁ : cofibrant b₁) (hb₃ : cofibrant b₃)
(hf₁₂ : is_cof f₁₂) (hg₁₂ : is_cof g₁₂)
(hwu₁ : is_weq u₁) (hwu₂ : is_weq u₂) (hwu₃ : is_weq u₃)
(s₁₂ : f₁₂ ≫ u₂ = u₁ ≫ g₁₂) (s₁₃ : f₁₃ ≫ u₃ = u₁ ≫ g₁₃)
lemma gluing_weq_aux (hcu₁ : is_cof u₁) (hcu₃ : is_cof u₃)
(hcu₂'' : is_cof ((pushout_by_cof f₁₂ u₁ hf₁₂).is_pushout.induced u₂ g₁₂ s₁₂)) :
is_weq (pushout_of_maps po_f po_g u₁ u₂ u₃ s₁₂ s₁₃) :=
have acof_u₁ : is_acof u₁ := ⟨hcu₁, hwu₁⟩,
have acof_u₃ : is_acof u₃ := ⟨hcu₃, hwu₃⟩,
let po₁₂ := pushout_by_cof f₁₂ u₁ hf₁₂,
u₂' := po₁₂.map₀,
u₂'' := po₁₂.is_pushout.induced u₂ g₁₂ s₁₂,
u₄ := pushout_of_maps po_f po_g u₁ u₂ u₃ s₁₂ s₁₃,
po₃₄ := pushout_by_cof f₃₄ u₃ (pushout_is_cof po_f hf₁₂),
u₄' := po₃₄.map₀,
u₄'' := po₃₄.is_pushout.induced u₄ g₃₄ (by simp) in
have acof_u₂' : is_acof u₂' := pushout_is_acof po₁₂.is_pushout.transpose acof_u₁,
have acof_u₄' : is_acof u₄' := pushout_is_acof po₃₄.is_pushout.transpose acof_u₃,
have acof_u₂'' : is_acof u₂'' := have _ := hwu₂, begin
refine ⟨hcu₂'', category_with_weak_equivalences.weq_of_comp_weq_left acof_u₂'.2 _⟩,
simpa using this
end,
let k := pushout_of_maps po₁₂.is_pushout po₃₄.is_pushout f₁₃ f₂₄ g₁₃ po_f.commutes s₁₃.symm in
suffices Is_pushout u₂'' k g₂₄ u₄'',
by convert weq_comp acof_u₄'.2 (pushout_is_acof this acof_u₂'').2; simp,
have _ := Is_pushout_of_Is_pushout_of_Is_pushout po_f po₃₄.is_pushout,
have Is_pushout f₁₂ (u₁ ≫ g₁₃) (u₂' ≫ k) po₃₄.map₁ := begin
convert this using 1,
{ exact s₁₃.symm },
{ simp }
end,
have Is_pushout po₁₂.map₁ g₁₃ k po₃₄.map₁ :=
Is_pushout_of_Is_pushout_of_Is_pushout' po₁₂.is_pushout this (by simp),
have po_g' : Is_pushout (po₁₂.map₁ ≫ u₂'') g₁₃ g₂₄ (po₃₄.map₁ ≫ u₄'') := by convert po_g using 1; simp,
Is_pushout_of_Is_pushout_of_Is_pushout_vert' this po_g' $
by apply po₁₂.is_pushout.uniqueness; rw [←category.assoc, ←category.assoc]; simp [po_g.commutes]
lemma gluing_weq : is_weq (pushout_of_maps po_f po_g u₁ u₂ u₃ s₁₂ s₁₃) :=
let ⟨c₁⟩ := exists_brown_factorization ha₁ hb₁ u₁,
⟨c₂, h₁₂, hv₂, hr₂, hw₂, x, y⟩ :=
exists_relative_brown_factorization
ha₁ hb₁ (cofibrant_of_cof ha₁ hf₁₂) (cofibrant_of_cof hb₁ hg₁₂) u₁ u₂ f₁₂ g₁₂ s₁₂.symm c₁,
⟨c₃, h₁₃, hv₃, hr₃, hw₃, _, _⟩ :=
exists_relative_brown_factorization ha₁ hb₁ ha₃ hb₃ u₁ u₃ f₁₃ g₁₃ s₁₃.symm c₁,
po := pushout_by_cof c₁.f' f₁₂ c₁.hf' in
have cof_h₁₂ : is_cof h₁₂ := begin
convert cof_comp (pushout_is_cof po.is_pushout.transpose hf₁₂) (x hg₁₂) using 1,
simp
end,
have wv : _ := gluing_weq_aux po_f (pushout_by_cof h₁₂ h₁₃ cof_h₁₂).is_pushout hf₁₂
(c₁.weq_f' hwu₁) (c₂.weq_f' hwu₂) (c₃.weq_f' hwu₃) hv₂.symm hv₃.symm c₁.hf' c₃.hf'
(by rw ←Is_pushout.transpose_induced; exact cof_comp (cof_iso _) (x hg₁₂)),
have ww : _ := gluing_weq_aux po_g (pushout_by_cof h₁₂ h₁₃ cof_h₁₂).is_pushout hg₁₂
c₁.hs.2 c₂.hs.2 c₃.hs.2 hw₂.symm hw₃.symm c₁.hs.1 c₃.hs.1
(by rw ←Is_pushout.transpose_induced; exact cof_comp (cof_iso _) (y hf₁₂).1),
let po_h := pushout_by_cof h₁₂ h₁₃ cof_h₁₂ in
have wr : is_weq (pushout_of_maps po_h.is_pushout po_g c₁.r c₂.r c₃.r hr₂.symm hr₃.symm), begin
refine (weq_iff_weq_inv _).mp ww,
rw ←pushout_of_maps_comp,
convert pushout_of_maps_id po_g,
{ exact c₁.hsr }, { exact c₂.hsr }, { exact c₃.hsr }
end,
begin
convert weq_comp wv wr,
rw ←pushout_of_maps_comp,
congr,
{ exact c₁.hf'r.symm }, { exact c₂.hf'r.symm}, { exact c₃.hf'r.symm }
end
end homotopy_theory.cofibrations
|
% Fig. 5.28 Feedback Control of Dynamic Systems, 6e
% Franklin, Powell, Emami
% script for LEFT side of Figure 5.28. Use fig5_28b to see RIGHT side.
clf
n=[1 2];
d=conv([1 1 0],[1 13]);
nc=91*[1 .05];
dc=[1 .01];
nol=conv([0 0 n],nc);
dol=conv(d,dc);
rlocus(nol,dol);
hold on
title('Fig.5.28a Root locus for lead plus lag')
axis([-20 4 -9 9])
z=0:.1:.9;
wn=2:2:19;
sgrid(z, wn)
dcl=nol+dol;
r=roots(dcl);
plot(r,'*')
hold off
|
classdef MimEditDelete < MimGuiPlugin
% MimEditDelete. Gui Plugin for setting paint colour to transparent
%
% You should not use this class within your own code. It is intended to
% be used by the gui of the TD MIM Toolkit.
%
% MimEditDelete is a Gui Plugin for the MIM Toolkit.
%
%
% Licence
% -------
% Part of the TD MIM Toolkit. https://github.com/tomdoel
% Author: Tom Doel, Copyright Tom Doel 2014. www.tomdoel.com
% Distributed under the MIT licence. Please see website for details.
%
properties
ButtonText = 'Delete'
SelectedText = 'Delete'
ToolTip = 'Paint over edits'
Category = 'Segmentation label'
Visibility = 'Dataset'
Mode = 'Edit'
HidePluginInDisplay = false
PTKVersion = '1'
ButtonWidth = 5
ButtonHeight = 1
Icon = 'paint.png'
IconColour = GemMarkerPoint.DefaultColours{8}
Location = 38
end
methods (Static)
function RunGuiPlugin(gui_app)
gui_app.ImagePanel.PaintBrushColour = 0;
end
function enabled = IsEnabled(gui_app)
enabled = gui_app.IsDatasetLoaded && gui_app.ImagePanel.OverlayImage.ImageExists && ...
isequal(gui_app.ImagePanel.SelectedControl, 'Paint');
end
function is_selected = IsSelected(gui_app)
is_selected = gui_app.ImagePanel.PaintBrushColour == 0;
end
end
end
|
module Main (main) where
-- package の import
-- CSVの読み込み
import qualified Text.CSV as CSV
import qualified Data.Text as T
import Data.Text
import Data.Attoparsec.Text as DAT
-- 可視化
import Graphics.Rendering.Chart.Easy hiding ( (:<))
import Graphics.Rendering.Chart.Backend.Cairo
import Graphics.Rendering.Chart.Axis
import Graphics.Rendering.Chart.Axis.Int
import Graphics.Rendering.Chart.Grid
-- 重回帰
import Statistics.Regression
-- その他
import qualified Control.Monad as CM
import qualified Data.List as L
import qualified Data.Vector.Unboxed as VU
-- | Doubleのパーサ
{-# INLINE parseDouble #-}
parseDouble :: Text -> Double
parseDouble tx = case DAT.parseOnly DAT.double tx of
Right r -> r
Left l -> error $ "Error on parseDouble : " ++ show l
type Title = String
type FileName = String
type Label = String
-- | 折れ線グラフの作成
plotLine :: (PlotValue a, PlotValue b) => [(Label, [(a, b)])] -> FileName -> Title -> IO ()
plotLine xs file title
= toFile def (file ++ ".png") $ do
layout_title .= title
CM.forM_ xs $ \(title,ys) -> plot $ line title [ys]
plotBar :: [(String,[Double])] -> FileName -> Title -> [Label] -> IO ()
plotBar xs file title labels
= toFile def (file ++ ".png") $ do
layout_title .= title
layout_title_style . font_size .= 10
layout_x_axis . laxis_generate .= autoIndexAxis (L.map fst xs)
plot $ fmap plotBars $ bars labels (addIndexes (L.map snd xs))
-- | 散布図の作成
plotGridPoints :: (PlotValue a, PlotValue b)
=> [[[(Label, [(a, b)])]]] -> FileName -> Title -> IO ()
plotGridPoints xs file name
= let ys = aboveN $ (flip L.map) xs
$ \ cols -> besideN
$ (flip L.map) cols -- columns
$ \ series -> layoutToGrid
$ execEC
$ CM.forM_ series
$ \(t,xs) -> plot $ points t xs
in CM.void $ renderableToFile def (file ++ ".png")
$ fillBackground def
$ gridToRenderable
$ title `wideAbove` ys
where
title = setPickFn nullPickFn $ label ls HTA_Centre VTA_Centre name
ls = def { _font_size = 15 , _font_weight = FontWeightBold }
main = do
-- CSVファイルの読み込み
-- Dataフォルダを作成し,そこにデータを入れておきましょう
xs <- CSV.parseCSVFromFile "Data/multiple_regression_test.csv" >>= \res
-> case res of
Right xs -> return $ L.map (L.map T.pack) xs
Left xs -> error $ "error on parseCSVFromFile: " ++ show xs
-- Headerの抽出 Vectorへの変換
let headers = L.map T.unpack
$ L.head xs
-- 値のDoubleへの変換 Vectorへの変換
let body = L.transpose
$ L.map (L.map parseDouble)
$ L.tail xs
let year = body !! 0
death = body !! 1
index = body !! 2
hospital = body !! 3
-- データをグラフで表示
plotLine (L.map (\(x,y) -> (x, L.zip year y))
[("Number of Death", death)
,("Economic Indicators", index)
,("Number of Hospitals", hospital)])
"Data/initial_data"
"Data Visualization"
-- 散布図行列を作成する
plotGridPoints [[[(xt ++ "_" ++ yt, L.zip xs ys)]
| (yt,ys) <- L.zip (L.tail headers) (L.tail body)]
| (xt,xs) <- L.zip (L.tail headers) (L.tail body)]
"Data/plot_matrix"
"Plot Matrix"
-- heatmap の作成はちょっと難しいのでpass
-- 重回帰
let (coeffs, r2) = olsRegress [ VU.fromList index
, VU.fromList hospital]
( VU.fromList death)
putStrLn $ "回帰係数:" ++ show (L.init (VU.toList coeffs))
putStrLn $ "切片:" ++ show (L.last (VU.toList coeffs))
-- 結果のプロット
plotBar (L.zipWith (\x y -> (x,[y]))
["Economic Indicators", "Number of Hospitals"]
(L.init (VU.toList coeffs)))
"Data/bar_result"
"Plot Result"
["Coeff"]
|
%----------------------------------------------------------------------------------------
% PACKAGES AND THEMES
%----------------------------------------------------------------------------------------
\documentclass[aspectratio=169,xcolor=dvipsnames]{beamer}
\usetheme{Simple}
\usepackage{hyperref}
\usepackage{graphicx} % Allows including images
\usepackage{booktabs} % Allows the use of \toprule, \midrule and \bottomrule in tables
\usepackage{graphicx}
\setbeamertemplate{caption}[numbered]
\setbeamertemplate{footline}[text line]{%
\parbox{\linewidth}{\vspace*{-8pt}Github Repository: \href{https://github.com/sanjay-kv/Semi-supervised-sequence-learning-Project}{https://github.com/sanjay-kv/Semi-supervised-sequence-learning-Project}.\hfill\insertpagenumber}}
\setbeamertemplate{navigation symbols}{}
%----------------------------------------------------------------------------------------
% TITLE PAGE
%----------------------------------------------------------------------------------------
% The title
\title[short title]{Project Final Presentation}
\subtitle{Semi-supervised Sequence Learning}
\author[Sanjay K V] {Sabiha Sultana\inst{1}, Piyakorn Munegan\inst{2},\\
Sanjay Kanakkot Viswanathan\inst{3},\break Mohammed Rizwan Amanullah\inst{4}}
\institute[NTU] % Your institution may be shorthand to save space
{
% Your institution for the title page
Department of Computing, \\
Macquarie University
\vskip 3pt
}
\date{\today} % Date, can be changed to a custom date
%----------------------------------------------------------------------------------------
% PRESENTATION SLIDES - Make Presentation title and source in 1st page, put earlier suggestion to consideration as example. no justification of paper again. Look at the email suggestion about predicting performance.
%----------------------------------------------------------------------------------------
\begin{document}
\begin{frame}
% Print the title page as the first slide
\titlepage
\end{frame}
\begin{frame}{Recap - Semi-supervised Sequence Learning Project}
% Throughout your presentation, if you choose to use \section{} and \subsection{} commands, these will automatically be printed on this slide as an overview of your presentation
\tableofcontents
%------------------------------------------------
%Recap
%------------------------------------------------
\begin{itemize}
\item Goal: Replicating project which aims on unlabelled data to improve sequence learning with Recurrent network
\item (LM-LSTM) Language modelling. Predict what comes next in sequence.
\item (SA-LSTM) Reads input sequence into vectors and predict the input sequence again.
\item \alert {Requirements:} AWS(EC2) with Python 3, tensorflow v 1.15.5
\item \alert{Source:} \href{https://arxiv.org/pdf/1511.01432v1.pdf}{https://arxiv.org/pdf/1511.01432v1.pdf}
\item \alert{Source Repo:}\href{ https://github.com/tensorflow/models/tree/master/research/adversarial_text}{ https://github.com/tensorflow/models/tree/master/research/adversarial}
\item Dataset: \break
- IMDB movie review dataset\break
- DBpedia dataset (DBpedia abstracts and its categories)
\end{itemize}
\end{frame}
%------------------------------------------------
%Replication2
%------------------------------------------------
\begin{frame}{Recap - Replication Process}
\begin{itemize}
\newline
\newline
\begin{figure}
\includegraphics[width=400]{replicationFlow2.PNG}
\caption{Explains the flow of replication for Sentiment Analysis.}
\end{figure}
\newline
\newline
\break
\end{itemize}
\end{frame}
%------------------------------------------------
%------------------------------------------------
% Sanjay Issues Explanation in details
%------------------------------------------------
\begin{frame}{IMDB - Data Generation}
% Throughout your presentation, if you choose to use \section{} and \subsection{} commands, these will automatically be printed on this slide as an overview of your presentation
\tableofcontents
%------------------------------------------------
%Overview
%------------------------------------------------
\begin{columns}[c] % The "c" option specifies centered vertical alignment while the "t" option is used for top vertical alignment
\column{.45\textwidth} % Left column and width
\textbf{The Process}
\begin{enumerate}
\item Created Python Script.
\item Scrapped the data in 7 categories.
\item BeautifulSoup python package.
\end{enumerate}
\column{.5\textwidth} % Right column and width
Used python script to scrap the recent reviews from IMDB Website. Scrapped 15\% of original data-set, latter manually annotated 2000 file, among them as positive and negative sentiment category and 1000 treated as unlabelled data.
\end{columns} \\
\begin{table}[h!]
\begin{center}
\caption{A summary of total data scrapped using Beautifulsoup from IMDB Website.}
\label{tab:table1}
\begin{tabular}{|l|c|r|} % <-- Alignments: 1st column left, 2nd middle and 3rd right, with vertical lines in between
\hline
\textbf{Dataset } & \textbf{Labelled} & \textbf{Unlabelled}\\
\hline
IMDB & 2000 & 1000 \\
\hline
\end{tabular}
\end{center}
\end{table} \newline
\begin{itemize}
\item \alert{Repository:}\href{ https://github.com/sanjay-kv/Semi-supervised-sequence-learning-Project/tree/main/imdb_review_scrapping}{ https://github.com/sanjay-kv/Semi-supervised-sequence-learning-Project/tree/main/imdb-review-scrapping}
\end{itemize}
\end{frame}
%------------------------------------------------
%------------------------------------------------
%justification of original work
%------------------------------------------------
\begin{frame}{Amazon New Data Generation}
\begin{itemize}
\item Scrapped amazon.in website using selenium.
\item We have extracted product listing and product information for ten categories. \break
- After extraction, we are manually tagging the product listing. \break
\end{itemize}
\begin{table}[h!]
\begin{center}
\caption{A summary of total data scrapped using Beautifulsoup from IMDB Website.}
\label{tab:table1}
\begin{tabular}{|l|c|} % <-- Alignments: 1st column left, 2nd middle and 3rd right, with vertical lines in between
\hline
\textbf{Dataset } & \textbf{Scrapped Listings} \\
\hline
Amazon & 3154 \\
\hline
\end{tabular}
\end{center}
\end{table}
\begin{itemize}
\item \alert{Repository:}\href{ https://github.com/sanjay-kv/Semi-supervised-sequence-learning-Project/tree/main/amazon_scrapping}{ https://github.com/sanjay-kv/Semi-supervised-sequence-learning-Project/tree/main/amazon-scrapping}
\end{itemize}
\end{frame}
%----------------------------------------------------------------------------------------
%------------------------------------------------
% Dataset for the sentiment classification task}
%------------------------------------------------
\begin{frame}{Dataset for the sentiment classification task}
\tableofcontents
\textbf{Dataset}
\begin{enumerate}
\item Original IMDB movie review dataset.\break
- Training set: 25,000 labeled and 50,000 unlabeled reviews.\break
- Test set: 25,000 labeled reviews.\break
\item Replication of 5\% the size of the original IMDB dataset.\break
- Training set: 1,111 labeled and 1,111 unlabeled reviews.\break
- Test set: 1,111 labeled reviews.\break
\item Replication of new IMDB dataset.\break
- Training set: 1,000 labeled and 1,000 unlabeled reviews.\break
- Test set: 1,000 labeled reviews.\break
\end{enumerate}
\end{frame}
%------------------------------------------------
%------------------------------------------------
% Dataset for the product classification task}
%------------------------------------------------
\begin{frame}{Dataset for the product classification task}
\tableofcontents
\textbf{Dataset}
\begin{enumerate}
\item Dataset: DBpedia dataset.\break
- Training set: 560,000 labeled examples.\break
- Test set: 70,000 examples.\break
\item Replication of 2\% the size of the original DBpedia dataset.\break
- Training set: 11,200 labeled examples.\break
- Test set: 1,400 examples.\break
\item Replication of new Amazon dataset\break
- Training set: 2,795 examples.\break
- Test set: 395 examples.\break
\end{enumerate}
\end{frame}
%------------------------------------------------
%-------------------------------------------------------------
%------------------------------------------------
% Sanjay Issues Explanation in details
%------------------------------------------------
\begin{frame}{Pre-training Process}
% Throughout your presentation, if you choose to use \section{} and \subsection{} commands, these will automatically be printed on this slide as an overview of your presentation
\tableofcontents
%------------------------------------------------
%Hyperparameters tuning
%------------------------------------------------
%Adding picture
\begin{figure}
\includegraphics[width=420]{updated_model_1.jpg}
\caption{On left the Default parameter, On right Parameters we used for replication}
\end{figure}
\end{frame}
%----
%------------------------------------------------
\begin{frame}{Evaluation Results}
% Throughout your presentation, if you choose to use \section{} and \subsection{} commands, these will automatically be printed on this slide as an overview of your presentation
\tableofcontents
%------------------------------------------------
%Overview
%------------------------------------------------
\begin{table}[h!]
\begin{center}
\caption{Summary of the accuracy scores of models on the IMDB sentiment classification task}
\label{tab:table1}
\begin{tabular}{|l|r|r|r|} % <-- Alignments: 1st column left, 2nd middle and 3rd right, with vertical lines in between
\hline
\textbf{Dataset} & \textbf{LM-LSTM} & \textbf{SA-LSTM} & \textbf{LSTM} \\
\hline
Original IMDB dataset (original work) & 92.36 & 92.76 & 86.5 \\
5 \% of the original IMDB dataset & 57.6 & 56.8 & - \\
New IMDB dataset & 50 & 50 & 50 \\
\hline
\end{tabular}
\caption{Summary of the accuracy scores of models on the product classification task}
\label{tab:table2}
\begin{tabular}{|l|r|r|r|r|}
\hline
\textbf{Dataset} & \textbf{LM-LSTM} & \textbf{SA-LSTM} & \textbf{LSTM} & \textbf{SVM}\\
\hline
Original DBpedia dataset (original work) & 98.5 & 97.66 & 86.36 & -\\
2 \% of the original DBpedia dataset & 7.1 & 7.1 & 7.1 & - \\
New Amazon dataset & 9.4 & 9.4 & 9.4 & 4.54\\
\hline
\end{tabular}
\break
\break
\footnotesize{Pretraining: LM = Language Model, and SA = Sequence Autoencoder}
\end{center}
\end{table}
\end{frame}
%------------------------------------------------
%------------------------------------------------
% Findings and conclusion for the project
%------------------------------------------------
\begin{frame}{Findings/ Conclusion}
\tableofcontents
%------------------------------------------------
%Overview
%------------------------------------------------
\begin{columns}[c] % The "c" option specifies centered vertical alignment while the "t" option is used for top vertical alignment
\column{.45\textwidth} % Left column and width
\textbf{The Process}
\begin{enumerate}
\item In sentiment Analysis we were able to replicate and validate the accuracy.
\item Impact of less data has been observed in the obtained accuracy of the classification task of amazon dataset
\end{enumerate}
\column{.5\textwidth} % Right column and width
We Ensured for NLP task can use LSTM recurrent network, along with it the team were able to find and validate sequence auto-encoder can stabilize the LSTM learning process. LSTM Outperformed all other evaluation categories.
\end{columns} \\
\end{frame}
%------------------------------------------------
%----------------------------------------------------------------------------------------
\begin{frame}
\Huge{\centerline{The End}}
\end{frame}
%----------------------------------------------------------------------------------------
\end{document}
|
function [ SimilarityMatrix ] = similarityNeighbor( x, n, range)
%SIMILARITYNEIGHBOR Summary of this function goes here
% Detailed explanation goes here
sz = size(x,1);
SimilarityMatrix = eye(sz);
i = 1:sz-n;
SimilarityMatrix(sub2ind([sz, sz], i+n,i)) = 1;
SimilarityMatrix(sub2ind([sz, sz], i,i+n)) = 1;
% invalidate the illegal values from the mask (if at least one element is
% not present in the mask set similarity to 0)
% if(numel(mask)~=0)
% invalidInds = sum(mask(:,range),2) < numel(range);
%
% SimilarityMatrix(invalidInds,:) = 0;
% SimilarityMatrix(:,invalidInds) = 0;
% end
DiagMask = ones(size(x, 1)) - eye(size(x,1));
SimilarityMatrix = SimilarityMatrix .* DiagMask;
SimilarityMatrix = SimilarityMatrix + eye(size(x, 1));
end
|
theory flash69Bra imports flash69Rev
begin
lemma onInv69:
assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv1~=iInv2 " and
b1:"r \<in> rules N" and b2:"invf=inv69 iInv1 iInv2 "
shows "invHoldForRule' s invf r (invariants N)"
proof -
have c1:"ex1P N (% iRule1 . r=NI_Local_GetX_PutX1 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_GetX iRule1 )\<or>ex1P N (% iRule1 . r=NI_Replace iRule1 )\<or>ex0P N ( r=NI_ShWb N )\<or>ex0P N ( r=PI_Local_GetX_GetX2 )\<or>ex0P N ( r=NI_Local_PutXAcksDone )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX7 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Nak2 iRule1 )\<or>ex0P N ( r=NI_ReplaceHomeShrVld )\<or>ex1P N (% iRule1 . r=NI_Remote_Put iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX5 N iRule1 )\<or>ex0P N ( r=NI_Wb )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Get iRule1 )\<or>ex0P N ( r=PI_Local_Replace )\<or>ex1P N (% iRule1 . r=NI_ReplaceShrVld iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Local_GetX_PutX8 N iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_InvAck_2 N iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Remote_Get_Nak2 iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=PI_Remote_Replace iRule1 )\<or>ex0P N ( r=NI_Nak_Home )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Put2 iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_InvAck_1 iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX11 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX6 N iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Remote_Get_Put2 iRule1 iRule2 )\<or>ex0P N ( r=PI_Local_Get_Put )\<or>ex0P N ( r=PI_Local_GetX_PutX1 N )\<or>ex1P N (% iRule1 . r=NI_InvAck_1_Home iRule1 )\<or>ex1P N (% iRule1 . r=NI_Remote_Get_Nak1 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Nak1 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_Nak2 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX10_home N iRule1 )\<or>ex1P N (% iRule1 . r=PI_Remote_Get iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_Nak3 iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Local_GetX_PutX10 N iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX2 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Remote_Get_Put1 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Remote_PutX iRule1 )\<or>ex1P N (% iRule1 . r=Store iRule1 )\<or>ex0P N ( r=NI_FAck )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX3 N iRule1 )\<or>ex0P N ( r=PI_Local_GetX_PutX3 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Remote_GetX_PutX iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX8_home N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Put1 N iRule1 )\<or>ex0P N ( r=PI_Local_GetX_GetX1 )\<or>ex0P N ( r=StoreHome )\<or>ex2P N (% iRule1 iRule2 . r=NI_Remote_GetX_Nak iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_Inv iRule1 )\<or>ex1P N (% iRule1 . r=PI_Remote_PutX iRule1 )\<or>ex0P N ( r=PI_Local_GetX_PutX4 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX4 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Nak iRule1 )\<or>ex0P N ( r=PI_Local_GetX_PutX2 N )\<or>ex0P N ( r=NI_Local_Put )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_Nak1 iRule1 )\<or>ex0P N ( r=NI_Nak_Clear )\<or>ex0P N ( r=PI_Local_PutX )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Nak3 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Remote_GetX_Nak_Home iRule1 )\<or>ex0P N ( r=PI_Local_Get_Get )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX9 N iRule1 )\<or>ex1P N (% iRule1 . r=PI_Remote_GetX iRule1 )\<or>ex0P N ( r=NI_ReplaceHome )\<or>ex1P N (% iRule1 . r=NI_Remote_GetX_PutX_Home iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Put3 iRule1 )"
apply(cut_tac b1)
apply auto
done moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX1 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX1 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX1 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX1VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_GetX iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_GetX iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_GetX iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_GetXVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Replace iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Replace iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Replace iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_ReplaceVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= NI_ShWb N )
"
from c1 have c2:" r= NI_ShWb N "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_ShWb N ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis NI_ShWbVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_GetX_GetX2 )
"
from c1 have c2:" r= PI_Local_GetX_GetX2 "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_GetX_GetX2 ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_GetX_GetX2VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= NI_Local_PutXAcksDone )
"
from c1 have c2:" r= NI_Local_PutXAcksDone "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_PutXAcksDone ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis NI_Local_PutXAcksDoneVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX7 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX7 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX7 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX7VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Nak2 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Nak2 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_Get_Nak2 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_Get_Nak2VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= NI_ReplaceHomeShrVld )
"
from c1 have c2:" r= NI_ReplaceHomeShrVld "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_ReplaceHomeShrVld ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis NI_ReplaceHomeShrVldVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Remote_Put iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_Put iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_Put iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_PutVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX5 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX5 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX5 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX5VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= NI_Wb )
"
from c1 have c2:" r= NI_Wb "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Wb ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis NI_WbVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Get iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Get iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_Get_Get iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_Get_GetVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_Replace )
"
from c1 have c2:" r= PI_Local_Replace "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_Replace ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_ReplaceVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_ReplaceShrVld iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_ReplaceShrVld iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_ReplaceShrVld iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_ReplaceShrVldVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Local_GetX_PutX8 N iRule1 iRule2 )
"
from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Local_GetX_PutX8 N iRule1 iRule2 "
by (auto simp add: ex2P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX8 N iRule1 iRule2 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX8VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_InvAck_2 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_InvAck_2 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_InvAck_2 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_InvAck_2VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Remote_Get_Nak2 iRule1 iRule2 )
"
from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Remote_Get_Nak2 iRule1 iRule2 "
by (auto simp add: ex2P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_Get_Nak2 iRule1 iRule2 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_Get_Nak2VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= PI_Remote_Replace iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= PI_Remote_Replace iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Remote_Replace iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis PI_Remote_ReplaceVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= NI_Nak_Home )
"
from c1 have c2:" r= NI_Nak_Home "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Nak_Home ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis NI_Nak_HomeVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Put2 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Put2 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_Get_Put2 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_Get_Put2VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex2P N (% iRule1 iRule2 . r= NI_InvAck_1 iRule1 iRule2 )
"
from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_InvAck_1 iRule1 iRule2 "
by (auto simp add: ex2P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_InvAck_1 iRule1 iRule2 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_InvAck_1VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX11 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX11 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX11 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX11VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX6 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX6 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX6 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX6VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Remote_Get_Put2 iRule1 iRule2 )
"
from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Remote_Get_Put2 iRule1 iRule2 "
by (auto simp add: ex2P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_Get_Put2 iRule1 iRule2 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_Get_Put2VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_Get_Put )
"
from c1 have c2:" r= PI_Local_Get_Put "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_Get_Put ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_Get_PutVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_GetX_PutX1 N )
"
from c1 have c2:" r= PI_Local_GetX_PutX1 N "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_GetX_PutX1 N ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_GetX_PutX1VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_InvAck_1_Home iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_InvAck_1_Home iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_InvAck_1_Home iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_InvAck_1_HomeVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Remote_Get_Nak1 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_Get_Nak1 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_Get_Nak1 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_Get_Nak1VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Nak1 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Nak1 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_Get_Nak1 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_Get_Nak1VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_Nak2 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_Nak2 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_Nak2 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_Nak2VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX10_home N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX10_home N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX10_home N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX10_homeVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= PI_Remote_Get iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= PI_Remote_Get iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Remote_Get iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis PI_Remote_GetVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_Nak3 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_Nak3 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_Nak3 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_Nak3VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Local_GetX_PutX10 N iRule1 iRule2 )
"
from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Local_GetX_PutX10 N iRule1 iRule2 "
by (auto simp add: ex2P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX10 N iRule1 iRule2 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX10VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX2 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX2 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX2 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX2VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Remote_Get_Put1 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_Get_Put1 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_Get_Put1 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_Get_Put1VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Remote_PutX iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_PutX iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_PutX iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_PutXVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= Store iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= Store iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (Store iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis StoreVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= NI_FAck )
"
from c1 have c2:" r= NI_FAck "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_FAck ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis NI_FAckVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX3 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX3 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX3 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX3VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_GetX_PutX3 )
"
from c1 have c2:" r= PI_Local_GetX_PutX3 "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_GetX_PutX3 ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_GetX_PutX3VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Remote_GetX_PutX iRule1 iRule2 )
"
from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Remote_GetX_PutX iRule1 iRule2 "
by (auto simp add: ex2P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_GetX_PutX iRule1 iRule2 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_GetX_PutXVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX8_home N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX8_home N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX8_home N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX8_homeVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Put1 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Put1 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_Get_Put1 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_Get_Put1VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_GetX_GetX1 )
"
from c1 have c2:" r= PI_Local_GetX_GetX1 "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_GetX_GetX1 ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_GetX_GetX1VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= StoreHome )
"
from c1 have c2:" r= StoreHome "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (StoreHome ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis StoreHomeVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Remote_GetX_Nak iRule1 iRule2 )
"
from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Remote_GetX_Nak iRule1 iRule2 "
by (auto simp add: ex2P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_GetX_Nak iRule1 iRule2 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_GetX_NakVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Inv iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Inv iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Inv iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_InvVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= PI_Remote_PutX iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= PI_Remote_PutX iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Remote_PutX iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis PI_Remote_PutXVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_GetX_PutX4 )
"
from c1 have c2:" r= PI_Local_GetX_PutX4 "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_GetX_PutX4 ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_GetX_PutX4VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX4 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX4 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX4 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX4VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Nak iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Nak iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Nak iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_NakVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_GetX_PutX2 N )
"
from c1 have c2:" r= PI_Local_GetX_PutX2 N "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_GetX_PutX2 N ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_GetX_PutX2VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= NI_Local_Put )
"
from c1 have c2:" r= NI_Local_Put "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_Put ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis NI_Local_PutVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_Nak1 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_Nak1 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_Nak1 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_Nak1VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= NI_Nak_Clear )
"
from c1 have c2:" r= NI_Nak_Clear "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Nak_Clear ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis NI_Nak_ClearVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_PutX )
"
from c1 have c2:" r= PI_Local_PutX "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_PutX ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_PutXVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Nak3 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Nak3 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_Get_Nak3 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_Get_Nak3VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Remote_GetX_Nak_Home iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_GetX_Nak_Home iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_GetX_Nak_Home iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_GetX_Nak_HomeVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= PI_Local_Get_Get )
"
from c1 have c2:" r= PI_Local_Get_Get "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Local_Get_Get ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis PI_Local_Get_GetVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX9 N iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX9 N iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_GetX_PutX9 N iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_GetX_PutX9VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= PI_Remote_GetX iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= PI_Remote_GetX iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (PI_Remote_GetX iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis PI_Remote_GetXVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex0P N ( r= NI_ReplaceHome )
"
from c1 have c2:" r= NI_ReplaceHome "
by (auto simp add: ex0P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_ReplaceHome ) (invariants N) "
apply(cut_tac a1 a2 a3 b2 c2 )
by (metis NI_ReplaceHomeVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Remote_GetX_PutX_Home iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_GetX_PutX_Home iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Remote_GetX_PutX_Home iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Remote_GetX_PutX_HomeVsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
} moreover
{assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Put3 iRule1 )
"
from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Put3 iRule1 "
by (auto simp add: ex1P_def)
have "invHoldForRule' s (inv69 iInv1 iInv2 ) (NI_Local_Get_Put3 iRule1 ) (invariants N) "
apply(cut_tac c2 a1 a2 a3 )
by (metis NI_Local_Get_Put3VsInv69 )
then have "invHoldForRule' s invf r (invariants N) "
by(cut_tac c2 b2, metis)
}ultimately show "invHoldForRule' s invf r (invariants N) "
by blast
qed
end
|
# this is an example script to run the package...
using Pkg
Pkg.activate(".")
using JuliaTutor
menu()
|
/-
Copyright (c) 2021 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import analysis.normed_space.finite_dimension
import analysis.p_series
import number_theory.arithmetic_function
import topology.algebra.infinite_sum.basic
/-!
# L-series
Given an arithmetic function, we define the corresponding L-series.
## Main Definitions
* `nat.arithmetic_function.l_series` is the `l_series` with a given arithmetic function as its
coefficients. This is not the analytic continuation, just the infinite series.
* `nat.arithmetic_function.l_series_summable` indicates that the `l_series`
converges at a given point.
## Main Results
* `nat.arithmetic_function.l_series_summable_of_bounded_of_one_lt_re`: the `l_series` of a bounded
arithmetic function converges when `1 < z.re`.
* `nat.arithmetic_function.zeta_l_series_summable_iff_one_lt_re`: the `l_series` of `ζ`
(whose analytic continuation is the Riemann ζ) converges iff `1 < z.re`.
-/
noncomputable theory
open_locale big_operators
namespace nat
namespace arithmetic_function
/-- The L-series of an `arithmetic_function`. -/
def l_series (f : arithmetic_function ℂ) (z : ℂ) : ℂ := ∑'n, (f n) / (n ^ z)
/-- `f.l_series_summable z` indicates that the L-series of `f` converges at `z`. -/
def l_series_summable (f : arithmetic_function ℂ) (z : ℂ) : Prop := summable (λ n, (f n) / (n ^ z))
lemma l_series_eq_zero_of_not_l_series_summable (f : arithmetic_function ℂ) (z : ℂ) :
¬ f.l_series_summable z → f.l_series z = 0 :=
tsum_eq_zero_of_not_summable
@[simp]
lemma l_series_summable_zero {z : ℂ} : l_series_summable 0 z :=
by simp [l_series_summable, summable_zero]
theorem l_series_summable_of_bounded_of_one_lt_real {f : arithmetic_function ℂ} {m : ℝ}
(h : ∀ (n : ℕ), complex.abs (f n) ≤ m) {z : ℝ} (hz : 1 < z) :
f.l_series_summable z :=
begin
by_cases h0 : m = 0,
{ subst h0,
have hf : f = 0 := arithmetic_function.ext (λ n, complex.abs.eq_zero.1
(le_antisymm (h n) (complex.abs.nonneg _))),
simp [hf] },
refine summable_of_norm_bounded (λ (n : ℕ), m / (n ^ z)) _ _,
{ simp_rw [div_eq_mul_inv],
exact (summable_mul_left_iff h0).2 (real.summable_nat_rpow_inv.2 hz) },
{ intro n,
have hm : 0 ≤ m := le_trans (complex.abs.nonneg _) (h 0),
cases n,
{ simp [hm, real.zero_rpow (ne_of_gt (lt_trans real.zero_lt_one hz))] },
simp only [map_div₀, complex.norm_eq_abs],
apply div_le_div hm (h _) (real.rpow_pos_of_pos (nat.cast_pos.2 n.succ_pos) _) (le_of_eq _),
rw [complex.abs_cpow_real, complex.abs_cast_nat] }
end
theorem l_series_summable_of_bounded_of_one_lt_re {f : arithmetic_function ℂ} {m : ℝ}
(h : ∀ (n : ℕ), complex.abs (f n) ≤ m) {z : ℂ} (hz : 1 < z.re) :
f.l_series_summable z :=
begin
rw ← l_series_summable_iff_of_re_eq_re (complex.of_real_re z.re),
apply l_series_summable_of_bounded_of_one_lt_real h,
exact hz,
end
open_locale arithmetic_function
theorem zeta_l_series_summable_iff_one_lt_re {z : ℂ} :
l_series_summable ζ z ↔ 1 < z.re :=
begin
rw [← l_series_summable_iff_of_re_eq_re (complex.of_real_re z.re), l_series_summable,
← summable_norm_iff, ← real.summable_one_div_nat_rpow, iff_iff_eq],
by_cases h0 : z.re = 0,
{ rw [h0, ← summable_nat_add_iff 1],
swap, { apply_instance },
apply congr rfl,
ext n,
simp [n.succ_ne_zero] },
{ apply congr rfl,
ext ⟨-|n⟩,
{ simp [h0] },
simp only [cast_zero, nat_coe_apply, zeta_apply, succ_ne_zero, if_false, cast_succ, one_div,
complex.norm_eq_abs, map_inv₀, complex.abs_cpow_real, inv_inj, zero_add],
rw [←cast_one, ←cast_add, complex.abs_of_nat, cast_add, cast_one] }
end
@[simp] theorem l_series_add {f g : arithmetic_function ℂ} {z : ℂ}
(hf : f.l_series_summable z) (hg : g.l_series_summable z) :
(f + g).l_series z = f.l_series z + g.l_series z :=
begin
simp only [l_series, add_apply],
rw ← tsum_add hf hg,
apply congr rfl (funext (λ n, _)),
apply _root_.add_div,
end
end arithmetic_function
end nat
|
Loco shed, Whipsnade & Umfolozi Railway, 25 July 1976. A dismantled loco is at right, behind the shed and flat wagon. Note the mixed standard and two foot six inch gauge track in the foreground and at left. Photo by Les Tindall.
|
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_miser.h>
#include <gsl/gsl_monte_vegas.h>
/* Computation of the integral,
I = int (dx dy dz)/(2pi)^3 1/(1-cos(x)cos(y)cos(z))
over (-pi,-pi,-pi) to (+pi, +pi, +pi). The exact answer
is Gamma(1/4)^4/(4 pi^3). This example is taken from
C.Itzykson, J.M.Drouffe, "Statistical Field Theory -
Volume 1", Section 1.1, p21, which cites the original
paper M.L.Glasser, I.J.Zucker, Proc.Natl.Acad.Sci.USA 74
1800 (1977) */
/* For simplicity we compute the integral over the region
(0,0,0) -> (pi,pi,pi) and multiply by 8 */
double exact = 1.3932039296856768591842462603255;
double
g (double *k, size_t dim, void *params)
{
double A = 1.0 / (M_PI * M_PI * M_PI);
return A / (1.0 - cos (k[0]) * cos (k[1]) * cos (k[2]));
}
void
display_results (char *title, double result, double error)
{
printf ("%s ==================\n", title);
printf ("result = % .6f\n", result);
printf ("sigma = % .6f\n", error);
printf ("exact = % .6f\n", exact);
printf ("error = % .6f = %.2g sigma\n", result - exact,
fabs (result - exact) / error);
}
int
main (void)
{
double res, err;
double xl[3] = { 0, 0, 0 };
double xu[3] = { M_PI, M_PI, M_PI };
const gsl_rng_type *T;
gsl_rng *r;
gsl_monte_function G = { &g, 3, 0 };
size_t calls = 500000;
gsl_rng_env_setup ();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
{
gsl_monte_plain_state *s = gsl_monte_plain_alloc (3);
gsl_monte_plain_integrate (&G, xl, xu, 3, calls, r, s,
&res, &err);
gsl_monte_plain_free (s);
display_results ("plain", res, err);
}
{
gsl_monte_miser_state *s = gsl_monte_miser_alloc (3);
gsl_monte_miser_integrate (&G, xl, xu, 3, calls, r, s,
&res, &err);
gsl_monte_miser_free (s);
display_results ("miser", res, err);
}
{
gsl_monte_vegas_state *s = gsl_monte_vegas_alloc (3);
gsl_monte_vegas_integrate (&G, xl, xu, 3, 10000, r, s,
&res, &err);
display_results ("vegas warm-up", res, err);
printf ("converging...\n");
do
{
gsl_monte_vegas_integrate (&G, xl, xu, 3, calls/5, r, s,
&res, &err);
printf ("result = % .6f sigma = % .6f "
"chisq/dof = %.1f\n", res, err, gsl_monte_vegas_chisq (s));
}
while (fabs (gsl_monte_vegas_chisq (s) - 1.0) > 0.5);
display_results ("vegas final", res, err);
gsl_monte_vegas_free (s);
}
gsl_rng_free (r);
return 0;
}
|
function value = year_length_months_english ( y )
%*****************************************************************************80
%
%% YEAR_LENGTH_MONTHS_ENGLISH returns the number of months in an English year.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 23 September 2012
%
% Author:
%
% John Burkardt
%
% Parameters:
%
% Input, integer Y, the year to be checked.
%
% Output, integer VALUE, the number of months in the year.
%
value = 12;
return
end
|
In Building a Bug Out Bag Part I we discussed why building a Bug Out Bag is important and what type of bag to select. In Part II we discussed the Transportation Items to consider for your Bug Out Bag. Today we’ll discuss Water preparedness and Water items to consider including when building a Bug Out Bag. Remember, this is your last ditch, carry on your back, walk away from trouble Bug Out Bag…not what you hope you can get to your bug out location if your car, SUV, or semi-submersible speedboat makes it.
Water is the one thing that you won’t be able to carry three days worth with you if you are forced to resort to bugging out by foot. Three days worth of water would weigh over 25 lbs per person at one gallon per day or 12.4 gallons if you’re planning on just a half gallon per day. You should carry as much water as you can comfortably carry though. You can buy survival water boxes and pouches, but as long as there’s a functioning tap and you have canteens (or 1 to 2 liter soda bottles that you’ve washed out with soap and water) there’s no need to buy ‘survival water.’ Make sure to rotate your stored tap water frequently (no less than twice a year and more often if it is subjected to high temperatures). You can also pack bottled water but the disposable bottles aren’t very durable so make sure that you carry a more durable water container or canteen to fill up as you bug out…preferably one that’s unbreakable or even capable of boiling water in.
Boiling: Boiling should almost certainly be one of your purification options because boiling doesn’t take as many specialized supplies as the other water ‘purification’ methods . However, remember that boiling takes time, could potentially compromise your location (if you’re laying low) through light and/or smoke being visible. Make sure that you have a metal container like a canteen cup capable of holding your water as you boil it. If you don’t want to spend any money than just clean out a tin can and use it as your boil pot.
Water Purification Tablets: Tablets are available from camping stores and the camping aisles of many national chain discount stores. Read the instructions carefully and expect a ‘taste.’ Treatment generally takes about 30 minutes. Monitor your tablet’s expiration dates.
Chlorine Drops: Common, unscented liquid bleach in a dropper bottle is another treatment option that’s cheap to put together with a new dropper bottle from the drug store and that bottle of unscented liquid bleach you should have at home anyway…no, not for laundry but to purify water if you bug in. Chlorine will lose it’s effectiveness much more quickly than water purification tablets so I encourage you to spend that little extra money if you want a treatment option and but the tablets. You can read more about treating water with chlorine HERE.
Note: There are also battery operated UV treatment options like the SteriPEN. I’ve chosen to steer clear of relying on battery powered options.
Straw Type Emergency Water Filter : These are generally inexpensive, disposable filters for drinking directly from contaminated sources using the filter as a straw. I have several of these and am a little leery of their use but carry one when I’m traveling by plane and can’t carry a full Bug Out or Get Home Bag.
Water Filter Bottle : These multi-use bottles allow you to scoop water directly from the contaminated source and drink filtered water immediately. These filters tend to look a lot like a sports bottle and are relatively durable. They cost two to three times what the straw filters do but are much more durable and are worth a look. The top of the line filter bottle is the Berkey Bottle .
Backpacking Type Filters: These filters weigh a great deal more than the other filter options mentioned but are much more long lasting. With these filters will provide you a more robust capability that will last long after you reach your bug out location. Katadyn is a quality manufacturer. I use the Katadyn Hiker Pro Microfilter.
Check back tomorrow for Building a Bug Out Bag – Part IV when we’ll discuss Food Preparedness for your Bug Out Bag.
|
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau
! This file was ported from Lean 3 source module data.list.nodup
! leanprover-community/mathlib commit c227d107bbada5d0d9d20287e3282c0a7f1651a0
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Data.List.Lattice
import Mathlib.Data.List.Pairwise
import Mathlib.Data.List.Forall2
import Mathlib.Data.Set.Pairwise.Basic
/-!
# Lists with no duplicates
`List.Nodup` is defined in `Data/List/Basic`. In this file we prove various properties of this
predicate.
-/
universe u v
open Nat Function
variable {α : Type u} {β : Type v} {l l₁ l₂ : List α} {r : α → α → Prop} {a b : α}
namespace List
@[simp]
theorem forall_mem_ne {a : α} {l : List α} : (∀ a' : α, a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨fun h m => h _ m rfl, fun h _ m e => h (e.symm ▸ m)⟩
#align list.forall_mem_ne List.forall_mem_ne
@[simp]
theorem nodup_nil : @Nodup α [] :=
Pairwise.nil
#align list.nodup_nil List.nodup_nil
@[simp]
theorem nodup_cons {a : α} {l : List α} : Nodup (a :: l) ↔ a ∉ l ∧ Nodup l := by
simp only [Nodup, pairwise_cons, forall_mem_ne]
#align list.nodup_cons List.nodup_cons
protected theorem Pairwise.nodup {l : List α} {r : α → α → Prop} [IsIrrefl α r] (h : Pairwise r l) :
Nodup l :=
h.imp ne_of_irrefl
#align list.pairwise.nodup List.Pairwise.nodup
theorem rel_nodup {r : α → β → Prop} (hr : Relator.BiUnique r) : (Forall₂ r ⇒ (· ↔ ·)) Nodup Nodup
| _, _, Forall₂.nil => by simp only [nodup_nil]
| _, _, Forall₂.cons hab h => by
simpa only [nodup_cons] using
Relator.rel_and (Relator.rel_not (rel_mem hr hab h)) (rel_nodup hr h)
#align list.rel_nodup List.rel_nodup
protected theorem Nodup.cons (ha : a ∉ l) (hl : Nodup l) : Nodup (a :: l) :=
nodup_cons.2 ⟨ha, hl⟩
#align list.nodup.cons List.Nodup.cons
theorem nodup_singleton (a : α) : Nodup [a] :=
pairwise_singleton _ _
#align list.nodup_singleton List.nodup_singleton
theorem Nodup.of_cons (h : Nodup (a :: l)) : Nodup l :=
(nodup_cons.1 h).2
#align list.nodup.of_cons List.Nodup.of_cons
theorem Nodup.not_mem (h : (a :: l).Nodup) : a ∉ l :=
(nodup_cons.1 h).1
#align list.nodup.not_mem List.Nodup.not_mem
theorem not_nodup_cons_of_mem : a ∈ l → ¬Nodup (a :: l) :=
imp_not_comm.1 Nodup.not_mem
#align list.not_nodup_cons_of_mem List.not_nodup_cons_of_mem
protected theorem Nodup.sublist : l₁ <+ l₂ → Nodup l₂ → Nodup l₁ :=
Pairwise.sublist
#align list.nodup.sublist List.Nodup.sublist
theorem not_nodup_pair (a : α) : ¬Nodup [a, a] :=
not_nodup_cons_of_mem <| mem_singleton_self _
#align list.not_nodup_pair List.not_nodup_pair
theorem nodup_iff_sublist {l : List α} : Nodup l ↔ ∀ a, ¬[a, a] <+ l :=
⟨fun d a h => not_nodup_pair a (d.sublist h),
by
induction' l with a l IH <;> intro h; · exact nodup_nil
exact
(IH fun a s => h a <| sublist_cons_of_sublist _ s).cons fun al =>
h a <| (singleton_sublist.2 al).cons_cons _⟩
#align list.nodup_iff_sublist List.nodup_iff_sublist
--Porting note: new theorem
theorem nodup_iff_injective_get {l : List α} :
Nodup l ↔ Function.Injective l.get :=
pairwise_iff_get.trans
⟨fun h i j hg => by
cases' i with i hi; cases' j with j hj
rcases lt_trichotomy i j with (hij | rfl | hji)
. exact (h ⟨i, hi⟩ ⟨j, hj⟩ hij hg).elim
. rfl
. exact (h ⟨j, hj⟩ ⟨i, hi⟩ hji hg.symm).elim,
fun hinj i j hij h => Nat.ne_of_lt hij (Fin.veq_of_eq (hinj h))⟩
set_option linter.deprecated false in
@[deprecated nodup_iff_injective_get]
theorem nodup_iff_nthLe_inj {l : List α} :
Nodup l ↔ ∀ i j h₁ h₂, nthLe l i h₁ = nthLe l j h₂ → i = j :=
nodup_iff_injective_get.trans
⟨fun hinj _ _ _ _ h => congr_arg Fin.val (hinj h),
fun hinj i j h => Fin.eq_of_veq (hinj i j i.2 j.2 h)⟩
#align list.nodup_iff_nth_le_inj List.nodup_iff_nthLe_inj
theorem Nodup.get_inj_iff {l : List α} (h : Nodup l) {i j : Fin l.length} :
l.get i = l.get j ↔ i = j :=
(nodup_iff_injective_get.1 h).eq_iff
set_option linter.deprecated false in
@[deprecated Nodup.get_inj_iff]
theorem Nodup.nthLe_inj_iff {l : List α} (h : Nodup l) {i j : ℕ} (hi : i < l.length)
(hj : j < l.length) : l.nthLe i hi = l.nthLe j hj ↔ i = j :=
⟨nodup_iff_nthLe_inj.mp h _ _ _ _, by simp (config := { contextual := true })⟩
#align list.nodup.nth_le_inj_iff List.Nodup.nthLe_inj_iff
theorem nodup_iff_get?_ne_get? {l : List α} :
l.Nodup ↔ ∀ i j : ℕ, i < j → j < l.length → l.get? i ≠ l.get? j := by
rw [Nodup, pairwise_iff_get]
constructor
. intro h i j hij hj
rw [get?_eq_get (lt_trans hij hj), get?_eq_get hj, Ne.def, Option.some_inj]
exact h _ _ hij
. intro h i j hij
rw [Ne.def, ← Option.some_inj, ← get?_eq_get, ← get?_eq_get]
exact h i j hij j.2
#align list.nodup_iff_nth_ne_nth List.nodup_iff_get?_ne_get?
theorem Nodup.ne_singleton_iff {l : List α} (h : Nodup l) (x : α) :
l ≠ [x] ↔ l = [] ∨ ∃ y ∈ l, y ≠ x := by
induction' l with hd tl hl
· simp
· specialize hl h.of_cons
by_cases hx : tl = [x]
· simpa [hx, and_comm, and_or_left] using h
· rw [← Ne.def, hl] at hx
rcases hx with (rfl | ⟨y, hy, hx⟩)
· simp
· suffices ∃ (y : α) (_ : y ∈ hd :: tl), y ≠ x by simpa [ne_nil_of_mem hy]
exact ⟨y, mem_cons_of_mem _ hy, hx⟩
#align list.nodup.ne_singleton_iff List.Nodup.ne_singleton_iff
theorem not_nodup_of_get_eq_of_ne (xs : List α) (n m : Fin xs.length)
(h : xs.get n = xs.get m) (hne : n ≠ m) : ¬Nodup xs := by
rw [nodup_iff_injective_get]
exact fun hinj => hne (hinj h)
set_option linter.deprecated false in
@[deprecated not_nodup_of_get_eq_of_ne]
theorem nthLe_eq_of_ne_imp_not_nodup (xs : List α) (n m : ℕ) (hn : n < xs.length)
(hm : m < xs.length) (h : xs.nthLe n hn = xs.nthLe m hm) (hne : n ≠ m) : ¬Nodup xs := by
rw [nodup_iff_nthLe_inj]
simp only [exists_prop, exists_and_right, not_forall]
exact ⟨n, m, ⟨hn, hm, h⟩, hne⟩
#align list.nth_le_eq_of_ne_imp_not_nodup List.nthLe_eq_of_ne_imp_not_nodup
--Porting note: new theorem
theorem get_indexOf [DecidableEq α] {l : List α} (H : Nodup l) (i : Fin l.length) :
indexOf (get l i) l = i :=
suffices (⟨indexOf (get l i) l, indexOf_lt_length.2 (get_mem _ _ _)⟩ : Fin l.length) = i
from Fin.veq_of_eq this
nodup_iff_injective_get.1 H (by simp)
set_option linter.deprecated false in
@[simp, deprecated get_indexOf]
theorem nthLe_index_of [DecidableEq α] {l : List α} (H : Nodup l) (n h) :
indexOf (nthLe l n h) l = n :=
nodup_iff_nthLe_inj.1 H _ _ _ h <| indexOf_nthLe <| indexOf_lt_length.2 <| nthLe_mem _ _ _
#align list.nth_le_index_of List.nthLe_index_of
theorem nodup_iff_count_le_one [DecidableEq α] {l : List α} : Nodup l ↔ ∀ a, count a l ≤ 1 :=
nodup_iff_sublist.trans <|
forall_congr' fun a =>
have : [a, a] <+ l ↔ 1 < count a l := (@le_count_iff_replicate_sublist _ _ _ 2 _).symm
(not_congr this).trans not_lt
#align list.nodup_iff_count_le_one List.nodup_iff_count_le_one
theorem nodup_replicate (a : α) : ∀ {n : ℕ}, Nodup (replicate n a) ↔ n ≤ 1
| 0 => by simp [Nat.zero_le]
| 1 => by simp
| n + 2 =>
iff_of_false
(fun H => nodup_iff_sublist.1 H a ((replicate_sublist_replicate _).2 (Nat.le_add_left 2 n)))
(not_le_of_lt <| Nat.le_add_left 2 n)
#align list.nodup_replicate List.nodup_replicate
@[simp]
theorem count_eq_one_of_mem [DecidableEq α] {a : α} {l : List α} (d : Nodup l) (h : a ∈ l) :
count a l = 1 :=
_root_.le_antisymm (nodup_iff_count_le_one.1 d a) (Nat.succ_le_of_lt (count_pos.2 h))
#align list.count_eq_one_of_mem List.count_eq_one_of_mem
theorem count_eq_of_nodup [DecidableEq α] {a : α} {l : List α} (d : Nodup l) :
count a l = if a ∈ l then 1 else 0 := by
split_ifs with h
· exact count_eq_one_of_mem d h
· exact count_eq_zero_of_not_mem h
#align list.count_eq_of_nodup List.count_eq_of_nodup
theorem Nodup.of_append_left : Nodup (l₁ ++ l₂) → Nodup l₁ :=
Nodup.sublist (sublist_append_left l₁ l₂)
#align list.nodup.of_append_left List.Nodup.of_append_left
theorem Nodup.of_append_right : Nodup (l₁ ++ l₂) → Nodup l₂ :=
Nodup.sublist (sublist_append_right l₁ l₂)
#align list.nodup.of_append_right List.Nodup.of_append_right
theorem nodup_append {l₁ l₂ : List α} : Nodup (l₁ ++ l₂) ↔ Nodup l₁ ∧ Nodup l₂ ∧ Disjoint l₁ l₂ :=
by simp only [Nodup, pairwise_append, disjoint_iff_ne]
#align list.nodup_append List.nodup_append
theorem disjoint_of_nodup_append {l₁ l₂ : List α} (d : Nodup (l₁ ++ l₂)) : Disjoint l₁ l₂ :=
(nodup_append.1 d).2.2
#align list.disjoint_of_nodup_append List.disjoint_of_nodup_append
theorem Nodup.append (d₁ : Nodup l₁) (d₂ : Nodup l₂) (dj : Disjoint l₁ l₂) : Nodup (l₁ ++ l₂) :=
nodup_append.2 ⟨d₁, d₂, dj⟩
#align list.nodup.append List.Nodup.append
theorem nodup_middle {a : α} {l₁ l₂ : List α} :
Nodup (l₁ ++ a :: l₂) ↔ Nodup (a :: (l₁ ++ l₂)) := by
simp only [nodup_append, not_or, and_left_comm, and_assoc, nodup_cons, mem_append,
disjoint_cons_right]
#align list.nodup_middle List.nodup_middle
theorem Nodup.of_map (f : α → β) {l : List α} : Nodup (map f l) → Nodup l :=
(Pairwise.of_map f) fun _ _ => mt <| congr_arg f
#align list.nodup.of_map List.Nodup.of_mapₓ -- Porting note: different universe order
theorem Nodup.map_on {f : α → β} (H : ∀ x ∈ l, ∀ y ∈ l, f x = f y → x = y) (d : Nodup l) :
(map f l).Nodup :=
Pairwise.map _ (fun a b ⟨ma, mb, n⟩ e => n (H a ma b mb e)) (Pairwise.and_mem.1 d)
#align list.nodup.map_on List.Nodup.map_onₓ -- Porting note: different universe order
theorem inj_on_of_nodup_map {f : α → β} {l : List α} (d : Nodup (map f l)) :
∀ ⦃x⦄, x ∈ l → ∀ ⦃y⦄, y ∈ l → f x = f y → x = y := by
induction' l with hd tl ih
· simp
· simp only [map, nodup_cons, mem_map, not_exists, not_and, ← Ne.def] at d
simp only [mem_cons]
rintro _ (rfl | h₁) _ (rfl | h₂) h₃
· rfl
· apply (d.1 _ h₂ h₃.symm).elim
· apply (d.1 _ h₁ h₃).elim
· apply ih d.2 h₁ h₂ h₃
#align list.inj_on_of_nodup_map List.inj_on_of_nodup_map
theorem nodup_map_iff_inj_on {f : α → β} {l : List α} (d : Nodup l) :
Nodup (map f l) ↔ ∀ x ∈ l, ∀ y ∈ l, f x = f y → x = y :=
⟨inj_on_of_nodup_map, fun h => d.map_on h⟩
#align list.nodup_map_iff_inj_on List.nodup_map_iff_inj_on
protected theorem Nodup.map {f : α → β} (hf : Injective f) : Nodup l → Nodup (map f l) :=
Nodup.map_on fun _ _ _ _ h => hf h
#align list.nodup.map List.Nodup.map -- Porting note: different universe order
theorem nodup_map_iff {f : α → β} {l : List α} (hf : Injective f) : Nodup (map f l) ↔ Nodup l :=
⟨Nodup.of_map _, Nodup.map hf⟩
#align list.nodup_map_iff List.nodup_map_iff
@[simp]
theorem nodup_attach {l : List α} : Nodup (attach l) ↔ Nodup l :=
⟨fun h => attach_map_val l ▸ h.map fun _ _ => Subtype.eq, fun h =>
Nodup.of_map Subtype.val ((attach_map_val l).symm ▸ h)⟩
#align list.nodup_attach List.nodup_attach
alias nodup_attach ↔ Nodup.of_attach Nodup.attach
#align list.nodup.attach List.Nodup.attach
#align list.nodup.of_attach List.Nodup.of_attach
--Porting note: commented out
--attribute [protected] nodup.attach
theorem Nodup.pmap {p : α → Prop} {f : ∀ a, p a → β} {l : List α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : Nodup l) : Nodup (pmap f l H) := by
rw [pmap_eq_map_attach]
exact h.attach.map fun ⟨a, ha⟩ ⟨b, hb⟩ h => by congr; exact hf a (H _ ha) b (H _ hb) h
#align list.nodup.pmap List.Nodup.pmap
theorem Nodup.filter (p : α → Bool) {l} : Nodup l → Nodup (filter p l) := by
simpa using Pairwise.filter (fun a ↦ p a)
#align list.nodup.filter List.Nodup.filter
@[simp]
theorem nodup_reverse {l : List α} : Nodup (reverse l) ↔ Nodup l :=
pairwise_reverse.trans <| by simp only [Nodup, Ne.def, eq_comm]
#align list.nodup_reverse List.nodup_reverse
theorem Nodup.erase_eq_filter [DecidableEq α] {l} (d : Nodup l) (a : α) :
l.erase a = l.filter (· ≠ a) := by
induction' d with b l m _ IH; · rfl
by_cases h : b = a
· subst h
rw [erase_cons_head, filter_cons_of_neg _ (by simp)]
symm
rw [filter_eq_self]
simpa [@eq_comm α] using m
· rw [erase_cons_tail _ h, filter_cons_of_pos, IH]
simp [h]
#align list.nodup.erase_eq_filter List.Nodup.erase_eq_filter
theorem Nodup.erase [DecidableEq α] (a : α) : Nodup l → Nodup (l.erase a) :=
Nodup.sublist <| erase_sublist _ _
#align list.nodup.erase List.Nodup.erase
theorem Nodup.diff [DecidableEq α] : l₁.Nodup → (l₁.diff l₂).Nodup :=
Nodup.sublist <| diff_sublist _ _
#align list.nodup.diff List.Nodup.diff
theorem Nodup.mem_erase_iff [DecidableEq α] (d : Nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by
rw [d.erase_eq_filter, mem_filter, and_comm, decide_eq_true_iff]
#align list.nodup.mem_erase_iff List.Nodup.mem_erase_iff
theorem Nodup.not_mem_erase [DecidableEq α] (h : Nodup l) : a ∉ l.erase a := fun H =>
(h.mem_erase_iff.1 H).1 rfl
#align list.nodup.not_mem_erase List.Nodup.not_mem_erase
theorem nodup_join {L : List (List α)} :
Nodup (join L) ↔ (∀ l ∈ L, Nodup l) ∧ Pairwise Disjoint L := by
simp only [Nodup, pairwise_join, disjoint_left.symm, forall_mem_ne]
#align list.nodup_join List.nodup_join
theorem nodup_bind {l₁ : List α} {f : α → List β} :
Nodup (l₁.bind f) ↔
(∀ x ∈ l₁, Nodup (f x)) ∧ Pairwise (fun a b : α => Disjoint (f a) (f b)) l₁ := by
simp only [List.bind, nodup_join, pairwise_map, and_comm, and_left_comm, mem_map, exists_imp,
and_imp]
rw [show (∀ (l : List β) (x : α), f x = l → x ∈ l₁ → Nodup l) ↔ ∀ x : α, x ∈ l₁ → Nodup (f x)
from forall_swap.trans <| forall_congr' fun _ => forall_eq']
#align list.nodup_bind List.nodup_bind
protected theorem Nodup.product {l₂ : List β} (d₁ : l₁.Nodup) (d₂ : l₂.Nodup) :
(l₁.product l₂).Nodup :=
nodup_bind.2
⟨fun a _ => d₂.map <| LeftInverse.injective fun b => (rfl : (a, b).2 = b),
d₁.imp fun {a₁ a₂} n x h₁ h₂ => by
rcases mem_map.1 h₁ with ⟨b₁, _, rfl⟩
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩
exact n rfl⟩
#align list.nodup.product List.Nodup.product
theorem Nodup.sigma {σ : α → Type _} {l₂ : ∀ a , List (σ a)} (d₁ : Nodup l₁)
(d₂ : ∀ a , Nodup (l₂ a)) : (l₁.sigma l₂).Nodup :=
nodup_bind.2
⟨fun a _ => (d₂ a).map fun b b' h => by injection h with _ h,
d₁.imp fun {a₁ a₂} n x h₁ h₂ => by
rcases mem_map.1 h₁ with ⟨b₁, _, rfl⟩
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩
exact n rfl⟩
#align list.nodup.sigma List.Nodup.sigma
protected theorem Nodup.filterMap {f : α → Option β} (h : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') :
Nodup l → Nodup (filterMap f l) :=
(Pairwise.filter_map f) @fun a a' n b bm b' bm' e => n <| h a a' b' (by rw [← e]; exact bm) bm'
#align list.nodup.filter_map List.Nodup.filterMap
protected theorem Nodup.concat (h : a ∉ l) (h' : l.Nodup) : (l.concat a).Nodup := by
rw [concat_eq_append]; exact h'.append (nodup_singleton _) (disjoint_singleton.2 h)
#align list.nodup.concat List.Nodup.concat
theorem Nodup.insert [DecidableEq α] (h : l.Nodup) : (l.insert a).Nodup :=
if h' : a ∈ l then by rw [insert_of_mem h']; exact h
else by rw [insert_of_not_mem h', nodup_cons]; constructor <;> assumption
#align list.nodup.insert List.Nodup.insert
theorem Nodup.union [DecidableEq α] (l₁ : List α) (h : Nodup l₂) : (l₁ ∪ l₂).Nodup := by
induction' l₁ with a l₁ ih generalizing l₂
· exact h
· exact (ih h).insert
#align list.nodup.union List.Nodup.union
theorem Nodup.inter [DecidableEq α] (l₂ : List α) : Nodup l₁ → Nodup (l₁ ∩ l₂) :=
Nodup.filter _
#align list.nodup.inter List.Nodup.inter
theorem Nodup.diff_eq_filter [DecidableEq α] :
∀ {l₁ l₂ : List α} (_ : l₁.Nodup), l₁.diff l₂ = l₁.filter (· ∉ l₂)
| l₁, [], _ => by simp
| l₁, a :: l₂, hl₁ => by
rw [diff_cons, (hl₁.erase _).diff_eq_filter, hl₁.erase_eq_filter, filter_filter]
simp only [decide_not, Bool.not_eq_true', decide_eq_false_iff_not, ne_eq, and_comm,
Bool.decide_and, find?, mem_cons, not_or]
#align list.nodup.diff_eq_filter List.Nodup.diff_eq_filter
theorem Nodup.mem_diff_iff [DecidableEq α] (hl₁ : l₁.Nodup) : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by
rw [hl₁.diff_eq_filter, mem_filter, decide_eq_true_iff]
#align list.nodup.mem_diff_iff List.Nodup.mem_diff_iff
protected theorem Nodup.set :
∀ {l : List α} {n : ℕ} {a : α} (_ : l.Nodup) (_ : a ∉ l), (l.set n a).Nodup
| [], _, _, _, _ => nodup_nil
| _ :: _, 0, _, hl, ha => nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩
| _ :: _, _ + 1, _, hl, ha =>
nodup_cons.2
⟨fun h =>
(mem_or_eq_of_mem_set h).elim (nodup_cons.1 hl).1 fun hba => ha (hba ▸ mem_cons_self _ _),
hl.of_cons.set (mt (mem_cons_of_mem _) ha)⟩
#align list.nodup.update_nth List.Nodup.set
theorem Nodup.map_update [DecidableEq α] {l : List α} (hl : l.Nodup) (f : α → β) (x : α) (y : β) :
l.map (Function.update f x y) =
if x ∈ l then (l.map f).set (l.indexOf x) y else l.map f := by
induction' l with hd tl ihl; · simp
rw [nodup_cons] at hl
simp only [mem_cons, map, ihl hl.2]
by_cases H : hd = x
· subst hd
simp [set, hl.1]
· simp [Ne.symm H, H, set, ← apply_ite (cons (f hd))]
#align list.nodup.map_update List.Nodup.map_update
theorem Nodup.pairwise_of_forall_ne {l : List α} {r : α → α → Prop} (hl : l.Nodup)
(h : ∀ a ∈ l, ∀ b ∈ l, a ≠ b → r a b) : l.Pairwise r := by
classical
refine' pairwise_of_reflexive_on_dupl_of_forall_ne _ h
intro x hx
rw [nodup_iff_count_le_one] at hl
exact absurd (hl x) hx.not_le
#align list.nodup.pairwise_of_forall_ne List.Nodup.pairwise_of_forall_ne
theorem Nodup.pairwise_of_set_pairwise {l : List α} {r : α → α → Prop} (hl : l.Nodup)
(h : { x | x ∈ l }.Pairwise r) : l.Pairwise r :=
hl.pairwise_of_forall_ne h
#align list.nodup.pairwise_of_set_pairwise List.Nodup.pairwise_of_set_pairwise
@[simp]
theorem Nodup.pairwise_coe [IsSymm α r] (hl : l.Nodup)
: { a | a ∈ l }.Pairwise r ↔ l.Pairwise r := by
induction' l with a l ih
· simp
rw [List.nodup_cons] at hl
have : ∀ b ∈ l, ¬a = b → r a b ↔ r a b := fun b hb =>
imp_iff_right (ne_of_mem_of_not_mem hb hl.1).symm
simp [Set.setOf_or, Set.pairwise_insert_of_symmetric (@symm_of _ r _), ih hl.2, and_comm,
forall₂_congr this]
#align list.nodup.pairwise_coe List.Nodup.pairwise_coe
--Porting note: new theorem
theorem Nodup.take_eq_filter_mem [DecidableEq α] :
∀ {l : List α} {n : ℕ} (_ : l.Nodup), l.take n = l.filter (. ∈ l.take n)
| [], n, _ => by simp
| b::l, 0, _ => by simp
| b::l, n+1, hl => by
rw [take_cons, Nodup.take_eq_filter_mem (Nodup.of_cons hl), List.filter_cons_of_pos _ (by simp)]
congr 1
refine' List.filter_congr' _
intro x hx
have : x ≠ b := fun h => (nodup_cons.1 hl).1 (h ▸ hx)
simp (config := {contextual := true}) [List.mem_filter, this, hx]
end List
theorem Option.toList_nodup {α} : ∀ o : Option α, o.toList.Nodup
| none => List.nodup_nil
| some x => List.nodup_singleton x
#align option.to_list_nodup Option.toList_nodup
|
-- Andreas, 2016-10-14, issue #2257, reported by m0davis
-- Bisected by Nisse.
{-# OPTIONS --allow-unsolved-metas #-}
-- {-# OPTIONS -v tc.ip:20 #-}
-- {-# OPTIONS -v tc:20 #-}
record R (A : Set) : Set₁ where
field
a : A
F : ∀ {f} → Set
foo : Set
foo = ∀ {f} → {!!}
field
bar : Set
|
State Before: α : Type u_1
β : Type ?u.187524
inst✝¹ : LinearOrder α
inst✝ : LinearOrder β
f : α → β
a a₁ a₂ b b₁ b₂ c d : α
⊢ Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) State After: α : Type u_1
β : Type ?u.187524
inst✝¹ : LinearOrder α
inst✝ : LinearOrder β
f : α → β
a a₁ a₂ b b₁ b₂ c d : α
⊢ Ioi a₁ ∩ Iio b₁ ∩ (Ioi a₂ ∩ Iio b₂) = Ioi a₁ ∩ Ioi a₂ ∩ (Iio b₁ ∩ Iio b₂) Tactic: simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm] State Before: α : Type u_1
β : Type ?u.187524
inst✝¹ : LinearOrder α
inst✝ : LinearOrder β
f : α → β
a a₁ a₂ b b₁ b₂ c d : α
⊢ Ioi a₁ ∩ Iio b₁ ∩ (Ioi a₂ ∩ Iio b₂) = Ioi a₁ ∩ Ioi a₂ ∩ (Iio b₁ ∩ Iio b₂) State After: no goals Tactic: ac_rfl
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-|
Module : Grenade.Layers.Tanh
Description : Hyperbolic tangent nonlinear layer
Copyright : (c) Huw Campbell, 2016-2017
License : BSD2
Stability : experimental
-}
module Grenade.Layers.Tanh
( Tanh(..)
, SpecTanh (..)
, specTanh1D
, specTanh2D
, specTanh3D
, specTanh
, tanhLayer
) where
import Control.DeepSeq (NFData (..))
import Data.Constraint (Dict (..))
import Data.Reflection (reifyNat)
import Data.Serialize
import Data.Singletons
import GHC.Generics (Generic)
import GHC.TypeLits
import qualified Numeric.LinearAlgebra.Static as LAS
import Unsafe.Coerce (unsafeCoerce)
import Grenade.Core
import Grenade.Dynamic
import Grenade.Dynamic.Internal.Build
import Grenade.Utils.Conversion
import Grenade.Utils.Vector
-- | A Tanh layer.
-- A layer which can act between any shape of the same dimension, performing a tanh function.
data Tanh = Tanh
deriving (Generic,NFData,Show)
instance UpdateLayer Tanh where
type Gradient Tanh = ()
runUpdate _ _ _ = Tanh
instance RandomLayer Tanh where
createRandomWith _ _ = return Tanh
instance Serialize Tanh where
put _ = return ()
get = return Tanh
instance (a ~ b, SingI a) => Layer Tanh a b where
type Tape Tanh a b = S a
-- runForwards _ (S1DV v) = (S1DV v, S1DV $ mapVectorInPlace tanh v) -- This is inplace replacement!
-- runForwards _ (S2DV v) = (S2DV v, S2DV $ mapVectorInPlace tanh v) -- This is inplace replacement!
runForwards _ a = (a, tanh a)
runBackwards _ (S1DV v) (S1DV gs) = ((), S1DV $ zipWithVector (\t g -> max 0.005 (1 - (tanh t) ^ (2 :: Int)) * g) v gs)
runBackwards _ (S2DV v) (S2DV gs) = ((), S2DV $ zipWithVector (\t g -> max 0.005 (1 - (tanh t) ^ (2 :: Int)) * g) v gs)
runBackwards _ (S1D a) (S1D g)= ((), S1D $ LAS.dvmap (max 0.005) (tanh' a) * g)
runBackwards _ (S2D a) (S2D g)= ((), S2D $ LAS.dmmap (max 0.005) (tanh' a) * g)
runBackwards _ (S3D a) (S3D g)= ((), S3D $ LAS.dmmap (max 0.005) (tanh' a) * g)
runBackwards l x y = runBackwards l x (toLayerShape x y)
-- runBackwards _ a g = ((), tanh' a * g)
tanh' :: (Floating a) => a -> a
tanh' t = 1 - s ^ (2 :: Int) where s = tanh t
-------------------- DynamicNetwork instance --------------------
instance FromDynamicLayer Tanh where
fromDynamicLayer inp _ _ = SpecNetLayer $ SpecTanh (tripleFromSomeShape inp)
instance ToDynamicLayer SpecTanh where
toDynamicLayer _ _ (SpecTanh (rows, cols, depth)) =
reifyNat rows $ \(_ :: (KnownNat rows) => Proxy rows) ->
reifyNat cols $ \(_ :: (KnownNat cols) => Proxy cols) ->
reifyNat depth $ \(_ :: (KnownNat depth) => Proxy depth) ->
case (rows, cols, depth) of
(_, 1, 1) -> return $ SpecLayer Tanh (sing :: Sing ('D1 rows)) (sing :: Sing ('D1 rows))
(_, _, 1) -> return $ SpecLayer Tanh (sing :: Sing ('D2 rows cols)) (sing :: Sing ('D2 rows cols))
_ -> case (unsafeCoerce (Dict :: Dict()) :: Dict (KnownNat (rows GHC.TypeLits.* depth))) of
Dict -> return $ SpecLayer Tanh (sing :: Sing ('D3 rows cols depth)) (sing :: Sing ('D3 rows cols depth))
-- | Create a specification for a Tanh layer.
specTanh1D :: Integer -> SpecNet
specTanh1D i = specTanh3D (i, 1, 1)
-- | Create a specification for a Tanh layer.
specTanh2D :: (Integer, Integer) -> SpecNet
specTanh2D (i, j) = specTanh3D (i, j, 1)
-- | Create a specification for a Tanh layer.
specTanh3D :: (Integer, Integer, Integer) -> SpecNet
specTanh3D = SpecNetLayer . SpecTanh
-- | Create a specification for a Tanh layer.
specTanh :: (Integer, Integer, Integer) -> SpecNet
specTanh = SpecNetLayer . SpecTanh
-- | Add a Tanh layer to your build.
tanhLayer :: BuildM ()
tanhLayer = buildGetLastLayerOut >>= buildAddSpec . SpecNetLayer . SpecTanh
-------------------- GNum instances --------------------
instance GNum Tanh where
_ |* Tanh = Tanh
_ |+ Tanh = Tanh
sumG _ = Tanh
|
theory Ex030
imports Main
begin
lemma "(A \<longrightarrow> B \<longrightarrow> C) \<longleftrightarrow> (\<not>C \<longrightarrow> A \<longrightarrow> \<not>B)"
proof -
{
assume a:"A \<longrightarrow> B \<longrightarrow> C"
{
assume b:"\<not>C"
{
assume A
with a have c:"B \<longrightarrow> C" by (rule mp)
{
assume B
with c have C by (rule mp)
with b have False by contradiction
}
hence "\<not>B" by (rule notI)
}
hence "A \<longrightarrow> \<not>B" by (rule impI)
}
hence "\<not>C \<longrightarrow> A \<longrightarrow> \<not>B" by (rule impI)
}
moreover
{
assume d:"\<not>C \<longrightarrow> A \<longrightarrow> \<not>B"
{
assume e:A
{
assume f:B
{
assume "\<not>C"
with d have "A \<longrightarrow> \<not>B" by (rule mp)
from this and e have "\<not>B" by (rule mp)
with f have False by contradiction
}
hence "\<not>\<not>C" by (rule notI)
hence C by (rule notnotD)
}
hence "B \<longrightarrow> C" by (rule impI)
}
hence "A \<longrightarrow> B \<longrightarrow> C" by (rule impI)
}
ultimately show ?thesis by (rule iffI)
qed
|
/-
Copyright (c) 2019 Jean Lo. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jean Lo, Bhavik Mehta, Yaël Dillies
-/
import analysis.convex.function
import analysis.convex.star
import analysis.normed_space.ordered
import analysis.normed_space.pointwise
import data.real.pointwise
import topology.algebra.filter_basis
import topology.algebra.uniform_filter_basis
import data.real.sqrt
/-!
# Seminorms and Local Convexity
This file defines absorbent sets, balanced sets, seminorms and the Minkowski functional.
An absorbent set is one that "surrounds" the origin. The idea is made precise by requiring that any
point belongs to all large enough scalings of the set. This is the vector world analog of a
topological neighborhood of the origin.
A balanced set is one that is everywhere around the origin. This means that `a • s ⊆ s` for all `a`
of norm less than `1`.
A seminorm is a function to the reals which is positive-semidefinite, absolutely homogeneous, and
subadditive. They are closely related to convex sets and a topological vector space is locally
convex if and only if its topology is induced by a family of seminorms.
The Minkowski functional of a set `s` is the function which associates each point to how much you
need to scale `s` for `x` to be inside it. When `s` is symmetric, convex and absorbent, its gauge is
a seminorm. Reciprocally, any seminorm arises as the gauge of some set, namely its unit ball. This
induces the equivalence of seminorms and locally convex topological vector spaces.
## Main declarations
For a vector space over a normed field:
* `absorbent`: A set `s` is absorbent if every point eventually belongs to all large scalings of
`s`.
* `balanced`: A set `s` is balanced if `a • s ⊆ s` for all `a` of norm less than `1`.
* `seminorm`: A function to the reals that is positive-semidefinite, absolutely homogeneous, and
subadditive.
* `norm_seminorm 𝕜 E`: The norm on `E` as a seminorm.
* `gauge`: Aka Minkowksi functional. `gauge s x` is the least (actually, an infimum) `r` such
that `x ∈ r • s`.
* `gauge_seminorm`: The Minkowski functional as a seminorm, when `s` is symmetric, convex and
absorbent.
## References
* [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966]
## TODO
Define and show equivalence of two notions of local convexity for a
topological vector space over ℝ or ℂ: that it has a local base of
balanced convex absorbent sets, and that it carries the initial
topology induced by a family of seminorms.
Prove the properties of balanced and absorbent sets of a real vector space.
## Tags
absorbent, balanced, seminorm, Minkowski functional, gauge, locally convex, LCTVS
-/
/-!
### Set Properties
Absorbent and balanced sets in a vector space over a normed field.
-/
open normed_field set
open_locale pointwise topological_space nnreal big_operators
variables {R 𝕜 𝕝 E F G ι ι' : Type*}
section semi_normed_ring
variables [semi_normed_ring 𝕜]
section has_scalar
variables (𝕜) [has_scalar 𝕜 E]
/-- A set `A` absorbs another set `B` if `B` is contained in all scalings of
`A` by elements of sufficiently large norms. -/
def absorbs (A B : set E) := ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → B ⊆ a • A
/-- A set is absorbent if it absorbs every singleton. -/
def absorbent (A : set E) := ∀ x, ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → x ∈ a • A
/-- A set `A` is balanced if `a • A` is contained in `A` whenever `a`
has norm less than or equal to one. -/
def balanced (A : set E) := ∀ a : 𝕜, ∥a∥ ≤ 1 → a • A ⊆ A
variables {𝕜} {A B : set E}
lemma balanced_univ : balanced 𝕜 (univ : set E) := λ a ha, subset_univ _
lemma balanced.union (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∪ B) :=
begin
intros a ha t ht,
rw [smul_set_union] at ht,
exact ht.imp (λ x, hA _ ha x) (λ x, hB _ ha x),
end
end has_scalar
section add_comm_group
variables [add_comm_group E] [module 𝕜 E] {s t u v A B : set E}
lemma balanced.inter (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∩ B) :=
begin
rintro a ha _ ⟨x, ⟨hx₁, hx₂⟩, rfl⟩,
exact ⟨hA _ ha ⟨_, hx₁, rfl⟩, hB _ ha ⟨_, hx₂, rfl⟩⟩,
end
lemma balanced.add (hA₁ : balanced 𝕜 A) (hA₂ : balanced 𝕜 B) : balanced 𝕜 (A + B) :=
begin
rintro a ha _ ⟨_, ⟨x, y, hx, hy, rfl⟩, rfl⟩,
rw smul_add,
exact ⟨_, _, hA₁ _ ha ⟨_, hx, rfl⟩, hA₂ _ ha ⟨_, hy, rfl⟩, rfl⟩,
end
lemma absorbs.mono (hs : absorbs 𝕜 s u) (hst : s ⊆ t) (hvu : v ⊆ u) : absorbs 𝕜 t v :=
let ⟨r, hr, h⟩ := hs in ⟨r, hr, λ a ha, hvu.trans $ (h _ ha).trans $ smul_set_mono hst⟩
lemma absorbs.mono_left (hs : absorbs 𝕜 s u) (h : s ⊆ t) : absorbs 𝕜 t u := hs.mono h subset.rfl
lemma absorbs.mono_right (hs : absorbs 𝕜 s u) (h : v ⊆ u) : absorbs 𝕜 s v := hs.mono subset.rfl h
lemma absorbs.union (hu : absorbs 𝕜 s u) (hv : absorbs 𝕜 s v) : absorbs 𝕜 s (u ∪ v) :=
begin
obtain ⟨a, ha, hu⟩ := hu,
obtain ⟨b, hb, hv⟩ := hv,
exact ⟨max a b, lt_max_of_lt_left ha,
λ c hc, union_subset (hu _ $ le_of_max_le_left hc) (hv _ $ le_of_max_le_right hc)⟩,
end
@[simp] lemma absorbs_union : absorbs 𝕜 s (u ∪ v) ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 s v :=
⟨λ h, ⟨h.mono_right $ subset_union_left _ _, h.mono_right $ subset_union_right _ _⟩,
λ h, h.1.union h.2⟩
lemma absorbent.subset (hA : absorbent 𝕜 A) (hAB : A ⊆ B) : absorbent 𝕜 B :=
begin
rintro x,
obtain ⟨r, hr, hx⟩ := hA x,
exact ⟨r, hr, λ a ha, set.smul_set_mono hAB $ hx a ha⟩,
end
lemma absorbent_iff_forall_absorbs_singleton : absorbent 𝕜 A ↔ ∀ x, absorbs 𝕜 A {x} :=
by simp_rw [absorbs, absorbent, singleton_subset_iff]
lemma absorbent.absorbs (hs : absorbent 𝕜 s) {x : E} : absorbs 𝕜 s {x} :=
absorbent_iff_forall_absorbs_singleton.1 hs _
lemma absorbent_iff_nonneg_lt : absorbent 𝕜 A ↔ ∀ x, ∃ r, 0 ≤ r ∧ ∀ a : 𝕜, r < ∥a∥ → x ∈ a • A :=
begin
split,
{ rintro hA x,
obtain ⟨r, hr, hx⟩ := hA x,
exact ⟨r, hr.le, λ a ha, hx a ha.le⟩ },
{ rintro hA x,
obtain ⟨r, hr, hx⟩ := hA x,
exact ⟨r + 1, add_pos_of_nonneg_of_pos hr zero_lt_one,
λ a ha, hx a ((lt_add_of_pos_right r zero_lt_one).trans_le ha)⟩ }
end
end add_comm_group
end semi_normed_ring
section normed_comm_ring
variables [normed_comm_ring 𝕜] [add_comm_monoid E] [module 𝕜 E] {A B : set E} (a : 𝕜)
lemma balanced.smul (hA : balanced 𝕜 A) : balanced 𝕜 (a • A) :=
begin
rintro b hb _ ⟨_, ⟨x, hx, rfl⟩, rfl⟩,
exact ⟨b • x, hA _ hb ⟨_, hx, rfl⟩, smul_comm _ _ _⟩,
end
end normed_comm_ring
section normed_field
variables [normed_field 𝕜] [normed_ring 𝕝] [normed_space 𝕜 𝕝] [add_comm_group E] [module 𝕜 E]
[smul_with_zero 𝕝 E] [is_scalar_tower 𝕜 𝕝 E] {s t u v A B : set E} {a b : 𝕜}
/-- Scalar multiplication (by possibly different types) of a balanced set is monotone. -/
lemma balanced.smul_mono (hs : balanced 𝕝 s) {a : 𝕝} {b : 𝕜} (h : ∥a∥ ≤ ∥b∥) : a • s ⊆ b • s :=
begin
obtain rfl | hb := eq_or_ne b 0,
{ rw norm_zero at h,
rw norm_eq_zero.1 (h.antisymm $ norm_nonneg _),
obtain rfl | h := s.eq_empty_or_nonempty,
{ simp_rw [smul_set_empty] },
{ simp_rw [zero_smul_set h] } },
rintro _ ⟨x, hx, rfl⟩,
refine ⟨b⁻¹ • a • x, _, smul_inv_smul₀ hb _⟩,
rw ←smul_assoc,
refine hs _ _ (smul_mem_smul_set hx),
rw [norm_smul, norm_inv, ←div_eq_inv_mul],
exact div_le_one_of_le h (norm_nonneg _),
end
/-- A balanced set absorbs itself. -/
lemma balanced.absorbs_self (hA : balanced 𝕜 A) : absorbs 𝕜 A A :=
begin
use [1, zero_lt_one],
intros a ha x hx,
rw mem_smul_set_iff_inv_smul_mem₀,
{ apply hA a⁻¹,
{ rw norm_inv, exact inv_le_one ha },
{ rw mem_smul_set, use [x, hx] }},
{ rw ←norm_pos_iff, calc 0 < 1 : zero_lt_one ... ≤ ∥a∥ : ha, }
end
lemma balanced.subset_smul (hA : balanced 𝕜 A) (ha : 1 ≤ ∥a∥) : A ⊆ a • A :=
begin
refine (subset_set_smul_iff₀ _).2 (hA (a⁻¹) _),
{ rintro rfl,
rw norm_zero at ha,
exact zero_lt_one.not_le ha },
{ rw norm_inv,
exact inv_le_one ha }
end
lemma balanced.smul_eq (hA : balanced 𝕜 A) (ha : ∥a∥ = 1) : a • A = A :=
(hA _ ha.le).antisymm $ hA.subset_smul ha.ge
lemma absorbs.inter (hs : absorbs 𝕜 s u) (ht : absorbs 𝕜 t u) : absorbs 𝕜 (s ∩ t) u :=
begin
obtain ⟨a, ha, hs⟩ := hs,
obtain ⟨b, hb, ht⟩ := ht,
have h : 0 < max a b := lt_max_of_lt_left ha,
refine ⟨max a b, lt_max_of_lt_left ha, λ c hc, _⟩,
rw smul_set_inter₀ (norm_pos_iff.1 $ h.trans_le hc),
exact subset_inter (hs _ $ le_of_max_le_left hc) (ht _ $ le_of_max_le_right hc),
end
@[simp] lemma absorbs_inter : absorbs 𝕜 (s ∩ t) u ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 t u :=
⟨λ h, ⟨h.mono_left $ inter_subset_left _ _, h.mono_left $ inter_subset_right _ _⟩,
λ h, h.1.inter h.2⟩
lemma absorbent_univ : absorbent 𝕜 (univ : set E) :=
begin
refine λ x, ⟨1, zero_lt_one, λ a ha, _⟩,
rw smul_set_univ₀ (norm_pos_iff.1 $ zero_lt_one.trans_le ha),
exact trivial,
end
/-! #### Topological vector space -/
variables [topological_space E] [has_continuous_smul 𝕜 E]
/-- Every neighbourhood of the origin is absorbent. -/
lemma absorbent_nhds_zero (hA : A ∈ 𝓝 (0 : E)) : absorbent 𝕜 A :=
begin
intro x,
rcases mem_nhds_iff.mp hA with ⟨w, hw₁, hw₂, hw₃⟩,
have hc : continuous (λ t : 𝕜, t • x), from continuous_id.smul continuous_const,
rcases metric.is_open_iff.mp (hw₂.preimage hc) 0 (by rwa [mem_preimage, zero_smul])
with ⟨r, hr₁, hr₂⟩,
have hr₃, from inv_pos.mpr (half_pos hr₁),
use [(r/2)⁻¹, hr₃],
intros a ha₁,
have ha₂ : 0 < ∥a∥ := hr₃.trans_le ha₁,
rw [mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.mp ha₂)],
refine hw₁ (hr₂ _),
rw [metric.mem_ball, dist_zero_right, norm_inv],
calc ∥a∥⁻¹ ≤ r/2 : (inv_le (half_pos hr₁) ha₂).mp ha₁
... < r : half_lt_self hr₁,
end
/-- The union of `{0}` with the interior of a balanced set is balanced. -/
lemma balanced_zero_union_interior (hA : balanced 𝕜 A) : balanced 𝕜 ((0 : set E) ∪ interior A) :=
begin
intros a ha, by_cases a = 0,
{ rw [h, zero_smul_set],
exacts [subset_union_left _ _, ⟨0, or.inl rfl⟩] },
{ rw [←image_smul, image_union],
apply union_subset_union,
{ rw [image_zero, smul_zero],
refl },
{ calc a • interior A ⊆ interior (a • A) : (is_open_map_smul₀ h).image_interior_subset A
... ⊆ interior A : interior_mono (hA _ ha) } }
end
/-- The interior of a balanced set is balanced if it contains the origin. -/
lemma balanced.interior (hA : balanced 𝕜 A) (h : (0 : E) ∈ interior A) :
balanced 𝕜 (interior A) :=
begin
rw ←singleton_subset_iff at h,
rw [←union_eq_self_of_subset_left h],
exact balanced_zero_union_interior hA,
end
/-- The closure of a balanced set is balanced. -/
lemma balanced.closure (hA : balanced 𝕜 A) : balanced 𝕜 (closure A) :=
assume a ha,
calc _ ⊆ closure (a • A) : image_closure_subset_closure_image (continuous_id.const_smul _)
... ⊆ _ : closure_mono (hA _ ha)
end normed_field
section nondiscrete_normed_field
variables [nondiscrete_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] {s : set E}
lemma absorbs_zero_iff : absorbs 𝕜 s 0 ↔ (0 : E) ∈ s :=
begin
refine ⟨_, λ h, ⟨1, zero_lt_one, λ a _, zero_subset.2 $ zero_mem_smul_set h⟩⟩,
rintro ⟨r, hr, h⟩,
obtain ⟨a, ha⟩ := normed_space.exists_lt_norm 𝕜 𝕜 r,
have := h _ ha.le,
rwa [zero_subset, zero_mem_smul_set_iff] at this,
exact norm_ne_zero_iff.1 (hr.trans ha).ne',
end
lemma absorbent.zero_mem (hs : absorbent 𝕜 s) : (0 : E) ∈ s :=
absorbs_zero_iff.1 $ absorbent_iff_forall_absorbs_singleton.1 hs _
end nondiscrete_normed_field
/-!
### Seminorms
-/
/-- A seminorm on a vector space over a normed field is a function to
the reals that is positive semidefinite, positive homogeneous, and
subadditive. -/
structure seminorm (𝕜 : Type*) (E : Type*) [semi_normed_ring 𝕜] [add_monoid E] [has_scalar 𝕜 E] :=
(to_fun : E → ℝ)
(smul' : ∀ (a : 𝕜) (x : E), to_fun (a • x) = ∥a∥ * to_fun x)
(triangle' : ∀ x y : E, to_fun (x + y) ≤ to_fun x + to_fun y)
namespace seminorm
section semi_normed_ring
variables [semi_normed_ring 𝕜]
section add_monoid
variables [add_monoid E]
section has_scalar
variables [has_scalar 𝕜 E]
instance fun_like : fun_like (seminorm 𝕜 E) E (λ _, ℝ) :=
{ coe := seminorm.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' }
/-- Helper instance for when there's too many metavariables to apply `to_fun.to_coe_fn`. -/
instance : has_coe_to_fun (seminorm 𝕜 E) (λ _, E → ℝ) := ⟨λ p, p.to_fun⟩
@[ext] lemma ext {p q : seminorm 𝕜 E} (h : ∀ x, (p : E → ℝ) x = q x) : p = q := fun_like.ext p q h
instance : has_zero (seminorm 𝕜 E) :=
⟨{ to_fun := 0,
smul' := λ _ _, (mul_zero _).symm,
triangle' := λ _ _, eq.ge (zero_add _) }⟩
@[simp] lemma coe_zero : ⇑(0 : seminorm 𝕜 E) = 0 := rfl
@[simp] lemma zero_apply (x : E) : (0 : seminorm 𝕜 E) x = 0 := rfl
instance : inhabited (seminorm 𝕜 E) := ⟨0⟩
variables (p : seminorm 𝕜 E) (c : 𝕜) (x y : E) (r : ℝ)
protected lemma smul : p (c • x) = ∥c∥ * p x := p.smul' _ _
protected lemma triangle : p (x + y) ≤ p x + p y := p.triangle' _ _
/-- Any action on `ℝ` which factors through `ℝ≥0` applies to a seminorm. -/
instance [has_scalar R ℝ] [has_scalar R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
has_scalar R (seminorm 𝕜 E) :=
{ smul := λ r p,
{ to_fun := λ x, r • p x,
smul' := λ _ _, begin
simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul],
rw [p.smul, mul_left_comm],
end,
triangle' := λ _ _, begin
simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul],
exact (mul_le_mul_of_nonneg_left (p.triangle _ _) (nnreal.coe_nonneg _)).trans_eq
(mul_add _ _ _),
end } }
lemma coe_smul [has_scalar R ℝ] [has_scalar R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p : seminorm 𝕜 E) : ⇑(r • p) = r • p := rfl
@[simp] lemma smul_apply [has_scalar R ℝ] [has_scalar R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p : seminorm 𝕜 E) (x : E) : (r • p) x = r • p x := rfl
instance : has_add (seminorm 𝕜 E) :=
{ add := λ p q,
{ to_fun := λ x, p x + q x,
smul' := λ a x, by rw [p.smul, q.smul, mul_add],
triangle' := λ _ _, has_le.le.trans_eq (add_le_add (p.triangle _ _) (q.triangle _ _))
(add_add_add_comm _ _ _ _) } }
lemma coe_add (p q : seminorm 𝕜 E) : ⇑(p + q) = p + q := rfl
@[simp] lemma add_apply (p q : seminorm 𝕜 E) (x : E) : (p + q) x = p x + q x := rfl
instance : add_monoid (seminorm 𝕜 E) :=
fun_like.coe_injective.add_monoid_smul _ rfl coe_add (λ p n, coe_smul n p)
instance : ordered_cancel_add_comm_monoid (seminorm 𝕜 E) :=
{ nsmul := (•), -- to avoid introducing a diamond
..seminorm.add_monoid,
..(fun_like.coe_injective.ordered_cancel_add_comm_monoid _ rfl coe_add
: ordered_cancel_add_comm_monoid (seminorm 𝕜 E)) }
instance [monoid R] [mul_action R ℝ] [has_scalar R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
mul_action R (seminorm 𝕜 E) :=
fun_like.coe_injective.mul_action _ coe_smul
variables (𝕜 E)
/-- `coe_fn` as an `add_monoid_hom`. Helper definition for showing that `seminorm 𝕜 E` is
a module. -/
@[simps]
def coe_fn_add_monoid_hom : add_monoid_hom (seminorm 𝕜 E) (E → ℝ) := ⟨coe_fn, coe_zero, coe_add⟩
lemma coe_fn_add_monoid_hom_injective : function.injective (coe_fn_add_monoid_hom 𝕜 E) :=
show @function.injective (seminorm 𝕜 E) (E → ℝ) coe_fn, from fun_like.coe_injective
variables {𝕜 E}
instance [monoid R] [distrib_mul_action R ℝ] [has_scalar R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
distrib_mul_action R (seminorm 𝕜 E) :=
(coe_fn_add_monoid_hom_injective 𝕜 E).distrib_mul_action _ coe_smul
instance [semiring R] [module R ℝ] [has_scalar R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
module R (seminorm 𝕜 E) :=
(coe_fn_add_monoid_hom_injective 𝕜 E).module R _ coe_smul
-- TODO: define `has_Sup` too, from the skeleton at
-- https://github.com/leanprover-community/mathlib/pull/11329#issuecomment-1008915345
noncomputable instance : has_sup (seminorm 𝕜 E) :=
{ sup := λ p q,
{ to_fun := p ⊔ q,
triangle' := λ x y, sup_le
((p.triangle x y).trans $ add_le_add le_sup_left le_sup_left)
((q.triangle x y).trans $ add_le_add le_sup_right le_sup_right),
smul' := λ x v, (congr_arg2 max (p.smul x v) (q.smul x v)).trans $
(mul_max_of_nonneg _ _ $ norm_nonneg x).symm } }
@[simp] lemma coe_sup (p q : seminorm 𝕜 E) : ⇑(p ⊔ q) = p ⊔ q := rfl
instance : partial_order (seminorm 𝕜 E) :=
partial_order.lift _ fun_like.coe_injective
lemma le_def (p q : seminorm 𝕜 E) : p ≤ q ↔ (p : E → ℝ) ≤ q := iff.rfl
lemma lt_def (p q : seminorm 𝕜 E) : p < q ↔ (p : E → ℝ) < q := iff.rfl
noncomputable instance : semilattice_sup (seminorm 𝕜 E) :=
function.injective.semilattice_sup _ fun_like.coe_injective coe_sup
end has_scalar
section smul_with_zero
variables [smul_with_zero 𝕜 E] (p : seminorm 𝕜 E)
@[simp]
protected lemma zero : p 0 = 0 :=
calc p 0 = p ((0 : 𝕜) • 0) : by rw zero_smul
... = 0 : by rw [p.smul, norm_zero, zero_mul]
end smul_with_zero
end add_monoid
section module
variables [add_comm_group E] [add_comm_group F] [add_comm_group G]
variables [module 𝕜 E] [module 𝕜 F] [module 𝕜 G]
variables [has_scalar R ℝ] [has_scalar R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
/-- Composition of a seminorm with a linear map is a seminorm. -/
def comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : seminorm 𝕜 E :=
{ to_fun := λ x, p(f x),
smul' := λ _ _, (congr_arg p (f.map_smul _ _)).trans (p.smul _ _),
triangle' := λ _ _, eq.trans_le (congr_arg p (f.map_add _ _)) (p.triangle _ _) }
lemma coe_comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : ⇑(p.comp f) = p ∘ f := rfl
@[simp] lemma comp_apply (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (x : E) : (p.comp f) x = p (f x) := rfl
@[simp] lemma comp_id (p : seminorm 𝕜 E) : p.comp linear_map.id = p :=
ext $ λ _, rfl
@[simp]
@[simp] lemma zero_comp (f : E →ₗ[𝕜] F) : (0 : seminorm 𝕜 F).comp f = 0 :=
ext $ λ _, rfl
lemma comp_comp (p : seminorm 𝕜 G) (g : F →ₗ[𝕜] G) (f : E →ₗ[𝕜] F) :
p.comp (g.comp f) = (p.comp g).comp f :=
ext $ λ _, rfl
lemma add_comp (p q : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : (p + q).comp f = p.comp f + q.comp f :=
ext $ λ _, rfl
lemma comp_triangle (p : seminorm 𝕜 F) (f g : E →ₗ[𝕜] F) : p.comp (f + g) ≤ p.comp f + p.comp g :=
λ _, p.triangle _ _
lemma smul_comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (c : R) : (c • p).comp f = c • (p.comp f) :=
ext $ λ _, rfl
lemma comp_mono {p : seminorm 𝕜 F} {q : seminorm 𝕜 F} (f : E →ₗ[𝕜] F) (hp : p ≤ q) :
p.comp f ≤ q.comp f := λ _, hp _
/-- The composition as an `add_monoid_hom`. -/
@[simps] def pullback (f : E →ₗ[𝕜] F) : add_monoid_hom (seminorm 𝕜 F) (seminorm 𝕜 E) :=
⟨λ p, p.comp f, zero_comp f, λ p q, add_comp p q f⟩
section norm_one_class
variables [norm_one_class 𝕜] (p : seminorm 𝕜 E) (x y : E) (r : ℝ)
@[simp]
protected lemma neg : p (-x) = p x :=
calc p (-x) = p ((-1 : 𝕜) • x) : by rw neg_one_smul
... = p x : by rw [p.smul, norm_neg, norm_one, one_mul]
protected lemma sub_le : p (x - y) ≤ p x + p y :=
calc
p (x - y)
= p (x + -y) : by rw sub_eq_add_neg
... ≤ p x + p (-y) : p.triangle x (-y)
... = p x + p y : by rw p.neg
lemma nonneg : 0 ≤ p x :=
have h: 0 ≤ 2 * p x, from
calc 0 = p (x + (- x)) : by rw [add_neg_self, p.zero]
... ≤ p x + p (-x) : p.triangle _ _
... = 2 * p x : by rw [p.neg, two_mul],
nonneg_of_mul_nonneg_left h zero_lt_two
lemma sub_rev : p (x - y) = p (y - x) := by rw [←neg_sub, p.neg]
instance : order_bot (seminorm 𝕜 E) := ⟨0, nonneg⟩
@[simp] lemma coe_bot : ⇑(⊥ : seminorm 𝕜 E) = 0 := rfl
lemma bot_eq_zero : (⊥ : seminorm 𝕜 E) = 0 := rfl
lemma smul_le_smul {p q : seminorm 𝕜 E} {a b : ℝ≥0} (hpq : p ≤ q) (hab : a ≤ b) :
a • p ≤ b • q :=
begin
simp_rw [le_def, pi.le_def, coe_smul],
intros x,
simp_rw [pi.smul_apply, nnreal.smul_def, smul_eq_mul],
exact mul_le_mul hab (hpq x) (nonneg p x) (nnreal.coe_nonneg b),
end
lemma finset_sup_apply (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) :
s.sup p x = ↑(s.sup (λ i, ⟨p i x, nonneg (p i) x⟩) : ℝ≥0) :=
begin
induction s using finset.cons_induction_on with a s ha ih,
{ rw [finset.sup_empty, finset.sup_empty, coe_bot, _root_.bot_eq_zero, pi.zero_apply,
nonneg.coe_zero] },
{ rw [finset.sup_cons, finset.sup_cons, coe_sup, sup_eq_max, pi.sup_apply, sup_eq_max,
nnreal.coe_max, subtype.coe_mk, ih] }
end
lemma finset_sup_le_sum (p : ι → seminorm 𝕜 E) (s : finset ι) : s.sup p ≤ ∑ i in s, p i :=
begin
classical,
refine finset.sup_le_iff.mpr _,
intros i hi,
rw [finset.sum_eq_sum_diff_singleton_add hi, le_add_iff_nonneg_left],
exact bot_le,
end
end norm_one_class
end module
end semi_normed_ring
section semi_normed_comm_ring
variables [semi_normed_comm_ring 𝕜] [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F]
lemma comp_smul (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (c : 𝕜) :
p.comp (c • f) = ∥c∥₊ • p.comp f :=
ext $ λ _, by rw [comp_apply, smul_apply, linear_map.smul_apply, p.smul, nnreal.smul_def,
coe_nnnorm, smul_eq_mul, comp_apply]
lemma comp_smul_apply (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (c : 𝕜) (x : E) :
p.comp (c • f) x = ∥c∥ * p (f x) := p.smul _ _
end semi_normed_comm_ring
/-! ### Seminorm ball -/
section semi_normed_ring
variables [semi_normed_ring 𝕜]
section add_comm_group
variables [add_comm_group E]
section has_scalar
variables [has_scalar 𝕜 E] (p : seminorm 𝕜 E)
/-- The ball of radius `r` at `x` with respect to seminorm `p` is the set of elements `y` with
`p (y - x) < `r`. -/
def ball (x : E) (r : ℝ) := { y : E | p (y - x) < r }
variables {x y : E} {r : ℝ}
@[simp] lemma mem_ball : y ∈ ball p x r ↔ p (y - x) < r := iff.rfl
lemma mem_ball_zero : y ∈ ball p 0 r ↔ p y < r := by rw [mem_ball, sub_zero]
lemma ball_zero_eq : ball p 0 r = { y : E | p y < r } := set.ext $ λ x, p.mem_ball_zero
@[simp] lemma ball_zero' (x : E) (hr : 0 < r) : ball (0 : seminorm 𝕜 E) x r = set.univ :=
begin
rw [set.eq_univ_iff_forall, ball],
simp [hr],
end
lemma ball_smul (p : seminorm 𝕜 E) {c : nnreal} (hc : 0 < c) (r : ℝ) (x : E) :
(c • p).ball x r = p.ball x (r / c) :=
by { ext, rw [mem_ball, mem_ball, smul_apply, nnreal.smul_def, smul_eq_mul, mul_comm,
lt_div_iff (nnreal.coe_pos.mpr hc)] }
lemma ball_sup (p : seminorm 𝕜 E) (q : seminorm 𝕜 E) (e : E) (r : ℝ) :
ball (p ⊔ q) e r = ball p e r ∩ ball q e r :=
by simp_rw [ball, ←set.set_of_and, coe_sup, pi.sup_apply, sup_lt_iff]
lemma ball_finset_sup' (p : ι → seminorm 𝕜 E) (s : finset ι) (H : s.nonempty) (e : E) (r : ℝ) :
ball (s.sup' H p) e r = s.inf' H (λ i, ball (p i) e r) :=
begin
induction H using finset.nonempty.cons_induction with a a s ha hs ih,
{ classical, simp },
{ rw [finset.sup'_cons hs, finset.inf'_cons hs, ball_sup, inf_eq_inter, ih] },
end
lemma ball_mono {p : seminorm 𝕜 E} {r₁ r₂ : ℝ} (h : r₁ ≤ r₂) : p.ball x r₁ ⊆ p.ball x r₂ :=
λ _ (hx : _ < _), hx.trans_le h
lemma ball_antitone {p q : seminorm 𝕜 E} (h : q ≤ p) : p.ball x r ⊆ q.ball x r :=
λ _, (h _).trans_lt
lemma ball_add_ball_subset (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) (x₁ x₂ : E):
p.ball (x₁ : E) r₁ + p.ball (x₂ : E) r₂ ⊆ p.ball (x₁ + x₂) (r₁ + r₂) :=
begin
rintros x ⟨y₁, y₂, hy₁, hy₂, rfl⟩,
rw [mem_ball, add_sub_comm],
exact (p.triangle _ _).trans_lt (add_lt_add hy₁ hy₂),
end
end has_scalar
section module
variables [module 𝕜 E]
variables [add_comm_group F] [module 𝕜 F]
lemma ball_comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (x : E) (r : ℝ) :
(p.comp f).ball x r = f ⁻¹' (p.ball (f x) r) :=
begin
ext,
simp_rw [ball, mem_preimage, comp_apply, set.mem_set_of_eq, map_sub],
end
section norm_one_class
variables [norm_one_class 𝕜] (p : seminorm 𝕜 E)
@[simp] lemma ball_bot {r : ℝ} (x : E) (hr : 0 < r) : ball (⊥ : seminorm 𝕜 E) x r = set.univ :=
ball_zero' x hr
/-- Seminorm-balls at the origin are balanced. -/
lemma balanced_ball_zero (r : ℝ) : balanced 𝕜 (ball p 0 r) :=
begin
rintro a ha x ⟨y, hy, hx⟩,
rw [mem_ball_zero, ←hx, p.smul],
calc _ ≤ p y : mul_le_of_le_one_left (p.nonneg _) ha
... < r : by rwa mem_ball_zero at hy,
end
lemma ball_finset_sup_eq_Inter (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ} (hr : 0 < r) :
ball (s.sup p) x r = ⋂ (i ∈ s), ball (p i) x r :=
begin
lift r to nnreal using hr.le,
simp_rw [ball, Inter_set_of, finset_sup_apply, nnreal.coe_lt_coe,
finset.sup_lt_iff (show ⊥ < r, from hr), ←nnreal.coe_lt_coe, subtype.coe_mk],
end
lemma ball_finset_sup (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ}
(hr : 0 < r) : ball (s.sup p) x r = s.inf (λ i, ball (p i) x r) :=
begin
rw finset.inf_eq_infi,
exact ball_finset_sup_eq_Inter _ _ _ hr,
end
lemma ball_smul_ball (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) :
metric.ball (0 : 𝕜) r₁ • p.ball 0 r₂ ⊆ p.ball 0 (r₁ * r₂) :=
begin
rw set.subset_def,
intros x hx,
rw set.mem_smul at hx,
rcases hx with ⟨a, y, ha, hy, hx⟩,
rw [←hx, mem_ball_zero, seminorm.smul],
exact mul_lt_mul'' (mem_ball_zero_iff.mp ha) (p.mem_ball_zero.mp hy) (norm_nonneg a) (p.nonneg y),
end
end norm_one_class
end module
end add_comm_group
end semi_normed_ring
section normed_field
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] (p : seminorm 𝕜 E) {A B : set E}
{a : 𝕜} {r : ℝ} {x : E}
/-- Seminorm-balls at the origin are absorbent. -/
protected lemma absorbent_ball_zero (hr : 0 < r) : absorbent 𝕜 (ball p (0 : E) r) :=
begin
rw absorbent_iff_nonneg_lt,
rintro x,
have hxr : 0 ≤ p x/r := div_nonneg (p.nonneg _) hr.le,
refine ⟨p x/r, hxr, λ a ha, _⟩,
have ha₀ : 0 < ∥a∥ := hxr.trans_lt ha,
refine ⟨a⁻¹ • x, _, smul_inv_smul₀ (norm_pos_iff.1 ha₀) x⟩,
rwa [mem_ball_zero, p.smul, norm_inv, inv_mul_lt_iff ha₀, ←div_lt_iff hr],
end
/-- Seminorm-balls containing the origin are absorbent. -/
protected lemma absorbent_ball (hpr : p x < r) : absorbent 𝕜 (ball p x r) :=
begin
refine (p.absorbent_ball_zero $ sub_pos.2 hpr).subset (λ y hy, _),
rw p.mem_ball_zero at hy,
exact p.mem_ball.2 ((p.sub_le _ _).trans_lt $ add_lt_of_lt_sub_right hy),
end
lemma symmetric_ball_zero (r : ℝ) (hx : x ∈ ball p 0 r) : -x ∈ ball p 0 r :=
balanced_ball_zero p r (-1) (by rw [norm_neg, norm_one]) ⟨x, hx, by rw [neg_smul, one_smul]⟩
@[simp]
lemma neg_ball (p : seminorm 𝕜 E) (r : ℝ) (x : E) :
-ball p x r = ball p (-x) r :=
by { ext, rw [mem_neg, mem_ball, mem_ball, ←neg_add', sub_neg_eq_add, p.neg], }
@[simp]
lemma smul_ball_preimage (p : seminorm 𝕜 E) (y : E) (r : ℝ) (a : 𝕜) (ha : a ≠ 0) :
((•) a) ⁻¹' p.ball y r = p.ball (a⁻¹ • y) (r / ∥a∥) :=
set.ext $ λ _, by rw [mem_preimage, mem_ball, mem_ball,
lt_div_iff (norm_pos_iff.mpr ha), mul_comm, ←p.smul, smul_sub, smul_inv_smul₀ ha]
end normed_field
section normed_linear_ordered_field
variables [normed_linear_ordered_field 𝕜] [add_comm_group E] [normed_space ℝ 𝕜] [module 𝕜 E]
section has_scalar
variables [has_scalar ℝ E] [is_scalar_tower ℝ 𝕜 E] (p : seminorm 𝕜 E)
/-- A seminorm is convex. Also see `convex_on_norm`. -/
protected lemma convex_on : convex_on ℝ univ p :=
begin
refine ⟨convex_univ, λ x y _ _ a b ha hb hab, _⟩,
calc p (a • x + b • y) ≤ p (a • x) + p (b • y) : p.triangle _ _
... = ∥a • (1 : 𝕜)∥ * p x + ∥b • (1 : 𝕜)∥ * p y
: by rw [←p.smul, ←p.smul, smul_one_smul, smul_one_smul]
... = a * p x + b * p y
: by rw [norm_smul, norm_smul, norm_one, mul_one, mul_one, real.norm_of_nonneg ha,
real.norm_of_nonneg hb],
end
end has_scalar
section module
variables [module ℝ E] [is_scalar_tower ℝ 𝕜 E] (p : seminorm 𝕜 E) (x : E) (r : ℝ)
/-- Seminorm-balls are convex. -/
lemma convex_ball : convex ℝ (ball p x r) :=
begin
convert (p.convex_on.translate_left (-x)).convex_lt r,
ext y,
rw [preimage_univ, sep_univ, p.mem_ball, sub_eq_add_neg],
refl,
end
end module
end normed_linear_ordered_field
-- TODO: convexity and absorbent/balanced sets in vector spaces over ℝ
end seminorm
/-! ### The norm as a seminorm -/
section norm_seminorm
variables (𝕜 E) [normed_field 𝕜] [semi_normed_group E] [normed_space 𝕜 E] {r : ℝ}
/-- The norm of a seminormed group as a seminorm. -/
def norm_seminorm : seminorm 𝕜 E := ⟨norm, norm_smul, norm_add_le⟩
@[simp] lemma coe_norm_seminorm : ⇑(norm_seminorm 𝕜 E) = norm := rfl
@[simp] lemma ball_norm_seminorm : (norm_seminorm 𝕜 E).ball = metric.ball :=
by { ext x r y, simp only [seminorm.mem_ball, metric.mem_ball, coe_norm_seminorm, dist_eq_norm] }
variables {𝕜 E} {x : E}
/-- Balls at the origin are absorbent. -/
lemma absorbent_ball_zero (hr : 0 < r) : absorbent 𝕜 (metric.ball (0 : E) r) :=
by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).absorbent_ball_zero hr }
/-- Balls containing the origin are absorbent. -/
lemma absorbent_ball (hx : ∥x∥ < r) : absorbent 𝕜 (metric.ball x r) :=
by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).absorbent_ball hx }
/-- Balls at the origin are balanced. -/
lemma balanced_ball_zero [norm_one_class 𝕜] : balanced 𝕜 (metric.ball (0 : E) r) :=
by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).balanced_ball_zero r }
end norm_seminorm
/-! ### Minkowksi functional -/
section gauge
noncomputable theory
section add_comm_group
variables [add_comm_group E] [module ℝ E]
/--The Minkowski functional. Given a set `s` in a real vector space, `gauge s` is the functional
which sends `x : E` to the smallest `r : ℝ` such that `x` is in `s` scaled by `r`. -/
def gauge (s : set E) (x : E) : ℝ := Inf {r : ℝ | 0 < r ∧ x ∈ r • s}
variables {s t : set E} {a : ℝ} {x : E}
lemma gauge_def : gauge s x = Inf {r ∈ set.Ioi 0 | x ∈ r • s} := rfl
/-- An alternative definition of the gauge using scalar multiplication on the element rather than on
the set. -/
lemma gauge_def' : gauge s x = Inf {r ∈ set.Ioi 0 | r⁻¹ • x ∈ s} :=
begin
unfold gauge,
congr' 1,
ext r,
exact and_congr_right (λ hr, mem_smul_set_iff_inv_smul_mem₀ hr.ne' _ _),
end
private lemma gauge_set_bdd_below : bdd_below {r : ℝ | 0 < r ∧ x ∈ r • s} := ⟨0, λ r hr, hr.1.le⟩
/-- If the given subset is `absorbent` then the set we take an infimum over in `gauge` is nonempty,
which is useful for proving many properties about the gauge. -/
lemma absorbent.gauge_set_nonempty (absorbs : absorbent ℝ s) :
{r : ℝ | 0 < r ∧ x ∈ r • s}.nonempty :=
let ⟨r, hr₁, hr₂⟩ := absorbs x in ⟨r, hr₁, hr₂ r (real.norm_of_nonneg hr₁.le).ge⟩
lemma gauge_mono (hs : absorbent ℝ s) (h : s ⊆ t) : gauge t ≤ gauge s :=
λ x, cInf_le_cInf gauge_set_bdd_below hs.gauge_set_nonempty $ λ r hr, ⟨hr.1, smul_set_mono h hr.2⟩
lemma exists_lt_of_gauge_lt (absorbs : absorbent ℝ s) (h : gauge s x < a) :
∃ b, 0 < b ∧ b < a ∧ x ∈ b • s :=
begin
obtain ⟨b, ⟨hb, hx⟩, hba⟩ := exists_lt_of_cInf_lt absorbs.gauge_set_nonempty h,
exact ⟨b, hb, hba, hx⟩,
end
/-- The gauge evaluated at `0` is always zero (mathematically this requires `0` to be in the set `s`
but, the real infimum of the empty set in Lean being defined as `0`, it holds unconditionally). -/
@[simp] lemma gauge_zero : gauge s 0 = 0 :=
begin
rw gauge_def',
by_cases (0 : E) ∈ s,
{ simp only [smul_zero, sep_true, h, cInf_Ioi] },
{ simp only [smul_zero, sep_false, h, real.Inf_empty] }
end
@[simp] lemma gauge_zero' : gauge (0 : set E) = 0 :=
begin
ext,
rw gauge_def',
obtain rfl | hx := eq_or_ne x 0,
{ simp only [cInf_Ioi, mem_zero, pi.zero_apply, eq_self_iff_true, sep_true, smul_zero] },
{ simp only [mem_zero, pi.zero_apply, inv_eq_zero, smul_eq_zero],
convert real.Inf_empty,
exact eq_empty_iff_forall_not_mem.2 (λ r hr, hr.2.elim (ne_of_gt hr.1) hx) }
end
@[simp] lemma gauge_empty : gauge (∅ : set E) = 0 :=
by { ext, simp only [gauge_def', real.Inf_empty, mem_empty_eq, pi.zero_apply, sep_false] }
lemma gauge_of_subset_zero (h : s ⊆ 0) : gauge s = 0 :=
by { obtain rfl | rfl := subset_singleton_iff_eq.1 h, exacts [gauge_empty, gauge_zero'] }
/-- The gauge is always nonnegative. -/
lemma gauge_nonneg (x : E) : 0 ≤ gauge s x := real.Inf_nonneg _ $ λ x hx, hx.1.le
lemma gauge_neg (symmetric : ∀ x ∈ s, -x ∈ s) (x : E) : gauge s (-x) = gauge s x :=
begin
have : ∀ x, -x ∈ s ↔ x ∈ s := λ x, ⟨λ h, by simpa using symmetric _ h, symmetric x⟩,
rw [gauge_def', gauge_def'],
simp_rw [smul_neg, this],
end
lemma gauge_le_of_mem (ha : 0 ≤ a) (hx : x ∈ a • s) : gauge s x ≤ a :=
begin
obtain rfl | ha' := ha.eq_or_lt,
{ rw [mem_singleton_iff.1 (zero_smul_subset _ hx), gauge_zero] },
{ exact cInf_le gauge_set_bdd_below ⟨ha', hx⟩ }
end
lemma gauge_le_eq (hs₁ : convex ℝ s) (hs₀ : (0 : E) ∈ s) (hs₂ : absorbent ℝ s) (ha : 0 ≤ a) :
{x | gauge s x ≤ a} = ⋂ (r : ℝ) (H : a < r), r • s :=
begin
ext,
simp_rw [set.mem_Inter, set.mem_set_of_eq],
split,
{ intros h r hr,
have hr' := ha.trans_lt hr,
rw mem_smul_set_iff_inv_smul_mem₀ hr'.ne',
obtain ⟨δ, δ_pos, hδr, hδ⟩ := exists_lt_of_gauge_lt hs₂ (h.trans_lt hr),
suffices : (r⁻¹ * δ) • δ⁻¹ • x ∈ s,
{ rwa [smul_smul, mul_inv_cancel_right₀ δ_pos.ne'] at this },
rw mem_smul_set_iff_inv_smul_mem₀ δ_pos.ne' at hδ,
refine hs₁.smul_mem_of_zero_mem hs₀ hδ
⟨mul_nonneg (inv_nonneg.2 hr'.le) δ_pos.le, _⟩,
rw [inv_mul_le_iff hr', mul_one],
exact hδr.le },
{ refine λ h, le_of_forall_pos_lt_add (λ ε hε, _),
have hε' := (lt_add_iff_pos_right a).2 (half_pos hε),
exact (gauge_le_of_mem (ha.trans hε'.le) $ h _ hε').trans_lt
(add_lt_add_left (half_lt_self hε) _) }
end
lemma gauge_lt_eq' (absorbs : absorbent ℝ s) (a : ℝ) :
{x | gauge s x < a} = ⋃ (r : ℝ) (H : 0 < r) (H : r < a), r • s :=
begin
ext,
simp_rw [mem_set_of_eq, mem_Union, exists_prop],
exact ⟨exists_lt_of_gauge_lt absorbs,
λ ⟨r, hr₀, hr₁, hx⟩, (gauge_le_of_mem hr₀.le hx).trans_lt hr₁⟩,
end
lemma gauge_lt_eq (absorbs : absorbent ℝ s) (a : ℝ) :
{x | gauge s x < a} = ⋃ (r ∈ set.Ioo 0 (a : ℝ)), r • s :=
begin
ext,
simp_rw [mem_set_of_eq, mem_Union, exists_prop, mem_Ioo, and_assoc],
exact ⟨exists_lt_of_gauge_lt absorbs,
λ ⟨r, hr₀, hr₁, hx⟩, (gauge_le_of_mem hr₀.le hx).trans_lt hr₁⟩,
end
lemma gauge_lt_one_subset_self (hs : convex ℝ s) (h₀ : (0 : E) ∈ s) (absorbs : absorbent ℝ s) :
{x | gauge s x < 1} ⊆ s :=
begin
rw gauge_lt_eq absorbs,
apply set.Union₂_subset,
rintro r hr _ ⟨y, hy, rfl⟩,
exact hs.smul_mem_of_zero_mem h₀ hy (Ioo_subset_Icc_self hr),
end
lemma gauge_le_one_of_mem {x : E} (hx : x ∈ s) : gauge s x ≤ 1 :=
gauge_le_of_mem zero_le_one $ by rwa one_smul
lemma self_subset_gauge_le_one : s ⊆ {x | gauge s x ≤ 1} := λ x, gauge_le_one_of_mem
lemma convex.gauge_le (hs : convex ℝ s) (h₀ : (0 : E) ∈ s) (absorbs : absorbent ℝ s) (a : ℝ) :
convex ℝ {x | gauge s x ≤ a} :=
begin
by_cases ha : 0 ≤ a,
{ rw gauge_le_eq hs h₀ absorbs ha,
exact convex_Inter (λ i, convex_Inter (λ hi, hs.smul _)) },
{ convert convex_empty,
exact eq_empty_iff_forall_not_mem.2 (λ x hx, ha $ (gauge_nonneg _).trans hx) }
end
lemma balanced.star_convex (hs : balanced ℝ s) : star_convex ℝ 0 s :=
star_convex_zero_iff.2 $ λ x hx a ha₀ ha₁,
hs _ (by rwa real.norm_of_nonneg ha₀) (smul_mem_smul_set hx)
lemma le_gauge_of_not_mem (hs₀ : star_convex ℝ 0 s) (hs₂ : absorbs ℝ s {x}) (hx : x ∉ a • s) :
a ≤ gauge s x :=
begin
rw star_convex_zero_iff at hs₀,
obtain ⟨r, hr, h⟩ := hs₂,
refine le_cInf ⟨r, hr, singleton_subset_iff.1 $ h _ (real.norm_of_nonneg hr.le).ge⟩ _,
rintro b ⟨hb, x, hx', rfl⟩,
refine not_lt.1 (λ hba, hx _),
have ha := hb.trans hba,
refine ⟨(a⁻¹ * b) • x, hs₀ hx' (mul_nonneg (inv_nonneg.2 ha.le) hb.le) _, _⟩,
{ rw ←div_eq_inv_mul,
exact div_le_one_of_le hba.le ha.le },
{ rw [←mul_smul, mul_inv_cancel_left₀ ha.ne'] }
end
lemma one_le_gauge_of_not_mem (hs₁ : star_convex ℝ 0 s) (hs₂ : absorbs ℝ s {x}) (hx : x ∉ s) :
1 ≤ gauge s x :=
le_gauge_of_not_mem hs₁ hs₂ $ by rwa one_smul
section linear_ordered_field
variables {α : Type*} [linear_ordered_field α] [mul_action_with_zero α ℝ] [ordered_smul α ℝ]
lemma gauge_smul_of_nonneg [mul_action_with_zero α E] [is_scalar_tower α ℝ (set E)] {s : set E}
{r : α} (hr : 0 ≤ r) (x : E) :
gauge s (r • x) = r • gauge s x :=
begin
obtain rfl | hr' := hr.eq_or_lt,
{ rw [zero_smul, gauge_zero, zero_smul] },
rw [gauge_def', gauge_def', ←real.Inf_smul_of_nonneg hr],
congr' 1,
ext β,
simp_rw [set.mem_smul_set, set.mem_sep_eq],
split,
{ rintro ⟨hβ, hx⟩,
simp_rw [mem_Ioi] at ⊢ hβ,
have := smul_pos (inv_pos.2 hr') hβ,
refine ⟨r⁻¹ • β, ⟨this, _⟩, smul_inv_smul₀ hr'.ne' _⟩,
rw ←mem_smul_set_iff_inv_smul_mem₀ at ⊢ hx,
rwa [smul_assoc, mem_smul_set_iff_inv_smul_mem₀ (inv_ne_zero hr'.ne'), inv_inv₀],
{ exact this.ne' },
{ exact hβ.ne' } },
{ rintro ⟨β, ⟨hβ, hx⟩, rfl⟩,
rw mem_Ioi at ⊢ hβ,
have := smul_pos hr' hβ,
refine ⟨this, _⟩,
rw ←mem_smul_set_iff_inv_smul_mem₀ at ⊢ hx,
rw smul_assoc,
exact smul_mem_smul_set hx,
{ exact this.ne' },
{ exact hβ.ne'} }
end
/-- In textbooks, this is the homogeneity of the Minkowksi functional. -/
lemma gauge_smul [module α E] [is_scalar_tower α ℝ (set E)] {s : set E}
(symmetric : ∀ x ∈ s, -x ∈ s) (r : α) (x : E) :
gauge s (r • x) = abs r • gauge s x :=
begin
rw ←gauge_smul_of_nonneg (abs_nonneg r),
obtain h | h := abs_choice r,
{ rw h },
{ rw [h, neg_smul, gauge_neg symmetric] },
{ apply_instance }
end
lemma gauge_smul_left_of_nonneg [mul_action_with_zero α E] [smul_comm_class α ℝ ℝ]
[is_scalar_tower α ℝ ℝ] [is_scalar_tower α ℝ E] {s : set E} {a : α} (ha : 0 ≤ a) :
gauge (a • s) = a⁻¹ • gauge s :=
begin
obtain rfl | ha' := ha.eq_or_lt,
{ rw [inv_zero, zero_smul, gauge_of_subset_zero (zero_smul_subset _)] },
ext,
rw [gauge_def', pi.smul_apply, gauge_def', ←real.Inf_smul_of_nonneg (inv_nonneg.2 ha)],
congr' 1,
ext r,
simp_rw [set.mem_smul_set, set.mem_sep_eq],
split,
{ rintro ⟨hr, y, hy, h⟩,
simp_rw [mem_Ioi] at ⊢ hr,
refine ⟨a • r, ⟨smul_pos ha' hr, _⟩, inv_smul_smul₀ ha'.ne' _⟩,
rwa [smul_inv₀, smul_assoc, ←h, inv_smul_smul₀ ha'.ne'] },
{ rintro ⟨r, ⟨hr, hx⟩, rfl⟩,
rw mem_Ioi at ⊢ hr,
have := smul_pos ha' hr,
refine ⟨smul_pos (inv_pos.2 ha') hr, r⁻¹ • x, hx, _⟩,
rw [smul_inv₀, smul_assoc, inv_inv₀] }
end
lemma gauge_smul_left [module α E] [smul_comm_class α ℝ ℝ] [is_scalar_tower α ℝ ℝ]
[is_scalar_tower α ℝ E] {s : set E} (symmetric : ∀ x ∈ s, -x ∈ s) (a : α) :
gauge (a • s) = |a|⁻¹ • gauge s :=
begin
rw ←gauge_smul_left_of_nonneg (abs_nonneg a),
obtain h | h := abs_choice a,
{ rw h },
{ rw [h, set.neg_smul_set, ←set.smul_set_neg],
congr,
ext y,
refine ⟨symmetric _, λ hy, _⟩,
rw ←neg_neg y,
exact symmetric _ hy },
{ apply_instance }
end
end linear_ordered_field
section topological_space
variables [topological_space E] [has_continuous_smul ℝ E]
lemma interior_subset_gauge_lt_one (s : set E) : interior s ⊆ {x | gauge s x < 1} :=
begin
intros x hx,
let f : ℝ → E := λ t, t • x,
have hf : continuous f,
{ continuity },
let s' := f ⁻¹' (interior s),
have hs' : is_open s' := hf.is_open_preimage _ is_open_interior,
have one_mem : (1 : ℝ) ∈ s',
{ simpa only [s', f, set.mem_preimage, one_smul] },
obtain ⟨ε, hε₀, hε⟩ := (metric.nhds_basis_closed_ball.1 _).1
(is_open_iff_mem_nhds.1 hs' 1 one_mem),
rw real.closed_ball_eq_Icc at hε,
have hε₁ : 0 < 1 + ε := hε₀.trans (lt_one_add ε),
have : (1 + ε)⁻¹ < 1,
{ rw inv_lt_one_iff,
right,
linarith },
refine (gauge_le_of_mem (inv_nonneg.2 hε₁.le) _).trans_lt this,
rw mem_inv_smul_set_iff₀ hε₁.ne',
exact interior_subset
(hε ⟨(sub_le_self _ hε₀.le).trans ((le_add_iff_nonneg_right _).2 hε₀.le), le_rfl⟩),
end
lemma gauge_lt_one_eq_self_of_open (hs₁ : convex ℝ s) (hs₀ : (0 : E) ∈ s) (hs₂ : is_open s) :
{x | gauge s x < 1} = s :=
begin
apply (gauge_lt_one_subset_self hs₁ ‹_› $ absorbent_nhds_zero $ hs₂.mem_nhds hs₀).antisymm,
convert interior_subset_gauge_lt_one s,
exact hs₂.interior_eq.symm,
end
lemma gauge_lt_one_of_mem_of_open (hs₁ : convex ℝ s) (hs₀ : (0 : E) ∈ s) (hs₂ : is_open s)
{x : E} (hx : x ∈ s) :
gauge s x < 1 :=
by rwa ←gauge_lt_one_eq_self_of_open hs₁ hs₀ hs₂ at hx
lemma gauge_lt_of_mem_smul (x : E) (ε : ℝ) (hε : 0 < ε) (hs₀ : (0 : E) ∈ s)
(hs₁ : convex ℝ s) (hs₂ : is_open s) (hx : x ∈ ε • s) :
gauge s x < ε :=
begin
have : ε⁻¹ • x ∈ s,
{ rwa ←mem_smul_set_iff_inv_smul_mem₀ hε.ne' },
have h_gauge_lt := gauge_lt_one_of_mem_of_open hs₁ hs₀ hs₂ this,
rwa [gauge_smul_of_nonneg (inv_nonneg.2 hε.le), smul_eq_mul, inv_mul_lt_iff hε, mul_one]
at h_gauge_lt,
apply_instance
end
end topological_space
lemma gauge_add_le (hs : convex ℝ s) (absorbs : absorbent ℝ s) (x y : E) :
gauge s (x + y) ≤ gauge s x + gauge s y :=
begin
refine le_of_forall_pos_lt_add (λ ε hε, _),
obtain ⟨a, ha, ha', hx⟩ := exists_lt_of_gauge_lt absorbs
(lt_add_of_pos_right (gauge s x) (half_pos hε)),
obtain ⟨b, hb, hb', hy⟩ := exists_lt_of_gauge_lt absorbs
(lt_add_of_pos_right (gauge s y) (half_pos hε)),
rw mem_smul_set_iff_inv_smul_mem₀ ha.ne' at hx,
rw mem_smul_set_iff_inv_smul_mem₀ hb.ne' at hy,
suffices : gauge s (x + y) ≤ a + b,
{ linarith },
have hab : 0 < a + b := add_pos ha hb,
apply gauge_le_of_mem hab.le,
have := convex_iff_div.1 hs hx hy ha.le hb.le hab,
rwa [smul_smul, smul_smul, mul_comm_div', mul_comm_div', ←mul_div_assoc, ←mul_div_assoc,
mul_inv_cancel ha.ne', mul_inv_cancel hb.ne', ←smul_add, one_div,
←mem_smul_set_iff_inv_smul_mem₀ hab.ne'] at this,
end
/-- `gauge s` as a seminorm when `s` is symmetric, convex and absorbent. -/
@[simps] def gauge_seminorm (hs₀ : ∀ x ∈ s, -x ∈ s) (hs₁ : convex ℝ s) (hs₂ : absorbent ℝ s) :
seminorm ℝ E :=
{ to_fun := gauge s,
smul' := λ r x, by rw [gauge_smul hs₀, real.norm_eq_abs, smul_eq_mul]; apply_instance,
triangle' := gauge_add_le hs₁ hs₂ }
section gauge_seminorm
variables {hs₀ : ∀ x ∈ s, -x ∈ s} {hs₁ : convex ℝ s} {hs₂ : absorbent ℝ s}
section topological_space
variables [topological_space E] [has_continuous_smul ℝ E]
lemma gauge_seminorm_lt_one_of_open (hs : is_open s) {x : E} (hx : x ∈ s) :
gauge_seminorm hs₀ hs₁ hs₂ x < 1 :=
gauge_lt_one_of_mem_of_open hs₁ hs₂.zero_mem hs hx
end topological_space
end gauge_seminorm
/-- Any seminorm arises as the gauge of its unit ball. -/
@[simp] protected lemma seminorm.gauge_ball (p : seminorm ℝ E) : gauge (p.ball 0 1) = p :=
begin
ext,
obtain hp | hp := {r : ℝ | 0 < r ∧ x ∈ r • p.ball 0 1}.eq_empty_or_nonempty,
{ rw [gauge, hp, real.Inf_empty],
by_contra,
have hpx : 0 < p x := (p.nonneg x).lt_of_ne h,
have hpx₂ : 0 < 2 * p x := mul_pos zero_lt_two hpx,
refine hp.subset ⟨hpx₂, (2 * p x)⁻¹ • x, _, smul_inv_smul₀ hpx₂.ne' _⟩,
rw [p.mem_ball_zero, p.smul, real.norm_eq_abs, abs_of_pos (inv_pos.2 hpx₂), inv_mul_lt_iff hpx₂,
mul_one],
exact lt_mul_of_one_lt_left hpx one_lt_two },
refine is_glb.cInf_eq ⟨λ r, _, λ r hr, le_of_forall_pos_le_add $ λ ε hε, _⟩ hp,
{ rintro ⟨hr, y, hy, rfl⟩,
rw p.mem_ball_zero at hy,
rw [p.smul, real.norm_eq_abs, abs_of_pos hr],
exact mul_le_of_le_one_right hr.le hy.le },
{ have hpε : 0 < p x + ε := add_pos_of_nonneg_of_pos (p.nonneg _) hε,
refine hr ⟨hpε, (p x + ε)⁻¹ • x, _, smul_inv_smul₀ hpε.ne' _⟩,
rw [p.mem_ball_zero, p.smul, real.norm_eq_abs, abs_of_pos (inv_pos.2 hpε), inv_mul_lt_iff hpε,
mul_one],
exact lt_add_of_pos_right _ hε }
end
lemma seminorm.gauge_seminorm_ball (p : seminorm ℝ E) :
gauge_seminorm (λ x, p.symmetric_ball_zero 1) (p.convex_ball 0 1)
(p.absorbent_ball_zero zero_lt_one) = p := fun_like.coe_injective p.gauge_ball
end add_comm_group
section norm
variables [semi_normed_group E] [normed_space ℝ E] {s : set E} {r : ℝ} {x : E}
lemma gauge_unit_ball (x : E) : gauge (metric.ball (0 : E) 1) x = ∥x∥ :=
begin
obtain rfl | hx := eq_or_ne x 0,
{ rw [norm_zero, gauge_zero] },
refine (le_of_forall_pos_le_add $ λ ε hε, _).antisymm _,
{ have := add_pos_of_nonneg_of_pos (norm_nonneg x) hε,
refine gauge_le_of_mem this.le _,
rw [smul_ball this.ne', smul_zero, real.norm_of_nonneg this.le, mul_one, mem_ball_zero_iff],
exact lt_add_of_pos_right _ hε },
refine le_gauge_of_not_mem balanced_ball_zero.star_convex
(absorbent_ball_zero zero_lt_one).absorbs (λ h, _),
obtain hx' | hx' := eq_or_ne (∥x∥) 0,
{ rw hx' at h,
exact hx (zero_smul_subset _ h) },
{ rw [mem_smul_set_iff_inv_smul_mem₀ hx', mem_ball_zero_iff, norm_smul, norm_inv, norm_norm,
inv_mul_cancel hx'] at h,
exact lt_irrefl _ h }
end
lemma smul_unit_ball {r : ℝ} (hr : 0 < r) : r • metric.ball (0 : E) 1 = metric.ball (0 : E) r :=
by rw [smul_ball hr.ne', smul_zero, mul_one, real.norm_of_nonneg hr.le]
lemma gauge_ball (hr : 0 < r) (x : E) : gauge (metric.ball (0 : E) r) x = ∥x∥ / r :=
begin
rw [←smul_unit_ball hr, gauge_smul_left, pi.smul_apply, gauge_unit_ball, smul_eq_mul,
abs_of_nonneg hr.le, div_eq_inv_mul],
simp_rw [mem_ball_zero_iff, norm_neg],
exact λ _, id,
end
lemma mul_gauge_le_norm (hs : metric.ball (0 : E) r ⊆ s) : r * gauge s x ≤ ∥x∥ :=
begin
obtain hr | hr := le_or_lt r 0,
{ exact (mul_nonpos_of_nonpos_of_nonneg hr $ gauge_nonneg _).trans (norm_nonneg _) },
rw [mul_comm, ←le_div_iff hr, ←gauge_ball hr],
exact gauge_mono (absorbent_ball_zero hr) hs x,
end
end norm
end gauge
/-! ### Topology induced by a family of seminorms -/
namespace seminorm
section filter_basis
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
/-- A filter basis for the neighborhood filter of 0. -/
def seminorm_basis_zero (p : ι → seminorm 𝕜 E) : set (set E) :=
⋃ (s : finset ι) r (hr : 0 < r), singleton $ ball (s.sup p) (0 : E) r
lemma seminorm_basis_zero_iff (p : ι → seminorm 𝕜 E) (U : set E) :
U ∈ seminorm_basis_zero p ↔ ∃ (i : finset ι) r (hr : 0 < r), U = ball (i.sup p) 0 r :=
by simp only [seminorm_basis_zero, mem_Union, mem_singleton_iff]
lemma seminorm_basis_zero_mem (p : ι → seminorm 𝕜 E) (i : finset ι) {r : ℝ} (hr : 0 < r) :
(i.sup p).ball 0 r ∈ seminorm_basis_zero p :=
(seminorm_basis_zero_iff _ _).mpr ⟨i,_,hr,rfl⟩
lemma seminorm_basis_zero_singleton_mem (p : ι → seminorm 𝕜 E) (i : ι) {r : ℝ} (hr : 0 < r) :
(p i).ball 0 r ∈ seminorm_basis_zero p :=
(seminorm_basis_zero_iff _ _).mpr ⟨{i},_,hr, by rw finset.sup_singleton⟩
lemma seminorm_basis_zero_nonempty (p : ι → seminorm 𝕜 E) [nonempty ι] :
(seminorm_basis_zero p).nonempty :=
begin
let i := classical.arbitrary ι,
refine set.nonempty_def.mpr ⟨ball (p i) 0 1, _⟩,
exact seminorm_basis_zero_singleton_mem _ i zero_lt_one,
end
lemma seminorm_basis_zero_intersect (p : ι → seminorm 𝕜 E)
(U V : set E) (hU : U ∈ seminorm_basis_zero p) (hV : V ∈ seminorm_basis_zero p) :
∃ (z : set E) (H : z ∈ (seminorm_basis_zero p)), z ⊆ U ∩ V :=
begin
classical,
rcases (seminorm_basis_zero_iff p U).mp hU with ⟨s, r₁, hr₁, hU⟩,
rcases (seminorm_basis_zero_iff p V).mp hV with ⟨t, r₂, hr₂, hV⟩,
use ((s ∪ t).sup p).ball 0 (min r₁ r₂),
refine ⟨seminorm_basis_zero_mem p (s ∪ t) (lt_min_iff.mpr ⟨hr₁, hr₂⟩), _⟩,
rw [hU, hV, ball_finset_sup_eq_Inter _ _ _ (lt_min_iff.mpr ⟨hr₁, hr₂⟩),
ball_finset_sup_eq_Inter _ _ _ hr₁, ball_finset_sup_eq_Inter _ _ _ hr₂],
exact set.subset_inter
(set.Inter₂_mono' $ λ i hi, ⟨i, finset.subset_union_left _ _ hi, ball_mono $ min_le_left _ _⟩)
(set.Inter₂_mono' $ λ i hi, ⟨i, finset.subset_union_right _ _ hi, ball_mono $
min_le_right _ _⟩),
end
lemma seminorm_basis_zero_zero (p : ι → seminorm 𝕜 E) (U) (hU : U ∈ seminorm_basis_zero p) :
(0 : E) ∈ U :=
begin
rcases (seminorm_basis_zero_iff p U).mp hU with ⟨ι', r, hr, hU⟩,
rw [hU, mem_ball_zero, (ι'.sup p).zero],
exact hr,
end
lemma seminorm_basis_zero_add (p : ι → seminorm 𝕜 E) (U) (hU : U ∈ seminorm_basis_zero p) :
∃ (V : set E) (H : V ∈ (seminorm_basis_zero p)), V + V ⊆ U :=
begin
rcases (seminorm_basis_zero_iff p U).mp hU with ⟨s, r, hr, hU⟩,
use (s.sup p).ball 0 (r/2),
refine ⟨seminorm_basis_zero_mem p s (div_pos hr zero_lt_two), _⟩,
refine set.subset.trans (ball_add_ball_subset (s.sup p) (r/2) (r/2) 0 0) _,
rw [hU, add_zero, add_halves'],
end
lemma seminorm_basis_zero_neg (p : ι → seminorm 𝕜 E) (U) (hU' : U ∈ seminorm_basis_zero p) :
∃ (V : set E) (H : V ∈ (seminorm_basis_zero p)), V ⊆ (λ (x : E), -x) ⁻¹' U :=
begin
rcases (seminorm_basis_zero_iff p U).mp hU' with ⟨s, r, hr, hU⟩,
rw [hU, neg_preimage, neg_ball (s.sup p), neg_zero],
exact ⟨U, hU', eq.subset hU⟩,
end
/-- The `add_group_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/
def seminorm_add_group_filter_basis [nonempty ι]
(p : ι → seminorm 𝕜 E) : add_group_filter_basis E :=
add_group_filter_basis_of_comm (seminorm_basis_zero p)
(seminorm_basis_zero_nonempty p)
(seminorm_basis_zero_intersect p)
(seminorm_basis_zero_zero p)
(seminorm_basis_zero_add p)
(seminorm_basis_zero_neg p)
lemma seminorm_basis_zero_smul_right (p : ι → seminorm 𝕜 E) (v : E) (U : set E)
(hU : U ∈ seminorm_basis_zero p) : ∀ᶠ (x : 𝕜) in 𝓝 0, x • v ∈ U :=
begin
rcases (seminorm_basis_zero_iff p U).mp hU with ⟨s, r, hr, hU⟩,
rw [hU, filter.eventually_iff],
simp_rw [(s.sup p).mem_ball_zero, (s.sup p).smul],
by_cases h : 0 < (s.sup p) v,
{ simp_rw (lt_div_iff h).symm,
rw ←_root_.ball_zero_eq,
exact metric.ball_mem_nhds 0 (div_pos hr h) },
simp_rw [le_antisymm (not_lt.mp h) ((s.sup p).nonneg v), mul_zero, hr],
exact is_open.mem_nhds is_open_univ (mem_univ 0),
end
variables [nonempty ι]
lemma seminorm_basis_zero_smul (p : ι → seminorm 𝕜 E) (U) (hU : U ∈ seminorm_basis_zero p) :
∃ (V : set 𝕜) (H : V ∈ 𝓝 (0 : 𝕜)) (W : set E)
(H : W ∈ (seminorm_add_group_filter_basis p).sets), V • W ⊆ U :=
begin
rcases (seminorm_basis_zero_iff p U).mp hU with ⟨s, r, hr, hU⟩,
refine ⟨metric.ball 0 r.sqrt, metric.ball_mem_nhds 0 (real.sqrt_pos.mpr hr), _⟩,
refine ⟨(s.sup p).ball 0 r.sqrt, seminorm_basis_zero_mem p s (real.sqrt_pos.mpr hr), _⟩,
refine set.subset.trans (ball_smul_ball (s.sup p) r.sqrt r.sqrt) _,
rw [hU, real.mul_self_sqrt (le_of_lt hr)],
end
lemma seminorm_basis_zero_smul_left (p : ι → seminorm 𝕜 E) (x : 𝕜) (U : set E)
(hU : U ∈ seminorm_basis_zero p) : ∃ (V : set E)
(H : V ∈ (seminorm_add_group_filter_basis p).sets), V ⊆ (λ (y : E), x • y) ⁻¹' U :=
begin
rcases (seminorm_basis_zero_iff p U).mp hU with ⟨s, r, hr, hU⟩,
rw hU,
by_cases h : x ≠ 0,
{ rw [(s.sup p).smul_ball_preimage 0 r x h, smul_zero],
use (s.sup p).ball 0 (r / ∥x∥),
exact ⟨seminorm_basis_zero_mem p s (div_pos hr (norm_pos_iff.mpr h)), subset.rfl⟩ },
refine ⟨(s.sup p).ball 0 r, seminorm_basis_zero_mem p s hr, _⟩,
simp only [not_ne_iff.mp h, subset_def, mem_ball_zero, hr, mem_univ, seminorm.zero,
implies_true_iff, preimage_const_of_mem, zero_smul],
end
/-- The `module_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/
def seminorm_module_filter_basis (p : ι → seminorm 𝕜 E) : module_filter_basis 𝕜 E :=
{ to_add_group_filter_basis := seminorm_add_group_filter_basis p,
smul' := seminorm_basis_zero_smul p,
smul_left' := seminorm_basis_zero_smul_left p,
smul_right' := seminorm_basis_zero_smul_right p }
end filter_basis
section bounded
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F]
/-- The proposition that a linear map is bounded between spaces with families of seminorms. -/
def is_bounded (p : ι → seminorm 𝕜 E) (q : ι' → seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : Prop :=
∀ i, ∃ s : finset ι, ∃ C : ℝ≥0, C ≠ 0 ∧ (q i).comp f ≤ C • s.sup p
lemma is_bounded_const (ι' : Type*) [nonempty ι']
{p : ι → seminorm 𝕜 E} {q : seminorm 𝕜 F} (f : E →ₗ[𝕜] F) :
is_bounded p (λ _ : ι', q) f ↔ ∃ (s : finset ι) C : ℝ≥0, C ≠ 0 ∧ q.comp f ≤ C • s.sup p :=
by simp only [is_bounded, forall_const]
lemma const_is_bounded (ι : Type*) [nonempty ι]
{p : seminorm 𝕜 E} {q : ι' → seminorm 𝕜 F} (f : E →ₗ[𝕜] F) :
is_bounded (λ _ : ι, p) q f ↔ ∀ i, ∃ C : ℝ≥0, C ≠ 0 ∧ (q i).comp f ≤ C • p :=
begin
dunfold is_bounded,
split,
{ intros h i,
rcases h i with ⟨s, C, hC, h⟩,
exact ⟨C, hC, le_trans h (smul_le_smul (finset.sup_le (λ _ _, le_rfl)) le_rfl)⟩ },
intros h i,
use [{classical.arbitrary ι}],
simp only [h, finset.sup_singleton],
end
lemma is_bounded_sup {p : ι → seminorm 𝕜 E} {q : ι' → seminorm 𝕜 F}
{f : E →ₗ[𝕜] F} (hf : is_bounded p q f) (s' : finset ι') :
∃ (C : ℝ≥0) (s : finset ι), 0 < C ∧ (s'.sup q).comp f ≤ C • (s.sup p) :=
begin
classical,
by_cases hs' : ¬s'.nonempty,
{ refine ⟨1, ∅, zero_lt_one, _⟩,
rw [finset.not_nonempty_iff_eq_empty.mp hs', finset.sup_empty, bot_eq_zero, zero_comp],
exact seminorm.nonneg _ },
rw not_not at hs',
choose fₛ fC hf using hf,
use [s'.card • s'.sup fC, finset.bUnion s' fₛ],
split,
{ refine nsmul_pos _ (ne_of_gt (finset.nonempty.card_pos hs')),
cases finset.nonempty.bex hs' with j hj,
exact lt_of_lt_of_le (zero_lt_iff.mpr (and.elim_left (hf j))) (finset.le_sup hj) },
have hs : ∀ i : ι', i ∈ s' → (q i).comp f ≤ s'.sup fC • ((finset.bUnion s' fₛ).sup p) :=
begin
intros i hi,
refine le_trans (and.elim_right (hf i)) (smul_le_smul _ (finset.le_sup hi)),
exact finset.sup_mono (finset.subset_bUnion_of_mem fₛ hi),
end,
refine le_trans (comp_mono f (finset_sup_le_sum q s')) _,
simp_rw [←pullback_apply, add_monoid_hom.map_sum, pullback_apply], --improve this
refine le_trans (finset.sum_le_sum hs) _,
rw [finset.sum_const, smul_assoc],
exact le_rfl,
end
end bounded
section topology
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F]
variables [nonempty ι] [nonempty ι']
/-- The proposition that the topology of `E` is induced by a family of seminorms `p`. -/
class with_seminorms (p : ι → seminorm 𝕜 E) [t : topological_space E] : Prop :=
(topology_eq_with_seminorms : t = (seminorm_module_filter_basis p).topology)
lemma with_seminorms_eq (p : ι → seminorm 𝕜 E) [t : topological_space E] [with_seminorms p] :
t = ((seminorm_module_filter_basis p).topology) := with_seminorms.topology_eq_with_seminorms
/-- The topology of a `normed_space 𝕜 E` is induced by the seminorm `norm_seminorm 𝕜 E`. -/
instance norm_with_seminorms (𝕜 E) [normed_field 𝕜] [semi_normed_group E] [normed_space 𝕜 E] :
with_seminorms (λ (_ : fin 1), norm_seminorm 𝕜 E) :=
begin
let p := λ _ : fin 1, norm_seminorm 𝕜 E,
refine ⟨topological_add_group.ext normed_top_group
((seminorm_add_group_filter_basis _).is_topological_add_group) _⟩,
refine filter.has_basis.eq_of_same_basis metric.nhds_basis_ball _,
rw ←ball_norm_seminorm 𝕜 E,
refine filter.has_basis.to_has_basis (seminorm_add_group_filter_basis p).nhds_zero_has_basis _
(λ r hr, ⟨(norm_seminorm 𝕜 E).ball 0 r, seminorm_basis_zero_singleton_mem p 0 hr, rfl.subset⟩),
rintros U (hU : U ∈ seminorm_basis_zero p),
rcases (seminorm_basis_zero_iff p U).mp hU with ⟨s, r, hr, hU⟩,
use [r, hr],
rw [hU, id.def],
by_cases h : s.nonempty,
{ rw finset.sup_const h },
rw [finset.not_nonempty_iff_eq_empty.mp h, finset.sup_empty, ball_bot _ hr],
exact set.subset_univ _,
end
lemma continuous_from_bounded (p : ι → seminorm 𝕜 E) (q : ι' → seminorm 𝕜 F)
[uniform_space E] [uniform_add_group E] [with_seminorms p]
[uniform_space F] [uniform_add_group F] [with_seminorms q]
(f : E →ₗ[𝕜] F) (hf : is_bounded p q f) : continuous f :=
begin
refine uniform_continuous.continuous _,
refine add_monoid_hom.uniform_continuous_of_continuous_at_zero f.to_add_monoid_hom _,
rw [f.to_add_monoid_hom_coe, continuous_at_def, f.map_zero, with_seminorms_eq p],
intros U hU,
rw [with_seminorms_eq q, add_group_filter_basis.nhds_zero_eq, filter_basis.mem_filter_iff] at hU,
rcases hU with ⟨V, hV : V ∈ seminorm_basis_zero q, hU⟩,
rcases (seminorm_basis_zero_iff q V).mp hV with ⟨s₂, r, hr, hV⟩,
rw hV at hU,
rw [(seminorm_add_group_filter_basis p).nhds_zero_eq, filter_basis.mem_filter_iff],
rcases (is_bounded_sup hf s₂) with ⟨C, s₁, hC, hf⟩,
refine ⟨(s₁.sup p).ball 0 (r/C),
seminorm_basis_zero_mem p _ (div_pos hr (nnreal.coe_pos.mpr hC)), _⟩,
refine subset.trans _ (preimage_mono hU),
simp_rw [←linear_map.map_zero f, ←ball_comp],
refine subset.trans _ (ball_antitone hf),
rw ball_smul (s₁.sup p) hC,
end
lemma cont_with_seminorms_normed_space (F) [semi_normed_group F] [normed_space 𝕜 F]
[uniform_space E] [uniform_add_group E]
(p : ι → seminorm 𝕜 E) [with_seminorms p] (f : E →ₗ[𝕜] F)
(hf : ∃ (s : finset ι) C : ℝ≥0, C ≠ 0 ∧ (norm_seminorm 𝕜 F).comp f ≤ C • s.sup p) :
continuous f :=
begin
rw ←is_bounded_const (fin 1) at hf,
exact continuous_from_bounded p (λ _ : fin 1, norm_seminorm 𝕜 F) f hf,
end
lemma cont_normed_space_to_with_seminorms (E) [semi_normed_group E] [normed_space 𝕜 E]
[uniform_space F] [uniform_add_group F]
(q : ι → seminorm 𝕜 F) [with_seminorms q] (f : E →ₗ[𝕜] F)
(hf : ∀ i : ι, ∃ C : ℝ≥0, C ≠ 0 ∧ (q i).comp f ≤ C • (norm_seminorm 𝕜 E)) : continuous f :=
begin
rw ←const_is_bounded (fin 1) at hf,
exact continuous_from_bounded (λ _ : fin 1, norm_seminorm 𝕜 E) q f hf,
end
end topology
end seminorm
-- TODO: local convexity.
|
module Language.LSP.CodeAction.AddClause
import Core.Context
import Core.Core
import Core.Env
import Core.Metadata
import Core.UnifyState
import Data.List
import Data.List1
import Data.String
import Idris.IDEMode.CaseSplit
import Idris.REPL.Opts
import Idris.Syntax
import Idris.Resugar
import Language.JSON
import Language.LSP.Message
import Libraries.Data.List.Extra
import Libraries.Data.PosMap
import Parser.Unlit
import Server.Configuration
import Server.Log
import Server.Utils
import TTImp.TTImp
buildCodeAction : URI -> List TextEdit -> CodeAction
buildCodeAction uri edits =
let workspaceEdit = MkWorkspaceEdit { changes = Just (singleton uri edits)
, documentChanges = Nothing
, changeAnnotations = Nothing
}
in MkCodeAction { title = "Add clause"
, kind = Just RefactorRewrite
, diagnostics = Just []
, isPreferred = Just False
, disabled = Nothing
, edit = Just workspaceEdit
, command = Nothing
, data_ = Nothing
}
export
addClause : Ref LSPConf LSPConfiguration
=> Ref MD Metadata
=> Ref Ctxt Defs
=> Ref UST UState
=> Ref Syn SyntaxInfo
=> Ref ROpts REPLOpts
=> CodeActionParams -> Core (Maybe CodeAction)
addClause params = do
let True = params.range.start.line == params.range.end.line
| _ => do logString Debug "addClause: start and end line were different"
pure Nothing
let line = params.range.start.line
Just clause <- getClause (line + 1) (UN "")
| Nothing => do logString Debug "addClause: not defined here"
pure Nothing
let range = MkRange (MkPosition (line + 1) 0) (MkPosition (line + 1) 0)
let edit = MkTextEdit range (clause ++ "\n")
pure $ Just $ buildCodeAction params.textDocument.uri [edit]
|
The degree of the primitive part of a polynomial is the same as the degree of the polynomial.
|
The polynomial $p_n(x)$ is zero at $x = 0$.
|
function bitArray2Str(x::Union{BitArray{1},Array{Bool,1}})
parseString(b::Bool) = b == 1 ? "1" : "0"
number = ""
for i = 1:1:length(x)
number = number * parseString(x[i])
end
return number
end
function intArray2Str(x::Array{Int64,1})
parseString(n::Int64) = n == 1 ? "1" : "0"
number = ""
for i = 1:1:length(x)
number = number * parseString(x[i])
end
return number
end
function bin2dec(buf)
num = 0
for i in 1:length(buf)
if buf[length(buf) - i + 1]
num += 2^(i - 1)
end
end
return num
end
function bin2dec_twoscomp(x::Union{BitArray{1},Array{Bool,1}})
if x[1] == false
num = bin2dec(x)
else
_xor = Array{Bool,1}(trues(length(x)))
_sum1 = [falses(length(x) - 1);true]
x = map(⊻, x, _xor) # invert Bits
x = map(+, x, _sum1) # sum 1. At this point x is no longer a BitArray but an Array{Int64,1}
for i = length(x):-1:2
if x[i] == 2
x[i] = 0
x[i - 1] = x[i - 1] + 1
end
end
x[1] == 2 ? x[1] = 0 : x[1] = x[1]
number = intArray2Str(x)
num = -parse(Int, number, base = 2)
end
return num
end
|
# This file was generated, do not modify it. # hide
params(krb) |> pprint
|
[STATEMENT]
lemma implications_cm_all[simp]:
"c_imp (cm_all' c \<Delta>) = c_imp c"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. c_imp (cm_all' c \<Delta>) = c_imp c
[PROOF STEP]
unfolding cm_all'_def Let_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. c_imp (Finite_Set.fold (\<lambda>(loc, t) c. apply_cm c loc t (zcount \<Delta> (loc, t))) c (set_zmset \<Delta>)) = c_imp c
[PROOF STEP]
apply (rule fold_invar[OF finite_set_zmset])
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. c_imp c = c_imp c
2. \<forall>z. \<forall>x\<in>#\<^sub>z\<Delta>. c_imp z = c_imp c \<longrightarrow> c_imp ((case x of (loc, t) \<Rightarrow> \<lambda>c. apply_cm c loc t (zcount \<Delta> (loc, t))) z) = c_imp c
3. comp_fun_commute (\<lambda>a. case a of (loc, t) \<Rightarrow> \<lambda>c. apply_cm c loc t (zcount \<Delta> (loc, t)))
[PROOF STEP]
apply auto
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
|
lemma pole_theorem_analytic_open_superset_0: assumes g: "g analytic_on S" "S \<subseteq> T" "open T" "\<And>z. z \<in> T - {a} \<Longrightarrow> g z = (z - a) * f z" and [simp]: "f a = deriv g a" "g a = 0" shows "f analytic_on S"
|
If two measures are defined on the same space and have the same sets, and if two functions are equal on the space, then the distributions of the functions with respect to the measures are equal.
|
\chapter{A Better Mechanism: Bluetana}\label{chap:3}
\begin{quote}
``So, in the interests of survival, they trained themselves to be agreeing machines instead of thinking machines.
All their minds had to do was to discover what other people were thinking, and then they thought that, too.'' \\
--- Kurt Vonnegut, \emph{Breakfast of Champions}
\end{quote}
In the last chapter, AZDWM documents revealed many skimming devices are Bluetooth enabled.
This motivated the development of an Android application, Bluetana, for skimmer detection.
Bluetana was ultimately deployed to over twenty government investigators.
The application was also responsible for the recovery of over 60 skimmers.
The fraud prevented is in the range of hundreds of thousands to millions of dollars
(Section~\ref{sec:background-on-skimming}).
In this chapter, I detail the development of Bluetana.
I also detail the set of systems allowing for the application's crowd-sourced deployment.
For educational purposes, I also note some of the mistakes made during implementation.
Many features made Bluetana usable in the field by a modest number of inspectors.
This includes the implementation of a \emph{kiosk} mode.
Kiosk mode made Bluetana the only accessible application on the phone.
This ensured inspectors didn't misuse the phones or accidentally close the application.
Another necessity were a fast, accessible-anywhere API endpoints.
This allowed us to push remote updates and get live reports from the phones.
To build this server, we cleverly leveraged existing consumer infrastructure.
Finally, I built caching mechanisms into the application for collected records.
This guaranteed scan records would not be lost until they were successfully uploaded.
Beyond implementation, this chapter details the front-end features added to the application.
Many of these systems were critical in spurring skimmer investigations during inspections.
The chapter gives a full description of the mechanisms used highlighting suspicious devices.
These mechanisms are undergoing constant change, and must adapt as skimmers adapt.
Thus, I conclude with a discussion of correct classification.
Classification remains difficult due to the number of Bluetooth devices seen by inspectors.
\section{Related Work}
There do exist systems and tools currently on the market for skimmer detection.
One example, developed by Scaife et al., is SkimReaper, a device for detecting external skimmers
\cite{scaife2018fear}.
This credit-card shaped device can detect the second read head of external skimmers.
However, this device cannot detect internal skimmers.
Other skimmer detection apps leveraging Bluetooth also exist on the app store.
Scaife et al. reviewed these applications in a survey of skimmer protection mechanisms
\cite{scaife2019rogue}.
They found these applications use a limited feature set in detection.
The apps match potential skimmers by MAC, name, or attempting to connect.
Apps attempting to connect to the device are most concerning.
This can remove forensic evidence recording the last paired MAC address.
\section{Construction of an Application for Skimmer Detection}
Most of the ``skimmer detection" work is actually back-end data analysis.
Thus, the front-end design of a skimmer detection application is trivial.
The application approximates a run-of-the-mill Bluetooth scanner.
Bluetana consists of two pages, a scan page and settings page.
The application consists of \numberofbluetanafiles code files and \numberoflinesbluetana lines in total.
The primary page allows the user to choose to turn scanning on or off and show a list of nearby Bluetooth devices.
The settings page allows for the user to adjust the behavior of scanning and the application.
Inspectors can set the app to scan only while the phone is connected to power.
This makes starting a scan as easy as plugging the phone in and preserves battery.
Another option, to start the app at boot-up, makes data collection more robust.
By requiring less user interaction, we increase the probability that users scan.
The settings page also provides versioning metadata and several override switches.
These are provided in case there are bugs in the application.
\subsection{Key Limitations}
Using Android for skimmer detection has one major drawback.
Bluetooth Service Discovery Protocol (SDP) look-ups require a connection to the other device.
SDP features offered by a device are an effective method of fingerprinting
\cite{wong2005potential}.
As mentioned above, connecting to a skimmer can destroy useful forensic evidence.
It may be possible to circumvent this restriction by sacrificing application stability.
Due to stability concerns, I did not implement these workarounds.
A key limitation to Bluetana specifically was the lack of constant geolocation recording.
Records were not recorded from gas stations with no Bluetooth devices.
Location recording could be used to better assess Bluetooth's prevalence.
For now, only stations with at least one measurable Bluetooth device appear in our analysis.
\subsection{The Benefits and Challenges of Crowdsourcing}
Detection of skimmers requires a significant amount of travel.
One must visit a large number of stations to find even a single skimmer.
Thus, crowd-sourcing Bluetana was necessary for the completion of this study.
This required the applications adoption by the users and making the design easy to use.
It also required sophisticated mechanisms for remote updates from and to the phone.
Bluetan implements a seamless, infallible remote update mechanism.
On application boot, the phone makes an API query to our server for a new application version.
If one is found, the app attempts to download the new application if possible using Android's \texttt{DownloadManager} API.
This allows the app to resume downloading even with a shoddy connection.
The Play Store was avoided due to the sensitivity of the application.
Serving remote updates in this manner causes no issue beyond the initial install.
This initial install requires the user to ``enable untrusted apps".
The application also checks for updates before closing if a fatal exception occurs.
In this case, the application can recover in case a broken update is pushed to the phones.
Another challenge is providing the API endpoints for file upload and download.
Coding these routes securely and efficiently takes time (and isn't much fun).
So facsimile endpoints were created by hosting files on Google Drive.
This requires some care in distribution and control of API keys.
However, these endpoints provided timestamps on data, dynamic content, and speedy hosting.
For research projects, this is a counter-intuitive but robust infrastructural route.
A separate scraper can be written to parse uploaded files into a SQL database.
The Drive did start lagging on direct access from the \emph{browser} after some time.
Otherwise, no significant (non-ethical) issues were encountered using Drive in this manner.
Of Bluetana's front-end features, the most challenging to implement was a kiosk mode.
This mode makes Bluetana the only application accessible on the phone.
Kiosk mode prevents accidental exit from Bluetana and misuse of the phone.
Making a separate APK for this mode would complicate version control.
Thus, I implemented it as a dynamic feature of the application.
Bluetana looks for the existence of an inaccessible-without-root file to enter this mode.
It then swaps the APK's application manifest description to allow extended permissions.
Complications arose in life-cycle management at startup.
Running an application as the home screen causes partial garbage-collection at inopportune times.
The application's initial implementation tied Bluetooth scanning to \emph{fragments} rather than \emph{services}.
Fragments are UI layers intended to be discarded.
Thus, background tasks should almost always be implemented as services.
These are lifecycle-independent data producers which the UI can consume.
This led to more development time making Kiosk mode stable.
\section{Bluetooth Scanning Implementation}
The Android API's \texttt{BluetoothAdapter} class handles Bluetooth scanning.
Methods of this object allow semi-direct control of the phone's Bluetooth module.
Unfortunately, there are minor variations of this class for different hardware.
I worked around these inconsistencies to make the application portable.
The Bluetooth adapter provides another class with Android \texttt{Intent} objects.
These intents provide a \texttt{BluetoothDevice} class object whenever a Bluetooth device is discovered.
Table~\ref{tab:bluetooth-device-fields} contains the functions and constants used for fingerprinting and localization.
The class functions and their descriptions are from Android API site \cite{bluetoothDevice}.
Bluetana records this data into a CSV with~\numfieldsCSV~fields.
Metadata such as location and time discovered are also recorded into this CSV.
\begin{table}
\centering
\caption{
Functions and constants provided by the Android API on device discovery.
All the functions return immediately.
However, \texttt{getName} can return \texttt{null} until the paging step of discovery is complete.
}
\label{tab:bluetooth-device-fields}
\begin{tabular}{@{}lcr@{}}
\toprule
Field & Data & Type \\ \midrule
getAddress() & Returns BluetoothDevice hardware address & String \\
getBluetoothClass() & Get device Bluetooth class & BluetoothClass \\
getName() & Get device Bluetooth name & String \\
getType() & Get Bluetooth device type & int \\
EXTRA\_RSSI & Extra field in intent for signal strength & String \\ \bottomrule
\end{tabular}
\end{table}
\section{Collecting Information}
Bluetana collects data until the size of the CSV file reaches~\filesizebeforecompression.
At this point, the app compresses the file to around~\filesizeaftercompression~for upload.
The CSV is then added to an upload queue folder.
Once a data connection is established, these files are uploaded to the drive.
They are then moved to a ``finished'' cache on the phone.
The drive is scraped every fifteen minutes for new files.
If there are any, the records contained within them are input to a PSQL database.
Additionally, Bluetana contains a ``hitlist'' it routinely downloads from the drive.
As new skimmer Bluetooth features are discovered, they are added to the hitlist.
Device records which match features on the hitlist are highlighted within the app
(Figure~\ref{fig:bluetana-highlight-screenshot}).
If the device is highlighted red, inspectors are instructed to try an localize it.
This increases the number of records collected for suspicious devices.
\begin{figure}
\centering
\includegraphics[width=4.25in]{pics/bluetana-highlight-screenshot.png}
\caption{
Screenshot of Bluetana's suspicious device highlighting.
Highly suspicious devices are highlighted red.
Less suspicious devices are highlighted orange or yellow.
}
\label{fig:bluetana-highlight-screenshot}
\end{figure}
A larger number of records helped to prevent false positives.
Using localization records, Bluetana was able to create heatmaps for each device
(Figure~\ref{fig:heatmap-localization}).
Skimmers will have a high signal strength close to a gas pump.
\begin{figure}
\centering
\includegraphics[width=4.25in]{pics/heatmap-localization.pdf}
\caption{
Screenshot comparing Bluetana's localization data between a skimmer and non-skimmer.
Skimmers, unlike other devices, have much higher signal strength near the gas pump.
Sensitive data has been redacted.
}
\label{fig:heatmap-localization}
\end{figure}
While other devices like car stereos may as well, this is less likely.
Live updates from each phone also allowed notifications to be created.
This allowed our research team to quickly respond to new suspicious devices.
It also allowed for the creation of a leaderboard and other metrics.
These were integrated into a web interface used in retroactive analysis
(Figure~\ref{fig:bluetana-website}).
\begin{figure}
\centering
\includegraphics[width=\linewidth]{pics/bluetana-website.png}
\caption{
Screenshot of Bluetana's web interface.
The site includes a leaderboard as well as query engine for suspicious devices.
Notifications of suspicious devices were pushed to team members via email.
}
\label{fig:bluetana-website}
\end{figure}
\subsection{Scan Time Reduction}
The application also has settings to reduce the Bluetooth scan time.
This helps to speed up device localization and records collected.
Prior research demonstrates a majority of devices are detected within 10 seconds of a Bluetooth scan
\cite{peterson2006bluetooth}.
However, this has two trade-offs.
The first being that the application may not scan both Bluetooth frequency trains.
These trains are used by devices during discovery to minimize signal conflicts
The second is that it prevents the device from performing some of the paging discovery stage.
This stage is used for transferring the device name to the scanning device
\cite{miller2001bluetooth}.
Due to these complications, inspectors phones were set to the android default scan time at startup.
\subsection{Suspicious Device Flagging}\label{sec:skimmer-flagging-workflow}
We designed Bluetana's method of highlighting suspicious devices based upon discovered skimmers.
Initially the hit-list contained information from the internet and existing applications
It then became clear inspectors were not finding Bluetooth Low Energy skimmers.
All the discovered skimmers also had an unset Bluetooth device class
\footnote{A set of bytes used to indicate what a device is (phone, stereo, etc.).}
and uncustomized MAC addresses.
These features alone were effective in finding skimmers
(Figure~\ref{fig:plot-of-class-and-MAC-filtered}).
However, we also performed edit-distance clustering on the device names.
This revealed known products and common default names.
Figure~\ref{fig:flagging-flowchart} presents a flowchart of the current flagging workflow.
\begin{figure}
\centering
\includegraphics[width=4.25in]{plots/plot-of-class-and-MAC-filtered.png}
\caption{
Plot of the distribution of skimmers in the last stage of flagging.
After MAC, Device class, and Bluetooth classic filtering few devices remain.
}
\label{fig:plot-of-class-and-MAC-filtered}
\end{figure}
\begin{figure}
\centering
\includegraphics[width=\linewidth]{plots/flagging-flowchart.pdf}
\caption{
Decision tree for determining how Bluetana highlights a device.
Orange and red devices suggest the performance of localization or manual inspection.
}
\label{fig:flagging-flowchart}
\end{figure}
\section{Future Work and Open Problems}
Bluetana managed to detect 64 skimmers, but the problem is not solved.
Detection mechanisms could be extended to catch SMS-enabled skimmers.
Figure~\ref{fig:bluetooth-or-gsm} demonstrates that these skimmers exist.
Additionally, persistent devices could be deployed for prevention.
For example, it may be possible RF bands for payment data transfers.
It may also be possible to detect the power draw from internal skimmers.
Criminals may also find ways of adapting their Bluetooth signature.
In this case, more sophisticated localization mechanisms may be needed.
The analysis routines of Bluetana itself also have room for improvement.
We relied on inspector's discovery of ground-truth data for our analysis.
However, there may be skimmers they missed, exhibiting uncommon features.
Notably, we did not analyze Bluetooth Low Energy modules in depth.
Additionally, SDP might be used to detect more well-hidden skimmers.
This would require developing workarounds for Android or low-cost embedded skimmer detection devices.
\section{Summary}
This chapter described the implementation of an Android application for skimmer detection.
This application, Bluetana, although simple, was able to discover 64 skimming devices
Beyond Bluetana, this chapter also gives some insight into crowd-sourced application design.
It notes the challenges in deploying an application to many users without the Play store.
Finally, it was important that the application was adaptable and robust.
This allowed continuous improvement after field deployment.
In many ways, this was what allowed for Bluetana's success in skimmer detection.
\section{Acknowledgements}
Thank you to Aaron and Kirill for their motivation and guidance during development.
Thank you to Nishant for being a friend and the other half in deployment and data analysis.
Thank you to the thousands of unnamed engineers and scientists that made this project possible.
And finally, thank you to the lovely staff of the AZDWM for your use of our application.
Chapter 3, in part, is a reprint of the material as it appears in USENIX Security 2019.
Bhaskar, Nishant; Bland, Maxwell; Levchenko, Kirill; Schulman, Aaron, In proc. USENIX Security,
2019. The dissertation/thesis author was a primary investigator and author of this paper.
|
.PH 1 1 \*(XL/paris_hours/phy.bnd
|
[STATEMENT]
lemma degree_linear_factors: "degree (\<Prod> a \<leftarrow> as. [: f a, 1:]) = length as"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. degree (\<Prod>a\<leftarrow>as. [:f a, 1::'a:]) = length as
[PROOF STEP]
proof (induct as)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. degree (\<Prod>a\<leftarrow>[]. [:f a, 1::'a:]) = length []
2. \<And>a as. degree (\<Prod>a\<leftarrow>as. [:f a, 1::'a:]) = length as \<Longrightarrow> degree (\<Prod>a\<leftarrow>a # as. [:f a, 1::'a:]) = length (a # as)
[PROOF STEP]
case (Cons b as)
[PROOF STATE]
proof (state)
this:
degree (\<Prod>a\<leftarrow>as. [:f a, 1::'a:]) = length as
goal (2 subgoals):
1. degree (\<Prod>a\<leftarrow>[]. [:f a, 1::'a:]) = length []
2. \<And>a as. degree (\<Prod>a\<leftarrow>as. [:f a, 1::'a:]) = length as \<Longrightarrow> degree (\<Prod>a\<leftarrow>a # as. [:f a, 1::'a:]) = length (a # as)
[PROOF STEP]
note IH = this
[PROOF STATE]
proof (state)
this:
degree (\<Prod>a\<leftarrow>as. [:f a, 1::'a:]) = length as
goal (2 subgoals):
1. degree (\<Prod>a\<leftarrow>[]. [:f a, 1::'a:]) = length []
2. \<And>a as. degree (\<Prod>a\<leftarrow>as. [:f a, 1::'a:]) = length as \<Longrightarrow> degree (\<Prod>a\<leftarrow>a # as. [:f a, 1::'a:]) = length (a # as)
[PROOF STEP]
have id: "(\<Prod>a\<leftarrow>b # as. [:f a, 1:]) = [:f b,1 :] * (\<Prod>a\<leftarrow>as. [:f a, 1:])"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<Prod>a\<leftarrow>b # as. [:f a, 1::'a:]) = [:f b, 1::'a:] * (\<Prod>a\<leftarrow>as. [:f a, 1::'a:])
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
(\<Prod>a\<leftarrow>b # as. [:f a, 1::'a:]) = [:f b, 1::'a:] * (\<Prod>a\<leftarrow>as. [:f a, 1::'a:])
goal (2 subgoals):
1. degree (\<Prod>a\<leftarrow>[]. [:f a, 1::'a:]) = length []
2. \<And>a as. degree (\<Prod>a\<leftarrow>as. [:f a, 1::'a:]) = length as \<Longrightarrow> degree (\<Prod>a\<leftarrow>a # as. [:f a, 1::'a:]) = length (a # as)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. degree (\<Prod>a\<leftarrow>b # as. [:f a, 1::'a:]) = length (b # as)
[PROOF STEP]
unfolding id
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. degree ([:f b, 1::'a:] * (\<Prod>a\<leftarrow>as. [:f a, 1::'a:])) = length (b # as)
[PROOF STEP]
by (subst degree_monic_mult, insert IH, auto)
[PROOF STATE]
proof (state)
this:
degree (\<Prod>a\<leftarrow>b # as. [:f a, 1::'a:]) = length (b # as)
goal (1 subgoal):
1. degree (\<Prod>a\<leftarrow>[]. [:f a, 1::'a:]) = length []
[PROOF STEP]
qed simp
|
Require Import Merges.Tactics.
Require Import Coq.Lists.List.
Import ListNotations.
Set Implicit Arguments.
Section Index.
Variable A : Type.
Hypothesis Heqdec : forall (a b : A), {a = b} + {a <> b}.
Fixpoint index_of (x : A) (vs : list A) : option nat
:= match vs with
| [] => None
| v::vs' => if Heqdec x v
then Some 0
else match index_of x vs' with
| None => None
| Some n => Some (S n)
end
end.
Lemma index_of__lt_length: forall a xs res,
index_of a xs = Some res ->
res < length xs.
Proof.
induction xs; intros.
- inversion H.
- simpl in H.
destruct (Heqdec a a0).
+ inverts H. simpl. omega.
+ simpl.
destruct (index_of a xs).
assert (n0 < length xs). apply IHxs. reflexivity.
inverts H. omega.
inverts H.
Qed.
Lemma index_of__nth: forall a xs res d,
index_of a xs = Some res ->
nth res xs d = a.
Proof.
induction xs; intros.
- inversion H.
- simpl in H.
destruct (Heqdec a a0).
+ inverts~ H.
+ destruct (index_of a xs); inverts H.
applys~ IHxs.
Qed.
Lemma index_of__not_In: forall a xs,
index_of a xs = None ->
~ In a xs.
Proof.
induction xs; unfold not; intros.
- inversion H0.
- simpl in *.
inverts H0.
destruct (Heqdec a a).
inverts H.
apply~ n.
destruct (Heqdec a a0).
inverts H.
destruct (index_of a xs).
inverts H.
apply~ IHxs.
Qed.
Lemma In__index_of: forall a xs,
In a xs ->
exists n, index_of a xs = Some n.
Proof.
induction xs; intros.
- inversion H.
- simpl in *.
inverts H.
destruct (Heqdec a a). eauto.
destruct n. eauto.
apply IHxs in H0.
destruct H0.
rewrite H.
destruct (Heqdec a a0); eauto.
Qed.
End Index.
|
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*)
theory spec_annotated_fn
imports "CParser.CTranslation"
begin
declare sep_conj_ac [simp add]
external_file "spec_annotated_fn.c"
install_C_file "spec_annotated_fn.c"
print_locale spec_annotated_fn
print_locale Square_spec
thm Square_spec_def
context spec_annotated_fn
begin
thm Square_body_def
thm Square_impl
thm Square_spec_def
thm \<Gamma>_def
thm f_spec_def
thm f_body_def
end
lemma (in Square_spec) foo:
shows "\<Gamma> \<turnstile> \<lbrace> T \<rbrace> \<acute>ret__unsigned :== CALL Square(4) \<lbrace> \<acute>ret__unsigned = 16 \<rbrace> "
apply vcg
apply simp
done
lemma (in spec_annotated_fn)
shows "\<forall>n. \<Gamma> \<turnstile> \<lbrace> \<acute>n = n \<rbrace> \<acute>ret__unsigned :== PROC Square(\<acute>n)
\<lbrace>\<acute>ret__unsigned = n * n \<rbrace>"
apply vcg
done
lemma (in spec_annotated_fn)
shows "\<forall>n. \<Gamma> \<turnstile> \<lbrace> \<acute>n = n \<rbrace> \<acute>ret__unsigned :== PROC f(\<acute>n) \<lbrace> \<acute>ret__unsigned = n * n \<rbrace>"
apply vcg
apply clarsimp
apply (simp add: mex_def meq_def)
done
end
|
Aggarwal has developed an alternative method employing the same sulfide as above and a novel alkylation involving a rhodium carbenoid formed in situ . The method too has limited substrate scope , failing for any electrophiles possessing basic substituents due to competitive consumption of the carbenoid .
|
#include "dsor_utils/frames.hpp"
#include <Eigen/Dense>
// Bring in gtest
#include <gtest/gtest.h>
// Declare a test
TEST(TestSuite, testCase1) {
ASSERT_DOUBLE_EQ(2, 2);
}
// Declare another test
// calling EXPECT_* and/or ASSERT_* macros as needed
TEST(TestSuite, testCase2) {
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
-- Lifting of substitutions, and instance of strength for δ
module SOAS.Coalgebraic.Lift {T : Set} where
open import SOAS.Common
open import SOAS.Context {T}
open import SOAS.Variable
open import SOAS.Families.Core {T}
import SOAS.Families.Delta {T} as δ; open δ.Sorted
open import SOAS.Abstract.Hom {T}
import SOAS.Abstract.Box {T} as □ ; open □.Sorted
import SOAS.Abstract.Coalgebra {T} as →□ ; open →□.Sorted
open import SOAS.Coalgebraic.Map
open import SOAS.Coalgebraic.Strength
private
variable
Γ Δ Θ : Ctx
α : T
module _ {𝒫 : Familyₛ} (𝒫ᴮ : Coalgₚ 𝒫) where
open Coalgₚ 𝒫ᴮ
-- General lifting over an arbitrary context
lift : (Ξ : Ctx) → Γ ~[ 𝒫 ]↝ Δ → (Ξ ∔ Γ) ~[ 𝒫 ]↝ (Ξ ∔ Δ)
lift ∅ σ v = σ v
lift (τ ∙ Ξ) σ new = η new
lift (τ ∙ Ξ) σ (old v) = r (lift Ξ σ v) old
-- Single-variable lifting
lift₁ : {τ : T} → Γ ~[ 𝒫 ]↝ Δ → (τ ∙ Γ) ~[ 𝒫 ]↝ (τ ∙ Δ)
lift₁ {τ = τ} = lift ⌈ τ ⌋
-- General lifting of renaming
rlift : (Ξ : Ctx) → Γ ↝ Δ → (Ξ ∔ Γ) ↝ (Ξ ∔ Δ)
rlift Ξ = lift ℐᴮ Ξ
-- Strength for context extension
δ:Strength : (Ξ : Ctx) → Strength (δF Ξ)
δ:Strength Ξ = record
{ str = λ 𝒫ᴮ 𝒳 h σ → h (lift 𝒫ᴮ Ξ σ)
; str-nat₁ = λ fᴮ⇒ h σ → cong h (dext (str-nat₁ Ξ fᴮ⇒ σ))
; str-nat₂ = λ f h σ → refl
; str-unit = λ 𝒳 h → cong h (dext (str-unit Ξ 𝒳))
; str-assoc = λ 𝒳 fᶜ h σ ς → cong h (dext (str-assoc Ξ 𝒳 fᶜ σ ς))
}
where
open ≡-Reasoning
open Coalgₚ
open Coalgₚ⇒
str-nat₁ : (Ξ : Ctx){𝒫 𝒬 : Familyₛ} {𝒫ᴮ : Coalgₚ 𝒫}
{𝒬ᴮ : Coalgₚ 𝒬} {f : 𝒬 ⇾̣ 𝒫}
→ Coalgₚ⇒ 𝒬ᴮ 𝒫ᴮ f
→ (σ : Γ ~[ 𝒬 ]↝ Δ)(v : ℐ α (Ξ ∔ Γ))
→ lift 𝒫ᴮ Ξ (f ∘ σ) v
≡ f (lift 𝒬ᴮ Ξ σ v)
str-nat₁ ∅ fᴮ⇒ σ v = refl
str-nat₁ (α ∙ Ξ) {𝒫ᴮ = 𝒫ᴮ} fᴮ⇒ σ new = sym (Coalgₚ⇒.⟨η⟩ fᴮ⇒)
str-nat₁ (α ∙ Ξ) {𝒫ᴮ = 𝒫ᴮ} {𝒬ᴮ}{f}fᴮ⇒ σ (old v) = begin
lift 𝒫ᴮ (α ∙ Ξ) (f ∘ σ) (old v)
≡⟨ congr (str-nat₁ Ξ fᴮ⇒ σ v) (λ - → r 𝒫ᴮ - old) ⟩
r 𝒫ᴮ (f (lift 𝒬ᴮ Ξ σ v)) old
≡˘⟨ ⟨r⟩ fᴮ⇒ ⟩
f (lift 𝒬ᴮ (α ∙ Ξ) σ (old v))
∎
str-unit : (Ξ : Ctx) (𝒳 : Familyₛ) (v : ℐ α (Ξ ∔ Γ))
→ lift ℐᴮ Ξ id v ≡ v
str-unit ∅ 𝒳 v = refl
str-unit (α ∙ Ξ) 𝒳 new = refl
str-unit (α ∙ Ξ) 𝒳 (old v) = cong old (str-unit Ξ 𝒳 v)
str-assoc : (Ξ : Ctx) (𝒳 : Familyₛ) {𝒫 𝒬 ℛ : Familyₛ}
{𝒫ᴮ : Coalgₚ 𝒫} {𝒬ᴮ : Coalgₚ 𝒬} {ℛᴮ : Coalgₚ ℛ}
{f : 𝒫 ⇾̣ 〖 𝒬 , ℛ 〗}
(fᶜ : Coalgebraic 𝒫ᴮ 𝒬ᴮ ℛᴮ f) (open Coalgebraic fᶜ)
(σ : Γ ~[ 𝒫 ]↝ Δ) (ς : Δ ~[ 𝒬 ]↝ Θ)(v : ℐ α (Ξ ∔ Γ))
→ lift ℛᴮ Ξ (λ u → f (σ u) ς) v
≡ lift 〖𝒫,𝒴〗ᴮ Ξ (f ∘ σ) v (lift 𝒬ᴮ Ξ ς)
str-assoc ∅ 𝒳 fᶜ σ ς v = refl
str-assoc (β ∙ Ξ) 𝒳 {𝒫ᴮ = 𝒫ᴮ}{𝒬ᴮ}{ℛᴮ} {f} fᶜ σ ς new = begin
η ℛᴮ new ≡˘⟨ f∘η ⟩
f (η 𝒫ᴮ new) (η 𝒬ᴮ) ≡⟨ eq-at-new refl ⟩
f (η 𝒫ᴮ new) (lift 𝒬ᴮ (β ∙ Ξ) ς) ∎
where open Coalgebraic fᶜ
str-assoc {Γ = Γ} (β ∙ Ξ) 𝒳 {𝒫 = 𝒫}{𝒬}{𝒫ᴮ = 𝒫ᴮ}{𝒬ᴮ}{ℛᴮ}{f} fᶜ σ ς (old v) =
begin
r ℛᴮ (lift ℛᴮ Ξ (λ u → f (σ u) ς) v) old
≡⟨ congr (str-assoc Ξ 𝒳 fᶜ σ ς v) (λ - → r ℛᴮ - old) ⟩
r ℛᴮ ( lift 〖𝒫,𝒴〗ᴮ Ξ (f ∘ σ) v (lift 𝒬ᴮ Ξ ς)) old
≡⟨ congr (str-nat₁ Ξ fᴮ⇒ (σ) v) (λ - → r ℛᴮ (- (lift 𝒬ᴮ Ξ ς)) old) ⟩
r ℛᴮ (f (lift 𝒫ᴮ Ξ σ v) (lift 𝒬ᴮ Ξ ς)) old
≡⟨ r∘f ⟩
f (lift 𝒫ᴮ Ξ σ v) (λ u → r 𝒬ᴮ (lift 𝒬ᴮ Ξ ς u) old)
≡˘⟨ congr (str-nat₁ Ξ fᴮ⇒ σ v) (λ - → - (λ u → r 𝒬ᴮ (lift 𝒬ᴮ Ξ ς u) old)) ⟩
lift 〖𝒫,𝒴〗ᴮ Ξ (f ∘ σ) v (λ u → r 𝒬ᴮ (lift 𝒬ᴮ Ξ ς u) old)
∎
where open Coalgebraic fᶜ renaming (ᴮ⇒ to fᴮ⇒)
module δ:Str Θ = Strength (δ:Strength Θ)
-- Derived lifting properties
rlift-id : (𝒳 : Familyₛ)(Ξ : Ctx)(b : δ Ξ (□ 𝒳) α Γ)
→ b (rlift Ξ id) ≡ b id
rlift-id 𝒳 Ξ = Strength.str-unit (δ:Strength Ξ) 𝒳
lift-comp : {𝒫 𝒬 : Familyₛ}{𝒫ᴮ : Coalgₚ 𝒫}{𝒬ᴮ : Coalgₚ 𝒬}
(𝒳 : Familyₛ)(Ξ : Ctx){f : 𝒬 ⇾̣ 𝒫}
(fᴮ⇒ : Coalgₚ⇒ 𝒬ᴮ 𝒫ᴮ f)
(h : δ Ξ 〖 𝒫 , 𝒳 〗 α Γ) (σ : Γ ~[ 𝒬 ]↝ Δ)
→ h (lift 𝒫ᴮ Ξ (f ∘ σ))
≡ h (f ∘ lift 𝒬ᴮ Ξ σ)
lift-comp 𝒳 Ξ fᴮ⇒ h σ = Strength.str-nat₁ (δ:Strength Ξ) {𝒳 = 𝒳} fᴮ⇒ h σ
lift-assoc : {𝒫 𝒬 ℛ : Familyₛ}
{𝒫ᴮ : Coalgₚ 𝒫} {𝒬ᴮ : Coalgₚ 𝒬} {ℛᴮ : Coalgₚ ℛ}
(𝒳 : Familyₛ)(Ξ : Ctx) {f : 𝒫 ⇾̣ 〖 𝒬 , ℛ 〗}
(fᶜ : Coalgebraic 𝒫ᴮ 𝒬ᴮ ℛᴮ f)
(open Coalgebraic fᶜ)
(h : δ Ξ 〖 ℛ , 𝒳 〗 α Γ)
(σ : Γ ~[ 𝒫 ]↝ Δ) (ς : Δ ~[ 𝒬 ]↝ Θ)
→ h (lift ℛᴮ Ξ (λ v → f (σ v) ς))
≡ h (λ v → lift 〖𝒫,𝒴〗ᴮ Ξ (f ∘ σ) v (lift 𝒬ᴮ Ξ ς))
lift-assoc 𝒳 Ξ fᶜ h σ ς = Strength.str-assoc (δ:Strength Ξ) 𝒳 fᶜ h σ ς
lift-dist : {𝒫 𝒬 ℛ : Familyₛ}{𝒫ᴮ : Coalgₚ 𝒫}{𝒬ᴮ : Coalgₚ 𝒬}{ℛᴮ : Coalgₚ ℛ}
(𝒳 : Familyₛ){Ξ : Ctx}{f : 𝒫 ⇾̣ 〖 𝒬 , ℛ 〗}
(fᶜ : Coalgebraic 𝒫ᴮ 𝒬ᴮ ℛᴮ f)
(h : δ Ξ 〖 ℛ , 𝒳 〗 α Γ)
(σ : Γ ~[ 𝒫 ]↝ Δ) (ς : Δ ~[ 𝒬 ]↝ Θ)
→ h (lift ℛᴮ Ξ (λ v → f (σ v) ς))
≡ h (λ v → f (lift 𝒫ᴮ Ξ σ v) (lift 𝒬ᴮ Ξ ς))
lift-dist 𝒳 {Ξ} = Strength.str-dist (δ:Strength Ξ) 𝒳
|
/-
Copyright (c) 2021 Eric Rodriguez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Rodriguez
-/
import algebra.algebra.basic
import algebra.char_p.basic
/-!
# `ne_zero` typeclass
We create a typeclass `ne_zero n` which carries around the fact that `(n : R) ≠ 0`.
## Main declarations
* `ne_zero`: `n ≠ 0` as a typeclass.
-/
/-- A type-class version of `n ≠ 0`. -/
class ne_zero {R} [has_zero R] (n : R) : Prop := (out : n ≠ 0)
lemma ne_zero.ne {R} [has_zero R] (n : R) [h : ne_zero n] : n ≠ 0 := h.out
lemma ne_zero.ne' (n : ℕ) (R) [add_monoid_with_one R] [h : ne_zero (n : R)] :
(n : R) ≠ 0 := h.out
lemma ne_zero_iff {R : Type*} [has_zero R] {n : R} : ne_zero n ↔ n ≠ 0 :=
⟨λ h, h.out, ne_zero.mk⟩
lemma not_ne_zero {R : Type*} [has_zero R] {n : R} : ¬ ne_zero n ↔ n = 0 :=
by simp [ne_zero_iff]
namespace ne_zero
variables {R S M F : Type*} {r : R} {x y : M} {n p : ℕ} {a : ℕ+}
instance pnat : ne_zero (a : ℕ) := ⟨a.ne_zero⟩
instance succ : ne_zero (n + 1) := ⟨n.succ_ne_zero⟩
instance char_zero [ne_zero n] [add_monoid_with_one M] [char_zero M] : ne_zero (n : M) :=
⟨nat.cast_ne_zero.mpr $ ne_zero.ne n⟩
@[priority 100] instance invertible [mul_zero_one_class M] [nontrivial M] [invertible x] :
ne_zero x := ⟨nonzero_of_invertible x⟩
instance coe_trans [has_zero M] [has_coe R S] [has_coe_t S M] [h : ne_zero (r : M)] :
ne_zero ((r : S) : M) := ⟨h.out⟩
lemma trans [has_zero M] [has_coe R S] [has_coe_t S M] (h : ne_zero ((r : S) : M)) :
ne_zero (r : M) := ⟨h.out⟩
lemma of_map [has_zero R] [has_zero M] [zero_hom_class F R M] (f : F) [ne_zero (f r)] :
ne_zero r := ⟨λ h, ne (f r) $ by convert map_zero f⟩
lemma nat_of_ne_zero [semiring R] [semiring S] [ring_hom_class F R S] (f : F)
[hn : ne_zero (n : S)] : ne_zero (n : R) :=
begin
apply ne_zero.of_map f,
simp [hn]
end
lemma of_injective [has_zero R] [h : ne_zero r] [has_zero M] [zero_hom_class F R M]
{f : F} (hf : function.injective f) : ne_zero (f r) :=
⟨by { rw ←map_zero f, exact hf.ne (ne r) }⟩
lemma nat_of_injective [non_assoc_semiring M] [non_assoc_semiring R] [h : ne_zero (n : R)]
[ring_hom_class F R M] {f : F} (hf : function.injective f) : ne_zero (n : M) :=
⟨λ h, (ne_zero.ne' n R) $ hf $ by simpa⟩
lemma pos (r : R) [canonically_ordered_add_monoid R] [ne_zero r] : 0 < r :=
(zero_le r).lt_of_ne $ ne_zero.out.symm
variables (R M)
lemma of_not_dvd [add_monoid_with_one M] [char_p M p] (h : ¬ p ∣ n) : ne_zero (n : M) :=
⟨(not_iff_not.mpr $ char_p.cast_eq_zero_iff M p n).mpr h⟩
lemma of_no_zero_smul_divisors (n : ℕ) [comm_ring R] [ne_zero (n : R)] [ring M] [nontrivial M]
[algebra R M] [no_zero_smul_divisors R M] : ne_zero (n : M) :=
nat_of_injective $ no_zero_smul_divisors.algebra_map_injective R M
lemma of_ne_zero_coe [add_monoid_with_one R] [h : ne_zero (n : R)] : ne_zero n :=
⟨by {casesI h, rintro rfl, by simpa using h}⟩
lemma not_char_dvd [add_monoid_with_one R] (p : ℕ) [char_p R p] (k : ℕ) [h : ne_zero (k : R)] :
¬ p ∣ k :=
by rwa [←not_iff_not.mpr $ char_p.cast_eq_zero_iff R p k, ←ne.def, ←ne_zero_iff]
lemma pos_of_ne_zero_coe [add_monoid_with_one R] [ne_zero (n : R)] : 0 < n :=
(ne_zero.of_ne_zero_coe R).out.bot_lt
end ne_zero
lemma eq_zero_or_ne_zero {α} [has_zero α] (a : α) : a = 0 ∨ ne_zero a :=
(eq_or_ne a 0).imp_right ne_zero.mk
|
[STATEMENT]
lemma WT_enc_callee [WT_intro]:
"\<I>_uniform (sec.Inp_Send ` carrier \<L>) UNIV, \<I>_uniform UNIV (key.Out_Alice ` carrier \<L>) \<oplus>\<^sub>\<I> \<I>_uniform (sec.Inp_Send ` carrier \<L>) UNIV \<turnstile>\<^sub>C CNV enc_callee () \<surd>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<I>_uniform (sec.Inp_Send ` carrier \<L>) UNIV, \<I>_uniform UNIV (key.Out_Alice ` carrier \<L>) \<oplus>\<^sub>\<I> \<I>_uniform (sec.Inp_Send ` carrier \<L>) UNIV \<turnstile>\<^sub>C CNV enc_callee () \<surd>
[PROOF STEP]
by (rule WT_converter_of_callee) (auto 4 3 simp add: enc_callee_def stateless_callee_def image_def split!: key.ousr_alice.split)
|
lemma mult_smult_right [simp]: "p * smult a q = smult a (p * q)"
|
\subsection{Cross-validated results}
The CNN models were trained using an ADAM-optimizer, a batch size of $30$ and the Area Under the Curve (AUC)-score, on the validation set, was used to reduce the learning rate during training. The learning rate was initially at $0.001$ for all models and decreased by a factor of 10, each epoch that the AUC score did not improve. Early stopping was used to stop training when the AUC score, on the validation data, did not improve over two successive epochs.
The ensemble models were trained using n\_estimators $=$ 5 for the random forest classifier and the input features were scaled using a Standard Scaler \cite{pedregosa_scikit-learn_2011}.
All models were scored using F1, F2, G2 and PhysioNet CinC Challenge score for each of the 10-folds \footnote{All codes and models are available here: \url{https://github.com/Bsingstad/FYS-STK4155-oblig3}}. The results in figure \ref{fig:crossval_score} show that the random forest-based ensemble model, using features from all 12 leads, outperformed the other models on all metrics used in this study.
\newpage
\begin{figure}[ht!]
\vspace{0em}
\subfloat[(a) F1-score]{
\begin{minipage}[c][1\width]{
0.5\textwidth}
\centering
\includegraphics[width=0.9\textwidth]{Figures/F_score_val}
\vspace{0em}
\end{minipage}}
\hfill
\subfloat[(b) F2-score]{
\begin{minipage}[c][1\width]{
0.5\textwidth}
\centering
\includegraphics[width=0.9\textwidth]{Figures/F2_score_val}
\vspace{0em}
\end{minipage}}
\end{figure}
\begin{figure}[hb!]
\vspace{0em}
\subfloat[(c) G2-score]{
\begin{minipage}[c][1\width]{
0.5\textwidth}
\centering
\includegraphics[width=0.9\textwidth]{Figures/G2_score_val}
\vspace{1em}
\end{minipage}}
\hfill
\subfloat[(d) PhysioNet/CinC Challenge-score]{
\begin{minipage}[c][1\width]{
0.5\textwidth}
\centering
\includegraphics[width=0.9\textwidth]{Figures/PhysioNetChallenge_score_val}
\vspace{0em}
\end{minipage}}
\caption{The figure shows 10-fold cross-validated scores achieved by ten different models. The upper left shows F1-score, the upper right show F2-score, the lower-left shows G2-score and the lower right shows PhysioNet/CinC Challenge score. The PhysioNet/CinC Challenge score is described in \cite{alday_classification_2020}. The models referred to as ensemble models in this study are named \textit{RandomForest 12-lead} and \textit{RandomForest 2-lead} in this figure.}
\label{fig:crossval_score}
\end{figure}
\subsection{Explainability results}
The tabular explainer that was applied to the ensemble model was trained on $5000$ ECGs from the training data and then tested on an ECG from the test data. The ECG that was explained by the LIME tabular explainer was from a patient with atrial fibrillation. The explanation is visualized in figure \ref{fig:explainability_rand_12}.
%\begin{figure}[!bp]
% \centering
% \includegraphics[width=0.8\textwidth]{Figures/atrialfib_atrialfib.png}
% \caption{}
% \label{fig:parameterregel}
%\end{figure}
\begin{figure}[!htp]
\centering
\includegraphics[width=.90\textwidth]{Figures/Atrialfib.png}
\caption{The figure shows the top $10$ features from an ECG diagnosed with atrial fibrillation (AF). The ECG was correctly classified by the ensemble model. The green bars indicate the degree of contribution towards a positive classification of AF, while the red bars would have been shown if some features contributed towards a negative prediction of AF.
In the labels on the vertical axis; amp is short for amplitude, std is short for standard deviation, HR is short for heart rate, P, Q, R,S,T are the characteristic peaks in the ECG and $I$, $II$, $III$, aVL, aVF, aVR, V1, V2, V3, V4, V5 and V& are the name of the 12 ECG leads.}
\label{fig:explainability_rand_12}
\end{figure}
%\begin{figure}[!htp]
% \centering
% \includegraphics[width=.90\textwidth]{Figures/conduction_disorder_12lead.png}
% \caption{The figure shows the top $10$ features from a ECG that contributed with the prediction. In the labels on the vertical axis; amp is short for amplitude, P, Q, R,S,T are the characteristic peaks in the ECG and $I$, $II$, $III$, aVL, aVF, aVR, V1, V2, V3, V4, V5 and V& are the name of the 12 ECG leads. The ECG-features are extracted from a ECG from a patient with non-specific intra ventricular conduction disorder (NSIVCB). The green bars indicate the the degree of contribution towards an positive classification of NSIVCB, while the red bars shows the degree of contribution towards a negative classification of NSIVCB.}
% \label{fig:explainability_rand_12}
%\end{figure}
%\begin{figure}[!bp]
% \centering
% \includegraphics[width=1\textwidth]{Figures/pacing_rytm_2lead.png}
% \caption{}
% \label{fig:parameterregel}
%\end{figure}
%\begin{figure}[!bp]
% \centering
% \includegraphics[width=1\textwidth]{Figures/Normal-V6.png}
% \caption{The figure shows the explainability results from the Encoder 1D convolutional model. Sub-figure shows a 10 second ECG sequence of a normal ECG extracted from lead $II$ and sub-figure b show The vertical, transparent red bars in the plots indicate sections of the ECG that}
% \label{fig:parameterregel}
%\end{figure}
The recurrent explainer, used on the Encoder model, was trained on $5000$ ECGs from the training data and then tested on an ECG from the test data. The ECG from the test data were abnormal and predicted correctly by the CNN model. The explanation model returned the channel/lead and the index of the sample/feature that was most important for the prediction by the Encoder. Figure \ref{fig:expl_cnn} shows the three most important features in lead aVR for the given test data.
\begin{figure}[!htp]
\centering
\includegraphics[width=1\textwidth]{Figures/Abnormal-aVR.png}
\caption{The figure shows a 10 seconds long ECG-recording represented by the aVR-lead. The ECG is correctly classified as abnormal by a 1D CNN Encoder. The horizontal, transparent green and red lines mark the features in the ECG that are seen as normal and abnormal by LIMEs recurrent explanation model. The green line indicates the part of the ECG that contributes towards a normal classification while the red lines indicates the parts of the ECG that contributes towards an abnormal classification.}
\label{fig:expl_cnn}
\end{figure}
\newpage
|
# This is the content
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.