text
stringlengths 0
3.34M
|
---|
[STATEMENT]
lemma parts_InsecTag [simp]: "parts {Tag t} = {Tag t}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. parts {Tag t} = {Tag t}
[PROOF STEP]
by (safe, erule parts.induct) (auto) |
Formal statement is: lemma setdist_Lipschitz: "\<bar>setdist {x} S - setdist {y} S\<bar> \<le> dist x y" Informal statement is: The distance between a point and a set is Lipschitz. |
function n = length( x )
s = size( x );
if any( s == 0 ),
n = 0;
else
n = max( s );
end
% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.
|
This editor can edit this entry and tell us a bit about themselves by clicking the Edit icon.
20110319 21:27:27 nbsp Welcome to the Wiki. The wiki is here so that we can all explore, discuss and compile anything and everything about Davis — especially the little, enjoyable things. http://daviswiki.org/Yolo_Fruit_Stand?actiondiff&version288&version187 Your comment about the Yolo Fruit Stand contains an accusation about how they conduct their business. How should the wiki react to that comment? How would you feel if you were the owner of a business and someone made a statement like that about you? Users/JasonAller
|
lemma add_comm (a b : mynat) : a + b = b + a :=
begin
induction b with k Pk,
rw add_zero, rw zero_add, refl,
rw add_succ, rw succ_add, rw Pk, refl,
end |
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*)
theory signed_div
imports "../CTranslation"
begin
install_C_file "signed_div.c"
context signed_div
begin
lemma f_result:
"\<Gamma> \<turnstile> \<lbrace> True \<rbrace> \<acute>ret__int :== CALL f(5, -1) \<lbrace> \<acute>ret__int = -5 \<rbrace>"
apply vcg
apply (clarsimp simp: sdiv_word_def sdiv_int_def)
done
lemma word_not_minus_one [simp]:
"0 \<noteq> (-1 :: word32)"
by (metis word_msb_0 word_msb_n1)
lemma f_overflow:
shows "\<lbrakk> a_' s = of_int (-2^31); b_' s = -1 \<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> \<langle> Call f_'proc ,Normal s\<rangle> \<Rightarrow> Fault SignedArithmetic"
apply (rule exec.Call [where \<Gamma>=\<Gamma>, OF f_impl, simplified f_body_def creturn_def])
apply (rule exec.CatchMiss)
apply (subst exec.simps, clarsimp simp del: word_neq_0_conv simp: sdiv_word_def sdiv_int_def)+
apply simp
done
lemma g_result:
"\<Gamma> \<turnstile> \<lbrace> True \<rbrace> \<acute>ret__int :== CALL g(-5, 10) \<lbrace> \<acute>ret__int = -5 \<rbrace>"
apply vcg
apply (clarsimp simp: smod_word_def smod_int_def sdiv_int_def)
done
lemma h_result:
"\<Gamma> \<turnstile> \<lbrace> True \<rbrace> \<acute>ret__int :== CALL h(5, -1) \<lbrace> \<acute>ret__int = 0 \<rbrace>"
apply vcg
apply (simp add: word_div_def uint_word_ariths)
done
lemma i_result:
"\<Gamma> \<turnstile> \<lbrace> True \<rbrace> \<acute>ret__int :== CALL f(5, -1) \<lbrace> \<acute>ret__int = -5 \<rbrace>"
apply vcg
apply (clarsimp simp: sdiv_word_def sdiv_int_def)
done
end
end
|
library(bitops)
bitAnd(35, 42) # 34
bitOr(35, 42) # 43
bitXor(35, 42) # 9
bitFlip(35, bitWidth=8) # 220
bitShiftL(35, 1) # 70
bitShiftR(35, 1) # 17
# Note that no bit rotation is provided in this package
|
section propositional
variables P Q R : Prop
------------------------------------------------
-- Proposições de dupla negaço:
------------------------------------------------
theorem doubleneg_intro :
P → ¬¬P :=
begin
intro hp,
intro np,
apply np hp,
end
theorem doubleneg_elim : -- "manchado" pela RAA (Redução ao absurdo)
¬¬P → P :=
begin
intro nnp,
by_contradiction pboom,
apply nnp pboom,
end
theorem doubleneg_law :
¬¬P ↔ P :=
begin
split,
-- parte ¬¬P → P:
apply doubleneg_elim P,
-- parte P → ¬¬P:
apply doubleneg_intro P,
end
------------------------------------------------
-- Comutatividade dos ∨,∧:
------------------------------------------------
theorem disj_comm :
(P ∨ Q) → (Q ∨ P) :=
begin
intro p_ou_q,
cases p_ou_q with hp hq,
-- caso P:
right,
exact hp,
-- caso Q:
left,
exact hq,
end
theorem conj_comm :
(P ∧ Q) → (Q ∧ P) :=
begin
intro p_e_q,
cases p_e_q with hp hq,
split,
-- parte q:
exact hq,
-- parte P:
exact hp,
end
------------------------------------------------
-- Proposições de interdefinabilidade dos →,∨:
------------------------------------------------
theorem impl_as_disj_converse :
(¬P ∨ Q) → (P → Q) :=
begin
intro np_ou_q,
intro hp,
cases np_ou_q with np hq,
-- caso ¬P:
have boom : false := np hp,
exfalso,
exact boom,
-- caso Q:
exact hq,
end
theorem disj_as_impl :
(P ∨ Q) → (¬P → Q) :=
begin
intro p_ou_q,
intro np,
cases p_ou_q with hp hq,
-- caso P:
contradiction,
-- caso Q:
exact hq,
end
------------------------------------------------
-- Proposições de contraposição:
------------------------------------------------
theorem impl_as_contrapositive :
(P → Q) → (¬Q → ¬P) :=
begin
intro p_implies_q,
intro nq,
intro hp,
have hq : Q := p_implies_q hp,
contradiction,
end
theorem impl_as_contrapositive_converse :
(¬Q → ¬P) → (P → Q) :=
begin
intro nq_implies_np,
intro hp,
by_contradiction nq,
have np : ¬P := nq_implies_np nq,
contradiction,
end
theorem contrapositive_law :
(P → Q) ↔ (¬Q → ¬P) :=
begin
split,
-- parte (P → Q) → ¬Q → ¬P:
exact impl_as_contrapositive P Q,
-- parte (¬Q → ¬P) → P → Q:
exact impl_as_contrapositive_converse P Q,
end
------------------------------------------------
-- A irrefutabilidade do LEM:
------------------------------------------------
theorem lem_irrefutable :
¬¬(P∨¬P) :=
begin
intro nn_p_ou_np,
apply nn_p_ou_np,
right,
intro hp,
apply nn_p_ou_np,
left,
exact hp,
end
------------------------------------------------
-- A lei de Peirce
------------------------------------------------
theorem peirce_law_weak :
((P → Q) → P) → ¬¬P :=
begin
intro hi,
intro np,
apply np,
apply hi,
intro hp,
contradiction,
end
------------------------------------------------
-- Proposições de interdefinabilidade dos ∨,∧:
------------------------------------------------
theorem disj_as_negconj :
P∨Q → ¬(¬P∧¬Q) :=
begin
intro p_ou_q,
intro n_np_e_nq,
cases n_np_e_nq with np nq,
cases p_ou_q with hp hq,
-- caso P:
contradiction,
-- caso Q:
contradiction,
end
theorem conj_as_negdisj :
P∧Q → ¬(¬P∨¬Q) :=
begin
intro p_e_q,
cases p_e_q with hp hq,
intro np_ou_nq,
cases np_ou_nq with np nq,
-- caso ¬P:
contradiction,
-- caso ¬Q:
contradiction,
end
------------------------------------------------
-- As leis de De Morgan para ∨,∧:
------------------------------------------------
theorem demorgan_disj :
¬(P∨Q) → (¬P ∧ ¬Q) :=
begin
intro n_p_ou_q,
split,
-- parte ¬P:
intro hp,
have p_ou_q : (P∨Q),
left,
exact hp,
have boom : false := n_p_ou_q p_ou_q,
exact boom,
-- parte ¬Q:
intro hq,
have p_ou_q: (P∨Q),
right,
exact hq,
have boom : false := n_p_ou_q p_ou_q,
exact boom,
end
theorem demorgan_disj_converse :
(¬P ∧ ¬Q) → ¬(P∨Q) :=
begin
intro np_e_nq,
cases np_e_nq with np nq,
intro p_ou_q,
cases p_ou_q with hp hq,
-- caso P:
have boom : false := np hp,
exact boom,
-- caso Q:
have boom : false := nq hq,
exact boom,
end
theorem demorgan_conj :
¬(P∧Q) → (¬Q ∨ ¬P) :=
begin
intro n_p_e_q,
by_cases hq : Q,
-- caso Q:
right,
intro hp,
have p_e_q : (P∧Q),
split,
-- parte P:
exact hp,
-- parte Q:
exact hq,
have boom : false := n_p_e_q p_e_q,
exact boom,
-- caso ¬Q:
left,
exact hq,
end
theorem demorgan_conj_converse :
(¬Q ∨ ¬P) → ¬(P∧Q) :=
begin
intro nq_ou_np,
intro p_e_q,
cases p_e_q with hp hq, -- uso do ∧
cases nq_ou_np with nq np, -- uso do ∨
-- caso ¬Q:
contradiction,
-- caso ¬P:
contradiction,
end
theorem demorgan_conj_law :
¬(P∧Q) ↔ (¬Q ∨ ¬P) :=
begin
split,
-- parte ¬(P ∧ Q) → ¬Q ∨ ¬P:
exact demorgan_conj P Q,
-- parte ¬Q ∨ ¬P → ¬(P ∧ Q):
exact demorgan_conj_converse P Q,
end
theorem demorgan_disj_law :
¬(P∨Q) ↔ (¬P ∧ ¬Q) :=
begin
split,
-- parte ¬(P ∨ Q) → ¬P ∧ ¬Q:
exact demorgan_disj P Q,
-- parte ¬P ∧ ¬Q → ¬(P ∨ Q):
exact demorgan_disj_converse P Q,
end
------------------------------------------------
-- Proposições de distributividade dos ∨,∧:
------------------------------------------------
theorem distr_conj_disj :
P∧(Q∨R) → (P∧Q)∨(P∧R) :=
begin
intro p_e_qour,
cases p_e_qour with hp q_ou_r, -- Uso da conjunção (Extrair)
cases q_ou_r with hq hr,
-- caso Q:
left,
split, -- P∧Q:
-- parte P:
exact hp,
-- parte Q:
exact hq,
-- caso R:
right,
split, -- P∧R:
-- parte P:
exact hp,
-- parte R:
exact hr,
end
theorem distr_conj_disj_converse :
(P∧Q)∨(P∧R) → P∧(Q∨R) :=
begin
intro pEq_ou_pEr,
cases pEq_ou_pEr with p_e_q p_e_r,
-- caso P∧Q:
cases p_e_q with hp hq,
split,
-- parte P:
exact hp,
-- parte Q∨R:
left,
exact hq,
-- caso P∧R:
cases p_e_r with hp hr,
split,
-- parte P:
exact hp,
-- parte Q∨R:
right,
exact hr,
end
theorem distr_disj_conj :
P∨(Q∧R) → (P∨Q)∧(P∨R) :=
begin
intro p_ou_qEr,
cases p_ou_qEr with hp q_e_r,
-- caso P:
split,
-- parte P∨Q:
left,
exact hp,
-- parte P∨R:
left,
exact hp,
-- caso Q∧R:
cases q_e_r with hq hr,
split,
-- parte P∨Q:
right,
exact hq,
-- parte P∨R:
right,
exact hr,
end
theorem distr_disj_conj_converse :
(P∨Q)∧(P∨R) → P∨(Q∧R) :=
begin
intro pOUq_e_pOUr,
cases pOUq_e_pOUr with p_ou_q p_ou_r,
cases p_ou_q with hp hq,
-- caso P:
cases p_ou_r with hp hr,
-- caso P:
left,
exact hp,
-- caso R:
left,
exact hp,
-- caso Q:
cases p_ou_r with hp hr,
-- caso P:
left,
exact hp,
-- caso R:
right,
split,
-- parte Q:
exact hq,
-- parte R:
exact hr,
end
------------------------------------------------
-- Currificação
------------------------------------------------
theorem curry_prop :
((P∧Q)→R) → (P→(Q→R)) :=
begin
intro pEq_implies_r,
intro hp,
intro hq,
have p_e_q : (P∧Q),
split,
-- parte P:
exact hp,
-- parte Q:
exact hq,
apply pEq_implies_r p_e_q,
end
theorem uncurry_prop :
(P→(Q→R)) → ((P∧Q)→R) :=
begin
intro h1,
intro p_e_q,
cases p_e_q with hp hq,
apply h1 hp hq,
end
------------------------------------------------
-- Reflexividade da →:
------------------------------------------------
theorem impl_refl :
P → P :=
begin
intro hp,
exact hp,
end
------------------------------------------------
-- Weakening and contraction:
------------------------------------------------
theorem weaken_disj_right :
P → (P∨Q) :=
begin
intro hp,
left,
exact hp,
end
theorem weaken_disj_left :
Q → (P∨Q) :=
begin
intro hq,
right,
exact hq,
end
theorem weaken_conj_right :
(P∧Q) → P :=
begin
intro p_e_q,
cases p_e_q with hp hq,
exact hp,
end
theorem weaken_conj_left :
(P∧Q) → Q :=
begin
intro p_e_q,
cases p_e_q with hp hq,
exact hq,
end
theorem conj_idempot :
(P∧P) ↔ P :=
begin
split,
-- parte P ∧ P → P:
intro p_e_p,
cases p_e_p with hp hp,
exact hp,
-- parte P → P ∧ P:
intro hp,
split,
-- parte P:
exact hp,
-- parte P:
exact hp,
end
theorem disj_idempot :
(P∨P) ↔ P :=
begin
split,
-- parte P ∨ P → P:
intro p_ou_p,
cases p_ou_p with hp hp,
-- caso P:
exact hp,
-- caso P:
exact hp,
-- parte P → P ∨ P:
intro hp,
left,
exact hp,
end
end propositional
----------------------------------------------------------------
section predicate
variable U : Type
variables P Q : U -> Prop
------------------------------------------------
-- As leis de De Morgan para ∃,∀:
------------------------------------------------
theorem demorgan_exists :
¬(∃x, P x) → (∀x, ¬P x) :=
begin
intro h1,
intro x,
intro px,
apply h1,
existsi x,
exact px,
end
theorem demorgan_exists_converse :
(∀x, ¬P x) → ¬(∃x, P x) :=
begin
intro h1,
intro h2,
cases h2 with x px,
apply h1 x px,
end
theorem demorgan_forall : -- Manchado (RAA)
¬(∀x, P x) → (∃x, ¬P x) :=
begin
intro h1,
by_contradiction h2,
apply h1,
intro x,
by_contradiction npx,
apply h2,
existsi x,
exact npx,
end
theorem demorgan_forall_converse :
(∃x, ¬P x) → ¬(∀x, P x) :=
begin
intro h1,
intro h2,
cases h1 with x npx,
have px : P x := h2 x,
apply npx px,
end
theorem demorgan_forall_law :
¬(∀x, P x) ↔ (∃x, ¬P x) :=
begin
split,
-- parte :
apply demorgan_forall U P,
-- parte :
apply demorgan_forall_converse U P,
end
theorem demorgan_exists_law :
¬(∃x, P x) ↔ (∀x, ¬P x) :=
begin
split,
-- parte (¬∃ (x : U), P x) → ∀ (x : U), ¬P x:
apply demorgan_exists U P,
-- parte (∀ (x : U), ¬P x) → (¬∃ (x : U), P x):
apply demorgan_exists_converse U P,
end
------------------------------------------------
-- Proposições de interdefinabilidade dos ∃,∀:
------------------------------------------------
theorem exists_as_neg_forall :
(∃x, P x) → ¬(∀x, ¬P x) :=
begin
intro h1,
intro h2,
cases h1 with x px,
apply h2 x px,
end
theorem forall_as_neg_exists :
(∀x, P x) → ¬(∃x, ¬P x) :=
begin
intro h1,
intro h2,
cases h2 with x npx,
have px : P x := h1 x,
have boom: false := npx px,
exact boom,
end
theorem forall_as_neg_exists_converse :
¬(∃x, ¬P x) → (∀x, P x) :=
begin
intro h1,
intro x,
by_contradiction npx,
apply h1,
existsi x,
exact npx,
end
theorem exists_as_neg_forall_converse :
¬(∀x, ¬P x) → (∃x, P x) :=
begin
intro h1,
by_contradiction h2,
apply h1,
intro x,
intro px,
apply h2,
existsi x,
exact px,
end
theorem forall_as_neg_exists_law :
(∀x, P x) ↔ ¬(∃x, ¬P x) :=
begin
split,
-- parte :
apply forall_as_neg_exists U P,
-- parte :
apply forall_as_neg_exists_converse U P,
end
theorem exists_as_neg_forall_law :
(∃x, P x) ↔ ¬(∀x, ¬P x) :=
begin
split,
-- parte :
apply exists_as_neg_forall U P,
-- parte :
apply exists_as_neg_forall_converse U P,
end
------------------------------------------------
-- Proposições de distributividade de quantificadores:
------------------------------------------------
theorem exists_conj_as_conj_exists :
(∃x, P x ∧ Q x) → (∃x, P x) ∧ (∃x, Q x) :=
begin
intro h1,
cases h1 with x pqx,
cases pqx with px qx,
split,
-- parte (∃x, P x):
existsi x,
exact px,
-- parte (∃x, Q x):
existsi x,
exact qx,
end
theorem exists_disj_as_disj_exists :
(∃x, P x ∨ Q x) → (∃x, P x) ∨ (∃x, Q x) :=
begin
intro h1,
cases h1 with x pxOUqx,
cases pxOUqx with px qx,
-- caso P x:
left,
existsi x,
exact px,
-- caso Q x:
right,
existsi x,
exact qx,
end
theorem exists_disj_as_disj_exists_converse :
(∃x, P x) ∨ (∃x, Q x) → (∃x, P x ∨ Q x) :=
begin
intro h1,
cases h1 with epx eqx,
-- caso ∃x, P x:
cases epx with x px,
existsi x,
left,
exact px,
-- caso ∃x, Q x:
cases eqx with x qx,
existsi x,
right,
exact qx,
end
theorem forall_conj_as_conj_forall :
(∀x, P x ∧ Q x) → (∀x, P x) ∧ (∀x, Q x) :=
begin
intro h1,
split,
-- parte ∀x, P x:
intro x,
have pxEqx : P x ∧ Q x := h1 x,
cases pxEqx with px qx,
exact px,
-- parte ∀x, Q x:
intro x,
have pxEqx : P x ∧ Q x := h1 x,
cases pxEqx with px qx,
exact qx,
end
theorem forall_conj_as_conj_forall_converse :
(∀x, P x) ∧ (∀x, Q x) → (∀x, P x ∧ Q x) :=
begin
intro h1,
cases h1 with apx aqx,
intro x,
split,
-- parte ∀x, P x:
have px : P x := apx x,
exact px,
-- parte ∀x, Q x:
have qx : Q x := aqx x,
exact qx,
end
theorem forall_disj_as_disj_forall_converse :
(∀x, P x) ∨ (∀x, Q x) → (∀x, P x ∨ Q x) :=
begin
intro h1,
cases h1 with apx aqx,
-- caso ∀x, P x:
intro x,
left,
have px : P x := apx x,
exact px,
-- caso ∀x, Q x:
intro x,
right,
have qx : Q x := aqx x,
exact qx,
end
/- NOT THEOREMS --------------------------------
theorem forall_disj_as_disj_forall :
(∀x, P x ∨ Q x) → (∀x, P x) ∨ (∀x, Q x) :=
begin
end
theorem exists_conj_as_conj_exists_converse :
(∃x, P x) ∧ (∃x, Q x) → (∃x, P x ∧ Q x) :=
begin
end
---------------------------------------------- -/
end predicate
|
-- This is not valid with magic mutual blocks that guess how far down the
-- file the mutual block extends
constructor
zero : Nat
suc : Nat → Nat
|
[STATEMENT]
lemma (in Group) joint_d_gchain_n0:"\<lbrakk>d_gchain G n f; d_gchain G 0 g;
g 0 \<subseteq> f n \<rbrakk> \<Longrightarrow> d_gchain G (Suc n) (jointfun n f 0 g)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>d_gchain G n f; d_gchain G 0 g; g 0 \<subseteq> f n\<rbrakk> \<Longrightarrow> d_gchain G (Suc n) (jointfun n f 0 g)
[PROOF STEP]
apply (frule joint_d_gchains [of "n" "f" "0" "g"], assumption+)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>d_gchain G n f; d_gchain G 0 g; g 0 \<subseteq> f n; d_gchain G (Suc (n + 0)) (jointfun n f 0 g)\<rbrakk> \<Longrightarrow> d_gchain G (Suc n) (jointfun n f 0 g)
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
program t
integer::i(2)
integer,parameter::j=1
i(1)=1
i(j+1)=2
print '(i0)',i(1)
print '(i0)',i(2)
end program t
|
A set is bounded if and only if it is bounded after inserting an element. |
lemma succ_mul (a b : mynat) : succ a * b = a * b + b :=
begin
induction b with c hc,
repeat {rw mul_zero},
simp,
repeat {rw mul_succ},
rw hc,
repeat {rw add_succ},
simp,
end
|
theory Sum imports
"../../tools/autocorres/AutoCorres"
Word
WordBitwise
begin
text{*
Author: Dan DaCosta
Description: Correctness proof for a function that calculates the sum from zero to n naively.
TODO: loop_support lemma should be cleaned up.
*}
install_C_file "./sum.c"
autocorres [ ts_rules = nondet ] "./sum.c"
context sum begin
lemma loop_support:"
\<lbrakk> \<not> result_C a + b \<le> result_C a; 2 * uint (result_C a) = x * (x + 1) - uint b * (uint b + 1)\<rbrakk>
\<Longrightarrow> 2 * uint (result_C a + b) = x * (x + 1) - uint (b - 1) * (uint (b - 1) + 1)"
proof -
assume A:" 2 * uint (result_C a) = x * (x + 1) - uint b * (uint b + 1)"
assume B:"\<not> result_C a + b \<le> result_C a"
then have B:"result_C a + b > result_C a" by simp
then have C:"b > 0" using word_neq_0_conv by fastforce
then have
"2 * uint (result_C a + b)
= x * (x + 1) - uint b * (uint b + 1) + 2 * uint b"
using B by (simp add: A distrib_left less_imp_le uint_plus_simple)
then have
"2 * uint (result_C a + b)
= x * (x + 1) - (uint b * uint b + uint b) + 2 * uint b"
by (metis (no_types, hide_lams) diff_diff_eq2
diff_zero mult.right_neutral mult_eq_0_iff right_diff_distrib)
then have
"2 * uint (result_C a + b) = x * (x + 1) - ((uint b - 1) * uint b)"
by (simp add: mult.commute right_diff_distrib)
then have
"2 * uint (result_C a + b) = x * (x + 1) - (uint (b - 1) * uint b)"
using C by (metis add.left_neutral linorder_not_less uint_1 uint_eq_0
uint_minus_simple_alt word_less_def zless_imp_add1_zle)
then have
"2 * uint (result_C a + b)
= x * (x + 1) - uint (b - 1) * (uint (b - 1) + 1)"
using C by (metis dual_order.strict_iff_order eq_diff_eq gt0_iff_gem1
uint_1 uint_plus_simple)
thus ?thesis by simp
qed
lemma "
\<lbrace> \<lambda> a. x \<ge> 0 \<and> 2^32 > x \<rbrace>
sum' ((word_of_int x)::32 word)
\<lbrace> \<lambda> r a. 2 * uint (result_C r) = x * (x + 1) \<or> overflow_C r = 1\<rbrace>!
"
apply (rule validNF_assume_pre)
apply (unfold sum'_def)
apply clarsimp
apply (subst whileLoop_add_inv [where
I = " \<lambda> (r,i) a. (((2 * uint (result_C r)
= (x * (x + 1)) - (uint i * ((uint i) + 1))))
\<or> overflow_C r = 1)"
and M = "\<lambda>((_,i),a). unat i"])
apply wp
apply (clarsimp,auto intro: loop_support simp: measure_unat)
using uint_eq_0 word_neq_0_conv apply blast
using word_of_int_inverse[of x "(word_of_int x)::32 word"] apply auto
done
end
end |
{-# OPTIONS --guardedness #-}
open import Agda.Builtin.Coinduction
open import Agda.Builtin.IO
open import Agda.Builtin.List
open import Agda.Builtin.Nat
open import Agda.Builtin.String
open import Agda.Builtin.Unit
private
variable
A : Set
postulate
putStrLn : String → IO ⊤
{-# FOREIGN GHC import qualified Data.Text.IO #-}
{-# COMPILE GHC putStrLn = Data.Text.IO.putStrLn #-}
record Stream₁ (A : Set) : Set where
coinductive
constructor _∷_
field
head : A
tail : Stream₁ A
open Stream₁
repeat₁ : A → Stream₁ A
repeat₁ x .head = x
repeat₁ x .tail = repeat₁ x
take₁ : Nat → Stream₁ A → List A
take₁ zero xs = []
take₁ (suc n) xs = xs .head ∷ take₁ n (xs .tail)
data List′ (A : Set) : Set where
[] : List′ A
_∷_ : A → List′ A → List′ A
to-list : List′ A → List A
to-list [] = []
to-list (x ∷ xs) = x ∷ to-list xs
data Stream₂ (A : Set) : Set where
_∷_ : A → ∞ (Stream₂ A) → Stream₂ A
repeat₂ : A → Stream₂ A
repeat₂ x = x ∷ ♯ repeat₂ x
take₂ : Nat → Stream₂ A → List′ A
take₂ zero _ = []
take₂ (suc n) (x ∷ xs) = x ∷ take₂ n (♭ xs)
_++_ : List A → List′ A → List A
[] ++ ys = to-list ys
(x ∷ xs) ++ ys = x ∷ (xs ++ ys)
main : IO ⊤
main =
putStrLn
(primStringFromList
(take₁ 3 (repeat₁ '(') ++ take₂ 3 (repeat₂ ')')))
|
Formal statement is: lemma complex_mod_rcis [simp]: "cmod (rcis r a) = \<bar>r\<bar>" Informal statement is: The modulus of a complex number of the form $re^{ia}$ is equal to the absolute value of $r$. |
------------------------------------------------------------------------------
-- The division specification
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module FOTC.Program.Division.Specification where
open import FOTC.Base
open import FOTC.Data.Nat
open import FOTC.Data.Nat.Inequalities
------------------------------------------------------------------------------
-- Specification: The division is total and the result is correct.
divSpec : D → D → D → Set
divSpec i j q = N q ∧ (∃[ r ] N r ∧ r < j ∧ i ≡ j * q + r)
{-# ATP definition divSpec #-}
|
dev = device()
@test name(dev) isa String
@test uuid(dev) isa Base.UUID
totalmem(dev)
attribute(dev, CUDA.DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK)
@test warpsize(dev) == 32
capability(dev)
@grab_output show(stdout, "text/plain", dev)
@test eval(Meta.parse(repr(dev))) == dev
@test eltype(devices()) == CuDevice
@grab_output show(stdout, "text/plain", CUDA.DEVICE_CPU)
@grab_output show(stdout, "text/plain", CUDA.DEVICE_INVALID)
|
/-
Copyright (c) 2019 Patrick MAssot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
! This file was ported from Lean 3 source module topology.uniform_space.compare_reals
! leanprover-community/mathlib commit 69c6a5a12d8a2b159f20933e60115a4f2de62b58
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Topology.UniformSpace.AbsoluteValue
import Mathbin.Topology.Instances.Real
import Mathbin.Topology.Instances.Rat
import Mathbin.Topology.UniformSpace.Completion
/-!
# Comparison of Cauchy reals and Bourbaki reals
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In `data.real.basic` real numbers are defined using the so called Cauchy construction (although
it is due to Georg Cantor). More precisely, this construction applies to commutative rings equipped
with an absolute value with values in a linear ordered field.
On the other hand, in the `uniform_space` folder, we construct completions of general uniform
spaces, which allows to construct the Bourbaki real numbers. In this file we build uniformly
continuous bijections from Cauchy reals to Bourbaki reals and back. This is a cross sanity check of
both constructions. Of course those two constructions are variations on the completion idea, simply
with different level of generality. Comparing with Dedekind cuts or quasi-morphisms would be of a
completely different nature.
Note that `metric_space/cau_seq_filter` also relates the notions of Cauchy sequences in metric
spaces and Cauchy filters in general uniform spaces, and `metric_space/completion` makes sure
the completion (as a uniform space) of a metric space is a metric space.
Historical note: mathlib used to define real numbers in an intermediate way, using completion
of uniform spaces but extending multiplication in an ad-hoc way.
TODO:
* Upgrade this isomorphism to a topological ring isomorphism.
* Do the same comparison for p-adic numbers
## Implementation notes
The heavy work is done in `topology/uniform_space/abstract_completion` which provides an abstract
caracterization of completions of uniform spaces, and isomorphisms between them. The only work left
here is to prove the uniform space structure coming from the absolute value on ℚ (with values in ℚ,
not referring to ℝ) coincides with the one coming from the metric space structure (which of course
does use ℝ).
## References
* [N. Bourbaki, *Topologie générale*][bourbaki1966]
## Tags
real numbers, completion, uniform spaces
-/
open Set Function Filter CauSeq UniformSpace
#print Rat.uniformSpace_eq /-
/-- The metric space uniform structure on ℚ (which presupposes the existence
of real numbers) agrees with the one coming directly from (abs : ℚ → ℚ). -/
theorem Rat.uniformSpace_eq :
(AbsoluteValue.abs : AbsoluteValue ℚ ℚ).UniformSpace = PseudoMetricSpace.toUniformSpace :=
by
ext s
rw [(AbsoluteValue.hasBasis_uniformity _).mem_iff, metric.uniformity_basis_dist_rat.mem_iff]
simp only [Rat.dist_eq, AbsoluteValue.abs_apply, ← Rat.cast_sub, ← Rat.cast_abs, Rat.cast_lt,
abs_sub_comm]
#align rat.uniform_space_eq Rat.uniformSpace_eq
-/
#print rationalCauSeqPkg /-
/-- Cauchy reals packaged as a completion of ℚ using the absolute value route. -/
def rationalCauSeqPkg : @AbstractCompletion ℚ <| (@AbsoluteValue.abs ℚ _).UniformSpace
where
Space := ℝ
coe := (coe : ℚ → ℝ)
uniformStruct := by infer_instance
complete := by infer_instance
separation := by infer_instance
UniformInducing := by
rw [Rat.uniformSpace_eq]
exact rat.uniform_embedding_coe_real.to_uniform_inducing
dense := Rat.denseEmbedding_coe_real.dense
#align rational_cau_seq_pkg rationalCauSeqPkg
-/
namespace CompareReals
#print CompareReals.Q /-
/-- Type wrapper around ℚ to make sure the absolute value uniform space instance is picked up
instead of the metric space one. We proved in rat.uniform_space_eq that they are equal,
but they are not definitionaly equal, so it would confuse the type class system (and probably
also human readers). -/
def Q :=
ℚ deriving CommRing, Inhabited
#align compare_reals.Q CompareReals.Q
-/
instance : UniformSpace Q :=
(@AbsoluteValue.abs ℚ _).UniformSpace
#print CompareReals.Bourbakiℝ /-
/-- Real numbers constructed as in Bourbaki. -/
def Bourbakiℝ : Type :=
Completion Q deriving Inhabited
#align compare_reals.Bourbakiℝ CompareReals.Bourbakiℝ
-/
#print CompareReals.Bourbaki.uniformSpace /-
instance Bourbaki.uniformSpace : UniformSpace Bourbakiℝ :=
Completion.uniformSpace Q
#align compare_reals.bourbaki.uniform_space CompareReals.Bourbaki.uniformSpace
-/
/- warning: compare_reals.Bourbaki_pkg -> CompareReals.bourbakiPkg is a dubious translation:
lean 3 declaration is
AbstractCompletion.{0} CompareReals.Q CompareReals.Q.uniformSpace
but is expected to have type
AbstractCompletion.{0} CompareReals.Q CompareReals.uniformSpace
Case conversion may be inaccurate. Consider using '#align compare_reals.Bourbaki_pkg CompareReals.bourbakiPkgₓ'. -/
/-- Bourbaki reals packaged as a completion of Q using the general theory. -/
def bourbakiPkg : AbstractCompletion Q :=
Completion.cPkg
#align compare_reals.Bourbaki_pkg CompareReals.bourbakiPkg
#print CompareReals.compareEquiv /-
/-- The uniform bijection between Bourbaki and Cauchy reals. -/
noncomputable def compareEquiv : Bourbakiℝ ≃ᵤ ℝ :=
bourbakiPkg.compareEquiv rationalCauSeqPkg
#align compare_reals.compare_equiv CompareReals.compareEquiv
-/
/- warning: compare_reals.compare_uc -> CompareReals.compare_uc is a dubious translation:
lean 3 declaration is
UniformContinuous.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) (coeFn.{1, 1} (UniformEquiv.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace)) (fun (_x : UniformEquiv.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace)) => CompareReals.Bourbakiℝ -> Real) (UniformEquiv.hasCoeToFun.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace)) CompareReals.compareEquiv)
but is expected to have type
UniformContinuous.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) (FunLike.coe.{1, 1, 1} (UniformEquiv.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace)) CompareReals.Bourbakiℝ (fun (_x : CompareReals.Bourbakiℝ) => (fun ([email protected]._hyg.19 : CompareReals.Bourbakiℝ) => Real) _x) (EmbeddingLike.toFunLike.{1, 1, 1} (UniformEquiv.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace)) CompareReals.Bourbakiℝ Real (EquivLike.toEmbeddingLike.{1, 1, 1} (UniformEquiv.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace)) CompareReals.Bourbakiℝ Real (UniformEquiv.instEquivLikeUniformEquiv.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace)))) CompareReals.compareEquiv)
Case conversion may be inaccurate. Consider using '#align compare_reals.compare_uc CompareReals.compare_ucₓ'. -/
theorem compare_uc : UniformContinuous compareEquiv :=
bourbakiPkg.uniformContinuous_compareEquiv _
#align compare_reals.compare_uc CompareReals.compare_uc
/- warning: compare_reals.compare_uc_symm -> CompareReals.compare_uc_symm is a dubious translation:
lean 3 declaration is
UniformContinuous.{0, 0} Real CompareReals.Bourbakiℝ (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.Bourbaki.uniformSpace (coeFn.{1, 1} (UniformEquiv.{0, 0} Real CompareReals.Bourbakiℝ (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.Bourbaki.uniformSpace) (fun (_x : UniformEquiv.{0, 0} Real CompareReals.Bourbakiℝ (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.Bourbaki.uniformSpace) => Real -> CompareReals.Bourbakiℝ) (UniformEquiv.hasCoeToFun.{0, 0} Real CompareReals.Bourbakiℝ (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.Bourbaki.uniformSpace) (UniformEquiv.symm.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.compareEquiv))
but is expected to have type
UniformContinuous.{0, 0} Real CompareReals.Bourbakiℝ (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.Bourbaki.uniformSpace (FunLike.coe.{1, 1, 1} (UniformEquiv.{0, 0} Real CompareReals.Bourbakiℝ (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.Bourbaki.uniformSpace) Real (fun (_x : Real) => (fun ([email protected]._hyg.19 : Real) => CompareReals.Bourbakiℝ) _x) (EmbeddingLike.toFunLike.{1, 1, 1} (UniformEquiv.{0, 0} Real CompareReals.Bourbakiℝ (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.Bourbaki.uniformSpace) Real CompareReals.Bourbakiℝ (EquivLike.toEmbeddingLike.{1, 1, 1} (UniformEquiv.{0, 0} Real CompareReals.Bourbakiℝ (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.Bourbaki.uniformSpace) Real CompareReals.Bourbakiℝ (UniformEquiv.instEquivLikeUniformEquiv.{0, 0} Real CompareReals.Bourbakiℝ (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.Bourbaki.uniformSpace))) (UniformEquiv.symm.{0, 0} CompareReals.Bourbakiℝ Real CompareReals.Bourbaki.uniformSpace (PseudoMetricSpace.toUniformSpace.{0} Real Real.pseudoMetricSpace) CompareReals.compareEquiv))
Case conversion may be inaccurate. Consider using '#align compare_reals.compare_uc_symm CompareReals.compare_uc_symmₓ'. -/
theorem compare_uc_symm : UniformContinuous compareEquiv.symm :=
bourbakiPkg.uniformContinuous_compareEquiv_symm _
#align compare_reals.compare_uc_symm CompareReals.compare_uc_symm
end CompareReals
|
\documentclass[aspectratio=169]{beamer}
\usepackage[utf8]{inputenc}
\usepackage{pgfpages}
\usepackage{subcaption}
\usepackage{graphicx}
\usepackage{multicol, bigstrut}
\usepackage{rotating}
\setlength\abovecaptionskip{0pt}
\captionsetup[figure]{font=scriptsize, labelfont=scriptsize}
\captionsetup[sub]{font=scriptsize}
\newcommand\scalemath[2]{\scalebox{#1}{\mbox{\ensuremath{\displaystyle #2}}}}
\usepackage{amssymb}
\newcommand{\R}{\mathbb{R}}
\newcommand{\mat}[1]{\mathbf{#1}}
\renewcommand{\vec}{\mathbf}
\usetheme[
logo=figures/unsw-portrait.png,
sidelogo=figures/unsw-landscape.png,
]{unsw}
\setbeameroption{show notes on second screen}
\setbeamerfont{footnote}{size=\tiny}
\usepackage{pifont}% http://ctan.org/pkg/pifont
\newcommand{\cmark}{\ding{51}}%
\newcommand{\xmark}{\ding{55}}%
\usepackage{tikz}
\usetikzlibrary{shapes,arrows}
\tikzstyle{block} = [rectangle, draw, text width=6em, text centered, rounded corners, minimum height=4em]
\tikzstyle{line} = [draw, -latex']
\tikzstyle{cloud} = [draw=white, minimum height=2em]
\usepackage[beamer,customcolors]{hf-tikz}
\tikzset{hl/.style={
set fill color=gray!80!black!40,
set border color=gray!80!black!40,
},
}
%Information to be included in the title page:
\title{Comprehensive and accurate estimation of lower body movement using few wearable sensors}
\subtitle{Annual Progress Review S1 2018}
\institute{Graduate School of Biomedical Engineering, UNSW}
\author{Luke Wicent Sy \\
{Supervisors: Scientia Prof. Nigel Lovell, A/Prof. Stephen Redmond}
}
\date{June 4, 2018}
\begin{document}
\begin{frame}[plain]
\titlepage
\end{frame}
\section{Motivation}
\begin{frame}{Human movement}
\begin{figure}
\centering
\includegraphics[height=0.7\textheight]{figures/physicalandmentalaffectsgait.png}
\caption*{physical + mental = gait \footnote{http://therebelworkout.com/blog/2016/03/25/physical-health-vs-mental-health}}
\label{fig:my_label}
\end{figure}
\note[item]{Most people move their bodies effortlessly. Yet, hidden within even ordinary movement lies a lot of information about us!}
\note[item]{Our physical and mental health affects the way we move. Unfortunately and fortunately, our body is a very complex system, such that there is almost always no single explanation for the way a person moves or walk. Nevertheless, that person's movement can give us hint on what is happening inside!}
\end{frame}
\begin{frame}{Gait Analysis - study of human movement}
\begin{figure}
\centering
\subcaptionbox{Osteoarthritis
\footnote{https://commons.wikimedia.org/wiki/File:Osteoarthritis.png}}
{\includegraphics[width=0.3\textwidth]{figures/osteoarthritis.jpg}}
\subcaptionbox{Cerebral palsy surgery}
{\includegraphics[width=0.3\textwidth]{figures/cerebralpalsy.jpg}}
\subcaptionbox{Fall risk}
{\includegraphics[width=0.3\textwidth]{figures/FallDetectionAirbag.png}}
\subcaptionbox{Performance improvement}
{\includegraphics[width=0.3\textwidth]{figures/golf-perf-improvement.jpg}}
\subcaptionbox{Diagnose Parkinson's Disease}
{\includegraphics[width=0.3\textwidth]{figures/parkinsonsdisease.jpg}}
\subcaptionbox{Feedback}
{\includegraphics[width=0.3\textwidth]{figures/gait-feedback.png}}
\end{figure}
\note[item]{Hence, it is no wonder that people got interested on the study of human motion, also known as gait analysis. Gait analysis has a wide range of applications.}
\note[item]{In rheumatology, it can help diagnose osteoarthritis}
\note[item]{In orthopedics, it changes or reinforces surgical decision making in children with cerebral palsy by understanding existing gait deviations in cerebral palsy patients.}
\note[item]{In geriatrics, it can help assess fall risk. Hausdorff etal has shown that stride time variability, an example of a parameter measured for gait analysis, is a good indicator of fall risk.}
\note[item]{In neurology, it can help diagnosis Parkinson’s disease, understand gait deviations, and then inform therapy.}
\note[item]{In sports, it is used for performance improvement and injury prevention.}
\note[item]{Last, gait analysis is integral to gait assistive devices. These devices can provide real time feedback (e.g. haptics) which can help correct their walk for better stability. }
\note[item]{Recent technological advances have even brought remote gait monitoring which has the potential to identify movement disorders even before it happens.}
\end{frame}
\begin{frame}{Motion Capture (MoCap)}
\begin{itemize}
\item Track body posture, specifically joint positions and orientations of body segments
\item Wide range of applications (clinical, sports, animation, robotics, virtual reality)
\end{itemize}
\begin{figure}
\centering
\subcaptionbox{Jogging}
{\includegraphics[width=0.3\textwidth]{figures/mocapjogging.jpeg}}
\subcaptionbox{Animation}
{\includegraphics[width=0.3\textwidth]{figures/lotrmocap.png}}
\subcaptionbox{Teleoperation}
{\includegraphics[width=0.3\textwidth]{figures/teleoperating.png}}
\end{figure}
\note[item]{Motion capture is the technology used to do gait analysis. Other than clinical applications mentioned earlier, it can also be used in animation, robotics, and VR.}
\note[item]{Motion capture is the tracking of the human body, where the system estimates the joint positions and orientations of body segments.}
\end{frame}
\begin{frame}{MoCap Output}
\begin{figure}
\centering
\subcaptionbox{3D skeleton}
{\includegraphics[width=0.45\textwidth]{figures/mocap-sample-output1.png} }
\subcaptionbox{Joint kinematics
\footnote{http://www.clinicalgaitanalysis.com/data/kinematics.jpg} }
{\includegraphics[width=0.5\textwidth]{figures/kinematics.jpg} }
\end{figure}
\note[item]{skeleton figure telling us the 3d state of the body}
\note[item]{joint angles. one way clinicians use this is that they have reference movement of healthy subjects, shown in the gray shade, and if the subject's motion is outside this range, this can be an indication of problem}
\end{frame}
\begin{frame}{Human Motion Capture Systems (HMCS)}
\textbf{Types}
\begin{enumerate} [<+->]
\item Nonwearable HMCS (camera-based)
\item Wearable HMCS (wearable sensors)
\item Hybrid HMCS (both cameras and wearable sensors)
\end{enumerate}
\note{Human motion capture systems can be categorized into 3 types}
\note[item]<1>{First, nonwearable system}
\note[item]<1>{It typically captures position through multiple cameras, by doing some sort of triangulation on markers attached to the human body.}
\note[item]<1>{Special: It's the industry standard for accuracy, capable of capturing up to mm 3d position accuracy.}
\note[item]<1>{Figure (a) shows a sample of such system}
\note[item]<2>{Second is the wearable system where in my opinion, is where technology trend is heading.}
\note[item]<2>{It typically captures data through sensor units such as Inertial measurement units (IMU) which measures acceleration and angular velocity.}
\note[item]<2>{Figure (b) shows a sample of such system.}
\note[item]<3>{Third is the hybrid system.}
\note[item]<3>{It is the combination of nonwearable and wearable systems}
\begin{figure}
\centering
\subcaptionbox{Vicon
\footnote{https://commons.wikimedia.org/wiki/File:MotionCapture.jpg} }
{\includegraphics[height=0.45\textheight]{figures/220px-MotionCapture.jpg}}
\hspace{1cm}
\subcaptionbox{Xsens
\footnote{https://www.xsens.com/products/xsens-mvn-analyze/} }
{\includegraphics[height=0.45\textheight]{figures/xsenssystem.png}}
\end{figure}
\end{frame}
\begin{frame}{Comparison of HMCS}
% Table generated by Excel2LaTeX from sheet 'researchgap2'
\begin{table}[htbp]
\centering
\begin{tabular}{|l|l|l|l|l|l|l|l|l|}
\hline
\includegraphics<1>[height=0.35\textheight]{figures/220px-MotionCapture.jpg}
\includegraphics<2>[height=0.35\textheight]{figures/xsenssystem.png}
\includegraphics<3>[height=0.35\textheight]{figures/sparse-inertial-poser.png}
& \begin{sideways}high accuracy\end{sideways} & \begin{sideways}all range of motion\end{sideways} & \begin{sideways}large capture volume\end{sideways} & \begin{sideways}ease of setup\end{sideways} & \begin{sideways}robust to occlusion\end{sideways} & \begin{sideways}inconspicuous setup\end{sideways} & \begin{sideways}low cost\end{sideways} & \begin{sideways}fast computation\end{sideways} \bigstrut\\
\hline
\tikzmarkin<1>[hl]{a}nonwearable & \cmark & \cmark & \xmark & \xmark & \xmark & \xmark & \xmark & \cmark \bigstrut
\tikzmarkend{a} \\ \hline
\tikzmarkin<1>[hl]{e}hybrid & \cmark & \cmark & \xmark & \cmark & \cmark & \xmark & \xmark & \cmark \bigstrut
\tikzmarkend{e} \\ \hline
\tikzmarkin<2>[hl]{b}wearable (1 sensor / segment) & \xmark & \cmark & \cmark & \cmark & \cmark & \xmark & \xmark & \cmark \bigstrut
\tikzmarkend{b} \\ \hline
\tikzmarkin<3>[hl]{c}wearable (sparse, Marcard etal) & \xmark & \cmark & \cmark & \cmark & \cmark & \cmark & \cmark & \xmark \bigstrut
\tikzmarkend{c} \\ \hline
\tikzmarkin<4>[hl]{d}proposed system & \xmark & \xmark & \cmark & \cmark & \cmark & \cmark & \cmark & \cmark \bigstrut
\tikzmarkend{d} \\ \hline
\end{tabular}%
\end{table}%
\note[item]<1>{Nonwearable and hybrid mcs \newline
great accuracy. 1 mm. industry standard \newline
captures all RoM within capture volume \newline
capture volume is very limited \newline
difficult to setup, put 16 markers you need them to wear tight clothes \newline
occlusion to camera and conspicuous for every day life \newline
Uneconomical to deploy in hospitals due to the space and personel requirement on top of it being time consuming \newline
motion capture inside a laboratory may have deviations from eveyday natural walking as found by Lee etal when comparing treadmill walking from overground natural walking.
}
\note[item]<2>{1 sensor / segment wearable mcs, both commercial and research ones, helped solve some of the problems although at a lower accuracy \newline
as sensor are self contained, capture volume is much bigger \newline
no occlusion issues \newline
easier to setup \newline
depending on implementation, can capture all RoM \newline
1 sensor for each body segment (7 sensors to the lower body) making it too conspicuous for everyday use, leading to non compliance, a huge cause of why medical interventions fail.
}
\note[item]<3>{Sparse mcs is where the future is going. \newline
To the best of my knowledge, only 1 other group in computer graphics and animation is doing it for now \newline
Main issue is the loss of information since less sensors are used.
On top of that, the error from the remaining sensors grows very fast in time due to the nature of how we calculate position. \newline
Marcard etal coped with it using window based optimizer which is computationally expensive. 7.5 min for 17 sec of motion. }
\note[item]<4>{My proposed system aims for a sparse wearable mcs that is (almost) real time at the cost of making some assumptions that will make me unable to monitor some movements \newline
A reason for wanting a real time system is that so it can be used to drive gait assistive, devices which can give real time feedback to users which can help correct their posture or walking stability
}
\end{frame}
\section{Aims}
\begin{frame}
\frametitle{Novelty}
Develop algorithm(s) to reconstruct the lower limbs using sparse sensors
\begin{enumerate}
\item Use estimator that is (almost) real time
\item Formulation of body model and biomechanical constraints
\item Utilise new sensor information (i.e., point-to-point distance measurement using ultra-wideband (UWB) ranging)
\end{enumerate}
\end{frame}
\begin{frame}
\frametitle{Aims}
\begin{columns}
\column{0.6\textwidth}
\begin{enumerate}[<+->]
\item Develop sparse sensor MoCap algorithm to track the pelvis, femur, and tibia
\item Incorporate UWB measurement
\item Extend MoCap algorithm to also track the foot
\end{enumerate}
\note[item]<1>{3 aims. Each aim build on top of the prior aims}
\note[item]<1>{Development of a MoCap algorithm to track 5 body segments. Sensor will be attached to ... to track ...}
\note[item]<1>{Cope with the information loss from not having a sensor on the thigh by making assumptions from our knowledge on how the body moves.}
\note[item]<2>{However, IMUs are very noisy and it is expected that system accuracy can be improved by adding new sources of information.}
\note[item]<2>{Adding a UWB ranging sensor which measures the distance between 2 points.}
\note[item]<2>{Validate the system on able and non-able bodies subjects.}
\note[item]<2>{Determine how the assumptions made affected the accuracy of the system.}
\note[item]<3>{Finally, I will extend the system by including the foot, tracking 7 body segments using 3 sensor units.}
\column{0.4\textwidth}
\begin{figure}[l]
\includegraphics<1>[width=\textwidth]{figures/sparse-mocap-step1.png}
\includegraphics<2>[width=\textwidth]{figures/sparse-mocap-step2.png}
\includegraphics<3>[width=\textwidth]{figures/sparse-mocap-step3.png}
\caption*{Proposed MoCap System}
\end{figure}
\end{columns}
\end{frame}
\subsection{Aim 1 5 segment estimator}
\begin{frame}{Aim 1 Estimator Overview (v1)}
\begin{tikzpicture}[node distance=3cm]
\node at (0, 0) [block] (pred) { Prediction Update $f(\vec{x}_{k}, \vec{u}_{k})$ };
\node [block, right of=pred] (meas) { Measurement Update $h(\vec{x}_{k})$};
\node [block, right of=meas] (cstr) { Constraint Update };
\node [cloud, left of=pred] (x) {$\vec{x}_{k}$};
\node [cloud, below of=x, node distance=1cm] (u) {$\vec{u}_{k}$};
\path [line] (x) -- (pred);
\path [line] (u) -- (pred);
\path [line] (pred) -- (meas);
\path [line] (meas) -- (cstr);
\path [line] (cstr.south) -- (6, -1.5)
-- node[midway] {$\vec{x}_{k+1}, \mat{P}_{k+1}$}(0, -1.5)
-- (pred.south);
\end{tikzpicture}
% $\vec{x}_{k+1}, \mat{P}^~_{k+1}$
\begin{itemize}
\item Estimator: Constrained Extended Kalman Filter (EKF) \pause
\item State $\vec{x}$: position, velocity, and orientation of the pelvis and tibia
\item Input $\vec{u}$: acceleration from IMU attached to the pelvis and tibia \pause
\item Prediction update: kinematic equations (e.g., $p = p_0 + vt + \frac{1}{2} at^2$) \pause
\item Measurement update:
\begin{itemize}
\item Zero velocity update: $\vec{v}_{segment, k} = 0$
\item Floor assumption: $\vec{p}_{segment, k, z} = floor$
\end{itemize} \pause
\item Constraint update: 2 formulations of hinge knee joint
\end{itemize}
\note[item]<1>{The block diagram shows an overview of my estimator based on the EKF framework. For each time step, it use all possible information it have to get the best possible estimate.}
\note[item]<1>{There are 3 main steps namely ...}
\note[item]<2>{The goal of the algorithm is to estimate ...}
\note[item]<2>{Source of information are accelerometer and orientation given to me by orientation estimation algorithms}
\note[item]<3>{At the prediction update, the next step is predicted using acceleration and our model based on kinematic equations}
\note[item]<4>{At the measurement update, special events are detected to improve our estimate, namely when the foot touches the ground}
\note[item]<4>{In our algorithm, every foot step, we set the ankle velocity to 0 and the ankle z position to the floor z position}
\note[item]<5>{Lastly, at the constraint update, orientation and our knowledge of how the body moves are used to ensures that the state estimate ends on a physically possible configuration}
\end{frame}
\begin{frame}{Aim 1 Estimator Overview (v1)}
\begin{columns}
\column{0.6\textwidth}
\begin{itemize}
\item Constraint formulation 1: linear, lock knee
{ \tiny \begin{align*}
& \vec{q}_{s, k} = \mat{R}_{s, k} =
\begin{bmatrix}
\vec{R}_{s, x, k} & \vec{R}_{s, y, k} & \vec{R}_{s, z, k}
\end{bmatrix} \\
& \vec{p}_{lhip, k} = \vec{p}_{pelv, k} + d_{pelv}/2*\vec{R}_{pelv, y, k} \\
& \vec{p}_{lkne, k} = \vec{p}_{lank, k} + d_{ltib}*\vec{R}_{ltib, z, k} \\
& \alpha_{lkne, k} = \cos^{-1} \left( (\vec{p}_{lhip, k} - \vec{p}_{lkne, k} ) \cdot \vec{R}_{ltib, z, k} \right)\\
& \vec{p}_{lank, k} - \vec{p}_{pelv, k} = d_{pelv}/2*\vec{R}_{pelv, y, k} - d_{lfem}* \\
& \left( cos(\alpha_{lkne})*\vec{R}_{ltib, z, k} + sin(\alpha_{lkne})*\vec{R}_{ltib, x, k} \right) \\
& - d_{ltib}*\vec{R}_{ltib, z, k}
\end{align*} }%
\item Projection algorithm: Maximum likelihood, Least squares estimation
\end{itemize}
\note[item]{Made assumptions to make the constraint linear, namely make the knee not move before and after the constraint update}
\note[item]{Things get very complicated when things are non-linear}
\note[item]{Here are the equations that define the constraint, but I won't delve in deeper.}
\note[item]{Intuitively, what it does is to make sure that the red arrow and the blue arrow meet at the same point}
\note[item]{Red arrow = my estimate from measurement update. Blue arrow = my body reconstruction from orientation estimate and knee lock.}
\column{0.4\textwidth}
\begin{figure}
\centering
\includegraphics[height=0.7\textheight]{figures/body3d-HJCv1.png}
\caption*{Formulation 1}
\end{figure}
\end{columns}
\end{frame}
\begin{frame}{Aim 1 Estimator Overview (v1)}
\begin{columns}
\column{0.6\textwidth}
\begin{itemize}
\item Constraint formulation 2: non-linear, hinge joint (1 DoF)
{ \tiny \begin{align*}
& \vec{q}_{s, k} = \mat{R}_{s, k} =
\begin{bmatrix}
\vec{R}_{s, x, k} & \vec{R}_{s, y, k} & \vec{R}_{s, z, k}
\end{bmatrix} \\
& \vec{p}_{lhip, k} = \vec{p}_{pelv, k} + d_{pelv}/2*\vec{R}_{pelv, y, k} \\
& \vec{p}_{lkne, k} = \vec{p}_{lank, k} + d_{ltib}*\vec{R}_{ltib, z, k} \\
& (\vec{p}_{lhip, k} - \vec{p}_{lkne, k} ) \cdot \vec{R}_{ltib, y, k} = 0\\
& ||\vec{p}_{lhip, k} - \vec{p}_{lkne, k}||_2 = d_{lfem}
\end{align*} }%
\item Projection algorithm: MATLAB's fmincon
\end{itemize}
\note[item]{non-linear}
\note[item]{the red line maintains fixed length. red line lies in the plane defined these 3 points (ankle, knee, hips)}
\column{0.4\textwidth}
\begin{figure}
\centering
\includegraphics[height=0.7\textheight]{figures/body3d-HJCv2.png}
\caption*{Formulation 2}
\end{figure}
\end{columns}
\end{frame}
\begin{frame}{Aim 1 Estimator Preliminary Results (v1)}
\begin{figure}
\includegraphics[width=\textwidth]{figures/aim1-result-anklepos.png}
\caption*{Ankle position relative to the pelvis}
\end{figure}
\note[item]{Highlight that the x and y pos estimation still needs work while z is doing well and show that in the table and plot}
\note[item]{I will try compare with mode position error if I have time}
\end{frame}
\begin{frame}{Aim 1 Estimator Preliminary Results (v1)}
\begin{center}
Demo video
\end{center}
\note[item]{Note that the algorithm is estimating from the pelvis. It is not estimating the global position. For this video, I simply placed my body estimate of the correct global position to help us visualize and understand what is happening}
\note[item]{although it may be difficult to observe, my estimated reconstruction is a bit jerky compared to the ground truth}
\end{frame}
\begin{frame}{Aim 1 Estimator Preliminary Results (v1)}
\begin{columns}
\column{0.6\textwidth}
Other findings
\begin{itemize}
\item Linear constraint: works better due to knee lock assumption
\item Non-linear constraint: added linearisation error with increased error during high dynamic motion
\end{itemize}
\pause
To finish v1
\begin{itemize}
\item Public dataset (total capture dataset) $\Rightarrow$ capture own data
\item Write and publish!
\end{itemize}
\note[item]<1>{linear works better because if we walk, we don't move knee much. however if we want to capture activities of daily living, this assumption will cause issues}
\note[item]<1>{nonlinear is ok, but not good with fast motion}
\column{0.4\textwidth}
\begin{figure}
\centering
\includegraphics[width=\textwidth]{figures/tcd-init-pose.png}
\caption*{TCD init pose}
\end{figure}
\end{columns}
\end{frame}
\begin{frame}{Aim 1 Estimator Next Steps (v2)}
\begin{columns}
\column{0.6\textwidth}
Estimator v1 limitations $\Rightarrow$ options moving forward
\begin{itemize}
\item<1-> Knee is assumed hinge joint
\item<2-> Uncertainty (covariance) estimate is inaccurate, hence not used $\Rightarrow$ unscented Kalman filter (UKF) and particle filter (PF)
\item<3-> Orientation is assumed correct $\Rightarrow$ other state representation? (e.g., swing twist parameterisation)
\item<4-> Crouching drift $\Rightarrow$ add more sensors
\end{itemize}
\column{0.4\textwidth}
\begin{figure}
\centering
\includegraphics<2>[width=\textwidth]{figures/apr-2018Jun-uncertainty-estimate.png}
\includegraphics<3>[width=\textwidth]{figures/apr-2018Jun-uncertainty-estimate.png} \includegraphics<4>[width=\textwidth]{figures/crouch-drift.png}
\end{figure}
\end{columns}
\note[item]<1>{knee hinge joint - leave as is. design choice.}
\note[item]<2>{EKF which is good for linear systems, is not good at tracking uncertainty. Usually we have a running estimate of which information we trust more or trust less, my estimate or new sensor measurements. Strict constraints lead to numerical instability. UKF and PF for better covariance estimate and more accurate non-linear model}
\note[item]<3>{Other state representation such that my estimate remains in the constraint space}
\note[item]<2>{SR: We need to keep a running estimate of which information we trust more or trust less. The related mathematics are unstable when strict constraints (like hinge joints) are imposed. Why? Because it completely removes uncertainty in some dimensions of our variable space, but not others.}
\note[item]<3>{Crouching drift - for now we prevent it by our floor assumption which does not help in daily living as you walk stair and slopes. more sensors as suggested in my aim 2}
\end{frame}
\subsection{Aim 2 IMU+UWB estimator}
\begin{frame}{Aim 2 IMU+UWB Estimator Next Steps}
\begin{itemize}
\item Incorporate UWB ranging measurement to my estimator
\item Evaluate the accuracy of UWB and how body parts affect it
\item Prototype sensor unit using off-the-shelf components
\end{itemize}
\begin{figure}
\centering
\subcaptionbox{System overview}
{\includegraphics[height=0.5\textheight]{figures/sparse-mocap-step2.png} }
\hspace{1cm}
\subcaptionbox{Prototype v0 design by undergraduate student Jeevan Shah}
{\includegraphics[height=0.5\textheight]{figures/kmu_v0.png} }
\end{figure}
\note[item]{incorporate UWB. utilize information in the measurement update step}
\note[item]{UWB is based on wireless radio technology. Body in line of sight will definite affect its accuracy so this must be tested}
\note[item]{build from the work conducted by undergraduate thesis student Jeevan Shah}
\end{frame}
\begin{frame}{Aim 2 IMU+UWB Estimator Evaluation}
\begin{columns}
\column{0.6\textwidth}
\begin{itemize}
\item Vicon (1 mm accuracy benchmark system) vs proposed wearable system
\item Able-bodied subjects
\begin{itemize}
\item $n \approx 5$ participants
\item Action: walk, run, jumping jacks
\end{itemize}
\item Non able-bodied subjects
\begin{itemize}
\item Target: elderly with fall risk or knee osteoarthritis
\item Sample size is TBD
\item Action: walk
\end{itemize}
\item Compare accuracy of joint angles, position/orientation of body segments
\item Note: data capture will also include the setup needed for Aim 3
\end{itemize}
\column{0.4\textwidth}
\begin{figure}
\centering
\includegraphics[width=\textwidth]{figures/sample-setup.jpg}
\caption*{Sample setup}
\end{figure}
\end{columns}
\end{frame}
\subsection{Aim 3 7 segment estimator}
\begin{frame}{Aim 3 Extend to the foot}
\begin{columns}
\column{0.6\textwidth}
\begin{itemize}
\item Reformulate model to include the foot using the best configuration from Aim 2,
\item Assumptions
\begin{itemize}
\item Ankle is also hinge joint
\item (maybe) balance constraint
\end{itemize}
\end{itemize}
\note[item]{track 7 segment with 3 sensors more information is needed so I expect I'll need more assumption / information}
\column{0.4\textwidth}
\begin{figure}
\centering
\includegraphics[width=\textwidth]{figures/body3d-HJCv3.png}
\caption*{Constraint formulation}
\end{figure}
\end{columns}
\end{frame}
\section{Timeline}
\begin{frame}{Timeline}
\includegraphics[width=\textwidth]{figures/gantt-APR-2018.png}
\note[item]{This semester, finalize my LR and a draft of aim 1. In the next few months, I hope to publish my aim 1 resuls}
\note[item]{Next year, start working on IMU+UWB, and evaluation on able-bodied subjects}
\note[item]{Third year, evaluation on non-able bodied subjects, extending algorithm to include the foot}
\end{frame}
\section{Acknowledgements}
\begin{frame}
\frametitle{Acknowledgements}
Special thanks to:
\begin{itemize}
\item Scientia Prof. Nigel Lovell, Associate Prof. Stephen Redmond
\item Gait technologies group (Dr. Michael Del Rosario, Michael Raitor, Inigo Sesar)
\item Colleagues in Samuels LG
\item Neuroscience Research Australia (NeuRA)
\item My wife (Cherry Sy)
\end{itemize}
\end{frame}
\begin{frame}{}
\begin{center}
\textbf{Q \& A}
\end{center}
\end{frame}
\section{Appendix}
\begin{frame}{}
\textbf{Appendix}
\end{frame}
\begin{frame}{Aim 1 Estimator Overview (v1)}
Develop sparse sensor MoCap algorithm to track pelvis, femur, and tibia.
\begin{itemize}
\item Estimator framework: Extended Kalman Filter (EKF)
\item State $\vec{x}$: position, velocity, and orientation of the pelvis and tibia (2x)
\[
\vec{x}_{k} = \scalemath{0.75}{
\begin{bmatrix}
\vec{p}_{pelv, k} & \vec{v}_{pelv, k} & \vec{q}_{pelv, k} &
\vec{p}_{lank, k} & \vec{v}_{lank, k} & \vec{q}_{ltib, k} &
\vec{p}_{rank, k} & \vec{v}_{rank, k} & \vec{q}_{rtib, k}
\end{bmatrix}^T }
\] where$\vec{p}_{segment, k}, \vec{v}_{segment, k} \in \R^3$, and quaternion $\vec{q}_{segment, k} \in SO(3)$.
\item Input $\vec{u}$: acceleration from IMU attached to the pelvis and tibia (2x)
\[
\vec{u} = \begin{bmatrix}
a_{pelv, k} & a_{lank, k} & a_{rank, k}
\end{bmatrix}^T
\]
\end{itemize}
\end{frame}
\begin{frame}{Aim 1 Estimator Overview (v1)}
\begin{itemize}
\item Process model $x_{k+1} = f(x_{k})$
\begin{align*}
\vec{p}_{s, k+1} &= \vec{p}_{s, k} + \vec{v}_{s, k}*dt + \frac{1}{2} \vec{a}_{s, k}*dt^2 \\
\vec{v}_{s, k+1} &= \vec{v}_{s, k} + \vec{a}_{s, k}*dt \\
\vec{q}_{s, k+1} &= \vec{q}_{s, k}
\end{align*}
where $s \in \{pelv, lank/ltib, rank/rtib \}$
\item Measurement
\begin{itemize}
\item Orientation estimation $\vec{q}_{k} = ori$
\item Zero velocity update: $\vec{v}_{s, k} = 0$
\item Floor assumption: $\vec{p}_{s, k, z} = floor$
\end{itemize}
\end{itemize}
\end{frame}
%\begin{frame}[allowframebreaks]
% \frametitle{References}
% \tiny
% \bibliographystyle{ieeetr}
% \bibliography{mendeley}
%\end{frame}
\end{document}
|
% test_trifacet_signed_area.m
% Author: Ramon Casero <[email protected]>
% Copyright © 2013 University of Oxford
% Version: 0.1.0
%
% University of Oxford means the Chancellor, Masters and Scholars of
% the University of Oxford, having an administrative office at
% Wellington Square, Oxford OX1 2JD, UK.
%
% This file is part of Gerardus.
%
% 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. The offer of this
% program under the terms of the License is subject to the License
% being interpreted in accordance with English Law and subject to any
% action against the University of Oxford being under the jurisdiction
% of the English Courts.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see
% <http://www.gnu.org/licenses/>.
% Triangle with positive area
x = [
0 0
1 0
0 1
];
tri = [1 2 3];
a = trifacet_signed_area(tri, x)
% Triangle with negative area
tri = [1 3 2];
a = trifacet_signed_area(tri, x)
|
@timedtestset "test A_canonical" for ix in 1:10
psi = bimps(rand, 9, 4)
T = mpo_triangular_AF_ising_alternative()
_, psi_a = A_canonical(T, psi)
# test psi_a.A is right canonical
A_tmp = permute(psi_a.A, (1, ), (2, 3))
@test A_tmp * A_tmp' ≈ id(ℂ^9)
# fidelity
@test abs(ln_fidelity(psi_a.A, psi.A)) < 1e-14
# test the fixed point equation
@tensor lhs[-1, -2; -3] := psi_a.B[1, 3, 4] * T[-2, 5, 2, 3] * psi_a.A[-1, 2, 1] * psi_a.A'[4, -3, 5]
@test lhs ≈ (lhs[1] / psi_a.B[1]) * psi_a.B
end
@timedtestset "test B_canonical" for ix in 1:10
psi = bimps(rand, 9, 4)
T = mpo_triangular_AF_ising_alternative()
_, psi_b = B_canonical(T, psi)
# test psi_b.B is left canonical
@test psi_b.B' * psi_b.B ≈ id(ℂ^9)
# fidelity
@test abs(ln_fidelity(psi_b.B, psi.B)) < 1e-14
# test the fixed point equation
@tensor lhs[-1, -2; -3] := psi_b.A[4, 2, 1] * T[5, -2, 2, 3] * psi_b.B[1, 3, -3] * psi_b.B'[-1, 4, 5]
@test lhs ≈ (lhs[1] / psi_b.A[1]) * psi_b.A
end |
[STATEMENT]
lemma independent_AbGroups_pairwise_int0_double :
assumes "AbGroup G" "AbGroup G'" "add_independentS [G,G']"
shows "G \<inter> G' = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. G \<inter> G' = 0
[PROOF STEP]
proof (cases "G = 0")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. G = 0 \<Longrightarrow> G \<inter> G' = 0
2. G \<noteq> 0 \<Longrightarrow> G \<inter> G' = 0
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
G = 0
goal (2 subgoals):
1. G = 0 \<Longrightarrow> G \<inter> G' = 0
2. G \<noteq> 0 \<Longrightarrow> G \<inter> G' = 0
[PROOF STEP]
with assms(2)
[PROOF STATE]
proof (chain)
picking this:
AbGroup G'
G = 0
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
AbGroup G'
G = 0
goal (1 subgoal):
1. G \<inter> G' = 0
[PROOF STEP]
using AbGroup.zero_closed
[PROOF STATE]
proof (prove)
using this:
AbGroup G'
G = 0
AbGroup ?G \<Longrightarrow> (0::?'g) \<in> ?G
goal (1 subgoal):
1. G \<inter> G' = 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
G \<inter> G' = 0
goal (1 subgoal):
1. G \<noteq> 0 \<Longrightarrow> G \<inter> G' = 0
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. G \<noteq> 0 \<Longrightarrow> G \<inter> G' = 0
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
G \<noteq> 0
goal (1 subgoal):
1. G \<noteq> 0 \<Longrightarrow> G \<inter> G' = 0
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. G \<inter> G' = 0
[PROOF STEP]
proof (rule independent_AbGroups_pairwise_int0)
[PROOF STATE]
proof (state)
goal (5 subgoals):
1. \<forall>G\<in>set ?Gs. AbGroup G
2. add_independentS ?Gs
3. G \<in> set ?Gs
4. G' \<in> set ?Gs
5. G \<noteq> G'
[PROOF STEP]
from assms(1,2)
[PROOF STATE]
proof (chain)
picking this:
AbGroup G
AbGroup G'
[PROOF STEP]
show "\<forall>G\<in>set [G,G']. AbGroup G"
[PROOF STATE]
proof (prove)
using this:
AbGroup G
AbGroup G'
goal (1 subgoal):
1. \<forall>G\<in>set [G, G']. AbGroup G
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<forall>G\<in>set [G, G']. AbGroup G
goal (4 subgoals):
1. add_independentS [G, G']
2. G \<in> set [G, G']
3. G' \<in> set [G, G']
4. G \<noteq> G'
[PROOF STEP]
from assms(3)
[PROOF STATE]
proof (chain)
picking this:
add_independentS [G, G']
[PROOF STEP]
show "add_independentS [G,G']"
[PROOF STATE]
proof (prove)
using this:
add_independentS [G, G']
goal (1 subgoal):
1. add_independentS [G, G']
[PROOF STEP]
by fast
[PROOF STATE]
proof (state)
this:
add_independentS [G, G']
goal (3 subgoals):
1. G \<in> set [G, G']
2. G' \<in> set [G, G']
3. G \<noteq> G'
[PROOF STEP]
show "G \<in> set [G,G']" "G' \<in> set [G,G']"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. G \<in> set [G, G'] &&& G' \<in> set [G, G']
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
G \<in> set [G, G']
G' \<in> set [G, G']
goal (1 subgoal):
1. G \<noteq> G'
[PROOF STEP]
show "G \<noteq> G'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. G \<noteq> G'
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. G = G' \<Longrightarrow> False
[PROOF STEP]
assume GG': "G = G'"
[PROOF STATE]
proof (state)
this:
G = G'
goal (1 subgoal):
1. G = G' \<Longrightarrow> False
[PROOF STEP]
from False assms(1)
[PROOF STATE]
proof (chain)
picking this:
G \<noteq> 0
AbGroup G
[PROOF STEP]
obtain g where g: "g \<in> G" "g \<noteq> 0"
[PROOF STATE]
proof (prove)
using this:
G \<noteq> 0
AbGroup G
goal (1 subgoal):
1. (\<And>g. \<lbrakk>g \<in> G; g \<noteq> (0::'a)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using AbGroup.nonempty
[PROOF STATE]
proof (prove)
using this:
G \<noteq> 0
AbGroup G
AbGroup ?G \<Longrightarrow> ?G \<noteq> {}
goal (1 subgoal):
1. (\<And>g. \<lbrakk>g \<in> G; g \<noteq> (0::'a)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
g \<in> G
g \<noteq> (0::'a)
goal (1 subgoal):
1. G = G' \<Longrightarrow> False
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
g \<in> G
g \<noteq> (0::'a)
goal (1 subgoal):
1. G = G' \<Longrightarrow> False
[PROOF STEP]
from assms(2) GG' g(1)
[PROOF STATE]
proof (chain)
picking this:
AbGroup G'
G = G'
g \<in> G
[PROOF STEP]
have "-g \<in> G'"
[PROOF STATE]
proof (prove)
using this:
AbGroup G'
G = G'
g \<in> G
goal (1 subgoal):
1. - g \<in> G'
[PROOF STEP]
using AbGroup.neg_closed
[PROOF STATE]
proof (prove)
using this:
AbGroup G'
G = G'
g \<in> G
\<lbrakk>AbGroup ?G; ?g \<in> ?G\<rbrakk> \<Longrightarrow> - ?g \<in> ?G
goal (1 subgoal):
1. - g \<in> G'
[PROOF STEP]
by fast
[PROOF STATE]
proof (state)
this:
- g \<in> G'
goal (1 subgoal):
1. G = G' \<Longrightarrow> False
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
- g \<in> G'
goal (1 subgoal):
1. G = G' \<Longrightarrow> False
[PROOF STEP]
have "g + (-g) = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. g + - g = (0::'a)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
g + - g = (0::'a)
goal (1 subgoal):
1. G = G' \<Longrightarrow> False
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
g \<in> G
g \<noteq> (0::'a)
- g \<in> G'
g + - g = (0::'a)
[PROOF STEP]
show False
[PROOF STATE]
proof (prove)
using this:
g \<in> G
g \<noteq> (0::'a)
- g \<in> G'
g + - g = (0::'a)
goal (1 subgoal):
1. False
[PROOF STEP]
using assms(3)
[PROOF STATE]
proof (prove)
using this:
g \<in> G
g \<noteq> (0::'a)
- g \<in> G'
g + - g = (0::'a)
add_independentS [G, G']
goal (1 subgoal):
1. False
[PROOF STEP]
by force
[PROOF STATE]
proof (state)
this:
False
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
G \<noteq> G'
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
G \<inter> G' = 0
goal:
No subgoals!
[PROOF STEP]
qed |
Formal statement is: lemma scale_measure_1 [simp]: "scale_measure 1 M = M" Informal statement is: The measure obtained by scaling a measure by 1 is the same as the original measure. |
function[varargout]=col2mat(varargin)
%COL2MAT Expands 'column-appended' data into a matrix.
%
% M=COL2MAT(C), where C is a column vector of data segments separated by
% NANs, returns a matrix M in which each segment has its own column.
%
% M will have enough rows to fit the longest data segment. Segments are
% read into columns of M from the top down, leaving empty spaces at the
% bottom which are filled in with NANs.
%
% If the data is complex, then gaps are filled with NAN+SQRT(-1)*NAN;
%
% [M1,M2,...,MN]=COL2MAT(C1,C2,...,CN), where the CN are input column
% vectors, also works, as does [M1,M2,...,MN]=COL2MAT(MAT), where MAT is
% a matrix of column vectors. In both cases the locations of NaNs in the
% first column is used as the reference for the others.
%
% COL2MAT(C1,C2,...); with no output arguments overwrites the original
% input variables.
%
% COL2MAT, MAT2COL, and COLBREAKS together form a system for moving data
% with segments of nonuniform length rapidly back and forth between a
% column format and a padded-matrix format.
%
% Note that while COL2CELL and CELL2COL work for arrays having multiple
% columns, COL2MAT only works with column vectors.
%
% See also MAT2COL, COLBREAKS, COL2CELL, CELL2COL.
% _________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2000--2016 J.M. Lilly --- type 'help jlab_license' for details
%no loops!
if ischar(varargin{1})
if strcmpi(varargin{1}(1:3),'--t')
return
end
end
if isempty(varargin{1})
for i=1:nargout
varargout{i}=[];
end
return
end
if nargin>1
for i=1:nargin
eval(['data(:,' int2str(i) ')=varargin{' int2str(i) '};'])
end
else
data=varargin{1};
end
for ii=1:size(data,2)
col=data(:,ii);
if ii==1;
%Account for potential missing NaNs at the end
if ~isnan(col(end))
col(end+1)=nan;
data(end+1,:)=nan;
end
%use index into NANs and index derivative
%to determine size of new matix
nani=find(isnan(col));
dnani=diff([0;nani]);
nrows=max(dnani);
ncols=length(nani);
%determine index into top of each column ==a
%and index into first NAN in each column ==b
a=1+nrows*(0:ncols-1)';
%size(dnani)
%size(a)
b=dnani+a;
index=zeros(nrows*ncols,1);
b=b(b<length(index));
%mark all the numbers between each a and each b
index(a)=1;
index(b)=index(b)-1;%this matters (a may equal b)
index=find(cumsum(index));
if length(index)>length(col)
index=index(1:length(col));
end
end
mat=nan*ones(nrows,ncols);
mat(index)=col;
if ~isreal(mat)
vswap(mat,nan,nan+sqrt(-1)*nan);
end
varargout{ii}=mat;
end
if nargout>nargin
varargout{int2str(size(data,2)+1)}=index;
end
if nargout==0
eval(to_overwrite(nargin));
end
|
module Effekt.CpsStaged
import Effekt.CpsUnstaged
public export
data Exp : Type -> Type where
Lam : (Exp a -> Exp b) -> Exp (a -> b)
App : Exp (a -> b) -> Exp a -> Exp b
Var : String -> Exp a
Tru : Exp Bool
Fls : Exp Bool
Uni : Exp ()
Lit : Int -> Exp Int
Add : Exp Int -> Exp Int -> Exp Int
Sub : Exp Int -> Exp Int -> Exp Int
Sma : Exp Int -> Exp Int -> Exp Bool
Equ : Exp Int -> Exp Int -> Exp Bool
Tri : Exp Int -> Exp Int -> Exp Int -> Exp (Int, Int, Int)
Dis : Exp String -> Exp (IO ())
Emp : Exp (List a)
Con : Exp a -> Exp (List a) -> Exp (List a)
Str : String -> Exp String
Cat : Exp String -> Exp String -> Exp String
Noh : Exp (Maybe a)
Jus : Exp a -> Exp (Maybe a)
Ski : Exp (IO ())
Seq : Exp (IO ()) -> Exp (IO ()) -> Exp (IO ())
Ite : Exp Bool -> Exp a -> Exp a -> Exp a
Rec : (Exp (a -> b) -> Exp a -> Exp b) -> Exp (a -> b)
export
pretty : Int -> Exp a -> String
pretty s (Lam f) = "(\\x" ++ show s ++ " => " ++ pretty (s + 1) (f (Var ("x" ++ show s))) ++ ")"
pretty s (App f x) = "(" ++ pretty s f ++ " " ++ pretty s x ++ ")"
pretty s (Var x) = x
pretty s Tru = "True"
pretty s Fls = "False"
pretty s Uni = "()"
pretty s (Lit n) = show n
pretty s (Add l r) = "(" ++ pretty s l ++ " + " ++ pretty s r ++ ")"
pretty s (Sub l r) = "(" ++ pretty s l ++ " - " ++ pretty s r ++ ")"
pretty s (Sma l r) = "(" ++ pretty s l ++ " < " ++ pretty s r ++ ")"
pretty s (Equ l r) = "(" ++ pretty s l ++ " == " ++ pretty s r ++ ")"
pretty s (Tri i j k) = "(" ++ pretty s i ++ ", " ++ pretty s j ++ ", " ++ pretty s k ++ ")"
pretty s (Dis ijk) = "(putStrLn " ++ pretty s ijk ++ ")"
pretty s Emp = "[]"
pretty s (Con h t) = "(" ++ pretty s h ++ " :: " ++ pretty s t ++ ")"
pretty s (Str a) = "\"" ++ a ++ "\""
pretty s (Cat l r) = "(" ++ pretty s l ++ " ++ " ++ pretty s r ++ ")"
pretty s Noh = "Nothing"
pretty s (Jus a) = "(Just " ++ pretty s a ++ ")"
pretty s Ski = "(return ())"
pretty s (Seq l r) = "(" ++ pretty s l ++ " >> " ++ pretty s r ++ ")"
pretty s (Ite b t e) = "(if " ++ pretty s b ++ " then " ++ pretty s t ++ " else " ++ pretty s e ++ ")"
pretty s (Rec f) = "(let f" ++ show s ++ " x" ++ show (s + 1) ++ " = " ++ pretty (s + 2) (f (Var ("f" ++ show s)) (Var ("x" ++ show (s + 1)))) ++ " in f" ++ show s ++ ")"
CPS : Type -> Type -> Type
CPS r a = (Exp a -> Exp r) -> Exp r
shift0 : ((Exp a -> Exp r) -> Exp r) -> CPS r a
shift0 = id
runIn0 : CPS r a -> (Exp a -> Exp r) -> Exp r
runIn0 = id
reset0 : CPS a a -> Exp a
reset0 m = runIn0 m id
pure : Exp a -> CPS r a
pure a = \k => k a
push : (Exp a -> CPS r b) -> (Exp b -> Exp r) -> (Exp a -> Exp r)
push f k = \a => f a k
bind : CPS r a -> (Exp a -> CPS r b) -> CPS r b
bind m f = \k => m (push f k)
(>>=) : CPS r a -> (Exp a -> CPS r b) -> CPS r b
(>>=) = bind
reify : CPS r a -> Exp (Cps r a)
reify m = (Lam $ \ k => m (\a => App k a))
reflect : Exp (Cps r a) -> CPS r a
reflect m = \k => App m ((Lam $ \ a => k a))
app : CPS r (a -> Cps r b) -> CPS r a -> CPS r b
app mf ma = do
f <- mf
a <- ma
reflect (App f a)
lam : (Exp a -> CPS r b) -> CPS r (a -> Cps r b)
lam f = pure ((Lam $ \ a => reify (f a)))
export
example : Exp Int
example = Add (Lit 1) (reset0 (do
x <- shift0 (\c => c (c (Lit 100)))
pure (Add (Lit 10) x)))
resumeTwice : CPS Int (Int -> Cps Int Int)
resumeTwice = lam (\n => shift0 (\c => c (c n)))
example' : Exp Int
example' = Add (Lit 1) (reset0 (do
x <- app resumeTwice (pure (Lit 100))
pure ((Add (Lit 10) x))))
|
module Issue417 where
data _≡_ (A : Set₁) : Set₁ → Set₂ where
refl : A ≡ A
abstract
A : Set₁
A = Set
unfold-A : A ≡ Set
unfold-A = refl
-- The result of inferring the type of unfold-A is the following:
--
-- Set ≡ Set
|
[STATEMENT]
lemma simp_Plus_simps[simp]:
"simp_Plus p1 p2 = (if (fst p1 = Zero) then (fst p2, F_RIGHT (snd p2))
else (if (fst p2 = Zero) then (fst p1, F_LEFT (snd p1))
else (Plus (fst p1) (fst p2), F_Plus (snd p1) (snd p2))))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. simp_Plus p1 p2 = (if fst p1 = Zero then (fst p2, F_RIGHT (snd p2)) else if fst p2 = Zero then (fst p1, F_LEFT (snd p1)) else (Plus (fst p1) (fst p2), F_Plus (snd p1) (snd p2)))
[PROOF STEP]
by (induct p1 p2 rule: simp_Plus.induct) (auto) |
CTI allows a computer to interact with the telephone, e.g. in setting up and terminating calls with numbers taken from a directory via a PC application.
The computer (e.g. a PC located at the same desk as the telephone) directly interacts with the telephone (First Party CTI).
The computer (could also be a co-located PC) interacts with the telephone system (e.g. SIP application server), and the latter controls the telephone: Third Party CTI.
Many OpenStage and optiPoint telephones are able to use CTI, like OpenStage 80 (Third Party) or OpenStage 40 T (First Party).
Mit CTI kann ein PC mit dem Telefon kommunizieren, z. B. zum Aufbau oder Beenden von Telefonverbindungen. Gewählt können die Rufnummern aus einem Adressbuch auf dem PC, z. B. Microsoft Outlook, werden.
Ein PC (z. B. ein Arbeitsplatzrechner neben dem Telefon) kommuniziert direkt mit dem Telefon (First Party CTI).
Ein Rechner kommuniziert mit einem Telefonsystem (z. B. SIP application server) und dieser steuert das Telefon (Third Party CTI).
Viele OpenStage- und optiPoint-Telefone sind fähig, CTI zu nutzen, z. B. OpenStage 80 (Third Party) oder OpenStage 40 T (First Party).
This page was last edited on 21 November 2013, at 12:21. |
#' Date Check for Water Quality Portal
#'
#' Checks date format for inputs to the Water Quality Portal. Used in \code{readWQPqw}
#' and \code{readWQPdata}.
#'
#' @param values named list with arguments to send to the Water Quality Portal
#' @return values named list with corrected arguments to send to the Water Quality Portal
#' @keywords internal
checkWQPdates <- function(values){
dateNames <- c("startDateLo","startDateHi","startDate","endDate")
if(any(names(values) %in% dateNames)){
index <- which(names(values) %in% dateNames)
if("" %in% values[index]){
values <- values[-index[values[index] == ""]]
index <- which(names(values) %in% dateNames)
}
if(length(index) > 0){
# If a valid R date was put in, the format needs to be changed to mm-dd-yyyy for the WQP:
for(i in index){
dateInput <- as.character(values[[i]])
splitDates <- unlist(strsplit(dateInput, "-"))
if(length(splitDates) == 3){
if(nchar(splitDates[1]) == 4){ #R object
dates <- as.Date(lubridate::parse_date_time(dateInput, "%Y-%m-%d"))
dates <- format(dates, format="%m-%d-%Y")
values[i] <- dates
} else if (nchar(splitDates[3]) != 4){ #The way WQP wants it == 4, so this is probably a 2 digit year or something
warning("Please check the date format for the arguments: ",
paste(names(values)[i],values[i], collapse=", "))
}
} else { # Probably something wrong
warning("Please check the date format for the arguments: ",
paste(names(values)[i],values[i], collapse=", "))
}
}
names(values)[names(values) == 'startDate'] <- 'startDateLo'
names(values)[names(values) == 'endDate'] <- 'startDateHi'
}
}
return(values)
} |
% The COBRAToolbox: testdynamicRFBA.m
%
% Purpose:
% - testrFBA tests the dynamicRFBA function and its different outputs
%
% Author:
% - Marouen BEN GUEBILA - 31/01/2017
% save the current path
currentDir = pwd;
% initialize the test
fileDir = fileparts(which('testdynamicRFBA'));
cd(fileDir);
%load model and test data
modelReg = getDistributedModel('modelReg.mat');
load('refData_dynamicRFBA.mat');
%Solver packages
solverPkgs = {'tomlab_cplex','ibm_cplex'};
%QP solvers
QPsolverPkgs = {'tomlab_cplex','ibm_cplex'};
for k =1:length(solverPkgs)
solverLPOK = changeCobraSolver(solverPkgs{k},'LP', 0);
for j=1:length(QPsolverPkgs)%QP solvers
solverQPOK = changeCobraSolver(QPsolverPkgs{j}, 'QP', 0);
if solverLPOK && solverQPOK
substrateRxns ={'EX_glc(e)' 'EX_ac(e)'};
initConcentrations = [10.8; 1];
initBiomass = 0.001;
timeStep = 1/100;
nSteps = 200;
%Assert
[concentrationMatrixtest,excRxnNamestest,timeVectest,biomassVectest,drGenestest,constrainedRxnstest,statestest] = ...
dynamicRFBA(modelReg,substrateRxns,initConcentrations,initBiomass,timeStep,nSteps);
tol = eps(0.5);%set tolerance
%assertions
assert(any(any(abs(concentrationMatrixtest-concentrationMatrix) < tol)))
assert(isequal(excRxnNamestest,excRxnNames))
assert(isequal(timeVectest,timeVec))
assert(any(abs(biomassVectest-biomassVec) < tol))
assert(isequal(drGenestest,drGenes))
assert(isequal(constrainedRxnstest,constrainedRxns))
assert(isequal(statestest,states))
end
end
fprintf('Done.\n');
end
% change the directory
cd(currentDir)
|
The panel to the east of the north portico is Shiva in a Yogic position called <unk> , <unk> , Dharmaraja and <unk> . Resembling a Buddha , Shiva is in a dilapidated condition with only two broken arms . Shiva is seated in padmasana yogic posture ( cross legged ) on a lotus carried by two Nāgas . His crown is carved with details adorned by a crescent , a round frill at the back , and hair curls dropping on either side of the shoulders . His face is calm in mediation , his eyes half @-@ closed . This represents Shiva in penance sitting amidst the Himalayan mountains after the death of his first wife Sati , who was later reborn as Parvati . He is surrounded by divinities in the sky and attendants below . Also seen is a plantain with three leaves already open and one opening , as well as a sunflower blossom . These are flanked by two attendants . Other figures discerned from a study of the broken images are : Vishnu riding Garuda on a plantain leaf ; the Sun @-@ god Surya riding a fully saddled horse ( head missing ) ; a saint with a rosary ; two female figures in the sky draped up to their thighs ; a faceless figure of the moon with a water container ; three identical figures of a male flanked by two females ; the skeleton of a sage ; Brahma ( without one arm ) riding a swan ; and Indra without his mount ( elephant missing ) .
|
module SmallStep
import Logic
%access public export
%default total
data Tm : Type where
C : Nat -> Tm
P : Tm -> Tm -> Tm
Uninhabited (C _ = P _ _) where
uninhabited Refl impossible
Uninhabited (P _ _ = C _) where
uninhabited Refl impossible
evalF : (t : Tm) -> Nat
evalF (C n) = n
evalF (P n m) = evalF n + evalF m
data Eval : Tm -> Nat -> Type where
E_Const : Eval (C n) n
E_Plus : Eval t1 n1 -> Eval t2 n2 -> Eval (P t1 t2) (n1 + n2)
infixl 5 =+>
(=+>) : (t : Tm) -> (n : Nat) -> Type
(=+>) = Eval
infix 4 -+>
data Value : Tm -> Type where
V_Const : (n : Nat) -> Value (C n)
Uninhabited (Value (P _ _)) where
uninhabited (V_Const _) impossible
data Step : Tm -> Tm -> Type where
ST_PlusConstConst : Step (P (C n1) (C n2)) (C (n1 + n2))
ST_Plus1 : Step t1 t1' -> Step (P t1 t2) (P t1' t2)
ST_Plus2 : Value v1 -> Step t2 t2' -> Step (P v1 t2) (P v1 t2')
(-+>) : Tm -> Tm -> Type
(-+>) = Step
test_step_1 : P (P (C 0) (C 3)) (P (C 2) (C 4)) -+>
P (C (0 + 3)) (P (C 2) (C 4))
test_step_1 = ST_Plus1 ST_PlusConstConst
test_step_2 : P (C 0) (P (C 2) (P (C 0) (C 3))) -+>
P (C 0) (P (C 2) (C (0 + 3)))
test_step_2 = ST_Plus2 (V_Const 0) (ST_Plus2 (V_Const 2) ST_PlusConstConst)
step_deterministic : Deterministic Step
step_deterministic ST_PlusConstConst ST_PlusConstConst =
Refl
step_deterministic (ST_Plus1 s1) (ST_Plus1 s2) =
rewrite step_deterministic s1 s2 in Refl
step_deterministic (ST_Plus2 _ s1) (ST_Plus2 _ s2) =
rewrite step_deterministic s1 s2 in Refl
strong_progress : (t : Tm) -> Either (Value t) (t' : Tm ** t -+> t')
strong_progress (C n) = Left (V_Const n)
strong_progress (P (C n) (C m)) = Right (C (n + m) ** ST_PlusConstConst)
strong_progress (P (C n) (P t1 t2)) = case strong_progress (P t1 t2) of
Left _ impossible
Right (t' ** s) => Right (P (C n) t' ** ST_Plus2 (V_Const n) s)
strong_progress (P (P t1 t2) t3) = case strong_progress (P t1 t2) of
Left _ impossible
Right (t' ** s) => Right (P t' t3 ** ST_Plus1 s)
value_is_nf : Value v -> NormalForm Step v
value_is_nf (V_Const _) (_ ** _) impossible
nf_is_value : NormalForm Step v -> Value v
nf_is_value {v = (C k)} _ = V_Const k
nf_is_value {v = (P (C k) (C j))} contra =
absurd (contra (C (k + j) ** ST_PlusConstConst))
nf_is_value {v = (P (C k) (P t1 t2))} contra = case strong_progress (P t1 t2) of
Left _ impossible
Right (x' ** s) => absurd (contra (P (C k) x' ** ST_Plus2 (V_Const k) s))
nf_is_value {v = (P (P t1 t2) t3)} contra = case strong_progress (P t1 t2) of
Left _ impossible
Right (x' ** s) => absurd (contra (P x' t3 ** ST_Plus1 s))
nf_same_as_value : (NormalForm Step v) ↔ (Value v)
nf_same_as_value = (nf_is_value, value_is_nf)
namespace Temp1
data Value1 : Tm -> Type where
V_Const1 : (n : Nat) -> Value1 (C n)
V_Funny1 : Value1 (P t1 (C n2))
data Step1 : Tm -> Tm -> Type where
ST_PlusConstConst1 : Step1 (P (C n1) (C n2)) (C (n1 + n2))
ST_Plus11 : Step1 t1 t1' -> Step1 (P t1 t2) (P t1' t2)
ST_Plus21 : Value1 v1 -> Step1 t2 t2' -> Step1 (P v1 t2) (P v1 t2')
value1_not_same_as_normal_form : (v : Tm ** ( Value1 v
, Not (NormalForm Step1 v) ))
value1_not_same_as_normal_form =
(P (C 0) (C 0) ** (V_Funny1, \contra => contra (C 0 ** ST_PlusConstConst1)))
namespace Temp2
data Value2 : Tm -> Type where
V_Const2 : (n : Nat) -> Value2 (C n)
data Step2 : Tm -> Tm -> Type where
ST_Funny2 : Step2 (C n) (P (C n) (C 0))
ST_PlusConstConst2 : Step2 (P (C n1) (C n2)) (C (n1 + n2))
ST_Plus12 : Step2 t1 t1' -> Step2 (P t1 t2) (P t1' t2)
ST_Plus22 : Value2 v1 -> Step2 t1 t2' -> Step2 (P v1 t2) (P v1 t2')
value2_not_same_as_normal_form : (v : Tm ** ( Value2 v
, Not (NormalForm Step2 v) ))
value2_not_same_as_normal_form =
(C 0 ** (V_Const2 0, \contra => contra (P (C 0) (C 0) ** ST_Funny2)))
namespace Temp3
data Value3 : Tm -> Type where
V_Const3 : (n : Nat) -> Value3 (C n)
data Step3 : Tm -> Tm -> Type where
ST_PlusConstConst3 : Step3 (P (C n1) (C n2)) (C (n1 + n2))
ST_Plus13 : Step3 t1 t1' -> Step3 (P t1 t2) (P t1' t2)
value3_not_same_as_normal_form : (v : Tm ** ( Not (Value3 v)
, NormalForm Step3 v ))
value3_not_same_as_normal_form =
(P (C 0) (P (C 0) (C 0)) ** ( \v => case v of
V_Const3 _ impossible
, \(x' ** s) => case s of
ST_Plus13 ST_PlusConstConst3 impossible
ST_Plus13 (ST_Plus13 _) impossible ))
namespace Temp4
data Tm4 : Type where
Tru4 : Tm4
Fls4 : Tm4
Test4 : Tm4 -> Tm4 -> Tm4 -> Tm4
data Value4 : Tm4 -> Type where
V_Tru4 : Value4 Tru4
V_Fls4 : Value4 Fls4
data Step4 : Tm4 -> Tm4 -> Type where
ST_IfTrue4 : Step4 (Test4 Tru4 t1 t2) t1
ST_IfFalse4 : Step4 (Test4 Fls4 t1 t2) t2
ST_If4 : Step4 t1 t1' -> Step4 (Test4 t1 t2 t3) (Test4 t1' t2 t3)
bool_step_prop1 : Not (Step4 Fls4 Fls4)
bool_step_prop1 ST_IfTrue4 impossible
bool_step_prop1 ST_IfFalse4 impossible
bool_step_prop1 (ST_If4 _) impossible
bool_step_prop2 : Not (Step4 (Test4 Tru4
(Test4 Tru4 Tru4 Tru4)
(Test4 Fls4 Fls4 Fls4))
Tru4)
bool_step_prop2 ST_IfTrue4 impossible
bool_step_prop2 ST_IfFalse4 impossible
bool_step_prop2 (ST_If4 _) impossible
bool_step_prop3 : Step4 (Test4 (Test4 Tru4 Tru4 Tru4)
(Test4 Tru4 Tru4 Tru4)
Fls4)
(Test4 Tru4
(Test4 Tru4 Tru4 Tru4)
Fls4)
bool_step_prop3 = ST_If4 ST_IfTrue4
strong_progress_bool : (t : Tm4) -> Either (Value4 t) (t' : Tm4 ** Step4 t t')
strong_progress_bool Tru4 = Left V_Tru4
strong_progress_bool Fls4 = Left V_Fls4
strong_progress_bool (Test4 Tru4 t2 _) = Right (t2 ** ST_IfTrue4)
strong_progress_bool (Test4 Fls4 _ t3) = Right (t3 ** ST_IfFalse4)
strong_progress_bool (Test4 (Test4 t1 t2 t3) t4 t5) =
case strong_progress_bool (Test4 t1 t2 t3) of
Left _ impossible
Right (t' ** s) => Right (Test4 t' t4 t5 ** ST_If4 s)
step_deterministic_bool : Step4 x y1 -> Step4 x y2 -> y1 = y2
step_deterministic_bool ST_IfTrue4 ST_IfTrue4 = Refl
step_deterministic_bool ST_IfFalse4 ST_IfFalse4 = Refl
step_deterministic_bool (ST_If4 s1) (ST_If4 s2) =
rewrite step_deterministic_bool s1 s2 in Refl
infix 4 -+>*
(-+>*) : Relation Tm
(-+>*) = Multi Step
test_multistep_1 : P (P (C 0) (C 3)) (P (C 2) (C 4)) -+>* C 9
test_multistep_1 = MultiStep (ST_Plus1 ST_PlusConstConst) $
MultiStep (ST_Plus2 (V_Const 3) ST_PlusConstConst) $
MultiStep ST_PlusConstConst $
MultiRefl
test_multistep_2 : C 3 -+>* C 3
test_multistep_2 = MultiRefl
test_multistep_3 : P (C 0) (C 3) -+>* P (C 0) (C 3)
test_multistep_3 = MultiRefl
test_multistep_4 : P (C 0) (P (C 2) (P (C 0) (C 3))) -+>* P (C 0) (C 5)
test_multistep_4 = MultiStep (ST_Plus2 (V_Const 0)
(ST_Plus2 (V_Const 2)
ST_PlusConstConst)) $
MultiStep (ST_Plus2 (V_Const 0) ST_PlusConstConst) $
MultiRefl
NormalFormOf : (t, t' : Tm) -> Type
NormalFormOf t t' = (t -+>* t', NormalForm Step t')
normal_forms_unique : Deterministic NormalFormOf
normal_forms_unique (MultiRefl, _) (MultiRefl, _) = Refl
normal_forms_unique (MultiRefl, contra) (MultiStep {y} x_step_y _, _) =
absurd (contra (y ** x_step_y))
normal_forms_unique (MultiStep {y} x_step_y _, _) (MultiRefl, contra) =
absurd (contra (y ** x_step_y))
normal_forms_unique {y2}
p@(MultiStep x_step_y y_step_y1, contra1)
(MultiStep x_step_y3 y3_step_y2, contra2) =
let y3_eq_y = sym (step_deterministic x_step_y x_step_y3)
y_step_y2 = replace {P=\x => Multi Step x y2} y3_eq_y y3_step_y2
in normal_forms_unique (assert_smaller p (y_step_y1, contra1))
(y_step_y2, contra2)
Normalizing : (r : Relation t) -> Type
Normalizing {t} r = (x : t) -> (y : t ** (Multi r x y, NormalForm r y))
multistep_congr_1 : t1 -+>* t1' -> P t1 t2 -+>* P t1' t2
multistep_congr_1 MultiRefl = MultiRefl
multistep_congr_1 (MultiStep once next) =
MultiStep (ST_Plus1 once) (multistep_congr_1 next)
multistep_congr_2 : Value t1 -> t2 -+>* t2' -> P t1 t2 -+>* P t1 t2'
multistep_congr_2 _ MultiRefl = MultiRefl
multistep_congr_2 v (MultiStep once next) =
MultiStep (ST_Plus2 v once) (multistep_congr_2 v next)
step_normalizing : Normalizing Step
step_normalizing (C n) =
(C n ** (MultiRefl, \(_ ** s) => case s of
ST_PlusConstConst impossible
ST_Plus1 _ impossible
ST_Plus2 _ _ impossible))
step_normalizing (P t1 t2) =
let (_ ** (s1, nf1)) = step_normalizing t1
(_ ** (s2, nf2)) = step_normalizing t2
v1@(V_Const n1) = nf_is_value nf1
V_Const n2 = nf_is_value nf2
steps = multi_trans (multistep_congr_1 {t2=t2} s1) $
multi_trans (multistep_congr_2 v1 s2) $
MultiStep ST_PlusConstConst MultiRefl
in (C (n1 + n2) ** (steps, \(_ ** s) => case s of
ST_PlusConstConst impossible
ST_Plus1 _ impossible
ST_Plus2 _ _ impossible))
eval__multistep : t =+> n -> t -+>* C n
eval__multistep E_Const = MultiRefl
eval__multistep (E_Plus {n1} e1 e2) =
multi_trans (multistep_congr_1 (eval__multistep e1)) $
multi_trans (multistep_congr_2 (V_Const n1) (eval__multistep e2)) $
MultiStep ST_PlusConstConst MultiRefl
step__eval : t -+> t' -> t' =+> n -> t =+> n
step__eval ST_PlusConstConst E_Const = E_Plus E_Const E_Const
step__eval (ST_Plus1 s1) (E_Plus e1 e2) = E_Plus (step__eval s1 e1) e2
step__eval (ST_Plus2 _ s2) (E_Plus e1 e2) = E_Plus e1 (step__eval s2 e2)
multistep__eval : NormalFormOf t t' -> (n : Nat ** (t' = C n, t =+> n))
multistep__eval (MultiRefl, nf) =
let V_Const n = nf_is_value nf
in (n ** (Refl, E_Const))
multistep__eval p@(MultiStep {y} once next, nf) =
let (n ** (prf, e)) = multistep__eval (assert_smaller p (next, nf))
in (n ** (prf, step__eval once e))
evalF_eval : (evalF t = n) ↔ (t =+> n)
evalF_eval = (forward, backward)
where forward : evalF t = n -> t =+> n
forward {t = (C _)} prf = rewrite prf in E_Const
forward {t = (P t1 t2)} prf with (evalF t1) proof prf1
forward {t = (P t1 t2)} prf | _ with (evalF t2) proof prf2
forward {t = (P t1 t2)} prf | _ | _ =
rewrite sym prf
in E_Plus (forward (sym prf1)) (forward (sym prf2))
backward : t =+> n -> evalF t = n
backward E_Const = Refl
backward (E_Plus e1 e2) =
rewrite backward e1
in rewrite backward e2
in Refl
|
lemma (in metric_space) CauchyI': "(\<And>e. 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n>m. dist (X m) (X n) < e) \<Longrightarrow> Cauchy X" |
/-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
! This file was ported from Lean 3 source module linear_algebra.finsupp_vector_space
! leanprover-community/mathlib commit 019ead10c09bb91f49b1b7005d442960b1e0485f
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.LinearAlgebra.Dimension
import Mathbin.LinearAlgebra.StdBasis
/-!
# Linear structures on function with finite support `ι →₀ M`
This file contains results on the `R`-module structure on functions of finite support from a type
`ι` to an `R`-module `M`, in particular in the case that `R` is a field.
Furthermore, it contains some facts about isomorphisms of vector spaces from equality of dimension.
## TODO
Move the second half of this file to more appropriate other files.
-/
noncomputable section
attribute [local instance] Classical.propDecidable
open Set LinearMap Submodule
open Cardinal
universe u v w
namespace Finsupp
section Ring
variable {R : Type _} {M : Type _} {ι : Type _}
variable [Ring R] [AddCommGroup M] [Module R M]
theorem linearIndependent_single {φ : ι → Type _} {f : ∀ ι, φ ι → M}
(hf : ∀ i, LinearIndependent R (f i)) :
LinearIndependent R fun ix : Σi, φ i => single ix.1 (f ix.1 ix.2) :=
by
apply @linearIndependent_unionᵢ_finite R _ _ _ _ ι φ fun i x => single i (f i x)
· intro i
have h_disjoint : Disjoint (span R (range (f i))) (ker (lsingle i)) :=
by
rw [ker_lsingle]
exact disjoint_bot_right
apply (hf i).map h_disjoint
· intro i t ht hit
refine' (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _
· rw [span_le]
simp only [supᵢ_singleton]
rw [range_coe]
apply range_comp_subset_range
· refine' supᵢ₂_mono fun i hi => _
rw [span_le, range_coe]
apply range_comp_subset_range
#align finsupp.linear_independent_single Finsupp.linearIndependent_single
end Ring
section Semiring
variable {R : Type _} {M : Type _} {ι : Type _}
variable [Semiring R] [AddCommMonoid M] [Module R M]
open LinearMap Submodule
/-- The basis on `ι →₀ M` with basis vectors `λ ⟨i, x⟩, single i (b i x)`. -/
protected def basis {φ : ι → Type _} (b : ∀ i, Basis (φ i) R M) : Basis (Σi, φ i) R (ι →₀ M) :=
Basis.ofRepr
{ toFun := fun g =>
{ toFun := fun ix => (b ix.1).repr (g ix.1) ix.2
support := g.support.Sigma fun i => ((b i).repr (g i)).support
mem_support_toFun := fun ix =>
by
simp only [Finset.mem_sigma, mem_support_iff, and_iff_right_iff_imp, Ne.def]
intro b hg
simpa [hg] using b }
invFun := fun g =>
{ toFun := fun i =>
(b i).repr.symm (g.comapDomain _ (Set.injOn_of_injective sigma_mk_injective _))
support := g.support.image Sigma.fst
mem_support_toFun := fun i =>
by
rw [Ne.def, ← (b i).repr.Injective.eq_iff, (b i).repr.apply_symm_apply, ext_iff]
simp only [exists_prop, LinearEquiv.map_zero, comap_domain_apply, zero_apply,
exists_and_right, mem_support_iff, exists_eq_right, Sigma.exists, Finset.mem_image,
not_forall] }
left_inv := fun g => by
ext i
rw [← (b i).repr.Injective.eq_iff]
ext x
simp only [coe_mk, LinearEquiv.apply_symm_apply, comap_domain_apply]
right_inv := fun g => by
ext ⟨i, x⟩
simp only [coe_mk, LinearEquiv.apply_symm_apply, comap_domain_apply]
map_add' := fun g h => by
ext ⟨i, x⟩
simp only [coe_mk, add_apply, LinearEquiv.map_add]
map_smul' := fun c h => by
ext ⟨i, x⟩
simp only [coe_mk, smul_apply, LinearEquiv.map_smul, RingHom.id_apply] }
#align finsupp.basis Finsupp.basis
@[simp]
theorem basis_repr {φ : ι → Type _} (b : ∀ i, Basis (φ i) R M) (g : ι →₀ M) (ix) :
(Finsupp.basis b).repr g ix = (b ix.1).repr (g ix.1) ix.2 :=
rfl
#align finsupp.basis_repr Finsupp.basis_repr
@[simp]
theorem coe_basis {φ : ι → Type _} (b : ∀ i, Basis (φ i) R M) :
⇑(Finsupp.basis b) = fun ix : Σi, φ i => single ix.1 (b ix.1 ix.2) :=
funext fun ⟨i, x⟩ =>
Basis.apply_eq_iff.mpr <| by
ext ⟨j, y⟩
by_cases h : i = j
· cases h
simp only [basis_repr, single_eq_same, Basis.repr_self,
Finsupp.single_apply_left sigma_mk_injective]
simp only [basis_repr, single_apply, h, false_and_iff, if_false, LinearEquiv.map_zero,
zero_apply]
#align finsupp.coe_basis Finsupp.coe_basis
/-- The basis on `ι →₀ M` with basis vectors `λ i, single i 1`. -/
@[simps]
protected def basisSingleOne : Basis ι R (ι →₀ R) :=
Basis.ofRepr (LinearEquiv.refl _ _)
#align finsupp.basis_single_one Finsupp.basisSingleOne
@[simp]
theorem coe_basisSingleOne : (Finsupp.basisSingleOne : ι → ι →₀ R) = fun i => Finsupp.single i 1 :=
funext fun i => Basis.apply_eq_iff.mpr rfl
#align finsupp.coe_basis_single_one Finsupp.coe_basisSingleOne
end Semiring
section Dim
variable {K : Type u} {V : Type v} {ι : Type v}
variable [Field K] [AddCommGroup V] [Module K V]
theorem dim_eq : Module.rank K (ι →₀ V) = (#ι) * Module.rank K V :=
by
let bs := Basis.ofVectorSpace K V
rw [← bs.mk_eq_dim'', ← (Finsupp.basis fun a : ι => bs).mk_eq_dim'', Cardinal.mk_sigma,
Cardinal.sum_const']
#align finsupp.dim_eq Finsupp.dim_eq
end Dim
end Finsupp
section Module
variable {K : Type u} {V V₁ V₂ : Type v} {V' : Type w}
variable [Field K]
variable [AddCommGroup V] [Module K V]
variable [AddCommGroup V₁] [Module K V₁]
variable [AddCommGroup V₂] [Module K V₂]
variable [AddCommGroup V'] [Module K V']
open Module
theorem equiv_of_dim_eq_lift_dim
(h : Cardinal.lift.{w} (Module.rank K V) = Cardinal.lift.{v} (Module.rank K V')) :
Nonempty (V ≃ₗ[K] V') := by
haveI := Classical.decEq V
haveI := Classical.decEq V'
let m := Basis.ofVectorSpace K V
let m' := Basis.ofVectorSpace K V'
rw [← Cardinal.lift_inj.1 m.mk_eq_dim, ← Cardinal.lift_inj.1 m'.mk_eq_dim] at h
rcases Quotient.exact h with ⟨e⟩
let e := (equiv.ulift.symm.trans e).trans Equiv.ulift
exact ⟨m.repr ≪≫ₗ Finsupp.domLCongr e ≪≫ₗ m'.repr.symm⟩
#align equiv_of_dim_eq_lift_dim equiv_of_dim_eq_lift_dim
/-- Two `K`-vector spaces are equivalent if their dimension is the same. -/
def equivOfDimEqDim (h : Module.rank K V₁ = Module.rank K V₂) : V₁ ≃ₗ[K] V₂ := by
classical exact Classical.choice (equiv_of_dim_eq_lift_dim (Cardinal.lift_inj.2 h))
#align equiv_of_dim_eq_dim equivOfDimEqDim
/-- An `n`-dimensional `K`-vector space is equivalent to `fin n → K`. -/
def finDimVectorspaceEquiv (n : ℕ) (hn : Module.rank K V = n) : V ≃ₗ[K] Fin n → K :=
by
have : Cardinal.lift.{u} (n : Cardinal.{v}) = Cardinal.lift.{v} (n : Cardinal.{u}) := by simp
have hn := Cardinal.lift_inj.{v, u}.2 hn
rw [this] at hn
rw [← @dim_fin_fun K _ n] at hn
exact Classical.choice (equiv_of_dim_eq_lift_dim hn)
#align fin_dim_vectorspace_equiv finDimVectorspaceEquiv
end Module
namespace Basis
variable {R M n : Type _}
variable [DecidableEq n] [Fintype n]
variable [Semiring R] [AddCommMonoid M] [Module R M]
theorem Finset.sum_single_ite (a : R) (i : n) :
(Finset.univ.Sum fun x : n => Finsupp.single x (ite (i = x) a 0)) = Finsupp.single i a :=
by
rw [Finset.sum_congr_set {i} (fun x : n => Finsupp.single x (ite (i = x) a 0)) fun _ =>
Finsupp.single i a]
· simp
· intro x hx
rw [Set.mem_singleton_iff] at hx
simp [hx]
intro x hx
have hx' : ¬i = x := by
refine' ne_comm.mp _
rwa [mem_singleton_iff] at hx
simp [hx']
#align finset.sum_single_ite Finset.sum_single_ite
@[simp]
theorem equivFun_symm_stdBasis (b : Basis n R M) (i : n) :
b.equivFun.symm (LinearMap.stdBasis R (fun _ => R) i 1) = b i :=
by
have := EquivLike.injective b.repr
apply_fun b.repr
simp only [equiv_fun_symm_apply, std_basis_apply', LinearEquiv.map_sum, LinearEquiv.map_smulₛₗ,
RingHom.id_apply, repr_self, Finsupp.smul_single', boole_mul]
exact Finset.sum_single_ite 1 i
#align basis.equiv_fun_symm_std_basis Basis.equivFun_symm_stdBasis
end Basis
|
lemma trivial_limit_eventually: "trivial_limit net \<Longrightarrow> eventually P net" |
[STATEMENT]
lemma (in is_cf_adjunction) cf_adjunction_counit_component_is_ua_fo:
assumes "x \<in>\<^sub>\<circ> \<DD>\<lparr>Obj\<rparr>"
shows "universal_arrow_fo \<FF> x (\<GG>\<lparr>ObjMap\<rparr>\<lparr>x\<rparr>) (\<epsilon>\<^sub>C \<Phi>\<lparr>NTMap\<rparr>\<lparr>x\<rparr>)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. universal_arrow_fo \<FF> x (\<GG>\<lparr>ObjMap\<rparr>\<lparr>x\<rparr>) (\<epsilon>\<^sub>C \<Phi>\<lparr>NTMap\<rparr>\<lparr>x\<rparr>)
[PROOF STEP]
by
(
rule is_cf_adjunction.cf_adjunction_unit_component_is_ua_of[
OF is_cf_adjunction_op,
unfolded cat_op_simps,
OF assms,
unfolded cf_adjunction_unit_NTMap_op
]
) |
\section{MarkLogic简介}
\label{sec:introduction}
MarkLogic
\begin{itemize}
\item A brief motivation and introduction to the topic of the project.
\item Discuss history of the technology, mention related technologies (if relevant).
\item A brief account of the results that have been obtained in the project.
\item A one paragraph overview at the end, explaining how the rest of
the report has been organised.
\end{itemize}
\noindent
This rest of this report is organised as follows:
Section~\ref{sec:background} gives an ....
|
#define BOOST_TEST_MODULE feed
#include <boost/test/unit_test.hpp>
#include <boost/aura/device.hpp>
#include <boost/aura/environment.hpp>
#include <boost/aura/feed.hpp>
#include <boost/core/ignore_unused.hpp>
#include <iostream>
// _____________________________________________________________________________
BOOST_AUTO_TEST_CASE(basic_feed)
{
boost::aura::initialize();
{
boost::aura::feed f0;
boost::aura::device d(AURA_UNIT_TEST_DEVICE);
boost::aura::feed f(d);
f.synchronize();
boost::aura::wait_for(f);
auto base_device_handle = f.get_base_device();
boost::ignore_unused(base_device_handle);
#ifndef AURA_BASE_METAL
auto base_context_handle = f.get_base_context();
boost::ignore_unused(base_context_handle);
#endif
auto base_feed_handle = f.get_base_feed();
boost::ignore_unused(base_feed_handle);
BOOST_CHECK(
f.get_device().get_ordinal() == AURA_UNIT_TEST_DEVICE);
boost::aura::feed f2(std::move(f));
f = std::move(f2);
#ifdef AURA_BASE_METAL
auto command_buffer = f.get_command_buffer();
boost::ignore_unused(command_buffer);
#endif
}
boost::aura::finalize();
}
|
Evoking the romance of a countryside vineyard, the Grapevine Heart Wreath will bring rustic charm to your home. For a unique display, thread sprays of dried flowers such as baby's breath, through the grapevine frame. This piece is 26in wide, 22in tall, and 5in deep. |
This notebook is part of https://github.com/AudioSceneDescriptionFormat/splines, see also http://splines.readthedocs.io/.
# Derivation of Uniform Catmull-Rom Splines
tangent vectors:
\begin{equation}
\boldsymbol{\dot{x}}_i = \frac{\boldsymbol{x}_{i+1} - \boldsymbol{x}_{i-1}}{2}
\end{equation}
```python
%matplotlib inline
import sympy as sp
sp.init_printing()
```
```python
from utility import NamedExpression, NamedMatrix
```
Reminder: [Hermite splines](hermite-uniform.ipynb) use the start and end positions as well as the tangent vectors at start and end:
```python
control_values_H = sp.Matrix(sp.symbols('xbm:2 xdotbm:2'))
control_values_H
```
Catmull-Rom splines use 4 positions instead:
The start and end positions of the current segment ($\boldsymbol{x}_0$ and $\boldsymbol{x}_1$) plus the start position of the previous segment ($\boldsymbol{x}_{-1}$) and the end position of the following segment ($\boldsymbol{x}_2$).
TODO: figure? more explanations ...
```python
x_1, x0, x1, x2 = sp.symbols('xbm_-1 xbm:3')
```
```python
control_values_CR = sp.Matrix([x_1, x0, x1, x2])
control_values_CR
```
```python
xd0 = NamedExpression('xdotbm0', (x1 - x_1) / 2)
xd0
```
```python
xd1 = NamedExpression('xdotbm1', (x2 - x0) / 2)
xd1
```
So let's look for a way to transform Catmull-Rom control values to Hermite control values.
Since we already have $M_\text{H}$ from [the notebook about uniform Hermite splines](hermite-uniform.ipynb), we can use it to get $M_\text{CR}$:
```python
M_H = NamedMatrix(r'{M_\text{H}}', sp.Matrix([[2, -2, 1, 1], [-3, 3, -2, -1], [0, 0, 1, 0], [1, 0, 0, 0]]))
M_H
```
```python
M_CRtoH = NamedMatrix(r'{M_{\text{CR$\to$H}}}', 4, 4)
```
```python
M_CR = NamedMatrix(r'{M_\text{CR}}', M_H.name * M_CRtoH.name)
M_CR
```
```python
sp.Eq(control_values_H, M_CRtoH.name * control_values_CR)
```
If we substitute the above definitions of $\boldsymbol{\dot{x}}_0$ and $\boldsymbol{\dot{x}}_1$, we can directly read off the matrix elements:
```python
M_CRtoH.expr = sp.Matrix([[expr.coeff(cv) for cv in control_values_CR]
for expr in control_values_H.subs([xd0.args, xd1.args])])
M_CRtoH
```
```python
M_CRtoH.pull_out(sp.S.Half)
```
```python
print(_.expr)
```
```python
M_HtoCR = NamedMatrix(r'{M_{\text{H$\to$CR}}}', M_CRtoH.I.expr)
M_HtoCR
```
```python
print(_.expr)
```
```python
M_CR = M_CR.subs([M_H, M_CRtoH]).doit()
M_CR
```
```python
M_CR.pull_out(sp.S.Half)
```
```python
print(_.expr)
```
And for completeness' sake, its inverse:
```python
M_CR.I
```
```python
print(_.expr)
```
```python
t = sp.symbols('t')
```
```python
b_CR = NamedMatrix(r'{b_\text{CR}}', sp.Matrix([t**3, t**2, t, 1]).T * M_CR.expr)
b_CR.T
```
```python
sp.plot(*b_CR.expr, (t, 0, 1));
```
TODO: plot some example curves
|
myTestRule {
#Input parameters are:
# String with conditional query
#Output parameter is:
# Result string
msiExecStrCondQuery(*Select,*QOut);
foreach(*QOut) {
msiPrintKeyValPair("stdout",*QOut)
}
}
INPUT *Select="SELECT DATA_NAME where DATA_NAME like 'rule%%'"
OUTPUT ruleExecOut
|
A halter top like you've never seen before. Sheer poly material and denim serve as the base on top of which beading, floral and abstract details are built. This piece is one of a kind. |
(* Title: HOL/Quickcheck_Examples/Quickcheck_Examples.thy
Author: Stefan Berghofer, Lukas Bulwahn
Copyright 2004 - 2010 TU Muenchen
*)
section \<open>Examples for the 'quickcheck' command\<close>
theory Quickcheck_Examples
imports Complex_Main "HOL-Library.Dlist" "HOL-Library.DAList_Multiset"
begin
text \<open>
The 'quickcheck' command allows to find counterexamples by evaluating
formulae.
Currently, there are two different exploration schemes:
- random testing: this is incomplete, but explores the search space faster.
- exhaustive testing: this is complete, but increasing the depth leads to
exponentially many assignments.
quickcheck can handle quantifiers on finite universes.
\<close>
declare [[quickcheck_timeout = 3600]]
subsection \<open>Lists\<close>
theorem "map g (map f xs) = map (g o f) xs"
quickcheck[random, expect = no_counterexample]
quickcheck[exhaustive, size = 3, expect = no_counterexample]
oops
theorem "map g (map f xs) = map (f o g) xs"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
theorem "rev (xs @ ys) = rev ys @ rev xs"
quickcheck[random, expect = no_counterexample]
quickcheck[exhaustive, expect = no_counterexample]
quickcheck[exhaustive, size = 1000, timeout = 0.1]
oops
theorem "rev (xs @ ys) = rev xs @ rev ys"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
theorem "rev (rev xs) = xs"
quickcheck[random, expect = no_counterexample]
quickcheck[exhaustive, expect = no_counterexample]
oops
theorem "rev xs = xs"
quickcheck[tester = random, finite_types = true, report = false, expect = counterexample]
quickcheck[tester = random, finite_types = false, report = false, expect = counterexample]
quickcheck[tester = random, finite_types = true, report = true, expect = counterexample]
quickcheck[tester = random, finite_types = false, report = true, expect = counterexample]
quickcheck[tester = exhaustive, finite_types = true, expect = counterexample]
quickcheck[tester = exhaustive, finite_types = false, expect = counterexample]
oops
text \<open>An example involving functions inside other data structures\<close>
primrec app :: "('a \<Rightarrow> 'a) list \<Rightarrow> 'a \<Rightarrow> 'a" where
"app [] x = x"
| "app (f # fs) x = app fs (f x)"
lemma "app (fs @ gs) x = app gs (app fs x)"
quickcheck[random, expect = no_counterexample]
quickcheck[exhaustive, size = 2, expect = no_counterexample]
by (induct fs arbitrary: x) simp_all
lemma "app (fs @ gs) x = app fs (app gs x)"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
primrec occurs :: "'a \<Rightarrow> 'a list \<Rightarrow> nat" where
"occurs a [] = 0"
| "occurs a (x#xs) = (if (x=a) then Suc(occurs a xs) else occurs a xs)"
primrec del1 :: "'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"del1 a [] = []"
| "del1 a (x#xs) = (if (x=a) then xs else (x#del1 a xs))"
text \<open>A lemma, you'd think to be true from our experience with delAll\<close>
lemma "Suc (occurs a (del1 a xs)) = occurs a xs"
\<comment> \<open>Wrong. Precondition needed.\<close>
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
lemma "xs ~= [] \<longrightarrow> Suc (occurs a (del1 a xs)) = occurs a xs"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
\<comment> \<open>Also wrong.\<close>
oops
lemma "0 < occurs a xs \<longrightarrow> Suc (occurs a (del1 a xs)) = occurs a xs"
quickcheck[random, expect = no_counterexample]
quickcheck[exhaustive, expect = no_counterexample]
by (induct xs) auto
primrec replace :: "'a \<Rightarrow> 'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"replace a b [] = []"
| "replace a b (x#xs) = (if (x=a) then (b#(replace a b xs))
else (x#(replace a b xs)))"
lemma "occurs a xs = occurs b (replace a b xs)"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
\<comment> \<open>Wrong. Precondition needed.\<close>
oops
lemma "occurs b xs = 0 \<or> a=b \<longrightarrow> occurs a xs = occurs b (replace a b xs)"
quickcheck[random, expect = no_counterexample]
quickcheck[exhaustive, expect = no_counterexample]
by (induct xs) simp_all
subsection \<open>Trees\<close>
datatype 'a tree = Twig | Leaf 'a | Branch "'a tree" "'a tree"
primrec leaves :: "'a tree \<Rightarrow> 'a list" where
"leaves Twig = []"
| "leaves (Leaf a) = [a]"
| "leaves (Branch l r) = (leaves l) @ (leaves r)"
primrec plant :: "'a list \<Rightarrow> 'a tree" where
"plant [] = Twig "
| "plant (x#xs) = Branch (Leaf x) (plant xs)"
primrec mirror :: "'a tree \<Rightarrow> 'a tree" where
"mirror (Twig) = Twig "
| "mirror (Leaf a) = Leaf a "
| "mirror (Branch l r) = Branch (mirror r) (mirror l)"
theorem "plant (rev (leaves xt)) = mirror xt"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
\<comment> \<open>Wrong!\<close>
oops
theorem "plant((leaves xt) @ (leaves yt)) = Branch xt yt"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
\<comment> \<open>Wrong!\<close>
oops
datatype 'a ntree = Tip "'a" | Node "'a" "'a ntree" "'a ntree"
primrec inOrder :: "'a ntree \<Rightarrow> 'a list" where
"inOrder (Tip a)= [a]"
| "inOrder (Node f x y) = (inOrder x)@[f]@(inOrder y)"
primrec root :: "'a ntree \<Rightarrow> 'a" where
"root (Tip a) = a"
| "root (Node f x y) = f"
theorem "hd (inOrder xt) = root xt"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
\<comment> \<open>Wrong!\<close>
oops
subsection \<open>Exhaustive Testing beats Random Testing\<close>
text \<open>Here are some examples from mutants from the List theory
where exhaustive testing beats random testing\<close>
lemma
"[] ~= xs ==> hd xs = last (x # xs)"
quickcheck[random]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
assumes "!!i. [| i < n; i < length xs |] ==> P (xs ! i)" "n < length xs ==> ~ P (xs ! n)"
shows "drop n xs = takeWhile P xs"
quickcheck[random, iterations = 10000, quiet]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"i < length (List.transpose (List.transpose xs)) ==> xs ! i = map (%xs. xs ! i) [ys<-xs. i < length ys]"
quickcheck[random, iterations = 10000]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"i < n - m ==> f (lcm m i) = map f [m..<n] ! i"
quickcheck[random, iterations = 10000, finite_types = false]
quickcheck[exhaustive, finite_types = false, expect = counterexample]
oops
lemma
"i < n - m ==> f (lcm m i) = map f [m..<n] ! i"
quickcheck[random, iterations = 10000, finite_types = false]
quickcheck[exhaustive, finite_types = false, expect = counterexample]
oops
lemma
"ns ! k < length ns ==> k <= sum_list ns"
quickcheck[random, iterations = 10000, finite_types = false, quiet]
quickcheck[exhaustive, finite_types = false, expect = counterexample]
oops
lemma
"[| ys = x # xs1; zs = xs1 @ xs |] ==> ys @ zs = x # xs"
quickcheck[random, iterations = 10000]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"i < length xs ==> take (Suc i) xs = [] @ xs ! i # take i xs"
quickcheck[random, iterations = 10000]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"i < length xs ==> take (Suc i) xs = (xs ! i # xs) @ take i []"
quickcheck[random, iterations = 10000]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"[| sorted (rev (map length xs)); i < length xs |] ==> xs ! i = map (%ys. ys ! i) [ys<-remdups xs. i < length ys]"
quickcheck[random]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"[| sorted (rev (map length xs)); i < length xs |] ==> xs ! i = map (%ys. ys ! i) [ys<-List.transpose xs. length ys \<in> {..<i}]"
quickcheck[random]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"(ys = zs) = (xs @ ys = splice xs zs)"
quickcheck[random]
quickcheck[exhaustive, expect = counterexample]
oops
subsection \<open>Random Testing beats Exhaustive Testing\<close>
lemma mult_inj_if_coprime_nat:
"inj_on f A \<Longrightarrow> inj_on g B
\<Longrightarrow> inj_on (%(a,b). f a * g b::nat) (A \<times> B)"
quickcheck[exhaustive]
quickcheck[random]
oops
subsection \<open>Examples with quantifiers\<close>
text \<open>
These examples show that we can handle quantifiers.
\<close>
lemma "(\<exists>x. P x) \<longrightarrow> (\<forall>x. P x)"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
lemma "(\<forall>x. \<exists>y. P x y) \<longrightarrow> (\<exists>y. \<forall>x. P x y)"
quickcheck[random, expect = counterexample]
quickcheck[expect = counterexample]
oops
lemma "(\<exists>x. P x) \<longrightarrow> (\<exists>!x. P x)"
quickcheck[random, expect = counterexample]
quickcheck[expect = counterexample]
oops
subsection \<open>Examples with sets\<close>
lemma
"{} = A Un - A"
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"[| bij_betw f A B; bij_betw f C D |] ==> bij_betw f (A Un C) (B Un D)"
quickcheck[exhaustive, expect = counterexample]
oops
subsection \<open>Examples with relations\<close>
lemma
"acyclic (R :: ('a * 'a) set) ==> acyclic S ==> acyclic (R Un S)"
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"acyclic (R :: (nat * nat) set) ==> acyclic S ==> acyclic (R Un S)"
quickcheck[exhaustive, expect = counterexample]
oops
(* FIXME: some dramatic performance decrease after changing the code equation of the ntrancl *)
lemma
"(x, z) \<in> rtrancl (R Un S) \<Longrightarrow> \<exists>y. (x, y) \<in> rtrancl R \<and> (y, z) \<in> rtrancl S"
(*quickcheck[exhaustive, expect = counterexample]*)
oops
lemma
"wf (R :: ('a * 'a) set) ==> wf S ==> wf (R Un S)"
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"wf (R :: (nat * nat) set) ==> wf S ==> wf (R Un S)"
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"wf (R :: (int * int) set) ==> wf S ==> wf (R Un S)"
quickcheck[exhaustive, expect = counterexample]
oops
subsection \<open>Examples with the descriptive operator\<close>
lemma
"(THE x. x = a) = b"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
subsection \<open>Examples with Multisets\<close>
lemma
"X + Y = Y + (Z :: 'a multiset)"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"X - Y = Y - (Z :: 'a multiset)"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"N + M - N = (N::'a multiset)"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
subsection \<open>Examples with numerical types\<close>
text \<open>
Quickcheck supports the common types nat, int, rat and real.
\<close>
lemma
"(x :: nat) > 0 ==> y > 0 ==> z > 0 ==> x * x + y * y \<noteq> z * z"
quickcheck[exhaustive, size = 10, expect = counterexample]
quickcheck[random, size = 10]
oops
lemma
"(x :: int) > 0 ==> y > 0 ==> z > 0 ==> x * x + y * y \<noteq> z * z"
quickcheck[exhaustive, size = 10, expect = counterexample]
quickcheck[random, size = 10]
oops
lemma
"(x :: rat) > 0 ==> y > 0 ==> z > 0 ==> x * x + y * y \<noteq> z * z"
quickcheck[exhaustive, size = 10, expect = counterexample]
quickcheck[random, size = 10]
oops
lemma "(x :: rat) >= 0"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"(x :: real) > 0 ==> y > 0 ==> z > 0 ==> x * x + y * y \<noteq> z * z"
quickcheck[exhaustive, size = 10, expect = counterexample]
quickcheck[random, size = 10]
oops
lemma "(x :: real) >= 0"
quickcheck[random, expect = counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
subsubsection \<open>floor and ceiling functions\<close>
lemma "\<lfloor>x\<rfloor> + \<lfloor>y\<rfloor> = \<lfloor>x + y :: rat\<rfloor>"
quickcheck[expect = counterexample]
oops
lemma "\<lfloor>x\<rfloor> + \<lfloor>y\<rfloor> = \<lfloor>x + y :: real\<rfloor>"
quickcheck[expect = counterexample]
oops
lemma "\<lceil>x\<rceil> + \<lceil>y\<rceil> = \<lceil>x + y :: rat\<rceil>"
quickcheck[expect = counterexample]
oops
lemma "\<lceil>x\<rceil> + \<lceil>y\<rceil> = \<lceil>x + y :: real\<rceil>"
quickcheck[expect = counterexample]
oops
subsection \<open>Examples with abstract types\<close>
lemma
"Dlist.length (Dlist.remove x xs) = Dlist.length xs - 1"
quickcheck[exhaustive]
quickcheck[random]
oops
lemma
"Dlist.length (Dlist.insert x xs) = Dlist.length xs + 1"
quickcheck[exhaustive]
quickcheck[random]
oops
subsection \<open>Examples with Records\<close>
record point =
xpos :: nat
ypos :: nat
lemma
"xpos r = xpos r' ==> r = r'"
quickcheck[exhaustive, expect = counterexample]
quickcheck[random, expect = counterexample]
oops
datatype colour = Red | Green | Blue
record cpoint = point +
colour :: colour
lemma
"xpos r = xpos r' ==> ypos r = ypos r' ==> (r :: cpoint) = r'"
quickcheck[exhaustive, expect = counterexample]
quickcheck[random, expect = counterexample]
oops
subsection \<open>Examples with locales\<close>
locale Truth
context Truth
begin
lemma "False"
quickcheck[exhaustive, expect = counterexample]
oops
end
interpretation Truth .
context Truth
begin
lemma "False"
quickcheck[exhaustive, expect = counterexample]
oops
end
locale antisym =
fixes R
assumes "R x y --> R y x --> x = y"
interpretation equal : antisym "(=)" by standard simp
interpretation order_nat : antisym "(<=) :: nat => _ => _" by standard simp
lemma (in antisym)
"R x y --> R y z --> R x z"
quickcheck[exhaustive, finite_type_size = 2, expect = no_counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
declare [[quickcheck_locale = "interpret"]]
lemma (in antisym)
"R x y --> R y z --> R x z"
quickcheck[exhaustive, expect = no_counterexample]
oops
declare [[quickcheck_locale = "expand"]]
lemma (in antisym)
"R x y --> R y z --> R x z"
quickcheck[exhaustive, finite_type_size = 2, expect = no_counterexample]
quickcheck[exhaustive, expect = counterexample]
oops
subsection \<open>Examples with HOL quantifiers\<close>
lemma
"\<forall> xs ys. xs = [] --> xs = ys"
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"ys = [] --> (\<forall>xs. xs = [] --> xs = y # ys)"
quickcheck[exhaustive, expect = counterexample]
oops
lemma
"\<forall>xs. (\<exists> ys. ys = []) --> xs = ys"
quickcheck[exhaustive, expect = counterexample]
oops
subsection \<open>Examples with underspecified/partial functions\<close>
lemma
"xs = [] ==> hd xs \<noteq> x"
quickcheck[exhaustive, expect = no_counterexample]
quickcheck[random, report = false, expect = no_counterexample]
quickcheck[random, report = true, expect = no_counterexample]
oops
lemma
"xs = [] ==> hd xs = x"
quickcheck[exhaustive, expect = no_counterexample]
quickcheck[random, report = false, expect = no_counterexample]
quickcheck[random, report = true, expect = no_counterexample]
oops
lemma "xs = [] ==> hd xs = x ==> x = y"
quickcheck[exhaustive, expect = no_counterexample]
quickcheck[random, report = false, expect = no_counterexample]
quickcheck[random, report = true, expect = no_counterexample]
oops
text \<open>with the simple testing scheme\<close>
setup Exhaustive_Generators.setup_exhaustive_datatype_interpretation
declare [[quickcheck_full_support = false]]
lemma
"xs = [] ==> hd xs \<noteq> x"
quickcheck[exhaustive, expect = no_counterexample]
oops
lemma
"xs = [] ==> hd xs = x"
quickcheck[exhaustive, expect = no_counterexample]
oops
lemma "xs = [] ==> hd xs = x ==> x = y"
quickcheck[exhaustive, expect = no_counterexample]
oops
declare [[quickcheck_full_support = true]]
subsection \<open>Equality Optimisation\<close>
lemma
"f x = y ==> y = (0 :: nat)"
quickcheck
oops
lemma
"y = f x ==> y = (0 :: nat)"
quickcheck
oops
lemma
"f y = zz # zzs ==> zz = (0 :: nat) \<and> zzs = []"
quickcheck
oops
lemma
"f y = x # x' # xs ==> x = (0 :: nat) \<and> x' = 0 \<and> xs = []"
quickcheck
oops
lemma
"x = f x \<Longrightarrow> x = (0 :: nat)"
quickcheck
oops
lemma
"f y = x # x # xs ==> x = (0 :: nat) \<and> xs = []"
quickcheck
oops
lemma
"m1 k = Some v \<Longrightarrow> (m1 ++ m2) k = Some v"
quickcheck
oops
end
|
lemma holomorphic_on_empty [holomorphic_intros]: "f holomorphic_on {}" |
include("../benchmark.jl")
include("create_report.jl")
overlapping_results = get_CUTEst_results()
its, best, ratios, times = compute_its_etc(overlapping_results,MAX_IT=3000);
using PyPlot
PyPlot.close()
plot_iteration_ratios(its, best, ratios)
savefig("$folder/inf_iter_ratios.pdf")
|
section \<open> CSP and Circus process examples \<close>
theory utp_csp_ex
imports "../theories/circus/utp_circus"
begin
subsection \<open> Sequential Examples \<close>
text \<open> In this theory we calculate reactive designs for a number of simple CSP/Circus processes. \<close>
datatype ev = a | b | c
lemma csp_ex_1:
"(a \<^bold>\<rightarrow> Skip) = \<^bold>R\<^sub>s(true\<^sub>r \<turnstile> \<E>(true,\<langle>\<rangle>, {\<guillemotleft>a\<guillemotright>}\<^sub>u) \<diamondop> \<Phi>(true,id\<^sub>s,\<langle>\<guillemotleft>a\<guillemotright>\<rangle>))"
by (rdes_simp)
lemma csp_ex_2:
"(a \<^bold>\<rightarrow> Chaos) = \<^bold>R\<^sub>s ((\<I>(true,\<langle>\<guillemotleft>a\<guillemotright>\<rangle>)) \<turnstile> \<E>(true,\<langle>\<rangle>, {\<guillemotleft>a\<guillemotright>}\<^sub>u) \<diamondop> false)"
by (rdes_simp)
lemma csp_ex_3:
"(a \<^bold>\<rightarrow> b \<^bold>\<rightarrow> Skip)
= \<^bold>R\<^sub>s (true\<^sub>r \<turnstile> (\<E>(true,\<langle>\<rangle>, {\<guillemotleft>a\<guillemotright>}\<^sub>u) \<or> \<E>(true,\<langle>\<guillemotleft>a\<guillemotright>\<rangle>, {\<guillemotleft>b\<guillemotright>}\<^sub>u)) \<diamondop> \<Phi>(true,id\<^sub>s,\<langle>\<guillemotleft>a\<guillemotright>, \<guillemotleft>b\<guillemotright>\<rangle>))"
by (rdes_simp)
lemma csp_ex_4:
"(a \<^bold>\<rightarrow> Stop \<box> b \<^bold>\<rightarrow> Skip) =
\<^bold>R\<^sub>s (true\<^sub>r \<turnstile> (\<E>(true,\<langle>\<rangle>, {\<guillemotleft>a\<guillemotright>, \<guillemotleft>b\<guillemotright>}\<^sub>u) \<or> \<E>(true,\<langle>\<guillemotleft>a\<guillemotright>\<rangle>, {}\<^sub>u)) \<diamondop> \<Phi>(true,id\<^sub>s,\<langle>\<guillemotleft>b\<guillemotright>\<rangle>))"
by (rdes_simp)
lemma csp_ex_5:
"(a \<^bold>\<rightarrow> Chaos \<box> b \<^bold>\<rightarrow> Skip) = \<^bold>R\<^sub>s (\<I>(true,\<langle>\<guillemotleft>a\<guillemotright>\<rangle>) \<turnstile> \<E>(true,\<langle>\<rangle>, {\<guillemotleft>a\<guillemotright>, \<guillemotleft>b\<guillemotright>}\<^sub>u) \<diamondop> \<Phi>(true,id\<^sub>s,\<langle>\<guillemotleft>b\<guillemotright>\<rangle>))"
by (rdes_simp)
lemma csp_ex_6:
assumes "P is NCSP" "Q is NCSP"
shows "(a \<^bold>\<rightarrow> P \<box> a \<^bold>\<rightarrow> Q) = a \<^bold>\<rightarrow> (P \<sqinter> Q)"
by (rdes_simp cls: assms)
lemma csp_ex_7: "a \<^bold>\<rightarrow> a \<^bold>\<rightarrow> a \<^bold>\<rightarrow> Miracle \<sqsubseteq> a \<^bold>\<rightarrow> Miracle"
by (rdes_refine)
lemma csp_ex_8:
"a \<^bold>\<rightarrow> b \<^bold>\<rightarrow> Skip \<box> c \<^bold>\<rightarrow> Skip =
\<^bold>R\<^sub>s (true\<^sub>r \<turnstile> (\<E>(true,\<langle>\<rangle>, {\<guillemotleft>a\<guillemotright>, \<guillemotleft>c\<guillemotright>}\<^sub>u) \<or> \<E>(true,\<langle>\<guillemotleft>a\<guillemotright>\<rangle>, {\<guillemotleft>b\<guillemotright>}\<^sub>u)) \<diamondop> (\<Phi>(true,id\<^sub>s,\<langle>\<guillemotleft>a\<guillemotright>, \<guillemotleft>b\<guillemotright>\<rangle>) \<or> \<Phi>(true,id\<^sub>s,\<langle>\<guillemotleft>c\<guillemotright>\<rangle>)))"
by (rdes_simp)
subsection \<open> State Examples \<close>
lemma assign_prefix_ex:
assumes "vwb_lens x"
shows "x :=\<^sub>C 1 ;; a \<^bold>\<rightarrow> x :=\<^sub>C (&x + 2) = a \<^bold>\<rightarrow> x :=\<^sub>C 3"
(is "?lhs = ?rhs")
proof -
from assms have "?lhs = \<^bold>R\<^sub>s (true\<^sub>r \<turnstile> \<E>(true,\<langle>\<rangle>, {\<guillemotleft>a\<guillemotright>}\<^sub>u) \<diamondop> \<Phi>(true,[&x \<mapsto>\<^sub>s 3],\<langle>\<guillemotleft>a\<guillemotright>\<rangle>))"
by (rdes_simp)
also have "... = ?rhs"
by (rdes_simp)
finally show ?thesis .
qed
subsection \<open> Parallel Examples \<close>
lemma csp_parallel_ex1:
"(a \<^bold>\<rightarrow> Skip) \<lbrakk>{a}\<rbrakk>\<^sub>C (a \<^bold>\<rightarrow> Skip) = a \<^bold>\<rightarrow> Skip" (is "?lhs = ?rhs")
by (rdes_eq)
lemma csp_parallel_ex2:
"(a \<^bold>\<rightarrow> Skip) \<lbrakk>{a,b}\<rbrakk>\<^sub>C (b \<^bold>\<rightarrow> Skip) = Stop" (is "?lhs = ?rhs")
by (rdes_eq)
lemma csp_parallel_ex3:
"(a \<^bold>\<rightarrow> b \<^bold>\<rightarrow> Skip) \<lbrakk>{b}\<rbrakk>\<^sub>C (b \<^bold>\<rightarrow> c \<^bold>\<rightarrow> Skip) = a \<^bold>\<rightarrow> b \<^bold>\<rightarrow> c \<^bold>\<rightarrow> Skip" (is "?lhs = ?rhs")
by (rdes_eq)
lemma csp_parallel_ex4:
"(a \<^bold>\<rightarrow> Skip \<box> b \<^bold>\<rightarrow> Skip) \<lbrakk>{b}\<rbrakk>\<^sub>C (b \<^bold>\<rightarrow> Skip) = a \<^bold>\<rightarrow> Stop \<box> b \<^bold>\<rightarrow> Skip" (is "?lhs = ?rhs")
by (rdes_eq)
lemma csp_parallel_ex5:
"(a \<^bold>\<rightarrow> Chaos \<box> b \<^bold>\<rightarrow> Skip) \<lbrakk>{a, b}\<rbrakk>\<^sub>C (b \<^bold>\<rightarrow> Skip) = b \<^bold>\<rightarrow> Skip" (is "?lhs = ?rhs")
by (rdes_eq)
lemma csp_parallel_ex6:
assumes "vwb_lens ns\<^sub>1" "vwb_lens ns\<^sub>2" "x \<subseteq>\<^sub>L ns\<^sub>1" "y \<subseteq>\<^sub>L ns\<^sub>2" "ns\<^sub>1 \<bowtie> ns\<^sub>2"
shows "(x :=\<^sub>C u) \<lbrakk>ns\<^sub>1\<parallel>{b}\<parallel>ns\<^sub>2\<rbrakk> (y :=\<^sub>C v) = \<langle>[x \<mapsto>\<^sub>s u, y \<mapsto>\<^sub>s v]\<rangle>\<^sub>C"
using assms by (rdes_eq)
lemma csp_interleave_ex1: "(a \<^bold>\<rightarrow> Skip) ||| (b \<^bold>\<rightarrow> Skip) = (a \<^bold>\<rightarrow> b \<^bold>\<rightarrow> Skip \<box> b \<^bold>\<rightarrow> a \<^bold>\<rightarrow> Skip)"
by (rdes_eq)
lemma csp_hiding_ex1: "(a \<^bold>\<rightarrow> b \<^bold>\<rightarrow> Skip) \\\<^sub>C {b} = a \<^bold>\<rightarrow> Skip"
by (rdes_eq)
lemma "(while\<^sub>C true do a \<^bold>\<rightarrow> b \<^bold>\<rightarrow> Skip od) \<lbrakk>{b}\<rbrakk>\<^sub>C (while\<^sub>C true do b \<^bold>\<rightarrow> c \<^bold>\<rightarrow> Skip od) =
while\<^sub>C true do a \<^bold>\<rightarrow> b \<^bold>\<rightarrow> c \<^bold>\<rightarrow> Skip od"
apply (rdes_eq_split)
oops
(*
lemma
assumes "P is NCSP" "Q is NCSP" "pre\<^sub>R P = true" "pre\<^sub>R Q = true" "B\<^sub>1 \<noteq> {}" "A\<^sub>1 \<noteq> {}"
"peri\<^sub>R(P) = (\<Sqinter> i\<in>A\<^sub>1\<bullet> \<E>(s\<^sub>P\<^sub>1(i),t\<^sub>P\<^sub>1(i),E\<^sub>P(i)))"
"post\<^sub>R(P) = (\<Sqinter> i\<in>A\<^sub>2\<bullet> \<Phi>(s\<^sub>P\<^sub>2(i),\<sigma>\<^sub>P(i),t\<^sub>P\<^sub>2(i)))"
"peri\<^sub>R(Q) = (\<Sqinter> i\<in>B\<^sub>1\<bullet> \<E>(s\<^sub>Q\<^sub>1(i),t\<^sub>Q\<^sub>1(i),E\<^sub>Q(i)))"
"post\<^sub>R(Q) = (\<Sqinter> i\<in>B\<^sub>2\<bullet> \<Phi>(s\<^sub>Q\<^sub>2(i),\<sigma>\<^sub>Q(i),t\<^sub>Q\<^sub>2(i)))"
shows "(a \<^bold>\<rightarrow> P) ||| (b \<^bold>\<rightarrow> Q) = (a \<^bold>\<rightarrow> (P ||| (b \<^bold>\<rightarrow> Q)) \<box> b \<^bold>\<rightarrow> ((a \<^bold>\<rightarrow> P) ||| Q))"
apply (rdes_eq_split cls: assms(1-2))
apply (simp_all add: assms wp rpred closure usubst unrest rdes_rel_norms)
*)
end |
Dallas Cole: UC Davis CalPIRG Treasurer Spring 2006, Chapter Chair 20062007
Phone Number: (916) 9527609
CalPIRG Office: 360 MU Third floor of the MU opposite side of the elevator
|
module TicTacToe.Simple
import TicTacToe.GameState
import TicTacToe.Player
import Data.Matrix
%access export
%default total
public export
Grid : Type
Grid = Matrix 3 3 (Maybe Player)
public export
Position : Type
Position = (Fin 3, Fin 3)
namespace Grid
export
show : Grid -> String
show g = unlines . intersperse rule . toList . map row $ g
where
row : Vect 3 (Maybe Player) -> String
row = strCons ' ' . concat . intersperse " | " . map showCell
rule : String
rule = pack $ List.replicate 11 '-'
--rule = pack $ List.replicate (n * 3 + (n `minus` 1)) '-'
public export
emptyGrid : Grid
emptyGrid = replicate _ . replicate _ $ Nothing
public export
get : Position -> Grid -> Maybe Player
get (x, y) = indices x y
public export
set : Player -> Position -> Grid -> Grid
set p (x, y) g = replaceAt x (replaceAt y (Just p) (getRow x g)) g
public export
occupied : Grid -> Nat
occupied = sum . map (DPair.fst . filter isJust)
public export
free : Position -> Grid -> Bool
free (x, y) = isNothing . indices x y
public export
hasWinner : Grid -> Maybe Player
hasWinner g = List.find pred (rows g) >>= Vect.head
where
rows : Grid -> List (Vect 3 (Maybe Player))
rows m = (diag m) :: (diag . reverse $ m) :: toList m ++ (toList $ transpose m)
pred : Vect 3 (Maybe Player) -> Bool
pred v = all (== Just Cross) v || all (== Just Nought) v
public export
data IsNothing : Maybe a -> Type where
ItIsNothing : IsNothing Nothing
public export
Uninhabited (IsNothing (Just v)) where
uninhabited ItIsNothing impossible
public export
isItNothing : (v : Maybe a) -> Dec (IsNothing v)
isItNothing Nothing = Yes ItIsNothing
isItNothing (Just _) = No absurd
public export
data Empty : (pos : Position) -> (g : Grid) -> Type where
IsEmpty : {auto prf : IsNothing (get pos g)} -> Empty pos g
public export
isEmptyJust : (contra : IsNothing (get pos g) -> Void) -> Empty pos g -> Void
isEmptyJust contra (IsEmpty {prf}) = contra prf
isEmpty : (pos : Position) -> (g : Grid) -> Dec (Empty pos g)
isEmpty pos g with (isItNothing (get pos g))
isEmpty _ _ | (Yes prf) = Yes IsEmpty
isEmpty _ _ | (No contra) = No (isEmptyJust contra)
public export
data Board : (g : Grid) -> (p : Player) -> (turn : Nat) -> Type where
Start : Board Simple.emptyGrid Cross 0
Turn : (pos : Position)
-> Board g p turn
-> {auto prf : Empty pos g}
-> Board (set p pos g) (switch p) (S turn)
Show (Board g p turn) where
show {g} _ = Grid.show g
public export
status : Board g p turn -> GameState
status {g} {turn} _ = case hasWinner g of
Nothing => if turn == 9
then Ended Draw
else InPlay
Just winner => Ended (Won winner)
public export
data Game : {g : Grid} -> (b : Board g p turn) -> GameState -> Type where
MkGame : (b : Board g p turn) -> Game b (status b)
Show (Game b state) where
show (MkGame {g} _) = Grid.show g
initGame : Game Start InPlay
initGame = MkGame Start
move : {b : Board g p turn}
-> (pos : Position)
-> Game b InPlay
-> {auto prf : Empty pos g}
-> (st : GameState ** Game (Turn pos b {prf = prf}) st)
move pos _ {b} {prf} = (_ ** MkGame (Turn pos b {prf = prf}))
winner : Game b (Ended (Won p)) -> Player
winner {p} _ = p
currentStatus : Game b st -> GameState
currentStatus {st} _ = st
currentGrid : Game b st -> Grid
currentGrid (MkGame {g} _) = g
currentBoard : {b : Board g p turn} -> Game b st -> Board g p turn
currentBoard (MkGame b) = b
|
%SHAPE Abstract superclass for primitive shapes
%
% Defines concrete and abstract properties and methods which are common
% to all shape subclasses (primitives). Also contains some functions
%
% Copyright (C) Bryan Moutrie, 2013-2014
% Licensed under the GNU Lesser General Public License
% see full file for full statement
%
% Syntax:
% (1) shape = Shape(T, s, ...)
%
% Outputs:
% shape : Shape object. Note as Shape is abstract it cannot be
% instantiated, hence shape is an object of a Shape subclass.
%
% Inputs:
% T : See transform property
% s : See scale property (can be input as scalar or 3-vector)
% ... : Options - other properties in name-value pairs
%
% See documentation for information on properties and methods
% (type doc Shape into the command window)
%
% See also Box.Box CollisionModel Cone Curvilinear Cylinder.Cylinder
% Ellipsoid.Ellipsoid Sphere.Sphere surface
% LICENSE STATEMENT:
%
% This file is part of pHRIWARE.
%
% pHRIWARE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation, either version 3 of
% the License, or (at your option) any later version.
%
% pHRIWARE 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 pHRIWARE. If not, see <http://www.gnu.org/licenses/>.
classdef (Abstract) Shape
properties
% Short text description of object for user reference
note = '<Add a description with note property>'
transform = eye(4) % Transformation matrix of the shape
scale = [1 1 1] % Scale vector of the shape, [s_x s_y s_z]
FaceColor = pHRIWARE('blue'); % The surface property
FaceAlpha = 1 % The surface property
EdgeColor = pHRIWARE('navy'); % The surface property
EdgeAlpha = 1 % The surface property
end
properties (Abstract)
volume % Volume of shape
%FACES Logical vector of which faces to plot
% For Boxes, faces is a 1x6 vector, whose elements correspond
% to the faces in the negative y-z, x-z, x-y and positive y-z,
% x-z, x-y planes, with respect to that shape's frame,
% in that order
% For Curvilinears, faces is a 1x2 vector, whose elements
% correspond to the end faces whose centres are at the origin
% and not at the origin, with respect to that shape's frame,
% in that order
% For Ellipsoids, faces is not currently used
faces
%N "Resolution" of the shape, for plotting
% For Boxes, each face will comprise of an nxn grid of points
% For Curvilinears, it is the equivalent of cylinder(n)
% For Ellipsoids, it is the equivalent of sphere(n)
n
end
properties (Constant)
sym = exist('sym','class'); % Symbolic Math Toolbox install flag
end
methods (Abstract)
%PLOT Plot the shape
%
% Plots the shape object to the current figure as a surface
% object or objects. Only a few options are included, but a
% graphics handle can be optionally returned for more advanced
% demands.
%
% Copyright (C) Bryan Moutrie, 2013-2014
% Licensed under the GNU General Public License, see file for
% statement
%
% Syntax:
% (1) shape.plot()
% (2) shape.plot(...)
% (3) h = shape.plot(...)
%
% (1) Plots the shape with the options specified by its
% various properties
% (2) is as per (1) but can specify over-riding values for
% options for the plot only, in name-value pairs
% (3) is as per (1) or (2) but returns a handle or vecor of
% handles to the surface objects plotted
%
% Outputs:
% h : graphics handle for each surface plotted
%
% Inputs:
% ... : Plotting options (which are Shape properties), in
% name-value pairs
%
% See also Shape.cloud Shape.parseopts
h = plot(shape, varargin)
%CLOUD Generate point cloud from shape
%
% Generates three arrays corresponding to the x, y and z points
% of a shape's point data which is readable by the surface
% function. If the shape is a Box, the third dimension of X, Y,
% and Z is the points for each face - therefore some points are
% duplicated (more specifically the corner and edge points)
%
% Copyright (C) Bryan Moutrie, 2013-2014
% Licensed under the GNU General Public License, see file for
% statement
%
% Syntax:
% (1) [X, Y, Z] = shape.cloud()
%
% Outputs:
% X : array of x-coordinates
% Y : array of y-coordinates
% Z : array of z-coordinates
%
% See also Shape.plot surface
[X, Y, Z] = cloud(shape)
%CHECK Check if point(s) are inside the shape
%
% Check to see if point(s) lie inside a primitive shape.
% Points on the surface are treated as outside the shape.
%
% Copyright (C) Bryan Moutrie, 2013-2014
% Licensed under the GNU General Public License, see file for
% statement
%
% Syntax:
% (1) c = shape.check(x, y, z)
% (2) c = shape.check(p)
% (3) f = shape.check()
% (4) h = shape.check()
%
% (2) is as per (1) where p = [x, y, z]
% (3) Requires the MuPAD symbolic mathematics toolbox
% (4) Repalces (3) if no MuPAD symbolic mathematics toolbox
%
% Outputs:
% c : mx1 vector, where there are m points. Each element is
% the logical value of the mth point being inside the
% shape
% f : anonymous function, f(x, y, z), which reduces check to a
% simplified, one-line evaluation
% h : function handle, h(x, y, z), OR h(p), which reduces
% check to a simplified, one-line evaluation
%
% Inputs:
% x : x-coordinate(s) of point(s), may be any size/shape
% y : y-coordinate(s) of point(s), may be any size/shape
% z : z-coordinate(s) of point(s), may be any size/shape
% p : An mx3 matrix, where each column is x, y, z. m may be 1.
%
% See also CollisionModel SerialLink.collisions sym2func
c = check(shape, varargin)
end
methods
function shape = Shape(T, s, varargin)
shape = shape.parseopts(varargin{:});
if ~isempty(T), shape.transform = T; end
if ~isempty(s), shape.scale = s; end
end
function disp(shape)
w = whos('shape');
line1 = [w.class,': ',shape.note];
line2(1:length(line1)) = '-';
line3 = 'transform =';
line4 = ['scale = ',mat2str(shape.scale)];
line5 = ['volume = ',num2str(shape.volume), ' u^3'];
if isprop(shape,'radius'),
if ~isa(shape.radius,'function_handle') %#ok<*MCNPN>
line6 = ['radius = ',num2str(shape.radius)];
else
line6 = ['radius = ',func2str(shape.radius)];
end
else
line6 = [];
end
line7 = line2;
line8 = 'Plot options:';
line9 = ['FaceColor = ',mat2str(shape.FaceColor,2),...
' | FaceAlpha = ',num2str(shape.FaceAlpha)];
line10 = ['EdgeColor = ',mat2str(shape.EdgeColor,2),...
' | EdgeAlpha = ',num2str(shape.EdgeAlpha)];
line11 = ['n = ',num2str(shape.n),' | faces = ',...
mat2str(shape.faces),];
disp(line1);
disp(line2);
disp(line3);
disp(shape.transform);
disp(line4);
disp(line5);
disp(line6);
disp(line7);
disp(line8);
disp(line9);
disp(line10);
disp(line11);
end
function [shape, frames] = parseopts(shape, varargin)
%PARSEOPTS Set plot options (and more) in one line
%
% Parses multiple plot options to shape properties (faces,
% n, FaceColor, FaceAlpha, EdgeColor, EdgeAlpha) in
% name-value pairs. The note property can also be set.
% Additionally, the pair "'animate', frames" may be used to
% animate the shape with the transformations in frames
% within the plot method. If not specified, is identity.
%
% Copyright (C) Bryan Moutrie, 2013-2014
% Licensed under the GNU General Public License, see file
% for statement
%
% Syntax:
% (1) [shape, frames] = shape.parseopts(...)
%
% Outputs:
% shape : Shape object with new property values
% frames : Coordinate frames to animate shape. Relative to
% the shape's own transform.
%
% Inputs:
% ... : Options - plotting properties in name-value pairs
frames = [];
for i = 1: 2: length(varargin)-1
if strcmp(varargin{i},'FaceColor')
shape.FaceColor = varargin{i+1};
elseif strcmp(varargin{i},'FaceAlpha')
shape.FaceAlpha = varargin{i+1};
elseif strcmp(varargin{i},'EdgeColor')
shape.EdgeColor = varargin{i+1};
elseif strcmp(varargin{i},'EdgeAlpha')
shape.EdgeAlpha = varargin{i+1};
elseif strcmp(varargin{i},'animate')
frames = varargin{i+1};
elseif strcmp(varargin{i},'n')
shape.n = varargin{i+1};
elseif strcmp(varargin{i},'faces')
shape.faces = varargin{i+1};
elseif strcmp(varargin{i},'note')
shape.note = varargin{i+1};
else
error(pHRIWARE('error','inputValue'));
end
end
end
function vargout = animate(shape, h, frames)
%ANIMATE Animate a plotted shape
%
% Animate a plotted shape by applying a series of
% transformations to its graphics handle. A handle can be
% returned by a call to plot. Transformations for each
% frame are applied before the shape's own transformation.
% Animation is at a fixed 100 fps.
%
% Copyright (C) Bryan Moutrie, 2013-2014
% Licensed under the GNU General Public License, see file
% for statement
%
% Syntax:
% (1) shape.animate(h, frames)
% (2) h = shape.animate(h, frames)
%
% (2) is as per (1) but returns graphics handle of
% animated shape
%
% Outputs:
% h : Modified graphics handle(s)
%
% Inputs:
% h : Graphics handle(s) of a Shape object
% frames: 4x4xm array of m frames/transformation matrices
%
% See also Shape.plot
t = hgtransform;
set(h,'Parent',t);
for i = 1: size(frames,3)
set(t, 'Matrix', frames(:,:,i));
pause(0.01);
end
if nargout == 1, vargout = h; end
end
function shape = set.note(shape, note)
if ~ischar(note)
error(pHRIWARE('error','inputType'));
else
shape.note = note;
end
end
function shape = set.scale(shape, scale)
shape.scale = scale .* [1 1 1]; % Allows scalar or 3-vector
end
% function f = dyncheck(s, points)
% s.transform = symT * s.transform;
% switch nargin
% case 1
% dyncheck = s.check;
% f = @(T,x,y,z) dyncheck(T(1),T(5),T(9),...
% T(2),T(6),T(10),...
% T(3),T(7),T(11),...
% T(13),T(14),T(15),x,y,z);
% case 2
% dyncheck = s.check(points);
% f = @(T) dyncheck(T(1),T(5),T(9),...
% T(2),T(6),T(10),...
% T(3),T(7),T(11),...
% T(13),T(14),T(15));
% end
% end
end
methods (Access = protected)
function [Xst, Yst, Zst] = sat(shape, X, Y, Z)
%SAT Scale and transform point cloud data
X_sz = size(X);
Y_sz = size(Y);
Z_sz = size(Z);
X = X(:) * shape.scale(1);
Y = Y(:) * shape.scale(2);
Z = Z(:) * shape.scale(3);
P = shape.transform * [X, Y, Z, ones(size(X))]';
Xst = reshape(P(1,:), X_sz);
Yst = reshape(P(2,:), Y_sz);
Zst = reshape(P(3,:), Z_sz);
end
end
end |
set_option trace.Elab true
theorem ex (h : a = b) : (fun x => x) a = b := by
simp (config := { beta := false })
trace_state
simp (config := { beta := true }) [h]
|
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4231)
#endif
#include <log4cxx/logmanager.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/propertyconfigurator.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <windows.h>
#include <shlwapi.h>
#include "YDJAPI.h"
#include "DllMain.h"
namespace fs = boost::filesystem;
#pragma comment(lib, "shlwapi.lib")
namespace NYDWE
{
HMODULE gSelfModule;
log4cxx::LoggerPtr gJAPIFrameworkLogger;
} // namespace NYDWE
BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID pReserved)
{
using namespace NYDWE;
if (reason == DLL_PROCESS_ATTACH)
{
DisableThreadLibraryCalls(module);
gSelfModule = module;
// Initialize locale
std::locale::global(std::locale("", LC_CTYPE));
// Self path
WCHAR buffer[MAX_PATH];
GetModuleFileNameW(module, buffer, sizeof(buffer) / sizeof(buffer[0]));
PathRemoveBlanksW(buffer);
PathUnquoteSpacesW(buffer);
PathRemoveBackslashW(buffer);
bool isAutoCalledByMSSEngine = boost::iends_with(buffer, L".m3d") || boost::iends_with(buffer, L".asi")
|| boost::iends_with(buffer, L".flt");
// Initialize logger
bool isConfigured = log4cxx::LogManager::getLoggerRepository()->isConfigured();
if (!isConfigured)
{
// If exists configuration file, use it
PathRemoveFileSpecW(buffer);
PathAppendW(buffer, L"YDJAPILogger.cfg");
if (PathFileExistsW(buffer))
{
log4cxx::PropertyConfigurator::configure(buffer);
isConfigured = true;
}
else
{
// Default configuration
log4cxx::BasicConfigurator::configure();
}
}
gJAPIFrameworkLogger = log4cxx::Logger::getLogger(LOG4CXX_STR("YDJAPIFramework"));
// Disable log if no configuration
if (!isConfigured)
{
gJAPIFrameworkLogger->setLevel(log4cxx::Level::getOff());
}
if (isAutoCalledByMSSEngine)
{
LOG4CXX_DEBUG(gJAPIFrameworkLogger, "Called by MSS sound engine, now try auto initialize.");
HMODULE gameDll = GetModuleHandleW(L"game.dll");
if (gameDll)
InitJAPIFramework(gameDll);
else
LOG4CXX_INFO(gJAPIFrameworkLogger, "Cannot find game.dll in process. Maybe we are not called by warcraft.");
}
LOG4CXX_INFO(gJAPIFrameworkLogger, "YDWE JAPI framework loaded.");
}
else if (reason == DLL_PROCESS_DETACH)
{
LOG4CXX_INFO(gJAPIFrameworkLogger, "YDWE JAPI framework unloaded.");
// Clean logger
gJAPIFrameworkLogger = NULL;
}
return TRUE;
}
|
program prog
logical a
a = .fals.
end
|
(** Coq coding by choukh, Oct 2021 **)
Require Import BBST.Axiom.Meta.
Require Import BBST.Axiom.Extensionality.
Require Import BBST.Axiom.Replacement.
Require Import BBST.Definition.Emptyset.
Require Import BBST.Definition.Singleton.
Require Import BBST.Definition.BinaryUnion.
Require Import BBST.Definition.BinaryIntersect.
Require Import BBST.Definition.Function.
Require Import BBST.Definition.Restriction.
Require Import BBST.Lemma.BasicFunction.
Lemma 函数之二元并 : ∀ f g, 为函数 f → 为函数 g →
(∀x ∈ dom f ∩ dom g, f[x] = g[x]) ↔ 为函数 (f ∪ g).
Proof with eauto.
intros * Hf Hg. split; intros.
- split.
+ (* 为序偶集 *) intros p Hp. apply 二元并除去 in Hp as [].
apply Hf in H0... apply Hg in H0...
+ (* 单值 *) intros x y z Hxy Hxz.
apply 二元并除去 in Hxy as [];
apply 二元并除去 in Hxz as []; [eapply Hf| | |eapply Hg]...
* 函数|-H0. 函数|-H1. apply H. apply 二元交介入; 域.
* 函数|-H0. 函数|-H1. symmetry. apply H. apply 二元交介入; 域.
- apply 二元交除去 in H0 as []. 函数 H0... 函数 H1...
eapply H. apply 左并介入... apply 右并介入...
Qed.
Lemma 函数之二元并之定义域 : ∀ f g, 为函数 f → 为函数 g →
dom (f ∪ g) = dom f ∪ dom g.
Proof with auto.
intros * Hf Hg. 外延.
- 定|-H as [y H]. apply 二元并除去 in H as [].
apply 左并介入. 域. apply 右并介入. 域.
- apply 二元并除去 in H as [].
+ 定|-H as [y H]. 定-|y. apply 左并介入...
+ 定|-H as [y H]. 定-|y. apply 右并介入...
Qed.
Lemma 函数加点 : ∀ f a b, 为函数 f → a ∉ dom f → 为函数 (f ∪ {<a, b>,}).
Proof with eauto.
intros f a b Hf 域外.
apply 函数之二元并... apply 单点集为函数.
intros x Hx. exfalso. apply 二元交除去 in Hx as [].
rewrite 单点集的定义域 in H0. apply 单集除去 in H0; subst...
Qed.
Lemma 函数加点之定义域 : ∀ f a b, dom (f ∪ {<a, b>,}) = dom f ∪ {a,}.
Proof with eauto.
intros f a b. 外延.
- 定|-H as [y H]. apply 二元并除去 in H as [].
+ 定 H. apply 左并介入...
+ apply 单集除去 in H. apply 序偶相等 in H as []; subst...
- apply 二元并除去 in H as [].
+ 定|-H as [y H]. 定-|y. apply 左并介入...
+ apply 单集除去 in H. subst. 定-|b. apply 右并介入...
Qed.
Lemma 函数加点之左应用 : ∀ f a b, 为函数 f → a ∉ dom f → ∀x ∈ dom f, (f ∪ {<a, b>,})[x] = f[x].
Proof. intros. apply 函数应用. apply 函数加点; auto. apply 左并介入. 函数-|. Qed.
Lemma 函数加点之右应用 : ∀ f a b, 为函数 f → a ∉ dom f → (f ∪ {<a, b>,})[a] = b.
Proof. intros. apply 函数应用. apply 函数加点; auto. apply 右并介入; auto. Qed.
Lemma 函数加点之左限制 : ∀ f a b, 为函数 f → a ∉ dom f → (f ∪ {<a, b>,}) ↾ (dom f) = f.
Proof with auto.
intros f a b Hf 域外. 外延 x Hx.
- 序偶分离|-Hx. apply 二元并除去 in Hp as []...
apply 单集除去 in H. apply 序偶相等 in H as []; subst. easy.
- 函数|-Hx. 序偶分离-|... 域.
Qed.
Lemma 函数加点之右限制 : ∀ f a b, 为函数 f → a ∉ dom f → (f ∪ {<a, b>,}) ↾ {a,} = {<a, b>,}.
Proof with auto.
intros f a b Hf 域外. 外延 x Hx.
- 序偶分离|-Hx. apply 二元并除去 in Hp as []...
apply 单集除去 in Hx; subst. 定 H. easy.
- apply 单集除去 in Hx; subst. 序偶分离-|...
Qed.
Lemma 函数集族并之定义域 : ∀ F A, dom (⋃ {F x | x ∊ A}) = ⋃ {dom (F x) | x ∊ A}.
Proof with auto.
intros. 外延 x Hx.
- 定|-Hx as [y Hp]. apply 集族并除去 in Hp as [a [Ha Hp]].
apply 集族并介入 with a... 域.
- apply 集族并除去 in Hx as [a [Ha Hp]]. 定|-Hp as [y Hp].
定-|y. apply 集族并介入 with a...
Qed.
|
# SymPy Expressions
SymPy expressions reason about mathematics and generate numeric code.
```
from sympy import *
from sympy.abc import x, y, z
init_printing(use_latex='mathjax')
```
### Operations on SymPy objects create expressions
```
x + y
```
$$x + y$$
```
type(x + y)
```
sympy.core.add.Add
### These expressions can be somewhat complex
```
expr = sin(x)**2 + 2*cos(x)
expr
```
$$\sin^{2}{\left (x \right )} + 2 \cos{\left (x \right )}$$
### We generate numeric code from these expressions
```
ccode(expr) # C
```
'pow(sin(x), 2) + 2*cos(x)'
```
fcode(expr) # Fortran
```
' sin(x)**2 + 2*cos(x)'
```
jscode(expr) # JavaScript
```
'Math.pow(Math.sin(x), 2) + 2*Math.cos(x)'
```
latex(expr) # Even LaTeX
```
'\\sin^{2}{\\left (x \\right )} + 2 \\cos{\\left (x \\right )}'
### We also reason about expressions
```
expr
```
$$\sin^{2}{\left (x \right )} + 2 \cos{\left (x \right )}$$
```
expr.diff(x)
```
$$2 \sin{\left (x \right )} \cos{\left (x \right )} - 2 \sin{\left (x \right )}$$
```
expr.diff(x).diff(x)
```
$$- 2 \sin^{2}{\left (x \right )} + 2 \cos^{2}{\left (x \right )} - 2 \cos{\left (x \right )}$$
### And then can generate code
```
ccode(expr.diff(x).diff(x))
```
'-2*pow(sin(x), 2) + 2*pow(cos(x), 2) - 2*cos(x)'
### Combining reasoning and code generation gives us more efficient code
```
expr.diff(x).diff(x)
```
$$- 2 \sin^{2}{\left (x \right )} + 2 \cos^{2}{\left (x \right )} - 2 \cos{\left (x \right )}$$
```
simplify(expr.diff(x).diff(x))
```
$$- 2 \cos{\left (x \right )} + 2 \cos{\left (2 x \right )}$$
```
ccode(simplify(expr.diff(x).diff(x))) # Faster code
```
'-2*cos(x) + 2*cos(2*x)'
# Final Thoughts
We combine high-level reasoning with low-level code generation.
Blaze does the same thing, just swap out calculus and trig with relational and linear algebra.
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : provisional
-- Portability : portable
--
-----------------------------------------------------------------------------
module Linear.Algebra
( Algebra(..)
, Coalgebra(..)
, multRep, unitalRep
, comultRep, counitalRep
) where
import Control.Lens hiding (index)
import Data.Functor.Rep
import Data.Complex
import Data.Void
import Linear.Vector
import Linear.Quaternion
import Linear.Conjugate
import Linear.V0
import Linear.V1
import Linear.V2
import Linear.V3
import Linear.V4
-- | An associative unital algebra over a ring
class Num r => Algebra r m where
mult :: (m -> m -> r) -> m -> r
unital :: r -> m -> r
multRep :: (Representable f, Algebra r (Rep f)) => f (f r) -> f r
multRep ffr = tabulate $ mult (index . index ffr)
unitalRep :: (Representable f, Algebra r (Rep f)) => r -> f r
unitalRep = tabulate . unital
instance Num r => Algebra r Void where
mult _ _ = 0
unital _ _ = 0
instance Num r => Algebra r (E V0) where
mult _ _ = 0
unital _ _ = 0
instance Num r => Algebra r (E V1) where
mult f _ = f ex ex
unital r _ = r
instance Num r => Algebra r () where
mult f () = f () ()
unital r () = r
instance (Algebra r a, Algebra r b) => Algebra r (a, b) where
mult f (a,b) = mult (\a1 a2 -> mult (\b1 b2 -> f (a1,b1) (a2,b2)) b) a
unital r (a,b) = unital r a * unital r b
instance Num r => Algebra r (E Complex) where
mult f = \ i -> c^.el i where
c = (f ee ee - f ei ei) :+ (f ee ei + f ei ee)
unital r i = (r :+ 0)^.el i
instance (Num r, TrivialConjugate r) => Algebra r (E Quaternion) where
mult f = index $ Quaternion
(f ee ee - (f ei ei + f ej ej + f ek ek))
(V3 (f ee ei + f ei ee + f ej ek - f ek ej)
(f ee ej + f ej ee + f ek ei - f ei ek)
(f ee ek + f ek ee + f ei ej - f ej ei))
unital r = index (Quaternion r 0)
-- | A coassociative counital coalgebra over a ring
class Num r => Coalgebra r m where
comult :: (m -> r) -> m -> m -> r
counital :: (m -> r) -> r
comultRep :: (Representable f, Coalgebra r (Rep f)) => f r -> f (f r)
comultRep fr = tabulate $ \i -> tabulate $ \j -> comult (index fr) i j
counitalRep :: (Representable f, Coalgebra r (Rep f)) => f r -> r
counitalRep = counital . index
instance Num r => Coalgebra r Void where
comult _ _ _ = 0
counital _ = 0
instance Num r => Coalgebra r () where
comult f () () = f ()
counital f = f ()
instance Num r => Coalgebra r (E V0) where
comult _ _ _ = 0
counital _ = 0
instance Num r => Coalgebra r (E V1) where
comult f _ _ = f ex
counital f = f ex
instance Num r => Coalgebra r (E V2) where
comult f = index . index v where
v = V2 (V2 (f ex) 0) (V2 0 (f ey))
counital f = f ex + f ey
instance Num r => Coalgebra r (E V3) where
comult f = index . index q where
q = V3 (V3 (f ex) 0 0)
(V3 0 (f ey) 0)
(V3 0 0 (f ez))
counital f = f ex + f ey + f ez
instance Num r => Coalgebra r (E V4) where
comult f = index . index v where
v = V4 (V4 (f ex) 0 0 0) (V4 0 (f ey) 0 0) (V4 0 0 (f ez) 0) (V4 0 0 0 (f ew))
counital f = f ex + f ey + f ez + f ew
instance Num r => Coalgebra r (E Complex) where
comult f = \i j -> c^.el i.el j where
c = (f ee :+ 0) :+ (0 :+ f ei)
counital f = f ee + f ei
instance (Num r, TrivialConjugate r) => Coalgebra r (E Quaternion) where
comult f = index . index
(Quaternion (Quaternion (f ee) (V3 0 0 0))
(V3 (Quaternion 0 (V3 (f ei) 0 0))
(Quaternion 0 (V3 0 (f ej) 0))
(Quaternion 0 (V3 0 0 (f ek)))))
counital f = f ee + f ei + f ej + f ek
instance (Coalgebra r m, Coalgebra r n) => Coalgebra r (m, n) where
comult f (a1, b1) (a2, b2) = comult (\a -> comult (\b -> f (a, b)) b1 b2) a1 a2
counital k = counital $ \a -> counital $ \b -> k (a,b)
|
Formal statement is: lemma algebraicE: assumes "algebraic x" obtains p where "\<And>i. coeff p i \<in> \<int>" "p \<noteq> 0" "poly p x = 0" Informal statement is: If $x$ is an algebraic number, then there exists a polynomial $p$ with integer coefficients such that $p(x) = 0$. |
module TestProcs
use iso_c_binding
implicit none
integer(8), bind(C, name='fortInt') :: fortInt = 0
real(8), bind(C, name='fortReal') :: fortReal = 0.0
contains
function getInt() bind(C, name='getInt')
integer(8) :: getInt
getInt = fortInt
end function getInt
function getReal() bind(C, name='getReal')
real(8) :: getReal
getReal = fortReal
end function getReal
subroutine setInt(i) bind(C, name='setInt')
integer(8) :: i
fortInt = i
end subroutine setInt
subroutine setReal(r) bind(C, name='setReal')
real(8) :: r
fortReal = r
end subroutine setReal
end module TestProcs
!program run
! use TestProcs
! call setInt(INT(42, 8))
! print *, "Hello from Fortran: ", getInt()
!end program run
|
Fill a very large pot three-quarters full with water and bring to a boil. Add the collard greens to the water and make sure they are all well submerged. Return the water to a boil and simmer until the greens are tender and bright green, 10 to 15 minutes. Drain the greens and run under cold water to stop the cooking. Drain the greens well, squeezing out excess water with your hands or by placing in a kitchen towel and squeezing. Chop the greens finely and set aside.
Melt the butter in a skillet or Dutch oven large enough to hold all of the greens. Add the garlic and shallots and cook over medium heat until softened but not browned, 4 to 6 minutes. Add the cream and bring to a simmer, stirring occasionally. Cook until reduced by half, about 25 minutes - watch carefully as the cream can quickly boil over! Add the greens and toss until warmed through. Season generously with nutmeg, salt and pepper. Add to a serving dish and sprinkle with the Parmesan. |
func $band32I (
var %i i32
) i32 {
return (
band i32(dread i32 %i,
constval i32 0x12))}
func $band32I_2 (
var %i i32
) i32 {
return (
band i32(dread i32 %i,
constval i32 0x112))}
func $band32RR (
var %i i32, var %j i32
) i32 {
return (
band i32(dread i32 %i,
dread i32 %j))}
func $band64I (
var %i i64
) i64 {
return (
band i64(dread i64 %i,
constval i64 0x1200000015))}
func $band64I_2 (
var %i i64
) i64 {
return (
band i64(dread i64 %i,
constval i64 0x1200000115))}
func $band64RR (
var %i i64,
var %j i64
) i64 {
return (
band i64(dread i64 %i,
dread i64 %j))}
# EXEC: %irbuild Main.mpl
# EXEC: %irbuild Main.irb.mpl
# EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
|
eta = 0.9
function f1(x)
(1.0 / 2.0) * (x[1]^2 + eta * x[2]^2)
end
function g1(x, storage)
storage[1] = x[1]
storage[2] = eta * x[2]
end
function h1(x, storage)
storage[1, 1] = 1.0
storage[1, 2] = 0.0
storage[2, 1] = 0.0
storage[2, 2] = eta
end
results = optimize(f1, g1, h1, [127.0, 921.0])
@assert results.converged
@assert norm(results.minimum - [0.0, 0.0]) < 0.01
results = optimize(f1, g1, [127.0, 921.0])
@assert results.converged
@assert norm(results.minimum - [0.0, 0.0]) < 0.01
results = optimize(f1, [127.0, 921.0])
@assert results.converged
@assert norm(results.minimum - [0.0, 0.0]) < 0.01
|
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.group_power.lemmas
import algebra.order.absolute_value
import algebra.order.group.min_max
import algebra.order.field.basic
import algebra.ring.pi
import group_theory.group_action.pi
/-!
# Cauchy sequences
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where
applicable, lemmas that will be reused in other contexts have been stated in extra generality.
There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology.
This is a concrete implementation that is useful for simplicity and computability reasons.
## Important definitions
* `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy.
* `cau_seq`: the type of Cauchy sequences valued in type `β` with respect to an absolute value
function `abv`.
## Tags
sequence, cauchy, abs val, absolute value
-/
open is_absolute_value
variables {G α β : Type*}
theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} :
(∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) →
∃ i, ∀ j ≥ i, P j ∧ Q j
| ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in
⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩
section
variables [linear_ordered_field α] [ring β] (abv : β → α) [is_absolute_value abv]
theorem rat_add_continuous_lemma
{ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β},
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε :=
⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂,
by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]
using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩
theorem rat_mul_continuous_lemma
{ε K₁ K₂ : α} (ε0 : 0 < ε) :
∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ →
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε :=
begin
have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _),
have εK := div_pos (half_pos ε0) K0,
refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩,
replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)),
replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)),
have := add_lt_add
(mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK)
(mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK),
rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this,
simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm]
using lt_of_le_of_lt (abv_add abv _ _) this
end
theorem rat_inv_continuous_lemma
{β : Type*} [division_ring β] (abv : β → α) [is_absolute_value abv]
{ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) :
∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b →
abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε :=
begin
refine ⟨K * ε * K, mul_pos (mul_pos K0 ε0) K0, λ a b ha hb h, _⟩,
have a0 := K0.trans_le ha,
have b0 := K0.trans_le hb,
rw [inv_sub_inv' ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_mul abv, abv_mul abv,
abv_inv abv, abv_inv abv, abv_sub abv],
refine lt_of_mul_lt_mul_left (lt_of_mul_lt_mul_right _ b0.le) a0.le,
rw [mul_assoc, inv_mul_cancel_right₀ b0.ne', ←mul_assoc, mul_inv_cancel a0.ne', one_mul],
refine h.trans_le _,
exact mul_le_mul (mul_le_mul ha le_rfl ε0.le a0.le) hb K0.le (mul_nonneg a0.le ε0.le),
end
end
/-- A sequence is Cauchy if the distance between its entries tends to zero. -/
def is_cau_seq {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) (f : ℕ → β) : Prop :=
∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε
namespace is_cau_seq
variables [linear_ordered_field α] [ring β] {abv : β → α} [is_absolute_value abv] {f g : ℕ → β}
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy₂ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε :=
begin
refine (hf _ (half_pos ε0)).imp (λ i hi j ij k ik, _),
rw ← add_halves ε,
refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _),
rw abv_sub abv, exact hi _ ik
end
theorem cauchy₃ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε :=
let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ (le_trans ij jk) _ ij⟩
lemma add (hf : is_cau_seq abv f) (hg : is_cau_seq abv g) : is_cau_seq abv (f + g) :=
λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (hf.cauchy₃ δ0) (hg.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ le_rfl in Hδ (H₁ _ ij) (H₂ _ ij)⟩
end is_cau_seq
/-- `cau_seq β abv` is the type of `β`-valued Cauchy sequences, with respect to the absolute value
function `abv`. -/
def cau_seq {α : Type*} [linear_ordered_field α]
(β : Type*) [ring β] (abv : β → α) : Type* :=
{f : ℕ → β // is_cau_seq abv f}
namespace cau_seq
variables [linear_ordered_field α]
section ring
variables [ring β] {abv : β → α}
instance : has_coe_to_fun (cau_seq β abv) (λ _, ℕ → β) := ⟨subtype.val⟩
@[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) :
@coe_fn (cau_seq β abv) _ _ ⟨f, hf⟩ = f := rfl
theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g :=
subtype.eq (funext h)
theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2
theorem cauchy (f : cau_seq β abv) :
∀ {ε}, 0 < ε → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2
/-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with
the same values as `f`. -/
def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv :=
⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩
variable [is_absolute_value abv]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy₂ (f : cau_seq β abv) {ε} : 0 < ε →
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂
theorem cauchy₃ (f : cau_seq β abv) {ε} : 0 < ε →
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃
theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r :=
begin
cases f.cauchy zero_lt_one with i h,
set R : ℕ → α := @nat.rec (λ n, α) (abv (f 0)) (λ i c, max c (abv (f i.succ))) with hR,
have : ∀ i, ∀ j ≤ i, abv (f j) ≤ R i,
{ refine nat.rec (by simp [hR]) _,
rintros i hi j (rfl | hj),
{ simp },
exact (hi j hj).trans (le_max_left _ _) },
refine ⟨R i + 1, λ j, _⟩,
cases lt_or_le j i with ij ij,
{ exact lt_of_le_of_lt (this i _ (le_of_lt ij)) (lt_add_one _) },
{ have := lt_of_le_of_lt (abv_add abv _ _)
(add_lt_add_of_le_of_lt (this i _ le_rfl) (h _ ij)),
rw [add_sub, add_comm] at this, simpa }
end
theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r :=
let ⟨r, h⟩ := f.bounded in
⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _),
λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩
instance : has_add (cau_seq β abv) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩
@[simp, norm_cast] lemma coe_add (f g : cau_seq β abv) : ⇑(f + g) = f + g := rfl
@[simp, norm_cast] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl
variable (abv)
/-- The constant Cauchy sequence. -/
def const (x : β) : cau_seq β abv :=
⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩
variable {abv}
local notation `const` := const abv
@[simp, norm_cast] lemma coe_const (x : β) : ⇑(const x) = function.const _ x := rfl
@[simp, norm_cast] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl
theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y :=
⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩
instance : has_zero (cau_seq β abv) := ⟨const 0⟩
instance : has_one (cau_seq β abv) := ⟨const 1⟩
instance : inhabited (cau_seq β abv) := ⟨0⟩
@[simp, norm_cast] lemma coe_zero : ⇑(0 : cau_seq β abv) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ⇑(1 : cau_seq β abv) = 1 := rfl
@[simp, norm_cast] lemma zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl
@[simp, norm_cast] lemma one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl
@[simp] lemma const_zero : const 0 = 0 := rfl
@[simp] lemma const_one : const 1 = 1 := rfl
theorem const_add (x y : β) : const (x + y) = const x + const y :=
rfl
instance : has_mul (cau_seq β abv) :=
⟨λ f g, ⟨f * g, λ ε ε0,
let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0,
⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ le_rfl in
Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩
@[simp, norm_cast] lemma coe_mul (f g : cau_seq β abv) : ⇑(f * g) = f * g := rfl
@[simp, norm_cast] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl
theorem const_mul (x y : β) : const (x * y) = const x * const y := rfl
instance : has_neg (cau_seq β abv) :=
⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩
@[simp, norm_cast] lemma coe_neg (f : cau_seq β abv) : ⇑(-f) = -f := rfl
@[simp, norm_cast] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl
theorem const_neg (x : β) : const (-x) = -const x := rfl
instance : has_sub (cau_seq β abv) :=
⟨λ f g, of_eq (f + -g) (λ x, f x - g x) (λ i, by simp [sub_eq_add_neg])⟩
@[simp, norm_cast] lemma coe_sub (f g : cau_seq β abv) : ⇑(f - g) = f - g := rfl
@[simp, norm_cast] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl
theorem const_sub (x y : β) : const (x - y) = const x - const y := rfl
section has_smul
variables [has_smul G β] [is_scalar_tower G β β]
instance : has_smul G (cau_seq β abv) :=
⟨λ a f, of_eq (const (a • 1) * f) (a • f) $ λ i, smul_one_mul _ _⟩
@[simp, norm_cast] lemma coe_smul (a : G) (f : cau_seq β abv) : ⇑(a • f) = a • f := rfl
@[simp, norm_cast] lemma smul_apply (a : G) (f : cau_seq β abv) (i : ℕ) : (a • f) i = a • f i := rfl
lemma const_smul (a : G) (x : β) : const (a • x) = a • const x := rfl
instance : is_scalar_tower G (cau_seq β abv) (cau_seq β abv) :=
⟨λ a f g, subtype.ext $ smul_assoc a ⇑f ⇑g⟩
end has_smul
instance : add_group (cau_seq β abv) :=
function.injective.add_group _ subtype.coe_injective
rfl coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _)
instance : add_group_with_one (cau_seq β abv) :=
{ one := 1,
nat_cast := λ n, const n,
nat_cast_zero := congr_arg const nat.cast_zero,
nat_cast_succ := λ n, congr_arg const (nat.cast_succ n),
int_cast := λ n, const n,
int_cast_of_nat := λ n, congr_arg const (int.cast_of_nat n),
int_cast_neg_succ_of_nat := λ n, congr_arg const (int.cast_neg_succ_of_nat n),
.. cau_seq.add_group }
instance : has_pow (cau_seq β abv) ℕ :=
⟨λ f n, of_eq (npow_rec n f) (λ i, f i ^ n) $ by induction n; simp [*, npow_rec, pow_succ]⟩
@[simp, norm_cast] lemma coe_pow (f : cau_seq β abv) (n : ℕ) : ⇑(f ^ n) = f ^ n := rfl
@[simp, norm_cast] lemma pow_apply (f : cau_seq β abv) (n i : ℕ) : (f ^ n) i = f i ^ n := rfl
lemma const_pow (x : β) (n : ℕ) : const (x ^ n) = const x ^ n := rfl
instance : ring (cau_seq β abv) :=
function.injective.ring _ subtype.coe_injective
rfl rfl coe_add coe_mul coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _) coe_pow
(λ _, rfl) (λ _, rfl)
instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] :
comm_ring (cau_seq β abv) :=
{ mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm],
..cau_seq.ring }
/-- `lim_zero f` holds when `f` approaches 0. -/
def lim_zero {abv : β → α} (f : cau_seq β abv) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε
theorem add_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g)
| ε ε0 := (exists_forall_ge_and
(hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $
λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in
by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂)
theorem mul_lim_zero_right (f : cau_seq β abv) {g}
(hg : lim_zero g) : lim_zero (f * g)
| ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in
(hg _ $ div_pos ε0 F0).imp $ λ i H j ij,
by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0;
rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this
theorem mul_lim_zero_left {f} (g : cau_seq β abv)
(hg : lim_zero f) : lim_zero (f * g)
| ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in
(hg _ $ div_pos ε0 G0).imp $ λ i H j ij,
by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _);
rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this
theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) :=
by rw ← neg_one_mul; exact mul_lim_zero_right _ hf
theorem sub_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) :=
by simpa only [sub_eq_add_neg] using add_lim_zero hf (neg_lim_zero hg)
theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) :=
by simpa using neg_lim_zero hfg
theorem zero_lim_zero : lim_zero (0 : cau_seq β abv)
| ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩
theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 :=
⟨λ H, (abv_eq_zero abv).1 $
eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $
λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ le_rfl,
λ e, e.symm ▸ zero_lim_zero⟩
instance equiv : setoid (cau_seq β abv) :=
⟨λ f g, lim_zero (f - g),
⟨λ f, by simp [zero_lim_zero],
λ f g h, by simpa using neg_lim_zero h,
λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩
lemma add_equiv_add {f1 f2 g1 g2 : cau_seq β abv} (hf : f1 ≈ f2) (hg : g1 ≈ g2) :
f1 + g1 ≈ f2 + g2 :=
by simpa only [←add_sub_add_comm] using add_lim_zero hf hg
lemma neg_equiv_neg {f g : cau_seq β abv} (hf : f ≈ g) : -f ≈ -g :=
by simpa only [neg_sub'] using neg_lim_zero hf
lemma sub_equiv_sub {f1 f2 g1 g2 : cau_seq β abv} (hf : f1 ≈ f2) (hg : g1 ≈ g2) :
f1 - g1 ≈ f2 - g2 :=
by simpa only [sub_eq_add_neg] using add_equiv_add hf (neg_equiv_neg hg)
theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε :=
(exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $
λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in
by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk));
rwa [sub_add_sub_cancel', add_halves] at this
theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g :=
⟨λ l, by simpa using add_lim_zero (setoid.symm h) l,
λ l, by simpa using add_lim_zero h l⟩
theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) :=
begin
haveI := classical.prop_decidable,
by_contra nk,
refine hf (λ ε ε0, _),
simp [not_forall] at nk,
cases f.cauchy₃ (half_pos ε0) with i hi,
rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩,
refine ⟨j, λ k jk, _⟩,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj),
rwa [sub_add_cancel, add_halves] at this
end
theorem of_near (f : ℕ → β) (g : cau_seq β abv)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f
| ε ε0 :=
let ⟨i, hi⟩ := exists_forall_ge_and
(h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in
⟨i, λ j ij, begin
cases hi _ le_rfl with h₁ h₂, rw abv_sub abv at h₁,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁),
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)),
rwa [add_halves, add_halves, add_right_comm,
sub_add_sub_cancel, sub_add_sub_cancel] at this
end⟩
lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f :=
assume : lim_zero f,
have lim_zero (f - 0), by simpa,
hf this
lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 :=
have lim_zero (f - 0), from hf,
have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa,
show lim_zero (g*f - 0), by simpa
lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 :=
have lim_zero (f - 0), from hf,
have lim_zero (f*g), from mul_lim_zero_left _ $ by simpa,
show lim_zero (f*g - 0), by simpa
lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 :=
assume : lim_zero (f*g - 0),
have hlz : lim_zero (f*g), by simpa,
have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf),
have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg),
begin
rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩,
rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩,
have : 0 < a1 * a2, from mul_pos ha1 ha2,
cases hlz _ this with N hN,
let i := max N (max N1 N2),
have hN' := hN i (le_max_left _ _),
have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)),
have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)),
apply not_le_of_lt hN',
change _ ≤ abv (_ * _),
rw is_absolute_value.abv_mul abv,
apply mul_le_mul; try { assumption },
{ apply le_of_lt ha2 },
{ apply is_absolute_value.abv_nonneg abv }
end
theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y :=
show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero]
lemma mul_equiv_mul {f1 f2 g1 g2 : cau_seq β abv} (hf : f1 ≈ f2) (hg : g1 ≈ g2) :
f1 * g1 ≈ f2 * g2 :=
by simpa only [mul_sub, sub_mul, sub_add_sub_cancel]
using add_lim_zero (mul_lim_zero_left g1 hf) (mul_lim_zero_right f2 hg)
lemma smul_equiv_smul [has_smul G β] [is_scalar_tower G β β] {f1 f2 : cau_seq β abv}
(c : G) (hf : f1 ≈ f2) :
c • f1 ≈ c • f2 :=
by simpa [const_smul, smul_one_mul _ _]
using mul_equiv_mul (const_equiv.mpr $ eq.refl $ c • 1) hf
lemma pow_equiv_pow {f1 f2 : cau_seq β abv} (hf : f1 ≈ f2) (n : ℕ) :
f1 ^ n ≈ f2 ^ n :=
begin
induction n with n ih,
{ simp only [pow_zero, setoid.refl] },
{ simpa only [pow_succ] using mul_equiv_mul hf ih, },
end
end ring
section is_domain
variables [ring β] [is_domain β] (abv : β → α) [is_absolute_value abv]
lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) :=
assume h,
have ∀ ε > 0, ∃ i, ∀ k, i ≤ k → abv (1 - 0) < ε, from h,
have h1 : abv 1 ≤ 0, from le_of_not_gt $
assume h2 : 0 < abv 1,
exists.elim (this _ h2) $ λ i hi,
lt_irrefl (abv 1) $ by simpa using hi _ le_rfl,
have h2 : 0 ≤ abv 1, from is_absolute_value.abv_nonneg _ _,
have abv 1 = 0, from le_antisymm h1 h2,
have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this,
absurd this one_ne_zero
end is_domain
section division_ring
variables [division_ring β] {abv : β → α} [is_absolute_value abv]
theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 :=
let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf,
⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0,
⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨iK, H'⟩ := H _ le_rfl in Hδ (H _ ij).1 iK (H' _ ij)⟩
/-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to
the inverses of the values of `f`. -/
def inv (f : cau_seq β abv) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩
@[simp, norm_cast] lemma coe_inv {f : cau_seq β abv} (hf) : ⇑(inv f hf) = f⁻¹ := rfl
@[simp, norm_cast] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl
theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 :=
λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in
⟨i, λ j ij,
by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)),
abv_zero abv] using ε0⟩
theorem mul_inv_cancel {f : cau_seq β abv} (hf) : f * inv f hf ≈ 1 :=
λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in
⟨i, λ j ij,
by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)),
abv_zero abv] using ε0⟩
theorem const_inv {x : β} (hx : x ≠ 0) :
const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) := rfl
end division_ring
section abs
local notation `const` := const abs
/-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/
def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j
theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0),
⟨h₁, h₂⟩ := h _ le_rfl in
not_lt_of_le h₁ (abs_lt.1 h₂).2
theorem const_pos {x : α} : pos (const x) ↔ 0 < x :=
⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ le_rfl),
λ h, ⟨x, h, 0, λ j _, le_rfl⟩⟩
theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.add_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩
theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g)
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in
⟨_, half_pos F0, i, λ j ij, begin
cases h j ij with h₁ h₂,
have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1),
rwa [← sub_eq_add_neg, sub_self_div_two] at this
end⟩
protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.mul_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in
mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩
theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) :=
begin
cases classical.em (lim_zero f); simp *,
rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩,
rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩,
refine (le_total 0 (f i)).imp _ _;
refine (λ h, ⟨K, K0, i, λ j ij, _⟩);
have := (hi _ ij).1;
cases hi _ le_rfl with h₁ h₂,
{ rwa abs_of_nonneg at this,
rw abs_of_nonneg h at h₁,
exact (le_add_iff_nonneg_right _).1
(le_trans h₁ $ neg_le_sub_iff_le_add'.1 $
le_of_lt (abs_lt.1 $ h₂ _ ij).1) },
{ rwa abs_of_nonpos at this,
rw abs_of_nonpos h at h₁,
rw [← sub_le_sub_iff_right, zero_sub],
exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ }
end
instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩
instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩
theorem lt_of_lt_of_eq {f g h : cau_seq α abs}
(fg : f < g) (gh : g ≈ h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh)
theorem lt_of_eq_of_lt {f g h : cau_seq α abs}
(fg : f ≈ g) (gh : g < h) : f < h :=
by have := pos_add_lim_zero gh (neg_lim_zero fg);
rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this
theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh
theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f
| h := not_lim_zero_of_pos h (by simp [zero_lim_zero])
lemma le_of_eq_of_le {f g h : cau_seq α abs}
(hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h :=
hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg)
(or.inr ∘ setoid.trans hfg)
lemma le_of_le_of_eq {f g h : cau_seq α abs}
(hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h :=
hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh))
(λ h, or.inr (setoid.trans h hgh))
instance : preorder (cau_seq α abs) :=
{ lt := (<),
le := λ f g, f < g ∨ f ≈ g,
le_refl := λ f, or.inr (setoid.refl _),
le_trans := λ f g h fg, match fg with
| or.inl fg, or.inl gh := or.inl $ lt_trans fg gh
| or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh
| or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh
| or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh
end,
lt_iff_le_not_le := λ f g,
⟨λ h, ⟨or.inl h,
not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩,
λ ⟨h₁, h₂⟩, h₁.resolve_right
(mt (λ h, or.inr (setoid.symm h)) h₂)⟩ }
theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g :=
fg.resolve_left (not_lt_of_le gf)
theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f :=
(trichotomy (g - f)).imp_right
(λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h))
theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f :=
(or.assoc.2 (lt_total f g)).imp_right or.inl
theorem const_lt {x y : α} : const x < const y ↔ x < y :=
show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos]
theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y :=
by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv
lemma le_of_exists {f g : cau_seq α abs}
(h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g :=
let ⟨i, hi⟩ := h in
(or.assoc.2 (cau_seq.lt_total f g)).elim
id
(λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in
not_lt_of_ge (hi (max i j) (le_max_left _ _))
(sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _))))))
theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a :=
let ⟨K, H⟩ := f.bounded in
⟨K + 1, 1, zero_lt_one, 0, λ i _, begin
rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right],
exact le_of_lt (abs_lt.1 (H _)).2
end⟩
theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f :=
let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _,
by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩
-- so named to match `rat_add_continuous_lemma`
theorem _root_.rat_sup_continuous_lemma {ε : α} {a₁ a₂ b₁ b₂ : α} :
abs (a₁ - b₁) < ε → abs (a₂ - b₂) < ε → abs (a₁ ⊔ a₂ - (b₁ ⊔ b₂)) < ε :=
λ h₁ h₂, (abs_max_sub_max_le_max _ _ _ _).trans_lt (max_lt h₁ h₂)
-- so named to match `rat_add_continuous_lemma`
theorem _root_.rat_inf_continuous_lemma {ε : α} {a₁ a₂ b₁ b₂ : α} :
abs (a₁ - b₁) < ε → abs (a₂ - b₂) < ε → abs (a₁ ⊓ a₂ - (b₁ ⊓ b₂)) < ε :=
λ h₁ h₂, (abs_min_sub_min_le_max _ _ _ _).trans_lt (max_lt h₁ h₂)
instance : has_sup (cau_seq α abs) :=
⟨λ f g, ⟨f ⊔ g, λ ε ε0,
(exists_forall_ge_and (f.cauchy₃ ε0) (g.cauchy₃ ε0)).imp $ λ i H j ij,
let ⟨H₁, H₂⟩ := H _ le_rfl in rat_sup_continuous_lemma (H₁ _ ij) (H₂ _ ij)⟩⟩
instance : has_inf (cau_seq α abs) :=
⟨λ f g, ⟨f ⊓ g, λ ε ε0,
(exists_forall_ge_and (f.cauchy₃ ε0) (g.cauchy₃ ε0)).imp $ λ i H j ij,
let ⟨H₁, H₂⟩ := H _ le_rfl in rat_inf_continuous_lemma (H₁ _ ij) (H₂ _ ij)⟩⟩
@[simp, norm_cast]
@[simp, norm_cast] lemma coe_inf (f g : cau_seq α abs) : ⇑(f ⊓ g) = f ⊓ g := rfl
theorem sup_lim_zero {f g : cau_seq α abs}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f ⊔ g)
| ε ε0 := (exists_forall_ge_and (hf _ ε0) (hg _ ε0)).imp $
λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in begin
rw abs_lt at H₁ H₂ ⊢,
exact ⟨lt_sup_iff.mpr (or.inl H₁.1), sup_lt_iff.mpr ⟨H₁.2, H₂.2⟩⟩
end
theorem inf_lim_zero {f g : cau_seq α abs}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f ⊓ g)
| ε ε0 := (exists_forall_ge_and (hf _ ε0) (hg _ ε0)).imp $
λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in begin
rw abs_lt at H₁ H₂ ⊢,
exact ⟨lt_inf_iff.mpr ⟨H₁.1, H₂.1⟩, inf_lt_iff.mpr (or.inl H₁.2), ⟩
end
lemma sup_equiv_sup {a₁ b₁ a₂ b₂ : cau_seq α abs} (ha : a₁ ≈ a₂) (hb : b₁ ≈ b₂) :
a₁ ⊔ b₁ ≈ a₂ ⊔ b₂ :=
begin
intros ε ε0,
obtain ⟨ai, hai⟩ := ha ε ε0,
obtain ⟨bi, hbi⟩ := hb ε ε0,
exact ⟨ai ⊔ bi, λ i hi,
(abs_max_sub_max_le_max (a₁ i) (b₁ i) (a₂ i) (b₂ i)).trans_lt
(max_lt (hai i (sup_le_iff.mp hi).1) (hbi i (sup_le_iff.mp hi).2))⟩,
end
lemma inf_equiv_inf {a₁ b₁ a₂ b₂ : cau_seq α abs} (ha : a₁ ≈ a₂) (hb : b₁ ≈ b₂) :
a₁ ⊓ b₁ ≈ a₂ ⊓ b₂ :=
begin
intros ε ε0,
obtain ⟨ai, hai⟩ := ha ε ε0,
obtain ⟨bi, hbi⟩ := hb ε ε0,
exact ⟨ai ⊔ bi, λ i hi,
(abs_min_sub_min_le_max (a₁ i) (b₁ i) (a₂ i) (b₂ i)).trans_lt
(max_lt (hai i (sup_le_iff.mp hi).1) (hbi i (sup_le_iff.mp hi).2))⟩,
end
protected lemma sup_lt {a b c : cau_seq α abs} (ha : a < c) (hb : b < c) : a ⊔ b < c :=
begin
obtain ⟨⟨εa, εa0, ia, ha⟩, ⟨εb, εb0, ib, hb⟩⟩ := ⟨ha, hb⟩,
refine ⟨εa ⊓ εb, lt_inf_iff.mpr ⟨εa0, εb0⟩, ia ⊔ ib, λ i hi, _⟩,
have := min_le_min (ha _ (sup_le_iff.mp hi).1) (hb _ (sup_le_iff.mp hi).2),
exact this.trans_eq (min_sub_sub_left _ _ _)
end
protected lemma lt_inf {a b c : cau_seq α abs} (hb : a < b) (hc : a < c) : a < b ⊓ c :=
begin
obtain ⟨⟨εb, εb0, ib, hb⟩, ⟨εc, εc0, ic, hc⟩⟩ := ⟨hb, hc⟩,
refine ⟨εb ⊓ εc, lt_inf_iff.mpr ⟨εb0, εc0⟩, ib ⊔ ic, λ i hi, _⟩,
have := min_le_min (hb _ (sup_le_iff.mp hi).1) (hc _ (sup_le_iff.mp hi).2),
exact this.trans_eq (min_sub_sub_right _ _ _),
end
@[simp] protected lemma sup_idem (a : cau_seq α abs) : a ⊔ a = a := subtype.ext sup_idem
@[simp] protected lemma inf_idem (a : cau_seq α abs) : a ⊓ a = a := subtype.ext inf_idem
protected lemma sup_comm (a b : cau_seq α abs) : a ⊔ b = b ⊔ a := subtype.ext sup_comm
protected lemma inf_comm (a b : cau_seq α abs) : a ⊓ b = b ⊓ a := subtype.ext inf_comm
protected lemma sup_eq_right {a b : cau_seq α abs} (h : a ≤ b) :
a ⊔ b ≈ b :=
begin
obtain ⟨ε, ε0 : _ < _, i, h⟩ | h := h,
{ intros _ _,
refine ⟨i, λ j hj, _⟩,
dsimp,
erw ←max_sub_sub_right,
rwa [sub_self, max_eq_right, abs_zero],
rw [sub_nonpos, ←sub_nonneg],
exact ε0.le.trans (h _ hj) },
{ refine setoid.trans (sup_equiv_sup h (setoid.refl _)) _,
rw cau_seq.sup_idem,
exact setoid.refl _ },
end
protected lemma inf_eq_right {a b : cau_seq α abs} (h : b ≤ a) :
a ⊓ b ≈ b :=
begin
obtain ⟨ε, ε0 : _ < _, i, h⟩ | h := h,
{ intros _ _,
refine ⟨i, λ j hj, _⟩,
dsimp,
erw ←min_sub_sub_right,
rwa [sub_self, min_eq_right, abs_zero],
exact ε0.le.trans (h _ hj) },
{ refine setoid.trans (inf_equiv_inf (setoid.symm h) (setoid.refl _)) _,
rw cau_seq.inf_idem,
exact setoid.refl _ },
end
protected lemma sup_eq_left {a b : cau_seq α abs} (h : b ≤ a) :
a ⊔ b ≈ a :=
by simpa only [cau_seq.sup_comm] using cau_seq.sup_eq_right h
protected lemma inf_eq_left {a b : cau_seq α abs} (h : a ≤ b) :
a ⊓ b ≈ a :=
by simpa only [cau_seq.inf_comm] using cau_seq.inf_eq_right h
protected lemma le_sup_left {a b : cau_seq α abs} : a ≤ a ⊔ b :=
le_of_exists ⟨0, λ j hj, le_sup_left⟩
protected lemma inf_le_left {a b : cau_seq α abs} : a ⊓ b ≤ a :=
le_of_exists ⟨0, λ j hj, inf_le_left⟩
protected lemma le_sup_right {a b : cau_seq α abs} : b ≤ a ⊔ b :=
le_of_exists ⟨0, λ j hj, le_sup_right⟩
protected lemma inf_le_right {a b : cau_seq α abs} : a ⊓ b ≤ b :=
le_of_exists ⟨0, λ j hj, inf_le_right⟩
protected lemma sup_le {a b c : cau_seq α abs} (ha : a ≤ c) (hb : b ≤ c) : a ⊔ b ≤ c :=
begin
cases ha with ha ha,
{ cases hb with hb hb,
{ exact or.inl (cau_seq.sup_lt ha hb) },
{ replace ha := le_of_le_of_eq ha.le (setoid.symm hb),
refine le_of_le_of_eq (or.inr _) hb,
exact cau_seq.sup_eq_right ha }, },
{ replace hb := le_of_le_of_eq hb (setoid.symm ha),
refine le_of_le_of_eq (or.inr _) ha,
exact cau_seq.sup_eq_left hb }
end
protected lemma le_inf {a b c : cau_seq α abs} (hb : a ≤ b) (hc : a ≤ c) : a ≤ b ⊓ c :=
begin
cases hb with hb hb,
{ cases hc with hc hc,
{ exact or.inl (cau_seq.lt_inf hb hc) },
{ replace hb := le_of_eq_of_le (setoid.symm hc) hb.le,
refine le_of_eq_of_le hc (or.inr _),
exact setoid.symm (cau_seq.inf_eq_right hb) }, },
{ replace hc := le_of_eq_of_le (setoid.symm hb) hc,
refine le_of_eq_of_le hb (or.inr _),
exact setoid.symm (cau_seq.inf_eq_left hc) }
end
/-! Note that `distrib_lattice (cau_seq α abs)` is not true because there is no `partial_order`. -/
protected lemma sup_inf_distrib_left (a b c : cau_seq α abs) : a ⊔ (b ⊓ c) = (a ⊔ b) ⊓ (a ⊔ c) :=
subtype.ext $ funext $ λ i, max_min_distrib_left
protected lemma sup_inf_distrib_right (a b c : cau_seq α abs) : (a ⊓ b) ⊔ c = (a ⊔ c) ⊓ (b ⊔ c) :=
subtype.ext $ funext $ λ i, max_min_distrib_right
end abs
end cau_seq
|
/-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.basic
/-!
# Homomorphisms of `R`-algebras
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines bundled homomorphisms of `R`-algebras.
## Main definitions
* `alg_hom R A B`: the type of `R`-algebra morphisms from `A` to `B`.
* `algebra.of_id R A : R →ₐ[R] A`: the canonical map from `R` to `A`, as an `alg_hom`.
## Notations
* `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`.
-/
open_locale big_operators
universes u v w u₁ v₁
set_option old_structure_cmd true
/-- Defining the homomorphism in the category R-Alg. -/
@[nolint has_nonempty_instance]
structure alg_hom (R : Type u) (A : Type v) (B : Type w)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B :=
(commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r)
run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`"
infixr ` →ₐ `:25 := alg_hom _
notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B
/-- `alg_hom_class F R A B` asserts `F` is a type of bundled algebra homomorphisms
from `A` to `B`. -/
class alg_hom_class (F : Type*) (R : out_param Type*) (A : out_param Type*) (B : out_param Type*)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
extends ring_hom_class F A B :=
(commutes : ∀ (f : F) (r : R), f (algebra_map R A r) = algebra_map R B r)
-- `R` becomes a metavariable but that's fine because it's an `out_param`
attribute [nolint dangerous_instance] alg_hom_class.to_ring_hom_class
attribute [simp] alg_hom_class.commutes
namespace alg_hom_class
variables {R : Type*} {A : Type*} {B : Type*} [comm_semiring R] [semiring A] [semiring B]
[algebra R A] [algebra R B]
@[priority 100] -- see Note [lower instance priority]
instance {F : Type*} [alg_hom_class F R A B] : linear_map_class F R A B :=
{ map_smulₛₗ := λ f r x, by simp only [algebra.smul_def, map_mul, commutes, ring_hom.id_apply],
..‹alg_hom_class F R A B› }
instance {F : Type*} [alg_hom_class F R A B] : has_coe_t F (A →ₐ[R] B) :=
{ coe := λ f,
{ to_fun := f,
commutes' := alg_hom_class.commutes f,
.. (f : A →+* B) } }
end alg_hom_class
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁}
section semiring
variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D]
variables [algebra R A] [algebra R B] [algebra R C] [algebra R D]
instance : has_coe_to_fun (A →ₐ[R] B) (λ _, A → B) := ⟨alg_hom.to_fun⟩
initialize_simps_projections alg_hom (to_fun → apply)
@[simp, protected] lemma coe_coe {F : Type*} [alg_hom_class F R A B] (f : F) :
⇑(f : A →ₐ[R] B) = f := rfl
@[simp] lemma to_fun_eq_coe (f : A →ₐ[R] B) : f.to_fun = f := rfl
instance : alg_hom_class (A →ₐ[R] B) R A B :=
{ coe := to_fun,
coe_injective' := λ f g h, by { cases f, cases g, congr' },
map_add := map_add',
map_zero := map_zero',
map_mul := map_mul',
map_one := map_one',
commutes := λ f, f.commutes' }
instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩
instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩
instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩
@[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) :
⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl
-- make the coercion the simp-normal form
@[simp] lemma to_ring_hom_eq_coe (f : A →ₐ[R] B) : f.to_ring_hom = f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl
@[simp, norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl
@[simp, norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl
variables (φ : A →ₐ[R] B)
theorem coe_fn_injective : @function.injective (A →ₐ[R] B) (A → B) coe_fn := fun_like.coe_injective
theorem coe_fn_inj {φ₁ φ₂ : A →ₐ[R] B} : (φ₁ : A → B) = φ₂ ↔ φ₁ = φ₂ := fun_like.coe_fn_eq
theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) :=
λ φ₁ φ₂ H, coe_fn_injective $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B),
from congr_arg _ H
theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) :=
ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective
theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) :=
ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective
protected lemma congr_fun {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁ = φ₂) (x : A) : φ₁ x = φ₂ x :=
fun_like.congr_fun H x
protected lemma congr_arg (φ : A →ₐ[R] B) {x y : A} (h : x = y) : φ x = φ y :=
fun_like.congr_arg φ h
@[ext]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := fun_like.ext _ _ H
theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x := fun_like.ext_iff
@[simp] theorem mk_coe {f : A →ₐ[R] B} (h₁ h₂ h₃ h₄ h₅) :
(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := ext $ λ _, rfl
@[simp]
theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r
theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B :=
ring_hom.ext $ φ.commutes
protected lemma map_add (r s : A) : φ (r + s) = φ r + φ s := map_add _ _ _
protected lemma map_zero : φ 0 = 0 := map_zero _
protected lemma map_mul (x y) : φ (x * y) = φ x * φ y := map_mul _ _ _
protected lemma map_one : φ 1 = 1 := map_one _
protected lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := map_pow _ _ _
@[simp] protected lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := map_smul _ _ _
protected lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∑ x in s, f x) = ∑ x in s, φ (f x) := map_sum _ _ _
protected lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) :
φ (f.sum g) = f.sum (λ i a, φ (g i a)) := map_finsupp_sum _ _ _
protected lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) := map_bit0 _ _
protected lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) := map_bit1 _ _
/-- If a `ring_hom` is `R`-linear, then it is an `alg_hom`. -/
def mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : A →ₐ[R] B :=
{ to_fun := f,
commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, h, f.map_one],
.. f }
@[simp]
section
variables (R A)
/-- Identity map as an `alg_hom`. -/
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
@[simp] lemma coe_id : ⇑(alg_hom.id R A) = id := rfl
@[simp] lemma id_to_ring_hom : (alg_hom.id R A : A →+* A) = ring_hom.id _ := rfl
end
lemma id_apply (p : A) : alg_hom.id R A p = p := rfl
/-- Composition of algebra homeomorphisms. -/
def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C :=
{ commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl,
.. φ₁.to_ring_hom.comp ↑φ₂ }
@[simp] lemma coe_comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂) = φ₁ ∘ φ₂ := rfl
lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
lemma comp_to_ring_hom (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) :
(φ₁.comp φ₂ : A →+* C) = (φ₁ : B →+* C).comp ↑φ₂ := rfl
@[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ :=
ext $ λ x, rfl
@[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ :=
ext $ λ x, rfl
theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) :
(φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) :=
ext $ λ x, rfl
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ[R] B :=
{ to_fun := φ,
map_add' := map_add _,
map_smul' := map_smul _ }
@[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl
theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A →ₗ[R] B)) :=
λ φ₁ φ₂ h, ext $ linear_map.congr_fun h
@[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) :
(g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
@[simp] lemma to_linear_map_id : to_linear_map (alg_hom.id R A) = linear_map.id :=
linear_map.ext $ λ _, rfl
/-- Promote a `linear_map` to an `alg_hom` by supplying proofs about the behavior on `1` and `*`. -/
@[simps]
def of_linear_map (f : A →ₗ[R] B) (map_one : f 1 = 1) (map_mul : ∀ x y, f (x * y) = f x * f y) :
A →ₐ[R] B :=
{ to_fun := f,
map_one' := map_one,
map_mul' := map_mul,
commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, f.map_smul, map_one],
.. f.to_add_monoid_hom }
@[simp] lemma of_linear_map_to_linear_map (map_one) (map_mul) :
of_linear_map φ.to_linear_map map_one map_mul = φ :=
by { ext, refl }
@[simp] lemma to_linear_map_of_linear_map (f : A →ₗ[R] B) (map_one) (map_mul) :
to_linear_map (of_linear_map f map_one map_mul) = f :=
by { ext, refl }
@[simp] lemma of_linear_map_id (map_one) (map_mul) :
of_linear_map linear_map.id map_one map_mul = alg_hom.id R A :=
ext $ λ _, rfl
lemma map_smul_of_tower {R'} [has_smul R' A] [has_smul R' B]
[linear_map.compatible_smul A B R' R] (r : R') (x : A) : φ (r • x) = r • φ x :=
φ.to_linear_map.map_smul_of_tower r x
lemma map_list_prod (s : list A) :
φ s.prod = (s.map φ).prod :=
φ.to_ring_hom.map_list_prod s
@[simps mul one {attrs := []}] instance End : monoid (A →ₐ[R] A) :=
{ mul := comp,
mul_assoc := λ ϕ ψ χ, rfl,
one := alg_hom.id R A,
one_mul := λ ϕ, ext $ λ x, rfl,
mul_one := λ ϕ, ext $ λ x, rfl }
@[simp] lemma one_apply (x : A) : (1 : A →ₐ[R] A) x = x := rfl
@[simp] lemma mul_apply (φ ψ : A →ₐ[R] A) (x : A) : (φ * ψ) x = φ (ψ x) := rfl
lemma algebra_map_eq_apply (f : A →ₐ[R] B) {y : R} {x : A} (h : algebra_map R A y = x) :
algebra_map R B y = f x :=
h ▸ (f.commutes _).symm
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [comm_semiring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
protected lemma map_multiset_prod (s : multiset A) :
φ s.prod = (s.map φ).prod := map_multiset_prod _ _
protected lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∏ x in s, f x) = ∏ x in s, φ (f x) := map_prod _ _ _
protected lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) :
φ (f.prod g) = f.prod (λ i a, φ (g i a)) := map_finsupp_prod _ _ _
end comm_semiring
section ring
variables [comm_semiring R] [ring A] [ring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
protected lemma map_neg (x) : φ (-x) = -φ x := map_neg _ _
protected lemma map_sub (x y) : φ (x - y) = φ x - φ y := map_sub _ _ _
end ring
end alg_hom
namespace ring_hom
variables {R S : Type*}
/-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/
def to_nat_alg_hom [semiring R] [semiring S] (f : R →+* S) :
R →ₐ[ℕ] S :=
{ to_fun := f, commutes' := λ n, by simp, .. f }
/-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/
def to_int_alg_hom [ring R] [ring S] [algebra ℤ R] [algebra ℤ S] (f : R →+* S) :
R →ₐ[ℤ] S :=
{ commutes' := λ n, by simp, .. f }
/-- Reinterpret a `ring_hom` as a `ℚ`-algebra homomorphism. This actually yields an equivalence,
see `ring_hom.equiv_rat_alg_hom`. -/
def to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) :
R →ₐ[ℚ] S :=
{ commutes' := f.map_rat_algebra_map, .. f }
@[simp]
lemma to_rat_alg_hom_to_ring_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S]
(f : R →+* S) : ↑f.to_rat_alg_hom = f :=
ring_hom.ext $ λ x, rfl
end ring_hom
section
variables {R S : Type*}
@[simp]
lemma alg_hom.to_ring_hom_to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S]
(f : R →ₐ[ℚ] S) : (f : R →+* S).to_rat_alg_hom = f :=
alg_hom.ext $ λ x, rfl
/-- The equivalence between `ring_hom` and `ℚ`-algebra homomorphisms. -/
@[simps]
def ring_hom.equiv_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] :
(R →+* S) ≃ (R →ₐ[ℚ] S) :=
{ to_fun := ring_hom.to_rat_alg_hom,
inv_fun := alg_hom.to_ring_hom,
left_inv := ring_hom.to_rat_alg_hom_to_ring_hom,
right_inv := alg_hom.to_ring_hom_to_rat_alg_hom, }
end
namespace algebra
variables (R : Type u) (A : Type v)
variables [comm_semiring R] [semiring A] [algebra R A]
/-- `algebra_map` as an `alg_hom`. -/
def of_id : R →ₐ[R] A :=
{ commutes' := λ _, rfl, .. algebra_map R A }
variables {R}
theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl
end algebra
namespace mul_semiring_action
variables {M G : Type*} (R A : Type*) [comm_semiring R] [semiring A] [algebra R A]
variables [monoid M] [mul_semiring_action M A] [smul_comm_class M R A]
/-- Each element of the monoid defines a algebra homomorphism.
This is a stronger version of `mul_semiring_action.to_ring_hom` and
`distrib_mul_action.to_linear_map`. -/
@[simps]
def to_alg_hom (m : M) : A →ₐ[R] A :=
{ to_fun := λ a, m • a,
commutes' := smul_algebra_map _,
..mul_semiring_action.to_ring_hom _ _ m }
theorem to_alg_hom_injective [has_faithful_smul M A] :
function.injective (mul_semiring_action.to_alg_hom R A : M → A →ₐ[R] A) :=
λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_hom.ext_iff.1 h r
end mul_semiring_action
|
Thanks for your interest in RSD Site Services. We appreciate your feedback and suggestions. If you have any questions about RSD Site Services, you can email us at [email protected].
Thanks for visiting. We’ll be in touch with you shortly with more information. |
State Before: P : Type u_1
inst✝ : Preorder P
IF : PrimePair P
src✝ : IsProper IF.I := I_isProper IF
⊢ IsPFilter (↑IF.Iᶜ) State After: P : Type u_1
inst✝ : Preorder P
IF : PrimePair P
src✝ : IsProper IF.I := I_isProper IF
⊢ IsPFilter ↑IF.F Tactic: rw [IF.compl_I_eq_F] State Before: P : Type u_1
inst✝ : Preorder P
IF : PrimePair P
src✝ : IsProper IF.I := I_isProper IF
⊢ IsPFilter ↑IF.F State After: no goals Tactic: exact IF.F.isPFilter |
State Before: x a : ℝ
⊢ 0 ^ x = a ↔ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 State After: case mp
x a : ℝ
⊢ 0 ^ x = a → x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1
case mpr
x a : ℝ
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 → 0 ^ x = a Tactic: constructor State Before: case mp
x a : ℝ
⊢ 0 ^ x = a → x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 State After: case mp
x a : ℝ
hyp : 0 ^ x = a
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 Tactic: intro hyp State Before: case mp
x a : ℝ
hyp : 0 ^ x = a
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 State After: case mp
x a : ℝ
hyp : (0 ^ ↑x).re = a
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 Tactic: simp only [rpow_def, Complex.ofReal_zero] at hyp State Before: case mp
x a : ℝ
hyp : (0 ^ ↑x).re = a
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 State After: case pos
x a : ℝ
hyp : (0 ^ ↑x).re = a
h : x = 0
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1
case neg
x a : ℝ
hyp : (0 ^ ↑x).re = a
h : ¬x = 0
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 Tactic: by_cases x = 0 State Before: case pos
x a : ℝ
hyp : (0 ^ ↑x).re = a
h : x = 0
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 State After: case pos
a : ℝ
hyp : (0 ^ ↑0).re = a
⊢ 0 ≠ 0 ∧ a = 0 ∨ 0 = 0 ∧ a = 1 Tactic: subst h State Before: case pos
a : ℝ
hyp : (0 ^ ↑0).re = a
⊢ 0 ≠ 0 ∧ a = 0 ∨ 0 = 0 ∧ a = 1 State After: case pos
a : ℝ
hyp : 1 = a
⊢ 0 ≠ 0 ∧ a = 0 ∨ 0 = 0 ∧ a = 1 Tactic: simp only [Complex.one_re, Complex.ofReal_zero, Complex.cpow_zero] at hyp State Before: case pos
a : ℝ
hyp : 1 = a
⊢ 0 ≠ 0 ∧ a = 0 ∨ 0 = 0 ∧ a = 1 State After: no goals Tactic: exact Or.inr ⟨rfl, hyp.symm⟩ State Before: case neg
x a : ℝ
hyp : (0 ^ ↑x).re = a
h : ¬x = 0
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 State After: case neg
x a : ℝ
hyp : 0.re = a
h : ¬x = 0
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 Tactic: rw [Complex.zero_cpow (Complex.ofReal_ne_zero.mpr h)] at hyp State Before: case neg
x a : ℝ
hyp : 0.re = a
h : ¬x = 0
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 State After: no goals Tactic: exact Or.inl ⟨h, hyp.symm⟩ State Before: case mpr
x a : ℝ
⊢ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 → 0 ^ x = a State After: case mpr.inl.intro
x : ℝ
h : x ≠ 0
⊢ 0 ^ x = 0
case mpr.inr.intro
⊢ 0 ^ 0 = 1 Tactic: rintro (⟨h, rfl⟩ | ⟨rfl, rfl⟩) State Before: case mpr.inl.intro
x : ℝ
h : x ≠ 0
⊢ 0 ^ x = 0 State After: no goals Tactic: exact zero_rpow h State Before: case mpr.inr.intro
⊢ 0 ^ 0 = 1 State After: no goals Tactic: exact rpow_zero _ |
(*
* Copyright (C) BedRock Systems Inc. 2023
* This software is distributed under the terms of the BedRock Open-Source License.
* See the LICENSE-BedRock file in the repository root for details.
*)
Require Import elpi.apps.locker.
From iris.proofmode Require Import proofmode.
From bedrock.lang.bi Require Import prelude observe.
From bedrock.lang.cpp.semantics Require Import values.
From bedrock.lang.cpp.logic Require Import arr heap_pred.
From bedrock.lang.cpp.bi Require Import spec.
Import ChargeNotation.
#[local] Open Scope Z_scope.
(** Core C++ string theory: part of the semantics. *)
(** [strings_bytesR ct q chars] is [q] (const) fractional ownership of
[chars] with a trailing [0].
- Unlike [zstring.t], does not assume the contents avoid `0` elements, since that property might not be guaranteed in all character types/encodings.
- Used for string literals of arbitrary character types.
NOTE that [chars] is in units of *characters* using the standard
character encoding (see [syntax/expr.v]). This is *not* the
same as bytes, and will not be for multi-byte characters.
*)
mlock
Definition string_bytesR `{Σ : cpp_logic} {σ : genv} (cty : char_type) (q : cQp.t) (ls : list N) : Rep :=
let ty := Tchar_ cty in
arrayR ty (λ c, primR ty q (N_to_char cty c)) (ls ++ [0%N]).
#[global] Arguments string_bytesR {_ _ _} _ _ _ : assert.
(* Arguments char_type.bitsN !_ /.
Arguments char_type.bytesN !_ /. *)
Lemma N_to_char_Cchar_eq (c : N) :
(c < 2 ^ 8)%N ->
N_to_char char_type.Cchar c = Vchar c.
Proof.
intros.
rewrite /N_to_char /operator.trimN/=. f_equiv.
exact: N.mod_small.
Qed.
Section with_Σ.
Context `{Σ : cpp_logic} {σ : genv}.
#[global] Instance string_bytesR_timeless : Timeless3 string_bytesR.
Proof. rewrite string_bytesR.unlock /=. apply _. Qed.
#[global] Instance string_bytesR_cfrac cty : CFractional1 (string_bytesR cty).
Proof. rewrite string_bytesR.unlock /=. apply _. Qed.
End with_Σ.
|
\thispagestyle{empty}
%----------------------------------------------------------------------
\chapter{Introduction}
\label{introduction.chap}
%----------------------------------------------------------------------
\section{Objectives}
%----------------------------------------------------------------------
This practical course reader aims at giving good advice to students realizing a project. Starting with the theoretical knowledge contained in the reader of Prof. Alexandre Bayen, students have to realize a project based on a distributed parameter system that they should:
\begin{enumerate}
\item describe
\item model
\item explain
\end{enumerate}
The first part is a descriptive (i.e. qualitative) description of the system to be studied, its interest and the goal of the study. The second part is an elaboration, under simplifications, of a quantitative model (meaning here some kind of Partial Differential Equation and some control or optimization). The third part is an analysis of this model, either by solving the equations, by simulation or by a combination of both, using the tools learned during the course. It should lead to a better understanding of how the system works and how it can be optimized or controlled to fulfill the goals set in the description.
Therefore this practical course reader shows examples of modeling and various analysis methods that can support the creativity of the students realizing a project.
\section{System description}\label{description.sec}
%----------------------------------------------------------------------
A system is, according to Cambridge dictionary ``a set of connected things or devices that operate together''. There is no recipe to describe a system. However, it is often useful, instead of having an \emph{analytical} description (i.e. tear the system into pieces), to have a \emph{synthetic} one (i.e. seeking for a global view). Without any generalization, again, one can look after the following 4 views of a system:
\begin{enumerate}
\item objective
\item environment
\item actions
\item transformations
\end{enumerate}
One can very arguably contest these words, but remember they are only guidelines. In most systems, since they are man-made, there is a goal. This \emph{objective} is important to describe since it contains the meaning: what is it for? Note this is quite often the opposite of the analytical view: how does it work? However, in our case, this goal contains the information about the \emph{objective function} for optimization or for control. The \emph{environment} dictates what the system has to do: a system is never isolated and its goal is often closely related to its environment. At least, the \emph{actions} a system perform are partially internal and partially external, so that taking into account the environment allow understanding of disturbances but also the objective. Since a system is usually complex, it may evolve (i.e. experience \emph{transformations}) according to actions and in line with the objective. One can also think of transformation as internal states of a finite automaton.
In any case, a description is intended at telling the whole story to other people and this is why it is highly recommended to use only words, no formula, but drawings can well replace a thousand words.
\section{System modeling}
%----------------------------------------------------------------------
While a system description is intended to be purely qualitative, modeling aims at estimating some quantities. Very clearly, the choice of the quantities is decisive. Important quantities can be derived from the system description, such as the objective function (what to maximize or minimize?), the transformations (internal states) or environment variables.
There are many ways to measure quantities, e.g. numbers of vehicles in a microscopic view may be equivalent to measuring densities of vehicle at a macroscopic scale. Unfortunately there is no algorithm to produce significant model and this is a knowledge that needs practice. However, in our present case, namely partial differential equations modeling, there is very often a kind of scaling that is necessary in order to produce continuous-space and continuous time variables. Since this reader aims at being practical, the reader is referred to Chapter~\ref{modeling.chap} for modeling examples.
One can (too?) quickly summarize some usual quantities of interest:
\begin{itemize}
\item macroscopic quantities (temperature, density, deformation...);
\item variables (state space, time...) and parameters including the control;
\item optimization criteria;
\item invariant quantities (mass, energy, momentum...) and constraints;
\item initial and boundary conditions.
\end{itemize}
\section{System explanation}
%----------------------------------------------------------------------
What is called here explanation has been also called ``solution'' during the course. It consists mainly in studying the model under various views and to produce new knowledge. This usually implies simulations, analytical analysis, optimization and visualization; all previous methods can be compared or combined in order to give more insight of the model.
\subsection{Analysis}\label{analysis.sec}
Analysis is important for the concepts it carries. We have learned a few methods to exactly solve or to transform the PDEs:
\begin{enumerate}
\item Dimensional analysis allow to build interesting quantities that should remain constant;
\item Product-form solutions leads to decomposition of solutions (often in the type of Fourrier transform) with knowledge of the modes and their frequencies (spatial and temporal).
\item the method of characteristics is a powerful methods to build solutions, even discontinuous like shockwaves in LWR equations. The characteristic curves are interesting features.
\end{enumerate}
In the present course, students should perform some initial analytical analysis, even if it does not lead to a complete solution, in order to exhibits interesting quantities as mentioned above. These quantities should be used as guidelines as far as possible for further study.
\subsection{Simulation}\label{simulation.sec}
Simulation is interesting for all the data it brings. However there are many ways to simulate a system. At least we can mention:
\begin{itemize}
\item Microscopic simulation --- often agent-based --- where a lot of microscopic entities evolves with their dynamics; This method is relevant when the PDE is a macroscopic view of the system, i.e. when it is derived from a scaling;
\item Finite differences schemes, that is often a direct implementation of the dynamics underlying the PDE (differences apply on a discretization of space and time);
\item Finite elements is usually associated to computation of eigenvalues and eigenvectors, i.e. to product-form solutions and the computation of modes; in this case, discretization is made through a projection of the functions onto a finite (functional) basis.
\end{itemize}
In this course, students have to produce simulations. The goal is to exploit the data to visualize the system evolution (see also Section~\ref{visualization.sec}) and get a better understanding. One of the main problem of simulation is to have a clear idea of the quantities to be displayed, be it statistics, metrics or functions. This is why a good prior analysis (see also Section~\ref{analysis.sec}) is a good idea. A must in simulation is to compare quantities computed from the output of the simulation with similar quantities computed from theoretical analysis: e.g. number of vehicles per km in micro-simulation with densities in LWR equations.
\subsection{Optimization or control}\label{optimization.sec}
The goal of this course is to learn how a system can be controlled or optimized. This requires to have a good description of the system in order to have clear ideas of what is to be optimized or controlled. Usually, the design of the control is free and this is where students can be creative.
There is a very common distinction between 2 close concepts: planning and control. In most real systems, the planning phase is responsible for building suitable a path, according to the dynamics of the system and to the environment; then, a control loop ensures the systems follows this path by using actuators (the controls) and taking care of disturbances (in sensors and in actuators). Planning is open-loop, usually with a simple model (deterministic...) but with a complex cost function that expresses the desirable behavior. Control is closed-loop, designed to be robust, taking into account noises and disturbances, with a simple cost function: follow the plan.
Techniques are very diverse and really depend on the system and the kind of control. Examples are given in Chapter~\ref{control.chap}.
\subsection{Visualization}\label{visualization.sec}
The visualization aspect of a study may be the most important yet the most challenging. Indeed, a drawing is extremely instructive, provided it is well explained. But the beauty can be misleading and the students have to take great care of the quantities they illustrate: What should be seen in the drawing? What does it tell us? Does it compare well with existing knowledge or not?
Therefore it is advised to start quickly (very early with simulation data) to try to see something and to continuously improve the visualization aspect. It is important for explaining the results as well as for enhancing the students' own understanding (and debugging the codes, very often).
|
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_DIRECTIVES_HPP_20111201
#define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_DIRECTIVES_HPP_20111201
// Copyright 2011 Dean Michael Berris <[email protected]>.
// Copyright 2011 Google, Inc.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/network/protocol/http/message/directives/method.hpp>
#include <boost/network/protocol/http/message/directives/status.hpp>
#include <boost/network/protocol/http/message/directives/status_message.hpp>
#include <boost/network/protocol/http/message/directives/uri.hpp>
#include <boost/network/protocol/http/message/directives/version.hpp>
#endif // BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_DIRECTIVES_HPP_20111201
|
[STATEMENT]
lemma (in ceuclidean_space) CBasis_zero [simp]: "0 \<notin> CBasis"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (0::'a) \<notin> CBasis
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (0::'a) \<in> CBasis \<Longrightarrow> False
[PROOF STEP]
assume "0 \<in> CBasis"
[PROOF STATE]
proof (state)
this:
(0::'a) \<in> CBasis
goal (1 subgoal):
1. (0::'a) \<in> CBasis \<Longrightarrow> False
[PROOF STEP]
thus "False"
[PROOF STATE]
proof (prove)
using this:
(0::'a) \<in> CBasis
goal (1 subgoal):
1. False
[PROOF STEP]
using cinner_CBasis [of 0 0]
[PROOF STATE]
proof (prove)
using this:
(0::'a) \<in> CBasis
\<lbrakk>(0::'a) \<in> CBasis; (0::'a) \<in> CBasis\<rbrakk> \<Longrightarrow> (0::'a) \<bullet>\<^sub>C (0::'a) = (if (0::'a) = (0::'a) then 1 else 0)
goal (1 subgoal):
1. False
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
False
goal:
No subgoals!
[PROOF STEP]
qed |
function [params, result] = ortho_quasi(params, W, w)
% Quasi-orthogonalization
% W = orthof(params, W) for symmetric dss
% w = orthof(params, W, w) for deflation dss
% params.alpha For deflation...
% W Matrix with projection vectors as rows. For deflation
% algorithm only previously calculated projections are given.
% w Currently iterated projection. Only for deflation algorithm.
% Copyright (C) 2004, 2005 DSS MATLAB package team ([email protected]).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$
if nargin<2
params.name = 'Quasi-orthogonalization';
params.description = 'Description of this function.';
params.param = {'alpha'};
params.param_type = {'scalar'};
params.param_value = {0.1};
params.param_desc = {'For deflation...'};
return;
end
if ~isfield(params, 'alpha')
% TODO: set alpha based on data dimension
params.alpha = 0.1;
end
if nargin>2
% per component quasi-orthogonalization
w = w - params.alpha * W' * W * w;
result = w / norm(w);
else
% symmetric quasi-orthogonalization
W = 3/2*W - W'*W*W'/2;
result = W.*(sum(W.^2,2).^(-1/2)*ones(1,size(W,2)));
end
|
myTestRule {
#Input parameter is:
# Message to send to iRODS server log file
#Output parameter is:
# Status
#Output from running the example is:
# Message is Test message for irods/server/log/rodsLog
#Output written to log file is:
# msiWriteRodsLog message: Test message for irods/server/log/rodsLog
writeLine("stdout","Message is *Message");
msiWriteRodsLog(*Message,*Status);
}
INPUT *Message="Test message for irods/server/log/rodsLog"
OUTPUT ruleExecOut
|
*----------------------------------------------------------------------*
logical function next_string(idorb,idspn,idss,
& nidx,ms,igam,first,
& igas_restr,
& mostnd_cur,igamorb,
& nsym,ngas_cur)
*----------------------------------------------------------------------*
* generate next string with for current Ms, IRREP
*----------------------------------------------------------------------*
implicit none
include 'opdim.h'
include 'stdunit.h'
integer, parameter ::
& ntest = 00
integer, intent(in) ::
& nidx, ms, igam,
& igas_restr(2,ngas_cur,2),
& nsym,ngas_cur,
& mostnd_cur(2,nsym),igamorb(*)
integer, intent(inout) ::
& idorb(nidx), idspn(nidx), idss(nidx)
logical, intent(in) ::
& first
logical ::
& succ
integer ::
& idx, idxoff
integer ::
& ioss(ngas_cur)
logical, external ::
& lexlstr, nextstr, next_ssd, allow_sbsp_dis
integer, external ::
& igamstr2, ielsum
if (ntest.gt.0) then
write(lulog,*) '-----------------------'
write(lulog,*) ' info from next_string'
write(lulog,*) '-----------------------'
write(lulog,*) ' nidx = ',nidx
write(lulog,*) ' ngas = ',ngas_cur
end if
c dbg
c print *,'idorb',idorb(1:nidx)
c dbg
if (first) then
next_string = .true.
if (nidx.eq.0) return
! first subspace distribution
idss(1:nidx) = 1
dss_loop: do
if (.not.allow_sbsp_dis(idss,nidx,ngas_cur,igas_restr)) then
if(next_ssd(idss,nidx,nidx,
& ngas_cur,igas_restr)) cycle dss_loop
succ = .false.
exit dss_loop
end if
! lexically lowest string
! reform distribution to occupation
ioss(1:ngas_cur) = 0
do idx = 1, nidx
ioss(idss(idx)) = ioss(idss(idx))+1
end do
succ = lexlstr(nidx,ms,
& ioss,idorb,idspn,
& mostnd_cur,nsym,ngas_cur)
if (succ) then
str_loop: do
! check symmetry
c dbg
c print *,'nidx,idorb: ',nidx,idorb(1:nidx)
c print *,'igamorb',igamorb(1:8)
c dbg
succ = igamstr2(nidx,idorb,igamorb).eq.igam
! exit if successful
if (succ) exit dss_loop
! else: get next possible string
succ = nextstr(nidx,ms,
& idss,idorb,idspn,
& mostnd_cur,nsym,ngas_cur)
if (.not.succ) exit str_loop
end do str_loop
end if
! if no appropriate string found:
! get next subspace distr.
succ = next_ssd(idss,nidx,nidx,
& ngas_cur,igas_restr)
! nothing: we have to give up
if (.not.succ) exit dss_loop
end do dss_loop
next_string = succ
if (ntest.ge.100) then
if (succ) then
write(lulog,*) 'first string: ',idorb(1:nidx)
write(lulog,*) ' ',idspn(1:nidx)
write(lulog,*) ' ',idss(1:nidx)
else
write(lulog,*) 'no string exists'
end if
end if
return
else
next_string = .false.
if (nidx.eq.0) return
if (ntest.ge.100) then
write(lulog,*) ' input string:',idorb(1:nidx)
write(lulog,*) ' ',idspn(1:nidx)
write(lulog,*) ' ',idss(1:nidx)
end if
dss_loop2: do
str_loop2: do
! try next string ...
succ = nextstr(nidx,ms,
& idss,idorb,idspn,
& mostnd_cur,nsym,ngas_cur)
! ... no further string ? ....
if (.not.succ) exit str_loop2
! ... else check symmetry ...
if (succ)
& succ = igamstr2(nidx,idorb,igamorb).eq.igam
! if symmetry was alright, we are done
if (succ) exit dss_loop2
end do str_loop2
! here we land, if we need to try the next
! subspace distribution
succ = next_ssd(idss,nidx,nidx,
& ngas_cur,igas_restr)
! nothing: we have to give up
if (.not.succ) exit dss_loop2
! else we have to get the lexically lowest string
! for the new subspace distribution
! reform distribution to occupation
ioss(1:ngas_cur) = 0
do idx = 1, nidx
ioss(idss(idx)) = ioss(idss(idx))+1
end do
succ = lexlstr(nidx,ms,
& ioss,idorb,idspn,
& mostnd_cur,nsym,ngas_cur)
c dbg
c print *,'nidx,idorb: ',nidx,idorb(1:nidx)
c print *,'igamorb',igamorb(1:8)
c dbg
! ... check symmetry ...
if (succ)
& succ = igamstr2(nidx,idorb,igamorb).eq.igam
! ... we are done?
if (succ) exit dss_loop2
! ... else go to top of loop and increment string
end do dss_loop2
next_string = succ
if (ntest.ge.100) then
if (succ) then
write(lulog,*) ' next string: ',idorb(1:nidx)
write(lulog,*) ' ',idspn(1:nidx)
write(lulog,*) ' ',idss(1:nidx)
else
write(lulog,*) ' no further string exists'
end if
end if
return
end if
end
*----------------------------------------------------------------------*
|
Hobbs made international news when Governor West sent her to implement martial law in the small Eastern Oregon town of Copperfield . The event was considered a strategic coup for West , establishing the State 's authority over a remote rural community and cementing his reputation as a proponent of prohibition .
|
lemma continuous_map_canonical_const [continuous_intros]: "continuous_map X euclidean (\<lambda>x. c)" |
-- An ATP-pragma must appear in the same module where its argument is
-- defined.
-- This error is detected by TypeChecking.Monad.Signature.
module ATPImports where
open import Imports.ATP-A
{-# ATP axiom p #-}
postulate foo : a ≡ b
{-# ATP prove foo #-}
|
-makelib xcelium_lib/xil_defaultlib \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ip/SDOS_ST_BT_SPLIT_0_0/sim/SDOS_ST_BT_SPLIT_0_0.vhd" \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ip/SDOS_ST_ISERDES_B_0_0/sim/SDOS_ST_ISERDES_B_0_0.vhd" \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ip/SDOS_ST_ISERDES_B_1_0/sim/SDOS_ST_ISERDES_B_1_0.vhd" \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ip/SDOS_ST_ISERDES_B_2_0/sim/SDOS_ST_ISERDES_B_2_0.vhd" \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ip/SDOS_ST_ISERDES_B_3_0/sim/SDOS_ST_ISERDES_B_3_0.vhd" \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ip/SDOS_ST_SDDR_ST_0_0/sim/SDOS_ST_SDDR_ST_0_0.vhd" \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ip/SDOS_ST_ST_REDIR_0_0/sim/SDOS_ST_ST_REDIR_0_0.vhd" \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ip/SDOS_ST_BT_SPLIT_0_1/sim/SDOS_ST_BT_SPLIT_0_1.vhd" \
-endlib
-makelib xcelium_lib/util_vector_logic_v2_0_1 \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ipshared/2137/hdl/util_vector_logic_v2_0_vl_rfs.v" \
-endlib
-makelib xcelium_lib/xil_defaultlib \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/ip/SDOS_ST_util_vector_logic_0_0/sim/SDOS_ST_util_vector_logic_0_0.v" \
-endlib
-makelib xcelium_lib/xil_defaultlib \
"../../../../SDOS_ST.srcs/sources_1/bd/SDOS_ST/sim/SDOS_ST.vhd" \
-endlib
-makelib xcelium_lib/xil_defaultlib \
glbl.v
-endlib
|
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Interaction_catalog")
# -----------------------------------------------------------------------------
# PROJECT:
# Evaluating the structure of the communities of the estuary
# and gulf of St.Lawrence
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# REPOSITORY
# The first step of this project is to compile a catalog of interactions
# from empirical data
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# PROCESS STEPS:
# 1. Species list for estuary and gulf of St. Lawrence
# Script <- file = "Script/1_EGSL_SpList.r"
# RData <- file = "RData/sp_egsl.RData" - EGSL species list
#
# 2. Import and format empirical food web data
#
# 2.1 Barnes et al. 2008
# Script <- file = "Script/2-1_Emp_Webs.r"
# RData <- file = "RData/barnes2008.RData"
#
# 2.2 Kortsch et al. 2015
# Script <- file = "Script/2-2_Emp_Webs.r"
# RData <- file = "RData/Kortsch2015.RData"
#
# 2.3 GlobalWeb data http://globalwebdb.com
# Script <- file = "Script/2-3_Emp_Web.r"
# RData <- file = "RData/GlobalWeb.RData"
#
# 2.4 Brose et al. 2005
# Script <- file = "Script/2-4_Emp_Webs.r"
# RData <- file = "RData/brose2005.RData"
#
# 2.5 Ecopath with Ecosim models *** !!!!! Still needs to be done
# Script <- file = "Script/2-5_Emp_Webs.r"
# RData <- file = "RData/EwE.RData"
#
# 3. List of binary interations to include in the analysis
# Script <- file = "Script/3-Bin_inter_tot.r"
# RData1 <- file = "RData/interactions.RData"
# RData2 <- file = "RData/taxon_list.RData"
#
# 4. Classification of taxon from empirical webs and St. Lawrence species
# Script <- file = "Script/4-Classification_Emp-Webs.r"
# RData <- file = "RData/class_tx_tot.RData"
#
# 5. Global Biotic Interactions (GloBI)
# http://www.globalbioticinteractions.org
# Script <- file = "Script/5-GloBI.r"
# RData <- file = "RData/GloBI.RData"
#
# 6. List of binary interactions from GloBI
# Script <- file = "Script/6-Bin_inter_GloBI.r"
# RData1 <- file = "RData/GloBI_interactions.RData"
# RData2 <- file = "RData/GloBI_taxon.RData"
#
# 7. Classification of taxon from GloBI
# Script <- file = "Script/7-Classification_GloBI.r"
# RData <- file = "RData/GloBI_classification.RData"
#
# 8. Final list of taxon and interations from EmpWeb & GloBI *** Final DB
# Script <- file = "Script/8-Taxon_final.r"
# RData <- file = "RData/Interaction_catalog.RData"
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/bin_inter.R")
source("Script/diet_mat_extend.R")
source("Script/dup_multi_tx.R")
source("Script/duplicate_row_col.R")
source("Script/locate_string.R")
source("Script/tax_rank.R")
source("Script/taxo_resolve.R")
source("Script/taxo_valid.R")
source("Script/tx_valid_res.R")
source("Script/binary_interaction.R")
source("Script/inter_taxo_resolution.R")
source("Script/taxon_resolve_for_classification.R")
source("Script/extract_id.R")
source("Script/class_taxo.R")
source("Script/GloBI_trophic_inter.R")
source("Script/GloBI_taxon_classification.R")
functions_to_keep <- ls()
functions_to_keep <- ls()
# -----------------------------------------------------------------------------
|
Formal statement is: lemma interior_UNIV [simp]: "interior UNIV = UNIV" Informal statement is: The interior of the whole space is the whole space. |
Rebol [
Title: "Log diff"
File: %log-diff.r
Copyright: [2012 "Saphirion AG"]
License: {
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
}
Author: "Ladislav Mecir"
Purpose: "Test framework"
]
import %test-parsing.r
make-diff: function [
old-log [file!]
new-log [file!]
diff-file [file!]
][
if exists? diff-file [delete diff-file]
collect-logs old-log-contents: copy [] old-log
collect-logs new-log-contents: copy [] new-log
sort/case/skip old-log-contents 2
sort/case/skip new-log-contents 2
; counter initialization
new-successes:
new-failures:
new-crashes:
progressions:
regressions:
removed:
unchanged:
0
; cycle initialization
set [old-test old-result] old-log-contents
old-log-contents: skip old-log-contents 2
set [new-test new-result] new-log-contents
new-log-contents: skip new-log-contents 2
loop [any [old-test new-test]] [
case [
all [
new-test
new-result <> 'skipped
any [
blank? old-test
all [
strict-not-equal? old-test new-test
old-test == second sort/case reduce [new-test old-test]
]
all [
old-test == new-test
old-result = 'skipped
]
]
] [
; fresh test
write/append diff-file spaced [
new-test
switch new-result [
'succeeded [
new-successes: new-successes + 1
"succeeded"
]
'failed [
new-failures: new-failures + 1
"failed"
]
'crashed [
new-crashes: new-crashes + 1
"crashed"
]
]
newline
]
]
all [
old-test
old-result <> 'skipped
any [
blank? new-test
all [
strict-not-equal? new-test old-test
new-test == second sort/case reduce [old-test new-test]
]
all [
new-test == old-test
new-result = 'skipped
]
]
] [
; removed test
removed: removed + 1
write/append diff-file spaced [old-test "removed" newline]
]
any [
old-result = new-result
strict-not-equal? old-test new-test
] [unchanged: unchanged + 1]
; having one test with different results
(
write/append diff-file new-test
any [
old-result = 'succeeded
all [
old-result = 'failed
new-result = 'crashed
]
]
) [
; regression
regressions: regressions + 1
write/append diff-file spaced [
space "regression," new-result newline
]
]
]
else [
; progression
progressions: progressions + 1
write/append diff-file spaced [
space "progression," new-result newline
]
]
next-old-log: all [
old-test
any [
blank? new-test
old-test == first sort/case reduce [old-test new-test]
]
]
next-new-log: all [
new-test
any [
blank? old-test
new-test == first sort/case reduce [new-test old-test]
]
]
if next-old-log [
if old-test == pick old-log-contents 1 [
print old-test
fail {duplicate test in old-log}
]
set [old-test old-result] old-log-contents
old-log-contents: skip old-log-contents 2
]
if next-new-log [
if new-test == pick new-log-contents 1 [
print new-test
fail {duplicate test in new-log}
]
set [new-test new-result] new-log-contents
new-log-contents: skip new-log-contents 2
]
]
print "Done."
summary: spaced [
"new-successes:" new-successes
|
"new-failures:" new-failures
|
"new-crashes:" new-crashes
|
"progressions:" progressions
|
"regressions:" regressions
|
"removed:" removed
|
"unchanged:" unchanged
|
"total:"
new-successes + new-failures + new-crashes + progressions
+ regressions + removed + unchanged
]
print summary
write/append diff-file unspaced [
newline
"Summary:" newline
summary newline
]
]
make-diff to-file first load system/script/args to-file second load system/script/args %diff.r
|
module examplesPaperJFP.Collatz where
open import Data.Nat.Base
open import Data.Nat.DivMod
open import Data.Fin using (Fin; zero; suc)
open import examplesPaperJFP.Colists
collatzStep : ℕ → ListF ℕ ℕ
collatzStep 1 = nil
collatzStep n with n divMod 2
... | result q zero _ = cons n q
... | _ = cons n (1 + 3 * n)
collatzSequence : ℕ → Colist ℕ
collatzSequence = unfold collatzStep
open Colist
open import Data.List
displayList : Colist ℕ → ℕ → List ℕ
displayList s 0 = []
displayList s (suc m) with force s
... | nil = []
... | (cons k s′) = k ∷ displayList s′ m
displayCollatz : ℕ → ℕ → List ℕ
displayCollatz n m = displayList (collatzSequence n) m
|
[GOAL]
ι : Type u_1
c : ComplexShape ι
⊢ symm (symm c) = c
[PROOFSTEP]
ext
[GOAL]
case Rel.h.h.a
ι : Type u_1
c : ComplexShape ι
x✝¹ x✝ : ι
⊢ Rel (symm (symm c)) x✝¹ x✝ ↔ Rel c x✝¹ x✝
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
c₁ c₂ : ComplexShape ι
i✝ j✝ j'✝ : ι
w : Relation.Comp c₁.Rel c₂.Rel i✝ j✝
w' : Relation.Comp c₁.Rel c₂.Rel i✝ j'✝
⊢ j✝ = j'✝
[PROOFSTEP]
obtain ⟨k, w₁, w₂⟩ := w
[GOAL]
case intro.intro
ι : Type u_1
c₁ c₂ : ComplexShape ι
i✝ j✝ j'✝ : ι
w' : Relation.Comp c₁.Rel c₂.Rel i✝ j'✝
k : ι
w₁ : Rel c₁ i✝ k
w₂ : Rel c₂ k j✝
⊢ j✝ = j'✝
[PROOFSTEP]
obtain ⟨k', w₁', w₂'⟩ := w'
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
c₁ c₂ : ComplexShape ι
i✝ j✝ j'✝ k : ι
w₁ : Rel c₁ i✝ k
w₂ : Rel c₂ k j✝
k' : ι
w₁' : Rel c₁ i✝ k'
w₂' : Rel c₂ k' j'✝
⊢ j✝ = j'✝
[PROOFSTEP]
rw [c₁.next_eq w₁ w₁'] at w₂
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
c₁ c₂ : ComplexShape ι
i✝ j✝ j'✝ k : ι
w₁ : Rel c₁ i✝ k
k' : ι
w₂ : Rel c₂ k' j✝
w₁' : Rel c₁ i✝ k'
w₂' : Rel c₂ k' j'✝
⊢ j✝ = j'✝
[PROOFSTEP]
exact c₂.next_eq w₂ w₂'
[GOAL]
ι : Type u_1
c₁ c₂ : ComplexShape ι
i✝ i'✝ j✝ : ι
w : Relation.Comp c₁.Rel c₂.Rel i✝ j✝
w' : Relation.Comp c₁.Rel c₂.Rel i'✝ j✝
⊢ i✝ = i'✝
[PROOFSTEP]
obtain ⟨k, w₁, w₂⟩ := w
[GOAL]
case intro.intro
ι : Type u_1
c₁ c₂ : ComplexShape ι
i✝ i'✝ j✝ : ι
w' : Relation.Comp c₁.Rel c₂.Rel i'✝ j✝
k : ι
w₁ : Rel c₁ i✝ k
w₂ : Rel c₂ k j✝
⊢ i✝ = i'✝
[PROOFSTEP]
obtain ⟨k', w₁', w₂'⟩ := w'
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
c₁ c₂ : ComplexShape ι
i✝ i'✝ j✝ k : ι
w₁ : Rel c₁ i✝ k
w₂ : Rel c₂ k j✝
k' : ι
w₁' : Rel c₁ i'✝ k'
w₂' : Rel c₂ k' j✝
⊢ i✝ = i'✝
[PROOFSTEP]
rw [c₂.prev_eq w₂ w₂'] at w₁
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
c₁ c₂ : ComplexShape ι
i✝ i'✝ j✝ k : ι
w₂ : Rel c₂ k j✝
k' : ι
w₁ : Rel c₁ i✝ k'
w₁' : Rel c₁ i'✝ k'
w₂' : Rel c₂ k' j✝
⊢ i✝ = i'✝
[PROOFSTEP]
exact c₁.prev_eq w₁ w₁'
[GOAL]
ι : Type u_1
c : ComplexShape ι
i : ι
⊢ Subsingleton { j // Rel c i j }
[PROOFSTEP]
constructor
[GOAL]
case allEq
ι : Type u_1
c : ComplexShape ι
i : ι
⊢ ∀ (a b : { j // Rel c i j }), a = b
[PROOFSTEP]
rintro ⟨j, rij⟩ ⟨k, rik⟩
[GOAL]
case allEq.mk.mk
ι : Type u_1
c : ComplexShape ι
i j : ι
rij : Rel c i j
k : ι
rik : Rel c i k
⊢ { val := j, property := rij } = { val := k, property := rik }
[PROOFSTEP]
congr
[GOAL]
case allEq.mk.mk.e_val
ι : Type u_1
c : ComplexShape ι
i j : ι
rij : Rel c i j
k : ι
rik : Rel c i k
⊢ j = k
[PROOFSTEP]
exact c.next_eq rij rik
[GOAL]
ι : Type u_1
c : ComplexShape ι
j : ι
⊢ Subsingleton { i // Rel c i j }
[PROOFSTEP]
constructor
[GOAL]
case allEq
ι : Type u_1
c : ComplexShape ι
j : ι
⊢ ∀ (a b : { i // Rel c i j }), a = b
[PROOFSTEP]
rintro ⟨i, rik⟩ ⟨j, rjk⟩
[GOAL]
case allEq.mk.mk
ι : Type u_1
c : ComplexShape ι
j✝ i : ι
rik : Rel c i j✝
j : ι
rjk : Rel c j j✝
⊢ { val := i, property := rik } = { val := j, property := rjk }
[PROOFSTEP]
congr
[GOAL]
case allEq.mk.mk.e_val
ι : Type u_1
c : ComplexShape ι
j✝ i : ι
rik : Rel c i j✝
j : ι
rjk : Rel c j j✝
⊢ i = j
[PROOFSTEP]
exact c.prev_eq rik rjk
[GOAL]
ι : Type u_1
c : ComplexShape ι
i j : ι
h : Rel c i j
⊢ next c i = j
[PROOFSTEP]
apply c.next_eq _ h
[GOAL]
ι : Type u_1
c : ComplexShape ι
i j : ι
h : Rel c i j
⊢ Rel c i (next c i)
[PROOFSTEP]
rw [next]
[GOAL]
ι : Type u_1
c : ComplexShape ι
i j : ι
h : Rel c i j
⊢ Rel c i (if h : ∃ j, Rel c i j then Exists.choose h else i)
[PROOFSTEP]
rw [dif_pos]
[GOAL]
ι : Type u_1
c : ComplexShape ι
i j : ι
h : Rel c i j
⊢ Rel c i (Exists.choose ?hc)
case hc ι : Type u_1 c : ComplexShape ι i j : ι h : Rel c i j ⊢ ∃ j, Rel c i j
[PROOFSTEP]
exact Exists.choose_spec ⟨j, h⟩
[GOAL]
ι : Type u_1
c : ComplexShape ι
i j : ι
h : Rel c i j
⊢ prev c j = i
[PROOFSTEP]
apply c.prev_eq _ h
[GOAL]
ι : Type u_1
c : ComplexShape ι
i j : ι
h : Rel c i j
⊢ Rel c (prev c j) j
[PROOFSTEP]
rw [prev, dif_pos]
[GOAL]
ι : Type u_1
c : ComplexShape ι
i j : ι
h : Rel c i j
⊢ Rel c (Exists.choose ?hc) j
case hc ι : Type u_1 c : ComplexShape ι i j : ι h : Rel c i j ⊢ ∃ i, Rel c i j
[PROOFSTEP]
exact Exists.choose_spec (⟨i, h⟩ : ∃ k, c.Rel k j)
|
##BarBIQ_final_fitting_OD.r
#####Author#####
#Jianshi Frank Jin
#####Version#####
#V1.001
#2018.12.02
###Before running, please change the following information which labeled by "CHECK1-4".
setwd("/yourpath") ### "CHECK1" path of your data
library (plotrix)
group1 <- read.table("output_filename_step15", ## "CHECK2" your data file name
header=T, sep="")
outputname<- "EDrops.txt" ## "CHECK3" your output file name
write.table(t(c("ID", "EDrop", "SE")),file=outputname,sep="\t",col.names = F, row.names = F, quote = F)
## ID: the index ID;
## EDrop: operational droplet (OD);
## SE: standard error.
### For the sample SX
for (i in c("S1","S2")) ## "CHECK4" Indexes you want to analysis
{
sample<- i
sampleA<-paste(c(sample,"A"),collapse = "_")
sampleB<-paste(c(sample,"B"),collapse = "_")
sampleO<-paste(c(sample,"O"),collapse = "_")
group2 <- group1[(group1[,sampleA]>0 & group1[,sampleB]>0), ]
x=log10(group2[,sampleA]*group2[,sampleB])
y=group2[,sampleO]
data <- cbind(x,y)
data <- data.frame(data)
### Calculate the median
stock<-c()
for(i in seq(from=-0.4, to=10, by=0.2))
{
low=i;
up=i+0.4;
mid=low+0.2;
data1<-data[data$x >low, ];
data1<-data1[data1$x <= up, ];
# print(nrow(data1));
if(nrow(data1)>2)
{
mean<-mean(data1[,2]);
media<-median(data1[,2]);
stock=rbind(stock,c(mid,mean,media));
}
}
stock <- data.frame(stock)
colnames(stock)=c("mid","mean","media")
stock$media<-log10(stock$media)
stock$mean<-log10(stock$mean)
stock[stock == "-Inf"]<- -2
select=stock[stock$media > -2, ];
x=select$mid
y=select$media
## Fitting
model <- lm(y ~ 1 + offset(x))
print(p<-summary(model))
predicted.intervals <- predict(model,data.frame(x=x),interval='confidence',
level=0.99)
# EDrop <- read.table(outputname, header=F, sep="", colClasses=c("character"))
newdata<-t(c(sample, -model$coeff,p$coefficients[,2]))
# EDrop<-rbind(EDrop,newdata)
write.table(newdata,file=outputname,sep="\t",col.names = F, row.names = F, quote = F, append = T)
}
##end##
|
A set $S$ is simply connected if and only if $S$ is empty or there exists a point $a \in S$ such that for every loop $p$ in $S$ with $p(0) = p(1) = a$, $p$ is homotopic to the constant loop at $a$. |
lemma pcompose_idR[simp]: "pcompose p [: 0, 1 :] = p" for p :: "'a::comm_semiring_1 poly" |
lemma tendsto_compose_at: assumes f: "(f \<longlongrightarrow> y) F" and g: "(g \<longlongrightarrow> z) (at y)" and fg: "eventually (\<lambda>w. f w = y \<longrightarrow> g y = z) F" shows "((g \<circ> f) \<longlongrightarrow> z) F" |
[STATEMENT]
lemma \<alpha>edges_finite[simp, intro!]: "invar g \<Longrightarrow> finite (\<alpha>edges_aux g)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. invar g \<Longrightarrow> finite (\<alpha>edges_aux g)
[PROOF STEP]
using finite_subset[OF \<alpha>edges_subset]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>invar ?g1; finite (\<alpha>nodes_aux ?g1 \<times> \<alpha>nodes_aux ?g1)\<rbrakk> \<Longrightarrow> finite (\<alpha>edges_aux ?g1)
goal (1 subgoal):
1. invar g \<Longrightarrow> finite (\<alpha>edges_aux g)
[PROOF STEP]
by blast |
The module does not cope well with discontinuities.
```
from sympy.plotting import plot
```
```
plot(1/x)
```
```
plot(1/x,(x, 0, 3))
```
```
plot(Heaviside(x))
```
```
plot(sqrt(x))
```
```
plot(-sqrt(sqrt(x)),sqrt(sqrt(x)))
```
```
plot(LambertW(x))
```
```
plot(LambertW(x), sqrt(LambertW(x)), (x, -2, 1))
```
|
program PSEConvergenceTest
use NumberKindsModule
use LoggerModule
use PolyMesh2dModule
use ParticlesModule
use EdgesModule
use FacesModule
use STDIntVectorModule
use FieldModule
use PSEDirectSumModule
use MPISetupModule
implicit none
include 'mpif.h'
type(Logger) :: exeLog
character(len=MAX_STRING_LENGTH) :: logstring
character(len=15) :: logKey = "planePSE"
integer(kint), parameter :: logLevel = DEBUG_LOGGING_LEVEL
type(PolyMesh2d) :: planarMesh
integer(kint), parameter :: meshSeed = QUAD_RECT_SEED
integer(kint) :: initNest
integer(kint) :: maxNest
integer(kint) :: amrLimit
real(kreal) :: ampFactor
type(Field) :: scalar
type(Field) :: estGrad, exactGrad, gradError
type(Field) :: estLap, exactLap, lapError
type(Field) :: est2ndPartials, exact2ndPartials, partialErr
real(kreal) :: maxLap, minLap, maxGradMag, minGradMag
type(PSE) :: pseSetup
real(kreal) :: interpLoc(3)
real(kreal), parameter :: b = 3.0_kreal
real(kreal), parameter :: xc = 0.0_kreal, yc = 0.0_kreal
real(kreal), parameter :: maxAbsLap = 36.0_kreal
real(kreal) :: estGradError(9), estLapError(9), interpError(9), meshSize(9)
real(kreal) :: testStart, testEnd, programStart, programEnd
integer(kint) :: i, j
real(kreal) :: xPhys(3), vecA(3), vecB(3)
integer(kint), parameter :: nn = 501
real(kreal), parameter :: dx = 8.0_kreal / real(nn-1,kreal)
real(kreal), parameter :: xmin = -4.0_kreal
real(kreal), parameter :: xmax = 4.0_kreal
real(kreal), parameter :: ymin = xmin
real(kreal), parameter :: ymax = xmax
real(kreal) :: x(nn), y(nn)
real(kreal) :: interpScalar(nn,nn), exactScalar(nn,nn)
character(len=MAX_STRING_LENGTH) :: filename
type(MPISetup) :: particlesMPI, interpMPI
integer(kint) :: mpiErrCode
call MPI_INIT(mpiErrCode)
call MPI_COMM_SIZE(MPI_COMM_WORLD, numProcs, mpiErrCode)
call MPI_COMM_RANK(MPI_COMM_WORLD, procRank, mpiErrCode)
call InitLogger(exeLog, procRank)
programStart = MPI_WTIME()
do i = 1, nn
x(i) = xmin + dx * (i-1)
y(i) = ymin + dx * (i-1)
enddo
do initNest = 0, 8
!call cpu_time(testStart)
testStart = MPI_WTIME()
!
! build the mesh
!
maxNest = initNest
amrLimit = 0
ampFactor = 3.0_kreal
call New(planarMesh, meshSeed, initNest, maxNest, amrLimit, ampFactor)
call New(particlesMPI, planarMesh%particles%N, numProcs)
call New(interpMPI, nn, numProcs)
! define the scalar
call New(scalar, 1, planarMesh%particles%N, "gaussScalar", "n/a")
call New(estGrad, 2, planarMesh%particles%N, "estGradient", "n/a")
call New(exactGrad, 2, planarMesh%particles%N, "exactGradient", "n/a")
call New(gradError, 1, planarMesh%particles%N, "gradError", "n/a")
call New(estLap, 1, planarMesh%particles%N, "estLap", "n/a")
call New(exactLap, 1, planarMesh%particles%N, "exactLap", "n/a")
call New(lapError, 1, planarMesh%particles%N, "lapError", "n/a")
call New(est2ndPartials, 3, planarMesh%particles%N, "est2ndPartials", "n/a")
call New(exact2ndPartials, 3, planarMesh%particles%N, "exact2ndPartials", "n/a")
call New(partialErr, 3, planarMesh%particles%N, "partialErr", "n/a")
do i = 1, planarMesh%particles%N
xPhys = PhysCoord(planarMesh%particles, i)
call InsertScalarToField( scalar, Gaussian( xPhys(1:2), b))
call InsertVectorToField( exactGrad, GaussGrad( xPhys(1:2), b))
vecA = Gauss2ndDerivs( xPhys(1:2), b)
call InsertVectorToField( exact2ndPartials, vecA)
call InsertScalarToField( exactLap, GaussLap( xPhys(1:2), b))
enddo
call New(pseSetup, planarMesh, 2.0_kreal)
call PSEPlaneGradientAtParticles( pseSetup, planarMesh, scalar, estGrad, particlesMPI)
call PSEPlaneSecondPartialsAtParticles( pseSetup, planarMesh, estGrad, est2ndPartials, particlesMPI)
call PSEPlaneLaplacianAtParticles( pseSetup, planarMesh, scalar, estLap, particlesMPI)
do j = 1, nn
do i = 1, nn
exactScalar(i,j) = Gaussian([x(j), y(i)], b)
enddo
enddo
interpLoc = 0.0_kreal
do j = interpMPI%indexStart(procRank), interpMPI%indexEnd(procRank)
do i = 1, nn
!exactScalar(i,j) = Gaussian( [x(j),y(i)], b)
interpLoc(1) = x(j)
interpLoc(2) = y(i)
interpScalar(i,j) = PSEPlaneInterpolateScalar(pseSetup, planarMesh, scalar, interpLoc )
enddo
enddo
do j = 0, numProcs-1
call MPI_BCAST( interpScalar(:, interpMPI%indexStart(j):interpMPI%indexEnd(j)), nn * interpMPI%messageLength(j), &
MPI_DOUBLE_PRECISION, j, MPI_COMM_WORLD, mpiErrCode)
enddo
do i = 1, planarMesh%particles%N
vecA = [ estGrad%xComp(i), estGrad%yComp(i), 0.0_kreal]
vecB = [ exactGrad%xComp(i), exactGrad%yComp(i), 0.0_kreal]
call InsertScalarToField( gradError, sqrt(sum( (vecB-vecA)*(vecB-vecA))))
vecA = [ est2ndPartials%xComp(i), est2ndPartials%yComp(i), est2ndPartials%zComp(i)]
vecB = [ exact2ndPartials%xComp(i), exact2ndPartials%yComp(i), exact2ndPartials%zComp(i)]
call InsertVectorToField( partialErr, vecB - vecA )
call InsertScalarToField( lapError, estLap%scalar(i) - exactLap%scalar(i))
enddo
maxGradMag = MaxMagnitude(exactGrad)
meshSize(initNest+1) = MaxEdgeLength(planarMesh%edges, planarMesh%particles)
estGradError(initNest+1) = maxval(gradError%scalar)/maxGradMag
estLapError(initNest+1) = maxval(abs(lapError%scalar))/maxAbsLap
interpError(initNest+1) = maxval(abs(interpScalar-exactScalar))
if ( procRank == 0 ) then
write(logString,'(4A24)') "dx", "gradErr-particles", "lapErr-particles", "interp error"
call LogMessage(exeLog, TRACE_LOGGING_LEVEL, logkey, logString)
write(logString,'(4F24.10)') meshSize(initNest+1), estGradError(initNest+1), estLapError(initNest+1), interpError(initNest+1)
call LogMessage(exeLog, TRACE_LOGGING_LEVEL, logkey, logString)
if ( meshSeed == TRI_HEX_SEED ) then
write(filename, '(A,I1,A)') 'pseTest_triHex', initNest, '.m'
elseif ( meshSeed == QUAD_RECT_SEED ) then
write(filename, '(A,I1,A)') 'pseTest_quadRect', initNest, '.m'
endif
open(unit=WRITE_UNIT_1, file=filename, status='REPLACE', action='WRITE')
call WriteParticlesToMatlab( planarMesh%particles, WRITE_UNIT_1)
call WriteFieldToMatlab( scalar, WRITE_UNIT_1)
call WriteFieldToMatlab( estGrad, WRITE_UNIT_1)
call WriteFieldToMatlab( exactGrad, WRITE_UNIT_1)
call WriteFieldToMatlab( estLap, WRITE_UNIT_1)
call WriteFieldToMatlab( exactLap, WRITE_UNIT_1)
call WriteFieldToMatlab( gradError, WRITE_UNIT_1)
call WriteFieldToMatlab( lapError, WRITE_UNIT_1)
call WriteFieldToMatlab( est2ndPartials, WRITE_UNIT_1)
call WriteFieldToMatlab( exact2ndPartials, WRITE_UNIT_1)
call WriteFieldToMatlab( partialErr, WRITE_UNIT_1)
write(WRITE_UNIT_1,'(A)',advance='NO') "xi = ["
do i = 1, nn-1
write(WRITE_UNIT_1,'(F18.12,A)',advance='NO') x(i), ", "
enddo
write(WRITE_UNIT_1,'(F18.12,A)') x(nn), "];"
write(WRITE_UNIT_1,'(A)') "yi = xi;"
write(WRITE_UNIT_1,'(A)',advance='NO') "interp = ["
do i = 1, nn - 1
do j = 1, nn - 1
write(WRITE_UNIT_1,'(F18.12,A)',advance='NO') interpScalar(i,j), ", "
enddo
write(WRITE_UNIT_1,'(F18.12,A)') interpScalar(i,nn), "; ..."
enddo
do j = 1, nn - 1
write(WRITE_UNIT_1,'(F18.12,A)',advance='NO') interpScalar(nn,j), ", "
enddo
write(WRITE_UNIT_1,'(F18.12,A)') interpScalar(nn,nn), "];"
close(WRITE_UNIT_1)
endif
!call cpu_time(testEnd)
testEnd = MPI_WTIME()
if ( procRank == 0 ) then
write(logString,'(A,I8,A,F12.2,A)') "nParticles = ", planarMesh%particles%N, ": elapsed time = ", &
testEnd-testStart, " seconds."
call LogMessage(exelog, TRACE_LOGGING_LEVEL, logKey, logString)
endif
!
! cleanup
!
call Delete(particlesMPI)
call Delete(interpMPI)
call Delete(pseSetup)
! call Delete(est2ndPartials)
! call Delete(exact2ndPartials)
call Delete(partialErr)
call Delete(lapError)
call Delete(exactLap)
call Delete(estLap)
call Delete(gradError)
call Delete(exactGrad)
call Delete(estGrad)
call Delete(scalar)
call Delete(planarMesh)
enddo
if ( procRank == 0 ) then
write(6,'(4A24)') "dx", "gradErr-particles", "lapErr-particles", "interp error"
do i = 1, 9
write(6,'(4F24.10)') meshSize(i), estGradError(i), estLapError(i), interpError(i)
enddo
programEnd = MPI_WTIME()
write(6,'(A,F12.2,A)') "PROGRAM COMPLETE : elapsed time = ", programEnd - programStart, " seconds."
endif
call Delete(exeLog)
call MPI_Finalize(mpiErrCode)
contains
function Gaussian( xy, b )
real(kreal) :: Gaussian
real(kreal), intent(in) :: xy(2)
real(kreal), intent(in) :: b
Gaussian = exp( - b * b * ( (xy(1)-xc)*(xy(1)-xc) + (xy(2)-yc)*(xy(2)-yc)))
end function
function GaussGrad(xy, b)
real(kreal) :: GaussGrad(2)
real(kreal), intent(in) :: xy(2)
real(kreal), intent(in) :: b
GaussGrad(1) = xy(1)-xc
GaussGrad(2) = xy(2)-yc
GaussGrad = -2.0_kreal * GaussGrad * b * b * exp( - b * b * ( (xy(1)-xc)*(xy(1)-xc) + (xy(2)-yc)*(xy(2)-yc) ))
end function
function GaussLap(xy, b)
real(kreal) :: GaussLap
real(kreal), intent(in) :: xy(2)
real(kreal), intent(in) :: b
GaussLap = ( b*b * ( (xy(1)-xc)*(xy(1)-xc) + (xy(2)-yc)*(xy(2)-yc) ) - 1.0_kreal ) * 4.0_kreal * b * b * &
exp( - b * b * ( (xy(1)-xc)*(xy(1)-xc) + (xy(2)-yc)*(xy(2)-yc) ))
end function
function Gauss2ndDerivs( xy, b)
real(kreal) :: Gauss2ndDerivs(3)
real(kreal), intent(in) :: xy(2)
real(kreal), intent(in) :: b
Gauss2ndDerivs(1) = 2.0_kreal * b * b *(2.0_kreal * b*b * (xy(1)-xc)*(xy(1)-xc) - 1.0_kreal)
Gauss2ndDerivs(2) = 4.0_kreal * b**4 * (xy(1)-xc)*(xy(2)-yc)
Gauss2ndDerivs(3) = 2.0_kreal * b * b *(2.0_kreal * b*b * (xy(2)-yc)*(xy(2)-yc) - 1.0_kreal)
Gauss2ndDerivs = Gauss2ndDerivs * exp( - b * b * ( (xy(1)-xc)*(xy(1)-xc) + (xy(2)-yc)*(xy(2)-yc) ))
end function
subroutine InitLogger(aLog,rank)
! Initialize a logger for this processor
type(Logger), intent(out) :: aLog
integer(kint), intent(in) :: rank
write(logKey,'(A,A,I0.2,A)') trim(logKey),'_',rank,' : '
if ( rank == 0 ) then
call New(aLog,logLevel)
else
call New(aLog,ERROR_LOGGING_LEVEL)
endif
end subroutine
end program
|
Baby announcement etiquette - what do you think?
For me, not acceptable. We are simply not telling people until we are ready for the news to be public this time. MIL has proven herself unable to bite her tongue when it comes to sharing our special news.
My SIL did this to us when DD was born. I was raging then and it still upsets me when I think about it. I know she only did it because she was so excited for us but it's still totally unacceptable to me.
I hate the thought of it. My sister was really unwell after her bub was born (spent 2 nights in ICU) and I didn't mention anything on FB even though I was so proud and excited. I wasn't FB friends with my BIL at that time (he has general family issues, more with his but long story) and I ended up texting my sister a few days later to ask if there were anymore photos (they live interstate) and all mum dad and I had seen was one photo from immediately after the birth. BIL had made the announcement on FB when he was born and had been sharing all these photos with his friends, but none with us. I don't know what my sister had done, but she wasn't tagged in any of the announcements/photos so we were literally in the dark, so that sucked. I was happy I waited until I knew they had announced it, but also annoyed at the fact that more of the news/photos were shared amongst his friends only. I'd do the same again though. Not my baby, not my news.
This however is my biggest worry when we have babies. My MIL puts everything on Facebook, there is no filter. It's like there's no thought about whether appropriate or not. (Her breast cancer diagnosis was played out on Facebook. Basically the second she was off the phone with us telling us she had announced it on FB 😕) She will be someone I'm wary of and I shouldn't have to be.
My friend had her baby in July. Her best friend announced it. And people congratulated her before she got a word in. I asked her and she said she didn't mind. Evidently it depends on the parent.
But in my personal opinion. Not ok in any circumstances.
When I had DS1 my father put it on Facebook within minutes of me calling. That's how my BFF (babies godmother) found out. I was planning on calling her within an hour or so when we had decided bubs name. I was furious.
With ds2 my BFF received the first phone call and my father the last. People were told "we're holding off posting in Facebook until we confirm bubs name."
It happened to us and I was so upset. We had a beautifully worded announcement ready that was spoilt by a family member jumping the gun. This family member had my phone number so could have text a congrats. I deleted the msg as soon as I saw it but a few people had already responded.
We wanted to wait till the next day to Facebook announce so we could enjoy the special time to ourselves for a while.
I think it's so rude.
Yeah it wouldn't really bother me. I know some people actually disable their account from a week out from their due date so they aren't bombarded and can concentrate on the impending birth.
Slightly different but my MIL announced when we found out I was pregnant on Facebook. I was only 10 weeks, so I was really annoyed!
It was our news to share and she took that away from us. Half my immediate family didn't know so I was annoyed.
Etiquette in baby change rooms! |
lemma higher_deriv_const [simp]: "(deriv ^^ n) (\<lambda>w. c) = (\<lambda>w. if n=0 then c else 0)" |
# Template for implementing an invertible neural network layer and its logdet.
# We will take an affine layer as an example to explain all necessary steps.
# The affine layer is defined as:
#
# Y = f(X) = S .* X .+ B
#
# Here, X is the 4D input tensor of dimensions (nx, ny, num_channel, batchsize).
# S and B are a scaling and bias term, both with dimensions (nx, ny, num_channel).
#
# The trainable parameters of this layer are S, B. The input is X and the output is Y.
#
# You need to expoert whichever functions you want to be able to access
export AffineLayer
# This immutable structure defines our network layer. The structure contains the
# parameters of our layer (in this case S and B) or any other building blocks that
# you want to use in your layer (for example 1x1 convolutions). However, in this
# case we only have parameters S and B.
struct AffineLayer <: NeuralNetLayer
S::Parameter # trainable parameters are defined as Parameters.
B::Parameter # both S and B have two fields: S.data and S.grad
logdet::Bool # bool to indicate whether you want to compute the logdet
end
# Functor the layer for gpu/cpu offloading
@Flux.functor AffineLayer
# The constructor builds and returns a new network layer for given input dimensions.
function AffineLayer(nx, ny, nc; logdet=false)
# Create S and B
S = Parameter(glorot_uniform(nx, ny, nc)) # initiliaze S with random values and make it a parameter
B = Parameter(zeros(Float32, nx, ny, nc)) # initilize B with zeros and make it a parameter
# Build an affine layer
return AffineLayer(S, B, logdet)
end
# Foward pass: Input X, Output Y
# The forward pass for the affine layer is:
# Y = X .* S .+ B
function forward(X::AbstractArray{T, N}, AL::AffineLayer) where {T, N}
Y = X .* AL.S.data .+ AL.B.data # S and B are Parameters, so access their values via the .data field
# If logdet is true, also compute the logdet and return it as a second output argument.
# Otherwise only return Y.
if AL.logdet == true
return Y, logdet_forward(S)
else
return Y
end
end
# Inverse pass: Input Y, Output X
# The inverse pass for our affine layer is:
# X = (Y .- B) ./ S
# To avoid division by zero, we add numerical noise to S in the division.
function inverse(Y::AbstractArray{T, N}, AL::AffineLayer) where {T, N}
X = (Y .- AL.B.data) ./ (AL.S.data .+ eps(T)) # avoid division by 0
return X
end
# Backward pass: Input (ΔY, Y), Output (ΔY, Y)
# Assuming that the layer is invertible, the backward function takes
# 2 input arguments: the data residual ΔY and the original output Y.
# The first step is to recompute the original input X by calling the
# inverse function on Y. If the layer is not invertible, this layer
# needs X as an input instead of Y.
# Second of all, we compute the partial derivatives of our layer
# with respect to X, S, and B:
# ΔX = S .* ΔY (corresponds to df/dX * dY)
# ΔS = X .* ΔY (corresponds to df/dS * dY)
# ΔB = 1 .* ΔY (corresponds to df/dB * dY)
function backward(ΔY::AbstractArray{T, N}, Y::AbstractArray{T, N}, AL::AffineLayer) where {T, N}
nx, ny, n_in, batchsize = size(Y)
# Recompute X from Y
X = inverse(Y, AL)
# Gradient w.r.t. X
ΔX = ΔY .* AL.S.data
# Gradient w.r.t. S (sum over the batchsize, as S is only a 3D tensor)
ΔS = sum(ΔY .* X, dims=4)[:,:,:,1]
# If the logdet is computed, in the forward pass, also compute the gradient of the
# logdet term and subtract from S (assuming that the logdet term is subtracted in the
# objective function)
AL.logdet == true && (ΔS -= logdet_backward(S))
# Gradient w.r.t. B (sum over the batchsize)
ΔB = sum(ΔY, dims=4)[:,:,:,1]
# Set the gradient fields of the parameters S and B
AL.S.grad = ΔS
AL.B.grad = ΔB
# Return the backpropagated data residual and the re-computed X
return ΔX, X
end
# For optimization, we need a function that clears all the gradients.
# I.e. we set the .grad fields of all parameters to nothing.
function clear_grad!(AL::AffineLayer)
AL.S.grad = nothing
AL.B.grad = nothing
end
# Also we define a get_params function that returns an array of all
# the parameters. In this case, our parameters are S and B
get_params(AL::AffineLayer) = [AL.S, AL.B]
# Function for the logdet and for computing the gradient of the logdet.
# For our affine layer consisting of an element-wise multiplication of S
# and X, the Jacobian is given by S, and the logdet is the sum of the logarithm
# of the (absolute) values.
logdet_forward(S) = sum(log.(abs.(S.data)))
# The gradient of the forward logdet function is given by 1/S
logdet_backward(S) = 1f0 ./ S.data
|
module Eval
-- Evaluators for terms in the simply-typed
-- lambda calculus.
import BigStep
import Equivalence
import Determinism
import Progress
import Step
import Subst
import Term
%access export
------------------------------------------------------------
-- Begin: EVALUATOR (FORMALLY) BASED ON SMALL-STEP SEMANTICS
eval : (e : Term [] t) -> (e' : Term [] t ** (Value e', TransStep e e'))
eval e = case progress e of
Left v => (e ** (v, TStRefl e))
Right (e' ** s') => let (e'' ** (v'', s'')) = eval e'
in (e'' ** (v'', TStTrans s' s''))
-- End: EVALUATOR (FORMALLY) BASED ON SMALL-STEP SEMANTICS
----------------------------------------------------------
----------------------------------------------------------
-- Begin: EVALUATOR INFORMALLY BASED ON BIG-STEP SEMANTICS
eval' : Term [] t -> Term [] t
eval' (TVar _) impossible
eval' (TAbs e) = TAbs e
eval' (TApp e1 e2) = let (TAbs e1v) = eval' e1
e2v = eval' e2
in eval' $ subst e2v First e1v
eval' (TFix e) = let (TAbs ev) = eval' e
in eval' $ subst (TFix (TAbs ev)) First ev
eval' TZero = TZero
eval' (TSucc e) = TSucc (eval' e)
eval' (TPred e) = case eval' e of
TZero => TZero
TSucc ev' => ev'
eval' (TIfz e1 e2 e3) = case eval' e1 of
TZero => eval' e2
TSucc _ => eval' e3
-- End: EVALUATOR INFORMALLY BASED ON BIG-STEP SEMANTICS
--------------------------------------------------------
--------------------------------------------------------
-- Begin: EVALUATOR FORMALLY BASED ON BIG-STEP SEMANTICS
evalBigStep : (e : Term [] t) -> (e' : Term [] t ** (Value e', BigStep e e'))
evalBigStep (TVar _) impossible
evalBigStep (TAbs x) = (TAbs x ** (VAbs, BStValue VAbs))
evalBigStep (TApp x y) = case evalBigStep x of
(_ ** (VZero, _)) impossible
(_ ** (VSucc _, _)) impossible
(TAbs ex ** (VAbs, bStx)) => let (ey ** (_ , bSty)) = evalBigStep y
(er ** (vr, bStr)) = evalBigStep (subst ey First ex)
in (er ** (vr, BStApp bStx bSty bStr))
evalBigStep (TFix x) = case evalBigStep x of
(_ ** (VZero, _)) impossible
(_ ** (VSucc _, _)) impossible
(TAbs ex ** (VAbs, bStx)) => let (er ** (vr, bStr)) = evalBigStep (subst (TFix (TAbs ex)) First ex)
in (er ** (vr, BStFix bStx bStr))
evalBigStep TZero = (TZero ** (VZero, BStValue VZero))
evalBigStep (TSucc x) = let (ex ** (vx, bStx)) = evalBigStep x
in (TSucc ex ** (VSucc vx, BStSucc bStx))
evalBigStep (TPred x) = case evalBigStep x of
(TZero ** (_, bStx)) => (TZero ** (VZero, BStPredZero bStx))
(TSucc ex ** (VSucc vx, bStx)) => (ex ** (vx, BStPredSucc bStx))
(_ ** (VAbs, _)) impossible
evalBigStep (TIfz x y z) = case evalBigStep x of
(TZero ** (_, bStx)) => let (ey ** (vy, bSty)) = evalBigStep y
in (ey ** (vy, BStIfzZero bStx bSty))
(TSucc ex ** (VSucc vx, bStx)) => let (ez ** (vz, bStz)) = evalBigStep z
in (ez ** (vz, BStIfzSucc bStx bStz))
(_ ** (VAbs, _)) impossible
-- End: EVALUATOR FORMALLY BASED ON BIG-STEP SEMANTICS
------------------------------------------------------
-----------------------------------
-- Begin: EQUIVALENCE OF EVALUATORS
total equivEval : (eval e1) = (e2 ** (v2, tst2)) ->
(evalBigStep e1) = (e3 ** (v3, bSt3)) ->
e2 = e3
equivEval {v2 = v2} {tst2 = tst2} {bSt3 = bSt3} _ _ =
let (tst3, v3) = bigStepToTransStep bSt3
in transStepDeterministic v2 tst2 v3 tst3
-- End: EQUIVALENCE OF EVALUATORS
---------------------------------
|
lemma succ_add (a b : mynat) : succ a + b = succ (a + b) :=
begin
induction b with c hc,
rw add_zero,
rw add_zero,
refl,
rw add_succ,
rw add_succ,
rw hc,
refl,
end
|
using BayesTests
using Base.Test
binomBF = BinomTest(1, 1)
samples = posterior(binomBF; iter = 10000)
credible = hpd(samples)
@test binomBF.BF == 1.0
@test_approx_eq_eps credible[1] .167 .1
@test_approx_eq_eps credible[2] .986 .1
update(binomBF, 3, 3)
corBF = CorrelationTest(1, 1; a = 1)
corBF2 = CorrelationTest(3, 1; a = 1)
@test isnan(corBF.BF)
@test !isnan(corBF2.BF)
x1 = collect(1:10)
x2 = collect(11:20)
ttestBF = TTest(x1, x2)
update(ttestBF, x1, x2)
ttestBF = TTest(x1, x2; typ = :twosample)
update(ttestBF, x1, x2)
|
//
// Created by L. Jonathan Feldstein
//
#ifndef CIMPLE_CIMPLE_CONTROLLER_H
#define CIMPLE_CIMPLE_CONTROLLER_H
#include <stddef.h>
#include <math.h>
#include "cimple_system.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include "cimple_polytope_library.h"
#include <pthread.h>
#include "cimple_mpc_computation.h"
/**
* @brief Action to get plant from current abstract state to target_abs_state.
*
* @param target target region the plant is supposed to reach
* @param now current state of the plant
* @param d_dyn discrete abstraction of the system
* @param s_dyn system dynamics including auxiliary matrices
* @param f_cost cost function to be minimized on the path
*/
void ACT(int target,
current_state * now,
discrete_dynamics * d_dyn,
system_dynamics * s_dyn,
cost_function * f_cost,
double sec);
/**
* @brief Apply the calculated control to the current state using system dynamics
* @param x current state at time [0]
* @param u matrix with next N inputs calculated by the MPC controller
* @param A system dynamics
* @param B input dynamics
*/
void apply_control(gsl_vector *x,
gsl_vector *u,
gsl_matrix *A,
gsl_matrix *B,
gsl_matrix *E,
gsl_vector *w,
size_t current_time);
/**
* Fill a vector with gaussian distributed noise
* @param w
*/
void simulate_disturbance(gsl_vector *w,
double mu,
double sigma);
void * main_computation(void *arg);
#endif //CIMPLE_CIMPLE_CONTROLLER_H
|
[STATEMENT]
lemma eq_mod_iff: "0 < n \<Longrightarrow> b = b mod n \<longleftrightarrow> 0 \<le> b \<and> b < n"
for b n :: int
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 0 < n \<Longrightarrow> (b = b mod n) = (0 \<le> b \<and> b < n)
[PROOF STEP]
using pos_mod_sign [of n b] pos_mod_bound [of n b]
[PROOF STATE]
proof (prove)
using this:
0 < n \<Longrightarrow> 0 \<le> b mod n
0 < n \<Longrightarrow> b mod n < n
goal (1 subgoal):
1. 0 < n \<Longrightarrow> (b = b mod n) = (0 \<le> b \<and> b < n)
[PROOF STEP]
by (safe, auto) |
flavor 1
func &ciori32 (
var %i i32, var %j i32, var %k i32
) i32 {
if (cior i32 ( cior i32(dread i32 %i, dread i32 %j), dread i32 %k)) {
return (constval i32 1)
}
return (
cior i32(dread i32 %i, dread i32 %j))}
func &candi64 (
var %i i64, var %j i64, var %k i64
) i32 {
if (cand i32 (cand i32(dread i32 %i, dread i32 %j), dread i32 %k)) {
return (constval i32 1)
}
return (
cand i64(dread i64 %i, dread i64 %j))}
# EXEC: %irbuild Main.mpl
# EXEC: %irbuild Main.irb.mpl
# EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
|
/**
*
* @file core_zpemv.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Dulceneia Becker
* @date 2011-06-29
* @precisions normal z -> c d s
*
**/
#include <cblas.h>
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex64_t
*
* CORE_zpemv performs one of the matrix-vector operations
*
* y = alpha*op( A )*x + beta*y
*
* where op( A ) is one of
*
* op( A ) = A or op( A ) = A**T or op( A ) = A**H,
*
* alpha and beta are scalars, x and y are vectors and A is a
* pentagonal matrix (see further details).
*
*
* Arguments
* ==========
*
* @param[in] storev
*
* @arg PlasmaColumnwise : array A stored columwise
* @arg PlasmaRowwise : array A stored rowwise
*
* @param[in] trans
*
* @arg PlasmaNoTrans : y := alpha*A*x + beta*y.
* @arg PlasmaTrans : y := alpha*A**T*x + beta*y.
* @arg PlasmaConjTrans : y := alpha*A**H*x + beta*y.
*
* @param[in] M
* Number of rows of the matrix A.
* M must be at least zero.
*
* @param[in] N
* Number of columns of the matrix A.
* N must be at least zero.
*
* @param[in] L
* Order of triangle within the matrix A (L specifies the shape
* of the matrix A; see further details).
*
* @param[in] ALPHA
* Scalar alpha.
*
* @param[in] A
* Array of size LDA-by-N. On entry, the leading M by N part
* of the array A must contain the matrix of coefficients.
*
* @param[in] LDA
* Leading dimension of array A.
*
* @param[in] X
* On entry, the incremented array X must contain the vector x.
*
* @param[in] INCX
* Increment for the elements of X. INCX must not be zero.
*
* @param[in] BETA
* Scalar beta.
*
* @param[in,out] Y
* On entry, the incremented array Y must contain the vector y.
*
* @param[out] INCY
* Increment for the elements of Y. INCY must not be zero.
*
* @param[out] WORK
* Workspace array of size at least L.
*
* Further Details
* ===============
*
* | N |
* _ ___________ _
* | |
* A: | |
* M-L | |
* | | M
* _ |..... |
* \ : |
* L \ : |
* _ \:_____| _
*
* | L | N-L |
*
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zpemv = PCORE_zpemv
#define CORE_zpemv PCORE_zpemv
#endif
int CORE_zpemv(PLASMA_enum trans, int storev,
int M, int N, int L,
PLASMA_Complex64_t ALPHA,
const PLASMA_Complex64_t *A, int LDA,
const PLASMA_Complex64_t *X, int INCX,
PLASMA_Complex64_t BETA,
PLASMA_Complex64_t *Y, int INCY,
PLASMA_Complex64_t *WORK)
{
/*
* y = alpha * op(A) * x + beta * y
*/
int K;
static PLASMA_Complex64_t zzero = 0.0;
/* Check input arguments */
if ((trans != PlasmaNoTrans) && (trans != PlasmaTrans) && (trans != PlasmaConjTrans)) {
coreblas_error(1, "Illegal value of trans");
return -1;
}
if ((storev != PlasmaColumnwise) && (storev != PlasmaRowwise)) {
coreblas_error(2, "Illegal value of storev");
return -2;
}
if (!( ((storev == PlasmaColumnwise) && (trans != PlasmaNoTrans)) ||
((storev == PlasmaRowwise) && (trans == PlasmaNoTrans)) )) {
coreblas_error(2, "Illegal values of trans/storev");
return -2;
}
if (M < 0) {
coreblas_error(3, "Illegal value of M");
return -3;
}
if (N < 0) {
coreblas_error(4, "Illegal value of N");
return -4;
}
if (L > min(M ,N)) {
coreblas_error(5, "Illegal value of L");
return -5;
}
if (LDA < max(1,M)) {
coreblas_error(8, "Illegal value of LDA");
return -8;
}
if (INCX < 1) {
coreblas_error(10, "Illegal value of INCX");
return -10;
}
if (INCY < 1) {
coreblas_error(13, "Illegal value of INCY");
return -13;
}
/* Quick return */
if ((M == 0) || (N == 0))
return PLASMA_SUCCESS;
if ((ALPHA == zzero) && (BETA == zzero))
return PLASMA_SUCCESS;
/* If L < 2, there is no triangular part */
if (L == 1) L = 0;
/* Columnwise */
if (storev == PlasmaColumnwise) {
/*
* ______________
* | | | A1: A[ 0 ]
* | | | A2: A[ M-L ]
* | A1 | | A3: A[ (N-L) * LDA ]
* | | |
* |______| A3 |
* \ | |
* \ A2 | |
* \ | |
* \|_____|
*
*/
/* Columnwise / NoTrans */
if (trans == PlasmaNoTrans) {
coreblas_error(1, "The case PlasmaNoTrans / PlasmaColumnwise is not yet implemented");
return -1;
}
/* Columnwise / [Conj]Trans */
else {
/* L top rows of y */
if (L > 0) {
/* w = A_2' * x_2 */
cblas_zcopy(
L, &X[INCX*(M-L)], INCX, WORK, 1);
cblas_ztrmv(
CblasColMajor, (CBLAS_UPLO)PlasmaUpper,
(CBLAS_TRANSPOSE)trans,
(CBLAS_DIAG)PlasmaNonUnit,
L, &A[M-L], LDA, WORK, 1);
if (M > L) {
/* y_1 = beta * y_1 [ + alpha * A_1 * x_1 ] */
cblas_zgemv(
CblasColMajor, (CBLAS_TRANSPOSE)trans,
M-L, L, CBLAS_SADDR(ALPHA), A, LDA,
X, INCX, CBLAS_SADDR(BETA), Y, INCY);
/* y_1 = y_1 + alpha * w */
cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY);
} else {
/* y_1 = y_1 + alpha * w */
if (BETA == zzero) {
cblas_zscal(L, CBLAS_SADDR(ALPHA), WORK, 1);
cblas_zcopy(L, WORK, 1, Y, INCY);
} else {
cblas_zscal(L, CBLAS_SADDR(BETA), Y, INCY);
cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY);
}
}
}
/* N-L bottom rows of Y */
if (N > L) {
K = N - L;
cblas_zgemv(
CblasColMajor, (CBLAS_TRANSPOSE)trans,
M, K, CBLAS_SADDR(ALPHA), &A[LDA*L], LDA,
X, INCX, CBLAS_SADDR(BETA), &Y[INCY*L], INCY);
}
}
}
/* Rowwise */
else {
/*
* --------------
* | | \ A1: A[ 0 ]
* | A1 | \ A2: A[ (N-L) * LDA ]
* | | A2 \ A3: A[ L ]
* |--------------------\
* | A3 |
* ----------------------
*
*/
/* Rowwise / NoTrans */
if (trans == PlasmaNoTrans) {
/* L top rows of A and y */
if (L > 0) {
/* w = A_2 * x_2 */
cblas_zcopy(
L, &X[INCX*(N-L)], INCX, WORK, 1);
cblas_ztrmv(
CblasColMajor, (CBLAS_UPLO)PlasmaLower,
(CBLAS_TRANSPOSE)PlasmaNoTrans,
(CBLAS_DIAG)PlasmaNonUnit,
L, &A[LDA*(N-L)], LDA, WORK, 1);
if (N > L) {
/* y_1 = beta * y_1 [ + alpha * A_1 * x_1 ] */
cblas_zgemv(
CblasColMajor, (CBLAS_TRANSPOSE)PlasmaNoTrans,
L, N-L, CBLAS_SADDR(ALPHA), A, LDA,
X, INCX, CBLAS_SADDR(BETA), Y, INCY);
/* y_1 = y_1 + alpha * w */
cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY);
} else {
/* y_1 = y_1 + alpha * w */
if (BETA == zzero) {
cblas_zscal(L, CBLAS_SADDR(ALPHA), WORK, 1);
cblas_zcopy(L, WORK, 1, Y, INCY);
} else {
cblas_zscal(L, CBLAS_SADDR(BETA), Y, INCY);
cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY);
}
}
}
/* M-L bottom rows of Y */
if (M > L) {
cblas_zgemv(
CblasColMajor, (CBLAS_TRANSPOSE)PlasmaNoTrans,
M-L, N, CBLAS_SADDR(ALPHA), &A[L], LDA,
X, INCX, CBLAS_SADDR(BETA), &Y[INCY*L], INCY);
}
}
/* Rowwise / [Conj]Trans */
else {
coreblas_error(1, "The case Plasma[Conj]Trans / PlasmaRowwise is not yet implemented");
return -1;
}
}
return PLASMA_SUCCESS;
}
|
#=
Motivation:
From GoF book, a class TCPConnection responds different to requests
depending on its current state of Established, Listening, or Closed.
=#
module StateExample
export LISTENING, ESTABLISHED, CLOSED
abstract type AbstractState end
struct ListeningState <: AbstractState end
struct EstablishedState <: AbstractState end
struct ClosedState <: AbstractState end
const LISTENING = ListeningState()
const ESTABLISHED = EstablishedState()
const CLOSED = ClosedState()
"""
A Connection object contains the current `state` and a reference
to a connection `conn`
"""
struct Connection{T <: AbstractState,S}
state::T
conn::S
end
# Use multiple dispatch
send(c::Connection, msg) = send(c.state, c.conn, msg)
# Implement `send` method for each state
send(::ListeningState, conn, msg) = error("No connection yet")
send(::EstablishedState, conn, msg) = write(conn, msg * "\n")
send(::ClosedState, conn, msg) = error("Connection already closed")
# test functions
function test(state, msg)
c = Connection(state, stdout)
try
send(c, msg)
catch ex
println("$(ex) for message '$msg'")
end
return nothing
end
function test()
test(LISTENING, "hello world 1")
test(CLOSED, "hello world 2")
test(ESTABLISHED, "hello world 3")
end
end #module
using .StateExample
StateExample.test()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.