text
stringlengths 0
3.34M
|
---|
// Copyright (c) 2001-2008 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(BOOST_SPIRIT_KARMA_FUNCTOR_DIRECTOR_APR_01_2007_1041AM)
#define BOOST_SPIRIT_KARMA_FUNCTOR_DIRECTOR_APR_01_2007_1041AM
#include <boost/spirit/home/support/auxiliary/functor_holder.hpp>
#include <boost/spirit/home/support/component.hpp>
#include <boost/spirit/home/karma/domain.hpp>
namespace boost { namespace spirit { namespace karma
{
// this is the director for all functor generators
struct functor_director
{
// expected value type of the generator
template <typename Component, typename Context, typename Unused>
struct attribute
{
typedef typename
result_of::subject<Component>::type::functor_holder
functor_holder;
typedef typename functor_holder::functor_type functor_type;
typedef typename
functor_type::template result<Context>::type
type;
};
// generate functionality, delegates back to the corresponding functor
template <typename Component, typename OutputIterator,
typename Context, typename Delimiter, typename Parameter>
static bool
generate(Component const& component, OutputIterator& sink,
Context& ctx, Delimiter const& d, Parameter const& param)
{
bool result = subject(component).held->generate(sink, ctx, param);
karma::delimit(sink, d); // always do post-delimiting
return result;
}
template <typename Component, typename Context>
static std::string what(Component const& component, Context const& ctx)
{
return "functor";
}
};
}}}
#endif
|
[STATEMENT]
lemma StarLR_Zero[simp]: "StarLR Zero r = Zero"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. StarLR Zero r = Zero
[PROOF STEP]
by coinduction auto |
-- Andreas, 2016-10-03, re issue #2231
-- Testing whether the musical coinduction works fine in abstract blocks
{-# OPTIONS --guardedness #-}
module AbstractCoinduction where
{-# BUILTIN INFINITY ∞_ #-}
{-# BUILTIN SHARP ♯_ #-}
{-# BUILTIN FLAT ♭ #-}
infixr 5 _≺_
abstract
------------------------------------------------------------------------
-- Streams
data Stream (A : Set) : Set where
_≺_ : (x : A) (xs : ∞ (Stream A)) -> Stream A
head : ∀ {A} -> Stream A -> A
head (x ≺ xs) = x
tail : ∀ {A} -> Stream A -> Stream A
tail (x ≺ xs) = ♭ xs
------------------------------------------------------------------------
-- Stream programs
infix 8 _∞
infixr 5 _⋎_
infix 4 ↓_
mutual
data Stream′ (A : Set) : Set1 where
_≺_ : (x : A) (xs : ∞ (StreamProg A)) -> Stream′ A
data StreamProg (A : Set) : Set1 where
↓_ : (xs : Stream′ A) -> StreamProg A
_∞' : (x : A) -> StreamProg A
_⋎'_ : (xs ys : StreamProg A) -> StreamProg A
_∞ : ∀ {A : Set} (x : A) -> StreamProg A
_∞ = _∞'
_⋎_ : ∀ {A : Set} (xs ys : StreamProg A) -> StreamProg A
_⋎_ = _⋎'_
head′ : ∀ {A} → Stream′ A → A
head′ (x ≺ xs) = x
tail′ : ∀ {A} → Stream′ A → StreamProg A
tail′ (x ≺ xs) = ♭ xs
P⇒′ : ∀ {A} -> StreamProg A -> Stream′ A
P⇒′ (↓ xs) = xs
P⇒′ (x ∞') = x ≺ ♯ (x ∞)
P⇒′ (xs ⋎' ys) with P⇒′ xs
P⇒′ (xs ⋎' ys) | xs′ = head′ xs′ ≺ ♯ (ys ⋎ tail′ xs′)
mutual
′⇒ : ∀ {A} -> Stream′ A -> Stream A
′⇒ (x ≺ xs) = x ≺ ♯ P⇒ (♭ xs)
P⇒ : ∀ {A} -> StreamProg A -> Stream A
P⇒ xs = ′⇒ (P⇒′ xs)
------------------------------------------------------------------------
-- Stream equality
infix 4 _≡_ _≈_ _≊_
data _≡_ {a : Set} (x : a) : a -> Set where
≡-refl : x ≡ x
data _≈_ {A} (xs ys : Stream A) : Set where
_≺_ : (x≡ : head xs ≡ head ys) (xs≈ : ∞ (tail xs ≈ tail ys)) ->
xs ≈ ys
_≊_ : ∀ {A} (xs ys : StreamProg A) -> Set
xs ≊ ys = P⇒ xs ≈ P⇒ ys
foo : ∀ {A : Set} (x : A) -> x ∞ ⋎ x ∞ ≊ x ∞
foo x = ≡-refl ≺ ♯ foo x
-- The first goal has goal type
-- head (′⇒ (x ≺ x ∞ ⋎ x ∞)) ≡ head (′⇒ (x ≺ x ∞)).
-- The normal form of the left-hand side is x, and the normal form of
-- the right-hand side is x (both according to Agda), but ≡-refl is
-- not accepted by the type checker:
-- x != head (′⇒ (P⇒′ (x ∞))) of type .A
-- when checking that the expression ≡-refl has type
-- (head (P⇒ (x ∞ ⋎ x ∞)) ≡ head (P⇒ (x ∞)))
|
include("6.7.6 (c+d x)^m hyper(a+b x)^n hyper(a+b x)^p.jl")
include("6.7.7 F^(c (a+b x)) hyper(d+e x)^n.jl")
include("6.7.8 u hyper(a+b log(c x^n))^p.jl")
include("6.7.9 Active hyperbolic functions.jl")
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- An equality postulate which evaluates
------------------------------------------------------------------------
{-# OPTIONS --with-K #-}
module Relation.Binary.PropositionalEquality.TrustMe where
open import Relation.Binary.PropositionalEquality.Core using (_≡_; refl)
open import Agda.Builtin.TrustMe
-- trustMe {x = x} {y = y} evaluates to refl if x and y are
-- definitionally equal.
trustMe : ∀ {a} {A : Set a} {x y : A} → x ≡ y
trustMe = primTrustMe
-- "Erases" a proof. The original proof is not inspected. The
-- resulting proof reduces to refl if the two sides are definitionally
-- equal. Note that checking for definitional equality can be slow.
erase : ∀ {a} {A : Set a} {x y : A} → x ≡ y → x ≡ y
erase _ = trustMe
-- A "postulate with a reduction": postulate[ a ↦ b ] a evaluates to b,
-- while postulate[ a ↦ b ] a' gets stuck if a' is not definitionally
-- equal to a. This can be used to define a postulate of type (x : A) → B x
-- by only specifying the behaviour at B t for some t : A. Introduced in
--
-- Alan Jeffrey, Univalence via Agda's primTrustMe again
-- 23 January 2015
-- https://lists.chalmers.se/pipermail/agda/2015/007418.html
postulate[_↦_] : ∀ {a b} {A : Set a}{B : A → Set b} →
(t : A) → B t → (x : A) → B x
postulate[ a ↦ b ] a' with trustMe {x = a} {a'}
postulate[ a ↦ b ] .a | refl = b
------------------------------------------------------------------------
-- DEPRECATION
------------------------------------------------------------------------
-- Version 0.18
{-# WARNING_ON_USAGE erase
"Warning: erase was deprecated in v0.18.
Please use the safe function ≡-erase defined in Relation.Binary.PropositionalEquality.WithK instead."
#-}
|
####
#### Trajectory
####
@auto_hash_equals struct Trajectory{SS<:AbsVec,OO<:AbsVec,AA<:AbsVec,RR<:AbsVec,ST,OT}
S::SS
O::OO
A::AA
R::RR
sT::ST
oT::OT
done::Bool
@inline function Trajectory{SS,OO,AA,RR,ST,OT}(
S::SS,
O::OO,
A::AA,
R::RR,
sT::ST,
oT::OT,
done::Bool,
) where {SS<:AbsVec,OO<:AbsVec,AA<:AbsVec,RR<:AbsVec,ST,OT}
τ = new(S, O, A, R, sT, oT, done)
checkrep(τ)
return τ
end
end
@inline function Trajectory(
S::SS,
O::OO,
A::AA,
R::RR,
sT::ST,
oT::OT,
done,
) where {SS,OO,AA,RR,ST,OT}
Trajectory{SS,OO,AA,RR,ST,OT}(S, O, A, R, sT, oT, done)
end
@inline function checkrep(τ::Trajectory)
if !(length(τ.S) == length(τ.O) == length(τ.A) == length(τ.R))
throw(DimensionMismatch("Lengths of S, O, A, and R don't match"))
end
return τ
end
Base.length(τ::Trajectory) = (checkrep(τ); length(τ.S))
####
#### TrajectoryBuffer
####
const VoA = AbstractVector{<:AbstractArray}
@auto_hash_equals struct TrajectoryBuffer{SS<:VoA,OO<:VoA,AA<:VoA,RR<:AbstractVector{<:Real}}
S::SS
O::OO
A::AA
R::RR
sT::SS
oT::OO
done::Vector{Bool}
offsets::Vector{Int}
function TrajectoryBuffer(
S::SS,
O::OO,
A::AA,
R::RR,
sT::SS,
oT::OO,
done::Vector{Bool},
offsets::Vector{Int},
) where {SS<:VoA,OO<:VoA,AA<:VoA,RR<:AbstractVector{<:Real}}
Base.require_one_based_indexing(S, O, A, R, sT, oT)
B = new{SS,OO,AA,RR}(S, O, A, R, sT, oT, done, offsets)
checkrep(B)
return B
end
end
function TrajectoryBuffer(
env::AbstractEnvironment;
dtype::Maybe{DataType} = nothing,
sizehint::Integer = 1024,
)
sizehint > 0 || argerror("sizehint must be > 0")
sp = dtype === nothing ? spaces(env) : adapt(dtype, spaces(env))
sizehint_traj = max(1, div(sizehint, 10)) # a heuristic
TrajectoryBuffer(
asvec(ElasticArray(undef, sp.statespace, sizehint)),
asvec(ElasticArray(undef, sp.observationspace, sizehint)),
asvec(ElasticArray(undef, sp.actionspace, sizehint)),
Array(undef, sp.rewardspace, sizehint),
asvec(ElasticArray(undef, sp.statespace, sizehint_traj)),
asvec(ElasticArray(undef, sp.observationspace, sizehint_traj)),
Vector{Bool}(undef, sizehint_traj),
Int[0],
)
end
asvec(A::AbstractArray{<:Any,L}) where {L} = SpecialArrays.slice(A, Val(L-1))
@noinline function checkrep(B::TrajectoryBuffer)
if !(length(B.S) == length(B.O) == length(B.A) == length(B.R))
throw(DimensionMismatch("Lengths of S, O, A, and R do not match"))
end
if !(length(B.sT) == length(B.oT) == length(B.done)) # TODO compare against offsets
throw(DimensionMismatch("Lengths of sT, oT, and done do not match"))
end
length(B.S) < nsamples(B) && error("invalid dimensions")
if !(B.offsets[1] == 0 && all(i -> B.offsets[i-1] < B.offsets[i], 2:ntrajectories(B)))
throw(DimensionMismatch("Invalid offsets"))
end
ntrajectories(B) < 0 && throw(DomainError("length must be > 0"))
return B
end
ntrajectories(B::TrajectoryBuffer) = length(B.offsets) - 1
nsamples(B::TrajectoryBuffer) = B.offsets[ntrajectories(B)+1]
@inline function nsamples(B::TrajectoryBuffer, i::Integer)
@boundscheck checkbounds(Base.OneTo(ntrajectories(B)), i)
B.offsets[i+1] - B.offsets[i]
end
Base.empty!(B::TrajectoryBuffer) = resize!(B.offsets, 1)
function truncate!(B::TrajectoryBuffer)
nsamp = nsamples(B)
ntraj = ntrajectories(B)
resize!(B.S, nsamp)
resize!(B.O, nsamp)
resize!(B.A, nsamp)
resize!(B.R, nsamp)
resize!(B.sT, ntraj)
resize!(B.oT, ntraj)
resize!(B.done, ntraj)
resize!(B.offsets, ntraj + 1)
checkrep(B)
return B
end
"""
$(SIGNATURES)
Rollout the actions computed by `policy!` on `env`, starting at whatever state `env` is currently
in, for `Hmax` timesteps or until `isdone(st, ot, env)` returns `true` and store the resultant
trajectory in `B`. `policy!` should be a function of the form `policy!(at, ot)` which computes an
action given the current observation `ot` and stores it in `at`.
See also: [`TrajectoryBuffer`](@ref), [`rollout`](@ref), [`sample`](@ref), [`sample!`](@ref)
"""
function rollout!(policy!, B::TrajectoryBuffer, env::AbstractEnvironment, Hmax::Integer)
_rollout!(policy!, B, env, convert(Int, Hmax))
truncate!(B)
return B
end
function rollout(policy!, env::AbstractEnvironment, Hmax::Integer)
rollout!(policy!, TrajectoryBuffer(env, sizehint = Hmax), env, Hmax)
end
function _rollout!(
@specialize(policy!),
B::TrajectoryBuffer,
env::AbstractEnvironment,
Hmax::Int,
stopcb = () -> false,
)
Hmax > 0 || argerror("Hmax must be > 0")
@unpack S, O, A, R = B
# pre-allocate for one additional trajectory with a length of Hmax + 1.
# "+1" because of the terminal state/observation
_preallocate_traj!(B, Hmax + 1)
offset = B.offsets[end]
t::Int = 1
done::Bool = false
# get the initial state/observation
st = S[offset+t]
ot = O[offset+t]
getstate!(st, env)
getobservation!(ot, env)
while true
# Abandon the current rollout. Used internally for multithreaded sampling.
stopcb() && return 0
at = A[offset+t]
getaction!(at, env) # Fill at with env's current action for convenience
policy!(at, ot)
R[offset+t] = getreward(st, at, ot, env)
setaction!(env, at)
step!(env)
t += 1
# Get the next state, which may be a terminal state.
st = S[offset+t]
ot = O[offset+t]
getstate!(st, env)
getobservation!(ot, env)
done = isdone(st, ot, env)
# Break *after* we've hit Hmax or isdone returns true. If isdone never returns true,
# then this loop will run for Hmax + 1 iterations.
(t > Hmax || done) && break
end
push!(B.offsets, B.offsets[end] + t - 1)
B.sT[ntrajectories(B)] = S[offset+t]
B.oT[ntrajectories(B)] = O[offset+t]
B.done[ntrajectories(B)] = done
return t - 1
end
function _preallocate_traj!(B::TrajectoryBuffer, H::Int)
nsamp = nsamples(B) + H
ntraj = ntrajectories(B) + 1
if length(B.S) < nsamp
l = nextpow(2, nsamp)
resize!(B.S, l)
resize!(B.O, l)
resize!(B.A, l)
resize!(B.R, l)
end
if length(B.offsets) < ntraj + 2
l = nextpow(2, ntraj + 2)
resize!(B.sT, l)
resize!(B.oT, l)
resize!(B.done, l)
end
checkrep(B)
return B
end
function collate!(dest::TrajectoryBuffer, Bs::AbstractVector{<:TrajectoryBuffer}, n::Integer)
n >= 0 || argerror("n must be ≥ 0")
ns = isempty(Bs) ? 0 : sum(nsamples, Bs)
n <= ns || argerror("n is greater than the number of available samples")
@unpack S, O, A, R, sT, oT, done, offsets = dest
if isempty(Bs) || ns == 0
resize!(S, 0)
resize!(O, 0)
resize!(A, 0)
resize!(R, 0)
resize!(sT, 0)
resize!(oT, 0)
resize!(done, 0)
resize!(offsets, 1)
return dest
end
ntraj = s = 0
for B in Bs, i in eachindex(B.offsets)[1:end-1]
s += B.offsets[i+1] - B.offsets[i]
ntraj += 1
s >= n && break
end
resize!(S, n)
resize!(O, n)
resize!(A, n)
resize!(R, n)
resize!(sT, ntraj)
resize!(oT, ntraj)
resize!(done, ntraj)
resize!(offsets, ntraj + 1)
togo = n
doffs_samp = doffs_traj = 1
for B in Bs
soffs_samp = 1
for soffs_traj = eachindex(B.offsets)[1:end-1]
len = B.offsets[soffs_traj+1] - B.offsets[soffs_traj]
if togo < len
copyto!(S, doffs_samp, B.S, soffs_samp, togo)
copyto!(O, doffs_samp, B.O, soffs_samp, togo)
copyto!(A, doffs_samp, B.A, soffs_samp, togo)
copyto!(R, doffs_samp, B.R, soffs_samp, togo)
sT[doffs_traj] = B.S[soffs_samp + togo]
oT[doffs_traj] = B.O[soffs_samp + togo]
done[doffs_traj] = false
offsets[doffs_traj+1] = offsets[doffs_traj] + togo
togo = 0
else
copyto!(S, doffs_samp, B.S, soffs_samp, len)
copyto!(O, doffs_samp, B.O, soffs_samp, len)
copyto!(A, doffs_samp, B.A, soffs_samp, len)
copyto!(R, doffs_samp, B.R, soffs_samp, len)
sT[doffs_traj] = B.sT[soffs_traj]
oT[doffs_traj] = B.oT[soffs_traj]
done[doffs_traj] = B.done[soffs_traj]
offsets[doffs_traj+1] = offsets[doffs_traj] + len
soffs_samp += len
doffs_samp += len
doffs_traj += 1
togo -= len
end
if togo == 0
checkrep(dest)
return dest
end
end
end
# This shouldn't be reached
internalerror()
end
function StructArrays.StructArray(B::TrajectoryBuffer)
S = BatchedVector(B.S, B.offsets)
O = BatchedVector(B.O, B.offsets)
A = BatchedVector(B.A, B.offsets)
R = BatchedVector(B.R, B.offsets)
sT = B.sT
oT = B.oT
done = B.done
T = Trajectory{eltype(S),eltype(O),eltype(A),eltype(R),eltype(sT),eltype(oT)}
return StructArray{T}((S, O, A, R, sT, oT, done))
end
|
Formal statement is: proposition\<^marker>\<open>tag unimportant\<close> homeomorphism_grouping_points_exists_gen: fixes S :: "'a::euclidean_space set" assumes opeU: "openin (top_of_set S) U" and opeS: "openin (top_of_set (affine hull S)) S" and "U \<noteq> {}" "finite K" "K \<subseteq> S" and S: "S \<subseteq> T" "T \<subseteq> affine hull S" "connected S" obtains f g where "homeomorphism T T f g" "{x. (\<not> (f x = x \<and> g x = x))} \<subseteq> S" "bounded {x. (\<not> (f x = x \<and> g x = x))}" "\<And>x. x \<in> K \<Longrightarrow> f x \<in> U" Informal statement is: Let $S$ be a connected subset of an affine space, and let $U$ be an open subset of $S$. Then there exists a homeomorphism $f$ of $S$ such that $f(x) \in U$ for all $x \in K$, where $K$ is a finite subset of $S$. |
function _precompile_()
ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
@assert precompile(Tuple{typeof(maybe_evaluate_builtin), Frame, Expr, Bool})
@assert precompile(Tuple{typeof(getargs), Vector{Any}, Frame})
@assert precompile(Tuple{typeof(get_call_framecode), Vector{Any}, FrameCode, Int})
@assert precompile(evaluate_call_recurse!, (Function, Frame, Expr))
@assert precompile(evaluate_call_compiled!, (Compiled, Frame, Expr))
for f in (evaluate_structtype,
evaluate_abstracttype,
evaluate_primitivetype)
@assert precompile(Tuple{typeof(f), Any, Frame, Expr})
end
@assert precompile(Tuple{typeof(evaluate_foreigncall), Frame, Expr})
@assert precompile(Tuple{typeof(evaluate_methoddef), Frame, Expr})
@assert precompile(Tuple{typeof(lookup_global_refs!), Expr})
@assert precompile(Tuple{typeof(lookup_or_eval), Any, Frame, Any})
@assert precompile(Tuple{typeof(eval_rhs), Any, Frame, Expr})
@assert precompile(Tuple{typeof(step_expr!), Any, Frame, Any, Bool})
for f in (finish!, finish_and_return!, finish_stack!, next_call!, maybe_next_call!, next_line!)
@assert precompile(Tuple{typeof(f), Any, Frame, Bool})
end
@assert precompile(Tuple{typeof(through_methoddef_or_done!), Any, Frame})
@assert precompile(Tuple{typeof(split_expressions), Module, Expr})
@assert precompile(Tuple{typeof(split_expressions!), Vector{Tuple{Module,Expr}}, Dict{Module,Vector{Expr}}, Expr, Module, Expr})
@assert precompile(Tuple{typeof(prepare_thunk), Module, Expr})
@assert precompile(Tuple{typeof(prepare_thunk), Module, Expr, Bool})
@assert precompile(Tuple{typeof(prepare_framedata), FrameCode, Vector{Any}, SimpleVector, Bool})
@assert precompile(Tuple{typeof(prepare_args), Any, Vector{Any}, Vector{Any}})
@assert precompile(Tuple{typeof(prepare_call), Any, Vector{Any}})
@assert precompile(Tuple{typeof(Core.kwfunc(prepare_call)), NamedTuple{(:enter_generated,),Tuple{Bool}}, typeof(prepare_call), Function, Vector{Any}})
@assert precompile(Tuple{typeof(Core.kwfunc(prepare_framecode)), NamedTuple{(:enter_generated,),Tuple{Bool}}, typeof(prepare_framecode), Method, Tuple{Int}})
@assert precompile(Tuple{typeof(prepare_frame), FrameCode, Vector{Any}, Core.SimpleVector})
@assert precompile(Tuple{typeof(extract_args), Module, Expr})
@assert precompile(Tuple{typeof(enter_call), Int, Int})
@assert precompile(Tuple{typeof(enter_call_expr), Expr})
@assert precompile(Tuple{typeof(copy_codeinfo), Core.CodeInfo})
@assert precompile(Tuple{typeof(optimize!), Core.CodeInfo, Module})
@assert precompile(Tuple{typeof(optimize!), Core.CodeInfo, Method})
@assert precompile(Tuple{typeof(set_structtype_const), Module, Symbol})
@assert precompile(Tuple{typeof(namedtuple), Vector{Any}})
@assert precompile(Tuple{typeof(resolvefc), Frame, Any})
@assert precompile(Tuple{typeof(check_isdefined), Frame, Any})
@assert precompile(Tuple{typeof(find_used), Core.CodeInfo})
@assert precompile(Tuple{typeof(do_assignment!), Frame, Any, Any})
@assert precompile(Tuple{typeof(pc_expr), Frame})
end
|
#include <boost/geometry/arithmetic/dot_product.hpp>
|
%% Copyright (C) 2014, 2016, 2018-2019, 2022 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy 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 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.
%%
%% You should have received a copy of the GNU General Public
%% License along with this software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.
%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defop Method @@sym mtimes {(@var{x}, @var{y})}
%% @defopx Operator @@sym {@var{x} * @var{y}} {}
%% Multiply symbolic matrices.
%%
%% Example:
%% @example
%% @group
%% syms x y
%% A = sym([1 2; 3 4])
%% @result{} A = (sym 2×2 matrix)
%% ⎡1 2⎤
%% ⎢ ⎥
%% ⎣3 4⎦
%% B = [x; y]
%% @result{} B = (sym 2×1 matrix)
%% ⎡x⎤
%% ⎢ ⎥
%% ⎣y⎦
%% A * B
%% @result{} (sym 2×1 matrix)
%% ⎡ x + 2⋅y ⎤
%% ⎢ ⎥
%% ⎣3⋅x + 4⋅y⎦
%% @end group
%% @end example
%% @end defop
function z = mtimes(x, y)
cmd = { '(x,y) = _ins'
'return x*y,' };
z = pycall_sympy__ (cmd, sym(x), sym(y));
end
%!test
%! % scalar
%! syms x
%! assert (isa (x*2, 'sym'))
%! assert (isequal (2*sym(3), sym(6)))
%! assert (isequal (sym(2)*3, sym(6)))
%!test
%! % matrix-scalar
%! D = [0 1; 2 3];
%! A = sym(D);
%! assert (isa (2*A, 'sym'))
%! assert (isequal ( 2*A , 2*D ))
%! assert (isequal ( A*2 , 2*D ))
%!test
%! % matrix-matrix
%! D = [0 1; 2 3];
%! A = sym(D);
%! assert (isa (A*A, 'sym'))
%! assert (isequal ( A*A , D*D ))
|
(***********************************************************************
* HiVe theory files
*
* Copyright (C) 2015 Commonwealth of Australia as represented by Defence Science and Technology
* Group (DST Group)
*
* All rights reserved.
*
* The HiVe theory files are free software: released for redistribution and use, and/or modification,
* under the BSD License, details of which can be found in the LICENSE file included in the
* distribution.
************************************************************************)
theory Order_Instances
imports
Order_Morphism
begin
section {* Axclass matters *}
text {*
We introduce some useful mechanism for discussing orders at the type level.
*}
notation (zed)
less_eq ("\<opleT>") and
less ("\<opltT>")
interpretation type_po: Order_Locale.partial_order "\<univ>-['a::order]" "\<opleT>-['a::order]"
apply (insert default_po [of "\<univ>-['a::order]"])
apply (simp add: default_order_def subset_order_def op2rel_def rel2op_def)
done
interpretation type_order: Order_Locale.order "\<univ>-['a::linorder]" "\<opleT>-['a::linorder]"
apply (insert default_order [of "\<univ>-['b::linorder]"])
apply (simp add: default_order_def subset_order_def op2rel_def rel2op_def)
done
lemma derefl_eq_less:
"derefl \<opleT>-['a::order] = \<opltT>"
apply (intro ext)
apply (simp add: less_le)
done
section {* Booleans *}
instance
bool :: linorder
proof (intro_classes, unfold le_bool_def less_bool_def derefl_def)
fix
x::"\<bool>" and
y::"\<bool>"
show
"(x \<Rightarrow> y) \<or> (y \<Rightarrow> x)"
by (auto)
qed
section {* The unit type *}
instantiation
unit :: linorder
begin
definition
less_eq_unit_def: "\<opleT>-[unit] \<defs> (\<olambda> x y \<bullet> True)"
definition
less_unit_def: "\<opltT>-[unit] \<defs> derefl \<opleT>"
instance
by (intro_classes, auto simp add: less_eq_unit_def less_unit_def)
end
section {* Products *}
text {*
The natural order on a product of ordered sets
is the conjunction of the component orders.
Actually
*}
definition
product_order :: "['a orderT, 'b orderT] \<rightarrow> ('a \<times> 'b) orderT"
where
product_order_def: "product_order BS_leq_d_1 BS_leq_d_2 \<defs> (\<olambda> (x_d_1, x_d_2) (y_d_1, y_d_2) \<bullet> \<^infopa>{:x_d_1:}{:BS_leq_d_1:}{:y_d_1:} \<and> \<^infopa>{:x_d_2:}{:BS_leq_d_2:}{:y_d_2:})"
notation (zed)
product_order ("\<^prodord>{:_:}{:_:}")
instantiation
prod :: (ord, ord) ord
begin
definition
less_eq_prod_def: "\<opleT>-[('a::ord) \<times> ('b::ord)] \<defs> \<^prodord>{:\<opleT>-['a]:}{:\<opleT>-['b]:}"
definition
less_prod_def: "\<opltT>-[('a::ord) \<times> ('b::ord)] \<defs> derefl \<opleT>"
instance
by (intro_classes)
end
lemma le_prod_conv:
"(x_d_1, y_d_1) \<le> (x_d_2, y_d_2) \<Leftrightarrow> x_d_1 \<le> x_d_2 \<and> y_d_1 \<le> y_d_2"
by (simp add: less_eq_prod_def product_order_def)
text {*
The product order preserves order properties of the component spaces.
*}
lemma product_poI:
assumes
a1: "\<^poset>{:X:}{:BS_leq_d_X:}" and a2: "\<^poset>{:Y:}{:BS_leq_d_Y:}"
shows
"\<^poset>{:(X \<times> Y):}{:(\<^prodord>{:BS_leq_d_X:}{:BS_leq_d_Y:}):}"
proof (rule partial_orderI)
from a1 interpret poX: partial_order X BS_leq_d_X
by (simp_all add: Order_Locale.partial_order_def)
from a2 interpret poY: partial_order Y BS_leq_d_Y
by (simp_all add: Order_Locale.partial_order_def)
{
from a1 a2 have
"X \<noteq> \<emptyset>" "Y \<noteq> \<emptyset>"
by (simp_all add: partial_order_def')
then show
"X \<times> Y \<noteq> \<emptyset>"
by (auto)
next
from a1 a2 have
"\<^oprel>{:BS_leq_d_X:} \<in> X \<zrel> X" "\<^oprel>{:BS_leq_d_Y:} \<in> Y \<zrel> Y"
by (simp_all add: partial_order_def')
then show
"\<^oprel>{:\<^prodord>{:BS_leq_d_X:}{:BS_leq_d_Y:}:} \<in> (X \<times> Y) \<zrel> (X \<times> Y)"
apply (msafe(fspace))
apply (auto simp add: product_order_def op2rel_def eind_def)
done
next
fix x
assume
b1: "x \<in> X \<times> Y"
with a1 a2 show
"(\<^prodord>{:BS_leq_d_X:}{:BS_leq_d_Y:}) x x"
by (auto simp add: product_order_def
partial_order_conv reflexive_def reflexive_axioms_def)
next
fix x y z
assume
b1: "x \<in> X \<times> Y \<and> y \<in> X \<times> Y \<and> z \<in> X \<times> Y" and
b2: "(\<^prodord>{:BS_leq_d_X:}{:BS_leq_d_Y:}) x y" and
b3: "(\<^prodord>{:BS_leq_d_X:}{:BS_leq_d_Y:}) y z"
then show
"(\<^prodord>{:BS_leq_d_X:}{:BS_leq_d_Y:}) x z"
apply (auto simp add: product_order_def)
apply (rule poX.trans [simplified, rule_format], mauto(inference))
apply (rule poY.trans [simplified, rule_format], mauto(inference))
done
(*J: note needed mauto(inference) here! *)
next
fix x y
assume
b1: "x \<in> X \<times> Y \<and> y \<in> X \<times> Y" and
b2: "(\<^prodord>{:BS_leq_d_X:}{:BS_leq_d_Y:}) x y" and
b3: "(\<^prodord>{:BS_leq_d_X:}{:BS_leq_d_Y:}) y x"
then show
"x = y"
apply (auto simp add: product_order_def)
apply (rule poX.antisym [simplified, rule_format], msafe(inference))
apply (rule poY.antisym [simplified, rule_format], msafe(inference))
done
}
qed
lemma UNIV_prod:
"\<univ>-['a \<times> 'b] = \<univ>-['a] \<times> \<univ>-['b]"
by (auto)
instance
prod :: (order, order) order
apply (rule order_classI)
apply (simp only: less_eq_prod_def UNIV_prod)
apply (rule product_poI)
apply (rule order_classD)
apply (rule order_classD)
apply (simp add: less_prod_def derefl_def)
done
section {* Operator spaces *}
definition
op_carrier :: "'b set \<rightarrow> ('a \<rightarrow> 'b) set"
where
op_carrier_def: "op_carrier X \<defs> { f | range f \<subseteq> X }"
definition
op_order :: "'b orderT \<rightarrow> ('a \<rightarrow> 'b) orderT"
where
op_order_def: "op_order BS_leq \<defs> (\<olambda> f g \<bullet> (\<forall> a \<bullet> \<^infopa>{:f a:}{:BS_leq:}{:g a:}))"
syntax (zed)
"_Order_Instances\<ZZ>op_carrier" :: "[type, logic] \<rightarrow> logic" ("\<^opset>{:_:}{:_:}")
"_Order_Instances\<ZZ>op_order" :: "[type, logic] \<rightarrow> logic" ("\<^opord>{:_:}{:_:}")
translations
"\<^opset>{:'a:}{:X:}" \<rightharpoonup> "(CONST Order_Instances.op_carrier X)::('a \<rightarrow> _) set"
"\<^opord>{:'a:}{:BS_leq:}" \<rightharpoonup> "(CONST Order_Instances.op_order BS_leq)::('a \<rightarrow> _) orderT"
lemma (in partial_order) operator_poI:
"\<^poset>{:\<^opset>{:'b:}{:X:}:}{:\<^opord>{:'b:}{:(op \<preceq>):}:}"
proof (rule partial_orderI)
from non_empty show
"\<^opset>{:'b:}{:X:} \<noteq> \<emptyset>"
by (auto simp add: op_carrier_def)
next
from rel show
"\<^oprel>{:\<^opord>{:'b:}{:(op \<preceq>):}:} \<in> \<^opset>{:'b:}{:X:} \<zrel>\<^opset>{:'b:}{:X:}"
by (auto simp add: rel_def op2rel_def op_carrier_def op_order_def eind_def)
next
fix f
assume
"f \<in> \<^opset>{:'b:}{:X:}"
with refl
show
"\<^infopa>{:f:}{:\<^opord>{:'b:}{:(op \<preceq>):}:}{:f:}"
by (auto simp add: op_carrier_def op_order_def)
next
fix f g h
assume
"f \<in> \<^opset>{:'b:}{:X:} \<and> g \<in> \<^opset>{:'b:}{:X:} \<and> h \<in> \<^opset>{:'b:}{:X:}" and
"\<^infopa>{:f:}{:\<^opord>{:'b:}{:(op \<preceq>):}:}{:g:}" "\<^infopa>{:g:}{:\<^opord>{:'b:}{:(op \<preceq>):}:}{:h:}"
then show
"\<^infopa>{:f:}{:\<^opord>{:'b:}{:(op \<preceq>):}:}{:h:}"
apply (auto simp add: op_carrier_def op_order_def)
apply (rule transD)
apply (auto)
done
next
fix f g
assume
"f \<in> \<^opset>{:'b:}{:X:} \<and> g \<in> \<^opset>{:'b:}{:X:}" and
"\<^infopa>{:f:}{:\<^opord>{:'b:}{:(op \<preceq>):}:}{:g:}" "\<^infopa>{:g:}{:\<^opord>{:'b:}{:(op \<preceq>):}:}{:f:}"
then show
"f = g"
apply (intro ext)
apply (auto simp add: op_carrier_def op_order_def)
apply (rule antisymD)
apply (auto)
done
qed
lemma UNIV_op:
"\<univ>-['a \<rightarrow> 'b] = \<^opset>{:'a:}{:\<univ>-['b]:}"
by (auto simp add: op_carrier_def)
lemma le_fun_conv:
"f \<le> g \<Leftrightarrow> (\<forall> x \<bullet> f x \<le> g x)"
by (auto simp add: le_fun_def op_order_def)
lemma fun_le:
"f \<le> g \<turnstile> f x \<le> g x"
by (auto simp add: le_fun_def op_order_def)
section {* Power sets *}
text {*
The power set of any set forms a partial order under the subset relation.
*}
definition
pow_subset :: "'a set \<rightarrow> ['a set, 'a set] \<rightarrow> \<bool>"
where
pow_subset_def: "pow_subset X A B \<defs> A \<subseteq> X \<and> B \<subseteq> X \<and> A \<subseteq> B"
syntax (xsymbols output)
"_Order_Instances\<ZZ>pow_subset" :: "[logic, logic, logic] \<rightarrow> logic" ("_/ \<subseteq>\<^bsub>_\<^esub> _" [50, 1000, 51] 50)
syntax (zed)
"_Order_Instances\<ZZ>pow_subset" :: "[logic, logic, logic] \<rightarrow> logic" ("_ \<^powsub>{:_:} _" [50, 1000, 51] 50)
translations
"_Order_Instances\<ZZ>pow_subset A X B" \<rightleftharpoons> "(CONST Order_Instances.pow_subset) X A B"
interpretation pow_po: Order_Locale.partial_order "\<pset> X" "pow_subset X"
apply (intro_locales)
apply (simp_all add: carrier_def setrel_axioms_def reflexive_axioms_def transitive_axioms_def antisymmetric_axioms_def)
apply (msafe(inference))
proof -
show "\<pset> X \<noteq> \<emptyset>"
by (auto)
next
show "\<^oprel>{:pow_subset X:} \<in> \<pset> X \<zrel> \<pset> X"
by (auto simp add: pow_subset_def op2rel_def rel_def)
next
fix A
assume
b1: "A \<subseteq> X"
then show
"A \<^powsub>{:X:} A"
by (auto simp add: pow_subset_def)
next
fix A B C
assume
b1: "A \<subseteq> X" "B \<subseteq> X" "C \<subseteq> X" and
b2: "A \<^powsub>{:X:} B" "B \<^powsub>{:X:} C"
then show
"A \<^powsub>{:X:} C"
by (auto simp add: pow_subset_def)
next
fix A B
assume
b1: "A \<subseteq> X" "B \<subseteq> X" and
b2: "A \<^powsub>{:X:} B" "B \<^powsub>{:X:} A"
then show
"A = B"
by (auto simp add: pow_subset_def)
qed
section {* Dual spaces *}
text {*
The ordering on the dual space is the reverse of the ordering on the
original space.
*}
definition
dual_carrier :: "'a set \<rightarrow> 'a dual set"
where
dual_carrier_def: "dual_carrier X \<defs> { x | x \<in> X \<bullet> \<^adual>{:x:} }"
definition
dual_order :: "'a orderT \<rightarrow> 'a dual orderT"
where
dual_order_def: "dual_order BS_leq \<defs> (\<olambda> a b \<bullet> \<^infopa>{:\<^rdual>{:b:}:}{:BS_leq:}{:\<^rdual>{:a:}:})"
notation (xsymbols output)
dual_carrier ("_\<^isup>\<circ>" [999] 1000) and
dual_order ("_\<^isup>\<circ>" [999] 1000)
notation (zed)
dual_carrier ("_\<dualset>" [999] 1000) and
dual_order ("_\<dualord>" [999] 1000)
lemma (in partial_order) dual_poI:
"\<^poset>{:X\<dualset>:}{:(op \<preceq>)\<dualord>:}"
proof (rule partial_orderI)
from non_empty show "X\<dualset> \<noteq> \<emptyset>"
by (auto simp add: dual_carrier_def)
next
show "\<^oprel>{:(op \<preceq>)\<dualord>:} \<in> X\<dualset> \<zrel> X\<dualset>"
apply (auto dest: relD1 relD2 simp add: rel_def op2rel_def dual_carrier_def dual_order_def type_definition.Rep_inverse [TDINST dual])
apply (intro exI conjI)
apply (rule type_definition.Rep_inverse [TDINST dual, symmetric])
apply (rule relD2)
apply (assumption)
apply (intro exI conjI)
apply (rule type_definition.Rep_inverse [TDINST dual, symmetric])
apply (rule relD1)
apply (assumption)
done
next
fix a
assume
"a \<in> X\<dualset>"
with refl show
"\<^infopa>{:a:}{:(op \<preceq>)\<dualord>:}{:a:}"
by (auto simp add: dual_carrier_def dual_order_def Abs_dual_inverse2)
next
fix a b c
assume "a \<in> X\<dualset> \<and> b \<in> X\<dualset> \<and> c \<in> X\<dualset>" and
"\<^infopa>{:a:}{:(op \<preceq>)\<dualord>:}{:b:}" "\<^infopa>{:b:}{:(op \<preceq>)\<dualord>:}{:c:}"
then show "\<^infopa>{:a:}{:(op \<preceq>)\<dualord>:}{:c:}"
apply (auto simp add: dual_carrier_def dual_order_def Abs_dual_inverse2)
apply (rule transD)
apply (assumption+)
done
next
fix a b
assume
"a \<in> X\<dualset> \<and> b \<in> X\<dualset>" and
"\<^infopa>{:a:}{:(op \<preceq>)\<dualord>:}{:b:}" "\<^infopa>{:b:}{:(op \<preceq>)\<dualord>:}{:a:}"
then show
"a = b"
apply (auto simp add: dual_carrier_def dual_order_def Abs_dual_inverse2 Abs_dual_inject Abs_dual)
apply (rule antisymD)
apply (assumption+)
done
qed
instantiation
dual :: (ord) ord
begin
definition
less_eq_dual_def: "\<opleT>-[('a::ord) dual] \<defs> (op \<le>)\<dualord>"
definition
less_dual_def: "\<opltT>-[('a::ord) dual] \<defs> derefl (op \<le>)"
instance
by (intro_classes)
end
lemma less_eq_dual_conv:
"a \<le> b \<Leftrightarrow> \<^rdual>{:b:} \<le> \<^rdual>{:a:}"
by (simp add: less_eq_dual_def dual_order_def)
text {*
The dual of an order is an order.
*}
lemma UNIV_dual:
"\<univ> = \<univ>\<dualset>"
apply (auto simp add: dual_carrier_def)
apply (rule exI)
apply (rule Rep_dual_inverse [symmetric])
done
instance
dual :: (order) order
apply (rule order_classI)
apply (simp add: less_eq_dual_def UNIV_dual)
apply (rule partial_order.dual_poI)
apply (rule order_classD)
apply (simp add: less_dual_def derefl_def)
done
text {*
The dual ordering induces the reverse order on the original type.
*}
lemma less_dual_conv:
"(a::('a::order) dual) < b \<Leftrightarrow> \<^rdual>{:b:} < \<^rdual>{:a:}"
by (auto simp add: less_dual_def less_eq_dual_conv dual_order_def derefl_def Abs_dual_inverse2 Abs_dual_inject Abs_dual order_less_le Rep_dual_inject)
lemma less_eq_dual_conv2:
"\<^adual>{:(a::'a::order):} \<le> \<^adual>{:b:} \<Leftrightarrow> b \<le> a"
by (simp add: less_eq_dual_def dual_order_def Abs_dual_inverse2)
lemma less_dual_conv2:
"\<^adual>{:(a::'a::order):} < \<^adual>{:b:} \<Leftrightarrow> b < a"
by (auto simp add: less_dual_def less_eq_dual_conv2 dual_order_def derefl_def Abs_dual_inverse2 Abs_dual_inject Abs_dual order_less_le)
definition
dual_fun :: "('a \<rightarrow> 'b) \<rightarrow> ('a dual \<rightarrow> 'b)"
where
dual_fun_def [simp]: "dual_fun \<defs> (\<olambda> f a \<bullet> (f \<^rdual>{:a:}))"
definition
amono :: "(('a::order) \<rightarrow> ('b::order)) \<rightarrow> \<bool>"
where
amono_def: "amono f \<defs> mono (dual_fun f)"
lemma amonoI:
assumes
a1: "(\<And> A B \<bullet> B \<le> A \<turnstile> f A \<le> f B)"
shows
"amono f"
apply (unfold amono_def)
apply (rule monoI)
apply (simp add: le_fun_def ge_def)
apply (rule a1)
apply (simp add: less_eq_dual_def dual_order_def)
done
lemma amonoI':
assumes
a1: "(\<And> A B \<bullet> B \<le> A \<turnstile> f A \<le> f B)"
shows
"amono f"
apply (rule amonoI)
apply (rule a1)
apply (assumption)
done
lemma amonoD:
assumes
a1: "amono f" and
a2: "B \<le> A"
shows
"f A \<le> f B"
proof -
from a2 have
b1:"\<^adual>{:A:} \<le> \<^adual>{:B:}"
by (simp add: less_eq_dual_def dual_order_def Abs_dual_inverse2)
from monoD [OF a1 [unfolded amono_def] b1] show
?thesis
by (simp add: Abs_dual_inverse2)
qed
lemma amonoD':
assumes
a1: "amono f" and
a2: "B \<le> A"
shows
"f A \<le> f B"
apply (rule amonoD [OF a1])
using a1 a2
apply (simp)
done
lemma amono_mono_comp:
assumes
a1: "amono f" and
a2: "mono g"
shows
"amono (f \<circ> g)"
using a1 a2
by (auto intro!: amonoI dest!: monoD amonoD)
lemma mono_amono_comp:
assumes
a1: "mono f" and
a2: "amono g"
shows
"amono (f \<circ> g)"
using a1 a2
by (auto intro!: amonoI dest!: monoD amonoD)
lemma amono_amono_comp:
assumes
a1: "amono f" and
a2: "amono g"
shows
"mono (f \<circ> g)"
using a1 a2
by (auto intro!: monoI dest!: amonoD)
lemma (in order) dual_orderI:
"\<^order>{:X\<dualset>:}{:(op \<preceq>)\<dualord>:}"
apply (simp add: order_conva)
apply (msafe(inference))
apply (rule dual_poI)
apply (simp add: dual_order_def dual_carrier_def)
apply (msafe(inference))
apply (simp add: Abs_dual_inverse2)
apply (rule linD)
apply (msafe(inference))
done
instance
dual :: (linorder) linorder
apply (rule linorder_classI)
apply (simp add: less_eq_dual_def UNIV_dual)
apply (rule order.dual_orderI)
apply (rule linorder_classD)
apply (simp add: less_dual_def derefl_def)
done
section {* The identity order *}
lemma id_poI:
"X \<noteq> \<emptyset> \<turnstile> \<^poset>{:X:}{:(\<^relop>{:(\<zid> X):}):}"
apply (insert id_in_relI [of X])
apply (rule partial_orderI)
apply (simp_all add: op2rel_def rel2op_def rel_id_def eind_def)
done
definition
extend_ord :: "['a set, ['a, 'a] \<rightarrow> \<bool>] \<rightarrow> (['a, 'a] \<rightarrow> \<bool>)"
where
extend_ord_def: "extend_ord Y BS_leq \<defs> \<^relop>{:\<^oprel>{:BS_leq:} \<union> \<zid> Y:}"
notation (zed)
extend_ord ("\<extord>{:_:}{:_:}")
lemma (in partial_order) extend_ord_conv:
assumes
a1: "X \<subseteq> Y"
shows
"\<^infop>{:x:}{:\<extord>{:Y:}{:(op \<preceq>):}:}{:y:}
\<Leftrightarrow> x \<in> Y \<and> x \<notin> X \<and> y = x \<or> x \<in> X \<and> y \<in> X \<and> \<^infop>{:x:}{:(op \<preceq>):}{:y:}"
proof -
from rel reflD
show
?thesis
apply (msafe(fspace))
apply (simp add: extend_ord_def op2rel_def rel2op_def rel_id_def)
apply (auto simp add: eind_def)
done
qed
lemma id_ext_poI:
assumes
a1: "\<^poset>{:X:}{:BS_leq:}" and
a2: "X \<subseteq> Y"
shows
"\<^poset>{:Y:}{:\<extord>{:Y:}{:BS_leq:}:}"
proof -
from a1 interpret partial_order "X" "BS_leq"
by (simp_all add: Order_Locale.partial_order_def)
show
?thesis
proof (rule partial_orderI)
from non_empty a2 show
"Y \<noteq> \<emptyset>"
by (auto)
next
from rel a2 show
"\<^oprel>{:\<extord>{:Y:}{:BS_leq:}:} \<in> Y \<zrel> Y"
apply (msafe(fspace))
apply (auto simp add: extend_ord_def op2rel_def rel2op_def rel_id_def eind_def)
done
next
fix y
assume
b1: "y \<in> Y"
with a2 show
"\<^infop>{:y:}{:\<extord>{:Y:}{:BS_leq:}:}{:y:}"
by (auto simp add: extend_ord_def op2rel_def rel2op_def rel_id_def eind_def)
next
fix x y z
assume
b1: "x \<in> Y \<and> y \<in> Y \<and> z \<in> Y" and
b2: "\<^infop>{:x:}{:\<extord>{:Y:}{:BS_leq:}:}{:y:}" and
b3: "\<^infop>{:y:}{:\<extord>{:Y:}{:BS_leq:}:}{:z:}"
with a2 show
"\<^infop>{:x:}{:\<extord>{:Y:}{:BS_leq:}:}{:z:}"
apply (auto simp add: extend_ord_conv)
apply (rule transD, assumption+)
apply (rule transD, assumption+)
done
next
fix x y
assume
b1: "x \<in> Y \<and> y \<in> Y" and
b2: "\<^infop>{:x:}{:\<extord>{:Y:}{:BS_leq:}:}{:y:}" and
b3: "\<^infop>{:y:}{:\<extord>{:Y:}{:BS_leq:}:}{:x:}"
with a2 show
"x = y"
apply (auto simp add: extend_ord_conv)
apply (rule antisymD, assumption+)
done
qed
qed
section {* Subset order on relational graphs *}
definition
rel_subset :: "['a set, 'b set ] \<rightarrow> ['a \<leftrightarrow> 'b, 'a \<leftrightarrow> 'b] \<rightarrow> \<bool>"
where
rel_subset_def: "rel_subset X Y \<defs> pow_subset (X \<times> Y)"
syntax (xsymbols output)
"_Order_Instances\<ZZ>rel_subset" :: "[logic, logic, logic, logic] \<rightarrow> logic" ("_ \<subseteq>\<^bsub>_ \<leftrightarrow> _\<^esub> _" [50, 1000, 1000, 51] 50)
syntax (zed)
"_Order_Instances\<ZZ>rel_subset" :: "[logic, logic, logic, logic] \<rightarrow> logic" ("_ \<^relsub>{:_:}{:_:} _")
translations
"_Order_Instances\<ZZ>rel_subset r X Y s" \<rightleftharpoons> "CONST Order_Instances.rel_subset X Y r s"
interpretation rel_po: Order_Locale.partial_order "X \<zrel> Y" "rel_subset X Y"
apply (intro_locales)
apply (simp_all add: rel_subset_def rel_def)
apply (simp_all only:
carrier_def setrel_axioms_def reflexive_axioms_def
transitive_axioms_def antisymmetric_axioms_def)
apply (msafe(inference))
apply (rule pow_po.non_empty)
apply (rule pow_po.rel)
apply (rule pow_po.reflD, assumption)
apply (rule pow_po.transD, assumption+)
apply (rule pow_po.antisymD, assumption+)
done
section {* Result order on functional graphs *}
definition
res_le :: "[['b, 'b] \<rightarrow> \<bool>, 'a \<leftrightarrow> 'b, 'a \<leftrightarrow> 'b] \<rightarrow> \<bool>"
where
res_le_def: "res_le r f g \<defs> functional f \<and> functional g \<and> (\<forall> x | x \<in> \<zdom> g \<bullet> x \<in> \<zdom> f \<and> \<^infop>{:f\<cdot>x:}{:r:}{:g\<cdot>x:})"
definition
def_res_le :: "['a \<leftrightarrow> ('b::ord), 'a \<leftrightarrow> 'b] \<rightarrow> \<bool>"
where
def_res_le_def: "def_res_le f g \<defs> res_le (op \<le>) f g"
notation (zed)
res_le ("\<^resle>{:_:}") and
def_res_le ("_ \<dresle> _" [50,51] 50)
lemma def_res_le_conv:
"f \<dresle> g \<Leftrightarrow> functional f \<and> functional g \<and> (\<forall> x | x \<in> \<zdom> g \<bullet> x \<in> \<zdom> f \<and> f\<cdot>x \<le> g\<cdot>x)"
by (simp add: def_res_le_def res_le_def)
lemma res_le_def':
"\<^infop>{:f:}{:\<^resle>{:r:}:}{:g:}
\<Leftrightarrow> functional f \<and> functional g \<and>
(\<forall> x y | (x \<mapsto> y) \<in> g \<bullet> (\<exists> y' | (x \<mapsto> y') \<in> f \<bullet> \<^infop>{:y':}{:r:}{:y:}))"
apply (unfold res_le_def)
apply (mauto(wind))
proof-
fix x
assume
b1: "functional f" and
b2: "functional g"
have "(x \<in> \<zdom> g \<Rightarrow> x \<in> \<zdom> f \<and> r (f\<cdot>x) (g\<cdot>x)) = (\<forall> y \<bullet> (x \<mapsto> y) \<in> g \<Rightarrow> x \<in> \<zdom> f \<and> r (f\<cdot>x) (g\<cdot>x))"
by (simp add: Domain_iff)
also have
"... = (\<forall> y \<bullet> (x, y) \<in> g \<Rightarrow> (\<exists> y' \<bullet> (x, y') \<in> f \<and> r y' y))"
apply (mauto(wind))
apply (simp add: Domain_iff)
apply (subst ex_simps')
apply (mauto(wind))
proof -
fix y y'
assume
b3: "(x \<mapsto> y) \<in> g" and
b4: "(x \<mapsto> y') \<in> f"
with b1 b2 show
"\<^infop>{:f\<cdot>x:}{:r:}{:g\<cdot>x:} \<Leftrightarrow> \<^infop>{:y':}{:r:}{:y:}"
by (simp add: functional_beta)
qed
finally show
"(x \<in> \<zdom> g
\<Rightarrow> x \<in> \<zdom> f \<and> r (f\<cdot>x) (g\<cdot>x)) = (\<forall> y \<bullet> (x \<mapsto> y) \<in> g \<Rightarrow> (\<exists> y' \<bullet> r y' y \<and> (x \<mapsto> y') \<in> f))"
by (auto)
qed
lemma functional_poI:
assumes
a1: "\<^poset>{:\<univ>:}{:BS_leq:}"
shows
"\<^poset>{:{f::'a \<leftrightarrow> 'b | functional f}:}{:\<^resle>{:BS_leq:}:}"
apply (rule partial_orderI)
apply (simp_all)
proof (msafe(inference))
show
"(\<exists> f::'a \<leftrightarrow> 'b \<bullet> functional f)"
apply (witness "\<glambda> (y::'a) \<bullet> \<arb>-['b]")
apply (auto simp add: glambda_functional glambda_ran)
done
next
show
"\<^oprel>{:\<^resle>{:BS_leq:}:} \<in> {f | functional f} \<zrel> {f | functional f}"
apply (msafe(fspace))
apply (auto simp add: op2rel_def res_le_def)
done
next
fix f::"'a \<leftrightarrow> 'b"
assume
b1: "functional f"
with a1 show
"\<^infop>{:f:}{:\<^resle>{:BS_leq:}:}{:f:}"
by (simp add: res_le_def partial_order_def')
next
fix f::"'a \<leftrightarrow> 'b"
assume
b1: "functional f"
fix g::"'a \<leftrightarrow> 'b"
assume
b2: "functional g"
fix h::"'a \<leftrightarrow> 'b"
assume
b3: "functional h"
assume
b4: "\<^infop>{:f:}{:\<^resle>{:BS_leq:}:}{:g:}" and
b5: "\<^infop>{:g:}{:\<^resle>{:BS_leq:}:}{:h:}"
show
"\<^infop>{:f:}{:\<^resle>{:BS_leq:}:}{:h:}"
apply (simp add: res_le_def b1 b3)
apply (msafe(inference))
proof -
fix x
assume
c1: "x \<in> \<zdom> h"
with b4 b5 show
"x \<in> \<zdom> f"
by (simp add: res_le_def)
from a1 c1 b4 b5 show
"\<^infop>{:f\<cdot>x:}{:BS_leq:}{:h\<cdot>x:}"
apply (intro transitive.transD [of "\<univ>" "BS_leq" "f\<cdot>x" "g\<cdot>x" "h\<cdot>x"])
apply (auto simp add: partial_order_conv res_le_def)
done
qed
next
fix f::"'a \<leftrightarrow> 'b"
assume
b1: "functional f"
fix g::"'a \<leftrightarrow> 'b"
assume
b2: "functional g"
assume
b3: "\<^infop>{:f:}{:\<^resle>{:BS_leq:}:}{:g:}" and
b4: "\<^infop>{:g:}{:\<^resle>{:BS_leq:}:}{:f:}"
show
"f = g"
apply (rule functional_eqI)
apply (rule b1, rule b2)
proof -
from b3 b4 show
c1: "\<zdom> f = \<zdom> g"
by (auto simp add: res_le_def)
fix x
assume
"x \<in> \<zdom> f"
with a1 b3 b4 c1 show
"f\<cdot>x = g\<cdot>x"
apply (intro antisymmetric.antisymD [of "\<univ>" "BS_leq" "f\<cdot>x" "g\<cdot>x"])
apply (simp_all add: partial_order_conv res_le_def)
done
qed
qed
lemma pfun_poI:
fixes
X::"'a set" and
Y::"'b set"
assumes
a1: "\<^poset>{:Y:}{:BS_leq:}"
shows
"\<^poset>{:(X \<zpfun> Y):}{:(\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}):}"
proof -
from a1 interpret a1: partial_order "Y" "BS_leq"
by (simp_all add: Order_Locale.partial_order_def)
show
?thesis
proof (rule partial_orderI, msafe(inference))
show
"X \<zpfun> Y \<noteq> \<emptyset>"
apply (simp add: fun_space_defs)
apply (witness "\<emptyset>-['a \<times> 'b]")
apply (auto)
done
next
show
"\<^oprel>{:\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}:} \<in> (X \<zpfun> Y) \<zrel> (X \<zpfun> Y)"
apply (msafe(fspace))
apply (auto simp add: op2rel_def rel2op_def subset_order_def subset_def)
done
next
fix f
assume
c1: "f \<in> X \<zpfun> Y"
then show
"\<^infop>{:f:}{:\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}:}{:f:}"
apply (simp add: res_le_def op2rel_def rel2op_def subset_order_def)
apply (msafe(inference))
apply (msafe(fspace))
proof -
fix x
assume
"x \<in> \<zdom> f"
with c1 have
"f\<cdot>x \<in> Y" by (auto)
with a1.refl show
"\<^infop>{:f\<cdot>x:}{:BS_leq:}{:f\<cdot>x:}"
by (auto)
qed
next
fix f g h
assume
c1: "f \<in> X \<zpfun> Y" " g \<in> X \<zpfun> Y" "h \<in> X \<zpfun> Y" and
c2: "\<^infop>{:f:}{:\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}:}{:g:}" and
c3: "\<^infop>{:g:}{:\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}:}{:h:}"
from c1 show
"\<^infop>{:f:}{:\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}:}{:h:}"
apply (simp add: res_le_def op2rel_def rel2op_def subset_order_def)
apply (msafe(inference))
apply (msafe(fspace))
proof -
fix x
assume
d1: "x \<in> \<zdom> h"
with c3 have
d2: "x \<in> \<zdom> g"
by (simp add: res_le_def op2rel_def rel2op_def subset_order_def)
with c2 show
d3: "x \<in> \<zdom> f"
by (simp add: res_le_def op2rel_def rel2op_def subset_order_def)
from c2 d2 d3 have
d4: "\<^infop>{:f\<cdot>x:}{:BS_leq:}{:g\<cdot>x:}"
by (auto simp add: res_le_def op2rel_def rel2op_def subset_order_def)
from c3 d1 d2 have
d5: "\<^infop>{:g\<cdot>x:}{:BS_leq:}{:h\<cdot>x:}"
by (auto simp add: res_le_def op2rel_def rel2op_def subset_order_def)
from d4 d5 show
"\<^infop>{:f\<cdot>x:}{:BS_leq:}{:h\<cdot>x:}"
by (rule a1.transD)
qed
next
fix f g
assume
c1: "f \<in> X \<zpfun> Y" "g \<in> X \<zpfun> Y" and
c2: "\<^infop>{:f:}{:\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}:}{:g:}" and
c3: "\<^infop>{:g:}{:\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}:}{:f:}"
show
"f = g"
apply (rule functional_eqI)
apply (rule c1 [THEN dr_pfunD1])
apply (rule c1 [THEN dr_pfunD1])
proof -
from c2 c3 show
d1: "\<zdom> f = \<zdom> g"
by (auto simp add: res_le_def op2rel_def rel2op_def subset_order_def)
fix x
assume
d2: "x \<in> \<zdom> f"
from d2 c2 d1 have
d3: "\<^infop>{:f\<cdot>x:}{:BS_leq:}{:g\<cdot>x:}"
by (auto simp add: res_le_def op2rel_def rel2op_def subset_order_def)
from d2 c3 d1 have
d4: "\<^infop>{:g\<cdot>x:}{:BS_leq:}{:f\<cdot>x:}"
by (auto simp add: res_le_def op2rel_def rel2op_def subset_order_def)
from d3 d4 show
"f\<cdot>x = g\<cdot>x"
by (rule a1.antisymD)
qed
qed
qed
text {*
The result order specialises nicely to total functions.
*}
definition
tfun_order :: "['a set, 'b set, ['b, 'b] \<rightarrow> \<bool>] \<rightarrow> (['a \<leftrightarrow> 'b, 'a \<leftrightarrow> 'b] \<rightarrow> \<bool>)"
where
tfun_order_def:
"tfun_order X Y BS_leq_d_Y
\<defs> (\<olambda> f g \<bullet>
\<lch> f, g \<chIn> X \<ztfun> Y \<rch> \<and>
(\<forall> x | x \<in> X \<bullet> \<^infopa>{:f\<cdot>x:}{:BS_leq_d_Y:}{:g\<cdot>x:}))"
lemma tfun_res_le:
"tfun_order X Y BS_leq = \<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<ztfun> Y):}"
apply (auto simp add: tfun_order_def op2rel_def rel2op_def subset_order_def fun_eq_def res_le_def)
apply (mauto(fspace))
apply (auto)
done
lemma tfun_poI:
assumes
a1: "\<^poset>{:Y:}{:BS_leq:}"
shows
"\<^poset>{:(X \<ztfun> Y):}{:(tfun_order X Y BS_leq):}"
proof -
from a1 interpret a1: Order_Locale.partial_order "Y" "BS_leq"
by (simp_all add: Order_Locale.partial_order_def)
from a1 interpret
b1: Order_Locale.partial_order "X \<zpfun> Y" "\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}"
by (rule pfun_poI)
interpret
b2: Order_Locale.sub_partial_order
"X \<zpfun> Y" "\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}" "X \<ztfun> Y"
proof (unfold_locales)
from a1.non_empty obtain y where
"y \<in> Y"
by (auto)
then show
"X \<ztfun> Y \<noteq> \<emptyset>"
apply (simp add: nempty_conv)
apply (witness "(\<glambda> x | x \<in> X \<bullet> y)")
apply (rule glambda_tfun)
apply (auto)
done
show "X \<ztfun> Y \<subseteq> X \<zpfun> Y"
by (auto)
qed
have
"\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<ztfun> Y):}
= \<^subord>{:\<^subord>{:\<^resle>{:BS_leq:}:}{:(X \<zpfun> Y):}:}{:(X \<ztfun> Y):}"
by (auto simp add: op2rel_def rel2op_def subset_order_def fun_eq_def)
then show
?thesis
apply (simp add: tfun_res_le)
apply (rule b2.Y_poI)
done
qed
section {* Strings *}
fun
find_ind_raw :: "'a \<rightarrow> \<nat> \<rightarrow> 'a list \<rightarrow> \<nat> option"
where
"find_ind_raw a n (x#xs) = \<if> a = x \<then> Some n \<else> find_ind_raw a (n+1) xs \<fi>"
| "find_ind_raw a n [] = None"
definition
find_ind :: "'a \<rightarrow> 'a list \<rightarrow> \<nat> option"
where
"find_ind a = find_ind_raw a 0"
lemma find_ind_raw_bound1:
"(\<forall> n m \<bullet> find_ind_raw x n X = Some m \<Rightarrow> n \<le> m)"
apply (induct "X")
apply (simp)
proof -
fix
a X
assume
b1 [rule_format]: "(\<forall> n m \<bullet> find_ind_raw x n X = Some m \<Rightarrow> n \<le> m)"
show
"(\<forall> n m \<bullet> find_ind_raw x n (a#X) = Some m \<Rightarrow> n \<le> m)"
apply (cases "x = a")
apply (simp)
apply (auto)
apply (rule order_trans)
apply (rule less_imp_le [OF lessI])
apply (rule b1)
apply (assumption)
done
qed
lemma find_ind_raw_bound2:
"(\<forall> n m \<bullet> Some m = find_ind_raw x n X \<Rightarrow> n \<le> m)"
by (auto intro!: find_ind_raw_bound1 [rule_format])
lemmas
find_ind_raw_bound = find_ind_raw_bound1 [rule_format] find_ind_raw_bound2 [rule_format]
lemma find_ind_raw_dom [rule_format]:
"(\<forall> n \<bullet> find_ind_raw x n X \<noteq> None \<Leftrightarrow> x \<in> set X)"
apply (induct "X")
apply (auto)
done
lemma find_ind_dom:
"find_ind x X \<noteq> None \<Leftrightarrow> x \<in> set X"
by (simp only: find_ind_def find_ind_raw_dom)
lemma find_ind_raw_inj [rule_format]:
"(\<forall> n x | x \<in> set X \<bullet> (\<forall> y | y \<in> set X \<bullet> find_ind_raw x n X = find_ind_raw y n X \<Leftrightarrow> x = y))"
apply (induct "X")
apply (simp)
apply (mauto(inference))
proof -
fix
a X n x y
assume
b1: "(\<forall> n x | x \<in> set X \<bullet> (\<forall> y | y \<in> set X \<bullet> find_ind_raw x n X = find_ind_raw y n X \<Leftrightarrow> x = y))" and
b2: "x \<in> set (a#X)" "y \<in> set (a#X)" and
b3: "find_ind_raw x n (a # X) = find_ind_raw y n (a # X)"
from b3 show
"x = y"
apply (multi_cases "x = a" "y = a")
using b1 [rule_format] b2
apply (auto dest: find_ind_raw_bound)
done
qed
context
enum
begin
definition
enum_ord :: "'a \<rightarrow> 'a \<rightarrow> \<bool>"
where
"enum_ord x y \<Leftrightarrow> the (find_ind x enum) \<le> the (find_ind y enum)"
lemma enum_ord_linear:
"\<^order>{:\<univ>-['a]:}{:enum_ord:}"
apply (intro orderI)
apply (auto simp add: enum_ord_def find_ind_def rel_def)
proof -
fix
x y
assume
b1: "the (find_ind_raw y 0 enum) = the (find_ind_raw x 0 enum)"
with in_enum [of "x"] in_enum [of "y"] have
b2: "(find_ind_raw y 0 enum) = (find_ind_raw x 0 enum)"
by (auto simp add: find_ind_dom [symmetric] find_ind_def)
show
"x = y"
apply (rule find_ind_raw_inj [THEN iffD1])
using in_enum [of "x"] in_enum [of "y"] b2 [symmetric]
apply (auto)
done
qed
end
instantiation
nibble :: ord
begin
definition
less_eq_nibble_def: "\<opleT>-[nibble] \<defs> enum_ord"
definition
less_nibble_def: "\<opltT>-[nibble] \<defs> derefl \<opleT>"
instance
by (intro_classes)
end
instance
nibble :: linorder
apply (rule linorder_classI)
apply (auto simp add: enum_ord_linear less_eq_nibble_def less_nibble_def)
done
instantiation char :: ord
begin
definition
less_eq_char_def: "\<opleT>-[char] \<defs> enum_ord"
definition
less_char_def: "\<opltT>-[char] \<defs> derefl \<opleT>"
instance
by (intro_classes)
end
instance
char :: linorder
apply (rule linorder_classI)
apply (auto simp add: enum_ord_linear less_eq_char_def less_char_def)
done
context
ord
begin
fun
lex_ord :: "['a list, 'a list] \<rightarrow> \<bool>"
where
"lex_ord [] [] \<Leftrightarrow> \<True>"
| "lex_ord [] (y#Y) \<Leftrightarrow> \<True>"
| "lex_ord (x#X) [] \<Leftrightarrow> \<False>"
| "lex_ord (x#X) (y#Y) \<Leftrightarrow> x < y \<or> x = y \<and> lex_ord X Y"
end
lemma lex_ord_poI:
"\<^poset>{:\<univ>-[(('a::order) list)]:}{:lex_ord:}"
apply (intro partial_order_intros)
apply (auto simp add: rel_def)
proof -
fix
x :: "'a list"
show
"lex_ord x x"
apply (induct "x")
apply (auto)
done
next
fix
x :: "'a list" and
y :: "'a list"
assume
b1: "lex_ord x y" "lex_ord y x"
have
"(\<forall> y \<bullet> lex_ord x y \<and> lex_ord y x \<Rightarrow> x = y)" (is "(\<forall> y \<bullet> ?P x y)")
apply (induct "x")
apply (intro allI)
proof -
fix
y :: "'a list"
show
"lex_ord [] y \<and> lex_ord y [] \<Rightarrow> [] = y"
apply (cases "y")
apply (auto)
done
next
apply_end (rule allI)
fix
a :: "'a" and
x :: "'a list" and
y :: "'a list"
assume
c1 [rule_format]: "(\<forall> y \<bullet> lex_ord x y \<and> lex_ord y x \<Rightarrow> x = y)"
show
"lex_ord (a#x) y \<and> lex_ord y (a#x) \<Rightarrow> (a#x) = y"
apply (cases "y")
apply (simp)
apply (msafe(inference))
apply (auto intro: c1 simp add: less_le)
done
qed
with b1 show
"x = y"
by (auto)
next
fix
x :: "'a list" and
y :: "'a list" and
z :: "'a list"
assume
b1: "lex_ord x y" "lex_ord y z"
have
"(\<forall> y z \<bullet> lex_ord x y \<and> lex_ord y z \<Rightarrow> lex_ord x z)" (is "(\<forall> y z \<bullet> ?P x y z)")
apply (induct "x")
apply (intro allI)
proof -
fix
y :: "'a list" and
z :: "'a list"
show
"?P [] y z"
apply (multi_cases "y" "z")
apply (auto)
done
next
apply_end (intro allI)
fix
a :: "'a" and
x :: "'a list" and
y :: "'a list" and
z :: "'a list"
assume
c1 [rule_format]: "(\<forall> y z \<bullet> ?P x y z)"
show
"?P (a#x) y z"
apply (multi_cases "y" "z")
apply (auto)
apply (mauto(inference) melim!: notE mintro: less_trans c1)
done
qed
with b1 show
"lex_ord x z"
by (auto)
qed
lemma lex_ord_orderI:
"\<^order>{:\<univ>-[('a::linorder) list]:}{:lex_ord:}"
apply (rule partial_order.orderIa)
apply (rule lex_ord_poI)
apply (simp)
proof -
fix
x :: "'a list" and
y :: "'a list"
have
"(\<forall> y \<bullet> lex_ord x y \<or> lex_ord y x)"
apply (induct "x")
apply (rule allI)
proof -
fix
y :: "'a list"
show
"lex_ord [] y \<or> lex_ord y []"
apply (cases "y")
apply (auto)
done
next
apply_end (rule allI)
fix
a :: "'a" and
x :: "'a list" and
y :: "'a list"
assume
c1 [rule_format]: "(\<forall> y \<bullet> lex_ord x y \<or> lex_ord y x)"
show
"lex_ord (a#x) y \<or> lex_ord y (a#x)"
apply (cases "y")
apply (simp)
using c1
apply (auto)
done
qed
then show
"lex_ord x y \<or> lex_ord y x"
by (auto)
qed
instantiation String.literal :: ord
begin
definition
less_eq_literal_def: "\<opleT>-[String.literal] = induce_ord explode lex_ord"
definition
less_literal_def: "\<opltT>-[String.literal] = derefl \<opleT>"
instance
by (intro_classes)
end
instance
String.literal :: linorder
proof (rule epi_typedefs_linorder_classI [OF _ lex_ord_orderI less_eq_literal_def less_literal_def])
interpret
litTD: type_definition explode STR \<univ>
by (rule type_definition_literal)
show
"epi_type_definition explode STR"
apply (rule epi_type_definition.intro)
apply (rule surjI)
apply (auto intro: litTD.Abs_inverse litTD.Rep_inverse)
done
qed
end
|
/**
* @file common.h
* @brief Public header file containing the common objects, API used by different applications
*/
#ifndef COMMON_H
#define COMMON_H
#include <petsc.h>
/**
* @brief The communicator context
*/
struct _p_COMM {
MPI_Comm type; /**< MPI communicator SELF or WORLD */
PetscMPIInt rank; /**< Process rank */
PetscMPIInt size; /**< Communicator size */
PetscInt refct; /**< Reference count to know how many objects are sharing the communicator */
};
typedef struct _p_COMM *COMM;
/**
* @brief Creates the communicator object COMM
* @param [in] MPI_Comm mpicomm - The MPI communicator
* @param [out] COMM* outcomm - The COMM object
*/
extern PetscErrorCode COMMCreate(MPI_Comm,COMM*);
/**
* @brief Destroys the communicator object COMM created with COMMCreate
* @param [in] COMM* outcomm - The COMM object
*/
extern PetscErrorCode COMMDestroy(COMM*);
/**
* @brief NOT IMPLIMENTED
*/
extern PetscErrorCode SetMatrixValues(Mat,PetscInt,PetscInt[],PetscInt,PetscInt[],PetscScalar[]);
#endif
|
function type2col(i)
if i == 0
return colorant"black"
elseif i == 1
return colorant"blue"
elseif i == 2
return colorant"white"
elseif i == 3
return colorant"red"
elseif i == 4
return colorant"green"
else
return colorant"black"
end
end
function display_flag(flag::Array{Float64,2},title_string::String)
heatmap(type2col.(flag),xticks = false,yticks = false,title = title_string, titlefont=font(10,"Computer Modern"))
end
function display_flag(flag::Array{Float64,2})
heatmap(type2col.(flag),xticks = false,yticks = false)
end |
# #This will be a different path if in the lab or at home
# dird="E:\\OneDrive\\MATH4753\\DATAxls\\" # 2017
#
# #my function to read data
# myread=function(csv){
# fl=paste(dird,csv,sep="")
# read.table(fl,header=TRUE,sep=",")
# }
# #EASY WAY TO READ IN FILES
#spruce.df=myread("SPRUCE.csv")#MS pg478
spruce.df = read.csv("SPRUCE.csv")
#with(spruce.df, dput(list(D=BHDiameter,H=Height),
#file="spruce.dat"))
# Or use
#spruce.df=read.table(file.choose(),header=TRUE,sep=",")
#get wd
getwd()
#Top six lines
tail(spruce.df)
#Plot the points
windows()
plot(Height~BHDiameter,bg="Blue",pch=21,cex=1.2,
ylim=c(0,max(Height)),xlim=c(0,max(BHDiameter)),
main="Spruce height prediction",data=spruce.df)
library(ggplot2)
windows()
g = ggplot(spruce.df,mapping = aes(x = BHDiameter, y = Height)) +
geom_point()
print(g)
g = g+ geom_smooth(formula = y~ log(x), method = "lm", col = "steelblue")
g = g + geom_smooth(formula = y ~ x, method = "lm", col = "Black")
g = g + geom_smooth(formula = y~ x+ I(x^2), method ="lm", col = "Red")
print(g)
g = g + geom_smooth(formula = y~ poly(x,3), method ="lm", col = "green3")
g
#load s20x library and make lowess smoother
library(s20x)
trendscatter(Height~BHDiameter,f=0.5,data=spruce.df)
# Now make the linear model
spruce.lm=lm(Height~BHDiameter,data=spruce.df)
summary(spruce.lm)
#residuals created from the linear model object
height.res=residuals(spruce.lm)
#fitted values made from the linear model object
height.fit=fitted(spruce.lm)
windows()
#Make the plot using the plot function
plot(height.fit,height.res)
# Put a lowess smoother through res vs fitted
trendscatter( height.fit,height.res)
# Quick way to make a residual plot
plot(spruce.lm, which =1)
# Two plots testing normality
windows()
normcheck(spruce.lm,shapiro.wilk = TRUE)
## Quadratic object using the linear model
quad.lm=lm(Height~BHDiameter + I(BHDiameter^2),data=spruce.df)
summary(quad.lm)
add1(spruce.lm,.~.+I(BHDiameter^2))
anova(spruce.lm)
anova(quad.lm)
anova(spruce.lm,quad.lm)
cubic.lm=lm(Height~BHDiameter + I(BHDiameter^2)+I(BHDiameter^3),data=spruce.df)
anova(cubic.lm)
add1(quad.lm,.~.+I(BHDiameter^3))
#add to the scatter plot
windows()
plot(Height~BHDiameter,bg="Blue",pch=21,cex=1.2,
ylim=c(0,max(Height)),xlim=c(0,max(BHDiameter)),
main="Spruce height prediction",data=spruce.df)
coef(quad.lm)
names(quad.lm)
quad.lm$coef[2]
myplot=function(x){
0.86089580 +1.46959217*x -0.02745726*x^2
}
#Or more general method
myplot=function(x){
quad.lm$coef[1] +quad.lm$coef[2]*x + quad.lm$coef[3]*x^2
}
curve(myplot, lwd=2, col="steelblue",add=TRUE)
plot(quad.lm, which=1)
plot(spruce.lm,which=1)
normcheck(quad.lm,shapiro.wilk = TRUE)
summary(quad.lm)
predict(quad.lm, data.frame(BHDiameter=c(3,6,8)))
ciReg(quad.lm)
predict(quad.lm, data.frame(BHDiameter=c(15,18,20)))
anova(spruce.lm,quad.lm)
data = 15:24
predict20x(quad.lm,data.frame(BHDiameter = data, `I(BhDiameter)^2`=data^2))
anova(quad.lm)
anova(spruce.lm)
height.qfit=fitted(quad.lm)
RSS=with(spruce.df, sum((Height-height.qfit)^2))
RSS
MSS = with(spruce.df, sum((height.qfit-mean(Height))^2))
MSS
TSS = with(spruce.df, sum((Height-mean(Height))^2))
TSS
MSS/TSS
cooks20x(quad.lm)
#Now remove the 24th datum and reanalyze data
quad2.lm=lm(Height~BHDiameter + I(BHDiameter^2) , data=spruce.df[-24,])
summary(quad2.lm)
summary(quad.lm)
###############################################################################
#some other code you might need
#The following code plots residuals
windows()
#Plot the data
plot(Height~BHDiameter,bg="Blue",pch=21,cex=1.2,
ylim=c(0,max(Height)),xlim=c(0,max(BHDiameter)),
main="Spruce height prediction",data=spruce.df)
#Make a quadratic model
quad.lm=lm(Height~BHDiameter + I(BHDiameter^2),data=spruce.df)
# Find the coefficients
coef(quad.lm)
#Make a function that produces heights for inputs "x"
myplot=function(x){
0.86089580 +1.46959217*x -0.02745726*x^2
}
# add the quadratic to the points
curve(myplot, lwd=2, col="steelblue",add=TRUE)
#Place segments (residuals) on the plot (except for the 3 largest cooks distances. 18, 21, 24)
with(spruce.df[-c(18,21,24),],segments(BHDiameter, Height, BHDiameter, height.qfit[-c(18,21,24)]) )
with(spruce.df[c(18,21,24),],segments(BHDiameter, Height, BHDiameter, height.qfit[c(18,21,24)], col="Red", lwd=3) )
with( spruce.df, arrows(5,Height[24], BHDiameter[24], Height[24],lwd=2,col="Blue"))
with(spruce.df,text(2,Height[24], paste("Highest Cook's","\n", "distance",sep=" ")))
with(spruce.df, text(BHDiameter,Height, 1:36,cex=0.5,pos=4))
#########################################################################
layout(matrix(1:4,nr=2,nc=2,byrow=TRUE))
#Lets look at where the plots will go
layout.show(4)
#Plot the data
plot(Height~BHDiameter,bg="Blue",pch=21,cex=1.2,
ylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)),
main="Spruce height prediction",data=spruce.df)
# add the line
abline(spruce.lm)
#make a new plot
plot(Height~BHDiameter,bg="Blue",pch=21,cex=1.2,
ylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)),
main="Spruce height prediction",data=spruce.df)
abline(spruce.lm)
#make yhat the estimates of E[Height | BHDiameter]
yhat=with(spruce.df,predict(spruce.lm,data.frame(BHDiameter)))
yhat=fitted(spruce.lm)
# Draw in segments making the residuals (regression errors)
with(spruce.df,{
segments(BHDiameter,Height,BHDiameter,yhat)
})
RSS=with(spruce.df,sum((Height-yhat)^2))
RSS
#make a new plot
plot(Height~BHDiameter,bg="Blue",pch=21,cex=1.2,
ylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)),
main="Spruce height prediction",data=spruce.df)
#make nieve model
with(spruce.df, abline(h=mean(Height)))
abline(spruce.lm)
#make the explained errors (explained by the model)
with(spruce.df, segments(BHDiameter,mean(Height),BHDiameter,yhat,col="Red"))
MSS=with(spruce.df,sum((yhat-mean(Height))^2))
MSS
# Total error
#make a new plot
plot(Height~BHDiameter,bg="Blue",pch=21,cex=1.2,
ylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)),
main="Spruce height prediction",data=spruce.df)
with(spruce.df,abline(h=mean(Height)))
with(spruce.df, segments(BHDiameter,Height,BHDiameter,mean(Height),col="Green"))
TSS=with(spruce.df,sum((Height-mean(Height))^2))
TSS
RSS + MSS
MSS/TSS
summary(spruce.lm)
#obtain coefft values
coef(spruce.lm)
#Calculate new y values given x
predict(spruce.lm, data.frame(BHDiameter=c(15,18,20)))
anova(spruce.lm)
spruce2.lm=lm(Height~BHDiameter + I(BHDiameter^2),data=spruce.df)
summary(spruce2.lm)
### More on the problem
windows()
plot(Height~BHDiameter,bg="Blue",pch=21,cex=1.2,
ylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)),
main="Spruce height prediction",data=spruce.df)
yhatt=with(spruce.df,fitted(spruce2.lm))
with(spruce.df,plot(BHDiameter,yhatt,col="Red")
)
sum(residuals(spruce2.lm)^2)
plot(yhatt~BHDiameter,data=spruce.df,type="p")
summary(spruce2.lm)
anova(spruce2.lm)
anova(spruce.lm,spruce2.lm)
MSS
RSS
## piecewise linear model in R
## Model y = b0 + b1x + b2(x-xk)*(x>xk)
## You will need to change the code appropriately
sp2.df=within(spruce.df, X<-(BHDiameter-20)*(BHDiameter>20)) # this makes a new variable and places it within the same df
sp2.df
lmp=lm(Height~BHDiameter + X,data=sp2.df)
tmp=summary(lmp)
names(tmp)
myf = function(x,coef){
coef[1]+coef[2]*(x) + coef[3]*(x-18)*(x-18>0)
}
plot(spruce.df,main="Piecewise regression")
myf(0, coef=tmp$coefficients[,"Estimate"])
curve(myf(x,coef=tmp$coefficients[,"Estimate"] ),add=TRUE, lwd=2,col="Blue")
abline(v=18)
text(18,16,paste("R sq.=",round(tmp$r.squared,4) ))
|
% The COBRAToolbox: testVerifyModel.m
%
% Purpose:
% - Tests the Model Verification function
%
model = getDistributedModel('ecoli_core_model.mat');
% test whether the correct "invalid" subSystem is found
modelSub = model;
modelSub.subSystems(20) = {'blubb'};
res = verifyModel(modelSub,'silentCheck',true);
assert(~isempty(res))
if isfield(res,'Errors')
assert(isequal(res.Errors.propertiesNotMatched.subSystems, sprintf('Field does not match the required properties at the following positions: \n 20')));
end
% test whether rules are checked crrectly
modelRule = model;
modelRule.rules(3) = {'x(17) )'};
res = verifyModel(modelRule,'silentCheck',true);
assert(~isempty(res))
assert(isequal(res.Errors.propertiesNotMatched.rules, sprintf('Field does not match the required properties at the following positions: \n 3')));
|
lemma box01_nonempty [simp]: "box 0 One \<noteq> {}" |
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_CSCD_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_CSCD_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-trigonometric
This function object returns the cosecant in degree: \f$1/\sin(180/(\pi x))\f$.
@par Header <boost/simd/function/cscd.hpp>
@par Note
As most other trigonometric function cscd can be called with a
second optional parameter which is a tag on speed and accuracy
(see @ref cos for further details)
@see csc, cscpi,
@par Example:
@snippet cscd.cpp cscd
@par Possible output:
@snippet cscd.txt cscd
**/
IEEEValue cscd(IEEEValue const& x);
} }
#endif
#include <boost/simd/function/scalar/cscd.hpp>
#include <boost/simd/function/simd/cscd.hpp>
#endif
|
Require Import String.
Require Import core.utils.Utils.
Require Import core.Syntax.
Require Import core.Semantics.
Require Import core.Certification.
Require Import core.modeling.ModelingMetamodel.
Require Import core.Model.
Require Import transformations.Class2Relational.Class2Relational.
Require Import transformations.Class2Relational.ClassMetamodel.
Require Import transformations.Class2Relational.RelationalMetamodel.
Require Import core.utils.CpdtTactics.
Theorem All_classes_match_impl:
forall (cm : ClassModel) (c : Class),
exists (r : Rule),
matchPattern Class2Relational cm [ClassMetamodel_toObject ClassClass c] = [r].
Proof.
eexists.
reflexivity.
Qed. |
public export
data Fuel = Dry | More (Lazy Fuel)
public export
partial
forever : Fuel
forever = More forever
|
(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)
Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq.
Require Import fintype.
Lemma test15: forall (y : nat) (x : 'I_2), y < 1 -> val x = y -> Some x = insub y.
move=> y x le_1 defx; rewrite insubT ?(leq_trans le_1) // => ?.
by congr (Some _); apply: val_inj=> /=; exact: defx.
Qed.
Axiom P : nat -> Prop.
Axiom Q : forall n, P n -> Prop.
Definition R := fun (x : nat) (p : P x) m (q : P (x+1)) => m > 0.
Inductive myEx : Type := ExI : forall n (pn : P n) pn', Q n pn -> R n pn n pn' -> myEx.
Variable P1 : P 1.
Variable P11 : P (1 + 1).
Variable Q1 : forall P1, Q 1 P1.
Lemma testmE1 : myEx.
Proof.
apply: ExI 1 _ _ _ _.
match goal with |- P 1 => exact: P1 | _ => fail end.
match goal with |- P (1+1) => exact: P11 | _ => fail end.
match goal with |- forall p : P 1, Q 1 p => move=>*; exact: Q1 | _ => fail end.
match goal with |- forall (p : P 1) (q : P (1+1)), is_true (R 1 p 1 q) => done | _ => fail end.
Qed.
Lemma testE2 : exists y : { x | P x }, sval y = 1.
Proof.
apply: ex_intro (exist _ 1 _) _.
match goal with |- P 1 => exact: P1 | _ => fail end.
match goal with |- forall p : P 1, @sval _ _ (@exist _ _ 1 p) = 1 => done | _ => fail end.
Qed.
Lemma testE3 : exists y : { x | P x }, sval y = 1.
Proof.
have := (ex_intro _ (exist _ 1 _) _); apply.
match goal with |- P 1 => exact: P1 | _ => fail end.
match goal with |- forall p : P 1, @sval _ _ (@exist _ _ 1 p) = 1 => done | _ => fail end.
Qed.
Lemma testE4 : P 2 -> exists y : { x | P x }, sval y = 2.
Proof.
move=> P2; apply: ex_intro (exist _ 2 _) _.
match goal with |- @sval _ _ (@exist _ _ 2 P2) = 2 => done | _ => fail end.
Qed.
Hint Resolve P1.
Lemma testmE12 : myEx.
Proof.
apply: ExI 1 _ _ _ _.
match goal with |- P (1+1) => exact: P11 | _ => fail end.
match goal with |- Q 1 P1 => exact: Q1 | _ => fail end.
match goal with |- forall (q : P (1+1)), is_true (R 1 P1 1 q) => done | _ => fail end.
Qed.
Create HintDb SSR.
Hint Resolve P11 : SSR.
Ltac ssrautoprop := trivial with SSR.
Lemma testmE13 : myEx.
Proof.
apply: ExI 1 _ _ _ _.
match goal with |- Q 1 P1 => exact: Q1 | _ => fail end.
match goal with |- is_true (R 1 P1 1 P11) => done | _ => fail end.
Qed.
Definition R1 := fun (x : nat) (p : P x) m (q : P (x+1)) (r : Q x p) => m > 0.
Inductive myEx1 : Type :=
ExI1 : forall n (pn : P n) pn' (q : Q n pn), R1 n pn n pn' q -> myEx1.
Hint Resolve (Q1 P1) : SSR.
(* tests that goals in prop are solved in the right order, propagating instantiations,
thus the goal Q 1 ?p1 is faced by trivial after ?p1, and is thus evar free *)
Lemma testmE14 : myEx1.
Proof.
apply: ExI1 1 _ _ _ _.
match goal with |- is_true (R1 1 P1 1 P11 (Q1 P1)) => done | _ => fail end.
Qed.
|
import data.list.basic tactic.linarith
import list.lemmas.long_lemmas misc_lemmas
open list
/-- The minimum element of a non-empty list-/
def list.min {X : Type*} [decidable_linear_order X] :
Π (L : list X), (L ≠ []) → X
| ([]) hL := false.elim $ hL rfl
| (x :: []) hL := x
| (x :: y :: L) _ := min x (list.min (y :: L) dec_trivial)
/--extended version of list.min on lists of integers that maps the empty list to 0-/
def list.min' (L : list ℤ) : ℤ :=
if h : L = [] then 0 else list.min L h
/--If we have two non-empty lists of the same length and for each index, elements with the same
index differ by at most d, then their minimums differ by at most d-/
theorem list.min_change (L M : list ℤ) (hL : L ≠ []) (hLM : L.length = M.length) (hM : M ≠ []) (d : ℤ)
(hdist : ∀ (i : ℕ) (hiL : i < L.length) (hiM : i < M.length), abs (L.nth_le i hiL - M.nth_le i hiM) ≤ d) :
abs (L.min hL - M.min hM) ≤ d :=
begin
-- if L = nil, that contradicts hL
cases L with n Ln,
contradiction,
-- L = (n :: Ln)
revert n M, -- so the inductive hypothesis does not depend on n or M
induction Ln with n1 Ln1 IH,
-- base case : Ln = nil (so L = [n])
{
intros n M hM hL hLM hdist,
change 1 = length M at hLM, -- as L = [n], and length [n] = length (n :: nil) = 1 by definition
symmetry' at hLM, -- change 1 = length M to length M = 1
rw length_eq_one at hLM, -- now hLM implies M is a singleton
cases hLM with m hLM, -- say M = [m], for some a of type ℕ
simp only [hLM],
show abs (n - m) ≤ d, /- because by def of list.min the minimum of a singleton
is its only element -/
convert hdist 0 (zero_lt_one) _, -- that is true because by hdist, abs (L.nth_le 0 hiL - M.nth_le 0 hiM) ≤ d
-- have already told Lean i is 0 and 0 < 1 (which is the length of [n] by def)
-- prove 0 < length M
swap,
{rw hLM,
exact zero_lt_one},
/- now prove m = nth_le M 0 _ (which convert reduced the goal to as it Lean noticed
all other similarities to hdist)-/
simp only [hLM], --
refl, -- by def of nth_le
},
--inductive step : Ln = (n1 :: Ln1)
{ intros n M hM hL hLM hdist,
-- if M = nil, that contradicts hM
cases M with m Mm,
contradiction,
-- now M = (m :: Mm)
-- but if Mm = nil, then by hLM length (n :: n1 :: Ln1) = length (m :: nil). Contradiction!
cases Mm with m1 Mm1,
cases hLM,
-- so M = (m :: m1 :: Mm1)
unfold list.min, /- changes list.min (n :: n1 :: Ln1) hL to min n (list.min (n1 :: Ln1) _)
and list.min (m :: m1 :: Mm1) hM to min m (list.min (m1 :: Mm1) _)
(third constructor of list.min)-/
/- we want to use the inductive hypothesis with M being (m1 :: Mm1)-/
replace hLM := nat.succ_inj hLM, -- get : length (n1 :: Ln1) = length (m1 :: Mm1)
-- the following is the version of hdist for M being (m1 :: Mm1)
have hyp : (∀ (i : ℕ) (hiL : i < length (n1 :: Ln1)) (hiM : i < length (m1 :: Mm1)),
abs (nth_le (n1 :: Ln1) i hiL - nth_le (m1 :: Mm1) i hiM) ≤ d),
intros i hiL hiM,
exact hdist (i + 1) (nat.succ_lt_succ hiL) (nat.succ_lt_succ hiM), -- follows from hdist
/- use the inductive hypothesis to get (h : abs (list.min (n1 :: Ln1) _ - list.min (m1 :: Mm1) _) ≤ d)
(the other hypotheses, that the lists are non-empty, are true by decidability)-/
have h := IH n1 (m1 :: Mm1) dec_trivial dec_trivial hLM hyp,
have hmn : abs (n - m) ≤ d,
exact hdist 0 dec_trivial dec_trivial, -- n, m are the 0th elements, so holds by hdist
exact abs_min_sub_min hmn h} -- (see misc_lemmas)
end
/--If we have two lists of the same length and for each index, elements with the same
index differ by at most some non-negative value d, then their extended minimums (min') differ by at most d-/
lemma list.min'_change (L M : list ℤ) (hLM : L.length = M.length) (d : ℤ) (hd : 0 ≤ d)
(hdist : ∀ (i : ℕ) (hiL : i < L.length) (hiM : i < M.length), abs (L.nth_le i hiL - M.nth_le i hiM) ≤ d) :
abs (L.min' - M.min') ≤ d :=
begin
/- if M and L are non-empty, this is basically proven by the lemma above, because of
how list.min' is defined.
Therefore we prove the empty-list-case separately-/
cases M with m Mn,
-- M = nil (so hLM is : length L = length nil)
{rw length at hLM, -- length nil = 0 by def of length
rw length_eq_zero at hLM, -- length L = 0 ↔ L = nil
rw hLM,
-- now this is true by the definition of list.min' and hd
unfold list.min',
split_ifs,
{exact hd}, -- case where nil = nil
{contradiction},}, -- case where ¬ (nil = nil), a contradiction
-- M = (m :: Mn)
/- now this is true by lis.min_change, but we first need to show M and N are non-empty-/
{have hM : ¬ (m :: Mn : list ℤ) = nil := by simp,
have hL : ¬ L = nil,
{apply ne_nil_of_length_pos, -- prove 0 < length L instead
rw hLM,
exact dec_trivial,}, -- true by decideability
unfold list.min',
split_ifs, -- (L = nil)-case killed immediately
exact list.min_change L (m :: Mn) hL hLM hM d hdist,},
end
|
notes: read/string %lotslines
|
import classes.context_free.basics.inclusion
import classes.unrestricted.closure_properties.concatenation
import utilities.written_by_others.trim_assoc
import utilities.written_by_others.print_sorries
variables {T : Type}
private def wrap_CF_rule₁ {N₁ : Type} (N₂ : Type) (r : (N₁ × list (symbol T N₁))) :
((nnn T N₁ N₂) × list (nst T N₁ N₂)) :=
((sum.inl (some (sum.inl r.fst))), (list.map (wrap_symbol₁ N₂) r.snd))
private def wrap_CF_rule₂ {N₂ : Type} (N₁ : Type) (r : (N₂ × list (symbol T N₂))) :
((nnn T N₁ N₂) × list (nst T N₁ N₂)) :=
((sum.inl (some (sum.inr r.fst))), (list.map (wrap_symbol₂ N₁) r.snd))
private def CF_rules_for_terminals₁ (N₂ : Type) (g : CF_grammar T) :
list ((nnn T g.nt N₂) × list (nst T g.nt N₂)) :=
list.map (λ t, ((sum.inr (sum.inl t)), [symbol.terminal t])) (all_used_terminals (grammar_of_cfg g))
private def CF_rules_for_terminals₂ (N₁ : Type) (g : CF_grammar T) :
list ((nnn T N₁ g.nt) × list (nst T N₁ g.nt)) :=
list.map (λ t, ((sum.inr (sum.inr t)), [symbol.terminal t])) (all_used_terminals (grammar_of_cfg g))
private def big_CF_grammar (g₁ g₂ : CF_grammar T) : CF_grammar T :=
CF_grammar.mk
(nnn T g₁.nt g₂.nt)
(sum.inl none)
(((sum.inl none), [
symbol.nonterminal (sum.inl (some (sum.inl g₁.initial))),
symbol.nonterminal (sum.inl (some (sum.inr g₂.initial)))]
) :: (
(list.map (wrap_CF_rule₁ g₂.nt) g₁.rules ++ list.map (wrap_CF_rule₂ g₁.nt) g₂.rules) ++
(CF_rules_for_terminals₁ g₂.nt g₁ ++ CF_rules_for_terminals₂ g₁.nt g₂)
))
private lemma big_CF_grammar_same_language (g₁ g₂ : CF_grammar T) :
CF_language (big_CF_grammar g₁ g₂) = grammar_language (big_grammar (grammar_of_cfg g₁) (grammar_of_cfg g₂)) :=
begin
rw CF_language_eq_grammar_language,
congr,
unfold big_CF_grammar,
unfold grammar_of_cfg,
unfold big_grammar,
dsimp only [list.map],
congr,
repeat {
rw list.map_append,
},
trim,
{
apply congr_arg2,
{
unfold rules_for_terminals₁,
unfold CF_rules_for_terminals₁,
finish,
},
{
unfold rules_for_terminals₂,
unfold CF_rules_for_terminals₂,
finish,
},
},
end
/-- The class of context-free languages is closed under concatenation.
This theorem is proved by translation from general grammars.
Compare to `classes.context_free.closure_properties.concatenation.lean` which uses
a simpler and more effective construction (based on context-gree grammars only). -/
private theorem bonus_CF_of_CF_c_CF (L₁ : language T) (L₂ : language T) :
is_CF L₁ ∧ is_CF L₂ → is_CF (L₁ * L₂) :=
begin
rintro ⟨⟨g₁, eq_L₁⟩, ⟨g₂, eq_L₂⟩⟩,
rw CF_language_eq_grammar_language g₁ at eq_L₁,
rw CF_language_eq_grammar_language g₂ at eq_L₂,
use big_CF_grammar g₁ g₂,
rw big_CF_grammar_same_language,
apply set.eq_of_subset_of_subset,
{
intros w hyp,
rw ←eq_L₁,
rw ←eq_L₂,
exact in_concatenated_of_in_big hyp,
},
{
intros w hyp,
rw ←eq_L₁ at hyp,
rw ←eq_L₂ at hyp,
exact in_big_of_in_concatenated hyp,
},
end
#check bonus_CF_of_CF_c_CF
#print_sorries_in bonus_CF_of_CF_c_CF
|
import ring_theory.int.basic
lemma units_int.values (u: units ℤ): u = 1 ∨ u = -1 :=
begin
have p₁ := fintype.complete u,
cases p₁,
left, exact p₁,
cases p₁,
right, exact p₁,
exfalso, exact list.not_mem_nil u p₁,
end
|
State Before: s t : ℤ
r' : ℕ
s' t' : ℤ
⊢ xgcdAux 0 s t r' s' t' = (r', s', t') State After: no goals Tactic: simp [xgcdAux] |
// MIT License
//
// Copyright (c) 2021 Marko Malenic
//
// 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.
#include <iostream>
#include <spdlog/spdlog.h>
#include <boost/asio.hpp>
#include <atomic>
#include <evgetcore/EventHandler.h>
#include <boost/program_options.hpp>
#include <linux/input.h>
//#include "evgetcore/CommandLine/ParserLinux.h"
//#include "evgetcore/XInputHandler.h"
//#include "evgetcore/EventTransformerLinux.h"
//#include "evgetcore/SystemEventLoopLinux.h"
//#include "../checkinput/include/checkinput/EventDeviceLister.h"
using namespace std;
int main(int argc, char* argv[]) {
// CliOption::ParserLinux cmd{};
// cmd.parseCommandLine(argc, (const char**) argv);
//
// spdlog::set_level(cmd.getLogLevel());
//
// boost::asio::thread_pool pool{};
// auto context = pool.get_executor();
// evget::Storage<boost::asio::thread_pool::executor_type> storage{context};
// Display* display = XOpenDisplay(nullptr);
// evget::EventTransformerLinux transformer{*display};
// evget::SystemEventLoopLinux eventLoop{context, evget::XInputHandler{*display}};
//
// evget::EventHandler<boost::asio::thread_pool::executor_type, evget::XInputEvent> handler{context, storage, eventLoop};
//
// boost::asio::co_spawn(context, [&]() { return handler.start(); }, boost::asio::detached);
//
// if (cmd.isListEventDevices()) {
// evget::EventDeviceLister lister{};
// cout << lister;
// }
//
// pool.join();
// po::options_description cmdlineDesc("Allowed options");
// cmdlineDesc.add_options()
// ("help", "produce help message")
// ("compression", po::_value<int>(), "set compression level")
// ;
//
// po::variables_map vm;
// po::store(po::parse_command_line(argc, argv, cmdlineDesc), vm);
// po::notify(vm);
//
// if (vm.count("help")) {
// cout << cmdlineDesc << "\n";
// return 1;
// }
//
// if (vm.count("compression")) {
// cout << "Compression level was set to "
// << vm["compression"].as<int>() << ".\n";
// } else {
// cout << "Compression level was not set.\n";
// }
return 1;
} |
example (p q : Prop) (hp : p) : p ∨ q :=
by { left, assumption } <|> { right, assumption }
example (p q : Prop) (hq : q) : p ∨ q :=
by { left, assumption } <|> { right, assumption }
|
import tactic -- hide
import data.real.basic -- hide
/-
## The `cases` tactic
We have talked before about how to deal with a conjunction `∧` in the goal. Sometimes,
we may have a conjuntion in a hypothesis. In this case, the tactic `cases` breaks it into
two new hypotheses. If we do `cases h with h1 h2` it will replace a hypothesis of
the form `h : P ∧ Q` into `h1 : P` and `h2 : Q`.
In the following lemma, a direct application of `assumption` won't work,
because the goal is not *exactly* our assumption. We need to break `h` into two.
**Pro tip:** If there is a double implication in `h`, then again we can use `cases h`
to break it into two.
**Pro tip 2:** We can refer to the two parts of `h` as `h.1` and `h.2`, so sometimes
we won't need to break `h`...
-/
/- Lemma : no-side-bar
If $a=5$ and $b=3$, then $a=5$.
-/
lemma c1 (a b : ℕ) (h : a = 5 ∧ b = 3) : a = 5 :=
begin
cases h,
assumption,
end |
This is an overview of admation’s Reassign Tasks Feature. Dispense with having to scroll through spreadsheets to reassign a task urgently. This feature enables marketers to re-allocate tasks in just a few easy steps.
Click Resources found on the top navigation bar.
The Timeline View is where you can view the workload of each resource in your department. To search for a specific resource, use the Search bar.
Click the Cog icon next to the resource whose task you want to reassign.
Select Re-assign Tasks from the dropdown menu.
Click on the task you wish to reassign.
Another dropdown menu with the task’s details will appear. Click on the Assign Task icon.
Next you will be directed to the Reassigning Task screen. Reassign the task by dragging and dropping it onto a specific day on the timeline of a resource with sufficient capacity.
Click Done Assigning once you have reassigned the task.
View the details of the task from the Timeline View screen. |
[GOAL]
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝ : UniformSpace 𝕜
⊢ UniformSpace (m → n → 𝕜)
[PROOFSTEP]
infer_instance
[GOAL]
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝ : UniformSpace 𝕜
⊢ 𝓤 (Matrix m n 𝕜) = ⨅ (i : m) (j : n), Filter.comap (fun a => (Prod.fst a i j, Prod.snd a i j)) (𝓤 𝕜)
[PROOFSTEP]
erw [Pi.uniformity, Pi.uniformity]
[GOAL]
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝ : UniformSpace 𝕜
⊢ ⨅ (i : m),
Filter.comap (fun a => (Prod.fst a i, Prod.snd a i))
(⨅ (i : n), Filter.comap (fun a => (Prod.fst a i, Prod.snd a i)) (𝓤 𝕜)) =
⨅ (i : m) (j : n), Filter.comap (fun a => (Prod.fst a i j, Prod.snd a i j)) (𝓤 𝕜)
[PROOFSTEP]
simp_rw [Filter.comap_iInf, Filter.comap_comap]
[GOAL]
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝ : UniformSpace 𝕜
⊢ ⨅ (i : m) (i_1 : n),
Filter.comap ((fun a => (Prod.fst a i_1, Prod.snd a i_1)) ∘ fun a => (Prod.fst a i, Prod.snd a i)) (𝓤 𝕜) =
⨅ (i : m) (j : n), Filter.comap (fun a => (Prod.fst a i j, Prod.snd a i j)) (𝓤 𝕜)
[PROOFSTEP]
rfl
[GOAL]
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝¹ : UniformSpace 𝕜
β : Type u_4
inst✝ : UniformSpace β
f : β → Matrix m n 𝕜
⊢ UniformContinuous f ↔ ∀ (i : m) (j : n), UniformContinuous fun x => f x i j
[PROOFSTEP]
simp only [UniformContinuous, Matrix.uniformity, Filter.tendsto_iInf, Filter.tendsto_comap_iff]
[GOAL]
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝¹ : UniformSpace 𝕜
β : Type u_4
inst✝ : UniformSpace β
f : β → Matrix m n 𝕜
⊢ (∀ (i : m) (i_1 : n),
Filter.Tendsto ((fun a => (Prod.fst a i i_1, Prod.snd a i i_1)) ∘ fun x => (f x.fst, f x.snd)) (𝓤 β) (𝓤 𝕜)) ↔
∀ (i : m) (j : n), Filter.Tendsto (fun x => (f x.fst i j, f x.snd i j)) (𝓤 β) (𝓤 𝕜)
[PROOFSTEP]
apply Iff.intro
[GOAL]
case mp
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝¹ : UniformSpace 𝕜
β : Type u_4
inst✝ : UniformSpace β
f : β → Matrix m n 𝕜
⊢ (∀ (i : m) (i_1 : n),
Filter.Tendsto ((fun a => (Prod.fst a i i_1, Prod.snd a i i_1)) ∘ fun x => (f x.fst, f x.snd)) (𝓤 β) (𝓤 𝕜)) →
∀ (i : m) (j : n), Filter.Tendsto (fun x => (f x.fst i j, f x.snd i j)) (𝓤 β) (𝓤 𝕜)
[PROOFSTEP]
intro a
[GOAL]
case mpr
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝¹ : UniformSpace 𝕜
β : Type u_4
inst✝ : UniformSpace β
f : β → Matrix m n 𝕜
⊢ (∀ (i : m) (j : n), Filter.Tendsto (fun x => (f x.fst i j, f x.snd i j)) (𝓤 β) (𝓤 𝕜)) →
∀ (i : m) (i_1 : n),
Filter.Tendsto ((fun a => (Prod.fst a i i_1, Prod.snd a i i_1)) ∘ fun x => (f x.fst, f x.snd)) (𝓤 β) (𝓤 𝕜)
[PROOFSTEP]
intro a
[GOAL]
case mp
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝¹ : UniformSpace 𝕜
β : Type u_4
inst✝ : UniformSpace β
f : β → Matrix m n 𝕜
a :
∀ (i : m) (i_1 : n),
Filter.Tendsto ((fun a => (Prod.fst a i i_1, Prod.snd a i i_1)) ∘ fun x => (f x.fst, f x.snd)) (𝓤 β) (𝓤 𝕜)
⊢ ∀ (i : m) (j : n), Filter.Tendsto (fun x => (f x.fst i j, f x.snd i j)) (𝓤 β) (𝓤 𝕜)
[PROOFSTEP]
apply a
[GOAL]
case mpr
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝¹ : UniformSpace 𝕜
β : Type u_4
inst✝ : UniformSpace β
f : β → Matrix m n 𝕜
a : ∀ (i : m) (j : n), Filter.Tendsto (fun x => (f x.fst i j, f x.snd i j)) (𝓤 β) (𝓤 𝕜)
⊢ ∀ (i : m) (i_1 : n),
Filter.Tendsto ((fun a => (Prod.fst a i i_1, Prod.snd a i i_1)) ∘ fun x => (f x.fst, f x.snd)) (𝓤 β) (𝓤 𝕜)
[PROOFSTEP]
apply a
[GOAL]
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝¹ : UniformSpace 𝕜
inst✝ : CompleteSpace 𝕜
⊢ CompleteSpace (m → n → 𝕜)
[PROOFSTEP]
infer_instance
[GOAL]
m : Type u_1
n : Type u_2
𝕜 : Type u_3
inst✝¹ : UniformSpace 𝕜
inst✝ : SeparatedSpace 𝕜
⊢ SeparatedSpace (m → n → 𝕜)
[PROOFSTEP]
infer_instance
|
I still get excited with each set of these I build. I get a lot of customers who come to me complaining of Zipp hub problems such as short bearing life and needing constant adjustment. This is not terribly surprising as Zipp really builds race wheels more than anything but many many people use them to handle the bulk of their training too. While I think Zipp makes some amazing rims that can handle training volume their hubs leave something to be desired, especially if you spend much time in the rain. To get my customers the best of both worlds I really like how building a Zipp to a White Industries T11 works out, not only are the hubs incredibly durable but they roll really really well so you end up with wheels that are fast enough to win any of the worlds biggest races but durable enough to train on day in and day out!
Sick and tired of dealing with hubs that do not want to stay adjusted or bearings wearing out quickly in less than perfect weather? If you don't mind voiding a warranty this is the most elegant solution to all of your hub troubles, re-lace your rim to a White Industries hub! That way you get the best of both worlds and no compromises, one of the best rims out there laced to one of the smoothest and longest running hubs you can buy! |
Formal statement is: lemma of_real_neg_numeral [simp]: "of_real (- numeral w) = - numeral w" Informal statement is: $-1$ is the additive inverse of $1$. |
program program2
implicit none
call b
call b()
contains
subroutine b()
print *, "b"
end subroutine
end program
|
//
// Copyright (C) 2001-2021 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <GraphMol/RDKitBase.h>
#include <GraphMol/RDKitQueries.h>
#include <GraphMol/MolPickler.h>
#include <GraphMol/QueryOps.h>
#include <GraphMol/MonomerInfo.h>
#include <GraphMol/StereoGroup.h>
#include <GraphMol/SubstanceGroup.h>
#include <RDGeneral/utils.h>
#include <RDGeneral/RDLog.h>
#include <RDGeneral/StreamOps.h>
#include <RDGeneral/types.h>
#include <DataStructs/DatastructsStreamOps.h>
#include <Query/QueryObjects.h>
#include <map>
#include <iostream>
#include <cstdint>
#include <boost/algorithm/string.hpp>
#ifdef RDK_THREADSAFE_SSS
#include <mutex>
#endif
using std::int32_t;
using std::uint32_t;
namespace RDKit {
const int32_t MolPickler::versionMajor = 13;
const int32_t MolPickler::versionMinor = 0;
const int32_t MolPickler::versionPatch = 0;
const int32_t MolPickler::endianId = 0xDEADBEEF;
void streamWrite(std::ostream &ss, MolPickler::Tags tag) {
auto tmp = static_cast<unsigned char>(tag);
streamWrite(ss, tmp);
}
template <typename T>
void streamWrite(std::ostream &ss, MolPickler::Tags tag, const T &what) {
streamWrite(ss, tag);
streamWrite(ss, what);
};
void streamRead(std::istream &ss, MolPickler::Tags &tag, int version) {
if (version < 7000) {
int32_t tmp;
streamRead(ss, tmp, version);
if (tmp < 0 || tmp >= MolPickler::Tags::INVALID_TAG) {
throw MolPicklerException("Invalid tag found.");
}
tag = static_cast<MolPickler::Tags>(tmp);
} else {
unsigned char tmp;
streamRead(ss, tmp, version);
if (tmp >= MolPickler::Tags::INVALID_TAG) {
throw MolPicklerException("Invalid tag found.");
}
tag = static_cast<MolPickler::Tags>(tmp);
}
}
void streamReadPositiveChar(std::istream &ss, char &res, int version) {
streamRead(ss, res, version);
if (res < 0) {
throw MolPicklerException("invalid value in pickle");
}
}
namespace {
static unsigned int defaultProperties = PicklerOps::NoProps;
static CustomPropHandlerVec defaultPropHandlers = {};
#ifdef RDK_THREADSAFE_SSS
std::mutex &propmutex_get() {
// create on demand
static std::mutex _mutex;
return _mutex;
}
void propmutex_create() {
std::mutex &mutex = propmutex_get();
std::lock_guard<std::mutex> test_lock(mutex);
}
std::mutex &GetPropMutex() {
static std::once_flag flag;
std::call_once(flag, propmutex_create);
return propmutex_get();
}
#endif
void write_sstream_to_stream(std::ostream &outStream,
const std::stringstream &toWrite) {
auto ts = toWrite.str();
int32_t tmpInt = static_cast<int32_t>(ts.size());
streamWrite(outStream, tmpInt);
outStream.write(ts.c_str(), sizeof(char) * tmpInt);
}
} // namespace
unsigned int MolPickler::getDefaultPickleProperties() {
#ifdef RDK_THREADSAFE_SSS
std::lock_guard<std::mutex> lock(GetPropMutex());
#endif
unsigned int props = defaultProperties;
return props;
}
void MolPickler::setDefaultPickleProperties(unsigned int props) {
#ifdef RDK_THREADSAFE_SSS
std::lock_guard<std::mutex> lock(GetPropMutex());
#endif
defaultProperties = props;
}
const CustomPropHandlerVec &MolPickler::getCustomPropHandlers() {
#ifdef RDK_THREADSAFE_SSS
std::lock_guard<std::mutex> lock(GetPropMutex());
#endif
if (defaultPropHandlers.size() == 0) {
// initialize handlers
defaultPropHandlers.push_back(
std::make_shared<DataStructsExplicitBitVecPropHandler>());
}
return defaultPropHandlers;
}
void MolPickler::addCustomPropHandler(const CustomPropHandler &handler) {
#ifdef RDK_THREADSAFE_SSS
std::lock_guard<std::mutex> lock(GetPropMutex());
#endif
if (defaultPropHandlers.size() == 0) {
// initialize handlers
defaultPropHandlers.push_back(
std::make_shared<DataStructsExplicitBitVecPropHandler>());
}
defaultPropHandlers.push_back(
std::shared_ptr<CustomPropHandler>(handler.clone()));
}
using namespace Queries;
namespace PicklerOps {
template <class T>
QueryDetails getQueryDetails(const Query<int, T const *, true> *query) {
PRECONDITION(query, "no query");
if (typeid(*query) == typeid(AndQuery<int, T const *, true>)) {
return QueryDetails(MolPickler::QUERY_AND);
} else if (typeid(*query) == typeid(OrQuery<int, T const *, true>)) {
return QueryDetails(MolPickler::QUERY_OR);
} else if (typeid(*query) == typeid(XOrQuery<int, T const *, true>)) {
return QueryDetails(MolPickler::QUERY_XOR);
} else if (typeid(*query) == typeid(EqualityQuery<int, T const *, true>)) {
return QueryDetails(std::make_tuple(
MolPickler::QUERY_EQUALS,
static_cast<const EqualityQuery<int, T const *, true> *>(query)
->getVal(),
static_cast<const EqualityQuery<int, T const *, true> *>(query)
->getTol()));
} else if (typeid(*query) == typeid(GreaterQuery<int, T const *, true>)) {
return QueryDetails(std::make_tuple(
MolPickler::QUERY_GREATER,
static_cast<const GreaterQuery<int, T const *, true> *>(query)
->getVal(),
static_cast<const GreaterQuery<int, T const *, true> *>(query)
->getTol()));
} else if (typeid(*query) ==
typeid(GreaterEqualQuery<int, T const *, true>)) {
return QueryDetails(std::make_tuple(
MolPickler::QUERY_GREATEREQUAL,
static_cast<const GreaterEqualQuery<int, T const *, true> *>(query)
->getVal(),
static_cast<const GreaterEqualQuery<int, T const *, true> *>(query)
->getTol()));
} else if (typeid(*query) == typeid(LessQuery<int, T const *, true>)) {
return QueryDetails(std::make_tuple(
MolPickler::QUERY_LESS,
static_cast<const LessQuery<int, T const *, true> *>(query)->getVal(),
static_cast<const LessQuery<int, T const *, true> *>(query)->getTol()));
} else if (typeid(*query) == typeid(LessEqualQuery<int, T const *, true>)) {
return QueryDetails(std::make_tuple(
MolPickler::QUERY_LESSEQUAL,
static_cast<const LessEqualQuery<int, T const *, true> *>(query)
->getVal(),
static_cast<const LessEqualQuery<int, T const *, true> *>(query)
->getTol()));
} else if (typeid(*query) == typeid(AtomRingQuery)) {
return QueryDetails(std::make_tuple(
MolPickler::QUERY_ATOMRING,
static_cast<const EqualityQuery<int, T const *, true> *>(query)
->getVal(),
static_cast<const EqualityQuery<int, T const *, true> *>(query)
->getTol()));
} else if (typeid(*query) == typeid(Query<int, T const *, true>)) {
return QueryDetails(MolPickler::QUERY_NULL);
} else if (typeid(*query) == typeid(RangeQuery<int, T const *, true>)) {
char ends;
bool lowerOpen, upperOpen;
boost::tie(lowerOpen, upperOpen) =
static_cast<const RangeQuery<int, T const *, true> *>(query)
->getEndsOpen();
ends = 0 | (rdcast<int>(lowerOpen) << 1) | rdcast<int>(upperOpen);
return QueryDetails(std::make_tuple(
MolPickler::QUERY_RANGE,
static_cast<const RangeQuery<int, T const *, true> *>(query)
->getLower(),
static_cast<const RangeQuery<int, T const *, true> *>(query)
->getUpper(),
static_cast<const EqualityQuery<int, T const *, true> *>(query)
->getTol(),
ends));
} else if (typeid(*query) == typeid(SetQuery<int, T const *, true>)) {
std::set<int32_t> tset(
static_cast<const SetQuery<int, T const *, true> *>(query)->beginSet(),
static_cast<const SetQuery<int, T const *, true> *>(query)->endSet());
return QueryDetails(
std::make_tuple(MolPickler::QUERY_SET, std::move(tset)));
} else {
throw MolPicklerException("do not know how to pickle part of the query.");
}
}
template RDKIT_GRAPHMOL_EXPORT QueryDetails getQueryDetails<RDKit::Atom>(
const Queries::Query<int, RDKit::Atom const *, true> *query);
template RDKIT_GRAPHMOL_EXPORT QueryDetails getQueryDetails<RDKit::Bond>(
const Queries::Query<int, RDKit::Bond const *, true> *query);
} // namespace PicklerOps
namespace {
template <class T>
void pickleQuery(std::ostream &ss, const Query<int, T const *, true> *query) {
PRECONDITION(query, "no query");
streamWrite(ss, query->getDescription());
if (!query->getTypeLabel().empty()) {
streamWrite(ss, MolPickler::QUERY_TYPELABEL);
streamWrite(ss, query->getTypeLabel());
}
if (query->getNegation()) {
streamWrite(ss, MolPickler::QUERY_ISNEGATED);
}
if (typeid(*query) == typeid(RecursiveStructureQuery)) {
streamWrite(ss, MolPickler::QUERY_RECURSIVE);
streamWrite(ss, MolPickler::QUERY_VALUE);
MolPickler::pickleMol(
((const RecursiveStructureQuery *)query)->getQueryMol(), ss);
} else {
auto qdetails = PicklerOps::getQueryDetails(query);
switch (qdetails.which()) {
case 0:
streamWrite(ss, boost::get<MolPickler::Tags>(qdetails));
break;
case 1: {
auto v = boost::get<std::tuple<MolPickler::Tags, int32_t>>(qdetails);
streamWrite(ss, std::get<0>(v));
streamWrite(ss, MolPickler::QUERY_VALUE, std::get<1>(v));
} break;
case 2: {
auto v = boost::get<std::tuple<MolPickler::Tags, int32_t, int32_t>>(
qdetails);
streamWrite(ss, std::get<0>(v));
streamWrite(ss, MolPickler::QUERY_VALUE, std::get<1>(v));
streamWrite(ss, std::get<2>(v));
} break;
case 3: {
auto v = boost::get<
std::tuple<MolPickler::Tags, int32_t, int32_t, int32_t, char>>(
qdetails);
streamWrite(ss, std::get<0>(v));
streamWrite(ss, MolPickler::QUERY_VALUE, std::get<1>(v));
streamWrite(ss, std::get<2>(v));
streamWrite(ss, std::get<3>(v));
streamWrite(ss, std::get<4>(v));
} break;
case 4: {
auto v = boost::get<std::tuple<MolPickler::Tags, std::set<int32_t>>>(
qdetails);
streamWrite(ss, std::get<0>(v));
const auto &tset = std::get<1>(v);
int32_t sz = tset.size();
streamWrite(ss, MolPickler::QUERY_VALUE, sz);
for (auto val : tset) {
streamWrite(ss, val);
}
} break;
default:
throw MolPicklerException(
"do not know how to pickle part of the query.");
}
}
// now the children:
streamWrite(ss, MolPickler::QUERY_NUMCHILDREN,
static_cast<unsigned char>(query->endChildren() -
query->beginChildren()));
typename Query<int, T const *, true>::CHILD_VECT_CI cit;
for (cit = query->beginChildren(); cit != query->endChildren(); ++cit) {
pickleQuery(ss, cit->get());
}
}
template <class T>
Query<int, T const *, true> *buildBaseQuery(std::istream &ss, T const *owner,
MolPickler::Tags tag, int version) {
PRECONDITION(owner, "no query");
std::string descr;
Query<int, T const *, true> *res = nullptr;
int32_t val;
int32_t nMembers;
char cval;
const unsigned int lowerOpen = 1 << 1;
const unsigned int upperOpen = 1;
switch (tag) {
case MolPickler::QUERY_AND:
res = new AndQuery<int, T const *, true>();
break;
case MolPickler::QUERY_OR:
res = new OrQuery<int, T const *, true>();
break;
case MolPickler::QUERY_XOR:
res = new XOrQuery<int, T const *, true>();
break;
case MolPickler::QUERY_EQUALS:
res = new EqualityQuery<int, T const *, true>();
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_VALUE) {
delete res;
throw MolPicklerException(
"Bad pickle format: QUERY_VALUE tag not found.");
}
streamRead(ss, val, version);
static_cast<EqualityQuery<int, T const *, true> *>(res)->setVal(val);
streamRead(ss, val, version);
static_cast<EqualityQuery<int, T const *, true> *>(res)->setTol(val);
break;
case MolPickler::QUERY_GREATER:
res = new GreaterQuery<int, T const *, true>();
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_VALUE) {
delete res;
throw MolPicklerException(
"Bad pickle format: QUERY_VALUE tag not found.");
}
streamRead(ss, val, version);
static_cast<GreaterQuery<int, T const *, true> *>(res)->setVal(val);
streamRead(ss, val, version);
static_cast<GreaterQuery<int, T const *, true> *>(res)->setTol(val);
break;
case MolPickler::QUERY_GREATEREQUAL:
res = new GreaterEqualQuery<int, T const *, true>();
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_VALUE) {
delete res;
throw MolPicklerException(
"Bad pickle format: QUERY_VALUE tag not found.");
}
streamRead(ss, val, version);
static_cast<GreaterEqualQuery<int, T const *, true> *>(res)->setVal(val);
streamRead(ss, val, version);
static_cast<GreaterEqualQuery<int, T const *, true> *>(res)->setTol(val);
break;
case MolPickler::QUERY_LESS:
res = new LessQuery<int, T const *, true>();
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_VALUE) {
delete res;
throw MolPicklerException(
"Bad pickle format: QUERY_VALUE tag not found.");
}
streamRead(ss, val, version);
static_cast<LessQuery<int, T const *, true> *>(res)->setVal(val);
streamRead(ss, val, version);
static_cast<LessQuery<int, T const *, true> *>(res)->setTol(val);
break;
case MolPickler::QUERY_LESSEQUAL:
res = new LessEqualQuery<int, T const *, true>();
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_VALUE) {
delete res;
throw MolPicklerException(
"Bad pickle format: QUERY_VALUE tag not found.");
}
streamRead(ss, val, version);
static_cast<LessEqualQuery<int, T const *, true> *>(res)->setVal(val);
streamRead(ss, val, version);
static_cast<LessEqualQuery<int, T const *, true> *>(res)->setTol(val);
break;
case MolPickler::QUERY_RANGE:
res = new RangeQuery<int, T const *, true>();
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_VALUE) {
delete res;
throw MolPicklerException(
"Bad pickle format: QUERY_VALUE tag not found.");
}
streamRead(ss, val, version);
static_cast<RangeQuery<int, T const *, true> *>(res)->setLower(val);
streamRead(ss, val, version);
static_cast<RangeQuery<int, T const *, true> *>(res)->setUpper(val);
streamRead(ss, val, version);
static_cast<RangeQuery<int, T const *, true> *>(res)->setTol(val);
streamRead(ss, cval, version);
static_cast<RangeQuery<int, T const *, true> *>(res)->setEndsOpen(
cval & lowerOpen, cval & upperOpen);
break;
case MolPickler::QUERY_SET:
res = new SetQuery<int, T const *, true>();
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_VALUE) {
delete res;
throw MolPicklerException(
"Bad pickle format: QUERY_VALUE tag not found.");
}
streamRead(ss, nMembers);
while (nMembers > 0) {
streamRead(ss, val, version);
static_cast<SetQuery<int, T const *, true> *>(res)->insert(val);
--nMembers;
}
break;
case MolPickler::QUERY_NULL:
res = new Query<int, T const *, true>();
break;
default:
throw MolPicklerException("unknown query-type tag encountered");
}
POSTCONDITION(res, "no match found");
return res;
}
Query<int, Atom const *, true> *unpickleQuery(std::istream &ss,
Atom const *owner, int version) {
PRECONDITION(owner, "no query");
std::string descr;
std::string typeLabel = "";
bool isNegated = false;
Query<int, Atom const *, true> *res;
streamRead(ss, descr, version);
MolPickler::Tags tag;
streamRead(ss, tag, version);
if (tag == MolPickler::QUERY_TYPELABEL) {
streamRead(ss, typeLabel, version);
streamRead(ss, tag, version);
}
if (tag == MolPickler::QUERY_ISNEGATED) {
isNegated = true;
streamRead(ss, tag, version);
}
int32_t val;
ROMol *tmpMol;
switch (tag) {
case MolPickler::QUERY_ATOMRING:
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_VALUE) {
throw MolPicklerException(
"Bad pickle format: QUERY_VALUE tag not found.");
}
res = new AtomRingQuery();
streamRead(ss, val, version);
static_cast<EqualityQuery<int, Atom const *, true> *>(res)->setVal(val);
streamRead(ss, val, version);
static_cast<EqualityQuery<int, Atom const *, true> *>(res)->setTol(val);
break;
case MolPickler::QUERY_RECURSIVE:
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_VALUE) {
throw MolPicklerException(
"Bad pickle format: QUERY_VALUE tag not found.");
}
tmpMol = new ROMol();
MolPickler::molFromPickle(ss, tmpMol);
res = new RecursiveStructureQuery(tmpMol);
break;
default:
res = buildBaseQuery(ss, owner, tag, version);
break;
}
CHECK_INVARIANT(res, "no query!");
res->setNegation(isNegated);
res->setDescription(descr);
if (!typeLabel.empty()) res->setTypeLabel(typeLabel);
QueryOps::finalizeQueryFromDescription(res, owner);
// read in the children:
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_NUMCHILDREN) {
throw MolPicklerException(
"Bad pickle format: QUERY_NUMCHILDREN tag not found.");
}
unsigned char numChildren;
streamRead(ss, numChildren, version);
while (numChildren > 0) {
Query<int, Atom const *, true> *child = unpickleQuery(ss, owner, version);
res->addChild(Query<int, Atom const *, true>::CHILD_TYPE(child));
--numChildren;
}
return res;
}
Query<int, Bond const *, true> *unpickleQuery(std::istream &ss,
Bond const *owner, int version) {
PRECONDITION(owner, "no query");
std::string descr;
bool isNegated = false;
Query<int, Bond const *, true> *res;
streamRead(ss, descr, version);
MolPickler::Tags tag;
streamRead(ss, tag, version);
if (tag == MolPickler::QUERY_ISNEGATED) {
isNegated = true;
streamRead(ss, tag, version);
}
res = buildBaseQuery(ss, owner, tag, version);
CHECK_INVARIANT(res, "no query!");
res->setNegation(isNegated);
res->setDescription(descr);
QueryOps::finalizeQueryFromDescription(res, owner);
// read in the children:
streamRead(ss, tag, version);
if (tag != MolPickler::QUERY_NUMCHILDREN) {
throw MolPicklerException(
"Bad pickle format: QUERY_NUMCHILDREN tag not found.");
}
unsigned char numChildren;
streamRead(ss, numChildren, version);
while (numChildren > 0) {
Query<int, Bond const *, true> *child = unpickleQuery(ss, owner, version);
res->addChild(Query<int, Bond const *, true>::CHILD_TYPE(child));
--numChildren;
}
return res;
}
void pickleAtomPDBResidueInfo(std::ostream &ss,
const AtomPDBResidueInfo *info) {
PRECONDITION(info, "no info");
if (info->getSerialNumber()) {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_SERIALNUMBER,
info->getSerialNumber());
}
if (info->getAltLoc() != "") {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_ALTLOC, info->getAltLoc());
}
if (info->getResidueName() != "") {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_RESIDUENAME,
info->getResidueName());
}
if (info->getResidueNumber()) {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_RESIDUENUMBER,
info->getResidueNumber());
}
if (info->getChainId() != "") {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_CHAINID, info->getChainId());
}
if (info->getInsertionCode() != "") {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_INSERTIONCODE,
info->getInsertionCode());
}
if (info->getOccupancy()) {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_OCCUPANCY,
info->getOccupancy());
}
if (info->getTempFactor()) {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_TEMPFACTOR,
info->getTempFactor());
}
if (info->getIsHeteroAtom()) {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_ISHETEROATOM,
static_cast<char>(info->getIsHeteroAtom()));
}
if (info->getSecondaryStructure()) {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_SECONDARYSTRUCTURE,
info->getSecondaryStructure());
}
if (info->getSegmentNumber()) {
streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_SEGMENTNUMBER,
info->getSegmentNumber());
}
}
void unpickleAtomPDBResidueInfo(std::istream &ss, AtomPDBResidueInfo *info,
int version) {
PRECONDITION(info, "no info");
std::string sval;
double dval;
char cval;
unsigned int uival;
int ival;
MolPickler::Tags tag = MolPickler::BEGIN_ATOM_MONOMER;
while (tag != MolPickler::END_ATOM_MONOMER) {
streamRead(ss, tag, version);
switch (tag) {
case MolPickler::ATOM_PDB_RESIDUE_SERIALNUMBER:
streamRead(ss, ival, version);
info->setSerialNumber(ival);
break;
case MolPickler::ATOM_PDB_RESIDUE_ALTLOC:
streamRead(ss, sval, version);
info->setAltLoc(sval);
break;
case MolPickler::ATOM_PDB_RESIDUE_RESIDUENAME:
streamRead(ss, sval, version);
info->setResidueName(sval);
break;
case MolPickler::ATOM_PDB_RESIDUE_RESIDUENUMBER:
streamRead(ss, ival, version);
info->setResidueNumber(ival);
break;
case MolPickler::ATOM_PDB_RESIDUE_CHAINID:
streamRead(ss, sval, version);
info->setChainId(sval);
break;
case MolPickler::ATOM_PDB_RESIDUE_INSERTIONCODE:
streamRead(ss, sval, version);
info->setInsertionCode(sval);
break;
case MolPickler::ATOM_PDB_RESIDUE_OCCUPANCY:
streamRead(ss, dval, version);
info->setOccupancy(dval);
break;
case MolPickler::ATOM_PDB_RESIDUE_TEMPFACTOR:
streamRead(ss, dval, version);
info->setTempFactor(dval);
break;
case MolPickler::ATOM_PDB_RESIDUE_ISHETEROATOM:
streamRead(ss, cval, version);
info->setIsHeteroAtom(cval);
break;
case MolPickler::ATOM_PDB_RESIDUE_SECONDARYSTRUCTURE:
streamRead(ss, uival, version);
info->setSecondaryStructure(uival);
break;
case MolPickler::ATOM_PDB_RESIDUE_SEGMENTNUMBER:
streamRead(ss, uival, version);
info->setSegmentNumber(uival);
break;
case MolPickler::END_ATOM_MONOMER:
break;
default:
throw MolPicklerException(
"unrecognized tag while parsing atom peptide residue info");
}
}
}
void pickleAtomMonomerInfo(std::ostream &ss, const AtomMonomerInfo *info) {
PRECONDITION(info, "no info");
streamWrite(ss, info->getName());
streamWrite(ss, static_cast<unsigned int>(info->getMonomerType()));
switch (info->getMonomerType()) {
case AtomMonomerInfo::UNKNOWN:
case AtomMonomerInfo::OTHER:
break;
case AtomMonomerInfo::PDBRESIDUE:
pickleAtomPDBResidueInfo(ss,
static_cast<const AtomPDBResidueInfo *>(info));
break;
default:
throw MolPicklerException("unrecognized MonomerType");
}
}
AtomMonomerInfo *unpickleAtomMonomerInfo(std::istream &ss, int version) {
MolPickler::Tags tag;
std::string nm;
streamRead(ss, nm, version);
unsigned int typ;
streamRead(ss, typ, version);
AtomMonomerInfo *res;
switch (typ) {
case AtomMonomerInfo::UNKNOWN:
case AtomMonomerInfo::OTHER:
streamRead(ss, tag, version);
if (tag != MolPickler::END_ATOM_MONOMER) {
throw MolPicklerException(
"did not find expected end of atom monomer info");
}
res =
new AtomMonomerInfo(RDKit::AtomMonomerInfo::AtomMonomerType(typ), nm);
break;
case AtomMonomerInfo::PDBRESIDUE:
res = static_cast<AtomMonomerInfo *>(new AtomPDBResidueInfo(nm));
unpickleAtomPDBResidueInfo(ss, static_cast<AtomPDBResidueInfo *>(res),
version);
break;
default:
throw MolPicklerException("unrecognized MonomerType");
}
return res;
}
} // namespace
// Resets the `exceptionState` of the passed stream `ss` in the destructor to
// the `exceptionState` the stream ss was in, before setting
// `newExceptionState`.
struct IOStreamExceptionStateResetter {
std::ios &originalStream;
std::ios_base::iostate originalExceptionState;
IOStreamExceptionStateResetter(std::ios &ss,
std::ios_base::iostate newExceptionState)
: originalStream(ss), originalExceptionState(ss.exceptions()) {
ss.exceptions(newExceptionState);
}
~IOStreamExceptionStateResetter() {
if (originalStream) {
originalStream.exceptions(originalExceptionState);
}
}
};
void MolPickler::pickleMol(const ROMol *mol, std::ostream &ss) {
pickleMol(mol, ss, MolPickler::getDefaultPickleProperties());
}
void MolPickler::pickleMol(const ROMol *mol, std::ostream &ss,
unsigned int propertyFlags) {
PRECONDITION(mol, "empty molecule");
// Ensure that the exception state of the `ostream` is reset to the previous
// state after we're done.
// Also enable exceptions here, so we're notified when we've reached EOF or
// any other problem.
IOStreamExceptionStateResetter resetter(ss, std::ios_base::eofbit |
std::ios_base::failbit |
std::ios_base::badbit);
try {
streamWrite(ss, endianId);
streamWrite(ss, static_cast<int>(VERSION));
streamWrite(ss, versionMajor);
streamWrite(ss, versionMinor);
streamWrite(ss, versionPatch);
#ifndef OLD_PICKLE
if (mol->getNumAtoms() > 255) {
_pickle<int32_t>(mol, ss, propertyFlags);
} else {
_pickle<unsigned char>(mol, ss, propertyFlags);
}
#else
_pickleV1(mol, ss);
#endif
} catch (const std::ios_base::failure &e) {
if (ss.eof()) {
throw MolPicklerException(
"Bad pickle format: unexpected End-of-File while writing");
} else if (ss.bad()) {
throw MolPicklerException("Bad pickle format: write error while writing");
} else if (ss.fail()) {
throw MolPicklerException(
"Bad pickle format: logical error while writing");
} else {
throw MolPicklerException(
"Bad pickle format: unexpected error while writing");
}
}
}
void MolPickler::pickleMol(const ROMol &mol, std::ostream &ss) {
pickleMol(&mol, ss, MolPickler::getDefaultPickleProperties());
}
void MolPickler::pickleMol(const ROMol *mol, std::string &res) {
pickleMol(mol, res, MolPickler::getDefaultPickleProperties());
}
void MolPickler::pickleMol(const ROMol *mol, std::string &res,
unsigned int pickleFlags) {
PRECONDITION(mol, "empty molecule");
std::stringstream ss(std::ios_base::binary | std::ios_base::out |
std::ios_base::in);
MolPickler::pickleMol(mol, ss, pickleFlags);
res = ss.str();
}
void MolPickler::pickleMol(const ROMol &mol, std::string &ss) {
pickleMol(&mol, ss, MolPickler::getDefaultPickleProperties());
}
// NOTE: if the mol passed in here already has atoms and bonds, they will
// be left intact. The side effect is that ALL atom and bond bookmarks
// will be blown out by the end of this process.
void MolPickler::molFromPickle(std::istream &ss, ROMol *mol,
unsigned int propertyFlags) {
PRECONDITION(mol, "empty molecule");
// Ensure that the exception state of the `istream` is reset to the previous
// state after we're done.
// Also enable exceptions here, so we're notified when we've reached EOF or
// any other problem.
IOStreamExceptionStateResetter resetter(ss, std::ios_base::eofbit |
std::ios_base::failbit |
std::ios_base::badbit);
try {
int32_t tmpInt;
mol->clearAllAtomBookmarks();
mol->clearAllBondBookmarks();
streamRead(ss, tmpInt);
if (tmpInt != endianId) {
throw MolPicklerException(
"Bad pickle format: bad endian ID or invalid file format");
}
streamRead(ss, tmpInt);
if (static_cast<Tags>(tmpInt) != VERSION) {
throw MolPicklerException("Bad pickle format: no version tag");
}
int32_t majorVersion, minorVersion, patchVersion;
streamRead(ss, majorVersion);
streamRead(ss, minorVersion);
streamRead(ss, patchVersion);
if (majorVersion > versionMajor ||
(majorVersion == versionMajor && minorVersion > versionMinor)) {
BOOST_LOG(rdWarningLog)
<< "Depickling from a version number (" << majorVersion << "."
<< minorVersion << ")"
<< "that is higher than our version (" << versionMajor << "."
<< versionMinor << ").\nThis probably won't work." << std::endl;
}
// version sanity checking
if (majorVersion > 1000 || minorVersion > 100 || patchVersion > 100) {
throw MolPicklerException("unreasonable version numbers");
}
majorVersion = 1000 * majorVersion + minorVersion * 10 + patchVersion;
if (majorVersion == 1) {
_depickleV1(ss, mol);
} else {
int32_t numAtoms;
streamRead(ss, numAtoms, majorVersion);
if (numAtoms > 255) {
_depickle<int32_t>(ss, mol, majorVersion, numAtoms, propertyFlags);
} else {
_depickle<unsigned char>(ss, mol, majorVersion, numAtoms,
propertyFlags);
}
}
mol->clearAllAtomBookmarks();
mol->clearAllBondBookmarks();
if (majorVersion < 4000) {
// FIX for issue 220 - probably better to change the pickle format later
MolOps::assignStereochemistry(*mol, true);
}
} catch (const std::ios_base::failure &e) {
if (ss.eof()) {
throw MolPicklerException(
"Bad pickle format: unexpected End-of-File while reading");
} else if (ss.bad()) {
throw MolPicklerException("Bad pickle format: read error while reading");
} else if (ss.fail()) {
throw MolPicklerException(
"Bad pickle format: logical error while reading");
} else {
throw MolPicklerException(
"Bad pickle format: unexpected error while reading");
}
}
}
void MolPickler::molFromPickle(const std::string &pickle, ROMol *mol,
unsigned int propertyFlags) {
PRECONDITION(mol, "empty molecule");
std::stringstream ss(std::ios_base::binary | std::ios_base::out |
std::ios_base::in);
ss.write(pickle.c_str(), pickle.length());
MolPickler::molFromPickle(ss, mol, propertyFlags);
}
//--------------------------------------
//
// Molecules
//
//--------------------------------------
template <typename T>
void MolPickler::_pickle(const ROMol *mol, std::ostream &ss,
unsigned int propertyFlags) {
PRECONDITION(mol, "empty molecule");
int32_t tmpInt;
std::map<int, int> atomIdxMap;
std::map<int, int> bondIdxMap;
tmpInt = static_cast<int32_t>(mol->getNumAtoms());
streamWrite(ss, tmpInt);
tmpInt = static_cast<int32_t>(mol->getNumBonds());
streamWrite(ss, tmpInt);
unsigned char flag = 0x1 << 7;
streamWrite(ss, flag);
// -------------------
//
// Write Atoms
//
// -------------------
streamWrite(ss, BEGINATOM);
ROMol::ConstAtomIterator atIt;
int nWritten = 0;
for (atIt = mol->beginAtoms(); atIt != mol->endAtoms(); ++atIt) {
_pickleAtom<T>(ss, *atIt);
atomIdxMap[(*atIt)->getIdx()] = nWritten;
nWritten++;
}
// -------------------
//
// Write Bonds
//
// -------------------
streamWrite(ss, BEGINBOND);
for (unsigned int i = 0; i < mol->getNumBonds(); i++) {
auto bond = mol->getBondWithIdx(i);
_pickleBond<T>(ss, bond, atomIdxMap);
bondIdxMap[bond->getIdx()] = i;
}
// -------------------
//
// Write Rings (if present)
//
// -------------------
const RingInfo *ringInfo = mol->getRingInfo();
if (ringInfo && ringInfo->isInitialized()) {
streamWrite(ss, BEGINSSSR);
_pickleSSSR<T>(ss, ringInfo, atomIdxMap);
}
// -------------------
//
// Write SubstanceGroups (if present)
//
// -------------------
const auto &sgroups = getSubstanceGroups(*mol);
if (!sgroups.empty()) {
streamWrite(ss, BEGINSGROUP);
tmpInt = static_cast<int32_t>(sgroups.size());
streamWrite(ss, tmpInt);
for (const auto &sgroup : sgroups) {
_pickleSubstanceGroup<T>(ss, sgroup, atomIdxMap, bondIdxMap);
}
}
// Write Stereo Groups
{
auto &stereo_groups = mol->getStereoGroups();
if (stereo_groups.size() > 0u) {
streamWrite(ss, BEGINSTEREOGROUP);
_pickleStereo<T>(ss, stereo_groups, atomIdxMap);
}
}
if (!(propertyFlags & PicklerOps::NoConformers)) {
std::stringstream tss;
if (propertyFlags & PicklerOps::CoordsAsDouble) {
// pickle the conformations
streamWrite(ss, BEGINCONFS_DOUBLE);
tmpInt = static_cast<int32_t>(mol->getNumConformers());
streamWrite(tss, tmpInt);
for (auto ci = mol->beginConformers(); ci != mol->endConformers(); ++ci) {
const Conformer *conf = ci->get();
_pickleConformer<T, double>(tss, conf);
}
} else {
// pickle the conformations
streamWrite(ss, BEGINCONFS);
tmpInt = static_cast<int32_t>(mol->getNumConformers());
streamWrite(tss, tmpInt);
for (auto ci = mol->beginConformers(); ci != mol->endConformers(); ++ci) {
const Conformer *conf = ci->get();
_pickleConformer<T, float>(tss, conf);
}
}
if (propertyFlags & PicklerOps::MolProps) {
streamWrite(tss, BEGINCONFPROPS);
std::stringstream tss2;
for (auto ci = mol->beginConformers(); ci != mol->endConformers(); ++ci) {
const Conformer *conf = ci->get();
_pickleProperties(tss2, *conf, propertyFlags);
}
write_sstream_to_stream(tss, tss2);
}
write_sstream_to_stream(ss, tss);
}
if (propertyFlags & PicklerOps::MolProps) {
streamWrite(ss, BEGINPROPS);
std::stringstream tss;
_pickleProperties(tss, *mol, propertyFlags);
write_sstream_to_stream(ss, tss);
streamWrite(ss, ENDPROPS);
}
if (propertyFlags & PicklerOps::AtomProps) {
streamWrite(ss, BEGINATOMPROPS);
std::stringstream tss;
for (ROMol::ConstAtomIterator atIt = mol->beginAtoms();
atIt != mol->endAtoms(); ++atIt) {
_pickleProperties(tss, **atIt, propertyFlags);
}
write_sstream_to_stream(ss, tss);
streamWrite(ss, ENDPROPS);
}
if (propertyFlags & PicklerOps::BondProps) {
streamWrite(ss, BEGINBONDPROPS);
std::stringstream tss;
for (ROMol::ConstBondIterator bondIt = mol->beginBonds();
bondIt != mol->endBonds(); ++bondIt) {
_pickleProperties(tss, **bondIt, propertyFlags);
}
write_sstream_to_stream(ss, tss);
streamWrite(ss, ENDPROPS);
}
streamWrite(ss, ENDMOL);
}
template <typename T>
void MolPickler::_depickle(std::istream &ss, ROMol *mol, int version,
int numAtoms, unsigned int propertyFlags) {
PRECONDITION(mol, "empty molecule");
bool directMap = mol->getNumAtoms() == 0;
Tags tag;
int32_t tmpInt;
// int numAtoms,numBonds;
int numBonds;
bool haveQuery = false;
streamRead(ss, tmpInt, version);
numBonds = tmpInt;
// did we include coordinates
bool includeCoords = false;
if (version >= 3000) {
unsigned char flag;
streamRead(ss, flag, version);
if (flag & 0x1 << 7) {
includeCoords = true;
}
}
// -------------------
//
// Read Atoms
//
// -------------------
streamRead(ss, tag, version);
if (tag != BEGINATOM) {
throw MolPicklerException("Bad pickle format: BEGINATOM tag not found.");
}
Conformer *conf = nullptr;
if ((version >= 2000 && version < 3000) && includeCoords) {
// there can only one conformation - since the positions were stored on
// the atoms themselves in this version
conf = new Conformer(numAtoms);
mol->addConformer(conf, true);
}
for (int i = 0; i < numAtoms; i++) {
RDGeom::Point3D pos;
Atom *atom = _addAtomFromPickle<T>(ss, mol, pos, version, directMap);
if ((version >= 2000 && version < 3000) && includeCoords) {
// this is a older pickle so we go the pos
conf->setAtomPos(i, pos);
}
if (!directMap) {
mol->setAtomBookmark(atom, i);
}
if (atom->hasQuery()) {
haveQuery = true;
}
}
// -------------------
//
// Read Bonds
//
// -------------------
streamRead(ss, tag, version);
if (tag != BEGINBOND) {
throw MolPicklerException("Bad pickle format: BEGINBOND tag not found.");
}
for (int i = 0; i < numBonds; i++) {
Bond *bond = _addBondFromPickle<T>(ss, mol, version, directMap);
if (!directMap) {
mol->setBondBookmark(bond, i);
}
}
// -------------------
//
// Read Rings (if needed)
//
// -------------------
streamRead(ss, tag, version);
if (tag == BEGINSSSR) {
_addRingInfoFromPickle<T>(ss, mol, version, directMap);
streamRead(ss, tag, version);
}
// -------------------
//
// Read SubstanceGroups (if needed)
//
// -------------------
if (tag == BEGINSGROUP) {
streamRead(ss, tmpInt, version);
// Create SubstanceGroups
for (int i = 0; i < tmpInt; ++i) {
auto sgroup = _getSubstanceGroupFromPickle<T>(ss, mol, version);
addSubstanceGroup(*mol, sgroup);
}
streamRead(ss, tag, version);
}
if (tag == BEGINSTEREOGROUP) {
_depickleStereo<T>(ss, mol, version);
streamRead(ss, tag, version);
}
if (tag == BEGINCONFS || tag == BEGINCONFS_DOUBLE) {
int32_t blkSize = 0;
if (version >= 13000) {
streamRead(ss, blkSize, version);
}
if (version >= 13000 && (propertyFlags & PicklerOps::NoConformers)) {
// not reading coordinates, so just skip over those bytes
ss.seekg(blkSize, std::ios_base::cur);
streamRead(ss, tag, version);
} else {
// read in the conformation
streamRead(ss, tmpInt, version);
std::vector<unsigned int> cids(tmpInt);
for (auto i = 0; i < tmpInt; i++) {
Conformer *conf;
if (tag == BEGINCONFS) {
conf = _conformerFromPickle<T, float>(ss, version);
} else {
conf = _conformerFromPickle<T, double>(ss, version);
}
mol->addConformer(conf);
cids[i] = conf->getId();
}
streamRead(ss, tag, version);
if (tag == BEGINCONFPROPS) {
int32_t blkSize = 0;
if (version >= 13000) {
streamRead(ss, blkSize, version);
}
if (version >= 13000 && !(propertyFlags & PicklerOps::MolProps)) {
ss.seekg(blkSize, std::ios_base::cur);
} else {
for (auto cid : cids) {
_unpickleProperties(ss, mol->getConformer(cid));
}
}
streamRead(ss, tag, version);
}
}
}
while (tag != ENDMOL) {
if (tag == BEGINPROPS) {
int32_t blkSize = 0;
if (version >= 13000) {
streamRead(ss, blkSize, version);
}
if (version >= 13000 && !(propertyFlags & PicklerOps::MolProps)) {
ss.seekg(blkSize, std::ios_base::cur);
} else {
_unpickleProperties(ss, *mol);
}
streamRead(ss, tag, version);
} else if (tag == BEGINATOMPROPS) {
int32_t blkSize = 0;
if (version >= 13000) {
streamRead(ss, blkSize, version);
}
if (version >= 13000 && !(propertyFlags & PicklerOps::AtomProps)) {
ss.seekg(blkSize, std::ios_base::cur);
} else {
for (ROMol::AtomIterator atIt = mol->beginAtoms();
atIt != mol->endAtoms(); ++atIt) {
_unpickleProperties(ss, **atIt);
}
}
streamRead(ss, tag, version);
} else if (tag == BEGINBONDPROPS) {
int32_t blkSize = 0;
if (version >= 13000) {
streamRead(ss, blkSize, version);
}
if (version >= 13000 && !(propertyFlags & PicklerOps::BondProps)) {
ss.seekg(blkSize, std::ios_base::cur);
} else {
for (ROMol::BondIterator bdIt = mol->beginBonds();
bdIt != mol->endBonds(); ++bdIt) {
_unpickleProperties(ss, **bdIt);
}
}
streamRead(ss, tag, version);
} else if (tag == BEGINQUERYATOMDATA) {
for (ROMol::AtomIterator atIt = mol->beginAtoms();
atIt != mol->endAtoms(); ++atIt) {
_unpickleAtomData(ss, *atIt, version);
}
streamRead(ss, tag, version);
} else {
break; // break to tag != ENDMOL
}
if (tag != ENDPROPS) {
throw MolPicklerException("Bad pickle format: ENDPROPS tag not found.");
}
streamRead(ss, tag, version);
}
if (tag != ENDMOL) {
throw MolPicklerException("Bad pickle format: ENDMOL tag not found.");
}
if (haveQuery) {
// we didn't read any property info for atoms with associated
// queries. update their property caches
// (was sf.net Issue 3316407)
for (ROMol::AtomIterator atIt = mol->beginAtoms(); atIt != mol->endAtoms();
++atIt) {
Atom *atom = *atIt;
if (atom->hasQuery()) {
atom->updatePropertyCache(false);
}
}
}
}
//--------------------------------------
//
// Atoms
//
//--------------------------------------
namespace {
bool getAtomMapNumber(const Atom *atom, int &mapNum) {
PRECONDITION(atom, "bad atom");
if (!atom->hasProp(common_properties::molAtomMapNumber)) {
return false;
}
bool res = true;
int tmpInt;
try {
atom->getProp(common_properties::molAtomMapNumber, tmpInt);
} catch (boost::bad_any_cast &) {
const std::string &tmpSVal =
atom->getProp<std::string>(common_properties::molAtomMapNumber);
try {
tmpInt = boost::lexical_cast<int>(tmpSVal);
} catch (boost::bad_lexical_cast &) {
res = false;
}
}
if (res) {
mapNum = tmpInt;
}
return res;
}
} // namespace
int32_t MolPickler::_pickleAtomData(std::ostream &tss, const Atom *atom) {
int32_t propFlags = 0;
char tmpChar;
signed char tmpSchar;
// tmpFloat=atom->getMass()-PeriodicTable::getTable()->getAtomicWeight(atom->getAtomicNum());
// if(fabs(tmpFloat)>.0001){
// propFlags |= 1;
// streamWrite(tss,tmpFloat);
// }
tmpSchar = static_cast<signed char>(atom->getFormalCharge());
if (tmpSchar != 0) {
propFlags |= 1 << 1;
streamWrite(tss, tmpSchar);
}
tmpChar = static_cast<char>(atom->getChiralTag());
if (tmpChar != 0) {
propFlags |= 1 << 2;
streamWrite(tss, tmpChar);
}
tmpChar = static_cast<char>(atom->getHybridization());
if (tmpChar != static_cast<char>(Atom::SP3)) {
propFlags |= 1 << 3;
streamWrite(tss, tmpChar);
}
tmpChar = static_cast<char>(atom->getNumExplicitHs());
if (tmpChar != 0) {
propFlags |= 1 << 4;
streamWrite(tss, tmpChar);
}
if (atom->d_explicitValence > 0) {
tmpChar = static_cast<char>(atom->d_explicitValence);
propFlags |= 1 << 5;
streamWrite(tss, tmpChar);
}
if (atom->d_implicitValence > 0) {
tmpChar = static_cast<char>(atom->d_implicitValence);
propFlags |= 1 << 6;
streamWrite(tss, tmpChar);
}
tmpChar = static_cast<char>(atom->getNumRadicalElectrons());
if (tmpChar != 0) {
propFlags |= 1 << 7;
streamWrite(tss, tmpChar);
}
unsigned int tmpuint = atom->getIsotope();
if (tmpuint > 0) {
propFlags |= 1 << 8;
streamWrite(tss, tmpuint);
}
return propFlags;
}
void MolPickler::_unpickleAtomData(std::istream &ss, Atom *atom, int version) {
int propFlags;
char tmpChar;
signed char tmpSchar;
streamRead(ss, propFlags, version);
if (propFlags & 1) {
float tmpFloat;
streamRead(ss, tmpFloat, version);
int iso = static_cast<int>(floor(tmpFloat + atom->getMass() + .0001));
atom->setIsotope(iso);
}
if (propFlags & (1 << 1)) {
streamRead(ss, tmpSchar, version);
} else {
tmpSchar = 0;
}
atom->setFormalCharge(static_cast<int>(tmpSchar));
if (propFlags & (1 << 2)) {
streamReadPositiveChar(ss, tmpChar, version);
} else {
tmpChar = 0;
}
atom->setChiralTag(static_cast<Atom::ChiralType>(tmpChar));
if (propFlags & (1 << 3)) {
streamReadPositiveChar(ss, tmpChar, version);
} else {
tmpChar = Atom::SP3;
}
atom->setHybridization(static_cast<Atom::HybridizationType>(tmpChar));
if (propFlags & (1 << 4)) {
streamRead(ss, tmpChar, version);
} else {
tmpChar = 0;
}
atom->setNumExplicitHs(tmpChar);
if (propFlags & (1 << 5)) {
streamRead(ss, tmpChar, version);
} else {
tmpChar = 0;
}
atom->d_explicitValence = tmpChar;
if (propFlags & (1 << 6)) {
streamRead(ss, tmpChar, version);
} else {
tmpChar = 0;
}
atom->d_implicitValence = tmpChar;
if (propFlags & (1 << 7)) {
streamReadPositiveChar(ss, tmpChar, version);
} else {
tmpChar = 0;
}
atom->d_numRadicalElectrons = static_cast<unsigned int>(tmpChar);
atom->d_isotope = 0;
if (propFlags & (1 << 8)) {
unsigned int tmpuint;
streamRead(ss, tmpuint, version);
atom->setIsotope(tmpuint);
}
}
// T refers to the type of the atom indices written
template <typename T>
void MolPickler::_pickleAtom(std::ostream &ss, const Atom *atom) {
PRECONDITION(atom, "empty atom");
char tmpChar;
unsigned char tmpUchar;
int tmpInt;
char flags;
tmpUchar = atom->getAtomicNum() % 256;
streamWrite(ss, tmpUchar);
flags = 0;
if (atom->getIsAromatic()) {
flags |= 0x1 << 6;
}
if (atom->getNoImplicit()) {
flags |= 0x1 << 5;
}
if (atom->hasQuery()) {
flags |= 0x1 << 4;
}
if (getAtomMapNumber(atom, tmpInt)) {
flags |= 0x1 << 3;
}
if (atom->hasProp(common_properties::dummyLabel)) {
flags |= 0x1 << 2;
}
if (atom->getMonomerInfo()) {
flags |= 0x1 << 1;
}
streamWrite(ss, flags);
std::stringstream tss(std::ios_base::binary | std::ios_base::out |
std::ios_base::in);
int32_t propFlags = _pickleAtomData(tss, atom);
streamWrite(ss, propFlags);
ss.write(tss.str().c_str(), tss.str().size());
if (atom->hasQuery()) {
streamWrite(ss, BEGINQUERY);
pickleQuery(ss, static_cast<const QueryAtom *>(atom)->getQuery());
streamWrite(ss, ENDQUERY);
}
if (getAtomMapNumber(atom, tmpInt)) {
if (tmpInt >= 0 && tmpInt < 128) {
tmpChar = static_cast<char>(tmpInt);
streamWrite(ss, ATOM_MAPNUMBER, tmpChar);
} else {
tmpChar = static_cast<char>(255);
streamWrite(ss, ATOM_MAPNUMBER, tmpChar);
streamWrite(ss, tmpInt);
}
}
if (atom->hasProp(common_properties::dummyLabel)) {
streamWrite(ss, ATOM_DUMMYLABEL,
atom->getProp<std::string>(common_properties::dummyLabel));
}
if (atom->getMonomerInfo()) {
streamWrite(ss, BEGIN_ATOM_MONOMER);
pickleAtomMonomerInfo(ss, atom->getMonomerInfo());
streamWrite(ss, END_ATOM_MONOMER);
}
}
template <typename T, typename C>
void MolPickler::_pickleConformer(std::ostream &ss, const Conformer *conf) {
PRECONDITION(conf, "empty conformer");
char tmpChr = static_cast<int>(conf->is3D());
streamWrite(ss, tmpChr);
auto tmpInt = static_cast<int32_t>(conf->getId());
streamWrite(ss, tmpInt);
T tmpT = static_cast<T>(conf->getNumAtoms());
streamWrite(ss, tmpT);
const RDGeom::POINT3D_VECT &pts = conf->getPositions();
for (const auto &pt : pts) {
C tmpFloat;
tmpFloat = static_cast<C>(pt.x);
streamWrite(ss, tmpFloat);
tmpFloat = static_cast<C>(pt.y);
streamWrite(ss, tmpFloat);
tmpFloat = static_cast<C>(pt.z);
streamWrite(ss, tmpFloat);
}
}
template <typename T, typename C>
Conformer *MolPickler::_conformerFromPickle(std::istream &ss, int version) {
C tmpFloat;
bool is3D = true;
if (version > 4000) {
char tmpChr;
streamRead(ss, tmpChr, version);
is3D = static_cast<bool>(tmpChr);
}
int tmpInt;
streamRead(ss, tmpInt, version);
auto cid = static_cast<unsigned int>(tmpInt);
T tmpT;
streamRead(ss, tmpT, version);
auto numAtoms = static_cast<unsigned int>(tmpT);
auto *conf = new Conformer(numAtoms);
conf->setId(cid);
conf->set3D(is3D);
try {
for (unsigned int i = 0; i < numAtoms; i++) {
streamRead(ss, tmpFloat, version);
conf->getAtomPos(i).x = static_cast<double>(tmpFloat);
streamRead(ss, tmpFloat, version);
conf->getAtomPos(i).y = static_cast<double>(tmpFloat);
streamRead(ss, tmpFloat, version);
conf->getAtomPos(i).z = static_cast<double>(tmpFloat);
}
} catch (...) {
delete conf;
throw;
}
return conf;
}
template <typename T>
Atom *MolPickler::_addAtomFromPickle(std::istream &ss, ROMol *mol,
RDGeom::Point3D &pos, int version,
bool directMap) {
RDUNUSED_PARAM(directMap);
PRECONDITION(mol, "empty molecule");
float x, y, z;
char tmpChar;
unsigned char tmpUchar;
signed char tmpSchar;
char flags;
Tags tag;
Atom *atom = nullptr;
int atomicNum = 0;
streamRead(ss, tmpUchar, version);
atomicNum = tmpUchar;
bool hasQuery = false;
streamRead(ss, flags, version);
if (version > 5000) {
hasQuery = flags & 0x1 << 4;
}
if (!hasQuery) {
atom = new Atom(atomicNum);
} else {
atom = new QueryAtom();
if (atomicNum) {
// can't set this in the constructor because that builds a
// query and we're going to take care of that later:
atom->setAtomicNum(atomicNum);
}
}
atom->setIsAromatic(flags & 0x1 << 6);
atom->setNoImplicit(flags & 0x1 << 5);
bool hasAtomMap = 0, hasDummyLabel = 0;
if (version >= 6020) {
hasAtomMap = flags & 0x1 << 3;
hasDummyLabel = flags & 0x1 << 2;
}
bool hasMonomerInfo = 0;
if (version >= 7020) {
hasMonomerInfo = flags & 0x1 << 1;
}
// are coordinates present?
if (flags & 0x1 << 7) {
streamRead(ss, x, version);
pos.x = static_cast<double>(x);
streamRead(ss, y, version);
pos.y = static_cast<double>(y);
streamRead(ss, z, version);
pos.z = static_cast<double>(z);
}
if (version <= 5000 || !hasQuery) {
if (version < 7000) {
if (version < 6030) {
streamRead(ss, tmpSchar, version);
// FIX: technically should be handling this in order to maintain true
// backwards compatibility
// atom->setMass(PeriodicTable::getTable()->getAtomicWeight(atom->getAtomicNum())+
// static_cast<int>(tmpSchar));
} else {
float tmpFloat;
streamRead(ss, tmpFloat, version);
// FIX: technically should be handling this in order to maintain true
// backwards compatibility
// atom->setMass(tmpFloat);
}
streamRead(ss, tmpSchar, version);
atom->setFormalCharge(static_cast<int>(tmpSchar));
streamRead(ss, tmpChar, version);
atom->setChiralTag(static_cast<Atom::ChiralType>(tmpChar));
streamRead(ss, tmpChar, version);
atom->setHybridization(static_cast<Atom::HybridizationType>(tmpChar));
streamRead(ss, tmpChar, version);
atom->setNumExplicitHs(static_cast<int>(tmpChar));
streamRead(ss, tmpChar, version);
atom->d_explicitValence = tmpChar;
streamRead(ss, tmpChar, version);
atom->d_implicitValence = tmpChar;
if (version > 6000) {
streamRead(ss, tmpChar, version);
atom->d_numRadicalElectrons = static_cast<unsigned int>(tmpChar);
}
} else {
_unpickleAtomData(ss, atom, version);
}
} else if (version > 5000) {
// we have a query
if (version >= 9000) {
_unpickleAtomData(ss, atom, version);
}
streamRead(ss, tag, version);
if (tag != BEGINQUERY) {
throw MolPicklerException("Bad pickle format: BEGINQUERY tag not found.");
}
static_cast<QueryAtom *>(atom)->setQuery(unpickleQuery(ss, atom, version));
streamRead(ss, tag, version);
if (tag != ENDQUERY) {
throw MolPicklerException("Bad pickle format: ENDQUERY tag not found.");
}
// atom->setNumExplicitHs(0);
}
if (version > 5000) {
if (version < 6020) {
unsigned int sPos = rdcast<unsigned int>(ss.tellg());
Tags tag;
streamRead(ss, tag, version);
if (tag == ATOM_MAPNUMBER) {
int32_t tmpInt;
streamRead(ss, tmpChar, version);
tmpInt = tmpChar;
atom->setProp(common_properties::molAtomMapNumber, tmpInt);
} else {
ss.seekg(sPos);
}
} else {
if (hasAtomMap) {
Tags tag;
streamRead(ss, tag, version);
if (tag != ATOM_MAPNUMBER) {
throw MolPicklerException(
"Bad pickle format: ATOM_MAPNUMBER tag not found.");
}
int tmpInt;
streamRead(ss, tmpChar, version);
// the test for tmpChar below seems redundant, but on at least
// the POWER8 architecture it seems that chars may be unsigned
// by default.
if ((tmpChar < 0 || tmpChar > 127) && version > 9000) {
streamRead(ss, tmpInt, version);
} else {
tmpInt = tmpChar;
}
atom->setProp(common_properties::molAtomMapNumber, tmpInt);
}
if (hasDummyLabel) {
streamRead(ss, tag, version);
if (tag != ATOM_DUMMYLABEL) {
throw MolPicklerException(
"Bad pickle format: ATOM_DUMMYLABEL tag not found.");
}
std::string tmpStr;
streamRead(ss, tmpStr, version);
atom->setProp(common_properties::dummyLabel, tmpStr);
}
}
}
if (version >= 7020) {
if (hasMonomerInfo) {
streamRead(ss, tag, version);
if (tag != BEGIN_ATOM_MONOMER) {
throw MolPicklerException(
"Bad pickle format: BEGIN_ATOM_MONOMER tag not found.");
}
atom->setMonomerInfo(unpickleAtomMonomerInfo(ss, version));
}
}
mol->addAtom(atom, false, true);
return atom;
}
//--------------------------------------
//
// Bonds
//
//--------------------------------------
template <typename T>
void MolPickler::_pickleBond(std::ostream &ss, const Bond *bond,
std::map<int, int> &atomIdxMap) {
PRECONDITION(bond, "empty bond");
T tmpT;
char tmpChar;
char flags;
tmpT = static_cast<T>(atomIdxMap[bond->getBeginAtomIdx()]);
streamWrite(ss, tmpT);
tmpT = static_cast<T>(atomIdxMap[bond->getEndAtomIdx()]);
streamWrite(ss, tmpT);
flags = 0;
if (bond->getIsAromatic()) {
flags |= 0x1 << 6;
}
if (bond->getIsConjugated()) {
flags |= 0x1 << 5;
}
if (bond->hasQuery()) {
flags |= 0x1 << 4;
}
if (bond->getBondType() != Bond::SINGLE) {
flags |= 0x1 << 3;
}
if (bond->getBondDir() != Bond::NONE) {
flags |= 0x1 << 2;
}
if (bond->getStereo() != Bond::STEREONONE) {
flags |= 0x1 << 1;
}
streamWrite(ss, flags);
if (bond->getBondType() != Bond::SINGLE) {
tmpChar = static_cast<char>(bond->getBondType());
streamWrite(ss, tmpChar);
}
if (bond->getBondDir() != Bond::NONE) {
tmpChar = static_cast<char>(bond->getBondDir());
streamWrite(ss, tmpChar);
}
// write info about the stereochemistry:
if (bond->getStereo() != Bond::STEREONONE) {
tmpChar = static_cast<char>(bond->getStereo());
streamWrite(ss, tmpChar);
const INT_VECT &stereoAts = bond->getStereoAtoms();
tmpChar = rdcast<unsigned int>(stereoAts.size());
streamWrite(ss, tmpChar);
for (int stereoAt : stereoAts) {
tmpT = static_cast<T>(stereoAt);
streamWrite(ss, tmpT);
}
}
if (bond->hasQuery()) {
streamWrite(ss, BEGINQUERY);
pickleQuery(ss, static_cast<const QueryBond *>(bond)->getQuery());
streamWrite(ss, ENDQUERY);
}
}
template <typename T>
Bond *MolPickler::_addBondFromPickle(std::istream &ss, ROMol *mol, int version,
bool directMap) {
PRECONDITION(mol, "empty molecule");
char tmpChar;
char flags;
int begIdx, endIdx;
T tmpT;
Bond *bond = nullptr;
streamRead(ss, tmpT, version);
if (directMap) {
begIdx = tmpT;
} else {
begIdx = mol->getAtomWithBookmark(static_cast<int>(tmpT))->getIdx();
}
streamRead(ss, tmpT, version);
if (directMap) {
endIdx = tmpT;
} else {
endIdx = mol->getAtomWithBookmark(static_cast<int>(tmpT))->getIdx();
}
streamRead(ss, flags, version);
bool hasQuery = flags & 0x1 << 4;
if (version <= 5000 || (version <= 7000 && !hasQuery) || version > 7000) {
bond = new Bond();
bond->setIsAromatic(flags & 0x1 << 6);
bond->setIsConjugated(flags & 0x1 << 5);
if (version < 7000) {
streamReadPositiveChar(ss, tmpChar, version);
bond->setBondType(static_cast<Bond::BondType>(tmpChar));
streamReadPositiveChar(ss, tmpChar, version);
bond->setBondDir(static_cast<Bond::BondDir>(tmpChar));
if (version > 3000) {
streamReadPositiveChar(ss, tmpChar, version);
auto stereo = static_cast<Bond::BondStereo>(tmpChar);
bond->setStereo(stereo);
if (stereo != Bond::STEREONONE) {
streamRead(ss, tmpChar, version);
for (char i = 0; i < tmpChar; ++i) {
streamRead(ss, tmpT, version);
bond->getStereoAtoms().push_back(static_cast<int>(tmpT));
}
}
}
} else {
if (flags & (0x1 << 3)) {
streamReadPositiveChar(ss, tmpChar, version);
bond->setBondType(static_cast<Bond::BondType>(tmpChar));
} else {
bond->setBondType(Bond::SINGLE);
}
if (flags & (0x1 << 2)) {
streamReadPositiveChar(ss, tmpChar, version);
bond->setBondDir(static_cast<Bond::BondDir>(tmpChar));
} else {
bond->setBondDir(Bond::NONE);
}
if (flags & (0x1 << 1)) {
streamReadPositiveChar(ss, tmpChar, version);
auto stereo = static_cast<Bond::BondStereo>(tmpChar);
streamRead(ss, tmpChar, version);
for (char i = 0; i < tmpChar; ++i) {
streamRead(ss, tmpT, version);
bond->getStereoAtoms().push_back(static_cast<int>(tmpT));
}
bond->setStereo(stereo);
} else {
bond->setStereo(Bond::STEREONONE);
}
}
}
if (version > 5000 && hasQuery) {
Tags tag;
if (bond) {
Bond *tbond = bond;
bond = new QueryBond(*bond);
delete tbond;
} else {
bond = new QueryBond();
}
// we have a query:
streamRead(ss, tag, version);
if (tag != BEGINQUERY) {
delete bond;
throw MolPicklerException("Bad pickle format: BEGINQUERY tag not found.");
}
static_cast<QueryBond *>(bond)->setQuery(unpickleQuery(ss, bond, version));
streamRead(ss, tag, version);
if (tag != ENDQUERY) {
delete bond;
throw MolPicklerException("Bad pickle format: ENDQUERY tag not found.");
}
}
if (bond) {
bond->setBeginAtomIdx(begIdx);
bond->setEndAtomIdx(endIdx);
mol->addBond(bond, true);
}
return bond;
}
//--------------------------------------
//
// Rings
//
//--------------------------------------
template <typename T>
void MolPickler::_pickleSSSR(std::ostream &ss, const RingInfo *ringInfo,
std::map<int, int> &atomIdxMap) {
PRECONDITION(ringInfo, "missing ring info");
T tmpT;
tmpT = ringInfo->numRings();
streamWrite(ss, tmpT);
for (unsigned int i = 0; i < ringInfo->numRings(); i++) {
INT_VECT ring;
ring = ringInfo->atomRings()[i];
tmpT = static_cast<T>(ring.size());
streamWrite(ss, tmpT);
for (int &j : ring) {
tmpT = static_cast<T>(atomIdxMap[j]);
streamWrite(ss, tmpT);
}
#if 0
ring = ringInfo->bondRings()[i];
tmpT = static_cast<T>(ring.size());
streamWrite(ss,tmpT);
for(unsigned int j=0;j<ring.size();j++){
tmpT = static_cast<T>(ring[j]);
streamWrite(ss,tmpT);
}
#endif
}
}
template <typename T>
void MolPickler::_addRingInfoFromPickle(std::istream &ss, ROMol *mol,
int version, bool directMap) {
PRECONDITION(mol, "empty molecule");
RingInfo *ringInfo = mol->getRingInfo();
if (!ringInfo->isInitialized()) {
ringInfo->initialize();
}
T numRings;
streamRead(ss, numRings, version);
if (numRings > 0) {
ringInfo->preallocate(mol->getNumAtoms(), mol->getNumBonds());
for (unsigned int i = 0; i < static_cast<unsigned int>(numRings); i++) {
T tmpT;
T ringSize;
streamRead(ss, ringSize, version);
if (ringSize < 0) {
throw MolPicklerException("negative ring size");
}
INT_VECT atoms(static_cast<int>(ringSize));
INT_VECT bonds(static_cast<int>(ringSize));
for (unsigned int j = 0; j < static_cast<unsigned int>(ringSize); j++) {
streamRead(ss, tmpT, version);
if (directMap) {
atoms[j] = static_cast<int>(tmpT);
if (atoms[j] < 0 || atoms[j] >= mol->getNumAtoms()) {
throw MolPicklerException("ring-atom index out of range");
}
} else {
atoms[j] = mol->getAtomWithBookmark(static_cast<int>(tmpT))->getIdx();
}
}
if (version < 7000) {
for (unsigned int j = 0; j < static_cast<unsigned int>(ringSize); j++) {
streamRead(ss, tmpT, version);
if (directMap) {
bonds[j] = static_cast<int>(tmpT);
if (bonds[j] < 0 || bonds[j] >= mol->getNumBonds()) {
throw MolPicklerException("ring-bond index out of range");
}
} else {
bonds[j] =
mol->getBondWithBookmark(static_cast<int>(tmpT))->getIdx();
}
}
} else {
for (unsigned int j = 1; j < static_cast<unsigned int>(ringSize); ++j) {
bonds[j - 1] =
mol->getBondBetweenAtoms(atoms[j - 1], atoms[j])->getIdx();
}
bonds[ringSize - 1] =
mol->getBondBetweenAtoms(atoms[0], atoms[ringSize - 1])->getIdx();
}
ringInfo->addRing(atoms, bonds);
}
}
}
//--------------------------------------
//
// SubstanceGroups
//
//--------------------------------------
template <typename T>
void MolPickler::_pickleSubstanceGroup(std::ostream &ss,
const SubstanceGroup &sgroup,
std::map<int, int> &atomIdxMap,
std::map<int, int> &bondIdxMap) {
T tmpT;
streamWriteProps(ss, sgroup);
const auto &atoms = sgroup.getAtoms();
streamWrite(ss, static_cast<T>(atoms.size()));
for (const auto &atom : atoms) {
tmpT = static_cast<T>(atomIdxMap[atom]);
streamWrite(ss, tmpT);
}
const auto &p_atoms = sgroup.getParentAtoms();
streamWrite(ss, static_cast<T>(p_atoms.size()));
for (const auto &p_atom : p_atoms) {
tmpT = static_cast<T>(atomIdxMap[p_atom]);
streamWrite(ss, tmpT);
}
const auto &bonds = sgroup.getBonds();
streamWrite(ss, static_cast<T>(bonds.size()));
for (const auto &bond : bonds) {
tmpT = static_cast<T>(bondIdxMap[bond]);
streamWrite(ss, tmpT);
}
const auto &brackets = sgroup.getBrackets();
streamWrite(ss, static_cast<T>(brackets.size()));
for (const auto &bracket : brackets) {
// 3 point per bracket; 3rd point and all z are zeros,
// but this might change in the future.
for (const auto &pt : bracket) {
float tmpFloat;
tmpFloat = static_cast<float>(pt.x);
streamWrite(ss, tmpFloat);
tmpFloat = static_cast<float>(pt.y);
streamWrite(ss, tmpFloat);
tmpFloat = static_cast<float>(pt.z);
streamWrite(ss, tmpFloat);
}
}
const auto &cstates = sgroup.getCStates();
streamWrite(ss, static_cast<T>(cstates.size()));
for (const auto &cstate : cstates) {
// Bond
tmpT = static_cast<T>(bondIdxMap[cstate.bondIdx]);
streamWrite(ss, tmpT);
// Vector -- existence depends on SubstanceGroup type
if ("SUP" == sgroup.getProp<std::string>("TYPE")) {
float tmpFloat;
tmpFloat = static_cast<float>(cstate.vector.x);
streamWrite(ss, tmpFloat);
tmpFloat = static_cast<float>(cstate.vector.y);
streamWrite(ss, tmpFloat);
tmpFloat = static_cast<float>(cstate.vector.z);
streamWrite(ss, tmpFloat);
}
}
const auto &attachPoints = sgroup.getAttachPoints();
streamWrite(ss, static_cast<T>(attachPoints.size()));
for (const auto &attachPoint : attachPoints) {
// aIdx -- always present
tmpT = static_cast<T>(atomIdxMap[attachPoint.aIdx]);
streamWrite(ss, tmpT);
// lvIdx -- may be -1 if not used (0 in spec)
auto tmpInt = -1;
if (attachPoint.lvIdx != -1) {
tmpInt = static_cast<signed int>(atomIdxMap[attachPoint.lvIdx]);
}
streamWrite(ss, tmpInt);
// id -- may be blank
auto tmpS = static_cast<const std::string>(attachPoint.id);
streamWrite(ss, tmpS);
}
}
template <typename T>
SubstanceGroup MolPickler::_getSubstanceGroupFromPickle(std::istream &ss,
ROMol *mol,
int version) {
T tmpT;
T numItems;
float tmpFloat;
int tmpInt = -1;
std::string tmpS;
// temporarily accept empty TYPE
SubstanceGroup sgroup(mol, "");
// Read RDProps, overriding ID, TYPE and COMPNO
streamReadProps(ss, sgroup, MolPickler::getCustomPropHandlers());
streamRead(ss, numItems, version);
for (int i = 0; i < numItems; ++i) {
streamRead(ss, tmpT, version);
sgroup.addAtomWithIdx(tmpT);
}
streamRead(ss, numItems, version);
for (int i = 0; i < numItems; ++i) {
streamRead(ss, tmpT, version);
sgroup.addParentAtomWithIdx(tmpT);
}
streamRead(ss, numItems, version);
for (int i = 0; i < numItems; ++i) {
streamRead(ss, tmpT, version);
sgroup.addBondWithIdx(tmpT);
}
streamRead(ss, numItems, version);
for (int i = 0; i < numItems; ++i) {
SubstanceGroup::Bracket bracket;
for (auto j = 0; j < 3; ++j) {
streamRead(ss, tmpFloat, version);
auto x = static_cast<double>(tmpFloat);
streamRead(ss, tmpFloat, version);
auto y = static_cast<double>(tmpFloat);
streamRead(ss, tmpFloat, version);
auto z = static_cast<double>(tmpFloat);
bracket[j] = RDGeom::Point3D(x, y, z);
}
sgroup.addBracket(bracket);
}
streamRead(ss, numItems, version);
for (int i = 0; i < numItems; ++i) {
streamRead(ss, tmpT, version);
RDGeom::Point3D vector;
if ("SUP" == sgroup.getProp<std::string>("TYPE")) {
streamRead(ss, tmpFloat, version);
vector.x = static_cast<double>(tmpFloat);
streamRead(ss, tmpFloat, version);
vector.y = static_cast<double>(tmpFloat);
streamRead(ss, tmpFloat, version);
vector.z = static_cast<double>(tmpFloat);
}
sgroup.addCState(tmpT, vector);
}
streamRead(ss, numItems, version);
for (int i = 0; i < numItems; ++i) {
streamRead(ss, tmpT, version);
unsigned int aIdx = tmpT;
streamRead(ss, tmpInt, version);
int lvIdx = tmpInt;
std::string id;
streamRead(ss, id, version);
sgroup.addAttachPoint(aIdx, lvIdx, id);
}
return sgroup;
}
template <typename T>
void MolPickler::_pickleStereo(std::ostream &ss,
const std::vector<StereoGroup> &groups,
std::map<int, int> &atomIdxMap) {
T tmpT = static_cast<T>(groups.size());
streamWrite(ss, tmpT);
for (auto &&group : groups) {
streamWrite(ss, static_cast<T>(group.getGroupType()));
auto &atoms = group.getAtoms();
streamWrite(ss, static_cast<T>(atoms.size()));
for (auto &&atom : atoms) {
tmpT = static_cast<T>(atomIdxMap[atom->getIdx()]);
streamWrite(ss, tmpT);
}
}
}
template <typename T>
void MolPickler::_depickleStereo(std::istream &ss, ROMol *mol, int version) {
T tmpT;
streamRead(ss, tmpT, version);
const auto numGroups = static_cast<unsigned>(tmpT);
if (numGroups > 0u) {
std::vector<StereoGroup> groups;
for (unsigned group = 0u; group < numGroups; ++group) {
T tmpT;
streamRead(ss, tmpT, version);
const auto groupType = static_cast<RDKit::StereoGroupType>(tmpT);
streamRead(ss, tmpT, version);
const auto numAtoms = static_cast<unsigned>(tmpT);
std::vector<Atom *> atoms;
atoms.reserve(numAtoms);
for (unsigned i = 0u; i < numAtoms; ++i) {
streamRead(ss, tmpT, version);
atoms.push_back(mol->getAtomWithIdx(tmpT));
}
groups.emplace_back(groupType, std::move(atoms));
}
mol->setStereoGroups(std::move(groups));
}
}
void MolPickler::_pickleProperties(std::ostream &ss, const RDProps &props,
unsigned int pickleFlags) {
if (!pickleFlags) {
return;
}
streamWriteProps(ss, props, pickleFlags & PicklerOps::PrivateProps,
pickleFlags & PicklerOps::ComputedProps,
MolPickler::getCustomPropHandlers());
}
//! unpickle standard properties
void MolPickler::_unpickleProperties(std::istream &ss, RDProps &props) {
streamReadProps(ss, props, MolPickler::getCustomPropHandlers());
}
//--------------------------------------
//
// Version 1 Pickler:
//
// NOTE: this is not 64bit clean, but it shouldn't be used anymore anyway
//
//--------------------------------------
void MolPickler::_pickleV1(const ROMol *mol, std::ostream &ss) {
PRECONDITION(mol, "empty molecule");
ROMol::ConstAtomIterator atIt;
const Conformer *conf = nullptr;
if (mol->getNumConformers() > 0) {
conf = &(mol->getConformer());
}
for (atIt = mol->beginAtoms(); atIt != mol->endAtoms(); ++atIt) {
const Atom *atom = *atIt;
streamWrite(ss, BEGINATOM);
streamWrite(ss, ATOM_NUMBER, atom->getAtomicNum());
streamWrite(ss, ATOM_INDEX, atom->getIdx());
streamWrite(ss, ATOM_POS);
RDGeom::Point3D p;
if (conf) {
p = conf->getAtomPos(atom->getIdx());
}
streamWrite(ss, p.x);
streamWrite(ss, p.y);
streamWrite(ss, p.z);
if (atom->getFormalCharge() != 0) {
streamWrite(ss, ATOM_CHARGE, atom->getFormalCharge());
}
if (atom->getNumExplicitHs() != 0) {
streamWrite(ss, ATOM_NEXPLICIT, atom->getNumExplicitHs());
}
if (atom->getChiralTag() != 0) {
streamWrite(ss, ATOM_CHIRALTAG, atom->getChiralTag());
}
if (atom->getIsAromatic()) {
streamWrite(ss, ATOM_ISAROMATIC,
static_cast<char>(atom->getIsAromatic()));
}
streamWrite(ss, ENDATOM);
}
ROMol::ConstBondIterator bondIt;
for (bondIt = mol->beginBonds(); bondIt != mol->endBonds(); ++bondIt) {
const Bond *bond = *bondIt;
streamWrite(ss, BEGINBOND);
streamWrite(ss, BOND_INDEX, bond->getIdx());
streamWrite(ss, BOND_BEGATOMIDX, bond->getBeginAtomIdx());
streamWrite(ss, BOND_ENDATOMIDX, bond->getEndAtomIdx());
streamWrite(ss, BOND_TYPE, bond->getBondType());
if (bond->getBondDir()) {
streamWrite(ss, BOND_DIR, bond->getBondDir());
}
streamWrite(ss, ENDBOND);
}
streamWrite(ss, ENDMOL);
}
void MolPickler::_depickleV1(std::istream &ss, ROMol *mol) {
PRECONDITION(mol, "empty molecule");
Tags tag;
auto *conf = new Conformer();
mol->addConformer(conf);
streamRead(ss, tag, 1);
while (tag != ENDMOL) {
switch (tag) {
case BEGINATOM:
_addAtomFromPickleV1(ss, mol);
break;
case BEGINBOND:
_addBondFromPickleV1(ss, mol);
break;
default:
UNDER_CONSTRUCTION("bad tag in pickle");
}
streamRead(ss, tag, 1);
}
mol->clearAllAtomBookmarks();
mol->clearAllBondBookmarks();
}
void MolPickler::_addAtomFromPickleV1(std::istream &ss, ROMol *mol) {
PRECONDITION(mol, "empty molecule");
Tags tag;
int intVar;
double dblVar;
char charVar;
int version = 1;
streamRead(ss, tag, version);
auto *atom = new Atom();
Conformer &conf = mol->getConformer();
RDGeom::Point3D pos;
while (tag != ENDATOM) {
switch (tag) {
case ATOM_INDEX:
streamRead(ss, intVar, version);
mol->setAtomBookmark(atom, intVar);
break;
case ATOM_NUMBER:
streamRead(ss, intVar, version);
atom->setAtomicNum(intVar);
break;
case ATOM_POS:
streamRead(ss, pos.x, version);
streamRead(ss, pos.y, version);
streamRead(ss, pos.z, version);
break;
case ATOM_CHARGE:
streamRead(ss, intVar, version);
atom->setFormalCharge(intVar);
break;
case ATOM_NEXPLICIT:
streamRead(ss, intVar, version);
atom->setNumExplicitHs(intVar);
break;
case ATOM_CHIRALTAG:
streamRead(ss, intVar, version);
atom->setChiralTag(static_cast<Atom::ChiralType>(intVar));
break;
case ATOM_MASS:
streamRead(ss, dblVar, version);
// we don't need to set this anymore, but we do need to read it in
// order to maintain backwards compatibility
break;
case ATOM_ISAROMATIC:
streamRead(ss, charVar, version);
atom->setIsAromatic(charVar);
break;
default:
ASSERT_INVARIANT(0, "bad tag in atom block of pickle");
}
streamRead(ss, tag, version);
}
unsigned int id = mol->addAtom(atom, false, true);
conf.setAtomPos(id, pos);
}
void MolPickler::_addBondFromPickleV1(std::istream &ss, ROMol *mol) {
PRECONDITION(mol, "empty molecule");
Tags tag;
int intVar, idx = -1;
int version = 1;
Bond::BondType bt;
Bond::BondDir bd;
streamRead(ss, tag, version);
auto *bond = new Bond();
while (tag != ENDBOND) {
switch (tag) {
case BOND_INDEX:
streamRead(ss, idx, version);
break;
case BOND_BEGATOMIDX:
streamRead(ss, intVar, version);
bond->setBeginAtomIdx(mol->getAtomWithBookmark(intVar)->getIdx());
break;
case BOND_ENDATOMIDX:
streamRead(ss, intVar, version);
bond->setEndAtomIdx(mol->getAtomWithBookmark(intVar)->getIdx());
break;
case BOND_TYPE:
streamRead(ss, bt, version);
bond->setBondType(bt);
break;
case BOND_DIR:
streamRead(ss, bd, version);
bond->setBondDir(bd);
break;
default:
ASSERT_INVARIANT(0, "bad tag in bond block of pickle");
}
streamRead(ss, tag, version);
}
mol->addBond(bond, true);
}
}; // namespace RDKit
|
#ifndef SPN_H
#define SPN_H
#include "init_cy_fde.h"
#include "matrix_util.h"
//#include <cblas.h>
typedef struct SemiCircularNet{
int p;
int d;
DCOMPLEX *Pa_h_A; // d
DCOMPLEX *Pa_omega; // 2*d
DCOMPLEX F_A[2]; //
DCOMPLEX h_A[2]; //
DCOMPLEX TG_Ge_sc[4] ; //
DCOMPLEX DG_sc[4]; //
DCOMPLEX temp_T_eta[4]; //
DCOMPLEX Dh_sc[4]; //
DCOMPLEX Psigma_G_sc[2]; //
DCOMPLEX Psigma_h_sc[2] ;//
DCOMPLEX DG_A[4]; //
DCOMPLEX Dh_A[4]; //
DCOMPLEX S[4]; //
DCOMPLEX temp_mat[4]; //
DCOMPLEX Psigma_omega[2];//
}SCN;
void
SCN_construct(SCN* self, int p , int d);
void
SCN_init(SCN* self);
void
SCN_init_forward(SCN* self);
void
SCN_init_backward(SCN* self);
void
SCN_destroy(SCN* self);
int
SCN_cauchy(SCN* self);
void
SCN_grad(SCN* self, int p, int d, double *a, double sigma, \
DCOMPLEX z,DCOMPLEX *G, DCOMPLEX *omega, DCOMPLEX *omega_sc,\
DCOMPLEX *o_grad_a, DCOMPLEX *o_grad_sigma);
/** Compute Cauchy transform of SemiCircular( returns total iterations)
* @param Z : input matrix
* @param o_G : out_put Cauchy transform
*
*/
int
cauchy_sc( int p, int d, double sigma, DCOMPLEX* Z, \
int max_iter, double thres,\
DCOMPLEX* o_G);
/** Compute Cauchy transform of Signal-Plus-Noise model( returns total iterations)
* @param Z : input matrix
* @param o_G_sc : out_put Cauchy transform
*
*/
int
cauchy_spn(int p_dim, int dim, double* a, double sigma,\
DCOMPLEX* B,\
int max_iter,double thres, \
DCOMPLEX* o_G_sc, DCOMPLEX* o_omega, DCOMPLEX* o_omega_sc);
/*
Only for debug
*/
void
grad_cauchy_spn(int p, int d, double *a, double sigma, \
DCOMPLEX z, DCOMPLEX *G, DCOMPLEX *omega, DCOMPLEX *omega_sc,\
DCOMPLEX *o_grad_a, DCOMPLEX *o_grad_sigma);
// transpose of derivation of Ge
// G : 2
// o_DGe: 2 x 2
void TG_Ge( const int p, const int d, const double sigma, \
const DCOMPLEX *G, DCOMPLEX *o_DGe);
// transpose of derivation of cauchy_sc
// G: 2
// DG: 2 x 2
void DG(const DCOMPLEX *G, const DCOMPLEX *DGe, DCOMPLEX *o_DG);
void T_eta(const int p, const int d, DCOMPLEX *o_T_eta);
void Dh(const DCOMPLEX* DG, const DCOMPLEX *T_eta, const double sigma,DCOMPLEX *o_Dh);
void Psigma_G(const int p,const int d, const double sigma, const DCOMPLEX *G, const DCOMPLEX *DGe, DCOMPLEX *o_Psigma_G);
void Psigma_h(const int p, const int d, const double sigma, const DCOMPLEX * G, const DCOMPLEX* P_sigma_G, const DCOMPLEX *T_eta,\
DCOMPLEX* o_Psigma_h);
//// Descrete
void des_DG( int p, int d, const double *a, const DCOMPLEX *W,DCOMPLEX*o_DG);
void des_Dh( const DCOMPLEX *DG, const DCOMPLEX *F,DCOMPLEX*o_Dh);
void des_Pa_h( int p, int d, const double *a, const DCOMPLEX *W, DCOMPLEX *F, DCOMPLEX *Pa_h);
/** compute gradient and loss of likelihood
* return total number of forward_iter
*
*/
int
grad_loss_cauchy_spn( int p, int d, double *a, double sigma, double scale, \
int batch_size, double *batch, \
double *o_grad_a, double *o_grad_sigma, double *o_loss);
#endif
|
Require Import MetaProp.
Require Import SyntaxProp.
Require Import DynamicProp.
Require Import TypesProp.
Require Import WellFormednessProp.
Require Import Shared.
Require Import Locking.
Hint Constructors is_econtext.
Hint Constructors cfg_blocked.
Tactic Notation "preservation_context_tactic" integer(n) :=
solve[
intuition;
match goal with
| [IH : forall cfg', _ / ?cfg ==> cfg' -> ?P,
Hstep : _ / ?cfg ==> _ |- _] =>
eapply IH in Hstep as (Gamma' & wfCfg' & Hsub);
eauto;
inverts wfCfg' as Hfresh' wfH' wfV' wfT';
inversion wfT'; inversion Hsub;
exists Gamma'; split; try(eassumption)
end;
repeat (econstructor;
simpl;
eauto n using hasType_subsumption,
hasType_subsumption_extend
with env); try(omega)
| eexists; split; eauto with env].
Hint Immediate lt_0_Sn.
Lemma single_threaded_preservation :
forall P t' Gamma H V n Ls e cfg' t,
wfProgram P t' ->
wfConfiguration P Gamma (H, V, n, T_Thread Ls e) t ->
P / (H, V, n, T_Thread Ls e) ==> cfg' ->
exists Gamma',
wfConfiguration P Gamma' cfg' t /\
wfSubsumption Gamma Gamma'.
Proof with eauto using subtypeOf with env.
introv wfP wfCfg Hstep.
inverts wfCfg as Hfresh wfH wfV wfT wfL.
inverts wfT as Hfree hasType.
gen cfg'.
hasType_cases(induction hasType) Case; intros;
(* Some trivial cases can be discarded*)
try(inv Hstep; malformed_context);
(* All variables must be dynamic *)
match goal with
| [Hfree : freeVars _ = nil |- _] =>
simpl in Hfree;
repeat
match goal with
| [Hfree : freeVars _ ++ _ ++ _ = nil |- _] =>
simpl in Hfree;
apply app_eq_nil in Hfree as (Hfree1 & Hfree2);
apply app_eq_nil in Hfree2 as (Hfree2 & Hfree3)
| [Hfree : freeVars _ ++ _ = nil |- _] =>
simpl in Hfree;
apply app_eq_nil in Hfree as (Hfree1 & Hfree2)
| [x : var |- _] =>
destruct x; try(congruence)
end
| _ => idtac
end;
(* Unfold the resulting configuation *)
destruct cfg' as [[[H' V'] n'] T'];
(* Assert that the fresh symbols grow monotonically *)
assert (Hmono: n <= n')
by eauto using step_n_monotonic;
try(
assert (wfL': wfLocking H' T')
by (eapply wfLocking_preservation in Hstep; eauto)
).
+ Case "T_Var".
inverts Hstep; try malformed_context...
wfEnvLookup. rewrite_and_invert.
eexists...
+ Case "T_New".
inv Hstep; try malformed_context.
exists (extend Gamma (env_loc (length H)) (TClass c)).
assert (wfEnv P (extend Gamma (env_loc (length H)) (TClass c)))...
assert (fresh Gamma (env_loc (length H)))...
split...
apply wfConfiguration_substitution
with (ENew c); eauto using subtypeOf, wfLocking_heapExtend.
eapply wfConfiguration_heapExtend;
eauto using wfFields_declsToFields.
+ Case "T_Call".
assert (wfL'': wfLocking H (T_Thread Ls e))
by eauto 3 using wfLocking_econtext.
inv Hstep;
try(malformed_context); try(inv_eq);
try(preservation_context_tactic 2).
- SCase "EvalCall". clear IHhasType2.
inv hasType1.
assert(Hsub: subtypeOf P (TClass c) t1)
by (wfEnvLookup; rewrite_and_invert;
inv hasType; wfEnvLookup;
assert (c0 = c) by crush; subst; eauto).
assert (wfC: wfType P (TClass c))...
assert (cLookup: classLookup P c <> None)
by (inv wfC; assumption).
apply classLookup_not_none in cLookup as (i & fs & ms & cLookup).
assert (wfCls: wfClassDecl P (Cls c i fs ms))
by (inv wfP; lookup_forall as wfCls; eauto)...
assert (mtds = ms)
by (simpls; destruct classLookup; eauto; inv_eq; inv_eq).
subst.
inverts wfCls as Hsigs wfFlds wfMtds.
assert (wfT2: wfType P t2)...
assert (sigLookup: methodSigLookup (extractSigs ms) m = Some (MethodSig m (y, t2) t))
by eauto using methodSigs_sub.
apply extractSigs_sound in sigLookup as [e mLookup].
rewrite_and_invert.
exists (extend
(extend
Gamma (env_var (DV (DVar n))) (TClass c))
(env_var (DV (DVar (S n)))) t2).
assert (fresh Gamma (env_var (DV (DVar n))))...
assert (n <= S n)...
assert (fresh Gamma (env_var (DV (DVar (S n)))))...
split...
* { econstructor; auto.
+ eapply wfHeap_invariance
with (Gamma := Gamma); eauto 3 with env.
+ eapply wfVars_extend; eauto 2 with env.
- eapply wfVars_extend...
apply wfVars_ge with n...
- eapply hasType_subsumption
with (Gamma := Gamma);
eauto 2 using wfSubsumption_fresh with env.
+ lookup_forall as wfMtd.
inv wfMtd. simpls.
econstructor...
- autorewrite with freeVars...
- eapply hasType_subst; eauto 3 with env.
eapply hasType_flip...
eapply hasType_subst; eauto 3 with env.
eapply hasType_subsumption
with (Gamma := (extend
(extend empty (env_var (SV y)) t2)
(env_var (SV this)) (TClass c)));
eauto 3 using wfSubsumption_extend with env.
unfold fresh. case_extend. inv_eq. omega.
}
+ Case "T_Select".
inv hasType.
assert (wfType P t)
by eauto using fieldLookup_wfType.
inv Hstep;
try(malformed_context); try(inv_eq);
try(preservation_context_tactic 2).
- SCase "EvalSelect". clear IHhasType.
wfEnvLookup. rewrite_and_invert.
inverts hasType as Vlookup envLookup Hsub.
assert (t2 = TClass c); subst...
assert (c0 = c)
by (wfEnvLookup; rewrite_and_invert); subst.
assert (wfF: exists v, F f = Some v /\
P; Gamma |- EVal v \in t)
by eauto using dyn_wfFieldLookup, wfHeap_wfFields.
inv wfF as (v' & Flookup & hasType).
rewrite_and_invert.
inv wfL.
eexists. split...
+ Case "T_Update".
assert (wfL'': wfLocking H (T_Thread Ls e))
by eauto 3 using wfLocking_econtext.
inv Hstep;
try(malformed_context); try(inv_eq);
try(preservation_context_tactic 2).
- SCase "EvalUpdate". clear IHhasType1. clear IHhasType2.
inv hasType1. wfEnvLookup. rewrite_and_invert.
inv hasType. wfEnvLookup.
assert (Heq: TClass c1 = TClass c)... inv Heq.
rewrite_and_invert.
exists Gamma. split...
inverts wfL as ? ? wfL.
inv wfL...
eapply wfConfiguration_heapUpdate;
eauto using wfFields_extend, wfHeldLocks_taken;
crush.
+ Case "T_Let".
assert (wfL': wfLocking H' T').
eapply wfLocking_preservation in Hstep...
econstructor...
econstructor...
simpl...
assert (wfLocking H (T_Thread Ls e))
by (apply wfLocking_econtext with (ctx := ctx_let x body); eauto).
inv Hstep;
try(malformed_context); try(inv_eq);
try(preservation_context_tactic 2).
- SCase "EvalLet". clear IHhasType1. clear IHhasType2.
exists (extend Gamma (env_var (DV (DVar n))) t).
split...
* { econstructor; auto.
+ eapply wfHeap_invariance
with (Gamma := Gamma);
eauto 2 with env.
+ eapply wfVars_extend...
eapply wfVars_ge...
+ econstructor;
eauto using hasType_subst with env;
autorewrite with freeVars...
}
* apply wfSubsumption_fresh...
+ Case "T_Cast".
assert (wfL'': wfLocking H (T_Thread Ls e))
by eauto 3 using wfLocking_econtext.
inv Hstep;
try(malformed_context); try(inv_eq);
try(preservation_context_tactic 2).
- SCase "EvalCast". clear IHhasType.
exists Gamma. split...
econstructor...
econstructor...
inv hasType...
+ Case "T_Par".
assert (wfL': wfLocking H' T').
eapply wfLocking_preservation in Hstep...
econstructor...
econstructor...
simpl... crush.
inv Hstep; try(malformed_context).
exists Gamma.
split...
econstructor...
apply wfSubsumption_frame in H0 as []...
econstructor...
- econstructor...
eapply hasType_subsumption with (Gamma := Gamma1)...
- econstructor...
eapply hasType_subsumption with (Gamma := Gamma2)...
+ Case "T_Lock".
inv hasType1.
wfEnvLookup.
inv hasType.
- SCase "V x = l".
inv Hstep;
try(malformed_context); try(inv_eq);
try(preservation_context_tactic 2);
rewrite_and_invert.
exists Gamma. split...
econstructor...
eapply wfHeap_update...
eapply wfHeap_wfFields...
- inv Hstep;
try(malformed_context); try(inv_eq);
try(preservation_context_tactic 2);
rewrite_and_invert.
+ Case "T_Locked".
inv hasType1.
assert (wfL'': wfLocking H (T_Thread Ls e))
by eauto 3 using wfLocking_econtext.
inv Hstep;
try(malformed_context); try(inv_eq);
try(preservation_context_tactic 2).
- SCase "EvalLock_Release". clear IHhasType1. clear IHhasType2.
exists Gamma. split...
econstructor...
eapply wfHeap_update...
eapply wfHeap_wfFields...
Qed.
Theorem preservation :
forall P t' Gamma cfg cfg' t,
wfProgram P t' ->
wfConfiguration P Gamma cfg t ->
P / cfg ==> cfg' ->
exists Gamma',
wfConfiguration P Gamma' cfg' t /\
wfSubsumption Gamma Gamma'.
Proof with eauto using wfConfiguration.
introv wfP wfCfg Hstep.
inverts wfCfg as Hfresh wfH wfV wfT wfL.
gen t cfg' wfL wfT.
induction T; intros...
+ Case "T = EXN".
(* EXN does not step *)
inv Hstep.
+ Case "T = T_Thread e".
eapply single_threaded_preservation...
+ Case "T = T_Async T1 T2 e".
inverts wfT as Hfree hasType wfT1 wfT2.
inverts wfL as wfWl wfRl Hdisj wfL1 wfL2.
destruct cfg' as [[[H' V'] n'] T'].
assert (Hmono: n <= n')
by eauto using step_n_monotonic.
assert(wfLocking H' T')
by eauto using wfLocking_preservation.
inv Hstep;
try(
solve
[
(* When no thread steps, Gamma still types the cfg *)
exists Gamma; split; eauto with env
|
(* When one of the threads step, IH applies *)
match goal with
| [IH: forall t cfg', _ / (_, _, _, ?T) ==> cfg' -> _,
Hstep: _ / (_, _, _, ?T) ==> _ |- _]
=> eapply IH in Hstep as [Gamma' [wfCfg' wfSub]];
eauto; inverts wfCfg'; exists Gamma'
end;
split; eauto;
econstructor; eauto with arith;
econstructor;
eauto using hasType_subsumption,
wfThreads_subsumption
]).
Qed.
|
[GOAL]
M : Type u → Type v
inst✝² : Monad M
ω α β : Type u
inst✝¹ : Monoid ω
inst✝ : LawfulMonad M
⊢ ∀ {α : Type u} (x : WriterT ω M α), id <$> x = x
[PROOFSTEP]
intros
[GOAL]
M : Type u → Type v
inst✝² : Monad M
ω α β : Type u
inst✝¹ : Monoid ω
inst✝ : LawfulMonad M
α✝ : Type u
x✝ : WriterT ω M α✝
⊢ id <$> x✝ = x✝
[PROOFSTEP]
simp [Functor.map, WriterT.mk]
[GOAL]
M : Type u → Type v
inst✝² : Monad M
ω α β : Type u
inst✝¹ : Monoid ω
inst✝ : LawfulMonad M
⊢ ∀ {α β : Type u} (x : α) (f : α → WriterT ω M β), pure x >>= f = f x
[PROOFSTEP]
intros
[GOAL]
M : Type u → Type v
inst✝² : Monad M
ω α β : Type u
inst✝¹ : Monoid ω
inst✝ : LawfulMonad M
α✝ β✝ : Type u
x✝ : α✝
f✝ : α✝ → WriterT ω M β✝
⊢ pure x✝ >>= f✝ = f✝ x✝
[PROOFSTEP]
simp [Bind.bind, Pure.pure, WriterT.mk]
[GOAL]
M : Type u → Type v
inst✝² : Monad M
ω α β : Type u
inst✝¹ : Monoid ω
inst✝ : LawfulMonad M
⊢ ∀ {α β γ : Type u} (x : WriterT ω M α) (f : α → WriterT ω M β) (g : β → WriterT ω M γ),
x >>= f >>= g = x >>= fun x => f x >>= g
[PROOFSTEP]
intros
[GOAL]
M : Type u → Type v
inst✝² : Monad M
ω α β : Type u
inst✝¹ : Monoid ω
inst✝ : LawfulMonad M
α✝ β✝ γ✝ : Type u
x✝ : WriterT ω M α✝
f✝ : α✝ → WriterT ω M β✝
g✝ : β✝ → WriterT ω M γ✝
⊢ x✝ >>= f✝ >>= g✝ = x✝ >>= fun x => f✝ x >>= g✝
[PROOFSTEP]
simp [Bind.bind, mul_assoc, WriterT.mk, ← bind_pure_comp]
[GOAL]
M : Type u → Type v
inst✝² : Monad M
ω α β : Type u
inst✝¹ : Monoid ω
inst✝ : LawfulMonad M
⊢ ∀ {α β : Type u} (f : α → β) (x : WriterT ω M α),
(do
let y ← x
pure (f y)) =
f <$> x
[PROOFSTEP]
intros
[GOAL]
M : Type u → Type v
inst✝² : Monad M
ω α β : Type u
inst✝¹ : Monoid ω
inst✝ : LawfulMonad M
α✝ β✝ : Type u
f✝ : α✝ → β✝
x✝ : WriterT ω M α✝
⊢ (do
let y ← x✝
pure (f✝ y)) =
f✝ <$> x✝
[PROOFSTEP]
simp [Bind.bind, Functor.map, Pure.pure, WriterT.mk, bind_pure_comp]
|
I was an Art and English Literature student at college, (alongside law, history and languages) so I was excited to be invited for a tour of St Pancras International station to discover its history, the story behind the statues and decor within the station and how it became the great shopping place it is today. Food and drink, as well as the new Eurostar Terminal is all available here. I delightfully finished off my tour with a delicious afternoon tea at Fortnum & Mason. The cakes were the prettiest and most tantalising tea cakes I have ever eaten. You can also experience this! St. Pancras International has teamed up with Fortnum & Mason, to celebrate the station’s 150th year, and from the 21st May they will be offering a unique hours tour of the station followed by afternoon tea at Fortnum’s. With an insightful historic walk around this iconic station and some very delicious treats to enjoy afterwards, it will definitely be a wonderful experience. I absolutely enjoyed every part of this tour. If you book a tour and tea package you’ll find out why I mentioned it’s great for art and English literature enthusiasts.
Tickets are £45 per person, please click here for further info or to book your experience.
All-new Afternoon Tea & Tour package from St Pancras International and Fortnum & Mason is the most delicious history lesson you’ll ever have!
Includes an hour-long walking tour to learn about the fascinating history of St Pancras International, followed by a delicious Fortnum’s Afternoon Tea. You will be served a decadent spread including Fortnum’s smoked salmon and tartare dressing on granary bread; plain and fruit scones with clotted cream and strawberry preserve; and a pot of Fortnum’s famous tea for one.
The new Afternoon Tea & Tour package is part of ‘Celebrate St Pancras – the people, the place, the journey’ – a series of events, exhibitions and installations commissioned by HS1 Ltd for the anniversary year. Throughout the year, St Pancras International will be showcasing the transformation of the station, the entry and role of women into the railway workforce; StPancras’ role in the trade of goods, food and beer into London; its wartime history; and the people and journeys that have been shaped by it. |
module Data.Vec.All.Properties.Extra {a p}{A : Set a}{P : A → Set p} where
open import Data.List using (List)
import Data.List.Relation.Unary.All as All
open import Data.Vec hiding (_[_]≔_)
open import Data.Vec.Relation.Unary.All hiding (lookup)
open import Data.Fin
all-fromList : ∀ {xs : List A} → All.All P xs → All P (fromList xs)
all-fromList All.[] = []
all-fromList (px All.∷ p) = px ∷ all-fromList p
_[_]≔_ : ∀ {n}{l : Vec A n} → All P l → (i : Fin n) → P (lookup l i)→ All P l
[] [ () ]≔ px
(px ∷ l) [ zero ]≔ px₁ = px₁ ∷ l
(px ∷ l) [ suc i ]≔ px₁ = px ∷ (l [ i ]≔ px₁)
|
lemmas of_real_eq_1_iff [simp] = of_real_eq_iff [of _ 1, simplified] |
lemma closed_imp_locally_compact: fixes S :: "'a :: heine_borel set" assumes "closed S" shows "locally compact S" |
Formal statement is: lemmas continuous_Re [simp] = bounded_linear.continuous [OF bounded_linear_Re] Informal statement is: The real part of a complex number is continuous. |
/*
Copyright 2015 Glen Joseph Fernandes
([email protected])
Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_ALIGN_ALIGN_DOWN_HPP
#define BOOST_ALIGN_ALIGN_DOWN_HPP
#include <boost/align/detail/align_down.hpp>
namespace boost {
namespace alignment {
BOOST_CONSTEXPR inline std::size_t
align_down(std::size_t value, std::size_t alignment) BOOST_NOEXCEPT
{
return value & ~(alignment - 1);
}
} /* alignment */
} /* boost */
#endif
|
[STATEMENT]
lemma "Fr_2 \<F> \<Longrightarrow> \<forall>A B. Cl(A) \<longrightarrow> lCoP1\<^sup>A\<^sup>B(\<^bold>\<rightarrow>) \<^bold>\<not>\<^sup>I"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Fr_2 \<F> \<Longrightarrow> \<forall>A. contains (\<lambda>B. contains (B \<^bold>\<rightarrow> \<^bold>\<not>\<^sup>I A) (A \<^bold>\<rightarrow> \<^bold>\<not>\<^sup>I B)) (\<lambda>B. \<forall>w. \<C> A w = A w)
[PROOF STEP]
using Int_fr_def OpCldual
[PROOF STATE]
proof (prove)
using this:
\<I>\<^sub>F ?\<F> \<equiv> \<lambda>A. A \<^bold>\<leftharpoonup> ?\<F> A
Fr_2 \<F> \<Longrightarrow> \<forall>A. (\<forall>w. \<C> A w = A w) = (\<forall>w. \<I> (\<^bold>\<midarrow>A) w = (\<^bold>\<midarrow>A) w)
goal (1 subgoal):
1. Fr_2 \<F> \<Longrightarrow> \<forall>A. contains (\<lambda>B. contains (B \<^bold>\<rightarrow> \<^bold>\<not>\<^sup>I A) (A \<^bold>\<rightarrow> \<^bold>\<not>\<^sup>I B)) (\<lambda>B. \<forall>w. \<C> A w = A w)
[PROOF STEP]
unfolding conn
[PROOF STATE]
proof (prove)
using this:
\<I>\<^sub>F ?\<F> \<equiv> \<lambda>A w. A w \<and> \<not> ?\<F> A w
Fr_2 \<F> \<Longrightarrow> \<forall>A. (\<forall>w. \<C> A w = A w) = (\<forall>w. \<I> (\<lambda>w. \<not> A w) w = (\<not> A w))
goal (1 subgoal):
1. Fr_2 \<F> \<Longrightarrow> \<forall>A. contains (\<lambda>B. contains (\<lambda>w. \<I> (\<lambda>w. \<not> A w) w \<longleftarrow> B w) (\<lambda>w. \<I> (\<lambda>w. \<not> B w) w \<longleftarrow> A w)) (\<lambda>B. \<forall>w. \<C> A w = A w)
[PROOF STEP]
by auto |
/-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean
import Std.Util.TermUnsafe
import Std.Tactic.OpenPrivate
/-!
Defines a command wrapper that prints the changes the command makes to the
environment.
```
whatsnew in
theorem foo : 42 = 6 * 7 := rfl
```
-/
open Lean Elab Command
namespace Mathlib.WhatsNew
private def throwUnknownId (id : Name) : CommandElabM Unit :=
throwError "unknown identifier '{mkConst id}'"
private def levelParamsToMessageData (levelParams : List Name) : MessageData :=
match levelParams with
| [] => ""
| u::us => Id.run <| do
let mut m := m!".\{{u}"
for u in us do
m := m ++ ", " ++ toMessageData u
return m ++ "}"
private def mkHeader (kind : String) (id : Name) (levelParams : List Name) (type : Expr)
(safety : DefinitionSafety) : CoreM MessageData := do
let m : MessageData :=
match safety with
| DefinitionSafety.unsafe => "unsafe "
| DefinitionSafety.partial => "partial "
| DefinitionSafety.safe => ""
let m := if isProtected (← getEnv) id then m ++ "protected " else m
let (m, id) := match privateToUserName? id with
| some id => (m ++ "private ", id)
| none => (m, id)
let m := m ++ kind ++ " " ++ id ++ levelParamsToMessageData levelParams ++ " : " ++ type
pure m
private def mkHeader' (kind : String) (id : Name) (levelParams : List Name) (type : Expr)
(isUnsafe : Bool) : CoreM MessageData :=
mkHeader kind id levelParams type
(if isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe)
private def printDefLike (kind : String) (id : Name) (levelParams : List Name) (type : Expr)
(value : Expr) (safety := DefinitionSafety.safe) : CoreM MessageData :=
return (← mkHeader kind id levelParams type safety) ++ " :=" ++ Format.line ++ value
private def printInduct (id : Name) (levelParams : List Name) (_numParams : Nat) (_numIndices : Nat)
(type : Expr) (ctors : List Name) (isUnsafe : Bool) : CoreM MessageData := do
let mut m ← mkHeader' "inductive" id levelParams type isUnsafe
m := m ++ Format.line ++ "constructors:"
for ctor in ctors do
let cinfo ← getConstInfo ctor
m := m ++ Format.line ++ ctor ++ " : " ++ cinfo.type
pure m
private def printIdCore (id : Name) : ConstantInfo → CoreM MessageData
| ConstantInfo.axiomInfo { levelParams := us, type := t, isUnsafe := u, .. } =>
mkHeader' "axiom" id us t u
| ConstantInfo.defnInfo { levelParams := us, type := t, value := v, safety := s, .. } =>
printDefLike "def" id us t v s
| ConstantInfo.thmInfo { levelParams := us, type := t, value := v, .. } =>
printDefLike "theorem" id us t v
| ConstantInfo.opaqueInfo { levelParams := us, type := t, isUnsafe := u, .. } =>
mkHeader' "constant" id us t u
| ConstantInfo.quotInfo { levelParams := us, type := t, .. } =>
mkHeader' "Quotient primitive" id us t false
| ConstantInfo.ctorInfo { levelParams := us, type := t, isUnsafe := u, .. } =>
mkHeader' "constructor" id us t u
| ConstantInfo.recInfo { levelParams := us, type := t, isUnsafe := u, .. } =>
mkHeader' "recursor" id us t u
| ConstantInfo.inductInfo
{ levelParams := us, numParams, numIndices, type := t, ctors, isUnsafe := u, .. } =>
printInduct id us numParams numIndices t ctors u
def diffExtension (old new : Environment)
(ext : PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState) :
CoreM (Option MessageData) := unsafe do
let oldSt := ext.toEnvExtension.getState old
let newSt := ext.toEnvExtension.getState new
if ptrAddrUnsafe oldSt == ptrAddrUnsafe newSt then return none
let oldEntries := ext.exportEntriesFn oldSt.state
let newEntries := ext.exportEntriesFn newSt.state
pure m!"-- {ext.name} extension: {(newEntries.size - oldEntries.size : Int)} new entries"
def whatsNew (old new : Environment) : CoreM MessageData := do
let mut diffs := #[]
for (c, i) in new.constants.map₂.toList do
unless old.constants.map₂.contains c do
diffs := diffs.push (← printIdCore c i)
for ext in ← persistentEnvExtensionsRef.get do
if let some diff := ← diffExtension old new ext then
diffs := diffs.push diff
if diffs.isEmpty then return "no new constants"
pure $ MessageData.joinSep diffs.toList "\n\n"
/-- `whatsnew in $command` executes the command and then prints the
declarations that were added to the environment. -/
elab "whatsnew" "in" ppLine cmd:command : command => do
let oldEnv ← getEnv
try
elabCommand cmd
finally
let newEnv ← getEnv
logInfo (← liftCoreM <| whatsNew oldEnv newEnv)
|
function dist = line_par_point_dist_3d ( f, g, h, x0, y0, z0, p )
%*****************************************************************************80
%
%% LINE_PAR_POINT_DIST_3D: distance ( parametric line, point ) in 3D.
%
% Discussion:
%
% The parametric form of a line in 3D is:
%
% X = X0 + F * T
% Y = Y0 + G * T
% Z = Z0 + H * T
%
% We normalize by choosing F*F+G*G+H*H=1 and 0 <= F.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 20 February 2005
%
% Author:
%
% John Burkardt
%
% Reference:
%
% Adrian Bowyer and John Woodwark,
% A Programmer's Geometry,
% Butterworths, 1983.
%
% Parameters:
%
% Input, real F, G, H, X0, Y0, Z0, the parametric line
% parameters.
%
% Input, real P(3,1), the point whose distance from the line is
% to be measured.
%
% Output, real DIST, the distance from the point to the line.
%
dx = g * ( f * ( p(2,1) - y0 ) - g * ( p(1,1) - x0 ) ) ...
+ h * ( f * ( p(3,1) - z0 ) - h * ( p(1,1) - x0 ) );
dy = h * ( g * ( p(3,1) - z0 ) - h * ( p(2,1) - y0 ) ) ...
- f * ( f * ( p(2,1) - y0 ) - g * ( p(1,1) - x0 ) );
dz = - f * ( f * ( p(3,1) - z0 ) - h * ( p(1,1) - x0 ) ) ...
- g * ( g * ( p(3,1) - z0 ) - h * ( p(2,1) - y0 ) );
dist = sqrt ( dx * dx + dy * dy + dz * dz ) ...
/ ( f * f + g * g + h * h );
return
end
|
# Learn the environment!
function learn!(learner, env::Union{EnvMultinomial, EnvGaussian}, callback)
for i in 1:env.nsteps
interact!(env)
update!(learner, env.state)
callback!(callback, learner, env)
end
end
|
Require Import VST.msl.msl_standard.
Local Open Scope pred.
Lemma andp_TT {A}`{ageable A}: forall (P: pred A), P && TT = P.
Proof.
intros.
apply pred_ext; intros w ?.
destruct H0; auto.
split; auto.
Qed.
Lemma sepcon_andp_prop' {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}: forall P Q R, (!!Q && P)*R = !!Q&&(P*R).
Proof.
intros.
rewrite sepcon_comm. rewrite sepcon_andp_prop.
rewrite sepcon_comm; auto.
Qed.
Hint Rewrite @sepcon_emp @emp_sepcon @TT_and @andp_TT
@exp_sepcon1 @exp_sepcon2
@exp_andp1 @exp_andp2
@sepcon_andp_prop @sepcon_andp_prop'
: normalize.
Definition pure {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}
(P: pred A) : Prop :=
P |-- emp.
Lemma pure_sepcon {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}: forall (P : pred A), pure P -> P*P=P.
Proof.
pose proof I.
intros.
apply pred_ext; intros w ?.
assert ((emp * P)%pred w).
eapply sepcon_derives; try apply H1; auto.
rewrite emp_sepcon in H2.
auto.
exists w; exists w.
split; [|split]; auto.
apply H0 in H1.
do 3 red in H1. apply identity_unit' in H1.
apply H1.
Qed.
Lemma pure_e {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}: forall (P: pred A), pure P -> (P |-- emp).
Proof.
intros.
apply H.
Qed.
#[export] Hint Resolve pure_e : core.
Lemma sepcon_pure_andp {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P Q, pure P -> pure Q -> ((P * Q) = (P && Q)).
Proof.
intros.
apply pred_ext; intros w ?.
destruct H1 as [w1 [w2 [? [? ?]]]].
unfold pure in *.
assert (unit_for w1 w2). apply H in H2; simpl in H2;
apply identity_unit; auto. exists w; auto.
unfold unit_for in H4.
assert (w2=w) by (apply (join_eq H4 H1)).
subst w2.
assert (join w w1 w1).
apply identity_unit; apply H0 in H3; simpl in H3; auto. exists w; auto.
assert (w1=w) by (apply (join_eq H5 (join_comm H1))).
subst w1.
split; auto.
destruct H1.
exists w; exists w; split; [|split]; auto.
apply H in H1.
do 3 red in H1.
clear dependent P. clear dependent Q.
pose proof (core_unit w); unfold unit_for in *.
pose proof (H1 _ _ (join_comm H)).
rewrite H0 in H; auto.
Qed.
Lemma pure_emp {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}: pure emp.
Proof.
intros. unfold pure; auto.
Qed.
#[export] Hint Resolve pure_emp : core.
Lemma join_equiv_refl {A}: forall x:A, @join A (Join_equiv A) x x x.
Proof. split; auto. Qed.
#[export] Hint Resolve join_equiv_refl : core.
Lemma pure_sepcon1'' {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}: forall P Q R, pure P -> Q |-- R -> P * Q |-- R.
Proof.
pose proof I.
intros.
intros w [w1 [w2 [? [? ?]]]].
apply H0 in H3.
apply join_unit1_e in H2; auto.
subst; auto.
Qed.
Lemma pure_existential {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall B (P: B -> pred A), (forall x: B , pure (P x)) -> pure (exp P).
Proof.
intros.
unfold pure in *.
intros w [x ?].
apply (H x); auto.
Qed.
#[export] Hint Resolve pure_existential : core.
Lemma pure_core {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P w, pure P -> P w -> P (core w).
Proof.
intros.
rewrite <- identity_core; auto.
apply H; auto.
Qed.
Lemma FF_sepcon {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P, FF * P = FF.
Proof.
intros.
apply pred_ext; intros w ?; try contradiction.
destruct H as [w1 [w2 [? [? ?]]]]; contradiction.
Qed.
Lemma sepcon_FF {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P, P * FF = FF.
Proof.
intros.
rewrite sepcon_comm. apply FF_sepcon.
Qed.
Hint Rewrite @FF_sepcon @sepcon_FF : normalize.
Hint Rewrite @prop_true_andp using (solve [auto]) : normalize.
Lemma true_eq {A} `{ageable A}: forall P: Prop, P -> (!! P) = (TT: pred A).
Proof.
intros. apply pred_ext; intros ? ?; simpl in *; intuition.
Qed.
Hint Rewrite @true_eq using (solve [auto]) : normalize.
Lemma pure_con' {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P Q, pure P -> pure Q -> pure (P*Q).
Proof.
intros.
unfold pure in *.
rewrite <- sepcon_emp.
apply sepcon_derives; auto.
Qed.
#[export] Hint Resolve pure_con' : core.
Lemma pure_intersection1: forall {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}
(P Q: pred A), pure P -> pure (P && Q).
Proof.
unfold pure; intros; auto.
intros w [? ?]; auto.
Qed.
Lemma pure_intersection2: forall {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}
(P Q: pred A), pure Q -> pure (P && Q).
Proof.
unfold pure; intros; auto.
intros w [? ?]; auto.
Qed.
#[export] Hint Resolve pure_intersection1 pure_intersection2 : core.
Lemma FF_andp {A} `{ageable A}: forall P: pred A, FF && P = FF.
Proof.
unfold FF, prop, andp; intros; apply pred_ext; intros ? ?; simpl in *; intuition.
Qed.
Lemma andp_FF {A}`{ageable A}: forall P: pred A, P && FF = FF.
Proof.
unfold FF, prop, andp; intros; apply pred_ext; intros ? ?; simpl in *; intuition.
Qed.
Hint Rewrite @FF_andp @andp_FF : normalize.
Hint Rewrite @andp_dup : normalize.
Lemma andp_emp_sepcon_TT {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall (Q: pred A),
(forall w1 w2, core w1 = core w2 -> Q w1 -> Q w2) ->
(Q && emp * TT = Q).
Proof.
intros.
apply pred_ext.
intros w [w1 [w2 [? [[? ?] ?]]]].
apply H with w1; auto.
apply join_core in H0; auto.
intros w ?.
destruct (join_ex_identities w) as [e [He [? Hj]]].
exists e; exists w; split; [|split]; auto.
specialize (He _ _ Hj); subst; auto.
split; auto.
apply H with w; auto.
symmetry; eapply join_core2; eauto.
Qed.
Lemma sepcon_TT {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall (P: pred A), P |-- (P * TT).
Proof.
intros.
rewrite <- (sepcon_emp P) at 1.
eapply sepcon_derives; try apply H0; auto.
Qed.
#[export] Hint Resolve sepcon_TT : core.
Lemma imp_extract_exp_left {B A: Type} `{ageable A}:
forall (p : B -> pred A) (q: pred A),
(forall x, p x |-- q) ->
exp p |-- q.
Proof.
intros.
intros w [x ?].
eapply H0; eauto.
Qed.
Lemma pure_sepcon_TT_andp {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P Q, pure P -> (P * TT) && Q = (P*Q).
Proof.
pose proof I.
intros.
apply pred_ext.
intros w [? ?].
destruct H1 as [w1 [w2 [? [? ?]]]].
exists w1; exists w2; split; [|split]; auto.
apply join_unit1_e in H1; auto.
subst; auto.
apply H0 in H3; auto.
apply andp_right.
apply sepcon_derives; auto.
intros w [w1 [w2 [? [? ?]]]].
apply join_unit1_e in H1; auto.
subst; auto.
apply H0 in H2; auto.
Qed.
Lemma pure_sepcon_TT_andp' {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P Q, pure P -> Q && (P * TT) = (Q*P).
Proof.
intros. rewrite andp_comm.
rewrite pure_sepcon_TT_andp; auto.
apply sepcon_comm.
Qed.
Hint Rewrite @pure_sepcon_TT_andp @pure_sepcon_TT_andp' using (solve [auto]): normalize.
Lemma pure_sepcon1' {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P Q R, pure P -> P * Q |-- P * R -> P * Q |-- R.
Proof.
intros.
eapply derives_trans; try apply H0.
apply pure_sepcon1''; auto.
Qed.
Lemma pull_right {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P Q R,
(Q * P * R) = (Q * R * P).
Proof.
intros. repeat rewrite sepcon_assoc. rewrite (sepcon_comm P); auto.
Qed.
Lemma pull_right0 {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}: forall P Q,
(P * Q) = (Q * P).
Proof.
intros. rewrite (sepcon_comm P); auto.
Qed.
Ltac pull_left A := repeat (rewrite <- (pull_right A) || rewrite <- (pull_right0 A)).
Ltac pull_right A := repeat (rewrite (pull_right A) || rewrite (pull_right0 A)).
Lemma pure_modus {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall P Q, P |-- Q -> pure Q -> P |-- Q && P.
Proof.
intros.
intros w ?.
split; auto.
Qed.
Lemma imp_exp_right {B A : Type} `{saA: ageable A}:
forall (x: B) (p: pred A) (q: B -> pred A),
p |-- q x ->
p |-- exp q.
Proof.
intros.
eapply derives_trans; try apply H.
intros w ?; exists x; auto.
Qed.
Lemma derives_extract_prop {A} `{ageable A}:
forall (P: Prop) (Q R: pred A), (P -> Q |-- R) -> !!P && Q |-- R.
Proof.
unfold derives, prop, andp; hnf in *; intuition.
hnf in H1; intuition.
Qed.
Lemma derives_extract_prop' {A} `{ageable A}:
forall (P: Prop) (Q R: pred A), (P -> Q |-- R) -> Q && !!P|-- R.
Proof.
unfold derives, prop, andp; intuition; hnf in *; intuition.
hnf in *; intuition. apply H1; auto.
Qed.
Ltac normalize1 :=
match goal with
| |- _ => contradiction
| |- context [(?P && ?Q) * ?R] => rewrite (corable_andp_sepcon1 P Q R) by (auto with normalize)
| |- context [?Q * (?P && ?R)] => rewrite (corable_sepcon_andp1 P Q R) by (auto with normalize)
| |- context [(?Q && ?P) * ?R] => rewrite (corable_andp_sepcon2 P Q R) by (auto with normalize)
| |- context [?Q * (?R && ?P)] => rewrite (corable_sepcon_andp2 P Q R) by (auto with normalize)
| |- _ => progress (autorewrite with normalize); auto with typeclass_instances
| |- _ = ?x -> _ => intro; subst x
| |- ?x = _ -> _ => intro; subst x
| |- ?ZZ -> _ => match type of ZZ with
| Prop =>
let H := fresh in
((assert (H:ZZ) by auto; clear H; intros _) || intro H)
| _ => intros _
end
| |- forall _, _ => let x := fresh "x" in (intro x; normalize1; try generalize dependent x)
| |- exp _ |-- _ => apply imp_extract_exp_left
| |- !! _ && _ |-- _ => apply derives_extract_prop
| |- _ && !! _ |-- _ => apply derives_extract_prop'
| |- _ |-- !! (?x = ?y) && _ =>
(rewrite prop_true_andp with (P:= (x=y))
by (unfold y; reflexivity); unfold y in *; clear y) ||
(rewrite prop_true_andp with (P:=(x=y))
by (unfold x; reflexivity); unfold x in *; clear x)
| |- _ => solve [auto with typeclass_instances]
end.
Ltac normalize1_in Hx :=
match type of Hx with
| app_pred (exp _) _ => destruct Hx
| app_pred (!! _ && _) _ => let H1 := fresh in destruct Hx as [H1 Hx]; unfold prop in H1
| context [ !! ?P ] =>
rewrite (true_eq P) in Hx by auto with typeclass_instances
| context [ !! ?P && ?Q ] =>
rewrite (prop_true_andp P Q) in Hx by auto with typeclass_instances
| context [(?P && ?Q) * ?R] => rewrite (corable_andp_sepcon1 P Q R) in Hx by (auto with normalize)
| context [?Q * (?P && ?R)] => rewrite (corable_sepcon_andp1 P Q R) in Hx by (auto with normalize)
| context [(?Q && ?P) * ?R] => rewrite (corable_andp_sepcon2 P Q R) in Hx by (auto with normalize)
| context [?Q * (?R && ?P)] => rewrite (corable_sepcon_andp2 P Q R) in Hx by (auto with normalize)
| _ => progress (autorewrite with normalize in Hx); auto with typeclass_instances
end.
Ltac normalize := repeat normalize1.
Tactic Notation "normalize" "in" hyp(H) := repeat (normalize1_in H).
Definition mark {A: Type} (i: nat) (j: A) := j.
Lemma swap_mark1 {A} {JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall i j Pi Pj B, (i<j)%nat -> B * mark i Pi * mark j Pj = B * mark j Pj * mark i Pi.
Proof.
intros.
repeat rewrite sepcon_assoc.
f_equal.
apply sepcon_comm.
Qed.
Lemma swap_mark0 {A} {JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A}:
forall i j Pi Pj, (i<j)%nat -> mark i Pi * mark j Pj = mark j Pj * mark i Pi.
Proof.
intros.
apply sepcon_comm.
Qed.
Ltac select_left n :=
repeat match goal with
| |- context [(_ * mark ?i _ * mark n _)%pred] =>
rewrite (swap_mark1 i n); [ | solve [simpl; auto]]
| |- context [(mark ?i _ * mark n _)%pred] =>
rewrite (swap_mark0 i n); [ | solve [simpl; auto]]
end.
Ltac select_all n := match n with
| O => idtac
| S ?n' => select_left n; select_all n'
end.
Ltac markem n P :=
match P with
| (?Y * ?Z) =>
(match goal with H: mark _ Z = Z |- _ => idtac end
|| assert (mark n Z = Z) by auto); markem (S n) Y
| ?Z => match goal with H: mark _ Z = Z |- _ => idtac end
|| assert (mark n Z = Z) by auto
end.
Ltac prove_assoc_commut :=
clear;
try (match goal with |- ?F _ -> ?G _ => replace G with F; auto end);
(repeat rewrite <- sepcon_assoc;
match goal with |- ?P = _ => markem O P end;
let LEFT := fresh "LEFT" in match goal with |- ?P = _ => set (LEFT := P) end;
match goal with H: mark ?n _ = _ |- _ =>
repeat match goal with H: mark ?n _ = ?P |- _ => rewrite <- H; clear H end;
select_all n;
reflexivity
end).
Lemma test_prove_assoc_commut {T}{JA: Join T}{PA: Perm_alg T}{agA: ageable T}{AgeA: Age_alg T} : forall A B C D E : pred T,
D * E * A * C * B = A * B * C * D * E.
Proof.
intros.
prove_assoc_commut.
Qed.
|
[STATEMENT]
theorem main\<^sub>K\<^sub>B: \<open>G \<TTurnstile>\<^sub>K\<^sub>B p \<longleftrightarrow> G \<turnstile>\<^sub>K\<^sub>B p\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (G \<TTurnstile>\<^sub>K\<^sub>B p) = (G \<turnstile>\<^sub>K\<^sub>B p)
[PROOF STEP]
using strong_soundness\<^sub>K\<^sub>B[of G p] strong_completeness\<^sub>K\<^sub>B[of G p]
[PROOF STATE]
proof (prove)
using this:
G \<turnstile>\<^sub>K\<^sub>B p \<Longrightarrow> symmetric; G \<TTurnstile>\<star> p
G \<TTurnstile>\<^sub>K\<^sub>B p \<Longrightarrow> G \<turnstile>\<^sub>K\<^sub>B p
goal (1 subgoal):
1. (G \<TTurnstile>\<^sub>K\<^sub>B p) = (G \<turnstile>\<^sub>K\<^sub>B p)
[PROOF STEP]
by fast |
open import MJ.Types
import MJ.Classtable.Core as Core
import MJ.Classtable.Code as Code
import MJ.Syntax as Syntax
module MJ.Semantics.Objects.Flat {c}(Ct : Core.Classtable c)(ℂ : Code.Code Ct) where
open import Prelude
open import Level renaming (suc to lsuc; zero to lzero)
open import Data.Vec hiding (_++_; lookup; drop)
open import Data.Star
open import Data.List
open import Data.List.First.Properties
open import Data.List.Membership.Propositional
open import Data.List.Any.Properties
open import Data.List.All as All
open import Data.List.All.Properties.Extra
open import Data.List.Prefix
open import Data.List.Properties.Extra
open import Data.Maybe as Maybe
open import Data.Maybe.Relation.Unary.All as MayAll using ()
open import Data.String using (String)
open import Relation.Binary.PropositionalEquality
open import MJ.Semantics.Values Ct
open import MJ.Semantics.Objects Ct
open import MJ.Syntax Ct
open Code Ct
open Core c
open Classtable Ct
open import MJ.Classtable.Membership Ct
private
collect : ∀ {cid}(chain : Σ ⊢ cid <: Object) ns → List (String × typing ns)
collect (super {cid} ◅ ch) ns = Class.decls (Σ (cls cid)) ns ++ collect ch ns
collect ε ns = Class.decls (Σ Object) ns
{-
We define collect members by delegation to collection of members over a particular
inheritance chain.
This makes the definition structurally recursive and is sound by the fact that
inheritance chains are unique.
-}
collect-members : ∀ cid ns → List (String × typing ns)
collect-members cid ns = collect (rooted cid) ns
{-
An Object is then simply represented by a list of values for all it's members.
-}
Obj : (World c) → (cid : _) → Set
Obj W cid = All (λ d → Val W (proj₂ d)) (collect-members cid FIELD)
weaken-obj : ∀ {W W'} cid → W' ⊒ W → Obj W cid → Obj W' cid
weaken-obj cid ext O = All.map (weaken-val ext) O
{-
We can relate the flat Object structure with the hierarchical notion of membership
through the definition of `collect`.
This allows us to get and set members on Objects.
-}
{-# TERMINATING #-}
getter : ∀ {W n a} cid → Obj W cid → IsMember cid FIELD n a → Val W a
getter cid O q with rooted cid
getter .Object O (.Object , ε , def) | ε = ∈-all (proj₁ (first⟶∈ def)) O
getter .Object O (_ , () ◅ _ , _) | ε
getter ._ O (._ , ε , def) | super {cid} ◅ z
with split-++ (Class.decls (Σ (cls _)) FIELD) _ O
... | own , inherited = ∈-all (proj₁ (first⟶∈ def)) own
getter ._ O (pid , super {cid} ◅ s , def) | super ◅ z
with split-++ (Class.decls (Σ (cls _)) FIELD) _ O
... | own , inherited rewrite <:-unique z (rooted (Class.parent (Σ (cls cid)))) =
getter _ inherited (pid , s , def)
{-# TERMINATING #-}
setter : ∀ {W f a} cid → Obj W cid → IsMember cid FIELD f a → Val W a → Obj W cid
setter (cls cid) O q v with rooted (cls cid)
setter (cls cid) O (._ , ε , def) v | super ◅ z with split-++ (Class.decls (Σ (cls _)) FIELD) _ O
... | own , inherited =
(own All.[ proj₁ (first⟶∈ def) ]≔ v) ++-all inherited
setter (cls cid) O (._ , super ◅ s , def) v | super ◅ z with split-++ (Class.decls (Σ (cls _)) FIELD) _ O
... | own , inherited rewrite <:-unique z (rooted (Class.parent (Σ (cls cid)))) =
own ++-all setter _ inherited (_ , s , def) v
setter Object O mem v = ⊥-elim (∉Object mem)
{-
A default object instance can be created for every class simply by tabulating `default`
over the types of all fields of a class.
-}
defaultObject' : ∀ {W cid} → (ch : Σ ⊢ cid <: Object) → All (λ d → Val W (proj₂ d)) (collect ch FIELD)
defaultObject' ε rewrite Σ-Object = []
defaultObject' {cid = Object} (() ◅ _)
defaultObject' {cid = cls x} (super ◅ z) =
All.tabulate {xs = Class.decls (Σ (cls x)) FIELD} (λ{ {_ , ty} _ → default ty})
++-all
defaultObject' z
{-
We collect these definitions under the abstract ObjEncoding interface for usage in the semantics
-}
encoding : ObjEncoding
encoding = record {
Obj = Obj ;
weaken-obj = λ cid ext O → weaken-obj cid ext O ;
getter = getter ;
setter = setter ;
defaultObject = λ cid → defaultObject' (rooted cid)
}
|
Since 1990 the total number of hours flown annually by the GA sector has remained in the range 1 @.@ 25 – 1 @.@ 35 million , the dominant sector being traditional GA flying , which accounts for 0 @.@ 6 million per year . An overall increase in aircraft numbers combined with nil growth in hours flown has brought the annual average utilisation per aircraft down from 157 hours in 1984 to 103 hours in 2002 . The decline in asset utilisation has led to speculation that the economic health of the GA industry is weakening , though the lack of data on profitability makes this difficult to confirm .
|
theory prop_10
imports Main
"../../TestTheories/Listi"
"../../TestTheories/Naturals"
"$HIPSTER_HOME/IsaHipster"
begin
theorem unknown02 : "init (tail x) = tail (init x)"
by hipster_induct_schemes
end
|
\section{TikZ externalize}
The .tikz image was generated using the \emph{externalize} option.
\begin{figure}[htbp]
\includegraphics[width=0.5\textwidth]{example_2}
\caption{Same plot from tikzfile again}
\label{tikz:fig:example:1}
\end{figure}
|
Want to get the current Womens Fashion discounts and bargains from Aldo Free Vouchers. All girls desire the finest price tags on style products. Then you have actually come to the ideal location, if you want to know all of the sales and offers. Dunfermline Press will keep going over for the best deals in order that you don't need to. Then you have come to the best location, if you are shopping for your self or for somebody else. |
------------------------------------------------------------------------------
-- Testing nested axioms
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
{-
Processing this file should be generate a TPTP file with the following
axioms
fof(..., axiom, ( a = b )).
fof(..., axiom, ( b = c )).
fof(..., axiom, ( c = d )).
-}
module NestedAxioms.C where
open import NestedAxioms.A
open import NestedAxioms.B
------------------------------------------------------------------------------
postulate
d : D
c≡d : c ≡ d
{-# ATP axiom c≡d #-}
postulate foo : d ≡ a
{-# ATP prove foo #-}
|
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module Issue3a where
module A where
postulate
D : Set
_≡_ : D → D → Set
a b : D
postulate p : a ≡ b
open A
{-# ATP axiom p #-}
postulate foo : a ≡ b
{-# ATP prove foo #-}
|
import category_theory.category.default
universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted
namespace category_theory
variables (C : Type u) [category.{v} C]
--rewrite this
/-
# Category world
## Level 7: Cancellations
With monomorphisms and epimorphisms, we get some new useful cancellation laws. You will notice that the following two lemmas are pretty similar to the lemma we had in level 5 of world 1. See if you can spot the difference.
-/
/- Lemma
If $$f : X ⟶ Y$$ and $$g : X ⟶ Y$$ are morphisms such that $$f = g$$, then $$f ≫ h = g ≫ h$$.
-/
lemma cancel_epi_id' (X Y : C) (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y :=
begin
split,
intro hyp,
rw ← category.comp_id f at hyp,
rw category.assoc at hyp,
rw category.id_comp at hyp,
rw ← cancel_epi f,
exact hyp,
intro hyp,
rw hyp,
exact category.comp_id f,
end
end category_theory |
{-# OPTIONS --rewriting -v rewriting:80 #-}
open import Agda.Builtin.Equality
{-# BUILTIN REWRITE _≡_ #-}
postulate
A : Set
f : A → A
h : .A → A → A
rew : ∀ {x} → h x x ≡ x
{-# REWRITE rew #-}
test2 : (x y : A) → h x y ≡ y
test2 x y = refl
postulate
r : .A → A
s : .A → A
rewr : ∀ x → r x ≡ s x
{-# REWRITE rewr #-}
|
function [leftmap,rightmap] = mne_read_morph_map(from,to,subjects_dir)
%
% [leftmap,rightmap] = mne_read_morph_map(from,to,subjects_dir)
%
% Read the morphing map from subject 'from' to subject 'to'.
% If subjects_dir is not specified, the SUBJECTS_DIR environment
% variable is used
%
%
% Author : Matti Hamalainen, MGH Martinos Center
% License : BSD 3-clause
%
%
% Revision 1.1 2008/03/25 21:06:08 msh
% Added mne_read_morph_map function
%
%
me='MNE:mne_read_morph_map';
global FIFF;
if isempty(FIFF)
FIFF = fiff_define_constants();
end
if nargin < 3
subjects_dir=getenv('SUBJECTS_DIR');
if isempty(subjects_dir)
error(me,'SUBJECTS_DIR not set');
end
end
if nargin < 2
error(me,'Not enough input arguments');
end
%
% Does the file exist
%
name = sprintf('%s/morph-maps/%s-%s-morph.fif',subjects_dir,from,to);
if ~exist(name,'file')
name = sprintf('%s/morph-maps/%s-%s-morph.fif',subjects_dir,to,from);
if ~exist(name,'file')
error(me,'The requested morph map does not exist');
end
end
%
% Open it
%
[fid,tree] = fiff_open(name);
%
% Locate all maps
%
maps = fiff_dir_tree_find(tree,FIFF.FIFFB_MNE_MORPH_MAP);
if isempty(maps)
fclose(fid);
error(me,'Morphing map data not found');
end
%
% Find the correct ones
%
for k = 1:length(maps)
tag = find_tag(maps(k),FIFF.FIFF_MNE_MORPH_MAP_FROM);
if strcmp(tag.data,from)
tag = find_tag(maps(k),FIFF.FIFF_MNE_MORPH_MAP_TO);
if strcmp(tag.data,to)
%
% Names match: which hemishere is this?
%
tag = find_tag(maps(k),FIFF.FIFF_MNE_HEMI);
if tag.data == FIFF.FIFFV_MNE_SURF_LEFT_HEMI
tag = find_tag(maps(k),FIFF.FIFF_MNE_MORPH_MAP);
leftmap = tag.data;
fprintf(1,'\tLeft-hemisphere map read.\n');
elseif tag.data == FIFF.FIFFV_MNE_SURF_RIGHT_HEMI
tag = find_tag(maps(k),FIFF.FIFF_MNE_MORPH_MAP);
rightmap = tag.data;
fprintf(1,'\tRight-hemisphere map read.\n');
end
end
end
end
fclose(fid);
if ~exist('leftmap')
error(me,'Left hemisphere map not found in %s',name);
end
if ~exist('rightmap')
error(me,'Left hemisphere map not found in %s',name);
end
return;
function [tag] = find_tag(node,findkind)
for p = 1:node.nent
if node.dir(p).kind == findkind
tag = fiff_read_tag(fid,node.dir(p).pos);
return;
end
end
tag = [];
return;
end
end
|
= = Taking The Gully = =
|
------------------------------------------------------------------------------
-- Testing the translation of the propositional functions
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module PropositionalFunction1 where
------------------------------------------------------------------------------
postulate
D : Set
A : D → Set
a : D
-- In this case, the propositional function does not use logical
-- constants.
postulate foo : A a → A a
{-# ATP prove foo #-}
|
"""
Overload of LightGraphs.bfs_parents that provides an alternative outneighbors function.
See [`LightGraphs.bfs_parents`](@ref)
"""
LightGraphs.bfs_parents(g::AbstractGraph, s::Integer; dir = :out) =
(dir == :out) ?
LightGraphs._bfs_parents(g, s, outneighbors_ranked) :
LightGraphs._bfs_parents(g, s, inneighbors)
"""
For the given graph and vertex, return the list of the vertex's out neighbors
ranked by edge weight between vertex and the neighbor (ascending order by default).
This function is invoked by [`bfs_parents`](@ref) and is not intended to be called directly.
@ TODO #17 Benchmark this to see if using views would be faster.
"""
function outneighbors_ranked(g, v; order=:asc)
alln = collect(outneighbors(g,v))
length(alln) == 1 && return alln
W = LightGraphs.weights(g)
T = eltype(W)
rw = T[]
for n in alln
w = W[v,n]
push!(rw, w)
end
idx = Array{Int}(undef, length(rw))
sortperm!(idx, rw; rev = (order == :desc))
return alln[idx]
end
|
/-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import data.nat.interval
import data.nat.prime
import group_theory.perm.sign
import tactic.fin_cases
example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val :=
begin
fin_cases *,
simp, assumption,
simp, assumption,
simp, assumption,
end
example (f : ℕ → Prop) (p : fin 0) : f p.val :=
by fin_cases *
example (f : ℕ → Prop) (p : fin 1) (h : f 0) : f p.val :=
begin
fin_cases p,
assumption
end
example (x2 : fin 2) (x3 : fin 3) (n : nat) (y : fin n) : x2.val * x3.val = x3.val * x2.val :=
begin
fin_cases x2;
fin_cases x3,
success_if_fail { fin_cases * },
success_if_fail { fin_cases y },
all_goals { refl },
end
open finset
example (x : ℕ) (h : x ∈ Ico 2 5) : x = 2 ∨ x = 3 ∨ x = 4 :=
begin
fin_cases h,
all_goals { simp }
end
open nat
example (x : ℕ) (h : x ∈ [2,3,5,7]) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 :=
begin
fin_cases h,
all_goals { simp }
end
example (x : ℕ) (h : x ∈ [2,3,5,7]) : true :=
begin
success_if_fail { fin_cases h with [3,3,5,7] },
trivial
end
example (x : list ℕ) (h : x ∈ [[1],[2]]) : x.length = 1 :=
begin
fin_cases h with [[1],[1+1]],
simp,
guard_target (list.length [1 + 1] = 1),
simp
end
-- testing that `with` arguments are elaborated with respect to the expected type:
example (x : ℤ) (h : x ∈ ([2,3] : list ℤ)) : x = 2 ∨ x = 3 :=
begin
fin_cases h with [2,3],
all_goals { simp }
end
instance (n : ℕ) : decidable (prime n) := decidable_prime_1 n
example (x : ℕ) (h : x ∈ (range 10).filter prime) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 :=
begin
fin_cases h; exact dec_trivial
end
open equiv.perm
example (x : (Σ (a : fin 4), fin 4)) (h : x ∈ fin_pairs_lt 4) : x.1.val < 4 :=
begin
fin_cases h; simp,
any_goals { exact dec_trivial },
end
example (x : fin 3) : x.val < 5 :=
begin
fin_cases x; exact dec_trivial
end
example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val :=
begin
fin_cases *,
all_goals { assumption }
end
example (n : ℕ) (h : n % 3 ∈ [0,1]) : true :=
begin
fin_cases h,
guard_hyp h : n % 3 = 0, trivial,
guard_hyp h : n % 3 = 1, trivial,
end
|
[STATEMENT]
lemma (in comm_group) triv_rel:
"restrict (\<lambda>_. 0::int) A \<in> relations A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<lambda>_\<in>A. 0) \<in> relations A
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. (\<Otimes>a\<in>A. a [^] (\<lambda>_\<in>A. 0) a) = \<one>
2. (\<lambda>_\<in>A. 0) \<in> extensional A
[PROOF STEP]
show "(\<Otimes>a\<in>A. a [^] (\<lambda>_\<in>A. 0::int) a) = \<one>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<Otimes>a\<in>A. a [^] (\<lambda>_\<in>A. 0) a) = \<one>
[PROOF STEP]
by (intro finprod_one_eqI, simp)
[PROOF STATE]
proof (state)
this:
(\<Otimes>a\<in>A. a [^] (\<lambda>_\<in>A. 0) a) = \<one>
goal (1 subgoal):
1. (\<lambda>_\<in>A. 0) \<in> extensional A
[PROOF STEP]
qed simp |
theory Substitution_Sema
imports Substitution Sema
begin
lemma substitution_lemma: "\<A> \<Turnstile> F[G / n] \<longleftrightarrow> \<A>(n := \<A> \<Turnstile> G) \<Turnstile> F" by(induction F; simp)
end
|
(*
* Module: SVAOS
*
* Description:
* Prove that a simple CFI policy is maintained for the semantics of our
* language.
*)
(* Load Coq Standard Library modules *)
Require Import Arith.
Require Import List.
Require Import Coq.Logic.Classical_Prop.
(* Load SVAOS specific modules *)
Require Import Semantics.
Require Import ICProofs.
(*
* Theorem: threadIsValid
*
* Description:
* This theorem proves that if a thread list is valid, then any thread
* fetched from the list is valid.
*)
Theorem threadIsValid: forall (cfg : list nat) (mmu : MMU) (ds : store) (tl : ThreadList) (n : nat),
validThreadList tl cfg mmu ds -> validThread (getThread n tl) cfg mmu ds.
Proof.
intros cfg mmu ds tl.
induction tl.
(* Case 1 *)
intros.
unfold getThread.
destruct n.
(* Case 1a *)
auto.
(* Case 1b *)
auto.
(* Case 2 *)
auto.
(* Case 3 *)
intros.
inversion H.
destruct n.
(* Case 3a *)
unfold getThread.
simpl.
auto.
(* Case 3b *)
fold validThreadList in H1.
assert (validThreadList (a :: tl) cfg mmu ds).
unfold validThreadList.
split.
auto.
fold validThreadList.
auto.
apply IHtl.
auto.
Qed.
(*
* Theorem: cfisafe
*
* Description:
* Prove that the program counter always moves to the next instruction
* or is changed to a value that is within the list of acceptable
* targets.
*)
Theorem cfisafe : forall c1 c2 : config,
c1 ==> c2 /\
(validThreadList (getThreadList c1) (getCFG c1) (getCMMU c1) (getStore c1)) /\
(In (getTH c1) (getCFG c1))
->
(getPC c2) = (getPC c1 + 1) \/
(In (getPC c2) (getCFG c1)) \/
((vlookup (minus (getPC c2) 1) c2) = svaSwap) \/
((getPC c2) = (getICPC (itop (getThreadICList (getCurrThread c1) (getThreadList c1))))).
Proof.
intros c1 c2.
intro H.
destruct H.
destruct H.
destruct c.
(* First induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Second induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Third induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Fourth induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Subtraction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Fifth induction case *)
right.
left.
simpl.
destruct H as [H1 H2].
apply H2.
(* Sixth induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Seventh induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Eighth induction case *)
right.
left.
simpl.
destruct H as [H1 H2].
apply H2.
(* Addition to case 8: jeq fallthrough *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Ninth induction case *)
right.
left.
simpl.
destruct H as [H1 H2].
apply H2.
(* Addition to case 9: jne fallthrough *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Tenth induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
auto.
(* Case 11 *)
left.
simpl.
rewrite -> plus_comm.
simpl.
auto.
(* Case 12 *)
simpl.
simpl in H0.
right.
unfold vlookup.
unfold vLookup.
simpl.
destruct H0 as [H0 TH].
assert (validThread (getThread vr tl) CFG MMU DS).
apply threadIsValid.
auto.
destruct H.
destruct H2.
destruct getThread.
unfold validThread in H1.
unfold canThreadSwap in H3.
destruct H3 as [H3 H4].
rewrite -> H3 in H1.
simpl.
unfold vLookup in H1.
destruct H1.
left.
auto.
right.
auto.
(* Case 13 *)
simpl.
right.
left.
simpl in H0.
apply H0.
(* Case 14 *)
simpl.
right.
right.
simpl in H0.
right.
destruct H as [H1 H2].
destruct H2 as [H2 H3].
destruct H3 as [H3 H4].
auto.
(* Case 15 *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Case 16 *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Case 17 *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Case 18 *)
simpl.
left.
rewrite -> plus_comm.
auto.
Qed.
(*
* Theorem: cfisafe2
*
* Description:
* Prove that the program counter always moves to the next instruction
* or is changed to a value that is within the list of acceptable
* targets.
*)
Theorem cfisafe2 : forall c1 c2 : config,
c1 ==> c2 /\
(validThreadList (getThreadList c1) (getCFG c1) (getCMMU c1) (getStore c1)) /\
(In (getTH c1) (getCFG c1)) /\
(pcInText c1) /\
(validThreadIDs c1) /\
(validCFG c1 (getCFG c1)) /\
(In (getThread (getCurrThread c1) (getThreadList c1)) (getThreadList c1)) /\
(textMappedLinear c1) /\
(AreAllThreadICsInText (getThreadList c1) (c1)) /\
(AreAllThreadSICsInText (getThreadList c1) (c1)) /\
(validConfig c1) /\
(textNotWriteable c1) /\
(textMappedOnce c1) /\
(threadListInText (getThreadList c1) (getCFG c1) (getCMMU c1)
(getTextStart c1) (getTextEnd c1)) /\
(goodPCInConfigIC c1) /\
(goodPCInConfigSIC c1)
->
(getPC c2) = (getPC c1 + 1) \/
(In (getPC c2) (getCFG c1)) \/
((vlookup (minus (getPC c2) 1) c2) = svaSwap) \/
((vlookup (minus (getPC c2) 1) c2) = trap) \/
((getPC c2) = 0).
Proof.
intros c1 c2.
intro H.
destruct H as [H I].
destruct I as [I1 I].
destruct I as [I2 I].
destruct I as [I3 I].
destruct I as [I4 I].
destruct I as [I5 I].
destruct I as [I6 I].
destruct I as [I7 I].
destruct I as [I8 I].
destruct I as [I9 I].
destruct I as [I10 I].
destruct I as [I11 I].
destruct I as [I12 I].
destruct I as [I13 I].
destruct I as [I14 I].
assert (goodPCInConfigIC c2).
apply pcInIC with (c1 := c1).
repeat (split ; auto).
apply areAllIffAll.
auto.
auto.
apply getNWTLPC.
repeat (split ; auto).
destruct H.
destruct c.
(* First induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Second induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Third induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Fourth induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Subtraction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Fifth induction case *)
right.
left.
simpl.
destruct H as [HA HB].
apply HB.
(* Sixth induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Seventh induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
reflexivity.
(* Eighth induction case *)
right.
left.
simpl.
apply H.
(* Addition to case 8: jeq fallthrough *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Ninth induction case *)
right.
left.
simpl.
apply H.
(* Addition to case 9: jne fallthrough *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Tenth induction case *)
left.
simpl.
rewrite -> plus_comm.
simpl.
auto.
(* Case 11 *)
left.
simpl.
rewrite -> plus_comm.
simpl.
auto.
(* Case 12: svaSwap *)
simpl.
simpl in H0.
right.
unfold vlookup.
unfold vLookup.
simpl.
assert (validThread (getThread vr tl) CFG MMU DS).
apply threadIsValid.
auto.
destruct H.
destruct H2.
destruct getThread.
unfold validThread in H1.
unfold canThreadSwap in H3.
destruct H3 as [H3 H4].
rewrite -> H3 in H1.
simpl.
unfold vLookup in H1.
destruct H1.
left.
auto.
right.
auto.
(* Case 13 *)
simpl.
right.
left.
apply I2.
(* Case 14 *)
simpl.
right.
assert (goodPCICL (getThreadICList tid tl) CFG MMU DS).
apply GoodPCICL.
auto.
destruct H as [H20 H].
destruct H as [H21 H].
destruct H as [H22 H].
rewrite -> H22.
simpl.
unfold vlookup.
simpl.
apply goodPCInItop in H1.
unfold goodPCIC in H1.
destruct H1.
left.
auto.
destruct H1.
right.
right.
left.
auto.
right.
right.
right.
auto.
(* Case 15 *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Case 16 *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Case 17 *)
simpl.
left.
rewrite -> plus_comm.
auto.
(* Case 18 *)
simpl.
left.
rewrite -> plus_comm.
auto.
Qed.
(*
* Theorem: NXText
*
* Description:
* Prove that fetching an instruction through a virtual address never changes
* even though stores can modify physical memory and the MMU can remap pages.
*)
Theorem NXText : forall (c1 c2 : config)
(v : nat),
(getTextStart c1) <= (getPhysical (getTLB v (getCMMU c1))) <= (getTextEnd c1) /\
(validConfig c1) /\
(textNotWriteable c1) /\
(textMappedOnce c1) /\
c1 ==> c2
-> (vLookup v (getCMMU c1) (getStore c1)) =
(vLookup v (getCMMU c2) (getStore c2)).
Proof.
intros.
destruct H as [h1 H].
destruct H as [h2 H].
destruct H as [h3 H].
destruct H as [h4 H].
(* Prove that several properties hold on the final configuration *)
(*
assert (validConfig c2).
apply alwaysValid with c1.
auto.
assert (textNotWriteable c2).
apply neverWriteText with c1.
auto.
assert (textMappedOnce c2).
apply neverMapTextTwice with c1.
auto.
*)
(* Prove by induction on the proof tree *)
destruct H.
destruct c.
(* Induction case 1 *)
auto.
(* Induction case 2 *)
auto.
(* Induction case 3 *)
simpl.
unfold vLookup.
simpl in h1.
simpl in h2.
simpl in h3.
destruct H.
destruct H0.
(*
* Need to show that the two physical addresses must be different. This is
* because the address written cannot be in the text segment while the address
* checked is within the text segment. The address written cannot be within
* the text segment because the text segment is not writeable.
*)
assert (getPhysical (getTLB v MMU) <> getPhysical (getTLB n MMU)).
(* Detour: show that v is not writeable *)
simpl in h4.
assert (~ canWrite v MMU).
apply h3.
auto.
(* Back from detour: show that the two physical addresses must be different *)
assert (v <> n).
contradict H2.
rewrite -> H2.
apply H1.
apply h4.
auto.
(* Resume the proof of induction case 3 *)
rewrite <- sameRead.
auto.
apply H2.
(* Induction case 4 *)
auto.
(* Induction case 5 *)
auto.
(* Subtraction case *)
auto.
(* Induction case 6 *)
simpl.
destruct H as [h5 H].
destruct H as [h6 H].
destruct H as [h7 H].
destruct H as [h8 H].
destruct H as [h9 H].
rewrite -> h7 in h9.
simpl in h1.
simpl in h2.
simpl in h3.
simpl in h4.
assert (v <> v0).
destruct h9 as [ha | hb].
(* Case: getPhysical (getTLB v0 MMU) < cs *)
contradict ha.
apply le_not_lt.
rewrite <- ha.
apply h1.
(* Case: ce < getPhysical (getTLB v0 MMU) *)
contradict hb.
apply le_not_lt.
rewrite <- hb.
apply h1.
apply sameMMURead.
apply H0.
(* Induction case 7 *)
auto.
(* Induction case 8 *)
auto.
auto.
(* Induction case 9 *)
auto.
auto.
(* Induction case 10 *)
auto.
(* Induction case 11 *)
auto.
(* Induction case 12 *)
auto.
(* Induction case 13 *)
auto.
(* Induction case 14 *)
auto.
(* Induction case 15 *)
auto.
(* Induction case 16 *)
auto.
(* Induction case 17 *)
auto.
(* Induction case 18 *)
auto.
Qed.
|
[STATEMENT]
lemma length_col_mat_to_cols_list [simp]:
assumes "j < dim_col A"
shows "length (col (mat_to_cols_list A) j) = dim_row A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. length (Matrix_Legacy.col (mat_to_cols_list A) j) = dim_row A
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
j < dim_col A
goal (1 subgoal):
1. length (Matrix_Legacy.col (mat_to_cols_list A) j) = dim_row A
[PROOF STEP]
by (simp add: col_def mat_to_cols_list_def) |
Require Import ssreflect.
Inductive color :=
| blue
| red.
Definition inv (c : color) :=
match c with
| red => blue
| blue => red
end.
Eval compute in (inv (inv red)).
(* various versions *)
Lemma inv_conv : forall x, inv (inv x) = x.
move => x.
case: x.
- simpl.
reflexivity.
- reflexivity.
Restart.
move => x.
case x; reflexivity.
Restart.
move => [ | ]; reflexivity.
Qed.
Check true.
(* ===> true : bool *)
Inductive opt_nat :=
None
| Some : nat -> opt_nat.
Definition opt_add :=
fun (n : opt_nat) (m : opt_nat) =>
match n, m with
| Some a, Some b => Some (a+b)
| _ , _ => None
end.
(* This two a equal
Definition add_opt n m :=
match n, m with
| Some a, Some b => Some (a+b)
| None, Some _ => None
| Some _, None => None
| None, None => None
end.
*)
Eval compute in (opt_add (Some 2)(Some 3)).
Eval compute in (opt_add (Some 2) None).
Definition pred n :=
match n with
O => O
| S m => m
end.
Eval compute in (pred (pred 6)).
Eval compute in (pred 0).
Eval compute in (pred 5).
Eval compute in (S 3).
Eval compute in (S (pred 3)).
(* The following function prove that if the pred of x plus 1 is iteself then it's 0 *)
Lemma pred_corr :
forall x, S (pred x) = x \/ x = 0.
move => x.
case: x.
- simpl.
right; reflexivity.
- move => x.
simpl.
left; reflexivity.
Restart.
move => [ | y].
- right; reflexivity.
- left; reflexivity.
Qed.
Fixpoint plus n m :=
match n with
| O => m
| S p => S (plus p m)
end.
Eval compute in (plus 2 2).
Eval compute in (plus (S O) (S O)).
Lemma dpd : (plus 2 2) = 4.
reflexivity.
Qed.
Lemma l1 : forall x, plus 0 x = x.
move => x.
reflexivity.
Qed.
Lemma l2 : forall x, plus x 0 = x.
move => x.
simpl.
induction x.
- simpl.
reflexivity.
- simpl.
rewrite IHx.
reflexivity.
Qed.
Fixpoint double (n : nat) :=
match n with
| O => O
| S m => S (S (double m))
end.
Eval compute in (double 3).
(* Proof by intduction *)
Theorem add_0_r_secondtry : forall n:nat,
n + 0 = n.
Proof.
intros n. destruct n as [| n'] eqn:E.
- (* n = 0 *)
reflexivity. (* so far so good... *)
- (* n = S n' *)
simpl. (* ...but here we are stuck again *)
Abort.
(* Since for n is an unknown number then therefore we need proof by induction *)
Theorem add_0_r : forall n:nat, n + 0 = n.
Proof.
intros n. induction n as [| n' IHn'].
- (* n = 0 *) reflexivity.
- (* n = S n' *) simpl. rewrite -> IHn'. reflexivity.
Qed. |
import GMLInit.Data.Nat.Extended.Basic
namespace ENat
abbrev Finite (e : ENat) : Prop := ∃ x, e.isLE x
namespace Finite
variable (e : ENat)
private def rel (x y : Nat) : Prop := x = y + 1 ∧ ¬e.isLE y
private def wf (isFinite : Finite e) : WellFounded (Finite.rel e) := by
constr
intro x
match isFinite with
| ⟨n,hn⟩ =>
apply Acc.intro
intro x' ⟨h', hx⟩
cases h'
have : x + 1 ≤ n := by
apply Nat.succ_le_of_lt
apply Nat.lt_of_not_ge
intro hge
apply hx
apply e.mono hge
exact hn
match Nat.le.dest this with
| ⟨y, hxy⟩ =>
clear this
induction y generalizing x with
| zero =>
rw [hxy]
apply Acc.intro
intro | _, ⟨rfl, _⟩ => contradiction
| succ y H =>
apply Acc.intro
intro
| _, ⟨rfl, h⟩ =>
apply H
· exact h
· rw [←hxy]
simp_arith
end Finite
private def toNatAux {e : ENat} (isFinite : Finite e) (x : Nat) : Nat :=
if h : e.isLE x then x else toNatAux isFinite (x+1)
termination_by' ⟨Finite.rel e, Finite.wf e isFinite⟩
decreasing_by trivial
private theorem toNatAux_eq {e : ENat} (isFinite : Finite e) (x : Nat) : toNatAux isFinite x = if e.isLE x then x else toNatAux isFinite (x+1) :=
WellFounded.fix_eq _ _ _
private theorem isLE_toNatAux {e : ENat} (isFinite : Finite e) (x : Nat) : e.isLE (toNatAux isFinite x) := by
rw [toNatAux_eq]
split
· assumption
· apply isLE_toNatAux
termination_by' ⟨Finite.rel e, Finite.wf e isFinite⟩
decreasing_by trivial
private theorem toNatAux_le {e : ENat} {y : Nat} (hy : e.isLE y) {x} (hle : x ≤ y) : toNatAux ⟨y,hy⟩ x ≤ y := by
rw [toNatAux_eq]
split
· assumption
· apply toNatAux_le hy
apply Nat.succ_le_of_lt
apply Nat.lt_of_le_of_ne
· exact hle
· intro heq
cases heq
contradiction
termination_by' invImage PSigma.fst ⟨Finite.rel e, Finite.wf e ⟨y,hy⟩⟩
decreasing_by trivial
def toNat (e : ENat) (isFinite : Finite e) : Nat := toNatAux isFinite 0
theorem isLE_toNat (e : ENat) (isFinite : Finite e) : e.isLE (e.toNat isFinite) :=
isLE_toNatAux isFinite 0
theorem toNat_le_of_isLE {e : ENat} {x : Nat} (h : e.isLE x) : toNat e ⟨x,h⟩ ≤ x := by
apply toNatAux_le
· exact h
· exact Nat.zero_le x
theorem isLE_iff_toNat_le (e : ENat) (isFinite : Finite e) (x : Nat) : e.isLE x ↔ e.toNat isFinite ≤ x := by
constr
· intro h
apply toNat_le_of_isLE
exact h
· intro h
apply mono _ h
apply isLE_toNat
@[simp] theorem toNat_ofNat (x : Nat) : toNat (ENat.ofNat x) ⟨x, ofNat_isLE_self x⟩ = x := by
antisymmetry using (.≤.:Nat→Nat→Prop)
· rw [←isLE_iff_toNat_le]
exact ofNat_isLE_self x
· cases x with
| zero => exact Nat.zero_le _
| succ x =>
apply Nat.succ_le_of_lt
apply Nat.lt_of_not_ge
intro (h : _ ≤ x)
rw [←isLE_iff_toNat_le, ofNat_isLE_iff_le] at h
apply Nat.not_gt_of_le h
exact Nat.lt_succ_self x
@[simp] theorem ofNat_toNat (e : ENat) (h : Finite e) : ENat.ofNat (toNat e h) = e := by
apply ENat.ext
intro x
cases hx : e.isLE x with
| true => rw [ofNat_isLE_iff_le, ←isLE_iff_toNat_le, hx]
| false =>
rw [←Bool.not_eq_true] at hx ⊢
apply mt _ hx
intro hx
rw [ofNat_isLE_iff_le] at hx
rw [isLE_iff_toNat_le _ h]
exact hx
end ENat
|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
# size = scratchpad segment size
# nsgmts = number of segments, defaults to 1.
Class(ALStore, AGenericTag, rec(
updateParams := meth(self)
Checked(Length(self.params)=3);
self.size := self.params[1];
self.nsgmts := self.params[2];
self.linesize := self.params[3];
end,
isRegCx := false
));
Class(ALStoreCx, ALStore, rec(
updateParams := meth(self)
Checked(Length(self.params)=3);
self.size := self.params[1]/2;
self.nsgmts := self.params[2];
self.linesize := self.params[3];
end,
isRegCx := true
));
# APad tag.
#
# APad is a special buffering tag meant for things like scratchpads, hence
# the name. It takes four parameters. In order, they are:
# b - the block size in number of elements
# s - the segment size, in number of blocks
# u - the number of segments
# n - a string identifier
#
# The block size is the SMALLEST allowed transfer size when copying data.
# The breakdown rules which propagate the APad tag insure that sub-block
# numbers of contiguous elements are never moved when the tag is present.
#
# A segment is a discrete memory separate from other segments, in the case
# that the 'u' parameter is >1. In the case of DPA, each segment is
# connected to a different compute processor, and we do parallelization
# after the APad tag is dropped.
#
# The string identifier is for the platform writer. You can label things
# like "local memory" or "vector register file."
#
# Also, the software pipelining loop (rather than a standard ISum) is
# automatically used with the APad tag.
Class(APad, AGenericTag, rec(
applied := false,
b := (self) >> self.params[1],
s := (self) >> self.params[2],
u := (self) >> self.params[3],
bs := (self) >> self.params[1] * self.params[2],
bsu := (self) >> Product(DropLast(self.params, 1)),
n := (self) >> self.params[4],
apply := self >> CopyFields(self, rec(applied := true)),
updateParams := meth(self)
Checked(Length(self.params)=4);
end,
print := meth(self)
Print(self.name, "(", PrintCS([self.b(), self.s(), self.u()]),
", \"", self.n(), "\")");
end
));
|
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule mold_jll
using Base
using Base: UUID
import JLLWrappers
JLLWrappers.@generate_main_file_header("mold")
JLLWrappers.@generate_main_file("mold", UUID("0903f2b2-81ff-5be9-abf7-91be1d67eee8"))
end # module mold_jll
|
Normally I am a big AVG fan and I have been getting the business anti-virus 10-key licensing for almost a decade now.
AVG Chat Support: Welcome to AVG.
You: Can you do an easy accross-all-platforms change of the email address to something like obfuscated?
You: And forward the complaint for me? The whole idea was that [email protected] was for official company to company communications between us and AVG. I suppose someone could brute-force guess “avg@” but none of the other addresses are getting this trojan. It is like the perpetrator knew that it was our most trusted anti-trojan relationship, you know what I mean?
You: Are you able to make the email change easier? I have shut down [email protected] and turned on obfuscated for you.
This entry was posted in Front Page on April 19, 2012 by reskin. |
From Categories Require Import Essentials.Notations.
From Categories Require Import Essentials.Types.
From Categories Require Import Essentials.Facts_Tactics.
From Categories Require Import Category.Main.
From Categories Require Import Topos.SubObject_Classifier.
From Categories Require Import Basic_Cons.Terminal Basic_Cons.PullBack.
From Categories Require Import Coq_Cats.Type_Cat.Type_Cat Coq_Cats.Type_Cat.CCC.
Require Import Coq.Logic.ChoiceFacts.
Require Coq.Logic.ClassicalFacts.
Local Axiom PropExt : ClassicalFacts.prop_extensionality.
Local Axiom ConstructiveIndefiniteDescription_Type :
forall T : Type, ConstructiveIndefiniteDescription_on T.
(** The type Prop is the sub-object classifier for Type_Cat. With ⊤ mapping the
single element of the singleton set to (True : Prop) *)
Section Type_Cat_characteristic_function_unique.
Context {A B : Type} (F : @Monic Type_Cat A B) (h : B → Prop)
(hpb : is_PullBack (mono_morphism F) (fun _ => tt) h (fun _ => True)).
Theorem Type_Cat_characteristic_function_unique :
h = fun x => (exists y : A, (mono_morphism F) y = x).
Proof.
extensionality x.
apply PropExt; split.
{
intros Hx.
cut ((fun _ : unit => h x) = (fun _ => True)).
{
intros H.
set (W := equal_f (is_pullback_morph_ex_com_1
hpb unit (fun _ => x) (fun _ => tt) H) tt).
cbn in W.
eexists; exact W.
}
{
extensionality y; apply PropExt; split; trivial.
}
}
{
intros [y []].
set (W := (equal_f (is_pullback_morph_com hpb))).
cbn in W.
rewrite W; trivial.
}
Qed.
End Type_Cat_characteristic_function_unique.
Local Hint Extern 1 =>
match goal with
[|- ?A = ?B :> unit] =>
try destruct A; try destruct B; trivial; fail
end.
Program Definition Type_Cat_SubObject_Classifier : SubObject_Classifier Type_Cat :=
{|
SOC := Prop;
SOC_morph := fun _ : unit => True;
SOC_char := fun A B f x => exists y : A, (mono_morphism f) y = x;
SO_pulback :=
fun A B f =>
{|
is_pullback_morph_ex :=
fun p' pm1 pm2 pmc x =>
proj1_sig (ConstructiveIndefiniteDescription_Type
A _
match eq_sym (equal_f pmc x) in _ = y return y with
eq_refl => I
end)
|}
|}.
Next Obligation.
Proof.
extensionality x.
apply PropExt; split; intros H; auto.
exists x; trivial.
Qed.
Next Obligation.
Proof.
extensionality x.
match goal with
[|- mono_morphism ?f (proj1_sig ?A) = _ ] => destruct A as [y Hy]
end.
trivial.
Qed.
Next Obligation.
Proof.
match goal with
[g : (_ ≫–> _)%morphism |- _] =>
match goal with
[H : (fun w => (mono_morphism g) (_ w)) = (fun x => (mono_morphism g) (_ x)) |- _] =>
apply (mono_morphism_monomorphic g) in H
end
end.
auto.
Qed.
Next Obligation.
Proof.
etransitivity; [|symmetry];
eapply Type_Cat_characteristic_function_unique; eassumption.
Qed.
|
lemma of_real_numeral [simp]: "of_real (numeral w) = numeral w" |
lemma poly_mod_minus_left [simp]: "(- x) mod y = - (x mod y)" for x y :: "'a::field poly" |
lemma bigo_const_iff [simp]: "(\<lambda>_. c1) \<in> O[F](\<lambda>_. c2) \<longleftrightarrow> F = bot \<or> c1 = 0 \<or> c2 \<noteq> 0" |
Require Import List Map Envs AllInRel Exp MoreList.
Require Import IL Annotation.
Require Import ExpVarsBounded SpillSound SpillUtil.
Require Import PartialOrder.
Set Implicit Arguments.
Definition is_live_min k ZL Λ s sl LV
:= forall R M, spill_sound k ZL Λ (R,M) s sl
-> LV ⊆ R ∪ M.
Inductive live_min (k:nat)
: list params -> list (⦃var⦄ * ⦃var⦄) -> ⦃var⦄ -> stmt -> spilling -> ann ⦃var⦄ -> Prop :=
| RMinLet ZL Λ x e s an sl LV lv G
: live_min k ZL Λ (singleton x) s sl lv
-> is_live_min k ZL Λ (stmtLet x e s) (ann1 an sl) (LV \ G)
-> live_min k ZL Λ G (stmtLet x e s) (ann1 an sl) (ann1 LV lv)
| RMinIf ZL Λ e s1 s2 an sl1 sl2 LV lv1 lv2 G
: live_min k ZL Λ ∅ s1 sl1 lv1
-> live_min k ZL Λ ∅ s2 sl2 lv2
-> is_live_min k ZL Λ (stmtIf e s1 s2) (ann2 an sl1 sl2) (LV \ G)
-> live_min k ZL Λ G (stmtIf e s1 s2) (ann2 an sl1 sl2) (ann2 LV lv1 lv2)
| RMinReturn ZL Λ e an LV G
: is_live_min k ZL Λ (stmtReturn e) (ann0 an) (LV \ G)
-> live_min k ZL Λ G (stmtReturn e) (ann0 an) (ann0 LV)
| RMinApp ZL Λ f Y an LV G
: is_live_min k ZL Λ (stmtApp f Y) (ann0 an) (LV \ G)
-> live_min k ZL Λ G (stmtApp f Y) (ann0 an) (ann0 LV)
| RSpillFun ZL Λ G F t spl rms sl_F sl_t LV lv_F lv_t
: (forall n Zs sl_s lv_s rm,
get F n Zs
-> get sl_F n sl_s
-> get lv_F n lv_s
-> get rms n rm
-> live_min k (fst ⊝ F ++ ZL) (rms ++ Λ) (fst rm) (snd Zs) sl_s lv_s)
-> live_min k (fst ⊝ F ++ ZL) (rms ++ Λ) ∅ t sl_t lv_t
-> is_live_min k ZL Λ (stmtFun F t) (annF (spl, rms) sl_F sl_t) (LV \ G)
-> live_min k ZL Λ G (stmtFun F t) (annF (spl, rms) sl_F sl_t) (annF LV lv_F lv_t)
.
Lemma live_min_G_anti k ZL Λ G G' s sl lv
: live_min k ZL Λ G s sl lv
-> G ⊆ G'
-> live_min k ZL Λ G' s sl lv.
Proof.
intros RLM Incl.
general induction RLM; econstructor; intros; eauto;
hnf; intros; rewrite <- Incl; eauto.
Qed.
Lemma live_min_getAnn k ZL Λ s sl lv R M :
live_min k ZL Λ ∅ s sl lv
-> spill_sound k ZL Λ (R,M) s sl
-> getAnn lv ⊆ R ∪ M
.
Proof.
intros rliveMin spillSnd. general induction rliveMin; cbn; unfold is_live_min in H;
rewrite <-minus_empty; try eapply H; eauto.
Qed.
Lemma live_min_getAnn_G k ZL Λ G s sl lv :
live_min k ZL Λ G s sl lv
-> (forall R M, spill_sound k ZL Λ (R,M) s sl -> getAnn lv ⊆ R ∪ M)
-> live_min k ZL Λ ∅ s sl lv
.
Proof.
intros rliveMin isMin.
general induction rliveMin; econstructor; cbn in *; eauto;
unfold is_live_min; intros; rewrite minus_empty; eapply isMin; eauto.
Qed.
Lemma live_min_incl_R k ZL Λ s sl lv R M G :
G ⊆ R ∪ M
-> spill_sound k ZL Λ (R, M) s sl
-> live_min k ZL Λ G s sl lv
-> getAnn lv ⊆ R ∪ M
.
Proof.
intros Geq spillSnd rlive.
general induction rlive; cbn;
unfold is_live_min in *; rewrite <-union_subset_equal with (s':=R ∪ M); eauto;
apply incl_minus_incl_union; [| | | |eapply H1;eauto]; eapply H; eauto.
Qed.
Lemma is_live_min_ext Λ Λ' k ZL s sl LV :
poEq Λ Λ'
-> is_live_min k ZL Λ s sl LV
-> is_live_min k ZL Λ' s sl LV
.
Proof.
intros pir2 H. unfold is_live_min in *.
intros. eapply spill_sound_ext in H0; eauto.
Qed.
Lemma live_min_ext Λ Λ' k ZL G s sl lv :
poEq Λ Λ'
-> live_min k ZL Λ G s sl lv
-> live_min k ZL Λ' G s sl lv
.
Proof.
intros Λeq lvMin. general induction lvMin; unfold is_live_min;
econstructor; eauto using is_live_min_ext.
Qed.
Lemma is_live_min_monotone Λ Λ' k ZL s sl LV :
poLe Λ Λ'
-> is_live_min k ZL Λ s sl LV
-> is_live_min k ZL Λ' s sl LV
.
Proof.
intros pir2 H. unfold is_live_min in *.
intros. eapply spill_sound_monotone in H0; eauto.
Qed.
Lemma live_min_monotone Λ Λ' k ZL G s sl lv :
poLe Λ Λ'
-> live_min k ZL Λ G s sl lv
-> live_min k ZL Λ' G s sl lv
.
Proof.
intros Λeq lvMin. general induction lvMin; unfold is_live_min;
econstructor; eauto using is_live_min_monotone.
Qed.
|
[STATEMENT]
lemma hensel_fpxs1_0 [simp]: "hensel_fpxs1 $ 0 = g"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. hensel_fpxs1 $ 0 = g
[PROOF STEP]
by (simp add: hensel_fpxs1_def) |
------------------------------------------------------------------------------
-- Properties for the equality on Conat
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module FOTC.Data.Conat.Equality.PropertiesATP where
open import FOTC.Base
open import FOTC.Data.Conat
open import FOTC.Data.Conat.Equality.Type
------------------------------------------------------------------------------
-- Because a greatest post-fixed point is a fixed-point, then the
-- relation _≈N_ is also a pre-fixed point of the functional ≈-F, i.e.
--
-- ≈-F _≈_ ≤ _≈_ (see FOTC.Data.Conat.Equality.Type).
-- See Issue https://github.com/asr/apia/issues/81 .
≈-inR : D → D → Set
≈-inR m n = m ≡ zero ∧ n ≡ zero
∨ (∃[ m' ] ∃[ n' ] m ≡ succ₁ m' ∧ n ≡ succ₁ n' ∧ m' ≈ n')
{-# ATP definition ≈-inR #-}
≈-in :
∀ {m n} →
m ≡ zero ∧ n ≡ zero
∨ (∃[ m' ] ∃[ n' ] m ≡ succ₁ m' ∧ n ≡ succ₁ n' ∧ m' ≈ n') →
m ≈ n
≈-in h = ≈-coind ≈-inR h' h
where
postulate
h' : ∀ {m n} → ≈-inR m n →
m ≡ zero ∧ n ≡ zero
∨ (∃[ m' ] ∃[ n' ] m ≡ succ₁ m' ∧ n ≡ succ₁ n' ∧ ≈-inR m' n')
{-# ATP prove h' #-}
-- See Issue https://github.com/asr/apia/issues/81 .
≈-reflR : D → D → Set
≈-reflR a b = Conat a ∧ Conat b ∧ a ≡ b
{-# ATP definition ≈-reflR #-}
≈-refl : ∀ {n} → Conat n → n ≈ n
≈-refl {n} Cn = ≈-coind ≈-reflR h₁ h₂
where
postulate
h₁ : ∀ {a b} → ≈-reflR a b →
a ≡ zero ∧ b ≡ zero
∨ (∃[ a' ] ∃[ b' ] a ≡ succ₁ a' ∧ b ≡ succ₁ b' ∧ ≈-reflR a' b')
{-# ATP prove h₁ #-}
postulate h₂ : ≈-reflR n n
{-# ATP prove h₂ #-}
postulate ≡→≈ : ∀ {m n} → Conat m → Conat n → m ≡ n → m ≈ n
{-# ATP prove ≡→≈ ≈-refl #-}
|
println(3+4)
☎ = 2
println(☎)
println(rationalize(1.20))
|
(* This file is generated by Why3's Coq driver *)
(* Beware! Only edit allowed sections below *)
Require Import ZArith.
Require Import Rbase.
Require int.Int.
Require int.MinMax.
Parameter bag : forall (a:Type), Type.
Parameter nb_occ: forall (a:Type), a -> (bag a) -> Z.
Implicit Arguments nb_occ.
Axiom occ_non_negative : forall (a:Type), forall (b:(bag a)) (x:a),
(0%Z <= (nb_occ x b))%Z.
(* Why3 assumption *)
Definition mem (a:Type)(x:a) (b:(bag a)): Prop := (0%Z < (nb_occ x b))%Z.
Implicit Arguments mem.
(* Why3 assumption *)
Definition eq_bag (a:Type)(a1:(bag a)) (b:(bag a)): Prop := forall (x:a),
((nb_occ x a1) = (nb_occ x b)).
Implicit Arguments eq_bag.
Axiom bag_extensionality : forall (a:Type), forall (a1:(bag a)) (b:(bag a)),
(eq_bag a1 b) -> (a1 = b).
Parameter empty_bag: forall (a:Type), (bag a).
Set Contextual Implicit.
Implicit Arguments empty_bag.
Unset Contextual Implicit.
Axiom occ_empty : forall (a:Type), forall (x:a), ((nb_occ x (empty_bag :(bag
a))) = 0%Z).
Axiom is_empty : forall (a:Type), forall (b:(bag a)), (forall (x:a),
((nb_occ x b) = 0%Z)) -> (b = (empty_bag :(bag a))).
Parameter singleton: forall (a:Type), a -> (bag a).
Implicit Arguments singleton.
Axiom occ_singleton : forall (a:Type), forall (x:a) (y:a), ((x = y) /\
((nb_occ y (singleton x)) = 1%Z)) \/ ((~ (x = y)) /\ ((nb_occ y
(singleton x)) = 0%Z)).
Axiom occ_singleton_eq : forall (a:Type), forall (x:a) (y:a), (x = y) ->
((nb_occ y (singleton x)) = 1%Z).
Axiom occ_singleton_neq : forall (a:Type), forall (x:a) (y:a), (~ (x = y)) ->
((nb_occ y (singleton x)) = 0%Z).
Parameter union: forall (a:Type), (bag a) -> (bag a) -> (bag a).
Implicit Arguments union.
Axiom occ_union : forall (a:Type), forall (x:a) (a1:(bag a)) (b:(bag a)),
((nb_occ x (union a1 b)) = ((nb_occ x a1) + (nb_occ x b))%Z).
Axiom Union_comm : forall (a:Type), forall (a1:(bag a)) (b:(bag a)),
((union a1 b) = (union b a1)).
Axiom Union_identity : forall (a:Type), forall (a1:(bag a)), ((union a1
(empty_bag :(bag a))) = a1).
Axiom Union_assoc : forall (a:Type), forall (a1:(bag a)) (b:(bag a)) (c:(bag
a)), ((union a1 (union b c)) = (union (union a1 b) c)).
Axiom bag_simpl : forall (a:Type), forall (a1:(bag a)) (b:(bag a)) (c:(bag
a)), ((union a1 b) = (union c b)) -> (a1 = c).
Axiom bag_simpl_left : forall (a:Type), forall (a1:(bag a)) (b:(bag a))
(c:(bag a)), ((union a1 b) = (union a1 c)) -> (b = c).
(* Why3 assumption *)
Definition add (a:Type)(x:a) (b:(bag a)): (bag a) := (union (singleton x) b).
Implicit Arguments add.
Axiom occ_add_eq : forall (a:Type), forall (b:(bag a)) (x:a) (y:a),
(x = y) -> ((nb_occ x (add x b)) = ((nb_occ x b) + 1%Z)%Z).
Axiom occ_add_neq : forall (a:Type), forall (b:(bag a)) (x:a) (y:a),
(~ (x = y)) -> ((nb_occ y (add x b)) = (nb_occ y b)).
Parameter card: forall (a:Type), (bag a) -> Z.
Implicit Arguments card.
Axiom Card_empty : forall (a:Type), ((card (empty_bag :(bag a))) = 0%Z).
Axiom Card_zero_empty : forall (a:Type), forall (x:(bag a)),
((card x) = 0%Z) -> (x = (empty_bag :(bag a))).
Axiom Card_singleton : forall (a:Type), forall (x:a),
((card (singleton x)) = 1%Z).
Axiom Card_union : forall (a:Type), forall (x:(bag a)) (y:(bag a)),
((card (union x y)) = ((card x) + (card y))%Z).
Axiom Card_add : forall (a:Type), forall (x:a) (b:(bag a)), ((card (add x
b)) = (1%Z + (card b))%Z).
Parameter diff: forall (a:Type), (bag a) -> (bag a) -> (bag a).
Implicit Arguments diff.
Axiom Diff_occ : forall (a:Type), forall (b1:(bag a)) (b2:(bag a)) (x:a),
((nb_occ x (diff b1 b2)) = (Zmax 0%Z ((nb_occ x b1) - (nb_occ x b2))%Z)).
Axiom Diff_empty_right : forall (a:Type), forall (b:(bag a)), ((diff b
(empty_bag :(bag a))) = b).
Axiom Diff_empty_left : forall (a:Type), forall (b:(bag a)),
((diff (empty_bag :(bag a)) b) = (empty_bag :(bag a))).
Axiom Diff_add : forall (a:Type), forall (b:(bag a)) (x:a), ((diff (add x b)
(singleton x)) = b).
Axiom Diff_comm : forall (a:Type), forall (b:(bag a)) (b1:(bag a)) (b2:(bag
a)), ((diff (diff b b1) b2) = (diff (diff b b2) b1)).
(* Why3 goal *)
Theorem Add_diff : forall (a:Type), forall (b:(bag a)) (x:a), (mem x b) ->
((add x (diff b (singleton x))) = b).
(* YOU MAY EDIT THE PROOF BELOW *)
intros X b x H. unfold mem in H.
apply bag_extensionality.
intro y.
unfold add; rewrite occ_union.
rewrite Diff_occ.
destruct (Zmax_spec 0 (nb_occ y b - nb_occ y (singleton x)))
as [(Ha,R)|(Ha,R)]; auto with zarith.
destruct (occ_singleton X x y) as [(H1,H2)|(H1,H2)].
subst; intuition.
generalize (occ_non_negative X b y).
omega.
Qed.
|
After two months of quietly dealing with his symptoms , Cullen 's wife finally called team trainers and asked them to check into his illness . The team took an x @-@ ray and found a large black shadow in his chest . He underwent a CAT scan which revealed Cullen had a baseball @-@ sized tumor ; he was diagnosed as having Non @-@ Hodgkin lymphoma . The diagnosis ended his season , and he immediately began chemotherapy treatments that quickly reduced his cancer . The tumor was gone by September 1997 , but a precautionary test prior to training camp revealed that Cullen still had cancer cells in his body . He missed the entire 1997 – 98 NHL season as he continued to battle the disease , while his teammates wore a uniform patch with his # 12 in support throughout the year .
|
deus ex: the eyeborg documentarian | Abler.
Remember this guy? I mentioned Rob Spence in this post a while back; he’s now working on several film projects around his own and others’ prosthetic gear. Lots to think about here, in the ways he frames the possibilities and discussion. |
module SkewBinaryRandomAccessList
import RandomAccessList
%default total
%access private
data Tree a = Leaf a | Node a (Tree a) (Tree a)
export
data SkewList a = SL (List (Int, Tree a))
ncCons : a -> List (Int, Tree a) -> SkewList a
ncCons x ts = SL ((1, Leaf x) :: ts)
export
RandomAccessList SkewList where
empty = SL []
isEmpty (SL ts) = isNil ts
cons x (SL ts@((w1, t1) :: (w2, t2) :: tts)) =
if w1 == w2 then SL ((1 + w1 + w2, Node x t1 t2) :: tts) else ncCons x ts
cons x (SL ts) = ncCons x ts
head (SL []) = idris_crash "empty list"
head (SL ((_, Leaf x) :: ts)) = x
head (SL ((w, Node x t1 t2) :: ts)) = x
tail (SL []) = ?RandomAccessList_rhs_1
tail (SL ((_, Leaf x) :: ts)) = SL ts
tail (SL ((w, Node x t1 t2) :: ts)) = let hw = assert_total $ w `div` 2 in
SL ((hw, t1) :: (hw, t2) :: ts)
lookup i (SL ts) = look i ts
where
lookTree : Int -> Int -> Tree a -> a
lookTree _ 0 (Leaf x) = x
lookTree _ i (Leaf x) = idris_crash "bad subscript"
lookTree w 0 (Node x t1 t2) = x
lookTree w i (Node x t1 t2) = let w' = assert_total $ w `div` 2 in
if i <= w' then lookTree w' (i - 1) t1 else lookTree w' (i - 1 - w') t2
look i [] = idris_crash "bad subscript"
look i ((w, t) :: ts) =
if i < w then lookTree w i t else look (i - w) ts
update i y (SL ts) = SL (upd i ts)
where
updTree : Int -> Int -> Tree a -> Tree a
updTree _ 0 (Leaf x) = Leaf y
updTree _ i (Leaf x) = idris_crash "bad subscript"
updTree w 0 (Node x t1 t2) = Node y t1 t2
updTree w i (Node x t1 t2) = let w' = assert_total $ w `div` 2 in
if i <= w' then Node x (updTree w' (i - 1) t1) t2
else Node x t1 (updTree w' (i - 1 - w') t2)
upd i [] = idris_crash "bad subscript"
upd i ((w, t) :: ts) =
if i < w then (w, updTree w i t) :: ts else (w, t) :: upd (i - w) ts
|
-- vim:fdm=marker:foldtext=foldtext()
--------------------------------------------------------------------
-- |
-- Module : Test.SmallCheck.Series
-- Copyright : (c) Colin Runciman et al.
-- License : BSD3
-- Maintainer: Roman Cheplyaka <[email protected]>
--
-- You need this module if you want to generate test values of your own
-- types.
--
-- You'll typically need the following extensions:
--
-- >{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
--
-- SmallCheck itself defines data generators for all the data types used
-- by the "Prelude".
--
-- In order to generate values and functions of your own types, you need
-- to make them instances of 'Serial' (for values) and 'CoSerial' (for
-- functions). There are two main ways to do so: using Generics or writing
-- the instances by hand.
--------------------------------------------------------------------
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE DefaultSignatures #-}
#endif
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
#if MIN_VERSION_base(4,8,0)
{-# LANGUAGE Safe #-}
#else
{-# LANGUAGE OverlappingInstances #-}
#if __GLASGOW_HASKELL__ >= 704
{-# LANGUAGE Trustworthy #-}
#endif
#endif
#define HASCBOOL MIN_VERSION_base(4,10,0)
module Test.SmallCheck.Series (
-- {{{
-- * Generic instances
-- | The easiest way to create the necessary instances is to use GHC
-- generics (available starting with GHC 7.2.1).
--
-- Here's a complete example:
--
-- >{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
-- >{-# LANGUAGE DeriveGeneric #-}
-- >
-- >import Test.SmallCheck.Series
-- >import GHC.Generics
-- >
-- >data Tree a = Null | Fork (Tree a) a (Tree a)
-- > deriving Generic
-- >
-- >instance Serial m a => Serial m (Tree a)
--
-- Here we enable the @DeriveGeneric@ extension which allows to derive 'Generic'
-- instance for our data type. Then we declare that @Tree@ @a@ is an instance of
-- 'Serial', but do not provide any definitions. This causes GHC to use the
-- default definitions that use the 'Generic' instance.
--
-- One minor limitation of generic instances is that there's currently no
-- way to distinguish newtypes and datatypes. Thus, newtype constructors
-- will also count as one level of depth.
-- * Data Generators
-- | Writing 'Serial' instances for application-specific types is
-- straightforward. You need to define a 'series' generator, typically using
-- @consN@ family of generic combinators where N is constructor arity.
--
-- For example:
--
-- >data Tree a = Null | Fork (Tree a) a (Tree a)
-- >
-- >instance Serial m a => Serial m (Tree a) where
-- > series = cons0 Null \/ cons3 Fork
--
-- For newtypes use 'newtypeCons' instead of 'cons1'.
-- The difference is that 'cons1' is counts as one level of depth, while
-- 'newtypeCons' doesn't affect the depth.
--
-- >newtype Light a = Light a
-- >
-- >instance Serial m a => Serial m (Light a) where
-- > series = newtypeCons Light
--
-- For data types with more than 6 fields define @consN@ as
--
-- >consN f = decDepth $
-- > f <$> series
-- > <~> series
-- > <~> series
-- > <~> ... {- series repeated N times in total -}
-- ** What does @consN@ do, exactly?
-- | @consN@ has type
-- @(Serial t₁, ..., Serial tₙ) => (t₁ -> ... -> tₙ -> t) -> Series t@.
--
-- @consN@ @f@ is a series which, for a given depth \(d > 0\), produces values of the
-- form
--
-- >f x₁ ... xₙ
--
-- where @xₖ@ ranges over all values of type @tₖ@ of depth up to \(d-1\)
-- (as defined by the 'series' functions for @tₖ@).
--
-- @consN@ functions also ensure that xₖ are enumerated in the
-- breadth-first order. Thus, combinations of smaller depth come first
-- (assuming the same is true for @tₖ@).
--
-- If \(d \le 0\), no values are produced.
cons0, cons1, cons2, cons3, cons4, cons5, cons6, newtypeCons,
-- * Function Generators
-- | To generate functions of an application-specific argument type,
-- make the type an instance of 'CoSerial'.
--
-- Again there is a standard pattern, this time using the @altsN@
-- combinators where again N is constructor arity. Here are @Tree@ and
-- @Light@ instances:
--
--
-- >instance CoSerial m a => CoSerial m (Tree a) where
-- > coseries rs =
-- > alts0 rs >>- \z ->
-- > alts3 rs >>- \f ->
-- > return $ \t ->
-- > case t of
-- > Null -> z
-- > Fork t1 x t2 -> f t1 x t2
--
-- >instance CoSerial m a => CoSerial m (Light a) where
-- > coseries rs =
-- > newtypeAlts rs >>- \f ->
-- > return $ \l ->
-- > case l of
-- > Light x -> f x
--
-- For data types with more than 6 fields define @altsN@ as
--
-- >altsN rs = do
-- > rs <- fixDepth rs
-- > decDepthChecked
-- > (constM $ constM $ ... $ constM rs)
-- > (coseries $ coseries $ ... $ coseries rs)
-- > {- constM and coseries are repeated N times each -}
-- ** What does altsN do, exactly?
-- | @altsN@ has type
-- @(Serial t₁, ..., Serial tₙ) => Series t -> Series (t₁ -> ... -> tₙ -> t)@.
--
-- @altsN@ @s@ is a series which, for a given depth \( d \), produces functions of
-- type
--
-- >t₁ -> ... -> tₙ -> t
--
-- If \( d \le 0 \), these are constant functions, one for each value produced
-- by @s@.
--
-- If \( d > 0 \), these functions inspect each of their arguments up to the depth
-- \( d-1 \) (as defined by the 'coseries' functions for the corresponding
-- types) and return values produced by @s@. The depth to which the
-- values are enumerated does not depend on the depth of inspection.
alts0, alts1, alts2, alts3, alts4, alts5, alts6, newtypeAlts,
-- * Basic definitions
Depth, Series, Serial(..), CoSerial(..),
#if __GLASGOW_HASKELL__ >= 702
-- * Generic implementations
genericSeries,
genericCoseries,
#endif
-- * Convenient wrappers
Positive(..), NonNegative(..), NonZero(..), NonEmpty(..),
-- * Other useful definitions
(\/), (><), (<~>), (>>-),
localDepth,
decDepth,
getDepth,
generate,
limit,
listSeries,
list,
listM,
fixDepth,
decDepthChecked,
constM
-- }}}
) where
import Control.Monad (liftM, guard, mzero, mplus, msum)
import Control.Monad.Logic (MonadLogic, (>>-), interleave, msplit, observeAllT)
import Control.Monad.Reader (ask, local)
import Control.Applicative (empty, pure, (<$>), (<|>))
import Data.Complex (Complex(..))
import Data.Foldable (Foldable)
import Data.Functor.Compose (Compose(..))
import Data.Void (Void, absurd)
import Control.Monad.Identity (Identity(..))
import Data.Int (Int, Int8, Int16, Int32, Int64)
import Data.List (intercalate)
import qualified Data.List.NonEmpty as NE
import Data.Ratio (Ratio, numerator, denominator, (%))
import Data.Traversable (Traversable)
import Data.Word (Word, Word8, Word16, Word32, Word64)
import Foreign.C.Types (CFloat(..), CDouble(..), CChar(..), CSChar(..), CUChar(..), CShort(..), CUShort(..), CInt(..), CUInt(..), CLong(..), CULong(..), CPtrdiff(..), CSize(..), CWchar(..), CSigAtomic(..), CLLong(..), CULLong(..), CIntPtr(..), CUIntPtr(..), CIntMax(..), CUIntMax(..), CClock(..), CTime(..))
#if __GLASGOW_HASKELL__ >= 702
import Foreign.C.Types (CUSeconds(..), CSUSeconds(..))
#endif
#if HASCBOOL
import Foreign.C.Types (CBool(..))
#endif
import Numeric.Natural (Natural)
import Test.SmallCheck.SeriesMonad
#if __GLASGOW_HASKELL__ >= 702
import GHC.Generics (Generic, (:+:)(..), (:*:)(..), C1, K1(..), M1(..), U1(..), V1(..), Rep, to, from)
#endif
------------------------------
-- Main types and classes
------------------------------
--{{{
class Monad m => Serial m a where
series :: Series m a
#if __GLASGOW_HASKELL__ >= 704
default series :: (Generic a, GSerial m (Rep a)) => Series m a
series = genericSeries
#endif
#if __GLASGOW_HASKELL__ >= 702
genericSeries
:: (Monad m, Generic a, GSerial m (Rep a))
=> Series m a
genericSeries = to <$> gSeries
#endif
class Monad m => CoSerial m a where
-- | A proper 'coseries' implementation should pass the depth unchanged to
-- its first argument. Doing otherwise will make enumeration of curried
-- functions non-uniform in their arguments.
coseries :: Series m b -> Series m (a->b)
#if __GLASGOW_HASKELL__ >= 704
default coseries :: (Generic a, GCoSerial m (Rep a)) => Series m b -> Series m (a->b)
coseries = genericCoseries
#endif
#if __GLASGOW_HASKELL__ >= 702
genericCoseries
:: (Monad m, Generic a, GCoSerial m (Rep a))
=> Series m b -> Series m (a->b)
genericCoseries rs = (. from) <$> gCoseries rs
#endif
-- }}}
------------------------------
-- Helper functions
------------------------------
-- {{{
-- | A simple series specified by a function from depth to the list of
-- values up to that depth.
generate :: (Depth -> [a]) -> Series m a
generate f = do
d <- getDepth
msum $ map return $ f d
-- | Limit a 'Series' to its first @n@ elements.
limit :: forall m a . Monad m => Int -> Series m a -> Series m a
limit n0 (Series s) = Series $ go n0 s
where
go 0 _ = empty
go n mb1 = do
cons :: Maybe (b, ml b) <- msplit mb1
case cons of
Nothing -> empty
Just (b, mb2) -> return b <|> go (n-1) mb2
suchThat :: Series m a -> (a -> Bool) -> Series m a
suchThat s p = s >>= \x -> if p x then pure x else empty
-- | Given a depth, return the list of values generated by a 'Serial' instance.
--
-- For example, list all integers up to depth 1:
--
-- * @listSeries 1 :: [Int] -- returns [0,1,-1]@
listSeries :: Serial Identity a => Depth -> [a]
listSeries d = list d series
-- | Return the list of values generated by a 'Series'. Useful for
-- debugging 'Serial' instances.
--
-- Examples:
--
-- * @'list' 3 'series' :: ['Int'] -- returns [0,1,-1,2,-2,3,-3]@
--
-- * @'list' 3 ('series' :: 'Series' 'Data.Functor.Identity' 'Int') -- returns [0,1,-1,2,-2,3,-3]@
--
-- * @'list' 2 'series' :: [['Bool']] -- returns [[],['True'],['False']]@
--
-- The first two are equivalent. The second has a more explicit type binding.
list :: Depth -> Series Identity a -> [a]
list d s = runIdentity $ observeAllT $ runSeries d s
-- | Monadic version of 'list'.
listM d s = observeAllT $ runSeries d s
-- | Sum (union) of series.
infixr 7 \/
(\/) :: Monad m => Series m a -> Series m a -> Series m a
(\/) = interleave
-- | Product of series
infixr 8 ><
(><) :: Monad m => Series m a -> Series m b -> Series m (a,b)
a >< b = (,) <$> a <~> b
-- | Fair version of 'Control.Applicative.ap' and '<*>'.
infixl 4 <~>
(<~>) :: Monad m => Series m (a -> b) -> Series m a -> Series m b
a <~> b = a >>- (<$> b)
uncurry3 :: (a->b->c->d) -> ((a,b,c)->d)
uncurry3 f (x,y,z) = f x y z
uncurry4 :: (a->b->c->d->e) -> ((a,b,c,d)->e)
uncurry4 f (w,x,y,z) = f w x y z
uncurry5 :: (a->b->c->d->e->f) -> ((a,b,c,d,e)->f)
uncurry5 f (v,w,x,y,z) = f v w x y z
uncurry6 :: (a->b->c->d->e->f->g) -> ((a,b,c,d,e,f)->g)
uncurry6 f (u,v,w,x,y,z) = f u v w x y z
-- | Query the current depth.
getDepth :: Series m Depth
getDepth = Series ask
-- | Run a series with a modified depth.
localDepth :: (Depth -> Depth) -> Series m a -> Series m a
localDepth f (Series a) = Series $ local f a
-- | Run a 'Series' with the depth decreased by 1.
--
-- If the current depth is less or equal to 0, the result is 'empty'.
decDepth :: Series m a -> Series m a
decDepth a = do
checkDepth
localDepth (subtract 1) a
checkDepth :: Series m ()
checkDepth = do
d <- getDepth
guard $ d > 0
-- | @'constM' = 'liftM' 'const'@
constM :: Monad m => m b -> m (a -> b)
constM = liftM const
-- | Fix the depth of a series at the current level. The resulting series
-- will no longer depend on the \"ambient\" depth.
fixDepth :: Series m a -> Series m (Series m a)
fixDepth s = getDepth >>= \d -> return $ localDepth (const d) s
-- | If the current depth is 0, evaluate the first argument. Otherwise,
-- evaluate the second argument with decremented depth.
decDepthChecked :: Series m a -> Series m a -> Series m a
decDepthChecked b r = do
d <- getDepth
if d <= 0
then b
else decDepth r
unwind :: MonadLogic m => m a -> m [a]
unwind a =
msplit a >>=
maybe (return []) (\(x,a') -> (x:) `liftM` unwind a')
-- }}}
------------------------------
-- cons* and alts* functions
------------------------------
-- {{{
cons0 :: a -> Series m a
cons0 x = decDepth $ pure x
cons1 :: Serial m a => (a->b) -> Series m b
cons1 f = decDepth $ f <$> series
-- | Same as 'cons1', but preserves the depth.
newtypeCons :: Serial m a => (a->b) -> Series m b
newtypeCons f = f <$> series
cons2 :: (Serial m a, Serial m b) => (a->b->c) -> Series m c
cons2 f = decDepth $ f <$> series <~> series
cons3 :: (Serial m a, Serial m b, Serial m c) =>
(a->b->c->d) -> Series m d
cons3 f = decDepth $
f <$> series
<~> series
<~> series
cons4 :: (Serial m a, Serial m b, Serial m c, Serial m d) =>
(a->b->c->d->e) -> Series m e
cons4 f = decDepth $
f <$> series
<~> series
<~> series
<~> series
cons5 :: (Serial m a, Serial m b, Serial m c, Serial m d, Serial m e) =>
(a->b->c->d->e->f) -> Series m f
cons5 f = decDepth $
f <$> series
<~> series
<~> series
<~> series
<~> series
cons6 :: (Serial m a, Serial m b, Serial m c, Serial m d, Serial m e, Serial m f) =>
(a->b->c->d->e->f->g) -> Series m g
cons6 f = decDepth $
f <$> series
<~> series
<~> series
<~> series
<~> series
<~> series
alts0 :: Series m a -> Series m a
alts0 s = s
alts1 :: CoSerial m a => Series m b -> Series m (a->b)
alts1 rs = do
rs <- fixDepth rs
decDepthChecked (constM rs) (coseries rs)
alts2
:: (CoSerial m a, CoSerial m b)
=> Series m c -> Series m (a->b->c)
alts2 rs = do
rs <- fixDepth rs
decDepthChecked
(constM $ constM rs)
(coseries $ coseries rs)
alts3 :: (CoSerial m a, CoSerial m b, CoSerial m c) =>
Series m d -> Series m (a->b->c->d)
alts3 rs = do
rs <- fixDepth rs
decDepthChecked
(constM $ constM $ constM rs)
(coseries $ coseries $ coseries rs)
alts4 :: (CoSerial m a, CoSerial m b, CoSerial m c, CoSerial m d) =>
Series m e -> Series m (a->b->c->d->e)
alts4 rs = do
rs <- fixDepth rs
decDepthChecked
(constM $ constM $ constM $ constM rs)
(coseries $ coseries $ coseries $ coseries rs)
alts5 :: (CoSerial m a, CoSerial m b, CoSerial m c, CoSerial m d, CoSerial m e) =>
Series m f -> Series m (a->b->c->d->e->f)
alts5 rs = do
rs <- fixDepth rs
decDepthChecked
(constM $ constM $ constM $ constM $ constM rs)
(coseries $ coseries $ coseries $ coseries $ coseries rs)
alts6 :: (CoSerial m a, CoSerial m b, CoSerial m c, CoSerial m d, CoSerial m e, CoSerial m f) =>
Series m g -> Series m (a->b->c->d->e->f->g)
alts6 rs = do
rs <- fixDepth rs
decDepthChecked
(constM $ constM $ constM $ constM $ constM $ constM rs)
(coseries $ coseries $ coseries $ coseries $ coseries $ coseries rs)
-- | Same as 'alts1', but preserves the depth.
newtypeAlts :: CoSerial m a => Series m b -> Series m (a->b)
newtypeAlts = coseries
-- }}}
------------------------------
-- Generic instances
------------------------------
-- {{{
class GSerial m f where
gSeries :: Series m (f a)
class GCoSerial m f where
gCoseries :: Series m b -> Series m (f a -> b)
#if __GLASGOW_HASKELL__ >= 702
instance {-# OVERLAPPABLE #-} GSerial m f => GSerial m (M1 i c f) where
gSeries = M1 <$> gSeries
{-# INLINE gSeries #-}
instance GCoSerial m f => GCoSerial m (M1 i c f) where
gCoseries rs = (. unM1) <$> gCoseries rs
{-# INLINE gCoseries #-}
instance Serial m c => GSerial m (K1 i c) where
gSeries = K1 <$> series
{-# INLINE gSeries #-}
instance CoSerial m c => GCoSerial m (K1 i c) where
gCoseries rs = (. unK1) <$> coseries rs
{-# INLINE gCoseries #-}
instance GSerial m U1 where
gSeries = pure U1
{-# INLINE gSeries #-}
instance GCoSerial m U1 where
gCoseries rs = constM rs
{-# INLINE gCoseries #-}
instance GSerial m V1 where
gSeries = mzero
{-# INLINE gSeries #-}
instance GCoSerial m V1 where
gCoseries = const $ return (\a -> a `seq` let x = x in x)
{-# INLINE gCoseries #-}
instance (Monad m, GSerial m a, GSerial m b) => GSerial m (a :*: b) where
gSeries = (:*:) <$> gSeries <~> gSeries
{-# INLINE gSeries #-}
instance (Monad m, GCoSerial m a, GCoSerial m b) => GCoSerial m (a :*: b) where
gCoseries rs = uncur <$> gCoseries (gCoseries rs)
where
uncur f (x :*: y) = f x y
{-# INLINE gCoseries #-}
instance (Monad m, GSerial m a, GSerial m b) => GSerial m (a :+: b) where
gSeries = (L1 <$> gSeries) `interleave` (R1 <$> gSeries)
{-# INLINE gSeries #-}
instance (Monad m, GCoSerial m a, GCoSerial m b) => GCoSerial m (a :+: b) where
gCoseries rs =
gCoseries rs >>- \f ->
gCoseries rs >>- \g ->
return $
\e -> case e of
L1 x -> f x
R1 y -> g y
{-# INLINE gCoseries #-}
instance {-# OVERLAPPING #-} GSerial m f => GSerial m (C1 c f) where
gSeries = M1 <$> decDepth gSeries
{-# INLINE gSeries #-}
#endif
-- }}}
------------------------------
-- Instances for basic types
------------------------------
-- {{{
instance Monad m => Serial m () where
series = return ()
instance Monad m => CoSerial m () where
coseries rs = constM rs
instance Monad m => Serial m Integer where series = unM <$> series
instance Monad m => CoSerial m Integer where coseries = fmap (. M) . coseries
instance Monad m => Serial m Natural where series = unN <$> series
instance Monad m => CoSerial m Natural where coseries = fmap (. N) . coseries
instance Monad m => Serial m Int where series = unM <$> series
instance Monad m => CoSerial m Int where coseries = fmap (. M) . coseries
instance Monad m => Serial m Word where series = unN <$> series
instance Monad m => CoSerial m Word where coseries = fmap (. N) . coseries
instance Monad m => Serial m Int8 where series = unM <$> series
instance Monad m => CoSerial m Int8 where coseries = fmap (. M) . coseries
instance Monad m => Serial m Word8 where series = unN <$> series
instance Monad m => CoSerial m Word8 where coseries = fmap (. N) . coseries
instance Monad m => Serial m Int16 where series = unM <$> series
instance Monad m => CoSerial m Int16 where coseries = fmap (. M) . coseries
instance Monad m => Serial m Word16 where series = unN <$> series
instance Monad m => CoSerial m Word16 where coseries = fmap (. N) . coseries
instance Monad m => Serial m Int32 where series = unM <$> series
instance Monad m => CoSerial m Int32 where coseries = fmap (. M) . coseries
instance Monad m => Serial m Word32 where series = unN <$> series
instance Monad m => CoSerial m Word32 where coseries = fmap (. N) . coseries
instance Monad m => Serial m Int64 where series = unM <$> series
instance Monad m => CoSerial m Int64 where coseries = fmap (. M) . coseries
instance Monad m => Serial m Word64 where series = unN <$> series
instance Monad m => CoSerial m Word64 where coseries = fmap (. N) . coseries
-- | 'N' is a wrapper for 'Integral' types that causes only non-negative values
-- to be generated. Generated functions of type @N a -> b@ do not distinguish
-- different negative values of @a@.
newtype N a = N { unN :: a } deriving (Eq, Ord, Show)
instance Real a => Real (N a) where
toRational (N x) = toRational x
instance Enum a => Enum (N a) where
toEnum x = N (toEnum x)
fromEnum (N x) = fromEnum x
instance Num a => Num (N a) where
N x + N y = N (x + y)
N x * N y = N (x * y)
negate (N x) = N (negate x)
abs (N x) = N (abs x)
signum (N x) = N (signum x)
fromInteger x = N (fromInteger x)
instance Integral a => Integral (N a) where
quotRem (N x) (N y) = (N q, N r)
where
(q, r) = x `quotRem` y
toInteger (N x) = toInteger x
instance (Num a, Enum a, Serial m a) => Serial m (N a) where
series = generate $ \d -> take (d+1) [0..]
instance (Integral a, Monad m) => CoSerial m (N a) where
coseries rs =
-- This is a recursive function, because @alts1 rs@ typically calls
-- back to 'coseries' (but with lower depth).
--
-- The recursion stops when depth == 0. Then alts1 produces a constant
-- function, and doesn't call back to 'coseries'.
alts0 rs >>- \z ->
alts1 rs >>- \f ->
return $ \(N i) ->
if i > 0
then f (N $ i-1)
else z
-- | 'M' is a helper type to generate values of a signed type of increasing magnitude.
newtype M a = M { unM :: a } deriving (Eq, Ord, Show)
instance Real a => Real (M a) where
toRational (M x) = toRational x
instance Enum a => Enum (M a) where
toEnum x = M (toEnum x)
fromEnum (M x) = fromEnum x
instance Num a => Num (M a) where
M x + M y = M (x + y)
M x * M y = M (x * y)
negate (M x) = M (negate x)
abs (M x) = M (abs x)
signum (M x) = M (signum x)
fromInteger x = M (fromInteger x)
instance Integral a => Integral (M a) where
quotRem (M x) (M y) = (M q, M r)
where
(q, r) = x `quotRem` y
toInteger (M x) = toInteger x
instance (Num a, Enum a, Monad m) => Serial m (M a) where
series = others `interleave` positives
where positives = generate $ \d -> take d [1..]
others = generate $ \d -> take (d+1) [0,-1..]
instance (Ord a, Num a, Monad m) => CoSerial m (M a) where
coseries rs =
alts0 rs >>- \z ->
alts1 rs >>- \f ->
alts1 rs >>- \g ->
pure $ \ i -> case compare i 0 of
GT -> f (M (i - 1))
LT -> g (M (abs i - 1))
EQ -> z
instance Monad m => Serial m Float where
series =
series >>- \(sig, exp) ->
guard (odd sig || sig==0 && exp==0) >>
return (encodeFloat sig exp)
instance Monad m => CoSerial m Float where
coseries rs =
coseries rs >>- \f ->
return $ f . decodeFloat
instance Monad m => Serial m Double where
series = (realToFrac :: Float -> Double) <$> series
instance Monad m => CoSerial m Double where
coseries rs =
(. (realToFrac :: Double -> Float)) <$> coseries rs
instance (Integral i, Serial m i) => Serial m (Ratio i) where
series = pairToRatio <$> series
where
pairToRatio (n, Positive d) = n % d
instance (Integral i, CoSerial m i) => CoSerial m (Ratio i) where
coseries rs = (. ratioToPair) <$> coseries rs
where
ratioToPair r = (numerator r, denominator r)
instance Monad m => Serial m Char where
series = generate $ \d -> take (d+1) ['a'..'z']
instance Monad m => CoSerial m Char where
coseries rs =
coseries rs >>- \f ->
return $ \c -> f (N (fromEnum c - fromEnum 'a'))
instance (Serial m a, Serial m b) => Serial m (a,b) where
series = cons2 (,)
instance (CoSerial m a, CoSerial m b) => CoSerial m (a,b) where
coseries rs = uncurry <$> alts2 rs
instance (Serial m a, Serial m b, Serial m c) => Serial m (a,b,c) where
series = cons3 (,,)
instance (CoSerial m a, CoSerial m b, CoSerial m c) => CoSerial m (a,b,c) where
coseries rs = uncurry3 <$> alts3 rs
instance (Serial m a, Serial m b, Serial m c, Serial m d) => Serial m (a,b,c,d) where
series = cons4 (,,,)
instance (CoSerial m a, CoSerial m b, CoSerial m c, CoSerial m d) => CoSerial m (a,b,c,d) where
coseries rs = uncurry4 <$> alts4 rs
instance (Serial m a, Serial m b, Serial m c, Serial m d, Serial m e) => Serial m (a,b,c,d,e) where
series = cons5 (,,,,)
instance (CoSerial m a, CoSerial m b, CoSerial m c, CoSerial m d, CoSerial m e) => CoSerial m (a,b,c,d,e) where
coseries rs = uncurry5 <$> alts5 rs
instance (Serial m a, Serial m b, Serial m c, Serial m d, Serial m e, Serial m f) => Serial m (a,b,c,d,e,f) where
series = cons6 (,,,,,)
instance (CoSerial m a, CoSerial m b, CoSerial m c, CoSerial m d, CoSerial m e, CoSerial m f) => CoSerial m (a,b,c,d,e,f) where
coseries rs = uncurry6 <$> alts6 rs
instance Monad m => Serial m Bool where
series = cons0 True \/ cons0 False
instance Monad m => CoSerial m Bool where
coseries rs =
rs >>- \r1 ->
rs >>- \r2 ->
return $ \x -> if x then r1 else r2
instance Monad m => Serial m Ordering where
series = cons0 LT \/ cons0 EQ \/ cons0 GT
instance Monad m => CoSerial m Ordering where
coseries rs =
rs >>- \r1 ->
rs >>- \r2 ->
rs >>- \r3 ->
pure $ \x -> case x of
LT -> r1
EQ -> r2
GT -> r3
instance (Serial m a) => Serial m (Maybe a) where
series = cons0 Nothing \/ cons1 Just
instance (CoSerial m a) => CoSerial m (Maybe a) where
coseries rs =
maybe <$> alts0 rs <~> alts1 rs
instance (Serial m a, Serial m b) => Serial m (Either a b) where
series = cons1 Left \/ cons1 Right
instance (CoSerial m a, CoSerial m b) => CoSerial m (Either a b) where
coseries rs =
either <$> alts1 rs <~> alts1 rs
instance Serial m a => Serial m [a] where
series = cons0 [] \/ cons2 (:)
instance CoSerial m a => CoSerial m [a] where
coseries rs =
alts0 rs >>- \y ->
alts2 rs >>- \f ->
return $ \xs -> case xs of [] -> y; x:xs' -> f x xs'
instance Serial m a => Serial m (NE.NonEmpty a) where
series = cons2 (NE.:|)
instance CoSerial m a => CoSerial m (NE.NonEmpty a) where
coseries rs =
alts2 rs >>- \f ->
return $ \(x NE.:| xs') -> f x xs'
#if MIN_VERSION_base(4,4,0)
instance Serial m a => Serial m (Complex a) where
#else
instance (RealFloat a, Serial m a) => Serial m (Complex a) where
#endif
series = cons2 (:+)
#if MIN_VERSION_base(4,4,0)
instance CoSerial m a => CoSerial m (Complex a) where
#else
instance (RealFloat a, CoSerial m a) => CoSerial m (Complex a) where
#endif
coseries rs =
alts2 rs >>- \f ->
return $ \(x :+ xs') -> f x xs'
instance Monad m => Serial m Void where
series = mzero
instance Monad m => CoSerial m Void where
coseries = const $ return absurd
instance (CoSerial m a, Serial m b) => Serial m (a->b) where
series = coseries series
-- Thanks to Ralf Hinze for the definition of coseries
-- using the nest auxiliary.
instance (Serial m a, CoSerial m a, Serial m b, CoSerial m b) => CoSerial m (a->b) where
coseries r = do
args <- unwind series
g <- nest r args
return $ \f -> g $ map f args
where
nest :: forall a b m c . (Serial m b, CoSerial m b) => Series m c -> [a] -> Series m ([b] -> c)
nest rs args = do
case args of
[] -> const `liftM` rs
_:rest -> do
let sf = coseries $ nest rs rest
f <- sf
return $ \(b:bs) -> f b bs
-- show the extension of a function (in part, bounded both by
-- the number and depth of arguments)
instance (Serial Identity a, Show a, Show b) => Show (a -> b) where
show f =
if maxarheight == 1
&& sumarwidth + length ars * length "->;" < widthLimit then
"{"++
intercalate ";" [a++"->"++r | (a,r) <- ars]
++"}"
else
concat $ [a++"->\n"++indent r | (a,r) <- ars]
where
ars = take lengthLimit [ (show x, show (f x))
| x <- list depthLimit series ]
maxarheight = maximum [ max (height a) (height r)
| (a,r) <- ars ]
sumarwidth = sum [ length a + length r
| (a,r) <- ars]
indent = unlines . map (" "++) . lines
height = length . lines
(widthLimit,lengthLimit,depthLimit) = (80,20,3)::(Int,Int,Depth)
instance (Monad m, Serial m (f (g a))) => Serial m (Compose f g a) where
series = Compose <$> series
instance (Monad m, CoSerial m (f (g a))) => CoSerial m (Compose f g a) where
coseries = fmap (. getCompose) . coseries
-- }}}
------------------------------
-- Convenient wrappers
------------------------------
-- {{{
--------------------------------------------------------------------------
-- | 'Positive' @x@ guarantees that \( x > 0 \).
newtype Positive a = Positive { getPositive :: a }
deriving (Eq, Ord, Functor, Foldable, Traversable)
instance Real a => Real (Positive a) where
toRational (Positive x) = toRational x
instance (Num a, Bounded a) => Bounded (Positive a) where
minBound = Positive 1
maxBound = Positive (maxBound :: a)
instance Enum a => Enum (Positive a) where
toEnum x = Positive (toEnum x)
fromEnum (Positive x) = fromEnum x
instance Num a => Num (Positive a) where
Positive x + Positive y = Positive (x + y)
Positive x * Positive y = Positive (x * y)
negate (Positive x) = Positive (negate x)
abs (Positive x) = Positive (abs x)
signum (Positive x) = Positive (signum x)
fromInteger x = Positive (fromInteger x)
instance Integral a => Integral (Positive a) where
quotRem (Positive x) (Positive y) = (Positive q, Positive r)
where
(q, r) = x `quotRem` y
toInteger (Positive x) = toInteger x
instance (Num a, Ord a, Serial m a) => Serial m (Positive a) where
series = Positive <$> series `suchThat` (> 0)
instance Show a => Show (Positive a) where
showsPrec n (Positive x) = showsPrec n x
-- | 'NonNegative' @x@ guarantees that \( x \ge 0 \).
newtype NonNegative a = NonNegative { getNonNegative :: a }
deriving (Eq, Ord, Functor, Foldable, Traversable)
instance Real a => Real (NonNegative a) where
toRational (NonNegative x) = toRational x
instance (Num a, Bounded a) => Bounded (NonNegative a) where
minBound = NonNegative 0
maxBound = NonNegative (maxBound :: a)
instance Enum a => Enum (NonNegative a) where
toEnum x = NonNegative (toEnum x)
fromEnum (NonNegative x) = fromEnum x
instance Num a => Num (NonNegative a) where
NonNegative x + NonNegative y = NonNegative (x + y)
NonNegative x * NonNegative y = NonNegative (x * y)
negate (NonNegative x) = NonNegative (negate x)
abs (NonNegative x) = NonNegative (abs x)
signum (NonNegative x) = NonNegative (signum x)
fromInteger x = NonNegative (fromInteger x)
instance Integral a => Integral (NonNegative a) where
quotRem (NonNegative x) (NonNegative y) = (NonNegative q, NonNegative r)
where
(q, r) = x `quotRem` y
toInteger (NonNegative x) = toInteger x
instance (Num a, Ord a, Serial m a) => Serial m (NonNegative a) where
series = NonNegative <$> series `suchThat` (>= 0)
instance Show a => Show (NonNegative a) where
showsPrec n (NonNegative x) = showsPrec n x
-- | 'NonZero' @x@ guarantees that \( x \ne 0 \).
newtype NonZero a = NonZero { getNonZero :: a }
deriving (Eq, Ord, Functor, Foldable, Traversable)
instance Real a => Real (NonZero a) where
toRational (NonZero x) = toRational x
instance (Eq a, Num a, Bounded a) => Bounded (NonZero a) where
minBound = let x = minBound in NonZero (if x == 0 then 1 else x)
maxBound = let x = maxBound in NonZero (if x == 0 then -1 else x)
instance Enum a => Enum (NonZero a) where
toEnum x = NonZero (toEnum x)
fromEnum (NonZero x) = fromEnum x
instance Num a => Num (NonZero a) where
NonZero x + NonZero y = NonZero (x + y)
NonZero x * NonZero y = NonZero (x * y)
negate (NonZero x) = NonZero (negate x)
abs (NonZero x) = NonZero (abs x)
signum (NonZero x) = NonZero (signum x)
fromInteger x = NonZero (fromInteger x)
instance Integral a => Integral (NonZero a) where
quotRem (NonZero x) (NonZero y) = (NonZero q, NonZero r)
where
(q, r) = x `quotRem` y
toInteger (NonZero x) = toInteger x
instance (Num a, Ord a, Serial m a) => Serial m (NonZero a) where
series = NonZero <$> series `suchThat` (/= 0)
instance Show a => Show (NonZero a) where
showsPrec n (NonZero x) = showsPrec n x
-- | 'NonEmpty' @xs@ guarantees that @xs@ is not null.
newtype NonEmpty a = NonEmpty { getNonEmpty :: [a] }
instance (Serial m a) => Serial m (NonEmpty a) where
series = NonEmpty <$> cons2 (:)
instance Show a => Show (NonEmpty a) where
showsPrec n (NonEmpty x) = showsPrec n x
-- }}}
------------------------------
-- Foreign.C.Types
------------------------------
-- {{{
#if MIN_VERSION_base(4,5,0)
instance Monad m => Serial m CFloat where
series = newtypeCons CFloat
instance Monad m => CoSerial m CFloat where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CFloat x -> f x
instance Monad m => Serial m CDouble where
series = newtypeCons CDouble
instance Monad m => CoSerial m CDouble where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CDouble x -> f x
#if HASCBOOL
instance Monad m => Serial m CBool where
series = newtypeCons CBool
instance Monad m => CoSerial m CBool where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CBool x -> f x
#endif
instance Monad m => Serial m CChar where
series = newtypeCons CChar
instance Monad m => CoSerial m CChar where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CChar x -> f x
instance Monad m => Serial m CSChar where
series = newtypeCons CSChar
instance Monad m => CoSerial m CSChar where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CSChar x -> f x
instance Monad m => Serial m CUChar where
series = newtypeCons CUChar
instance Monad m => CoSerial m CUChar where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CUChar x -> f x
instance Monad m => Serial m CShort where
series = newtypeCons CShort
instance Monad m => CoSerial m CShort where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CShort x -> f x
instance Monad m => Serial m CUShort where
series = newtypeCons CUShort
instance Monad m => CoSerial m CUShort where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CUShort x -> f x
instance Monad m => Serial m CInt where
series = newtypeCons CInt
instance Monad m => CoSerial m CInt where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CInt x -> f x
instance Monad m => Serial m CUInt where
series = newtypeCons CUInt
instance Monad m => CoSerial m CUInt where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CUInt x -> f x
instance Monad m => Serial m CLong where
series = newtypeCons CLong
instance Monad m => CoSerial m CLong where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CLong x -> f x
instance Monad m => Serial m CULong where
series = newtypeCons CULong
instance Monad m => CoSerial m CULong where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CULong x -> f x
instance Monad m => Serial m CPtrdiff where
series = newtypeCons CPtrdiff
instance Monad m => CoSerial m CPtrdiff where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CPtrdiff x -> f x
instance Monad m => Serial m CSize where
series = newtypeCons CSize
instance Monad m => CoSerial m CSize where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CSize x -> f x
instance Monad m => Serial m CWchar where
series = newtypeCons CWchar
instance Monad m => CoSerial m CWchar where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CWchar x -> f x
instance Monad m => Serial m CSigAtomic where
series = newtypeCons CSigAtomic
instance Monad m => CoSerial m CSigAtomic where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CSigAtomic x -> f x
instance Monad m => Serial m CLLong where
series = newtypeCons CLLong
instance Monad m => CoSerial m CLLong where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CLLong x -> f x
instance Monad m => Serial m CULLong where
series = newtypeCons CULLong
instance Monad m => CoSerial m CULLong where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CULLong x -> f x
instance Monad m => Serial m CIntPtr where
series = newtypeCons CIntPtr
instance Monad m => CoSerial m CIntPtr where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CIntPtr x -> f x
instance Monad m => Serial m CUIntPtr where
series = newtypeCons CUIntPtr
instance Monad m => CoSerial m CUIntPtr where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CUIntPtr x -> f x
instance Monad m => Serial m CIntMax where
series = newtypeCons CIntMax
instance Monad m => CoSerial m CIntMax where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CIntMax x -> f x
instance Monad m => Serial m CUIntMax where
series = newtypeCons CUIntMax
instance Monad m => CoSerial m CUIntMax where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CUIntMax x -> f x
instance Monad m => Serial m CClock where
series = newtypeCons CClock
instance Monad m => CoSerial m CClock where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CClock x -> f x
instance Monad m => Serial m CTime where
series = newtypeCons CTime
instance Monad m => CoSerial m CTime where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CTime x -> f x
instance Monad m => Serial m CUSeconds where
series = newtypeCons CUSeconds
instance Monad m => CoSerial m CUSeconds where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CUSeconds x -> f x
instance Monad m => Serial m CSUSeconds where
series = newtypeCons CSUSeconds
instance Monad m => CoSerial m CSUSeconds where
coseries rs = newtypeAlts rs >>- \f -> return $ \l -> case l of CSUSeconds x -> f x
#endif
-- }}}
|
#pragma once
#include <cassert>
#include <stdint.h>
#include <gsl/gsl-lite.hpp> // gsl::span
#include "HypCommands.h" // RECORD_LENGTH
// Utility constexpr function converting a enum class to its underlying type N/U
#include <type_traits>
template <typename E,
typename = std::enable_if_t<std::is_enum<E>::value>>
constexpr auto ut(E e) noexcept
{
return static_cast<std::underlying_type_t<E>>(e);
}
class SamplePoint {
public:
explicit SamplePoint(const gsl::span<uint8_t>& data);
enum ValueIndex {
eSeconds = 0,
eVolts ,
eAmps ,
emAh_Out , // recalculated
emAh_In , // -"- (is rarely present)
eRPM , // []
eAltitude, // RDU
eTemp1 , // []
eTemp2 , // []
eTemp3 , // []
eThrottle, // [RDU]
eTempAmb , // RDU
ePowerIn,
ePowerOut, // [PRM]
eEfficiency,//[PRM]
eThrust, // [RPM]
eNUM_VALUES
};
inline double& operator [](size_t idx) {
if (idx < eNUM_VALUES) {
return m_values[idx];
} else {
assert(!"Invalid index");
static double ERROR = 0.0;
return ERROR;
}
}
inline const double& operator [](size_t idx) const {
if (idx < eNUM_VALUES) {
return m_values[idx];
} else {
assert(!"Invalid index");
static const double ERROR = 0.0;
return ERROR;
}
}
//static:
static const char* SeriesName(size_t idx) {
if (idx < eNUM_VALUES) { return sSeriesNames[idx]; }
else { return "ERROR"; }
}
static const std::array<size_t, eNUM_VALUES> sSeriesPrecision;
private:
std::array<double, eNUM_VALUES> m_values;
//static
static const std::array<const char*, eNUM_VALUES> sSeriesNames;
};
|
#File treating all the prediction functions
const pred_nodes, pred_weights = (x -> (x[1] .* sqrt2, x[2] ./ sqrtπ))(gausshermite(100))
"""
predict_f(m::AbstractGP, X_test, cov::Bool=true, diag::Bool=true)
Compute the mean of the predicted latent distribution of `f` on `X_test` for the variational GP `model`
Return also the diagonal variance if `cov=true` and the full covariance if `diag=false`
"""
predict_f
function _predict_f(
m::GP{T}, X_test::AbstractVector; cov::Bool=true, diag::Bool=true
) where {T}
k_star = kernelmatrix(kernel(m.f), X_test, input(m))
μf = k_star * mean(m.f) # k * α
if !cov
return (μf,)
end
if !diag
k_starstar = kernelmatrix(kernel(m.f), X_test) + T(jitt) * I
covf = Symmetric(k_starstar - k_star' * (AGP.cov(m.f) \ k_star)) # k** - k* Σ⁻¹ k*
return μf, covf
else
k_starstar = kernelmatrix_diag(kernel(m.f), X_test) .+ T(jitt)
varf = k_starstar - diag_ABt(k_star / AGP.cov(m.f), k_star)
return μf, varf
end
end
@traitfn function _predict_f(
m::TGP, X_test::AbstractVector; cov::Bool=true, diag::Bool=true
) where {T,TGP<:AbstractGP{T};!IsMultiOutput{TGP}}
k_star = kernelmatrix.(kernels(m), [X_test], Zviews(m))
μf = k_star .* (pr_covs(m) .\ means(m))
if !cov
return (μf,)
end
A = pr_covs(m) .\ (Ref(I) .- covs(m) ./ pr_covs(m))
if !diag
k_starstar = kernelmatrix.(kernels(m), Ref(X_test)) .+ T(jitt) * [I]
Σf = Symmetric.(k_starstar .- k_star .* A .* transpose.(k_star))
return μf, Σf
else
k_starstar =
kernelmatrix_diag.(kernels(m), Ref(X_test)) .+
Ref(T(jitt) * ones(T, size(X_test, 1)))
σ²f = k_starstar .- diag_ABt.(k_star .* A, k_star)
return μf, σ²f
end
end
@traitfn function _predict_f(
m::TGP, X_test::AbstractVector; cov::Bool=true, diag::Bool=true
) where {T,TGP<:AbstractGP{T};IsMultiOutput{TGP}}
k_star = kernelmatrix(kernels(m), [X_test], Zviews(m))
μf = k_star .* (pr_covs(m) .\ means(m))
μf = [[sum(m.A[i][j] .* μf) for j in 1:m.nf_per_task[i]] for i in 1:nOutput(m)]
if !cov
return (μf,)
end
A = pr_covs(m) .\ ([I] .- covs(m) ./ pr_covs(m))
if !diag
k_starstar = (kernelmatrix.(kernels(m), [X_test]) .+ T(jitt) * [I])
Σf = k_starstar .- k_star .* A .* transpose.(k_star)
Σf = [[sum(m.A[i][j] .^ 2 .* Σf) for j in 1:m.nf_per_task[i]] for i in 1:nOutput(m)]
return μf, Σf
else
k_starstar =
kernelmatrix_diag.(kernels(m), [X_test]) .+ [T(jitt) * ones(T, length(X_test))]
σ²f = k_starstar .- diag_ABt.(k_star .* A, k_star)
σ²f = [
[sum(m.A[i][j] .^ 2 .* σ²f) for j in 1:m.nf_per_task[i]] for i in 1:nOutput(m)
]
return μf, σ²f
end
end
function _predict_f(
m::MCGP{T}, X_test::AbstractVector; cov::Bool=true, diag::Bool=true
) where {T}
k_star = kernelmatrix.(kernels(m), [X_test], Zviews(m))
f = _sample_f(m, X_test, k_star)
μf = mean.(f)
if !cov
return (μf,)
end
if !diag
k_starstar = kernelmatrix.(kernels(m), [X_test]) + T(jitt)
Σf = Symmetric.(k_starstar .- invquad.(pr_covs(m), k_star) .+ StatsBase.cov.(f))
return μf, Σf
else
k_starstar =
kernelmatrix_diag.(kernels(m), [X_test]) .+ [T(jitt) * ones(T, length(X_test))]
σ²f = k_starstar .- diag_ABt.(k_star ./ pr_covs(m), k_star) .+ StatsBase.var.(f)
return μf, σ²f
end
end
function _sample_f(
m::MCGP{T,<:AbstractLikelihood,<:GibbsSampling},
X_test::AbstractVector,
k_star=kernelmatrix.(kernels(m), [X_test], Zviews(m)),
) where {T}
return f = [
Ref(k_star[k] / pr_cov(m.f[k])) .* getindex.(inference(m).sample_store, k) for
k in 1:nLatent(m)
]
end
## Wrapper for vector input ##
function predict_f(
model::AbstractGP, X_test::AbstractVector{<:Real}; cov::Bool=false, diag::Bool=true
)
return predict_f(model, reshape(X_test, :, 1); cov=cov, diag=diag)
end
function predict_f(
model::AbstractGP,
X_test::AbstractMatrix;
cov::Bool=false,
diag::Bool=true,
obsdim::Int=1,
)
return predict_f(
model, KernelFunctions.vec_of_vecs(X_test; obsdim=obsdim); cov=cov, diag=diag
)
end
##
@traitfn function predict_f(
model::TGP, X_test::AbstractVector; cov::Bool=false, diag::Bool=true
) where {TGP; !IsMultiOutput{TGP}}
return first.(_predict_f(model, X_test; cov=cov, diag=diag))
end
@traitfn function predict_f(
model::TGP, X_test::AbstractVector; cov::Bool=false, diag::Bool=true
) where {TGP; IsMultiOutput{TGP}}
return _predict_f(model, X_test; cov=cov, diag=diag)
end
## Wrapper to predict vectors ##
function predict_y(model::AbstractGP, X_test::AbstractVector{<:Real})
return predict_y(model, reshape(X_test, :, 1))
end
function predict_y(model::AbstractGP, X_test::AbstractMatrix; obsdim::Int=1)
return predict_y(model, KernelFunctions.vec_of_vecs(X_test; obsdim=obsdim))
end
"""
predict_y(model::AbstractGP, X_test::AbstractVector)
predict_y(model::AbstractGP, X_test::AbstractMatrix; obsdim = 1)
Return
- the predictive mean of `X_test` for regression
- 0 or 1 of `X_test` for classification
- the most likely class for multi-class classification
- the expected number of events for an event likelihood
"""
@traitfn function predict_y(
model::TGP, X_test::AbstractVector
) where {TGP <: AbstractGP; !IsMultiOutput{TGP}}
return predict_y(likelihood(model), first(_predict_f(model, X_test; cov=false)))
end
@traitfn function predict_y(
model::TGP, X_test::AbstractVector
) where {TGP <: AbstractGP; IsMultiOutput{TGP}}
return predict_y.(likelihood(model), _predict_f(model, X_test; cov=false))
end
function predict_y(l::MultiClassLikelihood, μs::AbstractVector{<:AbstractVector{<:Real}})
return [l.class_mapping[argmax([μ[i] for μ in μs])] for i in 1:length(μs[1])]
end
function predict_y(
l::MultiClassLikelihood, μs::AbstractVector{<:AbstractVector{<:AbstractVector{<:Real}}}
)
return predict_y(l, first(μs))
end
predict_y(l::EventLikelihood, μ::AbstractVector{<:Real}) = expec_count(l, μ)
function predict_y(l::EventLikelihood, μ::AbstractVector{<:AbstractVector})
return expec_count(l, first(μ))
end
## Wrapper to return proba on vectors ##
function proba_y(model::AbstractGP, X_test::AbstractVector{<:Real})
return proba_y(model, reshape(X_test, :, 1))
end
function proba_y(model::AbstractGP, X_test::AbstractMatrix; obsdim::Int=1)
return proba_y(model, KernelFunctions.vec_of_vecs(X_test; obsdim=obsdim))
end
"""
proba_y(model::AbstractGP, X_test::AbstractVector)
proba_y(model::AbstractGP, X_test::AbstractMatrix; obsdim = 1)
Return the probability distribution p(y_test|model,X_test) :
- Tuple of vectors of mean and variance for regression
- Vector of probabilities of y_test = 1 for binary classification
- Dataframe with columns and probability per class for multi-class classification
"""
@traitfn function proba_y(
model::TGP, X_test::AbstractVector
) where {TGP <: AbstractGP; !IsMultiOutput{TGP}}
μ_f, Σ_f = _predict_f(model, X_test; cov=true)
return pred = compute_proba(model.likelihood, μ_f, Σ_f)
end
@traitfn function proba_y(
model::TGP, X_test::AbstractVector
) where {TGP <: AbstractGP; IsMultiOutput{TGP}}
return proba_multi_y(model, X_test)
end
function proba_multi_y(model::AbstractGP, X_test::AbstractVector)
μ_f, Σ_f = _predict_f(model, X_test; cov=true)
return preds = compute_proba.(likelihood(model), μ_f, Σ_f)
end
function compute_proba(
l::AbstractLikelihood,
μ::AbstractVector{<:AbstractVector},
σ²::AbstractVector{<:AbstractVector},
)
return compute_proba(l, first(μ), first(σ²))
end
function StatsBase.mean_and_var(lik::AbstractLikelihood, fs::AbstractMatrix)
vals = lik.(eachcol(fs))
return StatsBase.mean(vals), StatsBase.var(vals)
end
function proba_y(model::MCGP, X_test::AbstractVector{<:Real}; nSamples::Int=100)
return proba_y(model, reshape(X_test, :, 1); nSamples)
end
function proba_y(model::MCGP, X_test::AbstractMatrix; nSamples::Int=100, obsdim=1)
return proba_y(model, KernelFunctions.vec_of_vecs(X_test; obsdim); nSamples)
end
function proba_y(model::MCGP, X_test::AbstractVector; nSamples::Int=200)
nTest = length(X_test)
f = first(_sample_f(model, X_test))
return proba, sig_proba = mean_and_var(compute_proba_f.(likelihood(model), f))
end
function compute_proba_f(l::AbstractLikelihood, f::AbstractVector{<:Real})
return compute_proba.(l, f)
end
function compute_proba(
l::AbstractLikelihood, ::AbstractVector, ::AbstractVector
) where {T<:Real}
return error("Non implemented for the likelihood $l")
end
for f in [:predict_f, :predict_y, :proba_y]
end
|
Although a few Christian denominations follow the Judaic practice of observing the Sabbath on Saturday , Catholics , along with most Christians , observe Sunday as a special day , which they call the " Lord 's Day " . This practice dates to the first century , arising from their belief that Jesus rose from the dead on the first day of the week . The Didache calls on Christians to come together on the Lord 's Day to break bread and give thanks . Tertullian is the first to mention Sunday rest : " We , however ( just as tradition has taught us ) , on the day of the Lord 's Resurrection ought to guard not only against kneeling , but every posture and office of <unk> , deferring even our businesses lest we give any place to the devil " ( " De <unk> . " , xxiii ; cf . " Ad nation . " , I , xiii ; " <unk> . " , <unk> ) .
|
/-
Copyright (c) 2020 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton
! This file was ported from Lean 3 source module topology.tactic
! leanprover-community/mathlib commit ee05e9ce1322178f0c12004eb93c00d2c8c00ed2
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Tactic.AutoCases
import Mathbin.Tactic.Tidy
import Mathbin.Tactic.WithLocalReducibility
import Mathbin.Tactic.ShowTerm
import Mathbin.Topology.Basic
/-!
# Tactics for topology
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Currently we have one domain-specific tactic for topology: `continuity`.
-/
/-!
### `continuity` tactic
Automatically solve goals of the form `continuous f`.
Mark lemmas with `@[continuity]` to add them to the set of lemmas
used by `continuity`.
-/
/-- User attribute used to mark tactics used by `continuity`. -/
@[user_attribute]
unsafe def continuity : user_attribute
where
Name := `continuity
descr := "lemmas usable to prove continuity"
#align continuity continuity
-- Mark some continuity lemmas already defined in `topology.basic`
attribute [continuity] continuous_id continuous_const
#print continuous_id' /-
-- As we will be using `apply_rules` with `md := semireducible`,
-- we need another version of `continuous_id`.
@[continuity]
theorem continuous_id' {α : Type _} [TopologicalSpace α] : Continuous fun a : α => a :=
continuous_id
#align continuous_id' continuous_id'
-/
namespace Tactic
/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/
/-- Tactic to apply `continuous.comp` when appropriate.
Applying `continuous.comp` is not always a good idea, so we have some
extra logic here to try to avoid bad cases.
* If the function we're trying to prove continuous is actually
constant, and that constant is a function application `f z`, then
continuous.comp would produce new goals `continuous f`, `continuous
(λ _, z)`, which is silly. We avoid this by failing if we could
apply continuous_const.
* continuous.comp will always succeed on `continuous (λ x, f x)` and
produce new goals `continuous (λ x, x)`, `continuous f`. We detect
this by failing if a new goal can be closed by applying
continuous_id.
-/
unsafe def apply_continuous.comp : tactic Unit :=
sorry
#align tactic.apply_continuous.comp tactic.apply_continuous.comp
/-- List of tactics used by `continuity` internally. -/
unsafe def continuity_tactics (md : Transparency := reducible) : List (tactic String) :=
[intros1 >>= fun ns => pure ("intros " ++ " ".intercalate (ns.map fun e => e.toString)),
apply_rules [] [`` continuity] 50 { md } >> pure "apply_rules with continuity",
apply_continuous.comp >> pure "refine continuous.comp _ _"]
#align tactic.continuity_tactics tactic.continuity_tactics
namespace Interactive
/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/
/-- Solve goals of the form `continuous f`. `continuity?` reports back the proof term it found.
-/
unsafe def continuity (bang : parse <| optional (tk "!")) (trace : parse <| optional (tk "?"))
(cfg : tidy.cfg := { }) : tactic Unit :=
let md := if bang.isSome then semireducible else reducible
let continuity_core := tactic.tidy { cfg with tactics := continuity_tactics md }
let trace_fn := if trace.isSome then show_term else id
trace_fn continuity_core
#align tactic.interactive.continuity tactic.interactive.continuity
/-- Version of `continuity` for use with auto_param. -/
unsafe def continuity' : tactic Unit :=
continuity none none { }
#align tactic.interactive.continuity' tactic.interactive.continuity'
/-- `continuity` solves goals of the form `continuous f` by applying lemmas tagged with the
`continuity` user attribute.
```
example {X Y : Type*} [topological_space X] [topological_space Y]
(f₁ f₂ : X → Y) (hf₁ : continuous f₁) (hf₂ : continuous f₂)
(g : Y → ℝ) (hg : continuous g) : continuous (λ x, (max (g (f₁ x)) (g (f₂ x))) + 1) :=
by continuity
```
will discharge the goal, generating a proof term like
`((continuous.comp hg hf₁).max (continuous.comp hg hf₂)).add continuous_const`
You can also use `continuity!`, which applies lemmas with `{ md := semireducible }`.
The default behaviour is more conservative, and only unfolds `reducible` definitions
when attempting to match lemmas with the goal.
`continuity?` reports back the proof term it found.
-/
add_tactic_doc
{ Name := "continuity / continuity'"
category := DocCategory.tactic
declNames := [`tactic.interactive.continuity, `tactic.interactive.continuity']
tags := ["lemma application"] }
end Interactive
end Tactic
|
State Before: p n : ℕ
hn : n ≠ 0
⊢ Finset.image (fun x => p ^ x) (Finset.range (padicValNat p n + 1)) ⊆ divisors n State After: p n : ℕ
hn : n ≠ 0
t : ℕ
ht : t ∈ Finset.image (fun x => p ^ x) (Finset.range (padicValNat p n + 1))
⊢ t ∈ divisors n Tactic: intro t ht State Before: p n : ℕ
hn : n ≠ 0
t : ℕ
ht : t ∈ Finset.image (fun x => p ^ x) (Finset.range (padicValNat p n + 1))
⊢ t ∈ divisors n State After: p n : ℕ
hn : n ≠ 0
t : ℕ
ht : ∃ a, a < padicValNat p n + 1 ∧ p ^ a = t
⊢ t ∈ divisors n Tactic: simp only [exists_prop, Finset.mem_image, Finset.mem_range] at ht State Before: p n : ℕ
hn : n ≠ 0
t : ℕ
ht : ∃ a, a < padicValNat p n + 1 ∧ p ^ a = t
⊢ t ∈ divisors n State After: case intro.intro
p n : ℕ
hn : n ≠ 0
k : ℕ
hk : k < padicValNat p n + 1
⊢ p ^ k ∈ divisors n Tactic: obtain ⟨k, hk, rfl⟩ := ht State Before: case intro.intro
p n : ℕ
hn : n ≠ 0
k : ℕ
hk : k < padicValNat p n + 1
⊢ p ^ k ∈ divisors n State After: case intro.intro
p n : ℕ
hn : n ≠ 0
k : ℕ
hk : k < padicValNat p n + 1
⊢ p ^ k ∣ n ∧ n ≠ 0 Tactic: rw [Nat.mem_divisors] State Before: case intro.intro
p n : ℕ
hn : n ≠ 0
k : ℕ
hk : k < padicValNat p n + 1
⊢ p ^ k ∣ n ∧ n ≠ 0 State After: no goals Tactic: exact ⟨(pow_dvd_pow p <| by linarith).trans pow_padicValNat_dvd, hn⟩ State Before: p n : ℕ
hn : n ≠ 0
k : ℕ
hk : k < padicValNat p n + 1
⊢ k ≤ padicValNat p n State After: no goals Tactic: linarith |
open import Agda.Builtin.Unit
open import Agda.Builtin.List
open import Agda.Builtin.Reflection
id : ∀ {a} {A : Set a} → A → A
id x = x
macro
my-macro : Term → TC ⊤
my-macro goal = bindTC
(getType (quote id))
λ idType → bindTC
(reduce idType)
λ _ → returnTC _
fails? : ⊤
fails? = my-macro
|
/-
Copyright (c) 2021 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Sébastien Gouëzel
-/
import measure_theory.measure.lebesgue
import measure_theory.measure.haar
import linear_algebra.finite_dimensional
import analysis.normed_space.pointwise
import measure_theory.group.pointwise
/-!
# Relationship between the Haar and Lebesgue measures
We prove that the Haar measure and Lebesgue measure are equal on `ℝ` and on `ℝ^ι`, in
`measure_theory.add_haar_measure_eq_volume` and `measure_theory.add_haar_measure_eq_volume_pi`.
We deduce basic properties of any Haar measure on a finite dimensional real vector space:
* `map_linear_map_add_haar_eq_smul_add_haar`: a linear map rescales the Haar measure by the
absolute value of its determinant.
* `add_haar_preimage_linear_map` : when `f` is a linear map with nonzero determinant, the measure
of `f ⁻¹' s` is the measure of `s` multiplied by the absolute value of the inverse of the
determinant of `f`.
* `add_haar_image_linear_map` : when `f` is a linear map, the measure of `f '' s` is the
measure of `s` multiplied by the absolute value of the determinant of `f`.
* `add_haar_submodule` : a strict submodule has measure `0`.
* `add_haar_smul` : the measure of `r • s` is `|r| ^ dim * μ s`.
* `add_haar_ball`: the measure of `ball x r` is `r ^ dim * μ (ball 0 1)`.
* `add_haar_closed_ball`: the measure of `closed_ball x r` is `r ^ dim * μ (ball 0 1)`.
* `add_haar_sphere`: spheres have zero measure.
We also show that a Lebesgue density point `x` of a set `s` (with respect to closed balls) has
density one for the rescaled copies `{x} + r • t` of a given set `t` with positive measure, in
`tendsto_add_haar_inter_smul_one_of_density_one`. In particular, `s` intersects `{x} + r • t` for
small `r`, see `eventually_nonempty_inter_smul_of_density_one`.
-/
open topological_space set filter metric
open_locale ennreal pointwise topological_space
/-- The interval `[0,1]` as a compact set with non-empty interior. -/
def topological_space.positive_compacts.Icc01 : positive_compacts ℝ :=
⟨Icc 0 1, is_compact_Icc, by simp_rw [interior_Icc, nonempty_Ioo, zero_lt_one]⟩
universe u
/-- The set `[0,1]^ι` as a compact set with non-empty interior. -/
def topological_space.positive_compacts.pi_Icc01 (ι : Type*) [fintype ι] :
positive_compacts (ι → ℝ) :=
⟨set.pi set.univ (λ i, Icc 0 1), is_compact_univ_pi (λ i, is_compact_Icc),
by simp only [interior_pi_set, finite.of_fintype, interior_Icc, univ_pi_nonempty_iff, nonempty_Ioo,
implies_true_iff, zero_lt_one]⟩
namespace measure_theory
open measure topological_space.positive_compacts finite_dimensional
/-!
### The Lebesgue measure is a Haar measure on `ℝ` and on `ℝ^ι`.
-/
instance is_add_left_invariant_real_volume :
is_add_left_invariant (volume : measure ℝ) :=
⟨by simp [real.map_volume_add_left]⟩
/-- The Haar measure equals the Lebesgue measure on `ℝ`. -/
lemma add_haar_measure_eq_volume : add_haar_measure Icc01 = volume :=
by { convert (add_haar_measure_unique volume Icc01).symm, simp [Icc01] }
instance : is_add_haar_measure (volume : measure ℝ) :=
by { rw ← add_haar_measure_eq_volume, apply_instance }
instance is_add_left_invariant_real_volume_pi (ι : Type*) [fintype ι] :
is_add_left_invariant (volume : measure (ι → ℝ)) :=
⟨by simp [real.map_volume_pi_add_left]⟩
/-- The Haar measure equals the Lebesgue measure on `ℝ^ι`. -/
lemma add_haar_measure_eq_volume_pi (ι : Type*) [fintype ι] :
add_haar_measure (pi_Icc01 ι) = volume :=
begin
convert (add_haar_measure_unique volume (pi_Icc01 ι)).symm,
simp only [pi_Icc01, volume_pi_pi (λ i, Icc (0 : ℝ) 1),
finset.prod_const_one, ennreal.of_real_one, real.volume_Icc, one_smul, sub_zero]
end
instance is_add_haar_measure_volume_pi (ι : Type*) [fintype ι] :
is_add_haar_measure (volume : measure (ι → ℝ)) :=
by { rw ← add_haar_measure_eq_volume_pi, apply_instance }
namespace measure
/-!
### Strict subspaces have zero measure
-/
/-- If a set is disjoint of its translates by infinitely many bounded vectors, then it has measure
zero. This auxiliary lemma proves this assuming additionally that the set is bounded. -/
lemma add_haar_eq_zero_of_disjoint_translates_aux
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
{s : set E} (u : ℕ → E) (sb : bounded s) (hu : bounded (range u))
(hs : pairwise (disjoint on (λ n, {u n} + s))) (h's : measurable_set s) :
μ s = 0 :=
begin
by_contra h,
apply lt_irrefl ∞,
calc
∞ = ∑' (n : ℕ), μ s : (ennreal.tsum_const_eq_top_of_ne_zero h).symm
... = ∑' (n : ℕ), μ ({u n} + s) :
by { congr' 1, ext1 n, simp only [image_add_left, measure_preimage_add, singleton_add] }
... = μ (⋃ n, {u n} + s) :
by rw measure_Union hs
(λ n, by simpa only [image_add_left, singleton_add] using measurable_id.const_add _ h's)
... = μ (range u + s) : by rw [← Union_add, Union_singleton_eq_range]
... < ∞ : bounded.measure_lt_top (hu.add sb)
end
/-- If a set is disjoint of its translates by infinitely many bounded vectors, then it has measure
zero. -/
lemma add_haar_eq_zero_of_disjoint_translates
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
{s : set E} (u : ℕ → E) (hu : bounded (range u))
(hs : pairwise (disjoint on (λ n, {u n} + s))) (h's : measurable_set s) :
μ s = 0 :=
begin
suffices H : ∀ R, μ (s ∩ closed_ball 0 R) = 0,
{ apply le_antisymm _ (zero_le _),
calc μ s ≤ ∑' (n : ℕ), μ (s ∩ closed_ball 0 n) :
by { conv_lhs { rw ← Union_inter_closed_ball_nat s 0 }, exact measure_Union_le _ }
... = 0 : by simp only [H, tsum_zero] },
assume R,
apply add_haar_eq_zero_of_disjoint_translates_aux μ u
(bounded.mono (inter_subset_right _ _) bounded_closed_ball) hu _
(h's.inter (measurable_set_closed_ball)),
apply pairwise_disjoint.mono hs (λ n, _),
exact add_subset_add (subset.refl _) (inter_subset_left _ _)
end
/-- A strict vector subspace has measure zero. -/
lemma add_haar_submodule
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
(s : submodule ℝ E) (hs : s ≠ ⊤) : μ s = 0 :=
begin
obtain ⟨x, hx⟩ : ∃ x, x ∉ s,
by simpa only [submodule.eq_top_iff', not_exists, ne.def, not_forall] using hs,
obtain ⟨c, cpos, cone⟩ : ∃ (c : ℝ), 0 < c ∧ c < 1 := ⟨1/2, by norm_num, by norm_num⟩,
have A : bounded (range (λ (n : ℕ), (c ^ n) • x)),
{ have : tendsto (λ (n : ℕ), (c ^ n) • x) at_top (𝓝 ((0 : ℝ) • x)) :=
(tendsto_pow_at_top_nhds_0_of_lt_1 cpos.le cone).smul_const x,
exact bounded_range_of_tendsto _ this },
apply add_haar_eq_zero_of_disjoint_translates μ _ A _
(submodule.closed_of_finite_dimensional s).measurable_set,
assume m n hmn,
simp only [function.on_fun, image_add_left, singleton_add, disjoint_left, mem_preimage,
set_like.mem_coe],
assume y hym hyn,
have A : (c ^ n - c ^ m) • x ∈ s,
{ convert s.sub_mem hym hyn,
simp only [sub_smul, neg_sub_neg, add_sub_add_right_eq_sub] },
have H : c ^ n - c ^ m ≠ 0,
by simpa only [sub_eq_zero, ne.def] using (strict_anti_pow cpos cone).injective.ne hmn.symm,
have : x ∈ s,
{ convert s.smul_mem (c ^ n - c ^ m)⁻¹ A,
rw [smul_smul, inv_mul_cancel H, one_smul] },
exact hx this
end
/-!
### Applying a linear map rescales Haar measure by the determinant
We first prove this on `ι → ℝ`, using that this is already known for the product Lebesgue
measure (thanks to matrices computations). Then, we extend this to any finite-dimensional real
vector space by using a linear equiv with a space of the form `ι → ℝ`, and arguing that such a
linear equiv maps Haar measure to Haar measure.
-/
lemma map_linear_map_add_haar_pi_eq_smul_add_haar
{ι : Type*} [fintype ι] {f : (ι → ℝ) →ₗ[ℝ] (ι → ℝ)} (hf : f.det ≠ 0)
(μ : measure (ι → ℝ)) [is_add_haar_measure μ] :
measure.map f μ = ennreal.of_real (abs (f.det)⁻¹) • μ :=
begin
/- We have already proved the result for the Lebesgue product measure, using matrices.
We deduce it for any Haar measure by uniqueness (up to scalar multiplication). -/
have := add_haar_measure_unique μ (pi_Icc01 ι),
rw this,
simp [add_haar_measure_eq_volume_pi, real.map_linear_map_volume_pi_eq_smul_volume_pi hf,
smul_smul, mul_comm],
end
lemma map_linear_map_add_haar_eq_smul_add_haar
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
{f : E →ₗ[ℝ] E} (hf : f.det ≠ 0) :
measure.map f μ = ennreal.of_real (abs (f.det)⁻¹) • μ :=
begin
-- we reduce to the case of `E = ι → ℝ`, for which we have already proved the result using
-- matrices in `map_linear_map_add_haar_pi_eq_smul_add_haar`.
let ι := fin (finrank ℝ E),
haveI : finite_dimensional ℝ (ι → ℝ) := by apply_instance,
have : finrank ℝ E = finrank ℝ (ι → ℝ), by simp,
have e : E ≃ₗ[ℝ] ι → ℝ := linear_equiv.of_finrank_eq E (ι → ℝ) this,
-- next line is to avoid `g` getting reduced by `simp`.
obtain ⟨g, hg⟩ : ∃ g, g = (e : E →ₗ[ℝ] (ι → ℝ)).comp (f.comp (e.symm : (ι → ℝ) →ₗ[ℝ] E)) :=
⟨_, rfl⟩,
have gdet : g.det = f.det, by { rw [hg], exact linear_map.det_conj f e },
rw ← gdet at hf ⊢,
have fg : f = (e.symm : (ι → ℝ) →ₗ[ℝ] E).comp (g.comp (e : E →ₗ[ℝ] (ι → ℝ))),
{ ext x,
simp only [linear_equiv.coe_coe, function.comp_app, linear_map.coe_comp,
linear_equiv.symm_apply_apply, hg] },
simp only [fg, linear_equiv.coe_coe, linear_map.coe_comp],
have Ce : continuous e := (e : E →ₗ[ℝ] (ι → ℝ)).continuous_of_finite_dimensional,
have Cg : continuous g := linear_map.continuous_of_finite_dimensional g,
have Cesymm : continuous e.symm := (e.symm : (ι → ℝ) →ₗ[ℝ] E).continuous_of_finite_dimensional,
rw [← map_map Cesymm.measurable (Cg.comp Ce).measurable, ← map_map Cg.measurable Ce.measurable],
haveI : is_add_haar_measure (map e μ) := is_add_haar_measure_map μ e.to_add_equiv Ce Cesymm,
have ecomp : (e.symm) ∘ e = id,
by { ext x, simp only [id.def, function.comp_app, linear_equiv.symm_apply_apply] },
rw [map_linear_map_add_haar_pi_eq_smul_add_haar hf (map e μ), linear_map.map_smul,
map_map Cesymm.measurable Ce.measurable, ecomp, measure.map_id]
end
/-- The preimage of a set `s` under a linear map `f` with nonzero determinant has measure
equal to `μ s` times the absolute value of the inverse of the determinant of `f`. -/
@[simp] lemma add_haar_preimage_linear_map
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
{f : E →ₗ[ℝ] E} (hf : f.det ≠ 0) (s : set E) :
μ (f ⁻¹' s) = ennreal.of_real (abs (f.det)⁻¹) * μ s :=
calc μ (f ⁻¹' s) = measure.map f μ s :
((f.equiv_of_det_ne_zero hf).to_continuous_linear_equiv.to_homeomorph
.to_measurable_equiv.map_apply s).symm
... = ennreal.of_real (abs (f.det)⁻¹) * μ s :
by { rw map_linear_map_add_haar_eq_smul_add_haar μ hf, refl }
/-- The preimage of a set `s` under a continuous linear map `f` with nonzero determinant has measure
equal to `μ s` times the absolute value of the inverse of the determinant of `f`. -/
@[simp] lemma add_haar_preimage_continuous_linear_map
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
{f : E →L[ℝ] E} (hf : linear_map.det (f : E →ₗ[ℝ] E) ≠ 0) (s : set E) :
μ (f ⁻¹' s) = ennreal.of_real (abs (linear_map.det (f : E →ₗ[ℝ] E))⁻¹) * μ s :=
add_haar_preimage_linear_map μ hf s
/-- The preimage of a set `s` under a linear equiv `f` has measure
equal to `μ s` times the absolute value of the inverse of the determinant of `f`. -/
@[simp] lemma add_haar_preimage_linear_equiv
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
(f : E ≃ₗ[ℝ] E) (s : set E) :
μ (f ⁻¹' s) = ennreal.of_real (abs (f.symm : E →ₗ[ℝ] E).det) * μ s :=
begin
have A : (f : E →ₗ[ℝ] E).det ≠ 0 := (linear_equiv.is_unit_det' f).ne_zero,
convert add_haar_preimage_linear_map μ A s,
simp only [linear_equiv.det_coe_symm]
end
/-- The preimage of a set `s` under a continuous linear equiv `f` has measure
equal to `μ s` times the absolute value of the inverse of the determinant of `f`. -/
@[simp] lemma add_haar_preimage_continuous_linear_equiv
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
(f : E ≃L[ℝ] E) (s : set E) :
μ (f ⁻¹' s) = ennreal.of_real (abs (f.symm : E →ₗ[ℝ] E).det) * μ s :=
add_haar_preimage_linear_equiv μ _ s
/-- The image of a set `s` under a linear map `f` has measure
equal to `μ s` times the absolute value of the determinant of `f`. -/
@[simp] lemma add_haar_image_linear_map
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
(f : E →ₗ[ℝ] E) (s : set E) :
μ (f '' s) = ennreal.of_real (abs f.det) * μ s :=
begin
rcases ne_or_eq f.det 0 with hf|hf,
{ let g := (f.equiv_of_det_ne_zero hf).to_continuous_linear_equiv,
change μ (g '' s) = _,
rw [continuous_linear_equiv.image_eq_preimage g s, add_haar_preimage_continuous_linear_equiv],
congr,
ext x,
simp only [linear_equiv.coe_to_continuous_linear_equiv, linear_equiv.of_is_unit_det_apply,
linear_equiv.coe_coe, continuous_linear_equiv.symm_symm], },
{ simp only [hf, zero_mul, ennreal.of_real_zero, abs_zero],
have : μ f.range = 0 :=
add_haar_submodule μ _ (linear_map.range_lt_top_of_det_eq_zero hf).ne,
exact le_antisymm (le_trans (measure_mono (image_subset_range _ _)) this.le) (zero_le _) }
end
/-- The image of a set `s` under a continuous linear map `f` has measure
equal to `μ s` times the absolute value of the determinant of `f`. -/
@[simp] lemma add_haar_image_continuous_linear_map
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
(f : E →L[ℝ] E) (s : set E) :
μ (f '' s) = ennreal.of_real (abs (f : E →ₗ[ℝ] E).det) * μ s :=
add_haar_image_linear_map μ _ s
/-- The image of a set `s` under a continuous linear equiv `f` has measure
equal to `μ s` times the absolute value of the determinant of `f`. -/
@[simp] lemma add_haar_image_continuous_linear_equiv
{E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ]
(f : E ≃L[ℝ] E) (s : set E) :
μ (f '' s) = ennreal.of_real (abs (f : E →ₗ[ℝ] E).det) * μ s :=
add_haar_image_linear_map μ _ s
/-!
### Basic properties of Haar measures on real vector spaces
-/
variables {E : Type*} [normed_group E] [measurable_space E] [normed_space ℝ E]
[finite_dimensional ℝ E] [borel_space E] (μ : measure E) [is_add_haar_measure μ]
lemma map_add_haar_smul {r : ℝ} (hr : r ≠ 0) :
measure.map ((•) r) μ = ennreal.of_real (abs (r ^ (finrank ℝ E))⁻¹) • μ :=
begin
let f : E →ₗ[ℝ] E := r • 1,
change measure.map f μ = _,
have hf : f.det ≠ 0,
{ simp only [mul_one, linear_map.det_smul, ne.def, monoid_hom.map_one],
assume h,
exact hr (pow_eq_zero h) },
simp only [map_linear_map_add_haar_eq_smul_add_haar μ hf, mul_one, linear_map.det_smul,
monoid_hom.map_one],
end
@[simp] lemma add_haar_preimage_smul {r : ℝ} (hr : r ≠ 0) (s : set E) :
μ (((•) r) ⁻¹' s) = ennreal.of_real (abs (r ^ (finrank ℝ E))⁻¹) * μ s :=
calc μ (((•) r) ⁻¹' s) = measure.map ((•) r) μ s :
((homeomorph.smul (is_unit_iff_ne_zero.2 hr).unit).to_measurable_equiv.map_apply s).symm
... = ennreal.of_real (abs (r^(finrank ℝ E))⁻¹) * μ s : by { rw map_add_haar_smul μ hr, refl }
/-- Rescaling a set by a factor `r` multiplies its measure by `abs (r ^ dim)`. -/
@[simp] lemma add_haar_smul (r : ℝ) (s : set E) :
μ (r • s) = ennreal.of_real (abs (r ^ (finrank ℝ E))) * μ s :=
begin
rcases ne_or_eq r 0 with h|rfl,
{ rw [← preimage_smul_inv₀ h, add_haar_preimage_smul μ (inv_ne_zero h), inv_pow₀, inv_inv₀] },
rcases eq_empty_or_nonempty s with rfl|hs,
{ simp only [measure_empty, mul_zero, smul_set_empty] },
rw [zero_smul_set hs, ← singleton_zero],
by_cases h : finrank ℝ E = 0,
{ haveI : subsingleton E := finrank_zero_iff.1 h,
simp only [h, one_mul, ennreal.of_real_one, abs_one, subsingleton.eq_univ_of_nonempty hs,
pow_zero, subsingleton.eq_univ_of_nonempty (singleton_nonempty (0 : E))] },
{ haveI : nontrivial E := nontrivial_of_finrank_pos (bot_lt_iff_ne_bot.2 h),
simp only [h, zero_mul, ennreal.of_real_zero, abs_zero, ne.def, not_false_iff, zero_pow',
measure_singleton] }
end
/-! We don't need to state `map_add_haar_neg` here, because it has already been proved for
general Haar measures on general commutative groups. -/
/-! ### Measure of balls -/
lemma add_haar_ball_center
{E : Type*} [normed_group E] [measurable_space E]
[borel_space E] (μ : measure E) [is_add_haar_measure μ] (x : E) (r : ℝ) :
μ (ball x r) = μ (ball (0 : E) r) :=
begin
have : ball (0 : E) r = ((+) x) ⁻¹' (ball x r), by simp [preimage_add_ball],
rw [this, measure_preimage_add]
end
lemma add_haar_closed_ball_center
{E : Type*} [normed_group E] [measurable_space E]
[borel_space E] (μ : measure E) [is_add_haar_measure μ] (x : E) (r : ℝ) :
μ (closed_ball x r) = μ (closed_ball (0 : E) r) :=
begin
have : closed_ball (0 : E) r = ((+) x) ⁻¹' (closed_ball x r), by simp [preimage_add_closed_ball],
rw [this, measure_preimage_add]
end
lemma add_haar_ball_mul_of_pos (x : E) {r : ℝ} (hr : 0 < r) (s : ℝ) :
μ (ball x (r * s)) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 s) :=
begin
have : ball (0 : E) (r * s) = r • ball 0 s,
by simp only [smul_ball hr.ne' (0 : E) s, real.norm_eq_abs, abs_of_nonneg hr.le, smul_zero],
simp only [this, add_haar_smul, abs_of_nonneg hr.le, add_haar_ball_center, abs_pow],
end
lemma add_haar_ball_of_pos (x : E) {r : ℝ} (hr : 0 < r) :
μ (ball x r) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 1) :=
by rw [← add_haar_ball_mul_of_pos μ x hr, mul_one]
lemma add_haar_ball_mul [nontrivial E] (x : E) {r : ℝ} (hr : 0 ≤ r) (s : ℝ) :
μ (ball x (r * s)) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 s) :=
begin
rcases has_le.le.eq_or_lt hr with h|h,
{ simp only [← h, zero_pow finrank_pos, measure_empty, zero_mul, ennreal.of_real_zero,
ball_zero] },
{ exact add_haar_ball_mul_of_pos μ x h s }
end
lemma add_haar_ball [nontrivial E] (x : E) {r : ℝ} (hr : 0 ≤ r) :
μ (ball x r) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 1) :=
by rw [← add_haar_ball_mul μ x hr, mul_one]
lemma add_haar_closed_ball_mul_of_pos (x : E) {r : ℝ} (hr : 0 < r) (s : ℝ) :
μ (closed_ball x (r * s)) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (closed_ball 0 s) :=
begin
have : closed_ball (0 : E) (r * s) = r • closed_ball 0 s,
by simp [smul_closed_ball' hr.ne' (0 : E), real.norm_eq_abs, abs_of_nonneg hr.le],
simp only [this, add_haar_smul, abs_of_nonneg hr.le, add_haar_closed_ball_center, abs_pow],
end
lemma add_haar_closed_ball_mul (x : E) {r : ℝ} (hr : 0 ≤ r) {s : ℝ} (hs : 0 ≤ s) :
μ (closed_ball x (r * s)) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (closed_ball 0 s) :=
begin
have : closed_ball (0 : E) (r * s) = r • closed_ball 0 s,
by simp [smul_closed_ball r (0 : E) hs, real.norm_eq_abs, abs_of_nonneg hr],
simp only [this, add_haar_smul, abs_of_nonneg hr, add_haar_closed_ball_center, abs_pow],
end
/-- The measure of a closed ball can be expressed in terms of the measure of the closed unit ball.
Use instead `add_haar_closed_ball`, which uses the measure of the open unit ball as a standard
form. -/
lemma add_haar_closed_unit_ball_eq_add_haar_unit_ball :
μ (closed_ball (0 : E) 1) = μ (ball 0 1) :=
begin
apply le_antisymm _ (measure_mono ball_subset_closed_ball),
have A : tendsto (λ (r : ℝ), ennreal.of_real (r ^ (finrank ℝ E)) * μ (closed_ball (0 : E) 1))
(𝓝[<] 1) (𝓝 (ennreal.of_real (1 ^ (finrank ℝ E)) * μ (closed_ball (0 : E) 1))),
{ refine ennreal.tendsto.mul _ (by simp) tendsto_const_nhds (by simp),
exact ennreal.tendsto_of_real ((tendsto_id' nhds_within_le_nhds).pow _) },
simp only [one_pow, one_mul, ennreal.of_real_one] at A,
refine le_of_tendsto A _,
refine mem_nhds_within_Iio_iff_exists_Ioo_subset.2 ⟨(0 : ℝ), by simp, λ r hr, _⟩,
dsimp,
rw ← add_haar_closed_ball' μ (0 : E) hr.1.le,
exact measure_mono (closed_ball_subset_ball hr.2)
end
lemma add_haar_closed_ball (x : E) {r : ℝ} (hr : 0 ≤ r) :
μ (closed_ball x r) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 1) :=
by rw [add_haar_closed_ball' μ x hr, add_haar_closed_unit_ball_eq_add_haar_unit_ball]
lemma add_haar_sphere_of_ne_zero (x : E) {r : ℝ} (hr : r ≠ 0) :
μ (sphere x r) = 0 :=
begin
rcases hr.lt_or_lt with h|h,
{ simp only [empty_diff, measure_empty, ← closed_ball_diff_ball, closed_ball_eq_empty.2 h] },
{ rw [← closed_ball_diff_ball,
measure_diff ball_subset_closed_ball measurable_set_ball measure_ball_lt_top.ne,
add_haar_ball_of_pos μ _ h, add_haar_closed_ball μ _ h.le, tsub_self];
apply_instance }
end
lemma add_haar_sphere [nontrivial E] (x : E) (r : ℝ) :
μ (sphere x r) = 0 :=
begin
rcases eq_or_ne r 0 with rfl|h,
{ rw [sphere_zero, measure_singleton] },
{ exact add_haar_sphere_of_ne_zero μ x h }
end
lemma add_haar_singleton_add_smul_div_singleton_add_smul
{r : ℝ} (hr : r ≠ 0) (x y : E) (s t : set E) :
μ ({x} + r • s) / μ ({y} + r • t) = μ s / μ t :=
calc
μ ({x} + r • s) / μ ({y} + r • t)
= ennreal.of_real (|r| ^ finrank ℝ E) * μ s * (ennreal.of_real (|r| ^ finrank ℝ E) * μ t)⁻¹ :
by simp only [div_eq_mul_inv, add_haar_smul, image_add_left, measure_preimage_add, abs_pow,
singleton_add]
... = ennreal.of_real (|r| ^ finrank ℝ E) * (ennreal.of_real (|r| ^ finrank ℝ E))⁻¹ *
(μ s * (μ t)⁻¹) :
begin
rw ennreal.mul_inv,
{ ring },
{ simp only [pow_pos (abs_pos.mpr hr), ennreal.of_real_eq_zero, not_le, ne.def, true_or] },
{ simp only [ennreal.of_real_ne_top, true_or, ne.def, not_false_iff] },
end
... = μ s / μ t :
begin
rw [ennreal.mul_inv_cancel, one_mul, div_eq_mul_inv],
{ simp only [pow_pos (abs_pos.mpr hr), ennreal.of_real_eq_zero, not_le, ne.def], },
{ simp only [ennreal.of_real_ne_top, ne.def, not_false_iff] }
end
/-!
### Density points
Besicovitch covering theorem ensures that, for any locally finite measure on a finite-dimensional
real vector space, almost every point of a set `s` is a density point, i.e.,
`μ (s ∩ closed_ball x r) / μ (closed_ball x r)` tends to `1` as `r` tends to `0`
(see `besicovitch.ae_tendsto_measure_inter_div`).
When `μ` is a Haar measure, one can deduce the same property for any rescaling sequence of sets,
of the form `{x} + r • t` where `t` is a set with positive finite measure, instead of the sequence
of closed balls.
We argue first for the dual property, i.e., if `s` has density `0` at `x`, then
`μ (s ∩ ({x} + r • t)) / μ ({x} + r • t)` tends to `0`. First when `t` is contained in the ball
of radius `1`, in `tendsto_add_haar_inter_smul_zero_of_density_zero_aux1`,
(by arguing by inclusion). Then when `t` is bounded, reducing to the previous one by rescaling, in
`tendsto_add_haar_inter_smul_zero_of_density_zero_aux2`.
Then for a general set `t`, by cutting it into a bounded part and a part with small measure, in
`tendsto_add_haar_inter_smul_zero_of_density_zero`.
Going to the complement, one obtains the desired property at points of density `1`, first when
`s` is measurable in `tendsto_add_haar_inter_smul_one_of_density_one_aux`, and then without this
assumption in `tendsto_add_haar_inter_smul_one_of_density_one` by applying the previous lemma to
the measurable hull `to_measurable μ s`
-/
lemma tendsto_add_haar_inter_smul_zero_of_density_zero_aux1
(s : set E) (x : E)
(h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0))
(t : set E) (u : set E) (h'u : μ u ≠ 0) (t_bound : t ⊆ closed_ball 0 1) :
tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • u)) (𝓝[>] 0) (𝓝 0) :=
begin
have A : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0),
{ apply tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds h
(eventually_of_forall (λ b, zero_le _)),
filter_upwards [self_mem_nhds_within],
rintros r (rpos : 0 < r),
apply ennreal.mul_le_mul (measure_mono (inter_subset_inter_right _ _)) le_rfl,
assume y hy,
have : y - x ∈ r • closed_ball (0 : E) 1,
{ apply smul_set_mono t_bound,
simpa [neg_add_eq_sub] using hy },
simpa only [smul_closed_ball _ _ zero_le_one, real.norm_of_nonneg rpos.le,
mem_closed_ball_iff_norm, mul_one, sub_zero, smul_zero] },
have B : tendsto (λ (r : ℝ), μ (closed_ball x r) / μ ({x} + r • u)) (𝓝[>] 0)
(𝓝 (μ (closed_ball x 1) / μ ({x} + u))),
{ apply tendsto_const_nhds.congr' _,
filter_upwards [self_mem_nhds_within],
rintros r (rpos : 0 < r),
have : closed_ball x r = {x} + r • closed_ball 0 1,
by simp only [smul_closed_ball, real.norm_of_nonneg rpos.le, zero_le_one, add_zero, mul_one,
singleton_add_closed_ball, smul_zero],
simp only [this, add_haar_singleton_add_smul_div_singleton_add_smul μ rpos.ne'],
simp only [add_haar_closed_ball_center, image_add_left, measure_preimage_add, singleton_add] },
have C : tendsto (λ (r : ℝ),
(μ (s ∩ ({x} + r • t)) / μ (closed_ball x r)) * (μ (closed_ball x r) / μ ({x} + r • u)))
(𝓝[>] 0) (𝓝 (0 * (μ (closed_ball x 1) / μ ({x} + u)))),
{ apply ennreal.tendsto.mul A _ B (or.inr ennreal.zero_ne_top),
simp only [ennreal.div_eq_top, h'u, measure_closed_ball_lt_top.ne, false_or, image_add_left,
eq_self_iff_true, not_true, ne.def, not_false_iff, measure_preimage_add, singleton_add,
and_false, false_and] },
simp only [zero_mul] at C,
apply C.congr' _,
filter_upwards [self_mem_nhds_within],
rintros r (rpos : 0 < r),
calc μ (s ∩ ({x} + r • t)) / μ (closed_ball x r) * (μ (closed_ball x r) / μ ({x} + r • u))
= (μ (closed_ball x r) * (μ (closed_ball x r))⁻¹) * (μ (s ∩ ({x} + r • t)) / μ ({x} + r • u)) :
by { simp only [div_eq_mul_inv], ring }
... = μ (s ∩ ({x} + r • t)) / μ ({x} + r • u) :
by rw [ennreal.mul_inv_cancel (measure_closed_ball_pos μ x rpos).ne'
measure_closed_ball_lt_top.ne, one_mul],
end
lemma tendsto_add_haar_inter_smul_zero_of_density_zero_aux2
(s : set E) (x : E)
(h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0))
(t : set E) (u : set E) (h'u : μ u ≠ 0)
(R : ℝ) (Rpos : 0 < R) (t_bound : t ⊆ closed_ball 0 R) :
tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • u)) (𝓝[>] 0) (𝓝 0) :=
begin
set t' := R⁻¹ • t with ht',
set u' := R⁻¹ • u with hu',
have A : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t')) / μ ({x} + r • u')) (𝓝[>] 0) (𝓝 0),
{ apply tendsto_add_haar_inter_smul_zero_of_density_zero_aux1 μ s x h
t' u',
{ simp only [h'u, (pow_pos Rpos _).ne', abs_nonpos_iff, add_haar_smul, not_false_iff,
ennreal.of_real_eq_zero, inv_eq_zero, inv_pow₀, ne.def, or_self, mul_eq_zero] },
{ convert smul_set_mono t_bound,
rw [smul_closed_ball _ _ Rpos.le, smul_zero, real.norm_of_nonneg (inv_nonneg.2 Rpos.le),
inv_mul_cancel Rpos.ne'] } },
have B : tendsto (λ (r : ℝ), R * r) (𝓝[>] 0) (𝓝[>] (R * 0)),
{ apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within,
{ exact (tendsto_const_nhds.mul tendsto_id).mono_left nhds_within_le_nhds },
{ filter_upwards [self_mem_nhds_within],
assume r rpos,
rw mul_zero,
exact mul_pos Rpos rpos } },
rw mul_zero at B,
apply (A.comp B).congr' _,
filter_upwards [self_mem_nhds_within],
rintros r (rpos : 0 < r),
have T : (R * r) • t' = r • t,
by rw [mul_comm, ht', smul_smul, mul_assoc, mul_inv_cancel Rpos.ne', mul_one],
have U : (R * r) • u' = r • u,
by rw [mul_comm, hu', smul_smul, mul_assoc, mul_inv_cancel Rpos.ne', mul_one],
dsimp,
rw [T, U],
end
/-- Consider a point `x` at which a set `s` has density zero, with respect to closed balls. Then it
also has density zero with respect to any measurable set `t`: the proportion of points in `s`
belonging to a rescaled copy `{x} + r • t` of `t` tends to zero as `r` tends to zero. -/
lemma tendsto_add_haar_inter_smul_zero_of_density_zero
(s : set E) (x : E)
(h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0))
(t : set E) (ht : measurable_set t) (h''t : μ t ≠ ∞) :
tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 0) :=
begin
refine tendsto_order.2 ⟨λ a' ha', (ennreal.not_lt_zero ha').elim, λ ε (εpos : 0 < ε), _⟩,
rcases eq_or_ne (μ t) 0 with h't|h't,
{ apply eventually_of_forall (λ r, _),
suffices H : μ (s ∩ ({x} + r • t)) = 0,
by { rw H, simpa only [ennreal.zero_div] using εpos },
apply le_antisymm _ (zero_le _),
calc μ (s ∩ ({x} + r • t)) ≤ μ ({x} + r • t) : measure_mono (inter_subset_right _ _)
... = 0 : by simp only [h't, add_haar_smul, image_add_left, measure_preimage_add,
singleton_add, mul_zero] },
obtain ⟨n, npos, hn⟩ : ∃ (n : ℕ), 0 < n ∧ μ (t \ closed_ball 0 n) < (ε / 2) * μ t,
{ have A : tendsto (λ (n : ℕ), μ (t \ closed_ball 0 n)) at_top
(𝓝 (μ (⋂ (n : ℕ), t \ closed_ball 0 n))),
{ have N : ∃ (n : ℕ), μ (t \ closed_ball 0 n) ≠ ∞ :=
⟨0, ((measure_mono (diff_subset t _)).trans_lt h''t.lt_top).ne⟩,
refine tendsto_measure_Inter (λ n, ht.diff measurable_set_closed_ball) (λ m n hmn, _) N,
exact diff_subset_diff subset.rfl (closed_ball_subset_closed_ball (nat.cast_le.2 hmn)) },
have : (⋂ (n : ℕ), t \ closed_ball 0 n) = ∅,
by simp_rw [diff_eq, ← inter_Inter, Inter_eq_compl_Union_compl, compl_compl,
Union_closed_ball_nat, compl_univ, inter_empty],
simp only [this, measure_empty] at A,
have I : 0 < (ε / 2) * μ t := ennreal.mul_pos (ennreal.half_pos εpos.ne').ne' h't,
exact (eventually.and (Ioi_mem_at_top 0) ((tendsto_order.1 A).2 _ I)).exists },
have L : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) / μ ({x} + r • t))
(𝓝[>] 0) (𝓝 0) :=
tendsto_add_haar_inter_smul_zero_of_density_zero_aux2 μ s x h
_ t h't n (nat.cast_pos.2 npos) (inter_subset_right _ _),
filter_upwards [(tendsto_order.1 L).2 _ (ennreal.half_pos εpos.ne'), self_mem_nhds_within],
rintros r hr (rpos : 0 < r),
have I : μ (s ∩ ({x} + r • t)) ≤
μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) + μ ({x} + r • (t \ closed_ball 0 n)) := calc
μ (s ∩ ({x} + r • t))
= μ ((s ∩ ({x} + r • (t ∩ closed_ball 0 n))) ∪ (s ∩ ({x} + r • (t \ closed_ball 0 n)))) :
by rw [← inter_union_distrib_left, ← add_union, ← smul_set_union, inter_union_diff]
... ≤ μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) + μ (s ∩ ({x} + r • (t \ closed_ball 0 n))) :
measure_union_le _ _
... ≤ μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) + μ ({x} + r • (t \ closed_ball 0 n)) :
add_le_add le_rfl (measure_mono (inter_subset_right _ _)),
calc μ (s ∩ ({x} + r • t)) / μ ({x} + r • t)
≤ (μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) + μ ({x} + r • (t \ closed_ball 0 n))) /
μ ({x} + r • t) : ennreal.mul_le_mul I le_rfl
... < ε / 2 + ε / 2 :
begin
rw ennreal.add_div,
apply ennreal.add_lt_add hr _,
rwa [add_haar_singleton_add_smul_div_singleton_add_smul μ rpos.ne',
ennreal.div_lt_iff (or.inl h't) (or.inl h''t)],
end
... = ε : ennreal.add_halves _
end
lemma tendsto_add_haar_inter_smul_one_of_density_one_aux
(s : set E) (hs : measurable_set s) (x : E)
(h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1))
(t : set E) (ht : measurable_set t) (h't : μ t ≠ 0) (h''t : μ t ≠ ∞) :
tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 1) :=
begin
have I : ∀ u v, μ u ≠ 0 → μ u ≠ ∞ → measurable_set v →
μ u / μ u - μ (vᶜ ∩ u) / μ u = μ (v ∩ u) / μ u,
{ assume u v uzero utop vmeas,
simp_rw [div_eq_mul_inv],
rw ← ennreal.sub_mul, swap,
{ simp only [uzero, ennreal.inv_eq_top, implies_true_iff, ne.def, not_false_iff] },
congr' 1,
apply ennreal.sub_eq_of_add_eq
(ne_top_of_le_ne_top utop (measure_mono (inter_subset_right _ _))),
rw [inter_comm _ u, inter_comm _ u],
exact measure_inter_add_diff u vmeas },
have L : tendsto (λ r, μ (sᶜ ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0),
{ have A : tendsto (λ r, μ (closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1),
{ apply tendsto_const_nhds.congr' _,
filter_upwards [self_mem_nhds_within],
assume r hr,
rw [div_eq_mul_inv, ennreal.mul_inv_cancel],
{ exact (measure_closed_ball_pos μ _ hr).ne' },
{ exact measure_closed_ball_lt_top.ne } },
have B := ennreal.tendsto.sub A h (or.inl ennreal.one_ne_top),
simp only [tsub_self] at B,
apply B.congr' _,
filter_upwards [self_mem_nhds_within],
rintros r (rpos : 0 < r),
convert I (closed_ball x r) sᶜ (measure_closed_ball_pos μ _ rpos).ne'
(measure_closed_ball_lt_top).ne hs.compl,
rw compl_compl },
have L' : tendsto (λ (r : ℝ), μ (sᶜ ∩ ({x} + r • t)) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 0) :=
tendsto_add_haar_inter_smul_zero_of_density_zero μ sᶜ x L t ht h''t,
have L'' : tendsto (λ (r : ℝ), μ ({x} + r • t) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 1),
{ apply tendsto_const_nhds.congr' _,
filter_upwards [self_mem_nhds_within],
rintros r (rpos : 0 < r),
rw [add_haar_singleton_add_smul_div_singleton_add_smul μ rpos.ne', ennreal.div_self h't h''t] },
have := ennreal.tendsto.sub L'' L' (or.inl ennreal.one_ne_top),
simp only [tsub_zero] at this,
apply this.congr' _,
filter_upwards [self_mem_nhds_within],
rintros r (rpos : 0 < r),
refine I ({x} + r • t) s _ _ hs,
{ simp only [h't, abs_of_nonneg rpos.le, pow_pos rpos, add_haar_smul, image_add_left,
ennreal.of_real_eq_zero, not_le, or_false, ne.def, measure_preimage_add, abs_pow,
singleton_add, mul_eq_zero] },
{ simp only [h''t, ennreal.of_real_ne_top, add_haar_smul, image_add_left, with_top.mul_eq_top_iff,
ne.def, not_false_iff, measure_preimage_add, singleton_add, and_false, false_and, or_self] }
end
/-- Consider a point `x` at which a set `s` has density one, with respect to closed balls (i.e.,
a Lebesgue density point of `s`). Then `s` has also density one at `x` with respect to any
measurable set `t`: the proportion of points in `s` belonging to a rescaled copy `{x} + r • t`
of `t` tends to one as `r` tends to zero. -/
lemma tendsto_add_haar_inter_smul_one_of_density_one
(s : set E) (x : E)
(h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1))
(t : set E) (ht : measurable_set t) (h't : μ t ≠ 0) (h''t : μ t ≠ ∞) :
tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 1) :=
begin
have : tendsto (λ (r : ℝ), μ (to_measurable μ s ∩ ({x} + r • t)) / μ ({x} + r • t))
(𝓝[>] 0) (𝓝 1),
{ apply tendsto_add_haar_inter_smul_one_of_density_one_aux μ _
(measurable_set_to_measurable _ _) _ _ t ht h't h''t,
apply tendsto_of_tendsto_of_tendsto_of_le_of_le' h tendsto_const_nhds,
{ apply eventually_of_forall (λ r, _),
apply ennreal.mul_le_mul _ le_rfl,
exact measure_mono (inter_subset_inter_left _ (subset_to_measurable _ _)) },
{ filter_upwards [self_mem_nhds_within],
rintros r (rpos : 0 < r),
apply ennreal.div_le_of_le_mul,
rw one_mul,
exact measure_mono (inter_subset_right _ _) } },
apply this.congr (λ r, _),
congr' 1,
apply measure_to_measurable_inter_of_sigma_finite,
simp only [image_add_left, singleton_add],
apply (continuous_add_left (-x)).measurable (ht.const_smul₀ r)
end
/-- Consider a point `x` at which a set `s` has density one, with respect to closed balls (i.e.,
a Lebesgue density point of `s`). Then `s` intersects the rescaled copies `{x} + r • t` of a given
set `t` with positive measure, for any small enough `r`. -/
lemma eventually_nonempty_inter_smul_of_density_one (s : set E) (x : E)
(h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1))
(t : set E) (ht : measurable_set t) (h't : μ t ≠ 0) :
∀ᶠ r in 𝓝[>] (0 : ℝ), (s ∩ ({x} + r • t)).nonempty :=
begin
obtain ⟨t', t'_meas, t't, t'pos, t'top⟩ :
∃ t', measurable_set t' ∧ t' ⊆ t ∧ 0 < μ t' ∧ μ t' < ⊤ :=
exists_subset_measure_lt_top ht h't.bot_lt,
filter_upwards [(tendsto_order.1
(tendsto_add_haar_inter_smul_one_of_density_one μ s x h t'
t'_meas t'pos.ne' t'top.ne)).1 0 ennreal.zero_lt_one],
assume r hr,
have : μ (s ∩ ({x} + r • t')) ≠ 0 :=
λ h', by simpa only [ennreal.not_lt_zero, ennreal.zero_div, h'] using hr,
have : (s ∩ ({x} + r • t')).nonempty := nonempty_of_measure_ne_zero this,
apply this.mono (inter_subset_inter subset.rfl _),
exact add_subset_add subset.rfl (smul_set_mono t't),
end
end measure
end measure_theory
|
# function to parse the time-series data from the given folder and output a dictionary
# implementing the data into the original RTS_GMLC network.
#
# function parameters:
######################################################################################
# month_st: the month to start
# day_st: the day to start
# period_st: the hour to start
# month_en: the month that ends parsing
# day_en: the month that ends parsing
# period_en: the month that ends parsing (here the periods need to be chosen corresponding to the data set use in the future)
# folder: the folder containing the time-sereis data and subnetworks.csv(For example I set it to be time_series)
function hour_parse(month_st, day_st, period_st, month_en, day_en, period_en, folder)
# set the time range
start_t = DateTime(2020,month_st,day_st,period_st)
end_t = DateTime(2020,month_en,day_en,period_en)
range_t = start_t:Hour(1):end_t
# direct to the current directory
# println("$(@__DIR__)")
cur_dir_split = split(rstrip(folder, '/'), "/")
cur_dir_split = cur_dir_split[cur_dir_split .!= ""]
cur_dir_new = cur_dir_split[1:end-3]
# cur_dir = join([("$i/") for i in cur_dir_new])
cur_dir = pwd()
# for the base structure of network, parse all the subnetwork files
subnet_file = CSV.read("$(folder)/subnetworks.csv", DataFrame)
subnet_file_1 = subnet_file[!, "file"][1]
case = Dict()
for subnet in eachrow(subnet_file)
case[subnet.file] = parse_file("$(folder)/$(subnet.file)")
end
# Set the generator minimum active power limits to zero for surrent stage (release the constraints)
for (subnet_file, subnet) in case
for (gen_idx, gen) in subnet["gen"]
gen["pmin"] = 0
end
end
# read the time-series data from the folder
hour_csp_ori = CSV.read("$(cur_dir)/time_series/CSP/DAY_AHEAD_Natural_Inflow.csv", DataFrame)
hour_hydro_ori = CSV.read("$(cur_dir)/time_series/Hydro/DAY_AHEAD_hydro.csv", DataFrame)
hour_load_ori = CSV.read("$(cur_dir)/time_series/Load/DAY_AHEAD_regional_Load.csv", DataFrame)
hour_pv_ori = CSV.read("$(cur_dir)/time_series/PV/DAY_AHEAD_pv.csv", DataFrame)
# here didn't include reserve data for now (now optimizations on different time steps are independent)
hour_rtpv_ori = CSV.read("$(cur_dir)/time_series/RTPV/DAY_AHEAD_rtpv.csv", DataFrame)
hour_wind_ori = CSV.read("$(cur_dir)/time_series/WIND/DAY_AHEAD_wind.csv", DataFrame)
hour_wind = filter(row -> DateTime(row.Year, row.Month, row.Day, row.Period) in range_t, hour_wind_ori)
hour_pv = filter(row -> DateTime(row.Year, row.Month, row.Day, row.Period) in range_t, hour_pv_ori)
hour_csp = filter(row -> DateTime(row.Year, row.Month, row.Day, row.Period) in range_t, hour_csp_ori)
hour_rtpv = filter(row -> DateTime(row.Year, row.Month, row.Day, row.Period) in range_t, hour_rtpv_ori)
hour_load = filter(row -> DateTime(row.Year, row.Month, row.Day, row.Period) in range_t, hour_load_ori)
hour_hydro = filter(row -> DateTime(row.Year, row.Month, row.Day, row.Period) in range_t, hour_hydro_ori)
wind_names = names(hour_wind)[5:end]
pv_names = names(hour_pv)[5:end]
csp_names = names(hour_csp)[5:end]
rtpv_names = names(hour_rtpv)[5:end]
#load_names = names(hour_load)[5:end]
hydro_names = names(hour_hydro)[5:end]
#input_csp = filter()
# set the load in the three areas
total_load = Dict(1=>0.0, 2=>0.0, 3=>0.0)
for (id, load) in case[subnet_file_1]["load"]
bus= case[subnet_file_1]["bus"]["$(load["load_bus"])"]
total_load[bus["area"]] += load["pd"]*case[subnet_file_1]["baseMVA"]
end
hour_data = Dict()
# made a copy of original network at each time step and make modifications using time-series data.
for i in 1:size(hour_load, 1)
load_data = hour_load[i,:]
for subnet in eachrow(subnet_file)
# file name and index of current subnetwork file
name = subnet.file
hour_data[i] = deepcopy(case)
hour_data[i][name]["year"] = load_data.Year
hour_data[i][name]["month"] = load_data.Month
hour_data[i][name]["day"] = load_data.Day
hour_data[i][name]["period"] = load_data.Period
end
hour_data[i][subnet_file_1]["ori_load"] = Dict(1=>load_data[Symbol(1)], 2=>load_data[Symbol(2)], 3=>load_data[Symbol(3)]) end
# here distribute the power over the 3 areas
for (id, name) in hour_data
#for (ind, network) in name
for (load_id, load) in name[subnet_file_1]["load"]
#if haskey(network, "ori_load")
area = name[subnet_file_1]["bus"]["$(load["load_bus"])"]["area"]
scale = name[subnet_file_1]["ori_load"][area]/total_load[area]
load["pd"] = load["pd"]*scale
load["qd"] = load["qd"]*scale
#end
end
#end
end
# here change all the data of the points according to time-serires data of PV,
for (id, name) in hour_data
#for (ind, network) in name
for (gen_id, gen) in name[subnet_file_1]["gen"]
#for subnet in eachrow(subnet_file)
#if haskey(gen, "name")
if gen["name"] in wind_names
gen["pmax"] = hour_wind[id, gen["name"]]/case[subnet_file_1]["baseMVA"]
end
if gen["name"] in pv_names
gen["pmax"] = hour_pv[id, gen["name"]]/case[subnet_file_1]["baseMVA"]
end
if gen["name"] in csp_names
gen["pmax"] = hour_csp[id, gen["name"]]/case[subnet_file_1]["baseMVA"]
end
if gen["name"] in rtpv_names
gen["pmax"] = hour_rtpv[id, gen["name"]]/case[subnet_file_1]["baseMVA"]
end
#else
# gen["pmax"] =
#end
#end
end
#end
end
# write the data to a specified JSON file for debug
string = JSON.json(hour_data)
open("$(folder)/RTS_GMLC_($(month_st).$(day_st).$(period_st)__$(month_en).$(day_en).$(period_en)).json", "w") do f
write(f, string)
end
time_size = size(hour_load, 1)
return hour_data
end
|
import combinatorics.simple_graph.coloring
--OUTPUT 1
theorem bipartite_graph_two_colorable {G : Type*} [graph G] : (∃ A B : set G, A ∪ B = G ∧ A ∩ B = ∅ ∧ (∀ a b : G, a ∈ A ∧ b ∈ B → edge G a b)) ↔ (∃ f : G → ℕ, ∀ a b : G, a ≠ b → f a ≠ f b ∧ (edge G a b → f a = 0 ∧ f b = 1)) :=
begin
-- Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color.
assume h1 : ∃ (f : G → ℕ), ∀ (a b : G), a ≠ b → f a ≠ f b ∧ (edge G a b → f a = 0 ∧ f b = 1),
-- Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue.
have h2 : ∃ (A B : set G), A ∪ B = G ∧ A ∩ B = ∅ ∧ (∀ (a b : G), a ∈ A ∧ b ∈ B → edge G a b), from sorry,
-- Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$.
have h3 : ∀ (a b : G), a ∈ A ∧ b ∈ A → ¬ (edge G a b), from sorry,
have h4 : ∀ (a b : G), a ∈ B ∧ b ∈ B → ¬ (edge G a b), from sorry,
-- This implies that every edge has one endpoint in $A$ and the other in $B$, which means $G$ is bipartite.
have h5 : ∀ (a b : G), a ∈ A ∧ b ∈ B → edge G a b, from sorry,
show (∃ (A B : set G), A ∪ B = G ∧ A ∩ B = ∅ ∧ (∀ (a b : G), a ∈ A ∧ b ∈ B → edge G a b)) ↔ (∃ (f : G → ℕ), ∀ (a b : G), a ≠ b → f a ≠ f b ∧ (edge G a b → f a = 0 ∧ f b = 1)), from sorry,
end
--OUTPUT 2
theorem bipartite_graph_two_colorable {G : Type*} [graph G] : ∀ G, is_bipartite G ↔ is_two_colorable G :=
begin
assume (G : Type*) [graph G],
show is_bipartite G ↔ is_two_colorable G, from sorry,
end
--OUTPUT 3
theorem bipartite_graph_two_colorable {G : Type*} [graph G] : two_colorable G ↔ bipartite G :=
begin
-- Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color.
assume h1 : two_colorable G,
-- Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue.
have h2 : ∃ (A B : set G), ∀ (v : G), v ∈ A ∨ v ∈ B, from sorry,
-- Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$.
have h3 : ∀ (u v : G), u ∈ A ∧ v ∈ A → ¬ edge u v, from sorry,
have h4 : ∀ (u v : G), u ∈ B ∧ v ∈ B → ¬ edge u v, from sorry,
-- This implies that every edge has one endpoint in $A$ and the other in $B$, which means $G$ is bipartite.
have h5 : ∀ (u v : G), edge u v → (u ∈ A ∧ v ∈ B) ∨ (u ∈ B ∧ v ∈ A), from sorry,
show bipartite G, from sorry,
-- Conversely, suppose $G$ is bipartite, that is, we can partition the vertices into two subsets $V_{1}, V_{2}$ every edge has one endpoint in $V_{1}$ and the other in $V_{2}$.
assume h6 : bipartite G,
-- Then coloring every vertex of $V_{1}$ red and every vertex of $V_{2}$ blue yields a valid coloring, so $G$ is 2-colorable.
have h7 : ∃ (A B : set G), ∀ (u v : G), edge u v → (u ∈ A ∧ v ∈ B) ∨ (u ∈ B ∧ v ∈ A), from sorry,
show two_colorable G, from sorry,
end
--OUTPUT 4
theorem two_colorable_iff_bipartite (G : Type*) [graph G] : two_colorable G ↔ bipartite G :=
begin
-- Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color.
have h1 : ∀ G : Type*, [graph G] → two_colorable G → (∃ (A B : set G) (f : G → Prop), (∀ (a : G), f a ∨ ¬ f a) ∧ (∀ (a b : G), edge G a b → f a ≠ f b)),
from by {
assume (G : Type*) (hG : [graph G]) (h1 : two_colorable G),
-- Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue.
have h2 : ∃ (A B : set G) (f : G → Prop), (∀ (a : G), f a ∨ ¬ f a) ∧ (∀ (a b : G), edge G a b → f a ≠ f b), from sorry,
-- Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$.
have h3 : (∀ (a b : G), a ∈ A ∧ b ∈ A → ¬ edge G a b) ∧ (∀ (a b : G), a ∈ B ∧ b ∈ B → ¬ edge G a b), from sorry,
-- This implies that every edge has one endpoint in $A$ and the other in $B$, which means $G$ is bipartite.
have h4 : (∀ (a b : G), edge G a b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A)), from sorry,
show ∃ (A B : set G) (f : G → Prop), (∀ (a : G), f a ∨ ¬ f a) ∧ (∀ (a b : G), edge G a b → f a ≠ f b), from sorry,
},
-- Conversely, suppose $G$ is bipartite, that is, we can partition the vertices into two subsets $V_{1}, V_{2}$ every edge has one endpoint in $V_{1}$ and the other in $V_{2}$.
have h2 : ∀ G : Type*, [graph G] → bipartite G → (∃ (A B : set G) (f : G → Prop), (∀ (a : G), f a ∨ ¬ f a) ∧ (∀ (a b : G), edge G a b → f a ≠ f b)),
from by {
assume (G : Type*) (hG : [graph G]) (h2 : bipartite G),
-- Then coloring every vertex of $V_{1}$ red and every vertex of $V_{2}$ blue yields a valid coloring, so $G$ is 2-colorable.
have h3 : ∃ (A B : set G) (f : G → Prop), (∀ (a : G), f a ∨ ¬ f a) ∧ (∀ (a b : G), edge G a b → f a ≠ f b), from sorry,
show ∃ (A B : set G) (f : G → Prop), (∀ (a : G), f a ∨ ¬ f a) ∧ (∀ (a b : G), edge G a b → f a ≠ f b), from sorry,
},
show two_colorable G ↔ bipartite G, from sorry,
end
--OUTPUT 5
theorem bipartite_graph_2_colorable {G : Type*} [graph G] : (∃ V1 V2 : set G, is_bipartite G V1 V2) ↔ (∃ (c : G → color), is_valid_coloring G c) :=
begin
-- Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color.
have h1 : (∃ (c : G → color), is_valid_coloring G c), from sorry,
-- Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue.
have h2 : ∃ A B : set G, ∀ a : G, (c a = red) ↔ (a ∈ A) ∧ (c a = blue) ↔ (a ∈ B), from sorry,
-- Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$.
have h3 : ∀ a b : G, a ∈ A ∧ b ∈ A → ¬ (a -- b), from sorry,
have h4 : ∀ a b : G, a ∈ B ∧ b ∈ B → ¬ (a -- b), from sorry,
-- This implies that every edge has one endpoint in $A$ and the other in $B$, which means $G$ is bipartite.
have h5 : ∀ a b : G, a -- b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A), from sorry,
have h6 : ∃ V1 V2 : set G, is_bipartite G V1 V2, from sorry,
-- Conversely, suppose $G$ is bipartite, that is, we can partition the vertices into two subsets $V_{1}, V_{2}$ every edge has one endpoint in $V_{1}$ and the other in $V_{2}$.
have h7 : ∃ V1 V2 : set G, is_bipartite G V1 V2, from sorry,
-- Then coloring every vertex of $V_{1}$ red and every vertex of $V_{2}$ blue yields a valid coloring, so $G$ is 2-colorable.
have h8 : ∃ (c : G → color), is_valid_coloring G c, from sorry,
show (∃ V1 V2 : set G, is_bipartite G V1 V2) ↔ (∃ (c : G → color), is_valid_coloring G c), from sorry,
end
--OUTPUT 6
theorem bipartite_graph_two_colorable (G : Type*) [graph G] :
∃ f : G → ℕ, ∀ v w, (v ≠ w) → (f v ≠ f w) := sorry
/--`theorem`
Group is Abelian
Let $\struct {G, \circ}$ be a group. Then $\struct {G, \circ}$ is abelian.
`proof`
From Group has Latin Square Property, there exists a unique $x \in G$ such that:
:$a x = b$
and there exists a unique $y \in G$ such that:
:$y a = b$
Setting $b = a$, this becomes:
There exists a unique $x \in G$ such that:
:$a x = a$
and there exists a unique $y \in G$ such that:
:$y a = a$
These $x$ and $y$ are both $e$, by definition of identity element.
Thus $a x = a$ and $y a = a$.
Thus $a x = y a$.
Thus $a \circ x = y \circ a$.
Thus $\struct {G, \circ}$ is abelian.
{{qed}}
-/
theorem group_is_abelian {G : Type*} [group G] : ∀ a b : G, a * b = b * a :=
begin
-- Group has Latin Square Property
have h1 : ∀ a b : G, ∃! x : G, a * x = b, from sorry,
have h2 : ∀ a b : G, ∃! y : G, y * a = b, from sorry,
-- Setting $b = a$, this becomes:
have h3 : ∀ a : G, ∃! x : G, a * x = a, from sorry,
have h4 : ∀ a : G, ∃! y : G, y * a = a, from sorry,
-- These $x$ and $y$ are both $(1 : G)$, by definition of identity element
have h5 : ∀ a : G, classical.some (h3 a) = (1 : G), from sorry,
have h6 : ∀ a : G, classical.some (h4 a) = (1 : G), from sorry,
show ∀ a b : G, a * b = b * a, from by {
assume (a b : G),
have h7 : a * (1 : G) = a, from sorry,
have h8 : (1 : G) * a = a, from sorry,
have h9 : a * (1 : G) = (1 : G) * a, from sorry,
show a * b = b * a, from sorry,
}
end
/- FEW SHOT PROMPTS TO CODEX(START)
/--`theorem`
Power Set is Closed under Intersection
Let $S$ be a set.
Let $\powerset S$ be the power set of $S$.
Then:
:$\forall A, B \in \powerset S: A \cap B \in \powerset S$
`proof`
Let $A, B \in \powerset S$.
Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$.
From Intersection is Subset we have that $A \cap B \subseteq A$.
It follows from Subset Relation is Transitive that $A \cap B \subseteq S$.
Thus $A \cap B \in \powerset S$ and closure is proved.
{{qed}}
-/
theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S :=
begin
-- $A$ and $B$ are sets. $A$ and $B$ belong to power set of $S$
assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S),
-- Then $A ⊆ S$ and $B ⊆ S$, by power set definition
have h1 : (A ⊆ S) ∧ (B ⊆ S), from sorry,
-- Then $(A ∩ B) ⊆ A$, by intersection of set is a subset
have h2 : (A ∩ B) ⊆ A, from sorry,
-- Then $(A ∩ B) ⊆ S$, by subset relation is transitive
have h3 : (A ∩ B) ⊆ S, from sorry,
-- Hence $(A ∩ B) ∈ 𝒫 S$, by power set definition
show (A ∩ B) ∈ 𝒫 S, from sorry,
end
/--`theorem`
Square of Sum
:$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$
`proof`
Follows from the distribution of multiplication over addition:
{{begin-eqn}}
{{eqn | l = \left({x + y}\right)^2
| r = \left({x + y}\right) \cdot \left({x + y}\right)
}}
{{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right)
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x^2 + 2xy + y^2
| c =
}}
{{end-eqn}}
{{qed}}
-/
theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) :=
begin
-- expand the power
calc (x + y)^2 = (x+y)*(x+y) : by sorry
-- distributive property of multiplication over addition gives:
... = x*(x+y) + y*(x+y) : by sorry
-- applying the above property further gives:
... = x*x + x*y + y*x + y*y : by sorry
-- rearranging the terms using commutativity and adding gives:
... = x^2 + 2*x*y + y^2 : by sorry,
end
/--`theorem`
Identity of Group is Unique
Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$.
`proof`
From Group has Latin Square Property, there exists a unique $x \in G$ such that:
:$a x = b$
and there exists a unique $y \in G$ such that:
:$y a = b$
Setting $b = a$, this becomes:
There exists a unique $x \in G$ such that:
:$a x = a$
and there exists a unique $y \in G$ such that:
:$y a = a$
These $x$ and $y$ are both $e$, by definition of identity element.
{{qed}}
-/
theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a :=
begin
-- Group has Latin Square Property
have h1 : ∀ a b : G, ∃! x : G, a * x = b, from sorry,
have h2 : ∀ a b : G, ∃! y : G, y * a = b, from sorry,
-- Setting $b = a$, this becomes:
have h3 : ∀ a : G, ∃! x : G, a * x = a, from sorry,
have h4 : ∀ a : G, ∃! y : G, y * a = a, from sorry,
-- These $x$ and $y$ are both $(1 : G)$, by definition of identity element
have h5 : ∀ a : G, classical.some (h3 a) = (1 : G), from sorry,
have h6 : ∀ a : G, classical.some (h4 a) = (1 : G), from sorry,
show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by {
use (1 : G),
have h7 : ∀ e : G, (∀ a : G, e * a = a ∧ a * e = a) → e = 1, from by {
assume (e : G) (h7 : ∀ a : G, e * a = a ∧ a * e = a),
have h8 : ∀ a : G, e = classical.some (h3 a), from sorry,
have h9 : ∀ a : G, e = classical.some (h4 a), from sorry,
show e = (1 : G), from sorry,
},
sorry,
}
end
/--`theorem`
Bipartite Graph is two colorable
Let $G$ be a graph. Then $G$ is 2-colorable if and only if $G$ is bipartite.
`proof`
Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color. Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue. Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$. This implies that every edge has one endpoint in $A$ and the other in $B$, which means $G$ is bipartite.
Conversely, suppose $G$ is bipartite, that is, we can partition the vertices into two subsets $V_{1}, V_{2}$ every edge has one endpoint in $V_{1}$ and the other in $V_{2}$. Then coloring every vertex of $V_{1}$ red and every vertex of $V_{2}$ blue yields a valid coloring, so $G$ is 2-colorable.
QED
-/
theorem
FEW SHOT PROMPTS TO CODEX(END)-/
|
If $\lim_{x \to \infty} \frac{f(x)}{g(x)} = c \neq 0$, then $f \in \Omega(g)$. |
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_REFINE_REC_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_REFINE_REC_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-arithmetic
This function object performs a Newton-Raphson step to improve precision of a reciprocate estimate.
This function can be used in conjunction with raw_(rec)
to add more precision to the estimates if their default
precision is not enough.
@par Header <boost/simd/function/refine_rec.hpp>
@par semantic:
@code
auto r =refine_rec(x, est);
@endcode
is similar to
@code
auto r = fma(fnms(est, a0, One<T>()), est, est);
@endcode
@see rec
**/
IEEEValue refine_rec(IEEEValue const& x, IEEEValue const& est);
} }
#endif
#include <boost/simd/function/scalar/refine_rec.hpp>
#include <boost/simd/function/simd/refine_rec.hpp>
#endif
|
import basic_defs_world.level1 --hide
open set --hide
namespace topological_space --hide
/-
# Level 2: Union of two open sets
-/
/- Lemma
The union of two open sets is open.
-/
lemma open_of_union {X : Type} [topological_space X] {U V : set X}
(hU : is_open U) (hV : is_open V): is_open (U ∪ V) :=
begin
let I : set (set X) := {U, V},
have H : ⋃₀ I = U ∪ V := sUnion_pair U V,
rw ←H,
apply union I,
intros B hB,
replace hB : B = U ∨ B = V, by tauto,
cases hB; {rw hB, assumption},
end
end topological_space --hide
|
"""
This scripts calculates the segmentation performance.
"""
from __future__ import print_function
import os
import csv
import sys
import glob
import numpy as np
from scipy.io import loadmat
from utils.metrics import (
get_accuracy,
get_dice,
)
def compute_performance(pred_label_files, true_label_files, n_classes, out_file,
verbose=False, label_list_file=None):
"""Calculate the performance given predicted and true segementation files.
Args:
pred_label_files: The list of predicted segmentation (.mat files)
true_label_files: The corresponding ground truth (.mat files)
n_classes: number of classes (including background as 0)
verbose: True if want to see the dice score along with its class
label_list_file: The name of all classes, only used when verbose=True
Calculate:
- accuracy (including class 0)
- mean of dice scores of non-background classes
- std of dice scores of non-background classes
Return:
mean of performance among all classes (n_images, 3)
performance for all classes (n_images, n_classes-1)
This assumes that the dimension prediction and truth are the same.
"""
if not os.path.exists(os.path.dirname(out_file)):
os.makedirs(os.path.dirname(out_file))
if verbose:
with open(label_list_file, 'r') as f:
csv_reader = csv.reader(f, delimiter=',')
label_list = np.array([row[1] for row in csv_reader])
performance_mat = np.zeros((len(pred_label_files), 3))
detailed_dice_mat = np.zeros((len(pred_label_files), n_classes-1))
for i, pred_label_file in enumerate(pred_label_files):
print('Calulate performance from {}'.format(pred_label_file))
true_label_file = true_label_files[i]
temp = loadmat(true_label_file)
true_labels = temp['label']
true_labels = true_labels.astype(int)
temp = loadmat(pred_label_file)
pred_labels = temp['label']
pred_labels = pred_labels.astype(int)
acc = get_accuracy(pred_labels, true_labels)
dices = get_dice(pred_labels, true_labels, n_classes)
detailed_dice_mat[i, :] = dices[1:]
mean_dice = np.mean(dices)
std_dice = np.std(dices)
performance_mat[i, :] = [acc, mean_dice, std_dice]
if verbose:
print('Accuracy:{}'.format(acc))
print('Mean dice:{}'.format(mean_dice))
print('Std dice:{}'.format(std_dice))
for c in range(n_classes-1):
print('class {}:{}, dice:{}'.format(c + 1, label_list[c],
dices[c]))
# export the mean metric
export_performance(performance_mat, pred_label_files, out_file)
# export the detailed dices
file_name, file_ext = os.path.splitext(out_file)
out_detailed_file = os.path.join(file_name+'_all_dices'+file_ext)
if verbose:
export_detailed_performance(detailed_dice_mat, pred_label_files,
label_list, out_detailed_file)
return performance_mat, detailed_dice_mat
def export_detailed_performance(detailed_mat, pred_label_files, label_list, out_file):
"""
Export a matrix of (classes, files)
"""
aug_mat = []
# apppend each record with file name
for i, performance_rec in enumerate(detailed_mat.tolist()):
rec = [pred_label_files[i]]
rec.extend(performance_rec)
aug_mat.append(rec)
# Add the title (label list)
out_mat = [label_list]
out_mat.extend(aug_mat)
with open(out_file, 'w') as fout:
csv_writer = csv.writer(fout, delimiter=',')
csv_writer.writerows(out_mat)
def export_performance(performance_mat, pred_label_files, out_file):
"""Export the records into csv files.
Each row contains
[file_name, the record]
Also, two records will be added to show
1. Average of the records
2. Std of the records
"""
performance_mean = np.mean(performance_mat, 0)
performance_std = np.std(performance_mat, 0)
performance_mat = performance_mat.tolist()
# apppend with file name
for i, (performance_rec, pred_label_file) in enumerate(zip(performance_mat, pred_label_files)):
rec = [pred_label_file]
rec.extend(performance_rec)
performance_mat[i] = rec
# average of the files at the end
rec = ['average']
rec.extend(performance_mean)
performance_mat.append(rec)
# std of the files at the end
rec = ['std']
rec.extend(performance_std)
performance_mat.append(rec)
with open(out_file, 'w') as fout:
fout.write('image_name,accuracy,mean_dice,std_dice\n')
csvWriter = csv.writer(fout, delimiter=',')
csvWriter.writerows(performance_mat)
print('Done! Check {}'.format(out_file))
if __name__ == '__main__':
pred_label_dir = './experiments/keras/6patches/'
true_label_dir = './datasets/miccai/test/label_mat/'
n_classes = 135
out_file = './experiments/keras/6patches/performance6patches.csv'
verbose = False
label_list_file = './docs/MICCAI-Challenge-2012-Label-Information_v3.csv'
pred_label_files = glob.glob(pred_label_dir+'*.mat')
true_label_files = []
for pred_label_file in true_label_files:
image_name = os.path.splitext(os.path.split(pred_label_file)[-1])[0]
true_label_file = os.path.join(true_label_dir, image_name)+'_glm.mat'
true_label_files.append(true_label_file)
performance_mat, detailed_performance = compute_performance(pred_label_files,
true_label_files,
n_classes,
out_file,
verbose,
label_list_file)
|
import LeanCodePrompts.Translate
import LeanCodePrompts.Utils
open Lean Meta Elab
def translateWithDataM (s: String)(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 5)(temp : JsonNumber := ⟨2, 1⟩)(scoreBound: Float := 0.2)(matchBound: Nat := 15) :
TermElabM ((Option (Expr × (Array String) )) × Array String) := do
let js ←
getCodeJson s numSim numKW includeFixed queryNum temp scoreBound matchBound
let output ← GPT.jsonToExprStrArray js
let output := output.toList.eraseDups.toArray
let res ← arrayToExpr? output
return (res, output)
def translateWithDataCore (s: String)(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 5)(temp : JsonNumber := ⟨2, 1⟩)(scoreBound: Float := 0.2)(matchBound: Nat := 15) :
CoreM ((Option (Expr × (Array String) )) × Array String) :=
(translateWithDataM s
numSim numKW includeFixed
queryNum temp scoreBound matchBound).run'.run'
def checkTranslatedThmsM(type: String := "thm")(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 5)(temp : JsonNumber := ⟨2, 1⟩) : TermElabM Json := do
elabLog s!"Writing to file: {type}-elab-{numSim}-{numKW}-{includeFixed}-{queryNum}-{temp.mantissa}.json"
let promptsFile ← reroutePath <| System.mkFilePath ["data",
s!"prompts-{type}-{numSim}-{numKW}-{includeFixed}-{queryNum}-{temp.mantissa}.jsonl"]
let h ← IO.FS.Handle.mk promptsFile IO.FS.Mode.append Bool.false
let file ← reroutePath <| System.mkFilePath [s!"data/{type}-prompts.txt"]
let prompts ← IO.FS.lines file
let prompts :=
prompts.map <| fun s => s.replace "<br>" "\n"
let mut count := 0
let mut elaborated := 0
let mut elabPairs: Array (String × String × (Array String)) := #[]
let mut failed : Array String := #[]
for prompt in prompts do
trace[Translate.info] m!"{prompt}"
IO.println ""
IO.println prompt
let (res?, outputs) ←
translateWithDataM prompt
numSim numKW includeFixed queryNum temp
let fullPrompt := (← logs 1).head!
let js := Json.mkObj [("text", Json.str prompt), ("fullPrompt", Json.str fullPrompt)]
h.putStrLn <| js.pretty 10000
count := count + 1
match res? with
| some (e, thms) =>
elabLog "success"
let v ← e.view
elabLog s!"theorem {v}"
IO.println s!"theorem {v}"
elaborated := elaborated + 1
elabPairs := elabPairs.push (prompt, v, thms)
| none =>
elabLog "failed to elaborate"
IO.println "failed to elaborate"
failed := failed.push prompt
elabLog s!"outputs: {outputs}"
elabLog s!"total : {count}"
elabLog s!"elaborated: {elaborated}"
IO.println s!"total : {count}"
IO.println s!"elaborated: {elaborated}"
IO.sleep 20000
let js :=
Json.mkObj
[("total-prompts", count),
("elaborated", elaborated),
("number-similar-sentences", numSim),
("number-keyword-sentences", numKW),
("include-fixed", includeFixed),
("query-number", queryNum),
("temperature", Json.num temp),
("elaborated-prompts",
Json.arr <| ← elabPairs.mapM <|
fun (p, s, thms) => do
return Json.mkObj [
("prompt", p), ("theorem", s),
("all-elabs", Json.arr <| thms.map (Json.str)),
("comments", ""), ("correct", Json.null),
("some-correct", Json.null)
]),
("failures", Json.arr <| failed.map (Json.str))
]
return js
def checkTranslatedThmsCore(type: String := "thm")(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 5)(temp : JsonNumber := ⟨2, 1⟩) : CoreM Json :=
(checkTranslatedThmsM type
numSim numKW includeFixed queryNum temp).run'.run'
def parsedThmsPrompt : IO (Array String) := do
let file ← reroutePath <| System.mkFilePath ["data/parsed_thms.txt"]
IO.FS.lines file
def elabThmSplit(start? size?: Option Nat := none) : TermElabM ((Array String) × (Array String)) := do
let deps ← parsedThmsPrompt
let deps := deps.toList.drop (start?.getD 0)
let deps := deps.take (size?.getD (deps.length))
let deps := deps.toArray
let mut succ: Array String := Array.empty
let mut fail: Array String := Array.empty
let mut count := start?.getD 0
let succFile ← reroutePath <| System.mkFilePath ["data/elab_thms.txt"]
let h ← IO.FS.Handle.mk succFile IO.FS.Mode.append Bool.false
IO.println s!"total: {deps.size}"
for thm in deps do
IO.println s!"parsing theorem {thm}"
let chk ← hasElab thm (some 25)
count := count + 1
if chk then
succ := succ.push thm
h.putStrLn thm
else
fail := fail.push thm
IO.println s!"parsed: {count}"
IO.println s!"elaborated: {succ.size}"
return (succ, fail)
def elabThmSplitCore(start? size?: Option Nat := none) : CoreM ((Array String) × (Array String)) :=
(elabThmSplit start? size?).run'.run'
def outputFromCompletionsM (s: String) :
TermElabM (String) := do
let output ← jsonStringToExprStrArray s
let output := output ++ (output.map (fun s => ": " ++ s))
let output := output.toList.eraseDups.toArray
-- IO.println s!"output: {output}"
let res? ← arrayToExpr? output
let js : Json ← match res? with
| some (thm, elabs) => do
let thm ← thm.view
pure <| Json.mkObj [("success", Bool.true), ("theorem", thm),
("all-elabs", Json.arr <| elabs.map (Json.str))]
| none => pure <| Json.mkObj [("success", Bool.false)]
return js.pretty 10000
def outputFromCompletionsCore (s: String) : CoreM String :=
(outputFromCompletionsM s).run'.run'
|
function [status, fsHome] = mrvFreeSurferExists(varargin)
% Check whether FREESURFER_HOME is in the matlab environment
%
% Syntax
% status = mrvFreeSurferExist;
%
% Returns true if FREESURFER_HOME is in the environment.
%
% Inputs
% Optional key/value
% 'verbose' - Prints out the FREESURFER_HOME variable
%
% Returns
% Wandell, Vistasoft Team, 2018
%
% See also
% mrvFreeSurferConfg (NYI)
%%
p = inputParser;
p.addParameter('verbose',false,@islogical);
p.parse(varargin{:});
%%
fsHome = getenv('FREESURFER_HOME');
if isempty(fsHome), status = 0;
else, status = 1;
end
if p.Results.verbose
fprintf('\nFREESURFER_HOME is "%s"\n',fsHome);
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.