text
stringlengths 0
3.34M
|
---|
INTEGER FUNCTION IDAMAX(N,DX,INCX)
C
C FINDS THE INDEX OF ELEMENT HAVING MAX. ABSOLUTE VALUE.
C JACK DONGARRA, LINPACK, 3/11/78.
C
DOUBLE PRECISION DX(1),DMAX
INTEGER I,INCX,IX,N
C
IDAMAX = 0
IF( N .LT. 1 ) RETURN
IDAMAX = 1
IF(N.EQ.1)RETURN
IF(INCX.EQ.1)GO TO 20
C
C CODE FOR INCREMENT NOT EQUAL TO 1
C
IX = 1
DMAX = DABS(DX(1))
IX = IX + INCX
DO 10 I = 2,N
IF(DABS(DX(IX)).LE.DMAX) GO TO 5
IDAMAX = I
DMAX = DABS(DX(IX))
5 IX = IX + INCX
10 CONTINUE
RETURN
C
C CODE FOR INCREMENT EQUAL TO 1
C
20 DMAX = DABS(DX(1))
DO 30 I = 2,N
IF(DABS(DX(I)).LE.DMAX) GO TO 30
IDAMAX = I
DMAX = DABS(DX(I))
30 CONTINUE
RETURN
END
|
[GOAL]
M : Type u
inst✝ : Monoid M
X x✝¹ x✝ : Discrete M
f : x✝¹ ⟶ x✝
⊢ (fun X Y => { as := X.as * Y.as }) X x✝¹ = (fun X Y => { as := X.as * Y.as }) X x✝
[PROOFSTEP]
dsimp
[GOAL]
M : Type u
inst✝ : Monoid M
X x✝¹ x✝ : Discrete M
f : x✝¹ ⟶ x✝
⊢ { as := X.as * x✝¹.as } = { as := X.as * x✝.as }
[PROOFSTEP]
rw [eq_of_hom f]
[GOAL]
M : Type u
inst✝ : Monoid M
X₁✝ X₂✝ : Discrete M
f : X₁✝ ⟶ X₂✝
X : Discrete M
⊢ (fun X Y => { as := X.as * Y.as }) X₁✝ X = (fun X Y => { as := X.as * Y.as }) X₂✝ X
[PROOFSTEP]
dsimp
[GOAL]
M : Type u
inst✝ : Monoid M
X₁✝ X₂✝ : Discrete M
f : X₁✝ ⟶ X₂✝
X : Discrete M
⊢ { as := X₁✝.as * X.as } = { as := X₂✝.as * X.as }
[PROOFSTEP]
rw [eq_of_hom f]
[GOAL]
M : Type u
inst✝ : Monoid M
X₁✝ Y₁✝ X₂✝ Y₂✝ : Discrete M
f : X₁✝ ⟶ Y₁✝
g : X₂✝ ⟶ Y₂✝
⊢ (fun X Y => { as := X.as * Y.as }) X₁✝ X₂✝ = (fun X Y => { as := X.as * Y.as }) Y₁✝ Y₂✝
[PROOFSTEP]
dsimp
[GOAL]
M : Type u
inst✝ : Monoid M
X₁✝ Y₁✝ X₂✝ Y₂✝ : Discrete M
f : X₁✝ ⟶ Y₁✝
g : X₂✝ ⟶ Y₂✝
⊢ { as := X₁✝.as * X₂✝.as } = { as := Y₁✝.as * Y₂✝.as }
[PROOFSTEP]
rw [eq_of_hom f, eq_of_hom g]
|
/*
* Copyright (c) 2014, Stanislav Vorobiov
* All rights reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "SpawnerComponent.h"
#include "Scene.h"
#include "SceneObjectFactory.h"
#include "Settings.h"
#include "Utils.h"
#include "Const.h"
#include "SequentialTweening.h"
#include "SingleTweening.h"
#include <boost/make_shared.hpp>
namespace af
{
SpawnerComponent::SpawnerComponent(const b2Vec2& pos, float glowRadius)
: PhasedComponent(phaseThink),
pos_(pos),
glowRadius_(glowRadius),
tweenTime_(0.0f),
sndDone_(audio.createSound("spawner_done.ogg"))
{
}
SpawnerComponent::~SpawnerComponent()
{
}
void SpawnerComponent::accept(ComponentVisitor& visitor)
{
visitor.visitPhasedComponent(shared_from_this());
}
void SpawnerComponent::update(float dt)
{
if (parent()->life() <= 0) {
SceneObjectPtr explosion = sceneObjectFactory.createExplosion1(zOrderExplosion);
explosion->setTransform(parent()->getTransform());
scene()->addObject(explosion);
parent()->removeFromParent();
return;
}
if (!tweening_) {
return;
}
float value = tweening_->getValue(tweenTime_);
lineLight_->setDistance(value * 2.0f);
pointLight_->setDistance(value * glowRadius_);
tweenTime_ += dt;
if (tweening_->finished(tweenTime_)) {
cleanupSpawn();
}
}
void SpawnerComponent::startSpawn(const b2Vec2& dest)
{
cleanupSpawn();
beamAnimation_ = sceneObjectFactory.createLightningAnimation();
beamAnimation_->startAnimation(AnimationDefault);
float angle = vec2angle(dest - pos_);
beam_ = boost::make_shared<RenderBeamComponent>(pos_,
angle, 4.0f,
beamAnimation_->drawable(), zOrderEffects - 1);
beam_->setLength((dest - pos_).Length());
lineLight_ = boost::make_shared<LineLight>();
lineLight_->setDiffuse(false);
lineLight_->setColor(Color(0.0f, 0.0f, 1.0f, 1.0f));
lineLight_->setXray(true);
lineLight_->setDistance(0.0f);
lineLight_->setBothWays(true);
lineLight_->setAngle((b2_pi / 2.0f) + angle);
lineLight_->setPos(pos_ + angle2vec(angle, (dest - pos_).Length() / 2));
lineLight_->setLength((dest - pos_).Length() / 2);
pointLight_ = boost::make_shared<PointLight>();
pointLight_->setColor(Color(0.0f, 0.0f, 1.0f, 1.0f));
pointLight_->setDistance(0.0f);
pointLight_->setXray(true);
pointLight_->setPos(pos_);
lightC_ = boost::make_shared<LightComponent>();
lightC_->attachLight(lineLight_);
lightC_->attachLight(pointLight_);
parent()->addComponent(beam_);
parent()->addComponent(beamAnimation_);
parent()->addComponent(lightC_);
SequentialTweeningPtr tweening = boost::make_shared<SequentialTweening>();
tweening->addTweening(boost::make_shared<SingleTweening>(0.3f, EaseOutQuad, 0.0f, 4.0f / 3.0f));
SequentialTweeningPtr tweening2 = boost::make_shared<SequentialTweening>(true);
tweening2->addTweening(boost::make_shared<SingleTweening>(0.3f, EaseInOutQuad, (4.0f / 3.0f), (3.0f / 4.0f)));
tweening2->addTweening(boost::make_shared<SingleTweening>(0.3f, EaseInOutQuad, (3.0f / 4.0f), (4.0f / 3.0f)));
tweening->addTweening(tweening2);
tweening_ = tweening;
tweenTime_ = 0.0f;
}
void SpawnerComponent::finishSpawn()
{
if (tweening_) {
SequentialTweeningPtr tweening = boost::make_shared<SequentialTweening>();
float t = std::fmod(tweenTime_, 0.6f);
if (t >= 0.3f) {
tweening->addTweening(boost::make_shared<SingleTweening>(0.3f, EaseInOutQuad, (4.0f / 3.0f), (3.0f / 4.0f)));
tweening->addTweening(boost::make_shared<SingleTweening>(0.3f, EaseInOutQuad, (3.0f / 4.0f), (4.0f / 3.0f)));
tweening->addTweening(boost::make_shared<SingleTweening>(0.3f, EaseInQuad, (4.0f / 3.0f), 0.0f));
tweenTime_ = t - 0.3f;
} else {
tweening->addTweening(boost::make_shared<SingleTweening>(0.3f, EaseInOutQuad, (3.0f / 4.0f), (4.0f / 3.0f)));
tweening->addTweening(boost::make_shared<SingleTweening>(0.3f, EaseInQuad, (4.0f / 3.0f), 0.0f));
tweenTime_ = t;
}
tweening_ = tweening;
sndDone_->play();
}
}
void SpawnerComponent::cleanupSpawn()
{
if (beam_) {
beam_->removeFromParent();
beam_.reset();
beamAnimation_->removeFromParent();
beamAnimation_.reset();
lightC_->removeFromParent();
lightC_.reset();
lineLight_.reset();
pointLight_.reset();
tweening_.reset();
}
}
void SpawnerComponent::onRegister()
{
}
void SpawnerComponent::onUnregister()
{
cleanupSpawn();
}
}
|
SUBROUTINE CPRODP (ND,BD,NM1,BM1,NM2,BM2,NA,AA,X,YY,M,A,B,C,D,U,Y)
C
C PRODP APPLIES A SEQUENCE OF MATRIX OPERATIONS TO THE VECTOR X AND
C STORES THE RESULT IN YY PERIODIC BOUNDARY CONDITIONS
C AND COMPLEX CASE
C
C BD,BM1,BM2 ARE ARRAYS CONTAINING ROOTS OF CERTIAN B POLYNOMIALS
C ND,NM1,NM2 ARE THE LENGTHS OF THE ARRAYS BD,BM1,BM2 RESPECTIVELY
C AA ARRAY CONTAINING SCALAR MULTIPLIERS OF THE VECTOR X
C NA IS THE LENGTH OF THE ARRAY AA
C X,YY THE MATRIX OPERATIONS ARE APPLIED TO X AND THE RESULT IS YY
C A,B,C ARE ARRAYS WHICH CONTAIN THE TRIDIAGONAL MATRIX
C M IS THE ORDER OF THE MATRIX
C D,U,Y ARE WORKING ARRAYS
C ISGN DETERMINES WHETHER OR NOT A CHANGE IN SIGN IS MADE
C
COMPLEX Y ,D ,U ,V ,
1 DEN ,BH ,YM ,AM ,
2 Y1 ,Y2 ,YH ,BD ,
3 CRT
DIMENSION A(1) ,B(1) ,C(1) ,X(1) ,
1 Y(1) ,D(1) ,U(1) ,BD(1) ,
2 BM1(1) ,BM2(1) ,AA(1) ,YY(1)
DO 101 J=1,M
Y(J) = CMPLX(X(J),0.)
101 CONTINUE
MM = M-1
MM2 = M-2
ID = ND
M1 = NM1
M2 = NM2
IA = NA
102 IFLG = 0
IF (ID) 111,111,103
103 CRT = BD(ID)
ID = ID-1
IFLG = 1
C
C BEGIN SOLUTION TO SYSTEM
C
BH = B(M)-CRT
YM = Y(M)
DEN = B(1)-CRT
D(1) = C(1)/DEN
U(1) = A(1)/DEN
Y(1) = Y(1)/DEN
V = CMPLX(C(M),0.)
IF (MM2-2) 106,104,104
104 DO 105 J=2,MM2
DEN = B(J)-CRT-A(J)*D(J-1)
D(J) = C(J)/DEN
U(J) = -A(J)*U(J-1)/DEN
Y(J) = (Y(J)-A(J)*Y(J-1))/DEN
BH = BH-V*U(J-1)
YM = YM-V*Y(J-1)
V = -V*D(J-1)
105 CONTINUE
106 DEN = B(M-1)-CRT-A(M-1)*D(M-2)
D(M-1) = (C(M-1)-A(M-1)*U(M-2))/DEN
Y(M-1) = (Y(M-1)-A(M-1)*Y(M-2))/DEN
AM = A(M)-V*D(M-2)
BH = BH-V*U(M-2)
YM = YM-V*Y(M-2)
DEN = BH-AM*D(M-1)
IF (CABS(DEN)) 107,108,107
107 Y(M) = (YM-AM*Y(M-1))/DEN
GO TO 109
108 Y(M) = (1.,0.)
109 Y(M-1) = Y(M-1)-D(M-1)*Y(M)
DO 110 J=2,MM
K = M-J
Y(K) = Y(K)-D(K)*Y(K+1)-U(K)*Y(M)
110 CONTINUE
111 IF (M1) 112,112,114
112 IF (M2) 123,123,113
113 RT = BM2(M2)
M2 = M2-1
GO TO 119
114 IF (M2) 115,115,116
115 RT = BM1(M1)
M1 = M1-1
GO TO 119
116 IF (ABS(BM1(M1))-ABS(BM2(M2))) 118,118,117
117 RT = BM1(M1)
M1 = M1-1
GO TO 119
118 RT = BM2(M2)
M2 = M2-1
C
C MATRIX MULTIPLICATION
C
119 YH = Y(1)
Y1 = (B(1)-RT)*Y(1)+C(1)*Y(2)+A(1)*Y(M)
IF (MM-2) 122,120,120
120 DO 121 J=2,MM
Y2 = A(J)*Y(J-1)+(B(J)-RT)*Y(J)+C(J)*Y(J+1)
Y(J-1) = Y1
Y1 = Y2
121 CONTINUE
122 Y(M) = A(M)*Y(M-1)+(B(M)-RT)*Y(M)+C(M)*YH
Y(M-1) = Y1
IFLG = 1
GO TO 102
123 IF (IA) 126,126,124
124 RT = AA(IA)
IA = IA-1
IFLG = 1
C
C SCALAR MULTIPLICATION
C
DO 125 J=1,M
Y(J) = RT*Y(J)
125 CONTINUE
126 IF (IFLG) 127,127,102
127 DO 128 J=1,M
YY(J) = REAL(Y(J))
128 CONTINUE
RETURN
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, Mario Carneiro, Patrick Massot
-/
import group_theory.quotient_group
import order.filter.pointwise
import topology.algebra.monoid
import topology.compact_open
import topology.sets.compacts
import topology.algebra.constructions
/-!
# Topological groups
This file defines the following typeclasses:
* `topological_group`, `topological_add_group`: multiplicative and additive topological groups,
i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`;
* `has_continuous_sub G` means that `G` has a continuous subtraction operation.
There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate
typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups.
We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`,
`homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in
groups.
## Tags
topological space, group, topological group
-/
open classical set filter topological_space function
open_locale classical topological_space filter pointwise
universes u v w x
variables {α : Type u} {β : Type v} {G : Type w} {H : Type x}
section continuous_mul_group
/-!
### Groups with continuous multiplication
In this section we prove a few statements about groups with continuous `(*)`.
-/
variables [topological_space G] [group G] [has_continuous_mul G]
/-- Multiplication from the left in a topological group as a homeomorphism. -/
@[to_additive "Addition from the left in a topological additive group as a homeomorphism."]
protected def homeomorph.mul_left (a : G) : G ≃ₜ G :=
{ continuous_to_fun := continuous_const.mul continuous_id,
continuous_inv_fun := continuous_const.mul continuous_id,
.. equiv.mul_left a }
@[simp, to_additive]
lemma homeomorph.coe_mul_left (a : G) : ⇑(homeomorph.mul_left a) = (*) a := rfl
@[to_additive]
lemma homeomorph.mul_left_symm (a : G) : (homeomorph.mul_left a).symm = homeomorph.mul_left a⁻¹ :=
by { ext, refl }
@[to_additive]
lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) :=
(homeomorph.mul_left a).is_open_map
@[to_additive is_open.left_add_coset]
lemma is_open.left_coset {U : set G} (h : is_open U) (x : G) : is_open (left_coset x U) :=
is_open_map_mul_left x _ h
@[to_additive]
lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) :=
(homeomorph.mul_left a).is_closed_map
@[to_additive is_closed.left_add_coset]
lemma is_closed.left_coset {U : set G} (h : is_closed U) (x : G) : is_closed (left_coset x U) :=
is_closed_map_mul_left x _ h
/-- Multiplication from the right in a topological group as a homeomorphism. -/
@[to_additive "Addition from the right in a topological additive group as a homeomorphism."]
protected def homeomorph.mul_right (a : G) :
G ≃ₜ G :=
{ continuous_to_fun := continuous_id.mul continuous_const,
continuous_inv_fun := continuous_id.mul continuous_const,
.. equiv.mul_right a }
@[simp, to_additive]
lemma homeomorph.coe_mul_right (a : G) : ⇑(homeomorph.mul_right a) = λ g, g * a := rfl
@[to_additive]
lemma homeomorph.mul_right_symm (a : G) :
(homeomorph.mul_right a).symm = homeomorph.mul_right a⁻¹ :=
by { ext, refl }
@[to_additive]
lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) :=
(homeomorph.mul_right a).is_open_map
@[to_additive is_open.right_add_coset]
lemma is_open.right_coset {U : set G} (h : is_open U) (x : G) : is_open (right_coset U x) :=
is_open_map_mul_right x _ h
@[to_additive]
lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) :=
(homeomorph.mul_right a).is_closed_map
@[to_additive is_closed.right_add_coset]
lemma is_closed.right_coset {U : set G} (h : is_closed U) (x : G) : is_closed (right_coset U x) :=
is_closed_map_mul_right x _ h
@[to_additive]
lemma discrete_topology_of_open_singleton_one (h : is_open ({1} : set G)) : discrete_topology G :=
begin
rw ← singletons_open_iff_discrete,
intro g,
suffices : {g} = (λ (x : G), g⁻¹ * x) ⁻¹' {1},
{ rw this, exact (continuous_mul_left (g⁻¹)).is_open_preimage _ h, },
simp only [mul_one, set.preimage_mul_left_singleton, eq_self_iff_true,
inv_inv, set.singleton_eq_singleton_iff],
end
@[to_additive]
lemma discrete_topology_iff_open_singleton_one : discrete_topology G ↔ is_open ({1} : set G) :=
⟨λ h, forall_open_iff_discrete.mpr h {1}, discrete_topology_of_open_singleton_one⟩
end continuous_mul_group
/-!
### Topological operations on pointwise sums and products
A few results about interior and closure of the pointwise addition/multiplication of sets in groups
with continuous addition/multiplication. See also `submonoid.top_closure_mul_self_eq` in
`topology.algebra.monoid`.
-/
section pointwise
variables [topological_space α] [group α] [has_continuous_mul α] {s t : set α}
@[to_additive]
lemma is_open.mul_left (ht : is_open t) : is_open (s * t) :=
begin
rw ←Union_mul_left_image,
exact is_open_Union (λ a, is_open_Union $ λ ha, is_open_map_mul_left a t ht),
end
@[to_additive]
lemma is_open.mul_right (hs : is_open s) : is_open (s * t) :=
begin
rw ←Union_mul_right_image,
exact is_open_Union (λ a, is_open_Union $ λ ha, is_open_map_mul_right a s hs),
end
@[to_additive]
lemma subset_interior_mul_left : interior s * t ⊆ interior (s * t) :=
interior_maximal (set.mul_subset_mul_right interior_subset) is_open_interior.mul_right
@[to_additive]
lemma subset_interior_mul_right : s * interior t ⊆ interior (s * t) :=
interior_maximal (set.mul_subset_mul_left interior_subset) is_open_interior.mul_left
@[to_additive]
lemma subset_interior_mul : interior s * interior t ⊆ interior (s * t) :=
(set.mul_subset_mul_left interior_subset).trans subset_interior_mul_left
end pointwise
/-!
### `has_continuous_inv` and `has_continuous_neg`
-/
/-- Basic hypothesis to talk about a topological additive group. A topological additive group
over `M`, for example, is obtained by requiring the instances `add_group M` and
`has_continuous_add M` and `has_continuous_neg M`. -/
class has_continuous_neg (G : Type u) [topological_space G] [has_neg G] : Prop :=
(continuous_neg : continuous (λ a : G, -a))
/-- Basic hypothesis to talk about a topological group. A topological group over `M`, for example,
is obtained by requiring the instances `group M` and `has_continuous_mul M` and
`has_continuous_inv M`. -/
@[to_additive]
class has_continuous_inv (G : Type u) [topological_space G] [has_inv G] : Prop :=
(continuous_inv : continuous (λ a : G, a⁻¹))
export has_continuous_inv (continuous_inv)
export has_continuous_neg (continuous_neg)
section continuous_inv
variables [topological_space G] [has_inv G] [has_continuous_inv G]
@[to_additive]
lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s :=
continuous_inv.continuous_on
@[to_additive]
lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x :=
continuous_inv.continuous_within_at
@[to_additive]
lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x :=
continuous_inv.continuous_at
@[to_additive]
lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) :=
continuous_at_inv
/-- If a function converges to a value in a multiplicative topological group, then its inverse
converges to the inverse of this value. For the version in normed fields assuming additionally
that the limit is nonzero, use `tendsto.inv'`. -/
@[to_additive]
lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) :
tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) :=
(continuous_inv.tendsto y).comp h
variables [topological_space α] {f : α → G} {s : set α} {x : α}
@[continuity, to_additive]
lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) :=
continuous_inv.comp hf
@[to_additive]
lemma continuous_at.inv (hf : continuous_at f x) : continuous_at (λ x, (f x)⁻¹) x :=
continuous_at_inv.comp hf
@[to_additive]
lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s :=
continuous_inv.comp_continuous_on hf
@[to_additive]
lemma continuous_within_at.inv (hf : continuous_within_at f s x) :
continuous_within_at (λ x, (f x)⁻¹) s x :=
hf.inv
@[to_additive]
instance [topological_space H] [has_inv H] [has_continuous_inv H] : has_continuous_inv (G × H) :=
⟨(continuous_inv.comp continuous_fst).prod_mk (continuous_inv.comp continuous_snd)⟩
variable {ι : Type*}
@[to_additive]
instance pi.has_continuous_inv {C : ι → Type*} [∀ i, topological_space (C i)]
[∀ i, has_inv (C i)] [∀ i, has_continuous_inv (C i)] : has_continuous_inv (Π i, C i) :=
{ continuous_inv := continuous_pi (λ i, continuous.inv (continuous_apply i)) }
/-- A version of `pi.has_continuous_inv` for non-dependent functions. It is needed because sometimes
Lean fails to use `pi.has_continuous_inv` for non-dependent functions. -/
@[to_additive "A version of `pi.has_continuous_neg` for non-dependent functions. It is needed
because sometimes Lean fails to use `pi.has_continuous_neg` for non-dependent functions."]
instance pi.has_continuous_inv' : has_continuous_inv (ι → G) :=
pi.has_continuous_inv
@[priority 100, to_additive]
instance has_continuous_inv_of_discrete_topology [topological_space H]
[has_inv H] [discrete_topology H] : has_continuous_inv H :=
⟨continuous_of_discrete_topology⟩
section pointwise_limits
variables (G₁ G₂ : Type*) [topological_space G₂] [t2_space G₂]
@[to_additive] lemma is_closed_set_of_map_inv [has_inv G₁] [has_inv G₂] [has_continuous_inv G₂] :
is_closed {f : G₁ → G₂ | ∀ x, f x⁻¹ = (f x)⁻¹ } :=
begin
simp only [set_of_forall],
refine is_closed_Inter (λ i, is_closed_eq (continuous_apply _) (continuous_apply _).inv),
end
end pointwise_limits
instance additive.has_continuous_neg [h : topological_space H] [has_inv H]
[has_continuous_inv H] : @has_continuous_neg (additive H) h _ :=
{ continuous_neg := @continuous_inv H _ _ _ }
instance multiplicative.has_continuous_inv [h : topological_space H] [has_neg H]
[has_continuous_neg H] : @has_continuous_inv (multiplicative H) h _ :=
{ continuous_inv := @continuous_neg H _ _ _ }
end continuous_inv
@[to_additive]
lemma is_compact.inv [topological_space G] [has_involutive_inv G] [has_continuous_inv G]
{s : set G} (hs : is_compact s) : is_compact (s⁻¹) :=
by { rw [← image_inv], exact hs.image continuous_inv }
section lattice_ops
variables {ι' : Sort*} [has_inv G] [has_inv H] {ts : set (topological_space G)}
(h : Π t ∈ ts, @has_continuous_inv G t _) {ts' : ι' → topological_space G}
(h' : Π i, @has_continuous_inv G (ts' i) _) {t₁ t₂ : topological_space G}
(h₁ : @has_continuous_inv G t₁ _) (h₂ : @has_continuous_inv G t₂ _)
{t : topological_space H} [has_continuous_inv H]
@[to_additive] lemma has_continuous_inv_Inf :
@has_continuous_inv G (Inf ts) _ :=
{ continuous_inv := continuous_Inf_rng (λ t ht, continuous_Inf_dom ht
(@has_continuous_inv.continuous_inv G t _ (h t ht))) }
include h'
@[to_additive] lemma has_continuous_inv_infi :
@has_continuous_inv G (⨅ i, ts' i) _ :=
by {rw ← Inf_range, exact has_continuous_inv_Inf (set.forall_range_iff.mpr h')}
omit h'
include h₁ h₂
@[to_additive] lemma has_continuous_inv_inf :
@has_continuous_inv G (t₁ ⊓ t₂) _ :=
by {rw inf_eq_infi, refine has_continuous_inv_infi (λ b, _), cases b; assumption}
end lattice_ops
section topological_group
/-!
### Topological groups
A topological group is a group in which the multiplication and inversion operations are
continuous. Topological additive groups are defined in the same way. Equivalently, we can require
that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous.
-/
/-- A topological (additive) group is a group in which the addition and negation operations are
continuous. -/
class topological_add_group (G : Type u) [topological_space G] [add_group G]
extends has_continuous_add G, has_continuous_neg G : Prop
/-- A topological group is a group in which the multiplication and inversion operations are
continuous.
When you declare an instance that does not already have a `uniform_space` instance,
you should also provide an instance of `uniform_space` and `uniform_group` using
`topological_group.to_uniform_space` and `topological_group_is_uniform`. -/
@[to_additive]
class topological_group (G : Type*) [topological_space G] [group G]
extends has_continuous_mul G, has_continuous_inv G : Prop
section conj
/-- we slightly weaken the type class assumptions here so that it will also apply to `ennreal`, but
we nevertheless leave it in the `topological_group` namespace. -/
variables [topological_space G] [has_inv G] [has_mul G]
[has_continuous_mul G]
/-- Conjugation is jointly continuous on `G × G` when both `mul` and `inv` are continuous. -/
@[to_additive "Conjugation is jointly continuous on `G × G` when both `mul` and `inv` are
continuous."]
lemma topological_group.continuous_conj_prod [has_continuous_inv G] :
continuous (λ g : G × G, g.fst * g.snd * g.fst⁻¹) :=
continuous_mul.mul (continuous_inv.comp continuous_fst)
/-- Conjugation by a fixed element is continuous when `mul` is continuous. -/
@[to_additive "Conjugation by a fixed element is continuous when `add` is continuous."]
lemma topological_group.continuous_conj (g : G) : continuous (λ (h : G), g * h * g⁻¹) :=
(continuous_mul_right g⁻¹).comp (continuous_mul_left g)
/-- Conjugation acting on fixed element of the group is continuous when both `mul` and
`inv` are continuous. -/
@[to_additive "Conjugation acting on fixed element of the additive group is continuous when both
`add` and `neg` are continuous."]
lemma topological_group.continuous_conj' [has_continuous_inv G]
(h : G) : continuous (λ (g : G), g * h * g⁻¹) :=
(continuous_mul_right h).mul continuous_inv
end conj
variables [topological_space G] [group G] [topological_group G]
[topological_space α] {f : α → G} {s : set α} {x : α}
section zpow
@[continuity, to_additive]
lemma continuous_zpow : ∀ z : ℤ, continuous (λ a : G, a ^ z)
| (int.of_nat n) := by simpa using continuous_pow n
| -[1+n] := by simpa using (continuous_pow (n + 1)).inv
instance add_group.has_continuous_const_smul_int {A} [add_group A] [topological_space A]
[topological_add_group A] : has_continuous_const_smul ℤ A := ⟨continuous_zsmul⟩
instance add_group.has_continuous_smul_int {A} [add_group A] [topological_space A]
[topological_add_group A] : has_continuous_smul ℤ A :=
⟨continuous_uncurry_of_discrete_topology continuous_zsmul⟩
@[continuity, to_additive]
lemma continuous.zpow {f : α → G} (h : continuous f) (z : ℤ) :
continuous (λ b, (f b) ^ z) :=
(continuous_zpow z).comp h
@[to_additive]
lemma continuous_on_zpow {s : set G} (z : ℤ) : continuous_on (λ x, x ^ z) s :=
(continuous_zpow z).continuous_on
@[to_additive]
lemma continuous_at_zpow (x : G) (z : ℤ) : continuous_at (λ x, x ^ z) x :=
(continuous_zpow z).continuous_at
@[to_additive]
lemma filter.tendsto.zpow {α} {l : filter α} {f : α → G} {x : G} (hf : tendsto f l (𝓝 x)) (z : ℤ) :
tendsto (λ x, f x ^ z) l (𝓝 (x ^ z)) :=
(continuous_at_zpow _ _).tendsto.comp hf
@[to_additive]
lemma continuous_within_at.zpow {f : α → G} {x : α} {s : set α} (hf : continuous_within_at f s x)
(z : ℤ) : continuous_within_at (λ x, f x ^ z) s x :=
hf.zpow z
@[to_additive]
lemma continuous_at.zpow {f : α → G} {x : α} (hf : continuous_at f x) (z : ℤ) :
continuous_at (λ x, f x ^ z) x :=
hf.zpow z
@[to_additive continuous_on.zsmul]
lemma continuous_on.zpow {f : α → G} {s : set α} (hf : continuous_on f s) (z : ℤ) :
continuous_on (λ x, f x ^ z) s :=
λ x hx, (hf x hx).zpow z
end zpow
section ordered_comm_group
variables [topological_space H] [ordered_comm_group H] [topological_group H]
@[to_additive] lemma tendsto_inv_nhds_within_Ioi {a : H} :
tendsto has_inv.inv (𝓝[>] a) (𝓝[<] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Iio {a : H} :
tendsto has_inv.inv (𝓝[<] a) (𝓝[>] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Ioi_inv {a : H} :
tendsto has_inv.inv (𝓝[>] (a⁻¹)) (𝓝[<] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ioi _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Iio_inv {a : H} :
tendsto has_inv.inv (𝓝[<] (a⁻¹)) (𝓝[>] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iio _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Ici {a : H} :
tendsto has_inv.inv (𝓝[≥] a) (𝓝[≤] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Iic {a : H} :
tendsto has_inv.inv (𝓝[≤] a) (𝓝[≥] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Ici_inv {a : H} :
tendsto has_inv.inv (𝓝[≥] (a⁻¹)) (𝓝[≤] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ici _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Iic_inv {a : H} :
tendsto has_inv.inv (𝓝[≤] (a⁻¹)) (𝓝[≥] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iic _ _ _ _ (a⁻¹)
end ordered_comm_group
@[instance, to_additive]
instance [topological_space H] [group H] [topological_group H] :
topological_group (G × H) :=
{ continuous_inv := continuous_inv.prod_map continuous_inv }
@[to_additive]
instance pi.topological_group {C : β → Type*} [∀ b, topological_space (C b)]
[∀ b, group (C b)] [∀ b, topological_group (C b)] : topological_group (Π b, C b) :=
{ continuous_inv := continuous_pi (λ i, (continuous_apply i).inv) }
open mul_opposite
@[to_additive]
instance [group α] [has_continuous_inv α] : has_continuous_inv αᵐᵒᵖ :=
{ continuous_inv := continuous_induced_rng $ (@continuous_inv α _ _ _).comp continuous_unop }
/-- If multiplication is continuous in `α`, then it also is in `αᵐᵒᵖ`. -/
@[to_additive "If addition is continuous in `α`, then it also is in `αᵃᵒᵖ`."]
instance [group α] [topological_group α] :
topological_group αᵐᵒᵖ := { }
variable (G)
/-- Inversion in a topological group as a homeomorphism. -/
@[to_additive "Negation in a topological group as a homeomorphism."]
protected def homeomorph.inv : G ≃ₜ G :=
{ continuous_to_fun := continuous_inv,
continuous_inv_fun := continuous_inv,
.. equiv.inv G }
@[to_additive]
lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) :=
((homeomorph.inv G).comap_nhds_eq _).trans (congr_arg nhds one_inv)
/-- The map `(x, y) ↦ (x, xy)` as a homeomorphism. This is a shear mapping. -/
@[to_additive "The map `(x, y) ↦ (x, x + y)` as a homeomorphism.
This is a shear mapping."]
protected def homeomorph.shear_mul_right : G × G ≃ₜ G × G :=
{ continuous_to_fun := continuous_fst.prod_mk continuous_mul,
continuous_inv_fun := continuous_fst.prod_mk $ continuous_fst.inv.mul continuous_snd,
.. equiv.prod_shear (equiv.refl _) equiv.mul_left }
@[simp, to_additive]
lemma homeomorph.shear_mul_right_coe :
⇑(homeomorph.shear_mul_right G) = λ z : G × G, (z.1, z.1 * z.2) :=
rfl
@[simp, to_additive]
lemma homeomorph.shear_mul_right_symm_coe :
⇑(homeomorph.shear_mul_right G).symm = λ z : G × G, (z.1, z.1⁻¹ * z.2) :=
rfl
variables {G}
@[to_additive]
lemma is_open.inv {s : set G} (hs : is_open s) : is_open s⁻¹ := hs.preimage continuous_inv
@[to_additive]
lemma is_closed.inv {s : set G} (hs : is_closed s) : is_closed s⁻¹ := hs.preimage continuous_inv
@[to_additive]
lemma inv_closure (s : set G) : (closure s)⁻¹ = closure s⁻¹ :=
(homeomorph.inv G).preimage_closure s
@[to_additive] lemma is_open.mul_closure {U : set G} (hU : is_open U) (s : set G) :
U * closure s = U * s :=
begin
refine subset.antisymm _ (mul_subset_mul subset.rfl subset_closure),
rintro _ ⟨a, b, ha, hb, rfl⟩,
rw mem_closure_iff at hb,
have hbU : b ∈ U⁻¹ * {a * b},
from ⟨a⁻¹, a * b, inv_mem_inv.2 ha, rfl, inv_mul_cancel_left _ _⟩,
rcases hb _ hU.inv.mul_right hbU with ⟨_, ⟨c, d, hc, (rfl : d = _), rfl⟩, hcs⟩,
exact ⟨c⁻¹, _, hc, hcs, inv_mul_cancel_left _ _⟩
end
@[to_additive] lemma is_open.closure_mul {U : set G} (hU : is_open U) (s : set G) :
closure s * U = s * U :=
by rw [← inv_inv (closure s * U), set.mul_inv_rev, inv_closure, hU.inv.mul_closure,
set.mul_inv_rev, inv_inv, inv_inv]
namespace subgroup
@[to_additive] instance (S : subgroup G) :
topological_group S :=
{ continuous_inv :=
begin
rw embedding_subtype_coe.to_inducing.continuous_iff,
exact continuous_subtype_coe.inv
end,
..S.to_submonoid.has_continuous_mul }
end subgroup
/-- The (topological-space) closure of a subgroup of a space `M` with `has_continuous_mul` is
itself a subgroup. -/
@[to_additive "The (topological-space) closure of an additive subgroup of a space `M` with
`has_continuous_add` is itself an additive subgroup."]
def subgroup.topological_closure (s : subgroup G) : subgroup G :=
{ carrier := closure (s : set G),
inv_mem' := λ g m, by simpa [←mem_inv, inv_closure] using m,
..s.to_submonoid.topological_closure }
@[simp, to_additive] lemma subgroup.topological_closure_coe {s : subgroup G} :
(s.topological_closure : set G) = closure s :=
rfl
@[to_additive]
instance subgroup.topological_closure_topological_group (s : subgroup G) :
topological_group (s.topological_closure) :=
{ continuous_inv :=
begin
apply continuous_induced_rng,
change continuous (λ p : s.topological_closure, (p : G)⁻¹),
continuity,
end
..s.to_submonoid.topological_closure_has_continuous_mul}
@[to_additive] lemma subgroup.subgroup_topological_closure (s : subgroup G) :
s ≤ s.topological_closure :=
subset_closure
@[to_additive] lemma subgroup.is_closed_topological_closure (s : subgroup G) :
is_closed (s.topological_closure : set G) :=
by convert is_closed_closure
@[to_additive] lemma subgroup.topological_closure_minimal
(s : subgroup G) {t : subgroup G} (h : s ≤ t) (ht : is_closed (t : set G)) :
s.topological_closure ≤ t :=
closure_minimal h ht
@[to_additive] lemma dense_range.topological_closure_map_subgroup [group H] [topological_space H]
[topological_group H] {f : G →* H} (hf : continuous f) (hf' : dense_range f) {s : subgroup G}
(hs : s.topological_closure = ⊤) :
(s.map f).topological_closure = ⊤ :=
begin
rw set_like.ext'_iff at hs ⊢,
simp only [subgroup.topological_closure_coe, subgroup.coe_top, ← dense_iff_closure_eq] at hs ⊢,
exact hf'.dense_image hf hs
end
/-- The topological closure of a normal subgroup is normal.-/
@[to_additive "The topological closure of a normal additive subgroup is normal."]
lemma subgroup.is_normal_topological_closure {G : Type*} [topological_space G] [group G]
[topological_group G] (N : subgroup G) [N.normal] :
(subgroup.topological_closure N).normal :=
{ conj_mem := λ n hn g,
begin
apply mem_closure_of_continuous (topological_group.continuous_conj g) hn,
intros m hm,
exact subset_closure (subgroup.normal.conj_mem infer_instance m hm g),
end }
@[to_additive] lemma mul_mem_connected_component_one {G : Type*} [topological_space G]
[mul_one_class G] [has_continuous_mul G] {g h : G} (hg : g ∈ connected_component (1 : G))
(hh : h ∈ connected_component (1 : G)) : g * h ∈ connected_component (1 : G) :=
begin
rw connected_component_eq hg,
have hmul: g ∈ connected_component (g*h),
{ apply continuous.image_connected_component_subset (continuous_mul_left g),
rw ← connected_component_eq hh,
exact ⟨(1 : G), mem_connected_component, by simp only [mul_one]⟩ },
simpa [← connected_component_eq hmul] using (mem_connected_component)
end
@[to_additive] lemma inv_mem_connected_component_one {G : Type*} [topological_space G] [group G]
[topological_group G] {g : G} (hg : g ∈ connected_component (1 : G)) :
g⁻¹ ∈ connected_component (1 : G) :=
begin
rw ← one_inv,
exact continuous.image_connected_component_subset continuous_inv _
((set.mem_image _ _ _).mp ⟨g, hg, rfl⟩)
end
/-- The connected component of 1 is a subgroup of `G`. -/
@[to_additive "The connected component of 0 is a subgroup of `G`."]
def subgroup.connected_component_of_one (G : Type*) [topological_space G] [group G]
[topological_group G] : subgroup G :=
{ carrier := connected_component (1 : G),
one_mem' := mem_connected_component,
mul_mem' := λ g h hg hh, mul_mem_connected_component_one hg hh,
inv_mem' := λ g hg, inv_mem_connected_component_one hg }
/-- If a subgroup of a topological group is commutative, then so is its topological closure. -/
@[to_additive "If a subgroup of an additive topological group is commutative, then so is its
topological closure."]
def subgroup.comm_group_topological_closure [t2_space G] (s : subgroup G)
(hs : ∀ (x y : s), x * y = y * x) : comm_group s.topological_closure :=
{ ..s.topological_closure.to_group,
..s.to_submonoid.comm_monoid_topological_closure hs }
@[to_additive exists_nhds_half_neg]
lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) :
∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v / w ∈ s :=
have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G),
from continuous_at_fst.mul continuous_at_snd.inv (by simpa),
by simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage]
using this
@[to_additive]
lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x :=
((homeomorph.mul_right x⁻¹).comap_nhds_eq 1).trans $ show 𝓝 (1 * x⁻¹⁻¹) = 𝓝 x, by simp
@[simp, to_additive] lemma map_mul_left_nhds (x y : G) : map ((*) x) (𝓝 y) = 𝓝 (x * y) :=
(homeomorph.mul_left x).map_nhds_eq y
@[to_additive] lemma map_mul_left_nhds_one (x : G) : map ((*) x) (𝓝 1) = 𝓝 x := by simp
@[to_additive]
lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G}
(tg : @topological_group G t _) (tg' : @topological_group G t' _)
(h : @nhds G t 1 = @nhds G t' 1) : t = t' :=
eq_of_nhds_eq_nhds $ λ x, by
rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h]
@[to_additive]
lemma topological_group.of_nhds_aux {G : Type*} [group G] [topological_space G]
(hinv : tendsto (λ (x : G), x⁻¹) (𝓝 1) (𝓝 1))
(hleft : ∀ (x₀ : G), 𝓝 x₀ = map (λ (x : G), x₀ * x) (𝓝 1))
(hconj : ∀ (x₀ : G), map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) ≤ 𝓝 1) : continuous (λ x : G, x⁻¹) :=
begin
rw continuous_iff_continuous_at,
rintros x₀,
have key : (λ x, (x₀*x)⁻¹) = (λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹) ∘ (λ x, x⁻¹),
by {ext ; simp[mul_assoc] },
calc map (λ x, x⁻¹) (𝓝 x₀)
= map (λ x, x⁻¹) (map (λ x, x₀*x) $ 𝓝 1) : by rw hleft
... = map (λ x, (x₀*x)⁻¹) (𝓝 1) : by rw filter.map_map
... = map (((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) ∘ (λ x, x⁻¹)) (𝓝 1) : by rw key
... = map ((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) _ : by rw ← filter.map_map
... ≤ map ((λ x, x₀⁻¹ * x) ∘ λ x, x₀ * x * x₀⁻¹) (𝓝 1) : map_mono hinv
... = map (λ x, x₀⁻¹ * x) (map (λ x, x₀ * x * x₀⁻¹) (𝓝 1)) : filter.map_map
... ≤ map (λ x, x₀⁻¹ * x) (𝓝 1) : map_mono (hconj x₀)
... = 𝓝 x₀⁻¹ : (hleft _).symm
end
@[to_additive]
lemma topological_group.of_nhds_one' {G : Type u} [group G] [topological_space G]
(hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1))
(hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1))
(hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1))
(hright : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : topological_group G :=
begin
refine { continuous_mul := (has_continuous_mul.of_nhds_one hmul hleft hright).continuous_mul,
continuous_inv := topological_group.of_nhds_aux hinv hleft _ },
intros x₀,
suffices : map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) = 𝓝 1, by simp [this, le_refl],
rw [show (λ x, x₀ * x * x₀⁻¹) = (λ x, x₀ * x) ∘ λ x, x*x₀⁻¹, by {ext, simp [mul_assoc] },
← filter.map_map, ← hright, hleft x₀⁻¹, filter.map_map],
convert map_id,
ext,
simp
end
@[to_additive]
lemma topological_group.of_nhds_one {G : Type u} [group G] [topological_space G]
(hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1))
(hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1))
(hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1))
(hconj : ∀ x₀ : G, tendsto (λ x, x₀*x*x₀⁻¹) (𝓝 1) (𝓝 1)) : topological_group G :=
{ continuous_mul := begin
rw continuous_iff_continuous_at,
rintros ⟨x₀, y₀⟩,
have key : (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) =
((λ x, x₀*y₀*x) ∘ (uncurry (*)) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id)),
by { ext, simp [uncurry, prod.map, mul_assoc] },
specialize hconj y₀⁻¹, rw inv_inv at hconj,
calc map (λ (p : G × G), p.1 * p.2) (𝓝 (x₀, y₀))
= map (λ (p : G × G), p.1 * p.2) ((𝓝 x₀) ×ᶠ 𝓝 y₀)
: by rw nhds_prod_eq
... = map (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) ((𝓝 1) ×ᶠ (𝓝 1))
: by rw [hleft x₀, hleft y₀, prod_map_map_eq, filter.map_map]
... = map (((λ x, x₀*y₀*x) ∘ (uncurry (*))) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id))((𝓝 1) ×ᶠ (𝓝 1))
: by rw key
... = map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((map (λ x, y₀⁻¹*x*y₀) $ 𝓝 1) ×ᶠ (𝓝 1))
: by rw [← filter.map_map, ← prod_map_map_eq', map_id]
... ≤ map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((𝓝 1) ×ᶠ (𝓝 1))
: map_mono (filter.prod_mono hconj $ le_rfl)
... = map (λ x, x₀*y₀*x) (map (uncurry (*)) ((𝓝 1) ×ᶠ (𝓝 1))) : by rw filter.map_map
... ≤ map (λ x, x₀*y₀*x) (𝓝 1) : map_mono hmul
... = 𝓝 (x₀*y₀) : (hleft _).symm
end,
continuous_inv := topological_group.of_nhds_aux hinv hleft hconj}
@[to_additive]
lemma topological_group.of_comm_of_nhds_one {G : Type u} [comm_group G] [topological_space G]
(hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1))
(hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1))
(hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : topological_group G :=
topological_group.of_nhds_one hmul hinv hleft (by simpa using tendsto_id)
end topological_group
section quotient_topological_group
variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal)
@[to_additive]
instance quotient_group.quotient.topological_space {G : Type*} [group G] [topological_space G]
(N : subgroup G) : topological_space (G ⧸ N) :=
quotient.topological_space
open quotient_group
@[to_additive]
lemma quotient_group.is_open_map_coe : is_open_map (coe : G → G ⧸ N) :=
begin
intros s s_op,
change is_open ((coe : G → G ⧸ N) ⁻¹' (coe '' s)),
rw quotient_group.preimage_image_coe N s,
exact is_open_Union (λ n, (continuous_mul_right _).is_open_preimage s s_op)
end
@[to_additive]
instance topological_group_quotient [N.normal] : topological_group (G ⧸ N) :=
{ continuous_mul := begin
have cont : continuous ((coe : G → G ⧸ N) ∘ (λ (p : G × G), p.fst * p.snd)) :=
continuous_quot_mk.comp continuous_mul,
have quot : quotient_map (λ p : G × G, ((p.1 : G ⧸ N), (p.2 : G ⧸ N))),
{ apply is_open_map.to_quotient_map,
{ exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) },
{ exact continuous_quot_mk.prod_map continuous_quot_mk },
{ exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } },
exact (quotient_map.continuous_iff quot).2 cont,
end,
continuous_inv := begin
have : continuous ((coe : G → G ⧸ N) ∘ (λ (a : G), a⁻¹)) :=
continuous_quot_mk.comp continuous_inv,
convert continuous_quotient_lift _ this,
end }
end quotient_topological_group
/-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property
automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/
class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop :=
(continuous_sub : continuous (λ p : G × G, p.1 - p.2))
/-- A typeclass saying that `λ p : G × G, p.1 / p.2` is a continuous function. This property
automatically holds for topological groups. Lemmas using this class have primes.
The unprimed version is for `group_with_zero`. -/
@[to_additive]
class has_continuous_div (G : Type*) [topological_space G] [has_div G] : Prop :=
(continuous_div' : continuous (λ p : G × G, p.1 / p.2))
@[priority 100, to_additive] -- see Note [lower instance priority]
instance topological_group.to_has_continuous_div [topological_space G] [group G]
[topological_group G] : has_continuous_div G :=
⟨by { simp only [div_eq_mul_inv], exact continuous_fst.mul continuous_snd.inv }⟩
export has_continuous_sub (continuous_sub)
export has_continuous_div (continuous_div')
section has_continuous_div
variables [topological_space G] [has_div G] [has_continuous_div G]
@[to_additive sub]
lemma filter.tendsto.div' {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a))
(hg : tendsto g l (𝓝 b)) : tendsto (λ x, f x / g x) l (𝓝 (a / b)) :=
(continuous_div'.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
@[to_additive const_sub]
lemma filter.tendsto.const_div' (b : G) {c : G} {f : α → G} {l : filter α}
(h : tendsto f l (𝓝 c)) : tendsto (λ k : α, b / f k) l (𝓝 (b / c)) :=
tendsto_const_nhds.div' h
@[to_additive sub_const]
lemma filter.tendsto.div_const' (b : G) {c : G} {f : α → G} {l : filter α}
(h : tendsto f l (𝓝 c)) : tendsto (λ k : α, f k / b) l (𝓝 (c / b)) :=
h.div' tendsto_const_nhds
variables [topological_space α] {f g : α → G} {s : set α} {x : α}
@[continuity, to_additive sub] lemma continuous.div' (hf : continuous f) (hg : continuous g) :
continuous (λ x, f x / g x) :=
continuous_div'.comp (hf.prod_mk hg : _)
@[to_additive continuous_sub_left]
lemma continuous_div_left' (a : G) : continuous (λ b : G, a / b) :=
continuous_const.div' continuous_id
@[to_additive continuous_sub_right]
lemma continuous_div_right' (a : G) : continuous (λ b : G, b / a) :=
continuous_id.div' continuous_const
@[to_additive sub]
lemma continuous_at.div' {f g : α → G} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) :
continuous_at (λx, f x / g x) x :=
hf.div' hg
@[to_additive sub]
lemma continuous_within_at.div' (hf : continuous_within_at f s x)
(hg : continuous_within_at g s x) :
continuous_within_at (λ x, f x / g x) s x :=
hf.div' hg
@[to_additive sub]
lemma continuous_on.div' (hf : continuous_on f s) (hg : continuous_on g s) :
continuous_on (λx, f x / g x) s :=
λ x hx, (hf x hx).div' (hg x hx)
end has_continuous_div
section div_in_topological_group
variables [group G] [topological_space G] [topological_group G]
/-- A version of `homeomorph.mul_left a b⁻¹` that is defeq to `a / b`. -/
@[to_additive /-" A version of `homeomorph.add_left a (-b)` that is defeq to `a - b`. "-/,
simps {simp_rhs := tt}]
def homeomorph.div_left (x : G) : G ≃ₜ G :=
{ continuous_to_fun := continuous_const.div' continuous_id,
continuous_inv_fun := continuous_inv.mul continuous_const,
.. equiv.div_left x }
/-- A version of `homeomorph.mul_right a⁻¹ b` that is defeq to `b / a`. -/
@[to_additive /-" A version of `homeomorph.add_right (-a) b` that is defeq to `b - a`. "-/,
simps {simp_rhs := tt}]
def homeomorph.div_right (x : G) : G ≃ₜ G :=
{ continuous_to_fun := continuous_id.div' continuous_const,
continuous_inv_fun := continuous_id.mul continuous_const,
.. equiv.div_right x }
@[to_additive]
lemma is_open_map_div_right (a : G) : is_open_map (λ x, x / a) :=
(homeomorph.div_right a).is_open_map
@[to_additive]
lemma is_closed_map_div_right (a : G) : is_closed_map (λ x, x / a) :=
(homeomorph.div_right a).is_closed_map
end div_in_topological_group
@[to_additive]
lemma nhds_translation_div [topological_space G] [group G] [topological_group G] (x : G) :
comap (λy:G, y / x) (𝓝 1) = 𝓝 x :=
by simpa only [div_eq_mul_inv] using nhds_translation_mul_inv x
/-- additive group with a neighbourhood around 0.
Only used to construct a topology and uniform space.
This is currently only available for commutative groups, but it can be extended to
non-commutative groups too.
-/
class add_group_with_zero_nhd (G : Type u) extends add_comm_group G :=
(Z [] : filter G)
(zero_Z : pure 0 ≤ Z)
(sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z)
section filter_mul
section
variables (G) [topological_space G] [group G] [topological_group G]
@[to_additive]
lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G :=
⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩
@[to_additive]
lemma topological_group.regular_space [t1_space G] : regular_space G :=
⟨assume s a hs ha,
let f := λ p : G × G, p.1 * (p.2)⁻¹ in
have hf : continuous f := continuous_fst.mul continuous_snd.inv,
-- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s);
-- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s)
let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ :=
is_open_prod_iff.1 ((is_open_compl_iff.2 hs).preimage hf) a (1:G) (by simpa [f]) in
begin
use [s * t₂, ht₂.mul_left, λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩],
rw [nhds_within, inf_principal_eq_bot, mem_nhds_iff],
refine ⟨t₁, _, ht₁, a_mem_t₁⟩,
rintros x hx ⟨y, z, hy, hz, yz⟩,
have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz,
have : x * z⁻¹ ∈ s, rw ← yz, simpa,
contradiction
end⟩
local attribute [instance] topological_group.regular_space
@[to_additive]
lemma topological_group.t2_space [t1_space G] : t2_space G := regular_space.t2_space G
end
section
/-! Some results about an open set containing the product of two sets in a topological group. -/
variables [topological_space G] [group G] [topological_group G]
/-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1`
such that `K * V ⊆ U`. -/
@[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of
`0` such that `K + V ⊆ U`."]
lemma compact_open_separated_mul_right {K U : set G} (hK : is_compact K) (hU : is_open U)
(hKU : K ⊆ U) : ∃ V ∈ 𝓝 (1 : G), K * V ⊆ U :=
begin
apply hK.induction_on,
{ exact ⟨univ, by simp⟩ },
{ rintros s t hst ⟨V, hV, hV'⟩,
exact ⟨V, hV, (mul_subset_mul_right hst).trans hV'⟩ },
{ rintros s t ⟨V, V_in, hV'⟩ ⟨W, W_in, hW'⟩,
use [V ∩ W, inter_mem V_in W_in],
rw union_mul,
exact union_subset ((mul_subset_mul_left (V.inter_subset_left W)).trans hV')
((mul_subset_mul_left (V.inter_subset_right W)).trans hW') },
{ intros x hx,
have := tendsto_mul (show U ∈ 𝓝 (x * 1), by simpa using hU.mem_nhds (hKU hx)),
rw [nhds_prod_eq, mem_map, mem_prod_iff] at this,
rcases this with ⟨t, ht, s, hs, h⟩,
rw [← image_subset_iff, image_mul_prod] at h,
exact ⟨t, mem_nhds_within_of_mem_nhds ht, s, hs, h⟩ }
end
open mul_opposite
/-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1`
such that `V * K ⊆ U`. -/
@[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of
`0` such that `V + K ⊆ U`."]
lemma compact_open_separated_mul_left {K U : set G} (hK : is_compact K) (hU : is_open U)
(hKU : K ⊆ U) : ∃ V ∈ 𝓝 (1 : G), V * K ⊆ U :=
begin
rcases compact_open_separated_mul_right (hK.image continuous_op) (op_homeomorph.is_open_map U hU)
(image_subset op hKU) with ⟨V, (hV : V ∈ 𝓝 (op (1 : G))), hV' : op '' K * V ⊆ op '' U⟩,
refine ⟨op ⁻¹' V, continuous_op.continuous_at hV, _⟩,
rwa [← image_preimage_eq V op_surjective, ← image_op_mul, image_subset_iff,
preimage_image_eq _ op_injective] at hV'
end
/-- A compact set is covered by finitely many left multiplicative translates of a set
with non-empty interior. -/
@[to_additive "A compact set is covered by finitely many left additive translates of a set
with non-empty interior."]
lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K)
(hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V :=
begin
obtain ⟨t, ht⟩ : ∃ t : finset G, K ⊆ ⋃ x ∈ t, interior (((*) x) ⁻¹' V),
{ refine hK.elim_finite_subcover (λ x, interior $ ((*) x) ⁻¹' V) (λ x, is_open_interior) _,
cases hV with g₀ hg₀,
refine λ g hg, mem_Union.2 ⟨g₀ * g⁻¹, _⟩,
refine preimage_interior_subset_interior_preimage (continuous_const.mul continuous_id) _,
rwa [mem_preimage, inv_mul_cancel_right] },
exact ⟨t, subset.trans ht $ Union₂_mono $ λ g hg, interior_subset⟩
end
/-- Every locally compact separable topological group is σ-compact.
Note: this is not true if we drop the topological group hypothesis. -/
@[priority 100, to_additive separable_locally_compact_add_group.sigma_compact_space]
instance separable_locally_compact_group.sigma_compact_space
[separable_space G] [locally_compact_space G] : sigma_compact_space G :=
begin
obtain ⟨L, hLc, hL1⟩ := exists_compact_mem_nhds (1 : G),
refine ⟨⟨λ n, (λ x, x * dense_seq G n) ⁻¹' L, _, _⟩⟩,
{ intro n, exact (homeomorph.mul_right _).compact_preimage.mpr hLc },
{ refine Union_eq_univ_iff.2 (λ x, _),
obtain ⟨_, ⟨n, rfl⟩, hn⟩ : (range (dense_seq G) ∩ (λ y, x * y) ⁻¹' L).nonempty,
{ rw [← (homeomorph.mul_left x).apply_symm_apply 1] at hL1,
exact (dense_range_dense_seq G).inter_nhds_nonempty
((homeomorph.mul_left x).continuous.continuous_at $ hL1) },
exact ⟨n, hn⟩ }
end
/-- Every separated topological group in which there exists a compact set with nonempty interior
is locally compact. -/
@[to_additive] lemma topological_space.positive_compacts.locally_compact_space_of_group
[t2_space G] (K : positive_compacts G) :
locally_compact_space G :=
begin
refine locally_compact_of_compact_nhds (λ x, _),
obtain ⟨y, hy⟩ := K.interior_nonempty,
let F := homeomorph.mul_left (x * y⁻¹),
refine ⟨F '' K, _, K.compact.image F.continuous⟩,
suffices : F.symm ⁻¹' K ∈ 𝓝 x, by { convert this, apply equiv.image_eq_preimage },
apply continuous_at.preimage_mem_nhds F.symm.continuous.continuous_at,
have : F.symm x = y, by simp [F, homeomorph.mul_left_symm],
rw this,
exact mem_interior_iff_mem_nhds.1 hy
end
end
section
variables [topological_space G] [comm_group G] [topological_group G]
@[to_additive]
lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y :=
filter_eq $ set.ext $ assume s,
begin
rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)],
split,
{ rintros ⟨t, ht, ts⟩,
rcases exists_nhds_one_split ht with ⟨V, V1, h⟩,
refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V,
⟨V, V1, subset.refl _⟩, ⟨V, V1, subset.refl _⟩, _⟩,
rintros a ⟨v, w, v_mem, w_mem, rfl⟩,
apply ts,
simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) v_mem (w * y⁻¹) w_mem },
{ rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩,
refine ⟨b ∩ d, inter_mem hb hd, assume v, _⟩,
simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *,
rintros ⟨vb, vd⟩,
refine ac ⟨v * y⁻¹, y, _, _, _⟩,
{ rw ← mul_assoc _ _ _ at vb, exact ba _ vb },
{ apply dc y, rw mul_right_inv, exact mem_of_mem_nhds hd },
{ simp only [inv_mul_cancel_right] } }
end
/-- On a topological group, `𝓝 : G → filter G` can be promoted to a `mul_hom`. -/
@[to_additive "On an additive topological group, `𝓝 : G → filter G` can be promoted to an
`add_hom`.", simps]
def nhds_mul_hom : mul_hom G (filter G) :=
{ to_fun := 𝓝,
map_mul' := λ_ _, nhds_mul _ _ }
end
end filter_mul
instance additive.topological_add_group {G} [h : topological_space G]
[group G] [topological_group G] : @topological_add_group (additive G) h _ :=
{ continuous_neg := @continuous_inv G _ _ _ }
instance multiplicative.topological_group {G} [h : topological_space G]
[add_group G] [topological_add_group G] : @topological_group (multiplicative G) h _ :=
{ continuous_inv := @continuous_neg G _ _ _ }
section quotient
variables [group G] [topological_space G] [topological_group G] {Γ : subgroup G}
@[to_additive]
instance quotient_group.has_continuous_const_smul : has_continuous_const_smul G (G ⧸ Γ) :=
{ continuous_const_smul := λ g₀, begin
apply continuous_coinduced_dom,
change continuous (λ g : G, quotient_group.mk (g₀ * g)),
exact continuous_coinduced_rng.comp (continuous_mul_left g₀),
end }
@[to_additive]
lemma quotient_group.continuous_smul₁ (x : G ⧸ Γ) : continuous (λ g : G, g • x) :=
begin
obtain ⟨g₀, rfl⟩ : ∃ g₀, quotient_group.mk g₀ = x,
{ exact @quotient.exists_rep _ (quotient_group.left_rel Γ) x },
change continuous (λ g, quotient_group.mk (g * g₀)),
exact continuous_coinduced_rng.comp (continuous_mul_right g₀)
end
@[to_additive]
instance quotient_group.has_continuous_smul [locally_compact_space G] :
has_continuous_smul G (G ⧸ Γ) :=
{ continuous_smul := begin
let F : G × G ⧸ Γ → G ⧸ Γ := λ p, p.1 • p.2,
change continuous F,
have H : continuous (F ∘ (λ p : G × G, (p.1, quotient_group.mk p.2))),
{ change continuous (λ p : G × G, quotient_group.mk (p.1 * p.2)),
refine continuous_coinduced_rng.comp continuous_mul },
exact quotient_map.continuous_lift_prod_right quotient_map_quotient_mk H,
end }
end quotient
namespace units
open mul_opposite (continuous_op continuous_unop)
variables [monoid α] [topological_space α] [has_continuous_mul α] [monoid β] [topological_space β]
[has_continuous_mul β]
@[to_additive] instance : topological_group αˣ :=
{ continuous_inv := continuous_induced_rng ((continuous_unop.comp
(@continuous_embed_product α _ _).snd).prod_mk (continuous_op.comp continuous_coe)) }
/-- The topological group isomorphism between the units of a product of two monoids, and the product
of the units of each monoid. -/
def homeomorph.prod_units : homeomorph (α × β)ˣ (αˣ × βˣ) :=
{ continuous_to_fun :=
begin
show continuous (λ i : (α × β)ˣ, (map (monoid_hom.fst α β) i, map (monoid_hom.snd α β) i)),
refine continuous.prod_mk _ _,
{ refine continuous_induced_rng ((continuous_fst.comp units.continuous_coe).prod_mk _),
refine mul_opposite.continuous_op.comp (continuous_fst.comp _),
simp_rw units.inv_eq_coe_inv,
exact units.continuous_coe.comp continuous_inv, },
{ refine continuous_induced_rng ((continuous_snd.comp units.continuous_coe).prod_mk _),
simp_rw units.coe_map_inv,
exact continuous_op.comp (continuous_snd.comp (units.continuous_coe.comp continuous_inv)), }
end,
continuous_inv_fun :=
begin
refine continuous_induced_rng (continuous.prod_mk _ _),
{ exact (units.continuous_coe.comp continuous_fst).prod_mk
(units.continuous_coe.comp continuous_snd), },
{ refine continuous_op.comp
(units.continuous_coe.comp $ continuous_induced_rng $ continuous.prod_mk _ _),
{ exact (units.continuous_coe.comp (continuous_inv.comp continuous_fst)).prod_mk
(units.continuous_coe.comp (continuous_inv.comp continuous_snd)) },
{ exact continuous_op.comp ((units.continuous_coe.comp continuous_fst).prod_mk
(units.continuous_coe.comp continuous_snd)) }}
end,
..mul_equiv.prod_units }
end units
section lattice_ops
variables {ι : Sort*} [group G] [group H] {ts : set (topological_space G)}
(h : ∀ t ∈ ts, @topological_group G t _) {ts' : ι → topological_space G}
(h' : ∀ i, @topological_group G (ts' i) _) {t₁ t₂ : topological_space G}
(h₁ : @topological_group G t₁ _) (h₂ : @topological_group G t₂ _)
{t : topological_space H} [topological_group H] {F : Type*}
[monoid_hom_class F G H] (f : F)
@[to_additive] lemma topological_group_Inf :
@topological_group G (Inf ts) _ :=
{ continuous_inv := @has_continuous_inv.continuous_inv G (Inf ts) _
(@has_continuous_inv_Inf _ _ _
(λ t ht, @topological_group.to_has_continuous_inv G t _ (h t ht))),
continuous_mul := @has_continuous_mul.continuous_mul G (Inf ts) _
(@has_continuous_mul_Inf _ _ _
(λ t ht, @topological_group.to_has_continuous_mul G t _ (h t ht))) }
include h'
@[to_additive] lemma topological_group_infi :
@topological_group G (⨅ i, ts' i) _ :=
by {rw ← Inf_range, exact topological_group_Inf (set.forall_range_iff.mpr h')}
omit h'
include h₁ h₂
@[to_additive] lemma topological_group_inf :
@topological_group G (t₁ ⊓ t₂) _ :=
by {rw inf_eq_infi, refine topological_group_infi (λ b, _), cases b; assumption}
omit h₁ h₂
@[to_additive] lemma topological_group_induced :
@topological_group G (t.induced f) _ :=
{ continuous_inv :=
begin
letI : topological_space G := t.induced f,
refine continuous_induced_rng _,
simp_rw [function.comp, map_inv],
exact continuous_inv.comp (continuous_induced_dom : continuous f)
end,
continuous_mul := @has_continuous_mul.continuous_mul G (t.induced f) _
(@has_continuous_mul_induced G H _ _ t _ _ _ f) }
end lattice_ops
/-!
### Lattice of group topologies
We define a type class `group_topology α` which endows a group `α` with a topology such that all
group operations are continuous.
Group topologies on a fixed group `α` are ordered, by reverse inclusion. They form a complete
lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology.
Any function `f : α → β` induces `coinduced f : topological_space α → group_topology β`.
The additive version `add_group_topology α` and corresponding results are provided as well.
-/
/-- A group topology on a group `α` is a topology for which multiplication and inversion
are continuous. -/
structure group_topology (α : Type u) [group α]
extends topological_space α, topological_group α : Type u
/-- An additive group topology on an additive group `α` is a topology for which addition and
negation are continuous. -/
structure add_group_topology (α : Type u) [add_group α]
extends topological_space α, topological_add_group α : Type u
attribute [to_additive] group_topology
namespace group_topology
variables [group α]
/-- A version of the global `continuous_mul` suitable for dot notation. -/
@[to_additive]
lemma continuous_mul' (g : group_topology α) :
by haveI := g.to_topological_space; exact continuous (λ p : α × α, p.1 * p.2) :=
begin
letI := g.to_topological_space,
haveI := g.to_topological_group,
exact continuous_mul,
end
/-- A version of the global `continuous_inv` suitable for dot notation. -/
@[to_additive]
lemma continuous_inv' (g : group_topology α) :
by haveI := g.to_topological_space; exact continuous (has_inv.inv : α → α) :=
begin
letI := g.to_topological_space,
haveI := g.to_topological_group,
exact continuous_inv,
end
@[to_additive]
lemma to_topological_space_injective :
function.injective (to_topological_space : group_topology α → topological_space α):=
λ f g h, by { cases f, cases g, congr' }
@[ext, to_additive]
lemma ext' {f g : group_topology α} (h : f.is_open = g.is_open) : f = g :=
to_topological_space_injective $ topological_space_eq h
/-- The ordering on group topologies on the group `γ`.
`t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/
@[to_additive]
instance : partial_order (group_topology α) :=
partial_order.lift to_topological_space to_topological_space_injective
@[simp, to_additive] lemma to_topological_space_le {x y : group_topology α} :
x.to_topological_space ≤ y.to_topological_space ↔ x ≤ y := iff.rfl
@[to_additive]
instance : has_top (group_topology α) :=
⟨{to_topological_space := ⊤,
continuous_mul := continuous_top,
continuous_inv := continuous_top}⟩
@[simp, to_additive] lemma to_topological_space_top :
(⊤ : group_topology α).to_topological_space = ⊤ := rfl
@[to_additive]
instance : has_bot (group_topology α) :=
⟨{to_topological_space := ⊥,
continuous_mul := by continuity,
continuous_inv := continuous_bot}⟩
@[simp, to_additive] lemma to_topological_space_bot :
(⊥ : group_topology α).to_topological_space = ⊥ := rfl
@[to_additive]
instance : bounded_order (group_topology α) :=
{ top := ⊤,
le_top := λ x, show x.to_topological_space ≤ ⊤, from le_top,
bot := ⊥,
bot_le := λ x, show ⊥ ≤ x.to_topological_space, from bot_le }
@[to_additive]
instance : has_inf (group_topology α) :=
{ inf := λ x y,
{ to_topological_space := x.to_topological_space ⊓ y.to_topological_space,
continuous_mul := continuous_inf_rng
(continuous_inf_dom_left₂ x.continuous_mul') (continuous_inf_dom_right₂ y.continuous_mul'),
continuous_inv := continuous_inf_rng
(continuous_inf_dom_left x.continuous_inv') (continuous_inf_dom_right y.continuous_inv') } }
@[simp, to_additive]
lemma to_topological_space_inf (x y : group_topology α) :
(x ⊓ y).to_topological_space = x.to_topological_space ⊓ y.to_topological_space := rfl
@[to_additive]
instance : semilattice_inf (group_topology α) :=
to_topological_space_injective.semilattice_inf _ to_topological_space_inf
@[to_additive]
instance : inhabited (group_topology α) := ⟨⊤⟩
local notation `cont` := @continuous _ _
@[to_additive "Infimum of a collection of additive group topologies"]
instance : has_Inf (group_topology α) :=
{ Inf := λ S,
{ to_topological_space := Inf (to_topological_space '' S),
continuous_mul := continuous_Inf_rng begin
rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI,
exact continuous_Inf_dom₂
(set.mem_image_of_mem to_topological_space haS)
(set.mem_image_of_mem to_topological_space haS) continuous_mul,
end,
continuous_inv := continuous_Inf_rng begin
rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI,
exact continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_inv,
end, } }
@[simp, to_additive]
lemma to_topological_space_Inf (s : set (group_topology α)) :
(Inf s).to_topological_space = Inf (to_topological_space '' s) := rfl
@[simp, to_additive]
lemma to_topological_space_infi {ι} (s : ι → group_topology α) :
(⨅ i, s i).to_topological_space = ⨅ i, (s i).to_topological_space :=
congr_arg Inf (range_comp _ _).symm
/-- Group topologies on `γ` form a complete lattice, with `⊥` the discrete topology and `⊤` the
indiscrete topology.
The infimum of a collection of group topologies is the topology generated by all their open sets
(which is a group topology).
The supremum of two group topologies `s` and `t` is the infimum of the family of all group
topologies contained in the intersection of `s` and `t`. -/
@[to_additive]
instance : complete_semilattice_Inf (group_topology α) :=
{ Inf_le := λ S a haS, to_topological_space_le.1 $ Inf_le ⟨a, haS, rfl⟩,
le_Inf :=
begin
intros S a hab,
apply topological_space.complete_lattice.le_Inf,
rintros _ ⟨b, hbS, rfl⟩,
exact hab b hbS,
end,
..group_topology.has_Inf,
..group_topology.partial_order }
@[to_additive]
instance : complete_lattice (group_topology α) :=
{ inf := (⊓),
top := ⊤,
bot := ⊥,
..group_topology.bounded_order,
..group_topology.semilattice_inf,
..complete_lattice_of_complete_semilattice_Inf _ }
/-- Given `f : α → β` and a topology on `α`, the coinduced group topology on `β` is the finest
topology such that `f` is continuous and `β` is a topological group. -/
@[to_additive "Given `f : α → β` and a topology on `α`, the coinduced additive group topology on `β`
is the finest topology such that `f` is continuous and `β` is a topological additive group."]
def coinduced {α β : Type*} [t : topological_space α] [group β] (f : α → β) :
group_topology β :=
Inf {b : group_topology β | (topological_space.coinduced f t) ≤ b.to_topological_space}
@[to_additive]
lemma coinduced_continuous {α β : Type*} [t : topological_space α] [group β]
(f : α → β) : cont t (coinduced f).to_topological_space f :=
begin
rw continuous_iff_coinduced_le,
refine le_Inf _,
rintros _ ⟨t', ht', rfl⟩,
exact ht',
end
end group_topology
|
/-
Copyright (c) 2021 Vladimir Goryachev. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Vladimir Goryachev, Kyle Miller, Scott Morrison, Eric Rodriguez
-/
import set_theory.cardinal.basic
import tactic.ring
/-!
# Counting on ℕ
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the `count` function, which gives, for any predicate on the natural numbers,
"how many numbers under `k` satisfy this predicate?".
We then prove several expected lemmas about `count`, relating it to the cardinality of other
objects, and helping to evaluate it for specific `k`.
-/
open finset
namespace nat
variable (p : ℕ → Prop)
section count
variable [decidable_pred p]
/-- Count the number of naturals `k < n` satisfying `p k`. -/
def count (n : ℕ) : ℕ := (list.range n).countp p
@[simp] lemma count_zero : count p 0 = 0 :=
by rw [count, list.range_zero, list.countp]
/-- A fintype instance for the set relevant to `nat.count`. Locally an instance in locale `count` -/
def count_set.fintype (n : ℕ) : fintype {i // i < n ∧ p i} :=
begin
apply fintype.of_finset ((finset.range n).filter p),
intro x,
rw [mem_filter, mem_range],
refl,
end
localized "attribute [instance] nat.count_set.fintype" in count
lemma count_eq_card_filter_range (n : ℕ) : count p n = ((range n).filter p).card :=
by { rw [count, list.countp_eq_length_filter], refl, }
/-- `count p n` can be expressed as the cardinality of `{k // k < n ∧ p k}`. -/
lemma count_eq_card_fintype (n : ℕ) : count p n = fintype.card {k : ℕ // k < n ∧ p k} :=
by { rw [count_eq_card_filter_range, ←fintype.card_of_finset, ←count_set.fintype], refl, }
lemma count_succ (n : ℕ) : count p (n + 1) = count p n + (if p n then 1 else 0) :=
by split_ifs; simp [count, list.range_succ, h]
@[mono] lemma count_monotone : monotone (count p) :=
monotone_nat_of_le_succ $ λ n, by by_cases h : p n; simp [count_succ, h]
lemma count_add (a b : ℕ) : count p (a + b) = count p a + count (λ k, p (a + k)) b :=
begin
have : disjoint ((range a).filter p) (((range b).map $ add_left_embedding a).filter p),
{ apply disjoint_filter_filter,
rw finset.disjoint_left,
simp_rw [mem_map, mem_range, add_left_embedding_apply],
rintro x hx ⟨c, _, rfl⟩,
exact (self_le_add_right _ _).not_lt hx },
simp_rw [count_eq_card_filter_range, range_add, filter_union, card_disjoint_union this,
filter_map, add_left_embedding, card_map], refl,
end
lemma count_add' (a b : ℕ) : count p (a + b) = count (λ k, p (k + b)) a + count p b :=
by { rw [add_comm, count_add, add_comm], simp_rw [add_comm b] }
lemma count_one : count p 1 = if p 0 then 1 else 0 := by simp [count_succ]
lemma count_succ' (n : ℕ) : count p (n + 1) = count (λ k, p (k + 1)) n + if p 0 then 1 else 0 :=
by rw [count_add', count_one]
variables {p}
@[simp] lemma count_lt_count_succ_iff {n : ℕ} : count p n < count p (n + 1) ↔ p n :=
by by_cases h : p n; simp [count_succ, h]
lemma count_succ_eq_succ_count_iff {n : ℕ} : count p (n + 1) = count p n + 1 ↔ p n :=
by by_cases h : p n; simp [h, count_succ]
lemma count_succ_eq_count_iff {n : ℕ} : count p (n + 1) = count p n ↔ ¬p n :=
by by_cases h : p n; simp [h, count_succ]
alias count_succ_eq_succ_count_iff ↔ _ count_succ_eq_succ_count
alias count_succ_eq_count_iff ↔ _ count_succ_eq_count
lemma count_le_cardinal (n : ℕ) : (count p n : cardinal) ≤ cardinal.mk {k | p k} :=
begin
rw [count_eq_card_fintype, ← cardinal.mk_fintype],
exact cardinal.mk_subtype_mono (λ x hx, hx.2),
end
lemma lt_of_count_lt_count {a b : ℕ} (h : count p a < count p b) : a < b :=
(count_monotone p).reflect_lt h
lemma count_strict_mono {m n : ℕ} (hm : p m) (hmn : m < n) : count p m < count p n :=
(count_lt_count_succ_iff.2 hm).trans_le $ count_monotone _ (nat.succ_le_iff.2 hmn)
lemma count_injective {m n : ℕ} (hm : p m) (hn : p n) (heq : count p m = count p n) : m = n :=
begin
by_contra' h : m ≠ n,
wlog hmn : m < n,
{ exact this hn hm heq.symm h.symm (h.lt_or_lt.resolve_left hmn) },
{ simpa [heq] using count_strict_mono hm hmn }
end
lemma count_le_card (hp : (set_of p).finite) (n : ℕ) : count p n ≤ hp.to_finset.card :=
begin
rw count_eq_card_filter_range,
exact finset.card_mono (λ x hx, hp.mem_to_finset.2 (mem_filter.1 hx).2)
end
lemma count_lt_card {n : ℕ} (hp : (set_of p).finite) (hpn : p n) :
count p n < hp.to_finset.card :=
(count_lt_count_succ_iff.2 hpn).trans_le (count_le_card hp _)
variable {q : ℕ → Prop}
variable [decidable_pred q]
end count
end nat
|
/-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Scott Morrison
! This file was ported from Lean 3 source module category_theory.pi.basic
! leanprover-community/mathlib commit e97cf15cd1aec9bd5c193b2ffac5a6dc9118912b
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.CategoryTheory.NaturalIsomorphism
import Mathbin.CategoryTheory.EqToHom
import Mathbin.Data.Sum.Basic
/-!
# Categories of indexed families of objects.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the pointwise category structure on indexed families of objects in a category
(and also the dependent generalization).
-/
namespace CategoryTheory
universe w₀ w₁ w₂ v₁ v₂ u₁ u₂
variable {I : Type w₀} (C : I → Type u₁) [∀ i, Category.{v₁} (C i)]
#print CategoryTheory.pi /-
/-- `pi C` gives the cartesian product of an indexed family of categories.
-/
instance pi : Category.{max w₀ v₁} (∀ i, C i)
where
Hom X Y := ∀ i, X i ⟶ Y i
id X i := 𝟙 (X i)
comp X Y Z f g i := f i ≫ g i
#align category_theory.pi CategoryTheory.pi
-/
#print CategoryTheory.pi' /-
/-- This provides some assistance to typeclass search in a common situation,
which otherwise fails. (Without this `category_theory.pi.has_limit_of_has_limit_comp_eval` fails.)
-/
abbrev pi' {I : Type v₁} (C : I → Type u₁) [∀ i, Category.{v₁} (C i)] : Category.{v₁} (∀ i, C i) :=
CategoryTheory.pi C
#align category_theory.pi' CategoryTheory.pi'
-/
attribute [instance] pi'
namespace Pi
#print CategoryTheory.Pi.id_apply /-
@[simp]
theorem id_apply (X : ∀ i, C i) (i) : (𝟙 X : ∀ i, X i ⟶ X i) i = 𝟙 (X i) :=
rfl
#align category_theory.pi.id_apply CategoryTheory.Pi.id_apply
-/
#print CategoryTheory.Pi.comp_apply /-
@[simp]
theorem comp_apply {X Y Z : ∀ i, C i} (f : X ⟶ Y) (g : Y ⟶ Z) (i) :
(f ≫ g : ∀ i, X i ⟶ Z i) i = f i ≫ g i :=
rfl
#align category_theory.pi.comp_apply CategoryTheory.Pi.comp_apply
-/
#print CategoryTheory.Pi.eval /-
/--
The evaluation functor at `i : I`, sending an `I`-indexed family of objects to the object over `i`.
-/
@[simps]
def eval (i : I) : (∀ i, C i) ⥤ C i where
obj f := f i
map f g α := α i
#align category_theory.pi.eval CategoryTheory.Pi.eval
-/
section
variable {J : Type w₁}
#print CategoryTheory.Pi.comap /-
/-- Pull back an `I`-indexed family of objects to an `J`-indexed family, along a function `J → I`.
-/
@[simps]
def comap (h : J → I) : (∀ i, C i) ⥤ ∀ j, C (h j)
where
obj f i := f (h i)
map f g α i := α (h i)
#align category_theory.pi.comap CategoryTheory.Pi.comap
-/
variable (I)
#print CategoryTheory.Pi.comapId /-
/-- The natural isomorphism between
pulling back a grading along the identity function,
and the identity functor. -/
@[simps]
def comapId : comap C (id : I → I) ≅ 𝟭 (∀ i, C i)
where
Hom := { app := fun X => 𝟙 X }
inv := { app := fun X => 𝟙 X }
#align category_theory.pi.comap_id CategoryTheory.Pi.comapId
-/
variable {I}
variable {K : Type w₂}
#print CategoryTheory.Pi.comapComp /-
/-- The natural isomorphism comparing between
pulling back along two successive functions, and
pulling back along their composition
-/
@[simps]
def comapComp (f : K → J) (g : J → I) : comap C g ⋙ comap (C ∘ g) f ≅ comap C (g ∘ f)
where
Hom := { app := fun X b => 𝟙 (X (g (f b))) }
inv := { app := fun X b => 𝟙 (X (g (f b))) }
#align category_theory.pi.comap_comp CategoryTheory.Pi.comapComp
-/
#print CategoryTheory.Pi.comapEvalIsoEval /-
/-- The natural isomorphism between pulling back then evaluating, and just evaluating. -/
@[simps]
def comapEvalIsoEval (h : J → I) (j : J) : comap C h ⋙ eval (C ∘ h) j ≅ eval C (h j) :=
NatIso.ofComponents (fun f => Iso.refl _) (by tidy)
#align category_theory.pi.comap_eval_iso_eval CategoryTheory.Pi.comapEvalIsoEval
-/
end
section
variable {J : Type w₀} {D : J → Type u₁} [∀ j, Category.{v₁} (D j)]
/- warning: category_theory.pi.sum_elim_category -> CategoryTheory.Pi.sumElimCategoryₓ is a dubious translation:
lean 3 declaration is
forall {I : Type.{u1}} (C : I -> Type.{u3}) [_inst_1 : forall (i : I), CategoryTheory.Category.{u2, u3} (C i)] {J : Type.{u1}} {D : J -> Type.{u3}} [_inst_2 : forall (j : J), CategoryTheory.Category.{u2, u3} (D j)] (s : Sum.{u1, u1} I J), CategoryTheory.Category.{u2, u3} (Sum.elim.{u1, u1, succ (succ u3)} I J Type.{u3} C D s)
but is expected to have type
forall {I : Type.{u3}} (C : I -> Type.{u1}) [_inst_1 : forall (i : I), CategoryTheory.Category.{u2, u1} (C i)] {J : Type.{u3}} {D : J -> Type.{u1}} [_inst_2 : forall (j : J), CategoryTheory.Category.{u2, u1} (D j)] (s : Sum.{u3, u3} I J), CategoryTheory.Category.{u2, u1} (Sum.elim.{u3, u3, succ (succ u1)} I J Type.{u1} C D s)
Case conversion may be inaccurate. Consider using '#align category_theory.pi.sum_elim_category CategoryTheory.Pi.sumElimCategoryₓₓ'. -/
instance sumElimCategory : ∀ s : Sum I J, Category.{v₁} (Sum.elim C D s)
| Sum.inl i => by
dsimp
infer_instance
| Sum.inr j => by
dsimp
infer_instance
#align category_theory.pi.sum_elim_category CategoryTheory.Pi.sumElimCategoryₓ
/- warning: category_theory.pi.sum -> CategoryTheory.Pi.sum is a dubious translation:
lean 3 declaration is
forall {I : Type.{u1}} (C : I -> Type.{u3}) [_inst_1 : forall (i : I), CategoryTheory.Category.{u2, u3} (C i)] {J : Type.{u1}} {D : J -> Type.{u3}} [_inst_2 : forall (j : J), CategoryTheory.Category.{u2, u3} (D j)], CategoryTheory.Functor.{max u1 u2, max (max u1 u3) u1 u2, max u1 u3, max (max u1 u2) u1 u3} (forall (i : I), C i) (CategoryTheory.pi.{u1, u2, u3} I (fun (i : I) => C i) (fun (i : I) => _inst_1 i)) (CategoryTheory.Functor.{max u1 u2, max u1 u2, max u1 u3, max u1 u3} (forall (j : J), D j) (CategoryTheory.pi.{u1, u2, u3} J (fun (j : J) => D j) (fun (i : J) => _inst_2 i)) (forall (s : Sum.{u1, u1} I J), Sum.elim.{u1, u1, succ (succ u3)} I J Type.{u3} C D s) (CategoryTheory.pi.{u1, u2, u3} (Sum.{u1, u1} I J) (fun (s : Sum.{u1, u1} I J) => Sum.elim.{u1, u1, succ (succ u3)} I J Type.{u3} C D s) (fun (i : Sum.{u1, u1} I J) => CategoryTheory.Pi.sumElimCategoryₓ.{u1, u2, u3} I C (fun (i : I) => _inst_1 i) J D (fun (j : J) => _inst_2 j) i))) (CategoryTheory.Functor.category.{max u1 u2, max u1 u2, max u1 u3, max u1 u3} (forall (j : J), D j) (CategoryTheory.pi.{u1, u2, u3} J (fun (j : J) => D j) (fun (i : J) => _inst_2 i)) (forall (s : Sum.{u1, u1} I J), Sum.elim.{u1, u1, succ (succ u3)} I J Type.{u3} C D s) (CategoryTheory.pi.{u1, u2, u3} (Sum.{u1, u1} I J) (fun (s : Sum.{u1, u1} I J) => Sum.elim.{u1, u1, succ (succ u3)} I J Type.{u3} C D s) (fun (i : Sum.{u1, u1} I J) => CategoryTheory.Pi.sumElimCategoryₓ.{u1, u2, u3} I C (fun (i : I) => _inst_1 i) J D (fun (j : J) => _inst_2 j) i)))
but is expected to have type
forall {I : Type.{u1}} (C : I -> Type.{u3}) [_inst_1 : forall (i : I), CategoryTheory.Category.{u2, u3} (C i)] {J : Type.{u1}} {D : J -> Type.{u3}} [_inst_2 : forall (j : J), CategoryTheory.Category.{u2, u3} (D j)], CategoryTheory.Functor.{max u2 u1, max (max u3 u2) u1, max u3 u1, max (max u3 u1) u2 u1} (forall (i : I), C i) (CategoryTheory.pi.{u1, u2, u3} I (fun (i : I) => C i) (fun (i : I) => _inst_1 i)) (CategoryTheory.Functor.{max u2 u1, max u2 u1, max u3 u1, max u3 u1} (forall (j : J), D j) (CategoryTheory.pi.{u1, u2, u3} J (fun (j : J) => D j) (fun (i : J) => _inst_2 i)) (forall (s : Sum.{u1, u1} I J), Sum.elim.{u1, u1, succ (succ u3)} I J Type.{u3} C D s) (CategoryTheory.pi.{u1, u2, u3} (Sum.{u1, u1} I J) (fun (s : Sum.{u1, u1} I J) => Sum.elim.{u1, u1, succ (succ u3)} I J Type.{u3} C D s) (fun (i : Sum.{u1, u1} I J) => CategoryTheory.Pi.sumElimCategory.{u1, u2, u3} I C (fun (i : I) => (fun (i : I) => _inst_1 i) i) J D (fun (j : J) => (fun (j : J) => _inst_2 j) j) i))) (CategoryTheory.Functor.category.{max u2 u1, max u2 u1, max u3 u1, max u3 u1} (forall (j : J), D j) (CategoryTheory.pi.{u1, u2, u3} J (fun (j : J) => D j) (fun (i : J) => _inst_2 i)) (forall (s : Sum.{u1, u1} I J), Sum.elim.{u1, u1, succ (succ u3)} I J Type.{u3} C D s) (CategoryTheory.pi.{u1, u2, u3} (Sum.{u1, u1} I J) (fun (s : Sum.{u1, u1} I J) => Sum.elim.{u1, u1, succ (succ u3)} I J Type.{u3} C D s) (fun (i : Sum.{u1, u1} I J) => CategoryTheory.Pi.sumElimCategory.{u1, u2, u3} I C (fun (i : I) => (fun (i : I) => _inst_1 i) i) J D (fun (j : J) => (fun (j : J) => _inst_2 j) j) i)))
Case conversion may be inaccurate. Consider using '#align category_theory.pi.sum CategoryTheory.Pi.sumₓ'. -/
/-- The bifunctor combining an `I`-indexed family of objects with a `J`-indexed family of objects
to obtain an `I ⊕ J`-indexed family of objects.
-/
@[simps]
def sum : (∀ i, C i) ⥤ (∀ j, D j) ⥤ ∀ s : Sum I J, Sum.elim C D s
where
obj f :=
{ obj := fun g s => Sum.rec f g s
map := fun g g' α s => Sum.rec (fun i => 𝟙 (f i)) α s }
map f f' α := { app := fun g s => Sum.rec α (fun j => 𝟙 (g j)) s }
#align category_theory.pi.sum CategoryTheory.Pi.sum
end
variable {C}
#print CategoryTheory.Pi.isoApp /-
/-- An isomorphism between `I`-indexed objects gives an isomorphism between each
pair of corresponding components. -/
@[simps]
def isoApp {X Y : ∀ i, C i} (f : X ≅ Y) (i : I) : X i ≅ Y i :=
⟨f.Hom i, f.inv i, by
dsimp
rw [← comp_apply, iso.hom_inv_id, id_apply],
by
dsimp
rw [← comp_apply, iso.inv_hom_id, id_apply]⟩
#align category_theory.pi.iso_app CategoryTheory.Pi.isoApp
-/
#print CategoryTheory.Pi.isoApp_refl /-
@[simp]
theorem isoApp_refl (X : ∀ i, C i) (i : I) : isoApp (Iso.refl X) i = Iso.refl (X i) :=
rfl
#align category_theory.pi.iso_app_refl CategoryTheory.Pi.isoApp_refl
-/
#print CategoryTheory.Pi.isoApp_symm /-
@[simp]
theorem isoApp_symm {X Y : ∀ i, C i} (f : X ≅ Y) (i : I) : isoApp f.symm i = (isoApp f i).symm :=
rfl
#align category_theory.pi.iso_app_symm CategoryTheory.Pi.isoApp_symm
-/
#print CategoryTheory.Pi.isoApp_trans /-
@[simp]
theorem isoApp_trans {X Y Z : ∀ i, C i} (f : X ≅ Y) (g : Y ≅ Z) (i : I) :
isoApp (f ≪≫ g) i = isoApp f i ≪≫ isoApp g i :=
rfl
#align category_theory.pi.iso_app_trans CategoryTheory.Pi.isoApp_trans
-/
end Pi
namespace Functor
variable {C}
variable {D : I → Type u₁} [∀ i, Category.{v₁} (D i)] {A : Type u₁} [Category.{u₁} A]
#print CategoryTheory.Functor.pi /-
/-- Assemble an `I`-indexed family of functors into a functor between the pi types.
-/
@[simps]
def pi (F : ∀ i, C i ⥤ D i) : (∀ i, C i) ⥤ ∀ i, D i
where
obj f i := (F i).obj (f i)
map f g α i := (F i).map (α i)
#align category_theory.functor.pi CategoryTheory.Functor.pi
-/
#print CategoryTheory.Functor.pi' /-
/-- Similar to `pi`, but all functors come from the same category `A`
-/
@[simps]
def pi' (f : ∀ i, A ⥤ C i) : A ⥤ ∀ i, C i
where
obj a i := (f i).obj a
map a₁ a₂ h i := (f i).map h
#align category_theory.functor.pi' CategoryTheory.Functor.pi'
-/
section EqToHom
#print CategoryTheory.Functor.eqToHom_proj /-
@[simp]
theorem eqToHom_proj {x x' : ∀ i, C i} (h : x = x') (i : I) :
(eqToHom h : x ⟶ x') i = eqToHom (Function.funext_iff.mp h i) :=
by
subst h
rfl
#align category_theory.functor.eq_to_hom_proj CategoryTheory.Functor.eqToHom_proj
-/
end EqToHom
#print CategoryTheory.Functor.pi'_eval /-
-- One could add some natural isomorphisms showing
-- how `functor.pi` commutes with `pi.eval` and `pi.comap`.
@[simp]
theorem pi'_eval (f : ∀ i, A ⥤ C i) (i : I) : pi' f ⋙ Pi.eval C i = f i :=
by
apply Functor.ext <;> intros
· simp; · rfl
#align category_theory.functor.pi'_eval CategoryTheory.Functor.pi'_eval
-/
#print CategoryTheory.Functor.pi_ext /-
/-- Two functors to a product category are equal iff they agree on every coordinate. -/
theorem pi_ext (f f' : A ⥤ ∀ i, C i) (h : ∀ i, f ⋙ Pi.eval C i = f' ⋙ Pi.eval C i) : f = f' :=
by
apply Functor.ext; swap
· intro X
ext i
specialize h i
have := congr_obj h X
simpa
· intro x y p
ext i
specialize h i
have := congr_hom h p
simpa
#align category_theory.functor.pi_ext CategoryTheory.Functor.pi_ext
-/
end Functor
namespace NatTrans
variable {C}
variable {D : I → Type u₁} [∀ i, Category.{v₁} (D i)]
variable {F G : ∀ i, C i ⥤ D i}
#print CategoryTheory.NatTrans.pi /-
/-- Assemble an `I`-indexed family of natural transformations into a single natural transformation.
-/
@[simps]
def pi (α : ∀ i, F i ⟶ G i) : Functor.pi F ⟶ Functor.pi G where app f i := (α i).app (f i)
#align category_theory.nat_trans.pi CategoryTheory.NatTrans.pi
-/
end NatTrans
end CategoryTheory
|
(* Author: Tobias Nipkow, 2007 *)
theory QElin_opt
imports QElin
begin
subsubsection{*An optimization*}
text{* Atoms are simplified asap. *}
definition
"asimp a = (case a of
Less r cs \<Rightarrow> (if \<forall>c\<in> set cs. c = 0
then if r<0 then TrueF else FalseF
else Atom a) |
Eq r cs \<Rightarrow> (if \<forall>c\<in> set cs. c = 0
then if r=0 then TrueF else FalseF else Atom a))"
lemma asimp_pretty:
"asimp (Less r cs) =
(if \<forall>c\<in> set cs. c = 0
then if r<0 then TrueF else FalseF
else Atom(Less r cs))"
"asimp (Eq r cs) =
(if \<forall>c\<in> set cs. c = 0
then if r=0 then TrueF else FalseF
else Atom(Eq r cs))"
by(auto simp:asimp_def)
definition qe_FMo\<^sub>1 :: "atom list \<Rightarrow> atom fm" where
"qe_FMo\<^sub>1 as = list_conj [asimp(combine p q). p\<leftarrow>lbounds as, q\<leftarrow>ubounds as]"
lemma I_asimp: "R.I (asimp a) xs = I\<^sub>R a xs"
by(simp add:asimp_def iprod0_if_coeffs0 split:atom.split)
lemma I_qe_FMo\<^sub>1: "R.I (qe_FMo\<^sub>1 as) xs = R.I (qe_FM\<^sub>1 as) xs"
by(simp add:qe_FM\<^sub>1_def qe_FMo\<^sub>1_def I_asimp)
definition "qe_FMo = R\<^sub>e.lift_dnfeq_qe qe_FMo\<^sub>1"
lemma qfree_qe_FMo\<^sub>1: "qfree (qe_FMo\<^sub>1 as)"
by(auto simp:qe_FM\<^sub>1_def qe_FMo\<^sub>1_def asimp_def intro!:qfree_list_conj
split:atom.split)
corollary I_qe_FMo: "R.I (qe_FMo \<phi>) xs = R.I \<phi> xs"
unfolding qe_FMo_def
apply(rule R\<^sub>e.I_lift_dnfeq_qe)
apply(rule qfree_qe_FMo\<^sub>1)
apply(rule allI)
apply(subst I_qe_FMo\<^sub>1)
apply(rule I_qe_FM\<^sub>1)
prefer 2 apply blast
apply(clarify)
apply(drule_tac x=a in bspec) apply simp
apply(simp add: depends\<^sub>R_def split:atom.splits list.splits)
done
theorem qfree_qe_FMo: "qfree (qe_FMo f)"
by(simp add:qe_FMo_def R\<^sub>e.qfree_lift_dnfeq_qe qfree_qe_FMo\<^sub>1)
end
|
open import Data.Bool as Bool using (Bool; false; true; if_then_else_; not)
open import Data.String using (String)
open import Data.Nat using (ℕ; _+_; _≟_; suc; _>_; _<_; _∸_)
open import Relation.Nullary.Decidable using (⌊_⌋)
open import Data.List as l using (List; filter; map; take; foldl; length; []; _∷_)
open import Data.List.Properties
-- open import Data.List.Extrema using (max)
open import Data.Maybe using (to-witness)
open import Data.Fin using (fromℕ; _-_; zero; Fin)
open import Data.Fin.Properties using (≤-totalOrder)
open import Data.Product as Prod using (∃; ∃₂; _×_; _,_; Σ)
import Relation.Binary.PropositionalEquality as Eq
open Eq using (_≡_; refl; cong)
open Eq.≡-Reasoning
open import Level using (Level)
open import Data.Vec as v using (Vec; fromList; toList; last; length; []; _∷_; [_]; _∷ʳ_; _++_; lookup; head; initLast; filter; map)
open import Data.Vec.Bounded as vb using ([]; _∷_; fromVec; filter; Vec≤)
open import Agda.Builtin.Nat public
using () renaming (_==_ to _≡ᵇ_)
open import Relation.Binary.PropositionalEquality as P
using (_≡_; _≢_; refl; _≗_; cong₂; inspect; [_])
open import Data.Nat.Properties using (+-comm)
open import Relation.Unary using (Pred; Decidable)
open import Relation.Nullary using (does)
open import Data.Vec.Bounded.Base using (padRight; ≤-cast)
import Data.Nat.Properties as ℕₚ
open import Relation.Nullary.Decidable.Core using (dec-false)
open import Function using (_∘_)
open import Data.List.Extrema ℕₚ.≤-totalOrder
open import Data.Empty using (⊥)
-- TODO add to std-lib
open import Relation.Nullary
dec-¬ : ∀ {a} {P : Set a} → Dec P → Dec (¬ P)
dec-¬ (yes p) = no λ prf → prf p
dec-¬ (no ¬p) = yes ¬p
-- TODO switch to Vec init?
allButLast : ∀ {a} {A : Set a} → List A → List A
allButLast [] = l.[]
allButLast (_ ∷ []) = l.[]
allButLast (x ∷ x₁ ∷ l) = x l.∷ (allButLast (x₁ l.∷ l))
allButLast-∷ʳ : ∀ {a} {A : Set a} {l : List A} {x} → allButLast (l l.∷ʳ x) ≡ l
allButLast-∷ʳ {l = []} = refl
allButLast-∷ʳ {l = _ ∷ []} = refl
allButLast-∷ʳ {l = x ∷ x₁ ∷ l} = cong (x l.∷_) (allButLast-∷ʳ {l = x₁ l.∷ l})
filter' : {A : Set} → (A → Bool) → List A → List A
filter' p [] = l.[]
filter' p (x ∷ xs) with (p x)
... | true = x l.∷ filter' p xs
... | false = filter' p xs
record Todo : Set where
field
text : String
completed : Bool
id : ℕ
-- can't define this for (List any) since (last []) must be defined for each carrier type
TodoListLast : List Todo → Todo
TodoListLast [] = record {}
TodoListLast (x ∷ []) = x
TodoListLast (_ ∷ y ∷ l) = TodoListLast (y l.∷ l)
AddTodo : List Todo → String → List Todo
AddTodo todos text =
todos l.∷ʳ
record
{ id = 1
; completed = false
; text = text
}
-- AddTodo is well-defined
AddTodoAddsNewListItem :
(todos : List Todo) (text : String) →
l.length (AddTodo todos text) ≡ l.length todos + 1
AddTodoAddsNewListItem todos text = length-++ todos
AddTodoSetsNewCompletedToFalse :
(todos : List Todo) (text : String) →
Todo.completed (TodoListLast (AddTodo todos text)) ≡ false
AddTodoSetsNewCompletedToFalse [] text = refl
AddTodoSetsNewCompletedToFalse (_ ∷ []) text = refl
AddTodoSetsNewCompletedToFalse (_ ∷ _ ∷ l) text = AddTodoSetsNewCompletedToFalse (_ l.∷ l) text
-- TODO can't prove this until AddTodo definition changed
AddTodoSetsNewIdToNonExistingId :
(todos : List Todo) (text : String) →
l.length (l.filter (λ todo → dec-¬ (Todo.id todo ≟ Todo.id (TodoListLast (AddTodo todos text)))) (AddTodo todos text)) ≡ 1
AddTodoSetsNewIdToNonExistingId todos text = {! !}
AddTodoSetsNewTextToText :
(todos : List Todo) (text : String) →
Todo.text (TodoListLast (AddTodo todos text)) ≡ text
AddTodoSetsNewTextToText [] text = refl
AddTodoSetsNewTextToText (_ ∷ []) text = refl
AddTodoSetsNewTextToText (_ ∷ _ ∷ l) text = AddTodoSetsNewTextToText (_ l.∷ l) text
AddTodoDoesntChangeOtherTodos :
(todos : List Todo) (text : String) →
l.length todos > 0 →
allButLast (AddTodo todos text) ≡ todos
AddTodoDoesntChangeOtherTodos (x l.∷ xs) text _<_ = allButLast-∷ʳ
-- END AddTodo is well-defined
-- TODO text1 ≠ text2
AddTodo-not-comm :
(todos : List Todo) →
(text1 : String) →
(text2 : String) →
(AddTodo (AddTodo todos text1) text2 ≢ AddTodo (AddTodo todos text2) text1)
AddTodo-not-comm todos text1 text2 = {! !}
-- {-# COMPILE JS AddTodo =
-- function (todos) {
-- return function (text) {
-- return [
-- ...todos,
-- {
-- id: todos.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
-- completed: false,
-- text: text
-- }
-- ]
-- }
-- }
-- #-}
DeleteTodo : (List Todo) → ℕ → (List Todo)
DeleteTodo todos id = l.filter (λ todo → dec-¬ (Todo.id todo ≟ id)) todos
DeleteTodo' : (List Todo) → ℕ → (List Todo)
DeleteTodo' todos id = filter' (λ todo → not (Todo.id todo ≡ᵇ id)) todos
DeleteTodo'RemoveTodoWithId :
(todos : List Todo) (id : ℕ) →
filter' (λ todo → Todo.id todo ≡ᵇ id) (DeleteTodo' todos id) ≡ l.[]
DeleteTodo'RemoveTodoWithId [] id = refl
DeleteTodo'RemoveTodoWithId (x ∷ xs) id with (Todo.id x ≡ᵇ id) | inspect (_≡ᵇ id) (Todo.id x)
... | true | P.[ eq ] = DeleteTodo'RemoveTodoWithId xs id
... | false | P.[ eq ] rewrite eq = DeleteTodo'RemoveTodoWithId xs id
-- TODO this one needs Todo to specify that it can only have one unique id
DeleteTodo'Removes1Element :
(todos : List Todo) (id : ℕ) →
l.length (DeleteTodo' todos id) ≡ l.length todos ∸ 1
DeleteTodo'Removes1Element [] id = refl
DeleteTodo'Removes1Element (x ∷ xs) id with (Todo.id x ≡ᵇ id) | inspect (_≡ᵇ id) (Todo.id x)
... | true | P.[ eq ] rewrite eq = {! !} -- DeleteTodo'Removes1Element xs id
... | false | P.[ eq ] rewrite eq = {! !}
DeleteTodoDoesntChangeOtherTodos :
(todos : List Todo) (id : ℕ) →
DeleteTodo todos id ≡ l.filter (λ todo → dec-¬ (Todo.id todo ≟ id)) todos
DeleteTodoDoesntChangeOtherTodos todos id = refl
-- END DeleteTodo is well-defined
DeleteTodo-idem :
(todos : List Todo) (id : ℕ) →
DeleteTodo (DeleteTodo todos id) id ≡ DeleteTodo todos id
DeleteTodo-idem todos id = filter-idem (λ e → dec-¬ (Todo.id e ≟ id)) todos
-- {-# COMPILE JS DeleteTodo =
-- function (todos) {
-- return function (id) {
-- return todos.filter(function (todo) {
-- return todo.id !== id
-- });
-- }
-- }
-- #-}
-- EditTodo: can't use updateAt since id doesn't necessarily correspond to Vec index
EditTodo : (List Todo) → ℕ → String → (List Todo)
EditTodo todos id text =
l.map (λ todo →
if (⌊ Todo.id todo ≟ id ⌋)
then record todo { text = text }
else todo)
todos
EditTodo' : (List Todo) → ℕ → String → (List Todo)
EditTodo' todos id text =
l.map (λ todo →
if (Todo.id todo ≡ᵇ id)
then record todo { text = text }
else todo)
todos
-- EditTodo is well-defined
-- EditTodoChangesText :
-- (todos : List Todo) (id : ℕ) (text : String) →
-- l.map Todo.text (l.filter (λ todo → Todo.id todo ≟ id) (EditTodo todos id text)) ≡ l.[ text ]
-- EditTodoChangesText todos id text = {! !}
-- -- TODO not necessarily true
-- EditTodo'ChangesText :
-- (todos : List Todo) (id : ℕ) (text : String) →
-- l.map Todo.text (EditTodo' (filter' (λ todo → Todo.id todo ≡ᵇ id) todos) id text) ≡ l.map Todo.text (filter' (λ todo → Todo.id todo ≡ᵇ id) todos)
-- EditTodo'ChangesText [] id text = refl
-- EditTodo'ChangesText (x ∷ xs) id text with (Todo.id x ≡ᵇ id) | inspect (_≡ᵇ id) (Todo.id x)
-- ... | true | P.[ eq ] rewrite eq = {! !} -- cong (Todo.text x l.∷_) (EditTodo'ChangesText xs id text)
-- ... | false | P.[ eq ] rewrite eq = EditTodo'ChangesText xs id text
EditTodo'DoesntChangeId :
(todos : List Todo) (id : ℕ) (text : String) →
l.map Todo.id (EditTodo' todos id text) ≡ l.map Todo.id todos
EditTodo'DoesntChangeId [] id text = refl
EditTodo'DoesntChangeId (x ∷ xs) id text with (Todo.id x ≡ᵇ id)
... | true = cong ((Todo.id x) l.∷_) (EditTodo'DoesntChangeId xs id text)
... | false = cong ((Todo.id x) l.∷_) (EditTodo'DoesntChangeId xs id text)
EditTodo'DoesntChangeCompleted :
(todos : List Todo) (id : ℕ) (text : String) →
l.map Todo.completed (EditTodo' todos id text) ≡ l.map Todo.completed todos
EditTodo'DoesntChangeCompleted [] id text = refl
EditTodo'DoesntChangeCompleted (x ∷ xs) id text with (Todo.id x ≡ᵇ id)
... | true = cong ((Todo.completed x) l.∷_) (EditTodo'DoesntChangeCompleted xs id text)
... | false = cong ((Todo.completed x) l.∷_) (EditTodo'DoesntChangeCompleted xs id text)
EditTodo'DoesntChangeOtherTodos :
(todos : List Todo) (id : ℕ) (text : String) →
filter' (λ todo → not (Todo.id todo ≡ᵇ id)) (EditTodo' todos id text) ≡ filter' (λ todo → not (Todo.id todo ≡ᵇ id)) todos
EditTodo'DoesntChangeOtherTodos [] id text = refl
EditTodo'DoesntChangeOtherTodos (x ∷ xs) id text with (Todo.id x ≡ᵇ id) | inspect (_≡ᵇ id) (Todo.id x)
... | true | P.[ eq ] rewrite eq = EditTodo'DoesntChangeOtherTodos xs id text
... | false | P.[ eq ] rewrite eq = cong (x l.∷_) (EditTodo'DoesntChangeOtherTodos xs id text)
EditTodoLengthUnchanged :
(todos : List Todo) (id' : ℕ) (text : String) →
l.length (EditTodo todos id' text) ≡ l.length todos
EditTodoLengthUnchanged todos id' text = length-map (λ todo → if (⌊ Todo.id todo ≟ id' ⌋) then record todo { text = text } else todo) todos
-- END EditTodo is well-defined
EditTodo'-idem :
(todos : List Todo) (id : ℕ) (text : String) →
EditTodo' (EditTodo' todos id text) id text ≡ EditTodo' todos id text
EditTodo'-idem [] id text = refl
EditTodo'-idem (x ∷ xs) id text with (Todo.id x ≡ᵇ id) | inspect (_≡ᵇ id) (Todo.id x)
... | true | P.[ eq ] rewrite eq = cong (record x { text = text } List.∷_) (EditTodo'-idem xs id text)
... | false | P.[ eq ] rewrite eq = cong (x List.∷_) (EditTodo'-idem xs id text)
-- {-# COMPILE JS EditTodo =
-- function (todos) {
-- return function (id) {
-- return function (text) {
-- return todos.map(function (todo) {
-- if (todo.id === id) {
-- todo.text = text;
-- }
-- return todo;
-- });
-- }
-- }
-- }
-- #-}
CompleteTodo : (List Todo) → ℕ → (List Todo)
CompleteTodo todos id =
l.map (λ todo →
if (⌊ Todo.id todo ≟ id ⌋)
then record todo { completed = true }
else todo)
todos
CompleteTodo' : (List Todo) → ℕ → (List Todo)
CompleteTodo' todos id =
l.map (λ todo →
if (Todo.id todo ≡ᵇ id)
then record todo { completed = true }
else todo)
todos
-- CompleteTodo is well-defined
-- TODO don't know if there is only one instance of Todo with that id
CompleteTodo'ChangesCompleted :
(todos : List Todo) (id : ℕ) →
l.map Todo.completed (filter' (λ todo → Todo.id todo ≡ᵇ id) (CompleteTodo' todos id)) ≡ l.map (λ todo → true) (filter' (λ todo → Todo.id todo ≡ᵇ id) todos)
CompleteTodo'ChangesCompleted [] id = refl
CompleteTodo'ChangesCompleted (x ∷ xs) id with Todo.id x ≡ᵇ id | inspect (_≡ᵇ id) (Todo.id x)
... | true | P.[ eq ] rewrite eq = cong (true l.∷_) (CompleteTodo'ChangesCompleted xs id)
... | false | P.[ eq ] rewrite eq = CompleteTodo'ChangesCompleted xs id
CompleteTodoDoesntChangeIds :
(todos : List Todo) (id : ℕ) →
l.map Todo.id (CompleteTodo todos id) ≡ l.map Todo.id todos
CompleteTodoDoesntChangeIds [] id = refl
CompleteTodoDoesntChangeIds (x ∷ []) id = cong (l._∷ l.[]) (helper x id)
where
helper :
(x : Todo) (id : ℕ) →
Todo.id (if ⌊ Todo.id x ≟ id ⌋ then record { text = Todo.text x ; completed = true ; id = Todo.id x } else x) ≡ Todo.id x
helper x id with (⌊ Todo.id x ≟ id ⌋)
... | true = refl
... | false = refl
CompleteTodoDoesntChangeIds (x ∷ xs) id =
begin
l.map Todo.id (CompleteTodo (x l.∷ xs) id)
≡⟨⟩
(l.map Todo.id (CompleteTodo l.[ x ] id)) l.++ l.map Todo.id (CompleteTodo xs id)
≡⟨ cong (l._++ l.map Todo.id (CompleteTodo xs id)) (CompleteTodoDoesntChangeIds (x l.∷ l.[]) id) ⟩
l.map Todo.id (l.[ x ]) l.++ l.map Todo.id (CompleteTodo xs id)
≡⟨⟩
l.[ Todo.id x ] l.++ l.map Todo.id (CompleteTodo xs id)
≡⟨⟩
Todo.id x l.∷ l.map Todo.id (CompleteTodo xs id)
≡⟨ cong (Todo.id x l.∷_) (CompleteTodoDoesntChangeIds xs id) ⟩
Todo.id x l.∷ l.map Todo.id xs
≡⟨⟩
l.map Todo.id (x l.∷ xs)
∎
CompleteTodoDoesntChangeText :
(todos : List Todo) (id : ℕ) →
l.map Todo.text (CompleteTodo todos id) ≡ l.map Todo.text todos
CompleteTodoDoesntChangeText [] id = refl
CompleteTodoDoesntChangeText (x ∷ []) id = cong (l._∷ l.[]) (helper x id)
where
helper :
(x : Todo) (id : ℕ) →
Todo.text (if ⌊ Todo.id x ≟ id ⌋ then record { text = Todo.text x ; completed = true ; id = Todo.id x } else x) ≡ Todo.text x
helper x id with (⌊ Todo.id x ≟ id ⌋)
... | true = refl
... | false = refl
CompleteTodoDoesntChangeText (x ∷ xs) id =
begin
l.map Todo.text (CompleteTodo (x l.∷ xs) id)
≡⟨⟩
(l.map Todo.text (CompleteTodo l.[ x ] id)) l.++ l.map Todo.text (CompleteTodo xs id)
≡⟨ cong (l._++ l.map Todo.text (CompleteTodo xs id)) (CompleteTodoDoesntChangeText (x l.∷ l.[]) id) ⟩
l.map Todo.text (l.[ x ]) l.++ l.map Todo.text (CompleteTodo xs id)
≡⟨⟩
l.[ Todo.text x ] l.++ l.map Todo.text (CompleteTodo xs id)
≡⟨⟩
Todo.text x l.∷ l.map Todo.text (CompleteTodo xs id)
≡⟨ cong (Todo.text x l.∷_) (CompleteTodoDoesntChangeText xs id) ⟩
Todo.text x l.∷ l.map Todo.text xs
≡⟨⟩
l.map Todo.text (x l.∷ xs)
∎
CompleteTodo'DoesntChangeOthersCompleted :
(todos : List Todo) (id : ℕ) →
l.map Todo.completed (CompleteTodo' (filter' (λ todo → not (Todo.id todo ≡ᵇ id)) todos) id) ≡ l.map Todo.completed (filter' (λ todo → not (Todo.id todo ≡ᵇ id)) todos)
CompleteTodo'DoesntChangeOthersCompleted [] id = refl
CompleteTodo'DoesntChangeOthersCompleted (x ∷ xs) id with Todo.id x ≡ᵇ id | inspect (_≡ᵇ id) (Todo.id x)
... | true | P.[ eq ] rewrite eq = CompleteTodo'DoesntChangeOthersCompleted xs id --
... | false | P.[ eq ] rewrite eq = cong (Todo.completed x l.∷_) (CompleteTodo'DoesntChangeOthersCompleted xs id)
CompleteTodoLengthUnchanged :
(todos : List Todo) (id : ℕ) →
l.length (CompleteTodo todos id) ≡ l.length todos
CompleteTodoLengthUnchanged todos id = length-map (λ todo → if (⌊ Todo.id todo ≟ id ⌋) then record todo { completed = true } else todo) todos
-- END CompleteTodo is well-defined
CompleteTodo'-idem :
(todos : List Todo) (id : ℕ) →
CompleteTodo' (CompleteTodo' todos id) id ≡ CompleteTodo' todos id
CompleteTodo'-idem [] id = refl
CompleteTodo'-idem (x ∷ xs) id with Todo.id x ≡ᵇ id | inspect (_≡ᵇ id) (Todo.id x)
... | true | P.[ eq ] rewrite eq = cong (record x { completed = true } l.∷_) (CompleteTodo'-idem xs id)
... | false | P.[ eq ] rewrite eq = cong (x l.∷_) (CompleteTodo'-idem xs id)
-- {-# COMPILE JS CompleteTodo =
-- function (todos) {
-- return function (id) {
-- return todos.map(function (todo) {
-- if (todo.id === id) {
-- todo.completed = true;
-- }
-- return todo;
-- });
-- }
-- }
-- #-}
CompleteAllTodos : List Todo → List Todo
CompleteAllTodos todos =
l.map (λ todo →
record todo { completed = true })
todos
-- CompleteAllTodos is well-defined
CompleteAllTodosAllCompleted :
(todos : List Todo) →
l.filter (λ todo → (Todo.completed todo) Bool.≟ false) (CompleteAllTodos todos) ≡ l.[]
CompleteAllTodosAllCompleted [] = refl
CompleteAllTodosAllCompleted (x ∷ xs) = CompleteAllTodosAllCompleted xs
CompleteAllTodosDoesntChangeIds :
(todos : List Todo) →
l.map Todo.id (CompleteAllTodos todos) ≡ l.map Todo.id todos
CompleteAllTodosDoesntChangeIds [] = refl
CompleteAllTodosDoesntChangeIds (x ∷ []) = cong (l._∷ l.[]) (helper x)
where
helper :
(x : Todo) →
Todo.id (record x { completed = true }) ≡ Todo.id x
helper x = refl
CompleteAllTodosDoesntChangeIds (x ∷ xs) =
begin
l.map Todo.id (CompleteAllTodos (x l.∷ xs))
≡⟨⟩
(l.map Todo.id (CompleteAllTodos l.[ x ])) l.++ l.map Todo.id (CompleteAllTodos xs)
≡⟨ cong (l._++ l.map Todo.id (CompleteAllTodos xs)) (CompleteAllTodosDoesntChangeIds (x l.∷ l.[])) ⟩
l.map Todo.id (l.[ x ]) l.++ l.map Todo.id (CompleteAllTodos xs)
≡⟨⟩
l.[ Todo.id x ] l.++ l.map Todo.id (CompleteAllTodos xs)
≡⟨⟩
Todo.id x l.∷ l.map Todo.id (CompleteAllTodos xs)
≡⟨ cong (Todo.id x l.∷_) (CompleteAllTodosDoesntChangeIds xs) ⟩
Todo.id x l.∷ l.map Todo.id xs
≡⟨⟩
l.map Todo.id (x l.∷ xs)
∎
CompleteAllTodosDoesntChangeText :
(todos : List Todo) →
l.map Todo.text (CompleteAllTodos todos) ≡ l.map Todo.text todos
CompleteAllTodosDoesntChangeText [] = refl
CompleteAllTodosDoesntChangeText (x ∷ []) = cong (l._∷ l.[]) (helper x)
where
helper :
(x : Todo) →
Todo.text (record x { completed = true }) ≡ Todo.text x
helper x = refl
CompleteAllTodosDoesntChangeText (x ∷ xs) =
begin
l.map Todo.text (CompleteAllTodos (x l.∷ xs))
≡⟨⟩
(l.map Todo.text (CompleteAllTodos l.[ x ])) l.++ l.map Todo.text (CompleteAllTodos xs)
≡⟨ cong (l._++ l.map Todo.text (CompleteAllTodos xs)) (CompleteAllTodosDoesntChangeText (x l.∷ l.[])) ⟩
l.map Todo.text (l.[ x ]) l.++ l.map Todo.text (CompleteAllTodos xs)
≡⟨⟩
l.[ Todo.text x ] l.++ l.map Todo.text (CompleteAllTodos xs)
≡⟨⟩
Todo.text x l.∷ l.map Todo.text (CompleteAllTodos xs)
≡⟨ cong (Todo.text x l.∷_) (CompleteAllTodosDoesntChangeText xs) ⟩
Todo.text x l.∷ l.map Todo.text xs
≡⟨⟩
l.map Todo.text (x l.∷ xs)
∎
CompleteAllTodosLengthUnchanged :
(todos : List Todo) →
l.length (CompleteAllTodos todos) ≡ l.length todos
CompleteAllTodosLengthUnchanged todos = length-map (λ todo → record todo { completed = true }) todos
-- END CompleteAllTodos is well-defined
-- CompleteAllTodos-idem
-- {-# COMPILE JS CompleteAllTodos =
-- function (todos) {
-- return todos.map(function(todo) {
-- todo.completed = true;
-- return todo;
-- });
-- }
-- #-}
ClearCompleted : (List Todo) → (List Todo)
ClearCompleted todos =
(l.filter (λ todo → dec-¬ ((Todo.completed todo) Bool.≟ true)) todos)
-- ClearCompleted is well-defined
ClearCompletedRemovesOnlyCompleted :
(todos : List Todo) →
l.map Todo.completed (ClearCompleted todos) ≡ l.map Todo.completed (l.filter (λ todo → dec-¬ ((Todo.completed todo) Bool.≟ true)) todos)
ClearCompletedRemovesOnlyCompleted todos = refl
ClearCompletedDoesntChangeCompleted :
(todos : List Todo) →
l.map Todo.completed (ClearCompleted todos) ≡ l.map Todo.completed (l.filter (λ todo → dec-¬ ((Todo.completed todo) Bool.≟ true)) todos)
ClearCompletedDoesntChangeCompleted todos = refl
ClearCompletedDoesntChangeIds :
(todos : List Todo) →
l.map Todo.id (ClearCompleted todos) ≡ l.map Todo.id (l.filter (λ todo → dec-¬ ((Todo.completed todo) Bool.≟ true)) todos)
ClearCompletedDoesntChangeIds todos = refl
ClearCompletedDoesntChangeText :
(todos : List Todo) →
l.map Todo.text (ClearCompleted todos) ≡ l.map Todo.text (l.filter (λ todo → dec-¬ ((Todo.completed todo) Bool.≟ true)) todos)
ClearCompletedDoesntChangeText todos = refl
-- END ClearCompleted is well-defined
ClearCompleted-idem :
(todos : List Todo) →
ClearCompleted (ClearCompleted todos) ≡ ClearCompleted todos
ClearCompleted-idem todos = filter-idem (λ e → dec-¬ (Todo.completed e Bool.≟ true)) todos
-- {-# COMPILE JS ClearCompleted =
-- function (todos) {
-- return todos.filter(function(todo) {
-- return !todo.completed;
-- });
-- }
-- #-}
-- interactions
-- AddTodo-AddTodo
-- DeleteTodo-DeleteTodo
-- AddTodo-DeleteTodo
-- DeleteTodo-AddTodo
-- EditTodo-EditTodo
-- AddTodo-EditTodo
-- EditTodo-AddTodo
-- ...
|
Formal statement is: lemma fixes f g :: "complex fps" and r :: ereal defines "R \<equiv> Min {r, fps_conv_radius f, fps_conv_radius g}" assumes "subdegree g \<le> subdegree f" assumes "fps_conv_radius f > 0" "fps_conv_radius g > 0" "r > 0" assumes "\<And>z. z \<in> eball 0 r \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> eval_fps g z \<noteq> 0" shows fps_conv_radius_divide: "fps_conv_radius (f / g) \<ge> R" and eval_fps_divide: "ereal (norm z) < R \<Longrightarrow> c = fps_nth f (subdegree g) / fps_nth g (subdegree g) \<Longrightarrow> eval_fps (f / g) z = (if z = 0 then c else eval_fps f z / eval_fps g z)" Informal statement is: If $f$ and $g$ are power series with $g$ having a lower degree than $f$, and $g$ has a nonzero constant term, then the power series $f/g$ has a radius of convergence at least as large as the minimum of the radii of convergence of $f$ and $g$. |
dataFile <- read.csv('/Users/saugat/Downloads/2008.csv')
head(dataFile)
head(dataFile$Origin)
sum(dataFile$Origin == 'ORD')
sum(dataFile$Dest == 'ORD')
sum(dataFile$Origin == 'IND' & dataFile$Dest == 'ORD')
sum(dataFile$Origin == 'TUP' & dataFile$Year == 2008)
head(dataFile$Origin == 'TUP')
tup2008 <- subset(dataFile, dataFile$Origin == 'TUP' & dataFile$Year == 2008)
sum(tup2008$DepDelay)
sum(dataFile$Dest == 'LAX' & dataFile$Year == 2008)
atlToLax <- subset(dataFile, dataFile$Origin == 'ATL' & dataFile$Dest == 'LAX')
sum(atlToLax$DepTime < 1200, na.rm = TRUE)
brk = seq(0,2400,by=100)
hist(atlToLax$DepTime, brk, plot=TRUE)
|
Formal statement is: lemma components_eq_sing_iff: "components s = {s} \<longleftrightarrow> connected s \<and> s \<noteq> {}" Informal statement is: A set $s$ is connected if and only if the set of components of $s$ is equal to $\{s\}$. |
(* Property from Case-Analysis for Rippling and Inductive Proof,
Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010.
This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.
Some proofs were added by Yutaka Nagashima.*)
theory TIP_prop_70
imports "../../Test_Base"
begin
datatype Nat = Z | S "Nat"
fun t2 :: "Nat => Nat => bool" where
"t2 (Z) y = True"
| "t2 (S z) (Z) = False"
| "t2 (S z) (S x2) = t2 z x2"
theorem property0 :
"((t2 m n) ==> (t2 m (S n)))"
oops
end
|
context("lambda")
test_that("simple mult", {
fx = function(x) x*2
x = array(1:10)
re = lambda(~ fx(x), along=c(x=1))
expect_equal(re, c(x*2))
})
test_that("matrix mult", {
dot = function(x, y) sum(x * y)
a = matrix(1:6, ncol=2)
b = t(a)
re = lambda(~ dot(a, b), along=c(a=1, b=2))
dimnames(re) = NULL #FIXME:
expect_equal(re, a %*% b)
})
|
/- Eulerian circuits -/
/-
We provide you with a formalization of some facts about lists being equal up to permutation and
lists being sublists of their permutation
-/
import TBA.Eulerian.List
open List
namespace Eulerian
-- We model graphs as lists of pairs on a type with decidable equality.
variable {α : Type} (E : List (α × α)) [DecidableEq α]
def isNonEmpty : Prop := E.length > 0
-- Now it's your turn to fill out the following definitions and prove the characterization!
def isStronglyConnected (E : List (α × α)) : Prop := _
def hasEqualInOutDegrees (E : List (α × α)) : Prop := _
def isEulerian (E : List (α × α)) : Prop := _
theorem eulerian_degrees
(hne : isNonEmpty E)
(sc : isStronglyConnected E)
(ed : hasEqualInOutDegrees E)
: isEulerian E := _
end Eulerian |
Jay Chapman, a native of Birmingham, Ala., joined Georgia’s football operations staff in January, 2016.
Chapman spent the previous five seasons at Samford University where he served as the director of football operations. In that role, Chapman was responsible for day-to-day operations of the program and oversaw and coordinated all aspects of team travel.
Before joining the staff at Samford, Chapman worked as the director of player development at UAB from 2008 to 2010. He also served as the Blazers’ associate director of recruiting for his last two years in Birmingham.
In 2007, Chapman was a coordinator for Team Alabama in the All-American Football League.
A graduate of Samford, Chapman earned his bachelor’s degree in general studies. In addition, he received a bachelor’s degree in animal and dairy science from Auburn, as well as a master’s in public and private management from Birmingham-Southern. |
[STATEMENT]
lemma NSDERIV_inverse_fun:
"NSDERIV f x :> d \<Longrightarrow> f x \<noteq> 0 \<Longrightarrow>
NSDERIV (\<lambda>x. inverse (f x)) x :> (- (d * inverse (f x ^ Suc (Suc 0))))"
for x :: "'a::{real_normed_field}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>NSDERIV f x :> d; f x \<noteq> (0::'a)\<rbrakk> \<Longrightarrow> NSDERIV (\<lambda>x. inverse (f x)) x :> - (d * inverse (f x ^ Suc (Suc 0)))
[PROOF STEP]
by (simp add: NSDERIV_DERIV_iff DERIV_inverse_fun del: power_Suc) |
[GOAL]
α : Type u_1
inst✝ : DivisionRing α
src✝² : DivisionSemiring αᵐᵒᵖ := divisionSemiring α
src✝¹ : Ring αᵐᵒᵖ := ring α
src✝ : RatCast αᵐᵒᵖ := ratCast α
a : ℤ
b : ℕ
hb : b ≠ 0
h : Nat.coprime (Int.natAbs a) b
⊢ unop ↑(Rat.mk' a b) = unop (↑a * (↑b)⁻¹)
[PROOFSTEP]
rw [unop_ratCast, Rat.cast_def, unop_mul, unop_inv, unop_natCast, unop_intCast, Int.commute_cast, div_eq_mul_inv]
[GOAL]
α : Type ?u.3697
inst✝ : DivisionRing α
src✝² : Ring αᵃᵒᵖ := ring α
src✝¹ : GroupWithZero αᵃᵒᵖ := groupWithZero α
src✝ : RatCast αᵃᵒᵖ := ratCast α
a : ℤ
b : ℕ
hb : b ≠ 0
h : Nat.coprime (Int.natAbs a) b
⊢ unop ↑(Rat.mk' a b) = unop (↑a * (↑b)⁻¹)
[PROOFSTEP]
rw [unop_ratCast, Rat.cast_def, unop_mul, unop_inv, unop_natCast, unop_intCast, div_eq_mul_inv]
|
(* Title: HOL/Auth/n_germanSymIndex_lemma_inv__43_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_germanSymIndex Protocol Case Study*}
theory n_germanSymIndex_lemma_inv__43_on_rules imports n_germanSymIndex_lemma_on_inv__43
begin
section{*All lemmas on causal relation between inv__43*}
lemma lemma_inv__43_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__43 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqSVsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqEVsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__43) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__43) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
{-# OPTIONS --without-K --safe #-}
open import Categories.Category using (Category; module Definitions)
-- Definition of the "Twisted Arrow" Category of a Category 𝒞
module Categories.Category.Construction.TwistedArrow {o ℓ e} (𝒞 : Category o ℓ e) where
open import Level
open import Data.Product using (_,_; _×_; map; zip)
open import Function.Base using (_$_; flip)
open import Relation.Binary.Core using (Rel)
import Categories.Morphism as M
open M 𝒞
open import Categories.Morphism.Reasoning 𝒞
open Category 𝒞
open Definitions 𝒞
open HomReasoning
private
variable
A B C : Obj
record Morphism : Set (o ⊔ ℓ) where
field
{dom} : Obj
{cod} : Obj
arr : dom ⇒ cod
record Morphism⇒ (f g : Morphism) : Set (ℓ ⊔ e) where
constructor mor⇒
private
module f = Morphism f
module g = Morphism g
field
{dom⇐} : g.dom ⇒ f.dom
{cod⇒} : f.cod ⇒ g.cod
square : cod⇒ ∘ f.arr ∘ dom⇐ ≈ g.arr
TwistedArrow : Category (o ⊔ ℓ) (ℓ ⊔ e) e
TwistedArrow = record
{ Obj = Morphism
; _⇒_ = Morphism⇒
; _≈_ = λ f g → dom⇐ f ≈ dom⇐ g × cod⇒ f ≈ cod⇒ g
; id = mor⇒ (identityˡ ○ identityʳ)
; _∘_ = λ {A} {B} {C} m₁ m₂ → mor⇒ {A} {C} (∘′ m₁ m₂ ○ square m₁)
; assoc = sym-assoc , assoc
; sym-assoc = assoc , sym-assoc
; identityˡ = identityʳ , identityˡ
; identityʳ = identityˡ , identityʳ
; identity² = identity² , identity²
; equiv = record
{ refl = refl , refl
; sym = map sym sym
; trans = zip trans trans
}
; ∘-resp-≈ = zip (flip ∘-resp-≈) ∘-resp-≈
}
where
open Morphism⇒
open Equiv
open HomReasoning
∘′ : ∀ {A B C} (m₁ : Morphism⇒ B C) (m₂ : Morphism⇒ A B) →
(cod⇒ m₁ ∘ cod⇒ m₂) ∘ Morphism.arr A ∘ (dom⇐ m₂ ∘ dom⇐ m₁) ≈ cod⇒ m₁ ∘ Morphism.arr B ∘ dom⇐ m₁
∘′ {A} {B} {C} m₁ m₂ = begin
(cod⇒ m₁ ∘ cod⇒ m₂) ∘ Morphism.arr A ∘ (dom⇐ m₂ ∘ dom⇐ m₁) ≈⟨ pullʳ sym-assoc ⟩
cod⇒ m₁ ∘ (cod⇒ m₂ ∘ Morphism.arr A) ∘ (dom⇐ m₂ ∘ dom⇐ m₁) ≈⟨ refl⟩∘⟨ (pullˡ assoc) ⟩
cod⇒ m₁ ∘ (cod⇒ m₂ ∘ Morphism.arr A ∘ dom⇐ m₂) ∘ dom⇐ m₁ ≈⟨ (refl⟩∘⟨ square m₂ ⟩∘⟨refl) ⟩
cod⇒ m₁ ∘ Morphism.arr B ∘ dom⇐ m₁ ∎
|
theory PrimeRec
imports Main
begin
datatype nati = Zero | Suc nati
primrec add :: "nati \<Rightarrow> nati \<Rightarrow> nati" where
"add Zero n = n" |
"add (Suc m) n = Suc(add m n)"
primrec mult :: "nati \<Rightarrow> nati \<Rightarrow> nati" where
"mult Zero n = Zero" |
"mult (Suc m) n = add (mult m n) m"
primrec pow :: "nati => nati => nati" where
"pow Zero x = Suc Zero" |
"pow (Suc n) x = mult x (pow n x)"
primrec pow :: "nat => nat => nat" where
"pow x 0 = Suc 0"
| "pow x (Suc n) = x * pow x n"
lemma add_02[simp]: "add a Zero = a"
apply(induction a)
apply(auto)
done
lemma add_Associativ[simp]: "add(add a b) c = add a (add b c)"
apply(induction a)
apply(auto)
done
lemma add_suc[simp]: "add a (Suc b) = Suc( add a b)"
apply(induction a)
apply(simp)
apply(simp)
done
lemma add_com[simp]: "add a b= add b a"
apply(induction a)
apply(simp)
apply(simp)
done
lemma a1: "(a + a) = 2*a"
apply(arith)
done
lemma mult_a0: "add a a = mult(a Suc(Suc(Zero)))"
done
end |
module CoinToss
import Data.Vect
import QStateT
import QuantumOp
import LinearTypes
||| A fair coin toss (as an IO effect) via quantum resources.
|||
||| first create a new qubit in state |0>
||| then apply a hadamard gate to it, thereby preparing state |+>
||| and finally measure the qubit and return this as the result
export
coin : QuantumOp t => IO Bool
coin = do
[b] <- run (do
q <- newQubit {t = t}
q <- applyH q
r <- measure [q]
pure r
)
pure b
testCoin : IO Bool
testCoin = coin {t = SimulatedOp}
|
open import Agda.Primitive using (lzero; lsuc; _⊔_)
import SecondOrder.Arity
import SecondOrder.VContext
module SecondOrder.Signature
ℓ
(𝔸 : SecondOrder.Arity.Arity)
where
open SecondOrder.Arity.Arity 𝔸
-- a second-order algebraic signature
record Signature : Set (lsuc ℓ) where
-- a signature consists of a set of sorts and a set of operations
-- e.g. sorts A, B, C, ... and operations f, g, h
field
sort : Set ℓ -- sorts
oper : Set ℓ -- operations
open SecondOrder.VContext sort public
-- each operation has arity and a sort (the sort of its codomain)
field
oper-arity : oper → arity -- the arity of an operation
oper-sort : oper → sort -- the operation sort
arg-sort : ∀ (f : oper) → arg (oper-arity f) → sort -- the sorts of arguments
-- a second order operation can bind some free variables that occur as its arguments
-- e.g. the lambda operation binds one type and one term
arg-bind : ∀ (f : oper) → arg (oper-arity f) → VContext -- the argument bindings
-- the arguments of an operation
oper-arg : oper → Set
oper-arg f = arg (oper-arity f)
|
If $f$ is uniformly continuous on $S$, then for every $\epsilon > 0$, there exists a $\delta > 0$ such that for all $x, x' \in S$, if $|x - x'| < \delta$, then $|f(x) - f(x')| < \epsilon$. |
Formal statement is: lemma has_contour_integral_lmul: "(f has_contour_integral i) g \<Longrightarrow> ((\<lambda>x. c * (f x)) has_contour_integral (c*i)) g" Informal statement is: If $f$ has a contour integral $i$ along $g$, then $cf$ has a contour integral $ci$ along $g$. |
(* generated by Ott 0.28, locally-nameless from: ett.ott *)
Require Import Metatheory.
(** syntax *)
Definition tmvar := var. (*r variables *)
Definition covar := var. (*r coercion variables *)
Definition datacon := atom.
Definition const := atom.
Definition index := nat. (*r indices *)
Inductive relflag : Set := (*r relevance flag *)
| Rel : relflag
| Irrel : relflag.
Inductive role : Set := (*r Role *)
| Nom : role
| Rep : role.
Inductive appflag : Set := (*r applicative flag *)
| Role (R:role)
| Rho (rho:relflag).
Inductive App : Set :=
| A_Tm (nu:appflag)
| A_Co : App.
Inductive Apps : Set :=
| A_nil : Apps
| A_cons (App5:App) (Apps5:Apps).
Inductive constraint : Set := (*r props *)
| Eq (a:tm) (b:tm) (A:tm) (R:role)
with tm : Set := (*r types and kinds *)
| a_Star : tm
| a_Var_b (_:nat)
| a_Var_f (x:tmvar)
| a_Abs (rho:relflag) (A:tm) (b:tm)
| a_UAbs (rho:relflag) (b:tm)
| a_App (a:tm) (nu:appflag) (b:tm)
| a_Pi (rho:relflag) (A:tm) (B:tm)
| a_CAbs (phi:constraint) (b:tm)
| a_UCAbs (b:tm)
| a_CApp (a:tm) (g:co)
| a_CPi (phi:constraint) (B:tm)
| a_Conv (a:tm) (R:role) (g:co)
| a_Fam (F:const)
| a_Bullet : tm
| a_Pattern (R:role) (a:tm) (F:const) (Apps5:Apps) (b1:tm) (b2:tm)
| a_DataCon (K:datacon)
| a_Case (a:tm) (brs5:brs)
| a_Sub (R:role) (a:tm)
| a_Coerce : tm
| a_SrcApp (a:tm) (b:tm)
with brs : Set := (*r case branches *)
| br_None : brs
| br_One (K:datacon) (a:tm) (brs5:brs)
with co : Set := (*r explicit coercions *)
| g_Triv : co
| g_Var_b (_:nat)
| g_Var_f (c:covar)
| g_Beta (a:tm) (b:tm)
| g_Refl (a:tm)
| g_Refl2 (a:tm) (b:tm) (g:co)
| g_Sym (g:co)
| g_Trans (g1:co) (g2:co)
| g_Sub (g:co)
| g_PiCong (rho:relflag) (R:role) (g1:co) (g2:co)
| g_AbsCong (rho:relflag) (R:role) (g1:co) (g2:co)
| g_AppCong (g1:co) (rho:relflag) (R:role) (g2:co)
| g_PiFst (g:co)
| g_CPiFst (g:co)
| g_IsoSnd (g:co)
| g_PiSnd (g1:co) (g2:co)
| g_CPiCong (g1:co) (g3:co)
| g_CAbsCong (g1:co) (g3:co) (g4:co)
| g_CAppCong (g:co) (g1:co) (g2:co)
| g_CPiSnd (g:co) (g1:co) (g2:co)
| g_Cast (g1:co) (R:role) (g2:co)
| g_EqCong (g1:co) (A:tm) (g2:co)
| g_IsoConv (phi1:constraint) (phi2:constraint) (g:co)
| g_Eta (a:tm)
| g_Left (g:co) (g':co)
| g_Right (g:co) (g':co).
Definition roles : Set := list role.
Inductive sort : Set := (*r binding classifier *)
| Tm (A:tm)
| Co (phi:constraint).
Inductive sig_sort : Set := (*r signature classifier *)
| Cs (A:tm) (Rs:roles)
| Ax (p:tm) (a:tm) (A:tm) (R:role) (Rs:roles).
Inductive pattern_arg : Set := (*r Pattern arguments *)
| p_Tm (nu:appflag) (a:tm)
| p_Co (g:co).
Definition role_context : Set := list ( atom * role ).
Definition context : Set := list ( atom * sort ).
Definition available_props : Type := atoms.
Definition sig : Set := list (atom * sig_sort).
Definition atom_list : Set := list atom.
Definition pattern_args : Set := list pattern_arg.
Definition Nat : Set := nat.
Definition theta : Set := list ( atom * pattern_arg ).
(* EXPERIMENTAL *)
(** auxiliary functions on the new list types *)
(** library functions *)
(** subrules *)
(** arities *)
(** opening up abstractions *)
Fixpoint open_co_wrt_co_rec (k:nat) (g_5:co) (g__6:co) {struct g__6}: co :=
match g__6 with
| g_Triv => g_Triv
| (g_Var_b nat) => if (k === nat) then g_5 else (g_Var_b nat)
| (g_Var_f c) => g_Var_f c
| (g_Beta a b) => g_Beta (open_tm_wrt_co_rec k g_5 a) (open_tm_wrt_co_rec k g_5 b)
| (g_Refl a) => g_Refl (open_tm_wrt_co_rec k g_5 a)
| (g_Refl2 a b g) => g_Refl2 (open_tm_wrt_co_rec k g_5 a) (open_tm_wrt_co_rec k g_5 b) (open_co_wrt_co_rec k g_5 g)
| (g_Sym g) => g_Sym (open_co_wrt_co_rec k g_5 g)
| (g_Trans g1 g2) => g_Trans (open_co_wrt_co_rec k g_5 g1) (open_co_wrt_co_rec k g_5 g2)
| (g_Sub g) => g_Sub (open_co_wrt_co_rec k g_5 g)
| (g_PiCong rho R g1 g2) => g_PiCong rho R (open_co_wrt_co_rec k g_5 g1) (open_co_wrt_co_rec k g_5 g2)
| (g_AbsCong rho R g1 g2) => g_AbsCong rho R (open_co_wrt_co_rec k g_5 g1) (open_co_wrt_co_rec k g_5 g2)
| (g_AppCong g1 rho R g2) => g_AppCong (open_co_wrt_co_rec k g_5 g1) rho R (open_co_wrt_co_rec k g_5 g2)
| (g_PiFst g) => g_PiFst (open_co_wrt_co_rec k g_5 g)
| (g_CPiFst g) => g_CPiFst (open_co_wrt_co_rec k g_5 g)
| (g_IsoSnd g) => g_IsoSnd (open_co_wrt_co_rec k g_5 g)
| (g_PiSnd g1 g2) => g_PiSnd (open_co_wrt_co_rec k g_5 g1) (open_co_wrt_co_rec k g_5 g2)
| (g_CPiCong g1 g3) => g_CPiCong (open_co_wrt_co_rec k g_5 g1) (open_co_wrt_co_rec (S k) g_5 g3)
| (g_CAbsCong g1 g3 g4) => g_CAbsCong (open_co_wrt_co_rec k g_5 g1) (open_co_wrt_co_rec (S k) g_5 g3) (open_co_wrt_co_rec k g_5 g4)
| (g_CAppCong g g1 g2) => g_CAppCong (open_co_wrt_co_rec k g_5 g) (open_co_wrt_co_rec k g_5 g1) (open_co_wrt_co_rec k g_5 g2)
| (g_CPiSnd g g1 g2) => g_CPiSnd (open_co_wrt_co_rec k g_5 g) (open_co_wrt_co_rec k g_5 g1) (open_co_wrt_co_rec k g_5 g2)
| (g_Cast g1 R g2) => g_Cast (open_co_wrt_co_rec k g_5 g1) R (open_co_wrt_co_rec k g_5 g2)
| (g_EqCong g1 A g2) => g_EqCong (open_co_wrt_co_rec k g_5 g1) (open_tm_wrt_co_rec k g_5 A) (open_co_wrt_co_rec k g_5 g2)
| (g_IsoConv phi1 phi2 g) => g_IsoConv (open_constraint_wrt_co_rec k g_5 phi1) (open_constraint_wrt_co_rec k g_5 phi2) (open_co_wrt_co_rec k g_5 g)
| (g_Eta a) => g_Eta (open_tm_wrt_co_rec k g_5 a)
| (g_Left g g') => g_Left (open_co_wrt_co_rec k g_5 g) (open_co_wrt_co_rec k g_5 g')
| (g_Right g g') => g_Right (open_co_wrt_co_rec k g_5 g) (open_co_wrt_co_rec k g_5 g')
end
with open_brs_wrt_co_rec (k:nat) (g5:co) (brs_6:brs) {struct brs_6}: brs :=
match brs_6 with
| br_None => br_None
| (br_One K a brs5) => br_One K (open_tm_wrt_co_rec k g5 a) (open_brs_wrt_co_rec k g5 brs5)
end
with open_tm_wrt_co_rec (k:nat) (g5:co) (a5:tm) {struct a5}: tm :=
match a5 with
| a_Star => a_Star
| (a_Var_b nat) => a_Var_b nat
| (a_Var_f x) => a_Var_f x
| (a_Abs rho A b) => a_Abs rho (open_tm_wrt_co_rec k g5 A) (open_tm_wrt_co_rec k g5 b)
| (a_UAbs rho b) => a_UAbs rho (open_tm_wrt_co_rec k g5 b)
| (a_App a nu b) => a_App (open_tm_wrt_co_rec k g5 a) nu (open_tm_wrt_co_rec k g5 b)
| (a_Pi rho A B) => a_Pi rho (open_tm_wrt_co_rec k g5 A) (open_tm_wrt_co_rec k g5 B)
| (a_CAbs phi b) => a_CAbs (open_constraint_wrt_co_rec k g5 phi) (open_tm_wrt_co_rec (S k) g5 b)
| (a_UCAbs b) => a_UCAbs (open_tm_wrt_co_rec (S k) g5 b)
| (a_CApp a g) => a_CApp (open_tm_wrt_co_rec k g5 a) (open_co_wrt_co_rec k g5 g)
| (a_CPi phi B) => a_CPi (open_constraint_wrt_co_rec k g5 phi) (open_tm_wrt_co_rec (S k) g5 B)
| (a_Conv a R g) => a_Conv (open_tm_wrt_co_rec k g5 a) R (open_co_wrt_co_rec k g5 g)
| (a_Fam F) => a_Fam F
| a_Bullet => a_Bullet
| (a_Pattern R a F Apps5 b1 b2) => a_Pattern R (open_tm_wrt_co_rec k g5 a) F Apps5 (open_tm_wrt_co_rec k g5 b1) (open_tm_wrt_co_rec k g5 b2)
| (a_DataCon K) => a_DataCon K
| (a_Case a brs5) => a_Case (open_tm_wrt_co_rec k g5 a) (open_brs_wrt_co_rec k g5 brs5)
| (a_Sub R a) => a_Sub R (open_tm_wrt_co_rec k g5 a)
| a_Coerce => a_Coerce
| (a_SrcApp a b) => a_SrcApp (open_tm_wrt_co_rec k g5 a) (open_tm_wrt_co_rec k g5 b)
end
with open_constraint_wrt_co_rec (k:nat) (g5:co) (phi5:constraint) : constraint :=
match phi5 with
| (Eq a b A R) => Eq (open_tm_wrt_co_rec k g5 a) (open_tm_wrt_co_rec k g5 b) (open_tm_wrt_co_rec k g5 A) R
end.
Fixpoint open_co_wrt_tm_rec (k:nat) (a5:tm) (g_5:co) {struct g_5}: co :=
match g_5 with
| g_Triv => g_Triv
| (g_Var_b nat) => g_Var_b nat
| (g_Var_f c) => g_Var_f c
| (g_Beta a b) => g_Beta (open_tm_wrt_tm_rec k a5 a) (open_tm_wrt_tm_rec k a5 b)
| (g_Refl a) => g_Refl (open_tm_wrt_tm_rec k a5 a)
| (g_Refl2 a b g) => g_Refl2 (open_tm_wrt_tm_rec k a5 a) (open_tm_wrt_tm_rec k a5 b) (open_co_wrt_tm_rec k a5 g)
| (g_Sym g) => g_Sym (open_co_wrt_tm_rec k a5 g)
| (g_Trans g1 g2) => g_Trans (open_co_wrt_tm_rec k a5 g1) (open_co_wrt_tm_rec k a5 g2)
| (g_Sub g) => g_Sub (open_co_wrt_tm_rec k a5 g)
| (g_PiCong rho R g1 g2) => g_PiCong rho R (open_co_wrt_tm_rec k a5 g1) (open_co_wrt_tm_rec (S k) a5 g2)
| (g_AbsCong rho R g1 g2) => g_AbsCong rho R (open_co_wrt_tm_rec k a5 g1) (open_co_wrt_tm_rec (S k) a5 g2)
| (g_AppCong g1 rho R g2) => g_AppCong (open_co_wrt_tm_rec k a5 g1) rho R (open_co_wrt_tm_rec k a5 g2)
| (g_PiFst g) => g_PiFst (open_co_wrt_tm_rec k a5 g)
| (g_CPiFst g) => g_CPiFst (open_co_wrt_tm_rec k a5 g)
| (g_IsoSnd g) => g_IsoSnd (open_co_wrt_tm_rec k a5 g)
| (g_PiSnd g1 g2) => g_PiSnd (open_co_wrt_tm_rec k a5 g1) (open_co_wrt_tm_rec k a5 g2)
| (g_CPiCong g1 g3) => g_CPiCong (open_co_wrt_tm_rec k a5 g1) (open_co_wrt_tm_rec k a5 g3)
| (g_CAbsCong g1 g3 g4) => g_CAbsCong (open_co_wrt_tm_rec k a5 g1) (open_co_wrt_tm_rec k a5 g3) (open_co_wrt_tm_rec k a5 g4)
| (g_CAppCong g g1 g2) => g_CAppCong (open_co_wrt_tm_rec k a5 g) (open_co_wrt_tm_rec k a5 g1) (open_co_wrt_tm_rec k a5 g2)
| (g_CPiSnd g g1 g2) => g_CPiSnd (open_co_wrt_tm_rec k a5 g) (open_co_wrt_tm_rec k a5 g1) (open_co_wrt_tm_rec k a5 g2)
| (g_Cast g1 R g2) => g_Cast (open_co_wrt_tm_rec k a5 g1) R (open_co_wrt_tm_rec k a5 g2)
| (g_EqCong g1 A g2) => g_EqCong (open_co_wrt_tm_rec k a5 g1) (open_tm_wrt_tm_rec k a5 A) (open_co_wrt_tm_rec k a5 g2)
| (g_IsoConv phi1 phi2 g) => g_IsoConv (open_constraint_wrt_tm_rec k a5 phi1) (open_constraint_wrt_tm_rec k a5 phi2) (open_co_wrt_tm_rec k a5 g)
| (g_Eta a) => g_Eta (open_tm_wrt_tm_rec k a5 a)
| (g_Left g g') => g_Left (open_co_wrt_tm_rec k a5 g) (open_co_wrt_tm_rec k a5 g')
| (g_Right g g') => g_Right (open_co_wrt_tm_rec k a5 g) (open_co_wrt_tm_rec k a5 g')
end
with open_brs_wrt_tm_rec (k:nat) (a5:tm) (brs_6:brs) {struct brs_6}: brs :=
match brs_6 with
| br_None => br_None
| (br_One K a brs5) => br_One K (open_tm_wrt_tm_rec k a5 a) (open_brs_wrt_tm_rec k a5 brs5)
end
with open_tm_wrt_tm_rec (k:nat) (a5:tm) (a_6:tm) {struct a_6}: tm :=
match a_6 with
| a_Star => a_Star
| (a_Var_b nat) => if (k === nat) then a5 else (a_Var_b nat)
| (a_Var_f x) => a_Var_f x
| (a_Abs rho A b) => a_Abs rho (open_tm_wrt_tm_rec k a5 A) (open_tm_wrt_tm_rec (S k) a5 b)
| (a_UAbs rho b) => a_UAbs rho (open_tm_wrt_tm_rec (S k) a5 b)
| (a_App a nu b) => a_App (open_tm_wrt_tm_rec k a5 a) nu (open_tm_wrt_tm_rec k a5 b)
| (a_Pi rho A B) => a_Pi rho (open_tm_wrt_tm_rec k a5 A) (open_tm_wrt_tm_rec (S k) a5 B)
| (a_CAbs phi b) => a_CAbs (open_constraint_wrt_tm_rec k a5 phi) (open_tm_wrt_tm_rec k a5 b)
| (a_UCAbs b) => a_UCAbs (open_tm_wrt_tm_rec k a5 b)
| (a_CApp a g) => a_CApp (open_tm_wrt_tm_rec k a5 a) (open_co_wrt_tm_rec k a5 g)
| (a_CPi phi B) => a_CPi (open_constraint_wrt_tm_rec k a5 phi) (open_tm_wrt_tm_rec k a5 B)
| (a_Conv a R g) => a_Conv (open_tm_wrt_tm_rec k a5 a) R (open_co_wrt_tm_rec k a5 g)
| (a_Fam F) => a_Fam F
| a_Bullet => a_Bullet
| (a_Pattern R a F Apps5 b1 b2) => a_Pattern R (open_tm_wrt_tm_rec k a5 a) F Apps5 (open_tm_wrt_tm_rec k a5 b1) (open_tm_wrt_tm_rec k a5 b2)
| (a_DataCon K) => a_DataCon K
| (a_Case a brs5) => a_Case (open_tm_wrt_tm_rec k a5 a) (open_brs_wrt_tm_rec k a5 brs5)
| (a_Sub R a) => a_Sub R (open_tm_wrt_tm_rec k a5 a)
| a_Coerce => a_Coerce
| (a_SrcApp a b) => a_SrcApp (open_tm_wrt_tm_rec k a5 a) (open_tm_wrt_tm_rec k a5 b)
end
with open_constraint_wrt_tm_rec (k:nat) (a5:tm) (phi5:constraint) : constraint :=
match phi5 with
| (Eq a b A R) => Eq (open_tm_wrt_tm_rec k a5 a) (open_tm_wrt_tm_rec k a5 b) (open_tm_wrt_tm_rec k a5 A) R
end.
Definition open_sort_wrt_co_rec (k:nat) (g5:co) (sort5:sort) : sort :=
match sort5 with
| (Tm A) => Tm (open_tm_wrt_co_rec k g5 A)
| (Co phi) => Co (open_constraint_wrt_co_rec k g5 phi)
end.
Definition open_pattern_arg_wrt_tm_rec (k:nat) (a5:tm) (pattern_arg5:pattern_arg) : pattern_arg :=
match pattern_arg5 with
| (p_Tm nu a) => p_Tm nu (open_tm_wrt_tm_rec k a5 a)
| (p_Co g) => p_Co (open_co_wrt_tm_rec k a5 g)
end.
Definition open_sig_sort_wrt_co_rec (k:nat) (g5:co) (sig_sort5:sig_sort) : sig_sort :=
match sig_sort5 with
| (Cs A Rs) => Cs (open_tm_wrt_co_rec k g5 A) Rs
| (Ax p a A R Rs) => Ax (open_tm_wrt_co_rec k g5 p) (open_tm_wrt_co_rec k g5 a) (open_tm_wrt_co_rec k g5 A) R Rs
end.
Definition open_sig_sort_wrt_tm_rec (k:nat) (a5:tm) (sig_sort5:sig_sort) : sig_sort :=
match sig_sort5 with
| (Cs A Rs) => Cs (open_tm_wrt_tm_rec k a5 A) Rs
| (Ax p a A R Rs) => Ax (open_tm_wrt_tm_rec k a5 p) (open_tm_wrt_tm_rec k a5 a) (open_tm_wrt_tm_rec k a5 A) R Rs
end.
Definition open_pattern_arg_wrt_co_rec (k:nat) (g5:co) (pattern_arg5:pattern_arg) : pattern_arg :=
match pattern_arg5 with
| (p_Tm nu a) => p_Tm nu (open_tm_wrt_co_rec k g5 a)
| (p_Co g) => p_Co (open_co_wrt_co_rec k g5 g)
end.
Definition open_sort_wrt_tm_rec (k:nat) (a5:tm) (sort5:sort) : sort :=
match sort5 with
| (Tm A) => Tm (open_tm_wrt_tm_rec k a5 A)
| (Co phi) => Co (open_constraint_wrt_tm_rec k a5 phi)
end.
Definition open_brs_wrt_co g5 brs_6 := open_brs_wrt_co_rec 0 brs_6 g5.
Definition open_tm_wrt_co g5 a5 := open_tm_wrt_co_rec 0 a5 g5.
Definition open_brs_wrt_tm a5 brs_6 := open_brs_wrt_tm_rec 0 brs_6 a5.
Definition open_sort_wrt_co g5 sort5 := open_sort_wrt_co_rec 0 sort5 g5.
Definition open_pattern_arg_wrt_tm a5 pattern_arg5 := open_pattern_arg_wrt_tm_rec 0 pattern_arg5 a5.
Definition open_sig_sort_wrt_co g5 sig_sort5 := open_sig_sort_wrt_co_rec 0 sig_sort5 g5.
Definition open_co_wrt_co g_5 g__6 := open_co_wrt_co_rec 0 g__6 g_5.
Definition open_sig_sort_wrt_tm a5 sig_sort5 := open_sig_sort_wrt_tm_rec 0 sig_sort5 a5.
Definition open_pattern_arg_wrt_co g5 pattern_arg5 := open_pattern_arg_wrt_co_rec 0 pattern_arg5 g5.
Definition open_constraint_wrt_co g5 phi5 := open_constraint_wrt_co_rec 0 phi5 g5.
Definition open_constraint_wrt_tm a5 phi5 := open_constraint_wrt_tm_rec 0 phi5 a5.
Definition open_co_wrt_tm a5 g_5 := open_co_wrt_tm_rec 0 g_5 a5.
Definition open_sort_wrt_tm a5 sort5 := open_sort_wrt_tm_rec 0 sort5 a5.
Definition open_tm_wrt_tm a5 a_6 := open_tm_wrt_tm_rec 0 a_6 a5.
(** terms are locally-closed pre-terms *)
(** definitions *)
(* defns LC_co_brs_tm_constraint *)
Inductive lc_co : co -> Prop := (* defn lc_co *)
| lc_g_Triv :
(lc_co g_Triv)
| lc_g_Var_f : forall (c:covar),
(lc_co (g_Var_f c))
| lc_g_Beta : forall (a b:tm),
(lc_tm a) ->
(lc_tm b) ->
(lc_co (g_Beta a b))
| lc_g_Refl : forall (a:tm),
(lc_tm a) ->
(lc_co (g_Refl a))
| lc_g_Refl2 : forall (a b:tm) (g:co),
(lc_tm a) ->
(lc_tm b) ->
(lc_co g) ->
(lc_co (g_Refl2 a b g))
| lc_g_Sym : forall (g:co),
(lc_co g) ->
(lc_co (g_Sym g))
| lc_g_Trans : forall (g1 g2:co),
(lc_co g1) ->
(lc_co g2) ->
(lc_co (g_Trans g1 g2))
| lc_g_Sub : forall (g:co),
(lc_co g) ->
(lc_co (g_Sub g))
| lc_g_PiCong : forall (L:vars) (rho:relflag) (R:role) (g1 g2:co),
(lc_co g1) ->
( forall x , x \notin L -> lc_co ( open_co_wrt_tm g2 (a_Var_f x) ) ) ->
(lc_co (g_PiCong rho R g1 g2))
| lc_g_AbsCong : forall (L:vars) (rho:relflag) (R:role) (g1 g2:co),
(lc_co g1) ->
( forall x , x \notin L -> lc_co ( open_co_wrt_tm g2 (a_Var_f x) ) ) ->
(lc_co (g_AbsCong rho R g1 g2))
| lc_g_AppCong : forall (g1:co) (rho:relflag) (R:role) (g2:co),
(lc_co g1) ->
(lc_co g2) ->
(lc_co (g_AppCong g1 rho R g2))
| lc_g_PiFst : forall (g:co),
(lc_co g) ->
(lc_co (g_PiFst g))
| lc_g_CPiFst : forall (g:co),
(lc_co g) ->
(lc_co (g_CPiFst g))
| lc_g_IsoSnd : forall (g:co),
(lc_co g) ->
(lc_co (g_IsoSnd g))
| lc_g_PiSnd : forall (g1 g2:co),
(lc_co g1) ->
(lc_co g2) ->
(lc_co (g_PiSnd g1 g2))
| lc_g_CPiCong : forall (L:vars) (g1 g3:co),
(lc_co g1) ->
( forall c , c \notin L -> lc_co ( open_co_wrt_co g3 (g_Var_f c) ) ) ->
(lc_co (g_CPiCong g1 g3))
| lc_g_CAbsCong : forall (L:vars) (g1 g3 g4:co),
(lc_co g1) ->
( forall c , c \notin L -> lc_co ( open_co_wrt_co g3 (g_Var_f c) ) ) ->
(lc_co g4) ->
(lc_co (g_CAbsCong g1 g3 g4))
| lc_g_CAppCong : forall (g g1 g2:co),
(lc_co g) ->
(lc_co g1) ->
(lc_co g2) ->
(lc_co (g_CAppCong g g1 g2))
| lc_g_CPiSnd : forall (g g1 g2:co),
(lc_co g) ->
(lc_co g1) ->
(lc_co g2) ->
(lc_co (g_CPiSnd g g1 g2))
| lc_g_Cast : forall (g1:co) (R:role) (g2:co),
(lc_co g1) ->
(lc_co g2) ->
(lc_co (g_Cast g1 R g2))
| lc_g_EqCong : forall (g1:co) (A:tm) (g2:co),
(lc_co g1) ->
(lc_tm A) ->
(lc_co g2) ->
(lc_co (g_EqCong g1 A g2))
| lc_g_IsoConv : forall (phi1 phi2:constraint) (g:co),
(lc_constraint phi1) ->
(lc_constraint phi2) ->
(lc_co g) ->
(lc_co (g_IsoConv phi1 phi2 g))
| lc_g_Eta : forall (a:tm),
(lc_tm a) ->
(lc_co (g_Eta a))
| lc_g_Left : forall (g g':co),
(lc_co g) ->
(lc_co g') ->
(lc_co (g_Left g g'))
| lc_g_Right : forall (g g':co),
(lc_co g) ->
(lc_co g') ->
(lc_co (g_Right g g'))
with lc_brs : brs -> Prop := (* defn lc_brs *)
| lc_br_None :
(lc_brs br_None)
| lc_br_One : forall (K:datacon) (a:tm) (brs5:brs),
(lc_tm a) ->
(lc_brs brs5) ->
(lc_brs (br_One K a brs5))
with lc_tm : tm -> Prop := (* defn lc_tm *)
| lc_a_Star :
(lc_tm a_Star)
| lc_a_Var_f : forall (x:tmvar),
(lc_tm (a_Var_f x))
| lc_a_Abs : forall (L:vars) (rho:relflag) (A b:tm),
(lc_tm A) ->
( forall x , x \notin L -> lc_tm ( open_tm_wrt_tm b (a_Var_f x) ) ) ->
(lc_tm (a_Abs rho A b))
| lc_a_UAbs : forall (L:vars) (rho:relflag) (b:tm),
( forall x , x \notin L -> lc_tm ( open_tm_wrt_tm b (a_Var_f x) ) ) ->
(lc_tm (a_UAbs rho b))
| lc_a_App : forall (a:tm) (nu:appflag) (b:tm),
(lc_tm a) ->
(lc_tm b) ->
(lc_tm (a_App a nu b))
| lc_a_Pi : forall (L:vars) (rho:relflag) (A B:tm),
(lc_tm A) ->
( forall x , x \notin L -> lc_tm ( open_tm_wrt_tm B (a_Var_f x) ) ) ->
(lc_tm (a_Pi rho A B))
| lc_a_CAbs : forall (L:vars) (phi:constraint) (b:tm),
(lc_constraint phi) ->
( forall c , c \notin L -> lc_tm ( open_tm_wrt_co b (g_Var_f c) ) ) ->
(lc_tm (a_CAbs phi b))
| lc_a_UCAbs : forall (L:vars) (b:tm),
( forall c , c \notin L -> lc_tm ( open_tm_wrt_co b (g_Var_f c) ) ) ->
(lc_tm (a_UCAbs b))
| lc_a_CApp : forall (a:tm) (g:co),
(lc_tm a) ->
(lc_co g) ->
(lc_tm (a_CApp a g))
| lc_a_CPi : forall (L:vars) (phi:constraint) (B:tm),
(lc_constraint phi) ->
( forall c , c \notin L -> lc_tm ( open_tm_wrt_co B (g_Var_f c) ) ) ->
(lc_tm (a_CPi phi B))
| lc_a_Conv : forall (a:tm) (R:role) (g:co),
(lc_tm a) ->
(lc_co g) ->
(lc_tm (a_Conv a R g))
| lc_a_Fam : forall (F:const),
(lc_tm (a_Fam F))
| lc_a_Bullet :
(lc_tm a_Bullet)
| lc_a_Pattern : forall (R:role) (a:tm) (F:const) (Apps5:Apps) (b1 b2:tm),
(lc_tm a) ->
(lc_tm b1) ->
(lc_tm b2) ->
(lc_tm (a_Pattern R a F Apps5 b1 b2))
| lc_a_DataCon : forall (K:datacon),
(lc_tm (a_DataCon K))
| lc_a_Case : forall (a:tm) (brs5:brs),
(lc_tm a) ->
(lc_brs brs5) ->
(lc_tm (a_Case a brs5))
| lc_a_Sub : forall (R:role) (a:tm),
(lc_tm a) ->
(lc_tm (a_Sub R a))
| lc_a_Coerce :
(lc_tm a_Coerce)
| lc_a_SrcApp : forall (a b:tm),
(lc_tm a) ->
(lc_tm b) ->
(lc_tm (a_SrcApp a b))
with lc_constraint : constraint -> Prop := (* defn lc_constraint *)
| lc_Eq : forall (a b A:tm) (R:role),
(lc_tm a) ->
(lc_tm b) ->
(lc_tm A) ->
(lc_constraint (Eq a b A R)).
(* defns LC_sort *)
Inductive lc_sort : sort -> Prop := (* defn lc_sort *)
| lc_Tm : forall (A:tm),
(lc_tm A) ->
(lc_sort (Tm A))
| lc_Co : forall (phi:constraint),
(lc_constraint phi) ->
(lc_sort (Co phi)).
(* defns LC_sig_sort *)
Inductive lc_sig_sort : sig_sort -> Prop := (* defn lc_sig_sort *)
| lc_Cs : forall (A:tm) (Rs:roles),
(lc_tm A) ->
(lc_sig_sort (Cs A Rs))
| lc_Ax : forall (p a A:tm) (R:role) (Rs:roles),
(lc_tm p) ->
(lc_tm a) ->
(lc_tm A) ->
(lc_sig_sort (Ax p a A R Rs)).
(* defns LC_pattern_arg *)
Inductive lc_pattern_arg : pattern_arg -> Prop := (* defn lc_pattern_arg *)
| lc_p_Tm : forall (nu:appflag) (a:tm),
(lc_tm a) ->
(lc_pattern_arg (p_Tm nu a))
| lc_p_Co : forall (g:co),
(lc_co g) ->
(lc_pattern_arg (p_Co g)).
(** free variables *)
Fixpoint fv_tm_tm_co (g_5:co) : vars :=
match g_5 with
| g_Triv => {}
| (g_Var_b nat) => {}
| (g_Var_f c) => {}
| (g_Beta a b) => (fv_tm_tm_tm a) \u (fv_tm_tm_tm b)
| (g_Refl a) => (fv_tm_tm_tm a)
| (g_Refl2 a b g) => (fv_tm_tm_tm a) \u (fv_tm_tm_tm b) \u (fv_tm_tm_co g)
| (g_Sym g) => (fv_tm_tm_co g)
| (g_Trans g1 g2) => (fv_tm_tm_co g1) \u (fv_tm_tm_co g2)
| (g_Sub g) => (fv_tm_tm_co g)
| (g_PiCong rho R g1 g2) => (fv_tm_tm_co g1) \u (fv_tm_tm_co g2)
| (g_AbsCong rho R g1 g2) => (fv_tm_tm_co g1) \u (fv_tm_tm_co g2)
| (g_AppCong g1 rho R g2) => (fv_tm_tm_co g1) \u (fv_tm_tm_co g2)
| (g_PiFst g) => (fv_tm_tm_co g)
| (g_CPiFst g) => (fv_tm_tm_co g)
| (g_IsoSnd g) => (fv_tm_tm_co g)
| (g_PiSnd g1 g2) => (fv_tm_tm_co g1) \u (fv_tm_tm_co g2)
| (g_CPiCong g1 g3) => (fv_tm_tm_co g1) \u (fv_tm_tm_co g3)
| (g_CAbsCong g1 g3 g4) => (fv_tm_tm_co g1) \u (fv_tm_tm_co g3) \u (fv_tm_tm_co g4)
| (g_CAppCong g g1 g2) => (fv_tm_tm_co g) \u (fv_tm_tm_co g1) \u (fv_tm_tm_co g2)
| (g_CPiSnd g g1 g2) => (fv_tm_tm_co g) \u (fv_tm_tm_co g1) \u (fv_tm_tm_co g2)
| (g_Cast g1 R g2) => (fv_tm_tm_co g1) \u (fv_tm_tm_co g2)
| (g_EqCong g1 A g2) => (fv_tm_tm_co g1) \u (fv_tm_tm_tm A) \u (fv_tm_tm_co g2)
| (g_IsoConv phi1 phi2 g) => (fv_tm_tm_constraint phi1) \u (fv_tm_tm_constraint phi2) \u (fv_tm_tm_co g)
| (g_Eta a) => (fv_tm_tm_tm a)
| (g_Left g g') => (fv_tm_tm_co g) \u (fv_tm_tm_co g')
| (g_Right g g') => (fv_tm_tm_co g) \u (fv_tm_tm_co g')
end
with fv_tm_tm_brs (brs_6:brs) : vars :=
match brs_6 with
| br_None => {}
| (br_One K a brs5) => (fv_tm_tm_tm a) \u (fv_tm_tm_brs brs5)
end
with fv_tm_tm_tm (a5:tm) : vars :=
match a5 with
| a_Star => {}
| (a_Var_b nat) => {}
| (a_Var_f x) => {{x}}
| (a_Abs rho A b) => (fv_tm_tm_tm A) \u (fv_tm_tm_tm b)
| (a_UAbs rho b) => (fv_tm_tm_tm b)
| (a_App a nu b) => (fv_tm_tm_tm a) \u (fv_tm_tm_tm b)
| (a_Pi rho A B) => (fv_tm_tm_tm A) \u (fv_tm_tm_tm B)
| (a_CAbs phi b) => (fv_tm_tm_constraint phi) \u (fv_tm_tm_tm b)
| (a_UCAbs b) => (fv_tm_tm_tm b)
| (a_CApp a g) => (fv_tm_tm_tm a) \u (fv_tm_tm_co g)
| (a_CPi phi B) => (fv_tm_tm_constraint phi) \u (fv_tm_tm_tm B)
| (a_Conv a R g) => (fv_tm_tm_tm a) \u (fv_tm_tm_co g)
| (a_Fam F) => {}
| a_Bullet => {}
| (a_Pattern R a F Apps5 b1 b2) => (fv_tm_tm_tm a) \u (fv_tm_tm_tm b1) \u (fv_tm_tm_tm b2)
| (a_DataCon K) => {}
| (a_Case a brs5) => (fv_tm_tm_tm a) \u (fv_tm_tm_brs brs5)
| (a_Sub R a) => (fv_tm_tm_tm a)
| a_Coerce => {}
| (a_SrcApp a b) => (fv_tm_tm_tm a) \u (fv_tm_tm_tm b)
end
with fv_tm_tm_constraint (phi5:constraint) : vars :=
match phi5 with
| (Eq a b A R) => (fv_tm_tm_tm a) \u (fv_tm_tm_tm b) \u (fv_tm_tm_tm A)
end.
Fixpoint fv_co_co_co (g_5:co) : vars :=
match g_5 with
| g_Triv => {}
| (g_Var_b nat) => {}
| (g_Var_f c) => {{c}}
| (g_Beta a b) => (fv_co_co_tm a) \u (fv_co_co_tm b)
| (g_Refl a) => (fv_co_co_tm a)
| (g_Refl2 a b g) => (fv_co_co_tm a) \u (fv_co_co_tm b) \u (fv_co_co_co g)
| (g_Sym g) => (fv_co_co_co g)
| (g_Trans g1 g2) => (fv_co_co_co g1) \u (fv_co_co_co g2)
| (g_Sub g) => (fv_co_co_co g)
| (g_PiCong rho R g1 g2) => (fv_co_co_co g1) \u (fv_co_co_co g2)
| (g_AbsCong rho R g1 g2) => (fv_co_co_co g1) \u (fv_co_co_co g2)
| (g_AppCong g1 rho R g2) => (fv_co_co_co g1) \u (fv_co_co_co g2)
| (g_PiFst g) => (fv_co_co_co g)
| (g_CPiFst g) => (fv_co_co_co g)
| (g_IsoSnd g) => (fv_co_co_co g)
| (g_PiSnd g1 g2) => (fv_co_co_co g1) \u (fv_co_co_co g2)
| (g_CPiCong g1 g3) => (fv_co_co_co g1) \u (fv_co_co_co g3)
| (g_CAbsCong g1 g3 g4) => (fv_co_co_co g1) \u (fv_co_co_co g3) \u (fv_co_co_co g4)
| (g_CAppCong g g1 g2) => (fv_co_co_co g) \u (fv_co_co_co g1) \u (fv_co_co_co g2)
| (g_CPiSnd g g1 g2) => (fv_co_co_co g) \u (fv_co_co_co g1) \u (fv_co_co_co g2)
| (g_Cast g1 R g2) => (fv_co_co_co g1) \u (fv_co_co_co g2)
| (g_EqCong g1 A g2) => (fv_co_co_co g1) \u (fv_co_co_tm A) \u (fv_co_co_co g2)
| (g_IsoConv phi1 phi2 g) => (fv_co_co_constraint phi1) \u (fv_co_co_constraint phi2) \u (fv_co_co_co g)
| (g_Eta a) => (fv_co_co_tm a)
| (g_Left g g') => (fv_co_co_co g) \u (fv_co_co_co g')
| (g_Right g g') => (fv_co_co_co g) \u (fv_co_co_co g')
end
with fv_co_co_brs (brs_6:brs) : vars :=
match brs_6 with
| br_None => {}
| (br_One K a brs5) => (fv_co_co_tm a) \u (fv_co_co_brs brs5)
end
with fv_co_co_tm (a5:tm) : vars :=
match a5 with
| a_Star => {}
| (a_Var_b nat) => {}
| (a_Var_f x) => {}
| (a_Abs rho A b) => (fv_co_co_tm A) \u (fv_co_co_tm b)
| (a_UAbs rho b) => (fv_co_co_tm b)
| (a_App a nu b) => (fv_co_co_tm a) \u (fv_co_co_tm b)
| (a_Pi rho A B) => (fv_co_co_tm A) \u (fv_co_co_tm B)
| (a_CAbs phi b) => (fv_co_co_constraint phi) \u (fv_co_co_tm b)
| (a_UCAbs b) => (fv_co_co_tm b)
| (a_CApp a g) => (fv_co_co_tm a) \u (fv_co_co_co g)
| (a_CPi phi B) => (fv_co_co_constraint phi) \u (fv_co_co_tm B)
| (a_Conv a R g) => (fv_co_co_tm a) \u (fv_co_co_co g)
| (a_Fam F) => {}
| a_Bullet => {}
| (a_Pattern R a F Apps5 b1 b2) => (fv_co_co_tm a) \u (fv_co_co_tm b1) \u (fv_co_co_tm b2)
| (a_DataCon K) => {}
| (a_Case a brs5) => (fv_co_co_tm a) \u (fv_co_co_brs brs5)
| (a_Sub R a) => (fv_co_co_tm a)
| a_Coerce => {}
| (a_SrcApp a b) => (fv_co_co_tm a) \u (fv_co_co_tm b)
end
with fv_co_co_constraint (phi5:constraint) : vars :=
match phi5 with
| (Eq a b A R) => (fv_co_co_tm a) \u (fv_co_co_tm b) \u (fv_co_co_tm A)
end.
Definition fv_tm_tm_sort (sort5:sort) : vars :=
match sort5 with
| (Tm A) => (fv_tm_tm_tm A)
| (Co phi) => (fv_tm_tm_constraint phi)
end.
Definition fv_co_co_pattern_arg (pattern_arg5:pattern_arg) : vars :=
match pattern_arg5 with
| (p_Tm nu a) => (fv_co_co_tm a)
| (p_Co g) => (fv_co_co_co g)
end.
Definition fv_co_co_sig_sort (sig_sort5:sig_sort) : vars :=
match sig_sort5 with
| (Cs A Rs) => (fv_co_co_tm A)
| (Ax p a A R Rs) => (fv_co_co_tm p) \u (fv_co_co_tm a) \u (fv_co_co_tm A)
end.
Definition fv_co_co_sort (sort5:sort) : vars :=
match sort5 with
| (Tm A) => (fv_co_co_tm A)
| (Co phi) => (fv_co_co_constraint phi)
end.
Definition fv_tm_tm_pattern_arg (pattern_arg5:pattern_arg) : vars :=
match pattern_arg5 with
| (p_Tm nu a) => (fv_tm_tm_tm a)
| (p_Co g) => (fv_tm_tm_co g)
end.
Definition fv_tm_tm_sig_sort (sig_sort5:sig_sort) : vars :=
match sig_sort5 with
| (Cs A Rs) => (fv_tm_tm_tm A)
| (Ax p a A R Rs) => (fv_tm_tm_tm p) \u (fv_tm_tm_tm a) \u (fv_tm_tm_tm A)
end.
(** substitutions *)
Fixpoint co_subst_co_constraint (g5:co) (c5:covar) (phi5:constraint) {struct phi5} : constraint :=
match phi5 with
| (Eq a b A R) => Eq (co_subst_co_tm g5 c5 a) (co_subst_co_tm g5 c5 b) (co_subst_co_tm g5 c5 A) R
end
with co_subst_co_co (g_5:co) (c5:covar) (g__6:co) {struct g__6} : co :=
match g__6 with
| g_Triv => g_Triv
| (g_Var_b nat) => g_Var_b nat
| (g_Var_f c) => (if eq_var c c5 then g_5 else (g_Var_f c))
| (g_Beta a b) => g_Beta (co_subst_co_tm g_5 c5 a) (co_subst_co_tm g_5 c5 b)
| (g_Refl a) => g_Refl (co_subst_co_tm g_5 c5 a)
| (g_Refl2 a b g) => g_Refl2 (co_subst_co_tm g_5 c5 a) (co_subst_co_tm g_5 c5 b) (co_subst_co_co g_5 c5 g)
| (g_Sym g) => g_Sym (co_subst_co_co g_5 c5 g)
| (g_Trans g1 g2) => g_Trans (co_subst_co_co g_5 c5 g1) (co_subst_co_co g_5 c5 g2)
| (g_Sub g) => g_Sub (co_subst_co_co g_5 c5 g)
| (g_PiCong rho R g1 g2) => g_PiCong rho R (co_subst_co_co g_5 c5 g1) (co_subst_co_co g_5 c5 g2)
| (g_AbsCong rho R g1 g2) => g_AbsCong rho R (co_subst_co_co g_5 c5 g1) (co_subst_co_co g_5 c5 g2)
| (g_AppCong g1 rho R g2) => g_AppCong (co_subst_co_co g_5 c5 g1) rho R (co_subst_co_co g_5 c5 g2)
| (g_PiFst g) => g_PiFst (co_subst_co_co g_5 c5 g)
| (g_CPiFst g) => g_CPiFst (co_subst_co_co g_5 c5 g)
| (g_IsoSnd g) => g_IsoSnd (co_subst_co_co g_5 c5 g)
| (g_PiSnd g1 g2) => g_PiSnd (co_subst_co_co g_5 c5 g1) (co_subst_co_co g_5 c5 g2)
| (g_CPiCong g1 g3) => g_CPiCong (co_subst_co_co g_5 c5 g1) (co_subst_co_co g_5 c5 g3)
| (g_CAbsCong g1 g3 g4) => g_CAbsCong (co_subst_co_co g_5 c5 g1) (co_subst_co_co g_5 c5 g3) (co_subst_co_co g_5 c5 g4)
| (g_CAppCong g g1 g2) => g_CAppCong (co_subst_co_co g_5 c5 g) (co_subst_co_co g_5 c5 g1) (co_subst_co_co g_5 c5 g2)
| (g_CPiSnd g g1 g2) => g_CPiSnd (co_subst_co_co g_5 c5 g) (co_subst_co_co g_5 c5 g1) (co_subst_co_co g_5 c5 g2)
| (g_Cast g1 R g2) => g_Cast (co_subst_co_co g_5 c5 g1) R (co_subst_co_co g_5 c5 g2)
| (g_EqCong g1 A g2) => g_EqCong (co_subst_co_co g_5 c5 g1) (co_subst_co_tm g_5 c5 A) (co_subst_co_co g_5 c5 g2)
| (g_IsoConv phi1 phi2 g) => g_IsoConv (co_subst_co_constraint g_5 c5 phi1) (co_subst_co_constraint g_5 c5 phi2) (co_subst_co_co g_5 c5 g)
| (g_Eta a) => g_Eta (co_subst_co_tm g_5 c5 a)
| (g_Left g g') => g_Left (co_subst_co_co g_5 c5 g) (co_subst_co_co g_5 c5 g')
| (g_Right g g') => g_Right (co_subst_co_co g_5 c5 g) (co_subst_co_co g_5 c5 g')
end
with co_subst_co_brs (g5:co) (c5:covar) (brs_6:brs) {struct brs_6} : brs :=
match brs_6 with
| br_None => br_None
| (br_One K a brs5) => br_One K (co_subst_co_tm g5 c5 a) (co_subst_co_brs g5 c5 brs5)
end
with co_subst_co_tm (g5:co) (c5:covar) (a5:tm) {struct a5} : tm :=
match a5 with
| a_Star => a_Star
| (a_Var_b nat) => a_Var_b nat
| (a_Var_f x) => a_Var_f x
| (a_Abs rho A b) => a_Abs rho (co_subst_co_tm g5 c5 A) (co_subst_co_tm g5 c5 b)
| (a_UAbs rho b) => a_UAbs rho (co_subst_co_tm g5 c5 b)
| (a_App a nu b) => a_App (co_subst_co_tm g5 c5 a) nu (co_subst_co_tm g5 c5 b)
| (a_Pi rho A B) => a_Pi rho (co_subst_co_tm g5 c5 A) (co_subst_co_tm g5 c5 B)
| (a_CAbs phi b) => a_CAbs (co_subst_co_constraint g5 c5 phi) (co_subst_co_tm g5 c5 b)
| (a_UCAbs b) => a_UCAbs (co_subst_co_tm g5 c5 b)
| (a_CApp a g) => a_CApp (co_subst_co_tm g5 c5 a) (co_subst_co_co g5 c5 g)
| (a_CPi phi B) => a_CPi (co_subst_co_constraint g5 c5 phi) (co_subst_co_tm g5 c5 B)
| (a_Conv a R g) => a_Conv (co_subst_co_tm g5 c5 a) R (co_subst_co_co g5 c5 g)
| (a_Fam F) => a_Fam F
| a_Bullet => a_Bullet
| (a_Pattern R a F Apps5 b1 b2) => a_Pattern R (co_subst_co_tm g5 c5 a) F Apps5 (co_subst_co_tm g5 c5 b1) (co_subst_co_tm g5 c5 b2)
| (a_DataCon K) => a_DataCon K
| (a_Case a brs5) => a_Case (co_subst_co_tm g5 c5 a) (co_subst_co_brs g5 c5 brs5)
| (a_Sub R a) => a_Sub R (co_subst_co_tm g5 c5 a)
| a_Coerce => a_Coerce
| (a_SrcApp a b) => a_SrcApp (co_subst_co_tm g5 c5 a) (co_subst_co_tm g5 c5 b)
end.
Fixpoint tm_subst_tm_co (a5:tm) (x5:tmvar) (g_5:co) {struct g_5} : co :=
match g_5 with
| g_Triv => g_Triv
| (g_Var_b nat) => g_Var_b nat
| (g_Var_f c) => g_Var_f c
| (g_Beta a b) => g_Beta (tm_subst_tm_tm a5 x5 a) (tm_subst_tm_tm a5 x5 b)
| (g_Refl a) => g_Refl (tm_subst_tm_tm a5 x5 a)
| (g_Refl2 a b g) => g_Refl2 (tm_subst_tm_tm a5 x5 a) (tm_subst_tm_tm a5 x5 b) (tm_subst_tm_co a5 x5 g)
| (g_Sym g) => g_Sym (tm_subst_tm_co a5 x5 g)
| (g_Trans g1 g2) => g_Trans (tm_subst_tm_co a5 x5 g1) (tm_subst_tm_co a5 x5 g2)
| (g_Sub g) => g_Sub (tm_subst_tm_co a5 x5 g)
| (g_PiCong rho R g1 g2) => g_PiCong rho R (tm_subst_tm_co a5 x5 g1) (tm_subst_tm_co a5 x5 g2)
| (g_AbsCong rho R g1 g2) => g_AbsCong rho R (tm_subst_tm_co a5 x5 g1) (tm_subst_tm_co a5 x5 g2)
| (g_AppCong g1 rho R g2) => g_AppCong (tm_subst_tm_co a5 x5 g1) rho R (tm_subst_tm_co a5 x5 g2)
| (g_PiFst g) => g_PiFst (tm_subst_tm_co a5 x5 g)
| (g_CPiFst g) => g_CPiFst (tm_subst_tm_co a5 x5 g)
| (g_IsoSnd g) => g_IsoSnd (tm_subst_tm_co a5 x5 g)
| (g_PiSnd g1 g2) => g_PiSnd (tm_subst_tm_co a5 x5 g1) (tm_subst_tm_co a5 x5 g2)
| (g_CPiCong g1 g3) => g_CPiCong (tm_subst_tm_co a5 x5 g1) (tm_subst_tm_co a5 x5 g3)
| (g_CAbsCong g1 g3 g4) => g_CAbsCong (tm_subst_tm_co a5 x5 g1) (tm_subst_tm_co a5 x5 g3) (tm_subst_tm_co a5 x5 g4)
| (g_CAppCong g g1 g2) => g_CAppCong (tm_subst_tm_co a5 x5 g) (tm_subst_tm_co a5 x5 g1) (tm_subst_tm_co a5 x5 g2)
| (g_CPiSnd g g1 g2) => g_CPiSnd (tm_subst_tm_co a5 x5 g) (tm_subst_tm_co a5 x5 g1) (tm_subst_tm_co a5 x5 g2)
| (g_Cast g1 R g2) => g_Cast (tm_subst_tm_co a5 x5 g1) R (tm_subst_tm_co a5 x5 g2)
| (g_EqCong g1 A g2) => g_EqCong (tm_subst_tm_co a5 x5 g1) (tm_subst_tm_tm a5 x5 A) (tm_subst_tm_co a5 x5 g2)
| (g_IsoConv phi1 phi2 g) => g_IsoConv (tm_subst_tm_constraint a5 x5 phi1) (tm_subst_tm_constraint a5 x5 phi2) (tm_subst_tm_co a5 x5 g)
| (g_Eta a) => g_Eta (tm_subst_tm_tm a5 x5 a)
| (g_Left g g') => g_Left (tm_subst_tm_co a5 x5 g) (tm_subst_tm_co a5 x5 g')
| (g_Right g g') => g_Right (tm_subst_tm_co a5 x5 g) (tm_subst_tm_co a5 x5 g')
end
with tm_subst_tm_brs (a5:tm) (x5:tmvar) (brs_6:brs) {struct brs_6} : brs :=
match brs_6 with
| br_None => br_None
| (br_One K a brs5) => br_One K (tm_subst_tm_tm a5 x5 a) (tm_subst_tm_brs a5 x5 brs5)
end
with tm_subst_tm_tm (a5:tm) (x5:tmvar) (a_6:tm) {struct a_6} : tm :=
match a_6 with
| a_Star => a_Star
| (a_Var_b nat) => a_Var_b nat
| (a_Var_f x) => (if eq_var x x5 then a5 else (a_Var_f x))
| (a_Abs rho A b) => a_Abs rho (tm_subst_tm_tm a5 x5 A) (tm_subst_tm_tm a5 x5 b)
| (a_UAbs rho b) => a_UAbs rho (tm_subst_tm_tm a5 x5 b)
| (a_App a nu b) => a_App (tm_subst_tm_tm a5 x5 a) nu (tm_subst_tm_tm a5 x5 b)
| (a_Pi rho A B) => a_Pi rho (tm_subst_tm_tm a5 x5 A) (tm_subst_tm_tm a5 x5 B)
| (a_CAbs phi b) => a_CAbs (tm_subst_tm_constraint a5 x5 phi) (tm_subst_tm_tm a5 x5 b)
| (a_UCAbs b) => a_UCAbs (tm_subst_tm_tm a5 x5 b)
| (a_CApp a g) => a_CApp (tm_subst_tm_tm a5 x5 a) (tm_subst_tm_co a5 x5 g)
| (a_CPi phi B) => a_CPi (tm_subst_tm_constraint a5 x5 phi) (tm_subst_tm_tm a5 x5 B)
| (a_Conv a R g) => a_Conv (tm_subst_tm_tm a5 x5 a) R (tm_subst_tm_co a5 x5 g)
| (a_Fam F) => a_Fam F
| a_Bullet => a_Bullet
| (a_Pattern R a F Apps5 b1 b2) => a_Pattern R (tm_subst_tm_tm a5 x5 a) F Apps5 (tm_subst_tm_tm a5 x5 b1) (tm_subst_tm_tm a5 x5 b2)
| (a_DataCon K) => a_DataCon K
| (a_Case a brs5) => a_Case (tm_subst_tm_tm a5 x5 a) (tm_subst_tm_brs a5 x5 brs5)
| (a_Sub R a) => a_Sub R (tm_subst_tm_tm a5 x5 a)
| a_Coerce => a_Coerce
| (a_SrcApp a b) => a_SrcApp (tm_subst_tm_tm a5 x5 a) (tm_subst_tm_tm a5 x5 b)
end
with tm_subst_tm_constraint (a5:tm) (x5:tmvar) (phi5:constraint) {struct phi5} : constraint :=
match phi5 with
| (Eq a b A R) => Eq (tm_subst_tm_tm a5 x5 a) (tm_subst_tm_tm a5 x5 b) (tm_subst_tm_tm a5 x5 A) R
end.
Definition co_subst_co_sort (g5:co) (c5:covar) (sort5:sort) : sort :=
match sort5 with
| (Tm A) => Tm (co_subst_co_tm g5 c5 A)
| (Co phi) => Co (co_subst_co_constraint g5 c5 phi)
end.
Definition tm_subst_tm_pattern_arg (a5:tm) (x5:tmvar) (pattern_arg5:pattern_arg) : pattern_arg :=
match pattern_arg5 with
| (p_Tm nu a) => p_Tm nu (tm_subst_tm_tm a5 x5 a)
| (p_Co g) => p_Co (tm_subst_tm_co a5 x5 g)
end.
Definition tm_subst_tm_sig_sort (a5:tm) (x5:tmvar) (sig_sort5:sig_sort) : sig_sort :=
match sig_sort5 with
| (Cs A Rs) => Cs (tm_subst_tm_tm a5 x5 A) Rs
| (Ax p a A R Rs) => Ax (tm_subst_tm_tm a5 x5 p) (tm_subst_tm_tm a5 x5 a) (tm_subst_tm_tm a5 x5 A) R Rs
end.
Definition tm_subst_tm_sort (a5:tm) (x5:tmvar) (sort5:sort) : sort :=
match sort5 with
| (Tm A) => Tm (tm_subst_tm_tm a5 x5 A)
| (Co phi) => Co (tm_subst_tm_constraint a5 x5 phi)
end.
Definition co_subst_co_pattern_arg (g5:co) (c5:covar) (pattern_arg5:pattern_arg) : pattern_arg :=
match pattern_arg5 with
| (p_Tm nu a) => p_Tm nu (co_subst_co_tm g5 c5 a)
| (p_Co g) => p_Co (co_subst_co_co g5 c5 g)
end.
Definition co_subst_co_sig_sort (g5:co) (c5:covar) (sig_sort5:sig_sort) : sig_sort :=
match sig_sort5 with
| (Cs A Rs) => Cs (co_subst_co_tm g5 c5 A) Rs
| (Ax p a A R Rs) => Ax (co_subst_co_tm g5 c5 p) (co_subst_co_tm g5 c5 a) (co_subst_co_tm g5 c5 A) R Rs
end.
Definition min (r1 : role) (r2 : role) : role :=
match r1 , r2 with
| Nom, _ => Nom
| _ , Nom => Nom
| Rep, Rep => Rep
end.
Parameter str : bool.
Definition param (r1 : role) (r2 : role) := min r1 r2.
Definition app_role (rr : appflag) (r1 : role) : role :=
match rr with
| Rho _ => Nom
| Role r => param r r1
end.
Definition app_rho (rr : appflag) : relflag :=
match rr with
| Rho p => p
| Role _ => Rel
end.
Definition nu_rho (nu : appflag) : Prop :=
match nu with
| Rho _ => True
| Role _ => False
end.
Definition max (r1 : role) (r2 : role) : role :=
match r1 , r2 with
| _, Rep => Rep
| Rep, _ => Rep
| Nom, Nom => Nom
end.
Definition lte_role (r1 : role) (r2 : role) : bool :=
match r1 , r2 with
| Nom, _ => true
| Rep, Nom => false
| Rep, Rep => true
end.
Fixpoint erase_tm (a : tm) (r : role) : tm :=
match a with
| a_Star => a_Star
| a_Var_b n => a_Var_b n
| a_Var_f x => a_Var_f x
| a_Abs rho A b => a_UAbs rho (erase_tm b r)
| a_UAbs rho b => a_UAbs rho (erase_tm b r)
| a_App a (Role R) b => a_App (erase_tm a r) (Role R) (erase_tm b r)
| a_App a (Rho Rel) b => a_App (erase_tm a r) (Rho Rel) (erase_tm b r)
| a_App a (Rho Irrel) b => a_App (erase_tm a r) (Rho Irrel) a_Bullet
| a_Fam F => a_Fam F
| a_Pi rho A B => a_Pi rho (erase_tm A r) (erase_tm B r)
| a_Conv a r1 g => if (lte_role r1 r) then
erase_tm a r else
a_Conv (erase_tm a r) r1 g_Triv
| a_CPi phi B => a_CPi (erase_constraint phi r) (erase_tm B r)
| a_CAbs phi b => a_UCAbs (erase_tm b r)
| a_UCAbs b => a_UCAbs (erase_tm b r)
| a_CApp a g => a_CApp (erase_tm a r) g_Triv
| a_DataCon K => a_Star (* a_DataCon K *)
| a_Case a brs => a_Star (* a_Case (erase_tm a) (erase_brs brs) *)
| a_Bullet => a_Bullet
| a_Pattern R a1 F Apps b1 b2 => a_Pattern R (erase_tm a1 r) F Apps (erase_tm b1 r) (erase_tm b2 r)
| a => a
end
with erase_brs (x : brs) (r:role): brs :=
match x with
| br_None => br_None
| br_One k a y => br_One k (erase_tm a r) (erase_brs y r)
end
with erase_constraint (phi : constraint) (r:role): constraint :=
match phi with
| Eq A B A1 R => Eq (erase_tm A R) (erase_tm B R) (erase_tm A1 R) R
end.
Definition erase_sort s r :=
match s with
| Tm a => Tm (erase_tm a r)
| Co p => Co (erase_constraint p r)
end.
Definition erase_csort s r :=
match s with
| Cs a Rs => Cs (erase_tm a r) Rs
| Ax p a A R Rs => Ax (erase_tm p r) (erase_tm a r) (erase_tm A r) R Rs
end.
Definition erase_context G r := map (fun s => erase_sort s r) G.
Definition erase_sig S r := map (fun s => erase_csort s r) S.
Fixpoint pattern_length (a : tm) : nat := match a with
a_Fam F => 0
| a_App a nu b => pattern_length a + 1
| a_CApp a g_Triv => pattern_length a + 1
| _ => 0
end.
Fixpoint vars_Pattern (p : tm) := match p with
| a_Fam F => nil
| a_App p1 (Role _) (a_Var_f x) => vars_Pattern p1 ++ [ x ]
| a_App p1 (Rho Irrel) a_Bullet => vars_Pattern p1
| a_CApp p1 g_Triv => vars_Pattern p1
| _ => nil
end.
Fixpoint apply_pattern_args (a : tm) (args : pattern_args) : tm :=
match args with
| nil => a
| (p_Tm nu b :: rest) =>
apply_pattern_args (a_App a nu b) rest
| (p_Co g :: rest) =>
apply_pattern_args (a_CApp a g) rest
end.
Fixpoint A_snoc (xs : Apps) (x : App) : Apps :=
match xs with
| A_nil => A_cons x A_nil
| A_cons y ys => (A_cons y (A_snoc ys x))
end.
Fixpoint range (L : role_context) : roles :=
match L with
| nil => nil
| (x,R) :: L' => range(L') ++ [ R ]
end.
(* -------------- A specific signature with Fix ------------ *)
Definition constants :
{ Star : atom &
{ Fix : atom &
{ FixVar1 : atom &
{ FixVar2 : atom &
Fix `notin` singleton Star /\
FixVar1 `notin` singleton Star \u (singleton Fix) /\
FixVar2 `notin` singleton Star \u singleton Fix \u singleton FixVar1 } } } }.
Proof.
pick fresh Star.
pick fresh Fix.
pick fresh FixVar1.
pick fresh FixVar2.
exists Star.
exists Fix.
exists FixVar1.
exists FixVar2.
repeat split; auto.
Defined.
Definition Star : atom.
destruct constants as [s _].
exact s.
Defined.
Definition Fix : atom.
destruct constants as [_ [f _] ].
exact f.
Defined.
Lemma noteq : Star <> Fix.
Proof.
unfold Star, Fix.
destruct constants as [s [f [f1 [f2 h] ] ] ].
destruct h as [g _].
fsetdec.
Qed.
Definition FixVar1 : atom.
destruct constants as [_ [_ [f1 _] ] ].
exact f1.
Defined.
Definition FixVar2 : atom.
destruct constants as [_ [_ [_ [f2 _] ] ] ].
exact f2.
Defined.
Definition FixPat : tm := a_App (a_App (a_Fam Fix) (Rho Irrel) a_Bullet) (Rho Rel) (a_Var_f FixVar2).
Definition FixDef : tm := a_App (a_Var_f FixVar2) (Rho Rel)
(a_App (a_App (a_Fam Fix) (Rho Irrel) a_Bullet) (Rho Rel) (a_Var_f FixVar2)).
Definition FixTy : tm := a_Pi Irrel a_Star
(a_Pi Rel (a_Pi Rel (a_Var_b 0) (a_Var_b 1)) (a_Var_b 1)).
Definition toplevel : sig := Fix ~ Ax FixPat FixDef FixTy Rep (Nom :: [Nom]).
(** definitions *)
(* defns JSubRole *)
Inductive SubRole : role -> role -> Prop := (* defn SubRole *)
| NomBot : forall (R:role),
SubRole Nom R
| RepTop : forall (R:role),
SubRole R Rep
| Refl : forall (R:role),
SubRole R R
| Trans : forall (R1 R3 R2:role),
SubRole R1 R2 ->
SubRole R2 R3 ->
SubRole R1 R3.
(* defns JRolePath *)
Inductive RolePath : tm -> roles -> Prop := (* defn RolePath *)
| RolePath_AbsConst : forall (F:const) (Rs:roles) (A:tm),
binds F ( (Cs A Rs) ) toplevel ->
RolePath (a_Fam F) Rs
| RolePath_Const : forall (F:const) (Rs:roles) (p a A:tm) (R1:role),
binds F ( (Ax p a A R1 Rs) ) toplevel ->
RolePath (a_Fam F) Rs
| RolePath_TApp : forall (a:tm) (R1:role) (b:tm) (Rs:roles),
lc_tm b ->
RolePath a ( R1 :: Rs ) ->
RolePath (a_App a (Role R1) b) Rs
| RolePath_App : forall (a b:tm) (Rs:roles),
lc_tm b ->
RolePath a ( Nom :: Rs ) ->
RolePath (a_App a (Rho Rel) b) Rs
| RolePath_IApp : forall (a:tm) (Rs:roles),
RolePath a Rs ->
RolePath (a_App a (Rho Irrel) a_Bullet) Rs
| RolePath_CApp : forall (a:tm) (Rs:roles),
RolePath a Rs ->
RolePath (a_CApp a g_Triv) Rs.
(* defns JAppsPath *)
Inductive AppsPath : role -> tm -> const -> Apps -> Prop := (* defn AppsPath *)
| AppsPath_AbsConst : forall (R:role) (F:const) (A:tm) (Rs:roles),
binds F ( (Cs A Rs) ) toplevel ->
AppsPath R (a_Fam F) F A_nil
| AppsPath_Const : forall (R:role) (F:const) (p a A:tm) (R1:role) (Rs:roles),
binds F ( (Ax p a A R1 Rs) ) toplevel ->
not ( ( SubRole R1 R ) ) ->
AppsPath R (a_Fam F) F A_nil
| AppsPath_App : forall (R:role) (a:tm) (R1:role) (b':tm) (F:const) (Apps5:Apps),
lc_tm b' ->
AppsPath R a F Apps5 ->
AppsPath R ( (a_App a (Role R1) b') ) F ( (A_snoc Apps5 (A_Tm (Role R1)) ) )
| AppsPath_IApp : forall (R:role) (a b:tm) (F:const) (Apps5:Apps),
lc_tm b ->
AppsPath R a F Apps5 ->
AppsPath R ( (a_App a (Rho Irrel) b) ) F ( (A_snoc Apps5 (A_Tm (Rho Irrel)) ) )
| AppsPath_CApp : forall (R:role) (a:tm) (F:const) (Apps5:Apps),
AppsPath R a F Apps5 ->
AppsPath R ( (a_CApp a g_Triv) ) F ( (A_snoc Apps5 A_Co ) ) .
(* defns JSat *)
Inductive AppRoles : Apps -> roles -> Prop := (* defn AppRoles *)
| AR_nil :
AppRoles A_nil nil
| AR_consTApp : forall (R1:role) (Apps5:Apps) (Rs:roles),
AppRoles Apps5 Rs ->
AppRoles (A_cons (A_Tm (Role R1)) Apps5) ( R1 :: Rs )
| AR_consApp : forall (Apps5:Apps) (Rs:roles),
AppRoles Apps5 Rs ->
AppRoles (A_cons (A_Tm (Rho Rel)) Apps5) ( Nom :: Rs )
| AR_consIApp : forall (Apps5:Apps) (Rs:roles),
AppRoles Apps5 Rs ->
AppRoles (A_cons (A_Tm (Rho Irrel)) Apps5) Rs
| AR_consCApp : forall (Apps5:Apps) (Rs:roles),
AppRoles Apps5 Rs ->
AppRoles (A_cons A_Co Apps5) Rs
with SatApp : const -> Apps -> Prop := (* defn SatApp *)
| Sat_Const : forall (F:const) (Apps5:Apps) (A:tm) (Rs:roles),
binds F ( (Cs A Rs) ) toplevel ->
AppRoles Apps5 Rs ->
SatApp F Apps5
| Sat_Axiom : forall (F:const) (Apps5:Apps) (p a0 A1:tm) (R1:role) (Rs:roles),
binds F ( (Ax p a0 A1 R1 Rs) ) toplevel ->
not ( ( SubRole R1 Nom ) ) ->
AppRoles Apps5 Rs ->
SatApp F Apps5.
(* defns JPatCtx *)
Inductive PatternContexts : role_context -> context -> atom_list -> const -> tm -> tm -> tm -> Prop := (* defn PatternContexts *)
| PatCtx_Const : forall (F:const) (A:tm),
lc_tm A ->
PatternContexts nil nil nil F A (a_Fam F) A
| PatCtx_PiRel : forall (L:vars) (W:role_context) (R:role) (G:context) (A':tm) (V:atom_list) (F:const) (B p A:tm),
PatternContexts W G V F B p (a_Pi Rel A' A) ->
( forall x , x \notin L -> PatternContexts (( x ~ R ) ++ W ) (( x ~ Tm A' ) ++ G ) V F B (a_App p (Role R) (a_Var_f x)) ( open_tm_wrt_tm A (a_Var_f x) ) )
| PatCtx_PiIrr : forall (L:vars) (W:role_context) (G:context) (A':tm) (V:atom_list) (F:const) (B p A:tm),
PatternContexts W G V F B p (a_Pi Irrel A' A) ->
( forall x , x \notin L -> PatternContexts W (( x ~ Tm A' ) ++ G ) x :: V F B (a_App p (Rho Irrel) a_Bullet) ( open_tm_wrt_tm A (a_Var_f x) ) )
| PatCtx_CPi : forall (L:vars) (W:role_context) (G:context) (phi:constraint) (V:atom_list) (F:const) (B p A:tm),
PatternContexts W G V F B p (a_CPi phi A) ->
( forall c , c \notin L -> PatternContexts W (( c ~ Co phi ) ++ G ) V F B (a_CApp p g_Triv) ( open_tm_wrt_co A (g_Var_f c) ) ) .
(* defns JRename *)
Inductive Rename : tm -> tm -> tm -> tm -> available_props -> available_props -> Prop := (* defn Rename *)
| Rename_Base : forall (F:const) (a:tm) (D:available_props),
lc_tm a ->
Rename (a_Fam F) a (a_Fam F) a D AtomSetImpl.empty
| Rename_AppRel : forall (p1:tm) (R:role) (x:tmvar) (a1 p2:tm) (y:tmvar) (a2:tm) (D D':available_props),
Rename p1 a1 p2 a2 D D' ->
~ AtomSetImpl.In y ( ( D `union` D' ) ) ->
Rename ( (a_App p1 (Role R) (a_Var_f x)) ) a1 ( (a_App p2 (Role R) (a_Var_f y)) ) ( (tm_subst_tm_tm (a_Var_f y) x a2 ) ) D ( (singleton y \u D' ) )
| Rename_AppIrrel : forall (p1 a1 p2 a2:tm) (D D':available_props),
Rename p1 a1 p2 a2 D D' ->
Rename ( (a_App p1 (Rho Irrel) a_Bullet) ) a1 ( (a_App p2 (Rho Irrel) a_Bullet) ) a2 D D'
| Rename_CApp : forall (p1 a1 p2 a2:tm) (D D':available_props),
Rename p1 a1 p2 a2 D D' ->
Rename ( (a_CApp p1 g_Triv) ) a1 ( (a_CApp p2 g_Triv) ) a2 D D'.
(* defns JMatchSubst *)
Inductive MatchSubst : tm -> tm -> tm -> tm -> Prop := (* defn MatchSubst *)
| MatchSubst_Const : forall (F:const) (b:tm),
lc_tm b ->
MatchSubst (a_Fam F) (a_Fam F) b b
| MatchSubst_AppRelR : forall (a1:tm) (R:role) (a p1:tm) (x:tmvar) (b1 b2:tm),
lc_tm a ->
MatchSubst a1 p1 b1 b2 ->
MatchSubst ( (a_App a1 (Role R) a) ) ( (a_App p1 (Role R) (a_Var_f x)) ) b1 ( (tm_subst_tm_tm a x b2 ) )
| MatchSubst_AppIrrel : forall (a1 a p1 b1 b2:tm),
lc_tm a ->
MatchSubst a1 p1 b1 b2 ->
MatchSubst ( (a_App a1 (Rho Irrel) a) ) ( (a_App p1 (Rho Irrel) a_Bullet) ) b1 b2
| MatchSubst_CApp : forall (a1 a2 b1 b2:tm),
MatchSubst a1 a2 b1 b2 ->
MatchSubst ( (a_CApp a1 g_Triv) ) ( (a_CApp a2 g_Triv) ) b1 b2.
(* defns JIsPattern *)
Inductive Pattern : tm -> Prop := (* defn Pattern *)
| Pattern_Head : forall (F:const),
Pattern (a_Fam F)
| Pattern_Rel : forall (p:tm) (R:role) (a:tm),
lc_tm a ->
Pattern p ->
Pattern ( (a_App p (Role R) a) )
| Pattern_Irrel : forall (p a:tm),
lc_tm a ->
Pattern p ->
Pattern ( (a_App p (Rho Irrel) a) )
| Pattern_Co : forall (p:tm) (g:co),
lc_co g ->
Pattern p ->
Pattern ( (a_CApp p g) ) .
(* defns JSubPat *)
Inductive SubPat : tm -> tm -> Prop := (* defn SubPat *)
| SubPat_Refl : forall (p:tm),
Pattern p ->
SubPat p p
| SubPat_Rel : forall (p' p:tm) (R:role) (x:tmvar),
SubPat p' p ->
SubPat p' ( (a_App p (Role R) (a_Var_f x)) )
| SubPat_Irrel : forall (p' p:tm),
SubPat p' p ->
SubPat p' ( (a_App p (Rho Irrel) a_Bullet) )
| SubPat_Co : forall (p' p:tm),
SubPat p' p ->
SubPat p' ( (a_CApp p g_Triv) ) .
(* defns JTmPatternAgree *)
Inductive tm_pattern_agree : tm -> tm -> Prop := (* defn tm_pattern_agree *)
| tm_pattern_agree_Const : forall (F:const),
tm_pattern_agree (a_Fam F) (a_Fam F)
| tm_pattern_agree_AppRelR : forall (a1:tm) (R:role) (a2 p1:tm) (x:tmvar),
lc_tm a2 ->
tm_pattern_agree a1 p1 ->
tm_pattern_agree ( (a_App a1 (Role R) a2) ) ( (a_App p1 (Role R) (a_Var_f x)) )
| tm_pattern_agree_AppIrrel : forall (a1 a p1:tm),
lc_tm a ->
tm_pattern_agree a1 p1 ->
tm_pattern_agree ( (a_App a1 (Rho Irrel) a) ) ( (a_App p1 (Rho Irrel) a_Bullet) )
| tm_pattern_agree_CApp : forall (a1 p1:tm),
tm_pattern_agree a1 p1 ->
tm_pattern_agree ( (a_CApp a1 g_Triv) ) ( (a_CApp p1 g_Triv) ) .
(* defns JTmSubPatternAgree *)
Inductive tm_subpattern_agree : tm -> tm -> Prop := (* defn tm_subpattern_agree *)
| tm_subpattern_agree_Base : forall (a p:tm),
tm_pattern_agree a p ->
tm_subpattern_agree a p
| tm_subpattern_agree_AppRelR : forall (a p:tm) (R:role) (x:tmvar),
tm_subpattern_agree a p ->
tm_subpattern_agree a ( (a_App p (Role R) (a_Var_f x)) )
| tm_subpattern_agree_AppIrrel : forall (a p:tm),
tm_subpattern_agree a p ->
tm_subpattern_agree a ( (a_App p (Rho Irrel) a_Bullet) )
| tm_subpattern_agree_CAppp : forall (a p:tm),
tm_subpattern_agree a p ->
tm_subpattern_agree a ( (a_CApp p g_Triv) ) .
(* defns JSubTmPatternAgree *)
Inductive subtm_pattern_agree : tm -> tm -> Prop := (* defn subtm_pattern_agree *)
| subtm_pattern_agree_Base : forall (a p:tm),
tm_pattern_agree a p ->
subtm_pattern_agree a p
| subtm_pattern_agree_App : forall (a:tm) (nu:appflag) (a2 p:tm),
lc_tm a2 ->
subtm_pattern_agree a p ->
subtm_pattern_agree (a_App a nu a2) p
| subtm_pattern_agree_CAppp : forall (a p:tm),
subtm_pattern_agree a p ->
subtm_pattern_agree (a_CApp a g_Triv) p.
(* defns JValuePath *)
Inductive ValuePath : tm -> const -> Prop := (* defn ValuePath *)
| ValuePath_AbsConst : forall (F:const) (A:tm) (Rs:roles),
binds F ( (Cs A Rs) ) toplevel ->
ValuePath (a_Fam F) F
| ValuePath_Const : forall (F:const) (p a A:tm) (R1:role) (Rs:roles),
binds F ( (Ax p a A R1 Rs) ) toplevel ->
ValuePath (a_Fam F) F
| ValuePath_App : forall (a:tm) (nu:appflag) (b':tm) (F:const),
lc_tm b' ->
ValuePath a F ->
ValuePath ( (a_App a nu b') ) F
| ValuePath_CApp : forall (a:tm) (F:const),
ValuePath a F ->
ValuePath ( (a_CApp a g_Triv) ) F.
(* defns JCasePath *)
Inductive CasePath : role -> tm -> const -> Prop := (* defn CasePath *)
| CasePath_AbsConst : forall (R:role) (a:tm) (F:const) (A:tm) (Rs:roles),
ValuePath a F ->
binds F ( (Cs A Rs) ) toplevel ->
CasePath R a F
| CasePath_Const : forall (R:role) (a:tm) (F:const) (p b A:tm) (R1:role) (Rs:roles),
ValuePath a F ->
binds F ( (Ax p b A R1 Rs) ) toplevel ->
not ( ( SubRole R1 R ) ) ->
CasePath R a F
| CasePath_UnMatch : forall (R:role) (a:tm) (F:const) (p b A:tm) (R1:role) (Rs:roles),
ValuePath a F ->
binds F ( (Ax p b A R1 Rs) ) toplevel ->
not ( ( subtm_pattern_agree a p ) ) ->
CasePath R a F.
(* defns JApplyArgs *)
Inductive ApplyArgs : tm -> tm -> tm -> Prop := (* defn ApplyArgs *)
| ApplyArgs_Const : forall (F:const) (b:tm),
lc_tm b ->
ApplyArgs (a_Fam F) b b
| ApplyArgs_AppRole : forall (a:tm) (R:role) (a' b b':tm),
lc_tm a' ->
ApplyArgs a b b' ->
ApplyArgs ( (a_App a (Role R) a') ) b ( (a_App b' (Rho Rel) a') )
| ApplyArgs_AppRho : forall (a:tm) (rho:relflag) (a' b b':tm),
lc_tm a' ->
ApplyArgs a b b' ->
ApplyArgs ( (a_App a (Rho rho) a') ) b ( (a_App b' (Rho rho) a') )
| ApplyArgs_CApp : forall (a b b':tm),
ApplyArgs a b b' ->
ApplyArgs (a_CApp a g_Triv) b (a_CApp b' g_Triv).
(* defns JValue *)
Inductive Value : role -> tm -> Prop := (* defn Value *)
| Value_Star : forall (R:role),
Value R a_Star
| Value_Pi : forall (R:role) (rho:relflag) (A B:tm),
lc_tm A ->
lc_tm (a_Pi rho A B) ->
Value R (a_Pi rho A B)
| Value_CPi : forall (R:role) (phi:constraint) (B:tm),
lc_constraint phi ->
lc_tm (a_CPi phi B) ->
Value R (a_CPi phi B)
| Value_AbsRel : forall (R:role) (A a:tm),
lc_tm A ->
lc_tm (a_Abs Rel A a) ->
Value R (a_Abs Rel A a)
| Value_UAbsRel : forall (R:role) (a:tm),
lc_tm (a_UAbs Rel a) ->
Value R (a_UAbs Rel a)
| Value_UAbsIrrel : forall (L:vars) (R:role) (a:tm),
( forall x , x \notin L -> Value R ( open_tm_wrt_tm a (a_Var_f x) ) ) ->
Value R (a_UAbs Irrel a)
| Value_CAbs : forall (R:role) (phi:constraint) (a:tm),
lc_constraint phi ->
lc_tm (a_CAbs phi a) ->
Value R (a_CAbs phi a)
| Value_UCAbs : forall (R:role) (a:tm),
lc_tm (a_UCAbs a) ->
Value R (a_UCAbs a)
| Value_Path : forall (R:role) (a:tm) (F:const),
CasePath R a F ->
Value R a.
(* defns JValueType *)
Inductive value_type : role -> tm -> Prop := (* defn value_type *)
| value_type_Star : forall (R:role),
value_type R a_Star
| value_type_Pi : forall (R:role) (rho:relflag) (A B:tm),
lc_tm A ->
lc_tm (a_Pi rho A B) ->
value_type R (a_Pi rho A B)
| value_type_CPi : forall (R:role) (phi:constraint) (B:tm),
lc_constraint phi ->
lc_tm (a_CPi phi B) ->
value_type R (a_CPi phi B)
| value_type_ValuePath : forall (R:role) (a:tm) (F:const),
CasePath R a F ->
value_type R a.
(* defns Jconsistent *)
Inductive consistent : tm -> tm -> role -> Prop := (* defn consistent *)
| consistent_a_Star : forall (R:role),
consistent a_Star a_Star R
| consistent_a_Pi : forall (rho:relflag) (A1 B1 A2 B2:tm) (R':role),
lc_tm A1 ->
lc_tm (a_Pi rho A1 B1) ->
lc_tm A2 ->
lc_tm (a_Pi rho A2 B2) ->
consistent ( (a_Pi rho A1 B1) ) ( (a_Pi rho A2 B2) ) R'
| consistent_a_CPi : forall (phi1:constraint) (A1:tm) (phi2:constraint) (A2:tm) (R:role),
lc_constraint phi1 ->
lc_tm (a_CPi phi1 A1) ->
lc_constraint phi2 ->
lc_tm (a_CPi phi2 A2) ->
consistent ( (a_CPi phi1 A1) ) ( (a_CPi phi2 A2) ) R
| consistent_a_CasePath : forall (a1 a2:tm) (R:role) (F:const),
CasePath R a1 F ->
CasePath R a2 F ->
consistent a1 a2 R
| consistent_a_Step_R : forall (a b:tm) (R:role),
lc_tm a ->
not ( value_type R b ) ->
consistent a b R
| consistent_a_Step_L : forall (a b:tm) (R:role),
lc_tm b ->
not ( value_type R a ) ->
consistent a b R.
(* defns Jroleing *)
Inductive roleing : role_context -> tm -> role -> Prop := (* defn roleing *)
| role_a_Bullet : forall (W:role_context) (R:role),
uniq W ->
roleing W a_Bullet R
| role_a_Star : forall (W:role_context) (R:role),
uniq W ->
roleing W a_Star R
| role_a_Var : forall (W:role_context) (x:tmvar) (R1 R:role),
uniq W ->
binds x R W ->
SubRole R R1 ->
roleing W (a_Var_f x) R1
| role_a_Abs : forall (L:vars) (W:role_context) (rho:relflag) (a:tm) (R:role),
( forall x , x \notin L -> roleing (( x ~ Nom ) ++ W ) ( open_tm_wrt_tm a (a_Var_f x) ) R ) ->
roleing W ( (a_UAbs rho a) ) R
| role_a_App : forall (W:role_context) (a:tm) (rho:relflag) (b:tm) (R:role),
roleing W a R ->
roleing W b Nom ->
roleing W ( (a_App a (Rho rho) b) ) R
| role_a_TApp : forall (W:role_context) (a:tm) (R1:role) (b:tm) (R:role),
roleing W a R ->
roleing W b (param R1 R ) ->
roleing W (a_App a (Role R1) b) R
| role_a_Pi : forall (L:vars) (W:role_context) (rho:relflag) (A B:tm) (R:role),
roleing W A R ->
( forall x , x \notin L -> roleing (( x ~ Nom ) ++ W ) ( open_tm_wrt_tm B (a_Var_f x) ) R ) ->
roleing W ( (a_Pi rho A B) ) R
| role_a_CPi : forall (L:vars) (W:role_context) (a b A:tm) (R1:role) (B:tm) (R:role),
roleing W a R1 ->
roleing W b R1 ->
roleing W A Rep ->
( forall c , c \notin L -> roleing W ( open_tm_wrt_co B (g_Var_f c) ) R ) ->
roleing W ( (a_CPi (Eq a b A R1) B) ) R
| role_a_CAbs : forall (L:vars) (W:role_context) (b:tm) (R:role),
( forall c , c \notin L -> roleing W ( open_tm_wrt_co b (g_Var_f c) ) R ) ->
roleing W ( (a_UCAbs b) ) R
| role_a_CApp : forall (W:role_context) (a:tm) (R:role),
roleing W a R ->
roleing W ( (a_CApp a g_Triv) ) R
| role_a_Const : forall (W:role_context) (F:const) (R:role) (A:tm) (Rs:roles),
uniq W ->
binds F ( (Cs A Rs) ) toplevel ->
roleing W (a_Fam F) R
| role_a_Fam : forall (W:role_context) (F:const) (R1:role) (p a A:tm) (R:role) (Rs:roles),
uniq W ->
binds F ( (Ax p a A R Rs) ) toplevel ->
roleing W (a_Fam F) R1
| role_a_Pattern : forall (W:role_context) (a:tm) (F:const) (Apps5:Apps) (b1 b2:tm) (R1:role),
roleing W a Nom ->
roleing W b1 R1 ->
roleing W b2 R1 ->
roleing W (a_Pattern Nom a F Apps5 b1 b2) R1.
(* defns JChk *)
Inductive RhoCheck : relflag -> tmvar -> tm -> Prop := (* defn RhoCheck *)
| Rho_Rel : forall (x:tmvar) (A:tm),
True ->
RhoCheck Rel x A
| Rho_IrrRel : forall (x:tmvar) (A:tm),
~ AtomSetImpl.In x (fv_tm_tm_tm A ) ->
RhoCheck Irrel x A.
(* defns Jpar *)
Inductive Par : role_context -> tm -> tm -> role -> Prop := (* defn Par *)
| Par_Refl : forall (W:role_context) (a:tm) (R:role),
roleing W a R ->
Par W a a R
| Par_Beta : forall (W:role_context) (a:tm) (rho:relflag) (b a' b':tm) (R:role),
Par W a ( (a_UAbs rho a') ) R ->
Par W b b' Nom ->
Par W (a_App a (Rho rho) b) (open_tm_wrt_tm a' b' ) R
| Par_App : forall (W:role_context) (a:tm) (nu:appflag) (b a' b':tm) (R:role),
Par W a a' R ->
Par W b b' ( app_role nu R ) ->
Par W (a_App a nu b) (a_App a' nu b') R
| Par_CBeta : forall (W:role_context) (a a':tm) (R:role),
Par W a ( (a_UCAbs a') ) R ->
Par W (a_CApp a g_Triv) (open_tm_wrt_co a' g_Triv ) R
| Par_CApp : forall (W:role_context) (a a':tm) (R:role),
Par W a a' R ->
Par W (a_CApp a g_Triv) (a_CApp a' g_Triv) R
| Par_Abs : forall (L:vars) (W:role_context) (rho:relflag) (a a':tm) (R:role),
( forall x , x \notin L -> Par (( x ~ Nom ) ++ W ) ( open_tm_wrt_tm a (a_Var_f x) ) ( open_tm_wrt_tm a' (a_Var_f x) ) R ) ->
Par W (a_UAbs rho a) (a_UAbs rho a') R
| Par_Pi : forall (L:vars) (W:role_context) (rho:relflag) (A B A' B':tm) (R:role),
Par W A A' R ->
( forall x , x \notin L -> Par (( x ~ Nom ) ++ W ) ( open_tm_wrt_tm B (a_Var_f x) ) ( open_tm_wrt_tm B' (a_Var_f x) ) R ) ->
Par W (a_Pi rho A B) (a_Pi rho A' B') R
| Par_CAbs : forall (L:vars) (W:role_context) (a a':tm) (R:role),
( forall c , c \notin L -> Par W ( open_tm_wrt_co a (g_Var_f c) ) ( open_tm_wrt_co a' (g_Var_f c) ) R ) ->
Par W (a_UCAbs a) (a_UCAbs a') R
| Par_CPi : forall (L:vars) (W:role_context) (a b A:tm) (R1:role) (B a' b' A' B':tm) (R:role),
Par W A A' Rep ->
Par W a a' R1 ->
Par W b b' R1 ->
( forall c , c \notin L -> Par W ( open_tm_wrt_co B (g_Var_f c) ) ( open_tm_wrt_co B' (g_Var_f c) ) R ) ->
Par W (a_CPi (Eq a b A R1) B) (a_CPi (Eq a' b' A' R1) B') R
| Par_AxiomBase : forall (W:role_context) (F:const) (b:tm) (R:role) (A:tm) (R1:role) (Rs:roles),
binds F ( (Ax (a_Fam F) b A R1 Rs) ) toplevel ->
SubRole R1 R ->
uniq W ->
Par W (a_Fam F) b R
| Par_AxiomApp : forall (W:role_context) (a:tm) (nu:appflag) (a1 a2:tm) (R:role) (F:const) (p b A:tm) (R1:role) (Rs:roles) (a' a1' p' b':tm) (D':available_props),
binds F ( (Ax p b A R1 Rs) ) toplevel ->
tm_subpattern_agree a p /\ not ( ( tm_pattern_agree a p ) ) ->
Par W a a' R ->
Par W a1 a1' ( app_role nu R ) ->
Rename p b p' b' ( ( (dom W ) `union` (fv_tm_tm_tm p ) ) ) D' ->
MatchSubst ( (a_App a' nu a1') ) p' b' a2 ->
SubRole R1 R ->
Par W (a_App a nu a1) a2 R
| Par_AxiomCApp : forall (W:role_context) (a a2:tm) (R:role) (F:const) (p b A:tm) (R1:role) (Rs:roles) (a' p' b':tm) (D':available_props),
binds F ( (Ax p b A R1 Rs) ) toplevel ->
tm_subpattern_agree a p /\ not ( ( tm_pattern_agree a p ) ) ->
Par W a a' R ->
Rename p b p' b' ( ( (dom W ) `union` (fv_tm_tm_tm p ) ) ) D' ->
MatchSubst ( (a_CApp a' g_Triv) ) p' b' a2 ->
SubRole R1 R ->
Par W (a_CApp a g_Triv) a2 R
| Par_Pattern : forall (W:role_context) (a:tm) (F:const) (Apps5:Apps) (b1 b2 a' b1' b2':tm) (R0:role),
Par W a a' Nom ->
Par W b1 b1' R0 ->
Par W b2 b2' R0 ->
Par W ( (a_Pattern Nom a F Apps5 b1 b2) ) ( (a_Pattern Nom a' F Apps5 b1' b2') ) R0
| Par_PatternTrue : forall (W:role_context) (a:tm) (F:const) (Apps5:Apps) (b1 b2 b:tm) (R0:role) (a' b1' b2':tm) (Apps':Apps),
Par W a a' Nom ->
Par W b1 b1' R0 ->
Par W b2 b2' R0 ->
AppsPath Nom a' F Apps5 ->
ApplyArgs a' b1' b ->
SatApp F Apps' ->
Par W ( (a_Pattern Nom a F Apps5 b1 b2) ) (a_CApp b g_Triv) R0
| Par_PatternFalse : forall (W:role_context) (a:tm) (F:const) (Apps5:Apps) (b1 b2 b2':tm) (R0:role) (a' b1':tm),
Par W a a' Nom ->
Par W b1 b1' R0 ->
Par W b2 b2' R0 ->
Value Nom a' ->
not ( ( AppsPath Nom a' F Apps5 ) ) ->
Par W ( (a_Pattern Nom a F Apps5 b1 b2) ) b2' R0
with MultiPar : role_context -> tm -> tm -> role -> Prop := (* defn MultiPar *)
| MP_Refl : forall (W:role_context) (a:tm) (R:role),
lc_tm a ->
MultiPar W a a R
| MP_Step : forall (W:role_context) (a a':tm) (R:role) (b:tm),
Par W a b R ->
MultiPar W b a' R ->
MultiPar W a a' R
with joins : role_context -> tm -> tm -> role -> Prop := (* defn joins *)
| join : forall (W:role_context) (a1 a2:tm) (R:role) (b:tm),
MultiPar W a1 b R ->
MultiPar W a2 b R ->
joins W a1 a2 R.
(* defns Jbeta *)
Inductive Beta : tm -> tm -> role -> Prop := (* defn Beta *)
| Beta_AppAbs : forall (rho:relflag) (v b:tm) (R1:role),
lc_tm b ->
Value R1 ( (a_UAbs rho v) ) ->
Beta (a_App ( (a_UAbs rho v) ) (Rho rho) b) (open_tm_wrt_tm v b ) R1
| Beta_CAppCAbs : forall (a':tm) (R:role),
lc_tm (a_UCAbs a') ->
Beta (a_CApp ( (a_UCAbs a') ) g_Triv) (open_tm_wrt_co a' g_Triv ) R
| Beta_Axiom : forall (a b':tm) (R:role) (F:const) (p b A:tm) (R1:role) (Rs:roles) (p1 b1:tm) (D':available_props),
binds F ( (Ax p b A R1 Rs) ) toplevel ->
Rename p b p1 b1 ( ( (fv_tm_tm_tm a ) `union` (fv_tm_tm_tm p ) ) ) D' ->
MatchSubst a p1 b1 b' ->
SubRole R1 R ->
Beta a b' R
| Beta_PatternTrue : forall (a:tm) (F:const) (Apps5:Apps) (b1 b2 b1':tm) (R0:role) (Apps':Apps),
lc_tm b2 ->
AppsPath Nom a F Apps5 ->
ApplyArgs a b1 b1' ->
SatApp F Apps' ->
Beta (a_Pattern Nom a F Apps5 b1 b2) (a_CApp b1' g_Triv) R0
| Beta_PatternFalse : forall (a:tm) (F:const) (Apps5:Apps) (b1 b2:tm) (R0:role),
lc_tm b1 ->
lc_tm b2 ->
Value Nom a ->
not ( ( AppsPath Nom a F Apps5 ) ) ->
Beta (a_Pattern Nom a F Apps5 b1 b2) b2 R0
with reduction_in_one : tm -> tm -> role -> Prop := (* defn reduction_in_one *)
| E_AbsTerm : forall (L:vars) (a a':tm) (R1:role),
( forall x , x \notin L -> reduction_in_one ( open_tm_wrt_tm a (a_Var_f x) ) ( open_tm_wrt_tm a' (a_Var_f x) ) R1 ) ->
reduction_in_one (a_UAbs Irrel a) (a_UAbs Irrel a') R1
| E_AppLeft : forall (a:tm) (nu:appflag) (b a':tm) (R1:role),
lc_tm b ->
reduction_in_one a a' R1 ->
reduction_in_one (a_App a nu b) (a_App a' nu b) R1
| E_CAppLeft : forall (a a':tm) (R:role),
reduction_in_one a a' R ->
reduction_in_one (a_CApp a g_Triv) (a_CApp a' g_Triv) R
| E_Pattern : forall (a:tm) (F:const) (Apps5:Apps) (b1 b2 a':tm) (R0:role),
lc_tm b1 ->
lc_tm b2 ->
reduction_in_one a a' Nom ->
reduction_in_one (a_Pattern Nom a F Apps5 b1 b2) (a_Pattern Nom a' F Apps5 b1 b2) R0
| E_Prim : forall (a b:tm) (R:role),
Beta a b R ->
reduction_in_one a b R
with reduction : tm -> tm -> role -> Prop := (* defn reduction *)
| Equal : forall (a:tm) (R:role),
lc_tm a ->
reduction a a R
| Step : forall (a a':tm) (R:role) (b:tm),
reduction_in_one a b R ->
reduction b a' R ->
reduction a a' R.
(* defns JBranchTyping *)
Inductive BranchTyping : context -> Apps -> role -> tm -> tm -> tm -> pattern_args -> tm -> tm -> tm -> Prop := (* defn BranchTyping *)
| BranchTyping_Base : forall (G:context) (a A b:tm) (pattern_args5:pattern_args) (C1 C2:tm),
lc_tm a ->
lc_tm b ->
lc_tm A ->
uniq G ->
( (open_tm_wrt_co C1 g_Triv ) = C2 ) ->
BranchTyping G A_nil Nom a A b pattern_args5 A (a_CPi ( (Eq a (apply_pattern_args b pattern_args5 ) A Nom) ) C1) C2
| BranchTyping_PiRole : forall (L:vars) (G:context) (R:role) (Apps5:Apps) (a A1 b:tm) (pattern_args5:pattern_args) (A B C C':tm),
( forall x , x \notin L -> BranchTyping (( x ~ Tm A ) ++ G ) Apps5 Nom a A1 b ( pattern_args5 ++ [ (p_Tm (Role R) (a_Var_f x)) ]) ( open_tm_wrt_tm B (a_Var_f x) ) ( open_tm_wrt_tm C (a_Var_f x) ) C' ) ->
BranchTyping G ( (A_cons (A_Tm (Role R)) Apps5) ) Nom a A1 b pattern_args5 (a_Pi Rel A B) (a_Pi Rel A C) C'
| BranchTyping_PiRel : forall (L:vars) (G:context) (Apps5:Apps) (a A1 b:tm) (pattern_args5:pattern_args) (A B C C':tm),
( forall x , x \notin L -> BranchTyping (( x ~ Tm A ) ++ G ) Apps5 Nom a A1 b ( pattern_args5 ++ [ (p_Tm (Rho Rel) (a_Var_f x)) ]) ( open_tm_wrt_tm B (a_Var_f x) ) ( open_tm_wrt_tm C (a_Var_f x) ) C' ) ->
BranchTyping G ( (A_cons (A_Tm (Rho Rel)) Apps5) ) Nom a A1 b pattern_args5 (a_Pi Rel A B) (a_Pi Rel A C) C'
| BranchTyping_PiIrrel : forall (L:vars) (G:context) (Apps5:Apps) (a A1 b:tm) (pattern_args5:pattern_args) (A B C C':tm),
( forall x , x \notin L -> BranchTyping (( x ~ Tm A ) ++ G ) Apps5 Nom a A1 b ( pattern_args5 ++ [ (p_Tm (Rho Irrel) a_Bullet) ]) ( open_tm_wrt_tm B (a_Var_f x) ) ( open_tm_wrt_tm C (a_Var_f x) ) C' ) ->
BranchTyping G ( (A_cons (A_Tm (Rho Irrel)) Apps5) ) Nom a A1 b pattern_args5 (a_Pi Irrel A B) (a_Pi Irrel A C) C'
| BranchTyping_CPi : forall (L:vars) (G:context) (Apps5:Apps) (a A b:tm) (pattern_args5:pattern_args) (phi:constraint) (B C C':tm),
( forall c , c \notin L -> BranchTyping (( c ~ Co phi ) ++ G ) Apps5 Nom a A b ( pattern_args5 ++ [ (p_Co g_Triv) ]) ( open_tm_wrt_co B (g_Var_f c) ) ( open_tm_wrt_co C (g_Var_f c) ) C' ) ->
BranchTyping G ( (A_cons A_Co Apps5) ) Nom a A b pattern_args5 (a_CPi phi B) (a_CPi phi C) C'.
(* defns Jett *)
Inductive PropWff : context -> constraint -> Prop := (* defn PropWff *)
| E_Wff : forall (G:context) (a b A:tm) (R:role),
Typing G a A ->
Typing G b A ->
( Typing G A a_Star ) ->
PropWff G (Eq a b A R)
with Typing : context -> tm -> tm -> Prop := (* defn Typing *)
| E_Star : forall (G:context),
Ctx G ->
Typing G a_Star a_Star
| E_Var : forall (G:context) (x:tmvar) (A:tm),
Ctx G ->
binds x (Tm A ) G ->
Typing G (a_Var_f x) A
| E_Pi : forall (L:vars) (G:context) (rho:relflag) (A B:tm),
( forall x , x \notin L -> Typing (( x ~ Tm A ) ++ G ) ( open_tm_wrt_tm B (a_Var_f x) ) a_Star ) ->
Typing G A a_Star ->
Typing G (a_Pi rho A B) a_Star
| E_Abs : forall (L:vars) (G:context) (rho:relflag) (a A B:tm),
( forall x , x \notin L -> Typing (( x ~ Tm A ) ++ G ) ( open_tm_wrt_tm a (a_Var_f x) ) ( open_tm_wrt_tm B (a_Var_f x) ) ) ->
( Typing G A a_Star ) ->
( forall x , x \notin L -> RhoCheck rho x ( open_tm_wrt_tm a (a_Var_f x) ) ) ->
Typing G (a_UAbs rho a) ( (a_Pi rho A B) )
| E_App : forall (G:context) (b a B A:tm),
Typing G b (a_Pi Rel A B) ->
Typing G a A ->
Typing G (a_App b (Rho Rel) a) (open_tm_wrt_tm B a )
| E_TApp : forall (G:context) (b:tm) (R:role) (a B A:tm) (Rs:roles),
Typing G b (a_Pi Rel A B) ->
Typing G a A ->
RolePath b ( R :: Rs ) ->
Typing G (a_App b (Role R) a) (open_tm_wrt_tm B a )
| E_IApp : forall (G:context) (b B a A:tm),
Typing G b (a_Pi Irrel A B) ->
Typing G a A ->
Typing G (a_App b (Rho Irrel) a_Bullet) (open_tm_wrt_tm B a )
| E_Conv : forall (G:context) (a B A:tm),
Typing G a A ->
DefEq G (dom G ) A B a_Star Rep ->
( Typing G B a_Star ) ->
Typing G a B
| E_CPi : forall (L:vars) (G:context) (phi:constraint) (B:tm),
( forall c , c \notin L -> Typing (( c ~ Co phi ) ++ G ) ( open_tm_wrt_co B (g_Var_f c) ) a_Star ) ->
( PropWff G phi ) ->
Typing G (a_CPi phi B) a_Star
| E_CAbs : forall (L:vars) (G:context) (a:tm) (phi:constraint) (B:tm),
( forall c , c \notin L -> Typing (( c ~ Co phi ) ++ G ) ( open_tm_wrt_co a (g_Var_f c) ) ( open_tm_wrt_co B (g_Var_f c) ) ) ->
( PropWff G phi ) ->
Typing G (a_UCAbs a) (a_CPi phi B)
| E_CApp : forall (G:context) (a1 B1 a b A:tm) (R:role),
Typing G a1 (a_CPi ( (Eq a b A R) ) B1) ->
DefEq G (dom G ) a b A R ->
Typing G (a_CApp a1 g_Triv) (open_tm_wrt_co B1 g_Triv )
| E_Const : forall (G:context) (F:const) (A:tm) (Rs:roles),
Ctx G ->
binds F ( (Cs A Rs) ) toplevel ->
( Typing nil A a_Star ) ->
Typing G (a_Fam F) A
| E_Fam : forall (G:context) (F:const) (A p a:tm) (R1:role) (Rs:roles),
Ctx G ->
binds F ( (Ax p a A R1 Rs) ) toplevel ->
( Typing nil A a_Star ) ->
Typing G (a_Fam F) A
| E_Case : forall (G:context) (a:tm) (F:const) (Apps5:Apps) (b1 b2 C A B A1:tm),
Typing G a A ->
Typing G b1 B ->
Typing G b2 C ->
BranchTyping G Apps5 Nom a A (a_Fam F) nil A1 B C ->
Typing G (a_Fam F) A1 ->
SatApp F Apps5 ->
Typing G (a_Pattern Nom a F Apps5 b1 b2) C
with Iso : context -> available_props -> constraint -> constraint -> Prop := (* defn Iso *)
| E_PropCong : forall (G:context) (D:available_props) (A1 B1 A:tm) (R:role) (A2 B2:tm),
DefEq G D A1 A2 A R ->
DefEq G D B1 B2 A R ->
Iso G D (Eq A1 B1 A R) (Eq A2 B2 A R)
| E_IsoConv : forall (G:context) (D:available_props) (A1 A2 A:tm) (R:role) (B:tm) (R0:role),
DefEq G D A B a_Star R0 ->
PropWff G (Eq A1 A2 A R) ->
PropWff G (Eq A1 A2 B R) ->
Iso G D (Eq A1 A2 A R) (Eq A1 A2 B R)
| E_CPiFst : forall (G:context) (D:available_props) (a1 a2 A:tm) (R1:role) (b1 b2 B:tm) (R2:role) (B1 B2:tm) (R':role),
DefEq G D (a_CPi ( (Eq a1 a2 A R1) ) B1) (a_CPi ( (Eq b1 b2 B R2) ) B2) a_Star R' ->
Iso G D (Eq a1 a2 A R1) (Eq b1 b2 B R2)
with DefEq : context -> available_props -> tm -> tm -> tm -> role -> Prop := (* defn DefEq *)
| E_Assn : forall (G:context) (D:available_props) (a b A:tm) (R:role) (c:covar),
Ctx G ->
binds c (Co ( (Eq a b A R) ) ) G ->
AtomSetImpl.In c D ->
DefEq G D a b A R
| E_Refl : forall (G:context) (D:available_props) (a A:tm) (R:role),
Typing G a A ->
DefEq G D a a A R
| E_Sym : forall (G:context) (D:available_props) (a b A:tm) (R:role),
DefEq G D b a A R ->
DefEq G D a b A R
| E_Trans : forall (G:context) (D:available_props) (a b A:tm) (R:role) (a1:tm),
DefEq G D a a1 A R ->
DefEq G D a1 b A R ->
DefEq G D a b A R
| E_Sub : forall (G:context) (D:available_props) (a b A:tm) (R2 R1:role),
DefEq G D a b A R1 ->
SubRole R1 R2 ->
DefEq G D a b A R2
| E_Beta : forall (G:context) (D:available_props) (a1 a2 B:tm) (R:role),
Typing G a1 B ->
( Typing G a2 B ) ->
Beta a1 a2 R ->
DefEq G D a1 a2 B R
| E_PiCong : forall (L:vars) (G:context) (D:available_props) (rho:relflag) (A1 B1 A2 B2:tm) (R':role),
DefEq G D A1 A2 a_Star R' ->
( forall x , x \notin L -> DefEq (( x ~ Tm A1 ) ++ G ) D ( open_tm_wrt_tm B1 (a_Var_f x) ) ( open_tm_wrt_tm B2 (a_Var_f x) ) a_Star R' ) ->
( Typing G A1 a_Star ) ->
( Typing G (a_Pi rho A1 B1) a_Star ) ->
( Typing G (a_Pi rho A2 B2) a_Star ) ->
DefEq G D ( (a_Pi rho A1 B1) ) ( (a_Pi rho A2 B2) ) a_Star R'
| E_AbsCong : forall (L:vars) (G:context) (D:available_props) (rho:relflag) (b1 b2 A1 B:tm) (R':role),
( forall x , x \notin L -> DefEq (( x ~ Tm A1 ) ++ G ) D ( open_tm_wrt_tm b1 (a_Var_f x) ) ( open_tm_wrt_tm b2 (a_Var_f x) ) ( open_tm_wrt_tm B (a_Var_f x) ) R' ) ->
( Typing G A1 a_Star ) ->
( forall x , x \notin L -> RhoCheck rho x ( open_tm_wrt_tm b1 (a_Var_f x) ) ) ->
( forall x , x \notin L -> RhoCheck rho x ( open_tm_wrt_tm b2 (a_Var_f x) ) ) ->
DefEq G D ( (a_UAbs rho b1) ) ( (a_UAbs rho b2) ) ( (a_Pi rho A1 B) ) R'
| E_AppCong : forall (G:context) (D:available_props) (a1 a2 b1 b2 B:tm) (R':role) (A:tm),
DefEq G D a1 b1 ( (a_Pi Rel A B) ) R' ->
DefEq G D a2 b2 A Nom ->
DefEq G D (a_App a1 (Rho Rel) a2) (a_App b1 (Rho Rel) b2) ( (open_tm_wrt_tm B a2 ) ) R'
| E_TAppCong : forall (G:context) (D:available_props) (a1:tm) (R:role) (a2 b1 b2 B:tm) (R':role) (A:tm) (Rs:roles),
DefEq G D a1 b1 ( (a_Pi Rel A B) ) R' ->
DefEq G D a2 b2 A (param R R' ) ->
RolePath a1 ( R :: Rs ) ->
RolePath b1 ( R :: Rs ) ->
Typing G (a_App b1 (Role R) b2) (open_tm_wrt_tm B a2 ) ->
DefEq G D (a_App a1 (Role R) a2) (a_App b1 (Role R) b2) ( (open_tm_wrt_tm B a2 ) ) R'
| E_IAppCong : forall (G:context) (D:available_props) (a1 b1 B a:tm) (R':role) (A:tm),
DefEq G D a1 b1 ( (a_Pi Irrel A B) ) R' ->
Typing G a A ->
DefEq G D (a_App a1 (Rho Irrel) a_Bullet) (a_App b1 (Rho Irrel) a_Bullet) ( (open_tm_wrt_tm B a ) ) R'
| E_PiFst : forall (G:context) (D:available_props) (A1 A2:tm) (R':role) (rho:relflag) (B1 B2:tm),
DefEq G D (a_Pi rho A1 B1) (a_Pi rho A2 B2) a_Star R' ->
DefEq G D A1 A2 a_Star R'
| E_PiSnd : forall (G:context) (D:available_props) (B1 a1 B2 a2:tm) (R':role) (rho:relflag) (A1 A2:tm),
DefEq G D (a_Pi rho A1 B1) (a_Pi rho A2 B2) a_Star R' ->
DefEq G D a1 a2 A1 Nom ->
DefEq G D (open_tm_wrt_tm B1 a1 ) (open_tm_wrt_tm B2 a2 ) a_Star R'
| E_CPiCong : forall (L:vars) (G:context) (D:available_props) (a1 b1 A1:tm) (R:role) (A a2 b2 A2 B:tm) (R':role),
Iso G D (Eq a1 b1 A1 R) (Eq a2 b2 A2 R) ->
( forall c , c \notin L -> DefEq (( c ~ Co (Eq a1 b1 A1 R) ) ++ G ) D ( open_tm_wrt_co A (g_Var_f c) ) ( open_tm_wrt_co B (g_Var_f c) ) a_Star R' ) ->
( PropWff G (Eq a1 b1 A1 R) ) ->
( Typing G (a_CPi (Eq a1 b1 A1 R) A) a_Star ) ->
( Typing G (a_CPi (Eq a2 b2 A2 R) B) a_Star ) ->
DefEq G D (a_CPi (Eq a1 b1 A1 R) A) (a_CPi (Eq a2 b2 A2 R) B) a_Star R'
| E_CAbsCong : forall (L:vars) (G:context) (D:available_props) (a b:tm) (phi1:constraint) (B:tm) (R:role),
( forall c , c \notin L -> DefEq (( c ~ Co phi1 ) ++ G ) D ( open_tm_wrt_co a (g_Var_f c) ) ( open_tm_wrt_co b (g_Var_f c) ) ( open_tm_wrt_co B (g_Var_f c) ) R ) ->
( PropWff G phi1 ) ->
DefEq G D ( (a_UCAbs a) ) ( (a_UCAbs b) ) (a_CPi phi1 B) R
| E_CAppCong : forall (G:context) (D:available_props) (a1 b1 B:tm) (R':role) (a b A:tm) (R:role),
DefEq G D a1 b1 ( (a_CPi ( (Eq a b A R) ) B) ) R' ->
DefEq G (dom G ) a b A R ->
DefEq G D (a_CApp a1 g_Triv) (a_CApp b1 g_Triv) ( (open_tm_wrt_co B g_Triv ) ) R'
| E_CPiSnd : forall (G:context) (D:available_props) (B1 B2:tm) (R0:role) (a1 a2 A:tm) (R:role) (a1' a2' A':tm) (R':role),
DefEq G D (a_CPi ( (Eq a1 a2 A R) ) B1) (a_CPi ( (Eq a1' a2' A' R') ) B2) a_Star R0 ->
DefEq G (dom G ) a1 a2 A R ->
DefEq G (dom G ) a1' a2' A' R' ->
DefEq G D (open_tm_wrt_co B1 g_Triv ) (open_tm_wrt_co B2 g_Triv ) a_Star R0
| E_Cast : forall (G:context) (D:available_props) (a' b' A':tm) (R':role) (a b A:tm) (R:role),
DefEq G D a b A R ->
Iso G D (Eq a b A R) (Eq a' b' A' R') ->
DefEq G D a' b' A' R'
| E_EqConv : forall (G:context) (D:available_props) (a b B:tm) (R:role) (A:tm),
DefEq G D a b A R ->
DefEq G (dom G ) A B a_Star Rep ->
( Typing G B a_Star ) ->
DefEq G D a b B R
| E_IsoSnd : forall (G:context) (D:available_props) (A A' a b:tm) (R1:role) (a' b':tm),
Iso G D (Eq a b A R1) (Eq a' b' A' R1) ->
DefEq G D A A' a_Star Rep
| E_PatCong : forall (G:context) (D:available_props) (a:tm) (F:const) (Apps5:Apps) (b1 b2 a' b1' b2' C:tm) (R0:role) (A B A1 B':tm),
DefEq G D a a' A Nom ->
DefEq G D b1 b1' B R0 ->
DefEq G D b2 b2' C R0 ->
BranchTyping G Apps5 Nom a A (a_Fam F) nil A1 B C ->
BranchTyping G Apps5 Nom a' A (a_Fam F) nil A1 B' C ->
DefEq G D B B' a_Star Rep ->
SatApp F Apps5 ->
Typing G (a_Fam F) A1 ->
DefEq G D (a_Pattern Nom a F Apps5 b1 b2) (a_Pattern Nom a' F Apps5 b1' b2') C R0
| E_LeftRel : forall (G:context) (D:available_props) (a a' A B:tm) (R' R1:role) (b:tm) (F:const) (b':tm),
CasePath R' ( (a_App a (Role R1) b) ) F ->
CasePath R' ( (a_App a' (Role R1) b') ) F ->
Typing G a (a_Pi Rel A B) ->
Typing G b A ->
Typing G a' (a_Pi Rel A B) ->
Typing G b' A ->
DefEq G D (a_App a (Role R1) b) (a_App a' (Role R1) b') (open_tm_wrt_tm B b ) R' ->
DefEq G (dom G ) (open_tm_wrt_tm B b ) (open_tm_wrt_tm B b' ) a_Star Rep ->
DefEq G D a a' (a_Pi Rel A B) R'
| E_LeftIrrel : forall (G:context) (D:available_props) (a a' A B:tm) (R':role) (F:const) (b b':tm),
CasePath R' ( (a_App a (Rho Irrel) a_Bullet) ) F ->
CasePath R' ( (a_App a' (Rho Irrel) a_Bullet) ) F ->
Typing G a (a_Pi Irrel A B) ->
Typing G b A ->
Typing G a' (a_Pi Irrel A B) ->
Typing G b' A ->
DefEq G D (a_App a (Rho Irrel) a_Bullet) (a_App a' (Rho Irrel) a_Bullet) (open_tm_wrt_tm B b ) R' ->
DefEq G (dom G ) (open_tm_wrt_tm B b ) (open_tm_wrt_tm B b' ) a_Star Rep ->
DefEq G D a a' (a_Pi Irrel A B) R'
| E_Right : forall (G:context) (D:available_props) (b b' A:tm) (R1 R':role) (a:tm) (F:const) (a' B:tm),
CasePath R' ( (a_App a (Role R1) b) ) F ->
CasePath R' ( (a_App a' (Role R1) b') ) F ->
Typing G a (a_Pi Rel A B) ->
Typing G b A ->
Typing G a' (a_Pi Rel A B) ->
Typing G b' A ->
DefEq G D (a_App a (Role R1) b) (a_App a' (Role R1) b') (open_tm_wrt_tm B b ) R' ->
DefEq G (dom G ) (open_tm_wrt_tm B b ) (open_tm_wrt_tm B b' ) a_Star Rep ->
DefEq G D b b' A (param R1 R' )
| E_CLeft : forall (G:context) (D:available_props) (a a' a1 a2 A:tm) (R1:role) (B:tm) (R':role) (F:const),
CasePath R' ( (a_CApp a g_Triv) ) F ->
CasePath R' ( (a_CApp a' g_Triv) ) F ->
Typing G a (a_CPi ( (Eq a1 a2 A R1) ) B) ->
Typing G a' (a_CPi ( (Eq a1 a2 A R1) ) B) ->
DefEq G (dom G ) a1 a2 A (param R1 R' ) ->
DefEq G D (a_CApp a g_Triv) (a_CApp a' g_Triv) (open_tm_wrt_co B g_Triv ) R' ->
DefEq G D a a' (a_CPi ( (Eq a1 a2 A R1) ) B) R'
with Ctx : context -> Prop := (* defn Ctx *)
| E_Empty :
Ctx nil
| E_ConsTm : forall (G:context) (x:tmvar) (A:tm),
Ctx G ->
Typing G A a_Star ->
~ AtomSetImpl.In x (dom G ) ->
Ctx (( x ~ Tm A ) ++ G )
| E_ConsCo : forall (G:context) (c:covar) (phi:constraint),
Ctx G ->
PropWff G phi ->
~ AtomSetImpl.In c (dom G ) ->
Ctx (( c ~ Co phi ) ++ G ) .
(* defns Jsig *)
Inductive Sig : sig -> Prop := (* defn Sig *)
| Sig_Empty :
Sig nil
| Sig_ConsConst : forall (S:sig) (F:const) (A:tm) (Rs:roles),
Sig S ->
Typing nil A a_Star ->
~ AtomSetImpl.In F (dom S ) ->
Sig (( F ~ (Cs A Rs) )++ S )
| Sig_ConsAx : forall (S:sig) (F:const) (p a A:tm) (R:role) (W:role_context) (G:context) (V:atom_list) (B:tm),
Sig S ->
~ AtomSetImpl.In F (dom S ) ->
Typing nil A a_Star ->
PatternContexts W G V F A p B ->
Typing G a B ->
(forall x, In x V -> x `notin` (fv_tm_tm_tm a ) ) ->
roleing W a R ->
Sig (( F ~ (Ax p a A R (range( W )) ) )++ S ) .
(* defns Jhiding *)
Inductive RoleWeaken : roles -> roles -> Prop := (* defn RoleWeaken *)
| R_Nil :
RoleWeaken nil nil
| R_Cons : forall (R1:role) (Rs1:roles) (R2:role) (Rs2:roles),
SubRole R2 R1 ->
RoleWeaken Rs1 Rs2 ->
RoleWeaken ( R1 :: Rs1 ) ( R2 :: Rs2 )
with SigWeaken : sig -> sig -> Prop := (* defn SigWeaken *)
| S_Forget : forall (S1 S2:sig) (F:const) (sig_sort5:sig_sort),
lc_sig_sort sig_sort5 ->
SigWeaken S1 S2 ->
SigWeaken S1 (( F ~ sig_sort5 )++ S2 )
| S_Hide : forall (S1:sig) (F:const) (A:tm) (Rs1:roles) (S2:sig) (p a:tm) (R:role) (Rs2:roles),
lc_tm p ->
lc_tm a ->
lc_tm A ->
SigWeaken S1 S2 ->
RoleWeaken Rs1 Rs2 ->
SigWeaken (( F ~ (Cs A Rs1) )++ S1 ) (( F ~ (Ax p a A R Rs2) )++ S2 )
| S_WeakenConst : forall (S1:sig) (F:const) (A:tm) (Rs1:roles) (S2:sig) (Rs2:roles),
lc_tm A ->
SigWeaken S1 S2 ->
RoleWeaken Rs1 Rs2 ->
SigWeaken (( F ~ (Cs A Rs1) )++ S1 ) (( F ~ (Cs A Rs2) )++ S2 )
| S_WeakenAxiom : forall (S1:sig) (F:const) (p' a A:tm) (R:role) (Rs1:roles) (S2:sig) (p:tm) (Rs2:roles),
lc_tm p' ->
lc_tm p ->
lc_tm a ->
lc_tm A ->
SigWeaken S1 S2 ->
RoleWeaken Rs1 Rs2 ->
SigWeaken (( F ~ (Ax p' a A R Rs1) )++ S1 ) (( F ~ (Ax p a A R Rs2) )++ S2 )
| S_Empty :
SigWeaken nil nil
| S_Same : forall (S1:sig) (F:const) (sig_sort5:sig_sort) (S2:sig),
lc_sig_sort sig_sort5 ->
SigWeaken S1 S2 ->
SigWeaken (( F ~ sig_sort5 )++ S1 ) (( F ~ sig_sort5 )++ S2 ) .
(* defns JSrc *)
Inductive SrcTyping : context -> tm -> tm -> Prop := (* defn SrcTyping *)
| S_Star : forall (G:context),
Ctx G ->
SrcTyping G a_Star a_Star
| S_Var : forall (G:context) (x:tmvar) (A:tm),
Ctx G ->
binds x (Tm A ) G ->
SrcTyping G (a_Var_f x) A
| S_Pi : forall (L:vars) (G:context) (rho:relflag) (A B A':tm),
SrcTyping G A a_Star ->
SrcTrans G A A' a_Star ->
( forall x , x \notin L -> SrcTyping (( x ~ Tm A' ) ++ G ) ( open_tm_wrt_tm B (a_Var_f x) ) a_Star ) ->
SrcTyping G ( (a_Pi rho A B) ) a_Star
| S_Abs : forall (L:vars) (G:context) (a A B:tm),
( forall x , x \notin L -> SrcTyping (( x ~ Tm A ) ++ G ) a ( open_tm_wrt_tm B (a_Var_f x) ) ) ->
SrcTyping G (a_UAbs Rel a ) ( (a_Pi Rel A B) )
| S_IAbs : forall (L:vars) (G:context) (a A B:tm),
( forall x , x \notin L -> SrcTyping (( x ~ Tm A ) ++ G ) a ( open_tm_wrt_tm B (a_Var_f x) ) ) ->
SrcTyping G a ( (a_Pi Irrel A B) )
| S_Conv : forall (G:context) (a B A:tm),
SrcTyping G a A ->
DefEq G (dom G ) A B a_Star Nom ->
SrcTyping G a B
| S_Coerce : forall (G:context) (a B A:tm),
SrcTyping G a A ->
DefEq G (dom G ) A B a_Star Rep ->
SrcTyping G (a_SrcApp a_Coerce a) B
| S_App : forall (G:context) (b a B a' A:tm),
SrcTyping G b (a_Pi Rel A B) ->
SrcTrans G a a' A ->
SrcTyping G (a_SrcApp b a) (open_tm_wrt_tm B a' )
| S_IApp : forall (G:context) (b B a' A:tm),
SrcTyping G b (a_Pi Irrel A B) ->
Typing G a' A ->
SrcTyping G b (open_tm_wrt_tm B a' )
| S_CPi : forall (L:vars) (G:context) (phi:constraint) (B:tm) (phi':constraint),
SrcPropWff G phi phi' ->
( forall c , c \notin L -> SrcTyping (( c ~ Co phi' ) ++ G ) ( open_tm_wrt_co B (g_Var_f c) ) a_Star ) ->
SrcTyping G (a_CPi phi B) a_Star
| S_CAbs : forall (L:vars) (G:context) (a:tm) (phi:constraint) (B:tm) (phi':constraint),
lc_constraint phi ->
( forall c , c \notin L -> SrcTyping (( c ~ Co phi' ) ++ G ) a ( open_tm_wrt_co B (g_Var_f c) ) ) ->
SrcTyping G a (a_CPi phi B)
| S_CApp : forall (G:context) (a1 B1 a b A:tm) (R:role),
SrcTyping G a1 (a_CPi ( (Eq a b A R) ) B1) ->
DefEq G (dom G ) a b A R ->
SrcTyping G a1 (open_tm_wrt_co B1 g_Triv )
| S_Const : forall (G:context) (F:const) (A:tm) (Rs:roles),
Ctx G ->
binds F ( (Cs A Rs) ) toplevel ->
SrcTyping G (a_Fam F) A
| S_Fam : forall (G:context) (F:const) (A:tm),
lc_tm A ->
Ctx G ->
SrcTyping G (a_Fam F) A
| S_Case : forall (G:context) (a:tm) (F:const) (Apps5:Apps) (b1 b2 C A b1' B b2':tm),
lc_tm b1 ->
lc_tm b2 ->
SrcTyping G a A ->
SrcTyping G b1' B ->
SrcTyping G b2' C ->
SrcTyping G (a_Pattern Nom a F Apps5 b1 b2) C
with SrcTrans : context -> tm -> tm -> tm -> Prop := (* defn SrcTrans *)
| ST_Star : forall (G:context),
Ctx G ->
SrcTrans G a_Star a_Star a_Star
| ST_Var : forall (G:context) (x:tmvar) (A:tm),
Ctx G ->
binds x (Tm A ) G ->
SrcTrans G (a_Var_f x) (a_Var_f x) A
| ST_Pi : forall (L:vars) (G:context) (rho:relflag) (A B A' B':tm),
SrcTrans G A A' a_Star ->
( forall x , x \notin L -> SrcTrans (( x ~ Tm A' ) ++ G ) ( open_tm_wrt_tm B (a_Var_f x) ) ( open_tm_wrt_tm B' (a_Var_f x) ) a_Star ) ->
SrcTrans G ( (a_Pi rho A B) ) ( (a_Pi rho A' B') ) a_Star
| ST_Abs : forall (L:vars) (G:context) (a a' A B:tm),
( forall x , x \notin L -> SrcTrans (( x ~ Tm A ) ++ G ) a ( open_tm_wrt_tm a' (a_Var_f x) ) ( open_tm_wrt_tm B (a_Var_f x) ) ) ->
SrcTrans G (a_UAbs Rel a ) (a_UAbs Rel a') ( (a_Pi Rel A B) )
| ST_IAbs : forall (L:vars) (G:context) (a A B a':tm),
( forall x , x \notin L -> SrcTrans (( x ~ Tm A ) ++ G ) ( open_tm_wrt_tm a (a_Var_f x) ) a' ( open_tm_wrt_tm B (a_Var_f x) ) ) ->
( forall x , x \notin L -> ~ AtomSetImpl.In x (fv_tm_tm_tm ( open_tm_wrt_tm a (a_Var_f x) ) ) ) ->
( forall x , x \notin L -> SrcTrans G ( open_tm_wrt_tm a (a_Var_f x) ) (a_UAbs Irrel a) ( (a_Pi Irrel A B) ) )
| ST_App : forall (G:context) (b a b' a' B A:tm),
SrcTrans G b b' (a_Pi Rel A B) ->
SrcTrans G a a' A ->
SrcTrans G (a_SrcApp b a) (a_App b' (Rho Rel) a') (open_tm_wrt_tm B a' )
| ST_TApp : forall (G:context) (b a b':tm) (R:role) (a' B A:tm) (Rs:roles),
SrcTrans G b b' (a_Pi Rel A B) ->
SrcTrans G a a' A ->
RolePath b ( R :: Rs ) ->
SrcTrans G (a_SrcApp b a) (a_App b' (Role R) a') (open_tm_wrt_tm B a )
| ST_IApp : forall (G:context) (b b' B a A:tm),
SrcTrans G b b' (a_Pi Irrel A B) ->
Typing G a A ->
SrcTrans G b (a_App b' (Rho Irrel) a_Bullet) (open_tm_wrt_tm B a )
| ST_Conv : forall (G:context) (a a' B A:tm),
SrcTrans G a a' A ->
DefEq G (dom G ) A B a_Star Nom ->
SrcTrans G a a' B
| ST_Coerce : forall (G:context) (a a' B A:tm),
SrcTrans G a a' A ->
DefEq G (dom G ) A B a_Star Rep ->
SrcTrans G (a_SrcApp a_Coerce a) a' B
| ST_CPi : forall (L:vars) (G:context) (phi:constraint) (B B':tm) (phi':constraint),
SrcPropWff G phi phi' ->
( forall c , c \notin L -> SrcTrans (( c ~ Co phi' ) ++ G ) ( open_tm_wrt_co B (g_Var_f c) ) ( open_tm_wrt_co B' (g_Var_f c) ) a_Star ) ->
SrcTrans G (a_CPi phi B) (a_CPi phi B') a_Star
| ST_CAbs : forall (L:vars) (G:context) (a a':tm) (phi:constraint) (B:tm),
( forall c , c \notin L -> SrcTrans (( c ~ Co phi ) ++ G ) a ( open_tm_wrt_co a' (g_Var_f c) ) ( open_tm_wrt_co B (g_Var_f c) ) ) ->
SrcTrans G a (a_UCAbs a') (a_CPi phi B)
| ST_CApp : forall (G:context) (a1 a1' B1 a b A:tm) (R:role),
SrcTrans G a1 a1' (a_CPi ( (Eq a b A R) ) B1) ->
DefEq G (dom G ) a b A R ->
SrcTrans G a1 (a_CApp a1' g_Triv) (open_tm_wrt_co B1 g_Triv )
| ST_Const : forall (G:context) (F:const) (A:tm) (Rs:roles),
Ctx G ->
binds F ( (Cs A Rs) ) toplevel ->
SrcTrans G (a_Fam F) (a_Fam F) A
| ST_Fam : forall (G:context) (F:const) (A:tm),
lc_tm A ->
Ctx G ->
SrcTrans G (a_Fam F) (a_Fam F) A
| ST_Case : forall (G:context) (a:tm) (F:const) (Apps5:Apps) (b1 b2 a' b1' b2' C A B:tm),
SrcTrans G a a' A ->
SrcTrans G b1 b1' B ->
SrcTrans G b2 b2' C ->
SrcTrans G (a_Pattern Nom a F Apps5 b1 b2) (a_Pattern Nom a' F Apps5 b1' b2') C
with SrcPropWff : context -> constraint -> constraint -> Prop := (* defn SrcPropWff *)
| S_Wff : forall (G:context) (a b A a' b':tm),
SrcTrans G a a' A ->
SrcTrans G b b' A ->
SrcPropWff G ( (Eq a b A Nom) ) ( (Eq a' b' A Nom) ) .
(* defns Jann *)
Inductive AnnPropWff : context -> constraint -> Prop := (* defn AnnPropWff *)
with AnnTyping : context -> tm -> tm -> role -> Prop := (* defn AnnTyping *)
with AnnIso : context -> available_props -> co -> constraint -> constraint -> Prop := (* defn AnnIso *)
with AnnDefEq : context -> available_props -> co -> tm -> tm -> role -> Prop := (* defn AnnDefEq *)
with AnnCtx : context -> Prop := (* defn AnnCtx *).
(* defns Jred *)
Inductive head_reduction : context -> tm -> tm -> role -> Prop := (* defn head_reduction *).
(** infrastructure *)
Hint Constructors SubRole RolePath AppsPath AppRoles SatApp PatternContexts Rename MatchSubst Pattern SubPat tm_pattern_agree tm_subpattern_agree subtm_pattern_agree ValuePath CasePath ApplyArgs Value value_type consistent roleing RhoCheck Par MultiPar joins Beta reduction_in_one reduction BranchTyping PropWff Typing Iso DefEq Ctx Sig RoleWeaken SigWeaken SrcTyping SrcTrans SrcPropWff AnnPropWff AnnTyping AnnIso AnnDefEq AnnCtx head_reduction lc_co lc_brs lc_tm lc_constraint lc_sort lc_sig_sort lc_pattern_arg.
|
CoInductive CoNat : Set :=
| Zero : CoNat
| Succ : CoNat -> CoNat.
CoInductive CoEq : CoNat -> CoNat -> Prop :=
| coeq_base : CoEq Zero Zero
| coeq_next : forall x y, CoEq x y -> CoEq (Succ x) (Succ y).
(* assists with deconstruction in proofs *)
Definition decomp (x : CoNat) : CoNat :=
match x with
| Zero => Zero
| Succ x' => Succ x'
end.
Lemma decomp_eql : forall x, x = decomp x.
intro x. case x. simpl. auto.
intros. simpl. auto.
Defined.
CoFixpoint plus (x: CoNat) (y: CoNat) : CoNat :=
match x with
| Zero => y
| Succ x' => Succ (plus x' y)
end.
Require Import List.
Fixpoint sum (xs:list CoNat) : CoNat :=
match xs with
| nil => Zero
| cons x xs' => plus x (sum xs')
end.
CoInductive CoList : Set :=
| CoNil : CoList
| CoCons : CoNat -> CoList -> CoList.
Definition decompl (xs : CoList) : CoList :=
match xs with
| CoNil => CoNil
| CoCons x' xs' => CoCons x' xs'
end.
Lemma decompl_eql : forall x, x = decompl x.
intro x. case x. simpl. auto.
intros. simpl. auto.
Defined.
(*
CoFixpoint sumlen (xs: CoList) : CoNat :=
match xs with
| CoNil => Zero
| CoCons x' xs' => Succ (plus x' (sumlen xs'))
end.
*)
CoFixpoint f (x : CoNat) (xs : CoList) :=
match x with
| Zero => match xs with
| CoNil => Zero
| CoCons x' xs' => Succ (f x' xs')
end
| Succ x' => Succ (f x' xs)
end.
Definition sumlen (xs : CoList) :=
match xs with
| CoNil => Zero
| CoCons x' xs' => Succ (f x' xs')
end.
CoFixpoint f (x : CoNat) (xs : CoList) :=
match x with
| Zero => match xs with
| CoNil => Zero
| CoCons x' xs' => Succ (f x' xs')
end
| Succ x' => Succ (f x' xs)
end.
Definition sum (xs : List) :=
match xs with
| CoNil => Zero
| CoCons x' xs' => Succ (f x' xs')
end.
Infix "::" := CoCons (at level 60, right associativity).
Lemma test : sumlen (Zero::Zero::(Succ((Succ(Zero))))::CoNil) = Succ(Succ(Succ(Zero))).
Proof.
intros. rewrite (decomp_eql (sumlen (Zero :: Zero :: Succ (Succ Zero) ::CoNil))). simpl.
rewrite (decomp_eql (f Zero (Zero :: Succ (Succ Zero) :: CoNil))). simpl.
rewrite (decomp_eql (f Zero (Succ (Succ Zero) :: CoNil))). simpl.
rewrite (decomp_eql (f (Succ (Succ Zero)) CoNil)). simpl.
rewrite (decomp_eql (f (Succ Zero) CoNil)). simpl.
rewrite (decomp_eql (f Zero CoNil)). simpl.
g = (% x'. (% xs'. (case x' of
| Succ(x') => Succ(((g x') xs'))
| Zero => (f xs'))));
f = (% xs. (case xs of
| Cons(x',xs') => case x' of
| Zero => Succ(f xs')
| Succ(x') => Succ(Succ(g x' xs'))
| Nil => Zero));
|
Formal statement is: proposition Lim_within: "(f \<longlongrightarrow> l) (at a within S) \<longleftrightarrow> (\<forall>e >0. \<exists>d>0. \<forall>x \<in> S. 0 < dist x a \<and> dist x a < d \<longrightarrow> dist (f x) l < e)" Informal statement is: A function $f$ converges to $l$ at $a$ within $S$ if and only if for every $\epsilon > 0$, there exists a $\delta > 0$ such that for all $x \in S$, if $0 < |x - a| < \delta$, then $|f(x) - l| < \epsilon$. |
lemma continuous_ge_on_closure: fixes a::real assumes f: "continuous_on (closure s) f" and x: "x \<in> closure(s)" and xlo: "\<And>x. x \<in> s ==> f(x) \<ge> a" shows "f(x) \<ge> a" |
[STATEMENT]
lemma f_fold_merge: "(\<And>y. y \<in> set xs \<Longrightarrow> f y = f x) \<Longrightarrow> f (fold merge xs x) = f x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>y. y \<in> set xs \<Longrightarrow> f y = f x) \<Longrightarrow> f (fold merge xs x) = f x
[PROOF STEP]
by (induction xs rule: rev_induct) (auto simp: f_merge) |
lemma complete_Int_closed: fixes S :: "'a::metric_space set" assumes "complete S" and "closed t" shows "complete (S \<inter> t)" |
using Random
"""
Arguments:
- `f`: Function to be optimized
- `g`: Gradient function for `f`
- `c`: Constraints function. Evaluates all the constraint equations and return a Vector of values
- `x0`: (Vector) Initial position to start from
- `n`: (Int) Number of evaluations allowed. Remember `g` costs twice of `f`
- `prob`: (String) Name of the problem. So you can use a different strategy for each problem
"""
function optimize(f, g, c, x0, n, prob)
p = squared_sum_penalty_function(c)
x_best, xlist = penalty_method(f, p, x0, n)
return x_best
end
function sum_penalty_function(c)
f = function(x)
ceval = c(x)
sum(ceval[ceval .> 0])
end
return f
end
function squared_sum_penalty_function(c)
f = function(x)
ceval = c(x)
sum(ceval[ceval .> 0].^2)
end
return f
end
function penalty_method(f, p, x, n; ρ=1, γ=2)
numEvalsLeft = n
hj_max_eval = 10;
xlist = Array{Float64}[]
push!(xlist, x)
while numEvalsLeft >= hj_max_eval
x, evalsUsed, feasFound = hooke_jeeves(f, ρ, p, x, hj_max_eval)
push!(xlist, x)
numEvalsLeft = numEvalsLeft - evalsUsed
ρ *= γ
end
return x,xlist
end
function last_feasible_x(currXFeas, x, feasFound, last_x_feas)
if currXFeas
return x
else
if !feasFound
return x
else
return last_x_feas
end
end
end
basis(i, n) = [k == i ? 1.0 : 0.0 for k in 1 : n]
function hooke_jeeves(f, ρ, p, x, maxEval; α=1, γ=0.5)
xf = f(x)
xp = p(x)
y, m = xf + ρ*xp, length(x)
evalsUsed = 1
last_x_feas = x
if xp==0
feasFound = true
currXFeas = true
else
feasFound = false
currXFeas = false
end
while evalsUsed < maxEval
improved = false
for i in 1 : m
x′ = x + α*basis(i, m)
if evalsUsed >= maxEval
return last_feasible_x(currXFeas, x, feasFound, last_x_feas), evalsUsed, feasFound
end
xf′ = f(x′)
xp′ = p(x′)
y′ = xf′ + ρ*xp′
evalsUsed = evalsUsed + 1
if y′ < y
x, y, improved = x′, y′, true
if xp′==0
last_x_feas = x
feasFound = true
currXFeas = true
else
currXFeas = false
end
else
x′ = x - α*basis(i, m)
if evalsUsed >= maxEval
return last_feasible_x(currXFeas, x, feasFound, last_x_feas), evalsUsed, feasFound
end
xf′ = f(x′)
xp′ = p(x′)
y′ = xf′ + ρ*xp′
evalsUsed = evalsUsed + 1
if y′ < y
x, y, improved = x′, y′, true
if xp′==0
last_x_feas = x
feasFound = true
currXFeas = true
else
currXFeas = false
end
end
end
end
if !improved
α *= γ
end
end
return last_x_feas, evalsUsed, feasFound
end
|
On the morning of February 8 , 1861 , Rector and Totten signed an agreement placing the arsenal in the hands of state officials . That afternoon , the citizen militia marched to the arsenal with Governor Rector at its head . All of the federal troops had left at this point , except Totten who had stayed behind to listen to the Governor 's speech and to hand the arsenal over in person .
|
%
% BUS 314: Resourcing New Ventures - A Course Overview
% Section:
%
% Author: Jeffrey Leung
%
\section{}
\label{sec:}
\begin{easylist}
& \textbf{:}
\end{easylist}
\clearpage
|
import torch
from torch import nn
from torch import Tensor
from collections import OrderedDict
import numpy as np
class GetDensity(torch.nn.Module):
def __init__(self,rs,inta,cutoff,nipsin,norbit):
super(GetDensity,self).__init__()
'''
rs: tensor[ntype,nwave] float
inta: tensor[ntype,nwave] float
nipsin: np.array/list int
cutoff: float
'''
self.rs=nn.parameter.Parameter(rs)
self.inta=nn.parameter.Parameter(inta)
self.register_buffer('cutoff', torch.Tensor([cutoff]))
self.register_buffer('nipsin', torch.tensor([nipsin]))
npara=[1]
index_para=torch.tensor([0],dtype=torch.long)
for i in range(1,nipsin):
npara.append(int(3**i))
index_para=torch.cat((index_para,torch.ones((npara[i]),dtype=torch.long)*i))
self.register_buffer('index_para',index_para)
# index_para: Type: longTensor,index_para was used to expand the dim of params
# in nn with para(l)
# will have the form index_para[0,|1,1,1|,2,2,2,2,2,2,2,2,2|...npara[l]..\...]
self.params=nn.parameter.Parameter(torch.ones_like(self.rs))
def gaussian(self,distances,species_):
# Tensor: rs[nwave],inta[nwave]
# Tensor: distances[neighbour*numatom*nbatch,1]
# return: radial[neighbour*numatom*nbatch,nwave]
distances=distances.view(-1,1)
radial=torch.empty((distances.shape[0],self.rs.shape[1]),dtype=distances.dtype,device=distances.device)
for itype in range(self.rs.shape[0]):
mask = (species_ == itype)
ele_index = torch.nonzero(mask).view(-1)
if ele_index.shape[0]>0:
part_radial=torch.exp(-self.inta[itype:itype+1]*torch.square \
(distances.index_select(0,ele_index)-self.rs[itype:itype+1]))
radial.masked_scatter_(mask.view(-1,1),part_radial)
return radial
def cutoff_cosine(self,distances):
# assuming all elements in distances are smaller than cutoff
# return cutoff_cosine[neighbour*numatom*nbatch]
return torch.square(0.5 * torch.cos(distances * (np.pi / self.cutoff)) + 0.5)
def angular(self,dist_vec,f_cut):
# Tensor: dist_vec[neighbour*numatom*nbatch,3]
# return: angular[neighbour*numatom*nbatch,npara[0]+npara[1]+...+npara[ipsin]]
totneighbour=dist_vec.shape[0]
dist_vec=dist_vec.permute(1,0).contiguous()
orbital=f_cut.view(1,-1)
angular=torch.empty(self.index_para.shape[0],totneighbour,dtype=dist_vec.dtype,device=dist_vec.device)
angular[0]=f_cut
num=1
for ipsin in range(1,int(self.nipsin[0])):
orbital=torch.einsum("ji,ki -> jki",orbital,dist_vec).reshape(-1,totneighbour)
angular[num:num+orbital.shape[0]]=orbital
num+=orbital.shape[0]
return angular
def forward(self,cart,neigh_list,shifts,species):
"""
# input cart: coordinates (nbatch*numatom,3)
# input shifts: coordinates shift values (unit cell)
# input numatoms: number of atoms for each configuration
# atom_index: neighbour list indice
# species: indice for element of each atom
"""
numatom=cart.shape[0]
neigh_species=species.index_select(0,neigh_list[1])
selected_cart = cart.index_select(0, neigh_list.view(-1)).view(2, -1, 3)
dist_vec = selected_cart[0] - selected_cart[1]-shifts
distances = torch.linalg.norm(dist_vec,dim=-1)
orbital = torch.einsum("ji,ik -> ijk",self.angular(dist_vec,self.cutoff_cosine(distances)),self.gaussian(distances,neigh_species))
orb_coeff=self.params.index_select(0,species)
density=self.obtain_orb_coeff(0,numatom,orbital,neigh_list,orb_coeff)
return density
def obtain_orb_coeff(self,iteration:int,numatom:int,orbital,neigh_list,orb_coeff):
expandpara=orb_coeff.index_select(0,neigh_list[1])
worbital=torch.einsum("ijk,ik ->ijk", orbital,expandpara)
sum_worbital=torch.zeros((numatom,orbital.shape[1],self.rs.shape[1]),dtype=orb_coeff.dtype,device=orb_coeff.device)
sum_worbital=torch.index_add(sum_worbital,0,neigh_list[0],worbital)
density=torch.zeros(numatom,self.nipsin[0],self.rs.shape[1],dtype=orbital.dtype,device=orbital.device)
density=torch.index_add(density,1,self.index_para,torch.square(sum_worbital)).view(numatom,-1)
return density
|
This internet site contains data about Hobart Sheds Garages Kit Properties. By ticking this box I confirm I wish to get communications and promotional provides from Sheds and Residences. Design and style freedom, to easily make optimum architectural types to suit client demands and nearby developing situations. Our large range of sheds, kit homes and industrial buildings are created from excellent BlueScope Steel and are versatile in style making certain you get the most effective steel developing for your property.
In the back pages of the 1921 Sears Contemporary Properties catalog, you will locate a web page devoted to their garages. Our sheds incorporate structural members created from GALVASPAN® with a minimum of 450MPa cold-rolled sections and our steel framed properties are manufactured from TRUECORE® steel. While secrets of the mattress industry how to save 50 or more we presently do not have a shop on the ground in this location, our nearest Sheds n Houses team can function with you more than the telephone to design and style a steel developing to suit your application.
Quotes can be produced in a matter of minutes, and this will be for a developing that is engineered to suit your property and certified by ShedSafe. Some constructing departments demand therapy to your foundation for termites just before building, but section R202 of the International Residential Code states that steel framing is a termite resistant material”. If it really is a high quality steel building you are looking for your house in Warwick, then get in touch with Sheds n Properties.
We provide only the highest top quality steel structures made from BlueScope Steel. Notice that the reduced left garage is developed to match the Sears Alhambra. Two of the Sears garages” shown under are almost certainly custom-built structures, created (and constructed) just after negotiating your carpet worth the property, and intended to mirror the design components of the existing property. Call 1800 764 764 and to begin the design process for your new steel shed, garage or kit dwelling for your web site in Warwick.
This 1919 specialty catalog was devoted to the kit garages sold by Sears.
This website includes facts about Hobart Sheds Garages Kit Houses. Sheds n Houses is a single of Australia’s leading suppliers of premium BlueScope Steel steel kit buildings, houses, garages and sheds. This indicates we can design and style the finest sheds and steel structures for your site. Sturdy, light-weight: GreenTerraHomes uses 16-18 gauge steel, 30% thicker than most other steel frames in Canadian structures. This 1919 specialty catalog was devoted to the kit garages sold by Sears.
The look of their kit garages had changed pretty a bit by the 1938 Sears Contemporary Homes catalog. This saves time and money, and some trades actually choose to work on steel frames for the reason that they do not have to pack out, or plane off and compensate for warps, twists and knots. Identifying a Sears kit garage” is far a lot more complicated than identifying kit properties, since they are such basic structures.
In the back pages of the 1921 Sears Modern day Residences catalog, you are going to come across a page devoted to their garages. Our sheds incorporate structural members made from GALVASPAN® with a minimum of 450MPa cold-rolled sections and our steel framed homes are manufactured from TRUECORE® steel. Whilst we currently do not have a store on the ground in this region, our nearest Sheds n Properties group can operate with you more than the phone to style a steel constructing to suit your application.
By ticking this box I confirm I wish to receive communications and promotional presents from Sheds and Homes. Design freedom, to simply create optimum architectural types to suit client wants and local developing circumstances. Our big variety of sheds, kit residences and industrial buildings are made from quality BlueScope Steel and are flexible in design and style guaranteeing you get the very best steel constructing for your home.
Strong, light-weight: GreenTerraHomes utilizes 16-18 gauge steel, 30% thicker than most other steel frames in Canadian structures. Notice that the reduce left garage is developed to match the Sears Alhambra. |
The degree of an integer is zero. |
def test_perfect_model():
import numpy as np
from pysad.models import PerfectModel
from pysad.utils import fix_seed
fix_seed(61)
model = PerfectModel()
y1 = np.random.randint(0, 2, 100)
y = np.random.randint(0, 2, 100)
X = np.random.rand(100)
y_pred = model.fit_score(X, y)
print(y_pred)
assert np.all(np.isclose(y, y_pred))
assert not np.all(np.isclose(y1, y_pred))
|
{-# OPTIONS --cubical --no-import-sorts --no-exact-split --safe #-}
module Cubical.Data.NatMinusOne.Base where
open import Cubical.Core.Primitives
open import Cubical.Data.Nat
open import Cubical.Data.Empty
open import Cubical.Data.Int.Base using (ℤ; pos; negsuc; -_)
record ℕ₋₁ : Type₀ where
constructor -1+_
field
n : ℕ
pattern neg1 = -1+ zero
pattern ℕ→ℕ₋₁ n = -1+ (suc n)
1+_ : ℕ₋₁ → ℕ
1+_ (-1+ n) = n
suc₋₁ : ℕ₋₁ → ℕ₋₁
suc₋₁ (-1+ n) = -1+ (suc n)
-- Natural number and negative integer literals for ℕ₋₁
open import Cubical.Data.Nat.Literals public
instance
fromNatℕ₋₁ : FromNat ℕ₋₁
fromNatℕ₋₁ = record { Constraint = λ _ → ⊤ ; fromNat = ℕ→ℕ₋₁ }
instance
negativeℕ₋₁ : Negative ℕ₋₁
negativeℕ₋₁ = record { Constraint = λ { (suc (suc _)) → ⊥ ; _ → ⊤ }
; fromNeg = λ { zero → 0 ; (suc zero) → neg1 } }
|
Anderson is known for films set in the San Fernando Valley with realistically flawed and desperate characters . Among the themes dealt with in Anderson 's films are dysfunctional familial relationships , alienation , surrogate families , regret , loneliness , destiny , the power of forgiveness , and ghosts of the past . Anderson makes frequent use of repetition to build emphasis and thematic consistency . In Boogie Nights , Magnolia , Punch Drunk Love and The Master , the phrase " I didn 't do anything " is used at least once , developing themes of responsibility and denial . Anderson 's films are known for their bold visual style which includes stylistic trademarks such as constantly moving camera , steadicam @-@ based long takes , memorable use of music , and multilayered audiovisual imagery . Anderson also tends to reference the Book of Exodus , either explicitly or subtly , such as in recurring references to Exodus 8 : 2 in Magnolia , which chronicles the plague of frogs , culminating with the literal raining of frogs in the film 's climax , or the title and themes in There Will Be Blood , a phrase that can be found in Exodus 7 : 19 , which details the plague of blood .
|
program gw_params
c
c used to calculate gwflow_coef and gwstor_init parameters for PRMS
c
real qobs(100,366),qn(100,366)
real bQ0(3,100),bQ1(3,100)
real ra(1000),flow,flowlow(100),lowflow
real darea(100)
integer tlow(100),qdate(44000),k,iro,itmx,itmn,ipan,isol
integer gagebeg(100),gageend(100)
integer WY(100),flag(100)
character header*60,input*25,nme*8,abbrev(100)*8
real KK,t,gwflow_coef(100),gwstor_init(100),Q0(100),Q1(100)
real t0(100),t1(100),qmth(100,12)
real base_gwflow(3,100),base_gwstor(3,100)
real X(400),Y(400),qall(44000),baseOBS(44000,3)
integer qnum(44000),numq(100,12),YRbeg(100),YRend(100)
character state(100)*2,name(100)*20,prms_file*20
real QdayMEAN(3,366),QdayNUM(366)
real ppt(100),tmax(100),tmin(100),qdat(100,40000)
real sol(100),pan(100)
integer year(40000),month(40000),day(40000),ngage
c--------------------------------------------------------------------
iro=0
open(59,file='gwflow_params',status='replace')
open(58,file='gwstor_params',status='replace')
open(89,file='gw_params.LUCA',status='replace')
write(89,164)
164 format('abbrev gwflow_coef MIN MAX',
. ' gwstor_init MIN MAX')
c ----------------
close(40)
print *,'Enter name of PRMS input data file>'
read(*,*)prms_file
print *,'PRMS data file is: ',prms_file
open(40,file=prms_file,status='old')
54 read(40,4)header
4 format(a60)
if(header(1:10).eq.'##########')go to 55
if(header(28:33).eq.'runoff')then
print *,header(3:60)
iro=iro+1
abbrev(iro)=header(19:26)
end if
if(header(1:4).eq.'tmax')print *,header
if(header(1:4).eq.'tmin')print *,header
if(header(1:4).eq.'prec')print *,header
if(header(1:4).eq.'solr')print *,header
if(header(1:4).eq.'pan_')print *,header
if(header(1:4).eq.'form')print *,header
if(header(1:4).eq.'runo')print *,header
if(header(1:4).eq.'rain')print *,header
go to 54
55 continue
print *,'Enter # tmax>'
read(*,*)ntmx
print *,'Enter # tmin>'
read(*,*)ntmn
print *,'Enter # precip>'
read(*,*)nppt
print *,'Enter # solrad>'
read(*,*)nsol
print *,'Enter # pan_evap>'
read(*,*)npan
print *,'Enter # runoff>'
read(*,*)ngage
do i=1,ngage
print *,'Gage ',i,' ',abbrev(i),' Enter area (in km**2)>'
read(*,*)darea(i)
end do
do i=1,ngage
print *,'Gage ',i,' ',abbrev(i),' area (km**2)=',darea(i)
gagebeg(i)=0
gageend(i)=0
end do
j=1
56 read(40,*,end=57)year(j),month(j),day(j),i1,i2,i3,
. (tmax(i),i=1,ntmx),
. (tmin(i),i=1,ntmn),
. (ppt(i),i=1,nppt),
. (sol(i),i=1,nsol),
. (pan(i),i=1,npan),
. (qdat(i,j),i=1,ngage)
do i=1,ngage
if(qdat(i,j).gt.0.0)then
if(gagebeg(i).eq.0)gagebeg(i)=j
gageend(i)=j
end if
end do
j=j+1
go to 56
57 idays=j-1
close(40)
do i=1,ngage
i1=gagebeg(i)
i2=gageend(i)
print *,'Gage ',i,' ',abbrev(i),year(i1),month(i1),day(i1),
. ' - ',year(i2),month(i2),day(i2)
end do
c ================
c ===============================================
do ibas=1,ngage
i1=gagebeg(ibas)
i2=gageend(ibas)
print *,'abbrev=',abbrev(ibas)
c ===============================================
do i=1,100
WY(i)=0
YRbeg(i)=0
YRend(i)=0
tlow(i)=-999
flowlow(i)=-999.0
do j=1,366
qobs(i,j)=-999.
qn(i,j)=0.
end do
end do
do i=1,100
do m=1,12
qmth(i,m)=0.0
numq(i,m)=0
end do
end do
do i=1,366
QdayMEAN(1,i)=99999999.
QdayMEAN(2,i)=0.0
QdayMEAN(3,i)=-999.
QdayNUM(i)=0.0
end do
c ================
c drainage area is in km**2 -- convert to ft**2
area=darea(ibas)*10760000.0
c-----------------------------------------------------
c-----------------------------------------------------
c-----------------------------------------------------
ibeg=1001
c
ny=0
n=0
nyr=0
iflag=0
do 11 j=i1,i2
qo=qdat(ibas,j)
iy=year(j)
im=month(j)
nd=day(j)
idate=(im*100)+nd
if(iflag.eq.0)then
if(idate.eq.ibeg)iflag=1
end if
if(iflag.eq.0)go to 11
c
if(qo.lt.0.0)then
print *,abbrev(ibas),iy,im,nd,qo
end if
c
n=n+1
if(idate.eq.ibeg)then
nyr=nyr+1
YRbeg(nyr)=n
ny=0
end if
if(idate.eq.0930)then
YRend(nyr)=n
WY(nyr)=iy
end if
c
if(nyr.eq.0)then
print *,'nyr=0'
stop
end if
c
ny=ny+1
c
if(qo.ge.0.0)then
QdayMEAN(2,ny)=QdayMEAN(2,ny)+qo
if(QdayMEAN(1,ny).gt.qo)QdayMEAN(1,ny)=qo
if(QdayMEAN(3,ny).lt.qo)QdayMEAN(3,ny)=qo
QdayNUM(ny)=QdayNUM(ny)+1.
c
numq(nyr,im)=numq(nyr,im)+1
qmth(nyr,im)=qmth(nyr,im)+qo
end if
c
qobs(nyr,ny)=qo
qn(nyr,ny)=n
qall(n)=qo
qnum(n)=ny
c
qdate(n)=idate+(iy*10000)
c
c ----------------
11 continue
ndays=n
print *,qdate(n),' =final DATE'
c
do i=1,366
QdayMEAN(2,i)=QdayMEAN(2,i)/QdayNUM(i)
end do
c
do n=1,nyr
do m=1,12
qmth(n,m)=qmth(n,m)/float(numq(n,m))
end do
end do
c
c ----------------------------------------------
c sort and find low flow values for year:
do i=1,nyr
n=0
c
do j=20,366
if(qobs(i,j).gt.0.0)then
n=n+1
ra(n)=qobs(i,j)
end if
end do
ny=n
if(ny.gt.30)then
call sort(ny,ra)
flowlow(i)=ra(1)
else
flowlow(i)=-9.8
tlow(i)=0
end if
end do
c
do i=1,nyr
ijk=0
do j=20,366
if(qobs(i,j).eq.flowlow(i))then
tlow(i)=qn(i,j)
ijk=1
c ----------------------------------------
if(j.ge.365)then
print *,'look into next year for low flow'
n=i+1
if(n.gt.nyr)go to 333
q=flowlow(i)
c
do ij=1,100
if(qobs(n,ij).le.0.0)go to 333
if(qobs(n,ij).le.q)then
tlow(i)=qn(n,ij)
q=qobs(n,ij)
else
go to 333
end if
end do
c
333 continue
print *,'#=',ij-1,flowlow(i),(qobs(n,ii),ii=1,ij-1)
end if
c ----------------------------------------
end if
end do
print *,flowlow(i),i
end do
c
c ----------------------------------------------
c get base flow separation using hysep (part) program
DA=darea(ibas)
call PART(qall,ndays,baseOBS,DA)
c
c
c==================================================================
c now go thru each year and find lowest flow (Qlow)
c and count backward until flow is greater than Qlow*2
do i=1,nyr
Q0(i)=-999.9
Q1(i)=-999.9
t0(i)=-999.
t1(i)=-999.
do k=1,3
bQ0(k,i)=-999.
bQ1(k,i)=-999.
end do
gwflow_coef(i)=-999.9
gwstor_init(i)=-999.9
do k=1,3
base_gwflow(k,i)=-999.9
base_gwstor(k,i)=-999.9
end do
end do
c
xcoef=0.0
xinit=0.0
nump=0
c ------------
do 5555 i=1,nyr
n=tlow(i)
Qt=qall(n)
if(Qt.le.0.0)go to 5555
c ------------
num=0
nn=n-100
if(nn.lt.0)nn=1
c look for point where baseflow is no longer increasing
c
do j=n,nn,-1
c
if((baseOBS(j,1)*2.0).lt.baseOBS(j+1,1))go to 444
if((baseOBS(j,2)*2.0).lt.baseOBS(j+1,2))go to 444
if((baseOBS(j,3)*2.0).lt.baseOBS(j+1,3))go to 444
c
if(qall(j).gt.(baseOBS(j,1)*1.65))go to 444
if(qall(j).gt.(baseOBS(j,2)*1.65))go to 444
if(qall(j).gt.(baseOBS(j,3)*1.65))go to 444
c
num=num+1
X(num)=j
Y(num)=qall(j)
end do
444 continue
print *,'num=',num
if(num.lt.15)go to 555
c
MWT=0
NDATA=num
c
call FIT(X,Y,NDATA,MWT,A,B,SIGA,SIGB,CHI2,Q)
c Y = A + BX
c
c now use line to get Qo and Qt
iflag=0
t0(i)=X(num)
t1(i)=X(1)
Q0(i)=A + (B*t0(i))
Q1(i)=A + (B*t1(i))
if(Q0(i).le.0.0)Q0(i)=0.000001
if(Q1(i).le.0.0)Q1(i)=0.000001
c
if(Q1(i).gt.Q0(i))iflag=3
if(iflag.eq.0)then
t = t1(i)-t0(i)+1
KK = (log(Q0(i)/Q1(i)))/(t)
gwflow_coef(i) = KK
xcoef=xcoef+gwflow_coef(i)
Qinches=Q0(i)*(86400.0/area)*12.0
gwstor_init(i) = Qinches/gwflow_coef(i)
xinit=xinit+gwstor_init(i)
nump=nump+1
c now figure out params based on baseflow calc's
n1=X(1)
n0=X(num)
c =================
c =================
do k=1,3
bQ0(k,i)=baseOBS(n0,k)
bQ1(k,i)=baseOBS(n1,k)
nflag=0
c ............................................
if(bQ1(k,i).gt.bQ0(k,i))then
nflag=1
print *,'k=',k
print *,(baseOBS(nn,k),nn=n0,n1)
xx=float(num)/3.0
nx=xx
do nn=1,nx
if(baseOBS(n0+nn,k).gt.bQ1(k,i))then
bQ0(k,i)=baseOBS(n0+nn,k)
t=t-nn
print *,'Found new bQ0 ',k,i,nn
nflag=2
end if
if(nflag.eq.2)go to 543
end do
print *,'never figured it out',num,nx,bQ1(k,i)
543 continue
end if
c ............................................
if(nflag.eq.1)then
base_gwflow(k,i)=-99.
base_gwstor(k,i)=-99.
else
bQ0(k,i)=bQ0(k,i)+0.000011
bQ1(k,i)=bQ1(k,i)+0.00001
base_gwflow(k,i)=(log(bQ0(k,i)/bQ1(k,i)))/(t)
Qinches=bQ0(k,i)*(86400.0/area)*12.0
base_gwstor(k,i)=Qinches/base_gwflow(k,i)
end if
c
end do
c =================
c =================
end if
c =================
c
555 continue
c ------------
5555 continue
c ------------
c
if(nump.gt.0)then
xgwflow=xcoef/float(nump)
xgwstor=xinit/float(nump)
else
print *,'No calc made ',abbrev(ibas)
stop
xgwflow=0.001
xgwstor=1.0
do i=1,nyr
do k=1,3
base_gwflow(k,i)=0.001
base_gwstor(k,i)=1.0
end do
end do
end if
c
c if the baseflow parameters differ greatly from the i
c observed -- don't use that year.
do i=1,nyr
flag(i)=0
do k=1,3
c
if((gwflow_coef(i)*2.0).lt.base_gwflow(k,i))flag(i)=flag(i)+1
if((base_gwflow(k,i)*2.0).lt.gwflow_coef(i))flag(i)=flag(i)+1
c
end do
end do
c
c find the year that is the closest to the mean
c and print the output to a file
c
xdiff=10000.
do i=1,nyr
diff=abs(gwflow_coef(i)-xgwflow)
if(xdiff.gt.diff)then
xdiff=diff
numyr=i
end if
end do
c
c write out the data for chosen year
qmax=0.0
i=numyr
idate=qdate(tlow(i))
nx1=YRbeg(i)
nx2=YRend(i)
if(nx1.lt.0)nx1=1
nn=0
do j=nx1,nx2
nn=nn+1
c write(49,149)abbrev(ibas),j,qall(j),
c . QdayMEAN(1,nn),QdayMEAN(2,nn),QdayMEAN(3,nn),
c . (baseOBS(j,k),k=1,3)
149 format(a5,i5,1x,8(f9.1,1x))
if(qmax.lt.qall(j))qmax=qall(j)
end do
c write(79,139)abbrev(ibas),qmax,gwflow_coef(i),gwstor_init(i),
c . nx1,nx2,idate,WY(i)
139 format('./basinGW-plots.sc ',
. a5,1x,f9.0,1x,f7.4,1x,f7.3,1x,2i6,1x,
. i8,1x,i4)
c
cwrite(69,*)abbrev(ibas),t0(numyr),Q0(numyr)
c write(69,*)abbrev(ibas),t1(numyr),Q1(numyr)
do k=1,3
c write(68,*)abbrev(ibas),k,t0(numyr),bQ0(k,numyr)
c write(68,*)abbrev(ibas),k,t1(numyr),bQ1(k,numyr)
end do
c
xmnGW=0.0
xmaxGW=0.0
xminGW=1.0
xmnST=0.0
xmaxST=0.0
xminST=20.0
nGW=0
nST=0
do i=1,nyr
if(flag(i).lt.3)then
if(gwflow_coef(i).ge.0.0)then
c ----------------------------
write(59,122)abbrev(ibas),WY(i),gwflow_coef(i),
. (base_gwflow(k,i),k=1,3),flag(i)
write(58,122)abbrev(ibas),WY(i),gwstor_init(i),
. (base_gwstor(k,i),k=1,3)
if(gwflow_coef(i).lt.xminGW)xminGW=gwflow_coef(i)
if(gwstor_init(i).lt.xminST)xminST=gwstor_init(i)
xmnGW=xmnGW+gwflow_coef(i)
xmnST=xmnST+gwstor_init(i)
nGW=nGW+1
nST=nST+1
do k=1,3
if(base_gwflow(k,i).ge.0.0)then
if(base_gwflow(k,i).lt.xminGW)
. xminGW=base_gwflow(k,i)
if(base_gwflow(k,i).gt.xmaxGW)xmaxGW=base_gwflow(k,i)
xmnGW=xmnGW+base_gwflow(k,i)
nGW=nGW+1
end if
c
if(base_gwstor(k,i).ge.0.0)then
if(base_gwstor(k,i).lt.xminST)xminST=base_gwstor(k,i)
if(base_gwstor(k,i).gt.xmaxST)xmaxST=base_gwstor(k,i)
xmnST=xmnST+base_gwstor(k,i)
nST=nST+1
end if
end do
c ----------------------------
end if
end if
end do
xmnGW=xmnGW/float(nGW)
xmnST=xmnST/float(nGW)
if(xmaxST.gt.20.0)xmaxST=20.0
write(89,165)abbrev(ibas),xmnGW,xminGW,xmaxGW,
. xmnST,xminST,xmaxST
165 format(a8,1x,6f11.5)
122 format(a8,1x,i4,1x,4(f10.5,1x),i2)
c---------------------------------------
c---------------------------------------
c
end do
close(49)
close(59)
close(69)
c
stop
177 format(i8,1x,12(f7.0,1x))
end
SUBROUTINE sort(N,RA)
real RA(1000)
L=N/2+1
IR=N
10 CONTINUE
IF(L.GT.1)THEN
L=L-1
RRA=RA(L)
ELSE
RRA=RA(IR)
RA(IR)=RA(1)
IR=IR-1
IF(IR.EQ.1)THEN
RA(1)=RRA
RETURN
ENDIF
ENDIF
I=L
J=L+L
20 IF(J.LE.IR)THEN
IF(J.LT.IR)THEN
IF(RA(J).LT.RA(J+1))J=J+1
ENDIF
IF(RRA.LT.RA(J))THEN
RA(I)=RA(J)
I=J
J=J+J
ELSE
J=IR+1
ENDIF
GO TO 20
ENDIF
RA(I)=RRA
GO TO 10
END
c
SUBROUTINE FIT(X,Y,NDATA,MWT,A,B,SIGA,SIGB,CHI2,Q)
real X(400),Y(400),SIG(400)
SX=0.
SY=0.
ST2=0.
B=0.
IF(MWT.NE.0) THEN
SS=0.
DO 11 I=1,NDATA
WT=1./(SIG(I)**2)
SS=SS+WT
SX=SX+X(I)*WT
SY=SY+Y(I)*WT
11 CONTINUE
ELSE
DO 12 I=1,NDATA
SX=SX+X(I)
SY=SY+Y(I)
12 CONTINUE
SS=FLOAT(NDATA)
ENDIF
SXOSS=SX/SS
IF(MWT.NE.0) THEN
DO 13 I=1,NDATA
T=(X(I)-SXOSS)/SIG(I)
ST2=ST2+T*T
B=B+T*Y(I)/SIG(I)
13 CONTINUE
ELSE
DO 14 I=1,NDATA
T=X(I)-SXOSS
ST2=ST2+T*T
B=B+T*Y(I)
14 CONTINUE
ENDIF
B=B/ST2
A=(SY-SX*B)/SS
SIGA=SQRT((1.+SX*SX/(SS*ST2))/SS)
SIGB=SQRT(1./ST2)
CHI2=0.
IF(MWT.EQ.0) THEN
DO 15 I=1,NDATA
CHI2=CHI2+(Y(I)-A-B*X(I))**2
15 CONTINUE
Q=1.
SIGDAT=SQRT(CHI2/(NDATA-2))
SIGA=SIGA*SIGDAT
SIGB=SIGB*SIGDAT
ELSE
DO 16 I=1,NDATA
CHI2=CHI2+((Y(I)-A-B*X(I))/SIG(I))**2
16 CONTINUE
Q=GAMMQ(0.5*(NDATA-2),0.5*CHI2)
ENDIF
RETURN
END
c
FUNCTION GAMMQ(A,X)
IF(X.LT.0..OR.A.LE.0.)stop
IF(X.LT.A+1.)THEN
CALL GSER(GAMSER,A,X,GLN)
GAMMQ=1.-GAMSER
ELSE
CALL GCF(GAMMCF,A,X,GLN)
GAMMQ=GAMMCF
ENDIF
RETURN
END
c
SUBROUTINE GCF(GAMMCF,A,X,GLN)
PARAMETER (ITMAX=100,EPS=3.E-7)
GLN=GAMMLN(A)
GOLD=0.
A0=1.
A1=X
B0=0.
B1=1.
FAC=1.
DO 11 N=1,ITMAX
AN=FLOAT(N)
ANA=AN-A
A0=(A1+A0*ANA)*FAC
B0=(B1+B0*ANA)*FAC
ANF=AN*FAC
A1=X*A0+ANF*A1
B1=X*B0+ANF*B1
IF(A1.NE.0.)THEN
FAC=1./A1
G=B1*FAC
IF(ABS((G-GOLD)/G).LT.EPS)GO TO 1
GOLD=G
ENDIF
11 CONTINUE
print *,'A too large, ITMAX too small'
stop
1 GAMMCF=EXP(-X+A*ALOG(X)-GLN)*G
RETURN
END
c
SUBROUTINE GSER(GAMSER,A,X,GLN)
PARAMETER (ITMAX=100,EPS=3.E-7)
GLN=GAMMLN(A)
IF(X.LE.0.)THEN
IF(X.LT.0.)stop
GAMSER=0.
RETURN
ENDIF
AP=A
SUM=1./A
DEL=SUM
DO 11 N=1,ITMAX
AP=AP+1.
DEL=DEL*X/AP
SUM=SUM+DEL
IF(ABS(DEL).LT.ABS(SUM)*EPS)GO TO 1
11 CONTINUE
print *,'A too large, ITMAX too small'
stop
1 GAMSER=SUM*EXP(-X+A*LOG(X)-GLN)
RETURN
END
c
FUNCTION GAMMLN(XX)
REAL*8 COF(6),STP,HALF,ONE,FPF,X,TMP,SER
DATA COF,STP/76.18009173D0,-86.50532033D0,24.01409822D0,
* -1.231739516D0,.120858003D-2,-.536382D-5,2.50662827465D0/
DATA HALF,ONE,FPF/0.5D0,1.0D0,5.5D0/
X=XX-ONE
TMP=X+FPF
TMP=(X+HALF)*LOG(TMP)-TMP
SER=ONE
DO 11 J=1,6
X=X+ONE
SER=SER+COF(J)/X
11 CONTINUE
GAMMLN=TMP+LOG(STP*SER)
RETURN
END
c
subroutine PART(Q1D,ndays,B1D,DA)
C BY AL RUTLEDGE, USGS 2002 VERSION
c modified by L. Hay March 2003
c
C THIS PROGRAM PERFORMS STREAMFLOW PARTITIONING (A FORM OF HYDROGRAPH
C SEPARATION) USING A DAILY-VALUES RECORD OF STREAMFLOW. THIS AND
C OTHER PROGRAMS ARE DOCUMENTED IN USGS WRIR 98-4148. THIS 2002
C VERSION OF THE PROGRAM READS DAILY-VALUES FROM AN MMS output file
C
real Q1D(44000)
real B1D(44000,3)
INTEGER ITBASE
INTEGER TBASE1
REAL QMININT
CHARACTER*1 ALLGW(44000)
REAL DA
C
C-------------------------- INITIALIZE VARIABLES : -------------------
ICOUNT=ndays
C
DO 11 I=1,44000
ALLGW(I)= ' '
DO 11 IBASE=1,3
B1D(I,IBASE)= -888.0
11 CONTINUE
C
15 FORMAT (1I5,4F11.2,5X,3I4)
C
C
C OBTAIN DRAINAGE AREA(DA), THEN CALCULATE THE REQUIREMENT OF ANTECEDENT
C RECESSION (DA**0.2)
C
c convert DA from km**2 to miles**2
DA=DA*0.3861
C ----DETERMINE THREE INTEGER VALUES FOR THE REQMT. OF ANTEC. RECESSION ----
C -----(ONE THAT IS LESS THAN, AND TWO THAT ARE MORE THAN DA**0.2 )---------
C
TBASE1= INT(DA**0.2)
IF(TBASE1.GT.DA**0.2) THEN
TBASE1=TBASE1-1
END IF
IF(DA**0.2-TBASE1.GT.1.0) THEN
WRITE (*,*) 'PROBLEMS WITH CALCULATION OF REQUIREMENT OF '
WRITE (*,*) 'ANTECEDENT RECESSION. '
GO TO 1500
END IF
C
THRESH= 0.1
C
C -------- REPEAT FOR EACH OF THE 3 VALUES ----------
C -------- FOR THE REQUIREMENT OF ANTECEDENT RECESSION --------------
C
ITBASE= TBASE1-1
DO 500 IBASE=1,3
ITBASE= ITBASE+1
DO 185 I=1,ICOUNT
185 ALLGW(I)= ' '
C
C---DESIGNATE BASEFLOW=STREAMFLOW ON DATES PRECEEDED BY A RECESSION PERIOD ---
C---AND ON DATES OF ZERO STREAMFLOW. SET VARIABLE ALLGW='*' ON THESE DATES.---
C
DO 200 I= ITBASE+1, ICOUNT
INDICAT=1
IBACK= 0
190 IBACK= IBACK + 1
IF(Q1D(I-IBACK).LT.Q1D(I-IBACK+1)) INDICAT=0
IF(IBACK.LT.ITBASE) GO TO 190
IF(INDICAT.EQ.1) THEN
B1D(I,IBASE)= Q1D(I)
ALLGW(I)= '*'
ELSE
B1D(I,IBASE)= -888.0
ALLGW(I)= ' '
END IF
200 CONTINUE
DO 220 I=1,ITBASE
IF(Q1D(I).EQ.0.0) THEN
B1D(I,IBASE)= 0.0
ALLGW(I)= '*'
END IF
220 CONTINUE
C
C ------ DURING THESE RECESSION PERIODS, SET ALLGW = ' ' IF THE DAILY ------
C ---------- DECLINE OF LOG Q EXCEEDS THE THRESHOLD VALUE: -----------------
C
I=1
221 I=I+1
IF (I.EQ.ICOUNT) GO TO 224
IF (ALLGW(I).NE.'*') GO TO 221
IF (ALLGW(I+1).NE.'*') GO TO 221
IF (Q1D(I).EQ.0.0.OR.Q1D(I+1).EQ.0.0) GO TO 221
IF (ALLGW(I+1).NE.'*') GO TO 221
IF(Q1D(I).LT.0.0.OR.Q1D(I+1).LT.0.0) GO TO 221
DIFF= ( LOG(Q1D(I)) - LOG(Q1D(I+1)) ) / 2.3025851
IF (DIFF.GT.THRESH) ALLGW(I)= ' '
IF (I+1.LE.ICOUNT) GO TO 221
224 CONTINUE
225 CONTINUE
C
C ----EXTRAPOLATE BASEFLOW IN THE FIRST FEW DAYS OF THE PERIOD OF INTEREST:----
C
J=0
230 J=J+1
IF(ALLGW(J).EQ.' ') GO TO 230
STARTBF= B1D(J,IBASE)
DO 240 I=1,J
240 B1D(I,IBASE)= STARTBF
C
C ---- EXTRAPOLATE BASEFLOW IN LAST FEW DAYS OF PERIOD OF INTEREST: ----------
C
J=ICOUNT+1
250 J=J-1
IF(ALLGW(J).EQ.' ') GO TO 250
ENDBF= B1D(J,IBASE)
DO 260 I=J,ICOUNT
260 B1D(I,IBASE)= ENDBF
C
C --------- INTERPOLATE DAILY VALUES OF BASEFLOW FOR PERIODS WHEN ----------
C ------------------------- BASEFLOW IS NOT KNOWN: -------------------------
C
C FIND VERY FIRST INCIDENT OF BASEFLOW DATA:
280 CONTINUE
I= 0
290 CONTINUE
I=I + 1
IF(ALLGW(I).EQ.' ') GO TO 290
C NOW THAT A DAILY BASEFLOW IS FOUND, MARCH
C AHEAD TO FIRST GAP IN DATA:
300 CONTINUE
IF(B1D(I,IBASE).EQ.0.0) THEN
BASE1= -999.0
ELSE
IF (B1D(I,IBASE).LT.0.0) THEN
C WRITE (*,*) '(B)ARG OF LOG FUNC<0 AT I=', I
BASE1= -999.0
ELSE
BASE1= LOG(B1D(I,IBASE)) / 2.3025851
END IF
END IF
I= I + 1
IF(I.GT.ICOUNT) GO TO 350
IF(ALLGW(I).NE.' ') GO TO 300
ITSTART= I-1
C
C MARCH THROUGH GAP IN BASEFLOW DATA:
ITIME= 1
320 ITIME= ITIME + 1
IF(ITIME+ITSTART.GT.ICOUNT) GO TO 350
IF(ALLGW(ITSTART+ITIME).EQ.' ') GO TO 320
IDAYS= ITIME-1
T2= ITIME
IF (B1D(I+IDAYS,IBASE).EQ.0.0) THEN
BASE2= -999.0
ELSE
IF(B1D(I+IDAYS,IBASE).LT.0.0) THEN
C WRITE (*,*) '(C)ARG OF LOG FUNC<0 AT I=', I+DAYS
BASE2= -999.0
ELSE
BASE2= LOG(B1D(I+IDAYS,IBASE)) / 2.3025851
END IF
END IF
C
C FILL IN ESTIMATED BASEFLOW DATA:
C
IF(BASE1.EQ.-999.0.OR.BASE2.EQ.-999.0) THEN
DO 330 J=1,IDAYS
B1D(J+ITSTART,IBASE)=0.0
330 CONTINUE
ELSE
DO 340 J=1,IDAYS
T=J
Y= BASE1 + (BASE2-BASE1) * T / T2
B1D(J+ITSTART,IBASE)= 10**Y
340 CONTINUE
END IF
C
I= I + IDAYS
IF(I.LE.ICOUNT) GO TO 300
C
350 CONTINUE
C
C ------ TEST TO FIND OUT IF BASE FLOW EXCEEDS STREAMFLOW ON ANY DAY: -----
C
QLOW=0
DO 395 I=1,ICOUNT
IF(B1D(I,IBASE).GT.Q1D(I)) QLOW=1
395 CONTINUE
IF(QLOW.EQ.0) GO TO 420
C
C ------- IF ANY DAYS EXIST WHEN BASE FLOW > STREAMFLOW AND SF=0, ASSIGN
C ------- BF=SF, THEN RUN THROUGH INTERPOLATION (ABOVE):
C
QLOW2=0
DO 397 I=1,ICOUNT
IF (B1D(I,IBASE).GT.Q1D(I).AND.Q1D(I).EQ.0.0) THEN
QLOW2=1
B1D(I,IBASE)= 0.0
ALLGW(I)= '*'
END IF
397 CONTINUE
IF (QLOW2.EQ.1) GO TO 225
C
C -------- LOCATE INTERVALS OF INTERPOLATED BASEFLOW IN WHICH AT LEAST ------
C -------- ONE BASEFLOW EXCEEDS STREAMFLOW ON THE CORRESPONDING DAY. --------
C -------- LOCATE THE DAY ON THIS INTERVAL OF THE MAXIMUM "BF MINUS SF", ----
C -------- AND ASSIGN BASEFLOW=STREAMFLOW ON THIS DAY. THEN RUN THROUGH -----
C -------- THE INTERPOLATION SCHEME (ABOVE) AGAIN. -------------------------
C
I=0
400 CONTINUE
I=I+1
IF(B1D(I,IBASE).GT.Q1D(I)) THEN
QMININT= Q1D(I)
IF (B1D(I,IBASE).LT.0.0.OR.Q1D(I).LT.0.0) THEN
C WRITE (*,*) '(D)ARG OF LOG FUNC<0 AT I=', I
DELMAX=-999.0
ELSE
DELMAX= LOG(B1D(I,IBASE)) - LOG(Q1D(I))
END IF
ISEARCH= I
IMIN=I
402 CONTINUE
ISEARCH= ISEARCH + 1
IF(ALLGW(ISEARCH).NE.' '.OR.B1D(ISEARCH,IBASE).LE.
$ Q1D(ISEARCH).OR.ISEARCH.GT.ICOUNT) GO TO 405
IF (B1D(ISEARCH,IBASE).LT.0.0.OR.Q1D(ISEARCH).LT.0.0) THEN
C WRITE (*,*) '(E)ARG OF LOG FUNC<0 AT I=', ISEARCH
DEL= -999.0
ELSE
DEL= LOG(B1D(ISEARCH,IBASE)) - LOG(Q1D(ISEARCH))
END IF
IF(DEL.GT.DELMAX) THEN
DELMAX=DEL
QMININT= Q1D(ISEARCH)
IMIN= ISEARCH
END IF
IF(ALLGW(ISEARCH).EQ.' ') GO TO 402
405 CONTINUE
B1D(IMIN,IBASE)= QMININT
ALLGW(IMIN)= '*'
I= ISEARCH+1
END IF
IF(I.LT.ICOUNT) GO TO 400
IF(QLOW.EQ.1) GO TO 225
420 CONTINUE
C
C
C ---------- DETERMINE RANGE OF VALUES FOR STREAMFLOW AND BASEFLOW: ----------
C
QMINPI= Q1D(1)
QMAXPI= Q1D(1)
BMINPI= B1D(1,IBASE)
BMAXPI= B1D(1,IBASE)
DO 470 I=1,ICOUNT
IF(Q1D(I).LT.QMINPI) QMINPI=Q1D(I)
IF(Q1D(I).GT.QMAXPI) QMAXPI=Q1D(I)
IF(B1D(I,IBASE).LT.BMINPI) BMINPI= B1D(I,IBASE)
IF(B1D(I,IBASE).GT.BMAXPI) BMAXPI= B1D(I,IBASE)
470 CONTINUE
C
500 CONTINUE
C
C ------- WRITE DAILY STREAMFLOW AND BASEFLOW FOR ONE OR MORE YEARS: ---
c WRITE (12,*)' BASE FLOW FOR EACH'
c WRITE (12,*)' REQUIREMENT OF '
c WRITE (12,*)' STREAM ANTECEDENT RECESSION '
c WRITE (12,*)' DAY # FLOW #1 #2 #3'
ICNT=0
c DO 840 I=1,ndays
c WRITE (12,15) I,Q1D(I),B1D(I,1),
c $ B1D(I,2), B1D(I,3)
c 840 CONTINUE
845 CONTINUE
1500 CONTINUE
CLOSE (10,STATUS='KEEP')
CLOSE (12,STATUS='KEEP')
CLOSE (13,STATUS='KEEP')
CLOSE (15,STATUS='KEEP')
CLOSE (16,STATUS='KEEP')
RETURN
END
|
theory Unification
imports Main
begin
type_synonym var = nat
datatype 'a expression =
VAR var
| CON 'a "'a expression list"
fun vars :: "'a expression \<Rightarrow> var set" where
"vars (VAR x) = {x}"
| "vars (CON s es) = \<Union> (vars ` set es)"
datatype 'a substitution =
EMPTY
| EXTEND var "'a expression" "'a substitution"
primrec subst\<^sub>e :: "var \<Rightarrow> 'a expression \<Rightarrow> 'a expression \<Rightarrow> 'a expression" where
"subst\<^sub>e x e' (VAR y) = (if x = y then e' else VAR y)"
| "subst\<^sub>e x e' (CON s es) = CON s (map (subst\<^sub>e x e') es)"
primrec subst\<^sub>\<Theta> :: "'a substitution \<Rightarrow> var \<Rightarrow> 'a expression" where
"subst\<^sub>\<Theta> EMPTY x = VAR x"
| "subst\<^sub>\<Theta> (EXTEND y e \<Theta>) x = (if x = y then e else subst\<^sub>e y e (subst\<^sub>\<Theta> \<Theta> x))"
primrec subst\<^sub>e\<^sub>\<Theta> :: "'a substitution \<Rightarrow> 'a expression \<Rightarrow> 'a expression" where
"subst\<^sub>e\<^sub>\<Theta> \<Theta> (VAR x) = subst\<^sub>\<Theta> \<Theta> x"
| "subst\<^sub>e\<^sub>\<Theta> \<Theta> (CON s es) = CON s (map (subst\<^sub>e\<^sub>\<Theta> \<Theta>) es)"
type_synonym 'a equation = "'a expression \<times> 'a expression"
primrec subst\<^sub>e\<^sub>q\<^sub>n :: "var \<Rightarrow> 'a expression \<Rightarrow> 'a equation \<Rightarrow> 'a equation" where
"subst\<^sub>e\<^sub>q\<^sub>n x e' (e\<^sub>1, e\<^sub>2) = (subst\<^sub>e x e' e\<^sub>1, subst\<^sub>e x e' e\<^sub>2)"
primrec subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s :: "var \<Rightarrow> 'a expression \<Rightarrow> 'a equation list \<Rightarrow> 'a equation list" where
"subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s x e' [] = []"
| "subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s x e' (eq # eqs) = subst\<^sub>e\<^sub>q\<^sub>n x e' eq # subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s x e' eqs"
function unify' :: "'a equation list \<Rightarrow> 'a substitution option" where
"unify' [] = Some EMPTY"
| "unify' ((CON s es\<^sub>1, CON t es\<^sub>2) # eqs) = (
if s = t \<and> length es\<^sub>1 = length es\<^sub>2 then unify' (zip es\<^sub>1 es\<^sub>2 @ eqs)
else None)"
| "unify' ((CON s es, VAR x) # eqs) = unify' ((VAR x, CON s es) # eqs)"
| "unify' ((VAR x, t) # eqs) = (
if t = VAR x then unify' eqs
else if x \<in> vars t then None
else case unify' (subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s x t eqs) of
None \<Rightarrow> None
| Some \<Theta> \<Rightarrow> Some (EXTEND x (subst\<^sub>e\<^sub>\<Theta> \<Theta> t) \<Theta>))"
by pat_completeness auto
definition unify :: "'a expression \<Rightarrow> 'a expression \<Rightarrow> 'a substitution option" where
"unify e\<^sub>1 e\<^sub>2 = unify' [(e\<^sub>1, e\<^sub>2)]"
(* unification termination *)
(* useless function, useful induction pattern: expression_complete.induct *)
fun expression_complete :: "'a expression \<Rightarrow> bool" where
"expression_complete (VAR y) = True"
| "expression_complete (CON s []) = True"
| "expression_complete (CON s (e # es)) = (expression_complete e \<and> expression_complete (CON s es))"
(* useless function, useful induction pattern: two_lists.induct *)
fun two_lists :: "'a list \<Rightarrow> 'b list \<Rightarrow> bool" where
"two_lists [] [] = True"
| "two_lists [] (b # bs) = True"
| "two_lists (a # as) [] = True"
| "two_lists (a # as) (b # bs) = two_lists as bs"
fun vars_first :: "'a equation list \<Rightarrow> nat" where
"vars_first [] = 0"
| "vars_first ((VAR x, t) # eqs) = 1"
| "vars_first ((CON s es, t) # eqs) = 2"
primrec cons :: "'a expression \<Rightarrow> nat"
and conss :: "'a expression list \<Rightarrow> nat" where
"cons (VAR x) = 0"
| "cons (CON s es) = Suc (conss es)"
| "conss [] = 0"
| "conss (e # es) = cons e + conss es"
primrec vars\<^sub>e\<^sub>q\<^sub>n :: "'a equation \<Rightarrow> var set" where
"vars\<^sub>e\<^sub>q\<^sub>n (e\<^sub>1, e\<^sub>2) = vars e\<^sub>1 \<union> vars e\<^sub>2"
primrec vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s :: "'a equation list \<Rightarrow> var set" where
"vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s [] = {}"
| "vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s (eq # eqs) = vars\<^sub>e\<^sub>q\<^sub>n eq \<union> vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs"
primrec cons\<^sub>e\<^sub>q\<^sub>n :: "'a equation \<Rightarrow> nat" where
"cons\<^sub>e\<^sub>q\<^sub>n (e\<^sub>1, e\<^sub>2) = cons e\<^sub>1 + cons e\<^sub>2"
primrec cons\<^sub>e\<^sub>q\<^sub>n\<^sub>s :: "'a equation list \<Rightarrow> nat" where
"cons\<^sub>e\<^sub>q\<^sub>n\<^sub>s [] = 0"
| "cons\<^sub>e\<^sub>q\<^sub>n\<^sub>s (eq # eqs) = cons\<^sub>e\<^sub>q\<^sub>n eq + cons\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs"
lemma [simp]: "x \<notin> vars t \<Longrightarrow> vars (subst\<^sub>e x t e) =
(if x \<in> vars e then vars e - {x} \<union> vars t else vars e - {x})"
by (induction e rule: expression_complete.induct) auto
lemma [simp]: "x \<notin> vars e \<Longrightarrow> subst\<^sub>e x t e = e"
by (induction e rule: expression_complete.induct) simp_all
lemma [simp]: "vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s (eqs @ eqs') = vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs \<union> vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs'"
by (induction eqs arbitrary: eqs') auto
lemma [simp]: "length es1 = length es2 \<Longrightarrow> vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s (zip es1 es2) = \<Union> (vars ` set (es1 @ es2))"
by (induction es1 es2 rule: two_lists.induct) auto
lemma [simp]: "cons\<^sub>e\<^sub>q\<^sub>n\<^sub>s (eqs @ eqs') = cons\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs + cons\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs'"
by (induction eqs arbitrary: eqs') auto
lemma [simp]: "length es1 = length es2 \<Longrightarrow> cons\<^sub>e\<^sub>q\<^sub>n\<^sub>s (zip es1 es2) = conss es1 + conss es2"
by (induction es1 es2 rule: two_lists.induct) auto
lemma [simp]: "finite (vars\<^sub>e\<^sub>q\<^sub>n eq)"
by (induction eq) simp_all
lemma [simp]: "finite (vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs)"
by (induction eqs) simp_all
lemma [simp]: "x \<notin> vars t \<Longrightarrow> vars\<^sub>e\<^sub>q\<^sub>n (subst\<^sub>e\<^sub>q\<^sub>n x t eq) =
(if x \<in> vars\<^sub>e\<^sub>q\<^sub>n eq then vars\<^sub>e\<^sub>q\<^sub>n eq - {x} \<union> vars t else vars\<^sub>e\<^sub>q\<^sub>n eq - {x})"
by (induction eq) auto
lemma unfold_vars_subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s: "x \<notin> vars t \<Longrightarrow> vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s (subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s x t eqs) =
(if x \<in> vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs then vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs - {x} \<union> vars t else vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs - {x})"
by (induction eqs) auto
lemma [simp]: "x \<notin> vars t \<Longrightarrow> vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s (subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s x t eqs) \<subset> insert x (vars t \<union> vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs)"
by (auto simp add: unfold_vars_subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s)
lemma [simp]: "x \<notin> vars t \<Longrightarrow>
card (vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s (subst\<^sub>e\<^sub>q\<^sub>n\<^sub>s x t eqs)) < card (insert x (vars t \<union> vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs))"
by (simp add: psubset_card_mono)
lemma [simp]: "card (vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs) < card (insert x (vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs)) \<or>
card (vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs) = card (insert x (vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs))"
by (cases "x \<in> vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s eqs") (simp_all add: insert_absorb)
termination unify'
by (relation "measures [card o vars\<^sub>e\<^sub>q\<^sub>n\<^sub>s, cons\<^sub>e\<^sub>q\<^sub>n\<^sub>s, length, vars_first]") simp_all
end |
%% ppval_extrapVal
% Below is a demonstration of the features of the |ppval_extrapVal| function
%%
clear; close all; clc;
%% Syntax
% |v=ppval_extrapVal(pp,xx,interpLim,extrapVal);|
%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <[email protected]>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
|
/*
MIT License
Copyright (c) 2021 Shunji Uno <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <stdint.h>
#include <math.h>
#include <float.h>
#ifdef MKL
#include <mkl.h>
#ifdef MKL_SBLAS
#include <mkl_spblas.h>
#endif /* MKL_SBLAS */
#else
#include <cblas.h>
#endif /* MKL */
#ifdef SXAT
#include <sblas.h>
#endif
#define DNRM2(N,X) cblas_dnrm2(N,X,1)
#define DDOT(N,X,Y) cblas_ddot(N,X,1,Y,1)
#define MATRIX_TYPE_INDEX0 (0)
#define MATRIX_TYPE_INDEX1 (1)
#define MATRIX_TYPE_ASYMMETRIC (0<<4)
#define MATRIX_TYPE_SYMMETRIC (1<<4)
#define MATRIX_TYPE_LOWER (1<<5)
#define MATRIX_TYPE_UPPER (0)
#define MATRIX_TYPE_UNIT (1<<6)
#define MATRIX_TYPE_NON_UNIT (0)
#define MATRIX_TYPE_CSC (0<<8)
#define MATRIX_TYPE_CSR (1<<8)
#define MATRIX_TYPE_ELLPACK (2<<8)
#define MATRIX_TYPE_JAD (3<<8)
#define MATRIX_TYPE_DCSC (8<<8)
#define MATRIX_TYPE_DCSR (9<<8)
#define MATRIX_TYPE_MASK (0xf<<8)
#define MATRIX_INDEX_TYPE(A) (((A)->flags)&0xf)
#define MATRIX_IS_SYMMETRIC(A) (((A)->flags)&MATRIX_TYPE_SYMMETRIC)
#define MATRIX_IS_LOWER(A) (((A)->flags)&MATRIX_TYPE_LOWER)
#define MATRIX_IS_UNIT(A) (((A)->flags)&MATRIX_TYPE_UNIT)
#define MATRIX_IS_CSC(A) ((((A)->flags)&MATRIX_TYPE_MASK) == MATRIX_TYPE_CSC)
#define MATRIX_IS_CSR(A) ((((A)->flags)&MATRIX_TYPE_MASK) == MATRIX_TYPE_CSR)
#ifdef __cplusplus
extern "C" {
#endif
typedef struct ellpack_info {
int32_t nw;
double* COEF;
int32_t* ICOL;
} ellpack_info_t;
typedef struct jad_info {
int32_t* perm;
int32_t* ptr;
int32_t* index;
double* value;
int32_t maxnzr;
} jad_info_t;
typedef struct Matrix {
int NROWS;
int NNZ;
uint32_t flags;
int* pointers;
int* indice;
double* values;
ellpack_info_t _ellpack;
jad_info_t _jad;
void* info;
#ifdef MKL
sparse_matrix_t hdl;
#endif
#ifdef SXAT
sblas_handle_t hdl;
#endif
#ifdef SSL2
double *w;
int *iw;
#endif
int optimized;
} Matrix_t;
/*
* Generic Matrix operations
*/
void Matrix_init_generic(Matrix_t *A);
void Matrix_free_generic(Matrix_t *A);
int Matrix_optimize_generic(Matrix_t *A);
int Matrix_MV_generic(const Matrix_t *A, const double alpha, const double* x, const double beta, const double* y, double* z);
/*
* Architecture dependent Matrix operations (prototype for override)
*/
void Matrix_init(Matrix_t *A);
void Matrix_free(Matrix_t *A);
int Matrix_optimize(Matrix_t *A);
int Matrix_MV(const Matrix_t *A, const double alpha, const double* x, const double beta, const double* y, double* z);
/*
* Architecture independent functions
*/
void Matrix_setMatrixCSR(Matrix_t *A, const int nrows, const int nnz, const int *aptr,
const int *aind, const double *aval, const uint32_t flags);
Matrix_t* Matrix_duplicate(const Matrix_t* A);
int Matrix_convert_index(Matrix_t* A, int base);
int Matrix_transpose(Matrix_t* A);
int Matrix_extract_symmetric(Matrix_t* A);
int Matrix_create_ellpack(Matrix_t* A);
int Matrix_create_jad(Matrix_t* A);
#ifdef __cplusplus
}
#endif
|
From Coq Require Import ZArith.
Require Import coqutil.Z.Lia.
Require Import coqutil.Z.Lia.
Require Import Coq.Lists.List. Import ListNotations.
Require Import coqutil.Map.Interface coqutil.Map.Properties.
Require Import coqutil.Word.Interface coqutil.Word.Properties.
Require Import riscv.Utility.Monads.
Require Import riscv.Utility.Utility.
Require Import riscv.Spec.Decode.
Require Import riscv.Platform.Memory.
Require Import riscv.Spec.Machine.
Require Import riscv.Platform.RiscvMachine.
Require Import riscv.Platform.MetricRiscvMachine.
Require Import riscv.Platform.MetricLogging.
Require Import riscv.Spec.Primitives.
Require Import riscv.Spec.MetricPrimitives.
Require Import riscv.Platform.Run.
Require Import riscv.Spec.Execute.
Require Import riscv.Proofs.DecodeEncode.
Require Import coqutil.Tactics.Tactics.
Require Import compiler.SeparationLogic.
Require Import bedrock2.ptsto_bytes.
Require Import bedrock2.Scalars.
Require Import riscv.Utility.Encode.
Require Import riscv.Utility.RegisterNames.
Require Import riscv.Proofs.EncodeBound.
Require Import coqutil.Decidable.
Require Import compiler.GoFlatToRiscv.
Require Import riscv.Utility.InstructionCoercions. Local Open Scope ilist_scope.
Require Export coqutil.Word.SimplWordExpr.
Require Import coqutil.Tactics.Simp.
Require Import compiler.DivisibleBy4.
Require Import compiler.ZLemmas.
Import Utility.
Notation Register0 := 0%Z (only parsing).
(* R: evar to be instantiated to goal but with valid_machine replaced by True *)
Ltac replace_valid_machine_by_True R :=
let mach' := fresh "mach'" in
let D := fresh "D" in
let Pm := fresh "Pm" in
intros mach' D V Pm;
match goal with
| H: valid_machine mach' |- context C[valid_machine mach'] =>
let G := context C[True] in
let P := eval pattern mach' in G in
lazymatch P with
| ?F _ => instantiate (R := F)
end
end;
subst R;
clear -V Pm;
cbv beta in *;
simp;
solve [eauto 30].
(* if we have valid_machine for the current machine, and need to prove a
run1 with valid_machine in the postcondition, this tactic can
replace the valid_machine in the postcondition by True *)
Ltac get_run1_valid_for_free :=
let R := fresh "R" in
evar (R: MetricRiscvMachine -> Prop);
eapply run1_get_sane with (P := R);
[ (* valid_machine *)
assumption
| (* the simpler run1 goal, left open *)
idtac
| (* the implication, needs to replace valid_machine by True *)
replace_valid_machine_by_True R
];
subst R.
(* if we have valid_machine for the current machine, and need to prove a
runsTo with valid_machine in the postcondition, this tactic can
replace the valid_machine in the postcondition by True *)
Ltac get_runsTo_valid_for_free :=
let R := fresh "R" in
evar (R: MetricRiscvMachine -> Prop);
eapply runsTo_get_sane with (P := R);
[ (* valid_machine *)
assumption
| (* the simpler runsTo goal, left open *)
idtac
| (* the implication, needs to replace valid_machine by True *)
replace_valid_machine_by_True R
];
subst R.
Section Run.
Context {width} {BW: Bitwidth width} {word: word.word width} {word_ok: word.ok word}.
Context {Registers: map.map Z word}.
Context {mem: map.map word byte}.
Context {mem_ok: map.ok mem}.
Add Ring wring : (word.ring_theory (word := word))
(preprocess [autorewrite with rew_word_morphism],
morphism (word.ring_morph (word := word)),
constants [word_cst]).
Local Notation RiscvMachineL := MetricRiscvMachine.
Context {M: Type -> Type}.
Context {MM: Monad M}.
Context {RVM: RiscvProgram M word}.
Context {PRParams: PrimitivesParams M MetricRiscvMachine}.
Context {PR: MetricPrimitives PRParams}.
Ltac simulate'_step :=
first [ eapply go_loadByte_sep ; simpl; [sidecondition..|]
| eapply go_storeByte_sep; simpl; [sidecondition..|intros]
| eapply go_loadHalf_sep ; simpl; [sidecondition..|]
| eapply go_storeHalf_sep; simpl; [sidecondition..|intros]
| eapply go_loadWord_sep ; simpl; [sidecondition..|]
| eapply go_storeWord_sep; simpl; [sidecondition..|intros]
| eapply go_loadDouble_sep ; simpl; [sidecondition..|]
| eapply go_storeDouble_sep; simpl; [sidecondition..|intros]
| simpl_modu4_0
| simulate_step ].
Ltac simulate' := repeat simulate'_step.
Context (iset: InstructionSet).
Definition run_Jalr0_spec :=
forall (rs1: Z) (oimm12: Z) (initialL: RiscvMachineL) (Exec R Rexec: mem -> Prop)
(dest: word),
(* [verify] (and decode-encode-id) only enforces divisibility by 2 because there could be
compressed instructions, but we don't support them so we require divisibility by 4: *)
oimm12 mod 4 = 0 ->
(word.unsigned dest) mod 4 = 0 ->
(* valid_register almost follows from verify (or decode-encode-id) except for when
the register is Register0 *)
valid_register rs1 ->
map.get initialL.(getRegs) rs1 = Some dest ->
initialL.(getNextPc) = word.add initialL.(getPc) (word.of_Z 4) ->
subset (footpr Exec) (of_list (initialL.(getXAddrs))) ->
iff1 Exec (program iset initialL.(getPc) [[Jalr RegisterNames.zero rs1 oimm12]] * Rexec)%sep ->
(Exec * R)%sep initialL.(getMem) ->
valid_machine initialL ->
mcomp_sat (run1 iset) initialL (fun (finalL: RiscvMachineL) =>
finalL.(getRegs) = initialL.(getRegs) /\
finalL.(getLog) = initialL.(getLog) /\
finalL.(getMem) = initialL.(getMem) /\
finalL.(getXAddrs) = initialL.(getXAddrs) /\
finalL.(getPc) = word.add dest (word.of_Z oimm12) /\
finalL.(getNextPc) = word.add finalL.(getPc) (word.of_Z 4) /\
finalL.(getMetrics) = addMetricInstructions 1 (addMetricJumps 1 (addMetricLoads 1 initialL.(getMetrics))) /\
valid_machine finalL).
Definition run_Jal_spec :=
forall (rd: Z) (jimm20: Z) (initialL: RiscvMachineL) (Exec R Rexec: mem -> Prop),
jimm20 mod 4 = 0 ->
valid_register rd ->
initialL.(getNextPc) = word.add initialL.(getPc) (word.of_Z 4) ->
subset (footpr Exec) (of_list (initialL.(getXAddrs))) ->
iff1 Exec (program iset initialL.(getPc) [[Jal rd jimm20]] * Rexec)%sep ->
(Exec * R)%sep initialL.(getMem) ->
valid_machine initialL ->
mcomp_sat (run1 iset) initialL (fun finalL =>
finalL.(getRegs) = map.put initialL.(getRegs) rd initialL.(getNextPc) /\
finalL.(getLog) = initialL.(getLog) /\
finalL.(getMem) = initialL.(getMem) /\
finalL.(getXAddrs) = initialL.(getXAddrs) /\
finalL.(getPc) = word.add initialL.(getPc) (word.of_Z jimm20) /\
finalL.(getNextPc) = word.add finalL.(getPc) (word.of_Z 4) /\
finalL.(getMetrics) = addMetricInstructions 1 (addMetricJumps 1 (addMetricLoads 1 initialL.(getMetrics))) /\
valid_machine finalL).
Definition run_Jal0_spec :=
forall (jimm20: Z) (initialL: RiscvMachineL) (Exec R Rexec: mem -> Prop),
jimm20 mod 4 = 0 ->
subset (footpr Exec) (of_list (initialL.(getXAddrs))) ->
iff1 Exec (program iset initialL.(getPc) [[Jal Register0 jimm20]] * Rexec)%sep ->
(Exec * R)%sep initialL.(getMem) ->
valid_machine initialL ->
mcomp_sat (run1 iset) initialL (fun finalL =>
finalL.(getRegs) = initialL.(getRegs) /\
finalL.(getLog) = initialL.(getLog) /\
finalL.(getMem) = initialL.(getMem) /\
finalL.(getXAddrs) = initialL.(getXAddrs) /\
finalL.(getPc) = word.add initialL.(getPc) (word.of_Z jimm20) /\
finalL.(getNextPc) = word.add finalL.(getPc) (word.of_Z 4) /\
finalL.(getMetrics) = addMetricInstructions 1 (addMetricJumps 1 (addMetricLoads 1 initialL.(getMetrics))) /\
valid_machine finalL).
Definition run_ImmReg_spec(Op: Z -> Z -> Z -> Instruction)
(f: word -> word -> word): Prop :=
forall (rd rs: Z) rs_val imm (initialL: RiscvMachineL) (Exec R Rexec: mem -> Prop),
valid_register rd ->
valid_register rs ->
initialL.(getNextPc) = word.add initialL.(getPc) (word.of_Z 4) ->
map.get initialL.(getRegs) rs = Some rs_val ->
subset (footpr Exec) (of_list (initialL.(getXAddrs))) ->
iff1 Exec (program iset initialL.(getPc) [[Op rd rs imm]] * Rexec)%sep ->
(Exec * R)%sep initialL.(getMem) ->
valid_machine initialL ->
mcomp_sat (run1 iset) initialL (fun finalL =>
finalL.(getRegs) = map.put initialL.(getRegs) rd (f rs_val (word.of_Z imm)) /\
finalL.(getLog) = initialL.(getLog) /\
finalL.(getMem) = initialL.(getMem) /\
finalL.(getXAddrs) = initialL.(getXAddrs) /\
finalL.(getPc) = initialL.(getNextPc) /\
finalL.(getNextPc) = word.add finalL.(getPc) (word.of_Z 4) /\
finalL.(getMetrics) = addMetricInstructions 1 (addMetricLoads 1 initialL.(getMetrics)) /\
valid_machine finalL).
Definition run_Load_spec(n: nat)(L: Z -> Z -> Z -> Instruction)
(opt_sign_extender: Z -> Z): Prop :=
forall (base addr: word) (v: HList.tuple byte n) (rd rs: Z) (ofs: Z)
(initialL: RiscvMachineL) (Exec R Rexec: mem -> Prop),
(* valid_register almost follows from verify except for when the register is Register0 *)
valid_register rd ->
valid_register rs ->
initialL.(getNextPc) = word.add initialL.(getPc) (word.of_Z 4) ->
map.get initialL.(getRegs) rs = Some base ->
addr = word.add base (word.of_Z ofs) ->
subset (footpr Exec) (of_list (initialL.(getXAddrs))) ->
iff1 Exec (program iset initialL.(getPc) [[L rd rs ofs]] * Rexec)%sep ->
(Exec * ptsto_bytes n addr v * R)%sep initialL.(getMem) ->
valid_machine initialL ->
mcomp_sat (run1 iset) initialL (fun finalL =>
finalL.(getRegs) = map.put initialL.(getRegs) rd
(word.of_Z (opt_sign_extender (LittleEndian.combine n v))) /\
finalL.(getLog) = initialL.(getLog) /\
finalL.(getMem) = initialL.(getMem) /\
finalL.(getXAddrs) = initialL.(getXAddrs) /\
finalL.(getPc) = initialL.(getNextPc) /\
finalL.(getNextPc) = word.add finalL.(getPc) (word.of_Z 4) /\
finalL.(getMetrics) = addMetricInstructions 1 (addMetricLoads 2 initialL.(getMetrics)) /\
valid_machine finalL).
Definition run_Store_spec(n: nat)(S: Z -> Z -> Z -> Instruction): Prop :=
forall (base addr v_new: word) (v_old: HList.tuple byte n) (rs1 rs2: Z)
(ofs: Z) (initialL: RiscvMachineL) (Exec R Rexec: mem -> Prop),
(* valid_register almost follows from verify except for when the register is Register0 *)
valid_register rs1 ->
valid_register rs2 ->
initialL.(getNextPc) = word.add initialL.(getPc) (word.of_Z 4) ->
map.get initialL.(getRegs) rs1 = Some base ->
map.get initialL.(getRegs) rs2 = Some v_new ->
addr = word.add base (word.of_Z ofs) ->
subset (footpr Exec) (of_list (initialL.(getXAddrs))) ->
iff1 Exec (program iset initialL.(getPc) [[S rs1 rs2 ofs]] * Rexec)%sep ->
(Exec * ptsto_bytes n addr v_old * R)%sep initialL.(getMem) ->
valid_machine initialL ->
mcomp_sat (run1 iset) initialL (fun finalL =>
finalL.(getRegs) = initialL.(getRegs) /\
finalL.(getLog) = initialL.(getLog) /\
subset (footpr Exec) (of_list (finalL.(getXAddrs))) /\
(Exec * ptsto_bytes n addr (LittleEndian.split n (word.unsigned v_new)) * R)%sep
finalL.(getMem) /\
finalL.(getPc) = initialL.(getNextPc) /\
finalL.(getNextPc) = word.add finalL.(getPc) (word.of_Z 4) /\
finalL.(getMetrics) = addMetricInstructions 1 (addMetricStores 1 (addMetricLoads 1 initialL.(getMetrics))) /\
valid_machine finalL).
Ltac inline_iff1 :=
match goal with
| H: iff1 ?x _ |- _ => is_var x; apply iff1ToEq in H; subst x
end.
Ltac t0 :=
match goal with
| initialL: RiscvMachineL |- _ => destruct_RiscvMachine initialL
end;
simpl in *; subst;
simulate';
simpl;
repeat match goal with
| |- _ /\ _ => split
| |- _ => solve [auto]
| |- _ => ecancel_assumption
| |- _ => solve_MetricLog
end.
Ltac t := repeat intro; inline_iff1; get_run1_valid_for_free; t0.
Lemma run_Jalr0: run_Jalr0_spec.
Proof.
repeat intro.
inline_iff1.
get_run1_valid_for_free.
match goal with
| H: (?P * ?Q * ?R)%sep ?m |- _ =>
assert ((P * (Q * R))%sep m) as A by ecancel_assumption
end.
destruct (invert_ptsto_program1 iset A) as (DE & ?). clear A.
(* execution of Jalr clears lowest bit *)
assert (word.and (word.add dest (word.of_Z oimm12))
(word.xor (word.of_Z 1) (word.of_Z (2 ^ width - 1))) =
word.add dest (word.of_Z oimm12)) as A. {
assert (word.unsigned (word.add dest (word.of_Z oimm12)) mod 4 = 0) as C by
solve_divisibleBy4.
generalize dependent (word.add dest (word.of_Z oimm12)). clear -BW word_ok.
intros.
apply word.unsigned_inj.
rewrite word.unsigned_and, word.unsigned_xor, !word.unsigned_of_Z. unfold word.wrap.
assert (0 <= width) by (destruct width_cases as [E | E]; rewrite E; blia).
replace (2 ^ width - 1) with (Z.ones width); cycle 1. {
rewrite Z.ones_equiv. reflexivity.
}
change 1 with (Z.ones 1).
transitivity (word.unsigned r mod (2 ^ width)); cycle 1. {
rewrite word.wrap_unsigned. reflexivity.
}
rewrite <-! Z.land_ones by assumption.
change 4 with (2 ^ 2) in C.
prove_Zeq_bitwise.Zbitwise.
}
assert (word.unsigned
(word.and (word.add dest (word.of_Z oimm12))
(word.xor (word.of_Z 1) (word.of_Z (2 ^ width - 1)))) mod 4 = 0) as B. {
rewrite A. solve_divisibleBy4.
}
t0.
Qed.
Lemma run_Jal: run_Jal_spec.
Proof.
repeat intro.
inline_iff1.
get_run1_valid_for_free.
match goal with
| H: (?P * ?Q * ?R)%sep ?m |- _ =>
assert ((P * (Q * R))%sep m) as A by ecancel_assumption
end.
destruct (invert_ptsto_program1 iset A) as (DE & ?).
t0.
Qed.
Local Arguments Z.pow: simpl never.
Local Arguments Z.opp: simpl never.
Lemma run_Jal0: run_Jal0_spec.
Proof.
repeat intro.
inline_iff1.
get_run1_valid_for_free.
match goal with
| H: (?P * ?Q * ?R)%sep ?m |- _ =>
assert ((P * (Q * R))%sep m) as A by ecancel_assumption
end.
destruct (invert_ptsto_program1 iset A) as (DE & ?).
t0.
Qed.
Lemma run_Addi: run_ImmReg_spec Addi word.add.
Proof. t. Qed.
Lemma run_Lb: run_Load_spec 1 Lb (signExtend 8).
Proof. t. Qed.
Lemma run_Lbu: run_Load_spec 1 Lbu id.
Proof. t. Qed.
Lemma run_Lh: run_Load_spec 2 Lh (signExtend 16).
Proof. t. Qed.
Lemma run_Lhu: run_Load_spec 2 Lhu id.
Proof. t. Qed.
Lemma run_Lw: run_Load_spec 4 Lw (signExtend 32).
Proof. t. Qed.
Lemma run_Lw_unsigned: width = 32 -> run_Load_spec 4 Lw id.
Proof.
change width with (id width).
t. rewrite sextend_width_nop; [reflexivity|symmetry;assumption].
Qed.
Lemma run_Lwu: run_Load_spec 4 Lwu id.
Proof. t. Qed.
Lemma run_Ld: run_Load_spec 8 Ld (signExtend 64).
Proof. t. Qed.
(* Note: there's no Ldu instruction, because Ld does the same *)
Lemma run_Ld_unsigned: width = 64 -> run_Load_spec 8 Ld id.
Proof.
change width with (id width).
t. rewrite sextend_width_nop; [reflexivity|symmetry;assumption].
Qed.
Lemma iff1_emp: forall P Q,
(P <-> Q) ->
@iff1 mem (emp P) (emp Q).
Proof. unfold iff1, emp. clear. firstorder idtac. Qed.
Lemma removeXAddr_diff: forall (a1 a2: word) xaddrs,
a1 <> a2 ->
isXAddr1 a1 xaddrs ->
isXAddr1 a1 (removeXAddr a2 xaddrs).
Proof.
unfold isXAddr1, removeXAddr.
intros.
apply filter_In.
split; [assumption|].
rewrite word.eqb_ne by congruence.
reflexivity.
Qed.
Lemma removeXAddr_bw: forall (a1 a2: word) xaddrs,
isXAddr1 a1 (removeXAddr a2 xaddrs) ->
isXAddr1 a1 xaddrs.
Proof.
unfold isXAddr1, removeXAddr.
intros.
eapply filter_In.
eassumption.
Qed.
Lemma sep_ptsto_to_addr_neq: forall a1 v1 a2 v2 (m : mem) R,
(ptsto a1 v1 * ptsto a2 v2 * R)%sep m ->
a1 <> a2.
Proof.
intros. intro E. subst a2. unfold ptsto in *.
destruct H as (? & ? & ? & (? & ? & ? & ? & ?) & ?).
subst.
destruct H0 as [? D].
unfold map.disjoint in D.
eapply D; apply map.get_put_same.
Qed.
Local Arguments invalidateWrittenXAddrs: simpl never.
Lemma run_Sb: run_Store_spec 1 Sb.
Proof. t. Qed.
Lemma run_Sh: run_Store_spec 2 Sh.
Proof. t. Qed.
Lemma run_Sw: run_Store_spec 4 Sw.
Proof. t. Qed.
Lemma run_Sd: run_Store_spec 8 Sd.
Proof. t. Qed.
End Run.
|
# Project: GBS Tool
# Author: Jeremy VanderMeer, [email protected] Alaska Center for Energy and Power
# Date: February 1, 2018 -->
# License: MIT License (see LICENSE file of this package for more information)
# *** General Imports ***
from scipy.interpolate import interp2d
import numpy as np
class esLossMap:
'''
This class contains methods to build a dense loss map for energy storage units based on sparser information provided in
`esDescriptor.xml`. There ...
'''
# TODO: write
# Constructor
def __init__(self):
# ******* INPUT VARIABLES *******
# list of tuples for a loss map. (power [pu], SOC [pu], loss [pu of power], ambient temperature [K])
self.lossMapDataPoints = []
# Maximum output power [kW]. This is the will be the upper limit of the power axis
self.pInMax = 0
# Maximum input power [kW]. This is the will be the upper limit of the power axis
self.pOutMax = 0
# Maximum energy capacity in kWs
self.eMax = 0
# ******* INTERNAL VARIABLES *******
# Coordinates for interpolation
self.coords = []
# ******* OUTPUT VARIABLES *******
# The dense lossMap with units [kW, kg/s]
self.lossMap = []
# The dense lossMap, but with integer values only.
self.lossMapInt = []
# loss map array power vector
self.P = []
# loss map array energy vector
self.E = []
# loss map array temperature vector
self.Temp = []
# loss map array with dimensions power x energy
self.loss = np.array([])
# an array, with same dimensions as the loss map, with the max amount of time that the es can charge or discharge
# at a given power for starting at a given state of charge
self.maxDischTime = np.array([])
def checkInputs(self):
'''
Makes sure data inputs are self-consistent. **Does not** check for physical validity of data.
:raises ValueError: for various data inconsistencies or missing values.
:return:
'''
# make copy of the input
inptDataPoints = self.lossMapDataPoints
# Check if data was initialized at all.
if not inptDataPoints:
raise ValueError('Loss map is empty list.')
# remove these checks, since having the option to run a simulation with a zero EES is needed
#elif self.pInMax == 0:
# raise ValueError('Maximum input power is not configured, or set to 0.')
#elif self.pOutMax == 0:
# raise ValueError('Maximum output power is not configured, or set to 0.')
#elif self.eMax == 0:
# raise ValueError('Maximum energy capacoty is not configured, or set to 0.')
# Check for negative values in loss, temperature and soc - there shouldn't be any
for tpls in inptDataPoints:
if any(n < 0 for n in tpls[1:]):
raise ValueError('SOC, Loss or temperature inputs contain negative values.')
# Make a copy of the input
# Sort the new list of tuples based on power levels.
#inptDataPoints.sort()
# Check for duplicates and clean up if possible.
# TODO: implement
self.coords = inptDataPoints
def linearInterpolation(self,chargeRate, pStep = 1, eStep = 3600, tStep = 1):
# chargeRate is the maximum fraction of the remaining energy storage capacity that can be charged in 1 second,
# or remaining energy storage capacity that can be discharged in 1 second, units are pu/sec
# pStep, eStep and tStep are the steps to be used in the loss map for power, energy and temperature. Units are
# kW, kWs and K.
# unzip into individual arrays
pDataPoints, eDataPoints, lossDataPoints, tempAmbDataPoints = zip(*self.coords)
if len(set(tempAmbDataPoints)) < 2: # if not more than one temperature defined, only 2d array (power and energy)
# create interpolation function
fn = interp2d(eDataPoints,pDataPoints,lossDataPoints)
# create filled power and energy arrays
if self.pInMax > 0: # check if a positive value was given
usePinMax = - self.pInMax
else:
usePinMax = self.pInMax
self.P = range(int(usePinMax), int(self.pOutMax + pStep), int(pStep))
self.E = range(0, int(self.eMax + eStep), int(eStep))
self.Temp = tempAmbDataPoints
# create new filled loss array.
self.loss = np.array(fn(self.E,self.P)) # array with size power x energy
# create another array with the maximum amount of time that can be spent charging or discharging at a power
# given a state of charge
# first, create an array with the time it takes to reach the next energy bin, taking into account losses
self.nextBinTime = np.zeros([len(self.P), len(self.E)]) # initiate array
#self.nextBinTime[:] = np.nan # to nan
for idxE, E in enumerate(self.E): # for every energy level
for idxP, P in enumerate(self.P): # for every power
# if the power is within the chargeRate bounds
if (P >= (E - self.eMax) * chargeRate) & (P <= E * chargeRate):
if P > 0: # if discharging
# find the amount of time to get to the next energy bin
self.nextBinTime[idxP, idxE] = (eStep) / (P + self.loss[idxP, idxE])
elif P < 0: # if charging
# find the amount of time to get to the next energy bin
self.nextBinTime[idxP, idxE] = -(eStep) / (P + self.loss[idxP, idxE])
# now use the array of the time it takes to get to the next bin and calculate array of the max amount of
# time the ES can charge or discharge at a certain power, starting at a certain energy level
self.maxDischTime = np.zeros([len(self.P), len(self.E)]) # initiate array
#self.maxDischTime[:] = np.nan # to nan
for idxE, E in enumerate(self.E): # for every energy level
for idxP, P in enumerate(self.P): # for every power
if P > 0: # if discharging
# the total discharge time is the sum of the time taken to get to each consecutive bin.
self.maxDischTime[idxP,idxE] = np.nansum(self.nextBinTime[idxP,:idxE+1])
elif P < 0: # if charging
# the total charge time is the sum of the time taken to get to each consecutive bin.
self.maxDischTime[idxP,idxE] = np.nansum(self.nextBinTime[idxP,idxE:])
else: # if power is zero
self.maxDischTime[idxP, idxE] = np.inf
else: # if more than one temperature defined
# TODO: implement
self.P = []
self.E = []
self.Temp = []
self.loss = np.array([]) |
#pragma once
//=====================================================================//
/*! @file
@brief イグナイター・サーバー・クラス @n
※エミュレーション、テスト用、実際のサーバーは、外部マイコン
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include "utils/string_utils.hpp"
namespace asio = boost::asio;
namespace ip = asio::ip;
namespace net {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Ignitor Server クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class ign_server {
asio::io_service& io_service_;
ip::tcp::acceptor acceptor_;
ip::tcp::socket socket_;
asio::streambuf recv_;
bool connect_;
bool read_trg_;
void on_recv_(const boost::system::error_code& error, size_t bytes_transferred)
{
if(error && error != boost::asio::error::eof) {
std::cout << "receive failed: " << error.message() << std::endl;
} else {
const char* data = asio::buffer_cast<const char*>(recv_.data());
std::cout << "response(" << bytes_transferred << "): ";
std::cout << data << std::endl;
recv_.consume(recv_.size());
read_trg_ = true;
}
}
void on_accept_(const boost::system::error_code& error)
{
if(error) {
auto out = utils::sjis_to_utf8(error.message());
std::cout << "accept failed: " << out << std::endl;
} else {
std::cout << "accept correct!" << std::endl;
connect_ = true;
read_trg_ = true;
}
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
ign_server(asio::io_service& ios) : io_service_(ios),
acceptor_(ios, ip::tcp::endpoint(ip::address::from_string("127.0.0.1"), 31400)),
socket_(ios), recv_(), connect_(false), read_trg_(false) { }
//-----------------------------------------------------------------//
/*!
@brief 開始
*/
//-----------------------------------------------------------------//
void start()
{
connect_ = false;
acceptor_.async_accept(socket_,
boost::bind(&ign_server::on_accept_, this, asio::placeholders::error));
}
//-----------------------------------------------------------------//
/*!
@brief サービス
*/
//-----------------------------------------------------------------//
void service()
{
if(connect_) {
// boost::asio::async_read(socket_, recv_, asio::transfer_all(),
if(read_trg_) {
boost::asio::async_read(socket_, recv_, asio::transfer_at_least(4),
boost::bind(&ign_server::on_recv_, this,
asio::placeholders::error, asio::placeholders::bytes_transferred));
read_trg_ = false;
}
}
}
};
}
|
[STATEMENT]
lemma below_trans_cong[trans]:
"a \<sqsubseteq> f x \<Longrightarrow> x \<sqsubseteq> y \<Longrightarrow> cont f \<Longrightarrow> a \<sqsubseteq> f y "
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>a \<sqsubseteq> f x; x \<sqsubseteq> y; cont f\<rbrakk> \<Longrightarrow> a \<sqsubseteq> f y
[PROOF STEP]
by (metis below_trans cont2monofunE) |
In addition to the reactions originally reported by Johnson , Corey , and Chaykovsky , sulfur ylides have been used for a number of related homologation reactions that tend to be grouped under the same name .
|
module KrylovSolver
use AbstractOperators
private
public :: pcg
!! Derived type decscribing the operator
!! y=(~A)^{-1} x
!! with (~A)^{-1} is the approximate inverse via
!! Preconditoned Conjugate Gradient
type, public, extends(abstract_operator) :: pcg_solver
!! set main controls
integer :: max_iterations
real(kind=double) :: tolerance
!! pointers for matrix and precontioner
class(abstract_operator), pointer :: matrix
class(abstract_operator), pointer :: preconditioner
!! scratch vector
real(kind=double), allocatable :: aux(:)
contains
procedure, public, pass :: init => init_solver
procedure, public, pass :: kill => kill_solver
!! procedure overrided
procedure, public, pass :: apply => apply_pcg_solver
end type pcg_solver
contains
subroutine pcg(matrix,rhs,sol,ierr,&
tolerance,max_iterations,preconditioner,aux_passed)
use AbstractOperators
use SimpleVectors
implicit none
class(abstract_operator), intent(inout) :: matrix
real(kind=double), intent(in ) :: rhs(matrix%ncol)
real(kind=double), intent(inout) :: sol(matrix%nrow)
integer, intent(inout) :: ierr
real(kind=double), optional, intent(in ) :: tolerance
integer, optional, intent(in ) :: max_iterations
class(abstract_operator), target,optional, intent(inout) :: preconditioner
real(kind=double), target,optional, intent(inout) :: aux_passed(6*matrix%ncol)
!
! local vars
!
! logical
logical :: exit_test
! string
character(len=256) :: msg
! integer
integer :: i
integer :: lun_err, lun_out
integer :: iprt,max_iter
integer :: nequ,dim_ker,ndir=0
integer :: iort
integer :: info_prec
integer :: iter
! real
real(kind=double), pointer :: aux(:)
real(kind=double), target, allocatable :: aux_local(:)
real(kind=double), pointer :: axp(:), pres(:), ainv(:), resid(:), pk(:),scr(:)
real(kind=double) :: alpha, beta, presnorm,resnorm,bnorm
real(kind=double) :: ptap
real(kind=double) :: normres
real(kind=double) :: tol,rort
real(kind=double) :: inverse_residum_weight
!
type(eye), target :: identity
class(abstract_operator), pointer :: prec => null()
!! checks
if (.not. matrix%is_symmetric) then
ierr = 998
return
end if
if (matrix%nrow .ne. matrix%ncol ) then
ierr = 999
return
end if
nequ=matrix%nrow
if (present(tolerance)) then
tol=tolerance
else
tol=1.0d-6
end if
if (present(max_iterations)) then
max_iter=max_iterations
else
max_iter=200
end if
!! handle preconditing
if (present(preconditioner)) then
if (.not. preconditioner%is_symmetric) then
ierr = 999
return
end if
if ( preconditioner%nrow .ne. preconditioner%ncol ) then
ierr = 999
return
end if
prec => preconditioner
else
call identity%init(nequ)
prec => identity
end if
! allocate memory if required and set pointers for scratch arrays
if (present(aux_passed)) then
aux=>aux_passed
else
allocate(aux_local(6*nequ))
aux=>aux_local
end if
axp => aux( 1 : nequ)
pres => aux( nequ+1 : 2*nequ)
ainv => aux(2*nequ+1 : 3*nequ)
resid => aux(3*nequ+1 : 4*nequ)
pk => aux(4*nequ+1 : 5*nequ)
scr => aux(5*nequ+1 : 6*nequ)
! set tolerance
if (present (tolerance)) then
tol = tolerance
else
tol = 1.0d-6
end if
! set max iterations number
if (present (max_iterations)) then
max_iter = max_iterations
else
max_iter = 100
end if
exit_test = .false.
! compute rhs norm and break cycle
bnorm = d_norm(nequ,rhs)
if (bnorm<1.0d-16) then
ierr=0
sol=zero
! free memory
aux=>null()
if (allocated(aux_local)) deallocate(aux_local)
return
end if
! calculate initial residual (res = rhs-M*sol)
call matrix%apply(sol,resid,ierr)
resid = rhs - resid
resnorm = d_norm(nequ,resid)/bnorm
!
! cycle
!
iter=0
do while (.not. exit_test)
iter = iter + 1
! compute pres = PREC (r_{k+1})
call prec%apply(resid,pres,ierr)
! calculates beta_k
if (iter.eq.1) then
beta = zero
else
beta = -d_scalar_product(nequ,pres,axp)/ptap
end if
! calculates p_{k+1}:=pres_{k}+beta_{k}*p_{k}
call d_axpby(nequ,one,pres,beta,pk)
! calculates axp_{k+1}:= matrix * p_{k+1}
call matrix%apply(pk,axp,ierr)
! calculates \alpha_k
ptap = d_scalar_product(nequ,pk,axp)
alpha = d_scalar_product(nequ,pk,resid)/ptap
! calculates x_k+1 and r_k+1
call d_axpby(nequ,alpha,pk,one,sol)
call d_axpby(nequ,-alpha,axp,one,resid)
! compute residum
resnorm = d_norm(nequ,resid)/bnorm
! checks
exit_test = (&
iter .gt. max_iter .or.&
resnorm .le. tol)
if (iter.ge. max_iter) ierr = 1
end do
! free memory
aux=>null()
if (allocated(aux_local)) deallocate(aux_local)
end subroutine pcg
subroutine init_solver(this,&
matrix, max_iter, tolerance, precondtioner)
class(pcg_solver), intent(inout) :: this
class(abstract_operator), target, intent(in ) :: matrix
integer, intent(in ) :: max_iter
real(kind=double), intent(in ) :: tolerance
class(abstract_operator), target, intent(in ) :: precondtioner
!! the set domain/codomain operator dimension
this%nrow = matrix%nrow
this%ncol = matrix%ncol
!! the inverse of a symmetric matrix is symmetric but the
!! approximiate inverse it is not in general.
!! We set that that the operator is symmettric if
!! if the require tolerance is below 1e-13
if (tolerance < 1e-13) then
this%is_symmetric=.True.
else
this%is_symmetric=.False.
end if
!! the non-linearity will be (approximately) the tolerance of the
!! pcg solver
this%nonlinearity = tolerance
!! set controls
this%max_iterations = max_iter
this%tolerance = tolerance
!! set pointer
this%matrix => matrix
this%preconditioner => precondtioner
!! set work arrays
allocate(this%aux(6*matrix%nrow))
aux = zero
end subroutine init_solver
subroutine kill_solver(this)
class(pcg_solver), intent(inout) :: this
this%max_iterations = 0
this% tolerance = zero
!! the non-linearity will be approximately the tolerance of the
!! pcg solver
this%nonlinearity = zero
this%matrix => null()
this%preconditioner => null()
!! free memory
deallocate(this%aux)
end subroutine kill_solver
subroutine apply_pcg_solver(this,vec_in,vec_out,ierr)
implicit none
class(pcg_solver), intent(inout) :: this
real(kind=double), intent(in ) :: vec_in(this%ncol)
real(kind=double), intent(inout) :: vec_out(this%nrow)
integer, intent(inout) :: ierr
call pcg(this%matrix, vec_in, vec_out, ierr,&
tolerance=this%tolerance,&
max_iterations=this%max_iterations,&
preconditioner=this%preconditioner,&
aux_passed=this%aux)
end subroutine apply_pcg_solver
end module KrylovSolver
|
from typing import Dict, List
import numpy as np
from rb.complexity.complexity_index import ComplexityIndex
from rb.core.document import Document
from rb.processings.pipeline.dataset import Dataset, Task
from sklearn.base import BaseEstimator
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score, make_scorer, mean_squared_error
class Estimator:
def __init__(self, dataset: Dataset, tasks: List[Task], params: Dict[str, str]):
self.dataset = dataset
self.tasks = tasks
self.model: BaseEstimator = None
self.scoring = "accuracy"
def predict(self, indices: Dict[ComplexityIndex, float]):
return self.model.predict(self.construct_input(indices))
def construct_input(self, indices: Dict[ComplexityIndex, float]) -> np.ndarray:
result = [indices[feature]
for i, feature in enumerate(self.dataset.features)
if self.tasks[0].mask[i]]
return np.array(result)
def cross_validation(self, n=5) -> float:
x = [self.construct_input(indices) for indices in self.dataset.normalized_train_features]
y = self.tasks[0].get_train_targets()
scores = cross_val_score(self.model, x, y, scoring=make_scorer(self.scoring), cv=n)
return scores.mean()
def evaluate(self) -> float:
x = [self.construct_input(indices) for indices in self.dataset.normalized_train_features]
y = self.tasks[0].get_train_targets()
self.model.fit(x, y)
x = [self.construct_input(indices) for indices in self.dataset.normalized_dev_features]
y = self.tasks[0].get_dev_targets()
predicted = self.model.predict(x)
return self.scoring(y, predicted)
@classmethod
def parameters(cls) -> Dict[str, List]:
return {}
@classmethod
def valid_config(cls, config) -> bool:
return True
class Classifier(Estimator):
def __init__(self, dataset: Dataset, tasks: List[Task], params: Dict[str, str]):
super().__init__(dataset, tasks, params)
self.scoring = accuracy_score
class Regressor(Estimator):
def __init__(self, dataset: Dataset, tasks: List[Task], params: Dict[str, str]):
super().__init__(dataset, tasks, params)
self.scoring = mean_squared_error
|
(* Title: HOL/Auth/n_germanSimp_lemma_inv__31_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_germanSimp Protocol Case Study*}
theory n_germanSimp_lemma_inv__31_on_rules imports n_germanSimp_lemma_on_inv__31
begin
section{*All lemmas on causal relation between inv__31*}
lemma lemma_inv__31_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__31 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqE__part__0Vsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqE__part__1Vsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__31) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__31) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
module Main where
import Numeric.LinearAlgebra
import Control.Arrow
import Common
import Forward
import BackProp
import AutoEncoder
import ActivFunc
import Other
import Mnist
main :: IO ()
main = do
tm <- parseCsvToMatrixR "data/mnist_test_100.csv"
let (ty, tx) = tr *** tr $ mnistRead 10 tm
m <- parseCsvToMatrixR "data/mnist_train_600.csv"
let (y, x) = tr *** tr $ mnistRead 10 m
ws <- genWeights [784, 10]
-- let pws = preTrains 0.5 1000 ramps x ws
nws <- last . take 1000 $ iterateM (sgdMethod 100 (x, y) $ backPropClassification 0.5 ramps) ws
-- putStrLn "not trained outputs"
-- print . tr . classesToLabels . tr . forwardClassification rampC ws $ tx
-- TODO: use function
let o = tr . classesToLabels . tr . forwardClassification rampC nws $ tx
let t = tr . classesToLabels . tr $ ty
let l = head . toLists $ t - o
let a = length l
let s = length . filter (==0) $ l
print $ fromIntegral s / fromIntegral a
-- putStrLn "pretrainined outputs"
-- print . classesToLabels . tr . forwardClassification rampC npws $ x
|
module Main
data Cat = Cas | Luna | Sherlock
f : (cat: Cat) -> String
getName : (cat: Cat) -> String
getName Cas = "Cas"
getName Luna = "Luna"
plusTwo : (n: Nat) -> Nat
plusTwo n = plus 2 n
g : (n: Nat) -> (b: Bool) -> String
g n b = ?g_rhs
n : Nat
n = ?n_rhs
|
-- Andreas, 2017-10-17, issue #2807
--
-- Refining with an extended lambda gave internal error.
-- Seemed to be triggered only when giving resulted in an error.
{-# OPTIONS --allow-unsolved-metas #-}
-- {-# OPTIONS -v scope.extendedLambda:60 #-}
-- {-# OPTIONS -v impossible:10 #-}
data ⊥ : Set where
actuallyNotEmpty : ⊥
data D : Set where
c : ⊥ → D
test : D → ⊥
test = {! λ{ (c ()) }!} -- C-c C-r
-- WAS: internal error in ConcreteToAbstract (insertApp)
--
-- Expected:
-- Succeed with unsolved constraints and metas.
|
\<^marker>\<open>creator Bilel Ghorbel, Florian Kessler\<close>
section "Small step semantics of IMP-- "
subsection "IMP-- Small step semantics definition"
theory IMP_Minus_Minus_Small_StepT imports Main IMP_Minus_Minus_Com "IMP_Minus.Rel_Pow" begin
paragraph "Summary"
text\<open>We give small step semantics with time for IMP--.
Based on the small step semantics definition time for IMP-. In contrast to IMP-, we use partial
maps to represent states. That has the simple reason the we designed this with translation to
SAS++ in mind, which also uses partial states. \<close>
type_synonym state = "vname \<rightharpoonup> bit"
inductive
small_step :: "com * state \<Rightarrow> com * state \<Rightarrow> bool" ("_ \<rightarrow> _" 55)
where
Assign: "(x ::= v, s) \<rightarrow> (SKIP, s(x \<mapsto> v))" |
Seq1: "(SKIP;;c\<^sub>2,s) \<rightarrow> (c\<^sub>2,s)" |
Seq2: "(c\<^sub>1,s) \<rightarrow> (c\<^sub>1',s') \<Longrightarrow> (c\<^sub>1;;c\<^sub>2,s) \<rightarrow> (c\<^sub>1';;c\<^sub>2,s')" |
IfTrue: "\<exists>b \<in> set bs. s b \<noteq> Some Zero \<Longrightarrow> (IF bs \<noteq>0 THEN c\<^sub>1 ELSE c\<^sub>2,s) \<rightarrow> (c\<^sub>1,s)" |
IfFalse: "\<forall>b \<in> set bs. s b = Some Zero \<Longrightarrow> (IF bs \<noteq>0 THEN c\<^sub>1 ELSE c\<^sub>2,s) \<rightarrow> (c\<^sub>2,s)" |
WhileTrue: "(\<exists>b \<in> set bs. s b \<noteq> Some Zero) \<Longrightarrow> (WHILE bs \<noteq>0 DO c,s) \<rightarrow>
(c ;; (WHILE bs \<noteq>0 DO c), s)" |
WhileFalse: "(\<forall>b \<in> set bs. s b = Some Zero) \<Longrightarrow> (WHILE bs \<noteq>0 DO c,s) \<rightarrow>
(SKIP,s)"
subsection "Transitive Closure"
abbreviation
small_step_pow :: "com * state \<Rightarrow> nat \<Rightarrow> com * state \<Rightarrow> bool" ("_ \<rightarrow>\<^bsup>_\<^esup> _" 55)
where "x \<rightarrow>\<^bsup>t\<^esup> y == (rel_pow small_step t) x y"
bundle small_step_syntax
begin
notation small_step (infix "\<rightarrow>" 55) and
small_step_pow ("_ \<rightarrow>\<^bsup>_\<^esup> _" 55)
end
bundle no_small_step_syntax
begin
no_notation small_step (infix "\<rightarrow>" 55) and
small_step_pow ("_ \<rightarrow>\<^bsup>_\<^esup> _" 55)
end
subsection\<open>Executability\<close>
code_pred small_step .
subsection\<open>Proof infrastructure\<close>
subsubsection\<open>Induction rules\<close>
text\<open>The default induction rule @{thm[source] small_step.induct} only works
for lemmas of the form \<open>a \<rightarrow> b \<Longrightarrow> \<dots>\<close> where \<open>a\<close> and \<open>b\<close> are
not already pairs \<open>(DUMMY,DUMMY)\<close>. We can generate a suitable variant
of @{thm[source] small_step.induct} for pairs by ``splitting'' the arguments
\<open>\<rightarrow>\<close> into pairs:\<close>
lemmas small_step_induct = small_step.induct[split_format(complete)]
subsubsection\<open>Proof automation\<close>
declare small_step.intros[simp,intro]
text\<open>Rule inversion:\<close>
inductive_cases SkipE[elim!]: "(SKIP,s) \<rightarrow> ct"
inductive_cases Assign[elim!]: "(x ::= v,s) \<rightarrow> ct"
inductive_cases SeqE[elim]: "(c1;;c2,s) \<rightarrow> ct"
inductive_cases IfE[elim!]: "(IF b\<noteq>0 THEN c1 ELSE c2,s) \<rightarrow> ct"
inductive_cases WhileE[elim]: "(WHILE b\<noteq>0 DO c, s) \<rightarrow> ct"
subsection "Sequence properties"
declare rel_pow_intros[simp,intro]
text\<open>A simple property:\<close>
lemma deterministic:
"cs \<rightarrow> cs' \<Longrightarrow> cs \<rightarrow> cs'' \<Longrightarrow> cs'' = cs'"
apply(induction arbitrary: cs'' rule: small_step.induct)
by blast+
text "sequence property"
lemma star_seq2: "(c1,s) \<rightarrow>\<^bsup>t\<^esup> (c1',s') \<Longrightarrow> (c1;;c2,s) \<rightarrow>\<^bsup> t \<^esup> (c1';;c2,s')"
proof(induction t arbitrary: c1 c1' s s')
case (Suc t)
then obtain c1'' s'' where "(c1,s) \<rightarrow> (c1'', s'')"
and "(c1'', s'') \<rightarrow>\<^bsup> t \<^esup> (c1', s')" by auto
moreover then have "(c1'';;c2, s'') \<rightarrow>\<^bsup> t \<^esup> (c1';;c2, s')" using Suc by simp
ultimately show ?case by auto
qed auto
lemma if_trueI[intro]:
"is1 v = Some One \<Longrightarrow> v \<in> set x1 \<Longrightarrow> (IF x1\<noteq>0 THEN c11 ELSE c12, is1) \<rightarrow> (c11, is1)"
by force
lemma if_falseI[intro]:
"map_of (map (\<lambda>v. (v, Zero)) (remdups x1)) \<subseteq>\<^sub>m is1
\<Longrightarrow> (IF x1\<noteq>0 THEN c11 ELSE c12, is1) \<rightarrow> (c12, is1)"
proof -
assume "map_of (map (\<lambda>v. (v, Zero)) (remdups x1)) \<subseteq>\<^sub>m is1"
have "v \<in> set (remdups x1) \<Longrightarrow> map_of (map (\<lambda>v. (v, Zero)) (remdups x1)) v = Some Zero" for v
by(induction x1) (auto split: if_splits)
hence "\<forall>v \<in> set x1. is1 v = Some Zero"
apply(auto simp: map_le_def dom_map_of_conv_image_fst)
by (metis (mono_tags, lifting) \<open>map_of (map (\<lambda>v. (v, Zero)) (remdups x1)) \<subseteq>\<^sub>m is1\<close> domI map_le_def)
thus ?thesis by simp
qed
lemma while_trueI[intro]:
"is1 v = Some One \<Longrightarrow> v \<in> set x1 \<Longrightarrow> (WHILE x1\<noteq>0 DO c1, is1) \<rightarrow> (c1 ;; WHILE x1\<noteq>0 DO c1, is1)"
by force
lemma while_falseI[intro]:
"map_of (map (\<lambda>v. (v, Zero)) (remdups x1)) \<subseteq>\<^sub>m is1
\<Longrightarrow> (WHILE x1\<noteq>0 DO c1, is1) \<rightarrow> (SKIP, is1)"
proof -
assume "map_of (map (\<lambda>v. (v, Zero)) (remdups x1)) \<subseteq>\<^sub>m is1"
have "v \<in> set (remdups x1) \<Longrightarrow> map_of (map (\<lambda>v. (v, Zero)) (remdups x1)) v = Some Zero" for v
by(induction x1) (auto split: if_splits)
hence "\<forall>v \<in> set x1. is1 v = Some Zero"
apply(auto simp: map_le_def dom_map_of_conv_image_fst)
by (metis (mono_tags, lifting) \<open>map_of (map (\<lambda>v. (v, Zero)) (remdups x1)) \<subseteq>\<^sub>m is1\<close> domI map_le_def)
thus ?thesis by simp
qed
subsection \<open>Functional definition\<close>
text \<open>We also give a definition of small step semantics as a function rather than as a relation.
We show the equivalence between the two definitions. We also give some useful Lemmas to show
that IMP-- terminates in some state. \<close>
fun small_step_fun:: "com * state \<Rightarrow> com * state" where
"small_step_fun (SKIP, s) = (SKIP, s)" |
"small_step_fun (x ::= v, s) = (SKIP, s(x \<mapsto> v))" |
"small_step_fun (c\<^sub>1;;c\<^sub>2,s) = (if c\<^sub>1 = SKIP then (c\<^sub>2,s)
else (fst (small_step_fun (c\<^sub>1, s)) ;;c\<^sub>2, snd (small_step_fun (c\<^sub>1, s))))" |
"small_step_fun (IF bs \<noteq>0 THEN c\<^sub>1 ELSE c\<^sub>2,s) = (if \<exists>b \<in> set bs. s b \<noteq> Some Zero then (c\<^sub>1,s) else (c\<^sub>2,s))" |
"small_step_fun (WHILE bs \<noteq>0 DO c,s) = (if \<exists>b \<in> set bs. s b \<noteq> Some Zero
then (c ;; (WHILE bs \<noteq>0 DO c), s) else (SKIP,s))"
fun t_small_step_fun:: "nat \<Rightarrow> com * state \<Rightarrow> com * state" where
"t_small_step_fun 0 = id" |
"t_small_step_fun (Suc t) = (t_small_step_fun t) \<circ> small_step_fun"
lemma t_small_step_fun_ge_0: "t > 0
\<Longrightarrow> t_small_step_fun t (c, s) = t_small_step_fun (t - 1) (small_step_fun (c, s))"
proof-
assume "t > 0"
then obtain t' where "t = Suc t'" using lessE by blast
thus ?thesis by simp
qed
lemma t_small_step_fun_small_step_fun: "t_small_step_fun t (small_step_fun cs)
= t_small_step_fun (t + 1) cs"
by simp
lemma small_step_fun_t_small_step_fun: "small_step_fun (t_small_step_fun t (c, s))
= t_small_step_fun (t + 1) (c, s)"
proof(induction t arbitrary: c s)
case (Suc t)
let ?c' = "fst (small_step_fun (c, s))"
let ?s' = "snd (small_step_fun (c, s))"
have "small_step_fun (t_small_step_fun t (?c', ?s')) = t_small_step_fun t (small_step_fun (?c', ?s'))"
using Suc t_small_step_fun_small_step_fun by presburger
thus ?case by auto
qed auto
lemma t_small_step_fun_SKIP[simp]: "t_small_step_fun t (SKIP, s) = (SKIP, s)"
apply(induction t)
by auto
lemma t_small_step_fun_terminate_iff: "t_small_step_fun t (c1, s1) = (SKIP, s2) \<longleftrightarrow>
((c1 = SKIP \<and> s1 = s2) \<or> (t > 0 \<and> t_small_step_fun (t - 1) (small_step_fun (c1, s1))
= (SKIP, s2)))"
apply(auto simp: t_small_step_fun_ge_0)
apply (metis One_nat_def id_apply less_Suc_eq_0_disj prod.inject t_small_step_fun.elims t_small_step_fun_ge_0)
by (metis One_nat_def Pair_inject id_apply less_Suc_eq_0_disj t_small_step_fun.elims t_small_step_fun_ge_0)
lemma t_small_step_fun_decomposition: "t_small_step_fun (a + b) cs
= t_small_step_fun a (t_small_step_fun b cs)"
apply(induction a arbitrary: cs)
by(auto simp: small_step_fun_t_small_step_fun)
lemma t_small_step_fun_increase_time: "t \<le> t' \<Longrightarrow> t_small_step_fun t (c1, s1) = (SKIP, s2)
\<Longrightarrow> t_small_step_fun t' (c1, s1) = (SKIP, s2)"
using t_small_step_fun_decomposition[where ?a="t' - t" and ?b="t"] by simp
lemma exists_terminating_iff: "(\<exists>t < Suc t'.
t_small_step_fun t (c, s) = (SKIP, s'))
\<longleftrightarrow> t_small_step_fun t' (c, s) = (SKIP, s')"
using t_small_step_fun_increase_time by (auto simp: less_Suc_eq_le)
lemma terminates_then_can_reach_SKIP_in_seq: "t_small_step_fun t (c1, s1) = (SKIP, s2)
\<Longrightarrow> (\<exists>t' \<le> t. t_small_step_fun t' (c1 ;; c2, s1) = (SKIP ;; c2, s2))"
proof(induction t arbitrary: c1 s1)
case (Suc t)
have "c1 = SKIP \<or> c1 \<noteq> SKIP" by auto
thus ?case using Suc
proof (elim disjE)
assume *: "c1 \<noteq> SKIP"
let ?c1' = "fst (small_step_fun (c1, s1))"
let ?s1' = "snd (small_step_fun (c1, s1))"
have "t_small_step_fun t (?c1', ?s1') = (SKIP, s2)" using *
by (metis Suc.prems Suc_eq_plus1 prod.collapse t_small_step_fun_small_step_fun)
then obtain t' where "t' \<le> t \<and> t_small_step_fun t' (?c1' ;; c2, ?s1') = (SKIP ;; c2, s2)"
using Suc by blast
thus ?case using * by auto
qed auto
qed auto
lemma seq_terminates_iff: "t_small_step_fun t (a ;; b, s1) = (SKIP, s2) \<longleftrightarrow>
(\<exists>t' s3. t' < t \<and> t_small_step_fun t' (a, s1) = (SKIP, s3)
\<and> t_small_step_fun (t - (t' + 1)) (b, s3) = (SKIP, s2))"
proof(induction t arbitrary: a s1)
case (Suc t)
show ?case
proof
assume *: "t_small_step_fun (Suc t) (a;; b, s1) = (SKIP, s2)"
have "a = SKIP \<or> a \<noteq> SKIP" by auto
thus "\<exists>t' s3. t' < Suc t \<and> t_small_step_fun t' (a, s1) = (SKIP, s3)
\<and> t_small_step_fun (Suc t - (t' + 1)) (b, s3) = (SKIP, s2)"
using * proof (elim disjE)
assume **: "a \<noteq> SKIP"
let ?a' = "fst (small_step_fun (a, s1))"
let ?s1' = "snd (small_step_fun (a, s1))"
have "t_small_step_fun t (?a' ;; b, ?s1') = (SKIP, s2)" using * **
by (auto simp: t_small_step_fun_terminate_iff)
then obtain t' s3 where "t' < t \<and> t_small_step_fun t' (?a', ?s1') = (SKIP, s3)
\<and> t_small_step_fun (t - (t' + 1)) (b, s3) = (SKIP, s2)" using Suc by auto
hence "t' + 1 < t + 1 \<and> t_small_step_fun (t' + 1) (a, s1) = (SKIP, s3)
\<and> t_small_step_fun (t - (t' + 1)) (b, s3) = (SKIP, s2)" by(auto)
thus ?thesis by auto
qed auto
next
assume "\<exists>t' s3. t' < Suc t \<and> t_small_step_fun t' (a, s1) = (SKIP, s3)
\<and> t_small_step_fun (Suc t - (t' + 1)) (b, s3) = (SKIP, s2)"
then obtain t' s3 where t'_def: "t' < Suc t \<and> t_small_step_fun t' (a, s1) = (SKIP, s3)
\<and> t_small_step_fun (Suc t - (t' + 1)) (b, s3) = (SKIP, s2)" by blast
then obtain t'' where t''_def: "t'' \<le> t' \<and> t_small_step_fun t'' (a ;; b, s1) = (SKIP ;; b, s3)"
using terminates_then_can_reach_SKIP_in_seq by blast
hence "t_small_step_fun (t'' + ((Suc t - (t' + 1)) + 1)) (a ;; b, s1)
= t_small_step_fun (Suc t - (t' + 1) + 1) (SKIP ;; b, s3)"
using t_small_step_fun_decomposition[where ?b="t''"] t'_def by (metis add.commute)
also have "... = t_small_step_fun (Suc t - (t' + 1)) (b, s3)" using t'_def
by(auto simp: t_small_step_fun_ge_0)
also have "... = (SKIP, s2)" using t'_def by simp
ultimately show "t_small_step_fun (Suc t) (a ;; b, s1) = (SKIP, s2)"
apply -
apply(rule t_small_step_fun_increase_time[where ?t="t'' + ((Suc t - (t' + 1)) + 1)"])
using t'_def t''_def by(auto)
qed
qed auto
lemma seq_terminates_when: "t1 + t2 < t \<Longrightarrow> t_small_step_fun t1 (a, s1) = (SKIP, s3)
\<Longrightarrow> t_small_step_fun t2 (b, s3) = (SKIP, s2)
\<Longrightarrow> t_small_step_fun t (a ;; b, s1) = (SKIP, s2)"
apply(auto simp: seq_terminates_iff)
by (metis Nat.add_diff_assoc2 add_lessD1 diff_Suc_Suc diff_add_inverse le_add_same_cancel1
less_natE t_small_step_fun_increase_time zero_le)
lemma seq_terminates_when': "t_small_step_fun t1 (a, s1) = (SKIP, s3)
\<Longrightarrow> t_small_step_fun t2 (b, s3) = (SKIP, s2)
\<Longrightarrow> t1 + t2 < t
\<Longrightarrow> t_small_step_fun t (a ;; b, s1) = (SKIP, s2)"
apply(auto simp: seq_terminates_iff)
by (metis Nat.add_diff_assoc2 add_lessD1 diff_Suc_Suc diff_add_inverse le_add_same_cancel1
less_natE t_small_step_fun_increase_time zero_le)
lemma small_step_fun_small_step: "c1 \<noteq> SKIP \<Longrightarrow> small_step_fun (c1, s1) = (c2, s2)
\<longleftrightarrow> (c1, s1) \<rightarrow> (c2, s2)"
apply(induction c1 arbitrary: s1 c2 s2)
apply auto
apply fastforce
by (metis SeqE fstI eq_snd_iff)+
lemma small_step_fun_small_step': "c1 \<noteq> SKIP \<Longrightarrow>
(c1, s1) \<rightarrow> small_step_fun (c1, s1)"
apply(induction c1 arbitrary: s1)
by auto
lemma t_small_step_fun_t_small_step_equivalence: "(t_small_step_fun t (c1, s1) = (SKIP, s2))
\<longleftrightarrow> (\<exists>t' \<le> t. (c1, s1) \<rightarrow>\<^bsup>t'\<^esup> (SKIP, s2))"
proof(induction t arbitrary: c1 s1 rule: nat_less_induct)
case (1 n)
hence IH: "t'' < n
\<Longrightarrow> (t_small_step_fun t'' (c1, s1) = (SKIP, s2)) \<longleftrightarrow> (\<exists>t'\<le>t''. (c1, s1) \<rightarrow>\<^bsup>t'\<^esup> (SKIP, s2))"
for t'' c1 s1 by simp
show ?case
proof(cases n)
case (Suc t)
have "c1 = SKIP \<or> c1 \<noteq> SKIP" by auto
thus ?thesis
proof(elim disjE)
assume "c1 \<noteq> SKIP"
show ?thesis
proof
assume "t_small_step_fun n (c1, s1) = (SKIP, s2)"
hence "(c1, s1) \<rightarrow> small_step_fun (c1, s1)
\<and> (\<exists>t' \<le> t. small_step_fun (c1, s1) \<rightarrow>\<^bsup>t'\<^esup> (SKIP, s2))"
using IH[where ?c1.0="fst (small_step_fun (c1, s1))"
and ?s1.0="snd (small_step_fun (c1, s1))" and ?t''=t]
\<open>c1 \<noteq> SKIP\<close> small_step_fun_small_step' Suc by auto
thus "\<exists>t' \<le> n. (c1, s1) \<rightarrow>\<^bsup>t'\<^esup> (SKIP, s2)" using Suc by auto
next
assume "\<exists>t' \<le> n. (c1, s1) \<rightarrow>\<^bsup>t'\<^esup> (SKIP, s2)"
then obtain t' where t'_def: "t' \<le> n \<and> (c1, s1) \<rightarrow>\<^bsup>t'\<^esup> (SKIP, s2)" by blast
then obtain t'' where t''_def: "t' = Suc t''" using \<open>c1 \<noteq> SKIP\<close> by (metis prod.inject rel_pow.cases)
then obtain c3 s3 where "(c1, s1) \<rightarrow> (c3, s3) \<and> (c3, s3) \<rightarrow>\<^bsup>t''\<^esup> (SKIP, s2)"
using t'_def by auto
hence "small_step_fun (c1, s1) = (c3, s3) \<and> t_small_step_fun t'' (c3, s3) = (SKIP, s2)"
using IH[where ?c1.0=c3 and ?s1.0=s3 and ?t''=t''] small_step_fun_small_step \<open>c1 \<noteq> SKIP\<close>
t'_def t''_def by auto
hence "t_small_step_fun (Suc t'') (c1, s1) = (SKIP, s2)" by simp
thus "t_small_step_fun n (c1, s1) = (SKIP, s2)" using t'_def t''_def
t_small_step_fun_increase_time by blast
qed
next
assume "c1 = SKIP"
thus ?thesis using rel_pow.cases by fastforce
qed
qed auto
qed
end |
(* Title: ZF/Resid/Residuals.thy
Author: Ole Rasmussen
Copyright 1995 University of Cambridge
*)
theory Residuals imports Substitution begin
consts
Sres :: "i"
abbreviation
"residuals(u,v,w) == <u,v,w> \<in> Sres"
inductive
domains "Sres" \<subseteq> "redexes*redexes*redexes"
intros
Res_Var: "n \<in> nat ==> residuals(Var(n),Var(n),Var(n))"
Res_Fun: "[|residuals(u,v,w)|]==>
residuals(Fun(u),Fun(v),Fun(w))"
Res_App: "[|residuals(u1,v1,w1);
residuals(u2,v2,w2); b \<in> bool|]==>
residuals(App(b,u1,u2),App(0,v1,v2),App(b,w1,w2))"
Res_redex: "[|residuals(u1,v1,w1);
residuals(u2,v2,w2); b \<in> bool|]==>
residuals(App(b,Fun(u1),u2),App(1,Fun(v1),v2),w2/w1)"
type_intros subst_type nat_typechecks redexes.intros bool_typechecks
definition
res_func :: "[i,i]=>i" (infixl "|>" 70) where
"u |> v == THE w. residuals(u,v,w)"
subsection\<open>Setting up rule lists\<close>
declare Sres.intros [intro]
declare Sreg.intros [intro]
declare subst_type [intro]
inductive_cases [elim!]:
"residuals(Var(n),Var(n),v)"
"residuals(Fun(t),Fun(u),v)"
"residuals(App(b, u1, u2), App(0, v1, v2),v)"
"residuals(App(b, u1, u2), App(1, Fun(v1), v2),v)"
"residuals(Var(n),u,v)"
"residuals(Fun(t),u,v)"
"residuals(App(b, u1, u2), w,v)"
"residuals(u,Var(n),v)"
"residuals(u,Fun(t),v)"
"residuals(w,App(b, u1, u2),v)"
inductive_cases [elim!]:
"Var(n) \<Longleftarrow> u"
"Fun(n) \<Longleftarrow> u"
"u \<Longleftarrow> Fun(n)"
"App(1,Fun(t),a) \<Longleftarrow> u"
"App(0,t,a) \<Longleftarrow> u"
inductive_cases [elim!]:
"Fun(t) \<in> redexes"
declare Sres.intros [simp]
subsection\<open>residuals is a partial function\<close>
lemma residuals_function [rule_format]:
"residuals(u,v,w) ==> \<forall>w1. residuals(u,v,w1) \<longrightarrow> w1 = w"
by (erule Sres.induct, force+)
lemma residuals_intro [rule_format]:
"u \<sim> v ==> regular(v) \<longrightarrow> (\<exists>w. residuals(u,v,w))"
by (erule Scomp.induct, force+)
lemma comp_resfuncD:
"[| u \<sim> v; regular(v) |] ==> residuals(u, v, THE w. residuals(u, v, w))"
apply (frule residuals_intro, assumption, clarify)
apply (subst the_equality)
apply (blast intro: residuals_function)+
done
subsection\<open>Residual function\<close>
lemma res_Var [simp]: "n \<in> nat ==> Var(n) |> Var(n) = Var(n)"
by (unfold res_func_def, blast)
lemma res_Fun [simp]:
"[|s \<sim> t; regular(t)|]==> Fun(s) |> Fun(t) = Fun(s |> t)"
apply (unfold res_func_def)
apply (blast intro: comp_resfuncD residuals_function)
done
lemma res_App [simp]:
"[|s \<sim> u; regular(u); t \<sim> v; regular(v); b \<in> bool|]
==> App(b,s,t) |> App(0,u,v) = App(b, s |> u, t |> v)"
apply (unfold res_func_def)
apply (blast dest!: comp_resfuncD intro: residuals_function)
done
lemma res_redex [simp]:
"[|s \<sim> u; regular(u); t \<sim> v; regular(v); b \<in> bool|]
==> App(b,Fun(s),t) |> App(1,Fun(u),v) = (t |> v)/ (s |> u)"
apply (unfold res_func_def)
apply (blast elim!: redexes.free_elims dest!: comp_resfuncD
intro: residuals_function)
done
lemma resfunc_type [simp]:
"[|s \<sim> t; regular(t)|]==> regular(t) \<longrightarrow> s |> t \<in> redexes"
by (erule Scomp.induct, auto)
subsection\<open>Commutation theorem\<close>
lemma sub_comp [simp]: "u \<Longleftarrow> v \<Longrightarrow> u \<sim> v"
by (erule Ssub.induct, simp_all)
lemma sub_preserve_reg [rule_format, simp]:
"u \<Longleftarrow> v \<Longrightarrow> regular(v) \<longrightarrow> regular(u)"
by (erule Ssub.induct, auto)
lemma residuals_lift_rec: "[|u \<sim> v; k \<in> nat|]==> regular(v)\<longrightarrow> (\<forall>n \<in> nat.
lift_rec(u,n) |> lift_rec(v,n) = lift_rec(u |> v,n))"
apply (erule Scomp.induct, safe)
apply (simp_all add: lift_rec_Var subst_Var lift_subst)
done
lemma residuals_subst_rec:
"u1 \<sim> u2 ==> \<forall>v1 v2. v1 \<sim> v2 \<longrightarrow> regular(v2) \<longrightarrow> regular(u2) \<longrightarrow>
(\<forall>n \<in> nat. subst_rec(v1,u1,n) |> subst_rec(v2,u2,n) =
subst_rec(v1 |> v2, u1 |> u2,n))"
apply (erule Scomp.induct, safe)
apply (simp_all add: lift_rec_Var subst_Var residuals_lift_rec)
apply (drule_tac psi = "\<forall>x. P(x)" for P in asm_rl)
apply (simp add: substitution)
done
lemma commutation [simp]:
"[|u1 \<sim> u2; v1 \<sim> v2; regular(u2); regular(v2)|]
==> (v1/u1) |> (v2/u2) = (v1 |> v2)/(u1 |> u2)"
by (simp add: residuals_subst_rec)
subsection\<open>Residuals are comp and regular\<close>
lemma residuals_preserve_comp [rule_format, simp]:
"u \<sim> v ==> \<forall>w. u \<sim> w \<longrightarrow> v \<sim> w \<longrightarrow> regular(w) \<longrightarrow> (u|>w) \<sim> (v|>w)"
by (erule Scomp.induct, force+)
lemma residuals_preserve_reg [rule_format, simp]:
"u \<sim> v ==> regular(u) \<longrightarrow> regular(v) \<longrightarrow> regular(u|>v)"
apply (erule Scomp.induct, auto)
done
subsection\<open>Preservation lemma\<close>
lemma union_preserve_comp: "u \<sim> v ==> v \<sim> (u \<squnion> v)"
by (erule Scomp.induct, simp_all)
lemma preservation [rule_format]:
"u \<sim> v ==> regular(v) \<longrightarrow> u|>v = (u \<squnion> v)|>v"
apply (erule Scomp.induct, safe)
apply (drule_tac [3] psi = "Fun (u) |> v = w" for u v w in asm_rl)
apply (auto simp add: union_preserve_comp comp_sym_iff)
done
declare sub_comp [THEN comp_sym, simp]
subsection\<open>Prism theorem\<close>
(* Having more assumptions than needed -- removed below *)
lemma prism_l [rule_format]:
"v \<Longleftarrow> u \<Longrightarrow>
regular(u) \<longrightarrow> (\<forall>w. w \<sim> v \<longrightarrow> w \<sim> u \<longrightarrow>
w |> u = (w|>v) |> (u|>v))"
by (erule Ssub.induct, force+)
lemma prism: "[|v \<Longleftarrow> u; regular(u); w \<sim> v|] ==> w |> u = (w|>v) |> (u|>v)"
apply (rule prism_l)
apply (rule_tac [4] comp_trans, auto)
done
subsection\<open>Levy's Cube Lemma\<close>
lemma cube: "[|u \<sim> v; regular(v); regular(u); w \<sim> u|]==>
(w|>u) |> (v|>u) = (w|>v) |> (u|>v)"
apply (subst preservation [of u], assumption, assumption)
apply (subst preservation [of v], erule comp_sym, assumption)
apply (subst prism [symmetric, of v])
apply (simp add: union_r comp_sym_iff)
apply (simp add: union_preserve_regular comp_sym_iff)
apply (erule comp_trans, assumption)
apply (simp add: prism [symmetric] union_l union_preserve_regular
comp_sym_iff union_sym)
done
subsection\<open>paving theorem\<close>
lemma paving: "[|w \<sim> u; w \<sim> v; regular(u); regular(v)|]==>
\<exists>uv vu. (w|>u) |> vu = (w|>v) |> uv & (w|>u) \<sim> vu \<and>
regular(vu) & (w|>v) \<sim> uv \<and> regular(uv)"
apply (subgoal_tac "u \<sim> v")
apply (safe intro!: exI)
apply (rule cube)
apply (simp_all add: comp_sym_iff)
apply (blast intro: residuals_preserve_comp comp_trans comp_sym)+
done
end
|
(* Author: Tobias Nipkow *)
section "Deterministic Online and Offline Algorithms"
theory On_Off
imports Complex_Main
begin
type_synonym ('s,'r,'a) alg_off = "'s \<Rightarrow> 'r list \<Rightarrow> 'a list"
type_synonym ('s,'is,'r,'a) alg_on = "('s \<Rightarrow> 'is) * ('s * 'is \<Rightarrow> 'r \<Rightarrow> 'a * 'is)"
locale On_Off =
fixes step :: "'state \<Rightarrow> 'request \<Rightarrow> 'answer \<Rightarrow> 'state"
fixes t :: "'state \<Rightarrow> 'request \<Rightarrow> 'answer \<Rightarrow> nat"
fixes wf :: "'state \<Rightarrow> 'request list \<Rightarrow> bool"
begin
fun T :: "'state \<Rightarrow> 'request list \<Rightarrow> 'answer list \<Rightarrow> nat" where
"T s [] [] = 0" |
"T s (r#rs) (a#as) = t s r a + T (step s r a) rs as"
definition Step ::
"('state , 'istate, 'request, 'answer)alg_on
\<Rightarrow> 'state * 'istate \<Rightarrow> 'request \<Rightarrow> 'state * 'istate"
where
"Step A s r = (let (a,is') = snd A s r in (step (fst s) r a, is'))"
fun config' :: "('state,'is,'request,'answer) alg_on \<Rightarrow> ('state*'is) \<Rightarrow> 'request list
\<Rightarrow> ('state * 'is)" where
"config' A s [] = s" |
"config' A s (r#rs) = config' A (Step A s r) rs"
lemma config'_snoc: "config' A s (rs@[r]) = Step A (config' A s rs) r"
apply(induct rs arbitrary: s) by simp_all
lemma config'_append2: "config' A s (xs@ys) = config' A (config' A s xs) ys"
apply(induct xs arbitrary: s) by simp_all
lemma config'_induct: "P (fst init) \<Longrightarrow> (\<And>s q a. P s \<Longrightarrow> P (step s q a))
\<Longrightarrow> P (fst (config' A init rs))"
apply (induct rs arbitrary: init) by(simp_all add: Step_def split: prod.split)
abbreviation config where
"config A s0 rs == config' A (s0, fst A s0) rs"
lemma config_snoc: "config A s (rs@[r]) = Step A (config A s rs) r"
using config'_snoc by metis
lemma config_append: "config A s (xs@ys) = config' A (config A s xs) ys"
using config'_append2 by metis
lemma config_induct: "P s0 \<Longrightarrow> (\<And>s q a. P s \<Longrightarrow> P (step s q a)) \<Longrightarrow> P (fst (config A s0 qs))"
using config'_induct[of P "(s0, fst A s0)" ] by auto
fun T_on' :: "('state,'is,'request,'answer) alg_on \<Rightarrow> ('state*'is) \<Rightarrow> 'request list \<Rightarrow> nat" where
"T_on' A s [] = 0" |
"T_on' A s (r#rs) = (t (fst s) r (fst (snd A s r))) + T_on' A (Step A s r) rs"
lemma T_on'_append: "T_on' A s (xs@ys) = T_on' A s xs + T_on' A (config' A s xs) ys"
apply(induct xs arbitrary: s) by simp_all
abbreviation T_on'' :: "('state,'is,'request,'answer) alg_on \<Rightarrow> 'state \<Rightarrow> 'request list \<Rightarrow> nat" where
"T_on'' A s rs == T_on' A (s,fst A s) rs"
lemma T_on_append: "T_on'' A s (xs@ys) = T_on'' A s xs + T_on' A (config A s xs) ys"
by(rule T_on'_append)
abbreviation "T_on_n A s0 xs n == T_on' A (config A s0 (take n xs)) [xs!n]"
lemma T_on__as_sum: "T_on'' A s0 rs = sum (T_on_n A s0 rs) {..<length rs} "
apply(induct rs rule: rev_induct)
by(simp_all add: T_on'_append nth_append)
fun off2 :: "('state,'is,'request,'answer) alg_on \<Rightarrow> ('state * 'is,'request,'answer) alg_off" where
"off2 A s [] = []" |
"off2 A s (r#rs) = fst (snd A s r) # off2 A (Step A s r) rs"
abbreviation off :: "('state,'is,'request,'answer) alg_on \<Rightarrow> ('state,'request,'answer) alg_off" where
"off A s0 \<equiv> off2 A (s0, fst A s0)"
abbreviation T_off :: "('state,'request,'answer) alg_off \<Rightarrow> 'state \<Rightarrow> 'request list \<Rightarrow> nat" where
"T_off A s0 rs == T s0 rs (A s0 rs)"
abbreviation T_on :: "('state,'is,'request,'answer) alg_on \<Rightarrow> 'state \<Rightarrow> 'request list \<Rightarrow> nat" where
"T_on A == T_off (off A)"
lemma T_on_on': "T_off (\<lambda>s0. (off2 A (s0, x))) s0 qs = T_on' A (s0,x) qs"
apply(induct qs arbitrary: s0 x)
by(simp_all add: Step_def split: prod.split)
lemma T_on_on'': "T_on A s0 qs = T_on'' A s0 qs"
using T_on_on'[where x="fst A s0", of s0 qs A] by(auto)
lemma T_on_as_sum: "T_on A s0 rs = sum (T_on_n A s0 rs) {..<length rs} "
using T_on__as_sum T_on_on'' by metis
definition T_opt :: "'state \<Rightarrow> 'request list \<Rightarrow> nat" where
"T_opt s rs = Inf {T s rs as | as. size as = size rs}"
definition compet :: "('state,'is,'request,'answer) alg_on \<Rightarrow> real \<Rightarrow> 'state set \<Rightarrow> bool" where
"compet A c S = (\<forall>s\<in>S. \<exists>b \<ge> 0. \<forall>rs. wf s rs \<longrightarrow> real(T_on A s rs) \<le> c * T_opt s rs + b)"
lemma length_off[simp]: "length(off2 A s rs) = length rs"
by (induction rs arbitrary: s) (auto split: prod.split)
lemma compet_mono: assumes "compet A c S0" and "c \<le> c'"
shows "compet A c' S0"
proof (unfold compet_def, auto)
let ?compt = "\<lambda>s0 rs b (c::real). T_on A s0 rs \<le> c * T_opt s0 rs + b"
fix s0 assume "s0 \<in> S0"
with assms(1) obtain b where "b \<ge> 0" and 1: "\<forall>rs. wf s0 rs \<longrightarrow> ?compt s0 rs b c"
by(auto simp: compet_def)
have "\<forall>rs. wf s0 rs \<longrightarrow> ?compt s0 rs b c'"
proof safe
fix rs
assume wf: "wf s0 rs"
from 1 wf have "?compt s0 rs b c" by blast
thus "?compt s0 rs b c'"
using 1 mult_right_mono[OF assms(2) of_nat_0_le_iff[of "T_opt s0 rs"]]
by arith
qed
thus "\<exists>b\<ge>0. \<forall>rs. wf s0 rs \<longrightarrow> ?compt s0 rs b c'" using \<open>b\<ge>0\<close> by(auto)
qed
lemma competE: fixes c :: real
assumes "compet A c S0" "c \<ge> 0" "\<forall>s0 rs. size(aoff s0 rs) = length rs" "s0\<in>S0"
shows "\<exists>b\<ge>0. \<forall>rs. wf s0 rs \<longrightarrow> T_on A s0 rs \<le> c * T_off aoff s0 rs + b"
proof -
from assms(1,4) obtain b where "b\<ge>0" and
1: "\<forall>rs. wf s0 rs \<longrightarrow> T_on A s0 rs \<le> c * T_opt s0 rs + b"
by(auto simp add: compet_def)
{ fix rs
assume "wf s0 rs"
then have 2: "real(T_on A s0 rs) \<le> c * Inf {T s0 rs as | as. size as = size rs} + b"
(is "_ \<le> _ * real(Inf ?T) + _")
using 1 by(auto simp add: T_opt_def)
have "Inf ?T \<le> T_off aoff s0 rs"
using assms(3) by (intro cInf_lower) auto
from mult_left_mono[OF of_nat_le_iff[THEN iffD2, OF this] assms(2)]
have "T_on A s0 rs \<le> c * T_off aoff s0 rs + b" using 2 by arith
}
thus ?thesis using \<open>b\<ge>0\<close> by(auto simp: compet_def)
qed
end
end
|
SUBROUTINE IN_SKYC ( skysym, condtn, iret )
C************************************************************************
C* IN_SKYC *
C* *
C* This subroutine decodes the input for the sky coverage symbol. *
C* The input must be in the form: *
C* : size : width : type *
C* If the user has entered a condition, it must precede the first : *
C* *
C* IN_SKYC ( SKYSYM, CONDTN, IRET ) *
C* *
C* Input parameters: *
C* SKYSYM CHAR* Sky coverage symbol input *
C* *
C* Output parameters: *
C* CONDTN CHAR* Condition *
C* IRET INTEGER Return code *
C* 0 = normal return *
C* *
C** *
C* Log: *
C* S. Schotz/GSC 4/90 GEMPAK5 *
C* S. Schotz/GSC 7/90 Changed order of parts *
C* M. desJardins/NMC 10/91 Clean up; elim calls with substrings *
C* M. desJardins/NMC 11/91 Change * to : and retufn condition *
C************************************************************************
CHARACTER*(*) skysym, condtn
C*
REAL rarr (3)
CHARACTER symbol*24
C------------------------------------------------------------------------
iret = 0
C
C* Check for colon.
C
ipos = INDEX ( skysym, ':' )
IF ( ipos .eq. 0 ) THEN
condtn = skysym
RETURN
ELSE
condtn = skysym ( 1:ipos-1 )
symbol = skysym ( ipos+1: )
END IF
C
C* Decode size, width, and type.
C
CALL ST_RLST ( symbol, ':', 0. , 3, rarr, num, ier )
size = rarr (1)
iwidth = NINT ( rarr (2) )
itype = rarr (3)
CALL GSSKY ( size, itype, iwidth, ier )
C*
RETURN
END
|
function b = triangulation_isequal(face,faced)
% triangulation_isequal - true if two triangulations are equals
%
% b = triangulation_isequal(face,faced)
%
% Copyright (c) 2008 Gabriel Peyre
I = setdiff(sort(face)',sort(faced)', 'rows');
b = isempty(I); |
Require Import List Morphisms Lia.
Require Import Undecidability.Synthetic.DecidabilityFacts Undecidability.Synthetic.EnumerabilityFacts Undecidability.Shared.partial Undecidability.Shared.embed_nat Undecidability.Synthetic.FinitenessFacts.
Export EmbedNatNotations.
(** ** Semi-decidability *)
Definition equiv_sdec {X} := fun (f g : X -> nat -> bool) => forall x, (exists n, f x n = true) <-> exists n, g x n = true.
Instance Proper_semi_decider {X} :
Proper (@equiv_sdec X ==> pointwise_relation X iff ==> iff ) (@semi_decider X).
Proof.
intros f g H1 p q H2. red in H1, H2.
unfold semi_decider.
split; intros H x; cbn in H1.
- now rewrite <- H2, H, H1.
- now rewrite H2, H, H1.
Qed.
Instance Proper_semi_decidable {X} :
Proper (pointwise_relation X iff ==> iff) (@semi_decidable X).
Proof.
intros p q H2.
split; intros [f H]; exists f; red.
- intros x. now rewrite <- (H2 x).
- intros x. now rewrite H2.
Qed.
Lemma semi_decider_ext {X} {p q : X -> Prop} {f g} :
semi_decider f p -> semi_decider g q -> equiv_sdec f g -> p ≡{_} q.
Proof.
unfold semi_decider. cbn.
intros Hp Hq E x. red in E.
now rewrite Hp, E, Hq.
Qed.
Lemma semi_decidable_part_iff {X} {p : X -> Prop} {Part : partiality}:
semi_decidable p <-> exists Y (f : X -> part Y), forall x, p x <-> exists y, f x =! y.
Proof.
split.
- intros [f Hf].
exists nat, (fun x => mu_tot (f x)). intros x.
rewrite (Hf x). split; intros [n H].
+ eapply mu_tot_ter in H as [y H]. eauto.
+ eapply mu_tot_hasvalue in H as [H _]. eauto.
- intros (Y & f & Hf). exists (fun x n => if seval (f x) n is Some _ then true else false).
intros x. rewrite Hf. split.
+ intros [y H]. eapply seval_hasvalue in H as [n H].
exists n. now rewrite H.
+ intros [n H]. destruct seval eqn:E; inversion H.
eexists. eapply seval_hasvalue. eauto.
Qed.
Lemma forall_neg_exists_iff (f : nat -> bool) :
(forall n, f n = false) <-> ~ exists n, f n = true.
Proof.
split.
- intros H [n Hn]. rewrite H in Hn. congruence.
- intros H n. destruct (f n) eqn:E; try reflexivity.
destruct H. eauto.
Qed.
Lemma semi_decider_co_semi_decider {X} (p : X -> Prop) f :
semi_decider f p -> co_semi_decider f (complement p).
Proof.
intros Hf.
red in Hf. unfold complement. intros x. rewrite Hf.
now rewrite forall_neg_exists_iff.
Qed.
Lemma semi_decidable_co_semi_decidable {X} (p : X -> Prop) :
semi_decidable p -> co_semi_decidable (complement p).
Proof.
intros [f Hf]. eapply ex_intro, semi_decider_co_semi_decider, Hf.
Qed.
Lemma co_semi_decidable_stable :
forall X (p : X -> Prop), co_semi_decidable p -> stable p.
Proof.
intros X p [f Hf] x Hx.
eapply Hf. eapply forall_neg_exists_iff. red in Hf. rewrite Hf, forall_neg_exists_iff in Hx.
tauto.
Qed.
Lemma decider_semi_decider {X} {p : X -> Prop} f :
decider f p -> semi_decider (fun x n => f x) p.
Proof.
intros H x.
unfold decider, reflects in H.
rewrite H. now firstorder; econstructor.
Qed.
Lemma decider_co_semi_decider {X} {p : X -> Prop} f :
decider f p -> co_semi_decider (fun x n => negb (f x)) p.
Proof.
intros H x.
unfold decider, reflects in H.
rewrite H. split.
- now intros -> _.
- intros H0. destruct (f x); cbn in *; now try rewrite (H0 0).
Qed.
Lemma decidable_semi_decidable {X} {p : X -> Prop} :
decidable p -> semi_decidable p.
Proof.
intros [f H]. eapply ex_intro, decider_semi_decider, H.
Qed.
Lemma decidable_compl_semi_decidable {X} {p : X -> Prop} :
decidable p -> semi_decidable (complement p).
Proof.
intros H.
now eapply decidable_semi_decidable, decidable_complement.
Qed.
Lemma decidable_co_semi_decidable {X} {p : X -> Prop} :
decidable p -> co_semi_decidable p.
Proof.
intros [f H]. eapply ex_intro, decider_co_semi_decider, H.
Qed.
Lemma semi_decidable_projection_iff X (p : X -> Prop) :
semi_decidable p <-> exists (q : nat * X -> Prop), decidable q /\ forall x, p x <-> exists n, q (n, x).
Proof.
split.
- intros [d Hd].
exists (fun '(n, x) => d x n = true). split.
+ exists (fun '(n,x) => d x n). intros [n x]. firstorder congruence.
+ intros x. eapply Hd.
- intros (q & [f Hf] & Hq).
exists (fun x n => f (n, x)). unfold semi_decider, decider, reflects in *.
intros x. rewrite Hq. now setoid_rewrite Hf.
Qed.
Lemma semi_decider_and {X} {p q : X -> Prop} f g :
semi_decider f p -> semi_decider g q -> semi_decider (fun x n => andb (existsb (f x) (seq 0 n)) (existsb (g x) (seq 0 n))) (fun x => p x /\ q x).
Proof.
intros Hf Hg x.
red in Hf, Hg |- *. rewrite Hf, Hg.
setoid_rewrite Bool.andb_true_iff.
setoid_rewrite existsb_exists.
repeat setoid_rewrite in_seq. cbn.
clear.
split.
- intros [[n1 Hn1] [n2 Hn2]].
exists (1 + n1 + n2). firstorder lia.
- firstorder.
Qed.
Lemma semi_decidable_and {X} {p q : X -> Prop} :
semi_decidable p -> semi_decidable q -> semi_decidable (fun x => p x /\ q x).
Proof.
intros [f Hf] [g Hg]. eapply ex_intro, semi_decider_and; eauto.
Qed.
Lemma reflects_cases {P} {b} :
reflects b P -> b = true /\ P \/ b = false /\ ~ P.
Proof.
destruct b; firstorder congruence.
Qed.
Lemma semi_decider_or {X} {p q : X -> Prop} f g :
semi_decider f p -> semi_decider g q -> semi_decider (fun x n => orb (f x n) (g x n)) (fun x => p x \/ q x).
Proof.
intros Hf Hg.
red in Hf, Hg |- *. intros x.
rewrite Hf, Hg.
setoid_rewrite Bool.orb_true_iff.
clear. firstorder.
Qed.
Lemma semi_decidable_or {X} {p q : X -> Prop} :
semi_decidable p -> semi_decidable q -> semi_decidable (fun x => p x \/ q x).
Proof.
intros [f Hf] [g Hg]. eapply ex_intro, semi_decider_or; eauto.
Qed.
Lemma semi_decidable_ex {X} {p : nat -> X -> Prop} :
semi_decidable (fun pa => p (fst pa) (snd pa)) -> semi_decidable (fun x => exists n, p n x).
Proof.
intros [f Hf].
eapply semi_decidable_projection_iff.
exists (fun '(n,x) => (fun! ⟨n1,n2⟩ => f (n1, x) n2 = true) n).
split.
- eapply dec_decidable. intros (n, x).
destruct unembed. exact _.
- intros x. setoid_rewrite (Hf (_, x)).
split.
+ intros (n1 & n2 & H). exists ⟨n1, n2⟩. now rewrite embedP.
+ intros (n & H). destruct unembed as [n1 n2].
exists n1, n2. eauto.
Qed.
Lemma co_semi_decider_and {X} {p q : X -> Prop} f g :
co_semi_decider f p -> co_semi_decider g q -> co_semi_decider (fun x n => orb (f x n) (g x n)) (fun x => p x /\ q x).
Proof.
intros Hf Hg x. red in Hf, Hg. rewrite Hf, Hg.
setoid_rewrite Bool.orb_false_iff.
clear. firstorder.
Qed.
Lemma co_semi_decidable_and {X} {p q : X -> Prop} :
co_semi_decidable p -> co_semi_decidable q -> co_semi_decidable (fun x => p x /\ q x).
Proof.
intros [f Hf] [g Hg]. eapply ex_intro, co_semi_decider_and; eauto.
Qed.
Lemma semi_decider_AC X g (R : X -> nat -> Prop) :
semi_decider g (uncurry R) ->
(forall x, exists y, R x y) ->
∑ f : X -> nat, forall x, R x (f x).
Proof.
intros Hg Htot'. red in Hg. unfold uncurry in *.
pose (R' x := fun! ⟨n,m⟩ => g (x,n) m = true).
assert (Htot : forall x, exists n, R' x n). {
subst R'. intros x. destruct (Htot' x) as (n & [m H] % (Hg (_, _))).
exists ⟨n,m⟩. now rewrite embedP.
}
assert (Hdec : decider (fun '(x, nm) => let (n, m) := unembed nm in g (x, n) m) (uncurry R')). {
unfold R'. unfold uncurry. intros (x, nm). destruct (unembed nm) as (n, m).
destruct g; firstorder congruence.
}
eapply (decider_AC _ _ _ Hdec) in Htot as [f' Hf'].
exists (fun x => (fun! ⟨n, m⟩ => n) (f' x)).
intros x. subst R'. specialize (Hf' x). cbn in Hf'.
destruct (unembed (f' x)). eapply (Hg (_, _)). eauto.
Qed.
(* Lemma sdec_compute_lor {X} {p q : X -> Prop} :
semi_decidable p -> semi_decidable q -> (forall x, p x \/ q x) -> exists f : X -> bool, forall x, if f x then p x else q x.
Proof.
intros [f_p Hp] [f_q Hq] Ho.
unshelve eexists.
- refine (fun x => let (n, H) := mu_nat (P := fun n => orb (f_p x n) (f_q x n) = true) (ltac:(cbn; decide equality)) _ in f_p x n).
destruct (Ho x) as [[n H] % Hp | [n H] % Hq].
+ exists n. now rewrite H.
+ exists n. rewrite H. now destruct f_p.
- intros x. cbn -[mu_nat]. destruct mu_nat.
specialize (Hp x). specialize (Hq x).
destruct (f_p) eqn:E1. eapply Hp. eauto.
destruct (f_q) eqn:E2. eapply Hq. eauto.
inversion e.
Qed.
*)
(* ** Other *)
Lemma d_semi_decidable_impl {X} {p q : X -> Prop} :
decidable p -> semi_decidable q -> semi_decidable (fun x => p x -> q x).
Proof.
intros [f Hf] [g Hg].
exists (fun x n => if f x then g x n else true).
intros x. split.
- intros H. destruct (reflects_cases (Hf x)) as [ [-> H2] | [-> H2] ].
+ firstorder.
+ now exists 0.
- intros [n H]. revert H.
destruct (reflects_cases (Hf x)) as [ [-> H2] | [-> H2]]; intros H.
+ firstorder.
+ firstorder.
Qed.
Lemma d_co_semi_decidable_impl {X} {p q : X -> Prop} :
decidable p -> semi_decidable (complement q) -> semi_decidable (complement (fun x => p x -> q x)).
Proof.
intros [f Hf] [g Hg].
exists (fun x n => if f x then g x n else false).
intros x. split.
- intros H. destruct (reflects_cases (Hf x)) as [ [-> H2] | [-> H2] ].
+ red in H. firstorder.
+ firstorder.
- intros [n H]. revert H.
destruct (reflects_cases (Hf x)) as [ [-> H2] | [-> H2]]; intros H.
+ firstorder.
+ firstorder congruence.
Qed.
Lemma co_semi_decidable_impl {X} {p q : X -> Prop} :
(* (forall x, ~~ p x -> p x) -> *)
semi_decidable (complement (complement p)) -> decidable q -> semi_decidable (complement (fun x => p x -> q x)).
Proof.
intros [f Hf] [g Hg].
exists (fun x n => if g x then false else f x n).
intros x. split.
- intros H. destruct (reflects_cases (Hg x)) as [ [-> H2] | [-> H2] ].
+ firstorder.
+ eapply Hf. firstorder.
- intros [n H]. revert H.
destruct (reflects_cases (Hg x)) as [ [-> H2] | [-> H2]]; intros H.
+ congruence.
+ intros ?. firstorder.
Qed.
Lemma semi_decidable_impl {X} {p q : X -> Prop} :
semi_decidable (complement p) -> decidable q -> semi_decidable (fun x => p x -> q x).
Proof.
intros [f Hf] [g Hg].
exists (fun x n => if g x then true else f x n).
intros x. split.
- intros H. destruct (reflects_cases (Hg x)) as [ [-> H2] | [-> H2] ].
+ now exists 0.
+ eapply Hf. firstorder.
- intros [n H]. revert H.
destruct (reflects_cases (Hg x)) as [ [-> H2] | [-> H2]]; intros H.
+ eauto.
+ intros. firstorder.
Qed.
Lemma enumerator_semi_decider {X} {p : X -> Prop} d f :
decider d (eq_on X) -> enumerator f p -> semi_decider (fun x n => if f n is Some y then d (x,y) else false) p.
Proof.
intros Hd Hf x. red in Hf. rewrite Hf. split.
- intros [n Hn]. exists n.
rewrite Hn. now eapply Hd.
- intros [n Hn]. exists n.
destruct (f n); inversion Hn.
eapply Hd in Hn. now subst.
Qed.
Lemma enumerable_semi_decidable {X} {p : X -> Prop} :
discrete X -> enumerable p -> semi_decidable p.
Proof.
unfold enumerable, enumerator.
intros [d Hd] [f Hf].
eexists. eapply enumerator_semi_decider; eauto.
Qed.
Lemma semi_decider_enumerator {X} {p : X -> Prop} e f :
enumeratorᵗ e X -> semi_decider f p ->
enumerator (fun! ⟨n,m⟩ => if e n is Some x then if f x m then Some x else None else None) p.
Proof.
intros He Hf x. rewrite (Hf x). split.
- intros [n Hn]. destruct (He x) as [m Hm].
exists (embed (m,n)). now rewrite embedP, Hm, Hn.
- intros [mn Hmn]. destruct (unembed mn) as (m, n).
destruct (e m) as [x'|]; try congruence.
destruct (f x' n) eqn:E; inversion Hmn. subst.
exists n. exact E.
Qed.
Lemma semi_decidable_enumerable {X} {p : X -> Prop} :
enumerableᵗ X -> semi_decidable p -> enumerable p.
Proof.
unfold semi_decidable, semi_decider.
intros [e He] [f Hf].
now eapply ex_intro, semi_decider_enumerator.
Qed.
|
module ExactLengthDec
import Data.Vect
import Decidable.Equality
%default total
{-
interface DecEq ty where
decEq : (val1 : ty) -> (val2 : ty) -> Dec (val1 = val2)
data Dec: (prop : Type) -> Type where
Yes : (prf : prop) -> Dec prop
No : (contra : prop -> Void) -> Dec prop
-}
exactLength : { m : _ } -> (len : Nat) -> Vect m a -> Maybe (Vect len a)
exactLength len input = case decEq m len of
Yes Refl => Just input
No contra => Nothing
|
function circle_trajectory %(p1, p2, p3)
close all
p1=rand(1,3);p2=rand(1,3);p3=rand(1,3);
[pc,r,v1,v2] = circlefit3d(p1,p2,p3);
plot3(p1(:,1),p1(:,2),p1(:,3),'ro');hold on;plot3(p2(:,1),p2(:,2),p2(:,3),'go');plot3(p3(:,1),p3(:,2),p3(:,3),'bo');
x1 = (p1-pc);
x1 = x1/norm(x1);
phi1 = dot(v1,x1);
x2 = (p2-pc);
x2 = x2/norm(x2);
phi2 = dot(v1,x2);
angle = [phi1 phi2];
%angle = 0:0.1:2*pi;
%angle = pi/4:0.1:pi/2;
for i=1:length(angle)
a = angle(i);
x = pc(:,1)+cos(a)*r.*v1(:,1)+sin(a)*r.*v2(:,1);
y = pc(:,2)+cos(a)*r.*v1(:,2)+sin(a)*r.*v2(:,2);
z = pc(:,3)+cos(a)*r.*v1(:,3)+sin(a)*r.*v2(:,3);
plot3(x,y,z,'r+');
end
axis equal;grid on;rotate3d on;
% fit a circle with three points
%[pm, r, v1, v2] = circlefit3d(p1', p2', p3');
|
/-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Anne Baanen
-/
import logic.function.iterate
import order.galois_connection
import order.hom.basic
/-!
# Lattice structure on order homomorphisms
This file defines the lattice structure on order homomorphisms, which are bundled
monotone functions.
## Main definitions
* `order_hom.complete_lattice`: if `β` is a complete lattice, so is `α →o β`
## Tags
monotone map, bundled morphism
-/
namespace order_hom
variables {α β : Type*}
section preorder
variables [preorder α]
@[simps]
instance [semilattice_sup β] : has_sup (α →o β) :=
{ sup := λ f g, ⟨λ a, f a ⊔ g a, f.mono.sup g.mono⟩ }
instance [semilattice_sup β] : semilattice_sup (α →o β) :=
{ sup := has_sup.sup,
le_sup_left := λ a b x, le_sup_left,
le_sup_right := λ a b x, le_sup_right,
sup_le := λ a b c h₀ h₁ x, sup_le (h₀ x) (h₁ x),
.. (_ : partial_order (α →o β)) }
@[simps]
instance [semilattice_inf β] : has_inf (α →o β) :=
{ inf := λ f g, ⟨λ a, f a ⊓ g a, f.mono.inf g.mono⟩ }
instance [semilattice_inf β] : semilattice_inf (α →o β) :=
{ inf := (⊓),
.. (_ : partial_order (α →o β)),
.. (dual_iso α β).symm.to_galois_insertion.lift_semilattice_inf }
instance [lattice β] : lattice (α →o β) :=
{ .. (_ : semilattice_sup (α →o β)),
.. (_ : semilattice_inf (α →o β)) }
@[simps]
instance [preorder β] [order_bot β] : has_bot (α →o β) :=
{ bot := const α ⊥ }
instance [preorder β] [order_bot β] : order_bot (α →o β) :=
{ bot := ⊥,
bot_le := λ a x, bot_le }
@[simps]
instance [preorder β] [order_top β] : has_top (α →o β) :=
{ top := const α ⊤ }
instance [preorder β] [order_top β] : order_top (α →o β) :=
{ top := ⊤,
le_top := λ a x, le_top }
instance [complete_lattice β] : has_Inf (α →o β) :=
{ Inf := λ s, ⟨λ x, ⨅ f ∈ s, (f : _) x, λ x y h, binfi_le_binfi (λ f _, f.mono h)⟩ }
@[simp] lemma Inf_apply [complete_lattice β] (s : set (α →o β)) (x : α) :
Inf s x = ⨅ f ∈ s, (f : _) x := rfl
lemma infi_apply {ι : Sort*} [complete_lattice β] (f : ι → α →o β) (x : α) :
(⨅ i, f i) x = ⨅ i, f i x :=
(Inf_apply _ _).trans infi_range
@[simp, norm_cast] lemma coe_infi {ι : Sort*} [complete_lattice β] (f : ι → α →o β) :
((⨅ i, f i : α →o β) : α → β) = ⨅ i, f i :=
funext $ λ x, (infi_apply f x).trans (@_root_.infi_apply _ _ _ _ (λ i, f i) _).symm
instance [complete_lattice β] : has_Sup (α →o β) :=
{ Sup := λ s, ⟨λ x, ⨆ f ∈ s, (f : _) x, λ x y h, bsupr_le_bsupr (λ f _, f.mono h)⟩ }
@[simp] lemma Sup_apply [complete_lattice β] (s : set (α →o β)) (x : α) :
Sup s x = ⨆ f ∈ s, (f : _) x := rfl
lemma supr_apply {ι : Sort*} [complete_lattice β] (f : ι → α →o β) (x : α) :
(⨆ i, f i) x = ⨆ i, f i x :=
(Sup_apply _ _).trans supr_range
@[simp, norm_cast] lemma coe_supr {ι : Sort*} [complete_lattice β] (f : ι → α →o β) :
((⨆ i, f i : α →o β) : α → β) = ⨆ i, f i :=
funext $ λ x, (supr_apply f x).trans (@_root_.supr_apply _ _ _ _ (λ i, f i) _).symm
instance [complete_lattice β] : complete_lattice (α →o β) :=
{ Sup := Sup,
le_Sup := λ s f hf x, le_supr_of_le f (le_supr _ hf),
Sup_le := λ s f hf x, bsupr_le (λ g hg, hf g hg x),
Inf := Inf,
le_Inf := λ s f hf x, le_binfi (λ g hg, hf g hg x),
Inf_le := λ s f hf x, infi_le_of_le f (infi_le _ hf),
.. (_ : lattice (α →o β)),
.. order_hom.order_top,
.. order_hom.order_bot }
lemma iterate_sup_le_sup_iff {α : Type*} [semilattice_sup α] (f : α →o α) :
(∀ n₁ n₂ a₁ a₂, f^[n₁ + n₂] (a₁ ⊔ a₂) ≤ (f^[n₁] a₁) ⊔ (f^[n₂] a₂)) ↔
(∀ a₁ a₂, f (a₁ ⊔ a₂) ≤ (f a₁) ⊔ a₂) :=
begin
split; intros h,
{ exact h 1 0, },
{ intros n₁ n₂ a₁ a₂, have h' : ∀ n a₁ a₂, f^[n] (a₁ ⊔ a₂) ≤ (f^[n] a₁) ⊔ a₂,
{ intros n, induction n with n ih; intros a₁ a₂,
{ refl, },
{ calc f^[n + 1] (a₁ ⊔ a₂) = (f^[n] (f (a₁ ⊔ a₂))) : function.iterate_succ_apply f n _
... ≤ (f^[n] ((f a₁) ⊔ a₂)) : f.mono.iterate n (h a₁ a₂)
... ≤ (f^[n] (f a₁)) ⊔ a₂ : ih _ _
... = (f^[n + 1] a₁) ⊔ a₂ : by rw ← function.iterate_succ_apply, }, },
calc f^[n₁ + n₂] (a₁ ⊔ a₂) = (f^[n₁] (f^[n₂] (a₁ ⊔ a₂))) : function.iterate_add_apply f n₁ n₂ _
... = (f^[n₁] (f^[n₂] (a₂ ⊔ a₁))) : by rw sup_comm
... ≤ (f^[n₁] ((f^[n₂] a₂) ⊔ a₁)) : f.mono.iterate n₁ (h' n₂ _ _)
... = (f^[n₁] (a₁ ⊔ (f^[n₂] a₂))) : by rw sup_comm
... ≤ (f^[n₁] a₁) ⊔ (f^[n₂] a₂) : h' n₁ a₁ _, },
end
end preorder
end order_hom
|
Formal statement is: lemma filterlim_tendsto_pos_mult_at_bot: fixes c :: real assumes "(f \<longlongrightarrow> c) F" "0 < c" "filterlim g at_bot F" shows "LIM x F. f x * g x :> at_bot" Informal statement is: If $f$ tends to $c > 0$ and $g$ tends to $0$, then $f \cdot g$ tends to $0$. |
-- Categories with objects parameterised by a sort
module SOAS.Sorting {T : Set} where
open import SOAS.Common
import Categories.Category.CartesianClosed.Canonical as Canonical
import Categories.Category.CartesianClosed as CCC
open import Categories.Category.Cocartesian
open import Categories.Category.BicartesianClosed
import Categories.Category.Monoidal as Monoidal
import Categories.Category.Monoidal.Closed as MonClosed
open import Categories.Object.Product
open import Categories.Functor.Bifunctor
-- Add sorting to a set
Sorted : Set₁ → Set₁
Sorted Obj = T → Obj
-- Lift a function on Obj to one on sorted Obj
sorted : {O₁ O₂ : Set₁} → (O₁ → O₂) → Sorted O₁ → Sorted O₂
sorted f 𝒳 τ = f (𝒳 τ)
-- Lift a binary operation on Obj to one on sorted Obj
sorted₂ : {O₁ O₂ O₃ : Set₁} → (O₁ → O₂ → O₃)
→ Sorted O₁ → Sorted O₂ → Sorted O₃
sorted₂ op 𝒳 𝒴 τ = op (𝒳 τ) (𝒴 τ)
sortedᵣ : {O₁ O₂ O₃ : Set₁} → (O₁ → O₂ → O₃)
→ O₁ → Sorted O₂ → Sorted O₃
sortedᵣ op X 𝒴 τ = op X (𝒴 τ)
sortedₗ : {O₁ O₂ O₃ : Set₁} → (O₁ → O₂ → O₃)
→ Sorted O₁ → O₂ → Sorted O₃
sortedₗ op 𝒳 Y τ = op (𝒳 τ) Y
-- Turn a category into a sorted category
𝕊orted : Category 1ℓ 0ℓ 0ℓ → Category 1ℓ 0ℓ 0ℓ
𝕊orted Cat = categoryHelper (record
{ Obj = Sorted Obj
; _⇒_ = λ A B → ∀{τ : T} → A τ ⇒ B τ
; _≈_ = λ f g → ∀{α : T} → f {α} ≈ g {α}
; id = id Cat
; _∘_ = λ g f → Category._∘_ Cat g f
; assoc = assoc
; identityˡ = identityˡ
; identityʳ = identityʳ
; equiv = record { refl = E.refl equiv ; sym = λ p → E.sym equiv p
; trans = λ p q → E.trans equiv p q }
; ∘-resp-≈ = λ p q → ∘-resp-≈ p q
})
where
open Category Cat
open import Relation.Binary.Structures renaming (IsEquivalence to E)
-- Lift functors to functors between sorted categories
𝕊orted-Functor : {ℂ 𝔻 : Category 1ℓ 0ℓ 0ℓ} → Functor ℂ 𝔻 → Functor (𝕊orted ℂ) (𝕊orted 𝔻)
𝕊orted-Functor F = record
{ F₀ = λ X τ → Functor.₀ F (X τ)
; F₁ = λ f → Functor.₁ F f
; identity = Functor.identity F
; homomorphism = Functor.homomorphism F
; F-resp-≈ = λ z → Functor.F-resp-≈ F z
}
-- Lift bifunctors to bifunctors between sorted categories
𝕊orted-Bifunctor : {ℂ 𝔻 𝔼 : Category 1ℓ 0ℓ 0ℓ} → Bifunctor ℂ 𝔻 𝔼 → Bifunctor (𝕊orted ℂ) (𝕊orted 𝔻) (𝕊orted 𝔼)
𝕊orted-Bifunctor F = record
{ F₀ = λ{ (X , Y) τ → Functor.₀ F (X τ , Y τ)}
; F₁ = λ{ (f , g) → Functor.₁ F (f , g)}
; identity = Functor.identity F
; homomorphism = Functor.homomorphism F
; F-resp-≈ = λ{ (p , q) → Functor.F-resp-≈ F (p , q)}
}
private
variable C : Category 1ℓ 0ℓ 0ℓ
-- A sorted CCC is itself a CCC
𝕊orted-CanCCC : Canonical.CartesianClosed C
→ Canonical.CartesianClosed (𝕊orted C)
𝕊orted-CanCCC CCC = record
{ ⊤ = λ τ → 𝓒.terminal.⊤
; _×_ = λ A B τ → (A τ) 𝓒.× (B τ)
; ! = 𝓒.terminal.!
; π₁ = 𝓒.π₁
; π₂ = 𝓒.π₂
; ⟨_,_⟩ = λ f g → 𝓒.⟨ f , g ⟩
; !-unique = λ f → 𝓒.terminal.!-unique f
; π₁-comp = 𝓒.π₁-comp
; π₂-comp = 𝓒.π₂-comp
; ⟨,⟩-unique = λ p₁ p₂ → 𝓒.⟨,⟩-unique p₁ p₂
; _^_ = λ B A τ → B τ 𝓒.^ A τ
; eval = 𝓒.eval
; curry = λ f → 𝓒.curry f
; eval-comp = 𝓒.eval-comp
; curry-resp-≈ = λ p → 𝓒.curry-resp-≈ p
; curry-unique = λ p → 𝓒.curry-unique p
} where private module 𝓒 = Canonical.CartesianClosed CCC
-- A sorted co-Cartesian category is co-Cartesian
𝕊orted-Cocartesian : Cocartesian C
→ Cocartesian (𝕊orted C)
𝕊orted-Cocartesian Cocart = record
{ initial = record
{ ⊥ = λ τ → 𝓒.⊥ ; ⊥-is-initial = record
{ ! = 𝓒.initial.! ; !-unique = λ f → 𝓒.initial.!-unique f } }
; coproducts = record { coproduct = λ {A}{B} → record
{ A+B = λ τ → 𝓒.coproduct.A+B {A τ}{B τ}
; i₁ = 𝓒.i₁
; i₂ = 𝓒.i₂
; [_,_] = λ f g → 𝓒.[ f , g ]
; inject₁ = 𝓒.inject₁
; inject₂ = 𝓒.inject₂
; unique = λ p₁ p₂ → 𝓒.coproduct.unique p₁ p₂
} }
} where private module 𝓒 = Cocartesian Cocart
-- A sorted bi-Cartesian closed category is itself bi-Cartesian closed
𝕊orted-BCCC : BicartesianClosed C
→ BicartesianClosed (𝕊orted C)
𝕊orted-BCCC BCCC = record
{ cartesianClosed = fromCanonical _ (𝕊orted-CanCCC (toCanonical _ cartesianClosed))
; cocartesian = 𝕊orted-Cocartesian cocartesian
}
where
open BicartesianClosed BCCC
open Canonical.Equivalence
-- A sorted monoidal category is itself monoidal
𝕊orted-Monoidal : Monoidal.Monoidal C
→ Monoidal.Monoidal (𝕊orted C)
𝕊orted-Monoidal {C} Mon = record
{ ⊗ = record
{ F₀ = λ{ (X , Y) τ → X τ 𝓒.⊗₀ Y τ }
; F₁ = λ{ (f , g) → f 𝓒.⊗₁ g}
; identity = Functor.identity 𝓒.⊗
; homomorphism = Functor.homomorphism 𝓒.⊗
; F-resp-≈ = λ{ (p₁ , p₂) {α} → Functor.F-resp-≈ 𝓒.⊗ (p₁ , p₂) }
}
; unit = λ τ → 𝓒.unit
; unitorˡ = record { from = λ {τ} → 𝓒.unitorˡ.from ; to = 𝓒.unitorˡ.to
; iso = record { isoˡ = Iso.isoˡ 𝓒.unitorˡ.iso ; isoʳ = Iso.isoʳ 𝓒.unitorˡ.iso } }
; unitorʳ = record { from = λ {τ} → 𝓒.unitorʳ.from ; to = 𝓒.unitorʳ.to
; iso = record { isoˡ = Iso.isoˡ 𝓒.unitorʳ.iso ; isoʳ = Iso.isoʳ 𝓒.unitorʳ.iso } }
; associator = record { from = λ {τ} → 𝓒.associator.from ; to = 𝓒.associator.to
; iso = record { isoˡ = Iso.isoˡ 𝓒.associator.iso ; isoʳ = Iso.isoʳ 𝓒.associator.iso } }
; unitorˡ-commute-from = 𝓒.unitorˡ-commute-from
; unitorˡ-commute-to = 𝓒.unitorˡ-commute-to
; unitorʳ-commute-from = 𝓒.unitorʳ-commute-from
; unitorʳ-commute-to = 𝓒.unitorʳ-commute-to
; assoc-commute-from = 𝓒.assoc-commute-from
; assoc-commute-to = 𝓒.assoc-commute-to
; triangle = 𝓒.triangle
; pentagon = 𝓒.pentagon
}
where
private module 𝓒 = Monoidal.Monoidal Mon
open import Categories.Morphism C
-- A sorted monoidal closed category is itself monoidal closed
𝕊orted-MonClosed : {Mon : Monoidal.Monoidal C}
→ MonClosed.Closed Mon
→ MonClosed.Closed (𝕊orted-Monoidal Mon)
𝕊orted-MonClosed {Mon} Cl = record
{ [-,-] = record
{ F₀ = λ (X , Y) τ → 𝓒.[ X τ , Y τ ]₀
; F₁ = λ (f , g) → 𝓒.[ f , g ]₁
; identity = λ {A} {α} → Functor.identity 𝓒.[-,-]
; homomorphism = Functor.homomorphism 𝓒.[-,-]
; F-resp-≈ = λ{ (p₁ , p₂) {α} → Functor.F-resp-≈ 𝓒.[-,-] (p₁ , p₂) }
}
; adjoint = record
{ unit = ntHelper record
{ η = λ X {τ} → NT.η 𝓒.adjoint.unit (X τ)
; commute = λ f → NT.commute 𝓒.adjoint.unit f
}
; counit = ntHelper record
{ η = λ X {τ} → NT.η 𝓒.adjoint.counit (X τ)
; commute = λ f → NT.commute 𝓒.adjoint.counit f
}
; zig = 𝓒.adjoint.zig
; zag = 𝓒.adjoint.zag
}
; mate = λ f → record { commute₁ = 𝓒.mate.commute₁ f ; commute₂ = 𝓒.mate.commute₂ f }
} where private module 𝓒 = MonClosed.Closed Cl
|
subroutine specgrp(na,natom,jmat,neigh)
implicit double precision(a-h,o-z)
dimension jmat(natom,natom),neigh(natom)
neis=0
neistore=0
do n=1,natom
neigh(n)=0
enddo
neigh(na)=1
1 continue
do n=1,natom
if(neigh(n).ne.0)then
do m=1,natom
if(jmat(n,m).ne.0)then
neigh(m)=1
endif
enddo
endif
enddo
neis=0
do m=1,natom
if(neigh(m).eq.1)neis=neis+1
enddo
c write(6,*)neis
if(neis.eq.neistore)then
go to 2
else
neistore=neis
neis=0
go to 1
endif
2 continue
return
end
|
Formal statement is: proposition derivative_is_holomorphic: assumes "open S" and fder: "\<And>z. z \<in> S \<Longrightarrow> (f has_field_derivative f' z) (at z)" shows "f' holomorphic_on S" Informal statement is: If $f$ is a function whose derivative exists and is continuous on an open set $S$, then the derivative is holomorphic on $S$. |
[STATEMENT]
lemma symKey_neq_priK: "K \<in> symKeys \<Longrightarrow> K \<noteq> priK A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. K \<in> symKeys \<Longrightarrow> K \<noteq> priK A
[PROOF STEP]
by (auto simp add: symKeys_def) |
[GOAL]
c : Prop
inst✝ : Decidable c
a b : Ordering
⊢ ((if c then a else b) = lt) = if c then a = lt else b = lt
[PROOFSTEP]
by_cases c
[GOAL]
c : Prop
inst✝ : Decidable c
a b : Ordering
⊢ ((if c then a else b) = lt) = if c then a = lt else b = lt
[PROOFSTEP]
by_cases c
[GOAL]
case pos
c : Prop
inst✝ : Decidable c
a b : Ordering
h : c
⊢ ((if c then a else b) = lt) = if c then a = lt else b = lt
[PROOFSTEP]
simp [*]
[GOAL]
case neg
c : Prop
inst✝ : Decidable c
a b : Ordering
h : ¬c
⊢ ((if c then a else b) = lt) = if c then a = lt else b = lt
[PROOFSTEP]
simp [*]
[GOAL]
c : Prop
inst✝ : Decidable c
a b : Ordering
⊢ ((if c then a else b) = eq) = if c then a = eq else b = eq
[PROOFSTEP]
by_cases c
[GOAL]
c : Prop
inst✝ : Decidable c
a b : Ordering
⊢ ((if c then a else b) = eq) = if c then a = eq else b = eq
[PROOFSTEP]
by_cases c
[GOAL]
case pos
c : Prop
inst✝ : Decidable c
a b : Ordering
h : c
⊢ ((if c then a else b) = eq) = if c then a = eq else b = eq
[PROOFSTEP]
simp [*]
[GOAL]
case neg
c : Prop
inst✝ : Decidable c
a b : Ordering
h : ¬c
⊢ ((if c then a else b) = eq) = if c then a = eq else b = eq
[PROOFSTEP]
simp [*]
[GOAL]
c : Prop
inst✝ : Decidable c
a b : Ordering
⊢ ((if c then a else b) = gt) = if c then a = gt else b = gt
[PROOFSTEP]
by_cases c
[GOAL]
c : Prop
inst✝ : Decidable c
a b : Ordering
⊢ ((if c then a else b) = gt) = if c then a = gt else b = gt
[PROOFSTEP]
by_cases c
[GOAL]
case pos
c : Prop
inst✝ : Decidable c
a b : Ordering
h : c
⊢ ((if c then a else b) = gt) = if c then a = gt else b = gt
[PROOFSTEP]
simp [*]
[GOAL]
case neg
c : Prop
inst✝ : Decidable c
a b : Ordering
h : ¬c
⊢ ((if c then a else b) = gt) = if c then a = gt else b = gt
[PROOFSTEP]
simp [*]
[GOAL]
α : Type u
lt : α → α → Prop
inst✝ : DecidableRel lt
a b : α
⊢ (cmpUsing lt a b = Ordering.lt) = lt a b
[PROOFSTEP]
simp
[GOAL]
α : Type u
lt : α → α → Prop
inst✝¹ : DecidableRel lt
inst✝ : IsStrictOrder α lt
a b : α
⊢ (cmpUsing lt a b = Ordering.gt) = lt b a
[PROOFSTEP]
simp only [cmpUsing, Ordering.ite_eq_gt_distrib, if_false_right_eq_and, and_true, if_false_left_eq_and]
[GOAL]
α : Type u
lt : α → α → Prop
inst✝¹ : DecidableRel lt
inst✝ : IsStrictOrder α lt
a b : α
⊢ (¬lt a b ∧ lt b a) = lt b a
[PROOFSTEP]
apply propext
[GOAL]
case a
α : Type u
lt : α → α → Prop
inst✝¹ : DecidableRel lt
inst✝ : IsStrictOrder α lt
a b : α
⊢ ¬lt a b ∧ lt b a ↔ lt b a
[PROOFSTEP]
apply Iff.intro
[GOAL]
case a.mp
α : Type u
lt : α → α → Prop
inst✝¹ : DecidableRel lt
inst✝ : IsStrictOrder α lt
a b : α
⊢ ¬lt a b ∧ lt b a → lt b a
[PROOFSTEP]
exact fun h => h.2
[GOAL]
case a.mpr
α : Type u
lt : α → α → Prop
inst✝¹ : DecidableRel lt
inst✝ : IsStrictOrder α lt
a b : α
⊢ lt b a → ¬lt a b ∧ lt b a
[PROOFSTEP]
intro hba
[GOAL]
case a.mpr
α : Type u
lt : α → α → Prop
inst✝¹ : DecidableRel lt
inst✝ : IsStrictOrder α lt
a b : α
hba : lt b a
⊢ ¬lt a b ∧ lt b a
[PROOFSTEP]
constructor
[GOAL]
case a.mpr.left
α : Type u
lt : α → α → Prop
inst✝¹ : DecidableRel lt
inst✝ : IsStrictOrder α lt
a b : α
hba : lt b a
⊢ ¬lt a b
[PROOFSTEP]
intro hab
[GOAL]
case a.mpr.left
α : Type u
lt : α → α → Prop
inst✝¹ : DecidableRel lt
inst✝ : IsStrictOrder α lt
a b : α
hba : lt b a
hab : lt a b
⊢ False
[PROOFSTEP]
exact absurd (_root_.trans hab hba) (irrefl a)
[GOAL]
case a.mpr.right
α : Type u
lt : α → α → Prop
inst✝¹ : DecidableRel lt
inst✝ : IsStrictOrder α lt
a b : α
hba : lt b a
⊢ lt b a
[PROOFSTEP]
assumption
[GOAL]
α : Type u
lt : α → α → Prop
inst✝ : DecidableRel lt
a b : α
⊢ (cmpUsing lt a b = Ordering.eq) = (¬lt a b ∧ ¬lt b a)
[PROOFSTEP]
simp
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Translation from Compcert C to Clight.
Side effects are pulled out of Compcert C expressions. *)
Require Import Coqlib.
Require Import Errors.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import AST.
Require Import Ctypes.
Require Import Cop.
Require Import Csyntax.
Require Import Clight.
Local Open Scope string_scope.
(** State and error monad for generating fresh identifiers. *)
Record generator : Type := mkgenerator {
gen_next: ident;
gen_trail: list (ident * type)
}.
Inductive result (A: Type) (g: generator) : Type :=
| Err: Errors.errmsg -> result A g
| Res: A -> forall (g': generator), Ple (gen_next g) (gen_next g') -> result A g.
Arguments Err [A g].
Arguments Res [A g].
Definition mon (A: Type) := forall (g: generator), result A g.
Definition ret {A: Type} (x: A) : mon A :=
fun g => Res x g (Ple_refl (gen_next g)).
Definition error {A: Type} (msg: Errors.errmsg) : mon A :=
fun g => Err msg.
Definition bind {A B: Type} (x: mon A) (f: A -> mon B) : mon B :=
fun g =>
match x g with
| Err msg => Err msg
| Res a g' i =>
match f a g' with
| Err msg => Err msg
| Res b g'' i' => Res b g'' (Ple_trans _ _ _ i i')
end
end.
Definition bind2 {A B C: Type} (x: mon (A * B)) (f: A -> B -> mon C) : mon C :=
bind x (fun p => f (fst p) (snd p)).
Notation "'do' X <- A ; B" := (bind A (fun X => B))
(at level 200, X ident, A at level 100, B at level 200)
: gensym_monad_scope.
Notation "'do' ( X , Y ) <- A ; B" := (bind2 A (fun X Y => B))
(at level 200, X ident, Y ident, A at level 100, B at level 200)
: gensym_monad_scope.
Local Open Scope gensym_monad_scope.
Parameter first_unused_ident: unit -> ident.
Definition initial_generator (x: unit) : generator :=
mkgenerator (first_unused_ident x) nil.
Definition gensym (ty: type): mon ident :=
fun (g: generator) =>
Res (gen_next g)
(mkgenerator (Psucc (gen_next g)) ((gen_next g, ty) :: gen_trail g))
(Ple_succ (gen_next g)).
(** Construct a sequence from a list of statements. To facilitate the
proof, the sequence is nested to the left and starts with a [Sskip]. *)
Fixpoint makeseq_rec (s: statement) (l: list statement) : statement :=
match l with
| nil => s
| s' :: l' => makeseq_rec (Ssequence s s') l'
end.
Definition makeseq (l: list statement) : statement :=
makeseq_rec Sskip l.
(** Smart constructor for [if ... then ... else]. *)
(** NOTE: Here, we no longer need anything about the memory model,
by replacing (Mem.valid_block Mem.empty) with (fun _ => false).
See the Cop.SemCast class, and the sem_cast_unit instance.
*)
Fixpoint eval_simpl_expr (a: expr) : option val :=
match a with
| Econst_int n _ => Some(Vint n)
| Econst_float n _ => Some(Vfloat n)
| Econst_single n _ => Some(Vsingle n)
| Econst_long n _ => Some(Vlong n)
| Ecast b ty =>
match eval_simpl_expr b with
| None => None
| Some v => sem_cast v (typeof b) ty tt
end
| _ => None
end.
Function makeif (a: expr) (s1 s2: statement) : statement :=
match eval_simpl_expr a with
| Some v =>
match bool_val v (typeof a) tt with
| Some b => if b then s1 else s2
| None => Sifthenelse a s1 s2
end
| None => Sifthenelse a s1 s2
end.
(** Smart constructors for [&] and [*]. They optimize away [&*] and [*&] sequences. *)
Definition Ederef' (a: expr) (t: type) : expr :=
match a with
| Eaddrof a' t' => if type_eq t (typeof a') then a' else Ederef a t
| _ => Ederef a t
end.
Definition Eaddrof' (a: expr) (t: type) : expr :=
match a with
| Ederef a' t' => if type_eq t (typeof a') then a' else Eaddrof a t
| _ => Eaddrof a t
end.
(** Translation of pre/post-increment/decrement. *)
Definition transl_incrdecr (id: incr_or_decr) (a: expr) (ty: type) : expr :=
match id with
| Incr => Ebinop Oadd a (Econst_int Int.one type_int32s) (incrdecr_type ty)
| Decr => Ebinop Osub a (Econst_int Int.one type_int32s) (incrdecr_type ty)
end.
(** Generate a [Sset] or [Sbuiltin] operation as appropriate
to dereference a l-value [l] and store its result in temporary variable [id]. *)
Definition chunk_for_volatile_type (ty: type) : option memory_chunk :=
if type_is_volatile ty
then match access_mode ty with By_value chunk => Some chunk | _ => None end
else None.
Definition make_set (id: ident) (l: expr) : statement :=
match chunk_for_volatile_type (typeof l) with
| None => Sset id l
| Some chunk =>
let typtr := Tpointer (typeof l) noattr in
Sbuiltin (Some id) (EF_vload chunk) (Tcons typtr Tnil) ((Eaddrof l typtr):: nil)
end.
(** Translation of a "valof" operation.
If the l-value accessed is of volatile type, we go through a temporary. *)
Definition transl_valof (ty: type) (l: expr) : mon (list statement * expr) :=
if type_is_volatile ty
then do t <- gensym ty; ret (make_set t l :: nil, Etempvar t ty)
else ret (nil, l).
(** Translation of an assignment. *)
Definition make_assign (l r: expr) : statement :=
match chunk_for_volatile_type (typeof l) with
| None =>
Sassign l r
| Some chunk =>
let ty := typeof l in
let typtr := Tpointer ty noattr in
Sbuiltin None (EF_vstore chunk) (Tcons typtr (Tcons ty Tnil))
(Eaddrof l typtr :: r :: nil)
end.
(** Translation of expressions. Return a pair [(sl, a)] of
a list of statements [sl] and a pure expression [a].
- If the [dst] argument is [For_val], the statements [sl]
perform the side effects of the original expression,
and [a] evaluates to the same value as the original expression.
- If the [dst] argument is [For_effects], the statements [sl]
perform the side effects of the original expression,
and [a] is meaningless.
- If the [dst] argument is [For_set tyl tvar], the statements [sl]
perform the side effects of the original expression, then
assign the value of the original expression to the temporary [tvar].
The value is casted according to the list of types [tyl] before
assignment. In this case, [a] is meaningless.
*)
Inductive set_destination : Type :=
| SDbase (tycast ty: type) (tmp: ident)
| SDcons (tycast ty: type) (tmp: ident) (sd: set_destination).
Inductive destination : Type :=
| For_val
| For_effects
| For_set (sd: set_destination).
Definition dummy_expr := Econst_int Int.zero type_int32s.
Fixpoint do_set (sd: set_destination) (a: expr) : list statement :=
match sd with
| SDbase tycast ty tmp => Sset tmp (Ecast a tycast) :: nil
| SDcons tycast ty tmp sd' => Sset tmp (Ecast a tycast) :: do_set sd' (Etempvar tmp ty)
end.
Definition finish (dst: destination) (sl: list statement) (a: expr) :=
match dst with
| For_val => (sl, a)
| For_effects => (sl, a)
| For_set sd => (sl ++ do_set sd a, a)
end.
Definition sd_temp (sd: set_destination) :=
match sd with SDbase _ _ tmp => tmp | SDcons _ _ tmp _ => tmp end.
Definition sd_seqbool_val (tmp: ident) (ty: type) :=
SDbase type_bool ty tmp.
Definition sd_seqbool_set (ty: type) (sd: set_destination) :=
let tmp := sd_temp sd in SDcons type_bool ty tmp sd.
Fixpoint transl_expr (dst: destination) (a: Csyntax.expr) : mon (list statement * expr) :=
match a with
| Csyntax.Eloc b ofs ty =>
error (msg "SimplExpr.transl_expr: Eloc")
| Csyntax.Evar x ty =>
ret (finish dst nil (Evar x ty))
| Csyntax.Ederef r ty =>
do (sl, a) <- transl_expr For_val r;
ret (finish dst sl (Ederef' a ty))
| Csyntax.Efield r f ty =>
do (sl, a) <- transl_expr For_val r;
ret (finish dst sl (Efield a f ty))
| Csyntax.Eval (Vint n) ty =>
ret (finish dst nil (Econst_int n ty))
| Csyntax.Eval (Vfloat n) ty =>
ret (finish dst nil (Econst_float n ty))
| Csyntax.Eval (Vsingle n) ty =>
ret (finish dst nil (Econst_single n ty))
| Csyntax.Eval (Vlong n) ty =>
ret (finish dst nil (Econst_long n ty))
| Csyntax.Eval _ ty =>
error (msg "SimplExpr.transl_expr: Eval")
| Csyntax.Esizeof ty' ty =>
ret (finish dst nil (Esizeof ty' ty))
| Csyntax.Ealignof ty' ty =>
ret (finish dst nil (Ealignof ty' ty))
| Csyntax.Evalof l ty =>
do (sl1, a1) <- transl_expr For_val l;
do (sl2, a2) <- transl_valof (Csyntax.typeof l) a1;
ret (finish dst (sl1 ++ sl2) a2)
| Csyntax.Eaddrof l ty =>
do (sl, a) <- transl_expr For_val l;
ret (finish dst sl (Eaddrof' a ty))
| Csyntax.Eunop op r1 ty =>
do (sl1, a1) <- transl_expr For_val r1;
ret (finish dst sl1 (Eunop op a1 ty))
| Csyntax.Ebinop op r1 r2 ty =>
do (sl1, a1) <- transl_expr For_val r1;
do (sl2, a2) <- transl_expr For_val r2;
ret (finish dst (sl1 ++ sl2) (Ebinop op a1 a2 ty))
| Csyntax.Ecast r1 ty =>
do (sl1, a1) <- transl_expr For_val r1;
ret (finish dst sl1 (Ecast a1 ty))
| Csyntax.Eseqand r1 r2 ty =>
do (sl1, a1) <- transl_expr For_val r1;
match dst with
| For_val =>
do t <- gensym ty;
do (sl2, a2) <- transl_expr (For_set (sd_seqbool_val t ty)) r2;
ret (sl1 ++
makeif a1 (makeseq sl2) (Sset t (Econst_int Int.zero ty)) :: nil,
Etempvar t ty)
| For_effects =>
do (sl2, a2) <- transl_expr For_effects r2;
ret (sl1 ++ makeif a1 (makeseq sl2) Sskip :: nil, dummy_expr)
| For_set sd =>
do (sl2, a2) <- transl_expr (For_set (sd_seqbool_set ty sd)) r2;
ret (sl1 ++
makeif a1 (makeseq sl2) (makeseq (do_set sd (Econst_int Int.zero ty))) :: nil,
dummy_expr)
end
| Csyntax.Eseqor r1 r2 ty =>
do (sl1, a1) <- transl_expr For_val r1;
match dst with
| For_val =>
do t <- gensym ty;
do (sl2, a2) <- transl_expr (For_set (sd_seqbool_val t ty)) r2;
ret (sl1 ++
makeif a1 (Sset t (Econst_int Int.one ty)) (makeseq sl2) :: nil,
Etempvar t ty)
| For_effects =>
do (sl2, a2) <- transl_expr For_effects r2;
ret (sl1 ++ makeif a1 Sskip (makeseq sl2) :: nil, dummy_expr)
| For_set sd =>
do (sl2, a2) <- transl_expr (For_set (sd_seqbool_set ty sd)) r2;
ret (sl1 ++
makeif a1 (makeseq (do_set sd (Econst_int Int.one ty))) (makeseq sl2) :: nil,
dummy_expr)
end
| Csyntax.Econdition r1 r2 r3 ty =>
do (sl1, a1) <- transl_expr For_val r1;
match dst with
| For_val =>
do t <- gensym ty;
do (sl2, a2) <- transl_expr (For_set (SDbase ty ty t)) r2;
do (sl3, a3) <- transl_expr (For_set (SDbase ty ty t)) r3;
ret (sl1 ++ makeif a1 (makeseq sl2) (makeseq sl3) :: nil,
Etempvar t ty)
| For_effects =>
do (sl2, a2) <- transl_expr For_effects r2;
do (sl3, a3) <- transl_expr For_effects r3;
ret (sl1 ++ makeif a1 (makeseq sl2) (makeseq sl3) :: nil,
dummy_expr)
| For_set sd =>
do t <- gensym ty;
do (sl2, a2) <- transl_expr (For_set (SDcons ty ty t sd)) r2;
do (sl3, a3) <- transl_expr (For_set (SDcons ty ty t sd)) r3;
ret (sl1 ++ makeif a1 (makeseq sl2) (makeseq sl3) :: nil,
dummy_expr)
end
| Csyntax.Eassign l1 r2 ty =>
do (sl1, a1) <- transl_expr For_val l1;
do (sl2, a2) <- transl_expr For_val r2;
let ty1 := Csyntax.typeof l1 in
let ty2 := Csyntax.typeof r2 in
match dst with
| For_val | For_set _ =>
do t <- gensym ty1;
ret (finish dst
(sl1 ++ sl2 ++ Sset t (Ecast a2 ty1) :: make_assign a1 (Etempvar t ty1) :: nil)
(Etempvar t ty1))
| For_effects =>
ret (sl1 ++ sl2 ++ make_assign a1 a2 :: nil,
dummy_expr)
end
| Csyntax.Eassignop op l1 r2 tyres ty =>
let ty1 := Csyntax.typeof l1 in
do (sl1, a1) <- transl_expr For_val l1;
do (sl2, a2) <- transl_expr For_val r2;
do (sl3, a3) <- transl_valof ty1 a1;
match dst with
| For_val | For_set _ =>
do t <- gensym ty1;
ret (finish dst
(sl1 ++ sl2 ++ sl3 ++
Sset t (Ecast (Ebinop op a3 a2 tyres) ty1) ::
make_assign a1 (Etempvar t ty1) :: nil)
(Etempvar t ty1))
| For_effects =>
ret (sl1 ++ sl2 ++ sl3 ++ make_assign a1 (Ebinop op a3 a2 tyres) :: nil,
dummy_expr)
end
| Csyntax.Epostincr id l1 ty =>
let ty1 := Csyntax.typeof l1 in
do (sl1, a1) <- transl_expr For_val l1;
match dst with
| For_val | For_set _ =>
do t <- gensym ty1;
ret (finish dst
(sl1 ++ make_set t a1 ::
make_assign a1 (transl_incrdecr id (Etempvar t ty1) ty1) :: nil)
(Etempvar t ty1))
| For_effects =>
do (sl2, a2) <- transl_valof ty1 a1;
ret (sl1 ++ sl2 ++ make_assign a1 (transl_incrdecr id a2 ty1) :: nil,
dummy_expr)
end
| Csyntax.Ecomma r1 r2 ty =>
do (sl1, a1) <- transl_expr For_effects r1;
do (sl2, a2) <- transl_expr dst r2;
ret (sl1 ++ sl2, a2)
| Csyntax.Ecall r1 rl2 ty =>
do (sl1, a1) <- transl_expr For_val r1;
do (sl2, al2) <- transl_exprlist rl2;
match dst with
| For_val | For_set _ =>
do t <- gensym ty;
ret (finish dst (sl1 ++ sl2 ++ Scall (Some t) a1 al2 :: nil)
(Etempvar t ty))
| For_effects =>
ret (sl1 ++ sl2 ++ Scall None a1 al2 :: nil, dummy_expr)
end
| Csyntax.Ebuiltin ef tyargs rl ty =>
do (sl, al) <- transl_exprlist rl;
match dst with
| For_val | For_set _ =>
do t <- gensym ty;
ret (finish dst (sl ++ Sbuiltin (Some t) ef tyargs al :: nil)
(Etempvar t ty))
| For_effects =>
ret (sl ++ Sbuiltin None ef tyargs al :: nil, dummy_expr)
end
| Csyntax.Eparen r1 tycast ty =>
error (msg "SimplExpr.transl_expr: paren")
end
with transl_exprlist (rl: exprlist) : mon (list statement * list expr) :=
match rl with
| Csyntax.Enil =>
ret (nil, nil)
| Csyntax.Econs r1 rl2 =>
do (sl1, a1) <- transl_expr For_val r1;
do (sl2, al2) <- transl_exprlist rl2;
ret (sl1 ++ sl2, a1 :: al2)
end.
Definition transl_expression (r: Csyntax.expr) : mon (statement * expr) :=
do (sl, a) <- transl_expr For_val r; ret (makeseq sl, a).
Definition transl_expr_stmt (r: Csyntax.expr) : mon statement :=
do (sl, a) <- transl_expr For_effects r; ret (makeseq sl).
(*
Definition transl_if (r: Csyntax.expr) (s1 s2: statement) : mon statement :=
do (sl, a) <- transl_expr For_val r;
ret (makeseq (sl ++ makeif a s1 s2 :: nil)).
*)
Definition transl_if (r: Csyntax.expr) (s1 s2: statement) : mon statement :=
do (sl, a) <- transl_expr For_val r;
ret (makeseq (sl ++ makeif a s1 s2 :: nil)).
(** Translation of statements *)
Definition expr_true := Econst_int Int.one type_int32s.
Definition is_Sskip:
forall s, {s = Csyntax.Sskip} + {s <> Csyntax.Sskip}.
Proof.
destruct s; ((left; reflexivity) || (right; congruence)).
Defined.
Fixpoint transl_stmt (s: Csyntax.statement) : mon statement :=
match s with
| Csyntax.Sskip => ret Sskip
| Csyntax.Sdo e => transl_expr_stmt e
| Csyntax.Ssequence s1 s2 =>
do ts1 <- transl_stmt s1;
do ts2 <- transl_stmt s2;
ret (Ssequence ts1 ts2)
| Csyntax.Sifthenelse e s1 s2 =>
do ts1 <- transl_stmt s1;
do ts2 <- transl_stmt s2;
do (s', a) <- transl_expression e;
if is_Sskip s1 && is_Sskip s2 then
ret (Ssequence s' Sskip)
else
ret (Ssequence s' (Sifthenelse a ts1 ts2))
| Csyntax.Swhile e s1 =>
do s' <- transl_if e Sskip Sbreak;
do ts1 <- transl_stmt s1;
ret (Sloop (Ssequence s' ts1) Sskip)
| Csyntax.Sdowhile e s1 =>
do s' <- transl_if e Sskip Sbreak;
do ts1 <- transl_stmt s1;
ret (Sloop ts1 s')
| Csyntax.Sfor s1 e2 s3 s4 =>
do ts1 <- transl_stmt s1;
do s' <- transl_if e2 Sskip Sbreak;
do ts3 <- transl_stmt s3;
do ts4 <- transl_stmt s4;
if is_Sskip s1 then
ret (Sloop (Ssequence s' ts4) ts3)
else
ret (Ssequence ts1 (Sloop (Ssequence s' ts4) ts3))
| Csyntax.Sbreak =>
ret Sbreak
| Csyntax.Scontinue =>
ret Scontinue
| Csyntax.Sreturn None =>
ret (Sreturn None)
| Csyntax.Sreturn (Some e) =>
do (s', a) <- transl_expression e;
ret (Ssequence s' (Sreturn (Some a)))
| Csyntax.Sswitch e ls =>
do (s', a) <- transl_expression e;
do tls <- transl_lblstmt ls;
ret (Ssequence s' (Sswitch a tls))
| Csyntax.Slabel lbl s1 =>
do ts1 <- transl_stmt s1;
ret (Slabel lbl ts1)
| Csyntax.Sgoto lbl =>
ret (Sgoto lbl)
end
with transl_lblstmt (ls: Csyntax.labeled_statements) : mon labeled_statements :=
match ls with
| Csyntax.LSnil =>
ret LSnil
| Csyntax.LScons c s ls1 =>
do ts <- transl_stmt s;
do tls1 <- transl_lblstmt ls1;
ret (LScons c ts tls1)
end.
(** Translation of a function *)
Definition transl_function (f: Csyntax.function) : res function :=
match transl_stmt f.(Csyntax.fn_body) (initial_generator tt) with
| Err msg =>
Error msg
| Res tbody g i =>
OK (mkfunction
f.(Csyntax.fn_return)
f.(Csyntax.fn_callconv)
f.(Csyntax.fn_params)
f.(Csyntax.fn_vars)
g.(gen_trail)
tbody)
end.
Local Open Scope error_monad_scope.
Definition transl_fundef (fd: Csyntax.fundef) : res fundef :=
match fd with
| Internal f =>
do tf <- transl_function f; OK (Internal tf)
| External ef targs tres cc =>
OK (External ef targs tres cc)
end.
Definition transl_program (p: Csyntax.program) : res program :=
do p1 <- AST.transform_partial_program transl_fundef p;
OK {| prog_defs := AST.prog_defs p1;
prog_public := AST.prog_public p1;
prog_main := AST.prog_main p1;
prog_types := prog_types p;
prog_comp_env := prog_comp_env p;
prog_comp_env_eq := prog_comp_env_eq p |}.
|
-- Andreas, 2017-08-13, issue #2686
-- Overloaded constructor where only one alternative is not abstract.
-- Not ambiguous, since abstract constructors are not in scope!
-- {-# OPTIONS -v tc.check.term:40 #-}
abstract
data A : Set where
c : A
data D : Set where
c : D
test = c
match : D → D
match c = c
|
State Before: F : Type ?u.344901
α : Type u_1
β : Type ?u.344907
γ : Type ?u.344910
ι : Type ?u.344913
κ : Type ?u.344916
inst✝ : LinearOrder α
s : Finset α
H : Finset.Nonempty s
x : α
h₂ : 1 < card s
⊢ min' s (_ : Finset.Nonempty s) < max' s (_ : Finset.Nonempty s) State After: case intro.intro.intro.intro
F : Type ?u.344901
α : Type u_1
β : Type ?u.344907
γ : Type ?u.344910
ι : Type ?u.344913
κ : Type ?u.344916
inst✝ : LinearOrder α
s : Finset α
H : Finset.Nonempty s
x : α
h₂ : 1 < card s
a : α
ha : a ∈ s
b : α
hb : b ∈ s
hab : a ≠ b
⊢ min' s (_ : Finset.Nonempty s) < max' s (_ : Finset.Nonempty s) Tactic: rcases one_lt_card.1 h₂ with ⟨a, ha, b, hb, hab⟩ State Before: case intro.intro.intro.intro
F : Type ?u.344901
α : Type u_1
β : Type ?u.344907
γ : Type ?u.344910
ι : Type ?u.344913
κ : Type ?u.344916
inst✝ : LinearOrder α
s : Finset α
H : Finset.Nonempty s
x : α
h₂ : 1 < card s
a : α
ha : a ∈ s
b : α
hb : b ∈ s
hab : a ≠ b
⊢ min' s (_ : Finset.Nonempty s) < max' s (_ : Finset.Nonempty s) State After: no goals Tactic: exact s.min'_lt_max' ha hb hab |
(*
abhishek@brixpro:~/parametricity/reflective-paramcoq/test-suite$ ./coqid.sh indFunArg
*)
Require Import SquiggleEq.terms.
Require Import ReflParam.common.
Require Import ReflParam.templateCoqMisc.
Require Import String.
Require Import List.
Require Import Template.Ast.
Require Import SquiggleEq.terms.
Require Import ReflParam.paramDirect ReflParam.indType.
Require Import SquiggleEq.substitution.
Require Import ReflParam.PiTypeR.
Import ListNotations.
Open Scope string_scope.
Require Import ReflParam.PIWNew.
Require Import Template.Template.
(* Inductive nat : Set := O : nat | S : forall ns:nat, nat. *)
Run TemplateProgram (genParamIndAll [] "Coq.Init.Datatypes.nat").
Run TemplateProgram (mkIndEnv "indTransEnv" ["Coq.Init.Datatypes.nat"]).
Run TemplateProgram (genWrappers indTransEnv).
(*
Set Printing All.
Run TemplateProgram (genParamIndTotAll [] true "Coq.Init.Datatypes.nat").
Run TemplateProgram (genParamIso [] "Coq.Init.Datatypes.nat").
*)
(* functions wont work until we fully produce the goodness of inductives *) |
Add LoadPath "." as OmegaCategories.
Require Export Unicode.Utf8_core.
Require Import Vector.
Require Export path.
Set Universes Polymorphic.
Set Implicit Arguments.
Class Contr_internal (A : Type) := BuildContr {
center : A ;
contr : (forall y : A, center = y)
}.
Inductive trunc_index : Type :=
| minus_two : trunc_index
| trunc_S : trunc_index -> trunc_index.
(** We will use [Notation] for [trunc_index]es, so define a scope for them here. *)
Delimit Scope trunc_scope with trunc.
Bind Scope trunc_scope with trunc_index.
Arguments trunc_S _%trunc_scope.
Fixpoint nat_to_trunc_index (n : nat) : trunc_index
:= match n with
| 0 => trunc_S (trunc_S minus_two)
| S n' => trunc_S (nat_to_trunc_index n')
end.
Coercion nat_to_trunc_index : nat >-> trunc_index.
Fixpoint IsTrunc_internal (n : trunc_index) (A : Type) : Type :=
match n with
| minus_two => Contr_internal A
| trunc_S n' => forall (x y : A), IsTrunc_internal n' (x = y)
end.
Notation minus_one:=(trunc_S minus_two).
(** Include the basic numerals, so we don't need to go through the coercion from [nat], and so that we get the right binding with [trunc_scope]. *)
Notation "0" := (trunc_S minus_one) : trunc_scope.
Notation "1" := (trunc_S 0) : trunc_scope.
Notation "2" := (trunc_S 1) : trunc_scope.
Arguments IsTrunc_internal n A : simpl nomatch.
Class IsTrunc (n : trunc_index) (A : Type) : Type :=
Trunc_is_trunc : IsTrunc_internal n A.
(** We use the priciple that we should always be doing typeclass resolution on truncation of non-equality types. We try to change the hypotheses and goals so that they never mention something like [IsTrunc n (_ = _)] and instead say [IsTrunc (S n) _]. If you're evil enough that some of your paths [a = b] are n-truncated, but others are not, then you'll have to either reason manually or add some (local) hints with higher priority than the hint below, or generalize your equality type so that it's not a path anymore. *)
Typeclasses Opaque IsTrunc. (* don't auto-unfold [IsTrunc] in typeclass search *)
Arguments IsTrunc : simpl never. (* don't auto-unfold [IsTrunc] with [simpl] *)
Instance istrunc_paths (A : Type) n `{H : IsTrunc (trunc_S n) A} (x y : A)
: IsTrunc n (x = y)
:= H x y. (* but do fold [IsTrunc] *)
Notation Contr := (IsTrunc minus_two).
Notation IsHProp := (IsTrunc minus_one).
Notation IsHSet := (IsTrunc 0).
|
#redirect Graduate Record Examinations
|
# Date objects in R
# https://www.statmethods.net/input/dates.html
x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
z <- as.Date(x, "%d%b%Y")
# gives 1-1-1960 etc
y <- as.Date(z, format="%d-%m-%Y")
# Gives 1960-01-01
# Using posix as date formater
posixx <- as.POSIXlt("2018-08-30")
# Using POSIX i can - or + dates and get the date between back |
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
NewRulesFor(TConjEven, rec(
TConjEven_vec := rec(
switch := true,
applicable := (self, t) >> IsEvenInt(t.params[1]) and t.isTag(1, AVecReg) and
t.params[1] mod (2*t.getTag(1).v) = 0,
apply := (self, t, C, Nonterms) >> let(N := t.params[1], v := t.getTag(1).v, rot := t.params[2],
m := Mat([[1,0],[0,-1]]),
# d1 := Diag(diagDirsum(fConst(TReal, 2, 1.0), fConst(TReal, N-2, 1/2))),
d1 := VDiag(diagDirsum(fConst(TReal, 1, 1.0), fConst(TReal, v-1, 0.5), fConst(TReal, 1, 1.0), fConst(TReal, N-v-1, 0.5)), v),
#m1 := DirectSum(m, SUM(I(N-2), Tensor(J((N-2)/2), m))),
#dv1 := Diag(diagDirsum(fConst(TReal, v, 1.0), fConst(TReal, 1,-1.0), fConst(TReal, N-v-1, 1.0))),
dv1 := DirectSum(VTensor(I(1), v),
VBlk([[ [-1.0] :: Replicate(v-1, 1.0) ]], v),
VTensor(I(N/v-2), v)),
P1 := VPrm_x_I(L(N/v, N/(2*v)), v),
Q1 := VPrm_x_I(L(N/v, 2), v),
jv1 := P1*DirectSum(VO1dsJ(N/2, v), VScale(VO1dsJ(N/2, v), -1, v))*Q1,
mv1 := _VSUM([dv1,jv1], v),
#m2 := DirectSum(J(2), SUM(I(N-2), Tensor(J((N-2)/2), -m))),
e0 := [0.0] :: Replicate(v-1, 1.0),
e1 := [1.0] :: Replicate(v-1, 0.0),
blk := VBlk([[e0,e1],[e1,e0]], v).setSymmetric(),
dv2 := DirectSum(blk, VTensor(I(N/v-2), v)),
jv2 := P1 * DirectSum(VScale(VO1dsJ(N/2, v), -1, v), VO1dsJ(N/2, v))*Q1,
mv2 := _VSUM([dv2,jv2], v),
#
i := VTensor(I(N/v), v),
d2 := VRCLR(Diag(fPrecompute(diagDirsum(fConst(TReal, 1, 1.0), diagMul(fConst(TComplex, N/2-1, omegapi(-1/2)), fCompose(dOmega(N, rot), fAdd(N/2, N/2-1, 1)))))), v),
#
#d1 *
VBlkInt(d1 * _VHStack([mv1, mv2], v) * VStack(i, d2), v))
),
TConjEven_vec_tr := rec(
switch := true,
applicable := (self, t) >> IsEvenInt(t.params[1]) and t.isTag(1, AVecReg) and t.params[1] mod (2*t.getTag(AVecReg).v)=0,
transposed := true,
apply := (self, t, C, Nonterms) >> let(N := t.params[1], v := t.getTag(1).v, rot := t.params[2],
m := Mat([[1,0],[0,-1]]),
# d1 := Diag(diagDirsum(fConst(TReal, 2, 1.0), fConst(TReal, N-2, 1/2))),
d1 := VDiag(diagDirsum(fConst(TReal, 1, 1.0), fConst(TReal, v-1, 0.5), fConst(TReal, 1, 1.0), fConst(TReal, N-v-1, 0.5)), v),
#m1 := DirectSum(m, SUM(I(N-2), Tensor(J((N-2)/2), m))),
#dv1 := Diag(diagDirsum(fConst(TReal, v, 1.0), fConst(TReal, 1,-1.0), fConst(TReal, N-v-1, 1.0))),
dv1 := DirectSum(VTensor(I(1), v),
VBlk([[ [-1.0] :: Replicate(v-1, 1.0) ]], v),
VTensor(I(N/v-2), v)),
P1 := VPrm_x_I(L(N/v, N/(2*v)), v),
Q1 := VPrm_x_I(L(N/v, 2), v),
jv1 := P1*DirectSum(VO1dsJ(N/2, v), VScale(VO1dsJ(N/2, v), -1, v))*Q1,
mv1 := _VSUM([dv1,jv1], v),
#m2 := DirectSum(J(2), SUM(I(N-2), Tensor(J((N-2)/2), -m))),
e0 := [0.0] :: Replicate(v-1, 1.0),
e1 := [1.0] :: Replicate(v-1, 0.0),
blk := VBlk([[e0,e1],[e1,e0]], v).setSymmetric(),
dv2 := DirectSum(blk, VTensor(I(N/v-2), v)),
jv2 := P1 * DirectSum(VScale(VO1dsJ(N/2, v), -1, v), VO1dsJ(N/2, v))*Q1,
mv2 := _VSUM([dv2,jv2], v),
#
i := VTensor(I(N/v), v),
d2 := VRCLR(Diag(fPrecompute(diagDirsum(fConst(TReal, 1, 1.0), diagMul(fConst(TComplex, N/2-1, omegapi(-1/2)), fCompose(dOmega(N, rot), fAdd(N/2, N/2-1, 1)))))), v),
#
#d1 *
VBlkInt(_VHStack([i, d2.transpose()], v) * VStack(mv1, mv2) * d1, v))
)
));
NewRulesFor(TXMatDHT, rec(
TXMatDHT_vec := rec(
switch := true,
applicable := (self, t) >> IsEvenInt(t.params[1]) and t.isTag(1, AVecReg),
apply := (self, t, C, Nonterms) >> let(N := t.params[1], v := t.getTag(1).v,
f0 := Replicate(v, 1.0),
f1 := [0.0] :: Replicate(v-1, 1.0),
f2 := [1.0] :: Replicate(v-1, -1.0),
fblk := VBlk([[f0,f1],[f1,f2]], v).setSymmetric(),
fdiag := VTensor(Tensor(I(N/(2*v)-1), F(2)), v),
ff := DirectSum(fblk, fdiag),
###
m := Mat([[1,0],[0,-1]]),
d1 := Diag(diagDirsum(fConst(TReal, 2, 1.0), fConst(TReal, N-2, 1/2))),
#m1 := DirectSum(m, SUM(I(N-2), Tensor(J((N-2)/2), m))),
#dv1 := Diag(diagDirsum(fConst(TReal, v,1), fConst(TReal, 1,-1), fConst(TReal, N-v-1, 1))),
dv1 := DirectSum(VTensor(I(1), v),
VBlk([[ [-1.0] :: Replicate(v-1, 1.0) ]], v),
VTensor(I(N/v-2), v)),
P1 := VPrm_x_I(L(N/v, N/(2*v)), v),
Q1 := VPrm_x_I(L(N/v, 2), v),
jv1 := P1*DirectSum(VO1dsJ(N/2, v), VScale(VO1dsJ(N/2, v), -1, v))*Q1,
mv1 := _VSUM([dv1,jv1], v),
#m2 := DirectSum(J(2), SUM(I(N-2), Tensor(J((N-2)/2), -m))),
e0 := [0.0] :: Replicate(v-1, 1.0),
e1 := [1.0] :: Replicate(v-1, 0.0),
blk := VBlk([[e0,e1],[e1,e0]], v).setSymmetric(),
dv2 := DirectSum(blk, VTensor(I(N/v-2), v)),
jv2 := P1*DirectSum(VScale(VO1dsJ(N/2, v), -1, v), VO1dsJ(N/2, v))*Q1,
mv2 := _VSUM([dv2,jv2], v),
#
i := VTensor(I(N/v), v),
d2 := VRCLR(Diag(fPrecompute(diagDirsum(fConst(TReal, 1, 1.0), diagMul(fConst(TComplex, N/2-1, Complex(0,-1)), fCompose(dOmega(N, 1), fAdd(N/2, N/2-1, 1)))))), v),
#
d1 * VBlkInt(ff * _VHStack([mv1, mv2], v) * VStack(i, d2), v)
))
));
|
function vGlobal=getGlobalVectors(vLocal,uList)
%%GETGLOBALVECTORS Change a collection of local vectors into global
% vectors using the local coordinate axes. This multiplies
% the components of the vectors by the corresponding
% coordinate axis vectors.
%
%INPUTS: vLocal A numDimsXN matrix of N local vectors that are to be
% converted.
% uList A numDimsXnumDimsXN matrix of orthonormal unit coordinate
% axes that are associated with the local coordinate system
% in which the vectors are expressed. If all N vectors use
% the same local coordinate system, then a numDimsxnumDimsx1
% matrix can be passed instead.
%
%OUTPUTS: vGlobal The vectors in the global coordinate system.
%
%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.
numVel=size(vLocal,2);
if(size(uList,3)==1)
uList=repmat(uList,[1,1,numVel]);
end
numDims=size(vLocal,1);
vGlobal=zeros(numDims,numVel);
for curVel=1:numVel
for curDim=1:numDims
vGlobal(:,curVel)=vGlobal(:,curVel)+vLocal(curDim,curVel)*uList(:,curDim,curVel);
end
end
end
%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.
|
/-
In this file, we'll start to build a certified abstract
data type for the natural numbers. What we want is for
our implementations to faithfully present the properties
of natural numbers that we're familar with from highschool
algebra. For example, zero is a left identify for addition;
zero is also a right identity; addition is associative and
commutative; the distributive law holds; etc. We'll get
you started, and you will then finish off development of
a certified abstract data type for natural numbers.
-/
namespace hidden
/-
DATA TYPE
-/
inductive nt
| zero
| succ (n' : nt)
open nt
/-
Some example values of this type, with nice names.
-/
def one := succ zero
def two := succ (succ zero)
def three := succ (succ (succ zero))
def four := succ three -- works just fine
def five := succ four
def six := succ five
-- tests
#reduce four
#reduce five
#reduce six
/-
OPERATIONS
-/
-- COMPUTATIONAL
/-
This implementation of the identity function can
be read as saying that id is a function from nt
to nt, and in particular when applied to any
argument, n, it returns n. Importantly, we don't
need to "analyze/destructure" n to decide what
to return: we just return whatever we got.
-/
def id : nt → nt
| n := n
-- we can compute results of evaluating applications
#reduce (id two)
/-
We can also write test cases as equality propositions
that assert that actual outputs are equal to expected
outputs, with simple equality proofs. The failure of
rfl here indicates that either the computation or the
test case is wrong.
-/
example : id two = two := rfl
example : id three = two := rfl -- oops, bad test case
/-
A similar approaches works for defining increment.
-/
def inc : nt → nt
| n := succ n
/-
Next we'll look at the decrement function, defined
mathemtically as mapping 0 to 0 and and any positive
natural number, n = n'+1, to n', i.e., to n-1. Make
sure you understand what we just said! To implement
this function, we need to *analyze/destructure* the
argument in order to determine if it's zero or some
non-zero number (which is to say, the successor of
some one-smaller natural number, n').
-/
def dec : nt → nt
| zero := zero
| (succ n') := n' -- you must understand this!
-- tests
#reduce dec two -- expect one
#reduce dec one -- expect zero
#reduce dec zero -- expect zero
/-
Test cases as equality propositions for
individual inputs.
-/
example : dec two = one := rfl
example : dec one = zero := rfl
example : dec zero = zero := rfl
/-
The key to this definition is in the pattern match
that occurs in the second case. Take, for example,
the expression (dec two). To evaluate this we first
evaluate the identifier expression, two, which then
unfolds to (succ (succ zero)), then we do pattern
matching. This term does not match the term, zero,
so Lean moves on to match it with (succ n').
The essential technical concept at this point what
we call unification. Lean sees that the pattern,
(succ n'), can be unified with (succ (succ zero)),
where the "succ" in (succ n') matches the first
"succ" in (succ (succ zero)), and where n' matches
the rest, namely (succ zero); and that n' is what
gets returned.
The big idea is that you can use pattern matching
to "analyze" a term (argument in this case), to pull
it apart into subterms pieces, giving subterms names
(here n') that we can then use to express the return
result to the right of the colon-equals separator.
-/
/-
Next, we define an isZero "predicate function", a
function that returns true if an argument has a
particular property (here that of being zero), or
false if it doesn't. We again have to analyze the
argument (doing a kind of case analysis). The one
new concept introduced here is that sometimes you
will want to match on any value of a given argument
without giving it a name. This function matches on
its argument to determine if it's zero, in which
case the function returns true, otherwise it just
returns false without further naming or analysis
of the argument value.
-/
def isZero : nt → bool
| zero := tt
| _ := ff
/-
Another example of a function where there's no
need to analyze the argument: this function takes
a natural number and returns zero no matter what
it is.
-/
def const_zero : nt → nt
| _ := zero
/-
As an aside, it would be preferable for readability
to use simpler syntax to define this function. Here
is an alternative.
-/
def const_zero' (n : nt) := zero
-- some simple tests
#check const_zero'
#reduce const_zero' six -- expect zero
-- binary operations
/-
Addition is defined as iterated application of the
increment (inc) function to the second argument the
first argument number of times. For example, 3 + 2
reduces to 1 + 1 + 1 + 2. That's three applications
of inc to two.
-/
def add : nt → nt → nt
| zero m := m
| (succ n') m := succ (add n' m)
-- tests
#reduce add two three -- check by eye
example : add two three = five := rfl -- prove it
/-
Multiplication implemented as iteration of
addition of the second argument the first
argument number of times. Note that iterating
multiplication 0 times is defined to be one,
while iterating addition zero times is defined
to be zero.
-/
def mul : nt → nt → nt
| zero m := zero
| (succ n') m := add (mul n' m) m
-- test
example : mul two three = six := rfl
/-
Problem: represent the square function
on natural numbers declaratively.
-/
/-
Exponentiation is defined to be iteration
of multiplication of the first argument the
second argument number of times. Take some
time to really study the similarities and
differences in the definitions of add, mul,
and exp.
-/
def exp : nt → nt → nt
| n zero := one
| n (succ m') := mul n (exp n m')
-- tests
example : exp two three = succ (succ six) := rfl
example : exp zero three = zero := rfl
example : exp three zero = one := rfl
/-
PROOFS OF PROPERTIES
There are many properties we can try to prove. As
a starter, let's try to prove that zero is a left
identity for addition.
def add : nt → nt → nt
| zero m := m
| (succ n') m := succ (add n' m)
-/
example : ∀ (m : nt), add zero m = m := by simp [add]
/-
The crucial point in this case is that we already
know that, ∀ (m : nt), add zero m = m, *from the
definition of add*. In other words, add zero m is
*definitionally* equal to m.
def add : nt → nt → nt
| zero m := m
| (succ n') m := succ (add n' m)
The first rule serves as an axiom that allows us
instantly to conclude that: ∀ m, add zero m = m.
The proof is by simply invoking this axiom, which
we do by using the simplify (simp) tactic in Lean,
pointing it to the definition whose rules we want
it to employ.
Note that "by" is a way of introducing a proof
written using tactics without having the write
a complete "begin ... end" block.
-/
/-
Perhaps somewhat surprisingly, we hit a roadblock when
we try to prove that zero is a *right* identity. We don't
have an axiom for that! Rather we'll need to prove it
as a theorem.
-/
example : ∀ (m : nt), add m zero = m := by simp [add] --fail
/-
def add : nt → nt → nt
| zero m := m
| (succ n') m := succ (add n' m)
-/
-- Prove it!
theorem zero_is_right_zero : ∀ (m : nt), add m zero = m :=
begin
assume m,
induction m with m' h, -- by induction!
simp [add],
simp [add],
exact h,
end
-- NOTATION
/-
A complete, beautiful, and highly usable "module"
that implements an algebraic structure, such as
Boolean algebra or Peano arithmetic, often needs
to introduce convenient *notations* for applying
operations to arguments. We'd rather write (2 + 3)
than (nat.add zero.succ.succ zero.succ.succ.succ),
for example, even though we understand that they
mean the same thing.
In Lean, we can overload operators, such as +,
that are already defined in Lean's libraries,
and we will thereby inherit both precedence and
associativity properties that were carefully
crafted by the library designers.
-/
notation x + y := add x y
notation x * y := mul x y
#reduce five + six -- expect 11 .succs of zero
#reduce five * six + two -- expect 32 .succs of zero
-- Now we can use these notations in writing expressions
example : five + six = zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ := rfl
-- HOMEWORK
theorem add_commutes : ∀ (m n : nt), m + n = n + m :=
begin
assume m n,
induction m with m' h,
-- base case
-- exact rfl, does NOT work
simp [add],
rw zero_is_right_zero,
-- inductive case
simp [add],
rw h,
--
induction n with n' k,
--base case
rw <-h,
simp [add],
rw zero_is_right_zero,
--inductive case
end
end hidden |
[STATEMENT]
lemma while_mult_top:
"(x * top) \<star> z = z \<squnion> x * top"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top
[PROOF STEP]
have 1: "z \<squnion> x * top \<le> (x * top) \<star> z"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. z \<squnion> x * top \<le> x * top \<star> z
[PROOF STEP]
by (metis le_supI sup_ge1 while_def while_increasing tarski_top_omega)
[PROOF STATE]
proof (state)
this:
z \<squnion> x * top \<le> x * top \<star> z
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top
[PROOF STEP]
have "(x * top) \<star> z = z \<squnion> x * top * ((x * top) \<star> z)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top * (x * top \<star> z)
[PROOF STEP]
using while_left_unfold
[PROOF STATE]
proof (prove)
using this:
?x \<star> ?y = ?y \<squnion> ?x * (?x \<star> ?y)
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top * (x * top \<star> z)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
x * top \<star> z = z \<squnion> x * top * (x * top \<star> z)
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
x * top \<star> z = z \<squnion> x * top * (x * top \<star> z)
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top
[PROOF STEP]
have "... \<le> z \<squnion> x * top"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. z \<squnion> x * top * (x * top \<star> z) \<le> z \<squnion> x * top
[PROOF STEP]
using mult_right_isotone sup_right_isotone top_greatest mult_assoc
[PROOF STATE]
proof (prove)
using this:
?x \<le> ?y \<Longrightarrow> ?z * ?x \<le> ?z * ?y
?x \<le> ?y \<Longrightarrow> ?z \<squnion> ?x \<le> ?z \<squnion> ?y
?x \<le> top
?a * ?b * ?c = ?a * (?b * ?c)
goal (1 subgoal):
1. z \<squnion> x * top * (x * top \<star> z) \<le> z \<squnion> x * top
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
z \<squnion> x * top * (x * top \<star> z) \<le> z \<squnion> x * top
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
x * top \<star> z \<le> z \<squnion> x * top
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
x * top \<star> z \<le> z \<squnion> x * top
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top
[PROOF STEP]
using 1 order.antisym
[PROOF STATE]
proof (prove)
using this:
x * top \<star> z \<le> z \<squnion> x * top
z \<squnion> x * top \<le> x * top \<star> z
\<lbrakk>?a \<le> ?b; ?b \<le> ?a\<rbrakk> \<Longrightarrow> ?a = ?b
goal (1 subgoal):
1. x * top \<star> z = z \<squnion> x * top
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
x * top \<star> z = z \<squnion> x * top
goal:
No subgoals!
[PROOF STEP]
qed |
open import Agda.Primitive using (lzero; lsuc; _⊔_)
open import Relation.Binary.PropositionalEquality using (_≡_; refl)
open import SingleSorted.Substitution
open import Data.Nat using (ℕ; zero; suc)
import MultiSorted.Context as Context
module MultiSorted.Group where
data 𝒜 : Set₀ where
A : 𝒜
single-sort : ∀ (X : 𝒜) → X ≡ A
single-sort A = refl
open import MultiSorted.AlgebraicTheory
open import MultiSorted.AlgebraicTheory
data GroupOp : Set where
e : GroupOp
inv : GroupOp
mul : GroupOp
ctx : ∀ (n : ℕ) → Context.Context 𝒜
ctx zero = Context.ctx-empty
ctx (suc n) = Context.ctx-concat (ctx n) (Context.ctx-slot A)
-- the signature of the theory of small groups
-- has one constant, one unary operation, one binary operation
Σ : Signature {lzero} {lzero}
Σ = record { sort = 𝒜
; oper = GroupOp
; oper-arity = λ{ e → ctx 0 ; inv → ctx 1 ; mul → ctx 2}
; oper-sort = λ{ e → A ; inv → A ; mul → A}
}
open Signature Σ
singleton-context : (var (ctx-slot A)) → var (ctx-concat ctx-empty (ctx-slot A))
singleton-context (var-var {A}) = var-inr (var-var {A})
single-sort-context : ∀ {Γ : Context} (x : var Γ) → sort-of Γ x ≡ A
single-sort-context {Γ} x = single-sort (Context.sort-of 𝒜 Γ x)
single-sort-terms : ∀ {X : 𝒜} {Γ : Context} → Term Γ X ≡ Term Γ A
single-sort-terms {A} = refl
σ : ∀ {Γ : Context} {t : Term Γ A} → Γ ⇒s (ctx 1)
σ {Γ} {t} = λ{ (var-inr var-var) → t}
δ : ∀ {Γ : Context} {t : Term Γ A} {s : Term Γ A} → Γ ⇒s (ctx 2)
δ {Γ} {t} {s} = sub
where
sub : Γ ⇒s (ctx 2)
sub (var-inl x) rewrite (single-sort-terms {(sort-of (ctx 2) (var-inl x))} {Γ}) = t
sub (var-inr y) rewrite (single-sort-terms {(sort-of (ctx 2) (var-inr y))} {Γ}) = s
-- helper functions for creating terms
e' : ∀ {Γ : Context} → Term Γ A
e' {Γ} = tm-oper e λ()
_∗_ : ∀ {Γ} → Term Γ A → Term Γ A → Term Γ A
t ∗ s = tm-oper mul λ{ xs → δ {t = t} {s = s} xs}
_ⁱ : ∀ {Γ : Context} → Term Γ A → Term Γ A
t ⁱ = tm-oper inv λ{ x → σ {t = t} x}
-- _∗_ : ∀ {Γ} → Term Γ A → Term Γ A → Term Γ A
-- _∗_ {Γ} t s = tm-oper mul λ{ (var-inl i) → {!!} ; (var-inr i) → {!!}}
-- _ⁱ : ∀ {Γ : Context} → Term Γ A → Term Γ A
-- t ⁱ = tm-oper inv λ{ x → t }
infixl 5 _∗_
infix 6 _ⁱ
_ : Term (ctx 2) A
_ = tm-var (var-inl (var-inr var-var)) ∗ tm-var (var-inr var-var)
-- group equations
data GroupEq : Set where
mul-assoc e-left e-right inv-left inv-right : GroupEq
mul-assoc-eq : Equation Σ
e-left-eq : Equation Σ
e-right-eq : Equation Σ
inv-left-eq : Equation Σ
inv-right-eq : Equation Σ
mul-assoc-eq = record { eq-ctx = ctx 3
; eq-lhs = x ∗ y ∗ z
; eq-rhs = x ∗ (y ∗ z)
}
where
x : Term (ctx 3) A
y : Term (ctx 3) A
z : Term (ctx 3) A
x = tm-var (var-inl (var-inl (var-inr var-var)))
y = tm-var (var-inl (var-inr var-var))
z = tm-var (var-inr var-var)
e-left-eq = record { eq-ctx = ctx 1 ; eq-lhs = e' ∗ x ; eq-rhs = x }
where
x : Term (ctx 1) A
x = tm-var (var-inr var-var)
e-right-eq = record { eq-ctx = ctx 1 ; eq-lhs = x ∗ e' ; eq-rhs = x }
where
x : Term (ctx 1) A
x = tm-var (var-inr var-var)
inv-left-eq = record { eq-ctx = ctx 1 ; eq-lhs = x ⁱ ∗ x ; eq-rhs = e' }
where
x : Term (ctx 1) A
x = tm-var (var-inr var-var)
inv-right-eq = record { eq-ctx = ctx 1 ; eq-lhs = x ∗ x ⁱ ; eq-rhs = e' }
where
x : Term (ctx 1) A
x = tm-var (var-inr var-var)
𝒢 : Theory lzero Σ
𝒢 = record { ax = GroupEq
; ax-eq = λ{ mul-assoc → mul-assoc-eq
; e-left → e-left-eq
; e-right → e-right-eq
; inv-left → inv-left-eq
; inv-right → inv-right-eq
}
}
|
module India.Language.Core
import public India.Language.Core.Lexer
import public India.Language.Core.Parser
import public India.Language.Core.Types
%default total
|
(* Property from Case-Analysis for Rippling and Inductive Proof,
Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010.
This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.*)
theory TIP_prop_61
imports "../../Test_Base"
begin
datatype 'a list = nil2 | cons2 "'a" "'a list"
datatype Nat = Z | S "Nat"
fun x :: "'a list => 'a list => 'a list" where
"x (nil2) z = z"
| "x (cons2 z2 xs) z = cons2 z2 (x xs z)"
fun last :: "Nat list => Nat" where
"last (nil2) = Z"
| "last (cons2 z (nil2)) = z"
| "last (cons2 z (cons2 x2 x3)) = last (cons2 x2 x3)"
fun lastOfTwo :: "Nat list => Nat list => Nat" where
"lastOfTwo y (nil2) = last y"
| "lastOfTwo y (cons2 z2 x2) = last (cons2 z2 x2)"
theorem property0 :
"((last (x xs ys)) = (lastOfTwo xs ys))"
oops
end
|
-- Copyright (c) 2013 Radek Micek
module Main
import Common
import D3
main : IO ()
main = do
let width = 400
let height = 300
a <- mkNode "a"
b <- mkNode "b"
c <- mkNode "c"
d <- mkNode "d"
nodesArr <- mkArray [a, b, c, d]
ab <- mkLink a b ()
bc <- mkLink b c ()
ac <- mkLink a c ()
ad <- mkLink a d ()
linksArr <- mkArray [ab, bc, ac, ad]
fl <- mkForceLayout width height
fl ?? linkDistanceL 120 >=>
chargeL (-300)
putNodes fl nodesArr
putLinks fl linksArr
svg <- d3 ?? select "body" >=>
append "svg" >=>
attr "width" (show width) >=>
attr "height" (show height) >=>
style "border" "1px solid blue"
-- Style for arrows.
svg ?? append "svg:defs" >=>
append "svg:marker" >=>
attr "id" "arrow" >=>
attr "viewBox" "0 -7 16 14" >=>
attr "refX" "50" >=>
attr "markerWidth" "14" >=>
attr "markerHeight" "16" >=>
attr "orient" "auto" >=>
attr "fill" "green" >=>
append "svg:path" >=>
attr "d" "M0 -7 L16 0 L0 7"
linkLayer <- svg ?? append "svg:g"
nodeLayer <- svg ?? append "svg:g"
nodes <- nodeLayer ?? selectAll "text" >=>
bind nodesArr
nodes ?? enter >=>
append "svg:text" >=>
makeDraggableL fl >=>
text' (const . getNData)
links <- linkLayer ?? selectAll "line" >=>
bind linksArr
links ?? enter >=>
append "svg:line" >=>
style "stroke" "red" >=>
style "stroke-width" "1px" >=>
attr "marker-end" "url(#arrow)"
fl `onTickL` tickHandler nodes links
startL fl
return ()
where
tickHandler :
Sel NoData (Node String) ->
Sel NoData (Link String ()) ->
() -> IO ()
tickHandler nodes links () = do
nodes ??
attr' "x" (\d, i => pure show <$> getX d) >=>
attr' "y" (\d, i => pure show <$> getY d)
links ??
attr' "x1" (\d, i => getSource d >>= getX >>= pure . show) >=>
attr' "y1" (\d, i => getSource d >>= getY >>= pure . show) >=>
attr' "x2" (\d, i => getTarget d >>= getX >>= pure . show) >=>
attr' "y2" (\d, i => getTarget d >>= getY >>= pure . show)
return ()
|
(* Title: HOL/Analysis/Harmonic_Numbers.thy
Author: Manuel Eberl, TU München
*)
section \<open>Harmonic Numbers\<close>
theory Harmonic_Numbers
imports
Complex_Transcendental
Summation_Tests
begin
text \<open>
The definition of the Harmonic Numbers and the Euler-Mascheroni constant.
Also provides a reasonably accurate approximation of \<^term>\<open>ln 2 :: real\<close>
and the Euler-Mascheroni constant.
\<close>
subsection \<open>The Harmonic numbers\<close>
definition\<^marker>\<open>tag important\<close> harm :: "nat \<Rightarrow> 'a :: real_normed_field" where
"harm n = (\<Sum>k=1..n. inverse (of_nat k))"
lemma harm_altdef: "harm n = (\<Sum>k<n. inverse (of_nat (Suc k)))"
unfolding harm_def by (induction n) simp_all
lemma harm_Suc: "harm (Suc n) = harm n + inverse (of_nat (Suc n))"
by (simp add: harm_def)
lemma harm_nonneg: "harm n \<ge> (0 :: 'a :: {real_normed_field,linordered_field})"
unfolding harm_def by (intro sum_nonneg) simp_all
lemma harm_pos: "n > 0 \<Longrightarrow> harm n > (0 :: 'a :: {real_normed_field,linordered_field})"
unfolding harm_def by (intro sum_pos) simp_all
lemma harm_mono: "m \<le> n \<Longrightarrow> harm m \<le> (harm n :: 'a :: {real_normed_field,linordered_field})"
by(simp add: harm_def sum_mono2)
lemma of_real_harm: "of_real (harm n) = harm n"
unfolding harm_def by simp
lemma abs_harm [simp]: "(abs (harm n) :: real) = harm n"
using harm_nonneg[of n] by (rule abs_of_nonneg)
lemma norm_harm: "norm (harm n) = harm n"
by (subst of_real_harm [symmetric]) (simp add: harm_nonneg)
lemma harm_expand:
"harm 0 = 0"
"harm (Suc 0) = 1"
"harm (numeral n) = harm (pred_numeral n) + inverse (numeral n)"
proof -
have "numeral n = Suc (pred_numeral n)" by simp
also have "harm \<dots> = harm (pred_numeral n) + inverse (numeral n)"
by (subst harm_Suc, subst numeral_eq_Suc[symmetric]) simp
finally show "harm (numeral n) = harm (pred_numeral n) + inverse (numeral n)" .
qed (simp_all add: harm_def)
theorem not_convergent_harm: "\<not>convergent (harm :: nat \<Rightarrow> 'a :: real_normed_field)"
proof -
have "convergent (\<lambda>n. norm (harm n :: 'a)) \<longleftrightarrow>
convergent (harm :: nat \<Rightarrow> real)" by (simp add: norm_harm)
also have "\<dots> \<longleftrightarrow> convergent (\<lambda>n. \<Sum>k=Suc 0..Suc n. inverse (of_nat k) :: real)"
unfolding harm_def[abs_def] by (subst convergent_Suc_iff) simp_all
also have "... \<longleftrightarrow> convergent (\<lambda>n. \<Sum>k\<le>n. inverse (of_nat (Suc k)) :: real)"
by (subst sum.shift_bounds_cl_Suc_ivl) (simp add: atLeast0AtMost)
also have "... \<longleftrightarrow> summable (\<lambda>n. inverse (of_nat n) :: real)"
by (subst summable_Suc_iff [symmetric]) (simp add: summable_iff_convergent')
also have "\<not>..." by (rule not_summable_harmonic)
finally show ?thesis by (blast dest: convergent_norm)
qed
lemma harm_pos_iff [simp]: "harm n > (0 :: 'a :: {real_normed_field,linordered_field}) \<longleftrightarrow> n > 0"
by (rule iffI, cases n, simp add: harm_expand, simp, rule harm_pos)
lemma ln_diff_le_inverse:
assumes "x \<ge> (1::real)"
shows "ln (x + 1) - ln x < 1 / x"
proof -
from assms have "\<exists>z>x. z < x + 1 \<and> ln (x + 1) - ln x = (x + 1 - x) * inverse z"
by (intro MVT2) (auto intro!: derivative_eq_intros simp: field_simps)
then obtain z where z: "z > x" "z < x + 1" "ln (x + 1) - ln x = inverse z" by auto
have "ln (x + 1) - ln x = inverse z" by fact
also from z(1,2) assms have "\<dots> < 1 / x" by (simp add: field_simps)
finally show ?thesis .
qed
lemma ln_le_harm: "ln (real n + 1) \<le> (harm n :: real)"
proof (induction n)
fix n assume IH: "ln (real n + 1) \<le> harm n"
have "ln (real (Suc n) + 1) = ln (real n + 1) + (ln (real n + 2) - ln (real n + 1))" by simp
also have "(ln (real n + 2) - ln (real n + 1)) \<le> 1 / real (Suc n)"
using ln_diff_le_inverse[of "real n + 1"] by (simp add: add_ac)
also note IH
also have "harm n + 1 / real (Suc n) = harm (Suc n)" by (simp add: harm_Suc field_simps)
finally show "ln (real (Suc n) + 1) \<le> harm (Suc n)" by - simp
qed (simp_all add: harm_def)
lemma harm_at_top: "filterlim (harm :: nat \<Rightarrow> real) at_top sequentially"
proof (rule filterlim_at_top_mono)
show "eventually (\<lambda>n. harm n \<ge> ln (real (Suc n))) at_top"
using ln_le_harm by (intro always_eventually allI) (simp_all add: add_ac)
show "filterlim (\<lambda>n. ln (real (Suc n))) at_top sequentially"
by (intro filterlim_compose[OF ln_at_top] filterlim_compose[OF filterlim_real_sequentially]
filterlim_Suc)
qed
subsection \<open>The Euler-Mascheroni constant\<close>
text \<open>
The limit of the difference between the partial harmonic sum and the natural logarithm
(approximately 0.577216). This value occurs e.g. in the definition of the Gamma function.
\<close>
definition euler_mascheroni :: "'a :: real_normed_algebra_1" where
"euler_mascheroni = of_real (lim (\<lambda>n. harm n - ln (of_nat n)))"
lemma of_real_euler_mascheroni [simp]: "of_real euler_mascheroni = euler_mascheroni"
by (simp add: euler_mascheroni_def)
lemma harm_ge_ln: "harm n \<ge> ln (real n + 1)"
proof -
have "ln (n + 1) = (\<Sum>j<n. ln (real (Suc j + 1)) - ln (real (j + 1)))"
by (subst sum_lessThan_telescope) auto
also have "\<dots> \<le> (\<Sum>j<n. 1 / (Suc j))"
proof (intro sum_mono, clarify)
fix j assume j: "j < n"
have "\<exists>\<xi>. \<xi> > real j + 1 \<and> \<xi> < real j + 2 \<and>
ln (real j + 2) - ln (real j + 1) = (real j + 2 - (real j + 1)) * (1 / \<xi>)"
by (intro MVT2) (auto intro!: derivative_eq_intros)
then obtain \<xi> :: real
where \<xi>: "\<xi> \<in> {real j + 1..real j + 2}" "ln (real j + 2) - ln (real j + 1) = 1 / \<xi>"
by auto
note \<xi>(2)
also have "1 / \<xi> \<le> 1 / (Suc j)"
using \<xi>(1) by (auto simp: field_simps)
finally show "ln (real (Suc j + 1)) - ln (real (j + 1)) \<le> 1 / (Suc j)"
by (simp add: add_ac)
qed
also have "\<dots> = harm n"
by (simp add: harm_altdef field_simps)
finally show ?thesis by (simp add: add_ac)
qed
lemma decseq_harm_diff_ln: "decseq (\<lambda>n. harm (Suc n) - ln (Suc n))"
proof (rule decseq_SucI)
fix m :: nat
define n where "n = Suc m"
have "n > 0" by (simp add: n_def)
have "convex_on {0<..} (\<lambda>x :: real. -ln x)"
by (rule convex_on_realI[where f' = "\<lambda>x. -1/x"])
(auto intro!: derivative_eq_intros simp: field_simps)
hence "(-1 / (n + 1)) * (real n - real (n + 1)) \<le> (- ln (real n)) - (-ln (real (n + 1)))"
using \<open>n > 0\<close> by (intro convex_on_imp_above_tangent[where A = "{0<..}"])
(auto intro!: derivative_eq_intros simp: interior_open)
thus "harm (Suc n) - ln (Suc n) \<le> harm n - ln n"
by (auto simp: harm_Suc field_simps)
qed
lemma euler_mascheroni_sequence_nonneg:
assumes "n > 0"
shows "harm n - ln (real n) \<ge> (0 :: real)"
proof -
have "ln (real n) \<le> ln (real n + 1)"
using assms by simp
also have "\<dots> \<le> harm n"
by (rule harm_ge_ln)
finally show ?thesis by simp
qed
lemma euler_mascheroni_convergent: "convergent (\<lambda>n. harm n - ln n)"
proof -
have "harm (Suc n) - ln (real (Suc n)) \<ge> 0" for n :: nat
using euler_mascheroni_sequence_nonneg[of "Suc n"] by simp
hence "convergent (\<lambda>n. harm (Suc n) - ln (Suc n))"
by (intro Bseq_monoseq_convergent decseq_bounded[of _ 0] decseq_harm_diff_ln decseq_imp_monoseq)
auto
thus ?thesis
by (subst (asm) convergent_Suc_iff)
qed
lemma euler_mascheroni_sequence_decreasing:
"m > 0 \<Longrightarrow> m \<le> n \<Longrightarrow> harm n - ln (of_nat n) \<le> harm m - ln (of_nat m :: real)"
using decseqD[OF decseq_harm_diff_ln, of "m - 1" "n - 1"] by simp
lemma\<^marker>\<open>tag important\<close> euler_mascheroni_LIMSEQ:
"(\<lambda>n. harm n - ln (of_nat n) :: real) \<longlonglongrightarrow> euler_mascheroni"
unfolding euler_mascheroni_def
by (simp add: convergent_LIMSEQ_iff [symmetric] euler_mascheroni_convergent)
lemma euler_mascheroni_LIMSEQ_of_real:
"(\<lambda>n. of_real (harm n - ln (of_nat n))) \<longlonglongrightarrow>
(euler_mascheroni :: 'a :: {real_normed_algebra_1, topological_space})"
proof -
have "(\<lambda>n. of_real (harm n - ln (of_nat n))) \<longlonglongrightarrow> (of_real (euler_mascheroni) :: 'a)"
by (intro tendsto_of_real euler_mascheroni_LIMSEQ)
thus ?thesis by simp
qed
lemma euler_mascheroni_sum_real:
"(\<lambda>n. inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2)) :: real)
sums euler_mascheroni"
using sums_add[OF telescope_sums[OF LIMSEQ_Suc[OF euler_mascheroni_LIMSEQ]]
telescope_sums'[OF LIMSEQ_inverse_real_of_nat]]
by (simp_all add: harm_def algebra_simps)
lemma euler_mascheroni_sum:
"(\<lambda>n. inverse (of_nat (n+1)) + of_real (ln (of_nat (n+1))) - of_real (ln (of_nat (n+2))))
sums (euler_mascheroni :: 'a :: {banach, real_normed_field})"
proof -
have "(\<lambda>n. of_real (inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2))))
sums (of_real euler_mascheroni :: 'a :: {banach, real_normed_field})"
by (subst sums_of_real_iff) (rule euler_mascheroni_sum_real)
thus ?thesis by simp
qed
theorem alternating_harmonic_series_sums: "(\<lambda>k. (-1)^k / real_of_nat (Suc k)) sums ln 2"
proof -
let ?f = "\<lambda>n. harm n - ln (real_of_nat n)"
let ?g = "\<lambda>n. if even n then 0 else (2::real)"
let ?em = "\<lambda>n. harm n - ln (real_of_nat n)"
have "eventually (\<lambda>n. ?em (2*n) - ?em n + ln 2 = (\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k))) at_top"
using eventually_gt_at_top[of "0::nat"]
proof eventually_elim
fix n :: nat assume n: "n > 0"
have "(\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k)) =
(\<Sum>k<2*n. ((-1)^k + ?g k) / of_nat (Suc k)) - (\<Sum>k<2*n. ?g k / of_nat (Suc k))"
by (simp add: sum.distrib algebra_simps divide_inverse)
also have "(\<Sum>k<2*n. ((-1)^k + ?g k) / real_of_nat (Suc k)) = harm (2*n)"
unfolding harm_altdef by (intro sum.cong) (auto simp: field_simps)
also have "(\<Sum>k<2*n. ?g k / real_of_nat (Suc k)) = (\<Sum>k|k<2*n \<and> odd k. ?g k / of_nat (Suc k))"
by (intro sum.mono_neutral_right) auto
also have "\<dots> = (\<Sum>k|k<2*n \<and> odd k. 2 / (real_of_nat (Suc k)))"
by (intro sum.cong) auto
also have "(\<Sum>k|k<2*n \<and> odd k. 2 / (real_of_nat (Suc k))) = harm n"
unfolding harm_altdef
by (intro sum.reindex_cong[of "\<lambda>n. 2*n+1"]) (auto simp: inj_on_def field_simps elim!: oddE)
also have "harm (2*n) - harm n = ?em (2*n) - ?em n + ln 2" using n
by (simp_all add: algebra_simps ln_mult)
finally show "?em (2*n) - ?em n + ln 2 = (\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k))" ..
qed
moreover have "(\<lambda>n. ?em (2*n) - ?em n + ln (2::real))
\<longlonglongrightarrow> euler_mascheroni - euler_mascheroni + ln 2"
by (intro tendsto_intros euler_mascheroni_LIMSEQ filterlim_compose[OF euler_mascheroni_LIMSEQ]
filterlim_subseq) (auto simp: strict_mono_def)
hence "(\<lambda>n. ?em (2*n) - ?em n + ln (2::real)) \<longlonglongrightarrow> ln 2" by simp
ultimately have "(\<lambda>n. (\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k))) \<longlonglongrightarrow> ln 2"
by (blast intro: Lim_transform_eventually)
moreover have "summable (\<lambda>k. (-1)^k * inverse (real_of_nat (Suc k)))"
using LIMSEQ_inverse_real_of_nat
by (intro summable_Leibniz(1) decseq_imp_monoseq decseq_SucI) simp_all
hence A: "(\<lambda>n. \<Sum>k<n. (-1)^k / real_of_nat (Suc k)) \<longlonglongrightarrow> (\<Sum>k. (-1)^k / real_of_nat (Suc k))"
by (simp add: summable_sums_iff divide_inverse sums_def)
from filterlim_compose[OF this filterlim_subseq[of "(*) (2::nat)"]]
have "(\<lambda>n. \<Sum>k<2*n. (-1)^k / real_of_nat (Suc k)) \<longlonglongrightarrow> (\<Sum>k. (-1)^k / real_of_nat (Suc k))"
by (simp add: strict_mono_def)
ultimately have "(\<Sum>k. (- 1) ^ k / real_of_nat (Suc k)) = ln 2" by (intro LIMSEQ_unique)
with A show ?thesis by (simp add: sums_def)
qed
lemma alternating_harmonic_series_sums':
"(\<lambda>k. inverse (real_of_nat (2*k+1)) - inverse (real_of_nat (2*k+2))) sums ln 2"
unfolding sums_def
proof (rule Lim_transform_eventually)
show "(\<lambda>n. \<Sum>k<2*n. (-1)^k / (real_of_nat (Suc k))) \<longlonglongrightarrow> ln 2"
using alternating_harmonic_series_sums unfolding sums_def
by (rule filterlim_compose) (rule mult_nat_left_at_top, simp)
show "eventually (\<lambda>n. (\<Sum>k<2*n. (-1)^k / (real_of_nat (Suc k))) =
(\<Sum>k<n. inverse (real_of_nat (2*k+1)) - inverse (real_of_nat (2*k+2)))) sequentially"
proof (intro always_eventually allI)
fix n :: nat
show "(\<Sum>k<2*n. (-1)^k / (real_of_nat (Suc k))) =
(\<Sum>k<n. inverse (real_of_nat (2*k+1)) - inverse (real_of_nat (2*k+2)))"
by (induction n) (simp_all add: inverse_eq_divide)
qed
qed
subsection\<^marker>\<open>tag unimportant\<close> \<open>Bounds on the Euler-Mascheroni constant\<close>
(* TODO: perhaps move this section away to remove unnecessary dependency on integration *)
(* TODO: Move? *)
lemma ln_inverse_approx_le:
assumes "(x::real) > 0" "a > 0"
shows "ln (x + a) - ln x \<le> a * (inverse x + inverse (x + a))/2" (is "_ \<le> ?A")
proof -
define f' where "f' = (inverse (x + a) - inverse x)/a"
let ?f = "\<lambda>t. (t - x) * f' + inverse x"
let ?F = "\<lambda>t. (t - x)^2 * f' / 2 + t * inverse x"
have deriv: "\<exists>D. ((\<lambda>x. ?F x - ln x) has_field_derivative D) (at \<xi>) \<and> D \<ge> 0"
if "\<xi> \<ge> x" "\<xi> \<le> x + a" for \<xi>
proof -
from that assms have t: "0 \<le> (\<xi> - x) / a" "(\<xi> - x) / a \<le> 1" by simp_all
have "inverse \<xi> = inverse ((1 - (\<xi> - x) / a) *\<^sub>R x + ((\<xi> - x) / a) *\<^sub>R (x + a))" (is "_ = ?A")
using assms by (simp add: field_simps)
also from assms have "convex_on {x..x+a} inverse" by (intro convex_on_inverse) auto
from convex_onD_Icc[OF this _ t] assms
have "?A \<le> (1 - (\<xi> - x) / a) * inverse x + (\<xi> - x) / a * inverse (x + a)" by simp
also have "\<dots> = (\<xi> - x) * f' + inverse x" using assms
by (simp add: f'_def divide_simps) (simp add: field_simps)
finally have "?f \<xi> - 1 / \<xi> \<ge> 0" by (simp add: field_simps)
moreover have "((\<lambda>x. ?F x - ln x) has_field_derivative ?f \<xi> - 1 / \<xi>) (at \<xi>)"
using that assms by (auto intro!: derivative_eq_intros simp: field_simps)
ultimately show ?thesis by blast
qed
have "?F x - ln x \<le> ?F (x + a) - ln (x + a)"
by (rule DERIV_nonneg_imp_nondecreasing[of x "x + a", OF _ deriv]) (use assms in auto)
thus ?thesis
using assms by (simp add: f'_def divide_simps) (simp add: algebra_simps power2_eq_square)?
qed
lemma ln_inverse_approx_ge:
assumes "(x::real) > 0" "x < y"
shows "ln y - ln x \<ge> 2 * (y - x) / (x + y)" (is "_ \<ge> ?A")
proof -
define m where "m = (x+y)/2"
define f' where "f' = -inverse (m^2)"
from assms have m: "m > 0" by (simp add: m_def)
let ?F = "\<lambda>t. (t - m)^2 * f' / 2 + t / m"
let ?f = "\<lambda>t. (t - m) * f' + inverse m"
have deriv: "\<exists>D. ((\<lambda>x. ln x - ?F x) has_field_derivative D) (at \<xi>) \<and> D \<ge> 0"
if "\<xi> \<ge> x" "\<xi> \<le> y" for \<xi>
proof -
from that assms have "inverse \<xi> - inverse m \<ge> f' * (\<xi> - m)"
by (intro convex_on_imp_above_tangent[of "{0<..}"] convex_on_inverse)
(auto simp: m_def interior_open f'_def power2_eq_square intro!: derivative_eq_intros)
hence "1 / \<xi> - ?f \<xi> \<ge> 0" by (simp add: field_simps f'_def)
moreover have "((\<lambda>x. ln x - ?F x) has_field_derivative 1 / \<xi> - ?f \<xi>) (at \<xi>)"
using that assms m by (auto intro!: derivative_eq_intros simp: field_simps)
ultimately show ?thesis by blast
qed
have "ln x - ?F x \<le> ln y - ?F y"
by (rule DERIV_nonneg_imp_nondecreasing[of x y, OF _ deriv]) (use assms in auto)
hence "ln y - ln x \<ge> ?F y - ?F x"
by (simp add: algebra_simps)
also have "?F y - ?F x = ?A"
using assms by (simp add: f'_def m_def divide_simps) (simp add: algebra_simps power2_eq_square)
finally show ?thesis .
qed
lemma euler_mascheroni_lower:
"euler_mascheroni \<ge> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 2))"
and euler_mascheroni_upper:
"euler_mascheroni \<le> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 1))"
proof -
define D :: "_ \<Rightarrow> real"
where "D n = inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2))" for n
let ?g = "\<lambda>n. ln (of_nat (n+2)) - ln (of_nat (n+1)) - inverse (of_nat (n+1)) :: real"
define inv where [abs_def]: "inv n = inverse (real_of_nat n)" for n
fix n :: nat
note summable = sums_summable[OF euler_mascheroni_sum_real, folded D_def]
have sums: "(\<lambda>k. (inv (Suc (k + (n+1))) - inv (Suc (Suc k + (n+1))))/2) sums ((inv (Suc (0 + (n+1))) - 0)/2)"
unfolding inv_def
by (intro sums_divide telescope_sums' LIMSEQ_ignore_initial_segment LIMSEQ_inverse_real_of_nat)
have sums': "(\<lambda>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2) sums ((inv (Suc (0 + n)) - 0)/2)"
unfolding inv_def
by (intro sums_divide telescope_sums' LIMSEQ_ignore_initial_segment LIMSEQ_inverse_real_of_nat)
from euler_mascheroni_sum_real have "euler_mascheroni = (\<Sum>k. D k)"
by (simp add: sums_iff D_def)
also have "\<dots> = (\<Sum>k. D (k + Suc n)) + (\<Sum>k\<le>n. D k)"
by (subst suminf_split_initial_segment[OF summable, of "Suc n"],
subst lessThan_Suc_atMost) simp
finally have sum: "(\<Sum>k\<le>n. D k) - euler_mascheroni = -(\<Sum>k. D (k + Suc n))" by simp
note sum
also have "\<dots> \<le> -(\<Sum>k. (inv (k + Suc n + 1) - inv (k + Suc n + 2)) / 2)"
proof (intro le_imp_neg_le suminf_le allI summable_ignore_initial_segment[OF summable])
fix k' :: nat
define k where "k = k' + Suc n"
hence k: "k > 0" by (simp add: k_def)
have "real_of_nat (k+1) > 0" by (simp add: k_def)
with ln_inverse_approx_le[OF this zero_less_one]
have "ln (of_nat k + 2) - ln (of_nat k + 1) \<le> (inv (k+1) + inv (k+2))/2"
by (simp add: inv_def add_ac)
hence "(inv (k+1) - inv (k+2))/2 \<le> inv (k+1) + ln (of_nat (k+1)) - ln (of_nat (k+2))"
by (simp add: field_simps)
also have "\<dots> = D k" unfolding D_def inv_def ..
finally show "D (k' + Suc n) \<ge> (inv (k' + Suc n + 1) - inv (k' + Suc n + 2)) / 2"
by (simp add: k_def)
from sums_summable[OF sums]
show "summable (\<lambda>k. (inv (k + Suc n + 1) - inv (k + Suc n + 2))/2)" by simp
qed
also from sums have "\<dots> = -inv (n+2) / 2" by (simp add: sums_iff)
finally have "euler_mascheroni \<ge> (\<Sum>k\<le>n. D k) + 1 / (of_nat (2 * (n+2)))"
by (simp add: inv_def field_simps)
also have "(\<Sum>k\<le>n. D k) = harm (Suc n) - (\<Sum>k\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1)))"
unfolding harm_altdef D_def by (subst lessThan_Suc_atMost) (simp add: sum.distrib sum_subtractf)
also have "(\<Sum>k\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1))) = ln (of_nat (n+2))"
by (subst atLeast0AtMost [symmetric], subst sum_Suc_diff) simp_all
finally show "euler_mascheroni \<ge> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 2))"
by simp
note sum
also have "-(\<Sum>k. D (k + Suc n)) \<ge> -(\<Sum>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2)"
proof (intro le_imp_neg_le suminf_le allI summable_ignore_initial_segment[OF summable])
fix k' :: nat
define k where "k = k' + Suc n"
hence k: "k > 0" by (simp add: k_def)
have "real_of_nat (k+1) > 0" by (simp add: k_def)
from ln_inverse_approx_ge[of "of_nat k + 1" "of_nat k + 2"]
have "2 / (2 * real_of_nat k + 3) \<le> ln (of_nat (k+2)) - ln (real_of_nat (k+1))"
by (simp add: add_ac)
hence "D k \<le> 1 / real_of_nat (k+1) - 2 / (2 * real_of_nat k + 3)"
by (simp add: D_def inverse_eq_divide inv_def)
also have "\<dots> = inv ((k+1)*(2*k+3))" unfolding inv_def by (simp add: field_simps)
also have "\<dots> \<le> inv (2*k*(k+1))" unfolding inv_def using k
by (intro le_imp_inverse_le)
(simp add: algebra_simps, simp del: of_nat_add)
also have "\<dots> = (inv k - inv (k+1))/2" unfolding inv_def using k
by (simp add: divide_simps del: of_nat_mult) (simp add: algebra_simps)
finally show "D k \<le> (inv (Suc (k' + n)) - inv (Suc (Suc k' + n)))/2" unfolding k_def by simp
next
from sums_summable[OF sums']
show "summable (\<lambda>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2)" by simp
qed
also from sums' have "(\<Sum>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2) = inv (n+1)/2"
by (simp add: sums_iff)
finally have "euler_mascheroni \<le> (\<Sum>k\<le>n. D k) + 1 / of_nat (2 * (n+1))"
by (simp add: inv_def field_simps)
also have "(\<Sum>k\<le>n. D k) = harm (Suc n) - (\<Sum>k\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1)))"
unfolding harm_altdef D_def by (subst lessThan_Suc_atMost) (simp add: sum.distrib sum_subtractf)
also have "(\<Sum>k\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1))) = ln (of_nat (n+2))"
by (subst atLeast0AtMost [symmetric], subst sum_Suc_diff) simp_all
finally show "euler_mascheroni \<le> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 1))"
by simp
qed
lemma euler_mascheroni_pos: "euler_mascheroni > (0::real)"
using euler_mascheroni_lower[of 0] ln_2_less_1 by (simp add: harm_def)
context
begin
private lemma ln_approx_aux:
fixes n :: nat and x :: real
defines "y \<equiv> (x-1)/(x+1)"
assumes x: "x > 0" "x \<noteq> 1"
shows "inverse (2*y^(2*n+1)) * (ln x - (\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) \<in>
{0..(1 / (1 - y^2) / of_nat (2*n+1))}"
proof -
from x have norm_y: "norm y < 1" unfolding y_def by simp
from power_strict_mono[OF this, of 2] have norm_y': "norm y^2 < 1" by simp
let ?f = "\<lambda>k. 2 * y ^ (2*k+1) / of_nat (2*k+1)"
note sums = ln_series_quadratic[OF x(1)]
define c where "c = inverse (2*y^(2*n+1))"
let ?d = "c * (ln x - (\<Sum>k<n. ?f k))"
have "\<And>k. y\<^sup>2^k / of_nat (2*(k+n)+1) \<le> y\<^sup>2 ^ k / of_nat (2*n+1)"
by (intro divide_left_mono mult_right_mono mult_pos_pos zero_le_power[of "y^2"]) simp_all
moreover {
have "(\<lambda>k. ?f (k + n)) sums (ln x - (\<Sum>k<n. ?f k))"
using sums_split_initial_segment[OF sums] by (simp add: y_def)
hence "(\<lambda>k. c * ?f (k + n)) sums ?d" by (rule sums_mult)
also have "(\<lambda>k. c * (2*y^(2*(k+n)+1) / of_nat (2*(k+n)+1))) =
(\<lambda>k. (c * (2*y^(2*n+1))) * ((y^2)^k / of_nat (2*(k+n)+1)))"
by (simp only: ring_distribs power_add power_mult) (simp add: mult_ac)
also from x have "c * (2*y^(2*n+1)) = 1" by (simp add: c_def y_def)
finally have "(\<lambda>k. (y^2)^k / of_nat (2*(k+n)+1)) sums ?d" by simp
} note sums' = this
moreover from norm_y' have "(\<lambda>k. (y^2)^k / of_nat (2*n+1)) sums (1 / (1 - y^2) / of_nat (2*n+1))"
by (intro sums_divide geometric_sums) (simp_all add: norm_power)
ultimately have "?d \<le> (1 / (1 - y^2) / of_nat (2*n+1))" by (rule sums_le)
moreover have "c * (ln x - (\<Sum>k<n. 2 * y ^ (2 * k + 1) / real_of_nat (2 * k + 1))) \<ge> 0"
by (intro sums_le[OF _ sums_zero sums']) simp_all
ultimately show ?thesis unfolding c_def by simp
qed
lemma
fixes n :: nat and x :: real
defines "y \<equiv> (x-1)/(x+1)"
defines "approx \<equiv> (\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))"
defines "d \<equiv> y^(2*n+1) / (1 - y^2) / of_nat (2*n+1)"
assumes x: "x > 1"
shows ln_approx_bounds: "ln x \<in> {approx..approx + 2*d}"
and ln_approx_abs: "abs (ln x - (approx + d)) \<le> d"
proof -
define c where "c = 2*y^(2*n+1)"
from x have c_pos: "c > 0" unfolding c_def y_def
by (intro mult_pos_pos zero_less_power) simp_all
have A: "inverse c * (ln x - (\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) \<in>
{0.. (1 / (1 - y^2) / of_nat (2*n+1))}" using assms unfolding y_def c_def
by (intro ln_approx_aux) simp_all
hence "inverse c * (ln x - (\<Sum>k<n. 2*y^(2*k+1)/of_nat (2*k+1))) \<le> (1 / (1-y^2) / of_nat (2*n+1))"
by simp
hence "(ln x - (\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) / c \<le> (1 / (1 - y^2) / of_nat (2*n+1))"
by (auto simp add: field_split_simps)
with c_pos have "ln x \<le> c / (1 - y^2) / of_nat (2*n+1) + approx"
by (subst (asm) pos_divide_le_eq) (simp_all add: mult_ac approx_def)
moreover {
from A c_pos have "0 \<le> c * (inverse c * (ln x - (\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))))"
by (intro mult_nonneg_nonneg[of c]) simp_all
also have "\<dots> = (c * inverse c) * (ln x - (\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1)))"
by (simp add: mult_ac)
also from c_pos have "c * inverse c = 1" by simp
finally have "ln x \<ge> approx" by (simp add: approx_def)
}
ultimately show "ln x \<in> {approx..approx + 2*d}" by (simp add: c_def d_def)
thus "abs (ln x - (approx + d)) \<le> d" by auto
qed
end
lemma euler_mascheroni_bounds:
fixes n :: nat assumes "n \<ge> 1" defines "t \<equiv> harm n - ln (of_nat (Suc n)) :: real"
shows "euler_mascheroni \<in> {t + inverse (of_nat (2*(n+1)))..t + inverse (of_nat (2*n))}"
using assms euler_mascheroni_upper[of "n-1"] euler_mascheroni_lower[of "n-1"]
unfolding t_def by (cases n) (simp_all add: harm_Suc t_def inverse_eq_divide)
lemma euler_mascheroni_bounds':
fixes n :: nat assumes "n \<ge> 1" "ln (real_of_nat (Suc n)) \<in> {l<..<u}"
shows "euler_mascheroni \<in>
{harm n - u + inverse (of_nat (2*(n+1)))<..<harm n - l + inverse (of_nat (2*n))}"
using euler_mascheroni_bounds[OF assms(1)] assms(2) by auto
text \<open>
Approximation of \<^term>\<open>ln 2\<close>. The lower bound is accurate to about 0.03; the upper
bound is accurate to about 0.0015.
\<close>
lemma ln2_ge_two_thirds: "2/3 \<le> ln (2::real)"
and ln2_le_25_over_36: "ln (2::real) \<le> 25/36"
using ln_approx_bounds[of 2 1, simplified, simplified eval_nat_numeral, simplified] by simp_all
text \<open>
Approximation of the Euler-Mascheroni constant. The lower bound is accurate to about 0.0015;
the upper bound is accurate to about 0.015.
\<close>
lemma euler_mascheroni_gt_19_over_33: "(euler_mascheroni :: real) > 19/33" (is ?th1)
and euler_mascheroni_less_13_over_22: "(euler_mascheroni :: real) < 13/22" (is ?th2)
proof -
have "ln (real (Suc 7)) = 3 * ln 2" by (simp add: ln_powr [symmetric])
also from ln_approx_bounds[of 2 3] have "\<dots> \<in> {3*307/443<..<3*4615/6658}"
by (simp add: eval_nat_numeral)
finally have "ln (real (Suc 7)) \<in> \<dots>" .
from euler_mascheroni_bounds'[OF _ this] have "?th1 \<and> ?th2" by (simp_all add: harm_expand)
thus ?th1 ?th2 by blast+
qed
end
|
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
op_a1 := 1.5214:
op_a2 := 0.5764:
op_b1 := 1.1284:
op_b2 := 0.3183:
op_beta := (rs, z, xs0, xs1) ->
op_qab/b88_zab(1, op_f, rs, z, xs0, xs1):
f_op := (rs, z, xt, xs0, xs1) ->
- (1 - z^2)*n_total(rs)/4.0
* (op_a1*op_beta(rs, z, xs0, xs1) + op_a2)
/ (op_beta(rs, z, xs0, xs1)^4 + op_b1*op_beta(rs, z, xs0, xs1)^3 + op_b2*op_beta(rs, z, xs0, xs1)^2):
f := (rs, z, xt, xs0, xs1) ->
f_op(rs, z, xt, xs0, xs1):
|
module Data.Tagged
import Data.Bifunctor
import Data.Profunctor
%default total
public export
data Tagged : (a : Type) -> (b : Type) -> Type where
MkTagged: b -> Tagged a b
public export
retag : Tagged s b -> Tagged t b
retag (MkTagged b) = MkTagged b
||| Alias for 'unTagged'
public export
untag : Tagged s b -> b
untag (MkTagged x) = x
||| Tag a value with its own type.
public export
tagSelf : a -> Tagged a a
tagSelf = MkTagged
||| 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second.
public export
asTaggedTypeOf : s -> Tagged s b -> s
asTaggedTypeOf = const
||| 'untagSelf' is a type-restricted version of 'untag'.
public export
untagSelf : Tagged a a -> a
untagSelf (MkTagged x) = x
public export
Semigroup a => Semigroup (Tagged s a) where
(MkTagged a) <+> (MkTagged b) = MkTagged (a <+> b)
public export
Monoid a => Monoid (Tagged s a) where
neutral = MkTagged neutral
public export
Functor (Tagged s) where
map f (MkTagged x) = MkTagged (f x)
public export
implementation Applicative (Tagged s) where
pure = MkTagged
(MkTagged f) <*> (MkTagged x) = MkTagged (f x)
public export
implementation Monad (Tagged s) where
(MkTagged m) >>= k = k m
public export
implementation Bifunctor Tagged where
bimap _ g (MkTagged b) = MkTagged (g b)
public export
implementation Profunctor Tagged where
dimap _ f (MkTagged s) = MkTagged (f s)
lmap _ = retag
rmap = map
public export
implementation Choice Tagged where
left' (MkTagged b) = MkTagged (Left b)
right' (MkTagged b) = MkTagged (Right b)
|
Formal statement is: lemma minus_right: "prod a (- b) = - prod a b" Informal statement is: The product of a number and the negative of another number is the negative of the product of the two numbers. |
data_project = "[NAME]";
data_path_detail = "[SRC_DETAIL]";
data_all = data_load(data_path_detail);
# data_known_paths = c("/example/path/");
# data_all <- subset(data_all, !(path %in% data_known_paths));
|
FUNCTION:NAME
:BEGIN
:END
-- @@stderr --
dtrace: script 'test/unittest/actions/exit/tst.end-exit.d' matched 2 probes
|
[STATEMENT]
lemma cart_basis_eq_set_of_vector_cart_basis':
"cart_basis = set_of_vector (cart_basis')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cart_basis = set_of_vector cart_basis'
[PROOF STEP]
unfolding cart_basis_def cart_basis'_def set_of_vector_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {axis i (1::'a) |i. i \<in> UNIV} = {(\<chi>i. axis i (1::'a)) $ i |i. i \<in> UNIV}
[PROOF STEP]
by auto |
State Before: ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a : α
l : List α
⊢ indexOf a l ≤ length l State After: case nil
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a : α
⊢ indexOf a [] ≤ length []
case cons
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
⊢ indexOf a (b :: l) ≤ length (b :: l) Tactic: induction' l with b l ih State Before: case cons
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
⊢ indexOf a (b :: l) ≤ length (b :: l) State After: case cons
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
⊢ (if a = b then 0 else succ (indexOf a l)) ≤ length l + 1 Tactic: simp only [length, indexOf_cons] State Before: case cons
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
⊢ (if a = b then 0 else succ (indexOf a l)) ≤ length l + 1 State After: case pos
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
h : a = b
⊢ (if a = b then 0 else succ (indexOf a l)) ≤ length l + 1
case neg
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
h : ¬a = b
⊢ (if a = b then 0 else succ (indexOf a l)) ≤ length l + 1 Tactic: by_cases h : a = b State Before: case neg
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
h : ¬a = b
⊢ (if a = b then 0 else succ (indexOf a l)) ≤ length l + 1 State After: case neg
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
h : ¬a = b
⊢ succ (indexOf a l) ≤ length l + 1 Tactic: rw [if_neg h] State Before: case neg
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
h : ¬a = b
⊢ succ (indexOf a l) ≤ length l + 1 State After: no goals Tactic: exact succ_le_succ ih State Before: case nil
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a : α
⊢ indexOf a [] ≤ length [] State After: no goals Tactic: rfl State Before: case pos
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
h : a = b
⊢ (if a = b then 0 else succ (indexOf a l)) ≤ length l + 1 State After: case pos
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
h : a = b
⊢ 0 ≤ length l + 1 Tactic: rw [if_pos h] State Before: case pos
ι : Type ?u.80422
α : Type u
β : Type v
γ : Type w
δ : Type x
l₁ l₂ : List α
inst✝ : DecidableEq α
a b : α
l : List α
ih : indexOf a l ≤ length l
h : a = b
⊢ 0 ≤ length l + 1 State After: no goals Tactic: exact Nat.zero_le _ |
Anthem key offers a world that is a constant living and breathing challenge for anyone daring to explore its vast territories. To face the unknown threats, you must be well prepared, and luckily — you are. Choose one out of four battle-suits: Ranger, Colossus, Storm, or Interceptor, and fight with all your might!
Anthem key unlocks a window of unlimited potential. Whether it’s the skies, the land, the undergrounds, or the underwater realm, each of the environments are packed with formidable foes to face, numerous tasks to accomplish, and a variety of loot to discover!
Buy Anthem key and enter a world long-forgotten by its creators. Abandoned and newly discovered planet bursts out with defensive mechanisms, and there’s quite a lot to protect. This world is as deadly as it is beautiful and breathtaking. Fight to ensure your survival and discover the wonders within.
Anthem key doesn’t deliver just a game, it’s an experience worth your while to say the least. Your character is equipped with numerous weapons, your battle-suit is upgradeable to extents that are hard to describe, and an endless open-world exploration offers new challenges with each go.
Anthem key presents an ambitious piece that promises to deliver a sensational experience for every player alike. Anthem offers you an unprecedented opportunity to enter this new adventure as one of the very first explorers out there. This World untainted by men is yours to tame — one of the greatest adventures in your gaming-life await! |
module Common where
open import Data.String
using (String)
-- Basic sorts -----------------------------------------------------------------
Id : Set
Id = String
|
State Before: R : Type u_1
inst✝ : Semiring R
f✝ f : R[X]
⊢ coeff (reverse f) 0 = leadingCoeff f State After: no goals Tactic: rw [coeff_reverse, revAt_le (zero_le f.natDegree), tsub_zero, leadingCoeff] |
Formal statement is: proposition contour_integral_uniform_limit: assumes ev_fint: "eventually (\<lambda>n::'a. (f n) contour_integrable_on \<gamma>) F" and ul_f: "uniform_limit (path_image \<gamma>) f l F" and noleB: "\<And>t. t \<in> {0..1} \<Longrightarrow> norm (vector_derivative \<gamma> (at t)) \<le> B" and \<gamma>: "valid_path \<gamma>" and [simp]: "\<not> trivial_limit F" shows "l contour_integrable_on \<gamma>" "((\<lambda>n. contour_integral \<gamma> (f n)) \<longlongrightarrow> contour_integral \<gamma> l) F" Informal statement is: If $f_n$ is a sequence of functions that are all integrable over a path $\gamma$, and if $f_n$ converges uniformly to $f$ over the image of $\gamma$, then $f$ is integrable over $\gamma$, and the sequence of integrals of $f_n$ converges to the integral of $f$. |
If $I$ is a finite set, $F_i$ is a measurable set for each $i \in I$, and the sets $F_i$ are pairwise disjoint, then the measure of the union of the $F_i$ is the sum of the measures of the $F_i$. |
module Generic.Lib.Reflection.Fold where
open import Generic.Lib.Intro
open import Generic.Lib.Decidable
open import Generic.Lib.Category
open import Generic.Lib.Data.Nat
open import Generic.Lib.Data.String
open import Generic.Lib.Data.Maybe
open import Generic.Lib.Data.List
open import Generic.Lib.Reflection.Core
foldTypeOf : Data Type -> Type
foldTypeOf (packData d a b cs ns) = appendType iab ∘ pi "π" π ∘ pi "P" P $ cs ʰ→ from ‵→ to where
infixr 5 _ʰ→_
i = countPis a
j = countPis b
ab = appendType a b
iab = implicitize ab
π = implRelArg (quoteTerm Level)
P = explRelArg ∘ appendType (shiftBy (suc j) b) ∘ agda-sort ∘ set $ pureVar j
hyp = mapName (λ p -> appVar p ∘ drop i) d ∘ shiftBy (2 + j)
_ʰ→_ = flip $ foldr (λ c r -> hyp c ‵→ shift r)
from = appDef d (pisToArgVars (2 + i + j) ab)
to = appVar 1 (pisToArgVars (3 + j) b)
foldClausesOf : Name -> Data Type -> List Clause
foldClausesOf f (packData d a b cs ns) = allToList $ mapAllInd (λ {a} n -> clauseOf n a) ns where
k = length cs
clauseOf : ℕ -> Type -> Name -> Clause
clauseOf i c n = clause lhs rhs where
args = explPisToNames c
j = length args
lhs = patVars ("P" ∷ unmap (λ n -> "f" ++ˢ showName n) ns)
∷ʳ explRelArg (patCon n (patVars args))
tryHyp : ℕ -> ℕ -> Type -> Maybe Term
tryHyp m l (explPi r s a b) = explLam s <$> tryHyp (suc m) l b
tryHyp m l (pi s a b) = tryHyp m l b
tryHyp m l (appDef e _) = d == e ?> vis appDef f (pars ∷ʳ rarg) where
pars = map (λ i -> pureVar (m + i)) $ downFromTo (suc k + j) j
rarg = vis appVar (m + l) $ map pureVar (downFrom m)
tryHyp m l b = nothing
hyps : ℕ -> Type -> List Term
hyps (suc l) (explPi r s a b) = fromMaybe (pureVar l) (tryHyp 0 l a) ∷ hyps l b
hyps l (pi s a b) = hyps l b
hyps l b = []
rhs = vis appVar (k + j ∸ suc i) (hyps j c)
-- i = 1: f
-- j = 3: x t r
-- k = 2: g f
-- 5 4 3 2 1 0 3 2 4 3 1 1 0 6 5 2 1 0
-- fold P g f (cons x t r) = f x (fold g f t) (λ y u -> fold g f (r y u))
defineFold : Name -> Data Type -> TC _
defineFold f D =
declareDef (explRelArg f) (foldTypeOf D) >>
defineFun f (foldClausesOf f D)
deriveFold : Name -> Data Type -> TC Name
deriveFold d D =
freshName ("fold" ++ˢ showName d) >>= λ f ->
f <$ defineFold f D
deriveFoldTo : Name -> Name -> TC _
deriveFoldTo f = getData >=> defineFold f
|
1,010,000 (2000). 600,000 monolinguals. Total users in all countries: 1,016,650.
Vigorous. All domains. All ages. Positive attitudes. Some also use Lingala [lin]. A few also use French [fra]. Used as L2 by Gilima [gix], Mbandja [zmz], Mono [mnh], Ngbundu [nuu]. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.