text
stringlengths 0
3.34M
|
---|
#' Tools to Transform 'cURL' Command-Line Calls to 'httr' Requests
#'
#' Deciphering web/'REST' 'API' and 'XHR' calls can be tricky, which is one reason why
#' internet browsers provide "Copy as cURL" functionality within their "Developer Tools"
#' pane(s). These 'cURL' command-lines can be difficult to wrangle into an 'httr' 'GET' or
#' 'POST' request, but you can now "straighten" these 'cURLs' either from data copied to
#' the system clipboard or by passing in a vector of 'cURL' command-lines and getting back
#' a list of parameter elements which can be used to form 'httr' requests. These lists can
#' be passed to another function to automagically make 'httr' functions.
#'
#' @name curlconverter
#' @docType package
#' @author Bob Rudis (bob@@rud.is)
#' @import httr docopt
#' @importFrom formatR tidy_source
#' @importFrom clipr read_clip write_clip
#' @importFrom curl curl_unescape
#' @importFrom jsonlite toJSON fromJSON
#' @importFrom stringi stri_split_regex stri_split_fixed stri_detect_regex
#' @importFrom utils capture.output
#' @importFrom methods is
#' @importFrom stats setNames
#' @importFrom styler style_file
# @import shiny miniUI stringi
# @import rstudioapi
NULL
#' Pipe operator
#'
#' @name %>%
#' @rdname pipe
#' @export
#' @importFrom magrittr %>%
NULL
|
At about the same time that Villa and Orozco were marching on Ciudad Juárez , the Zapatista revolt gathered strength and spread to the states of Puebla , Tlaxcala , Mexico , Michoacán and Guerrero . On April 14 , Madero had Emiliano Zapata officially designated as his representative in the region . However , Zapata was worried that if he did not fully control all the major towns in Morelos by the time that Madero concluded negotiations with Díaz , the demands of his agrarian movement and the issue of the autonomy of Morelos would be ignored or sidelined . Zapata 's first military action was to take the town of <unk> where he obtained essential supplies . Subsequently Zapata , for political and strategic reasons , decided to attack the city of Cuautla . In order to mislead his opponents however , he initially attacked and captured the towns of <unk> de Matamoros ( which was subsequently retaken by federal forces ) and <unk> . From there he made a wide circle around Cuautla and captured Yautepec and <unk> where he gathered more supplies , munitions and soldiers . By May , out of all the major urban centers in the region , only Cuautla and the capital of Morelos , Cuernavaca , remained outside of his control .
|
#include "bounded_buffer_signatures_suite.h"
#include "cute.h"
#include "BoundedBuffer.h"
#include <boost/type_index.hpp>
#include <array>
void test_bounded_buffer_value_type_is_value() {
auto value_type = boost::typeindex::type_id_with_cvr<BoundedBuffer<int, 15>::value_type>();
auto expected_type = boost::typeindex::type_id_with_cvr<int>();
ASSERT_EQUAL(expected_type.pretty_name(), value_type.pretty_name());
}
void test_bounded_buffer_reference_type_is_reference() {
auto reference_type = boost::typeindex::type_id_with_cvr<BoundedBuffer<int, 15>::reference>();
auto expected_type = boost::typeindex::type_id_with_cvr<int &>();
ASSERT_EQUAL(expected_type.pretty_name(), reference_type.pretty_name());
}
void test_bounded_buffer_const_reference_type_is_const_reference() {
auto const_reference_type = boost::typeindex::type_id_with_cvr<BoundedBuffer<int, 15>::const_reference>();
auto expected_type = boost::typeindex::type_id_with_cvr<int const &>();
ASSERT_EQUAL(expected_type.pretty_name(), const_reference_type.pretty_name());
}
void test_bounded_buffer_container_type_is_array() {
auto container_type = boost::typeindex::type_id_with_cvr<BoundedBuffer<int, 15>::container_type>();
auto expected_type = boost::typeindex::type_id_with_cvr<std::array<int, 15>>();
ASSERT_EQUAL(expected_type.pretty_name(), container_type.pretty_name());
}
void test_bounded_buffer_size_type_is_size_t() {
auto size_type = boost::typeindex::type_id_with_cvr<BoundedBuffer<int, 15>::size_type>();
auto expected_type = boost::typeindex::type_id_with_cvr<size_t>();
ASSERT_EQUAL(expected_type.pretty_name(), size_type.pretty_name());
}
void test_const_bounded_buffer_type_of_empty_is_bool() {
BoundedBuffer<int, 15> const buffer{};
auto empty_type = boost::typeindex::type_id_with_cvr<decltype(buffer.empty())>();
auto expected_type = boost::typeindex::type_id_with_cvr<bool>();
ASSERT_EQUAL(expected_type.pretty_name(), empty_type.pretty_name());
}
void test_const_bounded_buffer_type_of_full_is_bool() {
BoundedBuffer<int, 15> const buffer{};
auto full_type = boost::typeindex::type_id_with_cvr<decltype(buffer.full())>();
auto expected_type = boost::typeindex::type_id_with_cvr<bool>();
ASSERT_EQUAL(expected_type.pretty_name(), full_type.pretty_name());
}
void test_bounded_buffer_front_type_is_reference_type() {
BoundedBuffer<int, 15> buffer{};
auto front_type = boost::typeindex::type_id_with_cvr<decltype(buffer.front())>();
auto expected_type = boost::typeindex::type_id_with_cvr<BoundedBuffer<int, 15>::reference>();
ASSERT_EQUAL(expected_type.pretty_name(), front_type.pretty_name());
}
void test_const_bounded_buffer_front_type_is_const_reference_type() {
BoundedBuffer<int, 15> const buffer{};
auto front_type = boost::typeindex::type_id_with_cvr<decltype(buffer.front())>();
auto expected_type = boost::typeindex::type_id_with_cvr<BoundedBuffer<int, 15>::const_reference>();
ASSERT_EQUAL(expected_type.pretty_name(), front_type.pretty_name());
}
void test_bounded_buffer_back_type_is_reference_type() {
BoundedBuffer<int, 15> buffer{};
auto back_type = boost::typeindex::type_id_with_cvr<decltype(buffer.back())>();
auto expected_type = boost::typeindex::type_id_with_cvr<BoundedBuffer<int, 15>::reference>();
ASSERT_EQUAL(expected_type.pretty_name(), back_type.pretty_name());
}
void test_const_bounded_buffer_back_type_is_reference_type() {
BoundedBuffer<int, 15> const buffer{};
auto back_type = boost::typeindex::type_id_with_cvr<decltype(buffer.back())>();
auto expected_type = boost::typeindex::type_id_with_cvr<BoundedBuffer<int, 15>::const_reference>();
ASSERT_EQUAL(expected_type.pretty_name(), back_type.pretty_name());
}
void test_bounded_buffer_pop_type_is_reference_type() {
BoundedBuffer<int, 15> buffer{};
auto pop_type = boost::typeindex::type_id_with_cvr<decltype(buffer.pop())>();
auto expected_type = boost::typeindex::type_id_with_cvr<void>();
ASSERT_EQUAL(expected_type.pretty_name(), pop_type.pretty_name());
}
void test_const_bounded_buffer_type_of_size_is_size_t() {
BoundedBuffer<int, 15> const buffer{};
auto size_type = boost::typeindex::type_id_with_cvr<decltype(buffer.size())>();
auto expected_type = boost::typeindex::type_id_with_cvr<size_t>();
ASSERT_EQUAL(expected_type.pretty_name(), size_type.pretty_name());
}
void test_bounded_buffer_type_of_push_of_const_lvalue_is_void() {
BoundedBuffer<int, 15> buffer{};
int const lvalue{23};
auto push_type = boost::typeindex::type_id_with_cvr<decltype(buffer.push(lvalue))>();
auto expected_type = boost::typeindex::type_id_with_cvr<void>();
ASSERT_EQUAL(expected_type.pretty_name(), push_type.pretty_name());
}
void test_bounded_buffer_type_of_push_of_rvalue_is_void() {
BoundedBuffer<int, 15> buffer{};
auto push_type = boost::typeindex::type_id_with_cvr<decltype(buffer.push(23))>();
auto expected_type = boost::typeindex::type_id_with_cvr<void>();
ASSERT_EQUAL(expected_type.pretty_name(), push_type.pretty_name());
}
void test_bounded_buffer_type_of_pop_is_void() {
BoundedBuffer<int, 15> buffer{};
auto pop_type = boost::typeindex::type_id_with_cvr<decltype(buffer.pop())>();
auto expected_type = boost::typeindex::type_id_with_cvr<void>();
ASSERT_EQUAL(expected_type.pretty_name(), pop_type.pretty_name());
}
void test_bounded_buffer_type_of_swap_is_void() {
BoundedBuffer<int, 15> buffer{};
BoundedBuffer<int, 15> other_buffer{};
auto pop_type = boost::typeindex::type_id_with_cvr<decltype(buffer.swap(other_buffer))>();
auto expected_type = boost::typeindex::type_id_with_cvr<void>();
ASSERT_EQUAL(expected_type.pretty_name(), pop_type.pretty_name());
}
cute::suite make_suite_bounded_buffer_signatures_suite(){
cute::suite s;
s.push_back(CUTE(test_bounded_buffer_value_type_is_value));
s.push_back(CUTE(test_bounded_buffer_reference_type_is_reference));
s.push_back(CUTE(test_bounded_buffer_container_type_is_array));
s.push_back(CUTE(test_bounded_buffer_const_reference_type_is_const_reference));
s.push_back(CUTE(test_bounded_buffer_size_type_is_size_t));
s.push_back(CUTE(test_const_bounded_buffer_type_of_empty_is_bool));
s.push_back(CUTE(test_const_bounded_buffer_type_of_full_is_bool));
s.push_back(CUTE(test_bounded_buffer_front_type_is_reference_type));
s.push_back(CUTE(test_bounded_buffer_back_type_is_reference_type));
s.push_back(CUTE(test_const_bounded_buffer_back_type_is_reference_type));
s.push_back(CUTE(test_bounded_buffer_pop_type_is_reference_type));
s.push_back(CUTE(test_const_bounded_buffer_front_type_is_const_reference_type));
s.push_back(CUTE(test_const_bounded_buffer_type_of_size_is_size_t));
s.push_back(CUTE(test_bounded_buffer_type_of_push_of_const_lvalue_is_void));
s.push_back(CUTE(test_bounded_buffer_type_of_push_of_rvalue_is_void));
s.push_back(CUTE(test_bounded_buffer_type_of_pop_is_void));
s.push_back(CUTE(test_bounded_buffer_type_of_swap_is_void));
return s;
}
|
The degree of a numeral is zero. |
Formal statement is: lemma is_pole_cong: assumes "eventually (\<lambda>x. f x = g x) (at a)" "a=b" shows "is_pole f a \<longleftrightarrow> is_pole g b" Informal statement is: If two functions are equal in a neighborhood of a point, then they have the same pole at that point. |
If a set of vectors is linearly independent, then it is finite and has at most as many elements as the dimension of the vector space. |
State Before: α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
h : Nodup s
x : α
hx : ¬x ∈ s
⊢ ↑(formPerm s h) x = x State After: case h
α : Type u_1
inst✝ : DecidableEq α
s s' : Cycle α
x : α
a✝ : List α
h : Nodup (Quot.mk Setoid.r a✝)
hx : ¬x ∈ Quot.mk Setoid.r a✝
⊢ ↑(formPerm (Quot.mk Setoid.r a✝) h) x = x Tactic: induction s using Quot.inductionOn State Before: case h
α : Type u_1
inst✝ : DecidableEq α
s s' : Cycle α
x : α
a✝ : List α
h : Nodup (Quot.mk Setoid.r a✝)
hx : ¬x ∈ Quot.mk Setoid.r a✝
⊢ ↑(formPerm (Quot.mk Setoid.r a✝) h) x = x State After: no goals Tactic: simpa using List.formPerm_eq_self_of_not_mem _ _ hx |
Copyright © 2019 AeroCheck. Theme: Himalayas by ThemeGrill. Powered by WordPress. |
using BISC195
using Test
@testset "BISC195.jl" begin
# Write your tests here.
end
|
Webb demonstrated his aggressiveness when he attempted to sortie on the first spring tide ( 30 May ) after taking command , but Atlanta 's forward engine broke down after he had passed the obstructions , and the ship ran aground . She was not damaged although it took over a day to pull her free . He planned to make another attempt on the next full tide , rejecting Mallory 's idea that he wait until the nearly complete ironclad Savannah was finished before his next sortie . In the meantime , Rear Admiral Samuel F. Du Pont , commander of the South Atlantic Blockading Squadron , had ordered the monitors Weehawken and Nahant into <unk> Sound . Commander John Rodgers in Weehawken had overall command of the two ships .
|
function TF = isempty(TC)
%ISEMPTY Display threecomp object
% TF = ISEMPTY(TC) returns an array the same size as TC, containing
% logical 1 (true) where the elements of TC are empty, and logical 0
% (false) elsewhere. Empty is defined as containging no waveform data.
% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
% $Date$
% $Revision$
% CHECK INPUTS
if ~isa(TC,'threecomp')
error('First argment must be a threecomp object');
end
if nargin~=1
error('Incorrect number of arguments');
end
% CHECK EACH ELEMENT TO SEE IF IT IS EMPTY
[objSize1,objSize2] = size(TC);
numObj = numel(TC);
TF = zeros(size(TC));
for n = 1:numObj
numSamples = min(get(TC(n).traces,'DATA_LENGTH'));
if numSamples == 0
TF(n) = 1;
else
TF(n) = 0;
end
end
|
[STATEMENT]
lemma tpOfV_pred: "\<exists> f. tpOfV_pred f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
define Ut Uv where "Ut = (UNIV :: 'tp set)" and "Uv = (UNIV :: var set)"
[PROOF STATE]
proof (state)
this:
Ut = UNIV
Uv = UNIV
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
define Unt where "Unt = (UNIV :: nat set)"
[PROOF STATE]
proof (state)
this:
Unt = UNIV
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
define U2 where "U2 = (UNIV :: ('tp \<times> nat) set)"
[PROOF STATE]
proof (state)
this:
U2 = UNIV
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
have U2: "U2 \<equiv> Ut \<times> Unt"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. U2 \<equiv> Ut \<times> Unt
[PROOF STEP]
unfolding Ut_def Unt_def U2_def UNIV_Times_UNIV
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. UNIV \<equiv> UNIV
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
U2 \<equiv> Ut \<times> Unt
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
have "|U2| =o |Unt \<times> Ut|"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. |U2| =o |Unt \<times> Ut|
[PROOF STEP]
unfolding U2
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. |Ut \<times> Unt| =o |Unt \<times> Ut|
[PROOF STEP]
by (metis card_of_Times_commute)
[PROOF STATE]
proof (state)
this:
|U2| =o |Unt \<times> Ut|
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
|U2| =o |Unt \<times> Ut|
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
have "|Unt \<times> Ut| =o |Unt|"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. |Unt \<times> Ut| =o |Unt|
[PROOF STEP]
apply(rule card_of_Times_infinite_simps(1))
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. infinite Unt
2. Ut \<noteq> {}
3. |Ut| \<le>o |Unt|
[PROOF STEP]
unfolding Ut_def Unt_def
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. infinite UNIV
2. UNIV \<noteq> {}
3. |UNIV| \<le>o |UNIV|
[PROOF STEP]
apply (metis nat_not_finite)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. UNIV \<noteq> {}
2. |UNIV| \<le>o |UNIV|
[PROOF STEP]
apply (metis UNIV_not_empty)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. |UNIV| \<le>o |UNIV|
[PROOF STEP]
by (metis countable_card_of_nat countable_tp)
[PROOF STATE]
proof (state)
this:
|Unt \<times> Ut| =o |Unt|
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
|Unt \<times> Ut| =o |Unt|
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
have "|Unt| =o |Uv|"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. |Unt| =o |Uv|
[PROOF STEP]
apply(rule ordIso_symmetric)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. |Uv| =o |Unt|
[PROOF STEP]
unfolding Unt_def Uv_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. |UNIV| =o |UNIV|
[PROOF STEP]
using card_of_var card_of_nat[THEN ordIso_symmetric]
[PROOF STATE]
proof (prove)
using this:
|UNIV| =o natLeq
natLeq =o |UNIV|
goal (1 subgoal):
1. |UNIV| =o |UNIV|
[PROOF STEP]
by(rule ordIso_transitive)
[PROOF STATE]
proof (state)
this:
|Unt| =o |Uv|
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
|U2| =o |Uv|
[PROOF STEP]
have "|U2| =o |Uv|"
[PROOF STATE]
proof (prove)
using this:
|U2| =o |Uv|
goal (1 subgoal):
1. |U2| =o |Uv|
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
|U2| =o |Uv|
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
hence "|Uv| =o |U2|"
[PROOF STATE]
proof (prove)
using this:
|U2| =o |Uv|
goal (1 subgoal):
1. |Uv| =o |U2|
[PROOF STEP]
by(rule ordIso_symmetric)
[PROOF STATE]
proof (state)
this:
|Uv| =o |U2|
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
|Uv| =o |U2|
[PROOF STEP]
obtain g where g: "bij_betw g Uv U2"
[PROOF STATE]
proof (prove)
using this:
|Uv| =o |U2|
goal (1 subgoal):
1. (\<And>g. bij_betw g Uv U2 \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
unfolding card_of_ordIso[symmetric]
[PROOF STATE]
proof (prove)
using this:
\<exists>f. bij_betw f Uv U2
goal (1 subgoal):
1. (\<And>g. bij_betw g Uv U2 \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
bij_betw g Uv U2
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Ex tpOfV_pred
[PROOF STEP]
apply(rule exI[of _ "fst o g"])
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. tpOfV_pred (fst \<circ> g)
[PROOF STEP]
unfolding tpOfV_pred_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>\<sigma>. infinite ((fst \<circ> g) -` {\<sigma>})
[PROOF STEP]
apply safe
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>\<sigma>. finite ((fst \<circ> g) -` {\<sigma>}) \<Longrightarrow> False
[PROOF STEP]
unfolding vimage_comp [symmetric]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>\<sigma>. finite (g -` fst -` {\<sigma>}) \<Longrightarrow> False
[PROOF STEP]
apply (drule finite_vimageD)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>\<sigma>. surj g
2. \<And>\<sigma>. finite (fst -` {\<sigma>}) \<Longrightarrow> False
[PROOF STEP]
using g
[PROOF STATE]
proof (prove)
using this:
bij_betw g Uv U2
goal (2 subgoals):
1. \<And>\<sigma>. surj g
2. \<And>\<sigma>. finite (fst -` {\<sigma>}) \<Longrightarrow> False
[PROOF STEP]
unfolding bij_betw_def Uv_def U2_def
[PROOF STATE]
proof (prove)
using this:
inj g \<and> surj g
goal (2 subgoals):
1. \<And>\<sigma>. surj g
2. \<And>\<sigma>. finite (fst -` {\<sigma>}) \<Longrightarrow> False
[PROOF STEP]
by (auto simp: infinite_fst_vimage)
[PROOF STATE]
proof (state)
this:
Ex tpOfV_pred
goal:
No subgoals!
[PROOF STEP]
qed |
module Linear
import public Linear.Epsilon
import public Linear.Metric
import public Linear.Vect
|
/-
Copyright (c) 2023 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Kevin Buzzard
-/
import tactic
import combinatorics.simple_graph.basic -- definition of graph
/-
# Graph theory
A year ago Lean's graph theory was a bit patchy, but now I think
it's robust enough to be taken seriously as a topic for a final project.
This sheet is just an overview of the basic API for graphs; there are
no sorrys.
So, how do graphs work in Lean? Actually it took a long time
to come up with a definition people were happy with. One issue
is that different people mean different things by "graph". In this
section we're going to stick to "simple graphs", which means
that you have a type of vertices `V`, and edges go between two
distinct vertices in `V`. The rules for a simple graph:
1) Edges are undirected (so they don't have a source and a target, they
just have two ends, which are vertices)
2) You can't have more than one edge between two distinct vertices.
3) You can't have an edge going from a vertex to itself.
Because of rule 2, you can represent an edge as a yes/no question:
"is there an edge between `v` and `w` or not?". In other words
you can represent edges as a function `adj: V → V → Prop`, and you
don't need a separate set or type `E` for edges. `adj` is short
for "adjacent", so `adj v w` means "there's an edge between `v` and `w`,
i.e. "`v` is adjacent to `w`".
Rule 1 means that `adj` is symmetric (if `v` is adjacent to `w` then
`w` is adjacent to `v`), and rule 3 means that it is irreflexive,
i.e. `∀ v, ¬ adj v v`.
Here's how to say "let `G` be a (simple) graph with vertex set `V`"
-/
variables (V : Type) (G : simple_graph V)
-- Here's how to say two edges are adjacent
example (v w : V) : Prop := G.adj v w
-- If v is adjacent to w then w is adjacent to v
example (v w : V) : G.adj v w → G.adj w v := G.adj_symm
-- v isn't adjacent to itself
example (v : V) : ¬ G.adj v v := G.irrefl
/-
Longish interlude: here's how to make a square graph. It's quite laborious.
Lean is better at proving theorems than making explicit examples!
v1 -- v2
| |
| |
v3 -- v4
-/
section square_graph
-- the vertex set of the square graph; we make it a type with four terms
inductive sqV : Type
| v1 : sqV
| v2 : sqV
| v3 : sqV
| v4 : sqV
open sqV -- so I can write `v1` not `sqV.v1`
-- here's one boring way of making the edges -- an inductive proposition
inductive sqE : sqV → sqV → Prop
| e12 : sqE v1 v2
| e21 : sqE v2 v1
| e24 : sqE v2 v4
| e42 : sqE v4 v2
| e34 : sqE v3 v4
| e43 : sqE v4 v3
| e13 : sqE v1 v3
| e31 : sqE v3 v1
-- Now let's make the graph
def sqG : simple_graph sqV :=
{ adj := sqE,
symm := begin
-- do all the cases for the two vertices and the edge
rintro (_ | _ | _ | _) (_ | _ | _ | _) (_ | _ | _ | _ | _ | _ | _ | _),
-- now 8 goals; find the right constructor for sqE in all cases
repeat {constructor},
end,
loopless := begin
rintro (_ | _ | _ | _) (_ | _ | _ | _ | _ | _ | _ | _),
end }
end square_graph
-- Here's how to make a triangle graph; it's rather easier
-- Here `fin 3` is the "canonical" type with 3 terms; to give a term of type `fin 3`
-- is to give a pair consisting of a natural `n` and a proof that `n < 3`.
-- Here the `complete_graph` function is doing all the work for you.
example : simple_graph (fin 3) := complete_graph (fin 3)
-- The collection of all simple graphs on a fixed vertex set `V` form a Boolean algebra
-- (whatever that is)
example : boolean_algebra (simple_graph V) := by apply_instance
-- and in particular they form a lattice, so you can do stuff like this:
example : simple_graph V := ⊥ -- empty graph
example : simple_graph V := ⊤ -- complete graph
example (G H : simple_graph V) : simple_graph V := G ⊔ H -- union of vertices
-- etc etc, and you can even do this
example (G : simple_graph V) : simple_graph V := Gᶜ -- complement, i.e. an edge exists in `Gᶜ` between
-- distinct vertices `v` and `w` iff it doesn't
-- exist in `G`
-- The *support* of a graph is the vertices that have an edge coming from them.
example (v : V) : v ∈ G.support ↔ ∃ w, G.adj v w :=
begin
refl, -- true by definition
end
-- The `neighbor_set` of a vertex is all the vertices connected to it by an edge.
example (v : V) : set V := G.neighbor_set v
example (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w := iff.rfl -- true by defn
-- The type `sym2 V` is the type of unordered pairs of elements of `V`, i.e. `V × V`
-- modulo the equivalence relation generated by `(v,w)~(w,v)`.
-- So you can regard the edges as a subset of `sym2 V`, and that's `G.edge_set`
example : set (sym2 V) := G.edge_set
-- You can use `v ∈ e` notation if `e : sym2 v`
-- For example, `G.incidence_set v` is the set of edges coming out of `v`,
-- regarded as elements of `sym2 V`
example (v : V) : G.incidence_set v = {e ∈ G.edge_set | v ∈ e} := rfl
-- You can delete a set of edges from `G` using `G.delete_edges`
example (E : set (sym2 V)) : simple_graph V := G.delete_edges E
-- if E contains edges not in G then this doesn't matter, they're just ignored.
-- You can push a graph forward along an injection
example (W : Type) (f : V ↪ W) : simple_graph W := G.map f
-- and pull it back along an arbitrary map
example (U : Type) (g : U → V) : simple_graph U := G.comap g
-- The degree of a vertex is the size of its neighbor_set.
-- Better assume some finiteness conditions to make this work.
variable [G.locally_finite]
-- now we have `finset` versions of some `set` things. For example
example (v : V) : G.degree v = finset.card (G.neighbor_finset v) := rfl
-- If `H` is another graph on a vertex set `W`
variables (W : Type) (H : simple_graph W)
-- then we can consider types of various maps between graphs
example : Type := G →g H -- maps f:V → W such that v₁~v₂ -> f(v₁)~f(v₂)
example : Type := G ↪g H -- injections f : V → W such that v₁~v₂ ↔ f(v₁)~f(v₂)
example : Type := G ≃g H -- isomorphisms of graphs |
subroutine intdir(gg,gp,ag,ap,ggmat,gpmat,en,fl,agi,api,ainf,max0)
c solution of the inhomogenios dirac equation
c gg gp initially exch. terms, at the time of return are wave functions
c ag and ap development coefficients of gg and gp
c ggmat gpmat values at the matching point for the inward integration
c en one-electron energy
c fl power of the first development term at the origin
c agi (api) initial values of the first development coefficients
c at the origin of a large (small) component
c ainf initial value for large component at point dr(max0)
c - at the end of tabulation of gg gp
implicit double precision (a-h,o-z)
common/comdir/cl,dz,bid1(522),dv(251),av(10),bid2(522)
common/tabtes/hx,dr(251),test1,test2,ndor,np,nes,method,idim
common/subdir/ell,fk,ccl,imm,nd,node,mat
common/messag/dlabpr,numerr
character*8 dlabpr
dimension gg(251),gp(251),ag(10),ap(10),coc(5),cop(5),dg(5),dp(5)
save
data cop/2.51d+02,-1.274d+03,2.616d+03,-2.774d+03,1.901d+03/,
1coc/-1.9d+01,1.06d+02,-2.64d+02,6.46d+02,2.51d+02/,
2cmixn/4.73d+02/,cmixd/5.02d+02/,hxd/7.2d+02/,npi/5/,icall/0/
c numerical method is a 5-point predictor-corrector method
c predicted value p(n) = y(n-1) + c * somme de i=1,5 cop(i)*y'(n-i)
c corrected value c(n) = y(n-1) + c * somme de i=1,4 coc(i)*y'(n-i)
c + coc(5)*p'(n)
c final value y(n) = cmix*c(n) + (1.-cmix)*p(n)
c cmix=cmixn/cmixd
if (icall.eq.0) then
icall=1
c=cmixn/cmixd
a=1.0d 00-c
cmc=c*coc(5)
f=coc(1)
do j=2,npi
g=coc(j)
coc(j)=c*f+a*cop(j)
f=g
enddo
coc(1)=c*cop(1)
endif
c=hx/hxd
ec=en/cl
ag(1)=agi
ap(1)=api
if (imm.lt.0) goto 81
if (imm.eq.0) then
c search for the second sign change point
mat=npi
j=1
16 continue
mat=mat+2
if (mat.ge.np) then
c i had trouble with screened k-hole for la, for f-electrons.
c below i still define matching point if one electron energy not less
c than -1ev.
if (ec .gt. -0.0003) then
mat = np - 12
go to 25
endif
numerr=56011
c * fail to find matching point
return
endif
f=dv(mat)+ell/(dr(mat)*dr(mat))
f=(f-ec)*j
if (f.gt.0) goto 16
25 continue
j = -j
if (j.lt.0) go to 16
if (mat .ge. np-npi) mat=np-12
c initial values for the outward integration
endif
do j=2,ndor
k=j-1
a=fl+fk+k
b=fl-fk+k
ep=a*b+av(1)*av(1)
f=(ec+ccl)*ap(k)+ap(j)
g=ec*ag(k)+ag(j)
do i=1,k
f=f-av(i+1)*ap(j-i)
g=g-av(i+1)*ag(j-i)
enddo
ag(j)=(b*f+av(1)*g)/ep
ap(j)=(av(1)*f-a*g)/ep
enddo
do i=1,npi
gg(i)=0.0d 00
gp(i)=0.0d 00
dg(i)=0.0d 00
dp(i)=0.0d 00
do j=1,ndor
a=fl+j-1
b=dr(i)**a
a=a*b*c
gg(i)=gg(i)+b*ag(j)
gp(i)=gp(i)+b*ap(j)
dg(i)=dg(i)+a*ag(j)
dp(i)=dp(i)+a*ap(j)
enddo
enddo
i=npi
k=1
ggmat=gg(mat)
gpmat=gp(mat)
c integration of the inhomogenious system
51 continue
cmcc=cmc*c
55 continue
a=gg(i)+dg(1)*cop(1)
b=gp(i)+dp(1)*cop(1)
i=i+k
ep=gp(i)
eg=gg(i)
gg(i)=a-dg(1)*coc(1)
gp(i)=b-dp(1)*coc(1)
do j=2,npi
a=a+dg(j)*cop(j)
b=b+dp(j)*cop(j)
gg(i)=gg(i)+dg(j)*coc(j)
gp(i)=gp(i)+dp(j)*coc(j)
dg(j-1)=dg(j)
dp(j-1)=dp(j)
enddo
f=(ec-dv(i))*dr(i)
g=f+ccl*dr(i)
gg(i)=gg(i)+cmcc*(g*b-fk*a+ep)
gp(i)=gp(i)+cmcc*(fk*b-f*a-eg)
dg(npi)=c*(g*gp(i)-fk*gg(i)+ep)
dp(npi)=c*(fk*gp(i)-f*gg(i)-eg)
if (i.ne.mat) go to 55
if (k.lt.0) go to 999
a=ggmat
ggmat=gg(mat)
gg(mat)=a
a=gpmat
gpmat=gp(mat)
gp(mat)=a
if (imm.ne.0) go to 81
c initial values for inward integration
a=test1* abs(ggmat)
if (ainf.gt.a) ainf=a
max0=np+2
73 continue
a=7.0d+02/cl
75 continue
max0=max0-2
if ((max0+1).le.(mat+npi)) then
numerr=138021
c *the last tabulation point is too close to the matching point
return
endif
if (((dv(max0)-ec)*dr(max0)*dr(max0)).gt.a) go to 75
81 continue
c=-c
a=- sqrt(-ec*(ccl+ec))
if ((a*dr(max0)).lt.-1.7d+02) go to 73
b=a/(ccl+ec)
f=ainf/ exp(a*dr(max0))
if (f.eq.0.0d 00) f=1.0d 00
do i=1,npi
j=max0+1-i
gg(j)=f* exp(a*dr(j))
gp(j)=b*gg(j)
dg(i)=a*dr(j)*gg(j)*c
dp(i)=b*dg(i)
enddo
i=max0-npi+1
k=-1
go to 51
999 return
end
|
(* Title: HOL/Auth/n_flash_nodata_cub_lemma_on_inv__96.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_flash_nodata_cub Protocol Case Study*}
theory n_flash_nodata_cub_lemma_on_inv__96 imports n_flash_nodata_cub_base
begin
section{*All lemmas on causal relation between inv__96 and some rule r*}
lemma n_NI_Local_Get_Put_HeadVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__96:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__96:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__96:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_ReplaceVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Replace src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Replace src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))"
have "?P2 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__96:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__96:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX__part__0Vsinv__96:
assumes a1: "(r=n_PI_Local_GetX_PutX__part__0 )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const false))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX__part__1Vsinv__96:
assumes a1: "(r=n_PI_Local_GetX_PutX__part__1 )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const false))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_PutXVsinv__96:
assumes a1: "(r=n_PI_Local_PutX )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_PutVsinv__96:
assumes a1: "(r=n_NI_Local_Put )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_WbVsinv__96:
assumes a1: "(r=n_NI_Wb )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_ShWbVsinv__96:
assumes a1: "(r=n_NI_ShWb N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "((formEval (andForm (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))\<or>((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) s))\<or>((formEval (andForm (neg (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_PutX_HomeVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetVsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__1Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__96:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__96:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__96:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__1Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__1Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Get__part__0Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__96:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__2Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Put_HomeVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__2Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__0Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__96:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__96:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_NakVsinv__96:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_NakVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetXVsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_PutXVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_PutVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_PutVsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__0Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__96:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_PutXVsinv__96:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_NakVsinv__96:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__96:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__0Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__96:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_PutVsinv__96:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__96:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__96:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
function [A]=patchArea(F,V)
% function [A]=patchArea(F,V)
% ------------------------------------------------------------------------
% This simple function calculates the areas of the faces specified by F and
% V. The output is a vector A containing size(F,1) elements. The face areas
% are calculated via triangulation of the faces. If faces are already
% triangular triangulation is skipped are area calculation is direction
% performed.
%
%
%
% Kevin Mattheus Moerman
%
% 2011/04/12
% 2021/09/13 Updated to use more efficient patchEdgeCrossProduct method
% 2021/09/14 Renamed to patchArea
%------------------------------------------------------------------------
%%
C=patchEdgeCrossProduct(F,V);
A=sqrt(sum(C.^2,2));
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
|
module Replica.Command.Info
import Data.String
import Replica.Help
import Replica.Option.Filter
import Replica.Option.Global
import Replica.Option.Types
import Replica.Other.Decorated
%default total
public export
record InfoCommand' (f : Type -> Type) where
constructor MkInfo
showExpectation : f Bool
filter : Filter' f
global : Global' f
public export
InfoCommand : Type
InfoCommand = Done InfoCommand'
export
TyMap InfoCommand' where
tyMap func x = MkInfo
(func x.showExpectation)
(tyMap func x.filter) (tyMap func x.global)
export
TyTraversable InfoCommand' where
tyTraverse func x = [| MkInfo
(func x.showExpectation)
(tyTraverse func x.filter) (tyTraverse func x.global)
|]
export
Show InfoCommand where
show i = unwords [ "MkInfo"
, show i.showExpectation
, show i.filter
, show i.global]
showExpectationPart : Part (Builder InfoCommand') Bool
showExpectationPart = inj $ MkOption
( singleton
$ MkMod (singleton "expectations") ['e'] (Left True)
"show expectation for each test")
False
go
where
go : Bool -> Builder InfoCommand' -> Either String (Builder InfoCommand')
go = ifSame showExpectation
(\x => record {showExpectation = Right x})
(const $ const "Contradictory values for expectations")
optParseInfo : OptParse (Builder InfoCommand') InfoCommand
optParseInfo = [|MkInfo
(liftAp showExpectationPart)
(embed filter (\x => record {filter = x}) optParseFilter)
(embed global (\x => record {global = x}) optParseGlobal)
|]
defaultInfo : Default InfoCommand'
defaultInfo = MkInfo
(defaultPart showExpectationPart)
defaultFilter
defaultGlobal
export
parseInfo : List1 String -> ParseResult InfoCommand
parseInfo ("info":::xs) = case parse (initBuilder defaultInfo) optParseInfo xs of
InvalidMix reason => InvalidMix reason
InvalidOption ys => InvalidMix "Unknown option: \{ys.head}"
Done x => maybe (InvalidMix "File is not set") Done $ build x
parseInfo xs = InvalidOption xs
export
helpInfo : Help
helpInfo =
commandHelp {b = Builder InfoCommand'}
"info" "Display information about test suites"
optParseInfo
(Just "JSON_TEST_FILE")
|
The damage dealt to the agricultural sector of Antigua and Barbuda fueled major concerns for " food security " in 2009 . The government allocated about $ 33 @,@ 897 @,@ 420 to help develop and repair the industry . Significant expansions of croplands were discussed , 15 @,@ 000 ft2 ( <unk> m2 ) area , to help promote growth of the sector .
|
Sell my PlayBook 4G LTE 32GB tablet. Important! Factory reset your tablet before sending or we may be unable to process it. |
-- Exercise_5_2.idr
-- Implement a guessing game fro numbers
module Main
import System
import ReadNum
||| Guessing game: Interactive dialogs to guess a given number.
||| @target the number to be guessed
||| @guesses the number of trials
guess : (target : Nat) -> (guesses : Nat) -> IO ()
guess target guesses =
do putStr ("Guess my number " ++ "(" ++ (show guesses) ++ " trial): ")
Just trial <- readNumber | Nothing => (putStrLn "Invalid input! Try again.." >>= \_ =>
guess target guesses)
case compare trial target of
EQ => putStrLn "Correct!"
LT => putStrLn "Too small, try again.." >>= \_ => guess target (S guesses)
GT => putStrLn "Too large, try again.." >>= \_ => guess target (S guesses)
||| Mimic replWith function from Prelude module
myReplWith : (state : a) -> (prompt : String) -> (onInput : a -> String -> Maybe (String, a)) -> IO ()
myReplWith state prompt onInput = do
putStr prompt
input <- getLine
let Just (output, newState) = onInput state input | Nothing => pure ()
putStr output
myReplWith newState prompt onInput
||| Mimic repl function from Prelude module
myRepl : (prompt : String) -> (onInput : String -> String) -> IO ()
myRepl prompt onInput = myReplWith () prompt (\(), input => Just (onInput input, ()))
main : IO ()
main = do
tsecs <- time
let target = tsecs `mod` 100
guess (cast target) 1
|
[STATEMENT]
lemma same_messages_2:
assumes
"\<forall>p. has_snapshotted c p = has_snapshotted d p" and
"msgs c i = msgs d i" and
"c \<turnstile> ev \<mapsto> c'" and
"d \<turnstile> ev \<mapsto> d'" and
"~ regular_event ev"
shows
"msgs c' i = msgs d' i"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
proof (cases "channel i = None")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. channel i = None \<Longrightarrow> msgs c' i = msgs d' i
2. channel i \<noteq> None \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
channel i = None
goal (2 subgoals):
1. channel i = None \<Longrightarrow> msgs c' i = msgs d' i
2. channel i \<noteq> None \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
channel i = None
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
channel i = None
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
using assms(2) assms(3) assms(4) no_msgs_change_if_no_channel
[PROOF STATE]
proof (prove)
using this:
channel i = None
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<lbrakk>?c \<turnstile> ?ev \<mapsto> ?c'; channel ?i = None\<rbrakk> \<Longrightarrow> msgs ?c ?i = msgs ?c' ?i
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal (1 subgoal):
1. channel i \<noteq> None \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. channel i \<noteq> None \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
channel i \<noteq> None
goal (1 subgoal):
1. channel i \<noteq> None \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
channel i \<noteq> None
[PROOF STEP]
obtain p q where chan: "channel i = Some (p, q)"
[PROOF STATE]
proof (prove)
using this:
channel i \<noteq> None
goal (1 subgoal):
1. (\<And>p q. channel i = Some (p, q) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
channel i = Some (p, q)
goal (1 subgoal):
1. channel i \<noteq> None \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
have "isSnapshot ev \<or> isRecvMarker ev"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. isSnapshot ev \<or> isRecvMarker ev
[PROOF STEP]
using assms(5) event.exhaust_disc
[PROOF STATE]
proof (prove)
using this:
\<not> regular_event ev
\<lbrakk>isTrans ?event \<Longrightarrow> ?P; isSend ?event \<Longrightarrow> ?P; isRecv ?event \<Longrightarrow> ?P; isSnapshot ?event \<Longrightarrow> ?P; isRecvMarker ?event \<Longrightarrow> ?P\<rbrakk> \<Longrightarrow> ?P
goal (1 subgoal):
1. isSnapshot ev \<or> isRecvMarker ev
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
isSnapshot ev \<or> isRecvMarker ev
goal (1 subgoal):
1. channel i \<noteq> None \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
isSnapshot ev \<or> isRecvMarker ev
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
isSnapshot ev \<or> isRecvMarker ev
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
proof (elim disjE)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. isSnapshot ev \<Longrightarrow> msgs c' i = msgs d' i
2. isRecvMarker ev \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
assume "isSnapshot ev"
[PROOF STATE]
proof (state)
this:
isSnapshot ev
goal (2 subgoals):
1. isSnapshot ev \<Longrightarrow> msgs c' i = msgs d' i
2. isRecvMarker ev \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
isSnapshot ev
[PROOF STEP]
obtain r where Snapshot: "ev = Snapshot r"
[PROOF STATE]
proof (prove)
using this:
isSnapshot ev
goal (1 subgoal):
1. (\<And>r. ev = Snapshot r \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (meson isSnapshot_def)
[PROOF STATE]
proof (state)
this:
ev = Snapshot r
goal (2 subgoals):
1. isSnapshot ev \<Longrightarrow> msgs c' i = msgs d' i
2. isRecvMarker ev \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
ev = Snapshot r
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
ev = Snapshot r
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
proof (cases "r = p")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>ev = Snapshot r; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
r = p
goal (2 subgoals):
1. \<lbrakk>ev = Snapshot r; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
r = p
[PROOF STEP]
have "msgs c' i = msgs c i @ [Marker]"
[PROOF STATE]
proof (prove)
using this:
r = p
goal (1 subgoal):
1. msgs c' i = msgs c i @ [Marker]
[PROOF STEP]
using chan Snapshot assms
[PROOF STATE]
proof (prove)
using this:
r = p
channel i = Some (p, q)
ev = Snapshot r
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs c' i = msgs c i @ [Marker]
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs c i @ [Marker]
goal (2 subgoals):
1. \<lbrakk>ev = Snapshot r; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs c i @ [Marker]
goal (2 subgoals):
1. \<lbrakk>ev = Snapshot r; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
have "msgs d' i = msgs d i @ [Marker]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. msgs d' i = msgs d i @ [Marker]
[PROOF STEP]
using chan Snapshot assms True
[PROOF STATE]
proof (prove)
using this:
channel i = Some (p, q)
ev = Snapshot r
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
r = p
goal (1 subgoal):
1. msgs d' i = msgs d i @ [Marker]
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs d' i = msgs d i @ [Marker]
goal (2 subgoals):
1. \<lbrakk>ev = Snapshot r; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
msgs c' i = msgs c i @ [Marker]
msgs d' i = msgs d i @ [Marker]
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
msgs c' i = msgs c i @ [Marker]
msgs d' i = msgs d i @ [Marker]
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
msgs c' i = msgs c i @ [Marker]
msgs d' i = msgs d i @ [Marker]
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal (1 subgoal):
1. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
r \<noteq> p
goal (1 subgoal):
1. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
r \<noteq> p
[PROOF STEP]
have "msgs c' i = msgs c i"
[PROOF STATE]
proof (prove)
using this:
r \<noteq> p
goal (1 subgoal):
1. msgs c' i = msgs c i
[PROOF STEP]
using chan Snapshot assms
[PROOF STATE]
proof (prove)
using this:
r \<noteq> p
channel i = Some (p, q)
ev = Snapshot r
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs c' i = msgs c i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs c i
goal (1 subgoal):
1. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs c i
goal (1 subgoal):
1. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
have "msgs d' i = msgs d i"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. msgs d' i = msgs d i
[PROOF STEP]
using chan Snapshot assms False
[PROOF STATE]
proof (prove)
using this:
channel i = Some (p, q)
ev = Snapshot r
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
r \<noteq> p
goal (1 subgoal):
1. msgs d' i = msgs d i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs d' i = msgs d i
goal (1 subgoal):
1. \<lbrakk>ev = Snapshot r; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
msgs c' i = msgs c i
msgs d' i = msgs d i
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
msgs c' i = msgs c i
msgs d' i = msgs d i
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
msgs c' i = msgs c i
msgs d' i = msgs d i
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal (1 subgoal):
1. isRecvMarker ev \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. isRecvMarker ev \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
assume "isRecvMarker ev"
[PROOF STATE]
proof (state)
this:
isRecvMarker ev
goal (1 subgoal):
1. isRecvMarker ev \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
isRecvMarker ev
[PROOF STEP]
obtain i' r s where RecvMarker: "ev = RecvMarker i' r s"
[PROOF STATE]
proof (prove)
using this:
isRecvMarker ev
goal (1 subgoal):
1. (\<And>i' r s. ev = RecvMarker i' r s \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (meson isRecvMarker_def)
[PROOF STATE]
proof (state)
this:
ev = RecvMarker i' r s
goal (1 subgoal):
1. isRecvMarker ev \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
ev = RecvMarker i' r s
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
ev = RecvMarker i' r s
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
proof (cases "has_snapshotted c r")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>ev = RecvMarker i' r s; ps c r \<noteq> None\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ev = RecvMarker i' r s; \<not> ps c r \<noteq> None\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case snap: True
[PROOF STATE]
proof (state)
this:
ps c r \<noteq> None
goal (2 subgoals):
1. \<lbrakk>ev = RecvMarker i' r s; ps c r \<noteq> None\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ev = RecvMarker i' r s; \<not> ps c r \<noteq> None\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
ps c r \<noteq> None
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
ps c r \<noteq> None
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
proof (cases "i = i'")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
i = i'
goal (2 subgoals):
1. \<lbrakk>ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
i = i'
[PROOF STEP]
have "Marker # msgs c' i = msgs c i"
[PROOF STATE]
proof (prove)
using this:
i = i'
goal (1 subgoal):
1. Marker # msgs c' i = msgs c i
[PROOF STEP]
using chan RecvMarker assms snap
[PROOF STATE]
proof (prove)
using this:
i = i'
channel i = Some (p, q)
ev = RecvMarker i' r s
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
ps c r \<noteq> None
goal (1 subgoal):
1. Marker # msgs c' i = msgs c i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
Marker # msgs c' i = msgs c i
goal (2 subgoals):
1. \<lbrakk>ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
Marker # msgs c' i = msgs c i
goal (2 subgoals):
1. \<lbrakk>ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
have "Marker # msgs d' i = msgs d i"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Marker # msgs d' i = msgs d i
[PROOF STEP]
using chan RecvMarker assms snap True
[PROOF STATE]
proof (prove)
using this:
channel i = Some (p, q)
ev = RecvMarker i' r s
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
ps c r \<noteq> None
i = i'
goal (1 subgoal):
1. Marker # msgs d' i = msgs d i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
Marker # msgs d' i = msgs d i
goal (2 subgoals):
1. \<lbrakk>ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
Marker # msgs c' i = msgs c i
Marker # msgs d' i = msgs d i
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
Marker # msgs c' i = msgs c i
Marker # msgs d' i = msgs d i
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
Marker # msgs c' i = msgs c i
Marker # msgs d' i = msgs d i
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
by (metis list.inject)
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal (1 subgoal):
1. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
i \<noteq> i'
goal (1 subgoal):
1. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
i \<noteq> i'
[PROOF STEP]
have "msgs d' i = msgs d i"
[PROOF STATE]
proof (prove)
using this:
i \<noteq> i'
goal (1 subgoal):
1. msgs d' i = msgs d i
[PROOF STEP]
using RecvMarker assms(1) assms(4) snap
[PROOF STATE]
proof (prove)
using this:
i \<noteq> i'
ev = RecvMarker i' r s
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
d \<turnstile> ev \<mapsto> d'
ps c r \<noteq> None
goal (1 subgoal):
1. msgs d' i = msgs d i
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
msgs d' i = msgs d i
goal (1 subgoal):
1. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
msgs d' i = msgs d i
goal (1 subgoal):
1. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
have "... = msgs c i"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. msgs d i = msgs c i
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs d i = msgs c i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs d i = msgs c i
goal (1 subgoal):
1. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
msgs d i = msgs c i
goal (1 subgoal):
1. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
have "... = msgs c' i"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. msgs c i = msgs c' i
[PROOF STEP]
using False RecvMarker snap assms
[PROOF STATE]
proof (prove)
using this:
i \<noteq> i'
ev = RecvMarker i' r s
ps c r \<noteq> None
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs c i = msgs c' i
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
msgs c i = msgs c' i
goal (1 subgoal):
1. \<lbrakk>ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
msgs d' i = msgs c' i
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
msgs d' i = msgs c' i
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
using snap
[PROOF STATE]
proof (prove)
using this:
msgs d' i = msgs c' i
ps c r \<noteq> None
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal (1 subgoal):
1. \<lbrakk>ev = RecvMarker i' r s; \<not> ps c r \<noteq> None\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>ev = RecvMarker i' r s; \<not> ps c r \<noteq> None\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case no_snap: False
[PROOF STATE]
proof (state)
this:
\<not> ps c r \<noteq> None
goal (1 subgoal):
1. \<lbrakk>ev = RecvMarker i' r s; \<not> ps c r \<noteq> None\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<not> ps c r \<noteq> None
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<not> ps c r \<noteq> None
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
proof (cases "i = i'")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>\<not> ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>\<not> ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
i = i'
goal (2 subgoals):
1. \<lbrakk>\<not> ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>\<not> ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
i = i'
[PROOF STEP]
have "Marker # msgs c' i = msgs c i"
[PROOF STATE]
proof (prove)
using this:
i = i'
goal (1 subgoal):
1. Marker # msgs c' i = msgs c i
[PROOF STEP]
using chan RecvMarker assms
[PROOF STATE]
proof (prove)
using this:
i = i'
channel i = Some (p, q)
ev = RecvMarker i' r s
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. Marker # msgs c' i = msgs c i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
Marker # msgs c' i = msgs c i
goal (2 subgoals):
1. \<lbrakk>\<not> ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>\<not> ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
Marker # msgs c' i = msgs c i
goal (2 subgoals):
1. \<lbrakk>\<not> ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>\<not> ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
have "Marker # msgs d' i = msgs d i"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Marker # msgs d' i = msgs d i
[PROOF STEP]
using chan RecvMarker assms True
[PROOF STATE]
proof (prove)
using this:
channel i = Some (p, q)
ev = RecvMarker i' r s
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
i = i'
goal (1 subgoal):
1. Marker # msgs d' i = msgs d i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
Marker # msgs d' i = msgs d i
goal (2 subgoals):
1. \<lbrakk>\<not> ps c r \<noteq> None; i = i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>\<not> ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
Marker # msgs c' i = msgs c i
Marker # msgs d' i = msgs d i
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
Marker # msgs c' i = msgs c i
Marker # msgs d' i = msgs d i
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
Marker # msgs c' i = msgs c i
Marker # msgs d' i = msgs d i
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
by (metis list.inject)
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal (1 subgoal):
1. \<lbrakk>\<not> ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>\<not> ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case not_i: False
[PROOF STATE]
proof (state)
this:
i \<noteq> i'
goal (1 subgoal):
1. \<lbrakk>\<not> ps c r \<noteq> None; i \<noteq> i'\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
i \<noteq> i'
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
i \<noteq> i'
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
proof (cases "r = p")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>i \<noteq> i'; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
r = p
goal (2 subgoals):
1. \<lbrakk>i \<noteq> i'; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
r = p
[PROOF STEP]
have "msgs c' i = msgs c i @ [Marker]"
[PROOF STATE]
proof (prove)
using this:
r = p
goal (1 subgoal):
1. msgs c' i = msgs c i @ [Marker]
[PROOF STEP]
using no_snap RecvMarker assms True chan not_i
[PROOF STATE]
proof (prove)
using this:
r = p
\<not> ps c r \<noteq> None
ev = RecvMarker i' r s
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
r = p
channel i = Some (p, q)
i \<noteq> i'
goal (1 subgoal):
1. msgs c' i = msgs c i @ [Marker]
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs c i @ [Marker]
goal (2 subgoals):
1. \<lbrakk>i \<noteq> i'; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs c i @ [Marker]
goal (2 subgoals):
1. \<lbrakk>i \<noteq> i'; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
have "msgs d' i = msgs d i @ [Marker]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. msgs d' i = msgs d i @ [Marker]
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. msgs d' i = msgs d i @ [Marker]
[PROOF STEP]
have "~ has_snapshotted d r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<not> ps d r \<noteq> None
[PROOF STEP]
using assms no_snap True
[PROOF STATE]
proof (prove)
using this:
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
\<not> ps c r \<noteq> None
r = p
goal (1 subgoal):
1. \<not> ps d r \<noteq> None
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<not> ps d r \<noteq> None
goal (1 subgoal):
1. msgs d' i = msgs d i @ [Marker]
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<not> ps d r \<noteq> None
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<not> ps d r \<noteq> None
goal (1 subgoal):
1. msgs d' i = msgs d i @ [Marker]
[PROOF STEP]
using no_snap RecvMarker assms True chan not_i
[PROOF STATE]
proof (prove)
using this:
\<not> ps d r \<noteq> None
\<not> ps c r \<noteq> None
ev = RecvMarker i' r s
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
r = p
channel i = Some (p, q)
i \<noteq> i'
goal (1 subgoal):
1. msgs d' i = msgs d i @ [Marker]
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
msgs d' i = msgs d i @ [Marker]
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
msgs d' i = msgs d i @ [Marker]
goal (2 subgoals):
1. \<lbrakk>i \<noteq> i'; r = p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
2. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
msgs c' i = msgs c i @ [Marker]
msgs d' i = msgs d i @ [Marker]
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
msgs c' i = msgs c i @ [Marker]
msgs d' i = msgs d i @ [Marker]
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
msgs c' i = msgs c i @ [Marker]
msgs d' i = msgs d i @ [Marker]
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal (1 subgoal):
1. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
r \<noteq> p
goal (1 subgoal):
1. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
r \<noteq> p
[PROOF STEP]
have "msgs c i = msgs c' i"
[PROOF STATE]
proof (prove)
using this:
r \<noteq> p
goal (1 subgoal):
1. msgs c i = msgs c' i
[PROOF STEP]
using False RecvMarker no_snap chan assms not_i
[PROOF STATE]
proof (prove)
using this:
r \<noteq> p
r \<noteq> p
ev = RecvMarker i' r s
\<not> ps c r \<noteq> None
channel i = Some (p, q)
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
i \<noteq> i'
goal (1 subgoal):
1. msgs c i = msgs c' i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs c i = msgs c' i
goal (1 subgoal):
1. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
msgs c i = msgs c' i
goal (1 subgoal):
1. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
have "msgs d' i = msgs d i"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. msgs d' i = msgs d i
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. msgs d' i = msgs d i
[PROOF STEP]
have "~ has_snapshotted d r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<not> ps d r \<noteq> None
[PROOF STEP]
using assms no_snap False
[PROOF STATE]
proof (prove)
using this:
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
\<not> ps c r \<noteq> None
r \<noteq> p
goal (1 subgoal):
1. \<not> ps d r \<noteq> None
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<not> ps d r \<noteq> None
goal (1 subgoal):
1. msgs d' i = msgs d i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<not> ps d r \<noteq> None
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<not> ps d r \<noteq> None
goal (1 subgoal):
1. msgs d' i = msgs d i
[PROOF STEP]
using False RecvMarker no_snap chan assms not_i
[PROOF STATE]
proof (prove)
using this:
\<not> ps d r \<noteq> None
r \<noteq> p
ev = RecvMarker i' r s
\<not> ps c r \<noteq> None
channel i = Some (p, q)
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
i \<noteq> i'
goal (1 subgoal):
1. msgs d' i = msgs d i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs d' i = msgs d i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
msgs d' i = msgs d i
goal (1 subgoal):
1. \<lbrakk>i \<noteq> i'; r \<noteq> p\<rbrakk> \<Longrightarrow> msgs c' i = msgs d' i
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
msgs c i = msgs c' i
msgs d' i = msgs d i
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
msgs c i = msgs c' i
msgs d' i = msgs d i
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
msgs c i = msgs c' i
msgs d' i = msgs d i
\<forall>p. (ps c p \<noteq> None) = (ps d p \<noteq> None)
msgs c i = msgs d i
c \<turnstile> ev \<mapsto> c'
d \<turnstile> ev \<mapsto> d'
\<not> regular_event ev
goal (1 subgoal):
1. msgs c' i = msgs d' i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
msgs c' i = msgs d' i
goal:
No subgoals!
[PROOF STEP]
qed |
\subsection{System Characterisation}
\label{sec:theory:characterisation}
A systems complete dynamic behaviour around an operating point of interest can
be determined by applying a step function -- $\epsilon(t)$ -- to its input and
recording the system's output. The derivative of the resulting function is the
system's \textit{impulse response} and can be used to calculate optimal
controller parameters.
Before measuring the step response we first have to select the step amplitude.
If the step amplitude is too small, the plant behaves in an atypical way. This
happens because of small disturbances which affect the step response. A good
example for this is static friction. On the other hand if the step amplitude
is too large, then non-linear effects will throw off the accuracy (and
validity) of the result.
After a system's step response has been measured, it is necessary to
characterise and determine its properties before it's possible to fit a
transfer function to it. The method of characterisation used here is to find
the point of inflection in the measured step response, through which a tangent
is placed. The tangent's intersection points with the lower and upper
horizontal bounds are used to determine the dead time $T_u$ and the rise time
$T_g$. Further, the amplitude $K_s$ of the step response can be determined.
This process is illustrated in figure \ref{fig:tu-tg-example}.
\begin{figure}[t]
\centering
\includegraphics[width=\imagewidth]{images/tu_tg_example}
\caption{Example step response of a system and measurement of the angle of inflection for determining $K_s$, $T_u$ and $T_g$. Image taken from Wikipedia\cite{ref:tu-tg}.}
\label{fig:tu-tg-example}
\end{figure}
It is important to note that this method of characterisation is valid for
systems with an order of at least $n=2$ and for systems that don't exhibit any
overshoot.
|
(** Coq coding by choukh, Oct 2021 **)
Require Import BBST.Axiom.Meta.
Require Import BBST.Axiom.Extensionality.
Require Import BBST.Axiom.Separation.
Require Import BBST.Axiom.Pairing.
Require Import BBST.Axiom.Union.
Require Import BBST.Definition.RussellSet.
Require Import BBST.Definition.Singleton.
Require Import BBST.Definition.BinaryUnion.
Lemma 配对与顺序无关 : ∀ a b, {a, b} = {b, a}.
Proof.
intros. 外延.
- apply 配对除去 in H as [].
+ rewrite H. auto.
+ rewrite H. auto.
- apply 配对除去 in H as [].
+ rewrite H. auto.
+ rewrite H. auto.
Qed.
Lemma 配对与顺序无关' : ∀ a b, {a, b} = {b, a}.
Proof.
intros. 外延.
- apply 配对除去 in H as []; rewrite H; auto.
- apply 配对除去 in H as []; rewrite H; auto.
Qed.
Lemma 配对相等 : ∀ a b c d,
{a, b} = {c, d} ↔ a = c ∧ b = d ∨ a = d ∧ b = c.
Proof.
split; intros.
- assert (Ha: a ∈ {c, d}). rewrite <- H. auto.
assert (Hb: b ∈ {c, d}). rewrite <- H. auto.
apply 配对除去 in Ha as [].
+ left. split.
* auto.
* apply 配对除去 in Hb as [].
-- subst. now apply 单集配对相等 in H as [].
-- auto.
+ right. split.
* auto.
* apply 配对除去 in Hb as [].
-- auto.
-- subst. now apply 单集配对相等 in H as [].
- destruct H as [[]|[]].
+ subst. auto.
+ subst. apply 配对与顺序无关.
Qed.
(* 练习3 *)
Fact 不存在所有单集的集合: ¬ ∃ A, ∀ a, {a,} ∈ A.
Proof.
Admitted.
|
module Hasql.Private.Prelude
(
module Exports,
LazyByteString,
ByteStringBuilder,
LazyText,
TextBuilder,
forMToZero_,
forMFromZero_,
strictCons,
mapLeft,
)
where
-- base
-------------------------
import Control.Applicative as Exports hiding (WrappedArrow(..))
import Control.Arrow as Exports hiding (first, second)
import Control.Category as Exports
import Control.Concurrent as Exports
import Control.Exception as Exports
import Control.Monad as Exports hiding (fail, mapM_, sequence_, forM_, msum, mapM, sequence, forM)
import Control.Monad.IO.Class as Exports
import Control.Monad.Fail as Exports
import Control.Monad.Fix as Exports hiding (fix)
import Control.Monad.ST as Exports
import Data.Bifunctor as Exports
import Data.Bits as Exports
import Data.Bool as Exports
import Data.Char as Exports
import Data.Coerce as Exports
import Data.Complex as Exports
import Data.Data as Exports
import Data.Dynamic as Exports
import Data.Either as Exports
import Data.Fixed as Exports
import Data.Foldable as Exports hiding (toList)
import Data.Function as Exports hiding (id, (.))
import Data.Functor as Exports
import Data.Functor.Compose as Exports
import Data.Functor.Contravariant as Exports
import Data.Int as Exports
import Data.IORef as Exports
import Data.Ix as Exports
import Data.List as Exports hiding (sortOn, isSubsequenceOf, uncons, concat, foldr, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, find, maximumBy, minimumBy, mapAccumL, mapAccumR, foldl')
import Data.List.NonEmpty as Exports (NonEmpty(..))
import Data.Maybe as Exports
import Data.Monoid as Exports hiding (Alt, (<>))
import Data.Ord as Exports
import Data.Proxy as Exports
import Data.Ratio as Exports
import Data.Semigroup as Exports hiding (First(..), Last(..))
import Data.STRef as Exports
import Data.String as Exports
import Data.Traversable as Exports
import Data.Tuple as Exports
import Data.Unique as Exports
import Data.Version as Exports
import Data.Void as Exports
import Data.Word as Exports
import Debug.Trace as Exports
import Foreign.ForeignPtr as Exports
import Foreign.Ptr as Exports
import Foreign.StablePtr as Exports
import Foreign.Storable as Exports
import GHC.Conc as Exports hiding (orElse, withMVar, threadWaitWriteSTM, threadWaitWrite, threadWaitReadSTM, threadWaitRead)
import GHC.Exts as Exports (IsList(..), lazy, inline, sortWith, groupWith)
import GHC.Generics as Exports (Generic)
import GHC.IO.Exception as Exports
import GHC.OverloadedLabels as Exports
import Numeric as Exports
import Prelude as Exports hiding (Read, fail, concat, foldr, mapM_, sequence_, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, mapM, sequence, id, (.))
import System.Environment as Exports
import System.Exit as Exports
import System.IO as Exports (Handle, hClose)
import System.IO.Error as Exports
import System.IO.Unsafe as Exports
import System.Mem as Exports
import System.Mem.StableName as Exports
import System.Timeout as Exports
import Text.ParserCombinators.ReadP as Exports (ReadP, readP_to_S, readS_to_P)
import Text.ParserCombinators.ReadPrec as Exports (ReadPrec, readPrec_to_P, readP_to_Prec, readPrec_to_S, readS_to_Prec)
import Text.Printf as Exports (printf, hPrintf)
import Unsafe.Coerce as Exports
-- transformers
-------------------------
import Control.Monad.IO.Class as Exports
import Control.Monad.Trans.Class as Exports
import Control.Monad.Trans.Cont as Exports hiding (shift, callCC)
import Control.Monad.Trans.Except as Exports (ExceptT(ExceptT), Except, except, runExcept, runExceptT, mapExcept, mapExceptT, withExcept, withExceptT, throwE, catchE)
import Control.Monad.Trans.Maybe as Exports
import Control.Monad.Trans.Reader as Exports (Reader, ask, runReader, mapReader, withReader, ReaderT(ReaderT), runReaderT, mapReaderT, withReaderT)
import Control.Monad.Trans.State.Strict as Exports (State, runState, evalState, execState, mapState, withState, StateT(StateT), runStateT, evalStateT, execStateT, mapStateT, withStateT)
import Control.Monad.Trans.Writer.Strict as Exports (Writer, runWriter, execWriter, mapWriter, WriterT(..), execWriterT, mapWriterT)
import Data.Functor.Compose as Exports
import Data.Functor.Identity as Exports
-- mtl
-------------------------
import Control.Monad.Error.Class as Exports (MonadError (..))
-- profunctors
-------------------------
import Data.Profunctor.Unsafe as Exports
-- contravariant
-------------------------
import Data.Functor.Contravariant.Divisible as Exports
-- hashable
-------------------------
import Data.Hashable as Exports (Hashable(..))
-- text
-------------------------
import Data.Text as Exports (Text)
-- bytestring
-------------------------
import Data.ByteString as Exports (ByteString)
-- vector
-------------------------
import Data.Vector as Exports (Vector)
-- dlist
-------------------------
import Data.DList as Exports (DList)
-- postgresql-binary
-------------------------
import PostgreSQL.Binary.Data as Exports (UUID)
-- custom
-------------------------
import qualified Data.Text.Lazy
import qualified Data.Text.Lazy.Builder
import qualified Data.ByteString.Lazy
import qualified Data.ByteString.Builder
type LazyByteString =
Data.ByteString.Lazy.ByteString
type ByteStringBuilder =
Data.ByteString.Builder.Builder
type LazyText =
Data.Text.Lazy.Text
type TextBuilder =
Data.Text.Lazy.Builder.Builder
{-# INLINE forMToZero_ #-}
forMToZero_ :: Applicative m => Int -> (Int -> m a) -> m ()
forMToZero_ !startN f =
($ pred startN) $ fix $ \loop !n -> if n >= 0 then f n *> loop (pred n) else pure ()
{-# INLINE forMFromZero_ #-}
forMFromZero_ :: Applicative m => Int -> (Int -> m a) -> m ()
forMFromZero_ !endN f =
($ 0) $ fix $ \loop !n -> if n < endN then f n *> loop (succ n) else pure ()
{-# INLINE strictCons #-}
strictCons :: a -> [a] -> [a]
strictCons !a b =
let !c = a : b in c
{-# INLINE mapLeft #-}
mapLeft :: (a -> c) -> Either a b -> Either c b
mapLeft f =
either (Left . f) Right
|
/*
ODE: a program to get optime Runge-Kutta and multi-steps methods.
Copyright 2011-2019, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``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 Javier Burguete Tolosa 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.
*/
/**
* \file rk_5_4.c
* \brief Source file to optimize Runge-Kutta 5 steps 4th order methods.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2011-2019.
*/
#define _GNU_SOURCE
#include <string.h>
#include <math.h>
#include <libxml/parser.h>
#include <glib.h>
#include <libintl.h>
#include <gsl/gsl_rng.h>
#include "config.h"
#include "utils.h"
#include "optimize.h"
#include "rk.h"
#include "rk_5_4.h"
#define DEBUG_RK_5_4 0 ///< macro to debug.
/**
* Function to obtain the coefficients of a 5 steps 4th order Runge-Kutta
* method.
*/
int
rk_tb_5_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *tb, *r;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t5 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
b21 (tb) = r[2];
t3 (tb) = r[3];
b31 (tb) = r[4];
b32 (tb) = r[5];
t4 (tb) = r[6];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = t4 (tb);
E[0] = 0.5L;
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = D[0] * t4 (tb);
E[1] = 1.L / 3.L;
A[2] = A[1] * t1 (tb);
B[2] = B[1] * t2 (tb);
C[2] = C[1] * t3 (tb);
D[2] = D[1] * t4 (tb);
E[2] = 0.25L;
A[3] = D[3] = 0.L;
B[3] = b21 (tb) * t1 (tb) * (t2 (tb) - t4 (tb));
C[3] = (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb)) * (t3 (tb) - t4 (tb));
E[3] = 0.125L - 1.L / 6.L * t4 (tb);
solve_4 (A, B, C, D, E);
if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))
return 0;
b54 (tb) = E[3];
b53 (tb) = E[2];
b52 (tb) = E[1];
b51 (tb) = E[0];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = 1.L / 6.L - b52 (tb) * b21 (tb) * t1 (tb)
- b53 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = 1.L / 12.L - b52 (tb) * b21 (tb) * sqr (t1 (tb))
- b53 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = 1.L / 24.L - b53 (tb) * b32 (tb) * b21 (tb) * t1 (tb);
solve_3 (A, B, C, D);
b43 (tb) = D[2] / b54 (tb);
if (isnan (b43 (tb)))
return 0;
b42 (tb) = D[1] / b54 (tb);
if (isnan (b42 (tb)))
return 0;
b41 (tb) = D[0] / b54 (tb);
if (isnan (b41 (tb)))
return 0;
rk_b_5 (tb);
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 5 steps 4th order, 5th order in
* equations depending only on time, Runge-Kutta method.
*/
int
rk_tb_5_4t (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *tb, *r;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4t: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t5 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
t3 (tb) = r[2];
t4 (tb) = r[3];
b31 (tb) = r[4];
b21 (tb) = r[5];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = t4 (tb);
E[0] = 0.5L;
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = D[0] * t4 (tb);
E[1] = 1.L / 3.L;
A[2] = A[1] * t1 (tb);
B[2] = B[1] * t2 (tb);
C[2] = C[1] * t3 (tb);
D[2] = D[1] * t4 (tb);
E[2] = 0.25L;
A[3] = A[2] * t1 (tb);
B[3] = B[2] * t2 (tb);
C[3] = C[2] * t3 (tb);
D[3] = D[2] * t4 (tb);
E[3] = 0.2L;
solve_4 (A, B, C, D, E);
if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))
return 0;
b54 (tb) = E[3];
b53 (tb) = E[2];
b52 (tb) = E[1];
b51 (tb) = E[0];
b32 (tb) = (1.L / 6.L * t4 (tb) - 0.125L
- t1 (tb) * (b52 (tb) * b21 (tb) * (t4 (tb) - t2 (tb))
+ b53 (tb) * b31 (tb) * (t4 (tb) - t3 (tb))))
/ (b53 (tb) * t2 (tb) * (t4 (tb) - t3 (tb)));
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = 1.L / 6.L - b52 (tb) * b21 (tb) * t1 (tb)
- b53 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = 1.L / 12.L - b52 (tb) * b21 (tb) * sqr (t1 (tb))
- b53 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = 1.L / 24.L - b53 (tb) * b32 (tb) * b21 (tb) * t1 (tb);
solve_3 (A, B, C, D);
b43 (tb) = D[2] / b54 (tb);
if (isnan (b43 (tb)))
return 0;
b42 (tb) = D[1] / b54 (tb);
if (isnan (b42 (tb)))
return 0;
b41 (tb) = D[0] / b54 (tb);
if (isnan (b41 (tb)))
return 0;
rk_b_5 (tb);
#if DEBUG_RK_5_4
rk_print_tb (optimize, "rk_tb_5_4t", stderr);
fprintf (stderr, "rk_tb_5_4t: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 5 steps 3rd-4th order Runge-Kutta
* pair.
*/
int
rk_tb_5_4p (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *tb;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4p: start\n");
#endif
if (!rk_tb_5_4 (optimize))
return 0;
tb = optimize->coefficient;
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = 0.5L;
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = 1.L / 3.L;
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = 1.L / 6.L;
solve_3 (A, B, C, D);
if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))
return 0;
e53 (tb) = D[2];
e52 (tb) = D[1];
e51 (tb) = D[0];
rk_e_5 (tb);
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4p: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 5 steps 3th-4th order, 4th-5th order
* in equations depending only on time, Runge-Kutta pair.
*/
int
rk_tb_5_4tp (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *tb, *r;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4tp: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t5 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
t3 (tb) = r[2];
t4 (tb) = r[3];
b31 (tb) = r[4];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = t4 (tb);
E[0] = 0.5L;
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = D[0] * t4 (tb);
E[1] = 1.L / 3.L;
A[2] = A[1] * t1 (tb);
B[2] = B[1] * t2 (tb);
C[2] = C[1] * t3 (tb);
D[2] = D[1] * t4 (tb);
E[2] = 0.25L;
A[3] = A[2] * t1 (tb);
B[3] = B[2] * t2 (tb);
C[3] = C[2] * t3 (tb);
D[3] = D[2] * t4 (tb);
E[3] = 0.2L;
solve_4 (A, B, C, D, E);
if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))
return 0;
b54 (tb) = E[3];
b53 (tb) = E[2];
b52 (tb) = E[1];
b51 (tb) = E[0];
e53 (tb) = (0.25L - 1.L / 3.L * t1 (tb)
- (1.L / 3.L - 0.5L * t1 (tb)) * t2 (tb))
/ (t3 (tb) * (t3 (tb) - t2 (tb)) * (t3 (tb) - t1 (tb)));
if (isnan (e53 (tb)))
return 0;
e52 (tb) = (1.L / 3.L - 0.5L * t1 (tb)
- t3 (tb) * (t3 (tb) - t1 (tb)) * e53 (tb))
/ (t2 (tb) * (t2 (tb) - t1 (tb)));
if (isnan (e52 (tb)))
return 0;
e51 (tb) = (0.5L - t2 (tb) * e52 (tb) - t3 (tb) * e53 (tb)) / t1 (tb);
if (isnan (e51 (tb)))
return 0;
b21 (tb) = (1.L / 6.L * b53 (tb) * (t4 (tb) - t3 (tb))
+ e53 (tb) * (0.125L - 1.L / 6.L * t4 (tb)))
/ (t1 (tb) * (e52 (tb) * b53 (tb) * (t4 (tb) - t3 (tb))
- e53 (tb) * b52 (tb) * (t4 (tb) - t2 (tb))));
if (isnan (b21 (tb)))
return 0;
b32 (tb) = (1.L / 6.L * t4 (tb) - 0.125L
- t1 (tb) * (b52 (tb) * b21 (tb) * (t4 (tb) - t2 (tb))
+ b53 (tb) * b31 (tb) * (t4 (tb) - t3 (tb))))
/ (b53 (tb) * t2 (tb) * (t4 (tb) - t3 (tb)));
if (isnan (b32 (tb)))
return 0;
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = 1.L / 6.L - b52 (tb) * b21 (tb) * t1 (tb)
- b53 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = 1.L / 12.L - b52 (tb) * b21 (tb) * sqr (t1 (tb))
- b53 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = 1.L / 24.L - b53 (tb) * b32 (tb) * b21 (tb) * t1 (tb);
solve_3 (A, B, C, D);
b43 (tb) = D[2] / b54 (tb);
if (isnan (b43 (tb)))
return 0;
b42 (tb) = D[1] / b54 (tb);
if (isnan (b42 (tb)))
return 0;
b41 (tb) = D[0] / b54 (tb);
if (isnan (b41 (tb)))
return 0;
rk_b_5 (tb);
rk_e_5 (tb);
#if DEBUG_RK_5_4
rk_print_tb (optimize, "rk_tb_5_4tp", stderr);
fprintf (stderr, "rk_tb_5_4tp: end\n");
#endif
return 1;
}
/**
* Function to calculate the objective function of a 5 steps 4th order
* Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_5_4 (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b54 (tb) < 0.L)
o += b54 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_5_4: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 5 steps 4th order, 5th
* order in equations depending only on time, Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_5_4t (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4t: start\n");
#endif
tb = rk->tb->coefficient;
#if DEBUG_RK_5_4
rk_print_tb (optimize, "rk_objective_tb_5_4t", stderr);
#endif
o = fminl (0.L, b20 (tb));
if (b21 (tb) < 0.L)
o += b21 (tb);
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b32 (tb) < 0.L)
o += b32 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b54 (tb) < 0.L)
o += b54 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4t: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_5_4t: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 5 steps 3rd-4th order
* Runge-Kutta pair.
*
* \return objective function value.
*/
long double
rk_objective_tb_5_4p (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4p: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b54 (tb) < 0.L)
o += b54 (tb);
if (e50 (tb) < 0.L)
o += e50 (tb);
if (e51 (tb) < 0.L)
o += e51 (tb);
if (e52 (tb) < 0.L)
o += e52 (tb);
if (e53 (tb) < 0.L)
o += e53 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4p: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_5_4p: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 5 steps 3th-4th order,
* 4th-5th order in equations depending only on time, Runge-Kutta pair.
*
* \return objective function value.
*/
long double
rk_objective_tb_5_4tp (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4t: start\n");
#endif
tb = rk->tb->coefficient;
#if DEBUG_RK_5_4
rk_print_tb (optimize, "rk_objective_tb_5_4tp", stderr);
#endif
o = fminl (0.L, b20 (tb));
if (b21 (tb) < 0.L)
o += b21 (tb);
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b32 (tb) < 0.L)
o += b32 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b54 (tb) < 0.L)
o += b54 (tb);
if (e50 (tb) < 0.L)
o += e50 (tb);
if (e51 (tb) < 0.L)
o += e51 (tb);
if (e52 (tb) < 0.L)
o += e52 (tb);
if (e53 (tb) < 0.L)
o += e53 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4tp: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_5_4tp: end\n");
#endif
return o;
}
|
(c) Juan Gomez 2019. Thanks to Universidad EAFIT for support. This material is part of the course Introduction to Finite Element Analysis
# Convergence of analysis results
## Introduction
In this section we address the problem of convergency of analysis results. We will approach the problem in a loose way proceeding from an engineering point of view. For a thorough discussion the reader is referred to textbooks of numerical analysis, see for instance Systèmes, D. (2012). Particularly we will review the fundamental aspects that must be satisfied by a finite element solution. In the first part we address the problem from the element point of view, while in the final part we study the convergence of particular problem in terms of several self-contained meshes.**After completing this notebook you should be able to:**
* Recognize the total potential energy of a model like the fundamental descriptor of the response.
* Perform a convergency analysis for a given finite element model.
## Definition of convergence
Let $\Pi$ be the total potential energy of a solid in equilibrium and under a elastic stress state. The value of $\Pi$ for a given finite element mesh is given by:
$$
{\Pi _{FE}} = - \frac{1}{2}{U^T}KU
$$
where $K$ and $U$ are the global stiffness matrix and global nodal displacements vector. If $q$ represents the number of finite elements in a given discretization then we define convergency as the condition that:
$$
\mathop {\lim }\limits_{q \to \infty } {\Pi_{FE}} \to \Pi
$$
To measure the state of stress associated to a given mesh we need to define a norm. Consider the square energy norm of the error $\left\| {{{\vec e}_h}} \right\|_E^2$. This measure satisfies
$$\left\| {{{\vec e}_h}} \right\|_E^2 > 0$$
and will be used as an error estimate of the accuraccy of the finite element solution. Particularly we will use the following relationship (see Systèmes, D. 2012).
$$
\left\| {{{\vec e}_h}} \right\| \le \alpha {h^k}
$$
from which we can write:
$$
\log \left\| {{{\vec e}_h}} \right\| \approx \log \alpha + k\log h
$$
In the expression above $k$ is the order of the complete interpolation polynomial present in the mesh and gives a measure of the order of convergence in the finite element solution, while the rate of convergency is given by $\alpha$.
## How to conduct the convergence analysis?
In order to conduct the convergency study we perform a series of finite element analysis. For each mesh we compute $\left\| {\vec u - {{\vec u}_h}} \right\|$ which is equivalent to $\vec e_h$ and where $\vec u$ is the exact solution. In order to find the exact solution we assume that the most refined results have functionals corresponding to ${\Pi _{n - 2}}$, ${\Pi _{n - 1}}$ and ${\Pi _{n}}$ from which:
$$
{\Pi _{Exa}} = \frac{{\Pi _{n - 1}^2 - {\Pi _n}{\Pi _{n - 2}}}}{{(2{\Pi _{n - 1}} - {\Pi _n} - {\Pi _{n - 2}})}}
$$
The procedure is summarized below:
* Solve a series of meshes with solutions given by $\vec u_1, \vec u_2,...,\vec u_n$. Each mesh has a characteristic element size $h$. Here the subscript represents a given discretization.
* For each mesh find the total potential energy:
$${\Pi_h} = - \frac{1}{2}{U^T}KU$$
* Using the most refined meshes compute the potential energy for the exact solution $\Pi _{Exa}$.
* For each mesh compute:
$$
\frac{{\left\| {{{\vec u}_{Exa}} - {{\vec u}_h}} \right\|}}{{\left\| {{{\vec u}_{Exa}}} \right\|}} \equiv {\left[ {\frac{{{\Pi _{Exa}} - {\Pi _h}}}{{{\Pi _{Exa}}}}} \right]^{1/2}}
$$
and keep track of the results.
* Plot the values of $\log \left( {\frac{{\left\| {{{\vec u}_{Exa}} - {{\vec u}_h}} \right\|}}{{\left\| {{{\vec u}_{Exa}}} \right\|}}} \right)$ vs $\log h$ and determine the slope which upon convergence must be close to the order of the complete polynomial used in the discretization.
### Example: Tappered bar in compression
The figure below shows a tappered bar under a compressive uniformly distributed load of total magnitude $P=0.5$. The bar is of length $l=10$ and its large and short ends given by $h_1 = 2.0$ and $h_2 =0.5$ respectively. The material properties correspond to a Poisson's ratio and Young modulos $\nu=0.30$ and $E=1.0$ respectively. We want to find the converged solution for the bar after using 3-noded triangular elements.
<center></center>
Analyses were conduted with 4 consecutive meshes with decreasing element size given by $h=[1.0, 0.5, 0.25, 0.125]$.
<center></center>
Now assuming we have consecutive meshes each one obtained after halving the elements in the previous mesh we have the following approximation for the exact total potential energy of the system, computed the last most refined meshes:
$${\Pi _{Exa}} = \frac{{{{1.161}^2} - ( - 1.160)( - 1.155)}}{{ - 2(1.161) - ( - 1.160) - ( - 1.155)}} = -1.160.$$
To compute the energy norm of the error we use:
$$\frac{{\left\| {{{\vec u}_{Exa}} - {{\vec u}_{FE}}} \right\|}}{{\left\| {{{\vec u}_{Exa}}} \right\|}} = {\left[ {\frac{{{\Pi _{Exa}} - {\prod _{FE}}}}{{{\Pi _{Exa}}}}} \right]^{1/2}}.$$
To measure convergence we plot:
$$\log \left( {\left\| {{{\vec u}_{Exa}} - {{\vec u}_{FE}}} \right\|} \right) = \log c + k\log h$$
<center></center>
### Computation of potential energy
The files **Tnodes.txt**, **Teles.txt** , **Tmater.txt** and **Tloads.txt** contained in the **files** folder correspond to the finite element mesh for one of the **tappred bar** model. To compute the potential energy
$${\Pi_h} = - \frac{1}{2}{U^T}KU$$
for the discretization the model is solved first using the dense assembly option.
```python
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import sympy as sym
import solidspy.assemutil as ass
import solidspy.postprocesor as pos
import solidspy.solutil as sol
```
```python
def readin():
nodes = np.loadtxt('files/' + 'Tnodes.txt', ndmin=2)
mats = np.loadtxt('files/' + 'Tmater.txt', ndmin=2)
elements = np.loadtxt('files/' + 'Teles.txt', ndmin=2, dtype=np.int)
loads = np.loadtxt('files/' + 'Tloads.txt', ndmin=2)
return nodes, mats, elements, loads
nodes, mats, elements, loads = readin()
```
```python
DME , IBC , neq = ass.DME(nodes, elements)
KG = ass.assembler(elements, mats, nodes, neq, DME, sparse=False)
RHSG = ass.loadasem(loads, IBC, neq)
UG = sol.static_sol(KG, RHSG)
UC = pos.complete_disp(IBC, nodes, UG)
Energy = np.dot(np.dot(UG.T , KG) , UG)
print(Energy)
```
0.5785646424764832
### Glossary of terms
**Converged solution:** A finite element solution associated to a specific discretization and numerically considered as close enough to the exact solution.
**Norm:** Specific mathematical form of measuring the magnitude of a vector in a given basis.
**Convergency analysis:** A series of finite element analysis of a given computational domain with increasingly refined meshes in order to determined an accepatble solution.
## Class activity.
Consider the cantilever beam shown below:
<center></center>
with analytic solution (Timoshenko and Goodier,1976) ) given by:
$$u = - \frac{P}{{2EI}}{x^2}y - \frac{{\nu P}}{{6EI}}{y^3} + \frac{P}{{2IG}}{y^3} + \left( {\frac{{P{l^2}}}{{2EI}} - \frac{{P{c^2}}}{{2IG}}} \right)y$$
$$v = \frac{{\nu P}}{{2EI}}x{y^2} + \frac{P}{{6EI}}{x^3} - \frac{{P{l^2}}}{{2EI}}x + \frac{{P{l^3}}}{{3EI}}$$
$${\varepsilon _{xx}} = \frac{{\partial u}}{{\partial x}} \equiv - \frac{P}{{EI}}xy$$
$${\varepsilon _{yy}} = \frac{{\partial v}}{{\partial y}} \equiv \frac{{\nu P}}{{EI}}xy$$
$${\gamma _{xy}} = \frac{{\partial u}}{{\partial y}} + \frac{{\partial v}}{{\partial x}} \equiv \frac{P}{{2IG}}\left( {{y^2} - {c^2}} \right).$$
The values of the material parameters are $E=1000.0$ and $\nu=0.30$ while the beam dimensions are $l=24$ and $2c=8$ and the applied load is $P=50$ (upwards).
Perform a finite element simulation using a series of refined meshes with charateristic element size corresponding to $h=[6.0,3.0,1.5,0.75,0.375]$ and show that convergence is achieved. To conduct the finite element analysis fill out \cref{problem}
### References
* Bathe, Klaus-Jürgen. (2006) Finite element procedures. Klaus-Jurgen Bathe. Prentice Hall International.
* Juan Gómez, Nicolás Guarín-Zapata (2018). SolidsPy: 2D-Finite Element Analysis with Python, <https://github.com/AppliedMechanics-EAFIT/SolidsPy>.
* Systèmes, D. (2012). ABAQUS 6.12 Theory manual. Dassault Systèmes Simulia Corp., Providence, Rhode Island.
* Timoshenko, S.P., and Goodier, J.N. (1976). Theory of Elasticity. International Student Edition. McGraw-Hill International.
```python
from IPython.core.display import HTML
def css_styling():
styles = open('./nb_style.css', 'r').read()
return HTML(styles)
css_styling()
```
<link href='http://fonts.googleapis.com/css?family=Fenix' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:300,400' rel='stylesheet' type='text/css'>
<style>
/*
Template for Notebooks for Modelación computacional.
Based on Lorena Barba template available at:
https://github.com/barbagroup/AeroPython/blob/master/styles/custom.css
*/
/* Fonts */
@font-face {
font-family: "Computer Modern";
src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');
}
/* Text */
div.cell{
width:800px;
margin-left:16% !important;
margin-right:auto;
}
h1 {
font-family: 'Alegreya Sans', sans-serif;
}
h2 {
font-family: 'Fenix', serif;
}
h3{
font-family: 'Fenix', serif;
margin-top:12px;
margin-bottom: 3px;
}
h4{
font-family: 'Fenix', serif;
}
h5 {
font-family: 'Alegreya Sans', sans-serif;
}
div.text_cell_render{
font-family: 'Alegreya Sans',Computer Modern, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
line-height: 135%;
font-size: 120%;
width:600px;
margin-left:auto;
margin-right:auto;
}
.CodeMirror{
font-family: "Source Code Pro";
font-size: 90%;
}
/* .prompt{
display: None;
}*/
.text_cell_render h1 {
font-weight: 200;
font-size: 50pt;
line-height: 100%;
color:#CD2305;
margin-bottom: 0.5em;
margin-top: 0.5em;
display: block;
}
.text_cell_render h5 {
font-weight: 300;
font-size: 16pt;
color: #CD2305;
font-style: italic;
margin-bottom: .5em;
margin-top: 0.5em;
display: block;
}
.warning{
color: rgb( 240, 20, 20 )
}
</style>
```python
```
|
/* $Id: map_context.hpp 48153 2011-01-01 15:57:50Z mordante $ */
/*
Copyright (C) 2008 - 2011 by Tomasz Sniatowski <[email protected]>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
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.
See the COPYING file for more details.
*/
#ifndef EDITOR_MAP_CONTEXT_HPP_INCLUDED
#define EDITOR_MAP_CONTEXT_HPP_INCLUDED
#include "editor_map.hpp"
#include <boost/utility.hpp>
namespace editor {
/**
* This class wraps around a map to provide a conscise interface for the editor to work with.
* The actual map object can change rapidly (be assigned to), the map context persists
* data (like the undo stacks) in this case. The functionality is here, not in editor_controller
* as e.g. the undo stack is part of the map, not the editor as a whole. This might allow many
* maps to be open at the same time.
*/
class map_context : private boost::noncopyable
{
public:
/**
* Create a map context from an existing map. The filename is set to be
* empty, indicating a new map.
* Marked "explicit" to avoid automatic conversions.
*/
explicit map_context(const editor_map& map);
/**
* Create map_context from a map file. If the map cannot be loaded, an
* exception will be thrown and the object will not be constructed. If the
* map file is a scenario, the map specified in its map_data key will be
* loaded, and the stored filename updated accordingly. Maps embedded
* inside scenarios do not change the filename, but set the "embedded" flag
* instead.
*/
map_context(const config& game_config, const std::string& filename);
/**
* Map context destructor
*/
~map_context();
/**
* Map accesor
*/
editor_map& get_map() { return map_; };
/**
* Map accesor - const version
*/
const editor_map& get_map() const { return map_; }
/**
* Draw a terrain on a single location on the map.
* Sets the refresh flags accordingly.
*/
void draw_terrain(t_translation::t_terrain terrain, const map_location& loc,
bool one_layer_only = false);
/**
* Actual drawing function used by both overloaded variants of draw_terrain.
*/
void draw_terrain_actual(t_translation::t_terrain terrain, const map_location& loc,
bool one_layer_only = false);
/**
* Draw a terrain on a set of locations on the map.
* Sets the refresh flags accordingly.
*/
void draw_terrain(t_translation::t_terrain terrain, const std::set<map_location>& locs,
bool one_layer_only = false);
/**
* Getter for the reload flag. Reload is the highest level of required refreshing,
* set when the map size has changed or the map was reassigned.
*/
bool needs_reload() const { return needs_reload_; }
/**
* Setter for the reload flag
*/
void set_needs_reload(bool value=true) { needs_reload_ = value; }
/**
* Getter for the terrain rebuild flag. Set whenever any terrain has changed.
*/
bool needs_terrain_rebuild() const { return needs_terrain_rebuild_; }
/**
* Setter for the terrain rebuild flag
*/
void set_needs_terrain_rebuild(bool value=true) { needs_terrain_rebuild_ = value; }
/**
* Getter fo the labels reset flag. Set when the labels need to be refreshed.
*/
bool needs_labels_reset() const { return needs_labels_reset_; }
/**
* Setter for the labels reset flag
*/
void set_needs_labels_reset(bool value=true) { needs_labels_reset_ = value; }
const std::set<map_location> changed_locations() const { return changed_locations_; }
void clear_changed_locations();
void add_changed_location(const map_location& loc);
void add_changed_location(const std::set<map_location>& locs);
void set_everything_changed();
bool everything_changed() const;
void clear_starting_position_labels(display& disp);
void set_starting_position_labels(display& disp);
void reset_starting_position_labels(display& disp);
const std::string& get_filename() const { return filename_; }
void set_filename(const std::string& fn) { filename_ = fn; }
const std::string& get_map_data_key() const { return map_data_key_; }
bool is_embedded() const { return embedded_; }
void set_embedded(bool v) { embedded_ = v; }
/**
* Saves the map under the current filename. Filename must be valid.
* May throw an exception on failure.
*/
bool save();
void set_map(const editor_map& map);
/**
* Performs an action (thus modyfying the map). An appropriate undo action is added to
* the undo stack. The redo stack is cleared. Note that this may throw, use caution
* when calling this with a dereferennced pointer that you own (i.e. use a smart pointer).
*/
void perform_action(const editor_action& action);
/**
* Performs a partial action, assumes that the top undo action has been modified to
* maintain coherent state of the undo stacks, and so a new undo action is not
* created.
*/
void perform_partial_action(const editor_action& action);
/** @return whether the map was modified since the last save */
bool modified() const;
/** Clear the modified state */
void clear_modified();
/** @return true when undo can be performed, false otherwise */
bool can_undo() const;
/** @return true when redo can be performed, false otherwise */
bool can_redo() const;
/** @return a pointer to the last undo action or NULL if the undo stack is empty */
editor_action* last_undo_action();
/** @return a pointer to the last redo action or NULL if the undo stack is empty */
editor_action* last_redo_action();
/** const version of last_undo_action */
const editor_action* last_undo_action() const;
/** const version of last_redo_action */
const editor_action* last_redo_action() const;
/** Un-does the last action, and puts it in the redo stack for a possible redo */
void undo();
/** Re-does a previousle undid action, and puts it back in the undo stack. */
void redo();
/**
* Un-does a single step from a undo action chain. The action is separated
* from the chain and it's undo (the redo) is added as a standalone action
* to the redo stack.
* Precodnition: the last undo action has to actually be an action chain.
*/
void partial_undo();
/**
* Clear the undo and redo stacks
*/
void clear_undo_redo();
protected:
/**
* The actual filename of this map. An empty string indicates a new map.
*/
std::string filename_;
/**
* When a scenario file is loaded, the referenced map is loaded instead.
* The verbatim form of the reference is kept here.
*/
std::string map_data_key_;
/**
* Whether the map context refers to a map embedded in a scenario file.
* This distinction is important in order to avoid overwriting the scenario.
*/
bool embedded_;
/**
* The map object of this map_context.
*/
editor_map map_;
/**
* Container type used to store actions in the undo and redo stacks
*/
typedef std::deque<editor_action*> action_stack;
/**
* Checks if an action stack reached its capacity and removes the front element if so.
*/
void trim_stack(action_stack& stack);
/**
* Clears an action stack and deletes all its contents. Helper function used when the undo
* or redo stack needs to be cleared
*/
void clear_stack(action_stack& stack);
/**
* Perform an action at the back of one stack, and then move it to the back of the other stack.
* This is the implementation of both undo and redo which only differ in the direction.
*/
void perform_action_between_stacks(action_stack& from, action_stack& to);
/**
* The undo stack. A double-ended queues due to the need to add items to one end,
* and remove from both when performing the undo or when trimming the size. This container owns
* all contents, i.e. no action in the stack shall be deleted, and unless otherwise noted the contents
* could be deleted at an time during normal operation of the stack. To work on an action, either
* remove it from the container or make a copy. Actions are inserted at the back of the container
* and disappear from the front when the capacity is exceeded.
* @todo Use boost's pointer-owning container?
*/
action_stack undo_stack_;
/**
* The redo stack. @see undo_stack_
*/
action_stack redo_stack_;
/**
* Action stack (i.e. undo and redo) maximum size
*/
static const size_t max_action_stack_size_;
/**
* Number of actions performed since the map was saved. Zero means the map was not modified.
*/
int actions_since_save_;
/**
* Cache of set starting position labels. Necessary for removing them.
*/
std::set<map_location> starting_position_label_locs_;
/**
* Refresh flag indicating the map in this context should be completely reloaded by the display
*/
bool needs_reload_;
/**
* Refresh flag indicating the terrain in the map has changed and requires a rebuild
*/
bool needs_terrain_rebuild_;
/**
* Refresh flag indicating the labels in the map have changed
*/
bool needs_labels_reset_;
std::set<map_location> changed_locations_;
bool everything_changed_;
};
} //end namespace editor
#endif
|
/-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.terminal
import category_theory.subobject.mono_over
/-!
# Subterminal objects
Subterminal objects are the objects which can be thought of as subobjects of the terminal object.
In fact, the definition can be constructed to not require a terminal object, by defining `A` to be
subterminal iff for any `Z`, there is at most one morphism `Z ⟶ A`.
An alternate definition is that the diagonal morphism `A ⟶ A ⨯ A` is an isomorphism.
In this file we define subterminal objects and show the equivalence of these three definitions.
We also construct the subcategory of subterminal objects.
## TODO
* Define exponential ideals, and show this subcategory is an exponential ideal.
* Use the above to show that in a locally cartesian closed category, every subobject lattice
is cartesian closed (equivalently, a Heyting algebra).
-/
universes v₁ v₂ u₁ u₂
noncomputable theory
namespace category_theory
open limits category
variables {C : Type u₁} [category.{v₁} C] {A : C}
/-- An object `A` is subterminal iff for any `Z`, there is at most one morphism `Z ⟶ A`. -/
def is_subterminal (A : C) : Prop := ∀ ⦃Z : C⦄ (f g : Z ⟶ A), f = g
lemma is_subterminal.def : is_subterminal A ↔ ∀ ⦃Z : C⦄ (f g : Z ⟶ A), f = g := iff.rfl
/--
If `A` is subterminal, the unique morphism from it to a terminal object is a monomorphism.
The converse of `is_subterminal_of_mono_is_terminal_from`.
-/
lemma is_subterminal.mono_is_terminal_from (hA : is_subterminal A) {T : C} (hT : is_terminal T) :
mono (hT.from A) :=
{ right_cancellation := λ Z g h _, hA _ _ }
/--
If `A` is subterminal, the unique morphism from it to the terminal object is a monomorphism.
The converse of `is_subterminal_of_mono_terminal_from`.
-/
lemma is_subterminal.mono_terminal_from [has_terminal C] (hA : is_subterminal A) :
mono (terminal.from A) :=
hA.mono_is_terminal_from terminal_is_terminal
/--
If the unique morphism from `A` to a terminal object is a monomorphism, `A` is subterminal.
The converse of `is_subterminal.mono_is_terminal_from`.
-/
lemma is_subterminal_of_mono_is_terminal_from {T : C} (hT : is_terminal T) [mono (hT.from A)] :
is_subterminal A :=
λ Z f g, by { rw ← cancel_mono (hT.from A), apply hT.hom_ext }
/--
If the unique morphism from `A` to the terminal object is a monomorphism, `A` is subterminal.
The converse of `is_subterminal.mono_terminal_from`.
-/
lemma is_subterminal_of_mono_terminal_from [has_terminal C] [mono (terminal.from A)] :
is_subterminal A :=
λ Z f g, by { rw ← cancel_mono (terminal.from A), apply subsingleton.elim }
lemma is_subterminal_of_is_terminal {T : C} (hT : is_terminal T) : is_subterminal T :=
λ Z f g, hT.hom_ext _ _
lemma is_subterminal_of_terminal [has_terminal C] : is_subterminal (⊤_ C) :=
λ Z f g, subsingleton.elim _ _
/--
If `A` is subterminal, its diagonal morphism is an isomorphism.
The converse of `is_subterminal_of_is_iso_diag`.
-/
lemma is_subterminal.is_iso_diag (hA : is_subterminal A) [has_binary_product A A] :
is_iso (diag A) :=
⟨⟨limits.prod.fst, ⟨by simp, by { rw is_subterminal.def at hA, tidy }⟩⟩⟩
/--
If the diagonal morphism of `A` is an isomorphism, then it is subterminal.
The converse of `is_subterminal.is_iso_diag`.
-/
lemma is_subterminal_of_is_iso_diag [has_binary_product A A] [is_iso (diag A)] :
is_subterminal A :=
λ Z f g,
begin
have : (limits.prod.fst : A ⨯ A ⟶ _) = limits.prod.snd,
{ simp [←cancel_epi (diag A)] },
rw [←prod.lift_fst f g, this, prod.lift_snd],
end
/-- If `A` is subterminal, it is isomorphic to `A ⨯ A`. -/
@[simps]
def is_subterminal.iso_diag (hA : is_subterminal A) [has_binary_product A A] :
A ⨯ A ≅ A :=
begin
letI := is_subterminal.is_iso_diag hA,
apply (as_iso (diag A)).symm,
end
variables (C)
/--
The (full sub)category of subterminal objects.
TODO: If `C` is the category of sheaves on a topological space `X`, this category is equivalent
to the lattice of open subsets of `X`. More generally, if `C` is a topos, this is the lattice of
"external truth values".
-/
@[derive category]
def subterminals (C : Type u₁) [category.{v₁} C] :=
full_subcategory (λ (A : C), is_subterminal A)
instance [has_terminal C] : inhabited (subterminals C) :=
⟨⟨⊤_ C, is_subterminal_of_terminal⟩⟩
/-- The inclusion of the subterminal objects into the original category. -/
@[derive [full, faithful], simps]
def subterminal_inclusion : subterminals C ⥤ C := full_subcategory_inclusion _
instance subterminals_thin (X Y : subterminals C) : subsingleton (X ⟶ Y) :=
⟨λ f g, Y.2 f g⟩
/--
The category of subterminal objects is equivalent to the category of monomorphisms to the terminal
object (which is in turn equivalent to the subobjects of the terminal object).
-/
@[simps]
def subterminals_equiv_mono_over_terminal [has_terminal C] :
subterminals C ≌ mono_over (⊤_ C) :=
{ functor :=
{ obj := λ X, ⟨over.mk (terminal.from X.1), X.2.mono_terminal_from⟩,
map := λ X Y f, mono_over.hom_mk f (by ext1 ⟨⟨⟩⟩) },
inverse :=
{ obj := λ X, ⟨X.obj.left, λ Z f g, by { rw ← cancel_mono X.arrow, apply subsingleton.elim }⟩,
map := λ X Y f, f.1 },
unit_iso :=
{ hom := { app := λ X, 𝟙 _ },
inv := { app := λ X, 𝟙 _ } },
counit_iso :=
{ hom := { app := λ X, over.hom_mk (𝟙 _) },
inv := { app := λ X, over.hom_mk (𝟙 _) } } }
@[simp]
lemma subterminals_to_mono_over_terminal_comp_forget [has_terminal C] :
(subterminals_equiv_mono_over_terminal C).functor ⋙ mono_over.forget _ ⋙ over.forget _ =
subterminal_inclusion C :=
rfl
@[simp]
lemma mono_over_terminal_to_subterminals_comp [has_terminal C] :
(subterminals_equiv_mono_over_terminal C).inverse ⋙ subterminal_inclusion C =
mono_over.forget _ ⋙ over.forget _ :=
rfl
end category_theory
|
module Structure.Logic where
|
"""
TriangularPrism(a, b, c, n, height, offset)
TriangularPrism(a, b, c, height, offset = 0)
Create a `TriangularPrism` that can be used for spatial lookup.
`a`, `b`, and `c` are the points of the triangle, `n` if provided is the normal
for the plane defined by `a`, `b`, and `c`.
The `height` is along the normal of the plane defined by the points of the triangle.
`offset` is a distance along the negative of the normal to `offset` the `height`.
For example, a prism with `height` 1 and `offset` 0 extends from the plane a
distance of 1 along the normal. A prism with `height` 1 and `offset` 0.5 extends
from a plane 0.5 along the negative of the normal and a distance of 1 along
the normal, in essence centering the volume for the prism evenly on both sides
of the plane defined by the three points of the triangle.
See also `AbstractRegion`
"""
struct TriangularPrism{T <: Real} <: AbstractRegion{T}
a::SVector{3,T}
b::SVector{3,T}
c::SVector{3,T}
n::SVector{3,T}
height::T
offset::T
end
@inline function TriangularPrism(a::StaticVector{3,T}, b::StaticVector{3,T}, c::StaticVector{3,T}, height::T, offset::T = 0.0) where T <: Real
v1 = b - a
v2 = c - a
n = cross(v1, v2)
n = n / norm(n)
return TriangularPrism{T}(a, b, c, n, height, offset)
end
"""
volume(prism::TriangularPrism)
Returns the volume of the `prism`.
"""
@inline volume(t::TriangularPrism) = t.height * dot(t.n, cross(t.b - t.a, t.c - t.a)) / 2.0
function boundingbox(t::TriangularPrism{T}) where T
points = vcat(
map(x -> x - t.offset * t.n, [t.a, t.b, t.c]),
map(x -> x + (t.height - t.offset) * t.n, [t.a, t.b, t.c])
)
xmin, xmax = extrema(map(x -> x[1], points))
ymin, ymax = extrema(map(x -> x[2], points))
zmin, zmax = extrema(map(x -> x[3], points))
return BoundingBox{T}(xmin, ymin, zmin, xmax, ymax, zmax)
end
function Base.in(p::StaticVector{3,T}, t::Region) where T <: Real where Region <: TriangularPrism
a, b, c, n, h = t.a, t.b, t.c, t.n, t.height
distance = dot(n, p - a)
if distance < -t.offset || distance > (t.height - t.offset)
return false
end
# project p to the plane
p = p - t.n * distance
# determine if the point is in the triangle when projected to the plane
# using barycentric coordinates http://mathworld.wolfram.com/BarycentricCoordinates.html
areaABC = dot(n, cross(b - a, c - a))
areaPBC = dot(n, cross(b - p, c - p))
areaPCA = dot(n, cross(c - p, a - p))
areaPAB = dot(n, cross(a - p, b - p))
u = areaPBC / areaABC
v = areaPCA / areaABC
w = areaPAB / areaABC
return (u + v + w) ≈ 1.0 && u > 0 && v > 0 && w > 0 && u < 1 && v < 1 && w < 1
end
|
{-# OPTIONS --cubical --safe --postfix-projections #-}
module Data.Fin.Properties where
open import Prelude
open import Data.Fin.Base
import Data.Nat.Properties as ℕ
open import Data.Nat.Properties using (+-comm)
open import Data.Nat
open import Function.Injective
open import Agda.Builtin.Nat renaming (_<_ to _<ᵇ_)
private
variable
n m : ℕ
suc-natfin : Σ[ m ⦂ ℕ ] (m ℕ.< n) → Σ[ m ⦂ ℕ ] (m ℕ.< suc n)
suc-natfin (m , p) = suc m , p
Fin-to-Nat-lt : Fin n → Σ[ m ⦂ ℕ ] (m ℕ.< n)
Fin-to-Nat-lt {n = suc n} f0 = zero , tt
Fin-to-Nat-lt {n = suc n} (fs x) = suc-natfin (Fin-to-Nat-lt x)
Fin-from-Nat-lt : ∀ m → m ℕ.< n → Fin n
Fin-from-Nat-lt {n = suc n} zero p = f0
Fin-from-Nat-lt {n = suc n} (suc m) p = fs (Fin-from-Nat-lt m p)
Fin-Nat-lt-rightInv : ∀ m → (p : m ℕ.< n) → Fin-to-Nat-lt {n = n} (Fin-from-Nat-lt m p) ≡ (m , p)
Fin-Nat-lt-rightInv {n = suc n} zero p = refl
Fin-Nat-lt-rightInv {n = suc n} (suc m) p = cong (suc-natfin {n = n}) (Fin-Nat-lt-rightInv {n = n} m p)
Fin-Nat-lt-leftInv : (x : Fin n) → uncurry Fin-from-Nat-lt (Fin-to-Nat-lt x) ≡ x
Fin-Nat-lt-leftInv {n = suc n} f0 = refl
Fin-Nat-lt-leftInv {n = suc n} (fs x) = cong fs (Fin-Nat-lt-leftInv x)
Fin-Nat-lt : Fin n ⇔ Σ[ m ⦂ ℕ ] (m ℕ.< n)
Fin-Nat-lt .fun = Fin-to-Nat-lt
Fin-Nat-lt .inv = uncurry Fin-from-Nat-lt
Fin-Nat-lt .rightInv = uncurry Fin-Nat-lt-rightInv
Fin-Nat-lt .leftInv = Fin-Nat-lt-leftInv
FinToℕ : Fin n → ℕ
FinToℕ {n = suc n} f0 = zero
FinToℕ {n = suc n} (fs x) = suc (FinToℕ x)
FinToℕ-injective : ∀ {k} {m n : Fin k} → FinToℕ m ≡ FinToℕ n → m ≡ n
FinToℕ-injective {suc k} {f0} {f0} _ = refl
FinToℕ-injective {suc k} {f0} {fs x} p = ⊥-elim (ℕ.znots p)
FinToℕ-injective {suc k} {fs m} {f0} p = ⊥-elim (ℕ.snotz p)
FinToℕ-injective {suc k} {fs m} {fs x} p = cong fs (FinToℕ-injective (ℕ.injSuc p))
pred : Fin (suc n) → Fin (suc (ℕ.pred n))
pred f0 = f0
pred {n = suc n} (fs m) = m
discreteFin : ∀ {k} → Discrete (Fin k)
discreteFin {k = suc _} f0 f0 = yes refl
discreteFin {k = suc _} f0 (fs fk) = no (ℕ.znots ∘ cong FinToℕ)
discreteFin {k = suc _} (fs fj) f0 = no (ℕ.snotz ∘ cong FinToℕ)
discreteFin {k = suc _} (fs fj) (fs fk) =
⟦yes cong fs ,no cong (λ { f0 → fk ; (fs x) → x}) ⟧ (discreteFin fj fk)
isSetFin : isSet (Fin n)
isSetFin = Discrete→isSet discreteFin
FinFromℕ : (n m : ℕ) → T (n <ᵇ m) → Fin m
FinFromℕ zero (suc m) p = f0
FinFromℕ (suc n) (suc m) p = fs (FinFromℕ n m p)
infix 4 _≢ᶠ_ _≡ᶠ_
_≢ᶠ_ _≡ᶠ_ : Fin n → Fin n → Type _
n ≢ᶠ m = T (not (discreteFin n m .does))
n ≡ᶠ m = T (discreteFin n m .does)
_F↣_ : ℕ → ℕ → Type₀
n F↣ m = Σ[ f ⦂ (Fin n → Fin m) ] ∀ {x y} → x ≢ᶠ y → f x ≢ᶠ f y
shift : (x y : Fin (suc n)) → x ≢ᶠ y → Fin n
shift f0 (fs y) x≢y = y
shift {suc _} (fs x) f0 x≢y = f0
shift {suc _} (fs x) (fs y) x≢y = fs (shift x y x≢y)
shift-inj : ∀ (x y z : Fin (suc n)) x≢y x≢z → y ≢ᶠ z → shift x y x≢y ≢ᶠ shift x z x≢z
shift-inj f0 (fs y) (fs z) x≢y x≢z x+y≢x+z = x+y≢x+z
shift-inj {suc _} (fs x) f0 (fs z) x≢y x≢z x+y≢x+z = tt
shift-inj {suc _} (fs x) (fs y) f0 x≢y x≢z x+y≢x+z = tt
shift-inj {suc _} (fs x) (fs y) (fs z) x≢y x≢z x+y≢x+z = shift-inj x y z x≢y x≢z x+y≢x+z
shrink : suc n F↣ suc m → n F↣ m
shrink (f , inj) .fst x = shift (f f0) (f (fs x)) (inj tt)
shrink (f , inj) .snd p = shift-inj (f f0) (f (fs _)) (f (fs _)) (inj tt) (inj tt) (inj p)
¬plus-inj : ∀ n m → ¬ (suc (n + m) F↣ m)
¬plus-inj zero zero (f , _) = f f0
¬plus-inj zero (suc m) inj = ¬plus-inj zero m (shrink inj)
¬plus-inj (suc n) m (f , p) = ¬plus-inj n m (f ∘ fs , p)
toFin-inj : (Fin n ↣ Fin m) → n F↣ m
toFin-inj f .fst = f .fst
toFin-inj (f , inj) .snd {x} {y} x≢ᶠy with discreteFin x y | discreteFin (f x) (f y)
... | no ¬p | yes p = ¬p (inj _ _ p)
... | no _ | no _ = tt
n≢sn+m : ∀ n m → Fin n ≢ Fin (suc (n + m))
n≢sn+m n m n≡m =
¬plus-inj m n
(toFin-inj
(subst
(_↣ Fin n)
(n≡m ; cong (Fin ∘ suc) (+-comm n m))
refl-↣))
Fin-inj : Injective Fin
Fin-inj n m eq with compare n m
... | equal _ = refl
... | less n k = ⊥-elim (n≢sn+m n k eq)
... | greater m k = ⊥-elim (n≢sn+m m k (sym eq))
|
#pragma once
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <dawn/read_config_file.hpp>
#include <dawn/app/log_init_from_pt.hpp>
namespace dawn {
namespace app {
inline boost::property_tree::ptree log_init_from_file(std::string const& filename, std::string const& syslog_ident = "")
{
boost::property_tree::ptree const pt = read_config_file(filename);
log_init_from_pt(pt, syslog_ident);
return pt;
}
}}
|
module Toolkit.Data.DList.Any
import Toolkit.Decidable.Informative
import Toolkit.Data.DList
import public Toolkit.Decidable.Equality.Indexed
%default total
||| Proof that some element satisfies the predicate
|||
||| @idx The type of the element's index.
||| @type The type of the list element.
||| @p A predicate
||| @xs The list itself.
public export
data Any : (idx : Type)
-> (type : idx -> Type)
-> (p : {i : idx} -> (x : type i) -> Type)
-> {is : List idx}
-> (xs : DList idx type is)
-> Type
where
||| Proof that the element is at the front of the list.
H : {p : {i : idx} -> (x : type i) -> Type}
-> {i : idx}
-> {y : type i}
-> (prf : p y)
-> Any idx type p (y :: xs)
||| Proof that the element is found later in the list.
T : {p : {i : idx} -> (x : type i) -> Type}
-> (contra : p x' -> Void)
-> (later : Any idx type p xs)
-> Any idx type p (x' ::xs)
empty : {p : {i : idx} -> (x : type i) -> Type} -> Any idx type p Nil -> Void
empty (H prf) impossible
empty (T contra later) impossible
isNotThere : {p : {i : idx} -> (x : type i) -> Type}
-> (Any idx type p rest -> Void)
-> (p i -> Void)
-> Any idx type p (i :: rest) -> Void
isNotThere f g (H prf) = g prf
isNotThere f g (T contra later) = f later
export
any : {p : {i : idx} -> (x : type i) -> Type}
-> (f : {i : idx} -> (x : type i) -> DecInfo err (p x))
-> (xs : DList idx type is)
-> Dec (Any idx type p xs)
any f [] = No empty
any f (elem :: rest) with (f elem)
any f (elem :: rest) | (Yes prfWhy)
= Yes (H prfWhy)
any f (elem :: rest) | (No msgWhyNot prfWhyNot) with (any f rest)
any f (elem :: rest) | (No msgWhyNot prfWhyNot) | (Yes prfWhy)
= Yes (T prfWhyNot prfWhy)
any f (elem :: rest) | (No msgWhyNot prfWhyNot) | (No g)
= No (isNotThere g prfWhyNot)
-- [ EOF ]
|
(*
Copyright © 2006-2008 Russell O’Connor
Permission is hereby granted, free of charge, to any person obtaining a copy of
this proof and associated documentation files (the "Proof"), to deal in
the Proof without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Proof, and to permit persons to whom the Proof is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Proof.
THE PROOF IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.
*)
Set Firstorder Depth 5.
Require Export CoRN.algebra.RSetoid.
Set Implicit Arguments.
(**
* Partial Order
A partial order is a relfexive, transitive, antisymetric ordering relation.
*)
(* Perhaps adding monotone and antitone to the signature is going too far *)
Record is_PartialOrder
(car : Type)
(eq : car -> car -> Prop)
(le : car -> car -> Prop)
(monotone : (car -> car) -> Prop)
(antitone : (car -> car) -> Prop) : Prop :=
{ po_equiv_le_def : forall x y, eq x y <-> (le x y /\ le y x)
; po_le_refl : forall x, le x x
; po_le_trans : forall x y z, le x y -> le y z -> le x z
; po_monotone_def : forall f, monotone f <-> (forall x y, le x y -> le (f x) (f y))
; po_antitone_def : forall f, antitone f <-> (forall x y, le x y -> le (f y) (f x))
}.
(* This ought to decend from RSetoid *)
Record PartialOrder : Type :=
{ po_car :> RSetoid
; le : po_car -> po_car -> Prop
; monotone : (po_car -> po_car) -> Prop
; antitone : (po_car -> po_car) -> Prop
; po_proof : is_PartialOrder (@st_eq po_car) le monotone antitone
}.
Notation "x == y" := (st_eq x y) (at level 70, no associativity) : po_scope.
Notation "x <= y" := (le _ x y) : po_scope.
Local Open Scope po_scope.
Lemma po_st : forall X eq le mnt ant, @is_PartialOrder X eq le mnt ant -> Setoid_Theory X eq.
Proof with trivial.
intros X eq le0 mnt ant H.
split.
firstorder.
intros x y E. apply (po_equiv_le_def H), and_comm, (po_equiv_le_def H)...
intros x y z.
repeat rewrite ->(po_equiv_le_def H).
firstorder.
Qed.
(* begin hide *)
Add Parametric Morphism (p:PartialOrder) : (le p) with signature (@st_eq p) ==> (@st_eq p) ==> iff as le_compat.
Proof.
assert (forall x1 x2 : p, x1 == x2 -> forall x3 x4 : p, x3 == x4 -> (x1 <= x3 -> x2 <= x4)).
intros.
rewrite -> (po_equiv_le_def (po_proof p)) in *|-.
destruct (po_proof p).
clear - H H0 H1 po_le_trans0.
firstorder.
intros x y Hxy x0 y0 Hx0y0.
assert (y==x).
symmetry; assumption.
assert (y0==x0).
symmetry; assumption.
firstorder.
Qed.
(* end hide *)
Section PartialOrder.
Variable X : PartialOrder.
Definition makePartialOrder car eq le monotone antitone p1 p2 p3 p4 p5 :=
let p := (@Build_is_PartialOrder car eq le monotone antitone p1 p2 p3 p4 p5) in
@Build_PartialOrder (Build_RSetoid (po_st p)) le monotone antitone p.
(** The axioms and basic properties of a partial order *)
Lemma equiv_le_def : forall x y:X, x == y <-> (x <= y /\ y <= x).
Proof (po_equiv_le_def (po_proof X)).
Lemma le_refl : forall x:X, x <= x.
Proof (po_le_refl (po_proof X)).
Lemma le_trans : forall x y z : X, x <= y -> y <= z -> x <= z.
Proof (po_le_trans (po_proof X)).
Lemma monotone_def : forall f, monotone X f <-> (forall x y, x <= y -> (f x) <= (f y)).
Proof (po_monotone_def (po_proof X)).
Lemma antitone_def : forall f, antitone X f <-> (forall x y, x <= y -> (f y) <= (f x)).
Proof (po_antitone_def (po_proof X)).
Lemma le_equiv_refl : forall x y:X, x == y -> x <= y.
Proof.
firstorder using equiv_le_def.
Qed.
Lemma le_antisym : forall x y:X, x <= y -> y <= x -> x == y.
Proof.
firstorder using equiv_le_def.
Qed.
(**
** Dual Order
The dual of a partial order is made by fliping the order relation.
*)
Definition Dual : PartialOrder.
Proof.
eapply makePartialOrder with (eq := @st_eq X) (le:= (fun x y => le X y x)) (monotone := @monotone X)
(antitone := @antitone X).
firstorder using equiv_le_def.
firstorder using le_refl.
firstorder using le_trans.
firstorder using monotone_def. (* Notice the use of <-> in monotone_def here *)
firstorder using antitone_def.
Defined.
End PartialOrder.
Module Default.
(**
** Default Monotone and Antitone
These provide default implemenations of Monotone and Antitone.
*)
Section MonotoneAntitone.
Variable A : Type.
Variable le : A -> A -> Prop.
Definition monotone (f: A -> A) := forall x y, le x y -> le (f x) (f y).
Lemma monotone_def : forall f, monotone f <-> (forall x y, le x y -> le (f x) (f y)).
Proof.
firstorder.
Qed.
Definition antitone (f: A -> A) := forall x y, le x y -> le (f y) (f x).
Lemma antitone_def : forall f, antitone f <-> (forall x y, le x y -> le (f y) (f x)).
Proof.
firstorder.
Qed.
End MonotoneAntitone.
End Default.
|
[STATEMENT]
lemma "finite A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite A
[PROOF STEP]
nitpick [expect = none]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite A
[PROOF STEP]
oops |
import data.matrix.basic data.real.basic
universes u v
namespace matrix
variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o]
variables {α : Type v}
-- TODO: move / generalize in matrix.lean
lemma mul_zero' [ring α] (M : matrix m n α) : M.mul (0 : matrix n l α) = 0 :=
begin
ext i j,
unfold matrix.mul,
simp
end
lemma mul_add' [ring α] (L : matrix m n α) (M N : matrix n l α) : L.mul (M + N) = L.mul M + L.mul N :=
begin
ext i j,
unfold matrix.mul,
simp [left_distrib, finset.sum_add_distrib]
end
lemma add_mul' [ring α] (M N : matrix m n α) (L : matrix n l α) : (M + N).mul L = M.mul L + N.mul L :=
begin
ext i j,
unfold matrix.mul,
simp [right_distrib, finset.sum_add_distrib]
end
lemma mul_sub' [ring α] (L : matrix m n α) (M N : matrix n l α) : L.mul (M - N) = L.mul M - L.mul N :=
by simp [mul_add']
lemma sub_mul' [ring α] (M N : matrix m n α) (L : matrix n l α) : (M - N).mul L = M.mul L - N.mul L :=
by simp [add_mul']
local postfix `ᵀ` : 1500 := transpose
-- TODO: add to mathlib
lemma transpose_smul [semiring α] (a : α) (M : matrix m n α) :
(a • M)ᵀ = a • Mᵀ :=
by ext i j; refl
-- TODO: add to mathlib
lemma eq_iff_transpose_eq (M : matrix m n α) (N : matrix m n α) : M = N ↔ Mᵀ = Nᵀ :=
begin
split,
{ intro h, ext i j, rw h },
{ intro h, ext i j, rw [←transpose_transpose M,h,transpose_transpose] },
end
end matrix
variables {k m n : nat}
variables {α : Type} [ring α]
@[reducible] def mat (α : Type) [ring α] (m n : nat) : Type :=
matrix (fin m) (fin n) α
@[reducible] def vec (α : Type) [ring α] (n : nat) : Type := (fin n) → α
local notation v `⬝` w := matrix.vec_mul_vec v w --TODO: matrix.vec_mul_vec is not the dot product but the outer vector product
namespace mat
def mem (a : α) (A : mat α m n) : Prop :=
∃ i : fin m, ∃ j : fin n, a = A i j
instance has_mem : has_mem α (mat α m n) := ⟨mem⟩
def trace_aux (A : mat α n n) : ∀ m, m ≤ n → α
| 0 h := 0
| (m+1) h :=
have h' : m < n := nat.lt_of_succ_le h,
A ⟨m,h'⟩ ⟨m,h'⟩ + trace_aux m (le_trans (nat.le_succ _) h)
def trace (A : mat α n n) : α := trace_aux A n (le_refl _)
def pos_semidef {α : Type} [ordered_ring α] (A : mat α n n) : Prop :=
∀ x : vec α n, ∀ a ∈ (x ⬝ (matrix.mul_vec A x)), (0 : α) ≤ a
def pos_def {α : Type} [ordered_ring α] (A : mat α n n) : Prop :=
∀ x : vec α n, x ≠ 0 → ∀ a ∈ (x ⬝ (matrix.mul_vec A x)), (0 : α) < a
def loewner {α : Type} [ordered_ring α] (A B : mat α n n) : Prop :=
pos_semidef (A - B)
infix `≼` : 1200 := loewner
infix `≽` : 1200 := λ A B, loewner B A
def strict_loewner [ordered_ring α] (A B : mat α n n) : Prop :=
A ≼ B ∧ A ≠ B
infix `≺` : 1200 := loewner
infix `≻` : 1200 := λ A B, strict_loewner B A
postfix `ᵀ` : 1500 := matrix.transpose
def get_diagonal (A : mat α m m) : mat α m m | i j :=
if i = j
then A i j
else 0
def lower_triangle (A : mat α m m) : mat α m m | i j :=
if i = j
then 1
else if i > j
then A i j
else 0
end mat
def lists_to_mat_core {m n : nat} (ls : list (list α))
(i : fin m) (j : fin n) : option α :=
do l ← ls.nth i.val, l.nth j.val
def lists_to_mat (m n : nat)
(ls : list (list α)) : mat α m n | i j :=
match lists_to_mat_core ls i j with
| none := 0
| (some a) := a
end
|
/-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
Transferring `traversable` instances using isomorphisms.
-/
import data.equiv.basic
import control.traversable.lemmas
universes u
namespace equiv
section functor
parameters {t t' : Type u → Type u}
parameters (eqv : Π α, t α ≃ t' α)
variables [functor t]
open functor
/-- Given a functor `t`, a function `t' : Type u → Type u`, and
equivalences `t α ≃ t' α` for all `α`, then every function `α → β` can
be mapped to a function `t' α → t' β` functorially (see
`equiv.functor`). -/
protected def map {α β : Type u} (f : α → β) (x : t' α) : t' β :=
eqv β $ map f ((eqv α).symm x)
/-- The function `equiv.map` transfers the functoriality of `t` to
`t'` using the equivalences `eqv`. -/
protected def functor : functor t' :=
{ map := @equiv.map _ }
variables [is_lawful_functor t]
protected lemma id_map {α : Type u} (x : t' α) : equiv.map id x = x :=
by simp [equiv.map, id_map]
protected lemma comp_map {α β γ : Type u} (g : α → β) (h : β → γ) (x : t' α) :
equiv.map (h ∘ g) x = equiv.map h (equiv.map g x) :=
by simp [equiv.map]; apply comp_map
protected lemma is_lawful_functor : @is_lawful_functor _ equiv.functor :=
{ id_map := @equiv.id_map _ _,
comp_map := @equiv.comp_map _ _ }
protected lemma is_lawful_functor' [F : _root_.functor t']
(h₀ : ∀ {α β} (f : α → β), _root_.functor.map f = equiv.map f)
(h₁ : ∀ {α β} (f : β), _root_.functor.map_const f = (equiv.map ∘ function.const α) f) :
_root_.is_lawful_functor t' :=
begin
have : F = equiv.functor,
{ casesI F, dsimp [equiv.functor],
congr; ext; [rw ← h₀, rw ← h₁] },
substI this,
exact equiv.is_lawful_functor
end
end functor
section traversable
parameters {t t' : Type u → Type u}
parameters (eqv : Π α, t α ≃ t' α)
variables [traversable t]
variables {m : Type u → Type u} [applicative m]
variables {α β : Type u}
/-- Like `equiv.map`, a function `t' : Type u → Type u` can be given
the structure of a traversable functor using a traversable functor
`t'` and equivalences `t α ≃ t' α` for all α. See `equiv.traversable`. -/
protected def traverse (f : α → m β) (x : t' α) : m (t' β) :=
eqv β <$> traverse f ((eqv α).symm x)
/-- The function `equiv.tranverse` transfers a traversable functor
instance across the equivalences `eqv`. -/
protected def traversable : traversable t' :=
{ to_functor := equiv.functor eqv,
traverse := @equiv.traverse _ }
end traversable
section equiv
parameters {t t' : Type u → Type u}
parameters (eqv : Π α, t α ≃ t' α)
variables [traversable t] [is_lawful_traversable t]
variables {F G : Type u → Type u} [applicative F] [applicative G]
variables [is_lawful_applicative F] [is_lawful_applicative G]
variables (η : applicative_transformation F G)
variables {α β γ : Type u}
open is_lawful_traversable functor
protected lemma id_traverse (x : t' α) :
equiv.traverse eqv id.mk x = x :=
by simp! [equiv.traverse,id_bind,id_traverse,functor.map] with functor_norm
protected lemma traverse_eq_map_id (f : α → β) (x : t' α) :
equiv.traverse eqv (id.mk ∘ f) x = id.mk (equiv.map eqv f x) :=
by simp [equiv.traverse, traverse_eq_map_id] with functor_norm; refl
protected lemma comp_traverse (f : β → F γ) (g : α → G β) (x : t' α) :
equiv.traverse eqv (comp.mk ∘ functor.map f ∘ g) x =
comp.mk (equiv.traverse eqv f <$> equiv.traverse eqv g x) :=
by simp [equiv.traverse,comp_traverse] with functor_norm; congr; ext; simp
protected lemma naturality (f : α → F β) (x : t' α) :
η (equiv.traverse eqv f x) = equiv.traverse eqv (@η _ ∘ f) x :=
by simp only [equiv.traverse] with functor_norm
/-- The fact that `t` is a lawful traversable functor carries over the
equivalences to `t'`, with the traversable functor structure given by
`equiv.traversable`. -/
protected def is_lawful_traversable :
@is_lawful_traversable t' (equiv.traversable eqv) :=
{ to_is_lawful_functor := @equiv.is_lawful_functor _ _ eqv _ _,
id_traverse := @equiv.id_traverse _ _,
comp_traverse := @equiv.comp_traverse _ _,
traverse_eq_map_id := @equiv.traverse_eq_map_id _ _,
naturality := @equiv.naturality _ _ }
/-- If the `traversable t'` instance has the properties that `map`,
`map_const`, and `traverse` are equal to the ones that come from
carrying the traversable functor structure from `t` over the
equivalences, then the the fact `t` is a lawful traversable functor
carries over as well. -/
protected def is_lawful_traversable' [_i : traversable t']
(h₀ : ∀ {α β} (f : α → β),
map f = equiv.map eqv f)
(h₁ : ∀ {α β} (f : β),
map_const f = (equiv.map eqv ∘ function.const α) f)
(h₂ : ∀ {F : Type u → Type u} [applicative F],
by exactI ∀ [is_lawful_applicative F]
{α β} (f : α → F β),
traverse f = equiv.traverse eqv f) :
_root_.is_lawful_traversable t' :=
begin
-- we can't use the same approach as for `is_lawful_functor'` because
-- h₂ needs a `is_lawful_applicative` assumption
refine {to_is_lawful_functor :=
equiv.is_lawful_functor' eqv @h₀ @h₁, ..}; introsI,
{ rw [h₂, equiv.id_traverse], apply_instance },
{ rw [h₂, equiv.comp_traverse f g x, h₂], congr,
rw [h₂], all_goals { apply_instance } },
{ rw [h₂, equiv.traverse_eq_map_id, h₀]; apply_instance },
{ rw [h₂, equiv.naturality, h₂]; apply_instance }
end
end equiv
end equiv
|
library(gmp)
a <- as.bigz("18446744073709551616")
mul.bigz(a,a)
|
(*
Title: The pi-calculus
Author/Maintainer: Jesper Bengtson (jebe.dk), 2012
*)
theory Weak_Early_Cong_Pres
imports Weak_Early_Cong Weak_Early_Step_Sim_Pres Weak_Early_Bisim_Pres
begin
lemma tauPres:
fixes P :: pi
and Q :: pi
assumes "P \<simeq> Q"
shows "\<tau>.(P) \<simeq> \<tau>.(Q)"
proof -
from assms have "P \<approx> Q" by(rule congruenceWeakBisim)
thus ?thesis by(force intro: Weak_Early_Step_Sim_Pres.tauPres simp add: weakCongruence_def dest: weakBisimE(2))
qed
lemma outputPres:
fixes P :: pi
and Q :: pi
assumes "P \<simeq> Q"
shows "a{b}.P \<simeq> a{b}.Q"
proof -
from assms have "P \<approx> Q" by(rule congruenceWeakBisim)
thus ?thesis by(force intro: Weak_Early_Step_Sim_Pres.outputPres simp add: weakCongruence_def dest: weakBisimE(2))
qed
assumes "P \<simeq> Q"
shows "[a\<frown>b]P \<simeq> [a\<frown>b]Q"
using assms
by(auto simp add: weakCongruence_def intro: Weak_Early_Step_Sim_Pres.matchPres)
lemma mismatchPres:
fixes P :: pi
and Q :: pi
and a :: name
and b :: name
assumes "P \<simeq> Q"
shows "[a\<noteq>b]P \<simeq> [a\<noteq>b]Q"
using assms
by(auto simp add: weakCongruence_def intro: Weak_Early_Step_Sim_Pres.mismatchPres)
lemma sumPres:
fixes P :: pi
and Q :: pi
and R :: pi
assumes "P \<simeq> Q"
shows "P \<oplus> R \<simeq> Q \<oplus> R"
using assms
by(auto simp add: weakCongruence_def intro: Weak_Early_Step_Sim_Pres.sumPres Weak_Early_Bisim.reflexive)
lemma parPres:
fixes P :: pi
and Q :: pi
and R :: pi
assumes "P \<simeq> Q"
shows "P \<parallel> R \<simeq> Q \<parallel> R"
proof -
have "\<And>P Q R. \<lbrakk>P \<leadsto>\<guillemotleft>weakBisim\<guillemotright> Q; P \<approx> Q\<rbrakk> \<Longrightarrow> P \<parallel> R \<leadsto>\<guillemotleft>weakBisim\<guillemotright> Q \<parallel> R"
proof -
fix P Q R
assume "P \<leadsto>\<guillemotleft>weakBisim\<guillemotright> Q" and "P \<approx> Q"
thus "P \<parallel> R \<leadsto>\<guillemotleft>weakBisim\<guillemotright> Q \<parallel> R"
using Weak_Early_Bisim_Pres.parPres Weak_Early_Bisim_Pres.resPres Weak_Early_Bisim.reflexive Weak_Early_Bisim.eqvt
by(blast intro: Weak_Early_Step_Sim_Pres.parPres)
qed
moreover from assms have "P \<approx> Q" by(rule congruenceWeakBisim)
ultimately show ?thesis using assms
by(auto simp add: weakCongruence_def dest: weakBisimE)
qed
assumes PeqQ: "P \<simeq> Q"
shows "<\<nu>x>P \<simeq> <\<nu>x>Q"
proof -
have "\<And>P Q x. P \<leadsto>\<guillemotleft>weakBisim\<guillemotright> Q \<Longrightarrow> <\<nu>x>P \<leadsto>\<guillemotleft>weakBisim\<guillemotright> <\<nu>x>Q"
proof -
fix P Q x
assume "P \<leadsto>\<guillemotleft>weakBisim\<guillemotright> Q"
with Weak_Early_Bisim.eqvt Weak_Early_Bisim_Pres.resPres show "<\<nu>x>P \<leadsto>\<guillemotleft>weakBisim\<guillemotright> <\<nu>x>Q"
by(blast intro: Weak_Early_Step_Sim_Pres.resPres)
qed
with assms show ?thesis by(simp add: weakCongruence_def)
qed
shows "!P \<simeq> !Q"
using assms
proof(induct rule: weakCongISym2)
case(cSim P Q)
let ?X = "{(P, Q) | P Q. P \<simeq> Q}"
from \<open>P \<simeq> Q\<close> have "(P, Q) \<in> ?X" by auto
moreover have "\<And>P Q. (P, Q) \<in> ?X \<Longrightarrow> P \<leadsto>\<guillemotleft>weakBisim\<guillemotright> Q" by(auto simp add: weakCongruence_def)
moreover from congruenceWeakBisim have "?X \<subseteq> weakBisim" by auto
ultimately have "!P \<leadsto>\<guillemotleft>bangRel weakBisim\<guillemotright> !Q" using Weak_Early_Bisim.eqvt
by(rule Weak_Early_Step_Sim_Pres.bangPres)
moreover have "bangRel weakBisim \<subseteq> weakBisim" by(rule bangRelSubWeakBisim)
ultimately show "!P \<leadsto>\<guillemotleft>weakBisim\<guillemotright> !Q"
by(rule Weak_Early_Step_Sim.monotonic)
qed
end
|
Formal statement is: lemma poly_pcompose: "poly (pcompose p q) x = poly p (poly q x)" Informal statement is: The polynomial $p \circ q$ is the same as the polynomial $p$ evaluated at the polynomial $q$. |
!
! This is included in domain_mod.f90, because the code was getting complicated
!
! Experimental energy-conservative flux computation.
#include "domain_mod_compute_fluxes_EEC_include.f90"
! Regular DE1 flux
subroutine compute_fluxes_DE1(domain, max_dt_out)
class(domain_type), intent(inout):: domain
real(dp), optional, intent(inout) :: max_dt_out
! Providing this at compile time leads to substantial optimization.
logical, parameter :: reduced_momentum_diffusion = .false.
logical, parameter :: upwind_transverse_momentum = .false.
#include "domain_mod_compute_fluxes_DE1_inner_include.f90"
end subroutine
! Low-diffusion DE1 flux
subroutine compute_fluxes_DE1_low_fr_diffusion(domain, max_dt_out)
class(domain_type), intent(inout):: domain
real(dp), optional, intent(inout) :: max_dt_out
! Providing this at compile time leads to substantial optimization.
logical, parameter :: reduced_momentum_diffusion = .true.
logical, parameter :: upwind_transverse_momentum = .false.
#include "domain_mod_compute_fluxes_DE1_inner_include.f90"
end subroutine
! Regular DE1 flux with upwind transverse momentum flux
subroutine compute_fluxes_DE1_upwind_transverse(domain, max_dt_out)
class(domain_type), intent(inout):: domain
real(dp), optional, intent(inout) :: max_dt_out
! Providing this at compile time leads to substantial optimization.
logical, parameter :: reduced_momentum_diffusion = .false.
logical, parameter :: upwind_transverse_momentum = .true.
#include "domain_mod_compute_fluxes_DE1_inner_include.f90"
end subroutine
! Low-diffusion DE1 flux with upwind transverse momentum flux
subroutine compute_fluxes_DE1_low_fr_diffusion_upwind_transverse(domain, max_dt_out)
class(domain_type), intent(inout):: domain
real(dp), optional, intent(inout) :: max_dt_out
! Providing this at compile time leads to substantial optimization.
logical, parameter :: reduced_momentum_diffusion = .true.
logical, parameter :: upwind_transverse_momentum = .true.
#include "domain_mod_compute_fluxes_DE1_inner_include.f90"
end subroutine
|
module syntax-util where
open import lib
open import cedille-types
open import general-util
open import constants
posinfo-gen : posinfo
posinfo-gen = "generated"
first-position : posinfo
first-position = "1"
dummy-var : var
dummy-var = "_dummy"
id-term : term
id-term = Lam posinfo-gen NotErased posinfo-gen "x" NoClass (Var posinfo-gen "x")
compileFailType : type
compileFailType = Abs posinfo-gen Erased posinfo-gen "X" (Tkk (Star posinfo-gen)) (TpVar posinfo-gen "X")
qualif-info : Set
qualif-info = var × args
qualif : Set
qualif = trie qualif-info
tag : Set
tag = string × rope
tagged-val : Set
tagged-val = string × rope × 𝕃 tag
tags-to-rope : 𝕃 tag → rope
tags-to-rope [] = [[]]
tags-to-rope ((t , v) :: []) = [[ "\"" ^ t ^ "\":" ]] ⊹⊹ v
tags-to-rope ((t , v) :: ts) = [[ "\"" ^ t ^ "\":" ]] ⊹⊹ v ⊹⊹ [[ "," ]] ⊹⊹ tags-to-rope ts
-- We number these when so we can sort them back in emacs
tagged-val-to-rope : ℕ → tagged-val → rope
tagged-val-to-rope n (t , v , []) = [[ "\"" ^ t ^ "\":[\"" ^ ℕ-to-string n ^ "\",\"" ]] ⊹⊹ v ⊹⊹ [[ "\"]" ]]
tagged-val-to-rope n (t , v , tags) = [[ "\"" ^ t ^ "\":[\"" ^ ℕ-to-string n ^ "\",\"" ]] ⊹⊹ v ⊹⊹ [[ "\",{" ]] ⊹⊹ tags-to-rope tags ⊹⊹ [[ "}]" ]]
tagged-vals-to-rope : ℕ → 𝕃 tagged-val → rope
tagged-vals-to-rope n [] = [[]]
tagged-vals-to-rope n (s :: []) = tagged-val-to-rope n s
tagged-vals-to-rope n (s :: (s' :: ss)) = tagged-val-to-rope n s ⊹⊹ [[ "," ]] ⊹⊹ tagged-vals-to-rope (suc n) (s' :: ss)
make-tag : (name : string) → (values : 𝕃 tag) → (start : ℕ) → (end : ℕ) → tag
make-tag name vs start end = name , [[ "{\"start\":\"" ^ ℕ-to-string start ^ "\",\"end\":\"" ^ ℕ-to-string end ^ "\"" ]] ⊹⊹ vs-to-rope vs ⊹⊹ [[ "}" ]]
where
vs-to-rope : 𝕃 tag → rope
vs-to-rope [] = [[]]
vs-to-rope ((t , v) :: ts) = [[ ",\"" ^ t ^ "\":\"" ]] ⊹⊹ v ⊹⊹ [[ "\"" ]] ⊹⊹ vs-to-rope ts
posinfo-to-ℕ : posinfo → ℕ
posinfo-to-ℕ pi with string-to-ℕ pi
posinfo-to-ℕ pi | just n = n
posinfo-to-ℕ pi | nothing = 0 -- should not happen
posinfo-plus : posinfo → ℕ → posinfo
posinfo-plus pi n = ℕ-to-string (posinfo-to-ℕ pi + n)
posinfo-plus-str : posinfo → string → posinfo
posinfo-plus-str pi s = posinfo-plus pi (string-length s)
star : kind
star = Star posinfo-gen
-- qualify variable by module name
_#_ : string → string → string
fn # v = fn ^ qual-global-str ^ v
_%_ : posinfo → var → string
pi % v = pi ^ qual-local-str ^ v
compileFail : var
compileFail = "compileFail"
compileFail-qual = "" % compileFail
mk-inst : params → args → trie arg × params
mk-inst (ParamsCons (Decl _ _ _ x _ _) ps) (ArgsCons a as) with mk-inst ps as
...| σ , ps' = trie-insert σ x a , ps'
mk-inst ps as = empty-trie , ps
apps-term : term → args → term
apps-term f (ArgsNil) = f
apps-term f (ArgsCons (TermArg me t) as) = apps-term (App f me t) as
apps-term f (ArgsCons (TypeArg t) as) = apps-term (AppTp f t) as
apps-type : type → args → type
apps-type f (ArgsNil) = f
apps-type f (ArgsCons (TermArg _ t) as) = apps-type (TpAppt f t) as
apps-type f (ArgsCons (TypeArg t) as) = apps-type (TpApp f t) as
append-params : params → params → params
append-params (ParamsCons p ps) qs = ParamsCons p (append-params ps qs)
append-params ParamsNil qs = qs
append-args : args → args → args
append-args (ArgsCons p ps) qs = ArgsCons p (append-args ps qs)
append-args (ArgsNil) qs = qs
append-cmds : cmds → cmds → cmds
append-cmds CmdsStart = id
append-cmds (CmdsNext c cs) = CmdsNext c ∘ append-cmds cs
qualif-lookup-term : qualif → string → term
qualif-lookup-term σ x with trie-lookup σ x
... | just (x' , as) = apps-term (Var posinfo-gen x') as
... | _ = Var posinfo-gen x
qualif-lookup-type : qualif → string → type
qualif-lookup-type σ x with trie-lookup σ x
... | just (x' , as) = apps-type (TpVar posinfo-gen x') as
... | _ = TpVar posinfo-gen x
qualif-lookup-kind : args → qualif → string → kind
qualif-lookup-kind xs σ x with trie-lookup σ x
... | just (x' , as) = KndVar posinfo-gen x' (append-args as xs)
... | _ = KndVar posinfo-gen x xs
inst-lookup-term : trie arg → string → term
inst-lookup-term σ x with trie-lookup σ x
... | just (TermArg me t) = t
... | _ = Var posinfo-gen x
inst-lookup-type : trie arg → string → type
inst-lookup-type σ x with trie-lookup σ x
... | just (TypeArg t) = t
... | _ = TpVar posinfo-gen x
params-to-args : params → args
params-to-args ParamsNil = ArgsNil
params-to-args (ParamsCons (Decl _ p me v (Tkt t) _) ps) = ArgsCons (TermArg me (Var posinfo-gen v)) (params-to-args ps)
params-to-args (ParamsCons (Decl _ p _ v (Tkk k) _) ps) = ArgsCons (TypeArg (TpVar posinfo-gen v)) (params-to-args ps)
qualif-insert-params : qualif → var → var → params → qualif
qualif-insert-params σ qv v ps = trie-insert σ v (qv , params-to-args ps)
qualif-insert-import : qualif → var → optAs → 𝕃 string → args → qualif
qualif-insert-import σ mn oa [] as = σ
qualif-insert-import σ mn oa (v :: vs) as = qualif-insert-import (trie-insert σ (import-as v oa) (mn # v , as)) mn oa vs as
where
import-as : var → optAs → var
import-as v NoOptAs = v
import-as v (SomeOptAs _ pfx) = pfx # v
tk-is-type : tk → 𝔹
tk-is-type (Tkt _) = tt
tk-is-type (Tkk _) = ff
me-unerased : maybeErased → 𝔹
me-unerased Erased = ff
me-unerased NotErased = tt
me-erased : maybeErased → 𝔹
me-erased x = ~ (me-unerased x)
term-start-pos : term → posinfo
type-start-pos : type → posinfo
kind-start-pos : kind → posinfo
liftingType-start-pos : liftingType → posinfo
term-start-pos (App t x t₁) = term-start-pos t
term-start-pos (AppTp t tp) = term-start-pos t
term-start-pos (Hole pi) = pi
term-start-pos (Lam pi x _ x₁ x₂ t) = pi
term-start-pos (Let pi _ _) = pi
term-start-pos (Open pi _ _) = pi
term-start-pos (Parens pi t pi') = pi
term-start-pos (Var pi x₁) = pi
term-start-pos (Beta pi _ _) = pi
term-start-pos (IotaPair pi _ _ _ _) = pi
term-start-pos (IotaProj t _ _) = term-start-pos t
term-start-pos (Epsilon pi _ _ _) = pi
term-start-pos (Phi pi _ _ _ _) = pi
term-start-pos (Rho pi _ _ _ _ _) = pi
term-start-pos (Chi pi _ _) = pi
term-start-pos (Delta pi _ _) = pi
term-start-pos (Sigma pi _) = pi
term-start-pos (Theta pi _ _ _) = pi
term-start-pos (Mu pi _ _ _ _ _ _) = pi
term-start-pos (Mu' pi _ _ _ _ _) = pi
type-start-pos (Abs pi _ _ _ _ _) = pi
type-start-pos (TpLambda pi _ _ _ _) = pi
type-start-pos (Iota pi _ _ _ _) = pi
type-start-pos (Lft pi _ _ _ _) = pi
type-start-pos (TpApp t t₁) = type-start-pos t
type-start-pos (TpAppt t x) = type-start-pos t
type-start-pos (TpArrow t _ t₁) = type-start-pos t
type-start-pos (TpEq pi _ _ pi') = pi
type-start-pos (TpParens pi _ pi') = pi
type-start-pos (TpVar pi x₁) = pi
type-start-pos (NoSpans t _) = type-start-pos t -- we are not expecting this on input
type-start-pos (TpHole pi) = pi --ACG
type-start-pos (TpLet pi _ _) = pi
kind-start-pos (KndArrow k k₁) = kind-start-pos k
kind-start-pos (KndParens pi k pi') = pi
kind-start-pos (KndPi pi _ x x₁ k) = pi
kind-start-pos (KndTpArrow x k) = type-start-pos x
kind-start-pos (KndVar pi x₁ _) = pi
kind-start-pos (Star pi) = pi
liftingType-start-pos (LiftArrow l l') = liftingType-start-pos l
liftingType-start-pos (LiftParens pi l pi') = pi
liftingType-start-pos (LiftPi pi x₁ x₂ l) = pi
liftingType-start-pos (LiftStar pi) = pi
liftingType-start-pos (LiftTpArrow t l) = type-start-pos t
term-end-pos : term → posinfo
type-end-pos : type → posinfo
kind-end-pos : kind → posinfo
liftingType-end-pos : liftingType → posinfo
tk-end-pos : tk → posinfo
lterms-end-pos : lterms → posinfo
args-end-pos : (if-nil : posinfo) → args → posinfo
arg-end-pos : arg → posinfo
kvar-end-pos : posinfo → var → args → posinfo
term-end-pos (App t x t') = term-end-pos t'
term-end-pos (AppTp t tp) = type-end-pos tp
term-end-pos (Hole pi) = posinfo-plus pi 1
term-end-pos (Lam pi x _ x₁ x₂ t) = term-end-pos t
term-end-pos (Let _ _ t) = term-end-pos t
term-end-pos (Open pi _ t) = term-end-pos t
term-end-pos (Parens pi t pi') = pi'
term-end-pos (Var pi x) = posinfo-plus-str pi x
term-end-pos (Beta pi _ (SomeTerm t pi')) = pi'
term-end-pos (Beta pi (SomeTerm t pi') _) = pi'
term-end-pos (Beta pi NoTerm NoTerm) = posinfo-plus pi 1
term-end-pos (IotaPair _ _ _ _ pi) = pi
term-end-pos (IotaProj _ _ pi) = pi
term-end-pos (Epsilon pi _ _ t) = term-end-pos t
term-end-pos (Phi _ _ _ _ pi) = pi
term-end-pos (Rho pi _ _ _ t t') = term-end-pos t'
term-end-pos (Chi pi T t') = term-end-pos t'
term-end-pos (Delta pi oT t) = term-end-pos t
term-end-pos (Sigma pi t) = term-end-pos t
term-end-pos (Theta _ _ _ ls) = lterms-end-pos ls
term-end-pos (Mu _ _ _ _ _ _ pi) = pi
term-end-pos (Mu' _ _ _ _ _ pi) = pi
type-end-pos (Abs pi _ _ _ _ t) = type-end-pos t
type-end-pos (TpLambda _ _ _ _ t) = type-end-pos t
type-end-pos (Iota _ _ _ _ tp) = type-end-pos tp
type-end-pos (Lft pi _ _ _ t) = liftingType-end-pos t
type-end-pos (TpApp t t') = type-end-pos t'
type-end-pos (TpAppt t x) = term-end-pos x
type-end-pos (TpArrow t _ t') = type-end-pos t'
type-end-pos (TpEq pi _ _ pi') = pi'
type-end-pos (TpParens pi _ pi') = pi'
type-end-pos (TpVar pi x) = posinfo-plus-str pi x
type-end-pos (TpHole pi) = posinfo-plus pi 1
type-end-pos (NoSpans t pi) = pi
type-end-pos (TpLet _ _ t) = type-end-pos t
kind-end-pos (KndArrow k k') = kind-end-pos k'
kind-end-pos (KndParens pi k pi') = pi'
kind-end-pos (KndPi pi _ x x₁ k) = kind-end-pos k
kind-end-pos (KndTpArrow x k) = kind-end-pos k
kind-end-pos (KndVar pi x ys) = args-end-pos (posinfo-plus-str pi x) ys
kind-end-pos (Star pi) = posinfo-plus pi 1
tk-end-pos (Tkt T) = type-end-pos T
tk-end-pos (Tkk k) = kind-end-pos k
args-end-pos pi (ArgsCons x ys) = args-end-pos (arg-end-pos x) ys
args-end-pos pi ArgsNil = pi
arg-end-pos (TermArg me t) = term-end-pos t
arg-end-pos (TypeArg T) = type-end-pos T
kvar-end-pos pi v = args-end-pos (posinfo-plus-str pi v)
liftingType-end-pos (LiftArrow l l') = liftingType-end-pos l'
liftingType-end-pos (LiftParens pi l pi') = pi'
liftingType-end-pos (LiftPi x x₁ x₂ l) = liftingType-end-pos l
liftingType-end-pos (LiftStar pi) = posinfo-plus pi 1
liftingType-end-pos (LiftTpArrow x l) = liftingType-end-pos l
lterms-end-pos (LtermsNil pi) = posinfo-plus pi 1 -- must add one for the implicit Beta that we will add at the end
lterms-end-pos (LtermsCons _ _ ls) = lterms-end-pos ls
{- return the end position of the given term if it is there, otherwise
the given posinfo -}
optTerm-end-pos : posinfo → optTerm → posinfo
optTerm-end-pos pi NoTerm = pi
optTerm-end-pos pi (SomeTerm x x₁) = x₁
optTerm-end-pos-beta : posinfo → optTerm → optTerm → posinfo
optTerm-end-pos-beta pi _ (SomeTerm x pi') = pi'
optTerm-end-pos-beta pi (SomeTerm x pi') NoTerm = pi'
optTerm-end-pos-beta pi NoTerm NoTerm = posinfo-plus pi 1
optAs-or : optAs → posinfo → var → posinfo × var
optAs-or NoOptAs pi x = pi , x
optAs-or (SomeOptAs pi x) _ _ = pi , x
tk-arrow-kind : tk → kind → kind
tk-arrow-kind (Tkk k) k' = KndArrow k k'
tk-arrow-kind (Tkt t) k = KndTpArrow t k
TpApp-tk : type → var → tk → type
TpApp-tk tp x (Tkk _) = TpApp tp (TpVar posinfo-gen x)
TpApp-tk tp x (Tkt _) = TpAppt tp (Var posinfo-gen x)
-- expression descriptor
data exprd : Set where
TERM : exprd
TYPE : exprd
KIND : exprd
LIFTINGTYPE : exprd
TK : exprd
ARG : exprd
QUALIF : exprd
⟦_⟧ : exprd → Set
⟦ TERM ⟧ = term
⟦ TYPE ⟧ = type
⟦ KIND ⟧ = kind
⟦ LIFTINGTYPE ⟧ = liftingType
⟦ TK ⟧ = tk
⟦ ARG ⟧ = arg
⟦ QUALIF ⟧ = qualif-info
exprd-name : exprd → string
exprd-name TERM = "term"
exprd-name TYPE = "type"
exprd-name KIND = "kind"
exprd-name LIFTINGTYPE = "lifting type"
exprd-name TK = "type-kind"
exprd-name ARG = "argument"
exprd-name QUALIF = "qualification"
-- checking-sythesizing enum
data checking-mode : Set where
checking : checking-mode
synthesizing : checking-mode
untyped : checking-mode
maybe-to-checking : {A : Set} → maybe A → checking-mode
maybe-to-checking (just _) = checking
maybe-to-checking nothing = synthesizing
is-app : {ed : exprd} → ⟦ ed ⟧ → 𝔹
is-app{TERM} (App _ _ _) = tt
is-app{TERM} (AppTp _ _) = tt
is-app{TYPE} (TpApp _ _) = tt
is-app{TYPE} (TpAppt _ _) = tt
is-app _ = ff
is-term-level-app : {ed : exprd} → ⟦ ed ⟧ → 𝔹
is-term-level-app{TERM} (App _ _ _) = tt
is-term-level-app{TERM} (AppTp _ _) = tt
is-term-level-app _ = ff
is-type-level-app : {ed : exprd} → ⟦ ed ⟧ → 𝔹
is-type-level-app{TYPE} (TpApp _ _) = tt
is-type-level-app{TYPE} (TpAppt _ _) = tt
is-type-level-app _ = ff
is-parens : {ed : exprd} → ⟦ ed ⟧ → 𝔹
is-parens{TERM} (Parens _ _ _) = tt
is-parens{TYPE} (TpParens _ _ _) = tt
is-parens{KIND} (KndParens _ _ _) = tt
is-parens{LIFTINGTYPE} (LiftParens _ _ _) = tt
is-parens _ = ff
is-arrow : {ed : exprd} → ⟦ ed ⟧ → 𝔹
is-arrow{TYPE} (TpArrow _ _ _) = tt
is-arrow{KIND} (KndTpArrow _ _) = tt
is-arrow{KIND} (KndArrow _ _) = tt
is-arrow{LIFTINGTYPE} (LiftArrow _ _) = tt
is-arrow{LIFTINGTYPE} (LiftTpArrow _ _) = tt
is-arrow _ = ff
is-abs : {ed : exprd} → ⟦ ed ⟧ → 𝔹
is-abs{TERM} (Let _ _ _) = tt
is-abs{TERM} (Lam _ _ _ _ _ _) = tt
is-abs{TYPE} (Abs _ _ _ _ _ _) = tt
is-abs{TYPE} (TpLambda _ _ _ _ _) = tt
is-abs{TYPE} (Iota _ _ _ _ _) = tt
is-abs{KIND} (KndPi _ _ _ _ _) = tt
is-abs{LIFTINGTYPE} (LiftPi _ _ _ _) = tt
is-abs _ = ff
is-eq-op : {ed : exprd} → ⟦ ed ⟧ → 𝔹
is-eq-op{TERM} (Sigma _ _) = tt
is-eq-op{TERM} (Epsilon _ _ _ _) = tt
is-eq-op{TERM} (Rho _ _ _ _ _ _) = tt
is-eq-op{TERM} (Chi _ _ _) = tt
is-eq-op{TERM} (Phi _ _ _ _ _) = tt
is-eq-op{TERM} (Delta _ _ _) = tt
is-eq-op _ = ff
is-beta : {ed : exprd} → ⟦ ed ⟧ → 𝔹
is-beta{TERM} (Beta _ _ _) = tt
is-beta _ = ff
is-hole : {ed : exprd} → ⟦ ed ⟧ → 𝔹
is-hole{TERM} (Hole _) = tt
is-hole{TERM} _ = ff
is-hole{TYPE} (TpHole _) = tt
is-hole{TYPE} _ = ff
is-hole{KIND} e = ff
is-hole{LIFTINGTYPE} e = ff
is-hole{TK} (Tkk x) = is-hole x
is-hole{TK} (Tkt x) = is-hole x
is-hole{ARG} (TermArg e? t) = is-hole t
is-hole{ARG} (TypeArg tp) = is-hole tp
is-hole{QUALIF} _ = ff
eq-maybeErased : maybeErased → maybeErased → 𝔹
eq-maybeErased Erased Erased = tt
eq-maybeErased Erased NotErased = ff
eq-maybeErased NotErased Erased = ff
eq-maybeErased NotErased NotErased = tt
eq-checking-mode : (m₁ m₂ : checking-mode) → 𝔹
eq-checking-mode checking checking = tt
eq-checking-mode checking synthesizing = ff
eq-checking-mode checking untyped = ff
eq-checking-mode synthesizing checking = ff
eq-checking-mode synthesizing synthesizing = tt
eq-checking-mode synthesizing untyped = ff
eq-checking-mode untyped checking = ff
eq-checking-mode untyped synthesizing = ff
eq-checking-mode untyped untyped = tt
optPublic-is-public : optPublic → 𝔹
optPublic-is-public IsPublic = tt
optPublic-is-public NotPublic = ff
------------------------------------------------------
-- functions intended for building terms for testing
------------------------------------------------------
mlam : var → term → term
mlam x t = Lam posinfo-gen NotErased posinfo-gen x NoClass t
Mlam : var → term → term
Mlam x t = Lam posinfo-gen Erased posinfo-gen x NoClass t
mappe : term → term → term
mappe t1 t2 = App t1 Erased t2
mapp : term → term → term
mapp t1 t2 = App t1 NotErased t2
mvar : var → term
mvar x = Var posinfo-gen x
mtpvar : var → type
mtpvar x = TpVar posinfo-gen x
mall : var → tk → type → type
mall x tk tp = Abs posinfo-gen All posinfo-gen x tk tp
mtplam : var → tk → type → type
mtplam x tk tp = TpLambda posinfo-gen posinfo-gen x tk tp
{- strip off lambda-abstractions from the term, return the lambda-bound vars and the innermost body.
The intention is to call this with at least the erasure of a term, if not the hnf -- so we do
not check for parens, etc. -}
decompose-lams : term → (𝕃 var) × term
decompose-lams (Lam _ _ _ x _ t) with decompose-lams t
decompose-lams (Lam _ _ _ x _ t) | vs , body = (x :: vs) , body
decompose-lams t = [] , t
{- decompose a term into spine form consisting of a non-applications head and arguments.
The outer arguments will come earlier in the list than the inner ones.
As for decompose-lams, we assume the term is at least erased. -}
decompose-apps : term → term × (𝕃 term)
decompose-apps (App t _ t') with decompose-apps t
decompose-apps (App t _ t') | h , args = h , (t' :: args)
decompose-apps t = t , []
decompose-var-headed : (var → 𝔹) → term → maybe (var × (𝕃 term))
decompose-var-headed is-bound t with decompose-apps t
decompose-var-headed is-bound t | Var _ x , args = if is-bound x then nothing else (just (x , args))
decompose-var-headed is-bound t | _ = nothing
data tty : Set where
tterm : term → tty
ttype : type → tty
decompose-tpapps : type → type × 𝕃 tty
decompose-tpapps (TpApp t t') with decompose-tpapps t
decompose-tpapps (TpApp t t') | h , args = h , (ttype t') :: args
decompose-tpapps (TpAppt t t') with decompose-tpapps t
decompose-tpapps (TpAppt t t') | h , args = h , (tterm t') :: args
decompose-tpapps (TpParens _ t _) = decompose-tpapps t
decompose-tpapps t = t , []
recompose-tpapps : type × 𝕃 tty → type
recompose-tpapps (h , []) = h
recompose-tpapps (h , ((tterm t') :: args)) = TpAppt (recompose-tpapps (h , args)) t'
recompose-tpapps (h , ((ttype t') :: args)) = TpApp (recompose-tpapps (h , args)) t'
recompose-apps : maybeErased → 𝕃 tty → term → term
recompose-apps me [] h = h
recompose-apps me ((tterm t') :: args) h = App (recompose-apps me args h) me t'
recompose-apps me ((ttype t') :: args) h = AppTp (recompose-apps me args h) t'
vars-to-𝕃 : vars → 𝕃 var
vars-to-𝕃 (VarsStart v) = [ v ]
vars-to-𝕃 (VarsNext v vs) = v :: vars-to-𝕃 vs
{- lambda-abstract the input variables in reverse order around the
given term (so closest to the top of the list is bound deepest in
the resulting term). -}
Lam* : 𝕃 var → term → term
Lam* [] t = t
Lam* (x :: xs) t = Lam* xs (Lam posinfo-gen NotErased posinfo-gen x NoClass t)
App* : term → 𝕃 (maybeErased × term) → term
App* t [] = t
App* t ((m , arg) :: args) = App (App* t args) m arg
App*' : term → 𝕃 term → term
App*' t [] = t
App*' t (arg :: args) = App*' (App t NotErased arg) args
TpApp* : type → 𝕃 type → type
TpApp* t [] = t
TpApp* t (arg :: args) = (TpApp (TpApp* t args) arg)
LiftArrow* : 𝕃 liftingType → liftingType → liftingType
LiftArrow* [] l = l
LiftArrow* (l' :: ls) l = LiftArrow* ls (LiftArrow l' l)
is-intro-form : term → 𝔹
is-intro-form (Lam _ _ _ _ _ _) = tt
--is-intro-form (IotaPair _ _ _ _ _) = tt
is-intro-form _ = ff
erase : { ed : exprd } → ⟦ ed ⟧ → ⟦ ed ⟧
erase-term : term → term
erase-type : type → type
erase-kind : kind → kind
erase-lterms : term → lterms → term
erase-tk : tk → tk
-- erase-optType : optType → optType
erase-liftingType : liftingType → liftingType
erase-cases : cases → cases
erase-varargs : varargs → varargs
erase-if : 𝔹 → { ed : exprd } → ⟦ ed ⟧ → ⟦ ed ⟧
erase-if tt = erase
erase-if ff = id
erase-term (Parens _ t _) = erase-term t
erase-term (App t1 Erased t2) = erase-term t1
erase-term (App t1 NotErased t2) = App (erase-term t1) NotErased (erase-term t2)
erase-term (AppTp t tp) = erase-term t
erase-term (Lam _ Erased _ _ _ t) = erase-term t
erase-term (Lam _ NotErased _ x oc t) = Lam posinfo-gen NotErased posinfo-gen x NoClass (erase-term t)
erase-term (Let _ (DefTerm _ x _ t) t') = Let posinfo-gen (DefTerm posinfo-gen x NoType (erase-term t)) (erase-term t')
erase-term (Let _ (DefType _ _ _ _) t) = erase-term t
erase-term (Open _ _ t) = erase-term t
erase-term (Var _ x) = Var posinfo-gen x
erase-term (Beta _ _ NoTerm) = id-term
erase-term (Beta _ _ (SomeTerm t _)) = erase-term t
erase-term (IotaPair _ t1 t2 _ _) = erase-term t1
erase-term (IotaProj t n _) = erase-term t
erase-term (Epsilon _ lr _ t) = erase-term t
erase-term (Sigma _ t) = erase-term t
erase-term (Hole _) = Hole posinfo-gen
erase-term (Phi _ t t₁ t₂ _) = erase-term t₂
erase-term (Rho _ _ _ t _ t') = erase-term t'
erase-term (Chi _ T t') = erase-term t'
erase-term (Delta _ T t) = id-term
erase-term (Theta _ u t ls) = erase-lterms (erase-term t) ls
erase-term (Mu _ x t ot _ c _) = Mu posinfo-gen x (erase-term t) NoType posinfo-gen (erase-cases c) posinfo-gen
erase-term (Mu' _ t ot _ c _) = Mu' posinfo-gen (erase-term t) NoType posinfo-gen (erase-cases c) posinfo-gen
erase-cases NoCase = NoCase
erase-cases (SomeCase _ x varargs t cs) = SomeCase posinfo-gen x (erase-varargs varargs) (erase-term t) (erase-cases cs)
erase-varargs NoVarargs = NoVarargs
erase-varargs (NormalVararg x varargs) = NormalVararg x (erase-varargs varargs)
erase-varargs (ErasedVararg x varargs) = erase-varargs varargs
erase-varargs (TypeVararg x varargs ) = erase-varargs varargs
-- Only erases TERMS in types, leaving the structure of types the same
erase-type (Abs _ b _ v atk tp) = Abs posinfo-gen b posinfo-gen v (erase-tk atk) (erase-type tp)
erase-type (Iota _ _ v otp tp) = Iota posinfo-gen posinfo-gen v (erase-type otp) (erase-type tp)
erase-type (Lft _ _ v t lt) = Lft posinfo-gen posinfo-gen v (erase-term t) (erase-liftingType lt)
erase-type (NoSpans tp _) = NoSpans (erase-type tp) posinfo-gen
erase-type (TpApp tp tp') = TpApp (erase-type tp) (erase-type tp')
erase-type (TpAppt tp t) = TpAppt (erase-type tp) (erase-term t)
erase-type (TpArrow tp at tp') = TpArrow (erase-type tp) at (erase-type tp')
erase-type (TpEq _ t t' _) = TpEq posinfo-gen (erase-term t) (erase-term t') posinfo-gen
erase-type (TpLambda _ _ v atk tp) = TpLambda posinfo-gen posinfo-gen v (erase-tk atk) (erase-type tp)
erase-type (TpParens _ tp _) = erase-type tp
erase-type (TpHole _) = TpHole posinfo-gen
erase-type (TpVar _ x) = TpVar posinfo-gen x
erase-type (TpLet _ (DefTerm _ x _ t) T) = TpLet posinfo-gen (DefTerm posinfo-gen x NoType (erase-term t)) (erase-type T)
erase-type (TpLet _ (DefType _ x k T) T') = TpLet posinfo-gen (DefType posinfo-gen x (erase-kind k) (erase-type T)) (erase-type T')
-- Only erases TERMS in types in kinds, leaving the structure of kinds and types in those kinds the same
erase-kind (KndArrow k k') = KndArrow (erase-kind k) (erase-kind k')
erase-kind (KndParens _ k _) = erase-kind k
erase-kind (KndPi _ _ v atk k) = KndPi posinfo-gen posinfo-gen v (erase-tk atk) (erase-kind k)
erase-kind (KndTpArrow tp k) = KndTpArrow (erase-type tp) (erase-kind k)
erase-kind (KndVar _ x ps) = KndVar posinfo-gen x ps
erase-kind (Star _) = Star posinfo-gen
erase{TERM} t = erase-term t
erase{TYPE} tp = erase-type tp
erase{KIND} k = erase-kind k
erase{LIFTINGTYPE} lt = erase-liftingType lt
erase{TK} atk = erase-tk atk
erase{ARG} a = a
erase{QUALIF} q = q
erase-tk (Tkt tp) = Tkt (erase-type tp)
erase-tk (Tkk k) = Tkk (erase-kind k)
erase-liftingType (LiftArrow lt lt') = LiftArrow (erase-liftingType lt) (erase-liftingType lt')
erase-liftingType (LiftParens _ lt _) = erase-liftingType lt
erase-liftingType (LiftPi _ v tp lt) = LiftPi posinfo-gen v (erase-type tp) (erase-liftingType lt)
erase-liftingType (LiftTpArrow tp lt) = LiftTpArrow (erase-type tp) (erase-liftingType lt)
erase-liftingType lt = lt
erase-lterms t (LtermsNil _) = t
erase-lterms t (LtermsCons Erased t' ls) = erase-lterms t ls
erase-lterms t (LtermsCons NotErased t' ls) = erase-lterms (App t NotErased (erase-term t')) ls
lterms-to-term : theta → term → lterms → term
lterms-to-term AbstractEq t (LtermsNil _) = App t Erased (Beta posinfo-gen NoTerm NoTerm)
lterms-to-term _ t (LtermsNil _) = t
lterms-to-term u t (LtermsCons e t' ls) = lterms-to-term u (App t e t') ls
imps-to-cmds : imports → cmds
imps-to-cmds ImportsStart = CmdsStart
imps-to-cmds (ImportsNext i is) = CmdsNext (ImportCmd i) (imps-to-cmds is)
-- TODO handle qualif & module args
get-imports : start → 𝕃 string
get-imports (File _ is _ _ mn _ cs _) = imports-to-include is ++ get-imports-cmds cs
where import-to-include : imprt → string
import-to-include (Import _ _ _ x oa _ _) = x
imports-to-include : imports → 𝕃 string
imports-to-include ImportsStart = []
imports-to-include (ImportsNext x is) = import-to-include x :: imports-to-include is
singleton-if-include : cmd → 𝕃 string
singleton-if-include (ImportCmd imp) = [ import-to-include imp ]
singleton-if-include _ = []
get-imports-cmds : cmds → 𝕃 string
get-imports-cmds (CmdsNext c cs) = singleton-if-include c ++ get-imports-cmds cs
get-imports-cmds CmdsStart = []
data language-level : Set where
ll-term : language-level
ll-type : language-level
ll-kind : language-level
ll-to-string : language-level → string
ll-to-string ll-term = "term"
ll-to-string ll-type = "type"
ll-to-string ll-kind = "kind"
is-rho-plus : optPlus → 𝔹
is-rho-plus RhoPlus = tt
is-rho-plus _ = ff
split-var-h : 𝕃 char → 𝕃 char × 𝕃 char
split-var-h [] = [] , []
split-var-h (qual-global-chr :: xs) = [] , xs
split-var-h (x :: xs) with split-var-h xs
... | xs' , ys = (x :: xs') , ys
split-var : var → var × var
split-var v with split-var-h (reverse (string-to-𝕃char v))
... | xs , ys = 𝕃char-to-string (reverse ys) , 𝕃char-to-string (reverse xs)
var-suffix : var → maybe var
var-suffix v with split-var v
... | "" , _ = nothing
... | _ , sfx = just sfx
-- unique qualif domain prefixes
qual-pfxs : qualif → 𝕃 var
qual-pfxs q = uniq (prefixes (trie-strings q))
where
uniq : 𝕃 var → 𝕃 var
uniq vs = stringset-strings (stringset-insert* empty-stringset vs)
prefixes : 𝕃 var → 𝕃 var
prefixes [] = []
prefixes (v :: vs) with split-var v
... | "" , sfx = vs
... | pfx , sfx = pfx :: prefixes vs
unqual-prefix : qualif → 𝕃 var → var → var → var
unqual-prefix q [] sfx v = v
unqual-prefix q (pfx :: pfxs) sfx v
with trie-lookup q (pfx # sfx)
... | just (v' , _) = if v =string v' then pfx # sfx else v
... | nothing = v
unqual-bare : qualif → var → var → var
unqual-bare q sfx v with trie-lookup q sfx
... | just (v' , _) = if v =string v' then sfx else v
... | nothing = v
unqual-local : var → var
unqual-local v = f' (string-to-𝕃char v) where
f : 𝕃 char → maybe (𝕃 char)
f [] = nothing
f ('@' :: t) = f t maybe-or just t
f (h :: t) = f t
f' : 𝕃 char → string
f' (meta-var-pfx :: t) = maybe-else' (f t) v (𝕃char-to-string ∘ _::_ meta-var-pfx)
f' t = maybe-else' (f t) v 𝕃char-to-string
unqual-all : qualif → var → string
unqual-all q v with var-suffix v
... | nothing = v
... | just sfx = unqual-bare q sfx (unqual-prefix q (qual-pfxs q) sfx v)
erased-params : params → 𝕃 string
erased-params (ParamsCons (Decl _ _ Erased x (Tkt _) _) ps) with var-suffix x
... | nothing = x :: erased-params ps
... | just x' = x' :: erased-params ps
erased-params (ParamsCons p ps) = erased-params ps
erased-params ParamsNil = []
lam-expand-term : params → term → term
lam-expand-term (ParamsCons (Decl _ _ me x tk _) ps) t =
Lam posinfo-gen (if tk-is-type tk then me else Erased) posinfo-gen x (SomeClass tk) (lam-expand-term ps t)
lam-expand-term ParamsNil t = t
lam-expand-type : params → type → type
lam-expand-type (ParamsCons (Decl _ _ me x tk _) ps) t =
TpLambda posinfo-gen posinfo-gen x tk (lam-expand-type ps t)
lam-expand-type ParamsNil t = t
abs-expand-type : params → type → type
abs-expand-type (ParamsCons (Decl _ _ me x tk _) ps) t =
Abs posinfo-gen (if tk-is-type tk then me else All) posinfo-gen x tk (abs-expand-type ps t)
abs-expand-type ParamsNil t = t
abs-expand-type' : params → type → type
abs-expand-type' (ParamsCons (Decl _ _ me x tk _) ps) t =
Abs posinfo-gen (if tk-is-type tk then me else All) posinfo-gen x tk (abs-expand-type' ps t)
abs-expand-type' ParamsNil t = t
abs-expand-kind : params → kind → kind
abs-expand-kind (ParamsCons (Decl _ _ me x tk _) ps) k =
KndPi posinfo-gen posinfo-gen x tk (abs-expand-kind ps k)
abs-expand-kind ParamsNil k = k
args-length : args → ℕ
args-length (ArgsCons p ps) = suc (args-length ps)
args-length ArgsNil = 0
erased-args-length : args → ℕ
erased-args-length (ArgsCons (TermArg NotErased _) ps) = suc (erased-args-length ps)
erased-args-length (ArgsCons (TermArg Erased _) ps) = erased-args-length ps
erased-args-length (ArgsCons (TypeArg _) ps) = erased-args-length ps
erased-args-length ArgsNil = 0
me-args-length : maybeErased → args → ℕ
me-args-length Erased = erased-args-length
me-args-length NotErased = args-length
spineApp : Set
spineApp = qvar × 𝕃 arg
term-to-spapp : term → maybe spineApp
term-to-spapp (App t me t') = term-to-spapp t ≫=maybe
(λ { (v , as) → just (v , TermArg me t' :: as) })
term-to-spapp (AppTp t T) = term-to-spapp t ≫=maybe
(λ { (v , as) → just (v , TypeArg T :: as) })
term-to-spapp (Var _ v) = just (v , [])
term-to-spapp _ = nothing
type-to-spapp : type → maybe spineApp
type-to-spapp (TpApp T T') = type-to-spapp T ≫=maybe
(λ { (v , as) → just (v , TypeArg T' :: as) })
type-to-spapp (TpAppt T t) = type-to-spapp T ≫=maybe
(λ { (v , as) → just (v , TermArg NotErased t :: as) })
type-to-spapp (TpVar _ v) = just (v , [])
type-to-spapp _ = nothing
spapp-term : spineApp → term
spapp-term (v , []) = Var posinfo-gen v
spapp-term (v , TermArg me t :: as) = App (spapp-term (v , as)) me t
spapp-term (v , TypeArg T :: as) = AppTp (spapp-term (v , as)) T
spapp-type : spineApp → type
spapp-type (v , []) = TpVar posinfo-gen v
spapp-type (v , TermArg me t :: as) = TpAppt (spapp-type (v , as)) t
spapp-type (v , TypeArg T :: as) = TpApp (spapp-type (v , as)) T
num-gt : num → ℕ → 𝕃 string
num-gt n n' = maybe-else [] (λ n'' → if n'' > n' then [ n ] else []) (string-to-ℕ n)
nums-gt : nums → ℕ → 𝕃 string
nums-gt (NumsStart n) n' = num-gt n n'
nums-gt (NumsNext n ns) n' =
maybe-else [] (λ n'' → if n'' > n' || iszero n'' then [ n ] else []) (string-to-ℕ n)
++ nums-gt ns n'
nums-to-stringset : nums → stringset × 𝕃 string {- Repeated numbers -}
nums-to-stringset (NumsStart n) = stringset-insert empty-stringset n , []
nums-to-stringset (NumsNext n ns) with nums-to-stringset ns
...| ss , rs = if stringset-contains ss n
then ss , n :: rs
else stringset-insert ss n , rs
optNums-to-stringset : optNums → maybe stringset × (ℕ → maybe string)
optNums-to-stringset NoNums = nothing , λ _ → nothing
optNums-to-stringset (SomeNums ns) with nums-to-stringset ns
...| ss , [] = just ss , λ n → case nums-gt ns n of λ where
[] → nothing
ns-g → just ("Occurrences not found: " ^ 𝕃-to-string id ", " ns-g ^ " (total occurrences: " ^ ℕ-to-string n ^ ")")
...| ss , rs = just ss , λ n →
just ("The list of occurrences contains the following repeats: " ^ 𝕃-to-string id ", " rs)
------------------------------------------------------
-- any delta contradiction → boolean contradiction
------------------------------------------------------
nlam : ℕ → term → term
nlam 0 t = t
nlam (suc n) t = mlam ignored-var (nlam n t)
delta-contra-app : ℕ → (ℕ → term) → term
delta-contra-app 0 nt = mvar "x"
delta-contra-app (suc n) nt = mapp (delta-contra-app n nt) (nt n)
delta-contrahh : ℕ → trie ℕ → trie ℕ → var → var → 𝕃 term → 𝕃 term → maybe term
delta-contrahh n ls rs x1 x2 as1 as2 with trie-lookup ls x1 | trie-lookup rs x2
...| just n1 | just n2 =
let t1 = nlam (length as1) (mlam "x" (mlam "y" (mvar "x")))
t2 = nlam (length as2) (mlam "x" (mlam "y" (mvar "y"))) in
if n1 =ℕ n2
then nothing
else just (mlam "x" (delta-contra-app n
(λ n → if n =ℕ n1 then t1 else if n =ℕ n2 then t2 else id-term)))
...| _ | _ = nothing
{-# TERMINATING #-}
delta-contrah : ℕ → trie ℕ → trie ℕ → term → term → maybe term
delta-contrah n ls rs (Lam _ _ _ x1 _ t1) (Lam _ _ _ x2 _ t2) =
delta-contrah (suc n) (trie-insert ls x1 n) (trie-insert rs x2 n) t1 t2
delta-contrah n ls rs (Lam _ _ _ x1 _ t1) t2 =
delta-contrah (suc n) (trie-insert ls x1 n) (trie-insert rs x1 n) t1 (mapp t2 (mvar x1))
delta-contrah n ls rs t1 (Lam _ _ _ x2 _ t2) =
delta-contrah (suc n) (trie-insert ls x2 n) (trie-insert rs x2 n) (mapp t1 (mvar x2)) t2
delta-contrah n ls rs t1 t2 with decompose-apps t1 | decompose-apps t2
...| Var _ x1 , as1 | Var _ x2 , as2 = delta-contrahh n ls rs x1 x2 as1 as2
...| _ | _ = nothing
-- For terms t1 and t2, given that check-beta-inequiv t1 t2 ≡ tt,
-- delta-contra produces a function f such that f t1 ≡ tt and f t2 ≡ ff
-- If it returns nothing, no contradiction could be found
delta-contra : term → term → maybe term
delta-contra = delta-contrah 0 empty-trie empty-trie
-- postulate: check-beta-inequiv t1 t2 ≡ isJust (delta-contra t1 t2)
check-beta-inequiv : term → term → 𝔹
check-beta-inequiv t1 t2 = isJust (delta-contra t1 t2)
tk-map : tk → (type → type) → (kind → kind) → tk
tk-map (Tkt T) fₜ fₖ = Tkt $ fₜ T
tk-map (Tkk k) fₜ fₖ = Tkk $ fₖ k
tk-map2 : tk → (∀ {ed} → ⟦ ed ⟧ → ⟦ ed ⟧) → tk
tk-map2 atk f = tk-map atk f f
optTerm-map : optTerm → (term → term) → optTerm
optTerm-map NoTerm f = NoTerm
optTerm-map (SomeTerm t pi) f = SomeTerm (f t) pi
optType-map : optType → (type → type) → optType
optType-map NoType f = NoType
optType-map (SomeType T) f = SomeType $ f T
optGuide-map : optGuide → (var → type → type) → optGuide
optGuide-map NoGuide f = NoGuide
optGuide-map (Guide pi x T) f = Guide pi x $ f x T
optClass-map : optClass → (tk → tk) → optClass
optClass-map NoClass f = NoClass
optClass-map (SomeClass atk) f = SomeClass $ f atk
|
C Copyright(C) 1999-2020 National Technology & Engineering Solutions
C of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
C NTESS, the U.S. Government retains certain rights in this software.
C
C See packages/seacas/LICENSE for details
C=======================================================================
SUBROUTINE ROTZM (RDMESH, NNPSUR, NPSURF, XN, YN, ZN,
& ROTMSH, ROTMAT, ROTCEN, ZMMESH, ZMCEN, *)
C=======================================================================
C --*** ROTZM *** (MESH) Find the object center within zoom limits
C -- Written by Amy Gilkey - revised 09/09/87
C --
C --ROTZM averages the coordinates of all surface nodes within the zoom
C --limits to find the center of the object visible within the zoom
C --window.
C --
C --Parameters:
C -- RDMESH - IN - the zoom mesh limits (may not be square)
C -- NNPSUR - IN - the number of surface nodes
C -- NPSURF - IN - the node numbers of the surface nodes
C -- XN, YN, ZN - IN - the nodal coordinates (unrotated)
C -- ROTMSH - IN - true iff the coordinates need to be rotated
C -- ROTMAT - IN - the rotation matrix
C -- ROTCEN - IN - the rotation center
C -- ZMMESH - OUT - the zoom mesh limits (may not be square)
C -- ZMCEN - OUT - the mesh center for the rotation
C -- * - return statement if no nodes within window; message is printed
PARAMETER (KLFT=1, KRGT=2, KBOT=3, KTOP=4, KNEA=5, KFAR=6)
REAL RDMESH(KTOP)
INTEGER NPSURF(*)
REAL XN(*), YN(*), ZN(*)
LOGICAL ROTMSH
REAL ROTMAT(3,3), ROTCEN(3)
REAL ZMMESH(KTOP)
REAL ZMCEN(3)
NIN = 0
XTOT = 0.0
YTOT = 0.0
ZTOT = 0.0
DO 100 IX = 1, NNPSUR
INP = NPSURF(IX)
IF (ROTMSH) THEN
CALL BL_ROTATE (1, 1, ROTMAT, ROTCEN,
& XN(INP), YN(INP), ZN(INP), X, Y, Z)
ELSE
X = XN(INP)
Y = YN(INP)
Z = ZN(INP)
END IF
IF ((X .GE. RDMESH(KLFT)) .AND. (X .LE. RDMESH(KRGT)) .AND.
& (Y .GE. RDMESH(KBOT)) .AND. (Y .LE. RDMESH(KTOP))) THEN
NIN = NIN + 1
XTOT = XTOT + X
YTOT = YTOT + Y
ZTOT = ZTOT + Z
END IF
100 CONTINUE
IF (NIN .LE. 0) THEN
CALL PRTERR ('CMDERR',
& 'No nodes within specified zoom window')
GOTO 110
END IF
XTOT = XTOT / NIN
YTOT = YTOT / NIN
ZTOT = ZTOT / NIN
CALL UNROT (1, 1, ROTMAT, ROTCEN,
& XTOT, YTOT, ZTOT, XCEN, YCEN, ZCEN)
XDIF = ROTCEN(1) - XCEN
YDIF = ROTCEN(2) - YCEN
ZMMESH(KLFT) = RDMESH(KLFT) + XDIF
ZMMESH(KRGT) = RDMESH(KRGT) + XDIF
ZMMESH(KBOT) = RDMESH(KBOT) + YDIF
ZMMESH(KTOP) = RDMESH(KTOP) + YDIF
ZMCEN(1) = XCEN
ZMCEN(2) = YCEN
ZMCEN(3) = ZCEN
RETURN
110 CONTINUE
RETURN 1
END
|
import numpy as np
import cv2
import os
from tqdm import tqdm
import random
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.patches as patches
import pickle
from glob import glob
import imgaug as ia
from imgaug import augmenters as iaa
from shapely.geometry import Polygon
cardW=57
cardH=87
cornerXmin=2
cornerXmax=10.5
cornerYmin=2.5
cornerYmax=23
# We convert the measures from mm to pixels: multiply by an arbitrary factor 'zoom'
# You shouldn't need to change this
zoom=4
cardW*=zoom
cardH*=zoom
cornerXmin=int(cornerXmin*zoom)
cornerXmax=int(cornerXmax*zoom)
cornerYmin=int(cornerYmin*zoom)
cornerYmax=int(cornerYmax*zoom)
def display_img(img, polygons=[], channels="bgr", size=9):
"""
Function to display an inline image, and draw optional polygons (bounding boxes, convex hulls) on it.
Use the param 'channels' to specify the order of the channels ("bgr" for an image coming from OpenCV world)
"""
if not isinstance(polygons,list):
polygons=[polygons]
if channels=="bgr": # bgr (cv2 image)
nb_channels=img.shape[2]
if nb_channels==4:
img=cv2.cvtColor(img,cv2.COLOR_BGRA2RGBA)
else:
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
fig,ax=plt.subplots(figsize=(size,size))
ax.set_facecolor((0,0,0))
ax.imshow(img)
for polygon in polygons:
# An polygon has either shape (n,2),
# either (n,1,2) if it is a cv2 contour (like convex hull).
# In the latter case, reshape in (n,2)
if len(polygon.shape)==3:
polygon=polygon.reshape(-1,2)
patch=patches.Polygon(polygon,linewidth=1,edgecolor='g',facecolor='none')
ax.add_patch(patch)
def give_me_filename(dirname, suffixes, prefix=""):
"""
Function that returns a filename or a list of filenames in directory 'dirname'
that does not exist yet. If 'suffixes' is a list, one filename per suffix in 'suffixes':
filename = dirname + "/" + prefix + random number + "." + suffix
Same random number for all the file name
Ex:
> give_me_filename("dir","jpg", prefix="prefix")
'dir/prefix408290659.jpg'
> give_me_filename("dir",["jpg","xml"])
['dir/877739594.jpg', 'dir/877739594.xml']
"""
if not isinstance(suffixes, list):
suffixes = [suffixes]
suffixes = [p if p[0] == '.' else '.' + p for p in suffixes]
while True:
bname = "%09d" % random.randint(0, 999999999)
fnames = []
for suffix in suffixes:
fname = os.path.join(dirname, prefix + bname + suffix)
if not os.path.isfile(fname):
fnames.append(fname)
if len(fnames) == len(suffixes): break
if len(fnames) == 1:
return fnames[0]
else:
return fnames
def generate_pickle():
dtd_dir = "/home/marc/playing-card-detection/dtd/images"
bg_images = []
for subdir in glob(dtd_dir + "/*"):
print("working on subdir: ", subdir)
for f in glob(subdir + "/*.jpg"):
bg_images.append(mpimg.imread(f))
# x = 1
file = open(backgrounds_pck_fn, 'wb')
pickle.dump(bg_images, file)
file.close()
print("Nb of images loaded :", len(bg_images))
print("Saved in :", backgrounds_pck_fn)
data_dir="data" # Directory that will contain all kinds of data (the data we download and the data we generate)
if not os.path.isdir(data_dir):
os.makedirs(data_dir)
card_suits=['s','h','d','c']
card_values=['A','K','Q','J','10','9','8','7','6','5','4','3','2']
# Pickle file containing the background images from the DTD
backgrounds_pck_fn=data_dir+"/backgrounds.pck"
# Pickle file containing the card images
cards_pck_fn=data_dir+"/cards.pck"
# imgW,imgH: dimensions of the generated dataset images
imgW=720
imgH=720
refCard=np.array([[0,0],[cardW,0],[cardW,cardH],[0,cardH]],dtype=np.float32)
refCardRot=np.array([[cardW,0],[cardW,cardH],[0,cardH],[0,0]],dtype=np.float32)
refCornerHL=np.array([[cornerXmin,cornerYmin],[cornerXmax,cornerYmin],[cornerXmax,cornerYmax],[cornerXmin,cornerYmax]],dtype=np.float32)
refCornerLR=np.array([[cardW-cornerXmax,cardH-cornerYmax],[cardW-cornerXmin,cardH-cornerYmax],[cardW-cornerXmin,cardH-cornerYmin],[cardW-cornerXmax,cardH-cornerYmin]],dtype=np.float32)
refCorners=np.array([refCornerHL,refCornerLR])
class Backgrounds():
def __init__(self, backgrounds_pck_fn=backgrounds_pck_fn):
self._images = pickle.load(open(backgrounds_pck_fn, 'rb'))
self._nb_images = len(self._images)
print("Nb of images loaded :", self._nb_images)
def get_random(self, display=False):
bg = self._images[random.randint(0, self._nb_images - 1)]
if display: plt.imshow(bg)
return bg
# backgrounds = Backgrounds()
generate_pickle() |
module Metalogic.Classical.Propositional.ProofSystem {ℓₚ} (Proposition : Set(ℓₚ)) where
import Lvl
open import Data hiding (empty)
import Data.List
open Data.List using (List ; ∅ ; _⊰_ ; _++_ ; [_ ; _])
open Data.List.Notation
import Data.List.Relation.Membership
import Data.List.Relation.Membership.Proofs
open import Metalogic.Classical.Propositional.Syntax(Proposition)
open import Functional
open Data.List.Relation.Membership{ℓₚ} {Formula}
open Data.List.Relation.Membership.Proofs{ℓₚ} {Formula}
module Meta where
data _⊢_ : List(Formula) → Formula → Set(ℓₚ) where -- TODO: Reduce the number of rules
[⊤]-intro : ∀{Γ} → (Γ ⊢ ⊤)
[⊥]-intro : ∀{Γ}{φ} → (φ ∈ Γ) → ((¬ φ) ∈ Γ) → (Γ ⊢ ⊥)
[⊥]-elim : ∀{Γ}{φ} → (⊥ ∈ Γ) → (Γ ⊢ φ)
[¬]-intro : ∀{Γ}{φ} → ((φ ∈ Γ) → (Γ ⊢ ⊥)) → (Γ ⊢ (¬ φ))
[¬]-elim : ∀{Γ}{φ} → (((¬ φ) ∈ Γ) → (Γ ⊢ ⊥)) → (Γ ⊢ φ)
[∧]-intro : ∀{Γ}{φ₁ φ₂} → (φ₁ ∈ Γ) → (φ₂ ∈ Γ) → (Γ ⊢ (φ₁ ∧ φ₂))
[∧]-elimₗ : ∀{Γ}{φ₁ φ₂} → ((φ₁ ∧ φ₂) ∈ Γ) → (Γ ⊢ φ₁)
[∧]-elimᵣ : ∀{Γ}{φ₁ φ₂} → ((φ₁ ∧ φ₂) ∈ Γ) → (Γ ⊢ φ₂)
[∨]-introₗ : ∀{Γ}{φ₁ φ₂} → (φ₁ ∈ Γ) → (Γ ⊢ (φ₁ ∨ φ₂))
[∨]-introᵣ : ∀{Γ}{φ₁ φ₂} → (φ₂ ∈ Γ) → (Γ ⊢ (φ₁ ∨ φ₂))
[∨]-elim : ∀{Γ}{φ₁ φ₂ φ₃} → ((φ₁ ∈ Γ) → (Γ ⊢ φ₃)) → ((φ₂ ∈ Γ) → (Γ ⊢ φ₃)) → ((φ₁ ∨ φ₂) ∈ Γ) → (Γ ⊢ φ₃)
[⇒]-intro : ∀{Γ}{φ₁ φ₂} → ((φ₁ ∈ Γ) → (Γ ⊢ φ₂)) → (Γ ⊢ (φ₁ ⇒ φ₂))
[⇒]-elim : ∀{Γ}{φ₁ φ₂} → ((φ₁ ⇒ φ₂) ∈ Γ) → (φ₁ ∈ Γ) → (Γ ⊢ φ₂)
[¬¬]-elim : ∀{Γ}{φ} → ((¬ ¬ φ) ∈ Γ) → (Γ ⊢ φ)
[¬¬]-elim{Γ}{φ} ([¬¬φ]-in) =
([¬]-elim{Γ}{φ} ([¬φ]-in ↦
([⊥]-intro{Γ}{¬ φ}
([¬φ]-in)
([¬¬φ]-in)
)
))
_⊬_ : List(Formula) → Formula → Set(ℓₚ)
_⊬_ Γ φ = (_⊢_ Γ φ) → Empty{ℓₚ}
-- Consistency
Inconsistent : List(Formula) → Set(ℓₚ)
Inconsistent Γ = (Γ ⊢ ⊥)
Consistent : List(Formula) → Set(ℓₚ)
Consistent Γ = (Γ ⊬ ⊥)
module TruthTables where
open Meta
-- Natural deduction proof trees.
-- This is a proof system that should reflect the semantic truth of formulas.
module NaturalDeduction where
-- A `Tree` is associated with a formula.
-- [Proposition without assumptions (Axiom)]
-- Represented by the type `Tree(φ)`.
-- It means that a tree with the formula φ at the bottom exists (is constructable).
-- This represents that the formula φ is provable in the natural deduction proof system.
-- [Proposition with an assumption]
-- Represented by the type `Tree(φ₁) → Tree(φ₂)`.
-- It means that a tree with φ₁ as a leaf and φ₂ at the bottom exists (is constructable).
-- This represents that the formula φ₂ is provable if one can assume the formula φ₁.
-- The constructors of `Tree` are all the possible ways to construct a natural deduction proof tree.
-- If a tree with a certain formula cannot be constructed, then it means that the formula is not provable.
{-# NO_POSITIVITY_CHECK #-} -- TODO: Could this be a problem? Maybe not? Classical logic is supposed to be consistent, but maybe that does not have anything to do with this?
data Tree : Formula → Set(ℓₚ) where
[⊤]-intro : Tree(⊤)
[⊥]-intro : ∀{φ} → Tree(φ) → Tree(¬ φ) → Tree(⊥)
[¬]-intro : ∀{φ} → (Tree(φ) → Tree(⊥)) → Tree(¬ φ)
[¬]-elim : ∀{φ} → (Tree(¬ φ) → Tree(⊥)) → Tree(φ)
[∧]-intro : ∀{φ₁ φ₂} → Tree(φ₁) → Tree(φ₂) → Tree(φ₁ ∧ φ₂)
[∧]-elimₗ : ∀{φ₁ φ₂} → Tree(φ₁ ∧ φ₂) → Tree(φ₁)
[∧]-elimᵣ : ∀{φ₁ φ₂} → Tree(φ₁ ∧ φ₂) → Tree(φ₂)
[∨]-introₗ : ∀{φ₁ φ₂} → Tree(φ₁) → Tree(φ₁ ∨ φ₂)
[∨]-introᵣ : ∀{φ₁ φ₂} → Tree(φ₂) → Tree(φ₁ ∨ φ₂)
[∨]-elim : ∀{φ₁ φ₂ φ₃} → (Tree(φ₁) → Tree(φ₃)) → (Tree(φ₂) → Tree(φ₃)) → Tree(φ₁ ∨ φ₂) → Tree(φ₃)
[⇒]-intro : ∀{φ₁ φ₂} → (Tree(φ₁) → Tree(φ₂)) → Tree(φ₁ ⇒ φ₂)
[⇒]-elim : ∀{φ₁ φ₂} → Tree(φ₁ ⇒ φ₂) → Tree(φ₁) → Tree(φ₂)
-- Double negated proposition is positive.
[¬¬]-elim : ∀{φ} → Tree(¬ (¬ φ)) → Tree(φ)
[¬¬]-elim nna = [¬]-elim(na ↦ [⊥]-intro na nna)
-- A contradiction can derive every formula.
[⊥]-elim : ∀{φ} → Tree(⊥) → Tree(φ)
[⊥]-elim bottom = [¬]-elim(_ ↦ bottom)
-- List of natural deduction proof trees.
-- A `Trees` is associated with a list of formulas.
-- If all formulas in the list can be constructed, then all the formulas in the list are provable.
-- This is used to express (⊢) using the usual conventions in formal logic.
-- Trees(Γ) is the statement that all formulas in Γ have proof trees.
Trees : List(Formula) → Set(ℓₚ)
Trees(Γ) = (∀{γ} → (γ ∈ Γ) → Tree(γ))
module Trees where
tree : ∀{Γ}{φ} → Trees(Γ) → (φ ∈ Γ) → Tree(φ)
tree f(x) = f(x)
empty : Trees(∅)
empty ()
singleton : ∀{φ} → Tree(φ) → Trees([ φ ])
singleton (φ-tree) (use) = φ-tree
singleton (φ-tree) (skip ())
-- TODO: This could possibly be generalized to: ∀{Γ₁ Γ₂}{F : T → Set} → (∀{a} → (a ∈ Γ₁) → (a ∈ Γ₂)) → ((∀{γ} → (γ ∈ Γ₂) → F(γ)) → (∀{γ} → (γ ∈ Γ₁) → F(γ)))
from-[∈] : ∀{Γ₁ Γ₂} → (∀{a} → (a ∈ Γ₁) → (a ∈ Γ₂)) → (Trees(Γ₂) → Trees(Γ₁))
from-[∈] (f) (Γ₂-trees) {γ} = liftᵣ (f{γ}) (Γ₂-trees)
push : ∀{Γ}{φ} → Tree(φ) → Trees(Γ) → Trees(φ ⊰ Γ)
push (φ-tree) (Γ-tree) (use) = φ-tree
push (φ-tree) (Γ-tree) (skip membership) = Γ-tree (membership)
pop : ∀{Γ}{φ} → Trees(φ ⊰ Γ) → Trees(Γ)
pop = from-[∈] (skip)
first : ∀{Γ}{φ} → Trees(φ ⊰ Γ) → Tree(φ)
first(f) = f(use)
-- TODO: Could be removed because liftᵣ is easier to use. ALthough a note/tip should be written for these purposes.
-- formula-weaken : ∀{ℓ}{T : Set(ℓ)}{Γ₁ Γ₂} → (Trees(Γ₁) → Trees(Γ₂)) → (Trees(Γ₂) → T) → (Trees(Γ₁) → T)
-- formula-weaken = liftᵣ
[++]-commute : ∀{Γ₁ Γ₂} → Trees(Γ₁ ++ Γ₂) → Trees(Γ₂ ++ Γ₁)
[++]-commute {Γ₁}{Γ₂} (trees) = trees ∘ ([∈][++]-commute{_}{Γ₂}{Γ₁})
[++]-left : ∀{Γ₁ Γ₂} → Trees(Γ₁ ++ Γ₂) → Trees(Γ₁)
[++]-left {Γ₁}{Γ₂} (trees) ([∈]-[Γ₁]) = trees ([∈][++]-expandᵣ {_}{Γ₁}{Γ₂} [∈]-[Γ₁])
[++]-right : ∀{Γ₁ Γ₂} → Trees(Γ₁ ++ Γ₂) → Trees(Γ₂)
[++]-right {Γ₁}{Γ₂} (trees) ([∈]-[Γ₂]) = trees ([∈][++]-expandₗ {_}{Γ₁}{Γ₂} [∈]-[Γ₂])
[++]-deduplicate : ∀{Γ} → Trees(Γ ++ Γ) → Trees(Γ)
[++]-deduplicate {Γ} (trees) {γ} = liftᵣ([∈][++]-expandₗ {γ}{Γ}{Γ})(trees{γ})
[⊰]-reorderₗ : ∀{Γ₁ Γ₂}{φ} → Trees(Γ₁ ++ (φ ⊰ Γ₂)) → Trees(φ ⊰ (Γ₁ ++ Γ₂))
[⊰]-reorderₗ {Γ₁}{Γ₂}{φ} (Γ₁φΓ₂-trees) = push (φ-tree) ([++]-commute{Γ₂}{Γ₁} Γ₂Γ₁-trees) where
φΓ₂Γ₁-trees : Trees(φ ⊰ (Γ₂ ++ Γ₁))
φΓ₂Γ₁-trees = [++]-commute{Γ₁}{φ ⊰ Γ₂} (Γ₁φΓ₂-trees)
φ-tree : Tree(φ)
φ-tree = first{Γ₂ ++ Γ₁}{φ} (φΓ₂Γ₁-trees)
Γ₂Γ₁-trees : Trees(Γ₂ ++ Γ₁)
Γ₂Γ₁-trees = pop{Γ₂ ++ Γ₁}{φ} (φΓ₂Γ₁-trees)
-- Γ₁ ++ (φ ⊰ Γ₂) //assumption
-- (φ ⊰ Γ₂) ++ Γ₁ //Trees.[++]-commute
-- φ ⊰ (Γ₂ ++ Γ₁) //Definition: (++)
-- φ ⊰ (Γ₁ ++ Γ₂) //Trees.[++]-commute
push-many : ∀{Γ₁ Γ₂} → Trees(Γ₁) → Trees(Γ₂) → Trees(Γ₁ ++ Γ₂)
push-many{∅} {Γ₂} ([∅]-trees) ([Γ₂]-trees) = [Γ₂]-trees
push-many{φ ⊰ Γ₁}{Γ₂} ([φ⊰Γ₁]-trees) ([Γ₂]-trees) = [⊰]-reorderₗ{Γ₁}{Γ₂}{φ} (push-many{Γ₁}{φ ⊰ Γ₂} (pop [φ⊰Γ₁]-trees) (push (first [φ⊰Γ₁]-trees) [Γ₂]-trees))
-- Derivability
-- Proof of: If there exists a tree for every formula in Γ, then there exists a tree for the formula φ.
data _⊢_ (Γ : List(Formula)) (φ : Formula) : Set(ℓₚ) where
[⊢]-construct : (Trees(Γ) → Tree(φ)) → (Γ ⊢ φ)
module Theorems where
[⊢]-from-trees : ∀{Γ₁ Γ₂}{φ} → (Trees(Γ₂) → Trees(Γ₁)) → (Γ₁ ⊢ φ) → (Γ₂ ⊢ φ)
[⊢]-from-trees (trees-fn) ([⊢]-construct (Γ₁⊢φ)) = [⊢]-construct ((Γ₁⊢φ) ∘ (trees-fn))
[⊢]-formula-weaken : ∀{Γ}{φ₁ φ₂} → (Γ ⊢ φ₁) → ((φ₂ ⊰ Γ) ⊢ φ₁)
[⊢]-formula-weaken {_}{_}{φ₂} = [⊢]-from-trees (Trees.pop {_}{φ₂})
[⊢]-weakenₗ : ∀{Γ₂}{φ} → (Γ₂ ⊢ φ) → ∀{Γ₁} → ((Γ₁ ++ Γ₂) ⊢ φ)
[⊢]-weakenₗ {_} {_} (Γ₂⊢φ) {∅} = (Γ₂⊢φ)
[⊢]-weakenₗ {Γ₂}{φ} (Γ₂⊢φ) {φ₂ ⊰ Γ₁} = [⊢]-formula-weaken {Γ₁ ++ Γ₂} ([⊢]-weakenₗ (Γ₂⊢φ) {Γ₁})
[⊢]-reorder-[++] : ∀{Γ₁ Γ₂}{φ} → ((Γ₁ ++ Γ₂) ⊢ φ) → ((Γ₂ ++ Γ₁) ⊢ φ)
[⊢]-reorder-[++] {Γ₁}{Γ₂} = [⊢]-from-trees (Trees.[++]-commute {Γ₂}{Γ₁})
[⊢]-apply : ∀{Γ}{φ} → (Γ ⊢ φ) → Trees(Γ) → Tree(φ)
[⊢]-apply ([⊢]-construct [Γ]⊢[φ]) (Γ-trees) = ([Γ]⊢[φ]) (Γ-trees)
[⊢]-apply-first : ∀{Γ}{φ₁ φ₂} → Tree(φ₁) → ((φ₁ ⊰ Γ) ⊢ φ₂) → (Γ ⊢ φ₂)
[⊢]-apply-first ([φ₁]-tree) ([⊢]-construct ([φ₁⊰Γ]⊢[φ₂])) =
[⊢]-construct([Γ]⊢[φ₂] ↦
([φ₁⊰Γ]⊢[φ₂]) (Trees.push ([φ₁]-tree) (\{γ} → [Γ]⊢[φ₂] {γ}))
)
[⊢]-apply-many : ∀{Γ₁ Γ₂}{φ} → Trees(Γ₁) → ((Γ₁ ++ Γ₂) ⊢ φ) → (Γ₂ ⊢ φ)
[⊢]-apply-many ([Γ₁]-trees) ([⊢]-construct ([Γ₁++Γ₂]⊢[φ])) =
[⊢]-construct([Γ₂]⊢[φ] ↦
([Γ₁++Γ₂]⊢[φ]) (Trees.push-many ([Γ₁]-trees) (\{γ} → [Γ₂]⊢[φ] {γ}))
)
[⊢]-reorderᵣ-[⊰] : ∀{Γ₁ Γ₂}{φ₁ φ₂} → ((Γ₁ ++ (φ₁ ⊰ Γ₂)) ⊢ φ₂) ← ((φ₁ ⊰ (Γ₁ ++ Γ₂)) ⊢ φ₂)
[⊢]-reorderᵣ-[⊰] {Γ₁}{Γ₂}{φ₁} = [⊢]-from-trees (Trees.[⊰]-reorderₗ {Γ₁}{Γ₂}{φ₁})
[⊢]-id : ∀{Γ}{φ} → (φ ∈ Γ) → (Γ ⊢ φ)
[⊢]-id (φ-in) = [⊢]-construct ([∈]-proof ↦ [∈]-proof (φ-in))
-- ((A → B) → B) → C
-- f(g ↦ g(x))
-- Almost like that cut rule.
[⊢]-compose : ∀{Γ}{φ₁ φ₂} → (Γ ⊢ φ₁) → ((φ₁ ⊰ Γ) ⊢ φ₂) → (Γ ⊢ φ₂)
[⊢]-compose ([Γ]⊢[φ₁]) ([φ₁Γ]⊢[φ₂]) =
[⊢]-construct ([Γ]-trees ↦
let [φ₁]-tree = [⊢]-apply ([Γ]⊢[φ₁]) (\{γ} → [Γ]-trees {γ})
[Γ]⊢[φ₂] = [⊢]-apply-first ([φ₁]-tree) ([φ₁Γ]⊢[φ₂])
in [⊢]-apply ([Γ]⊢[φ₂]) (\{γ} → [Γ]-trees {γ})
)
-- TODO: ∀{Γ}{φ₁ φ₂} → (Γ ⊢ φ₁) → ((φ₁ ∈ Γ) → (Γ ⊢ φ₂)) → (Γ ⊢ φ₂) Provable?
[⊢]-membership-precedingₗ : ∀{Γ}{φ₁ φ₂} → ((φ₁ ∈ Γ) → (Γ ⊢ φ₂)) ← ((φ₁ ⊰ Γ) ⊢ φ₂)
[⊢]-membership-precedingₗ{Γ}{φ₁}{φ₂} ([φ₁Γ]⊢[φ₂]) ([φ₁]-in) =
[⊢]-construct([Γ]-trees ↦
[⊢]-apply ([φ₁Γ]⊢[φ₂]) (Trees.push ([Γ]-trees [φ₁]-in) (\{γ} → [Γ]-trees {γ}))
)
{- TODO: Maybe this is unprovable? And also false?
postulate a : ∀{b : Set(ℓₚ)} → b
[⊢]-membership-precedingᵣ : ∀{Γ}{φ₁ φ₂} → ((φ₁ ∈ Γ) → (Γ ⊢ φ₂)) → ((φ₁ ⊰ Γ) ⊢ φ₂)
[⊢]-membership-precedingᵣ{Γ}{φ₁}{φ₂} (incl) =
[⊢]-construct ([φ₁Γ]-trees ↦
let [Γ]-trees = Trees.pop (\{γ} → [φ₁Γ]-trees {γ})
[φ₁]-in = a
[Γ]⊢[φ₂] = incl([φ₁]-in)
in [⊢]-apply ([Γ]⊢[φ₂]) ([Γ]-trees)
)
-}
[⊢][⊤]-intro : ∀{Γ} → (Γ ⊢ ⊤)
[⊢][⊤]-intro =
[⊢]-construct(const [⊤]-intro)
[⊢][⊥]-intro : ∀{Γ}{φ} → (φ ∈ Γ) → ((¬ φ) ∈ Γ) → (Γ ⊢ ⊥)
[⊢][⊥]-intro ([φ]-in) ([¬φ]-in) =
[⊢]-construct(assumption-trees ↦
([⊥]-intro
(assumption-trees ([φ]-in))
(assumption-trees ([¬φ]-in))
)
)
[⊢][⊥]-elim : ∀{Γ}{φ} → (⊥ ∈ Γ) → (Γ ⊢ φ)
[⊢][⊥]-elim ([⊥]-in) =
[⊢]-construct(assumption-trees ↦
([⊥]-elim
(assumption-trees ([⊥]-in))
)
)
[⊢][¬]-intro : ∀{Γ}{φ} → ((φ ⊰ Γ) ⊢ ⊥) → (Γ ⊢ (¬ φ))
[⊢][¬]-intro ([⊢]-construct φΓ⊢⊥) =
[⊢]-construct(assumption-trees ↦
([¬]-intro (φ-tree ↦
(φΓ⊢⊥) (Trees.push (φ-tree) (\{γ} → assumption-trees {γ}))
))
)
[⊢][¬]-elim : ∀{Γ}{φ} → (((¬ φ) ⊰ Γ) ⊢ ⊥) → (Γ ⊢ φ)
[⊢][¬]-elim ([⊢]-construct ¬φΓ⊢⊥) =
[⊢]-construct(assumption-trees ↦
([¬]-elim (φ-tree ↦
(¬φΓ⊢⊥) (Trees.push (φ-tree) (\{γ} → assumption-trees {γ}))
))
)
[⊢][∧]-intro : ∀{Γ}{φ₁ φ₂} → (φ₁ ∈ Γ) → (φ₂ ∈ Γ) → (Γ ⊢ (φ₁ ∧ φ₂))
[⊢][∧]-intro ([φ₁]-in) ([φ₂]-in) =
[⊢]-construct(assumption-trees ↦
([∧]-intro
(assumption-trees ([φ₁]-in))
(assumption-trees ([φ₂]-in))
)
)
[⊢][∧]-elimₗ : ∀{Γ}{φ₁ φ₂} → ((φ₁ ∧ φ₂) ∈ Γ) → (Γ ⊢ φ₁)
[⊢][∧]-elimₗ ([φ₁∧φ₂]-in) =
[⊢]-construct(assumption-trees ↦
[∧]-elimₗ (assumption-trees ([φ₁∧φ₂]-in))
)
[⊢][∧]-elimᵣ : ∀{Γ}{φ₁ φ₂} → ((φ₁ ∧ φ₂) ∈ Γ) → (Γ ⊢ φ₂)
[⊢][∧]-elimᵣ ([φ₁∧φ₂]-in) =
[⊢]-construct(assumption-trees ↦
[∧]-elimᵣ (assumption-trees ([φ₁∧φ₂]-in))
)
[⊢][∨]-introₗ : ∀{Γ}{φ₁ φ₂} → (φ₁ ∈ Γ) → (Γ ⊢ (φ₁ ∨ φ₂))
[⊢][∨]-introₗ ([φ₁]-in) =
[⊢]-construct(assumption-trees ↦
[∨]-introₗ (assumption-trees ([φ₁]-in))
)
[⊢][∨]-introᵣ : ∀{Γ}{φ₁ φ₂} → (φ₂ ∈ Γ) → (Γ ⊢ (φ₁ ∨ φ₂))
[⊢][∨]-introᵣ ([φ₂]-in) =
[⊢]-construct(assumption-trees ↦
[∨]-introᵣ (assumption-trees ([φ₂]-in))
)
[⊢][∨]-elim : ∀{Γ₁ Γ₂}{φ₁ φ₂ φ₃} → ((φ₁ ⊰ Γ₁) ⊢ φ₃) → ((φ₂ ⊰ Γ₂) ⊢ φ₃) → (((φ₁ ∨ φ₂) ⊰ (Γ₁ ++ Γ₂)) ⊢ φ₃)
[⊢][∨]-elim {Γ₁}{Γ₂} ([⊢]-construct φ₁Γ⊢φ₃) ([⊢]-construct φ₂Γ⊢φ₃) = [⊢]-construct
(assumption-trees ↦ [∨]-elim
(φ₁-tree ↦ (φ₁Γ⊢φ₃) (Trees.push (φ₁-tree) (Trees.[++]-left {Γ₁}{Γ₂} (Trees.pop (\{γ} → assumption-trees {γ})))))
(φ₂-tree ↦ (φ₂Γ⊢φ₃) (Trees.push (φ₂-tree) (Trees.[++]-right {Γ₁}{Γ₂} (Trees.pop (\{γ} → assumption-trees {γ})))))
(assumption-trees (use))
)
[⊢][⇒]-intro : ∀{Γ}{φ₁ φ₂} → ((φ₁ ⊰ Γ) ⊢ φ₂) → (Γ ⊢ (φ₁ ⇒ φ₂))
[⊢][⇒]-intro ([⊢]-construct φ₁Γ⊢φ₂) = [⊢]-construct
(assumption-trees ↦ [⇒]-intro
(φ-tree ↦ (φ₁Γ⊢φ₂) (Trees.push (φ-tree) (\{γ} → assumption-trees {γ})))
)
[⊢][⇒]-elim : ∀{Γ}{φ₁ φ₂} → ((φ₁ ⇒ φ₂) ∈ Γ) → (φ₁ ∈ Γ) → (Γ ⊢ φ₂)
[⊢][⇒]-elim ([φ₁⇒φ₂]-in) ([φ₁]-in) =
[⊢]-construct(assumption-trees ↦
[⇒]-elim
(assumption-trees ([φ₁⇒φ₂]-in))
(assumption-trees ([φ₁]-in))
)
-- [⊢]-metaᵣ : ∀{a}{b} → _⊢_ a b → Meta._⊢_ a b
-- [⊢]-metaₗ : ∀{a}{b} → _⊢_ a b ← Meta._⊢_ a b
{-[⊢]-rules : Meta.[⊢]-rules (_⊢_)
[⊢]-rules =
record{
[⊤]-intro = \{Γ} → [⊢][⊤]-intro {Γ} ;
[⊥]-intro = \{Γ}{φ} → [⊢][⊥]-intro {Γ}{φ} ;
[⊥]-elim = \{Γ}{φ} → [⊢][⊥]-elim {Γ}{φ} ;
[¬]-intro = \{Γ}{φ} → [⊢][¬]-intro {Γ}{φ} ;
[¬]-elim = \{Γ}{φ} → [⊢][¬]-elim {Γ}{φ} ;
[∧]-intro = \{Γ}{φ₁}{φ₂} → [⊢][∧]-intro {Γ}{φ₁}{φ₂} ;
[∧]-elimₗ = \{Γ}{φ₁}{φ₂} → [⊢][∧]-elimₗ {Γ}{φ₁}{φ₂} ;
[∧]-elimᵣ = \{Γ}{φ₁}{φ₂} → [⊢][∧]-elimᵣ {Γ}{φ₁}{φ₂} ;
[∨]-introₗ = \{Γ}{φ₁}{φ₂} → [⊢][∨]-introₗ {Γ}{φ₁}{φ₂} ;
[∨]-introᵣ = \{Γ}{φ₁}{φ₂} → [⊢][∨]-introᵣ {Γ}{φ₁}{φ₂} ;
[∨]-elim = \{Γ₁}{Γ₂}{φ₁ φ₂ φ₃} → [⊢][∨]-elim {Γ₁}{Γ₂}{φ₁}{φ₂}{φ₃} ;
[⇒]-intro = \{Γ}{φ₁}{φ₂} → [⊢][⇒]-intro {Γ}{φ₁}{φ₂} ;
[⇒]-elim = \{Γ}{φ₁}{φ₂} → [⊢][⇒]-elim {Γ}{φ₁}{φ₂}
}
-}
|
using FractionalTransforms
using Test
@testset "FractionalTransforms.jl" begin
include("frft.jl")
include("frst.jl")
include("frct.jl")
end
|
(*
* Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: GPL-2.0-only
*)
theory ArchFinalise_AI
imports "../Finalise_AI"
begin
(* FIXME: MOVE *)
lemma hoare_validE_R_conjI:
"\<lbrakk> \<lbrace>P\<rbrace> f \<lbrace>Q\<rbrace>, - ; \<lbrace>P\<rbrace> f \<lbrace>Q'\<rbrace>, - \<rbrakk> \<Longrightarrow> \<lbrace>P\<rbrace> f \<lbrace>\<lambda>rv s. Q rv s \<and> Q' rv s\<rbrace>, -"
by (auto simp: Ball_def validE_R_def validE_def valid_def)
context Arch begin
named_theorems Finalise_AI_asms
crunch caps_of_state[wp]: prepare_thread_delete "\<lambda>s. P (caps_of_state s)"
(wp: crunch_wps)
declare prepare_thread_delete_caps_of_state [Finalise_AI_asms]
global_naming RISCV64
lemma valid_global_refs_asid_table_udapte [iff]:
"valid_global_refs (s\<lparr>arch_state := riscv_asid_table_update f (arch_state s)\<rparr>) =
valid_global_refs s"
by (simp add: valid_global_refs_def global_refs_def)
lemma nat_to_cref_unat_of_bl':
"\<lbrakk> length xs < 64; n = length xs \<rbrakk> \<Longrightarrow>
nat_to_cref n (unat (of_bl xs :: machine_word)) = xs"
apply (simp add: nat_to_cref_def word_bits_def)
apply (rule nth_equalityI)
apply simp
apply clarsimp
apply (subst to_bl_nth)
apply (simp add: word_size)
apply (simp add: word_size)
apply (simp add: test_bit_of_bl rev_nth)
apply fastforce
done
lemmas nat_to_cref_unat_of_bl = nat_to_cref_unat_of_bl' [OF _ refl]
lemma riscv_global_pt_asid_table_update[simp]:
"riscv_global_pt (arch_state s\<lparr>riscv_asid_table := atable\<rparr>) = riscv_global_pt (arch_state s)"
by (simp add: riscv_global_pt_def)
lemma equal_kernel_mappings_asid_table_unmap:
"equal_kernel_mappings s
\<Longrightarrow> equal_kernel_mappings (s\<lparr>arch_state := arch_state s
\<lparr>riscv_asid_table := (asid_table s)(i := None)\<rparr>\<rparr>)"
unfolding equal_kernel_mappings_def
apply clarsimp
apply (erule_tac x=asid in allE)
apply (erule_tac x=pt_ptr in allE)
apply (clarsimp simp: fun_upd_def)
apply (erule impE)
subgoal by (clarsimp simp: vspace_for_asid_def in_omonad pool_for_asid_def split: if_splits)
apply (clarsimp simp: has_kernel_mappings_def)
done
lemma invs_riscv_asid_table_unmap:
"invs s \<and> is_aligned base asid_low_bits
\<and> tab = riscv_asid_table (arch_state s)
\<longrightarrow> invs (s\<lparr>arch_state := arch_state s\<lparr>riscv_asid_table := tab(asid_high_bits_of base := None)\<rparr>\<rparr>)"
apply (clarsimp simp: invs_def valid_state_def valid_arch_caps_def)
apply (strengthen valid_asid_map_unmap valid_vspace_objs_unmap_strg
valid_vs_lookup_unmap_strg valid_arch_state_unmap_strg)
apply (simp add: valid_irq_node_def valid_kernel_mappings_def)
apply (simp add: valid_table_caps_def valid_machine_state_def valid_global_objs_def
valid_asid_pool_caps_def equal_kernel_mappings_asid_table_unmap)
done
lemma delete_asid_pool_invs[wp]:
"delete_asid_pool base pptr \<lbrace>invs\<rbrace>"
unfolding delete_asid_pool_def
supply fun_upd_apply[simp del]
apply wpsimp
apply (strengthen invs_riscv_asid_table_unmap)
apply (simp add: asid_low_bits_of_def asid_low_bits_def ucast_zero_is_aligned)
done
lemma do_machine_op_pool_for_asid[wp]:
"do_machine_op f \<lbrace>\<lambda>s. P (pool_for_asid asid s)\<rbrace>"
by (wpsimp simp: pool_for_asid_def)
lemma do_machine_op_vspace_for_asid[wp]:
"do_machine_op f \<lbrace>\<lambda>s. P (vspace_for_asid asid s)\<rbrace>"
by (wpsimp simp: vspace_for_asid_def obind_def
wp: conjI hoare_vcg_all_lift hoare_vcg_imp_lift'
split: option.splits)
lemma set_vm_root_pool_for_asid[wp]:
"set_vm_root pt \<lbrace>\<lambda>s. P (pool_for_asid asid s)\<rbrace>"
by (wpsimp simp: set_vm_root_def wp: get_cap_wp)
lemma set_vm_root_vspace_for_asid[wp]:
"set_vm_root pt \<lbrace> \<lambda>s. P (vspace_for_asid asid s) \<rbrace>"
by (wpsimp simp: set_vm_root_def wp: get_cap_wp)
lemma clearExMonitor_invs[wp]:
"\<lbrace>invs\<rbrace> do_machine_op (hwASIDFlush a) \<lbrace>\<lambda>_. invs\<rbrace>"
by (wpsimp wp: dmo_invs
simp: hwASIDFlush_def machine_op_lift_def
machine_rest_lift_def in_monad select_f_def)
lemma delete_asid_invs[wp]:
"\<lbrace> invs and valid_asid_table and pspace_aligned \<rbrace>delete_asid asid pd \<lbrace>\<lambda>_. invs\<rbrace>"
apply (simp add: delete_asid_def cong: option.case_cong)
apply (wpsimp wp: set_asid_pool_invs_unmap)
apply blast
done
lemma delete_asid_pool_unmapped[wp]:
"\<lbrace>\<lambda>s. True \<rbrace>
delete_asid_pool asid poolptr
\<lbrace>\<lambda>_ s. pool_for_asid asid s \<noteq> Some poolptr \<rbrace>"
unfolding delete_asid_pool_def
by (wpsimp simp: pool_for_asid_def)
lemma set_asid_pool_unmap:
"\<lbrace>\<lambda>s. pool_for_asid asid s = Some poolptr \<rbrace>
set_asid_pool poolptr (pool(asid_low_bits_of asid := None))
\<lbrace>\<lambda>rv s. vspace_for_asid asid s = None \<rbrace>"
unfolding set_asid_pool_def
apply (wpsimp wp: set_object_wp)
by (simp add: pool_for_asid_def vspace_for_asid_def vspace_for_pool_def obind_def in_omonad
split: option.splits)
lemma delete_asid_unmapped:
"\<lbrace>\<lambda>s. vspace_for_asid asid s = Some pt\<rbrace>
delete_asid asid pt
\<lbrace>\<lambda>_ s. vspace_for_asid asid s = None\<rbrace>"
unfolding delete_asid_def
apply (simp cong: option.case_cong)
apply (wpsimp wp: set_asid_pool_unmap)
apply (clarsimp simp: vspace_for_asid_def pool_for_asid_def vspace_for_pool_def
obind_def in_omonad obj_at_def
split: option.splits)
done
lemma set_pt_tcb_at:
"\<lbrace>\<lambda>s. P (ko_at (TCB tcb) t s)\<rbrace> set_pt a b \<lbrace>\<lambda>_ s. P (ko_at (TCB tcb) t s)\<rbrace>"
by (wpsimp simp: set_pt_def obj_at_def wp: set_object_wp)
crunch tcb_at_arch: unmap_page "\<lambda>s. P (ko_at (TCB tcb) t s)"
(simp: crunch_simps wp: crunch_wps set_pt_tcb_at ignore: set_object)
lemmas unmap_page_tcb_at = unmap_page_tcb_at_arch
lemma unmap_page_tcb_cap_valid:
"\<lbrace>\<lambda>s. tcb_cap_valid cap r s\<rbrace>
unmap_page sz asid vaddr pptr
\<lbrace>\<lambda>rv s. tcb_cap_valid cap r s\<rbrace>"
apply (rule tcb_cap_valid_typ_st)
apply wp
apply (simp add: pred_tcb_at_def2)
apply (wp unmap_page_tcb_at hoare_vcg_ex_lift hoare_vcg_all_lift)+
done
global_naming Arch
lemma (* replaceable_cdt_update *)[simp,Finalise_AI_asms]:
"replaceable (cdt_update f s) = replaceable s"
by (fastforce simp: replaceable_def tcb_cap_valid_def
reachable_frame_cap_def reachable_target_def)
lemma (* replaceable_revokable_update *)[simp,Finalise_AI_asms]:
"replaceable (is_original_cap_update f s) = replaceable s"
by (fastforce simp: replaceable_def is_final_cap'_def2 tcb_cap_valid_def
reachable_frame_cap_def reachable_target_def)
lemma (* replaceable_more_update *) [simp,Finalise_AI_asms]:
"replaceable (trans_state f s) sl cap cap' = replaceable s sl cap cap'"
by (simp add: replaceable_def reachable_frame_cap_def reachable_target_def)
lemma reachable_target_trans_state[simp]:
"reachable_target ref p (trans_state f s) = reachable_target ref p s"
by (clarsimp simp: reachable_target_def split_def)
lemma reachable_frame_cap_trans_state[simp]:
"reachable_frame_cap cap (trans_state f s) = reachable_frame_cap cap s"
by (simp add: reachable_frame_cap_def)
lemmas [Finalise_AI_asms] = obj_refs_obj_ref_of (* used under name obj_ref_ofI *)
lemma (* empty_slot_invs *) [Finalise_AI_asms]:
"\<lbrace>\<lambda>s. invs s \<and> cte_wp_at (replaceable s sl cap.NullCap) sl s \<and>
emptyable sl s \<and>
(info \<noteq> NullCap \<longrightarrow> post_cap_delete_pre info ((caps_of_state s) (sl \<mapsto> NullCap)))\<rbrace>
empty_slot sl info
\<lbrace>\<lambda>rv. invs\<rbrace>"
apply (simp add: empty_slot_def set_cdt_def bind_assoc cong: if_cong)
apply (wp post_cap_deletion_invs)
apply (simp add: invs_def valid_state_def valid_mdb_def2)
apply (wp replace_cap_valid_pspace set_cap_caps_of_state2
replace_cap_ifunsafe get_cap_wp
set_cap_idle valid_irq_node_typ set_cap_typ_at
set_cap_irq_handlers set_cap_valid_arch_caps
set_cap_cap_refs_respects_device_region_NullCap
| simp add: trans_state_update[symmetric]
del: trans_state_update fun_upd_apply
split del: if_split)+
apply (clarsimp simp: is_final_cap'_def2 simp del: fun_upd_apply)
apply (clarsimp simp: conj_comms invs_def valid_state_def valid_mdb_def2)
apply (subgoal_tac "mdb_empty_abs s")
prefer 2
apply (rule mdb_empty_abs.intro)
apply (rule vmdb_abs.intro)
apply (simp add: valid_mdb_def swp_def cte_wp_at_caps_of_state conj_comms)
apply (clarsimp simp: untyped_mdb_def mdb_empty_abs.descendants mdb_empty_abs.no_mloop_n
valid_pspace_def cap_range_def)
apply (clarsimp simp: untyped_inc_def mdb_empty_abs.descendants mdb_empty_abs.no_mloop_n)
apply (simp add: ut_revocable_def cur_tcb_def valid_irq_node_def
no_cap_to_obj_with_diff_ref_Null)
apply (rule conjI)
apply (clarsimp simp: cte_wp_at_cte_at)
apply (rule conjI)
apply (clarsimp simp: valid_arch_mdb_def)
apply (rule conjI)
apply (clarsimp simp: irq_revocable_def)
apply (rule conjI)
apply (clarsimp simp: reply_master_revocable_def)
apply (thin_tac "info \<noteq> NullCap \<longrightarrow> P info" for P)
apply (rule conjI)
apply (clarsimp simp: valid_machine_state_def)
apply (rule conjI)
apply (clarsimp simp:descendants_inc_def mdb_empty_abs.descendants)
apply (rule conjI)
apply (clarsimp simp: reply_mdb_def)
apply (rule conjI)
apply (unfold reply_caps_mdb_def)[1]
apply (rule allEI, assumption)
apply (fold reply_caps_mdb_def)[1]
apply (case_tac "sl = ptr", simp)
apply (simp add: fun_upd_def split del: if_split del: split_paired_Ex)
apply (erule allEI, rule impI, erule(1) impE)
apply (erule exEI)
apply (simp, rule ccontr)
apply (erule(5) emptyable_no_reply_cap)
apply simp
apply (unfold reply_masters_mdb_def)[1]
apply (elim allEI)
apply (clarsimp simp: mdb_empty_abs.descendants)
apply (rule conjI)
apply (simp add: valid_ioc_def)
apply (rule conjI)
apply (clarsimp simp: tcb_cap_valid_def
dest!: emptyable_valid_NullCapD)
apply (rule conjI)
apply (clarsimp simp: mdb_cte_at_def cte_wp_at_caps_of_state)
apply (cases sl)
apply (rule conjI, clarsimp)
apply (subgoal_tac "cdt s \<Turnstile> (ab,bb) \<rightarrow> (ab,bb)")
apply (simp add: no_mloop_def)
apply (rule r_into_trancl)
apply (simp add: cdt_parent_of_def)
apply fastforce
apply (clarsimp simp: cte_wp_at_caps_of_state replaceable_def
reachable_frame_cap_def reachable_target_def
del: allI)
apply (case_tac "is_final_cap' cap s")
apply auto[1]
apply (simp add: is_final_cap'_def2 cte_wp_at_caps_of_state)
by fastforce
lemma dom_tcb_cap_cases_lt_ARCH [Finalise_AI_asms]:
"dom tcb_cap_cases = {xs. length xs = 3 \<and> unat (of_bl xs :: machine_word) < 5}"
apply (rule set_eqI, rule iffI)
apply clarsimp
apply (simp add: tcb_cap_cases_def tcb_cnode_index_def to_bl_1 split: if_split_asm)
apply clarsimp
apply (frule tcb_cap_cases_lt)
apply (clarsimp simp: nat_to_cref_unat_of_bl')
done
lemma (* unbind_notification_final *) [wp,Finalise_AI_asms]:
"\<lbrace>is_final_cap' cap\<rbrace> unbind_notification t \<lbrace> \<lambda>rv. is_final_cap' cap\<rbrace>"
unfolding unbind_notification_def
apply (wp final_cap_lift thread_set_caps_of_state_trivial hoare_drop_imps
| wpc | simp add: tcb_cap_cases_def)+
done
lemma arch_thread_set_caps_of_state[wp]:
"arch_thread_set v t \<lbrace>\<lambda>s. P (caps_of_state s) \<rbrace>"
apply (wpsimp simp: arch_thread_set_def wp: set_object_wp)
apply (clarsimp simp: fun_upd_def)
apply (frule get_tcb_ko_atD)
apply (auto simp: caps_of_state_after_update obj_at_def tcb_cap_cases_def)
done
lemma arch_thread_set_final_cap[wp]:
"\<lbrace>is_final_cap' cap\<rbrace> arch_thread_set v t \<lbrace>\<lambda>rv. is_final_cap' cap\<rbrace>"
by (wpsimp simp: is_final_cap'_def2 cte_wp_at_caps_of_state)
lemma arch_thread_get_final_cap[wp]:
"\<lbrace>is_final_cap' cap\<rbrace> arch_thread_get v t \<lbrace>\<lambda>rv. is_final_cap' cap\<rbrace>"
apply (simp add: arch_thread_get_def is_final_cap'_def2 cte_wp_at_caps_of_state, wp)
apply auto
done
lemma prepare_thread_delete_final[wp]:
"\<lbrace>is_final_cap' cap\<rbrace> prepare_thread_delete t \<lbrace> \<lambda>rv. is_final_cap' cap\<rbrace>"
unfolding prepare_thread_delete_def by wp
lemma length_and_unat_of_bl_length:
"(length xs = x \<and> unat (of_bl xs :: 'a::len word) < 2 ^ x) = (length xs = x)"
by (auto simp: unat_of_bl_length)
lemma (* finalise_cap_cases1 *)[Finalise_AI_asms]:
"\<lbrace>\<lambda>s. final \<longrightarrow> is_final_cap' cap s
\<and> cte_wp_at ((=) cap) slot s\<rbrace>
finalise_cap cap final
\<lbrace>\<lambda>rv s. fst rv = cap.NullCap
\<and> snd rv = (if final then cap_cleanup_opt cap else NullCap)
\<and> (snd rv \<noteq> NullCap \<longrightarrow> is_final_cap' cap s)
\<or>
is_zombie (fst rv) \<and> is_final_cap' cap s
\<and> snd rv = NullCap
\<and> appropriate_cte_cap (fst rv) = appropriate_cte_cap cap
\<and> cte_refs (fst rv) = cte_refs cap
\<and> gen_obj_refs (fst rv) = gen_obj_refs cap
\<and> obj_size (fst rv) = obj_size cap
\<and> fst_cte_ptrs (fst rv) = fst_cte_ptrs cap
\<and> vs_cap_ref cap = None\<rbrace>"
apply (cases cap, simp_all split del: if_split cong: if_cong)
apply ((wp suspend_final_cap[where sl=slot]
deleting_irq_handler_final[where slot=slot]
| simp add: o_def is_cap_simps fst_cte_ptrs_def
dom_tcb_cap_cases_lt_ARCH tcb_cnode_index_def
can_fast_finalise_def length_and_unat_of_bl_length
appropriate_cte_cap_def gen_obj_refs_def
vs_cap_ref_def cap_cleanup_opt_def
| intro impI TrueI ext conjI)+)[11]
apply (simp add: arch_finalise_cap_def split del: if_split)
apply (wpsimp simp: cap_cleanup_opt_def arch_cap_cleanup_opt_def)
done
crunch typ_at_arch [wp]: arch_thread_set "\<lambda>s. P (typ_at T p s)"
(wp: crunch_wps set_object_typ_at)
crunch typ_at[wp,Finalise_AI_asms]: arch_finalise_cap "\<lambda>s. P (typ_at T p s)"
(wp: crunch_wps simp: crunch_simps unless_def assertE_def
ignore: maskInterrupt set_object)
crunch typ_at[wp,Finalise_AI_asms]: prepare_thread_delete "\<lambda>s. P (typ_at T p s)"
crunch tcb_at[wp]: arch_thread_set "\<lambda>s. tcb_at p s"
(ignore: set_object)
crunch tcb_at[wp]: arch_thread_get "\<lambda>s. tcb_at p s"
crunch tcb_at[wp]: prepare_thread_delete "\<lambda>s. tcb_at p s"
lemma (* finalise_cap_new_valid_cap *)[wp,Finalise_AI_asms]:
"\<lbrace>valid_cap cap\<rbrace> finalise_cap cap x \<lbrace>\<lambda>rv. valid_cap (fst rv)\<rbrace>"
apply (cases cap; simp)
apply (wp suspend_valid_cap prepare_thread_delete_typ_at
| simp add: o_def valid_cap_def cap_aligned_def
valid_cap_Null_ext
split del: if_split
| clarsimp | rule conjI)+
(* ArchObjectCap *)
apply (wpsimp wp: o_def valid_cap_def cap_aligned_def
split_del: if_split
| clarsimp simp: arch_finalise_cap_def)+
done
crunch inv[wp]: arch_thread_get "P"
lemma hoare_split: "\<lbrakk>\<lbrace>P\<rbrace> f \<lbrace>Q\<rbrace>; \<lbrace>P\<rbrace> f \<lbrace>Q'\<rbrace>\<rbrakk> \<Longrightarrow> \<lbrace>P\<rbrace> f \<lbrace>\<lambda>r. Q r and Q' r\<rbrace>"
by (auto simp: valid_def)
sublocale
arch_thread_set: non_aobj_non_cap_non_mem_op "arch_thread_set f v"
by (unfold_locales;
((wpsimp)?;
wpsimp wp: set_object_non_arch simp: non_arch_objs arch_thread_set_def)?)
(* arch_thread_set invariants *)
lemma arch_thread_set_cur_tcb[wp]: "\<lbrace>cur_tcb\<rbrace> arch_thread_set p v \<lbrace>\<lambda>_. cur_tcb\<rbrace>"
unfolding cur_tcb_def[abs_def]
apply (rule hoare_lift_Pf [where f=cur_thread])
apply (simp add: tcb_at_typ)
apply wp
apply (simp add: arch_thread_set_def)
apply (wp hoare_drop_imp)
apply simp
done
lemma cte_wp_at_update_some_tcb:
"\<lbrakk>kheap s v = Some (TCB tcb) ; tcb_cnode_map tcb = tcb_cnode_map (f tcb)\<rbrakk>
\<Longrightarrow> cte_wp_at P p (s\<lparr>kheap := kheap s (v \<mapsto> TCB (f tcb))\<rparr>) = cte_wp_at P p s"
apply (clarsimp simp: cte_wp_at_cases2 dest!: get_tcb_SomeD)
done
lemma arch_thread_set_cap_refs_respects_device_region[wp]:
"\<lbrace>cap_refs_respects_device_region\<rbrace>
arch_thread_set p v
\<lbrace>\<lambda>s. cap_refs_respects_device_region\<rbrace>"
apply (simp add: arch_thread_set_def set_object_def get_object_def)
apply wp
apply (clarsimp dest!: get_tcb_SomeD simp del: fun_upd_apply)
apply (subst get_tcb_rev, assumption, subst option.sel)+
apply (subst cap_refs_respects_region_cong)
prefer 3
apply assumption
apply (rule cte_wp_caps_of_lift)
apply (subst arch_tcb_update_aux3)
apply (rule_tac cte_wp_at_update_some_tcb, assumption)
apply (simp add: tcb_cnode_map_def)+
done
lemma arch_thread_set_pspace_respects_device_region[wp]:
"\<lbrace>pspace_respects_device_region\<rbrace>
arch_thread_set p v
\<lbrace>\<lambda>s. pspace_respects_device_region\<rbrace>"
apply (simp add: arch_thread_set_def)
apply (wp get_object_wp set_object_pspace_respects_device_region)
apply clarsimp
done
lemma arch_thread_set_cap_refs_in_kernel_window[wp]:
"\<lbrace>cap_refs_in_kernel_window\<rbrace> arch_thread_set p v \<lbrace>\<lambda>_. cap_refs_in_kernel_window\<rbrace>"
unfolding cap_refs_in_kernel_window_def[abs_def]
apply (rule hoare_lift_Pf [where f="\<lambda>s. not_kernel_window s"])
apply (rule valid_refs_cte_lift)
apply wp+
done
crunch valid_irq_states[wp]: arch_thread_set valid_irq_states
(wp: crunch_wps simp: crunch_simps)
crunch interrupt_state[wp]: arch_thread_set "\<lambda>s. P (interrupt_states s)"
(wp: crunch_wps simp: crunch_simps)
lemmas arch_thread_set_valid_irq_handlers[wp] = valid_irq_handlers_lift[OF arch_thread_set.caps arch_thread_set_interrupt_state]
crunch interrupt_irq_node[wp]: arch_thread_set "\<lambda>s. P (interrupt_irq_node s)"
(wp: crunch_wps simp: crunch_simps)
lemmas arch_thread_set_valid_irq_node[wp] = valid_irq_node_typ[OF arch_thread_set_typ_at_arch arch_thread_set_interrupt_irq_node]
crunch idle_thread[wp]: arch_thread_set "\<lambda>s. P (idle_thread s)"
(wp: crunch_wps simp: crunch_simps)
lemma arch_thread_set_valid_global_refs[wp]:
"\<lbrace>valid_global_refs\<rbrace> arch_thread_set p v \<lbrace>\<lambda>rv. valid_global_refs\<rbrace>"
by (rule valid_global_refs_cte_lift) wp+
lemma arch_thread_set_valid_reply_masters[wp]:
"\<lbrace>valid_reply_masters\<rbrace> arch_thread_set p v \<lbrace>\<lambda>rv. valid_reply_masters\<rbrace>"
by (rule valid_reply_masters_cte_lift) wp
lemma arch_thread_set_pred_tcb_at[wp_unsafe]:
"\<lbrace>pred_tcb_at proj P t and K (proj_not_field proj tcb_arch_update)\<rbrace>
arch_thread_set p v
\<lbrace>\<lambda>rv. pred_tcb_at proj P t\<rbrace>"
apply (simp add: arch_thread_set_def set_object_def get_object_def)
apply wp
apply (clarsimp simp: pred_tcb_at_def obj_at_def get_tcb_rev
dest!: get_tcb_SomeD)
done
lemma arch_thread_set_valid_reply_caps[wp]:
"\<lbrace>valid_reply_caps\<rbrace> arch_thread_set p v \<lbrace>\<lambda>rv. valid_reply_caps\<rbrace>"
by (rule valid_reply_caps_st_cte_lift)
(wpsimp wp: arch_thread_set_pred_tcb_at)+
lemma arch_thread_set_if_unsafe_then_cap[wp]:
"\<lbrace>if_unsafe_then_cap\<rbrace> arch_thread_set p v \<lbrace>\<lambda>rv. if_unsafe_then_cap\<rbrace>"
apply (simp add: arch_thread_set_def)
apply (wp get_object_wp set_object_ifunsafe)
apply (clarsimp split: kernel_object.splits arch_kernel_obj.splits
dest!: get_tcb_SomeD)
apply (subst get_tcb_rev)
apply assumption
apply simp
apply (subst get_tcb_rev, assumption, simp)+
apply (clarsimp simp: obj_at_def tcb_cap_cases_def)
done
lemma arch_thread_set_only_idle[wp]:
"\<lbrace>only_idle\<rbrace> arch_thread_set p v \<lbrace>\<lambda>rv. only_idle\<rbrace>"
by (wpsimp wp: only_idle_lift set_asid_pool_typ_at
arch_thread_set_pred_tcb_at)
lemma arch_thread_set_valid_idle[wp]:
"arch_thread_set f t \<lbrace>valid_idle\<rbrace>"
by (wpsimp simp: arch_thread_set_def set_object_def get_object_def valid_idle_def
valid_arch_idle_def get_tcb_def pred_tcb_at_def obj_at_def pred_neg_def)
lemma arch_thread_set_valid_ioc[wp]:
"\<lbrace>valid_ioc\<rbrace> arch_thread_set p v \<lbrace>\<lambda>rv. valid_ioc\<rbrace>"
apply (simp add: arch_thread_set_def set_object_def get_object_def)
apply (wp set_object_valid_ioc_caps)
apply (clarsimp simp add: valid_ioc_def
simp del: fun_upd_apply
split: kernel_object.splits arch_kernel_obj.splits
dest!: get_tcb_SomeD)
apply (subst get_tcb_rev, assumption, subst option.sel)+
apply (subst arch_tcb_update_aux3)
apply (subst cte_wp_at_update_some_tcb,assumption)
apply (clarsimp simp: tcb_cnode_map_def)+
done
lemma arch_thread_set_valid_mdb[wp]: "\<lbrace>valid_mdb\<rbrace> arch_thread_set p v \<lbrace>\<lambda>rv. valid_mdb\<rbrace>"
by (wpsimp wp: valid_mdb_lift get_object_wp simp: arch_thread_set_def set_object_def)
lemma arch_thread_set_zombies_final[wp]: "\<lbrace>zombies_final\<rbrace> arch_thread_set p v \<lbrace>\<lambda>rv. zombies_final\<rbrace>"
apply (simp add: arch_thread_set_def)
apply (wp get_object_wp set_object_zombies)
apply (clarsimp split: kernel_object.splits arch_kernel_obj.splits
dest!: get_tcb_SomeD)
apply (subst get_tcb_rev)
apply assumption
apply simp
apply (subst get_tcb_rev, assumption, simp)+
apply (clarsimp simp: obj_at_def tcb_cap_cases_def)
done
lemma arch_thread_set_pspace_in_kernel_window[wp]:
"\<lbrace>pspace_in_kernel_window\<rbrace> arch_thread_set f v \<lbrace>\<lambda>_.pspace_in_kernel_window\<rbrace>"
by (rule pspace_in_kernel_window_atyp_lift, wp+)
lemma arch_thread_set_pspace_distinct[wp]: "\<lbrace>pspace_distinct\<rbrace>arch_thread_set f v\<lbrace>\<lambda>_. pspace_distinct\<rbrace>"
apply (simp add: arch_thread_set_def)
apply (wp set_object_distinct)
apply (clarsimp simp: get_object_def obj_at_def
dest!: get_tcb_SomeD)
done
lemma arch_thread_set_pspace_aligned[wp]:
"\<lbrace>pspace_aligned\<rbrace> arch_thread_set f v \<lbrace>\<lambda>_. pspace_aligned\<rbrace>"
apply (simp add: arch_thread_set_def)
apply (wp set_object_aligned)
apply (clarsimp simp: obj_at_def get_object_def
dest!: get_tcb_SomeD)
done
lemma arch_thread_set_valid_objs_context[wp]:
"arch_thread_set (tcb_context_update f) v \<lbrace>valid_objs\<rbrace>"
apply (simp add: arch_thread_set_def)
apply (wp set_object_valid_objs)
apply (clarsimp simp: Ball_def obj_at_def valid_objs_def dest!: get_tcb_SomeD)
apply (erule_tac x=v in allE)
apply (clarsimp simp: dom_def)
apply (subst get_tcb_rev, assumption, subst option.sel)+
apply (clarsimp simp:valid_obj_def valid_tcb_def tcb_cap_cases_def)
done
lemma sym_refs_update_some_tcb:
"\<lbrakk>kheap s v = Some (TCB tcb) ; refs_of (TCB tcb) = refs_of (TCB (f tcb))\<rbrakk>
\<Longrightarrow> sym_refs (state_refs_of (s\<lparr>kheap := kheap s (v \<mapsto> TCB (f tcb))\<rparr>)) = sym_refs (state_refs_of s)"
apply (rule_tac f=sym_refs in arg_cong)
apply (rule all_ext)
apply (clarsimp simp: sym_refs_def state_refs_of_def)
done
lemma arch_thread_sym_refs[wp]:
"\<lbrace>\<lambda>s. sym_refs (state_refs_of s)\<rbrace> arch_thread_set f p \<lbrace>\<lambda>rv s. sym_refs (state_refs_of s)\<rbrace>"
apply (simp add: arch_thread_set_def set_object_def get_object_def)
apply wp
apply (clarsimp simp del: fun_upd_apply dest!: get_tcb_SomeD)
apply (subst get_tcb_rev, assumption, subst option.sel)+
apply (subst arch_tcb_update_aux3)
apply (subst sym_refs_update_some_tcb[where f="tcb_arch_update f"])
apply assumption
apply (clarsimp simp: refs_of_def)
apply assumption
done
lemma as_user_unlive_hyp[wp]:
"\<lbrace>obj_at (Not \<circ> hyp_live) vr\<rbrace> as_user t f \<lbrace>\<lambda>_. obj_at (Not \<circ> hyp_live) vr\<rbrace>"
unfolding as_user_def
apply (wpsimp wp: set_object_wp)
by (clarsimp simp: obj_at_def hyp_live_def arch_tcb_context_set_def)
lemma as_user_unlive0[wp]:
"\<lbrace>obj_at (Not \<circ> live0) vr\<rbrace> as_user t f \<lbrace>\<lambda>_. obj_at (Not \<circ> live0) vr\<rbrace>"
unfolding as_user_def
apply (wpsimp wp: set_object_wp)
by (clarsimp simp: obj_at_def arch_tcb_context_set_def dest!: get_tcb_SomeD)
lemma o_def_not: "obj_at (\<lambda>a. \<not> P a) t s = obj_at (Not o P) t s"
by (simp add: obj_at_def)
lemma arch_thread_set_if_live_then_nonz_cap':
"\<forall>y. hyp_live (TCB (y\<lparr>tcb_arch := p (tcb_arch y)\<rparr>)) \<longrightarrow> hyp_live (TCB y) \<Longrightarrow>
\<lbrace>if_live_then_nonz_cap\<rbrace> arch_thread_set p v \<lbrace>\<lambda>rv. if_live_then_nonz_cap\<rbrace>"
apply (simp add: arch_thread_set_def)
apply (wp set_object_iflive)
apply (clarsimp simp: ex_nonz_cap_to_def if_live_then_nonz_cap_def
dest!: get_tcb_SomeD)
apply (subst get_tcb_rev, assumption, subst option.sel)+
apply (clarsimp simp: obj_at_def tcb_cap_cases_def)
apply (erule_tac x=v in allE, drule mp; assumption?)
apply (clarsimp simp: live_def)
done
lemma same_caps_tcb_arch_update[simp]:
"same_caps (TCB (tcb_arch_update f tcb)) = same_caps (TCB tcb)"
by (rule ext) (clarsimp simp: tcb_cap_cases_def)
lemma as_user_valid_irq_node[wp]:
"\<lbrace>valid_irq_node\<rbrace> as_user t f \<lbrace>\<lambda>_. valid_irq_node\<rbrace>"
unfolding as_user_def
apply (wpsimp wp: set_object_wp)
apply (clarsimp simp: valid_irq_node_def obj_at_def is_cap_table dest!: get_tcb_SomeD)
by (metis kernel_object.distinct(1) option.inject)
lemma dmo_machine_state_lift:
"\<lbrace>P\<rbrace> f \<lbrace>Q\<rbrace> \<Longrightarrow> \<lbrace>\<lambda>s. P (machine_state s)\<rbrace> do_machine_op f \<lbrace>\<lambda>rv s. Q rv (machine_state s)\<rbrace>"
unfolding do_machine_op_def by wpsimp (erule use_valid; assumption)
lemma as_user_valid_irq_states[wp]:
"\<lbrace>valid_irq_states\<rbrace> as_user t f \<lbrace>\<lambda>rv. valid_irq_states\<rbrace>"
unfolding as_user_def
by (wpsimp wp: set_object_wp simp: obj_at_def valid_irq_states_def)
lemma as_user_ioc[wp]:
"\<lbrace>\<lambda>s. P (is_original_cap s)\<rbrace> as_user t f \<lbrace>\<lambda>rv s. P (is_original_cap s)\<rbrace>"
unfolding as_user_def by (wpsimp wp: set_object_wp)
lemma as_user_valid_ioc[wp]:
"\<lbrace>valid_ioc\<rbrace> as_user t f \<lbrace>\<lambda>rv. valid_ioc\<rbrace>"
unfolding valid_ioc_def by (wpsimp wp: hoare_vcg_imp_lift hoare_vcg_all_lift)
lemma arch_finalise_cap_invs' [wp,Finalise_AI_asms]:
"\<lbrace>invs and valid_cap (ArchObjectCap cap)\<rbrace>
arch_finalise_cap cap final
\<lbrace>\<lambda>rv. invs\<rbrace>"
apply (simp add: arch_finalise_cap_def)
apply (rule hoare_pre)
apply (wp unmap_page_invs | wpc)+
apply (clarsimp simp: valid_cap_def cap_aligned_def)
apply (auto simp: mask_def vmsz_aligned_def wellformed_mapdata_def)
done
lemma as_user_unlive[wp]:
"\<lbrace>obj_at (Not \<circ> live) vr\<rbrace> as_user t f \<lbrace>\<lambda>_. obj_at (Not \<circ> live) vr\<rbrace>"
unfolding as_user_def
apply (wpsimp wp: set_object_wp)
by (clarsimp simp: obj_at_def live_def hyp_live_def arch_tcb_context_set_def dest!: get_tcb_SomeD)
lemma obj_at_not_live_valid_arch_cap_strg [Finalise_AI_asms]:
"(s \<turnstile> ArchObjectCap cap \<and> aobj_ref cap = Some r)
\<longrightarrow> obj_at (\<lambda>ko. \<not> live ko) r s"
by (clarsimp simp: valid_cap_def obj_at_def valid_arch_cap_ref_def
a_type_arch_live live_def hyp_live_def
split: arch_cap.split_asm if_splits)
crunches set_vm_root
for ptes_of[wp]: "\<lambda>s. P (ptes_of s)"
and asid_pools_of[wp]: "\<lambda>s. P (asid_pools_of s)"
and asid_table[wp]: "\<lambda>s. P (asid_table s)"
(simp: crunch_simps)
lemma set_vm_root_vs_lookup_target[wp]:
"set_vm_root tcb \<lbrace>\<lambda>s. P (vs_lookup_target level asid vref s)\<rbrace>"
by (wpsimp wp: vs_lookup_target_lift)
lemma vs_lookup_target_no_asid_pool:
"\<lbrakk>asid_pool_at ptr s; valid_vspace_objs s; valid_asid_table s; pspace_aligned s;
vs_lookup_target level asid 0 s = Some (level, ptr)\<rbrakk>
\<Longrightarrow> False"
apply (clarsimp simp: vs_lookup_target_def split: if_split_asm)
apply (clarsimp simp: vs_lookup_slot_def vs_lookup_table_def obj_at_def)
apply (frule (1) pool_for_asid_validD, clarsimp)
apply (subst (asm) pool_for_asid_vs_lookup[symmetric, where vref=0 and level=asid_pool_level, simplified])
apply (drule (1) valid_vspace_objsD; simp add: in_omonad)
apply (fastforce simp: vspace_for_pool_def in_omonad obj_at_def ran_def)
apply (rename_tac pt_ptr)
apply (clarsimp simp: vs_lookup_slot_def obj_at_def split: if_split_asm)
apply (clarsimp simp: in_omonad)
apply (frule (1) vs_lookup_table_is_aligned; clarsimp?)
apply (clarsimp simp: ptes_of_def)
apply (drule (1) valid_vspace_objsD; simp add: in_omonad)
apply (simp add: is_aligned_mask)
apply (drule_tac x=0 in bspec)
apply (clarsimp simp: kernel_mapping_slots_def pptr_base_def pptrBase_def pt_bits_left_def
bit_simps level_defs canonical_bit_def)
apply (clarsimp simp: pte_ref_def data_at_def obj_at_def split: pte.splits)
done
lemma delete_asid_pool_not_target[wp]:
"\<lbrace>asid_pool_at ptr and valid_vspace_objs and valid_asid_table and pspace_aligned\<rbrace>
delete_asid_pool asid ptr
\<lbrace>\<lambda>rv s. vs_lookup_target level asid 0 s \<noteq> Some (level, ptr)\<rbrace>"
unfolding delete_asid_pool_def
supply fun_upd_apply[simp del]
apply wpsimp
apply (rule conjI; clarsimp)
apply (frule vs_lookup_target_no_asid_pool[of _ _ level asid]; assumption?)
apply (erule vs_lookup_target_clear_asid_table)
apply (erule (4) vs_lookup_target_no_asid_pool)
done
lemma delete_asid_pool_not_reachable[wp]:
"\<lbrace>asid_pool_at ptr and valid_vspace_objs and valid_asid_table and pspace_aligned\<rbrace>
delete_asid_pool asid ptr
\<lbrace>\<lambda>rv s. \<not> reachable_target (asid, 0) ptr s\<rbrace>"
unfolding reachable_target_def by (wpsimp wp: hoare_vcg_all_lift)
lemmas reachable_frame_cap_simps =
reachable_frame_cap_def[unfolded is_frame_cap_def arch_cap_fun_lift_def, split_simps cap.split]
lemma vs_lookup_slot_non_PageTablePTE:
"\<lbrakk> ptes_of s p \<noteq> None; ptes_of s' = ptes_of s(p \<mapsto> pte); \<not> is_PageTablePTE pte;
asid_pools_of s' = asid_pools_of s;
asid_table s' = asid_table s; valid_asid_table s; pspace_aligned s\<rbrakk>
\<Longrightarrow> vs_lookup_slot level asid vref s' =
(if \<exists>level'. vs_lookup_slot level' asid vref s = Some (level', p) \<and> level < level'
then vs_lookup_slot (level_of_slot asid vref p s) asid vref s
else vs_lookup_slot level asid vref s)"
apply clarsimp
apply (rule conjI; clarsimp;
(simp (no_asm) add: vs_lookup_slot_def obind_def,
(subst vs_lookup_non_PageTablePTE; simp),
fastforce split: option.splits))
done
lemma unmap_page_table_pool_for_asid[wp]:
"unmap_page_table asid vref pt \<lbrace>\<lambda>s. P (pool_for_asid asid s)\<rbrace>"
unfolding unmap_page_table_def by (wpsimp simp: pool_for_asid_def)
lemma unmap_page_table_unreachable:
"\<lbrace> pt_at pt and valid_asid_table and valid_vspace_objs and pspace_aligned
and unique_table_refs and valid_vs_lookup and (\<lambda>s. valid_caps (caps_of_state s) s)
and K (0 < asid \<and> vref \<in> user_region)
and (\<lambda>s. vspace_for_asid asid s \<noteq> Some pt) \<rbrace>
unmap_page_table asid vref pt
\<lbrace>\<lambda>_ s. \<not> reachable_target (asid, vref) pt s\<rbrace>"
unfolding reachable_target_def
apply (wpsimp wp: hoare_vcg_all_lift unmap_page_table_not_target)
apply (drule (1) pool_for_asid_validD)
apply (clarsimp simp: obj_at_def in_omonad)
done
lemma unmap_page_unreachable:
"\<lbrace> data_at pgsz pptr and valid_asid_table and valid_vspace_objs and pspace_aligned
and unique_table_refs and valid_vs_lookup and (\<lambda>s. valid_caps (caps_of_state s) s)
and K (0 < asid \<and> vref \<in> user_region) \<rbrace>
unmap_page pgsz asid vref pptr
\<lbrace>\<lambda>rv s. \<not> reachable_target (asid, vref) pptr s\<rbrace>"
unfolding reachable_target_def
apply (wpsimp wp: hoare_vcg_all_lift unmap_page_not_target)
apply (drule (1) pool_for_asid_validD)
apply (clarsimp simp: obj_at_def data_at_def in_omonad)
done
lemma set_asid_pool_pool_for_asid[wp]:
"set_asid_pool ptr pool \<lbrace>\<lambda>s. P (pool_for_asid asid' s)\<rbrace>"
unfolding pool_for_asid_def by wpsimp
lemma delete_asid_pool_for_asid[wp]:
"delete_asid asid pt \<lbrace>\<lambda>s. P (pool_for_asid asid' s)\<rbrace>"
unfolding delete_asid_def by wpsimp
lemma delete_asid_no_vs_lookup_target:
"\<lbrace>\<lambda>s. vspace_for_asid asid s = Some pt\<rbrace>
delete_asid asid pt
\<lbrace>\<lambda>rv s. vs_lookup_target level asid vref s \<noteq> Some (level, pt)\<rbrace>"
apply (rule hoare_assume_pre)
apply (prop_tac "0 < asid")
apply (clarsimp simp: vspace_for_asid_def)
apply (rule hoare_strengthen_post, rule delete_asid_unmapped)
apply (clarsimp simp: vs_lookup_target_def split: if_split_asm)
apply (clarsimp simp: vs_lookup_slot_def vs_lookup_table_def split: if_split_asm)
apply (clarsimp simp: vspace_for_asid_def obind_def)
apply (clarsimp simp: vs_lookup_slot_def vs_lookup_table_def split: if_split_asm)
apply (clarsimp simp: vspace_for_asid_def obind_def)
done
lemma delete_asid_unreachable:
"\<lbrace>\<lambda>s. vspace_for_asid asid s = Some pt \<and> pt_at pt s \<and> valid_asid_table s \<rbrace>
delete_asid asid pt
\<lbrace>\<lambda>_ s. \<not> reachable_target (asid, vref) pt s\<rbrace>"
unfolding reachable_target_def
apply (wpsimp wp: hoare_vcg_all_lift delete_asid_no_vs_lookup_target)
apply (drule (1) pool_for_asid_validD)
apply (clarsimp simp: obj_at_def in_omonad)
done
lemma arch_finalise_cap_replaceable:
notes strg = tcb_cap_valid_imp_NullCap
obj_at_not_live_valid_arch_cap_strg[where cap=cap]
notes simps = replaceable_def and_not_not_or_imp
is_cap_simps vs_cap_ref_def
no_cap_to_obj_with_diff_ref_Null o_def
reachable_frame_cap_simps
notes wps = hoare_drop_imp[where R="%_. is_final_cap' cap" for cap]
valid_cap_typ
unmap_page_unreachable unmap_page_table_unreachable
delete_asid_unreachable
shows
"\<lbrace>\<lambda>s. s \<turnstile> ArchObjectCap cap \<and>
x = is_final_cap' (ArchObjectCap cap) s \<and>
pspace_aligned s \<and> valid_vspace_objs s \<and> valid_objs s \<and> valid_asid_table s \<and>
valid_arch_caps s\<rbrace>
arch_finalise_cap cap x
\<lbrace>\<lambda>rv s. replaceable s sl (fst rv) (ArchObjectCap cap)\<rbrace>"
apply (simp add: arch_finalise_cap_def valid_arch_caps_def)
apply (wpsimp simp: simps valid_objs_caps wp: wps | strengthen strg)+
apply (rule conjI, clarsimp)
apply (clarsimp simp: valid_cap_def)
apply (rule conjI; clarsimp)
apply (rule conjI; clarsimp simp: valid_cap_def wellformed_mapdata_def data_at_def split: if_split_asm)
apply (rule conjI; clarsimp)
apply (clarsimp simp: valid_cap_def wellformed_mapdata_def cap_aligned_def)
done
global_naming Arch
lemma (* deleting_irq_handler_slot_not_irq_node *)[Finalise_AI_asms]:
"\<lbrace>if_unsafe_then_cap and valid_global_refs
and cte_wp_at (\<lambda>cp. cap_irqs cp \<noteq> {}) sl\<rbrace>
deleting_irq_handler irq
\<lbrace>\<lambda>rv s. (interrupt_irq_node s irq, []) \<noteq> sl\<rbrace>"
apply (simp add: deleting_irq_handler_def)
apply wp
apply clarsimp
apply (drule(1) if_unsafe_then_capD)
apply clarsimp
apply (clarsimp simp: ex_cte_cap_wp_to_def cte_wp_at_caps_of_state)
apply (drule cte_refs_obj_refs_elem)
apply (erule disjE)
apply simp
apply (drule(1) valid_global_refsD[OF _ caps_of_state_cteD])
prefer 2
apply (erule notE, simp add: cap_range_def, erule disjI2)
apply (simp add: global_refs_def)
apply (clarsimp simp: appropriate_cte_cap_def split: cap.split_asm)
done
lemma no_cap_to_obj_with_diff_ref_finalI_ARCH[Finalise_AI_asms]:
"\<lbrakk> cte_wp_at ((=) cap) p s; is_final_cap' cap s;
obj_refs cap' = obj_refs cap \<rbrakk>
\<Longrightarrow> no_cap_to_obj_with_diff_ref cap' {p} s"
apply (case_tac "obj_refs cap = {}")
apply (case_tac "cap_irqs cap = {}")
apply (case_tac "arch_gen_refs cap = {}")
apply (simp add: is_final_cap'_def)
apply (case_tac cap, simp_all add: gen_obj_refs_def)
apply ((clarsimp simp add: no_cap_to_obj_with_diff_ref_def
cte_wp_at_caps_of_state
vs_cap_ref_def
dest!: obj_ref_none_no_asid[rule_format])+)[2]
apply (clarsimp simp: no_cap_to_obj_with_diff_ref_def
is_final_cap'_def2
simp del: split_paired_All)
apply (frule_tac x=p in spec)
apply (drule_tac x="(a, b)" in spec)
apply (clarsimp simp: cte_wp_at_caps_of_state
gen_obj_refs_Int)
done
lemma (* suspend_no_cap_to_obj_ref *)[wp,Finalise_AI_asms]:
"\<lbrace>no_cap_to_obj_with_diff_ref cap S\<rbrace>
suspend t
\<lbrace>\<lambda>rv. no_cap_to_obj_with_diff_ref cap S\<rbrace>"
apply (simp add: no_cap_to_obj_with_diff_ref_def
cte_wp_at_caps_of_state)
apply (wp suspend_caps_of_state)
apply (clarsimp dest!: obj_ref_none_no_asid[rule_format])
done
lemma prepare_thread_delete_no_cap_to_obj_ref[wp]:
"\<lbrace>no_cap_to_obj_with_diff_ref cap S\<rbrace>
prepare_thread_delete t
\<lbrace>\<lambda>rv. no_cap_to_obj_with_diff_ref cap S\<rbrace>"
unfolding prepare_thread_delete_def by wpsimp
lemma prepare_thread_delete_unlive_hyp:
"\<lbrace>obj_at \<top> ptr\<rbrace> prepare_thread_delete ptr \<lbrace>\<lambda>rv. obj_at (Not \<circ> hyp_live) ptr\<rbrace>"
apply (simp add: prepare_thread_delete_def)
apply (wpsimp simp: obj_at_def is_tcb_def hyp_live_def)
done
lemma prepare_thread_delete_unlive0:
"\<lbrace>obj_at (Not \<circ> live0) ptr\<rbrace> prepare_thread_delete ptr \<lbrace>\<lambda>rv. obj_at (Not \<circ> live0) ptr\<rbrace>"
by (simp add: prepare_thread_delete_def)
lemma prepare_thread_delete_unlive[wp]:
"\<lbrace>obj_at (Not \<circ> live0) ptr\<rbrace> prepare_thread_delete ptr \<lbrace>\<lambda>rv. obj_at (Not \<circ> live) ptr\<rbrace>"
apply (rule_tac Q="\<lambda>rv. obj_at (Not \<circ> live0) ptr and obj_at (Not \<circ> hyp_live) ptr" in hoare_strengthen_post)
apply (wpsimp wp: hoare_vcg_conj_lift prepare_thread_delete_unlive_hyp prepare_thread_delete_unlive0)
apply (clarsimp simp: obj_at_def)
apply (clarsimp simp: obj_at_def, case_tac ko, simp_all add: is_tcb_def live_def)
done
lemma (* finalise_cap_replaceable *) [Finalise_AI_asms]:
"\<lbrace>\<lambda>s. s \<turnstile> cap \<and> x = is_final_cap' cap s \<and> valid_mdb s
\<and> cte_wp_at ((=) cap) sl s \<and> valid_objs s \<and> sym_refs (state_refs_of s)
\<and> (cap_irqs cap \<noteq> {} \<longrightarrow> if_unsafe_then_cap s \<and> valid_global_refs s)
\<and> (is_arch_cap cap \<longrightarrow> pspace_aligned s \<and>
valid_vspace_objs s \<and>
valid_arch_state s \<and>
valid_arch_caps s)\<rbrace>
finalise_cap cap x
\<lbrace>\<lambda>rv s. replaceable s sl (fst rv) cap\<rbrace>"
apply (cases "is_arch_cap cap")
apply (clarsimp simp: is_cap_simps)
apply (wp arch_finalise_cap_replaceable)
apply (clarsimp simp: replaceable_def reachable_frame_cap_def
o_def cap_range_def valid_arch_state_def
ran_tcb_cap_cases is_cap_simps
gen_obj_refs_subset vs_cap_ref_def
all_bool_eq)
apply (cases cap;
simp add: replaceable_def reachable_frame_cap_def is_arch_cap_def
split del: if_split;
((wp suspend_unlive[unfolded o_def]
suspend_final_cap[where sl=sl]
prepare_thread_delete_unlive[unfolded o_def]
unbind_maybe_notification_not_bound
get_simple_ko_ko_at unbind_notification_valid_objs
| clarsimp simp: o_def dom_tcb_cap_cases_lt_ARCH
ran_tcb_cap_cases is_cap_simps
cap_range_def unat_of_bl_length
can_fast_finalise_def
gen_obj_refs_subset
vs_cap_ref_def
valid_ipc_buffer_cap_def
dest!: tcb_cap_valid_NullCapD
split: Structures_A.thread_state.split_asm
| simp cong: conj_cong
| simp cong: rev_conj_cong add: no_cap_to_obj_with_diff_ref_Null
| (strengthen tcb_cap_valid_imp_NullCap tcb_cap_valid_imp', wp)
| rule conjI
| erule cte_wp_at_weakenE tcb_cap_valid_imp'[rule_format, rotated -1]
| erule(1) no_cap_to_obj_with_diff_ref_finalI_ARCH
| (wp (once) hoare_drop_imps,
wp (once) cancel_all_ipc_unlive[unfolded o_def]
cancel_all_signals_unlive[unfolded o_def])
| ((wp (once) hoare_drop_imps)?,
(wp (once) hoare_drop_imps)?,
wp (once) deleting_irq_handler_empty)
| wpc
| simp add: valid_cap_simps is_nondevice_page_cap_simps)+))
done
lemma (* deleting_irq_handler_cte_preserved *)[Finalise_AI_asms]:
assumes x: "\<And>cap. P cap \<Longrightarrow> \<not> can_fast_finalise cap"
shows "\<lbrace>cte_wp_at P p\<rbrace> deleting_irq_handler irq \<lbrace>\<lambda>rv. cte_wp_at P p\<rbrace>"
apply (simp add: deleting_irq_handler_def)
apply (wp cap_delete_one_cte_wp_at_preserved | simp add: x)+
done
lemma arch_thread_set_cte_wp_at[wp]:
"\<lbrace>\<lambda>s. P (cte_wp_at P' p s)\<rbrace> arch_thread_set f t \<lbrace> \<lambda>_ s. P (cte_wp_at P' p s)\<rbrace>"
apply (simp add: arch_thread_set_def)
apply (wp set_object_wp)
apply (clarsimp dest!: get_tcb_SomeD simp del: fun_upd_apply)
apply (subst get_tcb_rev, assumption, subst option.sel)+
apply (subst arch_tcb_update_aux3)
apply (subst cte_wp_at_update_some_tcb[where f="tcb_arch_update f"])
apply (clarsimp simp: tcb_cnode_map_def)+
done
crunch cte_wp_at[wp,Finalise_AI_asms]: prepare_thread_delete "\<lambda>s. P (cte_wp_at P' p s)"
crunch cte_wp_at[wp,Finalise_AI_asms]: arch_finalise_cap "\<lambda>s. P (cte_wp_at P' p s)"
(simp: crunch_simps assertE_def wp: crunch_wps set_object_cte_at
ignore: arch_thread_set)
end
interpretation Finalise_AI_1?: Finalise_AI_1
proof goal_cases
interpret Arch .
case 1 show ?case by (intro_locales; (unfold_locales; fact Finalise_AI_asms)?)
qed
context Arch begin global_naming RISCV64
lemma fast_finalise_replaceable[wp]:
"\<lbrace>\<lambda>s. s \<turnstile> cap \<and> x = is_final_cap' cap s
\<and> cte_wp_at ((=) cap) sl s \<and> valid_asid_table s
\<and> valid_mdb s \<and> valid_objs s \<and> sym_refs (state_refs_of s)\<rbrace>
fast_finalise cap x
\<lbrace>\<lambda>rv s. cte_wp_at (replaceable s sl cap.NullCap) sl s\<rbrace>"
apply (cases "cap_irqs cap = {}")
apply (simp add: fast_finalise_def2)
apply wp
apply (rule hoare_strengthen_post)
apply (rule hoare_vcg_conj_lift)
apply (rule finalise_cap_replaceable[where sl=sl])
apply (rule finalise_cap_equal_cap[where sl=sl])
apply (clarsimp simp: cte_wp_at_caps_of_state)
apply wp
apply (clarsimp simp: is_cap_simps can_fast_finalise_def)
apply (clarsimp simp: cap_irqs_def cap_irq_opt_def split: cap.split_asm)
done
global_naming Arch
lemma (* cap_delete_one_invs *) [Finalise_AI_asms,wp]:
"\<lbrace>invs and emptyable ptr\<rbrace> cap_delete_one ptr \<lbrace>\<lambda>rv. invs\<rbrace>"
apply (simp add: cap_delete_one_def unless_def is_final_cap_def)
apply (rule hoare_pre)
apply (wp empty_slot_invs get_cap_wp)
apply clarsimp
apply (drule cte_wp_at_valid_objs_valid_cap, fastforce+)
done
end
interpretation Finalise_AI_2?: Finalise_AI_2
proof goal_cases
interpret Arch .
case 1 show ?case by (intro_locales; (unfold_locales; fact Finalise_AI_asms)?)
qed
context Arch begin global_naming RISCV64
crunch irq_node[Finalise_AI_asms,wp]: prepare_thread_delete "\<lambda>s. P (interrupt_irq_node s)"
crunch irq_node[wp]: arch_finalise_cap "\<lambda>s. P (interrupt_irq_node s)"
(simp: crunch_simps wp: crunch_wps)
crunch pred_tcb_at[wp]:
delete_asid_pool, delete_asid, unmap_page_table, unmap_page
"pred_tcb_at proj P t"
(simp: crunch_simps wp: crunch_wps test)
crunch pred_tcb_at[wp_unsafe]: arch_finalise_cap "pred_tcb_at proj P t"
(simp: crunch_simps wp: crunch_wps)
definition
replaceable_or_arch_update :: "'z::state_ext state \<Rightarrow> cslot_ptr \<Rightarrow> cap \<Rightarrow> cap \<Rightarrow> bool" where
"replaceable_or_arch_update \<equiv> \<lambda>s slot cap cap'.
if is_frame_cap cap
then is_arch_update cap cap' \<and>
(\<forall>asid vref. vs_cap_ref cap' = Some (asid,vref) \<longrightarrow>
vs_cap_ref cap = Some (asid,vref) \<and>
obj_refs cap = obj_refs cap' \<or>
(\<forall>oref\<in>obj_refs cap'. \<forall>level. vs_lookup_target level asid vref s \<noteq> Some (level, oref)))
else replaceable s slot cap cap'"
lemma is_final_cap_pt_asid_eq:
"is_final_cap' (ArchObjectCap (PageTableCap p y)) s \<Longrightarrow>
is_final_cap' (ArchObjectCap (PageTableCap p x)) s"
apply (clarsimp simp: is_final_cap'_def gen_obj_refs_def)
done
lemma is_final_cap_pd_asid_eq:
"is_final_cap' (ArchObjectCap (PageTableCap p y)) s \<Longrightarrow>
is_final_cap' (ArchObjectCap (PageTableCap p x)) s"
by (rule is_final_cap_pt_asid_eq)
lemma cte_wp_at_obj_refs_singleton_page_table:
"\<lbrakk>cte_wp_at
(\<lambda>cap'. obj_refs cap' = {p}
\<and> (\<exists>p asid. cap' = ArchObjectCap (PageTableCap p asid)))
(a, b) s\<rbrakk> \<Longrightarrow>
\<exists>asid. cte_wp_at ((=) (ArchObjectCap (PageTableCap p asid))) (a,b) s"
apply (clarsimp simp: cte_wp_at_def)
done
lemma final_cap_pt_slot_eq:
"\<lbrakk>is_final_cap' (ArchObjectCap (PageTableCap p asid)) s;
cte_wp_at ((=) (ArchObjectCap (PageTableCap p asid'))) slot s;
cte_wp_at ((=) (ArchObjectCap (PageTableCap p asid''))) slot' s\<rbrakk> \<Longrightarrow>
slot' = slot"
apply (clarsimp simp:is_final_cap'_def2)
apply (case_tac "(a,b) = slot'")
apply (case_tac "(a,b) = slot")
apply simp
apply (erule_tac x="fst slot" in allE)
apply (erule_tac x="snd slot" in allE)
apply (clarsimp simp: gen_obj_refs_def cap_irqs_def cte_wp_at_def)
apply (erule_tac x="fst slot'" in allE)
apply (erule_tac x="snd slot'" in allE)
apply (clarsimp simp: gen_obj_refs_def cap_irqs_def cte_wp_at_def)
done
lemma is_arch_update_reset_page:
"is_arch_update
(ArchObjectCap (FrameCap p r sz dev m))
(ArchObjectCap (FrameCap p r' sz dev m'))"
apply (simp add: is_arch_update_def is_arch_cap_def cap_master_cap_def)
done
crunch caps_of_state [wp]: arch_finalise_cap "\<lambda>s. P (caps_of_state s)"
(wp: crunch_wps simp: crunch_simps)
lemma set_vm_root_empty[wp]:
"\<lbrace>\<lambda>s. P (obj_at (empty_table S) p s)\<rbrace> set_vm_root v \<lbrace>\<lambda>_ s. P (obj_at (empty_table S) p s) \<rbrace>"
apply (simp add: set_vm_root_def)
apply (wpsimp wp: get_cap_wp)
done
lemma set_asid_pool_empty[wp]:
"\<lbrace>obj_at (empty_table S) word\<rbrace> set_asid_pool x2 pool' \<lbrace>\<lambda>xb. obj_at (empty_table S) word\<rbrace>"
by (wpsimp wp: set_object_wp simp: set_asid_pool_def obj_at_def empty_table_def)
lemma delete_asid_empty_table_pt[wp]:
"delete_asid a word \<lbrace>\<lambda>s. obj_at (empty_table S) word s\<rbrace>"
apply (simp add: delete_asid_def)
apply wpsimp
done
lemma ucast_less_shiftl_helper3:
"\<lbrakk> len_of TYPE('b) + 3 < len_of TYPE('a); 2 ^ (len_of TYPE('b) + 3) \<le> n\<rbrakk>
\<Longrightarrow> (ucast (x :: 'b::len word) << 3) < (n :: 'a::len word)"
apply (erule order_less_le_trans[rotated])
using ucast_less[where x=x and 'a='a]
apply (simp only: shiftl_t2n field_simps)
apply (rule word_less_power_trans2; simp)
done
lemma caps_of_state_aligned_page_table:
"\<lbrakk>caps_of_state s slot = Some (ArchObjectCap (PageTableCap word option)); invs s\<rbrakk>
\<Longrightarrow> is_aligned word pt_bits"
apply (frule caps_of_state_valid)
apply (frule invs_valid_objs, assumption)
apply (frule valid_cap_aligned)
apply (simp add: cap_aligned_def pt_bits_def pageBits_def)
done
end
lemma invs_valid_arch_capsI:
"invs s \<Longrightarrow> valid_arch_caps s"
by (simp add: invs_def valid_state_def)
context Arch begin global_naming RISCV64 (*FIXME: arch_split*)
lemma do_machine_op_reachable_pg_cap[wp]:
"\<lbrace>\<lambda>s. P (reachable_frame_cap cap s)\<rbrace>
do_machine_op mo
\<lbrace>\<lambda>rv s. P (reachable_frame_cap cap s)\<rbrace>"
apply (simp add:reachable_frame_cap_def reachable_target_def)
apply (wp_pre, wps dmo.vs_lookup_pages, wpsimp)
apply simp
done
lemma replaceable_or_arch_update_pg:
" (case (vs_cap_ref (ArchObjectCap (FrameCap word fun vm_pgsz dev y))) of None \<Rightarrow> True | Some (asid,vref) \<Rightarrow>
\<forall>level. vs_lookup_target level asid vref s \<noteq> Some (level, word))
\<longrightarrow> replaceable_or_arch_update s slot (ArchObjectCap (FrameCap word fun vm_pgsz dev None))
(ArchObjectCap (FrameCap word fun vm_pgsz dev y))"
unfolding replaceable_or_arch_update_def
apply (auto simp: is_cap_simps is_arch_update_def cap_master_cap_simps)
done
global_naming Arch
crunch invs[wp]: prepare_thread_delete invs
(ignore: set_object)
lemma (* finalise_cap_invs *)[Finalise_AI_asms]:
shows "\<lbrace>invs and cte_wp_at ((=) cap) slot\<rbrace> finalise_cap cap x \<lbrace>\<lambda>rv. invs\<rbrace>"
apply (cases cap, simp_all split del: if_split)
apply (wp cancel_all_ipc_invs cancel_all_signals_invs unbind_notification_invs
unbind_maybe_notification_invs
| simp add: o_def split del: if_split cong: if_cong
| wpc )+
apply clarsimp (* thread *)
apply (frule cte_wp_at_valid_objs_valid_cap, clarsimp)
apply (clarsimp simp: valid_cap_def)
apply (frule(1) valid_global_refsD[OF invs_valid_global_refs])
apply (simp add: global_refs_def, rule disjI1, rule refl)
apply (simp add: cap_range_def)
apply (wp deleting_irq_handler_invs | simp | intro conjI impI)+
apply (auto dest: cte_wp_at_valid_objs_valid_cap)
done
lemma (* finalise_cap_irq_node *)[Finalise_AI_asms]:
"\<lbrace>\<lambda>s. P (interrupt_irq_node s)\<rbrace> finalise_cap a b \<lbrace>\<lambda>_ s. P (interrupt_irq_node s)\<rbrace>"
apply (case_tac a,simp_all)
apply (wp | clarsimp)+
done
lemmas (*arch_finalise_cte_irq_node *) [wp,Finalise_AI_asms]
= hoare_use_eq_irq_node [OF arch_finalise_cap_irq_node arch_finalise_cap_cte_wp_at]
lemma (* deleting_irq_handler_st_tcb_at *) [Finalise_AI_asms]:
"\<lbrace>st_tcb_at P t and K (\<forall>st. simple st \<longrightarrow> P st)\<rbrace>
deleting_irq_handler irq
\<lbrace>\<lambda>rv. st_tcb_at P t\<rbrace>"
apply (simp add: deleting_irq_handler_def)
apply (wp cap_delete_one_st_tcb_at)
apply simp
done
lemma irq_node_global_refs_ARCH [Finalise_AI_asms]:
"interrupt_irq_node s irq \<in> global_refs s"
by (simp add: global_refs_def)
lemma (* get_irq_slot_fast_finalisable *)[wp,Finalise_AI_asms]:
"\<lbrace>invs\<rbrace> get_irq_slot irq \<lbrace>cte_wp_at can_fast_finalise\<rbrace>"
apply (simp add: get_irq_slot_def)
apply wp
apply (clarsimp simp: invs_def valid_state_def valid_irq_node_def)
apply (drule spec[where x=irq], drule cap_table_at_cte_at[where offset="[]"])
apply simp
apply (clarsimp simp: cte_wp_at_caps_of_state)
apply (case_tac "cap = cap.NullCap")
apply (simp add: can_fast_finalise_def)
apply (frule(1) if_unsafe_then_capD [OF caps_of_state_cteD])
apply simp
apply (clarsimp simp: ex_cte_cap_wp_to_def)
apply (drule cte_wp_at_norm, clarsimp)
apply (drule(1) valid_global_refsD [OF _ _ irq_node_global_refs_ARCH[where irq=irq]])
apply (case_tac c, simp_all)
apply (clarsimp simp: cap_range_def)
apply (clarsimp simp: cap_range_def)
apply (clarsimp simp: appropriate_cte_cap_def can_fast_finalise_def split: cap.split_asm)
apply (clarsimp simp: cap_range_def)
done
lemma (* replaceable_or_arch_update_same *) [Finalise_AI_asms]:
"replaceable_or_arch_update s slot cap cap"
by (clarsimp simp: replaceable_or_arch_update_def
replaceable_def is_arch_update_def is_cap_simps)
lemma (* replace_cap_invs_arch_update *)[Finalise_AI_asms]:
"\<lbrace>\<lambda>s. cte_wp_at (replaceable_or_arch_update s p cap) p s
\<and> invs s
\<and> cap \<noteq> cap.NullCap
\<and> ex_cte_cap_wp_to (appropriate_cte_cap cap) p s
\<and> s \<turnstile> cap\<rbrace>
set_cap cap p
\<lbrace>\<lambda>rv s. invs s\<rbrace>"
apply (simp add:replaceable_or_arch_update_def)
apply (cases "is_frame_cap cap")
apply (wp hoare_pre_disj[OF arch_update_cap_invs_unmap_page arch_update_cap_invs_map])
apply (simp add:replaceable_or_arch_update_def replaceable_def cte_wp_at_caps_of_state)
apply (clarsimp simp: cte_wp_at_caps_of_state is_cap_simps gen_obj_refs_def
cap_master_cap_simps is_arch_update_def)
apply (wp replace_cap_invs)
apply simp
done
lemma dmo_pred_tcb_at[wp]:
"do_machine_op mop \<lbrace>\<lambda>s. P (pred_tcb_at f Q t s)\<rbrace>"
apply (simp add: do_machine_op_def split_def)
apply (wp select_wp)
apply (clarsimp simp: pred_tcb_at_def obj_at_def)
done
lemma dmo_tcb_cap_valid_ARCH [Finalise_AI_asms]:
"do_machine_op mop \<lbrace>\<lambda>s. P (tcb_cap_valid cap ptr s)\<rbrace>"
apply (simp add: tcb_cap_valid_def no_cap_to_obj_with_diff_ref_def)
apply (wp_pre, wps, rule hoare_vcg_prop)
apply simp
done
lemma dmo_vs_lookup_target[wp]:
"do_machine_op mop \<lbrace>\<lambda>s. P (vs_lookup_target level asid vref s)\<rbrace>"
by (rule dmo.vs_lookup_pages)
lemma dmo_reachable_target[wp]:
"do_machine_op mop \<lbrace>\<lambda>s. P (reachable_target ref p s)\<rbrace>"
apply (simp add: reachable_target_def split_def)
apply (wp_pre, wps, wp)
apply simp
done
lemma (* dmo_replaceable_or_arch_update *) [Finalise_AI_asms,wp]:
"\<lbrace>\<lambda>s. replaceable_or_arch_update s slot cap cap'\<rbrace>
do_machine_op mo
\<lbrace>\<lambda>r s. replaceable_or_arch_update s slot cap cap'\<rbrace>"
unfolding replaceable_or_arch_update_def replaceable_def no_cap_to_obj_with_diff_ref_def
replaceable_final_arch_cap_def replaceable_non_final_arch_cap_def
apply (wp_pre, wps dmo_tcb_cap_valid_ARCH do_machine_op_reachable_pg_cap)
apply (rule hoare_vcg_prop)
apply simp
done
end
context begin interpretation Arch .
requalify_consts replaceable_or_arch_update
end
interpretation Finalise_AI_3?: Finalise_AI_3
where replaceable_or_arch_update = replaceable_or_arch_update
proof goal_cases
interpret Arch .
case 1 show ?case by (intro_locales; (unfold_locales; fact Finalise_AI_asms)?)
qed
context Arch begin global_naming RISCV64
lemma typ_at_data_at_wp:
assumes typ_wp: "\<And>a.\<lbrace>typ_at a p \<rbrace> g \<lbrace>\<lambda>s. typ_at a p\<rbrace>"
shows "\<lbrace>data_at b p\<rbrace> g \<lbrace>\<lambda>s. data_at b p\<rbrace>"
apply (simp add: data_at_def)
apply (wp typ_wp hoare_vcg_disj_lift)
done
end
interpretation Finalise_AI_4?: Finalise_AI_4
where replaceable_or_arch_update = replaceable_or_arch_update
proof goal_cases
interpret Arch .
case 1 show ?case by (intro_locales; (unfold_locales; fact Finalise_AI_asms)?)
qed
context Arch begin global_naming RISCV64
lemma set_asid_pool_obj_at_ptr:
"\<lbrace>\<lambda>s. P (ArchObj (arch_kernel_obj.ASIDPool mp))\<rbrace>
set_asid_pool ptr mp
\<lbrace>\<lambda>rv s. obj_at P ptr s\<rbrace>"
apply (simp add: set_asid_pool_def set_object_def)
apply (wp get_object_wp)
apply (clarsimp simp: obj_at_def)
done
locale_abbrev
"asid_table_update asid ap s \<equiv>
s\<lparr>arch_state := arch_state s\<lparr>riscv_asid_table := riscv_asid_table (arch_state s)(asid \<mapsto> ap)\<rparr>\<rparr>"
lemma valid_table_caps_table [simp]:
"valid_table_caps (s\<lparr>arch_state := arch_state s\<lparr>riscv_asid_table := table'\<rparr>\<rparr>) = valid_table_caps s"
by (simp add: valid_table_caps_def)
lemma valid_kernel_mappings [iff]:
"valid_kernel_mappings (s\<lparr>arch_state := arch_state s\<lparr>riscv_asid_table := table'\<rparr>\<rparr>) = valid_kernel_mappings s"
by (simp add: valid_kernel_mappings_def)
crunches unmap_page_table, store_pte, delete_asid_pool, copy_global_mappings
for valid_cap[wp]: "valid_cap c"
(wp: mapM_wp_inv mapM_x_wp' simp: crunch_simps)
lemmas delete_asid_typ_ats[wp] = abs_typ_at_lifts [OF delete_asid_typ_at]
lemma arch_finalise_cap_valid_cap[wp]:
"arch_finalise_cap cap b \<lbrace>valid_cap c\<rbrace>"
unfolding arch_finalise_cap_def
by (wpsimp split: arch_cap.split option.split bool.split)
global_naming Arch
lemmas clearMemory_invs[wp,Finalise_AI_asms] = clearMemory_invs
lemma valid_idle_has_null_cap_ARCH[Finalise_AI_asms]:
"\<lbrakk> if_unsafe_then_cap s; valid_global_refs s; valid_idle s; valid_irq_node s;
caps_of_state s (idle_thread s, v) = Some cap \<rbrakk>
\<Longrightarrow> cap = NullCap"
apply (rule ccontr)
apply (drule(1) if_unsafe_then_capD[OF caps_of_state_cteD])
apply clarsimp
apply (clarsimp simp: ex_cte_cap_wp_to_def cte_wp_at_caps_of_state)
apply (frule(1) valid_global_refsD2)
apply (case_tac capa, simp_all add: cap_range_def global_refs_def)[1]
apply (clarsimp simp: valid_irq_node_def valid_idle_def pred_tcb_at_def
obj_at_def is_cap_table_def)
apply (rename_tac word tcb)
apply (drule_tac x=word in spec, simp)
done
lemma (* zombie_cap_two_nonidles *)[Finalise_AI_asms]:
"\<lbrakk> caps_of_state s ptr = Some (Zombie ptr' zbits n); invs s \<rbrakk>
\<Longrightarrow> fst ptr \<noteq> idle_thread s \<and> ptr' \<noteq> idle_thread s"
apply (frule valid_global_refsD2, clarsimp+)
apply (simp add: cap_range_def global_refs_def)
apply (cases ptr, auto dest: valid_idle_has_null_cap_ARCH[rotated -1])[1]
done
crunches empty_slot, finalise_cap, send_ipc, receive_ipc
for ioports[wp]: valid_ioports
(wp: crunch_wps valid_ioports_lift simp: crunch_simps ignore: set_object)
lemma arch_derive_cap_notzombie[wp]:
"\<lbrace>\<top>\<rbrace> arch_derive_cap acap \<lbrace>\<lambda>rv s. \<not> is_zombie rv\<rbrace>, -"
by (cases acap; wpsimp simp: arch_derive_cap_def is_zombie_def o_def)
lemma arch_derive_cap_notIRQ[wp]:
"\<lbrace>\<top>\<rbrace> arch_derive_cap cap \<lbrace>\<lambda>rv s. rv \<noteq> cap.IRQControlCap\<rbrace>,-"
by (cases cap; wpsimp simp: arch_derive_cap_def o_def)
end
interpretation Finalise_AI_5?: Finalise_AI_5
where replaceable_or_arch_update = replaceable_or_arch_update
proof goal_cases
interpret Arch .
case 1 show ?case by (intro_locales; (unfold_locales; fact Finalise_AI_asms)?)
qed
end
|
subroutine radass(atm,res,rnum,chn,rad,norad)
c
c here the actual assignment from the hash tables is made
include "qdiffpar4.h"
c
character*3 tres
character*6 tatm
character*1 achn
character*3 ares
character*4 arnum
c
norad=0
call rfind(atm,res,rnum,chn,ifind,n)
if(ifind.eq.0) then
achn = ' '
call rfind(atm,res,rnum,achn,ifind,n)
if(ifind.eq.0) then
arnum = ' '
call rfind(atm,res,arnum,achn,ifind,n)
if(ifind.eq.0) then
ares = ' '
call rfind(atm,ares,arnum,achn,ifind,n)
if(ifind.eq.0) then
tatm = atm(1:1)//' '
call rfind(tatm,ares,arnum,achn,ifind,n)
if(ifind.eq.0) then
norad=1
n=1
end if
end if
end if
end if
end if
c
rad = radt(n)
c
return
end
|
program opkdemo7
c-----------------------------------------------------------------------
c Demonstration program for the DLSODI package.
c This is the version of 14 June 2001.
c
c This version is in double precision.
c
C this program solves a semi-discretized form of the Burgers equation,
c
c u = -(u*u/2) + eta * u
c t x xx
c
c for a = -1 .le. x .le. 1 = b, t .ge. 0.
c Here eta = 0.05.
c Boundary conditions: u(-1,t) = u(1,t) = 0.
c Initial profile: square wave
c u(0,x) = 0 for 1/2 .lt. abs(x) .le. 1
c u(0,x) = 1/2 for abs(x) = 1/2
c u(0,x) = 1 for 0 .le. abs(x) .lt. 1/2
c
c An ODE system is generated by a simplified Galerkin treatment
c of the spatial variable x.
c
c Reference:
c R. C. Y. Chin, G. W. Hedstrom, and K. E. Karlsson,
c A Simplified Galerkin Method for Hyperbolic Equations,
c Math. Comp., vol. 33, no. 146 (April 1979), pp. 647-658.
c
c The problem is run with the DLSODI package with a 10-point mesh
c and a 100-point mesh. In each case, it is run with two tolerances
c and for various appropriate values of the method flag mf.
c Output is on unit lout, set to 6 in a data statement below.
c-----------------------------------------------------------------------
external res, addabd, addafl, jacbd, jacfl
integer i, io, istate, itol, iwork, j,
1 lout, liw, lrw, meth, miter, mf, ml, mu,
2 n, nout, npts, nerr,
3 nptsm1, n14, n34, n14m1, n14p1, n34m1, n34p1
integer nm1
double precision a, b, eta, delta,
1 zero, fourth, half, one, hun,
2 t, tout, tlast, tinit, errfac,
3 atol, rtol, rwork, y, ydoti, elkup
double precision eodsq, r4d
dimension n(1)
dimension y(99), ydoti(99), tout(4), atol(2), rtol(2)
dimension rwork(2002), iwork(125)
c Pass problem parameters in the Common block test1.
common /test1/ r4d, eodsq, nm1
c
c Set problem parameters and run parameters
data eta/0.05d0/, a/-1.0d0/, b/1.0d0/
data zero/0.0d0/, fourth/0.25d0/, half/.5d0/, one/1.0d0/,
1 hun/100.0d0/
data tinit/0.0d0/, tlast/0.4d0/
data tout/.10d0,.20d0,.30d0,.40d0/
data ml/1/, mu/1/, lout/6/
data nout/4/, lrw/2002/, liw/125/
data itol/1/, rtol/1.0d-3, 1.0d-6/, atol/1.0d-3, 1.0d-6/
c
iwork(1) = ml
iwork(2) = mu
nerr = 0
c
c Loop over two values of npts.
do 300 npts = 10, 100, 90
c
c Compute the mesh width delta and other parameters.
delta = (b - a)/npts
r4d = fourth/delta
eodsq = eta/delta**2
nptsm1 = npts - 1
n14 = npts/4
n34 = 3 * n14
n14m1 = n14 - 1
n14p1 = n14m1 + 2
n34m1 = n34 - 1
n34p1 = n34m1 + 2
n(1) = nptsm1
nm1 = n(1) - 1
c
c Set the initial profile (for output purposes only).
c
do 10 i = 1,n14m1
10 y(i) = zero
y(n14) = half
do 20 i = n14p1,n34m1
20 y(i) = one
y(n34) = half
do 30 i = n34p1,nptsm1
30 y(i) = zero
c
if (npts .gt. 10) write (lout,1010)
write (lout,1000)
write (lout,1100) eta,a,b,tinit,tlast,ml,mu,n(1)
write (lout,1200) zero, (y(i), i=1,n(1)), zero
c
c The j loop is over error tolerances.
c
do 200 j = 1,2
c
c Loop over method flag loop (for demonstration).
c
do 100 meth = 1,2
do 100 miter = 1,5
if (miter .eq. 3) go to 100
if (miter .le. 2 .and. npts .gt. 10) go to 100
if (miter .eq. 5 .and. npts .lt. 100) go to 100
mf = 10*meth + miter
c
c Set the initial profile.
c
do 40 i = 1,n14m1
40 y(i) = zero
y(n14) = half
do 50 i = n14p1,n34m1
50 y(i) = one
y(n34) = half
do 60 i = n34p1,nptsm1
60 y(i) = zero
c
t = tinit
istate = 0
c
write (lout,1500) rtol(j), atol(j), mf, npts
c
c Output loop for each case
c
do 80 io = 1,nout
c
c call DLSODI
if (miter .le. 2) call dlsodi (res, addafl, jacfl, n, y,
1 ydoti, t, tout(io), itol, rtol(j), atol(j),
2 1, istate, 0, rwork, lrw, iwork, liw, mf)
if (miter .ge. 4) call dlsodi (res, addabd, jacbd, n, y,
1 ydoti, t, tout(io), itol, rtol(j), atol(j),
2 1, istate, 0, rwork, lrw, iwork, liw, mf)
write (lout,2000) t, rwork(11), iwork(14),(y(i), i=1,n(1))
c
c If istate is not 2 on return, print message and loop.
if (istate .ne. 2) then
write (lout,4000) mf, t, istate
nerr = nerr + 1
go to 100
endif
c
80 continue
c
write (lout,3000) mf, iwork(11), iwork(12), iwork(13),
1 iwork(17), iwork(18)
c
c Estimate final error and print result.
itemp = n(1)
errfac = elkup( itemp, y, rwork(21), itol, rtol(j), atol(j) )
if (errfac .gt. hun) then
write (lout,5001) errfac
nerr = nerr + 1
else
write (lout,5000) errfac
endif
100 continue
200 continue
300 continue
c
write (lout,6000) nerr
c stop
c
1000 format(20x,' Demonstration Problem for DLSODI')
1010 format(///80('*')///)
1100 format(/10x,' Simplified Galerkin Solution of Burgers Equation'//
1 13x,'Diffusion coefficient is eta =',d10.2/
2 13x,'Uniform mesh on interval',d12.3,' to ',d12.3/
3 13x,'Zero boundary conditions'/
4 13x,'Time limits: t0 = ',d12.5,' tlast = ',d12.5/
5 13x,'Half-bandwidths ml = ',i2,' mu = ',i2/
6 13x,'System size neq = ',i3/)
c
1200 format('Initial profile:'/17(6d12.4/))
c
1500 format(///80('-')///'Run with rtol =',d12.2,' atol =',d12.2,
1 ' mf =',i3,' npts =',i4,':'//)
c
2000 format('Output for time t = ',d12.5,' current h =',
1 d12.5,' current order =',i2,':'/17(6d12.4/))
c
3000 format(//'Final statistics for mf = ',i2,':'/
1 i4,' steps,',i5,' res,',i4,' Jacobians,',
2 ' rwork size =',i6,', iwork size =',i6)
c
4000 format(///80('*')//20x,'Final time reached for mf = ',i2,
1 ' was t = ',d12.5/25x,'at which istate = ',i2////80('*'))
5000 format(' Final output is correct to within ',d8.1,
1 ' times local error tolerance')
5001 format(' Final output is wrong by ',d8.1,
1 ' times local error tolerance')
6000 format(//80('*')//
1 'Run completed. Number of errors encountered =',i3)
c
c end of main program for the DLSODI demonstration problem.
end
|
{-# OPTIONS --without-K --rewriting #-}
open import lib.Base
open import lib.PathFunctor
open import lib.PathGroupoid
open import lib.path-seq.Reasoning
module lib.path-seq.Ap where
module _ {i j} {A : Type i} {B : Type j} (f : A → B) where
ap-seq : {a a' : A} → a =-= a' → f a =-= f a'
ap-seq [] = []
ap-seq (p ◃∙ s) = ap f p ◃∙ ap-seq s
private
ap-seq-∙-= : {a a' : A} → (s : a =-= a')
→ ap f (↯ s) == ↯ (ap-seq s)
ap-seq-∙-= [] = idp
ap-seq-∙-= (p ◃∙ []) = idp
ap-seq-∙-= (idp ◃∙ s@(_ ◃∙ _)) = ap-seq-∙-= s
ap-seq-∙ : {a a' : A} (s : a =-= a')
→ (ap f (↯ s) ◃∎) =ₛ ap-seq s
ap-seq-∙ s = =ₛ-in (ap-seq-∙-= s)
∙-ap-seq : {a a' : A} (s : a =-= a')
→ ap-seq s =ₛ (ap f (↯ s) ◃∎)
∙-ap-seq s = !ₛ (ap-seq-∙ s)
ap-seq-=ₛ : {a a' : A} {s t : a =-= a'}
→ s =ₛ t
→ ap-seq s =ₛ ap-seq t
ap-seq-=ₛ {s = s} {t = t} (=ₛ-in p) =
ap-seq s
=ₛ⟨ ∙-ap-seq s ⟩
ap f (↯ s) ◃∎
=ₛ₁⟨ ap (ap f) p ⟩
ap f (↯ t) ◃∎
=ₛ⟨ ap-seq-∙ t ⟩
ap-seq t ∎ₛ
module _ {i j k} {A : Type i} {B : Type j} {C : Type k} (f : A → B → C) where
ap2-seq : {a a' : A} {b b' : B} → a =-= a' → b =-= b' → f a b =-= f a' b'
ap2-seq [] [] = []
ap2-seq {a = a} [] t@(_ ◃∙ _) = ap-seq (f a) t
ap2-seq {b = b} s@(_ ◃∙ _) [] = ap-seq (λ a → f a b) s
ap2-seq (p ◃∙ s) (q ◃∙ t) = ap2 f p q ◃∙ ap2-seq s t
private
ap2-seq-∙-= : {a a' : A} {b b' : B}
(s : a =-= a') (t : b =-= b')
→ ap2 f (↯ s) (↯ t) == ↯ (ap2-seq s t)
ap2-seq-∙-= [] [] = idp
ap2-seq-∙-= {a = a} [] t@(_ ◃∙ _) =
ap2 f idp (↯ t)
=⟨ ap2-idp-l f (↯ t) ⟩
ap (f a) (↯ t)
=⟨ =ₛ-out (ap-seq-∙ (f a) t) ⟩
↯ (ap-seq (f a) t) =∎
ap2-seq-∙-= {b = b} s@(_ ◃∙ _) [] =
ap2 f (↯ s) idp
=⟨ ap2-idp-r f (↯ s) ⟩
ap (λ a → f a b) (↯ s)
=⟨ =ₛ-out (ap-seq-∙ (λ a → f a b) s ) ⟩
↯ (ap-seq (λ a → f a b) s) =∎
ap2-seq-∙-= (p ◃∙ []) (q ◃∙ []) = idp
ap2-seq-∙-= {a' = a'} (p ◃∙ []) (q ◃∙ t@(_ ◃∙ _)) =
ap2 f p (q ∙ ↯ t)
=⟨ ap (λ r → ap2 f r (q ∙ ↯ t)) (! (∙-unit-r p)) ⟩
ap2 f (p ∙ idp) (q ∙ ↯ t)
=⟨ ap2-∙ f p idp q (↯ t) ⟩
ap2 f p q ∙ ap2 f idp (↯ t)
=⟨ ap (ap2 f p q ∙_) (ap2-idp-l f (↯ t)) ⟩
ap2 f p q ∙ ap (f a') (↯ t)
=⟨ ap (ap2 f p q ∙_) (=ₛ-out (ap-seq-∙ (f a') t)) ⟩
ap2 f p q ∙ ↯ (ap-seq (f a') t) =∎
ap2-seq-∙-= {b' = b'} (p ◃∙ s@(_ ◃∙ _)) (q ◃∙ []) =
ap2 f (p ∙ ↯ s) q
=⟨ ap (ap2 f (p ∙ ↯ s)) (! (∙-unit-r q)) ⟩
ap2 f (p ∙ ↯ s) (q ∙ idp)
=⟨ ap2-∙ f p (↯ s) q idp ⟩
ap2 f p q ∙ ap2 f (↯ s) idp
=⟨ ap (ap2 f p q ∙_) (ap2-idp-r f (↯ s)) ⟩
ap2 f p q ∙ ap (λ a → f a b') (↯ s)
=⟨ ap (ap2 f p q ∙_) (=ₛ-out (ap-seq-∙ (λ a → f a b') s)) ⟩
ap2 f p q ∙ ↯ (ap-seq (λ a → f a b') s) =∎
ap2-seq-∙-= (p ◃∙ s@(_ ◃∙ _)) (q ◃∙ t@(_ ◃∙ _)) =
ap2 f (p ∙ ↯ s) (q ∙ ↯ t)
=⟨ ap2-∙ f p (↯ s) q (↯ t) ⟩
ap2 f p q ∙ ap2 f (↯ s) (↯ t)
=⟨ ap (ap2 f p q ∙_) (ap2-seq-∙-= s t) ⟩
ap2 f p q ∙ ↯ (ap2-seq s t) =∎
ap2-seq-∙ : {a a' : A} {b b' : B}
(s : a =-= a') (t : b =-= b')
→ ap2 f (↯ s) (↯ t) ◃∎ =ₛ ap2-seq s t
ap2-seq-∙ s t = =ₛ-in (ap2-seq-∙-= s t)
∙-ap2-seq : {a a' : A} {b b' : B}
(s : a =-= a') (t : b =-= b')
→ ap2-seq s t =ₛ ap2 f (↯ s) (↯ t) ◃∎
∙-ap2-seq s t = !ₛ (ap2-seq-∙ s t)
|
// ======================================================================
/*!
* \file NFmiGdalArea.cpp
* \brief Implementation of class NFmiGdalArea
*/
// ======================================================================
#ifndef DISABLED_GDAL
#include "NFmiGdalArea.h"
#include "NFmiString.h"
#include "NFmiStringTools.h"
#include <boost/functional/hash.hpp>
#include <boost/math/constants/constants.hpp>
#include <gis/CoordinateTransformation.h>
#include <gis/OGR.h>
#include <gis/SpatialReference.h>
#include <macgyver/Exception.h>
#include <cmath>
#include <iomanip>
#include <ogr_spatialref.h>
using namespace std;
// See also NFmiLatLonArea::WKT()
std::string fmiwkt =
R"(GEOGCS["FMI_Sphere",DATUM["FMI_2007",SPHEROID["FMI_Sphere",6371220,0]],PRIMEM["Greenwich",0],UNIT["Degree",0.0174532925199433]])";
// ----------------------------------------------------------------------
/*!
* \brief Destructor does nothing special
*/
// ----------------------------------------------------------------------
NFmiGdalArea::~NFmiGdalArea() = default;
// ----------------------------------------------------------------------
/*!
* \brief Default constructor
*/
// ----------------------------------------------------------------------
NFmiGdalArea::NFmiGdalArea() : NFmiArea(), itsDatum("WGS84") {}
// ----------------------------------------------------------------------
/*!
* \brief Copy constructor
*/
// ----------------------------------------------------------------------
NFmiGdalArea::NFmiGdalArea(const NFmiGdalArea &theArea)
= default;
// ----------------------------------------------------------------------
/*!
* \brief Assignment operator
*/
// ----------------------------------------------------------------------
NFmiGdalArea &NFmiGdalArea::operator=(const NFmiGdalArea &theArea) = default;
// ----------------------------------------------------------------------
/*!
* \brief Construct from user input
*/
// ----------------------------------------------------------------------
NFmiGdalArea::NFmiGdalArea(const std::string &theDatum,
const std::string &theDescription,
const NFmiPoint &theBottomLeftLatLon,
const NFmiPoint &theTopRightLatLon,
const NFmiPoint &theTopLeftXY,
const NFmiPoint &theBottomRightXY,
bool usePacificView)
: NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView),
itsDatum(theDatum),
itsDescription(theDescription),
itsBottomLeftLatLon(theBottomLeftLatLon),
itsTopRightLatLon(theTopRightLatLon),
itsWorldRect()
{
try
{
init();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Construct from user input
*/
// ----------------------------------------------------------------------
NFmiGdalArea::NFmiGdalArea(const std::string &theDatum,
const OGRSpatialReference &theCRS,
const NFmiPoint &theBottomLeftLatLon,
const NFmiPoint &theTopRightLatLon,
const NFmiPoint &theTopLeftXY,
const NFmiPoint &theBottomRightXY,
bool usePacificView)
: NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView),
itsDatum(theDatum),
itsDescription(),
itsBottomLeftLatLon(theBottomLeftLatLon),
itsTopRightLatLon(theTopRightLatLon),
itsWorldRect()
{
try
{
itsProjStr = Fmi::OGR::exportToProj(theCRS);
itsSpatialReference = std::make_shared<Fmi::SpatialReference>(itsProjStr);
// Guess a good value for itsDescription
const char *auth = theCRS.GetAuthorityName(nullptr);
if (auth != nullptr)
{
itsDescription = std::string(auth);
const char *code = theCRS.GetAuthorityCode(nullptr);
if (code != nullptr)
itsDescription += ":" + std::string(code);
}
else
{
itsDescription = Fmi::OGR::exportToWkt(theCRS);
}
init();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Construct from bounding box
*/
// ----------------------------------------------------------------------
NFmiGdalArea::NFmiGdalArea(const std::string &theDatum,
const OGRSpatialReference &theCRS,
double theXmin,
double theYmin,
double theXmax,
double theYmax,
const NFmiPoint &theTopLeftXY,
const NFmiPoint &theBottomRightXY,
bool usePacificView)
: NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView),
itsDatum(theDatum),
itsDescription(),
itsBottomLeftLatLon(),
itsTopRightLatLon(),
itsWorldRect(NFmiPoint(theXmin, theYmin), NFmiPoint(theXmax, theYmax))
{
try
{
itsProjStr = Fmi::OGR::exportToProj(theCRS);
itsSpatialReference = std::make_shared<Fmi::SpatialReference>(itsProjStr);
// Guess a good value for itsDescription
const char *auth = theCRS.GetAuthorityName(nullptr);
if (auth != nullptr)
{
itsDescription = std::string(auth);
const char *code = theCRS.GetAuthorityCode(nullptr);
if (code != nullptr)
itsDescription += ":" + std::string(code);
}
else
{
itsDescription = Fmi::OGR::exportToWkt(theCRS);
}
// The needed spatial references
OGRErr err;
std::shared_ptr<OGRSpatialReference> datum(new OGRSpatialReference);
if (itsDatum == "FMI")
err = datum->SetFromUserInput(fmiwkt.c_str());
else
err = datum->SetFromUserInput(itsDatum.c_str());
if (err != OGRERR_NONE)
throw Fmi::Exception(BCP, "Failed to set datum: '" + itsDatum + "'");
// The needed coordinate transformations
itsWorldXYToLatLonTransformation =
std::make_shared<Fmi::CoordinateTransformation>(*itsSpatialReference, *datum);
itsLatLonToWorldXYTransformation =
std::make_shared<Fmi::CoordinateTransformation>(*datum, *itsSpatialReference);
// Bottom left and top right coordinates - needed only for geographic projections (Width()
// calculations)
// The same data could be extracted from the WorldXYRect too though - and these variables
// would not be needed.
double x1 = theXmin;
double y1 = theYmin;
double x2 = theXmax;
double y2 = theYmax;
itsWorldXYToLatLonTransformation->transform(x1, y1);
itsWorldXYToLatLonTransformation->transform(x2, y2);
itsBottomLeftLatLon = NFmiPoint(x1, y1);
itsTopRightLatLon = NFmiPoint(x2, y2);
// Initialize itsWKT
itsWKT = Fmi::OGR::exportToWkt(*itsSpatialReference);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return class ID
*/
// ----------------------------------------------------------------------
unsigned long NFmiGdalArea::ClassId() const
{
try
{
return kNFmiGdalArea;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return class name
*/
// ----------------------------------------------------------------------
const char *NFmiGdalArea::ClassName() const
{
try
{
return "kNFmiGdalArea";
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return a clone
*/
// ----------------------------------------------------------------------
NFmiArea *NFmiGdalArea::Clone() const
{
try
{
return new NFmiGdalArea(*this);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Area descriptor
*/
// ----------------------------------------------------------------------
const std::string NFmiGdalArea::AreaStr() const
{
try
{
std::ostringstream out;
out << itsDatum << ':' << itsDescription << "|" << BottomLeftLatLon().X() << ","
<< BottomLeftLatLon().Y() << "," << TopRightLatLon().X() << "," << TopRightLatLon().Y();
return out.str();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Datum
*/
// ----------------------------------------------------------------------
const std::string &NFmiGdalArea::Datum() const
{
try
{
return itsDatum;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return the WKT description
*/
// ----------------------------------------------------------------------
const std::string NFmiGdalArea::WKT() const
{
try
{
return itsWKT;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Equality comparison
*/
// ----------------------------------------------------------------------
bool NFmiGdalArea::operator==(const NFmiGdalArea &theArea) const
{
try
{
return (itsBottomLeftLatLon == theArea.itsBottomLeftLatLon &&
itsTopRightLatLon == theArea.itsTopRightLatLon &&
itsWorldRect == theArea.itsWorldRect && itsDescription == theArea.itsDescription &&
itsDatum == theArea.itsDatum);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Inequality comparison
*/
// ----------------------------------------------------------------------
bool NFmiGdalArea::operator!=(const NFmiGdalArea &theArea) const
{
try
{
return !(*this == theArea);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Equality comparison
*/
// ----------------------------------------------------------------------
bool NFmiGdalArea::operator==(const NFmiArea &theArea) const
{
try
{
return *this == static_cast<const NFmiGdalArea &>(theArea);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Inequality comparison
*/
// ----------------------------------------------------------------------
bool NFmiGdalArea::operator!=(const NFmiArea &theArea) const
{
try
{
return !(*this == theArea);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Write the projection definition to a file
*/
// ----------------------------------------------------------------------
std::ostream &NFmiGdalArea::Write(std::ostream &file) const
{
try
{
NFmiString tmp1 = itsDatum;
NFmiString tmp2 = itsDescription;
NFmiArea::Write(file);
file << itsBottomLeftLatLon << itsTopRightLatLon << tmp1 << tmp2;
return file;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Read new projection definition from the input stream
*/
// ----------------------------------------------------------------------
std::istream &NFmiGdalArea::Read(std::istream &file)
{
try
{
NFmiString tmp1;
NFmiString tmp2;
NFmiArea::Read(file);
file >> itsBottomLeftLatLon >> itsTopRightLatLon >> tmp1 >> tmp2;
itsDatum = tmp1.CharPtr();
itsDescription = tmp2.CharPtr();
init();
return file;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief XY coordinate to LatLon
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiGdalArea::ToLatLon(const NFmiPoint &theXYPoint) const
{
try
{
double xscale = Width() / itsWorldRect.Width();
double yscale = Height() / itsWorldRect.Height();
double worldx = itsWorldRect.Left() + (theXYPoint.X() - Left()) / xscale;
double worldy = itsWorldRect.Bottom() - (theXYPoint.Y() - Top()) / yscale;
return WorldXYToLatLon(NFmiPoint(worldx, worldy));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief LatLon to XY-coordinate
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiGdalArea::ToXY(const NFmiPoint &theLatLonPoint) const
{
try
{
NFmiPoint latlon(FixLongitude(theLatLonPoint.X()), theLatLonPoint.Y());
NFmiPoint worldxy = LatLonToWorldXY(latlon);
double xscale = Width() / itsWorldRect.Width();
double yscale = Height() / itsWorldRect.Height();
double x = Left() + xscale * (worldxy.X() - itsWorldRect.Left());
double y = Top() + yscale * (itsWorldRect.Bottom() - worldxy.Y());
return NFmiPoint(x, y);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief XY-coordinate to World coordinates
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiGdalArea::XYToWorldXY(const NFmiPoint &theXYPoint) const
{
try
{
double xscale = Width() / itsWorldRect.Width();
double yscale = Height() / itsWorldRect.Height();
double worldx = itsWorldRect.Left() + (theXYPoint.X() - Left()) / xscale;
double worldy = itsWorldRect.Bottom() - (theXYPoint.Y() - Top()) / yscale;
return NFmiPoint(worldx, worldy);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theWorldXYPoint Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiGdalArea::WorldXYToXY(const NFmiPoint &theWorldXYPoint) const
{
try
{
double xscale = Width() / itsWorldRect.Width();
double yscale = Height() / itsWorldRect.Height();
double x = xscale * (theWorldXYPoint.X() - itsWorldRect.Left()) + Left();
double y = Top() - yscale * (theWorldXYPoint.Y() - itsWorldRect.Bottom());
return NFmiPoint(x, y);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief World coordinates to LatLon
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiGdalArea::WorldXYToLatLon(const NFmiPoint &theXYPoint) const
{
try
{
if (!itsWorldXYToLatLonTransformation)
throw Fmi::Exception(BCP, "Trying to use an uninitialized GDAL area");
double x = theXYPoint.X();
double y = theXYPoint.Y();
if (!itsWorldXYToLatLonTransformation->transform(x, y))
return NFmiPoint(kFloatMissing, kFloatMissing);
return NFmiPoint(x, y);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief LatLon to world coordinates
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiGdalArea::LatLonToWorldXY(const NFmiPoint &theLatLonPoint) const
{
try
{
if (!itsLatLonToWorldXYTransformation)
throw Fmi::Exception(BCP, "Trying to use an uninitialized GDAL area");
double x = theLatLonPoint.X();
double y = theLatLonPoint.Y();
if (!itsLatLonToWorldXYTransformation->transform(x, y))
return NFmiPoint(kFloatMissing, kFloatMissing);
return NFmiPoint(x, y);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return the world rectangle
*/
// ----------------------------------------------------------------------
const NFmiRect NFmiGdalArea::WorldRect() const
{
try
{
return itsWorldRect;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief
*/
// ----------------------------------------------------------------------
NFmiArea *NFmiGdalArea::NewArea(const NFmiPoint &theBottomLeftLatLon,
const NFmiPoint &theTopRightLatLon,
bool allowPacificFix) const
{
try
{
if (allowPacificFix)
{
PacificPointFixerData fix =
NFmiArea::PacificPointFixer(theBottomLeftLatLon, theTopRightLatLon);
return new NFmiGdalArea(itsDatum,
itsDescription,
fix.itsBottomLeftLatlon,
fix.itsTopRightLatlon,
TopLeft(),
BottomRight(),
fix.fIsPacific);
}
return new NFmiGdalArea(itsDatum,
itsDescription,
theBottomLeftLatLon,
theTopRightLatLon,
TopLeft(),
BottomRight(),
PacificView());
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Initialize the projection transformation objects
*/
// ----------------------------------------------------------------------
void NFmiGdalArea::init()
{
try
{
// The needed spatial references
if (!itsSpatialReference)
{
itsProjStr = itsDescription;
itsSpatialReference = std::make_shared<Fmi::SpatialReference>(itsProjStr);
}
OGRErr err;
std::shared_ptr<OGRSpatialReference> datum(new OGRSpatialReference);
if (itsDatum == "FMI")
err = datum->SetFromUserInput(fmiwkt.c_str());
else
err = datum->SetFromUserInput(itsDatum.c_str());
if (err != OGRERR_NONE)
throw Fmi::Exception(BCP, "Failed to set datum: '" + itsDatum + "'");
// The needed coordinate transformations
itsWorldXYToLatLonTransformation =
std::make_shared<Fmi::CoordinateTransformation>(*itsSpatialReference, *datum);
itsLatLonToWorldXYTransformation =
std::make_shared<Fmi::CoordinateTransformation>(*datum, *itsSpatialReference);
// The needed world XY rectangle
itsWorldRect =
NFmiRect(LatLonToWorldXY(itsBottomLeftLatLon), LatLonToWorldXY(itsTopRightLatLon));
// Initialize itsWKT
itsWKT = Fmi::OGR::exportToWkt(*itsSpatialReference);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
double NFmiGdalArea::WorldXYWidth() const
{
try
{
if (!itsSpatialReference->isGeographic())
return WorldRect().Width();
double pi = boost::math::constants::pi<double>();
double circumference = 2 * pi * 6371220;
double dlon = itsTopRightLatLon.X() - itsBottomLeftLatLon.X();
if (dlon < 0)
dlon += 360;
double clat = 0.5 * (itsBottomLeftLatLon.Y() + itsTopRightLatLon.Y());
return dlon / 360 * circumference * cos(clat * pi / 180);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
double NFmiGdalArea::WorldXYHeight() const
{
try
{
if (!itsSpatialReference->isGeographic())
return WorldRect().Height();
double pi = boost::math::constants::pi<double>();
double circumference = 2 * pi * 6371220;
double dlat = itsTopRightLatLon.Y() - itsBottomLeftLatLon.Y();
return dlat / 360.0 * circumference; // angle -> meters
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Hash value
*/
// ----------------------------------------------------------------------
std::size_t NFmiGdalArea::HashValue() const
{
try
{
std::size_t hash = NFmiArea::HashValue();
// some of these may be redundant:
boost::hash_combine(hash, boost::hash_value(itsDatum));
boost::hash_combine(hash, boost::hash_value(itsDescription));
boost::hash_combine(hash, boost::hash_value(itsWKT));
boost::hash_combine(hash, itsBottomLeftLatLon.HashValue());
boost::hash_combine(hash, itsTopRightLatLon.HashValue());
boost::hash_combine(hash, itsWorldRect.HashValue());
return hash;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
#endif // DISABLED_GDAL
// ======================================================================
|
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import order.upper_lower
import topology.sets.closeds
/-!
# Clopen upper sets
In this file we define the type of clopen upper sets.
-/
open set topological_space
variables {α β : Type*} [topological_space α] [has_le α] [topological_space β] [has_le β]
/-! ### Compact open sets -/
/-- The type of clopen upper sets of a topological space. -/
structure clopen_upper_set (α : Type*) [topological_space α] [has_le α] extends clopens α :=
(upper' : is_upper_set carrier)
namespace clopen_upper_set
instance : set_like (clopen_upper_set α) α :=
{ coe := λ s, s.carrier,
coe_injective' := λ s t h, by { obtain ⟨⟨_, _⟩, _⟩ := s, obtain ⟨⟨_, _⟩, _⟩ := t, congr' } }
lemma upper (s : clopen_upper_set α) : is_upper_set (s : set α) := s.upper'
lemma clopen (s : clopen_upper_set α) : is_clopen (s : set α) := s.clopen'
/-- Reinterpret a upper clopen as an upper set. -/
@[simps] def to_upper_set (s : clopen_upper_set α) : upper_set α := ⟨s, s.upper⟩
@[ext] protected lemma ext {s t : clopen_upper_set α} (h : (s : set α) = t) : s = t :=
set_like.ext' h
@[simp] lemma coe_mk (s : clopens α) (h) : (mk s h : set α) = s := rfl
instance : has_sup (clopen_upper_set α) :=
⟨λ s t, ⟨s.to_clopens ⊔ t.to_clopens, s.upper.union t.upper⟩⟩
instance : has_inf (clopen_upper_set α) :=
⟨λ s t, ⟨s.to_clopens ⊓ t.to_clopens, s.upper.inter t.upper⟩⟩
instance : has_top (clopen_upper_set α) := ⟨⟨⊤, is_upper_set_univ⟩⟩
instance : has_bot (clopen_upper_set α) := ⟨⟨⊥, is_upper_set_empty⟩⟩
instance : lattice (clopen_upper_set α) :=
set_like.coe_injective.lattice _ (λ _ _, rfl) (λ _ _, rfl)
instance : bounded_order (clopen_upper_set α) :=
bounded_order.lift (coe : _ → set α) (λ _ _, id) rfl rfl
@[simp] lemma coe_sup (s t : clopen_upper_set α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl
@[simp] lemma coe_inf (s t : clopen_upper_set α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl
@[simp] lemma coe_top : (↑(⊤ : clopen_upper_set α) : set α) = univ := rfl
@[simp]
instance : inhabited (clopen_upper_set α) := ⟨⊥⟩
end clopen_upper_set
|
# Tutorial on Image-based Experimental Modal Analysis
**Klemen Zaletelj$^a$, Domen Gorjup$^a$ and Janko Slavič$^a$\***
$^a$ Faculty of Mechanical Engineering, University of Ljubljana
\* Corresponding email: [email protected]
www.ladisk.si
---
# `github.com/ladisk/ImageBasedModalAnalysisTutorial`
---
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Basic-experimental-skills" data-toc-modified-id="Basic-experimental-skills-1"><span class="toc-item-num">1 </span>Basic experimental skills</a></span><ul class="toc-item"><li><span><a href="#Acquisition-parameters" data-toc-modified-id="Acquisition-parameters-1.1"><span class="toc-item-num">1.1 </span>Acquisition parameters</a></span></li><li><span><a href="#Lighting" data-toc-modified-id="Lighting-1.2"><span class="toc-item-num">1.2 </span>Lighting</a></span></li><li><span><a href="#Surface-preperation" data-toc-modified-id="Surface-preperation-1.3"><span class="toc-item-num">1.3 </span>Surface preperation</a></span></li><li><span><a href="#Possible-errors" data-toc-modified-id="Possible-errors-1.4"><span class="toc-item-num">1.4 </span>Possible errors</a></span><ul class="toc-item"><li><span><a href="#Out-of-focus-image" data-toc-modified-id="Out-of-focus-image-1.4.1"><span class="toc-item-num">1.4.1 </span>Out of focus image</a></span></li><li><span><a href="#Improper-lighting" data-toc-modified-id="Improper-lighting-1.4.2"><span class="toc-item-num">1.4.2 </span>Improper lighting</a></span></li></ul></li></ul></li><li><span><a href="#Simplified-Optical-flow-Method" data-toc-modified-id="Simplified-Optical-flow-Method-2"><span class="toc-item-num">2 </span>Simplified Optical-flow Method</a></span></li><li><span><a href="#The-Lucas-Kanade-Method" data-toc-modified-id="The-Lucas-Kanade-Method-3"><span class="toc-item-num">3 </span>The Lucas-Kanade Method</a></span></li><li><span><a href="#Frequency-Response-Functions" data-toc-modified-id="Frequency-Response-Functions-4"><span class="toc-item-num">4 </span>Frequency Response Functions</a></span></li><li><span><a href="#Modal-Analysis---camera-data,-only" data-toc-modified-id="Modal-Analysis---camera-data,-only-5"><span class="toc-item-num">5 </span>Modal Analysis - camera data, only</a></span></li><li><span><a href="#Modal-Analysis---Hybrid-method" data-toc-modified-id="Modal-Analysis---Hybrid-method-6"><span class="toc-item-num">6 </span>Modal Analysis - Hybrid method</a></span></li></ul></div>
To run this tutorial, Anaconda and these additional packages must be installed:
* ``pip install lvm_read``
* ``pip install pyFRF``
* ``pip install pyidi``
* ``pip install pyEMA``
Be sure to have the latest version of the avobe packages, use `pip install --upgrade package_name` if required.
```python
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.animation import FuncAnimation
from ipywidgets import interact
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
import warnings
warnings.filterwarnings('ignore')
import lvm_read
import pyFRF
import pyidi
import pyEMA
```
Some settings and functions that will be used during presentation:
```python
%matplotlib inline
font_size = 15
fig_size = (16.0, 8.0)
plt.style.use('ggplot')
matplotlib.rcParams['figure.figsize'] = fig_size
matplotlib.rcParams['font.size'] = font_size
def show_modal_data(nat_freq, damping):
"""Show modal data in a table-like structure."""
print(' Nat. f. Damping')
print(23*'-')
for i, f in enumerate(nat_freq):
print(f'{i+1}) {f:6.1f}\t{damping[i]:5.4f}')
def plot_mode_shape(shape, axis, style='o-', frequency=None, **kwargs):
"""Plot a mode shape in a consistent fashion."""
plot = axis.plot(shape / np.max(np.abs(shape)) * np.sign(shape[0]),
style, **kwargs)
if frequency is not None:
axis.set_title(f'Mode shape - {frequency:.0f} Hz')
axis.set_yticks([])
plt.tight_layout()
```
## Basic experimental skills
**Experimental setup**
**Excitation with modal hammer**
<video controls loop src="figures/experiment.mp4" width="100%" rotate="270deg"/>
Location of the selected files:
```python
cam_fname = 'data/camera.cih'
lvm_fname = 'data/acceleration.lvm'
```
Load the video using [pyidi][1] package, accessible on PyPI.
[1]: https://github.com/ladisk/pyidi
The package enables calculation of displacements and will be upgraded with additional functionalities.
Currently only Photron's MRAW image file format is supported.
```python
video = pyidi.pyIDI(cam_fname)
```
Images are stored in the ``mraw`` attribute.
```python
sequential_image_nr = 175
plt.imshow(video.mraw[sequential_image_nr], cmap='gray')
plt.grid(False)
```
*This example footage is for presentation purposes only and was made to be suitable for online sharing.*
*Normaly image acquisation parameters such as frame rate and image resolution would be chosen as high as possible to obtain more precise results.*
<video controls loop src="figures/video.MOV" width="950" rotate="270deg"/>
### Acquisition parameters
The parameters that were used when recording can be found in the ``info`` attribute:
```python
video.info
```
### Lighting
Lighting conditions are very important when using high-speed camera. To obtain optimal lighting conditions, a histogram of pixel intensity is viewed. An example of a well balanced historgram is shown.
```python
selected_frame = 0
x0 = 300 # position of observed rectangle
y0, d = 9, 25
roi = video.mraw[selected_frame, y0:y0+d, x0:x0+d]
fig, ax = plt.subplots(2)
ax[0].imshow(video.mraw[selected_frame], cmap='gray')
ax[1].hist(roi.flatten(), bins=50);
# Formating
ax[0].add_patch(patches.Rectangle((x0, y0), d, d, fill=False, color='r', linewidth=2))
ax[0].grid(False)
ax[1].set_xlabel('Grayscale value [/]')
ax[1].set_ylabel('n pixels [/]')
plt.tight_layout()
```
### Surface preperation
In order for gradient-based methods to work, sufficient gradient must be present on the images. Surface preperations is therefor necessary.
Stripe pattern and random speckle pattern generation is implemented in the [speckle-pattern][1] python module. In this case, horizontal stripes were used.
[1]: https://github.com/ladisk/speckle_pattern
```python
grad0, grad1 = np.gradient(video.mraw[0].astype(float)) # gradient computation
```
```python
x0 = 200 # position of cross section
fig, ax = plt.subplots(2)
ax[0].imshow(video.mraw[selected_frame], cmap='gray')
ax[1].plot(video.mraw[selected_frame, :, x0], label='Grayscale value')
ax[1].plot(grad0[:, x0], label='Gradient')
# Formating
ax[0].vlines(x0, 0, 40, colors='r', linewidth=3)
ax[0].text(x0+10, -5, 'Cross section')
ax[0].arrow(x0+50, 5, -35, 20, color='r', width=3)
ax[0].grid(False)
ax[1].set_xlabel('Image height [px]')
ax[1].set_ylabel('Grayscale/gradient value [/]')
plt.legend()
plt.tight_layout()
```
### Possible errors
#### Out of focus image
The right side of the beam is in focus, while the left side is not.
```python
layout_fname = r'data/focus.cih'
video_layout = pyidi.pyIDI(layout_fname)
```
```python
fig, ax = plt.subplots()
ax.imshow(video_layout.mraw[0], 'gray')
# Formating
ax.grid(False)
plt.tight_layout()
```
#### Improper lighting
```python
light_fname = r'data/illumination.cih'
video_light = pyidi.pyIDI(light_fname)
```
```python
selected_frame = 0
y0, d = 9, 20
def show(x0):
roi = video_light.mraw[selected_frame, y0:y0+d, x0:x0+d*2]
fig, ax = plt.subplots(2)
ax[0].imshow(video_light.mraw[selected_frame], cmap='gray')
ax[1].hist(roi.flatten(), bins=50);
# Formating
ax[0].add_patch(patches.Rectangle((x0, y0), d*2, d, fill=False, color='r', linewidth=2))
ax[0].grid(False)
ax[1].set_xlabel('Grayscale value [/]')
ax[1].set_ylabel('n pixels [/]')
ax[1].set_xlim([0, 260])
plt.tight_layout()
interact(show, x0=(75, 550, 50));
```
## Simplified Optical-flow Method
Basic formulation:
$$
s(x_j,y_k,t)=\frac{I_0(x_j,y_k)-I(x_j,y_k,t)}{|\nabla I_0|}
$$
As used by [Javh et al.][1] ([pdf][2]).
[1]: https://www.sciencedirect.com/science/article/pii/S0888327016304770
[2]: http://lab.fs.uni-lj.si/ladisk/?what=abstract&ID=179
First, the reference image must be computed:
```python
reference_image = np.average(video.mraw[:10], axis=0)
```
and gradients in ``x`` (1) and ``y`` (0) directions:
```python
grad0, grad1 = np.gradient(reference_image)
```
Points with the highest absolute value of gradient in **vertical** direction are determined:
```python
border = 20
border_h = 12
n = 2
N = 16
w = np.arange(border, reference_image.shape[1]-border, np.abs(border - reference_image.shape[1]-border)//N)
h = np.argsort(np.abs(grad0[border_h:-border_h, w]), axis=0)[-n:, :].T + border_h
inds = np.column_stack((h.flatten(), w.repeat(n)))
```
```python
fig, ax = plt.subplots()
ax.imshow(grad0, cmap='gray')
ax.scatter(inds[:, 1], inds[:, 0])
ax.grid(False)
ax.set_title('Gradient in $y$-direction');
```
Displacement computation, implemented in ``pyidi``:
```python
video.set_points(points=inds) # setting points for analysis
```
```python
video.set_method(method='sof',
mean_n_neighbours=n)
```
``get_displacements()`` method computes the displacements.
```python
displacements = video.get_displacements() * 8e-5
```
```python
location = 1
```
```python
fig, ax = plt.subplots()
ax.plot(displacements[location, :, 0], label='Direction 0 (y)');
ax.set_xlabel('Image [/]]')
ax.set_ylabel('Displacement [m]')
plt.legend()
```
## The Lucas-Kanade Method
By solving an overdetermined system of optical flow equations for a specified region of the image, 2D displacements of the subset can be calculated:
$$
\begin{equation}
\begin{bmatrix}
\Delta x \\
\Delta y
\end{bmatrix} =
\begin{bmatrix}
\sum g_x^2 &\sum g_x \, g_y \\
\sum g_x \, g_y &\sum g_y^2
\end{bmatrix}^{-1}
\begin{bmatrix}
\sum g_x \, (f-g) \\
\sum g_y \, (f-g)
\end{bmatrix}
\end{equation}
$$
where
$f(\mathbf{x}) \dots$ current (displaced) image
$g(\mathbf{x}) \dots$ reference image
```python
points_lk = np.column_stack([np.ones_like(w)*video.info['Image Height']//2, w])
```
```python
video.set_points(points_lk)
video.set_method('lk', roi_size=(21, 23), max_nfev=10, int_order=3)
```
```python
points_lk.shape
```
```python
video.show_points()
```
```python
# displacements_lk = video.get_displacements(processes=2) * 8e-5 # this might take a minute
```
```python
displacements_lk = np.load('data/displacements_lk.npy')
```
```python
fig, ax = plt.subplots()
ax.plot(displacements_lk[location, :, 0], label='Direction 0 (y)')
ax.set_xlabel('Image [/]]')
ax.set_ylabel('Displacement [m]')
plt.legend()
```
```python
displacements = displacements_lk
```
## Frequency Response Functions
First the FFT of displacement is computed:
```python
N = int(video.info['Total Frame'])
dt = 1/int(video.info['Record Rate(fps)'])
1/dt
```
```python
T = dt*N
T
```
```python
upper_f_limit = 4000 # upper observed frequency
```
```python
freq_cam = np.fft.rfftfreq(N, dt)
fft_cam = np.fft.rfft(displacements[:, :, 0], N) *2/N
```
Later the frequency range below `upper_f_limit` Hz is used:
```python
fft_cam = np.copy(fft_cam[:, freq_cam<upper_f_limit])
freq_cam = np.copy(freq_cam[freq_cam<upper_f_limit])
```
The FFT of force measurement is (also limited to `upper_f_limit`):
```python
lvm = lvm_read.read(lvm_fname)
force = lvm[0]['data'][:-30, 1] # 30 pre-samples
N = len(force)//4 # the video was captured for 1/4 of a second
dt = lvm[0]['Delta_X'][1]
fft_force = np.fft.rfft(force, N) *2/N
freq_force = np.fft.rfftfreq(N, dt)
fft_force = np.copy(fft_force[freq_force<upper_f_limit])
freq_force = np.copy(freq_force[freq_force<upper_f_limit])
```
Since only one measurement was used, the FRF is determined by:
```python
frf_cam = fft_cam/fft_force
```
```python
plt.semilogy(freq_cam, np.abs(frf_cam[location]));
```
## Modal Analysis - camera data, only
Modal analysis can be made using ``pyEMA`` package, accessible on [PyPI][1].
[1]: https://pypi.org/project/pyEMA/
```python
cam = pyEMA.Model(frf_cam, freq_cam, pol_order_high=50, upper=upper_f_limit)
```
Poles are computed:
```python
cam.get_poles(show_progress=True)
```
Stable poles can be picked in the stability chart, or preditermind by passing in approximate natural frequencies (picking poles works only in the interactive mode, use magic command: %matplotlib qt).
```python
cam.stab_chart(cam.all_poles)
```
```python
cam.print_modal_data()
```
After the stable poles are determind, a ``lsfd`` method can be called to reconstruct the FRF:
```python
frf_rec, shapes_cam = cam.get_constants(FRF_ind='all')
```
```python
fig, ax = plt.subplots()
ax.semilogy(freq_cam, np.abs(frf_cam[location]), label='Camera FRF', alpha=0.8)
ax.semilogy(freq_cam[:-1], np.abs(frf_rec[location]), label='Reconstructed FRF', lw=2)
ax.set_xlabel('frequency [Hz]')
ax.set_ylabel('Receptance')
plt.legend();
```
```python
fig, ax = plt.subplots(shapes_cam.shape[1])
for i, a in enumerate(ax):
plot_mode_shape(shapes_cam[:, i], axis=a, frequency=cam.nat_freq[i])
```
## Modal Analysis - Hybrid method
Hybrid method was developed by Javh et al. Further details can be found [here][1] ([pdf][2])
First, the acceleration and force data are needed:
[1]: https://www.sciencedirect.com/science/article/pii/S0888327017302637
[2]: http://lab.fs.uni-lj.si/ladisk/?what=abstract&ID=192
```python
hyb_acc = lvm[0]['data'][:-30, 0] * 9.81 # acceleration data (converted to m/s**2)
```
The FRF can be computed using ``pyFRF`` package, accessible on [PyPI][1].
[1]: https://pypi.org/project/pyFRF/
```python
import pyFRF
frf_ = pyFRF.FRF(
sampling_freq=1/dt,
exc=force,
resp=hyb_acc,
exc_window='None',
resp_type='a',
resp_window='None')
```
Only the frequencies lower than `upper_f_limit` Hz are observed:
```python
freq_acc = frf_.get_f_axis()
frf_acc = frf_.get_FRF(form='receptance')
frf_acc = frf_acc[freq_acc<upper_f_limit]
freq_acc = freq_acc[freq_acc<upper_f_limit]
```
The location of acceleration measurement is at identified camera point with index 3:
```python
fig, ax = plt.subplots()
ax.semilogy(freq_cam, np.abs(frf_cam[location]), label='Camera FRF')
ax.semilogy(freq_acc, np.abs(frf_acc), label='Accelerometer FRF')
ax.set_title('Camera-based response at accelerometer location')
plt.legend();
```
Next the ``lscf`` object can be created and poles are computed for the hybrid method:
```python
acc = pyEMA.Model(frf_acc[1:], freq_acc[1:], pol_order_high=50, upper=upper_f_limit)
```
```python
acc.get_poles(show_progress=True)
```
```python
acc.stab_chart(acc.all_poles)
```
```python
acc.print_modal_data()
```
The poles computed based on accleration data are more reliable. These poles can now be used in reconstruction of FRFs from camera. A new ``lscf`` object is made with camera FRF:
```python
cam_hyb = pyEMA.Model(frf_cam, freq_cam)
```
Next, the reconstruction is done using accleration-determined poles:
```python
frf_hyb, shapes_hybrid = cam_hyb.get_constants(whose_poles=acc)
```
```python
fig, ax = plt.subplots()
ax.semilogy(freq_cam, np.abs(frf_cam[location]), label='Camera FRF', alpha=0.8)
ax.semilogy(freq_acc, np.abs(frf_acc), label='Accelerometer FRF')
ax.semilogy(freq_cam[:-1], np.abs(frf_hyb[location]), label='Reconstructed FRF', lw=3)
plt.legend();
```
```python
fig, ax = plt.subplots(shapes_cam.shape[-1])
for i, a in enumerate(ax):
cam_freq = cam.nat_freq[i]
hybrid_f_index = np.argmin(np.abs(acc.nat_freq - cam_freq))
plot_mode_shape(shapes_hybrid[:, hybrid_f_index], axis=a,
frequency=acc.nat_freq[hybrid_f_index], lw=2, label='Hybrid')
plot_mode_shape(shapes_cam[:, i], axis=a , alpha=0.3, label='Camera')
a.set_yticks([])
ax[0].legend()
```
```python
plt.figure(figsize=(fig_size[0], fig_size[1]/3))
plot_mode_shape(shapes_hybrid[:, -1], axis=plt.gca(),
frequency=acc.nat_freq[-1], lw=2, label='Hybrid')
plt.legend()
```
---
<a href="http://www.ladisk.si/imageEMASummer.php"></a>
|
i0 = 123
i1 = BEGIN
i2 = 1
i3.s_x = 124
i4[10, 20] = 30
i5[123] = 124
|
lemma cone_convex_hull: assumes "cone S" shows "cone (convex hull S)" |
module Main
import Compiler.Common
import Compiler.ES.Imperative
import Core.CompileExpr
import Core.Context
import Core.Name.Namespace
import Data.List
import Data.List1
import Data.SortedSet as SortedSet
import Data.String
import Data.String.Extra
import Idris.Driver
import Libraries.Data.StringMap
import Libraries.Utils.Hex
import Primitives
import Printer
import System
import System.File
data Dart : Type where
record DartT where
constructor MkDartT
imports : StringMap Doc
nextImportId : Int
includes : SortedSet String
foreignTypeNames : StringMap Doc
usesDelay : Bool
usesArgs : Bool
modify : {auto ctx : Ref Dart DartT} -> (DartT -> DartT) -> Core ()
modify = Core.update Dart
useDelay : {auto ctx : Ref Dart DartT} -> Core ()
useDelay = modify { usesDelay := True }
useArgs : {auto ctx : Ref Dart DartT} -> Core ()
useArgs = modify { usesArgs := True }
include : {auto ctx : Ref Dart DartT} -> String -> Core ()
include code = modify { includes $= insert code }
Statement : Type
Statement = ImperativeStatement
Expression : Type
Expression = ImperativeExp
splitAtFirst : Char -> String -> (String, String)
splitAtFirst ch s =
let (before, rest) = break (== ch) s
in (before, drop 1 rest)
dartIdent : String -> String
dartIdent s = concatMap okChar (unpack s)
where
okChar : Char -> String
okChar c =
if isAlphaNum c || c == '_'
then cast c
else "$" ++ asHex (cast c)
addImport : {auto ctx : Ref Dart DartT} -> String -> Core Doc
addImport lib = do
s <- get Dart
case lookup lib (imports s) of
Nothing => do
let alias = text ("$" ++ show (nextImportId s))
put Dart (record { imports $= insert lib alias, nextImportId $= (+1) } s)
pure alias
Just alias =>
pure alias
keywordSafe : String -> String
keywordSafe s = case s of
"var" => "var_"
_ => s
data DartNameKind
= TopLevelName
| MemberName
| InfixOperator
| PrefixOperator
| GetAtOperator
| PutAtOperator
dartOperators : List (String, DartNameKind)
dartOperators = [
("==", InfixOperator),
("<", InfixOperator),
(">", InfixOperator),
("<=", InfixOperator),
(">=", InfixOperator),
("+", InfixOperator),
("-", InfixOperator),
("*", InfixOperator),
("/", InfixOperator),
("~/", InfixOperator),
("|", InfixOperator),
("&", InfixOperator),
("^", InfixOperator),
(">>", InfixOperator),
("<<", InfixOperator),
("~", PrefixOperator),
("[]", GetAtOperator),
("[]=", PutAtOperator)
]
parseDartOperator : String -> Maybe DartNameKind
parseDartOperator s = lookup s dartOperators
isMemberName : String -> Bool
isMemberName = isPrefixOf "."
dartNameKindOf : String -> DartNameKind
dartNameKindOf s =
if isMemberName s
then MemberName
else fromMaybe TopLevelName (parseDartOperator s)
dartNameString : Name -> String
dartNameString n = case n of
NS ns n => showNSWithSep "_" ns ++ "_" ++ dartNameString n
UN n => keywordSafe (dartIdent n)
MN n i => dartIdent n ++ "_" ++ show i
PV n d => "pat__" ++ dartNameString n
DN _ n => dartNameString n
Nested (i, x) n => "n__" ++ show i ++ "_" ++ show x ++ "_" ++ dartNameString n
CaseBlock x y => "case__" ++ dartIdent x ++ "_" ++ show y
WithBlock x y => "with__" ++ dartIdent x ++ "_" ++ show y
Resolved i => "fn__" ++ show i
RF n => "rf__" ++ dartIdent n
dartName : Name -> Doc
dartName = text . dartNameString
dartString : String -> String
dartString s = "\"" ++ (concatMap okChar (unpack s)) ++ "\""
where
okChar : Char -> String
okChar c = case c of
'\0' => "\\0"
'"' => "\\\""
'\r' => "\\r"
'\n' => "\\n"
'$' => "\\$"
'\\' => "\\\\"
c => if (c >= ' ') && (c <= '~')
then cast c
else "\\u{" ++ asHex (cast c) ++ "}"
dartStringDoc : String -> Doc
dartStringDoc = text . dartString
debug : Show e => e -> Doc
debug = dartStringDoc . show
comment : String -> Doc
comment c = "/* " <+> text c <+> "*/"
surroundWith : Doc -> Doc -> Doc
surroundWith s d = s <+> d <+> s
mdCode : Doc -> Doc
mdCode = surroundWith "`"
mdItalic : Doc -> Doc
mdItalic = surroundWith "_"
docCommentFor : FC -> Name -> Doc
docCommentFor fc n = "/// " <+> mdCode (shown n) <+> " from " <+> mdItalic (shown fc) <+> "." <+> line
argList : List Doc -> Doc
argList [] = text "()"
argList args = paren (commaSep args <+> ",")
assertionError : Doc -> Doc
assertionError e = "throw $.AssertionError" <+> paren e <+> semi
unsupportedError : Show a => a -> Doc
unsupportedError e = "throw $.UnsupportedError" <+> paren (debug e) <+> semi
unsupported : Show a => a -> Doc
unsupported e = "(() {" <+> unsupportedError e <+> "})()"
genericTypeArgs : List Doc -> Doc
genericTypeArgs args = "<" <+> commaSep args <+> ">"
null' : Doc
null' = text "null"
dynamic' : Doc
dynamic' = text "$.dynamic "
final' : Doc
final' = text "final "
var' : Doc
var' = text "var "
paramList : List Name -> Doc
paramList ps = tupled ((dynamic' <+>) . dartName <$> ps)
castTo : Doc -> Doc -> Doc
castTo ty e = paren (e <+> " as " <+> ty)
world' : Doc
world' = text "#World"
intTy : Doc
intTy = text "$.int"
bigIntTy : Doc
bigIntTy = text "$.BigInt"
stringTy : Doc
stringTy = text "$.String"
doubleTy : Doc
doubleTy = text "$.double"
refTy : Doc
refTy = text "Ref"
maxDartInt : Integer
maxDartInt = 9223372036854775807
bigIntConstant : Integer -> Doc
bigIntConstant = \case
0 => text "$.BigInt.zero"
1 => text "$.BigInt.one"
i => if i > maxDartInt
then "$.BigInt.parse(\"" <+> shown i <+> "\")"
else "$.BigInt.from(" <+> shown i <+> ")"
dartConstant : Constant -> Doc
dartConstant c = case c of
B8 i => shown i
B16 i => shown i
B32 i => shown i
B64 i => bigIntConstant i
BI i => bigIntConstant i
I i => shown i
Ch c => shown (cast {to=Int} c)
Str s => dartStringDoc s
Db d => shown d
WorldVal => world'
_ => unsupported c
runtimeTypeOf : Constant -> Doc
runtimeTypeOf ty = case ty of
StringType => stringTy
IntegerType => bigIntTy
Bits64Type => bigIntTy
DoubleType => doubleTy
_ => "$.int"
---- Dart FFI -------------------------------------
Lib : Type
Lib = String
data ForeignDartSpec
= ForeignFunction String Lib
| ForeignConst String Lib
| ForeignMethod String
dropPrefix : String -> String -> Maybe String
dropPrefix p s =
if p `isPrefixOf` s
then Just (drop (length p) s)
else Nothing
foreignDartSpecFrom : String -> Maybe ForeignDartSpec
foreignDartSpecFrom s = do
(name, lib) <- dartNameAndLib s
method name <|> const name lib <|> function name lib
where
dartNameAndLib : String -> Maybe (String, Lib)
dartNameAndLib s = splitAtFirst ',' <$> dropPrefix "Dart:" s
method : String -> Maybe ForeignDartSpec
method m = ForeignMethod <$> dropPrefix "." m
const : String -> Lib -> Maybe ForeignDartSpec
const n lib = (`ForeignConst` lib) <$> dropPrefix "const " n
function : String -> Lib -> Maybe ForeignDartSpec
function n lib = Just (ForeignFunction n lib)
FunctionType : Type
FunctionType = (List CFType, CFType)
mkFunctionType : List Expression -> CFType -> FunctionType
mkFunctionType ps ret = (const CFPtr <$> ps, ret)
uncurriedSignature : CFType -> CFType -> FunctionType
uncurriedSignature a b = go [a] b
where
go : List CFType -> CFType -> FunctionType
go ps (CFFun a b) = go (a :: ps) b
go ps ret = (reverse ps, ret)
argNamesFor : List a -> String -> List Doc
argNamesFor args p = text . (p ++) . show <$> [1..length args]
||| Adapts the foreign callback [c] so that it can be
||| invoked from Dart with the expected signature.
makeCallback : FunctionType -> Doc -> Doc
makeCallback (args, ret) c =
let
argNames = argNamesFor args "c$"
params = mapMaybe callbackParam (zip argNames args)
worldArg = case ret of
CFIORes _ => paren world'
_ => empty
callbackArgs = hcat (paren <$> params) <+> worldArg
in
tupled params <+> " => " <+> c <+> callbackArgs
where
callbackParam : (Doc, CFType) -> Maybe Doc
callbackParam (p, ty) = case ty of
CFWorld => Nothing
_ => Just p
foreignArg : {auto fc : FC} -> (Doc, CFType) -> Core (Maybe Doc)
foreignArg (n, ty) = case ty of
CFWorld => pure Nothing
CFFun a b => pure $ Just (makeCallback (uncurriedSignature a b) n)
CFUser (UN "Type") [] => pure Nothing
CFUser (UN "__") [] => pure Nothing
CFUser (NS ns (UN "Bool")) [] =>
if ns == basicsNS
then throw (GenericMsg fc "'Bool' is not a valid foreign type, use 'DartBool' from 'Dart.Core` instead!")
else pure $ Just n
_ => pure $ Just n
singleExpFunction : Doc -> List Doc -> Doc -> Doc
singleExpFunction n ps e =
n <+> tupled ps <+> block ("return " <+> e <+> semi)
convertForeignReturnType : CFType -> Doc -> Doc
convertForeignReturnType retTy e = case retTy of
CFUser (NS ns (UN "Bool")) [] =>
if ns == basicsNS
then e <+> " ? 0 : 1"
else e
_ => e
traverseMaybes : (a -> Core (Maybe b)) -> List a -> Core (List b)
traverseMaybes f as = catMaybes <$> traverse f as
collectPositional : Expression -> List Expression
collectPositional e = go [] e
where
go : List Expression -> Expression -> List Expression
go acc ({- HVect.:: -} IEConstructor (Left 1) (e :: es :: _)) = go (e :: acc) es
go acc _ = reverse acc
parseList : Expression -> Maybe (List Expression)
parseList e = case e of
IEConstructor _ _ => Just (collectPositional e)
_ => Nothing
foreignFunctionProxy : {auto fc : FC} -> Doc -> Doc -> List CFType -> CFType -> Core Doc
foreignFunctionProxy n ff args ret = do
let argNames = argNamesFor args "a$"
fArgs <- traverseMaybes foreignArg (zip argNames args)
let call = ff <+> tupled fArgs
pure (singleExpFunction n argNames (convertForeignReturnType ret call))
foreignName : {auto ctx : Ref Dart DartT}
-> Lib -> String -> Core Doc
foreignName lib n =
case fastUnpack lib of
('\n' :: rest) => do
include lib
pure (text n)
[] => pure (text n)
_ => pure (!(addImport lib) <+> dot <+> text n)
parseForeignName : {auto ctx : Ref Dart DartT}
-> String -> Core Doc
parseForeignName ty =
let (tyN, lib) = splitAtFirst ',' ty
in foreignName lib tyN
lookupForeignType : {auto ctx : Ref Dart DartT} -> String -> Core (Maybe Doc)
lookupForeignType ty = lookup ty . foreignTypeNames <$> get Dart
putForeignType : {auto ctx : Ref Dart DartT} -> String -> Doc -> Core ()
putForeignType ty doc = modify { foreignTypeNames $= insert ty doc }
foreignTypeName : {auto ctx : Ref Dart DartT} -> String -> Core Doc
foreignTypeName ty = do
case !(lookupForeignType ty) of
Just doc => pure doc
Nothing => do
doc <- parseForeignName ty
putForeignType ty doc
pure doc
foreignTypeOf : {auto ctx : Ref Dart DartT} -> CFType -> Core Doc
foreignTypeOf e = case e of
CFString => pure stringTy
CFDouble => pure doubleTy
CFChar => pure intTy
CFInt => pure intTy
CFUnsigned8 => pure intTy
CFUnsigned16 => pure intTy
CFUnsigned32 => pure intTy
CFUnsigned64 => pure intTy
CFStruct name _ => foreignTypeName name
_ => pure "$.dynamic"
foreignMethodProxy : {auto ctx : Ref Dart DartT}
-> Doc -> Doc -> List CFType -> CFType -> Core Doc
foreignMethodProxy n m args@(thisTy :: _) ret = do
let argNames = argNamesFor args "a$"
case !(traverseMaybes foreignArg (zip argNames args)) of
fThis :: fArgs => do
let mc = castTo !(foreignTypeOf thisTy) fThis <+> dot <+> m <+> tupled fArgs
pure (singleExpFunction n argNames (convertForeignReturnType ret mc))
_ => pure (unsupported (m, args))
foreignMethodProxy n m args ret =
pure (unsupported (m, args))
dartForeign : {auto ctx : Ref Dart DartT}
-> {auto fc : FC}
-> Name -> ForeignDartSpec
-> List CFType -> CFType
-> Core Doc
dartForeign n (ForeignFunction f lib) args ret = do
ff <- foreignName lib f
foreignFunctionProxy (dartName n) ff args ret
dartForeign n (ForeignConst c lib) _ _ = do
fc <- foreignName lib c
pure (singleExpFunction (dartName n) [] fc)
dartForeign n (ForeignMethod m) args ret = do
foreignMethodProxy (dartName n) (text m) args ret
parseFunctionType : Expression -> Maybe FunctionType
parseFunctionType e =
case e of
IEConstructor (Right "->") [a, b] => Just (go [a] b)
IEConstructor (Right "PrimIO.IO") [_] => Just (mkFunctionType [] (CFIORes CFPtr))
_ => Nothing
where
go : List Expression -> Expression -> FunctionType
go ps (IELambda _ (ReturnStatement (IEConstructor (Right ty) args))) =
case (ty, args) of
("->", [a, b]) => go (a :: ps) b
("PrimIO.IO", _) => mkFunctionType ps (CFIORes CFPtr)
_ => mkFunctionType ps CFPtr
go ps _ = mkFunctionType ps CFPtr
dartStdout : {auto ctx : Ref Dart DartT} -> Core Doc
dartStdout = foreignName "dart:io" "stdout"
dartStdin : {auto ctx : Ref Dart DartT} -> Core Doc
dartStdin = foreignName "dart:io" "stdin"
unknownForeignDecl : {auto ctx : Ref Dart DartT}
-> Name -> List String
-> Core Doc
unknownForeignDecl n ss =
pure (dartName n <+> "([a, b, c, d, e, f, g, h, i, j, k])" <+> block (unsupportedError (n, ss)))
maybeForeignDartDecl : {auto ctx : Ref Dart DartT}
-> {auto fc : FC}
-> Name -> List String
-> List CFType -> CFType
-> Core Doc
maybeForeignDartDecl n ss args ret =
case mapMaybe foreignDartSpecFrom ss of
[s] => dartForeign n s args ret
_ => unknownForeignDecl n ss
foreignDecl : {auto ctx : Ref Dart DartT}
-> {auto fc : FC}
-> Name -> List String
-> List CFType -> CFType
-> Core Doc
foreignDecl n ss args ret = case n of
NS _ (UN "prim__putStr") =>
pure (dartName n <+> "(s, w)" <+> block (!dartStdout <+> ".write(s);" <+> line <+> "return w;"))
NS _ (UN "prim__putChar") =>
pure (dartName n <+> "(c, w)" <+> block (!dartStdout <+> ".writeCharCode(c);" <+> line <+> "return w;"))
NS _ (UN "prim__getStr") =>
pure (dartName n <+> "(w)" <+> block ("return " <+> !dartStdin <+> ".readLineSync() ?? \"\";"))
NS _ (UN "prim__getArgCount") =>
useArgs *> pure (dartName n <+> "(w) => $args.length;")
NS _ (UN "prim__getArg") =>
useArgs *> pure (dartName n <+> "(i, w) => $args[i];")
NS ns (UN "fastConcat") => if ns == typesNS
then pure (text primDartFastConcat)
else maybeForeignDartDecl n ss args ret
NS ns (UN "fastUnpack") => if ns == typesNS
then pure (text primDartFastUnpack)
else maybeForeignDartDecl n ss args ret
NS ns (UN "fastPack") => if ns == typesNS
then pure (text primDartFastPack)
else maybeForeignDartDecl n ss args ret
_ => maybeForeignDartDecl n ss args ret
binOp : Doc -> Doc -> Doc -> Doc
binOp o lhs rhs = paren (lhs <+> o <+> rhs)
binOpOf' : Doc -> Doc -> Doc -> Doc -> Doc
binOpOf' ty op lhs rhs = binOp op (castTo ty lhs) (castTo ty rhs)
binOpOf : Constant -> Doc -> Doc -> Doc -> Doc
binOpOf ty = binOpOf' (runtimeTypeOf ty)
idrisBoolFrom : Doc -> Doc
idrisBoolFrom e = paren (e <+> " ? 1 : 0")
boolOpOf : Constant -> Doc -> Doc -> Doc -> Doc
boolOpOf ty o lhs rhs = idrisBoolFrom (binOpOf ty o lhs rhs)
stringOp : Doc -> Doc -> Doc
stringOp s m = (castTo stringTy s) <+> dot <+> m
doubleOp : Doc -> Doc -> Doc
doubleOp e m = (castTo doubleTy e) <+> dot <+> m
bigIntFrom : Doc -> Doc
bigIntFrom num = "$.BigInt.from" <+> paren num
toUnsigned : Int -> Doc -> Doc
toUnsigned width num = num <+> ".toUnsigned" <+> paren (shown width)
bigIntToBits : Int -> Doc -> Doc
bigIntToBits 64 i = toUnsigned 64 (castTo bigIntTy i)
bigIntToBits width i = toUnsigned width (castTo bigIntTy i) <+> ".toInt()"
bigIntToInt : Doc -> Doc
bigIntToInt i = toUnsigned 64 (castTo bigIntTy i) <+> ".toInt()"
intToBits : Int -> Doc -> Doc
intToBits 64 i = bigIntFrom i
intToBits width i = bigIntToBits width (bigIntFrom i)
boundedUIntOp : Int -> Doc -> Doc -> Doc -> Doc
boundedUIntOp 64 op x y = toUnsigned 64 (binOpOf' bigIntTy op x y)
boundedUIntOp width op x y = toUnsigned width (binOpOf' intTy op x y )
boundedShiftOp : Int -> Doc -> Doc -> Doc -> Doc
boundedShiftOp 64 op x y = toUnsigned 64 (bigIntFrom x <+> op <+> y)
boundedShiftOp width op x y = bigIntToBits width (bigIntFrom x <+> op <+> y)
stringCompare : Doc -> Doc -> Doc -> Doc
stringCompare zeroComparison lhs rhs =
idrisBoolFrom (stringOp lhs "compareTo" <+> paren rhs <+> zeroComparison)
runtimeCastOf : Constant -> Doc -> Doc
runtimeCastOf ty e = castTo (runtimeTypeOf ty) e
dartOp : {auto ctx : Ref Dart DartT}
-> PrimFn argCount
-> Vect argCount Doc
-> Doc
dartOp (LT StringType) [x, y] = stringCompare " < 0" x y
dartOp (LTE StringType) [x, y] = stringCompare " <= 0" x y
dartOp (EQ StringType) [x, y] = stringCompare " == 0" x y
dartOp (GTE StringType) [x, y] = stringCompare " >= 0" x y
dartOp (GT StringType) [x, y] = stringCompare " > 0" x y
dartOp (LT ty) [x, y] = boolOpOf ty "<" x y
dartOp (LTE ty) [x, y] = boolOpOf ty "<=" x y
dartOp (EQ ty) [x, y] = boolOpOf ty "==" x y
dartOp (GTE ty) [x, y] = boolOpOf ty ">=" x y
dartOp (GT ty) [x, y] = boolOpOf ty ">" x y
dartOp (Add Bits8Type) [x, y] = boundedUIntOp 8 "+" x y
dartOp (Sub Bits8Type) [x, y] = boundedUIntOp 8 "-" x y
dartOp (Mul Bits8Type) [x, y] = boundedUIntOp 8 "*" x y
dartOp (Div Bits8Type) [x, y] = boundedUIntOp 8 "~/" x y
dartOp (Mod Bits8Type) [x, y] = boundedUIntOp 8 "%" x y
dartOp (Add Bits16Type) [x, y] = boundedUIntOp 16 "+" x y
dartOp (Sub Bits16Type) [x, y] = boundedUIntOp 16 "-" x y
dartOp (Mul Bits16Type) [x, y] = boundedUIntOp 16 "*" x y
dartOp (Div Bits16Type) [x, y] = boundedUIntOp 16 "~/" x y
dartOp (Mod Bits16Type) [x, y] = boundedUIntOp 16 "%" x y
dartOp (Add Bits32Type) [x, y] = boundedUIntOp 32 "+" x y
dartOp (Sub Bits32Type) [x, y] = boundedUIntOp 32 "-" x y
dartOp (Mul Bits32Type) [x, y] = boundedUIntOp 32 "*" x y
dartOp (Div Bits32Type) [x, y] = boundedUIntOp 32 "~/" x y
dartOp (Mod Bits32Type) [x, y] = boundedUIntOp 32 "%" x y
dartOp (Add Bits64Type) [x, y] = boundedUIntOp 64 "+" x y
dartOp (Sub Bits64Type) [x, y] = boundedUIntOp 64 "-" x y
dartOp (Mul Bits64Type) [x, y] = boundedUIntOp 64 "*" x y
dartOp (Div Bits64Type) [x, y] = boundedUIntOp 64 "~/" x y
dartOp (Mod Bits64Type) [x, y] = boundedUIntOp 64 "%" x y
dartOp (ShiftL Bits8Type) [x, y] = boundedShiftOp 8 "<<" x y
dartOp (ShiftL Bits16Type) [x, y] = boundedShiftOp 16 "<<" x y
dartOp (ShiftL Bits32Type) [x, y] = boundedShiftOp 32 "<<" x y
dartOp (ShiftL Bits64Type) [x, y] = boundedShiftOp 64 "<<" x y
dartOp (ShiftL ty) [x, y] = binOpOf ty "<<" x y
dartOp (ShiftR Bits8Type) [x, y] = boundedShiftOp 8 ">>" x y
dartOp (ShiftR Bits16Type) [x, y] = boundedShiftOp 16 ">>" x y
dartOp (ShiftR Bits32Type) [x, y] = boundedShiftOp 32 ">>" x y
dartOp (ShiftR Bits64Type) [x, y] = boundedShiftOp 64 ">>" x y
dartOp (ShiftR ty) [x, y] = binOpOf ty ">>" x y
dartOp (BAnd ty) [x, y] = binOpOf ty "&" x y
dartOp (BOr ty) [x, y] = binOpOf ty "|" x y
dartOp (BXOr ty) [x, y] = binOpOf ty "^" x y
dartOp (Add ty) [x, y] = binOpOf ty "+" x y
dartOp (Sub ty) [x, y] = binOpOf ty "-" x y
dartOp (Mul ty) [x, y] = binOpOf ty "*" x y
dartOp (Div ty@DoubleType) [x, y] = binOpOf ty "/" x y
dartOp (Div ty) [x, y] = binOpOf ty "~/" x y
dartOp (Mod ty) [x, y] = binOpOf ty "%" x y
dartOp (Neg ty) [x] = paren ("-" <+> runtimeCastOf ty x)
dartOp StrLength [x] = stringOp x "length"
dartOp StrHead [x] = stringOp x "codeUnitAt(0)"
dartOp StrIndex [x, y] = stringOp x "codeUnitAt" <+> paren y
dartOp StrTail [x] = stringOp x "substring(1)"
dartOp StrCons [x, y] = binOp "+" ("$.String.fromCharCode" <+> paren x) (castTo stringTy y)
dartOp StrAppend [x, y] = binOpOf' stringTy "+" x y
dartOp StrSubstr [offset, length, str] = (castTo stringTy str) <+> ".substring" <+> tupled [offset, binOpOf IntType "+" offset length]
dartOp (Cast StringType IntegerType) [x] = paren (bigIntTy <+> ".tryParse" <+> castTo stringTy x <+> " ?? " <+> bigIntTy <+> ".zero")
dartOp (Cast StringType DoubleType) [x] = paren (doubleTy <+> ".tryParse" <+> castTo stringTy x <+> " ?? 0.0")
dartOp (Cast StringType IntType) [x] = paren (intTy <+> ".tryParse" <+> castTo stringTy x <+> " ?? 0")
dartOp (Cast DoubleType IntType) [x] = doubleOp x "toInt()"
dartOp (Cast IntegerType IntType) [x] = bigIntToInt x
dartOp (Cast IntegerType Bits8Type) [x] = bigIntToBits 8 x
dartOp (Cast IntegerType Bits16Type) [x] = bigIntToBits 16 x
dartOp (Cast IntegerType Bits32Type) [x] = bigIntToBits 32 x
dartOp (Cast IntegerType Bits64Type) [x] = bigIntToBits 64 x
dartOp (Cast Bits8Type Bits16Type) [x] = x
dartOp (Cast Bits8Type Bits32Type) [x] = x
dartOp (Cast Bits8Type IntType) [x] = x
dartOp (Cast Bits16Type IntType) [x] = x
dartOp (Cast Bits16Type Bits32Type) [x] = x
dartOp (Cast Bits32Type IntType) [x] = x
dartOp (Cast Bits64Type IntegerType) [x] = x
dartOp (Cast Bits64Type IntType) [x] = bigIntToInt x
dartOp (Cast Bits64Type Bits8Type) [x] = bigIntToBits 8 x
dartOp (Cast Bits64Type Bits16Type) [x] = bigIntToBits 16 x
dartOp (Cast Bits64Type Bits32Type) [x] = bigIntToBits 32 x
dartOp (Cast CharType IntType) [x] = x
dartOp (Cast IntType CharType) [x] = x
dartOp (Cast ty Bits8Type) [x] = intToBits 8 x
dartOp (Cast ty Bits16Type) [x] = intToBits 16 x
dartOp (Cast ty Bits32Type) [x] = intToBits 32 x
dartOp (Cast ty Bits64Type) [x] = intToBits 64 x
dartOp (Cast ty IntegerType) [x] = bigIntFrom x
dartOp (Cast ty DoubleType) [x] = runtimeCastOf ty x <+> ".toDouble()"
dartOp (Cast ty StringType) [x] = x <+> ".toString()"
dartOp DoubleFloor [x] = doubleOp x "floorToDouble()"
dartOp DoubleCeiling [x] = doubleOp x "ceilToDouble()"
dartOp BelieveMe [_, _, x] = x
dartOp Crash [_, m] = assertionError m
dartOp e args = unsupported ("dartOp", e, args)
dartTypeFromExpression : {auto ctx : Ref Dart DartT} -> Expression -> Core Doc
dartTypeFromExpression ty = case ty of
IEConstructor (Right "String") _ => pure stringTy
IEConstructor (Right "Int") _ => pure intTy
IEConstructor (Right "Integer") _ => pure bigIntTy
IEConstructor (Right "Double") _ => pure doubleTy
IEConstructor (Right "Prelude.Basics.Bool") _ => pure intTy -- Idris Bool is represented as int at runtime
IEConstructor (Right "System.FFI.Struct") (IEConstant (Str ty) :: _) =>
foreignTypeName ty
IEConstructor (Right "Dart.FFI.Types.GenericType") [IEConstant (Str baseType), args] => do
baseType' <- foreignTypeName baseType
let Just argList = parseList args
| _ => pure baseType'
argList' <- traverse dartTypeFromExpression argList
pure (baseType' <+> genericTypeArgs argList')
_ => pure dynamic'
mutual
dartBlock : {auto ctx : Ref Dart DartT} -> Statement -> Core Doc
dartBlock s = block <$> dartStatement s
dartLambda : {auto ctx : Ref Dart DartT} -> List Name -> Statement -> Core Doc
dartLambda ps s = (paramList ps <+>) <$> dartBlock s
commaSepExps : {auto ctx : Ref Dart DartT}
-> List Expression
-> Core Doc
commaSepExps es = do
es' <- traverse dartExp es
pure (commaSep es')
dartApp : {auto ctx : Ref Dart DartT} -> Expression -> List Expression -> Core Doc
dartApp f args = do
f' <- dartExp f
args' <- traverse dartExp args
pure (f' <+> argList args')
dartConstructor : {auto ctx : Ref Dart DartT}
-> Doc
-> List Expression
-> Core Doc
dartConstructor tag args = case args of
[] => pure (text "const [" <+> tag <+> "]")
args => pure ("[" <+> tag <+> ", " <+> !(commaSepExps args) <+> "]")
dartExp : {auto ctx : Ref Dart DartT}
-> Expression
-> Core Doc
dartExp e = case e of
IENull => pure null'
IEConstant c => pure (dartConstant c)
IEVar v => pure (dartName v)
IELambda ps s => dartLambda ps s
IEApp f@(IEVar (NS ns (UN "believe_me"))) args@[arg] =>
if ns == builtinNS
then dartExp arg
else dartApp f args
IEApp f args =>
dartApp f args
IEPrimFn f args =>
pure (dartOp f !(traverseVect dartExp args))
IEPrimFnExt n args =>
dartPrimFnExt n args
IEConstructor (Left tag) args =>
dartConstructor (shown tag) args
IEConstructor (Right tag) args =>
dartConstructor (dartStringDoc tag) args
IEConstructorHead e =>
pure (castTo "$.List" !(dartExp e) <+> "[0]")
IEConstructorTag (Left tag) =>
pure (shown tag)
IEConstructorTag (Right tag) =>
pure (shown tag)
IEConstructorArg i e =>
pure (castTo "$.List" !(dartExp e) <+> "[" <+> shown i <+> "]")
IEDelay e =>
useDelay *> pure ("$Delayed" <+> paren ("() => " <+> !(dartExp e)))
IEForce e =>
pure (castTo "$Delayed" !(dartExp e) <+> ".force()")
_ => pure (debug e)
maybeCastTo : Maybe Doc -> Doc -> Doc
maybeCastTo ty e = maybe e (flip castTo e) ty
dartPrimNew : {auto ctx : Ref Dart DartT}
-> Expression -> Expression -> String -> Expression -> Expression -> Core Doc
dartPrimNew ty positionalTys ctorName positional named = do
let posTys = collectPositional positionalTys
let pos' = collectPositional positional
let named' = collectNamed named
let typedPos = zip posTys pos'
posArgs <- traverse (uncurry dartForeignArg) typedPos
namedArgs <- traverse dartNamedArg named'
fTy <- dartTypeFromExpression ty
let ctorName' = if length ctorName > 0 then text ("." ++ ctorName) else empty
pure (fTy <+> ctorName' <+> argList (posArgs ++ namedArgs))
dartPrimInvoke : {auto ctx : Ref Dart DartT}
-> String -> Expression -> Expression -> Expression -> Expression -> Core Doc
dartPrimInvoke fn typeArgs positionalTys positional named = do
let posTys = collectPositional positionalTys
let pos' = collectPositional positional
let named' = collectNamed named
let typedPos = zip posTys pos'
posArgs <- traverse (uncurry dartForeignArg) typedPos
namedArgs <- traverse dartNamedArg named'
typeArgs' <- traverse dartTypeFromExpression (collectPositional typeArgs)
let typeArgs'' = if null typeArgs' then empty else genericTypeArgs typeArgs'
case (dartNameKindOf fn, posArgs) of
(MemberName, this :: args) => do -- Method call
thisTy <- methodReceiverTypeFrom positionalTys
pure $ maybeCastTo thisTy this <+> text fn <+> typeArgs'' <+> argList (args ++ namedArgs)
(TopLevelName, args) => do -- Static / Global function call
fn' <- parseForeignName fn
pure $ fn' <+> typeArgs'' <+> argList (args ++ namedArgs)
(InfixOperator, [x, y]) => do
xTy <- methodReceiverTypeFrom positionalTys
pure $ binOp (text fn) (maybeCastTo xTy x) y
_ =>
pure $ unsupported ("prim__dart_invoke", fn, positional, named)
dartPrimFnExt : {auto ctx : Ref Dart DartT}
-> Name -> List Expression -> Core Doc
dartPrimFnExt
(NS _ (UN "prim__newIORef"))
[IENull, e, _] = include refTyDef *> pure (refTy <+> paren !(dartExp e))
dartPrimFnExt
(NS _ (UN "prim__writeIORef"))
[IENull, ref, e, _] = pure $ castTo refTy !(dartExp ref) <+> ".v = " <+> !(dartExp e)
dartPrimFnExt
(NS _ (UN "prim__readIORef"))
[IENull, ref, _] = pure $ castTo refTy !(dartExp ref) <+> ".v"
dartPrimFnExt
(NS _ (UN "prim__setField"))
(IEConstant (Str ty) :: _ :: _ :: e :: IEConstant (Str f) :: _ :: rhs :: _) = do
fTy <- foreignTypeName ty
pure (castTo fTy !(dartExp e) <+> dot <+> text f <+> " = " <+> !(dartExp rhs))
dartPrimFnExt
(NS _ (UN "prim__getField"))
(IEConstant (Str ty) :: _ :: _ :: e :: IEConstant (Str f) :: _) = do
fTy <- foreignTypeName ty
pure (castTo fTy !(dartExp e) <+> dot <+> text f)
dartPrimFnExt
(NS _ (UN "prim__dart_set"))
[ thisTy
, valueTy
, IEConstant (Str propertyName)
, value
, this
, _
] = case isMemberName propertyName of
True => pure (castTo !(dartTypeFromExpression thisTy) !(dartExp this) <+> text propertyName <+> " = " <+> !(dartExp value))
False => pure (!(foreignTypeName propertyName) <+> " = " <+> !(dartExp value))
dartPrimFnExt
(NS _ (UN "prim__dart_get"))
[ IENull
, thisTy
, IEConstant (Str propertyName)
, this
, _
] = case isMemberName propertyName of
True => pure (castTo !(dartTypeFromExpression thisTy) !(dartExp this) <+> text propertyName)
False => foreignTypeName propertyName
dartPrimFnExt
(NS _ (UN "prim__dart_get_pure"))
[ IENull
, thisTy
, IEConstant (Str propertyName)
, this
] = case isMemberName propertyName of
True => pure (castTo !(dartTypeFromExpression thisTy) !(dartExp this) <+> text propertyName)
False => foreignTypeName propertyName
dartPrimFnExt
(NS _ (UN "prim__dart_invoke"))
[ IENull, IENull, IENull, IENull -- erased type arguments
, positionalTys
, IEConstant (Str fn)
, typeArguments
, positional
, named
, rest
] = dartPrimInvoke fn typeArguments positionalTys positional named
dartPrimFnExt
(NS _ (UN "prim__dart_invoke_pure"))
[ IENull, IENull, IENull, IENull -- erased type arguments
, positionalTys
, IEConstant (Str fn)
, typeArguments
, positional
, named
] = dartPrimInvoke fn typeArguments positionalTys positional named
dartPrimFnExt
(NS _ (UN "prim__dart_new_const"))
[ IENull, IENull, IENull -- erased type arguments
, ty
, positionalTys
, IEConstant (Str ctorName)
, positional
, named
] = dartPrimNew ty positionalTys ctorName positional named
dartPrimFnExt
(NS _ (UN "prim__dart_new"))
[ IENull, IENull, IENull -- erased type arguments
, ty
, positionalTys
, IEConstant (Str ctorName)
, positional
, named
, _
] = dartPrimNew ty positionalTys ctorName positional named
dartPrimFnExt
(NS _ (UN "prim__dart_List_new"))
[ elementTy
, _
] = do
elementTy' <- dartTypeFromExpression elementTy
pure (text "<" <+> elementTy' <+> text ">[]")
dartPrimFnExt
(NS _ (UN "prim__dart_List_empty"))
[ elementTy
] = do
elementTy' <- dartTypeFromExpression elementTy
pure (text "$.List<" <+> elementTy' <+> text ">.empty()")
dartPrimFnExt
(NS _ (UN "prim__dart_List_fromList"))
[ elementTy
, elements
] = do
elementTy' <- dartTypeFromExpression elementTy
case parseList elements of
Just es => pure ("<" <+> elementTy' <+> ">" <+> bracket !(commaSepExps es))
Nothing => do
include primDartIterableFromList
pure $
text "$.List<" <+> elementTy' <+> ">.unmodifiable" <+> paren (
"Dart_Iterable_fromList" <+> paren !(dartExp elements)
)
dartPrimFnExt
(NS _ (UN "prim__dart_if"))
[ IENull, condition, thenValue, elseValue ] =
pure (!(dartExp condition) <+> " ? " <+> !(dartExp thenValue) <+> " : " <+> !(dartExp elseValue))
dartPrimFnExt
(NS _ (UN "prim__dart_unsafe_null"))
_ = pure null'
dartPrimFnExt n args = pure (unsupported (n, args))
uncurryCallback : (hasIO : Bool) -> (args : List CFType) -> Expression -> Maybe (List Name, Statement)
uncurryCallback = go []
where
go : List Name -> Bool -> List CFType -> Expression -> Maybe (List Name, Statement)
go acc hasIO (_ :: as) (IELambda [n] (ReturnStatement e)) = go (n :: acc) hasIO as e
go acc True [] (IELambda [n] e) = Just (n :: acc, e)
go acc False (_ :: as) (IELambda [n] e) = Just (n :: acc, e)
go acc False [] e = Just (acc, ReturnStatement e)
go _ _ _ _ = Nothing
dartForeignArg : {auto ctx : Ref Dart DartT} -> Expression -> Expression -> Core Doc
dartForeignArg _ (IEPrimFnExt (NS _ (UN "prim__dart_unsafe_null")) _) =
pure null'
dartForeignArg ty value =
case parseFunctionType ty of
-- Optimize curried IO callbacks
Just fTy@(args, CFIORes _) =>
case uncurryCallback True args value of
-- TODO: Optimize partial applications
Just (worldP :: ps, e) => do
e' <- dartStatement e
let ignoreWarning = "// ignore: unused_local_variable"
let world = "const " <+> dartName worldP <+> " = " <+> world' <+> semi
pure $ tupled (dartName <$> reverse ps) <+> block (vcat [ignoreWarning, world, e'])
_ => makeCallback fTy <$> dartExp value
-- Optimize curried pure callbacks
Just (args, _) =>
case uncurryCallback False args value of
Just (ps, e) => pure $ tupled (dartName <$> reverse ps) <+> !(dartBlock e)
_ => dartExp value
_ => dartExp value
dartNamedArg : {auto ctx : Ref Dart DartT} -> (Expression, String, Expression) -> Core Doc
dartNamedArg (ty, name, value) =
pure (text name <+> ": " <+> !(dartForeignArg ty value))
methodReceiverTypeFrom : {auto ctx : Ref Dart DartT} -> Expression -> Core (Maybe Doc)
methodReceiverTypeFrom (IEConstructor (Left 1) (ty :: _)) =
Just <$> dartTypeFromExpression ty
methodReceiverTypeFrom _ =
pure Nothing
||| Collects the parameter name and value pairs from the expression
||| representing a `ParamList _`.
collectNamed : Expression -> List (Expression, String, Expression)
collectNamed e = go [] e
where
go : List (Expression, String, Expression) -> Expression -> List (Expression, String, Expression)
go acc ({- ParamList.:: -} IEConstructor (Left 1) [{- Assign key value -} IEConstructor (Left 0) [ty, IEConstant (Str key), value], es]) = go ((ty, key, value) :: acc) es
go acc _ = reverse acc
dartCase : {auto ctx : Ref Dart DartT}
-> (Expression, Statement)
-> Core Doc
dartCase (e, s) = do
e' <- case e of
IEConstant (BI i) => pure (shown i)
_ => dartExp e
s' <- dartStatement s
pure ("case " <+> e' <+> ":" <+> block s' <+> line <+> "break;")
defaultDartCase : {auto ctx : Ref Dart DartT}
-> Maybe Statement
-> Core Doc
defaultDartCase dc = case dc of
Just s => do
s' <- dartStatement s
pure (line <+> "default:" <+> block s' <+> line <+> "break;")
Nothing => pure empty
dartSwitch : {auto ctx : Ref Dart DartT}
-> Doc
-> List (Expression, Statement)
-> Maybe Statement
-> Core Doc
dartSwitch e cases def = do
cases' <- traverse dartCase cases
def' <- defaultDartCase def
pure ("switch " <+> paren e <+> block (vcat cases' <+> def'))
dartStatement : {auto ctx : Ref Dart DartT}
-> Statement
-> Core Doc
dartStatement s = case s of
FunDecl fc n ps body =>
pure (line <+> docCommentFor fc n <+> dartName n <+> !(dartLambda ps body))
ForeignDecl fc n ss args ret =>
pure (line <+> !(foreignDecl n ss args ret))
SwitchStatement e cases@((IEConstant (BI _), _) :: _) maybeDefault =>
dartSwitch (bigIntToInt !(dartExp e)) cases maybeDefault
SwitchStatement e cases maybeDefault =>
dartSwitch !(dartExp e) cases maybeDefault
SeqStatement a b =>
pure (!(dartStatement a) <+> line <+> !(dartStatement b))
ReturnStatement e =>
pure ("return " <+> !(dartExp e) <+> semi)
EvalExpStatement e =>
pure (!(dartExp e) <+> semi)
ConstDecl n e =>
dartVar final' n (Just e)
LetDecl n maybeE =>
dartVar var' n maybeE
MutateStatement n e =>
pure (dartName n <+> " = " <+> !(dartExp e) <+> semi)
ErrorStatement s =>
pure (assertionError (dartStringDoc s))
ForEverLoop s =>
pure ("while (true)" <+> block !(dartStatement s))
CommentStatement c =>
pure (comment c)
DoNothing => pure empty
dartVar : {auto ctx : Ref Dart DartT}
-> (keyword : Doc)
-> Name
-> Maybe Expression
-> Core Doc
dartVar kw n init = case init of
Just e => pure (kw <+> dartName n <+> " = " <+> !(dartExp e) <+> semi)
Nothing => pure (kw <+> dartName n <+> semi)
dartImport : (String, Doc) -> Doc
dartImport (lib, alias) =
"import \"" <+> text lib <+> "\" as " <+> alias <+> semi
header : List Doc
header = [
text "// @dart = 2.6",
text "// DO NOT CHANGE THIS FILE!",
text "// It has been generated by idris2dart.",
text "// ignore_for_file: non_constant_identifier_names",
text "// ignore_for_file: unnecessary_cast"
]
delayClass : Doc
delayClass = text """
class $Delayed {
$.dynamic Function() e;
$.dynamic value;
$Delayed(this.e);
$.dynamic force() {
final e = this.e;
if (e != null) {
this.value = e();
this.e = null;
}
return this.value;
}
}
"""
nubSort : Ord a => List a -> List a
nubSort = SortedSet.toList . SortedSet.fromList
mainFunctionFor : Doc -> (usesArgs : Bool) -> Doc
mainFunctionFor mainBody = \case
False => "void main()" <+> block mainBody
True => vcat [
"$.List<$.String> $args;",
emptyLine,
"void main($.List<$.String> $$args)" <+> block (vcat ["$args = $$args;", mainBody])
]
compileToDart : Ref Ctxt Defs -> ClosedTerm -> Core Doc
compileToDart defs term = do
(impDefs, impMain) <- compileToImperative defs term
ctx <- newRef Dart (MkDartT (fromList [("dart:core", "$")]) 1 empty empty False False)
dartDefs <- dartStatement impDefs
dartMain <- dartStatement impMain
finalState <- get Dart
let includeLines = concatMap (toList . lines) (SortedSet.toList finalState.includes)
let (importLines, nonImportLines) = partition ("import " `isPrefixOf`) includeLines
let includeImports' = text <$> nubSort importLines
let includes' = text (unlines nonImportLines)
let imports' = dartImport <$> toList finalState.imports
let header' = vcat (header ++ imports' ++ includeImports')
let mainDecl = mainFunctionFor dartMain finalState.usesArgs
let footer = if finalState.usesDelay then delayClass else empty
pure $
header'
<+> emptyLine
<+> mainDecl
<+> line
<+> dartDefs
<+> line
<+> delayClass
<+> includes'
compileToDartFile : String -> Ref Ctxt Defs -> ClosedTerm -> Core ()
compileToDartFile file defs term = do
dartDoc <- compileToDart defs term
Right _ <- coreLift (writeDocToFile file dartDoc)
| Left err => throw (FileErr file err)
pure ()
compile : Ref Ctxt Defs
-> (tmpDir : String)
-> (outputDir : String)
-> ClosedTerm
-> (outfile : String)
-> Core (Maybe String)
compile defs tmpDir outputDir term file = do
compileToDartFile (outputDir ++ "/" ++ file) defs term
pure Nothing
execute : Ref Ctxt Defs -> (tmpDir : String) -> ClosedTerm -> Core ()
execute defs tmpDir term = do
let tempDartFile = tmpDir ++ "/temp.dart"
compileToDartFile tempDartFile defs term
ignore $ coreLift $ system ("dart" ++ " " ++ tempDartFile)
pure ()
dartCodegen : Codegen
dartCodegen = MkCG compile execute Nothing Nothing
main : IO ()
main = mainWithCodegens [("dart", dartCodegen)]
|
If $f$ is eventually nonzero, then $\frac{1}{f}$ is Lebesgue integrable if and only if $f g$ is Lebesgue integrable. |
-- MIT License
-- Copyright (c) 2021 Luca Ciccone and Luca Padovani
-- Permission is hereby granted, free of charge, to any person
-- obtaining a copy of this software and associated documentation
-- files (the "Software"), to deal in the Software without
-- restriction, including without limitation the rights to use,
-- copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the
-- Software is furnished to do so, subject to the following
-- conditions:
-- The above copyright notice and this permission notice shall be
-- included in all copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-- OTHER DEALINGS IN THE SOFTWARE.
{-# OPTIONS --guardedness #-}
open import Data.Empty
open import Data.Product
open import Data.List using ([]; _∷_; _∷ʳ_; _++_)
open import Relation.Nullary
open import Relation.Unary using (_∈_; _⊆_;_∉_)
open import Relation.Binary.PropositionalEquality using (_≡_; refl)
import Relation.Binary.HeterogeneousEquality as Het
open import Common
module HasTrace {ℙ : Set} (message : Message ℙ)
where
open import Trace message
open import SessionType message
open import Transitions message
_HasTrace_ : SessionType -> Trace -> Set
_HasTrace_ T φ = ∃[ S ] (Defined S × Transitions T φ S)
after : ∀{T φ} -> T HasTrace φ -> SessionType
after (S , _ , _) = S
-- data _HasTrace_ : SessionType -> Trace -> Set where
-- does : ∀{T φ S} (tr : Transitions T φ S) (def : Defined S) -> T Does φ
_HasTrace?_ : (T : SessionType) (φ : Trace) -> Dec (T HasTrace φ)
nil HasTrace? _ = no λ { (_ , () , refl)
; (_ , _ , step () _) }
inp f HasTrace? [] = yes (_ , inp , refl)
inp f HasTrace? (I x ∷ φ) with x ∈? f
... | no nfx = no λ { (_ , def , step inp tr) → nfx (transitions+defined->defined tr def) }
... | yes fx with f x .force HasTrace? φ
... | yes (_ , def , tr) = yes (_ , def , step inp tr)
... | no ntφ = no λ { (_ , def , step inp tr) → ntφ (_ , def , tr) }
inp f HasTrace? (O x ∷ φ) = no λ { (_ , _ , step () _) }
out f HasTrace? [] = yes (_ , out , refl)
out f HasTrace? (I x ∷ φ) = no λ { (_ , _ , step () _) }
out f HasTrace? (O x ∷ φ) with x ∈? f
... | no nfx = no λ { (_ , _ , step (out fx) _) → nfx fx }
... | yes fx with f x .force HasTrace? φ
... | yes (_ , def , tr) = yes (_ , def , step (out fx) tr)
... | no ntφ = no λ { (_ , def , step (out fx) tr) → ntφ (_ , def , tr) }
has-trace->defined : ∀{T φ} -> T HasTrace φ -> Defined T
has-trace->defined (_ , tdef , tr) = transitions+defined->defined tr tdef
inp-has-trace : ∀{f x φ} -> f x .force HasTrace φ -> inp f HasTrace (I x ∷ φ)
inp-has-trace (_ , def , tr) = _ , def , step inp tr
inp-has-no-trace : ∀{f x φ} -> ¬ f x .force HasTrace φ -> ¬ inp f HasTrace (I x ∷ φ)
inp-has-no-trace nφ (_ , def , step inp tr) = nφ (_ , def , tr)
out-has-trace : ∀{f x φ} -> f x .force HasTrace φ -> out f HasTrace (O x ∷ φ)
out-has-trace (_ , def , tr) = _ , def , step (out (transitions+defined->defined tr def)) tr
out-has-no-trace : ∀{f x φ} -> ¬ f x .force HasTrace φ -> ¬ out f HasTrace (O x ∷ φ)
out-has-no-trace nφ (_ , def , step (out fx) tr) = nφ (_ , def , tr)
out-has-no-trace->undefined : ∀{f x} -> ¬ out f HasTrace (O x ∷ []) -> ¬ Defined (f x .force)
out-has-no-trace->undefined {f} {x} nt with x ∈? f
... | yes fx = ⊥-elim (nt (_ , fx , step (out fx) refl))
... | no nfx = nfx
unprefix-some : ∀{α φ ψ} -> (α ∷ ψ) ⊑ (α ∷ φ) -> ψ ⊑ φ
unprefix-some (some pre) = pre
⊑-has-trace : ∀{T φ ψ} -> ψ ⊑ φ -> T HasTrace φ -> T HasTrace ψ
⊑-has-trace none (_ , tdef , tr) = _ , transitions+defined->defined tr tdef , refl
⊑-has-trace (some pre) (_ , tdef , step t tr) =
let _ , sdef , sr = ⊑-has-trace pre (_ , tdef , tr) in
_ , sdef , step t sr
split-trace : ∀{T φ ψ} (tφ : T HasTrace φ) -> T HasTrace (φ ++ ψ) -> after tφ HasTrace ψ
split-trace (_ , tdef , refl) tφψ = tφψ
split-trace (_ , tdef , step inp tr) (_ , sdef , step inp sr) = split-trace (_ , tdef , tr) (_ , sdef , sr)
split-trace (_ , tdef , step (out _) tr) (_ , sdef , step (out _) sr) = split-trace (_ , tdef , tr) (_ , sdef , sr)
join-trace : ∀{T φ ψ} (tφ : T HasTrace φ) -> after tφ HasTrace ψ -> T HasTrace (φ ++ ψ)
join-trace (_ , _ , refl) tφ/ψ = tφ/ψ
join-trace (_ , tdef , step t tr) tφ/ψ =
let (_ , sdef , sr) = join-trace (_ , tdef , tr) tφ/ψ in
_ , sdef , step t sr
⊑-has-co-trace : ∀{T φ ψ} -> φ ⊑ ψ -> T HasTrace (co-trace ψ) -> T HasTrace (co-trace φ)
⊑-has-co-trace le tψ = ⊑-has-trace (⊑-co-trace le) tψ
⊑-tran-has-trace : ∀{T φ ψ χ} (pre1 : φ ⊑ ψ) (pre2 : ψ ⊑ χ) ->
(tχ : T HasTrace χ) ->
⊑-has-trace pre1 (⊑-has-trace pre2 tχ) ≡ ⊑-has-trace (⊑-tran pre1 pre2) tχ
⊑-tran-has-trace none none tχ = refl
⊑-tran-has-trace none (some pre2) (fst , fst₁ , step t snd) = refl
⊑-tran-has-trace (some pre1) (some pre2) (_ , def , step _ tr) rewrite ⊑-tran-has-trace pre1 pre2 (_ , def , tr) = refl
⊑-has-trace-after : ∀{T φ} (tφ : T HasTrace φ) -> ⊑-has-trace (⊑-refl φ) tφ ≡ tφ
⊑-has-trace-after (_ , _ , refl) = refl
⊑-has-trace-after (_ , tdef , step inp tr) rewrite ⊑-has-trace-after (_ , tdef , tr) = refl
⊑-has-trace-after (_ , tdef , step (out _) tr) rewrite ⊑-has-trace-after (_ , tdef , tr) = refl
nil-has-no-trace : ∀{φ} -> ¬ nil HasTrace φ
nil-has-no-trace (_ , () , refl)
nil-has-no-trace (_ , _ , step () _)
end-has-empty-trace : ∀{φ T} -> End T -> T HasTrace φ -> φ ≡ []
end-has-empty-trace (inp U) (_ , _ , refl) = refl
end-has-empty-trace (inp U) (_ , def , step inp refl) = ⊥-elim (U _ def)
end-has-empty-trace (inp U) (_ , def , step inp (step t _)) = ⊥-elim (U _ (transition->defined t))
end-has-empty-trace (out U) (_ , _ , refl) = refl
end-has-empty-trace (out U) (_ , _ , step (out !x) _) = ⊥-elim (U _ !x)
has-trace-++ : ∀{T φ ψ} -> T HasTrace (φ ++ ψ) -> T HasTrace φ
has-trace-++ tφψ = ⊑-has-trace ⊑-++ tφψ
trace-coherence : ∀{T φ ψ₁ ψ₂ x y} -> T HasTrace (φ ++ I x ∷ ψ₁) -> T HasTrace (φ ++ O y ∷ ψ₂) -> ⊥
trace-coherence {_} {[]} (_ , _ , step inp _) (_ , _ , step () _)
trace-coherence {_} {I _ ∷ _} (_ , tdef , step inp tr) (_ , sdef , step inp sr) = trace-coherence (_ , tdef , tr) (_ , sdef , sr)
trace-coherence {_} {O _ ∷ _} (_ , tdef , step (out _) tr) (_ , sdef , step (out _) sr) = trace-coherence (_ , tdef , tr) (_ , sdef , sr)
defined->has-empty-trace : ∀{T} -> Defined T -> T HasTrace []
defined->has-empty-trace inp = _ , inp , refl
defined->has-empty-trace out = _ , out , refl
has-trace-double-negation : ∀{T φ} -> ¬ ¬ T HasTrace φ -> T HasTrace φ
has-trace-double-negation {T} {φ} p with T HasTrace? φ
... | yes tφ = tφ
... | no ntφ = ⊥-elim (p ntφ)
{- New -}
not-nil-has-trace : ∀{ϕ} → ¬ (nil HasTrace ϕ)
not-nil-has-trace (.(inp _) , inp , step () _)
not-nil-has-trace (.(out _) , out , step () _)
trace-after-in : ∀{f x ϕ} → (inp f) HasTrace (I x ∷ ϕ) → (f x .force) HasTrace ϕ
trace-after-in (_ , def , step inp red) = _ , def , red
trace-after-out : ∀{f x ϕ} → (out f) HasTrace (O x ∷ ϕ) → (f x .force) HasTrace ϕ
trace-after-out (_ , def , step (out _) red) = _ , def , red
inp-hastrace->defined : ∀{f x tr} → (inp f) HasTrace (I x ∷ tr) → x ∈ dom f
inp-hastrace->defined (_ , def , step inp refl) = def
inp-hastrace->defined (_ , def , step inp (step red _)) = transition->defined red
empty-inp-has-empty-trace : ∀{f ϕ} → EmptyContinuation f → (inp f) HasTrace ϕ → ϕ ≡ []
empty-inp-has-empty-trace e (_ , _ , refl) = refl
empty-inp-has-empty-trace {f} e (_ , _ , step (inp {x = x}) reds) with Defined? (f x .force)
empty-inp-has-empty-trace {f} e (_ , def , step (inp {x = _}) refl) | no ¬def = ⊥-elim (¬def def)
empty-inp-has-empty-trace {f} e (_ , _ , step (inp {x = _}) (step t _)) | no ¬def = ⊥-elim (¬def (transition->defined t))
... | yes def = ⊥-elim (e _ def)
empty-out-has-empty-trace : ∀{f ϕ} → EmptyContinuation f → (out f) HasTrace ϕ → ϕ ≡ []
empty-out-has-empty-trace e (_ , _ , refl) = refl
empty-out-has-empty-trace e (_ , _ , step (out def) _) = ⊥-elim (e _ def) |
The concatenation of a list with a singleton list is the same as the concatenation of the list with the singleton list. |
# already contained in Core
# struct OverflowError <: Exception
# msg::String
# end
struct UnderflowError <: Exception
msg::String
end
function overflow_error(msg = "")
throw( OverflowError(msg) )
end
function underflow_error(msg = "")
throw( UnderflowError(msg) )
end
|
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.HITs.Ints.IsoInt where
open import Cubical.HITs.Ints.IsoInt.Base public
|
! Copyright (C) 2011
! Free Software Foundation, Inc.
! This file is part of the gtk-fortran GTK+ Fortran Interface library.
! This 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, or (at your option)
! any later version.
! This software 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.
! Under Section 7 of GPL version 3, you are granted additional
! permissions described in the GCC Runtime Library Exception, version
! 3.1, as published by the Free Software Foundation.
! You should have received a copy of the GNU General Public License along with
! this program; see the files COPYING3 and COPYING.RUNTIME respectively.
! If not, see <http://www.gnu.org/licenses/>.
!
! Contributed by James Tappin
! Last modification: 12-1-2011
! --------------------------------------------------------
! gtk-hl-menu.f90
! Generated: Tue Oct 29 17:02:03 2013 GMT
! Please do not edit this file directly,
! Edit gtk-hl-menu-tmpl.f90, and use ./mk_gtk_hl.pl to regenerate.
! Generated for GTK+ version: 2.24.0.
! Generated for GLIB version: 2.38.0.
! --------------------------------------------------------
!*
! Pulldown Menu
module gtk_hl_menu
! Implements the GtkMenuBar menu system.
!/
use gtk_sup
use gtk_hl_misc
use iso_c_binding
use iso_fortran_env, only: error_unit
! autogenerated use's
use gtk, only: gtk_check_menu_item_new,&
& gtk_check_menu_item_new_with_label,&
& gtk_check_menu_item_set_active, gtk_menu_bar_new,&
& gtk_menu_bar_set_pack_direction, gtk_menu_item_new,&
& gtk_menu_item_new_with_label, gtk_menu_item_set_submenu,&
& gtk_menu_new, gtk_menu_shell_append, gtk_menu_shell_insert,&
& gtk_radio_menu_item_get_group, gtk_radio_menu_item_new,&
& gtk_radio_menu_item_new_with_label, gtk_check_menu_item_get_active, &
& gtk_separator_menu_item_new, gtk_tearoff_menu_item_new,&
& gtk_widget_add_accelerator, gtk_widget_set_sensitive,&
& gtk_label_new, gtk_label_set_markup, gtk_container_add, &
& gtk_widget_set_tooltip_text, GTK_PACK_DIRECTION_LTR, &
& TRUE, FALSE, g_signal_connect
use g, only: g_slist_length, g_slist_nth, g_slist_nth_data
use gtk_hl_accelerator
implicit none
contains
!+
function hl_gtk_menu_new(orientation, bar) result(menu)
type(c_ptr) :: menu
integer(kind=c_int), intent(in), optional :: orientation, bar
! Menu initializer (mainly for consistency)
!
! ORIENTATION: integer: optional: Whether to lay out the top level
! horizontally or vertically.
! BAR: boolean: optional: Set this to FALSE to create a GtkMenu rather than
! a GtkMenuBar (useful in creating context menus).
!-
integer(kind=c_int) :: orient
logical :: isbar
if (present(orientation)) then
orient= orientation
else
orient = GTK_PACK_DIRECTION_LTR
end if
if (present(bar)) then
isbar = c_f_logical(bar)
else
isbar = .true.
end if
if (isbar) then
menu = gtk_menu_bar_new()
call gtk_menu_bar_set_pack_direction (menu, orient)
else
menu = gtk_menu_new()
end if
end function hl_gtk_menu_new
!+
function hl_gtk_menu_submenu_new(menu, label, tooltip, pos, is_markup, &
& sensitive) result(submenu)
type(c_ptr) :: submenu
type(c_ptr) :: menu
character(kind=c_char), dimension(*), intent(in) :: label
character(kind=c_char), dimension(*), intent(in), optional :: tooltip
integer(kind=c_int), intent(in), optional :: pos
integer(kind=c_int), intent(in), optional :: is_markup, sensitive
! Make a submenu node
!
! MENU: c_ptr: required: The parent of the submenu
! LABEL: string: required: The label of the submenu
! TOOLTIP: string: optional: A tooltip for the submenu.
! POS: integer: optional: The position at which to insert the item
! (omit to append)
! IS_MARKUP: boolean: optional: Set this to TRUE if the label contains
! Pango markup.
! SENSITIVE: boolean: optional: Set to FALSE to make the widget start in an
! insensitive state.
!-
type(c_ptr) :: item, label_w
logical :: markup
if (present(is_markup)) then
markup=c_f_logical(is_markup)
else
markup=.false.
end if
! Create a menu item
if (markup) then
item = gtk_menu_item_new()
label_w = gtk_label_new(label)
call gtk_label_set_markup(label_w, label)
call gtk_container_add(item, label_w)
else
item = gtk_menu_item_new_with_label(label)
end if
! Create a submenu and attach it to the item
submenu = gtk_menu_new()
call gtk_menu_item_set_submenu(item, submenu)
! Insert it to the parent
if (present(pos)) then
call gtk_menu_shell_insert(menu, item, pos)
else
call gtk_menu_shell_append(menu, item)
end if
if (present(sensitive)) call gtk_widget_set_sensitive(item, sensitive)
if (present(tooltip)) call gtk_widget_set_tooltip_text(item, tooltip)
end function hl_gtk_menu_submenu_new
!+
function hl_gtk_menu_item_new(menu, label, activate, data, tooltip, &
& pos, tearoff, sensitive, accel_key, accel_mods, accel_group, &
& accel_flags, is_markup) result(item)
type(c_ptr) :: item
type(c_ptr) :: menu
character(kind=c_char), dimension(*), intent(in), optional :: label
type(c_funptr), optional :: activate
type(c_ptr), optional :: data
character(kind=c_char), dimension(*), intent(in), optional :: tooltip
integer(kind=c_int), intent(in), optional :: pos
integer(kind=c_int), intent(in), optional :: tearoff, sensitive
character(kind=c_char), dimension(*), optional, intent(in) :: accel_key
integer(kind=c_int), optional, intent(in) :: accel_mods, accel_flags
type(c_ptr), optional, intent(in) :: accel_group
integer(kind=c_int), intent(in), optional :: is_markup
! Make a menu item or separator
!
! MENU: c_ptr: required: The parent menu.
! LABEL: string: optional: The label for the menu, if absent then insert
! a separator.
! ACTIVATE: c_funptr: optional: The callback function for the
! activate signal
! DATA: c_ptr: optional: Data to pass to the callback.
! TOOLTIP: string: optional: A tooltip for the menu item.
! POS: integer: optional: The position at which to insert the item
! (omit to append)
! TEAROFF: boolean: optional: Set to TRUE to make a tearoff point.
! SENSITIVE: boolean: optional: Set to FALSE to make the widget start in an
! insensitive state.
! ACCEL_KEY: string: optional: Set to the character value or code of a
! key to use as an accelerator.
! ACCEL_MODS: c_int: optional: Set to the modifiers for the accelerator.
! (If not given then GTK_CONTROL_MASK is assumed).
! ACCEL_GROUP: c_ptr: optional: The accelerator group to which the
! accelerator is attached, must have been added to the top-level
! window.
! ACCEL_FLAGS: c_int: optional: Flags for the accelerator, if not present
! then GTK_ACCEL_VISIBLE, is used (to hide the accelerator,
! use ACCEL_FLAGS=0).
! IS_MARKUP: boolean: optional: Set this to TRUE if the label contains
! Pango markup.
!-
integer(kind=c_int) :: istear
logical :: markup
type(c_ptr) :: label_w
if (present(tearoff)) then
istear = tearoff
else
istear = FALSE
end if
if (present(is_markup)) then
markup=c_f_logical(is_markup)
else
markup=.false.
end if
! Create the menu item
if (present(label)) then
if (markup) then
item=gtk_menu_item_new()
label_w=gtk_label_new(label)
call gtk_label_set_markup(label_w, label)
call gtk_container_add(item,label_w)
else
item = gtk_menu_item_new_with_label(label)
end if
else if (istear == TRUE) then
item = gtk_tearoff_menu_item_new()
else
item = gtk_separator_menu_item_new()
end if
! Insert it to the parent
if (present(pos)) then
call gtk_menu_shell_insert(menu, item, pos)
else
call gtk_menu_shell_append(menu, item)
end if
! If present, connect the callback
if (present(activate)) then
if (.not. present(label)) then
write(error_unit, *) &
& "HL_GTK_MENU_ITEM: Cannot connect a callback to a separator"
return
end if
if (present(data)) then
call g_signal_connect(item, "activate"//c_null_char, activate, data)
else
call g_signal_connect(item, "activate"//c_null_char, activate)
end if
! An accelerator
if (present(accel_key) .and. present(accel_group)) &
& call hl_gtk_widget_add_accelerator(item, "activate"//c_null_char, &
& accel_group, accel_key, accel_mods, accel_flags)
end if
! Attach a tooltip
if (present(tooltip)) call gtk_widget_set_tooltip_text(item, tooltip)
! sensitive?
if (present(sensitive)) call gtk_widget_set_sensitive(item, sensitive)
end function hl_gtk_menu_item_new
!+
function hl_gtk_check_menu_item_new(menu, label, toggled, data, &
& tooltip, pos, initial_state, sensitive, is_markup) result(item)
type(c_ptr) :: item
type(c_ptr) :: menu
character(kind=c_char), dimension(*), intent(in) :: label
type(c_funptr), optional :: toggled
type(c_ptr), optional :: data
character(kind=c_char), dimension(*), intent(in), optional :: tooltip
integer(kind=c_int), optional, intent(in) :: pos
integer(kind=c_int), optional, intent(in) :: initial_state
integer(kind=c_int), optional, intent(in) :: sensitive, is_markup
! Make a check button menu item.
!
! MENU: c_ptr: required: The parent menu.
! LABEL: string: required: The label for the menu.
! TOGGLED: c_funptr: optional: The callback function for the
! "toggled" signal
! DATA: c_ptr: optional: Data to pass to the callback.
! TOOLTIP: string: optional: A tooltip for the menu item.
! POS: integer: optional: The position at which to insert the item
! (omit to append)
! INITIAL_STATE: boolean: optional: Whether the item is initially selected.
! SENSITIVE: boolean: optional: Set to FALSE to make the widget start in an
! insensitive state.
! IS_MARKUP: boolean: optional: Set this to TRUE if the label contains
! Pango markup.
!-
type(c_ptr) :: label_w
logical :: markup
if (present(is_markup)) then
markup = c_f_logical(is_markup)
else
markup = .false.
end if
! Create the menu item
if (markup) then
item = gtk_check_menu_item_new()
label_w=gtk_label_new(c_null_char)
call gtk_label_set_markup(label_w, label)
call gtk_container_add(item, label_w)
else
item = gtk_check_menu_item_new_with_label(label)
end if
! Insert it to the parent
if (present(pos)) then
call gtk_menu_shell_insert(menu, item, pos)
else
call gtk_menu_shell_append(menu, item)
end if
! Set the state
if (present(initial_state)) &
& call gtk_check_menu_item_set_active(item, initial_state)
! If present, connect the callback
if (present(toggled)) then
if (present(data)) then
call g_signal_connect(item, "toggled"//c_null_char, toggled, data)
else
call g_signal_connect(item, "toggled"//c_null_char, toggled)
end if
end if
! Attach a tooltip
if (present(tooltip)) call gtk_widget_set_tooltip_text(item, tooltip)
! sensitive?
if (present(sensitive)) call gtk_widget_set_sensitive(item, sensitive)
end function hl_gtk_check_menu_item_new
!+
function hl_gtk_radio_menu_item_new(group, menu, label, toggled, data, &
& tooltip, pos, sensitive, is_markup) result(item)
type(c_ptr) :: item
type(c_ptr), intent(inout) :: group
type(c_ptr), intent(in) :: menu
character(kind=c_char), dimension(*), intent(in) :: label
type(c_funptr), optional :: toggled
type(c_ptr), optional :: data
character(kind=c_char), dimension(*), intent(in), optional :: tooltip
integer(kind=c_int), optional, intent(in) :: pos
integer(kind=c_int), optional, intent(in) :: sensitive, is_markup
! Make a radio button menu item
!
! GROUP: c_ptr: required: The group for the radio item (C_NULL_PTR for a
! new group).
! MENU: c_ptr: required: The parent menu.
! LABEL: string: required: The label for the menu.
! TOGGLED: c_funptr: optional: The callback function for the
! "toggled" signal
! DATA: c_ptr: optional: Data to pass to the callback.
! TOOLTIP: string: optional: A tooltip for the menu item.
! POS: integer: optional: The position at which to insert the item
! (omit to append)
! SENSITIVE: boolean: optional: Set to FALSE to make the widget start in an
! insensitive state.
! IS_MARKUP: boolean: optional: Set this to TRUE if the label contains
! Pango markup.
!-
type(c_ptr) :: label_w
logical :: markup
if (present(is_markup)) then
markup = c_f_logical(is_markup)
else
markup = .false.
end if
! Create the menu item
if (markup) then
item = gtk_radio_menu_item_new(group)
label_w=gtk_label_new(c_null_char)
call gtk_label_set_markup(label_w, label)
call gtk_container_add(item, label_w)
else
item = gtk_radio_menu_item_new_with_label(group, label)
end if
group = gtk_radio_menu_item_get_group(item)
! Insert it to the parent
if (present(pos)) then
call gtk_menu_shell_insert(menu, item, pos)
else
call gtk_menu_shell_append(menu, item)
end if
! If present, connect the callback
if (present(toggled)) then
if (present(data)) then
call g_signal_connect(item, "toggled"//c_null_char, toggled, data)
else
call g_signal_connect(item, "toggled"//c_null_char, toggled)
end if
end if
! Attach a tooltip
if (present(tooltip)) call gtk_widget_set_tooltip_text(item, tooltip)
! sensitive?
if (present(sensitive)) call gtk_widget_set_sensitive(item, sensitive)
end function hl_gtk_radio_menu_item_new
!+
subroutine hl_gtk_radio_menu_group_set_select(group, index)
type(c_ptr), intent(in) :: group
integer(kind=c_int), intent(in) :: index
! Set the indexth button of a radio menu group
!
! GROUP: c_ptr: required: The group of the last button added to
! the radio menu
! INDEX: integer: required: The index of the button to set
! (starting from the first as 0).
!-
integer(kind=c_int) :: nbuts
type(c_ptr) :: datan
nbuts = g_slist_length(group)
! Note that GROUP actually points to the last button added and to the
! group of the next to last & so on
datan= g_slist_nth_data(group, nbuts-index-1_c_int)
call gtk_check_menu_item_set_active(datan, TRUE)
end subroutine hl_gtk_radio_menu_group_set_select
!+
function hl_gtk_radio_menu_group_get_select(group) result(index)
integer(kind=c_int) :: index
type(c_ptr) :: group
! Find the selected button in a radio group in a menu.
!
! GROUP: c_ptr: required: The group of the last button added to
! the radio menu
!-
integer(kind=c_int) :: nbuts, i
type(c_ptr) :: but
nbuts = g_slist_length(group)
index=-1
do i = 1, nbuts
but = g_slist_nth_data(group, nbuts-i)
if (.not. c_associated(but)) exit
if (gtk_check_menu_item_get_active(but)==TRUE) then
index = i-1
return
end if
end do
end function hl_gtk_radio_menu_group_get_select
!+
subroutine hl_gtk_menu_item_set_label_markup(item, label)
type(c_ptr) :: item
character(kind=c_char), dimension(*), intent(in) :: label
! Set a markup label on a menu item
!
! ITEM: c_ptr: required: The menu item to relabel
! LABEL: string: required: The string (with Pango markup) to apply.
!
! Normally if the label does not need Pango markup, then
! gtk_menu_item_set_label can be used.
!-
call hl_gtk_bin_set_label_markup(item, label)
end subroutine hl_gtk_menu_item_set_label_markup
end module gtk_hl_menu
|
If $f$ converges to $l$, then $f - l$ converges to $0$. |
open import SOAS.Common
open import SOAS.Families.Core
open import Categories.Object.Initial
open import SOAS.Coalgebraic.Strength
import SOAS.Metatheory.MetaAlgebra
-- Substitution structure by initiality
module SOAS.Metatheory.Substitution {T : Set}
(⅀F : Functor 𝔽amiliesₛ 𝔽amiliesₛ) (⅀:Str : Strength ⅀F)
(𝔛 : Familyₛ) (open SOAS.Metatheory.MetaAlgebra ⅀F 𝔛)
(𝕋:Init : Initial 𝕄etaAlgebras)
where
open import SOAS.Context
open import SOAS.Variable
open import SOAS.Abstract.Hom
import SOAS.Abstract.Coalgebra as →□ ; open →□.Sorted
import SOAS.Abstract.Box as □ ; open □.Sorted
open import SOAS.Abstract.Monoid
open import SOAS.Coalgebraic.Map
open import SOAS.Coalgebraic.Monoid
open import SOAS.Coalgebraic.Lift
open import SOAS.Metatheory.Algebra ⅀F
open import SOAS.Metatheory.Semantics ⅀F ⅀:Str 𝔛 𝕋:Init
open import SOAS.Metatheory.Traversal ⅀F ⅀:Str 𝔛 𝕋:Init
open import SOAS.Metatheory.Renaming ⅀F ⅀:Str 𝔛 𝕋:Init
open import SOAS.Metatheory.Coalgebraic ⅀F ⅀:Str 𝔛 𝕋:Init
open Strength ⅀:Str
private
variable
Γ Δ : Ctx
α β : T
-- Substitution is a 𝕋-parametrised traversal into 𝕋
module Substitution = Traversal 𝕋ᴮ 𝕒𝕝𝕘 id 𝕞𝕧𝕒𝕣
𝕤𝕦𝕓 : 𝕋 ⇾̣ 〖 𝕋 , 𝕋 〗
𝕤𝕦𝕓 = Substitution.𝕥𝕣𝕒𝕧
-- The renaming and algebra structures on 𝕋 are compatible, so 𝕤𝕦𝕓 is coalgebraic
𝕤𝕦𝕓ᶜ : Coalgebraic 𝕋ᴮ 𝕋ᴮ 𝕋ᴮ 𝕤𝕦𝕓
𝕤𝕦𝕓ᶜ = Travᶜ.𝕥𝕣𝕒𝕧ᶜ 𝕋ᴮ 𝕒𝕝𝕘 id 𝕞𝕧𝕒𝕣 𝕋ᴮ idᴮ⇒ Renaming.𝕤𝕖𝕞ᵃ⇒
module 𝕤𝕦𝕓ᶜ = Coalgebraic 𝕤𝕦𝕓ᶜ
-- Compatibility of renaming and substitution
compat : {ρ : Γ ↝ Δ} (t : 𝕋 α Γ) → 𝕣𝕖𝕟 t ρ ≡ 𝕤𝕦𝕓 t (𝕧𝕒𝕣 ∘ ρ)
compat {ρ = ρ} t = begin 𝕣𝕖𝕟 t ρ ≡˘⟨ 𝕥𝕣𝕒𝕧-η≈id 𝕋ᴮ id refl ⟩
𝕤𝕦𝕓 (𝕣𝕖𝕟 t ρ) 𝕧𝕒𝕣 ≡⟨ 𝕤𝕦𝕓ᶜ.f∘r ⟩
𝕤𝕦𝕓 t (𝕧𝕒𝕣 ∘ ρ) ∎ where open ≡-Reasoning
-- Substitution associativity law
𝕤𝕦𝕓-comp : MapEq₂ 𝕋ᴮ 𝕋ᴮ 𝕒𝕝𝕘 (λ t σ ς → 𝕤𝕦𝕓 (𝕤𝕦𝕓 t σ) ς)
(λ t σ ς → 𝕤𝕦𝕓 t (λ v → 𝕤𝕦𝕓 (σ v) ς))
𝕤𝕦𝕓-comp = record
{ φ = id
; ϕ = 𝕤𝕦𝕓
; χ = 𝕞𝕧𝕒𝕣
; f⟨𝑣⟩ = 𝕥≈₁ 𝕥⟨𝕧⟩
; f⟨𝑚⟩ = trans (𝕥≈₁ 𝕥⟨𝕞⟩) 𝕥⟨𝕞⟩
; f⟨𝑎⟩ = λ{ {σ = σ}{ς}{t} → begin
𝕤𝕦𝕓 (𝕤𝕦𝕓 (𝕒𝕝𝕘 t) σ) ς
≡⟨ 𝕥≈₁ 𝕥⟨𝕒⟩ ⟩
𝕤𝕦𝕓 (𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 (⅀₁ 𝕤𝕦𝕓 t) σ)) ς
≡⟨ 𝕥⟨𝕒⟩ ⟩
𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 (⅀₁ 𝕤𝕦𝕓 (str 𝕋ᴮ 𝕋 (⅀₁ 𝕤𝕦𝕓 t) σ)) ς)
≡˘⟨ congr (str-nat₂ 𝕤𝕦𝕓 (⅀₁ 𝕤𝕦𝕓 t) σ) (λ - → 𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 - ς)) ⟩
𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 (str 𝕋ᴮ 〖 𝕋 , 𝕋 〗 (⅀.F₁ (λ { h ς → 𝕤𝕦𝕓 (h ς) }) (⅀₁ 𝕤𝕦𝕓 t)) σ) ς)
≡˘⟨ congr ⅀.homomorphism (λ - → 𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 (str 𝕋ᴮ 〖 𝕋 , 𝕋 〗 - σ) ς)) ⟩
𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 (str 𝕋ᴮ 〖 𝕋 , 𝕋 〗 (⅀₁ (λ{ t σ → 𝕤𝕦𝕓 (𝕤𝕦𝕓 t σ)}) t) σ) ς)
∎ }
; g⟨𝑣⟩ = 𝕥⟨𝕧⟩
; g⟨𝑚⟩ = 𝕥⟨𝕞⟩
; g⟨𝑎⟩ = λ{ {σ = σ}{ς}{t} → begin
𝕤𝕦𝕓 (𝕒𝕝𝕘 t) (λ v → 𝕤𝕦𝕓 (σ v) ς)
≡⟨ 𝕥⟨𝕒⟩ ⟩
𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 (⅀₁ 𝕤𝕦𝕓 t) (λ v → 𝕤𝕦𝕓 (σ v) ς))
≡⟨ cong 𝕒𝕝𝕘 (str-dist 𝕋 𝕤𝕦𝕓ᶜ (⅀₁ 𝕤𝕦𝕓 t) (λ {τ} z → σ z) ς) ⟩
𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 (str 𝕋ᴮ 〖 𝕋 , 𝕋 〗 (⅀.F₁ (precomp 𝕋 𝕤𝕦𝕓) (⅀₁ 𝕤𝕦𝕓 t)) σ) ς)
≡˘⟨ congr ⅀.homomorphism (λ - → 𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 (str 𝕋ᴮ 〖 𝕋 , 𝕋 〗 - σ) ς)) ⟩
𝕒𝕝𝕘 (str 𝕋ᴮ 𝕋 (str 𝕋ᴮ 〖 𝕋 , 𝕋 〗 (⅀₁ (λ{ t σ ς → 𝕤𝕦𝕓 t (λ v → 𝕤𝕦𝕓 (σ v) ς)}) t) σ) ς)
∎ }
} where open ≡-Reasoning ; open Substitution
-- Coalgebraic monoid structure on 𝕋
𝕋ᵐ : Mon 𝕋
𝕋ᵐ = record
{ η = 𝕧𝕒𝕣
; μ = 𝕤𝕦𝕓
; lunit = Substitution.𝕥⟨𝕧⟩
; runit = λ{ {t = t} → trans (𝕥𝕣𝕒𝕧-η≈𝕤𝕖𝕞 𝕋ᴮ 𝕋ᵃ id refl) 𝕤𝕖𝕞-id }
; assoc = λ{ {t = t} → MapEq₂.≈ 𝕤𝕦𝕓-comp t }
}
open Mon 𝕋ᵐ using ([_/] ; [_,_/]₂ ; lunit ; runit ; assoc) public
𝕋ᴹ : CoalgMon 𝕋
𝕋ᴹ = record { ᴮ = 𝕋ᴮ ; ᵐ = 𝕋ᵐ ; η-compat = refl ; μ-compat = λ{ {t = t} → compat t } }
-- Corollaries: renaming and simultaneous substitution commutes with
-- single-variable substitution
open import SOAS.ContextMaps.Combinators
𝕣𝕖𝕟[/] : (ρ : Γ ↝ Δ)(b : 𝕋 α (β ∙ Γ))(a : 𝕋 β Γ)
→ 𝕣𝕖𝕟 ([ a /] b) ρ ≡ [ (𝕣𝕖𝕟 a ρ) /] (𝕣𝕖𝕟 b (rlift _ ρ))
𝕣𝕖𝕟[/] ρ b a = begin
𝕣𝕖𝕟 ([ a /] b) ρ
≡⟨ 𝕤𝕦𝕓ᶜ.r∘f ⟩
𝕤𝕦𝕓 b (λ v → 𝕣𝕖𝕟 (add 𝕋 a 𝕧𝕒𝕣 v) ρ)
≡⟨ cong (𝕤𝕦𝕓 b) (dext (λ{ new → refl ; (old y) → Renaming.𝕥⟨𝕧⟩})) ⟩
𝕤𝕦𝕓 b (λ v → add 𝕋 (𝕣𝕖𝕟 a ρ) 𝕧𝕒𝕣 (rlift _ ρ v))
≡˘⟨ 𝕤𝕦𝕓ᶜ.f∘r ⟩
[ 𝕣𝕖𝕟 a ρ /] (𝕣𝕖𝕟 b (rlift _ ρ))
∎ where open ≡-Reasoning
𝕤𝕦𝕓[/] : (σ : Γ ~[ 𝕋 ]↝ Δ)(b : 𝕋 α (β ∙ Γ))(a : 𝕋 β Γ)
→ 𝕤𝕦𝕓 ([ a /] b) σ ≡ [ 𝕤𝕦𝕓 a σ /] (𝕤𝕦𝕓 b (lift 𝕋ᴮ ⌈ β ⌋ σ))
𝕤𝕦𝕓[/] {β = β} σ b a = begin
𝕤𝕦𝕓 ([ a /] b) σ
≡⟨ assoc ⟩
𝕤𝕦𝕓 b (λ v → 𝕤𝕦𝕓 (add 𝕋 a 𝕧𝕒𝕣 v) σ)
≡⟨ cong (𝕤𝕦𝕓 b) (dext (λ{ new → sym lunit ; (old v) → sym (begin
𝕤𝕦𝕓 (𝕣𝕖𝕟 (σ v) old) (add 𝕋 (𝕤𝕦𝕓 a σ) 𝕧𝕒𝕣)
≡⟨ 𝕤𝕦𝕓ᶜ.f∘r ⟩
𝕤𝕦𝕓 (σ v) (λ v → add 𝕋 (𝕤𝕦𝕓 a σ) 𝕧𝕒𝕣 (old v))
≡⟨ cong (𝕤𝕦𝕓 (σ v)) (dext (λ{ new → refl ; (old v) → refl})) ⟩
𝕤𝕦𝕓 (σ v) 𝕧𝕒𝕣
≡⟨ runit ⟩
σ v
≡˘⟨ lunit ⟩
𝕤𝕦𝕓 (𝕧𝕒𝕣 v) σ
∎)})) ⟩
𝕤𝕦𝕓 b (λ v → 𝕤𝕦𝕓 (lift 𝕋ᴮ ⌈ β ⌋ σ v) (add 𝕋 (𝕤𝕦𝕓 a σ) 𝕧𝕒𝕣))
≡˘⟨ assoc ⟩
[ 𝕤𝕦𝕓 a σ /] (𝕤𝕦𝕓 b (lift 𝕋ᴮ ⌈ β ⌋ σ))
∎ where open ≡-Reasoning
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Friggeri Resume/CV
% XeLaTeX Template
% Version 1.2 (3/5/15)
%
% This template has been downloaded from:
% http://www.LaTeXTemplates.com
%
% Original author:
% Adrien Friggeri ([email protected])
% https://github.com/afriggeri/CV
%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
%
% Important notes:
% This template needs to be compiled with XeLaTeX and the bibliography, if used,
% needs to be compiled with biber rather than bibtex.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[]{friggeri-cv} % Add 'print' as an option into the square bracket to remove colors from this template for printing
\begin{document}
\header{carl-philipp }{harmant}{software engineer}
%----------------------------------------------------------------------------------------
% SIDEBAR SECTION
%----------------------------------------------------------------------------------------
\begin{aside} % In the aside, each new line forces a line break
\section{about}
{\color{darkgray}Chicago, Illinois
USA
~
+1 (312) 834 1637
~
\email{[email protected]}
\linkedin{carlphilipp}
\github{carlphilipp}
\section{languages}
english (fluent)
french (native)
\section{programming}
%{color{red} $\varheartsuit$} Java
%{\color{red} $\varheartsuit$} Android
Java, Kotlin
Android, \LaTeX
JavaScript, SQL
\section{frameworks}
Spring, Camel
Dropwizard, Vert.x
RxJava, OSGi
\section{tools}
Gradle, Maven ,Git
JIRA, Bamboo
GitHub
\section{databases}
Oracle, MySQL
MongoDB}
\section{servers}
Tomcat, Karaf
Apache, JBoss
\section{os}
GNU/Linux, OSX
Windows
%\section{interests}
%Running
%Basketball
%Volleyball
%Travels
\end{aside}
\section{personal synopsis}
Currently working as a software engineer, I am interested in exploring new challenges. I am passionate about developing, configuring and testing software. My preferred programming language is Java, however I am open to learning about or utilizing any programming language. In my free time, I enjoy working on my Android application "Chicago Commutes", a Chicago public transit tracker, as well as publishing some of my source code on GitHub. I'm also a member of the Chicago Java User group.
%----------------------------------------------------------------------------------------
% WORK EXPERIENCE SECTION
%----------------------------------------------------------------------------------------
\section{experience}
\begin{entrylist}
\entry
{2017--Present}
{1 year 6 months}
{Senior Software Engineer}
{Slalom}
{Chicago, Illinois, Unites States}
{Consultant}
\vspace{-7mm}
\end{entrylist}
%------------------------------------------------
\begin{entrylist}
\entry
{2015--2017}
{8 months}
{Senior Software Engineer}
{Peapod Propulsion Labs}
{Chicago, Illinois, Unites States}
{Same as above.
}
\vspace{-7mm}
\end{entrylist}
%------------------------------------------------
\begin{entrylist}
\entry
{2015--2017}
{1 year 4 months}
{Software Engineer}
{Peapod Propulsion Labs}
{Chicago, Illinois, Unites States}
{Member of the Web Center team, in charge of developing and maintaining several public websites. Some of my daily responsibilities include:\\
\vspace{-4mm}
\begin{itemize}
\item Collaborating with product owners, business analysts and other team members in a cross-functional Agile environment to produce a content management system that is fully integrated with various loyalty, coupon, and user account systems.
\item Developing a Spring MVC proxy application around our ESB to allow OAuth2 protected REST APIs to be used by our websites.
\item Developing a modular REST-driven integration API using Apache Camel, Karaf, ActiveMQ and various other libraries.
\item Designing and implementing new features using TDD (Test Driven Development).
\item Improving software quality, reusability, extensibility and consistency.
\item Verifying and validating features via unit testing, integration testing and automated acceptance testing (Serenity BDD).
\item Participating in support rotation and troubleshooting production issues to ensure the continued operations of the business.
\item Main technologies used : Java, Spring, Apache Camel, OSGi, OAuth2, ActiveMQ.
\end{itemize}
}
\vspace{-7mm}
\end{entrylist}
%------------------------------------------------
\begin{entrylist}
\entry
{2012--2015}
{3 years 1 month}
{Software Consultant}
{Pros}
{Chicago, Illinois, Unites States}
{I was part of the Professional Services team providing expertise to customers related to the
Configure/Price/Quote (CPQ) solutions and more specifically involved in the following activities:\\
\vspace{-4mm}
\begin{itemize}
\item Integrating Pros CPQ solutions in the IT landscape by using web services.
\item Interfacing Pros CPQ solutions for data loading purposes.
\item Development of additional Java EE plugins to fit specific customer needs.
\item Designing the User Interface (HTML based xml files, CSS, Javascript).
\item Java-based macrolanguage developing and use of built-in configuration tools.
\item Responsible for deploying in our Cloud environment.
%\item Issue management/resolution in a SaaS environment.
\item Main technologies used : Java, JavaScript, HTML, CSS, Salesforce.com (Apex, Force.com), Oracle, JBoss, JSON, XML, SOAP.
\end{itemize}}
\vspace{-7mm}
\end{entrylist}
%------------------------------------------------
\begin{entrylist}
\entry
{2011}
{6 months}
{Java EE Developer}
{Fujitsu Technology Solutions}
{Luxembourg City, Luxembourg}
{Arquillian is a tool, made by JBoss, which allows developers to test the components of their
application in a container:\\
\vspace{-4mm}
\begin{itemize}
\item Made a solution to improve the way to use Arquillian.
\item Improved the company test process by the creation of a Maven plugin which generates an Arquillian test class.
\item Automated search of dependencies needed for the archive deployed on the server.
\item Utilized Maven, JUnit, EJBs, Cobertura, and many other tools and frameworks.
\end{itemize}}
\vspace{-7mm}
\end{entrylist}
%------------------------------------------------
\begin{entrylist}
\entry
{2010}
{5 months}
{Analyst Programmer}
{Sailendra}
{Nancy, France}
{Sailendra created a technology of user profiling. That technology creates a profile of each user and predicts their comportments based on their actions and artificial intelligence algorithms.\\
\vspace{-4mm}
\begin{itemize}
\item Managed a project from initiation to implementation overseeing the planning, functional specifications, technical specifications, development and testing.
\item Worked with the client to ascertain and identify their specific requirements.
\item Automated search of dependencies needed for the archive deployed on the server.
\item Created a Firefox plugin for Salendra technology and learnt new technologies like XUL, Spring, Zope/Plone, DTML or Python.
\end{itemize}}
\vspace{-7mm}
\end{entrylist}
%----------------------------------------------------------------------------------------
% PROJECTS SECTION
%----------------------------------------------------------------------------------------
\section{personnal projects}
\begin{entrylist}
\entry
{2014--2017}
{}
{Chicago Commutes}
{ Android Application}
{}
{Android application that helps commuting in Chicago. CTA (trains/buses) \& Divvy (bikes).\\
Technology used : Android SDK, XML, JSON, Google APIs, RxJava, Realm.\\
\footnotesize{Source: \href{https://github.com/carlphilipp/chicago-commutes}{https://github.com/carlphilipp/chicago-commutes}}\\
\footnotesize{Download: \href{https://play.google.com/store/apps/details?id=fr.cph.chicago}{https://play.google.com/store/apps/details?id=fr.cph.chicago}}}
\end{entrylist}
\begin{entrylist}
\entry
{2013--2017}
{}
{Stock Tracker}
{ Website \& Android Application}
{}
{Website and Android application that helps following your stock performance.\\
Technology used: Java, Android SDK, JSON, YQL (Yahoo Query Language), JSP, JSTL, MyBatis,
JUnit, Ant, Cobertura, PMD, Checkstyle, Quartz, JQuery, flotr2, Jasper, Dropbox API, JavaMail,
MySQL, Tomcat.\\
\footnotesize{Sources: \href{https://github.com/carlphilipp/stock-tracker}{https://github.com/carlphilipp/stock-tracker} \& \href{https://github.com/carlphilipp/stock-tracker}{https://github.com/carlphilipp/stock-tracker-android}}}
\end{entrylist}
\begin{entrylist}
\entry
{2014--2016}
{}
{Be My Chef}
{ RESTful API}
{}
{Java-based RESTful API with JSON output.\\
Technology used : Java, Maven, Spring Boot, Jackson, JSON, JUnit, Mockito, Stripe, Mandrill, GeoJSON, Quartz, Findbugs, Jacoco, PMD, MongoDB, JIRA, Git.\\
\footnotesize{Source: \href{https://github.com/carlphilipp/be-my-chef}{https://github.com/carlphilipp/be-my-chef}}
}
\end{entrylist}
%\begin{entrylist}
%\entry
%{2009--2012}
%{}
%{Management tool for Hyperiums.com}
%{Website}
%{}
%{Alliance management tool to help players gather and analyze data.\\
%Technology used : Java, JSP, JSTL, JQuery, iBATIS, PHP, Wamp, MySQL, Tomcat.}
%\end{entrylist}
%----------------------------------------------------------------------------------------
% EDUCATION SECTION
%----------------------------------------------------------------------------------------
\section{education}
\begin{entrylist}
%------------------------------------------------
\entry
{2013}
{}
{Masters {\normalfont of Software Engineering}}
{}
{Exia.Cesi, Nancy, France}
{}
%------------------------------------------------
\entry
{2011}
{}
{Bachelors {\normalfont of Software Engineering}}
{}
{Exia.Cesi, Nancy, France}
{}
%------------------------------------------------
\end{entrylist}
%----------------------------------------------------------------------------------------
% CERTIFICATIONS
%----------------------------------------------------------------------------------------
\section{certifications}
\begin{entrylist}
%------------------------------------------------
\entry
{2015}
{}
{MongoDB for Java Developers}
{MongoDB University}
{}
{}
\entry
{2013}
{}
{MongoDB for Node.js Developers}
{MongoDB University}
{}
{}
\entry
{2011}
{}
{OCJP : Oracle Certified Java SE 6 Programmer}
{Oracle}
{}
{}
%------------------------------------------------
\end{entrylist}
%----------------------------------------------------------------------------------------
% INTERESTS SECTION
%----------------------------------------------------------------------------------------
%\section{interests}
%In my spare time, I enjoy running, biking and playing basketball. I ran two marathons in Chicago. I also enjoy reading about and working with new technology, both software and hardware products. I love to travel and explore foreign countries to experience different languages, lifestyles and cultures.
\end{document} |
Publish by in Category home design ideas at May 27th, 2018. Tagged with exterior roll up motorized solar shades. exterior roll up solar shades. exterior roll up solar shades 12 feet. indoor roll up solar shades. installing roll up solar shades. interior roll up solar shades. outdoor roll up solar shades. outdoor roll up solar window shades. roll up solar shades. roll up solar shades outdoor. solar screen roll up shades.
Roll Up Solar Shades have 50 picture of home design ideas, it's including Roll Up Solar Shades Absurd Outdoor Rollup Sun Erikaemeren Home Design Ideas. Roll Up Solar Shades Wonderful Contactmpow Home Design Ideas. Roll Up Solar Shades Amazing Decoration In Patio Backyard Decorating Pictures Home Design Ideas. Roll Up Solar Shades Unthinkable Outdoor Rollup Sun Healthcareoasis Home Design Ideas. Roll Up Solar Shades Astound Outdoor Rollup Sun Healthcareoasis Home Design Ideas.
Tags : exterior roll up motorized solar shades. exterior roll up solar shades. exterior roll up solar shades 12 feet. indoor roll up solar shades. installing roll up solar shades. interior roll up solar shades. outdoor roll up solar shades. outdoor roll up solar window shades. roll up solar shades. roll up solar shades outdoor. solar screen roll up shades. |
#include <stan/math/prim/scal.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
#include <limits>
TEST(MathFunctions, fmaxFinite) {
using stan::math::fmax;
EXPECT_FLOAT_EQ(1.0, fmax(1, 0));
EXPECT_FLOAT_EQ(1.0, fmax(1.0, 0));
EXPECT_FLOAT_EQ(1.0, fmax(1, 0.0));
EXPECT_FLOAT_EQ(1.0, fmax(1.0, 0.0));
EXPECT_FLOAT_EQ(1.0, fmax(0, 1));
EXPECT_FLOAT_EQ(1.0, fmax(0, 1.0));
EXPECT_FLOAT_EQ(1.0, fmax(0.0, 1));
EXPECT_FLOAT_EQ(1.0, fmax(0.0, 1.0));
}
TEST(MathFunctions, fmaxNaN) {
using stan::math::fmax;
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_FLOAT_EQ(1.0, fmax(1, nan));
EXPECT_FLOAT_EQ(1.0, fmax(nan, 1));
EXPECT_PRED1(boost::math::isnan<double>, stan::math::fmax(nan, nan));
}
TEST(MathFunctions, fmaxInf) {
using stan::math::fmax;
double inf = std::numeric_limits<double>::infinity();
EXPECT_FLOAT_EQ(inf, fmax(inf, 1));
EXPECT_FLOAT_EQ(inf, fmax(1, inf));
EXPECT_FLOAT_EQ(inf, fmax(inf, -inf));
EXPECT_FLOAT_EQ(inf, fmax(-inf, inf));
}
|
[STATEMENT]
lemma subst_trm_ty_eqvt[eqvt]:
fixes pi::"tyvrs prm"
and t::"trm"
shows "pi\<bullet>(t[X \<mapsto>\<^sub>\<tau> T]) = (pi\<bullet>t)[(pi\<bullet>X) \<mapsto>\<^sub>\<tau> (pi\<bullet>T)]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. pi \<bullet> t[X \<mapsto>\<^sub>\<tau> T] = (pi \<bullet> t)[pi \<bullet> X \<mapsto>\<^sub>\<tau> pi \<bullet> T]
[PROOF STEP]
by (nominal_induct t avoiding: X T rule: trm.strong_induct)
(perm_simp add: fresh_bij subst_eqvt)+ |
Describe Users/mangosalsa here.
20110119 15:47:05 nbsp Welcome to the Wiki, mangosalsa! Users/PeterBoulay
20110119 16:28:00 nbsp Howdy! Just a heads up: recant means to retract or disavow. Retell, recall, or relate may better fit for your comment on Tuscany Villas. Sorry for being a grammar Nazi, I just happened to notice it. Users/JoePomidor
|
Formal statement is: lemma measure_of_subset: "M \<subseteq> Pow \<Omega> \<Longrightarrow> M' \<subseteq> M \<Longrightarrow> sets (measure_of \<Omega> M' \<mu>) \<subseteq> sets (measure_of \<Omega> M \<mu>')" Informal statement is: If $M$ is a $\sigma$-algebra on $\Omega$ and $M'$ is a sub-$\sigma$-algebra of $M$, then the $\sigma$-algebra generated by $M'$ is a sub-$\sigma$-algebra of the $\sigma$-algebra generated by $M$. |
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.finset.finsupp
import data.finset.locally_finite
import data.finsupp.order
/-!
# Finite intervals of finitely supported functions
This file provides the `locally_finite_order` instance for `ι →₀ α` when `α` itself is locally
finite and calculates the cardinality of its finite intervals.
## Main declarations
* `finsupp.range_singleton`: Postcomposition with `has_singleton.singleton` on `finset` as a
`finsupp`.
* `finsupp.range_Icc`: Postcomposition with `finset.Icc` as a `finsupp`.
Both these definitions use the fact that `0 = {0}` to ensure that the resulting function is finitely
supported.
-/
noncomputable theory
open finset finsupp function
open_locale big_operators classical pointwise
variables {ι α : Type*}
namespace finsupp
section range_singleton
variables [has_zero α] {f : ι →₀ α} {i : ι} {a : α}
/-- Pointwise `finset.singleton` bundled as a `finsupp`. -/
@[simps] def range_singleton (f : ι →₀ α) : ι →₀ finset α :=
{ to_fun := λ i, {f i},
support := f.support,
mem_support_to_fun := λ i, begin
rw [←not_iff_not, not_mem_support_iff, not_ne_iff],
exact singleton_injective.eq_iff.symm,
end }
lemma mem_range_singleton_apply_iff : a ∈ f.range_singleton i ↔ a = f i := mem_singleton
end range_singleton
section range_Icc
variables [has_zero α] [partial_order α] [locally_finite_order α] {f g : ι →₀ α} {i : ι} {a : α}
/-- Pointwise `finset.Icc` bundled as a `finsupp`. -/
@[simps] def range_Icc (f g : ι →₀ α) : ι →₀ finset α :=
{ to_fun := λ i, Icc (f i) (g i),
support := f.support ∪ g.support,
mem_support_to_fun := λ i, begin
rw [mem_union, ←not_iff_not, not_or_distrib, not_mem_support_iff, not_mem_support_iff,
not_ne_iff],
exact Icc_eq_singleton_iff.symm,
end }
lemma mem_range_Icc_apply_iff : a ∈ f.range_Icc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc
end range_Icc
variables [partial_order α] [has_zero α] [locally_finite_order α] (f g : ι →₀ α)
instance : locally_finite_order (ι →₀ α) :=
locally_finite_order.of_Icc (ι →₀ α)
(λ f g, (f.support ∪ g.support).finsupp $ f.range_Icc g)
(λ f g x, begin
refine (mem_finsupp_iff_of_support_subset $ subset.rfl).trans _,
simp_rw mem_range_Icc_apply_iff,
exact forall_and_distrib,
end)
lemma card_Icc : (Icc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card :=
card_finsupp _ _
lemma card_Ico : (Ico f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 :=
by rw [card_Ico_eq_card_Icc_sub_one, card_Icc]
lemma card_Ioc : (Ioc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 :=
by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc]
lemma card_Ioo : (Ioo f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 2 :=
by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc]
end finsupp
|
"""
NsoliPDE(n; fixedeta=true, eta=.1, lsolver="gmres", restarts = 99)
Solve the Elliptic PDE using nsoli.jl on an n x n grid. You give me
n and (optionally) the iteration paramaters and I return the output of nsoli.
"""
function NsoliPDE(
n;
eta = 0.1,
fixedeta = true,
rtol = 1.e-7,
atol = 1.e-10,
Pvec = Pvec2d,
pside = "right",
lsolver = "gmres",
restarts = 99
)
# Get some room for the residual
u0 = zeros(n * n)
FV = copy(u0)
# Get the precomputed data from pdeinit
pdata = pdeinit(n)
# Storage for the Krylov basis
(lsolver == "gmres") ? (JV = zeros(n * n, restarts+1)) : JV = zeros(n*n)
pout = nsoli(
pdeF!,
u0,
FV,
JV,
Jvec2d;
rtol = rtol,
atol = atol,
Pvec = Pvec,
pdata = pdata,
eta = eta,
fixedeta = fixedeta,
maxit = 20,
lmaxit = 20,
pside = pside,
lsolver = lsolver,
)
return pout
end
|
State Before: α : Type u
a : α
l : List α
⊢ ofFn (get (a :: l)) = a :: l State After: α : Type u
a : α
l : List α
⊢ (get (a :: l) 0 :: ofFn fun i => get (a :: l) (Fin.succ i)) = a :: l Tactic: rw [ofFn_succ] State Before: α : Type u
a : α
l : List α
⊢ (get (a :: l) 0 :: ofFn fun i => get (a :: l) (Fin.succ i)) = a :: l State After: case e_tail
α : Type u
a : α
l : List α
⊢ (ofFn fun i => get (a :: l) (Fin.succ i)) = l Tactic: congr State Before: case e_tail
α : Type u
a : α
l : List α
⊢ (ofFn fun i => get (a :: l) (Fin.succ i)) = l State After: case e_tail
α : Type u
a : α
l : List α
⊢ (ofFn fun i => get (a :: l) (Fin.succ i)) = l Tactic: simp only [Fin.val_succ] State Before: case e_tail
α : Type u
a : α
l : List α
⊢ (ofFn fun i => get (a :: l) (Fin.succ i)) = l State After: no goals Tactic: exact ofFn_get l |
(*
Author: Alexander Katovsky
*)
section "Yoneda"
theory Yoneda
imports NatTrans SetCat
begin
definition "YFtorNT' C f \<equiv> \<lparr>NTDom = Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> f] , NTCod = Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> f] ,
NatTransMap = \<lambda> B . Hom\<^bsub>C\<^esub>[B,f]\<rparr>"
definition "YFtorNT C f \<equiv> MakeNT (YFtorNT' C f)"
lemmas YFtorNT_defs = YFtorNT'_def YFtorNT_def MakeNT_def
lemma YFtorNTCatDom: "NTCatDom (YFtorNT C f) = Op C"
by (simp add: YFtorNT_defs NTCatDom_def HomFtorContraDom)
lemma YFtorNTCatCod: "NTCatCod (YFtorNT C f) = SET"
by (simp add: YFtorNT_defs NTCatCod_def HomFtorContraCod)
lemma YFtorNTApp1: assumes "X \<in> Obj (NTCatDom (YFtorNT C f))" shows "(YFtorNT C f) $$ X = Hom\<^bsub>C\<^esub>[X,f]"
proof-
have "(YFtorNT C f) $$ X = (YFtorNT' C f) $$ X" using assms by (simp add: MakeNTApp YFtorNT_def)
thus ?thesis by (simp add: YFtorNT'_def)
qed
definition
"YFtor' C \<equiv> \<lparr>
CatDom = C ,
CatCod = CatExp (Op C) SET ,
MapM = \<lambda> f . YFtorNT C f
\<rparr>"
definition "YFtor C \<equiv> MakeFtor(YFtor' C)"
lemmas YFtor_defs = YFtor'_def YFtor_def MakeFtor_def
lemma YFtorNTNatTrans':
assumes "LSCategory C" and "f \<in> Mor C"
shows "NatTransP (YFtorNT' C f)"
proof(auto simp only: NatTransP_def)
have Fd: "Ftor (NTDom (YFtorNT' C f)) : (Op C) \<longrightarrow> SET" using assms
by (simp add: HomFtorContraFtor Category.Cdom YFtorNT'_def)
have Fc: "Ftor (NTCod (YFtorNT' C f)) : (Op C) \<longrightarrow> SET" using assms
by (simp add: HomFtorContraFtor Category.Ccod YFtorNT'_def)
show "Functor (NTDom (YFtorNT' C f))" using Fd by auto
show "Functor (NTCod (YFtorNT' C f))" using Fc by auto
show "NTCatDom (YFtorNT' C f) = CatDom (NTCod (YFtorNT' C f))"
by(simp add: YFtorNT'_def NTCatDom_def HomFtorContraDom)
show "NTCatCod (YFtorNT' C f) = CatCod (NTDom (YFtorNT' C f))"
by(simp add: YFtorNT'_def NTCatCod_def HomFtorContraCod)
{
fix X assume a: "X \<in> Obj (NTCatDom (YFtorNT' C f))"
show "(YFtorNT' C f) $$ X maps\<^bsub>NTCatCod (YFtorNT' C f)\<^esub> (NTDom (YFtorNT' C f) @@ X) to (NTCod (YFtorNT' C f) @@ X)"
proof-
have Obj: "X \<in> Obj C" using a by (simp add: NTCatDom_def YFtorNT'_def HomFtorContraDom OppositeCategory_def)
have H1: "(Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> f]) @@ X = Hom\<^bsub>C \<^esub>X dom\<^bsub>C\<^esub> f " using assms Obj by(simp add: HomFtorOpObj Category.Cdom)
have H2: "(Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> f]) @@ X = Hom\<^bsub>C \<^esub>X cod\<^bsub>C\<^esub> f " using assms Obj by(simp add: HomFtorOpObj Category.Ccod)
have "Hom\<^bsub>C\<^esub>[X,f] maps\<^bsub>SET\<^esub> (Hom\<^bsub>C \<^esub>X dom\<^bsub>C\<^esub> f) to (Hom\<^bsub>C \<^esub>X cod\<^bsub>C\<^esub> f)" using assms Obj by (simp add: HomFtorMapsTo)
thus ?thesis using H1 H2 by(simp add: YFtorNT'_def NTCatCod_def NTCatDom_def HomFtorContraCod)
qed
}
{
fix g X Y assume a: "g maps\<^bsub>NTCatDom (YFtorNT' C f)\<^esub> X to Y"
show "((NTDom (YFtorNT' C f)) ## g) ;;\<^bsub>NTCatCod (YFtorNT' C f) \<^esub>(YFtorNT' C f $$ Y) =
((YFtorNT' C f) $$ X) ;;\<^bsub>NTCatCod (YFtorNT' C f) \<^esub>(NTCod (YFtorNT' C f) ## g)"
proof-
have M1: "g maps\<^bsub>Op C\<^esub> X to Y" using a by (auto simp add: NTCatDom_def YFtorNT'_def HomFtorContraDom)
have D1: "dom\<^bsub>C\<^esub> g = Y" and C1: "cod\<^bsub>C\<^esub> g = X" using M1 by (auto simp add: OppositeCategory_def)
have morf: "f \<in> Mor C" and morg: "g \<in> Mor C" using assms M1 by (auto simp add: OppositeCategory_def)
have H1: "(HomC\<^bsub>C\<^esub>[g,dom\<^bsub>C\<^esub> f]) = (Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> f]) ## g"
and H2: "(HomC\<^bsub>C\<^esub>[g,cod\<^bsub>C\<^esub> f]) = (Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> f]) ## g" using M1
by (auto simp add: HomFtorContra_def HomFtorContra'_def MakeFtor_def)
have "(HomC\<^bsub>C\<^esub>[g,dom\<^bsub>C\<^esub> f]) ;;\<^bsub>SET\<^esub> (Hom\<^bsub>C\<^esub>[dom\<^bsub>C\<^esub> g,f]) = (Hom\<^bsub>C\<^esub>[cod\<^bsub>C\<^esub> g,f]) ;;\<^bsub>SET\<^esub> (HomC\<^bsub>C\<^esub>[g,cod\<^bsub>C\<^esub> f])" using assms morf morg
by (simp add: HomCHom)
hence "((Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> f]) ## g) ;;\<^bsub>SET\<^esub> (Hom\<^bsub>C\<^esub>[Y,f]) = (Hom\<^bsub>C\<^esub>[X,f]) ;;\<^bsub>SET\<^esub> ((Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> f]) ## g)"
using H1 H2 D1 C1 by simp
thus ?thesis by (simp add: YFtorNT'_def NTCatCod_def HomFtorContraCod)
qed
}
qed
lemma YFtorNTNatTrans:
assumes "LSCategory C" and "f \<in> Mor C"
shows "NatTrans (YFtorNT C f)"
by (simp add: assms YFtorNTNatTrans' YFtorNT_def MakeNT)
lemma YFtorNTMor:
assumes "LSCategory C" and "f \<in> Mor C"
shows "YFtorNT C f \<in> Mor (CatExp (Op C) SET)"
proof(auto simp add: CatExp_def CatExp'_def MakeCatMor)
have "f \<in> Mor C" using assms by auto
thus "NatTrans (YFtorNT C f)" using assms by (simp add: YFtorNTNatTrans)
show "NTCatDom (YFtorNT C f) = Op C" by (simp add: YFtorNTCatDom)
show "NTCatCod (YFtorNT C f) = SET" by (simp add: YFtorNTCatCod)
qed
lemma YFtorNtMapsTo:
assumes "LSCategory C" and "f \<in> Mor C"
shows "YFtorNT C f maps\<^bsub>CatExp (Op C) SET\<^esub> (Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> f]) to (Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> f])"
proof(rule MapsToI)
have "f \<in> Mor C" using assms by auto
thus 1: "YFtorNT C f \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>" using assms by (simp add: YFtorNTMor)
show "dom\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C f = Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> f]" using 1 by(simp add:CatExpDom YFtorNT_defs)
show "cod\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C f = Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> f]" using 1 by(simp add:CatExpCod YFtorNT_defs)
qed
lemma YFtorNTCompDef:
assumes "LSCategory C" and "f \<approx>>\<^bsub>C\<^esub> g"
shows "YFtorNT C f \<approx>>\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g"
proof(rule CompDefinedI)
have "f \<in> Mor C" and "g \<in> Mor C" using assms by auto
hence 1: "YFtorNT C f maps\<^bsub>CatExp (Op C) SET\<^esub> (Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> f]) to (Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> f])"
and 2: "YFtorNT C g maps\<^bsub>CatExp (Op C) SET\<^esub> (Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> g]) to (Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> g])"
using assms by (simp add: YFtorNtMapsTo)+
thus "YFtorNT C f \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>"
and "YFtorNT C g \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>" by auto
have "cod\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C f = (Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> f])" using 1 by auto
moreover have "dom\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g = (Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> g])" using 2 by auto
moreover have "cod\<^bsub>C\<^esub> f = dom\<^bsub>C\<^esub> g" using assms by auto
ultimately show "cod\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C f = dom\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g" by simp
qed
lemma PreSheafCat: "LSCategory C \<Longrightarrow> Category (CatExp (Op C) SET)"
by(simp add: YFtor'_def OpCatCat SETCategory CatExpCat)
lemma YFtor'Obj1:
assumes "X \<in> Obj (CatDom (YFtor' C))" and "LSCategory C"
shows "(YFtor' C) ## (Id (CatDom (YFtor' C)) X) = Id (CatCod (YFtor' C)) (Hom\<^bsub>C \<^esub>[\<emdash>,X])"
proof(simp add: YFtor'_def, rule NatTransExt)
have Obj: "X \<in> Obj C" using assms by (simp add: YFtor'_def)
have HomObj: "(Hom\<^bsub>C\<^esub>[\<emdash>,X]) \<in> Obj (CatExp (Op C) SET)" using assms Obj by(simp add: CatExp_defs HomFtorContraFtor)
hence Id: "Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]) \<in> Mor (CatExp (Op C) SET)" using assms
by (simp add: PreSheafCat Category.CatIdInMor)
have CAT: "Category(CatExp (Op C) SET)" using assms by (simp add: PreSheafCat)
have HomObj: "(Hom\<^bsub>C\<^esub>[\<emdash>,X]) \<in> Obj (CatExp (Op C) SET)" using assms Obj
by(simp add: CatExp_defs HomFtorContraFtor)
show "NatTrans (YFtorNT C (Id C X))"
proof(rule YFtorNTNatTrans)
show "LSCategory C" using assms(2) .
show "Id C X \<in> Mor C" using assms Obj by (simp add: Category.CatIdInMor)
qed
show "NatTrans(Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]))" using Id by (simp add: CatExp_defs)
show "NTDom (YFtorNT C (Id C X)) = NTDom (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]))"
proof(simp add: YFtorNT_defs)
have "Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> (Id C X)] = Hom\<^bsub>C\<^esub>[\<emdash>,X]" using assms Obj by (simp add: Category.CatIdDomCod)
also have "... = dom\<^bsub>CatExp (Op C) SET\<^esub> (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]))" using CAT HomObj
by (simp add: Category.CatIdDomCod)
also have "... = NTDom (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]))" using Id by (simp add: CatExpDom)
finally show "Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> (Id C X)] = NTDom (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]))" .
qed
show "NTCod (YFtorNT C (Id C X)) = NTCod (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]))"
proof(simp add: YFtorNT_defs)
have "Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> (Id C X)] = Hom\<^bsub>C\<^esub>[\<emdash>,X]" using assms Obj by (simp add: Category.CatIdDomCod)
also have "... = cod\<^bsub>CatExp (Op C) SET\<^esub> (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]))" using CAT HomObj
by (simp add: Category.CatIdDomCod)
also have "... = NTCod (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]))" using Id by (simp add: CatExpCod)
finally show "Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> (Id C X)] = NTCod (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X]))" .
qed
{
fix Y assume a: "Y \<in> Obj (NTCatDom (YFtorNT C (Id C X)))"
show "(YFtorNT C (Id C X)) $$ Y = (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X])) $$ Y"
proof-
have CD: "CatDom (Hom\<^bsub>C\<^esub>[\<emdash>,X]) = Op C" by (simp add: HomFtorContraDom)
have CC: "CatCod (Hom\<^bsub>C\<^esub>[\<emdash>,X]) = SET" by (simp add: HomFtorContraCod)
have ObjY: "Y \<in> Obj C" and ObjYOp: "Y \<in> Obj (Op C)" using a by(simp add: YFtorNTCatDom OppositeCategory_def)+
have "(YFtorNT C (Id C X)) $$ Y = (Hom\<^bsub>C\<^esub>[Y,(Id C X)])" using a by (simp add: YFtorNTApp1)
also have "... = id\<^bsub>SET\<^esub> (Hom\<^bsub>C \<^esub>Y X)" using Obj ObjY assms by (simp add: HomFtorId)
also have "... = id\<^bsub>SET\<^esub> ((Hom\<^bsub>C\<^esub>[\<emdash>,X]) @@ Y)" using Obj ObjY assms by (simp add: HomFtorOpObj )
also have "... = (IdNatTrans (Hom\<^bsub>C\<^esub>[\<emdash>,X])) $$ Y" using CD CC ObjYOp by (simp add: IdNatTrans_map)
also have "... = (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<emdash>,X])) $$ Y" using HomObj by (simp add: CatExpId)
finally show ?thesis .
qed
}
qed
lemma YFtorPreFtor:
assumes "LSCategory C"
shows "PreFunctor (YFtor' C)"
proof(auto simp only: PreFunctor_def)
have CAT: "Category(CatExp (Op C) SET)" using assms by (simp add: PreSheafCat)
{
fix f g assume a: "f \<approx>>\<^bsub>CatDom (YFtor' C)\<^esub> g"
show "(YFtor' C) ## (f ;;\<^bsub>CatDom (YFtor' C)\<^esub> g) = ((YFtor' C) ## f) ;;\<^bsub>CatCod (YFtor' C)\<^esub> ((YFtor' C) ## g)"
proof(simp add: YFtor'_def, rule NatTransExt)
have CD: "f \<approx>>\<^bsub>C\<^esub> g" using a by (simp add: YFtor'_def)
have CD2: "YFtorNT C f \<approx>>\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g" using CD assms by (simp add: YFtorNTCompDef)
have Mor1: "YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g \<in> Mor (CatExp (Op C) SET)" using CAT CD2
by (simp add: Category.MapsToMorDomCod)
show "NatTrans (YFtorNT C (f ;;\<^bsub>C\<^esub> g))" using assms by (simp add: Category.MapsToMorDomCod CD YFtorNTNatTrans)
show "NatTrans (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)" using Mor1 by (simp add: CatExpMorNT)
show "NTDom (YFtorNT C (f ;;\<^bsub>C\<^esub> g)) = NTDom (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)"
proof-
have 1: "YFtorNT C f \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>" using CD2 by auto
have "NTDom (YFtorNT C (f ;;\<^bsub>C\<^esub> g)) = Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> (f ;;\<^bsub>C\<^esub> g)]" by (simp add: YFtorNT_defs)
also have "... = Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> f]" using CD assms by (simp add: Category.MapsToMorDomCod)
also have "... = NTDom (YFtorNT C f)" by (simp add: YFtorNT_defs)
also have "... = dom\<^bsub>CatExp (Op C) SET\<^esub> (YFtorNT C f)" using 1 by (simp add: CatExpDom)
also have "... = dom\<^bsub>CatExp (Op C) SET\<^esub> (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)" using CD2 CAT
by (simp add: Category.MapsToMorDomCod)
finally show ?thesis using Mor1 by (simp add: CatExpDom)
qed
show "NTCod (YFtorNT C (f ;;\<^bsub>C\<^esub> g)) = NTCod (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)"
proof-
have 1: "YFtorNT C g \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>" using CD2 by auto
have "NTCod (YFtorNT C (f ;;\<^bsub>C\<^esub> g)) = Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> (f ;;\<^bsub>C\<^esub> g)]" by (simp add: YFtorNT_defs)
also have "... = Hom\<^bsub>C\<^esub>[\<emdash>,cod\<^bsub>C\<^esub> g]" using CD assms by (simp add: Category.MapsToMorDomCod)
also have "... = NTCod (YFtorNT C g)" by (simp add: YFtorNT_defs)
also have "... = cod\<^bsub>CatExp (Op C) SET\<^esub> (YFtorNT C g)" using 1 by (simp add: CatExpCod)
also have "... = cod\<^bsub>CatExp (Op C) SET\<^esub> (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)" using CD2 CAT
by (simp add: Category.MapsToMorDomCod)
finally show ?thesis using Mor1 by (simp add: CatExpCod)
qed
{
fix X assume a: "X \<in> Obj (NTCatDom (YFtorNT C (f ;;\<^bsub>C\<^esub> g)))"
show "YFtorNT C (f ;;\<^bsub>C\<^esub> g) $$ X = (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g) $$ X"
proof-
have Obj: "X \<in> Obj C" and ObjOp: "X \<in> Obj (Op C)" using a by (simp add: YFtorNTCatDom OppositeCategory_def)+
have App1: "(Hom\<^bsub>C\<^esub>[X,f]) = (YFtorNT C f) $$ X"
and App2: "(Hom\<^bsub>C\<^esub>[X,g]) = (YFtorNT C g) $$ X" using a by (simp add: YFtorNTApp1 YFtorNTCatDom)+
have "(YFtorNT C (f ;;\<^bsub>C\<^esub> g)) $$ X = (Hom\<^bsub>C\<^esub>[X,(f ;;\<^bsub>C\<^esub> g)])" using a by (simp add: YFtorNTApp1)
also have "... = (Hom\<^bsub>C\<^esub>[X,f]) ;;\<^bsub>SET\<^esub> (Hom\<^bsub>C\<^esub>[X,g])" using CD assms Obj by (simp add: HomFtorDist)
also have "... = ((YFtorNT C f) $$ X) ;;\<^bsub>SET\<^esub> ((YFtorNT C g) $$ X)" using App1 App2 by simp
finally show ?thesis using ObjOp CD2 by (simp add: CatExpDist)
qed
}
qed
}
{
fix X assume a: "X \<in> Obj (CatDom (YFtor' C))"
show "\<exists> Y \<in> Obj (CatCod (YFtor' C)) . YFtor' C ## (Id (CatDom (YFtor' C)) X) = Id (CatCod (YFtor' C)) Y"
proof(rule_tac x="Hom\<^bsub>C \<^esub>[\<emdash>,X]" in Set.rev_bexI)
have "X \<in> Obj C" using a by(simp add: YFtor'_def)
thus "Hom\<^bsub>C \<^esub>[\<emdash>,X] \<in> Obj (CatCod (YFtor' C))" using assms by(simp add: YFtor'_def CatExp_defs HomFtorContraFtor)
show "(YFtor' C) ## (Id (CatDom (YFtor' C)) X) = Id (CatCod (YFtor' C)) (Hom\<^bsub>C \<^esub>[\<emdash>,X])" using a assms
by (simp add: YFtor'Obj1)
qed
}
show "Category (CatDom (YFtor' C))" using assms by (simp add: YFtor'_def)
show "Category (CatCod (YFtor' C))" using CAT by (simp add: YFtor'_def)
qed
lemma YFtor'Obj:
assumes "X \<in> Obj (CatDom (YFtor' C))"
and "LSCategory C"
shows "(YFtor' C) @@ X = Hom\<^bsub>C \<^esub>[\<emdash>,X]"
proof(rule PreFunctor.FmToFo, simp_all add: assms YFtor'Obj1 YFtorPreFtor)
have "X \<in> Obj C" using assms by(simp add: YFtor'_def)
thus "Hom\<^bsub>C \<^esub>[\<emdash>,X] \<in> Obj (CatCod (YFtor' C))" using assms by(simp add: YFtor'_def CatExp_defs HomFtorContraFtor)
qed
lemma YFtorFtor':
assumes "LSCategory C"
shows "FunctorM (YFtor' C)"
proof(auto simp only: FunctorM_def)
show "PreFunctor (YFtor' C)" using assms by (rule YFtorPreFtor)
show "FunctorM_axioms (YFtor' C)"
proof(auto simp add:FunctorM_axioms_def)
{
fix f X Y assume aa: "f maps\<^bsub>CatDom (YFtor' C) \<^esub>X to Y"
show "YFtor' C ## f maps\<^bsub>CatCod (YFtor' C)\<^esub> YFtor' C @@ X to YFtor' C @@ Y"
proof-
have Mor1: "f maps\<^bsub>C\<^esub> X to Y" using aa by (simp add: YFtor'_def)
have "Category (CatDom (YFtor' C))" using assms by (simp add: YFtor'_def)
hence Obj1: "X \<in> Obj (CatDom (YFtor' C))" and
Obj2: "Y \<in> Obj (CatDom (YFtor' C))" using aa assms by (simp add: Category.MapsToObj)+
have "(YFtor' C ## f) = YFtorNT C f" by (simp add: YFtor'_def)
moreover have "YFtor' C @@ X = Hom\<^bsub>C \<^esub>[\<emdash>,X]"
and "YFtor' C @@ Y = Hom\<^bsub>C \<^esub>[\<emdash>,Y]" using Obj1 Obj2 assms by (simp add: YFtor'Obj)+
moreover have "CatCod (YFtor' C) = CatExp (Op C) SET" by (simp add: YFtor'_def)
moreover have "YFtorNT C f maps\<^bsub>CatExp (Op C) SET\<^esub> (Hom\<^bsub>C \<^esub>[\<emdash>,X]) to (Hom\<^bsub>C \<^esub>[\<emdash>,Y])"
using assms Mor1 by (auto simp add: YFtorNtMapsTo)
ultimately show ?thesis by simp
qed
}
qed
qed
lemma YFtorFtor: assumes "LSCategory C" shows "Ftor (YFtor C) : C \<longrightarrow> (CatExp (Op C) SET)"
proof(auto simp only: functor_abbrev_def)
show "Functor (YFtor C)" using assms by(simp add: MakeFtor YFtor_def YFtorFtor')
show "CatDom (YFtor C) = C" and "CatCod (YFtor C) = (CatExp (Op C) SET)"
using assms by(simp add: MakeFtor_def YFtor_def YFtor'_def)+
qed
lemma YFtorObj:
assumes "LSCategory C" and "X \<in> Obj C"
shows "(YFtor C) @@ X = Hom\<^bsub>C \<^esub>[\<emdash>,X]"
proof-
have "CatDom (YFtor' C) = C" by (simp add: YFtor'_def)
moreover hence "(YFtor' C) @@ X = Hom\<^bsub>C \<^esub>[\<emdash>,X]" using assms by(simp add: YFtor'Obj)
moreover have "PreFunctor (YFtor' C)" using assms by (simp add: YFtorPreFtor)
ultimately show ?thesis using assms by (simp add: MakeFtorObj YFtor_def)
qed
lemma YFtorObj2:
assumes "LSCategory C" and "X \<in> Obj C" and "Y \<in> Obj C"
shows "((YFtor C) @@ Y) @@ X = Hom\<^bsub>C \<^esub>X Y"
proof-
have "Hom\<^bsub>C \<^esub>X Y = ((Hom\<^bsub>C\<^esub>[\<emdash>,Y]) @@ X)" using assms by (simp add: HomFtorOpObj)
also have "... = ((YFtor C @@ Y) @@ X)" using assms by (simp add: YFtorObj)
finally show ?thesis by simp
qed
lemma YFtorMor: "\<lbrakk>LSCategory C ; f \<in> Mor C\<rbrakk> \<Longrightarrow> (YFtor C) ## f = YFtorNT C f"
by (simp add: YFtor_defs MakeFtorMor)
(*
We can't do this because the presheaf category may not be locally small
definition
NatHom ("Nat\<index> _ _") where
"NatHom C F G \<equiv> Hom\<^bsub>CatExp (Op C) SET\<^esub> F G"
*)
definition "YMap C X \<eta> \<equiv> (\<eta> $$ X) |@| (m2z\<^bsub>C\<^esub> (id\<^bsub>C \<^esub>X))"
definition "YMapInv' C X F x \<equiv> \<lparr>
NTDom = ((YFtor C) @@ X),
NTCod = F,
NatTransMap = \<lambda> B . ZFfun (Hom\<^bsub>C\<^esub> B X) (F @@ B) (\<lambda> f . (F ## (z2m\<^bsub>C\<^esub> f)) |@| x)
\<rparr>"
definition "YMapInv C X F x \<equiv> MakeNT (YMapInv' C X F x)"
lemma YMapInvApp:
assumes "X \<in> Obj C" and "B \<in> Obj C" and "LSCategory C"
shows "(YMapInv C X F x) $$ B = ZFfun (Hom\<^bsub>C\<^esub> B X) (F @@ B) (\<lambda> f . (F ## (z2m\<^bsub>C\<^esub> f)) |@| x)"
proof-
have "NTCatDom (MakeNT (YMapInv' C X F x)) = CatDom (NTDom (YMapInv' C X F x))" by (simp add: MakeNT_def NTCatDom_def)
also have "... = CatDom (Hom\<^bsub>C\<^esub>[\<emdash>,X])" using assms by (simp add: YFtorObj YMapInv'_def)
also have "... = Op C" using assms HomFtorContraFtor[of C X] by auto
finally have "NTCatDom (MakeNT (YMapInv' C X F x)) = Op C" .
hence 1: "B \<in> Obj (NTCatDom (MakeNT (YMapInv' C X F x)))" using assms by (simp add: OppositeCategory_def)
have "(YMapInv C X F x) $$ B = (MakeNT (YMapInv' C X F x)) $$ B" by (simp add: YMapInv_def)
also have "... = (YMapInv' C X F x) $$ B" using 1 by(simp add: MakeNTApp)
finally show ?thesis by (simp add: YMapInv'_def)
qed
lemma YMapImage:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and "X \<in> Obj C"
and "NT \<eta> : (YFtor C @@ X) \<Longrightarrow> F"
shows "(YMap C X \<eta>) |\<in>| (F @@ X)"
proof(simp only: YMap_def)
have "(YFtor C @@ X) = (Hom\<^bsub>C\<^esub>[\<emdash>,X])" using assms by (auto simp add: YFtorObj)
moreover have "Ftor (Hom\<^bsub>C\<^esub>[\<emdash>,X]) : (Op C) \<longrightarrow> SET" using assms by (simp add: HomFtorContraFtor)
ultimately have "CatDom (YFtor C @@ X) = Op C" by auto
hence Obj: "X \<in> Obj (CatDom (YFtor C @@ X))" using assms by (simp add: OppositeCategory_def)
moreover have "CatCod F = SET" using assms by auto
moreover have "\<eta> $$ X maps\<^bsub>CatCod F \<^esub>((YFtor C @@ X) @@ X) to (F @@ X)" using assms Obj by (simp add: NatTransMapsTo)
ultimately have "\<eta> $$ X maps\<^bsub>SET\<^esub> ((YFtor C @@ X) @@ X) to (F @@ X)" by simp
moreover have "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| ((YFtor C @@ X) @@ X)"
proof-
have "(Id C X) maps\<^bsub>C \<^esub>X to X" using assms by (simp add: Category.Simps)
moreover have "((YFtor C @@ X) @@ X) = Hom\<^bsub>C\<^esub> X X" using assms by (simp add: YFtorObj2)
ultimately show ?thesis using assms by (simp add: LSCategory.m2zz2m)
qed
ultimately show "((\<eta> $$ X) |@| (m2z\<^bsub>C \<^esub>(Id C X))) |\<in>| (F @@ X)" by (simp add: SETfunDomAppCod)
qed
lemma YMapInvNatTransP:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and xobj: "X \<in> Obj C" and xinF: "x |\<in>| (F @@ X)"
shows "NatTransP (YMapInv' C X F x)"
proof(auto simp only: NatTransP_def, simp_all add: YMapInv'_def NTCatCod_def NTCatDom_def)
have yf: "(YFtor C @@ X) = Hom\<^bsub>C\<^esub>[\<emdash>,X]" using assms by (simp add: YFtorObj)
hence hf: "Ftor (YFtor C @@ X) : (Op C) \<longrightarrow> SET" using assms by (simp add: HomFtorContraFtor)
thus "Functor (YFtor C @@ X)" by auto
show ftf: "Functor F" using assms by auto
have df: "CatDom F = Op C" and cf: "CatCod F = SET" using assms by auto
have dy: "CatDom ((YFtor C) @@ X) = Op C" and cy: "CatCod ((YFtor C) @@ X) = SET" using hf by auto
show "CatDom ((YFtor C) @@ X) = CatDom F" using df dy by simp
show "CatCod F = CatCod ((YFtor C) @@ X)" using cf cy by simp
{
fix Y assume yobja: "Y \<in> Obj (CatDom ((YFtor C) @@ X))"
show "ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## (z2m\<^bsub>C \<^esub>f)) |@| x) maps\<^bsub>CatCod F\<^esub> ((YFtor C @@ X) @@ Y) to (F @@ Y)"
proof(simp add: cf, rule MapsToI)
have yobj: "Y \<in> Obj C" using yobja dy by (simp add: OppositeCategory_def)
have zffun: "isZFfun (ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## z2m\<^bsub>C\<^esub>f) |@| x))"
proof(rule SETfun, rule allI, rule impI)
{
fix y assume yhom: "y |\<in>| (Hom\<^bsub>C\<^esub> Y X)" show "(F ## (z2m\<^bsub>C \<^esub>y)) |@| x |\<in>| (F @@ Y)"
proof-
let ?f = "(F ## (z2m\<^bsub>C \<^esub>y))"
have "(z2m\<^bsub>C \<^esub>y) maps\<^bsub>C\<^esub> Y to X" using yhom yobj assms by (simp add: LSCategory.z2mm2z)
hence "(z2m\<^bsub>C \<^esub>y) maps\<^bsub>Op C\<^esub> X to Y" by (simp add: MapsToOp)
hence "?f maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Y)" using assms by (simp add: FunctorMapsTo)
hence "isZFfun (?f)" and "|dom| ?f = F @@ X" and "|cod| ?f = F @@ Y" by (simp add: SETmapsTo)+
thus "(?f |@| x) |\<in>| (F @@ Y)" using assms ZFfunDomAppCod[of ?f x] by simp
qed
}
qed
show "ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## z2m\<^bsub>C\<^esub>f) |@| x) \<in> mor\<^bsub>SET\<^esub>" using zffun
by(simp add: SETmor)
show "cod\<^bsub>SET\<^esub> ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## z2m\<^bsub>C\<^esub>f) |@| x) = F @@ Y" using zffun
by(simp add: SETcod)
have "(Hom\<^bsub>C\<^esub> Y X) = (YFtor C @@ X) @@ Y" using assms yobj by (simp add: YFtorObj2)
thus "dom\<^bsub>SET\<^esub> ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## z2m\<^bsub>C\<^esub>f) |@| x) = (YFtor C @@ X) @@ Y" using zffun
by(simp add: SETdom)
qed
}
{
fix f Z Y assume fmaps: "f maps\<^bsub>CatDom ((YFtor C ) @@ X)\<^esub> Z to Y"
have fmapsa: "f maps\<^bsub>Op C\<^esub> Z to Y" using fmaps dy by simp
hence fmapsb: "f maps\<^bsub>C\<^esub> Y to Z" by (rule MapsToOpOp)
hence fmor: "f \<in> Mor C" and fdom: "dom\<^bsub>C\<^esub> f = Y" and fcod: "cod\<^bsub>C\<^esub> f = Z" by (auto simp add: OppositeCategory_def)
hence hc: "(Hom\<^bsub>C\<^esub>[\<emdash>,X]) ## f = (HomC\<^bsub>C\<^esub>[f,X])" using assms by (simp add: HomContraMor)
have yobj: "Y \<in> Obj C" and zobj: "Z \<in> Obj C" using fmapsb assms by (simp add: Category.MapsToObj)+
have Ffmaps: "(F ## f) maps\<^bsub>SET\<^esub> (F @@ Z) to (F @@ Y)" using assms fmapsa by (simp add: FunctorMapsTo)
have Fzmaps: "\<And> h A B . \<lbrakk>h |\<in>| (Hom\<^bsub>C\<^esub> A B) ; A \<in> Obj C ; B \<in> Obj C\<rbrakk> \<Longrightarrow>
(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ B) to (F @@ A)"
proof-
fix h A B assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> A B)" and oA: "A \<in> Obj C" and oB: "B \<in> Obj C"
have "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> A to B" using assms h oA oB by (simp add: LSCategory.z2mm2z)
hence "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>Op C\<^esub> B to A" by (rule MapsToOp)
thus "(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ B) to (F @@ A)" using assms by (simp add: FunctorMapsTo)
qed
have hHomF: "\<And>h. h |\<in>| (Hom\<^bsub>C\<^esub> Z X) \<Longrightarrow> (F ## (z2m\<^bsub>C \<^esub>h)) |@| x |\<in>| (F @@ Z)" using xobj zobj xinF
proof-
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
have "(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Z)" using xobj zobj h by (simp add: Fzmaps)
thus "(F ## (z2m\<^bsub>C \<^esub>h)) |@| x |\<in>| (F @@ Z)" using assms by (simp add: SETfunDomAppCod)
qed
have Ff: "F ## f = ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h)" using Ffmaps by (simp add: SETZFfun)
have compdefa: "ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) \<approx>>\<^bsub>SET\<^esub>
ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x)"
proof(rule CompDefinedI, simp_all add: SETmor[THEN sym])
show "isZFfun (ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))))"
proof(rule SETfun, rule allI, rule impI)
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
have "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Z to X" using assms h xobj zobj by (simp add: LSCategory.z2mm2z)
hence "f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Y to X" using fmapsb assms(1) by (simp add: Category.Ccompt)
thus "(m2z\<^bsub>C\<^esub> (f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) |\<in>| (Hom\<^bsub>C\<^esub> Y X)" using assms by (simp add: LSCategory.m2zz2m)
qed
moreover show "isZFfun (ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x))"
proof(rule SETfun, rule allI, rule impI)
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Y X)"
have "(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Y)" using xobj yobj h by (simp add: Fzmaps)
thus "(F ## (z2m\<^bsub>C \<^esub>h)) |@| x |\<in>| (F @@ Y)" using assms by (simp add: SETfunDomAppCod)
qed
ultimately show "cod\<^bsub>SET\<^esub>(ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h)))) =
dom\<^bsub>SET\<^esub>(ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x))" by (simp add: SETcod SETdom)
qed
have compdefb: "ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) \<approx>>\<^bsub>SET\<^esub>
ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h)"
proof(rule CompDefinedI, simp_all add: SETmor[THEN sym])
show "isZFfun (ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x))" using hHomF by (simp add: SETfun)
moreover show "isZFfun (ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h))"
proof(rule SETfun, rule allI, rule impI)
fix h assume h: "h |\<in>| (F @@ Z)"
have "F ## f maps\<^bsub>SET\<^esub> F @@ Z to F @@ Y" using Ffmaps .
thus "(F ## f) |@| h |\<in>| (F @@ Y)" using h by (simp add: SETfunDomAppCod)
qed
ultimately show "cod\<^bsub>SET\<^esub> (ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x)) =
dom\<^bsub>SET\<^esub> (ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h))" by (simp add: SETcod SETdom)
qed
have "ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) ;;\<^bsub>SET\<^esub>
ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) =
ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) |o|
ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x)" using Ff compdefa by (simp add: SETComp)
also have "... = ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Y) ((\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) o (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))))"
proof(rule ZFfunComp, rule allI, rule impI)
{
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
show "(m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) |\<in>| (Hom\<^bsub>C\<^esub> Y X)"
proof-
have "Z \<in> Obj C" using fmapsb assms by (simp add: Category.MapsToObj)
hence "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Z to X" using assms h by (simp add: LSCategory.z2mm2z)
hence "f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Y to X" using fmapsb assms(1) by (simp add: Category.Ccompt)
thus ?thesis using assms by (simp add: LSCategory.m2zz2m)
qed
}
qed
also have "... = ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Y) ((\<lambda>h. (F ## f) |@| h) o (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x))"
proof(rule ZFfun_ext, rule allI, rule impI, simp)
{
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
have zObj: "Z \<in> Obj C" using fmapsb assms by (simp add: Category.MapsToObj)
hence hmaps: "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Z to X" using assms h by (simp add: LSCategory.z2mm2z)
hence "(z2m\<^bsub>C \<^esub>h) \<in> Mor C" and "dom\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h) = cod\<^bsub>C\<^esub> f" using fcod by auto
hence CompDef_hf: "f \<approx>>\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h)" using fmor by auto
hence CompDef_hfOp: "(z2m\<^bsub>C \<^esub>h) \<approx>>\<^bsub>Op C\<^esub> f" by (simp add: CompDefOp)
hence CompDef_FhfOp: "(F ## (z2m\<^bsub>C \<^esub>h)) \<approx>>\<^bsub>SET\<^esub> (F ## f)" using assms by (simp add: FunctorCompDef)
hence "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>Op C\<^esub> X to Z" using hmaps by (simp add: MapsToOp)
hence "(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Z)" using assms by (simp add: FunctorMapsTo)
hence xin: "x |\<in>| |dom|(F ## (z2m\<^bsub>C \<^esub>h))" using assms by (simp add: SETmapsTo)
have "(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h)) \<in> Mor C" using CompDef_hf assms by(simp add: Category.MapsToMorDomCod)
hence "(F ## (z2m\<^bsub>C \<^esub>(m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))))) |@| x = (F ## (f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) |@| x"
using assms by (simp add: LSCategory.m2zz2mInv)
also have "... = (F ## ((z2m\<^bsub>C \<^esub>h) ;;\<^bsub>Op C\<^esub> f)) |@| x" by (simp add: OppositeCategory_def)
also have "... = ((F ## (z2m\<^bsub>C \<^esub>h)) ;;\<^bsub>SET \<^esub>(F ## f)) |@| x" using assms CompDef_hfOp by (simp add: FunctorComp)
also have "... = (F ## f) |@| ((F ## (z2m\<^bsub>C \<^esub>h)) |@| x)" using CompDef_FhfOp xin by(rule SETCompAt)
finally show "(F ## (z2m\<^bsub>C \<^esub>(m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))))) |@| x = (F ## f) |@| ((F ## (z2m\<^bsub>C \<^esub>h)) |@| x)" .
}
qed
also have "... = ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) |o|
ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h)"
by(rule ZFfunComp[THEN sym], rule allI, rule impI, simp add: hHomF)
also have "... = ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) ;;\<^bsub>SET\<^esub> (F ## f)"
using Ff compdefb by (simp add: SETComp)
finally show "(((YFtor C) @@ X) ## f) ;;\<^bsub>CatCod F\<^esub> ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## (z2m\<^bsub>C \<^esub>f)) |@| x) =
ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>f. (F ## (z2m\<^bsub>C \<^esub>f)) |@| x) ;;\<^bsub>CatCod F\<^esub> (F ## f)"
by(simp add: cf yf hc fdom fcod HomFtorMapContra_def)
}
qed
lemma YMapInvNatTrans:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and "X \<in> Obj C" and "x |\<in>| (F @@ X)"
shows "NatTrans (YMapInv C X F x)"
by (simp add: assms YMapInv_def MakeNT YMapInvNatTransP)
lemma YMapInvImage:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and "X \<in> Obj C"
and "x |\<in>| (F @@ X)"
shows "NT (YMapInv C X F x) : (YFtor C @@ X) \<Longrightarrow> F"
proof(auto simp only: nt_abbrev_def)
show "NatTrans (YMapInv C X F x)" using assms by (simp add: YMapInvNatTrans)
show "NTDom (YMapInv C X F x) = YFtor C @@ X" by(simp add: YMapInv_def MakeNT_def YMapInv'_def)
show "NTCod (YMapInv C X F x) = F" by(simp add: YMapInv_def MakeNT_def YMapInv'_def)
qed
lemma YMap1:
assumes LSCat: "LSCategory C" and Fftor: "Ftor F : (Op C) \<longrightarrow> SET" and XObj: "X \<in> Obj C"
and NT: "NT \<eta> : (YFtor C @@ X) \<Longrightarrow> F"
shows "YMapInv C X F (YMap C X \<eta>) = \<eta>"
proof(rule NatTransExt)
have "(YMap C X \<eta>) |\<in>| (F @@ X)" using assms by (simp add: YMapImage)
hence 1: "NT (YMapInv C X F (YMap C X \<eta>)) : (YFtor C @@ X) \<Longrightarrow> F" using assms by (simp add: YMapInvImage)
thus "NatTrans (YMapInv C X F (YMap C X \<eta>))" by auto
show "NatTrans \<eta>" using assms by auto
have NTDYI: "NTDom (YMapInv C X F (YMap C X \<eta>)) = (YFtor C @@ X)" using 1 by auto
moreover have NTDeta: "NTDom \<eta> = (YFtor C @@ X)" using assms by auto
ultimately show "NTDom (YMapInv C X F (YMap C X \<eta>)) = NTDom \<eta>" by simp
have "NTCod (YMapInv C X F (YMap C X \<eta>)) = F" using 1 by auto
moreover have NTCeta: "NTCod \<eta> = F" using assms by auto
ultimately show "NTCod (YMapInv C X F (YMap C X \<eta>)) = NTCod \<eta>" by simp
{
fix Y assume Yobja: "Y \<in> Obj (NTCatDom (YMapInv C X F (YMap C X \<eta>)))"
have CCF: "CatCod F = SET" using assms by auto
have "Ftor (Hom\<^bsub>C\<^esub>[\<emdash>,X]) : (Op C) \<longrightarrow> SET" using LSCat XObj by (simp add: HomFtorContraFtor)
hence CDH: "CatDom (Hom\<^bsub>C\<^esub>[\<emdash>,X]) = Op C" by auto
hence CDYF: "CatDom (YFtor C @@ X) = Op C" using XObj LSCat by (auto simp add: YFtorObj)
hence "NTCatDom (YMapInv C X F (YMap C X \<eta>)) = Op C" using LSCat XObj NTDYI CDH by (simp add: NTCatDom_def)
hence YObjOp: "Y \<in> Obj (Op C)" using Yobja by simp
hence YObj: "Y \<in> Obj C" and XObjOp: "X \<in> Obj (Op C)" using XObj by (simp add: OppositeCategory_def)+
have yinv_mapsTo: "((YMapInv C X F (YMap C X \<eta>)) $$ Y) maps\<^bsub>SET\<^esub> (Hom\<^bsub>C \<^esub>Y X) to (F @@ Y)"
proof-
have "((YMapInv C X F (YMap C X \<eta>)) $$ Y) maps\<^bsub>SET\<^esub> ((YFtor C @@ X) @@ Y) to (F @@ Y)"
using 1 CCF CDYF YObjOp NatTransMapsTo[of "(YMapInv C X F (YMap C X \<eta>))" "(YFtor C @@ X)" F Y] by simp
thus ?thesis using LSCat XObj YObj by (simp add: YFtorObj2)
qed
have eta_mapsTo: "(\<eta> $$ Y) maps\<^bsub>SET\<^esub> (Hom\<^bsub>C \<^esub>Y X) to (F @@ Y)"
proof-
have "(\<eta> $$ Y) maps\<^bsub>SET\<^esub> ((YFtor C @@ X) @@ Y) to (F @@ Y)"
using NT CDYF CCF YObjOp NatTransMapsTo[of \<eta> "(YFtor C @@ X)" F Y] by simp
thus ?thesis using LSCat XObj YObj by (simp add: YFtorObj2)
qed
show "(YMapInv C X F (YMap C X \<eta>)) $$ Y = \<eta> $$ Y"
proof(rule ZFfunExt)
show "|dom|(YMapInv C X F (YMap C X \<eta>) $$ Y) = |dom|(\<eta> $$ Y)"
using yinv_mapsTo eta_mapsTo by (simp add: SETmapsTo)
show "|cod|(YMapInv C X F (YMap C X \<eta>) $$ Y) = |cod|(\<eta> $$ Y)"
using yinv_mapsTo eta_mapsTo by (simp add: SETmapsTo)
show "isZFfun (YMapInv C X F (YMap C X \<eta>) $$ Y)"
using yinv_mapsTo by (simp add: SETmapsTo)
show "isZFfun (\<eta> $$ Y)"
using eta_mapsTo by (simp add: SETmapsTo)
{
fix f assume fdomYinv: "f |\<in>| |dom|(YMapInv C X F (YMap C X \<eta>) $$ Y)"
have fHom: "f |\<in>| (Hom\<^bsub>C\<^esub> Y X)" using yinv_mapsTo fdomYinv by (simp add: SETmapsTo)
hence fMapsTo: "(z2m\<^bsub>C \<^esub>f) maps\<^bsub>C \<^esub>Y to X" using assms YObj by (simp add: LSCategory.z2mm2z)
hence fCod: "(cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) = X" and fDom: "(dom\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) = Y" and fMor: "(z2m\<^bsub>C \<^esub>f) \<in> Mor C" by auto
have "(YMapInv C X F (YMap C X \<eta>) $$ Y) |@| f =
(F ## (z2m\<^bsub>C \<^esub>f)) |@| ((\<eta> $$ X) |@| (m2z\<^bsub>C \<^esub>(Id C X)))"
using fHom assms YObj by (simp add: ZFfunApp YMapInvApp YMap_def)
also have "... = ((\<eta> $$ X) ;;\<^bsub>SET\<^esub> (F ## (z2m\<^bsub>C \<^esub>f))) |@| (m2z\<^bsub>C \<^esub>(Id C X))"
proof-
have aa: "(\<eta> $$ X) maps\<^bsub>SET\<^esub> ((YFtor C @@ X) @@ X) to (F @@ X)"
using NT CDYF CCF YObjOp XObjOp NatTransMapsTo[of \<eta> "(YFtor C @@ X)" F X] by simp
have bb: "(F ## (z2m\<^bsub>C \<^esub>f)) maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Y)"
using fMapsTo Fftor by (simp add: MapsToOp FunctorMapsTo)
have "(\<eta> $$ X) \<approx>>\<^bsub>SET\<^esub> (F ## (z2m\<^bsub>C \<^esub>f))" using aa bb by (simp add: MapsToCompDef)
moreover have "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| |dom| (\<eta> $$ X)" using assms aa
by (simp add: SETmapsTo YFtorObj2 Category.Cidm LSCategory.m2zz2m)
ultimately show ?thesis by (simp add: SETCompAt)
qed
also have "... = ((HomC\<^bsub>C\<^esub>[z2m\<^bsub>C \<^esub>f,X]) ;;\<^bsub>SET\<^esub> (\<eta> $$ Y)) |@| (m2z\<^bsub>C \<^esub>(Id C X))"
proof-
have "NTDom \<eta> = (Hom\<^bsub>C\<^esub>[\<emdash>,X])" using NTDeta assms by (simp add: YFtorObj)
moreover hence "NTCatDom \<eta> = Op C" by (simp add: NTCatDom_def HomFtorContraDom)
moreover have "NTCatCod \<eta> = SET" using assms by (auto simp add: NTCatCod_def)
moreover have "NatTrans \<eta>" and "NTCod \<eta> = F" using assms by auto
moreover have "(z2m\<^bsub>C \<^esub>f) maps\<^bsub>Op C \<^esub>X to Y"
using fMapsTo MapsToOp[where ?f = "(z2m\<^bsub>C \<^esub>f)" and ?X = Y and ?Y = X and ?C = C] by simp
ultimately have "(\<eta> $$ X) ;;\<^bsub>SET\<^esub> (F ## (z2m\<^bsub>C \<^esub>f)) = ((Hom\<^bsub>C\<^esub>[\<emdash>,X]) ## (z2m\<^bsub>C \<^esub>f)) ;;\<^bsub>SET\<^esub> (\<eta> $$ Y)"
using NatTransP.NatTrans[of \<eta> "(z2m\<^bsub>C \<^esub>f)" X Y] by simp
moreover have "((Hom\<^bsub>C\<^esub>[\<emdash>,X]) ## (z2m\<^bsub>C \<^esub>f)) = (HomC\<^bsub>C\<^esub>[(z2m\<^bsub>C \<^esub>f),X])" using assms fMor by (simp add: HomContraMor)
ultimately show ?thesis by simp
qed
also have "... = (\<eta> $$ Y) |@| ((HomC\<^bsub>C\<^esub>[z2m\<^bsub>C \<^esub>f,X]) |@| (m2z\<^bsub>C \<^esub>(Id C X)))"
proof-
have "(HomC\<^bsub>C\<^esub>[z2m\<^bsub>C \<^esub>f,X]) \<approx>>\<^bsub>SET\<^esub> (\<eta> $$ Y)"
using fCod fDom XObj LSCat fMor HomFtorContraMapsTo[of C X "z2m\<^bsub>C \<^esub>f"] eta_mapsTo by (simp add: MapsToCompDef)
moreover have "|dom| (HomC\<^bsub>C\<^esub>[z2m\<^bsub>C \<^esub>f,X]) = (Hom\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) X)"
by (simp add: ZFfunDom HomFtorMapContra_def)
moreover have "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| (Hom\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) X)"
using assms fCod by (simp add: Category.Cidm LSCategory.m2zz2m)
ultimately show ?thesis by (simp add: SETCompAt)
qed
also have "... = (\<eta> $$ Y) |@| (m2z\<^bsub>C\<^esub> ((z2m\<^bsub>C \<^esub>f) ;;\<^bsub>C\<^esub> (z2m\<^bsub>C\<^esub> (m2z\<^bsub>C \<^esub>(Id C X)))))"
proof-
have "(Id C X) maps\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) to X" using assms fCod by (simp add: Category.Cidm)
hence "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| (Hom\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) X)" using assms by (simp add: LSCategory.m2zz2m)
thus ?thesis by (simp add: HomContraAt)
qed
also have "... = (\<eta> $$ Y) |@| (m2z\<^bsub>C\<^esub> ((z2m\<^bsub>C \<^esub>f) ;;\<^bsub>C\<^esub> (Id C X)))"
using assms by (simp add: LSCategory.m2zz2mInv Category.CatIdInMor)
also have "... = (\<eta> $$ Y) |@| (m2z\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f))" using assms(1) fCod fMor Category.Cidr[of C "(z2m\<^bsub>C \<^esub>f)"] by (simp)
also have "... = (\<eta> $$ Y) |@| f" using assms YObj fHom by (simp add: LSCategory.z2mm2z)
finally show "(YMapInv C X F (YMap C X \<eta>) $$ Y) |@| f = (\<eta> $$ Y) |@| f" .
}
qed
}
qed
lemma YMap2:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and "X \<in> Obj C"
and "x |\<in>| (F @@ X)"
shows "YMap C X (YMapInv C X F x) = x"
proof(simp only: YMap_def)
let ?\<eta> = "(YMapInv C X F x)"
have "(?\<eta> $$ X) = ZFfun (Hom\<^bsub>C\<^esub> X X) (F @@ X) (\<lambda> f . (F ## (z2m\<^bsub>C\<^esub> f)) |@| x)" using assms by (simp add: YMapInvApp)
moreover have "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| (Hom\<^bsub>C\<^esub> X X)" using assms by (simp add: Category.Simps LSCategory.m2zz2m)
ultimately have "(?\<eta> $$ X) |@| (m2z\<^bsub>C \<^esub>(Id C X)) = (F ## (z2m\<^bsub>C\<^esub> (m2z\<^bsub>C \<^esub>(Id C X)))) |@| x"
by (simp add: ZFfunApp)
also have "... = (F ## (Id C X)) |@| x" using assms by (simp add: Category.CatIdInMor LSCategory.m2zz2mInv)
also have "... = (Id SET (F @@ X)) |@| x"
proof-
have "X \<in> Obj (Op C)" using assms by (auto simp add: OppositeCategory_def)
hence "(F ## (Id (Op C) X)) = (Id SET (F @@ X))"
using assms by(simp add: FunctorId)
moreover have "(Id (Op C) X) = (Id C X)" using assms by (auto simp add: OppositeCategory_def)
ultimately show ?thesis by simp
qed
also have "... = x" using assms by (simp add: SETId)
finally show "(?\<eta> $$ X) |@| (m2z\<^bsub>C \<^esub>(Id C X)) = x" .
qed
lemma YFtorNT_YMapInv:
assumes "LSCategory C" and "f maps\<^bsub>C\<^esub> X to Y"
shows "YFtorNT C f = YMapInv C X (Hom\<^bsub>C\<^esub>[\<emdash>,Y]) (m2z\<^bsub>C\<^esub> f)"
proof(simp only: YFtorNT_def YMapInv_def, rule NatTransExt')
have Cf: "cod\<^bsub>C\<^esub> f = Y" and Df: "dom\<^bsub>C\<^esub> f = X" using assms by auto
thus "NTCod (YFtorNT' C f) = NTCod (YMapInv' C X (Hom\<^bsub>C\<^esub>[\<emdash>,Y]) (m2z\<^bsub>C\<^esub>f))"
by(simp add: YFtorNT'_def YMapInv'_def )
have "Hom\<^bsub>C\<^esub>[\<emdash>,dom\<^bsub>C\<^esub> f] = YFtor C @@ X" using Df assms by (simp add: YFtorObj Category.MapsToObj)
thus "NTDom (YFtorNT' C f) = NTDom (YMapInv' C X (Hom\<^bsub>C\<^esub>[\<emdash>,Y]) (m2z\<^bsub>C\<^esub>f))"
by(simp add: YFtorNT'_def YMapInv'_def )
{
fix Z assume ObjZ1: "Z \<in> Obj (NTCatDom (YFtorNT' C f))"
have ObjZ2: "Z \<in> Obj C" using ObjZ1 by (simp add: YFtorNT'_def NTCatDom_def OppositeCategory_def HomFtorContraDom)
moreover have ObjX: "X \<in> Obj C" and ObjY: "Y \<in> Obj C" using assms by (simp add: Category.MapsToObj)+
moreover
{
fix x assume x: "x |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
have "m2z\<^bsub>C \<^esub>((z2m\<^bsub>C \<^esub>x) ;;\<^bsub>C\<^esub> f) = ((Hom\<^bsub>C\<^esub>[\<emdash>,Y]) ## (z2m\<^bsub>C \<^esub>x)) |@| (m2z\<^bsub>C\<^esub>f)"
proof-
have morf: "f \<in> Mor C" using assms by auto
have mapsx: "(z2m\<^bsub>C \<^esub>x) maps\<^bsub>C\<^esub> Z to X" using x assms(1) ObjZ2 ObjX by (simp add: LSCategory.z2mm2z)
hence morx: "(z2m\<^bsub>C \<^esub>x) \<in> Mor C" by auto
hence "(Hom\<^bsub>C\<^esub>[\<emdash>,Y]) ## (z2m\<^bsub>C \<^esub>x) = (HomC\<^bsub>C\<^esub>[(z2m\<^bsub>C \<^esub>x),Y])" using assms by (simp add: HomContraMor)
moreover have "(HomC\<^bsub>C\<^esub>[(z2m\<^bsub>C \<^esub>x),Y]) |@| (m2z\<^bsub>C \<^esub>f) = m2z\<^bsub>C \<^esub>((z2m\<^bsub>C \<^esub>x) ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>(m2z\<^bsub>C \<^esub>f)))"
proof (rule HomContraAt)
have "cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>x) = X" using mapsx by auto
thus "(m2z\<^bsub>C \<^esub>f) |\<in>| (Hom\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>x)) Y)" using assms by (simp add: LSCategory.m2zz2m)
qed
moreover have "(z2m\<^bsub>C \<^esub>(m2z\<^bsub>C \<^esub>f)) = f" using assms morf by (simp add: LSCategory.m2zz2mInv)
ultimately show ?thesis by simp
qed
}
ultimately show "(YFtorNT' C f) $$ Z = (YMapInv' C X (Hom\<^bsub>C\<^esub>[\<emdash>,Y]) (m2z\<^bsub>C\<^esub>f)) $$ Z" using Cf Df assms
apply(simp add: YFtorNT'_def YMapInv'_def HomFtorMap_def HomFtorOpObj)
apply(rule ZFfun_ext, rule allI, rule impI, simp)
done
}
qed
lemma YMapYoneda:
assumes "LSCategory C" and "f maps\<^bsub>C\<^esub> X to Y"
shows "YFtor C ## f = YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> f)"
proof-
have "f \<in> Mor C" using assms by auto
moreover have "Y \<in> Obj C" using assms by (simp add: Category.MapsToObj)
moreover have "YFtorNT C f = YMapInv C X (Hom\<^bsub>C\<^esub>[\<emdash>,Y]) (m2z\<^bsub>C\<^esub> f)" using assms by (simp add: YFtorNT_YMapInv)
ultimately show ?thesis using assms by (simp add: YFtorMor YFtorObj)
qed
lemma YonedaFull:
assumes "LSCategory C" and "X \<in> Obj C" and "Y \<in> Obj C"
and "NT \<eta> : (YFtor C @@ X) \<Longrightarrow> (YFtor C @@ Y)"
shows "YFtor C ## (z2m\<^bsub>C\<^esub> (YMap C X \<eta>)) = \<eta>"
and "z2m\<^bsub>C\<^esub> (YMap C X \<eta>) maps\<^bsub>C\<^esub> X to Y"
proof-
have ftor: "Ftor (YFtor C @@ Y) : (Op C) \<longrightarrow> SET" using assms by (simp add: YFtorObj HomFtorContraFtor)
hence "(YMap C X \<eta>) |\<in>| ((YFtor C @@ Y) @@ X)" using assms by (simp add: YMapImage)
hence yh: "(YMap C X \<eta>) |\<in>| (Hom\<^bsub>C\<^esub> X Y)" using assms by (simp add: YFtorObj2)
thus "(z2m\<^bsub>C\<^esub> (YMap C X \<eta>)) maps\<^bsub>C\<^esub> X to Y" using assms by (simp add: LSCategory.z2mm2z)
hence "YFtor C ## (z2m\<^bsub>C\<^esub> (YMap C X \<eta>)) = YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> (z2m\<^bsub>C\<^esub> (YMap C X \<eta>)))"
using assms yh by (simp add: YMapYoneda)
also have "... = YMapInv C X (YFtor C @@ Y) (YMap C X \<eta>)"
using assms yh by (simp add: LSCategory.z2mm2z)
finally show "YFtor C ## (z2m\<^bsub>C\<^esub> (YMap C X \<eta>)) = \<eta>" using assms ftor by (simp add: YMap1)
qed
lemma YonedaFaithful:
assumes "LSCategory C" and "f maps\<^bsub>C\<^esub> X to Y" and "g maps\<^bsub>C\<^esub> X to Y"
and "YFtor C ## f = YFtor C ## g"
shows "f = g"
proof-
have ObjX: "X \<in> Obj C" and ObjY: "Y \<in> Obj C" using assms by (simp add: Category.MapsToObj)+
have M2Zf: "(m2z\<^bsub>C\<^esub> f) |\<in>| ((YFtor C @@ Y) @@ X)" and M2Zg: "(m2z\<^bsub>C\<^esub> g) |\<in>| ((YFtor C @@ Y) @@ X)"
using assms ObjX ObjY by (simp add: LSCategory.m2zz2m YFtorObj2)+
have Ftor: "Ftor (YFtor C @@ Y) : (Op C) \<longrightarrow> SET" using assms ObjY by (simp add: YFtorObj HomFtorContraFtor)
have Morf: "f \<in> Mor C" and Morg: "g \<in> Mor C" using assms by auto
have "YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> f) = YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> g)"
using assms by (simp add: YMapYoneda)
hence "YMap C X (YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> f)) = YMap C X (YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> g))"
by simp
hence "(m2z\<^bsub>C\<^esub> f) = (m2z\<^bsub>C\<^esub> g)" using assms ObjX ObjY M2Zf M2Zg Ftor by (simp add: YMap2)
thus "f = g" using assms Morf Morg by (simp add: LSCategory.mor2ZFInj)
qed
lemma YonedaEmbedding:
assumes "LSCategory C" and "A \<in> Obj C" and "B \<in> Obj C" and "(YFtor C) @@ A = (YFtor C) @@ B"
shows "A = B"
proof-
have AObjOp: "A \<in> Obj (Op C)" and BObjOp: "B \<in> Obj (Op C)" using assms by (simp add: OppositeCategory_def)+
hence FtorA: "Ftor (Hom\<^bsub>C\<^esub>[\<emdash>,A]) : (Op C) \<longrightarrow> SET" and FtorB: "Ftor (Hom\<^bsub>C\<^esub>[\<emdash>,B]) : (Op C) \<longrightarrow> SET"
using assms by (simp add: HomFtorContraFtor)+
have "Hom\<^bsub>C\<^esub>[\<emdash>,A] = Hom\<^bsub>C\<^esub>[\<emdash>,B]" using assms by (simp add: YFtorObj)
hence "(Hom\<^bsub>C\<^esub>[\<emdash>,A]) ## (Id (Op C) A) = (Hom\<^bsub>C\<^esub>[\<emdash>,B]) ## (Id (Op C) A)" by simp
hence "Id SET ((Hom\<^bsub>C\<^esub>[\<emdash>,A]) @@ A) = Id SET ((Hom\<^bsub>C\<^esub>[\<emdash>,B]) @@ A)"
using AObjOp BObjOp FtorA FtorB by (simp add: FunctorId)
hence "Id SET (Hom\<^bsub>C \<^esub>A A) = Id SET (Hom\<^bsub>C \<^esub>A B)" using assms by (simp add: HomFtorOpObj)
hence "Hom\<^bsub>C \<^esub>A A = Hom\<^bsub>C \<^esub>A B" using SETCategory by (simp add: Category.IdInj SETobj[of "Hom\<^bsub>C \<^esub>A A"] SETobj[of "Hom\<^bsub>C \<^esub>A B"])
moreover have "(m2z\<^bsub>C\<^esub> (Id C A)) |\<in>| (Hom\<^bsub>C \<^esub>A A)" using assms by (simp add: Category.Cidm LSCategory.m2zz2m)
ultimately have "(m2z\<^bsub>C\<^esub> (Id C A)) |\<in>| (Hom\<^bsub>C \<^esub>A B)" by simp
hence "(z2m\<^bsub>C\<^esub> (m2z\<^bsub>C\<^esub> (Id C A))) maps\<^bsub>C\<^esub> A to B" using assms by (simp add: LSCategory.z2mm2z)
hence "(Id C A) maps\<^bsub>C\<^esub> A to B" using assms by (simp add: Category.CatIdInMor LSCategory.m2zz2mInv)
hence "cod\<^bsub>C\<^esub> (Id C A) = B" by auto
thus ?thesis using assms by (simp add: Category.CatIdDomCod)
qed
end
|
#### Example $\int x^2.e^{3x}.dx$
(from http://www.mathcentre.ac.uk/resources/uploaded/mc-ty-parts-2009-1.pdf)
$\ds \begin{equation} \label{eq3}
\begin{split}
\text{using formula} \\
\int u.\frac{d(v)}{dx} & = u.v - \int v.\frac{d(u)}{dx} dx \\
\text{we assign} \\
u & = x^2 \\
\frac{dv}{dx} & = e^{3x} \\
\text{we calculate} \\
v & = \int \frac{dv}{dx} dx = \int e^{3x} dx = \frac{1}{3}e^{3x} \\
\frac{du}{dx} & = \frac{d(x^2)}{dx} = 2x \\
\text{then apply to formula} \\
\int x^2e^{3x} & = x^2\frac{e^{3x}}{3} - \int \frac{e^{3x}}{3}2x dx \\
& = \frac{1}{3}x^2e^{3x} - \int \frac{2}{3}xe^{3x} dx \\
\\
\text{using formula again} \\
\int u.\frac{d(v)}{dx} & = u.v - \int v.\frac{d(u)}{dx} dx \\
\text{we assign} \\
u & = \frac{2}{3}x \\
\frac{dv}{dx} & = e^{3x} \\
\text{we calculate} \\
v & = \int \frac{dv}{dx} dx = \int e^{3x} dx = \frac{1}{3}e^{3x} \\
\frac{du}{dx} & = \frac{d(\frac{2}{3}x)}{dx} = \frac{2}{3} \\
\text{then apply to formula} \\
\int \frac{2}{3}xe^{3x} dx & = \frac{2}{3}x\frac{1}{3}e^{3x} - \int \Big( \frac{1}{3}e^{3x} . \frac{2}{3} \Big) dx \\
& = \frac{2}{9}x.e^{3x} - \int \frac{2}{9}e^{3x} dx \\
& = \frac{2}{9}x.e^{3x} - \frac{2}{27}e^{3x} \\
\\
\text{replace with earlier calc} \\
& = \frac{1}{3}x^2e^{3x} - \frac{2}{9}x.e^{3x} - \frac{2}{27}e^{3x} + C \\
& = \Big( \frac{1}{3}x^2 - \frac{2}{9}x - \frac{2}{27} \Big)e^{3x} + C \\
& = \frac{9x^2 - 6x - 2}{27}e^{3x} + C \\
\text{completing the square} \\
& = \frac{(3x-1)^2 - 3}{27}e^{3x} + C \\
\\
\end{split}
\end{equation}$
----
### Integration by Parts
#### Example $\int x.cos(x).dx$
(from http://www.mathcentre.ac.uk/resources/uploaded/mc-ty-parts-2009-1.pdf)
$\newcommand{\dv}{\displaystyle \frac{d}{dx}}$
$\newcommand{\ds}{\displaystyle}$
$\ds \begin{equation} \label{eq2}
\begin{split}
\text{using formula} \\
\int u.\frac{d(v)}{dx} & = u.v - \int v.\frac{d(u)}{dx} dx \\
\text{we assign} \\
u & = x \\
\frac{dv}{dx} & = cos(x) \\
\text{we calculate} \\
v & = \int \frac{dv}{dx} dx = \int cos(x) dx = sin(x) \\
\frac{du}{dx} & = \frac{d(x)}{dx} = 1 \\
\text{then apply to formula} \\
\int x.cos(x).dx & = x.sin(x) - \int sin(x).1.dx \\
& = x.sin(x) - cos(x) + C \\
\end{split}
\end{equation}$
----
```python
```
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 16:02:09 2020
Neural PDE - Tensorflow 2.X
Module : Sampler
Samples points from the domain space according to the specified procedure.
"""
import numpy as np
import tensorflow as tf
from pyDOE import lhs
def domain_sampler(N, lb, ub):
lb = np.asarray(lb)
ub = np.asarray(ub)
X_f = lb + (ub-lb)*lhs(2, N)
return X_f
def boundary_sampler(N, lb, ub):
lb = np.asarray(lb)
ub = np.asarray(ub)
N_2 = int(N/2)
X_b = lb + (ub-lb)*lhs(2, N)
X_b[0:N_2, 1] = lb[1]
X_b[N_2:2*N_2, 1] = ub[1]
return X_b
def initial_sampler(N, lb, ub):
lb = np.asarray(lb)
ub = np.asarray(ub)
X_i = lb + (ub-lb)*lhs(2, N)
X_i[:, 0] = np.zeros(N)
return X_i
class Sampler(object):
def __init__(self, N_samples, subspace_N):
"""
Parameters
----------
N_samples : INT
Number of points sampled from the domain space.
subspace_N : INT
Number of points we want to sample from each subspace.
Returns
-------
None.
"""
self.N = N_samples
self.ssN = subspace_N
def residual(self, n, t_bounds):
""" Calculates the residual value for across each subspace """
residual_across_time = []
for ii in range(n-1):
lb_temp = np.asarray([t_bounds[ii], self.lb[1]])
ub_temp = np.asarray([t_bounds[ii+1], self.ub[1]])
X_f = lb_temp + (ub_temp-lb_temp)*lhs(self.input_size, self.ssN)
str_val = tf.reduce_mean(tf.square(self.pde_func(X_f)))
residual_across_time.append(str_val)
return np.asarray(residual_across_time)
def str_sampler(self):
""" Samples ssN points from the subspace with the worst residual performance """
n = int(self.N/self.ssN)
t_bounds = np.linspace(self.lb[0], self.ub[0], n)
residuals = self.residual(n, t_bounds)
t_range_idx = np.argmax(residuals)
print('\n')
print("Time_Index : {}".format(t_range_idx))
lb_temp = np.asarray([t_bounds[t_range_idx], self.lb[1]])
ub_temp = np.asarray([t_bounds[t_range_idx+1], self.ub[1]])
X_f = lb_temp + (ub_temp-lb_temp)*lhs(self.input_size, self.ssN)
return X_f
def uniform_sampler(self):
""" Uniformly samples N points from across the domain space of interest """
X_f = self.lb + (self.ub-self.lb)*lhs(self.input_size, self.N)
return X_f
|
Tú siempre sales al mismo sitio para cenar.You always go out to the same place for dinner.
¿Hay sitio para todos en el coche?Is there room for everybody in the car?
Si no hay sitio para sentarse en el teatro, reembolsaremos su boleto.If there is no space to sit in the theater, we will reimburse your ticket.
El sitio a la ciudad duró tres días.The siege to the city lasted three days.
Hay muchos sitios en Internet donde puedes buscar una vivienda de alquiler o de compra.There are many sites on the Internet where you can search for a property to rent or purchase.
Mira, en este sitio puedes descargar esos programas que necesitas.Look, you can download those programs you need on this website.
Acabo de llegar al sitio así que estoy todavía a 20 minutos.I just got to the taxi stand, so I'm still 20 minutes away.
Planifican convertir a ese sitio en un centro comercial en los próximos diez años.They plan on converting that vacant lot into a mall in the next ten years.
Here are the most popular phrases with "sitio." Click the phrases to see the full entry.
si quieres volver a un sitio anterior, ¿qué haces?
if you want to go back to a previous site, what do you do?
¿Almorzaste en algún sitio típico mexicano?
Did you eat at a typical Mexican place? |
(*******************************************************************)
(* This is part of RelationAlgebra, it is distributed under the *)
(* terms of the GNU Lesser General Public License version 3 *)
(* (see file LICENSE for more details) *)
(* *)
(* Copyright 2012: Damien Pous. (CNRS, LIP - ENS Lyon, UMR 5668) *)
(*******************************************************************)
(** * kat_reification: various definitions to ease the KAT reification process *)
(** We reify KAT terms as [syntax.expr] trees over an alphabet
including [lsyntax.expr] for Boolean tests. This allows us to reuse
the tools developped for ra_{normalise,reflexivity}, and this gives
us more flexibility
Here define the conversion function from this syntax to [gregex],
as well as dependently typed positive maps to ease the definition
of the environment for predicate variables *)
Require Import lsyntax ordinal lset.
Require Export positives kat gregex syntax.
Section s.
Notation Idx := positive. (* type indices *)
Notation Sigma := positive. (* Kleene variable indices *)
Notation Pred := positive. (* predicate variables indices *)
Context {X: kat.ops}.
(** * Dependently types positive maps *)
(** we use dependently typed binary trees:
[v f'] is used to repredent dependent functions of
type [forall n, Pred -> tst (f' n)] *)
Inductive v: (Idx -> ob X) -> Type :=
| v_L: forall f', v f'
| v_N: forall f',
v (fun n => f' (xO n)) ->
(Pred -> tst (f' xH)) ->
v (fun n => f' (xI n)) -> v f'.
(** [v_get] transforms such a tree into the corresponding function,
using [lattice.top] to fill the gaps *)
Fixpoint v_get f' (t: v f') n p: tst (f' n) :=
match t with
| v_L _ => lattice.top
| v_N _ l m r =>
match n with
| xO n => v_get _ l n p
| xI n => v_get _ r n p
| xH => m p
end
end.
(** [v_add f' t n x] adds the binding [(n,x)] to [t] *)
Fixpoint v_add f' (t: v f') n: (Pred -> tst (f' n)) -> v f' :=
match t with
| v_L f' =>
match n with
| xH => fun x => v_N _ (v_L _) x (v_L _)
| xO n => fun x => v_N _
(v_add (fun n => f' (xO n)) (v_L _) n x) (fun _ => lattice.top) (v_L _)
| xI n => fun x => v_N _
(v_L _) (fun _ => lattice.top) (v_add (fun n => f' (xI n)) (v_L _) n x)
end
| v_N f' l y r =>
match n with
| xH => fun x => v_N _ l x r
| xO n => fun x => v_N _ (v_add (fun n => f' (xO n)) l n x) y r
| xI n => fun x => v_N _ l y (v_add (fun n => f' (xI n)) r n x)
end
end.
(** * Syntax of KAT reification *)
(** we use packages for Kleene variables, as for [ra_refication] *)
Context {f': Idx -> ob X} {fs: Sigma -> Pack X f'}.
(** reified KAT expressions are just generic expressions
([syntax.expr]) over the following alphabet, which includes
[lsyntax.expr] for Boolean expressions. The index type of the
Boolean expressions is declared only once, at the [e_var] nodes
switching from [syntax.expr] to [lsyntax.expr] *)
Definition var := (Sigma + Idx * lsyntax.expr Pred)%type.
(** typing functions for this alphabet: use the packages for Kleene
variables, and the declared type for Boolean expressions *)
Definition s' (a: var) := match a with inl a => src_ fs a | inr (n,_) => n end.
Definition t' (a: var) := match a with inl a => tgt_ fs a | inr (n,_) => n end.
(** final type of reified KAT expressions *)
Definition kat_expr := expr s' t'.
(** additional constructors:
- [e_inj n p] injects a Boolean expression [p], at type [n]
- [e_var i] produces a Kleene variable
- [p_var a] produces a predicat variable
*)
Definition e_inj n p: kat_expr n n := e_var (inr (n,p)).
Definition e_var i: kat_expr (src_ fs i) (tgt_ fs i) := e_var (inl i).
Definition p_var := @lsyntax.e_var Pred.
Section e.
(** * Interpretation of KAT reified expressions *)
(** we use the interpretations functions [syntax.expr] and
[lsyntax.expr], with the appropriate substitutions *)
Variable fp: forall n, Pred -> tst (f' n).
Definition eval: forall n m, kat_expr n m -> X (f' n) (f' m) :=
syntax.eval (fun a =>
match a return X (f' (s' a)) (f' (t' a)) with
| inl a => val (fs a)
| inr (n,p) => inj (lsyntax.eval (fp n) p)
end).
End e.
(** * Predicate variables of a KAT expression *)
Fixpoint vars {n m} (e: kat_expr n m): list Pred :=
match e with
| e_zer _ _
| e_top _ _
| e_one _ => []
| e_pls x y
| e_cap x y
| e_ldv x y
| e_rdv x y
| e_dot x y => union (vars x) (vars y)
| e_neg x
| e_itr x
| e_str x
| e_cnv x => vars x
| syntax.e_var (inr (_,x)) => lsyntax.vars x
| syntax.e_var _ => []
end.
(** index of an element in a list, as an ordinal.
Together with the list of all predicate variables indices appearing in a
reified term, this function will allow us to convert positive
indices to ordinal ones, as required byb [gregex]. *)
Fixpoint idx (x: Pred) (l: list Pred): option (ord (length l)) :=
match l with
| [] => None
| y::q =>
if eqb_pos x y then Some ord0 else
match idx x q with Some i => Some (ordS i) | None => None end
end.
(** * From reified KAT expressions to [gregex] *)
(** we interpret the expression in the [gregex] model,
mapping all Boolean expressions with positives variables
to their counterpart with ordinal variables *)
Definition to_gregex (l: list positive):
forall n m, kat_expr n m -> gregex (length l) (src_ fs) (tgt_ fs) n m :=
syntax.eval (fun a =>
match a return gregex _ (src_ fs) (tgt_ fs) (s' a) (t' a) with
| inl a => g_var a
| inr (n,p) => g_prd _ _
(* here we just map all predicate variable indices
into their ordinal counterpart *)
(lsyntax.eval (fun x =>
match idx x l with
| Some i => lsyntax.e_var i
| None => lsyntax.e_top: lsyntax.expr_ BL
end) p)
end).
(** correctness of the [idx] function *)
Lemma in_idx x l: In x l -> exists j, idx x l = Some j /\ nth j l xH = x.
Proof.
induction l. intros []. intro Hl. simpl idx. case eqb_spec.
intros <-. exists ord0. now split.
destruct Hl as [<-|Hl]. congruence.
intros _. apply IHl in Hl as [j [-> Hj]]. exists (ordS j). split. reflexivity.
destruct j. assumption.
Qed.
(** factorisation of the interpretation function, through [gregex]
since the type of expressions is slightly to big (it contains
residuals and converse, for instance), we have to check that the
expression does not use such constructions, whence the first
hypothesis. *)
Lemma to_gregex_eval {L: laws X} v n m e fp: e_level e << BKA -> vars e <== v ->
eval fp n m e ==
gregex.eval f' (fun n i => fp n (nth i v xH)) (fun i => val (fs i)) (to_gregex v n m e).
Proof.
induction e; simpl e_level; simpl (vars _); intros Hl Hv;
try discriminate_levels; simpl; rewrite ?union_app in Hv.
reflexivity.
symmetry. apply kat.inj_top.
apply cup_weq.
apply IHe1. solve_lower'. rewrite <- Hv. lattice.
apply IHe2. solve_lower'. rewrite <- Hv. lattice.
apply dot_weq.
apply IHe1. solve_lower'. rewrite <- Hv. lattice.
apply IHe2. solve_lower'. rewrite <- Hv. lattice.
apply itr_weq, IHe. solve_lower'. assumption.
rewrite kat.inj_top, <-str_itr. apply str_weq, IHe. solve_lower'. assumption.
destruct a as [a|[n p]]. reflexivity.
simpl. apply kat.inj_weq. clear Hl.
induction p; simpl; simpl (lsyntax.vars _) in Hv; rewrite ?union_app in Hv.
reflexivity.
reflexivity.
apply cup_weq.
apply IHp1. rewrite <-Hv. lattice.
apply IHp2. rewrite <-Hv. lattice.
apply cap_weq.
apply IHp1. rewrite <-Hv. lattice.
apply IHp2. rewrite <-Hv. lattice.
apply neg_weq, IHp. assumption.
simpl. destruct (in_idx a v) as [j [-> Hj]]. apply Hv; now left.
simpl. now rewrite Hj.
Qed.
(** as a corollary, we get the reification lemma
(The hypothesis that expressions do not use forbidden symbols will be easily
checked by reflection, dynamically.) *)
Corollary to_gregex_weq {L: laws X} n m e f fp:
e_level e + e_level f << BKA ->
(let v := vars (e_pls e f) in to_gregex v n m e == to_gregex v n m f) ->
eval fp n m e == eval fp n m f.
Proof.
intros Hl H. rewrite 2(to_gregex_eval (vars (e_pls e f)))
by (solve_lower' || simpl (vars _); rewrite union_app; lattice).
apply H, L.
Qed.
End s.
Arguments e_inj _ _ _ _%positive _%last.
Arguments e_var _ _ _ _%positive.
Arguments p_var _%positive.
(** Load ML reification modules *)
Declare ML Module "ra_common".
Declare ML Module "kat_reification".
|
library(tidyverse)
library(stringi)
dt <- readr::read_csv(
"inst/raw/brand_code.csv",
locale = locale(encoding = "cp932")
)
BrandCode <- dt %>%
dplyr::select(
"code" = "コード",
"name" = "銘柄名",
"category" = "市場\u30fb商品区分",
"indust17" = "17業種区分"
) %>%
dplyr::mutate(
name = stringi::stri_trans_nfkc(name)
)
usethis::use_data(BrandCode, overwrite = TRUE)
usethis::use_data(BrandCode, internal = TRUE, overwrite = TRUE)
|
=begin
[((<index-ja|URL:index-ja.html>))]
= Algebra::EuclidianRing
((*(G.C.D.計算モジュール)*))
((|divmod|)) から G.C.D(最大公約数)等を計算するモジュールです。
これは ((|Integer|)) や ((|Algebra::Polynomial|)) にインクルードされます。
== ファイル名:
* ((|euclidian-ring.rb|))
== メソッド:
--- gcd(other)
((|self|)) と ((|other|)) との最大公約数を返します。
--- gcd_all(other0 [, other1[, ...]])
((|self|)) と ((|other0|)), ((|other1|)),... との最大公約数を返します。
--- gcd_coeff(other)
((|self|)) と ((|other|)) との最大公約数と、それを表現する係数の
配列を返します。
例:
require "polynomial"
require "rational"
P = Algebra.Polynomial(Rational, "x")
x = P.var
f = (x + 2) * (x**2 - 1)**2
g = (x + 2)**2 * (x - 1)**3
gcd, a, b = f.gcd_coeff(g)
p gcd #=> 4x^3 - 12x + 8
p a #=> -x + 2
p b #=> x - 1
p gcd == a*f + b*g #=> true
--- gcd_ext(other)
((<gcd_coeff>)) と同じです。
--- gcd_coeff_all(other0 [, other1[, ...]])
((|self|)) と ((|other0|)), ((|other1|)),... との最大公約数と、それ
を表現する係数の配列を返します。
例:
require "polynomial"
require "rational"
P = Algebra.Polynomial(Rational, "x")
x = P.var
f = (x + 2) * (x**2 - 1)**2
g = (x + 2)**2 * (x - 1)**3
h = (x + 2) * (x + 1) * (x - 1)
gcd, a, b, c = f.gcd_coeff_all(g, h)
p gcd #=> -8x^2 - 8x + 16
p a #=> -x + 2
p b #=> x - 1
p c #=> -4
p gcd == a*f + b*g + c*h #=> true
--- gcd_ext_all(other)
((<gcd_coeff_all>)) と同じです。
--- lcm(b)
((|self|)) と ((|other|)) との最小公倍数を返します。
--- lcm_all(other0 [, other1[, ...]])
((|self|)) と ((|other0|)), ((|other1|)),... との最小公倍数を返します。
=end
|
/-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import topology.category.Top.opens
/-!
# The category of open neighborhoods of a point
Given an object `X` of the category `Top` of topological spaces and a point `x : X`, this file
builds the type `open_nhds x` of open neighborhoods of `x` in `X` and endows it with the partial
order given by inclusion and the corresponding category structure (as a full subcategory of the
poset category `set X`). This is used in `topology.sheaves.stalks` to build the stalk of a sheaf
at `x` as a limit over `open_nhds x`.
## Main declarations
Besides `open_nhds`, the main constructions here are:
* `inclusion (x : X)`: the obvious functor `open_nhds x ⥤ opens X`
* `functor_nhds`: An open map `f : X ⟶ Y` induces a functor `open_nhds x ⥤ open_nhds (f x)`
* `adjunction_nhds`: An open map `f : X ⟶ Y` induces an adjunction between `open_nhds x` and
`open_nhds (f x)`.
-/
open category_theory
open topological_space
open opposite
universe u
variables {X Y : Top.{u}} (f : X ⟶ Y)
namespace topological_space
/-- The type of open neighbourhoods of a point `x` in a (bundled) topological space. -/
def open_nhds (x : X) := { U : opens X // x ∈ U }
namespace open_nhds
instance (x : X) : partial_order (open_nhds x) :=
{ le := λ U V, U.1 ≤ V.1,
le_refl := λ _, le_refl _,
le_trans := λ _ _ _, le_trans,
le_antisymm := λ _ _ i j, subtype.eq $ le_antisymm i j }
instance (x : X) : lattice (open_nhds x) :=
{ inf := λ U V, ⟨U.1 ⊓ V.1, ⟨U.2, V.2⟩⟩,
le_inf := λ U V W, @le_inf _ _ U.1.1 V.1.1 W.1.1,
inf_le_left := λ U V, @inf_le_left _ _ U.1.1 V.1.1,
inf_le_right := λ U V, @inf_le_right _ _ U.1.1 V.1.1,
sup := λ U V, ⟨U.1 ⊔ V.1, V.1.1.mem_union_left U.2⟩,
sup_le := λ U V W, @sup_le _ _ U.1.1 V.1.1 W.1.1,
le_sup_left := λ U V, @le_sup_left _ _ U.1.1 V.1.1,
le_sup_right := λ U V, @le_sup_right _ _ U.1.1 V.1.1,
..open_nhds.partial_order x }
instance (x : X) : order_top (open_nhds x) :=
{ top := ⟨⊤, trivial⟩,
le_top := λ _, le_top }
instance (x : X) : inhabited (open_nhds x) := ⟨⊤⟩
instance open_nhds_category (x : X) : category.{u} (open_nhds x) :=
by {unfold open_nhds, apply_instance}
instance opens_nhds_hom_has_coe_to_fun {x : X} {U V : open_nhds x} :
has_coe_to_fun (U ⟶ V) (λ _, U.1 → V.1) :=
⟨λ f x, ⟨x, f.le x.2⟩⟩
/--
The inclusion `U ⊓ V ⟶ U` as a morphism in the category of open sets.
-/
def inf_le_left {x : X} (U V : open_nhds x) : U ⊓ V ⟶ U :=
hom_of_le inf_le_left
/--
The inclusion `U ⊓ V ⟶ V` as a morphism in the category of open sets.
-/
def inf_le_right {x : X} (U V : open_nhds x) : U ⊓ V ⟶ V :=
hom_of_le inf_le_right
/-- The inclusion functor from open neighbourhoods of `x`
to open sets in the ambient topological space. -/
def inclusion (x : X) : open_nhds x ⥤ opens X :=
full_subcategory_inclusion _
@[simp] lemma inclusion_obj (x : X) (U) (p) : (inclusion x).obj ⟨U,p⟩ = U := rfl
lemma open_embedding {x : X} (U : open_nhds x) : open_embedding (U.1.inclusion) :=
U.1.open_embedding
def map (x : X) : open_nhds (f x) ⥤ open_nhds x :=
{ obj := λ U, ⟨(opens.map f).obj U.1, by tidy⟩,
map := λ U V i, (opens.map f).map i }
@[simp] lemma map_obj (x : X) (U) (q) : (map f x).obj ⟨U, q⟩ = ⟨(opens.map f).obj U, by tidy⟩ :=
rfl
@[simp] lemma map_id_obj (x : X) (U) : (map (𝟙 X) x).obj U = U :=
by tidy
@[simp] lemma map_id_obj' (x : X) (U) (p) (q) : (map (𝟙 X) x).obj ⟨⟨U, p⟩, q⟩ = ⟨⟨U, p⟩, q⟩ :=
rfl
@[simp] lemma map_id_obj_unop (x : X) (U : (open_nhds x)ᵒᵖ) : (map (𝟙 X) x).obj (unop U) = unop U :=
by simp
@[simp] lemma op_map_id_obj (x : X) (U : (open_nhds x)ᵒᵖ) : (map (𝟙 X) x).op.obj U = U :=
by simp
/-- `opens.map f` and `open_nhds.map f` form a commuting square (up to natural isomorphism)
with the inclusion functors into `opens X`. -/
def inclusion_map_iso (x : X) : inclusion (f x) ⋙ opens.map f ≅ map f x ⋙ inclusion x :=
nat_iso.of_components
(λ U, begin split, exact 𝟙 _, exact 𝟙 _ end)
(by tidy)
@[simp] lemma inclusion_map_iso_hom (x : X) : (inclusion_map_iso f x).hom = 𝟙 _ := rfl
@[simp] lemma inclusion_map_iso_inv (x : X) : (inclusion_map_iso f x).inv = 𝟙 _ := rfl
end open_nhds
end topological_space
namespace is_open_map
open topological_space
variables {f}
/--
An open map `f : X ⟶ Y` induces a functor `open_nhds x ⥤ open_nhds (f x)`.
-/
@[simps]
def functor_nhds (h : is_open_map f) (x : X) :
open_nhds x ⥤ open_nhds (f x) :=
{ obj := λ U, ⟨h.functor.obj U.1, ⟨x, U.2, rfl⟩⟩,
map := λ U V i, h.functor.map i }
/--
An open map `f : X ⟶ Y` induces an adjunction between `open_nhds x` and `open_nhds (f x)`.
-/
def adjunction_nhds (h : is_open_map f) (x : X) :
is_open_map.functor_nhds h x ⊣ open_nhds.map f x :=
adjunction.mk_of_unit_counit
{ unit := { app := λ U, hom_of_le $ λ x hxU, ⟨x, hxU, rfl⟩ },
counit := { app := λ V, hom_of_le $ λ y ⟨x, hfxV, hxy⟩, hxy ▸ hfxV } }
end is_open_map
|
subroutine prep_board_dv(ar,md)
character*8 ar,md
common/brd_dv/xbr1(2),xbr2(2),dxbr1(2),dxbr2(2),&
ybr1(2),ybr2(2),dybr1(2),dybr2(2),&
zbr1(2),zbr2(2),dzbr1(2),dzbr2(2),amp(4)
open(1,file='../../../DATA/'//ar//'/'//md//'/anomaly.dat')
read(1,*)
read(1,*)
read(1,*)amp(1),amp(3)
read(1,*)xbr1(1),xbr2(1),dxbr1(1),dxbr2(1)
read(1,*)ybr1(1),ybr2(1),dybr1(1),dybr2(1)
read(1,*)zbr1(1),zbr2(1),dzbr1(1),dzbr2(1)
read(1,*)amp(2),amp(4)
read(1,*)xbr1(2),xbr2(2),dxbr1(2),dxbr2(2)
read(1,*)ybr1(2),ybr2(2),dybr1(2),dybr2(2)
read(1,*)zbr1(2),zbr2(2),dzbr1(2),dzbr2(2)
close(1)
write(*,*)' amp1=',amp(1),' amp2=',amp(2)
return
end |
State Before: A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
⊢ bernoulliPowerSeries A * (exp A - 1) = X State After: case h
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(coeff A n) (bernoulliPowerSeries A * (exp A - 1)) = ↑(coeff A n) X Tactic: ext n State Before: case h
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(coeff A n) (bernoulliPowerSeries A * (exp A - 1)) = ↑(coeff A n) X State After: case h.zero
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
⊢ ↑(coeff A zero) (bernoulliPowerSeries A * (exp A - 1)) = ↑(coeff A zero) X
case h.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(coeff A (succ n)) (bernoulliPowerSeries A * (exp A - 1)) = ↑(coeff A (succ n)) X Tactic: cases' n with n n State Before: case h.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(coeff A (succ n)) (bernoulliPowerSeries A * (exp A - 1)) = ↑(coeff A (succ n)) X State After: case h.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(algebraMap ℚ A) (bernoulli (n + 1) / ((↑n + 1) * ↑(Nat.add n 0)!)) * (↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A) (∑ x in antidiagonal n, bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
if succ n = 1 then 1 else 0 Tactic: simp only [bernoulliPowerSeries, coeff_mul, coeff_X, sum_antidiagonal_succ', one_div, coeff_mk,
coeff_one, coeff_exp, LinearMap.map_sub, factorial, if_pos, cast_succ, cast_one, cast_mul,
sub_zero, RingHom.map_one, add_eq_zero_iff, if_false, _root_.inv_one, zero_add, one_ne_zero,
MulZeroClass.mul_zero, and_false_iff, sub_self, ← RingHom.map_mul, ← map_sum] State Before: case h.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(algebraMap ℚ A) (bernoulli (n + 1) / ((↑n + 1) * ↑(Nat.add n 0)!)) * (↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A) (∑ x in antidiagonal n, bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
if succ n = 1 then 1 else 0 State After: case h.succ.zero
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
⊢ ↑(algebraMap ℚ A) (bernoulli (zero + 1) / ((↑zero + 1) * ↑(Nat.add zero 0)!)) * (↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal zero, bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
if succ zero = 1 then 1 else 0
case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(algebraMap ℚ A) (bernoulli (succ n + 1) / ((↑(succ n) + 1) * ↑(Nat.add (succ n) 0)!)) *
(↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
if succ (succ n) = 1 then 1 else 0 Tactic: cases' n with n State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(algebraMap ℚ A) (bernoulli (succ n + 1) / ((↑(succ n) + 1) * ↑(Nat.add (succ n) 0)!)) *
(↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
if succ (succ n) = 1 then 1 else 0 State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(algebraMap ℚ A) (bernoulli (succ n + 1) / ((↑(succ n) + 1) * ↑(Nat.add (succ n) 0)!)) *
(↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
0 Tactic: rw [if_neg n.succ_succ_ne_one] State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
⊢ ↑(algebraMap ℚ A) (bernoulli (succ n + 1) / ((↑(succ n) + 1) * ↑(Nat.add (succ n) 0)!)) *
(↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
0 State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
⊢ ↑(algebraMap ℚ A) (bernoulli (succ n + 1) / ((↑(succ n) + 1) * ↑(Nat.add (succ n) 0)!)) *
(↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
0 Tactic: have hfact : ∀ m, (m ! : ℚ) ≠ 0 := fun m => by exact_mod_cast factorial_ne_zero m State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
⊢ ↑(algebraMap ℚ A) (bernoulli (succ n + 1) / ((↑(succ n) + 1) * ↑(Nat.add (succ n) 0)!)) *
(↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
0 State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
⊢ ↑(algebraMap ℚ A) (bernoulli (succ n + 1) / ((↑(succ n) + 1) * ↑(Nat.add (succ n) 0)!)) *
(↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
0 Tactic: have hite2 : ite (n.succ = 0) 1 0 = (0 : ℚ) := if_neg n.succ_ne_zero State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
⊢ ↑(algebraMap ℚ A) (bernoulli (succ n + 1) / ((↑(succ n) + 1) * ↑(Nat.add (succ n) 0)!)) *
(↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
0 State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
⊢ ↑(algebraMap ℚ A) (∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹) = 0 Tactic: simp only [CharP.cast_eq_zero, zero_add, inv_one, map_one, sub_self, mul_zero, add_eq] State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
⊢ ↑(algebraMap ℚ A) (∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹) = 0 State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
⊢ ↑(algebraMap ℚ A) (∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹) =
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), ↑(Nat.choose (x.fst + x.snd) x.snd) / (↑x.snd + 1) * bernoulli x.fst / ↑(succ n)!) Tactic: rw [← map_zero (algebraMap ℚ A), ← zero_div (n.succ ! : ℚ), ← hite2, ← bernoulli_spec', sum_div] State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
⊢ ↑(algebraMap ℚ A) (∑ x in antidiagonal (succ n), bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹) =
↑(algebraMap ℚ A)
(∑ x in antidiagonal (succ n), ↑(Nat.choose (x.fst + x.snd) x.snd) / (↑x.snd + 1) * bernoulli x.fst / ↑(succ n)!) State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x ∈ antidiagonal (succ n)
⊢ bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹ * ↑(succ n)! =
↑(Nat.choose (x.fst + x.snd) x.snd) / (↑x.snd + 1) * bernoulli x.fst Tactic: refine' congr_arg (algebraMap ℚ A) (sum_congr rfl fun x h => eq_div_of_mul_eq (hfact n.succ) _) State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x ∈ antidiagonal (succ n)
⊢ bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹ * ↑(succ n)! =
↑(Nat.choose (x.fst + x.snd) x.snd) / (↑x.snd + 1) * bernoulli x.fst State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
⊢ bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹ * ↑(succ n)! =
↑(Nat.choose (x.fst + x.snd) x.snd) / (↑x.snd + 1) * bernoulli x.fst Tactic: rw [mem_antidiagonal] at h State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
⊢ bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹ * ↑(succ n)! =
↑(Nat.choose (x.fst + x.snd) x.snd) / (↑x.snd + 1) * bernoulli x.fst State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹ * ↑(succ n)! =
↑(Nat.choose (x.fst + x.snd) x.snd) / (↑x.snd + 1) * bernoulli x.fst Tactic: have hj : (x.2 + 1 : ℚ) ≠ 0 := by norm_cast; exact succ_ne_zero _ State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹ * ↑(succ n)! =
↑(Nat.choose (x.fst + x.snd) x.snd) / (↑x.snd + 1) * bernoulli x.fst State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹ * ↑(x.fst + x.snd)! =
↑(x.fst + x.snd)! / ↑(x.fst ! * x.snd !) / (↑x.snd + 1) * bernoulli x.fst Tactic: rw [← h, add_choose, cast_div_charZero (factorial_mul_factorial_dvd_factorial_add _ _)] State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(x.snd + 0)!)⁻¹ * ↑(x.fst + x.snd)! =
↑(x.fst + x.snd)! / ↑(x.fst ! * x.snd !) / (↑x.snd + 1) * bernoulli x.fst State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ ↑x.snd ! * (↑x.snd + 1) = (↑x.snd + 1) * ↑x.snd ! ∨ bernoulli x.fst = 0 Tactic: field_simp [mul_ne_zero hj (hfact x.2), hfact x.1, mul_comm _ (bernoulli x.1), mul_assoc,
Nat.factorial_ne_zero, hj] State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ ↑x.snd ! * (↑x.snd + 1) = (↑x.snd + 1) * ↑x.snd ! ∨ bernoulli x.fst = 0 State After: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ ↑x.snd ! * (↑x.snd + 1) = (↑x.snd + 1) * ↑x.snd ! ∨ bernoulli x.fst = 0 Tactic: simp only State Before: case h.succ.succ
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ ↑x.snd ! * (↑x.snd + 1) = (↑x.snd + 1) * ↑x.snd ! ∨ bernoulli x.fst = 0 State After: case h.succ.succ.h
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ ↑x.snd ! * (↑x.snd + 1) = (↑x.snd + 1) * ↑x.snd ! Tactic: left State Before: case h.succ.succ.h
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
hj : ↑x.snd + 1 ≠ 0
⊢ ↑x.snd ! * (↑x.snd + 1) = (↑x.snd + 1) * ↑x.snd ! State After: no goals Tactic: ring State Before: case h.zero
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
⊢ ↑(coeff A zero) (bernoulliPowerSeries A * (exp A - 1)) = ↑(coeff A zero) X State After: no goals Tactic: simp State Before: case h.succ.zero
A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
⊢ ↑(algebraMap ℚ A) (bernoulli (zero + 1) / ((↑zero + 1) * ↑(Nat.add zero 0)!)) * (↑(algebraMap ℚ A) (↑0 + 1)⁻¹ - 1) +
↑(algebraMap ℚ A)
(∑ x in antidiagonal zero, bernoulli x.fst / ↑x.fst ! * ((↑x.snd + 1) * ↑(Nat.add x.snd 0)!)⁻¹) =
if succ zero = 1 then 1 else 0 State After: no goals Tactic: simp State Before: A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n m : ℕ
⊢ ↑m ! ≠ 0 State After: no goals Tactic: exact_mod_cast factorial_ne_zero m State Before: A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
⊢ ↑x.snd + 1 ≠ 0 State After: A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
⊢ ¬x.snd + 1 = 0 Tactic: norm_cast State Before: A : Type u_1
inst✝¹ : CommRing A
inst✝ : Algebra ℚ A
n : ℕ
hfact : ∀ (m : ℕ), ↑m ! ≠ 0
hite2 : (if succ n = 0 then 1 else 0) = 0
x : ℕ × ℕ
h : x.fst + x.snd = succ n
⊢ ¬x.snd + 1 = 0 State After: no goals Tactic: exact succ_ne_zero _ |
is_valid(x, encoding::Symbol = :none) = is_valid(x, Val(encoding))
is_valid(x, ::Val) = true
function binarize(x::Vector{T}, d = length(x); binarization = :one_hot) where {T <: Number}
return collect(Iterators.flatten(map(i -> binarize(i, d; binarization), x)))
end
function binarize(x::T, domain_size::Int; binarization = :one_hot) where {T <: Number}
return binarize(x, domain(0:(domain_size - 1)), Val(binarization))
end
function binarize(x::T, d::D; binarization=:one_hot
) where {T <: Number, D <: DiscreteDomain{T}}
return binarize(x, d, Val(binarization))
end
function binarize(x::Vector{T}, d::Vector{D}; binarization=:one_hot
) where {T <: Number, D <: DiscreteDomain{T}}
return collect(Iterators.flatten(map(elt -> binarize(elt[1], elt[2]; binarization), zip(x,d))))
end
function debinarize(x; binarization = :one_hot)
ds::Int = if binarization == :domain_wall
(-1 + sqrt(1 + 4 * length(x))) ÷ 2 + 1
else
sqrt(length(x))
end
return debinarize(x, ds; binarization)
end
function debinarize(x, domain_size::Int; binarization = :one_hot)
return debinarize(x, domain(0:(domain_size - 1)); binarization)
end
function debinarize(x, domains_sizes::Vector{Int}; binarization = :one_hot)
domains = map(ds -> domain(0:(ds - 1)), domains_sizes)
return debinarize(x, domains; binarization)
end
function debinarize(x, d::D; binarization = :one_hot) where {D <: DiscreteDomain}
k::Int = length(x) / length(d)
if binarization == :domain_wall
typeof(d) <: RangeDomain && first(get_domain(d)) == 0 && (k += 1)
end
domains = fill(d, k)
return debinarize(x, domains; binarization)
end
function debinarize(x, domains::Vector{D}; binarization = :one_hot
) where {D <: DiscreteDomain}
return debinarize(x, domains, Val(binarization))
end
|
[STATEMENT]
lemma all_zeroes_replicate: "length_sum_set r 0 = {replicate r 0}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. length_sum_set r 0 = {replicate r 0}
[PROOF STEP]
by (auto simp: length_sum_set_def replicate_eqI) |
\chapter{To verify the truth table for NOR gate}
\section{Apparatus}
%\label{sec:objectives}
\begin{itemize}
\tightlist
\item Kit for realization of gates
\item Connecting Leads
\end{itemize}
\section{Theory}
This is a NOT-OR gate which is equal to an OR gate followed by a NOT gate. The outputs of all NOR gates are low if any of the inputs are high. The symbol is an OR gate with a small circle on the output. The small circle represents inversion.
\begin{figure}[h]
\centering
\includegraphics{img/exp5/1}
\caption{Symbol for NOR gate}
\label{fig:5:1}
\end{figure}
\begin{figure}[h]
\centering
\includegraphics{img/exp5/2}
\caption{Truth Table for NOR gate}
\label{fig:5:2}
\end{figure}
A simple 2-input logic NOR gate can be constructed using RTL (Resistor-transistor-logic) switches connected together as shown below with the inputs connected directly to the transistor bases. Both transistors must be cut-off or “OFF” for an output at Q.
\begin{figure}[h]
\centering
\includegraphics{img/exp5/3}
\caption{Circut for making NOR gate}
\label{fig:5:3}
\end{figure}
\section{Procedure}
\subsubsection{Simulator 1}
\begin{itemize}
\tightlist
\item Connect the supply(+5V) to the circuit.
\item Press the switches for inputs "A" and "B".
\item The bulb glows if both the switches are OFF else it won't glow.
\item Repeat step-2 and step-3 for all state of inputs.
\end{itemize}
\subsubsection{Simulator 2}
\begin{itemize}
\tightlist
\item Enter the Boolean input "A" and "B".
\item Enter the Boolean output for your corresponding inputs.
\item Click on "Check" Button to verify your output.
\item Click "Print" if you want to get print out of Truth Table.
\end{itemize}
\section{Observations}
\begin{figure}[h]
\centering
\includegraphics[width=0.9\linewidth]{img/exp5/4}
\caption{}
\label{fig:5:4}
\end{figure}
\begin{figure}[h]
\centering
\includegraphics[width=0.9\linewidth]{img/exp5/5}
\caption{}
\label{fig:5:5}
\end{figure}
\begin{figure}[h]
\centering
\includegraphics[width=0.9\linewidth]{img/exp5/6}
\caption{}
\label{fig:5:6}
\end{figure}
\begin{figure}[h]
\centering
\includegraphics[width=0.9\linewidth]{img/exp5/7}
\caption{}
\label{fig:5:7}
\end{figure}
\section{Conclusion}
NOR gate basically negates the results of OR gate . The output is low when both the inputs are high or when even one of the input is low. Iff both the inputs are low, we get a high output.
\section{Precautions}
\begin{enumerate}
\tightlist
\item Make the connections when power supply is OFF.
\item Ensure that the connections are tight.
\item Change the status of inputs only when power supply is OFF.
\end{enumerate} |
import numpy as np
import torch
import torch.nn as nn
import torchvision.transforms as transforms
class NormalizeInverse(transforms.Normalize):
'''
Undoes the normalization and returns the reconstructed images in the input domain.
'''
def __init__(self, mean, std):
mean = torch.as_tensor(mean)
std = torch.as_tensor(std)
std_inv = 1 / (std + 1e-7)
mean_inv = -mean * std_inv
super().__init__(mean=mean_inv, std=std_inv)
def __call__(self, tensor):
return super().__call__(tensor.clone())
class ToNumpyImage(object):
def __init__(self):
pass
def __call__(self, x):
assert len(x.shape) == 3
x = x.permute(1,2,0)
x = (x *255).numpy()
x = x.astype(np.uint8)
return x
def image_transforms(in_channels=3):
_image_transforms = [
transforms.ToTensor(),
transforms.Normalize((0.5,)*in_channels, (0.5,)*in_channels),
]
return transforms.Compose(_image_transforms)
def image_transforms_reverse(in_channels=3):
_image_transforms_reverse = [
NormalizeInverse((0.5,)*in_channels, (0.5,)*in_channels),
# transforms.ToPILImage(mode='RGB'),
ToNumpyImage(),
]
return transforms.Compose(_image_transforms_reverse)
|
```python
import sympy as sp
import pandas as pd
from operator import mul
from functools import reduce
```
```python
def print_derivatives(nodes, *args):
index = nodes
cols = ['f' + i * '\'' for i in range(len(derivatives_per_node[0]))]
return pd.DataFrame(derivatives_per_node, index=index, columns=cols)
```
```python
def calculate_div_diffs(nodes, *args, max_order=None):
derivatives_per_node = list(zip(*args))
max_order_per_node = [len([j for j in i if j != None]) for i in derivatives_per_node]
if max_order == None:
max_order = sum(max_order_per_node)
nodes_with_order = [nodes[i] for i in range(len(nodes)) for j in range(max_order_per_node[i])]
values_with_order = [args[0][i] for i in range(len(nodes)) for j in range(max_order_per_node[i])]
node_to_pos = {n: p for p, n in enumerate(nodes)}
nwo_to_pos = {i: node_to_pos[nodes_with_order[i]] for i in range(len(nodes_with_order))}
diffs = [values_with_order]
for order in range(max_order - 1):
current_diffs = []
for i in range(1, len(nodes_with_order) - order):
if nodes_with_order[i + order] == nodes_with_order[i - 1]:
current_diffs.append(
(derivatives_per_node[nwo_to_pos[i]][order + 1]) /
(reduce(mul, [1] + [j for j in range(1, order + 1)]))
)
else:
p = diffs[-1][i] - diffs[-1][i-1]
current_diffs.append((diffs[-1][i] - diffs[-1][i-1]) / (nodes_with_order[i + order] - nodes_with_order[i-1]))
if len(current_diffs) == 0:
break
diffs.append(current_diffs)
return diffs
```
```python
def print_diffs(diffs):
rows = 2 * len(diffs[0]) - 1
for r in range(rows):
row = '\t' if r % 2 == 1 else ''
for i in range(r % 2, min(rows - r, min(r + 1, len(diffs))), 2):
row += f'{float(diffs[i][(r - i) // 2]):.3f}\t\t'
print(row[:-2])
```
```python
nodes = [-1, 1, 2, 3]
fvals = [7, -11, -5, 43]
dfvals = [None, 5, 1, None]
ddfvals = [None, -22, None, None]
```
```python
derivatives_per_node = list(zip(fvals, dfvals, ddfvals))
max_order_per_node = [len([j for j in i if j != None]) for i in derivatives_per_node]
nodes_with_order = [nodes[i] for i in range(len(nodes)) for j in range(max_order_per_node[i])]
```
```python
print_derivatives(nodes, fvals, dfvals, ddfvals)
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>f</th>
<th>f'</th>
<th>f''</th>
</tr>
</thead>
<tbody>
<tr>
<th>-1</th>
<td>7</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<th>1</th>
<td>-11</td>
<td>5.0</td>
<td>-22.0</td>
</tr>
<tr>
<th>2</th>
<td>-5</td>
<td>1.0</td>
<td>NaN</td>
</tr>
<tr>
<th>3</th>
<td>43</td>
<td>NaN</td>
<td>NaN</td>
</tr>
</tbody>
</table>
</div>
```python
dds = calculate_div_diffs(nodes, fvals, dfvals, ddfvals)
```
```python
print_diffs(dds)
```
7.000
-9.000
-11.000 7.000
5.000 -14.500
-11.000 -22.000 12.500
5.000 23.000 -13.833
-11.000 1.000 -29.000 9.083
6.000 -6.000 22.500
-5.000 -5.000 16.000
1.000 26.000
-5.000 47.000
48.000
43.000
```python
x = sp.symbols('x')
polynom = 0
mult = 1
for i in range(len(dds)):
polynom += dds[i][0] * mult
mult *= x - nodes_with_order[i]
```
```python
sp.expand(polynom)
```
$\displaystyle 9.08333333333333 x^{6} - 68.3333333333333 x^{5} + 176.833333333333 x^{4} - 149.333333333333 x^{3} - 87.9166666666667 x^{2} + 208.666666666667 x - 100.0$
```python
polynom_test = []
dp = polynom
for i in range(len(derivatives_per_node[0])):
f_i = []
for j in range(len(nodes)):
if derivatives_per_node[j][i] != None:
f_i.append(dp.evalf(subs={x: nodes[i]}))
else:
f_i.append(None)
dp = sp.diff(dp)
polynom_test.append(f_i)
```
```python
print_derivatives(nodes, *polynom_test)
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>f</th>
<th>f'</th>
<th>f''</th>
</tr>
</thead>
<tbody>
<tr>
<th>-1</th>
<td>7</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<th>1</th>
<td>-11</td>
<td>5.0</td>
<td>-22.0</td>
</tr>
<tr>
<th>2</th>
<td>-5</td>
<td>1.0</td>
<td>NaN</td>
</tr>
<tr>
<th>3</th>
<td>43</td>
<td>NaN</td>
<td>NaN</td>
</tr>
</tbody>
</table>
</div>
|
TabModelData <- read.csv("~/GitHub/RAnalyses/TabModelData.csv")
View(TabModelData)
df <- TabModelData
TabModelData <- NULL
TabModelData <- NULL
df$DATE_VALUE <- NULL
df$RECORD <- NULL
df$LAST_NAME <- NULL
df$ADDRESS_LINE_1
df$ADDRESS_LINE_1 <- NULL
df$STATE_CODE <- NULL
df$ZIP <- NULL
df$MINSALEDATE <- NULL
df$LASTTABDATE <- NULL
summary(df)
df$REWARDS_CUSTOMER <- factor(df$REWARDS_CUSTOMER)
train.y <- df$PURCHASED_FIRST_15
collist <- c('MALES_IN_HOUSHOLD','REWARDS_CUSTOMER',
'DAYS_AS_CUSTOMER','TOTAL_TRANSACTIONS','TOTAL_SPEND',
'DAYS_SINCE_PURCHASE')
train.x <- df[, collist]
train.x$MALES_IN_HOUSHOLD <- scale(train.x$MALES_IN_HOUSHOLD)
train.x$FEMALES_IN_HOUSHOLD <-NULL
train.x$DAYS_AS_CUSTOMER <- scale(train.x$DAYS_AS_CUSTOMER)
train.x$TOTAL_TRANSACTIONS <- scale(train.x$TOTAL_TRANSACTIONS)
train.x$REW_TRANSACTIONS <- NULL
train.x$TOTAL_SPEND <- scale(train.x$TOTAL_SPEND)
train.x$DAYS_SINCE_PURCHASE <- scale(train.x$DAYS_SINCE_PURCHASE)
summary(train.x)
library(keras)
model <- keras_model_sequential()
model %>%
layer_dense(units = 12, activation = 'relu', input_shape = c(6)) %>%
layer_dense(units = 24, activation = 'relu') %>%
layer_dropout(rate=0.8) %>%
layer_dense(units = 36, activation = 'relu') %>%
layer_dropout(rate=0.8) %>%
layer_dense(units = 18, activation = 'relu') %>%
layer_dropout(rate=0.8) %>%
layer_dense(units = 6, activation = 'relu') %>%
layer_dense(units = 2, activation = 'softmax')
summary(model)
model %>% compile(
loss = 'binary_crossentropy',
optimizer = 'adadelta',
metrics = c('accuracy')
)
trainX<- as.matrix(train.x)
trainY <- to_categorical(as.matrix(train.y), num_classes = 2)
history <- model %>% fit(x = trainX, y = trainY,
epochs = 10, batch_size = 128,
validation_split = 0.4,
verbose = 1,
shuffle = T
)
plot(history)
# Plot the model loss
plot(history$metrics$loss, main="Model Loss", xlab = "epoch", ylab="loss", col="blue", type="l")
lines(history$metrics$val_loss, col="green")
legend("topright", c("train","test"), col=c("blue", "green"), lty=c(1,1))
# Plot the model accuracy
plot(history$metrics$acc, main="Model Accuracy", xlab = "epoch", ylab="accuracy", col="blue", type="l")
lines(history$metrics$val_acc, col="green")
legend("bottomright", c("train","test"), col=c("blue", "green"), lty=c(1,1))
|
Formal statement is: lemma complex_exp_exists: "\<exists>a r. z = complex_of_real r * exp a" Informal statement is: Every complex number $z$ can be written as $r e^a$ for some real number $r$ and some complex number $a$. |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. #
# #
# Date: 25-11-2020 #
# Author(s): Vincenzo Lomonaco, Lorenzo Pellegrini #
# E-mail: [email protected] #
# Website: www.continualai.org #
################################################################################
""" This module handles all the functionalities related to the logging of
Avalanche experiments using Weights & Biases. """
from PIL.Image import Image
from numpy import array
from torch import Tensor
from matplotlib.pyplot import Figure
from avalanche.evaluation.metric_results import AlternativeValues, \
MetricValue, TensorImage
from avalanche.logging import StrategyLogger
import numpy as np
class WandBLogger(StrategyLogger):
"""
The `WandBLogger` provides an easy integration with
Weights & Biases logging. Each monitored metric is automatically
logged to a dedicated Weights & Biases project dashboard.
"""
def __init__(self, project_name: str = "Avalanche",
run_name: str = "Avalanche Test", params: dict = None):
"""
Creates an instance of the `WandBLogger`.
:param project_name: Name of the W&B project.:
:param run_name: Name of the W&B run.:
:param params: All arguments for wandb.init() function call.
Visit https://docs.wandb.ai/ref/python/init to learn about all
wand.init() parameters.:
"""
super().__init__()
self.import_wandb()
self.params = params
self.project_name = project_name
self.run_name = run_name
self.args_parse()
self.before_run()
def import_wandb(self):
try:
import wandb
except ImportError:
raise ImportError(
'Please run "pip install wandb" to install wandb')
self.wandb = wandb
def args_parse(self):
self.init_kwargs = {"project": self.project_name, "name": self.run_name}
if self.params:
self.init_kwargs.update(self.params)
def before_run(self):
if self.wandb is None:
self.import_wandb()
if self.init_kwargs:
self.wandb.init(**self.init_kwargs)
else:
self.wandb.init()
def log_metric(self, metric_value: MetricValue, callback: str):
super().log_metric(metric_value, callback)
name = metric_value.name
value = metric_value.value
if isinstance(value, AlternativeValues):
value = value.best_supported_value(Image, Tensor, TensorImage,
Figure, float, int,
self.wandb.viz.CustomChart)
if not isinstance(value, (Image, Tensor, Figure, float, int,
self.wandb.viz.CustomChart)):
# Unsupported type
return
if isinstance(value, Image):
self.wandb.log({name: self.wandb.Image(value)})
elif isinstance(value, Tensor):
value = np.histogram(value.view(-1).numpy())
self.wandb.log({name: self.wandb.Histogram(np_histogram=value)})
elif isinstance(value, (float, int, Figure,
self.wandb.viz.CustomChart)):
self.wandb.log({name: value})
elif isinstance(value, TensorImage):
self.wandb.log({name: self.wandb.Image(array(value))})
__all__ = [
'WandBLogger'
]
|
Few markets have more options to choose from than today's home audio system and SmartTV industries. At Nerds on Call, we can help design the ideal home audio system.
Don't take chances on unknown home audio systems that may not "play nice together". Nerds on Call has done the research for you with companies you can trust and the expertise to optimize all of your systems to work together seamlessly.
The Sonos Wireless HiFi System delivers all the music on earth, in every room, with warm, full-bodies sound that's crystal clear at any volume. Sonos home audio systems can fill your home with music by combining HiFi sound and rock-solid wireless in a smart system that is easy to set-up, control and expand.
Sonos lets you stream from any source to any room. Enjoy access to different music sources from one app combined with complete multi-room capabilities so you can listen to your entire world of music in every room of your home. |
Require Import Raft.
Section LeaderSublogInterface.
Context {orig_base_params : BaseParams}.
Context {one_node_params : OneNodeParams orig_base_params}.
Context {raft_params : RaftParams orig_base_params}.
Definition leader_sublog_host_invariant (net : network) :=
forall leader e h,
type (nwState net leader) = Leader ->
In e (log (nwState net h)) ->
eTerm e = currentTerm (nwState net leader) ->
In e (log (nwState net leader)).
Definition leader_sublog_nw_invariant (net : network) :=
forall leader p t leaderId prevLogIndex prevLogTerm entries leaderCommit e,
type (nwState net leader) = Leader ->
In p (nwPackets net) ->
pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm
entries leaderCommit ->
In e entries ->
eTerm e = currentTerm (nwState net leader) ->
In e (log (nwState net leader)).
Definition leader_sublog_invariant (net : network) :=
leader_sublog_host_invariant net /\
leader_sublog_nw_invariant net.
Class leader_sublog_interface : Prop :=
{
leader_sublog_invariant_invariant :
forall net,
raft_intermediate_reachable net ->
leader_sublog_invariant net
}.
End LeaderSublogInterface. |
Require Import Reals Psatz.
From Bignums Require Import BigZ BigQ.
From Flocq Require Import Core.Raux Core.Defs Core.Digits.
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq.
From mathcomp Require Import choice finfun fintype matrix ssralg bigop.
From CoqEAL Require Import hrel.
From CoqEAL Require Import param refinements seqmx seqmx_complements.
From Interval Require Import Real.Xreal.
From Interval Require Import Float.Basic.
From Interval Require Import Float.Specific_ops.
Require Import mathcomp.analysis.Rstruct libValidSDP.misc.
Require Import libValidSDP.coqinterval_infnan libValidSDP.zulp.
Require Import iteri_ord libValidSDP.float_infnan_spec libValidSDP.real_matrix.
Require Import libValidSDP.cholesky libValidSDP.cholesky_infnan.
(** * Application: program for Cholesky decomposition *)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Open Scope R_scope.
Open Scope ring_scope.
Delimit Scope ring_scope with Ri.
Delimit Scope R_scope with Re.
Import Refinements.Op.
(** ** Part 0: Definition of operational type classes *)
(** for cholesky *)
Class sqrt_of T := sqrt_op : T -> T.
Class dotmulB0_of A I B :=
dotmulB0_op : forall n : nat, I n -> A -> B 1%nat n -> B 1%nat n -> A.
(** for cholesky-based tactic, including up/d(ow)n-rounded operations *)
Class addup_class B := addup : B -> B -> B.
Class mulup_class B := mulup : B -> B -> B.
Class divup_class B := divup : B -> B -> B.
Class nat2Fup_class B := nat2Fup : nat -> B.
Class subdn_class B := subdn : B -> B -> B.
(** ** Part 1: Generic programs *)
Section generic_cholesky.
(** *** 1.1 Cholesky *)
Context {T : Type} {ord : nat -> Type} {mx : Type -> nat -> nat -> Type}.
Context `{!zero_of T, !one_of T, !add_of T, !opp_of T, !mul_of T, !div_of T, !sqrt_of T}.
Context `{!fun_of_of T ord (mx T), !row_of ord (mx T), !store_of T ord (mx T), !dotmulB0_of T ord (mx T)}.
Context {n : nat}.
Context `{!I0_class ord n, !succ0_class ord n, !nat_of_class ord n}.
Definition ytilded (k : ord n) (c : T) a b bk := (dotmulB0_op k c a b %/ bk)%C.
Definition ytildes (k : ord n) c a := (sqrt_op (dotmulB0_op k c a a)).
(* note: R is transposed with respect to cholesky.v *)
Definition inner_loop j A R :=
iteri_ord (nat_of j)
(fun i R => store_op R j i (ytilded i (fun_of_op A i j)
(row_op i R) (row_op j R)
(fun_of_op R i i)))
R.
(* note: R is transposed with respect to cholesky.v *)
Definition outer_loop A R :=
iteri_ord n
(fun j R =>
let R := inner_loop j A R in
store_op R j j (ytildes j (fun_of_op A j j)
(row_op j R)))
R.
(* note: the result is transposed with respect to cholesky.v *)
Definition cholesky A := outer_loop A A.
(** *** 1.2 Reflexive tactic *)
Context `{!heq_of (mx T), !trmx_of (mx T)}.
Definition is_sym (A : mx T n n) : bool := (A^T == A)%HC.
Definition foldl_diag T' f (z : T') A :=
iteri_ord n (fun i z => f z (fun_of_op A i i)) z.
Definition all_diag f A := foldl_diag (fun b c => b && f c) true A.
Context `{!leq_of T}.
Definition noneg_diag := all_diag (fun x => 0 <= x)%C.
Context `{!lt_of T}.
Definition pos_diag := all_diag (fun x => 0 < x)%C.
Definition max (a b : T) := if (b <= a)%C then a else b.
Definition max_diag A := foldl_diag max 0%C A.
Definition map_diag f A :=
iteri_ord n (fun i A' => store_op A' i i (f (fun_of_op A i i))) A.
Context `{!addup_class T, !mulup_class T, !divup_class T}.
Context `{!nat2Fup_class T, !subdn_class T}.
Definition tr_up A := foldl_diag addup 0%C A.
(** over-approximations of [eps] and [eta] *)
Variables eps eta : T.
(** [compute_c_aux (A : 'M_n) maxdiag] over-approximates
[(n + 2) eps / (1 - (n + 2) eps) * \tr A + 4 * eta * n * (2 * (n + 1) + maxdiag)] *)
Definition compute_c_aux (A : mx T n n) (maxdiag : T) : T :=
let np2 := nat2Fup n.+1 in
let np2eps := mulup np2 eps in
let g := divup np2eps (- (addup np2eps (-1%C)))%C in
addup
(mulup g (tr_up A))
(mulup
(mulup (mulup (nat2Fup 4) eta) (nat2Fup n))
(addup (nat2Fup (2 * n.+1)%N) maxdiag)).
Variable is_finite : T -> bool.
Definition compute_c (A : mx T n n) :
option T :=
let nem1 := addup (mulup ((nat2Fup (n.+1)%N)) eps) (-1%C)%C in
if is_finite nem1 && (nem1 < 0)%C then
let c := compute_c_aux A (max_diag A) in
if is_finite c then Some c else None
else None.
(** [test_n] checks that [n] is not too large *)
Definition test_n n : bool :=
let f := mulup (mulup (nat2Fup 3%N) (nat2Fup n.+1)) eps in
is_finite f && (f < 1)%C.
Definition posdef_check (A : mx T n n) : bool :=
[&& test_n n, is_sym A, noneg_diag A &
(match compute_c A with
| None => false
| Some c =>
let A' := map_diag (fun x => subdn x c) A in
let R := cholesky A' in
all_diag is_finite R && pos_diag R
end)].
Definition posdef_check_itv (A : mx T n n) (r : T) : bool :=
[&& is_finite r, (0 <= r)%C &
let nm := mulup (nat2Fup n) r in
let A' := map_diag (fun x => subdn x nm) A in
posdef_check A'].
End generic_cholesky.
Section seqmx_cholesky.
(** *** 1.3 General definitions for seqmx
- instantiation of dotmulB0, store, map_mx, eq, transpose
- a few support lemmas
*)
Context {T : Type}.
Context `{!zero_of T, !one_of T, !add_of T, !opp_of T, !div_of T, !mul_of T, !sqrt_of T}.
Fixpoint stilde_seqmx k (c : T) a b :=
match k, a, b with
| O, _, _ => c
| S k, [::], _ => c
| S k, _, [::] => c
| S k, a1 :: a2, b1 :: b2 => stilde_seqmx k (c + (- (a1 * b1)))%C a2 b2
end.
Global Instance dotmulB0_seqmx : dotmulB0_of T ord_instN hseqmx :=
fun n k c a b => stilde_seqmx k c (head [::] a) (head [::] b).
Context {n : nat}.
Definition ytilded_seqmx :
ord_instN n.+1 -> T -> hseqmx 1%N n.+1 -> hseqmx 1%N n.+1 -> T -> T :=
ytilded (T := T).
Definition ytildes_seqmx : ord_instN n.+1 -> T -> hseqmx 1%N n.+1 -> T :=
ytildes.
Definition cholesky_seqmx : @hseqmx T n.+1 n.+1 -> @hseqmx T n.+1 n.+1 :=
cholesky.
Definition outer_loop_seqmx :
@hseqmx T n.+1 n.+1 -> @hseqmx T n.+1 n.+1 -> @hseqmx T n.+1 n.+1 :=
outer_loop.
Definition inner_loop_seqmx :
ord_instN n.+1 -> @hseqmx T n.+1 n.+1 -> @hseqmx T n.+1 n.+1 -> @hseqmx T n.+1 n.+1 :=
inner_loop.
Context `{!eq_of T, !leq_of T, !lt_of T}.
(** Rely on arithmetic operations with directed rounding: *)
Context `{!addup_class T, !mulup_class T, !divup_class T}.
Context `{!nat2Fup_class T, !subdn_class T}.
Variable feps feta : T.
Variable is_finite : T -> bool.
Definition posdef_check_seqmx : @hseqmx T n.+1 n.+1 -> bool :=
posdef_check feps feta is_finite.
Definition posdef_check_itv_seqmx : @hseqmx T n.+1 n.+1 -> T -> bool :=
posdef_check_itv feps feta is_finite.
End seqmx_cholesky.
(** ** Part 2: Correctness proofs for proof-oriented types and programs *)
Section theory_cholesky.
(** *** Proof-oriented definitions, polymorphic w.r.t scalars *)
Context {T : Type}.
Context `{!zero_of T, !one_of T, !add_of T, !opp_of T, !div_of T, !mul_of T, !sqrt_of T}.
Global Instance fun_of_ssr : fun_of_of T ordinal (matrix T) :=
fun m n => @matrix.fun_of_matrix T m n.
Global Instance row_ssr : row_of ordinal (matrix T) := @matrix.row T.
Fixpoint fsum_l2r_rec n (c : T) : T ^ n -> T :=
match n with
| 0%N => fun _ => c
| n'.+1 =>
fun a => fsum_l2r_rec (c + (a ord0))%C [ffun i => a (lift ord0 i)]
end.
Global Instance dotmulB0_ssr : dotmulB0_of T ordinal (matrix T) :=
fun n =>
match n with
| 0%N => fun i c a b => c
| n'.+1 => fun i c a b =>
fsum_l2r_rec c
[ffun k : 'I_i => (- ((a ord0 (inord k)) * (b ord0 (inord k))))%C]
end.
Context {n : nat}.
Definition ytilded_ssr : 'I_n.+1 -> T -> 'M[T]_(1, n.+1) -> 'M[T]_(1, n.+1) -> T -> T :=
ytilded.
Definition ytildes_ssr : 'I_n.+1 -> T -> 'M[T]_(1, n.+1) -> T :=
ytildes.
Definition iteri_ord_ssr : forall T, nat -> ('I_n.+1 -> T -> T) -> T -> T :=
iteri_ord.
Definition inner_loop_ssr : 'I_n.+1 -> 'M[T]_n.+1 -> 'M[T]_n.+1 -> 'M[T]_n.+1 :=
inner_loop.
Definition outer_loop_ssr : 'M[T]_n.+1 -> 'M[T]_n.+1 -> 'M[T]_n.+1 :=
outer_loop.
Definition cholesky_ssr : 'M[T]_n.+1 -> 'M[T]_n.+1 :=
cholesky.
(** *** Proofs *)
Lemma store_ssr_eq (M : 'M[T]_n.+1) (i j : 'I_n.+1) v i' j' :
nat_of_ord i' = i -> nat_of_ord j' = j -> (store_ssr M i j v) i' j' = v.
Proof. by rewrite /nat_of_ssr mxE => -> ->; rewrite !eq_refl. Qed.
Lemma store_ssr_lt1 (M : 'M[T]_n.+1) (i j : 'I_n.+1) v i' j' :
(nat_of_ord i' < i)%N -> (store_ssr M i j v) i' j' = M i' j'.
Proof. by move=> Hi; rewrite mxE (ltn_eqF Hi). Qed.
Lemma store_ssr_lt2 (M : 'M[T]_n.+1) (i j : 'I_n.+1) v i' j' :
(nat_of_ord j' < j)%N -> (store_ssr M i j v) i' j' = M i' j'.
Proof. by move=> Hj; rewrite mxE (ltn_eqF Hj) Bool.andb_false_r. Qed.
Lemma store_ssr_gt1 (M : 'M[T]_n.+1) (i j : 'I_n.+1) v i' j' :
(i < nat_of_ord i')%N -> (store_ssr M i j v) i' j' = M i' j'.
Proof. by move=> Hi; rewrite mxE eq_sym (ltn_eqF Hi). Qed.
Lemma store_ssr_gt2 (M : 'M[T]_n.+1) (i j : 'I_n.+1) v i' j' :
(j < nat_of_ord j')%N -> (store_ssr M i j v) i' j' = M i' j'.
Proof.
move=> Hj.
by rewrite mxE (@eq_sym _ (nat_of_ord j')) (ltn_eqF Hj) Bool.andb_false_r.
Qed.
Lemma fsum_l2r_rec_eq k (c1 : T) (a1 : T ^ k)
(c2 : T) (a2 : T ^ k) :
c1 = c2 -> (forall i : 'I_k, a1 i = a2 i) ->
fsum_l2r_rec c1 a1 = fsum_l2r_rec c2 a2.
Proof.
elim: k c1 a1 c2 a2 => [//|k IHk] c1 a1 c2 a2 Hc Ha.
by apply IHk; [rewrite /fplus Hc Ha|move=> i; rewrite !ffunE].
Qed.
Lemma dotmulB0_ssr_eq k (i : 'I_k)
(c1 : T) (a1 b1 : 'rV_k)
(c2 : T) (a2 b2 : 'rV_k) :
c1 = c2 -> (forall j : 'I_k, (j < i)%N -> a1 ord0 j = a2 ord0 j) ->
(forall j : 'I_k, (j < i)%N -> b1 ord0 j = b2 ord0 j) ->
dotmulB0_ssr i c1 a1 b1 = dotmulB0_ssr i c2 a2 b2.
Proof.
case: k i c1 a1 b1 c2 a2 b2 => //= k i c1 a1 b1 c2 a2 b2 Hc Ha Hb.
apply fsum_l2r_rec_eq => // j; rewrite !ffunE Ha ?Hb //;
(rewrite inordK; [ |apply (ltn_trans (ltn_ord j))]); apply ltn_ord.
Qed.
Lemma ytilded_ssr_eq (k : 'I_n.+1)
(c1 : T) (a1 b1 : 'rV_n.+1) (bk1 : T)
(c2 : T) (a2 b2 : 'rV_n.+1) (bk2 : T) :
c1 = c2 -> (forall i : 'I_n.+1, (i < k)%N -> a1 ord0 i = a2 ord0 i) ->
(forall i : 'I_n.+1, (i < k)%N -> b1 ord0 i = b2 ord0 i) -> (bk1 = bk2) ->
ytilded_ssr k c1 a1 b1 bk1 = ytilded_ssr k c2 a2 b2 bk2.
Proof.
move=> Hc Ha Hb Hbk.
by rewrite /ytilded_ssr /ytilded; apply f_equal2; [apply dotmulB0_ssr_eq| ].
Qed.
Lemma ytildes_ssr_eq (k : 'I_n.+1) (c1 : T) (a1 : 'rV_n.+1) (c2 : T) (a2 : 'rV_n.+1) :
c1 = c2 -> (forall i : 'I_n.+1, (i < k)%N -> a1 ord0 i = a2 ord0 i) ->
ytildes_ssr k c1 a1 = ytildes_ssr k c2 a2.
Proof.
by move=> Hc Ha; rewrite /ytildes_ssr /ytildes; apply f_equal, dotmulB0_ssr_eq.
Qed.
Definition cholesky_spec_ssr (A R : 'M_n.+1) : Prop :=
(forall (j i : 'I_n.+1),
(i < j)%N ->
(R i j = ytilded_ssr i (A i j) (row i R^T) (row j R^T) (R i i)))
/\ (forall (j : 'I_n.+1),
(R j j = ytildes_ssr j (A j j) (row j R^T))).
(** *** Loop invariants *)
Definition outer_loop_inv (A R : 'M_n.+1) j : Prop :=
(forall (j' i' : 'I_n.+1),
(j' < j)%N ->
(i' < j')%N ->
(R j' i' = ytilded_ssr i' (A i' j') (row i' R) (row j' R) (R i' i')))
/\ (forall (j' : 'I_n.+1),
(j' < j)%N ->
(R j' j' = ytildes_ssr j' (A j' j') (row j' R))).
Definition inner_loop_inv (A R : 'M_n.+1) j i : Prop :=
outer_loop_inv A R j /\
(forall (j' i' : 'I_n.+1),
nat_of_ord j' = j ->
(i' < i)%N ->
(i' < j)%N ->
(R j' i' = ytilded_ssr i' (A i' j') (row i' R) (row j' R) (R i' i'))).
Lemma inner_loop_correct (A R : 'M_n.+1) (j : 'I_n.+1) :
inner_loop_inv A R j 0 -> inner_loop_inv A (inner_loop_ssr j A R) j n.+1.
Proof.
move=> H; cut (inner_loop_inv A (inner_loop_ssr j A R) j j).
{ by move=> {H} [Ho Hi]; split; [ |move=> j' i' Hj' _ Hi'; apply Hi]. }
rewrite /inner_loop_ssr /inner_loop /nat_of /nat_of_ssr.
set P := fun i s => inner_loop_inv A s j i; rewrite -/(P _ _).
apply iteri_ord_ind => //.
{ apply /ltnW /(ltn_ord j). }
move=> i R' _ [Ho Hi]; split; [split; [move=> j' i' Hj' Hi'|move=> j' Hj']| ].
{ rewrite store_ssr_lt1 // (proj1 Ho _ _ Hj' Hi').
apply ytilded_ssr_eq => // [i''|i''| ]; try rewrite 2!mxE.
{ by rewrite store_ssr_lt1 //; apply (ltn_trans Hi'). }
{ by rewrite store_ssr_lt1. }
by rewrite store_ssr_lt1 //; apply (ltn_trans Hi'). }
{ rewrite store_ssr_lt1 // (proj2 Ho _ Hj').
by apply ytildes_ssr_eq => // i''; rewrite 2!mxE store_ssr_lt1. }
move=> j' i' Hj' Hi' Hi'j; case (ltnP i' i) => Hii'.
{ rewrite store_ssr_lt2 // (Hi _ _ Hj' Hii' Hi'j).
apply ytilded_ssr_eq => // [i'' Hi''|i'' Hi''| ]; try rewrite 2!mxE.
{ by rewrite store_ssr_lt1. }
{ by rewrite store_ssr_lt2 //; apply ltn_trans with i'. }
by rewrite store_ssr_lt2. }
have Hi'i : nat_of_ord i' = i.
{ apply anti_leq; rewrite Hii' Bool.andb_true_r -ltnS //. }
rewrite store_ssr_eq //.
have Hini : inord i = i'; [by rewrite -Hi'i inord_val| ].
have Hinj : inord j = j'; [by rewrite -Hj' inord_val| ].
move: Hini Hinj; rewrite !inord_val => <- <-; apply ytilded_ssr_eq => //.
{ by move=> i''' Hi'''; rewrite 2!mxE store_ssr_lt2. }
{ by move=> i''' Hi'''; rewrite 2!mxE store_ssr_lt2. }
by rewrite store_ssr_lt1 //; move: Hi'i; rewrite /nat_of_ord => <-.
Qed.
Lemma outer_loop_correct (A R : 'M_n.+1) : outer_loop_inv A (outer_loop_ssr A R) n.+1.
Proof.
rewrite /outer_loop_ssr /outer_loop.
set P := fun i s => outer_loop_inv A s i; rewrite -/(P _ _).
apply iteri_ord_ind => // j R' _ H.
have Hin_0 : inner_loop_inv A R' j 0; [by []| ].
have Hin_n := inner_loop_correct Hin_0.
split; [move=> j' i' Hj' Hi'|move=> j' Hj'].
{ case (ltnP j' j) => Hjj'.
{ rewrite store_ssr_lt1 // (proj1 (proj1 Hin_n) _ _ Hjj' Hi').
apply ytilded_ssr_eq => // [i''|i''| ]; try rewrite 2!mxE.
{ by rewrite store_ssr_lt1 //; apply (ltn_trans Hi'). }
{ by rewrite store_ssr_lt1. }
by rewrite store_ssr_lt1 //; apply (ltn_trans Hi'). }
have Hj'j : nat_of_ord j' = j.
{ by apply anti_leq; rewrite Hjj' Bool.andb_true_r -ltnS. }
have Hi'j : (i' < j)%N by rewrite -Hj'j.
rewrite store_ssr_lt2 // (proj2 Hin_n _ _ Hj'j (ltn_ord i') Hi'j).
apply ytilded_ssr_eq => // [i'' Hi''|i'' Hi''| ]; try rewrite 2!mxE.
{ by rewrite store_ssr_lt1. }
{ by rewrite store_ssr_lt2 //; move: Hi'j; apply ltn_trans. }
by rewrite store_ssr_lt2. }
case (ltnP j' j) => Hjj'.
{ rewrite store_ssr_lt2 // (proj2 (proj1 Hin_n) _ Hjj').
apply ytildes_ssr_eq => // j''; try rewrite 2!mxE.
by rewrite store_ssr_lt1. }
have Hj'j : nat_of_ord j' = j.
{ by apply anti_leq; rewrite Hjj' Bool.andb_true_r -ltnS. }
have Hinjj' : inord j = j'; [by rewrite -Hj'j inord_val| ].
rewrite store_ssr_eq //.
move: Hinjj'; rewrite inord_val => <-; apply ytildes_ssr_eq => // i'' Hi''.
by rewrite 2!mxE store_ssr_lt2.
Qed.
(** *** The implementation satisfies the specification above. *)
Lemma cholesky_correct (A : 'M[T]_n.+1) : cholesky_spec_ssr A (cholesky_ssr A)^T.
Proof.
split; [move=> j i Hij|move=> j]; rewrite !mxE.
{ replace ((cholesky_ssr A) j i)
with (ytilded_ssr i (A i j)
(row i (cholesky_ssr A)) (row j (cholesky_ssr A))
((cholesky_ssr A) i i)).
{ by apply /ytilded_ssr_eq => // i' Hi'; rewrite !mxE. }
by apply sym_eq, outer_loop_correct; [apply ltn_ord| ]. }
replace ((cholesky_ssr A) j j)
with (ytildes_ssr j (A j j) (row j (cholesky_ssr A))).
{ by apply ytildes_ssr_eq => // i' Hi'; rewrite !mxE. }
by apply sym_eq, outer_loop_correct, ltn_ord.
Qed.
(** *** Proofs for cholesky-based tactic *)
Definition all_diag_ssr : (T -> bool) -> 'M[T]_n.+1 -> bool :=
all_diag.
Definition foldl_diag_ssr (T' : Type) : (T' -> T -> T') -> T' -> 'M_n.+1 -> T' :=
foldl_diag (T' := T').
Definition map_diag_ssr : (T -> T) -> 'M[T]_n.+1 -> 'M[T]_n.+1 :=
map_diag.
Lemma all_diag_correct f A : all_diag_ssr f A -> forall i, f (A i i).
Proof.
move=> Had i; move: (ltn_ord i) Had.
set P := fun i b => b = true -> f (A i i) = true.
rewrite -/(P i (all_diag_ssr f A)).
rewrite -/(nat_of _); apply iteri_ord_ind_strong_cases.
{ move=> j' s Hj' H j'' Hj''.
by rewrite /P Bool.andb_true_iff => Hb; elim Hb => Hb' _; apply H. }
by move=> j' s Hj' H; rewrite /P Bool.andb_true_iff => Hb; elim Hb.
Qed.
Lemma foldl_diag_correct (T' : Type) (f : T' -> T -> T') (z : T') (A : 'M_n.+1) :
forall (P : nat -> T' -> Type),
(forall (i : 'I_n.+1) z, P i z -> P i.+1 (f z (A i i))) ->
P O z -> P n.+1 (foldl_diag_ssr f z A).
Proof.
move=> P Hind; rewrite /foldl_diag_ssr /foldl_diag.
apply iteri_ord_ind => // i s Hi HPi; apply Hind.
by move: HPi; rewrite /nat_of /nat_of_ord.
Qed.
Lemma map_diag_correct_ndiag f (A : 'M[T]_n.+1) :
forall i j : 'I_n.+1, i <> j -> (map_diag_ssr f A) i j = A i j.
Proof.
move=> i j Hij.
rewrite /map_diag_ssr /map_diag /iteri_ord; set f' := fun _ _ => _.
suff H : forall k R i',
(matrix.fun_of_matrix (@iteri_ord_rec _ _ succ0_ssr _ k i' f' R) i j
= R i j) => //; elim => // k IHk R i' /=.
rewrite IHk; case (ltnP i' j) => Hi'j; [by rewrite store_ssr_gt2| ].
case (ltnP i j) => Hij'.
{ by rewrite store_ssr_lt1 //; apply (leq_trans Hij'). }
case (ltnP i' i) => Hi'i; [by rewrite store_ssr_gt1| ].
rewrite store_ssr_lt2 //; move: Hi'i; apply leq_trans.
case (leqP i j) => Hij'' //.
by casetype False; apply Hij, ord_inj, anti_leq; rewrite Hij''.
Qed.
Lemma map_diag_correct_diag f (A : 'M[T]_n.+1) :
forall i, (map_diag_ssr f A) i i = f (A i i).
Proof.
move=> i; rewrite /map_diag_ssr /map_diag.
set f' := fun _ _ => _.
set P := fun i s => s i i = f (A i i); rewrite -/(P i _).
try (apply iteri_ord_ind_strong_cases with (i0 := i) => //)
|| apply iteri_ord_ind_strong_cases with (i := i) => //.
{ move=> j s Hj Hind j' Hj'.
rewrite /P /f' store_ssr_lt1 //; apply Hind => //; apply ltn_ord. }
{ move=> j s Hj Hind; rewrite /P /f' store_ssr_eq //. }
apply ltn_ord.
Qed.
End theory_cholesky.
Section theory_cholesky_2.
(** *** Proof-oriented definitions, Float_infnan_spec scalars *)
(** This spec corresponds to the one in [cholesky.v]... *)
Context {fs : Float_infnan_spec} (eta_neq_0 : eta fs <> 0).
Global Instance add_instFIS : add_of (FIS fs) := @fiplus fs.
Global Instance mul_instFIS : mul_of (FIS fs) := @fimult fs.
Global Instance sqrt_instFIS : sqrt_of (FIS fs) := @fisqrt fs.
Global Instance div_instFIS : div_of (FIS fs) := @fidiv fs.
Global Instance opp_instFIS : opp_of (FIS fs) := @fiopp fs.
Global Instance zero_instFIS : zero_of (FIS fs) := @FIS0 fs.
Global Instance one_instFIS : one_of (FIS fs) := @FIS1 fs.
Global Instance eq_instFIS : eq_of (FIS fs) := @fieq fs.
Global Instance leq_instFIS : leq_of (FIS fs) := @file fs.
Global Instance lt_instFIS : lt_of (FIS fs) := @filt fs.
Context {n : nat}.
Lemma dotmulB0_correct k (c : FIS fs) (a b : 'rV_n.+1) :
dotmulB0_ssr k c a b = stilde_infnan c
[ffun i : 'I_k => a ord0 (inord i)]
[ffun i : 'I_k => b ord0 (inord i)].
Proof.
case: k => //= k Hk; elim: k Hk c a b => //= k IHk Hk c a b.
pose a' := \row_(i < n.+1) a ord0 (inord (lift ord0 i)).
pose b' := \row_(i < n.+1) b ord0 (inord (lift ord0 i)).
rewrite (@fsum_l2r_rec_eq _ _ _ _ _ _
[ffun i : 'I_k => (- (a' ord0 (inord i) * b' ord0 (inord i)))%C] erefl).
{ by rewrite (IHk (ltnW Hk)); f_equal; [|apply ffunP => i..];
rewrite !ffunE // mxE /=;
do 3 apply f_equal; apply /inordK /(ltn_trans (ltn_ord i)) /ltnW. }
by move=> i; rewrite !ffunE !mxE /=; apply f_equal, f_equal2;
do 3 apply f_equal; apply sym_eq, inordK, (ltn_trans (ltn_ord i)), ltnW.
Qed.
Lemma ytilded_correct k (c : FIS fs) (a b : 'rV_n.+1) (bk : FIS fs) :
ytilded_ssr k c a b bk = ytilded_infnan c
[ffun i : 'I_k => a ord0 (inord i)]
[ffun i : 'I_k => b ord0 (inord i)]
bk.
Proof.
rewrite /ytilded_ssr /ytilded /ytilded_infnan; apply f_equal2 => //.
apply dotmulB0_correct.
Qed.
Lemma ytildes_correct k (c : FIS fs) (a : 'rV_n.+1) :
ytildes_ssr k c a = ytildes_infnan c [ffun i : 'I_k => a ord0 (inord i)].
Proof.
rewrite /ytildes_ssr /ytildes /ytildes_infnan; apply f_equal => //.
apply dotmulB0_correct.
Qed.
Lemma cholesky_spec_correct (A R : 'M[FIS fs]_n.+1) :
cholesky_spec_ssr A R -> cholesky_spec_infnan A R.
Proof.
move=> H; split.
{ move=> j i Hij; rewrite (proj1 H) // ytilded_correct /ytilded_infnan.
by apply f_equal2 => //; apply f_equal3 => //; apply /ffunP => k;
rewrite !ffunE !mxE. }
move=> j; rewrite (proj2 H) ytildes_correct /ytildes_infnan; apply f_equal.
by apply f_equal3 => //; apply ffunP => k; rewrite !ffunE !mxE.
Qed.
(** ... which enables to restate corollaries from [cholesky.v]. *)
(** If [A] contains no infinity or NaN, then [MFI2F A] = [A] and
[posdef (MF2R (MFI2F A))] means that [A] is positive definite. *)
Lemma corollary_2_4_with_c_upper_bound :
3 * INR n.+2 * eps fs < 1 ->
forall A : 'M[FIS fs]_n.+1, MF2R (MFI2F A^T) = MF2R (MFI2F A) ->
(forall i : 'I_n.+1, 0 <= (MFI2F A) i i) ->
forall maxdiag : R, (forall i : 'I_n.+1, (MFI2F A) i i <= maxdiag) ->
forall c : R,
(INR n.+2 * eps fs / (1 - INR n.+2 * eps fs) * (\tr (MF2R (MFI2F A)))
+ 4 * eta fs * INR n.+1 * (2 * INR n.+2 + maxdiag)
<= c)%Re ->
forall At : 'M[FIS fs]_n.+1,
((forall i j : 'I_n.+1, (i < j)%N -> At i j = A i j) /\
(forall i : 'I_n.+1, (MFI2F At) i i <= (MFI2F A) i i - c)) ->
let R := cholesky_ssr At in
(forall i, (0 < (MFI2F R) i i)%Re) ->
posdef (MF2R (MFI2F A)).
Proof.
move=> H3n A SymA Pdiag maxdiag Hmaxdiag c Hc At HAt R HAR.
apply corollary_2_4_with_c_upper_bound_infnan with maxdiag c At R^T =>//.
split.
- by apply cholesky_spec_correct, cholesky_correct.
- by move=> i; move: (HAR i); rewrite !mxE.
Qed.
End theory_cholesky_2.
Section theory_cholesky_3.
(** *** Proof-oriented definitions, Float_round_up_infnan_spec scalars *)
Context {fs : Float_round_up_infnan_spec} (eta_neq_0 : eta fs <> 0).
Global Instance addup_instFIS : addup_class (FIS (fris fs)) := @fiplus_up fs.
Global Instance mulup_instFIS : mulup_class (FIS (fris fs)) := @fimult_up fs.
Global Instance divup_instFIS : divup_class (FIS (fris fs)) := @fidiv_up fs.
Global Instance nat2Fup_instFIS : nat2Fup_class (FIS (fris fs)) :=
@float_of_nat_up fs.
Global Instance subdn_instFIS : subdn_class (FIS (fris fs)) := @fiminus_down fs.
Global Instance trmx_instFIS_ssr : trmx_of (matrix (FIS fs)) := @trmx (FIS fs).
Context {n : nat}.
Lemma is_sym_correct_aux (A : 'M[FIS fs]_n.+1) :
is_sym A -> forall i j, fieq (A^T i j) (A i j).
Proof. by move=> H i j; move/forallP/(_ i)/forallP/(_ j) in H. Qed.
Lemma is_sym_correct (A : 'M[FIS fs]_n.+1) :
is_sym A -> MF2R (MFI2F A^T) = MF2R (MFI2F A).
Proof.
move/is_sym_correct_aux=> H; apply /matrixP=> i j.
by move: (H i j); rewrite !mxE => H'; apply /f_equal /fieq_spec.
Qed.
Definition max_diag_ssr (A : 'M[FIS fs]_n.+1) : FIS fs :=
@max_diag _ _ _ _ fun_of_ssr _ _ succ0_ssr _ A.
Lemma max_diag_correct (A : 'M[FIS fs]_n.+1) : (forall i, finite (A i i)) ->
forall i, (MFI2F A) i i <= FIS2FS (max_diag_ssr A).
Proof.
move=> HF.
set f := fun m c : FIS fs => if (c <= m)%C then m else c.
move=> i; move: i (ltn_ord i).
set P' := fun j (s : FIS fs) => forall (i : 'I_n.+1), (i < j)%N ->
(MFI2F A) i i <= FIS2FS s; rewrite -/(P' _ _).
suff : (finite (foldl_diag_ssr f (FIS0 fs) A)
/\ P' n.+1 (foldl_diag_ssr f (FIS0 fs) A)).
{ by move=> H; elim H. }
have Hf : f =2 @fimax fs.
{ move=> x y; rewrite /f/fimax/leq_op/leq_instFIS/file.
by case ficompare. }
set P := fun j s => finite s /\ P' j s; rewrite -/(P _ _).
apply foldl_diag_correct; rewrite /P /P'.
{ move=> i z Hind; destruct Hind as (Hind, Hind'); split.
{ by rewrite Hf; apply fimax_spec_f. }
move=> j Hj; case (ltnP j i) => Hji.
{ rewrite /f -/(fimax _ _); apply (Rle_trans _ _ _ (Hind' _ Hji)).
by rewrite -/(f z (A i i)) Hf; apply fimax_spec_lel. }
have H' : j = i.
{ by apply ord_inj, anti_leq; rewrite Hji Bool.andb_true_r. }
by rewrite H' Hf mxE; apply fimax_spec_ler. }
by split; [apply finite0|].
Qed.
Lemma max_diag_pos (A : 'M[FIS fs]_n.+1) : (forall i, finite (A i i)) ->
0 <= FIS2FS (max_diag_ssr A).
Proof.
move=> HF.
set f := fun m c : FIS fs => if (c <= m)%C then m else c.
suff : (finite (foldl_diag_ssr f (FIS0 fs) A)
/\ 0 <= FIS2FS (foldl_diag_ssr f (FIS0 fs) A)).
{ by move=> H; elim H. }
have Hf : f =2 @fimax fs.
{ move=> x y; rewrite /f/fimax/leq_op/leq_instFIS/file.
by case ficompare. }
set P := fun (j : nat) s => @finite fs s /\ 0 <= FIS2FS s.
try (apply foldl_diag_correct with (P0 := P); rewrite /P)
|| apply foldl_diag_correct with (P := P); rewrite /P.
{ move=> i z Hind; destruct Hind as (Hind, Hind'); split.
{ by rewrite Hf; case (fimax_spec_eq z (A i i)) => ->. }
by rewrite Hf; apply (Rle_trans _ _ _ Hind'), fimax_spec_lel. }
by split; [apply finite0|rewrite FIS2FS0; right].
Qed.
Definition tr_up_ssr (n : nat) : 'M[FIS fs]_n.+1 -> FIS fs := tr_up.
Lemma tr_up_correct (A : 'M[FIS fs]_n.+1) : finite (tr_up_ssr A) ->
\tr (MF2R (MFI2F A)) <= FIS2FS (tr_up_ssr A).
Proof.
rewrite /tr_up_ssr /tr_up -/(foldl_diag_ssr _ _ _).
replace (\tr _) with (\sum_(i < n.+1) (FIS2FS (A (inord i) (inord i)) : R));
[ |by apply eq_big => // i _; rewrite !mxE inord_val].
set P := fun j (s : FIS fs) => finite s ->
(\sum_(i < j) (FIS2FS (A (inord i) (inord i)) : R)) <= FIS2FS s.
rewrite -/(P _ _); apply foldl_diag_correct; rewrite /P.
{ move=> i z Hind Fa; move: (fiplus_up_spec Fa); apply Rle_trans.
rewrite big_ord_recr /= /GRing.add /= inord_val.
apply Rplus_le_compat_r, Hind, (fiplus_up_spec_fl Fa). }
move=> _; rewrite big_ord0 FIS2FS0; apply Rle_refl.
Qed.
Definition test_n_ssr : nat -> bool :=
test_n (fieps fs) (@finite fs).
Lemma test_n_correct : test_n_ssr n.+1 -> 3 * INR n.+2 * eps fs < 1.
Proof.
rewrite /test_n_ssr /test_n; set f := _ (fieps _).
move/andP => [Ff Hf]; have Ffeps := fimult_up_spec_fr Ff.
have Fp := fimult_up_spec_fl Ff.
have Ff4 := fimult_up_spec_fl Fp; have Ffn := fimult_up_spec_fr Fp.
apply (Rle_lt_trans _ (FIS2FS f)).
{ move: (fimult_up_spec Ff); apply Rle_trans, Rmult_le_compat.
{ apply Rmult_le_pos; [lra|apply pos_INR]. }
{ apply eps_pos. }
{ move: (fimult_up_spec Fp); apply Rle_trans, Rmult_le_compat.
{ lra. }
{ apply pos_INR. }
{ move: (float_of_nat_up_spec Ff4); apply Rle_trans=>/=; lra. }
by move: (float_of_nat_up_spec Ffn); apply Rle_trans; right. }
apply fieps_spec. }
apply (Rlt_le_trans _ _ _ (filt_spec Ff (finite1 fs) Hf)).
by rewrite FIS2FS1; right.
Qed.
Definition compute_c_aux_ssr : 'M[FIS fs]_n.+1 -> FIS fs -> FIS fs :=
compute_c_aux (fieps fs) (fieta fs).
Lemma compute_c_aux_correct (A : 'M[FIS fs]_n.+1) maxdiag :
(INR n.+2 * eps fs < 1) ->
(finite (addup (mulup ((nat2Fup (n.+2)%N)) (fieps fs)) (- (1)))%C) ->
(FIS2FS (addup (mulup ((nat2Fup (n.+2)%N)) (fieps fs)) (- (1)))%C < 0) ->
(forall i, 0 <= FIS2FS (A i i)) ->
(0 <= FIS2FS maxdiag) ->
finite (compute_c_aux_ssr A maxdiag) ->
(INR n.+2 * eps fs / (1 - INR n.+2 * eps fs) * (\tr (MF2R (MFI2F A)))
+ 4%Re * eta fs * INR n.+1 * (2%Re * INR n.+2 + FIS2FS maxdiag)
<= FIS2FS (compute_c_aux_ssr A maxdiag))%R.
Proof.
have Pnp2 := pos_INR (n.+2)%N.
have Pe := eps_pos fs.
move=> Heps Fnem1 Nnem1 Pdiag Pmaxdiag Fc.
rewrite /compute_c_aux_ssr /compute_c_aux.
move: (fiplus_up_spec Fc); apply Rle_trans, Rplus_le_compat.
{ have Fl := fiplus_up_spec_fl Fc.
move: (fimult_up_spec Fl); apply Rle_trans, Rmult_le_compat.
{ apply Rmult_le_pos; [apply INR_eps_pos|].
apply Rlt_le, Rinv_0_lt_compat; lra. }
{ by apply big_sum_pos_pos => i; rewrite !mxE. }
{ have Fll := fimult_up_spec_fl Fl.
have F1mne := fiopp_spec_f Fnem1.
move: (fidiv_up_spec Fll F1mne); apply Rle_trans, Rmult_le_compat.
{ apply INR_eps_pos. }
{ apply Rlt_le, Rinv_0_lt_compat; lra. }
{ have Flr := fidiv_up_spec_fl Fll F1mne.
move: (fimult_up_spec Flr); apply /Rle_trans /Rmult_le_compat => //.
{ apply float_of_nat_up_spec, (fimult_up_spec_fl Flr). }
apply fieps_spec. }
apply Rinv_le.
{ rewrite (fiopp_spec (fiopp_spec_f Fnem1)) /=; lra. }
rewrite (fiopp_spec (fiopp_spec_f Fnem1)).
rewrite -Ropp_minus_distr; apply Ropp_le_contravar.
move: (fiplus_up_spec Fnem1); apply Rle_trans; apply Rplus_le_compat.
{ have Fne := fiplus_up_spec_fl Fnem1.
move: (fimult_up_spec Fne); apply /Rle_trans /Rmult_le_compat => //.
{ apply float_of_nat_up_spec, (fimult_up_spec_fl Fne). }
apply fieps_spec. }
rewrite (fiopp_spec (fiplus_up_spec_fr Fnem1)); apply Ropp_le_contravar.
by rewrite FIS2FS1; right. }
apply tr_up_correct, (fimult_up_spec_fr Fl). }
have Fr := fiplus_up_spec_fr Fc.
move: (fimult_up_spec Fr); apply Rle_trans; apply Rmult_le_compat.
{ apply Rmult_le_pos; [|by apply pos_INR]; apply Rmult_le_pos; [lra|].
apply eta_pos. }
{ apply Rplus_le_le_0_compat; [|apply Pmaxdiag].
apply Rmult_le_pos; [lra|apply pos_INR]. }
{ move: (fimult_up_spec (fimult_up_spec_fl Fr)); apply Rle_trans.
have Frl := fimult_up_spec_fl Fr.
apply Rmult_le_compat.
{ apply Rmult_le_pos; [lra|apply eta_pos]. }
{ apply pos_INR. }
{ have Frll := fimult_up_spec_fl Frl.
move: (fimult_up_spec Frll); apply Rle_trans.
apply Rmult_le_compat; [lra|by apply eta_pos| |by apply fieta_spec].
replace 4%Re with (INR 4); [|by simpl; lra].
apply float_of_nat_up_spec, (fimult_up_spec_fl Frll). }
apply float_of_nat_up_spec, (fimult_up_spec_fr Frl). }
have Frr := fimult_up_spec_fr Fr.
move: (fiplus_up_spec Frr); apply Rle_trans, Rplus_le_compat_r.
have Frrl := fiplus_up_spec_fl Frr.
by change 2%Re with (INR 2); rewrite -mult_INR; apply float_of_nat_up_spec.
Qed.
Definition compute_c_ssr : 'M[FIS fs]_n.+1 -> option (FIS fs) :=
compute_c (fieps fs) (fieta fs) (@finite fs).
Lemma compute_c_correct (A : 'M[FIS fs]_n.+1) :
(INR n.+2 * eps fs < 1) ->
(forall i, finite (A i i)) ->
(forall i, (0 <= FIS2FS (A i i))%R) ->
forall c : FIS fs, compute_c_ssr A = Some c ->
(INR n.+2 * eps fs / (1 - INR n.+2 * eps fs) * (\tr (MF2R (MFI2F A)))
+ 4 * eta fs * INR n.+1 * (2 * INR n.+2 + FIS2FS (max_diag_ssr A))
<= FIS2FS c)%R.
Proof.
move=> Heps Fdiag Pdiag c.
rewrite /compute_c_ssr /compute_c.
set nem1 := addup _ _.
case_eq (finite nem1 && (nem1 < 0)%C); [ |by []].
rewrite Bool.andb_true_iff => H; elim H => Fnem1 Nnem1.
set c' := compute_c_aux _ _ _ _.
case_eq (finite c') => Hite'; [ |by []]; move=> Hc'.
have Hc'' : c' = c by injection Hc'.
rewrite -Hc''; apply compute_c_aux_correct => //.
{ eapply (Rlt_le_trans _ (FIS2FS zero_instFIS)); [ |by right; rewrite FIS2FS0].
apply filt_spec => //; apply finite0. }
by apply max_diag_pos.
Qed.
Definition posdef_check_ssr : 'M[FIS fs]_n.+1 -> bool :=
posdef_check (fieps fs) (fieta fs) (@finite fs).
Lemma posdef_check_f1 A : posdef_check_ssr A ->
forall i j, finite (A i j).
Proof.
rewrite /posdef_check_ssr /posdef_check.
case/and4P=> [H1 H2 H3 H4].
move: H4; set cc := compute_c _ _ _ _; case_eq cc => // c' Hc'.
set At := map_diag _ _; set Rt := cholesky _.
move/andP => [Had Hpd].
suff: forall i j : 'I_n.+1, (i <= j)%N -> finite (A i j).
{ move=> H i j; case (ltnP j i); [ |by apply H]; move=> Hij.
rewrite -(@fieq_spec_f _ (A^T i j)); [by rewrite mxE; apply H, ltnW| ].
by apply is_sym_correct_aux. }
move=> i j Hij; suff: finite (At i j).
{ case_eq (i == j :> nat) => Hij'.
{ move /eqP /ord_inj in Hij'; rewrite Hij' map_diag_correct_diag.
apply fiminus_down_spec_fl. }
rewrite map_diag_correct_ndiag //.
by move /eqP in Hij' => H; apply Hij'; rewrite H. }
apply (@cholesky_success_infnan_f1 _ _ At Rt^T) => //; split.
{ rewrite /Rt -/(cholesky_ssr At).
apply cholesky_spec_correct, cholesky_correct. }
move=> i'; rewrite mxE.
have->: 0%Re = FIS2FS (FIS0 fs) by rewrite FIS2FS0.
apply filt_spec; [by apply finite0| | ].
{ move: Had i'; rewrite -/(all_diag_ssr _ _); apply all_diag_correct. }
move: Hpd i'; rewrite /pos_diag -/(all_diag_ssr _ _); apply all_diag_correct.
Qed.
Lemma posdef_check_correct A :
posdef_check_ssr A -> posdef (MF2R (MFI2F A)).
Proof.
move=> H; have Hfdiag := posdef_check_f1 H.
move: H; move/eqP/eqP.
rewrite /posdef_check_ssr /posdef_check.
case/and3P => [Hn Hsym Htpdiag].
move/test_n_correct in Hn.
have Hn' : INR n.+2 * eps fs < 1; [lra|].
move/is_sym_correct in Hsym.
move: Htpdiag.
set cc := compute_c _ _ _ _; case_eq cc => // c' Hc'.
case/and3P.
set At := map_diag _ _; set Rt := cholesky _.
move=> Htpdiag HtfRt HtpRt.
have Htpdiag' := all_diag_correct Htpdiag.
have Hpdiag : forall i, 0 <= FIS2FS (A i i).
{ move=> i.
eapply (Rle_trans _ (FIS2FS zero_instFIS)); [by right; rewrite FIS2FS0| ].
by apply file_spec => //; [apply finite0|apply Htpdiag']. }
have HfRt := all_diag_correct HtfRt.
have HtpRt' := all_diag_correct HtpRt.
have HpRt : forall i, 0 < (MFI2F Rt) i i.
{ move=> i.
eapply (Rle_lt_trans _ (FIS2FS zero_instFIS)); [by right; rewrite FIS2FS0| ].
rewrite mxE; apply filt_spec => //; [apply finite0|apply HtpRt']. }
move {Htpdiag HtfRt HtpRt Htpdiag' HtpRt'}.
try (apply corollary_2_4_with_c_upper_bound with
(maxdiag := FIS2FS (max_diag_ssr A)) (c := FIS2FS c') (At0 := At) => //)
|| apply corollary_2_4_with_c_upper_bound with
(maxdiag := FIS2FS (max_diag_ssr A)) (c := FIS2FS c') (At := At) => //.
{ by move=> i; rewrite mxE. }
{ by apply max_diag_correct. }
{ by apply compute_c_correct. }
have Hfat : forall i, finite (At i i).
{ move=> i; move: (cholesky_spec_correct (cholesky_correct At)).
elim=> _ Hs; move: (Hs i); rewrite mxE /cholesky_ssr => {}Hs.
move: (HfRt i); rewrite /Rt Hs /ytildes_infnan => H.
move: (fisqrt_spec_f1 H); apply stilde_infnan_fc. }
split; move=> i; [move=> j Hij| ].
{ by apply /map_diag_correct_ndiag /eqP; rewrite neq_ltn Hij. }
move: (Hfat i); rewrite !mxE /At map_diag_correct_diag; apply fiminus_down_spec.
by rewrite andbF in Hc'.
Qed.
Lemma map_diag_sub_down_correct (A : 'M_n.+1) r :
(forall i, finite (fiminus_down (A i i) r)) ->
exists d : 'rV_n.+1,
MF2R (MFI2F (map_diag_ssr ((@fiminus_down fs)^~ r) A))
= MF2R (MFI2F A) - diag_mx d
/\ (FIS2FS r : R) *: 1 <=m: diag_mx d.
Proof.
move=> HF; set A' := map_diag_ssr _ _.
exists (\row_i (((MFI2F A) i i : R) - ((MFI2F A') i i : R))); split.
{ rewrite -matrixP => i j; rewrite !mxE.
set b := (_ == _)%B; case_eq b; rewrite /b /GRing.natmul /= => Hij.
{ move /eqP in Hij; rewrite Hij map_diag_correct_diag.
rewrite /GRing.add /GRing.opp /=; ring. }
rewrite /GRing.add /GRing.opp /GRing.zero /= Ropp_0 Rplus_0_r.
by apply /f_equal /f_equal /map_diag_correct_ndiag /eqP; rewrite Hij. }
move=> i j; rewrite !mxE.
set b := (_ == _)%B; case_eq b; rewrite /b /GRing.natmul /= => Hij.
{ rewrite /GRing.mul /GRing.one /= Rmult_1_r /A' map_diag_correct_diag.
rewrite /GRing.add /GRing.opp /=.
replace (FIS2FS r : R)
with (Rminus (FIS2FS (A i i)) (Rminus (FIS2FS (A i i)) (FIS2FS r))) by ring.
by apply Rplus_le_compat_l, Ropp_le_contravar, fiminus_down_spec. }
by rewrite GRing.mulr0; right.
Qed.
Definition posdef_check_itv_ssr : 'M[FIS fs]_n.+1 -> FIS fs -> bool :=
posdef_check_itv (fieps fs) (fieta fs) (@finite fs).
Lemma posdef_check_itv_f1 A r : posdef_check_itv_ssr A r ->
forall i j, finite (A i j).
Proof.
rewrite /posdef_check_itv_ssr /posdef_check_itv; set A' := map_diag _ _.
move/and3P => [H1 H2 H3] i j.
suff: finite (A' i j); [ |by apply posdef_check_f1].
case_eq (i == j :> nat) => Hij'.
{ move /eqP /ord_inj in Hij'; rewrite Hij' map_diag_correct_diag.
apply fiminus_down_spec_fl. }
rewrite map_diag_correct_ndiag //.
by move /eqP in Hij' => H; apply Hij'; rewrite H.
Qed.
Lemma posdef_check_itv_correct A r : posdef_check_itv_ssr A r ->
forall Xt : 'M[R]_n.+1,
Mabs (Xt - MF2R (MFI2F A)) <=m: MF2R (MFI2F (matrix.const_mx r)) ->
posdef Xt.
Proof.
rewrite /posdef_check_itv_ssr /posdef_check_itv.
set nr := mulup _ _; set A' := map_diag _ _.
case/and3P => [Fr Pr HA' Xt HXt].
have HA'' := posdef_check_correct HA'.
have HF := posdef_check_f1 HA'.
have HF' : forall i, finite (fiminus_down (A i i) nr).
{ by move=> i; move: (HF i i); rewrite map_diag_correct_diag. }
rewrite -(GRing.addr0 Xt) -(GRing.subrr (MF2R (MFI2F A))).
elim (map_diag_sub_down_correct HF') => d [Hd Hd'].
rewrite /map_diag_ssr /fiminus_down -/A' in Hd.
have HA : MF2R (MFI2F A) = MF2R (MFI2F A') + diag_mx d.
{ by rewrite Hd -GRing.addrA (GRing.addrC _ (_ d)) GRing.subrr GRing.addr0. }
rewrite {1}HA.
rewrite !GRing.addrA (GRing.addrC Xt) -!GRing.addrA (GRing.addrC (diag_mx d)).
apply posdef_norm_eq_1 => x Hx.
rewrite mulmxDr mulmxDl -(GRing.addr0 0); apply Madd_lt_le_compat.
{ apply HA'' => Hx'; rewrite Hx' norm2_0 /GRing.zero /GRing.one /= in Hx.
move: Rlt_0_1; rewrite Hx; apply Rlt_irrefl. }
rewrite GRing.addrA mulmxDr mulmxDl -(GRing.opprK (_ *m diag_mx d *m _)).
apply Mle_sub.
apply Mle_trans with (- Mabs (x^T *m (Xt - MF2R (MFI2F A)) *m x));
[apply Mopp_le_contravar|by apply Mge_opp_abs].
apply Mle_trans with ((Mabs x)^T *m Mabs (Xt - MF2R (MFI2F A)) *m Mabs x).
{ apply (Mle_trans (Mabs_mul _ _)), Mmul_le_compat_r; [by apply Mabs_pos| ].
rewrite map_trmx; apply (Mle_trans (Mabs_mul _ _)).
by apply Mmul_le_compat_l; [apply Mabs_pos|apply Mle_refl]. }
apply (Mle_trans (Mmul_abs_lr _ HXt)).
apply Mle_trans with (INR n.+1 * FIS2FS r)%Re%:M.
{ apply r_upper_bound => //.
{ move: HXt; apply Mle_trans, Mabs_pos. }
by move=> i j; rewrite !mxE; right. }
set IN := INR n.+1; rewrite Mle_scalar !mxE /GRing.natmul /= -(Rmult_1_r (_ * _)).
replace 1%Re with (1%Re^2) by ring; rewrite /GRing.one /= in Hx; rewrite -Hx.
rewrite norm2_sqr_dotprod /dotprod mxE /= big_distrr /=.
apply big_rec2 => [ |i y1 y2 _ Hy12]; [by right| ]; rewrite mul_mx_diag !mxE.
rewrite /GRing.add /GRing.mul /=; apply Rplus_le_compat => //.
rewrite (Rmult_comm _ (d _ _)) !Rmult_assoc -Rmult_assoc.
apply Rmult_le_compat_r; [by apply Rle_0_sqr| ].
have Fnr : finite nr.
{ move: (HF' ord0); rewrite /fiminus_down => F.
apply fiopp_spec_f1 in F; apply (fiplus_up_spec_fl F). }
apply (Rle_trans _ (FIS2FS nr)).
{ apply (Rle_trans _ (FIS2FS (float_of_nat_up fs n.+1) * FIS2FS r)).
{ apply Rmult_le_compat_r.
{ change 0%Re with (F0 fs : R); rewrite -FIS2FS0; apply file_spec.
{ apply finite0. }
{ move: Fnr; rewrite /nr; apply fimult_up_spec_fr. }
by move: Pr. }
by apply float_of_nat_up_spec, (fimult_up_spec_fl Fnr). }
by apply fimult_up_spec. }
by move: (Hd' i i); rewrite !mxE eq_refl /GRing.natmul /GRing.mul /= Rmult_1_r.
Qed.
End theory_cholesky_3.
(** ** Part 3: Parametricity *)
(** *** 3.1 Data refinement *)
Require Import Equivalence RelationClasses Morphisms.
(* Definition inh T (R : T -> T -> Type) := fun x y => inhabited (R x y). *)
Global Instance Proper_refines0 T (R : T -> T -> Prop) x : refines R x x -> Proper R x | 99.
Proof. by rewrite /Proper refinesE. Qed.
Global Instance Proper_refines1 T0 T1 (R0 : T0 -> T0 -> Prop) (R1 : T1 -> T1 -> Prop) x :
refines (R0 ==> R1) x x -> Proper (R0 ==> R1) x | 99.
Proof. by rewrite /Proper refinesE. Qed.
Global Instance Proper_refines2 T0 T1 T2 (R0 : T0 -> T0 -> Prop) (R1 : T1 -> T1 -> Prop) (R2 : T2 -> T2 -> Prop) x :
refines (R0 ==> R1 ==> R2) x x -> Proper (R0 ==> R1 ==> R2) x | 99.
Proof. by rewrite /Proper refinesE. Qed.
Ltac ref_abstr := eapply refines_abstr.
Section refinement_cholesky.
(** "C" for "concrete type" *)
Context {C : Type}.
Context `{!zero_of C, !one_of C, !add_of C, !opp_of C, !mul_of C, !div_of C, !sqrt_of C}.
Local Notation mxC := (@hseqmx C) (only parsing).
Context `{!leq_of C}.
(* Erik: do we really need [n1] and [n2] ? *)
Context {n1 n2 : nat} {rn : nat_R n1.+1 n2.+1}.
Let r1 := nat_R_S_R nat_R_O_R.
Global Instance refine_dotmulB0 :
refines (Rord rn ==> eq ==> Rseqmx r1 rn ==> Rseqmx r1 rn ==> eq)
(@dotmulB0_ssr _ _ _ _ n1.+1) (@dotmulB0_seqmx C _ _ _ n2.+1).
Proof.
eapply refines_abstr => k k' ref_k.
eapply refines_abstr => c c' ref_c.
eapply refines_abstr => a0 a0' ref_a.
eapply refines_abstr => b0 b0' ref_b.
rewrite !refinesE in ref_k ref_a ref_b ref_c.
red in ref_k; rewrite -ref_k; clear ref_k.
have {ref_a} [a a' ha1 ha2 ha3] := ref_a.
have {ref_b} [b b' hb1 hb2 hb3] := ref_b.
(* rewrite refinesE=> k _ <- c _ <- _ _ [a a' ha1 ha2 ha3] _ _ [b b' hb1 hb2 hb3]. *)
rewrite /dotmulB0_seqmx refinesE.
move: ha1; case Ea' : a'=>[//|a'0 a'1] _ /=.
move: hb1; case Eb' : b'=>[//|b'0 b'1] _ /=.
move: (ha2 O erefl) (hb2 O erefl) (ha3 ord0) (hb3 ord0).
rewrite Ea' Eb' /= -(nat_R_eq rn).
elim: n1 k {ha3} a {hb3} b c c' {Ea'} a'0 {Eb'} b'0 ref_c => [ |n' IH] k a b c c' a'0 b'0 ref_c.
{ by rewrite (ord_1_0 k) /=. }
case Ea'0 : a'0 => [//|a'00 a'01].
case Eb'0 : b'0 => [//|b'00 b'01] ha1 hb1 ha3 hb3.
case k => {}k Hk.
case: k Hk => [ |k Hk] //=; set cc := (c' + - _)%C.
rewrite ltnS in Hk.
rewrite ffunE.
have->: [ffun i => [ffun k0 : 'I__ => (- (a ord0 (inord k0) * b ord0 (inord k0)))%C]
(lift ord0 i)] =
[ffun i => (- (a ord0 (inord (lift ord0 i)) * b ord0 (inord (lift ord0 i))))%C].
by move=> n; apply/ffunP => x; rewrite !ffunE.
rewrite <-(IH (Ordinal Hk) (\row_(i < n'.+1) a ord0 (lift ord0 i))
(\row_(i < n'.+1) b ord0 (lift ord0 i))
(c + - (a ord0 (@inord n'.+1 (@ord0 k.+1)) * b ord0 (@inord n'.+1 (@ord0 k.+1))))%C).
{ (* apply eq_subrelation; tc. *)
apply fsum_l2r_rec_eq => [ |i] //.
rewrite !ffunE /cc !mxE; repeat f_equal; apply/val_inj; rewrite /= !inordK //;
by apply (ltn_trans (ltn_ord _)). }
{ rewrite /cc ha3 hb3 !inordK //= ref_c; reflexivity. }
{ by move: ha1 => [ha1']. }
{ by move: hb1 => [hb1']. }
{ by move=> j; rewrite mxE ha3. }
by move=> j; rewrite mxE hb3.
Qed.
Lemma refine_ytilded :
refines (Rord rn ==> eq ==> Rseqmx r1 rn ==> Rseqmx r1 rn ==> eq ==> eq)
(ytilded_ssr (T:=C) (n := n1)) (ytilded_seqmx (n := n2)).
Proof.
ref_abstr => k k' ref_k; ref_abstr => c c' ref_c; ref_abstr => a a' ref_a; ref_abstr => b b' ref_b.
ref_abstr => bk bk' ref_bk'.
rewrite /ytilded_ssr /ytilded_seqmx /ytilded.
refines_apply1.
refines_apply1.
by rewrite refinesE => ??-> ??->.
Qed.
Global Instance refine_ytildes :
refines (Rord rn ==> eq ==> Rseqmx r1 rn ==> eq)
(ytildes_ssr (T:=C) (n := n1)) (ytildes_seqmx (n := n2)).
Proof.
ref_abstr=> k k' ref_k; ref_abstr=> c c' ref_c; ref_abstr=> a a' ref_a.
rewrite /ytildes_ssr /ytildes_seqmx /ytildes.
refines_apply1.
by rewrite refinesE => ??->.
Qed.
(* TODO: refactor *)
Definition Rordn := fun j j' => j = j' /\ (j <= n1.+1)%N.
Lemma refines_Rordn_eq j j' : refines Rordn j j' -> refines eq j j'.
Proof. by rewrite !refinesE; case. Qed.
Lemma Rordn_eq j j' : Rordn j j' -> j = j'.
Proof. exact: proj1. Qed.
Global Instance refine_iteri_ord :
forall T T', forall RT : T -> T' -> Type,
refines (Rordn ==> (Rord rn ==> RT ==> RT)
==> RT ==> RT)
(@iteri_ord _ n1.+1 I0_ssr succ0_ssr T)
(@iteri_ord _ n2.+1 I0_instN succ0_instN T').
Proof.
move=> T T' RT.
rewrite refinesE => j j' [Hj' Hj] f f' rf x x' rx; rewrite -Hj'.
have := nat_R_eq rn; case =><-.
apply (iteri_ord_ind2 (M := T) (M' := T') (j := j) (n := n1)) => // i i' s s' Hi Hi' Hs.
apply refinesP; refines_apply.
by rewrite refinesE.
Qed.
Global Instance refine_iteri_ord' :
forall T T', forall RT : T -> T' -> Type,
refines (Rordn ==> (Rordn ==> RT ==> RT)
==> RT ==> RT)
(@iteri_ord _ n1.+1 I0_instN succ0_instN T)
(@iteri_ord _ n1.+1 I0_instN succ0_instN T').
Proof.
move=> T T' RT.
rewrite refinesE => j j' ref_j f f' ref_f x x' ref_x.
rewrite -(proj1 ref_j).
apply (iteri_ord_ind2 (M := T) (M' := T') (j := j)) =>//.
exact: (proj2 ref_j).
intros.
apply refinesP; refines_apply.
by rewrite refinesE.
Qed.
(*
Global Instance refine_iteri_ord :
forall T T', forall RT : T -> T' -> Type,
refines (Rordn ==> (Rord rn' ==> RT ==> RT)
==> RT ==> RT)
(@iteri_ord _ n1.+1 I0_ssr succ0_ssr T)
(@iteri_ord _ n2.+1 I0_instN succ0_instN T').
Proof.
move=> T T' RT.
ref_abstr => j j' ref_j.
ref_abstr => f f' ref_f.
ref_abstr => x x' ref_x.
rewrite refinesE /Rord in ref_j.
rewrite -ref_j -(nat_R_eq rn) refinesE.
apply (iteri_ord_ind2 (M := T) (M' := T') (j := j)).
by rewrite ltnW // ltn_ord.
move=> i i' s s' Hi Hi' Hs.
apply refinesP; refines_apply_tc.
exact: refinesP.
Qed.
*)
Global Instance refine_inner_loop :
refines (Rord rn ==> Rseqmx rn rn ==> Rseqmx rn rn ==> Rseqmx rn rn)
(inner_loop_ssr (T:=C) (n := n1)) (inner_loop_seqmx (n := n2)).
Proof.
rewrite refinesE=> j j' rj a a' ra r r' rr.
rewrite /inner_loop_ssr /inner_loop_seqmx /inner_loop.
apply refinesP.
refines_apply1.
refines_apply1.
eapply refines_apply (*!*).
eapply refine_iteri_ord.
{ rewrite refinesE; split; [by []|apply ltnW, ltn_ord]. }
rewrite refinesE=> i i' ri s s' rs.
apply refinesP; refines_apply.
eapply refine_ytilded; tc.
Qed.
Global Instance refine_outer_loop :
refines (Rseqmx rn rn ==> Rseqmx rn rn ==> Rseqmx rn rn)
(outer_loop_ssr (T:=C) (n := n1)) (outer_loop_seqmx (n := n2)).
Proof.
rewrite refinesE=> a a' ra r r' rr.
rewrite /outer_loop_ssr /outer_loop_seqmx /outer_loop.
apply refinesP.
refines_apply1.
refines_apply1.
refines_apply1.
by rewrite refinesE /Rordn; split; rewrite (nat_R_eq rn).
rewrite refinesE=> i i' ri s s' rs.
eapply refinesP.
refines_apply.
Qed.
Global Instance refine_cholesky :
refines (Rseqmx rn rn ==> Rseqmx rn rn)
(cholesky_ssr (T:=C) (n := n1)) (cholesky_seqmx (n := n2)).
Proof.
rewrite refinesE=> a a' ra; rewrite /cholesky_ssr /cholesky_seqmx /cholesky.
exact: refinesP.
Qed.
End refinement_cholesky.
Section refinement_cholesky_2.
Context {fs : Float_round_up_infnan_spec}.
(* C := FIS fs *)
(* To move? *)
Variable eqFIS : FIS fs -> FIS fs -> Prop.
Context `{!Equivalence eqFIS}.
Context `{!refines (eqFIS) zero_instFIS zero_instFIS}.
Context `{!refines (eqFIS) one_instFIS one_instFIS}.
Context `{!refines (eqFIS ==> eqFIS) opp_instFIS opp_instFIS}.
Context `{!refines (eqFIS ==> eqFIS) sqrt_instFIS sqrt_instFIS}.
Context `{!refines (eqFIS ==> eqFIS ==> eqFIS) add_instFIS add_instFIS}.
Context `{!refines (eqFIS ==> eqFIS ==> eqFIS) mul_instFIS mul_instFIS}.
Context `{!refines (eqFIS ==> eqFIS ==> eqFIS) div_instFIS div_instFIS}.
Context `{ref_fin : !refines (eqFIS ==> bool_R) (@finite fs) (@finite fs)}.
Context `{!refines (eqFIS ==> eqFIS ==> bool_R) eq_instFIS eq_instFIS}.
Context `{!refines (eqFIS ==> eqFIS ==> bool_R) leq_instFIS leq_instFIS}.
Context `{!refines (eqFIS ==> eqFIS ==> bool_R) lt_instFIS lt_instFIS}.
Context `{!refines (eqFIS ==> eqFIS ==> eqFIS) addup_instFIS addup_instFIS}.
Context `{!refines (eqFIS ==> eqFIS ==> eqFIS) subdn_instFIS subdn_instFIS}.
Context `{!refines (eqFIS ==> eqFIS ==> eqFIS) mulup_instFIS mulup_instFIS}.
Context `{!refines (eqFIS ==> eqFIS ==> eqFIS) divup_instFIS divup_instFIS}.
Context `{!refines (nat_R ==> eqFIS) nat2Fup_instFIS nat2Fup_instFIS}.
Hypothesis eqFIS_P : forall x y, reflect (eqFIS x y) (eq_instFIS x y).
(* TODO: refactor sections, remove "@", "_", etc. *)
Variables (F : Type) (F2FIS : F -> FIS fs) (toR : F -> R).
Hypothesis (F2FIS_correct : forall f, finite (F2FIS f) -> FIS2FS (F2FIS f) = toR f :> R).
Section rn.
Context {n1 n2 : nat} {rn : nat_R n1.+1 n2.+1}.
Global Instance refine_stilde_seqmx :
refines (nat_R ==> eqFIS ==> list_R eqFIS ==> list_R eqFIS ==> eqFIS)
stilde_seqmx stilde_seqmx.
Proof.
ref_abstr => k k' ref_k.
ref_abstr => c c' ref_c.
ref_abstr => a0 a0' ref_a.
ref_abstr => b0 b0' ref_b.
elim: k k' ref_k c c' ref_c a0 a0' ref_a b0 b0' ref_b =>
[ |k IHk] k' ref_k c c' ref_c a0 a0' ref_a b0 b0' ref_b.
{ rewrite refinesE in ref_k; move/nat_R_eq: ref_k => <- //. }
rewrite refinesE in ref_k; move/nat_R_eq: ref_k => <- /=.
rewrite refinesE in ref_a ref_b.
case: ref_a => [ |a1 a1' Ha1 a2 a2' Ha2]; tc.
case: ref_b => [ |b1 b1' Hb1 b2 b2' Hb2]; tc.
apply IHk.
by rewrite refinesE; exact: nat_Rxx.
refines_apply.
by rewrite refinesE.
by rewrite refinesE.
Qed.
Global Instance refine_dotmulB0_seqmx :
refines (Rordn (n1 := n1) ==> eqFIS ==> list_R (list_R eqFIS) ==> list_R (list_R eqFIS) ==> eqFIS)
(dotmulB0_seqmx (n := n1.+1)) (dotmulB0_seqmx (n := n1.+1)).
Proof.
eapply refines_abstr => k k' ref_k.
eapply refines_abstr => c c' ref_c.
eapply refines_abstr => a0 a0' ref_a.
eapply refines_abstr => b0 b0' ref_b.
rewrite !refinesE in ref_k ref_a ref_b ref_c.
red in ref_k; rewrite -(proj1 ref_k); clear ref_k.
(* rewrite refinesE=> k _ <- c _ <- _ _ [a a' ha1 ha2 ha3] _ _ [b b' hb1 hb2 hb3]. *)
rewrite /dotmulB0_seqmx.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
by rewrite refinesE; exact: nat_Rxx.
param head_R.
by rewrite refinesE.
param head_R.
by rewrite refinesE.
Qed.
Lemma refine_ytilded_seqmx :
refines (Rordn (n1 := n1) ==> eqFIS ==> list_R (list_R eqFIS) ==> list_R (list_R eqFIS) ==> eqFIS ==> eqFIS)
(ytilded_seqmx (n := n1)) (ytilded_seqmx (n := n1)).
Proof.
refines_abstr.
rewrite /ytilded_ssr /ytilded_seqmx /ytilded.
refines_apply.
Qed.
Global Instance refine_ytildes_seqmx :
refines (Rordn (n1 := n1) ==> eqFIS ==> list_R (list_R eqFIS) ==> eqFIS)
(ytildes_seqmx (n := n1)) (ytildes_seqmx (n := n1)).
Proof.
refines_abstr.
rewrite /ytildes_seqmx /ytildes.
refines_apply.
Qed.
Global Instance refine_inner_loop_seqmx :
refines ((Rordn (n1 := n1)) ==> list_R (list_R eqFIS) ==> list_R (list_R eqFIS) ==> list_R (list_R eqFIS))
(inner_loop_seqmx (n := n1)) (inner_loop_seqmx (n := n1)).
Proof.
rewrite refinesE=> j j' rj a a' ra r r' rr.
rewrite /inner_loop_seqmx /inner_loop.
apply refinesP.
refines_apply1.
eapply refines_apply.
eapply refines_apply.
eapply refine_iteri_ord'.
by rewrite /nat_of /nat_of_instN refinesE /Rordn.
refines_abstr.
refines_apply1.
refines_apply1.
eapply refines_apply.
refines_apply1.
{ param store_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)).
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
eapply refines_apply.
eapply refine_ytilded_seqmx. by tc.
refines_apply1.
refines_apply1.
refines_apply1.
rewrite /fun_of_op.
{ param fun_of_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)).
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
refines_apply1.
refines_apply1.
{ param row_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
refines_apply1.
refines_apply1.
{ param row_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
refines_apply1.
refines_apply1.
refines_apply1.
rewrite /fun_of_op.
{ param fun_of_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)).
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
Qed.
(* Copy-paste of multipoly.v *)
Lemma composable_imply_id2 :
forall (A B A' B' C' : Type) (rAB : A -> B -> Type) (R1 : A' -> B' -> Type)
(R2 : B' -> C' -> Type) (R3 : A' -> C' -> Type),
composable R1 R2 R3 -> composable (rAB ==> R1)%rel (eq ==> R2)%rel (rAB ==> R3)%rel
.
Proof.
intros A0 B A' B' C' rAB R1 R2 R3.
rewrite !composableE => R123 fA fC [fB [RfAB RfBC]] a c rABac.
apply: R123; exists (fB c); split; [ exact: RfAB | exact: RfBC ].
Qed.
Lemma composable_Rordn :
composable (Rord rn) (Rordn (n1 := n1)) (Rord rn).
Proof.
rewrite composableE => a a' [b [H1 [H2 H3]]].
rewrite /Rord in H1 *.
by transitivity b.
Qed.
Instance composable_Rordn_impl :
forall (A' B' C' : Type) (R1 : A' -> B' -> Type) (R2 : B' -> C' -> Type) (R3 : A' -> C' -> Type),
composable R1 R2 R3 ->
composable (Rord rn ==> R1)%rel (Rordn (n1 := n1) ==> R2)%rel (Rord rn ==> R3)%rel.
Proof.
intros A' B' C' R1 R2 R3.
rewrite !composableE => R123 fA fC [fB [RfAB RfBC]] a c rABac.
apply: R123; exists (fB c); split; [ exact: RfAB | ].
apply: RfBC.
red in rABac |- *.
split=>//.
rewrite -rABac.
exact/ltnW/ltn_ord.
Qed.
Global Instance refine_inner_loop' :
refines (Rord rn ==> RseqmxC eqFIS rn rn ==> RseqmxC eqFIS rn rn ==> RseqmxC eqFIS rn rn)
(inner_loop_ssr (n := n1)) (inner_loop_seqmx (n := n2)).
Proof.
refines_trans.
Qed.
Global Instance refine_outer_loop_seqmx :
refines (list_R (list_R eqFIS) ==> list_R (list_R eqFIS) ==> list_R (list_R eqFIS))
(outer_loop_seqmx (n := n1)) (outer_loop_seqmx (n := n1)).
Proof.
rewrite refinesE=> a a' ra r r' rr.
rewrite /outer_loop_seqmx /outer_loop.
apply refinesP; refines_apply1.
refines_apply1.
eapply refines_apply.
apply refine_iteri_ord'.
{ by rewrite refinesE /Rordn. }
refines_abstr.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
rewrite /store_op.
{ param store_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)).
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
rewrite /fun_of_op.
{ param fun_of_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)).
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
refines_apply1.
refines_apply1.
{ param row_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
Qed.
Global Instance refine_cholesky_seqmx :
refines ((list_R (list_R eqFIS)) ==> list_R (list_R eqFIS))
(cholesky_seqmx (n := n1)) (cholesky_seqmx (n := n1)).
Proof.
rewrite /cholesky_seqmx /cholesky -[outer_loop]/(outer_loop_seqmx).
refines_abstr.
Qed.
Global Instance refine_trmx_seqmx m n :
refines (list_R (list_R eqFIS) ==> list_R (list_R eqFIS))
(@trmx_seqmx (@FIS fs) m n) (@trmx_seqmx (@FIS fs) m n).
Proof.
ref_abstr => a a' ref_a.
rewrite !refinesE in ref_a *.
rewrite /trmx_seqmx /trseqmx.
case: ifP => H.
apply nseq_R =>//.
apply: nat_Rxx.
eapply (foldr_R (T_R := list_R eqFIS)) =>//.
apply zipwith_R.
by constructor.
apply: nseq_R =>//.
exact: nat_Rxx.
Qed.
Existing Instance Rseqmx_trseqmx.
Global Instance refine_is_sym :
refines (Rseqmx rn rn ==> bool_R)
(@is_sym _ _ n1.+1 (@heq_ssr (FIS fs) (@fieq fs)) (@trmx _))
(@is_sym _ _ n2.+1 _ trmx_seqmx).
Proof. rewrite refinesE=> a a' ra; rewrite /is_sym; exact: refinesP. Qed.
Global Instance refine_heq_seqmx m n :
refines (list_R (list_R eqFIS) ==> list_R (list_R eqFIS) ==> bool_R)
(heq_seqmx (m := m) (n := n))
(heq_seqmx (m := m) (n := n)).
Proof.
refines_abstr.
rewrite refinesE.
eapply (eq_seq_R (T_R := list_R eqFIS)).
intros; apply (eq_seq_R (T_R := eqFIS)).
move=> x y H z t H'.
suff_eq bool_Rxx.
apply/eqFIS_P/eqFIS_P; by rewrite H H'.
done.
done.
exact: refinesP.
exact: refinesP.
Qed.
Global Instance refine_is_sym_seqmx n1' :
refines (list_R (list_R eqFIS) ==> bool_R)
(@is_sym _ _ n1'.+1 (@heq_seqmx (FIS fs) (@fieq fs)) trmx_seqmx)
(@is_sym _ _ n1'.+1 (@heq_seqmx (FIS fs) (@fieq fs)) trmx_seqmx) | 99.
Proof.
refines_abstr.
rewrite /is_sym /trmx_op /heq_op.
refines_apply1.
Qed.
Global Instance refine_is_sym' :
refines (RseqmxC eqFIS rn rn ==> bool_R)
(@is_sym _ _ n1.+1 (@heq_ssr (FIS fs) (@fieq fs)) (@trmx _))
(@is_sym _ _ n2.+1 (@heq_seqmx (FIS fs) (@fieq fs)) trmx_seqmx) | 99.
Proof.
refines_trans.
Qed.
Global Instance refine_fun_op_FIS :
refines (list_R (list_R eqFIS) ==> nat_R ==> nat_R ==> eqFIS)
(@fun_of_seqmx (FIS fs) (FIS0 fs) n1.+1 n1.+1)
(@fun_of_seqmx (FIS fs) (FIS0 fs) n2.+1 n2.+1).
Proof.
rewrite /fun_of_seqmx.
refines_abstr.
rewrite refinesE.
apply nth_R.
reflexivity.
apply nth_R =>//; exact: refinesP.
exact: refinesP.
Qed.
Global Instance refine_foldl_diag T' :
refines (eq ==> eq ==> Rseqmx rn rn ==> eq)
(@foldl_diag _ _ matrix (@fun_of_ssr (FIS fs)) n1.+1
(@I0_ssr n1) (@succ0_ssr n1) T')
(@foldl_diag _ _ (@hseqmx) (@fun_of_seqmx (FIS fs) (FIS0 fs)) n2.+1
(@I0_instN n2) (@succ0_instN n2) T').
Proof.
ref_abstr => f f' ref_f.
ref_abstr => a a' ref_a.
ref_abstr => b b' ref_b.
rewrite /foldl_diag.
refines_apply1; first refines_apply1; first refines_apply1.
{ by rewrite -(nat_R_eq rn) refinesE. }
rewrite refinesE=> i i' ref_i x x' ref_x.
apply refinesP; refines_apply.
rewrite refinesE =>??-> ??->.
by rewrite (refines_eq ref_f).
Qed.
Global Instance refine_foldl_diag_seqmx T' n1' :
forall eqf : T' -> T' -> Type,
refines ((eqf ==> eqFIS ==> eqf) ==> eqf ==> list_R (list_R eqFIS) ==> eqf)
(@foldl_diag _ _ (@hseqmx) (@fun_of_seqmx (FIS fs) (FIS0 fs)) n1'.+1
(@I0_instN n1') (@succ0_instN n1') T')
(@foldl_diag _ _ (@hseqmx) (@fun_of_seqmx (FIS fs) (FIS0 fs)) n1'.+1
(@I0_instN n1') (@succ0_instN n1') T').
Proof.
move=> eqf.
ref_abstr => a a' ref_a.
ref_abstr => b b' ref_b.
refines_abstr.
refines_apply.
ref_abstr => c c' ref_c.
ref_abstr => d d' ref_d.
refines_abstr.
rewrite /foldl_diag.
refines_apply1.
refines_apply1.
refines_apply1.
by rewrite refinesE /Rordn; split.
refines_abstr.
do 4!refines_apply1.
rewrite /fun_of_op.
{ param fun_of_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1')).
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1')). }
Qed.
Global Instance refine_foldl_diag' T' :
forall eqf : T' -> T' -> Type,
refines ((eqf ==> eqFIS ==> eqf) ==> eqf ==> RseqmxC eqFIS rn rn ==> eqf)
(@foldl_diag _ _ matrix (@fun_of_ssr (FIS fs)) n1.+1
(@I0_ssr n1) (@succ0_ssr n1) T')
(@foldl_diag _ _ (@hseqmx) (@fun_of_seqmx (FIS fs) (FIS0 fs)) n2.+1
(@I0_instN n2) (@succ0_instN n2) T').
Proof.
move=> eqf.
refines_trans.
Qed.
Global Instance refine_all_diag :
refines (eq ==> Rseqmx rn rn ==> bool_R)
(@all_diag _ _ _ (@fun_of_ssr _) n1.+1 (@I0_ssr n1) (@succ0_ssr n1))
(@all_diag _ _ (@hseqmx)
(@fun_of_seqmx _ (@zero_instFIS fs)) n2.+1 (@I0_instN n2)
(@succ0_instN n2)).
Proof.
rewrite refinesE=> f _ <- a a' ra; rewrite /all_diag.
apply refinesP; refines_apply1.
refines_apply1.
eapply refines_apply. (*!*)
(* Fail eapply refine_foldl_diag. *)
ref_abstr => x x' Hx.
ref_abstr => y y' /refinesP Hy.
ref_abstr => z z' Hz.
rewrite refinesE.
suff_eq bool_Rxx.
eapply refinesP.
eapply refines_apply. (*!*)
eapply refines_apply.
eapply refines_apply.
eapply refine_foldl_diag.
eapply Hx.
by apply refines_bool_eq; rewrite refinesE.
tc.
by rewrite refinesE.
Qed.
Global Instance refine_all_diag_seqmx n1' :
refines ((eqFIS ==> bool_R) ==> list_R (list_R eqFIS) ==> bool_R)
(@all_diag _ _ (@hseqmx)
(@fun_of_seqmx _ (@zero_instFIS fs)) n1'.+1 (@I0_instN n1')
(@succ0_instN n1'))
(@all_diag _ _ (@hseqmx)
(@fun_of_seqmx _ (@zero_instFIS fs)) n1'.+1 (@I0_instN n1')
(@succ0_instN n1')).
Proof.
rewrite /all_diag.
ref_abstr => x x' Hx.
ref_abstr => f f' Hf.
refines_apply.
ref_abstr=> a a' Ha.
ref_abstr=> b b' /refinesP Hb.
rewrite refinesE.
suff_eq bool_Rxx; congr andb.
by eapply refinesP, refines_bool_eq.
eapply refinesP, refines_bool_eq.
refines_apply.
Qed.
Global Instance refine_all_diag' :
refines ((eqFIS ==> bool_R) ==> RseqmxC eqFIS rn rn ==> bool_R)
(@all_diag _ _ _ (@fun_of_ssr _) n1.+1 (@I0_ssr n1) (@succ0_ssr n1))
(@all_diag _ _ (@hseqmx)
(@fun_of_seqmx _ (@zero_instFIS fs)) n2.+1 (@I0_instN n2)
(@succ0_instN n2)) | 100.
Proof.
refines_trans.
Qed.
Global Instance refine_max_diag :
refines (Rseqmx rn rn ==> eq)
(@max_diag _ _ _ (FIS0 fs)
(@fun_of_ssr (FIS fs)) n1.+1 (@I0_ssr n1) (@succ0_ssr n1)
(@leq_instFIS fs))
(@max_diag _ _ (@hseqmx) (FIS0 fs)
(@fun_of_seqmx (FIS fs) (FIS0 fs)) n2.+1 (@I0_instN n2)
(@succ0_instN n2) leq_instFIS).
Proof.
rewrite refinesE=> a a' ra; rewrite /max_diag.
apply refinesP; refines_apply1.
eapply refines_apply. (*!*)
eapply refines_apply.
eapply refine_foldl_diag.
by rewrite refinesE.
by rewrite refinesE.
Qed.
Global Instance refine_compute_c_aux :
refines (Rseqmx rn rn ==> eq ==> eq)
(@compute_c_aux _ _ _ (FIS0 fs) (FIS1 fs) (@fiopp fs)
(@fun_of_ssr (FIS fs)) n1.+1
(@I0_ssr n1) (@succ0_ssr n1) (@fiplus_up fs) (@fimult_up fs) (@fidiv_up fs)
(float_of_nat_up fs) (fieps fs) (fieta fs))
(@compute_c_aux _ _ (@hseqmx) (FIS0 fs) (FIS1 fs) (@fiopp fs)
(@fun_of_seqmx (FIS fs) (FIS0 fs)) n2.+1
(@I0_instN n2) (@succ0_instN n2) (@fiplus_up fs) (@fimult_up fs) (@fidiv_up fs)
(float_of_nat_up fs) (fieps fs) (fieta fs)).
Proof.
rewrite refinesE=> a a' ra x _ <-; rewrite /compute_c_aux.
set ta := tr_up a; set ta' := tr_up a'.
have <- : ta = ta'; [ |by rewrite -(nat_R_eq rn)].
rewrite /ta /ta' /tr_up; apply refinesP.
refines_apply1.
eapply refines_apply. (*!*)
eapply refines_apply.
eapply refine_foldl_diag.
by rewrite refinesE.
by rewrite refinesE.
Qed.
Global Instance refine_compute_c_aux_seqmx n1' :
refines (eqFIS ==> eqFIS ==> list_R (list_R eqFIS) ==> eqFIS ==> eqFIS)
(compute_c_aux (ord := ord_instN) (mx := @hseqmx) (n := n1'.+1) (T := FIS fs))
(compute_c_aux (ord := ord_instN) (mx := @hseqmx) (n := n1'.+1) (T := FIS fs)).
Proof.
ref_abstr => a a' ref_a.
ref_abstr => b b' ref_b.
ref_abstr => c c' ref_c.
ref_abstr => d d' ref_d.
rewrite /compute_c_aux.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
apply trivial_refines; reflexivity.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
eapply refines_apply.
tc.
rewrite refinesE.
exact: nat_Rxx.
refines_apply1.
rewrite /tr_up.
refines_abstr.
refines_apply1.
refines_apply1.
eapply refines_apply.
eapply refines_apply.
tc.
eapply refines_apply.
eapply refines_apply.
tc.
eapply refines_apply.
tc.
apply trivial_refines; exact: nat_Rxx.
tc.
apply trivial_refines; reflexivity.
eapply refines_apply.
eapply refines_apply.
tc.
apply trivial_refines; reflexivity.
tc.
Qed.
Global Instance refine_compute_c_aux' :
refines (RseqmxC eqFIS rn rn ==> eqFIS ==> eqFIS)
(@compute_c_aux _ _ _ (FIS0 fs) (FIS1 fs) (@fiopp fs)
(@fun_of_ssr (FIS fs)) n1.+1
(@I0_ssr n1) (@succ0_ssr n1) (@fiplus_up fs) (@fimult_up fs) (@fidiv_up fs)
(float_of_nat_up fs) (fieps fs) (fieta fs))
(@compute_c_aux _ _ (@hseqmx) (FIS0 fs) (FIS1 fs) (@fiopp fs)
(@fun_of_seqmx (FIS fs) (FIS0 fs)) n2.+1
(@I0_instN n2) (@succ0_instN n2) (@fiplus_up fs) (@fimult_up fs) (@fidiv_up fs)
(float_of_nat_up fs) (fieps fs) (fieta fs)).
Proof.
refines_trans.
(* some arguments are the same in both applications *)
eapply refines_apply.
eapply refines_apply. tc.
by rewrite refinesE; reflexivity.
by rewrite refinesE; reflexivity.
Qed.
Global Instance refine_compute_c :
refines (Rseqmx rn rn ==> eq)
(@compute_c (FIS fs) _ _
(@zero_instFIS fs) (@one_instFIS fs) (@opp_instFIS fs)
(@fun_of_ssr (FIS fs)) n1.+1 (@I0_ssr n1)
(@succ0_ssr n1) (@leq_instFIS fs) (@lt_instFIS fs) (@fiplus_up fs) (@fimult_up fs) (@fidiv_up fs)
(float_of_nat_up fs) (fieps fs) (fieta fs) (@finite fs))
(@compute_c _ _ (@hseqmx)
zero_instFIS one_instFIS opp_instFIS
(@fun_of_seqmx _ zero_instFIS) n2.+1 (@I0_instN n2)
(@succ0_instN n2) leq_instFIS lt_instFIS (@fiplus_up fs) (@fimult_up fs) (@fidiv_up fs)
(float_of_nat_up fs) (fieps fs) (fieta fs) (@finite fs)).
Proof.
rewrite refinesE=> a a' ra; rewrite /compute_c.
set ca := compute_c_aux _ _ a _.
set ca' := compute_c_aux _ _ a' _.
have <- : ca = ca'; [by exact: refinesP| ].
by rewrite -(nat_R_eq rn).
Qed.
Global Instance refine_compute_c_seqmx :
refines (eqFIS ==> eqFIS ==> (eqFIS ==> bool_R) ==> list_R (list_R eqFIS) ==> option_R eqFIS)
(compute_c (ord := ord_instN) (mx := @hseqmx) (n := n1.+1))
(compute_c (ord := ord_instN) (mx := @hseqmx) (n := n1.+1)).
Proof.
ref_abstr => x x' Hx.
ref_abstr => y y' Hy.
ref_abstr => z z' Hz.
ref_abstr => a a' ra.
rewrite /compute_c.
set ca := compute_c_aux _ _ a _.
set ca' := compute_c_aux _ _ a' _.
(* suff_eq option_Rxx.
intros; reflexivity. *)
have ref_ca: refines eqFIS ca ca'.
{ refines_apply1.
refines_apply1.
eapply refines_apply (*!*).
rewrite /max_diag.
refines_abstr.
refines_apply.
rewrite /max.
refines_abstr.
set le1 := (_ <= _)%C; set le2 := (_ <= _)%C.
have ->: le1 = le2.
rewrite /le1 /le2; eapply refinesP, refines_bool_eq; refines_apply.
by case: le2.
tc. }
rewrite ifE; apply refines_if_expr; first (rewrite refinesE; suff_eq bool_Rxx).
congr andb.
{ eapply refinesP, refines_bool_eq.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
by rewrite refinesE; exact: nat_Rxx. }
{ eapply refinesP, refines_bool_eq.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
by rewrite refinesE; exact: nat_Rxx. }
{ move=> _ _.
eapply refinesP; apply refines_if_expr.
by eapply refines_apply; tc.
move=> _ _.
constructor.
by apply refinesP.
move=> *; constructor; done. }
move=> _ _.
constructor.
Qed.
Global Instance refine_compute_c' :
refines (RseqmxC eqFIS rn rn ==> option_R eqFIS)
(@compute_c (FIS fs) _ _
(@zero_instFIS fs) (@one_instFIS fs) (@opp_instFIS fs)
(@fun_of_ssr (FIS fs)) n1.+1 (@I0_ssr n1)
(@succ0_ssr n1) (@leq_instFIS fs) (@lt_instFIS fs) (@fiplus_up fs) (@fimult_up fs) (@fidiv_up fs)
(float_of_nat_up fs) (fieps fs) (fieta fs) (@finite fs))
(@compute_c _ _ (@hseqmx)
zero_instFIS one_instFIS opp_instFIS
(@fun_of_seqmx _ zero_instFIS) n2.+1 (@I0_instN n2)
(@succ0_instN n2) leq_instFIS lt_instFIS (@fiplus_up fs) (@fimult_up fs) (@fidiv_up fs)
(float_of_nat_up fs) (fieps fs) (fieta fs) (@finite fs)).
Proof.
refines_trans.
rewrite refinesE=> a a' ra; rewrite /compute_c.
set ca := compute_c_aux _ _ a _.
set ca' := compute_c_aux _ _ a' _.
case: finite =>//=.
case: (addup _ _ < 0)%C =>//.
2: constructor.
2: constructor.
have ref_ca: refines eqFIS ca ca'.
{ refines_apply1.
refines_apply1.
eapply refines_apply (*!*).
rewrite /max_diag.
refines_abstr.
refines_apply.
rewrite refinesE; reflexivity.
rewrite refinesE; reflexivity.
rewrite /max_diag.
refines_apply.
rewrite /max.
refines_abstr.
set le1 := (_ <= _)%C; set le2 := (_ <= _)%C.
have ->: le1 = le2.
rewrite /le1 /le2; eapply refinesP, refines_bool_eq; refines_apply.
by case: le2. }
have->: finite ca = finite ca'.
{ eapply refinesP, refines_bool_eq; refines_apply. }
case: finite =>//; constructor.
exact: refinesP.
Qed.
Global Instance refine_map_diag :
refines ((eq ==> eq) ==> Rseqmx rn rn ==> Rseqmx rn rn)
(@map_diag _ _ _
(@fun_of_ssr (FIS fs)) (@store_ssr (FIS fs)) n1.+1
(@I0_ssr n1) (@succ0_ssr n1))
(@map_diag _ _ (@hseqmx)
(@fun_of_seqmx _ zero_instFIS) (@store_seqmx _) n2.+1
(@I0_instN n2) (@succ0_instN n2)).
Proof.
rewrite refinesE=> f f' rf a a' ra; rewrite /map_diag.
apply refinesP; refines_apply1; first refines_apply1; first refines_apply1.
by rewrite -(nat_R_eq rn) refinesE.
rewrite refinesE=> i i' ri b b' rb.
exact: refinesP.
Unshelve.
exact: rn.
Qed.
Global Instance refine_posdef_check :
refines (Rseqmx rn rn ==> bool_R)
(@posdef_check_ssr fs n1)
(posdef_check_seqmx (n:=n2) (fieps fs) (fieta fs) (@finite fs)).
Proof.
rewrite refinesE=> a a' ra.
rewrite /posdef_check_ssr /posdef_check_seqmx /posdef_check.
suff_eq bool_Rxx.
f_equal.
{ by rewrite -(nat_R_eq rn). }
f_equal.
{ exact: refinesP. }
f_equal.
{ rewrite /noneg_diag; apply refinesP, refines_bool_eq. (*:-*)
eapply refines_apply. (*!*)
eapply refines_apply.
eapply refine_all_diag. 2: tc.
by rewrite refinesE. }
set c := compute_c _ _ _ a.
set c' := compute_c _ _ _ a'.
have <- : c = c'; [by exact: refinesP| ]; case c=>// m.
set r := cholesky _; set r' := cholesky _.
suff rr : refines (Rseqmx (H:=FIS0 fs) rn rn) r r'.
{ f_equal; rewrite/pos_diag; apply refinesP, refines_bool_eq.
eapply refines_apply. (*!*)
eapply refines_apply.
eapply refine_all_diag. 2: tc.
by rewrite refinesE.
refines_apply1.
refines_apply1.
by rewrite refinesE. }
by refines_apply; rewrite refinesE=> f _ <-.
Qed.
Lemma refine_posdef_check_itv_aux :
refines (Rseqmx rn rn ==> eq ==> bool_R)
(@posdef_check_itv_ssr fs n1)
(posdef_check_itv_seqmx (n:=n2) (fieps fs) (fieta fs) (@finite fs)).
Proof.
ref_abstr => a a' ref_a'.
ref_abstr => r r' ref_r'.
rewrite refinesE; suff_eq bool_Rxx.
rewrite /posdef_check_itv_ssr /posdef_check_itv_seqmx /posdef_check_itv.
do 2?congr andb.
{ by rewrite (refines_eq ref_r'). }
{ eapply refines_eq, refines_bool_eq.
eapply refines_apply. (*!*)
2: exact: ref_r'.
rewrite refinesE => g g' ref_g; rewrite ref_g; exact: bool_Rxx. }
rewrite /posdef_check.
f_equal.
{ by rewrite -(nat_R_eq rn). }
set b := map_diag _ a; set b' := map_diag _ a'.
suff rb : refines (Rseqmx (H:=FIS0 fs) rn rn) b b'.
{ f_equal.
{ exact: refinesP. }
f_equal.
{ rewrite /noneg_diag. apply refinesP, refines_bool_eq.
refines_apply1.
refines_apply1.
by rewrite refinesE. }
set c := compute_c _ _ _ b.
set c' := compute_c _ _ _ b'.
have <- : c = c'; [by exact: refinesP| ]; case c=>// m.
set d := cholesky _; set d' := cholesky _.
suff rd : refines (Rseqmx (H:=FIS0 fs) rn rn) d d'.
{ f_equal; rewrite/pos_diag; apply refinesP, refines_bool_eq.
(*!*) eapply refines_apply.
eapply refines_apply.
eapply refine_all_diag.
by rewrite refinesE.
refines_apply1. refines_apply1. refines_apply1.
by rewrite refinesE => ??->.
eapply refines_apply.
eapply refines_apply.
eapply refine_all_diag.
by rewrite refinesE. done. }
by refines_apply; rewrite refinesE=> f _ <-. }
refines_apply1.
refines_apply1.
rewrite (refines_eq ref_r').
rewrite refinesE => ??->.
by rewrite -(nat_R_eq rn).
Qed.
End rn.
Global Instance refine_posdef_check_itv n :
refines (Rseqmx (nat_Rxx n.+1) (nat_Rxx n.+1) ==> eq ==> bool_R)
(@posdef_check_itv_ssr fs n)
(posdef_check_itv_seqmx (n:=n) (fieps fs) (fieta fs) (@finite fs)).
Proof.
ref_abstr => Q Q' ref_Q.
ref_abstr => r r' ref_r.
eapply refines_apply; [refines_apply|tc].
exact: refine_posdef_check_itv_aux.
Qed.
Definition map_diag_seqmx {n} :=
@map_diag _ _ (@hseqmx)
(@fun_of_seqmx _ (@zero_instFIS fs)) (@store_seqmx _) n.+1
(@I0_instN n) (@succ0_instN n).
Global Instance refine_map_diag_seqmx n1 :
refines ((eqFIS ==> eqFIS) ==> list_R (list_R eqFIS) ==> list_R (list_R eqFIS))
(map_diag_seqmx (n := n1))
(map_diag_seqmx (n := n1)).
Proof.
rewrite /map_diag_seqmx /map_diag.
refines_abstr.
eapply refines_apply.
eapply refines_apply.
eapply refines_apply.
eapply refine_iteri_ord'.
by rewrite refinesE /Rordn.
(* store *)
rewrite /cholesky.
refines_abstr; refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
rewrite /store_op.
{ param store_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)).
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
rewrite /fun_of_op.
{ param fun_of_seqmx_R.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => n n' ref_n.
rewrite !refinesE in ref_n *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)).
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n1)). }
done.
Qed.
Global Instance refine_posdef_check_seqmx n1 :
refines (list_R (list_R eqFIS) ==> bool_R)
(posdef_check_seqmx (n:=n1) (fieps fs) (fieta fs) (@finite fs))
(posdef_check_seqmx (n:=n1) (fieps fs) (fieta fs) (@finite fs)).
Proof.
rewrite /posdef_check_seqmx.
refines_apply1.
eapply refines_apply.
eapply refines_apply.
{ (*
refines (?R0 ==> ?R ==> (eqFIS ==> bool_R) ==> list_R (list_R eqFIS) ==> bool_R) posdef_check
posdef_check
*)
ref_abstr => x x' Hx.
ref_abstr => y y' Hy.
ref_abstr => f f' Hf.
ref_abstr => s s' Hs.
rewrite /posdef_check.
rewrite refinesE; suff_eq bool_Rxx.
congr [&& _ && _ , _, _ & _].
{ eapply refinesP, refines_bool_eq.
eapply refines_apply. tc.
eapply refines_apply.
eapply refines_apply. tc.
eapply refines_apply.
eapply refines_apply. tc.
rewrite refinesE; reflexivity.
rewrite refinesE; reflexivity.
tc. }
{ eapply refinesP, refines_bool_eq.
eapply refines_apply.
eapply refines_apply. tc.
eapply refines_apply.
eapply refines_apply. tc.
eapply refines_apply.
eapply refines_apply. tc.
rewrite refinesE; reflexivity.
rewrite refinesE; reflexivity.
tc.
rewrite refinesE; reflexivity. }
{ eapply refinesP, refines_bool_eq.
refines_apply. }
{ rewrite /noneg_diag.
apply refinesP, refines_bool_eq.
refines_apply1.
eapply refines_apply. (*!*)
eapply refine_all_diag_seqmx.
refines_apply. }
{ set c1 := compute_c _ _ _ _.
set c2 := compute_c _ _ _ _.
rewrite !optionE.
eapply refinesP, refines_bool_eq; refines_apply.
refines_abstr.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
by refines_abstr.
{ rewrite /pos_diag.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
by refines_abstr. } } }
rewrite refinesE; reflexivity.
rewrite refinesE; reflexivity.
Qed.
Global Instance refine_posdef_check_itv_seqmx n :
refines (list_R (list_R eqFIS) ==> eqFIS ==> bool_R)
(posdef_check_itv_seqmx (n:=n) (fieps fs) (fieta fs) (@finite fs))
(posdef_check_itv_seqmx (n:=n) (fieps fs) (fieta fs) (@finite fs)).
Proof.
refines_abstr.
rewrite refinesE.
suff_eq bool_Rxx.
rewrite /posdef_check_itv_seqmx.
rewrite /posdef_check_itv.
congr [&& _ , _ & _].
{ apply refinesP, refines_bool_eq.
refines_apply. }
{ apply refinesP, refines_bool_eq.
refines_apply. }
eapply refinesP, refines_bool_eq.
refines_apply1.
rewrite /map_diag.
refines_apply1.
refines_apply1.
refines_apply1.
by rewrite refinesE.
{ (* could be extracted to some lemma *)
refines_abstr; rewrite refinesE /store_op.
eapply store_seqmx_R.
exact: nat_Rxx.
exact: nat_Rxx.
exact: refinesP.
by suff_eq nat_Rxx; eapply refinesP, refines_Rordn_eq; tc.
by suff_eq nat_Rxx; eapply refinesP, refines_Rordn_eq; tc.
eapply refinesP.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
refines_apply1.
rewrite /fun_of_op.
{ param fun_of_seqmx_R.
ref_abstr => m m' ref_m.
rewrite !refinesE in ref_m *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
ref_abstr => p p' ref_p.
rewrite !refinesE in ref_p *.
suff_eq nat_Rxx.
congr S; exact: unify_rel.
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n)).
rewrite refinesE; suff_eq nat_Rxx.
exact: (Rordn_eq (n1 := n)). }
refines_apply1.
refines_apply1.
rewrite refinesE; reflexivity. }
Qed.
Global Instance refine_posdef_check' n :
refines (RseqmxC eqFIS (nat_Rxx n.+1) (nat_Rxx n.+1) ==> bool_R)
(@posdef_check_ssr fs n)
(posdef_check_seqmx (n:=n) (fieps fs) (fieta fs) (@finite fs)).
Proof. refines_trans. Qed.
Global Instance refine_posdef_check_itv' n :
refines (RseqmxC eqFIS (nat_Rxx n.+1) (nat_Rxx n.+1) ==> eqFIS ==> bool_R)
(@posdef_check_itv_ssr fs n)
(posdef_check_itv_seqmx (n:=n) (fieps fs) (fieta fs) (@finite fs)).
Proof. refines_trans. Qed.
Definition prec := 53%bigZ.
Definition bigQ2F (q : bigQ) : F.type * F.type :=
let (m, n) :=
match BigQ.red q with
| BigQ.Qz m => (m, 1%bigN)
| BigQ.Qq m n => (m, n)
end in
let m0 := Specific_ops.Float m Bir.exponent_zero in
let n0 := Specific_ops.Float (BigZ.Pos n) Bir.exponent_zero in
(F.div rnd_DN prec m0 n0, F.div rnd_UP prec m0 n0).
End refinement_cholesky_2.
|
module Control.Eff.Internal
import public Control.MonadRec
import public Control.Monad.Free
import public Data.Union
%default total
||| An effectful computation yielding a value
||| of type `t` and supporting the effects listed
||| in `fs`.
public export
Eff : (fs : List (Type -> Type)) -> (t : Type) -> Type
Eff fs t = Free (Union fs) t
||| Lift a an effectful comutation into the `Eff` monad.
export
send : Has f fs => f t -> Eff fs t
send = lift . inj
||| Handle all effectful computations in `m`,
||| returning the underlying free monad.
export
toFree : Eff fs t -> Handler fs m -> Free m t
toFree eff h = mapK (handleAll h) eff
||| Run an effectful computation without overflowing
||| the stack by handling all computations in monad `m`.
export
runEff : MonadRec m => Eff fs t -> Handler fs m -> m t
runEff eff h = foldMap (handleAll h) eff
||| Extract the (pure) result of an effectful computation
||| where all effects have been handled.
export
extract : Eff [] a -> a
extract fr = case toView fr of
Pure val => val
Bind u _ => absurd u
export
handleRelay : (prf : Has f fs)
=> (a -> Eff (fs - f) b)
-> (forall v . f v -> (v -> Eff (fs - f) b) -> Eff (fs - f) b)
-> Eff fs a
-> Eff (fs - f) b
handleRelay fval fcont fr = case toView fr of
Pure val => fval val
Bind x g => case decomp {prf} x of
Left y => assert_total $ lift y >>= handleRelay fval fcont . g
Right y => assert_total $ fcont y (handleRelay fval fcont . g)
export
handleRelayS : (prf : Has f fs)
=> s
-> (s -> a -> Eff (fs - f) b)
-> (forall v . s -> f v -> (s -> v -> Eff (fs - f) b) -> Eff (fs - f) b)
-> Eff fs a
-> Eff (fs - f) b
handleRelayS vs fval fcont fr = case toView fr of
Pure val => fval vs val
Bind x g => case decomp {prf} x of
Left y => assert_total $ lift y >>= handleRelayS vs fval fcont . g
Right y => assert_total $ fcont vs y (\vs2 => handleRelayS vs2 fval fcont . g)
|
InstallMethod(AlgebraicU,
"Simple algebraic of adjoint type",
[IsString,IsPosInt,IsRing],
function(Type,Rank,Ring)
local object,
avarnames;
object:=Objectify(NewType(NewFamily("AlgebraicUFamily"),
IsAttributeStoringRep and
IsChevalleyAdj and
IsAlgebraicU),
rec());
Settype(object,Type);
Setrank(object,Rank);
SetchevalleyAdj(object,ChevalleyAdj(Type,Rank,Ring));
SetBaseRing(object,Ring);
avarnames:=List([1..2*Length(positiveRoots(chevalleyAdj(object)))],i->Concatenation("a_{",String(i),"}"));
Setring(object,PolynomialRing(Ring,avarnames));
SetCharacteristic(object,Characteristic(Ring));
SetlieAlgebra(object,SimpleLieAlgebraTypeA_G(Type,Rank,ring(object)));
SetrootSystem(object,RootSystem(SimpleLieAlgebra(Type,Rank,Integers)));
SetpositiveRoots(object,positiveRoots(rootSystem(object)));
SetallRoots(object,Concatenation(
positiveRoots(rootSystem(object)),
-positiveRoots(rootSystem(object))));
SetweylGroup(object,WeylGroup(rootSystem(object)));
SetA(object,A_rs(object));
SetH(object,Eta(object));
SetN(object,N_rs(object));
SetM(object,M_rsi(object));
SetC(object,C_ijrs(object));
SetName(object,Concatenation("<simple adjoint ",Type,String(Rank),
" in characteristic ",String(Characteristic(Ring)),">"));
return object;
end);
InstallMethod(AlgebraicU,
"Simple algebraic of adjoint type",
[IsChevalleyAdj],
function(sys)
local object,
avarnames;
object:=Objectify(NewType(NewFamily("AlgebraicUFamily"),
IsAttributeStoringRep and
IsChevalleyAdj and
IsAlgebraicU),
rec());
Settype(object,type(sys));
Setrank(object,rank(sys));
avarnames:=List([1..2*Length(positiveRoots(sys))],i->Concatenation("a_{",String(i),"}"));
Setring(object,PolynomialRing(ring(sys),avarnames));
SetCharacteristic(object,Characteristic(sys));
SetlieAlgebra(object,SimpleLieAlgebraTypeA_G(type(object),rank(object),ring(object)));
SetrootSystem(object,rootSystem(sys));
SetpositiveRoots(object,positiveRoots(sys));
SetallRoots(object,allRoots(sys));
SetweylGroup(object,weylGroup(sys));
SetA(object,A(sys));
SetH(object,H(sys));
SetN(object,N(sys));
SetM(object,M(sys));
SetC(object,C(sys));
SetBaseRing(object,ring(sys));
SetchevalleyAdj(object,sys);
SetName(object,Concatenation("<simple adjoint ",type(object),String(rank(object)),
" in characteristic ",String(Characteristic(object)),">"));
return object;
end);
|
Formal statement is: lemma infdist_le2: "a \<in> A \<Longrightarrow> dist x a \<le> d \<Longrightarrow> infdist x A \<le> d" Informal statement is: If $x$ is within distance $d$ of some point in $A$, then the infimum distance of $x$ to $A$ is at most $d$. |
[STATEMENT]
lemma E_closed: "s \<in> S \<Longrightarrow> (s, t) \<in> E \<Longrightarrow> t \<in> S"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>s \<in> S; (s, t) \<in> E\<rbrakk> \<Longrightarrow> t \<in> S
[PROOF STEP]
using K_closed
[PROOF STATE]
proof (prove)
using this:
?s \<in> S \<Longrightarrow> \<Union> (set_pmf ` K ?s) \<subseteq> S
goal (1 subgoal):
1. \<lbrakk>s \<in> S; (s, t) \<in> E\<rbrakk> \<Longrightarrow> t \<in> S
[PROOF STEP]
by (auto simp: E_def) |
As Paul continues to develop a philosophy of the Church, he begins to develop the doctrine of spiritual gifts. He begins by reminding us that they are indeed grace gifts from the ascended Christ. We each have one or more, and none of us deserved them. But since they are from Christ, earned by him and are given for a particular reason – we are to use them wisely and cheerfully. He also lists four leadership gifts – to the exclusion of any others, He does so, however, not to minimize the importance of gifts among the laity, but to magnify them (by showing that the laity are the ones who actually do the yeoman’s work of the ministry – see. v 12). These gifts have at their core the teaching and preaching of the word of God – making the word an essential and necessary part of every pastor/teacher’s responsibilities. It also means that if the laity are to do the work of the ministry rightly, it begins with becoming a people of the word. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.