text
stringlengths 0
3.34M
|
---|
lemma smult_conv_map_poly: "smult c p = map_poly (\<lambda>x. c * x) p" |
/* test_fisher_f.cpp
*
* Copyright Steven Watanabe 2011
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* $Id: test_fisher_f.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $
*
*/
#include <boost/random/fisher_f_distribution.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/math/distributions/fisher_f.hpp>
#define BOOST_RANDOM_DISTRIBUTION boost::random::fisher_f_distribution<>
#define BOOST_RANDOM_DISTRIBUTION_NAME fisher_f
#define BOOST_MATH_DISTRIBUTION boost::math::fisher_f
#define BOOST_RANDOM_ARG1_TYPE double
#define BOOST_RANDOM_ARG1_NAME m
#define BOOST_RANDOM_ARG1_DEFAULT 1000.0
#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)
#define BOOST_RANDOM_ARG2_TYPE double
#define BOOST_RANDOM_ARG2_NAME n
#define BOOST_RANDOM_ARG2_DEFAULT 1000.0
#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)
#include "test_real_distribution.ipp"
|
Formal statement is: lemma starlike_convex_subset: assumes S: "a \<in> S" "closed_segment b c \<subseteq> S" and subs: "\<And>x. x \<in> S \<Longrightarrow> closed_segment a x \<subseteq> S" shows "convex hull {a,b,c} \<subseteq> S" Informal statement is: If $a \in S$, $b,c \in S$, and $S$ is starlike with respect to $a$, then the convex hull of $a,b,c$ is contained in $S$. |
/* rng/knuthran2002.c
*
* Copyright (C) 2007 Brian Gough
* Copyright (C) 2001 Brian Gough, Carlo Perassi
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* This generator is taken from
*
* Donald E. Knuth, The Art of Computer Programming, Volume 2, Section 3.6
* Third Edition, Addison-Wesley,
*
* The modifications introduced in the 9th printing (2002) are
* included here; there's no backwards compatibility with the
* original. [ see http://www-cs-faculty.stanford.edu/~knuth/taocp.html ]
*
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#define BUFLEN 1009 /* length of the buffer aa[] */
#define KK 100 /* the long lag */
#define LL 37 /* the short lag */
#define MM (1L << 30) /* the modulus */
#define TT 70 /* guaranteed separation between streams */
#define is_odd(x) ((x) & 1) /* the units bit of x */
#define mod_diff(x, y) (((x) - (y)) & (MM - 1)) /* (x - y) mod MM */
static inline void ran_array (long int aa[], unsigned int n,
long int ran_x[]);
static inline unsigned long int ran_get (void *vstate);
static double ran_get_double (void *vstate);
static void ran_set (void *state, unsigned long int s);
typedef struct
{
unsigned int i;
long int aa[BUFLEN];
long int ran_x[KK]; /* the generator state */
}
ran_state_t;
static inline void
ran_array (long int aa[], unsigned int n, long int ran_x[])
{
unsigned int i;
unsigned int j;
for (j = 0; j < KK; j++)
aa[j] = ran_x[j];
for (; j < n; j++)
aa[j] = mod_diff (aa[j - KK], aa[j - LL]);
for (i = 0; i < LL; i++, j++)
ran_x[i] = mod_diff (aa[j - KK], aa[j - LL]);
for (; i < KK; i++, j++)
ran_x[i] = mod_diff (aa[j - KK], ran_x[i - LL]);
}
static inline unsigned long int
ran_get (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
unsigned int i = state->i;
unsigned long int v;
if (i == 0)
{
/* fill buffer with new random numbers */
ran_array (state->aa, BUFLEN, state->ran_x);
}
v = state->aa[i];
state->i = (i + 1) % KK;
return v;
}
static double
ran_get_double (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
return ran_get (state) / 1073741824.0; /* RAND_MAX + 1 */
}
static void
ran_set (void *vstate, unsigned long int s)
{
ran_state_t *state = (ran_state_t *) vstate;
long x[KK + KK - 1]; /* the preparation buffer */
register int j;
register int t;
register long ss;
if (s == 0 )
s = 314159; /* default seed used by Knuth */
ss = (s + 2)&(MM-2);
for (j = 0; j < KK; j++)
{
x[j] = ss; /* bootstrap the buffer */
ss <<= 1;
if (ss >= MM) /* cyclic shift 29 bits */
ss -= MM - 2;
}
x[1]++; /* make x[1] (and only x[1]) odd */
ss = s & (MM - 1);
t = TT - 1;
while (t)
{
for (j = KK - 1; j > 0; j--) /* square */
{
x[j + j] = x[j];
x[j + j - 1] = 0;
}
for (j = KK + KK - 2; j >= KK; j--)
{
x[j - (KK - LL)] = mod_diff (x[j - (KK - LL)], x[j]);
x[j - KK] = mod_diff (x[j - KK], x[j]);
}
if (is_odd (ss))
{ /* multiply by "z" */
for (j = KK; j > 0; j--)
{
x[j] = x[j - 1];
}
x[0] = x[KK]; /* shift the buffer cyclically */
x[LL] = mod_diff (x[LL], x[KK]);
}
if (ss)
ss >>= 1;
else
t--;
}
for (j = 0; j < LL; j++)
state->ran_x[j + KK - LL] = x[j];
for (; j < KK; j++)
state->ran_x[j - LL] = x[j];
for (j = 0; j< 10; j++)
ran_array(x, KK+KK-1, state->ran_x); /* warm things up */
state->i = 0;
return;
}
static const gsl_rng_type ran_type = {
"knuthran2002", /* name */
0x3fffffffUL, /* RAND_MAX = (2 ^ 30) - 1 */
0, /* RAND_MIN */
sizeof (ran_state_t),
&ran_set,
&ran_get,
&ran_get_double
};
const gsl_rng_type *gsl_rng_knuthran2002 = &ran_type;
|
If $f$ is a function with $n$ continuous derivatives on a convex set $S$, and if $f^{(n+1)}$ is bounded on $S$, then $f$ is approximated by its Taylor polynomial of degree $n$ on $S$. |
\documentclass[11pt, twoside]{article}
\usepackage{holtex}
\makeindex
\begin{document}
\input{HOLcipher}
\tableofcontents
\cleardoublepage
\HOLpagestyle
% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
\section{cipher Theory}
\index{cipher Theory@\textbf {cipher Theory}}
\begin{flushleft}
\textbf{Built:} \HOLcipherDate \\[2pt]
\textbf{Parent Theories:} indexedLists, patternMatches
\end{flushleft}
% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
\subsection{Datatypes}
\index{cipher Theory@\textbf {cipher Theory}!Datatypes}
% .....................................
\HOLcipherDatatypes
\subsection{Definitions}
\index{cipher Theory@\textbf {cipher Theory}!Definitions}
% .....................................
\HOLcipherDefinitions
\subsection{Theorems}
\index{cipher Theory@\textbf {cipher Theory}!Theorems}
% .....................................
\HOLcipherTheorems
\HOLindex
\end{document} |
/-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Neil Strickland
! This file was ported from Lean 3 source module data.pnat.defs
! leanprover-community/mathlib commit 448144f7ae193a8990cb7473c9e9a01990f64ac7
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Order.Basic
import Mathbin.Algebra.NeZero
/-!
# The positive natural numbers
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains the definitions, and basic results.
Most algebraic facts are deferred to `data.pnat.basic`, as they need more imports.
-/
#print PNat /-
/-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype,
and the VM representation of `ℕ+` is the same as `ℕ` because the proof
is not stored. -/
def PNat :=
{ n : ℕ // 0 < n }deriving DecidableEq, LinearOrder
#align pnat PNat
-/
-- mathport name: «exprℕ+»
notation "ℕ+" => PNat
instance : One ℕ+ :=
⟨⟨1, Nat.zero_lt_one⟩⟩
#print coePNatNat /-
instance coePNatNat : Coe ℕ+ ℕ :=
⟨Subtype.val⟩
#align coe_pnat_nat coePNatNat
-/
instance : Repr ℕ+ :=
⟨fun n => repr n.1⟩
namespace PNat
#print PNat.mk_coe /-
@[simp]
theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n :=
rfl
#align pnat.mk_coe PNat.mk_coe
-/
#print PNat.natPred /-
/-- Predecessor of a `ℕ+`, as a `ℕ`. -/
def natPred (i : ℕ+) : ℕ :=
i - 1
#align pnat.nat_pred PNat.natPred
-/
#print PNat.natPred_eq_pred /-
@[simp]
theorem natPred_eq_pred {n : ℕ} (h : 0 < n) : natPred (⟨n, h⟩ : ℕ+) = n.pred :=
rfl
#align pnat.nat_pred_eq_pred PNat.natPred_eq_pred
-/
end PNat
namespace Nat
#print Nat.toPNat /-
/-- Convert a natural number to a positive natural number. The
positivity assumption is inferred by `dec_trivial`. -/
def toPNat (n : ℕ) (h : 0 < n := by decide) : ℕ+ :=
⟨n, h⟩
#align nat.to_pnat Nat.toPNat
-/
#print Nat.succPNat /-
/-- Write a successor as an element of `ℕ+`. -/
def succPNat (n : ℕ) : ℕ+ :=
⟨succ n, succ_pos n⟩
#align nat.succ_pnat Nat.succPNat
-/
#print Nat.succPNat_coe /-
@[simp]
theorem succPNat_coe (n : ℕ) : (succPNat n : ℕ) = succ n :=
rfl
#align nat.succ_pnat_coe Nat.succPNat_coe
-/
#print Nat.natPred_succPNat /-
@[simp]
theorem natPred_succPNat (n : ℕ) : n.succPNat.natPred = n :=
rfl
#align nat.nat_pred_succ_pnat Nat.natPred_succPNat
-/
#print PNat.succPNat_natPred /-
@[simp]
theorem PNat.succPNat_natPred (n : ℕ+) : n.natPred.succPNat = n :=
Subtype.eq <| succ_pred_eq_of_pos n.2
#align pnat.succ_pnat_nat_pred PNat.succPNat_natPred
-/
#print Nat.toPNat' /-
/-- Convert a natural number to a pnat. `n+1` is mapped to itself,
and `0` becomes `1`. -/
def toPNat' (n : ℕ) : ℕ+ :=
succPNat (pred n)
#align nat.to_pnat' Nat.toPNat'
-/
/- warning: nat.to_pnat'_coe -> Nat.toPNat'_coe is a dubious translation:
lean 3 declaration is
forall (n : Nat), Eq.{1} Nat ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) (Nat.toPNat' n)) (ite.{1} Nat (LT.lt.{0} Nat Nat.hasLt (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero))) n) (Nat.decidableLt (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero))) n) n (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))))
but is expected to have type
forall (n : Nat), Eq.{1} Nat (PNat.val (Nat.toPNat' n)) (ite.{1} Nat (LT.lt.{0} Nat instLTNat (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0)) n) (Nat.decLt (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0)) n) n (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)))
Case conversion may be inaccurate. Consider using '#align nat.to_pnat'_coe Nat.toPNat'_coeₓ'. -/
@[simp]
theorem toPNat'_coe : ∀ n : ℕ, (toPNat' n : ℕ) = ite (0 < n) n 1
| 0 => rfl
| m + 1 => by
rw [if_pos (succ_pos m)]
rfl
#align nat.to_pnat'_coe Nat.toPNat'_coe
end Nat
namespace PNat
open Nat
#print PNat.mk_le_mk /-
/-- We now define a long list of structures on ℕ+ induced by
similar structures on ℕ. Most of these behave in a completely
obvious way, but there are a few things to be said about
subtraction, division and powers.
-/
@[simp]
theorem mk_le_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) ≤ ⟨k, hk⟩ ↔ n ≤ k :=
Iff.rfl
#align pnat.mk_le_mk PNat.mk_le_mk
-/
#print PNat.mk_lt_mk /-
@[simp]
theorem mk_lt_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) < ⟨k, hk⟩ ↔ n < k :=
Iff.rfl
#align pnat.mk_lt_mk PNat.mk_lt_mk
-/
#print PNat.coe_le_coe /-
@[simp, norm_cast]
theorem coe_le_coe (n k : ℕ+) : (n : ℕ) ≤ k ↔ n ≤ k :=
Iff.rfl
#align pnat.coe_le_coe PNat.coe_le_coe
-/
#print PNat.coe_lt_coe /-
@[simp, norm_cast]
theorem coe_lt_coe (n k : ℕ+) : (n : ℕ) < k ↔ n < k :=
Iff.rfl
#align pnat.coe_lt_coe PNat.coe_lt_coe
-/
#print PNat.pos /-
@[simp]
theorem pos (n : ℕ+) : 0 < (n : ℕ) :=
n.2
#align pnat.pos PNat.pos
-/
#print PNat.eq /-
theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n :=
Subtype.eq
#align pnat.eq PNat.eq
-/
#print PNat.coe_injective /-
theorem coe_injective : Function.Injective (coe : ℕ+ → ℕ) :=
Subtype.coe_injective
#align pnat.coe_injective PNat.coe_injective
-/
#print PNat.ne_zero /-
@[simp]
theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 :=
n.2.ne'
#align pnat.ne_zero PNat.ne_zero
-/
#print NeZero.pnat /-
instance NeZero.pnat {a : ℕ+} : NeZero (a : ℕ) :=
⟨a.NeZero⟩
#align ne_zero.pnat NeZero.pnat
-/
#print PNat.toPNat'_coe /-
theorem toPNat'_coe {n : ℕ} : 0 < n → (n.toPNat' : ℕ) = n :=
succ_pred_eq_of_pos
#align pnat.to_pnat'_coe PNat.toPNat'_coe
-/
#print PNat.coe_toPNat' /-
@[simp]
theorem coe_toPNat' (n : ℕ+) : (n : ℕ).toPNat' = n :=
eq (toPNat'_coe n.Pos)
#align pnat.coe_to_pnat' PNat.coe_toPNat'
-/
#print PNat.one_le /-
@[simp]
theorem one_le (n : ℕ+) : (1 : ℕ+) ≤ n :=
n.2
#align pnat.one_le PNat.one_le
-/
#print PNat.not_lt_one /-
@[simp]
theorem not_lt_one (n : ℕ+) : ¬n < 1 :=
not_lt_of_le n.one_le
#align pnat.not_lt_one PNat.not_lt_one
-/
instance : Inhabited ℕ+ :=
⟨1⟩
#print PNat.mk_one /-
-- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals.
@[simp]
theorem mk_one {h} : (⟨1, h⟩ : ℕ+) = (1 : ℕ+) :=
rfl
#align pnat.mk_one PNat.mk_one
-/
#print PNat.one_coe /-
@[norm_cast]
theorem one_coe : ((1 : ℕ+) : ℕ) = 1 :=
rfl
#align pnat.one_coe PNat.one_coe
-/
#print PNat.coe_eq_one_iff /-
@[simp, norm_cast]
theorem coe_eq_one_iff {m : ℕ+} : (m : ℕ) = 1 ↔ m = 1 :=
Subtype.coe_injective.eq_iff' one_coe
#align pnat.coe_eq_one_iff PNat.coe_eq_one_iff
-/
instance : WellFoundedRelation ℕ+ :=
⟨(· < ·), measure_wf coe⟩
#print PNat.strongInductionOn /-
/-- Strong induction on `ℕ+`. -/
def strongInductionOn {p : ℕ+ → Sort _} : ∀ (n : ℕ+) (h : ∀ k, (∀ m, m < k → p m) → p k), p n
| n => fun IH => IH _ fun a h => strong_induction_on a IH
#align pnat.strong_induction_on PNat.strongInductionOn
-/
#print PNat.modDivAux /-
/-- We define `m % k` and `m / k` in the same way as for `ℕ`
except that when `m = n * k` we take `m % k = k` and
`m / k = n - 1`. This ensures that `m % k` is always positive
and `m = (m % k) + k * (m / k)` in all cases. Later we
define a function `div_exact` which gives the usual `m / k`
in the case where `k` divides `m`.
-/
def modDivAux : ℕ+ → ℕ → ℕ → ℕ+ × ℕ
| k, 0, q => ⟨k, q.pred⟩
| k, r + 1, q => ⟨⟨r + 1, Nat.succ_pos r⟩, q⟩
#align pnat.mod_div_aux PNat.modDivAux
-/
#print PNat.modDiv /-
/-- `mod_div m k = (m % k, m / k)`.
We define `m % k` and `m / k` in the same way as for `ℕ`
except that when `m = n * k` we take `m % k = k` and
`m / k = n - 1`. This ensures that `m % k` is always positive
and `m = (m % k) + k * (m / k)` in all cases. Later we
define a function `div_exact` which gives the usual `m / k`
in the case where `k` divides `m`.
-/
def modDiv (m k : ℕ+) : ℕ+ × ℕ :=
modDivAux k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ))
#align pnat.mod_div PNat.modDiv
-/
#print PNat.mod /-
/-- We define `m % k` in the same way as for `ℕ`
except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive.
-/
def mod (m k : ℕ+) : ℕ+ :=
(modDiv m k).1
#align pnat.mod PNat.mod
-/
#print PNat.div /-
/-- We define `m / k` in the same way as for `ℕ` except that when `m = n * k` we take
`m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we
define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`.
-/
def div (m k : ℕ+) : ℕ :=
(modDiv m k).2
#align pnat.div PNat.div
-/
/- warning: pnat.mod_coe -> PNat.mod_coe is a dubious translation:
lean 3 declaration is
forall (m : PNat) (k : PNat), Eq.{1} Nat ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) (PNat.mod m k)) (ite.{1} Nat (Eq.{1} Nat (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) m) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) k)) (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero)))) (Nat.decidableEq (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) m) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) k)) (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero)))) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) k) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) m) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) k)))
but is expected to have type
forall (m : PNat) (k : PNat), Eq.{1} Nat (PNat.val (PNat.mod m k)) (ite.{1} Nat (Eq.{1} Nat (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) (PNat.val m) (PNat.val k)) (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))) (instDecidableEqNat (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) (PNat.val m) (PNat.val k)) (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))) (PNat.val k) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) (PNat.val m) (PNat.val k)))
Case conversion may be inaccurate. Consider using '#align pnat.mod_coe PNat.mod_coeₓ'. -/
theorem mod_coe (m k : ℕ+) :
(mod m k : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) (k : ℕ) ((m : ℕ) % (k : ℕ)) :=
by
dsimp [mod, mod_div]
cases (m : ℕ) % (k : ℕ)
· rw [if_pos rfl]
rfl
· rw [if_neg n.succ_ne_zero]
rfl
#align pnat.mod_coe PNat.mod_coe
/- warning: pnat.div_coe -> PNat.div_coe is a dubious translation:
lean 3 declaration is
forall (m : PNat) (k : PNat), Eq.{1} Nat (PNat.div m k) (ite.{1} Nat (Eq.{1} Nat (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) m) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) k)) (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero)))) (Nat.decidableEq (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) m) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) k)) (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero)))) (Nat.pred (HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) m) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) k))) (HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) m) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) PNat Nat (HasLiftT.mk.{1, 1} PNat Nat (CoeTCₓ.coe.{1, 1} PNat Nat (coeBase.{1, 1} PNat Nat coePNatNat))) k)))
but is expected to have type
forall (m : PNat) (k : PNat), Eq.{1} Nat (PNat.div m k) (ite.{1} Nat (Eq.{1} Nat (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) (PNat.val m) (PNat.val k)) (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))) (instDecidableEqNat (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) (PNat.val m) (PNat.val k)) (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))) (Nat.pred (HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) (PNat.val m) (PNat.val k))) (HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) (PNat.val m) (PNat.val k)))
Case conversion may be inaccurate. Consider using '#align pnat.div_coe PNat.div_coeₓ'. -/
theorem div_coe (m k : ℕ+) :
(div m k : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) ((m : ℕ) / (k : ℕ)).pred ((m : ℕ) / (k : ℕ)) :=
by
dsimp [div, mod_div]
cases (m : ℕ) % (k : ℕ)
· rw [if_pos rfl]
rfl
· rw [if_neg n.succ_ne_zero]
rfl
#align pnat.div_coe PNat.div_coe
#print PNat.divExact /-
/-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/
def divExact (m k : ℕ+) : ℕ+ :=
⟨(div m k).succ, Nat.succ_pos _⟩
#align pnat.div_exact PNat.divExact
-/
end PNat
section CanLift
#print Nat.canLiftPNat /-
instance Nat.canLiftPNat : CanLift ℕ ℕ+ coe ((· < ·) 0) :=
⟨fun n hn => ⟨Nat.toPNat' n, PNat.toPNat'_coe hn⟩⟩
#align nat.can_lift_pnat Nat.canLiftPNat
-/
#print Int.canLiftPNat /-
instance Int.canLiftPNat : CanLift ℤ ℕ+ coe ((· < ·) 0) :=
⟨fun n hn =>
⟨Nat.toPNat' (Int.natAbs n), by
rw [coe_coe, Nat.toPNat'_coe, if_pos (Int.natAbs_pos_of_ne_zero hn.ne'),
Int.natAbs_of_nonneg hn.le]⟩⟩
#align int.can_lift_pnat Int.canLiftPNat
-/
end CanLift
|
{-
In this file we apply the cubical machinery to Martin Hötzel-Escardó's
structure identity principle:
https://www.cs.bham.ac.uk/~mhe/HoTT-UF-in-Agda-Lecture-Notes/HoTT-UF-Agda.html#sns
-}
{-# OPTIONS --cubical --safe #-}
module Cubical.Foundations.SIP where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Univalence renaming (ua-pathToEquiv to ua-pathToEquiv')
open import Cubical.Foundations.Transport
open import Cubical.Foundations.Path
open import Cubical.Foundations.Isomorphism
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.Equiv.Properties renaming (cong≃ to _⋆_)
open import Cubical.Foundations.HAEquiv
open import Cubical.Data.Prod.Base hiding (_×_) renaming (_×Σ_ to _×_)
open import Cubical.Foundations.Structure public
private
variable
ℓ₁ ℓ₂ ℓ₃ ℓ₄ ℓ₅ : Level
S : Type ℓ₁ → Type ℓ₂
-- For technical reasons we reprove ua-pathToEquiv using the
-- particular proof constructed by iso→HAEquiv. The reason is that we
-- want to later be able to extract
--
-- eq : ua-au (ua e) ≡ cong ua (au-ua e)
--
uaHAEquiv : (A B : Type ℓ₁) → HAEquiv (A ≃ B) (A ≡ B)
uaHAEquiv A B = iso→HAEquiv (iso ua pathToEquiv ua-pathToEquiv' pathToEquiv-ua)
open isHAEquiv
-- We now extract the particular proof constructed from iso→HAEquiv
-- for reasons explained above.
ua-pathToEquiv : {A B : Type ℓ₁} (e : A ≡ B) → ua (pathToEquiv e) ≡ e
ua-pathToEquiv e = uaHAEquiv _ _ .snd .ret e
-- Note that for any equivalence (f , e) : X ≃ Y the type ι (X , s) (Y , t) (f , e) need not to be
-- a proposition. Indeed this type should correspond to the ways s and t can be identified
-- as S-structures. This we call a standard notion of structure or SNS.
-- We will use a different definition, but the two definitions are interchangeable.
SNS-≡ : (S : Type ℓ₁ → Type ℓ₂) (ι : StrIso S ℓ₃) → Type (ℓ-max (ℓ-max (ℓ-suc ℓ₁) ℓ₂) ℓ₃)
SNS-≡ {ℓ₁} S ι = ∀ {X : Type ℓ₁} (s t : S X) → ι (X , s) (X , t) (idEquiv X) ≃ (s ≡ t)
-- We introduce the notation for structure preserving equivalences a
-- bit differently, but this definition doesn't actually change from
-- Escardó's notes.
_≃[_]_ : (A : TypeWithStr ℓ₁ S) (ι : StrIso S ℓ₂) (B : TypeWithStr ℓ₁ S) → Type (ℓ-max ℓ₁ ℓ₂)
A ≃[ ι ] B = Σ[ e ∈ typ A ≃ typ B ] (ι A B e)
-- The following PathP version of SNS-≡ is a bit easier to work with
-- for the proof of the SIP
SNS-PathP : (S : Type ℓ₁ → Type ℓ₂) (ι : StrIso S ℓ₃) → Type (ℓ-max (ℓ-max (ℓ-suc ℓ₁) ℓ₂) ℓ₃)
SNS-PathP {ℓ₁} S ι = {A B : TypeWithStr ℓ₁ S} (e : typ A ≃ typ B)
→ ι A B e ≃ PathP (λ i → S (ua e i)) (str A) (str B)
-- A quick sanity-check that our definition is interchangeable with
-- Escardó's. The direction SNS-≡→SNS-PathP corresponds more or less
-- to a dependent EquivJ formulation of Escardó's homomorphism-lemma.
SNS-PathP→SNS-≡ : (S : Type ℓ₁ → Type ℓ₂) (ι : StrIso S ℓ₃) → SNS-PathP S ι → SNS-≡ S ι
SNS-PathP→SNS-≡ S ι θ {X = X} s t = ι (X , s) (X , t) (idEquiv X) ≃⟨ θ (idEquiv X) ⟩
PathP (λ i → S (ua (idEquiv X) i)) s t ≃⟨ φ ⟩
s ≡ t ■
where
φ = transportEquiv (λ j → PathP (λ i → S (uaIdEquiv {A = X} j i)) s t)
SNS-≡→SNS-PathP : (ι : StrIso S ℓ₃) → SNS-≡ S ι → SNS-PathP S ι
SNS-≡→SNS-PathP {S = S} ι θ {A = A} {B = B} e = EquivJ P C e (str A) (str B)
where
Y = typ B
P : (X : Type _) → X ≃ Y → Type _
P X e' = (s : S X) (t : S Y) → ι (X , s) (Y , t) e' ≃ PathP (λ i → S (ua e' i)) s t
C : (s t : S Y) → ι (Y , s) (Y , t) (idEquiv Y) ≃ PathP (λ i → S (ua (idEquiv Y) i)) s t
C s t = ι (Y , s) (Y , t) (idEquiv Y) ≃⟨ θ s t ⟩
s ≡ t ≃⟨ ψ ⟩
PathP (λ i → S (ua (idEquiv Y) i)) s t ■
where
ψ = transportEquiv λ j → PathP (λ i → S (uaIdEquiv {A = Y} (~ j) i)) s t
-- We can now directly define an invertible function
--
-- sip : A ≃[ ι ] B → A ≡ B
--
sip : (S : Type ℓ₁ → Type ℓ₂) (ι : StrIso S ℓ₃) (θ : SNS-PathP S ι)
(A B : TypeWithStr ℓ₁ S) → A ≃[ ι ] B → A ≡ B
sip S ι θ A B (e , p) i = ua e i , θ e .fst p i
-- The inverse to sip uses the following little lemma
private
lem : (S : Type ℓ₁ → Type ℓ₂) (A B : TypeWithStr ℓ₁ S) (e : typ A ≡ typ B)
→ PathP (λ i → S (ua (pathToEquiv e) i)) (A .snd) (B .snd) ≡
PathP (λ i → S (e i)) (A .snd) (B .snd)
lem S A B e i = PathP (λ j → S (ua-pathToEquiv e i j)) (A .snd) (B .snd)
-- The inverse
sip⁻ : (S : Type ℓ₁ → Type ℓ₂) (ι : StrIso S ℓ₃) (θ : SNS-PathP S ι)
(A B : TypeWithStr ℓ₁ S) → A ≡ B → A ≃[ ι ] B
sip⁻ S ι θ A B r = pathToEquiv p , invEq (θ (pathToEquiv p)) q
where
p : typ A ≡ typ B
p = cong fst r
q : PathP (λ i → S (ua (pathToEquiv p) i)) (A .snd) (B .snd)
q = transport⁻ (lem S A B p) (cong snd r)
-- We can rather directly show that sip and sip⁻ are mutually inverse:
sip-sip⁻ : (S : Type ℓ₁ → Type ℓ₂) (ι : StrIso S ℓ₃) (θ : SNS-PathP S ι)
(A B : TypeWithStr ℓ₁ S) (r : A ≡ B)
→ sip S ι θ A B (sip⁻ S ι θ A B r) ≡ r
sip-sip⁻ S ι θ A B r =
let p : typ A ≡ typ B
p = cong fst r
q : PathP (λ i → S (p i)) (str A) (str B)
q = cong snd r
in sip S ι θ A B (sip⁻ S ι θ A B r)
≡⟨ refl ⟩
(λ i → ( ua (pathToEquiv p) i)
, θ (pathToEquiv p) .fst
(invEq (θ (pathToEquiv p))
(transport⁻ (lem S A B p) q)) i)
≡⟨ (λ i j → ( ua (pathToEquiv p) j
, retEq (θ (pathToEquiv p))
(transport⁻ (lem S A B p) q) i j)) ⟩
(λ i → ( ua (pathToEquiv p) i
, transport⁻ (lem S A B p) q i))
≡⟨ (λ i j → ( ua-pathToEquiv p i j
, transp (λ k → PathP (λ j → S (ua-pathToEquiv p (i ∧ k) j)) (str A) (str B))
(~ i) (transport⁻ (lem S A B p) q) j)) ⟩
(λ i → ( p i
, transport (λ i → lem S A B p i) (transport⁻ (lem S A B p) q) i))
≡⟨ (λ i j → ( p j
, transportTransport⁻ (lem S A B p) q i j)) ⟩
r ∎
-- The trickier direction:
sip⁻-sip : (S : Type ℓ₁ → Type ℓ₂) (ι : StrIso S ℓ₃) (θ : SNS-PathP S ι)
(A B : TypeWithStr ℓ₁ S) (r : A ≃[ ι ] B)
→ sip⁻ S ι θ A B (sip S ι θ A B r) ≡ r
sip⁻-sip S ι θ A B (e , p) =
sip⁻ S ι θ A B (sip S ι θ A B (e , p))
≡⟨ refl ⟩
pathToEquiv (ua e) , invEq (θ (pathToEquiv (ua e))) (f⁺ p')
≡⟨ (λ i → pathToEquiv-ua e i , invEq (θ (pathToEquiv-ua e i)) (pth' i)) ⟩
e , invEq (θ e) (f⁻ (f⁺ p'))
≡⟨ (λ i → e , invEq (θ e) (transportTransport⁻ (lem S A B (ua e)) p' i)) ⟩
e , invEq (θ e) (θ e .fst p)
≡⟨ (λ i → e , (secEq (θ e) p i)) ⟩
e , p ∎
where
p' : PathP (λ i → S (ua e i)) (str A) (str B)
p' = θ e .fst p
f⁺ : PathP (λ i → S (ua e i)) (str A) (str B)
→ PathP (λ i → S (ua (pathToEquiv (ua e)) i)) (str A) (str B)
f⁺ = transport (λ i → PathP (λ j → S (ua-pathToEquiv (ua e) (~ i) j)) (str A) (str B))
f⁻ : PathP (λ i → S (ua (pathToEquiv (ua e)) i)) (str A) (str B)
→ PathP (λ i → S (ua e i)) (str A) (str B)
f⁻ = transport (λ i → PathP (λ j → S (ua-pathToEquiv (ua e) i j)) (str A) (str B))
-- We can prove the following as in sip∘pis-id, but the type is not
-- what we want as it should be "cong ua (pathToEquiv-ua e)"
pth : PathP (λ j → PathP (λ k → S (ua-pathToEquiv (ua e) j k)) (str A) (str B))
(f⁺ p') (f⁻ (f⁺ p'))
pth i = transp (λ k → PathP (λ j → S (ua-pathToEquiv (ua e) (i ∧ k) j)) (str A) (str B))
(~ i) (f⁺ p')
-- So we build an equality that we want to cast the types with
casteq : PathP (λ j → PathP (λ k → S (ua-pathToEquiv (ua e) j k)) (str A) (str B))
(f⁺ p') (f⁻ (f⁺ p'))
≡ PathP (λ j → PathP (λ k → S (cong ua (pathToEquiv-ua e) j k)) (str A) (str B))
(f⁺ p') (f⁻ (f⁺ p'))
casteq i = PathP (λ j → PathP (λ k → S (eq i j k)) (str A) (str B)) (f⁺ p') (f⁻ (f⁺ p'))
where
-- This is where we need the half-adjoint equivalence property
eq : ua-pathToEquiv (ua e) ≡ cong ua (pathToEquiv-ua e)
eq = sym (uaHAEquiv (typ A) (typ B) .snd .com e)
-- We then get a term of the type we need
pth' : PathP (λ j → PathP (λ k → S (cong ua (pathToEquiv-ua e) j k)) (str A) (str B))
(f⁺ p') (f⁻ (f⁺ p'))
pth' = transport (λ i → casteq i) pth
-- Finally package everything up to get the cubical SIP
SIP : (S : Type ℓ₁ → Type ℓ₂) (ι : StrIso S ℓ₃)
(θ : SNS-PathP S ι) (A B : TypeWithStr ℓ₁ S)
→ A ≃[ ι ] B ≃ (A ≡ B)
SIP S ι θ A B = isoToEquiv (iso (sip S ι θ A B) (sip⁻ S ι θ A B)
(sip-sip⁻ S ι θ A B) (sip⁻-sip S ι θ A B))
-- Now, we want to add axioms (i.e. propositions) to our Structure S that don't affect the ι.
-- We use a lemma due to Zesen Qian, which can now be found in Foundations.Prelude:
-- https://github.com/riaqn/cubical/blob/hgroup/Cubical/Data/Group/Properties.agda#L83
add-to-structure : (S : Type ℓ₁ → Type ℓ₂)
(axioms : (X : Type ℓ₁) → S X → Type ℓ₄)
→ Type ℓ₁ → Type (ℓ-max ℓ₂ ℓ₄)
add-to-structure S axioms X = Σ[ s ∈ S X ] (axioms X s)
add-to-iso : (S : Type ℓ₁ → Type ℓ₂) (ι : StrIso S ℓ₃)
(axioms : (X : Type ℓ₁) → S X → Type ℓ₄)
→ StrIso (add-to-structure S axioms) ℓ₃
add-to-iso S ι axioms (X , (s , a)) (Y , (t , b)) f = ι (X , s) (Y , t) f
add-ax-lemma : (S : Type ℓ₁ → Type ℓ₂)
(axioms : (X : Type ℓ₁) → S X → Type ℓ₄)
(axioms-are-Props : (X : Type ℓ₁) (s : S X) → isProp (axioms X s))
{X Y : Type ℓ₁} {s : S X} {t : S Y} {a : axioms X s} {b : axioms Y t}
(f : X ≃ Y)
→ PathP (λ i → S (ua f i)) s t ≃
PathP (λ i → add-to-structure S axioms (ua f i)) (s , a) (t , b)
add-ax-lemma S axioms axioms-are-Props {s = s} {t = t} {a = a} {b = b} f = isoToEquiv (iso φ ψ η ε)
where
φ : PathP (λ i → S (ua f i)) s t → PathP (λ i → add-to-structure S axioms (ua f i)) (s , a) (t , b)
φ p i = p i , isProp→PathP (λ i → axioms-are-Props (ua f i) (p i)) a b i
ψ : PathP (λ i → add-to-structure S axioms (ua f i)) (s , a) (t , b) → PathP (λ i → S (ua f i)) s t
ψ r i = r i .fst
η : section φ ψ
η r i j = r j .fst , isProp→isSet-PathP (λ k → axioms-are-Props (ua f k) (r k .fst)) _ _
(isProp→PathP (λ k → axioms-are-Props (ua f k) (r k .fst)) a b)
(λ k → r k .snd) i j
ε : retract φ ψ
ε p = refl
add-axioms-SNS : (S : Type ℓ₁ → Type ℓ₂)
(ι : (A B : Σ[ X ∈ (Type ℓ₁) ] (S X)) → A .fst ≃ B .fst → Type ℓ₃)
(axioms : (X : Type ℓ₁) → S X → Type ℓ₄)
(axioms-are-Props : (X : Type ℓ₁) (s : S X) → isProp (axioms X s))
(θ : SNS-PathP S ι)
→ SNS-PathP (add-to-structure S axioms) (add-to-iso S ι axioms)
add-axioms-SNS S ι axioms axioms-are-Props θ {X , s , a} {Y , t , b} f =
add-to-iso S ι axioms (X , s , a) (Y , t , b) f ≃⟨ θ f ⟩
PathP (λ i → S (ua f i)) s t ≃⟨ add-ax-lemma S axioms axioms-are-Props f ⟩
PathP (λ i → (add-to-structure S axioms) (ua f i)) (s , a) (t , b) ■
-- Now, we want to join two structures. Together with the adding of
-- axioms this will allow us to prove that a lot of mathematical
-- structures are a standard notion of structure
join-structure : (S₁ : Type ℓ₁ → Type ℓ₂) (S₂ : Type ℓ₁ → Type ℓ₄)
→ Type ℓ₁ → Type (ℓ-max ℓ₂ ℓ₄)
join-structure S₁ S₂ X = S₁ X × S₂ X
join-iso : {S₁ : Type ℓ₁ → Type ℓ₂} (ι₁ : StrIso S₁ ℓ₃)
{S₂ : Type ℓ₁ → Type ℓ₄} (ι₂ : StrIso S₂ ℓ₅)
→ StrIso (join-structure S₁ S₂) (ℓ-max ℓ₃ ℓ₅)
join-iso ι₁ ι₂ (X , s₁ , s₂) (Y , t₁ , t₂) f = (ι₁ (X , s₁) (Y , t₁) f) × (ι₂ (X , s₂) (Y , t₂) f)
join-SNS : (S₁ : Type ℓ₁ → Type ℓ₂) (ι₁ : StrIso S₁ ℓ₃) (θ₁ : SNS-PathP S₁ ι₁)
(S₂ : Type ℓ₁ → Type ℓ₄) (ι₂ : StrIso S₂ ℓ₅) (θ₂ : SNS-PathP S₂ ι₂)
→ SNS-PathP (join-structure S₁ S₂) (join-iso ι₁ ι₂)
join-SNS S₁ ι₁ θ₁ S₂ ι₂ θ₂ {X , s₁ , s₂} {Y , t₁ , t₂} e = isoToEquiv (iso φ ψ η ε)
where
φ : join-iso ι₁ ι₂ (X , s₁ , s₂) (Y , t₁ , t₂) e
→ PathP (λ i → join-structure S₁ S₂ (ua e i)) (s₁ , s₂) (t₁ , t₂)
φ (p , q) i = (θ₁ e .fst p i) , (θ₂ e .fst q i)
ψ : PathP (λ i → join-structure S₁ S₂ (ua e i)) (s₁ , s₂) (t₁ , t₂)
→ join-iso ι₁ ι₂ (X , s₁ , s₂) (Y , t₁ , t₂) e
ψ p = invEq (θ₁ e) (λ i → p i .fst) , invEq (θ₂ e) (λ i → p i .snd)
η : section φ ψ
η p i j = retEq (θ₁ e) (λ k → p k .fst) i j , retEq (θ₂ e) (λ k → p k .snd) i j
ε : retract φ ψ
ε (p , q) i = secEq (θ₁ e) p i , secEq (θ₂ e) q i
|
"""A simple script to play a bit with pyqtgraph plotting.
This has no direct connection to plottr but is just to explore.
"""
import sys
import numpy as np
import pyqtgraph as pg
from plottr import QtWidgets, QtGui, QtCore
from plottr.gui.tools import widgetDialog
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
def image_test():
app = QtWidgets.QApplication([])
# create data
x = np.linspace(0, 10, 51)
y = np.linspace(-4, 4, 51)
xx, yy = np.meshgrid(x, y, indexing='ij')
zz = np.cos(xx)*np.exp(-(yy-1.)**2)
# layout widget
pgWidget = pg.GraphicsLayoutWidget()
# main plot
imgPlot = pgWidget.addPlot(title='my image', row=0, col=0)
img = pg.ImageItem()
imgPlot.addItem(img)
# histogram and colorbar
hist = pg.HistogramLUTItem()
hist.setImageItem(img)
pgWidget.addItem(hist)
hist.gradient.loadPreset('viridis')
# cut elements
pgWidget2 = pg.GraphicsLayoutWidget()
# plots for x and y cuts
xplot = pgWidget2.addPlot(row=1, col=0)
yplot = pgWidget2.addPlot(row=0, col=0)
xplot.addLegend()
yplot.addLegend()
# add crosshair to main plot
vline = pg.InfiniteLine(angle=90, movable=False, pen='r')
hline = pg.InfiniteLine(angle=0, movable=False, pen='b')
imgPlot.addItem(vline, ignoreBounds=True)
imgPlot.addItem(hline, ignoreBounds=True)
def crossMoved(event):
pos = event[0].scenePos()
if imgPlot.sceneBoundingRect().contains(pos):
origin = imgPlot.vb.mapSceneToView(pos)
vline.setPos(origin.x())
hline.setPos(origin.y())
vidx = np.argmin(np.abs(origin.x()-x))
hidx = np.argmin(np.abs(origin.y()-y))
yplot.clear()
yplot.plot(zz[vidx, :], y, name='vertical cut',
pen=pg.mkPen('r', width=2),
symbol='o', symbolBrush='r', symbolPen=None)
xplot.clear()
xplot.plot(x, zz[:, hidx], name='horizontal cut',
pen=pg.mkPen('b', width=2),
symbol='o', symbolBrush='b', symbolPen=None)
proxy = pg.SignalProxy(imgPlot.scene().sigMouseClicked, slot=crossMoved)
dg = widgetDialog(pgWidget, title='pyqtgraph image test')
dg2 = widgetDialog(pgWidget2, title='line cuts')
# setting the data
img.setImage(zz)
img.setRect(QtCore.QRectF(0, -4, 10, 8.))
hist.setLevels(zz.min(), zz.max())
# formatting
imgPlot.setLabel('left', "Y", units='T')
imgPlot.setLabel('bottom', "X", units='A')
xplot.setLabel('left', 'Z')
xplot.setLabel('bottom', "X", units='A')
yplot.setLabel('left', "Y", units='T')
yplot.setLabel('bottom', "Z")
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtWidgets.QApplication.instance().exec_()
if __name__ == '__main__':
image_test() |
println("\n\ncheck_records.jl: start")
prepend!(LOAD_PATH, ["Project.toml"])
import LibPQ
using DataFrames, PrettyTables
DISASTER_PASSWORD = read("./etc/disaster-pass", String)
postgres = LibPQ.Connection("host=127.0.0.1 port=5432 dbname=disaster user=disaster password=$DISASTER_PASSWORD")
sql_queries = [
"""
select 's_earthquake: record_count=' ||
(select count(*) from public.s_earthquake) ||
', with_ogc_fid_count=' ||
(select count(*) from public.s_earthquake where ogc_fid is not null);
""",
"""
select 's_storm: record_count=' ||
(select count(*) from public.s_storm) ||
', with_ogc_fid_count=' ||
(select count(*) from public.s_storm where ogc_fid is not null);
""",
"""
select 's_wildfire: record_count=' ||
(select count(*) from public.s_wildfire) ||
', with_ogc_fid_count=' ||
(select count(*) from public.s_wildfire where ogc_fid is not null);
""",
"""
select 'total: record_count=' || (
(select count(*) from public.f_earthquake) +
(select count(*) from public.f_storm) +
(select count(*) from public.f_wildfire)
);
""",
"""
select 'f_earthquake: record_count=' ||
(select count(*) from public.f_earthquake);
""",
"""
select 'f_storm: record_count=' ||
(select count(*) from public.f_storm);
""",
"""
select 'f_wildfire: record_count=' ||
(select count(*) from public.f_wildfire);
""",
"""
select distinct(d_severity_id), count(1)
from public.f_earthquake
group by d_severity_id
order by d_severity_id;
""",
"""
select distinct(d_severity_id), count(1)
from public.f_wildfire
group by d_severity_id
order by d_severity_id;
""",
"""
select distinct(d_severity_id), count(1)
from public.f_storm
group by d_severity_id
order by d_severity_id;
""",
]
for sql_query in sql_queries
result = LibPQ.execute(postgres, sql_query) |> DataFrame
pretty_table(result)
end
LibPQ.close(postgres)
println("\ncheck_records: stop")
|
#!/usr/bin/env julia
# Homebrew has a nice way of dealing with version numbers, so let's just use that here
import Homebrew: make_version
import Base: isless, show
immutable Bottle
name::String
version::VersionNumber
platform::String
revision::Int64
Bottle(n,v,p,r) = new(n,make_version(n,v),p, r == nothing ? 0 : int64(r))
end
function isless(a::Bottle, b::Bottle)
if a.name != b.name
return isless(a.name, b.name)
end
if a.platform != b.platform
return isless(a.platform, b.platform)
end
if a.version != b.version
return isless(a.version, b.version)
end
return isless(a.revision, b.revision)
end
function show(io::IO, x::Bottle)
revision = x.revision > 0 ? "$(x.revision)." : ""
print(io, "$(x.name)-$(x.version).$(x.platform).bottle.$(revision)tar.gz")
end
# Parse them all into (name-version, platform, revision):
function parsebottle(filename)
# Unescape "+" because AWS is silly
filename = replace(filename, ' ', '+')
# This matches (name)-(version).(platform).bottle.(revision).tar.gz
# name: freeform
# version: decimal
# platform: freeform
# revision: integer
bottle_regex = r"^(.*)-([0-9._]+)\.([^\.]+).bottle.(?:([0-9]+)\.)?tar.gz"
m = match(bottle_regex, filename)
if m == nothing
println("Skipping $filename because we can't parse it as a bottle...")
return
end
return Bottle(m.captures...)
end
# Get list of bottles
all_bottles = split(readchomp(`aws ls juliabottles --simple` |> `cut -f3-`),'\n')
all_bottles = filter(x -> x != nothing, map(parsebottle, all_bottles))
# Bin them by name:
binned = Dict{String,Array{Bottle,1}}()
for b in all_bottles
if !haskey(binned, b.name)
binned[b.name] = Bottle[]
end
push!(binned[b.name], b)
end
# For each name, find the highest version/revision for each platform, delete all the others
to_delete = Bottle[]
to_keep = Bottle[]
for (name, bottles) in binned
platforms = Dict{String,Array{Bottle,1}}()
for b in bottles
if !haskey(platforms, b.platform)
platforms[b.platform] = Bottle[]
end
push!(platforms[b.platform], b)
end
keep_bottles = map( x -> maximum(x[2])::Bottle, platforms)
for b in keep_bottles
push!(to_keep, b)
end
for b in bottles
if !(b in keep_bottles)
push!(to_delete, b)
end
end
end
# Iterate through to_delete and, well, delete them!
for b in to_delete
println("deleting juliabottles/$b")
run(`aws rm juliabottles/$b`)
end
|
(*
Copyright © 2006-2008 Russell O’Connor
Copyright © 2020 Vincent Semeria
Permission is hereby granted, free of charge, to any person obtaining a copy of
this proof and associated documentation files (the "Proof"), to deal in
the Proof without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Proof, and to permit persons to whom the Proof 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 Proof.
THE PROOF 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 PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.
*)
Require Import CoRN.metric2.Metric.
Require Import CoRN.metric2.UniformContinuity.
Require Import CoRN.model.totalorder.QMinMax.
Require Import CoRN.model.totalorder.QposMinMax.
Require Import Coq.setoid_ring.Ring_theory.
Require Import Coq.Setoids.Setoid.
Require Import Coq.QArith.QArith.
Require Import Coq.QArith.Qabs.
Require Import Coq.QArith.Qround.
Require Import CoRN.metric2.Complete.
Require Import CoRN.metric2.ProductMetric.
Require Export CoRN.reals.fast.CRFieldOps.
Require Import CoRN.model.metric2.Qmetric.
Require Import CoRN.logic.Stability.
Require Import Coq.Logic.ConstructiveEpsilon.
Require Import CoRN.util.Qdlog.
Require Import MathClasses.interfaces.abstract_algebra.
Require Import MathClasses.interfaces.orders.
(* Backwards compatibility for Hint Rewrite locality attributes *)
Set Warnings "-unsupported-attributes".
Local Open Scope CR_scope.
(** Operations on rational numbers over CR are the same as the operations
on rational numbers. *)
Lemma CReq_Qeq : forall (x y:Q), inject_Q_CR x == inject_Q_CR y <-> (x == y)%Q.
Proof.
intros x y.
rewrite <- Qball_0.
apply Cunit_eq.
Qed.
Lemma CRlt_Qlt : forall a b, (a < b)%Q -> ((' a%Q) < (' b))%CR.
Proof.
intros a b H.
destruct (Qpos_sub _ _ H) as [c Hc].
exists c.
intros d.
change (-proj1_sig d <= b + - a + - proj1_sig c)%Q.
rewrite -> Hc.
rewrite -> Qle_minus_iff.
ring_simplify.
apply Qpos_nonneg.
Qed.
Lemma CRplus_Qplus : forall (x y:Q), inject_Q_CR x + inject_Q_CR y == inject_Q_CR (x + y)%Q.
Proof.
intros x y e1 e2; apply ball_refl.
rewrite Qplus_0_r.
apply (Qpos_nonneg (e1+e2)).
Qed.
#[global]
Hint Rewrite <- CRplus_Qplus : toCRring.
Lemma CRopp_Qopp : forall (x:Q), - inject_Q_CR x == inject_Q_CR (- x)%Q.
Proof.
intros x e1 e2; apply ball_refl.
rewrite Qplus_0_r.
apply (Qpos_nonneg (e1+e2)).
Qed.
(* begin hide *)
#[global]
Hint Rewrite CRopp_Qopp : CRfast_compute.
#[global]
Hint Rewrite <- CRopp_Qopp : toCRring.
(* end hide *)
Lemma CRminus_Qminus : forall (x y:Q), inject_Q_CR x - inject_Q_CR y == inject_Q_CR (x - y)%Q.
Proof.
intros x y e1 e2; apply ball_refl.
rewrite Qplus_0_r.
apply (Qpos_nonneg (e1+e2)).
Qed.
(* begin hide *)
#[global]
Hint Rewrite <- CRminus_Qminus : toCRring.
(* end hide *)
Lemma CRmult_Qmult : forall (x y:Q), inject_Q_CR x * inject_Q_CR y == inject_Q_CR (x * y)%Q.
Proof.
intros x y.
rewrite -> CRmult_scale.
intros e1 e2; apply ball_refl.
rewrite Qplus_0_r.
apply (Qpos_nonneg (e1+e2)).
Qed.
(* begin hide *)
#[global]
Hint Rewrite <- CRmult_Qmult : toCRring.
(* end hide *)
Lemma Qap_CRap : forall (x y:Q), (~(x==y))%Q -> (' x)><(' y).
Proof.
intros x y Hxy.
destruct (Q_dec x y) as [[H|H]|H]; try contradiction;
destruct (Qpos_sub _ _ H) as [c Hc];[left|right]; exists c; abstract (rewrite -> CRminus_Qminus;
rewrite -> CRle_Qle; rewrite -> Hc; ring_simplify; apply Qle_refl).
Defined.
Lemma CRinv_Qinv : forall (x:Q) x_, CRinvT (inject_Q_CR x) x_ == inject_Q_CR (/x)%Q.
Proof.
intros x [[c x_]|[c x_]];
[change (' proj1_sig c <= 0 + - 'x)%CR in x_|change (' proj1_sig c <= ' x + - 0)%CR in x_]; unfold CRinvT;
rewrite -> CRopp_Qopp, CRplus_Qplus, CRle_Qle in x_; try rewrite -> CRopp_Qopp;
rewrite -> (@CRinv_pos_Qinv c).
rewrite -> CRopp_Qopp.
rewrite -> CReq_Qeq.
assert (~x==0)%Q.
intros H.
rewrite -> H in x_.
apply (Qle_not_lt _ _ x_).
apply Qpos_ispos.
field.
intros X; apply H.
assumption.
rewrite -> Qplus_0_l in x_.
assumption.
reflexivity.
rewrite -> Qplus_0_r in x_.
assumption.
Qed.
(* begin hide *)
#[global]
Hint Rewrite <- CRinv_Qinv : toCRring.
(* end hide *)
(**
** Ring
CR forms a ring for the ring tactic.
*)
Lemma CRplus_0_l (x: CR): (0 + x == x)%CR.
Proof.
intros e1 e2. destruct x; simpl.
unfold Cap_raw; simpl.
rewrite Qplus_0_r.
rewrite Qplus_0_l.
assert ((1#2)*`e1 + `e2 <= `e1 + `e2)%Q.
{ apply Qplus_le_l. rewrite <- (Qmult_1_l (`e1)) at 2.
apply Qmult_le_r. apply Qpos_ispos. discriminate. }
apply (ball_weak_le Q_as_MetricSpace _ _ H),
(regFun_prf ((1#2)*e1)%Qpos e2).
Qed.
(* Lifting of Qplus_comm *)
Lemma CRplus_comm (x y: CR): x + y == y + x.
Proof.
rewrite CRplus_uncurry_eq.
rewrite CRplus_uncurry_eq.
apply Cmap2_comm.
intros a b. apply Qball_0, Qplus_comm.
Qed.
Lemma CRplus_assoc (x y z: CR): x + (y + z) == (x + y) + z.
Proof.
intros.
intros e1 e2. destruct x,y,z; simpl; unfold Cap_raw; simpl.
unfold Cap_raw; simpl.
apply AbsSmall_Qabs.
setoid_replace (approximate ((1 # 2) * e1)%Qpos +
(approximate0 ((1 # 2) * ((1 # 2) * e1))%Qpos +
approximate1 ((1 # 2) * ((1 # 2) * e1))%Qpos) -
(approximate ((1 # 2) * ((1 # 2) * e2))%Qpos +
approximate0 ((1 # 2) * ((1 # 2) * e2))%Qpos +
approximate1 ((1 # 2) * e2)%Qpos))%Q
with ((approximate ((1 # 2) * e1)%Qpos
- approximate ((1 # 2) * ((1 # 2) * e2))%Qpos)
+ (approximate0 ((1 # 2) * ((1 # 2) * e1))%Qpos
- approximate0 ((1 # 2) * ((1 # 2) * e2))%Qpos)
+ (approximate1 ((1 # 2) * ((1 # 2) * e1))%Qpos
- approximate1 ((1 # 2) * e2)%Qpos))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
rewrite Qplus_0_r.
setoid_replace (` e1 + ` e2)%Q
with (((1#2)* ` e1 + (1#2)*((1#2) * `e2))
+ ((1#2)*((1#2)* `e1) + (1#2)*((1#2)*`e2))
+ ((1#2)*((1#2)* `e1) + (1#2)* ` e2))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply (Qle_trans _ _ _ (Qabs_triangle _ _)).
apply Qplus_le_compat.
apply (Qle_trans _ _ _ (Qabs_triangle _ _)).
apply Qplus_le_compat.
- apply AbsSmall_Qabs.
apply (regFun_prf ((1#2)*e1)%Qpos ((1#2)*((1#2)*e2))%Qpos).
- apply AbsSmall_Qabs.
apply (regFun_prf0 ((1#2)*((1#2)*e1))%Qpos ((1#2)*((1#2)*e2))%Qpos).
- apply AbsSmall_Qabs.
apply (regFun_prf1 ((1#2)*((1#2)*e1))%Qpos ((1#2)*e2)%Qpos).
Qed.
Lemma CRmult_1_l : forall (x: CR), 1 * x == x.
Proof.
intro x. rewrite CRmult_scale.
intros e1 e2. destruct x; simpl.
rewrite Qplus_0_r.
rewrite Qmult_1_l.
rewrite <- (Qmult_1_l (`e1)).
apply (regFun_prf ((1#1)*e1)%Qpos e2).
Qed.
(* Lift Qmult_comm. *)
Lemma CRmult_comm_bounded (x y: CR) (b:Qpos) :
(' (- ` b)%Q <= x)%CR
-> (x <= 'proj1_sig b)%CR
-> (' (- ` b)%Q <= y)%CR
-> (y <= 'proj1_sig b)%CR
-> CRmult_bounded b x y == CRmult_bounded b y x.
Proof.
intros. rewrite CRmult_uncurry_eq, CRmult_uncurry_eq; try assumption.
apply Cmap2_comm.
intros. apply Qball_0, Qmult_comm.
Qed.
Lemma CRmult_comm (x y: CR): x * y == y * x.
Proof.
pose (Qpos_max (CR_b (1#1) x) (CR_b (1#1) y)) as b.
assert (' (- ` b)%Q <= x) as xlower.
{ apply (@CRle_trans _ (' (-proj1_sig (CR_b (1#1) x))%Q)).
2: apply (CR_b_lowerBound _ _).
apply CRle_Qle. apply Qopp_le_compat, Qpos_max_ub_l. }
assert (x <= '(` b)%Q) as xupper.
{ apply (@CRle_trans _ (' (proj1_sig (CR_b (1#1) x))) _ (CR_b_upperBound _ _)).
apply CRle_Qle. apply Qpos_max_ub_l. }
assert (' (- ` b)%Q <= y) as ylower.
{ apply (@CRle_trans _ (' (-proj1_sig (CR_b (1#1) y))%Q)).
2: apply (CR_b_lowerBound _ _).
apply CRle_Qle. apply Qopp_le_compat, Qpos_max_ub_r. }
assert (y <= '(` b)%Q) as yupper.
{ apply (@CRle_trans _ (' (proj1_sig (CR_b (1#1) y))) _ (CR_b_upperBound _ _)).
apply CRle_Qle. apply Qpos_max_ub_r. }
rewrite <- (@CRmult_bounded_mult b x y).
2: exact ylower. 2: exact yupper.
rewrite <- (@CRmult_bounded_mult b y x).
2: exact xlower. 2: exact xupper.
- apply CRmult_comm_bounded.
+ exact xlower.
+ exact xupper.
+ exact ylower.
+ exact yupper.
Qed.
Lemma CRmult_1_r : forall (x: CR), x * 1 == x.
Proof.
intro x. rewrite CRmult_comm. apply CRmult_1_l.
Qed.
Lemma CRmult_assoc (x y z : CR): (x * y) * z == x * (y * z).
Proof.
pose ((CR_b (1#1) x + (1#1)) * (CR_b (1#1) y + (1#1)) * (CR_b (1#1) z + (1#1)))%Qpos
as b.
assert (' (- ` b)%Q <= z) as zlower.
{ apply (@CRle_trans _ (' (-proj1_sig (CR_b (1#1) z))%Q)).
2: apply CR_b_lowerBound.
apply CRle_Qle. apply Qopp_le_compat.
apply (Qle_trans _ (` (CR_b (1#1)%Qpos z) + (1#1))).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
apply CRmult_assoc_zfactor_le. }
assert (z <= ' (` b)%Q) as zupper.
{ apply (@CRle_trans _ (' (proj1_sig (CR_b (1#1) z))%Q)).
apply CR_b_upperBound.
apply CRle_Qle.
apply (Qle_trans _ (` (CR_b (1#1)%Qpos z) + (1#1))).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
apply CRmult_assoc_zfactor_le. }
rewrite <- (@CRmult_bounded_mult b x y), <- (@CRmult_bounded_mult b).
2: exact zlower. 2: exact zupper.
rewrite <- (@CRmult_bounded_mult b), <- (@CRmult_bounded_mult b).
apply CRmult_assoc_bounded.
- exact zlower.
- exact zupper.
- apply (@CRle_trans _ ('(-proj1_sig ((CR_b (1#1) y) * CR_b (1#1) z)%Qpos)%Q)).
2: apply CR_b_lowerBound_2.
apply CRle_Qle, Qopp_le_compat.
apply (Qle_trans _ ((1#1)*proj1_sig (CR_b (1#1) y + (1#1))%Qpos
* proj1_sig ((CR_b (1#1) z) + (1#1))%Qpos)).
rewrite Qmult_1_l.
apply (Qpos_mult_le_compat (CR_b (1#1) y) (CR_b (1#1) z)).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
apply Qmult_le_compat_r. 2: apply Qpos_nonneg.
apply Qmult_le_compat_r. 2: apply Qpos_nonneg.
rewrite <- Qplus_0_l at 1. apply Qplus_le_l. apply Qpos_nonneg.
- apply (CRle_trans (CR_b_upperBound_2 y z)).
apply CRle_Qle.
apply (Qle_trans _ ((1#1)*proj1_sig (CR_b (1#1) y + (1#1))%Qpos
* proj1_sig ((CR_b (1#1) z) + (1#1))%Qpos)).
rewrite Qmult_1_l.
apply (Qpos_mult_le_compat (CR_b (1#1) y) (CR_b (1#1) z)).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
apply Qmult_le_compat_r. 2: apply Qpos_nonneg.
apply Qmult_le_compat_r. 2: apply Qpos_nonneg.
rewrite <- Qplus_0_l at 1. apply Qplus_le_l. apply Qpos_nonneg.
- apply (@CRle_trans _ (' (-proj1_sig (CR_b (1#1) y))%Q)).
2: apply CR_b_lowerBound.
apply CRle_Qle. apply Qopp_le_compat.
apply (Qle_trans _ (` (CR_b (1#1)%Qpos y) + (1#1))).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
apply CRmult_assoc_yfactor_le.
- apply (@CRle_trans _ (' (proj1_sig (CR_b (1#1) y))%Q)).
apply CR_b_upperBound.
apply CRle_Qle.
apply (Qle_trans _ (` (CR_b (1#1)%Qpos y) + (1#1))).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
apply CRmult_assoc_yfactor_le.
Qed.
Lemma CRmult_plus_distr_r : ∀ x y z : CR,
((x + y) * z == x * z + y * z).
Proof.
intros x y z.
pose ((CR_b (1#1) x + CR_b (1#1) y + CR_b (1#1) z))%Qpos as b.
assert (forall u v, QboundAbs u v <= `u)%Q as qbound_bound.
{ intros. apply Qmax_lub.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
apply Qpos_nonneg. apply Qmin_lb_l. }
assert ( ' (- ` b)%Q <= x)%CR as xlower.
{ apply (@CRle_trans _ ('(-(proj1_sig (CR_b (1#1) x)))%Q)).
2: apply CR_b_lowerBound.
apply CRle_Qle, Qopp_le_compat.
rewrite <- Qplus_0_r. simpl.
rewrite <- (Qplus_assoc (Qabs (approximate x (Qpos2QposInf (1#1))) + 1)).
apply Qplus_le_r.
apply (Qpos_nonneg (CR_b (1#1) y + CR_b (1#1) z)). }
assert (x <= ' (` b)%Q)%CR as xupper.
{ apply (@CRle_trans _ ('((proj1_sig (CR_b (1#1) x)))%Q)).
apply CR_b_upperBound.
apply CRle_Qle.
rewrite <- Qplus_0_r. simpl.
rewrite <- (Qplus_assoc (Qabs (approximate x (Qpos2QposInf (1#1))) + 1)).
apply Qplus_le_r.
apply (Qpos_nonneg (CR_b (1#1) y + CR_b (1#1) z)). }
assert ( ' (- ` b)%Q <= y)%CR as ylower.
{ apply (@CRle_trans _ ('(-(proj1_sig (CR_b (1#1) y)))%Q)).
2: apply CR_b_lowerBound.
apply CRle_Qle, Qopp_le_compat.
rewrite <- Qplus_0_l. simpl.
rewrite <- Qplus_assoc. apply Qplus_le_compat.
apply (Qpos_nonneg ((CR_b (1#1) x))).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r.
apply (Qpos_nonneg ((CR_b (1#1) z))). }
assert (y <= ' (` b)%Q)%CR as yupper.
{ apply (@CRle_trans _ ('((proj1_sig (CR_b (1#1) y)))%Q)).
apply CR_b_upperBound.
apply CRle_Qle.
rewrite <- Qplus_0_l. simpl.
rewrite <- Qplus_assoc. apply Qplus_le_compat.
apply (Qpos_nonneg ((CR_b (1#1) x))).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r.
apply (Qpos_nonneg ((CR_b (1#1) z))). }
rewrite <- (CRboundAbs_Eq _ (CR_b_lowerBound (1#1) y) (CR_b_upperBound (1#1) y)).
rewrite <- (CRboundAbs_Eq _ (CR_b_lowerBound (1#1) x) (CR_b_upperBound (1#1) x)).
assert ( ' (- ` b)%Q <= z)%CR as zlower.
{ apply (@CRle_trans _ ('(-(proj1_sig (CR_b (1#1) z)))%Q)).
2: apply CR_b_lowerBound.
apply CRle_Qle, Qopp_le_compat.
rewrite <- Qplus_0_l. apply Qplus_le_compat.
apply Qpos_nonneg. apply Qle_refl. }
assert (z <= ' (` b)%Q)%CR as zupper.
{ apply (@CRle_trans _ ('((proj1_sig (CR_b (1#1) z)))%Q)).
apply CR_b_upperBound.
apply CRle_Qle.
rewrite <- Qplus_0_l. apply Qplus_le_compat.
apply Qpos_nonneg. apply Qle_refl. }
rewrite <- (@CRmult_bounded_mult b (CRboundAbs _ x) z).
2: exact zlower. 2: exact zupper.
rewrite <- (@CRmult_bounded_mult b (CRboundAbs _ y) z).
2: exact zlower. 2: exact zupper.
rewrite <- (@CRmult_bounded_mult b).
2: exact zlower. 2: exact zupper.
rewrite (@CRmult_uncurry_eq b (CRboundAbs _ x) z).
2: rewrite (CRboundAbs_Eq _ (CR_b_lowerBound (1#1) x) (CR_b_upperBound (1#1) x))
; exact xlower.
2: rewrite (CRboundAbs_Eq _ (CR_b_lowerBound (1#1) x) (CR_b_upperBound (1#1) x))
; exact xupper.
rewrite (@CRmult_uncurry_eq b (CRboundAbs _ y) z).
2: rewrite (CRboundAbs_Eq _ (CR_b_lowerBound (1#1) y) (CR_b_upperBound (1#1) y))
; exact ylower.
2: rewrite (CRboundAbs_Eq _ (CR_b_lowerBound (1#1) y) (CR_b_upperBound (1#1) y))
; exact yupper.
rewrite CRmult_uncurry_eq.
intros e1 e2.
rewrite Qplus_0_r.
change (Qball (`e1 + `e2)
(QboundAbs b
(approximate (CRboundAbs (CR_b (1#1) x) x)
((1 # 2) * ((1 # 2) * e1 * Qpos_inv b))%Qpos +
approximate (CRboundAbs (CR_b (1#1) y) y)
((1 # 2) * ((1 # 2) * e1 * Qpos_inv b))%Qpos)%Q
* QboundAbs b (approximate z (Qmult_modulus b ((1 # 2) * e1))))
(QboundAbs b (approximate (CRboundAbs (CR_b (1#1) x) x)
(Qmult_modulus b ((1 # 2) * ((1 # 2) * e2))))
* QboundAbs b (approximate z
(Qmult_modulus b ((1 # 2) * ((1 # 2) * e2))))
+ QboundAbs b (approximate (CRboundAbs (CR_b (1#1) y) y)
(Qmult_modulus b ((1 # 2) * ((1 # 2) * e2))))
* QboundAbs b (approximate z
(Qmult_modulus b ((1 # 2) * ((1 # 2) * e2)))))).
rewrite <- Qmult_plus_distr_l.
unfold Qmult_modulus.
apply AbsSmall_Qabs.
assert (forall i j k l : Q, Qabs (i*j-k*l) <= Qabs i * Qabs(j-l) + Qabs(i-k)*Qabs l)%Q
as multMaj.
{ intros.
setoid_replace (i*j-k*l)%Q with (i*(j-l)+ (i-k)*l)%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply (Qle_trans _ _ _ (Qabs_triangle _ _)).
rewrite Qabs_Qmult, Qabs_Qmult. apply Qle_refl. }
apply (Qle_trans _ ((1#2)*`e1 + (1#2)*`e2 +((1#2)*`e1 +(1#2)*`e2))).
2: ring_simplify; apply Qle_refl.
apply (Qle_trans _ _ _ (multMaj _ _ _ _)). clear multMaj.
apply Qplus_le_compat.
- apply (Qle_trans _ (`b * Qabs
(QboundAbs b (approximate z ((1 # 2) * e1 * Qpos_inv b)%Qpos) -
QboundAbs b
(approximate z
((1 # 2) * ((1 # 2) * e2) * Qpos_inv b)%Qpos)))).
apply Qmult_le_compat_r. 2: apply Qabs_nonneg.
rewrite QboundAbs_abs. apply Qmin_lb_r.
rewrite Qmult_comm.
apply (Qle_trans _ (Qabs
(approximate z ((1 # 2) * e1 * Qpos_inv b)%Qpos -
approximate z
((1 # 2) * ((1 # 2) * e2) * Qpos_inv b)%Qpos) * ` b)).
apply Qmult_le_compat_r. 2: apply Qpos_nonneg.
apply QboundAbs_contract.
apply (Qle_trans _ (((1#2)*`e1 / `b + (1#2)*`e2 / `b) * `b)).
apply Qmult_le_r. apply Qpos_ispos.
pose proof (regFun_prf z ((1 # 2) * e1 * Qpos_inv b)%Qpos
((1 # 2) * ((1 # 2) * e2) * Qpos_inv b)%Qpos) as H4.
apply AbsSmall_Qabs in H4.
apply (Qle_trans _ _ _ H4).
apply Qplus_le_r. simpl.
rewrite Qmult_assoc. apply Qmult_le_r.
apply Qinv_lt_0_compat, (Qpos_ispos b).
apply Qmult_le_r. apply Qpos_ispos. discriminate.
rewrite Qmult_comm.
rewrite Qmult_plus_distr_r.
apply Qplus_le_compat.
unfold Qdiv. rewrite Qmult_assoc.
apply Qle_shift_div_r. apply Qpos_ispos.
rewrite Qmult_comm. apply Qle_refl.
unfold Qdiv. rewrite Qmult_assoc.
apply Qle_shift_div_r. apply Qpos_ispos.
rewrite Qmult_comm. apply Qle_refl.
- assert (forall u, Qabs u <= `b -> QboundAbs b u == u)%Q.
{ intros u H. apply QboundAbs_elim.
intros. apply Qle_antisym. exact H0.
apply (Qle_trans _ (Qabs u)). apply Qle_Qabs. exact H.
intros. apply Qle_antisym. 2: exact H0.
rewrite <- (Qopp_involutive u). apply Qopp_le_compat.
rewrite <- Qabs_opp in H.
exact (Qle_trans _ _ _ (Qle_Qabs _) H).
intros. reflexivity. }
rewrite H, H, H; clear H.
rewrite QboundAbs_abs.
rewrite Qmult_comm.
apply (Qle_trans _ (` b * Qabs
(approximate (CRboundAbs (CR_b (1#1) x) x)
((1 # 2) * ((1 # 2) * e1 * Qpos_inv b))%Qpos +
approximate (CRboundAbs (CR_b (1#1) y) y)
((1 # 2) * ((1 # 2) * e1 * Qpos_inv b))%Qpos -
(approximate (CRboundAbs (CR_b (1#1) x) x)
((1 # 2) * ((1 # 2) * e2) * Qpos_inv b)%Qpos +
approximate (CRboundAbs (CR_b (1#1) y) y)
((1 # 2) * ((1 # 2) * e2) * Qpos_inv b)%Qpos)))).
+ apply Qmult_le_compat_r. 2: apply Qabs_nonneg. apply Qmin_lb_r.
+ rewrite Qmult_comm.
apply (Qle_trans _ (((1#2)*`e1 / `b + (1#2)*`e2 / `b) * `b)).
apply Qmult_le_r. apply Qpos_ispos.
assert (forall a b c d, a + b - (c+d) == a - c + (b-d))%Q by (intros; ring).
rewrite H; clear H.
apply (Qle_trans _ _ _ (Qabs_triangle _ _)).
apply (Qle_trans _ (((1#2) * ((1 # 2) * ` e1 / ` b) + (1#2) * ((1 # 2) * ` e2) / ` b)
+ ((1#2) * ((1 # 2) * ` e1 / ` b) + (1#2) * ((1 # 2) * ` e2) / ` b))).
apply Qplus_le_compat.
pose proof (regFun_prf (CRboundAbs (CR_b (1#1) x) x)
((1 # 2) * ((1 # 2) * e1 * Qpos_inv b))%Qpos
((1 # 2) * ((1 # 2) * e2) * Qpos_inv b)%Qpos) as H4.
apply AbsSmall_Qabs in H4.
apply (Qle_trans _ _ _ H4). clear H4. apply Qle_refl.
pose proof (regFun_prf (CRboundAbs (CR_b (1#1) y) y)
((1 # 2) * ((1 # 2) * e1 * Qpos_inv b))%Qpos
((1 # 2) * ((1 # 2) * e2) * Qpos_inv b)%Qpos) as H4.
apply AbsSmall_Qabs in H4.
apply (Qle_trans _ _ _ H4). clear H4. apply Qle_refl.
unfold Qdiv. ring_simplify.
setoid_replace (8#16)%Q with (1#2)%Q by reflexivity. apply Qle_refl.
rewrite Qmult_comm, Qmult_plus_distr_r.
apply Qplus_le_compat.
unfold Qdiv. rewrite Qmult_assoc.
apply Qle_shift_div_r. apply Qpos_ispos.
rewrite Qmult_comm. apply Qle_refl.
unfold Qdiv. rewrite Qmult_assoc.
apply Qle_shift_div_r. apply Qpos_ispos.
rewrite Qmult_comm. apply Qle_refl.
+ change (Qabs (QboundAbs (CR_b (1#1) y) (approximate y ((1 # 2) * ((1 # 2) * e2) * Qpos_inv b)%Qpos))
<= `b)%Q.
rewrite QboundAbs_abs.
apply (Qle_trans _ _ _ (Qmin_lb_r _ _)).
rewrite <- Qplus_0_r. apply Qplus_le_compat.
2: apply Qpos_nonneg.
rewrite <- Qplus_0_l. apply Qplus_le_l.
apply Qpos_nonneg.
+ change (Qabs (QboundAbs (CR_b (1#1) x) (approximate x ((1 # 2) * ((1 # 2) * e2) * Qpos_inv b)%Qpos))
<= `b)%Q.
rewrite QboundAbs_abs.
apply (Qle_trans _ _ _ (Qmin_lb_r _ _)).
rewrite <- Qplus_0_r. apply Qplus_le_compat.
2: apply Qpos_nonneg.
rewrite <- Qplus_0_r. apply Qplus_le_r.
apply Qpos_nonneg.
+ apply (Qle_trans _ _ _ (Qabs_triangle _ _)).
setoid_replace (proj1_sig b) with
(proj1_sig (CR_b (1#1) x) + (proj1_sig (CR_b (1#1) y) + proj1_sig (CR_b (1#1) z)))%Q
by (simpl; unfold equiv, stdlib_rationals.Q_eq; ring).
apply Qplus_le_compat.
change (Qabs (QboundAbs (CR_b (1#1) x)
(approximate x ((1 # 2) * ((1 # 2) * e1 * Qpos_inv b))%Qpos)) <= proj1_sig (CR_b (1#1) x))%Q.
rewrite QboundAbs_abs.
apply Qmin_lb_r.
change (Qabs (QboundAbs (CR_b (1#1) y)
(approximate y ((1 # 2) * ((1 # 2) * e1 * Qpos_inv b))%Qpos)) <= proj1_sig (CR_b (1#1) y) + proj1_sig (CR_b (1#1) z))%Q.
rewrite QboundAbs_abs.
apply (Qle_trans _ (proj1_sig (CR_b (1#1) y) + 0)).
rewrite Qplus_0_r. apply Qmin_lb_r.
apply Qplus_le_r. apply Qpos_nonneg.
- simpl. intro e. simpl.
unfold Cap_raw; simpl.
unfold Cap_raw; simpl.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
rewrite <- Qle_minus_iff.
apply (Qle_trans _ (- (Qabs (approximate x (Qpos2QposInf (1#1))) + 1)
- (Qabs (approximate y (Qpos2QposInf (1#1))) + 1))).
2: apply Qplus_le_compat; apply Qmax_ub_l.
setoid_replace (- (Qabs (approximate x (Qpos2QposInf (1#1))) + 1) -
(Qabs (approximate y (Qpos2QposInf (1#1))) + 1))%Q
with (- ((Qabs (approximate x (Qpos2QposInf (1#1))) + 1) +
(Qabs (approximate y (Qpos2QposInf (1#1))) + 1)))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply Qopp_le_compat.
rewrite <- Qplus_0_r. apply Qplus_le_r.
apply (Qpos_nonneg (CR_b (1#1) z)).
- simpl. intro e. simpl.
unfold Cap_raw; simpl.
unfold Cap_raw; simpl.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
rewrite <- Qle_minus_iff.
apply (Qle_trans _ (Qabs (approximate x (Qpos2QposInf (1#1))) + 1
+ (Qabs (approximate y (Qpos2QposInf (1#1))) + 1))).
apply Qplus_le_compat.
apply (qbound_bound (CR_b (1#1) x)).
apply (qbound_bound (CR_b (1#1) y)).
rewrite <- Qplus_0_r. apply Qplus_le_r.
apply (Qpos_nonneg (CR_b (1#1) z)).
Qed.
Lemma CRmult_plus_distr_l : ∀ x y z : CR,
(z * (x + y) == z * x + z * y)%CR.
Proof.
intros.
rewrite CRmult_comm, CRmult_plus_distr_r.
rewrite (CRmult_comm z).
rewrite (CRmult_comm z).
reflexivity.
Qed.
Lemma CR_ring_theory :
@ring_theory CR 0 1 (ucFun2 CRplus_uc) CRmult
(fun (x y:CR) => (x + - y)) CRopp (@msp_eq CR).
Proof.
split.
- exact CRplus_0_l.
- exact CRplus_comm.
- exact CRplus_assoc.
- exact CRmult_1_l.
- exact CRmult_comm.
- intros. symmetry. apply CRmult_assoc.
- exact CRmult_plus_distr_r.
- reflexivity.
- intros x e1 e2. simpl.
unfold Cap_raw;simpl. rewrite Qplus_0_r.
rewrite Qplus_opp_r.
apply Qball_Reflexive. apply (Qpos_nonneg (e1+e2)).
Qed.
Lemma CR_Q_ring_morphism :
ring_morph 0%CR 1%CR (ucFun2 CRplus_uc) CRmult
(fun x y => (x + - y)) CRopp (@msp_eq CR)
(0%Q) (1%Q) Qplus Qmult Qminus Qopp Qeq_bool (inject_Q_CR).
Proof.
split; try reflexivity.
apply CRplus_Qplus.
apply CRminus_Qminus.
intros x y; rewrite -> CRmult_Qmult; reflexivity.
apply CRopp_Qopp.
intros x y H.
rewrite -> CReq_Qeq.
apply Qeq_bool_eq.
assumption.
Qed.
Ltac CRcst t :=
match t with
| (inject_Q_CR ?z) => Qcst z
| _ => NotConstant
end.
Ltac CRring_pre := autorewrite with toCRring.
Lemma CR_ring_eq_ext : ring_eq_ext (ucFun2 CRplus_uc) CRmult CRopp (@msp_eq CR).
Proof.
split.
rapply ucFun2_wd.
rapply CRmult_wd.
rapply uc_wd.
Qed.
Add Ring CR_ring : CR_ring_theory (morphism CR_Q_ring_morphism, setoid (@msp_Setoid CR) CR_ring_eq_ext, constants [CRcst], preprocess [CRring_pre]).
(** Relationship between strict and nonstrict positivity *)
Lemma CRpos_nonNeg : forall x, CRpos x -> CRnonNeg x.
Proof.
intros x [c Hx].
cut (0 <= x)%CR.
unfold CRle.
intros H.
assert (x == x - 0)%CR. ring. rewrite -> H0.
assumption.
apply CRle_trans with (' proj1_sig c)%CR; auto with *.
rewrite -> CRle_Qle; auto with *.
Qed.
Lemma CRneg_nonPos : forall x, CRneg x -> CRnonPos x.
Proof.
intros x [c Hx].
cut (x <= 0)%CR.
unfold CRle.
intros H.
assert (0 - x == -x)%CR. ring. rewrite -> H0 in H.
intros e.
rewrite <- (Qopp_involutive (proj1_sig e)).
rewrite <- (Qopp_involutive (approximate x e)).
apply Qopp_le_compat.
apply H.
apply CRle_trans with ('(-proj1_sig c)%Q)%CR; auto with *.
rewrite -> CRle_Qle.
apply (Qopp_le_compat 0). apply Qpos_nonneg.
Qed.
(** Now that we have ring-ness, we can easily prove some auxiliary utility lemmas about operations on CR. *)
Ltac CRring_replace x y :=
assert (x == y) as CRring_replace_temp by ring;
rewrite CRring_replace_temp;
clear CRring_replace_temp.
(* setoid_replace picks the st_eq equality which ring doesn't work for... *)
Lemma CRle_opp (x y: CR): x <= y <-> - y <= - x.
Proof.
unfold CRle. intros.
assert (- x - - y == y - x)%CR as E by ring.
rewrite E.
intuition.
Qed.
Lemma CRopp_opp (x: CR): (--x == x)%CR.
Proof. intros. ring. Qed.
Lemma CRplus_opp (x: CR): (x + - x == 0)%CR.
Proof. intros. ring. Qed.
Lemma CRopp_0: (-0 == 0)%CR.
Proof. intros. ring. Qed.
Lemma CRplus_0_r (x: CR): (x + 0 == x)%CR.
Proof. intros. ring. Qed.
Lemma CRmult_0_r (x: CR): (x * 0 == 0)%CR.
Proof. intros. ring. Qed.
Lemma CRopp_plus_distr : forall (r1 r2 : CR),
- (r1 + r2) == - r1 + - r2.
Proof. intros. ring. Qed.
Lemma CRopp_mult_distr_r : forall (r1 r2 : CR),
- (r1 * r2) == r1 * (- r2).
Proof. intros. ring. Qed.
Lemma CRopp_mult_distr_l : forall (r1 r2 : CR),
- (r1 * r2) == (-r1) * r2.
Proof. intros. ring. Qed.
Lemma approximate_CRplus (x y: CR) (e: Qpos):
approximate (x + y)%CR e = (approximate x ((1#2) * e)%Qpos + approximate y ((1#2) * e)%Qpos)%Q.
Proof. reflexivity. Qed.
Lemma CRnonNeg_CRplus (x y: CR): CRnonNeg x -> CRnonNeg y -> CRnonNeg (x + y)%CR.
Proof.
unfold CRnonNeg. intros. rewrite approximate_CRplus.
setoid_replace (- proj1_sig e)%Q
with (- proj1_sig ((1#2)*e)%Qpos + - proj1_sig ((1#2)*e)%Qpos)%Q
by (simpl; unfold equiv, stdlib_rationals.Q_eq; ring).
apply Qplus_le_compat; auto.
Qed.
Lemma CRplus_eq_l (z x y: CR): x == y <-> x + z == y + z.
Proof with ring.
split; intro E. rewrite E...
rewrite <- (CRplus_0_r x), <- (CRplus_opp z), CRplus_assoc, E...
Qed.
Lemma CRplus_eq_r (z x y: CR): x == y <-> z + x == z + y.
Proof. intros. do 2 rewrite (CRplus_comm z). apply CRplus_eq_l. Qed.
Lemma CRplus_le_r (x y z: CR): x <= y <-> x+z <= y+z.
Proof.
unfold CRle. intros.
assert (y + z - (x + z) == y - x)%CR as E by ring. rewrite E.
intuition.
Qed.
Lemma CRplus_le_l x: forall y z : CR, x <= y <-> z + x <= z + y.
Proof.
intros. rewrite (CRplus_le_r x y z), (CRplus_comm x), (CRplus_comm y). reflexivity.
Qed.
Lemma CRplus_le_compat (x x' y y': CR): x <= x' -> y <= y' -> x+y <= x'+y'.
Proof.
unfold CRle. intros.
assert (x' + y' - (x + y) == (x' - x) + (y' - y)) as E by ring. rewrite E.
apply CRnonNeg_CRplus; assumption.
Qed.
Lemma CRplus_lt_r (x y z: CR):
prod (x < y -> x+z < y+z)
(x+z < y+z -> x < y).
Proof.
split.
- intros. destruct H as [q H].
exists q. setoid_replace (y+z-(x+z))%CR with (y-x)%CR
by (unfold equiv, msp_Equiv; ring).
exact H.
- intros. destruct H as [q H].
exists q. setoid_replace (y-x) with (y+z-(x+z))
by (unfold equiv, msp_Equiv; ring).
exact H.
Qed.
Lemma CRplus_lt_l (x y z: CR):
prod (x < y -> z+x < z+y)
(z+x < z+y -> x < y).
Proof.
split.
- intros. destruct H as [q H].
exists q. setoid_replace (z+y-(z+x)) with (y-x)
by (unfold equiv, msp_Equiv; ring).
exact H.
- intros. destruct H as [q H].
exists q. setoid_replace (y-x) with (z+y-(z+x))
by (unfold equiv, msp_Equiv; ring).
exact H.
Qed.
Lemma CRopp_lt_compat : forall x y : CR,
x < y -> -y < -x.
Proof.
intros. apply (CRplus_lt_l _ _ (x+y)).
assert (x == x+y-y)%CR by ring.
assert (y == x+y-x)%CR by ring.
apply (CRltT_wd H0 H1), H.
Qed.
Lemma CRopp_lt_cancel : forall x y : CR,
-y < -x -> x < y.
Proof.
intros. apply (CRplus_lt_l _ _ (-x-y)).
assert (-y == -x-y+x)%CR by ring.
assert (-x == -x-y+y)%CR by ring.
apply (CRltT_wd H0 H1), H.
Qed.
Lemma CRopp_le_compat : forall x y : CR,
x <= y -> -y <= -x.
Proof.
intros. apply (CRplus_le_l _ _ (x+y)).
ring_simplify. exact H.
Qed.
Lemma CRopp_le_cancel : forall x y : CR,
-y <= -x -> x <= y.
Proof.
intros. apply (CRplus_le_l (-y) (-x) (x+y)) in H.
ring_simplify in H. exact H.
Qed.
Lemma CRle_Q : forall (x : CR) (q : Q),
('q <= x)%CR
<-> (forall e:Qpos, q <= approximate x e + proj1_sig e)%Q.
Proof.
split.
- intros.
unfold CRle in H.
rewrite CRopp_Qopp, CRplus_comm, CRplus_translate in H.
specialize (H e).
simpl in H. apply (Qplus_le_l _ _ (`e + q)) in H.
ring_simplify in H. rewrite Qplus_comm. exact H.
- intros. unfold CRle.
rewrite CRopp_Qopp, CRplus_comm, CRplus_translate.
intro e.
simpl. apply (Qplus_le_l _ _ (`e + q)).
ring_simplify. rewrite Qplus_comm. apply H.
Qed.
Lemma CRlt_irrefl (x: CR): x < x -> False.
Proof with auto.
unfold CRltT.
intro.
assert (x - x == 0)%CR by ring.
intros.
generalize (CRpos_wd H0 H).
unfold CRpos.
intros.
destruct H1.
destruct x0.
simpl in c.
assert (x0 <= 0)%Q.
rewrite <- CRle_Qle...
apply Qlt_irrefl with 0%Q.
apply Qlt_le_trans with x0...
Qed.
Lemma CRAbsSmall_ball : forall (x y:CR) (e:Q),
(-'e <= x-y /\ x-y <= 'e)%CR <-> ball e x y.
Proof.
intros x y e.
split.
- intros [H1 H2].
rewrite <- (doubleSpeed_Eq x).
rewrite <- (doubleSpeed_Eq (doubleSpeed x)).
rewrite <- (doubleSpeed_Eq y).
rewrite <- (doubleSpeed_Eq (doubleSpeed y)).
apply regFunBall_e.
intros d.
assert (H1':=H1 d).
assert (H2':=H2 d).
clear H1 H2.
simpl.
set (x':=approximate x ((1#2)*((1#2)*d))%Qpos).
set (y':=approximate y ((1#2)*((1#2)*d))%Qpos).
change (-proj1_sig d <= x' - y' + - - e)%Q in H1'.
change (-proj1_sig d <= e + - (x' - y'))%Q in H2'.
rewrite -> Qle_minus_iff in *.
apply ball_weak. apply Qpos_nonneg.
split; simpl; rewrite -> Qle_minus_iff.
rewrite Qopp_involutive. do 2 rewrite Qopp_involutive in H1'.
rewrite (Qplus_comm (proj1_sig d)).
rewrite Qplus_assoc. exact H1'.
rewrite <- Qplus_assoc, Qplus_comm. rewrite Qopp_involutive in H2'.
exact H2'.
- intros H.
rewrite <- (doubleSpeed_Eq x) in H.
rewrite <- (doubleSpeed_Eq y) in H.
split; intros d; destruct (H ((1#2)*d)%Qpos ((1#2)*d)%Qpos) as [H1 H2]; clear H;
set (x':=(approximate (doubleSpeed x) ((1 # 2) * d)%Qpos)) in *;
set (y':=(approximate (doubleSpeed y) ((1 # 2) * d)%Qpos)) in *.
autorewrite with QposElim in H1.
change (- ((1 # 2) * proj1_sig d + e + (1 # 2) * proj1_sig d)<=x' - y')%Q in H1.
change (-proj1_sig d <= x' - y' + - - e)%Q.
rewrite -> Qle_minus_iff.
rewrite -> Qle_minus_iff in H1.
setoid_replace (x' - y' + - - e + - - ` d)%Q
with (x' - y' + - - ((1 # 2) * proj1_sig d + e + (1 # 2) * proj1_sig d))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
assumption.
autorewrite with QposElim in H2.
change (x' - y'<=((1 # 2) * proj1_sig d + e + (1 # 2) * proj1_sig d))%Q in H2.
change (-proj1_sig d <= e + - (x' - y'))%Q.
rewrite -> Qle_minus_iff.
rewrite -> Qle_minus_iff in H2.
setoid_replace (e + - (x' - y') + - - ` d)%Q
with ((1 # 2) * proj1_sig d + e + (1 # 2) * proj1_sig d + - (x' - y'))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
assumption.
Qed.
Lemma in_CRball (r: Q) (x y : CR)
: x - ' r <= y /\ y <= x + ' r <-> ball r x y.
(* A characterization of ball in terms of <=, similar to CRAbsSmall. *)
Proof with intuition.
intros.
cut ((-' r <= x - y /\ x-y <= 'r) <-> (x - ' r <= y /\ y <= x + ' r)).
- pose proof (CRAbsSmall_ball x y r)...
- simpl.
setoid_replace (x - y <= ' r) with (x - ' r <= y).
setoid_replace (- ' r <= x - y) with (y <= x + ' r).
intuition.
rewrite (CRplus_le_r (- ' r) (x - y) ('r + y)).
assert (- ' r + (' r + y) == y) as E by ring. rewrite E.
assert (x - y + (' r + y) == x + ' r)%CR as F by ring. rewrite F...
rewrite (CRplus_le_r (x - y) (' r) (y - 'r)).
assert (x - y + (y - ' r) == x - ' r) as E by ring. rewrite E.
assert (' r + (y - ' r) == y) as F by ring. rewrite F...
Qed.
(* And the same for gball: *)
Lemma in_CRgball (r: Q) (x y: CR): x - ' r <= y /\ y <= x + ' r <-> ball r x y.
Proof with intuition.
apply in_CRball.
Qed.
Lemma CRgball_plus (x x' y y': CR) e1 e2:
ball e1 x x' -> ball e2 y y' -> ball (e1 + e2) (x + y)%CR (x' + y')%CR.
Proof with auto.
do 3 rewrite <- in_CRgball.
intros [A B] [C D].
CRring_replace (x + y - ' (e1 + e2)%Q) (x - ' e1 + (y - ' e2)).
CRring_replace (x + y + ' (e1 + e2)%Q) (x + ' e1 + (y + ' e2)).
split; apply CRplus_le_compat...
Qed.
Lemma Qlt_from_CRlt (a b: Q): (' a < ' b)%CR -> (a < b)%Q.
Proof with auto.
unfold CRltT.
unfold CRpos.
intros [[e p] H].
revert H.
simpl.
rewrite CRminus_Qminus.
rewrite CRle_Qle.
intros.
apply Qlt_le_trans with (a + e)%Q.
rewrite <-(Qplus_0_r a) at 1.
apply Qplus_lt_r...
apply Q.Qplus_le_l with (-a)%Q.
ring_simplify.
rewrite Qplus_comm...
Qed.
Lemma CRlt_trans (x y z: CR): x < y -> y < z -> x < z.
Proof.
intros [q H] [r H0]. exists (q+r)%Qpos.
rewrite <- (doubleSpeed_Eq z).
rewrite <- (doubleSpeed_Eq x).
intro e. simpl.
unfold Cap_raw; simpl.
unfold Cap_raw; simpl.
specialize (H ((1#2)*e)%Qpos). simpl in H.
specialize (H0 ((1#2)*e)%Qpos). simpl in H0.
unfold Cap_raw in H0; simpl in H0.
unfold Cap_raw in H0; simpl in H0.
unfold Cap_raw in H; simpl in H.
unfold Cap_raw in H; simpl in H.
apply (Qplus_le_compat _ _ _ _ H) in H0.
setoid_replace (- ((1 # 2) * ` e) + - ((1 # 2) * ` e))%Q
with (-`e)%Q in H0 by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply (Qle_trans _ _ _ H0).
ring_simplify. apply Qle_refl.
Qed.
Lemma CRle_lt_trans (x y z: CR): x <= y -> y < z -> x < z.
Proof with auto.
intros ? [e ?]. exists e.
apply CRle_trans with (z - y)%CR...
assert (z - x - (z - y) == y - x)%CR as E by ring.
unfold CRle.
rewrite E...
Qed.
Lemma CRlt_le_trans (x y z: CR): x < y -> y <= z -> x < z.
Proof with auto.
intros [e ?] ?. exists e.
apply CRle_trans with (y - x)%CR...
assert (z - x - (y - x) == z - y)%CR as E by ring.
unfold CRle.
rewrite E...
Qed.
Lemma CRlt_le_weak (x y: CR): (x < y -> x <= y)%CR.
Proof. intros. apply CRpos_nonNeg. assumption. Qed.
Lemma lower_CRapproximation (x: CR) (e: Qpos): ' (approximate x e - proj1_sig e)%Q <= x.
Proof.
intros. rewrite <- CRminus_Qminus.
apply CRplus_le_r with ('proj1_sig e)%CR.
ring_simplify. rewrite CRplus_comm.
apply in_CRball, ball_approx_r.
Qed.
Lemma upper_CRapproximation (x: CR) (e: Qpos): x <= ' (approximate x e + proj1_sig e)%Q.
Proof.
intros. rewrite <- CRplus_Qplus.
apply CRplus_le_r with (-'proj1_sig e)%CR.
assert (' approximate x e + 'proj1_sig e - 'proj1_sig e == ' approximate x e)%CR as E by ring. rewrite E.
apply (in_CRball (proj1_sig e) x ('approximate x e)), ball_approx_r.
Qed.
#[global]
Hint Immediate lower_CRapproximation upper_CRapproximation.
Lemma reverseRegFun : forall (x : CR) (e1 e2 : Qpos),
(-(`e1+`e2) <= Qabs (approximate x e1) - Qabs (approximate x e2))%Q.
Proof.
intros.
setoid_replace (Qabs (approximate x e1) - Qabs (approximate x e2))%Q
with (-(Qabs (approximate x e2) - Qabs (approximate x e1)))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply Qopp_le_compat.
apply (Qle_trans _ _ _ (Qabs_triangle_reverse _ _)).
pose proof (regFun_prf x e2 e1).
apply AbsSmall_Qabs in H. rewrite Qplus_comm. exact H.
Qed.
Lemma CRinv_0_lt_compat : forall (x : CR) (xnz : (x >< 0)%CR),
(0 < x -> 0 < CRinvT x xnz)%CR.
Proof.
intros. unfold CRinvT. destruct xnz.
- exfalso. apply (CRlt_irrefl x).
exact (CRlt_trans _ _ _ c H).
- destruct c as [q c].
pose (CR_b (1#1) x + (1#1))%Qpos as b.
exists (Qpos_inv b). rewrite CRopp_0, CRplus_0_r.
rewrite CRopp_0, CRplus_0_r in c.
intro e. simpl. unfold Cap_raw. simpl.
unfold Qinv_modulus.
change (Qabs (approximate x (Qpos2QposInf (1 # 1))) + 1 + 1)%Q
with (`b).
assert (`q <= `b)%Q as qleb.
{ apply CRle_Qle. apply (CRle_trans c).
apply (CRle_trans (CR_b_upperBound (1#1)%Qpos x)).
simpl. apply CRle_Qle.
rewrite <- Qplus_assoc. apply Qplus_le_r. discriminate. }
apply Qmax_case.
+ intros _. apply (Qle_trans _ 0).
apply (Qopp_le_compat 0), Qpos_nonneg.
rewrite <- Qle_minus_iff.
apply Qle_shift_inv_r. apply Qpos_ispos.
rewrite Qmult_comm. apply Qle_shift_div_l. apply Qpos_ispos.
rewrite Qmult_1_l. exact qleb.
+ intros.
apply (Qmult_le_l _ _ (approximate x (q * q * ((1 # 2)%Q ↾ eq_refl * e))%Qpos)).
exact (Qlt_le_trans _ (`q) _ (Qpos_ispos q) H0).
rewrite Qmult_plus_distr_r, Qmult_inv_r.
apply (Qmult_le_l _ _ (`b)).
apply Qpos_ispos.
rewrite Qmult_plus_distr_r.
setoid_replace (` b *
((approximate x (q * q * ((1 # 2) * e))%Qpos) * - / ` b))%Q
with (-(approximate x (q * q * ((1 # 2)%Q ↾ eq_refl * e))%Qpos))%Q
by (unfold equiv, stdlib_rationals.Q_eq; field).
2: apply Qpos_nonzero.
rewrite Qmult_1_r.
apply (Qle_trans _ (-(`q * `q * `e))).
setoid_replace (` b * (approximate x (q * q * ((1 # 2)%Q ↾ eq_refl * e))%Qpos * - ` e))%Q
with (-(` b * (approximate x (q * q * ((1 # 2)%Q ↾ eq_refl * e))%Qpos *` e)))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply Qopp_le_compat.
rewrite Qmult_assoc. apply Qmult_le_r. apply Qpos_ispos.
apply Qpos_mult_le_compat. exact qleb. exact H0.
unfold b, CR_b. simpl.
rewrite <- (Qabs_pos (approximate x (q * q * ((1 # 2)%Q ↾ eq_refl * e))%Qpos)).
apply (Qle_trans _ (-((1#1)+(`q * `q * ((1 # 2) * `e))) + (2#1)))%Q.
apply (Qle_trans _ (-(`q * `q * ((1 # 2) * `e)))).
apply Qopp_le_compat. apply Qmult_le_l. apply (Qpos_ispos (q*q)).
rewrite <- (Qmult_1_l (`e)) at 2.
apply Qmult_le_r. apply Qpos_ispos. discriminate.
rewrite <- Qplus_0_r.
setoid_replace (- ((1#1) + ` q * ` q * ((1 # 2) * ` e)) + (2#1))%Q
with (- (` q * ` q * ((1 # 2) * ` e)) + (1#1))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply Qplus_le_r. discriminate.
rewrite <- Qplus_assoc, <- Qplus_assoc, (Qplus_assoc (1#1)).
setoid_replace ((1#1)+(1#1))%Q with (2#1)%Q by reflexivity.
rewrite (Qplus_comm (2#1)), Qplus_assoc.
apply Qplus_le_compat.
apply (reverseRegFun x (1#1) (q * q * ((1 # 2) * e))).
discriminate.
apply (Qle_trans _ (`q)). apply Qpos_nonneg. exact H0.
intro abs. rewrite abs in H0.
apply (Qle_not_lt _ _ H0), Qpos_ispos.
Qed.
Lemma CRlt_Qmid (x y: CR): x < y -> sigT (λ q: Q, prod (x < 'q) ('q < y)).
Proof with auto.
intros [q E].
set (quarter := ((1#4)*q)%Qpos).
exists (proj1_sig quarter + (approximate x quarter + proj1_sig quarter))%Q.
split.
apply CRle_lt_trans with (' (0 + (approximate x quarter + proj1_sig quarter))%Q)%CR...
rewrite Qplus_0_l...
apply CRlt_Qlt.
apply Qplus_lt_l...
apply CRlt_le_trans with (x + 'proj1_sig q)%CR.
apply CRlt_le_trans with (' (approximate x quarter - proj1_sig quarter + proj1_sig q)%Q)%CR.
apply CRlt_Qlt.
setoid_replace (proj1_sig q)
with (proj1_sig quarter + proj1_sig quarter + proj1_sig quarter + proj1_sig quarter)%Q.
ring_simplify.
apply Qplus_lt_l.
apply Qmult_lt_compat_r...
reflexivity.
simpl. unfold equiv, stdlib_rationals.Q_eq; ring.
rewrite <- CRplus_Qplus.
apply CRplus_le_compat...
apply CRle_refl.
apply CRplus_le_r with (-x)%CR.
CRring_replace (x + 'proj1_sig q - x) ('proj1_sig q)...
Qed.
Lemma CRlt_linear : forall x y z : CR,
x < z -> (sum (x < y) (y < z)).
Proof.
intros.
destruct (CRlt_Qmid _ _ H) as [q [H0 H1]]. (* Destructing x < z and dividing the
witness by 2 would be faster. *)
destruct (CRlt_Qmid _ _ H1) as [r [H2 H3]].
assert (Qlt 0 ((1#2)*(r-q))) as qltr.
{ rewrite <- (Qmult_0_r (1#2)). apply Qmult_lt_l.
reflexivity.
unfold Qminus. rewrite <- Qlt_minus_iff.
apply Qlt_from_CRlt, H2. }
destruct (Qlt_le_dec (approximate y (Qpos2QposInf (exist (Qlt 0) _ qltr)))
((1#2)*(q+r))).
- right. refine (CRle_lt_trans _ ('r) _ _ H3).
pose proof (upper_CRapproximation y (exist (Qlt 0) _ qltr)).
apply (@CRle_trans _ _ _ H4).
apply CRle_Qle.
apply (Qle_trans _ ((1 # 2) * (q + r) + (1 # 2) * (r - q))).
apply Qplus_le_l, Qlt_le_weak, q0.
ring_simplify. apply Qle_refl.
- left. apply (CRlt_le_trans _ ('q) _ H0).
pose proof (lower_CRapproximation y (exist (Qlt 0) _ qltr)).
refine (@CRle_trans _ _ _ _ H4). apply CRle_Qle.
apply (Qle_trans _ ((1 # 2) * (q + r) - (1 # 2) * (r - q))).
ring_simplify. apply Qle_refl.
apply Qplus_le_l, q0.
Qed.
Lemma CRle_not_lt (x y: CR): (x <= y)%CR <-> (y < x -> False)%CR.
Proof.
split.
- intros H [q H0].
apply (CRplus_le_compat _ _ _ _ H) in H0.
setoid_replace (y + (x-y))%CR with (x+0) in H0
by (unfold equiv, msp_Equiv; ring).
apply CRplus_le_l in H0.
apply CRle_Qle in H0.
apply (Qle_not_lt _ _ H0 (Qpos_ispos q)).
- intros.
assert (forall z:CR, (0 < z -> False) -> z <= 0) as zero_irrefl.
{ clear H x y. intros z H0. unfold CRltT in H0.
unfold CRle.
apply (@CRnonNeg_wd (-z)). ring.
intro q.
apply Qnot_lt_le. intro abs. apply H0. clear H0.
apply (@CRpos_wd z). ring. simpl in abs.
apply Qlt_minus_iff in abs.
rewrite Qopp_involutive, Qplus_comm in abs.
exists (exist (Qlt 0) _ abs). intro r.
simpl. unfold Cap_raw; simpl.
pose proof (regFun_prf z q ((1#2)*r)%Qpos).
apply AbsSmall_Qabs in H.
apply (Qle_trans _ _ _ (Qle_Qabs _)) in H.
apply (Qplus_le_l _ _ (approximate z q + `r)).
simpl. ring_simplify.
apply (Qplus_le_l _ _ (approximate z ((1#2)*r)%Qpos)) in H.
ring_simplify in H. rewrite (Qplus_comm (`r)).
apply (Qle_trans _ _ _ H).
rewrite <- Qplus_assoc, <- Qplus_assoc.
apply Qplus_le_r. rewrite Qplus_comm.
apply Qplus_le_l. simpl.
rewrite <- (Qmult_1_l (`r)) at 2.
apply Qmult_le_r. apply Qpos_ispos. discriminate. }
assert (0<x-y -> False)%CR.
{ intros [q H0]. apply H. clear H zero_irrefl.
exists q. unfold CRle. unfold CRle in H0.
setoid_replace (x - y - ' 0%Q - ' ` q)%CR
with (x - y - ' ` q) in H0
by (unfold equiv, msp_Equiv; ring).
exact H0. }
apply (CRplus_le_r _ _ (-y)).
rewrite CRplus_opp.
apply zero_irrefl, H0.
Qed.
Lemma CRle_alt : forall (x y : CR),
x <= y <-> forall e:Qpos, (-(2#1)*proj1_sig e <= approximate y e - approximate x e)%Q.
Proof.
split.
- intros.
apply Qnot_lt_le. intro abs.
pose proof (lower_CRapproximation x e).
pose proof (upper_CRapproximation y e).
apply (Qplus_lt_l _ _ (`e + approximate x e)) in abs.
ring_simplify in abs.
setoid_replace (approximate x e + -(1#1) * `e)%Q
with (approximate x e - `e)%Q in abs
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply CRlt_Qlt in abs.
apply (CRle_lt_trans _ _ _ H1) in abs. clear H1.
apply (CRlt_le_trans _ _ _ abs) in H0.
apply CRle_not_lt in H. contradiction. exact H0.
- intros. intro e.
specialize (H ((1#2)*e)%Qpos). simpl in H.
setoid_replace (- (2#1) * ((1 # 2) * ` e))%Q with (-`e)%Q
in H by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply H.
Qed.
Lemma CRnonNeg_le_0 x: CRnonNeg x <-> 0 <= x.
Proof.
unfold CRle.
assert (x - 0 == x)%CR as E by ring.
rewrite E.
intuition.
Qed.
Lemma CRnonNeg_0: CRnonNeg (0)%CR.
Proof.
unfold CRnonNeg. simpl. intros.
apply (Qopp_le_compat 0). apply Qpos_nonneg.
Qed.
#[global]
Hint Immediate CRnonNeg_0.
Definition CRle_lt_dec: forall x y, DN ((x <= y)%CR + (y < x)%CR).
Proof with auto.
intros.
apply (DN_fmap (@DN_decisionT (y < x)%CR)).
intros [A | B]...
left.
apply CRle_not_lt in B. exact B.
Qed.
Definition CRle_dec: forall (x y: CR), DN ((x<=y)%CR + (y<=x)%CR).
Proof with auto.
intros. apply (DN_fmap (CRle_lt_dec x y)).
intros [A | B]...
right.
apply CRlt_le_weak...
Qed.
Lemma approximate_CRminus (x y: CR) (e: QposInf):
approximate (x - y)%CR e =
(approximate x (Qpos2QposInf (1 # 2) * e)%QposInf - approximate y (Qpos2QposInf (1 # 2) * e)%QposInf)%Q.
Proof. destruct e; reflexivity. Qed.
Lemma CRnonNeg_criterion (x: CR): (forall q, (x <= ' q)%CR -> 0 <= q)%Q -> CRnonNeg x.
Proof with auto with qarith.
unfold CRle.
unfold CRnonNeg.
intros.
apply Q.Qplus_le_l with (proj1_sig e).
ring_simplify.
apply H.
intros.
rewrite approximate_CRminus.
simpl.
cut (approximate x ((1 # 2) * e0)%Qpos - approximate x e <= proj1_sig e0 + proj1_sig e)%Q.
- intros.
apply Q.Qplus_le_l with (proj1_sig e0 + approximate x ((1#2)*e0)%Qpos - approximate x e)%Q.
simpl. ring_simplify...
- apply Qle_trans with (Qabs (approximate x ((1 # 2) * e0)%Qpos - approximate x e))%Q.
apply Qle_Qabs.
apply Qle_trans with (proj1_sig ((1#2)*e0)%Qpos + proj1_sig e)%Q...
pose proof (regFun_prf x ((1#2)*e0)%Qpos e).
apply Qball_Qabs in H0...
apply Qplus_le_compat.
simpl.
rewrite <- (Qmult_1_r (proj1_sig e0)) at 2.
rewrite (Qmult_comm (proj1_sig e0)).
apply Qmult_le_compat_r...
apply Qle_refl.
Qed.
(* Similarly, we can derive non-strict inequalities between reals from
non-strict inequalities which approximate it by a rational on one or both sides. *)
Lemma Qle_CRle_r (x y: CR): (forall y', y <= ' y' -> x <= ' y') <-> x <= y.
Proof with auto.
split; intros. 2: apply CRle_trans with y...
apply from_DN.
apply (DN_bind (CRle_lt_dec x y)).
intros [?|W]. apply DN_return...
exfalso.
destruct (CRlt_Qmid _ _ W) as [w [A B]].
pose proof (H w (CRlt_le_weak _ _ A)).
apply (CRle_not_lt x ('w)%CR)...
Qed.
Lemma Qle_CRle_l (x y: CR): (forall x', ' x' <= x -> ' x' <= y) <-> x <= y.
Proof with auto.
intros.
rewrite CRle_opp.
rewrite <- Qle_CRle_r.
split; intros.
rewrite CRle_opp, CRopp_opp, CRopp_Qopp.
apply H.
rewrite CRle_opp, CRopp_Qopp, Qopp_opp...
rewrite CRle_opp, CRopp_Qopp.
apply H.
rewrite CRle_opp, CRopp_Qopp, CRopp_opp, Qopp_opp...
Qed.
Lemma Qle_CRle (x y: CR): (forall x' y', ' x' <= x -> y <= ' y' -> (x' <= y')%Q) <-> x <= y.
Proof with auto.
split; intros.
apply (proj1 (Qle_CRle_l _ _)). intros.
apply (proj1 (Qle_CRle_r _ _)). intros.
apply CRle_Qle...
apply CRle_Qle.
apply CRle_trans with x...
apply CRle_trans with y...
Qed.
Lemma CRnonNegQpos : forall e : Qpos, CRnonNeg (' ` e).
Proof.
intros [e e_pos]; apply CRnonNeg_criterion; simpl.
intros q A; apply Qlt_le_weak, Qlt_le_trans with (y := e); trivial.
now apply CRle_Qle.
Qed.
Lemma scale_0 x: scale 0 x == 0.
Proof. rewrite <- CRmult_scale. ring. Qed.
Lemma scale_CRplus (q: Q) (x y: CR): scale q (x + y) == scale q x + scale q y.
Proof. intros. do 3 rewrite <- CRmult_scale. ring. Qed.
Lemma scale_CRopp (q: Q) (x: CR): scale q (-x) == - scale q x.
Proof. intros. do 2 rewrite <- CRmult_scale. ring. Qed.
(** This returs GT if x is clearly greater than e, returns LT if x
is clearly less than (-e), and returns Eq otherwise. *)
Definition CR_epsilon_sign_dec (e:Qpos) (x:CR) : comparison :=
let z := approximate x e in
match Q.Qle_dec ((2#1) * proj1_sig e) z with
| left p => Gt
| right _ =>
match Q.Qle_dec z (-(2#1) * proj1_sig e)%Q with
| left p => Datatypes.Lt
| right _ => Eq
end
end.
(** This helper lemma reduces a CRpos problem to a sigma type with
a simple equality proposition. *)
Lemma CR_epsilon_sign_dec_pos : forall x,
{e:Qpos | CR_epsilon_sign_dec e x ≡ Gt} -> CRpos x.
Proof.
intros x [e H].
apply (@CRpos_char e).
abstract (unfold CR_epsilon_sign_dec in H; destruct (Q.Qle_dec ((2#1) * proj1_sig e) (approximate x e)) as [A|A];
[assumption | destruct (Q.Qle_dec (approximate x e) (- (2#1) * proj1_sig e)) as [B|B]; discriminate H]).
Defined.
Lemma CR_epsilon_sign_dec_Gt (e:Qpos) (x:CR) :
((2#1) * proj1_sig e <= approximate x e)%Q -> CR_epsilon_sign_dec e x ≡ Gt.
Proof.
intros.
unfold CR_epsilon_sign_dec.
destruct Q.Qle_dec; intuition.
Qed.
(* nasty because approximate is not Proper *)
Lemma CR_epsilon_sign_dec_pos_rev (x : CR) (e : Qpos) :
('proj1_sig e <= x)%CR -> CR_epsilon_sign_dec ((1#4) * e) x ≡ Gt.
Proof.
intros E.
apply CR_epsilon_sign_dec_Gt.
apply Qplus_le_l with (-proj1_sig e)%Q.
simpl ((2#1) * ` ((1 # 4)%Q ↾ eq_refl * e)%Qpos + - ` e)%Q.
setoid_replace ((2#1) * ((1 # 4) * proj1_sig e) + - proj1_sig e)%Q
with (-((1#2) * proj1_sig e))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
replace ((1#4) * e)%Qpos with ((1#2) * ((1#2) * e))%Qpos.
now apply (E ((1#2) * e))%Qpos.
apply Qpos_hprop.
now destruct e as [[[ | | ] ?] ?].
Qed.
Lemma CRbound_distance_from_below
: forall (x : CR) (q : Q) (a b : Qpos),
(approximate x a <= q)%Q -> ('q <= x)%CR
-> (Qabs (approximate x b - q) <= `a + `b)%Q.
Proof.
intros.
assert (x <= 'q + '`a)%CR.
{ apply (CRle_trans (upper_CRapproximation x a)).
rewrite CRplus_Qplus. apply CRle_Qle.
apply Qplus_le_l. exact H. }
apply Qabs_case.
- intros.
pose proof (lower_CRapproximation x b).
apply (Qplus_le_l _ _ (q-`b)).
ring_simplify.
setoid_replace (-(1#1)*`b)%Q with (- ` b)%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply CRle_Qle. apply (CRle_trans H3).
rewrite <- CRplus_Qplus. exact H1.
- intros.
pose proof (upper_CRapproximation x b).
apply (Qplus_le_r _ _ (approximate x b)).
ring_simplify.
rewrite (Qplus_comm (approximate x b)), <- Qplus_assoc.
apply (Qle_trans _ (0 + (approximate x b + `b))).
rewrite Qplus_0_l.
apply CRle_Qle. apply (CRle_trans H0), H3.
apply Qplus_le_l. apply Qpos_nonneg.
Qed.
Lemma CRmult_inv_r_bounded
: forall (x : CR) (q b : Qpos),
(' ` q <= x)%CR
-> (`q < `b)%Q
-> (/ `q <= `b)%Q
-> (forall e:Qpos, approximate x e <= `b)%Q
-> (forall e:Qpos, - `b <= approximate x e)%Q
-> CRmult_bounded b x (CRinv_pos q x) == 1.
Proof.
intros x q b pos qltb invqleb xbelow xabove.
rewrite CRmult_uncurry_eq.
intros e1 e2.
simpl.
apply AbsSmall_Qabs.
assert (forall a c : Q,
0 < c -> Qabs (a*/c-(1#1)) == Qabs (/c) * Qabs (a-c))%Q as absShift.
{ intros. rewrite <- (Qmult_inv_r c).
setoid_replace (a * / c - c * / c)%Q
with ((a-c)*/c)%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
rewrite Qabs_Qmult. apply Qmult_comm. intro abs. rewrite abs in H.
exact (Qlt_irrefl 0 H). }
assert (forall i j : Q, i<=j -> Qmax i j == j)%Q as elim_max.
{ intros. apply (Qle_max_r i j), H. }
assert (forall i j : Q, j<=i -> Qmin i j == j)%Q as elim_min.
{ intros. apply (Qle_min_r i j), H. }
assert (QboundAbs b (/ Qmax (` q) (approximate x (Qinv_modulus q ((1 # 2) ↾ eq_refl * e1 * Qpos_inv b))))
== / Qmax (` q) (approximate x (Qinv_modulus q ((1 # 2) ↾ eq_refl * e1 * Qpos_inv b))))%Q.
{ simpl.
rewrite elim_max.
apply Qle_min_r. apply (Qle_trans _ (/`q)).
2: exact invqleb. apply Qle_shift_inv_l.
apply Qpos_ispos. rewrite Qmult_comm.
apply Qle_shift_div_r.
apply (Qlt_le_trans _ (`q)). apply Qpos_ispos.
apply Qmax_ub_l. rewrite Qmult_1_l. apply Qmax_ub_l.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
apply Qmin_glb. apply Qpos_nonneg.
apply Qlt_le_weak, Qinv_lt_0_compat.
apply (Qlt_le_trans _ (`q)). apply Qpos_ispos.
apply Qmax_ub_l. }
simpl in H. rewrite H, absShift. clear absShift H.
rewrite Qabs_pos.
rewrite Qmult_comm. apply Qle_shift_div_r.
apply (Qlt_le_trans _ (`q)). apply Qpos_ispos.
apply Qmax_ub_l.
apply (Qle_trans _ ((1#2)*`e1 * `q + (1#2)*`e1 * `q)).
assert (((1 # 2) * ` e1 * / ` b + ` q * ` q * ((1 # 2) * ` e1 * / ` b) <=
(1 # 2) * ` e1 * ` q + (1 # 2) * ` e1 * ` q))%Q as dist_ok.
{ apply Qplus_le_compat.
- apply Qmult_le_l. apply (Qpos_ispos ((1#2)*e1)).
apply Qle_shift_inv_r. apply Qpos_ispos.
rewrite <- (Qmult_inv_r (`q)).
apply Qmult_le_l. apply Qpos_ispos. exact invqleb.
apply Qpos_nonzero.
- rewrite <- Qmult_assoc, (Qmult_comm (`q)).
apply Qmult_le_r. apply Qpos_ispos.
rewrite Qmult_assoc.
apply (Qle_shift_div_r _ (`b)). apply Qpos_ispos.
rewrite Qmult_comm. apply Qmult_le_l.
apply (Qpos_ispos ((1#2)*e1)). apply Qlt_le_weak, qltb. }
apply (Qmax_case (`q)).
- unfold Qinv_modulus. intros.
unfold Qmult_modulus.
assert (QboundAbs b (` q) == `q)%Q as H1.
{ simpl. transitivity (Qmin (`b) (`q)). apply Qle_max_r.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
apply Qmin_glb. apply Qpos_nonneg.
apply Qpos_nonneg.
apply Qle_min_r. apply Qlt_le_weak, qltb. }
rewrite <- H1 at 1. clear H1.
apply (Qle_trans _ (Qabs
(approximate x ((1 # 2)%Q ↾ eq_refl * e1 * Qpos_inv b)%Qpos - (` q)))).
apply QboundAbs_contract.
apply (Qle_trans _ ((`q * `q * ((1 # 2) * `e1 * / `b))
+ (1 # 2) * `e1 * / `b )).
apply (CRbound_distance_from_below
x (`q)
(q * q * ((1 # 2)%Q ↾ eq_refl * e1 * Qpos_inv b))%Qpos
((1 # 2) * e1 * Qpos_inv b)%Qpos).
2: exact pos.
exact H. rewrite Qplus_comm. exact dist_ok.
- unfold Qinv_modulus. intros.
unfold Qmult_modulus.
rewrite elim_min.
rewrite elim_max.
pose proof (regFun_prf x ((1 # 2)%Q ↾ eq_refl * e1 * Qpos_inv b)%Qpos
(q * q * ((1 # 2)%Q ↾ eq_refl * e1 * Qpos_inv b))%Qpos)
as H1.
apply AbsSmall_Qabs in H1.
apply (Qle_trans _ _ _ H1). clear H1. exact dist_ok.
apply xabove. apply xbelow.
- rewrite <- Qmult_plus_distr_l.
rewrite <- Qmult_plus_distr_l.
setoid_replace ((1 # 2) + (1 # 2))%Q with (1#1)%Q by reflexivity.
rewrite Qmult_1_l.
apply (Qle_trans _ ((`e1+`e2)*`q)).
rewrite <- Qplus_0_r, Qmult_plus_distr_l.
apply Qplus_le_r. apply (Qpos_nonneg (e2*q)).
rewrite Qplus_0_r.
apply Qmult_le_l. apply (Qpos_ispos (e1+e2)).
apply Qmax_ub_l.
- apply Qlt_le_weak, Qinv_lt_0_compat.
apply (Qlt_le_trans _ (`q)). apply Qpos_ispos.
apply Qmax_ub_l.
- apply (Qlt_le_trans _ (`q)). apply Qpos_ispos.
apply Qmax_ub_l.
- intro e. simpl. unfold Cap_raw. simpl.
apply (Qle_trans _ 0).
apply (Qopp_le_compat 0), Qpos_nonneg.
rewrite <- Qle_minus_iff. apply xabove.
- intro e. simpl. unfold Cap_raw. simpl.
apply (Qle_trans _ 0).
apply (Qopp_le_compat 0), Qpos_nonneg.
rewrite <- Qle_minus_iff. apply xbelow.
Qed.
Lemma CRmult_inv_r_pos : forall (x : CR) (xnz : (x >< 0)%CR),
(0 < x)%CR -> (x * CRinvT x xnz == 1).
Proof.
intros. destruct xnz.
exfalso. exact (CRlt_irrefl x (CRlt_trans _ _ _ c H)).
destruct c as [q pos]. unfold CRinvT.
rewrite CRopp_0, CRplus_0_r in pos.
pose (Qpos_max (Qpos_inv q) (CR_b (1#1) x + (1#1))) as b.
assert (' (- ` b)%Q <= x) as xlower.
{ apply (@CRle_trans _ (' (-proj1_sig (CR_b (1#1) x))%Q)).
2: apply (CR_b_lowerBound _ _).
apply CRle_Qle. apply Qopp_le_compat.
apply (Qle_trans _ (proj1_sig (CR_b (1#1)%Qpos x) + (1#1))).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
apply (Qpos_max_ub_r (Qpos_inv q) (CR_b (1#1) x + (1#1))). }
assert (x <= '(` b)%Q) as xupper.
{ apply (@CRle_trans _ (' (proj1_sig (CR_b (1#1) x))) _ (CR_b_upperBound _ _)).
apply CRle_Qle.
apply (Qle_trans _ (proj1_sig (CR_b (1#1)%Qpos x) + (1#1))).
rewrite <- Qplus_0_r at 1. apply Qplus_le_r. discriminate.
apply (Qpos_max_ub_r (Qpos_inv q) (CR_b (1#1) x + (1#1))). }
rewrite <- (CRboundAbs_Eq _ xlower xupper).
assert (`q < `b)%Q as qltb.
{ apply Qlt_from_CRlt. apply (CRle_lt_trans _ _ _ pos).
apply (CRle_lt_trans _ _ _ (CR_b_upperBound (1#1) x)).
apply CRlt_Qlt. unfold b.
apply (Qlt_le_trans _ (proj1_sig (CR_b (1#1) x + (1#1))%Qpos)).
rewrite <- Qplus_0_r. apply Qplus_lt_r. reflexivity.
apply Qpos_max_ub_r. }
assert (/`q <= `b)%Q as invqleb.
{ apply (Qpos_max_ub_l (Qpos_inv q) (CR_b (1#1) x + (1#1))). }
rewrite <- (CRmult_bounded_mult b).
apply (CRmult_inv_r_bounded (CRboundAbs b x) q b).
- rewrite (CRboundAbs_Eq _ xlower xupper). exact pos.
- exact qltb.
- exact invqleb.
- intros. simpl. apply Qmax_lub.
apply (Qle_trans _ 0).
apply (Qopp_le_compat 0), Qpos_nonneg.
apply Qpos_nonneg. apply Qmin_lb_l.
- intros. simpl. apply Qmax_ub_l.
- rewrite (CRboundAbs_Eq _ xlower xupper).
intro e. simpl. unfold Cap_raw. simpl.
rewrite Qopp_involutive.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
apply (Qle_trans _ (/ Qmax (` q) (approximate x (Qinv_modulus q ((1 # 2) ↾ eq_refl * e))) + 0)).
rewrite Qplus_0_r.
apply Qlt_le_weak, Qinv_lt_0_compat.
apply (Qlt_le_trans _ (`q)). apply Qpos_ispos.
apply Qmax_ub_l. apply Qplus_le_r. apply Qpos_nonneg.
- rewrite (CRboundAbs_Eq _ xlower xupper).
intro e. simpl. unfold Cap_raw. simpl.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
rewrite <- Qle_minus_iff.
apply (Qle_trans _ (/ `q)).
2: apply (Qpos_max_ub_l (Qpos_inv q) (CR_b (1#1) x + (1#1))).
apply Qle_shift_inv_r.
apply (Qlt_le_trans _ (`q)). apply Qpos_ispos.
apply Qmax_ub_l.
rewrite Qmult_comm. apply Qle_shift_div_l.
apply Qpos_ispos. rewrite Qmult_1_l.
apply Qmax_ub_l.
Qed.
Lemma CRmult_inv_r : forall (x : CR) (xnz : (x >< 0)%CR),
x * CRinvT x xnz == 1.
Proof.
intros. destruct xnz as [neg|pos].
- pose proof neg as otherNeg.
destruct neg as [q neg]. unfold CRinvT.
setoid_replace (x * - CRinv_pos q (- x))%CR
with (-x * CRinv_pos q (- x))%CR
by (unfold equiv, msp_Equiv; ring).
apply CRopp_lt_compat in otherNeg.
apply (CRltT_wd CRopp_0 (reflexivity _)) in otherNeg.
pose proof (CRmult_inv_r_pos (-x)%CR (inr otherNeg) otherNeg).
pose proof (CRinvT_pos_inv q (inr otherNeg)).
destruct otherNeg as [r H1]. unfold CRinvT in H.
unfold CRinvT in H0.
rewrite H0. exact H. rewrite CRplus_0_l in neg. exact neg.
- apply CRmult_inv_r_pos, pos.
Qed.
(* Type class versions of a lot of the above *)
Close Scope CR_scope.
Local Opaque CR.
#[global]
Instance: Ring CR.
Proof. apply (rings.from_stdlib_ring_theory CR_ring_theory). Qed.
(* We need the (1#4) because CR_epsilon_sign_dec_pos_rev is nasty *)
#[global]
Instance CRlt: Lt CR := λ x y,
∃ n : nat, CR_epsilon_sign_dec ((1#4) * Qpos_power (2#1) (-cast nat Z n)) (y - x) ≡ Gt.
Lemma CR_lt_ltT x y : prod (x < y -> CRltT x y)
(CRltT x y -> x < y).
Proof.
split.
intros E.
apply CR_epsilon_sign_dec_pos.
apply constructive_indefinite_description_nat in E.
destruct E as [n En].
now exists ((1#4) * Qpos_power (2#1) (-cast nat Z n))%Qpos.
intros. now apply comparison_eq_dec.
intros [ε Eε].
exists (Z.nat_of_Z (-Qdlog2 ('ε))).
apply CR_epsilon_sign_dec_pos_rev.
apply CRle_trans with ('proj1_sig ε); auto.
apply CRle_Qle. simpl.
destruct (decide (proj1_sig ε ≤ 1)).
rewrite Z.nat_of_Z_nonneg.
rewrite Z.opp_involutive.
apply Qdlog2_spec.
now destruct ε.
apply Z.opp_nonneg_nonpos.
now apply Qdlog2_nonpos.
rewrite Z.nat_of_Z_nonpos.
now apply Qlt_le_weak, Qnot_le_lt.
apply Z.opp_nonpos_nonneg.
apply Qdlog2_nonneg.
now apply Qlt_le_weak, Qnot_le_lt.
Qed.
#[global]
Instance CRapart: Apart CR := λ x y, x < y ∨ y < x.
Lemma CR_apart_apartT x y : prod (x ≶ y -> CRapartT x y)
(CRapartT x y -> x ≶ y).
Proof.
split.
intros E.
set (f (n : nat) := CR_epsilon_sign_dec ((1#4) * Qpos_power (2#1) (-cast nat Z n))).
assert (∃ n, f n (y - x) ≡ Gt ∨ f n (x - y) ≡ Gt) as E2.
now destruct E as [[n En] | [n En]]; exists n; [left | right].
apply constructive_indefinite_description_nat in E2.
destruct E2 as [n E2].
destruct (comparison_eq_dec (f n (y - x)) Gt) as [En|En].
left. apply CR_epsilon_sign_dec_pos.
now exists ((1#4) * Qpos_power (2#1) (-cast nat Z n))%Qpos.
right. apply CR_epsilon_sign_dec_pos.
exists ((1#4) * Qpos_power (2#1) (-cast nat Z n))%Qpos.
destruct E2; tauto.
intros n.
destruct (comparison_eq_dec (f n (y - x)) Gt); auto.
destruct (comparison_eq_dec (f n (x - y)) Gt); tauto.
intros [E|E].
left. now apply CR_lt_ltT.
right. now apply CR_lt_ltT.
Qed.
Lemma CReq_not_apart : forall x y : CR,
(x == y)%CR <-> (CRapartT x y -> False).
Proof.
split.
- intros. destruct H0.
revert c. apply CRle_not_lt.
rewrite H. apply CRle_refl.
revert c. apply CRle_not_lt.
rewrite H. apply CRle_refl.
- intros. apply CRle_antisym. split.
apply CRle_not_lt. intro abs.
contradict H. right. exact abs.
apply CRle_not_lt. intro abs.
contradict H. left. exact abs.
Qed.
#[global]
Instance: StrongSetoid CR.
Proof.
split.
- intros x E.
destruct E; apply CR_lt_ltT in H; exact (CRlt_irrefl x H).
- intros x y E.
destruct E. right. exact H. left. exact H.
- intros x y E z. destruct E. apply CR_lt_ltT in H.
apply (@CRlt_linear x z y) in H. destruct H.
left. left. apply CR_lt_ltT. exact c. right. left.
apply CR_lt_ltT. exact c. apply CR_lt_ltT in H.
apply (@CRlt_linear _ z) in H. destruct H.
right. right. apply CR_lt_ltT.
exact c. left. right. apply CR_lt_ltT. exact c.
- split.
+ intros. apply CRle_antisym. split.
apply CRle_not_lt. intro abs. apply H. right.
apply CR_lt_ltT. exact abs.
apply CRle_not_lt. intro abs. apply H. left.
apply CR_lt_ltT. exact abs.
+ intros H abs. destruct abs.
apply CR_lt_ltT in H0.
pose proof (@CRltT_wd _ _ H y y (reflexivity _) H0).
exact (CRlt_irrefl y H1).
apply CR_lt_ltT in H0. symmetry in H.
pose proof (@CRltT_wd _ _ H x x (reflexivity _) H0).
exact (CRlt_irrefl x H1).
Qed.
Lemma CRle_scale : forall (a b : CR) (q : Qpos),
(a <= b)%CR <-> (scale (`q) a <= scale (`q) b)%CR.
Proof.
assert (forall (a b:CR) (q:Qpos), (a <= b)%CR -> (scale (`q) a <= scale (`q) b)%CR).
{ intros. intro e. simpl.
unfold Cap_raw; simpl.
unfold Qscale_modulus. destruct q, x, Qnum. simpl.
- exfalso; inversion q.
- simpl.
rewrite CRle_alt in H.
specialize (H ((Qden # p) * ((1#2)*e))%Qpos).
simpl in H.
setoid_replace (- (2#1) * ((Zpos Qden # p) * ((1 # 2) * ` e)))%Q
with (-`e * (Zpos Qden#p))%Q in H
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply Qle_shift_div_l in H. 2: reflexivity.
apply (Qle_trans _ _ _ H). clear H.
unfold Qdiv.
setoid_replace (/ (Zpos Qden # p)) with (Zpos p # Qden) by reflexivity.
rewrite Qmult_comm. unfold Qminus.
rewrite Qmult_plus_distr_r. apply Qplus_le_r.
ring_simplify. apply Qle_refl.
- exfalso. inversion q. }
split. intros. apply H, H0.
intros. apply (H _ _ (Qpos_inv q)) in H0.
setoid_replace (scale (` (Qpos_inv q)) (scale (` q) a)) with a in H0.
setoid_replace (scale (` (Qpos_inv q)) (scale (` q) b)) with b in H0.
exact H0.
- rewrite <- CRmult_scale, <- CRmult_scale.
rewrite <- CRmult_assoc. rewrite CRmult_Qmult.
setoid_replace (` (Qpos_inv q) * ` q)%Q with 1%Q.
apply CRmult_1_l. simpl.
rewrite Qmult_comm, Qmult_inv_r. reflexivity. apply Qpos_nonzero.
- rewrite <- CRmult_scale, <- CRmult_scale.
rewrite <- CRmult_assoc. rewrite CRmult_Qmult.
setoid_replace (` (Qpos_inv q) * ` q)%Q with 1%Q.
apply CRmult_1_l. simpl.
rewrite Qmult_comm, Qmult_inv_r. reflexivity. apply Qpos_nonzero.
Qed.
Lemma QboundAbs_mult : forall (a b : Q) (c : Qpos),
-(`c*`c) <= QboundAbs c a * QboundAbs c b.
Proof.
intros. destruct (Qlt_le_dec 0 a).
- assert (-`c <= QboundAbs c b) by apply Qmax_ub_l.
apply (Qmult_le_compat_r _ _ (QboundAbs c a)) in H.
rewrite (Qmult_comm (QboundAbs c b)) in H.
refine (Qle_trans _ _ _ _ H).
setoid_replace (- ` c * QboundAbs c a)%Q
with (-(` c * QboundAbs c a))%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply Qopp_le_compat. apply Qmult_le_l. apply Qpos_ispos.
apply Qmax_lub. apply (Qle_trans _ 0).
apply (Qopp_le_compat 0), Qpos_nonneg. apply Qpos_nonneg.
apply Qmin_lb_l.
apply (Qle_trans _ (Qmin (`c) a)).
apply Qmin_glb. apply Qpos_nonneg. apply Qlt_le_weak, q.
apply Qmax_ub_r.
- rewrite <- (Qopp_involutive (QboundAbs c a * QboundAbs c b)).
apply Qopp_le_compat.
assert (QboundAbs c b <= `c)%Q.
{ apply Qmax_lub. apply (Qle_trans _ 0).
apply (Qopp_le_compat 0), Qpos_nonneg. apply Qpos_nonneg.
apply Qmin_lb_l. }
apply (Qmult_le_compat_r _ _ (-QboundAbs c a)) in H.
rewrite Qmult_comm in H.
setoid_replace (-(QboundAbs c a * QboundAbs c b))%Q
with (- QboundAbs c a * QboundAbs c b)%Q
by (unfold equiv, stdlib_rationals.Q_eq; ring).
apply (Qle_trans _ _ _ H).
apply Qmult_le_l. apply Qpos_ispos.
rewrite <- (Qopp_involutive (`c)).
apply Qopp_le_compat. apply Qmax_ub_l.
apply (Qopp_le_compat _ 0).
apply Qmax_lub. apply (Qopp_le_compat 0), Qpos_nonneg.
apply (Qle_trans _ a). apply Qmin_lb_r. exact q.
Qed.
Lemma CRmult_le_0_compat_bounded
: forall (a b : CR) (c : Qpos),
CRnonNeg b
-> CRnonNeg a
-> (forall e:Qpos, -`c <= approximate a e)
-> (forall e:Qpos, approximate a e <= `c)
-> (forall e:Qpos, -`c <= approximate b e)
-> (forall e:Qpos, approximate b e <= `c)
-> (0 <= CRmult_bounded c a b)%CR.
Proof.
intros a b c H0 H alower aupper blower bupper.
rewrite CRmult_uncurry_eq.
intro e.
simpl. unfold Cap_raw;simpl.
rewrite Qplus_0_r. unfold Qmult_modulus.
destruct (Qlt_le_dec (`c*`c) (`e)).
apply (Qle_trans _ (-(`c*`c))).
apply Qopp_le_compat, Qlt_le_weak, q.
apply QboundAbs_mult.
specialize (H ((1 # 2) * ((1 # 2) * e) * Qpos_inv c)%Qpos).
specialize (H0 ((1 # 2) * ((1 # 2) * e) * Qpos_inv c)%Qpos).
apply Qle_minus_iff in H. rewrite Qopp_involutive in H.
apply Qle_minus_iff in H0. rewrite Qopp_involutive in H0.
apply (Qmult_le_0_compat _ _ H) in H0. clear H.
rewrite Qmult_plus_distr_r in H0.
rewrite Qmult_plus_distr_l, Qmult_plus_distr_l in H0.
assert (forall i j k l:Q, 0 <= i + j + (k + l) -> -(j+k+l) <= i).
{ intros. apply (Qplus_le_r _ _ (j+k+l)).
ring_simplify.
rewrite <- Qplus_assoc, (Qplus_comm i) in H.
rewrite Qplus_assoc in H. exact H. }
apply H in H0. clear H.
simpl in H0.
assert (forall i j : Q, i<=j -> Qmax i j == j)%Q as elim_max.
{ intros. apply (Qle_max_r i j), H. }
assert (forall i j : Q, j<=i -> Qmin i j == j)%Q as elim_min.
{ intros. apply (Qle_min_r i j), H. }
rewrite elim_min, elim_min, elim_max, elim_max.
refine (Qle_trans _ _ _ _ H0).
apply Qopp_le_compat.
apply (Qle_trans _ ((1#3)*`e + (1#3)*`e + (1#3)*`e)).
2: ring_simplify; apply Qle_refl.
apply Qplus_le_compat. apply Qplus_le_compat.
- apply (Qle_trans _ _ _ (Qle_Qabs _)).
rewrite Qabs_Qmult.
rewrite Qmult_comm.
apply (Qle_trans _ (`c * Qabs ((1 # 2) * ((1 # 2) * ` e) * / ` c))).
apply Qmult_le_compat_r. 2: apply Qabs_nonneg.
pose proof (QboundAbs_abs c (approximate b
((1 # 2) * ((1 # 2) * e) * Qpos_inv c)%Qpos)) as H.
simpl in H. rewrite elim_min, elim_max in H. rewrite H. clear H.
apply Qmin_lb_r.
apply blower. apply bupper.
rewrite Qmult_comm, Qabs_pos, <- Qmult_assoc.
rewrite (Qmult_comm (/`c)), Qmult_inv_r, Qmult_1_r.
2: apply Qpos_nonzero. rewrite Qmult_assoc.
apply Qmult_le_r. apply Qpos_ispos. discriminate.
apply Qmult_le_0_compat.
apply Qmult_le_0_compat. discriminate.
apply Qmult_le_0_compat. discriminate.
apply Qpos_nonneg. apply Qlt_le_weak, Qinv_lt_0_compat, Qpos_ispos.
- apply (Qle_trans _ _ _ (Qle_Qabs _)).
rewrite Qabs_Qmult.
apply (Qle_trans _ (`c * Qabs ((1 # 2) * ((1 # 2) * ` e) * / ` c))).
apply Qmult_le_compat_r. 2: apply Qabs_nonneg.
pose proof (QboundAbs_abs c (approximate a
((1 # 2) * ((1 # 2) * e) * Qpos_inv c)%Qpos)).
simpl in H. rewrite elim_min, elim_max in H.
rewrite H. clear H.
apply Qmin_lb_r. apply alower. apply aupper.
rewrite Qmult_comm, Qabs_pos, <- Qmult_assoc.
rewrite (Qmult_comm (/`c)), Qmult_inv_r, Qmult_1_r.
2: apply Qpos_nonzero. rewrite Qmult_assoc.
apply Qmult_le_r. apply Qpos_ispos. discriminate.
apply Qmult_le_0_compat.
apply Qmult_le_0_compat. discriminate.
apply Qmult_le_0_compat. discriminate.
apply Qpos_nonneg. apply Qlt_le_weak, Qinv_lt_0_compat, Qpos_ispos.
- apply (Qle_trans _ ((1#16)*(`e*/`c*/`c)*`e)).
ring_simplify. apply Qle_refl. apply Qmult_le_r.
apply Qpos_ispos. apply (Qle_trans _ ((1#16)*(1#1))).
2: discriminate.
apply Qmult_le_l. reflexivity. apply Qle_shift_div_r.
apply Qpos_ispos. apply Qle_shift_div_r. apply Qpos_ispos.
rewrite Qmult_1_l. exact q.
- apply blower.
- apply alower.
- apply bupper.
- apply aupper.
- intro e. simpl. unfold Cap_raw. simpl.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
rewrite <- Qle_minus_iff. apply alower.
- intro e. simpl. unfold Cap_raw. simpl.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
rewrite <- Qle_minus_iff. apply aupper.
Qed.
Lemma CRmult_le_0_compat : forall a b : CR,
(0 <= a)%CR -> (0 <= b)%CR -> (0 <= a*b)%CR.
Proof.
intros.
pose (Qpos_max (CR_b (1#1) a) (CR_b (1#1) b)) as c.
assert (' (- ` c)%Q <= a)%CR as alower.
{ apply (@CRle_trans _ (' (-proj1_sig (CR_b (1#1) a))%Q)).
2: apply (CR_b_lowerBound _ _).
apply CRle_Qle. apply Qopp_le_compat, Qpos_max_ub_l. }
assert (a <= '(` c)%Q)%CR as aupper.
{ apply (@CRle_trans _ (' (proj1_sig (CR_b (1#1) a))) _ (CR_b_upperBound _ _)).
apply CRle_Qle. apply Qpos_max_ub_l. }
assert (' (- ` c)%Q <= b)%CR as blower.
{ apply (@CRle_trans _ (' (-proj1_sig (CR_b (1#1) b))%Q)).
2: apply (CR_b_lowerBound _ _).
apply CRle_Qle. apply Qopp_le_compat, Qpos_max_ub_r. }
assert (b <= '(` c)%Q)%CR as bupper.
{ apply (@CRle_trans _ (' (proj1_sig (CR_b (1#1) b))) _ (CR_b_upperBound _ _)).
apply CRle_Qle. apply Qpos_max_ub_r. }
unfold CRle in H0.
rewrite CRopp_0, CRplus_0_r in H0.
unfold CRle in H.
rewrite CRopp_0, CRplus_0_r in H.
rewrite <- (@CRboundAbs_Eq c a) in H.
2: exact alower. 2: exact aupper.
rewrite <- (@CRboundAbs_Eq c b) in H0.
2: exact blower. 2: exact bupper.
rewrite <- (CRmult_bounded_mult c).
2: exact blower. 2: exact bupper.
change (0 <= ucFun2 (CRmult_bounded c) a b)%CR.
rewrite <- (@CRboundAbs_Eq c a).
rewrite <- (@CRboundAbs_Eq c b).
apply (CRmult_le_0_compat_bounded
(CRboundAbs c a) (CRboundAbs c b) c).
- exact H0.
- exact H.
- intros. apply Qmax_ub_l.
- intros. simpl. apply Qmax_lub.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
apply Qpos_nonneg. apply Qmin_lb_l.
- intros. apply Qmax_ub_l.
- intros. simpl. apply Qmax_lub.
apply (Qle_trans _ 0). apply (Qopp_le_compat 0), Qpos_nonneg.
apply Qpos_nonneg. apply Qmin_lb_l.
- exact blower.
- exact bupper.
- exact alower.
- exact aupper.
Qed.
Lemma CRmult_lt_0_compat : forall a b : CR,
(0 < a)%CR -> (0 < b)%CR -> (0 < a*b)%CR.
Proof.
intros a b [q H] [r H0]. exists (q*r).
rewrite CRopp_0, CRplus_0_r.
rewrite CRopp_0, CRplus_0_r in H.
rewrite CRopp_0, CRplus_0_r in H0.
pose proof (CRle_scale ('`r) b q) as [H1 _].
specialize (H1 H0).
rewrite <- CRmult_scale in H1.
rewrite CRmult_Qmult in H1.
apply (CRle_trans H1).
apply (CRplus_le_r _ _ (-scale (`q) b)%CR).
rewrite CRplus_opp.
rewrite <- CRmult_scale.
setoid_replace (a * b - ' ` q * b)%CR with ((a-'`q)*b)%CR
by (unfold equiv, msp_Equiv; ring).
apply CRmult_le_0_compat.
apply (CRplus_le_l _ _ ('`q)%CR). ring_simplify. exact H.
apply (@CRle_trans _ ('`r)%CR).
apply CRle_Qle. apply Qpos_nonneg. exact H0.
Qed.
Lemma CRmult_lt_r : forall (x y z: CR),
(0 < z)%CR -> prod (x < y -> x*z < y*z)%CR
(x*z < y*z -> x < y)%CR.
Proof.
assert (forall (x y z: CR), (0 < z)%CR -> (x < y -> x*z < y*z)%CR).
{ intros.
pose proof (@CRplus_lt_r x y (-x)%CR) as [H1 _].
apply H1 in H0. clear H1.
apply (CRltT_wd (CRplus_opp x) (reflexivity (y-x)%CR)) in H0.
apply (CRmult_lt_0_compat _ _ H) in H0.
pose proof (@CRplus_lt_r 0%CR (z*(y-x))%CR (x*z)%CR) as [H1 _].
apply H1 in H0. clear H1.
assert (z*(y-x)+x*z == y*z)%CR by ring.
pose proof (CRltT_wd (CRplus_0_l (x*z)%CR) H1).
apply H2 in H0. exact H0. }
split. apply X, H.
intros. (* Divide by z in H0. *)
pose proof (CRinv_0_lt_compat _ (inr H) H).
specialize (X (x*z)%CR (y*z)%CR _ H1 H0).
assert (x * z * CRinvT z (inr H) == x)%CR.
{ rewrite CRmult_assoc, CRmult_inv_r. apply CRmult_1_r. }
assert (y * z * CRinvT z (inr H) == y)%CR.
{ rewrite CRmult_assoc, CRmult_inv_r. apply CRmult_1_r. }
apply (CRltT_wd H2 H3) in X. exact X.
Qed.
Lemma CRmult_lt_l (x y z: CR):
(0 < z)%CR -> prod (x < y -> z*x < z*y)%CR
(z*x < z*y -> x < y)%CR.
Proof.
split.
- intros.
apply (CRltT_wd (CRmult_comm x z) (CRmult_comm y z)).
pose proof (CRmult_lt_r x y z H) as [H1 _].
apply H1, H0.
- intros.
pose proof (CRmult_lt_r x y z H) as [_ H1].
apply H1. clear H1.
apply (CRltT_wd (CRmult_comm z x) (CRmult_comm z y)).
apply H0.
Qed.
Lemma CRmult_le_compat_l : forall (x y z: CR),
(0 <= z -> x <= y -> z*x <= z*y)%CR.
Proof.
intros. pose proof (@CRplus_le_r x y (-x)%CR) as [H1 _].
specialize (H1 H0). rewrite CRplus_opp in H1.
apply (CRmult_le_0_compat _ _ H) in H1.
pose proof (@CRplus_le_l 0%CR (z*(y-x))%CR (x*z)%CR) as [H2 _].
specialize (H2 H1). ring_simplify in H2.
rewrite CRmult_comm in H2. exact H2.
Qed.
Lemma CRmult_lt_0_weaken
: forall (x y : CR),
(0 < x * y -> 0 <= y -> 0 < x)%CR.
Proof.
intros.
pose proof (CRlt_Qlt 0 1 eq_refl) as zeroLtOne.
destruct (CRlt_linear 0%CR x 1%CR zeroLtOne) as [H3|H3].
- exact H3.
- clear zeroLtOne.
(* Prove that x*y <= y, then 0 < y and then 0 < x. *)
apply CRlt_le_weak in H3.
pose proof (CRmult_le_compat_l x 1%CR y H0 H3) as H1.
rewrite CRmult_1_r in H1.
rewrite CRmult_comm in H1.
apply (@CRlt_le_trans 0%CR (x*y) y H) in H1.
assert (0 == 0*y)%CR by ring.
apply (CRltT_wd H2 (reflexivity _)) in H. clear H2.
apply (CRmult_lt_r 0%CR x y). exact H1. exact H.
Qed.
Lemma CRmult_lt_0_cancel_l : forall a b : CR,
(0 < a*b)%CR -> prod (a≶0) (b≶0).
Proof.
pose proof (CRlt_Qlt 0 1 eq_refl).
intros.
destruct (CRlt_linear _ a _ H) as [H1|H1].
- split. right. apply CR_lt_ltT, H1.
(* Divide by a *)
right.
pose proof (CRinv_0_lt_compat _ (inr H1) H1).
pose proof (CRmult_lt_l 0%CR (a*b)%CR _ H2) as [H3 _].
apply H3 in H0. clear H3 H2.
assert (CRinvT a (inr H1) * (a * b) == b)%CR.
rewrite <- CRmult_assoc. rewrite <- (CRmult_comm a), CRmult_inv_r.
apply CRmult_1_l.
assert (CRinvT a (inr H1) * 0 == 0)%CR by ring.
apply (CRltT_wd H3 H2) in H0. apply CR_lt_ltT, H0.
- destruct (CRlt_linear _ b _ H0) as [H2|H2].
+ split. 2: right; apply CR_lt_ltT, H2. right.
pose proof (CRmult_lt_r 0%CR a b H2) as [_ H3].
apply CR_lt_ltT, H3.
assert (0 == 0 * b)%CR by ring.
apply (CRltT_wd H4 (reflexivity _)), H0.
+ (* Both a and b are negative *)
assert (a*b == (-a)*(-b))%CR by ring.
apply (CRltT_wd (reflexivity 0%CR) H3) in H0. clear H3.
assert (0 <= -b)%CR.
{ apply (CRplus_le_l _ _ b). rewrite CRplus_opp, CRplus_0_r.
apply CRle_not_lt. intro abs.
pose proof (CRmult_lt_r 1 a b abs)%CR as [_ H3].
apply (CRlt_irrefl a).
apply (CRlt_trans _ _ _ H1), H3.
assert (b == 1 * b)%CR by ring.
apply (CRltT_wd H4 (reflexivity _)), H2. }
pose proof (CRmult_lt_0_weaken _ _ H0 H3).
split; left.
apply CR_lt_ltT, (CRopp_lt_cancel a 0%CR).
pose proof CRopp_0. symmetry in H5.
apply (CRltT_wd H5 (reflexivity _)), H4.
pose proof (@CRplus_lt_r b 0%CR (-b)%CR) as [_ H5].
apply CR_lt_ltT, H5. clear H5.
assert (-b == 0-b)%CR by ring.
pose proof (CRplus_opp b). symmetry in H6.
apply (CRltT_wd H6 H5). clear H6 H5.
pose proof (CRmult_lt_l 0 (-b) (-a) H4)%CR as [_ H5].
apply H5. clear H5.
assert (0 == (-a) * 0)%CR by ring.
apply (CRltT_wd H5 (reflexivity _)), H0.
Qed.
Lemma CRmult_lt_cancel_l : forall a b c : CR,
(a*b < a*c)%CR -> (prod (a≶0) (b≶c)).
Proof.
intros.
pose proof (CRplus_lt_l (a*b) (a*c) (-a*b))%CR as [H0 _].
specialize (H0 H).
assert (- a * b + a * b == 0)%CR by ring.
assert (- a * b + a * c == a*(c-b))%CR by ring.
apply (CRltT_wd H1 H2) in H0. clear H1 H2.
apply CRmult_lt_0_cancel_l in H0. destruct H0.
split. exact a0. destruct a1.
- right. apply CR_lt_ltT in H0.
pose proof (CRplus_lt_l (c-b) (0) b)%CR as [H1 _].
specialize (H1 H0).
assert (b + (c - b) == c)%CR by ring.
assert (b + 0 == b)%CR by ring.
apply (CRltT_wd H2 H3) in H1. apply CR_lt_ltT, H1.
- left. apply CR_lt_ltT in H0.
pose proof (CRplus_lt_l 0 (c-b) b)%CR as [H1 _].
specialize (H1 H0).
assert (b + (c - b) == c)%CR by ring.
assert (b + 0 == b)%CR by ring.
apply (CRltT_wd H3 H2) in H1. apply CR_lt_ltT, H1.
Qed.
Lemma CRmult_le_0_reg_l : forall a b : CR,
~((0 < a)%CR -> False) -> (0 <= a * b)%CR -> (0 <= b)%CR.
Proof.
intros.
apply CRle_not_lt. intro abs.
contradict H; intro H.
rewrite <- CRopp_0 in H0.
setoid_replace (a*b)%CR with (-(a*-b))%CR in H0
by (unfold equiv, msp_Equiv; ring).
apply CRopp_le_cancel in H0.
pose proof (CRle_not_lt (a*-b)%CR 0%CR) as [H1 _].
specialize (H1 H0). contradict H1. clear H0.
apply CRmult_lt_0_compat.
exact H.
apply (CRltT_wd CRopp_0 (reflexivity _)).
apply CRopp_lt_compat, abs.
Qed.
Lemma CRmult_eq_0_reg_l : forall x y : CR,
(~(y == 0)%CR)
-> (x*y == 0)%CR
-> (x == 0)%CR.
Proof.
intros. apply ball_stable.
change (~~(x==0)%CR).
intros abs.
rewrite CReq_not_apart in abs.
contradict abs; intro xap0.
rewrite CReq_not_apart in H.
contradict H; intro yap0.
pose proof CRopp_0 as opp0.
symmetry in opp0.
destruct xap0.
- pose proof (CRopp_opp x).
symmetry in H.
apply (CRltT_wd H opp0) in c. clear H.
apply CRopp_lt_cancel in c.
destruct yap0.
+ pose proof (CRopp_opp y).
symmetry in H.
apply (CRltT_wd H opp0) in c0. clear H.
apply CRopp_lt_cancel in c0.
pose proof (CRmult_lt_0_compat _ _ c c0) as H.
revert H.
apply CRle_not_lt.
setoid_replace (-x*-y)%CR with (x*y)%CR
by (unfold equiv, msp_Equiv; ring).
rewrite H0. apply CRle_refl.
+ pose proof (CRmult_lt_0_compat _ _ c c0) as H.
revert H.
apply CRle_not_lt.
rewrite opp0.
setoid_replace (-x*y)%CR with (-(x*y))%CR
by (unfold equiv, msp_Equiv; ring).
apply CRopp_le_compat.
rewrite H0. apply CRle_refl.
- destruct yap0.
+ pose proof (CRopp_opp y).
symmetry in H.
apply (CRltT_wd H opp0) in c0. clear H.
apply CRopp_lt_cancel in c0.
pose proof (CRmult_lt_0_compat _ _ c c0) as H.
revert H.
apply CRle_not_lt.
setoid_replace (x*-y)%CR with (-(x*y))%CR
by (unfold equiv, msp_Equiv; ring).
rewrite H0, <- opp0. apply CRle_refl.
+ pose proof (CRmult_lt_0_compat _ _ c c0) as H.
revert H.
apply CRle_not_lt.
rewrite H0. apply CRle_refl.
Qed.
Lemma CRsquare_pos : forall x : CR, (0 <= x*x)%CR.
Proof.
(* Goal is a negation, use excluded middle x is positive or not. *)
intros x.
apply CRle_not_lt. intro abs.
assert (~(0 <= x)%CR) as H.
{ intro J. revert abs.
apply CRle_not_lt.
exact (CRmult_le_0_compat x x J J). }
contradict H. apply CRle_not_lt.
intro H.
revert abs.
apply CRle_not_lt.
apply CRlt_le_weak in H.
setoid_replace (x*x)%CR with (-x*-x)%CR
by (unfold equiv, msp_Equiv; ring).
apply CRmult_le_0_compat.
rewrite <- CRopp_0.
apply CRopp_le_compat, H.
rewrite <- CRopp_0.
apply CRopp_le_compat, H.
Qed.
#[global]
Instance: StrongSetoid_BinaryMorphism CRmult.
Proof.
split; try apply _.
assert (forall a b c d : CR, (a*b < c*d)%CR -> (sum (a≶c) (b≶d))).
{ intros.
pose proof (@CRlt_linear _ (a*d)%CR _ H) as [H0|H0].
right. apply CRmult_lt_cancel_l in H0. apply H0.
left. apply (@CRltT_wd (a*d) (d*a) (CRmult_comm _ _)
(c*d) (d*c) (CRmult_comm _ _)) in H0.
apply CRmult_lt_cancel_l in H0. apply H0. }
intros x₁ y₁ x₂ y₂ E.
destruct E. apply CR_lt_ltT in H. apply X in H.
destruct H. left. exact a. right. exact a.
apply CR_lt_ltT, X in H.
destruct H. left.
destruct a. right. exact H. left. exact H.
right. destruct a. right. exact H. left. exact H.
Qed.
#[global]
Instance: FullPseudoOrder CRle CRlt.
Proof.
split.
split; try apply _.
- intros x y [E1 E2].
apply CR_lt_ltT in E1. apply CR_lt_ltT in E2.
exact (@CRlt_irrefl x (@CRlt_trans x y x E1 E2)).
- intros x y E z.
apply CR_lt_ltT in E.
pose proof (CRlt_linear _ z _ E). destruct H.
left. apply CR_lt_ltT. exact c.
right. apply CR_lt_ltT. exact c.
- intros x y; split.
intro E. exact E. intro E. exact E.
- split. intros.
pose proof (CRle_not_lt x y) as [H0 _]. specialize (H0 H).
intro abs. apply CR_lt_ltT in abs. apply H0, abs.
intros. apply CRle_not_lt. intro abs.
apply H. apply CR_lt_ltT. exact abs.
Qed.
#[global]
Instance: FullPseudoSemiRingOrder CRle CRlt.
Proof.
apply rings.from_full_pseudo_ring_order.
- repeat (split; try apply _).
intros. apply CR_lt_ltT. apply CRplus_lt_l.
apply CR_lt_ltT. exact H.
- split; try apply _.
intros. apply (strong_binary_extensionality CRmult), H.
- intros. apply CR_lt_ltT. apply CRmult_lt_0_compat.
apply CR_lt_ltT, H.
apply CR_lt_ltT, H0.
Qed.
#[global]
Program Instance CRinv: Recip CR := λ x, CRinvT x _.
Next Obligation. apply CR_apart_apartT. now destruct x. Qed.
#[global]
Instance: Field CR.
Proof.
split; try apply _.
- apply CR_apart_apartT. right.
exists (1#1)%Qpos. simpl. rewrite CRopp_0, CRplus_0_r.
apply CRle_refl.
- split; try apply _.
intros [x Px] [y Py] E.
unfold recip, CRinv. simpl.
apply (CRinvT_wd (CRinv_obligation_1 (x ↾ Px))
(CRinv_obligation_1 (y ↾ Py))).
apply E.
- intros x.
unfold recip. simpl.
destruct x as [x xnz]. apply CRmult_inv_r.
Qed.
#[global]
Instance: StrongSetoid_Morphism inject_Q_CR.
Proof.
apply strong_setoids.dec_strong_morphism.
split; try apply _.
Qed.
#[global]
Instance: StrongSemiRing_Morphism inject_Q_CR.
Proof.
repeat (split; try apply _); intros; try reflexivity; symmetry.
now apply CRplus_Qplus.
now apply CRmult_Qmult.
Qed.
#[global]
Instance: StrongInjective inject_Q_CR.
Proof.
repeat (split; try apply _); intros.
apply CR_apart_apartT.
now apply Qap_CRap.
Qed.
#[global]
Instance: OrderEmbedding inject_Q_CR.
Proof. repeat (split; try apply _); now apply CRle_Qle. Qed.
#[global]
Instance: StrictOrderEmbedding inject_Q_CR.
Proof. split; apply _. Qed.
|
module Main
import Data.Vect
import Data.Fin
%language DSLNotation
data Ty = TyInt | TyBool| TyFun Ty Ty
interpTy : Ty -> Type
interpTy TyInt = Int
interpTy TyBool = Bool
interpTy (TyFun s t) = interpTy s -> interpTy t
using (G : Vect n Ty)
data Env : Vect n Ty -> Type where
Nil : Env Nil
(::) : interpTy a -> Env G -> Env (a :: G)
data HasType : (i : Fin n) -> Vect n Ty -> Ty -> Type where
Stop : HasType FZ (t :: G) t
Pop : HasType k G t -> HasType (FS k) (u :: G) t
lookup : HasType i G t -> Env G -> interpTy t
lookup Stop (x :: xs) = x
lookup (Pop k) (x :: xs) = lookup k xs
lookup Stop [] impossible
data Expr : Vect n Ty -> Ty -> Type where
Var : HasType i G t -> Expr G t
Val : (x : Int) -> Expr G TyInt
Lam : Expr (a :: G) t -> Expr G (TyFun a t)
App : Lazy (Expr G (TyFun a t)) -> Expr G a -> Expr G t
Op : (interpTy a -> interpTy b -> interpTy c) -> Expr G a -> Expr G b ->
Expr G c
If : Expr G TyBool -> Expr G a -> Expr G a -> Expr G a
Bind : Expr G a -> (interpTy a -> Expr G b) -> Expr G b
%static
lam_ : TTName -> Expr (a :: G) t -> Expr G (TyFun a t)
lam_ _ = Lam
dsl expr
lambda = lam_
variable = Var
index_first = Stop
index_next = Pop
total
interp : Env G -> %static (e : Expr G t) -> interpTy t
interp env (Var i) = lookup i env
interp env (Val x) = x
interp env (Lam sc) = \x => interp (x :: env) sc
interp env (App f s) = (interp env f) (interp env s)
interp env (Op op x y) = op (interp env x) (interp env y)
interp env (If x t e) = if interp env x then interp env t else interp env e
interp env (Bind v f) = interp env (f (interp env v))
eId : Expr G (TyFun TyInt TyInt)
eId = expr (\x => x)
eTEST : Expr G (TyFun TyInt (TyFun TyInt TyInt))
eTEST = expr (\x, y => y)
eAdd : Expr G (TyFun TyInt (TyFun TyInt TyInt))
eAdd = expr (\x, y => Op (+) x y)
-- eDouble : Expr G (TyFun TyInt TyInt)
-- eDouble = Lam (App (App (Lam (Lam (Op' (+) (Var FZ) (Var (FS FZ))))) (Var FZ)) (Var FZ))
eDouble : Expr G (TyFun TyInt TyInt)
eDouble = expr (\x => App (App eAdd x) (Var Stop))
-- app : Lazy (Expr G (TyFun a t)) -> Expr G a -> Expr G t
-- app = \f, a => App (Force f) a
eFac : Expr G (TyFun TyInt TyInt)
eFac = expr (\x => If (Op (==) x (Val 0))
(Val 1)
(Op (*) (App eFac (Op (-) x (Val 1))) x))
-- Exercise elaborator: Complicated way of doing \x y => x*4 + y*2
eProg : Expr G (TyFun TyInt (TyFun TyInt TyInt))
eProg = Lam (Lam
(Bind (App eDouble (Var (Pop Stop)))
(\x => Bind (App eDouble (Var Stop))
(\y => Bind (App eDouble (Val x))
(\z => App (App eAdd (Val y)) (Val z))))))
test : Int
test = interp [] eProg 2 2
testFac : Int
testFac = interp [] eFac 4
testEnv : Int -> Env [TyInt,TyInt]
testEnv x = [x,x]
main : IO ()
main = do { printLn testFac
printLn test }
|
(** * Trace Semantics *)
(** Anticipating the need for trace semantics for reduction in a concurrent setting,
we develop them for the language extended with procedures from Recursion.v
*)
Set Warnings "-notation-overridden,-parsing".
From Coq Require Import Strings.String.
From Coq Require Import Bool.Bool.
From Coq Require Import Arith.EqNat. Import Nat.
From Coq Require Import Init.Datatypes.
From Coq Require Import Program. (* for `dependent induction` *)
(* which apparently (CTrees) smuggles in UIP(-equivalent) *)
From Coq Require Import Logic.FunctionalExtensionality. (* for equality of substitutions *)
From Coq Require Import Relations.
From SymEx Require Import Expr.
Import ProcedureExpr.
From SymEx Require Import Maps.
Import ProcedureMaps.
From SymEx Require Import Recursion.
From SymEx Require Import Traces.
Open Scope com_scope.
Open Scope string_scope.
Open Scope trace_scope.
(** Symbolic semantics *)
Fixpoint Stmt_sub (s:Stmt) (u y:LVar) : Stmt :=
let t : LSub := (u !-> (ALVar y) ; Lid_sub) in
match s with
| SGAsgn x e => SGAsgn x (Aapply Gid_sub t e)
| SLAsgn x e => SLAsgn (if u =? x then y else x) (Aapply Gid_sub t e)
| SProc P e => SProc P (Aapply Gid_sub t e)
| SSeq s1 s2 => SSeq (Stmt_sub s1 u y) (Stmt_sub s2 u y)
| SIf b s1 s2 => SIf (Bapply Gid_sub t b) (Stmt_sub s1 u y) (Stmt_sub s2 u y)
| SWhile b s => SWhile (Bapply Gid_sub t b) (Stmt_sub s u y)
| SReturn => SReturn
end.
Definition STrace_step : Type := (Bexpr + (GVar * Aexpr) + (LVar * Aexpr)).
Definition cond : Bexpr -> STrace_step := fun x => inl (inl x).
Definition asgnG : GVar -> Aexpr -> STrace_step := fun x e => inl (inr (x, e)).
Definition asgnL : LVar -> Aexpr -> STrace_step := fun x e => inr (x, e).
Definition STrace := trace STrace_step.
Fixpoint acc_GSubst (G:GSub) (L:LSub) (t:STrace) : GSub :=
match t with
| [] => G
| t' :: inl (inr (x, e)) => let l := acc_LSubst G L t' in
let g := acc_GSubst G L t' in
(x !-> Aapply g l e ; g)
| t' :: _ => acc_GSubst G L t'
end
with acc_LSubst (G:GSub) (L:LSub) (t:STrace) : LSub :=
match t with
| [] => L
| t' :: inr (x, e) => let l := acc_LSubst G L t' in
let g := acc_GSubst G L t' in
(x !-> Aapply g l e ; l)
| t' :: _ => acc_LSubst G L t'
end.
Definition acc_GSubst_id := acc_GSubst Gid_sub Lid_sub.
Definition acc_LSubst_id := acc_LSubst Gid_sub Lid_sub.
Definition Aapply_t : STrace -> Aexpr -> Aexpr :=
fun t e => Aapply (acc_GSubst_id t) (acc_LSubst_id t) e.
Definition Bapply_t : STrace -> Bexpr -> Bexpr :=
fun t e => Bapply (acc_GSubst_id t) (acc_LSubst_id t) e.
Fixpoint pc (t:STrace) : Bexpr :=
match t with
| [] => BTrue
| t' :: inr _ => pc t'
| t' :: inl (inr _) => pc t'
| t' :: inl (inl p) => BAnd (Bapply_t t' p) (pc t')
end.
Definition SConfig : Type := Stmt * STrace.
Reserved Notation " c '->s' c' " (at level 40).
Inductive Sstep : relation SConfig :=
| SGAsgn_step : forall x e s t,
(<{ x :=G e ; s }>, t) ->s (s, (t :: asgnG x e))
| SLAsgn_step : forall x e s t,
(<{ x :=L e ; s }>, t) ->s (s, t :: asgnL x e)
| SProc_step : forall (t:STrace) u y body e s t,
(* "y fresh", somehow *)
(<{ proc(u){body}(e) ; s }>, t) ->s (SSeq (Stmt_sub body u y) s, t :: asgnL y e)
| SReturn_step : forall s t,
(<{ return ; s }>, t) ->s (s, t)
| SIfTrue_step : forall b s1 s2 s t,
(<{ if b {s1}{s2} ; s}>, t) ->s (<{ s1 ; s }>, t :: cond b)
| SIfFalse_step : forall b s1 s2 s t,
(<{ if b {s1}{s2} ; s}>, t) ->s (<{ s2 ; s }>, t :: cond (BNot b))
| SWhileTrue_step : forall b s s' t,
(<{ while b {s} ; s' }>, t) ->s (<{ s ; while b {s} ; s' }>, t :: cond b)
| SWhileFalse_step : forall b s s' t,
(<{ while b {s} ; s' }>, t) ->s (s', t :: cond (BNot b))
where " c '->s' c' " := (Sstep c c').
Definition multi_Sstep := clos_refl_trans_n1 _ Sstep.
Notation " c '->*' c' " := (multi_Sstep c c') (at level 40) : trace_scope.
(** Properties *)
Lemma Sstep_progress : forall s s' t t',
(s, t) ->s (s', t') ->
s <> s' \/ t <> t'.
Proof.
intros. inversion H; subst;
try (left; apply SSeq_disjoint);
try (right; apply cons_neq').
Qed.
Definition S_is_extension (t0 t:STrace) := exists t', t = t0 ++ t'.
Lemma STrace_extends : forall s s' t0 t,
(s, t0) ->* (s', t) ->
S_is_extension t0 t.
Proof.
intros. dependent induction H.
- exists []. reflexivity.
- inversion H; subst.
+ destruct (IHclos_refl_trans_n1 s <{ x :=G e ; s' }> t0 t1);
try reflexivity.
exists (x0 :: asgnG x e). rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ x :=L e ; s' }> t0 t1);
try reflexivity.
exists (x0 :: asgnL x e). rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ proc(u){body}(e) ; s0 }> t0 t2);
try reflexivity.
exists (x :: asgnL y0 e). rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ return ; s' }> t0 t);
try reflexivity.
exists x. rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0 }> t0 t1);
try reflexivity.
exists (x :: cond b). rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0 }> t0 t1);
try reflexivity.
exists (x :: cond <{~ b}>). rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s'0 }> t0 t1);
try reflexivity.
exists (x :: cond b). rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s' }> t0 t1);
try reflexivity.
exists (x :: cond <{~ b}>). rewrite H1. reflexivity.
Qed.
(** Concrete semantics *)
Definition Val : Type := nat.
Definition CTrace_step : Type := (GVar * Val) + (LVar * Val).
Definition CTrace := trace CTrace_step.
Fixpoint acc_GVal (G0:GVal) (L0:LVal) (t:CTrace) : GVal :=
match t with
| Tnil => G0
| Tcons t' (inr _) => acc_GVal G0 L0 t'
| Tcons t' (inl (x, v)) => let G' := acc_GVal G0 L0 t' in
(x !-> v ; G')
end.
Fixpoint acc_LVal (G0:GVal) (L0:LVal) (t:CTrace) : LVal :=
match t with
| Tnil => L0
| Tcons t' (inl _) => acc_LVal G0 L0 t'
| Tcons t' (inr (x, v)) => let L' := acc_LVal G0 L0 t' in
(x !-> v ; L')
end.
Definition Aeval_t (G0:GVal) (L0:LVal) (t:CTrace) (e:Aexpr) : nat :=
Aeval (acc_GVal G0 L0 t) (acc_LVal G0 L0 t) e.
Definition Beval_t (G0:GVal) (L0:LVal) (t:CTrace) (b:Bexpr) : bool :=
Beval (acc_GVal G0 L0 t) (acc_LVal G0 L0 t) b.
Lemma Gcomp_update_comm : forall G L x (v:Val) s,
GComp G L (update s x (AConst v)) = update (GComp G L s) x v.
Proof.
intros. extensionality y.
unfold GComp. unfold update. destruct (x =? y); simpl; reflexivity.
Qed.
Lemma Lcomp_update_comm : forall G L x (v:Val) s,
LComp G L (update s x (AConst v)) = update (LComp G L s) x v.
Proof.
intros. extensionality y.
unfold LComp. unfold update. destruct (x =? y); simpl; reflexivity.
Qed.
Definition CConfig : Type := Stmt * CTrace.
Inductive Cstep (G0:GVal) (L0:LVal) : relation CConfig :=
| CGAsgn_step : forall x e s t,
Cstep G0 L0 (<{ x :=G e ; s }>, t) (s, t :: inl (x, Aeval_t G0 L0 t e))
| CLAsgn_step : forall x e s t,
Cstep G0 L0 (<{ x :=L e ; s }>, t) (s, t :: inr (x, Aeval_t G0 L0 t e))
| CProc_step : forall u body e s' t y,
(* y fresh *)
Cstep G0 L0 (<{ proc(u){body}(e) ; s' }>, t) (SSeq (Stmt_sub body u y) s', t :: inr (y, Aeval_t G0 L0 t e))
| CReturn_step : forall s t,
Cstep G0 L0 (<{ return ; s }>, t) (s, t)
| CIfTrue_step : forall b s1 s2 s t,
Beval_t G0 L0 t b = true ->
Cstep G0 L0 (<{ if b {s1}{s2} ; s }>, t) (<{s1 ; s}>, t)
| CIfFalse_step : forall b s1 s2 s t,
Beval_t G0 L0 t b = false ->
Cstep G0 L0 (<{ if b {s1}{s2} ; s }>, t) (<{s2 ; s}>, t)
| CWhileTrue_step : forall b s s' t,
Beval_t G0 L0 t b = true ->
Cstep G0 L0 (<{ while b {s} ; s' }>, t) (<{s ; while b {s} ; s'}>, t)
| CWhileFalse_step : forall b s s' t,
Beval_t G0 L0 t b = false ->
Cstep G0 L0 (<{ while b {s} ; s' }>, t) (s', t).
Definition multi_Cstep {G0:GVal} {L0:LVal} := clos_refl_trans_n1 _ (Cstep G0 L0).
Notation " c '=>c' c'" := (Cstep _ _ c c').
Notation " c '=>*' c' " := (multi_Cstep c c') (at level 40).
(** Properties *)
Definition deterministic {X : Type} (R : relation X) :=
forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.
Theorem Cstep_deterministic {G0:GVal} {L0:LVal} : deterministic (@Cstep G0 L0).
Proof.
unfold deterministic. intros.
generalize dependent y2.
induction H; intros;
(* simple cases *)
try (inversion H0; subst; reflexivity);
(* branches *)
try (inversion H0; subst;
try reflexivity;
try (try rewrite H in H6;
try rewrite H in H7;
discriminate)).
- admit. (* no way to show that the "fresh" variable is the same*)
Admitted.
Definition C_is_extension (t0 t:CTrace) := exists t', t = t0 ++ t'.
Lemma CTrace_extends : forall s s' t0 t G0 L0,
@multi_Cstep G0 L0 (s, t0) (s', t) ->
C_is_extension t0 t.
Proof.
intros. dependent induction H.
- exists []. reflexivity.
- inversion H; subst.
+ destruct (IHclos_refl_trans_n1 s <{ x :=G e ; s' }> t0 t1);
try reflexivity.
exists (x0 :: inl (x, Aeval_t G0 L0 t1 e)).
rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ x :=L e ; s' }> t0 t1);
try reflexivity.
exists (x0 :: inr (x, Aeval_t G0 L0 t1 e)).
rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ proc(u){body}(e) ; s'0 }> t0 t1);
try reflexivity.
exists (x :: inr (y0, Aeval_t G0 L0 t1 e)). rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ return ; s' }> t0 t);
try reflexivity.
exists x. rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0 }> t0 t);
try reflexivity.
exists x. rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0 }> t0 t);
try reflexivity.
exists x. rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s'0 }> t0 t);
try reflexivity.
exists x. rewrite H1. reflexivity.
+ destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s' }> t0 t);
try reflexivity.
exists x. rewrite H1. reflexivity.
Qed.
(** Correctness *)
Ltac splits := repeat (try split).
Theorem correctness : forall s s' t0 t t0' G0 L0,
(s, t0) ->* (s', t) ->
Beval G0 L0 (pc t) = true ->
(* start trace is concretely reachable *)
acc_GVal G0 L0 t0' = GComp G0 L0 (acc_GSubst_id t0) ->
acc_LVal G0 L0 t0' = LComp G0 L0 (acc_LSubst_id t0) ->
(* this is a somewhat "brute force" solution *)
exists t', @multi_Cstep G0 L0 (s, t0') (s', t')
/\ acc_GVal G0 L0 t' = GComp G0 L0 (acc_GSubst_id t)
/\ acc_LVal G0 L0 t' = LComp G0 L0 (acc_LSubst_id t).
Proof.
intros. dependent induction H.
- exists t0'. splits;
[apply rtn1_refl
| assumption
| assumption].
- dependent destruction H.
+ (* global assignment *)
destruct (IHclos_refl_trans_n1 s <{ x :=G e ; s'}> t0 t1) as [t' [comp [IHG IHL]]];
try reflexivity;
try assumption.
exists (t' :: inl (x, Aeval (acc_GVal G0 L0 t') (acc_LVal G0 L0 t') e)). splits.
* eapply Relation_Operators.rtn1_trans. apply CGAsgn_step. apply comp.
* unfold acc_GSubst_id in *. unfold acc_LSubst_id in *. unfold Aeval_t.
simpl. rewrite Gasgn_sound. rewrite eval_comp.
rewrite <- IHG. rewrite <- IHL. reflexivity.
* simpl. assumption.
+ (* local assignment *)
destruct (IHclos_refl_trans_n1 s <{ x :=L e ; s'}> t0 t1) as [t' [comp [IHG IHL]]];
try reflexivity;
try assumption.
exists (t' :: inr (x, Aeval (acc_GVal G0 L0 t') (acc_LVal G0 L0 t') e)). splits.
* eapply Relation_Operators.rtn1_trans. apply CLAsgn_step. apply comp.
* simpl. assumption.
* unfold acc_GSubst_id in *. unfold acc_LSubst_id in *. unfold Aeval_t.
simpl. rewrite Lasgn_sound. rewrite eval_comp.
rewrite <- IHG. rewrite <- IHL. reflexivity.
+ (* proc *)
destruct (IHclos_refl_trans_n1 s <{ proc(u){body}(e) ; s0}> t0 t2) as [t' [comp [IHG IHL]]];
try reflexivity;
try assumption.
exists (t' :: inr (y, Aeval_t G0 L0 t' e)). splits.
* eapply Relation_Operators.rtn1_trans;
[apply CProc_step | apply comp].
* simpl. assumption.
* unfold acc_GSubst_id in *. unfold acc_LSubst_id in *. unfold Aeval_t.
simpl. rewrite Lasgn_sound. rewrite eval_comp.
rewrite <- IHG. rewrite <- IHL. reflexivity.
+ (* return *)
destruct (IHclos_refl_trans_n1 s <{ return ; s'}> t0 t) as [t' [comp [IHG IHL]]];
try reflexivity;
try assumption.
exists t'. splits.
* eapply Relation_Operators.rtn1_trans;
[apply CReturn_step | apply comp].
* assumption.
* assumption.
+ (* if true *)
simpl in H1. apply andb_true_iff in H1. destruct H1.
destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0}> t0 t1) as [t' [comp [IHG IHL]]];
try reflexivity;
try assumption.
exists t'. splits.
* eapply Relation_Operators.rtn1_trans.
** eapply CIfTrue_step. unfold Beval_t.
unfold Bapply_t in H. rewrite IHG. rewrite IHL.
rewrite <- eval_compB. rewrite Comp_subB. apply H.
** apply comp.
* assumption.
* assumption.
+ (* if false *)
simpl in H1. apply andb_true_iff in H1. destruct H1. apply negb_true_iff in H.
destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0}> t0 t1) as [t' [comp [IHG IHL]]];
try reflexivity;
try assumption.
exists t'. splits.
* eapply Relation_Operators.rtn1_trans.
** eapply CIfFalse_step. unfold Beval_t.
unfold Bapply_t in H. rewrite IHG. rewrite IHL.
rewrite <- eval_compB. rewrite Comp_subB. apply H.
** apply comp.
* simpl. assumption.
* simpl. assumption.
+ (* while true *)
simpl in H1. apply andb_true_iff in H1. destruct H1.
destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s'0}> t0 t1) as [t' [comp [IHG IHL]]];
try reflexivity;
try assumption.
exists t'. splits.
* eapply Relation_Operators.rtn1_trans.
** eapply CWhileTrue_step. unfold Beval_t.
unfold Bapply_t in H. rewrite IHG. rewrite IHL.
rewrite <- eval_compB. rewrite Comp_subB. apply H.
** apply comp.
* simpl. assumption.
* simpl. assumption.
+ (* while false *)
simpl in H1. apply andb_true_iff in H1. destruct H1. apply negb_true_iff in H.
destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s'}> t0 t1) as [t' [comp [IHG IHL]]];
try reflexivity;
try assumption.
exists t'. splits.
* eapply Relation_Operators.rtn1_trans.
** eapply CWhileFalse_step. unfold Beval_t.
unfold Bapply_t in H. rewrite IHG. rewrite IHL.
rewrite <- eval_compB. rewrite Comp_subB. apply H.
** apply comp.
* simpl. assumption.
* simpl. assumption.
Qed.
Theorem correctness_empty : forall s s' t G0 L0,
(s, []) ->* (s', t) ->
Beval G0 L0 (pc t) = true ->
exists t', @multi_Cstep G0 L0 (s, []) (s', t')
/\ acc_GVal G0 L0 t' = GComp G0 L0 (acc_GSubst_id t)
/\ acc_LVal G0 L0 t' = LComp G0 L0 (acc_LSubst_id t).
Proof.
intros.
apply correctness with (t0 := []); try assumption.
- unfold acc_GSubst_id. apply GComp_id with (L := L0).
- unfold acc_LSubst_id. apply LComp_id with (G := G0).
Qed.
Theorem completeness : forall s s' t0 t t0' G0 L0,
@multi_Cstep G0 L0 (s, t0) (s', t) ->
Beval G0 L0 (pc t0') = true ->
GComp G0 L0 (acc_GSubst_id t0') = acc_GVal G0 L0 t0 ->
LComp G0 L0 (acc_LSubst_id t0') = acc_LVal G0 L0 t0 ->
exists t',
(s, t0') ->* (s', t')
/\ Beval G0 L0 (pc t') = true
/\ GComp G0 L0 (acc_GSubst_id t') = acc_GVal G0 L0 t
/\ LComp G0 L0 (acc_LSubst_id t') = acc_LVal G0 L0 t.
Proof.
intros. dependent induction H.
- exists t0'. splits;
try assumption. apply rtn1_refl.
- inversion H; subst.
+ (* global assignment *)
destruct (IHclos_refl_trans_n1 s <{ x :=G e ; s'}> t0 t1) as [t' [comp [pc_true [IHG IHL]]]];
try reflexivity; try assumption.
exists (t' :: asgnG x e). splits.
* eapply Relation_Operators.rtn1_trans. apply SGAsgn_step. apply comp.
* simpl. assumption.
* unfold acc_GSubst_id in *. unfold acc_LSubst_id in *. unfold Aeval_t.
simpl. rewrite Gasgn_sound. rewrite eval_comp.
rewrite IHG. rewrite IHL. reflexivity.
* simpl. assumption.
+ (* local assignment *)
destruct (IHclos_refl_trans_n1 s <{ x :=L e ; s'}> t0 t1) as [t' [comp [pc_true [IHG IHL]]]];
try reflexivity; try assumption.
exists (t' :: asgnL x e). splits.
* eapply Relation_Operators.rtn1_trans. apply SLAsgn_step. apply comp.
* simpl. assumption.
* simpl. assumption.
* unfold acc_GSubst_id in *. unfold acc_LSubst_id in *. unfold Aeval_t.
simpl. rewrite Lasgn_sound. rewrite eval_comp.
rewrite IHG. rewrite IHL. reflexivity.
+ (* procedure call *)
destruct (IHclos_refl_trans_n1 s <{ proc(u){body}(e) ; s'0}> t0 t1) as [t' [comp [pc_true [IHG IHL]]]];
try reflexivity; try assumption.
exists (t' :: asgnL y0 e). splits.
* eapply Relation_Operators.rtn1_trans. apply SProc_step. exact []. apply comp.
* simpl. assumption.
* simpl. assumption.
* unfold acc_LSubst_id in *. unfold acc_GSubst_id in *. unfold Aeval_t.
simpl. rewrite Lasgn_sound. rewrite eval_comp.
rewrite IHG. rewrite IHL. reflexivity.
+ (* return *)
destruct (IHclos_refl_trans_n1 s <{ return ; s'}> t0 t) as [t' [comp [pc_true [IHG IHL]]]];
try reflexivity; try assumption.
exists t'. splits;
try assumption.
eapply Relation_Operators.rtn1_trans. apply SReturn_step. apply comp.
+ (* if true *)
destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0}> t0 t) as [t' [comp [pc_true [IHG IHL]]]];
try reflexivity; try assumption.
exists (t' :: cond b). splits.
* eapply Relation_Operators.rtn1_trans. apply SIfTrue_step. apply comp.
* simpl. apply andb_true_iff. split.
** unfold Beval_t in H6. rewrite <- IHG in H6. rewrite <- IHL in H6. rewrite <- eval_compB in H6.
rewrite Comp_subB in H6. unfold Bapply_t. assumption.
** assumption.
* simpl. assumption.
* simpl. assumption.
+ (* if false *)
destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0}> t0 t) as [t' [comp [pc_true [IHG IHL]]]];
try reflexivity; try assumption.
exists (t' :: cond (BNot b)). splits.
* eapply Relation_Operators.rtn1_trans. apply SIfFalse_step. apply comp.
* simpl. apply andb_true_iff. split.
** unfold Beval_t in H6. rewrite <- IHG in H6. rewrite <- IHL in H6. rewrite <- eval_compB in H6.
rewrite Comp_subB in H6. unfold Bapply_t. apply negb_true_iff. assumption.
** assumption.
* simpl. assumption.
* simpl. assumption.
+ (* while true *)
destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s'0}> t0 t) as [t' [comp [pc_true [IHG IHL]]]];
try reflexivity; try assumption.
exists (t' :: cond b). splits.
* eapply Relation_Operators.rtn1_trans. apply SWhileTrue_step. apply comp.
* simpl. apply andb_true_iff. split.
** unfold Beval_t in H6. rewrite <- IHG in H6. rewrite <- IHL in H6. rewrite <- eval_compB in H6.
rewrite Comp_subB in H6. unfold Bapply_t. assumption.
** assumption.
* simpl. assumption.
* simpl. assumption.
+ (* while false *)
destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s'}> t0 t) as [t' [comp [pc_true [IHG IHL]]]];
try reflexivity; try assumption.
exists (t' :: cond (BNot b)). splits.
* eapply Relation_Operators.rtn1_trans. apply SWhileFalse_step. apply comp.
* simpl. apply andb_true_iff. split.
** unfold Beval_t in H6. rewrite <- IHG in H6. rewrite <- IHL in H6. rewrite <- eval_compB in H6.
rewrite Comp_subB in H6. unfold Bapply_t. apply negb_true_iff. assumption.
** assumption.
* simpl. assumption.
* simpl. assumption.
Qed.
Theorem completeness_empty : forall s s' t G0 L0,
@multi_Cstep G0 L0 (s, []) (s', t) ->
exists t',
(s, []) ->* (s', t')
/\ Beval G0 L0 (pc t') = true
/\ GComp G0 L0 (acc_GSubst_id t') = acc_GVal G0 L0 t
/\ LComp G0 L0 (acc_LSubst_id t') = acc_LVal G0 L0 t.
Proof.
intros.
apply completeness with (t0 := []);
try assumption; try reflexivity.
Qed.
(** Attempts to merge some states *)
(** Plan: *)
(** 1. define an equivalence on Straces that lead to the same state *)
(** 2. show that we can contine computation from an equivalent state (?)
*)
Definition GSub_equiv (G G':GSub) := forall x, G x = G' x.
Definition LSub_equiv (L L':LSub) := forall x, L x = L' x.
Definition PC_equiv (t t': STrace) := forall G0 L0, Beval G0 L0 (pc t) = true <-> Beval G0 L0 (pc t') = true.
Definition STrace_equiv (t t':STrace) := GSub_equiv (acc_GSubst_id t) (acc_GSubst_id t')
/\ LSub_equiv (acc_LSubst_id t) (acc_LSubst_id t')
/\ PC_equiv t t'.
Notation "t ~ t'" := (STrace_equiv t t') (at level 40) : trace_scope.
Lemma STrace_equiv_refl : forall t, t ~ t.
Proof. intro. unfold STrace_equiv. splits; intro; assumption. Qed.
Lemma STrace_equiv_sym : forall t t', t ~ t' -> t' ~ t.
Proof. intros. unfold STrace_equiv in *. destruct H. destruct H0. splits;
[ intro; symmetry; apply H
| intro; symmetry; apply H0
| apply H1 | apply H1].
Qed.
Lemma STrace_equiv_trans : forall t t' t'', t ~ t' -> t' ~ t'' -> t ~ t''.
Proof. intros. unfold STrace_equiv in *. destruct H, H0, H1, H2. splits; intro.
- rewrite H, H0. reflexivity.
- rewrite H1, H2. reflexivity.
- apply H3 in H5. apply H4 in H5. apply H5.
- apply H4 in H5. apply H3 in H5. apply H5.
Qed.
(** The necessary condition on trace-prefixes for correctness*)
(* seems a bit strong to say forall *)
Definition correctness_prefix_condition t G0 L0 :=
(exists t', acc_GVal G0 L0 t' = GComp G0 L0 (acc_GSubst_id t)
/\ acc_LVal G0 L0 t' = LComp G0 L0 (acc_LSubst_id t)).
(**Idea: if two straces are equivalent, and one satisfies ^, then the other also does*)
Lemma STrace_correct_equiv_cong : forall t t' G0 L0,
t ~ t' ->
correctness_prefix_condition t G0 L0 ->
correctness_prefix_condition t' G0 L0 .
Proof.
intros. destruct H0 as [ct [HG HL]].
exists ct. destruct H. splits.
- rewrite HG. extensionality x.
unfold GComp. rewrite <- H. reflexivity.
- rewrite HL. extensionality x.
unfold LComp. rewrite <- (proj1 H0). reflexivity.
Qed.
Lemma STrace_pc_equiv_cong : forall t t' G0 L0,
t ~ t' ->
Beval G0 L0 (pc t) = true ->
Beval G0 L0 (pc t') = true.
Proof.
intros t t' G0 L0 H. destruct H as [_ [_ PCEquiv]].
apply PCEquiv.
Qed.
(* use these lemmas for something like "for t ~ t', if a concretization of t exists then a concretization of t' does too"
and then maybe "(s, t) -> (s, t') is a sound reduction if t ~ t'" and do some state merging?*)
(* Note: still indexing on initial valuations, not sure what to do about that *)
Lemma G_cond_idempotent : forall t b,
acc_GSubst_id t = acc_GSubst_id (t :: inl (inl b)).
Proof. intros. unfold acc_GSubst_id. unfold acc_GSubst. reflexivity. Qed.
Lemma L_cond_idempotent : forall t b,
acc_LSubst_id t = acc_LSubst_id (t :: inl (inl b)).
Proof. intros. unfold acc_LSubst_id. unfold acc_LSubst. reflexivity. Qed.
Lemma STrace_Bapply_t_equiv_cong : forall t t' b,
t ~ t' ->
Bapply_t t b = Bapply_t t' b.
Proof.
intros. unfold Bapply_t. destruct H, H0.
unfold GSub_equiv in H. unfold LSub_equiv in H0.
extensionality in H. extensionality in H0.
rewrite H, H0. reflexivity.
Qed.
Lemma STrace_equiv_extend : forall t t' x,
t ~ t' ->
(t :: x) ~ (t' :: x).
Proof.
intros. destruct x. destruct s.
- unfold STrace_equiv in *. destruct H as [GEquiv [LEquiv PCEquiv]]. splits.
+ repeat (rewrite <- G_cond_idempotent in *). assumption.
+ repeat (rewrite <- L_cond_idempotent in *). assumption.
+ simpl. rewrite andb_true_iff. intro. destruct H.
rewrite andb_true_iff. split.
* unfold Bapply_t in *.
unfold GSub_equiv in GEquiv. extensionality in GEquiv. rewrite <- GEquiv.
unfold LSub_equiv in LEquiv. extensionality in LEquiv. rewrite <- LEquiv.
apply H.
* apply PCEquiv. assumption.
+ simpl. rewrite andb_true_iff. intro. destruct H.
rewrite andb_true_iff. split.
* unfold Bapply_t in *.
unfold GSub_equiv in GEquiv. extensionality in GEquiv. rewrite GEquiv.
unfold LSub_equiv in LEquiv. extensionality in LEquiv. rewrite LEquiv.
apply H.
* apply PCEquiv. assumption.
- destruct p. unfold STrace_equiv in *.
unfold acc_GSubst_id in *. unfold acc_LSubst_id in *.
unfold GSub_equiv in *. unfold LSub_equiv in *.
destruct H, H0. splits; intro.
+ extensionality in H. extensionality in H0. simpl. rewrite H, H0. reflexivity.
+ simpl. apply H0.
+ simpl in *. apply H1. apply H2.
+ simpl in *. apply H1. apply H2.
- destruct p. unfold STrace_equiv in *.
unfold acc_GSubst_id in *. unfold acc_LSubst_id in *.
unfold GSub_equiv in *. unfold LSub_equiv in *.
destruct H, H0. splits; intro.
+ simpl. apply H.
+ extensionality in H. extensionality in H0. simpl. rewrite H, H0. reflexivity.
+ simpl in *. apply H1. apply H2.
+ simpl in *. apply H1. apply H2.
Qed.
Lemma STrace_equiv_continue : forall s s' t0 t0' t G0 L0,
t0 ~ t0' ->
(s, t0) ->* (s', t) ->
Beval G0 L0 (pc t) = true ->
exists t', t ~ t'
/\ Beval G0 L0 (pc t') = true
/\ (s, t0') ->* (s', t').
Proof.
intros. dependent induction H0.
- exists t0'. split.
+ assumption.
+ split.
* apply STrace_pc_equiv_cong with (t := t); assumption.
* apply rtn1_refl.
- inversion H1; subst.
+ (* global assignment *)
destruct (IHclos_refl_trans_n1 s <{ x :=G e ; s'}> t0 t1) as [t' [IHEquiv [IHpc IHComp]]];
try reflexivity; try assumption.
exists (t' :: asgnG x e). split.
* apply STrace_equiv_extend. assumption.
* split.
** simpl. apply IHpc.
** eapply Relation_Operators.rtn1_trans. apply SGAsgn_step. apply IHComp.
+ (* local assignment *)
destruct (IHclos_refl_trans_n1 s <{ x :=L e ; s'}> t0 t1) as [t' [IHEquiv [IHpc IHComp]]];
try reflexivity; try assumption.
exists (t' :: asgnL x e). split.
* apply STrace_equiv_extend. assumption.
* split.
** simpl. apply IHpc.
** eapply Relation_Operators.rtn1_trans. apply SLAsgn_step. apply IHComp.
+ (* proc *)
destruct (IHclos_refl_trans_n1 s <{ proc(u){body}(e) ; s0}> t0 t2) as [t' [IHEquiv [IHpc IHComp]]];
try reflexivity; try assumption.
exists (t' :: asgnL y0 e). split.
* apply STrace_equiv_extend. assumption.
* split.
** simpl. apply IHpc.
** eapply Relation_Operators.rtn1_trans. apply SProc_step. exact []. apply IHComp.
+ (* return *)
destruct (IHclos_refl_trans_n1 s <{ return ; s'}> t0 t) as [t' [IHEquiv [IHpc IHComp]]];
try reflexivity; try assumption.
exists t'. split.
* assumption.
* split.
** assumption.
** eapply Relation_Operators.rtn1_trans. apply SReturn_step. apply IHComp.
+ (* if true *)
simpl in H2. apply andb_true_iff in H2. destruct H2.
destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0}> t0 t1) as [t' [IHEquiv [IHpc IHComp]]];
try reflexivity; try assumption.
exists (t' :: cond b). split.
* apply STrace_equiv_extend. assumption.
* split.
** simpl. apply andb_true_iff. split;
[rewrite STrace_Bapply_t_equiv_cong with (t' := t1);
[assumption | apply STrace_equiv_sym; assumption]
| assumption ].
** eapply Relation_Operators.rtn1_trans. apply SIfTrue_step. apply IHComp.
+ (* if false *)
simpl in H2. apply andb_true_iff in H2. destruct H2.
destruct (IHclos_refl_trans_n1 s <{ if b {s1}{s2} ; s0}> t0 t1) as [t' [IHEquiv [IHpc IHComp]]];
try reflexivity; try assumption.
exists (t' :: cond <{~ b}>). split.
* apply STrace_equiv_extend. assumption.
* split.
** simpl. apply andb_true_iff. rewrite negb_true_iff in *. split.
*** destruct IHEquiv, H5. unfold GSub_equiv in *. unfold LSub_equiv in *.
extensionality in H4. extensionality in H5.
rewrite <- H4, <- H5. assumption.
*** assumption.
** eapply Relation_Operators.rtn1_trans. apply SIfFalse_step. apply IHComp.
+ (* while true *)
simpl in H2. apply andb_true_iff in H2. destruct H2.
destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s'0}> t0 t1) as [t' [IHEquiv [IHpc IHComp]]];
try reflexivity; try assumption.
exists (t' :: cond b). split.
* apply STrace_equiv_extend. assumption.
* split.
** simpl. apply andb_true_iff. split;
[rewrite STrace_Bapply_t_equiv_cong with (t' := t1);
[assumption | apply STrace_equiv_sym; assumption]
| assumption ].
** eapply Relation_Operators.rtn1_trans. apply SWhileTrue_step. apply IHComp.
+ (* while false *)
simpl in H2. apply andb_true_iff in H2. destruct H2.
destruct (IHclos_refl_trans_n1 s <{ while b {s0} ; s'}> t0 t1) as [t' [IHEquiv [IHpc IHComp]]];
try reflexivity; try assumption.
exists (t' :: cond <{~b}>). split.
* apply STrace_equiv_extend. assumption.
* split.
** simpl. apply andb_true_iff. rewrite negb_true_iff in *. split.
*** destruct IHEquiv, H5. unfold GSub_equiv in *. unfold LSub_equiv in *.
extensionality in H4. extensionality in H5.
rewrite <- H4, <- H5. assumption.
*** assumption.
** eapply Relation_Operators.rtn1_trans. apply SWhileFalse_step. apply IHComp.
Qed.
(** Correctness modulo trace equivalance*)
(* In current formulation: does not actually use any of the above lemmas *)
Theorem correctness_reduced : forall s s' t0 t0' t tc G0 L0,
(s, t0) ->* (s', t) ->
Beval G0 L0 (pc t) = true ->
(* equivalent start trace is concretely reachable *)
t0 ~ t0' ->
acc_GVal G0 L0 tc = GComp G0 L0 (acc_GSubst_id t0') ->
acc_LVal G0 L0 tc = LComp G0 L0 (acc_LSubst_id t0') ->
exists t', @multi_Cstep G0 L0 (s, tc) (s', t')
/\ acc_GVal G0 L0 t' = GComp G0 L0 (acc_GSubst_id t)
/\ acc_LVal G0 L0 t' = LComp G0 L0 (acc_LSubst_id t).
Proof.
intros.
destruct H1 as [HG [HL _]].
unfold GSub_equiv in HG. extensionality in HG. rewrite <- HG in H2.
unfold LSub_equiv in HL. extensionality in HL. rewrite <- HL in H3.
apply correctness with (t0 := t0);
try assumption.
Qed.
(* Next steps:
- completeness modulo trace equivalence
- relation to Dominique's abstractions
- relation to Bubel & Hähnle's traces (backwards reasoning)
- different/sufficient notions of trace equivalence
*)
Lemma GComp_not_injective: ~(forall sig sig' G0 L0,
GComp G0 L0 sig = GComp G0 L0 sig' -> sig = sig').
Proof.
remember ((_ !-> AGVar "x")) as sig.
remember (_ !-> AConst 0) as sig'.
remember (_ !-> 0) as G0.
remember (_ !-> 1) as L0.
intro. specialize (H sig sig' G0 L0).
assert (comp_equal: GComp G0 L0 sig = GComp G0 L0 sig'). {
extensionality x. unfold GComp, Aeval. subst. simpl.
apply apply_empty.
}
specialize (H comp_equal). subst.
eapply equal_f in H. rewrite 2 apply_empty in H. discriminate.
Unshelve. exact "x".
Qed.
(*... so that can't be used for completeness *)
Lemma step_unique : forall G0 L0 s s' t0 t t',
(s, t0) ->s (s', t) ->
(s, t0) ->s (s', t') ->
Beval G0 L0 (pc t) = true ->
Beval G0 L0 (pc t') = true ->
t = t'.
Proof.
intros. inversion H; inversion H0; subst;
inversion H8;
try reflexivity;
try assumption;
try (simpl in *; unfold Bapply_t in *;
apply andb_true_iff in H1; destruct H1;
apply andb_true_iff in H2; destruct H2;
try (apply negb_true_iff in H2);
try (apply negb_true_iff in H1);
rewrite H4 in H2; rewrite H1 in H2);
try discriminate.
admit. (* fresh variable again *)
Admitted.
(*... so maybe completeness isn't even interesting in this setting *)
(*(and yet I can't prove it :/)*)
(* more interesting: add some non-determinism *)
(** Completeness modulo trace equivalence *)
(* with empty starting trace while experimenting *)
(* Theorem completeness_reduced : forall s s' tc t t' G0 L0, *)
(* (* there is a concrete computation *) *)
(* @multi_Cstep G0 L0 (s, []) (s', tc) -> *)
(* (* t is an abstraction in the sense of regular completeness *) *)
(* (s, []) ->* (s', t) -> *)
(* Beval G0 L0 (pc t) = true -> *)
(* GComp G0 L0 (acc_GSubst_id t) = acc_GVal G0 L0 tc -> *)
(* LComp G0 L0 (acc_LSubst_id t) = acc_LVal G0 L0 tc -> *)
(* (* and so is t' *) *)
(* (s, []) ->* (s', t') -> *)
(* Beval G0 L0 (pc t') = true -> *)
(* GComp G0 L0 (acc_GSubst_id t') = acc_GVal G0 L0 tc -> *)
(* LComp G0 L0 (acc_LSubst_id t') = acc_LVal G0 L0 tc -> *)
(* (* then t ~ t' *) *)
(* t ~ t'. *)
(* Proof. *)
(* (* this appears not to be true in current formulation *) *)
(* unfold STrace_equiv. unfold GSub_equiv. unfold LSub_equiv. intros. *)
(* splits. *)
(* - rewrite <- H2 in H6. *)
(* admit. (* this is where injectivity would be useful, but it only holds up to Aeval *) *)
(* - rewrite <- H3 in H7. *)
(* admit. (* ditto *) *)
(* - intro. *)
|
! S08A-cant-assert-keyword-nonnull.f90
! In 'c_action_actual_arg_spec', assertion 'keyword' != NULL is incorrect.
! CASE A: rule for 'substring_range_or_arg_list', alternative 5.
!
! An alternate return specifier as the first argument in an actual
! argument list causes the front end to fail an assertion.
! The subroutine definition for reference below is commented out because
! it causes front end to fail another assertion before showing this bug.
! subroutine g(*)
! end subroutine
program p
call g(*100) ! assertion failure: 'keyword' is null
100 continue
end program
|
Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.solinas64_2e448m2e224m1_10limbs.Synthesis.
(* TODO : change this to field once field isomorphism happens *)
Definition carry :
{ carry : feBW_loose -> feBW_tight
| forall a, phiBW_tight (carry a) = (phiBW_loose a) }.
Proof.
Set Ltac Profiling.
Time synthesize_carry ().
Show Ltac Profile.
Time Defined.
Print Assumptions carry.
|
open import Relation.Binary.PropositionalEquality using (_≡_; refl; sym)
open import Function.Equivalence using (_⇔_; equivalence; Equivalence)
open import Data.Bool using (Bool; true; false; if_then_else_)
open import Data.Product using (_×_; _,_; proj₁; proj₂)
open import Data.Sum using (_⊎_)
open import IMP
open import OperationalSemantics
open import Hoare
wp : ∀{l} → com → assn {l} → assn {l}
wp c Q s = ∀ t → ⦅ c , s ⦆⇒ t → Q t
fatto : ∀{P Q : assn} {c}
→ ⊨[ P ] c [ Q ]
→ (∀ s → P s → wp c Q s)
fatto = λ z s z₁ t → z z₁
fatto-converse : ∀{P Q : assn} {c}
→ (∀ s → P s → wp c Q s)
→ ⊨[ P ] c [ Q ]
fatto-converse = (λ z {s} {t} z₁ → z s z₁ t)
wp-hoare : ∀ c {l} {Q : assn {l}}
→ ⊢[ wp c Q ] c [ Q ]
wp-hoare SKIP = Conseq (λ s z → z s Skip) Skip (λ s z → z)
wp-hoare (x ::= a) = Conseq (λ s wpe → wpe (s [ x ::= aval a s ]) Loc) Loc (λ s r → r)
wp-hoare (c :: c₁) = Comp (Conseq (λ s z x x₁ x₂ x₃ → z x₂ (Comp x₁ x₃)) (wp-hoare c) (λ s z → z)) (wp-hoare c₁)
wp-hoare (IF x THEN c ELSE c₁) = If (Conseq (λ s z x x₁ → proj₁ z x (IfTrue (proj₂ z) x₁)) (wp-hoare c) (λ s z → z))
(Conseq (λ s z x x₁ → proj₁ z x (IfFalse (proj₂ z) x₁)) (wp-hoare c₁) (λ s z → z))
wp-hoare (WHILE b DO c) =
Conseq (λ s x → x)
(While (Conseq (λ s z x x₁ x₂ x₃ → proj₁ z x₂ (WhileTrue (proj₂ z) x₁ x₃))
(wp-hoare c)
(λ s z → z)))
(λ s z → proj₁ z s (WhileFalse (proj₂ z)))
completeness : ∀ c {P Q : assn}
→ ⊨[ P ] c [ Q ]
→ ⊢[ P ] c [ Q ]
completeness c cc = Conseq (fatto cc) (wp-hoare c) (λ r x → x)
|
{-# OPTIONS --prop --rewriting #-}
open import Examples.Sorting.Sequential.Comparable
module Examples.Sorting.Sequential.MergeSort.Split (M : Comparable) where
open Comparable M
open import Examples.Sorting.Sequential.Core M
open import Calf costMonoid
open import Calf.Types.Nat
open import Calf.Types.List
open import Calf.Types.Bounded costMonoid
open import Relation.Binary.PropositionalEquality as Eq using (_≡_; refl)
open import Data.Product using (_×_; _,_; ∃; proj₁; proj₂)
open import Data.Nat as Nat using (ℕ; zero; suc; _+_; _*_; ⌊_/2⌋; ⌈_/2⌉)
open import Data.Nat.Properties as N using (module ≤-Reasoning)
pair = Σ++ (list A) λ _ → (list A)
split/clocked : cmp (Π nat λ _ → Π (list A) λ _ → F pair)
split/clocked zero l = ret ([] , l)
split/clocked (suc k) [] = ret ([] , [])
split/clocked (suc k) (x ∷ xs) = bind (F pair) (split/clocked k xs) λ (l₁ , l₂) → ret (x ∷ l₁ , l₂)
split/clocked/correct : ∀ k k' l → k + k' ≡ length l →
◯ (∃ λ l₁ → ∃ λ l₂ → split/clocked k l ≡ ret (l₁ , l₂) × length l₁ ≡ k × length l₂ ≡ k' × l ↭ (l₁ ++ l₂))
split/clocked/correct zero k' l refl u = [] , l , refl , refl , refl , refl
split/clocked/correct (suc k) k' (x ∷ xs) h u =
let (l₁ , l₂ , ≡ , h₁ , h₂ , ↭) = split/clocked/correct k k' xs (N.suc-injective h) u in
x ∷ l₁ , l₂ , Eq.cong (λ e → bind (F pair) e _) ≡ , Eq.cong suc h₁ , h₂ , prep x ↭
split/clocked/cost : cmp (Π nat λ _ → Π (list A) λ _ → cost)
split/clocked/cost _ _ = zero
split/clocked≤split/clocked/cost : ∀ k l → IsBounded pair (split/clocked k l) (split/clocked/cost k l)
split/clocked≤split/clocked/cost zero l = bound/ret
split/clocked≤split/clocked/cost (suc k) [] = bound/ret
split/clocked≤split/clocked/cost (suc k) (x ∷ xs) = bound/bind/const zero zero (split/clocked≤split/clocked/cost k xs) λ _ → bound/ret
split : cmp (Π (list A) λ _ → F pair)
split l = split/clocked ⌊ length l /2⌋ l
split/correct : ∀ l →
◯ (∃ λ l₁ → ∃ λ l₂ → split l ≡ ret (l₁ , l₂) × length l₁ ≡ ⌊ length l /2⌋ × length l₂ ≡ ⌈ length l /2⌉ × l ↭ (l₁ ++ l₂))
split/correct l = split/clocked/correct ⌊ length l /2⌋ ⌈ length l /2⌉ l (N.⌊n/2⌋+⌈n/2⌉≡n (length l))
split/cost : cmp (Π (list A) λ _ → cost)
split/cost l = split/clocked/cost ⌊ length l /2⌋ l
split≤split/cost : ∀ l → IsBounded pair (split l) (split/cost l)
split≤split/cost l = split/clocked≤split/clocked/cost ⌊ length l /2⌋ l
|
export GoToDoor
using Random
mutable struct GoToDoor{W<:GridWorldBase} <: AbstractGridWorld
world::W
agent_pos::CartesianIndex{2}
agent::Agent
end
function GoToDoor(;n=8, agent_start_pos=CartesianIndex(2,2), rng=Random.GLOBAL_RNG)
objects = (EMPTY, WALL, (Door(c) for c in COLORS)...)
world = GridWorldBase(objects, n, n)
world[EMPTY, :, :] .= true
world[WALL, [1,n], 1:n] .= true
world[EMPTY, [1,n], 1:n] .= false
world[WALL, 1:n, [1,n]] .= true
world[EMPTY, 1:n, [1,n]] .= false
door_pos = [(rand(rng, 2:n-1),1), (rand(rng, 2:n-1),n), (1,rand(rng, 2:n-1)), (n,rand(rng, 2:n-1))]
door_colors = COLORS[randperm(rng, length(COLORS))][1:length(door_pos)]
for (c, p) in zip(door_colors, door_pos)
world[Door(c), p...] = true
world[WALL, p...] = false
end
GoToDoor(world, agent_start_pos, Agent(dir=RIGHT))
end
function (w::GoToDoor)(::MoveForward)
dir = get_dir(w.agent)
dest = dir(w.agent_pos)
if dest ∈ CartesianIndices((size(w.world, 2), size(w.world, 3))) && !w.world[WALL,dest]
w.agent_pos = dest
end
w
end |
If $f$ is convex on $t$, and $S \subseteq t$, then $f$ is convex on $S$. |
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Lemma conj23eqsynthconj4 : forall (lv0 : natural) (lv1 : natural) (lv2 : natural), (@eq natural (plus (mult lv0 lv1) lv2) (plus (mult lv1 lv0) lv2)).
Admitted.
QuickChick conj23eqsynthconj4.
|
If $C$ is a finite affinely dependent set, then there exist two disjoint subsets $m$ and $p$ of $C$ such that $m \cup p = C$ and the convex hulls of $m$ and $p$ intersect. |
Townsend recently discussed at least a year @-@ long hiatus , beginning after the Z ² show taking place at the Royal Albert Hall on April 13 , 2015 . During the indefinitely long break Townsend intends to " recharge his batteries " , " get some inspiration and experiences " and to " see what the next chapter holds " for him .
|
# MAT 221 Calculus I
## April 9, 2020
Today's Agenda:
1. Continuous Function
2. Intermediate Value Theorem
3. Exercises
## Derivatives of Logarithmic Functions
Implicit differentation, which we explored in the last section, can also be employed to find the derivatives of logarithmic functions, which are of the form $y = \log_a{x}$. This also includes the natural logarithmic function $y = \ln{x}$.
## Proving $\frac{d}{dx} (\log_a{x}) = \frac{1}{x \ln{a}}$
Taking advantage of the fact that $y = \log_a{x}$ can be rewritten as an exponential equation, $a^y = x$, we can state the derivative of $\log_a{x}$ as:
$$ \frac{d}{dx} (\log_a{x}) = \frac{1}{x \ln{a}} $$
This can be proved by applying implicit differentiation. First we find the deriative of $y = a^x$. Start by taking the $\ln{}$ of both sides of the equation:
$$ \ln{y} = \ln{a^x} $$
Then exponentiate both sides:
$$ e^{\ln{y}} = e^{\ln{a^x}} $$
As $a^{\ln{x}}$ = $x \ln{e}$, and $\ln{e} = 1$, we can simplify the left side of the equation to remove the exponent and natural log.
$$ y = e^{\ln{a^x}} $$
Proceed to find the derivative by using the chain rule:
$$ \frac{dx}{dy} = e^{\ln{a^x}}, \qquad y = e^u, \qquad u = \ln{a^x} = x\ln{a} $$
$$ \frac{dy}{du} = e^u, \qquad \frac{du}{dx} = \ln{a} $$
$$ \ln{a} e^u = \ln{a} e^{\ln{a}} $$
Just as $\ln{e} = 1$, $e^{\ln{x}} = x$, thus:
$$ \frac{dy}{dx} \ln{a} \space a^x $$
Returning to the derivative of $y = \log_a{x}$, rewrite the equation:
$$ a^y = x $$
Now that we know $\frac{dy}{dx} \ln{a} \space a^x$, we can derive the equation implicitly with respect to $x$:
$$ \frac{d}{dx} a^y = \frac{d}{dx} x $$
$$ a^y \ln{a} \frac{dy}{dx} = 1 $$
Then, dividing by $a^y \ln{a}$:
$$ \frac{d}{dx} \log_a{x} = \frac{1}{x \ln{a}} $$
## Proving $\frac{d}{dx} (\ln{x}) = \frac{1}{x}$
Start with $y = \ln{x}$. Exponentate both sides of the equation:
$$ e^y = e^{\ln{x}} $$
Recalling that $e^{\ln{x}} = x$:
$$ e^y = x $$
Applying implicit differentiation:
$$ \frac{dy}{dx} e^y = \frac{d}{dx} x $$
$$ e^y \frac{dy}{dx} = 1 $$
Using the fact that $e^y = x$, we can substitute $x$ for $e^y$:
$$ x \frac{dy}{dx} = 1 $$
Divide by $x$:
$$ \frac{dy}{dx} = \frac{1}{x} $$
## Examples
```python
from sympy import symbols, diff, simplify, sin, cos, log, tan, sqrt, init_printing
from mpmath import ln, e
init_printing()
x = symbols('x')
y = symbols('y')
```
### Example 1: Calculate the derivative of $f(x) = \sin{\ln{x}}$
Apply the Chain Rule:
$$ y = \sin{u}, \qquad u = \ln{x} $$
As we proved above, $\frac{du}{dx} = \frac{1}{x}$, therefore:
$$ \frac{dy}{dx} = \frac{1}{x} \cos{\ln{x}} $$
```python
diff(sin(ln(x)))
```
## Example 2: Find the derivative of the function $f(x) = \log_2{(1 - 3x)}$
Using the fact that $\frac{d}{dx} (\log_a{x}) = \frac{1}{x \ln{a}}$, apply the Chain Rule:
$$ y = \log_2{u}, \qquad u = 1 - 3x $$
$$ \frac{dy}{du} = \frac{1}{u \ln{2}}, \qquad \frac{du}{dx} = 3 $$
$$ \frac{dy}{dx} = \frac{3}{(1 - 3x) \ln{2}} $$
```python
diff(log((1 - 3 * x), 2))
```
### Example 3: Find the derivative to the function $\sqrt[5]{\ln{x}}$
First, rewrite the equation as $\sqrt[5]{\ln{x}} = (\ln{x})^{\frac{1}{5}}$. Then, apply the Chain Rule:
$$ y = u^\frac{1}{5}, \qquad u = \ln{x} $$
$$ \frac{dy}{du} = \frac{1}{5} (\ln{x})^{-\frac{4}{5}}, \qquad \frac{du}{dx} = \frac{1}{x} $$
$$ \frac{dy}{dx} = \frac{1}{x} \space \frac{1}{5} (\ln{x})^{-\frac{4}{5}} = \frac{(\ln{x})^{-\frac{4}{5}}}{5x} = \frac{1}{5x \ln^\frac{4}{5}{x}} $$
```python
diff((log(x)) ** (1/5))
```
### Example 4: Find the derivative of $f(x) = \sin{x} \ln{5x}$
Start by using the Product rule, $u \frac{dv}{dx} + v \frac{du}{dx}$:
$$ u = \sin{x}, \qquad v = \ln{5x} $$
$$ \frac{dy}{dx} = (\sin{x}) \frac{dv}{dx} \ln{5x} + (\ln{5x}) \frac{du}{dx} \sin{x} $$
$$ \frac{dy}{dx} = \frac{\sin{x}}{x} + \ln{5x} \cos{x} $$
```python
diff(sin(x) * log(5 * x))
```
### Example 5: Find the derivative of the function $F(x) = \ln{\frac{(2x + 1)^3}{(3x - 1)^4}}$
Here, rather than applying the Chain Rule and then the Quotient Rule to the inner equation, which would result in a very lengthy and tedious derivation, we can take advantage of one of the logarithmic identities, $\ln{ab} = \ln{a} + \ln{b}$. Thus, we can rewrite the function as:
$$ F(x) = \ln{(2x + 1)^3} + \ln{\frac{1}{(3x - 1)^4}} $$
With the rewritten function, we can leverage another logarithmic identity, $\ln{a^b} = b \ln{a}$ to simplify the derivation. We can therefore rewrite the function again as:
$$ F(x) = 3 \ln{(2x + 1)} - 4 \ln{(3x - 1)} $$
Then, proceed to differentiate the function:
$$ \frac{dy}{dx} = 3 \frac{d}{dx} \ln{(2x + 1)} - 4 \frac{d}{dx} \ln{(3x - 1)} $$
$$ \frac{dy}{dx} = 3 \frac{2}{2x + 1} - 4 \frac{3}{3x - 1} = \frac{6}{2x + 1} - \frac{12}{3x - 1} $$
```python
simplify(diff(log((2 * x + 1) ** 3 / (3 * x - 1) ** 4)))
```
## References
Stewart, J. (2007). Essential calculus: Early transcendentals. Belmont, CA: Thomson Higher Education.
|
theory Chapter2
imports Main
begin
value "1 + (2::nat)"
value "1 + (2::int)"
value "1 - (2::nat)"
value "1 - (2::int)"
value "[a,b] @ [c,d]"
fun add :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"add 0 n = n" |
"add (Suc m) n = Suc(add m n)"
lemma add_assoc : "add (add m n) p = add m (add n p)"
apply (induction m)
apply auto
done
lemma add_aux1 [simp] : "n = add n 0"
apply (induction n)
apply auto
done
lemma add_aux2 [simp] : "Suc (add n m) = add n (Suc m)"
apply (induction n)
apply auto
done
lemma add_comm: "add m n = add n m"
apply (induction m)
apply auto
done
fun double :: "nat \<Rightarrow> nat" where
"double 0 = 0" |
"double (Suc n) = Suc (Suc (double n))"
lemma double_add: "double m = add m m"
apply (induction m)
apply auto
done
fun count :: "'a list \<Rightarrow> 'a \<Rightarrow> nat" where
"count [] x = 0" |
"count (x#xs) y = (if x = y then (1+ count xs y) else (count xs y))"
theorem "count xs x \<le> length xs"
apply (induction xs)
apply auto
done
fun snoc :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a list" where
"snoc [] y = [y]" |
"snoc (x#xs) y = x#(snoc xs y)"
value "snoc [1,2,3] (4::int)"
fun reverse :: "'a list \<Rightarrow> 'a list" where
"reverse [] = []" |
"reverse (x#xs) = snoc (reverse xs) x"
value "reverse [1,2,3,(4::int)]"
value "reverse [(4::int)]"
lemma "sum_upto n = n * (n+1) div 2"
apply (induction n)
apply auto
done
datatype 'a tree = Tip | Node "'a tree" 'a "'a tree"
fun contents :: "'a tree \<Rightarrow> 'a list" where
"contents Tip = []" |
"contents (Node l a r) = a#(contents l @ contents r)"
fun sum_tree :: "nat tree \<Rightarrow> nat" where
"sum_tree Tip = 0" |
"sum_tree (Node l a r) = a + sum_tree l + sum_tree r"
lemma "sum_tree t = sum_list(contents t)"
apply (induction t)
apply auto
done
datatype 'a tree2 = Tip 'a | Node "'a tree2" 'a "'a tree2"
fun mirror :: "'a tree2 \<Rightarrow> 'a tree2" where
"mirror (Tip a) = Tip a" |
"mirror (Node l a r) = Node (mirror r) a (mirror l)"
fun pre_order :: "'a tree2 \<Rightarrow> 'a list" where
"pre_order (Tip a) = [a]" |
"pre_order (Node l a r) = a # (pre_order l @ pre_order r)"
fun post_order :: "'a tree2 \<Rightarrow> 'a list" where
"post_order (Tip a) = [a]" |
"post_order (Node l a r) = (post_order l) @ (post_order r) @ [a]"
value "rev (post_order (Node (Node (Tip 1) 4 (Tip 2)) 3 (Node (Tip 0) 7 (Tip (4::int)))))"
value "pre_order (mirror (Node (Node (Tip 1) 4 (Tip 2)) 3 (Node (Tip 0) 7 (Tip (4::int)))))"
lemma "pre_order (mirror t) = rev (post_order t)"
apply (induction t)
apply auto
done
end
|
/-
Copyright (c) 2020 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.group.opposite
import group_theory.group_action.defs
/-!
# Scalar actions on and by `Mᵐᵒᵖ`
This file defines the actions on the opposite type `has_smul R Mᵐᵒᵖ`, and actions by the opposite
type, `has_smul Rᵐᵒᵖ M`.
Note that `mul_opposite.has_smul` is provided in an earlier file as it is needed to provide the
`add_monoid.nsmul` and `add_comm_group.gsmul` fields.
-/
variables (α : Type*)
/-! ### Actions _on_ the opposite type
Actions on the opposite type just act on the underlying type.
-/
namespace mul_opposite
@[to_additive] instance (R : Type*) [monoid R] [mul_action R α] : mul_action R αᵐᵒᵖ :=
{ one_smul := λ x, unop_injective $ one_smul R (unop x),
mul_smul := λ r₁ r₂ x, unop_injective $ mul_smul r₁ r₂ (unop x),
.. mul_opposite.has_smul α R }
instance (R : Type*) [monoid R] [add_monoid α] [distrib_mul_action R α] :
distrib_mul_action R αᵐᵒᵖ :=
{ smul_add := λ r x₁ x₂, unop_injective $ smul_add r (unop x₁) (unop x₂),
smul_zero := λ r, unop_injective $ smul_zero r,
.. mul_opposite.mul_action α R }
instance (R : Type*) [monoid R] [monoid α] [mul_distrib_mul_action R α] :
mul_distrib_mul_action R αᵐᵒᵖ :=
{ smul_mul := λ r x₁ x₂, unop_injective $ smul_mul' r (unop x₂) (unop x₁),
smul_one := λ r, unop_injective $ smul_one r,
.. mul_opposite.mul_action α R }
instance {M N} [has_smul M N] [has_smul M α] [has_smul N α] [is_scalar_tower M N α] :
is_scalar_tower M N αᵐᵒᵖ :=
⟨λ x y z, unop_injective $ smul_assoc _ _ _⟩
@[to_additive] instance {M N} [has_smul M α] [has_smul N α] [smul_comm_class M N α] :
smul_comm_class M N αᵐᵒᵖ :=
⟨λ x y z, unop_injective $ smul_comm _ _ _⟩
instance (R : Type*) [has_smul R α] [has_smul Rᵐᵒᵖ α] [is_central_scalar R α] :
is_central_scalar R αᵐᵒᵖ :=
⟨λ r m, unop_injective $ op_smul_eq_smul _ _⟩
lemma op_smul_eq_op_smul_op {R : Type*} [has_smul R α] [has_smul Rᵐᵒᵖ α] [is_central_scalar R α]
(r : R) (a : α) : op (r • a) = op r • op a :=
(op_smul_eq_smul r (op a)).symm
lemma unop_smul_eq_unop_smul_unop {R : Type*} [has_smul R α] [has_smul Rᵐᵒᵖ α]
[is_central_scalar R α] (r : Rᵐᵒᵖ) (a : αᵐᵒᵖ) : unop (r • a) = unop r • unop a :=
(unop_smul_eq_smul r (unop a)).symm
end mul_opposite
/-! ### Actions _by_ the opposite type (right actions)
In `has_mul.to_has_smul` in another file, we define the left action `a₁ • a₂ = a₁ * a₂`. For the
multiplicative opposite, we define `mul_opposite.op a₁ • a₂ = a₂ * a₁`, with the multiplication
reversed.
-/
open mul_opposite
/-- Like `has_mul.to_has_smul`, but multiplies on the right.
See also `monoid.to_opposite_mul_action` and `monoid_with_zero.to_opposite_mul_action_with_zero`. -/
@[to_additive] instance has_mul.to_has_opposite_smul [has_mul α] : has_smul αᵐᵒᵖ α :=
{ smul := λ c x, x * c.unop }
@[to_additive] lemma op_smul_eq_mul [has_mul α] {a a' : α} : op a • a' = a' * a := rfl
@[simp, to_additive] lemma mul_opposite.smul_eq_mul_unop [has_mul α] {a : αᵐᵒᵖ} {a' : α} :
a • a' = a' * a.unop := rfl
/-- The right regular action of a group on itself is transitive. -/
@[to_additive "The right regular action of an additive group on itself is transitive."]
instance mul_action.opposite_regular.is_pretransitive {G : Type*} [group G] :
mul_action.is_pretransitive Gᵐᵒᵖ G :=
⟨λ x y, ⟨op (x⁻¹ * y), mul_inv_cancel_left _ _⟩⟩
@[to_additive] instance semigroup.opposite_smul_comm_class [semigroup α] :
smul_comm_class αᵐᵒᵖ α α :=
{ smul_comm := λ x y z, (mul_assoc _ _ _) }
@[to_additive] instance semigroup.opposite_smul_comm_class' [semigroup α] :
smul_comm_class α αᵐᵒᵖ α :=
smul_comm_class.symm _ _ _
instance comm_semigroup.is_central_scalar [comm_semigroup α] : is_central_scalar α α :=
⟨λ r m, mul_comm _ _⟩
/-- Like `monoid.to_mul_action`, but multiplies on the right. -/
@[to_additive] instance monoid.to_opposite_mul_action [monoid α] : mul_action αᵐᵒᵖ α :=
{ smul := (•),
one_smul := mul_one,
mul_smul := λ x y r, (mul_assoc _ _ _).symm }
instance is_scalar_tower.opposite_mid {M N} [has_mul N] [has_smul M N]
[smul_comm_class M N N] :
is_scalar_tower M Nᵐᵒᵖ N :=
⟨λ x y z, mul_smul_comm _ _ _⟩
instance smul_comm_class.opposite_mid {M N} [has_mul N] [has_smul M N]
[is_scalar_tower M N N] :
smul_comm_class M Nᵐᵒᵖ N :=
⟨λ x y z, by { induction y using mul_opposite.rec, simp [smul_mul_assoc] }⟩
-- The above instance does not create an unwanted diamond, the two paths to
-- `mul_action αᵐᵒᵖ αᵐᵒᵖ` are defeq.
example [monoid α] : monoid.to_mul_action αᵐᵒᵖ = mul_opposite.mul_action α αᵐᵒᵖ := rfl
/-- `monoid.to_opposite_mul_action` is faithful on cancellative monoids. -/
@[to_additive] instance left_cancel_monoid.to_has_faithful_opposite_scalar [left_cancel_monoid α] :
has_faithful_smul αᵐᵒᵖ α :=
⟨λ x y h, unop_injective $ mul_left_cancel (h 1)⟩
/-- `monoid.to_opposite_mul_action` is faithful on nontrivial cancellative monoids with zero. -/
instance cancel_monoid_with_zero.to_has_faithful_opposite_scalar
[cancel_monoid_with_zero α] [nontrivial α] : has_faithful_smul αᵐᵒᵖ α :=
⟨λ x y h, unop_injective $ mul_left_cancel₀ one_ne_zero (h 1)⟩
|
module Cats.Category.Mon where
open import Data.Unit using (⊤)
open import Relation.Binary using (Setoid ; _Preserves₂_⟶_⟶_ ; IsEquivalence)
open import Level
open import Cats.Category
open import Cats.Category.Setoids using (Setoids)
open import Cats.Util.Conv
import Cats.Util.Function as Fun
record Monoid l l≈ : Set (suc (l ⊔ l≈)) where
infixr 9 _⊕_
field
Universe : Setoid l l≈
open Setoid Universe public
field
_⊕_ : Carrier → Carrier → Carrier
unit : Carrier
⊕-resp : _⊕_ Preserves₂ _≈_ ⟶ _≈_ ⟶ _≈_
assoc : ∀ {a b c} → (a ⊕ b) ⊕ c ≈ a ⊕ (b ⊕ c)
id-l : ∀ {a} → unit ⊕ a ≈ a
id-r : ∀ {a} → a ⊕ unit ≈ a
module ≈ = IsEquivalence isEquivalence
module _ (l l≈ : Level) where
infixr 9 _∘_
infixr 4 _≈_
module Setoids = Category (Setoids l l≈)
Obj : Set (suc (l ⊔ l≈))
Obj = Monoid l l≈
record _⇒_ (M N : Obj) : Set (l ⊔ l≈) where
private
module M = Monoid M
module N = Monoid N
field
arr : M.Universe Setoids.⇒ N.Universe
unit : (arr ⃗) M.unit N.≈ N.unit
commute : ∀ {n m} → (arr ⃗) (n M.⊕ m) N.≈ (arr ⃗) n N.⊕ (arr ⃗) m
open Cats.Category.Setoids._⇒_ arr public using (resp)
open _⇒_ using (unit ; commute ; resp)
instance
HasArrow-⇒ : ∀ M N → HasArrow (M ⇒ N) _ _ _
HasArrow-⇒ M N = record { Cat = Setoids l l≈ ; _⃗ = _⇒_.arr }
id : ∀ {M} → M ⇒ M
id {M} = record
{ arr = Setoids.id
; unit = refl
; commute = refl
}
where
open Monoid M using (refl)
_≈_ : ∀ {M N} (f g : M ⇒ N) → Set (l≈ ⊔ l)
_≈_ = Setoids._≈_ Fun.on _⃗
_∘_ : ∀ {M N O} → (N ⇒ O) → (M ⇒ N) → (M ⇒ O)
_∘_ {M} {N} {O} f g = record
{ arr = f ⃗ Setoids.∘ g ⃗
; unit = trans (resp f (unit g)) (unit f)
; commute = trans (resp f (commute g)) (commute f)
}
where
open Monoid O using (trans)
Mon : Category (suc (l≈ ⊔ l)) (l≈ ⊔ l) (l≈ ⊔ l)
Mon = record
{ Obj = Obj
; _⇒_ = _⇒_
; _≈_ = _≈_
; id = id
; _∘_ = _∘_
; equiv = Fun.on-isEquivalence _⃗ Setoids.equiv
; ∘-resp = Setoids.∘-resp
; id-r = Setoids.id-r
; id-l = Setoids.id-l
; assoc = λ { {f = f} {g} {h} → Setoids.assoc {f = f ⃗} {g ⃗} {h ⃗} }
}
monoidAsCategory : ∀ {l l≈} → Monoid l l≈ → Category zero l l≈
monoidAsCategory M = record
{ Obj = ⊤
; _⇒_ = λ _ _ → M.Carrier
; _≈_ = M._≈_
; id = M.unit
; _∘_ = M._⊕_
; equiv = M.isEquivalence
; ∘-resp = M.⊕-resp
; id-r = M.id-r
; id-l = M.id-l
; assoc = M.assoc
}
where
module M = Monoid M
|
If two sets $A$ and $B$ are almost equal, then they have the same measure. |
A Bullseye View “Perspectives” is a forum for Target’s top executives to share their point of view on everything from industry trends to best business practices. In the story below, Jodee Kozlak, Executive Vice President and Chief Human Resources Officer, details Target’s decision to sign the amicus brief on marriage equality.
If you’ve been a fan or follower of Target for some time, you’ve likely heard us say those words. You may have heard us talk about our long-standing commitment to inclusivity and diversity. Those aren’t just words. They are how we conduct ourselves – as a business and as a team. And as a part of that belief, we continually evaluate where we are as a company to ensure we are taking steps that balance doing what is right for our business, guests and for our team.
It is in that same spirit that, this week, Target joined several other national companies to sign on to an amicus brief in support of marriage equality. The brief is currently pending in the Seventh Circuit. |
[STATEMENT]
lemma rvars_pivot_eq:
"\<lbrakk>x\<^sub>j \<in> rvars_eq eq; lhs eq \<notin> rvars_eq eq \<rbrakk> \<Longrightarrow> rvars_eq (pivot_eq eq x\<^sub>j) = {lhs eq} \<union> (rvars_eq eq - {x\<^sub>j})"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>x\<^sub>j \<in> rvars_eq eq; lhs eq \<notin> rvars_eq eq\<rbrakk> \<Longrightarrow> rvars_eq (pivot_eq eq x\<^sub>j) = {lhs eq} \<union> (rvars_eq eq - {x\<^sub>j})
[PROOF STEP]
using vars_pivot_eq
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>?x\<^sub>j \<in> rvars_eq ?eq; lhs ?eq \<notin> rvars_eq ?eq\<rbrakk> \<Longrightarrow> let eq' = pivot_eq ?eq ?x\<^sub>j in lhs eq' = ?x\<^sub>j \<and> rvars_eq eq' = {lhs ?eq} \<union> (rvars_eq ?eq - {?x\<^sub>j})
goal (1 subgoal):
1. \<lbrakk>x\<^sub>j \<in> rvars_eq eq; lhs eq \<notin> rvars_eq eq\<rbrakk> \<Longrightarrow> rvars_eq (pivot_eq eq x\<^sub>j) = {lhs eq} \<union> (rvars_eq eq - {x\<^sub>j})
[PROOF STEP]
by (simp add: Let_def) |
[STATEMENT]
lemma lines_comm: "lines P Q = lines Q P"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. lines P Q = lines Q P
[PROOF STEP]
using lines_def
[PROOF STATE]
proof (prove)
using this:
lines ?P ?Q \<equiv> {l. incid ?P l \<and> incid ?Q l}
goal (1 subgoal):
1. lines P Q = lines Q P
[PROOF STEP]
by auto |
[STATEMENT]
lemma real_of_nat_Sup:
assumes "A \<noteq> {}" "bdd_above A"
shows "of_nat (Sup A) = (SUP a\<in>A. of_nat a :: real)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. real (Sup A) = Sup (real ` A)
[PROOF STEP]
proof (intro antisym)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. real (Sup A) \<le> Sup (real ` A)
2. Sup (real ` A) \<le> real (Sup A)
[PROOF STEP]
show "(SUP a\<in>A. of_nat a::real) \<le> of_nat (Sup A)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Sup (real ` A) \<le> real (Sup A)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
A \<noteq> {}
bdd_above A
goal (1 subgoal):
1. Sup (real ` A) \<le> real (Sup A)
[PROOF STEP]
by (intro cSUP_least of_nat_mono) (auto intro: cSup_upper)
[PROOF STATE]
proof (state)
this:
Sup (real ` A) \<le> real (Sup A)
goal (1 subgoal):
1. real (Sup A) \<le> Sup (real ` A)
[PROOF STEP]
have "Sup A \<in> A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Sup A \<in> A
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
A \<noteq> {}
bdd_above A
goal (1 subgoal):
1. Sup A \<in> A
[PROOF STEP]
by (auto simp: Sup_nat_def bdd_above_nat)
[PROOF STATE]
proof (state)
this:
Sup A \<in> A
goal (1 subgoal):
1. real (Sup A) \<le> Sup (real ` A)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
Sup A \<in> A
[PROOF STEP]
show "of_nat (Sup A) \<le> (SUP a\<in>A. of_nat a::real)"
[PROOF STATE]
proof (prove)
using this:
Sup A \<in> A
goal (1 subgoal):
1. real (Sup A) \<le> Sup (real ` A)
[PROOF STEP]
by (intro cSUP_upper bdd_above_image_mono assms) (auto simp: mono_def)
[PROOF STATE]
proof (state)
this:
real (Sup A) \<le> Sup (real ` A)
goal:
No subgoals!
[PROOF STEP]
qed |
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Lemma conj3eqsynthconj1 : forall (lv0 : natural) (lv1 : natural), (@eq natural (plus lv0 lv1) (plus lv1 (plus Zero lv0))).
Admitted.
QuickChick conj3eqsynthconj1.
|
function [predictedCluster,centroids,eigens] = kernelkmeans(Kn, k)
[H, ~] = eigs(Kn, k);
H_normalized = H ./ repmat(sqrt(sum(H.^2, 2)), 1, k);
predictedCluster = kmeans(H_normalized, k);
eigens = H;
centroids = zeros(k,k);
for i = 1:k
centroids(i,:) = sum(H_normalized(predictedCluster==i,:),1)/size(H_normalized(predictedCluster==i,:),1);
end
end
|
Inductive nat : Type :=
| O : nat
| S : nat -> nat.
Definition pred (n : nat) : nat :=
match n with
| O => O
| S n' => n'
end.
Definition succ (n:nat) :nat :=
match n with
| O => (S O)
| S n' => S (S n')
end.
Definition minustwo (n: nat) : nat :=
match n with
| O => O
| S O => O
| S (S n') => n'
end.
Fixpoint evenb (n:nat) : bool :=
match n with
| O => true
| S O => false
| S n' => negb (evenb n')
end.
Definition oddb (n:nat) : bool := negb (evenb n).
Fixpoint plus (n:nat) (m:nat) : nat :=
match n with
| O => m
| S n' => S (plus n' m)
end.
Fixpoint mult (n m :nat) : nat :=
match n with
| O => O
| S O => m
| S n' => plus m (mult n' m)
end.
Fixpoint minus (n m : nat) : nat :=
match n, m with
| O, _ => O
| S n', O => n
| S n, S m => minus n m
end.
Fixpoint exp (base power :nat) : nat :=
match power with
| O => S O
| S n => mult base (exp base n)
end.
Fixpoint factorial (n:nat) : nat :=
match n with
| O => S O
| S O => S O
| S n' => mult n (factorial n')
end.
Notation "x + y" := (plus x y)
(at level 50, left associativity)
: nat_scope.
Notation "x - y" := (minus x y)
(at level 50,left associativity)
: nat_scope.
Notation "x * y" := (mult x y)
(at level 40,left associativity)
: nat_scope.
Fixpoint beq_nat (n m : nat) : bool :=
match n with
| O => match m with
| O => true
| S m' => false
end
| S n' => match m with
| O => false
| S m' => (beq_nat n' m')
end
end.
Fixpoint blt_nat (n m : nat) : bool :=
match n with
| O => match m with
| O => false
| S _ => true
end
| S n' => match m with
| O => false
| S m' => blt_nat n' m'
end
end.
Inductive bin : Type :=
| Z : bin
| T : bin -> bin
| T' : bin -> bin.
Fixpoint incr (n : bin) : bin :=
match n with
| Z => T' Z
| T n' => T' n'
| T' n' => T (incr n')
end.
Fixpoint bin_pred (n: bin) : bin :=
match n with
| Z => Z
| T Z => Z
| T' Z => Z
| T' n' => T n'
| T n' => T' (bin_pred n')
end.
Fixpoint bin_to_nat (n: bin) : nat :=
match n with
| Z => O
| T' n' => succ (bin_to_nat (T n'))
| T n' => succ (bin_to_nat (T' (bin_pred n')))
end.
|
Require Import init.
Require Import module_category.
Require Import algebra_category.
Require Import linear_grade.
Require Import linear_subspace.
Require Import tensor_algebra.
Require Import nat.
Require Import set.
Require Import unordered_list.
Require Import ring_ideal.
Require Export exterior_construct.
(* begin hide *)
Section ExteriorGrade.
Local Arguments grade_subspace : simpl never.
(* end hide *)
Context {F : CRingObj} (V : ModuleObj F).
(* begin hide *)
Let UP := cring_plus F.
Let UZ := cring_zero F.
Let UN := cring_neg F.
Let UPC := cring_plus_comm F.
Let UPZ := cring_plus_lid F.
Let UPN := cring_plus_linv F.
Let UO := cring_one F.
Existing Instances UP UZ UN UPC UPZ UPN UO.
Let EP := ext_plus V.
Let EZ := ext_zero V.
Let EN := ext_neg V.
Let EPC := ext_plus_comm V.
Let EPA := ext_plus_assoc V.
Let EPZ := ext_plus_lid V.
Let EPN := ext_plus_linv V.
Let EM := ext_mult V.
Let EO := ext_one V.
Let ESM := ext_scalar V.
Existing Instances EP EZ EN EPC EPA EPZ EPN EM EO ESM.
Let TP := algebra_plus (tensor_algebra V).
Let TZ := algebra_zero (tensor_algebra V).
Let TN := algebra_neg (tensor_algebra V).
Let TPA := algebra_plus_assoc (tensor_algebra V).
Let TPC := algebra_plus_comm (tensor_algebra V).
Let TPZ := algebra_plus_lid (tensor_algebra V).
Let TPN := algebra_plus_linv (tensor_algebra V).
Let TSM := algebra_scalar (tensor_algebra V).
Let TSMO := algebra_scalar_id (tensor_algebra V).
Let TSML := algebra_scalar_ldist (tensor_algebra V).
Let TSMR := algebra_scalar_rdist (tensor_algebra V).
Let TM := algebra_mult (tensor_algebra V).
Let TMO := algebra_one (tensor_algebra V).
Let TL := algebra_ldist (tensor_algebra V).
Let TR := algebra_rdist (tensor_algebra V).
Let TML := algebra_mult_lid (tensor_algebra V).
Let TMR := algebra_mult_rid (tensor_algebra V).
Existing Instances TP TZ TN TPA TPC TPZ TPN TSM TSMO TSML TSMR TM TMO TL TR TML TMR.
Let TG := tensor_grade V.
Let TAG := tensor_grade_mult V.
Existing Instances TG TAG.
(* end hide *)
Definition ext_grade_set n (v : ext V)
:= ∃ v', tensor_to_ext V v' = v ∧ of_grade (H9 := TG) n v'.
Lemma ext_grade_zero : ∀ n, ext_grade_set n 0.
Proof.
intros n.
exists 0.
split.
- apply tensor_to_ext_zero.
- apply of_grade_zero.
Qed.
Lemma ext_grade_plus : ∀ n u v,
ext_grade_set n u → ext_grade_set n v → ext_grade_set n (u + v).
Proof.
intros n u v [u' [u_eq nu]] [v' [v_eq nv]].
subst u v.
exists (u' + v').
split.
- apply tensor_to_ext_plus.
- apply of_grade_plus; assumption.
Qed.
Lemma ext_grade_scalar : ∀ n a v, ext_grade_set n v → ext_grade_set n (a · v).
Proof.
intros n a v [v' [v_eq nv]]; subst v.
exists (a · v').
split.
- apply tensor_to_ext_scalar.
- apply of_grade_scalar.
exact nv.
Qed.
Definition ext_grade n := make_subspace
(ext_grade_set n)
(ext_grade_zero n)
(ext_grade_plus n)
(ext_grade_scalar n).
Program Instance exterior_grade : GradedSpace (cring_U F) (ext V) := {
grade_I := nat;
grade_subspace n := ext_grade n;
}.
Next Obligation.
rename H into neq.
rename H0 into iv.
rename H1 into jv.
destruct iv as [v' [v'_eq iv]].
destruct jv as [v'' [v''_eq jv]].
rewrite <- v''_eq.
rewrite <- v''_eq in v'_eq.
clear v v''_eq.
rewrite <- plus_0_anb_a_b in v'_eq.
rewrite <- (tensor_to_ext_neg V) in v'_eq.
rewrite <- (tensor_to_ext_plus V) in v'_eq.
unfold tensor_to_ext, zero in v'_eq; equiv_simpl in v'_eq.
apply equiv_eq in v'_eq; cbn in v'_eq.
rewrite plus_lid in v'_eq.
rewrite neg_plus, neg_neg in v'_eq.
destruct v'_eq as [l l_eq].
apply (f_equal (λ x, grade_project (VG := TG) x j)) in l_eq.
rewrite grade_project_plus in l_eq.
rewrite (grade_project_of_grade _ _ jv) in l_eq.
rewrite grade_project_neg in l_eq.
rewrite (grade_project_of_grade_neq _ _ _ iv neq) in l_eq.
rewrite neg_zero, plus_lid in l_eq.
rewrite l_eq; clear l_eq iv jv v' v'' neq i.
induction l using ulist_induction.
{
rewrite ulist_image_end, ulist_sum_end.
rewrite grade_project_zero.
symmetry; apply tensor_to_ext_zero.
}
rewrite ulist_image_add, ulist_sum_add.
rewrite grade_project_plus.
rewrite (tensor_to_ext_plus V).
rewrite <- IHl; clear IHl l.
rewrite plus_rid.
destruct a as [[a1 a2] [a3 [v a3_eq]]]; subst a3; cbn.
induction a1 as [|a11 a12 i a12i i_z] using grade_induction.
{
do 2 rewrite mult_lanni.
rewrite grade_project_zero.
symmetry; apply tensor_to_ext_zero.
}
do 2 rewrite rdist.
rewrite grade_project_plus.
rewrite (tensor_to_ext_plus V).
rewrite <- IHa1; clear i_z IHa1.
rewrite plus_rid.
induction a2 as [|a21 a22 k a22k k_z] using grade_induction.
{
rewrite mult_ranni.
rewrite grade_project_zero.
symmetry; apply tensor_to_ext_zero.
}
rewrite ldist.
rewrite grade_project_plus.
rewrite (tensor_to_ext_plus V).
rewrite <- IHa2; clear k_z IHa2.
rewrite plus_rid.
assert (of_grade (i + 2 + k)
(a11 * (vector_to_tensor v * vector_to_tensor v) * a21)) as a_grade.
{
apply of_grade_mult; [>|exact a22k].
apply of_grade_mult; [>exact a12i|].
apply of_grade_mult; apply vector_to_tensor_grade.
}
classic_case (i + 2 + k = j) as [j_eq|j_neq].
- rewrite j_eq in a_grade.
rewrite (grade_project_of_grade _ _ a_grade).
unfold tensor_to_ext, zero; equiv_simpl.
symmetry; apply equiv_eq; cbn.
rewrite neg_zero, plus_rid.
assert (ext_ideal_base V (vector_to_tensor v * vector_to_tensor v))
as v2_in by (exists v; reflexivity).
exists (((a11, a21), [_|v2_in]) ː ulist_end).
rewrite ulist_image_add, ulist_sum_add; cbn.
rewrite ulist_image_end, ulist_sum_end.
rewrite plus_rid.
reflexivity.
- rewrite (grade_project_of_grade_neq _ _ _ a_grade j_neq).
symmetry; apply tensor_to_ext_zero.
Qed.
Next Obligation.
equiv_get_value v.
change (to_equiv (ring_ideal.ideal_equiv (ext_ideal V)) v)
with (tensor_to_ext V v).
pose proof (grade_decompose_ex v) as [l [l_eq l_in]].
pose (ST := SubspaceVector (cring_U F) (algebra_V (tensor_algebra V))).
(* TODO: Make this and the definiiton of ext_grade_set fuse somehow *)
pose (ext_subset (S : ST) := λ x : ext V,
∃ x', tensor_to_ext V x' = x ∧ subspace_set (sub_vector_sub S) x').
assert (ext_sub_zero : ∀ S, ext_subset S 0).
{
intros S.
exists 0.
split.
- apply tensor_to_ext_zero.
- apply subspace_zero.
}
assert (ext_sub_plus : ∀ S, ∀ u v,
ext_subset S u → ext_subset S v → ext_subset S (u + v)).
{
clear v l_eq.
intros S u v [u' [u_eq u'_in]] [v' [v_eq v'_in]]; subst u v.
exists (u' + v').
split.
- apply tensor_to_ext_plus.
- apply subspace_plus; assumption.
}
assert (ext_sub_scalar : ∀ S, ∀ a v, ext_subset S v → ext_subset S (a · v)).
{
intros S a u [u' [u_eq u'_in]]; subst u.
exists (a · u').
split.
- apply tensor_to_ext_scalar.
- apply subspace_scalar.
exact u'_in.
}
pose (ext_sub S := make_subspace
(ext_subset S)
(ext_sub_zero S)
(ext_sub_plus S)
(ext_sub_scalar S)).
assert (S_in : ∀ S, ext_subset S (tensor_to_ext V (sub_vector_v S))).
{
intros [S u Su]; cbn.
exists u; cbn.
split.
- reflexivity.
- exact Su.
}
pose (f S := make_subspace_vector (ext_sub S) _ (S_in S)).
exists (ulist_image f l).
split.
- rewrite ulist_image_comp.
unfold f; cbn.
clear l_in ext_subset ext_sub_zero ext_sub_plus ext_sub_scalar
ext_sub S_in f.
subst v.
induction l using ulist_induction.
+ do 2 rewrite ulist_image_end, ulist_sum_end.
apply tensor_to_ext_zero.
+ do 2 rewrite ulist_image_add, ulist_sum_add.
rewrite <- IHl; clear IHl.
apply tensor_to_ext_plus.
- clear l_eq.
induction l using ulist_induction.
+ rewrite ulist_image_end.
apply ulist_prop_end.
+ rewrite ulist_image_add, ulist_prop_add.
apply ulist_prop_add in l_in as [a_in l_in].
split; [>clear l_in IHl|exact (IHl l_in)].
unfold f; cbn.
destruct a_in as [i a_in].
exists i.
apply predicate_ext.
intros x; split; intros [x' [x_eq x'_in]]; subst x.
* exists x'.
split.
-- reflexivity.
-- rewrite <- a_in.
exact x'_in.
* exists x'.
split.
-- reflexivity.
-- rewrite <- a_in in x'_in.
exact x'_in.
Qed.
Next Obligation.
rename H into l_in, H0 into l_uni, H1 into l_z.
assert (∀ i (l : ulist (algebra_V (tensor_algebra V) * algebra_V
(tensor_algebra V) * set_type (ext_ideal_base V))),
tensor_to_ext V (grade_project (ulist_sum (ulist_image
(λ p, fst (fst p) * [snd p|] * snd (fst p)) l)) i) = 0) as lem.
{
clear l l_in l_uni l_z.
intros i l.
induction l using ulist_induction.
- rewrite ulist_image_end, ulist_sum_end.
rewrite grade_project_zero.
apply tensor_to_ext_zero.
- rewrite ulist_image_add, ulist_sum_add.
rewrite grade_project_plus.
rewrite (tensor_to_ext_plus V).
rewrite IHl; clear IHl l.
rewrite plus_rid.
destruct a as [[a1 a2] [a3 a3_in]]; cbn.
induction a1 as [|a1 a1' j a1j a1'j] using grade_induction.
{
do 2 rewrite mult_lanni.
rewrite grade_project_zero.
apply tensor_to_ext_zero.
}
do 2 rewrite rdist.
rewrite grade_project_plus, (tensor_to_ext_plus V).
rewrite IHa1; clear IHa1 a1' a1'j.
rewrite plus_rid.
induction a2 as [|a2 a2' k a2k a2'k] using grade_induction.
{
rewrite mult_ranni.
rewrite grade_project_zero.
apply tensor_to_ext_zero.
}
rewrite ldist.
rewrite grade_project_plus, (tensor_to_ext_plus V).
rewrite IHa2; clear IHa2 a2' a2'k.
rewrite plus_rid.
assert (of_grade (j + 2 + k) (a1 * a3 * a2)) as a_grade.
{
apply grade_mult; [>|exact a2k].
apply grade_mult; [>exact a1j|].
destruct a3_in as [v a3_eq].
subst a3.
apply grade_mult; apply vector_to_tensor_grade.
}
classic_case (j + 2 + k = i) as [eq|neq].
+ rewrite eq in a_grade.
rewrite (grade_project_of_grade _ _ a_grade).
unfold tensor_to_ext, zero; equiv_simpl.
apply equiv_eq; cbn.
rewrite neg_zero, plus_rid.
exists (((a1, a2), [a3|a3_in]) ː ulist_end).
rewrite ulist_image_add, ulist_sum_add; cbn.
rewrite ulist_image_end, ulist_sum_end.
rewrite plus_rid.
reflexivity.
+ rewrite (grade_project_of_grade_neq _ _ _ a_grade neq).
apply tensor_to_ext_zero.
}
apply ulist_prop_split.
intros [A v Av] l' l_eq; cbn in *.
subst l; rename l' into l.
rewrite ulist_image_add, ulist_sum_add in l_z; cbn in l_z.
rewrite ulist_image_add, ulist_unique_add in l_uni; cbn in l_uni.
destruct l_uni as [A_nin l_uni]; clear l_uni.
apply ulist_prop_add in l_in as [[i Ai] l_in]; cbn in *.
pose proof Av as Av'.
rewrite <- Ai in Av'.
destruct Av' as [v' [v'_eq v'i]].
subst v.
assert (∃ lv, tensor_to_ext V (lv - grade_project lv i) =
ulist_sum (ulist_image sub_vector_v l)) as [lv lv_eq].
{
clear v' l_z v'i Av.
pose (l' := ulist_image (λ x, from_equiv (sub_vector_v x)) l).
assert (ulist_sum (ulist_image sub_vector_v l) =
tensor_to_ext V (ulist_sum l')) as l_eq.
{
unfold l'.
clear l' l_in A A_nin i Ai.
induction l using ulist_induction.
- do 2 rewrite ulist_image_end, ulist_sum_end.
symmetry; apply tensor_to_ext_zero.
- do 2 rewrite ulist_image_add, ulist_sum_add.
rewrite (tensor_to_ext_plus V).
rewrite <- IHl; clear IHl.
apply rplus; clear l.
destruct a as [a_sub a]; cbn.
unfold tensor_to_ext.
rewrite from_equiv_eq.
reflexivity.
}
exists (ulist_sum l').
rewrite (tensor_to_ext_plus V).
rewrite l_eq.
apply plus_0_a_ba_b.
rewrite (tensor_to_ext_neg V).
rewrite <- neg_zero.
apply f_equal.
unfold l'.
clear l_eq l'.
induction l using ulist_induction.
- rewrite ulist_image_end, ulist_sum_end.
rewrite grade_project_zero.
symmetry; apply tensor_to_ext_zero.
- rewrite ulist_image_add, in_ulist_add in A_nin.
rewrite not_or in A_nin.
destruct A_nin as [Aa A_nin].
rewrite ulist_prop_add in l_in.
destruct l_in as [a_in l_in].
specialize (IHl A_nin l_in).
clear A_nin l_in.
rewrite ulist_image_add, ulist_sum_add.
rewrite grade_project_plus.
rewrite (tensor_to_ext_plus V).
rewrite <- IHl; clear IHl.
rewrite plus_rid.
assert (∃ v, v = from_equiv (sub_vector_v a) ∧
tensor_to_ext V v = sub_vector_v a) as [v [v_eq1 v_eq2]].
{
exists (from_equiv (sub_vector_v a)).
split; [>reflexivity|].
unfold tensor_to_ext.
apply from_equiv_eq.
}
rewrite <- v_eq1; clear v_eq1.
destruct a_in as [j aj].
destruct a as [B b Bb]; cbn in *.
rename Aa into AB, aj into Bj.
subst b.
pose proof Bb as Bb'.
rewrite <- Bj in Bb'.
destruct Bb' as [v' [v'_eq v'j]].
classic_case (i = j) as [eq|neq].
{
subst.
rewrite <- Ai, <- Bj in AB.
contradiction.
}
symmetry in v'_eq.
unfold tensor_to_ext in v'_eq; equiv_simpl in v'_eq.
apply equiv_eq in v'_eq; cbn in v'_eq.
clear l.
destruct v'_eq as [l l_eq].
rewrite <- plus_rrmove in l_eq.
rewrite l_eq; clear l_eq.
rewrite grade_project_plus.
rewrite neq_sym in neq.
rewrite (grade_project_of_grade_neq _ _ _ v'j neq).
rewrite plus_rid.
clear neq v'j v' Bj Ai j AB Bb v A B.
symmetry; apply lem.
}
rewrite <- lv_eq in l_z.
unfold plus at 1, zero, tensor_to_ext in l_z; equiv_simpl in l_z.
symmetry in l_z.
apply equiv_eq in l_z; cbn in l_z.
rewrite neg_zero, plus_rid in l_z.
destruct l_z as [vl vl_eq].
apply (f_equal (λ x, grade_project (VG := TG) x i)) in vl_eq.
rewrite grade_project_plus in vl_eq.
rewrite (grade_project_of_grade _ _ v'i) in vl_eq.
rewrite grade_project_plus in vl_eq.
rewrite grade_project_neg in vl_eq.
rewrite grade_project_project in vl_eq.
rewrite plus_rinv, plus_rid in vl_eq.
clear lv lv_eq.
rewrite vl_eq.
clear vl_eq A_nin Ai l_in v'i.
symmetry; apply lem.
Qed.
Program Instance exterior_grade_mult : GradedAlgebraObj (cring_U F) (ext V).
Next Obligation.
destruct H as [u' [u_eq u'i]].
destruct H0 as [v' [v_eq v'j]].
subst u v.
exists (u' * v').
split.
- apply tensor_to_ext_mult.
- apply (grade_mult (GradedAlgebraObj := TAG)); assumption.
Qed.
Theorem scalar_to_ext_grade : ∀ a, of_grade 0 (scalar_to_ext V a).
Proof.
intros a.
exists (scalar_to_tensor V a).
split.
- reflexivity.
- apply scalar_to_tensor_grade.
Qed.
Theorem ext_grade_zero_scalar : ∀ v : ext V,
of_grade 0 v ↔ (∃ a, v = scalar_to_ext V a).
Proof.
intros v.
split.
- intros [v' [v_eq v0]].
subst v.
apply tensor_grade_zero_scalar in v0 as [a v'_eq].
subst v'.
exists a.
reflexivity.
- intros [a v_eq]; subst v.
apply scalar_to_ext_grade.
Qed.
Theorem vector_to_ext_grade : ∀ a, of_grade 1 (vector_to_ext V a).
Proof.
intros a.
exists (vector_to_tensor a).
split.
- reflexivity.
- apply vector_to_tensor_grade.
Qed.
Theorem ext_grade_one_vector : ∀ v : ext V,
of_grade 1 v ↔ (∃ a, v = vector_to_ext V a).
Proof.
intros v.
split.
- intros [v' [v_eq v0]].
subst v.
apply tensor_grade_one_vector in v0 as [a v'_eq].
subst v'.
exists a.
reflexivity.
- intros [a v_eq]; subst v.
apply vector_to_ext_grade.
Qed.
Theorem ext_list_grade : ∀ l,
of_grade (H9 := exterior_grade) (list_size l)
(list_prod (list_image (vector_to_ext V) l)).
Proof.
intros l.
induction l.
- rewrite list_image_end.
rewrite list_prod_end.
rewrite <- scalar_to_ext_one.
apply scalar_to_ext_grade.
- rewrite list_image_add.
cbn.
change (list_size (a ꞉ l)) with (1 + list_size l).
apply (grade_mult (GradedAlgebraObj := exterior_grade_mult)).
+ apply vector_to_ext_grade.
+ exact IHl.
Qed.
Theorem ext_grade_sum : ∀ (v : ext V) n, of_grade n v →
∃ l : ulist (cring_U F * set_type (λ l', list_size l' = n)),
v = ulist_sum (ulist_image
(λ p, fst p · list_prod (list_image (vector_to_ext V) [snd p|])) l).
Proof.
intros v' n nv.
destruct nv as [v [v_eq nv]]; subst v'.
pose proof (tensor_grade_sum _ _ _ nv) as [l l_eq].
subst v; clear nv.
exists l.
induction l as [|[α x] l] using ulist_induction.
{
do 2 rewrite ulist_image_end, ulist_sum_end.
reflexivity.
}
do 2 rewrite ulist_image_add, ulist_sum_add; cbn.
rewrite tensor_to_ext_plus.
rewrite IHl; clear IHl.
apply rplus; clear l.
rewrite tensor_to_ext_scalar.
apply f_equal.
destruct x as [l l_size]; cbn; clear l_size.
induction l.
{
cbn.
reflexivity.
}
cbn.
rewrite tensor_to_ext_mult.
rewrite IHl.
reflexivity.
Qed.
(* begin hide *)
End ExteriorGrade.
(* end hide *)
|
\documentclass[12pt]{article}
\usepackage{fullpage,graphicx,psfrag,amsmath,amsfonts,verbatim}
\usepackage[small,bf]{caption}
\input defs.tex
\bibliographystyle{alpha}
\title{Power Allocation in Heterogeneous Networks with Multiple Antenna }
\author{Peter Hartig}
\newtheorem{theorem}{Theorem}
\begin{document}
\maketitle
%\begin{abstract}
This game considers a wireless communications network which includes both macro cell and femto cell users. In order to allow for uncoordinated usage of femto cells within the network, femto cell base stations must ensure that the users served by macro cells intercept an acceptable amount of interference below a certain threshold. The strategy for transmission across all such femto cell base stations in a network is investigated here in a game theoretic context.
%\end{abstract}
\newpage
\tableofcontents
\newpage
\section{Game and System Setup}
\subsection{Game Elements}
\subsubsection{Players: Femto Cell Base Stations}
Individual femto cell base stations (FC-BS) are the players of this game.
\\
Femto Cells are characterized by the following parameters
\begin{itemize}
\item
Each FC-BS $f \in \{1 ... F\}$ is considered to have a number of antennas $T_f$ with which to transmit to $K_f$ femto cell users. It is assumed throughout the remainder that $T_f \geq K_f$.
\\
\item
FC-BSs with multiple antennas ($T_f >=1$) can beamform their transmission using the precoding
matrix $\mathbf{U}_{\mathrm{f}} \in \mathbb{C}_{T_f \times K_f}$ .
The columns of $\mathbf{U}_{\mathrm{f}}$ are normalized such that
$\|\mathbf{u}_{\mathrm{fi}}\|^2 \;\forall i \in \{1 ... T_f\}$.
Similarly, $\mathbf{x_{\mathrm{f}}}$ is the
normalized vector of symbols for users of FC-BS $f$ (i.e. $E[\|\mathbf{x}_{\mathrm{f}}
\|_2^2]=1 \; \forall f \in \{1 ... F\}$).
\\
\item
FC-BSs allocate their transmission power using the diagonal power allocation
matrix $\mathrm{diag}(\mathbf{p}_{\mathrm{f}})$ with $p_{\mathrm{fi}} \geq 0 $
such that the final transmitted
signal is
$\mathbf{s}_{\mathrm{f} }= \mathbf{U_{\mathrm{f}}}
\mathrm{diag}(\mathbf{p}_{\mathrm{f}})
\mathbf{x_{\mathrm{f}}}$
\\
\item
FC-BS $f$ has power constraint
$trace(\mathbf{s}_\mathrm{f}\mathbf{s}_\mathrm{f}^H) =
trace(\mathbf{U_{\mathrm{f}}}
\mathrm{diag}(\mathbf{p}_{\mathrm{f}})
\mathbf{x_{\mathrm{f}}}
\mathbf{x_{\mathrm{f}}^H}
\mathrm{diag}(\mathbf{p}_{\mathrm{f}})
\mathbf{U_{\mathrm{f}}}^H
)
\leq P^{Total}_{f} $.
\\
\item
FC-BSs are assumed to be spaced far apart in distance such that FC-BS $f$ can be modeled as
causing no interference to the users of FC-BS $j \in \{1 ... F\}\backslash f$
\item
FC-BSs are assumed to have a cost function based upon the quality of service
provided to its users $U_f()$ which is strictly concave in its argument.
\item
FC-BS $f$ is assumed to know the downlink channel ($\mathbf{H_\mathrm{f}}$) from its transmission
antennas to all served users.
% TODO(Simulate degradation with incomplete CSI solution?)
\\
\end{itemize}
\subsubsection{Macro Cell Users}
\begin{itemize}
\item
Macro Cell user $m \in \{1 ... M\}$ experiences receiver interference due to transmission by
FC- BSs. These macro-cell users have limits to the amount of interference they may tolerate
$\sum^F_{f=1} \mathbf{\tilde{h}}_{\mathrm{m,f}}^T \mathbf{s}_{\mathrm{f}}
\mathbf{s_{\mathrm{f}}^{\mathrm{H}}} \mathbf{\tilde{h}_{\mathrm{m,f}}^*} \leq I^{Threshold}
_{\mathrm{m}} $.
\item
FC-BS $f$ is assumed to know the downlink channel ($\tilde{\mathbf{H}_{\mathrm{f}}}$) from its $T_f$
transmission antennas to all $M$ macro-cells with which it interferes.
\\
\end{itemize}
\subsubsection{Femto Cell Users}
\begin{itemize}
%\item TODO Decide if there should be minimum rate constraints for femto cell users in case (Look back at later in case some users are beam-formed out of the transmission). Check if this constraint will disrupt solution.
%\\
\item User $i$ of FC-BS $f$ has SINR:
\begin{equation*}
\gamma_{\mathrm{f,i}} =
\frac{\|p_{\mathrm{fi}}\mathbf{h^H_{\mathrm{f,i}}u_{\mathrm{f,i}}}x_{\mathrm{fi}}\|^2}
{\sigma^2_{noise} +
\underbrace{
\sum_{\mathrm{\tilde{f}=1,\tilde{f} \neq f}}^{\mathrm{F}}
\sum_{\mathrm{\tilde{k}\neq i}}^{\mathrm{K_f}}
\|p_{\mathrm{f\tilde{k}}}\mathbf{h^H_{\mathrm{f,\tilde{k}}}u_{\mathrm{f,\tilde{k}}}}x_{\mathrm{f\tilde{k}}}\|^2}_
{\mathrm{Inter-cell}}+ \underbrace{
\sum_{\mathrm{\tilde{k}\neq i}}^{\mathrm{K_f}}
\|p_{\mathrm{f\tilde{k}}}\mathbf{h^H_{\mathrm{f,\tilde{k}}}u_{\mathrm{f,\tilde{k}}}}x_{\mathrm{f\tilde{k}}}\|^2}
_{\mathrm{Intra-cell}}}
\; \mathrm{i \in \{1 ... K_f\}}\end{equation*}
\\
with AWGN $\sim \mathcal{N}(0,\sigma^2_n)$
\\
Assuming negligible inter-cell interference, this reduces to
\begin{equation*}
\gamma_{\mathrm{f,i}} = \frac{\|p_{\mathrm{fi}}\mathbf{h^H_{\mathrm{f,i}}
u_{\mathrm{f,i}}}x_{\mathrm{fi}}\|^2}
{\sigma^2_{noise}
+ \sum_{\mathrm{\tilde{k}\neq i}}^{\mathrm{K_f}}
\|p_{\mathrm{f\tilde{k}}}\mathbf{h^H_{\mathrm{f,\tilde{k}}}u_{\mathrm{f,\tilde{k}}}}x_{\mathrm{f\tilde{k}}}\|^2}
\; \mathrm{i \in \{1 ... K_f\}}
\end{equation*}
\\
%This further simplifies assuming that users use a zero-forcing beam-former
%
%\begin{equation}\label{zf_snr}
%\gamma_{\mathrm{f,i}} = \frac{|\mathbf{h^H_{\mathrm{f,i}}u_{\mathrm{f,i}}}|^2}
%{\sigma^2_{noise}
%}
%\end{equation}
%\\
\end{itemize}
%\subsection{Variations of Game Setup}
%
%\subsubsection{Case: $T_f \geq M + K_f$}
%FC-BSs could potentially zero-beam-form towards all macro users. However, as base stations have power constraints, it may be beneficial to cause certain amounts of interference.
%
%\subsubsection{Case: $K_f \leq T_f < M + K_f$}
%FC-BSs can send unique signals to all users but does not have sufficient DOF to zero-beam-form for all macro users.
\subsection{General Optimization Problem}
Each player $f$ attempts to maximize utility function $U_f()$ while playing a feasible strategy with respect to the region constrained by the interference constraints imposed by the macro cell users.
\par
If intra-cell interference is prohibited by the restriction of $\mathbf{U}_f$ to the set of zero-forcing matrices, the player optimization problem of player $f$ can be written as:
\begin{subequations}
\label{optim}
\begin{align}
\underset{\mathbf{U}_{\mathrm{f}} }{\text{minimize}} \;
& - \sum_{\mathrm{i=1}}^{\mathrm{K_f}}
U_{\mathrm{f,i}}(\gamma_{\mathrm{f,i}}) \label{player_opt} \\
\text{subject to} \; &
\sum^F_{f=1} \mathbf{\tilde{h}}_{\mathrm{m,f}}^T \mathbf{U_{\mathrm{f}}}
\mathbf{U_{\mathrm{f}}^{\mathrm{H}}} \mathbf{\tilde{h}_{\mathrm{m,f}}^*} \leq I^{Threshold}
_{\mathrm{m}} & m \in \{1 ...M\}
\label{interference_const}\\
& trace(\mathbf{U_f^H}\mathbf{U_f}) \leq P^{Total}_{f} \label{power_const}\\
& \langle \mathbf{h_{f,j}}\mathbf{u_{f,i}} \rangle =0\ & \; \forall j \in \{1... K_f\}\backslash i ,\; \forall i \in \{1 ... K_f\} \label{zf_const}
\end{align}
\end{subequations}
Note that over the feasible region of this problem, the SINR of femto cell users reduces to
\begin{equation}\label{zf_snr}
\gamma_{\mathrm{f,i}} = \frac{\|\mathbf{h^H_{\mathrm{f,i}}u_{\mathrm{f,i}}}\|^2}
{\sigma^2_{noise}
}
=
\frac{\mathbf{u^H_{\mathrm{f,i}}h_{\mathrm{f,i}}h^H_{\mathrm{f,i}}u_{\mathrm{f,i}}}}
{\sigma^2_{noise}
}
\end{equation}
due to \eqref{zf_const}
\section{Solving the Game}
\subsection{Verifying Conexity of Player Optimization Problem}
Sufficient conditions for a convex problem are:
\begin{enumerate}
\item The utility function is concave in its argument
\begin{itemize}
\item
First note that constraint \eqref{zf_const} ensures that $\gamma_{\mathrm{f,i}}$ takes the form of \eqref{zf_snr} and is therefore convex in ${\mathbf{u}_{\mathrm{f,i}}}$.
\item
As $U_f(\gamma_{\mathrm{f,i}}) $ is strictly concave (non-decreasing?) by definition.
This result is not generally a convex composition.
\end{itemize}
\item
Constraints form convex, closed and bounded set.
\\
TODO show closed and boundedness of set
\begin{itemize}
\item
Constaint \eqref{interference_const} contains $M$ quadratic constraints on $\mathbf{U_f}$ and
can be rewritten as
\begin{gather*}
\sum_{f=1}^F
trace(\mathbf{U_f^H} \mathbf{\tilde{h}_{m,f}} \mathbf{\tilde{h}_{m,f}^H} \mathbf{U_f} )\leq
I^{Threshold}_{m}.
\end{gather*}
This can be decomposed into \textit{independent} components
\begin{gather*}
\sum_{f=1}^F
\sum_{i=1}^{f_i}
\mathbf{u_{\mathrm{f,i}}^H}\mathbf{\tilde{h}_{\mathrm{m,f}}} \mathbf{\tilde{h}}_{\mathrm{m,f}}^H
\mathbf{u_{\mathrm{f,i}}} \leq I^{Threshold}_{m}
\end{gather*}
in which the term $ \mathbf{\tilde{h}_{\mathrm{m,f}}} \mathbf{\tilde{h}}_{\mathrm{m,f}}^H$ is always a positive semi-definite matrix and is, therefore, a convex set as shown in
\cite[p.8,9]{BoV:04}.
%This is essentially high dimensional ellipsoid.
\item \
Constraint \eqref{power_const} can be similarly decomposed into the sum
\begin{gather*}
\sum_{i=1}^{K_f}\mathbf{u_{\mathrm{f,i}}^{\mathrm{H}}} \mathbf{I}
\mathbf{u_{\mathrm{f,i}}} \leq P^{Total}_{f}
\end{gather*}
in which $\mathbf{I}$ is always positive definite and
therefore the constraint is strictly convex by the same
reasons as \eqref{interference_const}.
\end{itemize}
\item
Constaint \eqref{zf_const} is an affine constraint.
\begin{gather*}
\langle \mathbf{h_{\mathrm{f,j}}}\mathbf{u_{\mathrm{f,i}}} \rangle =0
\end{gather*}
%Note that affine constaints to not have to satisfy Slater's condition
\end{enumerate}
\subsection{Finding Nash Equilibrium}
\begin{enumerate}
\item \textbf{Existence of Nash Equilibrium:} Given that the player optimization problem is convex, this is an n-person concave game and therefore a NE exists \cite[Thm1]{rosen1964existence}.
\item \textbf{Uniqueness of Nash Equilibrium:} In order to use the tools defined in \cite[Thm4]{rosen1964existence} for proving uniqueness of Nash Equilibrium. The function $G(b,r) $ is defined as the Jacobian of $g(b,r) $ which is defined as
\begin{equation}
g(b,r)=
\begin{bmatrix}
r_1 \nabla V_{1}(b)
\\
r_2 \nabla V_{1}(b)
\\
\vdots\\
r_F \nabla V_{1}(b)
\end{bmatrix}
\end{equation}
with $r_i>0$.
In the setup of this game, $\nabla V_{1}(b)$
is the gradient of the utility function of FCBS $U_f(\mathbf{U}_{\mathrm{f}}) $ with respect to elements of the beam-forming matrix
$\mathbf{U}_{\mathrm{f}}$
\begin{itemize}
\item
Negative Definiteness of the matrix $[G(b,r)+G^{T}(b,r)] $ is a sufficient condition for Diagonally Strict Concavity of the game and therefore implies uniqueness of a NNE in n-person concave games \cite[Thm6]{rosen1964existence}
\item First, \eqref{player_opt} contains no inter-cell interference by assumption and therefore, the derivative with respect to any beam-forming variables from other players is zero. Therefore all off-diagonal elements of $[G(b,r)+G^{T}(b,r)] $ wil be zero.
\item Second, in order to obtain a negative definite result, \eqref{player_opt} must have strictly negative second derivative with respect to the variables in the argument. If we allow
\begin{equation*}
U_f(\mathbf{U}_\mathrm{f})=
- \sum_{\mathrm{i=1}}^{\mathrm{K_f}}
U_{\mathrm{f,i}}(\gamma_{\mathrm{f,i}})
\end{equation*}
By definition, $U_{\mathrm{f,i}}()$ is concave in its argument and therefore $- U_{\mathrm{f,i}}()$ is convex.
The argument of the function $- U_{\mathrm{f,i}}()$ is $\gamma_{\mathrm{f,i}}$ which can we expanded under the constraints of \eqref{optim} can be expanded as
\begin{equation}\label{zf_snr_expanded}
\gamma_{\mathrm{f,i}} = \frac{\|\mathbf{h^H_{\mathrm{f,i}}u_{\mathrm{f,i}}}\|^2}
{\sigma^2_{noise}
}
=
\frac{\mathbf{u^H_{\mathrm{f,i}}h_{\mathrm{f,i}}h^H_{\mathrm{f,i}}u_{\mathrm{f,i}}}}
{\sigma^2_{noise}
}
\end{equation}
Noting that the matrix
$\mathbf{h}_{\mathrm{f,i}}\mathbf{hh}^H_{\mathrm{f,i}}$
is limited to rank = 1. This is only a positive semidefinite function in
$u_{\mathrm{f,i}}$ and therefore is convex but not strictly convex.
\end{itemize}
\item
Summary of above:
While NE for the game are known to exist for the problem, these are not necessarily unique.
\item
If the utility function Uf is by assumption strictly concave increasing and the argument to this function (gamma) is strictly convex in ufi then does it work?
\end{enumerate}
%\end{document}
\subsection{Setup as a Potential Game}
It is useful to now represent the game as a "Potential Game". This is defined by a function
$ \Psi(\mathbf{U})$ which satisfies the condition
\begin{equation}\label{potential_game_condition}
\frac{d\Psi}{du_f} = \frac{d U()_f}{du_f}
\end{equation}
With this condition satisfied, the solution to the maximization problem
\begin{subequations}
\label{optim}
\begin{align}
\underset{\mathbf{U}}{\text{minimize}}
& \; \Psi(\mathbf{U}) \label{potential_game}
\\
\text{subject to} & \;
\sum^F_{f=1}\mathbf{\tilde{h_{m,f}^T}} \mathbf{U_f} \mathbf{U_f^H}
\mathbf{\tilde{h_{m,f}^*}} \leq I^{\mathrm{Threshold}}_{m} & m \in \{1 ...M\}
\label{interference_const_central}\\
& trace(\mathbf{U_f^H}\mathbf{U_f}) \leq P^{Total}_{f} & \forall f \in \{1 ... F\}
\label{power_const_central}\\
& \langle \mathbf{h_{f,j}}\mathbf{u_{f,i}} \rangle =0\ \; \forall j \in \{1... K_f\} \backslash i &\forall i \in \{1 ... K_f\}\; \forall f \in \{1 ... F\} \label{zf_const_central}
\end{align}
\end{subequations}
is a normalized Nash Equilibrium of the original problem.
As shown above, Nash Equilibria to this problem exists (though not necessarily unique).
\\
\textbf{Potential Function:} The proposed potential function is
\begin{gather*} \label{Potential_Function}
\Psi() = \sum_{f = 1}^{F} U_f()
\end{gather*}
As the utility functions of individual players $f$ do not share any common variables, \label{Potential_Function} will have the same derivative as individual $U_f()$ with respect to $\mathbf{U_{f,i}} $, satisfying condition \eqref{potential_game_condition}. This is primary motivation for including the \eqref{zf_const} as this allows us describe the game using a single optimization problem (the Potential Game) from which we can solve for NE.
%\begin{theorem}\label{distributed}
%\cite{ghosh2015normalized}
%If a game's potential function is strictly concave and the derivative of the function with respect to the individual players variables are independent of the other player variables, then there exists a distributed solution.
%\end{theorem}
\subsection{Distributed Solution to the Game}
A desirable feature to \eqref{potential_game} is for methods for reaching the solution to be distributable. This may allow for minimal communication overhead between processes (in this case players and macro users).
\subsubsection{Central Problem Resulting from Potential Game}
As described in \cite[p.~8,9]{boyd2011distributed}, the dual ascent method can be used to find a distributed solution to this problem using the Lagrangian of \eqref{potential_game}.
\\
\begin{multline}
L(\mathbf{U,\lambda}) =
\;
\sum_{f=1}^F U_f()
+
\sum_{\mathrm{m=1}}^M \lambda_{\mathrm{m}}
(\sum_{\mathrm{f=1}}^F
\sum_{\mathrm{i=1}}^{K_f}
\mathbf{u_{ \mathrm{f,i}}^H} \mathbf{\tilde{h_{m,f}}} \mathbf{\tilde{h_{m,f}^H}} \mathbf{u_{\mathrm{f,i}}} - I^{Threshold}_{m} )
\\
+
\sum_{f=1}^F
\lambda_{\mathrm{f}}^{'}(
\sum_{i=1}^{K_f}\mathbf{u_{f,i}^H} \mathbf{I} \mathbf{u_{\mathrm{f,i}}} - P^{Total}_{f})
+
\sum_{f=1}^F
\sum_{i=1}^{K_f}
\sum_{j=1, j\neq i}^{K_f}
\
\nu_{\mathrm{f,i,j}}(\mathbf{h^T_{\mathrm{f,j}}}\mathbf{u_{\mathrm{f,i}}})
\end{multline}
in which $\mathbf{U^{\mathrm{k}}} = [\mathbf{U^{\mathrm{k}}_{\mathrm{1}}}...\mathbf{U^{\mathrm{k}}_{\mathrm{F}}}]$.
The corresponding dual function and dual problem are then
\begin{gather*}
g(\lambda,\nu) = \underset{\mathbf{U}}{\mathrm{argmin}}\;L(\mathbf{U,\lambda})
\end{gather*}
\begin{gather*}
g(\lambda,\nu) = \underset{\lambda}{\mathrm{argmax}}\;\underset{\mathbf{U}}{\mathrm{argmin}}\;L(\mathbf{U,\lambda})
\end{gather*}
.
This dual function can then be decomposed into F component functions
\begin{multline}
g_f(\lambda,\nu) = \underset{\mathbf{U_f}}{\mathrm{argmin}}
\{
\;
U_f()
+
\sum_{\mathrm{i=1}}^{K_f}
\sum_{\mathrm{m=1}}^M \lambda_{\mathrm{m}}
\mathbf{u_{ \mathrm{f,i}}^H} \mathbf{\tilde{h_{m,f}}} \mathbf{\tilde{h_{m,f}^H}} \mathbf{u_{\mathrm{f,i}}} - I^{Threshold}_{m}
\\
+
\lambda_{\mathrm{f}}^{'}(
\sum_{i=1}^{K_f}\mathbf{u_{f,i}^H} \mathbf{I} \mathbf{u_{\mathrm{f,i}}} - P^{Total}_{f})
+
\sum_{i=1}^{K_f}
\sum_{j=1, j\neq i}^{K_f}
\
\nu_{\mathrm{f,i,j}}(\mathbf{h^T_{\mathrm{f,j}}}\mathbf{u_{\mathrm{f,i}}})\}
\end{multline}
\\
The following steps can then be iterated in order to reach an optimal solution.
\begin{enumerate}
\item
Individual players can solve $ g_f(\lambda,\nu) $ independently.
TODO: The Lagrangian is only guaranteed to be convex wrt the dual variables thus there is no guarantee this problem is bounded.
\item
Using $g(\lambda,\nu) = \sum_{f=1}^{F}g_f(\lambda,\nu)$ and the calculus of subgradients $\partial g(\lambda,\nu) = \sum_{f=1}^{F} \partial g_f(\lambda,\nu)$, the dual variables can updated by
\begin{gather}
\lambda_{\mathrm{m}}^{\mathrm{k+1}} =
\lambda_{\mathrm{m}}^{\mathrm{k}}
+
\alpha^{\mathrm{k}}*
\partial g(\lambda,\nu)
\end{gather}
using to predefined $\alpha^{\mathrm{k}}$ which must satisfy certain sumability conditions.
\end{enumerate}
TODO
\begin{itemize}
\item show proof convergence conditions of this algorithm
\item check if the distributed solution depends on strict convexity (or is the solution for these methods needs to be unique)-> Doesn't seem so
\item see if 1st update is bounded (if not, a new method will be needed)
\item begin looking at how to choose the update step-size in the second step
\item after writing explicitly, verify that no information passing between femto cells will be needed
\end{itemize}
\section{Additional Points of Interest}
\begin{itemize}
\item
Also of interest is studying whether or not the zero-forcing matrix typically chosen which minimizes the error covariance matrix is unique in the presence of interference constraints.
\item
See why Potential game requires equality of gradient and not just the same sign (strictly)
\item Similarly it might be interesting to extend this to cased of non-differentiable potential or utility functions
\end{itemize}
\newpage
\bibliography{system_model_bib}
\end{document}
© 2020 GitHub, Inc.
Terms
Privacy
Security
Status
Help
Contact GitHub
Pricing
API
Training
Blog
About
|
subroutine SHExpandDH(grid, py_m, py_n, lmax_calc, py_lmax, cilm, lmax, norm, sampling, csphase)
! in in in in in in out out in in in
use FFTW3
use SHTOOLS, only: DHaj
implicit none
integer, intent(in) :: py_m, py_n, py_lmax, lmax_calc
real*8, intent(in) :: grid(py_m, py_n)
real*8, intent(out) :: cilm(2, py_lmax+1, py_lmax+1)
integer, intent(out) :: lmax
integer, intent(in), optional :: norm, sampling, csphase
complex*16 :: cc(py_m+1)
integer :: l, m, n, i, l1, m1, i_eq, i_s, astat(4), lmax_comp, nlong
integer*8 :: plan
real*8 :: pi, gridl(2*py_m), aj(py_m), fcoef1(2, py_m/2+1), fcoef2(2, py_m/2+1)
real*8 :: theta, prod, scalef, rescalem, u, p, pmm, pm1, pm2, z, ffc(1:2,-1:1)
real*8, save, allocatable :: sqr(:), ff1(:,:), ff2(:,:)
integer*1, save, allocatable :: fsymsign(:,:)
integer, save :: lmax_old=0, norm_old = 0
n = py_m
lmax = py_m/2 - 1
nlong = py_n
lmax_comp = min(lmax, lmax_calc)
pi = acos(-1.0d0)
cilm = 0.0d0
scalef = 1.0d-280
call DHaj(n, aj)
aj(1:n) = aj(1:n)*sqrt(4.0d0*pi) ! Driscoll and Heally use unity normalized spherical harmonics
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Calculate recursion constants used in computing the Legendre polynomials
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (lmax_comp /= lmax_old .or. norm /= norm_old) then
if (allocated(sqr)) deallocate(sqr)
if (allocated(ff1)) deallocate(ff1)
if (allocated(ff2)) deallocate(ff2)
if (allocated(fsymsign)) deallocate(fsymsign)
allocate(sqr(2*lmax_comp+1), stat=astat(1))
allocate(ff1(lmax_comp+1,lmax_comp+1), stat=astat(2))
allocate(ff2(lmax_comp+1,lmax_comp+1), stat=astat(3))
allocate(fsymsign(lmax_comp+1,lmax_comp+1), stat=astat(4))
if (sum(astat(1:4)) /= 0) then
print*, "Error --- SHExpandDH"
print*, "Problem allocating arrays SQR, FF1, FF2, or FSYMSIGN", &
astat(1), astat(2), astat(3), astat(4)
stop
endif
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Calculate signs used for symmetry of Legendre functions about equator
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
do l = 0, lmax_comp, 1
do m = 0, l, 1
if (mod(l-m,2) == 0) then
fsymsign(l+1,m+1) = 1
else
fsymsign(l+1,m+1) = -1
endif
enddo
enddo
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Precompute square roots of integers that are used several times.
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
do l=1, 2*lmax_comp+1
sqr(l) = sqrt(dble(l))
enddo
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Precompute multiplicative factors used in recursion relationships
! P(l,m) = x*f1(l,m)*P(l-1,m) - P(l-2,m)*f2(l,m)
! k = l*(l+1)/2 + m + 1
! Note that prefactors are not used for the case when m=l as a different
! recursion is used. Furthermore, for m=l-1, Plmbar(l-2,m) is assumed to be zero.
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
select case(norm)
case(1,4)
if (lmax_comp /= 0) then
ff1(2,1) = sqr(3)
ff2(2,1) = 0.0d0
endif
do l=2, lmax_comp, 1
ff1(l+1,1) = sqr(2*l-1) * sqr(2*l+1) / dble(l)
ff2(l+1,1) = dble(l-1) * sqr(2*l+1) / sqr(2*l-3) / dble(l)
do m=1, l-2, 1
ff1(l+1,m+1) = sqr(2*l+1) * sqr(2*l-1) / sqr(l+m) / sqr(l-m)
ff2(l+1,m+1) = sqr(2*l+1) * sqr(l-m-1) * sqr(l+m-1) &
/ sqr(2*l-3) / sqr(l+m) / sqr(l-m)
enddo
ff1(l+1,l) = sqr(2*l+1) * sqr(2*l-1) / sqr(l+m) / sqr(l-m)
ff2(l+1,l) = 0.0d0
enddo
case(2)
if (lmax_comp /= 0) then
ff1(2,1) = 1.0d0
ff2(2,1) = 0.0d0
endif
do l=2, lmax_comp, 1
ff1(l+1,1) = dble(2*l-1) /dble(l)
ff2(l+1,1) = dble(l-1) /dble(l)
do m=1, l-2, 1
ff1(l+1,m+1) = dble(2*l-1) / sqr(l+m) / sqr(l-m)
ff2(l+1,m+1) = sqr(l-m-1) * sqr(l+m-1) / sqr(l+m) / sqr(l-m)
enddo
ff1(l+1,l)= dble(2*l-1) / sqr(l+m) / sqr(l-m)
ff2(l+1,l) = 0.0d0
enddo
case(3)
do l=1, lmax_comp, 1
ff1(l+1,1) = dble(2*l-1) /dble(l)
ff2(l+1,1) = dble(l-1) /dble(l)
do m=1, l-1, 1
ff1(l+1,m+1) = dble(2*l-1) / dble(l-m)
ff2(l+1,m+1) = dble(l+m-1) / dble(l-m)
enddo
enddo
end select
lmax_old = lmax_comp
norm_old = norm
endif
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Create generic plan for gridl
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
call dfftw_plan_dft_r2c_1d(plan, nlong, gridl(1:nlong), cc, FFTW_MEASURE)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Integrate over all latitudes. Take into account symmetry of the
! Plms about the equator.
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
i_eq = n/2 + 1 ! Index correspondong to the equator
do i=2, i_eq - 1, 1
theta = (i-1) * pi / dble(n)
z = cos(theta)
u = sqrt( (1.0d0-z) * (1.0d0+z) )
gridl(1:nlong) = grid(i,1:nlong)
call dfftw_execute(plan) ! take fourier transform
fcoef1(1,1:n/2) = sqrt(2*pi) * aj(i) * dble(cc(1:n/2)) / dble(nlong)
fcoef1(2,1:n/2) = -sqrt(2*pi) * aj(i) * dimag(cc(1:n/2)) / dble(nlong)
i_s = 2*i_eq -i
gridl(1:nlong) = grid(i_s,1:nlong)
call dfftw_execute(plan) ! take fourier transform
fcoef2(1,1:n/2) = sqrt(2*pi) * aj(i_s) * dble(cc(1:n/2)) / dble(nlong)
fcoef2(2,1:n/2) = -sqrt(2*pi) * aj(i_s) * dimag(cc(1:n/2)) / dble(nlong)
select case(norm)
case(1,2,3); pm2 = 1.0d0
case(4); pm2 = 1.0d0 / sqrt(4*pi)
end select
cilm(1,1,1) = cilm(1,1,1) + pm2 * (fcoef1(1,1) + fcoef2(1,1) )
! fsymsign = 1
if (lmax_comp == 0) cycle
pm1 = ff1(2,1) * z * pm2
cilm(1,2,1) = cilm(1,2,1) + pm1 * ( fcoef1(1,1) - fcoef2(1,1) )
! fsymsign = -1
ffc(1,-1) = fcoef1(1,1) - fcoef2(1,1)
ffc(1, 1) = fcoef1(1,1) + fcoef2(1,1)
do l=2, lmax_comp, 1
l1 = l+1
p = ff1(l1,1) * z * pm1 - ff2(l1,1) * pm2
pm2 = pm1
pm1 = p
cilm(1,l1,1) = cilm(1,l1,1) + p * ffc(1,fsymsign(l1,1))
enddo
select case(norm)
case(1,2); pmm = sqr(2) * scalef
case(3); pmm = scalef
case(4); pmm = sqr(2) * scalef / sqrt(4*pi)
end select
rescalem = 1.0d0/scalef
do m = 1, lmax_comp-1, 1
m1 = m+1
rescalem = rescalem * u
select case(norm)
case(1,4)
pmm = csphase * pmm * sqr(2*m+1) / sqr(2*m)
pm2 = pmm
case(2)
pmm = csphase * pmm * sqr(2*m+1) / sqr(2*m)
pm2 = pmm / sqr(2*m+1)
case(3)
pmm = csphase * pmm * (2*m-1)
pm2 = pmm
end select
fcoef1(1:2,m1) = fcoef1(1:2,m1) * rescalem
fcoef2(1:2,m1) = fcoef2(1:2,m1) * rescalem
cilm(1:2,m1,m1) = cilm(1:2,m1,m1) + pm2 * &
( fcoef1(1:2,m1) + fcoef2(1:2,m1) )
! fsymsign = 1
pm1 = z * ff1(m1+1,m1) * pm2
cilm(1:2,m1+1,m1) = cilm(1:2,m1+1,m1) + pm1 * &
( fcoef1(1:2,m1) - fcoef2(1:2,m1) )
! fsymsign = -1
ffc(1:2,-1) = fcoef1(1:2,m1) - fcoef2(1:2,m1)
ffc(1:2, 1) = fcoef1(1:2,m1) + fcoef2(1:2,m1)
do l = m+2, lmax_comp, 1
l1 = l+1
p = z * ff1(l1,m1) * pm1-ff2(l1,m1) * pm2
pm2 = pm1
pm1 = p
cilm(1:2,l1,m1) = cilm(1:2,l1,m1) + p * ffc(1:2,fsymsign(l1,m1))
enddo
enddo
rescalem = rescalem * u
select case(norm)
case(1,4); pmm = csphase * pmm * sqr(2*lmax_comp+1) / sqr(2*lmax_comp) * rescalem
case(2); pmm = csphase * pmm / sqr(2*lmax_comp) * rescalem
case(3); pmm = csphase * pmm * (2*lmax_comp-1) * rescalem
end select
cilm(1:2,lmax_comp+1,lmax_comp+1) = cilm(1:2,lmax_comp+1,lmax_comp+1) + pmm * &
( fcoef1(1:2,lmax_comp+1) + fcoef2(1:2,lmax_comp+1) )
! fsymsign = 1
enddo
! Finally, do equator
i = i_eq
z = 0.0d0
u = 1.0d0
gridl(1:nlong) = grid(i,1:nlong)
call dfftw_execute(plan) ! take fourier transform
fcoef1(1,1:n/2) = sqrt(2*pi) * aj(i) * dble(cc(1:n/2)) / dble(nlong)
fcoef1(2,1:n/2) = -sqrt(2*pi) * aj(i) * dimag(cc(1:n/2)) / dble(nlong)
select case(norm)
case(1,2,3); pm2 = 1.0d0
case(4); pm2 = 1.0d0 / sqrt(4*pi)
end select
cilm(1,1,1) = cilm(1,1,1) + pm2 * fcoef1(1,1)
if (lmax_comp /= 0) then
do l=2, lmax_comp, 2
l1 = l+1
p = - ff2(l1,1) * pm2
pm2 = p
cilm(1,l1,1) = cilm(1,l1,1) + p * fcoef1(1,1)
enddo
select case(norm)
case(1,2); pmm = sqr(2) * scalef
case(3); pmm = scalef
case(4); pmm = sqr(2) * scalef / sqrt(4*pi)
end select
rescalem = 1.0d0/scalef
do m = 1, lmax_comp-1, 1
m1 = m+1
select case(norm)
case(1,4)
pmm = csphase * pmm * sqr(2*m+1) / sqr(2*m)
pm2 = pmm
case(2)
pmm = csphase * pmm * sqr(2*m+1) / sqr(2*m)
pm2 = pmm / sqr(2*m+1)
case(3)
pmm = csphase * pmm * (2*m-1)
pm2 = pmm
end select
fcoef1(1:2,m1) = fcoef1(1:2,m1) * rescalem
cilm(1:2,m1,m1) = cilm(1:2,m1,m1) + pm2 * fcoef1(1:2,m1)
do l = m+2, lmax_comp, 2
l1 = l+1
p = - ff2(l1,m1) * pm2
pm2 = p
cilm(1:2,l1,m1) = cilm(1:2,l1,m1) + p * fcoef1(1:2,m1)
enddo
enddo
select case(norm)
case(1,4); pmm = csphase * pmm * sqr(2*lmax_comp+1) / sqr(2*lmax_comp) * rescalem
case(2); pmm = csphase * pmm / sqr(2*lmax_comp) * rescalem
case(3); pmm = csphase * pmm * (2*lmax_comp-1) * rescalem
end select
cilm(1:2,lmax_comp+1,lmax_comp+1) = cilm(1:2,lmax_comp+1,lmax_comp+1) + pmm * fcoef1(1:2,lmax_comp+1)
endif
call dfftw_destroy_plan(plan)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Divide by integral of Ylm*Ylm
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
select case(norm)
case(1)
do l=0, lmax_comp, 1
cilm(1:2,l+1, 1:l+1) = cilm(1:2,l+1, 1:l+1) / (4*pi)
enddo
case(2)
do l=0, lmax_comp, 1
cilm(1:2,l+1, 1:l+1) = cilm(1:2,l+1, 1:l+1) * (2*l+1) / (4*pi)
enddo
case(3)
do l=0, lmax_comp, 1
prod = 4 * pi / dble(2*l+1)
cilm(1,l+1,1) = cilm(1,l+1,1) / prod
prod = prod / 2.0d0
do m=1, l-1, 1
prod = prod * (l+m) * (l-m+1)
cilm(1:2,l+1,m+1) = cilm(1:2,l+1,m+1) / prod
enddo
!do m=l case
if (l /= 0) cilm(1:2,l+1,l+1) = cilm(1:2,l+1, l+1)/(prod*2*l)
enddo
end select
end subroutine SHExpandDH
|
module TreeKnit
# External modules
using Comonicon
using Logging
using LoggingExtras
using Parameters
using Random
using Setfield
# Personal modules
using TreeTools
include("mcc_base.jl")
export naive_mccs
include("mcc_splits.jl")
include("mcc_tools.jl")
include("mcc_IO.jl")
export read_mccs, write_mccs
include("resolving.jl")
export resolve!
include("SplitGraph/SplitGraph.jl")
using TreeKnit.SplitGraph
include("objects.jl")
export OptArgs
include("main.jl")
export computeMCCs, inferARG
include("SimpleReassortmentGraph/SimpleReassortmentGraph.jl")
import TreeKnit.SimpleReassortmentGraph: SRG
export SRG
include("cli.jl")
# TreeTools re-exports for docs
import TreeTools: node2tree, parse_newick
export node2tree
export parse_newick
end # module
|
import math
import logging
from typing import Union
import jieba
import numpy
import torch
import pickle
UKN, PAD = '<ukn>', '<pad>'
jieba.setLogLevel(log_level=logging.INFO)
class Tokenizer:
"""ok
"""
def __init__(self, is_char_segment: bool):
self.is_char_segment = is_char_segment
def tokenize(self, text: str) -> list:
if self.is_char_segment:
return self.tokenize_by_char(text)
else:
return self.tokenize_by_word(text)
def tokenize_by_char(self, text: str) -> list:
result = [char for char in text]
return result
def tokenize_by_word(self, text: str) -> list:
seg_list = jieba.cut(text)
result = list(seg_list)
return result
class Vocab:
"""ok
"""
def __init__(self, train_path: str, vocab_path: str, tokenizer: Tokenizer, min_freq: int = 2):
self.train_path = train_path
self.vocab_path = vocab_path
self.tokenizer = tokenizer
self.min_freq = min_freq
self.idx_to_token, self.token_to_idx = [PAD, UKN], {PAD: 0, UKN: 1}
def build_vocab_of_sentences(self):
vocab_dic = {}
separator = '\t'
with open(self.train_path, 'r', encoding='UTF-8') as f:
for line in f:
sentence = line.strip().split(separator)[0]
if sentence == '':
continue
for word in self.tokenizer.tokenize(sentence):
vocab_dic[word] = vocab_dic.get(word, 0) + 1
i = 2
for key in vocab_dic:
if key == PAD or key == UKN:
continue
if vocab_dic[key] >= self.min_freq:
self.idx_to_token.append(key)
self.token_to_idx[key] = i
i = i + 1
pickle.dump(self.idx_to_token, open(self.vocab_path, 'wb'))
def load_vocab(self):
self.idx_to_token = pickle.load(open(self.vocab_path, 'rb'))
self.token_to_idx = {}
for idx, token in enumerate(self.idx_to_token):
self.token_to_idx[token] = idx
def get_len(self) -> int:
return len(self.idx_to_token)
def to_token(self, index: int) -> str:
if index < 0 or (index + 1) > self.get_len():
return None
return self.idx_to_token[index]
def to_index(self, token: str) -> int:
return self.token_to_idx.get(token, 1) # if token not found ,consider it as unknown
def __len__(self):
return len(self.idx_to_token)
class Embedding:
"""ok
"""
def __init__(self, trimmed_path: str, original_path: str, vocab: Vocab):
self.original_path = original_path
self.trimmed_path = trimmed_path
self.vocab = vocab
self.representation = None # array of trimmed Embedding (num of vocab ,len of Embedding for one token)
self.len = None # len of Embedding for one token
self.residual_index = [] # token index which is not found in original pretrained Embedding
# [PAD, UKN]
self.special_index = [0, 1]
def build_trimmed(self):
original_has_header = True
# embedding_len
with open(self.original_path, 'r', encoding='UTF-8') as f:
if original_has_header:
f.readline()
elems = f.readline().strip().split()
self.len = len(elems[1:])
# representation of embedding
self.representation = numpy.zeros(shape=(self.vocab.get_len(), self.len))
with open(self.original_path, 'r', encoding='UTF-8') as f:
if original_has_header:
f.readline()
for line in f:
elems = line.strip().split()
# if original embedding has PAD or UKN ,just abandon it bc it may has diff meaning
if elems[0] == PAD or elems[0] == UKN:
continue
vocab_index = self.vocab.to_index(elems[0])
if vocab_index is None:
continue
self.representation[vocab_index, 0:] = elems[1:]
zero = numpy.zeros(self.len)
for vocab_index in range(self.vocab.get_len()):
if vocab_index == 0:
self.representation[vocab_index] = self._get_pad_embedding()
elif vocab_index == 1:
self.representation[vocab_index] = self._get_ukn_embedding()
else:
if (self.representation[vocab_index] == zero).all():
self.representation[vocab_index] = self._get_residual_embedding()
self.residual_index.append(vocab_index)
numpy.savez_compressed(self.trimmed_path, representation=self.representation,
residual_index=self.residual_index)
def load_trimmed(self):
trimmed = numpy.load(self.trimmed_path)
self.representation = trimmed['representation']
self.residual_index = trimmed['residual_index']
self.len = self.representation.shape[1]
def get_representation_by_index(self, index: int):
return self.representation[index]
def get_all_representation(self) -> numpy.ndarray:
return self.representation
def get_residual_index(self) -> list:
return self.residual_index
def get_residual_index_token(self):
return [(index, self.vocab.to_token(index)) for index in self.residual_index]
def _get_pad_embedding(self):
result = numpy.random.rand(self.len)
return result
def _get_ukn_embedding(self):
result = numpy.random.rand(self.len)
return result
def _get_residual_embedding(self):
result = numpy.random.rand(self.len)
return result
class TextClassifyDataset:
"""ok
"""
def __init__(self, file_path: str, text_length: str, vocab: Vocab, tokenizer: Tokenizer):
self.file_path = file_path
self.text_length = text_length
self.vocab = vocab
self.tokenizer = tokenizer
self.file_iterator = None
def __iter__(self):
self.reset()
return self
def __len__(self):
length = 0
with open(self.file_path, 'r', encoding='UTF-8') as file:
while True:
line = file.readline().strip()
if line == '':
break
else:
length = length + 1
return length
def __next__(self):
separator = '\t'
line = next(self.file_iterator)
sentence, label = line.split(separator)
tokens = self.tokenizer.tokenize(sentence)
if len(tokens) < self.text_length:
tokens.extend([PAD] * (self.text_length - len(tokens)))
else:
tokens = tokens[:self.text_length]
return [self.vocab.to_index(token) for token in tokens], int(label)
def reset(self):
self.file_iterator = self._get_file_iterator()
return self
def _get_file_iterator(self):
with open(self.file_path, 'r', encoding='UTF-8') as file:
while True:
line = file.readline().strip()
if line == '':
break
else:
yield line
class Dataloader:
"""ok
"""
def __init__(self, dataset_iterator: Union[TextClassifyDataset], batch_size: int):
self.dataset_iterator = dataset_iterator
self.batch_size = batch_size
def __iter__(self):
self.dataset_iterator.reset()
return self
def __len__(self):
length = len(self.dataset_iterator)
return math.ceil(length / self.batch_size)
def __next__(self):
i = 0
X_list = []
Y_list = []
while True:
try:
X, Y = next(self.dataset_iterator)
except StopIteration:
break
else:
X_list.append(X)
Y_list.append(Y)
i = i + 1
if i == self.batch_size:
break
if len(X_list) == 0:
raise StopIteration
else:
return torch.tensor(X_list), torch.tensor(Y_list)
def get_text_classify_dataloader(file_path, text_length, batch_size, vocab, tokenizer):
dataset = TextClassifyDataset(file_path, text_length, vocab,
tokenizer)
dataloader = Dataloader(dataset, batch_size)
return dataloader
|
[STATEMENT]
lemma vcons_vsubset: "xs \<subseteq>\<^sub>\<circ> xs #\<^sub>\<circ> x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. xs \<subseteq>\<^sub>\<circ> xs #\<^sub>\<circ> x
[PROOF STEP]
by clarsimp |
% File: computation_notes.tex
% Created: Mon Dec 20 02:00 PM 2010 C
% Last Change: Mon Dec 20 02:00 PM 2010 C
%
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\newcommand{\Spa}[1]{\mathbf{\hat{#1}}}
\newcommand{\Nspa}[1]{\mathbf{\underline{#1}}}
\newcommand{\Vec}[1]{\mathbf{#1}}
\newcommand{\figref}[1]{\figurename~\ref{#1}}
\begin{document}
\section{Computation of the velocity of a point on a rigid body using spatial
algebra}
The ABA computes automatically the spatial velocity of body $i$ in the
reference frame of the body such that computation of joint velocities are
easier. Now we want to compute the (linear) velocity in base coordinates of a
point $\Vec{p}$ that is attached to body $i$ with body coordinates
${}^i\Vec{r}_p$, i.e. we want to compute ${}^0 \Vec{\dot{r}}_p = {}^0
\Vec{r}_p$.
First of all we compute the spatial velocities ${}^0\Spa{v}$ of all bodies in
base coordinates (which can be done during the first loop of the ABA):
\begin{equation}
{}^0\Spa{v}_i = {}^0\Spa{v}_{\lambda(i)} + {}^{0}\Spa{X}_{i} \Spa{v}_{Ji}
\end{equation}
where $\Spa{v}_{Ji} = \Spa{S}_i \dot{q}_i $ which is the velocity that is
propagated by joint $i$ from body $\lambda(i)$ to body $i$ along joint axis
$\Spa{S}_i$ (see also RBDA p. 80).
This is now the velocity of the body $i$ in base coordinates. What is now left
todo is to transform this velocity into the velocity of the point $\Vec{p}$.
Before we can do that we have to compute the coordinates of $P$ in base
coordinates which can be done by:
\begin{equation}
{}^0\Vec{r}_p = {}^0 \Vec{r}_i + {}^0\Vec{R}_i {}^i \Vec{r}_p
\end{equation}
for which ${}^0 \Vec{r}_i$ is the origin of the bodies in base coordinates and
${}^0 \Vec{R}_i$ the orientation of the base relative to the body.
Now we can compute the velocity of point $\Vec{r}_p$ with the following
formulation:
\begin{equation}
{}^0\Spa{v}_p = \textit{xlt}({}^0\Vec{r}_p) {}^0\Spa{v}_i =
\left[
\begin{array}{cc}
\Vec{1} & 0 \\
-{}^0\Vec{r}_p \times & \Vec{1}
\end{array}
\right]
{}^0\Spa{v}_i
\end{equation}
By doing so, the linear part of the spatial velocity ${}^0\Spa{v}_p$ has the
following entries:
\begin{equation}
{}^0\Spa{v}_p = \left[
\begin{array}{c}
\Nspa{\omega} \\
-{}^0\Nspa{r}_p \times \Nspa{\omega} + {}^0 \Nspa{\Vec{v}}_i
\end{array}
\right]
=
\left[
\begin{array}{c}
\Nspa{\omega} \\
{}^0 \Nspa{\Vec{v}}_i + \Nspa{\omega} \times {}^0 \Nspa{r}_p
\end{array}
\right]
\end{equation}
For which the bottom line is the term for linear velocity in the standard 3D
notation.
\section{Computation of the acceleration of a point on a rigid body using
spatial algebra}
The acceleration of a point depends on three quantities: the position of the
point, velocity of the body and the acceleration of the body. We therefore
assume that we already computed the velocity as described in the previous
section.
To compute the acceleration of a point we have to compute the spatial
acceleration of a body in base coordinates. This can be expressed as:
\begin{equation}
\Spa{a}_i = {}^0\Spa{a}_{\lambda(i)}
+ {}^{0}\Spa{X}_{i} \Spa{a}_{Ji}
\end{equation}
for which $\Spa{a}_{Ji} = \Spa{S}_i \ddot{q}_i + \dot{\Spa{S}}_i \dot{q}_i$.
The last term can be written as: $\dot{\Spa{S}} = \Spa{v}_i \times \Spa{S}_i$.
\begin{figure}[h!]
\begin{center}
\includegraphics[width=0.9\textwidth]{acceleration_visualization}
\end{center}
\caption{Visualization of the acceleration of a point}
\label{fig:acceleration_visualization}
\end{figure}
There are three coordinate systems involved in the computation of the
acceleration of point p which are shown in
\figref{fig:acceleration_visualization}. The \emph{base coordinate system}
which is the global reference frame, \emph{link $i$ coordinate system}
which is the coordinate system of body $i$, and the \emph{point coordinate
system} that is locate at the current position of $p$ and has the same
orientation as the base coordinate system.
First of all we build the transformation from the body coordinate system to
the point coordinate system:
\begin{equation}
{^p}\Vec{X}_i =
\left[
\begin{array}{cc}
{^0}\Vec{E}_i & \Vec{0} \\
\Vec{0} & {^0}\Vec{E}_i
\end{array}
\right]
\left[
\begin{array}{cc}
\Vec{1} & \Vec{0} \\
-{^i}\Nspa{r}_p \times & \Vec{1}
\end{array}
\right].
\end{equation}
This can now be used to express the velocity and acceleration of the body at
the point p:
\begin{equation}
{^p}\Spa{v}_i = {^p}\Vec{X}_i \Spa{v}_i
\end{equation}
\begin{equation}
{^p}\Spa{a}_i = {^p}\Vec{X}_i \Spa{a}_i
\end{equation}
We now want to retrieve the \emph{classical acceleration}. It is expressed in a
coordinate frame that has a pure linear velocity of ${^0}\Nspa{\dot{p}}$.
\begin{equation}
{^p}\Spa{a}'_i = {^p}\Spa{a}_i +
\left[
\begin{array}{c}
\Vec{0}\\
{^0}\Nspa{\omega}_i \times {^0}\Nspa{\dot{p}}
\end{array}
\right]
\end{equation}
The linear part of this vector is then the acceleration of the point in base
coordinates.
\end{document}
|
lemma (in metric_space) eventually_nhds_metric: "eventually P (nhds a) \<longleftrightarrow> (\<exists>d>0. \<forall>x. dist x a < d \<longrightarrow> P x)" |
Troy King Back in the Game With Big Money From Small Donors – Taking Alabama Back!
A campaign finance report filed today shows former Republican Attorney General Troy King is back in the game, raising over $130,000.00 in small donations in just over two weeks.
King, once thought to be another asterisk in former Gov. Bob Riley’s scheme to hold onto the reins of power after leaving office in 2010, formally filed his campaign with the secretary of state’s office in mid-November. |
theory Cyclic_List imports
"HOL-Library.Confluent_Quotient"
begin
inductive cyclic1 :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool" for xs where
"cyclic1 xs (rotate1 xs)"
abbreviation cyclic :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool" where
"cyclic \<equiv> equivclp cyclic1"
lemma cyclic_mapI: "cyclic xs ys \<Longrightarrow> cyclic (map f xs) (map f ys)"
by(induction rule: equivclp_induct)
(auto 4 4 elim!: cyclic1.cases simp add: rotate1_map[symmetric] intro: equivclp_into_equivclp cyclic1.intros)
quotient_type 'a cyclic_list = "'a list" / cyclic by simp
lemma map_respect_cyclic: includes lifting_syntax shows
"((=) ===> cyclic ===> cyclic) map map"
by(auto simp add: rel_fun_def cyclic_mapI)
lemma confluentp_cyclic1: "confluentp cyclic1"
by(intro strong_confluentp_imp_confluentp strong_confluentpI)(auto simp add: cyclic1.simps)
lemma cyclic_set_eq: "cyclic xs ys \<Longrightarrow> set xs = set ys"
by(induction rule: converse_equivclp_induct)(simp_all add: cyclic1.simps, safe, simp_all)
lemma retract_cyclic1:
assumes "cyclic1 (map f xs) ys"
shows "\<exists>zs. cyclic xs zs \<and> ys = map f zs \<and> set zs \<subseteq> set xs"
using assms by(force simp add: cyclic1.simps rotate1_map intro: cyclic1.intros symclpI1)
lemma confluent_quotient_cyclic1:
"confluent_quotient cyclic1 cyclic cyclic cyclic cyclic cyclic (map fst) (map snd) (map fst) (map snd) list_all2 list_all2 list_all2 set set"
by(unfold_locales)
(auto dest: retract_cyclic1 cyclic_set_eq simp add: list.in_rel list.rel_compp map_respect_cyclic[THEN rel_funD, OF refl] confluentp_cyclic1 intro: rtranclp_mono[THEN predicate2D, OF symclp_greater])
lift_bnf 'a cyclic_list
subgoal by(rule confluent_quotient.subdistributivity[OF confluent_quotient_cyclic1])
subgoal by(force dest: cyclic_set_eq)
done
end
|
(*
Author: Norbert Schirmer
Maintainer: Norbert Schirmer, norbert.schirmer at web de
License: LGPL
*)
(* Title: AlternativeSmallStep.thy
Author: Norbert Schirmer, TU Muenchen
Copyright (C) 2006-2008 Norbert Schirmer
Some rights reserved, TU Muenchen
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
*)
section \<open>Alternative Small Step Semantics\<close>
theory AlternativeSmallStep imports HoareTotalDef
begin
text \<open>
This is the small-step semantics, which is described and used in my PhD-thesis \<^cite>\<open>"Schirmer-PhD"\<close>.
It decomposes the statement into a list of statements and finally executes the head.
So the redex is always the head of the list. The equivalence between termination
(based on the big-step semantics) and the absence of infinite computations in
this small-step semantics follows the same lines of reasoning as for
the new small-step semantics. However, it is technically more involved since
the configurations are more complicated. Thats why I switched to the new small-step
semantics in the "main trunk". I keep this alternative version and the important
proofs in this theory, so that one can compare both approaches.
\<close>
subsection \<open>Small-Step Computation: \<open>\<Gamma>\<turnstile>(cs, css, s) \<rightarrow> (cs', css', s')\<close>\<close>
type_synonym ('s,'p,'f) continuation = "('s,'p,'f) com list \<times> ('s,'p,'f) com list"
type_synonym ('s,'p,'f) config =
"('s,'p,'f)com list \<times> ('s,'p,'f)continuation list \<times> ('s,'f) xstate"
inductive "step"::"[('s,'p,'f) body,('s,'p,'f) config,('s,'p,'f) config] \<Rightarrow> bool"
("_\<turnstile> (_ \<rightarrow>/ _)" [81,81,81] 100)
for \<Gamma>::"('s,'p,'f) body"
where
Skip: "\<Gamma>\<turnstile>(Skip#cs,css,Normal s) \<rightarrow> (cs,css,Normal s)"
| Guard: "s\<in>g \<Longrightarrow> \<Gamma>\<turnstile>(Guard f g c#cs,css,Normal s) \<rightarrow> (c#cs,css,Normal s)"
| GuardFault: "s\<notin>g \<Longrightarrow> \<Gamma>\<turnstile>(Guard f g c#cs,css,Normal s) \<rightarrow> (cs,css,Fault f)"
| FaultProp: "\<Gamma>\<turnstile>(c#cs,css,Fault f) \<rightarrow> (cs,css,Fault f)"
| FaultPropBlock: "\<Gamma>\<turnstile>([],(nrms,abrs)#css,Fault f) \<rightarrow> (nrms,css,Fault f)"
(* FaultPropBlock: "\<Gamma>\<turnstile>([],cs#css,Fault) \<rightarrow> ([],css,Fault)"*)
| AbruptProp: "\<Gamma>\<turnstile>(c#cs,css,Abrupt s) \<rightarrow> (cs,css,Abrupt s)"
| ExitBlockNormal:
"\<Gamma>\<turnstile>([],(nrms,abrs)#css,Normal s) \<rightarrow> (nrms,css,Normal s)"
| ExitBlockAbrupt:
"\<Gamma>\<turnstile>([],(nrms,abrs)#css,Abrupt s) \<rightarrow> (abrs,css,Normal s)"
| Basic: "\<Gamma>\<turnstile>(Basic f#cs,css,Normal s) \<rightarrow> (cs,css,Normal (f s))"
| Spec: "(s,t) \<in> r \<Longrightarrow> \<Gamma>\<turnstile>(Spec r#cs,css,Normal s) \<rightarrow> (cs,css,Normal t)"
| SpecStuck: "\<forall>t. (s,t) \<notin> r \<Longrightarrow> \<Gamma>\<turnstile>(Spec r#cs,css,Normal s) \<rightarrow> (cs,css,Stuck)"
| Seq: "\<Gamma>\<turnstile>(Seq c\<^sub>1 c\<^sub>2#cs,css,Normal s) \<rightarrow> (c\<^sub>1#c\<^sub>2#cs,css,Normal s)"
| CondTrue: "s\<in>b \<Longrightarrow> \<Gamma>\<turnstile>(Cond b c\<^sub>1 c\<^sub>2#cs,css,Normal s) \<rightarrow> (c\<^sub>1#cs,css,Normal s)"
| CondFalse: "s\<notin>b \<Longrightarrow> \<Gamma>\<turnstile>(Cond b c\<^sub>1 c\<^sub>2#cs,css,Normal s) \<rightarrow> (c\<^sub>2#cs,css,Normal s)"
| WhileTrue: "\<lbrakk>s\<in>b\<rbrakk>
\<Longrightarrow>
\<Gamma>\<turnstile>(While b c#cs,css,Normal s) \<rightarrow> (c#While b c#cs,css,Normal s)"
| WhileFalse: "\<lbrakk>s\<notin>b\<rbrakk>
\<Longrightarrow>
\<Gamma>\<turnstile>(While b c#cs,css,Normal s) \<rightarrow> (cs,css,Normal s)"
| Call: "\<Gamma> p=Some bdy \<Longrightarrow>
\<Gamma>\<turnstile>(Call p#cs,css,Normal s) \<rightarrow> ([bdy],(cs,Throw#cs)#css,Normal s)"
| CallUndefined: "\<Gamma> p=None \<Longrightarrow>
\<Gamma>\<turnstile>(Call p#cs,css,Normal s) \<rightarrow> (cs,css,Stuck)"
| StuckProp: "\<Gamma>\<turnstile>(c#cs,css,Stuck) \<rightarrow> (cs,css,Stuck)"
| StuckPropBlock: "\<Gamma>\<turnstile>([],(nrms,abrs)#css,Stuck) \<rightarrow> (nrms,css,Stuck)"
| DynCom: "\<Gamma>\<turnstile>(DynCom c#cs,css,Normal s) \<rightarrow> (c s#cs,css,Normal s)"
| Throw: "\<Gamma>\<turnstile>(Throw#cs,css,Normal s) \<rightarrow> (cs,css,Abrupt s)"
| Catch: "\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2#cs,css,Normal s) \<rightarrow> ([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s)"
lemmas step_induct = step.induct [of _ "(c,css,s)" "(c',css',s')", split_format (complete),
case_names
Skip Guard GuardFault FaultProp FaultPropBlock AbruptProp ExitBlockNormal ExitBlockAbrupt
Basic Spec SpecStuck Seq CondTrue CondFalse WhileTrue WhileFalse Call CallUndefined
StuckProp StuckPropBlock DynCom Throw Catch, induct set]
inductive_cases step_elim_cases [cases set]:
"\<Gamma>\<turnstile>(c#cs,css,Fault f) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Fault f) \<rightarrow> u"
"\<Gamma>\<turnstile>(c#cs,css,Stuck) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Stuck) \<rightarrow> u"
"\<Gamma>\<turnstile>(c#cs,css,Abrupt s) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Abrupt s) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Skip#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Guard f g c#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Basic f#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Spec r#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Seq c1 c2#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Cond b c1 c2#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(While b c#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Call p#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(DynCom c#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Throw#cs,css,s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Catch c1 c2#cs,css,s) \<rightarrow> u"
inductive_cases step_Normal_elim_cases [cases set]:
"\<Gamma>\<turnstile>(c#cs,css,Fault f) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Fault f) \<rightarrow> u"
"\<Gamma>\<turnstile>(c#cs,css,Stuck) \<rightarrow> u"
"\<Gamma>\<turnstile>([],css,Stuck) \<rightarrow> u"
"\<Gamma>\<turnstile>([],(nrms,abrs)#css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>([],(nrms,abrs)#css,Abrupt s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Skip#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Guard f g c#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Basic f#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Spec r#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Seq c1 c2#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Cond b c1 c2#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(While b c#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Call p#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(DynCom c#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Throw#cs,css,Normal s) \<rightarrow> u"
"\<Gamma>\<turnstile>(Catch c1 c2#cs,css,Normal s) \<rightarrow> u"
abbreviation
"step_rtrancl" :: "[('s,'p,'f) body,('s,'p,'f) config,('s,'p,'f) config] \<Rightarrow> bool"
("_\<turnstile> (_ \<rightarrow>\<^sup>*/ _)" [81,81,81] 100)
where
"\<Gamma>\<turnstile>cs0 \<rightarrow>\<^sup>* cs1 == (step \<Gamma>)\<^sup>*\<^sup>* cs0 cs1"
abbreviation
"step_trancl" :: "[('s,'p,'f) body,('s,'p,'f) config,('s,'p,'f) config] \<Rightarrow> bool"
("_\<turnstile> (_ \<rightarrow>\<^sup>+/ _)" [81,81,81] 100)
where
"\<Gamma>\<turnstile>cs0 \<rightarrow>\<^sup>+ cs1 == (step \<Gamma>)\<^sup>+\<^sup>+ cs0 cs1"
subsubsection \<open>Structural Properties of Small Step Computations\<close>
lemma Fault_app_steps: "\<Gamma>\<turnstile>(cs@xs,css,Fault f) \<rightarrow>\<^sup>* (xs,css,Fault f)"
proof (induct cs)
case Nil thus ?case by simp
next
case (Cons c cs)
have "\<Gamma>\<turnstile>(c#cs@xs, css, Fault f) \<rightarrow>\<^sup>* (xs, css, Fault f)"
proof -
have "\<Gamma>\<turnstile>(c#cs@xs, css, Fault f) \<rightarrow> (cs@xs, css, Fault f)"
by (rule step.FaultProp)
also
have "\<Gamma>\<turnstile>(cs@xs, css, Fault f) \<rightarrow>\<^sup>* (xs, css, Fault f)"
by (rule Cons.hyps)
finally show ?thesis .
qed
thus ?case
by simp
qed
lemma Stuck_app_steps: "\<Gamma>\<turnstile>(cs@xs,css,Stuck) \<rightarrow>\<^sup>* (xs,css,Stuck)"
proof (induct cs)
case Nil thus ?case by simp
next
case (Cons c cs)
have "\<Gamma>\<turnstile>(c#cs@xs, css, Stuck) \<rightarrow>\<^sup>* (xs, css, Stuck)"
proof -
have "\<Gamma>\<turnstile>(c#cs@xs, css, Stuck) \<rightarrow> (cs@xs, css, Stuck)"
by (rule step.StuckProp)
also
have "\<Gamma>\<turnstile>(cs@xs, css, Stuck) \<rightarrow>\<^sup>* (xs, css, Stuck)"
by (rule Cons.hyps)
finally show ?thesis .
qed
thus ?case
by simp
qed
text \<open>We can only append commands inside a block, if execution does not
enter or exit a block.
\<close>
lemma app_step:
assumes step: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css',t)"
shows "css=css' \<Longrightarrow> \<Gamma>\<turnstile>(cs@xs,css,s) \<rightarrow> (cs'@xs,css',t)"
using step
apply induct
apply (simp_all del: fun_upd_apply,(blast intro: step.intros)+)
done
text \<open>We can append whole blocks, without interfering with the actual
block. Outer blocks do not influence execution of
inner blocks.\<close>
lemma app_css_step:
assumes step: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css',t)"
shows "\<Gamma>\<turnstile>(cs,css@xs,s) \<rightarrow> (cs',css'@xs,t)"
using step
apply induct
apply (simp_all del: fun_upd_apply,(blast intro: step.intros)+)
done
ML \<open>
ML_Thms.bind_thm ("trancl_induct3", Split_Rule.split_rule @{context}
(Rule_Insts.read_instantiate @{context}
[((("a", 0), Position.none), "(ax, ay, az)"),
((("b", 0), Position.none), "(bx, by, bz)")] []
@{thm tranclp_induct}));
\<close>
lemma app_css_steps:
assumes step: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>+ (cs',css',t)"
shows "\<Gamma>\<turnstile>(cs,css@xs,s) \<rightarrow>\<^sup>+ (cs',css'@xs,t)"
apply(rule trancl_induct3 [OF step])
apply (rule app_css_step [THEN tranclp.r_into_trancl [of "step \<Gamma>"]],assumption)
apply(blast intro:app_css_step tranclp_trans)
done
lemma step_Cons':
assumes step: "\<Gamma>\<turnstile>(ccs,css,s) \<rightarrow> (cs',css',t)"
shows
"\<And>c cs. ccs=c#cs \<Longrightarrow> \<exists>css''. css'=css''@css \<and>
(if css''=[] then \<exists>p. cs'=p@cs
else (\<exists>pnorm pabr. css''=[(pnorm@cs,pabr@cs)]))"
using step
by induct force+
lemma step_Cons:
assumes step: "\<Gamma>\<turnstile>(c#cs,css,s) \<rightarrow> (cs',css',t)"
shows "\<exists>pcss. css'=pcss@css \<and>
(if pcss=[] then \<exists>ps. cs'=ps@cs
else (\<exists>pcs_normal pcs_abrupt. pcss=[(pcs_normal@cs,pcs_abrupt@cs)]))"
using step_Cons' [OF step]
by blast
lemma step_Nil':
assumes step: "\<Gamma>\<turnstile>(cs,asscss,s) \<rightarrow> (cs',css',t)"
shows
"\<And>ass. \<lbrakk>cs=[]; asscss=ass@css; ass\<noteq>Nil\<rbrakk> \<Longrightarrow>
css'=tl ass@css \<and>
(case s of
Abrupt s' \<Rightarrow> cs'=snd (hd ass) \<and> t=Normal s'
| _ \<Rightarrow> cs'=fst (hd ass) \<and> t=s)"
using step
by (induct) (fastforce simp add: neq_Nil_conv)+
lemma step_Nil:
assumes step: "\<Gamma>\<turnstile>([],ass@css,s) \<rightarrow> (cs',css',t)"
assumes ass_not_Nil: "ass\<noteq>[]"
shows "css'=tl ass@css \<and>
(case s of
Abrupt s' \<Rightarrow> cs'=snd (hd ass) \<and> t=Normal s'
| _ \<Rightarrow> cs'=fst (hd ass) \<and> t=s)"
using step_Nil' [OF step _ _ ass_not_Nil]
by simp
lemma step_Nil'':
assumes step: "\<Gamma>\<turnstile>([],(pcs_normal,pcs_abrupt)#pcss@css,s) \<rightarrow> (cs',pcss@css,t)"
shows "(case s of
Abrupt s' \<Rightarrow> cs'=pcs_abrupt \<and> t=Normal s'
| _ \<Rightarrow> cs'=pcs_normal \<and> t=s)"
using step_Nil' [OF step, where ass ="(pcs_normal,pcs_abrupt)#pcss" and css="css"]
by (auto split: xstate.splits)
lemma drop_suffix_css_step':
assumes step: "\<Gamma>\<turnstile>(cs,cssxs,s) \<rightarrow> (cs',css'xs,t)"
shows "\<And>css css' xs. \<lbrakk>cssxs = css@xs; css'xs=css'@xs\<rbrakk>
\<Longrightarrow> \<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css',t)"
using step
apply induct
apply (fastforce intro: step.intros)+
done
lemma drop_suffix_css_step:
assumes step: "\<Gamma>\<turnstile>(cs,pcss@css,s) \<rightarrow> (cs',pcss'@css,t)"
shows "\<Gamma>\<turnstile>(cs,pcss,s) \<rightarrow> (cs',pcss',t)"
using step by (blast intro: drop_suffix_css_step')
lemma drop_suffix_hd_css_step':
assumes step: "\<Gamma>\<turnstile> (pcs,css,s) \<rightarrow> (cs',css'css,t)"
shows "\<And>p ps cs pnorm pabr. \<lbrakk>pcs=p#ps@cs; css'css=(pnorm@cs,pabr@cs)#css\<rbrakk>
\<Longrightarrow> \<Gamma>\<turnstile> (p#ps,css,s) \<rightarrow> (cs',(pnorm,pabr)#css,t)"
using step
by induct (force intro: step.intros)+
lemma drop_suffix_hd_css_step'':
assumes step: "\<Gamma>\<turnstile> (p#ps@cs,css,s) \<rightarrow> (cs',(pnorm@cs,pabr@cs)#css,t)"
shows "\<Gamma>\<turnstile> (p#ps,css,s) \<rightarrow> (cs',(pnorm,pabr)#css,t)"
using drop_suffix_hd_css_step' [OF step]
by auto
lemma drop_suffix_hd_css_step:
assumes step: "\<Gamma>\<turnstile> (p#ps@cs,css,s) \<rightarrow> (cs',[(pnorm@ps@cs,pabr@ps@cs)]@css,t)"
shows "\<Gamma>\<turnstile> (p#ps,css,s) \<rightarrow> (cs',[(pnorm@ps,pabr@ps)]@css,t)"
proof -
from step drop_suffix_hd_css_step'' [of _ p ps cs css s cs' "pnorm@ps" "pabr@ps" t]
show ?thesis
by auto
qed
lemma drop_suffix':
assumes step: "\<Gamma>\<turnstile>(csxs,css,s) \<rightarrow> (cs'xs,css',t)"
shows "\<And>xs cs cs'. \<lbrakk>css=css'; csxs=cs@xs; cs'xs = cs'@xs; cs\<noteq>[] \<rbrakk>
\<Longrightarrow> \<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css,t)"
using step
apply induct
apply (fastforce intro: step.intros simp add: neq_Nil_conv)+
done
lemma drop_suffix:
assumes step: "\<Gamma>\<turnstile>(c#cs@xs,css,s) \<rightarrow> (cs'@xs,css,t)"
shows "\<Gamma>\<turnstile>(c#cs,css,s) \<rightarrow> (cs',css,t)"
by(rule drop_suffix' [OF step _ _ _]) auto
lemma drop_suffix_same_css_step:
assumes step: "\<Gamma>\<turnstile>(cs@xs,css,s) \<rightarrow> (cs'@xs,css,t)"
assumes not_Nil: "cs\<noteq>[]"
shows "\<Gamma>\<turnstile>(cs,xss,s) \<rightarrow> (cs',xss,t)"
proof-
from drop_suffix' [OF step _ _ _ not_Nil]
have "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css,t)"
by auto
with drop_suffix_css_step [of _ cs "[]" css s cs' "[]" t]
have "\<Gamma>\<turnstile> (cs, [], s) \<rightarrow> (cs', [], t)"
by auto
from app_css_step [OF this]
show ?thesis
by auto
qed
lemma Cons_change_css_step:
assumes step: "\<Gamma>\<turnstile> (cs,css,s) \<rightarrow> (cs',css'@css,t)"
shows "\<Gamma>\<turnstile> (cs,xss,s) \<rightarrow> (cs',css'@xss,t)"
proof -
from step
drop_suffix_css_step [where cs=cs and pcss="[]" and css=css and s=s
and cs'=cs' and pcss'=css' and t=t]
have "\<Gamma>\<turnstile> (cs, [], s) \<rightarrow> (cs', css', t)"
by auto
from app_css_step [where xs=xss, OF this]
show ?thesis
by auto
qed
lemma Nil_change_css_step:
assumes step: "\<Gamma>\<turnstile>([],ass@css,s) \<rightarrow> (cs',ass'@css,t)"
assumes ass_not_Nil: "ass\<noteq>[]"
shows "\<Gamma>\<turnstile>([],ass@xss,s) \<rightarrow> (cs',ass'@xss,t)"
proof -
from step drop_suffix_css_step [of _ "[]" ass css s cs' ass' t]
have "\<Gamma>\<turnstile> ([], ass, s) \<rightarrow> (cs', ass', t)"
by auto
from app_css_step [where xs=xss, OF this]
show ?thesis
by auto
qed
subsubsection \<open>Equivalence between Big and Small-Step Semantics\<close>
lemma exec_impl_steps:
assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t"
shows "\<And>cs css. \<Gamma>\<turnstile>(c#cs,css,s) \<rightarrow>\<^sup>* (cs,css,t)"
using exec
proof (induct)
case Skip thus ?case by (blast intro: step.Skip)
next
case Guard thus ?case by (blast intro: step.Guard rtranclp_trans)
next
case GuardFault thus ?case by (blast intro: step.GuardFault)
next
case FaultProp thus ?case by (blast intro: step.FaultProp)
next
case Basic thus ?case by (blast intro: step.Basic)
next
case Spec thus ?case by (blast intro: step.Spec)
next
case SpecStuck thus ?case by (blast intro: step.SpecStuck)
next
case Seq thus ?case by (blast intro: step.Seq rtranclp_trans)
next
case CondTrue thus ?case by (blast intro: step.CondTrue rtranclp_trans)
next
case CondFalse thus ?case by (blast intro: step.CondFalse rtranclp_trans)
next
case WhileTrue thus ?case by (blast intro: step.WhileTrue rtranclp_trans)
next
case WhileFalse thus ?case by (blast intro: step.WhileFalse)
next
case (Call p bdy s s' cs css)
have bdy: "\<Gamma> p = Some bdy" by fact
have steps_body: "\<Gamma>\<turnstile>([bdy],(cs,Throw#cs)#css,Normal s) \<rightarrow>\<^sup>*
([],(cs,Throw#cs)#css, s')" by fact
show ?case
proof (cases s')
case (Normal s'')
note steps_body
also from Normal have "\<Gamma>\<turnstile>([],(cs,Throw#cs)#css, s') \<rightarrow> (cs,css,s')"
by (auto intro: step.intros)
finally show ?thesis
using bdy
by (blast intro: step.Call rtranclp_trans)
next
case (Abrupt s'')
with steps_body
have "\<Gamma>\<turnstile>([bdy],(cs,Throw#cs)#css,Normal s) \<rightarrow>\<^sup>*
([],(cs,Throw#cs)#css, Abrupt s'')" by simp
also have "\<Gamma>\<turnstile>([],(cs,Throw#cs)#css, Abrupt s'') \<rightarrow> (Throw#cs,css,Normal s'')"
by (rule ExitBlockAbrupt)
also have "\<Gamma>\<turnstile>(Throw#cs,css,Normal s'') \<rightarrow> (cs,css,Abrupt s'')"
by (rule Throw)
finally show ?thesis
using bdy Abrupt
by (auto intro: step.Call rtranclp_trans)
next
case Fault
note steps_body
also from Fault have "\<Gamma>\<turnstile>([],(cs,Throw#cs)#css, s') \<rightarrow> (cs,css,s')"
by (auto intro: step.intros)
finally show ?thesis
using bdy
by (blast intro: step.Call rtranclp_trans)
next
case Stuck
note steps_body
also from Stuck have "\<Gamma>\<turnstile>([],(cs,Throw#cs)#css, s') \<rightarrow> (cs,css,s')"
by (auto intro: step.intros)
finally show ?thesis
using bdy
by (blast intro: step.Call rtranclp_trans)
qed
next
case (CallUndefined p s cs css)
have undef: "\<Gamma> p = None" by fact
hence "\<Gamma>\<turnstile>(Call p # cs, css, Normal s) \<rightarrow> (cs, css, Stuck)"
by (rule step.CallUndefined)
thus ?case ..
next
case StuckProp thus ?case by (blast intro: step.StuckProp rtrancl_trans)
next
case DynCom thus ?case by (blast intro: step.DynCom rtranclp_trans)
next
case Throw thus ?case by (blast intro: step.Throw)
next
case AbruptProp thus ?case by (blast intro: step.AbruptProp)
next
case (CatchMatch c\<^sub>1 s s' c\<^sub>2 s'' cs css)
have steps_c1: "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>*
([],(cs,c\<^sub>2#cs)#css,Abrupt s')" by fact
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Abrupt s') \<rightarrow> (c\<^sub>2#cs,css,Normal s')"
by (rule ExitBlockAbrupt)
also
have steps_c2: "\<Gamma>\<turnstile>(c\<^sub>2#cs,css,Normal s') \<rightarrow>\<^sup>* (cs,css,s'')" by fact
finally
show "\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal s) \<rightarrow>\<^sup>* (cs, css, s'')"
by (blast intro: step.Catch rtranclp_trans)
next
case (CatchMiss c\<^sub>1 s s' c\<^sub>2 cs css)
assume notAbr: "\<not> isAbr s'"
have steps_c1: "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,s')" by fact
show "\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal s) \<rightarrow>\<^sup>* (cs, css, s')"
proof (cases s')
case (Normal w)
with steps_c1
have "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,Normal w)"
by simp
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Normal w) \<rightarrow> (cs,css,Normal w)"
by (rule ExitBlockNormal)
finally show ?thesis using Normal
by (auto intro: step.Catch rtranclp_trans)
next
case Abrupt with notAbr show ?thesis by simp
next
case (Fault f)
with steps_c1
have "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,Fault f)"
by simp
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Fault f) \<rightarrow> (cs,css,Fault f)"
by (rule FaultPropBlock)
finally show ?thesis using Fault
by (auto intro: step.Catch rtranclp_trans)
next
case Stuck
with steps_c1
have "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal s) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,Stuck)"
by simp
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Stuck) \<rightarrow> (cs,css,Stuck)"
by (rule StuckPropBlock)
finally show ?thesis using Stuck
by (auto intro: step.Catch rtranclp_trans)
qed
qed
inductive "execs"::"[('s,'p,'f) body,('s,'p,'f) com list,
('s,'p,'f) continuation list,
('s,'f) xstate,('s,'f) xstate] \<Rightarrow> bool"
("_\<turnstile> \<langle>_,_,_\<rangle> \<Rightarrow> _" [50,50,50,50,50] 50)
for \<Gamma>:: "('s,'p,'f) body"
where
Nil: "\<Gamma>\<turnstile>\<langle>[],[],s\<rangle> \<Rightarrow> s"
| ExitBlockNormal: "\<Gamma>\<turnstile>\<langle>nrms,css,Normal s\<rangle> \<Rightarrow> t
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>[],(nrms,abrs)#css,Normal s\<rangle> \<Rightarrow> t"
| ExitBlockAbrupt: "\<Gamma>\<turnstile>\<langle>abrs,css,Normal s\<rangle> \<Rightarrow> t
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>[],(nrms,abrs)#css,Abrupt s\<rangle> \<Rightarrow> t"
| ExitBlockFault: "\<Gamma>\<turnstile>\<langle>nrms,css,Fault f\<rangle> \<Rightarrow> t
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>[],(nrms,abrs)#css,Fault f\<rangle> \<Rightarrow> t"
| ExitBlockStuck: "\<Gamma>\<turnstile>\<langle>nrms,css,Stuck\<rangle> \<Rightarrow> t
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>[],(nrms,abrs)#css,Stuck\<rangle> \<Rightarrow> t"
| Cons: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t; \<Gamma>\<turnstile>\<langle>cs,css,t\<rangle> \<Rightarrow> u\<rbrakk>
\<Longrightarrow>
\<Gamma>\<turnstile>\<langle>c#cs,css,s\<rangle> \<Rightarrow> u"
inductive_cases execs_elim_cases [cases set]:
"\<Gamma>\<turnstile>\<langle>[],css,s\<rangle> \<Rightarrow> t"
"\<Gamma>\<turnstile>\<langle>c#cs,css,s\<rangle> \<Rightarrow> t"
ML \<open>
ML_Thms.bind_thm ("converse_rtrancl_induct3", Split_Rule.split_rule @{context}
(Rule_Insts.read_instantiate @{context}
[((("a", 0), Position.none), "(cs, css, s)"),
((("b", 0), Position.none), "(cs', css', t)")] []
@{thm converse_rtranclp_induct}));
\<close>
lemma execs_Fault_end:
assumes execs: "\<Gamma>\<turnstile>\<langle>cs,css,s\<rangle> \<Rightarrow> t" shows "s=Fault f\<Longrightarrow> t=Fault f"
using execs
by (induct) (auto dest: Fault_end)
lemma execs_Stuck_end:
assumes execs: "\<Gamma>\<turnstile>\<langle>cs,css,s\<rangle> \<Rightarrow> t" shows "s=Stuck \<Longrightarrow> t=Stuck"
using execs
by (induct) (auto dest: Stuck_end)
theorem steps_impl_execs:
assumes steps: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* ([],[],t)"
shows "\<Gamma>\<turnstile>\<langle>cs,css,s\<rangle> \<Rightarrow> t"
using steps
proof (induct rule: converse_rtrancl_induct3 [consumes 1])
show "\<Gamma>\<turnstile>\<langle>[],[],t\<rangle> \<Rightarrow> t" by (rule execs.Nil)
next
fix cs css s cs' css' w
assume step: "\<Gamma>\<turnstile>(cs,css, s) \<rightarrow> (cs',css', w)"
assume execs: "\<Gamma>\<turnstile>\<langle>cs',css',w\<rangle> \<Rightarrow> t"
from step
show "\<Gamma>\<turnstile>\<langle>cs,css,s\<rangle> \<Rightarrow> t"
proof (cases)
case (Catch c1 c2 cs s)
with execs obtain t' where
exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> t'" and
execs_rest: "\<Gamma>\<turnstile>\<langle>[],(cs, c2 # cs) # css,t'\<rangle> \<Rightarrow> t"
by (clarsimp elim!: execs_elim_cases)
have "\<Gamma>\<turnstile>\<langle>Catch c1 c2 # cs,css,Normal s\<rangle> \<Rightarrow> t"
proof (cases t')
case (Normal t'')
with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> t'"
by (auto intro: exec.CatchMiss)
moreover
from execs_rest Normal have "\<Gamma>\<turnstile>\<langle>cs,css,t'\<rangle> \<Rightarrow> t"
by (cases) auto
ultimately show ?thesis
by (rule execs.Cons)
next
case (Abrupt t'')
from execs_rest Abrupt have "\<Gamma>\<turnstile>\<langle>c2#cs,css,Normal t''\<rangle> \<Rightarrow> t"
by (cases) auto
then obtain v where
exec_c2: "\<Gamma>\<turnstile>\<langle>c2,Normal t''\<rangle> \<Rightarrow> v" and
rest: "\<Gamma>\<turnstile>\<langle>cs,css,v\<rangle> \<Rightarrow> t"
by cases
from exec_c1 Abrupt exec_c2
have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> v"
by - (rule exec.CatchMatch, auto)
from this rest
show ?thesis
by (rule execs.Cons)
next
case (Fault f)
with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> Fault f"
by (auto intro: exec.intros)
moreover from execs_rest Fault have "\<Gamma>\<turnstile>\<langle>cs,css,Fault f\<rangle> \<Rightarrow> t"
by (cases) auto
ultimately show ?thesis
by (rule execs.Cons)
next
case Stuck
with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> Stuck"
by (auto intro: exec.intros)
moreover from execs_rest Stuck have "\<Gamma>\<turnstile>\<langle>cs,css,Stuck\<rangle> \<Rightarrow> t"
by (cases) auto
ultimately show ?thesis
by (rule execs.Cons)
qed
with Catch show ?thesis by simp
next
case (Call p bdy cs s)
have bdy: "\<Gamma> p = Some bdy" by fact
from Call execs obtain t' where
exec_body: "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> \<Rightarrow> t'" and
execs_rest:
"\<Gamma>\<turnstile>\<langle>[],(cs,Throw#cs)#css ,t'\<rangle> \<Rightarrow> t"
by (clarsimp elim!: execs_elim_cases)
have "\<Gamma>\<turnstile>\<langle>Call p # cs,css,Normal s\<rangle> \<Rightarrow> t"
proof (cases t')
case (Normal t'')
with exec_body bdy
have "\<Gamma>\<turnstile>\<langle>Call p ,Normal s\<rangle> \<Rightarrow> Normal t''"
by (auto intro: exec.intros)
moreover
from execs_rest Normal
have "\<Gamma>\<turnstile>\<langle>cs,css ,Normal t''\<rangle> \<Rightarrow> t"
by cases auto
ultimately show ?thesis by (rule execs.Cons)
next
case (Abrupt t'')
with exec_body bdy
have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Abrupt t''"
by (auto intro: exec.intros)
moreover
from execs_rest Abrupt have
"\<Gamma>\<turnstile>\<langle>Throw # cs,css,Normal t''\<rangle> \<Rightarrow> t"
by (cases) auto
then obtain v where v: "\<Gamma>\<turnstile>\<langle>Throw,Normal t''\<rangle> \<Rightarrow> v" "\<Gamma>\<turnstile>\<langle>cs,css,v\<rangle> \<Rightarrow> t"
by (clarsimp elim!: execs_elim_cases)
moreover from v have "v=Abrupt t''"
by (auto elim: exec_Normal_elim_cases)
ultimately
show ?thesis by (auto intro: execs.Cons)
next
case (Fault f)
with exec_body bdy have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Fault f"
by (auto intro: exec.intros)
moreover from execs_rest Fault have "\<Gamma>\<turnstile>\<langle>cs,css,Fault f\<rangle> \<Rightarrow> t"
by (cases) (auto elim: execs_elim_cases dest: Fault_end)
ultimately
show ?thesis by (rule execs.Cons)
next
case Stuck
with exec_body bdy have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Stuck"
by (auto intro: exec.intros)
moreover from execs_rest Stuck have "\<Gamma>\<turnstile>\<langle>cs,css,Stuck\<rangle> \<Rightarrow> t"
by (cases) (auto elim: execs_elim_cases dest: Stuck_end)
ultimately
show ?thesis by (rule execs.Cons)
qed
with Call show ?thesis by simp
qed (insert execs,
(blast intro:execs.intros exec.intros elim!: execs_elim_cases)+)
qed
theorem steps_impl_exec:
assumes steps: "\<Gamma>\<turnstile>([c],[],s) \<rightarrow>\<^sup>* ([],[],t)"
shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t"
using steps_impl_execs [OF steps]
by (blast elim: execs_elim_cases)
corollary steps_eq_exec: "\<Gamma>\<turnstile>([c],[],s) \<rightarrow>\<^sup>* ([],[],t) = \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t"
by (blast intro: steps_impl_exec exec_impl_steps)
subsection \<open>Infinite Computations: \<open>inf \<Gamma> cs css s\<close>\<close>
definition inf ::
"[('s,'p,'f) body,('s,'p,'f) com list,('s,'p,'f) continuation list,('s,'f) xstate]
\<Rightarrow> bool"
where "inf \<Gamma> cs css s = (\<exists>f. f 0 = (cs,css,s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f(Suc i)))"
lemma not_infI: "\<lbrakk>\<And>f. \<lbrakk>f 0 = (cs,css,s); \<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)\<rbrakk> \<Longrightarrow> False\<rbrakk>
\<Longrightarrow> \<not>inf \<Gamma> cs css s"
by (auto simp add: inf_def)
subsection \<open>Equivalence of Termination and Absence of Infinite Computations\<close>
inductive "terminatess":: "[('s,'p,'f) body,('s,'p,'f) com list,
('s,'p,'f) continuation list,('s,'f) xstate] \<Rightarrow> bool"
("_\<turnstile>_,_ \<Down> _" [60,20,60] 89)
for \<Gamma>::"('s,'p,'f) body"
where
Nil: "\<Gamma>\<turnstile>[],[]\<Down>s"
| ExitBlockNormal: "\<Gamma>\<turnstile>nrms,css\<Down>Normal s
\<Longrightarrow>
\<Gamma>\<turnstile>[],(nrms,abrs)#css\<Down>Normal s"
| ExitBlockAbrupt: "\<Gamma>\<turnstile>abrs,css\<Down>Normal s
\<Longrightarrow>
\<Gamma>\<turnstile>[],(nrms,abrs)#css\<Down>Abrupt s"
| ExitBlockFault: "\<Gamma>\<turnstile>nrms,css\<Down>Fault f
\<Longrightarrow>
\<Gamma>\<turnstile>[],(nrms,abrs)#css\<Down>Fault f"
| ExitBlockStuck: "\<Gamma>\<turnstile>nrms,css\<Down>Stuck
\<Longrightarrow>
\<Gamma>\<turnstile>[],(nrms,abrs)#css\<Down>Stuck"
| Cons: "\<lbrakk>\<Gamma>\<turnstile>c\<down>s; (\<forall>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<longrightarrow> \<Gamma>\<turnstile>cs,css\<Down>t)\<rbrakk>
\<Longrightarrow>
\<Gamma>\<turnstile>c#cs,css\<Down>s"
inductive_cases terminatess_elim_cases [cases set]:
"\<Gamma>\<turnstile>[],css\<Down>t"
"\<Gamma>\<turnstile>c#cs,css\<Down>t"
lemma terminatess_Fault: "\<And>cs. \<Gamma>\<turnstile>cs,css\<Down>Fault f"
proof (induct css)
case Nil
show "\<Gamma>\<turnstile>cs,[]\<Down>Fault f"
proof (induct cs)
case Nil show "\<Gamma>\<turnstile>[],[]\<Down>Fault f" by (rule terminatess.Nil)
next
case (Cons c cs)
thus ?case
by (auto intro: terminatess.intros terminates.intros dest: Fault_end)
qed
next
case (Cons d css)
have hyp: "\<And>cs. \<Gamma>\<turnstile>cs,css\<Down>Fault f" by fact
obtain nrms abrs where d: "d=(nrms,abrs)" by (cases d) auto
have "\<Gamma>\<turnstile>cs,(nrms,abrs)#css\<Down>Fault f"
proof (induct cs)
case Nil
show "\<Gamma>\<turnstile>[],(nrms, abrs) # css\<Down>Fault f"
by (rule terminatess.ExitBlockFault) (rule hyp)
next
case (Cons c cs)
have hyp1: "\<Gamma>\<turnstile>cs,(nrms, abrs) # css\<Down>Fault f" by fact
show "\<Gamma>\<turnstile>c#cs,(nrms, abrs)#css\<Down>Fault f"
by (auto intro: hyp1 terminatess.Cons terminates.intros dest: Fault_end)
qed
with d show ?case by simp
qed
lemma terminatess_Stuck: "\<And>cs. \<Gamma>\<turnstile>cs,css\<Down>Stuck"
proof (induct css)
case Nil
show "\<Gamma>\<turnstile>cs,[]\<Down>Stuck"
proof (induct cs)
case Nil show "\<Gamma>\<turnstile>[],[]\<Down>Stuck" by (rule terminatess.Nil)
next
case (Cons c cs)
thus ?case
by (auto intro: terminatess.intros terminates.intros dest: Stuck_end)
qed
next
case (Cons d css)
have hyp: "\<And>cs. \<Gamma>\<turnstile>cs,css\<Down>Stuck" by fact
obtain nrms abrs where d: "d=(nrms,abrs)" by (cases d) auto
have "\<Gamma>\<turnstile>cs,(nrms,abrs)#css\<Down>Stuck"
proof (induct cs)
case Nil
show "\<Gamma>\<turnstile>[],(nrms, abrs) # css\<Down>Stuck"
by (rule terminatess.ExitBlockStuck) (rule hyp)
next
case (Cons c cs)
have hyp1: "\<Gamma>\<turnstile>cs,(nrms, abrs) # css\<Down>Stuck" by fact
show "\<Gamma>\<turnstile>c#cs,(nrms, abrs)#css\<Down>Stuck"
by (auto intro: hyp1 terminatess.Cons terminates.intros dest: Stuck_end)
qed
with d show ?case by simp
qed
lemma Basic_terminates: "\<Gamma>\<turnstile>Basic f \<down> t"
by (cases t) (auto intro: terminates.intros)
lemma step_preserves_terminations:
assumes step: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow> (cs',css',t)"
shows "\<Gamma>\<turnstile>cs,css\<Down>s \<Longrightarrow> \<Gamma>\<turnstile>cs',css'\<Down>t"
using step
proof (induct)
case Skip thus ?case
by (auto elim: terminates_Normal_elim_cases terminatess_elim_cases
intro: exec.intros)
next
case Guard thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case GuardFault thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case FaultProp show ?case by (rule terminatess_Fault)
next
case FaultPropBlock show ?case by (rule terminatess_Fault)
next
case AbruptProp thus ?case
by (blast elim: terminatess_elim_cases
intro: terminatess.intros)
next
case ExitBlockNormal thus ?case
by (blast elim: terminatess_elim_cases
intro: terminatess.intros )
next
case ExitBlockAbrupt thus ?case
by (blast elim: terminatess_elim_cases
intro: terminatess.intros )
next
case Basic thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case Spec thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case SpecStuck thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case Seq thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case CondTrue thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case CondFalse thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case WhileTrue thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case WhileFalse thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case (Call p bdy cs css s)
have bdy: "\<Gamma> p = Some bdy" by fact
from Call obtain
term_body: "\<Gamma>\<turnstile>bdy \<down> Normal s" and
term_rest: "\<forall>t. \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> t \<longrightarrow> \<Gamma>\<turnstile>cs,css\<Down>t"
by (fastforce elim!: terminatess_elim_cases terminates_Normal_elim_cases)
show "\<Gamma>\<turnstile>[bdy],(cs,Throw # cs)#css\<Down>Normal s"
proof (rule terminatess.Cons [OF term_body],clarsimp)
fix t
assume exec_body: "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> \<Rightarrow> t"
show "\<Gamma>\<turnstile>[],(cs,Throw # cs) # css\<Down>t"
proof (cases t)
case (Normal t')
with exec_body bdy
have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Normal t'"
by (auto intro: exec.intros)
with term_rest have "\<Gamma>\<turnstile>cs,css\<Down>Normal t'"
by iprover
with Normal show ?thesis
by (auto intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case (Abrupt t')
with exec_body bdy
have "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Abrupt t'"
by (auto intro: exec.intros)
with term_rest have "\<Gamma>\<turnstile>cs,css\<Down>Abrupt t'"
by iprover
with Abrupt show ?thesis
by (fastforce intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case Fault
thus ?thesis
by (iprover intro: terminatess_Fault)
next
case Stuck
thus ?thesis
by (iprover intro: terminatess_Stuck)
qed
qed
next
case CallUndefined thus ?case
by (iprover intro: terminatess_Stuck)
next
case StuckProp show ?case by (rule terminatess_Stuck)
next
case StuckPropBlock show ?case by (rule terminatess_Stuck)
next
case DynCom thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case Throw thus ?case
by (blast elim: terminatess_elim_cases terminates_Normal_elim_cases
intro: terminatess.intros terminates.intros exec.intros)
next
case (Catch c1 c2 cs css s)
then obtain
term_c1: "\<Gamma>\<turnstile>c1 \<down> Normal s" and
term_c2: "\<forall>s'. \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> Abrupt s' \<longrightarrow> \<Gamma>\<turnstile>c2 \<down> Normal s'"and
term_rest: "\<forall>t. \<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> t \<longrightarrow> \<Gamma>\<turnstile>cs,css\<Down>t"
by (clarsimp elim!: terminatess_elim_cases terminates_Normal_elim_cases)
show "\<Gamma>\<turnstile>[c1],(cs, c2 # cs) # css\<Down>Normal s"
proof (rule terminatess.Cons [OF term_c1],clarsimp)
fix t
assume exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> t"
show "\<Gamma>\<turnstile>[],(cs, c2 # cs) # css\<Down>t"
proof (cases t)
case (Normal t')
with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> t"
by (auto intro: exec.intros)
with term_rest have "\<Gamma>\<turnstile>cs,css\<Down>t"
by iprover
with Normal show ?thesis
by (iprover intro: terminatess.intros)
next
case (Abrupt t')
with exec_c1 term_c2 have "\<Gamma>\<turnstile>c2 \<down> Normal t'"
by auto
moreover
{
fix w
assume exec_c2: "\<Gamma>\<turnstile>\<langle>c2,Normal t'\<rangle> \<Rightarrow> w"
have "\<Gamma>\<turnstile>cs,css\<Down>w"
proof -
from exec_c1 Abrupt exec_c2
have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> w"
by (auto intro: exec.intros)
with term_rest show ?thesis by simp
qed
}
ultimately
show ?thesis using Abrupt
by (auto intro: terminatess.intros)
next
case Fault thus ?thesis
by (iprover intro: terminatess_Fault)
next
case Stuck thus ?thesis
by (iprover intro: terminatess_Stuck)
qed
qed
qed
ML \<open>
ML_Thms.bind_thm ("rtrancl_induct3", Split_Rule.split_rule @{context}
(Rule_Insts.read_instantiate @{context}
[((("a", 0), Position.none), "(ax, ay, az)"),
((("b", 0), Position.none), "(bx, by, bz)")] []
@{thm rtranclp_induct}));
\<close>
lemma steps_preserves_terminations:
assumes steps: "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* (cs',css',t)"
shows "\<Gamma>\<turnstile>cs,css\<Down>s \<Longrightarrow> \<Gamma>\<turnstile>cs',css'\<Down>t"
using steps
proof (induct rule: rtrancl_induct3 [consumes 1])
assume "\<Gamma>\<turnstile>cs,css\<Down>s" then show "\<Gamma>\<turnstile>cs,css\<Down>s".
next
fix cs'' css'' w cs' css' t
assume "\<Gamma>\<turnstile>(cs'',css'', w) \<rightarrow> (cs',css', t)" "\<Gamma>\<turnstile>cs,css\<Down>s \<Longrightarrow> \<Gamma>\<turnstile>cs'',css''\<Down>w"
"\<Gamma>\<turnstile>cs,css\<Down>s"
then show "\<Gamma>\<turnstile>cs',css'\<Down>t"
by (blast dest: step_preserves_terminations)
qed
theorem steps_preserves_termination:
assumes steps: "\<Gamma>\<turnstile>([c],[],s) \<rightarrow>\<^sup>* (c'#cs',css',t)"
assumes term_c: "\<Gamma>\<turnstile>c\<down>s"
shows "\<Gamma>\<turnstile>c'\<down>t"
proof -
from term_c have "\<Gamma>\<turnstile>[c],[]\<Down>s"
by (auto intro: terminatess.intros)
from steps this
have "\<Gamma>\<turnstile>c'#cs',css'\<Down>t"
by (rule steps_preserves_terminations)
thus "\<Gamma>\<turnstile>c'\<down>t"
by (auto elim: terminatess_elim_cases)
qed
lemma renumber':
assumes f: "\<forall>i. (a,f i) \<in> r\<^sup>* \<and> (f i,f(Suc i)) \<in> r"
assumes a_b: "(a,b) \<in> r\<^sup>*"
shows "b = f 0 \<Longrightarrow> (\<exists>f. f 0 = a \<and> (\<forall>i. (f i, f(Suc i)) \<in> r))"
using a_b
proof (induct rule: converse_rtrancl_induct [consumes 1])
assume "b = f 0"
with f show "\<exists>f. f 0 = b \<and> (\<forall>i. (f i, f (Suc i)) \<in> r)"
by blast
next
fix a z
assume a_z: "(a, z) \<in> r" and "(z, b) \<in> r\<^sup>*"
assume "b = f 0 \<Longrightarrow> \<exists>f. f 0 = z \<and> (\<forall>i. (f i, f (Suc i)) \<in> r)"
"b = f 0"
then obtain f where f0: "f 0 = z" and seq: "\<forall>i. (f i, f (Suc i)) \<in> r"
by iprover
{
fix i have "((\<lambda>i. case i of 0 \<Rightarrow> a | Suc i \<Rightarrow> f i) i, f i) \<in> r"
using seq a_z f0
by (cases i) auto
}
then
show "\<exists>f. f 0 = a \<and> (\<forall>i. (f i, f (Suc i)) \<in> r)"
by - (rule exI [where x="\<lambda>i. case i of 0 \<Rightarrow> a | Suc i \<Rightarrow> f i"],simp)
qed
lemma renumber:
"\<forall>i. (a,f i) \<in> r\<^sup>* \<and> (f i,f(Suc i)) \<in> r
\<Longrightarrow> \<exists>f. f 0 = a \<and> (\<forall>i. (f i, f(Suc i)) \<in> r)"
by(blast dest:renumber')
lemma not_inf_Fault':
assumes enum_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
shows "\<And>k cs. f k = (cs,css,Fault m) \<Longrightarrow> False"
proof (induct css)
case Nil
have f_k: "f k = (cs,[],Fault m)" by fact
have "\<And>k. f k = (cs,[],Fault m) \<Longrightarrow> False"
proof (induct cs)
case Nil
have "f k = ([], [], Fault m)" by fact
moreover
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
ultimately show "False"
by (fastforce elim: step_elim_cases)
next
case (Cons c cs)
have fk: "f k = (c # cs, [], Fault m)" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (cs,[],Fault m)"
by (fastforce elim: step_elim_cases)
with enum_step Cons.hyps
show False
by blast
qed
from this f_k show False by blast
next
case (Cons ds css)
then obtain nrms abrs where ds: "ds=(nrms,abrs)" by (cases ds) auto
have hyp: "\<And>k cs. f k = (cs,css,Fault m) \<Longrightarrow> False" by fact
have "\<And>k. f k = (cs,(nrms,abrs)#css,Fault m) \<Longrightarrow> False"
proof (induct cs)
case Nil
have fk: "f k = ([], (nrms, abrs) # css, Fault m)" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (nrms,css,Fault m)"
by (fastforce elim: step_elim_cases)
thus ?case
by (rule hyp)
next
case (Cons c cs)
have fk: "f k = (c#cs, (nrms, abrs) # css, Fault m)" by fact
have hyp1: "\<And>k. f k = (cs, (nrms, abrs) # css, Fault m) \<Longrightarrow> False" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (cs,(nrms,abrs)#css,Fault m)"
by (fastforce elim: step_elim_cases)
thus ?case
by (rule hyp1)
qed
with ds Cons.prems show False by auto
qed
lemma not_inf_Fault:
"\<not> inf \<Gamma> cs css (Fault m)"
apply (rule not_infI)
apply (rule_tac f=f in not_inf_Fault' )
by auto
lemma not_inf_Stuck':
assumes enum_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
shows "\<And>k cs. f k = (cs,css,Stuck) \<Longrightarrow> False"
proof (induct css)
case Nil
have f_k: "f k = (cs,[],Stuck)" by fact
have "\<And>k. f k = (cs,[],Stuck) \<Longrightarrow> False"
proof (induct cs)
case Nil
have "f k = ([], [], Stuck)" by fact
moreover
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
ultimately show "False"
by (fastforce elim: step_elim_cases)
next
case (Cons c cs)
have fk: "f k = (c # cs, [], Stuck)" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (cs,[],Stuck)"
by (fastforce elim: step_elim_cases)
with enum_step Cons.hyps
show False
by blast
qed
from this f_k show False .
next
case (Cons ds css)
then obtain nrms abrs where ds: "ds=(nrms,abrs)" by (cases ds) auto
have hyp: "\<And>k cs. f k = (cs,css,Stuck) \<Longrightarrow> False" by fact
have "\<And>k. f k = (cs,(nrms,abrs)#css,Stuck) \<Longrightarrow> False"
proof (induct cs)
case Nil
have fk: "f k = ([], (nrms, abrs) # css, Stuck)" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (nrms,css,Stuck)"
by (fastforce elim: step_elim_cases)
thus ?case
by (rule hyp)
next
case (Cons c cs)
have fk: "f k = (c#cs, (nrms, abrs) # css, Stuck)" by fact
have hyp1: "\<And>k. f k = (cs, (nrms, abrs) # css, Stuck) \<Longrightarrow> False" by fact
from enum_step have "\<Gamma>\<turnstile>f k \<rightarrow> f (Suc k)"..
with fk have "f (Suc k) = (cs,(nrms,abrs)#css,Stuck)"
by (fastforce elim: step_elim_cases)
thus ?case
by (rule hyp1)
qed
with ds Cons.prems show False by auto
qed
lemma not_inf_Stuck:
"\<not> inf \<Gamma> cs css Stuck"
apply (rule not_infI)
apply (rule_tac f=f in not_inf_Stuck')
by auto
lemma last_butlast_app:
assumes butlast: "butlast as = xs @ butlast bs"
assumes not_Nil: "bs \<noteq> []" "as \<noteq> []"
assumes last: "fst (last as) = fst (last bs)" "snd (last as) = snd (last bs)"
shows "as = xs @ bs"
proof -
from last have "last as = last bs"
by (cases "last as",cases "last bs") simp
moreover
from not_Nil have "as = butlast as @ [last as]" "bs = butlast bs @ [last bs]"
by auto
ultimately show ?thesis
using butlast
by simp
qed
lemma last_butlast_tl:
assumes butlast: "butlast bs = x # butlast as"
assumes not_Nil: "bs \<noteq> []" "as \<noteq> []"
assumes last: "fst (last as) = fst (last bs)" "snd (last as) = snd (last bs)"
shows "as = tl bs"
proof -
from last have "last as = last bs"
by (cases "last as",cases "last bs") simp
moreover
from not_Nil have "as = butlast as @ [last as]" "bs = butlast bs @ [last bs]"
by auto
ultimately show ?thesis
using butlast
by simp
qed
locale inf =
fixes CS:: "('s,'p,'f) config \<Rightarrow> ('s, 'p,'f) com list"
and CSS:: "('s,'p,'f) config \<Rightarrow> ('s, 'p,'f) continuation list"
and S:: "('s,'p,'f) config \<Rightarrow> ('s,'f) xstate"
defines CS_def : "CS \<equiv> fst"
defines CSS_def : "CSS \<equiv> \<lambda>c. fst (snd c)"
defines S_def: "S \<equiv> \<lambda>c. snd (snd c)"
lemma (in inf) steps_hd_drop_suffix:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes not_finished: "\<forall>i < k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
assumes simul: "\<forall>i\<le>k.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
defines "p\<equiv>\<lambda>i. (pcs i, pcss i, S (f i))"
shows "\<forall>i<k. \<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)"
using not_finished simul
proof (induct k)
case 0
thus ?case by simp
next
case (Suc k)
have simul: "\<forall>i\<le>Suc k.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)" by fact
have not_finished': "\<forall>i < Suc k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)" by fact
with simul
have not_finished: "\<forall>i<Suc k. \<not> (pcs i = [] \<and> pcss i = [])"
by (auto simp add: CS_def CSS_def S_def split: if_split_asm)
show ?case
proof (clarify)
fix i
assume i_le_Suc_k: "i < Suc k"
show "\<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)"
proof (cases "i < k")
case True
with not_finished' simul Suc.hyps
show ?thesis
by auto
next
case False
with i_le_Suc_k
have eq_i_k: "i=k"
by simp
show "\<Gamma>\<turnstile>p i \<rightarrow> p (Suc i)"
proof -
obtain cs' css' t' where
f_Suc_i: "f (Suc i) = (cs', css', t')"
by (cases "f (Suc i)")
obtain cs'' css'' t'' where
f_i: "f i = (cs'',css'',t'')"
by (cases "f i")
from not_finished eq_i_k
have pcs_pcss_not_Nil: "\<not> (pcs i = [] \<and> pcss i = [])"
by auto
from simul [rule_format, of i] i_le_Suc_k f_i
have pcs_pcss_i:
"if pcss i = [] then css''=css \<and> cs''=pcs i@cs
else cs''=pcs i \<and>
css''= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css"
by (simp add: CS_def CSS_def S_def cong: if_cong)
from simul [rule_format, of "Suc i"] i_le_Suc_k f_Suc_i
have pcs_pcss_Suc_i:
"if pcss (Suc i) = [] then css' = css \<and> cs' = pcs (Suc i) @ cs
else cs' = pcs (Suc i) \<and>
css' = butlast (pcss (Suc i)) @
[(fst (last (pcss (Suc i))) @ cs, snd (last (pcss (Suc i))) @ cs)] @
css"
by (simp add: CS_def CSS_def S_def cong: if_cong)
show ?thesis
proof (cases "pcss i = []")
case True
note pcss_Nil = this
with pcs_pcss_i pcs_pcss_not_Nil obtain p ps where
pcs_i: "pcs i = p#ps" and
css'': "css''=css" and
cs'': "cs''=(p#ps)@cs"
by (auto simp add: neq_Nil_conv)
with f_i have "f i = (p#(ps@cs),css,t'')"
by simp
with f_Suc_i f_step [rule_format, of i]
have step_css: "\<Gamma>\<turnstile> (p#(ps@cs),css,t'') \<rightarrow> (cs',css',t')"
by simp
from step_Cons' [OF this, of p "ps@cs"]
obtain css''' where
css''': "css' = css''' @ css"
"if css''' = [] then \<exists>p. cs' = p @ ps @ cs
else (\<exists>pnorm pabr. css'''=[(pnorm @ ps @ cs,pabr @ ps @ cs)])"
by auto
show ?thesis
proof (cases "css''' = []")
case True
with css'''
obtain p' where
css': "css' = css" and
cs': "cs' = p' @ ps @ cs"
by auto
(*from cs' css' f_Suc_i f_i [rule_format, of "Suc k"]
have p_ps_not_Nil: "p'@ps \<noteq> Nil"
by auto*)
from css' cs' step_css
have step: "\<Gamma>\<turnstile> (p#(ps@cs),css,t'') \<rightarrow> (p'@ps@cs,css,t')"
by simp
hence "\<Gamma>\<turnstile> ((p#ps)@cs,css,t'') \<rightarrow> ((p'@ps)@cs,css,t')"
by simp
from drop_suffix_css_step' [OF drop_suffix_same_css_step [OF this],
where xs="css" and css="[]" and css'="[]"]
have "\<Gamma>\<turnstile> (p#ps,[],t'') \<rightarrow> (p'@ps,[],t')"
by simp
moreover
from css' cs' pcs_pcss_Suc_i
obtain "pcs (Suc i) = p'@ps" and "pcss (Suc i) = []"
by (simp split: if_split_asm)
ultimately show ?thesis
using pcs_i pcss_Nil f_i f_Suc_i
by (simp add: CS_def CSS_def S_def p_def)
next
case False
with css'''
obtain pnorm pabr where
css': "css'=css'''@css"
"css'''=[(pnorm @ ps @ cs,pabr @ ps @ cs)]"
by auto
with css''' step_css
have "\<Gamma>\<turnstile> (p#ps@cs,css,t'') \<rightarrow> (cs',[(pnorm@ps@cs,pabr@ps@cs)]@css,t')"
by simp
then
have "\<Gamma>\<turnstile>(p#ps, css, t'') \<rightarrow> (cs', [(pnorm@ps, pabr@ps)] @ css, t')"
by (rule drop_suffix_hd_css_step)
from drop_suffix_css_step' [OF this,
where css="[]" and xs="css" and css'="[(pnorm@ps, pabr@ps)]"]
have "\<Gamma>\<turnstile> (p#ps,[],t'') \<rightarrow> (cs',[(pnorm@ps, pabr@ps)],t')"
by simp
moreover
from css' pcs_pcss_Suc_i
obtain "pcs (Suc i) = cs'" "pcss (Suc i) = [(pnorm@ps, pabr@ps)]"
apply (cases "pcss (Suc i)")
apply (auto split: if_split_asm)
done
ultimately show ?thesis
using pcs_i pcss_Nil f_i f_Suc_i
by (simp add: p_def CS_def CSS_def S_def)
qed
next
case False
note pcss_i_not_Nil = this
with pcs_pcss_i obtain
cs'': "cs''=pcs i" and
css'': "css''= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css"
by auto
from f_Suc_i f_i f_step [rule_format, of i]
have step_i_full: "\<Gamma>\<turnstile> (cs'',css'',t'') \<rightarrow> (cs',css',t')"
by simp
show ?thesis
proof (cases cs'')
case (Cons c' cs)
with step_Cons' [OF step_i_full]
obtain css''' where css': "css' = css'''@css''"
by auto
with step_i_full
have "\<Gamma>\<turnstile> (cs'',css'',t'') \<rightarrow> (cs',css'''@css'',t')"
by simp
from Cons_change_css_step [OF this, where xss="pcss i"] Cons cs''
have "\<Gamma>\<turnstile> (pcs i, pcss i,t'') \<rightarrow> (cs',css'''@pcss i,t')"
by simp
moreover
from cs'' css'' css' False pcs_pcss_Suc_i
obtain "pcs (Suc i) = cs'" "pcss (Suc i) = css'''@pcss i"
apply (auto split: if_split_asm)
apply (drule (4) last_butlast_app)
by simp
ultimately show ?thesis
using f_i f_Suc_i
by (simp add: p_def CS_def CSS_def S_def)
next
case Nil
note cs''_Nil = this
show ?thesis
proof (cases "butlast (pcss i)")
case (Cons bpcs bpcss)
with cs''_Nil step_i_full css''
have *: "\<Gamma>\<turnstile> ([],[hd css'']@tl css'',t'') \<rightarrow> (cs',css',t')"
by simp
moreover
from step_Nil [OF *]
have css': "css'=tl css''"
by simp
ultimately have
step_i_full: "\<Gamma>\<turnstile> ([],[hd css'']@tl css'',t'') \<rightarrow> (cs',tl css'',t')"
by simp
from css'' Cons pcss_i_not_Nil
have "hd css'' = hd (pcss i)"
by (auto simp add: neq_Nil_conv split: if_split_asm)
with cs'' cs''_Nil
Nil_change_css_step [where ass="[hd css'']" and
css="tl css''" and ass'="[]" and
xss="tl (pcss i)", simplified, OF step_i_full [simplified]]
have "\<Gamma>\<turnstile> (pcs i,[hd (pcss i)]@tl (pcss i),t'') \<rightarrow> (cs',tl (pcss i),t')"
by simp
with pcss_i_not_Nil
have "\<Gamma>\<turnstile> (pcs i,pcss i,t'') \<rightarrow> (cs',tl (pcss i),t')"
by simp
moreover
from css' css'' cs''_Nil Cons pcss_i_not_Nil pcs_pcss_Suc_i
obtain "pcs (Suc i) = cs'" "pcss (Suc i) = tl (pcss i)"
apply (clarsimp split: if_split_asm)
apply (drule (4) last_butlast_tl)
by simp
ultimately show ?thesis
using f_i f_Suc_i
by (simp add: p_def CS_def CSS_def S_def)
next
case Nil
with css'' pcss_i_not_Nil
obtain pnorm pabr
where css'': "css''= [(pnorm@cs,pabr@cs)]@css" and
pcss_i: "pcss i = [(pnorm,pabr)]"
by (force simp add: neq_Nil_conv split: if_split_asm)
with cs''_Nil step_i_full
have "\<Gamma>\<turnstile>([],[(pnorm@cs,pabr@cs)]@css,t'') \<rightarrow> (cs',css',t')"
by simp
from step_Nil [OF this]
obtain
css': "css'=css" and
cs': "(case t'' of
Abrupt s' \<Rightarrow> cs' = pabr @ cs \<and> t' = Normal s'
| _ \<Rightarrow> cs' = pnorm @ cs \<and> t' = t'')"
by (simp cong: xstate.case_cong)
let "?pcs_Suc_i " = "(case t'' of Abrupt s' \<Rightarrow> pabr | _ \<Rightarrow> pnorm)"
from cs'
have "\<Gamma>\<turnstile>([],[(pnorm,pabr)],t'') \<rightarrow> (?pcs_Suc_i,[],t')"
by (auto intro: step.intros split: xstate.splits)
moreover
from css'' css' cs' pcss_i pcs_pcss_Suc_i
obtain "pcs (Suc i) = ?pcs_Suc_i" "pcss (Suc i) = []"
by (simp split: if_split_asm xstate.splits)
ultimately
show ?thesis
using pcss_i cs'' cs''_Nil f_i f_Suc_i
by (simp add: p_def CS_def CSS_def S_def)
qed
qed
qed
qed
qed
qed
qed
lemma k_steps_to_rtrancl:
assumes steps: "\<forall>i<k. \<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)"
shows "\<Gamma>\<turnstile>p 0\<rightarrow>\<^sup>* p k"
using steps
proof (induct k)
case 0 thus ?case by auto
next
case (Suc k)
have "\<forall>i<Suc k. \<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)" by fact
then obtain
step_le_k: "\<forall>i<k. \<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)" and step_k: "\<Gamma>\<turnstile> p k \<rightarrow> p (Suc k)"
by auto
from Suc.hyps [OF step_le_k]
have "\<Gamma>\<turnstile> p 0 \<rightarrow>\<^sup>* p k".
also note step_k
finally show ?case .
qed
lemma (in inf) steps_hd_drop_suffix_finite:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes not_finished: "\<forall>i < k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
assumes simul: "\<forall>i\<le>k.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
shows "\<Gamma>\<turnstile>([c],[],s) \<rightarrow>\<^sup>* (pcs k, pcss k, S (f k))"
proof -
from steps_hd_drop_suffix [OF f_0 f_step not_finished simul]
have "\<forall>i<k. \<Gamma>\<turnstile> (pcs i, pcss i, S (f i)) \<rightarrow>
(pcs (Suc i), pcss (Suc i), S (f (Suc i)))".
from k_steps_to_rtrancl [OF this]
have "\<Gamma>\<turnstile> (pcs 0, pcss 0, S (f 0)) \<rightarrow>\<^sup>* (pcs k, pcss k, S (f k))".
moreover from f_0 simul [rule_format, of 0]
have "(pcs 0, pcss 0, S (f 0)) = ([c],[],s)"
by (auto split: if_split_asm simp add: CS_def CSS_def S_def)
ultimately show ?thesis by simp
qed
lemma (in inf) steps_hd_drop_suffix_infinite:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes not_finished: "\<forall>i. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
(*assumes not_finished: "\<forall>i. \<not> (pcs i = [] \<and> pcss i = [])"*)
assumes simul: "\<forall>i.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
defines "p\<equiv>\<lambda>i. (pcs i, pcss i, S (f i))"
shows "\<Gamma>\<turnstile> p i \<rightarrow> p (Suc i)"
proof -
from steps_hd_drop_suffix [OF f_0 f_step, of "Suc i" pcss pcs] not_finished simul
show ?thesis
by (auto simp add: p_def)
qed
lemma (in inf) steps_hd_progress:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes c_unfinished: "\<forall>i < k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
shows "\<forall>i \<le> k. (\<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css))"
using c_unfinished
proof (induct k)
case 0
with f_0 show ?case
by (simp add: CSS_def CS_def)
next
case (Suc k)
have c_unfinished: "\<forall>i<Suc k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)" by fact
hence c_unfinished': "\<forall>i< k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)" by simp
show ?case
proof (clarify)
fix i
assume i_le_Suc_k: "i \<le> Suc k"
show "\<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css)"
proof (cases "i < Suc k")
case True
with Suc.hyps [OF c_unfinished', rule_format, of i] c_unfinished
show ?thesis
by auto
next
case False
with i_le_Suc_k have eq_i_Suc_k: "i=Suc k"
by auto
obtain cs' css' t' where
f_Suc_k: "f (Suc k) = (cs', css', t')"
by (cases "f (Suc k)")
obtain cs'' css'' t'' where
f_k: "f k = (cs'',css'',t'')"
by (cases "f k")
with Suc.hyps [OF c_unfinished',rule_format, of k]
obtain pcs pcss where
pcs_pcss_k:
"if pcss = [] then css'' = css \<and> cs'' = pcs @ cs
else cs'' = pcs \<and>
css'' = butlast pcss @
[(fst (last pcss) @ cs, snd (last pcss) @ cs)] @
css"
by (auto simp add: CSS_def CS_def cong: if_cong)
from c_unfinished [rule_format, of k] f_k pcs_pcss_k
have pcs_pcss_empty: "\<not> (pcs = [] \<and> pcss = [])"
by (auto simp add: CS_def CSS_def S_def split: if_split_asm)
show ?thesis
proof (cases "pcss = []")
case True
note pcss_Nil = this
with pcs_pcss_k pcs_pcss_empty obtain p ps where
pcs_i: "pcs = p#ps" and
css'': "css''=css" and
cs'': "cs''=(p#ps)@cs"
by (cases "pcs") auto
with f_k have "f k = (p#(ps@cs),css,t'')"
by simp
with f_Suc_k f_step [rule_format, of k]
have step_css: "\<Gamma>\<turnstile> (p#(ps@cs),css,t'') \<rightarrow> (cs',css',t')"
by simp
from step_Cons' [OF this, of p "ps@cs"]
obtain css''' where
css''': "css' = css''' @ css"
"if css''' = [] then \<exists>p. cs' = p @ ps @ cs
else (\<exists>pnorm pabr. css'''=[(pnorm @ ps @ cs,pabr @ ps @ cs)])"
by auto
show ?thesis
proof (cases "css''' = []")
case True
with css'''
obtain p' where
css': "css' = css" and
cs': "cs' = p' @ ps @ cs"
by auto
from css' cs' f_Suc_k
show ?thesis
apply (rule_tac x="p'@ps" in exI)
apply (rule_tac x="[]" in exI)
apply (simp add: CSS_def CS_def eq_i_Suc_k)
done
next
case False
with css'''
obtain pnorm pabr where
css': "css'=css'''@css"
"css'''=[(pnorm @ ps @ cs,pabr @ ps @ cs)]"
by auto
with f_Suc_k eq_i_Suc_k
show ?thesis
apply (rule_tac x="cs'" in exI)
apply (rule_tac x="[(pnorm@ps, pabr@ps)]" in exI)
by (simp add: CSS_def CS_def)
qed
next
case False
note pcss_k_not_Nil = this
with pcs_pcss_k obtain
cs'': "cs''=pcs" and
css'': "css''= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css"
by auto
from f_Suc_k f_k f_step [rule_format, of k]
have step_i_full: "\<Gamma>\<turnstile> (cs'',css'',t'') \<rightarrow> (cs',css',t')"
by simp
show ?thesis
proof (cases cs'')
case (Cons c' cs)
with step_Cons' [OF step_i_full]
obtain css''' where css': "css' = css'''@css''"
by auto
with cs'' css'' f_Suc_k eq_i_Suc_k pcss_k_not_Nil
show ?thesis
apply (rule_tac x="cs'" in exI)
apply (rule_tac x="css'''@pcss" in exI)
by (clarsimp simp add: CSS_def CS_def butlast_append)
next
case Nil
note cs''_Nil = this
show ?thesis
proof (cases "butlast pcss")
case (Cons bpcs bpcss)
with cs''_Nil step_i_full css''
have *: "\<Gamma>\<turnstile> ([],[hd css'']@tl css'',t'') \<rightarrow> (cs',css',t')"
by simp
moreover
from step_Nil [OF *]
obtain css': "css'=tl css''" and
cs': "cs' = (case t'' of Abrupt s' \<Rightarrow> snd (hd css'')
| _ \<Rightarrow> fst (hd css''))"
by (auto split: xstate.splits)
from css'' Cons pcss_k_not_Nil
have "hd css'' = hd pcss"
by (auto simp add: neq_Nil_conv split: if_split_asm)
with css' cs' css'' cs''_Nil Cons pcss_k_not_Nil f_Suc_k eq_i_Suc_k
show ?thesis
apply (rule_tac x="cs'" in exI)
apply (rule_tac x="tl pcss" in exI)
apply (clarsimp split: xstate.splits
simp add: CS_def CSS_def neq_Nil_conv split: if_split_asm)
done
next
case Nil
with css'' pcss_k_not_Nil
obtain pnorm pabr
where css'': "css''= [(pnorm@cs,pabr@cs)]@css" and
pcss_k: "pcss = [(pnorm,pabr)]"
by (force simp add: neq_Nil_conv split: if_split_asm)
with cs''_Nil step_i_full
have "\<Gamma>\<turnstile>([],[(pnorm@cs,pabr@cs)]@css,t'') \<rightarrow> (cs',css',t')"
by simp
from step_Nil [OF this]
obtain
css': "css'=css" and
cs': "(case t'' of
Abrupt s' \<Rightarrow> cs' = pabr @ cs \<and> t' = Normal s'
| _ \<Rightarrow> cs' = pnorm @ cs \<and> t' = t'')"
by (simp cong: xstate.case_cong)
let "?pcs_Suc_k " = "(case t'' of Abrupt s' \<Rightarrow> pabr | _ \<Rightarrow> pnorm)"
from css'' css' cs' pcss_k f_Suc_k eq_i_Suc_k
show ?thesis
apply (rule_tac x="?pcs_Suc_k" in exI)
apply (rule_tac x="[]" in exI)
apply (simp split: xstate.splits add: CS_def CSS_def)
done
qed
qed
qed
qed
qed
qed
lemma (in inf) inf_progress:
assumes f_0: "f 0 = (c#cs,css,s)"
assumes f_step: "\<forall>i. \<Gamma>\<turnstile> f(i) \<rightarrow> f(Suc i)"
assumes unfinished: "\<forall>i. \<not> ((CS (f i) = cs) \<and> (CSS (f i) = css))"
shows "\<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css)"
proof -
from steps_hd_progress [OF f_0 f_step, of "i"] unfinished
show ?thesis
by auto
qed
lemma skolemize1: "\<forall>x. P x \<longrightarrow> (\<exists>y. Q x y) \<Longrightarrow> \<exists>f.\<forall>x. P x \<longrightarrow> Q x (f x)"
by (rule choice) blast
lemma skolemize2: "\<forall>x. P x \<longrightarrow> (\<exists>y z. Q x y z) \<Longrightarrow> \<exists>f g.\<forall>x. P x \<longrightarrow> Q x (f x) (g x)"
apply (drule skolemize1)
apply (erule exE)
apply (drule skolemize1)
apply fast
done
lemma skolemize2': "\<forall>x.\<exists>y z. P x y z \<Longrightarrow> \<exists>f g.\<forall>x. P x (f x) (g x)"
apply (drule choice)
apply (erule exE)
apply (drule choice)
apply fast
done
theorem (in inf) inf_cases:
fixes c::"('s,'p,'f) com"
assumes inf: "inf \<Gamma> (c#cs) css s"
shows "inf \<Gamma> [c] [] s \<or> (\<exists>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<and> inf \<Gamma> cs css t)"
proof -
from inf obtain f where
f_0: "f 0 = (c#cs,css,s)" and
f_step: "(\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i))"
by (auto simp add: inf_def)
show ?thesis
proof (cases "\<exists>i. CS (f i) = cs \<and> CSS (f i) = css")
case True
define k where "k = (LEAST i. CS (f i) = cs \<and> CSS (f i) = css)"
from True
obtain CS_f_k: "CS (f k) = cs" and CSS_f_k: "CSS (f k) = css"
apply -
apply (erule exE)
apply (drule LeastI)
apply (simp add: k_def)
done
have less_k_prop: "\<forall>i<k. \<not> (CS (f i) = cs \<and> CSS (f i) = css)"
apply (intro allI impI)
apply (unfold k_def)
apply (drule not_less_Least)
apply simp
done
have "\<Gamma>\<turnstile>([c], [], s) \<rightarrow>\<^sup>* ([],[],S (f k))"
proof -
have "\<forall>i\<le>k. \<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css)"
by (rule steps_hd_progress
[OF f_0 f_step, where k=k, OF less_k_prop])
from skolemize2 [OF this] obtain pcs pcss where
pcs_pcss:
"\<forall>i\<le>k.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
by iprover
from pcs_pcss [rule_format, of k] CS_f_k CSS_f_k
have finished: "pcs k = []" "pcss k = []"
by (auto simp add: CS_def CSS_def S_def split: if_split_asm)
from pcs_pcss
have simul: "\<forall>i\<le>k. (if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
by auto
from steps_hd_drop_suffix_finite [OF f_0 f_step less_k_prop simul] finished
show ?thesis
by simp
qed
hence "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> S (f k)"
by (rule steps_impl_exec)
moreover
from CS_f_k CSS_f_k f_step
have "inf \<Gamma> cs css (S (f k))"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (i + k)" in exI)
apply simp
apply (auto simp add: CS_def CSS_def S_def)
done
ultimately
have "(\<exists>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<and> inf \<Gamma> cs css t)"
by blast
thus ?thesis
by simp
next
case False
hence unfinished: "\<forall>i. \<not> ((CS (f i) = cs) \<and> (CSS (f i) = css))"
by simp
from inf_progress [OF f_0 f_step this]
have "\<forall>i. \<exists>pcs pcss.
(if pcss = [] then CSS (f i)=css \<and> CS (f i)=pcs@cs
else CS (f i)=pcs \<and>
CSS (f i)= butlast pcss@
[(fst (last pcss)@cs,(snd (last pcss))@cs)]@
css)"
by auto
from skolemize2' [OF this] obtain pcs pcss where
pcs_pcss: "\<forall>i.
(if pcss i = [] then CSS (f i)=css \<and> CS (f i)=pcs i@cs
else CS (f i)=pcs i \<and>
CSS (f i)= butlast (pcss i)@
[(fst (last (pcss i))@cs,(snd (last (pcss i)))@cs)]@
css)"
by iprover
define g where "g i = (pcs i, pcss i, S (f i))" for i
from pcs_pcss [rule_format, of 0] f_0
have "g 0 = ([c],[],s)"
by (auto split: if_split_asm simp add: CS_def CSS_def S_def g_def)
moreover
from steps_hd_drop_suffix_infinite [OF f_0 f_step unfinished pcs_pcss]
have "\<forall>i. \<Gamma>\<turnstile>g i \<rightarrow> g (Suc i)"
by (simp add: g_def)
ultimately
have "inf \<Gamma> [c] [] s"
by (auto simp add: inf_def)
thus ?thesis
by simp
qed
qed
lemma infE [consumes 1]:
assumes inf: "inf \<Gamma> (c#cs) css s"
assumes cases: "inf \<Gamma> [c] [] s \<Longrightarrow> P"
"\<And>t. \<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t; inf \<Gamma> cs css t\<rbrakk> \<Longrightarrow> P"
shows P
using inf cases
apply -
apply (drule inf.inf_cases)
apply auto
done
lemma inf_Seq:
"inf \<Gamma> (Seq c1 c2#cs) css (Normal s) = inf \<Gamma> (c1#c2#cs) css (Normal s)"
proof
assume "inf \<Gamma> (Seq c1 c2 # cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (Seq c1 c2#cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
from f_step [rule_format, of 0] f_0
have "f 1 = (c1#c2#cs,css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step show "inf \<Gamma> (c1#c2#cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
apply simp
done
next
assume "inf \<Gamma> (c1 # c2 # cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (c1# c2#cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
define g where "g i = (case i of 0 \<Rightarrow> (Seq c1 c2#cs,css,Normal s) | Suc j \<Rightarrow> f j)" for i
with f_0 have
"\<Gamma>\<turnstile>g 0 \<rightarrow> g (Suc 0)"
by (auto intro: step.intros)
moreover
from f_step have "\<forall>i. i\<noteq>0 \<longrightarrow> \<Gamma>\<turnstile>g i \<rightarrow> g (Suc i)"
by (auto simp add: g_def split: nat.splits)
ultimately
show "inf \<Gamma> (Seq c1 c2 # cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x=g in exI)
apply (simp add: g_def split: nat.splits)
done
qed
lemma inf_WhileTrue:
assumes b: "s \<in> b"
shows "inf \<Gamma> (While b c#cs) css (Normal s) =
inf \<Gamma> (c#While b c#cs) css (Normal s)"
proof
assume "inf \<Gamma> (While b c # cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (While b c#cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
from b f_step [rule_format, of 0] f_0
have "f 1 = (c#While b c#cs,css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step show "inf \<Gamma> (c # While b c # cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
apply simp
done
next
assume "inf \<Gamma> (c # While b c # cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (c # While b c #cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
define h where "h i = (case i of 0 \<Rightarrow> (While b c#cs,css,Normal s) | Suc j \<Rightarrow> f j)" for i
with b f_0 have
"\<Gamma>\<turnstile>h 0 \<rightarrow> h (Suc 0)"
by (auto intro: step.intros)
moreover
from f_step have "\<forall>i. i\<noteq>0 \<longrightarrow> \<Gamma>\<turnstile>h i \<rightarrow> h (Suc i)"
by (auto simp add: h_def split: nat.splits)
ultimately
show "inf \<Gamma> (While b c # cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x=h in exI)
apply (simp add: h_def split: nat.splits)
done
qed
lemma inf_Catch:
"inf \<Gamma> (Catch c1 c2#cs) css (Normal s) = inf \<Gamma> [c1] ((cs,c2#cs)#css) (Normal s)"
proof
assume "inf \<Gamma> (Catch c1 c2#cs) css (Normal s)"
then obtain f where
f_0: "f 0 = (Catch c1 c2#cs,css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
from f_step [rule_format, of 0] f_0
have "f 1 = ([c1],(cs,c2#cs)#css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step show "inf \<Gamma> [c1] ((cs,c2#cs)#css) (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
apply simp
done
next
assume "inf \<Gamma> [c1] ((cs,c2#cs)#css) (Normal s)"
then obtain f where
f_0: "f 0 = ([c1],(cs,c2#cs)#css,Normal s)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
define h where "h i = (case i of 0 \<Rightarrow> (Catch c1 c2#cs,css,Normal s) | Suc j \<Rightarrow> f j)" for i
with f_0 have
"\<Gamma>\<turnstile>h 0 \<rightarrow> h (Suc 0)"
by (auto intro: step.intros)
moreover
from f_step have "\<forall>i. i\<noteq>0 \<longrightarrow> \<Gamma>\<turnstile>h i \<rightarrow> h (Suc i)"
by (auto simp add: h_def split: nat.splits)
ultimately
show "inf \<Gamma> (Catch c1 c2 # cs) css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x=h in exI)
apply (simp add: h_def split: nat.splits)
done
qed
theorem terminates_impl_not_inf:
assumes termi: "\<Gamma>\<turnstile>c \<down> s"
shows "\<not>inf \<Gamma> [c] [] s"
using termi
proof induct
case (Skip s) thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Skip], [], Normal s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Basic g s)
thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Basic g], [], Normal s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Normal (g s))"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Spec r s)
thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Spec r], [], Normal s)"
with f_step [of 0]
have "\<Gamma>\<turnstile>([Spec r], [], Normal s) \<rightarrow> f (Suc 0)"
by simp
then show False
proof (cases)
fix t
assume "(s, t) \<in> r" "f (Suc 0) = ([], [], Normal t)"
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
next
assume "\<forall>t. (s, t) \<notin> r" "f (Suc 0) = ([], [], Stuck)"
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
qed
next
case (Guard s g c m)
have g: "s \<in> g" by fact
have hyp: "\<not> inf \<Gamma> [c] [] (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Guard m g c], [], Normal s)"
from g f_step [of 0] f_0
have "f (Suc 0) = ([c],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step
have "inf \<Gamma> [c] [] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp show False ..
qed
next
case (GuardFault s g m c)
have g: "s \<notin> g" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Guard m g c], [], Normal s)"
from g f_step [of 0] f_0
have "f (Suc 0) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Fault c m)
thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([c], [], Fault m)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Seq c1 s c2)
have hyp_c1: "\<not> inf \<Gamma> [c1] [] (Normal s)" by fact
have hyp_c2: "\<forall>s'. \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> s' \<longrightarrow> \<Gamma>\<turnstile>c2 \<down> s' \<and> \<not> inf \<Gamma> [c2] [] s'" by fact
have "\<not> inf \<Gamma> ([c1,c2]) [] (Normal s)"
proof
assume "inf \<Gamma> [c1, c2] [] (Normal s)"
then show False
proof (cases rule: infE)
assume "inf \<Gamma> [c1] [] (Normal s)"
with hyp_c1 show ?thesis by simp
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> t" "inf \<Gamma> [c2] [] t"
with hyp_c2 show ?thesis by simp
qed
qed
thus ?case
by (simp add: inf_Seq)
next
case (CondTrue s b c1 c2)
have b: "s \<in> b" by fact
have hyp_c1: "\<not> inf \<Gamma> [c1] [] (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Cond b c1 c2], [], Normal s)"
from b f_step [of 0] f_0
have "f 1 = ([c1],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step
have "inf \<Gamma> [c1] [] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp_c1 show False by simp
qed
next
case (CondFalse s b c2 c1)
have b: "s \<notin> b" by fact
have hyp_c2: "\<not> inf \<Gamma> [c2] [] (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Cond b c1 c2], [], Normal s)"
from b f_step [of 0] f_0
have "f 1 = ([c2],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step
have "inf \<Gamma> [c2] [] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp_c2 show False by simp
qed
next
case (WhileTrue s b c)
have b: "s \<in> b" by fact
have hyp_c: "\<not> inf \<Gamma> [c] [] (Normal s)" by fact
have hyp_w: "\<forall>s'. \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> s' \<longrightarrow>
\<Gamma>\<turnstile>While b c \<down> s' \<and> \<not> inf \<Gamma> [While b c] [] s'" by fact
have "\<not> inf \<Gamma> [c,While b c] [] (Normal s)"
proof
assume "inf \<Gamma> [c,While b c] [] (Normal s)"
from this hyp_c hyp_w show False
by (cases rule: infE) auto
qed
with b show ?case
by (simp add: inf_WhileTrue)
next
case (WhileFalse s b c)
have b: "s \<notin> b" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([While b c], [], Normal s)"
from b f_step [of 0] f_0
have "f (Suc 0) = ([],[],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Call p bdy s)
have bdy: "\<Gamma> p = Some bdy" by fact
have hyp: "\<not> inf \<Gamma> [bdy] [] (Normal s)" by fact
have not_inf_bdy:
"\<not> inf \<Gamma> [bdy] [([],[Throw])] (Normal s)"
proof
assume "inf \<Gamma> [bdy] [([],[Throw])] (Normal s)"
then show False
proof (rule infE)
assume "inf \<Gamma> [bdy] [] (Normal s)"
with hyp show False by simp
next
fix t
assume "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> \<Rightarrow> t"
assume inf: "inf \<Gamma> [] [([], [Throw])] t"
then obtain f where
f_0: "f 0 = ([],[([], [Throw])],t)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
show False
proof (cases t)
case (Normal t')
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],(Normal t'))"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc 0"]
show False
by (auto elim: step.cases)
next
case (Abrupt t')
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([Throw],[],(Normal t'))"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc 0"]
have "f (Suc (Suc 0)) = ([],[],(Abrupt t'))"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc(Suc 0)"]
show False
by (auto elim: step.cases)
next
case (Fault m)
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
have "f (Suc (Suc 0)) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc (Suc 0)"]
show False
by (auto elim: step.cases)
next
case Stuck
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Stuck)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
have "f (Suc (Suc 0)) = ([],[],Stuck)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc (Suc 0)"]
show False
by (auto elim: step.cases)
qed
qed
qed
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Call p], [], Normal s)"
from bdy f_step [of 0] f_0
have "f (Suc 0) =
([bdy],[([],[Throw])],Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step
have "inf \<Gamma> [bdy] [([],[Throw])] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with not_inf_bdy
show False by simp
qed
next
case (CallUndefined p s)
have undef: "\<Gamma> p = None" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Call p], [], Normal s)"
from undef f_step [of 0] f_0
have "f (Suc 0) = ([],[],Stuck)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of "Suc 0"]
show False
by (auto elim: step_elim_cases)
qed
next
case (Stuck c)
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([c], [], Stuck)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Stuck)"
by (auto elim: step_elim_cases)
with f_step [rule_format, of "Suc 0"]
show False
by (auto elim: step_elim_cases)
qed
next
case (DynCom c s)
have hyp: "\<not> inf \<Gamma> [(c s)] [] (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([DynCom c], [], Normal s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([(c s)], [], Normal s)"
by (auto elim: step_elim_cases)
with f_step have "inf \<Gamma> [(c s)] [] (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp
show False by simp
qed
next
case (Throw s)
thus ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([Throw], [], Normal s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Abrupt s)"
by (auto elim: step_Normal_elim_cases)
with f_step [of 1]
show False
by (auto elim: step_elim_cases)
qed
next
case (Abrupt c s)
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f_0: "f 0 = ([c], [], Abrupt s)"
from f_step [of 0] f_0
have "f (Suc 0) = ([],[],Abrupt s)"
by (auto elim: step_elim_cases)
with f_step [rule_format, of "Suc 0"]
show False
by (auto elim: step_elim_cases)
qed
next
case (Catch c1 s c2)
have hyp_c1: "\<not> inf \<Gamma> [c1] [] (Normal s)" by fact
have hyp_c2: "\<forall>s'. \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> Abrupt s' \<longrightarrow>
\<Gamma>\<turnstile>c2 \<down> Normal s' \<and> \<not> inf \<Gamma> [c2] [] (Normal s')" by fact
have "\<not> inf \<Gamma> [c1] [([],[c2])] (Normal s)"
proof
assume "inf \<Gamma> [c1] [([],[c2])] (Normal s)"
then show False
proof (rule infE)
assume "inf \<Gamma> [c1] [] (Normal s)"
with hyp_c1 show False by simp
next
fix t
assume eval: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow> t"
assume inf: "inf \<Gamma> [] [([], [c2])] t"
then obtain f where
f_0: "f 0 = ([],[([], [c2] )],t)" and
f_step: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
by (auto simp add: inf_def)
show False
proof (cases t)
case (Normal t')
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Normal t')"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
show False
by (auto elim: step_elim_cases)
next
case (Abrupt t')
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([c2],[],Normal t')"
by (auto elim: step_Normal_elim_cases)
with f_step eval Abrupt
have "inf \<Gamma> [c2] [] (Normal t')"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with eval hyp_c2 Abrupt show False by simp
next
case (Fault m)
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Fault m)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
show False
by (auto elim: step_elim_cases)
next
case Stuck
with f_0 f_step [rule_format, of 0]
have "f (Suc 0) = ([],[],Stuck)"
by (auto elim: step_Normal_elim_cases)
with f_step [rule_format, of 1]
show False
by (auto elim: step_elim_cases)
qed
qed
qed
thus ?case
by (simp add: inf_Catch)
qed
lemma terminatess_impl_not_inf:
assumes termi: "\<Gamma>\<turnstile>cs,css\<Down>s"
shows "\<not>inf \<Gamma> cs css s"
using termi
proof (induct)
case (Nil s)
show ?case
proof (rule not_infI)
fix f
assume "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
hence "\<Gamma>\<turnstile>f 0 \<rightarrow> f (Suc 0)"
by simp
moreover
assume "f 0 = ([], [], s)"
ultimately show False
by (fastforce elim: step.cases)
qed
next
case (ExitBlockNormal nrms css s abrs)
have hyp: "\<not> inf \<Gamma> nrms css (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f0: "f 0 = ([], (nrms, abrs) # css, Normal s)"
with f_step [of 0] have "f (Suc 0) = (nrms,css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step have "inf \<Gamma> nrms css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp show False ..
qed
next
case (ExitBlockAbrupt abrs css s nrms)
have hyp: "\<not> inf \<Gamma> abrs css (Normal s)" by fact
show ?case
proof (rule not_infI)
fix f
assume f_step: "\<And>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
assume f0: "f 0 = ([], (nrms, abrs) # css, Abrupt s)"
with f_step [of 0] have "f (Suc 0) = (abrs,css,Normal s)"
by (auto elim: step_Normal_elim_cases)
with f_step have "inf \<Gamma> abrs css (Normal s)"
apply (simp add: inf_def)
apply (rule_tac x="\<lambda>i. f (Suc i)" in exI)
by simp
with hyp show False ..
qed
next
case (ExitBlockFault nrms css f abrs)
show ?case
by (rule not_inf_Fault)
next
case (ExitBlockStuck nrms css abrs)
show ?case
by (rule not_inf_Stuck)
next
case (Cons c s cs css)
have termi_c: "\<Gamma>\<turnstile>c \<down> s" by fact
have hyp: "\<forall>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<longrightarrow> \<Gamma>\<turnstile>cs,css\<Down>t \<and> \<not> inf \<Gamma> cs css t" by fact
show "\<not> inf \<Gamma> (c # cs) css s"
proof
assume "inf \<Gamma> (c # cs) css s"
thus False
proof (rule infE)
assume "inf \<Gamma> [c] [] s"
with terminates_impl_not_inf [OF termi_c]
show False ..
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" "inf \<Gamma> cs css t"
with hyp show False by simp
qed
qed
qed
lemma lem:
"\<forall>y. r\<^sup>+\<^sup>+ a y \<longrightarrow> P a \<longrightarrow> P y
\<Longrightarrow> ((b,a) \<in> {(y,x). P x \<and> r x y}\<^sup>+) = ((b,a) \<in> {(y,x). P x \<and> r\<^sup>+\<^sup>+ x y})"
apply(rule iffI)
apply clarify
apply(erule trancl_induct)
apply blast
apply(blast intro:tranclp_trans)
apply clarify
apply(erule tranclp_induct)
apply blast
apply(blast intro:trancl_trans)
done
corollary terminatess_impl_no_inf_chain:
assumes terminatess: "\<Gamma>\<turnstile>cs,css\<Down>s"
shows "\<not>(\<exists>f. f 0 = (cs,css,s) \<and> (\<forall>i::nat. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ f(Suc i)))"
proof -
have "wf({(y,x). \<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}\<^sup>+)"
proof (rule wf_trancl)
show "wf {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}"
proof (simp only: wf_iff_no_infinite_down_chain,clarify,simp)
fix f
assume "\<forall>i. \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f i \<and> \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
hence "\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i))"
by (rule renumber [to_pred])
moreover from terminatess
have "\<not> (\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)))"
by (rule terminatess_impl_not_inf [unfolded inf_def])
ultimately show False
by simp
qed
qed
hence "\<not> (\<exists>f. \<forall>i. (f (Suc i), f i)
\<in> {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}\<^sup>+)"
by (simp add: wf_iff_no_infinite_down_chain)
thus ?thesis
proof (rule contrapos_nn)
assume "\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ f (Suc i))"
then obtain f where
f0: "f 0 = (cs, css, s)" and
seq: "\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ f (Suc i)"
by iprover
show
"\<exists>f. \<forall>i. (f (Suc i), f i) \<in> {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}\<^sup>+"
proof (rule exI [where x=f],rule allI)
fix i
show "(f (Suc i), f i) \<in> {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow> y}\<^sup>+"
proof -
{
fix i have "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* f i"
proof (induct i)
case 0 show "\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f 0"
by (simp add: f0)
next
case (Suc n)
have "\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f n" by fact
with seq show "\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f (Suc n)"
by (blast intro: tranclp_into_rtranclp rtranclp_trans)
qed
}
hence "\<Gamma>\<turnstile>(cs,css,s) \<rightarrow>\<^sup>* f i"
by iprover
with seq have
"(f (Suc i), f i) \<in> {(y, x). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* x \<and> \<Gamma>\<turnstile>x \<rightarrow>\<^sup>+ y}"
by clarsimp
moreover
have "\<forall>y. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ y\<longrightarrow>\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f i\<longrightarrow>\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* y"
by (blast intro: tranclp_into_rtranclp rtranclp_trans)
ultimately
show ?thesis
by (subst lem)
qed
qed
qed
qed
corollary terminates_impl_no_inf_chain:
"\<Gamma>\<turnstile>c\<down>s \<Longrightarrow> \<not>(\<exists>f. f 0 = ([c],[],s) \<and> (\<forall>i::nat. \<Gamma>\<turnstile>f i \<rightarrow>\<^sup>+ f(Suc i)))"
by (rule terminatess_impl_no_inf_chain) (iprover intro: terminatess.intros)
definition
termi_call_steps :: "('s,'p,'f) body \<Rightarrow> (('s \<times> 'p) \<times> ('s \<times> 'p))set"
where
"termi_call_steps \<Gamma> =
{((t,q),(s,p)). \<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal s \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal s) \<rightarrow>\<^sup>+ ([the (\<Gamma> q)],css,Normal t))}"
text \<open>Sequencing computations, or more exactly continuation stacks\<close>
primrec seq:: "(nat \<Rightarrow> 'a list) \<Rightarrow> nat \<Rightarrow> 'a list"
where
"seq css 0 = []" |
"seq css (Suc i) = css i@seq css i"
theorem wf_termi_call_steps: "wf (termi_call_steps \<Gamma>)"
proof (simp only: termi_call_steps_def wf_iff_no_infinite_down_chain,
clarify,simp)
fix S
assume inf:
"\<forall>i. (\<lambda>(t,q) (s,p). \<Gamma>\<turnstile>(the (\<Gamma> p)) \<down> Normal s \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal s) \<rightarrow>\<^sup>+ ([the (\<Gamma> q)],css,Normal t)))
(S (Suc i)) (S i)"
obtain s p where "s = (\<lambda>i. fst (S i))" and "p = (\<lambda>i. snd (S i))"
by auto
with inf
have inf':
"\<forall>i. \<Gamma>\<turnstile>(the (\<Gamma> (p i))) \<down> Normal (s i) \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))],css,Normal (s (Suc i))))"
apply -
apply (rule allI)
apply (erule_tac x=i in allE)
apply auto
done
show False
proof -
from inf' \<comment> \<open>Skolemization of css with axiom of choice\<close>
have "\<exists>css. \<forall>i. \<Gamma>\<turnstile>(the (\<Gamma> (p i))) \<down> Normal (s i) \<and>
\<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))],css i,Normal (s (Suc i)))"
apply -
apply (rule choice)
by blast
then obtain css where
termi_css: "\<forall>i. \<Gamma>\<turnstile>(the (\<Gamma> (p i))) \<down> Normal (s i)" and
step_css: "\<forall>i. \<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))],css i,Normal (s (Suc i)))"
by blast
define f where "f i = ([the (\<Gamma> (p i))], seq css i,Normal (s i)::('a,'c) xstate)" for i
have "f 0 = ([the (\<Gamma> (p 0))],[],Normal (s 0))"
by (simp add: f_def)
moreover
have "\<forall>i. \<Gamma>\<turnstile> (f i) \<rightarrow>\<^sup>+ (f (i+1))"
proof
fix i
from step_css [rule_format, of i]
have "\<Gamma>\<turnstile>([the (\<Gamma> (p i))], [], Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))], css i, Normal (s (Suc i)))".
from app_css_steps [OF this,simplified]
have "\<Gamma>\<turnstile>([the (\<Gamma> (p i))], seq css i, Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))], css i@seq css i, Normal (s (Suc i)))".
thus "\<Gamma>\<turnstile> (f i) \<rightarrow>\<^sup>+ (f (i+1))"
by (simp add: f_def)
qed
moreover from termi_css [rule_format, of 0]
have "\<not> (\<exists>f. (f 0 = ([the (\<Gamma> (p 0))],[],Normal (s 0)) \<and>
(\<forall>i. \<Gamma>\<turnstile>(f i) \<rightarrow>\<^sup>+ f(Suc i))))"
by (rule terminates_impl_no_inf_chain)
ultimately show False
by auto
qed
qed
text \<open>An alternative proof using Hilbert-choice instead of axiom of choice.\<close>
theorem "wf (termi_call_steps \<Gamma>)"
proof (simp only: termi_call_steps_def wf_iff_no_infinite_down_chain,
clarify,simp)
fix S
assume inf:
"\<forall>i. (\<lambda>(t,q) (s,p). \<Gamma>\<turnstile>(the (\<Gamma> p)) \<down> Normal s \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal s) \<rightarrow>\<^sup>+ ([the (\<Gamma> q)],css,Normal t)))
(S (Suc i)) (S i)"
obtain s p where "s = (\<lambda>i. fst (S i))" and "p = (\<lambda>i. snd (S i))"
by auto
with inf
have inf':
"\<forall>i. \<Gamma>\<turnstile>(the (\<Gamma> (p i))) \<down> Normal (s i) \<and>
(\<exists>css. \<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (Suc i)))],css,Normal (s (Suc i))))"
apply -
apply (rule allI)
apply (erule_tac x=i in allE)
apply auto
done
show "False"
proof -
define CSS where "CSS i = (SOME css.
\<Gamma>\<turnstile>([the (\<Gamma> (p i))],[], Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (i+1)))],css,Normal (s (i+1))))" for i
define f where "f i = ([the (\<Gamma> (p i))], seq CSS i,Normal (s i)::('a,'c) xstate)" for i
have "f 0 = ([the (\<Gamma> (p 0))],[],Normal (s 0))"
by (simp add: f_def)
moreover
have "\<forall>i. \<Gamma>\<turnstile> (f i) \<rightarrow>\<^sup>+ (f (i+1))"
proof
fix i
from inf' [rule_format, of i] obtain css where
css: "\<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (i+1)))],css,Normal (s (i+1)))"
by fastforce
hence "\<Gamma>\<turnstile>([the (\<Gamma> (p i))], seq CSS i, Normal (s i)) \<rightarrow>\<^sup>+
([the (\<Gamma> (p (i+1)))], CSS i @ seq CSS i, Normal (s (i+1)))"
apply -
apply (unfold CSS_def)
apply (rule someI2
[where P="\<lambda>css.
\<Gamma>\<turnstile>([the (\<Gamma> (p i))],[],Normal (s i))\<rightarrow>\<^sup>+
([the (\<Gamma> (p (i+1)))],css, Normal (s (i+1)))"])
apply (rule css)
apply (fastforce dest: app_css_steps)
done
thus "\<Gamma>\<turnstile> (f i) \<rightarrow>\<^sup>+ (f (i+1))"
by (simp add: f_def)
qed
moreover from inf' [rule_format, of 0]
have "\<Gamma>\<turnstile>the (\<Gamma> (p 0)) \<down> Normal (s 0)"
by iprover
then have "\<not> (\<exists>f. (f 0 = ([the (\<Gamma> (p 0))],[],Normal (s 0)) \<and>
(\<forall>i. \<Gamma>\<turnstile>(f i) \<rightarrow>\<^sup>+ f(Suc i))))"
by (rule terminates_impl_no_inf_chain)
ultimately show False
by auto
qed
qed
lemma not_inf_implies_wf: assumes not_inf: "\<not> inf \<Gamma> cs css s"
shows "wf {(c2,c1). \<Gamma> \<turnstile> (cs,css,s) \<rightarrow>\<^sup>* c1 \<and> \<Gamma> \<turnstile> c1 \<rightarrow> c2}"
proof (simp only: wf_iff_no_infinite_down_chain,clarify, simp)
fix f
assume "\<forall>i. \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* f i \<and> \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)"
hence "\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i))"
by (rule renumber [to_pred])
moreover from not_inf
have "\<not> (\<exists>f. f 0 = (cs, css, s) \<and> (\<forall>i. \<Gamma>\<turnstile>f i \<rightarrow> f (Suc i)))"
by (unfold inf_def)
ultimately show False
by simp
qed
lemma wf_implies_termi_reach:
assumes wf: "wf {(c2,c1). \<Gamma> \<turnstile> (cs,css,s) \<rightarrow>\<^sup>* c1 \<and> \<Gamma> \<turnstile> c1 \<rightarrow> c2}"
shows "\<And>cs1 css1 s1. \<lbrakk>\<Gamma> \<turnstile> (cs,css,s) \<rightarrow>\<^sup>* c1; c1=(cs1,css1,s1)\<rbrakk>\<Longrightarrow> \<Gamma>\<turnstile>cs1,css1\<Down>s1"
using wf
proof (induct c1, simp)
fix cs1 css1 s1
assume reach: "\<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* (cs1, css1, s1)"
assume hyp_raw: "\<And>y cs2 css2 s2. \<lbrakk>\<Gamma> \<turnstile> (cs1,css1,s1) \<rightarrow> (cs2,css2,s2);
\<Gamma> \<turnstile> (cs,css,s) \<rightarrow>\<^sup>* (cs2,css2,s2); y=(cs2,css2,s2)\<rbrakk> \<Longrightarrow>
\<Gamma>\<turnstile>cs2,css2\<Down>s2"
have hyp: "\<And>cs2 css2 s2. \<lbrakk>\<Gamma> \<turnstile> (cs1,css1,s1) \<rightarrow> (cs2,css2,s2)\<rbrakk> \<Longrightarrow>
\<Gamma>\<turnstile>cs2,css2\<Down>s2"
apply -
apply (rule hyp_raw)
apply assumption
using reach
apply simp
apply (rule refl)
done
show "\<Gamma>\<turnstile>cs1,css1\<Down>s1"
proof (cases s1)
case (Normal s1')
show ?thesis
proof (cases cs1)
case Nil
note cs1_Nil = this
show ?thesis
proof (cases css1)
case Nil
with cs1_Nil show ?thesis
by (auto intro: terminatess.intros)
next
case (Cons nrms_abrs css1')
then obtain nrms abrs where nrms_abrs: "nrms_abrs=(nrms,abrs)"
by (cases "nrms_abrs")
have "\<Gamma> \<turnstile> ([],(nrms,abrs)#css1',Normal s1') \<rightarrow> (nrms,css1',Normal s1')"
by (rule step.intros)
from hyp [simplified cs1_Nil Cons nrms_abrs Normal, OF this]
have "\<Gamma>\<turnstile>nrms,css1'\<Down>Normal s1'".
from ExitBlockNormal [OF this] cs1_Nil Cons nrms_abrs Normal
show ?thesis
by auto
qed
next
case (Cons c1 cs1')
have "\<Gamma>\<turnstile>c1#cs1',css1\<Down>Normal s1'"
proof (cases c1)
case Skip
have "\<Gamma> \<turnstile> (Skip#cs1',css1,Normal s1') \<rightarrow> (cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Skip Normal, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Normal s1'".
with Normal Skip show ?thesis
by (auto intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case (Basic f)
have "\<Gamma> \<turnstile> (Basic f#cs1',css1,Normal s1') \<rightarrow> (cs1',css1,Normal (f s1'))"
by (rule step.intros)
from hyp [simplified Cons Basic Normal, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Normal (f s1')".
with Normal Basic show ?thesis
by (auto intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case (Spec r)
with Normal show ?thesis
apply simp
apply (rule terminatess.Cons)
apply (fastforce intro: terminates.intros)
apply (clarify)
apply (erule exec_Normal_elim_cases)
apply clarsimp
apply (rule hyp)
apply (fastforce intro: step.intros simp add: Cons Spec Normal )
apply (fastforce intro: terminatess_Stuck)
done
next
case (Seq c\<^sub>1 c\<^sub>2)
have "\<Gamma> \<turnstile> (Seq c\<^sub>1 c\<^sub>2#cs1',css1,Normal s1') \<rightarrow> (c\<^sub>1#c\<^sub>2#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Seq Normal, OF this]
have "\<Gamma>\<turnstile>c\<^sub>1 # c\<^sub>2 # cs1',css1\<Down>Normal s1'".
with Normal Seq show ?thesis
by (fastforce intro: terminatess.intros terminates.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case (Cond b c\<^sub>1 c\<^sub>2)
show ?thesis
proof (cases "s1' \<in> b")
case True
hence "\<Gamma>\<turnstile>(Cond b c\<^sub>1 c\<^sub>2#cs1',css1,Normal s1') \<rightarrow> (c\<^sub>1#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Cond Normal, OF this]
have "\<Gamma>\<turnstile>c\<^sub>1 # cs1',css1\<Down>Normal s1'".
with Normal Cond True show ?thesis
by (fastforce intro: terminatess.intros terminates.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case False
hence "\<Gamma>\<turnstile>(Cond b c\<^sub>1 c\<^sub>2#cs1',css1,Normal s1') \<rightarrow> (c\<^sub>2#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Cond Normal, OF this]
have "\<Gamma>\<turnstile>c\<^sub>2 # cs1',css1\<Down>Normal s1'".
with Normal Cond False show ?thesis
by (fastforce intro: terminatess.intros terminates.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
qed
next
case (While b c')
show ?thesis
proof (cases "s1' \<in> b")
case True
then have "\<Gamma>\<turnstile>(While b c' # cs1', css1, Normal s1') \<rightarrow>
(c' # While b c' # cs1', css1, Normal s1')"
by (rule step.intros)
from hyp [simplified Cons While Normal, OF this]
have "\<Gamma>\<turnstile>c' # While b c' # cs1',css1\<Down>Normal s1'".
with Cons While True Normal
show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case False
then
have "\<Gamma>\<turnstile>(While b c' # cs1', css1, Normal s1') \<rightarrow> (cs1', css1, Normal s1')"
by (rule step.intros)
from hyp [simplified Cons While Normal, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Normal s1'".
with Cons While False Normal
show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
qed
next
case (Call p)
show ?thesis
proof (cases "\<Gamma> p")
case None
with Call Normal show ?thesis
by (fastforce intro: terminatess.intros terminates.intros terminatess_Stuck
elim: exec_Normal_elim_cases)
next
case (Some bdy)
then
have "\<Gamma> \<turnstile> (Call p#cs1',css1,Normal s1') \<rightarrow>
([bdy],(cs1',Throw#cs1')#css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Call Normal Some, OF this]
have "\<Gamma>\<turnstile>[bdy],(cs1', Throw # cs1') # css1\<Down>Normal s1'".
with Some Call Normal show ?thesis
apply simp
apply (rule terminatess.intros)
apply (blast elim: terminatess_elim_cases intro: terminates.intros)
apply clarify
apply (erule terminatess_elim_cases)
apply (erule exec_Normal_elim_cases)
prefer 2
apply simp
apply (erule_tac x=t in allE)
apply (case_tac t)
apply (auto intro: terminatess_Stuck terminatess_Fault exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
done
qed
next
case (DynCom c')
have "\<Gamma> \<turnstile> (DynCom c'#cs1',css1,Normal s1') \<rightarrow> (c' s1'#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons DynCom Normal, OF this]
have "\<Gamma>\<turnstile>c' s1'#cs1',css1\<Down>Normal s1'".
with Normal DynCom show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case (Guard f g c')
show ?thesis
proof (cases "s1' \<in> g")
case True
then have "\<Gamma> \<turnstile> (Guard f g c'#cs1',css1,Normal s1') \<rightarrow> (c'#cs1',css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Guard Normal, OF this]
have "\<Gamma>\<turnstile>c'#cs1',css1\<Down>Normal s1'".
with Normal Guard True show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
next
case False
with Guard Normal show ?thesis
by (fastforce intro: terminatess.intros terminatess_Fault
terminates.intros
elim: exec_Normal_elim_cases)
qed
next
case Throw
have "\<Gamma> \<turnstile> (Throw#cs1',css1,Normal s1') \<rightarrow> (cs1',css1,Abrupt s1')"
by (rule step.intros)
from hyp [simplified Cons Throw Normal, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Abrupt s1'".
with Normal Throw show ?thesis
by (auto intro: terminatess.intros terminates.intros
elim: exec_Normal_elim_cases)
next
case (Catch c\<^sub>1 c\<^sub>2)
have "\<Gamma> \<turnstile> (Catch c\<^sub>1 c\<^sub>2#cs1',css1,Normal s1') \<rightarrow>
([c\<^sub>1], (cs1',c\<^sub>2#cs1')# css1,Normal s1')"
by (rule step.intros)
from hyp [simplified Cons Catch Normal, OF this]
have "\<Gamma>\<turnstile>[c\<^sub>1],(cs1', c\<^sub>2 # cs1') # css1\<Down>Normal s1'".
with Normal Catch show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
qed
with Cons Normal show ?thesis
by simp
qed
next
case (Abrupt s1')
show ?thesis
proof (cases cs1)
case Nil
note cs1_Nil = this
show ?thesis
proof (cases css1)
case Nil
with cs1_Nil show ?thesis by (auto intro: terminatess.intros)
next
case (Cons nrms_abrs css1')
then obtain nrms abrs where nrms_abrs: "nrms_abrs=(nrms,abrs)"
by (cases "nrms_abrs")
have "\<Gamma> \<turnstile> ([],(nrms,abrs)#css1',Abrupt s1') \<rightarrow> (abrs,css1',Normal s1')"
by (rule step.intros)
from hyp [simplified cs1_Nil Cons nrms_abrs Abrupt, OF this]
have "\<Gamma>\<turnstile>abrs,css1'\<Down>Normal s1'".
from ExitBlockAbrupt [OF this] cs1_Nil Cons nrms_abrs Abrupt
show ?thesis
by auto
qed
next
case (Cons c1 cs1')
have "\<Gamma>\<turnstile>c1#cs1',css1\<Down>Abrupt s1'"
proof -
have "\<Gamma> \<turnstile> (c1#cs1',css1,Abrupt s1') \<rightarrow> (cs1',css1,Abrupt s1')"
by (rule step.intros)
from hyp [simplified Cons Abrupt, OF this]
have "\<Gamma>\<turnstile>cs1',css1\<Down>Abrupt s1'".
with Cons Abrupt
show ?thesis
by (fastforce intro: terminatess.intros terminates.intros exec.intros
elim: terminatess_elim_cases exec_Normal_elim_cases)
qed
with Cons Abrupt show ?thesis by simp
qed
next
case (Fault f)
thus ?thesis by (auto intro: terminatess_Fault)
next
case Stuck
thus ?thesis by (auto intro: terminatess_Stuck)
qed
qed
lemma not_inf_impl_terminatess:
assumes not_inf: "\<not> inf \<Gamma> cs css s"
shows "\<Gamma>\<turnstile>cs,css\<Down>s"
proof -
from not_inf_implies_wf [OF not_inf]
have wf: "wf {(c2, c1). \<Gamma>\<turnstile>(cs, css, s) \<rightarrow>\<^sup>* c1 \<and> \<Gamma>\<turnstile>c1 \<rightarrow> c2}".
show ?thesis
by (rule wf_implies_termi_reach [OF wf]) auto
qed
lemma not_inf_impl_terminates:
assumes not_inf: "\<not> inf \<Gamma> [c] [] s"
shows "\<Gamma>\<turnstile>c\<down>s"
proof -
from not_inf_impl_terminatess [OF not_inf]
have "\<Gamma>\<turnstile>[c],[]\<Down>s".
thus ?thesis
by (auto elim: terminatess_elim_cases)
qed
theorem terminatess_iff_not_inf:
"\<Gamma>\<turnstile>cs,css\<Down>s = (\<not> inf \<Gamma> cs css s)"
apply rule
apply (erule terminatess_impl_not_inf)
apply (erule not_inf_impl_terminatess)
done
corollary terminates_iff_not_inf:
"\<Gamma>\<turnstile>c\<down>s = (\<not> inf \<Gamma> [c] [] s)"
apply (rule)
apply (erule terminates_impl_not_inf)
apply (erule not_inf_impl_terminates)
done
subsection \<open>Completeness of Total Correctness Hoare Logic\<close>
lemma ConseqMGT:
assumes modif: "\<forall>Z::'a. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P' Z::'a assn) c (Q' Z),(A' Z)"
assumes impl: "\<And>s. s \<in> P \<Longrightarrow> s \<in> P' s \<and> (\<forall>t. t \<in> Q' s \<longrightarrow> t \<in> Q) \<and>
(\<forall>t. t \<in> A' s \<longrightarrow> t \<in> A)"
shows "\<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
using impl
by - (rule conseq [OF modif],blast)
lemma conseq_extract_state_indep_prop:
assumes state_indep_prop:"\<forall>s \<in> P. R"
assumes to_show: "R \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
shows "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"
apply (rule Conseq)
apply (clarify)
apply (rule_tac x="P" in exI)
apply (rule_tac x="Q" in exI)
apply (rule_tac x="A" in exI)
using state_indep_prop to_show
by blast
{
fix u assume "\<Gamma>\<turnstile>\<langle>c,Normal e\<rangle> \<Rightarrow> Abrupt u"
with Abrupt_r have "\<Gamma>\<turnstile>\<langle>While b c,Normal r\<rangle> \<Rightarrow> Abrupt u" by simp
moreover from Z_r obtain
"Z \<in> b" "\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal r"
by simp
ultimately have "\<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Abrupt u"
by (blast intro: exec.intros)
}
with cNoFault show "?Prop Z e"
by iprover
qed
}
with P show "s \<in> ?P' s"
by blast
next
{
fix t
assume "termination": "t \<notin> b"
assume "(Z, t) \<in> ?unroll"
hence "\<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Normal t"
proof (induct rule: converse_rtrancl_induct [consumes 1])
from "termination"
show "\<Gamma>\<turnstile>\<langle>While b c,Normal t\<rangle> \<Rightarrow> Normal t"
by (blast intro: exec.WhileFalse)
next
fix Z r
assume first_body:
"(Z, r) \<in> {(s, t). s \<in> b \<and> \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> Normal t}"
assume "(r, t) \<in> ?unroll"
assume rest_loop: "\<Gamma>\<turnstile>\<langle>While b c, Normal r\<rangle> \<Rightarrow> Normal t"
show "\<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Normal t"
proof -
from first_body obtain
"Z \<in> b" "\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal r"
by fast
moreover
from rest_loop have
"\<Gamma>\<turnstile>\<langle>While b c,Normal r\<rangle> \<Rightarrow> Normal t"
by fast
ultimately show "\<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Normal t"
by (rule exec.WhileTrue)
qed
qed
}
with P
show "\<forall>t. t\<in>(?P' s \<inter> - b)
\<longrightarrow>t\<in>{t. \<Gamma>\<turnstile>\<langle>While b c,Normal Z\<rangle> \<Rightarrow> Normal t}"
by blast
next
from P show "\<forall>t. t\<in>?A s \<longrightarrow> t\<in>?A Z"
by simp
qed
qed
next
case (Call q)
let ?P = "{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call q ,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>*
(Call q # cs,css,Normal s))}"
from noStuck_Call
have "\<forall>s \<in> ?P. q \<in> dom \<Gamma>"
by (fastforce simp add: final_notin_def)
then show ?case
proof (rule conseq_extract_state_indep_prop)
assume q_defined: "q \<in> dom \<Gamma>"
from Call_hyp have
"\<forall>q\<in>dom \<Gamma>. \<forall>Z.
\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub>{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>the (\<Gamma> q),Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>(the (\<Gamma> q))\<down>Normal s \<and> ((s,q),(\<sigma>,p)) \<in> termi_call_steps \<Gamma>}
(Call q)
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> q),Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> q),Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by (simp add: exec_Call_body' noFaultStuck_Call_body' [simplified]
terminates_Normal_Call_body)
from Call_hyp q_defined have Call_hyp':
"\<forall>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call q,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call q\<down>Normal s \<and> ((s,q),(\<sigma>,p)) \<in> termi_call_steps \<Gamma>}
(Call q)
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by auto
show
"\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ?P
(Call q)
{t. \<Gamma>\<turnstile>\<langle>Call q ,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call q ,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (rule ConseqMGT [OF Call_hyp'],safe)
fix cs css
assume
"\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>)\<rightarrow>\<^sup>* (Call q # cs,css,Normal Z)"
"\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma>"
hence "\<Gamma>\<turnstile>Call q \<down> Normal Z"
by (rule steps_preserves_termination)
with q_defined show "\<Gamma>\<turnstile>Call q \<down> Normal Z"
by (auto elim: terminates_Normal_elim_cases)
next
fix cs css
assume reach:
"\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Call q#cs,css,Normal Z)"
moreover have "\<Gamma>\<turnstile>(Call q # cs,css, Normal Z) \<rightarrow>
([the (\<Gamma> q)],(cs,Throw#cs)#css, Normal Z)"
by (rule step.Call) (insert q_defined,auto)
ultimately
have "\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>+ ([the (\<Gamma> q)],(cs,Throw#cs)#css,Normal Z)"
by (rule rtranclp_into_tranclp1)
moreover
assume termi: "\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma>"
ultimately
show "((Z,q), \<sigma>,p) \<in> termi_call_steps \<Gamma>"
by (auto simp add: termi_call_steps_def)
qed
qed
next
case (DynCom c)
have hyp:
"\<And>s'. \<forall>Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub>
{s. s = Z \<and> \<Gamma>\<turnstile>\<langle>c s',Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c s'#cs,css,Normal s))}
(c s')
{t. \<Gamma>\<turnstile>\<langle>c s',Normal Z\<rangle> \<Rightarrow> Normal t},{t. \<Gamma>\<turnstile>\<langle>c s',Normal Z\<rangle> \<Rightarrow> Abrupt t}"
using DynCom by simp
have hyp':
"\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>DynCom c,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (DynCom c#cs,css,Normal s))}
(c Z)
{t. \<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow> Normal t},{t. \<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (rule ConseqMGT [OF hyp],safe)
assume "\<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
then show "\<Gamma>\<turnstile>\<langle>c Z,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
by (fastforce simp add: final_notin_def intro: exec.intros)
next
fix cs css
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (DynCom c # cs, css, Normal Z)"
also have "\<Gamma>\<turnstile>(DynCom c # cs, css, Normal Z) \<rightarrow> (c Z#cs,css,Normal Z)"
by (rule step.DynCom)
finally
show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (c Z # cs, css, Normal Z)"
by blast
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c Z,Normal Z\<rangle> \<Rightarrow> Normal t"
thus "\<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow> Normal t"
by (auto intro: exec.intros)
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c Z,Normal Z\<rangle> \<Rightarrow> Abrupt t"
thus "\<Gamma>\<turnstile>\<langle>DynCom c,Normal Z\<rangle> \<Rightarrow> Abrupt t"
by (auto intro: exec.intros)
qed
show ?case
apply (rule hoaret.DynCom)
apply safe
apply (rule hyp')
done
next
case (Guard f g c)
have hyp_c: "\<forall>Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub>
{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c#cs,css,Normal s))}
c
{t. \<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
using Guard.hyps by iprover
show "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal s))}
Guard f g c
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (cases "f \<in> F")
case True
have "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> {s. s=Z \<and>
\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal s))})
c
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (rule ConseqMGT [OF hyp_c], safe)
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))" "Z\<in>g"
thus "\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
by (auto simp add: final_notin_def intro: exec.intros)
next
fix cs css
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal Z)"
also
assume "Z \<in> g"
hence "\<Gamma>\<turnstile>(Guard f g c#cs,css,Normal Z) \<rightarrow> (c#cs,css,Normal Z)"
by (rule step.Guard)
finally show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c#cs,css,Normal Z)"
by iprover
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal t" "Z \<in> g"
thus "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t"
by (auto simp add: final_notin_def intro: exec.intros )
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Abrupt t" "Z \<in> g"
thus "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t"
by (auto simp add: final_notin_def intro: exec.intros )
qed
from True this show ?thesis
by (rule conseqPre [OF Guarantee]) auto
next
case False
have "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> {s. s=Z \<and>
\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal s))})
c
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof (rule ConseqMGT [OF hyp_c], safe)
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
thus "\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
using False
by (cases "Z\<in> g") (auto simp add: final_notin_def intro: exec.intros)
next
fix cs css
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (Guard f g c#cs,css,Normal Z)"
also assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
hence "Z \<in> g"
using False by (auto simp add: final_notin_def intro: exec.GuardFault)
hence "\<Gamma>\<turnstile>(Guard f g c#cs,css,Normal Z) \<rightarrow> (c#cs,css,Normal Z)"
by (rule step.Guard)
finally show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c#cs,css,Normal Z)"
by iprover
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Normal t"
thus "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Normal t"
using False
by (cases "Z\<in> g") (auto simp add: final_notin_def intro: exec.intros )
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c,Normal Z\<rangle> \<Rightarrow> Abrupt t"
thus "\<Gamma>\<turnstile>\<langle>Guard f g c ,Normal Z\<rangle> \<Rightarrow> Abrupt t"
using False
by (cases "Z\<in> g") (auto simp add: final_notin_def intro: exec.intros )
qed
then show ?thesis
apply (rule conseqPre [OF hoaret.Guard])
apply clarify
apply (frule Guard_noFaultStuckD [OF _ False])
apply auto
done
qed
next
case Throw
show "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Throw,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[], Normal \<sigma>) \<rightarrow>\<^sup>* (Throw#cs,css,Normal s))}
Throw
{t. \<Gamma>\<turnstile>\<langle>Throw,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Throw,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by (rule conseqPre [OF hoaret.Throw])
(blast intro: exec.intros terminates.intros)
next
case (Catch c\<^sub>1 c\<^sub>2)
have hyp_c1:
"\<forall>Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s= Z \<and> \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>1# cs, css,Normal s))}
c\<^sub>1
{t. \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Normal t},{t. \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
using Catch.hyps by iprover
have hyp_c2:
"\<forall>Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s= Z \<and> \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>2# cs, css,Normal s))}
c\<^sub>2
{t. \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Normal t},{t. \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
using Catch.hyps by iprover
have
"\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s = Z \<and> \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>)\<rightarrow>\<^sup>*(Catch c\<^sub>1 c\<^sub>2 #cs,css,Normal s))}
c\<^sub>1
{t. \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t \<and>
\<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal t\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault`(-F)) \<and> \<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>2# cs, css,Normal t))}"
proof (rule ConseqMGT [OF hyp_c1],clarify,safe)
assume "\<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
thus "\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
by (fastforce simp add: final_notin_def intro: exec.intros)
next
fix cs css
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal Z)"
also have
"\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal Z) \<rightarrow> ([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal Z)"
by (rule step.Catch)
finally
show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>1 # cs, css, Normal Z)"
by iprover
next
fix t
assume "\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Normal t"
thus "\<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Normal t"
by (auto intro: exec.intros)
next
fix t
assume "\<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
"\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t"
thus "\<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal t\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))"
by (auto simp add: final_notin_def intro: exec.intros)
next
fix cs css t
assume "\<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal Z)"
also have
"\<Gamma>\<turnstile>(Catch c\<^sub>1 c\<^sub>2 # cs, css, Normal Z) \<rightarrow> ([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal Z)"
by (rule step.Catch)
also
assume "\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t"
hence "\<Gamma>\<turnstile>([c\<^sub>1],(cs,c\<^sub>2#cs)#css,Normal Z) \<rightarrow>\<^sup>* ([],(cs,c\<^sub>2#cs)#css,Abrupt t)"
by (rule exec_impl_steps)
also
have "\<Gamma>\<turnstile>([],(cs,c\<^sub>2#cs)#css,Abrupt t) \<rightarrow> (c\<^sub>2#cs,css,Normal t)"
by (rule step.intros)
finally
show "\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)], [], Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>2 # cs, css, Normal t)"
by iprover
qed
moreover
have "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {t. \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal Z\<rangle> \<Rightarrow> Abrupt t \<and>
\<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal t\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p) \<down> Normal \<sigma> \<and>
(\<exists>cs css. \<Gamma>\<turnstile>([the (\<Gamma> p)],[],Normal \<sigma>) \<rightarrow>\<^sup>* (c\<^sub>2# cs, css,Normal t))}
c\<^sub>2
{t. \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by (rule ConseqMGT [OF hyp_c2]) (fastforce intro: exec.intros)
ultimately show ?case
by (rule hoaret.Catch)
qed
text \<open>To prove a procedure implementation correct it suffices to assume
only the procedure specifications of procedures that actually
occur during evaluation of the body.
\<close>
lemma Call_lemma:
assumes
Call: "\<forall>q \<in> dom \<Gamma>. \<forall>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub>
{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call q,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call q\<down>Normal s \<and> ((s,q),(\<sigma>,p)) \<in> termi_call_steps \<Gamma>}
(Call q)
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
shows "\<And>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub>
({\<sigma>} \<inter> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal s})
the (\<Gamma> p)
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal Z\<rangle> \<Rightarrow> Abrupt t}"
apply (rule conseqPre)
apply (rule Call_lemma')
apply (rule Call)
apply blast
done
lemma Call_lemma_switch_Call_body:
assumes
call: "\<forall>q \<in> dom \<Gamma>. \<forall>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub>
{s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call q,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call q\<down>Normal s \<and> ((s,q),(\<sigma>,p)) \<in> termi_call_steps \<Gamma>}
(Call q)
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call q,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
assumes p_defined: "p \<in> dom \<Gamma>"
shows "\<And>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub>
({\<sigma>} \<inter> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s})
the (\<Gamma> p)
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
apply (simp only: exec_Call_body' [OF p_defined] noFaultStuck_Call_body' [OF p_defined] terminates_Normal_Call_body [OF p_defined])
apply (rule conseqPre)
apply (rule Call_lemma')
apply (rule call)
apply blast
done
lemma MGT_Call:
"\<forall>p \<in> dom \<Gamma>. \<forall>Z.
\<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>(Call p)\<down>Normal s}
(Call p)
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
apply (intro ballI allI)
apply (rule CallRec' [where Procs="dom \<Gamma>" and
P="\<lambda>p Z. {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s}" and
Q="\<lambda>p Z. {t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t}" and
A="\<lambda>p Z. {t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}" and
r="termi_call_steps \<Gamma>"
])
apply simp
apply simp
apply (rule wf_termi_call_steps)
apply (intro ballI allI)
apply simp
apply (rule Call_lemma_switch_Call_body [rule_format, simplified])
apply (rule hoaret.Asm)
apply fastforce
apply assumption
done
lemma CollInt_iff: "{s. P s} \<inter> {s. Q s} = {s. P s \<and> Q s}"
by auto
lemma image_Un_conv: "f ` (\<Union>p\<in>dom \<Gamma>. \<Union>Z. {x p Z}) = (\<Union>p\<in>dom \<Gamma>. \<Union>Z. {f (x p Z)})"
by (auto iff: not_None_eq)
text \<open>Another proof of \<open>MGT_Call\<close>, maybe a little more readable\<close>
lemma
"\<forall>p \<in> dom \<Gamma>. \<forall>Z.
\<Gamma>,{} \<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. s=Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>(Call p)\<down>Normal s}
(Call p)
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
proof -
{
fix p Z \<sigma>
assume defined: "p \<in> dom \<Gamma>"
define Specs where "Specs = (\<Union>p\<in>dom \<Gamma>. \<Union>Z.
{({s. s=Z \<and>
\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s},
p,
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t})})"
define Specs_wf where "Specs_wf p \<sigma> = (\<lambda>(P,q,Q,A).
(P \<inter> {s. ((s,q),\<sigma>,p) \<in> termi_call_steps \<Gamma>}, q, Q, A)) ` Specs" for p \<sigma>
have "\<Gamma>,Specs_wf p \<sigma>
\<turnstile>\<^sub>t\<^bsub>/F\<^esub>({\<sigma>} \<inter>
{s. s = Z \<and> \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>the (\<Gamma> p)\<down>Normal s})
(the (\<Gamma> p))
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal Z\<rangle> \<Rightarrow> Abrupt t}"
apply (rule Call_lemma [rule_format])
apply (rule hoaret.Asm)
apply (clarsimp simp add: Specs_wf_def Specs_def image_Un_conv)
apply (rule_tac x=q in bexI)
apply (rule_tac x=Z in exI)
apply (clarsimp simp add: CollInt_iff)
apply auto
done
hence "\<Gamma>,Specs_wf p \<sigma>
\<turnstile>\<^sub>t\<^bsub>/F\<^esub>({\<sigma>} \<inter>
{s. s = Z \<and> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s})
(the (\<Gamma> p))
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t}"
by (simp only: exec_Call_body' [OF defined]
noFaultStuck_Call_body' [OF defined]
terminates_Normal_Call_body [OF defined])
} note bdy=this
show ?thesis
apply (intro ballI allI)
apply (rule hoaret.CallRec [where Specs="(\<Union>p\<in>dom \<Gamma>. \<Union>Z.
{({s. s=Z \<and>
\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) \<and>
\<Gamma>\<turnstile>Call p\<down>Normal s},
p,
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Normal t},
{t. \<Gamma>\<turnstile>\<langle>Call p,Normal Z\<rangle> \<Rightarrow> Abrupt t})})",
OF _ wf_termi_call_steps [of \<Gamma>] refl])
apply fastforce
apply clarify
apply (rule conjI)
apply fastforce
apply (rule allI)
apply (simp (no_asm_use) only : Un_empty_left)
apply (rule bdy)
apply auto
done
qed
end
|
#' @param name Name of a collection or core. Or leave as \code{NULL} if not needed.
#' @param callopts Call options passed on to [crul::HttpClient]
#' @param raw (logical) If TRUE, returns raw data in format specified by wt param
#' @param parsetype (character) One of 'list' or 'df'
#' @param concat (character) Character to concatenate elements of longer than length 1.
#' Note that this only works reliably when data format is json (wt='json'). The parsing
#' is more complicated in XML format, but you can do that on your own.
#' @param progress a function with logic for printing a progress
#' bar for an HTTP request, ultimately passed down to \pkg{curl}. only supports
#' \code{httr::progress} for now. See the README for an example.
#' @param ... Further args to be combined into query
#'
#' @section More like this parameters:
#' \itemize{
#' \item q Query terms, defaults to '*:*', or everything.
#' \item fq Filter query, this does not affect the search, only what gets returned
#' \item mlt.count The number of similar documents to return for each result. Default is 5.
#' \item mlt.fl The fields to use for similarity. NOTE: if possible these should have a stored
#' TermVector DEFAULT_FIELD_NAMES = new String[] {"contents"}
#' \item mlt.mintf Minimum Term Frequency - the frequency below which terms will be ignored in
#' the source doc. DEFAULT_MIN_TERM_FREQ = 2
#' \item mlt.mindf Minimum Document Frequency - the frequency at which words will be ignored which
#' do not occur in at least this many docs. DEFAULT_MIN_DOC_FREQ = 5
#' \item mlt.minwl minimum word length below which words will be ignored.
#' DEFAULT_MIN_WORD_LENGTH = 0
#' \item mlt.maxwl maximum word length above which words will be ignored.
#' DEFAULT_MAX_WORD_LENGTH = 0
#' \item mlt.maxqt maximum number of query terms that will be included in any generated query.
#' DEFAULT_MAX_QUERY_TERMS = 25
#' \item mlt.maxntp maximum number of tokens to parse in each example doc field that is not stored
#' with TermVector support. DEFAULT_MAX_NUM_TOKENS_PARSED = 5000
#' \item mlt.boost (true/false) set if the query will be boosted by the interesting term relevance.
#' DEFAULT_BOOST = false
#' \item mlt.qf Query fields and their boosts using the same format as that used in
#' DisMaxQParserPlugin. These fields must also be specified in mlt.fl.
#' \item fl Fields to return. We force 'id' to be returned so that there is a unique identifier
#' with each record.
#' \item wt (character) Data type returned, defaults to 'json'. One of json or xml. If json,
#' uses \code{\link[jsonlite]{fromJSON}} to parse. If xml, uses \code{\link[XML]{xmlParse}} to
#' parse. csv is only supported in \code{\link{solr_search}} and \code{\link{solr_all}}.
#' \item start Record to start at, default to beginning.
#' \item rows Number of records to return. Defaults to 10.
#' \item key API key, if needed.
#' }
|
A new wooden nave altar, constructed by Matthew Burt of Hindon, will be dedicated by the Rt Revd Andrew Rumsey the Bishop of Ramsbury, in a special Parish Communion service on Sunday 7th April at 0930.
Matthew Burt’s new work replaces a stone altar which has now been repositioned in the Lady Chapel. The obvious advantage of the new altar is its mobility. Up till now the stone altar (shown in its former position below) has restricted the amount of space for concerts and other functions. |
\chapter{\label{chap:hmm}Sequence learning}
The machine learning methods we discusses so far are
built on the assumption that the training instances
are \emph{independent and identically distributed} (i.i.d).
When this assumption is reasonable,
each prediction the machine learning system can be made
independently of other predictions.
For example, whether current email is spam or not
does not depend on our prediction on the previous email.
In most realistic scenarios,
it is fairly reasonable to make each decision in isolation.
\begin{margintable}
\centering
\caption{\label{tbl:example-pos-tagging}%
An example sentence and the assigned POS tags.
}
\begin{tabular}{lll}
\toprule
Word & POS tag & Alternative\\
\midrule
We & \ttag{PRON} & \\
need & \ttag{VERB} & \ttag{NOUN}\\
to & \ttag{ADP} & \\
plan & \ttag{VERB} & \ttag{NOUN}\\
and & \ttag{CONJ} & \\
book & \ttag{VERB} & \ttag{NOUN}\\
\bottomrule
\end{tabular}
\end{margintable}
In some problems, however, individual predictions
are not independent of each other.
For example,
consider the task of predicting
the part-of-speech tagging
where the aim is to assign part-of-speech tags,
such as \ttag{NOUN} or \ttag{VERB} to words.
Table~\ref{tbl:example-pos-tagging} shows the POS tags
we want to assign to the words in the sentence
\emph{We need to plan and book}.
The table also lists alternative tags for some of the words.
The first decision, whether \emph{need} is a noun or a verb,
clearly depends on the previous word.
If we had \emph{Our need},
the more likely option would be \ttag{NOUN}.
The decision for word \emph{plan} depends clearly on the previous word as well.
However, more crucially it depends on the POS tag of the word, not only the form of the word.
The fact that it follows a preposition is a good clue that it is a verb.
Furthermore, the POS tag of the word that it conjoined with,
\emph{book}, also provides further clues that it should be a verb.
What is important to realize in the example above is that
the individual POS tag predictions depend on each other.
One way to turn this into an i.i.d.\ problem is to
consider the whole sequence of labels as a single label.
However, this would result in a large number of possible labels.%
\sidenote{In fact, exponentially many.
We would have $m^{n}$ possible labels
for a sentence of $n$ words with a tagset size of $m$ possible tags.
}
Where most of the labels, even perfectly valid ones,
would not be observed in a realistic data set.
Furthermore, such an approach would not be able to make use of the
regularities within the structure.
For example, for two unobserved sequences,
we would not be able to learn that a partial sequence of \ttag{DET NOUN}
is more likely than \ttag{DET VERB}.
In similar problems
we need to consider the dependencies between the parts of the sequence.
Considering all possible dependencies,
however, is intractable in most realistic problems.
As a result, most solutions rely on restricting the dependencies we consider
to a subset of the all dependencies.
A common assumption that is useful in many sequence learning applications
is to consider dependencies between the labels in a fixed distance.
A well-known traditional model that is used often with sequence learning
is hidden Markov models which will be main focus in the first part of this lecture.
Problems that require learning sequences are prevalent in NLP.
Sequence learning is an instance of \emph{structured learning},
where the prediction is not a simple atomic label,
but a complex structure with interdependencies between its parts.
The structure does not have to be a sequence,
for example, in parsing, the target we want to predict is
better expressed by a hierarchical structure rather than a sequence.
In this lecture we will focus on learning sequences,
and return to the discussion of more-general structure learning
while introducing parsing.
\section{Hidden Markov models}
\emph{Hidden Markov models} are one of the ways to make the learning over
sequences easier.
\section*{Where to go from here}
\textcite{wasserman2004}
|
module module_fr_fire_phys
use module_model_constants, only: cp,xlv
use module_fr_fire_util
PRIVATE
PUBLIC:: init_fuel_cats,fire_ros,heat_fluxes,set_nfuel_cat,set_fire_params,write_fuels_m
PUBLIC::fire_params
type fire_params
real,pointer,dimension(:,:):: vx,vy
real,pointer,dimension(:,:):: zsf
real,pointer,dimension(:,:):: dzdxf,dzdyf
real,pointer,dimension(:,:):: bbb,betafl,phiwc,r_0
real,pointer,dimension(:,:):: fgip
real,pointer,dimension(:,:):: ischap
end type fire_params
REAL, SAVE:: cmbcnst,hfgl,fuelmc_g,fuelmc_c
REAL, SAVE:: bmst,fuelheat
DATA cmbcnst / 17.433e+06/
DATA hfgl / 17.e4 /
DATA fuelmc_g / 0.08 /
DATA fuelmc_c / 1.00 /
INTEGER, PARAMETER :: nf=14
INTEGER, SAVE :: nfuelcats = 13
INTEGER, PARAMETER :: mfuelcats = 30
INTEGER, PARAMETER :: zf = mfuelcats-nf
INTEGER, SAVE :: no_fuel_cat = 14
CHARACTER (len=80), DIMENSION(mfuelcats ), save :: fuel_name
INTEGER, DIMENSION( mfuelcats ), save :: ichap
REAL , DIMENSION( mfuelcats ), save :: windrf,weight,fgi,fci,fci_d,fct,fcbr, &
fueldepthm,fueldens,fuelmce, &
savr,st,se
DATA windrf /0.36, 0.36, 0.44, 0.55, 0.42, 0.44, 0.44, &
0.36, 0.36, 0.36, 0.36, 0.43, 0.46, 1e-7, zf*0 /
DATA fgi / 0.166, 0.896, 0.674, 3.591, 0.784, 1.344, 1.091, &
1.120, 0.780, 2.692, 2.582, 7.749, 13.024, 1.e-7, zf*0. /
DATA fueldepthm /0.305, 0.305, 0.762, 1.829, 0.61, 0.762,0.762, &
0.0610, 0.0610, 0.305, 0.305, 0.701, 0.914, 0.305,zf*0. /
DATA savr / 3500., 2784., 1500., 1739., 1683., 1564., 1562., &
1889., 2484., 1764., 1182., 1145., 1159., 3500., zf*0. /
DATA fuelmce / 0.12, 0.15, 0.25, 0.20, 0.20, 0.25, 0.40, &
0.30, 0.25, 0.25, 0.15, 0.20, 0.25, 0.12 , zf*0. /
DATA fueldens / nf * 32., zf*0. /
DATA st / nf* 0.0555 , zf*0./
DATA se / nf* 0.010 , zf*0./
DATA weight / 7., 7., 7., 180., 100., 100., 100., &
900., 900., 900., 900., 900., 900., 7. , zf*0./
DATA fci_d / 0., 0., 0., 1.123, 0., 0., 0., &
1.121, 1.121, 1.121, 1.121, 1.121, 1.121, 0., zf*0./
DATA fct / 60., 60., 60., 60., 60., 60., 60., &
60., 120., 180., 180., 180., 180. , 60. , zf*0. /
DATA ichap / 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , zf*0/
contains
subroutine init_fuel_cats
implicit none
logical, external:: wrf_dm_on_monitor
integer:: i,j,k,ii,iounit
character(len=128):: msg
namelist /fuel_scalars/ cmbcnst,hfgl,fuelmc_g,fuelmc_c,nfuelcats,no_fuel_cat
namelist /fuel_categories/ fuel_name,windrf,fgi,fueldepthm,savr, &
fuelmce,fueldens,st,se,weight,fci_d,fct,ichap
IF ( wrf_dm_on_monitor() ) THEN
iounit=open_text_file('namelist.fire','read')
read(iounit,fuel_scalars)
read(iounit,fuel_categories)
CLOSE(iounit)
if (nfuelcats>mfuelcats) then
write(msg,*)'nfuelcats=',nfuelcats,' is too large, increase mfuelcats'
call crash(msg)
endif
if (no_fuel_cat >= 1 .and. no_fuel_cat <= nfuelcats)then
write(msg,*)'no_fuel_cat=',no_fuel_cat,' may not be between 1 and nfuelcats=',nfuelcats
call crash(msg)
endif
ENDIF
call wrf_dm_bcast_real(cmbcnst,1)
call wrf_dm_bcast_real(hfgl,1)
call wrf_dm_bcast_real(fuelmc_g,1)
call wrf_dm_bcast_real(fuelmc_c,1)
call wrf_dm_bcast_integer(nfuelcats,1)
call wrf_dm_bcast_integer(no_fuel_cat,1)
call wrf_dm_bcast_real(windrf, nfuelcats)
call wrf_dm_bcast_real(fgi, nfuelcats)
call wrf_dm_bcast_real(fueldepthm,nfuelcats)
call wrf_dm_bcast_real(savr, nfuelcats)
call wrf_dm_bcast_real(fuelmce, nfuelcats)
call wrf_dm_bcast_real(fueldens, nfuelcats)
call wrf_dm_bcast_real(st, nfuelcats)
call wrf_dm_bcast_real(se, nfuelcats)
call wrf_dm_bcast_real(weight, nfuelcats)
call wrf_dm_bcast_real(fci_d, nfuelcats)
call wrf_dm_bcast_real(fct, nfuelcats)
call wrf_dm_bcast_integer(ichap, nfuelcats)
bmst = fuelmc_g/(1+fuelmc_g)
fuelheat = cmbcnst * 4.30e-04
DO i = 1,nfuelcats
fci(i) = (1.+fuelmc_c)*fci_d(i)
if(fct(i) .ne. 0.)then
fcbr(i) = fci_d(i)/fct(i)
else
fcbr(i) = 0
endif
END DO
call message('**********************************************************')
call message('FUEL COEFFICIENTS')
write(msg,8)'cmbcnst ',cmbcnst
call message(msg)
write(msg,8)'hfgl ',hfgl
call message(msg)
write(msg,8)'fuelmc_g ',fuelmc_g
call message(msg)
write(msg,8)'fuelmc_c ',fuelmc_c
call message(msg)
write(msg,8)'bmst ',bmst
call message(msg)
write(msg,8)'fuelheat ',fuelheat
call message(msg)
write(msg,7)'nfuelcats ',nfuelcats
call message(msg)
write(msg,7)'no_fuel_cat',no_fuel_cat
call message(msg)
j=1
7 format(a,5(1x,i8,4x))
8 format(a,5(1x,g12.5e2))
9 format(a,5(1x,a))
do i=1,nfuelcats,j
k=min(i+j-1,nfuelcats)
call message(' ')
write(msg,7)'CATEGORY ',(ii,ii=i,k)
call message(msg)
write(msg,9)'fuel name ',(fuel_name(ii),ii=i,k)
call message(msg)
write(msg,8)'fgi ',(fgi(ii),ii=i,k)
call message(msg)
write(msg,8)'fueldepthm',(fueldepthm(ii),ii=i,k)
call message(msg)
write(msg,8)'savr ',(savr(ii),ii=i,k)
call message(msg)
write(msg,8)'fuelmce ',(fuelmce(ii),ii=i,k)
call message(msg)
write(msg,8)'fueldens ',(fueldens(ii),ii=i,k)
call message(msg)
write(msg,8)'st ',(st(ii),ii=i,k)
call message(msg)
write(msg,8)'se ',(se(ii),ii=i,k)
call message(msg)
write(msg,8)'weight ',(weight(ii),ii=i,k)
call message(msg)
write(msg,8)'fci_d ',(fci_d(ii),ii=i,k)
call message(msg)
write(msg,8)'fct ',(fct(ii),ii=i,k)
call message(msg)
write(msg,7)'ichap ',(ichap(ii),ii=i,k)
call message(msg)
write(msg,8)'fci ',(fci(ii),ii=i,k)
call message(msg)
write(msg,8)'fcbr ',(fcbr(ii),ii=i,k)
call message(msg)
enddo
call message('**********************************************************')
IF ( wrf_dm_on_monitor() ) THEN
call write_fuels_m(61,30.,1.)
ENDIF
end subroutine init_fuel_cats
subroutine write_fuels_m(nsteps,maxwind,maxslope)
implicit none
integer, intent(in):: nsteps
real, intent(in):: maxwind,maxslope
integer:: iounit,k,j,i
type(fire_params)::fp
real, dimension(1:2,1:nsteps), target::vx,vy,zsf,dzdxf,dzdyf,bbb,betafl,phiwc,r_0,fgip,ischap
real, dimension(1:2,1:nsteps)::nfuel_cat,fuel_time,ros
real::ros_base,ros_wind,ros_slope,propx,propy,r
fp%vx=>vx
fp%vy=>vy
fp%dzdxf=>dzdxf
fp%dzdyf=>dzdyf
fp%bbb=>bbb
fp%betafl=>betafl
fp%phiwc=>phiwc
fp%r_0=>r_0
fp%fgip=>fgip
fp%ischap=>ischap
iounit = open_text_file('fuels.m','write')
10 format('fuel(',i3,').',a,'=',"'",a,"'",';% ',a)
do k=1,nfuelcats
write(iounit,10)k,'fuel_name',trim(fuel_name(k)),'FUEL MODEL NAME'
call write_var(k,'windrf',windrf(k),'WIND REDUCTION FACTOR FROM 20ft TO MIDFLAME HEIGHT' )
call write_var(k,'fgi',fgi(k),'INITIAL TOTAL MASS OF SURFACE FUEL (KG/M**2)' )
call write_var(k,'fueldepthm',fueldepthm(k),'FUEL DEPTH (M)')
call write_var(k,'savr',savr(k),'FUEL PARTICLE SURFACE-AREA-TO-VOLUME RATIO, 1/FT')
call write_var(k,'fuelmce',fuelmce(k),'MOISTURE CONTENT OF EXTINCTION')
call write_var(k,'fueldens',fueldens(k),'OVENDRY PARTICLE DENSITY, LB/FT^3')
call write_var(k,'st',st(k),'FUEL PARTICLE TOTAL MINERAL CONTENT')
call write_var(k,'se',se(k),'FUEL PARTICLE EFFECTIVE MINERAL CONTENT')
call write_var(k,'weight',weight(k),'WEIGHTING PARAMETER THAT DETERMINES THE SLOPE OF THE MASS LOSS CURVE')
call write_var(k,'fci_d',fci_d(k),'INITIAL DRY MASS OF CANOPY FUEL')
call write_var(k,'fct',fct(k),'BURN OUT TIME FOR CANOPY FUEL, AFTER DRY (S)')
call write_var(k,'ichap',float(ichap(k)),'1 if chaparral, 0 if not')
call write_var(k,'fci',fci(k),'INITIAL TOTAL MASS OF CANOPY FUEL')
call write_var(k,'fcbr',fcbr(k),'FUEL CANOPY BURN RATE (KG/M**2/S)')
call write_var(k,'hfgl',hfgl,'SURFACE FIRE HEAT FLUX THRESHOLD TO IGNITE CANOPY (W/m^2)')
call write_var(k,'cmbcnst',cmbcnst,'JOULES PER KG OF DRY FUEL')
call write_var(k,'fuelheat',fuelheat,'FUEL PARTICLE LOW HEAT CONTENT, BTU/LB')
call write_var(k,'fuelmc_g',fuelmc_g,'FUEL PARTICLE (SURFACE) MOISTURE CONTENT')
call write_var(k,'fuelmc_c',fuelmc_c,'FUEL PARTICLE (CANOPY) MOISTURE CONTENT')
nfuel_cat = k
call set_fire_params( &
1,2,1,nsteps, &
1,2,1,nsteps, &
1,2,1,nsteps, &
0.,0.,k, &
nfuel_cat,fuel_time, &
fp )
propx=1.
propy=0.
do j=1,nsteps
r=float(j-1)/float(nsteps-1)
vx(1,j)=maxwind*r
vy(1,j)=0.
dzdxf(1,j)=0.
dzdyf(1,j)=0.
vx(2,j)=0.
vy(2,j)=0.
dzdxf(2,j)=maxslope*r
dzdyf(2,j)=0.
enddo
do j=1,nsteps
do i=1,2
call fire_ros(ros_base,ros_wind,ros_slope, &
propx,propy,i,j,fp)
ros(i,j)=ros_base+ros_wind+ros_slope
enddo
write(iounit,13)k,'wind',j,vx(1,j),'wind speed'
write(iounit,13)k,'ros_wind',j,ros(1,j),'rate of spread for the wind speed'
write(iounit,13)k,'slope',j,dzdxf(2,j),'slope'
write(iounit,13)k,'ros_slope',j,ros(2,j),'rate of spread for the slope'
enddo
enddo
13 format('fuel(',i3,').',a,'(',i3,')=',g12.5e2,';% ',a)
close(iounit)
contains
subroutine write_var(k,name,value,descr)
integer, intent(in)::k
character(len=*), intent(in)::name,descr
real, intent(in)::value
write(iounit,11)k,name,value
write(iounit,12)k,name,descr
11 format('fuel(',i3,').',a,'=',g12.5e2, ';')
12 format('fuel(',i3,').',a,"_descr='",a,"';")
end subroutine write_var
end subroutine write_fuels_m
subroutine set_fire_params( &
ifds,ifde,jfds,jfde, &
ifms,ifme,jfms,jfme, &
ifts,ifte,jfts,jfte, &
fdx,fdy,nfuel_cat0, &
nfuel_cat,fuel_time, &
fp )
implicit none
integer, intent(in)::ifds,ifde,jfds,jfde
integer, intent(in)::ifts,ifte,jfts,jfte
integer, intent(in)::ifms,ifme,jfms,jfme
real, intent(in):: fdx,fdy
integer,intent(in)::nfuel_cat0
real, intent(in),dimension(ifms:ifme, jfms:jfme)::nfuel_cat
real, intent(out), dimension(ifms:ifme, jfms:jfme)::fuel_time
type(fire_params),intent(inout)::fp
real:: fuelload, fueldepth, rtemp1, rtemp2, &
qig, epsilon, rhob, wn, betaop, e, c, &
xifr, etas, etam, a, gammax, gamma, ratio, ir, &
fuelloadm,fdxinv,fdyinv
integer:: i,j,k
integer::nerr
character(len=128)::msg
nerr=0
do j=jfts,jfte
do i=ifts,ifte
k=int( nfuel_cat(i,j) )
if(k.eq.no_fuel_cat)then
fp%fgip(i,j)=0.
fp%ischap(i,j)=0.
fp%betafl(i,j)=0.
fp%bbb(i,j)=1.
fuel_time(i,j)=7./0.85
fp%phiwc(i,j)=0.
fp%r_0(i,j)=0.
else
if(k.eq.0.and.nfuel_cat0.ge.1.and.nfuel_cat0.le.nfuelcats)then
k=nfuel_cat0
nerr=nerr+1
endif
if(k.lt.1.or.k.gt.nfuelcats)then
!$OMP CRITICAL(FIRE_PHYS_CRIT)
write(msg,'(3(a,i5))')'nfuel_cat(', i ,',',j,')=',k
!$OMP END CRITICAL(FIRE_PHYS_CRIT)
call message(msg)
call crash('set_fire_params: fuel category out of bounds')
endif
fuel_time(i,j)=weight(k)/0.85
fp%ischap(i,j)=ichap(k)
fp%fgip(i,j)=fgi(k)
fuelloadm= (1.-bmst) * fgi(k)
fuelload = fuelloadm * (.3048)**2 * 2.205
fueldepth = fueldepthm(k)/0.3048
fp%betafl(i,j) = fuelload/(fueldepth * fueldens(k))
betaop = 3.348 * savr(k)**(-0.8189)
qig = 250. + 1116.*fuelmc_g
epsilon = exp(-138./savr(k) )
rhob = fuelload/fueldepth
c = 7.47 * exp( -0.133 * savr(k)**0.55)
fp%bbb(i,j) = 0.02526 * savr(k)**0.54
e = 0.715 * exp( -3.59e-4 * savr(k))
fp%phiwc(i,j) = c * (fp%betafl(i,j)/betaop)**(-e)
rtemp2 = savr(k)**1.5
gammax = rtemp2/(495. + 0.0594*rtemp2)
a = 1./(4.774 * savr(k)**0.1 - 7.27)
ratio = fp%betafl(i,j)/betaop
gamma = gammax *(ratio**a) *exp(a*(1.-ratio))
wn = fuelload/(1 + st(k))
rtemp1 = fuelmc_g/fuelmce(k)
etam = 1.-2.59*rtemp1 +5.11*rtemp1**2 -3.52*rtemp1**3
etas = 0.174* se(k)**(-0.19)
ir = gamma * wn * fuelheat * etam * etas
xifr = exp( (0.792 + 0.681*savr(k)**0.5) &
* (fp%betafl(i,j)+0.1)) /(192. + 0.2595*savr(k))
fp%r_0(i,j) = ir*xifr/(rhob * epsilon *qig)
endif
enddo
enddo
if(nerr.gt.1)then
!$OMP CRITICAL(FIRE_PHYS_CRIT)
write(msg,'(a,i6,a)')'set_fire_params: WARNING: fuel category 0 replaced in',nerr,' cells'
!$OMP END CRITICAL(FIRE_PHYS_CRIT)
call message(msg)
endif
end subroutine set_fire_params
subroutine heat_fluxes(dt, &
ifms,ifme,jfms,jfme, &
ifts,ifte,jfts,jfte, &
iffs,iffe,jffs,jffe, &
fgip,fuel_frac_burnt, &
grnhft,grnqft)
implicit none
real, intent(in)::dt
integer, intent(in)::ifts,ifte,jfts,jfte,ifms,ifme,jfms,jfme,iffs,iffe,jffs,jffe
real, intent(in),dimension(ifms:ifme,jfms:jfme):: fgip
real, intent(in),dimension(iffs:iffe,jffs:jffe):: fuel_frac_burnt
real, intent(out),dimension(ifms:ifme,jfms:jfme):: grnhft,grnqft
integer::i,j
real:: dmass
do j=jfts,jfte
do i=ifts,ifte
dmass = &
fgip(i,j) &
* fuel_frac_burnt(i,j)
grnhft(i,j) = (dmass/dt)*(1.-bmst)*cmbcnst
grnqft(i,j) = (bmst+(1.-bmst)*.56)*(dmass/dt)*xlv
enddo
enddo
end subroutine heat_fluxes
subroutine set_nfuel_cat( &
ifms,ifme,jfms,jfme, &
ifts,ifte,jfts,jfte, &
ifuelread,nfuel_cat0,zsf,nfuel_cat)
implicit none
integer, intent(in):: ifts,ifte,jfts,jfte, &
ifms,ifme,jfms,jfme
integer, intent(in)::ifuelread,nfuel_cat0
real, intent(in), dimension(ifms:ifme, jfms:jfme)::zsf
real, intent(out), dimension(ifms:ifme, jfms:jfme)::nfuel_cat
integer:: i,j,iu1
real:: t1
character(len=128)msg
!$OMP CRITICAL(FIRE_PHYS_CRIT)
write(msg,'(a,i3)')'set_nfuel_cat: ifuelread=',ifuelread
!$OMP END CRITICAL(FIRE_PHYS_CRIT)
call message(msg)
if (ifuelread .eq. -1 .or. ifuelread .eq. 2) then
!$OMP CRITICAL(FIRE_PHYS_CRIT)
call message('set_nfuel_cat: assuming nfuel_cat initialized already')
call message(msg)
!$OMP END CRITICAL(FIRE_PHYS_CRIT)
else if (ifuelread .eq. 0) then
do j=jfts,jfte
do i=ifts,ifte
nfuel_cat(i,j)=real(nfuel_cat0)
enddo
enddo
!$OMP CRITICAL(FIRE_PHYS_CRIT)
write(msg,'(a,i3)')'set_nfuel_cat: fuel initialized with category',nfuel_cat0
!$OMP END CRITICAL(FIRE_PHYS_CRIT)
call message(msg)
else if (ifuelread .eq. 1) then
do j=jfts,jfte
do i=ifts,ifte
t1 = zsf(i,j)
if(t1.le.1524.)then
nfuel_cat(i,j)= 3
else if(t1.ge.1524. .and. t1.le.2073.)then
nfuel_cat(i,j)= 2
else if(t1.ge.2073..and.t1.le.2438.)then
nfuel_cat(i,j)= 8
else if(t1.gt.2438. .and. t1.le. 3354.) then
nfuel_cat(i,j)= 10
else if(t1.gt.3354. .and. t1.le. 3658.) then
nfuel_cat(i,j)= 1
else if(t1.gt.3658. ) then
nfuel_cat(i,j)= 14
endif
enddo
enddo
call message('set_nfuel_cat: fuel initialized by altitude')
else
call crash('set_nfuel_cat: bad ifuelread')
endif
end subroutine set_nfuel_cat
subroutine fire_ros(ros_base,ros_wind,ros_slope, &
propx,propy,i,j,fp)
implicit none
real, intent(out)::ros_base,ros_wind,ros_slope
real, intent(in)::propx,propy
integer, intent(in)::i,j
type(fire_params),intent(in)::fp
real:: speed, tanphi
real:: umid, phis, phiw, spdms, umidm, excess
real:: ros_back
integer, parameter::ibeh=1
real, parameter::ros_max=6.
character(len=128)msg
real::cor_wind,cor_slope,nvx,nvy,scale
scale=1.
nvx=propx/scale
nvy=propy/scale
if (fire_advection.ne.0) then
speed = sqrt(fp%vx(i,j)*fp%vx(i,j)+ fp%vy(i,j)*fp%vy(i,j))+tiny(speed)
tanphi = sqrt(fp%dzdxf(i,j)*fp%dzdxf(i,j) + fp%dzdyf(i,j)*fp%dzdyf(i,j))+tiny(tanphi)
cor_wind = max(0.,(fp%vx(i,j)*nvx + fp%vy(i,j)*nvy)/speed)
cor_slope = max(0., (fp%dzdxf(i,j)*nvx + fp%dzdyf(i,j)*nvy)/tanphi)
else
speed = fp%vx(i,j)*nvx + fp%vy(i,j)*nvy
tanphi = fp%dzdxf(i,j)*nvx + fp%dzdyf(i,j)*nvy
cor_wind=1.
cor_slope=1.
endif
if (.not. fp%ischap(i,j) > 0.) then
if (ibeh .eq. 1) then
spdms = max(speed,0.)
umidm = min(spdms,30.)
umid = umidm * 196.850
phiw = umid**fp%bbb(i,j) * fp%phiwc(i,j)
phis=0.
if (tanphi .gt. 0.) then
phis = 5.275 *(fp%betafl(i,j))**(-0.3) *tanphi**2
endif
ros_base = fp%r_0(i,j) * .00508
ros_wind = ros_base*phiw
ros_slope= ros_base*phis
else
ros_base = 0.18*exp(0.8424)
ros_wind = 0.18*exp(0.8424*max(speed,0.))
ros_slope =0.
endif
else
spdms = max(speed,0.)
ros_back=.03333
ros_wind = 1.2974 * spdms**1.41
ros_wind = max(ros_wind, ros_back)
ros_slope =0.
endif
ros_wind=ros_wind*cor_wind
ros_slope=ros_slope*cor_slope
excess = ros_base + ros_wind + ros_slope - ros_max
if (excess > 0.)then
ros_wind = ros_wind - excess*ros_wind/(ros_wind+ros_slope)
ros_slope = ros_slope - excess*ros_slope/(ros_wind+ros_slope)
endif
return
contains
real function nrm2(u,v)
real, intent(in)::u,v
nrm2=sqrt(u*u+v*v)
end function nrm2
end subroutine fire_ros
end module module_fr_fire_phys
|
#' Add style to a string
#'
#' See `names(styles)`, or the crayon manual for available styles.
#'
#' @param string Character vector to style.
#' @param as Style function to apply, either the function object,
#' or its name, or an object to pass to [make_style()].
#' @param bg Background style, a style function, or a name that
#' is passed to [make_style()].
#' @return Styled character vector.
#'
#' @export
#' @importFrom methods is
#'
#' @examples
#' ## These are equivalent
#' style("foobar", bold)
#' style("foobar", "bold")
#' bold("foobar")
style <- function(string, as = NULL, bg = NULL) {
as <- use_or_make_style(as)
bg <- use_or_make_style(bg, bg = TRUE)
if (!is(as, "crayon")) stop("Cannot make style from 'as'")
if (!is(bg, "crayon")) stop("Cannot make style from 'bg'")
as(bg(string))
}
#' @importFrom methods is
use_or_make_style <- function(style, bg = FALSE) {
if (is.null(style)) {
structure(base::identity, class = "crayon")
} else if (is(style, "crayon")) {
style
} else if (style %in% names(styles())) {
make_crayon(styles()[style])
} else {
make_style(style, bg = bg)
}
}
|
Require Import CodeProofDeps.
Require Import Ident.
Require Import Constants.
Require Import RData.
Require Import EventReplay.
Require Import MoverTypes.
Require Import CommonLib.
Require Import TableDataOpsIntro.Spec.
Require Import TableDataOpsRef1.Spec.
Require Import TableDataOpsRef1.Layer.
Require Import TableDataOpsRef2.Code.table_unmap2.
Require Import TableDataOpsRef2.LowSpecs.table_unmap2.
Local Open Scope Z_scope.
Section CodeProof.
Context `{real_params: RealParams}.
Context {memb} `{Hmemx: Mem.MemoryModelX memb}.
Context `{Hmwd: UseMemWithData memb}.
Let mem := mwd (cdata RData).
Context `{Hstencil: Stencil}.
Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.
Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.
Let L : compatlayer (cdata RData) :=
_table_unmap ↦ gensem table_unmap_spec
⊕ _table_unmap1 ↦ gensem table_unmap1_spec
.
Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.
Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.
Section BodyProof.
Context `{Hwb: WritableBlockOps}.
Variable (sc: stencil).
Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge).
Variable b_table_unmap: block.
Hypothesis h_table_unmap_s : Genv.find_symbol ge _table_unmap = Some b_table_unmap.
Hypothesis h_table_unmap_p : Genv.find_funct_ptr ge b_table_unmap
= Some (External (EF_external _table_unmap
(signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default))
(Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default).
Local Opaque table_unmap_spec.
Variable b_table_unmap1: block.
Hypothesis h_table_unmap1_s : Genv.find_symbol ge _table_unmap1 = Some b_table_unmap1.
Hypothesis h_table_unmap1_p : Genv.find_funct_ptr ge b_table_unmap1
= Some (External (EF_external _table_unmap1
(signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default))
(Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default).
Local Opaque table_unmap1_spec.
Lemma table_unmap2_body_correct:
forall m d d' env le g_rd_base g_rd_offset map_addr level res
(Henv: env = PTree.empty _)
(Hinv: high_level_invariant d)
(HPTg_rd: PTree.get _g_rd le = Some (Vptr g_rd_base (Int.repr g_rd_offset)))
(HPTmap_addr: PTree.get _map_addr le = Some (Vlong map_addr))
(HPTlevel: PTree.get _level le = Some (Vlong level))
(Hspec: table_unmap2_spec0 (g_rd_base, g_rd_offset) (VZ64 (Int64.unsigned map_addr)) (VZ64 (Int64.unsigned level)) d = Some (d', VZ64 (Int64.unsigned res))),
exists le', (exec_stmt ge env le ((m, d): mem) table_unmap2_body E0 le' (m, d') (Out_return (Some (Vlong res, tulong)))).
Proof.
solve_code_proof Hspec table_unmap2_body; eexists; solve_proof_low.
Qed.
End BodyProof.
End CodeProof.
|
(* Title: JinjaThreads/Common/StartConfig.thy
Author: Andreas Lochbihler
*)
header {*
\isaheader{The initial configuration}
*}
theory StartConfig
imports
Exceptions
Observable_Events
begin
definition initialization_list :: "cname list"
where
"initialization_list = Thread # sys_xcpts_list"
context heap_base begin
definition create_initial_object :: "'heap \<times> 'addr list \<times> bool \<Rightarrow> cname \<Rightarrow> 'heap \<times> 'addr list \<times> bool"
where
"create_initial_object =
(\<lambda>(h, ads, b) C.
if b
then let HA = allocate h (Class_type C)
in if HA = {} then (h, ads, False)
else let (h', a'') = SOME ha. ha \<in> HA in (h', ads @ [a''], True)
else (h, ads, False))"
definition start_heap_data :: "'heap \<times> 'addr list \<times> bool"
where
"start_heap_data = foldl create_initial_object (empty_heap, [], True) initialization_list"
definition start_heap :: 'heap
where "start_heap = fst start_heap_data"
definition start_heap_ok :: bool
where "start_heap_ok = snd (snd (start_heap_data))"
definition start_heap_obs :: "('addr, 'thread_id) obs_event list"
where
"start_heap_obs =
map (\<lambda>(C, a). NewHeapElem a (Class_type C)) (zip initialization_list (fst (snd start_heap_data)))"
definition start_addrs :: "'addr list"
where "start_addrs = fst (snd start_heap_data)"
definition addr_of_sys_xcpt :: "cname \<Rightarrow> 'addr"
where "addr_of_sys_xcpt C = the (map_of (zip initialization_list start_addrs) C)"
definition start_tid :: 'thread_id
where "start_tid = addr2thread_id (hd start_addrs)"
definition start_state :: "(cname \<Rightarrow> mname \<Rightarrow> ty list \<Rightarrow> ty \<Rightarrow> 'm \<Rightarrow> 'addr val list \<Rightarrow> 'x) \<Rightarrow> 'm prog \<Rightarrow> cname \<Rightarrow> mname \<Rightarrow> 'addr val list \<Rightarrow> ('addr,'thread_id,'x,'heap,'addr) state"
where
"start_state f P C M vs \<equiv>
let (D, Ts, T, m) = method P C M
in (K$ None, ([start_tid \<mapsto> (f D M Ts T (the m) vs, no_wait_locks)], start_heap), empty, {})"
lemma create_initial_object_simps:
"create_initial_object (h, ads, b) C =
(if b
then let HA = allocate h (Class_type C)
in if HA = {} then (h, ads, False)
else let (h', a'') = SOME ha. ha \<in> HA in (h', ads @ [a''], True)
else (h, ads, False))"
unfolding create_initial_object_def by simp
lemma create_initial_object_False [simp]:
"create_initial_object (h, ads, False) C = (h, ads, False)"
by(simp add: create_initial_object_simps)
lemma foldl_create_initial_object_False [simp]:
"foldl create_initial_object (h, ads, False) Cs = (h, ads, False)"
by(induct Cs) simp_all
lemma NewHeapElem_start_heap_obs_start_addrsD:
"NewHeapElem a CTn \<in> set start_heap_obs \<Longrightarrow> a \<in> set start_addrs"
unfolding start_heap_obs_def start_addrs_def
by(auto dest: set_zip_rightD)
lemma shr_start_state: "shr (start_state f P C M vs) = start_heap"
by(simp add: start_state_def split_beta)
lemma start_heap_obs_not_Read:
"ReadMem ad al v \<notin> set start_heap_obs"
unfolding start_heap_obs_def by auto
lemma length_initialization_list_le_length_start_addrs:
"length initialization_list \<ge> length start_addrs"
proof -
{ fix h ads xs
have "length (fst (snd (foldl create_initial_object (h, ads, True) xs))) \<le> length ads + length xs"
proof(induct xs arbitrary: h ads)
case Nil thus ?case by simp
next
case (Cons x xs)
from this[of "fst (SOME ha. ha \<in> allocate h (Class_type x))" "ads @ [snd (SOME ha. ha \<in> allocate h (Class_type x))]"]
show ?case by(clarsimp simp add: create_initial_object_simps split_beta)
qed }
from this[of empty_heap "[]" initialization_list]
show ?thesis unfolding start_heap_def start_addrs_def start_heap_data_def by simp
qed
lemma distinct_initialization_list:
"distinct initialization_list"
by(simp add: initialization_list_def sys_xcpts_list_def sys_xcpts_neqs Thread_neq_sys_xcpts)
lemma wf_syscls_initialization_list_is_class:
"\<lbrakk> wf_syscls P; C \<in> set initialization_list \<rbrakk> \<Longrightarrow> is_class P C"
by(auto simp add: initialization_list_def sys_xcpts_list_def wf_syscls_is_class_xcpt)
lemma start_addrs_NewHeapElem_start_heap_obsD:
"a \<in> set start_addrs \<Longrightarrow> \<exists>CTn. NewHeapElem a CTn \<in> set start_heap_obs"
using length_initialization_list_le_length_start_addrs
unfolding start_heap_obs_def start_addrs_def
by(force simp add: set_zip in_set_conv_nth intro: rev_image_eqI)
lemma in_set_start_addrs_conv_NewHeapElem:
"a \<in> set start_addrs \<longleftrightarrow> (\<exists>CTn. NewHeapElem a CTn \<in> set start_heap_obs)"
by(blast dest: start_addrs_NewHeapElem_start_heap_obsD intro: NewHeapElem_start_heap_obs_start_addrsD)
subsection {* @{term preallocated} *}
definition preallocated :: "'heap \<Rightarrow> bool"
where "preallocated h \<equiv> \<forall>C \<in> sys_xcpts. typeof_addr h (addr_of_sys_xcpt C) = \<lfloor>Class_type C\<rfloor>"
lemma typeof_addr_sys_xcp:
"\<lbrakk> preallocated h; C \<in> sys_xcpts \<rbrakk> \<Longrightarrow> typeof_addr h (addr_of_sys_xcpt C) = \<lfloor>Class_type C\<rfloor>"
by(simp add: preallocated_def)
lemma typeof_sys_xcp:
"\<lbrakk> preallocated h; C \<in> sys_xcpts \<rbrakk> \<Longrightarrow> typeof\<^bsub>h\<^esub> (Addr (addr_of_sys_xcpt C)) = \<lfloor>Class C\<rfloor>"
by(simp add: typeof_addr_sys_xcp)
lemma addr_of_sys_xcpt_start_addr:
"\<lbrakk> start_heap_ok; C \<in> sys_xcpts \<rbrakk> \<Longrightarrow> addr_of_sys_xcpt C \<in> set start_addrs"
unfolding start_heap_ok_def start_heap_data_def initialization_list_def sys_xcpts_list_def
preallocated_def start_heap_def start_addrs_def
apply(simp split: prod.split_asm split_if_asm add: create_initial_object_simps)
apply(erule sys_xcpts_cases)
apply(simp_all add: addr_of_sys_xcpt_def start_addrs_def start_heap_data_def initialization_list_def sys_xcpts_list_def create_initial_object_simps)
done
lemma cname_of_xcp [simp]:
"\<lbrakk> preallocated h; C \<in> sys_xcpts \<rbrakk> \<Longrightarrow> cname_of h (addr_of_sys_xcpt C) = C"
by(drule (1) typeof_addr_sys_xcp)(simp add: cname_of_def)
lemma preallocated_hext:
"\<lbrakk> preallocated h; h \<unlhd> h' \<rbrakk> \<Longrightarrow> preallocated h'"
by(auto simp add: preallocated_def dest: hext_objD)
end
context heap begin
lemma preallocated_heap_ops:
assumes "preallocated h"
shows preallocated_allocate: "\<And>a. (h', a) \<in> allocate h hT \<Longrightarrow> preallocated h'"
and preallocated_write_field: "heap_write h a al v h' \<Longrightarrow> preallocated h'"
using preallocated_hext[OF assms, of h']
by(blast intro: hext_heap_ops)+
lemma not_empty_pairE: "\<lbrakk> A \<noteq> {}; \<And>a b. (a, b) \<in> A \<Longrightarrow> thesis \<rbrakk> \<Longrightarrow> thesis"
by auto
lemma allocate_not_emptyI: "(h', a) \<in> allocate h hT \<Longrightarrow> allocate h hT \<noteq> {}"
by auto
lemma allocate_Eps:
"\<lbrakk> (h'', a'') \<in> allocate h hT; (SOME ha. ha \<in> allocate h hT) = (h', a') \<rbrakk> \<Longrightarrow> (h', a') \<in> allocate h hT"
by(drule sym)(auto intro: someI)
lemma preallocated_start_heap:
"\<lbrakk> start_heap_ok; wf_syscls P \<rbrakk> \<Longrightarrow> preallocated start_heap"
unfolding start_heap_ok_def start_heap_data_def initialization_list_def sys_xcpts_list_def
preallocated_def start_heap_def start_addrs_def
apply(clarsimp split: prod.split_asm split_if_asm simp add: create_initial_object_simps)
apply(erule not_empty_pairE)+
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(drule (1) allocate_Eps)
apply(rotate_tac 13)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(frule allocate_SomeD, simp add: wf_syscls_is_class_xcpt, frule hext_allocate, rotate_tac 1)
apply(erule sys_xcpts_cases)
apply(simp_all add: addr_of_sys_xcpt_def initialization_list_def sys_xcpts_list_def sys_xcpts_neqs Thread_neq_sys_xcpts start_heap_data_def start_addrs_def create_initial_object_simps allocate_not_emptyI split del: split_if)
apply(assumption|erule typeof_addr_hext_mono)+
done
lemma start_tid_start_addrs:
"\<lbrakk> wf_syscls P; start_heap_ok \<rbrakk> \<Longrightarrow> thread_id2addr start_tid \<in> set start_addrs"
unfolding start_heap_ok_def start_heap_data_def initialization_list_def sys_xcpts_list_def
preallocated_def start_heap_def start_addrs_def
apply(simp split: prod.split_asm split_if_asm add: create_initial_object_simps addr_of_sys_xcpt_def start_addrs_def start_tid_def start_heap_data_def initialization_list_def sys_xcpts_list_def)
apply(erule not_empty_pairE)+
apply(drule (1) allocate_Eps)
apply(rotate_tac -1)
apply(drule allocate_SomeD, simp)
apply(auto intro: addr2thread_id_inverse)
done
lemma
assumes "wf_syscls P"
shows dom_typeof_addr_start_heap: "set start_addrs \<subseteq> dom (typeof_addr start_heap)"
and distinct_start_addrs: "distinct start_addrs"
proof -
{ fix h ads b and Cs xs :: "cname list"
assume "set ads \<subseteq> dom (typeof_addr h)" and "distinct (Cs @ xs)" and "length Cs = length ads"
and "\<And>C a. (C, a) \<in> set (zip Cs ads) \<Longrightarrow> typeof_addr h a = \<lfloor>Class_type C\<rfloor>"
and "\<And>C. C \<in> set xs \<Longrightarrow> is_class P C"
hence "set (fst (snd (foldl create_initial_object (h, ads, b) xs))) \<subseteq>
dom (typeof_addr (fst (foldl create_initial_object (h, ads, b) xs))) \<and>
(distinct ads \<longrightarrow> distinct (fst (snd (foldl create_initial_object (h, ads, b) xs))))"
(is "?concl xs h ads b Cs")
proof(induct xs arbitrary: h ads b Cs)
case Nil thus ?case by auto
next
case (Cons x xs)
note ads = `set ads \<subseteq> dom (typeof_addr h)`
note dist = `distinct (Cs @ x # xs)`
note len = `length Cs = length ads`
note type = `\<And>C a. (C, a) \<in> set (zip Cs ads) \<Longrightarrow> typeof_addr h a = \<lfloor>Class_type C\<rfloor>`
note is_class = `\<And>C. C \<in> set (x # xs) \<Longrightarrow> is_class P C`
show ?case
proof(cases "b \<and> allocate h (Class_type x) \<noteq> {}")
case False thus ?thesis
using ads len by(auto simp add: create_initial_object_simps zip_append1)
next
case True[simp]
obtain h' a' where h'a': "(SOME ha. ha \<in> allocate h (Class_type x)) = (h', a')"
by(cases "SOME ha. ha \<in> allocate h (Class_type x)")
with True have new_obj: "(h', a') \<in> allocate h (Class_type x)"
by(auto simp del: True intro: allocate_Eps)
hence hext: "h \<unlhd> h'" by(rule hext_allocate)
with ads new_obj have ads': "set ads \<subseteq> dom (typeof_addr h')"
by(auto dest: typeof_addr_hext_mono[OF hext_allocate])
moreover {
from new_obj ads' is_class[of x]
have "set (ads @ [a']) \<subseteq> dom (typeof_addr h')"
by(auto dest: allocate_SomeD)
moreover from dist have "distinct ((Cs @ [x]) @ xs)" by simp
moreover have "length (Cs @ [x]) = length (ads @ [a'])" using len by simp
moreover {
fix C a
assume "(C, a) \<in> set (zip (Cs @ [x]) (ads @ [a']))"
hence "typeof_addr h' a = \<lfloor>Class_type C\<rfloor>"
using hext new_obj type[of C a] len is_class
by(auto dest: allocate_SomeD hext_objD) }
note type' = this
moreover have is_class': "\<And>C. C \<in> set xs \<Longrightarrow> is_class P C" using is_class by simp
ultimately have "?concl xs h' (ads @ [a']) True (Cs @ [x])" by(rule Cons)
moreover have "a' \<notin> set ads"
proof
assume a': "a' \<in> set ads"
then obtain C where "(C, a') \<in> set (zip Cs ads)" "C \<in> set Cs"
using len unfolding set_zip in_set_conv_nth by auto
hence "typeof_addr h a' = \<lfloor>Class_type C\<rfloor>" by-(rule type)
with hext have "typeof_addr h' a' = \<lfloor>Class_type C\<rfloor>" by(rule typeof_addr_hext_mono)
moreover from new_obj is_class
have "typeof_addr h' a' = \<lfloor>Class_type x\<rfloor>" by(auto dest: allocate_SomeD)
ultimately have "C = x" by simp
with dist `C \<in> set Cs` show False by simp
qed
moreover note calculation }
ultimately show ?thesis by(simp add: create_initial_object_simps new_obj h'a')
qed
qed }
from this[of "[]" empty_heap "[]" initialization_list True]
distinct_initialization_list wf_syscls_initialization_list_is_class[OF assms]
show "set start_addrs \<subseteq> dom (typeof_addr start_heap)"
and "distinct start_addrs"
unfolding start_heap_def start_addrs_def start_heap_data_def by auto
qed
lemma NewHeapElem_start_heap_obsD:
assumes "wf_syscls P"
and "NewHeapElem a hT \<in> set start_heap_obs"
shows "typeof_addr start_heap a = \<lfloor>hT\<rfloor>"
proof -
show ?thesis
proof(cases hT)
case (Class_type C)
{ fix h ads b xs Cs
assume "(C, a) \<in> set (zip (Cs @ xs) (fst (snd (foldl create_initial_object (h, ads, b) xs))))"
and "\<forall>(C, a) \<in> set (zip Cs ads). typeof_addr h a = \<lfloor>Class_type C\<rfloor>"
and "length Cs = length ads"
and "\<forall>C \<in> set xs. is_class P C"
hence "typeof_addr (fst (foldl create_initial_object (h, ads, b) xs)) a = \<lfloor>Class_type C\<rfloor>"
proof(induct xs arbitrary: h ads b Cs)
case Nil thus ?case by auto
next
case (Cons x xs)
note inv = `\<forall>(C, a) \<in> set (zip Cs ads). typeof_addr h a = \<lfloor>Class_type C\<rfloor>`
and Ca = `(C, a) \<in> set (zip (Cs @ x # xs) (fst (snd (foldl create_initial_object (h, ads, b) (x # xs)))))`
and len = `length Cs = length ads`
and is_class = `\<forall>C \<in> set (x # xs). is_class P C`
show ?case
proof(cases "b \<and> allocate h (Class_type x) \<noteq> {}")
case False thus ?thesis
using inv Ca len by(auto simp add: create_initial_object_simps zip_append1 split: split_if_asm)
next
case True[simp]
obtain h' a' where h'a': "(SOME ha. ha \<in> allocate h (Class_type x)) = (h', a')"
by(cases "SOME ha. ha \<in> allocate h (Class_type x)")
with True have new_obj: "(h', a') \<in> allocate h (Class_type x)"
by(auto simp del: True intro: allocate_Eps)
hence hext: "h \<unlhd> h'" by(rule hext_allocate)
have "(C, a) \<in> set (zip ((Cs @ [x]) @ xs) (fst (snd (foldl create_initial_object (h', ads @ [a'], True) xs))))"
using Ca new_obj by(simp add: create_initial_object_simps h'a')
moreover have "\<forall>(C, a)\<in>set (zip (Cs @ [x]) (ads @ [a'])). typeof_addr h' a = \<lfloor>Class_type C\<rfloor>"
proof(clarify)
fix C a
assume "(C, a) \<in> set (zip (Cs @ [x]) (ads @ [a']))"
thus "typeof_addr h' a = \<lfloor>Class_type C\<rfloor>"
using inv len hext new_obj is_class by(auto dest: allocate_SomeD typeof_addr_hext_mono)
qed
moreover have "length (Cs @ [x]) = length (ads @ [a'])" using len by simp
moreover have "\<forall>C \<in> set xs. is_class P C" using is_class by simp
ultimately have "typeof_addr (fst (foldl create_initial_object (h', ads @ [a'], True) xs)) a = \<lfloor>Class_type C\<rfloor>"
by(rule Cons)
thus ?thesis using new_obj by(simp add: create_initial_object_simps h'a')
qed
qed }
from this[of "[]" initialization_list empty_heap "[]" True] assms wf_syscls_initialization_list_is_class[of P]
show ?thesis by(auto simp add: start_heap_obs_def start_heap_data_def start_heap_def Class_type)
next
case Array_type thus ?thesis using assms
by(auto simp add: start_heap_obs_def start_heap_data_def start_heap_def)
qed
qed
end
subsection {* Code generation *}
definition pick_addr :: "('heap \<times> 'addr) set \<Rightarrow> 'heap \<times> 'addr"
where "pick_addr HA = (SOME ha. ha \<in> HA)"
lemma pick_addr_code [code]:
"pick_addr (set [ha]) = ha"
by(simp add: pick_addr_def)
lemma (in heap_base) start_heap_data_code:
"start_heap_data =
(let
(h, ads, b) = foldl
(\<lambda>(h, ads, b) C.
if b then
let HA = allocate h (Class_type C)
in if HA = {} then (h, ads, False)
else let (h', a'') = pick_addr HA in (h', a'' # ads, True)
else (h, ads, False))
(empty_heap, [], True)
initialization_list
in (h, rev ads, b))"
unfolding start_heap_data_def create_initial_object_def pick_addr_def
by(rule rev_induct)(simp_all add: split_beta)
lemmas [code] =
heap_base.start_heap_data_code
heap_base.start_heap_def
heap_base.start_heap_ok_def
heap_base.start_heap_obs_def
heap_base.start_addrs_def
heap_base.addr_of_sys_xcpt_def
heap_base.start_tid_def
heap_base.start_state_def
end |
(*
Copyright (C) 2019 Susi Lehtola
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/.
*)
(* type: gga_exc *)
(* prefix:
gga_x_s12_params *params;
assert(p->params != NULL);
params = (gga_x_s12_params * )(p->params);
*)
s12g_f := x -> params_a_bx*(params_a_A + params_a_B*(1 - 1/(1 + params_a_C*x^2 + params_a_D*x^4))*(1 - 1/(1 + params_a_E*x^2))):
f := (rs, z, xt, xs0, xs1) -> gga_exchange(s12g_f, rs, z, xs0, xs1):
|
Root of Happiness is an alcoholfree bar that serves kava shots, kava mixed drinks, and kombucha. The bar is open to the 18andover crowd. The ambience is quite relaxing and reminiscent of the tropics, featuring a mural by artist Te Pou Huke, who was flown in from Easter Island just to create the piece. They also have board games like chess and Jenga!
If you are new to kava, Wednesdays are a good time to get introduced, because the bar offers three kava shots for $10. They also have a happy hour on most days from 47pm.
The Davis Root of Happiness opened in July 2014 after about a year of postponements. It is the second kava bar of the same name, the first of which can be found in Rancho Cordova.
What is Kava?
Kava is a shrub native to the Western Pacific Islands, prized for its root. The root is harvested, ground up, and traditionally prepared as a beverage in a halved coconut shell. The drink is of increasing popularity in the West due to its mild relaxing effects. Most users agree that kava does not affect mental clarity, making it markedly different than other recreational drugs like alcohol. However, it is not advisable to take kava along with alcohol as it can upset the stomach and increase drowsiness. There is some evidence that Kava is hepatotoxic (causes liver damage).
|
/* multimin/fdfminimizer.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multimin.h>
gsl_multimin_fdfminimizer *
gsl_multimin_fdfminimizer_alloc (const gsl_multimin_fdfminimizer_type * T,
size_t n)
{
int status;
gsl_multimin_fdfminimizer *s =
(gsl_multimin_fdfminimizer *) malloc (sizeof (gsl_multimin_fdfminimizer));
if (s == 0)
{
GSL_ERROR_VAL ("failed to allocate space for minimizer struct",
GSL_ENOMEM, 0);
}
s->type = T;
s->x = gsl_vector_calloc (n);
if (s->x == 0)
{
free (s);
GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
}
s->gradient = gsl_vector_calloc (n);
if (s->gradient == 0)
{
gsl_vector_free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for gradient", GSL_ENOMEM, 0);
}
s->dx = gsl_vector_calloc (n);
if (s->dx == 0)
{
gsl_vector_free (s->x);
gsl_vector_free (s->gradient);
free (s);
GSL_ERROR_VAL ("failed to allocate space for dx", GSL_ENOMEM, 0);
}
s->state = malloc (T->size);
if (s->state == 0)
{
gsl_vector_free (s->x);
gsl_vector_free (s->gradient);
gsl_vector_free (s->dx);
free (s);
GSL_ERROR_VAL ("failed to allocate space for minimizer state",
GSL_ENOMEM, 0);
}
status = (T->alloc) (s->state, n);
if (status != GSL_SUCCESS)
{
free (s->state);
gsl_vector_free (s->x);
gsl_vector_free (s->gradient);
gsl_vector_free (s->dx);
free (s);
GSL_ERROR_VAL ("failed to initialize minimizer state", GSL_ENOMEM, 0);
}
return s;
}
int
gsl_multimin_fdfminimizer_set (gsl_multimin_fdfminimizer * s,
gsl_multimin_function_fdf * fdf,
const gsl_vector * x,
double step_size, double tol)
{
if (s->x->size != fdf->n)
{
GSL_ERROR ("function incompatible with solver size", GSL_EBADLEN);
}
if (x->size != fdf->n)
{
GSL_ERROR ("vector length not compatible with function", GSL_EBADLEN);
}
s->fdf = fdf;
gsl_vector_memcpy (s->x,x);
gsl_vector_set_zero (s->dx);
return (s->type->set) (s->state, s->fdf, s->x, &(s->f), s->gradient, step_size, tol);
}
void
gsl_multimin_fdfminimizer_free (gsl_multimin_fdfminimizer * s)
{
(s->type->free) (s->state);
free (s->state);
gsl_vector_free (s->dx);
gsl_vector_free (s->gradient);
gsl_vector_free (s->x);
free (s);
}
int
gsl_multimin_fdfminimizer_iterate (gsl_multimin_fdfminimizer * s)
{
return (s->type->iterate) (s->state, s->fdf, s->x, &(s->f), s->gradient, s->dx);
}
int
gsl_multimin_fdfminimizer_restart (gsl_multimin_fdfminimizer * s)
{
return (s->type->restart) (s->state);
}
const char *
gsl_multimin_fdfminimizer_name (const gsl_multimin_fdfminimizer * s)
{
return s->type->name;
}
gsl_vector *
gsl_multimin_fdfminimizer_x (gsl_multimin_fdfminimizer * s)
{
return s->x;
}
gsl_vector *
gsl_multimin_fdfminimizer_dx (gsl_multimin_fdfminimizer * s)
{
return s->dx;
}
gsl_vector *
gsl_multimin_fdfminimizer_gradient (gsl_multimin_fdfminimizer * s)
{
return s->gradient;
}
double
gsl_multimin_fdfminimizer_minimum (gsl_multimin_fdfminimizer * s)
{
return s->f;
}
|
State Before: k : Type u₁
G : Type u₂
R : Type ?u.2056792
inst✝¹ : Semiring k
inst✝ : AddZeroClass G
f : AddMonoidAlgebra k G
r : k
x a : G
⊢ a + 0 = x ↔ a = x State After: no goals Tactic: rw [add_zero] |
// based on: http://stackoverflow.com/questions/12215395/thread-pool-using-boost-asio
// code from: Tanner Sansbury
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <atomic>
class asio_thread_pool
{
private:
boost::asio::io_service io_service_;
boost::asio::io_service::work work_;
boost::thread_group threads_;
std::atomic<std::size_t> available_;
public:
/// @brief Constructor.
asio_thread_pool( std::size_t pool_size )
: work_( io_service_ ),
available_( pool_size )
{
for ( std::size_t i = 0; i < pool_size; ++i )
{
threads_.create_thread( boost::bind( &boost::asio::io_service::run,
&io_service_ ) );
}
}
/// @brief Destructor.
~asio_thread_pool()
{
// Force all threads to return from io_service::run().
io_service_.stop();
// Suppress all exceptions.
try
{
threads_.join_all();
}
catch ( const std::exception& ) {}
}
/// @brief Adds a task to the thread pool if a thread is currently available.
template < typename Task >
bool run_task( Task task )
{
// If no threads are available, then return.
if ( 0 == available_ ) return false;
// Decrement count, indicating thread is no longer available.
--available_;
// Post a wrapped task into the queue.
io_service_.post( boost::bind( &asio_thread_pool::wrap_task, this,
boost::function< void() >( task ) ) );
return true;
}
private:
/// @brief Wrap a task so that the available count can be increased once
/// the user provided task has completed.
void wrap_task( boost::function< void() > task )
{
// Run the user supplied task.
try
{
task();
}
// Suppress all exceptions.
catch ( const std::exception& ) {}
// Task has finished, so increment count of available threads.
++available_;
}
};
|
import group.basic group.powers finsum.basic
/-!
Basic definitions for subgroups in group theory.
Not for the mathematician beginner.
-/
-- We're always overwriting group theory here so we always work in
-- a namespace
namespace mygroup
open mygroup.group
/- subgroups (bundled) -/
/-- A subgroup of a group G is a subset containing 1
and closed under multiplication and inverse. -/
structure subgroup (G : Type) [group G] :=
(carrier : set G)
(one_mem' : (1 : G) ∈ carrier)
(mul_mem' {x y} : x ∈ carrier → y ∈ carrier → x * y ∈ carrier)
(inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier)
-- Defintion of normal subgroup (in a bundled form)
structure normal (G : Type) [group G] extends subgroup G :=
(conj_mem' : ∀ n, n ∈ carrier → ∀ g : G, g * n * g⁻¹ ∈ carrier)
-- we put dashes in all the names, because we'll define
-- non-dashed versions which don't mention `carrier` at all
-- and just talk about elements of the subgroup.
namespace subgroup
variables {G : Type} [group G] (H : subgroup G)
-- Instead let's define ∈ directly
instance : has_mem G (subgroup G) := ⟨λ m H, m ∈ H.carrier⟩
-- subgroups form a lattice and we might want to prove this
-- later on?
instance : has_le (subgroup G) := ⟨λ S T, S.carrier ⊆ T.carrier⟩
/-- Two subgroups are equal if the underlying subsets are equal. -/
theorem ext' {H K : subgroup G} (h : H.carrier = K.carrier) : H = K :=
by cases H; cases K; congr'
/-- Two subgroups are equal if they have the same elements. -/
theorem ext {H K : subgroup G}
(h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h
lemma mem_coe {g : G} : g ∈ H.carrier ↔ g ∈ H := iff.rfl
/-- Two subgroups are equal if and only if the underlying subsets are equal. -/
protected theorem ext'_iff {H K : subgroup G} :
H.carrier = K.carrier ↔ H = K :=
⟨ext', λ h, h ▸ rfl⟩
attribute [ext] subgroup.ext
/-- A subgroup contains the group's 1. -/
theorem one_mem : (1 : G) ∈ H := H.one_mem'
/-- A subgroup is closed under multiplication. -/
theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := subgroup.mul_mem' _
/-- A subgroup is closed under inverse -/
theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := subgroup.inv_mem' _
/-- A subgroup is closed under integer powers -/
theorem pow_mem {x : G} {n : ℤ} : x ∈ H → x ^ n ∈ H :=
begin
intro hx,
apply int.induction_on n,
{ rw group.pow_zero, exact H.one_mem },
{ intros i hi,
convert H.mul_mem hi hx,
rw [group.pow_add, group.pow_one] },
{ intros i hi,
convert H.mul_mem hi (H.inv_mem hx),
rw [← group.pow_neg_one_inv, ← group.pow_add ], congr' }
end
@[simp] theorem inv_mem_iff {x :G} : x⁻¹ ∈ H ↔ x ∈ H :=
⟨ λ hx, group.inv_inv x ▸ H.inv_mem hx, H.inv_mem ⟩
-- Coersion to group
-- Coercion from subgroup to underlying type
instance : has_coe (subgroup G) (set G) := ⟨subgroup.carrier⟩
lemma mem_coe' {g : G} : g ∈ (H : set G) ↔ g ∈ H := iff.rfl
instance of_subgroup (K : subgroup G) : group ↥K :=
{ mul := λ a b, ⟨a.1 * b.1, K.mul_mem' a.2 b.2⟩,
one := ⟨1, K.one_mem'⟩,
inv := λ a, ⟨a⁻¹, K.inv_mem' a.2⟩,
mul_assoc := λ a b c, by { cases a, cases b, cases c, refine subtype.ext _,
apply group.mul_assoc },
one_mul := λ a, by { cases a, apply subtype.ext, apply group.one_mul },
mul_left_inv := λ a, by { cases a, apply subtype.ext,
apply group.mul_left_inv } }
/-- Returns index of a subgroup in a group -/
noncomputable def index (H : subgroup G) : ℕ := fincard G / fincard H
/-- `index' H J` returns the index of J in H -/
noncomputable def index'(H : subgroup G) (J : subgroup G): ℕ := fincard H / fincard J
-- Defining cosets thats used in some lemmas
def lcoset (g : G) (K : subgroup G) := {s : G | ∃ k ∈ K, s = g * k}
def rcoset (g : G) (K : subgroup G) := {s : G | ∃ k ∈ K, s = k * g}
notation g ` ⋆ ` :70 H :70 := lcoset g H
notation H ` ⋆ ` :70 g :70 := rcoset g H
attribute [reducible] lcoset rcoset
@[simp] lemma coe_mul (a b : G) (ha : a ∈ H) (hb : b ∈ H) :
((⟨a, ha⟩ * ⟨b, hb⟩ : H) : G) = a * b := rfl
end subgroup
namespace normal
variables {G : Type} [group G]
instance : has_coe (normal G) (subgroup G) :=
⟨λ K, K.to_subgroup⟩
-- This saves me from writting m ∈ (K : subgroup G) every time
instance : has_mem G (normal G) := ⟨λ m K, m ∈ K.carrier⟩
instance to_set : has_coe (normal G) (set G) := ⟨λ K, K.carrier⟩
@[simp] lemma mem_to_subgroup {K : normal G} (x : G) :
x ∈ K.to_subgroup ↔ x ∈ K := iff.rfl
@[simp] lemma mem_carrier {K : normal G} (x : G) :
x ∈ K.carrier ↔ x ∈ K := iff.rfl
lemma conj_mem (N : normal G) (n : G) (hn : n ∈ N) (g : G) :
g * n * g⁻¹ ∈ N := N.conj_mem' n hn g
@[ext] lemma ext (A B : normal G) (h : ∀ g, g ∈ A ↔ g ∈ B) : A = B :=
begin
cases A with A, cases B with B, cases A with A, cases B with B,
suffices : A = B,
simp * at *,
ext x, exact h x
end
theorem ext' {H K : normal G} (h : H.to_subgroup = K.to_subgroup) : H = K :=
by cases H; cases K; congr'
instance of_normal (N : normal G) : group ↥N :=
subgroup.of_subgroup (N : subgroup G)
def of_subgroup (H : subgroup G)
(hH : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) : normal G :=
{ conj_mem' := hH, .. H }
def of_comm_subgroup {G : Type} [comm_group G] (H : subgroup G) :
normal G :=
{ conj_mem' := λ _ _ _, by simpa [group.mul_comm, group.mul_assoc], .. H}
end normal
/-
An API for subgroups
Mathematician-friendly
Let G be a group. The type of subgroups of G is `subgroup G`.
In other words, if `H : subgroup G` then H is a subgroup of G.
The three basic facts you need to know about H are:
H.one_mem : (1 : G) ∈ H
H.mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H
H.inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H
-/
variables {G : Type} [group G]
namespace lagrange
variables {H : subgroup G}
lemma self_mem_coset (a : G) (H : subgroup G): a ∈ a ⋆ H :=
⟨1, H.one_mem, (group.mul_one a).symm⟩
/-- Two cosets `a ⋆ H`, `b ⋆ H` are equal if and only if `b⁻¹ * a ∈ H` -/
theorem lcoset_eq {a b : G} :
a ⋆ H = b ⋆ H ↔ b⁻¹ * a ∈ H :=
begin
split; intro h,
{ replace h : a ∈ b ⋆ H, rw ←h, exact self_mem_coset a H,
rcases h with ⟨g, hg₀, hg₁⟩,
rw hg₁, simp [←group.mul_assoc, hg₀] },
{ ext, split; intro hx,
{ rcases hx with ⟨g, hg₀, hg₁⟩, rw hg₁,
exact ⟨b⁻¹ * a * g, H.mul_mem h hg₀, by simp [←group.mul_assoc]⟩ },
{ rcases hx with ⟨g, hg₀, hg₁⟩, rw hg₁,
refine ⟨a⁻¹ * b * g, H.mul_mem _ hg₀, by simp [←group.mul_assoc]⟩,
convert H.inv_mem h, simp } }
end
-- A corollary of this is a ⋆ H = H iff a ∈ H
/-- The coset of `H`, `1 ⋆ H` equals `H` -/
theorem lcoset_of_one : 1 ⋆ H = H :=
begin
ext, split; intro hx,
{ rcases hx with ⟨h, hh₀, hh₁⟩,
rwa [hh₁, group.one_mul] },
{ exact ⟨x, hx, (group.one_mul x).symm⟩ }
end
/-- A left coset `a ⋆ H` equals `H` if and only if `a ∈ H` -/
theorem lcoset_of_mem {a : G} :
a ⋆ H = H ↔ a ∈ H := by rw [←lcoset_of_one, lcoset_eq]; simp
/-- Two left cosets `a ⋆ H` and `b ⋆ H` are equal if they are not disjoint -/
theorem lcoset_digj {a b c : G} (ha : c ∈ a ⋆ H) (hb : c ∈ b ⋆ H) :
a ⋆ H = b ⋆ H :=
begin
rcases ha with ⟨g₀, hg₀, hca⟩,
rcases hb with ⟨g₁, hg₁, hcb⟩,
rw lcoset_eq, rw (show a = c * g₀⁻¹, by simp [hca, group.mul_assoc]),
rw (show b⁻¹ = g₁ * c⁻¹,
by rw (show b = c * g₁⁻¹, by simp [hcb, group.mul_assoc]); simp),
suffices : g₁ * g₀⁻¹ ∈ H,
{ rw [group.mul_assoc, ←@group.mul_assoc _ _ c⁻¹],
simp [this] },
exact H.mul_mem hg₁ (H.inv_mem hg₀)
end
-- Now we would like to prove that all lcosets have the same order
open function
private def aux_map (a : G) (H : subgroup G) : H → a ⋆ H :=
λ h, ⟨a * h, h, h.2, rfl⟩
private lemma aux_map_biject {a : G} : bijective $ aux_map a H :=
begin
split,
{ intros x y hxy,
suffices : (x : G) = y,
{ ext, assumption },
{ simp [aux_map] at hxy, assumption } },
{ rintro ⟨y, y_prop⟩,
rcases y_prop with ⟨h, hh₀, hh₁⟩,
refine ⟨⟨h, hh₀⟩, by simp [aux_map, hh₁]⟩ }
end
/-- There is a bijection between `H` and its left cosets -/
noncomputable theorem lcoset_equiv {a : G} : H ≃ a ⋆ H :=
equiv.of_bijective (aux_map a H) aux_map_biject
-- We are going to use fincard which maps a fintype to its fintype.card
-- and maps to 0 otherwise
/-- The cardinality of `H` equals its left cosets-/
lemma eq_card_of_lcoset {a : G} : fincard H = fincard (a ⋆ H) :=
fincard.of_equiv lcoset_equiv
/-- The cardinality of all left cosets are equal -/
theorem card_of_lcoset_eq {a b : G} :
fincard (a ⋆ H) = fincard (b ⋆ H) := by iterate 2 { rw ←eq_card_of_lcoset }
-- The rest of the proof will requires quotient
end lagrange
namespace normal
lemma mem_normal {x} {N : normal G} :
x ∈ N ↔ ∃ (g : G) (n ∈ N), x = g * n * g⁻¹ :=
begin
split; intro h,
{ exact ⟨1, x, h, by simp⟩ },
{ rcases h with ⟨g, n, hn, rfl⟩,
exact conj_mem _ _ hn _ }
end
lemma mem_normal' {x} {N : normal G} :
x ∈ N ↔ ∃ (g : G) (n ∈ N), x = g⁻¹ * n * g :=
begin
rw mem_normal,
split; rintro ⟨g, n, hn, rfl⟩;
{ exact ⟨g⁻¹, n, hn, by simp⟩ }
end
-- Any two elements commute regarding the normal subgroup membership relation
lemma comm_mem_of_normal {K : normal G}
{g k : G} (h : g * k ∈ K) : k * g ∈ K :=
begin
suffices : k * (g * k) * k⁻¹ ∈ K,
{ simp [group.mul_assoc] at this, assumption },
refine normal.conj_mem _ _ h _
end
def normal_of_mem_comm {K : subgroup G}
(h : ∀ g k : G, g * k ∈ K → k * g ∈ K) : normal G :=
{ conj_mem' :=
begin
intros n hn g,
suffices : g * (n * g⁻¹) ∈ K,
{ rwa ←group.mul_assoc at this },
refine h _ _ _, simpa [group.mul_assoc]
end, .. K } -- The .. tells Lean that we use K for the unfilled fields
-- If K is a normal subgroup of the group G, then the sets of left and right
-- cosets of K in the G coincide
lemma nomal_coset_eq {K : normal G} :
∀ g : G, g ⋆ (K : subgroup G) = (K : subgroup G) ⋆ g :=
begin
-- dsimp,
-- Without the dsimp it displays weridly,
-- dsimp not required if we write out right_coset g K however?
intros g,
ext, split; intro hx,
{ rcases hx with ⟨k, hk, rfl⟩,
refine ⟨_, K.2 k hk g, _⟩,
simp [group.mul_assoc] },
{ rcases hx with ⟨k, hk, rfl⟩,
refine ⟨_, K.2 k hk g⁻¹, _⟩,
simp [←group.mul_assoc] }
end
def normal_of_coset_eq {K : subgroup G}
(h : ∀ g : G, g ⋆ K = K ⋆ g) : normal G :=
{ conj_mem' :=
begin
intros n hn g,
have : ∃ s ∈ K ⋆ g, s = g * n,
{ refine ⟨g * n, _, rfl⟩,
rw ←h, exact ⟨n, hn, rfl⟩ },
rcases this with ⟨s, ⟨l, hl₁, hl₂⟩, hs₂⟩,
rw [←hs₂, hl₂],
simpa [group.mul_assoc]
end, .. K}
-- If K is normal then if x ∈ g K and y ∈ h K then x * y ∈ (g * h) K
lemma prod_in_coset_of_normal {K : normal G} {x y g h : G}
(hx : x ∈ g ⋆ K) (hy : y ∈ h ⋆ K) : x * y ∈ (g * h) ⋆ K :=
begin
rcases hx with ⟨k₀, hx₁, rfl⟩,
rcases hy with ⟨k₁, hy₁, rfl⟩,
refine ⟨h⁻¹ * k₀ * h * k₁, _, _⟩,
{ refine K.1.3 _ hy₁,
convert K.2 _ hx₁ _, exact (group.inv_inv _).symm },
{ iterate 2 { rw group.mul_assoc },
rw group.mul_left_cancel_iff g _ _,
simp [←group.mul_assoc] }
end
def normal_of_prod_in_coset {K : subgroup G}
(h : ∀ x y g h : G, x ∈ g ⋆ K → y ∈ h ⋆ K → x * y ∈ (g * h) ⋆ K) : normal G :=
{ conj_mem' :=
begin
intros n hn g,
rcases h (g * n) (g⁻¹ * n) g g⁻¹
⟨n, hn, rfl⟩ ⟨n, hn, rfl⟩ with ⟨m, hm₀, hm₁⟩,
rw [←group.mul_right_cancel_iff n⁻¹,
group.mul_assoc, group.mul_assoc, group.mul_assoc] at hm₁,
suffices : g * n * g⁻¹ = m * n⁻¹,
rw this, exact K.mul_mem hm₀ (K.inv_mem hn),
simp [←group.mul_assoc] at hm₁; assumption
end, .. K }
end normal
end mygroup
|
On the half @-@ domed ceiling of the apse is a large oil @-@ painted mural depicting a scene in Heaven . In the center , God the Father and Jesus are enthroned on a cloud ; a stained @-@ glass skylight at the top of the dome depicting the Holy Spirit completes the Trinity . Flanking the Father and Son are the Virgin Mary and John the Baptist . Below the cloud is Satan in torment . At the left and right of the scene is an assemblage of 18 Catholic saints and 10 angels .
|
[STATEMENT]
lemma iso_imp_eqpoll_carrier: "G \<cong> H \<Longrightarrow> carrier G \<approx> carrier H"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. G \<cong> H \<Longrightarrow> carrier G \<approx> carrier H
[PROOF STEP]
by (auto simp: is_iso_def iso_def eqpoll_def) |
State Before: R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x : R
⊢ ↑(Ideal.span {x}) = spanSingleton S (↑(algebraMap R P) x) State After: case a
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x : R
y : P
⊢ y ∈ ↑(Ideal.span {x}) ↔ y ∈ spanSingleton S (↑(algebraMap R P) x) Tactic: ext y State Before: case a
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x : R
y : P
⊢ y ∈ ↑(Ideal.span {x}) ↔ y ∈ spanSingleton S (↑(algebraMap R P) x) State After: case a
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x : R
y : P
⊢ (∃ x', x' ∈ Ideal.span {x} ∧ ↑(algebraMap R P) x' = y) ↔ ∃ z, z • ↑(algebraMap R P) x = y Tactic: refine' (mem_coeIdeal S).trans (Iff.trans _ (mem_spanSingleton S).symm) State Before: case a
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x : R
y : P
⊢ (∃ x', x' ∈ Ideal.span {x} ∧ ↑(algebraMap R P) x' = y) ↔ ∃ z, z • ↑(algebraMap R P) x = y State After: case a.mp
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x : R
y : P
⊢ (∃ x', x' ∈ Ideal.span {x} ∧ ↑(algebraMap R P) x' = y) → ∃ z, z • ↑(algebraMap R P) x = y
case a.mpr
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x : R
y : P
⊢ (∃ z, z • ↑(algebraMap R P) x = y) → ∃ x', x' ∈ Ideal.span {x} ∧ ↑(algebraMap R P) x' = y Tactic: constructor State Before: case a.mp
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x : R
y : P
⊢ (∃ x', x' ∈ Ideal.span {x} ∧ ↑(algebraMap R P) x' = y) → ∃ z, z • ↑(algebraMap R P) x = y State After: case a.mp.intro.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x y' : R
hy' : y' ∈ Ideal.span {x}
⊢ ∃ z, z • ↑(algebraMap R P) x = ↑(algebraMap R P) y' Tactic: rintro ⟨y', hy', rfl⟩ State Before: case a.mp.intro.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x y' : R
hy' : y' ∈ Ideal.span {x}
⊢ ∃ z, z • ↑(algebraMap R P) x = ↑(algebraMap R P) y' State After: case a.mp.intro.intro.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x x' : R
hy' : x' • x ∈ Ideal.span {x}
⊢ ∃ z, z • ↑(algebraMap R P) x = ↑(algebraMap R P) (x' • x) Tactic: obtain ⟨x', rfl⟩ := Submodule.mem_span_singleton.mp hy' State Before: case a.mp.intro.intro.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x x' : R
hy' : x' • x ∈ Ideal.span {x}
⊢ ∃ z, z • ↑(algebraMap R P) x = ↑(algebraMap R P) (x' • x) State After: case a.mp.intro.intro.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x x' : R
hy' : x' • x ∈ Ideal.span {x}
⊢ x' • ↑(algebraMap R P) x = ↑(algebraMap R P) (x' • x) Tactic: use x' State Before: case a.mp.intro.intro.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x x' : R
hy' : x' • x ∈ Ideal.span {x}
⊢ x' • ↑(algebraMap R P) x = ↑(algebraMap R P) (x' • x) State After: no goals Tactic: rw [smul_eq_mul, RingHom.map_mul, Algebra.smul_def] State Before: case a.mpr
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x : R
y : P
⊢ (∃ z, z • ↑(algebraMap R P) x = y) → ∃ x', x' ∈ Ideal.span {x} ∧ ↑(algebraMap R P) x' = y State After: case a.mpr.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x y' : R
⊢ ∃ x', x' ∈ Ideal.span {x} ∧ ↑(algebraMap R P) x' = y' • ↑(algebraMap R P) x Tactic: rintro ⟨y', rfl⟩ State Before: case a.mpr.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x y' : R
⊢ ∃ x', x' ∈ Ideal.span {x} ∧ ↑(algebraMap R P) x' = y' • ↑(algebraMap R P) x State After: case a.mpr.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x y' : R
⊢ ↑(algebraMap R P) (y' * x) = y' • ↑(algebraMap R P) x Tactic: refine' ⟨y' * x, Submodule.mem_span_singleton.mpr ⟨y', rfl⟩, _⟩ State Before: case a.mpr.intro
R : Type u_2
inst✝⁶ : CommRing R
S : Submonoid R
P : Type u_1
inst✝⁵ : CommRing P
inst✝⁴ : Algebra R P
loc : IsLocalization S P
R₁ : Type ?u.1339818
inst✝³ : CommRing R₁
K : Type ?u.1339824
inst✝² : Field K
inst✝¹ : Algebra R₁ K
inst✝ : IsFractionRing R₁ K
x y' : R
⊢ ↑(algebraMap R P) (y' * x) = y' • ↑(algebraMap R P) x State After: no goals Tactic: rw [RingHom.map_mul, Algebra.smul_def] |
State Before: E : Type ?u.10318
inst✝¹ : NormedAddCommGroup E
inst✝ : NormedSpace ℂ E
z w : ℂ
⊢ dist z w = Real.sqrt ((z.re - w.re) ^ 2 + (z.im - w.im) ^ 2) State After: E : Type ?u.10318
inst✝¹ : NormedAddCommGroup E
inst✝ : NormedSpace ℂ E
z w : ℂ
⊢ dist z w = Real.sqrt ((z.re - w.re) * (z.re - w.re) + (z.im - w.im) * (z.im - w.im)) Tactic: rw [sq, sq] State Before: E : Type ?u.10318
inst✝¹ : NormedAddCommGroup E
inst✝ : NormedSpace ℂ E
z w : ℂ
⊢ dist z w = Real.sqrt ((z.re - w.re) * (z.re - w.re) + (z.im - w.im) * (z.im - w.im)) State After: no goals Tactic: rfl |
-- @@stderr --
dtrace: failed to compile script test/unittest/actions/trace/err.D_TRACE_DYN.d: [D_TRACE_DYN] line 19: trace( ) may not be applied to a dynamic expression
|
(* This program is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU Lesser General Public License *)
(* as published by the Free Software Foundation; either version 2.1 *)
(* 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 Lesser General Public *)
(* License along with this program; if not, write to the Free *)
(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)
(* 02110-1301 USA *)
(* Contribution to the Coq Library V6.3 (July 1999) *)
(* A development written by Pierre Castéran for Coq V6.1
Coq : A product of inria : "http://pauillac.inria.fr/coq/coq-eng.html"
Pierre Castéran : A product of LaBRI :
LaBRI, Universite Bordeaux-I | 12 place Puy Paulin
351 Cours de la Liberation | 33000 Bordeaux
F-33405 TALENCE Cedex | France
France | (+ 33) 5 56 81 15 80
tel : (+ 33) 5 56 84 69 31
fax : (+ 33) 5 56 84 66 69
email: [email protected]
www: http://dept-info.labri.u-bordeaux.fr/~casteran
"Les rêves sont aussi beaux que la réalité, mais ils ne sont pas mieux".
( J.L.Borges )
*)
(* VI Deletion.
******************
*******************
Deleting an element from a binary search tree is a little more
complex than inserting or searching.
The difficult case is the deletion of the root of a tree; we have
to reconstruct a search tree. To solve this problem, we define
an auxiliary operation: deleting the greatest element of a non-empty
binary search tree.
*)
(* VI.2 Deletion in general
****************************
We are now ready to study the remove operation in it's generality:
(RM n t t') if t' is a search tree obtained by removing n from t *)
Require Import nat_trees.
Require Import search_trees.
Require Import DeleteMax.
Require Import Arith.
Require Import Compare_dec.
Inductive RM (n : nat) (t t' : nat_tree) : Prop :=
rm_intro :
~ occ t' n ->
(forall p : nat, occ t' p -> occ t p) ->
(forall p : nat, occ t p -> occ t' p \/ n = p) ->
search t' -> RM n t t'.
Hint Resolve rm_intro: searchtrees.
(* base cases *)
Remark RM_0 : forall n : nat, RM n NIL NIL.
(*********************************)
Proof.
intro n; apply rm_intro; auto with searchtrees arith.
Defined.
Hint Resolve RM_0: searchtrees.
Remark RM_1 : forall n : nat, RM n (bin n NIL NIL) NIL.
(*********************************************)
Proof.
intros; apply rm_intro; auto with searchtrees arith.
intros p H; elim (occ_inv n _ _ _ H); auto with searchtrees arith.
tauto.
Defined.
Hint Resolve RM_1: searchtrees.
(* deleting in the left son *)
Remark rm_left :
forall (n p : nat) (t1 t2 t' : nat_tree),
p < n ->
search (bin n t1 t2) -> RM p t1 t' -> RM p (bin n t1 t2) (bin n t' t2).
(*************************************************)
Proof.
intros n p t1 t2 t' H H0 H1.
apply rm_intro. unfold not in |- *; intro H2.
elim (occ_inv n p t' t2).
intro eg; absurd (p < p); auto with searchtrees arith.
pattern p at 2 in |- *; elim eg; auto with searchtrees arith.
intro D; elim D; intro H3.
elim H1; auto with searchtrees arith.
absurd (occ t2 p); auto with searchtrees arith.
apply not_right with n t1; auto with searchtrees arith.
auto with searchtrees arith.
intros p0 H2.
elim (occ_inv n p0 t' t2).
simple induction 1; auto with searchtrees arith.
simple induction 1; auto with searchtrees arith.
intro; elim H1; auto with searchtrees arith.
auto with searchtrees arith.
intros.
elim (occ_inv n p0 t1 t2).
simple induction 1; auto with searchtrees arith.
simple induction 1; intro H4.
elim H1.
intros H5 H6 H7 H8.
elim (H7 p0 H4); auto with searchtrees arith.
auto with searchtrees arith.
auto with searchtrees arith.
apply bin_search.
elim H1; auto with searchtrees arith.
apply search_r with n t1; auto with searchtrees arith.
apply maj_intro; intros q H2.
cut (occ t1 q).
intro; elim (maj_l n t1 t2 H0); intros; auto with searchtrees arith.
auto with searchtrees arith.
elim H1; auto with searchtrees arith.
apply min_r with t1; auto with searchtrees arith.
Defined.
Hint Resolve rm_left: searchtrees.
(* deleting in the right son *)
Remark rm_right :
forall (n p : nat) (t1 t2 t' : nat_tree),
n < p ->
search (bin n t1 t2) -> RM p t2 t' -> RM p (bin n t1 t2) (bin n t1 t').
(**************************************************)
Proof.
intros n p t1 t2 t' H H0 H1.
apply rm_intro.
unfold not in |- *; intro H2.
elim (occ_inv n p t1 t').
intro eg; absurd (p < p); auto with searchtrees arith.
pattern p at 1 in |- *; elim eg; auto with searchtrees arith.
intro D; elim D; intro H3.
elim H1; auto with searchtrees arith.
absurd (occ t1 p).
apply not_left with n t2; auto with searchtrees arith.
auto with searchtrees arith.
elim H1; auto with searchtrees arith.
auto with searchtrees arith.
intros p0 H2.
elim (occ_inv n p0 t1 t').
simple induction 1; auto with searchtrees arith.
simple induction 1; auto with searchtrees arith.
intro; elim H1; auto with searchtrees arith.
auto with searchtrees arith.
intros.
elim (occ_inv n p0 t1 t2).
simple induction 1; auto with searchtrees arith.
simple induction 1; auto with searchtrees arith.
intro H4.
elim H1; intros H5 H6 H7 H8.
elim (H7 p0 H4); auto with searchtrees arith.
auto with searchtrees arith.
apply bin_search.
apply search_l with n t2; auto with searchtrees arith.
elim H1; auto with searchtrees arith.
apply maj_l with t2; auto with searchtrees arith.
apply min_intro; intros q H2.
cut (occ t2 q).
intro.
elim (min_r n t1 t2 H0); auto with searchtrees arith.
elim H1; auto with searchtrees arith.
Defined.
Hint Resolve rm_right: searchtrees.
(* base case for deleting the root *)
Remark rm_NILt :
forall (n : nat) (t : nat_tree),
search (bin n NIL t) -> RM n (bin n NIL t) t.
(*******************************************************)
Proof.
intros; apply rm_intro.
apply not_right with n NIL; auto with searchtrees arith.
auto with searchtrees arith.
intros p H1; elim (occ_inv n p NIL t H1); intro H2.
right; auto with searchtrees arith.
elim H2; intro.
absurd (occ NIL p); auto with searchtrees arith.
left; auto with searchtrees arith.
apply search_r with n NIL; auto with searchtrees arith.
Defined.
Hint Resolve rm_NILt: searchtrees.
(* General case: we use the RMAX predicate *)
Section rm_root.
Variable n p : nat.
Variable t1 t2 t' : nat_tree.
Hypothesis S : search (bin n (bin p t1 t2) t').
Variable q : nat.
Variable t0 : nat_tree.
Hypothesis R : RMAX (bin p t1 t2) t0 q.
Hint Resolve S: searchtrees.
Remark rm_2 : q < n.
(********************)
Proof.
elim R.
intros.
elim (maj_l n (bin p t1 t2) t').
auto with searchtrees arith.
auto with searchtrees arith.
Qed.
Hint Resolve rm_2: searchtrees.
Remark rm_3 : ~ occ (bin q t0 t') n.
(**********************************)
Proof.
unfold not in |- *; intro H.
elim (occ_inv q n t0 t').
intro eg; absurd (q < q); auto with searchtrees arith.
pattern q at 2 in |- *; rewrite eg; auto with searchtrees arith.
intro D; elim D; intro H'.
elim R; intros H0 H1 H2 H3 H4 H5.
absurd (occ (bin p t1 t2) n); auto with searchtrees arith.
apply not_left with n t'; auto with searchtrees arith.
absurd (occ t' n); auto with searchtrees arith.
apply not_right with n (bin p t1 t2); auto with searchtrees arith.
auto with searchtrees arith.
Qed.
Hint Resolve rm_3: searchtrees.
Remark rm_4 :
forall p0 : nat,
occ (bin q t0 t') p0 -> occ (bin n (bin p t1 t2) t') p0.
(***************************************************************)
Proof.
intros p0 H.
elim (occ_inv q p0 t0 t' H).
intro eg.
elim R; rewrite eg; auto with searchtrees arith.
simple induction 1; auto with searchtrees arith.
intro H'. elim R; auto with searchtrees arith.
Qed.
Hint Resolve rm_4: searchtrees.
Remark rm_5 :
forall p0 : nat,
occ (bin n (bin p t1 t2) t') p0 -> occ (bin q t0 t') p0 \/ n = p0.
(********************************************)
Proof.
intros p0 H.
elim (occ_inv n p0 (bin p t1 t2) t').
simple induction 1; auto with searchtrees arith.
simple induction 1.
intro H1.
elim R; intros H2 H3 H4 H5 H6 H7.
elim (H5 p0 H1). intro; left; auto with searchtrees arith.
simple induction 1; left; auto with searchtrees arith.
intro; left; auto with searchtrees arith.
auto with searchtrees arith.
Qed.
Hint Resolve rm_5: searchtrees.
Remark rm_6 : search (bin q t0 t').
(**********************************)
Proof.
apply bin_search.
elim R; auto with searchtrees arith.
apply search_r with n (bin p t1 t2); auto with searchtrees arith.
elim R; intros H H0 H1 H2 H3 H4.
apply maj_intro.
intros q0 H5; elim (le_lt_or_eq q0 q (H0 q0 (H1 q0 H5))).
auto with searchtrees arith.
intro eg; absurd (occ t0 q0).
rewrite eg; auto with searchtrees arith.
auto with searchtrees arith.
apply min_intro.
intros q0 H.
apply lt_trans with n.
elim R; auto with searchtrees arith.
elim (min_r n (bin p t1 t2) t').
auto with searchtrees arith.
auto with searchtrees arith.
Qed.
Hint Resolve rm_6: searchtrees.
Lemma rm_root_lemma : RM n (bin n (bin p t1 t2) t') (bin q t0 t').
(********************************************************************)
Proof.
apply rm_intro; auto with searchtrees arith.
Qed.
End rm_root.
(* The final algorithm *)
Theorem rm :
forall (n : nat) (t : nat_tree), search t -> {t' : nat_tree | RM n t t'}.
(*********************************************)
Proof.
simple induction t;
[ intros s; exists NIL
| intros p; elim (le_gt_dec n p); intros h;
[ elim (le_lt_eq_dec n p h); intros h';
[ intros t1 hr1 t2 hr2 s; elim hr1;
[ intros t3 h3; exists (bin p t3 t2) | idtac ]
| intros t1; case t1;
[ intros hr1 t2 hr2 s; exists t2
| intros p' t1' t2' hr1 t2 hr2 s; elim (rmax (bin p' t1' t2'));
[ intros q ex; elim ex; intros t' H; exists (bin q t' t2)
| idtac
| idtac ] ] ]
| intros t1 hr1 t2 hr2 s; elim hr2;
[ intros t3 h3; exists (bin p t1 t3) | idtac ] ] ];
auto with searchtrees arith.
(*
Realizer Fix rm{rm/2 : nat -> nat_tree -> nat_tree :=
[n:nat][t:nat_tree]
<nat_tree> Cases t of
NIL => NIL
| (bin p t1 t2) =>
<nat_tree> if (le_gt_dec n p)
then <nat_tree> if (le_lt_eq_dec n p)
then (bin p (rm n t1) t2)
else (<nat_tree> Cases t1 of
NIL => t2
| _ =>
<nat_tree>let (q,t')= (rmax t1)
in (bin q t' t2)
end)
else (bin p t1 (rm n t2))
end }.
Program_all.
*)
eapply search_l; eauto with searchtrees arith.
rewrite h'; apply rm_NILt; auto with searchtrees arith.
rewrite h'; apply rm_root_lemma; auto with searchtrees arith.
eapply search_l; eauto with searchtrees arith.
eapply search_r; eauto with searchtrees arith.
Defined.
|
/* linalg/qr_ur.c
*
* Copyright (C) 2019, 2020 Patrick Alken
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
/*
* this module contains routines for the QR factorization of a matrix
* using the recursive Level 3 BLAS algorithm of Elmroth and Gustavson with
* additional modifications courtesy of Julien Langou.
*/
static double qrtr_householder_transform (double *v0, gsl_vector * v);
/*
gsl_linalg_QR_UR_decomp()
Compute the QR decomposition of the "triangle on top of rectangle" matrix
[ S ] = Q [ R ]
[ A ] [ 0 ]
where S is N-by-N upper triangular and A is M-by-N dense.
Inputs: S - on input, upper triangular N-by-N matrix
on output, R factor in upper triangle
A - on input, dense M-by-N matrix
on output, Householder matrix V
T - (output) block reflector matrix, N-by-N
Notes:
1) Based on the Elmroth/Gustavson algorithm, taking into account the
sparse structure of the S matrix
2) The Householder matrix V has the special form:
N
V = [ I ] N
[ V~ ] M
The matrix V~ is stored in A on output; the identity is not stored
3) The orthogonal matrix is
Q = I - V T V^T
*/
int
gsl_linalg_QR_UR_decomp (gsl_matrix * S, gsl_matrix * A, gsl_matrix * T)
{
const size_t M = A->size1;
const size_t N = S->size1;
if (N != S->size2)
{
GSL_ERROR ("S matrix must be square", GSL_ENOTSQR);
}
else if (N != A->size2)
{
GSL_ERROR ("S and A have different number of columns", GSL_EBADLEN);
}
else if (T->size1 != N || T->size2 != N)
{
GSL_ERROR ("T matrix has wrong dimensions", GSL_EBADLEN);
}
else if (N == 1)
{
/* base case, compute Householder transform for single column matrix */
double * T00 = gsl_matrix_ptr(T, 0, 0);
double * S00 = gsl_matrix_ptr(S, 0, 0);
gsl_vector_view v = gsl_matrix_column(A, 0);
*T00 = qrtr_householder_transform(S00, &v.vector);
return GSL_SUCCESS;
}
else
{
/*
* partition matrices:
*
* N1 N2 N1 N2
* N1 [ S11 S12 ] and N1 [ T11 T12 ]
* N2 [ 0 S22 ] N2 [ 0 T22 ]
* M [ A1 A2 ]
*/
int status;
const size_t N1 = N / 2;
const size_t N2 = N - N1;
gsl_matrix_view S11 = gsl_matrix_submatrix(S, 0, 0, N1, N1);
gsl_matrix_view S12 = gsl_matrix_submatrix(S, 0, N1, N1, N2);
gsl_matrix_view S22 = gsl_matrix_submatrix(S, N1, N1, N2, N2);
gsl_matrix_view A1 = gsl_matrix_submatrix(A, 0, 0, M, N1);
gsl_matrix_view A2 = gsl_matrix_submatrix(A, 0, N1, M, N2);
gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1);
gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2);
gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2);
/*
* Eq. 2: recursively factor
*
* N1 N1
* N1 [ S11 ] = Q1 [ R11 ] N1
* N2 [ 0 ] [ 0 ] N2
* M [ A1 ] [ 0 ] M
*/
status = gsl_linalg_QR_UR_decomp(&S11.matrix, &A1.matrix, &T11.matrix);
if (status)
return status;
/*
* Eq. 3:
*
* N2 N2 N2
* N1 [ R12 ] = Q1^T [ S12 ] = [ S12 - W ] N1
* N2 [ S22~ ] [ S22 ] [ S22 ] N2
* M [ A2~ ] [ A2 ] [ A2 - V1~ W ] M
*
* where W = T11^T ( S12 + V1~^T A2 ), using T12 as temporary storage, and
*
* N1
* V1 = [ I ] N1
* [ 0 ] N2
* [ V1~ ] M
*/
gsl_matrix_memcpy(&T12.matrix, &S12.matrix); /* W := S12 */
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 1.0, &T12.matrix); /* W := S12 + V1~^T A2 */
gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T W */
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A1.matrix, &T12.matrix, 1.0, &A2.matrix); /* A2 := A2 - V1~ W */
gsl_matrix_sub(&S12.matrix, &T12.matrix); /* R12 := S12 - W */
/*
* Eq. 4: recursively factor
*
* [ S22~ ] = Q2~ [ R22 ]
* [ A2~ ] [ 0 ]
*/
status = gsl_linalg_QR_UR_decomp(&S22.matrix, &A2.matrix, &T22.matrix);
if (status)
return status;
/*
* Eq. 13: update T12 := -T11 * V1^T * V2 * T22
*
* where:
*
* N1 N2
* V1 = [ I ] N1 V2 = [ 0 ] N1
* [ 0 ] N2 [ I ] N2
* [ V1~ ] M [ V2~ ] M
*
* Note: V1^T V2 = V1~^T V2~
*/
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 0.0, &T12.matrix); /* T12 := V1~^T * V2~ */
gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */
gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */
return GSL_SUCCESS;
}
}
/*
qrtr_householder_transform()
This routine is an optimized version of
gsl_linalg_householder_transform(), designed for the QR
decomposition of M-by-N matrices of the form:
B = [ S ]
[ A ]
where S is N-by-N upper triangular, and A is M-by-N dense.
This routine computes a householder transformation (tau,v) of a
x so that P x = [ I - tau*v*v' ] x annihilates x(1:n-1). x will
be a subcolumn of the matrix B, and so its structure will be:
x = [ x0 ] <- 1 nonzero value for the diagonal element of S
[ 0 ] <- N - j - 1 zeros, where j is column of matrix in [0,N-1]
[ x ] <- M nonzero values for the dense part A
Inputs: v0 - pointer to diagonal element of S
on input, v0 = x0;
v - on input, x vector
on output, householder vector v
*/
static double
qrtr_householder_transform (double *v0, gsl_vector * v)
{
/* replace v[0:M-1] with a householder vector (v[0:M-1]) and
coefficient tau that annihilate v[1:M-1] */
double alpha, beta, tau ;
/* compute xnorm = || [ 0 ; v ] ||, ignoring zero part of vector */
double xnorm = gsl_blas_dnrm2(v);
if (xnorm == 0)
{
return 0.0; /* tau = 0 */
}
alpha = *v0;
beta = - GSL_SIGN(alpha) * hypot(alpha, xnorm) ;
tau = (beta - alpha) / beta ;
{
double s = (alpha - beta);
if (fabs(s) > GSL_DBL_MIN)
{
gsl_blas_dscal (1.0 / s, v);
*v0 = beta;
}
else
{
gsl_blas_dscal (GSL_DBL_EPSILON / s, v);
gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, v);
*v0 = beta;
}
}
return tau;
}
|
module Minecraft.Core.Tangible.Export
import public Minecraft.Core.Tangible
%default total
|
{-# OPTIONS --without-K --exact-split --safe #-}
open import Fragment.Algebra.Signature
module Fragment.Algebra.Free (Σ : Signature) where
open import Fragment.Algebra.Free.Base Σ public
open import Fragment.Algebra.Free.Properties Σ public
open import Fragment.Algebra.Free.Monad Σ public
open import Fragment.Algebra.Free.Evaluation Σ public
|
function slwritearray(A, filename)
%SLWRITEARRAY Writes an array to an array file
%
% $ Syntax $
% - slwritearray(A, filename)
%
% $ Arguments $
% - A: The array to be written
% - filename: The filename of the array file
%
% $ Description $
% - slwritearray(A, filename) writes an array A to the array file.
%
% $ History $
% - Created by Dahua Lin, on Jul 26th, 2006
%
value_types = { ...
'double', ...
'single', ...
'logical', ...
'char', ...
'int8', ...
'uint8', ...
'int16', ...
'uint16', ...
'int32', ...
'uint32', ...
'int64', ...
'uint64'};
%% open file
fid = fopen(filename, 'w');
if fid <= 0
error('sltoolbox:filefail', ...
'Fail to open file %s', filename);
end
%% write header
% write tag
fwrite(fid, ['arr', 0], 'char');
% write value type and dimension number
[tf, typeidx] = ismember(class(A), value_types);
if ~tf
error('Unknown type for A: %s', class(A));
end
d = ndims(A);
info = uint8([typeidx, d, 0, 0]);
fwrite(fid, info, 'uint8');
%% write size
siz = size(A);
fwrite(fid, uint32(siz), 'uint32');
%% write data
fwrite(fid, A, class(A));
%% close file
fclose(fid);
|
/*!
@file
Defines `boost::hana::scan_left`.
@copyright Louis Dionne 2013-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_SCAN_LEFT_HPP
#define BOOST_HANA_SCAN_LEFT_HPP
#include <boost/hana/fwd/scan_left.hpp>
#include <boost/hana/at.hpp>
#include <boost/hana/concept/sequence.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/core/dispatch.hpp>
#include <boost/hana/core/make.hpp>
#include <boost/hana/empty.hpp>
#include <boost/hana/length.hpp>
#include <boost/hana/prepend.hpp>
#include <cstddef>
#include <utility>
BOOST_HANA_NAMESPACE_BEGIN
//! @cond
template <typename Xs, typename F>
constexpr auto scan_left_t::operator()(Xs&& xs, F const& f) const {
using S = typename hana::tag_of<Xs>::type;
using ScanLeft = BOOST_HANA_DISPATCH_IF(scan_left_impl<S>,
hana::Sequence<S>::value
);
#ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
static_assert(hana::Sequence<S>::value,
"hana::scan_left(xs, f) requires 'xs' to be a Sequence");
#endif
return ScanLeft::apply(static_cast<Xs&&>(xs), f);
}
template <typename Xs, typename State, typename F>
constexpr auto scan_left_t::operator()(Xs&& xs, State&& state, F const& f) const {
using S = typename hana::tag_of<Xs>::type;
using ScanLeft = BOOST_HANA_DISPATCH_IF(scan_left_impl<S>,
hana::Sequence<S>::value
);
#ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
static_assert(hana::Sequence<S>::value,
"hana::scan_left(xs, state, f) requires 'xs' to be a Sequence");
#endif
return ScanLeft::apply(static_cast<Xs&&>(xs),
static_cast<State&&>(state), f);
}
//! @endcond
template <typename S, bool condition>
struct scan_left_impl<S, when<condition>> : default_ {
// Without initial state
template <typename Xs, typename F, std::size_t n1, std::size_t n2, std::size_t ...ns>
static constexpr auto
apply1_impl(Xs&& xs, F const& f, std::index_sequence<n1, n2, ns...>) {
static_assert(n1 == 0, "logic error in Boost.Hana: file a bug report");
// Use scan_left with the first element as an initial state.
return scan_left_impl::apply_impl(
static_cast<Xs&&>(xs),
hana::at_c<0>(static_cast<Xs&&>(xs)),
f, std::index_sequence<n2, ns...>{}
);
}
template <typename Xs, typename F, std::size_t n>
static constexpr auto apply1_impl(Xs&& xs, F const&, std::index_sequence<n>) {
return hana::make<S>(hana::at_c<n>(static_cast<Xs&&>(xs)));
}
template <typename Xs, typename F>
static constexpr auto apply1_impl(Xs&&, F const&, std::index_sequence<>) {
return hana::empty<S>();
}
template <typename Xs, typename F>
static constexpr auto apply(Xs&& xs, F const& f) {
constexpr std::size_t Len = decltype(hana::length(xs))::value;
return scan_left_impl::apply1_impl(static_cast<Xs&&>(xs),
f, std::make_index_sequence<Len>{});
}
// With initial state
template <typename Xs, typename State, typename F,
std::size_t n1, std::size_t n2, std::size_t ...ns>
static constexpr auto
apply_impl(Xs&& xs, State&& state, F const& f,
std::index_sequence<n1, n2, ns...>)
{
auto rest = scan_left_impl::apply_impl(
static_cast<Xs&&>(xs),
f(state, hana::at_c<n1>(static_cast<Xs&&>(xs))),
f, std::index_sequence<n2, ns...>{});
return hana::prepend(std::move(rest), static_cast<State&&>(state));
}
template <typename Xs, typename State, typename F, std::size_t n>
static constexpr auto
apply_impl(Xs&& xs, State&& state, F const& f, std::index_sequence<n>) {
auto new_state = f(state, hana::at_c<n>(static_cast<Xs&&>(xs)));
return hana::make<S>(static_cast<State&&>(state), std::move(new_state));
}
template <typename Xs, typename State, typename F>
static constexpr auto
apply_impl(Xs&&, State&& state, F const&, std::index_sequence<>) {
return hana::make<S>(static_cast<State&&>(state));
}
template <typename Xs, typename State, typename F>
static constexpr auto apply(Xs&& xs, State&& state, F const& f) {
constexpr std::size_t Len = decltype(hana::length(xs))::value;
return scan_left_impl::apply_impl(static_cast<Xs&&>(xs),
static_cast<State&&>(state),
f, std::make_index_sequence<Len>{});
}
};
BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_SCAN_LEFT_HPP
|
(*<*)
(*
* The worker/wrapper transformation, following Gill and Hutton.
* (C)opyright 2009-2011, Peter Gammie, peteg42 at gmail.com.
* License: BSD
*)
theory Backtracking
imports
HOLCF
Nats
WorkerWrapperNew
begin
(*>*)
section\<open>Backtracking using lazy lists and continuations\<close>
text\<open>
\label{sec:ww-backtracking}
To illustrate the utility of worker/wrapper fusion to programming
language semantics, we consider here the first-order part of a
higher-order backtracking language by \citet{DBLP:conf/icfp/WandV04};
see also \citet{DBLP:journals/ngc/DanvyGR01}. We refer the reader to
these papers for a broader motivation for these languages.
As syntax is typically considered to be inductively generated, with
each syntactic object taken to be finite and completely defined, we
define the syntax for our language using a HOL datatype:
\<close>
datatype expr = const nat | add expr expr | disj expr expr | fail
(*<*)
lemma case_expr_cont[cont2cont]:
assumes f1: "\<And>y. cont (\<lambda>x. f1 x y)"
assumes f2: "\<And>y z. cont (\<lambda>x. f2 x y z)"
assumes f3: "\<And>y z. cont (\<lambda>x. f3 x y z)"
assumes f4: "cont (\<lambda>x. f4 x)"
shows "cont (\<lambda>x. case_expr (f1 x) (f2 x) (f3 x) (f4 x) expr)"
using assms by (cases expr) simp_all
(* Presumably obsolete in the HG version, not so in Isabelle2011. *)
fun
expr_encode :: "expr \<Rightarrow> nat"
where
"expr_encode (const n) = prod_encode (0, n)"
| "expr_encode (add e1 e2) = prod_encode (1, (prod_encode (expr_encode e1, expr_encode e2)))"
| "expr_encode (disj e1 e2) = prod_encode (2, (prod_encode (expr_encode e1, expr_encode e2)))"
| "expr_encode fail = prod_encode (3, 0)"
lemma expr_encode_inj:
"expr_encode x = expr_encode y \<Longrightarrow> x = y"
by (induct x arbitrary: y) ((case_tac y, auto dest!: inj_onD[OF inj_prod_encode, where A=UNIV])[1])+
instance expr :: countable
by (rule countable_classI[OF expr_encode_inj])
(*>*)
text\<open>
The language consists of constants, an addition function, a
disjunctive choice between expressions, and failure. We give it a
direct semantics using the monad of lazy lists of natural numbers,
with the goal of deriving an an extensionally-equivalent evaluator
that uses double-barrelled continuations.
Our theory of lazy lists is entirely standard.
\<close>
default_sort predomain
domain 'a llist =
lnil
| lcons (lazy "'a") (lazy "'a llist")
text\<open>
By relaxing the default sort of type variables to \<open>predomain\<close>,
our polymorphic definitions can be used at concrete types that do not
contain @{term "\<bottom>"}. These include those constructed from HOL types
using the discrete ordering type constructor @{typ "'a discr"}, and in
particular our interpretation @{typ "nat discr"} of the natural
numbers.
The following standard list functions underpin the monadic
infrastructure:
\<close>
fixrec lappend :: "'a llist \<rightarrow> 'a llist \<rightarrow> 'a llist" where
"lappend\<cdot>lnil\<cdot>ys = ys"
| "lappend\<cdot>(lcons\<cdot>x\<cdot>xs)\<cdot>ys = lcons\<cdot>x\<cdot>(lappend\<cdot>xs\<cdot>ys)"
fixrec lconcat :: "'a llist llist \<rightarrow> 'a llist" where
"lconcat\<cdot>lnil = lnil"
| "lconcat\<cdot>(lcons\<cdot>x\<cdot>xs) = lappend\<cdot>x\<cdot>(lconcat\<cdot>xs)"
fixrec lmap :: "('a \<rightarrow> 'b) \<rightarrow> 'a llist \<rightarrow> 'b llist" where
"lmap\<cdot>f\<cdot>lnil = lnil"
| "lmap\<cdot>f\<cdot>(lcons\<cdot>x\<cdot>xs) = lcons\<cdot>(f\<cdot>x)\<cdot>(lmap\<cdot>f\<cdot>xs)"
(*<*)
lemma lappend_strict'[simp]: "lappend\<cdot>\<bottom> = (\<Lambda> a. \<bottom>)"
by fixrec_simp
lemma lconcat_strict[simp]: "lconcat\<cdot>\<bottom> = \<bottom>"
by fixrec_simp
lemma lmap_strict[simp]: "lmap\<cdot>f\<cdot>\<bottom> = \<bottom>"
by fixrec_simp
(*>*)
text\<open>
We define the lazy list monad \<open>S\<close> in the traditional fashion:
\<close>
type_synonym S = "nat discr llist"
definition returnS :: "nat discr \<rightarrow> S" where
"returnS = (\<Lambda> x. lcons\<cdot>x\<cdot>lnil)"
definition bindS :: "S \<rightarrow> (nat discr \<rightarrow> S) \<rightarrow> S" where
"bindS = (\<Lambda> x g. lconcat\<cdot>(lmap\<cdot>g\<cdot>x))"
text\<open>
Unfortunately the lack of higher-order polymorphism in HOL prevents us
from providing the general typing one would expect a monad to have in
Haskell.
The evaluator uses the following extra constants:
\<close>
definition addS :: "S \<rightarrow> S \<rightarrow> S" where
"addS \<equiv> (\<Lambda> x y. bindS\<cdot>x\<cdot>(\<Lambda> xv. bindS\<cdot>y\<cdot>(\<Lambda> yv. returnS\<cdot>(xv + yv))))"
definition disjS :: "S \<rightarrow> S \<rightarrow> S" where
"disjS \<equiv> lappend"
definition failS :: "S" where
"failS \<equiv> lnil"
text\<open>
We interpret our language using these combinators in the obvious
way. The only complication is that, even though our evaluator is
primitive recursive, we must explicitly use the fixed point operator
as the worker/wrapper technique requires us to talk about the body of
the recursive definition.
\<close>
definition
evalS_body :: "(expr discr \<rightarrow> nat discr llist)
\<rightarrow> (expr discr \<rightarrow> nat discr llist)"
where
"evalS_body \<equiv> \<Lambda> r e. case undiscr e of
const n \<Rightarrow> returnS\<cdot>(Discr n)
| add e1 e2 \<Rightarrow> addS\<cdot>(r\<cdot>(Discr e1))\<cdot>(r\<cdot>(Discr e2))
| disj e1 e2 \<Rightarrow> disjS\<cdot>(r\<cdot>(Discr e1))\<cdot>(r\<cdot>(Discr e2))
| fail \<Rightarrow> failS"
abbreviation evalS :: "expr discr \<rightarrow> nat discr llist" where
"evalS \<equiv> fix\<cdot>evalS_body"
text\<open>
We aim to transform this evaluator into one using double-barrelled
continuations; one will serve as a "success" context, taking a natural
number into "the rest of the computation", and the other outright
failure.
In general we could work with an arbitrary observation type ala
\citet{DBLP:conf/icalp/Reynolds74}, but for convenience we use the
clearly adequate concrete type @{typ "nat discr llist"}.
\<close>
type_synonym Obs = "nat discr llist"
type_synonym Failure = "Obs"
type_synonym Success = "nat discr \<rightarrow> Failure \<rightarrow> Obs"
type_synonym K = "Success \<rightarrow> Failure \<rightarrow> Obs"
text\<open>
To ease our development we adopt what
\citet[\S5]{DBLP:conf/icfp/WandV04} call a "failure computation"
instead of a failure continuation, which would have the type @{typ
"unit \<rightarrow> Obs"}.
The monad over the continuation type @{typ "K"} is as follows:
\<close>
definition returnK :: "nat discr \<rightarrow> K" where
"returnK \<equiv> (\<Lambda> x. \<Lambda> s f. s\<cdot>x\<cdot>f)"
definition bindK :: "K \<rightarrow> (nat discr \<rightarrow> K) \<rightarrow> K" where
"bindK \<equiv> \<Lambda> x g. \<Lambda> s f. x\<cdot>(\<Lambda> xv f'. g\<cdot>xv\<cdot>s\<cdot>f')\<cdot>f"
text\<open>
Our extra constants are defined as follows:
\<close>
definition addK :: "K \<rightarrow> K \<rightarrow> K" where
"addK \<equiv> (\<Lambda> x y. bindK\<cdot>x\<cdot>(\<Lambda> xv. bindK\<cdot>y\<cdot>(\<Lambda> yv. returnK\<cdot>(xv + yv))))"
definition disjK :: "K \<rightarrow> K \<rightarrow> K" where
"disjK \<equiv> (\<Lambda> g h. \<Lambda> s f. g\<cdot>s\<cdot>(h\<cdot>s\<cdot>f))"
definition failK :: "K" where
"failK \<equiv> \<Lambda> s f. f"
text\<open>
The continuation semantics is again straightforward:
\<close>
definition
evalK_body :: "(expr discr \<rightarrow> K) \<rightarrow> (expr discr \<rightarrow> K)"
where
"evalK_body \<equiv> \<Lambda> r e. case undiscr e of
const n \<Rightarrow> returnK\<cdot>(Discr n)
| add e1 e2 \<Rightarrow> addK\<cdot>(r\<cdot>(Discr e1))\<cdot>(r\<cdot>(Discr e2))
| disj e1 e2 \<Rightarrow> disjK\<cdot>(r\<cdot>(Discr e1))\<cdot>(r\<cdot>(Discr e2))
| fail \<Rightarrow> failK"
abbreviation evalK :: "expr discr \<rightarrow> K" where
"evalK \<equiv> fix\<cdot>evalK_body"
text\<open>
We now set up a worker/wrapper relation between these two semantics.
The kernel of @{term "unwrap"} is the following function that converts
a lazy list into an equivalent continuation representation.
\<close>
fixrec SK :: "S \<rightarrow> K" where
"SK\<cdot>lnil = failK"
| "SK\<cdot>(lcons\<cdot>x\<cdot>xs) = (\<Lambda> s f. s\<cdot>x\<cdot>(SK\<cdot>xs\<cdot>s\<cdot>f))"
definition
unwrap :: "(expr discr \<rightarrow> nat discr llist) \<rightarrow> (expr discr \<rightarrow> K)"
where
"unwrap \<equiv> \<Lambda> r e. SK\<cdot>(r\<cdot>e)"
(*<*)
lemma SK_strict[simp]: "SK\<cdot>\<bottom> = \<bottom>"
by fixrec_simp
lemma unwrap_strict[simp]: "unwrap\<cdot>\<bottom> = \<bottom>"
unfolding unwrap_def by simp
(*>*)
text\<open>
Symmetrically @{term "wrap"} converts an evaluator using continuations
into one generating lazy lists by passing it the right continuations.
\<close>
definition KS :: "K \<rightarrow> S" where
"KS \<equiv> (\<Lambda> k. k\<cdot>lcons\<cdot>lnil)"
definition wrap :: "(expr discr \<rightarrow> K) \<rightarrow> (expr discr \<rightarrow> nat discr llist)" where
"wrap \<equiv> \<Lambda> r e. KS\<cdot>(r\<cdot>e)"
(*<*)
lemma KS_strict[simp]: "KS\<cdot>\<bottom> = \<bottom>"
unfolding KS_def by simp
lemma wrap_strict[simp]: "wrap\<cdot>\<bottom> = \<bottom>"
unfolding wrap_def by simp
(*>*)
text\<open>
The worker/wrapper condition follows directly from these definitions.
\<close>
lemma KS_SK_id:
"KS\<cdot>(SK\<cdot>xs) = xs"
by (induct xs) (simp_all add: KS_def failK_def)
lemma wrap_unwrap_id:
"wrap oo unwrap = ID"
unfolding wrap_def unwrap_def
by (simp add: KS_SK_id cfun_eq_iff)
text\<open>
The worker/wrapper transformation is only non-trivial if @{term
"wrap"} and @{term "unwrap"} do not witness an isomorphism. In this
case we can show that we do not even have a Galois connection.
\<close>
lemma cfun_not_below:
"f\<cdot>x \<notsqsubseteq> g\<cdot>x \<Longrightarrow> f \<notsqsubseteq> g"
by (auto simp: cfun_below_iff)
lemma unwrap_wrap_not_under_id:
"unwrap oo wrap \<notsqsubseteq> ID"
proof -
let ?witness = "\<Lambda> e. (\<Lambda> s f. lnil :: K)"
have "(unwrap oo wrap)\<cdot>?witness\<cdot>(Discr fail)\<cdot>\<bottom>\<cdot>(lcons\<cdot>0\<cdot>lnil)
\<notsqsubseteq> ?witness\<cdot>(Discr fail)\<cdot>\<bottom>\<cdot>(lcons\<cdot>0\<cdot>lnil)"
by (simp add: failK_def wrap_def unwrap_def KS_def)
hence "(unwrap oo wrap)\<cdot>?witness \<notsqsubseteq> ?witness"
by (fastforce intro!: cfun_not_below)
thus ?thesis by (simp add: cfun_not_below)
qed
text\<open>
We now apply \texttt{worker\_wrapper\_id}:
\<close>
definition eval_work :: "expr discr \<rightarrow> K" where
"eval_work \<equiv> fix\<cdot>(unwrap oo evalS_body oo wrap)"
definition eval_ww :: "expr discr \<rightarrow> nat discr llist" where
"eval_ww \<equiv> wrap\<cdot>eval_work"
lemma "evalS = eval_ww"
unfolding eval_ww_def eval_work_def
using worker_wrapper_id[OF wrap_unwrap_id]
by simp
text\<open>
We now show how the monadic operations correspond by showing that
@{term "SK"} witnesses a \emph{monad morphism}
\citep[\S6]{wadler92:_comprehending_monads}. As required by
\citet[Definition~2.1]{DBLP:journals/ngc/DanvyGR01}, the mapping needs
to hold for our specific operations in addition to the common monadic
scaffolding.
\<close>
lemma SK_returnS_returnK:
"SK\<cdot>(returnS\<cdot>x) = returnK\<cdot>x"
by (simp add: returnS_def returnK_def failK_def)
lemma SK_lappend_distrib:
"SK\<cdot>(lappend\<cdot>xs\<cdot>ys)\<cdot>s\<cdot>f = SK\<cdot>xs\<cdot>s\<cdot>(SK\<cdot>ys\<cdot>s\<cdot>f)"
by (induct xs) (simp_all add: failK_def)
lemma SK_bindS_bindK:
"SK\<cdot>(bindS\<cdot>x\<cdot>g) = bindK\<cdot>(SK\<cdot>x)\<cdot>(SK oo g)"
by (induct x)
(simp_all add: cfun_eq_iff
bindS_def bindK_def failK_def
SK_lappend_distrib)
lemma SK_addS_distrib:
"SK\<cdot>(addS\<cdot>x\<cdot>y) = addK\<cdot>(SK\<cdot>x)\<cdot>(SK\<cdot>y)"
by (clarsimp simp: cfcomp1
addS_def addK_def failK_def
SK_bindS_bindK SK_returnS_returnK)
lemma SK_disjS_disjK:
"SK\<cdot>(disjS\<cdot>xs\<cdot>ys) = disjK\<cdot>(SK\<cdot>xs)\<cdot>(SK\<cdot>ys)"
by (simp add: cfun_eq_iff disjS_def disjK_def SK_lappend_distrib)
lemma SK_failS_failK:
"SK\<cdot>failS = failK"
unfolding failS_def by simp
text\<open>
These lemmas directly establish the precondition for our all-in-one
worker/wrapper and fusion rule:
\<close>
lemma evalS_body_evalK_body:
"unwrap oo evalS_body oo wrap = evalK_body oo unwrap oo wrap"
proof(intro cfun_eqI)
fix r e' s f
obtain e :: "expr"
where ee': "e' = Discr e" by (cases e')
have "(unwrap oo evalS_body oo wrap)\<cdot>r\<cdot>(Discr e)\<cdot>s\<cdot>f
= (evalK_body oo unwrap oo wrap)\<cdot>r\<cdot>(Discr e)\<cdot>s\<cdot>f"
by (cases e)
(simp_all add: evalS_body_def evalK_body_def unwrap_def
SK_returnS_returnK SK_addS_distrib
SK_disjS_disjK SK_failS_failK)
with ee' show "(unwrap oo evalS_body oo wrap)\<cdot>r\<cdot>e'\<cdot>s\<cdot>f
= (evalK_body oo unwrap oo wrap)\<cdot>r\<cdot>e'\<cdot>s\<cdot>f"
by simp
qed
theorem evalS_evalK:
"evalS = wrap\<cdot>evalK"
using worker_wrapper_fusion_new[OF wrap_unwrap_id unwrap_strict]
evalS_body_evalK_body
by simp
text\<open>
This proof can be considered an instance of the approach of
\citet{DBLP:journals/jfp/HuttonJG10}, which uses the worker/wrapper
machinery to relate two algebras.
This result could be obtained by a structural induction over the
syntax of the language. However our goal here is to show how such a
transformation can be achieved by purely equational means; this has
the advantange that our proof can be locally extended, e.g. to the
full language of \citet{DBLP:journals/ngc/DanvyGR01} simply by proving
extra equations. In contrast the higher-order language of
\citet{DBLP:conf/icfp/WandV04} is beyond the reach of this approach.
\<close>
(*<*)
end
(*>*)
|
State Before: α : Type u_1
β : Type u_2
γ : Type ?u.176896
ι : Type ?u.176899
inst✝ : CompleteBooleanAlgebra α
f : Filter β
u : β → α
a : α
⊢ a \ liminf u f = limsup (fun b => a \ u b) f State After: α : Type u_1
β : Type u_2
γ : Type ?u.176896
ι : Type ?u.176899
inst✝ : CompleteBooleanAlgebra α
f : Filter β
u : β → α
a : α
⊢ (a \ liminf u f)ᶜ = limsup (fun b => a \ u b) fᶜ Tactic: rw [← compl_inj_iff] |
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
_SVCT_THRSHOLD := 2^13;
NewRulesFor(GT, rec(
# Vectorize AxI: A x I_n -> (A x I_n/v) x I_v
GT_Vec_AxI := rec(
forTransposition := false,
requiredFirstTag := [AVecReg, AVecRegCx],
applicable := t -> t.rank()=1 and t.params[2]=GTVec and t.params[3]=GTVec and
IsInt(t.params[4][1] / t.firstTag().v),
children := t -> let(
r := t.params[4][1] / t.firstTag().v,
isa := t.firstTag().isa,
spl := t.params[1], #.setWrap(VWrap(isa)),
tags := Drop(t.getTags(), 1),
[[ GT(spl, GTVec, GTVec, [r]).withTags(tags).setWrap(VWrap(isa)) ]]),
apply := (t, C, Nonterms) -> VTensor(C[1], t.firstTag().v),
),
GT_Vec_IxA := rec(
forTransposition := false,
requiredFirstTag := [AVecReg, AVecRegCx],
applicable := t -> t.rank()=1 and t.params[2]=GTPar and t.params[3]=GTPar and
IsInt(t.params[4][1] / t.firstTag().v),
children := t -> let(
tags := t.getTags(),
v := t.firstTag().v,
# r := t.params[4][1] / v,
spl := t.params[1],
[[ TL(Rows(spl)*v, v, 1, 1).withTags(tags).setWrap(VWrapId),
spl.withTags(Drop(tags, 1)).setWrap(VWrap(tags[1].isa)),
TL(Cols(spl)*v, Cols(spl), 1, 1).withTags(tags).setWrap(VWrapId)
]]),
apply := (t, C, Nonterms) ->
let(P := t.params, v := t.firstTag().v, r := P[4][1] / v,
A := C[1] * VTensor(C[2], v) * C[3], When(r=1, A, Tensor(I(r), A)))
),
# Push vector tag down to preserve locality: vec(I x A) -> (I x vec(A))
GT_Vec_IxA_Push := rec(
forTransposition := false,
requiredFirstTag := [AVecReg, AVecRegCx],
applicable := t -> t.rank()=1 and t.params[2]=GTPar and t.params[3]=GTPar,
children := t -> [[ t.params[1].withTags(t.getTags()) ]],
apply := (t, C, Nonterms) -> Tensor(I(t.params[4][1]), C[1])
),
# Split off L: vectorizes (I x A), (I x A) L, or L (I x A)
#
GT_Vec_SplitL := rec(
minSize := _SVCT_THRSHOLD,
forTransposition := false,
requiredFirstTag := [AVecReg, AVecRegCx],
applicable := (self, t) >> t.rank()=1 and Maximum(t.dims()) > self.minSize and
(t.params{[2,3]} in [[GTPar, GTPar], [GTVec, GTPar], [GTPar, GTVec]]),
children := t -> let(tags := t.getTags(), spl := t.params[1], n := t.params[4][1],
g := t.params[2], s := t.params[3],
[[ GT(spl, GTVec, GTVec, [n]).withTags(tags) ]]),
apply := (t, C, Nonterms) -> let(spl := t.params[1], n := t.params[4][1], g := t.params[2], s := t.params[3],
c := Concatenation(
When(s=GTPar, [ L(Rows(spl)*n, n) ], []),
[ C[1] ],
When(g=GTPar, [ L(Cols(spl)*n, Cols(spl)) ], [])), Product(c))
),
GT_Vec_IxA_L := rec(
maxSize := _SVCT_THRSHOLD,
forTransposition := false,
requiredFirstTag := [AVecReg, AVecRegCx],
applicable := (self, t) >> t.rank()=1
and t.params[2]=GTVec
and t.params[3]=GTPar
and Maximum(t.dims()) <= self.maxSize
and IsInt(t.params[4][1] / t.firstTag().v),
children := t -> let(tags := t.getTags(),
spl := t.params[1], v:=tags[1].v,
isa:=tags[1].isa, spl := t.params[1], d:=spl.dims(),
[[ TL(d[1]*v, v).withTags(tags).setWrap(VWrapId),
spl.withTags(Drop(tags,1)).setWrap(VWrap(isa)) ]]
),
apply := (t, C, Nonterms) -> let(spl := t.params[1],
d:=spl.dims(), n := t.params[4][1], tag := t.firstTag(),
v := tag.v, m := n / v,
NoDiagPullinLeft(When(m=1,
C[1] * VTensor(C[2], v),
Tensor(I(m), C[1] * VTensor(C[2], v)) * VTensor(L(m*d[2], m), v)
))
),
),
GT_Vec_L_IxA := rec(
maxSize := _SVCT_THRSHOLD,
forTransposition := false,
requiredFirstTag := [AVecReg, AVecRegCx],
applicable := (self, t) >> t.rank()=1 and t.params[2]=GTPar and t.params[3]=GTVec and Maximum(t.dims()) <= self.maxSize and
IsInt(t.params[4][1] / t.firstTag().v),
children := t -> let(tags := t.getTags(), spl := t.params[1], v:=tags[1].v,
isa:=tags[1].isa, spl := t.params[1], d:=spl.dims(),
[[ spl.withTags(Drop(tags,1)).setWrap(VWrap(isa)),
TL(d[2]*v, d[2]).withTags(tags).setWrap(VWrapId) ]] ),
apply := (t, C, Nonterms) -> let(spl := t.params[1], d:=spl.dims(), n := t.params[4][1], tag := t.firstTag(), v := tag.v, m := n / v,
NoDiagPullinRight(When(m=1, VTensor(C[1], v) * C[2], VTensor(L(m*d[2], d[2]), v) * Tensor(I(m), VTensor(C[1], v) * C[2]))))
)
));
|
Adweek: So what’s a digital-media tyro like you doing at a fusty old-media company like CBS?
Jim Lanzone: I don’t really think of it that way at all. People think the Internet will supercede TV, but it’s really been more additive than anything else, largely because it’s so portable. It’s not taking anything away from linear television; if anything, it’s encouraged people to spend even more time watching video.
AW: The fact that we can watch TV on a telephone: is this doing something insidious to the parts of our brain that process narrative?
JL: Think about the very early days of TV—the first shows were structured just like radio broadcasts or Broadway shows. You start with the familiar and you expand from there. Creative people haven’t taken advantage of the new media platforms; we’re still in this brackish time between two eras.
AW: You still watch TV?
JL: I’m a binge watcher. I have DirecTV, so I have a ton of shows on the DVR: The Daily Show, [Real Time With] Bill Maher, SNL. I’ve been watching How I Met Your Mother for six years. There are definitely more shows out there that I want to watch that I don’t have time to watch, which I suppose is a great sign of where programming is headed.
AW: Why did CBS issue a fatwa against Hulu?
AW: Can you write code?
JL: I never got into programming when I was a kid. I was too busy playing Pitfall and Kaboom! on Atari to write code. But then again, I don’t think Les Moonves knows how to make a television set either.
AW: So there’s no disconnect between the old media centers—New York, L.A.—and Silicon Valley?
JL: Well, you’re looking at it from a geographic standpoint and that really isn’t relevant any longer. I think Silicon Valley is the third leg of the media stool; I mean, there’s a reason why all the animated features are made in Silicon Valley now. Engineers are the new artists of this generation of media.
AW: Are you from Silicon Valley?
JL: I grew up in San Carlos, where Oracle now stands. In fact, they built Oracle on the old Marine World site. George Lucas used some of the elephants from Marine World in Star Wars, and after it came out—I must have seen it 25 times that summer—they started offering Bantha rides at Marine World.
AW: Speaking of which, what the hell happened to George Lucas? Those three Star Wars prequels were just god-awful.
JL: I know what happened to George Lucas: the ‘80s. If movies peaked in the ‘70s, then it’s fair to say that the 2000s is the Renaissance period for TV. The new Battlestar [Galactica] was at least a thousand times better than the old one. And I almost didn’t watch it at first because I was afraid it was going to ruin my childhood memories of the original. |
[STATEMENT]
lemma varInClauseVars:
fixes variable :: Variable and clause :: Clause
shows "variable \<in> vars clause = (\<exists> literal. literal el clause \<and> var literal = variable)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (variable \<in> vars clause) = (\<exists>literal. literal el clause \<and> var literal = variable)
[PROOF STEP]
by (induct clause) auto |
open import FRP.JS.Behaviour using ( Beh ; [_] ; hold )
open import FRP.JS.Event using ( tag )
open import FRP.JS.DOM using ( DOM ; text ; element ; listen ; click ; _++_ )
open import FRP.JS.RSet using ( ⟦_⟧ )
module FRP.JS.Demo.Button where
main : ∀ {w} → ⟦ Beh (DOM w) ⟧
main = text lab ++ but where
but = element "button" (text ["OK"])
lab = hold "Press me: " (tag "Pressed: " (listen click but))
|
C$Procedure KPLFRM ( Kernel pool frame IDs )
SUBROUTINE KPLFRM ( FRMCLS, IDSET )
C$ Abstract
C
C Return a SPICE set containing the frame IDs of all reference
C frames of a given class having specifications in the kernel pool.
C
C$ Disclaimer
C
C THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C CELLS
C FRAMES
C KERNEL
C NAIF_IDS
C SETS
C
C$ Keywords
C
C FRAME
C SET
C UTILITY
C
C$ Declarations
IMPLICIT NONE
INCLUDE 'frmtyp.inc'
INCLUDE 'ninert.inc'
INCLUDE 'nninrt.inc'
INTEGER LBCELL
PARAMETER ( LBCELL = -5 )
INTEGER FRMCLS
INTEGER IDSET ( LBCELL : * )
C$ Brief_I/O
C
C VARIABLE I/O DESCRIPTION
C -------- --- --------------------------------------------------
C FRMCLS I Frame class.
C IDSET O Set of ID codes of frames of the specified class.
C
C$ Detailed_Input
C
C FRMCLS is an integer code specifying the frame class or
C classes for which frame ID codes are requested.
C The applicable reference frames are those having
C specifications present in the kernel pool.
C
C FRMCLS may designate a single class or "all
C classes."
C
C The include file frmtyp.inc declares parameters
C identifying frame classes. The supported values
C and corresponding meanings of FRMCLS are
C
C Parameter Value Meaning
C ========= ===== =================
C ALL -1 All frame classes
C specified in the
C kernel pool. Class 1
C is not included.
C
C INERTL 1 Built-in inertial.
C No frames will be
C returned in the
C output set.
C
C PCK 2 PCK-based frame
C
C CK 3 CK-based frame
C
C TK 4 Fixed rotational
C offset ("text
C kernel") frame
C
C DYN 5 Dynamic frame
C
C$ Detailed_Output
C
C IDSET is a SPICE set containing the ID codes of all
C reference frames having specifications present in
C the kernel pool and belonging to the specified
C class or classes.
C
C Note that if FRMCLS is set to INERTL, IDSET
C will be empty on output.
C
C$ Parameters
C
C See the INCLUDE file frmtyp.inc.
C
C$ Exceptions
C
C 1) If the input frame class argument is not defined in
C frmtyp.inc, the error SPICE(BADFRAMECLASS) is signaled.
C
C 2) If the size of IDSET is too small to hold the requested frame
C ID set, the error SPICE(SETTOOSMALL) is signaled.
C
C 3) Frames of class 1 may not be specified in the kernel pool.
C However, for the convenience of users, this routine does not
C signal an error if the input class is set to INERTL. In this
C case the output set will be empty.
C
C 4) This routine relies on the presence of just three kernel
C variable assignments for a reference frame in order to
C determine that that reference frame has been specified:
C
C FRAME_<frame name> = <ID code>
C FRAME_<ID code>_NAME = <frame name>
C
C and either
C
C FRAME_<ID code>_CLASS = <class>
C
C or
C
C FRAME_<frame name>_CLASS = <class>
C
C It is possible for the presence of an incomplete frame
C specification to trick this routine into incorrectly
C deciding that a frame has been specified. This routine
C does not attempt to diagnose this problem.
C
C$ Files
C
C 1) Reference frame specifications for frames that are not
C built in are typically established by loading frame kernels.
C
C$ Particulars
C
C This routine enables SPICE-based applications to conveniently
C find the frame ID codes of reference frames having specifications
C present in the kernel pool. Such frame specifications are
C introduced into the kernel pool either by loading frame kernels
C or by means of calls to the kernel pool "put" API routines
C
C PCPOOL
C PDPOOL
C PIPOOL
C
C Given a reference frame's ID code, other attributes of the
C frame can be obtained via calls to entry points of the
C umbrella routine FRAMEX:
C
C FRMNAM {Return a frame's name}
C FRINFO {Return a frame's center, class, and class ID}
C
C This routine has a counterpart
C
C BLTFRM
C
C which fetches the frame IDs of all built-in reference frames.
C
C$ Examples
C
C 1) Display the IDs and names of all reference frames having
C specifications present in the kernel pool. Group the outputs
C by frame class. Also fetch and display the entire set of IDs
C and names using the parameter ALL.
C
C The meta-kernel used for this example is shown below. The
C Rosetta kernels referenced by the meta-kernel are available
C in the path
C
C pub/naif/ROSETTA/kernels/fk
C
C on the NAIF server. Older, but officially archived versions
C of these kernels are available in the path
C
C pub/naif/pds/data/ros-e_m_a_c-spice-6-v1.0/
C rossp_1000/DATA/FK
C
C The referenced PCK is available from the pck path under the
C generic_kernels path on the same server.
C
C
C KPL/MK
C
C \begindata
C
C KERNELS_TO_LOAD = ( 'pck00010.tpc'
C 'EARTHFIXEDITRF93.TF'
C 'ROS_LUTETIA_RSOC_V03.TF'
C 'ROS_V18.TF'
C 'RSSD0002.TF' )
C \begintext
C
C
C Program source code:
C
C
C PROGRAM EX1
C IMPLICIT NONE
C
C INCLUDE 'frmtyp.inc'
C C
C C SPICELIB functions
C C
C INTEGER CARDI
C C
C C Local parameters
C C
C CHARACTER*(*) META
C PARAMETER ( META = 'kplfrm.tm' )
C
C INTEGER NFRAME
C PARAMETER ( NFRAME = 1000 )
C
C INTEGER LBCELL
C PARAMETER ( LBCELL = -5 )
C
C INTEGER LNSIZE
C PARAMETER ( LNSIZE = 80 )
C
C INTEGER FRNMLN
C PARAMETER ( FRNMLN = 32 )
C
C C
C C Local variables
C C
C CHARACTER*(FRNMLN) FRNAME
C CHARACTER*(LNSIZE) OUTLIN
C
C INTEGER I
C INTEGER IDSET ( LBCELL : NFRAME )
C INTEGER J
C
C C
C C Initialize the frame set.
C C
C CALL SSIZEI ( NFRAME, IDSET )
C
C C
C C Load kernels that contain frame specifications.
C C
C CALL FURNSH ( META )
C
C C
C C Fetch and display the frames of each class.
C C
C DO I = 1, 6
C
C IF ( I .LT. 6 ) THEN
C C
C C Fetch the frames of class I.
C C
C CALL KPLFRM ( I, IDSET )
C
C OUTLIN = 'Number of frames of class #: #'
C CALL REPMI ( OUTLIN, '#', I, OUTLIN )
C CALL REPMI ( OUTLIN, '#', CARDI(IDSET), OUTLIN )
C
C ELSE
C C
C C Fetch IDs of all frames specified in the kernel
C C pool.
C C
C CALL KPLFRM ( ALL, IDSET )
C
C OUTLIN = 'Number of frames in the kernel pool: #'
C CALL REPMI ( OUTLIN, '#', CARDI(IDSET), OUTLIN )
C
C END IF
C
C CALL TOSTDO ( ' ' )
C CALL TOSTDO ( OUTLIN )
C CALL TOSTDO ( ' Frame IDs and names' )
C
C DO J = 1, CARDI(IDSET)
C CALL FRMNAM ( IDSET(J), FRNAME )
C WRITE (*,*) IDSET(J), ' ', FRNAME
C END DO
C
C END DO
C
C END
C
C
C The output from the program, when the program was linked
C against the N0064 SPICE Toolkit, is shown below. The output
C shown here has been abbreviated.
C
C
C Number of frames of class 1: 0
C Frame IDs and names
C
C Number of frames of class 2: 3
C Frame IDs and names
C 1000012 67P/C-G_FIXED
C 2000021 LUTETIA_FIXED
C 2002867 STEINS_FIXED
C
C Number of frames of class 3: 7
C Frame IDs and names
C -226570 ROS_RPC_BOOM2
C -226215 ROS_VIRTIS-M_SCAN
C -226072 ROS_HGA_AZ
C -226071 ROS_HGA_EL
C -226025 ROS_SA-Y
C -226015 ROS_SA+Y
C -226000 ROS_SPACECRAFT
C
C Number of frames of class 4: 64
C Frame IDs and names
C -2260021 ROS_LUTETIA
C -226999 ROSLND_LOCAL_LEVEL
C -226900 ROSLND_LANDER
C -226560 ROS_RPC_BOOM1
C
C ...
C
C -226030 ROS_MGA-S
C -226020 ROS_SA-Y_ZERO
C -226010 ROS_SA+Y_ZERO
C 1502010 HCI
C 1502301 LME2000
C 1503299 VME2000
C 1503499 MME2000
C
C Number of frames of class 5: 19
C Frame IDs and names
C -226967 2867/STEINS_CSO
C -226945 45P/H-M-P_CSO
C -226921 21/LUTETIA_CSO
C -226920 21/LUTETIA_CSEQ
C -226912 67P/C-G_CSO
C -226910 67P/C-G_CSEQ
C 1500010 HEE
C 1500299 VSO
C 1500301 LSE
C 1500399 GSE
C 1500499 MME
C 1501010 HEEQ
C 1501299 VME
C 1501301 LME
C 1501399 EME
C 1501499 MME_IAU2000
C 1502399 GSEQ
C 1502499 MSO
C 1503399 ECLIPDATE
C
C Number of frames in the kernel pool: 93
C Frame IDs and names
C -2260021 ROS_LUTETIA
C -226999 ROSLND_LOCAL_LEVEL
C -226967 2867/STEINS_CSO
C -226945 45P/H-M-P_CSO
C -226921 21/LUTETIA_CSO
C
C ...
C
C 1503299 VME2000
C 1503399 ECLIPDATE
C 1503499 MME2000
C 2000021 LUTETIA_FIXED
C 2002867 STEINS_FIXED
C
C
C$ Restrictions
C
C 1) This routine will work correctly if the kernel pool
C contains no invalid frame specifications. See the
C description of exception 4 above. Users must ensure
C that no invalid frame specifications are introduced
C into the kernel pool, either by loaded kernels or
C by means of the kernel pool "put" APIs.
C
C$ Literature_References
C
C None.
C
C$ Author_and_Institution
C
C N.J. Bachman (JPL)
C
C$ Version
C
C- SPICELIB Version 1.1.0, 18-JUN-2015 (NJB)
C
C Bug fix: previous algorithm failed if the number of frame
C names fetched from the kernel pool on a single call exceeded
C twice the kernel variable buffer size. The count of
C fetched names is now maintained correctly.
C
C- SPICELIB Version 1.0.0, 22-MAY-2012 (NJB)
C
C-&
C$ Index_Entries
C
C fetch IDs of reference_frames from the kernel_pool
C
C-&
C
C SPICELIB functions
C
INTEGER SIZEI
LOGICAL RETURN
C
C Local parameters
C
INTEGER FRNMLN
PARAMETER ( FRNMLN = 32 )
INTEGER KVNMLN
PARAMETER ( KVNMLN = 32 )
INTEGER BUFSIZ
PARAMETER ( BUFSIZ = 100 )
C
C Local variables
C
CHARACTER*(FRNMLN) FRNAME
CHARACTER*(KVNMLN) KVBUFF ( BUFSIZ )
CHARACTER*(KVNMLN) KVNAME
CHARACTER*(KVNMLN) KVTEMP
CHARACTER*(KVNMLN) KVCODE
CHARACTER*(KVNMLN) KVCLAS
CHARACTER*(FRNMLN) TMPNAM
INTEGER FCLASS
INTEGER I
INTEGER IDCODE
INTEGER L
INTEGER M
INTEGER N
INTEGER TO
INTEGER TOTAL
INTEGER W
LOGICAL FOUND
IF ( RETURN() ) THEN
RETURN
END IF
CALL CHKIN ( 'KPLFRM' )
C
C The output set starts out empty.
C
CALL SCARDI ( 0, IDSET )
C
C Check the input frame class.
C
C This block of code must be kept in sync with frmtyp.inc.
C
IF ( ( FRMCLS .GT. DYN )
. .OR. ( FRMCLS .EQ. 0 )
. .OR. ( FRMCLS .LT. ALL ) ) THEN
CALL SETMSG ( 'Frame class specifier FRMCLS was #; this '
. // 'value is not supported.' )
CALL ERRINT ( '#', FRMCLS )
CALL SIGERR ( 'SPICE(BADFRAMECLASS)' )
CALL CHKOUT ( 'KPLFRM' )
RETURN
END IF
C
C Initialize the output buffer index. The
C index is to be incremented prior to each
C write to the buffer.
C
TO = 0
C
C Find all of the kernel variables having names
C that could correspond to frame name assignments.
C
C We expect that all frame specifications will
C include assignments of the form
C
C FRAME_<ID code>_NAME = <frame name>
C
C We may pick up some additional assignments that are not part of
C frame specifications; we plan to filter out as many as possible
C by looking the corresponding frame ID and frame class
C assignments.
C
KVTEMP = 'FRAME_*_NAME'
CALL GNPOOL ( KVTEMP, 1, BUFSIZ, N, KVBUFF, FOUND )
TOTAL = 0
DO WHILE ( N .GT. 0 )
TOTAL = TOTAL + N
C
C At least one kernel variable was found by the last
C GNPOOL call. Each of these variables is a possible
C frame name. Look up each of these candidate names.
C
DO I = 1, N
C
C Attempt to fetch the right hand side value for
C the Ith kernel variable found on the previous
C GNPOOL call.
C
CALL GCPOOL ( KVBUFF(I), 1, 1, M, FRNAME, FOUND )
IF ( FOUND ) THEN
C
C We found a possible frame name. Attempt to look
C up an ID code variable for the name. The assignment
C for the ID code, if present, will have the form
C
C FRAME_<name> = <ID code>
C
C Create the kernel variable name on the left hand
C side of the assignment.
C
KVCODE = 'FRAME_<name>'
CALL REPMC ( KVCODE, '<name>', FRNAME, KVCODE )
C
C Try to fetch the ID code.
C
CALL GIPOOL ( KVCODE, 1, 1, L, IDCODE, FOUND )
IF ( FOUND ) THEN
C
C We found an integer on the right hand side
C of the assignment. We probably have a
C frame specification at this point. Check that
C the variable
C
C FRAME_<ID code>_NAME
C
C is present in the kernel pool and maps to
C the name FRNAME.
C
KVNAME = 'FRAME_<code>_NAME'
CALL REPMI ( KVNAME, '<code>', IDCODE, KVNAME )
CALL GCPOOL ( KVNAME, 1, 1, W, TMPNAM, FOUND )
IF ( FOUND ) THEN
C
C Try to look up the frame class using a
C kernel variable name of the form
C
C FRAME_<integer ID code>_CLASS
C
C Create the kernel variable name on the left
C hand side of the frame class assignment.
C
KVCLAS = 'FRAME_<integer>_CLASS'
CALL REPMI ( KVCLAS, '<integer>', IDCODE, KVCLAS )
C
C Look for the frame class.
C
CALL GIPOOL ( KVCLAS, 1, 1, W, FCLASS, FOUND )
IF ( .NOT. FOUND ) THEN
C
C Try to look up the frame class using a kernel
C variable name of the form
C
C FRAME_<frame name>_CLASS
C
KVCLAS = 'FRAME_<name>_CLASS'
CALL REPMC ( KVCLAS, '<name>', FRNAME, KVCLAS )
CALL GIPOOL ( KVCLAS, 1, 1, W, FCLASS, FOUND )
END IF
C
C At this point FOUND indicates whether we found
C the frame class.
C
IF ( FOUND ) THEN
C
C Check whether the frame class is one
C we want.
C
IF ( ( FRMCLS .EQ. ALL )
. .OR. ( FRMCLS .EQ. FCLASS ) ) THEN
C
C We have a winner. Add it to the output set.
C
C First make sure the set is large enough to
C hold another element.
C
IF ( TO .EQ. SIZEI(IDSET) ) THEN
CALL SETMSG ( 'Frame ID set argument '
. // 'IDSET has size #; required'
. // ' size is at least #. Make '
. // 'sure that the caller of '
. // 'this routine has initial'
. // 'ized IDSET via SSIZEI.' )
CALL ERRINT ( '#', SIZEI(IDSET) )
CALL ERRINT ( '#', TO+1 )
CALL SIGERR ( 'SPICE(SETTOOSMALL)' )
CALL CHKOUT ( 'KPLFRM' )
RETURN
END IF
TO = TO + 1
IDSET(TO) = IDCODE
END IF
C
C End of IF block for processing a frame having
C a frame class matching the request.
C
END IF
C
C End of IF block for finding the frame class.
C
END IF
C
C End of IF block for finding the frame name.
C
END IF
C
C End of IF block for finding the frame ID.
C
END IF
C
C End of IF block for finding string value corresponding to
C the Ith kernel variable matching the name template.
C
END DO
C
C End of loop for processing last batch of potential
C frame names.
C
C Fetch next batch of potential frame names.
C
CALL GNPOOL ( KVTEMP, TOTAL+1, BUFSIZ, N, KVBUFF, FOUND )
END DO
C
C At this point all kernel variables that matched the frame name
C keyword template have been processed. All frames of the specified
C class or classes have had their ID codes appended to IDSET. In
C general IDSET is not yet a SPICELIB set, since it's not sorted
C and it may contain duplicate values.
C
C Turn IDSET into a set. VALIDI sorts and removes duplicates.
C
CALL VALIDI ( SIZEI(IDSET), TO, IDSET )
CALL CHKOUT ( 'KPLFRM' )
RETURN
END
|
------------------------------------------------------------------------
-- A specification of the language χ
------------------------------------------------------------------------
open import Atom
-- The specification is parametrised by an instance of χ-atoms.
module Chi (atoms : χ-atoms) where
open import Equality.Propositional
open import Prelude hiding (const)
open χ-atoms atoms
-- Abstract syntax.
mutual
data Exp : Type where
apply : Exp → Exp → Exp
lambda : Var → Exp → Exp
case : Exp → List Br → Exp
rec : Var → Exp → Exp
var : Var → Exp
const : Const → List Exp → Exp
data Br : Type where
branch : Const → List Var → Exp → Br
-- Substitution.
mutual
infix 6 _[_←_] _[_←_]B _[_←_]⋆ _[_←_]B⋆
_[_←_] : Exp → Var → Exp → Exp
apply e₁ e₂ [ x ← e′ ] = apply (e₁ [ x ← e′ ]) (e₂ [ x ← e′ ])
lambda y e [ x ← e′ ] = lambda y (if x V.≟ y
then e
else e [ x ← e′ ])
case e bs [ x ← e′ ] = case (e [ x ← e′ ]) (bs [ x ← e′ ]B⋆)
rec y e [ x ← e′ ] = rec y (if x V.≟ y
then e
else e [ x ← e′ ])
var y [ x ← e′ ] = if x V.≟ y then e′ else var y
const c es [ x ← e′ ] = const c (es [ x ← e′ ]⋆)
_[_←_]B : Br → Var → Exp → Br
branch c xs e [ x ← e′ ]B with V.member x xs
... | yes _ = branch c xs e
... | no _ = branch c xs (e [ x ← e′ ])
_[_←_]⋆ : List Exp → Var → Exp → List Exp
[] [ x ← e′ ]⋆ = []
(e ∷ es) [ x ← e′ ]⋆ = e [ x ← e′ ] ∷ es [ x ← e′ ]⋆
_[_←_]B⋆ : List Br → Var → Exp → List Br
[] [ x ← e′ ]B⋆ = []
(b ∷ bs) [ x ← e′ ]B⋆ = b [ x ← e′ ]B ∷ bs [ x ← e′ ]B⋆
infix 5 ∷_
infix 4 _[_←_]↦_
data _[_←_]↦_ (e : Exp) : List Var → List Exp → Exp → Type where
[] : e [ [] ← [] ]↦ e
∷_ : ∀ {x xs e′ es′ e″} →
e [ xs ← es′ ]↦ e″ → e [ x ∷ xs ← e′ ∷ es′ ]↦ e″ [ x ← e′ ]
-- Operational semantics.
data Lookup (c : Const) : List Br → List Var → Exp → Type where
here : ∀ {xs e bs} → Lookup c (branch c xs e ∷ bs) xs e
there : ∀ {c′ xs′ e′ bs xs e} →
c ≢ c′ → Lookup c bs xs e →
Lookup c (branch c′ xs′ e′ ∷ bs) xs e
infixr 5 _∷_
infix 4 _⇓_ _⇓⋆_
mutual
data _⇓_ : Exp → Exp → Type where
apply : ∀ {e₁ e₂ x e v₂ v} →
e₁ ⇓ lambda x e → e₂ ⇓ v₂ → e [ x ← v₂ ] ⇓ v →
apply e₁ e₂ ⇓ v
case : ∀ {e bs c es xs e′ e″ v} →
e ⇓ const c es → Lookup c bs xs e′ →
e′ [ xs ← es ]↦ e″ → e″ ⇓ v →
case e bs ⇓ v
rec : ∀ {x e v} → e [ x ← rec x e ] ⇓ v → rec x e ⇓ v
lambda : ∀ {x e} → lambda x e ⇓ lambda x e
const : ∀ {c es vs} → es ⇓⋆ vs → const c es ⇓ const c vs
data _⇓⋆_ : List Exp → List Exp → Type where
[] : [] ⇓⋆ []
_∷_ : ∀ {e es v vs} → e ⇓ v → es ⇓⋆ vs → e ∷ es ⇓⋆ v ∷ vs
|
! Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
!
! Licensed under the Apache License, Version 2.0 (the "License");
! you may not use this file except in compliance with the License.
! You may obtain a copy of the License at
!
! http://www.apache.org/licenses/LICENSE-2.0
!
! Unless required by applicable law or agreed to in writing, software
! distributed under the License is distributed on an "AS IS" BASIS,
! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
! See the License for the specific language governing permissions and
! limitations under the License.
module m
type :: t
procedure(a), pointer, pass :: c
procedure(a), pointer, pass(x) :: d
contains
procedure, pass(y) :: a, b
end type
contains
subroutine a(x, y)
class(t) :: x, y
end
subroutine b(y)
class(t) :: y
end
end module
!Expect: m.mod
!module m
! type::t
! procedure(a),pass,pointer::c
! procedure(a),pass(x),pointer::d
! contains
! procedure,pass(y)::a
! procedure,pass(y)::b
! end type
!contains
! subroutine a(x,y)
! class(t)::x
! class(t)::y
! end
! subroutine b(y)
! class(t)::y
! end
!end
|
State Before: R : Type u_1
inst✝³ : CommSemiring R
M : Submonoid R
S : Type ?u.2768138
inst✝² : CommSemiring S
inst✝¹ : Algebra R S
P : Type ?u.2768305
inst✝ : CommSemiring P
a : R
b : { x // x ∈ M }
c : R
⊢ mk a b + mk c b = mk (a + c) b State After: R : Type u_1
inst✝³ : CommSemiring R
M : Submonoid R
S : Type ?u.2768138
inst✝² : CommSemiring S
inst✝¹ : Algebra R S
P : Type ?u.2768305
inst✝ : CommSemiring P
a : R
b : { x // x ∈ M }
c : R
⊢ ↑(r' M) (↑b * c + ↑b * a, b * b) (a + c, b) Tactic: rw [add_mk, mk_eq_mk_iff, r_eq_r'] State Before: R : Type u_1
inst✝³ : CommSemiring R
M : Submonoid R
S : Type ?u.2768138
inst✝² : CommSemiring S
inst✝¹ : Algebra R S
P : Type ?u.2768305
inst✝ : CommSemiring P
a : R
b : { x // x ∈ M }
c : R
⊢ ↑(r' M) (↑b * c + ↑b * a, b * b) (a + c, b) State After: R : Type u_1
inst✝³ : CommSemiring R
M : Submonoid R
S : Type ?u.2768138
inst✝² : CommSemiring S
inst✝¹ : Algebra R S
P : Type ?u.2768305
inst✝ : CommSemiring P
a : R
b : { x // x ∈ M }
c : R
⊢ ↑1 * (↑(↑b * c + ↑b * a, b * b).snd * (a + c, b).fst) = ↑1 * (↑(a + c, b).snd * (↑b * c + ↑b * a, b * b).fst) Tactic: refine' (r' M).symm ⟨1, _⟩ State Before: R : Type u_1
inst✝³ : CommSemiring R
M : Submonoid R
S : Type ?u.2768138
inst✝² : CommSemiring S
inst✝¹ : Algebra R S
P : Type ?u.2768305
inst✝ : CommSemiring P
a : R
b : { x // x ∈ M }
c : R
⊢ ↑1 * (↑(↑b * c + ↑b * a, b * b).snd * (a + c, b).fst) = ↑1 * (↑(a + c, b).snd * (↑b * c + ↑b * a, b * b).fst) State After: R : Type u_1
inst✝³ : CommSemiring R
M : Submonoid R
S : Type ?u.2768138
inst✝² : CommSemiring S
inst✝¹ : Algebra R S
P : Type ?u.2768305
inst✝ : CommSemiring P
a : R
b : { x // x ∈ M }
c : R
⊢ 1 * (↑b * ↑b * (a + c)) = 1 * (↑b * (↑b * c + ↑b * a)) Tactic: simp only [Submonoid.coe_one, Submonoid.coe_mul] State Before: R : Type u_1
inst✝³ : CommSemiring R
M : Submonoid R
S : Type ?u.2768138
inst✝² : CommSemiring S
inst✝¹ : Algebra R S
P : Type ?u.2768305
inst✝ : CommSemiring P
a : R
b : { x // x ∈ M }
c : R
⊢ 1 * (↑b * ↑b * (a + c)) = 1 * (↑b * (↑b * c + ↑b * a)) State After: no goals Tactic: ring |
module BoundedVect
import Data.Vect
import NatHelpers
%default total
||| A bounded Vect is a vector with a maximum capacity that cannot be exceeded.
|||
||| The only way to append an element to the vector is to provide a prood that
||| it's size is strictly less than it's capacity. Therefore the size of a BoundedVect
||| will always be less or equal to its maximum capacity
public export
data BoundedVect : (max, size: Nat) -> (elem : Type) -> Type where
Nil : BoundedVect max Z elem
Cons : (prf : size `LT` max) -> (x : elem) -> BoundedVect max size elem -> BoundedVect max (S size) elem
%name BoundedVect xs, ys, zs, ws
export
fromVect : Vect size elem -> (ok : size `LTE` max) -> BoundedVect max size elem
fromVect [] ok = []
fromVect (x :: xs) ok = Cons ok x (fromVect xs (lteSuccLeft ok))
export
fromVectAuto : Vect size elem -> {auto ok : size `LTE` max} -> BoundedVect max size elem
fromVectAuto xs {ok} = fromVect xs ok
||| attempt to append an element to a bounded vect, if the vect is at max capacity
||| return nothing, otherwise, return the new boundedVect with the same bounds
export maybeAppendBoundedVect : (x : elem) -> BoundedVect max size elem -> Maybe (BoundedVect max (S size) elem)
maybeAppendBoundedVect x xs {max} {size} with (cmp size max)
maybeAppendBoundedVect x xs {max = (size + (S y))} {size = size} | (CmpLT y) =
let lte = LTESucc $ lteRightPlusNat {k = y} (size) in
Just (Cons (lteRighPlusSuccRightSucc lte) x xs)
maybeAppendBoundedVect x xs {max = max} {size = max} | CmpEQ = Nothing
maybeAppendBoundedVect x xs {max = max} {size = (max + (S k))} | (CmpGT k) = Nothing
||| Appends an element to a boundedVect and increase the size of its bound
export
appendVectExtendBound : (x : elem) -> BoundedVect max size elem -> BoundedVect (S max) (S size) elem
appendVectExtendBound x [] = Cons (LTESucc LTEZero) x []
appendVectExtendBound x (Cons prf y xs) with (appendVectExtendBound y xs)
appendVectExtendBound x (Cons prf y xs) | (Cons z w ys) = Cons (LTESucc prf) w (Cons z w ys)
|
import numpy as np
import superfast
def test_sum():
a = np.array([[1,2,3],[2,3,4]]).astype('float64')
assert(a.sum() == superfast.sum_row_major_order(a))
|
function R = apprRot(Ra)
%R = apprRot(Ra)
i1 = 0.5; i2 = 0.5;
U = Ra(1,:);
V = Ra(2,:);
un = norm(U);
vn = norm(V);
Un = U/un;
Vn = V/vn;
vp = Un*Vn';
up = Vn*Un';
Vc = Vn-vp*Un; Vc = Vc/norm(Vc);
Uc = Un-up*Vn; Uc = Uc/norm(Uc);
Ua = i1*Un+i2*Uc; Ua = Ua/norm(Ua);
Va = i1*Vn+i2*Vc; Va = Va/norm(Va);
R = [Ua;Va;cross(Ua,Va)];
if det(R)<0, R(3,:) = -R(3,:); end;
|
#include <boost/format/format_class.hpp>
|
% -*- mode: tex; fill-column: 115; -*-
%\input{common/conf_top.tex}
\input{common/conf_top_print.tex} %settings for printed booklets - comment out by default, uncomment for print and comment out line above. don't save this change! "conf_top" should be default
\input{common/conf_titles.tex}
\begin{document}
\input{common/conf_listings.tex} %see note for `conf_top_print.tex` above
%\input{common/conf_listings_colorized.tex} %Use this for online version
\thispagestyle{empty} %removes page number
\newgeometry{bmargin=0cm, hmargin=0cm}
\begin{center}
\textsc{\Large\bf{Gradient Boosted Models with H2O}}
\bigskip
\line(1,0){250} %inserts horizontal line
\\
\bigskip
\small
\textsc{Cliff Click \hspace{10pt} Michal Malohlava \hspace{10pt} Viraj Parmar}
\textsc{Hank Roark \hspace{10pt} Arno Candel}
\textsc{Edited by: Jessica Lanford}
\normalsize
\line(1,0){250} %inserts horizontal line
{\url{http://h2o.ai/resources/}}
\bigskip
\monthname \hspace{1pt} \the\year: Fourth Edition
\bigskip
\end{center}
% commenting out lines image due to print issues, but leaving in for later
%\null\vfill
%\begin{figure}[!b]
%\noindent\makebox[\textwidth]{%
%\centerline{\includegraphics[width=\paperwidth]{waves.png}}}
%\end{figure}
\newpage
\restoregeometry
\null\vfill %move next text block to lower left of new page
\thispagestyle{empty}%remove pg#
{\raggedright
Gradient Boosted Models with H2O\\
by Cliff Click, Michal Malohlava, \\
Viraj Parmar, Hank Roark \&\ Arno Candel\\
Edited by: Jessica Lanford
\bigskip
Published by H2O.ai, Inc. \\
2307 Leghorn St. \\
Mountain View, CA 94043\\
\bigskip
\textcopyright \the\year \hspace{1pt} H2O.ai, Inc. All Rights Reserved.
\bigskip
\monthname \hspace{1pt} \the\year: Fourth Edition
\bigskip
Photos by \textcopyright H2O.ai, Inc.
\bigskip
All copyrights belong to their respective owners.\\
While every precaution has been taken in the\\
preparation of this book, the publisher and\\
authors assume no responsibility for errors or\\
omissions, or for damages resulting from the\\
use of the information contained herein.\\
\bigskip
Printed in the United States of America.
}
\newpage
\thispagestyle{empty}%remove pg#
\tableofcontents
%----------------------------------------------------------------------
%----------------------------------------------------------------------
\newpage
\section{Introduction}
This document describes how to use Gradient Boosted Models (GBM) with H2O.
Examples are written in R and Python.
Topics include:
\begin{itemize}
\item installation of H2O
\item basic GBM concepts
\item building GBM models in H2O
\item interpreting model output
\item making predictions
\end{itemize}
%----------------------------------------------------------------------
%----------------------------------------------------------------------
\input{common/what_is_h2o.tex}
%----------------------------------------------------------------------
%----------------------------------------------------------------------
\input{generated_buildinfo.tex}
\input{common/installation.tex}
\subsection{Example Code}
R and Python code for the examples in this document are available here:\\
\url{https://github.com/h2oai/h2o-3/tree/master/h2o-docs/src/booklets/v2_2015/source/GBM_Vignette_code_examples}
\subsection{Citation}
To cite this booklet, use the following:
Click, C., Malohlava, M., Parmar, V., Roark, H., and Candel, A. (Nov. 2015). \textit{Gradient Boosted Models with H2O}. \url{http://h2o.ai/resources/}.
%----------------------------------------------------------------------
%----------------------------------------------------------------------
\section{Overview}
A GBM is an ensemble of either regression or classification tree models.
Both are forward-learning ensemble methods that obtain predictive results using gradually improved estimations.
Boosting is a flexible nonlinear regression procedure that helps improve the accuracy of trees. Weak classification algorithms are sequentially applied to the incrementally changed data to create a series of decision trees, producing an ensemble of weak prediction models.
While boosting trees increases their accuracy, it also decreases speed and user interpretability.
The gradient boosting method generalizes tree boosting to minimize these drawbacks.
\subsection{Summary of Features}
H2O's GBM functionalities include:
\begin{itemize}
\item supervised learning for regression and classification tasks
\item distributed and parallelized computation on either a single node or a multi-node cluster
\item fast and memory-efficient Java implementations of the algorithms
\item the ability to run H2O from R, Python, Scala, or the intuitive web UI (Flow)
\item automatic early stopping based on convergence of user-specified metrics to user-specified relative tolerance
\item stochastic gradient boosting with column and row sampling for better generalization
\item support for exponential families (Poisson, Gamma, Tweedie) and loss functions in addition to binomial (Bernoulli), Gaussian and multinomial distributions
\item grid search for hyperparameter optimization and model selection
\item model export in plain Java code for deployment in production environments
\item additional parameters for model tuning (for a complete listing of parameters, refer to the {\textbf{\nameref{ssec:Model Parameters}}} section.)
\end{itemize}
Gradient boosted models (also known as gradient boosting machines) sequentially fit new models to provide a more accurate estimate of a response variable in supervised learning tasks such as regression and classification. Although GBM is known to be difficult to distribute and parallelize, H2O provides an easily distributable and parallelizable version of GBM in its framework, as well as an effortless environment for model tuning and selection.
\subsection{Theory and Framework}
Gradient boosting is a machine learning technique that combines two powerful tools: gradient-based optimization and
boosting. Gradient-based optimization uses gradient computations to minimize a model's loss function in terms of
the training data.
Boosting additively collects an ensemble of weak models to create a robust
learning system for predictive tasks. The following example considers gradient boosting in the example of $K$-class classification; the model for regression follows a similar logic. The following analysis follows from the discussion in
Hastie et al (2010) at {\url{http://statweb.stanford.edu/~tibs/ElemStatLearn/}}.
\bf{\footnotesize{GBM for classification}}
\normalfont
\\
\line(1,0){350}
\\
1. Initialize $f_{k0} = 0, k = 1,2,\dots,K$
\\
2. For $m=1$ to $M$
\hspace{1cm} a. Set $p_k(x) = \frac{e^{f_k(x)}}{\sum_{l=1}^K e^{f_l(x)}}$ for all $k = 1,2\dots, K$
\hspace{1cm} b. For $k=1$ to $K$
\hspace{2cm} i. Compute $r_{ikm} = y_{ik} - p_k(x_i), i = 1,2,\dots,N$
\hspace{2cm} ii. Fit a regression tree to the targets $r_{ikm}, i = 1,2,\dots,N$,
\par \hspace{2.5cm} giving terminal regions $R_{jkm}, 1,2,\dots,J_m$
\hspace{2cm}iii. Compute $$\gamma_{jkm} = \frac{K-1}{K} \frac{\sum_{x_i \in R_{jkm}} (r_{ikm})}{\sum_{x_i \in R_{jkm}} |r_{ikm}| (1 - |r_{ikm}|)} , j=1,2,\dots,J_m$$
\hspace{2cm} iv. Update $f_{km}(x) = f_{k,m-1}(x) + \sum_{j=1}^{J_m} \gamma_{jkm} I(x \in R_{jkm})$
\\
3. Output $f_k^{\hat{}}(x) = f_{kM}(x), k=1,2,\dots,K$
\\
\line(1,0){350}
In the above algorithm for multi-class classification, H2O builds $k$-regression trees: one tree represents each target class. The index, $m$, tracks the number of weak learners added to the current ensemble. Within this outer loop, there is an inner loop across each of the $K$ classes.
\begin{minipage}{\textwidth}
Within this inner loop, the first step is to compute the residuals, $r_{ikm}$, which are actually the gradient values, for each of the $N$ bins in the CART model. A regression tree is then fit to these gradient computations. This fitting process is distributed and parallelized. Details on this framework are available at {\url{http://h2o.ai/blog/2013/10/building-distributed-gbm-h2o/}}.
\end{minipage}
The final procedure in the inner loop is to add the current model to the fitted regression tree to improve the accuracy of the model during the inherent gradient descent step. After $M$ iterations, the final ``boosted" model can be tested out on new data.
%%\subsection{Loss Function}
%%The AdaBoost method builds an additive logistic regression model:
%%$${F(x) = log}\frac{Pr(Y = 1|x)}{Pr(Y = -1|x)} = \sum_{m=1}^{M} \alpha_m f_m (x) $$
%%
%%by stagewise fitting using the loss function:
%%$$L(y, F(x)) = exp(-y F (x)) $$
\subsection{Distributed Trees}
H2O's implementation of GBM uses distributed trees. H2O overlays trees on the data by assigning a tree node to each row.
The nodes are numbered and the number of each node is stored as {\texttt{Node\_ID}} in a temporary vector for each row. H2O makes a pass over all the rows using the most efficient method (not necessarily numerical order).
A local
histogram using only local data is created in parallel for each row on each node. The histograms are then assembled and a split column is selected to make the decision. The rows are re-assigned to nodes and the entire process is repeated.
With an initial tree, all rows start on node 0. An in-memory MapReduce (MR) task computes the statistics and uses
them to make an algorithmically-based decision, such as lowest mean squared error (MSE). In the next layer in the
tree (and the next MR task), a decision is made for each row: if X $<$ 1.5, go right in the tree; otherwise, go left.
H2O computes the stats for each new leaf in the tree, and each pass across all the rows builds the entire layer.
For multinomial or binomial models, each bin is inspected as a potential split point. The best split point is selected after evaluating all bins. For example, for a hundred-column dataset that uses twenty bins,
there are 2000 (20x100) possible split points.
Each layer is computed using another MR task: a tree that is five layers deep requires five passes. Each tree
level is fully data-parallelized. Each pass builds a per-node histogram in the MR call over one layer in the tree. During each pass, H2O analyzes the tree level and decides how to build the next level. In another pass, H2O reassigns rows to new levels by merging the two passes and then builds a histogram for each node. Each per-level histogram is done in parallel.
Scoring and building is done in the same pass. Each row is tested against the decision from the previous pass and assigned
to a new leaf, where a histogram is built. To score, H2O traverses the tree and obtains the results. The
tree is compressed to a smaller object that can still be traversed, scored, and printed.
Although the GBM algorithm builds each tree one level at a time, H2O is able to quickly run the entire level in
parallel and distributed. The processing requirements for more data can be offset by more CPUs or nodes.
The data can be very large for deep trees. Large trees that need to be sent over the network can be expensive, due to the size of the dataset, which can lead to slow model build times.
For the MSE reports, the zero-tree report uses the class distribution as the prediction. The one-tree report
uses the first tree, so the first two reports are not equal. The reported MSE is the inclusive effect of all
prior trees and generally decreases monotonically on the training dataset. However, the curve will generally
bottom out and then begin to slowly rise on the validation set as overfitting sets in.
The computing cost is based on a number of factors, including the final count of leaves in all trees. Depending on the dataset, the number of leaves can be
difficult to predict. The maximum number of leaves is $2^d$, where $d$ represents the tree depth.
\subsection{Treatment of Factors}
If the training data contains columns with categorical levels (factors), then these factors are split by assigning an integer to each distinct
categorical level, then binning the ordered integers according to the user-specified number of bins \texttt{nbins\_cats} (which defaults to 1024 bins),
and then picking the optimal split point among the bins.
To specify a model that considers all factors individually (and perform an optimal group split,
where every level goes in the right direction based on the training response), specify \texttt{nbins\_cats} to be at least as large as the number of factors.
Values greater than 1024 (the maximum number of levels supported in R) are supported, but might increase model training time.
The value of \texttt{nbins\_cats} for categorical factors has a much greater impact on the generalization error rate than \texttt{nbins} for real- or integer-valued columns (where higher values mainly lead to more accurate numerical split points).
For columns with many factors, a small \texttt{nbins\_cats} value can add randomness to the split decisions (since the columns are grouped together somewhat arbitrarily), while large values can lead to perfect splits, resulting in overfitting.
\subsection{Key Parameters}
\label{ssec:Key parameters}
\raggedbottom
In the above example, an important user-specified value is $N$, which represents the number of bins used to partition the data before the tree's best split point is determined. To model all factors individually, specify high $N$ values, but this will slow down the modeling process. For shallow trees, the total count of bins across all splits is kept at 1024 for numerical columns (so that a top-level split uses 1024, but a second-level split uses 512 bins, and so forth). This value is then maxed with the input bin count.
Specify the depth of the trees ($J$) to avoid overfitting. Increasing $J$ results in larger variable interaction effects. Large values of $J$ have also been found to have an excessive computational cost,
since Cost = \#columns $\cdot N \cdot K \cdot 2^{J}$. Lower values generally have the highest
performance.
Models with $4 \leq J \leq 8$ and a larger number of trees $M$ reflect this generalization.
Grid search models can be used to tune these parameters in the model selection process. For more information, refer to {\textbf{\nameref{ssec:Grid search}}}.
To control the learning rate of the model, specify the \texttt{learn\_rate} constant, which is actually a
form of regularization. Shrinkage modifies the algorithm's update of $f_{km}(x)$ with the scaled
addition $\nu \cdot \sum_{j=1}^{J_m} \gamma_{jkm} I(x \in R_{jkm})$, where the constant $\nu$ is between 0 and 1.
Smaller values of $\nu$ learn more slowly and need more trees to reach the same overall error rate but typically result in a better model, assuming that $M$ is constant. In general, $\nu$ and $M$ are inversely related when the error rate is constant. However, despite the greater rate of training error with small values of $\nu$, very small ($\nu < 0.1$) values typically lead to better generalization and performance on test data.
\newpage
\subsubsection{Convergence-based Early Stopping}
One nice feature for finding the optimal number of trees is early stopping based on convergence of a user-specified metric. By default, it uses the metrics on the validation dataset, if provided. Otherwise, training metrics are used.
\begin{itemize}
\item To stop model building if misclassification improves (goes down) by less than one percent between individual scoring events, specify \\\texttt{stopping\_rounds=1}, \texttt{stopping\_tolerance=0.01} and \\\texttt{stopping\_metric="misclassification"}.
\item To stop model building if the logloss on the validation set does not improve at all for 3 consecutive scoring events, specify a \texttt{validation\_frame}, \texttt{stopping\_rounds=3}, \texttt{stopping\_tolerance=0} and \\\texttt{stopping\_metric="logloss"}.
\item To stop model building if the simple moving average (window length 5) of the AUC improves (goes up) by less than 0.1 percent for 5 consecutive scoring events, specify \texttt{stopping\_rounds=5}, \texttt{stopping\_tolerance=0.001} and \texttt{stopping\_metric="AUC"}.
\item To not stop model building even after metrics have converged, disable this feature with \texttt{stopping\_rounds=0}.
\item To compute the best number of trees with cross-validation, simply specify \texttt{stopping\_rounds>0} as in the examples above, in combination with \texttt{nfolds>1}, and the main model will pick the ideal number of trees from the convergence behavior of the \texttt{nfolds} cross-validation models.
\end{itemize}
\subsubsection{Stochastic GBM}
Stochastic GBM is a way to improve generalization by sampling columns (per split) and rows (per tree) during the model building process. To control the sampling ratios use \texttt{sample\_rate} for rows and \texttt{col\_sample\_rate} for columns. Both parameters must range from 0 to 1.
\section{Use Case: Airline Data Classification}
Download the Airline dataset from: {\url{https://github.com/h2oai/h2o-2/blob/master/smalldata/airlines/allyears2k_headers.zip}} and save the .csv file to your working directory.
\subsection{Loading Data}
Loading a dataset in R or Python for use with H2O is slightly different from the usual methodology because the datasets must be converted into \texttt{H2OParsedData} objects. For this example, download the toy weather dataset from
{\url{https://github.com/h2oai/h2o-2/blob/master/smalldata/weather.csv}}.
Load the data to your current working directory in your R Console (do this for any future dataset downloads), and then run the following command.
\waterExampleInR
\lstinputlisting[style=R]{GBM_Vignette_code_examples/gbm_uploadfile_example.R}
Load the data to your current working directory in Python (do this for any future dataset downloads), and then run the following command.
\waterExampleInPython
\lstinputlisting[style=python]{GBM_Vignette_code_examples/gbm_uploadfile_example.py}
\subsection{Performing a Trial Run}
Load the Airline dataset into H2O and select the variables to use to predict the response. The following example models delayed flights based on the departure's scheduled day of the week and day of the month.
\waterExampleInR
\lstinputlisting[style=R]{GBM_Vignette_code_examples/gbm_examplerun.R}
\waterExampleInPython
\lstinputlisting[style=python]{GBM_Vignette_code_examples/gbm_examplerun.py}
Since it is meant just as a trial run, the model contains only 100 trees. In this trial run, no validation set was
specified, so by default, the model evaluates the entire training set. To use n-fold validation, specify an n-folds value (for example, \texttt{nfolds=5}).
Let's run again with row and column sampling:
\waterExampleInR
\lstinputlisting[style=R]{GBM_Vignette_code_examples/gbm_examplerun_stochastic.R}
\waterExampleInPython
\lstinputlisting[style=python]{GBM_Vignette_code_examples/gbm_examplerun_stochastic.py}
\subsection{Extracting and Handling the Results}
Now, extract the parameters of the model, examine the scoring process, and make predictions on the new data.
\begin{minipage}{\textwidth}
\waterExampleInR
\lstinputlisting[style=R]{GBM_Vignette_code_examples/gbm_extractmodelparams.R}
\end{minipage}
\begin{minipage}{\textwidth}
\waterExampleInPython
\lstinputlisting[style=python]{GBM_Vignette_code_examples/gbm_extractmodelparams.py}
\end{minipage}
The first command ({\texttt{air.model}}) returns the trained model's training and validation errors.
After generating a satisfactory model, use the \texttt{h2o.predict()} command to compute and store predictions on the
new data, which can then be used for further tasks in the interactive modeling process.
\begin{minipage}{\textwidth}
\waterExampleInR
\lstinputlisting[style=R]{GBM_Vignette_code_examples/gbm_predict.R}
\end{minipage}
\begin{minipage}{\textwidth}
\waterExampleInPython
\lstinputlisting[style=python]{GBM_Vignette_code_examples/gbm_predict.py}
\end{minipage}
\subsection{Web Interface}
H2O users have the option of using an intuitive web interface for H2O, Flow. After loading data or training a model, point your browser to your IP address and port number (e.g., localhost:12345) to launch the web interface. In the web UI, click \textsc{Admin} $>$ \textsc{Jobs} to view specific details about your model or click \textsc{Data} $>$ \textsc{List All Frames} to view all current H2O frames.
\subsection{Variable Importances}
The GBM algorithm automatically calculates variable importances. The model output includes the absolute and relative predictive strength of each feature in the prediction task. To extract the variable importances from the model:
\begin{itemize}
\item \textbf{In R}: Use \texttt{h2o.varimp(air.model)}
\item \textbf{In Python}: Use \texttt{air\_model.varimp(return\_list=True)}
\end{itemize}
To view a visualization of the variable importances using the web interface, click the \textsc{Model} menu, then select \textsc{List All Models}. Click the \textsc{Inspect} button next to the model, then select \textsc{output - Variable Importances}.
\begin{minipage}{\textwidth}
\subsection{Supported Output}
The following algorithm outputs are supported:
\begin{itemize}
\item {\bf{Regression}}: Mean Squared Error (MSE), with an option to output variable importances or a Plain Old Java Object (POJO) model
\item {\bf{Binary Classification}}: Confusion Matrix or Area Under Curve (AUC), with an option to output variable importances or a Java POJO model
\item {\bf{Classification}}: Confusion Matrix (with an option to output variable importances or a Java POJO model)
\end{itemize}
\end{minipage}
\subsection{Java Models}
To access Java code to use to build the current model in Java, click the \textsc{Preview POJO} button at the bottom of the model results. This button generates a POJO model that can be used in a Java application independently of H2O. If the model is small enough, the code for the model displays within the GUI; larger models can be inspected after downloading the model.
To download the model:
\begin{enumerate}
\item Open the terminal window.
\item Create a directory where the model will be saved.
\item Set the new directory as the working directory.
\item Follow the \texttt{curl} and \texttt{java compile} commands displayed in the instructions at the top of the Java model.
\end{enumerate}
For more information on how to use an H2O POJO, refer to the \textbf{POJO Quick Start Guide} at {\url{https://github.com/h2oai/h2o-3/blob/master/h2o-docs/src/product/howto/POJO_QuickStart.md}}.
\subsection{Grid Search for Model Comparison}
\label{ssec:Grid search}
To enable grid search capabilities for model tuning, specify sets of values for parameter arguments that will configure certain parameters and then observe the changes in the model behavior. The following example represents a grid search:
\waterExampleInR
\lstinputlisting[style=R]{GBM_Vignette_code_examples/gbm_gridsearch.R}
\waterExampleInPython
\lstinputlisting[style=python]{GBM_Vignette_code_examples/gbm_gridsearch.py}
This example specifies three different tree numbers, three different tree sizes, and two different shrinkage values. This grid search model effectively trains eighteen different models over the possible combinations of these parameters.
Of course, sets of other parameters can be specified for a larger space of models. This allows for more subtle insights in the model tuning and selection process, especially during inspection and comparison of the trained models after the grid search process is complete. To decide how and when to choose different parameter configurations in a grid search, refer to {\textbf{\nameref{ssec:Model Parameters}}} for parameter descriptions and suggested values.
\begin{minipage}{\textwidth}
\waterExampleInR
\lstinputlisting[style=R]{GBM_Vignette_code_examples/gbm_gridsearch_result.R}
\waterExampleInPython
\lstinputlisting[style=python]{GBM_Vignette_code_examples/gbm_gridsearch_result.py}
\end{minipage}
\newpage
\subsection{ Model Parameters}
\label{ssec:Model Parameters}
This section describes the functions of the parameters for GBM.
\begin{itemize}
\item {\texttt{x}}: A vector containing the names of the predictors to use while building the GBM model.
\item {\texttt{y}}: A character string or index that represents the response variable in the model.
\item {\texttt{training\_frame}}: An \texttt{H2OFrame} object containing the variables in the model.
\item {\texttt{validation\_frame}}: An \texttt{H2OFrame} object containing the validation dataset used to construct confusion matrix. If blank, the training data is used by default.
\item {\texttt{nfolds}}: Number of folds for cross-validation.
\item {\texttt{ignore\_const\_cols}}: A boolean indicating if constant columns should be ignored. The default is {\texttt{TRUE}}.
\item {\texttt{ntrees}}: A non-negative integer that defines the number of trees. The default is 50.
\item {\texttt{max\_depth}}: The user-defined tree depth. The default is 5.
\item {\texttt{min\_rows}}: The minimum number of rows to assign to the terminal nodes. The default is 10.
\item {\texttt{nbins}}: For numerical columns (real/int), build a histogram of at least the specified number of bins, then split at the best point The default is 20.
\item {\texttt{nbins\_cats}}: For categorical columns (enum), build a histogram of the specified number of bins, then split at the best point. Higher values can lead to more overfitting. The default is 1024. \label{nbins_cats}
\item {\texttt{seed}}: Seed containing random numbers that affects sampling.
\item {\texttt{learn\_rate}}: An integer that defines the learning rate. The default is 0.1 and the range is 0.0 to 1.0.
\item {\texttt{distribution}}: The distribution function options: {\texttt{AUTO, bernoulli, multinomial, gaussian, poisson, gamma}} or {\texttt{tweedie}}. The default is {\texttt{AUTO}}.
\item {\texttt{score\_each\_iteration}}: A boolean indicating whether to score during each iteration of model training. The default is {\texttt{FALSE}}.
\item \texttt{fold\_assignment}: Cross-validation fold assignment scheme, if \\ \texttt{fold\_column} is not specified. The following options are supported: \texttt{AUTO, Random,} or \texttt{Modulo}.
\item \texttt{fold\_column}: Column with cross-validation fold index assignment per observation.
\item \texttt{offset\_column}: Specify the offset column. {\textbf{Note}}: Offsets are per-row “bias values” that are used during model training. For Gaussian distributions, they can be seen as simple corrections to the response (y) column. Instead of learning to predict the response (y-row), the model learns to predict the (row) offset of the response column. For other distributions, the offset corrections are applied in the linearized space before applying the inverse link function to get the actual response values.
\item \texttt{weights\_column}: Specify the weights column. {\textbf{Note}}: Weights are per-row observation weights. This is typically the number of times a row is repeated, but non-integer values are supported as well. During training, rows with higher weights matter more, due to the larger loss function pre-factor.
\item {\texttt{balance\_classes}}: Balance training data class counts via over or undersampling for imbalanced data. The default is {\texttt{FALSE}}.
\item {\texttt{max\_confusion\_matrix\_size}}: Maximum size (number of classes) for confusion matrices to print in the H2O logs. The default is 20.
\item {\texttt{max\_hit\_ratio\_k}}: (for multi-class only) Maximum number (top K) of predictions to use for hit ratio computation. To disable, enter {\texttt{0}}. The default is 10.
\item {\texttt{r2\_stopping}}: Stop making trees when the $R^2$ metric equals or exceeds this value. The default is 0.999999.
\item \texttt{regression\_stop}: Specifies the stopping criterion for regression error (MSE) on the training data scoring dataset. When the error is at or below this threshold, training stops. The default is 1e-6. To disable, specify \texttt{-1}.
\item \texttt{stopping\_rounds}: Early stopping based on convergence of \\\texttt{stopping\_metric}. Stop if simple moving average of length k of the \texttt{stopping\_metric} does not improve for k:=\texttt{stopping\_rounds} scoring events. Can only trigger after at least 2k scoring events. To disable, specify \texttt{0}.
\item \texttt{stopping\_metric}: Metric to use for early stopping (\texttt{AUTO}: \texttt{logloss} for classification, \texttt{deviance} for regression). Can be any of \texttt{AUTO, deviance, logloss, MSE, AUC, r2, misclassification}.
\item \texttt{stopping\_tolerance}: Relative tolerance for metric-based stopping criterion Relative tolerance for metric-based stopping criterion (stop if relative improvement is not at least this much).
\item {\texttt{build\_tree\_one\_node}}: Specify if GBM should be run on one node only; no network overhead but fewer CPUs used. Suitable for small datasets. The default is {\texttt{FALSE}}.
\item {\texttt{tweedie\_power}}: A numeric specifying the power for the Tweedie function when \texttt{distribution = "tweedie"}. The default is 1.5.
\item {\texttt{checkpoint}}: Enter a model key associated with a previously-trained model. Use this option to build a new model as a continuation of a previously-generated model.
\item {\texttt{keep\_cross\_validation\_predictions}}: Specify whether to keep the predictions of the cross-validation models. The default is {\texttt{FALSE}}.
\item {\texttt{class\_sampling\_factors}}: Desired over/under-sampling ratios per class (in lexicographic order). If not specified, sampling factors will be automatically computed to obtain class balance during training. Requires \texttt{balance\_classes}.
\item {\texttt{max\_after\_balance\_size}}: Maximum relative size of the training data after balancing class counts; can be less than 1.0. The default is 5.
\item {\texttt{nbins\_top\_level}}: For numerical columns (real/int), build a histogram of (at most) this many bins at the root level, then decrease by factor of two per level.
\item \texttt{model\_id}: The unique ID assigned to the generated model. If not specified, an ID is generated automatically.
\end{itemize}
\newpage
\section{References}
\bibliographystyle{plainnat} %alphadin}
\nobibliography{bibliography.bib} %hides entire bibliography so just \bibentry items are included
%use \bibentry{bibname} (where bibname is the entry name in the bibliography) to include entries from bibliography.bib; double brackets {{ are required in .bib file to preserve capitalization
\bibentry{cliffgbm}
\bibentry{bias}
\bibentry{boost}
\bibentry{greedyfunction}
\bibentry{discussion}
\bibentry{additivelogistic}
\bibentry{esl}
\bibentry{h2osite}
\bibentry{h2odocs}
\bibentry{h2ogithubrepo}
\bibentry{h2odatasets}
\bibentry{h2ojira}
\bibentry{stream}
\bibentry{rdocs}
%Friedman, Jerome, Trevor Hastie, and Robert Tibshirani. {\textbf{``Additive Logistic Regression: A Statistical View of Boosting (With Discussion and a Rejoinder by the Authors).``}} \url{http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.aos/1016218223} The Annals of Statistics 28.2 (2000): 337-407
%Hastie, Trevor, Robert Tibshirani, and J Jerome H Friedman. {\textbf{``The Elements of Statistical Learning``}} \url{http://statweb.stanford.edu/~tibs/ElemStatLearn/printings/ESLII_print10.pdf}. Vol.1. N.p., page 339: Springer New York, 2001.
\newpage
\section{Authors}
\textbf{Cliff Click}
Cliff Click is the CTO and Co-Founder of H2O, makers of H2O, the open-source math and machine learning engine for Big Data. Cliff is invited to speak regularly at industry and academic conferences and has published many papers about HotSpot technology. He holds a PhD in Computer Science from Rice University and about 15 patents.
\textbf{Michal Malohlava}
Michal is a geek, developer, Java, Linux, programming languages enthusiast developing software for over 10 years. He obtained PhD from the Charles University in Prague in 2012 and post-doc at Purdue University. He participated in design and development of various systems including SOFA and Fractal component systems or jPapabench control system.
\textbf{Viraj Parmar}
Prior to joining H2O as a data and math hacker intern, Viraj worked in a research group at the MIT Center for Technology and Design. His interests are in software engineering and large-scale machine learning.
\textbf{Hank Roark}
Hank is a Data Scientist and Hacker at H2O. Hank comes to H2O with a background turning data into products and system solutions and loves helping others find value in their data. Hank has an SM from MIT in Engineering and Management and BS Physics from Georgia Tech.
\textbf{Arno Candel}
Arno is the Chief Architect of H2O, a distributed and scalable open-source machine learning platform and the main author of H2O Deep Learning. Arno holds a PhD and Masters summa cum laude in Physics from ETH Zurich, Switzerland. He has authored dozens of scientific papers and is a sought-after conference speaker. Arno was named “2014 Big Data All-Star” by Fortune Magazine. Follow him on Twitter: @ArnoCandel.
\textbf{Jessica Lanford}
Jessica is a word hacker and seasoned technical communicator at H2O.ai. She brings our product to life by documenting the many features and functionality of H2O. Having worked for some of the top companies in technology including Dell, AT$\&$T, and Lam Research, she is an expert at translating complex ideas to digestible articles.
\end{document}
|
Formal statement is: lemma continuous_at_within_inverse[continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous (at a within s) f" and "f a \<noteq> 0" shows "continuous (at a within s) (\<lambda>x. inverse (f x))" Informal statement is: If $f$ is a continuous function on a set $S$ and $f(a) \neq 0$, then the function $1/f$ is continuous at $a$. |
/-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import category_theory.single_obj
import category_theory.limits.shapes.products
import category_theory.pi.basic
import category_theory.limits.is_limit
/-!
# Category of groupoids
This file contains the definition of the category `Groupoid` of all groupoids.
In this category objects are groupoids and morphisms are functors
between these groupoids.
We also provide two “forgetting” functors: `objects : Groupoid ⥤ Type`
and `forget_to_Cat : Groupoid ⥤ Cat`.
## Implementation notes
Though `Groupoid` is not a concrete category, we use `bundled` to define
its carrier type.
-/
universes v u
namespace category_theory
/-- Category of groupoids -/
@[nolint check_univs] -- intended to be used with explicit universe parameters
def Groupoid := bundled groupoid.{v u}
namespace Groupoid
instance : inhabited Groupoid := ⟨bundled.of (single_obj punit)⟩
instance str (C : Groupoid.{v u}) : groupoid.{v u} C.α := C.str
/-- Construct a bundled `Groupoid` from the underlying type and the typeclass. -/
def of (C : Type u) [groupoid.{v} C] : Groupoid.{v u} := bundled.of C
/-- Category structure on `Groupoid` -/
instance category : large_category.{max v u} Groupoid.{v u} :=
{ hom := λ C D, C.α ⥤ D.α,
id := λ C, 𝟭 C.α,
comp := λ C D E F G, F ⋙ G,
id_comp' := λ C D F, by cases F; refl,
comp_id' := λ C D F, by cases F; refl,
assoc' := by intros; refl }
/-- Functor that gets the set of objects of a groupoid. It is not
called `forget`, because it is not a faithful functor. -/
def objects : Groupoid.{v u} ⥤ Type u :=
{ obj := bundled.α,
map := λ C D F, F.obj }
/-- Forgetting functor to `Cat` -/
def forget_to_Cat : Groupoid.{v u} ⥤ Cat.{v u} :=
{ obj := λ C, Cat.of C.α,
map := λ C D, id }
instance forget_to_Cat_full : full forget_to_Cat :=
{ preimage := λ C D, id }
instance forget_to_Cat_faithful : faithful forget_to_Cat := { }
/-- Convert arrows in the category of groupoids to functors,
which sometimes helps in applying simp lemmas -/
lemma hom_to_functor {C D E : Groupoid.{v u}} (f : C ⟶ D) (g : D ⟶ E) : f ≫ g = f ⋙ g := rfl
section products
/-- The cone for the product of a family of groupoids indexed by J is a limit cone -/
@[simps]
def pi_limit_cone {J : Type u} (F : discrete J ⥤ Groupoid.{u u}) :
limits.limit_cone F :=
{ cone :=
{ X := @of (Π j : J, (F.obj j).α) _,
π := { app := λ j : J, category_theory.pi.eval _ j, } },
is_limit :=
{ lift := λ s, functor.pi' s.π.app,
fac' := by { intros, simp [hom_to_functor], },
uniq' :=
begin
intros s m w,
apply functor.pi_ext,
intro j, specialize w j,
simpa,
end } }
/-- `pi_limit_cone` reinterpreted as a fan -/
abbreviation pi_limit_fan {J : Type u} (F : J → Groupoid.{u u}) : limits.fan F :=
(pi_limit_cone (discrete.functor F)).cone
instance has_pi : limits.has_products Groupoid.{u u} :=
λ J, { has_limit := λ F, { exists_limit := nonempty.intro (pi_limit_cone F) } }
/-- The product of a family of groupoids is isomorphic
to the product object in the category of Groupoids -/
noncomputable def pi_iso_pi (J : Type u) (f : J → Groupoid.{u u}) : @of (Π j, (f j).α) _ ≅ ∏ f :=
limits.is_limit.cone_point_unique_up_to_iso
(pi_limit_cone (discrete.functor f)).is_limit
(limits.limit.is_limit (discrete.functor f))
@[simp]
lemma pi_iso_pi_hom_π (J : Type u) (f : J → Groupoid.{u u}) (j : J) :
(pi_iso_pi J f).hom ≫ (limits.pi.π f j) = category_theory.pi.eval _ j :=
by { simp [pi_iso_pi], refl, }
end products
end Groupoid
end category_theory
|
!> @file
!! Module to load environment variables and store tem in global variables
!! It can be used bu developers for tune futile behaviour
!! as well as the verbosity of the output
!! like operations on external files and basic operations in memory
!! @author
!! Copyright (C) 2016-2016 BigDFT group
!! This file is distributed under the terms of the
!! GNU General Public License, see ~/COPYING file
!! or http://www.gnu.org/copyleft/gpl.txt .
!! For the list of contributors, see ~/AUTHORS
module f_environment
implicit none
!these variables have to be accessed by all the associating routines
public
!> simple flag to see if we are in debug mode or not
logical :: f_debug=.false.
!> integer flag specifying the debug level
integer :: f_debug_level=0
!> flag to sontrol if we are in simulation mode
logical :: f_simulation_mode=.false.
!> ndebug integer, associated to the extra elements which are padded with NaN (whenever possible)
!! in the last dimension of the array
integer :: f_nan_pad_size=0
!> memorylimit of the allocation, raise an error whenever the allocated buffers pass above a given threshold
integer :: f_memorylimit=0
!> maximum depth of the profiling routines (unlimited by default)
integer :: f_maximum_profiling_depth=-1
interface f_getenv
module procedure getenv_i0,getenv_l0
end interface f_getenv
private :: getenv_i0,getenv_l0
contains
subroutine f_environment_acquire()
implicit none
call f_getenv('FUTILE_DEBUG_MODE',f_debug_level)
f_debug = f_debug_level /= 0
call f_getenv('FUTILE_SIMULATION_MODE',f_simulation_mode)
call f_getenv('FUTILE_MALLOC_NAN_PADDING',f_nan_pad_size)
call f_getenv('FUTILE_MEMORYLIMIT_GB',f_memorylimit)
call f_getenv('FUTILE_PROFILING_DEPTH',f_maximum_profiling_depth)
end subroutine f_environment_acquire
subroutine getenv_i0(envvar,data)
implicit none
character(len=*), intent(in) :: envvar
integer, intent(inout) :: data
!local variables
integer :: istat,idum
character(len=8) :: val
call get_environment_variable(envvar,val,status=istat)
if (istat==0) then
read(val,*)idum !let it crash if the reading is unsafe
data=idum
end if
end subroutine getenv_i0
subroutine getenv_l0(envvar,data)
implicit none
character(len=*), intent(in) :: envvar
logical, intent(inout) :: data
!local variables
integer :: istat,idum
character(len=8) :: val
call get_environment_variable(envvar,val,status=istat)
if (istat==0) then
read(val,*)idum !let it crash if the reading is unsafe
data=idum==1
end if
end subroutine getenv_l0
end module f_environment
|
Range : 2 @,@ 200 km ( 1 @,@ 367 miles )
|
program tabchk
c
c***********************************************************************
c
c dl_poly utility to check accuracy of tabulation procedures
c
c copyright daresbury laboratory 1994
c author - t.forester october 1994
c
c***********************************************************************
c
implicit real*8(a-h,o-z)
parameter (mega=10000,mxvdw=1000,mxpvdw=5)
parameter (nfield=10)
character*8 atom1,atom2
character*80 record
dimension parvdw(mxpvdw)
dimension lstvdw(mxvdw),ltpvdw(mxvdw),prmvdw(mxvdw,mxpvdw)
write(*,*) 'trial mxgrid '
read(*,*) ngrid
ngrid = max(ngrid,5)
write(*,*)
write(*,*) 'trial cutoff ?'
read(*,*) rcut
write(*,*)
write(*,*) ' what is the minimum permitted pair separation ?'
read(*,*) rmin
write(*,*)
write(*,*) 'number of test points ? (eg. 2311) '
read(*,*) npts
npts = max(npts,2)
c
c increment for distance
dr = (rcut-rmin)/dble(npts-1)
c
c set up constants
idnode=0
mxnode = 1
keyvdw = 0
open(nfield,file='FIELD')
c
c search for vdw tables
do irec = 1,mega
read(nfield,'(a80)') record
call lowcase(record,80)
call strip(record,80)
if(record(1:3).eq.'vdw') then
ntpvdw=intstr(record,80,idum)
if(ntpvdw.gt.mxvdw) call error(idnode,80)
do ivdw=1,mxvdw
lstvdw(ivdw)=0
enddo
do itpvdw=1,ntpvdw
do i=1,mxpvdw
parvdw(i)=0.d0
enddo
read(nfield,'(2a8,i5,5f12.0)',end=9999)
x atom1,atom2,keypot,parvdw
keyvdw=keyvdw + 1
if(keyvdw.gt.mxvdw) call error(idnode,82)
lstvdw(keyvdw)=itpvdw
ltpvdw(itpvdw)=keypot
do i=1,5
prmvdw(itpvdw,i)=parvdw(i)
enddo
enddo
elseif(record(1:5).eq.'close')then
close (nfield)
goto 100
endif
enddo
c
c uncontrolled error exit from field file procesing
close (nfield)
call error(idnode,16)
c
c end of field file error exit
9999 close (nfield)
call error(idnode,52)
c
c evaluate accuracy of tabulation procedures
100 continue
c
c begin testing
do iter = 1,3
write(*,*)
write(*,*)
if(iter.eq.1) then
c
c three point interpolation
write(*,*) 'Three point interpolation: '
dlrpot = rcut/dble(ngrid-4)
elseif(iter.eq.2) then
write(*,*) 'four point interpolation '
dlrpot = rcut/dble(ngrid-4)
elseif(iter.eq.3) then
write(*,*) 'r-squared 2 point interpolation '
dlrpot = (rcut**2)/dble(ngrid-4)
endif
write(*,*) ' functions : ',ntpvdw
write(*,'(/,45x,a,60x,a)') 'energies','forces'
write(*,'(1x,4(22x,a))') 'absolute error','relative error',
x 'absolute error','relative error'
write(*,'(a,5x,4(a,3x))') 'ivdw',
x 'maximum mean variance ',
x 'maximum mean variance ',
x ' maximum mean variance ',
x 'maximum mean variance'
rdlpot = 1.d0/dlrpot
do ivdw = 1,ntpvdw
ltp = ltpvdw(ivdw)
aev=0.d0
aeg=0.d0
rev=0.d0
reg=0.d0
accv=0.d0
ac2v=0.d0
arcv=0.d0
ar2v=0.d0
accg=0.d0
ac2g=0.d0
arcg=0.d0
ar2g=0.d0
do ii = 0,npts-1
rrr = rmin + dble(ii)*dr
call lookup(ltp,ivdw,rrr,exactv,exactg,prmvdw)
if(iter.eq.1) then
call three(ltp,ivdw,rrr,dlrpot,engsrp,gamma,prmvdw)
elseif(iter.eq.2) then
call four(ltp,ivdw,rrr,dlrpot,engsrp,gamma,prmvdw)
elseif(iter.eq.3) then
call rsquare(ltp,ivdw,rrr,dlrpot,engsrp,gamma,prmvdw)
endif
c
c absolute errors
errv = engsrp - exactv
errg = gamma - exactg
c
c make sure both non-zero!!!
ev = sign(max(abs(exactv),1.d-6),exactv)
eg = sign(max(abs(exactg),1.d-6),exactg)
c
c relative errors
relv = errv/ev
relg = errg/eg
c
c maximum solute error in forces and energy
aev = max(aev,abs(errv))
aeg = max(aeg,abs(errg))
rev= max(rev,abs(relv))
reg= max(reg,abs(relg))
c
c accumulators for mean error + sd
accv = accv + errv
ac2v = ac2v + errv*errv
accg = accg + errg
ac2g = ac2g + errg*errg
c
c accumulators for mean relative error + sd
arcv = arcv + relv
ar2v = ar2v + relv*relv
arcg = arcg + relg
ar2g = ar2g + relg*relg
enddo
c
c report on errors
averv = accv/dble(npts)
vdv = abs((ac2v - accv**2)/dble(npts-1))
averg = accg/dble(npts)
vdg = abs((ac2g - accg**2)/dble(npts-1))
avrv = arcv/dble(npts)
vrdv = abs((ar2v - arcv**2)/dble(npts-1))
avrg = arcg/dble(npts)
vrdg = abs((ar2g - arcg**2)/dble(npts-1))
write(*,'(i4,1p,6e12.4,3x,6e12.4)')
x ivdw,aev,averv,vdv,rev,avrv,vrdv,aeg,averg,vdg,
x reg,avrg,vrdg
enddo
enddo
end
subroutine lookup(ltp,ivdw,rrr,eng,for,prmvdw)
c*********************************************************************
c
c copyright daresbury laboratory
c author t.forester
c
c*********************************************************************
implicit real*8(a-h,o-z)
parameter (mxvdw=1000,mxpvdw=5)
dimension prmvdw(mxvdw,mxpvdw)
c
c 12 - 6 potential
vv1(r,a,b)=(a/r**6-b)/r**6
gg1(r,a,b)=6.d0*(2.d0*a/r**6-b)/r**6
c
c lennard-jones potential
vv2(r,a,b)=4.d0*a*(b/r)**6*((b/r)**6-1.d0)
gg2(r,a,b)=24.d0*a*(b/r)**6*(2.d0*(b/r)**6-1.d0)
c
c n - m potential
vv3(r,a,b,c,d)=a/(b-c)*(c*(d/r)**b-b*(d/r)**c)
gg3(r,a,b,c,d)=a*c*b/(b-c)*((d/r)**b-(d/r)**c)
c
c buckingham exp - 6 potential
vv4(r,a,b,c)=a*exp(-r/b)-c/r**6
gg4(r,a,b,c)=r*a*exp(-r/b)/b-6.d0*c/r**6
c
c born-huggins-meyer exp - 6 - 8 potential
vv5(r,a,b,c,d,e)=a*exp(b*(c-r))-d/r**6-e/r**8
gg5(r,a,b,c,d,e)=r*a*b*exp(b*(c-r))-6.d0*d/r**6-8.d0*e/r**8
c
c Hydrogen-bond 12 - 10 potential
vv6(r,a,b) = a/r**12 - b/r**10
gg6(r,a,b) = 12.0d0*a/r**12 - 10.d0*b/r**10
if(ltp.eq.1) then
eng = vv1(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2))
for = gg1(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2))
elseif(ltp.eq.2) then
eng = vv2(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2))
for = gg2(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2))
elseif(ltp.eq.3) then
eng = vv3(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2),
x prmvdw(ivdw,3),prmvdw(ivdw,4))
for = gg3(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2),
x prmvdw(ivdw,3),prmvdw(ivdw,4))
elseif(ltp.eq.4) then
eng = vv4(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2),
x prmvdw(ivdw,3))
for = gg4(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2),
x prmvdw(ivdw,3))
elseif(ltp.eq.5) then
eng = vv5(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2),
x prmvdw(ivdw,3),prmvdw(ivdw,4),prmvdw(ivdw,5))
for = gg5(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2),
x prmvdw(ivdw,3),prmvdw(ivdw,4),prmvdw(ivdw,5))
elseif(ltp.eq.6) then
eng = vv6(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2))
for = gg6(rrr,prmvdw(ivdw,1),prmvdw(ivdw,2))
else
call error(0,150)
endif
return
end
subroutine three(ltp,ivdw,rrr,dlrpot,engsrp,gamma,prmvdw)
c*********************************************************************
c
c mimic 3pt interpolation
c
c copyright daresbury laboratory
c author t.forester
c
c*********************************************************************
implicit real*8(a-h,o-z)
parameter (mxvdw=1000,mxpvdw=5)
dimension prmvdw(mxvdw,mxpvdw)
rdlpot = 1.d0/dlrpot
l=int(rrr*rdlpot)
ppp=rrr*rdlpot-dble(l)
c
c calculate interaction energy using 3-point interpolation
r0 = dble(l)*dlrpot
call lookup(ltp,ivdw,r0,vk,gk,prmvdw)
r1 = dble(l+1)*dlrpot
call lookup(ltp,ivdw,r1,vk1,gk1,prmvdw)
r2 = dble(l+2)*dlrpot
call lookup(ltp,ivdw,r2,vk2,gk2,prmvdw)
t1 = vk + (vk1-vk)*ppp
t2 = vk1 +(vk2 - vk1)*(ppp - 1.0d0)
engsrp = t1 + (t2-t1)*ppp*0.5d0
c
c calculate forces using 3-point interpolation
t1 = gk + (gk1-gk)*ppp
t2 = gk1 + (gk2-gk1)*(ppp - 1.0d0)
gamma = (t1 +(t2-t1)*ppp*0.5d0)
return
end
subroutine four(ltp,ivdw,rrr,dlrpot,engsrp,gamma,prmvdw)
c*********************************************************************
c
c mimic 4pt interpolation
c
c copyright daresbury laboratory
c author t.forester
c
c*********************************************************************
implicit real*8(a-h,o-z)
parameter (mxvdw=1000,mxpvdw=5)
dimension prmvdw(mxvdw,mxpvdw)
rdlpot = 1.d0/dlrpot
l=int(rrr*rdlpot)
ppp=rrr*rdlpot-dble(l)
c
c calculate interaction energy using 3-point interpolation
rm = dble(l-1)*dlrpot
call lookup(ltp,ivdw,rm,vkm,gkm,prmvdw)
r0 = dble(l)*dlrpot
call lookup(ltp,ivdw,r0,vk,gk,prmvdw)
r1 = dble(l+1)*dlrpot
call lookup(ltp,ivdw,r1,vk1,gk1,prmvdw)
r2 = dble(l+2)*dlrpot
call lookup(ltp,ivdw,r2,vk2,gk2,prmvdw)
engsrp=vk+
x ppp*(-2.d0*vkm-3.d0*vk+6.d0*vk1-vk2+
x ppp*(3.d0*(vkm-vk-vk+vk1)+
x ppp*(-vkm+vk2+3.d0*(vk-vk1))))/6.d0
c
c calculate forces using 4-point interpolation
gamma=gk+
x ppp*(-2.d0*gkm-3.d0*gk+6.d0*gk1-gk2+
x ppp*(3.d0*(gkm-gk-gk+gk1)+
x ppp*(-gkm+gk2+3.d0*(gk-gk1))))/6.d0
return
end
subroutine rsquare(ltp,ivdw,rrr,dlrpot,engsrp,gamma,prmvdw)
c*********************************************************************
c
c mimic r-squared interpolation
c
c copyright daresbury laboratory
c author t.forester
c
c*********************************************************************
implicit real*8(a-h,o-z)
parameter (mxvdw=1000,mxpvdw=5)
dimension prmvdw(mxvdw,mxpvdw)
rdlpot = 1.d0/dlrpot
rsq = rrr*rrr
l=int(rsq*rdlpot)
ppp=rsq*rdlpot-dble(l)
c
c calculate interaction energy using 2-point interpolation
r0 = sqrt(dble(l)*dlrpot)
call lookup(ltp,ivdw,r0,vk,gk,prmvdw)
r1 = sqrt(dble(l+1)*dlrpot)
call lookup(ltp,ivdw,r1,vk1,gk1,prmvdw)
engsrp=vk+ (vk1-vk)*ppp
c
c calculate forces using 2-point interpolation
gamma=gk+(gk1-gk)*ppp
return
end
subroutine strip(string,length)
c***********************************************************************
c
c DL_POLY routine to strip blanks from start of a string
c maximum length is 255 characters
c
c copyright daresbury laboratory 1993
c author t.forester july 1993
c
c***********************************************************************
implicit real*8(a-h,o-z)
character*(*) string
imax = min(length,255)
do i = 1,imax
if(string(1:1).eq.' ') then
do j = 1,imax-1
string(j:j) = string(j+1:j+1)
enddo
string(imax:imax) = ' '
endif
enddo
return
end
subroutine lowcase(string,length)
c***********************************************************************
c
c DL_POLY routine to lowercase a string of up to 255 characters.
c Transportable to non-ASCII machines
c
c copyright daresbury laboratory 1993
c author t. forester july 1993
c
c***********************************************************************
implicit real*8(a-h,o-z)
character*(*) string
character*1 letter
do i = 1,min(255,length)
letter = string(i:i)
if(letter.eq.'A') letter = 'a'
if(letter.eq.'B') letter = 'b'
if(letter.eq.'C') letter = 'c'
if(letter.eq.'D') letter = 'd'
if(letter.eq.'E') letter = 'e'
if(letter.eq.'F') letter = 'f'
if(letter.eq.'G') letter = 'g'
if(letter.eq.'H') letter = 'h'
if(letter.eq.'I') letter = 'i'
if(letter.eq.'J') letter = 'j'
if(letter.eq.'K') letter = 'k'
if(letter.eq.'L') letter = 'l'
if(letter.eq.'M') letter = 'm'
if(letter.eq.'N') letter = 'n'
if(letter.eq.'O') letter = 'o'
if(letter.eq.'P') letter = 'p'
if(letter.eq.'Q') letter = 'q'
if(letter.eq.'R') letter = 'r'
if(letter.eq.'S') letter = 's'
if(letter.eq.'T') letter = 't'
if(letter.eq.'U') letter = 'u'
if(letter.eq.'V') letter = 'v'
if(letter.eq.'W') letter = 'w'
if(letter.eq.'X') letter = 'x'
if(letter.eq.'Y') letter = 'y'
if(letter.eq.'Z') letter = 'z'
string(i:i) = letter
enddo
return
end
function intstr(word,len,lst)
c
c***********************************************************************
c
c dl_poly function for extracting integers from a
c character string
c
c copyright - daresbury laboratory 1994
c author - w. smith may 1994.
c
c parameters:
c word - input character string
c len - working length of character string
c lst - location of space character at end of
c integer string
c
c***********************************************************************
c
implicit real*8(a-h,o-z)
character*1 n(0:9),word(len),ksn
logical flag,final
data n/'0','1','2','3','4','5','6','7','8','9'/
isn=1
ksn='+'
intstr=0
final=.false.
do lst=1,len
flag=.false.
do j=0,9
if(n(j).eq.word(lst))then
intstr=10*intstr+j
flag=.true.
endif
enddo
if(flag.and.ksn.eq.'-')isn=-1
ksn=word(lst)
if(flag)then
final=.true.
else
if(final)then
intstr=isn*intstr
return
endif
endif
enddo
return
end
subroutine error(idnode,iode)
c
c***********************************************************************
c
c dl_poly subroutine for printing error messages and bringing
c about a controlled termination of the program
c
c copyright - daresbury laboratory 1992
c author - w. smith march 1992.
c amended - t.forester sept 1994
c
c warning - this routine will terminate the job if iode > 0.
c Users must ensure that all nodes are informed of error condition
c efore this subroutine is called. e.g. using subroutine gstate().
c
c***********************************************************************
c
implicit real*8(a-h,o-z)
logical kill
kill=(iode.ge.0)
kode = abs(iode)
if(idnode.eq.0) then
if(kill) then
write(nrite,'(//,1x,a,i5)')
x 'TABCHK terminated due to error ', kode
else
write(nrite,'(//,1x,a,i5)')
x 'TABCHK will terminate due to error ', kode
endif
if (kode.eq. 0) then
c
c dummy entry
elseif (kode.eq.16) then
write(nrite,'(//,1x,a)')
x 'error - strange exit from FIELD file processing'
elseif (kode.eq.52) then
write(nrite,'(//,1x,a)')
x 'error - end of FIELD file encountered'
elseif (kode.eq.80) then
write(nrite,'(//,1x,a)')
x 'error - too many pair potentials specified'
elseif (kode.eq.82) then
write(nrite,'(//,1x,a)')
x 'error - calculated pair potential index too large'
elseif (kode.eq.150) then
write(nrite,'(//,1x,a)')
x 'error - unknown van der waals potential selected'
else
write(nrite,'(//,1x,a)')
x 'error - unnamed error found'
endif
endif
if (kill) then
call exit()
endif
return
end
|
[STATEMENT]
lemma mset_remdups: "mset (remdups xs) = mset_set (set xs)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. mset (remdups xs) = mset_set (set xs)
[PROOF STEP]
proof (induction xs)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. mset (remdups []) = mset_set (set [])
2. \<And>a xs. mset (remdups xs) = mset_set (set xs) \<Longrightarrow> mset (remdups (a # xs)) = mset_set (set (a # xs))
[PROOF STEP]
case (Cons x xs)
[PROOF STATE]
proof (state)
this:
mset (remdups xs) = mset_set (set xs)
goal (2 subgoals):
1. mset (remdups []) = mset_set (set [])
2. \<And>a xs. mset (remdups xs) = mset_set (set xs) \<Longrightarrow> mset (remdups (a # xs)) = mset_set (set (a # xs))
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
mset (remdups xs) = mset_set (set xs)
goal (1 subgoal):
1. mset (remdups (x # xs)) = mset_set (set (x # xs))
[PROOF STEP]
by (cases "x \<in> set xs") (auto simp: insert_absorb)
[PROOF STATE]
proof (state)
this:
mset (remdups (x # xs)) = mset_set (set (x # xs))
goal (1 subgoal):
1. mset (remdups []) = mset_set (set [])
[PROOF STEP]
qed auto |
[STATEMENT]
lemma of_rat_lec_sum: "of_rat_lec (sum_list c) = sum_list (map of_rat_lec c)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. of_rat_lec (sum_list c) = sum_list (map of_rat_lec c)
[PROOF STEP]
by (induct c, auto simp: of_rat_lec_zero of_rat_lec_add) |
function [e1,e2,E1_l,E2_l,E1_s1,E2_s2] = pluckerEndpoints(L,s1,s2)
% PLUCKERENDPOINTS Plucker line and abscissas to endpoints conversion.
% [E1,E2] = PLUCKERENDPOINTS(L,S1,S2) are the endpoints of the Plucker
% line L at abscissas S1 and S2.
%
% [E1,E2,E1_l,E2_l,E1_s1,E2_s2] = PLUCKERENDPOINTS(L,S1,S2) returns the
% Jacobians wrt the line L and the abscissas S1 and S2.
%
% See also LS2E, LS2SEG.
% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.
v = L(4:6);
if nargout == 1
vn = normvec(v);
p0 = pluckerOrigin(L);
e1 = p0 + s1*vn;
e2 = p0 + s2*vn;
else % Jac
[vn,VN_v] = normvec(v,0);
[p0,P0_l] = pluckerOrigin(L);
P0_n = P0_l(:,1:3);
P0_v = P0_l(:,4:6);
e1 = p0 + s1*vn;
E1_s1 = vn;
E1_n = P0_n;
E1_v = P0_v + s1*VN_v;
E1_l = [E1_n E1_v];
e2 = p0 + s2*vn;
E2_s2 = vn;
E2_n = P0_n;
E2_v = P0_v + s2*VN_v;
E2_l = [E2_n E2_v];
end
return
%% jac
syms n1 n2 n3 v1 v2 v3 s1 s2 real
L = [n1;n2;n3;v1;v2;v3];
[e1,e2,E1_l,E2_l,E1_s1,E2_s2] = pluckerEndpoints(L,s1,s2);
simplify(E1_l - jacobian(e1,L))
simplify(E2_l - jacobian(e2,L))
simplify(E1_s1 - jacobian(e1,s1))
simplify(E2_s2 - jacobian(e2,s2))
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB 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.
%
% SLAMTB 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 SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
library(raster)
library(watershed)
library(sf)
library(units)
data("kamp_dem")
kamp = delineate(kamp_dem)
kv = vectorise_stream(kamp[["stream"]])
par(mar=c(4,4,4,4))
xl = c(4679000, 4689000) + 5000 * c(-1, 1)
yl = c(2835000, 2846000) + 5000 * c(-1, 1)
plot(kamp_dem, col=terrain.colors(20), axes = TRUE, xlim=xl, ylim=yl)
plot(st_geometry(kv), col='blue', add = TRUE)
rect(4675000, 2835000, 4689700, 2846300, border='red')
kamp_dem_sm = crop(kamp_dem, raster::extent(c(4675000, 4689700, 2835000, 2846300)))
saveRDS(kamp_dem_sm, "inst/testdata/kamp_dem_sm.rds")
kamp_sm = delineate(kamp_dem_sm)
## warning - a topological error. we can kill this
Tp = pixel_topology(kamp_sm)
kv_sm = vectorise_stream(kamp_sm[["stream"]])
plot(kamp_dem_sm, col=terrain.colors(20), axes = FALSE)
plot(st_geometry(kv_sm), col='blue', add = TRUE)
## prep some data for hydrology test
ca = catchment(kamp_sm, type='reach')
kv_sm$ca = ca[kv_sm$reach_id]
data(kamp_q)
kamp_q2 = st_snap(kamp_q, kv, tolerance=100)
plot(kamp_dem_sm, col=terrain.colors(20), axes = FALSE)
plot(st_geometry(kv_sm), col='blue', add = TRUE)
plot(kamp_q, col='cyan', add=TRUE)
plot(kamp_q2, col='red', add=TRUE)
## save the other intermediate calculations
kamp_sm = readAll(kamp_sm)
saveRDS(kamp_sm, "inst/testdata/kamp_sm.rds")
saveRDS(kv_sm, "inst/testdata/kv_sm.rds")
## some points get duplicated, add a point ID to eliminate them
kamp_q2$id = 1:nrow(kamp_q2)
kamp_q2 = st_intersection(kamp_q2, kv_sm)
kamp_q2$id
kamp_q2 = kamp_q2[!duplicated(kamp_q2$id),]
units(kamp_q2$ca) = "m^2"
saveRDS(kamp_q2, "inst/testdata/kamp_q_sm.rds")
|
lemma convergent_mult_const_right_iff: fixes c :: "'a::{field,topological_semigroup_mult}" assumes "c \<noteq> 0" shows "convergent (\<lambda>n. f n * c) \<longleftrightarrow> convergent f" |
function [v,x,t,m,ze]=v_quadpeak(z)
%V_PEAK2DQUAD find quadratically-interpolated peak in a N-D array
%
% Inputs: Z(m,n,...) is the input array (ignoring trailing singleton dimensions)
% Note: a row vector will have 2 dimensions
%
% Outputs: V is the peak value
% X(:,1) is the position of the peak (in fractional subscript values)
% T is -1, 0, +1 for maximum, saddle point or minimum
% M defines the fitted quadratic: z = [x y ... 1]*M*[x y ... 1]'
% ZE the estimated version of Z
% Copyright (C) Mike Brookes 2008
% Version: $Id: v_quadpeak.m 10865 2018-09-21 17:22:45Z dmb $
%
% VOICEBOX is a MATLAB toolbox for speech processing.
% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You can obtain a copy of the GNU General Public License from
% http://www.gnu.org/copyleft/gpl.html or by writing to
% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
persistent wz a
% first calculate the fixed matrix, a (can be stored if sz is constant)
sz=size(z); % size of input array
psz=prod(sz); % number of elements in input array
dz=numel(sz); % number of input dimensions
mz=find(sz>1); % non-singleton dimension indices
nm=numel(mz); % number of non-singleton dimensions
vz=sz(mz); % size of squeezed input array
dx=max(mz); % number of output dimensions
if ~nm % if the input array is a scalar
error('Cannot find peak of a scalar');
end
nc=(nm+1)*(nm+2)/2; % number of columns in A matrix
if min(vz)<3
error('Need at least 3 points in each non-singleton dimension');
end
if isempty(wz) || numel(wz)~=numel(vz) || ~all(wz==vz)
wz=vz;
a=ones(psz,nc);
ix=(0:psz-1)';
for i=1:nm
jx=floor(ix/sz(mz(i)));
a(:,i+nc-nm-1)=1+ix-jx*sz(mz(i));
ix=jx;
a(:,(i^2-i+2)/2:i*(i+1)/2)=a(:,nc-nm:i+nc-nm-1).*repmat(a(:,i+nc-nm-1),1,i);
end
a=(a'*a)\a'; % converts to polynomial coeficients {x^2 xy y^2 x y 1]
end
% now find the peak
c=a*z(:); % polynomial coefficients for this data
w=zeros(nm+1,nm+1);
i=1:(nm+1)*(nm+2)/2;
j=floor((sqrt(8*i-7)-1)/2);
w(i+j.*(2*nm+1-j)/2)=c;
w=(w+w.')/2; % make it symmetrical
mr=w(1:nm,1:nm);
we=w(1:nm,nm+1);
y=-(mr\we);
v=y'*we+w(nm+1,nm+1); % value at peak
% insert singleton dimensions into outputs
x=zeros(dx,1);
x(mz)=y;
m=zeros(dx+1,dx+1);
mz(nm+1)=dx+1;
m(mz,mz)=w;
if nargout>2
ev=eig(mr);
t=all(ev>0)-all(ev<0);
end
if nargout>4
ze=zeros(sz);
scp=cumprod([1 sz(1:end-1)]);
ivec=fix(repmat((0:psz-1)',1,dz)./repmat(scp,psz,1));
xe=[1+ivec-repmat(sz,psz,1).*fix(ivec./repmat(sz,psz,1)) ones(psz,1)];
ze=reshape(sum((xe*m).*xe,2),sz);
end
if ~nargout && nm<=2
% plot the data
desc={'Maximum','Saddle Point','Minimum'};
if nargout<=2
ev=eig(mr);
t=all(ev>0)-all(ev<0);
end
if nm==1
xax=linspace(1,psz,100);
plot(xax,c(1)*xax.^2+c(2)*xax+c(3),'-r',1:psz,z(:),'ob',x,v,'^k');
set(gca,'xlim',[0.9 psz+0.1]);
ylabel('z');
xlabel(sprintf('x%d',mz(1)));
title(sprintf('\\Delta = %s: z(%.2g) = %.2g',desc{t+2},y(1),v));
else
ngr=17;
xax=repmat(linspace(1,vz(1),ngr)',1,ngr);
yax=repmat(linspace(1,vz(2),ngr),ngr,1);
zq=(c(1)*xax+c(2)*yax+c(4)).*xax+(c(3)*yax+c(5)).*yax+c(6);
hold off
mesh(xax,yax,zq,'EdgeColor','r');
hold on
plot3(repmat((1:vz(1))',1,vz(2)),repmat(1:vz(2),vz(1),1),reshape(z,vz),'ob',y(1),y(2),v,'^k');
hold off
set(gca,'xlim',[0.9 vz(1)+0.1],'ylim',[0.9 vz(2)+0.1]);
xlabel(sprintf('x%d',mz(1)));
ylabel(sprintf('x%d',mz(2)));
zlabel('z');
title(sprintf('\\Delta = %s: z(%.2g,%.2g) = %.2g',desc{t+2},y(1),y(2),v));
end
end
|
theory sort_QSortSorts
imports Main
"$HIPSTER_HOME/IsaHipster"
begin
datatype 'a list = Nil2 | Cons2 "'a" "'a list"
fun filter :: "('t => bool) => 't list => 't list" where
"filter p (Nil2) = Nil2"
| "filter p (Cons2 y z) =
(if p y then Cons2 y (filter p z) else filter p z)"
fun append :: "'a list => 'a list => 'a list" where
"append (Nil2) y = y"
| "append (Cons2 z xs) y = Cons2 z (append xs y)"
fun qsort :: "int list => int list" where
"qsort (Nil2) = Nil2"
| "qsort (Cons2 y xs) =
append
(append
(qsort (filter (% (z :: int) => z <= y) xs)) (Cons2 y (Nil2)))
(qsort (filter (% (x2 :: int) => x2 > y) xs))"
fun and2 :: "bool => bool => bool" where
"and2 True y = y"
| "and2 False y = False"
fun ordered :: "int list => bool" where
"ordered (Nil2) = True"
| "ordered (Cons2 y (Nil2)) = True"
| "ordered (Cons2 y (Cons2 y2 xs)) =
and2 (y <= y2) (ordered (Cons2 y2 xs))"
(*hipster filter append qsort and2 ordered *)
theorem x0 :
"!! (x :: int list) . ordered (qsort x)"
by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>)
end
|
[STATEMENT]
lemma increasing_conv_subseq_fun_0:
assumes "s \<in> closed_seqs Zp"
assumes "\<exists>s'. s' = convergent_subseq s"
assumes "a = acc_point s"
shows "convergent_subseq_fun s a (Suc n) > convergent_subseq_fun s a n"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. convergent_subseq_fun s a n < convergent_subseq_fun s a (Suc n)
[PROOF STEP]
apply(auto)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. convergent_subseq_fun s a n < (SOME k. convergent_subseq_fun s a n < k \<and> s k (Suc n) = a (Suc n))
[PROOF STEP]
proof(induction n)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. convergent_subseq_fun s a 0 < (SOME k. convergent_subseq_fun s a 0 < k \<and> s k (Suc 0) = a (Suc 0))
2. \<And>n. convergent_subseq_fun s a n < (SOME k. convergent_subseq_fun s a n < k \<and> s k (Suc n) = a (Suc n)) \<Longrightarrow> convergent_subseq_fun s a (Suc n) < (SOME k. convergent_subseq_fun s a (Suc n) < k \<and> s k (Suc (Suc n)) = a (Suc (Suc n)))
[PROOF STEP]
case 0
[PROOF STATE]
proof (state)
this:
goal (2 subgoals):
1. convergent_subseq_fun s a 0 < (SOME k. convergent_subseq_fun s a 0 < k \<and> s k (Suc 0) = a (Suc 0))
2. \<And>n. convergent_subseq_fun s a n < (SOME k. convergent_subseq_fun s a n < k \<and> s k (Suc n) = a (Suc n)) \<Longrightarrow> convergent_subseq_fun s a (Suc n) < (SOME k. convergent_subseq_fun s a (Suc n) < k \<and> s k (Suc (Suc n)) = a (Suc (Suc n)))
[PROOF STEP]
have "convergent_subseq_fun s a 0 = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. convergent_subseq_fun s a 0 = 0
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
convergent_subseq_fun s a 0 = 0
goal (2 subgoals):
1. convergent_subseq_fun s a 0 < (SOME k. convergent_subseq_fun s a 0 < k \<and> s k (Suc 0) = a (Suc 0))
2. \<And>n. convergent_subseq_fun s a n < (SOME k. convergent_subseq_fun s a n < k \<and> s k (Suc n) = a (Suc n)) \<Longrightarrow> convergent_subseq_fun s a (Suc n) < (SOME k. convergent_subseq_fun s a (Suc n) < k \<and> s k (Suc (Suc n)) = a (Suc (Suc n)))
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
convergent_subseq_fun s a 0 = 0
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
convergent_subseq_fun s a 0 = 0
goal (1 subgoal):
1. convergent_subseq_fun s a 0 < (SOME k. convergent_subseq_fun s a 0 < k \<and> s k (Suc 0) = a (Suc 0))
[PROOF STEP]
by (smt assms(1) assms(3) less_Suc_eq less_Suc_eq_0_disj increasing_conv_induction_0_pre padic_integers_axioms someI_ex)
[PROOF STATE]
proof (state)
this:
convergent_subseq_fun s a 0 < (SOME k. convergent_subseq_fun s a 0 < k \<and> s k (Suc 0) = a (Suc 0))
goal (1 subgoal):
1. \<And>n. convergent_subseq_fun s a n < (SOME k. convergent_subseq_fun s a n < k \<and> s k (Suc n) = a (Suc n)) \<Longrightarrow> convergent_subseq_fun s a (Suc n) < (SOME k. convergent_subseq_fun s a (Suc n) < k \<and> s k (Suc (Suc n)) = a (Suc (Suc n)))
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>n. convergent_subseq_fun s a n < (SOME k. convergent_subseq_fun s a n < k \<and> s k (Suc n) = a (Suc n)) \<Longrightarrow> convergent_subseq_fun s a (Suc n) < (SOME k. convergent_subseq_fun s a (Suc n) < k \<and> s k (Suc (Suc n)) = a (Suc (Suc n)))
[PROOF STEP]
case (Suc k)
[PROOF STATE]
proof (state)
this:
convergent_subseq_fun s a k < (SOME ka. convergent_subseq_fun s a k < ka \<and> s ka (Suc k) = a (Suc k))
goal (1 subgoal):
1. \<And>n. convergent_subseq_fun s a n < (SOME k. convergent_subseq_fun s a n < k \<and> s k (Suc n) = a (Suc n)) \<Longrightarrow> convergent_subseq_fun s a (Suc n) < (SOME k. convergent_subseq_fun s a (Suc n) < k \<and> s k (Suc (Suc n)) = a (Suc (Suc n)))
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
convergent_subseq_fun s a k < (SOME ka. convergent_subseq_fun s a k < ka \<and> s ka (Suc k) = a (Suc k))
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
convergent_subseq_fun s a k < (SOME ka. convergent_subseq_fun s a k < ka \<and> s ka (Suc k) = a (Suc k))
goal (1 subgoal):
1. convergent_subseq_fun s a (Suc k) < (SOME ka. convergent_subseq_fun s a (Suc k) < ka \<and> s ka (Suc (Suc k)) = a (Suc (Suc k)))
[PROOF STEP]
by (metis (mono_tags, lifting) assms(1) assms(3) increasing_conv_induction_0_pre someI_ex)
[PROOF STATE]
proof (state)
this:
convergent_subseq_fun s a (Suc k) < (SOME ka. convergent_subseq_fun s a (Suc k) < ka \<and> s ka (Suc (Suc k)) = a (Suc (Suc k)))
goal:
No subgoals!
[PROOF STEP]
qed |
Require Import
CertifiedExtraction.Core
CertifiedExtraction.FacadeNotations
CertifiedExtraction.PropertiesOfTelescopes
CertifiedExtraction.ExtendedPropertiesOfTelescopes
CertifiedExtraction.ExtendedLemmas.
Fixpoint TelAppend {av} (t1 t2: Telescope av) :=
match t1 with
| Nil => t2
| Cons T key val tail => Cons (T := T) key val (fun v => TelAppend (tail v) t2)
end.
Lemma TelAppend_Nil {av} :
forall t: Telescope av,
TelStrongEq (TelAppend t Nil) t.
Proof.
induction t; simpl.
+ reflexivity.
+ econstructor; eauto with typeclass_instances.
Qed.
Lemma TelEq_TelAppend_Cons_Second {av A B}:
forall {H : FacadeWrapper (Value av) B} (t1: Telescope av) t2 k (v : Comp A) ext,
TelEq ext
([[ k ~~> v as vv]] :: TelAppend t1 (t2 vv))
(TelAppend t1 ([[ k ~~> v as vv]] :: (t2 vv))).
Proof.
intros.
induction t1; simpl.
+ reflexivity.
+ rewrite TelEq_swap.
setoid_rewrite H0.
reflexivity.
Qed.
Add Parametric Morphism {av} : (@TelAppend av)
with signature ((TelStrongEq) ==> (TelStrongEq) ==> (TelStrongEq))
as TelAppend_TelStrongEq_morphism.
Proof.
induction 1; simpl.
+ eauto with typeclass_instances.
+ intros.
econstructor; eauto.
Qed.
Add Parametric Morphism {av} ext : (@TelAppend av)
with signature (TelStrongEq ==> (TelEq ext) ==> (TelEq ext))
as TelAppend_TelStrongEq_TelEq_morphism.
Proof.
intros.
rewrite H; clear H.
induction y; simpl; intros.
+ assumption.
+ apply Cons_TelEq_pointwise_morphism; red; eauto.
Qed.
Add Parametric Morphism {av} ext : (@TelAppend av)
with signature (TelEq ext ==> TelEq ext ==> (TelEq ext))
as TelAppend_TelEq_morphism.
Proof.
intros.
rewrite H0; clear H0.
induction y0.
+ rewrite !TelAppend_Nil; assumption.
+ setoid_rewrite <- TelEq_TelAppend_Cons_Second.
setoid_rewrite H0.
reflexivity.
Qed.
Ltac standalone_tail tail :=
(* Recurse down the TAIL of telescope (of type (a: A) → Telescope) to find the
first subtelescope that doesn't depend on ‘a’. *)
lazymatch tail with (* This is a really cute piece of code *)
| (fun a => Cons _ _ (fun _ => ?tail)) => constr:(tail)
| (fun a => Cons _ _ (fun _ => @?tail a)) => standalone_tail tail
end.
Ltac function_surrounding_standalone_tail tail :=
(* Recurse down the TAIL of telescope (of type (a: A) → Telescope) to find the
first subtelescope that doesn't depend on ‘a’, and construct a function
plugging an arbitrary argument instead of that subtelescope. *)
lazymatch tail with
| (fun a: ?A => Cons ?k ?v (fun _ => ?tail)) =>
let _t := constr:(tail) in (* Fails if ‘tail’ depends on a *)
constr:(fun plug => fun a: A => (Cons k v (fun _ => plug)))
| (fun a: ?A => Cons ?k ?v (fun _ => @?tail a)) =>
let fn := function_surrounding_standalone_tail tail in
eval cbv beta in (fun plug => fun a: A => (Cons k v (fun _ => fn plug a)))
end.
Ltac split_tail_of_telescope tel :=
(* Split the tail TEL (a function) into two parts, using ‘standalone_tail’ and
‘function_surrounding_standalone_tail’. *)
match tel with
| Cons ?k ?v ?tail =>
let tl := standalone_tail tail in
let tenvF := function_surrounding_standalone_tail tail in
(* let tenvF := (eval cbv beta in (fun plug => Cons k v (tenvF plug))) in *)
constr:(tenvF, tl)
end.
Ltac make_TelAppend tel :=
(** Change the tail of TEL into a ‘TelAppend’ of two parts: one depending on
the head value of tail, and the other independent of it. *)
match tel with
| Cons ?k ?v ?tail =>
let appTl := standalone_tail tail in
let tenvF := function_surrounding_standalone_tail tail in
let appHead := (eval cbv beta in (Cons k v (tenvF Nil))) in
constr:(TelAppend appHead appTl)
end.
|
Require Import Undecidability.Synthetic.DecidabilityFacts Undecidability.Synthetic.EnumerabilityFacts Undecidability.Shared.partial Undecidability.Shared.embed_nat Undecidability.Synthetic.FinitenessFacts.
Require Import List Lia.
Export EmbedNatNotations.
(** ** Semi-decidability *)
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 enumerable_semi_decidable {X} {p : X -> Prop} :
discrete X -> enumerable p -> semi_decidable p.
Proof.
unfold enumerable, enumerator.
intros [d Hd] [f Hf].
exists (fun x n => if f n is Some y then d (x,y) else false).
intros x. 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 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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.