text
stringlengths 0
3.34M
|
---|
lemma open_Int_closure_eq_empty: "open S \<Longrightarrow> (S \<inter> closure T) = {} \<longleftrightarrow> S \<inter> T = {}"
|
library(digest)
resultCode = 0
getColumnMap = function() {
map = list(
table=NULL,
columns=list(
login="login",
password="password",
enabled="enabled"
)
)
if(userBankType == "table") {
map = fromJSON(userBankTable)
}
return(map)
}
getUserByLogin = function(login, columnMap) {
if(userBankType == "direct") {
userList = fromJSON(userBankList)
if(length(userList) == 0) {
resultCode <<- 1
return(NULL)
}
for(i in 1:length(userList)) {
user = userList[[i]]
if(user$login == login && user$enabled == 1) {
return(user)
}
}
resultCode <<- 1
return(NULL)
} else {
sql = "
SELECT *
FROM {{table}}
WHERE
{{loginColumn}}='{{login}}'
AND {{enabledColumn}}=1
"
user = concerto.table.query(sql, params=list(
table=columnMap$table,
loginColumn=columnMap$columns$login,
enabledColumn=columnMap$columns$enabled,
login=login
))
if(dim(user)[1] == 0) {
resultCode <<- 1
return(NULL)
}
return(as.list(user[1,]))
}
}
checkPassword = function(rawPassword, encryptedPassword, encryption) {
if(is.na(encryptedPassword) || encryptedPassword == "") { return(T) }
if(is.na(rawPassword)) { return(F) }
if(encryption=="plain") {
return(rawPassword == encryptedPassword)
}
return(digest(rawPassword, encryption, serialize=F) == encryptedPassword)
}
authorizeUser = function(login, password, columnMap) {
user = getUserByLogin(login, columnMap)
concerto.log(login, "login checked")
concerto.log(password, "password checked")
concerto.log(user, "user checked for password")
if(!is.null(user) && checkPassword(password, user[[columnMap$columns$password]], userBankEncryption)) {
return(user)
}
resultCode <<- 1
return(NULL)
}
columnMap = getColumnMap()
user = authorizeUser(login, password, columnMap)
if(is.null(user)) {
concerto.log(paste0("user ",login," unauthorized"), title="authorization result")
.branch = "unauthorized"
} else {
concerto.log(paste0("user ",login," authorized"), title="authorization result")
.branch = "authorized"
}
|
function [params, names] = rbfwhiteKernExtractParam(kern)
% RBFWHITEKERNEXTRACTPARAM Extract parameters from the RBF-WHITE kernel
% structure.
% FORMAT
% DESC extracts parameters from the RBF-WHITE kernel structure into a vector
% of parameters for optimisation.
% ARG kern : the kernel structure containing the parameters to be
% extracted.
% RETURN param : vector of parameters extracted from the kernel. If
% the field 'transforms' is not empty in the kernel structure, the
% parameters will be transformed before optimisation (for example
% positive only parameters could be logged before being returned).
%
% FORMAT
% DESC extracts parameters and parameter names from the RBF-WHITE kernel
% structure.
% ARG kern : the kernel structure containing the parameters to be
% extracted.
% RETURN param : vector of parameters extracted from the kernel. If the
% field 'transforms' is not empty in the kernel structure, the parameters
% will be transformed before optimisation (for example positive only
% parameters could be logged before being returned).
% RETURN names : cell array of strings containing names for each
% parameter.
%
% SEEALSO rbfwhiteKernParamInit, rbfwhiteKernExpandParam, kernExtractParam,
% scg, conjgrad
%
% COPYRIGHT : David Luengo, 2009
%
% KERN
params = [kern.inverseWidth kern.variance];
if nargout > 1
names = {'inverse width', 'variance'};
end
|
{-# OPTIONS --without-K --exact-split --rewriting #-}
module index where
-- An organised list of modules:
import Pi.Everything
-- An exhaustive list of all modules:
|
Require Import VST.floyd.proofauto.
Require Import sha.SHA256.
Require Import sha.spec_sha.
Require Import sha.sha.
Require Export sha.pure_lemmas.
Require Export sha.general_lemmas.
Export ListNotations.
Local Open Scope logic.
Global Opaque K256.
Transparent peq.
Lemma mapsto_tc_val:
forall sh t p v,
readable_share sh ->
v <> Vundef ->
mapsto sh t p v = !! tc_val t v && mapsto sh t p v .
Proof.
intros.
apply pred_ext; [ | normalize].
apply andp_right; auto.
unfold mapsto; simpl.
destruct (access_mode t); try apply FF_left.
destruct (attr_volatile (attr_of_type t)); try apply FF_left.
destruct p; try apply FF_left.
if_tac; try contradiction. apply orp_left.
normalize.
normalize.
Qed.
Fixpoint loops (s: statement) : list statement :=
match s with
| Ssequence a b => loops a ++ loops b
| Sloop _ _ => [s]
| Sifthenelse _ a b => loops a ++ loops b
| _ => nil
end.
Lemma nth_big_endian_integer:
forall i bl w,
nth_error bl i = Some w ->
w = big_endian_integer
(sublist (Z.of_nat i * WORD)
(Z.succ (Z.of_nat i) * WORD)
(map Int.repr (intlist_to_Zlist bl))).
Proof.
induction i; destruct bl; intros; inv H.
*
unfold sublist; simpl.
rewrite big_endian_integer4.
repeat rewrite Int.repr_unsigned.
assert (Int.zwordsize=32)%Z by reflexivity.
unfold Z_to_Int, Shr; simpl.
change 255%Z with (Z.ones 8).
apply Int.same_bits_eq; intros;
autorewrite with testbit.
if_tac; simpl.
if_tac; simpl.
if_tac; simpl; autorewrite with testbit. auto. f_equal; omega.
rewrite if_false by omega. autorewrite with testbit. f_equal; omega.
rewrite if_false by omega. rewrite if_false by omega.
autorewrite with testbit. f_equal; omega.
*
specialize (IHi _ _ H1); clear H1.
simpl map.
rewrite IHi.
unfold sublist.
replace (Z.to_nat (Z.of_nat (S i) * WORD)) with (4 + Z.to_nat (Z.of_nat i * WORD))%nat
by (rewrite plus_comm, inj_S; unfold Z.succ; rewrite Z.mul_add_distr_r;
rewrite Z2Nat.inj_add by (change WORD with 4; omega); reflexivity).
rewrite <- skipn_skipn.
simpl skipn.
f_equal. f_equal. f_equal. rewrite inj_S. unfold Z.succ.
rewrite !Z.mul_add_distr_r; omega.
Qed.
Lemma Znth_big_endian_integer:
forall i bl,
0 <= i < Zlength bl ->
Znth i bl Int.zero =
big_endian_integer
(sublist (i * WORD) (Z.succ i * WORD)
(map Int.repr (intlist_to_Zlist bl))).
Proof.
intros.
unfold Znth.
rewrite if_false by omega.
pose proof (nth_error_nth _ Int.zero (Z.to_nat i) bl).
rewrite <- (Z2Nat.id i) at 2 3 by omega.
apply nth_big_endian_integer.
apply H0.
apply Nat2Z.inj_lt.
rewrite Z2Nat.id by omega.
rewrite <- Zlength_correct; omega.
Qed.
Fixpoint sequence (cs: list statement) s :=
match cs with
| nil => s
| c::cs' => Ssequence c (sequence cs' s)
end.
Fixpoint rsequence (cs: list statement) s :=
match cs with
| nil => s
| c::cs' => Ssequence (rsequence cs' s) c
end.
Lemma sequence_rsequence:
forall Espec CS Delta P cs s0 s R,
@semax CS Espec Delta P (Ssequence s0 (sequence cs s)) R <->
@semax CS Espec Delta P (Ssequence (rsequence (rev cs) s0) s) R.
Proof.
intros.
revert Delta P R s0 s; induction cs; intros.
simpl. apply iff_refl.
simpl.
rewrite seq_assoc.
rewrite IHcs; clear IHcs.
replace (rsequence (rev cs ++ [a]) s0) with
(rsequence (rev cs) (Ssequence s0 a)); [apply iff_refl | ].
revert s0 a; induction (rev cs); simpl; intros; auto.
rewrite IHl. auto.
Qed.
Lemma seq_assocN:
forall {Espec: OracleKind} CS,
forall Q Delta P cs s R,
@semax CS Espec Delta P (sequence cs Sskip) (normal_ret_assert Q) ->
@semax CS Espec
(update_tycon Delta (sequence cs Sskip)) Q s R ->
@semax CS Espec Delta P (sequence cs s) R.
Proof.
intros.
rewrite semax_skip_seq.
rewrite sequence_rsequence.
rewrite semax_skip_seq in H.
rewrite sequence_rsequence in H.
rewrite <- semax_seq_skip in H.
eapply semax_seq'; [apply H | ].
eapply semax_extensionality_Delta; try apply H0.
clear.
revert Delta; induction cs; simpl; intros.
apply tycontext_sub_refl.
eapply tycontext_sub_trans; [apply IHcs | ].
clear.
revert Delta; induction (rev cs); simpl; intros.
apply tycontext_sub_refl.
apply update_tycon_sub.
apply IHl.
Qed.
Fixpoint sequenceN (n: nat) (s: statement) : list statement :=
match n, s with
| S n', Ssequence a s' => a::sequenceN n' s'
| _, _ => nil
end.
Lemma data_block_local_facts:
forall {cs: compspecs} sh f data,
data_block sh f data |--
prop (field_compatible (tarray tuchar (Zlength f)) [] data
/\ Forall isbyteZ f).
Proof.
intros. unfold data_block, array_at.
simpl.
entailer.
Qed.
Hint Resolve @data_block_local_facts : saturate_local.
Require Import JMeq.
Lemma reptype_tarray {cs: compspecs}:
forall t len, reptype (tarray t len) = list (reptype t).
Proof.
intros.
rewrite reptype_eq. simpl. reflexivity.
Qed.
Local Open Scope nat.
(*** Application of Omega stuff ***)
Lemma CBLOCKz_eq : CBLOCKz = 64%Z.
Proof. reflexivity. Qed.
Lemma LBLOCKz_eq : LBLOCKz = 16%Z.
Proof. reflexivity. Qed.
Ltac helper2 :=
match goal with
| |- context [CBLOCK] => add_nonredundant (CBLOCK_eq)
| |- context [LBLOCK] => add_nonredundant (LBLOCK_eq)
| |- context [CBLOCKz] => add_nonredundant (CBLOCKz_eq)
| |- context [LBLOCKz] => add_nonredundant (LBLOCKz_eq)
| H: context [CBLOCK] |- _ => add_nonredundant (CBLOCK_eq)
| H: context [LBLOCK] |- _ => add_nonredundant (LBLOCK_eq)
| H: context [CBLOCKz] |- _ => add_nonredundant (CBLOCKz_eq)
| H: context [LBLOCKz] |- _ => add_nonredundant (LBLOCKz_eq)
end.
Ltac Omega1 := Omega (helper1 || helper2).
Ltac MyOmega :=
rewrite ?length_list_repeat, ?skipn_length, ?map_length,
?Zlength_map, ?Zlength_nil;
pose proof CBLOCK_eq;
pose proof CBLOCKz_eq;
pose proof LBLOCK_eq;
pose proof LBLOCKz_eq;
Omega1.
(*** End Omega stuff ***)
Local Open Scope Z.
Local Open Scope logic.
Lemma data_block_valid_pointer {cs: compspecs} sh l p: sepalg.nonidentity sh -> Zlength l > 0 ->
data_block sh l p |-- valid_pointer p.
Proof. unfold data_block. simpl; intros.
apply andp_valid_pointer2. apply data_at_valid_ptr; auto; simpl.
rewrite Z.max_r, Z.mul_1_l; omega.
Qed.
Lemma data_block_isbyteZ {cs: compspecs}:
forall sh data v, data_block sh data v = !! Forall isbyteZ data && data_block sh data v.
Proof.
unfold data_block; intros.
simpl.
normalize.
f_equal. f_equal. apply prop_ext. intuition.
Qed.
Lemma sizeof_tarray_tuchar:
forall (n:Z), (n>=0)%Z -> (sizeof (tarray tuchar n) = n)%Z.
Proof. intros.
unfold sizeof,tarray; cbv beta iota.
rewrite Z.max_r by omega.
unfold alignof, tuchar; cbv beta iota.
rewrite Z.mul_1_l. auto.
Qed.
Lemma isbyte_value_fits_tuchar:
forall x, isbyteZ x -> value_fits tuchar (Vint (Int.repr x)).
Proof.
intros. hnf in H|-*; intros.
simpl. rewrite Int.unsigned_repr by rep_omega.
change Byte.max_unsigned with 255%Z. omega.
Qed.
Lemma Zlength_Zlist_to_intlist:
forall (n:Z) (l: list Z),
(Zlength l = WORD*n)%Z -> Zlength (Zlist_to_intlist l) = n.
Proof.
intros.
rewrite Zlength_correct in *.
assert (0 <= n)%Z by ( change WORD with 4%Z in H; omega).
rewrite (length_Zlist_to_intlist (Z.to_nat n)).
apply Z2Nat.id; auto.
apply Nat2Z.inj. rewrite H.
rewrite Nat2Z.inj_mul.
f_equal. rewrite Z2Nat.id; omega.
Qed.
Lemma nth_intlist_to_Zlist_eq:
forall d (n i j k: nat) al, (i < n)%nat -> (i < j*4)%nat -> (i < k*4)%nat ->
nth i (intlist_to_Zlist (firstn j al)) d = nth i (intlist_to_Zlist (firstn k al)) d.
Proof.
induction n; destruct i,al,j,k; simpl; intros; auto; try omega.
destruct i; auto. destruct i; auto. destruct i; auto.
apply IHn; omega.
Qed.
Hint Resolve isbyteZ_sublist.
Lemma split2_data_block:
forall {cs: compspecs} n sh data d,
(0 <= n <= Zlength data)%Z ->
data_block sh data d =
(data_block sh (sublist 0 n data) d *
data_block sh (sublist n (Zlength data) data)
(field_address0 (tarray tuchar (Zlength data)) [ArraySubsc n] d))%logic.
Proof.
intros.
unfold data_block. simpl. normalize.
f_equal. f_equal.
apply prop_ext.
split; intro. split; apply Forall_sublist; auto.
erewrite <- (sublist_same 0 (Zlength data)); auto.
rewrite (sublist_split 0 n) by omega.
apply Forall_app; auto.
rewrite <- !sublist_map.
unfold tarray.
rewrite split2_data_at_Tarray_tuchar with (n1:=n) by (autorewrite with sublist; auto).
autorewrite with sublist.
reflexivity.
Qed.
Lemma split3_data_block:
forall {cs: compspecs} lo hi sh data d,
0 <= lo <= hi ->
hi <= Zlength data ->
data_block sh data d =
(data_block sh (sublist 0 lo data) d *
data_block sh (sublist lo hi data)
(field_address0 (tarray tuchar (Zlength data)) [ArraySubsc lo] d) *
data_block sh (sublist hi (Zlength data) data)
(field_address0 (tarray tuchar (Zlength data)) [ArraySubsc hi] d))%logic.
Proof.
intros.
unfold data_block. simpl. normalize.
f_equal. f_equal.
apply prop_ext.
split; intro. split3; apply Forall_sublist; auto.
erewrite <- (sublist_same 0 (Zlength data)); auto.
rewrite (sublist_split 0 lo (Zlength data)) by omega.
rewrite (sublist_split lo hi (Zlength data)) by omega.
destruct H1 as [? [? ?]].
repeat (apply Forall_app; split); auto.
rewrite <- !sublist_map.
unfold tarray.
rewrite split3_data_at_Tarray_tuchar with (n1:=lo)(n2:=hi) by (autorewrite with sublist; auto).
autorewrite with sublist.
reflexivity.
Qed.
Global Opaque WORD.
Lemma S256abs_data:
forall hashed data,
(LBLOCKz | Zlength hashed) ->
Zlength data < CBLOCKz ->
s256a_data (S256abs hashed data) = data.
Proof.
intros. unfold S256abs, s256a_data.
rewrite Zlength_app.
rewrite Zlength_intlist_to_Zlist.
destruct H as [n ?].
rewrite H.
assert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).
pose proof (Zmod_eq (n * CBLOCKz + Zlength data) CBLOCKz H1).
pose proof (Zmod_eq (Zlength data) CBLOCKz H1).
pose proof (Zlength_nonneg data).
rewrite sublist_app2; rewrite Zlength_intlist_to_Zlist; rewrite H;
rewrite <- Z.mul_assoc; change (LBLOCKz * 4)%Z with CBLOCKz.
apply sublist_same.
rewrite Z.div_add_l by omega.
rewrite Z.mul_add_distr_r.
rewrite Z.div_small by omega. omega.
omega.
rewrite Z.div_add_l by omega.
rewrite Z.mul_add_distr_r.
rewrite Z.div_small by omega.
split; [ | omega].
apply Z.mul_nonneg_nonneg.
clear - H.
assert (n < 0 \/ 0 <= n) by omega.
destruct H0; auto.
pose proof (Zlength_nonneg hashed).
assert (n * LBLOCKz < 0).
apply Z.mul_neg_pos; auto.
omega.
omega.
Qed.
Lemma S256abs_hashed:
forall hashed data,
(LBLOCKz | Zlength hashed) ->
Zlength data < CBLOCKz ->
s256a_hashed (S256abs hashed data) = hashed.
Proof.
intros; unfold S256abs, s256a_hashed.
rewrite Zlength_app.
rewrite Zlength_intlist_to_Zlist.
destruct H as [n ?].
assert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).
pose proof (Zmod_eq (n * CBLOCKz + Zlength data) CBLOCKz H1).
pose proof (Zmod_eq (Zlength data) CBLOCKz H1).
pose proof (Zlength_nonneg data).
rewrite sublist_app1; rewrite ?Zlength_intlist_to_Zlist;
rewrite H.
rewrite sublist_same; try omega.
apply intlist_to_Zlist_to_intlist.
rewrite Zlength_intlist_to_Zlist.
rewrite H.
rewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.
rewrite Z.div_add_l by omega.
rewrite Z.mul_add_distr_r.
rewrite Z.div_small by omega. omega.
split; [omega | ].
rewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.
rewrite Z.div_add_l by omega.
rewrite Z.mul_add_distr_r.
rewrite Z.div_small by omega.
clear - H.
assert (n < 0 \/ 0 <= n) by omega.
simpl.
destruct H0.
pose proof (Zlength_nonneg hashed).
assert (n * LBLOCKz < 0).
apply Z.mul_neg_pos; auto.
omega.
rewrite Z.add_0_r.
apply Z.mul_nonneg_nonneg; auto.
rewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.
rewrite Z.div_add_l by omega.
rewrite Z.mul_add_distr_r.
rewrite Z.div_small by omega. omega.
Qed.
Lemma s256a_hashed_divides:
forall a, (LBLOCKz | Zlength (s256a_hashed a)).
Proof.
intros. unfold s256a_hashed.
exists (Zlength a / CBLOCKz)%Z.
erewrite Zlength_Zlist_to_intlist; [reflexivity |].
rewrite Zlength_sublist.
rewrite (Z.mul_comm WORD).
rewrite <- Z.mul_assoc.
change (LBLOCKz * WORD)%Z with CBLOCKz.
omega.
split; [ omega |] .
apply Z.mul_nonneg_nonneg; auto.
apply Z.div_pos.
apply Zlength_nonneg.
rewrite CBLOCKz_eq; omega.
assert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).
pose proof (Zmod_eq (Zlength a) CBLOCKz H).
pose proof (Z_mod_lt (Zlength a) CBLOCKz H).
omega.
Qed.
Lemma s256a_data_len:
forall a: s256abs,
Zlength (s256a_data a) = Zlength a mod CBLOCKz.
Proof.
intros.
unfold s256a_data.
assert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).
pose proof (Zmod_eq (Zlength a) CBLOCKz H).
pose proof (Z_mod_lt (Zlength a) CBLOCKz H).
rewrite H0.
rewrite Zlength_sublist; try omega.
split; try omega.
apply Z.mul_nonneg_nonneg.
apply Z.div_pos.
apply Zlength_nonneg.
omega. omega.
Qed.
Lemma s256a_data_Zlength_less:
forall a, Zlength (s256a_data a) < CBLOCKz.
Proof.
intros.
rewrite s256a_data_len.
apply Z_mod_lt.
rewrite CBLOCKz_eq; omega.
Qed.
Lemma hashed_data_recombine:
forall a,
Forall isbyteZ a ->
intlist_to_Zlist (s256a_hashed a) ++ s256a_data a = a.
Proof.
intros. rename H into BYTES.
unfold s256a_hashed, s256a_data.
assert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).
rewrite Zlist_to_intlist_to_Zlist.
rewrite sublist_rejoin.
autorewrite with sublist. auto.
split; [ omega |] .
apply Z.mul_nonneg_nonneg; auto.
apply Z.div_pos.
apply Zlength_nonneg.
rewrite CBLOCKz_eq; omega.
assert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).
pose proof (Zmod_eq (Zlength a) CBLOCKz H).
pose proof (Z_mod_lt (Zlength a) CBLOCKz H).
omega.
rewrite Zlength_sublist.
rewrite Z.sub_0_r.
apply Z.divide_mul_r.
exists LBLOCKz. reflexivity.
split; [ omega |] .
apply Z.mul_nonneg_nonneg; auto.
apply Z.div_pos.
apply Zlength_nonneg.
omega.
pose proof (Zmod_eq (Zlength a) CBLOCKz H).
pose proof (Z_mod_lt (Zlength a) CBLOCKz H).
omega.
apply Forall_sublist.
auto.
Qed.
Definition bitlength (hashed: list int) (data: list Z) : Z :=
((Zlength hashed * WORD + Zlength data) * 8)%Z.
Lemma bitlength_eq:
forall hashed data,
bitlength hashed data = s256a_len (S256abs hashed data).
Proof.
intros.
unfold bitlength, s256a_len, S256abs.
rewrite Zlength_app.
rewrite Zlength_intlist_to_Zlist.
reflexivity.
Qed.
Lemma S256abs_recombine:
forall a, Forall isbyteZ a ->
S256abs (s256a_hashed a) (s256a_data a) = a.
Proof.
intros.
apply hashed_data_recombine; auto.
Qed.
Lemma Zlist_to_intlist_app:
forall a b,
(WORD | Zlength a) ->
Zlist_to_intlist (a++b) = Zlist_to_intlist a ++ Zlist_to_intlist b.
Proof.
intros.
destruct H as [na H].
rewrite <- (Z2Nat.id na) in H.
Focus 2.
destruct (zlt na 0); try omega.
assert (na * WORD < 0); [apply Z.mul_neg_pos; auto | ].
pose proof (Zlength_nonneg a); omega.
revert a H; induction (Z.to_nat na); intros.
simpl in H. destruct a. simpl. auto. rewrite Zlength_cons in H.
pose proof (Zlength_nonneg a); omega.
rewrite inj_S in H.
unfold Z.succ in H. rewrite Z.mul_add_distr_r in H.
change (1*WORD)%Z with 4 in H.
assert (Zlength a >= 4).
assert (0 <= Z.of_nat n * WORD); [ | omega].
apply Z.mul_nonneg_nonneg; try omega.
change WORD with 4%Z; omega.
do 4 (destruct a; [rewrite Zlength_nil in H0; omega | rewrite Zlength_cons in H,H0 ]).
simpl.
do 4 f_equal. apply IHn.
omega.
Qed.
Lemma round_range:
forall {A} (a: list A) (N:Z),
N > 0 ->
0 <= Zlength a / N * N <= Zlength a.
Proof.
intros.
split.
apply Z.mul_nonneg_nonneg; auto; try omega.
apply Z.div_pos; try omega.
apply Zlength_nonneg.
pose proof (Zmod_eq (Zlength a) N H).
pose proof (Z_mod_lt (Zlength a) N H).
omega.
Qed.
Lemma CBLOCKz_gt: CBLOCKz > 0.
Proof. rewrite CBLOCKz_eq; omega.
Qed.
Lemma Zlist_to_intlist_inj:
forall a b,
(WORD | Zlength a) ->
(WORD | Zlength b) ->
Forall isbyteZ a ->
Forall isbyteZ b ->
Zlist_to_intlist a = Zlist_to_intlist b ->
a=b.
Proof.
intros.
rewrite <- (Zlist_to_intlist_to_Zlist a) by auto.
rewrite H3.
apply Zlist_to_intlist_to_Zlist; auto.
Qed.
Definition update_abs (incr: list Z) (a: list Z) (a': list Z) :=
a' = a ++ incr.
Lemma update_abs_eq:
forall msg a a',
Forall isbyteZ (a++msg) ->
Forall isbyteZ a' ->
(update_abs msg a a' <->
exists blocks,
s256a_hashed a' = s256a_hashed a ++ blocks /\
s256a_data a ++ msg = intlist_to_Zlist blocks ++ s256a_data a').
Proof.
intros. rename H0 into H'.
unfold update_abs.
assert (0 <= 0 <= Zlength a / CBLOCKz * CBLOCKz). {
split; [omega | ].
apply Z.mul_nonneg_nonneg.
apply Z.div_pos.
apply Zlength_nonneg.
rewrite CBLOCKz_eq; omega.
rewrite CBLOCKz_eq; omega.
}
pose proof (round_range a _ CBLOCKz_gt).
pose proof (round_range (a++msg) _ CBLOCKz_gt).
split; intro.
*
subst a'.
unfold s256a_hashed.
exists (Zlist_to_intlist
(sublist (Zlength a / CBLOCKz * CBLOCKz) (Zlength (a++msg) / CBLOCKz * CBLOCKz)
(a++msg))).
split.
+
rewrite (sublist_split 0 (Zlength a / CBLOCKz * CBLOCKz)); auto.
rewrite Zlist_to_intlist_app.
f_equal.
rewrite sublist_app1; auto. omega.
rewrite Zlength_sublist; auto.
rewrite Z.sub_0_r.
apply Z.divide_mul_r.
exists LBLOCKz; reflexivity.
rewrite Zlength_app.
pose proof (Zlength_nonneg msg); omega.
split; [ | apply round_range; apply CBLOCKz_gt].
apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].
apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].
rewrite Zlength_app; Omega1.
+
rewrite Zlist_to_intlist_to_Zlist.
Focus 2. rewrite Zlength_sublist. rewrite <- Z.mul_sub_distr_r.
apply Z.divide_mul_r.
exists LBLOCKz; reflexivity.
split; [Omega1 | ].
apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].
apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].
rewrite Zlength_app; Omega1.
apply round_range. apply CBLOCKz_gt.
2: apply Forall_sublist; auto.
unfold s256a_data.
destruct (zlt (Zlength (a ++ msg) / CBLOCKz * CBLOCKz) (Zlength a) ).
-
rewrite sublist_app1; try omega.
rewrite (sublist_split (Zlength (a ++ msg) / CBLOCKz * CBLOCKz)
(Zlength a) (Zlength (a ++ msg))); try omega.
rewrite sublist_app1; try omega.
rewrite sublist_app2 by omega.
autorewrite with sublist.
rewrite (sublist_same 0) by omega.
rewrite <- app_ass. f_equal.
rewrite sublist_rejoin; try omega. auto.
split. apply round_range; apply CBLOCKz_gt.
apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].
apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].
Omega1.
rewrite Zlength_app in l; omega.
rewrite Zlength_app; Omega1.
split. apply round_range; apply CBLOCKz_gt.
apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].
apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].
rewrite Zlength_app; Omega1.
-
rewrite (sublist_split (Zlength a / CBLOCKz * CBLOCKz) (Zlength a)
(Zlength (a ++ msg) / CBLOCKz * CBLOCKz) ); auto.
rewrite app_ass.
rewrite sublist_app1; try omega.
rewrite sublist_app2; try omega.
rewrite Z.sub_diag.
f_equal.
rewrite sublist_app2; try omega.
rewrite sublist_rejoin.
autorewrite with sublist. auto.
omega.
split; try omega. rewrite Zlength_app; Omega1.
omega.
*
destruct H3 as [blocks [? ?]].
match type of H3 with ?A = ?B =>
assert (Zlength A * WORD = Zlength B * WORD)%Z by congruence
end.
match type of H4 with ?A = ?B =>
assert (sublist 0 (Zlength a / CBLOCKz * CBLOCKz) a ++ A =
sublist 0 (Zlength a / CBLOCKz * CBLOCKz) a ++ B) by congruence
end.
unfold s256a_hashed, s256a_data in *.
rewrite <- app_ass in H6.
rewrite sublist_rejoin in H6 by omega.
rewrite sublist_same in H6 by omega.
rewrite H6.
clear H6 H4.
rewrite <- (sublist_same 0 (Zlength a') a') at 1; auto.
rewrite <- app_ass.
rewrite (sublist_split 0 (Zlength a' / CBLOCKz * CBLOCKz) (Zlength a')); try omega.
f_equal.
apply Zlist_to_intlist_inj.
rewrite Zlength_sublist.
rewrite Z.sub_0_r.
apply Z.divide_mul_r.
exists LBLOCKz; reflexivity.
split; [clear; omega | ].
apply Z.mul_nonneg_nonneg; [ | rewrite CBLOCKz_eq; omega].
apply Z.div_pos; [ | rewrite CBLOCKz_eq; omega].
apply Zlength_nonneg.
apply round_range; apply CBLOCKz_gt.
rewrite Zlength_app.
apply Z.divide_add_r.
rewrite Zlength_sublist.
rewrite Z.sub_0_r.
apply Z.divide_mul_r.
exists LBLOCKz; reflexivity.
split; [clear; omega | ].
apply Z.mul_nonneg_nonneg; [ | rewrite CBLOCKz_eq; omega].
apply Z.div_pos; [ | rewrite CBLOCKz_eq; omega].
apply Zlength_nonneg.
apply round_range; apply CBLOCKz_gt.
exists (Zlength blocks).
apply Zlength_intlist_to_Zlist.
apply Forall_sublist; auto.
apply Forall_app; split.
apply Forall_app in H; destruct H;
apply Forall_sublist; auto.
apply isbyte_intlist_to_Zlist.
rewrite H3.
rewrite Zlist_to_intlist_app. f_equal.
symmetry; apply intlist_to_Zlist_to_intlist.
rewrite Zlength_sublist.
rewrite Z.sub_0_r.
apply Z.divide_mul_r.
exists LBLOCKz; reflexivity.
auto.
omega.
split; [clear; omega |].
apply round_range; apply CBLOCKz_gt.
split; [ | clear; omega].
apply round_range; apply CBLOCKz_gt.
Qed.
Lemma array_at_memory_block:
forall {cs: compspecs} sh t gfs lo hi v p n,
sizeof (nested_field_array_type t gfs lo hi) = n ->
lo <= hi ->
array_at sh t gfs lo hi v p |--
memory_block sh n (field_address0 t (ArraySubsc lo :: gfs) p).
Proof.
intros.
rewrite array_at_data_at by auto.
normalize.
unfold at_offset.
rewrite field_address0_offset by auto.
subst n.
apply data_at_memory_block.
Qed.
Hint Extern 2 (array_at _ _ _ _ _ _ _ |-- memory_block _ _ _) =>
(apply array_at_memory_block; try reflexivity; try omega) : cancel.
|
\documentclass[red]{mytest}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{blindtext}
\title{Example to show how classes work}
\author{Team Learn ShareLaTeX}
\date{2019/4/20}
\begin{document}
\maketitle
\noindent
Let's begin with a simple working example here.
\blindtext
\section{Introduction}
The Monty Hall problem...
\blindtext
\section{The same thing}
The Monty...
\blindtext
\section{The same thing}
The Monty...
\blindtext
\section{The same thing}
The Monty...
\blindtext
\section{The same thing}
The Monty...
\blindtext
\end{document}
|
[STATEMENT]
lemma before_exists: "\<turnstile> $(\<exists> x. P x) = (\<exists> x. $(P x))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<turnstile> $(\<exists>x. P x) = (\<exists>x. $P x)
[PROOF STEP]
by (auto simp: before_def)
|
The fractional part of $1$ is $1$.
|
[STATEMENT]
lemma prime_factors_characterization_nat:
"S = {p. 0 < f (p::nat)} \<Longrightarrow>
finite S \<Longrightarrow> \<forall>p\<in>S. prime p \<Longrightarrow> n = (\<Prod>p\<in>S. p ^ f p) \<Longrightarrow> prime_factors n = S"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>S = {p. 0 < f p}; finite S; \<forall>p\<in>S. prime p; n = (\<Prod>p\<in>S. p ^ f p)\<rbrakk> \<Longrightarrow> prime_factors n = S
[PROOF STEP]
by (rule prime_factorization_unique_nat [THEN conjunct1, symmetric])
|
(* Default settings (from HsToCoq.Coq.Preamble) *)
Generalizable All Variables.
Unset Implicit Arguments.
Set Maximal Implicit Insertion.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Require Coq.Program.Tactics.
Require Coq.Program.Wf.
(* Converted imports: *)
Require GHC.Base.
Import GHC.Base.Notations.
(* Converted type declarations: *)
Inductive StateR s a : Type :=
| Mk_StateR (runStateR : s -> (s * a)%type) : StateR s a.
Inductive StateL s a : Type :=
| Mk_StateL (runStateL : s -> (s * a)%type) : StateL s a.
Inductive Min a : Type := | Mk_Min (getMin : option a) : Min a.
Inductive Max a : Type := | Mk_Max (getMax : option a) : Max a.
Arguments Mk_StateR {_} {_} _.
Arguments Mk_StateL {_} {_} _.
Arguments Mk_Min {_} _.
Arguments Mk_Max {_} _.
Definition runStateR {s} {a} (arg_0__ : StateR s a) :=
let 'Mk_StateR runStateR := arg_0__ in
runStateR.
Definition runStateL {s} {a} (arg_0__ : StateL s a) :=
let 'Mk_StateL runStateL := arg_0__ in
runStateL.
Definition getMin {a} (arg_0__ : Min a) :=
let 'Mk_Min getMin := arg_0__ in
getMin.
Definition getMax {a} (arg_0__ : Max a) :=
let 'Mk_Max getMax := arg_0__ in
getMax.
(* Midamble *)
(* We should be able to automatically generate these *)
Instance Unpeel_StateR {s}{a} : HsToCoq.Unpeel.Unpeel (StateR s a) (s -> (s * a)%type)
:= HsToCoq.Unpeel.Build_Unpeel _ _ (fun arg => match arg with | Mk_StateR x => x end) Mk_StateR.
Instance Unpeel_StateL {s}{a} : HsToCoq.Unpeel.Unpeel (StateL s a) (s -> (s * a)%type)
:= HsToCoq.Unpeel.Build_Unpeel _ _ (fun arg => match arg with | Mk_StateL x => x end) Mk_StateL.
Instance Unpeel_Min {a} : HsToCoq.Unpeel.Unpeel (Min a) (option a)
:= HsToCoq.Unpeel.Build_Unpeel _ _ (fun arg => match arg with | Mk_Min x => x end) Mk_Min.
Instance Unpeel_Max {a} : HsToCoq.Unpeel.Unpeel (Max a) (option a)
:= HsToCoq.Unpeel.Build_Unpeel _ _ (fun arg => match arg with | Mk_Max x => x end) Mk_Max.
(* Converted value declarations: *)
Local Definition Semigroup__Max_op_zlzlzgzg__ {inst_a : Type} `{GHC.Base.Ord
inst_a}
: Max inst_a -> Max inst_a -> Max inst_a :=
fun arg_0__ arg_1__ =>
match arg_0__, arg_1__ with
| m, Mk_Max None => m
| Mk_Max None, n => n
| Mk_Max (Some x as m), Mk_Max (Some y as n) =>
if x GHC.Base.>= y : bool then Mk_Max m else
Mk_Max n
end.
Program Instance Semigroup__Max {a : Type} `{GHC.Base.Ord a}
: GHC.Base.Semigroup (Max a) :=
fun _ k__ => k__ {| GHC.Base.op_zlzlzgzg____ := Semigroup__Max_op_zlzlzgzg__ |}.
Local Definition Monoid__Max_mappend {inst_a : Type} `{GHC.Base.Ord inst_a}
: Max inst_a -> Max inst_a -> Max inst_a :=
_GHC.Base.<<>>_.
Local Definition Monoid__Max_mempty {inst_a : Type} `{GHC.Base.Ord inst_a}
: Max inst_a :=
Mk_Max None.
Local Definition Monoid__Max_mconcat {inst_a : Type} `{GHC.Base.Ord inst_a}
: list (Max inst_a) -> Max inst_a :=
GHC.Base.foldr Monoid__Max_mappend Monoid__Max_mempty.
Program Instance Monoid__Max {a : Type} `{GHC.Base.Ord a}
: GHC.Base.Monoid (Max a) :=
fun _ k__ =>
k__ {| GHC.Base.mappend__ := Monoid__Max_mappend ;
GHC.Base.mconcat__ := Monoid__Max_mconcat ;
GHC.Base.mempty__ := Monoid__Max_mempty |}.
Local Definition Semigroup__Min_op_zlzlzgzg__ {inst_a : Type} `{GHC.Base.Ord
inst_a}
: Min inst_a -> Min inst_a -> Min inst_a :=
fun arg_0__ arg_1__ =>
match arg_0__, arg_1__ with
| m, Mk_Min None => m
| Mk_Min None, n => n
| Mk_Min (Some x as m), Mk_Min (Some y as n) =>
if x GHC.Base.<= y : bool then Mk_Min m else
Mk_Min n
end.
Program Instance Semigroup__Min {a : Type} `{GHC.Base.Ord a}
: GHC.Base.Semigroup (Min a) :=
fun _ k__ => k__ {| GHC.Base.op_zlzlzgzg____ := Semigroup__Min_op_zlzlzgzg__ |}.
Local Definition Monoid__Min_mappend {inst_a : Type} `{GHC.Base.Ord inst_a}
: Min inst_a -> Min inst_a -> Min inst_a :=
_GHC.Base.<<>>_.
Local Definition Monoid__Min_mempty {inst_a : Type} `{GHC.Base.Ord inst_a}
: Min inst_a :=
Mk_Min None.
Local Definition Monoid__Min_mconcat {inst_a : Type} `{GHC.Base.Ord inst_a}
: list (Min inst_a) -> Min inst_a :=
GHC.Base.foldr Monoid__Min_mappend Monoid__Min_mempty.
Program Instance Monoid__Min {a : Type} `{GHC.Base.Ord a}
: GHC.Base.Monoid (Min a) :=
fun _ k__ =>
k__ {| GHC.Base.mappend__ := Monoid__Min_mappend ;
GHC.Base.mconcat__ := Monoid__Min_mconcat ;
GHC.Base.mempty__ := Monoid__Min_mempty |}.
Local Definition Functor__StateL_fmap {inst_s : Type}
: forall {a : Type},
forall {b : Type}, (a -> b) -> StateL inst_s a -> StateL inst_s b :=
fun {a : Type} {b : Type} =>
fun arg_0__ arg_1__ =>
match arg_0__, arg_1__ with
| f, Mk_StateL k => Mk_StateL (fun s => let 'pair s' v := k s in pair s' (f v))
end.
Local Definition Functor__StateL_op_zlzd__ {inst_s : Type}
: forall {a : Type},
forall {b : Type}, a -> StateL inst_s b -> StateL inst_s a :=
fun {a : Type} {b : Type} => Functor__StateL_fmap GHC.Base.∘ GHC.Base.const.
Program Instance Functor__StateL {s : Type} : GHC.Base.Functor (StateL s) :=
fun _ k__ =>
k__ {| GHC.Base.fmap__ := fun {a : Type} {b : Type} => Functor__StateL_fmap ;
GHC.Base.op_zlzd____ := fun {a : Type} {b : Type} =>
Functor__StateL_op_zlzd__ |}.
Local Definition Applicative__StateL_liftA2 {inst_s : Type}
: forall {a : Type},
forall {b : Type},
forall {c : Type},
(a -> b -> c) -> StateL inst_s a -> StateL inst_s b -> StateL inst_s c :=
fun {a : Type} {b : Type} {c : Type} =>
fun arg_0__ arg_1__ arg_2__ =>
match arg_0__, arg_1__, arg_2__ with
| f, Mk_StateL kx, Mk_StateL ky =>
Mk_StateL (fun s =>
let 'pair s' x := kx s in
let 'pair s'' y := ky s' in
pair s'' (f x y))
end.
Local Definition Applicative__StateL_op_zlztzg__ {inst_s : Type}
: forall {a : Type},
forall {b : Type},
StateL inst_s (a -> b) -> StateL inst_s a -> StateL inst_s b :=
fun {a : Type} {b : Type} =>
fun arg_0__ arg_1__ =>
match arg_0__, arg_1__ with
| Mk_StateL kf, Mk_StateL kv =>
Mk_StateL (fun s =>
let 'pair s' f := kf s in
let 'pair s'' v := kv s' in
pair s'' (f v))
end.
Local Definition Applicative__StateL_op_ztzg__ {inst_s : Type}
: forall {a : Type},
forall {b : Type}, StateL inst_s a -> StateL inst_s b -> StateL inst_s b :=
fun {a : Type} {b : Type} =>
fun a1 a2 => Applicative__StateL_op_zlztzg__ (GHC.Base.id GHC.Base.<$ a1) a2.
Local Definition Applicative__StateL_pure {inst_s : Type}
: forall {a : Type}, a -> StateL inst_s a :=
fun {a : Type} => fun x => Mk_StateL (fun s => pair s x).
Program Instance Applicative__StateL {s : Type}
: GHC.Base.Applicative (StateL s) :=
fun _ k__ =>
k__ {| GHC.Base.liftA2__ := fun {a : Type} {b : Type} {c : Type} =>
Applicative__StateL_liftA2 ;
GHC.Base.op_zlztzg____ := fun {a : Type} {b : Type} =>
Applicative__StateL_op_zlztzg__ ;
GHC.Base.op_ztzg____ := fun {a : Type} {b : Type} =>
Applicative__StateL_op_ztzg__ ;
GHC.Base.pure__ := fun {a : Type} => Applicative__StateL_pure |}.
Local Definition Functor__StateR_fmap {inst_s : Type}
: forall {a : Type},
forall {b : Type}, (a -> b) -> StateR inst_s a -> StateR inst_s b :=
fun {a : Type} {b : Type} =>
fun arg_0__ arg_1__ =>
match arg_0__, arg_1__ with
| f, Mk_StateR k => Mk_StateR (fun s => let 'pair s' v := k s in pair s' (f v))
end.
Local Definition Functor__StateR_op_zlzd__ {inst_s : Type}
: forall {a : Type},
forall {b : Type}, a -> StateR inst_s b -> StateR inst_s a :=
fun {a : Type} {b : Type} => Functor__StateR_fmap GHC.Base.∘ GHC.Base.const.
Program Instance Functor__StateR {s : Type} : GHC.Base.Functor (StateR s) :=
fun _ k__ =>
k__ {| GHC.Base.fmap__ := fun {a : Type} {b : Type} => Functor__StateR_fmap ;
GHC.Base.op_zlzd____ := fun {a : Type} {b : Type} =>
Functor__StateR_op_zlzd__ |}.
Local Definition Applicative__StateR_liftA2 {inst_s : Type}
: forall {a : Type},
forall {b : Type},
forall {c : Type},
(a -> b -> c) -> StateR inst_s a -> StateR inst_s b -> StateR inst_s c :=
fun {a : Type} {b : Type} {c : Type} =>
fun arg_0__ arg_1__ arg_2__ =>
match arg_0__, arg_1__, arg_2__ with
| f, Mk_StateR kx, Mk_StateR ky =>
Mk_StateR (fun s =>
let 'pair s' y := ky s in
let 'pair s'' x := kx s' in
pair s'' (f x y))
end.
Local Definition Applicative__StateR_op_zlztzg__ {inst_s : Type}
: forall {a : Type},
forall {b : Type},
StateR inst_s (a -> b) -> StateR inst_s a -> StateR inst_s b :=
fun {a : Type} {b : Type} =>
fun arg_0__ arg_1__ =>
match arg_0__, arg_1__ with
| Mk_StateR kf, Mk_StateR kv =>
Mk_StateR (fun s =>
let 'pair s' v := kv s in
let 'pair s'' f := kf s' in
pair s'' (f v))
end.
Local Definition Applicative__StateR_op_ztzg__ {inst_s : Type}
: forall {a : Type},
forall {b : Type}, StateR inst_s a -> StateR inst_s b -> StateR inst_s b :=
fun {a : Type} {b : Type} =>
fun a1 a2 => Applicative__StateR_op_zlztzg__ (GHC.Base.id GHC.Base.<$ a1) a2.
Local Definition Applicative__StateR_pure {inst_s : Type}
: forall {a : Type}, a -> StateR inst_s a :=
fun {a : Type} => fun x => Mk_StateR (fun s => pair s x).
Program Instance Applicative__StateR {s : Type}
: GHC.Base.Applicative (StateR s) :=
fun _ k__ =>
k__ {| GHC.Base.liftA2__ := fun {a : Type} {b : Type} {c : Type} =>
Applicative__StateR_liftA2 ;
GHC.Base.op_zlztzg____ := fun {a : Type} {b : Type} =>
Applicative__StateR_op_zlztzg__ ;
GHC.Base.op_ztzg____ := fun {a : Type} {b : Type} =>
Applicative__StateR_op_ztzg__ ;
GHC.Base.pure__ := fun {a : Type} => Applicative__StateR_pure |}.
(* Skipping definition `Data.Functor.Utils.hash_compose' *)
(* External variables:
None Some Type bool list op_zt__ option pair GHC.Base.Applicative
GHC.Base.Functor GHC.Base.Monoid GHC.Base.Ord GHC.Base.Semigroup GHC.Base.const
GHC.Base.fmap__ GHC.Base.foldr GHC.Base.id GHC.Base.liftA2__ GHC.Base.mappend__
GHC.Base.mconcat__ GHC.Base.mempty__ GHC.Base.op_z2218U__ GHC.Base.op_zgze__
GHC.Base.op_zlzd__ GHC.Base.op_zlzd____ GHC.Base.op_zlze__
GHC.Base.op_zlzlzgzg__ GHC.Base.op_zlzlzgzg____ GHC.Base.op_zlztzg____
GHC.Base.op_ztzg____ GHC.Base.pure__
*)
|
(*
File: FinCard.thy
Time-stamp: <2015-12-12T10:47:26Z>
Author: JRF
Web: http://jrf.cocolog-nifty.com/software/2016/01/post.html
Logic Image: ZF (of Isabelle2015)
*)
theory FinCard imports Finite Cardinal begin
lemma Fin_subset2:
assumes "X: Fin(A)"
and "X <= B"
shows "X: Fin(B)"
apply (rule assms(2) [THEN rev_mp])
apply (rule assms(1) [THEN Fin_induct])
apply (rule impI)
apply (rule Fin.emptyI)
apply (rule impI)
apply (erule cons_subsetE)
apply (rule Fin.consI)
apply (drule_tac [2] mp)
apply assumption+
done
lemma Fin_domainI [TC]:
"X: Fin(A*B) ==> domain(X): Fin(A)"
apply (erule Fin_induct)
apply (erule_tac [2] SigmaE)
apply simp_all
done
lemma Fin_rangeI [TC]:
"X: Fin(A*B) ==> range(X): Fin(B)"
apply (erule Fin_induct)
apply (erule_tac [2] SigmaE)
apply simp_all
done
lemma Fin_RepFunI [TC]:
"[| X: Fin(A); !!x. x: A ==> f(x): B |] ==> {f(x). x: X}: Fin(B)"
apply (erule Fin_induct)
apply simp_all
done
lemmas Fin_imp_Finite = Fin_into_Finite
lemmas Finite_imp_Fin = Finite_into_Fin
lemma Finite_imp_card_nat [TC]:
"Finite(A) ==> |A|: nat"
apply (unfold Finite_def)
apply (erule bexE)
apply (drule cardinal_cong)
apply (erule ssubst)
apply (rule lt_nat_in_nat)
apply (rule Ord_cardinal_le)
apply (erule nat_into_Ord)
apply (erule nat_succI)
done
lemma Fin_complete_induct_lemma:
"n: nat ==> (ALL X: Fin(A). |X| = n -->
(ALL x: Fin(A). (ALL y. y: Fin(A) & |y| < |x| --> P(y)) --> P(x))
--> P(X))"
apply (erule complete_induct)
apply clarsimp
apply (erule bspec [THEN mp])
apply assumption
apply clarsimp
apply (drule ltD)
apply simp
done
lemma Fin_complete_induct:
assumes major: "X: Fin(A)"
and indstep: "!!x. [| x: Fin(A);
ALL y. y: Fin(A) & |y| < |x| --> P(y)
|] ==> P(x)"
shows "P(X)"
apply (rule major [THEN Fin_into_Finite, THEN Finite_imp_card_nat,
THEN Fin_complete_induct_lemma,
THEN bspec, THEN mp, THEN mp])
apply ((rule major refl ballI impI indstep) | assumption)+
done
lemma Finite_lepoll_imp_le:
assumes major: "A lepoll B"
and prem: "Finite(B)"
shows "|A| le |B|"
apply (insert lepoll_Finite [OF major prem] prem major)
apply (unfold Finite_def cardinal_def)
apply clarify
apply (rule le_trans)
apply (rule Least_le)
apply (erule eqpoll_sym)
apply (erule nat_into_Ord)
apply (rule_tac P="%x. n le x" in ssubst)
apply (rule Least_equality)
apply (erule eqpoll_sym)
apply (erule nat_into_Ord)
apply (rule notI)
apply (drule eqpoll_trans, assumption)
apply (frule lt_nat_in_nat)
apply assumption
apply (drule nat_eqpoll_iff [THEN iffD1], assumption, assumption)
apply hypsubst
apply (erule lt_irrefl)
apply (rule nat_lepoll_imp_le)
apply assumption+
apply (rule lepoll_trans)
apply (rule eqpoll_sym [THEN eqpoll_imp_lepoll], assumption)
apply (rule lepoll_trans, assumption)
apply (erule eqpoll_imp_lepoll)
done
lemma Finite_cardinal_succ:
"Finite(A) ==> |succ(A)| = succ(|A|)"
apply (unfold Finite_def)
apply (erule bexE)
apply (rule_tac b="|succ(n)|" in trans)
apply (rule cardinal_cong)
apply (simp only: succ_def)
apply (blast elim!: mem_irrefl intro: cons_eqpoll_cong)
apply (drule cardinal_cong)
apply (simp add: nat_into_Card [THEN Card_cardinal_eq])
done
lemma Finite_cardinal_cons:
assumes major: "Finite(A)"
shows "a ~: A ==> |cons(a, A)| = succ(|A|)"
apply (rule major [THEN Finite_cardinal_succ, THEN [2] trans])
apply (rule cardinal_cong)
apply (unfold succ_def)
apply (blast elim!: mem_irrefl intro: eqpoll_refl cons_eqpoll_cong)
done
lemmas FinCard_simps = Finite_cardinal_cons cons_absorb cardinal_0
end
|
lemmas independent_imp_finite = finiteI_independent
|
Formal statement is: lemma Sup_sigma: assumes [simp]: "M \<noteq> {}" and M: "\<And>m. m \<in> M \<Longrightarrow> m \<subseteq> Pow \<Omega>" shows "(SUP m\<in>M. sigma \<Omega> m) = (sigma \<Omega> (\<Union>M))" Informal statement is: If $M$ is a nonempty set of subsets of $\Omega$, then $\sigma(\bigcup M) = \sigma(\bigcup_{m \in M} m)$.
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
"""
# librerias
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model i
# leer el CSV
data = pd.read_csv('../../data/data/dataFromAguascalientestTest.csv')
#
|
||| A simple module to process 'literate' documents.
|||
||| The module uses a lexer to split the document into code blocks,
||| delineated by user-defined markers, and code lines that are
||| indicated be a line marker. The lexer returns a document stripped
||| of non-code elements but preserving the original document's line
||| count. Column numbering of code lines are not preserved.
|||
||| The underlying tokeniser is greedy.
|||
||| Once it identifies a line marker it reads a prettifying space then
||| consumes until the end of line. Once identifies a starting code
||| block marker, the lexer will consume input until the next
||| identifiable end block is encountered. Any other content is
||| treated as part of the original document.
|||
||| Thus, the input literate files *must* be well-formed w.r.t
||| to code line markers and code blocks.
|||
||| A further restriction is that literate documents cannot contain
||| the markers within the document's main text: This will confuse the
||| lexer.
|||
module Text.Literate
import Text.Lexer
import Data.List
import Data.List1
import Data.List.Views
import Data.String
import Data.String.Extra
%default total
untilEOL : Recognise False
untilEOL = manyUntil newline any
line : String -> Lexer
line s = exact s <+> (newline <|> space <+> untilEOL)
block : String -> String -> Lexer
block s e = surround (exact s <+> untilEOL) (exact e <+> untilEOL) any
notCodeLine : Lexer
notCodeLine = newline
<|> any <+> untilEOL
data Token = CodeBlock String String String
| Any String
| CodeLine String String
Show Token where
showPrec d (CodeBlock l r x) = showCon d "CodeBlock" $ showArg l ++ showArg r ++ showArg x
showPrec d (Any x) = showCon d "Any" $ showArg x
showPrec d (CodeLine m x) = showCon d "CodeLine" $ showArg m ++ showArg x
rawTokens : (delims : List (String, String))
-> (markers : List String)
-> TokenMap (Token)
rawTokens delims ls =
map (\(l,r) => (block l r, CodeBlock (trim l) (trim r))) delims
++ map (\m => (line m, CodeLine (trim m))) ls
++ [(notCodeLine, Any)]
namespace Compat
-- `reduce` below was depending on the old behaviour of `lines` before #1585
-- was merged. That old `lines` function is added here to preserve behaviour
-- of `reduce`.
lines' : List Char -> List1 (List Char)
lines' [] = singleton []
lines' s = case break isNL s of
(l, s') => l ::: case s' of
[] => []
_ :: s'' => forget $ lines' (assert_smaller s s'')
export
lines : String -> List1 String
lines s = map pack (lines' (unpack s))
||| Merge the tokens into a single source file.
reduce : List (WithBounds Token) -> List String -> String
reduce [] acc = fastAppend (reverse acc)
reduce (MkBounded (Any x) _ _ :: rest) acc =
-- newline will always be tokenized as a single token
if x == "\n"
then reduce rest ("\n"::acc)
else reduce rest acc
reduce (MkBounded (CodeLine m src) _ _ :: rest) acc =
if m == trim src
then reduce rest ("\n"::acc)
else reduce rest ((substr (length m + 1) -- remove space to right of marker.
(length src)
src
)::acc)
reduce (MkBounded (CodeBlock l r src) _ _ :: rest) acc with (Compat.lines src) -- Strip the deliminators surrounding the block.
reduce (MkBounded (CodeBlock l r src) _ _ :: rest) acc | (s ::: ys) with (snocList ys)
reduce (MkBounded (CodeBlock l r src) _ _ :: rest) acc | (s ::: []) | Empty = reduce rest acc -- 2
reduce (MkBounded (CodeBlock l r src) _ _ :: rest) acc | (s ::: (srcs ++ [f])) | (Snoc f srcs rec) =
-- the "\n" counts for the open deliminator; the closing deliminator should always be followed by a (Any "\n"), so we don't add a newline
reduce rest (((unlines srcs) ++ "\n") :: "\n" :: acc)
-- [ NOTE ] 1 & 2 shouldn't happen as code blocks are well formed i.e. have two deliminators.
public export
record LiterateError where
constructor MkLitErr
line : Int
column : Int
input : String
||| Description of literate styles.
|||
||| A 'literate' style comprises of
|||
||| + a list of code block deliminators (`deliminators`);
||| + a list of code line markers (`line_markers`); and
||| + a list of known file extensions `file_extensions`.
|||
||| Some example specifications:
|||
||| + Bird Style
|||
|||```
|||MkLitStyle Nil [">"] [".lidr"]
|||```
|||
||| + Literate Haskell (for LaTeX)
|||
|||```
|||MkLitStyle [("\\begin{code}", "\\end{code}"),("\\begin{spec}","\\end{spec}")]
||| Nil
||| [".lhs", ".tex"]
|||```
|||
||| + OrgMode
|||
|||```
|||MkLitStyle [("#+BEGIN_SRC idris","#+END_SRC"), ("#+COMMENT idris","#+END_COMMENT")]
||| ["#+IDRIS:"]
||| [".org"]
|||```
|||
||| + Common Mark
|||
|||```
|||MkLitStyle [("```idris","```"), ("<!-- idris","--!>")]
||| Nil
||| [".md", ".markdown"]
|||```
|||
public export
record LiterateStyle where
constructor MkLitStyle
||| The pairs of start and end tags for code blocks.
deliminators : List (String, String)
||| Line markers that indicate a line contains code.
line_markers : List String
||| Recognised file extensions. Not used by the module, but will be
||| of use when connecting to code that reads in the original source
||| files.
file_extensions : List String
||| Given a 'literate specification' extract the code from the
||| literate source file (`litStr`) that follows the presented style.
|||
||| @specification The literate specification to use.
||| @litStr The literate source file.
|||
||| Returns a `LiterateError` if the literate file contains malformed
||| code blocks or code lines.
|||
export
extractCode : (specification : LiterateStyle)
-> (litStr : String)
-> Either LiterateError String
extractCode (MkLitStyle delims markers exts) str =
case lex (rawTokens delims markers) str of
(toks, (_,_,"")) => Right (reduce toks Nil)
(_, (l,c,i)) => Left (MkLitErr l c i)
||| Synonym for `extractCode`.
export
unlit : (specification : LiterateStyle)
-> (litStr : String)
-> Either LiterateError String
unlit = extractCode
||| Is the provided line marked up using a line marker?
|||
||| If the line is suffixed by any one of the style's set of line
||| markers then return length of literate line marker, and the code stripped from the line
||| marker. Otherwise, return Nothing and the unmarked line.
export
isLiterateLine : (specification : LiterateStyle)
-> (str : String)
-> Pair (Maybe String) String
isLiterateLine (MkLitStyle delims markers _) str with (lex (rawTokens delims markers) str)
isLiterateLine (MkLitStyle delims markers _) str | ([MkBounded (CodeLine m str') _ _], (_,_, "")) = (Just m, str')
isLiterateLine (MkLitStyle delims markers _) str | (_, _) = (Nothing, str)
||| Given a 'literate specification' embed the given code using the
||| literate style provided.
|||
||| If the style uses deliminators to denote code blocks use the first
||| pair of deliminators in the style. Otherwise use first linemarker
||| in the style. If there is **no style** return the presented code
||| string unembedded.
|||
|||
||| @specification The literate specification to use.
||| @code The code to embed,
|||
|||
export
embedCode : (specification : LiterateStyle)
-> (code : String)
-> String
embedCode (MkLitStyle ((s,e)::delims) _ _) str = unlines [s,str,e]
embedCode (MkLitStyle Nil (m::markers) _) str = unwords [m, str]
embedCode (MkLitStyle _ _ _) str = str
||| Synonm for `embedCode`
export
relit : (specification : LiterateStyle)
-> (code : String)
-> String
relit = embedCode
-- --------------------------------------------------------------------- [ EOF ]
|
server <- function(input, output){
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins +1)
hist(x, breaks = bins, col= "#75AADB", border = "white",
xlab = "waiting time till next (in min)",
main = "histogram of waiting times")
})
}
|
module Parser where
import Data.Binary
import Data.Binary.Get
import qualified Data.ByteString.Lazy as BS
import Codec.Compression.GZip (decompress)
import Control.Monad
import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.Devel
import qualified Data.Vector as V
import Control.Monad.ST
type Pixel = Word8
type Image = V.Vector (Matrix Float)
type Label = Vector Float
decodeImages :: Get [Image]
decodeImages = do
mc <- getWord32be
guard (mc == 0x00000803)
[d1,d2,d3] <- many 3 getWord32be
guard (d2 == 28 && d3 == 28)
many d1 pic
where
pic :: Get Image
pic = do
bs <- getByteString (28*28)
return . V.singleton . reshape 28 . toVecDouble . fromByteString $ bs
toVecDouble :: Vector Pixel -> Vector Float
-- mapVectorM requires the monad be strict
-- so Identity monad shall not be used
toVecDouble v = runST $ mapVectorM (return . (/255) . fromIntegral) v
decodeLabels :: Get [Label]
decodeLabels = do
mc <- getWord32be
guard (mc == 0x00000801)
d1 <- getWord32be
many d1 lbl
where
lbl :: Get Label
lbl = do
v <- fromIntegral <$> (get :: Get Word8)
return $ fromList (replicate v 0 ++ [1] ++ replicate (9-v) 0)
many :: (Integral n, Monad m) => n -> m a -> m [a]
many cnt dec = sequence (replicate (fromIntegral cnt) dec)
trainingData :: IO ([Image], [Label])
trainingData = do
s <- decompress <$> BS.readFile "tdata/train-images-idx3-ubyte.gz"
t <- decompress <$> BS.readFile "tdata/train-labels-idx1-ubyte.gz"
return (runGet decodeImages s, runGet decodeLabels t)
testData :: IO ([Image], [Label])
testData = do
s <- decompress <$> BS.readFile "tdata/t10k-images-idx3-ubyte.gz"
t <- decompress <$> BS.readFile "tdata/t10k-labels-idx1-ubyte.gz"
return (runGet decodeImages s, runGet decodeLabels t)
|
subsection\<open>Simplified Variant with Simple Entailment in Logic K (Fig.~8 in \<^cite>\<open>"C85"\<close>)\<close>
theory SimpleVariantSE imports
HOML
MFilter
BaseDefs
begin
text\<open>Axiom's of new variant based on ultrafilters.\<close>
axiomatization where
A1': "\<lfloor>\<^bold>\<not>(\<P>(\<lambda>x.(x\<^bold>\<noteq>x)))\<rfloor>" and
A2'': "\<lfloor>\<^bold>\<forall>X Y.(((\<P> X) \<^bold>\<and> (X\<^bold>\<sqsubseteq>Y)) \<^bold>\<rightarrow> (\<P> Y))\<rfloor>" and
T2: "\<lfloor>\<P> \<G>\<rfloor>"
text\<open>Necessary existence of a Godlike entity.\<close>
theorem T6: "\<lfloor>\<^bold>\<box>(\<^bold>\<exists>\<^sup>E \<G>)\<rfloor>" using A1' A2'' T2 by blast
theorem T7: "\<lfloor>\<^bold>\<exists>\<^sup>E \<G>\<rfloor>" using A1' A2'' T2 by blast
text\<open>Possible existence of a Godlike: has counterodel.\<close>
lemma T3: "\<lfloor>\<^bold>\<diamond>(\<^bold>\<exists>\<^sup>E \<G>)\<rfloor>" nitpick oops \<comment>\<open>Countermodel\<close>
lemma T3': assumes T: "\<lfloor>\<^bold>\<forall>\<phi>.((\<^bold>\<box>\<phi>) \<^bold>\<rightarrow> \<phi>)\<rfloor>"
shows "\<lfloor>\<^bold>\<diamond>(\<^bold>\<exists>\<^sup>E \<G>)\<rfloor>"
using A1' A2'' T2 T by metis
end
|
import data.nat.basic
import tactic.linarith
import tactic.ring
namespace nat
lemma power_geq_1 {k n : ℕ} : (succ k)^n ≥ 1 := begin
induction n,
{ rw [pow_zero], exact le_refl _ },
{ rw [pow_succ], exact _root_.le_add_left n_ih }
end
lemma mul_left_cancel {a b c : ℕ} : a > 0 → a * b = a * c → b = c := λ pos eq, calc
b = b * a / a : symm (nat.mul_div_cancel _ pos)
... = a * b / a : by rw [mul_comm]
... = a * c / a : by rw [eq]
... = c * a / a : by rw [mul_comm]
... = c : nat.mul_div_cancel _ pos
lemma sub_add_from_add_sub : Π {a b c : ℕ}, a ≥ c -> b ≥ c -> a + (b - c) = (a - c) + b
| 0 b c a_ge_c b_ge_c := begin have : c = 0 := by linarith, simp [this] end
| (a+1) 0 c a_ge_c b_ge_c := begin have : c = 0 := by linarith, simp [this] end
| (a+1) (b+1) 0 a_ge_c b_ge_c := by simp
| (a+1) (b+1) (c+1) a_ge_c b_ge_c := begin
have a_ge_c : a ≥ c := lt_succ_iff.mp a_ge_c,
have b_ge_c : b ≥ c := lt_succ_iff.mp b_ge_c,
repeat { rw [add_one] },
repeat { rw [add_succ] <|> rw [succ_add] },
repeat { rw [succ_sub_succ] },
rw [sub_add_from_add_sub a_ge_c b_ge_c]
end
lemma pow_le_pow {a b k : ℕ} : a ≥ b -> a^k ≥ b^k := begin
intro gt,
induction k,
{ simp },
rw [pow_succ, pow_succ],
exact (mul_le_mul k_ih gt (by linarith) (by linarith))
end
lemma pow_ge_one {a k : ℕ} : a ≥ 1 -> a^k ≥ 1 := λ a_pos, calc
a^k ≥ 1^k : pow_le_pow a_pos
... = 1 : by simp
lemma prime_positive {p : ℕ} : prime p -> p > 0 := λ pr, have h : p ≥ 2 := prime.two_le pr, by linarith
lemma prime_pow_ge_one {p k : ℕ} : prime p -> p^k ≥ 1 :=
λ pr, pow_ge_one (prime_positive pr)
lemma pow_lt_pow_right {a k l : ℕ} : a > 1 -> k < l -> a^k < a^l := begin
intros a_big lt,
induction lt,
{ exact calc
a^k = 1 * a^k : symm (one_mul _)
... < a * a^k : mul_lt_mul a_big (refl _) (pow_ge_one (by linarith)) (by linarith)
... = a^k * a : mul_comm _ _
... = a^(k + 1) : by simp [pow_succ]},
exact calc
a^k = 1 * a^k : symm (one_mul _)
... < a * a^lt_b : mul_lt_mul a_big (by linarith) (pow_ge_one (by linarith)) (by linarith)
... = a^lt_b * a : mul_comm _ _
... = a^(lt_b + 1) : by simp [pow_succ]
end
lemma prod_lt_gt {a a' b b' : ℕ} : b > 0 -> a * b = a' * b' -> a < a' -> b > b' := begin
intros b_pos eq a_lt_a',
have : a' * b > a' * b' := calc
a' * b > a * b : mul_lt_mul_of_pos_right a_lt_a' b_pos
... = a' * b' : eq,
apply lt_of_mul_lt_mul_left this (zero_le _)
end
lemma prod_gt_lt {a a' b b' : ℕ} : a > 0 -> a * b = a' * b' -> b < b' -> a > a' := begin
rw [mul_comm a b, mul_comm a' b'],
apply prod_lt_gt
end
lemma pos_of_mul_pos {a b : ℕ} : a * b > 0 -> a > 0 := begin
cases a,
{ simp },
intros _,
exact succ_pos a
end
lemma pos_of_mul_pos_right {a b : ℕ} : a * b > 0 -> b > 0 := begin
cases b,
{ simp },
intros _,
exact succ_pos b
end
lemma pos_of_dvd_pos {a b : ℕ} : b > 0 -> a ∣ b -> a > 0 := begin
rintros gt ⟨k, prod⟩,
rw [prod] at gt,
apply pos_of_mul_pos gt,
end
lemma dvd_pow_succ {p k n : ℕ} : prime p -> n ∣ p^(k + 1) -> n = p^(k + 1) ∨ n ∣ p^k := begin
rintros pr divides,
obtain ⟨l , bound, pf⟩ := (dvd_prime_pow pr).1 divides,
rcases lt_trichotomy l (k+1) with h | h | h,
{ have : l ≤ k := by linarith,
apply or.inr,
apply (dvd_prime_pow pr).2,
finish },
{ apply or.inl,
rw [pf, h] },
have : p^(k + 1) > 0 := prime_pow_ge_one pr,
have : n ≤ p^(k + 1) := le_of_dvd this divides,
have : p^(k + 1) < p^(k + 1) := calc
p^(k + 1) < p^l : pow_lt_pow_right (prime.two_le pr) h
... = n : symm pf
... ≤ p^(k + 1) : this,
linarith
end
lemma coprime_gcd {a b c : ℕ} : coprime b c → coprime (gcd a b) (gcd a c) :=
coprime.coprime_dvd_left (gcd_dvd_right a b) ∘
coprime.coprime_dvd_right (gcd_dvd_right a c)
lemma prod_coprime_gcd {a b c : ℕ} : a > 0 -> coprime b c -> gcd a b * gcd a c = gcd a (b * c) := begin
intros a_pos coprime,
apply le_antisymm;
apply le_of_dvd,
{ exact gcd_pos_of_pos_left _ a_pos },
{ exact nat.coprime.mul_dvd_of_dvd_of_dvd (coprime_gcd coprime) (gcd_dvd_gcd_mul_right_right a b c) (gcd_dvd_gcd_mul_left_right a c b) },
{ exact (mul_lt_mul_left (gcd_pos_of_pos_left _ a_pos)).2 (gcd_pos_of_pos_left _ a_pos) },
{ exact gcd_mul_dvd_mul_gcd _ _ _ }
end
lemma prod_coprime_gcd_left {a b c : ℕ} : c > 0 -> coprime a b -> gcd a c * gcd b c = gcd (a * b) c := begin
rw [gcd_comm a c, gcd_comm b c, gcd_comm (a * b) c],
exact prod_coprime_gcd
end
open nat (succ)
@[simp]
lemma gcd_add {a b : ℕ} : nat.gcd a (a + b) = nat.gcd b a := begin
cases a,
{ simp },
cases b,
{ simp },
exact calc
nat.gcd (succ a) (succ a + succ b)
= nat.gcd (succ b % succ a) (succ a) : by rw [nat.gcd_succ, nat.add_mod_left]
... = nat.gcd (succ b) (succ a) : by rw [←nat.gcd_succ, nat.gcd_comm]
end
theorem coprime_sub_one {n : ℕ} : n > 0 -> coprime (n - 1) n := begin
intro n_pos,
cases n,
{ linarith },
exact calc
nat.gcd ((n + 1) - 1) (n + 1) = nat.gcd 1 n : by simp
... = 1 : nat.gcd_one_left _
end
end nat
|
Formal statement is: lemma measure_space_closed: assumes "measure_space \<Omega> M \<mu>" shows "M \<subseteq> Pow \<Omega>" Informal statement is: If $(\Omega, M, \mu)$ is a measure space, then $M \subseteq \mathcal{P}(\Omega)$.
|
\section{User Guide}
When using this model, the user should follow the setup procedure corresponding to his or her desired conversion described below. The procedures outline the required inputs and some recommended parameter values. \begin{itemize}
\item \textit{eclipseCondition}
\begin{itemize}
\item \textit{full} for full eclipse
\item \textit{partial} for partial eclipse
\item \textit{annular} for annular eclipse
\item \textit{none} for no eclipse
\end{itemize}
\item $\mu$ is recommended to be $3.86\text{e+}14$ $\frac{\text{m}^3}{\text{s}^2}$ for Earth.
\item \textit{UTCCalInit} is used in this test as \textit{2021 MAY 04 07:47:49.965 (UTC)} but can be any UTC time.
\item Keplerian orbital elements are given in Table \ref{tab:OrbElem} previously. These are just suggested values that are used for the test and can be varied. The module only accepts Cartesian vectors.
\begin{itemize}
\item To convert from orbital elements to Cartesian vectors, use the \textit{elem2rv} method from orbitalMotion
\end{itemize}
\item Planet Names
\begin{itemize}
\item \textit{venus}
\item \textit{earth}
\item \textit{mars barycenter}
\end{itemize}
\end{itemize}
\subsection{Variable Definition and Code Description}
The variables in Table \ref{tabular:vars} are available for user input. Variables used by the module but not available to the user are not mentioned here. Variables with default settings do not necessarily need to be changed by the user, but may be.
\begin{table}[H]
\caption{Definition and Explanation of Variables Used.}
\label{tab:errortol}
\centering \fontsize{10}{10}\selectfont
\begin{tabular}{| m{3.4cm}| m{3cm} | m{2.5cm} | m{6cm}|} % Column formatting,
\hline
\textbf{Variable} & \textbf{LaTeX Equivalent} & \textbf{Variable Type} & \textbf{Notes} \\ \hline
r$_BN_N$ &$\bm{r}$ & double & [m]Default setting: 0.0. Spacecract position vector used as an input.\\ \hline
$\mu$ & $\mu$ & double & [m3/s2] Required Input. This is the gravitational parameter of the body. Replaces the product of Earth's gravitational force and mass for this test..\\
\hline
a & $a$ & double & [km] Required Input. The semimajor axis of the body's orbit.\\
\hline
e & $e$ & double & Required Input. The eccentricity of the body's orbit.\\
\hline
i & $i$ & double & [rad] Required Input. The inclination of the body's orbit\\
\hline
Omega & $\Omega$ & double & [rad] Required Input. The ascending node of the body's orbit. \\
\hline
omega & $\omega$ & double & [rad] Required Input. The argument of periapses of the body's orbit. \\
\hline
f & $f$ & double & [rad] Required Input. The true anomaly of the body's orbit \\
\hline
spiceObject.UTCCalInit & \textit{UTCCalInit} & str & Required Input. A UTC time that provides the means of obtaining planet and sun state data. \\
\hline
Planet Names & N/A & str & Required Input. Identifies the planets desired to be evaluated.\\
\hline
\end{tabular}
\label{tabular:vars}
\end{table}
\begin{thebibliography}{1}
\bibitem{bib:1}
Montenbruck, O., and Gill, E., \textit{Satellite Orbits Models, Methods and Applications}, 1st ed. Berlin: Springer Berlin, 2000
\end{thebibliography}
|
url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
wordlist = open(readlines, download(url))
wsort(word::AbstractString) = join(sort(collect(word)))
function anagram(wordlist::Vector{<:AbstractString})
dict = Dict{String, Set{String}}()
for word in wordlist
sorted = wsort(word)
push!(get!(dict, sorted, Set{String}()), word)
end
wcnt = maximum(length, values(dict))
return collect(Iterators.filter((y) -> length(y) == wcnt, values(dict)))
end
println.(anagram(wordlist))
|
using FastDMTransform, NPZ, Test, Statistics
function standardize(A; dims=1)
μ = mean(A; dims=dims)
σ = std(A; mean=μ, dims=dims)
return @. (A - μ) / σ
end
@testset "FastDMTransform.jl" begin
pulse = npzread("../pulse.npz")
dedispersed = standardize(npzread("../dedispersed.npz"))
dedisped = standardize(fdmt(pulse, 1500, 1200, 1e-3, 0, 2000))
@test findmax(dedisped) == findmax(dedispersed)
end
|
How Bruker’s innovative methods and non-destructive analytical techniques help to protect and preserve artifacts and historical monuments all over the world.
Bruker’s art conservation solutions are perfectly suited to analyze artifacts, help to restore objects without destroying their original substance and determine the composition of materials used for production. Bruker offers mobile Micro-XRF and handheld XRF solutions for non-destructive in-situ analysis as well as innovative FT-IR and Raman solutions for optimal sample visualization and sample collection. Bruker’s instruments enable a reliable and fast analysis of ceramics, paintings, photographs, glass, obsidians, bronzes, coppers and alloys.
Precious artifacts and historical monument are often affected by decay and through environmental pollution, vandalism, climate change, lack of budgets or just simple neglect.
Conservators around the world are working day by day to save the world’s heritage for the future.
Researching artifacts to help see the big picture.
|
State Before: n : ℕ
h : n < size
⊢ Nat.isValidChar ↑(UInt32.ofNat n).val State After: n : ℕ
h : n < size
⊢ Nat.isValidChar n
n : ℕ
h : n < size
⊢ n < UInt32.size Tactic: rw [UInt32.val_eq_of_lt] State Before: n : ℕ
h : n < size
⊢ Nat.isValidChar n
n : ℕ
h : n < size
⊢ n < UInt32.size State After: n : ℕ
h : n < size
⊢ n < UInt32.size Tactic: exact Or.inl $ Nat.lt_trans h $ by decide State Before: n : ℕ
h : n < size
⊢ n < UInt32.size State After: no goals Tactic: exact Nat.lt_trans h $ by decide State Before: n : ℕ
h : n < size
⊢ size < 55296 State After: no goals Tactic: decide State Before: n : ℕ
h : n < size
⊢ size < UInt32.size State After: no goals Tactic: decide
|
(*
Copyright 2014 Cornell University
Copyright 2015 Cornell University
Copyright 2016 Cornell University
Copyright 2017 Cornell University
This file is part of VPrl (the Verified Nuprl project).
VPrl 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.
VPrl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VPrl. If not, see <http://www.gnu.org/licenses/>.
Websites: http://nuprl.org/html/verification/
http://nuprl.org/html/Nuprl2Coq
https://github.com/vrahli/NuprlInCoq
Authors: Vincent Rahli
*)
Require Export sequents2.
Require Export sequents_lib.
Require Export sequents_tacs.
Require Export sequents_equality.
Require Export per_props_uni.
Require Export per_props_halts.
Definition rule_universe_equality_concl {o} (H : @bhyps o) i j : baresequent :=
mk_baresequent H (mk_conclax (mk_member (mk_uni i) (mk_uni j))).
(*
H |- Type(i) = Type(i) in Type(j)
By universeEquality (i < j)
*)
Definition rule_universe_equality {o}
(H : @bhyps o)
(i j : nat) :=
mk_rule
(rule_universe_equality_concl H i j)
[]
[].
Lemma rule_universe_equality_true3 {o} :
forall lib (H : @bhyps o) (i j : nat),
i < j -> rule_true3 lib (rule_universe_equality H i j).
Proof.
intros.
unfold rule_universe_equality, rule_true3, wf_bseq, closed_type_baresequent, closed_extract_baresequent; simpl.
intros; repnd.
clear cargs hyps.
(* We prove the well-formedness of things *)
destseq; allsimpl; proof_irr; GC.
assert (wf_csequent (H) ||- (mk_conclax (mk_member (mk_uni i) (mk_uni j)))) as wfc.
{ unfold wf_csequent, closed_type, closed_extract, wf_sequent, wf_concl; simpl.
dwfseq.
rw @vswf_hypotheses_nil_eq.
dands; tcsp. }
exists wfc.
unfold wf_csequent, wf_sequent, wf_concl in wfc; allsimpl; repnd; proof_irr; GC.
(* We prove some simple facts on our sequents *)
(* done with proving these simple facts *)
(* we now start proving the sequent *)
vr_seq_true.
lsubst_tac.
pose proof (teq_and_member_if_member lib (mk_uni j) (mk_uni i) s1 s2 H wT wt ct ct0 cT cT0) as q.
rw <- @member_member_iff.
lsubst_tac.
apply q; auto.
{ apply tequality_mkc_uni. }
clear dependent s1; clear dependent s2.
introv hf sim.
lsubst_tac.
apply uni_in_uni; auto.
Qed.
Lemma rule_universe_equality_true_ext_lib {o} :
forall lib (H : @bhyps o) (i j : nat),
i < j -> rule_true_ext_lib lib (rule_universe_equality H i j).
Proof.
introv ltij.
apply rule_true3_implies_rule_true_ext_lib.
introv.
apply rule_universe_equality_true3; auto.
Qed.
Definition rule_cumulativity_concl {o} (H : @bhyps o) T j :=
mk_baresequent H (mk_conclax (mk_member T (mk_uni j))).
Definition rule_cumulativity_hyp {o} (H : @bhyps o) T i e :=
mk_baresequent H (mk_concl (mk_member T (mk_uni i)) e).
(*
H |- T in Type(j)
By cumulativity (i < j)
H |- T in Type(i)
*)
Definition rule_cumulativity {o}
(H : @bhyps o)
(T e : NTerm)
(i j : nat) :=
mk_rule
(rule_cumulativity_concl H T j)
[ rule_cumulativity_hyp H T i e ]
[].
Lemma rule_cumulativity_true3 {o} :
forall lib (H : @bhyps o) T e (i j : nat),
i <= j -> rule_true3 lib (rule_cumulativity H T e i j).
Proof.
intros.
unfold rule_cumulativity, rule_true3, wf_bseq, closed_type_baresequent, closed_extract_baresequent; simpl.
intros; repnd.
clear cargs.
(* We prove the well-formedness of things *)
destseq; allsimpl.
dLin_hyp; exrepnd.
destruct Hyp as [ ws1 hyp1 ].
destseq; allsimpl; proof_irr; GC.
assert (wf_csequent (H) ||- (mk_conclax (mk_member T (mk_uni j)))) as wfc.
{ clear hyp1.
unfold wf_csequent, closed_type, closed_extract, wf_sequent, wf_concl; simpl.
dwfseq.
rw @vswf_hypotheses_nil_eq.
dands; tcsp.
introv xx; allrw in_app_iff; tcsp. }
exists wfc.
unfold wf_csequent, wf_sequent, wf_concl in wfc; allsimpl; repnd; proof_irr; GC.
(* We prove some simple facts on our sequents *)
(* done with proving these simple facts *)
(* we now start proving the sequent *)
vr_seq_true.
lsubst_tac.
rw <- @member_member_iff.
pose proof (teq_and_member_if_member lib (mk_uni j) T s1 s2 H wT wt ct0 ct1 cT cT0) as q.
lsubst_tac.
apply q; auto.
{ apply tequality_mkc_uni. }
clear dependent s1; clear dependent s2.
introv hf sim.
vr_seq_true in hyp1.
pose proof (hyp1 s1 s2 hf sim) as q; clear hyp1; exrepnd.
lsubst_tac.
apply member_if_inhabited in q1.
apply tequality_mkc_member in q0; repnd; clear q2.
dimp q0. eapply cumulativity;eauto.
Qed.
Lemma rule_cumulativity_true_ext_lib {o} :
forall lib (H : @bhyps o) T e (i j : nat),
i <= j -> rule_true_ext_lib lib (rule_cumulativity H T e i j).
Proof.
introv ltij.
apply rule_true3_implies_rule_true_ext_lib.
introv.
apply rule_cumulativity_true3; auto.
Qed.
Lemma rule_cumulativity_wf2 {o} :
forall (H : @bhyps o) T e (i j : nat),
wf_rule2 (rule_cumulativity H T e i j).
Proof.
introv wf k.
allsimpl; repndors; subst; tcsp;
allunfold @wf_bseq; repnd; allsimpl; wfseq.
Qed.
(*
H |- halts(t)
By callbyvalueType
H |- t in Type(i)
*)
Definition rule_callbyvalue_type {o}
(H : @bhyps o)
(t : NTerm)
(i : nat) :=
mk_rule
(mk_baresequent H (mk_conclax (mk_halts t)))
[
mk_baresequent H (mk_conclax (mk_member t (mk_uni i)))
]
[].
Lemma rule_callbyvalue_type_true3 {o} :
forall lib (H : @bhyps o) t i,
rule_true3 lib (rule_callbyvalue_type H t i).
Proof.
intros.
unfold rule_callbyvalue_type, rule_true3, wf_bseq, closed_type_baresequent, closed_extract_baresequent; simpl.
intros; repnd.
clear cargs.
(* We prove the well-formedness of things *)
destseq; allsimpl.
dLin_hyp; exrepnd.
destruct Hyp as [ ws1 hyp1 ].
destseq; allsimpl; proof_irr; GC.
match goal with
| [ |- sequent_true2 _ ?s ] => assert (wf_csequent s) as wfc
end.
{ clear hyp1.
unfold wf_csequent, closed_type, closed_extract, wf_sequent, wf_concl; simpl.
dwfseq.
rw @vswf_hypotheses_nil_eq.
dands; tcsp. }
exists wfc.
unfold wf_csequent, wf_sequent, wf_concl in wfc; allsimpl; repnd; proof_irr; GC.
(* We prove some simple facts on our sequents *)
(* done with proving these simple facts *)
(* we now start proving the sequent *)
vr_seq_true.
vr_seq_true in hyp1.
pose proof (hyp1 s1 s2 eqh sim) as h; clear hyp1; exrepnd.
lsubst_tac.
rw <- @member_member_iff in h1.
repeat (rw <- @fold_mkc_member in h0).
apply equality_commutes in h0; auto.
clear h1.
apply equality_in_uni in h0.
applydup @tequality_refl in h0.
apply tequality_sym in h0.
apply tequality_refl in h0.
apply types_converge in h0.
apply types_converge in h1.
spcast.
rw @equality_in_mkc_halts_ax.
eapply teq_and_eq_if_halts; eauto; spcast; auto.
Qed.
|
import category_theory.isomorphism category_theory.concrete_category
import category_theory.limits.shapes.equalizers
import category_theory.endomorphism
import category_theory.category.preorder data.fin.basic
import category_theory.arrow
import category_theory.category.Cat
import category_theory.limits.presheaf
import category_theory.limits.comma
-- Should not be here...
lemma nat.iterate_succ {α : Type*} (f : α → α)
: ∀ (n : ℕ) (x0 : α), f^[n + 1] x0 = f (f^[n] x0)
| 0 x0 := rfl
| (n + 1) x0 := nat.iterate_succ n (f x0)
namespace category_theory
open category_theory category_theory.limits
local attribute [instance]
category_theory.concrete_category.has_coe_to_sort
category_theory.concrete_category.has_coe_to_fun
lemma iso.eq_app_inv_of_app_hom_eq
{C : Type*} [category C] [concrete_category C] {X Y : C} (f : X ≅ Y)
{x : X} {y : Y} (H : f.hom x = y) : x = f.inv y :=
begin
transitivity f.inv (f.hom x),
{ rw [← comp_apply, iso.hom_inv_id, id_apply] },
{ rw H }
end
lemma is_iso.eq_app_inv_of_app_hom_eq
{C : Type*} [category C] [concrete_category C] {X Y : C} (f : X ⟶ Y) [is_iso f]
{x : X} {y : Y} : f x = y → x = inv f y :=
iso.eq_app_inv_of_app_hom_eq (as_iso f)
theorem is_iso.cancel_iso_inv_left {C : Type*} [category C] {X Y Z : C}
(f : Y ⟶ X) [is_iso f] : ∀ (g g' : Y ⟶ Z), inv f ≫ g = inv f ≫ g' ↔ g = g' :=
iso.cancel_iso_inv_left (as_iso f)
lemma parallel_pair_comp
{C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)
: parallel_pair f g ⋙ F = parallel_pair (F.map f) (F.map g) :=
begin
apply category_theory.functor.hext,
{ intro u, cases u; refl },
{ intros u v i, cases u; cases v; cases i,
all_goals { simp },
all_goals { refl } },
end
def parallel_pair_comp.cocone_comp_to_cocone_pair
{C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)
(c : cocone (parallel_pair f g ⋙ F)) : cocone (parallel_pair (F.map f) (F.map g)) := {
X := c.X,
ι := eq_to_hom (parallel_pair_comp F f g).symm ≫ c.ι
}
def parallel_pair_comp.cocone_pair_to_cocone_comp
{C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)
(c : cocone (parallel_pair (F.map f) (F.map g))) : cocone (parallel_pair f g ⋙ F) := {
X := c.X,
ι := eq_to_hom (parallel_pair_comp F f g) ≫ c.ι
}
def parallel_pair_comp.is_colimit_comp_to_is_colimit_pair
{C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)
(c : cocone (parallel_pair f g ⋙ F)) (hc : is_colimit c)
: is_colimit (parallel_pair_comp.cocone_comp_to_cocone_pair F f g c) := {
desc := λ s, hc.desc (parallel_pair_comp.cocone_pair_to_cocone_comp F f g s),
fac' := by { intros, refine eq.trans (category.assoc _ _ _) _, rw hc.fac',
refine eq.trans (category.assoc _ _ _).symm _, simp },
uniq' := λ s m h, hc.uniq' (parallel_pair_comp.cocone_pair_to_cocone_comp F f g s) m
(λ u, by { refine eq.trans _ (congr_arg (λ w, nat_trans.app (eq_to_hom (parallel_pair_comp F f g)) u ≫ w) (h u)),
refine eq.trans _ (category.assoc _ _ _),
refine congr_arg (λ w, w ≫ m) _,
refine eq.trans _ (category.assoc _ _ _),
simp }) }
def parallel_pair_comp.is_colimit_pair_to_is_colimit_comp
{C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)
(c : cocone (parallel_pair (F.map f) (F.map g))) (hc : is_colimit c)
: is_colimit (parallel_pair_comp.cocone_pair_to_cocone_comp F f g c) := {
desc := λ s, hc.desc (parallel_pair_comp.cocone_comp_to_cocone_pair F f g s),
fac' := by { intros, refine eq.trans (category.assoc _ _ _) _, rw hc.fac',
refine eq.trans (category.assoc _ _ _).symm _, simp },
uniq' := λ s m h, hc.uniq' (parallel_pair_comp.cocone_comp_to_cocone_pair F f g s) m
(λ u, by { refine eq.trans _ (congr_arg (λ w, nat_trans.app (eq_to_hom (parallel_pair_comp F f g).symm) u ≫ w) (h u)),
refine eq.trans _ (category.assoc _ _ _),
refine congr_arg (λ w, w ≫ m) _,
refine eq.trans _ (category.assoc _ _ _),
simp }) }
lemma concrete_category.pow_eq_iter {C : Type*} [category C] [concrete_category C] {X : C} (f : X ⟶ X)
(k : ℕ) : @coe_fn _ _ concrete_category.has_coe_to_fun (f ^ k : End X) = (f^[k]) :=
begin
ext x,
induction k with k ih,
{ simp },
{ rw nat.iterate_succ, rw ← npow_eq_pow, dsimp [monoid.npow, npow_rec], simp, congr, exact ih }
end
universe u
def restricted_yoneda_functor {C : Type u} [small_category C] {ℰ : Type*} [category ℰ]
: (C ⥤ ℰ)ᵒᵖ ⥤ ℰ ⥤ Cᵒᵖ ⥤ Type u :=
category_theory.functor.op_hom _ _
⋙ whiskering_left Cᵒᵖ ℰᵒᵖ (Type u)
⋙ (whiskering_left _ _ _).obj yoneda
lemma restricted_yoneda_functor_obj {C : Type u} [small_category C] {ℰ : Type*} [category ℰ]
(A : C ⥤ ℰ) : restricted_yoneda_functor.obj (opposite.op A) = colimit_adj.restricted_yoneda A := rfl
def functor.map_cone_comp {J C D E : Type*} [category J] [category C] [category D] [category E]
(K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E)
: cones.functoriality K (F ⋙ G)
≅ cones.functoriality K F
⋙ cones.functoriality (K ⋙ F) G
⋙ cones.postcompose (functor.associator K F G).hom :=
begin
refine nat_iso.of_components _ _,
{ intro c, refine category_theory.limits.cones.ext (iso.refl _) _,
intro j, symmetry, exact eq.trans (category.id_comp _) (category.comp_id _) },
{ intros c c' f, ext,
exact eq.trans (category.comp_id _) (category.id_comp _).symm }
end
def functor.map_cone_map_cone {J C D E : Type*} [category J] [category C] [category D] [category E]
(K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E)
: cones.functoriality K (F ⋙ G) ⋙ cones.postcompose (functor.associator K F G).inv
≅ cones.functoriality K F ⋙ cones.functoriality (K ⋙ F) G :=
((whiskering_right _ _ _).obj (cones.postcompose (functor.associator K F G).inv)).map_iso
(functor.map_cone_comp K F G)
≪≫ ((whiskering_right _ _ _).obj (cones.postcompose (functor.associator K F G).inv)).map_iso
(functor.associator (cones.functoriality K F) (cones.functoriality (K ⋙ F) G)
(cones.postcompose (K.associator F G).hom)).symm
≪≫ (functor.associator _ _ _)
≪≫ ((whiskering_left _ _ _).obj _).map_iso
((limits.cones.postcompose_comp _ _).symm ≪≫
by { rw (K.associator F G).hom_inv_id, exact limits.cones.postcompose_id })
≪≫ (functor.right_unitor _)
def functor.map_cone_comp' {J C D E : Type*} [category J] [category C] [category D] [category E]
(K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E) (c : cone K)
: (F ⋙ G).map_cone c
≅ (cones.postcompose (functor.associator K F G).hom).obj (G.map_cone (F.map_cone c)) :=
((evaluation _ _).obj c).map_iso (functor.map_cone_comp K F G)
def functor.map_cone_map_cone' {J C D E : Type*} [category J] [category C] [category D] [category E]
(K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E) (c : cone K)
: (cones.postcompose (functor.associator K F G).inv).obj ((F ⋙ G).map_cone c)
≅ G.map_cone (F.map_cone c) :=
((evaluation _ _).obj c).map_iso (functor.map_cone_map_cone K F G)
def functor.map_cocone_comp {J C D E : Type*} [category J] [category C] [category D] [category E]
(K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E)
: cocones.functoriality K (F ⋙ G)
≅ cocones.functoriality K F
⋙ cocones.functoriality (K ⋙ F) G
⋙ cocones.precompose (functor.associator K F G).hom :=
begin
refine nat_iso.of_components _ _,
{ intro c, refine category_theory.limits.cocones.ext (iso.refl _) _,
intro j,
exact eq.trans (category.comp_id _) (category.id_comp _).symm },
{ intros c c' f, ext,
exact eq.trans (category.comp_id _) (category.id_comp _).symm }
end
def functor.map_cocone_map_cocone {J C D E : Type*} [category J] [category C] [category D] [category E]
(K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E)
: cocones.functoriality K (F ⋙ G) ⋙ cocones.precompose (functor.associator K F G).inv
≅ cocones.functoriality K F ⋙ cocones.functoriality (K ⋙ F) G :=
((whiskering_right _ _ _).obj (cocones.precompose (functor.associator K F G).inv)).map_iso
(functor.map_cocone_comp K F G)
≪≫ ((whiskering_right _ _ _).obj (cocones.precompose (functor.associator K F G).inv)).map_iso
(functor.associator (cocones.functoriality K F) (cocones.functoriality (K ⋙ F) G)
(cocones.precompose (K.associator F G).hom)).symm
≪≫ (functor.associator _ _ _)
≪≫ ((whiskering_left _ _ _).obj _).map_iso
((limits.cocones.precompose_comp _ _).symm ≪≫
by { rw (K.associator F G).inv_hom_id, exact limits.cocones.precompose_id })
≪≫ (functor.right_unitor _)
def functor.map_cocone_comp' {J C D E : Type*} [category J] [category C] [category D] [category E]
(K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E) (c : cocone K)
: (F ⋙ G).map_cocone c
≅ (cocones.precompose (functor.associator K F G).hom).obj (G.map_cocone (F.map_cocone c)) :=
((evaluation _ _).obj c).map_iso (functor.map_cocone_comp K F G)
def functor.map_cocone_map_cocone' {J C D E : Type*} [category J] [category C] [category D]
[category E] (K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E) (c : cocone K)
: (cocones.precompose (functor.associator K F G).inv).obj ((F ⋙ G).map_cocone c)
≅ G.map_cocone (F.map_cocone c) :=
((evaluation _ _).obj c).map_iso (functor.map_cocone_map_cocone K F G)
def category_theory.limits.preserves_limits_of_equiv_domain {C : Type*} [category C]
{D : Type*} [category D] {J : Type*} [category J] {K : J ⥤ C}
{C' : Type*} [category C'] (F : C ⥤ D) (e : C ≌ C')
(h : preserves_limit (K ⋙ e.functor) (e.inverse ⋙ F))
: preserves_limit K F :=
begin
constructor, intros c hc,
let α : K ⋙ F ≅ (K ⋙ e.functor) ⋙ (e.inverse ⋙ F) :=
calc K ⋙ F ≅ K ⋙ (𝟭 C ⋙ F) : ((whiskering_left _ _ _).obj K).map_iso F.left_unitor.symm
... ≅ K ⋙ ((e.functor ⋙ e.inverse) ⋙ F) : ((whiskering_left _ _ _).obj K).map_iso
(((whiskering_right _ _ _).obj F).map_iso
e.unit_iso)
... ≅ K ⋙ (e.functor ⋙ (e.inverse ⋙ F)) : ((whiskering_left _ _ _).obj K).map_iso
(functor.associator _ _ _)
... ≅ (K ⋙ e.functor) ⋙ (e.inverse ⋙ F) : functor.associator _ _ _,
refine is_limit.equiv_of_nat_iso_of_iso α.symm
((e.inverse ⋙ F).map_cone (e.functor.map_cone c))
(F.map_cone c) _ _,
{ ext, swap, { exact F.map_iso (e.unit_iso.app c.X).symm },
{ dsimp,
refine eq.trans (congr_arg _ (category.id_comp _))
(eq.trans (congr_arg _ (category.id_comp _))
(eq.trans (congr_arg _ (category.comp_id _)) _)),
rw [← F.map_comp, ← F.map_comp],
refine congr_arg _ _,
rw [← functor.comp_map],
apply e.unit_iso.inv.naturality } },
{ destruct h, intros h' _, refine h' _,
destruct adjunction.is_equivalence_preserves_limits e.functor, intros h'' _,
destruct h'', intros h''' _, destruct @h''' K, intros H _,
exact H hc, }
end.
def category_theory.limits.preserves_colimits_of_equiv_domain {C : Type*} [category C]
{D : Type*} [category D] {J : Type*} [category J] {K : J ⥤ C}
{C' : Type*} [category C'] (F : C ⥤ D) (e : C ≌ C')
(h : preserves_colimit (K ⋙ e.functor) (e.inverse ⋙ F))
: preserves_colimit K F :=
begin
constructor, intros c hc,
let α : K ⋙ F ≅ (K ⋙ e.functor) ⋙ (e.inverse ⋙ F) :=
calc K ⋙ F ≅ K ⋙ (𝟭 C ⋙ F) : ((whiskering_left _ _ _).obj K).map_iso F.left_unitor.symm
... ≅ K ⋙ ((e.functor ⋙ e.inverse) ⋙ F) : ((whiskering_left _ _ _).obj K).map_iso
(((whiskering_right _ _ _).obj F).map_iso
e.unit_iso)
... ≅ K ⋙ (e.functor ⋙ (e.inverse ⋙ F)) : ((whiskering_left _ _ _).obj K).map_iso
(functor.associator _ _ _)
... ≅ (K ⋙ e.functor) ⋙ (e.inverse ⋙ F) : functor.associator _ _ _,
refine is_colimit.equiv_of_nat_iso_of_iso α.symm
((e.inverse ⋙ F).map_cocone (e.functor.map_cocone c))
(F.map_cocone c) _ _,
{ ext, swap, { exact F.map_iso (e.unit_iso.app c.X).symm },
{ dsimp,
refine eq.trans (congr_arg2 _ (congr_arg2 _ (category.comp_id _) rfl) rfl) _,
refine eq.trans (congr_arg2 _ (congr_arg2 _ (category.comp_id _) rfl) rfl) _,
refine eq.trans (congr_arg2 _ (congr_arg2 _ (category.id_comp _) rfl) rfl) _,
rw [← F.map_comp, ← F.map_comp],
refine congr_arg _ _,
rw [← functor.comp_map],
rw ← e.unit_iso.hom.naturality, simp } },
{ destruct h, intros h' _, refine h' _,
destruct adjunction.is_equivalence_preserves_colimits e.functor, intros h'' _,
destruct h'', intros h''' _, destruct @h''' K, intros H _,
exact H hc, }
end.
def category_theory.limits.preserves_colimits_of_equiv_codomain {C : Type*} [category C]
{D : Type*} [category D] {J : Type*} [category J] {K : J ⥤ C}
{D' : Type*} [category D'] (F : C ⥤ D) (e : D ≌ D')
(h : preserves_colimit K (F ⋙ e.functor))
: preserves_colimit K F :=
@limits.preserves_colimit_of_nat_iso _ _ _ _ _ _ _ _ _
(functor.associator _ _ _ ≪≫ ((whiskering_left _ _ _).obj F).map_iso e.unit_iso.symm
≪≫ functor.right_unitor _)
(@limits.comp_preserves_colimit C _ D' _ J _ K D _ (F ⋙ e.functor) e.inverse h _)
def category_theory.iso_to_equiv {C : Type*} [category C] {D : Type*} [category D]
(F : Cat.of C ≅ Cat.of D) : C ≌ D :=
⟨F.hom, F.inv, eq_to_iso (F.hom_inv_id.symm), eq_to_iso (F.inv_hom_id),
by { intro, simp, rw category_theory.eq_to_hom_map, simp, refl }⟩.
lemma colimit_iso_colimit_cocone_desc {J C : Type*} [category J] [category C]
(F : J ⥤ C) [has_colimit F] (c : colimit_cocone F) (c' : cocone F)
: (colimit.iso_colimit_cocone c).inv ≫ colimit.desc F c' = c.is_colimit.desc c' :=
by { apply c.is_colimit.hom_ext, intro j, simp }
-- universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄
-- I think the universe levels are borked :(
-- def comma.cocone_of_preserves_is_colimit'
-- {J : Type u₁} [small_category.{u₁} J] {A : Type u₂}
-- [category.{(max u₁ u₂) u₂} A] {B : Type u₃}
-- [category.{(max u₁ u₃) u₃} B] {T : Type u₄}
-- [category.{(max u₁ u₄) u₄} T] {L : A ⥤ T} {R : B ⥤ T}
-- (F : J ⥤ comma L R)
-- [preserves_colimit (F ⋙ comma.fst L R) L]
-- {c₁ : cocone (F ⋙ comma.fst L R)} (t₁ : is_colimit c₁)
-- {c₂ : cocone (F ⋙ comma.snd L R)} (t₂ : is_colimit c₂) :
-- is_colimit (comma.cocone_of_preserves.{u₁} F t₁ c₂) :=
-- { desc := λ s,
-- { left := t₁.desc ((fst L R).map_cocone s),
-- right := t₂.desc ((snd L R).map_cocone s),
-- w' := (is_colimit_of_preserves L t₁).hom_ext $ λ j,
-- begin
-- rw [cocone_of_preserves_X_hom, (is_colimit_of_preserves L t₁).fac_assoc,
-- colimit_auxiliary_cocone_ι_app, assoc, ←R.map_comp, t₂.fac, L.map_cocone_ι_app,
-- ←L.map_comp_assoc, t₁.fac],
-- exact (s.ι.app j).w,
-- end },
-- uniq' := λ s m w, comma_morphism.ext _ _
-- (t₁.uniq ((fst L R).map_cocone s) _ (by simp [←w]))
-- (t₂.uniq ((snd L R).map_cocone s) _ (by simp [←w])) }
end category_theory
|
# 2D Stokes Solver
$\newcommand{\dd}{\,{\rm d}}$
$\newcommand{\uu}{\mathbf{u}}$
$\newcommand{\ff}{\mathbf{f}}$
$\newcommand{\Div}{\nabla \cdot}$
We consider now the Stokes problem for the steady-state modelling of an incompressible fluid
\begin{align}
\left\{
\begin{array}{rl}
- \nabla^2 \uu + \nabla p = \ff & \mbox{in} ~ \Omega, \\
\Div \uu = 0 & \mbox{in} ~ \Omega, \\
\uu = 0 & \mbox{on} ~ \partial \Omega,
\end{array}
\right.
\label{eq:stokes}
\end{align}
## First mixed formulation of the Stokes problem
For the variational formulation, we take the dot product of the first equation with $v$ and integrate over the whole domain
$$\int_{\Omega} (-\Delta \mathbf{u} + \nabla p)\cdot \mathbf{v} \dd \mathbf{x}
=\int_{\Omega}\nabla \mathbf{u}:\nabla \mathbf{v} \dd \mathbf{x} + \int_{\Omega} \nabla p \cdot \mathbf{v} \dd \mathbf{x}
= \int_{\Omega} \mathbf{f}\cdot \mathbf{v} \dd \mathbf{x}$$
The integration by parts is performed component by component. We impose the essential boundary condition $ \mathbf{v}=0$ on $\partial\Omega$, and we denote by
$$\int_{\Omega}\nabla \mathbf{u}:\nabla \mathbf{v} \dd \mathbf{x} =\sum_{i=1}^3 \int_{\Omega}\nabla u_i\cdot\nabla v_i \dd \mathbf{x} =\sum_{i,j=1}^3 \int_{\Omega}\partial_j u_i\partial_j v_i \dd \mathbf{x} .$$
We now need to deal with the constraint $\nabla\cdot \mathbf{u}=0$. The theoretical framework for saddle point problems requires that the corresponding bilinear form is the same as the second one appearing in the first part of the variational formulation. To this aim we multiply $\nabla\cdot \mathbf{u}=0$ by a scalar test function (which will be associated to $p$) and integrate on the full domain, with an integration by parts in order to get the same bilinear form as in the first equation
$$\int_{\Omega} \nabla\cdot \mathbf{u} \,q \dd \mathbf{x}= - \int_{\Omega} \mathbf{u}\cdot \nabla q\dd \mathbf{x}=0,$$
using that $q=0$ on the boundary as an essential boundary condition.
We finally obtain the mixed variational formulation:
---
Find $( \mathbf{u},p)\in H^1_0(\Omega)^3\times H^1_0(\Omega)$ such that
\begin{align}
\left\{
\begin{array}{llll}
\int_{\Omega}\nabla \mathbf{u}:\nabla \mathbf{v} \dd \mathbf{x} &+ \int_{\Omega} \nabla p \cdot \mathbf{v} \dd \mathbf{x}
&= \int_{\Omega} \mathbf{f}\cdot \mathbf{v} \dd \mathbf{x}, & \forall \mathbf{v}\in H_0^1(\Omega)^3 \\
\int_{\Omega} \mathbf{u}\cdot \nabla q\dd \mathbf{x} & &=0, & \forall p\in H^1_0(\Omega)
\end{array}
\right.
\label{eq:abs_var_mixed_stokes_1}
\end{align}
---
## Second mixed formulation of the Stokes problem
Another possibility to obtained a well posed variational formulation, is to integrate by parts the
$ \int_{\Omega} \nabla p \cdot \mathbf{v} \dd \mathbf{x}$ term in the first formulation:
$$ \int_{\Omega} \nabla p \cdot \mathbf{v} \dd \mathbf{x} = - \int_{\Omega} p \nabla \cdot \mathbf{v} \dd \mathbf{x}
+ \int_{\partial\Omega} p \mathbf{v} \cdot \mathbf{n}\dd \sigma=
-\int_{\Omega} p \,\nabla \cdot \mathbf{v} \dd \mathbf{x} ,$$
using here $p=0$ as a natural boundary condition. Note that in the other variational formulation the same boundary condition was essential. In this case, for the second variational formulation, we just multiply $\nabla\cdot \mathbf{u}=0$ by $q$ and integrate. No integration by parts is needed in this case.
$$\int_{\Omega} \nabla \cdot \mathbf{u}\, q \dd \mathbf{x} =0.$$
This then leads to the following variational formulation:
---
Find $( \mathbf{u},p)\in H^1(\Omega)^3\times L^2(\Omega)$ such that
\begin{align}
\left\{
\begin{array}{llll}
\int_{\Omega}\nabla \mathbf{u}:\nabla \mathbf{v} \dd \mathbf{x} &- \int_{\Omega} p \, \nabla\cdot \mathbf{v} \dd \mathbf{x}
&= \int_{\Omega} \mathbf{f}\cdot \mathbf{v} \dd \mathbf{x}, &\forall \mathbf{v}\in H^1(\Omega)^3
\\
\int_{\Omega} \nabla\cdot\mathbf{u}\, q\dd \mathbf{x} & &=0, &\forall q\in L^2(\Omega)
\end{array}
\right.
\label{eq:abs_var_mixed_stokes_2}
\end{align}
---
```python
import numpy as np
from sympy import pi, cos, sin, sqrt, Matrix, Tuple, lambdify
from scipy.sparse.linalg import spsolve
from scipy.sparse.linalg import gmres as sp_gmres
from scipy.sparse.linalg import minres as sp_minres
from scipy.sparse.linalg import cg as sp_cg
from scipy.sparse.linalg import bicg as sp_bicg
from scipy.sparse.linalg import bicgstab as sp_bicgstab
from sympde.calculus import grad, dot, inner, div, curl, cross
from sympde.topology import NormalVector
from sympde.topology import ScalarFunctionSpace, VectorFunctionSpace
from sympde.topology import ProductSpace
from sympde.topology import element_of, elements_of
from sympde.topology import Square
from sympde.expr import BilinearForm, LinearForm, integral
from sympde.expr import Norm
from sympde.expr import find, EssentialBC
from psydac.fem.basic import FemField
from psydac.fem.vector import ProductFemSpace
from psydac.api.discretization import discretize
from psydac.linalg.utilities import array_to_stencil
from psydac.linalg.iterative_solvers import pcg, bicg
```
## Solving the first mixed formulation using Psydac
```python
# ... abstract model
domain = Square()
x, y = domain.coordinates
V1 = VectorFunctionSpace('V1', domain, kind='H1')
V2 = ScalarFunctionSpace('V2', domain, kind='L2')
X = ProductSpace(V1, V2)
# ... Exact solution
fx = -x**2*(x - 1)**2*(24*y - 12) - 4*y*(x**2 + 4*x*(x - 1) + (x - 1)**2)*(2*y**2 - 3*y + 1) - 2*pi*cos(2*pi*x)
fy = 4*x*(2*x**2 - 3*x + 1)*(y**2 + 4*y*(y - 1) + (y - 1)**2) + y**2*(24*x - 12)*(y - 1)**2 + 2*pi*cos(2*pi*y)
f = Tuple(fx, fy)
ux = x**2*(-x + 1)**2*(4*y**3 - 6*y**2 + 2*y)
uy =-y**2*(-y + 1)**2*(4*x**3 - 6*x**2 + 2*x)
ue = Tuple(ux, uy)
pe = -sin(2*pi*x) + sin(2*pi*y)
# ...
u, v = elements_of(V1, names='u, v')
p, q = elements_of(V2, names='p, q')
x, y = domain.coordinates
int_0 = lambda expr: integral(domain , expr)
a = BilinearForm(((u, p), (v, q)), int_0(inner(grad(u), grad(v)) - div(u)*q - p*div(v)) )
l = LinearForm((v, q), int_0(dot(f, v)))
# Dirichlet boundary conditions are given in the form u = g where g may be
# just 0 (hence homogeneous BCs are prescribed) or a symbolic expression
# g(x, y) that represents the boundary data. Here we use the exact solution
bc = EssentialBC(u, 0, domain.boundary)
equation = find((u, p), forall=(v, q), lhs=a((u, p), (v, q)), rhs=l(v, q), bc=bc)
```
```python
ncells = [2**3, 2**3]
degree = [2, 2]
```
```python
# ... create the computational domain from a topological domain
domain_h = discretize(domain, ncells=ncells)
# ... discrete spaces
V1h = discretize(V1, domain_h, degree=degree)
V2h = discretize(V2, domain_h, degree=degree, basis='M')
Xh = discretize(X , domain_h, degree=degree, basis='M')
# ... discretize the equation using Dirichlet bc
equation_h = discretize(equation, domain_h, [Xh, Xh])
```
```python
equation_h.set_solver('cg', info=True)
phi_h, info = equation_h.solve()
x = phi_h.coeffs
print(info)
```
{'niter': 75, 'success': True, 'res_norm': 8.078519203112407e-10}
```python
# Numerical solution: velocity field
# TODO: allow this: uh = FemField(V1h, coeffs=x[0:2]) or similar
uh = FemField(V1h)
uh.coeffs[0][:] = x[0][:]
uh.coeffs[1][:] = x[1][:]
# Numerical solution: pressure field
# TODO: allow this: uh = FemField(V2h, coeffs=x[2])
ph = FemField(V2h)
ph.coeffs[:] = x[2][:]
# Compute norms of exact solution
x1, x2 = domain.coordinates
ue_1 = lambdify([x1, x2], ue[0])
ue_2 = lambdify([x1, x2], ue[1])
pe_c = lambdify([x1, x2], pe )
l2_norm_ue = np.sqrt(V1h.spaces[0].integral(lambda *x: ue_1(*x)**2 + ue_2(*x)**2))
l2_norm_pe = np.sqrt(V2h.integral(lambda *x: pe_c(*x)**2))
# Average value of the pressure (should be 0)
domain_area = V2h.integral(lambda x1, x2: 1.0)
p_avg = V2h.integral(ph) / domain_area
# L2 error norm of the velocity field
error_u = [ue[0]-u[0], ue[1]-u[1]]
l2norm_u = Norm(error_u, domain, kind='l2')
l2norm_uh = discretize(l2norm_u, domain_h, V1h)
# L2 error norm of the pressure, after removing the average value from the field
l2norm_p = Norm(pe - (p - p_avg), domain, kind='l2')
l2norm_ph = discretize(l2norm_p, domain_h, V2h)
# Compute error norms
l2_error_u = l2norm_uh.assemble(u = uh)
l2_error_p = l2norm_ph.assemble(p = ph)
print()
print('Relative l2_error(u) = {}'.format(l2_error_u / l2_norm_ue))
print('Relative l2_error(p) = {}'.format(l2_error_p / l2_norm_pe))
print('Average(p) = {}'.format(p_avg))
```
Relative l2_error(u) = 0.0023928602597358293
Relative l2_error(p) = 0.02442817246105665
Average(p) = -5.784464418329125e-12
```python
```
|
Formal statement is: lemma coeffs_eq_Nil [simp]: "coeffs p = [] \<longleftrightarrow> p = 0" Informal statement is: The coefficients of a polynomial are the empty list if and only if the polynomial is zero.
|
%! Author = tstreule
\section{Generation of X-rays}
\subsection{Basic formulas}
%
\begin{itemize}
\item \highlight{$\displaystyle c = \frac{1}{\sqrt{\mu_0\epsilon_0}} = \lambda\nu$}
\highlight{$\displaystyle E = h\nu = \frac{hc}{\lambda}$}
\hfill rest mass: $mc^2=\unit[511]{eV}$
\item Range of X-Rays: $\lambda = \unit[10]{pm} - \unit[10]{nm}$
\item $E\ped{radiation} = n \cdot E\ped{photon}$ \quad with \quad $E\ped{photon} = h \cdot \nu = e U_a$
\item $p\ped{photon} = mc = h/\lambda, \qquad \lambda\ped{min} = \frac{hc}{e U_a}$
\end{itemize}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Spectrum}
%
Photon flux vs E: Speaks by \textbf{Characteristic Radiation}.
Continuous spectrum by \textbf{Bremsstrahlung}: 1st el. deflection: Spectrum $0-E_{max}$, 2nd el. defl. Not to $E\ped{max}$ anymore.
If material changes: $E\ped{max} = const$, slope changes\\
If E changes: slope const., intersection with E-axis @ E
Low-Energy rad. absorbed anyway $\to$ Al filter $\to$ dose $\downarrow$
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Heat generation \& dissipation}
%
Efficiency: $\eta = \frac{\textrm{absorbed power}}{\textrm{incident power}} = 1\%$\\
$P_\textrm{heat} = U_a \cdot I_a \cdot (1-\eta)$ \textcolor{gray}{$= P - P_\textrm{X-ray}$}
\textbf{Dissipation} (Infrared): Diffusion ($\propto T^4$) and\\
Radiation ($\propto\Delta T$): $\lambda$ vs. $I$, $\lambda_\textrm{peak} = b/T$, $b = \unit[2.9\E{-3}]{mK}$
|
section \<open>Computing the Gcd via the subresultant PRS\<close>
text \<open>This theory now formalizes how the subresultant PRS can be used to calculate the gcd
of two polynomials. Moreover, it proves the connection between resultants and gcd, namely that
the resultant is 0 iff the degree of the gcd is non-zero.\<close>
theory Subresultant_Gcd
imports
Subresultant
Polynomial_Factorization.Missing_Polynomial_Factorial
begin
subsection \<open>Algorithm\<close>
definition gcd_impl_primitive where
[code del]: "gcd_impl_primitive G1 G2 = normalize (primitive_part (fst (subresultant_prs dichotomous_Lazard G1 G2)))"
definition gcd_impl_main where
[code del]: "gcd_impl_main G1 G2 = (if G1 = 0 then 0 else if G2 = 0 then normalize G1 else
smult (gcd (content G1) (content G2))
(gcd_impl_primitive (primitive_part G1) (primitive_part G2)))"
definition gcd_impl where
"gcd_impl f g = (if length (coeffs f) \<ge> length (coeffs g) then gcd_impl_main f g else gcd_impl_main g f)"
subsection \<open>Soundness Proof for @{term "gcd_impl = gcd"}\<close>
locale subresultant_prs_gcd = subresultant_prs_locale2 F n \<delta> f k \<beta> G1 G2 for
F :: "nat \<Rightarrow> 'a :: {factorial_ring_gcd,semiring_gcd_mult_normalize} fract poly"
and n :: "nat \<Rightarrow> nat"
and \<delta> :: "nat \<Rightarrow> nat"
and f :: "nat \<Rightarrow> 'a fract"
and k :: nat
and \<beta> :: "nat \<Rightarrow> 'a fract"
and G1 G2 :: "'a poly"
begin
text \<open>The subresultant PRS computes the gcd up to a scalar multiple.\<close>
lemma subresultant_prs_gcd: assumes "subresultant_prs dichotomous_Lazard G1 G2 = (Gk, hk)"
shows "\<exists> a b. a \<noteq> 0 \<and> b \<noteq> 0 \<and> smult a (gcd G1 G2) = smult b (normalize Gk)"
proof -
from subresultant_prs[OF dichotomous_Lazard assms]
have Fk: "F k = ffp Gk" and "\<forall> i. \<exists> H. i \<noteq> 0 \<longrightarrow> F i = ffp H"
and "\<forall> i. \<exists> b. 3 \<le> i \<longrightarrow> i \<le> Suc k \<longrightarrow> \<beta> i = ff b" by auto
from choice[OF this(2)] choice[OF this(3)] obtain H beta where
FH: "\<And> i. i \<noteq> 0 \<Longrightarrow> F i = ffp (H i)" and
beta: "\<And> i. 3 \<le> i \<Longrightarrow> i \<le> Suc k \<Longrightarrow> \<beta> i = ff (beta i)" by auto
from Fk FH[OF k0] FH[of 1] FH[of 2] FH[of "Suc k"] F0[of "Suc k"] F1 F2
have border: "H k = Gk" "H 1 = G1" "H 2 = G2" "H (Suc k) = 0" by auto
have "i \<noteq> 0 \<Longrightarrow> i \<le> k \<Longrightarrow> \<exists> a b. a \<noteq> 0 \<and> b \<noteq> 0 \<and> smult a (gcd G1 G2) = smult b (gcd (H i) (H (Suc i)))" for i
proof (induct i rule: less_induct)
case (less i)
from less(3) have ik: "i \<le> k" .
from less(2) have "i = 1 \<or> i \<ge> 2" by auto
thus ?case
proof
assume "i = 1"
thus ?thesis unfolding border[symmetric] by (intro exI[of _ 1], auto simp: numeral_2_eq_2)
next
assume i2: "i \<ge> 2"
with ik have "i - 1 < i" "i - 1 \<noteq> 0" and imk: "i - 1 \<le> k" by auto
from less(1)[OF this] i2
obtain a b where a: "a \<noteq> 0" and b: "b \<noteq> 0" and IH: "smult a (gcd G1 G2) = smult b (gcd (H (i - 1)) (H i))" by auto
define M where "M = pseudo_mod (H (i - 1)) (H i)"
define c where "c = \<beta> (Suc i)"
have M: "pseudo_mod (F (i - 1)) (F i) = ffp M" unfolding to_fract_hom.pseudo_mod_hom[symmetric] M_def
using i2 FH by auto
have c: "c \<noteq> 0" using \<beta>0 unfolding c_def .
from i2 ik have 3: "Suc i \<ge> 3" "Suc i \<le> Suc k" by auto
from pmod[OF 3]
have pm: "smult c (F (Suc i)) = pseudo_mod (F (i - 1)) (F i)" unfolding c_def by simp
from beta[OF 3, folded c_def] obtain d where cd: "c = ff d" by auto
with c have d: "d \<noteq> 0" by auto
from pm[unfolded cd M] FH[of "Suc i"]
have "ffp (smult d (H (Suc i))) = ffp M" by auto
hence pm: "smult d (H (Suc i)) = M" by (rule map_poly_hom.injectivity)
from ik F0[of i] i2 FH[of i] have Hi0: "H i \<noteq> 0" by auto
from pseudo_mod[OF this, of "H (i - 1)", folded M_def]
obtain c Q where c: "c \<noteq> 0" and "smult c (H (i - 1)) = H i * Q + M" by auto
from this[folded pm] have "smult c (H (i - 1)) = Q * H i + smult d (H (Suc i))" by simp
from gcd_add_mult[of "H i" Q "smult d (H (Suc i))", folded this]
have "gcd (H i) (smult c (H (i - 1))) = gcd (H i) (smult d (H (Suc i)))" .
with gcd_smult_ex[OF c, of "H (i - 1)" "H i"] obtain e where
e: "e \<noteq> 0" and "gcd (H i) (smult d (H (Suc i))) = smult e (gcd (H i) (H (i - 1)))"
unfolding gcd.commute[of "H i"] by auto
with gcd_smult_ex[OF d, of "H (Suc i)" "H i"] obtain c where
c: "c \<noteq> 0" and "smult c (gcd (H i) (H (Suc i))) = smult e (gcd (H (i - 1)) (H i))"
unfolding gcd.commute[of "H i"] by auto
from arg_cong[OF this(2), of "smult b"] arg_cong[OF IH, of "smult e"]
have "smult (e * a) (gcd G1 G2) = smult (b * c) (gcd (H i) (H (Suc i)))" unfolding smult_smult
by (simp add: ac_simps)
moreover have "e * a \<noteq> 0" "b * c \<noteq> 0" using a b c e by auto
ultimately show ?thesis by blast
qed
qed
from this[OF k0 le_refl, unfolded border]
obtain a b where "a \<noteq> 0" "b \<noteq> 0" and "smult a (gcd G1 G2) = smult b (normalize Gk)" by auto
thus ?thesis by auto
qed
lemma gcd_impl_primitive: assumes "primitive_part G1 = G1" and "primitive_part G2 = G2"
shows "gcd_impl_primitive G1 G2 = gcd G1 G2"
proof -
let ?pp = primitive_part
let ?c = "content"
let ?n = normalize
from F2 F0[of 2] k2 have G2: "G2 \<noteq> 0" by auto
obtain Gk hk where sub: "subresultant_prs dichotomous_Lazard G1 G2 = (Gk, hk)" by force
have impl: "gcd_impl_primitive G1 G2 = ?n (?pp Gk)" unfolding gcd_impl_primitive_def sub by auto
from subresultant_prs_gcd[OF sub]
obtain a b where a: "a \<noteq> 0" and b: "b \<noteq> 0" and id: "smult a (gcd G1 G2) = smult b (?n Gk)"
by auto
define c where "c = unit_factor (gcd G1 G2)"
define d where "d = smult (unit_factor a) c"
from G2 have c: "is_unit c" unfolding c_def by auto
from arg_cong[OF id, of ?pp, unfolded primitive_part_smult primitive_part_gcd assms
primitive_part_normalize c_def[symmetric]]
have id: "d * gcd G1 G2 = smult (unit_factor b) (?n (?pp Gk))" unfolding d_def by simp
have d: "is_unit d" unfolding d_def using c a
by (simp add: is_unit_smult_iff)
from is_unitE[OF d]
obtain e where e: "is_unit e" and de: "d * e = 1" by metis
define a where "a = smult (unit_factor b) e"
from arg_cong[OF id, of "\<lambda> x. e * x"]
have "(d * e) * gcd G1 G2 = a * (?n (?pp Gk))" by (simp add: ac_simps a_def)
hence id: "gcd G1 G2 = a * (?n (?pp Gk))" using de by simp
have a: "is_unit a" unfolding a_def using b e
by (simp add: is_unit_smult_iff)
define b where "b = unit_factor (?pp Gk)"
have "Gk \<noteq> 0" using subresultant_prs[OF dichotomous_Lazard sub] F0[OF k0] by auto
hence b: "is_unit b" unfolding b_def by auto
from is_unitE[OF b]
obtain c where c: "is_unit c" and bc: "b * c = 1" by metis
obtain d where d: "is_unit d" and dac: "d = a * c" using c a by auto
have "gcd G1 G2 = d * (b * ?n (?pp Gk))"
unfolding id dac using bc by (simp add: ac_simps)
also have "b * ?n (?pp Gk) = ?pp Gk" unfolding b_def by simp
finally have "gcd G1 G2 = d * ?pp Gk" by simp
from arg_cong[OF this, of ?n]
have "gcd G1 G2 = ?n (d * ?pp Gk)" by simp
also have "\<dots> = ?n (?pp Gk)" using d
unfolding normalize_mult by (simp add: is_unit_normalize)
finally show ?thesis unfolding impl ..
qed
end
lemma gcd_impl_main: assumes len: "length (coeffs G1) \<ge> length (coeffs G2)"
shows "gcd_impl_main G1 G2 = gcd G1 G2"
proof (cases "G1 = 0")
case G1: False
show ?thesis
proof (cases "G2 = 0")
case G2: False
let ?pp = "primitive_part"
from G2 have G2: "?pp G2 \<noteq> 0" and id: "(G2 = 0) = False" by auto
from len have len: "length (coeffs (?pp G1)) \<ge> length (coeffs (?pp G2))" by simp
from enter_subresultant_prs[OF len G2] obtain F n d f k b
where "subresultant_prs_locale2 F n d f k b (?pp G1) (?pp G2)" by auto
interpret subresultant_prs_locale2 F n d f k b "?pp G1" "?pp G2" by fact
interpret subresultant_prs_gcd F n d f k b "?pp G1" "?pp G2" ..
show ?thesis unfolding gcd_impl_main_def gcd_poly_decompose[of G1] id if_False using G1
by (subst gcd_impl_primitive, auto)
next
case True
thus ?thesis unfolding gcd_impl_main_def by simp
qed
next
case True
with len have "G2 = 0" by auto
thus ?thesis using True unfolding gcd_impl_main_def by simp
qed
text \<open>The implementation also reveals an important connection between resultant and gcd.\<close>
lemma resultant_0_gcd: "resultant f g = 0 \<longleftrightarrow> degree (gcd f g) \<noteq> 0"
proof -
{
fix f g :: "'a poly"
assume len: "length (coeffs f) \<ge> length (coeffs g)"
{
assume g: "g \<noteq> 0"
with len have f: "f \<noteq> 0" by auto
let ?f = "primitive_part f"
let ?g = "primitive_part g"
let ?c = "content"
from len have len: "length (coeffs ?f) \<ge> length (coeffs ?g)" by simp
obtain Gk hk where sub: "subresultant_prs dichotomous_Lazard ?f ?g = (Gk,hk)" by force
have cf: "?c f \<noteq> 0" and cg: "?c g \<noteq> 0" using f g by auto
{
from g have "?g \<noteq> 0" by auto
from enter_subresultant_prs[OF len this] obtain F n d f k b
where "subresultant_prs_locale2 F n d f k b ?f ?g" by auto
interpret subresultant_prs_locale2 F n d f k b ?f ?g by fact
from subresultant_prs[OF dichotomous_Lazard sub] have "h k = ff hk" by auto
with h0[OF le_refl] have "hk \<noteq> 0" by auto
} note hk0 = this
have "resultant f g = 0 \<longleftrightarrow> resultant (smult (?c f) ?f) (smult (?c g) ?g) = 0" by simp
also have "\<dots> \<longleftrightarrow> resultant ?f ?g = 0" unfolding resultant_smult_left[OF cf] resultant_smult_right[OF cg]
using cf cg by auto
also have "\<dots> \<longleftrightarrow> resultant_impl_main dichotomous_Lazard ?f ?g = 0"
unfolding resultant_impl[symmetric] resultant_impl_def resultant_impl_main_def
resultant_impl_generic_def using len by auto
also have "\<dots> \<longleftrightarrow> (degree Gk \<noteq> 0)"
unfolding resultant_impl_main_def sub split using g hk0 by auto
also have "degree Gk = degree (gcd_impl_primitive ?f ?g)"
unfolding gcd_impl_primitive_def sub by simp
also have "\<dots> = degree (gcd_impl_main f g)"
unfolding gcd_impl_main_def using f g by auto
also have "\<dots> = degree (gcd f g)" unfolding gcd_impl[symmetric] gcd_impl_def using len by auto
finally have "(resultant f g = 0) = (degree (gcd f g) \<noteq> 0)" .
}
moreover
{
assume g: "g = 0" and f: "degree f \<noteq> 0"
have "(resultant f g = 0) = (degree (gcd f g) \<noteq> 0)"
unfolding g using f by auto
}
moreover
{
assume g: "g = 0" and f: "degree f = 0"
have "(resultant f g = 0) = (degree (gcd f g) \<noteq> 0)"
unfolding g using f by (auto simp: resultant_def sylvester_mat_def sylvester_mat_sub_def)
}
ultimately have "(resultant f g = 0) = (degree (gcd f g) \<noteq> 0)" by blast
} note main = this
show ?thesis
proof (cases "length (coeffs f) \<ge> length (coeffs g)")
case True
from main[OF True] show ?thesis .
next
case False
hence "length (coeffs g) \<ge> length (coeffs f)" by auto
from main[OF this] show ?thesis
unfolding gcd.commute[of g f] resultant_swap[of g f] by (simp split: if_splits)
qed
qed
subsection \<open>Code Equations\<close>
definition [code del]:
"gcd_impl_rec = subresultant_prs_main_impl fst"
definition [code del]:
"gcd_impl_start = subresultant_prs_impl fst"
lemma gcd_impl_rec_code[code]:
"gcd_impl_rec Gi_1 Gi ni_1 d1_1 hi_2 = (
let pmod = pseudo_mod Gi_1 Gi
in
if pmod = 0 then Gi
else let
ni = degree Gi;
d1 = ni_1 - ni;
gi_1 = lead_coeff Gi_1;
hi_1 = (if d1_1 = 1 then gi_1 else dichotomous_Lazard gi_1 hi_2 d1_1);
divisor = if d1 = 1 then gi_1 * hi_1 else if even d1 then - gi_1 * hi_1 ^ d1 else gi_1 * hi_1 ^ d1;
Gi_p1 = sdiv_poly pmod divisor
in gcd_impl_rec Gi Gi_p1 ni d1 hi_1)"
unfolding gcd_impl_rec_def subresultant_prs_main_impl.simps[of _ Gi_1] split Let_def
unfolding gcd_impl_rec_def[symmetric]
by (rule if_cong, auto)
lemma gcd_impl_start_code[code]:
"gcd_impl_start G1 G2 =
(let pmod = pseudo_mod G1 G2
in if pmod = 0 then G2
else let
n2 = degree G2;
n1 = degree G1;
d1 = n1 - n2;
G3 = if even d1 then - pmod else pmod;
pmod = pseudo_mod G2 G3
in if pmod = 0
then G3
else let
g2 = lead_coeff G2;
n3 = degree G3;
h2 = (if d1 = 1 then g2 else g2 ^ d1);
d2 = n2 - n3;
divisor = (if d2 = 1 then g2 * h2 else if even d2 then - g2 * h2 ^ d2 else g2 * h2 ^ d2);
G4 = sdiv_poly pmod divisor
in gcd_impl_rec G3 G4 n3 d2 h2)"
proof -
obtain d1 where d1: "degree G1 - degree G2 = d1" by auto
have id1: "(if even d1 then - pmod else pmod) = (-1)^ (d1 + 1) * (pmod :: 'a poly)" for pmod by simp
show ?thesis
unfolding gcd_impl_start_def subresultant_prs_impl_def gcd_impl_rec_def[symmetric] Let_def split
unfolding d1
unfolding id1
by (rule if_cong, auto)
qed
lemma gcd_impl_main_code[code]:
"gcd_impl_main G1 G2 = (if G1 = 0 then 0 else if G2 = 0 then normalize G1 else
let c1 = content G1;
c2 = content G2;
p1 = map_poly (\<lambda> x. x div c1) G1;
p2 = map_poly (\<lambda> x. x div c2) G2
in smult (gcd c1 c2) (normalize (primitive_part (gcd_impl_start p1 p2))))"
unfolding gcd_impl_main_def Let_def primitive_part_def gcd_impl_start_def gcd_impl_primitive_def
subresultant_prs_impl by simp
corollary gcd_via_subresultant: "gcd f g = gcd_impl f g" by simp
text \<open>Note that we did not activate @{thm gcd_via_subresultant} as code-equation, since according to our experiments,
the subresultant-gcd algorithm is not always more efficient than the currently active equation.
In particular, on @{typ "int poly"} @{const gcd_impl} performs worse, but on multi-variate polynomials,
e.g., @{typ "int poly poly poly"}, @{const gcd_impl} is preferable.\<close>
end
|
/*
* Copyright 2020 Naval Postgraduate School
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <assert.h>
#include <sys/stat.h>
#include <tf/tf.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/point_cloud2_iterator.h>
#include <nps_uw_sensors_gazebo/sonar_calculation_cuda.cuh>
#include <opencv2/core/core.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <nps_uw_sensors_gazebo/gazebo_ros_image_sonar.hh>
#include <gazebo/sensors/Sensor.hh>
#include <sdf/sdf.hh>
#include <gazebo/sensors/SensorTypes.hh>
#include <algorithm>
#include <string>
#include <vector>
#include <limits>
namespace gazebo
{
// Register this plugin with the simulator
GZ_REGISTER_SENSOR_PLUGIN(NpsGazeboRosImageSonar)
// Constructor
NpsGazeboRosImageSonar::NpsGazeboRosImageSonar() :
SensorPlugin(), width(0), height(0), depth(0)
{
this->depth_image_connect_count_ = 0;
this->depth_info_connect_count_ = 0;
this->point_cloud_connect_count_ = 0;
this->sonar_image_connect_count_ = 0;
this->last_depth_image_camera_info_update_time_ = common::Time(0);
// for csv write logs
this->writeCounter = 0;
this->writeNumber = 1;
}
// Destructor
NpsGazeboRosImageSonar::~NpsGazeboRosImageSonar()
{
this->newDepthFrameConnection.reset();
this->newImageFrameConnection.reset();
this->newRGBPointCloudConnection.reset();
this->newSonarImageConnection.reset();
this->parentSensor.reset();
this->depthCamera.reset();
// CSV log write stream close
writeLog.close();
}
// Load the controller
void NpsGazeboRosImageSonar::Load(sensors::SensorPtr _parent,
sdf::ElementPtr _sdf)
{
this->parentSensor =
std::dynamic_pointer_cast<sensors::DepthCameraSensor>(_parent);
this->depthCamera = this->parentSensor->DepthCamera();
if (!this->parentSensor)
{
gzerr << "DepthCameraPlugin not attached to a depthCamera sensor\n";
return;
}
this->width = this->depthCamera->ImageWidth();
this->height = this->depthCamera->ImageHeight();
this->depth = this->depthCamera->ImageDepth();
this->format = this->depthCamera->ImageFormat();
this->newDepthFrameConnection =
this->depthCamera->ConnectNewDepthFrame(
std::bind(&NpsGazeboRosImageSonar::OnNewDepthFrame,
this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4,
std::placeholders::_5));
this->newImageFrameConnection =
this->depthCamera->ConnectNewImageFrame(
std::bind(&NpsGazeboRosImageSonar::OnNewImageFrame,
this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4,
std::placeholders::_5));
this->newSonarImageConnection =
this->depthCamera->ConnectNewDepthFrame(
std::bind(&NpsGazeboRosImageSonar::OnNewDepthFrame,
this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4,
std::placeholders::_5));
this->parentSensor->SetActive(true);
// Make sure the ROS node for Gazebo has already been initialized
if (!ros::isInitialized())
{
ROS_FATAL_STREAM_NAMED("depth_camera", "A ROS node for Gazebo "
<< "has not been initialized, unable to load plugin. "
<< "Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so'"
<< " in the gazebo_ros package)");
return;
}
// copying from DepthCameraPlugin into GazeboRosCameraUtils
this->parentSensor_ = this->parentSensor;
this->width_ = this->width;
this->height_ = this->height;
this->depth_ = this->depth;
this->format_ = this->format;
this->camera_ = this->depthCamera;
// not using default GazeboRosCameraUtils topics
if (!_sdf->HasElement("imageTopicName"))
this->image_topic_name_ = "ir/image_raw";
if (!_sdf->HasElement("cameraInfoTopicName"))
this->camera_info_topic_name_ = "ir/camera_info";
// depth image stuff
if (!_sdf->HasElement("depthImageTopicName"))
this->depth_image_topic_name_ = "depth/image_raw";
else
this->depth_image_topic_name_ =
_sdf->GetElement("depthImageTopicName")->Get<std::string>();
if (!_sdf->HasElement("depthImageCameraInfoTopicName"))
this->depth_image_camera_info_topic_name_ = "depth/camera_info";
else
this->depth_image_camera_info_topic_name_ =
_sdf->GetElement("depthImageCameraInfoTopicName")->Get<std::string>();
if (!_sdf->HasElement("pointCloudTopicName"))
this->point_cloud_topic_name_ = "points";
else
this->point_cloud_topic_name_ =
_sdf->GetElement("pointCloudTopicName")->Get<std::string>();
if (!_sdf->HasElement("pointCloudCutoff"))
this->point_cloud_cutoff_ = 0.4;
else
this->point_cloud_cutoff_ =
_sdf->GetElement("pointCloudCutoff")->Get<double>();
// sonar stuff
if (!_sdf->HasElement("sonarImageRawTopicName"))
this->sonar_image_raw_topic_name_ = "sonar_image_raw";
else
this->sonar_image_raw_topic_name_ =
_sdf->GetElement("sonarImageRawTopicName")->Get<std::string>();
if (!_sdf->HasElement("sonarImageTopicName"))
this->sonar_image_topic_name_ = "sonar_image";
else
this->sonar_image_topic_name_ =
_sdf->GetElement("sonarImageTopicName")->Get<std::string>();
if (!_sdf->HasElement("clip"))
{
gzerr << "We do not have clip" << std::endl;
}
else
{
gzerr << "We do have clip" << std::endl;
gzerr << _sdf->GetElement("clip")->GetElement("far")->Get<double>()
<< std::endl;
}
// TODO: Implement additional SDF options (ROS namespaces & topics) here
// Read sonar properties from model.sdf
if (!_sdf->HasElement("sonarFreq"))
this->sonarFreq = 900e3; // Blueview P900 [Hz]
else
this->sonarFreq =
_sdf->GetElement("sonarFreq")->Get<double>();
if (!_sdf->HasElement("bandwidth"))
this->bandwidth = 29.5e6; // Blueview P900 [Hz]
else
this->bandwidth =
_sdf->GetElement("bandwidth")->Get<double>();
if (!_sdf->HasElement("soundSpeed"))
this->soundSpeed = 1500;
else
this->soundSpeed =
_sdf->GetElement("soundSpeed")->Get<double>();
if (!_sdf->HasElement("maxDistance"))
this->maxDistance = 60;
else
this->maxDistance =
_sdf->GetElement("maxDistance")->Get<double>();
if (!_sdf->HasElement("sourceLevel"))
this->sourceLevel = 220;
else
this->sourceLevel =
_sdf->GetElement("sourceLevel")->Get<double>();
if (!_sdf->HasElement("constantReflectivity"))
this->constMu = true;
else
this->constMu =
_sdf->GetElement("constantReflectivity")->Get<bool>();
if (!_sdf->HasElement("raySkips"))
this->raySkips = 10;
else
this->raySkips =
_sdf->GetElement("raySkips")->Get<int>();
if (!_sdf->HasElement("plotScaler"))
this->plotScaler = 1;
else
this->plotScaler =
_sdf->GetElement("plotScaler")->Get<int>();
// Configure skips
if (this->raySkips == 0) this->raySkips = 1;
// --- Calculate common sonar parameters ---- //
// if (this->constMu)
this->mu = 1e-3;
// else
// // nothing yet
// Transmission path properties (typical model used here)
// More sophisticated model by Francois-Garrison model is available
this->absorption = 0.0354; // [dB/m]
this->attenuation = this->absorption*log(10)/20.0;
// Range vector
const float max_T = this->maxDistance*2.0/this->soundSpeed;
float delta_f = 1.0/max_T;
const float delta_t = 1.0/this->bandwidth;
this->nFreq = ceil(this->bandwidth/delta_f);
delta_f = this->bandwidth/this->nFreq;
const int nTime = nFreq;
this->rangeVector = new float[nTime];
for (int i = 0; i < nTime; i++)
{
this->rangeVector[i] = delta_t*i*this->soundSpeed/2.0;
}
// FOV, Number of beams, number of rays are defined at model.sdf
// Currently, this->width equals # of beams, and this->height equals # of rays
// Each beam consists of (elevation,azimuth)=(this->height,1) rays
// Beam patterns
this->nBeams = this->width;
this->nRays = this->height;
this->ray_nElevationRays = this->height;
this->ray_nAzimuthRays = 1;
// Print sonar calculation settings
ROS_INFO_STREAM("");
ROS_INFO_STREAM("==================================================");
ROS_INFO_STREAM("============ SONAR PLUGIN LOADED =============");
ROS_INFO_STREAM("==================================================");
ROS_INFO_STREAM("Maximum view range [m] = " << this->maxDistance);
ROS_INFO_STREAM("Distance resolution [m] = " <<
this->soundSpeed*(1.0/(this->nFreq*delta_f)));
ROS_INFO_STREAM("# of Beams = " << this->nBeams);
ROS_INFO_STREAM("# of Rays / Beam (Elevation, Azimuth) = ("
<< ray_nElevationRays << ", " << ray_nAzimuthRays << ")");
ROS_INFO_STREAM("Calculation skips (Elevation) = "
<< this->raySkips);
ROS_INFO_STREAM("# of Time data / Beam = " << this->nFreq);
ROS_INFO_STREAM("==================================================");
ROS_INFO_STREAM("");
// get writeLog Flag
if (!_sdf->HasElement("writeLog"))
this->writeLogFlag = false;
else
{
this->writeLogFlag = _sdf->Get<bool>("writeLog");
if (this->writeLogFlag)
{
if (_sdf->HasElement("writeFrameInterval"))
this->writeInterval = _sdf->Get<int>("writeFrameInterval");
else
this->writeInterval = 10;
ROS_INFO_STREAM("Raw data at " << "/tmp/SonarRawData_{numbers}.csv");
ROS_INFO_STREAM("every " << this->writeInterval << " frames");
ROS_INFO_STREAM("");
struct stat buffer;
std::string logfilename("/tmp/SonarRawData_000001.csv");
if (stat (logfilename.c_str(), &buffer) == 0)
system("rm /tmp/SonarRawData*.csv");
}
}
// Get debug flag for computation time display
if (!_sdf->HasElement("debugFlag"))
this->debugFlag = false;
else
this->debugFlag =
_sdf->GetElement("debugFlag")->Get<bool>();
// -- Pre calculations for sonar -- //
// Hamming window
this->window = new float[this->nFreq];
float windowSum = 0;
for (size_t f = 0; f < this->nFreq; f++)
{
this->window[f] = 0.54 - 0.46 * cos(2.0*M_PI*(f+1)/this->nFreq);
windowSum += pow(this->window[f], 2.0);
}
for (size_t f = 0; f < this->nFreq; f++)
this->window[f] = this->window[f]/sqrt(windowSum);
// Sonar corrector preallocation
this->beamCorrector = new float*[nBeams];
for (int i = 0; i < nBeams; i++)
this->beamCorrector[i] = new float[nBeams];
this->beamCorrectorSum = 0.0;
load_connection_ =
GazeboRosCameraUtils::OnLoad(
boost::bind(&NpsGazeboRosImageSonar::Advertise, this));
GazeboRosCameraUtils::Load(_parent, _sdf);
}
void NpsGazeboRosImageSonar::Advertise()
{
ros::AdvertiseOptions depth_image_ao =
ros::AdvertiseOptions::create<sensor_msgs::Image>(
this->depth_image_topic_name_, 1,
boost::bind(&NpsGazeboRosImageSonar::DepthImageConnect, this),
boost::bind(&NpsGazeboRosImageSonar::DepthImageDisconnect, this),
ros::VoidPtr(), &this->camera_queue_);
this->depth_image_pub_ = this->rosnode_->advertise(depth_image_ao);
ros::AdvertiseOptions depth_image_camera_info_ao =
ros::AdvertiseOptions::create<sensor_msgs::CameraInfo>(
this->depth_image_camera_info_topic_name_, 1,
boost::bind(&NpsGazeboRosImageSonar::DepthInfoConnect, this),
boost::bind(&NpsGazeboRosImageSonar::DepthInfoDisconnect, this),
ros::VoidPtr(), &this->camera_queue_);
this->depth_image_camera_info_pub_ =
this->rosnode_->advertise(depth_image_camera_info_ao);
ros::AdvertiseOptions normal_image_ao =
ros::AdvertiseOptions::create<sensor_msgs::Image>(
this->depth_image_topic_name_+"_normals", 1,
boost::bind(&NpsGazeboRosImageSonar::NormalImageConnect, this),
boost::bind(&NpsGazeboRosImageSonar::NormalImageDisconnect, this),
ros::VoidPtr(), &this->camera_queue_);
this->normal_image_pub_ = this->rosnode_->advertise(normal_image_ao);
ros::AdvertiseOptions point_cloud_ao =
ros::AdvertiseOptions::create<sensor_msgs::PointCloud2>(
this->point_cloud_topic_name_, 1,
boost::bind(&NpsGazeboRosImageSonar::PointCloudConnect, this),
boost::bind(&NpsGazeboRosImageSonar::PointCloudDisconnect, this),
ros::VoidPtr(), &this->camera_queue_);
this->point_cloud_pub_ = this->rosnode_->advertise(point_cloud_ao);
// Publisher for sonar image
ros::AdvertiseOptions sonar_image_raw_ao =
ros::AdvertiseOptions::create<acoustic_msgs::SonarImage>(
this->sonar_image_raw_topic_name_, 1,
boost::bind(&NpsGazeboRosImageSonar::SonarImageRawConnect, this),
boost::bind(&NpsGazeboRosImageSonar::SonarImageRawDisconnect, this),
ros::VoidPtr(), &this->camera_queue_);
this->sonar_image_raw_pub_ = this->rosnode_->advertise(sonar_image_raw_ao);
ros::AdvertiseOptions sonar_image_ao =
ros::AdvertiseOptions::create<sensor_msgs::Image>(
this->sonar_image_topic_name_, 1,
boost::bind(&NpsGazeboRosImageSonar::SonarImageConnect, this),
boost::bind(&NpsGazeboRosImageSonar::SonarImageDisconnect, this),
ros::VoidPtr(), &this->camera_queue_);
this->sonar_image_pub_ = this->rosnode_->advertise(sonar_image_ao);
this->sonar_image_pub_ =
this->rosnode_->advertise<sensor_msgs::Image>
("sonar_image", 10);
}
//----------------------------------------------------------------
// Increment and decriment a connection counter so that the sensor
// is only active and ROS messages being published when required
// TODO: Update once new message (plugin output) is being published
//----------------------------------------------------------------
void NpsGazeboRosImageSonar::DepthImageConnect()
{
this->depth_image_connect_count_++;
this->parentSensor->SetActive(true);
}
void NpsGazeboRosImageSonar::DepthImageDisconnect()
{
this->depth_image_connect_count_--;
}
void NpsGazeboRosImageSonar::NormalImageConnect()
{
this->depth_image_connect_count_++;
this->parentSensor->SetActive(true);
}
void NpsGazeboRosImageSonar::NormalImageDisconnect()
{
this->depth_image_connect_count_--;
}
void NpsGazeboRosImageSonar::DepthInfoConnect()
{
this->depth_info_connect_count_++;
}
void NpsGazeboRosImageSonar::DepthInfoDisconnect()
{
this->depth_info_connect_count_--;
}
void NpsGazeboRosImageSonar::PointCloudConnect()
{
this->point_cloud_connect_count_++;
(*this->image_connect_count_)++;
this->parentSensor->SetActive(true);
}
void NpsGazeboRosImageSonar::PointCloudDisconnect()
{
this->point_cloud_connect_count_--;
(*this->image_connect_count_)--;
if (this->point_cloud_connect_count_ <= 0)
this->parentSensor->SetActive(false);
}
void NpsGazeboRosImageSonar::SonarImageConnect()
{
this->sonar_image_connect_count_++;
this->parentSensor->SetActive(true);
}
void NpsGazeboRosImageSonar::SonarImageDisconnect()
{
this->sonar_image_connect_count_--;
}
void NpsGazeboRosImageSonar::SonarImageRawConnect()
{
this->sonar_image_connect_count_++;
this->parentSensor->SetActive(true);
}
void NpsGazeboRosImageSonar::SonarImageRawDisconnect()
{
this->sonar_image_connect_count_--;
}
// Update everything when Gazebo provides a new depth frame (texture)
void NpsGazeboRosImageSonar::OnNewDepthFrame(const float *_image,
unsigned int _width,
unsigned int _height,
unsigned int _depth,
const std::string &_format)
{
if (!this->initialized_ || this->height_ <=0 || this->width_ <=0)
return;
this->depth_sensor_update_time_ = this->parentSensor->LastMeasurementTime();
if (this->parentSensor->IsActive())
{
// Deactivate if no subscribers
if (this->depth_image_connect_count_ <= 0 &&
this->point_cloud_connect_count_ <= 0 &&
(*this->image_connect_count_) <= 0)
{
this->parentSensor->SetActive(false);
}
else
{
// Generate a point cloud every time regardless of subscriptions
// for use in sonar computation (published in function if needed)
this->ComputePointCloud(_image);
// Generate sonar image data if topics have subscribers
if (this->depth_image_connect_count_ > 0)
this->ComputeSonarImage(_image);
}
}
else
{
// Won't this just toggle on and off unnecessarily?
// TODO: Find a better way to ensure it runs once after activation
if (this->depth_image_connect_count_ <= 0 ||
this->point_cloud_connect_count_ > 0)
// do this first so there's chance for sensor
// to run 1 frame after activate
this->parentSensor->SetActive(true);
}
}
// Process the camera image when Gazebo provides one. Do we actually need this?
void NpsGazeboRosImageSonar::OnNewImageFrame(const unsigned char *_image,
unsigned int _width,
unsigned int _height,
unsigned int _depth,
const std::string &_format)
{
if (!this->initialized_ || this->height_ <=0 || this->width_ <=0)
return;
this->sensor_update_time_ = this->parentSensor->LastMeasurementTime();
if (!this->parentSensor->IsActive())
{
if ((*this->image_connect_count_) > 0)
// do this first so there's chance for sensor
// to run 1 frame after activate
this->parentSensor->SetActive(true);
}
else
{
if ((*this->image_connect_count_) > 0)
{
this->PutCameraData(_image);
}
}
}
// Most of the plugin work happens here
void NpsGazeboRosImageSonar::ComputeSonarImage(const float *_src)
{
this->lock_.lock();
cv::Mat depth_image = this->point_cloud_image_;
cv::Mat normal_image = this->ComputeNormalImage(depth_image);
double vFOV = this->parentSensor->DepthCamera()->VFOV().Radian();
double hFOV = this->parentSensor->DepthCamera()->HFOV().Radian();
double vPixelSize = vFOV / this->height;
double hPixelSize = hFOV / this->width;
// rand number generator
cv::Mat rand_image = cv::Mat(depth_image.rows, depth_image.cols, CV_32FC2);
uint64 randN = static_cast<uint64>(std::rand());
cv::theRNG().state = randN;
cv::RNG rng = cv::theRNG();
rng.fill(rand_image, cv::RNG::NORMAL, 0.f, 1.f);
if (this->beamCorrectorSum == 0)
ComputeCorrector();
// For calc time measure
auto start = std::chrono::high_resolution_clock::now();
// ------------------------------------------------//
// -------- Sonar calculations -------- //
// ------------------------------------------------//
CArray2D P_Beams = NpsGazeboSonar::sonar_calculation_wrapper(
depth_image, // cv::Mat& depth_image
normal_image, // cv::Mat& normal_image
rand_image, // cv::Mat& rand_image
hPixelSize, // hPixelSize
vPixelSize, // vPixelSize
hFOV, // hFOV
vFOV, // VFOV
hPixelSize, // _beam_azimuthAngleWidth
vPixelSize, // _beam_elevationAngleWidth
hPixelSize, // _ray_azimuthAngleWidth
vPixelSize*(raySkips), // _ray_elevationAngleWidth
this->soundSpeed, // _soundSpeed
this->maxDistance, // _maxDistance
this->sourceLevel, // _sourceLevel
this->nBeams, // _nBeams
this->nRays, // _nRays
this->raySkips, // _raySkips
this->sonarFreq, // _sonarFreq
this->bandwidth, // _bandwidth
this->nFreq, // _nFreq
this->mu, // _mu
this->attenuation, // _attenuation
this->window, // _window
this->beamCorrector, // _beamCorrector
this->beamCorrectorSum, // _beamCorrectorSum
this->debugFlag);
// For calc time measure
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<
std::chrono::microseconds>(stop - start);
if (debugFlag)
{
ROS_INFO_STREAM("GPU Sonar Frame Calc Time " <<
duration.count()/10000 << "/100 [s]\n");
}
// CSV log write stream
// Each cols corresponds to each beams
if (this->writeLogFlag)
{
this->writeCounter = this->writeCounter + 1;
if (this->writeCounter == 1
||this->writeCounter % this->writeInterval == 0)
{
double time = this->parentSensor_->LastMeasurementTime().Double();
std::stringstream filename;
filename << "/tmp/SonarRawData_" << std::setw(6) << std::setfill('0')
<< this->writeNumber << ".csv";
writeLog.open(filename.str().c_str(), std::ios_base::app);
filename.clear();
writeLog << "# Raw Sonar Data Log (Row: beams, Col: time series data)\n";
writeLog << "# First column is range vector\n";
writeLog << "# nBeams : " << nBeams << "\n";
writeLog << "# Simulation time : " << time << "\n";
for (size_t i = 0; i < P_Beams[0].size(); i++)
{
// writing range vector at first column
writeLog << this->rangeVector[i];
for (size_t b = 0; b < nBeams; b ++)
{
if (P_Beams[b][i].imag() > 0)
writeLog << "," << P_Beams[b][i].real()
<< "+" << P_Beams[b][i].imag() << "i";
else
writeLog << "," << P_Beams[b][i].real()
<< P_Beams[b][i].imag() << "i";
}
writeLog << "\n";
}
writeLog.close();
this->writeNumber = this->writeNumber + 1;
}
}
// Sonar image ROS msg
this->sonar_image_raw_msg_.header.frame_id
= this->frame_name_.c_str();
this->sonar_image_raw_msg_.header.stamp.sec
= this->depth_sensor_update_time_.sec;
this->sonar_image_raw_msg_.header.stamp.nsec
= this->depth_sensor_update_time_.nsec;
this->sonar_image_raw_msg_.frequency = this->sonarFreq;
this->sonar_image_raw_msg_.sound_speed = this->soundSpeed;
this->sonar_image_raw_msg_.azimuth_beamwidth = hPixelSize;
this->sonar_image_raw_msg_.elevation_beamwidth = hPixelSize*this->nRays;
std::vector<float> azimuth_angles;
double fl = static_cast<double>(width) / (2.0 * tan(hFOV/2.0));
for (size_t beam = 0; beam < nBeams; beam ++)
azimuth_angles.push_back(atan2(static_cast<double>(beam) -
0.5 * static_cast<double>(width-1), fl));
this->sonar_image_raw_msg_.azimuth_angles = azimuth_angles;
// std::vector<float> elevation_angles;
// elevation_angles.push_back(vFOV / 2.0); // 1D in elevation
// this->sonar_image_raw_msg_.elevation_angles = elevation_angles;
std::vector<float> ranges;
for (size_t i = 0; i < P_Beams[0].size(); i ++)
ranges.push_back(rangeVector[i]);
this->sonar_image_raw_msg_.ranges = ranges;
// this->sonar_image_raw_msg_.is_bigendian = false;
this->sonar_image_raw_msg_.data_size = 1; // sizeof(float) * nFreq * nBeams;
std::vector<uchar> intensities;
for (size_t f = 0; f < nFreq; f ++)
for (size_t beam = 0; beam < nBeams; beam ++)
intensities.push_back(
static_cast<uchar>(static_cast<int>(abs(P_Beams[beam][f]))));
this->sonar_image_raw_msg_.intensities = intensities;
this->sonar_image_raw_pub_.publish(this->sonar_image_raw_msg_);
// Construct visual sonar image for rqt plot in sensor::image msg format
cv_bridge::CvImage img_bridge;
// Calculate and allocate plot data
int Intensity[nBeams][nFreq];
for (size_t beam = 0; beam < nBeams; beam ++)
for (size_t f = 0; f < nFreq; f ++)
Intensity[beam][f] = static_cast<int>(abs(P_Beams[beam][f]));
// Generate image of 16UC1
cv::Mat Intensity_image = cv::Mat::zeros(cv::Size(nBeams, nFreq), CV_16UC1);
const float rangeMax = maxDistance;
const float rangeRes = ranges[1]-ranges[0];
const int nEffectiveRanges = ceil(rangeMax / rangeRes);
const unsigned int radius = Intensity_image.size().height;
const cv::Point origin(Intensity_image.size().width/2,
Intensity_image.size().height);
const float binThickness = 2 * ceil(radius / nEffectiveRanges);
struct BearingEntry
{
float begin, center, end;
BearingEntry(float b, float c, float e)
: begin(b), center(c), end(e)
{;}
};
std::vector<BearingEntry> angles;
angles.reserve(nBeams);
for ( int b = 0; b < nBeams; ++b )
{
const float center = azimuth_angles[b];
float begin = 0.0, end = 0.0;
if (b == 0)
{
end = (azimuth_angles[b + 1] + center) / 2.0;
begin = 2 * center - end;
}
else if (b == nBeams - 1)
{
begin = angles[b - 1].end;
end = 2 * center - begin;
}
else
{
begin = angles[b - 1].end;
end = (azimuth_angles[b + 1] + center) / 2.0;
}
angles.push_back(BearingEntry(begin, center, end));
}
const float ThetaShift = 1.5*M_PI;
for ( int r = 0; r < ranges.size(); ++r )
{
if ( ranges[r] > rangeMax ) continue;
for ( int b = 0; b < nBeams; ++b )
{
const float range = ranges[r];
const int intensity = Intensity[b][r];
const float begin = angles[b].begin + ThetaShift,
end = angles[b].end + ThetaShift;
const float rad = static_cast<float>(radius) * range/rangeMax;
// Assume angles are in image frame x-right, y-down
cv::ellipse(Intensity_image, origin, cv::Size(rad, rad), 0,
begin * 180/M_PI, end * 180/M_PI,
intensity*256/5*this->plotScaler,
binThickness);
}
}
// Publish final sonar image
this->sonar_image_msg_.header.frame_id
= this->frame_name_;
this->sonar_image_msg_.header.stamp.sec
= this->depth_sensor_update_time_.sec;
this->sonar_image_msg_.header.stamp.nsec
= this->depth_sensor_update_time_.nsec;
img_bridge = cv_bridge::CvImage(this->sonar_image_msg_.header,
sensor_msgs::image_encodings::MONO16,
Intensity_image);
// from cv_bridge to sensor_msgs::Image
img_bridge.toImageMsg(this->sonar_image_msg_);
this->sonar_image_pub_.publish(this->sonar_image_msg_);
// ---------------------------------------- End of sonar calculation
// Still publishing the depth and normal image (just because)
// Depth image
this->depth_image_msg_.header.frame_id
= this->frame_name_;
this->depth_image_msg_.header.stamp.sec
= this->depth_sensor_update_time_.sec;
this->depth_image_msg_.header.stamp.nsec
= this->depth_sensor_update_time_.nsec;
img_bridge = cv_bridge::CvImage(this->depth_image_msg_.header,
sensor_msgs::image_encodings::TYPE_32FC1,
depth_image);
// from cv_bridge to sensor_msgs::Image
img_bridge.toImageMsg(this->depth_image_msg_);
this->depth_image_pub_.publish(this->depth_image_msg_);
// Normal image
this->normal_image_msg_.header.frame_id
= this->frame_name_;
this->normal_image_msg_.header.stamp.sec
= this->depth_sensor_update_time_.sec;
this->normal_image_msg_.header.stamp.nsec
= this->depth_sensor_update_time_.nsec;
cv::Mat normal_image8;
normal_image.convertTo(normal_image8, CV_8UC3, 255.0);
img_bridge = cv_bridge::CvImage(this->normal_image_msg_.header,
sensor_msgs::image_encodings::RGB8,
normal_image8);
img_bridge.toImageMsg(this->normal_image_msg_);
// from cv_bridge to sensor_msgs::Image
this->normal_image_pub_.publish(this->normal_image_msg_);
this->lock_.unlock();
}
void NpsGazeboRosImageSonar::ComputePointCloud(const float *_src)
{
this->lock_.lock();
this->point_cloud_msg_.header.frame_id
= this->frame_name_;
this->point_cloud_msg_.header.stamp.sec
= this->depth_sensor_update_time_.sec;
this->point_cloud_msg_.header.stamp.nsec
= this->depth_sensor_update_time_.nsec;
this->point_cloud_msg_.width = this->width;
this->point_cloud_msg_.height = this->height;
this->point_cloud_msg_.row_step
= this->point_cloud_msg_.point_step * this->width;
sensor_msgs::PointCloud2Modifier pcd_modifier(point_cloud_msg_);
pcd_modifier.setPointCloud2FieldsByString(2, "xyz", "rgb");
pcd_modifier.resize(this->height * this->width);
// resize if point cloud image to camera parameters if required
this->point_cloud_image_.create(this->height, this->width, CV_32FC1);
sensor_msgs::PointCloud2Iterator<float> iter_x(point_cloud_msg_, "x");
sensor_msgs::PointCloud2Iterator<float> iter_y(point_cloud_msg_, "y");
sensor_msgs::PointCloud2Iterator<float> iter_z(point_cloud_msg_, "z");
sensor_msgs::PointCloud2Iterator<uint8_t> iter_rgb(point_cloud_msg_, "rgb");
cv::MatIterator_<float> iter_image = this->point_cloud_image_.begin<float>();
point_cloud_msg_.is_dense = true;
float* toCopyFrom = const_cast<float*>(_src);
int index = 0;
double hfov = this->parentSensor->DepthCamera()->HFOV().Radian();
double fl = static_cast<double>(this->width) / (2.0 * tan(hfov/2.0));
for (uint32_t j = 0; j < this->height; j++)
{
double elevation;
if (this->height > 1)
elevation = atan2(static_cast<double>(j) -
0.5 * static_cast<double>(this->height-1), fl);
else
elevation = 0.0;
for (uint32_t i = 0; i < this->width;
i++, ++iter_x, ++iter_y, ++iter_z, ++iter_rgb, ++iter_image)
{
double azimuth;
if (this->width > 1)
azimuth = atan2(static_cast<double>(i) -
0.5 * static_cast<double>(this->width-1), fl);
else
azimuth = 0.0;
double depth = toCopyFrom[index++];
// in optical frame hardcoded rotation
// rpy(-M_PI/2, 0, -M_PI/2) is built-in
// to urdf, where the *_optical_frame should have above relative
// rotation from the physical camera *_frame
*iter_x = depth * tan(azimuth);
*iter_y = depth * tan(elevation);
if (depth > this->point_cloud_cutoff_)
{
*iter_z = depth;
*iter_image = sqrt(*iter_x * *iter_x +
*iter_y * *iter_y +
*iter_z * *iter_z);
}
else // point in the unseeable range
{
*iter_x = *iter_y = *iter_z = std::numeric_limits<float>::quiet_NaN();
*iter_image = 0.0;
point_cloud_msg_.is_dense = false;
}
// put image color data for each point
uint8_t* image_src = static_cast<uint8_t*>(&(this->image_msg_.data[0]));
if (this->image_msg_.data.size() == this->height * this->width*3)
{
// color
iter_rgb[0] = image_src[i*3+j*this->width*3+0];
iter_rgb[1] = image_src[i*3+j*this->width*3+1];
iter_rgb[2] = image_src[i*3+j*this->width*3+2];
}
else if (this->image_msg_.data.size() == this->height * this->width)
{
// mono (or bayer? @todo; fix for bayer)
iter_rgb[0] = image_src[i+j*this->width];
iter_rgb[1] = image_src[i+j*this->width];
iter_rgb[2] = image_src[i+j*this->width];
}
else
{
// no image
iter_rgb[0] = 0;
iter_rgb[1] = 0;
iter_rgb[2] = 0;
}
}
}
if (this->point_cloud_connect_count_ > 0)
this->point_cloud_pub_.publish(this->point_cloud_msg_);
this->lock_.unlock();
}
/////////////////////////////////////////////////
// incidence angle is target's normal angle accounting for the ray's azimuth
// and elevation
double NpsGazeboRosImageSonar::ComputeIncidence(double azimuth,
double elevation,
cv::Vec3f normal)
{
// ray normal from camera azimuth and elevation
double camera_x = cos(-azimuth)*cos(elevation);
double camera_y = sin(-azimuth)*cos(elevation);
double camera_z = sin(elevation);
cv::Vec3f ray_normal(camera_x, camera_y, camera_z);
// target normal with axes compensated to camera axes
cv::Vec3f target_normal(normal[2], -normal[0], -normal[1]);
// dot product
double dot_product = ray_normal.dot(target_normal);
return M_PI - acos(dot_product);
}
/////////////////////////////////////////////////
// Precalculation of corrector sonar calculation
void NpsGazeboRosImageSonar::ComputeCorrector()
{
double hFOV = this->parentSensor->DepthCamera()->HFOV().Radian();
double hPixelSize = hFOV / this->width;
// Beam culling correction precalculation
for (size_t beam = 0; beam < nBeams; beam ++)
{
float beam_azimuthAngle = -(hFOV/2.0) + beam * hPixelSize + hPixelSize/2.0;
for (size_t beam_other = 0; beam_other < nBeams; beam_other ++)
{
float beam_azimuthAngle_other
= -(hFOV/2.0) + beam_other * hPixelSize + hPixelSize/2.0;
float azimuthBeamPattern =
unnormalized_sinc(M_PI * 0.884 / hPixelSize
* sin(beam_azimuthAngle-beam_azimuthAngle_other));
this->beamCorrector[beam][beam_other] = azimuthBeamPattern;
this->beamCorrectorSum += pow(azimuthBeamPattern, 2);
}
}
this->beamCorrectorSum = sqrt(this->beamCorrectorSum);
}
/////////////////////////////////////////////////
cv::Mat NpsGazeboRosImageSonar::ComputeNormalImage(cv::Mat& depth)
{
// filters
cv::Mat_<float> f1 = (cv::Mat_<float>(3, 3) << 1, 2, 1,
0, 0, 0,
-1, -2, -1) / 8;
cv::Mat_<float> f2 = (cv::Mat_<float>(3, 3) << 1, 0, -1,
2, 0, -2,
1, 0, -1) / 8;
cv::Mat f1m, f2m;
cv::flip(f1, f1m, 0);
cv::flip(f2, f2m, 1);
cv::Mat n1, n2;
cv::filter2D(depth, n1, -1, f1m, cv::Point(-1, -1), 0, cv::BORDER_REPLICATE);
cv::filter2D(depth, n2, -1, f2m, cv::Point(-1, -1), 0, cv::BORDER_REPLICATE);
cv::Mat no_readings;
cv::erode(depth == 0, no_readings, cv::Mat(), cv::Point(-1, -1), 2, 1, 1);
// cv::dilate(no_readings, no_readings, cv::Mat(),
// cv::Point(-1, -1), 2, 1, 1);
n1.setTo(0, no_readings);
n2.setTo(0, no_readings);
std::vector<cv::Mat> images(3);
cv::Mat white = cv::Mat::ones(depth.rows, depth.cols, CV_32FC1);
// NOTE: with different focal lengths, the expression becomes
// (-dzx*fy, -dzy*fx, fx*fy)
images.at(0) = n1; // for green channel
images.at(1) = n2; // for red channel
images.at(2) = 1.0/this->focal_length_*depth; // for blue channel
cv::Mat normal_image;
cv::merge(images, normal_image);
for (int i = 0; i < normal_image.rows; ++i)
{
for (int j = 0; j < normal_image.cols; ++j)
{
cv::Vec3f& n = normal_image.at<cv::Vec3f>(i, j);
n = cv::normalize(n);
float& d = depth.at<float>(i, j);
}
}
return normal_image;
}
/////////////////////////////////////////////////
void NpsGazeboRosImageSonar::PublishCameraInfo()
{
ROS_DEBUG_NAMED("depth_camera",
"publishing default camera info, then depth camera info");
GazeboRosCameraUtils::PublishCameraInfo();
if (this->depth_info_connect_count_ > 0)
{
common::Time sensor_update_time
= this->parentSensor_->LastMeasurementTime();
this->sensor_update_time_ = sensor_update_time;
if (sensor_update_time
- this->last_depth_image_camera_info_update_time_
>= this->update_period_)
{
this->PublishCameraInfo(this->depth_image_camera_info_pub_);
// , sensor_update_time);
this->last_depth_image_camera_info_update_time_ = sensor_update_time;
}
}
}
}
|
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a✝ : α
s : Multiset α
h : ∀ (a : α) (t : Multiset α), s ≠ a ::ₘ a ::ₘ t
a : α
le : a ::ₘ a ::ₘ 0 ≤ s
t : Multiset α
s_eq : s = a ::ₘ a ::ₘ 0 + t
⊢ s = a ::ₘ a ::ₘ t
[PROOFSTEP]
rwa [cons_add, cons_add, zero_add] at s_eq
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t : Multiset α
a : α
inst✝ : DecidableEq α
s : Multiset α
_l : List α
⊢ Nodup (Quot.mk Setoid.r _l) ↔ ∀ (a : α), count a (Quot.mk Setoid.r _l) ≤ 1
[PROOFSTEP]
simp only [quot_mk_to_coe'', coe_nodup, mem_coe, coe_count]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t : Multiset α
a : α
inst✝ : DecidableEq α
s : Multiset α
_l : List α
⊢ List.Nodup _l ↔ ∀ (a : α), List.count a _l ≤ 1
[PROOFSTEP]
apply List.nodup_iff_count_le_one
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t : Multiset α
a✝ : α
inst✝ : DecidableEq α
a : α
s : Multiset α
d : Nodup s
⊢ count a s = if a ∈ s then 1 else 0
[PROOFSTEP]
split_ifs with h
[GOAL]
case pos
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t : Multiset α
a✝ : α
inst✝ : DecidableEq α
a : α
s : Multiset α
d : Nodup s
h : a ∈ s
⊢ count a s = 1
[PROOFSTEP]
exact count_eq_one_of_mem d h
[GOAL]
case neg
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t : Multiset α
a✝ : α
inst✝ : DecidableEq α
a : α
s : Multiset α
d : Nodup s
h : ¬a ∈ s
⊢ count a s = 0
[PROOFSTEP]
exact count_eq_zero_of_not_mem h
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s t : Multiset α
a : α
d₁ : Nodup s
d₂ : Nodup t
⊢ Nodup (s + t) ↔ Disjoint s t
[PROOFSTEP]
simp [nodup_add, d₁, d₂]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s t : Multiset α
a✝ : α
inst✝ : DecidableEq α
a b : α
l : Multiset α
d : Nodup l
⊢ a ∈ Multiset.erase l b ↔ a ≠ b ∧ a ∈ l
[PROOFSTEP]
rw [d.erase_eq_filter b, mem_filter, and_comm]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s t✝ : Multiset α
a : α
t : Multiset β
l₁ : List α
l₂ : List β
d₁ : Nodup (Quotient.mk (isSetoid α) l₁)
d₂ : Nodup (Quotient.mk (isSetoid β) l₂)
⊢ Nodup (Quotient.mk (isSetoid α) l₁ ×ˢ Quotient.mk (isSetoid β) l₂)
[PROOFSTEP]
simp [List.Nodup.product d₁ d₂]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s t✝ : Multiset α
a : α
σ : α → Type u_4
t : (a : α) → Multiset (σ a)
l₁ : List α
⊢ Nodup (Quot.mk Setoid.r l₁) → (∀ (a : α), Nodup (t a)) → Nodup (Multiset.sigma (Quot.mk Setoid.r l₁) t)
[PROOFSTEP]
choose f hf using fun a => Quotient.exists_rep (t a)
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s t✝ : Multiset α
a : α
σ : α → Type u_4
t : (a : α) → Multiset (σ a)
l₁ : List α
f : (a : α) → List (σ a)
hf : ∀ (a : α), Quotient.mk (isSetoid (σ a)) (f a) = t a
⊢ Nodup (Quot.mk Setoid.r l₁) → (∀ (a : α), Nodup (t a)) → Nodup (Multiset.sigma (Quot.mk Setoid.r l₁) t)
[PROOFSTEP]
simpa [← funext hf] using List.Nodup.sigma
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a✝ : α
inst✝ : DecidableEq α
s t : Multiset α
x✝ : Nodup s ∧ Nodup t
h₁ : Nodup s
h₂ : Nodup t
a : α
⊢ count a (s ∪ t) ≤ 1
[PROOFSTEP]
rw [count_union]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a✝ : α
inst✝ : DecidableEq α
s t : Multiset α
x✝ : Nodup s ∧ Nodup t
h₁ : Nodup s
h₂ : Nodup t
a : α
⊢ max (count a s) (count a t) ≤ 1
[PROOFSTEP]
exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a : α
s : Multiset α
t : α → Multiset β
h₁ : ∀ (a : α), ∃ l, t a = ↑l
t' : α → List β
h' : ∀ (x : α), t x = ↑(t' x)
this : t = fun a => ↑(t' a)
hd : Symmetric fun a b => List.Disjoint (t' a) (t' b)
⊢ ∀ (a : List α),
Nodup (bind (Quot.mk Setoid.r a) t) ↔
(∀ (a_1 : α), a_1 ∈ Quot.mk Setoid.r a → Nodup (t a_1)) ∧
Pairwise (fun a b => Disjoint (t a) (t b)) (Quot.mk Setoid.r a)
[PROOFSTEP]
simp [this, List.nodup_bind, pairwise_coe_iff_pairwise hd]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a✝ : α
inst✝ : DecidableEq α
a : α
s t : Multiset α
d : Nodup s
h : a ∈ s - t
h' : a ∈ t
⊢ False
[PROOFSTEP]
refine' count_eq_zero.1 _ h
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a✝ : α
inst✝ : DecidableEq α
a : α
s t : Multiset α
d : Nodup s
h : a ∈ s - t
h' : a ∈ t
⊢ count a (s - t) = 0
[PROOFSTEP]
rw [count_sub a s t, tsub_eq_zero_iff_le]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a✝ : α
inst✝ : DecidableEq α
a : α
s t : Multiset α
d : Nodup s
h : a ∈ s - t
h' : a ∈ t
⊢ count a s ≤ count a t
[PROOFSTEP]
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a : α
f : α → γ
g : β → γ
s : Multiset α
t : Multiset β
hs : Nodup s
ht : Nodup t
i : (a : α) → a ∈ s → β
hi : ∀ (a : α) (ha : a ∈ s), i a ha ∈ t
h : ∀ (a : α) (ha : a ∈ s), f a = g (i a ha)
i_inj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂
i_surj : ∀ (b : β), b ∈ t → ∃ a ha, b = i a ha
x : β
⊢ x ∈ t ↔ x ∈ map (fun x => i ↑x (_ : ↑x ∈ s)) (attach s)
[PROOFSTEP]
simp only [mem_map, true_and_iff, Subtype.exists, eq_comm, mem_attach]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a : α
f : α → γ
g : β → γ
s : Multiset α
t : Multiset β
hs : Nodup s
ht : Nodup t
i : (a : α) → a ∈ s → β
hi : ∀ (a : α) (ha : a ∈ s), i a ha ∈ t
h : ∀ (a : α) (ha : a ∈ s), f a = g (i a ha)
i_inj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂
i_surj : ∀ (b : β), b ∈ t → ∃ a ha, b = i a ha
x : β
⊢ x ∈ t ↔ ∃ a h, x = i a (_ : ↑{ val := a, property := (_ : a ∈ s) } ∈ s)
[PROOFSTEP]
exact ⟨i_surj _, fun ⟨y, hy⟩ => hy.snd.symm ▸ hi _ _⟩
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a : α
f : α → γ
g : β → γ
s : Multiset α
t : Multiset β
hs : Nodup s
ht : Nodup t
i : (a : α) → a ∈ s → β
hi : ∀ (a : α) (ha : a ∈ s), i a ha ∈ t
h : ∀ (a : α) (ha : a ∈ s), f a = g (i a ha)
i_inj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂
i_surj : ∀ (b : β), b ∈ t → ∃ a ha, b = i a ha
this : t = map (fun x => i ↑x (_ : ↑x ∈ s)) (attach s)
⊢ map f s = pmap (fun x x_1 => f x) s (_ : ∀ (x : α), x ∈ s → x ∈ s)
[PROOFSTEP]
rw [pmap_eq_map]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a : α
f : α → γ
g : β → γ
s : Multiset α
t : Multiset β
hs : Nodup s
ht : Nodup t
i : (a : α) → a ∈ s → β
hi : ∀ (a : α) (ha : a ∈ s), i a ha ∈ t
h : ∀ (a : α) (ha : a ∈ s), f a = g (i a ha)
i_inj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂
i_surj : ∀ (b : β), b ∈ t → ∃ a ha, b = i a ha
this : t = map (fun x => i ↑x (_ : ↑x ∈ s)) (attach s)
⊢ pmap (fun x x_1 => f x) s (_ : ∀ (x : α), x ∈ s → x ∈ s) = map (fun x => f ↑x) (attach s)
[PROOFSTEP]
rw [pmap_eq_map_attach]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a : α
f : α → γ
g : β → γ
s : Multiset α
t : Multiset β
hs : Nodup s
ht : Nodup t
i : (a : α) → a ∈ s → β
hi : ∀ (a : α) (ha : a ∈ s), i a ha ∈ t
h : ∀ (a : α) (ha : a ∈ s), f a = g (i a ha)
i_inj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂
i_surj : ∀ (b : β), b ∈ t → ∃ a ha, b = i a ha
this : t = map (fun x => i ↑x (_ : ↑x ∈ s)) (attach s)
⊢ map (fun x => f ↑x) (attach s) = map g t
[PROOFSTEP]
rw [this, Multiset.map_map]
[GOAL]
α : Type u_1
β : Type u_2
γ : Type u_3
r : α → α → Prop
s✝ t✝ : Multiset α
a : α
f : α → γ
g : β → γ
s : Multiset α
t : Multiset β
hs : Nodup s
ht : Nodup t
i : (a : α) → a ∈ s → β
hi : ∀ (a : α) (ha : a ∈ s), i a ha ∈ t
h : ∀ (a : α) (ha : a ∈ s), f a = g (i a ha)
i_inj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂
i_surj : ∀ (b : β), b ∈ t → ∃ a ha, b = i a ha
this : t = map (fun x => i ↑x (_ : ↑x ∈ s)) (attach s)
⊢ map (fun x => f ↑x) (attach s) = map (g ∘ fun x => i ↑x (_ : ↑x ∈ s)) (attach s)
[PROOFSTEP]
exact map_congr rfl fun x _ => h _ _
|
// Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#ifndef BOOST_HANA_TEST_AUTO_TRANSFORM_HPP
#define BOOST_HANA_TEST_AUTO_TRANSFORM_HPP
#include <boost/hana/assert.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/transform.hpp>
#include "test_case.hpp"
#include <laws/base.hpp>
TestCase test_transform{[] {
namespace hana = boost::hana;
using hana::test::ct_eq;
struct undefined { };
constexpr hana::test::_injection<0> f{};
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::transform(MAKE_TUPLE(), undefined{}),
MAKE_TUPLE()
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::transform(MAKE_TUPLE(ct_eq<1>{}), f),
MAKE_TUPLE(f(ct_eq<1>{}))
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::transform(MAKE_TUPLE(ct_eq<1>{}, ct_eq<2>{}), f),
MAKE_TUPLE(f(ct_eq<1>{}), f(ct_eq<2>{}))
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::transform(MAKE_TUPLE(ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{}), f),
MAKE_TUPLE(f(ct_eq<1>{}), f(ct_eq<2>{}), f(ct_eq<3>{}))
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::transform(MAKE_TUPLE(ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{}, ct_eq<4>{}), f),
MAKE_TUPLE(f(ct_eq<1>{}), f(ct_eq<2>{}), f(ct_eq<3>{}), f(ct_eq<4>{}))
));
#ifndef MAKE_TUPLE_NO_CONSTEXPR
struct incr {
constexpr int operator()(int i) const { return i + 1; }
};
static_assert(hana::equal(
hana::transform(MAKE_TUPLE(1), incr{}),
MAKE_TUPLE(2)
), "");
static_assert(hana::equal(
hana::transform(MAKE_TUPLE(1, 2), incr{}),
MAKE_TUPLE(2, 3)
), "");
static_assert(hana::equal(
hana::transform(MAKE_TUPLE(1, 2, 3), incr{}),
MAKE_TUPLE(2, 3, 4)
), "");
static_assert(hana::equal(
hana::transform(MAKE_TUPLE(1, 2, 3, 4), incr{}),
MAKE_TUPLE(2, 3, 4, 5)
), "");
#endif
}};
#endif // !BOOST_HANA_TEST_AUTO_TRANSFORM_HPP
|
% -*- root: Main.tex -*-
\section{SVD}
$\mathbf{A} = \mathbf{U} \mathbf{D} \mathbf{V}^\top = \sum_{k=1}^{\operatorname{rank}(\mathbf{A})} d_{k,k} u_k (v_k)^\top$\\
$\mathbf{A} \in \mathbb{R}^{N \times P}, \mathbf{U} \in \mathbb{R}^{N \times N}, \mathbf{D} \in \mathbb{R}^{N \times P}, \mathbf{V} \in \mathbb{R}^{P \times P}$\\
$\mathbf{U}^\top \mathbf{U} = I = \mathbf{V}^\top \mathbf{V}$ ($\mathbf{U}, \mathbf{V}$ orthogonal)\\
$\mathbf{U}$ columns are eigenvectors of $\mathbf{A} \mathbf{A}^\top$, $\mathbf{V}$ columns are eigenvectors of $\mathbf{A}^\top \mathbf{A}$, $\mathbf{D}$ diagonal elements are singular values.\\
$(\mathbf{D}^{-1})_{i,i} = \frac{1}{\mathbf{D}_{i, i}}$ (don't forget to transpose)
1. calculate $\mathbf{A}^\top \mathbf{A}$.\\
2. calculate eigenvalues of $\mathbf{A}^\top \mathbf{A}$, the square root of them, in descending order, are the diagonal elements of $\mathbf{D}$.\\
3. calculate eigenvectors of $\mathbf{A}^\top \mathbf{A}$ using the eigenvalues resulting in the columns of $\mathbf{V}$.\\
4. calculate the missing matrix: $\mathbf{U} = \mathbf{A} \mathbf{V} \mathbf{D}^{-1}$.\\
5. normalize each column of $\mathbf{U}$ and $\mathbf{V}$.
\subsection*{Low-Rank approximation}
Using only $K$ largest eigenvalues and corresponding eigenvectors. $\tilde{\mathbf{A}}_{i, j} = \sum_{k=1}^K \mathbf{U}_{i, k} \mathbf{D}_{k,k} \mathbf{V}_{j, k} = \sum_{k=1}^K \mathbf{U}_{i, k} \mathbf{D}_{k,k} (\mathbf{V}^\top)_{k, j}$.
\subsection*{Collaborative Filtering \textendash\ Prediction}
For $\mathbf{U}, \mathbf{V}$ (Movie-/User-embedding) use $k$-rank approx (fill up dimensions). Predict user preferences: $\mathbf{U_k} \mathbf{U_k^T} b$.
\subsection*{Echart-Young Theorem}
$\min_{rank(B)=K} ||A-B||_F^2 = ||A-A_k||_F^2 = \sum_{r=k+1}^{rank(A)} \sigma_r^2$
$\min_{rank(B)=K} ||A-B||_2 = ||A-A_k||_2 = \sigma_{k+1}$
|
module Loading
import JSON
import Tables
using AtBackslash: @\
using BangBang
using Transducers
function as_sorted_namedtuple(d)
xs = sort!(collect(d); by = first)
(; (Symbol(k) => v for (k, v) in xs)...)
end
paths_to_rows_xf(; bench_xf = Map(identity), result_xf = Map(identity)) =
Map(as_sorted_namedtuple ∘ JSON.parsefile) |> Zip(
Map(x -> delete!!(x, :benchmarks)), # broadcast scalars
MapCat(@\ _.benchmarks) |> Map(as_sorted_namedtuple),
) |> MapSplat(merge) |> bench_xf |> Zip(
Map(x -> delete!!(x, :results)), # broadcast scalars
MapCat(@\ _.results) |> Map(as_sorted_namedtuple),
) |> MapSplat(merge) |> result_xf |> Zip(
Map(x -> delete!!(x, :trial)), # broadcast scalars
MapCat() do x
Tables.namedtupleiterator((
time = x[:trial]["times"],
gctime = x[:trial]["gctimes"],
itime = 1:length(x[:trial]["times"]),
))
end,
) |> MapSplat(merge)
results(jsonpath::AbstractString; kw...) = results([jsonpath]; kw...)
results(jsonpaths::AbstractVector{<:AbstractString}; kw...) =
eduction(paths_to_rows_xf(; kw...), jsonpaths)
results_by_benchname(benchname::AbstractString, args...; kw...) =
results_by_benchname(==(benchname), args...; kw...)
results_by_benchname(predicate, args...; kw...) = results(
args...;
bench_xf = Filter(@\ predicate(:benchname)),
result_xf = Map(x -> merge(delete!!(x, :parameter), as_sorted_namedtuple(x.parameter))),
kw...,
)
end # module
|
import topology.tactic
import topology.instances.real
example {X : Type*} [topological_space X] : continuous (@id X) :=
by { continuity, }
example : continuous (λ (x : ℝ), -x) :=
by { exact continuous_id'.neg, }
|
(*
Author: René Thiemann
Akihisa Yamada
License: BSD
*)
subsection \<open>Missing List\<close>
text \<open>The provides some standard algorithms and lemmas on lists.\<close>
theory Missing_List
imports
Matrix.Utility
"HOL-Library.Monad_Syntax"
begin
fun concat_lists :: "'a list list \<Rightarrow> 'a list list" where
"concat_lists [] = [[]]"
| "concat_lists (as # xs) = concat (map (\<lambda>vec. map (\<lambda>a. a # vec) as) (concat_lists xs))"
lemma concat_lists_listset: "set (concat_lists xs) = listset (map set xs)"
by (induct xs, auto simp: set_Cons_def)
lemma sum_list_concat: "sum_list (concat ls) = sum_list (map sum_list ls)"
by (induct ls, auto)
(* TODO: move to src/HOL/List *)
lemma listset: "listset xs = { ys. length ys = length xs \<and> (\<forall> i < length xs. ys ! i \<in> xs ! i)}"
proof (induct xs)
case (Cons x xs)
let ?n = "length xs"
from Cons
have "?case = (set_Cons x {ys. length ys = ?n \<and> (\<forall>i < ?n. ys ! i \<in> xs ! i)} =
{ys. length ys = Suc ?n \<and> ys ! 0 \<in> x \<and> (\<forall>i < ?n. ys ! Suc i \<in> xs ! i)})"
(is "_ = (?L = ?R)")
by (auto simp: all_Suc_conv)
also have "?L = ?R"
by (auto simp: set_Cons_def, case_tac xa, auto)
finally show ?case by simp
qed auto
declare concat_lists.simps[simp del]
fun find_map_filter :: "('a \<Rightarrow> 'b) \<Rightarrow> ('b \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> 'b option" where
"find_map_filter f p [] = None"
| "find_map_filter f p (a # as) = (let b = f a in if p b then Some b else find_map_filter f p as)"
lemma find_map_filter_None: "find_map_filter f p as = None \<Longrightarrow> \<forall> b \<in> f ` set as. \<not> p b"
by (induct f p as rule: find_map_filter.induct, auto simp: Let_def split: if_splits)
lemma remdups_adj_sorted_distinct[simp]: "sorted xs \<Longrightarrow> distinct (remdups_adj xs)"
by (induct xs rule: remdups_adj.induct) (auto)
lemma subseqs_length_simple:
assumes "b \<in> set (subseqs xs)" shows "length b \<le> length xs"
using assms by(induct xs arbitrary:b;auto simp:Let_def Suc_leD)
lemma subseqs_length_simple_False:
assumes "b \<in> set (subseqs xs)" " length xs < length b" shows False
using assms subseqs_length_simple by fastforce
lemma full_list_subseqs: "{ys. ys \<in> set (subseqs xs) \<and> length ys = length xs} = {xs}"
proof (induct xs)
case (Cons x xs)
have "?case = ({ys \<in> (#) x ` set (subseqs xs) \<union> set (subseqs xs).
length ys = Suc (length xs)} = (#) x ` {xs})" (is "_ = (?l = ?r)")
by (auto simp: Let_def)
also have "?l = {ys \<in> (#) x ` set (subseqs xs). length ys = Suc (length xs)}"
using length_subseqs[of xs]
using subseqs_length_simple_False by force
also have "\<dots> = (#) x ` {ys \<in> set (subseqs xs). length ys = length xs}"
by auto
also have "\<dots> = (#) x ` {xs}" unfolding Cons by auto
finally show ?case by simp
qed simp
lemma nth_concat_split: assumes "i < length (concat xs)"
shows "\<exists> j k. j < length xs \<and> k < length (xs ! j) \<and> concat xs ! i = xs ! j ! k"
using assms
proof (induct xs arbitrary: i)
case (Cons x xs i)
define I where "I = i - length x"
show ?case
proof (cases "i < length x")
case True note l = this
hence i: "concat (Cons x xs) ! i = x ! i" by (auto simp: nth_append)
show ?thesis unfolding i
by (rule exI[of _ 0], rule exI[of _ i], insert Cons l, auto)
next
case False note l = this
from l Cons(2) have i: "i = length x + I" "I < length (concat xs)" unfolding I_def by auto
hence iI: "concat (Cons x xs) ! i = concat xs ! I" by (auto simp: nth_append)
from Cons(1)[OF i(2)] obtain j k where
IH: "j < length xs \<and> k < length (xs ! j) \<and> concat xs ! I = xs ! j ! k" by auto
show ?thesis unfolding iI
by (rule exI[of _ "Suc j"], rule exI[of _ k], insert IH, auto)
qed
qed simp
lemma nth_concat_diff: assumes "i1 < length (concat xs)" "i2 < length (concat xs)" "i1 \<noteq> i2"
shows "\<exists> j1 k1 j2 k2. (j1,k1) \<noteq> (j2,k2) \<and> j1 < length xs \<and> j2 < length xs
\<and> k1 < length (xs ! j1) \<and> k2 < length (xs ! j2)
\<and> concat xs ! i1 = xs ! j1 ! k1 \<and> concat xs ! i2 = xs ! j2 ! k2"
using assms
proof (induct xs arbitrary: i1 i2)
case (Cons x xs)
define I1 where "I1 = i1 - length x"
define I2 where "I2 = i2 - length x"
show ?case
proof (cases "i1 < length x")
case True note l1 = this
hence i1: "concat (Cons x xs) ! i1 = x ! i1" by (auto simp: nth_append)
show ?thesis
proof (cases "i2 < length x")
case True note l2 = this
hence i2: "concat (Cons x xs) ! i2 = x ! i2" by (auto simp: nth_append)
show ?thesis unfolding i1 i2
by (rule exI[of _ 0], rule exI[of _ i1], rule exI[of _ 0], rule exI[of _ i2],
insert Cons(4) l1 l2, auto)
next
case False note l2 = this
from l2 Cons(3) have i22: "i2 = length x + I2" "I2 < length (concat xs)" unfolding I2_def by auto
hence i2: "concat (Cons x xs) ! i2 = concat xs ! I2" by (auto simp: nth_append)
from nth_concat_split[OF i22(2)] obtain j2 k2 where
*: "j2 < length xs \<and> k2 < length (xs ! j2) \<and> concat xs ! I2 = xs ! j2 ! k2" by auto
show ?thesis unfolding i1 i2
by (rule exI[of _ 0], rule exI[of _ i1], rule exI[of _ "Suc j2"], rule exI[of _ k2],
insert * l1, auto)
qed
next
case False note l1 = this
from l1 Cons(2) have i11: "i1 = length x + I1" "I1 < length (concat xs)" unfolding I1_def by auto
hence i1: "concat (Cons x xs) ! i1 = concat xs ! I1" by (auto simp: nth_append)
show ?thesis
proof (cases "i2 < length x")
case False note l2 = this
from l2 Cons(3) have i22: "i2 = length x + I2" "I2 < length (concat xs)" unfolding I2_def by auto
hence i2: "concat (Cons x xs) ! i2 = concat xs ! I2" by (auto simp: nth_append)
from Cons(4) i11 i22 have diff: "I1 \<noteq> I2" by auto
from Cons(1)[OF i11(2) i22(2) diff] obtain j1 k1 j2 k2
where IH: "(j1,k1) \<noteq> (j2,k2) \<and> j1 < length xs \<and> j2 < length xs
\<and> k1 < length (xs ! j1) \<and> k2 < length (xs ! j2)
\<and> concat xs ! I1 = xs ! j1 ! k1 \<and> concat xs ! I2 = xs ! j2 ! k2" by auto
show ?thesis unfolding i1 i2
by (rule exI[of _ "Suc j1"], rule exI[of _ k1], rule exI[of _ "Suc j2"], rule exI[of _ k2],
insert IH, auto)
next
case True note l2 = this
hence i2: "concat (Cons x xs) ! i2 = x ! i2" by (auto simp: nth_append)
from nth_concat_split[OF i11(2)] obtain j1 k1 where
*: "j1 < length xs \<and> k1 < length (xs ! j1) \<and> concat xs ! I1 = xs ! j1 ! k1" by auto
show ?thesis unfolding i1 i2
by (rule exI[of _ "Suc j1"], rule exI[of _ k1], rule exI[of _ 0], rule exI[of _ i2],
insert * l2, auto)
qed
qed
qed auto
lemma list_all2_map_map: "(\<And> x. x \<in> set xs \<Longrightarrow> R (f x) (g x)) \<Longrightarrow> list_all2 R (map f xs) (map g xs)"
by (induct xs, auto)
subsection \<open>Partitions\<close>
text \<open>Check whether a list of sets forms a partition, i.e.,
whether the sets are pairwise disjoint.\<close>
definition is_partition :: "('a set) list \<Rightarrow> bool" where
"is_partition cs \<longleftrightarrow> (\<forall>j<length cs. \<forall>i<j. cs ! i \<inter> cs ! j = {})"
(* and an equivalent but more symmetric version *)
definition is_partition_alt :: "('a set) list \<Rightarrow> bool" where
"is_partition_alt cs \<longleftrightarrow> (\<forall> i j. i < length cs \<and> j < length cs \<and> i \<noteq> j \<longrightarrow> cs!i \<inter> cs!j = {})"
lemma is_partition_alt: "is_partition = is_partition_alt"
proof (intro ext)
fix cs :: "'a set list"
{
assume "is_partition_alt cs"
hence "is_partition cs" unfolding is_partition_def is_partition_alt_def by auto
}
moreover
{
assume part: "is_partition cs"
have "is_partition_alt cs" unfolding is_partition_alt_def
proof (intro allI impI)
fix i j
assume "i < length cs \<and> j < length cs \<and> i \<noteq> j"
with part show "cs ! i \<inter> cs ! j = {}"
unfolding is_partition_def
by (cases "i < j", simp, cases "j < i", force, simp)
qed
}
ultimately
show "is_partition cs = is_partition_alt cs" by auto
qed
lemma is_partition_Nil:
"is_partition [] = True" unfolding is_partition_def by auto
lemma is_partition_Cons:
"is_partition (x#xs) \<longleftrightarrow> is_partition xs \<and> x \<inter> \<Union>(set xs) = {}" (is "?l = ?r")
proof
assume ?l
have one: "is_partition xs"
proof (unfold is_partition_def, intro allI impI)
fix j i assume "j < length xs" and "i < j"
hence "Suc j < length(x#xs)" and "Suc i < Suc j" by auto
from \<open>?l\<close>[unfolded is_partition_def,THEN spec,THEN mp,THEN spec,THEN mp,OF this]
have "(x#xs)!(Suc i) \<inter> (x#xs)!(Suc j) = {}" .
thus "xs!i \<inter> xs!j = {}" by simp
qed
have two: "x \<inter> \<Union>(set xs) = {}"
proof (rule ccontr)
assume "x \<inter> \<Union>(set xs) \<noteq> {}"
then obtain y where "y \<in> x" and "y \<in> \<Union>(set xs)" by auto
then obtain z where "z \<in> set xs" and "y \<in> z" by auto
then obtain i where "i < length xs" and "xs!i = z" using in_set_conv_nth[of z xs] by auto
with \<open>y \<in> z\<close> have "y \<in> (x#xs)!Suc i" by auto
moreover with \<open>y \<in> x\<close> have "y \<in> (x#xs)!0" by simp
ultimately have "(x#xs)!0 \<inter> (x#xs)!Suc i \<noteq> {}" by auto
moreover from \<open>i < length xs\<close> have "Suc i < length(x#xs)" by simp
ultimately show False using \<open>?l\<close>[unfolded is_partition_def] by best
qed
from one two show ?r ..
next
assume ?r
show ?l
proof (unfold is_partition_def, intro allI impI)
fix j i
assume j: "j < length (x # xs)"
assume i: "i < j"
from i obtain j' where j': "j = Suc j'" by (cases j, auto)
with j have j'len: "j' < length xs" and j'elem: "(x # xs) ! j = xs ! j'" by auto
show "(x # xs) ! i \<inter> (x # xs) ! j = {}"
proof (cases i)
case 0
with j'elem have "(x # xs) ! i \<inter> (x # xs) ! j = x \<inter> xs ! j'" by auto
also have "\<dots> \<subseteq> x \<inter> \<Union>(set xs)" using j'len by force
finally show ?thesis using \<open>?r\<close> by auto
next
case (Suc i')
with i j' have i'j': "i' < j'" by auto
from Suc j' have "(x # xs) ! i \<inter> (x # xs) ! j = xs ! i' \<inter> xs ! j'" by auto
with \<open>?r\<close> i'j' j'len show ?thesis unfolding is_partition_def by auto
qed
qed
qed
lemma is_partition_sublist:
assumes "is_partition (us @ xs @ ys @ zs @ vs)"
shows "is_partition (xs @ zs)"
proof (rule ccontr)
assume "\<not> is_partition (xs @ zs)"
then obtain i j where j:"j < length (xs @ zs)" and i:"i < j" and *:"(xs @ zs) ! i \<inter> (xs @ zs) ! j \<noteq> {}"
unfolding is_partition_def by blast
then show False
proof (cases "j < length xs")
case True
let ?m = "j + length us"
let ?n = "i + length us"
from True have "?m < length (us @ xs @ ys @ zs @ vs)" by auto
moreover from i have "?n < ?m" by auto
moreover have "(us @ xs @ ys @ zs @ vs) ! ?n \<inter> (us @ xs @ ys @ zs @ vs) ! ?m \<noteq> {}"
using i True * nth_append
by (metis (no_types, lifting) add_diff_cancel_right' not_add_less2 order.strict_trans)
ultimately show False using assms unfolding is_partition_def by auto
next
case False
let ?m = "j + length us + length ys"
from j have m:"?m < length (us @ xs @ ys @ zs @ vs)" by auto
have mj:"(us @ (xs @ ys @ zs @ vs)) ! ?m = (xs @ zs) ! j" unfolding nth_append using False j by auto
show False
proof (cases "i < length xs")
case True
let ?n = "i + length us"
from i have "?n < ?m" by auto
moreover have "(us @ xs @ ys @ zs @ vs) ! ?n = (xs @ zs) ! i" by (simp add: True nth_append)
ultimately show False using * m assms mj unfolding is_partition_def by blast
next
case False
let ?n = "i + length us + length ys"
from i have i:"?n < ?m" by auto
moreover have "(us @ xs @ ys @ zs @ vs) ! ?n = (xs @ zs) ! i"
unfolding nth_append using False i j less_diff_conv2 by auto
ultimately show False using * m assms mj unfolding is_partition_def by blast
qed
qed
qed
lemma is_partition_inj_map:
assumes "is_partition xs"
and "inj_on f (\<Union>x \<in> set xs. x)"
shows "is_partition (map ((`) f) xs)"
proof (rule ccontr)
assume "\<not> is_partition (map ((`) f) xs)"
then obtain i j where neq:"i \<noteq> j"
and i:"i < length (map ((`) f) xs)" and j:"j < length (map ((`) f) xs)"
and "map ((`) f) xs ! i \<inter> map ((`) f) xs ! j \<noteq> {}"
unfolding is_partition_alt is_partition_alt_def by auto
then obtain x where "x \<in> map ((`) f) xs ! i" and "x \<in> map ((`) f) xs ! j" by auto
then obtain y z where yi:"y \<in> xs ! i" and yx:"f y = x" and zj:"z \<in> xs ! j" and zx:"f z = x"
using i j by auto
show False
proof (cases "y = z")
case True
with zj yi neq assms(1) i j show ?thesis by (auto simp: is_partition_alt is_partition_alt_def)
next
case False
have "y \<in> (\<Union>x \<in> set xs. x)" using yi i by force
moreover have "z \<in> (\<Union>x \<in> set xs. x)" using zj j by force
ultimately show ?thesis using assms(2) inj_on_def[of f "(\<Union>x\<in>set xs. x)"] False zx yx by blast
qed
qed
context
begin
private fun is_partition_impl :: "'a set list \<Rightarrow> 'a set option" where
"is_partition_impl [] = Some {}"
| "is_partition_impl (as # rest) = do {
all \<leftarrow> is_partition_impl rest;
if as \<inter> all = {} then Some (all \<union> as) else None
}"
lemma is_partition_code[code]: "is_partition as = (is_partition_impl as \<noteq> None)"
proof -
note [simp] = is_partition_Cons is_partition_Nil
have "\<And> bs. (is_partition as = (is_partition_impl as \<noteq> None)) \<and>
(is_partition_impl as = Some bs \<longrightarrow> bs = \<Union> (set as))"
proof (induct as)
case (Cons as rest bs)
show ?case
proof (cases "is_partition rest")
case False
thus ?thesis using Cons by auto
next
case True
with Cons obtain c where rest: "is_partition_impl rest = Some c"
by (cases "is_partition_impl rest", auto)
with Cons True show ?thesis by auto
qed
qed auto
thus ?thesis by blast
qed
end
lemma case_prod_partition:
"case_prod f (partition p xs) = f (filter p xs) (filter (Not \<circ> p) xs)"
by simp
lemmas map_id[simp] = list.map_id
subsection \<open>merging functions\<close>
definition fun_merge :: "('a \<Rightarrow> 'b)list \<Rightarrow> 'a set list \<Rightarrow> 'a \<Rightarrow> 'b"
where "fun_merge fs as a \<equiv> (fs ! (LEAST i. i < length as \<and> a \<in> as ! i)) a"
lemma fun_merge: assumes
i: "i < length as"
and a: "a \<in> as ! i"
and ident: "\<And> i j a. i < length as \<Longrightarrow> j < length as \<Longrightarrow> a \<in> as ! i \<Longrightarrow> a \<in> as ! j \<Longrightarrow> (fs ! i) a = (fs ! j) a"
shows "fun_merge fs as a = (fs ! i) a"
proof -
let ?p = "\<lambda> i. i < length as \<and> a \<in> as ! i"
let ?l = "LEAST i. ?p i"
have p: "?p ?l"
by (rule LeastI, insert i a, auto)
show ?thesis unfolding fun_merge_def
by (rule ident[OF _ i _ a], insert p, auto)
qed
lemma fun_merge_part: assumes
part: "is_partition as"
and i: "i < length as"
and a: "a \<in> as ! i"
shows "fun_merge fs as a = (fs ! i) a"
proof(rule fun_merge[OF i a])
fix i j a
assume "i < length as" and "j < length as" and "a \<in> as ! i" and "a \<in> as ! j"
hence "i = j" using part[unfolded is_partition_alt is_partition_alt_def] by (cases "i = j", auto)
thus "(fs ! i) a = (fs ! j) a" by simp
qed
lemma map_nth_conv: "map f ss = map g ts \<Longrightarrow> \<forall>i < length ss. f(ss!i) = g(ts!i)"
proof (intro allI impI)
fix i show "map f ss = map g ts \<Longrightarrow> i < length ss \<Longrightarrow> f(ss!i) = g(ts!i)"
proof (induct ss arbitrary: i ts)
case Nil thus ?case by (induct ts) auto
next
case (Cons s ss) thus ?case
by (induct ts, simp, (cases i, auto))
qed
qed
lemma distinct_take_drop:
assumes dist: "distinct vs" and len: "i < length vs" shows "distinct(take i vs @ drop (Suc i) vs)" (is "distinct(?xs@?ys)")
proof -
from id_take_nth_drop[OF len] have vs[symmetric]: "vs = ?xs @ vs!i # ?ys" .
with dist have "distinct ?xs" and "distinct(vs!i#?ys)" and "set ?xs \<inter> set(vs!i#?ys) = {}" using distinct_append[of ?xs "vs!i#?ys"] by auto
hence "distinct ?ys" and "set ?xs \<inter> set ?ys = {}" by auto
with \<open>distinct ?xs\<close> show ?thesis using distinct_append[of ?xs ?ys] vs by simp
qed
lemma map_nth_eq_conv:
assumes len: "length xs = length ys"
shows "(map f xs = ys) = (\<forall>i<length ys. f (xs ! i) = ys ! i)" (is "?l = ?r")
proof -
have "(map f xs = ys) = (map f xs = map id ys)" by auto
also have "... = (\<forall> i < length ys. f (xs ! i) = id (ys ! i))"
using map_nth_conv[of f xs id ys] nth_map_conv[OF len, of f id] unfolding len
by blast
finally show ?thesis by auto
qed
lemma map_upt_len_conv:
"map (\<lambda> i . f (xs!i)) [0..<length xs] = map f xs"
by (rule nth_equalityI, auto)
lemma map_upt_add':
"map f [a..<a+b] = map (\<lambda> i. f (a + i)) [0..<b]"
by (induct b, auto)
definition generate_lists :: "nat \<Rightarrow> 'a list \<Rightarrow> 'a list list"
where "generate_lists n xs \<equiv> concat_lists (map (\<lambda> _. xs) [0 ..< n])"
lemma set_generate_lists[simp]: "set (generate_lists n xs) = {as. length as = n \<and> set as \<subseteq> set xs}"
proof -
{
fix as
have "(length as = n \<and> (\<forall>i<n. as ! i \<in> set xs)) = (length as = n \<and> set as \<subseteq> set xs)"
proof -
{
assume "length as = n"
hence n: "n = length as" by auto
have "(\<forall>i<n. as ! i \<in> set xs) = (set as \<subseteq> set xs)" unfolding n
unfolding all_set_conv_all_nth[of as "\<lambda> x. x \<in> set xs", symmetric] by auto
}
thus ?thesis by auto
qed
}
thus ?thesis unfolding generate_lists_def unfolding set_concat_lists by auto
qed
lemma nth_append_take:
assumes "i \<le> length xs" shows "(take i xs @ y#ys)!i = y"
proof -
from assms have a: "length(take i xs) = i" by simp
have "(take i xs @ y#ys)!(length(take i xs)) = y" by (rule nth_append_length)
thus ?thesis unfolding a .
qed
lemma nth_append_take_is_nth_conv:
assumes "i < j" and "j \<le> length xs" shows "(take j xs @ ys)!i = xs!i"
proof -
from assms have "i < length(take j xs)" by simp
hence "(take j xs @ ys)!i = take j xs ! i" unfolding nth_append by simp
thus ?thesis unfolding nth_take[OF assms(1)] .
qed
lemma nth_append_drop_is_nth_conv:
assumes "j < i" and "j \<le> length xs" and "i \<le> length xs"
shows "(take j xs @ y # drop (Suc j) xs)!i = xs!i"
proof -
from \<open>j < i\<close> obtain n where ij: "Suc(j + n) = i" using less_imp_Suc_add by auto
with assms have i: "i = length(take j xs) + Suc n" by auto
have len: "Suc j + n \<le> length xs" using assms i by auto
have "(take j xs @ y # drop (Suc j) xs)!i =
(y # drop (Suc j) xs)!(i - length(take j xs))" unfolding nth_append i by auto
also have "\<dots> = (y # drop (Suc j) xs)!(Suc n)" unfolding i by simp
also have "\<dots> = (drop (Suc j) xs)!n" by simp
finally show ?thesis using ij len by simp
qed
lemma nth_append_take_drop_is_nth_conv:
assumes "i \<le> length xs" and "j \<le> length xs" and "i \<noteq> j"
shows "(take j xs @ y # drop (Suc j) xs)!i = xs!i"
proof -
from assms have "i < j \<or> i > j" by auto
thus ?thesis using assms
by (auto simp: nth_append_take_is_nth_conv nth_append_drop_is_nth_conv)
qed
lemma take_drop_imp_nth: "\<lbrakk>take i ss @ x # drop (Suc i) ss = ss\<rbrakk> \<Longrightarrow> x = ss!i"
proof (induct ss arbitrary: i)
case (Cons s ss)
from \<open>take i (s#ss) @ x # drop (Suc i) (s#ss) = (s#ss)\<close> show ?case
proof (induct i)
case (Suc i)
from Cons have IH: "take i ss @ x # drop (Suc i) ss = ss \<Longrightarrow> x = ss!i" by auto
from Suc have "take i ss @ x # drop (Suc i) ss = ss" by auto
with IH show ?case by auto
qed auto
qed auto
lemma take_drop_update_first: assumes "j < length ds" and "length cs = length ds"
shows "(take j ds @ drop j cs)[j := ds ! j] = take (Suc j) ds @ drop (Suc j) cs"
using assms
proof (induct j arbitrary: ds cs)
case 0
then obtain d dds c ccs where ds: "ds = d # dds" and cs: "cs = c # ccs" by (cases ds, simp, cases cs, auto)
show ?case unfolding ds cs by auto
next
case (Suc j)
then obtain d dds c ccs where ds: "ds = d # dds" and cs: "cs = c # ccs" by (cases ds, simp, cases cs, auto)
from Suc(1)[of dds ccs] Suc(2) Suc(3) show ?case unfolding ds cs by auto
qed
lemma take_drop_update_second: assumes "j < length ds" and "length cs = length ds"
shows "(take j ds @ drop j cs)[j := cs ! j] = take j ds @ drop j cs"
using assms
proof (induct j arbitrary: ds cs)
case 0
then obtain d dds c ccs where ds: "ds = d # dds" and cs: "cs = c # ccs" by (cases ds, simp, cases cs, auto)
show ?case unfolding ds cs by auto
next
case (Suc j)
then obtain d dds c ccs where ds: "ds = d # dds" and cs: "cs = c # ccs" by (cases ds, simp, cases cs, auto)
from Suc(1)[of dds ccs] Suc(2) Suc(3) show ?case unfolding ds cs by auto
qed
lemma nth_take_prefix:
"length ys \<le> length xs \<Longrightarrow> \<forall>i < length ys. xs!i = ys!i \<Longrightarrow> take (length ys) xs = ys"
proof (induct xs ys rule: list_induct2')
case (4 x xs y ys)
have "take (length ys) xs = ys"
by (rule 4(1), insert 4(2-3), auto)
moreover from 4(3) have "x = y" by auto
ultimately show ?case by auto
qed auto
lemma take_upt_idx:
assumes i: "i < length ls"
shows "take i ls = [ ls ! j . j \<leftarrow> [0..<i]]"
proof -
have e: "0 + i \<le> i" by auto
show ?thesis
using take_upt[OF e] take_map map_nth
by (metis (hide_lams, no_types) add.left_neutral i nat_less_le take_upt)
qed
fun distinct_eq :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> bool" where
"distinct_eq _ [] = True"
| "distinct_eq eq (x # xs) = ((\<forall> y \<in> set xs. \<not> (eq y x)) \<and> distinct_eq eq xs)"
lemma distinct_eq_append: "distinct_eq eq (xs @ ys) = (distinct_eq eq xs \<and> distinct_eq eq ys \<and> (\<forall> x \<in> set xs. \<forall> y \<in> set ys. \<not> (eq y x)))"
by (induct xs, auto)
lemma append_Cons_nth_left:
assumes "i < length xs"
shows "(xs @ u # ys) ! i = xs ! i"
using assms nth_append[of xs _ i] by simp
lemma append_Cons_nth_middle:
assumes "i = length xs"
shows "(xs @ y # zs) ! i = y"
using assms by auto
lemma append_Cons_nth_right:
assumes "i > length xs"
shows "(xs @ u # ys) ! i = (xs @ z # ys) ! i"
proof -
from assms have "i - length xs > 0" by auto
then obtain j where j: "i - length xs = Suc j" by (cases "i - length xs", auto)
thus ?thesis by (simp add: nth_append)
qed
lemma append_Cons_nth_not_middle:
assumes "i \<noteq> length xs"
shows "(xs @ u # ys) ! i = (xs @ z # ys) ! i"
proof (cases "i < length xs")
case True
thus ?thesis by (simp add: append_Cons_nth_left)
next
case False
with assms have "i > length xs" by arith
thus ?thesis by (rule append_Cons_nth_right)
qed
lemmas append_Cons_nth = append_Cons_nth_middle append_Cons_nth_not_middle
lemma concat_all_nth:
assumes "length xs = length ys"
and "\<And>i. i < length xs \<Longrightarrow> length (xs ! i) = length (ys ! i)"
and "\<And>i j. i < length xs \<Longrightarrow> j < length (xs ! i) \<Longrightarrow> P (xs ! i ! j) (ys ! i ! j)"
shows "\<forall>k<length (concat xs). P (concat xs ! k) (concat ys ! k)"
using assms
proof (induct xs ys rule: list_induct2)
case (Cons x xs y ys)
from Cons(3)[of 0] have xy: "length x = length y" by simp
from Cons(4)[of 0] xy have pxy: "\<And> j. j < length x \<Longrightarrow> P (x ! j) (y ! j)" by auto
{
fix i
assume i: "i < length xs"
with Cons(3)[of "Suc i"]
have len: "length (xs ! i) = length (ys ! i)" by simp
from Cons(4)[of "Suc i"] i have "\<And> j. j < length (xs ! i) \<Longrightarrow> P (xs ! i ! j) (ys ! i ! j)"
by auto
note len and this
}
from Cons(2)[OF this] have ind: "\<And> k. k < length (concat xs) \<Longrightarrow> P (concat xs ! k) (concat ys ! k)"
by auto
show ?case unfolding concat.simps
proof (intro allI impI)
fix k
assume k: "k < length (x @ concat xs)"
show "P ((x @ concat xs) ! k) ((y @ concat ys) ! k)"
proof (cases "k < length x")
case True
show ?thesis unfolding nth_append using True xy pxy[OF True]
by simp
next
case False
with k have "k - (length x) < length (concat xs)" by auto
then obtain n where n: "k - length x = n" and nxs: "n < length (concat xs)" by auto
show ?thesis unfolding nth_append n n[unfolded xy] using False xy ind[OF nxs]
by auto
qed
qed
qed auto
lemma eq_length_concat_nth:
assumes "length xs = length ys"
and "\<And>i. i < length xs \<Longrightarrow> length (xs ! i) = length (ys ! i)"
shows "length (concat xs) = length (concat ys)"
using assms
proof (induct xs ys rule: list_induct2)
case (Cons x xs y ys)
from Cons(3)[of 0] have xy: "length x = length y" by simp
{
fix i
assume "i < length xs"
with Cons(3)[of "Suc i"]
have "length (xs ! i) = length (ys ! i)" by simp
}
from Cons(2)[OF this] have ind: "length (concat xs) = length (concat ys)" by simp
show ?case using xy ind by auto
qed auto
primrec
list_union :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list"
where
"list_union [] ys = ys"
| "list_union (x # xs) ys = (let zs = list_union xs ys in if x \<in> set zs then zs else x # zs)"
lemma set_list_union[simp]: "set (list_union xs ys) = set xs \<union> set ys"
proof (induct xs)
case (Cons x xs) thus ?case by (cases "x \<in> set (list_union xs ys)") (auto)
qed simp
declare list_union.simps[simp del]
(*Why was list_inter thrown out of List.thy?*)
fun list_inter :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"list_inter [] bs = []"
| "list_inter (a#as) bs =
(if a \<in> set bs then a # list_inter as bs else list_inter as bs)"
lemma set_list_inter[simp]:
"set (list_inter xs ys) = set xs \<inter> set ys"
by (induct rule: list_inter.induct) simp_all
declare list_inter.simps[simp del]
primrec list_diff :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"list_diff [] ys = []"
| "list_diff (x # xs) ys = (let zs = list_diff xs ys in if x \<in> set ys then zs else x # zs)"
lemma set_list_diff[simp]:
"set (list_diff xs ys) = set xs - set ys"
proof (induct xs)
case (Cons x xs) thus ?case by (cases "x \<in> set ys") (auto)
qed simp
declare list_diff.simps[simp del]
lemma set_foldr_remdups_set_map_conv[simp]:
"set (foldr (\<lambda>x xs. remdups (f x @ xs)) xs []) = \<Union>(set (map (set \<circ> f) xs))"
by (induct xs) auto
lemma subset_set_code[code_unfold]: "set xs \<subseteq> set ys \<longleftrightarrow> list_all (\<lambda>x. x \<in> set ys) xs"
unfolding list_all_iff by auto
fun union_list_sorted where
"union_list_sorted (x # xs) (y # ys) =
(if x = y then x # union_list_sorted xs ys
else if x < y then x # union_list_sorted xs (y # ys)
else y # union_list_sorted (x # xs) ys)"
| "union_list_sorted [] ys = ys"
| "union_list_sorted xs [] = xs"
fun subtract_list_sorted :: "('a :: linorder) list \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"subtract_list_sorted (x # xs) (y # ys) =
(if x = y then subtract_list_sorted xs (y # ys)
else if x < y then x # subtract_list_sorted xs (y # ys)
else subtract_list_sorted (x # xs) ys)"
| "subtract_list_sorted [] ys = []"
| "subtract_list_sorted xs [] = xs"
lemma set_subtract_list_sorted[simp]: "sorted xs \<Longrightarrow> sorted ys \<Longrightarrow>
set (subtract_list_sorted xs ys) = set xs - set ys"
proof (induct xs ys rule: subtract_list_sorted.induct)
case (1 x xs y ys)
have xxs: "sorted (x # xs)" by fact
have yys: "sorted (y # ys)" by fact
have xs: "sorted xs" using xxs by (simp)
show ?case
proof (cases "x = y")
case True
thus ?thesis using 1(1)[OF True xs yys] by auto
next
case False note neq = this
note IH = 1(2-3)[OF this]
show ?thesis
by (cases "x < y", insert IH xxs yys False, auto)
qed
qed auto
lemma subset_subtract_listed_sorted: "set (subtract_list_sorted xs ys) \<subseteq> set xs"
by (induct xs ys rule: subtract_list_sorted.induct, auto)
lemma set_subtract_list_distinct[simp]: "distinct xs \<Longrightarrow> distinct (subtract_list_sorted xs ys)"
by (induct xs ys rule: subtract_list_sorted.induct, insert subset_subtract_listed_sorted, auto)
definition "remdups_sort xs = remdups_adj (sort xs)"
lemma remdups_sort[simp]: "sorted (remdups_sort xs)" "set (remdups_sort xs) = set xs"
"distinct (remdups_sort xs)"
by (simp_all add: remdups_sort_def)
text \<open>maximum and minimum\<close>
lemma max_list_mono: assumes "\<And> x. x \<in> set xs - set ys \<Longrightarrow> \<exists> y. y \<in> set ys \<and> x \<le> y"
shows "max_list xs \<le> max_list ys"
using assms
proof (induct xs)
case (Cons x xs)
have "x \<le> max_list ys"
proof (cases "x \<in> set ys")
case True
from max_list[OF this] show ?thesis .
next
case False
with Cons(2)[of x] obtain y where y: "y \<in> set ys"
and xy: "x \<le> y" by auto
from xy max_list[OF y] show ?thesis by arith
qed
moreover have "max_list xs \<le> max_list ys"
by (rule Cons(1)[OF Cons(2)], auto)
ultimately show ?case by auto
qed auto
fun min_list :: "('a :: linorder) list \<Rightarrow> 'a" where
"min_list [x] = x"
| "min_list (x # xs) = min x (min_list xs)"
lemma min_list: "(x :: 'a :: linorder) \<in> set xs \<Longrightarrow> min_list xs \<le> x"
proof (induct xs)
case oCons : (Cons y ys)
show ?case
proof (cases ys)
case Nil
thus ?thesis using oCons by auto
next
case (Cons z zs)
hence id: "min_list (y # ys) = min y (min_list ys)"
by auto
show ?thesis
proof (cases "x = y")
case True
show ?thesis unfolding id True by auto
next
case False
have "min y (min_list ys) \<le> min_list ys" by auto
also have "... \<le> x" using oCons False by auto
finally show ?thesis unfolding id .
qed
qed
qed simp
lemma min_list_Cons:
assumes xy: "x \<le> y"
and len: "length xs = length ys"
and xsys: "min_list xs \<le> min_list ys"
shows "min_list (x # xs) \<le> min_list (y # ys)"
proof (cases xs)
case Nil
with len have ys: "ys = []" by simp
with xy Nil show ?thesis by simp
next
case (Cons x' xs')
with len obtain y' ys' where ys: "ys = y' # ys'" by (cases ys, auto)
from Cons have one: "min_list (x # xs) = min x (min_list xs)" by auto
from ys have two: "min_list (y # ys) = min y (min_list ys)" by auto
show ?thesis unfolding one two using xy xsys
unfolding min_def by auto
qed
lemma min_list_nth:
assumes "length xs = length ys"
and "\<And>i. i < length ys \<Longrightarrow> xs ! i \<le> ys ! i"
shows "min_list xs \<le> min_list ys"
using assms
proof (induct xs arbitrary: ys)
case (Cons x xs zs)
from Cons(2) obtain y ys where zs: "zs = y # ys" by (cases zs, auto)
note Cons = Cons[unfolded zs]
from Cons(2) have len: "length xs = length ys" by simp
from Cons(3)[of 0] have xy: "x \<le> y" by simp
{
fix i
assume "i < length xs"
with Cons(3)[of "Suc i"] Cons(2)
have "xs ! i \<le> ys ! i" by simp
}
from Cons(1)[OF len this] Cons(2) have ind: "min_list xs \<le> min_list ys" by simp
show ?case unfolding zs
by (rule min_list_Cons[OF xy len ind])
qed auto
lemma min_list_ex:
assumes "xs \<noteq> []" shows "\<exists>x\<in>set xs. min_list xs = x"
using assms
proof (induct xs)
case oCons : (Cons x xs)
show ?case
proof (cases xs)
case (Cons y ys)
hence id: "min_list (x # xs) = min x (min_list xs)" and nNil: "xs \<noteq> []" by auto
show ?thesis
proof (cases "x \<le> min_list xs")
case True
show ?thesis unfolding id
by (rule bexI[of _ x], insert True, auto simp: min_def)
next
case False
show ?thesis unfolding id min_def
using oCons(1)[OF nNil] False by auto
qed
qed auto
qed auto
lemma min_list_subset:
assumes subset: "set ys \<subseteq> set xs" and mem: "min_list xs \<in> set ys"
shows "min_list xs = min_list ys"
proof -
from subset mem have "xs \<noteq> []" by auto
from min_list_ex[OF this] obtain x where x: "x \<in> set xs" and mx: "min_list xs = x" by auto
from min_list[OF mem] have two: "min_list ys \<le> min_list xs" by auto
from mem have "ys \<noteq> []" by auto
from min_list_ex[OF this] obtain y where y: "y \<in> set ys" and my: "min_list ys = y" by auto
from y subset have "y \<in> set xs" by auto
from min_list[OF this] have one: "min_list xs \<le> y" by auto
from one two
show ?thesis unfolding mx my by auto
qed
text\<open>Apply a permutation to a list.\<close>
primrec permut_aux :: "'a list \<Rightarrow> (nat \<Rightarrow> nat) \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"permut_aux [] _ _ = []" |
"permut_aux (a # as) f bs = (bs ! f 0) # (permut_aux as (\<lambda>n. f (Suc n)) bs)"
definition permut :: "'a list \<Rightarrow> (nat \<Rightarrow> nat) \<Rightarrow> 'a list" where
"permut as f = permut_aux as f as"
declare permut_def[simp]
lemma permut_aux_sound:
assumes "i < length as"
shows "permut_aux as f bs ! i = bs ! (f i)"
using assms proof (induct as arbitrary: i f bs)
case (Cons x xs)
show ?case
proof (cases i)
case (Suc j)
with Cons(2) have "j < length xs" by simp
from Cons(1)[OF this] and Suc show ?thesis by simp
qed simp
qed simp
lemma permut_sound:
assumes "i < length as"
shows "permut as f ! i = as ! (f i)"
using assms and permut_aux_sound by simp
lemma permut_aux_length:
assumes "bij_betw f {..<length as} {..<length bs}"
shows "length (permut_aux as f bs) = length as"
by (induct as arbitrary: f bs, simp_all)
lemma permut_length:
assumes "bij_betw f {..< length as} {..< length as}"
shows "length (permut as f) = length as"
using permut_aux_length[OF assms] by simp
declare permut_def[simp del]
lemma foldl_assoc:
fixes b :: "('a \<Rightarrow> 'a) \<Rightarrow> ('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "\<cdot>" 55)
assumes "\<And>f g h. f \<cdot> (g \<cdot> h) = f \<cdot> g \<cdot> h"
shows "foldl (\<cdot>) (x \<cdot> y) zs = x \<cdot> foldl (\<cdot>) y zs"
using assms[symmetric] by (induct zs arbitrary: y) simp_all
lemma foldr_assoc:
assumes "\<And>f g h. b (b f g) h = b f (b g h)"
shows "foldr b xs (b y z) = b (foldr b xs y) z"
using assms by (induct xs) simp_all
lemma foldl_foldr_o_id:
"foldl (\<circ>) id fs = foldr (\<circ>) fs id"
proof (induct fs)
case (Cons f fs)
have "id \<circ> f = f \<circ> id" by simp
with Cons [symmetric] show ?case
by (simp only: foldl_Cons foldr_Cons o_apply [of _ _ id] foldl_assoc o_assoc)
qed simp
lemma foldr_o_o_id[simp]:
"foldr ((\<circ>) \<circ> f) xs id a = foldr f xs a"
by (induct xs) simp_all
lemma Ex_list_of_length_P:
assumes "\<forall>i<n. \<exists>x. P x i"
shows "\<exists>xs. length xs = n \<and> (\<forall>i<n. P (xs ! i) i)"
proof -
from assms have "\<forall> i. \<exists> x. i < n \<longrightarrow> P x i" by simp
from choice[OF this] obtain xs where xs: "\<And> i. i < n \<Longrightarrow> P (xs i) i" by auto
show ?thesis
by (rule exI[of _ "map xs [0 ..< n]"], insert xs, auto)
qed
lemma ex_set_conv_ex_nth: "(\<exists>x\<in>set xs. P x) = (\<exists>i<length xs. P (xs ! i))"
using in_set_conv_nth[of _ xs] by force
lemma map_eq_set_zipD [dest]:
assumes "map f xs = map f ys"
and "(x, y) \<in> set (zip xs ys)"
shows "f x = f y"
using assms
proof (induct xs arbitrary: ys)
case (Cons x xs)
then show ?case by (cases ys) auto
qed simp
fun span :: "('a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> 'a list \<times> 'a list" where
"span P (x # xs) =
(if P x then let (ys, zs) = span P xs in (x # ys, zs)
else ([], x # xs))" |
"span _ [] = ([], [])"
lemma span[simp]: "span P xs = (takeWhile P xs, dropWhile P xs)"
by (induct xs, auto)
declare span.simps[simp del]
lemma parallel_list_update: assumes
one_update: "\<And> xs i y. length xs = n \<Longrightarrow> i < n \<Longrightarrow> r (xs ! i) y \<Longrightarrow> p xs \<Longrightarrow> p (xs[i := y])"
and init: "length xs = n" "p xs"
and rel: "length ys = n" "\<And> i. i < n \<Longrightarrow> r (xs ! i) (ys ! i)"
shows "p ys"
proof -
note len = rel(1) init(1)
{
fix i
assume "i \<le> n"
hence "p (take i ys @ drop i xs)"
proof (induct i)
case 0 with init show ?case by simp
next
case (Suc i)
hence IH: "p (take i ys @ drop i xs)" by simp
from Suc have i: "i < n" by simp
let ?xs = "(take i ys @ drop i xs)"
have "length ?xs = n" using i len by simp
from one_update[OF this i _ IH, of "ys ! i"] rel(2)[OF i] i len
show ?case by (simp add: nth_append take_drop_update_first)
qed
}
from this[of n] show ?thesis using len by auto
qed
lemma nth_concat_two_lists:
"i < length (concat (xs :: 'a list list)) \<Longrightarrow> length (ys :: 'b list list) = length xs
\<Longrightarrow> (\<And> i. i < length xs \<Longrightarrow> length (ys ! i) = length (xs ! i))
\<Longrightarrow> \<exists> j k. j < length xs \<and> k < length (xs ! j) \<and> (concat xs) ! i = xs ! j ! k \<and>
(concat ys) ! i = ys ! j ! k"
proof (induct xs arbitrary: i ys)
case (Cons x xs i yys)
then obtain y ys where yys: "yys = y # ys" by (cases yys, auto)
note Cons = Cons[unfolded yys]
from Cons(4)[of 0] have [simp]: "length y = length x" by simp
show ?case
proof (cases "i < length x")
case True
show ?thesis unfolding yys
by (rule exI[of _ 0], rule exI[of _ i], insert True Cons(2-4), auto simp: nth_append)
next
case False
let ?i = "i - length x"
from False Cons(2-3) have "?i < length (concat xs)" "length ys = length xs" by auto
note IH = Cons(1)[OF this]
{
fix i
assume "i < length xs"
with Cons(4)[of "Suc i"] have "length (ys ! i) = length (xs ! i)" by simp
}
from IH[OF this]
obtain j k where IH1: "j < length xs" "k < length (xs ! j)"
"concat xs ! ?i = xs ! j ! k"
"concat ys ! ?i = ys ! j ! k" by auto
show ?thesis unfolding yys
by (rule exI[of _ "Suc j"], rule exI[of _ k], insert IH1 False, auto simp: nth_append)
qed
qed simp
text \<open>Removing duplicates w.r.t. some function.\<close>
fun remdups_gen :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"remdups_gen f [] = []"
| "remdups_gen f (x # xs) = x # remdups_gen f [y <- xs. \<not> f x = f y]"
lemma remdups_gen_subset: "set (remdups_gen f xs) \<subseteq> set xs"
by (induct f xs rule: remdups_gen.induct, auto)
lemma remdups_gen_elem_imp_elem: "x \<in> set (remdups_gen f xs) \<Longrightarrow> x \<in> set xs"
using remdups_gen_subset[of f xs] by blast
lemma elem_imp_remdups_gen_elem: "x \<in> set xs \<Longrightarrow> \<exists> y \<in> set (remdups_gen f xs). f x = f y"
proof (induct f xs rule: remdups_gen.induct)
case (2 f z zs)
show ?case
proof (cases "f x = f z")
case False
with 2(2) have "x \<in> set [y\<leftarrow>zs . f z \<noteq> f y]" by auto
from 2(1)[OF this] show ?thesis by auto
qed auto
qed auto
lemma take_nth_drop_concat:
assumes "i < length xss" and "xss ! i = ys"
and "j < length ys" and "ys ! j = z"
shows "\<exists>k < length (concat xss).
take k (concat xss) = concat (take i xss) @ take j ys \<and>
concat xss ! k = xss ! i ! j \<and>
drop (Suc k) (concat xss) = drop (Suc j) ys @ concat (drop (Suc i) xss)"
using assms(1, 2)
proof (induct xss arbitrary: i rule: List.rev_induct)
case (snoc xs xss)
then show ?case using assms by (cases "i < length xss") (auto simp: nth_append)
qed simp
lemma concat_map_empty [simp]:
"concat (map (\<lambda>_. []) xs) = []"
by simp
lemma map_upt_len_same_len_conv:
assumes "length xs = length ys"
shows "map (\<lambda>i. f (xs ! i)) [0 ..< length ys] = map f xs"
unfolding assms [symmetric] by (rule map_upt_len_conv)
lemma concat_map_concat [simp]:
"concat (map concat xs) = concat (concat xs)"
by (induct xs) simp_all
lemma concat_concat_map:
"concat (concat (map f xs)) = concat (map (concat \<circ> f) xs)"
by (induct xs) simp_all
lemma UN_upt_len_conv [simp]:
"length xs = n \<Longrightarrow> (\<Union>i \<in> {0 ..< n}. f (xs ! i)) = \<Union>(set (map f xs))"
by (force simp: in_set_conv_nth)
lemma Ball_at_Least0LessThan_conv [simp]:
"length xs = n \<Longrightarrow>
(\<forall>i \<in> {0 ..< n}. P (xs ! i)) \<longleftrightarrow> (\<forall>x \<in> set xs. P x)"
by (metis atLeast0LessThan in_set_conv_nth lessThan_iff)
lemma sum_list_replicate_length [simp]:
"sum_list (replicate (length xs) (Suc 0)) = length xs"
by (induct xs) simp_all
lemma list_all2_in_set2:
assumes "list_all2 P xs ys" and "y \<in> set ys"
obtains x where "x \<in> set xs" and "P x y"
using assms by (induct) auto
lemma map_eq_conv':
"map f xs = map g ys \<longleftrightarrow> length xs = length ys \<and> (\<forall>i < length xs. f (xs ! i) = g (ys ! i))"
by (auto dest: map_eq_imp_length_eq map_nth_conv simp: nth_map_conv)
lemma list_3_cases[case_names Nil 1 2]:
assumes "xs = [] \<Longrightarrow> P"
and "\<And>x. xs = [x] \<Longrightarrow> P"
and "\<And>x y ys. xs = x#y#ys \<Longrightarrow> P"
shows P
using assms by (cases xs; cases "tl xs", auto)
lemma list_4_cases[case_names Nil 1 2 3]:
assumes "xs = [] \<Longrightarrow> P"
and "\<And>x. xs = [x] \<Longrightarrow> P"
and "\<And>x y. xs = [x,y] \<Longrightarrow> P"
and "\<And>x y z zs. xs = x # y # z # zs \<Longrightarrow> P"
shows P
using assms by (cases xs; cases "tl xs"; cases "tl (tl xs)", auto)
lemma foldr_append2 [simp]:
"foldr ((@) \<circ> f) xs (ys @ zs) = foldr ((@) \<circ> f) xs ys @ zs"
by (induct xs) simp_all
lemma foldr_append2_Nil [simp]:
"foldr ((@) \<circ> f) xs [] @ zs = foldr ((@) \<circ> f) xs zs"
unfolding foldr_append2 [symmetric] by simp
lemma UNION_set_zip:
"(\<Union>x \<in> set (zip [0..<length xs] (map f xs)). g x) = (\<Union>i < length xs. g (i, f (xs ! i)))"
by (auto simp: set_conv_nth)
lemma zip_fst: "p \<in> set (zip as bs) \<Longrightarrow> fst p \<in> set as"
by (cases p, rule set_zip_leftD, simp)
lemma zip_snd: "p \<in> set (zip as bs) \<Longrightarrow> snd p \<in> set bs"
by (cases p, rule set_zip_rightD, simp)
lemma zip_size_aux: "size_list (size o snd) (zip ts ls) \<le> (size_list size ls)"
proof (induct ls arbitrary: ts)
case (Cons l ls ts)
thus ?case by (cases ts, auto)
qed auto
text\<open>We definie the function that remove the nth element of
a list. It uses take and drop and the soundness is therefore not
too hard to prove thanks to the already existing lemmas.\<close>
definition remove_nth :: "nat \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"remove_nth n xs \<equiv> (take n xs) @ (drop (Suc n) xs)"
declare remove_nth_def[simp]
lemma remove_nth_len:
assumes i: "i < length xs"
shows "length xs = Suc (length (remove_nth i xs))"
proof -
show ?thesis unfolding arg_cong[where f = "length", OF id_take_nth_drop[OF i]]
unfolding remove_nth_def by simp
qed
lemma remove_nth_length :
assumes n_bd: "n < length xs"
shows "length (remove_nth n xs) = length xs - 1"
proof-
from length_take have ll:"n < length xs \<longrightarrow> length (take n xs) = n" by auto
from length_drop have lr: "length (drop (Suc n) xs) = length xs - (Suc n)" by simp
from ll and lr and length_append and n_bd show ?thesis by auto
qed
lemma remove_nth_id : "length xs \<le> n \<Longrightarrow> remove_nth n xs = xs"
using take_all drop_all append_Nil2 by simp
lemma remove_nth_sound_l :
assumes p_ub: "p < n"
shows "(remove_nth n xs) ! p = xs ! p"
proof (cases "n < length xs")
case True
from length_take and True have ltk: "length (take n xs) = n" by simp
{
assume pltn: "p < n"
from this and ltk have plttk: "p < length (take n xs)" by simp
with nth_append[of "take n xs" _ p]
have "((take n xs) @ (drop (Suc n) xs)) ! p = take n xs ! p" by auto
with pltn and nth_take have "((take n xs) @ (drop (Suc n) xs)) ! p = xs ! p" by simp
}
from this and ltk and p_ub show ?thesis by simp
next
case False
hence "length xs \<le> n" by arith
with remove_nth_id show ?thesis by force
qed
lemma remove_nth_sound_r :
assumes "n \<le> p" and "p < length xs"
shows "(remove_nth n xs) ! p = xs ! (Suc p)"
proof-
from \<open>n \<le> p\<close> and \<open>p < length xs\<close> have n_ub: "n < length xs" by arith
from length_take and n_ub have ltk: "length (take n xs) = n" by simp
from \<open>n \<le> p\<close> and ltk and nth_append[of "take n xs" _ p]
have Hrew: "((take n xs) @ (drop (Suc n) xs)) ! p = drop (Suc n) xs ! (p - n)" by auto
from \<open>n \<le> p\<close> have idx: "Suc n + (p - n) = Suc p" by arith
from \<open>p < length xs\<close> have Sp_ub: "Suc p \<le> length xs" by arith
from idx and Sp_ub and nth_drop have Hrew': "drop (Suc n) xs ! (p - n) = xs ! (Suc p)" by simp
from Hrew and Hrew' show ?thesis by simp
qed
lemma nth_remove_nth_conv:
assumes "i < length (remove_nth n xs)"
shows "remove_nth n xs ! i = xs ! (if i < n then i else Suc i)"
using assms remove_nth_sound_l remove_nth_sound_r[of n i xs] by auto
lemma remove_nth_P_compat :
assumes aslbs: "length as = length bs"
and Pab: "\<forall>i. i < length as \<longrightarrow> P (as ! i) (bs ! i)"
shows "\<forall>i. i < length (remove_nth p as) \<longrightarrow> P (remove_nth p as ! i) (remove_nth p bs ! i)"
proof (cases "p < length as")
case True
hence p_ub: "p < length as" by assumption
with remove_nth_length have lr_ub: "length (remove_nth p as) = length as - 1" by auto
{
fix i assume i_ub: "i < length (remove_nth p as)"
have "P (remove_nth p as ! i) (remove_nth p bs ! i)"
proof (cases "i < p")
case True
from i_ub and lr_ub have i_ub2: "i < length as" by arith
from i_ub2 and Pab have P: "P (as ! i) (bs ! i)" by blast
from P and remove_nth_sound_l[OF True, of as] and remove_nth_sound_l[OF True, of bs]
show ?thesis by simp
next
case False
hence p_ub2: "p \<le> i" by arith
from i_ub and lr_ub have Si_ub: "Suc i < length as" by arith
with Pab have P: "P (as ! Suc i) (bs ! Suc i)" by blast
from i_ub and lr_ub have i_uba: "i < length as" by arith
from i_uba and aslbs have i_ubb: "i < length bs" by simp
from P and p_ub and aslbs and remove_nth_sound_r[OF p_ub2 i_uba]
and remove_nth_sound_r[OF p_ub2 i_ubb]
show ?thesis by auto
qed
}
thus ?thesis by simp
next
case False
hence p_lba: "length as \<le> p" by arith
with aslbs have p_lbb: "length bs \<le> p" by simp
from remove_nth_id[OF p_lba] and remove_nth_id[OF p_lbb] and Pab
show ?thesis by simp
qed
declare remove_nth_def[simp del]
definition adjust_idx :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"adjust_idx i j \<equiv> (if j < i then j else (Suc j))"
definition adjust_idx_rev :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"adjust_idx_rev i j \<equiv> (if j < i then j else j - Suc 0)"
lemma adjust_idx_rev1: "adjust_idx_rev i (adjust_idx i j) = j"
unfolding adjust_idx_def adjust_idx_rev_def by (cases "i < j", auto)
lemma adjust_idx_rev2:
assumes "j \<noteq> i" shows "adjust_idx i (adjust_idx_rev i j) = j"
unfolding adjust_idx_def adjust_idx_rev_def using assms by (cases "i < j", auto)
lemma adjust_idx_i:
"adjust_idx i j \<noteq> i"
unfolding adjust_idx_def by (cases "j < i", auto)
lemma adjust_idx_nth:
assumes i: "i < length xs"
shows "remove_nth i xs ! j = xs ! adjust_idx i j" (is "?l = ?r")
proof -
let ?j = "adjust_idx i j"
from i have ltake: "length (take i xs) = i" by simp
note nth_xs = arg_cong[where f = "\<lambda> xs. xs ! ?j", OF id_take_nth_drop[OF i], unfolded nth_append ltake]
show ?thesis
proof (cases "j < i")
case True
hence j: "?j = j" unfolding adjust_idx_def by simp
show ?thesis unfolding nth_xs unfolding j remove_nth_def nth_append ltake
using True by simp
next
case False
hence j: "?j = Suc j" unfolding adjust_idx_def by simp
from i have lxs: "min (length xs) i = i" by simp
show ?thesis unfolding nth_xs unfolding j remove_nth_def nth_append
using False by (simp add: lxs)
qed
qed
lemma adjust_idx_rev_nth:
assumes i: "i < length xs"
and ji: "j \<noteq> i"
shows "remove_nth i xs ! adjust_idx_rev i j = xs ! j" (is "?l = ?r")
proof -
let ?j = "adjust_idx_rev i j"
from i have ltake: "length (take i xs) = i" by simp
note nth_xs = arg_cong[where f = "\<lambda> xs. xs ! j", OF id_take_nth_drop[OF i], unfolded nth_append ltake]
show ?thesis
proof (cases "j < i")
case True
hence j: "?j = j" unfolding adjust_idx_rev_def by simp
show ?thesis unfolding nth_xs unfolding j remove_nth_def nth_append ltake
using True by simp
next
case False
with ji have ji: "j > i" by auto
hence j: "?j = j - Suc 0" unfolding adjust_idx_rev_def by simp
show ?thesis unfolding nth_xs unfolding j remove_nth_def nth_append ltake
using ji by auto
qed
qed
lemma adjust_idx_length:
assumes i: "i < length xs"
and j: "j < length (remove_nth i xs)"
shows "adjust_idx i j < length xs"
using j unfolding remove_nth_len[OF i] adjust_idx_def by (cases "j < i", auto)
lemma adjust_idx_rev_length:
assumes "i < length xs"
and "j < length xs"
and "j \<noteq> i"
shows "adjust_idx_rev i j < length (remove_nth i xs)"
using assms by (cases "j < i") (simp_all add: adjust_idx_rev_def remove_nth_len[OF assms(1)])
text\<open>If a binary relation holds on two couples of lists, then it holds on
the concatenation of the two couples.\<close>
lemma P_as_bs_extend:
assumes lab: "length as = length bs"
and lcd: "length cs = length ds"
and nsab: "\<forall>i. i < length bs \<longrightarrow> P (as ! i) (bs ! i)"
and nscd: "\<forall>i. i < length ds \<longrightarrow> P (cs ! i) (ds ! i)"
shows "\<forall>i. i < length (bs @ ds) \<longrightarrow> P ((as @ cs) ! i) ((bs @ ds) ! i)"
proof-
{
fix i
assume i_bd: "i < length (bs @ ds)"
have "P ((as @ cs) ! i) ((bs @ ds) ! i)"
proof (cases "i < length as")
case True
with nth_append and nsab and lab
show ?thesis by metis
next
case False
with lab and lcd and i_bd and length_append[of bs ds]
have "(i - length as) < length cs" by arith
with False and nth_append[of _ _ i] and lab and lcd
and nscd[rule_format] show ?thesis by metis
qed
}
thus ?thesis by clarify
qed
text\<open>Extension of filter and partition to binary relations.\<close>
fun filter2 :: "('a \<Rightarrow> 'b \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> 'b list \<Rightarrow> ('a list \<times> 'b list)" where
"filter2 P [] _ = ([], [])" |
"filter2 P _ [] = ([], [])" |
"filter2 P (a # as) (b # bs) = (if P a b
then (a # fst (filter2 P as bs), b # snd (filter2 P as bs))
else filter2 P as bs)"
lemma filter2_length:
"length (fst (filter2 P as bs)) \<equiv> length (snd (filter2 P as bs))"
proof (induct as arbitrary: bs)
case Nil
show ?case by simp
next
case (Cons a as) note IH = this
thus ?case proof (cases bs)
case Nil
thus ?thesis by simp
next
case (Cons b bs)
thus ?thesis proof (cases "P a b")
case True
with Cons and IH show ?thesis by simp
next
case False
with Cons and IH show ?thesis by simp
qed
qed
qed
lemma filter2_sound: "\<forall>i. i < length (fst (filter2 P as bs)) \<longrightarrow> P (fst (filter2 P as bs) ! i) (snd (filter2 P as bs) ! i)"
proof (induct as arbitrary: bs)
case Nil
thus ?case by simp
next
case (Cons a as) note IH = this
thus ?case proof (cases bs)
case Nil
thus ?thesis by simp
next
case (Cons b bs)
thus ?thesis proof (cases "P a b")
case False
with Cons and IH show ?thesis by simp
next
case True
{
fix i
assume i_bd: "i < length (fst (filter2 P (a # as) (b # bs)))"
have "P (fst (filter2 P (a # as) (b # bs)) ! i) (snd (filter2 P (a # as) (b # bs)) ! i)" proof (cases i)
case 0
with True show ?thesis by simp
next
case (Suc j)
with i_bd and True have "j < length (fst (filter2 P as bs))" by auto
with Suc and IH and True show ?thesis by simp
qed
}
with Cons show ?thesis by simp
qed
qed
qed
definition partition2 :: "('a \<Rightarrow> 'b \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> 'b list \<Rightarrow> ('a list \<times> 'b list) \<times> ('a list \<times> 'b list)" where
"partition2 P as bs \<equiv> ((filter2 P as bs) , (filter2 (\<lambda>a b. \<not> (P a b)) as bs))"
lemma partition2_sound_P: "\<forall>i. i < length (fst (fst (partition2 P as bs))) \<longrightarrow>
P (fst (fst (partition2 P as bs)) ! i) (snd (fst (partition2 P as bs)) ! i)"
proof-
from filter2_sound show ?thesis unfolding partition2_def by simp
qed
lemma partition2_sound_nP: "\<forall>i. i < length (fst (snd (partition2 P as bs))) \<longrightarrow>
\<not> P (fst (snd (partition2 P as bs)) ! i) (snd (snd (partition2 P as bs)) ! i)"
proof-
from filter2_sound show ?thesis unfolding partition2_def by simp
qed
text\<open>Membership decision function that actually returns the
value of the index where the value can be found.\<close>
fun mem_idx :: "'a \<Rightarrow> 'a list \<Rightarrow> nat Option.option" where
"mem_idx _ [] = None" |
"mem_idx x (a # as) = (if x = a then Some 0 else map_option Suc (mem_idx x as))"
lemma mem_idx_sound_output:
assumes "mem_idx x as = Some i"
shows "i < length as \<and> as ! i = x"
using assms proof (induct as arbitrary: i)
case Nil thus ?case by simp
next
case (Cons a as) note IH = this
thus ?case proof (cases "x = a")
case True with IH(2) show ?thesis by simp
next
case False note neq_x_a = this
show ?thesis proof (cases "mem_idx x as")
case None with IH(2) and neq_x_a show ?thesis by simp
next
case (Some j)
with IH(2) and neq_x_a have "i = Suc j" by simp
with IH(1) and Some show ?thesis by simp
qed
qed
qed
lemma mem_idx_sound_output2:
assumes "mem_idx x as = Some i"
shows "\<forall>j. j < i \<longrightarrow> as ! j \<noteq> x"
using assms proof (induct as arbitrary: i)
case Nil thus ?case by simp
next
case (Cons a as) note IH = this
thus ?case proof (cases "x = a")
case True with IH show ?thesis by simp
next
case False note neq_x_a = this
show ?thesis proof (cases "mem_idx x as")
case None with IH(2) and neq_x_a show ?thesis by simp
next
case (Some j)
with IH(2) and neq_x_a have eq_i_Sj: "i = Suc j" by simp
{
fix k assume k_bd: "k < i"
have "(a # as) ! k \<noteq> x"
proof (cases k)
case 0 with neq_x_a show ?thesis by simp
next
case (Suc l)
with k_bd and eq_i_Sj have l_bd: "l < j" by arith
with IH(1) and Some have "as ! l \<noteq> x" by simp
with Suc show ?thesis by simp
qed
}
thus ?thesis by simp
qed
qed
qed
lemma mem_idx_sound:
"(x \<in> set as) = (\<exists>i. mem_idx x as = Some i)"
proof (induct as)
case Nil thus ?case by simp
next
case (Cons a as) note IH = this
show ?case proof (cases "x = a")
case True thus ?thesis by simp
next
case False
{
assume "x \<in> set (a # as)"
with False have "x \<in> set as" by simp
with IH obtain i where Some_i: "mem_idx x as = Some i" by auto
with False have "mem_idx x (a # as) = Some (Suc i)" by simp
hence "\<exists>i. mem_idx x (a # as) = Some i" by simp
}
moreover
{
assume "\<exists>i. mem_idx x (a # as) = Some i"
then obtain i where Some_i: "mem_idx x (a # as) = Some i" by fast
have "x \<in> set as" proof (cases i)
case 0 with mem_idx_sound_output[OF Some_i] and False show ?thesis by simp
next
case (Suc j)
with Some_i and False have "mem_idx x as = Some j" by simp
hence "\<exists>i. mem_idx x as = Some i" by simp
with IH show ?thesis by simp
qed
hence "x \<in> set (a # as)" by simp
}
ultimately show ?thesis by fast
qed
qed
lemma mem_idx_sound2:
"(x \<notin> set as) = (mem_idx x as = None)"
unfolding mem_idx_sound by auto
lemma sum_list_replicate_mono: assumes "w1 \<le> (w2 :: nat)"
shows "sum_list (replicate n w1) \<le> sum_list (replicate n w2)"
proof (induct n)
case (Suc n)
thus ?case using \<open>w1 \<le> w2\<close> by auto
qed simp
lemma all_gt_0_sum_list_map:
assumes *: "\<And>x. f x > (0::nat)"
and x: "x \<in> set xs" and len: "1 < length xs"
shows "f x < (\<Sum>x\<leftarrow>xs. f x)"
using x len
proof (induct xs)
case (Cons y xs)
show ?case
proof (cases "y = x")
case True
with *[of "hd xs"] Cons(3) show ?thesis by (cases xs, auto)
next
case False
with Cons(2) have x: "x \<in> set xs" by auto
then obtain z zs where xs: "xs = z # zs" by (cases xs, auto)
show ?thesis
proof (cases "length zs")
case 0
with x xs *[of y] show ?thesis by auto
next
case (Suc n)
with xs have "1 < length xs" by auto
from Cons(1)[OF x this] show ?thesis by simp
qed
qed
qed simp
lemma finite_distinct_subset:
assumes "finite X"
shows "finite { xs . distinct xs \<and> set xs \<subseteq> X}" (is "finite (?S X)")
proof -
let ?X = "{ { xs. distinct xs \<and> set xs = Y} | Y. Y \<subseteq> X}"
have id: "?S X = \<Union> ?X" by blast
show ?thesis unfolding id
proof (rule finite_Union)
show "finite ?X" using assms by auto
next
fix M
assume "M \<in> ?X"
with finite_distinct show "finite M" by auto
qed
qed
lemma map_of_filter:
assumes "P x"
shows "map_of [(x',y) \<leftarrow> ys. P x'] x = map_of ys x"
proof (induct ys)
case (Cons xy ys)
obtain x' y where xy: "xy = (x',y)" by force
show ?case
by (cases "x' = x", insert assms xy Cons, auto)
qed simp
lemma set_subset_insertI: "set xs \<subseteq> set (List.insert x xs)" by auto
lemma set_removeAll_subset: "set (removeAll x xs) \<subseteq> set xs" by auto
lemma map_of_append_Some:
"map_of xs y = Some z \<Longrightarrow> map_of (xs @ ys) y = Some z"
by (induction xs) auto
lemma map_of_append_None:
"map_of xs y = None \<Longrightarrow> map_of (xs @ ys) y = map_of ys y"
by (induction xs) auto
end
|
[STATEMENT]
lemma bot_ca_lf_rep [intro, simp]:
"(\<bottom>, P) \<in> ca_lf_rep r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<bottom>, P) \<in> ca_lf_rep r
[PROOF STEP]
unfolding ca_lf_rep_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<bottom>, P) \<in> (case r of (rm, rp) \<Rightarrow> {\<bottom>} \<times> UNIV \<union> {(d, P) |d P. (\<exists>n. d = ValN\<cdot>n \<and> unProg P \<Down> DBNum n) \<or> d = ValTT \<and> unProg P \<Down> DBtt \<or> d = ValFF \<and> unProg P \<Down> DBff \<or> (\<exists>f M. d = ValF\<cdot>f \<and> unProg P \<Down> DBAbsN M \<and> (\<forall>(x, X)\<in>unsynlr (undual rm). (f\<cdot>x, mkProg (M<unProg X/0>)) \<in> unsynlr rp)) \<or> (\<exists>f M. d = ValF\<cdot>f \<and> unProg P \<Down> DBAbsV M \<and> f\<cdot>\<bottom> = \<bottom> \<and> (\<forall>(x, X)\<in>unsynlr (undual rm). \<forall>V. unProg X \<Down> V \<longrightarrow> (f\<cdot>x, mkProg (M<V/0>)) \<in> unsynlr rp))})
[PROOF STEP]
by (simp add: split_def)
|
{-# OPTIONS --warning=error #-}
module UselessPrivatePragma where
postulate Char : Set
private
{-# BUILTIN CHAR Char #-}
|
(************************************************************************************)
(** *)
(** The SQLEngines Library *)
(** *)
(** LRI, CNRS & Université Paris-Sud, Université Paris-Saclay *)
(** *)
(** Copyright 2016-2019 : FormalData *)
(** *)
(** Authors: Véronique Benzaken *)
(** Évelyne Contejean *)
(** *)
(************************************************************************************)
Set Implicit Arguments.
Require Import Relations SetoidList List String Ascii Bool ZArith NArith.
Require Import ListFacts OrderedSet FiniteSet.
Section Sec.
Hypothesis All : Type.
Hypothesis OAll : Oeset.Rcd All.
Inductive tree : Type :=
| Leaf : All -> tree
| Node : N -> list tree -> tree.
Fixpoint tree_compare (t1 t2 : tree) : comparison :=
match t1, t2 with
| Leaf a1, Leaf a2 => Oeset.compare OAll a1 a2
| Leaf _, Node _ _ => Lt
| Node _ _, Leaf _ => Gt
| Node n1 l1, Node n2 l2 =>
compareAB (Oset.compare ON) (comparelA tree_compare) (n1, l1) (n2, l2)
end.
Lemma tree_compare_unfold :
forall t1 t2, tree_compare t1 t2 =
match t1, t2 with
| Leaf a1, Leaf a2 => Oeset.compare OAll a1 a2
| Leaf _, Node _ _ => Lt
| Node _ _, Leaf _ => Gt
| Node n1 l1, Node n2 l2 =>
compareAB (Oset.compare ON) (comparelA tree_compare) (n1, l1) (n2, l2)
end.
Proof.
intros t1 t2; destruct t1; destruct t2; apply refl_equal.
Qed.
Close Scope N_scope.
Fixpoint tree_size (t : tree) : nat :=
match t with
| Leaf _ => 1
| Node _ l => 1 + list_size tree_size l
end.
Lemma tree_size_unfold :
forall t,
tree_size t =
match t with
| Leaf _ => 1
| Node _ l => 1 + list_size tree_size l
end.
Proof.
intro t; destruct t; apply refl_equal.
Qed.
Notation suitable_x n size_a a_compare x1 :=
(size_a x1 <= n ->
a_compare x1 x1 = Eq /\
forall x2, (a_compare x1 x2 = CompOpp (a_compare x2 x1)) /\
forall x3,
(a_compare x1 x2 = Eq -> a_compare x2 x3 = Eq -> a_compare x1 x3 = Eq) /\
(a_compare x1 x2 = Eq -> a_compare x2 x3 = Lt -> a_compare x1 x3 = Lt) /\
(a_compare x1 x2 = Lt -> a_compare x2 x3 = Eq -> a_compare x1 x3 = Lt) /\
(a_compare x1 x2 = Lt -> a_compare x2 x3 = Lt -> a_compare x1 x3 = Lt)).
Notation suitable n size_a a_compare :=
(forall x1, suitable_x n size_a a_compare x1).
Lemma all_suitable_tree_rec1 :
forall n, suitable n tree_size tree_compare ->
forall a, suitable_x (S n) tree_size tree_compare (Leaf a).
Proof.
intros n IHt a1 _.
split; [ | intro t2; split; [ | intro t3; split; [ | split; [ | split]]]].
- (* 1/6 *)
simpl; (trivial || discriminate || oeset_compare_tac).
- (* 1/5 *)
case t2; simpl; intros; (trivial || discriminate || oeset_compare_tac).
- (* 1/4 *)
case t2; clear t2; try discriminate.
intro a2; case t3; simpl; intros; (trivial || discriminate || oeset_compare_tac).
- (* 1/3 *)
case t2; clear t2; try discriminate.
intro a2; case t3; simpl; intros; (trivial || discriminate || oeset_compare_tac).
- (* 1/2 *)
case t2; clear t2; try discriminate;
intro a2; case t3; simpl; intros; (trivial || discriminate || oeset_compare_tac).
- (* 1/1 *)
case t2; clear t2; try discriminate;
intro a2; case t3; simpl; intros; (trivial || discriminate || oeset_compare_tac).
Qed.
Lemma all_suitable_tree_rec2 :
forall n, suitable n tree_size tree_compare ->
forall m l, suitable_x (S n) tree_size tree_compare (Node m l).
Proof.
intros n IHt m l L.
assert (Sl : forall t, List.In t l -> tree_size t <= n).
{
intros t Ht; apply le_trans with (list_size tree_size l).
- apply in_list_size; apply Ht.
- apply le_S_n; apply L.
}
assert (IH := fun t (h : List.In t l) => IHt t (Sl t h)).
split; [ | intro t2; split; [ | intro t3; split; [ | split; [ | split]]]].
- (* 1/6 *)
rewrite tree_compare_unfold; compareAB_tac.
apply comparelA_eq_refl.
intros t Ht; apply (proj1 (IH t Ht)).
- (* 1/5 *)
destruct t2 as [a2 | m2 l2]; [simpl; apply refl_equal | ].
rewrite 2 tree_compare_unfold; compareAB_tac.
+ oset_compare_tac.
+ comparelA_tac.
apply (proj1 (proj2 (IH _ H) _)).
- (* 1/4 *)
destruct t2 as [a1 | m2 l2]; [intro H1; discriminate H1 | ].
destruct t3 as [a3 | m3 l3]; [intros H1 H2; discriminate H2 | ].
rewrite 3 tree_compare_unfold; compareAB_tac.
+ oset_compare_tac.
+ comparelA_tac.
apply (proj1 (proj2 (proj2 (IH _ H) _) _)).
- (* 1/3 *)
destruct t2 as [a2 | m2 l2]; [intro H1; discriminate H1 | ].
destruct t3 as [a3 | m3 l3]; [intros H1 H2; discriminate H2 | ].
rewrite 3 tree_compare_unfold; compareAB_tac; (oset_compare_tac || comparelA_tac).
+ apply (proj1 (proj2 (proj2 (IH _ H) _) _)).
+ apply (proj1 (proj2 (proj2 (proj2 (IH _ H) _) _))).
- (* 1/2 *)
destruct t2 as [a2 | m2 l2]; [intro H1; discriminate H1 | ].
destruct t3 as [a3 | m3 l3]; [intros H1 H2; discriminate H2 | ].
rewrite 3 tree_compare_unfold; compareAB_tac; (oset_compare_tac || comparelA_tac).
+ apply (proj1 (proj2 (proj2 (IH _ H) _) _)).
+ apply (proj1 (proj2 (proj2 (proj2 (proj2 (IH _ H) _) _)))).
- (* 1/1 *)
destruct t2 as [a2 | m2 l2]; [intro H1; discriminate H1 | ].
destruct t3 as [a3 | m3 l3]; [intros H1 H2; discriminate H2 | ].
rewrite 3 tree_compare_unfold; compareAB_tac; (oset_compare_tac || comparelA_tac).
+ apply (proj1 (proj2 (proj2 (IH _ H) _) _)).
+ apply (proj1 (proj2 (proj2 (proj2 (IH _ H) _) _))).
+ apply (proj1 (proj2 (proj2 (proj2 (proj2 (IH _ H) _) _)))).
+ apply (proj2 (proj2 (proj2 (proj2 (proj2 (IH _ H) _) _)))).
Qed.
Lemma all_suitable_tree :
forall x1,
tree_compare x1 x1 = Eq /\
forall x2, (tree_compare x1 x2 = CompOpp (tree_compare x2 x1)) /\
forall x3,
(tree_compare x1 x2 = Eq -> tree_compare x2 x3 = Eq -> tree_compare x1 x3 = Eq) /\
(tree_compare x1 x2 = Eq -> tree_compare x2 x3 = Lt -> tree_compare x1 x3 = Lt) /\
(tree_compare x1 x2 = Lt -> tree_compare x2 x3 = Eq -> tree_compare x1 x3 = Lt) /\
(tree_compare x1 x2 = Lt -> tree_compare x2 x3 = Lt -> tree_compare x1 x3 = Lt).
Proof.
intro x1.
set (n := tree_size x1).
assert (Sx : tree_size x1 <= n).
apply le_n.
clearbody n.
revert x1 Sx; induction n as [ | n].
intros x1 Sx; destruct x1; simpl in Sx; inversion Sx.
intro x1; case x1.
apply all_suitable_tree_rec1; assumption.
apply all_suitable_tree_rec2; assumption.
Qed.
Lemma tree_compare_lt_gt :
forall x1 x2, tree_compare x1 x2 = CompOpp (tree_compare x2 x1).
Proof.
intros x1 x2.
destruct (all_suitable_tree x1) as [_ H]; apply (proj1 (H x2)).
Qed.
Lemma tree_compare_eq_refl :
forall x1, tree_compare x1 x1 = Eq.
Proof.
intros x1.
destruct (all_suitable_tree x1) as [H _]; apply H.
Qed.
Lemma tree_compare_size_eq :
forall t1 t2, tree_compare t1 t2 = Eq -> tree_size t1 = tree_size t2.
Proof.
intro t1; set (n := tree_size t1).
assert (Hn := le_n n); unfold n at 1 in Hn.
unfold n; clearbody n.
revert t1 Hn; induction n as [ | n];
intros [a1 | f1 l1] Hn [a2 | f2 l2] Ht; simpl; simpl in Hn;
try (trivial || discriminate Ht).
- inversion Hn.
- subst; apply f_equal.
rewrite tree_compare_unfold in Ht; unfold compareAB in Ht.
case_eq (Oset.compare ON f1 f2);
intro Hl; rewrite Hl in Ht; try discriminate Ht.
generalize (le_S_n _ _ Hn); clear Hn; intro Hn.
clear Hl.
assert (IH : forall t1 : tree, List.In t1 l1 ->
forall t2 : tree,
tree_compare t1 t2 = Eq -> tree_size t1 = tree_size t2).
{
intros t1 Ht1 t2; apply IHn.
clear Ht.
refine (le_trans _ _ _ _ Hn).
apply in_list_size; assumption.
}
clear IHn.
revert l2 Ht; induction l1 as [ | t1 l1]; intros [ | t2 l2] Ht.
* apply refl_equal.
* discriminate Ht.
* discriminate Ht.
* simpl in Ht; simpl.
case_eq (tree_compare t1 t2);
intro Kt; rewrite Kt in Ht; try discriminate Ht.
apply f_equal2; [apply (IH t1 (or_introl _ (refl_equal _)) t2 Kt) | ].
{
apply IHl1.
- refine (le_trans _ _ _ _ Hn).
simpl; apply le_plus_r.
- do 3 intro; apply IH; right; assumption.
- assumption.
}
Qed.
Lemma tree_rec3 :
forall (P : tree -> Type),
(forall a, P (Leaf a)) ->
(forall m l, (forall t, In t l -> P t) -> P (Node m l)) -> forall t, P t.
Proof.
intros P IH1 IH2 t.
set (n := tree_size t).
assert (Hn := le_n n).
unfold n at 1 in Hn; clearbody n.
revert t Hn; induction n as [ | n].
- intros t Hn; destruct t; simpl in Hn; (assert (H : False); [inversion Hn | contradiction H]).
- intros t Hn; destruct t as [a | m l]; [apply IH1 | ].
apply IH2; intros t Ht; apply IHn.
simpl in Hn.
refine (le_trans _ _ _ _ (le_S_n _ _ Hn)).
apply in_list_size; assumption.
Qed.
End Sec.
Section Equality.
Hypothesis All : Type.
Hypothesis OAll : Oset.Rcd All.
Definition OTree : Oset.Rcd (tree All).
set (AST := all_suitable_tree (oeset_of_oset OAll)).
split with (tree_compare (oeset_of_oset OAll)).
- intros x1; pattern x1; apply tree_rec3; clear x1.
+ intros a1 [a2 | m2 l2]; simpl; [ | discriminate].
oset_compare_tac.
+ intros m1 l1 IH1 [a1 | m2 l2]; [simpl; discriminate | ].
rewrite tree_compare_unfold.
unfold compareAB.
generalize (Oset.eq_bool_ok ON m1 m2).
case (Oset.compare ON m1 m2).
* intros H1; subst m2.
{
case_eq (comparelA (tree_compare (oeset_of_oset OAll)) l1 l2); intro H2.
- apply f_equal.
revert l2 H2; induction l1 as [ | a1 l1]; intros [ | a2 l2] H2;
try (trivial || discriminate H2).
simpl in H2.
case_eq (tree_compare (oeset_of_oset OAll) a1 a2);
intro Ha; rewrite Ha in H2; try discriminate H2.
apply f_equal2.
+ assert (IHa1 := IH1 a1 (or_introl _ (refl_equal _)) a2).
rewrite Ha in IHa1; apply IHa1.
+ apply IHl1; [ | assumption].
do 2 intro; apply IH1; right; assumption.
- intro H; injection H; clear H; intro; subst l2.
induction l1 as [ | a1 l1]; [discriminate H2 | ].
simpl in H2.
assert (IHa1 := IH1 a1 (or_introl _ (refl_equal _)) a1).
case_eq (tree_compare (oeset_of_oset OAll) a1 a1); intro Ha1; rewrite Ha1 in IHa1, H2.
+ refine (IHl1 _ H2).
do 2 intro; apply IH1; right; assumption.
+ apply False_rec; apply IHa1; apply refl_equal.
+ apply False_rec; apply IHa1; apply refl_equal.
- intro H; injection H; clear H; intro; subst l2.
induction l1 as [ | a1 l1]; [discriminate H2 | ].
simpl in H2.
assert (IHa1 := IH1 a1 (or_introl _ (refl_equal _)) a1).
case_eq (tree_compare (oeset_of_oset OAll) a1 a1); intro Ha1; rewrite Ha1 in IHa1, H2.
+ refine (IHl1 _ H2).
do 2 intro; apply IH1; right; assumption.
+ apply False_rec; apply IHa1; apply refl_equal.
+ apply False_rec; apply IHa1; apply refl_equal.
}
* intros H1 H2; injection H2; clear H2; do 2 intro; subst; apply H1; apply refl_equal.
* intros H1 H2; injection H2; clear H2; do 2 intro; subst; apply H1; apply refl_equal.
- intros x1 x2 x3.
destruct (AST x1) as [_ H]; apply (proj2 (proj2 (proj2 (proj2 (H x2) x3)))).
- intros x1 x2.
destruct (AST x1) as [_ H]; apply (proj1 (H x2)).
Defined.
End Equality.
Section Equivalence.
Hypothesis All : Type.
Hypothesis OEAll : Oeset.Rcd All.
Definition OETree : Oeset.Rcd (tree All).
set (AST := all_suitable_tree OEAll).
split with (tree_compare OEAll).
- intros x1 x2 x3; destruct (AST x1) as [_ H].
apply (proj1 ((proj2 (H x2)) x3)).
- intros x1 x2 x3; destruct (AST x1) as [_ H].
apply (proj1 (proj2 ((proj2 (H x2)) x3))).
- intros x1 x2 x3; destruct (AST x1) as [_ H].
apply (proj1 (proj2 (proj2 ((proj2 (H x2)) x3)))).
- intros x1 x2 x3; destruct (AST x1) as [_ H].
apply (proj2 (proj2 (proj2 ((proj2 (H x2)) x3)))).
- intros x1 x2.
destruct (AST x1) as [_ H]; apply (proj1 (H x2)).
Defined.
End Equivalence.
|
MODULE mdl_planets
! ---------------------------------------------------------------------------
! Purpose:
! Module used in the modified version of the JPL source code for the
! DE (Development Ephemeris) data processing:
! ---------------------------------------------------------------------------
! Variables:
! TTL_glb,CNAM__glb,SS_glb,NCON_glb,AU_glb,EMRAT_glb, IPT_glb,NUMDE_glb,
! LPT_glb,RPT_glb,TPT_glb
! CVAL_glb, DB_glb
! ----------------------------------------------------------------------
! Allocatable arrays: CVAL_2, DB_array
! Related subroutine: asc2eph.f90 (reading DE data format)
! ---------------------------------------------------------------------------
! Dr. Thomas D. Papanikolaou, Geoscience Australia October 2015
! ---------------------------------------------------------------------------
USE mdl_precision
IMPLICIT NONE
SAVE
! ---------------------------------------------------------------------------
CHARACTER (LEN=50) :: TTL_2(14,3)
CHARACTER (LEN=50) :: CNAM_2(1000)
REAL (KIND = prec_q) :: SS_2(3)
REAL (KIND = prec_q) :: AU_2, EMRAT_2
INTEGER (KIND = prec_int2) :: NCON_2, NUMDE_2
INTEGER (KIND = prec_int2) :: IPT_2(3,12)
INTEGER (KIND = prec_int2) :: LPT_2(3), RPT_2(3), TPT_2(3)
! ---------------------------------------------------------------------------
! Gravity Constants of Sun, Moon and Planets
REAL (KIND = prec_q) :: GMconst_au(11), GMconst(11)
! Allocatable Arrays
! ---------------------------------------------------------------------------
! Chebyshev coefficients
REAL (KIND = prec_q), DIMENSION(:), ALLOCATABLE :: CVAL_2
REAL (KIND = prec_q), DIMENSION(:,:), ALLOCATABLE :: DB_array
! ---------------------------------------------------------------------------
END
|
[STATEMENT]
lemma FL_valid_Conj [simp]:
assumes "finite (supp xset)"
shows "P \<Turnstile> Conj xset \<longleftrightarrow> (\<forall>x\<in>set_bset xset. P \<Turnstile> x)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. P \<Turnstile> Conj xset = (\<forall>x\<in>set_bset xset. P \<Turnstile> x)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
finite (supp xset)
goal (1 subgoal):
1. P \<Turnstile> Conj xset = (\<forall>x\<in>set_bset xset. P \<Turnstile> x)
[PROOF STEP]
by (simp add: FL_valid_def Conj_def map_bset.rep_eq)
|
/-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Mario Carneiro, Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.fin2
import Mathlib.data.typevec
import Mathlib.logic.function.basic
import Mathlib.tactic.basic
import Mathlib.PostPort
universes u_1 u_2 l u v
namespace Mathlib
/-!
Functors between the category of tuples of types, and the category Type
Features:
`mvfunctor n` : the type class of multivariate functors
`f <$$> x` : notation for map
-/
/-- multivariate functors, i.e. functor between the category of type vectors
and the category of Type -/
class mvfunctor {n : ℕ} (F : typevec n → Type u_2)
where
map : {α β : typevec n} → typevec.arrow α β → F α → F β
namespace mvfunctor
/-- predicate lifting over multivariate functors -/
def liftp {n : ℕ} {F : typevec n → Type v} [mvfunctor F] {α : typevec n} (p : (i : fin2 n) → α i → Prop) (x : F α) :=
∃ (u : F fun (i : fin2 n) => Subtype (p i)), map (fun (i : fin2 n) => subtype.val) u = x
/-- relational lifting over multivariate functors -/
def liftr {n : ℕ} {F : typevec n → Type v} [mvfunctor F] {α : typevec n} (r : {i : fin2 n} → α i → α i → Prop) (x : F α) (y : F α) :=
∃ (u : F fun (i : fin2 n) => Subtype fun (p : α i × α i) => r (prod.fst p) (prod.snd p)),
map (fun (i : fin2 n) (t : Subtype fun (p : α i × α i) => r (prod.fst p) (prod.snd p)) => prod.fst (subtype.val t))
u =
x ∧
map (fun (i : fin2 n) (t : Subtype fun (p : α i × α i) => r (prod.fst p) (prod.snd p)) => prod.snd (subtype.val t))
u =
y
/-- given `x : F α` and a projection `i` of type vector `α`, `supp x i` is the set
of `α.i` contained in `x` -/
def supp {n : ℕ} {F : typevec n → Type v} [mvfunctor F] {α : typevec n} (x : F α) (i : fin2 n) : set (α i) :=
set_of fun (y : α i) => ∀ {p : (i : fin2 n) → α i → Prop}, liftp p x → p i y
theorem of_mem_supp {n : ℕ} {F : typevec n → Type v} [mvfunctor F] {α : typevec n} {x : F α} {p : {i : fin2 n} → α i → Prop} (h : liftp p x) (i : fin2 n) (y : α i) (H : y ∈ supp x i) : p y :=
hy h
end mvfunctor
/-- laws for `mvfunctor` -/
class is_lawful_mvfunctor {n : ℕ} (F : typevec n → Type u_2) [mvfunctor F]
where
id_map : ∀ {α : typevec n} (x : F α), mvfunctor.map typevec.id x = x
comp_map : ∀ {α β γ : typevec n} (g : typevec.arrow α β) (h : typevec.arrow β γ) (x : F α),
mvfunctor.map (typevec.comp h g) x = mvfunctor.map h (mvfunctor.map g x)
namespace mvfunctor
/-- adapt `mvfunctor.liftp` to accept predicates as arrows -/
def liftp' {n : ℕ} {α : typevec n} {F : typevec n → Type v} [mvfunctor F] (p : typevec.arrow α (typevec.repeat n Prop)) : F α → Prop :=
liftp fun (i : fin2 n) (x : α i) => typevec.of_repeat (p i x)
/-- adapt `mvfunctor.liftp` to accept relations as arrows -/
def liftr' {n : ℕ} {α : typevec n} {F : typevec n → Type v} [mvfunctor F] (r : typevec.arrow (typevec.prod α α) (typevec.repeat n Prop)) : F α → F α → Prop :=
liftr fun (i : fin2 n) (x y : α i) => typevec.of_repeat (r i (typevec.prod.mk i x y))
@[simp] theorem id_map {n : ℕ} {α : typevec n} {F : typevec n → Type v} [mvfunctor F] [is_lawful_mvfunctor F] (x : F α) : map typevec.id x = x :=
is_lawful_mvfunctor.id_map x
@[simp] theorem id_map' {n : ℕ} {α : typevec n} {F : typevec n → Type v} [mvfunctor F] [is_lawful_mvfunctor F] (x : F α) : map (fun (i : fin2 n) (a : α i) => a) x = x :=
id_map x
theorem map_map {n : ℕ} {α : typevec n} {β : typevec n} {γ : typevec n} {F : typevec n → Type v} [mvfunctor F] [is_lawful_mvfunctor F] (g : typevec.arrow α β) (h : typevec.arrow β γ) (x : F α) : map h (map g x) = map (typevec.comp h g) x :=
Eq.symm (comp_map g h x)
theorem exists_iff_exists_of_mono {n : ℕ} {α : typevec n} {β : typevec n} (F : typevec n → Type v) [mvfunctor F] [is_lawful_mvfunctor F] {p : F α → Prop} {q : F β → Prop} (f : typevec.arrow α β) (g : typevec.arrow β α) (h₀ : typevec.comp f g = typevec.id) (h₁ : ∀ (u : F α), p u ↔ q (map f u)) : (∃ (u : F α), p u) ↔ ∃ (u : F β), q u := sorry
theorem liftp_def {n : ℕ} {α : typevec n} {F : typevec n → Type v} [mvfunctor F] (p : typevec.arrow α (typevec.repeat n Prop)) [is_lawful_mvfunctor F] (x : F α) : liftp' p x ↔ ∃ (u : F (typevec.subtype_ p)), map (typevec.subtype_val p) u = x := sorry
theorem liftr_def {n : ℕ} {α : typevec n} {F : typevec n → Type v} [mvfunctor F] (r : typevec.arrow (typevec.prod α α) (typevec.repeat n Prop)) [is_lawful_mvfunctor F] (x : F α) (y : F α) : liftr' r x y ↔
∃ (u : F (typevec.subtype_ r)),
map (typevec.comp typevec.prod.fst (typevec.subtype_val r)) u = x ∧
map (typevec.comp typevec.prod.snd (typevec.subtype_val r)) u = y := sorry
end mvfunctor
namespace mvfunctor
theorem liftp_last_pred_iff {n : ℕ} {F : typevec (n + 1) → Type u_1} [mvfunctor F] [is_lawful_mvfunctor F] {α : typevec n} {β : Type u} (p : β → Prop) (x : F (α ::: β)) : liftp' (typevec.pred_last' α p) x ↔ liftp (typevec.pred_last α p) x := sorry
theorem liftr_last_rel_iff {n : ℕ} {F : typevec (n + 1) → Type u_1} [mvfunctor F] [is_lawful_mvfunctor F] {α : typevec n} {β : Type u} (rr : β → β → Prop) (x : F (α ::: β)) (y : F (α ::: β)) : liftr' (typevec.rel_last' α rr) x y ↔ liftr (typevec.rel_last α rr) x y := sorry
|
module Cam.Platform
import Cam.FFI
public export
%inline
platformName : () -> Boxed String
platformName () = believe_me . unsafePerformIO $ fcall1 "platform_name" (believe_me ())
public export
%inline
platformSystem : () -> Boxed String
platformSystem () = believe_me . unsafePerformIO $ fcall1 "platform_system" (believe_me ())
|
using FunctionZeros
using BenchmarkTools
import SpecialFunctions
@btime besselj_zero(3,10)
@btime besselj_zero(3,10)
const z = besselj_zero(3,10)
zer = SpecialFunctions.besselj(3,z)
|
module Compiler.Erlang.Codegen.ErlExprToAbstractFormat.Serialise
import Compiler.Erlang.Name
import Compiler.Erlang.IR.AbstractFormat
import Compiler.Erlang.Codegen.ErlExprToAbstractFormat.Internal
%default total
defaultEndianness : BitEndianness
defaultEndianness = ABBig
genSerialiseDecodeResultSuccess : Line -> Expr -> Expr
genSerialiseDecodeResultSuccess l value =
genDataCtorExpr l (constructorName (NS serialiseCoreNS (UN (Basic "Success")))) [value]
genSerialiseDecodeResultFail : Line -> String -> Expr
genSerialiseDecodeResultFail l err =
genDataCtorExpr l (constructorName (NS serialiseCoreNS (UN (Basic "Fail")))) [genStringLiteralExpr l err]
genSerialiseMkIteratorRes : Line -> Expr -> Expr -> Expr
genSerialiseMkIteratorRes l value it =
genDataCtorExpr l (constructorName (NS serialiseCoreNS (UN (Basic "MkIteratorRes")))) [value, it]
-- Similar to the following Erlang code:
-- ```
-- <<Bin/binary, Value:8/integer>>.
-- ```
setGeneric : (targetTSL : TypeSpecifierList) -> (targetSize : Int) -> Line -> (builder : Expr) -> (value : Expr) -> Expr
setGeneric targetTSL targetSize l builder value =
let binary =
AEBitstring l
[ MkBitSegment l builder ABSDefault ABBinary
, MkBitSegment l value (ABSInteger l (cast targetSize)) targetTSL
]
in binary
-- Similar to the following Erlang code:
-- ```
-- get_byte(<<Value:8/integer, NewIt/binary>>) ->
-- {{next, Value}, NewIt};
-- get_byte(It) ->
-- {fail, It}.
-- ```
getGeneric : (targetTSL : TypeSpecifierList) -> (targetSize : Int) -> Line -> (it : Expr) -> Expr
getGeneric targetTSL targetSize l it =
let successPattern = APBitstring l
[ MkBitSegment l (ABPVar l "Value") (ABSInteger l (cast targetSize)) targetTSL
, MkBitSegment l (ABPVar l "NewIt") ABSDefault ABBinary
]
successBody =
genSerialiseMkIteratorRes l (genSerialiseDecodeResultSuccess l (AEVar l "Value")) (AEVar l "NewIt") ::: []
failPattern = APVar l "It"
failBody =
genSerialiseMkIteratorRes l (genSerialiseDecodeResultFail l "Failed to decode number") (AEVar l "It") ::: []
funExpr = AEFun l 1
(MkFunClause l
[successPattern]
[]
successBody :::
[ MkFunClause l
[failPattern]
[]
failBody
]
)
in AEFunCall l funExpr [it]
export
setUnsignedInt : (size : Int) -> Line -> (builder : Expr) -> (value : Expr) -> Expr
setUnsignedInt = setGeneric (ABInteger {endianness=defaultEndianness})
export
getUnsignedInt : (size : Int) -> Line -> (it : Expr) -> Expr
getUnsignedInt = getGeneric (ABInteger {endianness=defaultEndianness})
export
setSignedInt : (size : Int) -> Line -> (builder : Expr) -> (value : Expr) -> Expr
setSignedInt = setGeneric (ABInteger {endianness=defaultEndianness})
export
getSignedInt : (size : Int) -> Line -> (it : Expr) -> Expr
getSignedInt = getGeneric (ABInteger {endianness=defaultEndianness})
export
setDouble : Line -> (builder : Expr) -> (value : Expr) -> Expr
setDouble = setGeneric (ABFloat {endianness=defaultEndianness}) 64
export
getDouble : Line -> (it : Expr) -> Expr
getDouble = getGeneric (ABFloat {endianness=defaultEndianness}) 64
-- Similar to the following Erlang code:
-- ```
-- set_binary(Bin, Value) ->
-- Size = erlang:byte_size(Value),
-- <<Bin/binary, Size:32/integer, Value/binary>>.
-- ```
export
setBinary : Line -> (builder : Expr) -> (value : Expr) -> Expr
setBinary l builder value =
let binary =
AEBitstring l
[ MkBitSegment l (AEVar l "Bin") ABSDefault ABBinary
, MkBitSegment l (AEVar l "Size") (ABSInteger l 32) (ABInteger {endianness=defaultEndianness})
, MkBitSegment l (AEVar l "Value") ABSDefault ABBinary
]
body =
AEMatch l (APVar l "Size") (genFunCall l "erlang" "byte_size" [AEVar l "Value"]) :::
[ binary
]
funExpr = AEFun l 2
(singleton $ MkFunClause l
[APVar l "Bin", APVar l "Value"]
[]
body
)
in AEFunCall l funExpr [builder, value]
-- Similar to the following Erlang code:
-- ```
-- get_binary(<<Size:32/integer, Value:Size/binary, NewIt/binary>>) ->
-- {{next, Value}, NewIt};
-- get_binary(It) ->
-- {fail, It}.
-- ```
export
getBinary : Line -> (it : Expr) -> Expr
getBinary l it =
let successPattern = APBitstring l
[ MkBitSegment l (ABPVar l "Size") (ABSInteger l 32) (ABInteger {endianness=defaultEndianness})
, MkBitSegment l (ABPVar l "Value") (ABSVar l "Size") ABBinary
, MkBitSegment l (ABPVar l "NewIt") ABSDefault ABBinary
]
successBody =
genSerialiseMkIteratorRes l (genSerialiseDecodeResultSuccess l (AEVar l "Value")) (AEVar l "NewIt") ::: []
failPattern = APVar l "It"
failBody =
genSerialiseMkIteratorRes l (genSerialiseDecodeResultFail l "Failed to decode binary") (AEVar l "It") ::: []
funExpr = AEFun l 1
(MkFunClause l
[successPattern]
[]
successBody :::
[ MkFunClause l
[failPattern]
[]
failBody
]
)
in AEFunCall l funExpr [it]
|
{-# LANGUAGE NamedFieldPuns #-}
module School.Unit.Affine
( affine ) where
import Numeric.LinearAlgebra ((<>), R, add, tr')
import School.Unit.Unit (Unit(..))
import School.Unit.UnitActivation (UnitActivation(..))
import School.Unit.UnitParams (UnitParams(..))
import School.Unit.UnitGradient (UnitGradient(..))
import School.Utils.LinearAlgebra (mapRows, sumRows)
affine :: Unit Double
affine = Unit
{ apply = affineApply
, deriv = affineDeriv
}
affineApply :: UnitParams R
-> UnitActivation R
-> UnitActivation R
affineApply AffineParams { affineBias, affineWeights }
(BatchActivation inMatrix) =
BatchActivation $ mapRows (add affineBias) (inMatrix <> tr' affineWeights)
affineApply _ (ApplyFail msg) = ApplyFail msg
affineApply _ _ = ApplyFail "Failure when applying affine unit"
failure :: String
-> ( UnitGradient R
, UnitParams R
)
failure msg = (GradientFail msg, EmptyParams)
affineDeriv :: UnitParams R
-> UnitGradient R
-> UnitActivation R
-> ( UnitGradient R
, UnitParams R
)
affineDeriv AffineParams { affineWeights }
(BatchGradient inGrad)
(BatchActivation input) =
(outGrad, paramDerivs) where
outGrad = BatchGradient $ inGrad <> affineWeights
bias = sumRows inGrad
weights = tr' inGrad <> input
paramDerivs = AffineParams { affineBias = bias
, affineWeights = weights
}
affineDeriv _ (GradientFail msg) _ = failure msg
affineDeriv _ _ (ApplyFail msg) = failure msg
affineDeriv _ _ _ = failure "Failure when differentiating affine unit"
|
/**
* Orthanc - A Lightweight, RESTful DICOM Store
* Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
* Department, University Hospital of Liege, Belgium
* Copyright (C) 2017-2020 Osimis S.A., Belgium
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
#include "../Common/OrthancPluginCppWrapper.h"
#include <json/reader.h>
#include <json/value.h>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#if HAS_ORTHANC_EXCEPTION == 1
# error The macro HAS_ORTHANC_EXCEPTION must be set to 0 to compile this plugin
#endif
static std::map<std::string, std::string> extensions_;
static std::map<std::string, std::string> folders_;
static const char* INDEX_URI = "/app/plugin-serve-folders.html";
static bool allowCache_ = false;
static bool generateETag_ = true;
static void SetHttpHeaders(OrthancPluginRestOutput* output)
{
if (!allowCache_)
{
// http://stackoverflow.com/a/2068407/881731
OrthancPluginContext* context = OrthancPlugins::GetGlobalContext();
OrthancPluginSetHttpHeader(context, output, "Cache-Control", "no-cache, no-store, must-revalidate");
OrthancPluginSetHttpHeader(context, output, "Pragma", "no-cache");
OrthancPluginSetHttpHeader(context, output, "Expires", "0");
}
}
static void RegisterDefaultExtensions()
{
extensions_["css"] = "text/css";
extensions_["gif"] = "image/gif";
extensions_["html"] = "text/html";
extensions_["jpeg"] = "image/jpeg";
extensions_["jpg"] = "image/jpeg";
extensions_["js"] = "application/javascript";
extensions_["json"] = "application/json";
extensions_["nexe"] = "application/x-nacl";
extensions_["nmf"] = "application/json";
extensions_["pexe"] = "application/x-pnacl";
extensions_["png"] = "image/png";
extensions_["svg"] = "image/svg+xml";
extensions_["wasm"] = "application/wasm";
extensions_["woff"] = "application/x-font-woff";
extensions_["xml"] = "application/xml";
extensions_["pdf"] = "application/pdf";
extensions_["woff2"] = "font/woff2";
}
static std::string GetMimeType(const std::string& path)
{
size_t dot = path.find_last_of('.');
std::string extension = (dot == std::string::npos) ? "" : path.substr(dot + 1);
std::transform(extension.begin(), extension.end(), extension.begin(), tolower);
std::map<std::string, std::string>::const_iterator found = extensions_.find(extension);
if (found != extensions_.end() &&
!found->second.empty())
{
return found->second;
}
else
{
OrthancPlugins::LogWarning("ServeFolders: Unknown MIME type for extension \"" + extension + "\"");
return "application/octet-stream";
}
}
static bool LookupFolder(std::string& folder,
OrthancPluginRestOutput* output,
const OrthancPluginHttpRequest* request)
{
const std::string uri = request->groups[0];
std::map<std::string, std::string>::const_iterator found = folders_.find(uri);
if (found == folders_.end())
{
OrthancPlugins::LogError("Unknown URI in plugin server-folders: " + uri);
OrthancPluginSendHttpStatusCode(OrthancPlugins::GetGlobalContext(), output, 404);
return false;
}
else
{
folder = found->second;
return true;
}
}
static void Answer(OrthancPluginRestOutput* output,
const char* content,
size_t size,
const std::string& mime)
{
if (generateETag_)
{
OrthancPlugins::OrthancString md5;
md5.Assign(OrthancPluginComputeMd5(OrthancPlugins::GetGlobalContext(), content, size));
std::string etag = "\"" + std::string(md5.GetContent()) + "\"";
OrthancPluginSetHttpHeader(OrthancPlugins::GetGlobalContext(), output, "ETag", etag.c_str());
}
SetHttpHeaders(output);
OrthancPluginAnswerBuffer(OrthancPlugins::GetGlobalContext(), output, content, size, mime.c_str());
}
void ServeFolder(OrthancPluginRestOutput* output,
const char* url,
const OrthancPluginHttpRequest* request)
{
namespace fs = boost::filesystem;
if (request->method != OrthancPluginHttpMethod_Get)
{
OrthancPluginSendMethodNotAllowed(OrthancPlugins::GetGlobalContext(), output, "GET");
return;
}
std::string folder;
if (LookupFolder(folder, output, request))
{
const fs::path item(request->groups[1]);
const fs::path parent((fs::path(folder) / item).parent_path());
if (item.filename().string() == "index.html" &&
fs::is_directory(parent) &&
!fs::is_regular_file(fs::path(folder) / item))
{
// On-the-fly generation of an "index.html"
std::string s;
s += "<html>\n";
s += " <body>\n";
s += " <ul>\n";
fs::directory_iterator end;
for (fs::directory_iterator it(parent) ; it != end; ++it)
{
if (fs::is_directory(it->status()))
{
std::string f = it->path().filename().string();
s += " <li><a href=\"" + f + "/index.html\">" + f + "/</a></li>\n";
}
}
for (fs::directory_iterator it(parent) ; it != end; ++it)
{
fs::file_type type = it->status().type();
if (type == fs::regular_file ||
type == fs::reparse_file) // cf. BitBucket issue #11
{
std::string f = it->path().filename().string();
s += " <li><a href=\"" + f + "\">" + f + "</a></li>\n";
}
}
s += " </ul>\n";
s += " </body>\n";
s += "</html>\n";
Answer(output, s.c_str(), s.size(), "text/html");
}
else
{
std::string path = folder + "/" + item.string();
std::string mime = GetMimeType(path);
OrthancPlugins::MemoryBuffer content;
try
{
content.ReadFile(path);
}
catch (...)
{
ORTHANC_PLUGINS_THROW_EXCEPTION(InexistentFile);
}
boost::posix_time::ptime lastModification =
boost::posix_time::from_time_t(fs::last_write_time(path));
std::string t = boost::posix_time::to_iso_string(lastModification);
OrthancPluginSetHttpHeader(OrthancPlugins::GetGlobalContext(),
output, "Last-Modified", t.c_str());
Answer(output, content.GetData(), content.GetSize(), mime);
}
}
}
void ListServedFolders(OrthancPluginRestOutput* output,
const char* url,
const OrthancPluginHttpRequest* request)
{
if (request->method != OrthancPluginHttpMethod_Get)
{
OrthancPluginSendMethodNotAllowed(OrthancPlugins::GetGlobalContext(), output, "GET");
return;
}
std::string s = "<html><body><h1>Additional folders served by Orthanc</h1>\n";
if (folders_.empty())
{
s += "<p>Empty section <tt>ServeFolders</tt> in your configuration file: No additional folder is served.</p>\n";
}
else
{
s += "<ul>\n";
for (std::map<std::string, std::string>::const_iterator
it = folders_.begin(); it != folders_.end(); ++it)
{
// The URI is relative to INDEX_URI ("/app/plugin-serve-folders.html")
s += "<li><a href=\"../" + it->first + "/index.html\">" + it->first + "</li>\n";
}
s += "</ul>\n";
}
s += "</body></html>\n";
Answer(output, s.c_str(), s.size(), "text/html");
}
static void ConfigureFolders(const Json::Value& folders)
{
if (folders.type() != Json::objectValue)
{
OrthancPlugins::LogError("The list of folders to be served is badly formatted (must be a JSON object)");
ORTHANC_PLUGINS_THROW_EXCEPTION(BadFileFormat);
}
Json::Value::Members members = folders.getMemberNames();
// Register the callback for each base URI
for (Json::Value::Members::const_iterator
it = members.begin(); it != members.end(); ++it)
{
if (folders[*it].type() != Json::stringValue)
{
OrthancPlugins::LogError("The folder to be served \"" + *it +
"\" must be associated with a string value (its mapped URI)");
ORTHANC_PLUGINS_THROW_EXCEPTION(BadFileFormat);
}
std::string baseUri = *it;
// Remove the heading and trailing slashes in the root URI, if any
while (!baseUri.empty() &&
*baseUri.begin() == '/')
{
baseUri = baseUri.substr(1);
}
while (!baseUri.empty() &&
*baseUri.rbegin() == '/')
{
baseUri.resize(baseUri.size() - 1);
}
if (baseUri.empty())
{
OrthancPlugins::LogError("The URI of a folder to be served cannot be empty");
ORTHANC_PLUGINS_THROW_EXCEPTION(BadFileFormat);
}
// Check whether the source folder exists and is indeed a directory
const std::string folder = folders[*it].asString();
if (!boost::filesystem::is_directory(folder))
{
OrthancPlugins::LogError("Trying to serve an inexistent folder: " + folder);
ORTHANC_PLUGINS_THROW_EXCEPTION(InexistentFile);
}
folders_[baseUri] = folder;
// Register the callback to serve the folder
{
const std::string regex = "/(" + baseUri + ")/(.*)";
OrthancPlugins::RegisterRestCallback<ServeFolder>(regex.c_str(), true);
}
}
}
static void ConfigureExtensions(const Json::Value& extensions)
{
if (extensions.type() != Json::objectValue)
{
OrthancPlugins::LogError("The list of extensions is badly formatted (must be a JSON object)");
ORTHANC_PLUGINS_THROW_EXCEPTION(BadFileFormat);
}
Json::Value::Members members = extensions.getMemberNames();
for (Json::Value::Members::const_iterator
it = members.begin(); it != members.end(); ++it)
{
if (extensions[*it].type() != Json::stringValue)
{
OrthancPlugins::LogError("The file extension \"" + *it +
"\" must be associated with a string value (its MIME type)");
ORTHANC_PLUGINS_THROW_EXCEPTION(BadFileFormat);
}
const std::string& mime = extensions[*it].asString();
std::string name = *it;
if (!name.empty() &&
name[0] == '.')
{
name = name.substr(1); // Remove the leading dot "."
}
extensions_[name] = mime;
if (mime.empty())
{
OrthancPlugins::LogWarning("ServeFolders: Removing MIME type for file extension \"." +
name + "\"");
}
else
{
OrthancPlugins::LogWarning("ServeFolders: Associating file extension \"." + name +
"\" with MIME type \"" + mime + "\"");
}
}
}
static void ReadConfiguration()
{
OrthancPlugins::OrthancConfiguration configuration;
{
OrthancPlugins::OrthancConfiguration globalConfiguration;
globalConfiguration.GetSection(configuration, "ServeFolders");
}
if (!configuration.IsSection("Folders"))
{
// This is a basic configuration
ConfigureFolders(configuration.GetJson());
}
else
{
// This is an advanced configuration
ConfigureFolders(configuration.GetJson()["Folders"]);
bool tmp;
if (configuration.LookupBooleanValue(tmp, "AllowCache"))
{
allowCache_ = tmp;
OrthancPlugins::LogWarning("ServeFolders: Requesting the HTTP client to " +
std::string(tmp ? "enable" : "disable") +
" its caching mechanism");
}
if (configuration.LookupBooleanValue(tmp, "GenerateETag"))
{
generateETag_ = tmp;
OrthancPlugins::LogWarning("ServeFolders: The computation of an ETag for the "
"served resources is " +
std::string(tmp ? "enabled" : "disabled"));
}
OrthancPlugins::OrthancConfiguration extensions;
configuration.GetSection(extensions, "Extensions");
ConfigureExtensions(extensions.GetJson());
}
if (folders_.empty())
{
OrthancPlugins::LogWarning("ServeFolders: Empty configuration file: "
"No additional folder will be served!");
}
}
extern "C"
{
ORTHANC_PLUGINS_API int32_t OrthancPluginInitialize(OrthancPluginContext* context)
{
OrthancPlugins::SetGlobalContext(context);
/* Check the version of the Orthanc core */
if (OrthancPluginCheckVersion(context) == 0)
{
OrthancPlugins::ReportMinimalOrthancVersion(ORTHANC_PLUGINS_MINIMAL_MAJOR_NUMBER,
ORTHANC_PLUGINS_MINIMAL_MINOR_NUMBER,
ORTHANC_PLUGINS_MINIMAL_REVISION_NUMBER);
return -1;
}
RegisterDefaultExtensions();
OrthancPluginSetDescription(context, "Serve additional folders with the HTTP server of Orthanc.");
OrthancPluginSetRootUri(context, INDEX_URI);
OrthancPlugins::RegisterRestCallback<ListServedFolders>(INDEX_URI, true);
try
{
ReadConfiguration();
}
catch (OrthancPlugins::PluginException& e)
{
OrthancPlugins::LogError("Error while initializing the ServeFolders plugin: " +
std::string(e.What(context)));
}
return 0;
}
ORTHANC_PLUGINS_API void OrthancPluginFinalize()
{
}
ORTHANC_PLUGINS_API const char* OrthancPluginGetName()
{
return "serve-folders";
}
ORTHANC_PLUGINS_API const char* OrthancPluginGetVersion()
{
return SERVE_FOLDERS_VERSION;
}
}
|
section {*composition\_of\_fixed\_point\_iterators*}
theory
composition_of_fixed_point_iterators
imports
operations_on_discrete_event_systems
begin
lemma unused_Characteristic_Fixed_Point_Iterator_F_spec_cont1: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator ((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Star_Controllable_Subset SigmaUC (des_langUM P))) IsDES
(predicate_AND (predicate_AND IsDES (DES_controllability SigmaUC P)) (predicate_AND IsDES (DES_specification_satisfied S))) (predicate_AND IsDES (DES_specification_satisfied S))"
apply(rule Characteristic_Composition_of_Fixed_Point_Iterators)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Star_Controllable_Subset)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Specification_Satisfaction)
apply(force)
apply(rename_tac Q)(*strict*)
apply(simp add: DES_controllability_def)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_spec_cont1_bf: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator (((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Star_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES)
IsDES
(predicate_AND (predicate_AND IsDES DES_nonblockingness) ((predicate_AND (predicate_AND IsDES (DES_controllability SigmaUC P)) (predicate_AND IsDES (DES_specification_satisfied S)))))
(predicate_AND IsDES (DES_specification_satisfied S))"
apply(rule Characteristic_Composition_of_Fixed_Point_Iterators)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Nonblockingness_DES)
apply(rule unused_Characteristic_Fixed_Point_Iterator_F_spec_cont1)
apply(force)
apply(force)
apply(rename_tac Q)(*strict*)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_spec_cont1_bf_Enforce_Valid_DES: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator (((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Star_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES\<circ>Enforce_Valid_DES) UNIVmap
(predicate_AND IsDES (predicate_AND (predicate_AND IsDES DES_nonblockingness) ((predicate_AND (predicate_AND IsDES (DES_controllability SigmaUC P)) (predicate_AND IsDES (DES_specification_satisfied S))))))
(predicate_AND IsDES (DES_specification_satisfied S))"
apply(rule Characteristic_Composition_of_Fixed_Point_Iterators)
prefer 2
apply(rule unused_Characteristic_Fixed_Point_Iterator_F_spec_cont1_bf)
apply(force)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Valid_DES)
apply(rename_tac Q)(*strict*)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_IteratorX_F_spec_cont1_bf_Enforce_Valid_DES: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_IteratorX (((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Star_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES\<circ>Enforce_Valid_DES)
(predicate_AND IsDES (predicate_AND (predicate_AND IsDES DES_nonblockingness) ((predicate_AND (predicate_AND IsDES (DES_controllability SigmaUC P)) (predicate_AND IsDES (DES_specification_satisfied S))))))"
apply(rule_tac ssubst)
apply(rule Characteristic_Fixed_Point_IteratorX_vs_Characteristic_Fixed_Point_Iterator)
apply(rule Characteristic_Fixed_Point_Iterator_weakening)
apply(rule unused_Characteristic_Fixed_Point_Iterator_F_spec_cont1_bf_Enforce_Valid_DES)
apply(force)
apply(force)
done
corollary unused_decomposition_sound_and_least_restrictive: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> F = (((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Star_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES\<circ>Enforce_Valid_DES)
\<Longrightarrow> gfp (\<lambda>X. F (inf X (F Y))) = gfp (\<lambda>X. F (inf X Y))"
apply(rule gfp_invariant)
apply(rule_tac
t="F"
and s="(((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Star_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES\<circ>Enforce_Valid_DES)"
in ssubst)
apply(force)
apply(rule unused_Characteristic_Fixed_Point_IteratorX_F_spec_cont1_bf_Enforce_Valid_DES)
apply(force)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_spec2_cont: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator ((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Controllable_Subset SigmaUC (des_langUM P))) IsDES
(predicate_AND (predicate_AND IsDES (DES_controllability SigmaUC P)) (predicate_AND IsDES (DES_specification_satisfied S)))
(predicate_AND IsDES (DES_specification_satisfied S))"
apply(rule Characteristic_Composition_of_Fixed_Point_Iterators)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Controllable_Subset)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Specification_Satisfaction)
apply(force)
apply(rename_tac Q)(*strict*)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_spec2_cont_bf: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator (((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES) IsDES
(predicate_AND (predicate_AND IsDES DES_nonblockingness) (predicate_AND (predicate_AND IsDES (DES_controllability SigmaUC P)) (predicate_AND IsDES (DES_specification_satisfied S))))
(predicate_AND IsDES (DES_specification_satisfied S))"
apply(rule Characteristic_Composition_of_Fixed_Point_Iterators)
prefer 2
apply(rule unused_Characteristic_Fixed_Point_Iterator_F_spec2_cont)
apply(force)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Nonblockingness_DES)
apply(rename_tac Q)(*strict*)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_spec_cont2_bf_Enforce_Valid_DES: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator (((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES\<circ>Enforce_Valid_DES) UNIVmap
(predicate_AND IsDES (predicate_AND (predicate_AND IsDES DES_nonblockingness) (predicate_AND (predicate_AND IsDES (DES_controllability SigmaUC P)) (predicate_AND IsDES (DES_specification_satisfied S)))))
(predicate_AND IsDES (DES_specification_satisfied S))"
apply(rule Characteristic_Composition_of_Fixed_Point_Iterators)
prefer 2
apply(rule unused_Characteristic_Fixed_Point_Iterator_F_spec2_cont_bf)
apply(force)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Valid_DES)
apply(rename_tac Q)(*strict*)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_IteratorX_F_spec_cont2_bf_Enforce_Valid_DES: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_IteratorX (((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES\<circ>Enforce_Valid_DES) (predicate_AND IsDES (predicate_AND (predicate_AND IsDES DES_nonblockingness) (predicate_AND (predicate_AND IsDES (DES_controllability SigmaUC P)) (predicate_AND IsDES (DES_specification_satisfied S)))))"
apply(rule_tac
P="\<lambda>X. X"
in ssubst)
apply(rule Characteristic_Fixed_Point_IteratorX_vs_Characteristic_Fixed_Point_Iterator)
apply(rule Characteristic_Fixed_Point_Iterator_weakening)
apply(rule unused_Characteristic_Fixed_Point_Iterator_F_spec_cont2_bf_Enforce_Valid_DES)
apply(force)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_spec_cont4: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator ((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Marked_Controllable_Subset SigmaUC (des_langUM P))) (predicate_AND IsDES DES_nonblockingness)
(predicate_AND (predicate_AND IsDES (predicate_AND DES_nonblockingness (DES_controllability SigmaUC P))) (predicate_AND IsDES (DES_specification_satisfied S)))
(predicate_AND IsDES (DES_specification_satisfied S))"
apply(rule Characteristic_Composition_of_Fixed_Point_Iterators)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Marked_Controllable_Subset)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Specification_Satisfaction)
apply(force)
apply(rename_tac Q)(*strict*)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_spec_cont4_bf: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator (((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Marked_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES) IsDES
(predicate_AND (predicate_AND IsDES DES_nonblockingness) (predicate_AND (predicate_AND IsDES (predicate_AND DES_nonblockingness (DES_controllability SigmaUC P))) (predicate_AND IsDES (DES_specification_satisfied S))))
(predicate_AND IsDES (DES_specification_satisfied S))"
apply(rule Characteristic_Composition_of_Fixed_Point_Iterators)
prefer 2
apply(rule unused_Characteristic_Fixed_Point_Iterator_F_spec_cont4)
apply(force)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Nonblockingness_DES)
apply(rename_tac Q)(*strict*)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_spec_cont4_bf_Enforce_Valid_DES: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator
(((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Marked_Controllable_Subset SigmaUC (des_langUM P) ))\<circ>Enforce_Nonblockingness_DES\<circ>Enforce_Valid_DES)
UNIVmap
(predicate_AND IsDES (predicate_AND (predicate_AND IsDES DES_nonblockingness) (predicate_AND (predicate_AND IsDES (predicate_AND DES_nonblockingness (DES_controllability SigmaUC P))) (predicate_AND IsDES (DES_specification_satisfied S)))))
(predicate_AND IsDES (DES_specification_satisfied S))"
apply(rule Characteristic_Composition_of_Fixed_Point_Iterators)
prefer 2
apply(rule unused_Characteristic_Fixed_Point_Iterator_F_spec_cont4_bf)
apply(force)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Valid_DES)
apply(rename_tac Q)(*strict*)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_IteratorX_F_spec_cont4_bf_Enforce_Valid_DES: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_IteratorX (((Enforce_Specification_Satisfaction S)\<circ>(Enforce_Marked_Controllable_Subset SigmaUC (des_langUM P)))\<circ>Enforce_Nonblockingness_DES\<circ>Enforce_Valid_DES) (predicate_AND IsDES (predicate_AND (predicate_AND IsDES DES_nonblockingness) (predicate_AND (predicate_AND IsDES (predicate_AND DES_nonblockingness (DES_controllability SigmaUC P))) (predicate_AND IsDES (DES_specification_satisfied S)))))"
apply(rule_tac
P="\<lambda>X. X"
in ssubst)
apply(rule Characteristic_Fixed_Point_IteratorX_vs_Characteristic_Fixed_Point_Iterator)
apply(rule Characteristic_Fixed_Point_Iterator_weakening)
apply(rule unused_Characteristic_Fixed_Point_Iterator_F_spec_cont4_bf_Enforce_Valid_DES)
apply(force)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_bf_spec: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator (Enforce_Nonblockingness_DES\<circ>(\<lambda>C. Enforce_Specification_Satisfaction S C)) IsDES
(predicate_AND (predicate_AND IsDES (DES_specification_satisfied S)) (predicate_AND IsDES DES_nonblockingness)) (predicate_AND IsDES DES_nonblockingness)"
apply(rule_tac Characteristic_Composition_of_Fixed_Point_Iterators)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Specification_Satisfaction)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Nonblockingness_DES)
apply(rename_tac Q)(*strict*)
apply(force)
done
lemma unused_Characteristic_Fixed_Point_Iterator_F_bf_cont4_bf_des: "
IsDES P
\<Longrightarrow> IsDES S
\<Longrightarrow> Characteristic_Fixed_Point_Iterator (Enforce_Nonblockingness_DES\<circ>(Enforce_Marked_Controllable_Subset SigmaUC (des_langUM P))\<circ>Enforce_Nonblockingness_DES\<circ>Enforce_Valid_DES) UNIVmap
(predicate_AND IsDES (predicate_AND (predicate_AND IsDES DES_nonblockingness) (predicate_AND (predicate_AND IsDES (predicate_AND DES_nonblockingness (DES_controllability SigmaUC P))) (predicate_AND IsDES DES_nonblockingness)))) (predicate_AND IsDES DES_nonblockingness)"
apply(rule_tac
?Qinter1.0="IsDES"
and ?Qinter2.0="IsDES"
in Characteristic_Composition_of_Fixed_Point_Iterators)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Valid_DES)
prefer 2
apply(rename_tac Q)(*strict*)
apply(force)
apply(rule_tac
?Qinter1.0="(predicate_AND IsDES DES_nonblockingness)"
and ?Qinter2.0="(predicate_AND IsDES DES_nonblockingness)"
in Characteristic_Composition_of_Fixed_Point_Iterators)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Nonblockingness_DES)
prefer 2
apply(rename_tac Q)(*strict*)
apply(force)
apply(rule_tac
?Qinter1.0="IsDES"
and ?Qinter2.0="IsDES"
in Characteristic_Composition_of_Fixed_Point_Iterators)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Marked_Controllable_Subset)
apply(force)
prefer 2
apply(rename_tac Q)(*strict*)
apply(force)
apply(rule Characteristic_Fixed_Point_Iterator_Enforce_Nonblockingness_DES)
done
end
|
State Before: k : ℕ
⊢ (k + 1 + 1)! = (k + 1 + 1)‼ * (k + 1)‼ State After: no goals Tactic: rw [doubleFactorial_add_two, factorial, factorial_eq_mul_doubleFactorial _, mul_comm _ k‼,
mul_assoc]
|
C
C
SUBROUTINE MYFORTRAN(A,B, C, D, E)
CALL MAIN(A,B,C)
CALL COUNT_ARGS(A,B,C,D,E,F)
CALL MAIN(A,B,C,D)
RETURN
END
C
C
SUBROUTINE ZORG()
RETURN
END
|
module Web.Internal.ClipboardTypes
import JS
--------------------------------------------------------------------------------
-- Enums
--------------------------------------------------------------------------------
namespace PresentationStyle
public export
data PresentationStyle = Unspecified | Inline | Attachment
public export
Show PresentationStyle where
show Unspecified = "unspecified"
show Inline = "inline"
show Attachment = "attachment"
public export
Eq PresentationStyle where
(==) = (==) `on` show
public export
Ord PresentationStyle where
compare = compare `on` show
public export
read : String -> Maybe PresentationStyle
read "unspecified" = Just Unspecified
read "inline" = Just Inline
read "attachment" = Just Attachment
read _ = Nothing
public export
fromString : (s : String)
-> {auto 0 _ : IsJust (PresentationStyle.read s)}
-> PresentationStyle
fromString s = fromJust $ read s
export
ToFFI PresentationStyle String where
toFFI = show
export
FromFFI PresentationStyle String where
fromFFI = read
--------------------------------------------------------------------------------
-- Interfaces
--------------------------------------------------------------------------------
export data Clipboard : Type where [external]
export
ToFFI Clipboard Clipboard where toFFI = id
export
FromFFI Clipboard Clipboard where fromFFI = Just
export
SafeCast Clipboard where
safeCast = unsafeCastOnPrototypeName "Clipboard"
export data ClipboardEvent : Type where [external]
export
ToFFI ClipboardEvent ClipboardEvent where toFFI = id
export
FromFFI ClipboardEvent ClipboardEvent where fromFFI = Just
export
SafeCast ClipboardEvent where
safeCast = unsafeCastOnPrototypeName "ClipboardEvent"
export data ClipboardItem : Type where [external]
export
ToFFI ClipboardItem ClipboardItem where toFFI = id
export
FromFFI ClipboardItem ClipboardItem where fromFFI = Just
export
SafeCast ClipboardItem where
safeCast = unsafeCastOnPrototypeName "ClipboardItem"
--------------------------------------------------------------------------------
-- Dictionaries
--------------------------------------------------------------------------------
export data ClipboardEventInit : Type where [external]
export
ToFFI ClipboardEventInit ClipboardEventInit where toFFI = id
export
FromFFI ClipboardEventInit ClipboardEventInit where fromFFI = Just
export data ClipboardItemOptions : Type where [external]
export
ToFFI ClipboardItemOptions ClipboardItemOptions where toFFI = id
export
FromFFI ClipboardItemOptions ClipboardItemOptions where fromFFI = Just
export data ClipboardPermissionDescriptor : Type where [external]
export
ToFFI ClipboardPermissionDescriptor ClipboardPermissionDescriptor where toFFI = id
export
FromFFI ClipboardPermissionDescriptor ClipboardPermissionDescriptor where fromFFI = Just
--------------------------------------------------------------------------------
-- Callbacks
--------------------------------------------------------------------------------
export data ClipboardItemDelayedCallback : Type where [external]
export
ToFFI ClipboardItemDelayedCallback ClipboardItemDelayedCallback where toFFI = id
export
FromFFI ClipboardItemDelayedCallback ClipboardItemDelayedCallback where fromFFI = Just
|
lemma CauchyI: "(\<And>e. 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e) \<Longrightarrow> Cauchy X" for X :: "nat \<Rightarrow> 'a::real_normed_vector"
|
theory Scott_S5U imports QML_S5U
begin consts P :: "(\<mu>\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" (* Positive *)
axiomatization where
A1a: "\<lfloor>\<^bold>\<forall>\<Phi>. P(\<^sup>\<not>\<Phi>) \<^bold>\<rightarrow> \<^bold>\<not>P(\<Phi>)\<rfloor>" and
A1b: "\<lfloor>\<^bold>\<forall>\<Phi>. \<^bold>\<not>P(\<Phi>) \<^bold>\<rightarrow> P(\<^sup>\<not>\<Phi>)\<rfloor>" and
A2: "\<lfloor>\<^bold>\<forall>\<Phi> \<Psi>. P(\<Phi>) \<^bold>\<and> \<^bold>\<box>(\<^bold>\<forall>x. \<Phi>(x) \<^bold>\<rightarrow> \<Psi>(x)) \<^bold>\<rightarrow> P(\<Psi>)\<rfloor>"
definition G where "G(x) = (\<^bold>\<forall>\<Phi>. P(\<Phi>) \<^bold>\<rightarrow> \<Phi>(x))" (* Definition of God *)
axiomatization where
A3: "\<lfloor>P(G)\<rfloor>" and
A4: "\<lfloor>\<^bold>\<forall>\<Phi>. P(\<Phi>) \<^bold>\<rightarrow> \<^bold>\<box>(P(\<Phi>))\<rfloor>"
definition ess (infixr "ess" 85) where
"\<Phi> ess x = \<Phi>(x) \<^bold>\<and> (\<^bold>\<forall>\<Psi>. \<Psi>(x) \<^bold>\<rightarrow> \<^bold>\<box>(\<^bold>\<forall>y. \<Phi>(y) \<^bold>\<rightarrow> \<Psi>(y)))" (* Essence *)
definition NE where "NE(x) = (\<^bold>\<forall>\<Phi>. \<Phi> ess x \<^bold>\<rightarrow> \<^bold>\<box>(\<^bold>\<exists> \<Phi>))"(* Necessary Existence *)
axiomatization where
A5: "\<lfloor>P(NE)\<rfloor>"
theorem T3: "\<lfloor>\<^bold>\<box>(\<^bold>\<exists>x. G(x))\<rfloor>" (* Necessarily, God exists: LEO-II proof in 2,5sec *)
sledgehammer [provers = remote_leo2,verbose]
by (metis (lifting, full_types)
A1a A1b A2 A3 A4 A5 G_def NE_def ess_def)
lemma True nitpick [satisfy,user_axioms] oops
(* Consistency check with Nitpick *)
lemma False sledgehammer [provers = remote_leo2,verbose] oops
(* Inconsistency check with Leo-II *)
theorem T2: "\<lfloor>\<^bold>\<forall>x. G(x) \<^bold>\<rightarrow> G ess x\<rfloor>"
sledgehammer [provers = remote_leo2]
by (metis A1b A4 G_def ess_def)
lemma MC: "\<lfloor>\<^bold>\<forall>\<Phi>. \<Phi> \<^bold>\<rightarrow> (\<^bold>\<box> \<Phi>)\<rfloor>" (* Modal Collapse *)
sledgehammer [provers = remote_satallax, timeout=600]
by (meson T2 T3 ess_def)
end
|
lemma of_real_Re [simp]: "z \<in> \<real> \<Longrightarrow> of_real (Re z) = z"
|
State Before: α : Type ?u.565531
β : Type ?u.565534
γ : Type ?u.565537
inst✝ : PseudoEMetricSpace α
a b : ℝ
h : a ≤ b
⊢ Metric.diam (Ioo a b) = b - a State After: no goals Tactic: simp [Metric.diam, ENNReal.toReal_ofReal (sub_nonneg.2 h)]
|
! ###################################################################
! Copyright (c) 2013-2022, Marc De Graef Research Group/Carnegie Mellon University
! All rights reserved.
!
! Redistribution and use in source and binary forms, with or without modification, are
! permitted provided that the following conditions are met:
!
! - Redistributions of source code must retain the above copyright notice, this list
! of conditions and the following disclaimer.
! - Redistributions in binary form must reproduce the above copyright notice, this
! list of conditions and the following disclaimer in the documentation and/or
! other materials provided with the distribution.
! - Neither the names of Marc De Graef, Carnegie Mellon University nor the names
! of its contributors may be used to endorse or promote products derived from
! this software without specific prior written permission.
!
! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
! SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
! OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
! USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
! ###################################################################
module mod_OrientationViz
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! class definition for the EMOrientationViz program
use mod_kinds
use mod_global
IMPLICIT NONE
! namelist for the EMOrientationViz program
type, public :: OrientationVizNameListType
integer(kind=irg) :: cubochoric
integer(kind=irg) :: homochoric
integer(kind=irg) :: rodrigues
integer(kind=irg) :: stereographic
integer(kind=irg) :: eulerspace
integer(kind=irg) :: reducetoRFZ
integer(kind=irg) :: nx
integer(kind=irg) :: ny
integer(kind=irg) :: nz
integer(kind=irg) :: overridepgnum
integer(kind=irg) :: MacKenzieCell
real(kind=sgl) :: rgb(3)
real(kind=sgl) :: sphrad
real(kind=sgl) :: distance
character(3) :: scalingmode
character(3) :: mrcmode
character(fnlen) :: df3file
character(fnlen) :: mrcfile
character(fnlen) :: framemrcfile
character(fnlen) :: xtalname
character(fnlen) :: povrayfile
character(fnlen) :: anglefile
end type OrientationVizNameListType
! class definition
type, public :: OrientationViz_T
private
character(fnlen) :: nmldeffile = 'EMOrientationViz.nml'
type(OrientationVizNameListType) :: nml
contains
private
procedure, pass(self) :: readNameList_
procedure, pass(self) :: getNameList_
procedure, pass(self) :: OrientationViz_
procedure, pass(self) :: get_cubochoric_
procedure, pass(self) :: get_homochoric_
procedure, pass(self) :: get_rodrigues_
procedure, pass(self) :: get_stereographic_
procedure, pass(self) :: get_eulerspace_
procedure, pass(self) :: get_reducetoRFZ_
procedure, pass(self) :: get_nx_
procedure, pass(self) :: get_ny_
procedure, pass(self) :: get_nz_
procedure, pass(self) :: get_overridepgnum_
procedure, pass(self) :: get_MacKenzieCell_
procedure, pass(self) :: get_rgb_
procedure, pass(self) :: get_sphrad_
procedure, pass(self) :: get_distance_
procedure, pass(self) :: get_scalingmode_
procedure, pass(self) :: get_mrcmode_
procedure, pass(self) :: get_df3file_
procedure, pass(self) :: get_mrcfile_
procedure, pass(self) :: get_framemrcfile_
procedure, pass(self) :: get_xtalname_
procedure, pass(self) :: get_povrayfile_
procedure, pass(self) :: get_anglefile_
procedure, pass(self) :: set_cubochoric_
procedure, pass(self) :: set_homochoric_
procedure, pass(self) :: set_rodrigues_
procedure, pass(self) :: set_stereographic_
procedure, pass(self) :: set_eulerspace_
procedure, pass(self) :: set_reducetoRFZ_
procedure, pass(self) :: set_nx_
procedure, pass(self) :: set_ny_
procedure, pass(self) :: set_nz_
procedure, pass(self) :: set_overridepgnum_
procedure, pass(self) :: set_MacKenzieCell_
procedure, pass(self) :: set_rgb_
procedure, pass(self) :: set_sphrad_
procedure, pass(self) :: set_distance_
procedure, pass(self) :: set_scalingmode_
procedure, pass(self) :: set_mrcmode_
procedure, pass(self) :: set_df3file_
procedure, pass(self) :: set_mrcfile_
procedure, pass(self) :: set_framemrcfile_
procedure, pass(self) :: set_xtalname_
procedure, pass(self) :: set_povrayfile_
procedure, pass(self) :: set_anglefile_
generic, public :: getNameList => getNameList_
generic, public :: readNameList => readNameList_
generic, public :: OrientationViz => OrientationViz_
generic, public :: get_cubochoric => get_cubochoric_
generic, public :: get_homochoric => get_homochoric_
generic, public :: get_rodrigues => get_rodrigues_
generic, public :: get_stereographic => get_stereographic_
generic, public :: get_eulerspace => get_eulerspace_
generic, public :: get_reducetoRFZ => get_reducetoRFZ_
generic, public :: get_nx => get_nx_
generic, public :: get_ny => get_ny_
generic, public :: get_nz => get_nz_
generic, public :: get_overridepgnum => get_overridepgnum_
generic, public :: get_MacKenzieCell => get_MacKenzieCell_
generic, public :: get_rgb => get_rgb_
generic, public :: get_sphrad => get_sphrad_
generic, public :: get_distance => get_distance_
generic, public :: get_scalingmode => get_scalingmode_
generic, public :: get_mrcmode => get_mrcmode_
generic, public :: get_df3file => get_df3file_
generic, public :: get_mrcfile => get_mrcfile_
generic, public :: get_framemrcfile => get_framemrcfile_
generic, public :: get_xtalname => get_xtalname_
generic, public :: get_povrayfile => get_povrayfile_
generic, public :: get_anglefile => get_anglefile_
generic, public :: set_cubochoric => set_cubochoric_
generic, public :: set_homochoric => set_homochoric_
generic, public :: set_rodrigues => set_rodrigues_
generic, public :: set_stereographic => set_stereographic_
generic, public :: set_eulerspace => set_eulerspace_
generic, public :: set_reducetoRFZ => set_reducetoRFZ_
generic, public :: set_nx => set_nx_
generic, public :: set_ny => set_ny_
generic, public :: set_nz => set_nz_
generic, public :: set_overridepgnum => set_overridepgnum_
generic, public :: set_MacKenzieCell => set_MacKenzieCell_
generic, public :: set_rgb => set_rgb_
generic, public :: set_sphrad => set_sphrad_
generic, public :: set_distance => set_distance_
generic, public :: set_scalingmode => set_scalingmode_
generic, public :: set_mrcmode => set_mrcmode_
generic, public :: set_df3file => set_df3file_
generic, public :: set_mrcfile => set_mrcfile_
generic, public :: set_framemrcfile => set_framemrcfile_
generic, public :: set_xtalname => set_xtalname_
generic, public :: set_povrayfile => set_povrayfile_
generic, public :: set_anglefile => set_anglefile_
end type OrientationViz_T
! the constructor routine for this class
interface OrientationViz_T
module procedure OrientationViz_constructor
end interface OrientationViz_T
contains
!--------------------------------------------------------------------------
type(OrientationViz_T) function OrientationViz_constructor( nmlfile ) result(OrientationViz)
!DEC$ ATTRIBUTES DLLEXPORT :: OrientationViz_constructor
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! constructor for the OrientationViz_T Class; reads the name list
IMPLICIT NONE
character(fnlen), OPTIONAL :: nmlfile
call OrientationViz%readNameList(nmlfile)
end function OrientationViz_constructor
!--------------------------------------------------------------------------
subroutine OrientationViz_destructor(self)
!DEC$ ATTRIBUTES DLLEXPORT :: OrientationViz_destructor
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! destructor for the OrientationViz_T Class
IMPLICIT NONE
type(OrientationViz_T), INTENT(INOUT) :: self
call reportDestructor('OrientationViz_T')
end subroutine OrientationViz_destructor
!--------------------------------------------------------------------------
subroutine readNameList_(self, nmlfile, initonly)
!DEC$ ATTRIBUTES DLLEXPORT :: readNameList_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! read the namelist from an nml file for the OrientationViz_T Class
use mod_io
use mod_EMsoft
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen),INTENT(IN) :: nmlfile
!! full path to namelist file
logical,OPTIONAL,INTENT(IN) :: initonly
!! fill in the default values only; do not read the file
type(EMsoft_T) :: EMsoft
type(IO_T) :: Message
logical :: skipread = .FALSE.
integer(kind=irg) :: cubochoric
integer(kind=irg) :: homochoric
integer(kind=irg) :: rodrigues
integer(kind=irg) :: stereographic
integer(kind=irg) :: eulerspace
integer(kind=irg) :: reducetoRFZ
integer(kind=irg) :: nx
integer(kind=irg) :: ny
integer(kind=irg) :: nz
integer(kind=irg) :: overridepgnum
integer(kind=irg) :: MacKenzieCell
real(kind=sgl) :: rgb(3)
real(kind=sgl) :: sphrad
real(kind=sgl) :: distance
character(3) :: scalingmode
character(3) :: mrcmode
character(fnlen) :: df3file
character(fnlen) :: mrcfile
character(fnlen) :: framemrcfile
character(fnlen) :: xtalname
character(fnlen) :: povrayfile
character(fnlen) :: anglefile
! define the IO namelist to facilitate passing variables to the program.
namelist / EMOrientationViz / cubochoric, homochoric, rodrigues, stereographic, eulerspace, &
xtalname, povrayfile, anglefile, reducetoRFZ, rgb, sphrad, df3file, &
mrcfile, framemrcfile, mrcmode, &
nx, ny, nz, distance, scalingmode, overridepgnum, MacKenzieCell
! initialize
cubochoric = 0
homochoric = 0
rodrigues = 0
stereographic = 0
eulerspace = 0
reducetoRFZ = 1
overridepgnum = 0
MacKenzieCell = 0
rgb = (/ 0.0, 0.0, 1.0 /)
sphrad = 0.015
distance = 4.0
nx = 64
ny = 64
nz = 64
scalingmode = 'lev' ! or 'log' or 'lev' (for equi-level contours)
mrcmode = 'off' ! 'off', 'reg', 'frm'
df3file = 'undefined'
mrcfile = 'undefined'
framemrcfile = 'undefined'
xtalname = 'undefined'
povrayfile = 'undefined'
anglefile = 'undefined'
if (present(initonly)) then
if (initonly) skipread = .TRUE.
end if
if (.not.skipread) then
! read the namelist file
open(UNIT=dataunit,FILE=trim(nmlfile),DELIM='apostrophe',STATUS='old')
read(UNIT=dataunit,NML=EMOrientationViz)
close(UNIT=dataunit,STATUS='keep')
! check for required entries
if (trim(xtalname).eq.'undefined') then
call Message%printError('readNameList:',' structure file name is undefined in '//nmlfile)
end if
if (mrcmode.eq.'off') then
if (trim(povrayfile).eq.'undefined') then
call Message%printError('readNameList:',' povray file name is undefined in '//nmlfile)
end if
else
if (mrcmode.eq.'reg') then
if (trim(mrcfile).eq.'undefined') then
call Message%printError('readNameList:',' mrc file name is undefined in '//nmlfile)
end if
else
if (trim(framemrcfile).eq.'undefined') then
call Message%printError('readNameList:',' frame mrc file name is undefined in '//nmlfile)
end if
end if
end if
if (trim(anglefile).eq.'undefined') then
call Message%printError('readNameList:',' angle file name is undefined in '//nmlfile)
end if
end if
self%nml%cubochoric = cubochoric
self%nml%homochoric = homochoric
self%nml%rodrigues = rodrigues
self%nml%stereographic = stereographic
self%nml%eulerspace = eulerspace
self%nml%reducetoRFZ = reducetoRFZ
self%nml%nx = nx
self%nml%ny = ny
self%nml%nz = nz
self%nml%overridepgnum = overridepgnum
self%nml%MacKenzieCell = MacKenzieCell
self%nml%rgb = rgb
self%nml%sphrad = sphrad
self%nml%distance = distance
self%nml%scalingmode = scalingmode
self%nml%mrcmode = mrcmode
self%nml%df3file = df3file
self%nml%mrcfile = mrcfile
self%nml%framemrcfile = framemrcfile
self%nml%xtalname = trim(xtalname)
self%nml%povrayfile = trim(povrayfile)
self%nml%anglefile = trim(anglefile)
end subroutine readNameList_
!--------------------------------------------------------------------------
function getNameList_(self) result(nml)
!DEC$ ATTRIBUTES DLLEXPORT :: getNameList_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! pass the namelist for the OrientationViz_T Class to the calling program
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
type(OrientationVizNameListType) :: nml
nml = self%nml
end function getNameList_
!--------------------------------------------------------------------------
function get_cubochoric_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_cubochoric_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get cubochoric from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%cubochoric
end function get_cubochoric_
!--------------------------------------------------------------------------
subroutine set_cubochoric_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_cubochoric_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set cubochoric in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%cubochoric = inp
end subroutine set_cubochoric_
!--------------------------------------------------------------------------
function get_homochoric_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_homochoric_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get homochoric from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%homochoric
end function get_homochoric_
!--------------------------------------------------------------------------
subroutine set_homochoric_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_homochoric_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set homochoric in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%homochoric = inp
end subroutine set_homochoric_
!--------------------------------------------------------------------------
function get_rodrigues_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_rodrigues_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get rodrigues from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%rodrigues
end function get_rodrigues_
!--------------------------------------------------------------------------
subroutine set_rodrigues_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_rodrigues_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set rodrigues in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%rodrigues = inp
end subroutine set_rodrigues_
!--------------------------------------------------------------------------
function get_stereographic_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_stereographic_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get stereographic from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%stereographic
end function get_stereographic_
!--------------------------------------------------------------------------
subroutine set_stereographic_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_stereographic_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set stereographic in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%stereographic = inp
end subroutine set_stereographic_
!--------------------------------------------------------------------------
function get_eulerspace_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_eulerspace_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get eulerspace from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%eulerspace
end function get_eulerspace_
!--------------------------------------------------------------------------
subroutine set_eulerspace_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_eulerspace_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set eulerspace in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%eulerspace = inp
end subroutine set_eulerspace_
!--------------------------------------------------------------------------
function get_reducetoRFZ_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_reducetoRFZ_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get reducetoRFZ from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%reducetoRFZ
end function get_reducetoRFZ_
!--------------------------------------------------------------------------
subroutine set_reducetoRFZ_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_reducetoRFZ_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set reducetoRFZ in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%reducetoRFZ = inp
end subroutine set_reducetoRFZ_
!--------------------------------------------------------------------------
function get_nx_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_nx_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get nx from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%nx
end function get_nx_
!--------------------------------------------------------------------------
subroutine set_nx_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_nx_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set nx in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%nx = inp
end subroutine set_nx_
!--------------------------------------------------------------------------
function get_ny_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_ny_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get ny from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%ny
end function get_ny_
!--------------------------------------------------------------------------
subroutine set_ny_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_ny_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set ny in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%ny = inp
end subroutine set_ny_
!--------------------------------------------------------------------------
function get_nz_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_nz_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get nz from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%nz
end function get_nz_
!--------------------------------------------------------------------------
subroutine set_nz_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_nz_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set nz in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%nz = inp
end subroutine set_nz_
!--------------------------------------------------------------------------
function get_overridepgnum_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_overridepgnum_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get overridepgnum from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%overridepgnum
end function get_overridepgnum_
!--------------------------------------------------------------------------
subroutine set_overridepgnum_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_overridepgnum_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set overridepgnum in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%overridepgnum = inp
end subroutine set_overridepgnum_
!--------------------------------------------------------------------------
function get_MacKenzieCell_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_MacKenzieCell_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get MacKenzieCell from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg) :: out
out = self%nml%MacKenzieCell
end function get_MacKenzieCell_
!--------------------------------------------------------------------------
subroutine set_MacKenzieCell_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_MacKenzieCell_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set MacKenzieCell in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
integer(kind=irg), INTENT(IN) :: inp
self%nml%MacKenzieCell = inp
end subroutine set_MacKenzieCell_
!--------------------------------------------------------------------------
function get_rgb_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_rgb_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get rgb from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
real(kind=sgl) :: out(3)
out = self%nml%rgb
end function get_rgb_
!--------------------------------------------------------------------------
subroutine set_rgb_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_rgb_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set rgb(3) in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
real(kind=sgl), INTENT(IN) :: inp(3)
self%nml%rgb = inp
end subroutine set_rgb_
!--------------------------------------------------------------------------
function get_sphrad_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_sphrad_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get sphrad from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
real(kind=sgl) :: out
out = self%nml%sphrad
end function get_sphrad_
!--------------------------------------------------------------------------
subroutine set_sphrad_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_sphrad_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set sphrad in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
real(kind=sgl), INTENT(IN) :: inp
self%nml%sphrad = inp
end subroutine set_sphrad_
!--------------------------------------------------------------------------
function get_distance_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_distance_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get distance from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
real(kind=sgl) :: out
out = self%nml%distance
end function get_distance_
!--------------------------------------------------------------------------
subroutine set_distance_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_distance_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set distance in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
real(kind=sgl), INTENT(IN) :: inp
self%nml%distance = inp
end subroutine set_distance_
!--------------------------------------------------------------------------
function get_scalingmode_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_scalingmode_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get scalingmode from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(3) :: out
out = self%nml%scalingmode
end function get_scalingmode_
!--------------------------------------------------------------------------
subroutine set_scalingmode_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_scalingmode_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set scalingmode in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(3), INTENT(IN) :: inp
self%nml%scalingmode = inp
end subroutine set_scalingmode_
!--------------------------------------------------------------------------
function get_mrcmode_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_mrcmode_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get mrcmode from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(3) :: out
out = self%nml%mrcmode
end function get_mrcmode_
!--------------------------------------------------------------------------
subroutine set_mrcmode_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_mrcmode_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set mrcmode in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(3), INTENT(IN) :: inp
self%nml%mrcmode = inp
end subroutine set_mrcmode_
!--------------------------------------------------------------------------
function get_df3file_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_df3file_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get df3file from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen) :: out
out = self%nml%df3file
end function get_df3file_
!--------------------------------------------------------------------------
subroutine set_df3file_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_df3file_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set df3file in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen), INTENT(IN) :: inp
self%nml%df3file = inp
end subroutine set_df3file_
!--------------------------------------------------------------------------
function get_mrcfile_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_mrcfile_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get mrcfile from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen) :: out
out = self%nml%mrcfile
end function get_mrcfile_
!--------------------------------------------------------------------------
subroutine set_mrcfile_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_mrcfile_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set mrcfile in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen), INTENT(IN) :: inp
self%nml%mrcfile = inp
end subroutine set_mrcfile_
!--------------------------------------------------------------------------
function get_framemrcfile_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_framemrcfile_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get framemrcfile from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen) :: out
out = self%nml%framemrcfile
end function get_framemrcfile_
!--------------------------------------------------------------------------
subroutine set_framemrcfile_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_framemrcfile_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set framemrcfile in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen), INTENT(IN) :: inp
self%nml%framemrcfile = inp
end subroutine set_framemrcfile_
!--------------------------------------------------------------------------
function get_xtalname_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_xtalname_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get xtalname from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen) :: out
out = self%nml%xtalname
end function get_xtalname_
!--------------------------------------------------------------------------
subroutine set_xtalname_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_xtalname_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set xtalname in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen), INTENT(IN) :: inp
self%nml%xtalname = inp
end subroutine set_xtalname_
!--------------------------------------------------------------------------
function get_povrayfile_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_povrayfile_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get povrayfile from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen) :: out
out = self%nml%povrayfile
end function get_povrayfile_
!--------------------------------------------------------------------------
subroutine set_povrayfile_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_povrayfile_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set povrayfile in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen), INTENT(IN) :: inp
self%nml%povrayfile = inp
end subroutine set_povrayfile_
!--------------------------------------------------------------------------
function get_anglefile_(self) result(out)
!DEC$ ATTRIBUTES DLLEXPORT :: get_anglefile_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! get anglefile from the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen) :: out
out = self%nml%anglefile
end function get_anglefile_
!--------------------------------------------------------------------------
subroutine set_anglefile_(self,inp)
!DEC$ ATTRIBUTES DLLEXPORT :: set_anglefile_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! set anglefile in the OrientationViz_T class
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
character(fnlen), INTENT(IN) :: inp
self%nml%anglefile = inp
end subroutine set_anglefile_
!--------------------------------------------------------------------------
subroutine OrientationViz_(self, EMsoft, progname, progdesc)
!DEC$ ATTRIBUTES DLLEXPORT :: OrientationViz_
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! perform the computations
use mod_EMsoft
use mod_io
use mod_crystallography
use mod_symmetry
use mod_rotations
use mod_Lambert
use mod_quaternions
use mod_povray
use mod_so3
use mod_dirstats
use mod_math
use mod_so3
use mod_HDFsupport, only: openFortranHDFInterface, closeFortranHDFInterface
IMPLICIT NONE
class(OrientationViz_T), INTENT(INOUT) :: self
type(EMsoft_T), INTENT(INOUT) :: EMsoft
character(fnlen), INTENT(INOUT) :: progname
character(fnlen), INTENT(INOUT) :: progdesc
type(IO_T) :: Message
type(PoVRay_T) :: PoVcu, PoVho, PoVro, PoVst, PoVeu
type(DirStat_T) :: dict
type(so3_T) :: SO
type(SpaceGroup_T) :: SG
type(cell_T) :: cell
type(QuaternionArray_T) :: Pm, dummy
type(r_T) :: ro
type(h_T) :: ho
type(s_T) :: st
type(e_T) :: eu
type(c_T) :: cu
real(kind=dbl) :: rod(4), sh(3), xyz(3), xyz4(4), XY(2), euFZ(3), rstep, ac, dd, qur(4)
integer(kind=irg) :: i,j,k, icnt, imax, nt, npx, ngroups, groups(10), dataunit4=25, dataunit5=40, &
ierr, ig, ix, iy, iz, num, ixyz(3), pgnum, io_int(2), nums(3)
real(kind=dbl) :: delta, eps = 1.0D-2
character(fnlen) :: locationline, fname, dataname, outname, lightline, skyline, rgbstring, locationlineeu, &
colorstring, df3name, mrcname
character(11) :: p0
character(21) :: p1, p2
character(9) :: px, py, pz, pd
character(7) :: pd2
character(3) :: gid(10)
character(2) :: angleformat
integer(kind=irg) :: FZtype, FZorder, numpoints, seed, istat, FZtype_override, FZorder_override
logical :: levelset, skipthis, drawMK
real(kind=dbl),allocatable :: samples(:,:)
real(kind=dbl) :: muhat(4), kappahat
! rendering volumes
real(kind=sgl),allocatable :: rovol(:,:,:), spvol(:,:,:), euvol(:,:,:), cuvol(:,:,:), hovol(:,:,:)
real(kind=sgl) :: maxRFZdis(5), rodx, rody, rodz, eudx, eudy, eudz, spdx, spdy, spdz, cudx, cudy, cudz, &
hodx, hody, hodz, scalefactors(3,5), acubo, ahomo, grid3(3,3,3), eyepos(3)
type(FZpointd),pointer :: FZtmp
associate( enl=>self%nml )
call setRotationPrecision('Double')
! turn off the automatic range check whenever a rotation class is instantiated;
! in the povray module, we get a lot of out-of-range warnings for the euler mode
! so we turn those off since they are not errors.
rotationRangeCheck = .FALSE.
! init a few parameters and arrays
grid3 = trilinear_splat( (/ 0.0, 0.0, 0.0/), (/ 0.0, 0.0, 0.0/), init=.TRUE.)
! define some parameters
sh = (/ sngl(cPi), sngl(cPi/2.D0), sngl(cPi) /) ! offset parameter for primary Euler cell
! get the space group symmetry
call openFortranHDFInterface()
call cell%getCrystalData(enl%xtalname, SG, EMsoft)
call closeFortranHDFInterface()
pgnum = SG%getPGnumber()
! set the FZtype and FZorder parameters in the SO class
if (enl%overridepgnum.ne.0) then
pgnum = enl%overridepgnum
end if
SO = so3_T( pgnum, zerolist='FZ')
call SO%getFZtypeandorder(FZtype, FZorder)
! Regular or MacKenzie FZ ?
if (enl%MacKenzieCell.eq.1) then
call SO%setMK(.TRUE.)
call SO%setMFZtypeandorder(pgnum)
call SO%getMFZtypeandorder(FZtype, FZorder)
end if
! define some FZ dimensional parameters (used for volume rendering)
maxRFZdis = (/ 5.0, 2.5, 1.0, 1.0/3.0, sqrt(2.0)-1.0 /)
scalefactors(1:3,1) = (/ 1.0, 1.0, 1.0 /)
if (FZorder.ne.0) then
scalefactors(1:3,2) = (/ 2.0, 2.0, 2.0*tan(sngl(cPi)*0.5/float(FZorder)) /)
scalefactors(1:3,3) = (/ 2.0, 2.0, 2.0*tan(sngl(cPi)*0.5/float(FZorder)) /)
end if
scalefactors(1:3,4) = (/ 2.0/3.0, 2.0/3.0, 2.0/3.0 /)
scalefactors(1:3,5) = (/ (sqrt(2.0)-1.0)/0.5, (sqrt(2.0)-1.0)/0.5, (sqrt(2.0)-1.0)/0.5 /)
! get the symmetry operator quaternions for the point group
call dummy%QSym_Init(pgnum, Pm)
! make sure that the outname does not have an extension (no . in the string)
outname = trim(enl%povrayfile)
if ((index(trim(outname),'.').ne.0).and.(index(trim(outname),'.').gt.20)) then
call Message%printError('EMOrientationViz','the output filename may not contain any periods')
end if
outname = EMsoft%generateFilePath('EMdatapathname', enl%povrayfile)
! generate the locationline parameters for PoVRay rendering
dd = enl%distance
eyepos = (/ 0.387, 0.825, 0.412 /)
eyepos = eyepos/sqrt( sum( eyepos*eyepos))
write (px,"(F9.3)") eyepos(1)
write (py,"(F9.3)") eyepos(2)
write (pz,"(F9.3)") eyepos(3)
write (pd,"(F9.3)") dd
p0 = "location < "
p1 = "*cos(clock*0.0174533)"
p2 = "*sin(clock*0.0174533)"
locationline = p0//px//p1//"-"//py//p2//","//px//p2//"+"//py//p1//","//pz//">*"//pd
locationlineeu = p0//'5.0, 1.0, 0.0>*'//pd
! PoVRay/DF3 initializations (this opens the file, sets the camera and light source
! and allocates the rendering volume)
!===========
! cubochoric
!===========
if (enl%cubochoric.ne.0) then
if (enl%mrcmode.eq.'off') then
call initFiles(EMsoft, enl, PoVcu, SO, 'cu', outname, dataunit, locationline )
end if
! create the rendering volume
allocate(cuvol(-enl%nx:enl%nx,-enl%ny:enl%ny,-enl%nz:enl%nz),stat=istat)
cuvol = 0.0
! generate the x/y/z scaling factors
! these should be set so that the render box has the outer dimensions of the cubochoric cube,
acubo = sngl(cPi)**0.6666666 * 0.5
cudx = float(enl%nx) / acubo
cudy = float(enl%nx) / acubo
cudz = float(enl%nz) / acubo
end if
!===========
! homochoric
!===========
if (enl%homochoric.ne.0) then
if (enl%mrcmode.eq.'off') then
call initFiles(EMsoft, enl, PoVcu, SO, 'ho', outname, dataunit2, locationline )
end if
! create the rendering volume
allocate(hovol(-enl%nx:enl%nx,-enl%ny:enl%ny,-enl%nz:enl%nz),stat=istat)
hovol = 0.0
! generate the x/y/z scaling factors
! these should be set so that the render box has the outer dimensions of the cubochoric cube,
ahomo = (3.0*sngl(cPi)/4.0)**0.3333333
hodx = float(enl%nx) / ahomo
hody = float(enl%nx) / ahomo
hodz = float(enl%nz) / ahomo
end if
!===========
! Rodrigues
!===========
if (enl%rodrigues.ne.0) then
if (enl%mrcmode.eq.'off') then
call initFiles(EMsoft, enl, PoVro, SO, 'ro', outname, dataunit3, locationline )
end if
! create the rendering volume
allocate(rovol(-enl%nx:enl%nx,-enl%ny:enl%ny,-enl%nz:enl%nz),stat=istat)
rovol = 0.0
! generate the x/y/z scaling factors
! these should be set so that the render box has the outer dimensions of the RFZ,
! with the exception of the cyclic groups for which we pick some value that is
! reasonable. For the dihedral groups the box should have an edge length of 2,
! for tetrahedral 1/3, and for octahedral sqrt(2)-1.
rodx = float(enl%nx)
rody = float(enl%nx)
rodz = float(enl%nx)
end if
!==============
! stereographic
!==============
if (enl%stereographic.ne.0) then
if (enl%mrcmode.eq.'off') then
call initFiles(EMsoft, enl, PoVst, SO, 'st', outname, dataunit4, locationline )
end if
! create the rendering volume
allocate(spvol(-enl%nx:enl%nx,-enl%ny:enl%ny,-enl%nz:enl%nz),stat=istat)
spvol = 0.0
! generate the x/y/z scaling factors
! these should be set so that the render box has the outer dimensions of the stereographic sphere,
! which has unit radius.
spdx = float(enl%nx)
spdy = float(enl%nx)
spdz = float(enl%nz)
end if
!==============
! stereographic
!==============
if (enl%eulerspace.ne.0) then
if (enl%mrcmode.eq.'off') then
! Euler space has a slightly different eye position so we need to redefine the locationline and skyline strings
fname = trim(outname)//'-eu.pov'
skyline = 'sky <0.0, 1.0, 0.0>'
PoVeu = PoVRay_T( EMsoft, fname, dunit=dataunit5, nmlfile=EMsoft%nmldeffile, skyline = skyline, &
locationline = locationlineeu )
call initFiles(EMsoft, enl, PoVeu, SO, 'eu', outname, dataunit5, locationlineeu )
end if
! create the rendering volume
allocate(euvol(1:2*enl%nx+1,1:2*enl%ny+1,1:2*enl%nz+1),stat=istat)
euvol = 0.0
! generate the x/y/z scaling factors
! these should be set so that the render box has the outer dimensions of the primary Euler cell
eudx = float(2*enl%nx+1) / (2.0*cPi)
eudy = float(2*enl%ny+1) / (2.0*cPi)
eudz = float(2*enl%nz+1) / (2.0*cPi)
end if
! data file of orientations, convert the orientations to the RFZ
fname = EMsoft%generateFilePath('EMdatapathname', enl%anglefile)
call SO%getOrientationsfromFile(fname)
! next, we reduce these orientations to the RFZ or MacKenzie cell
if (enl%MacKenzieCell.eq.0) then
call SO%ReducelisttoRFZ(Pm)
else
call SO%ReducelisttoMFZ(SG) ! this requires the full crystal point group
end if
FZtmp => SO%getListHead('FZ') ! point to the top of the list
numpoints = SO%getListCount('FZ')
pointloop: do ix = 1,numpoints
ro = FZtmp%rod
! are we drawing a point or splatting it into a volume ?
if ((trim(enl%df3file).eq.'undefined').and.(enl%mrcmode.eq.'off')) then
! we have the point, so now transform it to all alternative representations and draw the
! corresponding spheres
! cubochoric
if (enl%cubochoric.ne.0) then
cu = ro%rc()
xyz = sngl(cu%c_copyd())
write (dataunit,"('sphere { <',2(F14.6,','),F14.6,'>,',F6.4,' }')") xyz(1:3), enl%sphrad
end if
! homochoric
if (enl%homochoric.ne.0) then
ho = ro%rh()
xyz = sngl(ho%h_copyd())
write (dataunit2,"('sphere { <',2(F14.6,','),F14.6,'>,',F6.4,' }')") xyz(1:3), enl%sphrad
end if
! rodrigues
if (enl%rodrigues.ne.0) then
xyz4 = sngl(ro%r_copyd())
if (xyz4(4).le.1000.0) then
write (dataunit3,"('sphere { <',2(F20.6,','),F20.6,'>,',F6.4,' }')") xyz4(1:3)*xyz4(4), enl%sphrad
end if
end if
! stereographic
if (enl%stereographic.ne.0) then
st = ro%rs()
xyz = sngl(st%s_copyd())
write (dataunit4,"('sphere { <',2(F14.6,','),F14.6,'>,',F6.4,' }')") xyz(1:3), enl%sphrad
end if
! Euler box
if (enl%eulerspace.ne.0) then
eu = ro%re()
xyz = sngl(eu%e_copyd())
write (dataunit5,"('sphere { <',2(F14.6,','),F14.6,'>,',F6.4,' }')") xyz(1:3) - sh(1:3), enl%sphrad
end if
else ! we're filling up the rendering volume(s)
! cubochoric rendering volume
if (enl%cubochoric.ne.0) then
cu = ro%rc()
xyz = sngl(cu%c_copyd())
grid3 = trilinear_splat( sngl(xyz(1:3)), (/ cudx, cudy, cudz /), init=.FALSE.)
ixyz(1:3) = nint(xyz(1:3) * (/ cudx, cudy, cudz /))
if ((abs(ixyz(1)).lt.enl%nx).and.(abs(ixyz(2)).lt.enl%ny).and.(abs(ixyz(3)).lt.enl%nz) ) then
cuvol(ixyz(1)-1:ixyz(1)+1,ixyz(2)-1:ixyz(2)+1,ixyz(3)-1:ixyz(3)+1) = &
cuvol(ixyz(1)-1:ixyz(1)+1,ixyz(2)-1:ixyz(2)+1,ixyz(3)-1:ixyz(3)+1) + grid3
end if
end if
! homochoric rendering volume
if (enl%homochoric.ne.0) then
ho = ro%rh()
xyz = sngl(ho%h_copyd())
grid3 = trilinear_splat( sngl(xyz(1:3)), (/ hodx, hody, hodz /), init=.FALSE.)
ixyz(1:3) = nint(xyz(1:3) * (/ hodx, hody, hodz /))
if ((abs(ixyz(1)).lt.enl%nx).and.(abs(ixyz(2)).lt.enl%ny).and.(abs(ixyz(3)).lt.enl%nz) ) then
hovol(ixyz(1)-1:ixyz(1)+1,ixyz(2)-1:ixyz(2)+1,ixyz(3)-1:ixyz(3)+1) = &
hovol(ixyz(1)-1:ixyz(1)+1,ixyz(2)-1:ixyz(2)+1,ixyz(3)-1:ixyz(3)+1) + grid3
end if
end if
! rodrigues rendering volume
if (enl%rodrigues.ne.0) then
xyz4 = sngl(ro%r_copyd())
grid3 = trilinear_splat( sngl(xyz4(1:3)*xyz4(4)), (/ rodx, rody, rodz /), init=.FALSE.)
ixyz(1:3) = nint((xyz4(1:3)*xyz4(4)) * (/ rodx, rody, rodz /))
if ((abs(ixyz(1)).lt.enl%nx).and.(abs(ixyz(2)).lt.enl%ny).and.(abs(ixyz(3)).lt.enl%nz) ) then
rovol(ixyz(1)-1:ixyz(1)+1,ixyz(2)-1:ixyz(2)+1,ixyz(3)-1:ixyz(3)+1) = &
rovol(ixyz(1)-1:ixyz(1)+1,ixyz(2)-1:ixyz(2)+1,ixyz(3)-1:ixyz(3)+1) + grid3
end if
end if
! stereographic rendering volume
if (enl%stereographic.ne.0) then
st = ro%rs()
xyz = sngl(st%s_copyd())
grid3 = trilinear_splat( sngl(xyz), (/ spdx, spdy, spdz /), init=.FALSE.)
ixyz(1:3) = nint(xyz(1:3) * (/ spdx, spdy, spdz /))
! in the following test, we are potentially eliminating a few points that lie on
! the surface of the volume array...
if ((abs(ixyz(1)).lt.enl%nx).and.(abs(ixyz(2)).lt.enl%ny).and.(abs(ixyz(3)).lt.enl%nz) ) then
spvol(ixyz(1)-1:ixyz(1)+1,ixyz(2)-1:ixyz(2)+1,ixyz(3)-1:ixyz(3)+1) = &
spvol(ixyz(1)-1:ixyz(1)+1,ixyz(2)-1:ixyz(2)+1,ixyz(3)-1:ixyz(3)+1) + grid3
end if
end if
! Euler primary cell rendering volume [needs to be updated with trilinear splatting]
if (enl%eulerspace.ne.0) then
eu = ro%re()
xyz = sngl(eu%e_copyd())
xyz(1) = mod(xyz(1)+10.0*cPi,2.0*cPi)
xyz(2) = mod(xyz(2)+5.0*cPi,cPi)
xyz(3) = mod(xyz(3)+10.0*cPi,2.0*cPi)
ixyz(1:3) = nint(xyz(1:3) * (/ eudx, eudy * 2.0, eudz /))
if ((ixyz(1).le.2*enl%nx).and.(ixyz(2).le.2*enl%ny).and.(ixyz(3).le.2*enl%nz) ) then
euvol(ixyz(1)+1,ixyz(2)+1,ixyz(3)+1) = euvol(ixyz(1)+1,ixyz(2)+1,ixyz(3)+1) + 1.0
end if
end if
end if
FZtmp => FZtmp%next
end do pointloop
! final stage of the program so close the PoVray files
if (enl%mrcmode.eq.'off') then
if (trim(enl%df3file).eq.'undefined') then ! we're drawing spheres, so close the union and add color information
write(rgbstring,"(F8.6,',',F8.6,',',F8.6)") enl%rgb(1:3)
colorstring = 'material { texture { pigment { rgb <'//trim(rgbstring)//'> filter 0.95 }'
if (enl%cubochoric.ne.0) then
write (dataunit,"(A)") trim(colorstring)
write (dataunit,"(' finish { diffuse 0.6, 0.6 brilliance 1.0 } } } } ')")
write (dataunit,"(A)") 'background { color rgb <0.9, 0.9, 0.9> }'
call PoVcu%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-cu.pov')
end if
if (enl%homochoric.ne.0) then
write (dataunit2,"(A)") trim(colorstring)
write (dataunit2,"(' finish { diffuse 0.6, 0.6 brilliance 1.0 } } } }')")
write (dataunit2,"(A)") 'background { color rgb <0.9, 0.9, 0.9> }'
call PoVho%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-ho.pov')
end if
if (enl%rodrigues.ne.0) then
write (dataunit3,"(A)") trim(colorstring)
write (dataunit3,"('finish { diffuse 0.6, 0.6 brilliance 1.0 } } } }')")
write (dataunit3,"(A)") 'background { color rgb <0.9, 0.9, 0.9> }'
call PoVro%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-ro.pov')
end if
if (enl%stereographic.ne.0) then
write (dataunit4,"(A)") trim(colorstring)
write (dataunit4,"(' finish { diffuse 0.6, 0.6 brilliance 1.0 } } } }')")
write (dataunit4,"(A)") 'background { color rgb <0.9, 0.9, 0.9> }'
call PoVst%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-sp.pov')
end if
if (enl%eulerspace.ne.0) then
write (dataunit5,"(A)") trim(colorstring)
write (dataunit5,"(' finish { diffuse 0.6, 0.6 brilliance 1.0 } } } }')")
write (dataunit5,"(A)") 'background { color rgb <0.9, 0.9, 0.9> }'
call PoVeu%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-eu.pov')
end if
else ! we're writing the rendering volume to a DF3 file and closing the povray file
if (enl%cubochoric.ne.0) then
! output the final rendering commands
write (dataunit,"(A)") 'background { color rgb <0.2, 0.2, 0.2> }'
write (dataunit,"('object { renderbox translate <-0.5, -0.5, -0.5>')")
write (dataunit,"(' scale <',F10.6,',',F10.6,',',F10.6,' > }')") 2.0 * (/ acubo, acubo, acubo /)
! and close the file
call PoVcu%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-cu.pov')
df3name = trim(EMsoft%generateFilePath('EMdatapathname', enl%df3file))//'-cu.df3'
call PoVcu%write_DF3file(df3name, cuvol, (/ enl%nx, enl%ny, enl%nz /), enl%scalingmode)
end if
if (enl%homochoric.ne.0) then
! output the final rendering commands
write (dataunit2,"(A)") 'background { color rgb <0.2, 0.2, 0.2> }'
write (dataunit2,"('object { renderbox translate <-0.5, -0.5, -0.5>')")
write (dataunit2,"(' scale <',F10.6,',',F10.6,',',F10.6,' > }')") 2.0 * (/ ahomo, ahomo, ahomo /)
! and close the file
call PoVho%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-ho.pov')
df3name = trim(EMsoft%generateFilePath('EMdatapathname', enl%df3file))//'-ho.df3'
call PoVho%write_DF3file(df3name, hovol, (/ enl%nx, enl%ny, enl%nz /), enl%scalingmode)
end if
if (enl%rodrigues.ne.0) then
! output the final rendering commands
write (dataunit3,"(A)") 'background { color rgb <0.2, 0.2, 0.2> }'
write (dataunit3,"('object { renderbox translate <-0.5, -0.5, -0.5>')")
! if (enl%overridepgnum.eq.0) then
write (dataunit3,"(' scale <',F10.6,',',F10.6,',',F10.6,' > }')") scalefactors(1:3,FZtype+1)
! else
! write (dataunit3,"(' scale <',F10.6,',',F10.6,',',F10.6,' > }')") scalefactors(1:3,FZtype_override+1)
! end if
! and close the file
call PoVro%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-ro.pov')
df3name = trim(EMsoft%generateFilePath('EMdatapathname', enl%df3file))//'-ro.df3'
call PoVro%write_DF3file(df3name, rovol, (/ enl%nx, enl%ny, enl%nz /), enl%scalingmode)
end if
if (enl%stereographic.ne.0) then
! output the final rendering commands
write (dataunit4,"(A)") 'background { color rgb <0.2, 0.2, 0.2> }'
write (dataunit4,"('object { renderbox translate <-0.5, -0.5, -0.5>')")
write (dataunit4,"(' scale <',F10.6,',',F10.6,',',F10.6,' > }')") (/ 2.0, 2.0, 2.0 /)
! and close the file
call PoVst%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-sp.pov')
df3name = trim(EMsoft%generateFilePath('EMdatapathname', enl%df3file))//'-sp.df3'
call PoVst%write_DF3file(df3name, spvol, (/ enl%nx, enl%ny, enl%nz /), enl%scalingmode)
end if
if (enl%eulerspace.ne.0) then
! output the final rendering commands
write (dataunit5,"(A)") 'background { color rgb <0.2, 0.2, 0.2> }'
write (dataunit5,"('object { renderbox scale < 6.2831855, 3.1415927, 6.2831855 > ')")
write (dataunit5,"(' translate < -3.1415927, -1.5707964, -3.1415927 > } ')")
! and close the file
call PoVeu%closeFile()
call Message%printMessage('PoVray rendering script stored in '//trim(outname)//'-eu.pov')
df3name = trim(EMsoft%generateFilePath('EMdatapathname', enl%df3file))//'-eu.df3'
call PoVeu%write_DF3file(df3name, euvol, (/ enl%nx, enl%ny, enl%nz /), enl%scalingmode)
end if
end if
else ! we're creating an .mrc file, so we do not need any of the povray commands...
nums = (/ 2*enl%nx+1, 2*enl%ny+1, 2*enl%nz+1 /)
if (enl%cubochoric.ne.0) then
call generateMRCfile(EMsoft, enl, nums, dble(cuvol), 'cu')
end if
if (enl%homochoric.ne.0) then
call generateMRCfile(EMsoft, enl, nums, dble(hovol), 'ho')
end if
if (enl%rodrigues.ne.0) then
call generateMRCfile(EMsoft, enl, nums, dble(rovol), 'ro')
end if
if (enl%stereographic.ne.0) then
call generateMRCfile(EMsoft, enl, nums, dble(spvol), 'sp')
end if
if (enl%eulerspace.ne.0) then
call generateMRCfile(EMsoft, enl, nums, dble(euvol), 'eu')
end if
end if
end associate
end subroutine OrientationViz_
!--------------------------------------------------------------------------
subroutine initFiles(EMsoft, enl, PoV, SO, rep, outname, dunit, locationline)
!DEC$ ATTRIBUTES DLLEXPORT :: initFiles
!! author: MDG
!! version: 1.0
!! date: 03/27/20
!!
!! perform the file initializations
use mod_EMsoft
use mod_io
use mod_povray
use mod_so3
IMPLICIT NONE
type(EMsoft_T),INTENT(INOUT) :: EMsoft
type(OrientationVizNameListType),INTENT(INOUT) :: enl
type(PoVRay_T),INTENT(INOUT) :: PoV
character(2),INTENT(IN) :: rep
type(so3_T),INTENT(INOUT) :: SO
character(fnlen),INTENT(IN) :: outname
integer(kind=irg),INTENT(IN) :: dunit
character(fnlen),INTENT(IN) :: locationline
type(IO_T) :: Message
character(fnlen) :: fname, DF3name
logical :: drawMK = .FALSE.
integer(kind=irg) :: dFZ
drawMK = SO%getMK()
select case(rep)
case('cu')
dFZ = 1
case('ho')
dFZ = 2
case('st')
dFZ = 3
case('ro')
dFZ = 4
case('eu')
dFZ = 5
end select
fname = trim(outname)//'-'//rep//'.pov'
call Message%printMessage('opening '//trim(fname))
if (rep.ne.'eu') then
PoV = PoVRay_T( EMsoft, fname, dunit=dunit, nmlfile=EMsoft%nmldeffile, locationline=locationline )
end if
if (trim(enl%df3file).eq.'undefined') then
! we're just going to draw a bunch of spheres, so put them together in a PoVRay union
call PoV%drawFZ(SO, dFZ, 0.005D0)
! open the union here
write (dunit,"('union { ')")
else
! insert code to read in a 3D Density File (df3) containing the object to be rendered
df3name = trim(EMsoft%generateFilePath('EMdatapathname',enl%df3file))//'-'//rep//'.df3'
if (enl%scalingmode.eq.'lev') then
call PoV%declare_DF3file(df3name,levelset=.TRUE.)
else
call PoV%declare_DF3file(df3name)
end if
call PoV%drawFZ(SO, dFZ, 0.005D0)
end if
end subroutine initFiles
!--------------------------------------------------------------------------
subroutine generateMRCfile(EMsoft, enl, nums, volume, rep)
!DEC$ ATTRIBUTES DLLEXPORT :: generateMRCfile
use mod_EMsoft
use mod_MRC
use mod_io
IMPLICIT NONE
type(EMsoft_T),INTENT(INOUT) :: EMsoft
type(OrientationVizNameListType),INTENT(INOUT) :: enl
integer(kind=irg), INTENT(IN) :: nums(3)
real(kind=dbl),INTENT(IN) :: volume(nums(1),nums(2),nums(3))
character(2),INTENT(IN) :: rep
character(fnlen) :: mrcname
type(MRC_T) :: MRC
type(MRCstruct) :: MRCheader
type(FEIstruct) :: FEIheaders(1024)
integer(kind=irg) :: iz
real(kind=dbl) :: psum(nums(3))
type(IO_T) :: Message
mrcname = trim(EMsoft%generateFilePath('EMdatapathname', enl%mrcfile))//'-'//rep//'.mrc'
MRC = MRC_T(mrcname)
MRCheader = MRC%getMRCheader()
FEIheaders = MRC%getFEIheaders()
call setMRCvals(MRCheader, FEIheaders, nums )
call MRC%setVolumeDimensions( nums )
psum = sum(sum(volume,1),1)
do iz=1,nums(3)
FEIheaders(iz)%mean_int = psum(iz)/float(nums(1))/float(nums(2))
end do
MRCheader%amin = minval(volume)
MRCheader%amax = maxval(volume)
MRCheader%amean = sum(volume)/float(nums(1))/float(nums(2))/float(nums(3))
! and write the volume to file
call MRC%setMRCheader(MRCheader)
call MRC%setFEIheaders(FEIheaders)
call MRC%write_3Dvolume(volume,verbose=.TRUE.)
call MRC%closeFile()
call Message%printMessage(' Volume data stored in '//trim(mrcname))
end subroutine generateMRCfile
!--------------------------------------------------------------------------
subroutine setMRCvals(MRCheader, FEIheaders, nums)
!DEC$ ATTRIBUTES DLLEXPORT :: setMRCvals
use mod_MRC
IMPLICIT NONE
type(MRCstruct), INTENT(INOUT) :: MRCheader
type(FEIstruct), INTENT(INOUT) :: FEIheaders(1024)
integer(kind=irg), INTENT(IN) :: nums(3)
integer(kind=irg) :: i
MRCheader%nx = nums(1)
MRCheader%ny = nums(2)
MRCheader%nz = nums(3)
MRCheader%mode = 2 ! for floating point output
MRCheader%mx = nums(1)
MRCheader%my = nums(2)
MRCheader%mz = nums(3)
MRCheader%xlen = nums(1)
MRCheader%ylen = nums(2)
MRCheader%zlen = nums(3)
do i=1,nums(3)
FEIheaders(i)%b_tilt = 0.0
FEIheaders(i)%defocus = 0.0
FEIheaders(i)%pixelsize = 1.0e-9
FEIheaders(i)%magnification = 1000.0
FEIheaders(i)%voltage = 0.0
end do
end subroutine setMRCvals
end module mod_OrientationViz
|
/-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro
-/
import algebra.field.defs
import algebra.group_with_zero.power
import algebra.parity
/-!
# Results about powers in fields or division rings.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file exists to ensure we can define `field` with minimal imports,
so contains some lemmas about powers of elements which need imports
beyond those needed for the basic definition.
-/
variables {α : Type*}
section division_ring
variables [division_ring α] {n : ℤ}
@[simp] lemma zpow_bit1_neg (a : α) (n : ℤ) : (-a) ^ bit1 n = - a ^ bit1 n :=
by rw [zpow_bit1', zpow_bit1', neg_mul_neg, neg_mul_eq_mul_neg]
lemma odd.neg_zpow (h : odd n) (a : α) : (-a) ^ n = - a ^ n :=
by { obtain ⟨k, rfl⟩ := h.exists_bit1, exact zpow_bit1_neg _ _ }
lemma odd.neg_one_zpow (h : odd n) : (-1 : α) ^ n = -1 := by rw [h.neg_zpow, one_zpow]
end division_ring
|
"""
ESS
Elliptical slice sampling algorithm.
# Examples
```jldoctest; setup = :(Random.seed!(1))
julia> @model gdemo(x) = begin
m ~ Normal()
x ~ Normal(m, 0.5)
end
gdemo (generic function with 2 methods)
julia> sample(gdemo(1.0), ESS(), 1_000) |> mean
Mean
│ Row │ parameters │ mean │
│ │ Symbol │ Float64 │
├─────┼────────────┼──────────┤
│ 1 │ m │ 0.824853 │
```
"""
struct ESS{space} <: InferenceAlgorithm end
ESS() = ESS{()}()
ESS(space::Symbol) = ESS{(space,)}()
# always accept in the first step
function DynamicPPL.initialstep(
rng::AbstractRNG,
model::Model,
spl::Sampler{<:ESS},
vi::AbstractVarInfo;
kwargs...
)
# Sanity check
vns = _getvns(vi, spl)
length(vns) == 1 ||
error("[ESS] does only support one variable ($(length(vns)) variables specified)")
for vn in vns[1]
dist = getdist(vi, vn)
EllipticalSliceSampling.isgaussian(typeof(dist)) ||
error("[ESS] only supports Gaussian prior distributions")
end
return Transition(vi), vi
end
function AbstractMCMC.step(
rng::AbstractRNG,
model::Model,
spl::Sampler{<:ESS},
vi::AbstractVarInfo;
kwargs...
)
# obtain previous sample
f = vi[spl]
# define previous sampler state
# (do not use cache to avoid in-place sampling from prior)
oldstate = EllipticalSliceSampling.ESSState(f, getlogp(vi), nothing)
# compute next state
sample, state = AbstractMCMC.step(
rng,
EllipticalSliceSampling.ESSModel(
ESSPrior(model, spl, vi), ESSLogLikelihood(model, spl, vi),
),
EllipticalSliceSampling.ESS(),
oldstate,
)
# update sample and log-likelihood
vi[spl] = sample
setlogp!(vi, state.loglikelihood)
return Transition(vi), vi
end
# Prior distribution of considered random variable
struct ESSPrior{M<:Model,S<:Sampler{<:ESS},V<:AbstractVarInfo,T}
model::M
sampler::S
varinfo::V
μ::T
function ESSPrior{M,S,V}(model::M, sampler::S, varinfo::V) where {
M<:Model,S<:Sampler{<:ESS},V<:AbstractVarInfo
}
vns = _getvns(varinfo, sampler)
μ = mapreduce(vcat, vns[1]) do vn
dist = getdist(varinfo, vn)
EllipticalSliceSampling.isgaussian(typeof(dist)) ||
error("[ESS] only supports Gaussian prior distributions")
vectorize(dist, mean(dist))
end
return new{M,S,V,typeof(μ)}(model, sampler, varinfo, μ)
end
end
function ESSPrior(model::Model, sampler::Sampler{<:ESS}, varinfo::AbstractVarInfo)
return ESSPrior{typeof(model),typeof(sampler),typeof(varinfo)}(
model, sampler, varinfo,
)
end
# Ensure that the prior is a Gaussian distribution (checked in the constructor)
EllipticalSliceSampling.isgaussian(::Type{<:ESSPrior}) = true
# Only define out-of-place sampling
function Base.rand(rng::Random.AbstractRNG, p::ESSPrior)
sampler = p.sampler
varinfo = p.varinfo
vns = _getvns(varinfo, sampler)
set_flag!(varinfo, vns[1][1], "del")
p.model(rng, varinfo, sampler)
return varinfo[sampler]
end
# Mean of prior distribution
Distributions.mean(p::ESSPrior) = p.μ
# Evaluate log-likelihood of proposals
struct ESSLogLikelihood{M<:Model,S<:Sampler{<:ESS},V<:AbstractVarInfo}
model::M
sampler::S
varinfo::V
end
function (ℓ::ESSLogLikelihood)(f)
sampler = ℓ.sampler
varinfo = ℓ.varinfo
varinfo[sampler] = f
ℓ.model(varinfo, sampler)
return getlogp(varinfo)
end
function DynamicPPL.tilde(rng, ctx::DefaultContext, sampler::Sampler{<:ESS}, right, vn::VarName, inds, vi)
if inspace(vn, sampler)
return DynamicPPL.tilde(rng, LikelihoodContext(), SampleFromPrior(), right, vn, inds, vi)
else
return DynamicPPL.tilde(rng, ctx, SampleFromPrior(), right, vn, inds, vi)
end
end
function DynamicPPL.tilde(ctx::DefaultContext, sampler::Sampler{<:ESS}, right, left, vi)
return DynamicPPL.tilde(ctx, SampleFromPrior(), right, left, vi)
end
function DynamicPPL.dot_tilde(rng, ctx::DefaultContext, sampler::Sampler{<:ESS}, right, left, vn::VarName, inds, vi)
if inspace(vn, sampler)
return DynamicPPL.dot_tilde(rng, LikelihoodContext(), SampleFromPrior(), right, left, vn, inds, vi)
else
return DynamicPPL.dot_tilde(rng, ctx, SampleFromPrior(), right, left, vn, inds, vi)
end
end
function DynamicPPL.dot_tilde(rng, ctx::DefaultContext, sampler::Sampler{<:ESS}, right, left, vi)
return DynamicPPL.dot_tilde(rng, ctx, SampleFromPrior(), right, left, vi)
end
|
[STATEMENT]
lemma shrinking:
assumes "is_zariski_open U" and "\<pp> \<in> U" and "s \<in> \<O> U" and "t \<in> \<O> U"
obtains V a f b g where "is_zariski_open V" "V \<subseteq> U" "\<pp> \<in> V" "a \<in> R" "f \<in> R" "b \<in> R" "g \<in> R"
"f \<notin> \<pp>" "g \<notin> \<pp>"
"\<And>\<qq>. \<qq> \<in> V \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f"
"\<And>\<qq>. \<qq> \<in> V \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>V a f b g. \<lbrakk>is_zariski_open V; V \<subseteq> U; \<pp> \<in> V; a \<in> R; f \<in> R; b \<in> R; g \<in> R; f \<notin> \<pp>; g \<notin> \<pp>; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (\<And>V a f b g. \<lbrakk>is_zariski_open V; V \<subseteq> U; \<pp> \<in> V; a \<in> R; f \<in> R; b \<in> R; g \<in> R; f \<notin> \<pp>; g \<notin> \<pp>; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
obtain Vs a f where "is_zariski_open Vs" "Vs \<subseteq> U" "\<pp> \<in> Vs" "a \<in> R" "f \<in> R"
"\<And>\<qq>. \<qq> \<in> Vs \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>Vs a f. \<lbrakk>is_zariski_open Vs; Vs \<subseteq> U; \<pp> \<in> Vs; a \<in> R; f \<in> R; \<And>\<qq>. \<qq> \<in> Vs \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using assms(2,3) sheaf_spec_def is_regular_def is_locally_frac_def
[PROOF STATE]
proof (prove)
using this:
\<pp> \<in> U
s \<in> \<O> U
\<O> ?U \<equiv> {s \<in> \<Pi>\<^sub>E \<pp>\<in>?U. R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>. is_regular s ?U}
is_regular ?s ?U \<equiv> \<forall>\<pp>. \<pp> \<in> ?U \<longrightarrow> (\<exists>V. is_zariski_open V \<and> V \<subseteq> ?U \<and> \<pp> \<in> V \<and> is_locally_frac ?s V)
is_locally_frac ?s ?V \<equiv> \<exists>r f. r \<in> R \<and> f \<in> R \<and> (\<forall>\<qq>\<in>?V. f \<notin> \<qq> \<and> ?s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r f)
goal (1 subgoal):
1. (\<And>Vs a f. \<lbrakk>is_zariski_open Vs; Vs \<subseteq> U; \<pp> \<in> Vs; a \<in> R; f \<in> R; \<And>\<qq>. \<qq> \<in> Vs \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
is_zariski_open Vs
Vs \<subseteq> U
\<pp> \<in> Vs
a \<in> R
f \<in> R
?\<qq>3 \<in> Vs \<Longrightarrow> f \<notin> ?\<qq>3 \<and> s ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> a f
goal (1 subgoal):
1. (\<And>V a f b g. \<lbrakk>is_zariski_open V; V \<subseteq> U; \<pp> \<in> V; a \<in> R; f \<in> R; b \<in> R; g \<in> R; f \<notin> \<pp>; g \<notin> \<pp>; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
obtain Vt b g where "is_zariski_open Vt" "Vt \<subseteq> U" "\<pp> \<in> Vt" "b \<in> R" "g \<in> R"
"\<And>\<qq>. \<qq> \<in> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>Vt b g. \<lbrakk>is_zariski_open Vt; Vt \<subseteq> U; \<pp> \<in> Vt; b \<in> R; g \<in> R; \<And>\<qq>. \<qq> \<in> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using assms(2,4) sheaf_spec_def is_regular_def is_locally_frac_def
[PROOF STATE]
proof (prove)
using this:
\<pp> \<in> U
t \<in> \<O> U
\<O> ?U \<equiv> {s \<in> \<Pi>\<^sub>E \<pp>\<in>?U. R \<^bsub>\<pp> (+) (\<cdot>) \<zero>\<^esub>. is_regular s ?U}
is_regular ?s ?U \<equiv> \<forall>\<pp>. \<pp> \<in> ?U \<longrightarrow> (\<exists>V. is_zariski_open V \<and> V \<subseteq> ?U \<and> \<pp> \<in> V \<and> is_locally_frac ?s V)
is_locally_frac ?s ?V \<equiv> \<exists>r f. r \<in> R \<and> f \<in> R \<and> (\<forall>\<qq>\<in>?V. f \<notin> \<qq> \<and> ?s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> r f)
goal (1 subgoal):
1. (\<And>Vt b g. \<lbrakk>is_zariski_open Vt; Vt \<subseteq> U; \<pp> \<in> Vt; b \<in> R; g \<in> R; \<And>\<qq>. \<qq> \<in> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
is_zariski_open Vt
Vt \<subseteq> U
\<pp> \<in> Vt
b \<in> R
g \<in> R
?\<qq>3 \<in> Vt \<Longrightarrow> g \<notin> ?\<qq>3 \<and> t ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> b g
goal (1 subgoal):
1. (\<And>V a f b g. \<lbrakk>is_zariski_open V; V \<subseteq> U; \<pp> \<in> V; a \<in> R; f \<in> R; b \<in> R; g \<in> R; f \<notin> \<pp>; g \<notin> \<pp>; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
is_zariski_open Vt
Vt \<subseteq> U
\<pp> \<in> Vt
b \<in> R
g \<in> R
?\<qq>3 \<in> Vt \<Longrightarrow> g \<notin> ?\<qq>3 \<and> t ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> b g
[PROOF STEP]
have "is_zariski_open (Vs \<inter> Vt)" "Vs \<inter> Vt \<subseteq> U" "\<pp> \<in> Vs \<inter> Vt"
"\<And>\<qq>. \<qq> \<in> (Vs \<inter> Vt) \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f"
"\<And>\<qq>. \<qq> \<in> (Vs \<inter> Vt) \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g"
[PROOF STATE]
proof (prove)
using this:
is_zariski_open Vt
Vt \<subseteq> U
\<pp> \<in> Vt
b \<in> R
g \<in> R
?\<qq>3 \<in> Vt \<Longrightarrow> g \<notin> ?\<qq>3 \<and> t ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> b g
goal (1 subgoal):
1. (is_zariski_open (Vs \<inter> Vt) &&& Vs \<inter> Vt \<subseteq> U) &&& \<pp> \<in> Vs \<inter> Vt &&& (\<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f) &&& (\<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g)
[PROOF STEP]
using topological_space.open_inter
[PROOF STATE]
proof (prove)
using this:
is_zariski_open Vt
Vt \<subseteq> U
\<pp> \<in> Vt
b \<in> R
g \<in> R
?\<qq>3 \<in> Vt \<Longrightarrow> g \<notin> ?\<qq>3 \<and> t ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> b g
\<lbrakk>topological_space ?S ?is_open; ?is_open ?U; ?is_open ?V\<rbrakk> \<Longrightarrow> ?is_open (?U \<inter> ?V)
goal (1 subgoal):
1. (is_zariski_open (Vs \<inter> Vt) &&& Vs \<inter> Vt \<subseteq> U) &&& \<pp> \<in> Vs \<inter> Vt &&& (\<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f) &&& (\<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g)
[PROOF STEP]
apply (simp add: \<open>is_zariski_open Vs\<close>)
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. Vs \<inter> Vt \<subseteq> U
2. \<pp> \<in> Vs \<inter> Vt
3. \<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f
4. \<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g
[PROOF STEP]
using \<open>Vs \<subseteq> U\<close>
[PROOF STATE]
proof (prove)
using this:
Vs \<subseteq> U
goal (4 subgoals):
1. Vs \<inter> Vt \<subseteq> U
2. \<pp> \<in> Vs \<inter> Vt
3. \<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f
4. \<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g
[PROOF STEP]
apply auto[1]
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<pp> \<in> Vs \<inter> Vt
2. \<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f
3. \<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g
[PROOF STEP]
apply (simp add: \<open>\<pp> \<in> Vs\<close> \<open>\<pp> \<in> Vt\<close>)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f
2. \<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g
[PROOF STEP]
apply (simp add: \<open>\<And>\<qq>. \<qq> \<in> Vs \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f\<close>)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>\<qq>. \<qq> \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g
[PROOF STEP]
by (simp add: \<open>\<And>\<qq>. \<qq> \<in> Vt \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g\<close>)
[PROOF STATE]
proof (state)
this:
is_zariski_open (Vs \<inter> Vt)
Vs \<inter> Vt \<subseteq> U
\<pp> \<in> Vs \<inter> Vt
?\<qq>3 \<in> Vs \<inter> Vt \<Longrightarrow> f \<notin> ?\<qq>3 \<and> s ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> a f
?\<qq>3 \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> ?\<qq>3 \<and> t ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> b g
goal (1 subgoal):
1. (\<And>V a f b g. \<lbrakk>is_zariski_open V; V \<subseteq> U; \<pp> \<in> V; a \<in> R; f \<in> R; b \<in> R; g \<in> R; f \<notin> \<pp>; g \<notin> \<pp>; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> f \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> a f; \<And>\<qq>. \<qq> \<in> V \<Longrightarrow> g \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> b g\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
is_zariski_open (Vs \<inter> Vt)
Vs \<inter> Vt \<subseteq> U
\<pp> \<in> Vs \<inter> Vt
?\<qq>3 \<in> Vs \<inter> Vt \<Longrightarrow> f \<notin> ?\<qq>3 \<and> s ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> a f
?\<qq>3 \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> ?\<qq>3 \<and> t ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> b g
goal (1 subgoal):
1. thesis
[PROOF STEP]
using \<open>a \<in> R\<close> \<open>b \<in> R\<close> \<open>f \<in> R\<close> \<open>g \<in> R\<close> that
[PROOF STATE]
proof (prove)
using this:
is_zariski_open (Vs \<inter> Vt)
Vs \<inter> Vt \<subseteq> U
\<pp> \<in> Vs \<inter> Vt
?\<qq>3 \<in> Vs \<inter> Vt \<Longrightarrow> f \<notin> ?\<qq>3 \<and> s ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> a f
?\<qq>3 \<in> Vs \<inter> Vt \<Longrightarrow> g \<notin> ?\<qq>3 \<and> t ?\<qq>3 = quotient_ring.frac (R\<setminus>?\<qq>3) R (+) (\<cdot>) \<zero> b g
a \<in> R
b \<in> R
f \<in> R
g \<in> R
\<lbrakk>is_zariski_open ?V3; ?V3 \<subseteq> U; \<pp> \<in> ?V3; ?a3 \<in> R; ?f3 \<in> R; ?b3 \<in> R; ?g3 \<in> R; ?f3 \<notin> \<pp>; ?g3 \<notin> \<pp>; \<And>\<qq>. \<qq> \<in> ?V3 \<Longrightarrow> ?f3 \<notin> \<qq> \<and> s \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> ?a3 ?f3; \<And>\<qq>. \<qq> \<in> ?V3 \<Longrightarrow> ?g3 \<notin> \<qq> \<and> t \<qq> = quotient_ring.frac (R\<setminus>\<qq>) R (+) (\<cdot>) \<zero> ?b3 ?g3\<rbrakk> \<Longrightarrow> thesis
goal (1 subgoal):
1. thesis
[PROOF STEP]
by presburger
[PROOF STATE]
proof (state)
this:
thesis
goal:
No subgoals!
[PROOF STEP]
qed
|
module Coirc.Network where
open import Function
open import Coinduction
open import Data.Unit
open import Data.String
open import Data.Maybe
open import IO
open import Coirc
open import Coirc.Parser
import Coirc.Network.Primitive as Prim
private
Handle = Prim.Handle
hConnect : String → IO Handle
hConnect s = lift (Prim.hConnect s)
hGetLine : Handle → IO String
hGetLine h =
♯ lift (Prim.hGetLine h) >>= λ s →
♯ (♯ putStrLn s >>
♯ return (s ++ "\n"))
hPutStr : Handle → String → IO ⊤
hPutStr h s = ♯ lift (Prim.hPutStr h s) >> ♯ return tt
hSend : Handle → String → IO ⊤
hSend h s =
♯ putStrLn ("> " ++ s) >>
♯ hPutStr h (s ++ "\r\n")
getEvent : Handle → IO (Maybe Event)
getEvent h = ♯ hGetLine h >>= (λ x → ♯ f x) where
f : String → IO (Maybe Event)
f = return ∘ parse-Event ∘ toList
runAction : Handle → Action → IO ⊤
runAction h (print text) =
putStrLn text
runAction h (nick name) =
hSend h ("NICK " ++ name)
runAction h (user name real) =
hSend h ("USER " ++ name ++ " 0 * :" ++ real)
runAction h (pong name) =
hSend h ("PONG " ++ name)
runAction h (join channel) =
hSend h ("JOIN " ++ channel)
runAction h (part channel) =
hSend h ("PART " ++ channel)
runAction h (privmsg target text) =
hSend h ("PRIVMSG " ++ target ++ " :" ++ text)
runAction h (quit text) =
hSend h ("QUIT :" ++ text)
runSP : Handle → Bot → IO ⊤
runSP h (get f) =
♯ getEvent h >>= λ e? →
♯ g e?
where
g : Maybe Event → IO ⊤
g nothing =
♯ putStrLn "<disconnect>" >>
♯ return tt
g (just e) = runSP h (f e)
runSP h (put a sp) =
♯ runAction h a >>
♯ runSP h (♭ sp)
runBot : Bot → String → IO ⊤
runBot bot server =
♯ hConnect server >>= λ h →
♯ runSP h bot
|
/-
Copyright (c) 2020 Bolton Bailey. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bolton Bailey
-/
import data.fintype.basic
import group_theory.order_of_element
import tactic.zify
import data.nat.totient
/-!
# The Lucas test for primes.
This file implements the Lucas test for primes (not to be confused with the Lucas-Lehmer test for
Mersenne primes). A number `a` witnesses that `n` is prime if `a` has order `n-1` in the
multiplicative group of integers mod `n`. This is checked by verifying that `a^(n-1) = 1 (mod n)`
and `a^d ≠ 1 (mod n)` for any divisor `d | n - 1`. This test is the basis of the Pratt primality
certificate.
## TODO
- Bonus: Show the reverse implication i.e. if a number is prime then it has a Lucas witness.
Use `units.is_cyclic` from `ring_theory/integral_domain` to show the group is cyclic.
- Write a tactic that uses this theorem to generate Pratt primality certificates
- Integrate Pratt primality certificates into the norm_num primality verifier
## Implementation notes
Note that the proof for `lucas_primality` relies on analyzing the multiplicative group
modulo `p`. Despite this, the theorem still holds vacuously for `p = 0` and `p = 1`: In these
cases, we can take `q` to be any prime and see that `hd` does not hold, since `a^((p-1)/q)` reduces
to `1`.
-/
/--
If `a^(p-1) = 1 mod p`, but `a^((p-1)/q) ≠ 1 mod p` for all prime factors `q` of `p-1`, then `p`
is prime. This is true because `a` has order `p-1` in the multiplicative group mod `p`, so this
group must itself have order `p-1`, which only happens when `p` is prime.
-/
theorem lucas_primality (p : ℕ) (a : zmod p) (ha : a^(p-1) = 1)
(hd : ∀ q : ℕ, q.prime → q ∣ (p-1) → a^((p-1)/q) ≠ 1) : p.prime :=
begin
have h0 : p ≠ 0, { rintro ⟨⟩, exact hd 2 nat.prime_two (dvd_zero _) (pow_zero _) },
have h1 : p ≠ 1, { rintro ⟨⟩, exact hd 2 nat.prime_two (dvd_zero _) (pow_zero _) },
have hp1 : 1 < p := lt_of_le_of_ne h0.bot_lt h1.symm,
have order_of_a : order_of a = p-1,
{ apply order_of_eq_of_pow_and_pow_div_prime _ ha hd,
exact tsub_pos_of_lt hp1, },
haveI : ne_zero p := ⟨h0⟩,
rw nat.prime_iff_card_units,
-- Prove cardinality of `units` of `zmod p` is both `≤ p-1` and `≥ p-1`
refine le_antisymm (nat.card_units_zmod_lt_sub_one hp1) _,
have hp' : p - 2 + 1 = p - 1 := tsub_add_eq_add_tsub hp1,
let a' : (zmod p)ˣ := units.mk_of_mul_eq_one a (a ^ (p-2)) (by rw [←pow_succ, hp', ha]),
calc p - 1 = order_of a : order_of_a.symm
... = order_of a' : order_of_injective (units.coe_hom (zmod p)) units.ext a'
... ≤ fintype.card (zmod p)ˣ : order_of_le_card_univ,
end
|
# Use data from EveryCen-boxplot.pl and process taking the ratio of ChIP/ Input
## Rscript plot_median.r sample1 sample2 output
args <- commandArgs(trailingOnly = TRUE)
# Load data
sample1 <- read.table(args[1])
sample2 <- read.table(args[2])
library(dplyr)
#calculate the median per region
sample1_median <- as.data.frame(sample1) %>% summarise_each(funs(median(., na.rm=TRUE) ))
sample2_median <- as.data.frame(sample2) %>% summarise_each(funs(median(., na.rm=TRUE) ))
# windows are 100bp, + - 25000bp from the centre of the centromere
Coords <- (1:499 * 100) -25000
#Plot
pdf(paste(args[3], ".pdf", sep=""), width=15)
plot(Coords, log2(sample1_median), pch='.', col="red",
xlab="Position", ylab="log2 of median ratio of reads: ChIP/Input")
lines (Coords, log2(sample1_median), pch='.', col="red", lw=3)
lines (Coords, log2(sample2_median), pch='.', col="darkblue", lw=3)
|
There are 5 XING members by the name of Sebastian Streit.
There are 6 XING members by the name of Sonja Streit.
There are 7 XING members by the name of Stefan Streit.
Projektmitarbeiterin im Projekt "Wie macht man Teilhabe?"
There are 18 XING members by the name of Thomas Streit.
There are 5 XING members by the name of Yvonne Streit.
There are 6 XING members by the name of Michael Streitberger.
|
{-# LANGUAGE RecordWildCards #-}
module Statistics.Block
( BlockHeader (..)
, blockHeadersF
, blockChain
, blockChainF
, txBlocksF
, inBlockChainF
, txCntInChainF
, TxFate (..)
, txFateF
) where
import Control.Foldl (Fold (..), fold)
import qualified Data.Map.Lazy as ML
import qualified Data.Map.Strict as MS
import Data.Maybe (fromJust, isJust)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Time.Units (Microsecond)
import JSONLog (IndexedJLTimedEvent (..))
import Pos.Infra.Util.JsonLog.Events (JLBlock (..), JLEvent (..))
import Prelude (id)
import Statistics.Tx (txFirstReceivedF)
import Types
import Universum hiding (fold)
data BlockHeader = BlockHeader
{ bhNode :: !NodeId
, bhTimestamp :: !Timestamp
, bhHash :: !BlockHash
, bhPrevBlock :: !BlockHash
, bhSlot :: !Slot
, bhTxCnt :: !Int
} deriving Show
type SMap k a = MS.Map k a
type LMap k a = ML.Map k a
blockHeadersF :: Fold IndexedJLTimedEvent (SMap BlockHash BlockHeader)
blockHeadersF = Fold step MS.empty id
where
step :: SMap Text BlockHeader -> IndexedJLTimedEvent -> SMap Text BlockHeader
step m IndexedJLTimedEvent{..} = case ijlEvent of
JLCreatedBlock JLBlock{..} ->
let bh = BlockHeader
{ bhNode = ijlNode
, bhTimestamp = ijlTimestamp
, bhHash = jlHash
, bhPrevBlock = jlPrevBlock
, bhSlot = jlSlot
, bhTxCnt = length jlTxs
}
in MS.insert jlHash bh m
_ -> m
blockChain :: SMap BlockHash BlockHeader -> Set BlockHash
blockChain m = S.fromList $ maybe [] id $ (fmap fst . uncons) $ sortByLengthDesc [getLongestChain h | h <- allHashes]
where
allHashes :: [BlockHash]
allHashes = MS.keys m
sortByLengthDesc :: [[a]] -> [[a]]
sortByLengthDesc = sortBy (compare `on` (negate . length))
successors :: SMap BlockHash [BlockHash]
successors = foldl' f MS.empty allHashes
getSuccessors :: BlockHash -> [BlockHash]
getSuccessors h = MS.findWithDefault [] h successors
f :: SMap BlockHash [BlockHash] -> BlockHash -> SMap BlockHash [BlockHash]
f s h = let BlockHeader{..} = m MS.! h
in MS.alter (Just . maybe [bhHash] (bhHash :)) bhPrevBlock s
longestChains :: LMap Text [Text]
longestChains = ML.fromList [(h, getLongestChain h) | h <- allHashes]
getLongestChain :: Text -> [Text]
getLongestChain h = case sortByLengthDesc $ map (longestChains ML.!) $ getSuccessors h of
[] -> [h]
(c : _) -> h : c
blockChainF :: Fold IndexedJLTimedEvent (Set BlockHash)
blockChainF = blockChain <$> blockHeadersF
txBlocksF :: Fold IndexedJLTimedEvent (SMap TxHash [(Timestamp, BlockHash)])
txBlocksF = Fold step MS.empty id
where
step :: SMap Text [(Microsecond, Text)]
-> IndexedJLTimedEvent
-> SMap Text [(Microsecond, Text)]
step m IndexedJLTimedEvent{..} = case ijlEvent of
JLCreatedBlock JLBlock{..} -> foldl' (f ijlTimestamp jlHash) m [T.take 16 x | x <- jlTxs]
_ -> m
f :: Timestamp
-> Text
-> SMap Text [(Timestamp, Text)]
-> Text
-> SMap Text [(Timestamp, Text)]
f ts h m tx = let y = (ts, h)
in MS.alter (Just . maybe [y] (y :)) tx m
inBlockChainF :: Fold IndexedJLTimedEvent (SMap TxHash Timestamp)
inBlockChainF = f <$> txFateF
where
f :: SMap TxHash TxFate -> SMap TxHash Timestamp
f = MS.map fromJust . MS.filter isJust . MS.map txInBlockChain
txCntInChainF :: Fold IndexedJLTimedEvent [(NodeId, Timestamp, Int)]
txCntInChainF = f <$> blockHeadersF <*> blockChainF
where
f :: Map BlockHash BlockHeader -> Set BlockHash -> [(NodeId, Timestamp, Int)]
f m cs = [(bhNode, bhTimestamp, bhTxCnt) | (_, BlockHeader{..}) <- MS.toList m, bhHash `S.member` cs]
data TxFate =
InNoBlock
| InBlockChain !Timestamp !BlockHash !(Set (Timestamp, BlockHash))
| InFork !(Set (Timestamp, BlockHash))
deriving Show
txInBlockChain :: TxFate -> Maybe Timestamp
txInBlockChain InNoBlock = Nothing
txInBlockChain (InBlockChain ts _ _) = Just ts
txInBlockChain (InFork _) = Nothing
txFateF :: Fold IndexedJLTimedEvent (SMap TxHash TxFate)
txFateF = f <$> txFirstReceivedF <*> txBlocksF <*> blockChainF
where
f :: SMap TxHash Timestamp -> SMap TxHash [(Timestamp, BlockHash)] -> Set BlockHash -> SMap TxHash TxFate
f received blocks chain = MS.fromList [(tx, fate tx) | tx <- MS.keys received]
where
fate :: TxHash -> TxFate
fate tx = case MS.lookup tx blocks of
Nothing -> InNoBlock
Just xs -> fold (Fold step (Nothing, S.empty) extract) xs
step :: (Maybe (Timestamp, BlockHash), Set (Timestamp, BlockHash))
-> (Timestamp, BlockHash)
-> (Maybe (Timestamp, BlockHash), Set (Timestamp, BlockHash))
step (Nothing, s) (ts, h)
| S.member h chain = (Just (ts, h), s)
| otherwise = (Nothing , S.insert (ts, h) s)
step (p , s) q = (p , S.insert q s)
extract :: (Maybe (Timestamp, BlockHash), Set (Timestamp, BlockHash)) -> TxFate
extract (Nothing , s) = InFork s
extract (Just (ts, h), s) = InBlockChain ts h s
|
(*
* © 2019 Massachusetts Institute of Technology.
* MIT Proprietary, Subject to FAR52.227-11 Patent Rights - Ownership by the Contractor (May 2014)
* SPDX-License-Identifier: MIT
*
*)
From Coq Require Import
List
Eqdep
Lia
.
From SPICY Require Import
MyPrelude
AdversaryUniverse
Automation
Keys
Maps
Messages
MessageEq
RealWorld
Simulation
Tactics
Theory.KeysTheory
ModelCheck.ClosureStepLemmas
ModelCheck.SafeProtocol
ModelCheck.UniverseEqAutomation
ModelCheck.ProtocolFunctions
ModelCheck.PartialOrderReduction
ModelCheck.RealWorldStepLemmas
ModelCheck.SilentStepElimination
.
From SPICY Require
IdealWorld
RealWorld
ChMaps
.
From Frap Require
Sets
.
Import ChMaps.ChMapNotation
ChMaps.ChNotation.
Set Implicit Arguments.
Module SimulationAutomation.
#[export] Hint Constructors RealWorld.msg_accepted_by_pattern : core.
#[export] Hint Extern 1 (_ $k++ _ $? _ = Some _) => solve [ solve_perm_merges ] : core.
Module T.
Import RealWorld.
Lemma message_match_not_match_pattern_different :
forall t1 t2 (msg1 : crypto t1) (msg2 : crypto t2) cs suid froms pat,
~ msg_accepted_by_pattern cs suid froms pat msg1
-> msg_accepted_by_pattern cs suid froms pat msg2
-> existT _ _ msg1 <> existT _ _ msg2.
Proof.
intros.
unfold not; intros.
generalize (projT1_eq H1); intros EQ; simpl in EQ; subst.
eapply inj_pair2 in H1; subst.
contradiction.
Qed.
Lemma message_queue_split_head :
forall t1 t2 (msg1 : crypto t1) (msg2 : crypto t2) qmsgs qmsgs1 qmsgs2
cs suid froms pat,
existT _ _ msg2 :: qmsgs = qmsgs1 ++ existT _ _ msg1 :: qmsgs2
-> msg_accepted_by_pattern cs suid froms pat msg1
-> ~ msg_accepted_by_pattern cs suid froms pat msg2
-> Forall (fun '(existT _ _ msg') => ~ msg_accepted_by_pattern cs suid froms pat msg') qmsgs1
-> exists qmsgs1',
qmsgs1 = (existT _ _ msg2) :: qmsgs1'.
Proof.
intros.
destruct qmsgs1.
- rewrite app_nil_l in H.
eapply message_match_not_match_pattern_different in H0; eauto.
invert H; contradiction.
- rewrite <- app_comm_cons in H.
invert H; eauto.
Qed.
Lemma message_queue_solve_head :
forall t1 t2 (msg1 : crypto t1) (msg2 : crypto t2) qmsgs qmsgs1 qmsgs2
cs suid froms pat,
existT _ _ msg2 :: qmsgs = qmsgs1 ++ existT _ _ msg1 :: qmsgs2
-> msg_accepted_by_pattern cs suid froms pat msg1
-> msg_accepted_by_pattern cs suid froms pat msg2
-> Forall (fun '(existT _ _ msg') => ~ msg_accepted_by_pattern cs suid froms pat msg') qmsgs1
-> qmsgs1 = []
/\ qmsgs2 = qmsgs
/\ existT _ _ msg1 = existT _ _ msg2.
Proof.
intros.
subst.
destruct qmsgs1.
rewrite app_nil_l in H
; invert H
; eauto.
exfalso.
rewrite <- app_comm_cons in H.
invert H; eauto.
invert H2; contradiction.
Qed.
Ltac pr_message cs uid froms pat msg :=
(assert (msg_accepted_by_pattern cs uid froms pat msg)
by (econstructor; eauto))
|| (assert (~ msg_accepted_by_pattern cs uid froms pat msg)
by (let MA := fresh "MA" in unfold not; intros MA; invert MA; clean_map_lookups)).
Ltac cleanup_msg_queue :=
repeat (
invert_base_equalities1 ||
match goal with
| [ H : context [ (_ :: _) ++ _ ] |- _ ] =>
rewrite <- app_comm_cons in H
end ).
Ltac process_message_queue :=
cleanup_msg_queue;
match goal with
| [ H : (existT _ _ ?m) :: ?msgs = ?msgs1 ++ (existT _ _ ?msg) :: ?msgs2,
M : msg_accepted_by_pattern ?cs ?suid ?froms ?pat ?msg
|- _ ] =>
pr_message cs suid froms pat m
; match goal with
| [ MSA : msg_accepted_by_pattern cs suid froms pat m
, HD : Forall _ msgs1
|- _ ] =>
idtac "solving " H M MSA HD
; pose proof (message_queue_solve_head _ H M MSA HD)
; split_ex; subst
; cleanup_msg_queue; subst
| [ MSA : ~ msg_accepted_by_pattern cs suid froms pat m
, HD : Forall _ msgs1
|- _ ] =>
idtac "splitting"
; pose proof (message_queue_split_head _ H M MSA HD)
; split_ex; subst
; invert HD
; cleanup_msg_queue; subst
; process_message_queue (* recurse *)
end
end.
Ltac step_usr_hyp H cmd :=
match cmd with
| Return _ => apply step_user_inv_ret in H; contradiction
(* | Bind _ _ => apply step_user_inv_bind in H; split_ands; split_ors; split_ands; subst; try discriminate *)
| Bind _ _ => apply step_user_inv_bind in H; destruct H; split_ex; subst; try discriminate
| Gen => apply step_user_inv_gen in H
| Send _ _ => apply step_user_inv_send in H
| Recv _ => apply step_user_inv_recv in H; split_ex; subst; process_message_queue
| SignEncrypt _ _ _ _ => apply step_user_inv_enc in H
| Decrypt _ => apply step_user_inv_dec in H
| Sign _ _ _ => apply step_user_inv_sign in H
| Verify _ _ => apply step_user_inv_verify in H
| GenerateKey _ _ => apply step_user_inv_genkey in H
| realServer 0 _ _ => rewrite realserver_done in H
| realServer _ _ _ => erewrite unroll_realserver_step in H by reflexivity
| _ => idtac "***Missing inversion: " cmd; invert H
end; split_ex; subst.
Lemma inv_univ_silent_step :
forall t__hon t__adv ru ru' suid b,
lameAdv b ru.(RealWorld.adversary)
-> @RealWorld.step_universe t__hon t__adv suid ru Silent ru'
-> exists uid ud usrs adv cs gks ks qmsgs mycs froms sents cur_n cmd,
ru.(RealWorld.users) $? uid = Some ud
/\ step_user Silent (Some uid)
(build_data_step ru ud)
(usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)
/\ ru' = buildUniverse usrs adv cs gks uid {| key_heap := ks
; msg_heap := qmsgs
; protocol := cmd
; c_heap := mycs
; from_nons := froms
; sent_nons := sents
; cur_nonce := cur_n |}.
Proof.
intros * LAME STEP
; invert STEP.
- unfold mkULbl in H2
; destruct lbl
; try discriminate
; eauto 20.
- unfold lameAdv in LAME.
unfold build_data_step in H
; rewrite LAME in H
; invert H.
Qed.
Lemma inv_univ_labeled_step :
forall t__hon t__adv ru ru' suid uid a,
@RealWorld.step_universe t__hon t__adv suid ru (Action (uid,a)) ru'
-> exists ud usrs adv cs gks ks qmsgs mycs froms sents cur_n cmd,
ru.(RealWorld.users) $? uid = Some ud
/\ suid = Some uid
/\ step_user (@Action RealWorld.action a) (Some uid)
(build_data_step ru ud)
(usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)
/\ ru' = buildUniverse usrs adv cs gks uid {| key_heap := ks
; msg_heap := qmsgs
; protocol := cmd
; c_heap := mycs
; from_nons := froms
; sent_nons := sents
; cur_nonce := cur_n |}.
Proof.
intros * STEP
; invert STEP.
unfold mkULbl in H2
; destruct lbl
; try discriminate.
invert H2; eauto 20.
Qed.
Ltac rw_step1 :=
match goal with
(* Only take a user step if we have chosen a user *)
| [ H : RealWorld.step_user _ (Some ?u) _ _ |- _ ] =>
progress simpl in H
| [ H : RealWorld.step_user _ (Some ?u) (_,_,_,_,_,_,_,_,_,_,?cmd) _ |- _ ] =>
is_not_var u;
step_usr_hyp H cmd
| [ STEP : RealWorld.step_user _ None (_,_,_,_,_,_,_,_,_,_,RealWorld.protocol ?adv) _
, LAME : lameAdv _ ?adv |- _ ] => pose proof (adv_no_step LAME STEP); contradiction
| [ H : RealWorld.step_user _ _ (build_data_step _ _) _ |- _ ] =>
unfold build_data_step in H; autounfold with user_build in H; simpl in H
| [ |- context [RealWorld.buildUniverse _ _ _ _ _ _] ] =>
unfold RealWorld.buildUniverse
| [ H: step_universe _ ?U Silent _ |- _ ] =>
is_not_var U
; eapply inv_univ_silent_step in H
; eauto
; split_ex
; subst
| [ H: step_universe _ ?U (Action _) _ |- _ ] =>
is_not_var U
; eapply inv_univ_labeled_step in H
; eauto
; split_ex
; subst
end.
Ltac prove_alignment1 :=
equality1 ||
match goal with
| [ |- labels_align _ ] => unfold labels_align; intros
| [ H : _ \/ False |- _ ] =>
destruct H; [|contradiction]
| [ H : _ \/ ?r |- _ ] =>
destruct H
| [ H : indexedRealStep _ _ _ _ |- _ ] => invert H
| [ H : users _ $? _ = Some _ |- _ ] =>
progress (autounfold in H; simpl in H)
(* | [ H : _ $+ (_,_) $? _ = Some _ |- _ ] => progress clean_map_lookups *)
| [ H : _ $+ (?k1,_) $? ?k2 = Some _ |- _ ] => destruct (k1 ==n k2); subst
| [ H : step_user (Action _) (Some ?uid) _ _ |- _ ] =>
progress (autounfold in H; unfold RealWorld.build_data_step in H; simpl in H)
| [ H : step_user _ (Some ?u) (_,_,_,_,_,_,_,_,_,_,?cmd) _ |- _ ] =>
is_not_var u; is_not_evar u;
step_usr_hyp H cmd
| [ |- exists _ _ _, _ ] => simpl; (do 3 eexists); repeat simple apply conj
end.
(* || equality1. *)
Lemma label_align_step_split :
forall t__hon t__adv st st',
@step t__hon t__adv st st'
-> labels_align st
-> forall ru ru' iu iu' b b' a,
st = (ru,iu,b)
-> st' = (ru',iu',b')
-> lameAdv a ru.(adversary)
-> b = b'
/\ exists uid,
( indexedRealStep uid Silent ru ru' /\ iu = iu' )
\/ exists iu0 ra ia,
indexedRealStep uid (Action ra) ru ru'
/\ (indexedIdealStep uid Silent) ^* iu iu0
/\ indexedIdealStep uid (Action ia) iu0 iu'
/\ action_matches (all_ciphers ru) (all_keys ru) (uid,ra) ia.
Proof.
intros.
subst; invert H; try contradiction.
- invert H2;
try
match goal with
| [ H : Silent = mkULbl ?lbl _ |- _ ] => unfold mkULbl in H; destruct lbl; try discriminate
end;
split; eexists; left; eauto.
unfold build_data_step in *; unfold lameAdv in H3; rewrite H3 in *.
invert H.
- split; eexists; right; eauto 10.
Unshelve.
auto.
Qed.
Lemma label_align_indexedModelStep_split :
forall t__hon t__adv st st' uid,
@indexedModelStep t__hon t__adv uid st st'
-> labels_align st
-> forall ru ru' iu iu' b b' a,
st = (ru,iu,b)
-> st' = (ru',iu',b')
-> lameAdv a ru.(adversary)
-> b = b'
/\ ( (indexedRealStep uid Silent ru ru' /\ iu = iu')
\/ (exists iu0 ra ia,
indexedRealStep uid (Action ra) ru ru'
/\ (indexedIdealStep uid Silent) ^* iu iu0
/\ indexedIdealStep uid (Action ia) iu0 iu'
/\ action_matches (all_ciphers ru) (all_keys ru) (uid,ra) ia)).
Proof.
intros;
subst; invert H; try contradiction; eauto 12.
Qed.
End T.
Import T.
Export T.
Ltac fill_unification_var_ineq uni v :=
match goal with
| [ H : ?uni' = v -> False |- _ ] => unify uni uni'
| [ H : v = ?uni' -> False |- _ ] => unify uni uni'
end.
Ltac solve_simple_ineq :=
repeat
match goal with
| [ |- ?kid1 <> ?kid2 ] =>
congruence
|| (is_evar kid1; fill_unification_var_ineq kid1 kid2)
|| (is_evar kid2; fill_unification_var_ineq kid2 kid1)
|| (is_not_var kid1; progress unfold kid1)
|| (is_not_var kid2; progress unfold kid2)
end.
Ltac solve_concrete_maps1 :=
clean_map_lookups1
|| ChMaps.ChMap.clean_map_lookups1
|| match goal with
(* | [ H : Some _ = Some _ |- _ ] => invert H *)
(* | [ H : Some _ = None |- _ ] => discriminate *)
(* | [ H : None = Some _ |- _ ] => discriminate *)
| [ H : mkKeys _ $? _ = _ |- _ ] => unfold mkKeys in H; simpl in H
| [ H : ?m $? _ = _ |- _ ] => progress (unfold m in H)
| [ H : ?m #? _ = _ |- _ ] => progress (unfold m in H)
| [ |- context [ ?m $? _ ] ] => progress (unfold m)
| [ |- context [ ?m #? _ ] ] => progress (unfold m)
| [ H : ?m $+ (?k1,_) $? ?k2 = _ |- _ ] =>
progress ( repeat ( rewrite add_neq_o in H by solve_simple_ineq ) )
| [ H : ?m #+ (?k1,_) #? ?k2 = _ |- _ ] =>
progress ( repeat ( rewrite ChMaps.ChMap.F.add_neq_o in H by solve_simple_ineq ) )
| [ |- context [ _ $+ (?kid2,_) $? ?kid1 ] ] =>
progress ( repeat ( rewrite add_neq_o by solve_simple_ineq ) )
| [ |- context [ _ #+ (?kid2,_) #? ?kid1 ] ] =>
progress ( repeat ( rewrite ChMaps.ChMap.F.add_neq_o by solve_simple_ineq ) )
| [ H : In ?k ?m -> False |- _ ] =>
is_not_var k;
assert (In k m) by (clear H; rewrite in_find_iff; unfold not; intros; repeat solve_concrete_maps1);
contradiction
| [ H : In _ _ |- _ ] => rewrite in_find_iff in H
| [ H : ~ In _ _ |- _ ] => rewrite not_find_in_iff in H
| [ |- ~ In _ _ ] => rewrite not_find_in_iff; try eassumption
| [ H : In ?x ?xs -> False |- _ ] => change (In x xs -> False) with (~ In x xs) in H
| [ H : ChMaps.ChMap.Map.In ?k ?m -> False |- _ ] =>
is_not_var k
; assert (ChMaps.ChMap.Map.In k m)
by (clear H; rewrite ChMaps.ChMap.F.in_find_iff; unfold not; intros; repeat solve_concrete_maps1)
; contradiction
| [ H : ChMaps.ChMap.Map.In _ _ |- _ ] => rewrite ChMaps.ChMap.F.in_find_iff in H
| [ H : ~ ChMaps.ChMap.Map.In _ _ |- _ ] => rewrite ChMaps.ChMap.F.not_find_in_iff in H
| [ |- ~ ChMaps.ChMap.Map.In _ _ ] => rewrite ChMaps.ChMap.F.not_find_in_iff; try eassumption
| [ H : ChMaps.ChMap.Map.In ?x ?xs -> False |- _ ] =>
change (ChMaps.ChMap.Map.In x xs -> False) with (~ ChMaps.ChMap.Map.In x xs) in H
| [ |- context [ next_key ] ] => progress (unfold next_key; simpl)
| [ |- _ $+ (?k1,_) $? ?k2 = _ ] =>
is_not_evar k2; is_not_evar k2; (is_var k1 || is_var k2)
; destruct (k1 ==n k2); subst; try contradiction
| [ |- _ #+ (?k1,_) #? ?k2 = _ ] =>
is_not_evar k2; is_not_evar k2; (is_var k1 || is_var k2)
; destruct (ChMaps.ChMap.F.eq_dec k1 k2); subst; try contradiction
| [ |- context [ add_key_perm _ _ _ ]] => progress (unfold add_key_perm)
| [ |- _ = _ ] => reflexivity
| [ |- _ $+ (_,_) = _ ] => apply map_eq_Equal; unfold Equal; intros
| [ |- _ #+ (_,_) = _ ] => apply ChMaps.ChMap.map_eq_Equal; unfold ChMaps.ChMap.Map.Equal; intros
| [ |- Some _ = Some _ ] => f_equal
| [ |- {| RealWorld.key_heap := _ |} = _ ] => f_equal
| [ |- _ $? _ = _ ] => eassumption
| [ |- _ #? _ = _ ] => eassumption
| [ H : ?m $+ (?k1,_) $? ?k2 = _ |- _ $+ (_,_) $? _ = _ ] =>
(is_var k1 || is_var k2); idtac "destructing1 " k1 k2; destruct (k1 ==n k2); subst
| [ H : ?m $+ (?k1,_) $? ?k2 = _ |- (match _ $+ (_,_) $? _ with _ => _ end) $? _ = _ ] =>
(is_var k1 || is_var k2); idtac "destructing2 " k1 k2; destruct (k1 ==n k2); subst
| [ H : ?m #+ (?k1,_) #? ?k2 = _ |- _ #+ (_,_) #? _ = _ ] =>
(is_var k1 || is_var k2); idtac "#destructing1 " k1 k2; destruct (ChMaps.ChMap.F.eq_dec k1 k2); subst
| [ H : ?m #+ (?k1,_) #? ?k2 = _ |- (match _ #+ (_,_) #? _ with _ => _ end) #? _ = _ ] =>
(is_var k1 || is_var k2); idtac "#destructing2 " k1 k2; destruct (ChMaps.ChMap.F.eq_dec k1 k2); subst
end.
Ltac solve_concrete_maps := repeat solve_concrete_maps1.
Ltac churn2 :=
(repeat equality1); subst; split_ors; try contradiction; rw_step1.
(* (repeat equality1); subst; rw_step1; intuition idtac; split_ex; intuition idtac; subst; try discriminate; solve_concrete_maps. *)
Ltac churn :=
repeat churn2.
Ltac i_single_silent_step :=
eapply IdealWorld.LStepBindProceed
|| eapply IdealWorld.LStepGen
|| eapply IdealWorld.LStepCreateChannel
.
Ltac r_single_silent_step :=
eapply RealWorld.StepBindProceed
|| eapply RealWorld.StepGen
(* || eapply RealWorld.StepRecvDrop *)
|| eapply RealWorld.StepEncrypt
|| eapply RealWorld.StepDecrypt
|| eapply RealWorld.StepSign
|| eapply RealWorld.StepVerify
|| eapply RealWorld.StepGenerateKey
.
Ltac pick_user uid :=
match goal with
| [ |- _ $? ?euid = Some _ ] => unify euid uid
end; reflexivity.
Ltac istep_univ uid :=
eapply IdealWorld.LStepUser'; simpl; swap 2 3; [ pick_user uid | ..];
(try eapply @eq_refl); (try f_equal); simpl.
Ltac rstep_univ uid :=
eapply RealWorld.StepUser; simpl; swap 2 3; [ pick_user uid | ..]; (try eapply @eq_refl); simpl.
Ltac rw H :=
(rewrite ChMaps.ChMap.F.add_neq_o in H by congruence)
|| (rewrite ChMaps.ChMap.F.add_eq_o in H by congruence).
Ltac solve_ideal_step_stuff1 :=
match goal with
| [ H : context [ _ #+ (_,_) #? _ ] |- _ ] => progress (repeat rw H)
| [ Heq : ?k = _, H : _ #+ (?k1,_) #? ?k2 = None |- _ ] =>
match k2 with
| # k => idtac k
| _ => fail 1
end;
assert (k1 <> k2)
by (destruct (ChMaps.ChMap.F.eq_dec k1 k2); clear Heq; try assumption;
unfold ChMaps.ChannelType.eq in *; subst; ChMaps.ChMap.clean_map_lookups);
ChMaps.ChMap.clean_map_lookups
| [ H : # ?x = # ?y -> False |- _ ] => assert (x <> y) by congruence; clear H
| [ |- Forall _ _ ] => econstructor
| [ |- {| IdealWorld.channel_vector := _; IdealWorld.users := _ |} = _] => smash_universe; solve_concrete_maps
| [ |- _ = {| IdealWorld.channel_vector := _; IdealWorld.users := _ |}] => smash_universe; solve_concrete_maps
| [ |- IdealWorld.screen_msg _ _ ] => econstructor
| [ |- IdealWorld.permission_subset _ _ ] => econstructor
| [ |- IdealWorld.check_perm _ _ _ ] => unfold IdealWorld.check_perm
| [ |- ?m #? (# ?k) = None ] =>
solve [ is_evar k; unify k (ChMaps.next_key_nat m); apply ChMaps.next_key_not_in; trivial ]
| [ |- context [ ChMaps.next_key_nat ?m ]] =>
match goal with
| [ |- context [ IdealWorld.addMsg ] ] => unfold IdealWorld.addMsg; simpl
| _ =>
idtac "posing"
; pose proof (ChMaps.next_key_not_in m _ eq_refl)
; let k := fresh "k" in
let Heq := fresh "Heq"
in remember (ChMaps.next_key_nat m) as k eqn:Heq
end
(* | [ |- context [ match ?m $+ (?kid1,_) $? ?kid1 with _ => _ end ] ] => *)
(* rewrite add_eq_o by trivial *)
| [ |- context [ match ?m $+ (?kid2,_) $? ?kid1 with _ => _ end] ] =>
progress (
repeat (
( rewrite add_eq_o by trivial)
|| (rewrite add_neq_o by solve_simple_ineq)
)
)
| [ |- context [ #0 #? _ ]] => rewrite ChMaps.ChMap.lookup_empty_none
| [ |- _ = _ ] => subst; reflexivity
| [ |- context [ _ $? _ ] ] => progress solve_concrete_maps
| [ |- context [ _ #? _ ] ] => progress solve_concrete_maps
| [ H : match _ $+ (?k1,_) $? ?k2 with _ => _ end |- _ ] =>
try (
progress (
repeat (( rewrite add_eq_o in H by trivial)
|| (rewrite add_neq_o in H by solve_simple_ineq)
|| (rewrite lookup_empty_none in H))
))
|| destruct (k1 ==n k2); subst
end; simpl.
Ltac solve_ideal_step_stuff := repeat solve_ideal_step_stuff1.
Ltac isilent_step_univ uid :=
eapply IdealWorld.LStepUser'; simpl; swap 2 3; [ pick_user uid | ..]; (try simple eapply @eq_refl);
((eapply IdealWorld.LStepBindRecur; i_single_silent_step; solve [ solve_ideal_step_stuff; eauto 2 ])
|| (i_single_silent_step; solve [ solve_ideal_step_stuff; eauto 2 ])).
Ltac rsilent_step_univ uid :=
eapply RealWorld.StepUser; simpl; swap 2 3; [ pick_user uid | ..]; (try simple eapply @eq_refl);
((eapply RealWorld.StepBindRecur; r_single_silent_step) || r_single_silent_step).
Ltac single_silent_multistep usr_step := eapply TrcFront; [usr_step |]; simpl.
Ltac single_silent_multistep3 usr_step := eapply Trc3Front; swap 1 2; [usr_step |..]; simpl; trivial.
Ltac real_single_silent_multistep uid := single_silent_multistep3 ltac:(rsilent_step_univ uid).
Ltac ideal_single_silent_multistep uid := single_silent_multistep ltac:(isilent_step_univ uid).
Ltac figure_out_ideal_user_step step_tac U1 U2 :=
match U1 with
| context [ add ?u ?usr1 _ ] =>
match U2 with
| context [ add u ?usr2 _ ] =>
let p1 := constr:(IdealWorld.protocol usr1) in
let p2 := constr:(IdealWorld.protocol usr2) in
does_not_unify p1 p2; step_tac u
end
end.
Ltac figure_out_real_user_step step_tac U1 U2 :=
match U1 with
| context [ add ?u ?usr1 _ ] =>
match U2 with
| context [ add u ?usr2 _ ] =>
let p1 := constr:(RealWorld.protocol usr1) in
let p2 := constr:(RealWorld.protocol usr2) in
does_not_unify p1 p2; step_tac u
end
end.
#[export] Remove Hints TrcRefl TrcFront Trc3Refl Trc3Front : core.
#[export] Hint Extern 1 (_ ^* ?U ?U) => apply TrcRefl : core.
#[export] Remove Hints
eq_sym (* includes_lookup *)
trans_eq_bool mult_n_O plus_n_O eq_add_S f_equal_nat : core.
#[export] Hint Constructors action_matches : core.
#[export] Hint Resolve IdealWorld.LStepSend IdealWorld.LStepRecv' : core.
Lemma TrcRefl' :
forall {A} (R : A -> A -> Prop) x1 x2,
x1 = x2 ->
trc R x1 x2.
Proof.
intros. subst. apply TrcRefl.
Qed.
Lemma Trc3Refl' :
forall {A B} (R : A -> B -> A -> Prop) x1 x2 P,
x1 = x2 ->
trc3 R P x1 x2.
Proof.
intros. subst. apply Trc3Refl.
Qed.
Ltac solve_refl :=
solve [
eapply TrcRefl
| eapply TrcRefl'; simpl; eauto ].
Ltac solve_refl3 :=
solve [
eapply Trc3Refl
| eapply Trc3Refl'; simpl; smash_universe; solve_concrete_maps ].
Ltac simpl_real_users_context :=
simpl;
repeat
match goal with
| [ |- context [ RealWorld.buildUniverse ] ] => progress (unfold RealWorld.buildUniverse; simpl)
| [ |- context [ {| RealWorld.users := ?usrs |}] ] => progress canonicalize_map usrs
(* | [ |- context [ RealWorld.mkUniverse ?usrs _ _ _] ] => canonicalize_map usrs *)
end.
Ltac simpl_ideal_users_context :=
simpl;
repeat
match goal with
| [ |- context [ {| IdealWorld.users := ?usrs |}] ] => progress canonicalize_map usrs
end.
Ltac rss_clean uid := real_single_silent_multistep uid; [ solve [eauto 3] .. |].
Ltac ideal_silent_multistep :=
simpl_ideal_users_context;
match goal with
| [ |- istepSilent ^* ?U1 ?U2 ] =>
is_not_evar U1; is_not_evar U2;
first [
solve_refl
| figure_out_ideal_user_step ideal_single_silent_multistep U1 U2 ]
end.
Ltac single_step_ideal_universe :=
simpl_ideal_users_context;
match goal with
| [ |- IdealWorld.lstep_universe _ ?U1 _ ?U2] =>
match U1 with
| IdealWorld.construct_universe _ ?usrs1 =>
match U2 with
| IdealWorld.construct_universe _ ?usrs2 =>
figure_out_ideal_user_step istep_univ usrs1 usrs2
end
end
end.
Ltac single_labeled_ideal_step uid :=
eapply IdealWorld.LStepUser' with (u_id := uid);
[ solve [ solve_concrete_maps ] | simpl | reflexivity ];
eapply IdealWorld.LStepBindRecur;
( (eapply IdealWorld.LStepRecv'; solve [ solve_ideal_step_stuff ])
|| (eapply IdealWorld.LStepSend; solve [ solve_ideal_step_stuff ])).
Ltac step_each_ideal_user U :=
match U with
| ?usrs $+ (?AB,_) =>
idtac "stepping " AB; (single_labeled_ideal_step AB || step_each_ideal_user usrs)
end.
(* TODO: during canonicalization, cleanup the channels map *)
Local Ltac blah1 :=
match goal with
| [ |- context [ IdealWorld.addMsg ]] => unfold IdealWorld.addMsg; simpl
| [ |- context [ ?m #? _ ]] => progress unfold m
| [ |- context [ _ #+ (?k1,_) #? ?k1 ]] => rewrite ChMaps.ChMap.F.add_eq_o by trivial
| [ |- context [ _ #+ (?k1,_) #? ?k2 ]] => rewrite ChMaps.ChMap.F.add_neq_o by congruence
end.
Ltac step_ideal_user :=
match goal with
| [ |- IdealWorld.lstep_universe _ _ (Action _) ?U' ] =>
is_evar U'; simpl_ideal_users_context; (repeat blah1);
match goal with
| [ |- IdealWorld.lstep_universe
{| IdealWorld.users := ?usrs; IdealWorld.channel_vector := _ |} _ _ ] =>
step_each_ideal_user usrs
end
end.
Ltac idealUserSilentStep :=
(eapply IdealWorld.LStepBindRecur; i_single_silent_step; solve [ solve_ideal_step_stuff; eauto 2 ])
|| (i_single_silent_step; solve [ solve_ideal_step_stuff; eauto 2 ]).
Ltac indexedIdealSilentStep :=
econstructor; simpl; [ solve [ clean_map_lookups; trivial ]
| solve [ idealUserSilentStep ]
| reflexivity ].
Ltac solve_indexed_silent_multistep :=
simpl_ideal_users_context;
eapply TrcFront; [ indexedIdealSilentStep |].
Ltac unBindi :=
match goal with
| [ |- IdealWorld.lstep_user _ (Action _) (_,IdealWorld.Bind _ _,_) _ ] =>
eapply IdealWorld.LStepBindRecur
end.
Ltac ideal_user_labeled_step :=
simpl
; (try match goal with
| [ |- IdealWorld.lstep_user _ (Action _) (_,idealServer 0 _ _,_) _ ] =>
rewrite idealserver_done
| [ |- IdealWorld.lstep_user _ (Action _) (_,idealServer _ _ _,_) _ ] =>
erewrite unroll_idealserver_step by reflexivity
end)
; repeat unBindi
; match goal with
| [ |- IdealWorld.lstep_user _ (Action _) (_,IdealWorld.Recv _,_) _ ] =>
eapply IdealWorld.LStepRecv'; solve_ideal_step_stuff
| [ |- IdealWorld.lstep_user _ (Action _) (_,IdealWorld.Send _ _,_) _ ] =>
eapply IdealWorld.LStepSend; solve_ideal_step_stuff
end.
Ltac indexedIdealStep :=
match goal with
| [ |- indexedIdealStep _ (Action _) _ ?U' ] =>
is_evar U'; simpl_ideal_users_context; (repeat blah1);
econstructor; simpl; [ solve [ clean_map_lookups; trivial ]
| ideal_user_labeled_step
| reflexivity ]
end.
#[export] Hint Extern 1 ((indexedIdealStep _ Silent) ^* _ _) =>
repeat solve_indexed_silent_multistep; solve_refl : core.
#[export] Hint Extern 1 (indexedIdealStep _ (Action _) _ _) => indexedIdealStep : core.
#[export] Hint Extern 1 (istepSilent ^* _ _) => ideal_silent_multistep : core.
#[export] Hint Extern 1 ({| IdealWorld.channel_vector := _; IdealWorld.users := _ |} = _) => smash_universe; solve_concrete_maps : core.
#[export] Hint Extern 1 (_ = {| IdealWorld.channel_vector := _; IdealWorld.users := _ |}) => smash_universe; solve_concrete_maps : core.
#[export] Hint Extern 1 (IdealWorld.lstep_universe _ _ _) => step_ideal_user : core.
#[export] Hint Extern 1 (List.In _ _) => progress simpl : core.
#[export] Hint Extern 1 (~ In ?k ?m) =>
solve_concrete_maps : core.
#[export] Hint Extern 1 (action_adversary_safe _ _ _ = _) => unfold action_adversary_safe; simpl : core.
#[export] Hint Extern 1 (IdealWorld.screen_msg _ _) => econstructor; progress simpl : core.
#[export] Hint Extern 1 (_ = RealWorld.addUserKeys _ _) => unfold RealWorld.addUserKeys, map; simpl : core.
#[export] Hint Extern 1 (_ $+ (_,_) = _) =>
reflexivity || (solve [ solve_concrete_maps ] ) || (progress m_equal) || (progress clean_map_lookups) : core.
#[export] Hint Extern 1 (_ $? _ = _) =>
reflexivity || (solve [ solve_concrete_maps ] ) || (progress m_equal) || (progress clean_map_lookups) : core.
#[export] Hint Extern 1 (_ #+ (_,_) = _) =>
reflexivity || (solve [ solve_concrete_maps ] ) || (progress ChMaps.m_equal) || (progress ChMaps.ChMap.clean_map_lookups) : core.
#[export] Hint Extern 1 (_ #? _ = _) =>
reflexivity || (solve [ solve_concrete_maps ] ) || (progress ChMaps.m_equal) || (progress ChMaps.ChMap.clean_map_lookups) : core.
Local Ltac merge_perms_helper :=
repeat match goal with
| [ |- _ = _ ] => reflexivity
| [ |- _ $? _ = _ ] => solve_concrete_maps
end.
Ltac solve_action_matches1 :=
match goal with
| [ |- content_eq _ _ _ ] => progress simpl
| [ |- action_matches _ _ _ _ ] => progress simpl_real_users_context
| [ |- action_matches _ _ _ _ ] => progress simpl_ideal_users_context
| [ H : ?cs $? ?cid = Some (SigCipher _ _ _ _ )
|- action_matches ?cs _ (_,RealWorld.Output (SignedCiphertext ?cid) _ _ _) _ ] => eapply OutSig
| [ H : ?cs $? ?cid = Some (SigEncCipher _ _ _ _ _ )
|- action_matches ?cs _ (_,RealWorld.Output (SignedCiphertext ?cid) _ _ _) _ ] => eapply OutEnc
| [ H : ?cs $? ?cid = Some (SigCipher _ _ _ _ )
|- action_matches ?cs _ (_,RealWorld.Input (SignedCiphertext ?cid) _ _) _ ] => eapply InpSig
| [ H : ?cs $? ?cid = Some (SigEncCipher _ _ _ _ _ )
|- action_matches ?cs _ (_,RealWorld.Input (SignedCiphertext ?cid) _ _) _ ] => eapply InpEnc
| [ |- action_matches ?cs _ (_,RealWorld.Output (SignedCiphertext ?cid) _ _ _) _ ] =>
match cs with
| context [ _ $+ (cid, SigCipher _ _ _ _)] => eapply OutSig
| context [_ $+ (cid, SigEncCipher _ _ _ _ _)] => eapply OutEnc
end
| [ |- action_matches ?cs _ (_,RealWorld.Input (SignedCiphertext ?cid) _ _) _ ] =>
match cs with
| context[ _ $+ (cid, SigCipher _ _ _ _)] => eapply InpSig
| context[ _ $+ (cid, SigEncCipher _ _ _ _ _)] => eapply InpEnc
end
| [ H : _ $+ (?k1,_) $? ?k2 = Some ?d__rw |- context [ RealWorld.key_heap ?d__rw $? _ = Some _ ] ] =>
is_var d__rw; is_var k2; is_not_var k1;
destruct (k1 ==n k2); subst; clean_map_lookups; simpl
| [ H : ?P $? _ = Some {| IdealWorld.read := _; IdealWorld.write := _ |} |- _ ] =>
simpl in *; unfold P in H; solve_concrete_maps
| [ |- _ $? _ = Some _ ] => progress solve_concrete_maps
| [ |- context [ IdealWorld.addMsg ]] => unfold IdealWorld.addMsg; simpl
| [ |- context [ ?m #? _ ]] => progress unfold m
| [ |- context [ _ #+ (?k1,_) #? ?k1 ]] => rewrite ChMaps.ChMap.F.add_eq_o by trivial
| [ |- context [ _ #+ (?k1,_) #? ?k2 ]] => rewrite ChMaps.ChMap.F.add_neq_o by congruence
| [ |- context [ IdealWorld.perm_intersection ] ] =>
unfold IdealWorld.perm_intersection; simpl
| [ H : _ $k++ _ $? _ = Some ?b |- context [ ?b ]] =>
solve [ solve_perm_merges; solve_concrete_maps ]
| [ |- _ $k++ _ $? _ = Some _ ] =>
solve [ erewrite merge_perms_adds_ks1; (swap 2 4; merge_perms_helper) ]
|| solve [ erewrite merge_perms_adds_ks2; (swap 2 4; merge_perms_helper) ]
| [ H : match _ $+ (?k1,_) $? ?k1 with _ => _ end = _ |- _ ] =>
rewrite add_eq_o in H by trivial
| [ H : match _ $+ (?k1,_) $? ?k2 with _ => _ end = _ |- _ ] =>
rewrite add_neq_o in H by congruence
| [ |- _ <-> _ ] => split
| [ |- _ -> _ ] => intros
| [ |- _ = _ ] => reflexivity
| [ |- _ /\ _ ] => split
| [ |- context [ _ $? _ ]] =>
progress (
repeat (
(rewrite add_eq_o by trivial)
|| (rewrite add_neq_o by congruence)
|| (rewrite lookup_empty_none by congruence)
)
)
end; split_ex; simpl in *.
#[export] Hint Extern 1 (action_matches _ _ _ _) =>
repeat (solve_action_matches1)
; NatMap.clean_map_lookups
; ChMaps.ChMap.clean_map_lookups : core.
#[export] Hint Resolve
findUserKeys_foldfn_proper
findUserKeys_foldfn_transpose : core.
Lemma findUserKeys_add_reduce :
forall {A} (usrs : RealWorld.honest_users A) u_id ks p qmsgs mycs froms sents cur_n,
~ In u_id usrs
-> RealWorld.findUserKeys (usrs $+ (u_id, {| RealWorld.key_heap := ks;
RealWorld.protocol := p;
RealWorld.msg_heap := qmsgs;
RealWorld.c_heap := mycs;
RealWorld.from_nons := froms;
RealWorld.sent_nons := sents;
RealWorld.cur_nonce := cur_n |})) = RealWorld.findUserKeys usrs $k++ ks.
Proof.
intros.
unfold RealWorld.findUserKeys.
rewrite fold_add; eauto.
Qed.
Lemma findUserKeys_empty_is_empty :
forall A, @RealWorld.findUserKeys A $0 = $0.
Proof. trivial. Qed.
#[export] Hint Constructors RealWorld.msg_pattern_safe : core.
Lemma reduce_merge_perms :
forall perms1 perms2 kid perm1 perm2,
perm1 = match perms1 $? kid with
| Some p => p
| None => false
end
-> perm2 = match perms2 $? kid with
| Some p => p
| None => false
end
-> (perms1 $? kid = None -> perms2 $? kid = None -> False)
-> perms1 $k++ perms2 $? kid = Some (perm1 || perm2).
Proof.
intros; solve_perm_merges; subst; eauto.
- rewrite orb_false_r; auto.
- exfalso; eauto.
Qed.
Ltac solve_concrete_perm_merges :=
repeat
match goal with
| [ |- context [true || _] ] => rewrite orb_true_l
| [ |- context [_ || true] ] => rewrite orb_true_r
| [ |- context [$0 $k++ _] ] => rewrite merge_perms_left_identity
| [ |- context [_ $k++ $0] ] => rewrite merge_perms_right_identity
| [ |- context [_ $k++ _] ] => erewrite reduce_merge_perms by (clean_map_lookups; eauto)
end; trivial.
Ltac simplify_terms :=
unfold RealWorld.msg_honestly_signed
, RealWorld.msg_signing_key
, RealWorld.msg_to_this_user
, RealWorld.msg_destination_user
, RealWorld.cipher_signing_key
, RealWorld.honest_keyb
, RealWorld.cipher_nonce
, add_key_perm.
Ltac assert_lkp ks k tac :=
let ev' := fresh "ev"
in evar (ev' : option bool);
let ev := eval unfold ev' in ev'
in (clear ev'
; match ks with
| ?ks1 $k++ ?ks2 => assert (ks $? k = ev) by tac
| _ => assert (ks $? k = ev) by tac
end).
Ltac bldLkup ks k tac :=
match goal with
| [ H : ks $? k = ?ans |- _ ] => idtac (* idtac "done with: " ks *)
| _ =>
match ks with
| ?ks1 $k++ ?ks2 => (* idtac "splitting: " ks1 " and " ks2; *) bldLkup ks1 k tac; bldLkup ks2 k tac
| _ => idtac (* "will build: " ks *)
end; assert_lkp ks k tac
end.
Ltac prove_lookup :=
solve [
repeat
match goal with
| [ |- None = _ ] => reflexivity
| [ |- Some _ = _ ] => reflexivity
| [ |- $0 $? _ = _ ] => rewrite lookup_empty_none
| [ |- ?ks $+ (?k1,_) $? ?k2 = _ ] =>
(rewrite add_eq_o by trivial)
|| (rewrite add_neq_o by auto 2)
|| fail 2
| [ |- ?m $? _ = _ ] => progress (unfold m)
| [ H1 : ?ks1 $? ?kid = Some _
, H2 : ?ks2 $? ?kid = Some _ |- ?ks1 $k++ ?ks2 $? ?kid = _ ]
=> rewrite (merge_perms_chooses_greatest _ _ H1 H2) by trivial; unfold greatest_permission; simpl
| [ H1 : ?ks1 $? ?kid = Some _
, H2 : ?ks2 $? ?kid = None |- ?ks1 $k++ ?ks2 $? ?kid = _ ]
=> rewrite (merge_perms_adds_ks1 _ _ _ H1 H2) by trivial
| [ H1 : ?ks1 $? ?kid = None
, H2 : ?ks2 $? ?kid = Some _ |- ?ks1 $k++ ?ks2 $? ?kid = _ ]
=> rewrite (merge_perms_adds_ks2 _ _ _ H1 H2) by trivial
| [ H1 : ?ks1 $? ?kid = None
, H2 : ?ks2 $? ?kid = None |- ?ks1 $k++ ?ks2 $? ?kid = _ ]
=> rewrite (merge_perms_adds_no_new_perms _ _ _ H1 H2) by trivial
| [ H : ?ks1 $? ?kid = _ |- ?ks1 $k++ ?ks2 $? ?kid = _ ] =>
assert_lkp ks2 kid prove_lookup
| [ H : ?ks2 $? ?kid = _ |- ?ks1 $k++ ?ks2 $? ?kid = _ ] =>
assert_lkp ks1 kid prove_lookup
| [ |- ?ks1 $k++ ?ks2 $? ?kid = _ ] =>
assert_lkp ks1 kid prove_lookup
; assert_lkp ks2 kid prove_lookup
end
].
Ltac solve_merges :=
repeat
match goal with
| [ |- context [true || _] ] => rewrite orb_true_l
| [ |- context [_ || true] ] => rewrite orb_true_r
| [ |- context [ _ $k++ $0 ] ] => rewrite merge_perms_right_identity
| [ |- context [ $0 $k++ _ ] ] => rewrite merge_perms_left_identity
| [ RW : ?ks $? ?k = _ |- context [ ?ks $? ?k ] ] => rewrite RW
| [ |- context [ ?ks $? ?k ] ] => (* idtac "building: " ks; *) bldLkup ks k prove_lookup
end; trivial.
Lemma reduce_merge_perms_r :
forall perms1 perms2 kid p2,
perms1 $? kid = None
-> perms1 $k++ (perms2 $+ (kid,p2)) = perms1 $+ (kid,p2) $k++ (perms2 $- kid).
Proof.
intros.
eapply map_eq_Equal; unfold Equal; intros.
cases (perms1 $? y);
cases (perms2 $? y);
destruct (kid ==n y); subst;
clean_map_lookups.
- erewrite !merge_perms_chooses_greatest; try reflexivity; clean_map_lookups; eauto.
- erewrite merge_perms_adds_ks1 with (ks1 := perms1) (ks2 := perms2 $+ (kid, p2)); eauto.
erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (kid, p2)) (ks2 := perms2 $- kid); eauto.
- erewrite merge_perms_adds_ks2 with (ks1 := perms1) (ks2 := perms2 $+ (y, p2)); eauto.
erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (y, p2)) (ks2 := perms2 $- y); eauto.
- erewrite merge_perms_adds_ks2 with (ks1 := perms1) (ks2 := perms2 $+ (kid, p2) ); eauto.
erewrite merge_perms_adds_ks2 with (ks1 := perms1 $+ (kid, p2)) (ks2 := perms2 $- kid); eauto.
- erewrite merge_perms_adds_ks2 with (ks1 := perms1); eauto; clean_map_lookups; try reflexivity.
erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (y, p2)) (ks2 := perms2 $- y); eauto.
- rewrite !merge_perms_adds_no_new_perms; eauto.
Qed.
Lemma reduce_merge_perms_both :
forall perms1 perms2 kid p1 p2,
perms1 $? kid = Some p1
-> perms1 $k++ (perms2 $+ (kid,p2)) = perms1 $+ (kid,greatest_permission p1 p2) $k++ (perms2 $- kid).
Proof.
intros.
eapply map_eq_Equal; unfold Equal; intros.
cases (perms1 $? y);
cases (perms2 $? y);
destruct (kid ==n y); subst;
clean_map_lookups.
- erewrite merge_perms_chooses_greatest; eauto; clean_map_lookups; try reflexivity.
erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (y, greatest_permission b p2)) (ks2 := perms2 $- y); eauto.
- erewrite !merge_perms_chooses_greatest; try reflexivity; clean_map_lookups; trivial.
- erewrite merge_perms_chooses_greatest; eauto; clean_map_lookups; try reflexivity.
erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (y, greatest_permission b p2)) (ks2 := perms2 $- y); eauto.
- erewrite merge_perms_adds_ks1 with (ks1 := perms1) (ks2 := perms2 $+ (kid, p2)); eauto.
erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (kid, greatest_permission p1 p2)) (ks2 := perms2 $- kid); eauto.
- erewrite merge_perms_adds_ks2 with (ks1 := perms1) (ks2 := perms2 $+ (kid, p2)); eauto.
erewrite merge_perms_adds_ks2 with (ks1 := perms1 $+ (kid, greatest_permission p1 p2)) (ks2 := perms2 $- kid); eauto.
- rewrite !merge_perms_adds_no_new_perms; eauto.
Qed.
Ltac xx := clean_map_lookups;
try match goal with
| [ |- $0 $? _ = _ ] => rewrite lookup_empty_none
end;
eauto.
Ltac find_merge_rewrite ks1 ks2 :=
match ks1 with
| ?ks1' $k++ ?ks2' =>
find_merge_rewrite ks1' ks2'
| _ => match ks2 with
| ?ks $+ (?k,?p) =>
assert_lkp ks1 k xx
; match goal with
| [ H : ks1 $? k = ?opt |- _ ] =>
match opt with
| Some ?p' =>
rewrite reduce_merge_perms_both with (perms1 := ks1) (perms2 := ks) (kid := k) (p1 := p') (p2 := p)
| None =>
rewrite reduce_merge_perms_r with (perms1 := ks1) (perms2 := ks) (kid := k) (p2 := p)
end
end
end
end.
Lemma remove_empty :
forall k V, (@empty V) $- k = $0.
Proof.
intros.
eapply map_eq_Equal; unfold Equal; intros; eauto.
Qed.
Ltac elim_removes1 :=
(rewrite !map_add_remove_eq by trivial)
|| (rewrite !map_add_remove_neq by eauto)
|| (rewrite !remove_empty).
Ltac elim_removes := repeat elim_removes.
Ltac reduce_merges :=
repeat
match goal with
| [ |- context [true || _] ] => rewrite orb_true_l
| [ |- context [_ || true] ] => rewrite orb_true_r
| [ |- context [ _ $k++ $0 ] ] => rewrite merge_perms_right_identity
| [ |- context [ $0 $k++ _ ] ] => rewrite merge_perms_left_identity
| [ |- context [ _ $- _ ]] => elim_removes1
| [ |- context [ ?ks1 $k++ ?ks2 ]] =>
find_merge_rewrite ks1 ks2
| [ RW : ?ks $? ?k = _ |- context [ ?ks $? ?k ] ] => rewrite RW
end; trivial.
Ltac has_key ks k :=
match ks with
| context [ _ $+ (k,_) ] => idtac
end.
Ltac solve_merges1 :=
match goal with
| [ H : Some _ = Some _ |- _ ] => injection H; subst
| [ H : Some _ = None |- _ ] => discriminate H
| [ H : None = Some _ |- _ ] => discriminate H
| [ H : findKeysMessage _ $? _ = _ |- _ ] => progress (simpl in H)
| [ H : ?ks $? ?k = _ |- _ ] =>
progress (
repeat (
(rewrite add_eq_o in H by trivial)
|| (rewrite add_neq_o in H by congruence)
|| (rewrite lookup_empty_none in H by congruence)
)
)
| [ H : _ $+ (?k1,_) $? ?k2 = _ |- _ ] =>
destruct (k1 ==n k2); subst
| [ H : _ $k++ _ $? _ = None |- _ ] =>
apply merge_perms_no_disappear_perms in H
; destruct H
| [ H : _ $k++ _ $? ?kid = Some _ |- _ ] =>
apply merge_perms_split in H
; destruct H
| [ |- context [ ?kss1 $k++ ?kss2 $? ?ky ] ] =>
has_key kss1 ky; has_key kss2 ky
; erewrite merge_perms_chooses_greatest
with (ks1 := kss1) (ks2 := kss2) (k := ky) (k' := ky)
| [ |- context [ ?kss1 $k++ ?kss2 $? ?ky ] ] =>
has_key kss1 ky
; erewrite merge_perms_adds_ks1
with (ks1 := kss1) (ks2 := kss2) (k := ky)
; try reflexivity
| [ |- context [ ?kss1 $k++ ?kss2 $? ?ky ] ] =>
has_key kss2 ky
; erewrite merge_perms_adds_ks2
with (ks1 := kss1) (ks2 := kss2) (k := ky)
; try reflexivity
| [ |- context [ ?kss1 $k++ ?kss2 $? ?ky ] ] =>
erewrite merge_perms_adds_no_new_perms
with (ks1 := kss1) (ks2 := kss2) (k := ky)
| [ |- ?ks $? ?k = _ ] =>
progress (
repeat (
(rewrite add_eq_o by trivial)
|| (rewrite add_neq_o by congruence)
|| (rewrite lookup_empty_none by congruence)
)
)
| [ |- _ = _ ] => (progress simpl) || reflexivity
end.
Ltac solve_honest_actions_safe1 :=
solve_merges1 ||
match goal with
| [ H : _ = {| RealWorld.users := _;
RealWorld.adversary := _;
RealWorld.all_ciphers := _;
RealWorld.all_keys := _ |} |- _ ] => invert H
| [ |- honest_cmds_safe _ ] => unfold honest_cmds_safe; intros; simpl in *
| [ |- next_cmd_safe _ _ _ _ _ _ ] => unfold next_cmd_safe; intros
| [ H : _ $+ (?id1,_) $? ?id2 = _ |- _ ] => is_var id2; destruct (id1 ==n id2); subst; clean_map_lookups
| [ H : nextAction _ _ |- _ ] => invert H
| [ H : mkKeys _ $? _ = _ |- _ ] => unfold mkKeys in H; simpl in H
| [ |- context [ RealWorld.findUserKeys ?usrs ] ] => canonicalize_map usrs
| [ |- context [ RealWorld.findUserKeys _ ] ] =>
rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty by eauto
| [ H : RealWorld.findKeysMessage _ $? _ = _ |- _ ] => progress (simpl in H)
| [ |- (_ -> _) ] => intros
| [ |- context [ _ $+ (_,_) $? _ ] ] => progress clean_map_lookups
| [ |- RealWorld.msg_pattern_safe _ _ ] => econstructor
| [ |- RealWorld.honest_key _ _ ] => econstructor
(* | [ |- context [_ $k++ _ ] ] => progress reduce_merges *)
(* | [ |- context [_ $k++ _ $? _ ] ] => progress solve_merges *)
| [ |- context [ ?m $? _ ] ] => unfold m
| [ |- Forall _ _ ] => econstructor
| [ |- exists x y, (_ /\ _)] => (do 2 eexists); repeat simple apply conj; eauto 2
| [ |- _ /\ _ ] => repeat simple apply conj
| [ |- ~ List.In _ _ ] => progress simpl
| [ |- ~ (_ \/ _) ] => unfold not; intros; split_ors; subst; try contradiction
| [ H : (_,_) = (_,_) |- _ ] => invert H
end.
Ltac solve_honest_actions_safe :=
repeat (solve_honest_actions_safe1 || (progress simplify_terms) (* ; simpl; cbn *)).
Ltac solve_labels_align :=
(do 3 eexists); repeat (simple apply conj);
[ solve [ eauto 3 ]
| indexedIdealStep; simpl
| subst; repeat solve_action_matches1; clean_map_lookups; ChMaps.ChMap.clean_map_lookups
]; eauto 3; simpl; eauto.
End SimulationAutomation.
Import SimulationAutomation Sets.
Module Foo <: EMPTY.
End Foo.
Module Import SN := SetNotations(Foo).
Ltac univ_equality1 :=
match goal with
| [ |- _ = _ ] => reflexivity
| [ |- _ /\ _ ] => repeat simple apply conj
| [ |- (_,_) = (_,_) ] => rewrite pair_equal_spec
| [ |- {| RealWorld.users := _ |} = _ ] => eapply real_univ_eq_fields_eq
| [ |- {| IdealWorld.users := _ |} = _ ] => eapply ideal_univ_eq_fields_eq
end
|| ( progress m_equal )
|| ( progress ChMaps.m_equal ).
Ltac univ_equality := progress (repeat univ_equality1).
Ltac sets0 := Sets.sets ltac:(simpl in *
; intuition (subst; auto; try congruence; try univ_equality; try lia)).
Ltac sets' :=
propositional;
try match goal with
| [ |- @eq (?T -> Prop) _ _ ] =>
change (T -> Prop) with (set T)
end;
try match goal with
| [ |- @eq (set _) _ _ ] =>
let x := fresh "x" in
apply sets_equal; intro x;
repeat match goal with
| [ H : @eq (set _) _ _ |- _ ] => apply (f_equal (fun f => f x)) in H;
apply eq_iff in H
end
end; sets0;
try match goal with
| [ H : @eq (set ?T) _ _, x : ?T |- _ ] =>
repeat match goal with
| [ H : @eq (set T) _ _ |- _ ] => apply (f_equal (fun f => f x)) in H;
apply eq_iff in H
end;
solve [ sets0 ]
end.
Tactic Notation "sets" := sets'.
Module SetLemmas.
Lemma setminus_empty_subtr : forall {A} (s : set A),
s \setminus {} = s.
Proof. sets. Qed.
Lemma setminus_empty_minu : forall {A} (s : set A),
{} \setminus s = {}.
Proof. sets. Qed.
Lemma setminus_self : forall {A} (s : set A),
s \setminus s = {}.
Proof. sets. Qed.
Lemma setminus_other : forall {A} (s1 s2 : set A),
s1 \cap s2 = {} -> s1 \setminus s2 = s1.
Proof. sets. Qed.
Lemma setminus_distr_subtr : forall {A} (s1 s2 s3 : set A),
(s1 \cup s2) \setminus s3 = (s1 \setminus s3) \cup (s2 \setminus s3).
Proof. sets. Qed.
Lemma setminus_distr_minu : forall {A} (s1 s2 s3 : set A),
s1 \setminus (s2 \cup s3) = (s1 \setminus s2) \cap (s1 \setminus s3).
Proof. sets. Qed.
Lemma union_self : forall {A} (s : set A),
s \cup s = s.
Proof. sets. Qed.
Lemma union_self_thru : forall {A} (s1 s2 : set A), s1 \cup (s1 \cup s2) = s1 \cup s2.
Proof. sets. Qed.
Lemma union_empty_r : forall {A} (s : set A),
s \cup {} = s.
Proof. sets. Qed.
Lemma union_empty_l : forall {A} (s : set A),
{} \cup s = s.
Proof. sets. Qed.
Lemma intersect_self : forall {A} (s : set A),
s \cap s = s.
Proof. sets. Qed.
Lemma intersect_empty_r : forall {A} (s : set A),
s \cap {} = {}.
Proof. sets. Qed.
Lemma intersect_empty_l : forall {A} (s : set A),
{} \cap s = {}.
Proof. sets. Qed.
End SetLemmas.
Module Tacs.
Import SetLemmas.
Ltac simpl_sets1 disj_tac :=
match goal with
| [|- context[?s' \cup ?s']] =>
rewrite union_self
with (s := s')
| [|- context[?s1' \cup (?s1' \cup ?s2')]] =>
rewrite union_self_thru
with (s1 := s1') (s2 := s2')
| [|- context[?s' \cup {}]] =>
rewrite union_empty_r
with (s := s')
| [|- context[{} \cup ?s']] =>
rewrite union_empty_l
with (s := s')
| [|- context[?s' \cap ?s']] =>
rewrite intersect_self
with (s := s')
| [|- context[?s' \cap {}]] =>
rewrite intersect_empty_r
with (s := s')
| [|- context[{} \cap ?s']] =>
rewrite intersect_empty_l
with (s := s')
| [|- context[?s' \setminus ?s']] =>
rewrite setminus_self
with (s := s')
| [|- context[?s' \setminus {}]] =>
rewrite setminus_empty_subtr
with (s := s')
| [|- context[{} \setminus ?s']] =>
rewrite setminus_empty_minu
with (s := s')
| [|- context[(?s1' \cup ?s2') \setminus ?s3']] =>
rewrite setminus_distr_subtr
with (s1 := s1') (s2 := s2') (s3 := s3')
| [|- context[?s1' \setminus (?s2' \cup ?s3')]] =>
rewrite setminus_distr_minu
with (s1 := s1') (s2 := s2') (s3 := s3')
| [|- context[?s1' \setminus ?s2']] =>
rewrite setminus_other
with (s1 := s1') (s2 := s2') by disj_tac
end.
Ltac sets_invert :=
repeat match goal with
| [H : (_ \cup _) _ |- _] => invert H
| [H : (_ \cap _) _ |- _] => invert H
| [H : [_ | _] _ |- _] => invert H
| [H : (_ \setminus _) _ |- _] => invert H
| [H : _ \in _ |- _] => invert H
| [H : (complement _) _ |- _] => invert H
| [H : { } _ |- _] => invert H
| [H : { _ } _ |- _] => invert H
| [H : _ \/ False |- _ ] => destruct H; [ | contradiction]
end.
Ltac case_lookup H :=
match type of H with
| ?m $? ?k = Some ?v =>
let t := type of v in
repeat match m with
| context[add ?k' ?v' _ ] =>
let t' := type of v'
in unify t t'
; match goal with
| [e : k = k' |- _] => fail 2
| [n : k <> k' |- _] => fail 2
| _ => destruct (k ==n k')
end
end
; subst
; simpl in *
; clean_map_lookups
; simpl in *
end.
Lemma map_sym : forall {v} (m : NatMap.t v) k1 k2 v1 v2,
k1 <> k2
-> m $+ (k1, v1) $+ (k2, v2) = m $+ (k2, v2) $+ (k1, v1).
Proof. intros; maps_equal. Qed.
Ltac reorder_usrs n :=
repeat match n with
| context[add ?a ?va (add ?b ?vb ?rest)] =>
match eval cbv in (Nat.leb a b) with
| true =>
rewrite map_sym
with (m := rest) (k1 := b) (k2 := a) (v1 := vb) (v2 := va)
by auto
end
end.
Tactic Notation "simpl_sets" := repeat (simpl_sets1 ltac:(shelve)).
Tactic Notation "simpl_sets" tactic(disj_tac) := repeat (simpl_sets1 ltac:(disj_tac)).
Tactic Notation "ifnot" tactic(t) "at" int_or_var(lvl) := tryif t then fail lvl else idtac.
Tactic Notation "ifnot" tactic(t) := ifnot t at 0.
Tactic Notation "concrete" constr(x) "at" int_or_var(lvl) :=
(ifnot (is_var x) at lvl); (ifnot (is_evar x) at lvl).
Tactic Notation "concrete" constr(x) := concrete x at 0.
Tactic Notation "concrete" "iuniv" constr(u) :=
match u with
| {| IdealWorld.channel_vector := ?cv
; IdealWorld.users := ?usrs |} =>
concrete cv; concrete usrs
end.
Tactic Notation "concrete" "iproc" constr(p) :=
match p with
| (IdealWorld.protocol ?p) => concrete p at 1
| _ => concrete p at 1
end.
Tactic Notation "canonicalize" "rusers" :=
repeat match goal with
| [|- context[{| RealWorld.users := ?usrs
; RealWorld.adversary := _
; RealWorld.all_ciphers := _
; RealWorld.all_keys := _ |}]] =>
progress canonicalize_concrete_map usrs
end.
Tactic Notation "canonicalize" "iusers" :=
repeat match goal with
| [|- context[{| IdealWorld.channel_vector := _
; IdealWorld.users := ?usrs |}]] =>
progress canonicalize_concrete_map usrs
end.
Tactic Notation "canonicalize" "users" :=
canonicalize rusers; canonicalize iusers.
End Tacs.
Import Tacs.
Module Gen.
Import
SetLemmas.
#[export] Hint Unfold oneStepClosure oneStepClosure_current oneStepClosure_new : osc.
Lemma oneStepClosure_grow : forall state (sys : trsys state) (inv1 inv2 : state -> Prop),
(forall st st', inv1 st -> sys.(Step) st st' -> inv2 st')
-> oneStepClosure sys inv1 (inv1 \cup inv2).
Proof. sets; repeat autounfold with osc in *; propositional; eauto. Qed.
Lemma msc_step_alt : forall {state} (sys : trsys state) wl wl' inv inv',
oneStepClosure_new sys wl wl'
-> wl' \cap (wl \cup inv) = { }
-> multiStepClosure sys ((inv \cup wl) \cup wl') wl' inv'
-> multiStepClosure sys (inv \cup wl) wl inv'.
Proof.
Ltac uf := repeat autounfold with osc in *.
intros.
apply MscStep with (inv'0 := (wl \cup wl')).
- uf; sets; firstorder.
- replace ((inv \cup wl) \cup (wl \cup wl'))
with (inv \cup wl \cup wl') by sets.
replace (((wl \cup wl') \setminus (inv \cup wl)))
with wl' by sets.
assumption.
Qed.
Lemma in_empty_map_contra : (forall {t} x, Map.In (elt := t) x $0 -> False).
Proof. propositional. invert H. invert H0. Qed.
Lemma incl_empty_empty : (forall {t}, @incl t [] []).
Proof. cbv; auto. Qed.
#[export] Hint Resolve
incl_empty_empty : core.
Ltac concrete_isteps :=
match goal with
| [H : indexedIdealStep _ _ _ _ |- _ ] =>
invert H
| [H : (indexedIdealStep _ Silent)^* ?u _ |- _] =>
concrete iuniv u; invert H
| [H : istepSilent^* ?u _ |- _] =>
concrete iuniv u; invert H
| [H : istepSilent ?u _ |- _] =>
concrete iuniv u; invert H
| [H : IdealWorld.lstep_universe ?u _ _ |- _] =>
concrete iuniv u; invert H
| [H : IdealWorld.lstep_user _ _ (_, idealServer 0 _ _, _) _ |- _] =>
rewrite idealserver_done in H by reflexivity
| [H : IdealWorld.lstep_user _ _ (_, idealServer _ _ _, _) _ |- _] =>
erewrite unroll_idealserver_step in H by reflexivity
| [H : IdealWorld.lstep_user _ _ (_, ?p, _) _ |- _] =>
concrete iproc p; invert H
end.
Ltac simplify :=
repeat (unifyTails);
repeat match goal with
| [ H : True |- _ ] => clear H
end;
repeat progress (simpl in *; intros; try autorewrite with core in *);
repeat (normalize_set || doSubtract).
Ltac infer_istep :=
match goal with
| [H : IdealWorld.lstep_user _ _ (_, ?u.(IdealWorld.protocol), _) _,
L : ?m $? ?u_id = Some ?u |- _] =>
case_lookup L
end.
Ltac istep := repeat ((repeat concrete_isteps); try infer_istep).
Ltac incorp :=
let rec preconditions acc :=
(match goal with
| [H : ?P |- _] =>
match type of P with
| Prop =>
match eval hnf in acc with
| context[P] => fail 1
| _ =>
let acc' := eval hnf in (P /\ acc)
in preconditions acc'
end
end
| _ => acc
end)
in let rec existentialize p :=
(match goal with
| [x : ?A |- _] =>
match type of A with
| Prop => fail 1
| _ =>
match A with
| ((RealWorld.universe _ _) * (IdealWorld.universe _) * bool)%type =>
fail 2
| _ =>
match p with
| context[x] =>
match eval pattern x in p with
| ?g _ =>
let p' := (eval hnf in (exists y : A, g y))
in existentialize p'
end
end
end
end
| _ => p
end)
in let conds := (preconditions True) in
match goal with
| [|- ?i ?v] =>
is_evar i
; let lp := constr:(exists x , conds /\ x = v) in
let p := fresh "p" in
let p' := fresh "p'" in
let x := fresh "x" in
assert (p : lp) by (eexists; intuition eauto)
; destruct p as [x p']
; let lp' := type of p'
in clear p'
; let lp'' := existentialize lp'
in match eval pattern x in lp'' with
| ?f _ =>
clear x
; let scomp := (eval simpl in [e | (f e)])
in instantiate (1 := (scomp \cup _))
end
end.
Ltac solve_returns_align1 :=
match goal with
| [ H : users _ $? _ = Some _ |- _ ] => progress (simpl in H)
| [ H1 : _ $? ?u = Some ?ud, H2 : protocol ?ud = Return _ |- _ ] =>
progress (
repeat ( (rewrite add_eq_o in H1 by trivial)
|| (rewrite add_neq_o in H1 by congruence)
|| (rewrite lookup_empty_none in H1; discriminate H1)
)
)
| [ H1 : _ $+ (?u1,_) $? ?u2 = Some ?ud, H2 : protocol ?ud = Return _ |- _ ] =>
destruct (u1 ==n u2); subst
| [ H1 : Some _ = Some ?ud, H2 : protocol ?ud = Return _ |- _ ] =>
injection H1; subst
| [ H : _ = Return _ |- _ ] =>
discriminate H
end.
Ltac idealUnivSilentStep uid :=
eapply IdealWorld.LStepUser with (u_id := uid)
; simpl
; [ solve [ clean_map_lookups; trivial ]
| solve [ idealUserSilentStep ]
].
Ltac step_ideal1 uid :=
idtac "stepping " uid
; eapply TrcFront
; [ idealUnivSilentStep uid |].
Ltac multistep_ideal usrs :=
simpl_ideal_users_context;
match usrs with
| ?us $+ (?uid,_) =>
idtac "multi stepping " uid
; (repeat step_ideal1 uid)
; multistep_ideal us
| _ => eapply TrcRefl
end.
Ltac run_ideal_silent_steps_to_end :=
simpl_ideal_users_context;
match goal with
| [ |- istepSilent ^* {| IdealWorld.users := ?usrs |} ?U ] =>
is_evar U
; multistep_ideal usrs
end.
Ltac solve_real_step_stuff1 :=
equality1
|| (progress subst)
|| solve_merges1
|| match goal with
| [ |- RealWorld.keys_mine _ _ ] =>
simpl in *; hnf
| [ |- ?m $? next_key ?m = None ] =>
apply Maps.next_key_not_in
; trivial
| [ |- ~ Map.In (next_key ?m) ?m ] =>
rewrite not_find_in_iff
; apply Maps.next_key_not_in
; trivial
| [ H : _ $+ (?k1,_) $? ?kid = Some _ |- context [ ?kid ] ] =>
is_var kid
; destruct (k1 ==n kid); subst; clean_map_lookups
| [ |- context [ $0 $? _ ]] =>
rewrite lookup_empty_none
(* | [ |- _ $? _ = _ ] => *)
| [ |- context [ _ $? _ = _ ] ] =>
progress clean_map_lookups
| [ |- _ -> _ ] => intros
| [ |- _ ] => ( progress simpl ) || ( progress hnf )
end.
Ltac solve_indexedRealStep :=
repeat (match goal with [ |- exists _ , _ ] => eexists end)
; econstructor; [
solve [ simpl; clean_map_lookups; trivial ]
| autounfold; unfold RealWorld.build_data_step; simpl;
repeat ( match goal with
| [ |- RealWorld.step_user _ _ _ _ ] => solve [ eapply RealWorld.StepBindProceed; eauto ]
| [ |- RealWorld.step_user _ _ _ _ ] => eapply RealWorld.StepBindRecur; eauto
| [ |- RealWorld.step_user _ _ (_,_,?cs,?gks,_,_,_,_,_,_,?cmd) _ ] =>
match cmd with
| RealWorld.SignEncrypt _ _ _ _ =>
eapply RealWorld.StepEncrypt with (c_id := next_key cs)
| RealWorld.Sign _ _ _ =>
eapply RealWorld.StepSign with (c_id := next_key cs)
| RealWorld.GenerateKey _ _ =>
eapply RealWorld.StepGenerateKey with (k_id := next_key gks)
| _ => econstructor
end
end
)
; trivial (* take a first pass to get the simple stuff *)
; repeat (solve_real_step_stuff1; trivial)
; eauto
| reflexivity ].
Ltac find_indexed_real_step usrs uid :=
match usrs with
| ?us $+ (?u,_) =>
(unify uid u; solve [ solve_indexedRealStep ])
|| find_indexed_real_step us uid
| $0 =>
fail 1
end.
(* note the automation here creates a bunch of extra existentials while
* doint the search for available steps. This creates several nats
* that need to be resolved at the end of proofs that use it.
* Should look at fixing this. *)
Ltac find_step_or_solve :=
simpl in *;
match goal with
| [ H1 : forall _ _ _, indexedRealStep _ _ ?ru _ -> False
, H2 : ?usrs $? _ = Some ?ur
, H3 : RealWorld.protocol ?ur = RealWorld.Return _ |- _ ] =>
( assert (exists uid lbl ru', indexedRealStep uid lbl ru ru')
by (eexists ?[uid]; (do 2 eexists); find_indexed_real_step usrs ?uid)
; split_ex; exfalso; eauto
)
|| ( repeat solve_returns_align1
; ( (do 3 eexists); simpl in *; (repeat equality1)
; subst
; repeat simple apply conj
; [ solve [ run_ideal_silent_steps_to_end ]
| solve [ simpl; clean_map_lookups; trivial ]
| reflexivity
| reflexivity
]
))
end.
Ltac invert_commutes :=
match goal with
| [ H : commutes (RealWorld.Recv _) _ |- _ ] => invert H
| [ H : commutes (RealWorld.Send _ _) _ |- _ ] => invert H
| [ H : commutes _ _ |- _ ] => fail 2
end.
Ltac non_commuter uid :=
exists uid; eexists; repeat simple apply conj; [
congruence
| solve [ autounfold; simpl; clean_map_lookups; trivial ]
| solve [ intros; simpl; trivial] ].
Ltac non_commuter_all uids :=
match uids with
| [] => fail 2
| (?uid :: ?uids') => (non_commuter uid) || (non_commuter_all uids')
end.
Ltac non_commuters := non_commuter_all [0;1;2;3;4;5].
Ltac discharge_nextStep2 :=
repeat
match goal with
| [ H : (forall _ _, ~ indexedRealStep ?uid _ ?ru _)
\/ (exists _ _, ?uid <> _ /\ _ $? _ = Some _ /\ (forall _, ?sums $? _ = Some _ -> commutes ?proto _ -> False))
|- _ ] => split_ex; exfalso; destruct H
| [ H : (forall _ _, ~ indexedRealStep ?uid _ ?ru _), ARG : indexedRealStep ?uid _ ?ru _ |- _ ] =>
eapply H in ARG; contradiction
| [ H : summarize_univ ?ru ?sums,
ARG : (forall _, ?sums $? ?uid = Some _ -> commutes _ _),
USR : _ $? ?uid = Some _
|- _ ] =>
specialize (H _ _ {| sending_to := { } |} USR); split_ex
| [ H : ?sums $? ?uid = Some _,
COMM : (forall _, ?sums $? ?uid = Some _ -> commutes _ _)
|- _ ] =>
specialize (COMM _ H); simpl in COMM; contradiction
end.
Lemma upper_users_cant_step_rewrite :
forall A B (U : RealWorld.universe A B) uid,
(forall uid' ud' U', U.(RealWorld.users) $? uid' = Some ud' -> uid' > uid -> ~ indexedRealStep uid' Silent U U')
-> (forall uid' U', uid' > uid -> ~ indexedRealStep uid' Silent U U').
Proof.
intros * H * INEQ.
unfold not; intros IRS.
invert IRS; eauto.
eapply H; eauto.
Qed.
Lemma indexedModelStep_user_step :
forall t__hon t__adv uid ru ru' iu iu' b b',
@indexedModelStep t__hon t__adv uid (ru,iu,b) (ru',iu',b')
-> (indexedRealStep uid Silent ru ru' /\ iu = iu' /\ b = b')
\/ (exists a, indexedRealStep uid (Action a) ru ru')
.
Proof.
induct 1; eauto 8.
Qed.
Lemma sstep_inv_silent :
forall A B (U U' : RealWorld.universe A B) uid U__i b st',
indexedRealStep uid Silent U U'
-> (forall uid' U', uid' > uid -> ~ indexedRealStep uid' Silent U U')
-> stepSS (U,U__i,b) st'
-> exists U__r,
indexedModelStep uid (U,U__i,b) (U__r,U__i,b)
/\ indexedRealStep uid Silent U U__r
/\ st' = (U__r,U__i,b).
Proof.
intros.
invert H1; repeat equality1.
destruct (u_id ==n uid); subst.
- invert H2; clear_mislabeled_steps; clean_map_lookups.
invert H5; clear_mislabeled_steps.
eexists; eauto 8.
- invert H2.
+ invert H5; try solve [ clear_mislabeled_steps ].
apply not_eq in n; split_ors.
* assert (uid > u_id) as GT by lia.
specialize (H4 _ U' GT); contradiction.
* assert (u_id > uid) as GT by lia.
specialize (H0 _ ru' GT); contradiction.
+ eapply H3 in H; contradiction.
Qed.
Lemma sstep_inv_labeled :
forall A B st st' ru,
(forall uid U', ~ @indexedRealStep A B uid Silent ru U')
-> @stepSS A B st st'
-> labels_align st
-> forall ru' iu iu' b b',
st = (ru,iu,b)
-> st' = (ru',iu',b')
-> b = b'
/\ (exists uid iu0 ra ia,
indexedRealStep uid (Action ra) ru ru'
/\ (indexedIdealStep uid Silent) ^* iu iu0
/\ indexedIdealStep uid (Action ia) iu0 iu'
/\ action_matches (RealWorld.all_ciphers ru) (RealWorld.all_keys ru) (uid,ra) ia).
Proof.
intros; subst.
invert H0; clear_mislabeled_steps.
repeat equality1.
invert H2.
specialize (H u_id U'); simpl in *; contradiction.
invert H5; try contradiction; eauto 12.
clear_mislabeled_steps.
Qed.
Ltac rstep :=
repeat (autounfold
; equality1
|| (progress ( simpl in * ))
|| discriminate
|| match goal with
| [H : action_matches _ _ _ _ |- _] =>
invert H
| [ H : forall _ _ _, _ -> _ -> _ -> _ <-> _ |- _ ] => clear H
| [ H : forall _ _ _ _, _ -> _ -> _ -> _ -> _ <-> _ |- _ ] => clear H
| [ H : (forall _ _ _, indexedRealStep _ _ ?ru _ -> exists _ _ _, (indexedIdealStep _ _) ^* ?iu _ /\ _) |- _ ] =>
clear H
| [ H : summarize_univ _ _ |- _ ] => clear H
| [H : indexedRealStep _ _ _ _ |- _ ] =>
invert H
| [H : RealWorld.step_universe _ ?u _ _ |- _] =>
concrete u; churn
| [H : RealWorld.step_user _ None _ _ |- _] =>
invert H
| [H : RealWorld.step_user _ _ ?u _ |- _] =>
concrete u; churn
end).
Ltac prove_gt_pred :=
intros
; simpl in *
; repeat
match goal with
| [ H : context [ _ $+ (_,_) $- _ ] |- _ ] =>
repeat (
(rewrite map_add_remove_neq in H by congruence)
|| (rewrite map_add_remove_eq in H by trivial)
|| (rewrite remove_empty in H)
)
| [ H : _ $+ (?uid,_) $? ?uid' = Some _ |- _ ] =>
destruct (uid ==n uid'); subst; clean_map_lookups; try lia
| [ |- ~ indexedRealStep _ _ _ _ ] => unfold not; intros; rstep
end.
Ltac assert_gt_pred U uid :=
let P := fresh "P"
in assert (forall uid' ud' U', U.(RealWorld.users) $? uid' = Some ud'
-> uid' > uid
-> ~ indexedRealStep uid' Silent U U') as P by prove_gt_pred
; pose proof (upper_users_cant_step_rewrite P); clear P
.
Ltac assert_no_silents U :=
let P := fresh "P"
in assert (forall uid U', ~ indexedRealStep uid Silent U U') as P by prove_gt_pred
.
Ltac find_silent U us :=
let MAX := fresh "MEQ"
in remember (O.max_elt us) eqn:MAX
; unfold O.max_elt in MAX
; simpl in MAX
; match type of MAX with
| _ = Some (?uid,?u) =>
( ( assert (exists U', indexedRealStep uid Silent U U') by solve_indexedRealStep
; assert_gt_pred U uid)
|| find_silent U (us $- uid)
) || assert_no_silents U
end
; subst; split_ex
.
Ltac inv_stepSS1 :=
match goal with
| [ H : stepSS (?U,_,_) _ |- _ ] =>
match U with
| {| RealWorld.users := ?usrs |} =>
find_silent U usrs
end
| [ STEP : stepSS (?U,_,_) _
, IRS : indexedRealStep ?uid Silent ?U _
, P : (forall _ _, _ > ?uid -> _)
|- _ ] =>
pose proof (sstep_inv_silent IRS P STEP)
; clear STEP IRS P
; split_ex
; subst
| [ STEP : stepSS (?ru,?iu,?b) _
, P : (forall _ _, ~ indexedRealStep _ Silent _ _)
|- _ ] =>
progress ( unfold not in P )
| [ STEP : stepSS (?ru,?iu,?b) (_,_,_)
, P : (forall _ _, indexedRealStep _ Silent _ _ -> False)
|- _ ] =>
concrete ru
; match goal with
| [ LA : labels_align (?ru,?iu,?b) |- _ ] =>
pose proof (sstep_inv_labeled P STEP LA eq_refl eq_refl )
; split_ex; subst
; clear STEP P LA
| _ =>
idtac "proving alignment 4"
; assert (labels_align (ru,iu,b)) by ((repeat prove_alignment1); eauto)
end
| [ STEP : stepSS ?st ?st'
, P : (forall _ _, indexedRealStep _ Silent _ _ -> False)
|- _ ] =>
match st with
| (_,_,_) => idtac
| _ => destruct st as [[?ru ?iu] ?b]
end
; match st' with
| (_,_,_) => idtac
| _ => destruct st' as [[?ru' ?iu'] ?b']
end
| [ H : stepSS (?U,_,_) _ |- _ ] =>
match U with
| {| RealWorld.users := ?usrs |} =>
find_silent U usrs
end
| [ IMS : indexedModelStep ?uid (?U,_,_) _
, IRS : indexedRealStep ?uid _ ?U _
|- _ ] => clear IMS
end.
Ltac step_model1 :=
match goal with
| [H : Step _ _ _ |- _] =>
simpl in H
| [H : exists _, _ |- _] =>
destruct H; split_ex; subst (* invert H; propositional; subst *)
| [ H : nextAction _ _ |- _ ] =>
progress (simpl in H)
| [ H : nextAction ?cmd1 ?cmd2 |- _ ] =>
is_var cmd2;
match cmd1 with (* doubt this is general enough *)
| (RealWorld.protocol ?ud) => concrete ud || fail 1
| _ => concrete cmd1
end; invert H
| [ H : O.max_elt _ = Some _ |- _ ] =>
unfold O.max_elt in H; simpl in H; invert H
| [H : In _ $0 |- _] =>
apply in_empty_map_contra in H; contradiction
(* invert H *)
| [H : Raw.PX.MapsTo _ _ $0 |- _] =>
invert H
| [H : (existT _ _ _) = (existT _ _ _) |- _] =>
invert H
| [ S : step ?st ?st' |- _ ] =>
concrete st; is_var st';
match st' with
| (_,_,_) => fail 2
| (?f,_) => destruct f as [?ru ?iu]
| _ => destruct st' as [[?ru ?iu] ?b]
end
| [ S : step ?st _ |- _ ] =>
concrete st;
match goal with
| [ LA : labels_align ?st |- _ ] =>
eapply label_align_step_split in S; (reflexivity || eauto 2); split_ex; split_ors; split_ex; subst
| _ =>
idtac "proving alignment 1"; assert (labels_align st) by ((repeat prove_alignment1); eauto)
end
| [ S : stepC ?st _ |- _ ] =>
concrete st; invert S
| [ H : nextStep _ _ _ |- _ ] => invert H
| [ S : indexedModelStep ?uid ?st _ |- _ ] =>
concrete st;
match goal with
| [ LA : labels_align ?st |- _ ] =>
eapply label_align_indexedModelStep_split in S; (reflexivity || eauto 2); split_ex; split_ors; split_ex; subst
| _ =>
idtac "proving alignment 2"; assert (labels_align st) by ((repeat prove_alignment1); eauto)
end
| [ H : (forall _ _, ~ indexedRealStep ?uid _ ?ru _)
\/ (exists _ _, ?uid <> _ /\ _ $? _ = Some _ /\ (forall _, ?sums $? _ = Some _ -> commutes ?proto _ -> False))
, S : summarize_univ ?ru ?sums
|- _ ] =>
( (assert (exists lbl ru', indexedRealStep uid lbl ru ru') by solve_indexedRealStep )
; (assert (exists uid2 ud2, uid <> uid2
/\ ru.(RealWorld.users) $? uid2 = Some ud2
/\ (forall s, sums $? uid2 = Some s -> commutes proto s)) by non_commuters ))
; discharge_nextStep2 (* clear this goal since the preconditions weren't satisfied *)
end.
Ltac gen_val_typ t :=
match t with
| Nat => constr:(0)
| Bool => constr:(true)
| Unit => constr:(tt)
| Access => constr:((0,false))
| (TPair ?t1 ?t2) =>
let v1 := gen_val_typ t1 in
let v2 := gen_val_typ t2
in constr:((v1,v2))
end.
Ltac gen_msg t :=
match t with
| Access => let v := gen_val_typ Access in constr:(message.Permission v)
| Nat => let v := gen_val_typ Nat in constr:(message.Content v)
| (TPair ?t1 ?t2) =>
let m1 := gen_msg t1 in
let m2 := gen_msg t2 in
constr:(message.MsgPair m1 m2)
end.
Ltac gen_crypto t :=
let m := gen_msg t in constr:(Content m).
Ltac gen_val_cmd_typ ct :=
match ct with
| Base ?t => gen_val_typ t
| Message ?t => gen_msg t
| Crypto ?t => gen_crypto t
| UPair ?t1 ?t2 =>
let v1 := gen_val_cmd_typ t1 in
let v2 := gen_val_cmd_typ t2 in constr:((v1,v2))
end.
(* We have to be careful here when inverting the model checking terms. If we run injection
* on universes which only differ in their protocols, it seems that this fact gets erased.
* I am not entirely sure why this happens. For this reason, we carefully do the inversions
* here manually rather than running injection.
*
*)
Ltac univ_equality_discr :=
discriminate ||
match goal with
| [ H : RealWorld.Bind _ _ = RealWorld.Bind _ _ |- _ ] =>
apply invert_bind_eq in H; split_ex
| [ H1 : ?x = ?y1, H2 : ?x = ?y2 |- _ ] =>
rewrite H1 in H2
; clear H1
| [ H1 : ?x = ?y1, H2 : ?y2 = ?x |- _ ] =>
rewrite H1 in H2
; clear H1
| [ H : (?x1,?y1) = (?x2,?y2) |- _ ] =>
apply tuple_eq_inv in H; split_ex; subst
| [ H : {| users := _ |} = {| users := _ |} |- _ ] =>
apply split_real_univ_fields in H; split_ex
| [ H : Some _ = Some _ |- _ ] =>
apply some_eq_inv in H; split_ex; subst
| [ H : {| key_heap := _ |} = {| key_heap := _ |} |- _ ] =>
apply split_real_user_data_fields in H; split_ex; subst
| [ H : _ $+ (_,_) = _ |- _ ] =>
apply map_eq_fields_eq in H; clean_map_lookups
| [ H : << ?t >> -> _ = _ |- _ ] =>
let vt := gen_val_cmd_typ t
in specialize (H vt)
end.
Ltac tidy :=
autounfold
; intros
; sets_invert
; propositional
; subst
; clean_map_lookups
; subst
; idtac "discriminating univ - tidy"
; repeat (
univ_equality_discr
(* equality has to run after univ equality discrimination because equality1 uses injeection
* which isn't always safe to use on universes. See comment on univ_equality_discr
*)
|| equality1
|| inv_stepSS1
|| step_model1
)
; idtac "discriminating univ - tidy done"
.
Ltac s := simpl in *.
Ltac cleanup :=
repeat (
equality1
|| match goal with
| [ H : True |- _ ] => clear H
| [ H : ?X = ?X |- _ ] => clear H
| [ H : ?x <> ?y |- _ ] =>
match type of x with
| nat => concrete x; concrete y; clear H
end
| [ H : ?x = ?y -> False |- _ ] =>
match type of x with
| nat => concrete x; concrete y; clear H
end
| [ H: RealWorld.keys_mine _ $0 |- _ ] => clear H
| [ H : _ $+ (?k1,_) $? ?k2 = None |- _ ] =>
(rewrite add_neq_o in H by solve_simple_ineq)
|| (rewrite add_eq_o in H by trivial)
|| (destruct (k1 ==n k2); subst)
| [ H : context [ ChMaps.ChannelType.eq _ _ ] |- _ ] => unfold ChMaps.ChannelType.eq in H
| [ H : _ #+ (?k1,_) #? ?k2 = None |- _ ] =>
(rewrite ChMaps.ChMap.F.add_neq_o in H by solve_simple_ineq)
|| (rewrite ChMaps.ChMap.F.add_eq_o in H by trivial)
|| (destruct (ChMaps.ChMap.F.eq_dec k1 k2); subst)
| [ H : context [ _ #+ (?k,_) #? ?k ] |- _ ] =>
is_not_evar k
; rewrite ChMaps.ChMap.F.add_eq_o in H by trivial
| [ H : context [ _ #+ (?k1,_) #? ?k2 ] |- _ ] =>
is_not_evar k1
; is_not_evar k2
; rewrite ChMaps.ChMap.F.add_neq_o in H by congruence
| [ H : mkKeys _ $? _ = _ |- _ ] => unfold mkKeys in H; simpl in H
| [ H : RealWorld.msg_accepted_by_pattern _ _ _ _ _ |- _ ] => clear H
| [ H : ~ RealWorld.msg_accepted_by_pattern _ _ _ _ _ |- _ ] => clear H
| [ H : RealWorld.msg_accepted_by_pattern _ _ _ _ _ -> False |- _ ] => clear H
| [ H : IdealWorld.screen_msg _ _ |- _ ] => invert H
| [ H : IdealWorld.permission_subset _ _ |- _ ] => invert H
| [ H : IdealWorld.check_perm _ _ _ |- _ ] => unfold IdealWorld.check_perm in H
| [ H : context [ IdealWorld.addMsg _ _ _ ] |- _ ] => unfold IdealWorld.addMsg in H; simpl in H
| [ H : Forall _ [] |- _ ] => clear H
| [ H : context [true || _] |- _] => rewrite orb_true_l in H
| [ H : context [_ || true] |- _] => rewrite orb_true_r in H
| [ H : context [false || _] |- _] => rewrite orb_false_l in H
| [ H : context [_ || false] |- _] => rewrite orb_false_r in H
| [ H : context [$0 $k++ _] |- _] => rewrite merge_perms_left_identity in H
| [ H : context [_ $k++ $0] |- _] => rewrite merge_perms_right_identity in H
| [ H : context [_ $k++ _] |- _] =>
erewrite reduce_merge_perms in H by (clean_map_lookups; eauto)
| [ H : context [_ $k++ _] |- _] =>
unfold merge_perms, add_key_perm, fold in H; simpl in H; clean_map_lookups
| [ H : context [ _ $+ (?k1,_) $? ?k2] |- _ ] =>
(rewrite add_neq_o in H by solve_simple_ineq)
|| (rewrite add_eq_o in H by trivial)
| [ H : context [ ?m $? _ ] |- _ ] =>
progress (unfold m in H)
| [ |- context [$0 $k++ _] ] => rewrite !merge_perms_left_identity
| [ |- context [_ $k++ $0] ] => rewrite !merge_perms_right_identity
end
).
Ltac close :=
match goal with
| [|- [_ | _] (?ru, ?iu, _)] =>
concrete ru
; concrete iuniv iu
; tidy
(* ; repeat( progress (subst; cleanup) ) *)
; repeat eexists
; propositional
; solve[ eauto
| canonicalize users
; repeat univ_equality1 ]
| [|- (?inv1 \cup ?inv2) (?ru, ?iu, _)] =>
concrete inv1
; concrete ru
; concrete iuniv iu
; solve[ idtac "trying left"; left; close
| idtac "left fails; trying right"; right; close
| idtac "something is horribly wrong" (* prevent an infinite loop *)
]
| [|- ?inv (?ru, ?iu, _)] =>
is_evar inv
; concrete ru
; concrete iuniv iu
; repeat equality1
; solve_concrete_maps
; canonicalize users
; clean_context
; repeat( progress (subst; cleanup) )
(* ; cleanup *)
; NatMap.clean_map_lookups
; ChMaps.ChMap.clean_map_lookups
; incorp
; solve[ close ]
end.
Ltac gen1' :=
simplify
; tidy
; idtac "rstep start"
; rstep
; idtac "istep start"
; istep
; idtac "istep done"
; subst
; canonicalize users
; idtac "close start"
; repeat close
; idtac "close done".
Locate intersect_empty_l.
Ltac normalize_set_arg s :=
match s with
| context[@union ?A ?X ?Y] =>
quote (@union A X Y) (@nil A)
ltac:(fun e env =>
change (@union A X Y) with (interp_setexpr env e));
rewrite <- normalize_setexpr_ok; sets_cbv
end.
Ltac gen1 :=
match goal with
| [|- multiStepClosure _ _ { } _] =>
eapply MscDone
| [|- multiStepClosure _ {(_,_,_)} {(_,_,_)} _] =>
eapply MscStep
; [ solve[ apply oneStepClosure_grow; repeat gen1' ]
| simplify; simpl_sets (sets; tidy)]
| [|- multiStepClosure _ (?pr \cup ?wl) ?wl _] =>
progress ( normalize_set_arg pr ; normalize_set_arg wl )
| [|- multiStepClosure _ (_ \cup ?wl) ?wl _] =>
eapply msc_step_alt
; [ solve[ unfold oneStepClosure_new; repeat gen1' ]
| solve[ idtac "proving empty intersection"
; simplify
; sets
; split_ex
; propositional
; idtac "preparing to discriminate universes"
(* equality has to run after univ equality discrimination because equality1 uses injeection
* which isn't always safe to use on universes. See comment on univ_equality_discr
*)
; repeat (univ_equality_discr || equality1)
; idtac "universes discriminated"
| eapply intersect_empty_l]
| rewrite ?union_empty_r ]
end.
(* Use this to generate the invariant *)
Ltac gen := repeat gen1.
Ltac discr_sets :=
simplify
; sets
; split_ex
(* equality has to run after univ equality discrimination because equality1 uses injeection
* which isn't always safe to use on universes. See comment on univ_equality_discr
*)
; repeat (univ_equality_discr || equality1).
Ltac dedup_worklist wl k :=
let rec dedup_wl acc wl :=
idtac "iterating";
match wl with
| ?s1 \cup ?s2 =>
( assert ( acc \cap s1 = { } ) by discr_sets
; dedup_wl (acc \cup s1) s2 )
|| dedup_wl acc s2
| ?s =>
( assert ( acc \cap s = { } ) by discr_sets
; k (acc \cup s) )
|| k acc
end
in idtac "wl";
match wl with
| { } \cup ?s => dedup_worklist s k
| ?s1 \cup ?s2 => dedup_wl s1 s2
| ?s1 => k s1
end.
End Gen.
(* Helps with initial universe state proofs *)
Ltac focus_user :=
repeat
match goal with
| [ H : _ $+ (?k1,_) $? ?k2 = Some ?v |- _ ] =>
is_var v;
match type of v with
| RealWorld.user_data _ => idtac
end; destruct (k1 ==n k2); subst; clean_map_lookups
end.
|
/***************************************************************************
File : FrequencyCountDialog.h
Project : QtiPlot
--------------------------------------------------------------------
Copyright : (C) 2008 by Ion Vasilief
Email (use @ for *) : ion_vasilief*yahoo.fr
Description : Frequency count options dialog
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301 USA *
* *
***************************************************************************/
#ifndef FREQUENCYCOUNTDIALOG_H
#define FREQUENCYCOUNTDIALOG_H
#include <QDialog>
#include <gsl/gsl_vector.h>
class QPushButton;
class DoubleSpinBox;
class Table;
//! Filter options dialog
class FrequencyCountDialog : public QDialog
{
Q_OBJECT
public:
FrequencyCountDialog(Table *t, QWidget* parent = 0, Qt::WFlags fl = 0 );
~FrequencyCountDialog();
private slots:
bool apply();
void accept();
private:
Table *d_source_table;
Table *d_result_table;
QString d_col_name;
gsl_vector *d_col_values;
int d_bins;
QPushButton* buttonApply;
QPushButton* buttonCancel;
QPushButton* buttonOk;
DoubleSpinBox* boxStart;
DoubleSpinBox* boxEnd;
DoubleSpinBox* boxStep;
};
#endif
|
! { dg-do run }
integer, allocatable :: a(:, :)
integer :: b(6, 3)
integer :: i, j
logical :: k, l
b(:, :) = 16
l = .false.
if (allocated (a)) call abort
!$omp task private (a, b) shared (l)
l = l.or.allocated (a)
allocate (a(3, 6))
l = l.or..not.allocated (a)
l = l.or.size(a).ne.18.or.size(a,1).ne.3.or.size(a,2).ne.6
a(3, 2) = 1
b(3, 2) = 1
deallocate (a)
l = l.or.allocated (a)
!$omp end task
!$omp taskwait
if (allocated (a).or.l) call abort
allocate (a(6, 3))
a(:, :) = 3
if (.not.allocated (a)) call abort
l = l.or.size(a).ne.18.or.size(a,1).ne.6.or.size(a,2).ne.3
if (l) call abort
!$omp task private (a, b) shared (l)
l = l.or..not.allocated (a)
a(3, 2) = 1
b(3, 2) = 1
!$omp end task
!$omp taskwait
if (l.or..not.allocated (a)) call abort
!$omp task firstprivate (a, b) shared (l)
l = l.or..not.allocated (a)
l = l.or.size(a).ne.18.or.size(a,1).ne.6.or.size(a,2).ne.3
do i = 1, 6
l = l.or.(a(i, 1).ne.3).or.(a(i, 2).ne.3)
l = l.or.(a(i, 3).ne.3).or.(b(i, 1).ne.16)
l = l.or.(b(i, 2).ne.16).or.(b(i, 3).ne.16)
end do
a(:, :) = 7
b(:, :) = 8
!$omp end task
!$omp taskwait
if (any (a.ne.3).or.any (b.ne.16).or.l) call abort
end
|
module Libgit.Object
import Control.Monad.Managed
import Libgit.FFI
import Libgit.Oid
import Libgit.Types
enrichGitObject : AnyPtr -> (typ ** GitObject typ)
enrichGitObject ptr =
let objTyp = gitObjectTypeFromInt (git_object_type ptr) in
(objTyp ** MkGitObject ptr)
withGitObject : GitRepository
-> GitOid
-> (GitResult (typ ** GitObject typ) -> IO a)
-> IO a
withGitObject (MkGitRepository repoPtr) (MkGitOid oidPtr) act = do
let cgr = git_lookup_object repoPtr oidPtr (gitObjectTypeToInt GitObjectAny)
result <- getGitResult cgr
let objResult = enrichGitObject <$> result
actResult <- act objResult
case result of
Right ptr => pure actResult <* primIO (prim_git_object_free ptr)
Left _ => pure actResult
||| Retrieve an object of any type from a Git repository.
|||
||| Returns on success a dependent pair of the object's type and a managed
||| reference to the object.
||| Returns on failure a Git error code.
|||
||| @repo The GitRepository to retrieve the object from.
||| @oid The object ID to retrieve from the repository.
export
gitObject : (repo : GitRepository)
-> (oid : GitOid)
-> Managed (GitResult (typ ** GitObject typ))
gitObject repo oid = managed (withGitObject repo oid)
||| Retrieve an object of any type from a Git repository based on the object
||| ID's string representation.
|||
||| Returns on success a dependent pair of the object's type and a managed
||| reference to the object.
||| Returns on failure a Git error code.
|||
||| @repo The GitRepository to retrieve the object from.
||| @str The string representation of an object ID.
export
gitObjectFromString : GitRepository
-> String
-> Managed (GitResult (typ ** GitObject typ))
gitObjectFromString repo str = do
Right oid <- oidFromString str
| Left err => pure (Left err)
gitObject repo oid
withParsedRev : (repo : GitRepository)
-> (rev : String)
-> (GitResult (typ ** GitObject typ) -> IO a)
-> IO a
withParsedRev (MkGitRepository repo) rev act = do
cgr <- primIO (prim_git_single_revparse repo rev)
(err, ptr) <- getGitResultPair cgr
let revResult = enrichGitObject <$> toGitResult err ptr
result <- act revResult
primIO (prim_git_object_free ptr)
pure result
||| Parse a formatted revision string into a Git object.
|||
||| Returns on success a managed reference to the Git object.
||| Returns on failure a Git error code.
|||
||| @repo The Git repository to perform the lookup in.
||| @rev The string, formatted per the git revision spec
||| http://git-scm.com/docs/git-rev-parse.html#_specifying_revisions),
||| to parse into an object.
export
revParse : (repo : GitRepository)
-> (rev : String)
-> Managed (GitResult (typ ** GitObject typ))
revParse repo rev = managed (withParsedRev repo rev)
withTypedGitObject : GitRepository
-> GitOid
-> (typ : GitObjectType)
-> (GitResult (GitObject typ) -> IO a)
-> IO a
withTypedGitObject (MkGitRepository repoPtr) (MkGitOid oidPtr) typ act = do
let cgr = git_lookup_object repoPtr oidPtr (gitObjectTypeToInt typ)
result <- getGitResult cgr
actResult <- act (MkGitObject <$> result)
case result of
Right ptr => pure actResult <* primIO (prim_git_object_free ptr)
Left _ => pure actResult
||| Retrieve an object of a specific type from a Git repository.
|||
||| Returns on success a managed reference to the object.
||| Returns on failure a Git error code.
|||
||| @repo The GitRepository to retrieve the object from.
||| @oid The object ID to retrieve from the repository.
||| @typ The GitObjectType of the object to retrieve.
export
typedGitObject : GitRepository
-> GitOid
-> (typ : GitObjectType)
-> Managed (GitResult (GitObject typ))
typedGitObject repo oid typ = managed (withTypedGitObject repo oid typ)
||| Retrieve an object of a specific type from a Git repository based on the
||| object ID's string representation.
|||
||| Returns on success a managed reference to the object.
||| Returns on failure a Git error code.
|||
||| @repo The GitRepository to retrieve the object from.
||| @str The string representation of an object ID.
||| @typ The GitObjectType of the object to retrieve.
export
typedGitObjectFromString : GitRepository
-> String
-> (typ : GitObjectType)
-> Managed (GitResult (GitObject typ))
typedGitObjectFromString repo str typ = do
Right oid <- oidFromString str
| Left err => pure (Left err)
managed (withTypedGitObject repo oid typ)
|
section \<open>Integers\<close>
theory Integers
imports
Integers_Rep
Set_Extensions
Transport.Transport
begin
unbundle no_HOL_groups_syntax
subsection \<open>The Integers as a Subset of the Naturals\<close>
interpretation Int : set_extension \<nat> int_rep Int_Rep_nonneg
by unfold_locales (auto intro: ElementI)
abbreviation "int \<equiv> Int.Abs"
bundle isa_set_int_syntax begin notation int ("\<int>") end
bundle no_isa_set_int_syntax begin no_notation int ("\<int>") end
unbundle isa_set_int_syntax
abbreviation "Int \<equiv> Element \<int>"
lemmas nat_subset_int [iff] = Int.Core_subset_Abs
corollary Int_if_Nat [derive]: "n : Nat \<Longrightarrow> n : Int"
using subsetD[OF nat_subset_int] by unfold_types
subsection \<open>Arithmetic operations lifted to Int\<close>
text \<open>We lift constants/functions from @{term "Int_Rep"} to @{term "\<int>"}
manually. This should be automated in the future.\<close>
definition "int_nonneg n \<equiv> Int.l (Int_Rep_nonneg n)"
definition "int_neg n \<equiv> Int.l (Int_Rep_neg n)"
definition "int_succ i \<equiv> Int.l (Int_Rep_succ (Int.r i))"
definition "int_pred i \<equiv> Int.l (Int_Rep_pred (Int.r i))"
definition "int_inv i \<equiv> Int.l (Int_Rep_inv (Int.r i))"
definition "int_add i j \<equiv> Int.l (Int_Rep_add (Int.r i) (Int.r j))"
definition "int_sub i j \<equiv> Int.l (Int_Rep_sub (Int.r i) (Int.r j))"
definition "int_mul i j \<equiv> Int.l (Int_Rep_mul (Int.r i) (Int.r j))"
(*TODO: automatic translation between @{term "Nat \<Coprod> Element (\<nat> \<setminus> {0})"}
and @{term "Element (\<nat> \<Coprod> \<nat> \<setminus> {0})"} not working at the moment;
maybe we want to introduce extensionality for types?*)
lemma
shows int_nonneg_type [type]: "int_nonneg : Nat \<Rightarrow> Int"
and int_neg_type [type]: "int_neg : Element (\<nat> \<setminus> {0}) \<Rightarrow> Int"
and int_succ_type [type]: "int_succ : Int \<Rightarrow> Int"
and int_pred_type [type]: "int_pred : Int \<Rightarrow> Int"
and int_inv_type [type]: "int_inv : Int \<Rightarrow> Int"
and int_add_type [type]: "int_add : Int \<Rightarrow> Int \<Rightarrow> Int"
and int_sub_type [type]: "int_sub : Int \<Rightarrow> Int \<Rightarrow> Int"
and int_mul_type [type]: "int_mul : Int \<Rightarrow> Int \<Rightarrow> Int"
unfolding int_nonneg_def int_neg_def int_succ_def int_pred_def int_inv_def
int_add_def int_sub_def int_mul_def
oops
(* using [[type_derivation_depth=3]] *)
(* by auto *)
text \<open>We need a notation package that also does inference to determine if a
number is a Nat, Int, etc. Typeclass integration here already?\<close>
bundle isa_set_int_add_syntax begin notation int_add (infixl "+" 65) end
bundle no_isa_set_int_add_syntax begin no_notation int_add (infixl "+" 65) end
bundle isa_set_int_sub_syntax begin notation int_sub (infixl "-" 65) end
bundle no_isa_set_int_sub_syntax begin no_notation int_sub (infixl "-" 65) end
bundle isa_set_int_mul_syntax begin notation int_mul (infixl "*" 70) end
bundle no_isa_set_int_mul_syntax begin no_notation int_mul (infixl "*" 70) end
unbundle
no_isa_set_nat_add_syntax
no_isa_set_nat_sub_syntax
no_isa_set_nat_mul_syntax
isa_set_int_add_syntax
isa_set_int_sub_syntax
isa_set_int_mul_syntax
(*TODO: no proper normal forms at the moment*)
subsubsection \<open>Examples\<close>
experiment begin
named_theorems arith
lemmas [arith] =
int_nonneg_def int_neg_def int_add_def int_sub_def int_mul_def
Int_Rep_zero_def[symmetric] Int_Rep_one_def[symmetric]
Int_Rep_nonneg_succ_add_eq
text \<open>At some point we want to just be able to write \<open>succ n\<close> below, and
automatically infer that it has to have soft type \<open>Int\<close>.\<close>
schematic_goal
"int_nonneg (succ 0) + int_nonneg (succ 0) + int_neg (succ 0) = ?a"
by (simp add: arith)
schematic_goal
"int_nonneg 0 * int_neg (succ 0) + int_nonneg (succ 0) - int_neg (succ 0) = ?a"
by (simp add: arith)
end
subsection \<open>Algebraic Structures\<close>
text \<open>Additive group structure\<close>
definition "int_Group \<equiv> object {
\<langle>@zero, 0\<rangle>,
\<langle>@add, \<lambda>i j \<in> \<int>. int_add i j\<rangle>,
\<langle>@inv, \<lambda>i \<in> \<int>. Int_Rep_inv i\<rangle>
}"
bundle isa_set_int_Group_syntax
begin notation int_Group ("'(\<int>, +')") end
bundle no_isa_set_int_Monoid_syntax
begin no_notation int_Group ("'(\<int>, +')") end
unbundle isa_set_int_Group_syntax
(*TODO: The following should be automatically generated*)
lemma "(\<int>, +) : Group Int"
(* proof (rule GroupI, rule MonoidI)
show "(\<int>, +) : Zero Int" by (rule ZeroI) simp
show "(\<int>, +) : Add Int"
(*TODO: object selector simplifier not working properly*)
(* unfolding nat_Monoid_def by (rule AddI) simp *)
proof (rule AddI)
have select_add_eq: "(\<int>, +)@@add = \<lambda>i j \<in> \<int>. int_add i j" by simp
show "(\<int>, +)@@add : Int \<rightarrow>s Int \<rightarrow>s Int" by (subst select_add_eq) discharge_types
qed
(*TODO: needs transferred theorems from representation type*)
qed (unfold add_def zero_def inv_def, auto) *)
oops
text \<open>Multiplicative monoid structure\<close>
definition "int_Mul_Monoid \<equiv> object {
\<langle>@one, 1\<rangle>,
\<langle>@mul, \<lambda>i j \<in> \<int>. int_mul i j\<rangle>
}"
bundle isa_set_int_Mul_Monoid_syntax
begin notation int_Mul_Monoid ("'(\<int>, *')") end
bundle no_isa_set_int_Mul_Monoid_syntax
begin no_notation int_Mul_Monoid ("'(\<int>, *')") end
unbundle isa_set_int_Mul_Monoid_syntax
(* lemma int_mul_assoc:
assumes "i : Int" "j : Int" "k : Int"
shows "i * j * k = i * (j * k)"
(* using assms Int_Rep_mul_assoc unfolding int_mul_def by simp *)
oops *)
lemma "(\<int>, *) : Mul_Monoid Int"
\<comment> \<open>
proof (intro Mul_MonoidI)
show "(\<int>, *) : One \<int>"
unfolding int_Mul_Monoid_def by (rule OneI) simp
next
show "(\<int>, *) : Mul \<int>"
unfolding int_Mul_Monoid_def by (rule MulI) simp
next
fix x assume "x \<in> \<int>"
then show "mul int_Mul_Monoid (one int_Mul_Monoid) x = x" and
"mul int_Mul_Monoid x (one int_Mul_Monoid) = x"
unfolding int_Mul_Monoid_def mul_def one_def by auto
next
fix x y z assume "x \<in> \<int>" "y \<in> \<int>" "z \<in> \<int>"
show "mul int_Mul_Monoid (mul int_Mul_Monoid x y) z =
mul int_Mul_Monoid x (mul int_Mul_Monoid y z)"
(* using int_mul_assoc unfolding int_Mul_Monoid_def mul_def by simp *)
qed\<close>
oops
end
|
using Plots
f(x) = 100*x - 60
g(x) = 30 - 60*x
h(x) = 0
v(x) = max.(f(x),g(x),h(x))
x = 0:0.1:1
plot(x, f.(x),
xaxis = ("prob. (mu)", [0.0, 0.5, 0.6, 1.0]),
yaxis = ("expected value", (-10,40)),
label = "outdoor")
plot!(x, g.(x),
label = "indoor")
plot!(x, h.(x),
label = "none")
plot!(x, v.(x),
label = "max{o,i,n}")
|
Stephen Thomas Erlewine from Allmusic gave the album three out of five stars , but felt that the track list could have been shortened . Erlewine complimented some of the remixes , including those by Pet Shop Boys and Space Cowboy , adding that The Remix " is not an essential addition to Gaga ’ s canon goes without saying ... but there ’ s glitz and glamour to enjoy here . " Mark Beech , reviewing the album for Bloomberg Television , noticed that the already familiar tracks from Gaga " are given a new sheen by the Pet Shop Boys and sometime Madonna producer Stuart Price . " Nicki Escudero from Phoenix New Times gave a positive review saying that the songs featured in The Remix can be a great addition during workouts , as well as staple dance floor music . She listed the Chew Fu remix of " LoveGame " as a highlight from the album . Monica Herrera from Billboard complimented the album saying " Gaga has employed a collection of more @-@ than @-@ capable producers to make her dance @-@ ready smashes from The Fame and The Fame Monster even more <unk> . " Giving it three out of five stars , Caryn Ganz from Rolling Stone noted an uneven sequencing among the tracks in The Remix . She felt that the Passion Pit remix of " Telephone " was the best remix on the album .
|
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.HITs.Rationals.QuoQ.Properties where
open import Cubical.Foundations.Everything hiding (_⁻¹)
open import Cubical.HITs.Ints.QuoInt as ℤ using (ℤ; Sign; signed; pos; neg; posneg; sign)
open import Cubical.HITs.SetQuotients as SetQuotient using () renaming (_/_ to _//_)
open import Cubical.Data.Nat as ℕ using (ℕ; zero; suc)
open import Cubical.Data.NatPlusOne
open import Cubical.Data.Sigma
open import Cubical.Data.Sum
open import Cubical.Relation.Nullary
open import Cubical.HITs.Rationals.QuoQ.Base
ℚ-cancelˡ : ∀ {a b} (c : ℕ₊₁) → [ ℕ₊₁→ℤ c ℤ.· a / c ·₊₁ b ] ≡ [ a / b ]
ℚ-cancelˡ {a} {b} c = eq/ _ _
(cong (ℤ._· ℕ₊₁→ℤ b) (ℤ.·-comm (ℕ₊₁→ℤ c) a) ∙ sym (ℤ.·-assoc a (ℕ₊₁→ℤ c) (ℕ₊₁→ℤ b)))
ℚ-cancelʳ : ∀ {a b} (c : ℕ₊₁) → [ a ℤ.· ℕ₊₁→ℤ c / b ·₊₁ c ] ≡ [ a / b ]
ℚ-cancelʳ {a} {b} c = eq/ _ _
(sym (ℤ.·-assoc a (ℕ₊₁→ℤ c) (ℕ₊₁→ℤ b)) ∙ cong (a ℤ.·_) (ℤ.·-comm (ℕ₊₁→ℤ c) (ℕ₊₁→ℤ b)))
-- useful functions for defining operations on ℚ
onCommonDenom :
(g : ℤ × ℕ₊₁ → ℤ × ℕ₊₁ → ℤ)
(g-eql : ∀ ((a , b) (c , d) (e , f) : ℤ × ℕ₊₁) (p : a ℤ.· ℕ₊₁→ℤ d ≡ c ℤ.· ℕ₊₁→ℤ b)
→ ℕ₊₁→ℤ d ℤ.· (g (a , b) (e , f)) ≡ ℕ₊₁→ℤ b ℤ.· (g (c , d) (e , f)))
(g-eqr : ∀ ((a , b) (c , d) (e , f) : ℤ × ℕ₊₁) (p : c ℤ.· ℕ₊₁→ℤ f ≡ e ℤ.· ℕ₊₁→ℤ d)
→ (g (a , b) (c , d)) ℤ.· ℕ₊₁→ℤ f ≡ (g (a , b) (e , f)) ℤ.· ℕ₊₁→ℤ d)
→ ℚ → ℚ → ℚ
onCommonDenom g g-eql g-eqr = SetQuotient.rec2 isSetℚ
(λ { (a , b) (c , d) → [ g (a , b) (c , d) / b ·₊₁ d ] })
(λ { (a , b) (c , d) (e , f) p → eql (a , b) (c , d) (e , f) p })
(λ { (a , b) (c , d) (e , f) p → eqr (a , b) (c , d) (e , f) p })
where eql : ∀ ((a , b) (c , d) (e , f) : ℤ × ℕ₊₁) (p : a ℤ.· ℕ₊₁→ℤ d ≡ c ℤ.· ℕ₊₁→ℤ b)
→ [ g (a , b) (e , f) / b ·₊₁ f ] ≡ [ g (c , d) (e , f) / d ·₊₁ f ]
eql (a , b) (c , d) (e , f) p =
[ g (a , b) (e , f) / b ·₊₁ f ]
≡⟨ sym (ℚ-cancelˡ d) ⟩
[ ℕ₊₁→ℤ d ℤ.· (g (a , b) (e , f)) / d ·₊₁ (b ·₊₁ f) ]
≡[ i ]⟨ [ ℕ₊₁→ℤ d ℤ.· (g (a , b) (e , f)) / ·₊₁-assoc d b f i ] ⟩
[ ℕ₊₁→ℤ d ℤ.· (g (a , b) (e , f)) / (d ·₊₁ b) ·₊₁ f ]
≡[ i ]⟨ [ g-eql (a , b) (c , d) (e , f) p i / ·₊₁-comm d b i ·₊₁ f ] ⟩
[ ℕ₊₁→ℤ b ℤ.· (g (c , d) (e , f)) / (b ·₊₁ d) ·₊₁ f ]
≡[ i ]⟨ [ ℕ₊₁→ℤ b ℤ.· (g (c , d) (e , f)) / ·₊₁-assoc b d f (~ i) ] ⟩
[ ℕ₊₁→ℤ b ℤ.· (g (c , d) (e , f)) / b ·₊₁ (d ·₊₁ f) ]
≡⟨ ℚ-cancelˡ b ⟩
[ g (c , d) (e , f) / d ·₊₁ f ] ∎
eqr : ∀ ((a , b) (c , d) (e , f) : ℤ × ℕ₊₁) (p : c ℤ.· ℕ₊₁→ℤ f ≡ e ℤ.· ℕ₊₁→ℤ d)
→ [ g (a , b) (c , d) / b ·₊₁ d ] ≡ [ g (a , b) (e , f) / b ·₊₁ f ]
eqr (a , b) (c , d) (e , f) p =
[ g (a , b) (c , d) / b ·₊₁ d ]
≡⟨ sym (ℚ-cancelʳ f) ⟩
[ (g (a , b) (c , d)) ℤ.· ℕ₊₁→ℤ f / (b ·₊₁ d) ·₊₁ f ]
≡[ i ]⟨ [ (g (a , b) (c , d)) ℤ.· ℕ₊₁→ℤ f / ·₊₁-assoc b d f (~ i) ] ⟩
[ (g (a , b) (c , d)) ℤ.· ℕ₊₁→ℤ f / b ·₊₁ (d ·₊₁ f) ]
≡[ i ]⟨ [ g-eqr (a , b) (c , d) (e , f) p i / b ·₊₁ ·₊₁-comm d f i ] ⟩
[ (g (a , b) (e , f)) ℤ.· ℕ₊₁→ℤ d / b ·₊₁ (f ·₊₁ d) ]
≡[ i ]⟨ [ (g (a , b) (e , f)) ℤ.· ℕ₊₁→ℤ d / ·₊₁-assoc b f d i ] ⟩
[ (g (a , b) (e , f)) ℤ.· ℕ₊₁→ℤ d / (b ·₊₁ f) ·₊₁ d ]
≡⟨ ℚ-cancelʳ d ⟩
[ g (a , b) (e , f) / b ·₊₁ f ] ∎
onCommonDenomSym :
(g : ℤ × ℕ₊₁ → ℤ × ℕ₊₁ → ℤ)
(g-sym : ∀ x y → g x y ≡ g y x)
(g-eql : ∀ ((a , b) (c , d) (e , f) : ℤ × ℕ₊₁) (p : a ℤ.· ℕ₊₁→ℤ d ≡ c ℤ.· ℕ₊₁→ℤ b)
→ ℕ₊₁→ℤ d ℤ.· (g (a , b) (e , f)) ≡ ℕ₊₁→ℤ b ℤ.· (g (c , d) (e , f)))
→ ℚ → ℚ → ℚ
onCommonDenomSym g g-sym g-eql = onCommonDenom g g-eql q-eqr
where q-eqr : ∀ ((a , b) (c , d) (e , f) : ℤ × ℕ₊₁) (p : c ℤ.· ℕ₊₁→ℤ f ≡ e ℤ.· ℕ₊₁→ℤ d)
→ (g (a , b) (c , d)) ℤ.· ℕ₊₁→ℤ f ≡ (g (a , b) (e , f)) ℤ.· ℕ₊₁→ℤ d
q-eqr (a , b) (c , d) (e , f) p =
(g (a , b) (c , d)) ℤ.· ℕ₊₁→ℤ f ≡[ i ]⟨ ℤ.·-comm (g-sym (a , b) (c , d) i) (ℕ₊₁→ℤ f) i ⟩
ℕ₊₁→ℤ f ℤ.· (g (c , d) (a , b)) ≡⟨ g-eql (c , d) (e , f) (a , b) p ⟩
ℕ₊₁→ℤ d ℤ.· (g (e , f) (a , b)) ≡[ i ]⟨ ℤ.·-comm (ℕ₊₁→ℤ d) (g-sym (e , f) (a , b) i) i ⟩
(g (a , b) (e , f)) ℤ.· ℕ₊₁→ℤ d ∎
onCommonDenomSym-comm : ∀ {g} g-sym {g-eql} (x y : ℚ)
→ onCommonDenomSym g g-sym g-eql x y ≡
onCommonDenomSym g g-sym g-eql y x
onCommonDenomSym-comm g-sym = SetQuotient.elimProp2 (λ _ _ → isSetℚ _ _)
(λ { (a , b) (c , d) i → [ g-sym (a , b) (c , d) i / ·₊₁-comm b d i ] })
-- basic arithmetic operations on ℚ
infixl 6 _+_
infixl 7 _·_
private
lem₁ : ∀ a b c d e (p : a ℤ.· b ≡ c ℤ.· d) → b ℤ.· (a ℤ.· e) ≡ d ℤ.· (c ℤ.· e)
lem₁ a b c d e p = ℤ.·-assoc b a e
∙ cong (ℤ._· e) (ℤ.·-comm b a ∙ p ∙ ℤ.·-comm c d)
∙ sym (ℤ.·-assoc d c e)
lem₂ : ∀ a b c → a ℤ.· (b ℤ.· c) ≡ c ℤ.· (b ℤ.· a)
lem₂ a b c = cong (a ℤ.·_) (ℤ.·-comm b c) ∙ ℤ.·-assoc a c b
∙ cong (ℤ._· b) (ℤ.·-comm a c) ∙ sym (ℤ.·-assoc c a b)
∙ cong (c ℤ.·_) (ℤ.·-comm a b)
_+_ : ℚ → ℚ → ℚ
_+_ = onCommonDenomSym
(λ { (a , b) (c , d) → a ℤ.· (ℕ₊₁→ℤ d) ℤ.+ c ℤ.· (ℕ₊₁→ℤ b) })
(λ { (a , b) (c , d) → ℤ.+-comm (a ℤ.· (ℕ₊₁→ℤ d)) (c ℤ.· (ℕ₊₁→ℤ b)) })
(λ { (a , b) (c , d) (e , f) p →
ℕ₊₁→ℤ d ℤ.· (a ℤ.· ℕ₊₁→ℤ f ℤ.+ e ℤ.· ℕ₊₁→ℤ b)
≡⟨ sym (ℤ.·-distribˡ (ℕ₊₁→ℤ d) (a ℤ.· ℕ₊₁→ℤ f) (e ℤ.· ℕ₊₁→ℤ b)) ⟩
ℕ₊₁→ℤ d ℤ.· (a ℤ.· ℕ₊₁→ℤ f) ℤ.+ ℕ₊₁→ℤ d ℤ.· (e ℤ.· ℕ₊₁→ℤ b)
≡[ i ]⟨ lem₁ a (ℕ₊₁→ℤ d) c (ℕ₊₁→ℤ b) (ℕ₊₁→ℤ f) p i ℤ.+ lem₂ (ℕ₊₁→ℤ d) e (ℕ₊₁→ℤ b) i ⟩
ℕ₊₁→ℤ b ℤ.· (c ℤ.· ℕ₊₁→ℤ f) ℤ.+ ℕ₊₁→ℤ b ℤ.· (e ℤ.· ℕ₊₁→ℤ d)
≡⟨ ℤ.·-distribˡ (ℕ₊₁→ℤ b) (c ℤ.· ℕ₊₁→ℤ f) (e ℤ.· ℕ₊₁→ℤ d) ⟩
ℕ₊₁→ℤ b ℤ.· (c ℤ.· ℕ₊₁→ℤ f ℤ.+ e ℤ.· ℕ₊₁→ℤ d) ∎ })
+-comm : ∀ x y → x + y ≡ y + x
+-comm = onCommonDenomSym-comm
(λ { (a , b) (c , d) → ℤ.+-comm (a ℤ.· (ℕ₊₁→ℤ d)) (c ℤ.· (ℕ₊₁→ℤ b)) })
+-identityˡ : ∀ x → 0 + x ≡ x
+-identityˡ = SetQuotient.elimProp (λ _ → isSetℚ _ _)
(λ { (a , b) i → [ ℤ.·-identityʳ a i / ·₊₁-identityˡ b i ] })
+-identityʳ : ∀ x → x + 0 ≡ x
+-identityʳ x = +-comm x _ ∙ +-identityˡ x
+-assoc : ∀ x y z → x + (y + z) ≡ (x + y) + z
+-assoc = SetQuotient.elimProp3 (λ _ _ _ → isSetℚ _ _)
(λ { (a , b) (c , d) (e , f) i → [ eq a (ℕ₊₁→ℤ b) c (ℕ₊₁→ℤ d) e (ℕ₊₁→ℤ f) i / ·₊₁-assoc b d f i ] })
where eq₁ : ∀ a b c → (a ℤ.· b) ℤ.· c ≡ a ℤ.· (c ℤ.· b)
eq₁ a b c = sym (ℤ.·-assoc a b c) ∙ cong (a ℤ.·_) (ℤ.·-comm b c)
eq₂ : ∀ a b c → (a ℤ.· b) ℤ.· c ≡ (a ℤ.· c) ℤ.· b
eq₂ a b c = eq₁ a b c ∙ ℤ.·-assoc a c b
eq : ∀ a b c d e f → Path ℤ _ _
eq a b c d e f =
a ℤ.· (d ℤ.· f) ℤ.+ (c ℤ.· f ℤ.+ e ℤ.· d) ℤ.· b
≡[ i ]⟨ a ℤ.· (d ℤ.· f) ℤ.+ ℤ.·-distribʳ (c ℤ.· f) (e ℤ.· d) b (~ i) ⟩
a ℤ.· (d ℤ.· f) ℤ.+ ((c ℤ.· f) ℤ.· b ℤ.+ (e ℤ.· d) ℤ.· b)
≡[ i ]⟨ ℤ.+-assoc (ℤ.·-assoc a d f i) (eq₂ c f b i) (eq₁ e d b i) i ⟩
((a ℤ.· d) ℤ.· f ℤ.+ (c ℤ.· b) ℤ.· f) ℤ.+ e ℤ.· (b ℤ.· d)
≡[ i ]⟨ ℤ.·-distribʳ (a ℤ.· d) (c ℤ.· b) f i ℤ.+ e ℤ.· (b ℤ.· d) ⟩
(a ℤ.· d ℤ.+ c ℤ.· b) ℤ.· f ℤ.+ e ℤ.· (b ℤ.· d) ∎
_·_ : ℚ → ℚ → ℚ
_·_ = onCommonDenomSym
(λ { (a , _) (c , _) → a ℤ.· c })
(λ { (a , _) (c , _) → ℤ.·-comm a c })
(λ { (a , b) (c , d) (e , _) p → lem₁ a (ℕ₊₁→ℤ d) c (ℕ₊₁→ℤ b) e p })
·-comm : ∀ x y → x · y ≡ y · x
·-comm = onCommonDenomSym-comm (λ { (a , _) (c , _) → ℤ.·-comm a c })
·-identityˡ : ∀ x → 1 · x ≡ x
·-identityˡ = SetQuotient.elimProp (λ _ → isSetℚ _ _)
(λ { (a , b) i → [ ℤ.·-identityˡ a i / ·₊₁-identityˡ b i ] })
·-identityʳ : ∀ x → x · 1 ≡ x
·-identityʳ = SetQuotient.elimProp (λ _ → isSetℚ _ _)
(λ { (a , b) i → [ ℤ.·-identityʳ a i / ·₊₁-identityʳ b i ] })
·-zeroˡ : ∀ x → 0 · x ≡ 0
·-zeroˡ = SetQuotient.elimProp (λ _ → isSetℚ _ _)
(λ { (a , b) → (λ i → [ p a b i / 1 ·₊₁ b ]) ∙ ℚ-cancelʳ b })
where p : ∀ a b → 0 ℤ.· a ≡ 0 ℤ.· ℕ₊₁→ℤ b
p a b = ℤ.·-zeroˡ {ℤ.spos} a ∙ sym (ℤ.·-zeroˡ {ℤ.spos} (ℕ₊₁→ℤ b))
·-zeroʳ : ∀ x → x · 0 ≡ 0
·-zeroʳ = SetQuotient.elimProp (λ _ → isSetℚ _ _)
(λ { (a , b) → (λ i → [ p a b i / b ·₊₁ 1 ]) ∙ ℚ-cancelˡ b })
where p : ∀ a b → a ℤ.· 0 ≡ ℕ₊₁→ℤ b ℤ.· 0
p a b = ℤ.·-zeroʳ {ℤ.spos} a ∙ sym (ℤ.·-zeroʳ {ℤ.spos} (ℕ₊₁→ℤ b))
·-assoc : ∀ x y z → x · (y · z) ≡ (x · y) · z
·-assoc = SetQuotient.elimProp3 (λ _ _ _ → isSetℚ _ _)
(λ { (a , b) (c , d) (e , f) i → [ ℤ.·-assoc a c e i / ·₊₁-assoc b d f i ] })
·-distribˡ : ∀ x y z → (x · y) + (x · z) ≡ x · (y + z)
·-distribˡ = SetQuotient.elimProp3 (λ _ _ _ → isSetℚ _ _)
(λ { (a , b) (c , d) (e , f) → eq a b c d e f })
where lem : ∀ {ℓ} {A : Type ℓ} (_·_ : A → A → A)
(·-comm : ∀ x y → x · y ≡ y · x)
(·-assoc : ∀ x y z → x · (y · z) ≡ (x · y) · z)
a c b d
→ (a · c) · (b · d) ≡ (a · (c · d)) · b
lem _·_ ·-comm ·-assoc a c b d =
(a · c) · (b · d) ≡[ i ]⟨ (a · c) · ·-comm b d i ⟩
(a · c) · (d · b) ≡⟨ ·-assoc (a · c) d b ⟩
((a · c) · d) · b ≡[ i ]⟨ ·-assoc a c d (~ i) · b ⟩
(a · (c · d)) · b ∎
lemℤ = lem ℤ._·_ ℤ.·-comm ℤ.·-assoc
lemℕ₊₁ = lem _·₊₁_ ·₊₁-comm ·₊₁-assoc
eq : ∀ a b c d e f →
[ (a ℤ.· c) ℤ.· ℕ₊₁→ℤ (b ·₊₁ f) ℤ.+ (a ℤ.· e) ℤ.· ℕ₊₁→ℤ (b ·₊₁ d)
/ (b ·₊₁ d) ·₊₁ (b ·₊₁ f) ]
≡ [ a ℤ.· (c ℤ.· ℕ₊₁→ℤ f ℤ.+ e ℤ.· ℕ₊₁→ℤ d)
/ b ·₊₁ (d ·₊₁ f) ]
eq a b c d e f =
(λ i → [ lemℤ a c (ℕ₊₁→ℤ b) (ℕ₊₁→ℤ f) i ℤ.+ lemℤ a e (ℕ₊₁→ℤ b) (ℕ₊₁→ℤ d) i
/ lemℕ₊₁ b d b f i ]) ∙
(λ i → [ ℤ.·-distribʳ (a ℤ.· (c ℤ.· ℕ₊₁→ℤ f)) (a ℤ.· (e ℤ.· ℕ₊₁→ℤ d)) (ℕ₊₁→ℤ b) i
/ (b ·₊₁ (d ·₊₁ f)) ·₊₁ b ]) ∙
ℚ-cancelʳ {a ℤ.· (c ℤ.· ℕ₊₁→ℤ f) ℤ.+ a ℤ.· (e ℤ.· ℕ₊₁→ℤ d)} {b ·₊₁ (d ·₊₁ f)} b ∙
(λ i → [ ℤ.·-distribˡ a (c ℤ.· ℕ₊₁→ℤ f) (e ℤ.· ℕ₊₁→ℤ d) i
/ b ·₊₁ (d ·₊₁ f) ])
·-distribʳ : ∀ x y z → (x · z) + (y · z) ≡ (x + y) · z
·-distribʳ x y z = (λ i → ·-comm x z i + ·-comm y z i) ∙ ·-distribˡ z x y ∙ ·-comm z (x + y)
-_ : ℚ → ℚ
- x = -1 · x
negate-invol : ∀ x → - - x ≡ x
negate-invol x = ·-assoc -1 -1 x ∙ ·-identityˡ x
negateEquiv : ℚ ≃ ℚ
negateEquiv = isoToEquiv (iso -_ -_ negate-invol negate-invol)
negateEq : ℚ ≡ ℚ
negateEq = ua negateEquiv
+-inverseˡ : ∀ x → (- x) + x ≡ 0
+-inverseˡ x = (λ i → (-1 · x) + ·-identityˡ x (~ i)) ∙ ·-distribʳ -1 1 x ∙ ·-zeroˡ x
_-_ : ℚ → ℚ → ℚ
x - y = x + (- y)
+-inverseʳ : ∀ x → x - x ≡ 0
+-inverseʳ x = +-comm x (- x) ∙ +-inverseˡ x
+-injˡ : ∀ x y z → x + y ≡ x + z → y ≡ z
+-injˡ x y z p = sym (q y) ∙ cong ((- x) +_) p ∙ q z
where q : ∀ y → (- x) + (x + y) ≡ y
q y = +-assoc (- x) x y ∙ cong (_+ y) (+-inverseˡ x) ∙ +-identityˡ y
+-injʳ : ∀ x y z → x + y ≡ z + y → x ≡ z
+-injʳ x y z p = +-injˡ y x z (+-comm y x ∙ p ∙ +-comm z y)
|
[GOAL]
a b x : ℕ
⊢ x ∈ (fun a b => { val := ↑(List.range' a (b + 1 - a)), nodup := (_ : List.Nodup (List.range' a (b + 1 - a))) }) a b ↔
a ≤ x ∧ x ≤ b
[PROOFSTEP]
rw [Finset.mem_mk, Multiset.mem_coe, List.mem_range'_1]
[GOAL]
a b x : ℕ
⊢ a ≤ x ∧ x < a + (b + 1 - a) ↔ a ≤ x ∧ x ≤ b
[PROOFSTEP]
cases le_or_lt a b with
| inl h => rw [add_tsub_cancel_of_le (Nat.lt_succ_of_le h).le, Nat.lt_succ_iff]
| inr h =>
rw [tsub_eq_zero_iff_le.2 (succ_le_of_lt h), add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2)
[GOAL]
a b x : ℕ
x✝ : a ≤ b ∨ b < a
⊢ a ≤ x ∧ x < a + (b + 1 - a) ↔ a ≤ x ∧ x ≤ b
[PROOFSTEP]
cases le_or_lt a b with
| inl h => rw [add_tsub_cancel_of_le (Nat.lt_succ_of_le h).le, Nat.lt_succ_iff]
| inr h =>
rw [tsub_eq_zero_iff_le.2 (succ_le_of_lt h), add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2)
[GOAL]
case inl
a b x : ℕ
h : a ≤ b
⊢ a ≤ x ∧ x < a + (b + 1 - a) ↔ a ≤ x ∧ x ≤ b
[PROOFSTEP]
| inl h => rw [add_tsub_cancel_of_le (Nat.lt_succ_of_le h).le, Nat.lt_succ_iff]
[GOAL]
case inl
a b x : ℕ
h : a ≤ b
⊢ a ≤ x ∧ x < a + (b + 1 - a) ↔ a ≤ x ∧ x ≤ b
[PROOFSTEP]
rw [add_tsub_cancel_of_le (Nat.lt_succ_of_le h).le, Nat.lt_succ_iff]
[GOAL]
case inr
a b x : ℕ
h : b < a
⊢ a ≤ x ∧ x < a + (b + 1 - a) ↔ a ≤ x ∧ x ≤ b
[PROOFSTEP]
| inr h =>
rw [tsub_eq_zero_iff_le.2 (succ_le_of_lt h), add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2)
[GOAL]
case inr
a b x : ℕ
h : b < a
⊢ a ≤ x ∧ x < a + (b + 1 - a) ↔ a ≤ x ∧ x ≤ b
[PROOFSTEP]
rw [tsub_eq_zero_iff_le.2 (succ_le_of_lt h), add_zero]
[GOAL]
case inr
a b x : ℕ
h : b < a
⊢ a ≤ x ∧ x < a ↔ a ≤ x ∧ x ≤ b
[PROOFSTEP]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2)
[GOAL]
a b x : ℕ
⊢ x ∈ (fun a b => { val := ↑(List.range' a (b - a)), nodup := (_ : List.Nodup (List.range' a (b - a))) }) a b ↔
a ≤ x ∧ x < b
[PROOFSTEP]
rw [Finset.mem_mk, Multiset.mem_coe, List.mem_range'_1]
[GOAL]
a b x : ℕ
⊢ a ≤ x ∧ x < a + (b - a) ↔ a ≤ x ∧ x < b
[PROOFSTEP]
cases le_or_lt a b with
| inl h => rw [add_tsub_cancel_of_le h]
| inr h =>
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2.le)
[GOAL]
a b x : ℕ
x✝ : a ≤ b ∨ b < a
⊢ a ≤ x ∧ x < a + (b - a) ↔ a ≤ x ∧ x < b
[PROOFSTEP]
cases le_or_lt a b with
| inl h => rw [add_tsub_cancel_of_le h]
| inr h =>
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2.le)
[GOAL]
case inl
a b x : ℕ
h : a ≤ b
⊢ a ≤ x ∧ x < a + (b - a) ↔ a ≤ x ∧ x < b
[PROOFSTEP]
| inl h => rw [add_tsub_cancel_of_le h]
[GOAL]
case inl
a b x : ℕ
h : a ≤ b
⊢ a ≤ x ∧ x < a + (b - a) ↔ a ≤ x ∧ x < b
[PROOFSTEP]
rw [add_tsub_cancel_of_le h]
[GOAL]
case inr
a b x : ℕ
h : b < a
⊢ a ≤ x ∧ x < a + (b - a) ↔ a ≤ x ∧ x < b
[PROOFSTEP]
| inr h =>
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2.le)
[GOAL]
case inr
a b x : ℕ
h : b < a
⊢ a ≤ x ∧ x < a + (b - a) ↔ a ≤ x ∧ x < b
[PROOFSTEP]
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
[GOAL]
case inr
a b x : ℕ
h : b < a
⊢ a ≤ x ∧ x < a ↔ a ≤ x ∧ x < b
[PROOFSTEP]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2.le)
[GOAL]
a b x : ℕ
⊢ x ∈
(fun a b => { val := ↑(List.range' (a + 1) (b - a)), nodup := (_ : List.Nodup (List.range' (a + 1) (b - a))) }) a
b ↔
a < x ∧ x ≤ b
[PROOFSTEP]
rw [Finset.mem_mk, Multiset.mem_coe, List.mem_range'_1]
[GOAL]
a b x : ℕ
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - a) ↔ a < x ∧ x ≤ b
[PROOFSTEP]
cases le_or_lt a b with
| inl h => rw [← succ_sub_succ, add_tsub_cancel_of_le (succ_le_succ h), Nat.lt_succ_iff, Nat.succ_le_iff]
| inr h =>
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.le.trans hx.2)
[GOAL]
a b x : ℕ
x✝ : a ≤ b ∨ b < a
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - a) ↔ a < x ∧ x ≤ b
[PROOFSTEP]
cases le_or_lt a b with
| inl h => rw [← succ_sub_succ, add_tsub_cancel_of_le (succ_le_succ h), Nat.lt_succ_iff, Nat.succ_le_iff]
| inr h =>
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.le.trans hx.2)
[GOAL]
case inl
a b x : ℕ
h : a ≤ b
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - a) ↔ a < x ∧ x ≤ b
[PROOFSTEP]
| inl h => rw [← succ_sub_succ, add_tsub_cancel_of_le (succ_le_succ h), Nat.lt_succ_iff, Nat.succ_le_iff]
[GOAL]
case inl
a b x : ℕ
h : a ≤ b
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - a) ↔ a < x ∧ x ≤ b
[PROOFSTEP]
rw [← succ_sub_succ, add_tsub_cancel_of_le (succ_le_succ h), Nat.lt_succ_iff, Nat.succ_le_iff]
[GOAL]
case inr
a b x : ℕ
h : b < a
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - a) ↔ a < x ∧ x ≤ b
[PROOFSTEP]
| inr h =>
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.le.trans hx.2)
[GOAL]
case inr
a b x : ℕ
h : b < a
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - a) ↔ a < x ∧ x ≤ b
[PROOFSTEP]
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
[GOAL]
case inr
a b x : ℕ
h : b < a
⊢ a + 1 ≤ x ∧ x < a + 1 ↔ a < x ∧ x ≤ b
[PROOFSTEP]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.le.trans hx.2)
[GOAL]
a b x : ℕ
⊢ x ∈
(fun a b =>
{ val := ↑(List.range' (a + 1) (b - a - 1)), nodup := (_ : List.Nodup (List.range' (a + 1) (b - a - 1))) })
a b ↔
a < x ∧ x < b
[PROOFSTEP]
rw [Finset.mem_mk, Multiset.mem_coe, List.mem_range'_1, ← tsub_add_eq_tsub_tsub]
[GOAL]
a b x : ℕ
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - (a + 1)) ↔ a < x ∧ x < b
[PROOFSTEP]
cases le_or_lt (a + 1) b with
| inl h => rw [add_tsub_cancel_of_le h, Nat.succ_le_iff]
| inr h =>
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2)
[GOAL]
a b x : ℕ
x✝ : a + 1 ≤ b ∨ b < a + 1
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - (a + 1)) ↔ a < x ∧ x < b
[PROOFSTEP]
cases le_or_lt (a + 1) b with
| inl h => rw [add_tsub_cancel_of_le h, Nat.succ_le_iff]
| inr h =>
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2)
[GOAL]
case inl
a b x : ℕ
h : a + 1 ≤ b
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - (a + 1)) ↔ a < x ∧ x < b
[PROOFSTEP]
| inl h => rw [add_tsub_cancel_of_le h, Nat.succ_le_iff]
[GOAL]
case inl
a b x : ℕ
h : a + 1 ≤ b
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - (a + 1)) ↔ a < x ∧ x < b
[PROOFSTEP]
rw [add_tsub_cancel_of_le h, Nat.succ_le_iff]
[GOAL]
case inr
a b x : ℕ
h : b < a + 1
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - (a + 1)) ↔ a < x ∧ x < b
[PROOFSTEP]
| inr h =>
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2)
[GOAL]
case inr
a b x : ℕ
h : b < a + 1
⊢ a + 1 ≤ x ∧ x < a + 1 + (b - (a + 1)) ↔ a < x ∧ x < b
[PROOFSTEP]
rw [tsub_eq_zero_iff_le.2 h.le, add_zero]
[GOAL]
case inr
a b x : ℕ
h : b < a + 1
⊢ a + 1 ≤ x ∧ x < a + 1 ↔ a < x ∧ x < b
[PROOFSTEP]
exact iff_of_false (fun hx => hx.2.not_le hx.1) fun hx => h.not_le (hx.1.trans hx.2)
[GOAL]
a b c : ℕ
⊢ Iio = range
[PROOFSTEP]
ext b x
[GOAL]
case h.a
a b✝ c b x : ℕ
⊢ x ∈ Iio b ↔ x ∈ range b
[PROOFSTEP]
rw [mem_Iio, mem_range]
[GOAL]
a b c : ℕ
⊢ Ico 0 = range
[PROOFSTEP]
rw [← bot_eq_zero, ← Iio_eq_Ico, Iio_eq_range]
[GOAL]
a b c : ℕ
⊢ card (uIcc a b) = Int.natAbs (↑b - ↑a) + 1
[PROOFSTEP]
refine' (card_Icc _ _).trans (Int.ofNat.inj _)
[GOAL]
a b c : ℕ
⊢ Int.ofNat (a ⊔ b + 1 - a ⊓ b) = Int.ofNat (Int.natAbs (↑b - ↑a) + 1)
[PROOFSTEP]
change ((↑) : ℕ → ℤ) _ = _
[GOAL]
a b c : ℕ
⊢ ↑(a ⊔ b + 1 - a ⊓ b) = Int.ofNat (Int.natAbs (↑b - ↑a) + 1)
[PROOFSTEP]
rw [sup_eq_max, inf_eq_min, Int.ofNat_sub]
[GOAL]
a b c : ℕ
⊢ ↑(max a b + 1) - ↑(min a b) = Int.ofNat (Int.natAbs (↑b - ↑a) + 1)
[PROOFSTEP]
rw [add_comm, Int.ofNat_add, add_sub_assoc]
-- porting note: `norm_cast` puts a `Int.subSubNat` in the goal
-- norm_cast
[GOAL]
a b c : ℕ
⊢ ↑1 + (↑(max a b) - ↑(min a b)) = Int.ofNat (Int.natAbs (↑b - ↑a) + 1)
[PROOFSTEP]
change _ = ↑(Int.natAbs (b - a) + 1)
[GOAL]
a b c : ℕ
⊢ ↑1 + (↑(max a b) - ↑(min a b)) = ↑(Int.natAbs (↑b - ↑a) + 1)
[PROOFSTEP]
push_cast
[GOAL]
a b c : ℕ
⊢ 1 + (max ↑a ↑b - min ↑a ↑b) = |↑b - ↑a| + 1
[PROOFSTEP]
rw [max_sub_min_eq_abs, add_comm]
[GOAL]
a b c : ℕ
⊢ min a b ≤ max a b + 1
[PROOFSTEP]
exact min_le_max.trans le_self_add
[GOAL]
a b c : ℕ
⊢ card (Iic b) = b + 1
[PROOFSTEP]
rw [Iic_eq_Icc, card_Icc, bot_eq_zero, tsub_zero]
[GOAL]
a b c : ℕ
⊢ card (Iio b) = b
[PROOFSTEP]
rw [Iio_eq_Ico, card_Ico, bot_eq_zero, tsub_zero]
[GOAL]
a b c : ℕ
⊢ Fintype.card ↑(Set.Icc a b) = b + 1 - a
[PROOFSTEP]
rw [Fintype.card_ofFinset, card_Icc]
[GOAL]
a b c : ℕ
⊢ Fintype.card ↑(Set.Ico a b) = b - a
[PROOFSTEP]
rw [Fintype.card_ofFinset, card_Ico]
[GOAL]
a b c : ℕ
⊢ Fintype.card ↑(Set.Ioc a b) = b - a
[PROOFSTEP]
rw [Fintype.card_ofFinset, card_Ioc]
[GOAL]
a b c : ℕ
⊢ Fintype.card ↑(Set.Ioo a b) = b - a - 1
[PROOFSTEP]
rw [Fintype.card_ofFinset, card_Ioo]
[GOAL]
a b c : ℕ
⊢ Fintype.card ↑(Set.Iic b) = b + 1
[PROOFSTEP]
rw [Fintype.card_ofFinset, card_Iic]
[GOAL]
a b c : ℕ
⊢ Fintype.card ↑(Set.Iio b) = b
[PROOFSTEP]
rw [Fintype.card_ofFinset, card_Iio]
[GOAL]
a b c : ℕ
⊢ Icc (succ a) b = Ioc a b
[PROOFSTEP]
ext x
[GOAL]
case a
a b c x : ℕ
⊢ x ∈ Icc (succ a) b ↔ x ∈ Ioc a b
[PROOFSTEP]
rw [mem_Icc, mem_Ioc, succ_le_iff]
[GOAL]
a b c : ℕ
⊢ Ico a (succ b) = Icc a b
[PROOFSTEP]
ext x
[GOAL]
case a
a b c x : ℕ
⊢ x ∈ Ico a (succ b) ↔ x ∈ Icc a b
[PROOFSTEP]
rw [mem_Ico, mem_Icc, lt_succ_iff]
[GOAL]
a b c : ℕ
⊢ Ico (succ a) b = Ioo a b
[PROOFSTEP]
ext x
[GOAL]
case a
a b c x : ℕ
⊢ x ∈ Ico (succ a) b ↔ x ∈ Ioo a b
[PROOFSTEP]
rw [mem_Ico, mem_Ioo, succ_le_iff]
[GOAL]
a b✝ c b : ℕ
h : 0 < b
⊢ Icc a (b - 1) = Ico a b
[PROOFSTEP]
ext x
[GOAL]
case a
a b✝ c b : ℕ
h : 0 < b
x : ℕ
⊢ x ∈ Icc a (b - 1) ↔ x ∈ Ico a b
[PROOFSTEP]
rw [mem_Icc, mem_Ico, lt_iff_le_pred h]
[GOAL]
a b c : ℕ
⊢ Ico (succ a) (succ b) = Ioc a b
[PROOFSTEP]
ext x
[GOAL]
case a
a b c x : ℕ
⊢ x ∈ Ico (succ a) (succ b) ↔ x ∈ Ioc a b
[PROOFSTEP]
rw [mem_Ico, mem_Ioc, succ_le_iff, lt_succ_iff]
[GOAL]
a b c : ℕ
⊢ Ico a (a + 1) = {a}
[PROOFSTEP]
rw [Ico_succ_right, Icc_self]
[GOAL]
a✝ b c a : ℕ
h : 0 < a
⊢ Ico (a - 1) a = {a - 1}
[PROOFSTEP]
rw [← Icc_pred_right _ h, Icc_self]
[GOAL]
a b c : ℕ
⊢ Ioc b (b + 1) = {b + 1}
[PROOFSTEP]
rw [← Nat.Icc_succ_left, Icc_self]
[GOAL]
a b c : ℕ
h : a ≤ b
⊢ Ico a (b + 1) = insert b (Ico a b)
[PROOFSTEP]
rw [Ico_succ_right, ← Ico_insert_right h]
[GOAL]
a b c : ℕ
h : a < b
⊢ insert a (Ico (succ a) b) = Ico a b
[PROOFSTEP]
rw [Ico_succ_left, ← Ioo_insert_left h]
[GOAL]
a b c : ℕ
h : c ≤ a
⊢ image (fun x => x - c) (Ico a b) = Ico (a - c) (b - c)
[PROOFSTEP]
ext x
[GOAL]
case a
a b c : ℕ
h : c ≤ a
x : ℕ
⊢ x ∈ image (fun x => x - c) (Ico a b) ↔ x ∈ Ico (a - c) (b - c)
[PROOFSTEP]
rw [mem_image]
[GOAL]
case a
a b c : ℕ
h : c ≤ a
x : ℕ
⊢ (∃ a_1, a_1 ∈ Ico a b ∧ a_1 - c = x) ↔ x ∈ Ico (a - c) (b - c)
[PROOFSTEP]
constructor
[GOAL]
case a.mp
a b c : ℕ
h : c ≤ a
x : ℕ
⊢ (∃ a_1, a_1 ∈ Ico a b ∧ a_1 - c = x) → x ∈ Ico (a - c) (b - c)
[PROOFSTEP]
rintro ⟨x, hx, rfl⟩
[GOAL]
case a.mp.intro.intro
a b c : ℕ
h : c ≤ a
x : ℕ
hx : x ∈ Ico a b
⊢ x - c ∈ Ico (a - c) (b - c)
[PROOFSTEP]
rw [mem_Ico] at hx ⊢
[GOAL]
case a.mp.intro.intro
a b c : ℕ
h : c ≤ a
x : ℕ
hx : a ≤ x ∧ x < b
⊢ a - c ≤ x - c ∧ x - c < b - c
[PROOFSTEP]
exact ⟨tsub_le_tsub_right hx.1 _, tsub_lt_tsub_right_of_le (h.trans hx.1) hx.2⟩
[GOAL]
case a.mpr
a b c : ℕ
h : c ≤ a
x : ℕ
⊢ x ∈ Ico (a - c) (b - c) → ∃ a_2, a_2 ∈ Ico a b ∧ a_2 - c = x
[PROOFSTEP]
rintro h
[GOAL]
case a.mpr
a b c : ℕ
h✝ : c ≤ a
x : ℕ
h : x ∈ Ico (a - c) (b - c)
⊢ ∃ a_1, a_1 ∈ Ico a b ∧ a_1 - c = x
[PROOFSTEP]
refine' ⟨x + c, _, add_tsub_cancel_right _ _⟩
[GOAL]
case a.mpr
a b c : ℕ
h✝ : c ≤ a
x : ℕ
h : x ∈ Ico (a - c) (b - c)
⊢ x + c ∈ Ico a b
[PROOFSTEP]
rw [mem_Ico] at h ⊢
[GOAL]
case a.mpr
a b c : ℕ
h✝ : c ≤ a
x : ℕ
h : a - c ≤ x ∧ x < b - c
⊢ a ≤ x + c ∧ x + c < b
[PROOFSTEP]
exact ⟨tsub_le_iff_right.1 h.1, lt_tsub_iff_right.1 h.2⟩
[GOAL]
a b c : ℕ
hac : a ≤ c
⊢ image (fun x => c - x) (Ico a b) = Ico (c + 1 - b) (c + 1 - a)
[PROOFSTEP]
ext x
[GOAL]
case a
a b c : ℕ
hac : a ≤ c
x : ℕ
⊢ x ∈ image (fun x => c - x) (Ico a b) ↔ x ∈ Ico (c + 1 - b) (c + 1 - a)
[PROOFSTEP]
rw [mem_image, mem_Ico]
[GOAL]
case a
a b c : ℕ
hac : a ≤ c
x : ℕ
⊢ (∃ a_1, a_1 ∈ Ico a b ∧ c - a_1 = x) ↔ c + 1 - b ≤ x ∧ x < c + 1 - a
[PROOFSTEP]
constructor
[GOAL]
case a.mp
a b c : ℕ
hac : a ≤ c
x : ℕ
⊢ (∃ a_1, a_1 ∈ Ico a b ∧ c - a_1 = x) → c + 1 - b ≤ x ∧ x < c + 1 - a
[PROOFSTEP]
rintro ⟨x, hx, rfl⟩
[GOAL]
case a.mp.intro.intro
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : x ∈ Ico a b
⊢ c + 1 - b ≤ c - x ∧ c - x < c + 1 - a
[PROOFSTEP]
rw [mem_Ico] at hx
[GOAL]
case a.mp.intro.intro
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : a ≤ x ∧ x < b
⊢ c + 1 - b ≤ c - x ∧ c - x < c + 1 - a
[PROOFSTEP]
refine' ⟨_, ((tsub_le_tsub_iff_left hac).2 hx.1).trans_lt ((tsub_lt_tsub_iff_right hac).2 (Nat.lt_succ_self _))⟩
[GOAL]
case a.mp.intro.intro
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : a ≤ x ∧ x < b
⊢ c + 1 - b ≤ c - x
[PROOFSTEP]
cases lt_or_le c b with
| inl h =>
rw [tsub_eq_zero_iff_le.mpr (succ_le_of_lt h)]
exact zero_le _
| inr h =>
rw [← succ_sub_succ c]
exact (tsub_le_tsub_iff_left (succ_le_succ <| hx.2.le.trans h)).2 hx.2
[GOAL]
case a.mp.intro.intro
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : a ≤ x ∧ x < b
x✝ : c < b ∨ b ≤ c
⊢ c + 1 - b ≤ c - x
[PROOFSTEP]
cases lt_or_le c b with
| inl h =>
rw [tsub_eq_zero_iff_le.mpr (succ_le_of_lt h)]
exact zero_le _
| inr h =>
rw [← succ_sub_succ c]
exact (tsub_le_tsub_iff_left (succ_le_succ <| hx.2.le.trans h)).2 hx.2
[GOAL]
case a.mp.intro.intro.inl
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : a ≤ x ∧ x < b
h : c < b
⊢ c + 1 - b ≤ c - x
[PROOFSTEP]
| inl h =>
rw [tsub_eq_zero_iff_le.mpr (succ_le_of_lt h)]
exact zero_le _
[GOAL]
case a.mp.intro.intro.inl
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : a ≤ x ∧ x < b
h : c < b
⊢ c + 1 - b ≤ c - x
[PROOFSTEP]
rw [tsub_eq_zero_iff_le.mpr (succ_le_of_lt h)]
[GOAL]
case a.mp.intro.intro.inl
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : a ≤ x ∧ x < b
h : c < b
⊢ 0 ≤ c - x
[PROOFSTEP]
exact zero_le _
[GOAL]
case a.mp.intro.intro.inr
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : a ≤ x ∧ x < b
h : b ≤ c
⊢ c + 1 - b ≤ c - x
[PROOFSTEP]
| inr h =>
rw [← succ_sub_succ c]
exact (tsub_le_tsub_iff_left (succ_le_succ <| hx.2.le.trans h)).2 hx.2
[GOAL]
case a.mp.intro.intro.inr
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : a ≤ x ∧ x < b
h : b ≤ c
⊢ c + 1 - b ≤ c - x
[PROOFSTEP]
rw [← succ_sub_succ c]
[GOAL]
case a.mp.intro.intro.inr
a b c : ℕ
hac : a ≤ c
x : ℕ
hx : a ≤ x ∧ x < b
h : b ≤ c
⊢ c + 1 - b ≤ succ c - succ x
[PROOFSTEP]
exact (tsub_le_tsub_iff_left (succ_le_succ <| hx.2.le.trans h)).2 hx.2
[GOAL]
case a.mpr
a b c : ℕ
hac : a ≤ c
x : ℕ
⊢ c + 1 - b ≤ x ∧ x < c + 1 - a → ∃ a_2, a_2 ∈ Ico a b ∧ c - a_2 = x
[PROOFSTEP]
rintro ⟨hb, ha⟩
[GOAL]
case a.mpr.intro
a b c : ℕ
hac : a ≤ c
x : ℕ
hb : c + 1 - b ≤ x
ha : x < c + 1 - a
⊢ ∃ a_1, a_1 ∈ Ico a b ∧ c - a_1 = x
[PROOFSTEP]
rw [lt_tsub_iff_left, lt_succ_iff] at ha
[GOAL]
case a.mpr.intro
a b c : ℕ
hac : a ≤ c
x : ℕ
hb : c + 1 - b ≤ x
ha✝ : x < c + 1 - a
ha : a + x ≤ c
⊢ ∃ a_1, a_1 ∈ Ico a b ∧ c - a_1 = x
[PROOFSTEP]
have hx : x ≤ c := (Nat.le_add_left _ _).trans ha
[GOAL]
case a.mpr.intro
a b c : ℕ
hac : a ≤ c
x : ℕ
hb : c + 1 - b ≤ x
ha✝ : x < c + 1 - a
ha : a + x ≤ c
hx : x ≤ c
⊢ ∃ a_1, a_1 ∈ Ico a b ∧ c - a_1 = x
[PROOFSTEP]
refine' ⟨c - x, _, tsub_tsub_cancel_of_le hx⟩
[GOAL]
case a.mpr.intro
a b c : ℕ
hac : a ≤ c
x : ℕ
hb : c + 1 - b ≤ x
ha✝ : x < c + 1 - a
ha : a + x ≤ c
hx : x ≤ c
⊢ c - x ∈ Ico a b
[PROOFSTEP]
rw [mem_Ico]
[GOAL]
case a.mpr.intro
a b c : ℕ
hac : a ≤ c
x : ℕ
hb : c + 1 - b ≤ x
ha✝ : x < c + 1 - a
ha : a + x ≤ c
hx : x ≤ c
⊢ a ≤ c - x ∧ c - x < b
[PROOFSTEP]
exact ⟨le_tsub_of_add_le_right ha, (tsub_lt_iff_left hx).2 <| succ_le_iff.1 <| tsub_le_iff_right.1 hb⟩
[GOAL]
a b c : ℕ
⊢ Ico (succ a) b = erase (Ico a b) a
[PROOFSTEP]
ext x
[GOAL]
case a
a b c x : ℕ
⊢ x ∈ Ico (succ a) b ↔ x ∈ erase (Ico a b) a
[PROOFSTEP]
rw [Ico_succ_left, mem_erase, mem_Ico, mem_Ioo, ← and_assoc, ne_comm, @and_comm (a ≠ x), lt_iff_le_and_ne]
[GOAL]
a✝ b c n a : ℕ
⊢ Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
[PROOFSTEP]
induction' n with n ih
[GOAL]
case zero
a✝ b c a : ℕ
⊢ Set.InjOn (fun x => x % a) ↑(Ico zero (zero + a))
[PROOFSTEP]
simp only [zero_add, Nat.zero_eq, Ico_zero_eq_range]
[GOAL]
case zero
a✝ b c a : ℕ
⊢ Set.InjOn (fun x => x % a) ↑(range a)
[PROOFSTEP]
rintro k hk l hl (hkl : k % a = l % a)
[GOAL]
case zero
a✝ b c a k : ℕ
hk : k ∈ ↑(range a)
l : ℕ
hl : l ∈ ↑(range a)
hkl : k % a = l % a
⊢ k = l
[PROOFSTEP]
simp only [Finset.mem_range, Finset.mem_coe] at hk hl
[GOAL]
case zero
a✝ b c a k l : ℕ
hkl : k % a = l % a
hk : k < a
hl : l < a
⊢ k = l
[PROOFSTEP]
rwa [mod_eq_of_lt hk, mod_eq_of_lt hl] at hkl
[GOAL]
case succ
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
⊢ Set.InjOn (fun x => x % a) ↑(Ico (succ n) (succ n + a))
[PROOFSTEP]
rw [Ico_succ_left_eq_erase_Ico, succ_add, succ_eq_add_one, Ico_succ_right_eq_insert_Ico le_self_add]
[GOAL]
case succ
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
⊢ Set.InjOn (fun x => x % a) ↑(erase (insert (n + a) (Ico n (n + a))) n)
[PROOFSTEP]
rintro k hk l hl (hkl : k % a = l % a)
[GOAL]
case succ
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
hk : k ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
l : ℕ
hl : l ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
hkl : k % a = l % a
⊢ k = l
[PROOFSTEP]
have ha : 0 < a := by
by_contra ha
simp only [not_lt, nonpos_iff_eq_zero] at ha
simp [ha] at hk
[GOAL]
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
hk : k ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
l : ℕ
hl : l ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
hkl : k % a = l % a
⊢ 0 < a
[PROOFSTEP]
by_contra ha
[GOAL]
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
hk : k ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
l : ℕ
hl : l ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
hkl : k % a = l % a
ha : ¬0 < a
⊢ False
[PROOFSTEP]
simp only [not_lt, nonpos_iff_eq_zero] at ha
[GOAL]
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
hk : k ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
l : ℕ
hl : l ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
hkl : k % a = l % a
ha : a = 0
⊢ False
[PROOFSTEP]
simp [ha] at hk
[GOAL]
case succ
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
hk : k ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
l : ℕ
hl : l ∈ ↑(erase (insert (n + a) (Ico n (n + a))) n)
hkl : k % a = l % a
ha : 0 < a
⊢ k = l
[PROOFSTEP]
simp only [Finset.mem_coe, Finset.mem_insert, Finset.mem_erase] at hk hl
[GOAL]
case succ
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k l : ℕ
hkl : k % a = l % a
ha : 0 < a
hk : k ≠ n ∧ (k = n + a ∨ k ∈ Ico n (n + a))
hl : l ≠ n ∧ (l = n + a ∨ l ∈ Ico n (n + a))
⊢ k = l
[PROOFSTEP]
rcases hk with ⟨hkn, rfl | hk⟩
[GOAL]
case succ.intro.inl
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
l : ℕ
ha : 0 < a
hl : l ≠ n ∧ (l = n + a ∨ l ∈ Ico n (n + a))
hkl : (n + a) % a = l % a
hkn : n + a ≠ n
⊢ n + a = l
[PROOFSTEP]
rcases hl with ⟨hln, rfl | hl⟩
[GOAL]
case succ.intro.inr
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k l : ℕ
hkl : k % a = l % a
ha : 0 < a
hl : l ≠ n ∧ (l = n + a ∨ l ∈ Ico n (n + a))
hkn : k ≠ n
hk : k ∈ Ico n (n + a)
⊢ k = l
[PROOFSTEP]
rcases hl with ⟨hln, rfl | hl⟩
[GOAL]
case succ.intro.inl.intro.inl
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
ha : 0 < a
hkn : n + a ≠ n
hkl : (n + a) % a = (n + a) % a
hln : n + a ≠ n
⊢ n + a = n + a
[PROOFSTEP]
rfl
[GOAL]
case succ.intro.inl.intro.inr
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
l : ℕ
ha : 0 < a
hkl : (n + a) % a = l % a
hkn : n + a ≠ n
hln : l ≠ n
hl : l ∈ Ico n (n + a)
⊢ n + a = l
[PROOFSTEP]
rw [add_mod_right] at hkl
[GOAL]
case succ.intro.inl.intro.inr
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
l : ℕ
ha : 0 < a
hkl : n % a = l % a
hkn : n + a ≠ n
hln : l ≠ n
hl : l ∈ Ico n (n + a)
⊢ n + a = l
[PROOFSTEP]
refine' (hln <| ih hl _ hkl.symm).elim
[GOAL]
case succ.intro.inl.intro.inr
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
l : ℕ
ha : 0 < a
hkl : n % a = l % a
hkn : n + a ≠ n
hln : l ≠ n
hl : l ∈ Ico n (n + a)
⊢ n ∈ ↑(Ico n (n + a))
[PROOFSTEP]
simp only [lt_add_iff_pos_right, Set.left_mem_Ico, Finset.coe_Ico, ha]
[GOAL]
case succ.intro.inr.intro.inl
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
ha : 0 < a
hkn : k ≠ n
hk : k ∈ Ico n (n + a)
hkl : k % a = (n + a) % a
hln : n + a ≠ n
⊢ k = n + a
[PROOFSTEP]
rw [add_mod_right] at hkl
[GOAL]
case succ.intro.inr.intro.inl
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
ha : 0 < a
hkn : k ≠ n
hk : k ∈ Ico n (n + a)
hkl : k % a = n % a
hln : n + a ≠ n
⊢ k = n + a
[PROOFSTEP]
suffices k = n by contradiction
[GOAL]
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
ha : 0 < a
hkn : k ≠ n
hk : k ∈ Ico n (n + a)
hkl : k % a = n % a
hln : n + a ≠ n
this : k = n
⊢ k = n + a
[PROOFSTEP]
contradiction
[GOAL]
case succ.intro.inr.intro.inl
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
ha : 0 < a
hkn : k ≠ n
hk : k ∈ Ico n (n + a)
hkl : k % a = n % a
hln : n + a ≠ n
⊢ k = n
[PROOFSTEP]
refine' ih hk _ hkl
[GOAL]
case succ.intro.inr.intro.inl
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k : ℕ
ha : 0 < a
hkn : k ≠ n
hk : k ∈ Ico n (n + a)
hkl : k % a = n % a
hln : n + a ≠ n
⊢ n ∈ ↑(Ico n (n + a))
[PROOFSTEP]
simp only [lt_add_iff_pos_right, Set.left_mem_Ico, Finset.coe_Ico, ha]
[GOAL]
case succ.intro.inr.intro.inr
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k l : ℕ
hkl : k % a = l % a
ha : 0 < a
hkn : k ≠ n
hk : k ∈ Ico n (n + a)
hln : l ≠ n
hl : l ∈ Ico n (n + a)
⊢ k = l
[PROOFSTEP]
refine' ih _ _ hkl
[GOAL]
case succ.intro.inr.intro.inr.refine'_1
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k l : ℕ
hkl : k % a = l % a
ha : 0 < a
hkn : k ≠ n
hk : k ∈ Ico n (n + a)
hln : l ≠ n
hl : l ∈ Ico n (n + a)
⊢ k ∈ ↑(Ico n (n + a))
[PROOFSTEP]
simp only [Finset.mem_coe, hk, hl]
[GOAL]
case succ.intro.inr.intro.inr.refine'_2
a✝ b c a n : ℕ
ih : Set.InjOn (fun x => x % a) ↑(Ico n (n + a))
k l : ℕ
hkl : k % a = l % a
ha : 0 < a
hkn : k ≠ n
hk : k ∈ Ico n (n + a)
hln : l ≠ n
hl : l ∈ Ico n (n + a)
⊢ l ∈ ↑(Ico n (n + a))
[PROOFSTEP]
simp only [Finset.mem_coe, hk, hl]
[GOAL]
a✝ b c n a : ℕ
⊢ image (fun x => x % a) (Ico n (n + a)) = range a
[PROOFSTEP]
obtain rfl | ha := eq_or_ne a 0
[GOAL]
case inl
a b c n : ℕ
⊢ image (fun x => x % 0) (Ico n (n + 0)) = range 0
[PROOFSTEP]
rw [range_zero, add_zero, Ico_self, image_empty]
[GOAL]
case inr
a✝ b c n a : ℕ
ha : a ≠ 0
⊢ image (fun x => x % a) (Ico n (n + a)) = range a
[PROOFSTEP]
ext i
[GOAL]
case inr.a
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
⊢ i ∈ image (fun x => x % a) (Ico n (n + a)) ↔ i ∈ range a
[PROOFSTEP]
simp only [mem_image, exists_prop, mem_range, mem_Ico]
[GOAL]
case inr.a
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
⊢ (∃ a_1, (n ≤ a_1 ∧ a_1 < n + a) ∧ a_1 % a = i) ↔ i < a
[PROOFSTEP]
constructor
[GOAL]
case inr.a.mp
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
⊢ (∃ a_1, (n ≤ a_1 ∧ a_1 < n + a) ∧ a_1 % a = i) → i < a
[PROOFSTEP]
rintro ⟨i, _, rfl⟩
[GOAL]
case inr.a.mp.intro.intro
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
left✝ : n ≤ i ∧ i < n + a
⊢ i % a < a
[PROOFSTEP]
exact mod_lt i ha.bot_lt
[GOAL]
case inr.a.mpr
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
⊢ i < a → ∃ a_2, (n ≤ a_2 ∧ a_2 < n + a) ∧ a_2 % a = i
[PROOFSTEP]
intro hia
[GOAL]
case inr.a.mpr
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
⊢ ∃ a_1, (n ≤ a_1 ∧ a_1 < n + a) ∧ a_1 % a = i
[PROOFSTEP]
have hn := Nat.mod_add_div n a
[GOAL]
case inr.a.mpr
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
⊢ ∃ a_1, (n ≤ a_1 ∧ a_1 < n + a) ∧ a_1 % a = i
[PROOFSTEP]
obtain hi | hi := lt_or_le i (n % a)
[GOAL]
case inr.a.mpr.inl
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : i < n % a
⊢ ∃ a_1, (n ≤ a_1 ∧ a_1 < n + a) ∧ a_1 % a = i
[PROOFSTEP]
refine' ⟨i + a * (n / a + 1), ⟨_, _⟩, _⟩
[GOAL]
case inr.a.mpr.inl.refine'_1
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : i < n % a
⊢ n ≤ i + a * (n / a + 1)
[PROOFSTEP]
rw [add_comm (n / a), mul_add, mul_one, ← add_assoc]
[GOAL]
case inr.a.mpr.inl.refine'_1
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : i < n % a
⊢ n ≤ i + a + a * (n / a)
[PROOFSTEP]
refine' hn.symm.le.trans (add_le_add_right _ _)
[GOAL]
case inr.a.mpr.inl.refine'_1
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : i < n % a
⊢ n % a ≤ i + a
[PROOFSTEP]
simpa only [zero_add] using add_le_add (zero_le i) (Nat.mod_lt n ha.bot_lt).le
[GOAL]
case inr.a.mpr.inl.refine'_2
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : i < n % a
⊢ i + a * (n / a + 1) < n + a
[PROOFSTEP]
refine' lt_of_lt_of_le (add_lt_add_right hi (a * (n / a + 1))) _
[GOAL]
case inr.a.mpr.inl.refine'_2
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : i < n % a
⊢ n % a + a * (n / a + 1) ≤ n + a
[PROOFSTEP]
rw [mul_add, mul_one, ← add_assoc, hn]
[GOAL]
case inr.a.mpr.inl.refine'_3
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : i < n % a
⊢ (i + a * (n / a + 1)) % a = i
[PROOFSTEP]
rw [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hia]
[GOAL]
case inr.a.mpr.inr
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : n % a ≤ i
⊢ ∃ a_1, (n ≤ a_1 ∧ a_1 < n + a) ∧ a_1 % a = i
[PROOFSTEP]
refine' ⟨i + a * (n / a), ⟨_, _⟩, _⟩
[GOAL]
case inr.a.mpr.inr.refine'_1
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : n % a ≤ i
⊢ n ≤ i + a * (n / a)
[PROOFSTEP]
exact hn.symm.le.trans (add_le_add_right hi _)
[GOAL]
case inr.a.mpr.inr.refine'_2
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : n % a ≤ i
⊢ i + a * (n / a) < n + a
[PROOFSTEP]
rw [add_comm n a]
[GOAL]
case inr.a.mpr.inr.refine'_2
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : n % a ≤ i
⊢ i + a * (n / a) < a + n
[PROOFSTEP]
refine' add_lt_add_of_lt_of_le hia (le_trans _ hn.le)
[GOAL]
case inr.a.mpr.inr.refine'_2
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : n % a ≤ i
⊢ a * (n / a) ≤ n % a + a * (n / a)
[PROOFSTEP]
simp only [zero_le, le_add_iff_nonneg_left]
[GOAL]
case inr.a.mpr.inr.refine'_3
a✝ b c n a : ℕ
ha : a ≠ 0
i : ℕ
hia : i < a
hn : n % a + a * (n / a) = n
hi : n % a ≤ i
⊢ (i + a * (n / a)) % a = i
[PROOFSTEP]
rw [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hia]
[GOAL]
a✝ b c n a : ℕ
⊢ Multiset.map (fun x => x % a) (Multiset.Ico n (n + a)) = Multiset.range a
[PROOFSTEP]
convert congr_arg Finset.val (image_Ico_mod n a)
[GOAL]
case h.e'_2
a✝ b c n a : ℕ
⊢ Multiset.map (fun x => x % a) (Multiset.Ico n (n + a)) = (image (fun x => x % a) (Finset.Ico n (n + a))).val
[PROOFSTEP]
refine' ((nodup_map_iff_inj_on (Finset.Ico _ _).nodup).2 <| _).dedup.symm
[GOAL]
case h.e'_2
a✝ b c n a : ℕ
⊢ ∀ (x : ℕ), x ∈ (Finset.Ico n (n + a)).val → ∀ (y : ℕ), y ∈ (Finset.Ico n (n + a)).val → x % a = y % a → x = y
[PROOFSTEP]
exact mod_injOn_Ico _ _
[GOAL]
a b c n : ℕ
⊢ image (fun j => n - 1 - j) (range n) = range n
[PROOFSTEP]
cases n
[GOAL]
case zero
a b c : ℕ
⊢ image (fun j => zero - 1 - j) (range zero) = range zero
[PROOFSTEP]
rw [range_zero, image_empty]
[GOAL]
case succ
a b c n✝ : ℕ
⊢ image (fun j => succ n✝ - 1 - j) (range (succ n✝)) = range (succ n✝)
[PROOFSTEP]
rw [Finset.range_eq_Ico, Nat.Ico_image_const_sub_eq_Ico (Nat.zero_le _)]
[GOAL]
case succ
a b c n✝ : ℕ
⊢ Ico (succ n✝ - 1 + 1 - succ n✝) (succ n✝ - 1 + 1 - 0) = Ico 0 (succ n✝)
[PROOFSTEP]
simp_rw [succ_sub_succ, tsub_zero, tsub_self]
[GOAL]
a b c : ℕ
⊢ range (a + b) = range a ∪ map (addLeftEmbedding a) (range b)
[PROOFSTEP]
rw [Finset.range_eq_Ico, map_eq_image]
[GOAL]
a b c : ℕ
⊢ Ico 0 (a + b) = Ico 0 a ∪ image (↑(addLeftEmbedding a)) (Ico 0 b)
[PROOFSTEP]
convert (@Ico_union_Ico_eq_Ico _ _ _ _ _ (a + b) a.zero_le le_self_add).symm
[GOAL]
case h.e'_3.h.e'_4
a b c : ℕ
⊢ image (↑(addLeftEmbedding a)) (Ico 0 b) = Ico a (a + b)
[PROOFSTEP]
exact image_add_left_Ico _ _ _
[GOAL]
a b c : ℕ
P : ℕ → Prop
h : ∀ (n : ℕ), P (n + 1) → P n
seed : ℕ
hs : P seed
hi : ∀ (x : ℕ), seed ≤ x → P x → ∃ y, x < y ∧ P y
n : ℕ
⊢ P n
[PROOFSTEP]
apply Nat.decreasing_induction_of_infinite h fun hf => _
[GOAL]
a b c : ℕ
P : ℕ → Prop
h : ∀ (n : ℕ), P (n + 1) → P n
seed : ℕ
hs : P seed
hi : ∀ (x : ℕ), seed ≤ x → P x → ∃ y, x < y ∧ P y
n : ℕ
⊢ Set.Finite {x | P x} → False
[PROOFSTEP]
intro hf
[GOAL]
a b c : ℕ
P : ℕ → Prop
h : ∀ (n : ℕ), P (n + 1) → P n
seed : ℕ
hs : P seed
hi : ∀ (x : ℕ), seed ≤ x → P x → ∃ y, x < y ∧ P y
n : ℕ
hf : Set.Finite {x | P x}
⊢ False
[PROOFSTEP]
obtain ⟨m, hP, hm⟩ := hf.exists_maximal_wrt id _ ⟨seed, hs⟩
[GOAL]
case intro.intro
a b c : ℕ
P : ℕ → Prop
h : ∀ (n : ℕ), P (n + 1) → P n
seed : ℕ
hs : P seed
hi : ∀ (x : ℕ), seed ≤ x → P x → ∃ y, x < y ∧ P y
n : ℕ
hf : Set.Finite {x | P x}
m : ℕ
hP : m ∈ {x | P x}
hm : ∀ (a' : ℕ), a' ∈ {x | P x} → id m ≤ id a' → id m = id a'
⊢ False
[PROOFSTEP]
obtain ⟨y, hl, hy⟩ := hi m (le_of_not_lt fun hl => hl.ne <| hm seed hs hl.le) hP
[GOAL]
case intro.intro.intro.intro
a b c : ℕ
P : ℕ → Prop
h : ∀ (n : ℕ), P (n + 1) → P n
seed : ℕ
hs : P seed
hi : ∀ (x : ℕ), seed ≤ x → P x → ∃ y, x < y ∧ P y
n : ℕ
hf : Set.Finite {x | P x}
m : ℕ
hP : m ∈ {x | P x}
hm : ∀ (a' : ℕ), a' ∈ {x | P x} → id m ≤ id a' → id m = id a'
y : ℕ
hl : m < y
hy : P y
⊢ False
[PROOFSTEP]
exact hl.ne (hm y hy hl.le)
[GOAL]
a b c : ℕ
P : ℕ → Prop
h : ∀ (n : ℕ), P (n + 1) → P n
k seed : ℕ
hk : 1 < k
hs : P (succ seed)
hm : ∀ (x : ℕ), seed < x → P x → P (k * x)
n : ℕ
⊢ P n
[PROOFSTEP]
apply Nat.cauchy_induction h _ hs ((· * ·) k) fun x hl hP => ⟨_, hm x hl hP⟩
[GOAL]
a b c : ℕ
P : ℕ → Prop
h : ∀ (n : ℕ), P (n + 1) → P n
k seed : ℕ
hk : 1 < k
hs : P (succ seed)
hm : ∀ (x : ℕ), seed < x → P x → P (k * x)
n : ℕ
⊢ ∀ (x : ℕ), succ seed ≤ x → P x → x < (fun x x_1 => x * x_1) k x
[PROOFSTEP]
intro _ hl _
[GOAL]
a b c : ℕ
P : ℕ → Prop
h : ∀ (n : ℕ), P (n + 1) → P n
k seed : ℕ
hk : 1 < k
hs : P (succ seed)
hm : ∀ (x : ℕ), seed < x → P x → P (k * x)
n x✝ : ℕ
hl : succ seed ≤ x✝
hP✝ : P x✝
⊢ x✝ < (fun x x_1 => x * x_1) k x✝
[PROOFSTEP]
convert (mul_lt_mul_right <| seed.succ_pos.trans_le hl).2 hk
[GOAL]
case h.e'_3
a b c : ℕ
P : ℕ → Prop
h : ∀ (n : ℕ), P (n + 1) → P n
k seed : ℕ
hk : 1 < k
hs : P (succ seed)
hm : ∀ (x : ℕ), seed < x → P x → P (k * x)
n x✝ : ℕ
hl : succ seed ≤ x✝
hP✝ : P x✝
⊢ x✝ = 1 * x✝
[PROOFSTEP]
rw [one_mul]
|
#include <boost/phoenix/function/lazy_smart.hpp>
|
module Dbcritic.Interface
export
formatMessage : Int -> String -> List String -> List String -> String
formatMessage index description problems solutions =
"\x1B[34mISSUE #" ++ show index ++ ": " ++ description ++ "\x1B[0m\n" ++
"\n" ++
"\x1B[31m If you do not solve this issue, you will encounter the following problems:\x1B[0m\n" ++
"\n" ++
concatMap (\p => " \x1B[31m• " ++ p ++ "\x1B[0m\n") (problems) ++
"\n" ++
"\x1B[32m You can solve this issue by taking one of the following measures:\x1B[0m\n" ++
"\n" ++
concatMap (\p => " \x1B[32m• " ++ p ++ "\x1B[0m\n") (solutions)
|
#include <memory>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <exception>
#include <string>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_io.hpp>
#include <boost/bind/bind.hpp>
#ifdef WIN32
#include "gettimeofday_win.hxx"
#else
#include <sys/time.h>
#endif
#include "library.hxx"
using std::cerr;
using std::endl;
using boost::cref;
using namespace library;
using namespace boost::tuples;
using namespace boost::placeholders;
#ifdef WITH_LEESA
#include "library-meta.hxx"
#include "LEESA/LEESA.h"
using namespace LEESA;
#endif // WITH_LEESA
template <class T>
struct SeqType
{
typedef ::xsd::cxx::tree::sequence< T > type;
};
#include <vector>
#ifdef TEST1
// Get a sequence of books.
SeqType<book>::type
get_books(catalog & c)
{
#ifdef WITH_LEESA
SeqType<book>::type book_seq = evaluate (c, catalog() >> book());
#endif
#ifdef WITHOUT_LEESA
SeqType<book>::type book_seq = c.book();
#endif
return book_seq;
};
#endif // TEST1
#ifdef TEST2
// Get a sequence of authors.
SeqType<author>::type
get_authors (catalog & c)
{
#ifdef WITH_LEESA
SeqType<author>::type author_seq =
evaluate (c, catalog() >> book() >> author());
#endif
#ifdef WITHOUT_LEESA
SeqType<author>::type author_seq;
for (catalog::book_const_iterator bi (c.book().begin ());
bi != c.book().end ();
++bi)
{
author_seq.insert(author_seq.end(), bi->author().begin(), bi->author().end());
}
#endif
return author_seq;
}
#endif // TEST2
#ifdef TEST3
// Get a sequence of author names.
SeqType<name>::type
//unsigned int
get_author_names (catalog & c)
{
#ifdef WITH_LEESA
SeqType<name>::type name_seq =
evaluate (c, catalog() >> book() >> author() >> name());
#endif
#ifdef WITHOUT_LEESA
SeqType<name>::type name_seq;
for (catalog::book_const_iterator bi (c.book().begin ());
bi != c.book().end ();
++bi)
{
for (book::author_const_iterator ai (bi->author().begin ());
ai != bi->author().end ();
++ai)
{
name_seq.push_back(ai->name());
}
}
#endif
return name_seq;
}
#endif // TEST3
#ifdef TEST4
// Get a sequence of author names.
SeqType<name>::type
get_author_names_descendants_of (catalog & c)
{
#ifdef WITH_LEESA
SeqType<name>::type name_seq =
// evaluate (c, catalog() >> DescendantsOf(catalog(), name()));
DescendantsOf(catalog(), name())(c);
#endif
#ifdef WITHOUT_LEESA
SeqType<name>::type name_seq;
for (catalog::book_const_iterator bi (c.book().begin ());
bi != c.book().end ();
++bi)
{
for (book::author_const_iterator ai (bi->author().begin ());
ai != bi->author().end ();
++ai)
{
name_seq.push_back(ai->name());
}
}
#endif
return name_seq;
}
#endif // TEST4
#ifdef TEST5
bool comparator(library::name const & n)
{
return n=="Leo Tolstoy";
}
struct match_unary {
bool operator () (library::name const & n) {
return n=="Leo Tolstoy";
}
};
// Get a sequence of author names.
SeqType<name>::type
get_author_names_level_descendants_of (catalog & c)
{
#ifdef WITH_LEESA
SeqType<name>::type name_seq =
evaluate (c, catalog() >> LevelDescendantsOf(catalog(), _, _, name())
>> Select(name(), comparator));
evaluate (c, catalog() >> LevelDescendantsOf(catalog(), _, _, name())
>> Select(name(), match_unary()));
evaluate (c, catalog() >> LevelDescendantsOf(catalog(), _, _, name())
>> Select(name(), boost::bind(std::equal_to<std::string>(), _1, "Leo Tolstoy")));
#ifdef LEESA_SUPPORTS_LAMBDA
evaluate (c, catalog() >> LevelDescendantsOf(catalog(), _, _, name())
>> Select(name(), [](const library::name & n) { return n=="Leo Tolstoy"; }));
#endif
#endif
#ifdef WITHOUT_LEESA
SeqType<name>::type name_seq;
for (catalog::book_const_iterator bi (c.book().begin ());
bi != c.book().end ();
++bi)
{
for (book::author_const_iterator ai (bi->author().begin ());
ai != bi->author().end ();
++ai)
{
name_seq.push_back(ai->name());
}
}
#endif
return name_seq;
}
#endif // TEST5
#ifdef TEST6
// Get a sequence of tuples of author names and born.
typedef tuple<name *, died *> PtrTuple;
std::vector<PtrTuple>
get_tuples (catalog & c)
{
#ifdef WITH_LEESA
std::vector<PtrTuple> tuple_seq =
evaluate (c, catalog() >> book()
>> author()
>> MembersAsTupleOf(author(), PtrTuple()));
#endif
#ifdef WITHOUT_LEESA
std::vector<tuple<name *, born *> > tuple_seq;
for (catalog::book_iterator bi (c.book().begin ());
bi != c.book().end ();
++bi)
{
for (book::author_iterator ai (bi->author().begin ());
ai != bi->author().end ();
++ai)
{
tuple_seq.push_back(make_tuple(&ai->name(), &ai->born()));
}
}
#endif
return tuple_seq;
}
#endif // TEST6
#ifdef TEST7
// Get a sequence of "died" date, which is optional.
SeqType<died>::type
get_died (catalog & c)
{
#ifdef WITH_LEESA
SeqType<died>::type died_seq =
evaluate (c, catalog() >> DescendantsOf(catalog(), died()));
#endif
#ifdef WITHOUT_LEESA
SeqType<died>::type died_seq;
for (catalog::book_const_iterator bi (c.book().begin ());
bi != c.book().end ();
++bi)
{
for (book::author_const_iterator ai (bi->author().begin ());
ai != bi->author().end ();
++ai)
{
if(ai->died().present())
died_seq.push_back(ai->died().get());
}
}
#endif
return died_seq;
}
#endif // TEST7
#ifdef TEST8
// Nesting test
void visit (catalog & c, visitor & v)
{
#ifdef WITH_LEESA
BOOST_AUTO(inner_author, author() >>= born() >> v >> Leave(born(), v));
BOOST_AUTO(inner_book, book() >>= author() >> v
>> Call(author(), inner_author)
>> Leave(author(), v));
BOOST_AUTO(inner_catalog, catalog() >>= book() >> v
>> Call(book(), inner_book)
>> Leave(book(), v));
evaluate (c, catalog() >> v
>> Call(catalog(), inner_catalog)
>> Leave(catalog(), v));
#endif
}
#endif // TEST8
#ifdef TEST9
// Nesting test
void pair_caller_many (catalog & c, visitor & v)
{
#ifdef WITH_LEESA
BOOST_AUTO(inner_author, author() >>= born() >> Visit(born(), v) >> Leave(born(), v));
BOOST_AUTO(inner_book, book() >>= author() >> VisitLeave(author(), v, inner_author));
BOOST_AUTO(inner_catalog, catalog() >>= book() >> VisitLeave(book(), v, inner_book));
evaluate(c, catalog() >> VisitLeave(catalog(), v, inner_catalog));
#endif
}
#endif // TEST9
#ifdef TEST10
// Nesting test
void pair_caller_single (catalog & c, visitor & v)
{
#ifdef WITH_LEESA
evaluate(c, catalog()
>> VisitLeave(catalog(), v,
catalog() >>= book()
>> VisitLeave(book(), v,
book() >>= author()
>> VisitLeave(author(), v,
author() >>= born()
>> VisitLeave(born(), v)))));
#endif
}
#endif // TEST10
#ifdef TEST11
void fulltd(catalog &c, visitor &v)
{
evaluate(c, catalog() >> FullTD(catalog(), LeaveStrategy(v)));
}
#endif // TEST11
#ifdef TEST12
void aroundfulltd(catalog &c, visitor &v)
{
AroundFullTD(catalog(), VisitStrategy(v), LeaveStrategy(v))(c);
}
#endif // TEST12
#ifdef TEST13
void membersof(catalog &c, visitor &v)
{
BOOST_AUTO(v_born, author() >> v >> born() >> v);
BOOST_AUTO(v_title, title() >> v);
BOOST_AUTO(members, MembersOf(book(), v_born, v_title));
SeqType<catalog>::type catalogs;
catalogs.push_back(c);
catalogs.push_back(c);
/* There is a critical difference in semantics between the following two evaluate
expressions. This example shows how to begin depth-frist traversal from the root.
Note the different in the return type. */
/* The one with Identity begins depth-first traversal from catalog itself.
I.e., It visits one catalog and goes deeper in it and only when the specified sub-
tree is traversed, it goes to the next catalog. Note the return type is
container of catalogs. */
catalogs =
evaluate(catalogs, Identity(catalog()) >>= catalog() >> v >>= book() >> members);
std::cout << "*********************************************************\n";
/* The expression without Identity, visits all catalogs first and then begins
depth-first traversal from books. Note the return type is container of books. */
SeqType<book>::type books =
evaluate(catalogs, catalog() >> v >>= book() >> members);
}
#endif // TEST13
timeval operator - (timeval t1, timeval t2)
{
if (t1.tv_usec < t2.tv_usec)
{
t1.tv_sec--;
t1.tv_usec += 1000000;
}
time_t sec = t1.tv_sec - t2.tv_sec;
suseconds_t usec = t1.tv_usec - t2.tv_usec;
timeval retval;
retval.tv_sec = sec;
retval.tv_usec = usec;
return retval;
}
std::ostream & operator << (std::ostream & o, timeval const & t)
{
o << "[" << t.tv_sec << ", " << t.tv_usec << "]";
//o << t.tv_sec << " " << t.tv_usec;
return o;
}
#ifdef WITH_LEESA
class MyVisitor : public visitor
{
public:
virtual void visit_catalog(catalog &) {
std::cout << "Catalog:" << std::endl;
}
virtual void visit_author(author & x) {
std::cout << "Author: " << x.name() << std::endl;
}
virtual void visit_book(book & x) {
std::cout << "Book: " << x.title() << std::endl;
}
virtual void visit_born(born & x) {
std::cout << "Born: " << x << std::endl;
}
virtual void visit_title(title & t) {
std::cout << "Title: " << t << std::endl;
}
virtual void leave_catalog(catalog &) {
std::cout << "Leave Catalog:" << std::endl;
}
virtual void leave_author(author & x) {
std::cout << "Leave Author: " << x.name() << std::endl;
}
virtual void leave_book(book & x) {
std::cout << "Leave Book: " << x.title() << std::endl;
}
virtual void leave_born(born & x) {
std::cout << "Leave Born: " << x << std::endl;
}
virtual void leave_title(title & t) {
std::cout << "Leave Title: " << t << std::endl;
}
};
#endif // WITH_LEESA
#ifdef TEST20
namespace LEESA {
template <class Vector, unsigned SIZE = boost::mpl::size<Vector>::Value>
struct ComposedIterator : ComposedIterator<typename boost::mpl::pop_front<Vector>::type>
{
typedef typename boost::mpl::front<Vector>::type Head;
typedef typename ContainerTraits<Head>::Container HeadContainer;
typedef typename HeadContainer::iterator HeadIterator;
HeadIterator head_iter_;
};
template <class Vector>
struct ComposedIterator<Vector, 0>
{ };
template <class Expr>
struct ComposedIterator2
{
typedef Expr type;
};
template <class Context, class Expr>
typename ComposedIterator2<Expr>::type
evaluate_lazy(Context &c, Expr e)
{
BOOST_AUTO(result, e(c));
return e;
}
};
#endif // TEST20
int main (int argc, char* argv[])
{
if (argc != 2)
{
cerr << "usage: " << argv[0] << "<xml filename>" << endl;
return 1;
}
try
{
timeval start, end;
MyVisitor v;
gettimeofday(&start, 0);
std::auto_ptr<catalog> c (catalog_ (argv[1]));
gettimeofday(&end, 0);
std::cout << "Parsing time = " << end-start << std::endl;
gettimeofday(&start, 0);
#ifdef TEST1
std::cout << "Size = " << get_books(*c).size() << std::endl;
#endif
#ifdef TEST2
std::cout << "Size = " << get_authors(*c).size() << std::endl;
#endif
#ifdef TEST3
std::cout << "Size = " << get_author_names(*c).size() << std::endl;
#endif
#ifdef TEST4
std::cout << "Size = " << get_author_names_descendants_of(*c).size() << std::endl;
#endif
#ifdef TEST5
std::cout << "Size = " << get_author_names_level_descendants_of(*c).size() << std::endl;
#endif
#ifdef TEST6
typedef std::vector<PtrTuple> TupleVector;
TupleVector tuple_vec = get_tuples(*c);
std::cout << "Size = " << tuple_vec.size() << std::endl;
for(TupleVector::const_iterator iter(tuple_vec.begin());
iter != tuple_vec.end();
++iter)
{
if (get<0>(*iter) && get<1>(*iter))
std::cout << "[" << *get<0>(*iter) << ", " << *get<1>(*iter) << "]\n";
else if (!get<0>(*iter) && get<1>(*iter))
std::cout << "[NULL, " << *get<1>(*iter) << "]\n";
else if (get<0>(*iter) && !get<1>(*iter))
std::cout << "[" << *get<0>(*iter) << ", NULL]\n";
else
std::cout << "[NULL, NULL]\n";
}
#endif
#ifdef TEST7
SeqType<died>::type died_seq = get_died(*c);
std::cout << "Size = " << died_seq.size() << std::endl;
//std::copy(died_seq.begin(), died_seq.end(), std::ostream_iterator<died> (std::cout, "\n"));
#endif
#ifdef TEST8
visit(*c, v);
#endif
#ifdef TEST9
pair_caller_many(*c, v);
#endif
#ifdef TEST10
pair_caller_single(*c, v);
#endif
#ifdef TEST11
fulltd(*c, v);
#endif
#ifdef TEST12
aroundfulltd(*c, v);
#endif
#ifdef TEST13
membersof(*c, v);
#endif
#ifdef TEST20
LEESA::evaluate_lazy(*c, catalog() >>= book() >>= author());
#endif
gettimeofday(&end, 0);
std::cout << "Query-time = " << end-start << std::endl;
}
catch (const xml_schema::exception& e)
{
cerr << e << endl;
return 1;
}
}
|
State Before: α : Type u
β : Type v
ι✝ : Sort w
a : α
s✝ s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
ι : Type u_1
s : Finset ι
f : ι → Set α
⊢ closure (⋃ (i : ι) (_ : i ∈ s), f i) = ⋃ (i : ι) (_ : i ∈ s), closure (f i) State After: no goals Tactic: classical
refine' s.induction_on (by simp) _
intro i s _ h₂
simp [h₂] State Before: α : Type u
β : Type v
ι✝ : Sort w
a : α
s✝ s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
ι : Type u_1
s : Finset ι
f : ι → Set α
⊢ closure (⋃ (i : ι) (_ : i ∈ s), f i) = ⋃ (i : ι) (_ : i ∈ s), closure (f i) State After: α : Type u
β : Type v
ι✝ : Sort w
a : α
s✝ s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
ι : Type u_1
s : Finset ι
f : ι → Set α
⊢ ∀ ⦃a : ι⦄ {s : Finset ι},
¬a ∈ s →
(closure (⋃ (i : ι) (_ : i ∈ s), f i) = ⋃ (i : ι) (_ : i ∈ s), closure (f i)) →
closure (⋃ (i : ι) (_ : i ∈ insert a s), f i) = ⋃ (i : ι) (_ : i ∈ insert a s), closure (f i) Tactic: refine' s.induction_on (by simp) _ State Before: α : Type u
β : Type v
ι✝ : Sort w
a : α
s✝ s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
ι : Type u_1
s : Finset ι
f : ι → Set α
⊢ ∀ ⦃a : ι⦄ {s : Finset ι},
¬a ∈ s →
(closure (⋃ (i : ι) (_ : i ∈ s), f i) = ⋃ (i : ι) (_ : i ∈ s), closure (f i)) →
closure (⋃ (i : ι) (_ : i ∈ insert a s), f i) = ⋃ (i : ι) (_ : i ∈ insert a s), closure (f i) State After: α : Type u
β : Type v
ι✝ : Sort w
a : α
s✝¹ s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
ι : Type u_1
s✝ : Finset ι
f : ι → Set α
i : ι
s : Finset ι
a✝ : ¬i ∈ s
h₂ : closure (⋃ (i : ι) (_ : i ∈ s), f i) = ⋃ (i : ι) (_ : i ∈ s), closure (f i)
⊢ closure (⋃ (i_1 : ι) (_ : i_1 ∈ insert i s), f i_1) = ⋃ (i_1 : ι) (_ : i_1 ∈ insert i s), closure (f i_1) Tactic: intro i s _ h₂ State Before: α : Type u
β : Type v
ι✝ : Sort w
a : α
s✝¹ s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
ι : Type u_1
s✝ : Finset ι
f : ι → Set α
i : ι
s : Finset ι
a✝ : ¬i ∈ s
h₂ : closure (⋃ (i : ι) (_ : i ∈ s), f i) = ⋃ (i : ι) (_ : i ∈ s), closure (f i)
⊢ closure (⋃ (i_1 : ι) (_ : i_1 ∈ insert i s), f i_1) = ⋃ (i_1 : ι) (_ : i_1 ∈ insert i s), closure (f i_1) State After: no goals Tactic: simp [h₂] State Before: α : Type u
β : Type v
ι✝ : Sort w
a : α
s✝ s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
ι : Type u_1
s : Finset ι
f : ι → Set α
⊢ closure (⋃ (i : ι) (_ : i ∈ ∅), f i) = ⋃ (i : ι) (_ : i ∈ ∅), closure (f i) State After: no goals Tactic: simp
|
\documentclass{article}
\usepackage{lipsum}
\title{My Second \LaTeX Document}
\author{Perry J. Williams}
\date{\today}
\begin{document}
\maketitle
\section*{Abstract}
\begin{enumerate}
\item The key result from this research is \ldots
\item My research took place in Reno, Nevada.
\end{enumerate}
Here is my own abstract. It is pretty short.
\section*{Introduction}
\lipsum[1]
File $\beta_{3,2}$
\section*{Methods}
\lipsum[1]
\section*{Results}
\lipsum[1]
\section*{Discussion}
\lipsum[1]
\end{document}
|
/*
* libasiotap - A portable TAP adapter extension for Boost::ASIO.
* Copyright (C) 2010-2011 Julien KAUFFMANN <[email protected]>
*
* This file is part of libasiotap.
*
* libasiotap 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.
*
* libasiotap is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*
* If you intend to use libasiotap in a commercial software, please
* contact me : we may arrange this for a small fee or no fee at all,
* depending on the nature of your project.
*/
/**
* \file ip_configuration.cpp
* \author Julien KAUFFMANN <[email protected]>
* \brief Deals with IP configurations.
*/
#include "types/ip_route.hpp"
#include "types/stream_operations.hpp"
#include <boost/lexical_cast.hpp>
namespace asiotap
{
template <typename AddressType>
std::istream& operator>>(std::istream& is, base_ip_route<AddressType>& value)
{
std::string ip_address;
std::string prefix_length;
std::string gateway;
if (read_ip_address_prefix_length_gateway<AddressType>(is, ip_address, prefix_length, gateway))
{
base_ip_network_address<AddressType> ina;
if (prefix_length.empty())
{
ina = AddressType::from_string(ip_address);
}
else
{
ina = { AddressType::from_string(ip_address), boost::lexical_cast<unsigned int>(prefix_length) };
}
if (gateway.empty())
{
value = ina;
}
else
{
value = { ina, AddressType::from_string(gateway) };
}
}
return is;
}
template std::istream& operator>>(std::istream& is, ipv4_route& value);
template std::istream& operator>>(std::istream& is, ipv6_route& value);
template <typename AddressType>
std::ostream& operator<<(std::ostream& os, const base_ip_route<AddressType>& value)
{
if (value.gateway())
{
return os << value.network_address() << " => " << *value.gateway();
}
else
{
return os << value.network_address();
}
}
template std::ostream& operator<<(std::ostream& is, const ipv4_route& value);
template std::ostream& operator<<(std::ostream& is, const ipv6_route& value);
std::istream& operator>>(std::istream& is, ip_route& value)
{
if (is)
{
ipv6_route ir;
if (is >> ir)
{
value = ir;
return is;
}
is.clear();
}
if (is)
{
ipv4_route ir;
if (is >> ir)
{
value = ir;
return is;
}
}
return is;
}
std::ostream& operator<<(std::ostream& os, const ip_route_set& routes)
{
if (routes.size() > 0)
{
auto route = routes.begin();
os << *route;
for (++route; route != routes.end(); ++route)
{
os << ", " << *route;
}
}
return os;
}
}
|
Inductive ALVec (A : Type) : nat -> Type :=
| Nil : ALVec A 0
| Cons : forall (m : nat) (h : A) {n : nat} (t : ALVec A n), ALVec A (1 + m + n).
|
#
# Copyright © 2021 United States Government as represented by the Administrator
# of the National Aeronautics and Space Administration. No copyright is claimed
# in the United States under Title 17, U.S. Code. All Other Rights Reserved.
#
# SPDX-License-Identifier: NASA-1.3
#
"""Spacecraft orbit."""
from astroplan import Observer
from astropy.coordinates import SkyCoord, TEME
from astropy import units as u
from astropy.utils.data import get_readable_fileobj
import numpy as np
from sgp4.api import Satrec, SGP4_ERRORS
from .constraints import OrbitNightConstraint
__all__ = ('Orbit',)
class Orbit:
"""An Earth satellite whose orbit is specified by its TLE.
Parameters
----------
tle : str, file
The filename or file-like object containing the two-line element (TLE).
Examples
--------
Load an example TLE from a file:
>>> from importlib import resources
>>> from astropy.time import Time
>>> from astropy import units as u
>>> from dorado.scheduling import Orbit
>>> from astropy.utils.data import get_pkg_data_filename
>>> with resources.path('dorado.scheduling.data',
... 'dorado-625km-sunsync.tle') as path:
... orbit = Orbit(path)
Get the orbital period:
>>> orbit.period
<Quantity 97.20725153 min>
Evaluate the position and velocity of the satellite at one specific time:
>>> time = Time('2021-04-16 15:27')
>>> orbit(time)
<SkyCoord (ITRS: obstime=2021-04-16 15:27:00.000): (x, y, z) in km
(3902.59776726, -5209.69991116, 2582.69921222)
(v_x, v_y, v_z) in km / s
(-2.9282713, 1.25697383, 6.93396922)>
Or evaluate at an array of times:
>>> times = time + np.linspace(0 * u.min, 2 * u.min, 50)
>>> orbit(times).shape
(50,)
""" # noqa: E501
def __init__(self, tle):
with get_readable_fileobj(tle) as f:
*_, line1, line2 = f.readlines()
self._tle = Satrec.twoline2rv(line1, line2)
@property
def period(self):
"""The orbital period at the epoch of the TLE."""
return 2 * np.pi / self._tle.no * u.minute
def __call__(self, time):
"""Get the position and velocity of the satellite.
Parameters
----------
time : :class:`astropy.time.Time`
The time of the observation.
Returns
-------
coord : :class:`astropy.coordinates.SkyCoord`
The coordinates of the satellite in the ITRS frame.
Notes
-----
The orbit propagation is based on the example code at
https://docs.astropy.org/en/stable/coordinates/satellites.html.
"""
shape = time.shape
time = time.ravel()
time = time.utc
e, xyz, vxyz = self._tle.sgp4_array(time.jd1, time.jd2)
x, y, z = xyz.T
vx, vy, vz = vxyz.T
# If any errors occurred, only raise for the first error
e = e[e != 0]
if e.size > 0:
raise RuntimeError(SGP4_ERRORS[e[0]])
coord = SkyCoord(x=x*u.km, v_x=vx*u.km/u.s,
y=y*u.km, v_y=vy*u.km/u.s,
z=z*u.km, v_z=vz*u.km/u.s,
frame=TEME(obstime=time)).itrs
if shape:
coord = coord.reshape(shape)
else:
coord = coord[0]
return coord
def is_night(self, time):
"""Determine if the spacecraft is in orbit night.
Parameters
----------
time : :class:`astropy.time.Time`
The time of the observation.
Returns
-------
bool, :class:`np.ndarray`
True when the spacecraft is in orbit night, False otherwise.
"""
return OrbitNightConstraint().compute_constraint(
time, Observer(self(time).earth_location))
|
module examples.Vec where
{- Computed datatypes -}
data One : Set where
unit : One
data Nat : Set where
zero : Nat
suc : Nat -> Nat
data _*_ (A B : Set) : Set where
pair : A -> B -> A * B
infixr 20 _=>_
data _=>_ (A B : Set) : Set where
lam : (A -> B) -> A => B
lam2 : {A B C : Set} -> (A -> B -> C) -> (A => B => C)
lam2 f = lam (\x -> lam (f x))
app : {A B : Set} -> (A => B) -> A -> B
app (lam f) x = f x
Vec : Nat -> Set -> Set
Vec zero X = One
Vec (suc n) X = X * Vec n X
{- ... construct the vectors of a given length -}
vHead : {X : Set} -> (n : Nat)-> Vec (suc n) X -> X
vHead n (pair a b) = a
vTail : {X : Set} -> (n : Nat)-> Vec (suc n) X -> Vec n X
vTail n (pair a b) = b
{- safe destructors for nonempty vectors -}
{- useful vector programming operators -}
vec : {X : Set} -> (n : Nat) -> X -> Vec n X
vec zero x = unit
vec (suc n) x = pair x (vec n x)
vapp : {S T : Set} -> (n : Nat) -> Vec n (S => T) -> Vec n S -> Vec n T
vapp zero unit unit = unit
vapp (suc n) (pair f fs) (pair s ss) = pair (app f s) (vapp n fs ss)
{- mapping and zipping come from these -}
vMap : {S T : Set} -> (n : Nat) -> (S -> T) -> Vec n S -> Vec n T
vMap n f ss = vapp n (vec n (lam f)) ss
{- transposition gets the type it deserves -}
transpose : {X : Set} -> (m n : Nat)-> Vec m (Vec n X) -> Vec n (Vec m X)
transpose zero n xss = vec n unit
transpose (suc m) n (pair xs xss) =
vapp n (vapp n (vec n (lam2 pair)) xs)
(transpose m n xss)
{- Sets of a given finite size may be computed as follows... -}
{- Resist the temptation to mention idioms. -}
data Zero : Set where
data _+_ (A B : Set) : Set where
inl : A -> A + B
inr : B -> A + B
Fin : Nat -> Set
Fin zero = Zero
Fin (suc n) = One + Fin n
{- We can use these sets to index vectors safely. -}
vProj : {X : Set} -> (n : Nat)-> Vec n X -> Fin n -> X
-- vProj zero () we can pretend that there is an exhaustiveness check
vProj (suc n) (pair x xs) (inl unit) = x
vProj (suc n) (pair x xs) (inr i) = vProj n xs i
{- We can also tabulate a function as a vector. Resist
the temptation to mention logarithms. -}
vTab : {X : Set} -> (n : Nat)-> (Fin n -> X) -> Vec n X
vTab zero _ = unit
vTab (suc n) f = pair (f (inl unit)) (vTab n (\x -> f (inr x)))
{- Question to ponder in your own time:
if we use functional vectors what are vec and vapp -}
{- Answer: K and S -}
{- Inductive datatypes of the unfocused variety -}
{- Every constructor must target the whole family rather
than focusing on specific indices. -}
data Tm (n : Nat) : Set where
evar : Fin n -> Tm n
eapp : Tm n -> Tm n -> Tm n
elam : Tm (suc n) -> Tm n
{- Renamings -}
Ren : Nat -> Nat -> Set
Ren m n = Vec m (Fin n)
_`Ren`_ = Ren
{- identity and composition -}
idR : (n : Nat) -> n `Ren` n
idR n = vTab n (\i -> i)
coR : (l m n : Nat) -> m `Ren` n -> l `Ren` m -> l `Ren` n
coR l m n m2n l2m = vMap l (vProj m m2n) l2m
{- what theorems should we prove -}
{- the lifting functor for Ren -}
liftR : (m n : Nat) -> m `Ren` n -> suc m `Ren` suc n
liftR m n m2n = pair (inl unit) (vMap m inr m2n)
{- what theorems should we prove -}
{- the functor from Ren to Tm-arrows -}
rename : {m n : Nat} -> (m `Ren` n) -> Tm m -> Tm n
rename {m}{n} m2n (evar i) = evar (vProj m m2n i)
rename {m}{n} m2n (eapp f s) = eapp (rename m2n f) (rename m2n s)
rename {m}{n} m2n (elam t) = elam (rename (liftR m n m2n) t)
{- Substitutions -}
Sub : Nat -> Nat -> Set
Sub m n = Vec m (Tm n)
_`Sub`_ = Sub
{- identity; composition must wait; why -}
idS : (n : Nat) -> n `Sub` n
idS n = vTab n (evar {n})
{- functor from renamings to substitutions -}
Ren2Sub : (m n : Nat) -> m `Ren` n -> m `Sub` n
Ren2Sub m n m2n = vMap m evar m2n
{- lifting functor for substitution -}
liftS : (m n : Nat) -> m `Sub` n -> suc m `Sub` suc n
liftS m n m2n = pair (evar (inl unit))
(vMap m (rename (vMap n inr (idR n))) m2n)
{- functor from Sub to Tm-arrows -}
subst : {m n : Nat} -> m `Sub` n -> Tm m -> Tm n
subst {m}{n} m2n (evar i) = vProj m m2n i
subst {m}{n} m2n (eapp f s) = eapp (subst m2n f) (subst m2n s)
subst {m}{n} m2n (elam t) = elam (subst (liftS m n m2n) t)
{- and now we can define composition -}
coS : (l m n : Nat) -> m `Sub` n -> l `Sub` m -> l `Sub` n
coS l m n m2n l2m = vMap l (subst m2n) l2m
|
! RUN: not %flang -fsyntax-only 2>&1 %s | FileCheck %s
module m
contains
subroutine subr1(f)
character(5) f
print *, f('abcde')
end subroutine
subroutine subr2(f)
character(*) f
print *, f('abcde')
end subroutine
character(5) function explicitLength(x)
character(5), intent(in) :: x
explicitLength = x
end function
real function notChar(x)
character(*), intent(in) :: x
notChar = 0
end function
end module
character(*) function assumedLength(x)
character(*), intent(in) :: x
assumedLength = x
end function
subroutine subr3(f)
character(5) f
print *, f('abcde')
end subroutine
program main
use m
external assumedlength
character(5) :: assumedlength
call subr1(explicitLength)
call subr1(assumedLength)
!CHECK: error: Actual argument function associated with procedure dummy argument 'f=' has incompatible result type
call subr1(notChar)
call subr2(explicitLength)
call subr2(assumedLength)
!CHECK: error: Actual argument function associated with procedure dummy argument 'f=' has incompatible result type
call subr2(notChar)
call subr3(explicitLength)
call subr3(assumedLength)
!CHECK: warning: If the procedure's interface were explicit, this reference would be in error:
!CHECK: because: Actual argument function associated with procedure dummy argument 'f=' has incompatible result type
call subr3(notChar)
end program
|
State Before: m : Type u_1 → Type u_2
ε α : Type u_1
inst✝ : Monad m
x y : ExceptT ε m α
h : run x = run y
⊢ x = y State After: m : Type u_1 → Type u_2
ε α : Type u_1
inst✝ : Monad m
x y : ExceptT ε m α
h : x = y
⊢ x = y Tactic: simp [run] at h State Before: m : Type u_1 → Type u_2
ε α : Type u_1
inst✝ : Monad m
x y : ExceptT ε m α
h : x = y
⊢ x = y State After: no goals Tactic: assumption
|
lemma degree_prod_eq_sum_degree: fixes A :: "'a set" and f :: "'a \<Rightarrow> 'b::idom poly" assumes f0: "\<forall>i\<in>A. f i \<noteq> 0" shows "degree (\<Prod>i\<in>A. (f i)) = (\<Sum>i\<in>A. degree (f i))"
|
If $S$ is a bounded set, then its closure is bounded.
|
\section{Related work}
\label{sec:related-work}
In the world of tiny (IoT) several mobility-enabling routing protocols have been proposed. Firstly we highlight $\mu$Matrix's features against its original static version \cite{Peres:2016}. Then, we survey recent protocols in the context of 6LoWPAN and put them in perspective with $\mu$Matrix.
Matrix was originally proposed without support for mobility\cite{Peres:2016}. If a node moved from its home location, the hierarchical IPv6 address allocation would become invalid and compromise downward routing. Although RPL~\cite{rfc6550} is the standard protocol for 6LoWPANs, it presents limitations, for example, in mobility scenarios, scalability issues, reliability and robustness for point-to-multipoint traffic~\cite{iova2016rpl, Peres:2016}. Most recent mobile-enabled routing protocols are RPL extensions. They deal with mobile issues, but they do not handle RPL drawbacks. Co-RPL~\cite{gaddour2014co} provides mobility support to RPL but without Trickle. This turns Co-RPL more responsive but has higher overhead. MMRPL~\cite{cobarzan2014analysis} modifies the RPL beacon periodicity by replacing the Trickle mechanism with a Reverse Trickle-Like. Their Reverse Trickle decays exponentially, while our approach quickly goes to the minimum after an unacknowledged beacon. MMRPL also needs some static nodes. In ME-RPL~\cite{el2012mobility}, static nodes have higher priority than mobile ones. ME-RPL requires some fixed nodes. The memory requirement to downward routes is still prohibitive. mRPL~\cite{fotouhi2015mrpl} proposes a hand-off mechanism for mobile nodes in RPL by separating nodes into mobile (MN) or serving access point (AP). They use smart-HOP algorithm on MN nodes to perform hand-off between AP.
XCTP~\cite{santos2015extend} extends CTP to support bidirectional traffic. XCTP does not support IPv6 addressing and any-to-any traffic. Hydro~\cite{dawson2010hydro} fills the gap of any-to-any traffic, but it requires static nodes with a large memory to perform the routing and support mobility nodes.
Mobile IP~\cite{perkins2011mobility} and Hierarchical Mobile IPv6 (HMIPv6) Mobility Management~\cite{rfc5380} are standards for IPv6 networks for handling local mobility. However, they are not designed for 6LoWPANs, they do not present a mobility detection or adjustable timers. LOAD~\cite{kim20076lowpan} and DYMO-Low~\cite{kim2007dynamic} are 6LoWPAN protocols inspired in AODV and DYMO, but they are not suitable for mobile networks.
Table~\ref{tab:rel-works} summarizes properties of the related protocols.
\input{related-work-table}
|
/*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "numpydelegate.hpp"
#include <sstream>
#include <iostream>
#include <iomanip>
#include <boost/thread.hpp>
#include "NPY.hpp"
#include "numpyserver.hpp"
#include "NumpyEvt.hpp"
#include "Cfg.hh"
#include <boost/log/trivial.hpp>
#define LOG BOOST_LOG_TRIVIAL
// trace/debug/info/warning/error/fatal
numpydelegate::numpydelegate()
:
m_server(NULL),
m_udp_port(8080),
m_npy_echo(0),
m_zmq_backend("tcp://127.0.0.1:5002"),
m_evt(NULL)
{
}
void numpydelegate::setServer(numpyserver<numpydelegate>* server)
{
m_server = server ;
}
void numpydelegate::setNumpyEvt(NumpyEvt* evt)
{
m_evt = evt ;
}
void numpydelegate::configureI(const char* name, std::vector<int> values)
{
if(values.empty()) return ;
if(strcmp(name, "udpport")==0) setUDPPort(values.back());
if(strcmp(name, "npyecho")==0) setNPYEcho(values.back());
}
void numpydelegate::configureS(const char* name, std::vector<std::string> values)
{
if(values.empty()) return ;
if(strcmp(name, "zmqbackend")==0) setZMQBackend(values.back());
}
void numpydelegate::setUDPPort(int port)
{
m_udp_port = port ;
}
void numpydelegate::setNPYEcho(int echo)
{
m_npy_echo = echo ;
}
void numpydelegate::setZMQBackend(std::string& backend)
{
m_zmq_backend = backend ;
}
int numpydelegate::getUDPPort()
{
return m_udp_port ;
}
int numpydelegate::getNPYEcho()
{
return m_npy_echo ;
}
std::string& numpydelegate::getZMQBackend()
{
return m_zmq_backend ;
}
void numpydelegate::liveConnect(Cfg* cfg)
{
if( cfg->containsOthers())
{
for(size_t i=0 ; i<cfg->getNumOthers() ; i++)
{
Cfg* other = cfg->getOther(i);
if(other->isLive())
{
m_live_cfg.push_back(other);
}
}
}
else
{
m_live_cfg.push_back(cfg);
}
}
void numpydelegate::interpretExternalMessage(std::string msg)
{
//printf("numpydelegate::interpretExternalMessage %s \n", msg.c_str());
for(size_t i=0 ; i<m_live_cfg.size() ; ++i)
{
Cfg* cfg = m_live_cfg[i];
cfg->liveline(msg.c_str()); // cfg listener objects may get live configured
}
}
void numpydelegate::on_msg(std::string _addr, unsigned short port, std::string msg)
{
//std::cout << std::setw(20) << boost::this_thread::get_id()
LOG(info) << "numpydelegate::on_msg "
<< " addr [" << _addr << "] "
<< " port [" << port << "] "
<< " msg [" << msg << "] "
<< std::endl;
interpretExternalMessage(msg);
std::stringstream ss ;
ss << msg ;
ss << " returned from numpydelegate " ;
boost::shared_ptr<std::string> addr(new std::string(_addr));
boost::shared_ptr<std::string> reply(new std::string(ss.str()));
m_server->send( *addr, port, *reply );
// is passing a deref-ed shared_ptr simply a cunning way to leak
}
void numpydelegate::on_npy(std::vector<int> _shape, std::vector<float> _data, std::string _metadata)
{
assert(_shape.size() == 3);
//std::cout << std::setw(20) << boost::this_thread::get_id()
LOG(info) << " numpydelegate::on_npy "
<< " shape dimension " << _shape.size() << " ["
<< _shape[0] << "/"
<< _shape[1] << "/"
<< _shape[2] << "] "
<< " data size " << _data.size()
<< " metadata [" << _metadata << "]"
<< std::endl ;
// copying and replying
boost::shared_ptr<std::vector<int>> shape(new std::vector<int>(_shape));
boost::shared_ptr<std::vector<float>> data(new std::vector<float>(_data));
boost::shared_ptr<std::string> metadata(new std::string(_metadata));
if(m_evt)
{
m_evt->setIncomingData(new NPY<float>(*shape, *data, *metadata)); // TODO: avoid excessive copying
LOG(info) << m_evt->description("NPY lodged incoming data into NumpyEvt");
}
// demo that can modify the npy
//for(size_t i=0 ; i< data->size() ; ++i) (*data)[i] = (*data)[i]*2.0f ;
m_server->response( *shape, *data, *metadata );
}
|
#this is a test script.
|
\documentclass[twoside]{article}
\usepackage[sc]{mathpazo} % Use the Palatino font
\usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs
\linespread{1.05} % Line spacing - Palatino needs more space between lines
\usepackage{microtype} % Slightly tweak font spacing for aesthetics
\usepackage[hmarginratio=1:1,top=32mm,columnsep=20pt]{geometry} % Document margins
\usepackage{multicol} % Used for the two-column layout of the document
\usepackage[hang, small,labelfont=bf,up,textfont=it,up]{caption} % Custom captions under/above floats in tables or figures
\usepackage{booktabs} % Horizontal rules in tables
\usepackage{float} % Required for tables and figures in the multi-column environment - they need to be placed in specific locations with the [H] (e.g. \begin{table}[H])
\usepackage{hyperref} % For hyperlinks in the PDF
\usepackage{lettrine} % The lettrine is the first enlarged letter at the beginning of the text
\usepackage{paralist} % Used for the compactitem environment which makes bullet points with less space between them
\usepackage{abstract} % Allows abstract customization
\renewcommand{\abstractnamefont}{\normalfont\bfseries} % Set the "Abstract" text to bold
\renewcommand{\abstracttextfont}{\normalfont\small\itshape} % Set the abstract itself to small italic text
\usepackage{titlesec} % Allows customization of titles
\renewcommand\thesection{\Roman{section}} % Roman numerals for the sections
\renewcommand\thesubsection{\Roman{subsection}} % Roman numerals for subsections
\titleformat{\section}[block]{\large\scshape\centering}{\thesection.}{1em}{} % Change the look of the section titles
\titleformat{\subsection}[block]{\large}{\thesubsection.}{1em}{} % Change the look of the section titles
\usepackage{fancyhdr} % Headers and footers
\pagestyle{fancy} % All pages have headers and footers
\fancyhead{} % Blank out the default header
\fancyfoot{} % Blank out the default footer
\fancyhead[C]{Bitquant Research Laboratories Working Paper No. 1} % Custom header text
\fancyfoot[RO,LE]{\thepage} % Custom footer text
\title{\vspace{-15mm}\fontsize{24pt}{10pt}\selectfont\textbf{A simple macroeconomic model of bitcoin}} % Article title
\author{
\large
\textsc{Joseph C Wang}
\normalsize Bitquant Research Laboratories\\
\normalsize \href{http://www.bitquant.com.hk/}{http://www.bitquant.com.hk/} \\
\normalsize \href{mailto:[email protected]}{[email protected]} \\
\date{2014 February 11}
}
\usepackage{natbib}
\bibliographystyle{plainnat}
\usepackage{url}
\begin{document}
\maketitle
\thispagestyle{fancy}
\begin{abstract}
This working paper presents a simple model for the macroeconomic
behavior of bitcoin based on the economic equation of exchange.
According to this model, the value of bitcoin is determined largely by
the willingness of bitcoin holders to save bitcoin and not by its
transactional use. This model therefore predicts that increased use
of bitcoin will not cause its value to rise, but that the value of
bitcoin in terms of fiat currency will be almost solely determined by
the willingness of bitcoin holders to pull bitcoin out of circulation.
This model suggests that bitcoin will not fall victim to a liquidity
trap as suggested by some economists.
\end{abstract}
\begin{multicols}{2}
\section{Introduction}
In this working paper, we present a model for the valuation of bitcoin
based on simple macroeconomic arguments. We caution that our model is
intended primarily to stimulate discussion and that the truth of this
model or any economic model will be determined by empirical
observation of the bitcoin market.
\section{Macroeconomics of Bitcoin}
We begin our money with the equation of exchange where
\begin{equation}
M \cdot V = P \cdot Q
\end{equation}
where
\begin{eqnarray*}
& M & \mbox{is the nominal amount of money}\\
& V & \mbox{is the velocity of money}\\
& P & \mbox{is the price level}\\
& Q & \mbox{is the index of real expenditures}\\
\end{eqnarray*}
We now modify the equation in order to take into account the unique
aspects of bitcoin. First we express all of our quantities in units
of fiat currency. By expressing all of our quantities in terms of
fiat currency, we can set the $P$ to $1$. Since we are expressing all
quantities in units of fiat currency, the value for $M$ is now the
value of bitcoin as measured in fiat currency units.
We next expand the quantity $M$ in terms of the number of bitcoin in
circulation $n_b$ and the price of a single bitcoin $p_b$. The number
of bitcoin in circulation is externally determined and slowing and
predictable varying, whereas the price of a single bitcoin will
fluctuate. Substituting $M=n_b p_b$ we and rearranging we get.
\begin{equation}
p_b = \frac{Q}{n_b V}
\end{equation}
We note that $n_b$ is an externally determined and slowing changing
variable. The main determinant of the price of bitcoin is the
interaction between the level of bitcoin usage and the velocity of
bitcoin.
At this point we have made no assumptions concerning the dynamics of
bitcoin. We shall now add some dynamical assumptions concerning the
relationship between the number of bitcoin expended $Q$ and the
velocity of an individual bitcoin $V$.
We decompose the velocity of bitcoin into a portion that is saved and
portion that is transacted. We denote the likelihood that a
invididual bitcoin is saved by $l_s$ and the likelihood that a bitcoin
is transacted as $l_t$. These two variables will sum to $1$. These
portions have a corresponding set of velocities $v_s$ being the
velocity of a saved bitcoin and $v_t$ being the velocity of a
transacted bitcoin.
We now make several claims about the dynamics of bitcoin. Because
$v_t \gg v_s$ we claim that we can set the velocity of saved bitcoins
to $0$. We further claim that the velocity of transacted bitcoins can
be modeled as a linear function of $Q$. We therefore have the
following expression for the total velocity of bitcoin.
\begin{equation}
V = l_t\alpha_t Q
\end{equation}.
Substituting back into the original equation we see that
\begin{equation}
p_b = \frac{1}{l_t \alpha_t}
\end{equation}.
We claim that $\alpha_t$ will remain roughly constant over time. That
leaves only one term which impacts the price of bitcoin, which is the
$l_t$ the likelihood that a given bitcoin will be transacted rathr
than saved.
\section{Implications of our model}
Our model makes very strong claims concerning the price of bitcoins.
In particular, it states that the price of bitcoin is determined
almost solely by the likelihood that a given bitcoin will be saved. If
a user uses bitcoin for transaction purposes then this has no impact
on the value of bitcoin, while the value of bitcoin rises a given
bitcoin is more likely to be saved rather than transacted.
This model seems to agree with the changes in bitcoin pricing in 2013.
The two events that caused bitcoin prices to increase were the Cyprus
banking crisis in April 2013 and the rise of mainland Chinese bitcoin
exchanges in October 2013. Both these events increased the likelihood
that a given bitcoin would be saved rather than transacted which
increased the price of bitcoin. We note that the main drivers for
bitcoin prices have been news reports concerning the convertibility of
bitcoin, and that news reports concerning the increasing usage of
bitcoin has made very little impact on its price.
We also note that bitcoin has is prone to sudden changes in price due
to news events but that the price of bitcoin after a sudden shock has
returned to stable levels. Our model explains this phenomenon by
asserting that although shocks can cause a sudden change in the price
of bitcoin, to the extent that it does not cause a change in how
likely a bitcoin is saved or transacted, it will not cause a change in
the long-run price level of bitcoin.
Our model also makes predictions concerning the future price of
bitcoin. If our model is correct, then we should expect that
increased usage of bitcoin should manifest itself in larger volumes
rather than increased prices. Prices in bitcoin would only be
effected by events which increase or decrease the likelihood that a
given bitcoin would be saved rather than transacted.
Some economists, notably Paul Krugman, are pessimistic about the
viability of bitcoin as a medium of exchange, because they believe
that bitcoin will fall into a liquidity trap caused by the fixed
supply of bitcoin \cite{krugman1}. Krugman claims that as the price
of bitcoin rises, the amount of bitcoin in circulation will decrease
thereby increasing the price, ultimately creating a situation in
which bitcoin is completely hoarded. This effect has been observed
in scrip economies such as the Capital Hill Babysitting Co-op
\cite{krugman2}.
However, our model provides a mechanism by which bitcoin can avoid a
liquidity trap and explains why bitcoin has not experienced such a
trap. The mechanism which we claim this will occur involves the
interaction between bitcoin and fiat currency. As the price of
bitcoin rises, we claim that people will be more likely to spend their
bitcoin rather than fiat currency, which will decrease saved bitcoin
thereby cause bitcoin prices to fall. Conversely a fall in the price
of bitcoin will increase the likelihood that people will save bitcoin
as they will be more likely to spend fiat, and this will cause bitcoin
prices to rise. Our models claims that long-run increases or
decreases in the price of bitcoin will not influenced by the
transactional use of bitcoin but rather by external factors which
change the likelihood that a given bitcoin will be saved.
Krugman's belief that bitcoin is destined for a liquidity trap ignores
the fact that bitcoin exists within an fiat-based economy, and that
the ease of convertibility to and from fiat prevents a liquidity trap
that exists when convertibility is difficult.
\section{Conclusion}
We caution that the correctness of the model will be determined by
future empirical observations of the bitcoin market. However, we hope
to illustrate that the behavior of bitcoin can be modelled using basic
economic principles, and we hope that this working paper will
stimulate research and discussion in this area.
\bibliography{macro}
\end{multicols}
\end{document}
|
lemma compact_fip_Heine_Borel: fixes \<F> :: "'a::heine_borel set set" assumes clof: "\<And>T. T \<in> \<F> \<Longrightarrow> compact T" and none: "\<And>\<F>'. \<lbrakk>finite \<F>'; \<F>' \<subseteq> \<F>\<rbrakk> \<Longrightarrow> \<Inter>\<F>' \<noteq> {}" shows "\<Inter>\<F> \<noteq> {}"
|
integer(4) :: x
x = 6
x
|
\chapter{Code: quantinf Module}
The code developed to extend QuTiP with QI functionality, all put together in a single module file. Save it with the name \texttt{quantinf.py} in order to run the time evolution and Werner states programs from chapter 6. Save the programs in the same directory as this module for convenience, if not familiar with how to add a module to the Python path.\\
A copy can be obtained from\\
https://github.com/saad440/undergrad-project \\
\begin{verbatim}
# -*- coding: utf-8 -*-
"""
This module implements a number of quantum information functions
in QuTiP (Quantum Toolbox in Python)
Project: Investigation of Entanglement Measures in QuTiP
(IIUI, Fall 2015)
@author: Muhammad Saad <[email protected]>
"""
__all__ = ['purity','ispure','purity_of_reduced','ismixed_reduced',
'peres_horodecki_bipartite','schmidt_decomposition', 'dist_kl',
'entropy_entg', 'entropy_linear_entg', 'negativity', 'log_neg',
'linear_entropy', 'entropy_renyi', 'entropy_renyi_entg' ]
from qutip import ( Qobj, ket2dm, entropy_vn, ptrace, partial_transpose )
from numpy import log2
import numpy as np
def purity(dm):
""" Calculates trace of density matrix squared
Parameters
----------
dm: qobj/array-like
Input density matrix
Returns
-------
purity:
Purity of the state. 1 for pure, 0.5 for maximally mixed.
"""
if dm.type == 'ket':
dm = ket2dm(dm)
if dm.type != 'oper':
raise TypeError("Input must be a state ket or density matrix")
purity = (dm**2).tr()
return purity
def purity_of_reduced(rho):
""" Calculates trace of reduced density matrix square
Parameters
----------
dm: qobj/array-like
Input density matrix
Returns
-------
purityreduced:
Purity of the reduced DM. 1 for pure, 0.5 for maximally mixed.
"""
rhopartial = ptrace(rho,0)
purityreduced = purity(rhopartial)
return purityreduced
def ispure(dm):
""" Checks whether or not a density matrix represents a pure state
Parameters
----------
dm : qobj/array-like
Density operator representing the state.
-------
pure : bool
Whether or not the state is pure. True: Pure, False: Mixed.
"""
if np.round(purity(dm),8) == 1:
return True
else:
return False
def ismixed_reduced(dm):
""" One way to check for entanglement is that the reduced density
matrix is mixed. This function checks for that criterion.
Parameters
----------
dm : qobj/array-like
Density operator representing the state.
-------
mixed : bool
Whether or not the reduced DM is mixed. True: Mixed, False: Pure
"""
if np.round(purity_of_reduced(dm),8) != 1:
return True
else:
return False
def schmidt_decomposition(vec):
""" Schmidt decomposition of a bipartite vector
Based on the implementation in QETLAB 0.9
which was written by Nathaniel Johnston ([email protected])
and as of this port, last updated on December 1, 2012
Parameters
----------
vec : qobj, ket vector of product state
ket vector representing the bipartite state
-------
Returns:
[s, u, v]
s : list of floats
Schmidt coefficients
u : list of Qobj
list of left Schmidt vectors of ket
v : list of Qobj
list of right Schmidt vectors of ket
"""
if vec.type != 'ket':
raise TypeError("Input must be a ket vector.")
if len(vec.dims[0])==1:
raise TypeError("Input must be a joint state.")
dim = vec.dims[0][0]
vecnp = vec.full()
vecnpr = np.reshape(vecnp,[dim,dim])
um,s,vm = np.linalg.svd(vecnpr)
s = list(s)
def extract_vecs(mat):
veclist = list()
for j in range(mat.shape[1]):
veclist.append(Qobj(mat[:,j]))
return veclist
u = extract_vecs(um)
v = extract_vecs(vm)
return [s,u,v]
def peres_horodecki_bipartite(rho, mask=[0,1]):
""" Tests the given bipartite state for Peres-Horodecki criterion
Parameters
----------
rho: qobj/array-like
Density operator for the state
mask: list of int, length 2
mask used for partial transpose
Returns
-------
isentangled: bool
True for entangled, False for disentangled
"""
if rho.type != 'oper':
raise TypeError("Input must be a density matrix")
rhopt = partial_transpose(rho,mask)
rhopt_eigs = rhopt.eigenenergies()
if min(rhopt_eigs) < 0:
isentangled = True
else:
isentangled = False
return isentangled
def entropy_entg(rho, base=2):
""" Calculates the entropy of entanglement of a density matrix
Parameters:
-----------
rho : qobj/array-like
Input density matrix
base:
Base of log
Returns:
--------
ent_entg: Entropy of Entanglement
"""
if rho.type == 'ket':
rho = ket2dm(rho)
if rho.type != 'oper':
raise TypeError("Input must be density matrix")
rhopartial = ptrace(rho,0)
ent_entg = entropy_vn(rhopartial,base)
return ent_entg
def linear_entropy(dm, normalize=False):
""" Returns the linear entropy of a state.
Parameters
----------
dm : qobj/array-like
Density operator representing the state.
normalize : bool
Optional argument to normalize linear entropy such that the
completely mixed state has LE = 1 rather than 1-1/d. [1]
Default: False
----------
le : float
Linear entropy
----------
References:
[1] "Linear entropy and Bell inequalities", Santos and Ferrero,
Phys. Rev. A 62, 024101
"""
if dm.type not in ('oper','ket'):
raise TypeError("Input must be a Qobj representing a state.")
if dm.type=='ket':
dm = ket2dm(dm)
le = 1 - (dm**2).tr()
if normalize:
d = dm.shape[0]
le = le * d/(d-1)
return le
def entropy_linear_entg(rho, normalize=True):
""" Calculates the linear entropy of entanglement of a density matrix
Parameters:
-----------
rho : qobj/array-like
Input density matrix
Returns:
--------
linent_entg: Linear Entropy of Entanglement
"""
if rho.type == 'ket':
rho = ket2dm(rho)
if rho.type != 'oper':
raise TypeError("Input must be density matrix")
rhopartial = ptrace(rho,0)
linent_entg = linear_entropy(rhopartial,normalize)
return linent_entg
def entropy_renyi(rho,alpha):
""" Calculate Renyi entropy of the density matrix with given index
(Currently limited to 2-level systems)
Parameters
----------
dm: qobj/array-like
Input density matrix
alpha: Renyi index alpha
Returns
-------
ent_rn: Renyi Entropy
"""
if rho.type != 'oper':
raise TypeError("Input must be a density matrix")
qi = rho.eigenenergies()
if alpha == 1:
ent_rn = entropy_vn(rho,2)
elif alpha >= 0:
ent_rn = ( 1/(1-alpha) ) * log2 ( sum( qi**alpha ) )
else:
raise ValueError("alpha must be a non-negative number")
return ent_rn
def entropy_renyi_entg(rho,alpha):
""" Calculate Renyi entropy of entanglement for the DM with given index
(Currently limited to 2-level systems)
Parameters
----------
dm: qobj/array-like
Input density matrix
alpha: Renyi index alpha
Returns
-------
ent_rn_entg: Renyi Entropy of Entanglement
"""
rhopartial = ptrace(rho,0)
ent_rn_entg = entropy_renyi(rhopartial,alpha)
return ent_rn_entg
def negativity(rho,mask=[1,0]):
""" Calculate the negativity for a density matrix
Parameters:
-----------
rho : qobj/array-like
Input density matrix
Returns:
--------
neg : Negativity
"""
if rho.type != 'oper':
raise TypeError("Input must be a density matrix")
rhopt = partial_transpose(rho,mask)
neg = ( rhopt.norm() - 1 ) / 2
return neg
def log_neg(rho,mask=[1,0]):
""" Calculate the logarithmic negativity for a density matrix
Parameters:
-----------
rho : qobj/array-like
Input density matrix
Returns:
--------
logneg: Logarithmic Negativity
"""
if rho.type != 'oper':
raise TypeError("Input must be a density matrix")
rhopt = partial_transpose(rho,mask)
logneg = log2( rhopt.norm() )
return logneg
def dist_kl(rho, sgm):
""" Calculates the Kullback-Leibler distance (a.k.a. relative entropy)
between DMs rho and sgm representing two-level systems.
Parameters
----------
rho : qobj/array-like
First density operator.
sgm : qobj/array-like
Second density operator.
Returns
-------
kldist : float
Relative Entropy between rho and sgm.
"""
if rho.type != 'oper' or sgm.type != 'oper':
raise TypeError("Inputs must be density matrices..")
ent_vn = entropy_vn(rho,2)
r_eigs = rho.eigenenergies()
s_eigs = sgm.eigenenergies()
# too small negtive values may give trouble
s_eigs = np.round(s_eigs,8)
kldist = -ent_vn
for pj, qj in zip(r_eigs,s_eigs):
if qj==0:
pass
else:
kldist -= pj * log2(qj)
kldist = abs(kldist)
return kldist
\end{verbatim}
|
import Statistics.Distribution
import Statistics.Distribution.Normal
nd :: NormalDistribution
nd = normalDistr 0.0 1.0
main = do
putStrLn $ "P( 2< Z) = " ++ show (complCumulative nd 2)
putStrLn $ "P(-2<=Z<=2)= " ++ show (cumulative nd 2 - cumulative nd (-2))
putStrLn $ "P( 0<=Z<=1.73)= " ++ show (cumulative nd 1.73 - cumulative nd 0)
|
Formal statement is: lemma vector_derivative_part_circlepath: "vector_derivative (part_circlepath z r s t) (at x) = \<i> * r * (of_real t - of_real s) * exp(\<i> * linepath s t x)" Informal statement is: The derivative of the part of a circle path from $s$ to $t$ is $\iota r (t - s) \exp(\iota \text{ linepath } s t x)$.
|
```python
# Solving an expression in python
my_value = 2 * (3 + 2)**2 / 5 - 4
print(my_value)
```
6.0
```python
# making use of parenthesis for clarity in python
my_value = 2 * ((3 + 2)**2 / 5) - 4
print(my_value) # prints 6.0
```
6.0
```python
# Functions are expressions that define relationships between two or more variables.
# More specifically, a function takes input variables (also called domain variables or independent variables),
# plugs them into an expression, and then results in an output variable (also called dependent variable).
def f(x):
return 2 * x + 1
x_values = [0, 1, 2, 3]
for x in x_values:
y = f(x)
print(y)
```
1
3
5
7
```python
# Charting a linear function in python using Sympy (Sympy comes auto bundled in Anaconda)
from matplotlib import *
from sympy import *
x = symbols('x')
f = 2*x + 1
plot(f)
```
```python
x = symbols('x')
f = x**2 + 1
plot(f)
```
```python
from sympy.plotting import plot3d
x, y = symbols('x y')
f = 2*x + 3*y
plot3d(f)
```
```python
# A summation is expressed as a sigma and adds elements together.
# Summation in python
summation = sum(2*i for i in range(1,6))
print(summation)
```
30
```python
# Exponents multiplies a number by itself a specified number of times
# .The base is the variable or value we are exponentiating,
# and the exponent is the number of times we multiply the base value.
# using sympy to print exponent expression
x = symbols('x')
expr = x**2 / x**5
print(expr) # x**(-3)
```
x**(-3)
```python
# A logarithm is a math function that finds a power for a specific number and base.
# Using the log function in python
from math import log
# 2 raised to what power gives me 8?
x = log(8, 2)
print(x)
```
3.0
```python
# There is a special number that shows up quite a bit in math called Euler’s number e.
# It is a special number much like Pi π, and is approximately 2.71828.
# e is used a lot because it mathematically simplifies a lot of problems.
# Calculating continuous interest in python, A = P*e**rt
from math import exp
p = 100 # principal, starting amount
r = .20 # interest rate, by year
t = 2.0 # time, number of years
a = p * exp(r*t)
print(a)
```
149.18246976412703
```python
# When we use e as our base for a logarithm, we call it a natural logarithm.
from math import log
# e raised to what power gives us 10?
x = log(10)
print(x) # prints 2.302585092994046
```
2.302585092994046
```python
# A derivative tells the slope of a function, and it is useful to measure the rate of change at any point in a function.
# derivative calculator in python
def derivative_x(f, x, step_size):
m = (f(x + step_size) - f(x)) / ((x + step_size) - x)
return m
def my_function(x):
return x**2
slope_at_2 = derivative_x(my_function, 2, .00001)
print(slope_at_2)
```
4.000010000000827
```python
# Calculating a derivative in Sympy
# Declare 'x' to SymPy
x = symbols('x')
# Now just use Python syntax to declare function
f = x**2
# Calculate the derivative of the function
dx_f = diff(f)
print(dx_f) # prints 2*x
```
2*x
```python
# Calculating partial derivative with Sympy
# Declare x and y to SymPy
x,y = symbols('x y')
# Now just use Python syntax to declare function
f = 2*x**3 + 3*y**3
# Calculate the partial derivatives for x and y
dx_f = diff(f, x)
dy_f = diff(f, y)
print(dx_f) # prints 6*x**2
print(dy_f) # prints 9*y**2
# plot the function
plot3d(f)
```
```python
# integral, which finds the area under the curve for a given range.
# Integral approximation in python
def approximate_integral(a, b, n, f):
delta_x = (b - a) / n
total_sum = 0
for i in range(1, n + 1):
midpoint = 0.5 * (2 * a + delta_x * (2 * i - 1))
total_sum += f(midpoint)
return total_sum * delta_x
def my_function(x):
return x**2 + 1
area = approximate_integral(a=0, b=1, n=5, f=my_function)
print(area)
```
1.33
```python
```
|
! (C) Copyright 2019 UCAR
!
! This software is licensed under the terms of the Apache Licence Version 2.0
! which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
!> This Define interfaces for accessing C++ Locations objects from Fortran
!-------------------------------------------------------------------------------
interface
!-------------------------------------------------------------------------------
function aq_locs_nlocs_c(locs) bind(C,name="aq_locs_nlocs_f90")
use iso_c_binding, only: c_ptr, c_int
integer(c_int) :: aq_locs_nlocs_c
type(c_ptr), value :: locs
end function
function aq_locs_lonlat_c(locs) bind(C,name="aq_locs_lonlat_f90")
use iso_c_binding, only: c_ptr
type(c_ptr) :: aq_locs_lonlat_c
type(c_ptr), value :: locs
end function
function aq_locs_altitude_c(locs) bind(C,name="aq_locs_altitude_f90")
use iso_c_binding, only: c_ptr
type(c_ptr) :: aq_locs_altitude_c
type(c_ptr), value :: locs
end function
function aq_locs_times_c(locs, idx) bind(C,name="aq_locs_times_f90")
use iso_c_binding, only: c_ptr, c_size_t
type(c_ptr) :: aq_locs_times_c
type(c_ptr), value :: locs
integer(c_size_t) idx
end function
!-------------------------------------------------------------------------------
end interface
!-------------------------------------------------------------------------------
|
{-# OPTIONS --without-K --safe #-}
module Cats.Category.Fun.Facts.Terminal where
open import Cats.Category.Base
open import Cats.Category.Constructions.Terminal using (HasTerminal)
open import Cats.Category.Fun using (_↝_ ; ≈-intro)
open import Cats.Functor using (Functor)
open import Cats.Functor.Const using (Const)
open Functor
instance
hasTerminal : ∀ {lo la l≈ lo′ la′ l≈′}
→ {C : Category lo la l≈} {D : Category lo′ la′ l≈′}
→ {{_ : HasTerminal D}}
→ HasTerminal (C ↝ D)
hasTerminal {C = C} {D = D} {{D⊤}} = record
{ ⊤ = Const C ⊤
; isTerminal = λ X → record
{ arr = record
{ component = λ c → ! (fobj X c)
; natural = λ {c} {d} {f} → ⇒⊤-unique _ _
}
; unique = λ _ → ≈-intro (⇒⊤-unique _ _)
}
}
where
open HasTerminal D⊤
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.