text
stringlengths 0
3.34M
|
---|
module Streaming.Encoding.Base64
import Streaming.Internal as S
import Streaming.API as S
import Data.Functor.Of
import Streaming.Bytes
import System.File
import Data.Strings
-- import Data.LazyList
import Data.List -- zip
import Data.IOArray
import Control.Monad.State
import Util
import Language.Reflection
import public Streaming.Encoding.Base64.Alphabet
-- base64 is an encoding _from_ binary data _to_ binary data matching a
-- restricted alphabet of characters.
-- https://tools.ietf.org/rfc/rfc4648#section-1
export
data EncodeError = CodepointOutOfRange
| InvalidStartByte Bits8
| CodepointEndedEarly
export
Show EncodeError where
show CodepointOutOfRange = "CodepointOutOfRange"
show (InvalidStartByte x) = "InvalidStartByte " ++ show x
show CodepointEndedEarly = "CodepointEndedEarly"
export
data DecodeError = CharNotInAlphabet Char | DataEndedEarly | TooMuchPadding
export
Show DecodeError where
show (CharNotInAlphabet x) = "CharNotInAlphabet: " ++ show x
show DataEndedEarly = "Encoded data ended early"
show TooMuchPadding = "TooMuchPadding"
-- base64 can't have a decode error because it pads missing bits.
export
encodeBase64 : Monad m => Alphabet -> Stream (Of Bits8) m r
-> Stream (Of Char) m r
encodeBase64 alph str0
= str0 &$
chunksOf 3 -- this foldl needs to account for folding over 3 instead of less
|> mapf (store (\str => foldl (\acc,b => shiftL acc 8 .|. cast b) 0
(take'' 3 $ str <* replicate 3 0)) -- pad to 3
|> length -- <^ compute length and combine bits in one pass
|> \res => effect $ do
len :> b <- res
pure $ case len of
1 => splitGroup 2 b <* yield 65 <* yield 65 -- pads
2 => splitGroup 3 b <* yield 65
_ => splitGroup 4 b)
-- ^ Combine up to three Bits8, note the number we got, split based on it
|> concats
|> encode alph
where
-- Split the Int into 4 six bit parts. Left as Int to skip a cast.
-- Because we construct the pieces ourself we don't need to do checks later
-- to be sure our Int fits into our alphabet. Their size means they must.
splitGroup : forall r. Int -> Of Int r -> Stream (Of Int) m r
splitGroup n (x :> r) = (iterate (`shiftR`6) x
&$ take {r=()} 4
|> maps (.&. 0x3F)
|> rev -- the shifting makes the order backward
|> take n) *> pure r
-- e. = 101 46
-- Z S 4 = 25 28 56
-- A G U u = 0 6 20 46
-- Take our six bit parts and convert them to chars.
encode : forall r. Alphabet -> Stream (Of Int) m r -> Stream (Of Char) m r
encode alph str0 = effect $ do
Right (b :> str) <- inspect str0
| Left r => pure . pure $ r
pure $ if b == 65 -- pad
then yield alph.pad *> encode alph str
else yield (alph.toChar b) *> encode alph str
-- What to do if encoded data ends early?
-- Return what was decoded and the rest of the stream?
||| decode Char (from an Alphabet) to binary data
export
decodeBase64 : Monad m => Alphabet -> Stream (Of Char) m r
-> Stream (Of Bits8) m (Either DecodeError r)
decodeBase64 alph str0 = str0
&$ S.filter (not . alph.whitespace) -- ignore whitespace
|> validate alph
|> chunksOf 4
|> mapf (graft alph)
|> concats
where
-- Ensure the encountered character is part of our alphabet
validate : forall r. Alphabet -> Stream (Of Char) m r
-> Stream (Of Char) m (Either DecodeError r)
validate alph str0 = effect $ do
Right (c :> str) <- inspect str0
| Left l => pure . pure . Right $ l
pure $ if c /= alph.pad
then case alph.fromChar c of
Nothing => pure . Left $ CharNotInAlphabet c
Just _ => wrap (c :> validate alph str)
else wrap (c :> validate alph str)
-- Split the collected bytes into `n` eight bit parts.
splitGroup : forall r. Int -> Of Int r -> Stream (Of Bits8) m r
splitGroup n (x :> r) = (iterate (`shiftR`8) x
&$ take {r=()} 3
|> rev
|> take n
|> maps cast) -- the shifting makes the order backward
*> Return r
-- process 4 chars into 3 bytes
-- store, check length gotten, unSplit, use what length demands pad otherwise
graft : forall r. Alphabet -> Stream (Of Char) m r -> Stream (Of Bits8) m r
graft alph str0 = str0 &$ store (maps (maybe 0 id . alph.fromChar)
|> foldl (\acc,c => shiftL acc 6 .|. c) 0) -- merge chars)
|> (length . S.filter (/= alph.pad))
|> \x => effect $ do
len :> res <- x
case len of
-- 1 => pure . pure $ Left TooMuchPadding
2 => pure (splitGroup 1 res)
3 => pure (splitGroup 2 res)
_ => pure (splitGroup len res)
-- doesn't quite handle padding right yet
|
Symmetric : {c : Type} -> (c -> c -> Type) -> Type
Symmetric {c} rel = {a : c} -> {b : c} -> rel a b -> rel b a
record Symmetry (t : Type) (rel : t -> t -> Type) where
constructor MkSymmetry
is_symmetric : Symmetric {c=t} rel
symmetry : {ty : Type} -> Symmetry ty (=)
symmetry = MkSymmetry sym
|
import init.data.nat.basic
import tactic.finish
import tactic.ext
import biject
import init.data.int.basic
import data.int.basic
import data.nat.parity
import tactic.hint
import data.nat.basic
universes u1 u2 u3 u4
def denombrable (α : Sort u1) : Prop :=
in_bijection ā α
theorem tf_l {A : Sort u1} {B : Sort u2} {x3 x4 :pprod A B} : x3 = x4 ā x3.1 = x4.1 ā§ x3.2 = x4.2 :=
begin
intro a,
apply and.intro,
apply map_eq (Ī» x :pprod A B, x.1) a,
apply map_eq (Ī» x :pprod A B, x.2) a,
end
theorem tf_r {A : Sort u1} {B : Sort u2} {x3 x4 :pprod A B} : x3.1 = x4.1 ā§ x3.2 = x4.2 ā x3 = x4 :=
begin
intro eq1,
cases eq1 with a b,
cases x3,
cases x4,
finish
end
theorem tf {A : Sort u1} {B : Sort u2} (x3 x4 :pprod A B) : x3 = x4 ā x3.1 = x4.1 ā§ x3.2 = x4.2 :=
begin
split,
apply tf_l,
apply tf_r
end
def prod_func {A : Sort u1} {B : Sort u2} {C : Sort u3}
{D : Sort u4} (f : A ā B) (g : C ā D) : pprod A C ā pprod B D :=
Ī» x : pprod A C , pprod.mk (f (x.fst)) (g x.snd)
theorem prod_bij_prod_left {A : Sort u1} {B : Sort u2} {C : Sort u3}
{D : Sort u4} (f : A ā B) (g : C ā D) [bijective f] [bijective g] :
bijective (prod_func f g) :=
begin
apply and.intro,
intros x1 x2,
rw prod_func,
simp,
intro h,
apply iff.elim_right (tf x1 x2),
apply and.intro,
apply _inst_1.left x1.fst x2.fst
((tf (prod_func f g x1) (prod_func f g x2)).elim_left h).left,
apply _inst_2.left x1.snd x2.snd
((tf (prod_func f g x1) (prod_func f g x2)).elim_left h).right,
intro y,
let x1 := (_inst_1.elim_right y.1).some,
let x2 := (_inst_2.elim_right y.2).some,
use pprod.mk x1 x2,
rw prod_func,
simp,
apply tf_r,
simp,
change x1 with (_inst_1.elim_right y.1).some,
change x2 with (_inst_2.elim_right y.2).some,
split,
apply Exists.some_spec (_inst_1.elim_right y.1),
apply Exists.some_spec (_inst_2.elim_right y.2)
end
def nat_plus := { n : ā // ¬ n = 0}
lemma nat_succ_not_zero (n : ā) : ¬ n.succ = 0 :=
begin
apply not.intro,
trivial
end
def succ_plus (n : ā ) : nat_plus :=
⨠n.succ,nat_succ_not_zero nā©
lemma not_zero_le (n : ā) : ¬ n = 0 ā 0 < n :=
begin
split,
apply nat.cases_on n,
trivial,
intro m,
simp,
apply nat.cases_on n,
simp,
intro m,
simp,
trivial
end
lemma bon (n : nat_plus) : n.val.pred.succ = n.val :=
begin
apply n.cases_on,
intros k p,
simp,
apply nat.succ_pred_eq_of_pos ((not_zero_le k).elim_left p)
end
theorem Nplus_denumbrable : denombrable nat_plus :=
begin
rw [denombrable,in_bijection],
use succ_plus,
split,
intros x1 x2,
rw [succ_plus,succ_plus],
intro hyp,
apply subtype.mk.inj,
simp,
apply nat.succ.inj (subtype.mk_eq_mk.elim_left hyp),
exact (Ī» n : ā , true),
trivial,
trivial,
intro y,
use y.val.pred,
rw succ_plus,
rw eq.symm (subtype.coe_eta y y.property),
rw subtype.mk.inj_eq,
simp,
apply bon y
end
def abs_nat : ⤠ā ā
|(int.of_nat k) := k
|(int.neg_succ_of_nat k) := k
@[simp] def nat_abs : ⤠ā ā
| (int.of_nat m) := m
| -[1+ m] := m.succ
constant h : Prop
constant dh : decidable h
constants a b : α
lemma if_works {α : Sort u1} {p : Prop} [decidable p] {a b: α} : p ā (ite p a b = a) :=
begin
intro h,
simp,
intro nh,
trivial
end
lemma if_not_works {α : Sort u1} {p : Prop} [decidable p] {a b: α} : ¬ p ā (ite p a b = b) :=
begin
intro h,
rw eq.symm (ite_not p b a),
apply if_works,
exact h
end
lemma whatever_decidable : decidable (ā (n : ā), 0 ⤠(n : ⤠)) :=
begin
simp,
apply decidable.true
end
def f : ā ā ⤠:= Ī» n: ā , (-1) ^n *(n/2)
def g : ⤠ā ā := Ī» z : ā¤, if z ⤠0 then (0-2*(nat_abs z)) else 1+2*(nat_abs z)
lemma leq_two_z_o (n : ā) : n<2 ā n=0 ⨠n=1 :=
begin
cases n,
tauto,
intro,
fconstructor,
hint
end
lemma is_le_one_is_zero : ā n : ā, n<1 ā n=0 :=
begin
intro n,
cases n,
simp,
intro h,
have p : ¬ n.succ < 1 := dec_trivial,
apply absurd h p
end
lemma even_succ_not_zero (n : ā) (h : even n.succ) : ¬(n.succ / 2 = 0) :=
begin
apply not.intro,
have wut : 0 < 2 := by simp,
rw nat.div_eq_zero_iff wut,
simp at *,
cases h,
norm_cast at *,
intro x,
safe,
rw eq.symm (nat.one_mul 2) at x,
rw nat.mul_assoc at x,
have lol : 1 * (2 * h_w) = (2 * h_w) := by simp,
rw lol at x,
rw nat.mul_comm 1 2 at x,
have triv : 0 ⤠2 := by simp,
have hmm := @lt_of_mul_lt_mul_left nat nat.linear_ordered_semiring h_w 1 2 x triv,
have hw_z : h_w= 0 := by apply is_le_one_is_zero h_w hmm,
rw hw_z at h_h,
simp at h_h,
have triv : ¬ n.succ = 0 := by trivial,
apply absurd h_h triv
end
theorem comp_fg_is_id : comp g f = id :=
begin
rw comp,
change g with Ī» (z : ā¤), ite (z ⤠0) (0 - 2 * nat_abs z) (1+2 * nat_abs z),
change f with Ī» (n : ā), (-1) ^ n * (ān / 2),
simp,
rw function.funext_iff,
intro n,
simp,
by_cases even n,
rw nat.neg_one_pow_of_even h,
simp,
cases n,
simp,
have p : ¬(n.succ / 2 ⤠0) := by simp;exact even_succ_not_zero n h,
simp at p,
split_ifs,
simp at h_1,
norm_cast at *,
rw nat.succ_eq_add_one n at p,
simp at h_1,
apply absurd h_1 p,
simp,
cases n,
simp,
apply or.intro_right,
finish,
norm_cast at *,
simp,
cases n,
simp,
end
/- theorem Z_denumbrable : denombrable ⤠:=
begin
rw denombrable,
rw in_bijection,
use f,
rw [bijective,and_comm],
split,
intro x,
use g x,
change g with Ī» (z : ā¤), ite (z ⤠0) (1 - 2 * nat_abs z) (2 * nat_abs z),
change f with Ī» (n : ā), (-1) ^ n * (ān / 2),
cases x,
simp,
apply if_works int.coe_nat_nonneg,
end -/
|
program ch0811
! Rank 2 Arrays and the Sum Intrinsic Funcoltion
implicit none
integer, parameter :: nrow = 5
integer, parameter :: ncol = 6
real, dimension(1:nrow*ncol) :: results = [ &
50., 47., 28., 89., 30., 46., 37., 67., 34., 65., 68., &
98., 25., 45., 26., 48., 10., 36., 89., 56., 33., 45., &
30., 65., 68., 78., 38., 76., 98., 65. ]
real, dimension(1:nrow,1:ncol) :: exam_results = 0.
real, dimension(1:nrow) :: people_average = 0.
real, dimension(1:ncol) :: subject_average = 0.
exam_results = reshape(results, [nrow,ncol], [0.,0.], [2,1])
exam_results(1:nrow,3) = exam_results(1:nrow,3)*2.5
people_average = sum(exam_results, 2)
people_average = people_average/ncol
subject_average = sum(exam_results, 1)
subject_average = subject_average/nrow
print *, ' People averages'
print *, people_average
print *, ' Subject averages'
print *, subject_average
end program
|
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include <boost/optional.hpp>
#include <functional>
#include "mongo/platform/atomic_word.h"
#include "mongo/stdx/thread.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/future.h"
#include "mongo/util/invalidating_lru_cache.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest
namespace mongo {
namespace {
// The structure for testing is intentionally made movable, but non-copyable
struct TestValue {
TestValue(std::string in_value) : value(std::move(in_value)) {}
TestValue(TestValue&&) = default;
std::string value;
};
using TestValueCache = InvalidatingLRUCache<int, TestValue>;
using TestValueHandle = TestValueCache::ValueHandle;
using TestValueCacheCausallyConsistent = InvalidatingLRUCache<int, TestValue, Timestamp>;
using TestValueHandleCausallyConsistent = TestValueCacheCausallyConsistent::ValueHandle;
TEST(InvalidatingLRUCacheTest, StandaloneValueHandle) {
TestValueHandle standaloneHandle({"Standalone value"});
ASSERT(standaloneHandle.isValid());
ASSERT_EQ("Standalone value", standaloneHandle->value);
}
TEST(InvalidatingLRUCacheTest, ValueHandleOperators) {
TestValueCache cache(1);
cache.insertOrAssign(100, {"Test value"});
// Test non-const operators
{
auto valueHandle = cache.get(100);
ASSERT_EQ("Test value", valueHandle->value);
ASSERT_EQ("Test value", (*valueHandle).value);
}
// Test const operators
{
const auto valueHandle = cache.get(100);
ASSERT_EQ("Test value", valueHandle->value);
ASSERT_EQ("Test value", (*valueHandle).value);
}
}
TEST(InvalidatingLRUCacheTest, CausalConsistency) {
TestValueCacheCausallyConsistent cache(1);
cache.insertOrAssign(2, TestValue("Value @ TS 100"), Timestamp(100));
ASSERT_EQ("Value @ TS 100", cache.get(2, CacheCausalConsistency::kLatestCached)->value);
ASSERT_EQ("Value @ TS 100", cache.get(2, CacheCausalConsistency::kLatestKnown)->value);
auto value = cache.get(2, CacheCausalConsistency::kLatestCached);
ASSERT(cache.advanceTimeInStore(2, Timestamp(200)));
ASSERT_EQ("Value @ TS 100", value->value);
ASSERT(!value.isValid());
ASSERT_EQ("Value @ TS 100", cache.get(2, CacheCausalConsistency::kLatestCached)->value);
ASSERT(!cache.get(2, CacheCausalConsistency::kLatestCached).isValid());
ASSERT(!cache.get(2, CacheCausalConsistency::kLatestKnown));
// Intentionally push value for key with a timestamp higher than the one passed to advanceTime
cache.insertOrAssign(2, TestValue("Value @ TS 300"), Timestamp(300));
ASSERT_EQ("Value @ TS 100", value->value);
ASSERT(!value.isValid());
ASSERT_EQ("Value @ TS 300", cache.get(2, CacheCausalConsistency::kLatestCached)->value);
ASSERT_EQ("Value @ TS 300", cache.get(2, CacheCausalConsistency::kLatestKnown)->value);
}
TEST(InvalidatingLRUCacheTest, InvalidateNonCheckedOutValue) {
TestValueCache cache(3);
cache.insertOrAssign(0, {"Non checked-out (not invalidated)"});
cache.insertOrAssign(1, {"Non checked-out (invalidated)"});
cache.insertOrAssign(2, {"Non checked-out (not invalidated)"});
ASSERT(cache.get(0));
ASSERT(cache.get(1));
ASSERT(cache.get(2));
ASSERT_EQ(3UL, cache.getCacheInfo().size());
cache.invalidate(1);
ASSERT(cache.get(0));
ASSERT(!cache.get(1));
ASSERT(cache.get(2));
ASSERT_EQ(2UL, cache.getCacheInfo().size());
}
TEST(InvalidatingLRUCacheTest, InvalidateCheckedOutValue) {
TestValueCache cache(3);
cache.insertOrAssign(0, {"Non checked-out (not invalidated)"});
auto checkedOutValue = cache.insertOrAssignAndGet(1, {"Checked-out (invalidated)"});
cache.insertOrAssign(2, {"Non checked-out (not invalidated)"});
ASSERT(checkedOutValue.isValid());
ASSERT_EQ(3UL, cache.getCacheInfo().size());
cache.invalidate(1);
ASSERT(!checkedOutValue.isValid());
ASSERT_EQ(2UL, cache.getCacheInfo().size());
ASSERT(cache.get(0));
ASSERT(!cache.get(1));
ASSERT(cache.get(2));
}
TEST(InvalidatingLRUCacheTest, InvalidateOneKeyDoesnAffectAnyOther) {
TestValueCache cache(4);
auto checkedOutKey = cache.insertOrAssignAndGet(0, {"Checked-out key (0)"});
auto checkedOutAndInvalidatedKey =
cache.insertOrAssignAndGet(1, {"Checked-out and invalidated key (1)"});
cache.insertOrAssign(2, {"Non-checked-out and invalidated key (2)"});
cache.insertOrAssign(3, {"Key which is not neither checked-out nor invalidated (3)"});
// Invalidated keys 1 and 2 above and then ensure that only they are affected
cache.invalidate(1);
cache.invalidate(2);
ASSERT(checkedOutKey.isValid());
ASSERT(!checkedOutAndInvalidatedKey.isValid());
ASSERT(!cache.get(2));
ASSERT(cache.get(3));
ASSERT_EQ(2UL, cache.getCacheInfo().size());
}
TEST(InvalidatingLRUCacheTest, CheckedOutItemsAreInvalidatedWhenEvictedFromCache) {
TestValueCache cache(3);
// Make a cache that's at its maximum size
auto checkedOutKey = cache.insertOrAssignAndGet(
0, {"Checked-out key which will be discarded and invalidated (0)"});
(void)cache.insertOrAssignAndGet(1, {"Non-checked-out key (1)"});
(void)cache.insertOrAssignAndGet(2, {"Non-checked-out key (2)"});
{
auto cacheInfo = cache.getCacheInfo();
std::sort(cacheInfo.begin(), cacheInfo.end(), [](auto a, auto b) { return a.key < b.key; });
ASSERT_EQ(3UL, cacheInfo.size());
ASSERT_EQ(0, cacheInfo[0].key);
ASSERT_EQ(1, cacheInfo[0].useCount);
ASSERT_EQ(1, cacheInfo[1].key);
ASSERT_EQ(2, cacheInfo[2].key);
}
// Inserting one more key, should boot out key 0, which was inserted first, but it should still
// show-up in the statistics for the cache
cache.insertOrAssign(3, {"Non-checked-out key (3)"});
{
auto cacheInfo = cache.getCacheInfo();
std::sort(cacheInfo.begin(), cacheInfo.end(), [](auto a, auto b) { return a.key < b.key; });
ASSERT_EQ(4UL, cacheInfo.size());
ASSERT_EQ(0, cacheInfo[0].key);
ASSERT_EQ(1, cacheInfo[0].useCount);
ASSERT_EQ(1, cacheInfo[1].key);
ASSERT_EQ(2, cacheInfo[2].key);
ASSERT_EQ(3, cacheInfo[3].key);
}
// Invalidating the key, which was booted out due to cache size exceeded should still be
// reflected on the checked-out key
ASSERT(checkedOutKey.isValid());
cache.invalidate(0);
ASSERT(!checkedOutKey.isValid());
{
auto cacheInfo = cache.getCacheInfo();
std::sort(cacheInfo.begin(), cacheInfo.end(), [](auto a, auto b) { return a.key < b.key; });
ASSERT_EQ(3UL, cacheInfo.size());
ASSERT_EQ(1, cacheInfo[0].key);
ASSERT_EQ(2, cacheInfo[1].key);
ASSERT_EQ(3, cacheInfo[2].key);
}
}
TEST(InvalidatingLRUCacheTest, CheckedOutItemsAreInvalidatedWithPredicateWhenEvictedFromCache) {
TestValueCache cache(3);
// Make a cache that's at its maximum size
auto checkedOutKey = cache.insertOrAssignAndGet(
0, {"Checked-out key which will be discarded and invalidated (0)"});
(void)cache.insertOrAssignAndGet(1, {"Non-checked-out key (1)"});
(void)cache.insertOrAssignAndGet(2, {"Non-checked-out key (2)"});
{
auto cacheInfo = cache.getCacheInfo();
std::sort(cacheInfo.begin(), cacheInfo.end(), [](auto a, auto b) { return a.key < b.key; });
ASSERT_EQ(3UL, cacheInfo.size());
ASSERT_EQ(0, cacheInfo[0].key);
ASSERT_EQ(1, cacheInfo[0].useCount);
ASSERT_EQ(1, cacheInfo[1].key);
ASSERT_EQ(2, cacheInfo[2].key);
}
// Inserting one more key, should boot out key 0, which was inserted first, but it should still
// show-up in the statistics for the cache
cache.insertOrAssign(3, {"Non-checked-out key (3)"});
{
auto cacheInfo = cache.getCacheInfo();
std::sort(cacheInfo.begin(), cacheInfo.end(), [](auto a, auto b) { return a.key < b.key; });
ASSERT_EQ(4UL, cacheInfo.size());
ASSERT_EQ(0, cacheInfo[0].key);
ASSERT_EQ(1, cacheInfo[0].useCount);
ASSERT_EQ(1, cacheInfo[1].key);
ASSERT_EQ(2, cacheInfo[2].key);
ASSERT_EQ(3, cacheInfo[3].key);
}
// Invalidating the key, which was booted out due to cache size exceeded should still be
// reflected on the checked-out key
ASSERT(checkedOutKey.isValid());
cache.invalidateIf([](int key, TestValue* value) { return key == 0; });
ASSERT(!checkedOutKey.isValid());
{
auto cacheInfo = cache.getCacheInfo();
std::sort(cacheInfo.begin(), cacheInfo.end(), [](auto a, auto b) { return a.key < b.key; });
ASSERT_EQ(3UL, cacheInfo.size());
ASSERT_EQ(1, cacheInfo[0].key);
ASSERT_EQ(2, cacheInfo[1].key);
ASSERT_EQ(3, cacheInfo[2].key);
}
}
TEST(InvalidatingLRUCacheTest, CausalConsistencyPreservedForEvictedCheckedOutKeys) {
TestValueCacheCausallyConsistent cache(1);
auto key1ValueAtTS10 =
cache.insertOrAssignAndGet(1, TestValue("Key 1 - Value @ TS 10"), Timestamp(10));
// This will evict key 1, but we have a handle to it, so it will stay accessible on the evicted
// list
cache.insertOrAssign(2, TestValue("Key 2 - Value @ TS 20"), Timestamp(20));
auto [cachedValueAtTS10, timeInStoreAtTS10] = cache.getCachedValueAndTimeInStore(1);
ASSERT_EQ(Timestamp(10), timeInStoreAtTS10);
ASSERT_EQ("Key 1 - Value @ TS 10", cachedValueAtTS10->value);
ASSERT_EQ("Key 1 - Value @ TS 10", key1ValueAtTS10->value);
ASSERT_EQ("Key 1 - Value @ TS 10", cache.get(1, CacheCausalConsistency::kLatestCached)->value);
ASSERT_EQ("Key 1 - Value @ TS 10", cache.get(1, CacheCausalConsistency::kLatestKnown)->value);
ASSERT(cache.advanceTimeInStore(1, Timestamp(11)));
auto [cachedValueAtTS11, timeInStoreAtTS11] = cache.getCachedValueAndTimeInStore(1);
ASSERT_EQ(Timestamp(11), timeInStoreAtTS11);
ASSERT(!key1ValueAtTS10.isValid());
ASSERT_EQ("Key 1 - Value @ TS 10", cachedValueAtTS11->value);
ASSERT_EQ("Key 1 - Value @ TS 10", key1ValueAtTS10->value);
ASSERT_EQ("Key 1 - Value @ TS 10", cache.get(1, CacheCausalConsistency::kLatestCached)->value);
ASSERT(!cache.get(1, CacheCausalConsistency::kLatestKnown));
cache.insertOrAssign(1, TestValue("Key 1 - Value @ TS 12"), Timestamp(12));
ASSERT_EQ("Key 1 - Value @ TS 12", cache.get(1, CacheCausalConsistency::kLatestCached)->value);
ASSERT_EQ("Key 1 - Value @ TS 12", cache.get(1, CacheCausalConsistency::kLatestKnown)->value);
}
TEST(InvalidatingLRUCacheTest, InvalidateAfterAdvanceTime) {
TestValueCacheCausallyConsistent cache(1);
cache.insertOrAssign(20, TestValue("Value @ TS 200"), Timestamp(200));
ASSERT(cache.advanceTimeInStore(20, Timestamp(250)));
ASSERT_EQ("Value @ TS 200", cache.get(20, CacheCausalConsistency::kLatestCached)->value);
ASSERT(!cache.get(20, CacheCausalConsistency::kLatestKnown));
cache.invalidate(20);
ASSERT(!cache.get(20, CacheCausalConsistency::kLatestCached));
ASSERT(!cache.get(20, CacheCausalConsistency::kLatestKnown));
}
TEST(InvalidatingLRUCacheTest, InsertEntryAtTimeLessThanAdvanceTime) {
TestValueCacheCausallyConsistent cache(1);
cache.insertOrAssign(20, TestValue("Value @ TS 200"), Timestamp(200));
ASSERT(cache.advanceTimeInStore(20, Timestamp(300)));
ASSERT_EQ("Value @ TS 200", cache.get(20, CacheCausalConsistency::kLatestCached)->value);
ASSERT(!cache.get(20, CacheCausalConsistency::kLatestKnown));
cache.insertOrAssign(20, TestValue("Value @ TS 250"), Timestamp(250));
ASSERT_EQ("Value @ TS 250", cache.get(20, CacheCausalConsistency::kLatestCached)->value);
ASSERT(!cache.get(20, CacheCausalConsistency::kLatestKnown));
cache.insertOrAssign(20, TestValue("Value @ TS 300"), Timestamp(300));
ASSERT_EQ("Value @ TS 300", cache.get(20, CacheCausalConsistency::kLatestCached)->value);
ASSERT_EQ("Value @ TS 300", cache.get(20, CacheCausalConsistency::kLatestKnown)->value);
}
TEST(InvalidatingLRUCacheTest, OrderOfDestructionOfHandlesDiffersFromOrderOfInsertion) {
TestValueCache cache(1);
boost::optional<TestValueCache::ValueHandle> firstValue(
cache.insertOrAssignAndGet(100, {"Key 100, Value 1"}));
ASSERT(*firstValue);
ASSERT(firstValue->isValid());
// This will invalidate the first value of key 100
auto secondValue = cache.insertOrAssignAndGet(100, {"Key 100, Value 2"});
ASSERT(secondValue);
ASSERT(secondValue.isValid());
ASSERT(!firstValue->isValid());
// This will evict the second value of key 100
cache.insertOrAssignAndGet(200, {"Key 200, Value 1"});
ASSERT(secondValue);
ASSERT(secondValue.isValid());
ASSERT(!firstValue->isValid());
// This makes the first value of 100's handle go away before the second value's hande
firstValue.reset();
ASSERT(secondValue.isValid());
cache.invalidate(100);
ASSERT(!secondValue.isValid());
}
TEST(InvalidatingLRUCacheTest, AssignWhileValueIsCheckedOutInvalidatesFirstValue) {
TestValueCache cache(1);
auto firstGet = cache.insertOrAssignAndGet(100, {"First check-out of the key (100)"});
ASSERT(firstGet);
ASSERT(firstGet.isValid());
auto secondGet = cache.insertOrAssignAndGet(100, {"Second check-out of the key (100)"});
ASSERT(!firstGet.isValid());
ASSERT(secondGet);
ASSERT(secondGet.isValid());
ASSERT_EQ("Second check-out of the key (100)", secondGet->value);
}
TEST(InvalidatingLRUCacheTest, InvalidateIfAllEntries) {
TestValueCache cache(6);
for (int i = 0; i < 6; i++) {
cache.insertOrAssign(i, TestValue{str::stream() << "Test value " << i});
}
const std::vector checkedOutValues{cache.get(0), cache.get(1), cache.get(2)};
cache.invalidateIf([](int, TestValue*) { return true; });
}
TEST(InvalidatingLRUCacheTest, CacheSizeZero) {
TestValueCache cache(0);
{
auto immediatelyEvictedValue = cache.insertOrAssignAndGet(0, TestValue{"Evicted value"});
auto anotherImmediatelyEvictedValue =
cache.insertOrAssignAndGet(1, TestValue{"Another evicted value"});
ASSERT(immediatelyEvictedValue.isValid());
ASSERT(anotherImmediatelyEvictedValue.isValid());
ASSERT(cache.get(0));
ASSERT(cache.get(1));
ASSERT_EQ(2UL, cache.getCacheInfo().size());
ASSERT_EQ(1UL, cache.getCacheInfo()[0].useCount);
ASSERT_EQ(1UL, cache.getCacheInfo()[1].useCount);
}
ASSERT(!cache.get(0));
ASSERT(!cache.get(1));
ASSERT_EQ(0UL, cache.getCacheInfo().size());
}
TEST(InvalidatingLRUCacheTest, CacheSizeZeroInvalidate) {
TestValueCache cache(0);
auto immediatelyEvictedValue = cache.insertOrAssignAndGet(0, TestValue{"Evicted value"});
ASSERT(immediatelyEvictedValue.isValid());
ASSERT(cache.get(0));
ASSERT_EQ(1UL, cache.getCacheInfo().size());
ASSERT_EQ(1UL, cache.getCacheInfo()[0].useCount);
cache.invalidate(0);
ASSERT(!immediatelyEvictedValue.isValid());
ASSERT(!cache.get(0));
ASSERT_EQ(0UL, cache.getCacheInfo().size());
}
TEST(InvalidatingLRUCacheTest, CacheSizeZeroInvalidateAllEntries) {
TestValueCache cache(0);
std::vector<TestValueHandle> checkedOutValues;
for (int i = 0; i < 6; i++) {
checkedOutValues.emplace_back(
cache.insertOrAssignAndGet(i, TestValue{str::stream() << "Test value " << i}));
}
cache.invalidateIf([](int, TestValue*) { return true; });
for (auto&& value : checkedOutValues) {
ASSERT(!value.isValid()) << "Value " << value->value << " was not invalidated";
}
}
TEST(InvalidatingLRUCacheTest, CacheSizeZeroCausalConsistency) {
TestValueCacheCausallyConsistent cache(0);
ASSERT(cache.advanceTimeInStore(100, Timestamp(30)));
cache.insertOrAssign(100, TestValue("Value @ TS 30"), Timestamp(30));
auto [cachedValueAtTS30, timeInStoreAtTS30] = cache.getCachedValueAndTimeInStore(100);
ASSERT_EQ(Timestamp(), timeInStoreAtTS30);
ASSERT(!cachedValueAtTS30);
auto valueAtTS30 = cache.insertOrAssignAndGet(100, TestValue("Value @ TS 30"), Timestamp(30));
ASSERT_EQ("Value @ TS 30", cache.get(100, CacheCausalConsistency::kLatestCached)->value);
ASSERT_EQ("Value @ TS 30", cache.get(100, CacheCausalConsistency::kLatestKnown)->value);
ASSERT(cache.advanceTimeInStore(100, Timestamp(35)));
auto [cachedValueAtTS35, timeInStoreAtTS35] = cache.getCachedValueAndTimeInStore(100);
ASSERT_EQ(Timestamp(35), timeInStoreAtTS35);
ASSERT_EQ("Value @ TS 30", cachedValueAtTS35->value);
ASSERT_EQ("Value @ TS 30", cache.get(100, CacheCausalConsistency::kLatestCached)->value);
ASSERT(!cache.get(100, CacheCausalConsistency::kLatestKnown));
auto valueAtTS40 = cache.insertOrAssignAndGet(100, TestValue("Value @ TS 40"), Timestamp(40));
ASSERT_EQ("Value @ TS 40", cache.get(100, CacheCausalConsistency::kLatestCached)->value);
ASSERT_EQ("Value @ TS 40", cache.get(100, CacheCausalConsistency::kLatestKnown)->value);
}
TEST(InvalidatingLRUCacheTest, AdvanceTimeNoEntry) {
TestValueCacheCausallyConsistent cache(1);
// If there is no cached entry advanceTime will always return true
ASSERT(cache.advanceTimeInStore(100, Timestamp(30)));
ASSERT(cache.advanceTimeInStore(100, Timestamp(30)));
}
TEST(InvalidatingLRUCacheTest, AdvanceTimeSameTime) {
TestValueCacheCausallyConsistent cache(1);
cache.insertOrAssignAndGet(100, TestValue("Value @ TS 30"), Timestamp(30));
ASSERT(!cache.advanceTimeInStore(100, Timestamp(30)));
}
template <class TCache, typename TestFunc>
void parallelTest(size_t cacheSize, TestFunc doTest) {
constexpr auto kNumIterations = 100'000;
constexpr auto kNumThreads = 4;
TCache cache(cacheSize);
std::vector<stdx::thread> threads;
for (int i = 0; i < kNumThreads; i++) {
threads.emplace_back([&] {
for (int i = 0; i < kNumIterations / kNumThreads; i++) {
doTest(cache);
}
});
}
for (auto&& thread : threads) {
thread.join();
}
}
TEST(InvalidatingLRUCacheParallelTest, InsertOrAssignThenGet) {
parallelTest<TestValueCache>(1, [](auto& cache) {
const int key = 100;
cache.insertOrAssign(key, TestValue{"Parallel tester value"});
auto cachedItem = cache.get(key);
if (!cachedItem || !cachedItem.isValid())
return;
auto cachedItemSecondRef = cachedItem;
cache.invalidate(key);
ASSERT(!cachedItem.isValid());
ASSERT(!cachedItemSecondRef.isValid());
});
}
TEST(InvalidatingLRUCacheParallelTest, InsertOrAssignAndGet) {
parallelTest<TestValueCache>(1, [](auto& cache) {
const int key = 200;
auto cachedItem = cache.insertOrAssignAndGet(key, TestValue{"Parallel tester value"});
ASSERT(cachedItem);
auto cachedItemSecondRef = cache.get(key);
ASSERT(cachedItemSecondRef);
});
}
TEST(InvalidatingLRUCacheParallelTest, CacheSizeZeroInsertOrAssignAndGet) {
parallelTest<TestValueCache>(0, [](auto& cache) {
const int key = 300;
auto cachedItem = cache.insertOrAssignAndGet(key, TestValue{"Parallel tester value"});
ASSERT(cachedItem);
auto cachedItemSecondRef = cache.get(key);
});
}
TEST(InvalidatingLRUCacheParallelTest, AdvanceTime) {
AtomicWord<uint64_t> counter{1};
Mutex insertOrAssignMutex = MONGO_MAKE_LATCH("ReadThroughCacheBase::_cancelTokenMutex");
parallelTest<TestValueCacheCausallyConsistent>(0, [&](auto& cache) {
const int key = 300;
{
// The calls to insertOrAssign must always pass strictly incrementing time
stdx::lock_guard lg(insertOrAssignMutex);
cache.insertOrAssign(
key, TestValue{"Parallel tester value"}, Timestamp(counter.fetchAndAdd(1)));
}
auto latestCached = cache.get(key, CacheCausalConsistency::kLatestCached);
auto latestKnown = cache.get(key, CacheCausalConsistency::kLatestKnown);
ASSERT(cache.advanceTimeInStore(key, Timestamp(counter.fetchAndAdd(1))));
});
}
} // namespace
} // namespace mongo
|
{-# OPTIONS --warning=error --safe --without-K #-}
open import LogicalFormulae
open import Agda.Primitive using (Level; lzero; lsuc; _ā_)
open import Numbers.Naturals.Naturals
open import Numbers.Naturals.Order
open import Vectors
open import Semirings.Definition
open import Categories.Definition
open import Groups.Definition
open import Setoids.Setoids
open import Groups.Homomorphisms.Definition
open import Groups.Homomorphisms.Examples
open import Groups.Homomorphisms.Lemmas
open import Functions
module Categories.Examples where
SET : {a : _} ā Category {lsuc a} {a}
Category.objects (SET {a}) = Set a
Category.arrows (SET {a}) = Ī» a b ā (a ā b)
Category.id (SET {a}) = Ī» x ā Ī» y ā y
Category._ā_ (SET {a}) = Ī» f g ā Ī» x ā f (g x)
Category.rightId (SET {a}) = Ī» f ā refl
Category.leftId (SET {a}) = Ī» f ā refl
Category.compositionAssociative (SET {a}) = Ī» f g h ā refl
GROUP : {a b : _} ā Category {lsuc a ā lsuc b} {a ā b}
Category.objects (GROUP {a} {b}) = Sg (Set a) (Ī» A ā Sg (A ā A ā A) (Ī» _+_ ā Sg (Setoid {a} {b} A) (Ī» S ā Group S _+_)))
Category.arrows (GROUP {a}) (A , (_+A_ , (S , G))) (B , (_+B_ , (T , H))) = Sg (A ā B) (GroupHom G H)
Category.id (GROUP {a}) (A , (_+A_ , (S , G))) = (Ī» i ā i) , identityHom G
Category._ā_ (GROUP {a}) {A , (_+A_ , (S , G))} {B , (_+B_ , (T , H))} {C , (_+C_ , (U , I))} (f , fHom) (g , gHom) = (f ā g) , groupHomsCompose gHom fHom
Category.rightId (GROUP {a}) {A , (_+A_ , (S , G))} {B , (_+B_ , (T , H))} (f , fHom) = {!!}
Category.leftId (GROUP {a}) {A , (_+A_ , (S , G))} {B , (_+B_ , (T , H))} (f , fHom) = {!!}
Category.compositionAssociative (GROUP {a}) = {!!}
DISCRETE : {a : _} (X : Set a) ā Category {a} {a}
Category.objects (DISCRETE X) = X
Category.arrows (DISCRETE X) = Ī» a b ā a ā” b
Category.id (DISCRETE X) = Ī» x ā refl
Category._ā_ (DISCRETE X) = Ī» y=z x=y ā transitivity x=y y=z
Category.rightId (DISCRETE X) refl = refl
Category.leftId (DISCRETE X) refl = refl
Category.compositionAssociative (DISCRETE X) refl refl refl = refl
|
/-
Copyright (c) 2023 David Loeffler. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Loeffler
-/
import analysis.special_functions.complex.circle
import measure_theory.group.integration
import measure_theory.integral.integral_eq_improper
/-!
# The Fourier transform
We set up the Fourier transform for complex-valued functions on finite-dimensional spaces.
## Design choices
In namespace `vector_fourier`, we define the Fourier integral in the following context:
* `š` is a commutative ring.
* `V` and `W` are `š`-modules.
* `e` is a unitary additive character of `š`, i.e. a homomorphism `(multiplicative š) ā* circle`.
* `μ` is a measure on `V`.
* `L` is a `š`-bilinear form `V Ć W ā š`.
* `E` is a complete normed `ā`-vector space.
With these definitions, we define `fourier_integral` to be the map from functions `V ā E` to
functions `W ā E` that sends `f` to
`Ī» w, ā« v in V, e [-L v w] ⢠f v āμ`,
where `e [x]` is notational sugar for `(e (multiplicative.of_add x) : ā)` (available in locale
`fourier_transform`). This includes the cases `W` is the dual of `V` and `L` is the canonical
pairing, or `W = V` and `L` is a bilinear form (e.g. an inner product).
In namespace `fourier`, we consider the more familiar special case when `V = W = š` and `L` is the
multiplication map (but still allowing `š` to be an arbitrary ring equipped with a measure).
The most familiar case of all is when `V = W = š = ā`, `L` is multiplication, `μ` is volume, and
`e` is `real.fourier_char`, i.e. the character `Ī» x, exp ((2 * Ļ * x) * I)`. The Fourier integral
in this case is defined as `real.fourier_integral`.
## Main results
At present the only nontrivial lemma we prove is `continuous_fourier_integral`, stating that the
Fourier transform of an integrable function is continuous (under mild assumptions).
-/
noncomputable theory
local notation `š` := circle
open measure_theory filter
open_locale topology
-- To avoid messing around with multiplicative vs. additive characters, we make a notation.
localized "notation e `[` x `]` := (e (multiplicative.of_add x) : ā)" in fourier_transform
/-! ## Fourier theory for functions on general vector spaces -/
namespace vector_fourier
variables
{š : Type*} [comm_ring š]
{V : Type*} [add_comm_group V] [module š V] [measurable_space V]
{W : Type*} [add_comm_group W] [module š W]
{E : Type*} [normed_add_comm_group E] [normed_space ā E]
section defs
variables [complete_space E]
/-- The Fourier transform integral for `f : V ā E`, with respect to a bilinear form `L : V Ć W ā š`
and an additive character `e`. -/
def fourier_integral
(e : (multiplicative š) ā* š) (μ : measure V) (L : V āā[š] W āā[š] š)
(f : V ā E) (w : W) : E :=
ā« v, e [-L v w] ⢠f v āμ
lemma fourier_integral_smul_const
(e : (multiplicative š) ā* š) (μ : measure V) (L : V āā[š] W āā[š] š)
(f : V ā E) (r : ā) :
fourier_integral e μ L (r ⢠f) = r ⢠(fourier_integral e μ L f) :=
begin
ext1 w,
simp only [pi.smul_apply, fourier_integral, smul_comm _ r, integral_smul],
end
/-- The uniform norm of the Fourier integral of `f` is bounded by the `L¹` norm of `f`. -/
lemma fourier_integral_norm_le (e : (multiplicative š) ā* š) {μ : measure V}
(L : V āā[š] W āā[š] š) {f : V ā E} (hf : integrable f μ) (w : W) :
āfourier_integral e μ L f wā ⤠āhf.to_L1 fā :=
begin
rw L1.norm_of_fun_eq_integral_norm,
refine (norm_integral_le_integral_norm _).trans (le_of_eq _),
simp_rw [norm_smul, complex.norm_eq_abs, abs_coe_circle, one_mul],
end
/-- The Fourier integral converts right-translation into scalar multiplication by a phase factor.-/
lemma fourier_integral_comp_add_right [has_measurable_add V]
(e : (multiplicative š) ā* š) (μ : measure V) [μ.is_add_right_invariant]
(L : V āā[š] W āā[š] š) (f : V ā E) (vā : V) :
fourier_integral e μ L (f ā (Ī» v, v + vā)) = Ī» w, e [L vā w] ⢠fourier_integral e μ L f w :=
begin
ext1 w,
dsimp only [fourier_integral, function.comp_apply],
conv in (L _) { rw āadd_sub_cancel v vā },
rw integral_add_right_eq_self (Ī» (v : V), e [-L (v - vā) w] ⢠f v),
swap, apply_instance,
dsimp only,
rw āintegral_smul,
congr' 1 with v,
rw [āsmul_assoc, smul_eq_mul, āsubmonoid.coe_mul, āe.map_mul, āof_add_add, ālinear_map.neg_apply,
āsub_eq_add_neg, ālinear_map.sub_apply, linear_map.map_sub, neg_sub]
end
end defs
section continuous
/- In this section we assume š, V, W have topologies, and L, e are continuous (but f needn't be).
This is used to ensure that `e [-L v w]` is (ae strongly) measurable. We could get away with
imposing only a measurable-space structure on š (it doesn't have to be the Borel sigma-algebra of
a topology); but it seems hard to imagine cases where this extra generality would be useful, and
allowing it would complicate matters in the most important use cases.
-/
variables [topological_space š] [topological_ring š] [topological_space V] [borel_space V]
[topological_space W] {e : (multiplicative š) ā* š} {μ : measure V} {L : V āā[š] W āā[š] š}
/-- If `f` is integrable, then the Fourier integral is convergent for all `w`. -/
lemma fourier_integral_convergent
(he : continuous e) (hL : continuous (Ī» p : V Ć W, L p.1 p.2))
{f : V ā E} (hf : integrable f μ) (w : W) :
integrable (λ (v : V), (e [-L v w]) ⢠f v) μ :=
begin
rw continuous_induced_rng at he,
have c : continuous (Ī» v, e[-L v w]),
{ refine he.comp (continuous_of_add.comp (continuous.neg _)),
exact hL.comp (continuous_prod_mk.mpr āØcontinuous_id, continuous_constā©) },
rw āintegrable_norm_iff (c.ae_strongly_measurable.smul hf.1),
convert hf.norm,
ext1 v,
rw [norm_smul, complex.norm_eq_abs, abs_coe_circle, one_mul]
end
variables [complete_space E]
lemma fourier_integral_add
(he : continuous e) (hL : continuous (Ī» p : V Ć W, L p.1 p.2))
{f g : V ā E} (hf : integrable f μ) (hg : integrable g μ) :
(fourier_integral e μ L f) + (fourier_integral e μ L g) = fourier_integral e μ L (f + g) :=
begin
ext1 w,
dsimp only [pi.add_apply, fourier_integral],
simp_rw smul_add,
rw integral_add,
{ exact fourier_integral_convergent he hL hf w },
{ exact fourier_integral_convergent he hL hg w },
end
/-- The Fourier integral of an `L^1` function is a continuous function. -/
lemma fourier_integral_continuous [topological_space.first_countable_topology W]
(he : continuous e) (hL : continuous (Ī» p : V Ć W, L p.1 p.2))
{f : V ā E} (hf : integrable f μ) :
continuous (fourier_integral e μ L f) :=
begin
apply continuous_of_dominated,
{ exact Ī» w, (fourier_integral_convergent he hL hf w).1 },
{ refine Ī» w, ae_of_all _ (Ī» v, _),
{ exact Ī» v, āf vā },
{ rw [norm_smul, complex.norm_eq_abs, abs_coe_circle, one_mul] } },
{ exact hf.norm },
{ rw continuous_induced_rng at he,
refine ae_of_all _ (Ī» v, (he.comp (continuous_of_add.comp _)).smul continuous_const),
refine (hL.comp (continuous_prod_mk.mpr āØcontinuous_const, continuous_idā©)).neg }
end
end continuous
end vector_fourier
/-! ## Fourier theory for functions on `š` -/
namespace fourier
variables {š : Type*} [comm_ring š] [measurable_space š]
{E : Type*} [normed_add_comm_group E] [normed_space ā E]
section defs
variables [complete_space E]
/-- The Fourier transform integral for `f : š ā E`, with respect to the measure `μ` and additive
character `e`. -/
def fourier_integral
(e : (multiplicative š) ā* š) (μ : measure š) (f : š ā E) (w : š) : E :=
vector_fourier.fourier_integral e μ (linear_map.mul š š) f w
lemma fourier_integral_def (e : (multiplicative š) ā* š) (μ : measure š) (f : š ā E) (w : š) :
fourier_integral e μ f w = ā« (v : š), e[-(v * w)] ⢠f v āμ :=
rfl
lemma fourier_integral_smul_const
(e : (multiplicative š) ā* š) (μ : measure š) (f : š ā E) (r : ā) :
fourier_integral e μ (r ⢠f) = r ⢠(fourier_integral e μ f) :=
vector_fourier.fourier_integral_smul_const _ _ _ _ _
/-- The uniform norm of the Fourier transform of `f` is bounded by the `L¹` norm of `f`. -/
lemma fourier_integral_norm_le (e : (multiplicative š) ā* š) {μ : measure š}
{f : š ā E} (hf : integrable f μ) (w : š) :
āfourier_integral e μ f wā ⤠āhf.to_L1 fā :=
vector_fourier.fourier_integral_norm_le _ _ _ _
/-- The Fourier transform converts right-translation into scalar multiplication by a phase factor.-/
lemma fourier_integral_comp_add_right [has_measurable_add š]
(e : (multiplicative š) ā* š) (μ : measure š) [μ.is_add_right_invariant] (f : š ā E) (vā : š) :
fourier_integral e μ (f ā (Ī» v, v + vā)) = Ī» w, e [vā * w] ⢠fourier_integral e μ f w :=
vector_fourier.fourier_integral_comp_add_right _ _ _ _ _
end defs
end fourier
open_locale real
namespace real
/-- The standard additive character of `ā`, given by `Ī» x, exp (2 * Ļ * x * I)`. -/
def fourier_char : (multiplicative ā) ā* š :=
{ to_fun := Ī» z, exp_map_circle (2 * Ļ * z.to_add),
map_one' := by rw [to_add_one, mul_zero, exp_map_circle_zero],
map_mul' := Ī» x y, by rw [to_add_mul, mul_add, exp_map_circle_add] }
lemma fourier_char_apply (x : ā) :
real.fourier_char [x] = complex.exp (ā(2 * Ļ * x) * complex.I) :=
by refl
@[continuity]
lemma continuous_fourier_char : continuous real.fourier_char :=
(map_continuous exp_map_circle).comp (continuous_const.mul continuous_to_add)
variables {E : Type*} [normed_add_comm_group E] [complete_space E] [normed_space ā E]
lemma vector_fourier_integral_eq_integral_exp_smul
{V : Type*} [add_comm_group V] [module ā V] [measurable_space V]
{W : Type*} [add_comm_group W] [module ā W]
(L : V āā[ā] W āā[ā] ā) (μ : measure V) (f : V ā E) (w : W) :
vector_fourier.fourier_integral fourier_char μ L f w
= ā« (v : V), complex.exp (ā(-2 * Ļ * L v w) * complex.I) ⢠f v āμ :=
by simp_rw [vector_fourier.fourier_integral, real.fourier_char_apply, mul_neg, neg_mul]
/-- The Fourier integral for `f : ā ā E`, with respect to the standard additive character and
measure on `ā`. -/
def fourier_integral (f : ā ā E) (w : ā) := fourier.fourier_integral fourier_char volume f w
lemma fourier_integral_def (f : ā ā E) (w : ā) :
fourier_integral f w = ā« (v : ā), fourier_char [-(v * w)] ⢠f v :=
rfl
localized "notation (name := fourier_integral) `š` := real.fourier_integral" in fourier_transform
lemma fourier_integral_eq_integral_exp_smul
{E : Type*} [normed_add_comm_group E] [complete_space E] [normed_space ā E]
(f : ā ā E) (w : ā) :
š f w = ā« (v : ā), complex.exp (ā(-2 * Ļ * v * w) * complex.I) ⢠f v :=
by simp_rw [fourier_integral_def, real.fourier_char_apply, mul_neg, neg_mul, mul_assoc]
end real
|
[STATEMENT]
theorem HEndPhase0_HInv4c:
"\<lbrakk> HEndPhase0 s s' p; HInv4c s q\<rbrakk> \<Longrightarrow> HInv4c s' q"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>HEndPhase0 s s' p; HInv4c s q\<rbrakk> \<Longrightarrow> HInv4c s' q
[PROOF STEP]
by(blast dest: HEndPhase0_HInv4c_p HEndPhase0_HInv4c_q) |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
module FokkerPlanck.BrownianMotion
( Particle(..)
, generatePath
, moveParticle
, thetaPlus
, scalePlus
, generateRandomNumber
, generatePath'
) where
import Control.DeepSeq
import Control.Monad
import Data.DList as DL
import Data.Ix
import Data.List as L
import GHC.Generics (Generic)
import Statistics.Distribution
import Statistics.Distribution.Exponential
import Statistics.Distribution.Normal
import Statistics.Distribution.Uniform
import System.Random.MWC
import Text.Printf
import Utils.Distribution
data Particle =
Particle {-# UNPACK #-}!Double -- \phi
{-# UNPACK #-}!Double -- \rho
{-# UNPACK #-}!Double -- \theta
{-# UNPACK #-}!Double -- r
{-# UNPACK #-}!Double -- weight
deriving (Show,Generic)
instance NFData Particle
{-# INLINE getParticleRho #-}
getParticleRho :: Particle -> Double
getParticleRho (Particle _ rho _ _ _ ) = rho
thetaCheck :: Double -> Double
thetaCheck theta =
if theta < -pi
then thetaCheck (theta + 2 * pi)
else if theta >= pi
then thetaCheck (theta - 2 * pi)
else theta
{-# INLINE scaleCheck #-}
scaleCheck :: Double -> Double -> Double
scaleCheck maxScale scale =
if scale >= (1 / maxScale) && scale <= maxScale
then scale
else error
(printf
"scaleCheck: %.2f is out of boundary (0,%.2f)\n"
scale
maxScale)
{-# INLINE thetaPlus #-}
thetaPlus :: Double -> Double -> Double
thetaPlus !x !y =
let z = x + y
in thetaCheck z
{-# INLINE scalePlus #-}
scalePlus :: Double -> Double -> Double
scalePlus x delta = x * exp delta
{-# INLINE scalePlusPeriodic #-}
scalePlusPeriodic :: Double -> Double -> Double -> Double
scalePlusPeriodic !logMaxScale !delta !x
| z >= m = exp (z - 2 * m)
| z < -m = exp (2 * m + z)
| otherwise = exp z
where
!m = logMaxScale
!z = log x + delta
{-# INLINE rhoCutoff #-}
rhoCutoff :: Double -> Double
rhoCutoff !rho =
if rho < 0
then 0
else rho
{-# INLINE generateRandomNumber #-}
generateRandomNumber ::
(Distribution d, ContGen d) => GenIO -> Maybe d -> IO Double
generateRandomNumber !gen dist =
case dist of
Nothing -> return 0
Just d -> genContVar d gen
{-# INLINE moveParticle #-}
moveParticle :: Double -> Particle -> Particle
moveParticle deltaT (Particle phi rho theta r0 v) =
let !r = r0 * deltaT
!x = theta - phi
!cosX = cos x
!newPhi = phi `thetaPlus` atan2 (r * sin x) (rho + r * cosX)
!newRho = sqrt (rho * rho + r * r + 2 * r * rho * cosX)
in Particle newPhi newRho theta r0 v
{-# INLINE diffuseParticle #-}
diffuseParticle :: Double -> Double -> Double -> Particle -> Particle
diffuseParticle !deltaTheta !deltaScale maxScale (Particle phi rho theta r v) =
Particle
phi
rho
(theta `thetaPlus` deltaTheta)
(r `scalePlus` deltaScale)
v
brownianMotion ::
(Distribution d1, ContGen d1, Distribution d2, ContGen d2, Distribution d3)
=> GenIO
-> Maybe d1
-> Maybe d2
-> Maybe d3
-> Double
-> Double
-> Double
-> Double
-> Double
-> Particle
-> DList Particle
-> IO (DList Particle)
brownianMotion randomGen thetaDist scaleDist poissonDist deltaT maxRho maxR tao stdR2 particle xs = do
deltaTheta <- generateRandomNumber randomGen thetaDist
deltaScale <- generateRandomNumber randomGen scaleDist
let newParticle@(Particle phi rho theta r v) = moveParticle deltaT particle
ys =
if r <= maxR && r > 1 / maxR && rho <= maxRho && rho >= 1 / maxRho
then DL.cons
(Particle phi rho theta r (1 - gaussian2DPolar rho stdR2))
xs
else xs
t <- genContVar (uniformDistr 0 1) randomGen :: IO Double
if t > exp (1 / (-tao))
then return ys
else brownianMotion
randomGen
thetaDist
scaleDist
poissonDist
deltaT
maxRho
maxR
tao
stdR2
(diffuseParticle deltaTheta deltaScale maxR newParticle)
ys
{-# INLINE generatePath #-}
generatePath ::
(Distribution d1, ContGen d1, Distribution d2, ContGen d2, Distribution d3)
=> Maybe d1
-> Maybe d2
-> Maybe d3
-> Double
-> Double
-> Double
-> Double
-> Double
-> GenIO
-> IO (DList Particle)
generatePath thetaDist scaleDist poissonDist maxRho maxR tao deltaT stdR2 randomGen =
brownianMotion
randomGen
thetaDist
scaleDist
poissonDist
deltaT
maxRho
maxR
tao
stdR2
(Particle 0 1 0 1 1)
DL.empty
{-# INLINE moveParticle' #-}
moveParticle' :: Particle -> Particle
moveParticle' (Particle phi rho theta r v) =
let !x = theta - phi
!cosX = cos x
!newPhi = phi `thetaPlus` atan2 (r * sin x) (rho + r * cosX)
!newRho = sqrt (rho * rho + r * r + 2 * r * rho * cosX)
in Particle newPhi newRho theta r v
{-# INLINE diffuseParticle' #-}
diffuseParticle' :: (Distribution d, ContGen d)
=> GenIO -> Double -> Maybe d -> Double -> Particle -> IO Particle
diffuseParticle' randomGen thetaSigma scaleDist deltaT (Particle phi rho theta r v) = do
deltaScale <- generateRandomNumber randomGen scaleDist
let r1 = r `scalePlus` deltaScale
deltaTheta <-
genContVar (normalDistr 0 (thetaSigma * sqrt (r1 * deltaT))) randomGen
return $ Particle phi rho (theta `thetaPlus` deltaTheta) r1 v
brownianMotion' ::
(Distribution d, ContGen d)
=> GenIO
-> Double
-> Maybe d
-> Double
-> Double
-> Double
-> Double
-> Double
-> Double
-> Particle
-> DList Particle
-> IO (DList Particle)
brownianMotion' randomGen thetaSigma scaleDist poissonLambda deltaT maxRho maxR tao stdR2 particle xs = do
let newParticle@(Particle phi rho theta r v) = moveParticle deltaT particle
ys =
if r <= maxR && r > 1 / maxR && rho <= maxRho && rho >= 1 / maxRho
then DL.cons (Particle phi rho theta r (1 - gaussian2DPolar rho stdR2)) xs
else xs
t <- genContVar (uniformDistr 0 1) randomGen :: IO Double
if t > exp (1 / (-tao / (r * deltaT)))
then return ys
else do
diffusedParticle <-
diffuseParticle' randomGen thetaSigma scaleDist deltaT newParticle
brownianMotion'
randomGen
thetaSigma
scaleDist
poissonLambda
deltaT
maxRho
maxR
tao
stdR2
diffusedParticle
ys
{-# INLINE generatePath' #-}
generatePath' ::
(Distribution d, ContGen d)
=> Double
-> Maybe d
-> Double
-> Double
-> Double
-> Double
-> Double
-> Double
-> GenIO
-> IO (DList Particle)
generatePath' thetaSigma scaleDist poissonLambda maxRho maxR tao deltaT stdR2 randomGen = do
brownianMotion'
randomGen
thetaSigma
scaleDist
poissonLambda
deltaT
maxRho
maxR
tao
stdR2
(Particle 0 1 0 1 1)
DL.empty
|
subroutine compute_b(A,Nx,B)
implicit none
integer Nx
real*8 A(Nx)
real*8 B(Nx)
integer i
do i=1,Nx,1
B(i) = 1.0D0/dsqrt(A(i))
end do
END
|
# MIT License
#
# Copyright (c) 2018 Martin Biel
#
# 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.
"""
SerialExecution
Functor object for using serial execution in a progressive-hedging algorithm. Create by supplying a [`Serial`](@ref) object through `execution` in the `ProgressiveHedgingSolver` factory function and then pass to a `StochasticPrograms.jl` model.
"""
struct SerialExecution{T <: AbstractFloat,
A <: AbstractVector,
PT <: AbstractPenaltyTerm} <: AbstractProgressiveHedgingExecution
subproblems::Vector{SubProblem{T,A,PT}}
function SerialExecution(::Type{T}, ::Type{A}, ::Type{PT}) where {T <: AbstractFloat, A <: AbstractVector, PT <: AbstractPenaltyTerm}
return new{T,A,PT}(Vector{SubProblem{T,A,PT}}())
end
end
function initialize_subproblems!(ph::AbstractProgressiveHedging,
execution::SerialExecution{T},
scenarioproblems::ScenarioProblems,
penaltyterm::AbstractPenaltyTerm) where T <: AbstractFloat
# Create subproblems
for i = 1:num_subproblems(scenarioproblems)
push!(execution.subproblems, SubProblem(
subproblem(scenarioproblems, i),
i,
T(probability(scenarioproblems, i)),
copy(penaltyterm)))
end
# Initial reductions
update_iterate!(ph)
update_dual_gap!(ph)
return nothing
end
function finish_initilization!(execution::SerialExecution, penalty::AbstractFloat)
for subproblem in execution.subproblems
initialize!(subproblem, penalty)
end
return nothing
end
function restore_subproblems!(ph::AbstractProgressiveHedging, execution::SerialExecution)
for subproblem in execution.subproblems
restore_subproblem!(subproblem)
end
return nothing
end
function resolve_subproblems!(ph::AbstractProgressiveHedging, execution::SerialExecution)
Qs = Vector{SubproblemSolution}(undef, length(execution.subproblems))
# Reformulate and solve sub problems
for (i, subproblem) in enumerate(execution.subproblems)
reformulate_subproblem!(subproblem, ph.ξ, penalty(ph))
Qs[i] = subproblem(ph.ξ)
end
# Return current objective value
return sum(Qs)
end
function update_iterate!(ph::AbstractProgressiveHedging, execution::SerialExecution)
# Update the estimate
ξ_prev = copy(ph.ξ)
ph.ξ .= mapreduce(+, execution.subproblems, init = zero(ph.ξ)) do subproblem
Ļ = subproblem.probability
x = subproblem.x
Ļ * x
end
# Update Ī“ā
ph.data.Ī“ā = norm(ph.ξ - ξ_prev, 2) ^ 2
return nothing
end
function update_subproblems!(ph::AbstractProgressiveHedging, execution::SerialExecution)
# Update dual prices
update_subproblems!(execution.subproblems, ph.ξ, penalty(ph))
return nothing
end
function update_dual_gap!(ph::AbstractProgressiveHedging, execution::SerialExecution{T}) where T <: AbstractFloat
# Update Ī“ā
ph.data.Ī“ā = mapreduce(+, execution.subproblems, init = zero(T)) do subproblem
Ļ = subproblem.probability
x = subproblem.x
Ļ * norm(x - ph.ξ, 2) ^ 2
end
return nothing
end
function calculate_objective_value(ph::AbstractProgressiveHedging, execution::SerialExecution{T}) where T <: AbstractFloat
return mapreduce(+, execution.subproblems, init = zero(T)) do subproblem
_objective_value(subproblem)
end
end
function scalar_subproblem_reduction(value::Function, execution::SerialExecution{T}) where T <: AbstractFloat
return mapreduce(+, execution.subproblems, init = zero(T)) do subproblem
Ļ = subproblem.probability
return Ļ * value(subproblem)
end
end
function vector_subproblem_reduction(value::Function, execution::SerialExecution{T}, n::Integer) where T <: AbstractFloat
return mapreduce(+, execution.subproblems, init = zero(T, n)) do subproblem
Ļ = subproblem.probability
return Ļ * value(subproblem)
end
end
# API
# ------------------------------------------------------------
function (execution::Serial)(::Type{T}, ::Type{A}, ::Type{PT}) where {T <: AbstractFloat, A <: AbstractVector, PT <: AbstractPenaltyTerm}
return SerialExecution(T, A, PT)
end
function str(::Serial)
return ""
end
|
Set Implicit Arguments.
Set Bullet Behavior "Strict Subproofs".
From Utils Require Import Base Booleans Eqb Default.
Section __.
Context (A : Type)
`{Eqb_ok A}.
Lemma invert_none_some (x : A)
: None = Some x <-> False.
Proof.
solve_invert_constr_eq_lemma.
Qed.
Hint Rewrite invert_none_some : utils.
Lemma invert_some_none (x : A)
: Some x = None <-> False.
Proof.
solve_invert_constr_eq_lemma.
Qed.
Hint Rewrite invert_some_none : utils.
Lemma invert_some_some (x y : A)
: Some x = Some y <-> x = y.
Proof. solve_invert_constr_eq_lemma. Qed.
Hint Rewrite invert_some_some : utils.
#[export] Instance option_eqb : Eqb (option A) :=
fun a b =>
match a, b with
| Some a, Some b => eqb a b
| None, None => true
| _, _ => false
end.
#[export] Instance option_eqb_ok : Eqb_ok option_eqb.
Proof.
unfold Eqb_ok, option_eqb, eqb.
intros a b;
destruct a;
destruct b;
basic_goal_prep;
basic_utils_crush.
pose proof (H0 a a0) as H'.
unfold eqb in *.
revert H'.
case_match;
basic_utils_crush.
Qed.
#[export] Instance option_default : WithDefault (option A) := None.
End __.
#[export] Hint Rewrite invert_none_some : utils.
#[export] Hint Rewrite invert_some_none : utils.
#[export] Hint Rewrite invert_some_some : utils.
|
PROGRAM Qfep
! #DES: Program to produce and write the FEP/US calculation data in Qfep format. (SIC throughout)
USE Util, ONLY : Startup, Cleanup
USE Data, ONLY : ComputeDerivedData
USE Log, ONLY : logUnit
IMPLICIT NONE
INTEGER, PARAMETER :: outUnit = 64
CALL Startup(readCoords=.FALSE.)
CALL ComputeDerivedData(logUnit,doTiming=.FALSE.,readCoords=.FALSE.,doFEPUS=.TRUE.)
CALL QFepAnalysis()
CALL CleanUp()
CONTAINS
!Run the 3-stage analysis of the simulation data as in qfep
SUBROUTINE QfepAnalysis()
! #DES: Master routine: create a Qfep log file, do the analyses and write the output.
USE FileIO, ONLY : OpenFile, CloseFile
USE Log, ONLY : logUnit
IMPLICIT NONE
WRITE(logUnit,'(A)') "Performing qfep analysis - output to QFEPstyle.log"
WRITE(logUnit,*)
CALL OpenFile(outUnit,"QFEPstyle.log","write")
WRITE(outUnit,'(A)') "Qfep-style output generated by Fepcat (NB: small numerical differences with Qfep output may be observed)"
WRITE(outUnit,*) ""
CALL WriteParameters()
CALL AnalyzeDynamics_Q()
CALL AnalyzeFEP_Q()
CALL AnalyzeFepUs_Q()
CALL CloseFile(outUnit)
END SUBROUTINE QfepAnalysis
!*
SUBROUTINE WriteParameters()
USE Input, ONLY : nFepSteps, stateA, stateB, nStates, nSkip, nBins, minPop, rcCoeffA, rcCoeffB, alpha, beta
IMPLICIT NONE
WRITE(outUnit,'(A27)') "--> Number of energy files:"
WRITE(outUNit,'(A20,I4)') "# Number of files = ", nFepSteps
WRITE(outUnit,'(A55)') "--> No. of states, no. of predefined off-diag elements:"
WRITE(outUnit,'(A21,I4)') "# Number of states = ", nStates
WRITE(outUnit,'(A36,I4)') "# Number of off-diagonal elements = ", 0
WRITE(outUnit,'(A54)') "--> Give kT & no, of pts to skip & calculation mode:"
WRITE(outUnit,'(A7,F7.3)') "# kT = ", 1.0d0 / beta
WRITE(outUnit,'(A34,I6)') "# Number of data points to skip = ", nSkip
WRITE(outUnit,'(A44,L1)') "# Only QQ interactions will be considered = ", .FALSE.
WRITE(outUnit,'(A28)') "--> Give number of gap-bins:"
WRITE(outUnit,'(A23,I4)') "# Number of gap-bins = ", nBins
WRITE(outUnit,'(A27)') "--> Give minimum # pts/bin:"
WRITE(outUnit,'(A37,I4)') "# Minimum number of points per bin = ", minPop
WRITE(outUnit,'(A27)') "--> Give alpha for state 2:"
WRITE(outUnit,'(A22,F7.2)') "# Alpha for state 2 = ", alpha(stateB) - alpha(stateA)
WRITE(outUnit,'(A16)') "--> Hij scaling:"
WRITE(outUNit,'(A25,F7.2)') "# Scale factor for Hij = ", 1.0d0
WRITE(outUnit,'(A57)') "--> linear combination of states defining reaction coord:"
WRITE(outUnit,'(A37,2F7.2)') "# Linear combination co-efficients = ", rcCoeffA, rcCoeffB
WRITE(outUnit,*); WRITE(outUnit,*)
END SUBROUTINE WriteParameters
!*
SUBROUTINE AnalyzeDynamics_Q()
! #DES: Reproduce the output simulation data table of Q (same data, slightly different format)
USE Input, ONLY : energyNames, stateEnergy, coeffs, mask, CreateFileNames, fileBase, nFepSteps
USE StatisticalFunctions, ONLY : mean
IMPLICIT NONE
INTEGER :: name, fepstep, state, type
CHARACTER(500) :: fileNames(nFepSteps)
CALL CreateFileNames('en',fileBase,fileNames)
WRITE(outUnit,'(A)') "# Part 0: Average energies for all states in all files"
WRITE(outUnit,'(A9,1X,A5,1X,A8,1X,A9)',ADVANCE='NO') "FEP Index", "State", "Points", "Coeff"
DO name = 1, SIZE(energyNames) !nEnergyTypes
WRITE(outUnit,'(A11)',ADVANCE='NO') energyNames(name)
ENDDO
WRITE(outUnit,*)
DO fepstep = 1, SIZE(stateEnergy,2) !nFepSteps
DO state = 1, SIZE(stateEnergy,3) !nStates
WRITE(outUnit,'(A,1X,I5,1X,I8,1X,F9.6)',ADVANCE='NO') TRIM(ADJUSTL(fileNames(fepstep))), state, COUNT(mask(fepstep,:)), coeffs(1,fepstep,state)
DO type = 1, SIZE(energyNames)
WRITE(outUnit,'(F11.2)',ADVANCE='NO') mean( stateEnergy(:,fepstep,state,type),mask=mask(fepstep,:) )
ENDDO
WRITE(outUnit,*)
ENDDO
WRITE(outUnit,*)
ENDDO
ENDSUBROUTINE AnalyzeDynamics_Q
!*
! Compute and print the output of the FEP procedure in Q format
SUBROUTINE AnalyzeFep_Q()
USE Data, ONLY : mappingEnergies
USE Input, ONLY : stateA, coeffs, nFepSteps, mask
USE FreeEnergy, ONLY : ComputeFEPIncrements
IMPLICIT NONE
REAL(8) :: forward(nFepSteps-1), reverse(nFepSteps-1), profile(nFepSteps-1)
REAL(8) :: deltaG_f(nFepSteps), deltaG_r(nFepSteps), deltaG(nFepSteps)
INTEGER :: fepstep
CALL ComputeFEPIncrements(1,nFepSteps,mappingEnergies(:,:,:,1),mask(:,:),forward,reverse,profile)
WRITE(outUnit,'(A43)') "# Part 1: Free energy perturbation summary:"
WRITE(outUnit,*) ""
WRITE(outUnit,'(A)') "# Calculation for full system"
WRITE(outUnit,'(A)') "# lambda(1) dGf sum(dGf) dGr sum(dGr) <dG>"
deltaG_f(:) = 0.0d0
deltaG(:) = 0.0d0
!1st value is 0 in each
DO fepstep = 2, nFepSteps
deltaG_f(fepstep) = forward(fepstep-1)
deltaG(fepstep) = profile(fepstep-1)
ENDDO
!final value is 0
deltaG_r(:) = 0.0d0
DO fepstep = 1, nFepSteps - 1
deltaG_r(fepstep) = reverse(fepstep)
ENDDO
DO fepstep = 1, nFepSteps
WRITE(outUnit,'(2X,F9.6,5F9.3)') coeffs(1,fepstep,stateA), deltaG_f(fepstep), SUM(deltaG_f(1:fepstep)) , &
& deltaG_r(fepstep), SUM(deltaG_r(fepstep:nFepSteps)), &
& SUM(deltaG(1:fepstep))
ENDDO
WRITE(outUnit,*)
ENDSUBROUTINE AnalyzeFep_Q
!*
! Compute and print the output of the FEP/US procedure in Q format
SUBROUTINE AnalyzeFepUs_Q()
USE Data, ONLY : energyGap, mappingEnergies, groundStateEnergy, lambda
USE Input, ONLY : Nbins, minPop, stateA, stateB, stateEnergy, mask
USE FreeEnergy, ONLY : Histogram, ComputeFepProfile, FepUS
IMPLICIT NONE
INTEGER :: bin, step, binPopulations(Nbins,SIZE(energyGap,1)), binIndices(SIZE(energyGap,1),SIZE(energyGap,2))
REAL(8) :: binMidpoints(Nbins)
REAL(8) :: dGg(Nbins,SIZE(energyGap,1)), dGa(Nbins,SIZE(energyGap,1)), dGb(Nbins,SIZE(energyGap,1))
REAL(8) :: binG(Nbins)
REAL(8) :: G_FEP(SIZE(energyGap,1))
INTEGER :: count
WRITE(outUnit,'(A20,F7.2)') "# Min energy-gap is:", MINVAL(energyGap(:,:))
WRITE(outUnit,'(A20,F7.2)') "# Max energy-gap is:", MAXVAL(energyGap(:,:))
WRITE(outUnit,*); WRITE(outUnit,*); WRITE(outUnit,*)
WRITE(outUnit,'(A39)') "# Part 2: Reaction free energy summary:"
WRITE(outUnit,'(A79)') "# Lambda(1) bin Energy gap dGa dGb dGg # pts c1**2 c2**2"
CALL Histogram(energyGap,mask,Nbins,binPopulations,binIndices,binMidpoints)
CALL ComputeFEPProfile(1,SIZE(energyGap,1),mappingEnergies(:,:,:,1),mask(:,:),profile=G_FEP)
! energyGap is the reaction coordinate, nBins is num histogram bins, binPop is histogram values,
! indices is which bin each point is in, binMidpoints is x values
CALL FepUS(mappingEnergies(:,:,:,1),stateEnergy(:,:,stateA,1),G_FEP,binPopulations,binIndices,PMF2Dout=dGa,PMF1D=binG,minPop=minPop)
CALL FepUS(mappingEnergies(:,:,:,1),stateEnergy(:,:,stateB,1),G_FEP,binPopulations,binIndices,PMF2Dout=dGb,PMF1D=binG,minPop=minPop)
CALL FepUS(mappingEnergies(:,:,:,1),groundStateEnergy(:,:), G_FEP,binPopulations,binIndices,PMF2Dout=dGg,PMF1D=binG,minPop=minPop)
DO step = 1, SIZE(energyGap,1)
DO bin = 1, Nbins
IF (binPopulations(bin,step) >= minPop) WRITE(outUnit,'(2X,F9.6,I5,2X,4F9.2,2X,I5)') lambda(step), bin, binMidpoints(bin), &
& dGa(bin,step),dGb(bin,step), dGg(bin,step), binPopulations(bin,step)
ENDDO
ENDDO
WRITE(outUnit,*); WRITE(outUnit,*)
WRITE(outUnit,'(A30)') "# Part 3: Bin-averaged summary"
WRITE(outUnit,'(A63)') "# bin energy gap <dGg> <dGg norm> pts <c1**2> <c2**2> <r_xy>"
DO bin = 1, nBins
count = SUM(binPopulations(bin,:), MASK = binPopulations(bin,:) >= minPop)
IF (SUM(binPopulations(bin,:)) > minPop) WRITE(outUnit,'(I4,1X,3F9.2,2X,I5)') bin, binMidpoints(bin), binG(bin), binG(bin)-MINVAL(binG), count
ENDDO
ENDSUBROUTINE AnalyzeFepUs_Q
END PROGRAM Qfep
|
module Issue1168 where
id : {A : Set} ā A ā A
id {A = A} a = a
|
"
ДозГаŃŃ ŃŠŗŃŠøŠæŃ Šø ŠæŠµŃŠµŠ½ŠµŃŃŠø в него ŃŠµŠ·ŃŠ»ŃŃŠ°ŃŃ ŃŠ°Š¼Š¾ŃŃŠ¾ŃŃŠµŠ»Ńного Š·Š°Š“Š°Š½ŠøŃ No 3
ŠøŠ· ŠŠ°Š±Š¾ŃŠ°ŃŠ¾ŃŠ½Š¾ŠøĢ ŃŠ°Š±Š¾ŃŃ No 2: ŃŠ¾Š·Š“аŃŃ Š½ŠµŃŠŗŠ¾Š»Ńко конŃŃŠ°Š½Ń Šø ŠæŠµŃŠµŠ¼ŠµŠ½Š½ŃŃ
ŃŠ°Š·Š½ŃŃ
ŃŠøŠæŠ¾Š²
Š²ŃŠæŠ¾Š»Š½ŠøŃŃ Š°ŃŠøŃŠ¼ŠµŃŠøŃŠµŃŠŗŠøŠµ ŃŠ°ŃŃŠµŃŃ ŠæŠ¾ ŃŠ°Š¼Š¾ŃŃŠ¾ŃŃŠµŠ»Ńно ŠæŠ¾Š“Š³Š¾ŃŠ¾Š²Š»ŠµŠ½Š½Ńм ŃŠ¾ŃŠ¼ŃŠ»Š°Š¼ Ń
ŃŃŠøŠ¼Šø конŃŃŠ°Š½Ńами Šø ŠæŠµŃŠµŠ¼ŠµŠ½Š½Ńми. Š ŃŠ¾ŃŠ¼ŃŠ»Š°Ń
ŠæŃŠ¾Š²ŠµŃŠøŃŃ ŃŠ°Š±Š¾ŃŃ Š¾ŠæŠµŃŠ°ŃŠ¾ŃŠ¾Š² %% Šø % / %.
"
{
a <- c(5, 3, 6, 2)
b <- 5
s <- c(4i, 5i, 6i)
result <- a %% b
print(result)
result <- a %/% b
print(result)
result <- s %% b
print(result)
result <- s %/% b
print(result)
}
|
# Copyright (c) 2020: Matthew Wilhelm & Matthew Stuber.
# This work is licensed under the Creative Commons Attribution-NonCommercial-
# ShareAlike 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative
# Commons, PO Box 1866, Mountain View, CA 94042, USA.
#############################################################################
# DynamicBounds.jl
# A package for compute bounds and relaxations of the solutions of
# parametric differential equations.
# See https://github.com/PSORLab/DynamicBoundsBase.jl
#############################################################################
# src/reexport_using.jl
# A copy of the reexport module that contains the `@reexport using foo: bar`
# syntax functionality contained in Reexport.jl master branch. Since no such
# tagged release is currently available.
#=
Copyright (c) 2014: Simon Kornblith.
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.
=#
#############################################################################
macro reexport(ex)
isa(ex, Expr) && (ex.head == :module ||
ex.head == :using ||
(ex.head == :toplevel &&
all(e->isa(e, Expr) && e.head == :using, ex.args))) ||
error("@reexport: syntax error")
if ex.head == :module
modules = Any[ex.args[2]]
ex = Expr(:toplevel, ex, :(using .$(ex.args[2])))
elseif ex.head == :using && all(e->isa(e, Symbol), ex.args)
modules = Any[ex.args[end]]
elseif ex.head == :using && ex.args[1].head == :(:)
symbols = [e.args[end] for e in ex.args[1].args[2:end]]
return esc(Expr(:toplevel, ex, :(eval(Expr(:export, $symbols...)))))
else
modules = Any[e.args[end] for e in ex.args]
end
esc(Expr(:toplevel, ex,
[:(eval(Expr(:export, names($mod)...))) for mod in modules]...))
end
|
lemma scale_scale_measure [simp]: "scale_measure r (scale_measure r' M) = scale_measure (r * r') M" |
\documentclass[main.tex]{subfiles}
\begin{document}
\subsection{No shock accretion}
\marginpar{Wednesday\\ 2020-12-16, \\ compiled \\ \today}
% Yesterday we discussed column accretion onto a magnetized NS.
If there is no shock, the velocity of the infalling gas will be very high
%
\begin{align}
v \sim v _{\text{free-fall}} = \sqrt{ \frac{2GM}{R}} \sim \num{.5} c
\,,
\end{align}
%
while if there is a collisionless shock the velocity will be much lower: \(v \ll c_s\).
The matter, with particles of mass \(m_1 \) (typically \(m_1 = m_p\)) accretes with a velocity \(u\) onto a plasma, which we assume to be composed of constituents with masses \(m_2 \) (typically \(m_2 = m_e\)) and \(m_1\).
We assume that the typical kinetic energy of an accreting particle is much larger than the thermal energy of the plasma on the surface:
%
\begin{align}
\frac{1}{2 } m_1 u^2 \gg \frac{3}{2} k_B T = \frac{1}{2} m_2 v_2^2
\,.
\end{align}
% \todo[inline]{Not \((\gamma -1 ) mc^2\)?}
The typical \textbf{deflection timescale} for the infalling particles will look like
%
\begin{align}
t_D = \frac{v^2}{\dv{(\Delta v)^2}{t}}
\,,
\end{align}
%
(we take the square in order to have a positive quantity) which can be calculated to be
%
\begin{align}
t_D = \frac{m_1^2 u^3}{8 \pi n e_1^2 e_2^2 \log \Lambda }
\,,
\end{align}
%
where \(e_i\) are the charges of the particles, while \(\log \Lambda \) is known as the Coulomb logarithm. It is typically of the order \(\log \Lambda \sim 15 \divisionsymbol 20\), and it is given by
%
\begin{align}
\log \Lambda = \log( \frac{\chi _{\text{max}}}{\chi _{\text{min}}})
\,,
\end{align}
%
where the \(\chi \)s are the maximum and minimum deflection angles in a collision, respectively.
% \todo[inline]{What are the \(e_i\)?}
This is the typical time required in order to isotropize an initially anisotropic velocity distribution --- it need not become compatible with the thermal velocity distribution.
For that, we have a new \textbf{energy exchange timescale}:
%
\begin{align}
t_E &= \frac{E^2}{\dv{(\Delta E)^2}{t}} \\
&= \underbrace{\frac{m_1^2u^3}{8 \pi n e_1^2 e_2^2 \log \Lambda }}_{t_D} \underbrace{\frac{m_2 u^2}{2 k_B T}}_{\gg 1}
\,.
\end{align}
This is the time we need to wait for in order to reach a Maxwell-Boltzmann-like distribution.
The last timescale we will introduce is the \textbf{slowing-down} timescale: the typical time needed for an incoming particle to become stationary with respect to the Neutron Star,
%
\begin{align}
t_S = \frac{u}{\dv{u}{t}} = \underbrace{\frac{m_1^2u^3}{8 \pi n e_1^2 e_2^2 \log \Lambda }}_{t_D} \underbrace{\frac{m_2}{m_1 + m_2 }}_{\sim 1/2000}
\,.
\end{align}
The slowing down is \emph{mostly} due to interactions between the incoming protons (\(m_1 \)) and the plasma electrons (\(m_2 \)).
% Typically, \(m_1 \sim m_p\) while \(m_2 \sim m_e\).
% Then,
% %
% \begin{align}
% t_S \propto \frac{m_e}{m_p + m_e} \sim \frac{m_e}{m_D}
% \,,
% \end{align}
% %
% so \(t_S \sim t_D (m_e / m_p) \ll t_D\).
The result we get is then \(t_S \ll t_D \ll t_E\) typically: first the particles slow down, then they isotropize, then they transfer their energies.
What happens, instead, if we take \(m_1 \) to be the \emph{electron} mass? Then, the stopping timescale will have contribution both from interactions with the plasma electrons and protons --- the contributions are \(m_e / (m_e + m_e) = 1/2\) and \(m_p / (m_p + m_e) \approx 1\) respectively, so they are both relevant. In this case, then, \(t_S \approx t_D \ll t_E\).
A sketch of this is shown in figure \ref{fig:timescales}.
\begin{figure}[]
\centering
\includegraphics[width=\textwidth]{figures/timescales}
\caption{A very bad figure to show how the timescales look.}
\label{fig:timescales}
\end{figure}
% Electrons are decelerated in the same way by both electrons and protons, protons are mostly decelerated by electrons:
% %
% \begin{align}
% t_S^{(p)} &\propto \frac{m_p}{m_e + m_p} \\
% t_S^{(e)} &\propto 1
% \,.
% \end{align}
The stopping length will typically be \(\lambda _S \sim u t_S\), and the path will look like a random walk. We can write this in terms of the kinetic energy of the proton: \(E_{kp} = m_p u^2 /2\), so
%
\begin{align}
\lambda _S = \frac{E_{kp}^2}{2 \pi n e^4 \log \Lambda } \frac{m_e}{m_p} = \frac{E^2_{kp}}{2 \pi \rho e^{4} \log \Lambda } m_e
\,.
\end{align}
The stopping column density is defined as \(y_0 = \rho \lambda _S\), which resembles the definition for the optical depth (but without the absorption coefficient). Dimensionally, it is a mass over a length squared.
The plasma will start to emit photons as it is heated by the accretion, and it is interesting to compare the typical free path of a photon to \(\lambda _S\). The main source of opacity will be scattering;
the Thompson cross-section is given by
%
\begin{align}
\sigma _T = \frac{8 \pi }{3} \frac{e^{4}}{m_e^2 c^{4}}
\,.
\end{align}
The mean free path for photons looks like \(\lambda _{ph} = 1/ (n \sigma _T)\). The ratio \(\lambda _S / \lambda _{\text{ph}}\) is then
%
\begin{align}
\frac{\lambda_S}{\lambda_{\text{ph}}} = \frac{m_p}{m_e} \frac{1}{3 \log \Lambda } \qty( \frac{u}{c})^4
\,;
\end{align}
%
in order for the accreting material to ``penetrate'' the plasma and heat it from inside, as opposed to losing all of its energy on the surface, we need to ask \(\lambda _S > \lambda _{\text{ph}}\),
and this is equivalent to \(u/c \gtrsim \num{.4}\).
\end{document}
|
[STATEMENT]
lemma octo_in_Reals_if_Re_con: assumes "Ree (octo_of_real q) = q"
shows "q \<in> Reals"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. q \<in> \<real>
[PROOF STEP]
by (metis Reals_of_real inner_real_def mult.right_neutral of_real_inner_1) |
import os
import random
import time
import networkx as nx
import numpy as np
import constants
from gen.utils import game_util
MAX_WEIGHT_IN_GRAPH = 1e5
PRED_WEIGHT_THRESH = 10
EPSILON = 1e-4
# Direction: 0: north, 1: east, 2: south, 3: west
class Graph(object):
def __init__(self, use_gt=False, construct_graph=True, scene_id=None, debug=False):
t_start = time.time()
self.construct_graph = construct_graph
'''
event = env.step({'action': 'GetReachablePositions'})
new_reachable_positions = event.metadata['reachablePositions']
points = []
for point in new_reachable_positions:
xx = int(point['x'] / constants.AGENT_STEP_SIZE)
yy = int(point['z'] / constants.AGENT_STEP_SIZE)
points.append([xx, yy])
self.points = np.array(points, dtype=np.int32)
self.points = self.points[np.lexsort(self.points.T)]
'''
self.scene_id = scene_id
self.points = np.load(os.path.join(
os.path.dirname(__file__),
os.pardir,
'layouts',
'FloorPlan%s-layout.npy' % self.scene_id))
self.points /= constants.AGENT_STEP_SIZE
self.points = np.round(self.points).astype(np.int32)
self.xMin = self.points[:, 0].min() - constants.SCENE_PADDING * 2
self.yMin = self.points[:, 1].min() - constants.SCENE_PADDING * 2
self.xMax = self.points[:, 0].max() + constants.SCENE_PADDING * 2
self.yMax = self.points[:, 1].max() + constants.SCENE_PADDING * 2
self.memory = np.zeros((self.yMax - self.yMin + 1, self.xMax - self.xMin + 1), dtype=np.float32)
self.gt_graph = None
self.shortest_paths = {}
self.shortest_paths_unweighted = {}
self.use_gt = use_gt
self.impossible_spots = set()
self.updated_weights = {}
self.prev_navigable_locations = None
if self.use_gt:
self.memory[:] = MAX_WEIGHT_IN_GRAPH
self.memory[self.points[:, 1] - self.yMin, self.points[:, 0] - self.xMin] = 1 + EPSILON
else:
self.memory[:] = 1
self.memory[:, :int(constants.SCENE_PADDING * 1.5)] = MAX_WEIGHT_IN_GRAPH
self.memory[:int(constants.SCENE_PADDING * 1.5), :] = MAX_WEIGHT_IN_GRAPH
self.memory[:, -int(constants.SCENE_PADDING * 1.5):] = MAX_WEIGHT_IN_GRAPH
self.memory[-int(constants.SCENE_PADDING * 1.5):, :] = MAX_WEIGHT_IN_GRAPH
if self.gt_graph is None:
self.gt_graph = nx.DiGraph()
if self.construct_graph:
for yy in np.arange(self.yMin, self.yMax + 1):
for xx in np.arange(self.xMin, self.xMax + 1):
weight = self.memory[yy - self.yMin, xx - self.xMin]
for direction in range(4):
node = (xx, yy, direction)
back_direction = (direction + 2) % 4
back_node = (xx, yy, back_direction)
self.gt_graph.add_edge(node, (xx, yy, (direction + 1) % 4), weight=1)
self.gt_graph.add_edge(node, (xx, yy, (direction - 1) % 4), weight=1)
forward_node = None
if direction == 0 and yy != self.yMax:
forward_node = (xx, yy + 1, back_direction)
elif direction == 1 and xx != self.xMax:
forward_node = (xx + 1, yy, back_direction)
elif direction == 2 and yy != self.yMin:
forward_node = (xx, yy - 1, back_direction)
elif direction == 3 and xx != self.xMin:
forward_node = (xx - 1, yy, back_direction)
if forward_node is not None:
self.gt_graph.add_edge(forward_node, back_node, weight=weight)
self.initial_memory = self.memory.copy()
self.debug = debug
if self.debug:
print('Graph construction time %.3f' % (time.time() - t_start))
def clear(self):
self.shortest_paths = {}
self.shortest_paths_unweighted = {}
self.impossible_spots = set()
self.prev_navigable_locations = None
if self.use_gt:
self.memory[:] = self.initial_memory
else:
self.memory[:] = 1
self.memory[:, :int(constants.SCENE_PADDING * 1.5)] = MAX_WEIGHT_IN_GRAPH
self.memory[:int(constants.SCENE_PADDING * 1.5), :] = MAX_WEIGHT_IN_GRAPH
self.memory[:, -int(constants.SCENE_PADDING * 1.5):] = MAX_WEIGHT_IN_GRAPH
self.memory[-int(constants.SCENE_PADDING * 1.5):, :] = MAX_WEIGHT_IN_GRAPH
if self.construct_graph:
for (nodea, nodeb), original_weight in self.updated_weights.items():
self.gt_graph[nodea][nodeb]['weight'] = original_weight
self.updated_weights = {}
@property
def image(self):
return self.memory[:, :].astype(np.uint8)
def check_graph_memory_correspondence(self):
# graph sanity check
if self.construct_graph:
for yy in np.arange(self.yMin, self.yMax + 1):
for xx in np.arange(self.xMin, self.xMax + 1):
for direction in range(4):
back_direction = (direction + 2) % 4
back_node = (xx, yy, back_direction)
if direction == 0 and yy != self.yMax:
assert(abs(self.gt_graph[(xx, yy + 1, back_direction)][back_node]['weight'] -
self.memory[int(yy - self.yMin), int(xx - self.xMin)]) < 0.0001)
elif direction == 1 and xx != self.xMax:
assert(abs(self.gt_graph[(xx + 1, yy, back_direction)][back_node]['weight'] -
self.memory[int(yy - self.yMin), int(xx - self.xMin)]) < 0.0001)
elif direction == 2 and yy != self.yMin:
assert(abs(self.gt_graph[(xx, yy - 1, back_direction)][back_node]['weight'] -
self.memory[int(yy - self.yMin), int(xx - self.xMin)]) < 0.0001)
elif direction == 3 and xx != self.xMin:
assert(abs(self.gt_graph[(xx - 1, yy, back_direction)][back_node]['weight'] -
self.memory[int(yy - self.yMin), int(xx - self.xMin)]) < 0.0001)
print('\t\t\tgraph tested successfully')
def update_graph(self, graph_patch, pose):
graph_patch, curr_val = graph_patch
curr_val = np.array(curr_val)
# Rotate the array to get its global coordinate frame orientation.
rotation = int(pose[2])
assert(rotation in {0, 1, 2, 3}), 'rotation was %s' % str(rotation)
if rotation != 0:
graph_patch = np.rot90(graph_patch, rotation)
# Shift offsets to global coordinate frame.
if rotation == 0:
x_min = pose[0] - int(constants.STEPS_AHEAD / 2)
y_min = pose[1] + 1
elif rotation == 1:
x_min = pose[0] + 1
y_min = pose[1] - int(constants.STEPS_AHEAD / 2)
elif rotation == 2:
x_min = pose[0] - int(constants.STEPS_AHEAD / 2)
y_min = pose[1] - constants.STEPS_AHEAD
elif rotation == 3:
x_min = pose[0] - constants.STEPS_AHEAD
y_min = pose[1] - int(constants.STEPS_AHEAD / 2)
else:
raise Exception('Invalid pose direction')
if self.construct_graph:
for yi, yy in enumerate(range(y_min, y_min + constants.STEPS_AHEAD)):
for xi, xx in enumerate(range(x_min, x_min + constants.STEPS_AHEAD)):
self.update_weight(xx, yy, graph_patch[yi, xi, 0])
self.update_weight(pose[0], pose[1], curr_val[0])
def get_graph_patch(self, pose):
rotation = int(pose[2])
assert(rotation in {0, 1, 2, 3})
if rotation == 0:
x_min = pose[0] - int(constants.STEPS_AHEAD / 2)
y_min = pose[1] + 1
elif rotation == 1:
x_min = pose[0] + 1
y_min = pose[1] - int(constants.STEPS_AHEAD / 2)
elif rotation == 2:
x_min = pose[0] - int(constants.STEPS_AHEAD / 2)
y_min = pose[1] - constants.STEPS_AHEAD
elif rotation == 3:
x_min = pose[0] - constants.STEPS_AHEAD
y_min = pose[1] - int(constants.STEPS_AHEAD / 2)
else:
raise Exception('Invalid pose direction')
x_min -= self.xMin
y_min -= self.yMin
graph_patch = self.memory[y_min:y_min + constants.STEPS_AHEAD,
x_min:x_min + constants.STEPS_AHEAD].copy()
if rotation != 0:
graph_patch = np.rot90(graph_patch, -rotation)
return graph_patch, self.memory[pose[1] - self.yMin, pose[0] - self.xMin].copy()
def add_impossible_spot(self, spot):
self.update_weight(spot[0], spot[1], MAX_WEIGHT_IN_GRAPH)
self.impossible_spots.add(spot)
def update_weight(self, xx, yy, weight):
if (xx, yy) not in self.impossible_spots:
if self.construct_graph:
for direction in range(4):
node = (xx, yy, direction)
self.update_edge(node, weight)
self.memory[yy - self.yMin, xx - self.xMin] = weight
self.shortest_paths = {}
def update_edge(self, pose, weight):
rotation = int(pose[2])
assert(rotation in {0, 1, 2, 3})
(xx, yy, direction) = pose
back_direction = (direction + 2) % 4
back_pose = (xx, yy, back_direction)
if direction == 0 and yy != self.yMax:
forward_pose = (xx, yy + 1, back_direction)
elif direction == 1 and xx != self.xMax:
forward_pose = (xx + 1, yy, back_direction)
elif direction == 2 and yy != self.yMin:
forward_pose = (xx, yy - 1, back_direction)
elif direction == 3 and xx != self.xMin:
forward_pose = (xx - 1, yy, back_direction)
else:
raise NotImplementedError('Unknown direction')
if (forward_pose, back_pose) not in self.updated_weights:
self.updated_weights[(forward_pose, back_pose)] = self.gt_graph[forward_pose][back_pose]['weight']
self.gt_graph[forward_pose][back_pose]['weight'] = weight
def get_shortest_path(self, pose, goal_pose):
assert(pose[2] in {0, 1, 2, 3})
assert(goal_pose[2] in {0, 1, 2, 3})
# Store horizons for possible final look correction.
curr_horizon = int(pose[3])
goal_horizon = int(goal_pose[3])
pose = tuple(int(pp) for pp in pose[:3])
goal_pose = tuple(int(pp) for pp in goal_pose[:3])
try:
assert(self.construct_graph), 'Graph was not constructed, cannot get shortest path.'
assert(pose in self.gt_graph), 'start point not in graph'
assert(goal_pose in self.gt_graph), 'start point not in graph'
except Exception as ex:
print('pose', pose, 'goal_pose', goal_pose)
raise ex
if (pose, goal_pose) not in self.shortest_paths:
path = nx.astar_path(self.gt_graph, pose, goal_pose,
heuristic=lambda nodea, nodeb: (abs(nodea[0] - nodeb[0]) + abs(nodea[1] - nodeb[1]) +
abs(nodea[2] - nodeb[2])),
weight='weight')
for ii, pp in enumerate(path):
self.shortest_paths[(pp, goal_pose)] = path[ii:]
path = self.shortest_paths[(pose, goal_pose)]
max_point = 1
for ii in range(len(path) - 1):
weight = self.gt_graph[path[ii]][path[ii + 1]]['weight']
if path[ii][:2] != path[ii + 1][:2]:
if abs(self.memory[path[ii + 1][1] - self.yMin, path[ii + 1][0] - self.xMin] - weight) > 0.001:
print(self.memory[path[ii + 1][1] - self.yMin, path[ii + 1][0] - self.xMin], weight)
raise AssertionError('weights do not match')
if weight >= PRED_WEIGHT_THRESH:
break
max_point += 1
path = path[:max_point]
actions = [Graph.get_plan_move(path[ii], path[ii + 1]) for ii in range(len(path) - 1)]
Graph.horizon_adjust(actions, path, curr_horizon, goal_horizon)
return actions, path
def get_shortest_path_unweighted(self, pose, goal_pose):
assert(pose[2] in {0, 1, 2, 3})
assert(goal_pose[2] in {0, 1, 2, 3})
curr_horizon = int(pose[3])
goal_horizon = int(goal_pose[3])
pose = tuple(int(pp) for pp in pose[:3])
goal_pose = tuple(int(pp) for pp in goal_pose[:3])
try:
assert(self.construct_graph), 'Graph was not constructed, cannot get shortest path.'
assert(pose in self.gt_graph), 'start point not in graph'
assert(goal_pose in self.gt_graph), 'start point not in graph'
except Exception as ex:
print('pose', pose, 'goal_pose', goal_pose)
raise ex
if (pose, goal_pose) not in self.shortest_paths_unweighted:
# TODO: swap this out for astar (might be get_shortest_path tho) and update heuristic to account for
# TODO: actual number of turns.
path = nx.shortest_path(self.gt_graph, pose, goal_pose)
for ii, pp in enumerate(path):
self.shortest_paths_unweighted[(pp, goal_pose)] = path[ii:]
path = self.shortest_paths_unweighted[(pose, goal_pose)]
actions = [Graph.get_plan_move(path[ii], path[ii + 1]) for ii in range(len(path) - 1)]
Graph.horizon_adjust(actions, path, curr_horizon, goal_horizon)
return actions, path
def update_map(self, env):
event = env.step({'action': 'GetReachablePositions'})
new_reachable_positions = event.metadata['reachablePositions']
new_memory = np.full_like(self.memory[:, :], MAX_WEIGHT_IN_GRAPH)
if self.construct_graph:
for point in new_reachable_positions:
xx = int(point['x'] / constants.AGENT_STEP_SIZE)
yy = int(point['z'] / constants.AGENT_STEP_SIZE)
new_memory[yy - self.yMin, xx - self.xMin] = 1 + EPSILON
changed_locations = np.where(np.logical_xor(self.memory[:, :] == MAX_WEIGHT_IN_GRAPH, new_memory == MAX_WEIGHT_IN_GRAPH))
for location in zip(*changed_locations):
self.update_weight(location[1] + self.xMin, location[0] + self.yMin, 1 + EPSILON)
def navigate_to_goal(self, game_state, start_pose, end_pose):
# Look down
self.update_map(game_state.env)
start_angle = start_pose[3]
if start_angle > 180:
start_angle -= 360
if start_angle != 30: # pitch angle
# Perform initial tilt to get to 45 degrees.
tilt_pose = [pp for pp in start_pose]
tilt_pose[3] = 30
tilt_actions, _ = self.get_shortest_path(start_pose, tilt_pose)
for action in tilt_actions:
game_state.step(action)
start_pose = tuple(tilt_pose)
actions, path = self.get_shortest_path(start_pose, end_pose)
while len(actions) > 0:
for ii, (action, pose) in enumerate(zip(actions, path)):
game_state.step(action)
event = game_state.env.last_event
last_action_success = event.metadata['lastActionSuccess']
if not last_action_success:
# Can't traverse here, make sure the weight is correct.
if action['action'].startswith('Look') or action['action'].startswith('Rotate'):
raise Exception('Look action failed %s' % event.metadata['errorMessage'])
self.add_impossible_spot(path[ii + 1])
break
pose = game_util.get_pose(event)
actions, path = self.get_shortest_path(pose, end_pose)
print('nav done')
@staticmethod
def get_plan_move(pose0, pose1):
if (pose0[2] + 1) % 4 == pose1[2]:
action = {'action': 'RotateRight'}
elif (pose0[2] - 1) % 4 == pose1[2]:
action = {'action': 'RotateLeft'}
else:
action = {'action': 'MoveAhead', 'moveMagnitude': constants.AGENT_STEP_SIZE}
return action
@staticmethod
def horizon_adjust(actions, path, hor0, hor1):
if hor0 < hor1:
for _ in range((hor1 - hor0) // constants.AGENT_HORIZON_ADJ):
actions.append({'action': 'LookDown'})
path.append(path[-1])
elif hor0 > hor1:
for _ in range((hor0 - hor1) // constants.AGENT_HORIZON_ADJ):
actions.append({'action': 'LookUp',})
path.append(path[-1])
if __name__ == '__main__':
# Test graphs
env = game_util.create_env()
scenes = sorted(constants.TRAIN_SCENE_NUMBERS + constants.TEST_SCENE_NUMBERS)
while True:
scene_id = random.choice(scenes)
graph = Graph(use_gt=True, construct_graph=True, scene_id=scene_id)
game_util.reset(env, scene_id,
render_image=False,
render_depth_image=False,
render_class_image=False,
render_object_image=False)
num_points = len(graph.points)
point1 = random.randint(0, num_points - 1)
point2 = point1
while point2 == point1:
point2 = random.randint(0, num_points)
point1 = graph.points[point1]
point2 = graph.points[point2]
start_pose = (point1[0], point1[1], random.randint(0, 3), 0)
end_pose = (point2[0], point2[1], random.randint(0, 3), 0)
agent_height = env.last_event.metadata['agent']['position']['y']
action = {'action': 'TeleportFull',
'x': start_pose[0] * constants.AGENT_STEP_SIZE,
'y': agent_height,
'z': start_pose[1] * constants.AGENT_STEP_SIZE,
'rotateOnTeleport': True,
'rotation': start_pose[2],
'horizon': start_pose[3],
}
env.step(action)
actions, path = graph.get_shortest_path(start_pose, end_pose)
while len(actions) > 0:
for ii, (action, pose) in enumerate(zip(actions, path)):
env.step(action)
event = env.last_event
last_action_success = event.metadata['lastActionSuccess']
if not last_action_success:
# Can't traverse here, make sure the weight is correct.
if action['action'].startswith('Look') or action['action'].startswith('Rotate'):
raise Exception('Look action failed %s' % event.metadata['errorMessage'])
graph.add_impossible_spot(path[ii + 1])
break
pose = game_util.get_pose(event)
actions, path = graph.get_shortest_path(pose, end_pose)
if end_pose == pose:
print('made it')
else:
print('could not make it :(')
|
@test get_discretization_counts(LinearDiscretizer([0.0,1.0,2.0]), [0.5,0.5,0.5,1.5,1.5]) == [3,2] |
/-
Copyright (c) 2019 SƩbastien Gouƫzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SƩbastien Gouƫzel
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.geometry.manifold.algebra.smooth_functions
import Mathlib.linear_algebra.finite_dimensional
import Mathlib.analysis.normed_space.inner_product
import Mathlib.PostPort
namespace Mathlib
/-!
# Constructing examples of manifolds over ā
We introduce the necessary bits to be able to define manifolds modelled over `ā^n`, boundaryless
or with boundary or with corners. As a concrete example, we construct explicitly the manifold with
boundary structure on the real interval `[x, y]`.
More specifically, we introduce
* `model_with_corners ā (euclidean_space ā (fin n)) (euclidean_half_space n)` for the model space used
to define `n`-dimensional real manifolds with boundary
* `model_with_corners ā (euclidean_space ā (fin n)) (euclidean_quadrant n)` for the model space used
to define `n`-dimensional real manifolds with corners
## Notations
In the locale `manifold`, we introduce the notations
* `š” n` for the identity model with corners on `euclidean_space ā (fin n)`
* `š”ā n` for `model_with_corners ā (euclidean_space ā (fin n)) (euclidean_half_space n)`.
For instance, if a manifold `M` is boundaryless, smooth and modelled on `euclidean_space ā (fin m)`,
and `N` is smooth with boundary modelled on `euclidean_half_space n`, and `f : M ā N` is a smooth
map, then the derivative of `f` can be written simply as `mfderiv (š” m) (š”ā n) f` (as to why the
model with corners can not be implicit, see the discussion in `smooth_manifold_with_corners.lean`).
## Implementation notes
The manifold structure on the interval `[x, y] = Icc x y` requires the assumption `x < y` as a
typeclass. We provide it as `[fact (x < y)]`.
-/
/--
The half-space in `ā^n`, used to model manifolds with boundary. We only define it when
`1 ⤠n`, as the definition only makes sense in this case.
-/
def euclidean_half_space (n : ā) [HasZero (fin n)] :=
Subtype fun (x : euclidean_space ā (fin n)) => 0 ⤠x 0
/--
The quadrant in `ā^n`, used to model manifolds with corners, made of all vectors with nonnegative
coordinates.
-/
def euclidean_quadrant (n : ā) :=
Subtype fun (x : euclidean_space ā (fin n)) => ā (i : fin n), 0 ⤠x i
/- Register class instances for euclidean half-space and quadrant, that can not be noticed
without the following reducibility attribute (which is only set in this section). -/
protected instance euclidean_half_space.topological_space {n : ā} [HasZero (fin n)] : topological_space (euclidean_half_space n) :=
subtype.topological_space
protected instance euclidean_quadrant.topological_space {n : ā} : topological_space (euclidean_quadrant n) :=
subtype.topological_space
protected instance euclidean_half_space.inhabited {n : ā} [HasZero (fin n)] : Inhabited (euclidean_half_space n) :=
{ default := { val := 0, property := sorry } }
protected instance euclidean_quadrant.inhabited {n : ā} : Inhabited (euclidean_quadrant n) :=
{ default := { val := 0, property := sorry } }
theorem range_half_space (n : ā) [HasZero (fin n)] : (set.range fun (x : euclidean_half_space n) => subtype.val x) = set_of fun (x : euclidean_space ā (fin n)) => 0 ⤠x 0 := sorry
theorem range_quadrant (n : ā) : (set.range fun (x : euclidean_quadrant n) => subtype.val x) =
set_of fun (x : euclidean_space ā (fin n)) => ā (i : fin n), 0 ⤠x i := sorry
/--
Definition of the model with corners `(euclidean_space ā (fin n), euclidean_half_space n)`, used as a
model for manifolds with boundary. In the locale `manifold`, use the shortcut `š”ā n`.
-/
def model_with_corners_euclidean_half_space (n : ā) [HasZero (fin n)] : model_with_corners ā (euclidean_space ā (fin n)) (euclidean_half_space n) :=
model_with_corners.mk
(local_equiv.mk (fun (x : euclidean_half_space n) => subtype.val x)
(fun (x : euclidean_space ā (fin n)) =>
{ val := fun (i : fin n) => dite (i = 0) (fun (h : i = 0) => max (x i) 0) fun (h : ¬i = 0) => x i,
property := sorry })
set.univ (set.range fun (x : euclidean_half_space n) => subtype.val x) sorry sorry sorry sorry)
sorry sorry
/--
Definition of the model with corners `(euclidean_space ā (fin n), euclidean_quadrant n)`, used as a
model for manifolds with corners -/
def model_with_corners_euclidean_quadrant (n : ā) : model_with_corners ā (euclidean_space ā (fin n)) (euclidean_quadrant n) :=
model_with_corners.mk
(local_equiv.mk (fun (x : euclidean_quadrant n) => subtype.val x)
(fun (x : euclidean_space ā (fin n)) => { val := fun (i : fin n) => max (x i) 0, property := sorry }) set.univ
(set.range fun (x : euclidean_quadrant n) => subtype.val x) sorry sorry sorry sorry)
sorry sorry
/--
The left chart for the topological space `[x, y]`, defined on `[x,y)` and sending `x` to `0` in
`euclidean_half_space 1`.
-/
def Icc_left_chart (x : ā) (y : ā) [fact (x < y)] : local_homeomorph (ā„(set.Icc x y)) (euclidean_half_space 1) :=
local_homeomorph.mk
(local_equiv.mk (fun (z : ā„(set.Icc x y)) => { val := fun (i : fin 1) => subtype.val z - x, property := sorry })
(fun (z : euclidean_half_space 1) => { val := min (subtype.val z 0 + x) y, property := sorry })
(set_of fun (z : ā„(set.Icc x y)) => subtype.val z < y)
(set_of fun (z : euclidean_half_space 1) => subtype.val z 0 < y - x) sorry sorry sorry sorry)
sorry sorry sorry sorry
/--
The right chart for the topological space `[x, y]`, defined on `(x,y]` and sending `y` to `0` in
`euclidean_half_space 1`.
-/
def Icc_right_chart (x : ā) (y : ā) [fact (x < y)] : local_homeomorph (ā„(set.Icc x y)) (euclidean_half_space 1) :=
local_homeomorph.mk
(local_equiv.mk (fun (z : ā„(set.Icc x y)) => { val := fun (i : fin 1) => y - subtype.val z, property := sorry })
(fun (z : euclidean_half_space 1) => { val := max (y - subtype.val z 0) x, property := sorry })
(set_of fun (z : ā„(set.Icc x y)) => x < subtype.val z)
(set_of fun (z : euclidean_half_space 1) => subtype.val z 0 < y - x) sorry sorry sorry sorry)
sorry sorry sorry sorry
/--
Charted space structure on `[x, y]`, using only two charts taking values in `euclidean_half_space 1`.
-/
protected instance Icc_manifold (x : ā) (y : ā) [fact (x < y)] : charted_space (euclidean_half_space 1) ā„(set.Icc x y) :=
charted_space.mk (insert (Icc_left_chart x y) (singleton (Icc_right_chart x y)))
(fun (z : ā„(set.Icc x y)) => ite (subtype.val z < y) (Icc_left_chart x y) (Icc_right_chart x y)) sorry sorry
/--
The manifold structure on `[x, y]` is smooth.
-/
protected instance Icc_smooth_manifold (x : ā) (y : ā) [fact (x < y)] : smooth_manifold_with_corners (model_with_corners_euclidean_half_space 1) ā„(set.Icc x y) := sorry
/-! Register the manifold structure on `Icc 0 1`, and also its zero and one. -/
theorem fact_zero_lt_one : fact (0 < 1) :=
zero_lt_one
protected instance set.Icc.charted_space : charted_space (euclidean_half_space 1) ā„(set.Icc 0 1) :=
Mathlib.Icc_manifold 0 1
protected instance set.Icc.smooth_manifold_with_corners : smooth_manifold_with_corners (model_with_corners_euclidean_half_space 1) ā„(set.Icc 0 1) :=
Mathlib.Icc_smooth_manifold 0 1
|
subroutine runend(message)
use typre
!-----------------------------------------------------------------------
!
! This routine stops the run and writes the summary of CPU time.
!
!-----------------------------------------------------------------------
implicit none
character(*) :: message
logical(lg) :: lopen
! !Write the table with the CPU times.
! call cputab
integer :: STATUS = 1
!Write message and stop the run.
if(message/='O.K.!') then
write(*,901) 'AN ERROR HAS BEEN DETECTED: '//message
else
write(*,'(//,a,/)') ' * * * END OF ANALYSIS * * *'
end if
!
! Formats.
!
900 format(//,5x,34('* '),//,25x,'AN ERROR HAS BEEN DETECTED:',/)
901 format(/,5x,a,/)
end subroutine runend
|
[STATEMENT]
lemma error_free_Some [simp,intro]:
"\<not> (\<exists> err. x=Error err) \<Longrightarrow> error_free ((Some x),s)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<nexists>err. x = Error err \<Longrightarrow> error_free (Some x, s)
[PROOF STEP]
by (auto simp add: error_free_def) |
Are you one of the blessed few who has extremely nice neighbors? Do they share their Wi-Fi with you? Or, are there quite a few open networks that you could use? |
Require Import List.
Require Import Logic.Class.Eq.
Require Import Logic.Func.Replace.
Require Import Logic.Func.Composition.
Require Import Logic.Fol.Free.
Require Import Logic.Fol.Valid.
Require Import Logic.Fol.Functor.
Require Import Logic.Set.Set.
Require Import Logic.Set.Equal.
Require Import Logic.Lang1.Syntax.
Require Import Logic.Lang1.Semantics.
Require Import Logic.Lang1.Relevance.
Require Import Logic.Lang1.Environment.
Require Import Logic.Lang1.Substitution.
(* A formula with a free variable could be viewed as a predicate which needs to *)
(* be 'evaluated' at some variable, where such evaluation corresponds to a *)
(* variable substitution. In the following, we formalize this evaluation by *)
(* substituting the variable '0' by the argument 'n'. This choice of variable *)
(* '0' is arbitrary, but having this default choice leads to simpler syntax as *)
(* there is no need to spell out which variable is being replaced. There is *)
(* nothing deep here, as we are just creating a new formula from an old one. *)
(* The ability to apply a formula viewed as predicate to variables is important *)
(* for two variables, and is needed to express the axiom schema of replacement. *)
Definition apply (p:Formula) (n:nat) : Formula := fmap (n // 0) p.
(* Same idea, but with two variables. *)
Definition apply2 (p:Formula) (n m:nat) : Formula := fmap (replace2 0 1 n m) p.
(* The semantics of 'apply p n' in an environement where n is bound to set x *)
(* is the same as the semantics of p in an environment where 0 is bound to x. *)
(* However, we cannot hope to obtain this semantics equivalence without *)
(* assuming that the replacement of variable 0 by n is a valid substitution *)
(* for p. Also, n cannot already be a free variable of p. *)
Lemma evalApply1 : forall (e:Env) (p:Formula) (n:nat) (x:set),
valid (n // 0) p ->
~In n (Fr p) ->
eval1 e (apply p n) n x <-> eval1 e p 0 x.
Proof.
unfold eval1, apply. intros e p n x H1 H2. rewrite Substitution.
- apply relevance. intros m H3. apply bindReplace. intros H4.
subst. apply H2. assumption.
- assumption.
Qed.
(* The semantics of 'apply2 p n m' in an environment where n is bound to x and *)
(* m is bound to y, is the same as the semantics of p in an environment where 0 *)
(* is bound to x and 1 is bound to y, with the obvious caveat. *)
Lemma evalApply2 : forall (e:Env) (p:Formula) (n m:nat) (x y:set),
valid (replace2 0 1 n m) p ->
~In n (Fr p) ->
~In m (Fr p) ->
n <> m ->
eval2 e (apply2 p n m) n m x y <-> eval2 e p 0 1 x y.
Proof.
unfold eval2, apply2. intros e p n m x y H1 H2 H3 H4. rewrite Substitution.
- apply relevance. intros r H5. unfold comp. apply bindReplace2.
+ auto.
+ apply H4. (* <- H4 *)
+ intros H6. apply H2. rewrite H6. assumption. (* <- H2 *)
+ intros H6. apply H3. rewrite H6. assumption. (* <- H3 *)
- apply H1. (* <- H1 *)
Qed.
Lemma evalApplyF1 : forall (e:Env) (p:Formula) (n m m':nat) (x y y':set),
n <> m ->
n <> m' ->
m <> m' ->
valid (replace2 0 1 n m) p ->
~ In m' (Fr p) ->
~ In m (Fr p) ->
~ In n (Fr p) ->
eval (bind (bind (bind e n x) m y) m' y') (apply2 p n m)
<->
eval (bind (bind e 0 x) 1 y) p.
Proof.
intros e p n m m' x y y' H1 H2 H3 H4 H1' H2' H3'.
unfold apply2. rewrite Substitution.
remember (bind (bind (bind e n x) m y) m' y'; replace2 0 1 n m)
as e1 eqn:E1. remember (bind (bind e 0 x) 1 y) as e2 eqn:E2.
apply (relevance e1 e2).
- intros k H5. rewrite E1, E2. unfold comp, bind, replace2.
destruct (eqDec k 0) as [H6|H6] eqn:K0.
+ subst. destruct (eqDec m' n) as [H7|H7].
{ subst. exfalso. apply H2. reflexivity. }
{ destruct (eqDec m n) as [H8|H8].
{ subst. exfalso. apply H1. reflexivity. }
{ simpl. destruct (PeanoNat.Nat.eq_dec n n) as [H9|H9].
{ apply equalRefl. }
{ exfalso. apply H9. reflexivity. }}}
+ destruct (eqDec k 1) as [H7|H7] eqn:K1.
{ subst. destruct (eqDec m' m) as [H7|H7].
{ subst. exfalso. apply H3. reflexivity. }
{ simpl. destruct (PeanoNat.Nat.eq_dec m m) as [H8|H8].
{ apply equalRefl. }
{ exfalso. apply H8. reflexivity. }}}
{ destruct (eqDec m' k) as [H8|H8].
{ subst. exfalso. apply H1'. assumption. }
{ destruct (eqDec m k) as [H9|H9].
{ subst. exfalso. apply H2'. assumption. }
{ destruct (eqDec n k) as [H10|H10].
{ subst. exfalso. apply H3'. assumption. }
{ destruct (eqDec 0 k) as [H11|H11];
destruct (eqDec 1 k) as [H12|H12].
{ subst. inversion H12. }
{ exfalso. apply H6. symmetry. assumption. }
{ exfalso. apply H7. symmetry. assumption. }
{ apply equalRefl. }}}}}
- assumption.
Qed.
Lemma evalApplyF2 : forall (e:Env) (p:Formula) (n m m':nat) (x y y':set),
n <> m ->
n <> m' ->
m <> m' ->
valid (replace2 0 1 n m') p ->
~ In m' (Fr p) ->
~ In m (Fr p) ->
~ In n (Fr p) ->
eval (bind (bind (bind e n x) m y) m' y') (apply2 p n m')
<->
eval (bind (bind e 0 x) 1 y') p.
Proof.
intros e p n m m' x y y' H1 H2 H3 H4 H1' H2' H3'.
remember (bind (bind (bind e n x) m y) m' y') as e1 eqn:E1.
remember (bind (bind (bind e n x) m' y') m y) as e2 eqn:E2.
remember (bind (bind e 0 x) 1 y') as e3 eqn:E3.
assert (envEqual e1 e2) as H5.
{ rewrite E1, E2. apply bindPermute. apply not_eq_sym. assumption. }
assert (eval e1 (apply2 p n m') <-> eval e2 (apply2 p n m')) as H6.
{ apply evalEnvEqual. assumption. }
rewrite H6, E2, E3. apply evalApplyF1; try (assumption).
apply not_eq_sym. assumption.
Qed.
|
items <- c(1,2,3,2,4,3,2)
unique (items)
|
Require Import ProofIrrelevance.
Lemma proj1_sig_injective: forall {A:Type} (P:A->Prop)
(a1 a2:{x:A | P x}), proj1_sig a1 = proj1_sig a2 -> a1 = a2.
Proof.
intros.
destruct a1, a2.
now apply subset_eq_compat.
Qed.
|
data Bad : Type where
R : (Bad -> Nat) -> Bad
|
lemma collinear_lemma: "collinear {0, x, y} \<longleftrightarrow> x = 0 \<or> y = 0 \<or> (\<exists>c. y = c *\<^sub>R x)" (is "?lhs \<longleftrightarrow> ?rhs") |
Formal statement is: lemma AE_distrD: assumes f: "f \<in> measurable M M'" and AE: "AE x in distr M M' f. P x" shows "AE x in M. P (f x)" Informal statement is: If $f$ is a measurable function from $M$ to $M'$ and $P$ holds almost everywhere on the image of $f$, then $P$ holds almost everywhere on $M$. |
section propositional
variables P Q R : Prop
------------------------------------------------
-- ProposiƧƵes de dupla negaƧo:
------------------------------------------------
theorem doubleneg_intro :
P ā ¬¬P :=
begin
intro P,
intro NoP,
have boom : false := NoP P,
exact boom,
end
theorem doubleneg_elim :
¬¬P ā P :=
begin
intro h,
by_contradiction g,
contradiction,
end
theorem doubleneg_law :
¬¬P ā P :=
begin
split,
intro h,
by_contradiction p,
have boom: false := h p,
contradiction,
intro g,
intro t,
contradiction,
end
------------------------------------------------
-- Comutatividade dos āØ,ā§:
------------------------------------------------
theorem disj_comm :
(P ⨠Q) ā (Q ⨠P) :=
begin
intro pouq,
cases pouq with p q,
right,
exact p,
left,
exact q,
end
theorem conj_comm :
(P ā§ Q) ā (Q ā§ P) :=
begin
intro h,
cases h with u v,
split,
exact v,
exact u,
end
------------------------------------------------
-- ProposiƧƵes de interdefinabilidade dos ā,āØ:
------------------------------------------------
theorem impl_as_disj_converse :
(¬P ⨠Q) ā (P ā Q) :=
begin
intro Nopq,
intro p,
cases Nopq with np q,
have boom: false := np p,
contradiction,
exact q,
end
theorem disj_as_impl :
(P ⨠Q) ā (¬P ā Q) :=
begin
intro pouq,
intro Nop,
cases pouq with p q,
have boom: false := Nop p,
contradiction,
exact q,
end
------------------------------------------------
-- Proposições de contraposição:
------------------------------------------------
theorem impl_as_contrapositive :
(P ā Q) ā (¬Q ā ¬P) :=
begin
intro PimpQ,
intro NoQ,
intro P,
have Q: Q := PimpQ P,
have boom: false := NoQ Q,
exact boom,
end
theorem impl_as_contrapositive_converse :
(¬Q ā ¬P) ā (P ā Q) :=
begin
intro u,
intro p,
by_contra,
have jj: ¬P := u h,
contradiction,
end
theorem contrapositive_law :
(P ā Q) ā (¬Q ā ¬P) :=
begin
split,
apply impl_as_contrapositive,
apply impl_as_contrapositive_converse,
end
------------------------------------------------
-- A irrefutabilidade do LEM:
------------------------------------------------
theorem lem_irrefutable :
¬¬(PāØĀ¬P) :=
begin
intro h,
have g: (PāØĀ¬P),
right,
intro j,
have ll: (PāØĀ¬P),
left,
exact j,
contradiction,
contradiction,
end
------------------------------------------------
-- A lei de Peirce
------------------------------------------------
theorem peirce_law_weak :
((P ā Q) ā P) ā ¬¬P :=
begin
intro h,
intro g,
have hh: (P ā Q),
intro b,
contradiction,
have kj: P := h hh,
contradiction,
end
------------------------------------------------
-- ProposiƧƵes de interdefinabilidade dos āØ,ā§:
------------------------------------------------
theorem disj_as_negconj :
PāØQ ā ¬(¬Pā§Ā¬Q) :=
begin
intro h,
intro g,
cases h with p q,
cases g with nop noq,
have boom: false := nop p,
contradiction,
cases g with nop noq,
have boom: false := noq q,
exact boom,
end
theorem conj_as_negdisj :
Pā§Q ā ¬(¬PāØĀ¬Q) :=
begin
intro h,
intro g,
cases h with p q,
cases g with nop noq,
contradiction,
contradiction,
end
------------------------------------------------
-- As leis de De Morgan para āØ,ā§:
------------------------------------------------
theorem demorgan_disj :
¬(PāØQ) ā (¬P ⧠¬Q) :=
begin
intro h,
split,
intro g,
have pq: (PāØQ),
left,
exact g,
have boom: false:= h pq,
contradiction,
intro pp,
have bom: (PāØQ),
right,
exact pp,
contradiction,
end
theorem demorgan_disj_converse :
(¬P ⧠¬Q) ā ¬(PāØQ) :=
begin
intro h,
intro g,
cases h with nop noq,
cases g with p q,
contradiction,
contradiction,
end
theorem demorgan_conj :
¬(Pā§Q) ā (¬Q ⨠¬P) :=
begin
intro h,
by_cases df: Q,
right,
intro gg,
have nb: P ā§ Q,
split,
exact gg,
exact df,
have boom: false := h nb,
contradiction,
left,
exact df,
end
theorem demorgan_conj_converse :
(¬Q ⨠¬P) ā ¬(Pā§Q) :=
begin
intro h,
intro g,
cases g with u v,
cases h with t o,
contradiction,
contradiction,
end
theorem demorgan_conj_law :
¬(Pā§Q) ā (¬Q ⨠¬P) :=
begin
split,
apply demorgan_conj,
apply demorgan_conj_converse,
end
theorem demorgan_disj_law :
¬(PāØQ) ā (¬P ⧠¬Q) :=
begin
split,
apply demorgan_disj,
apply demorgan_disj_converse,
end
------------------------------------------------
-- ProposiƧƵes de distributividade dos āØ,ā§:
------------------------------------------------
theorem distr_conj_disj :
Pā§(QāØR) ā (Pā§Q)āØ(Pā§R) :=
begin
intro p,
cases p with u v,
cases v with pp mm,
left,
split,
exact u,
exact pp,
right,
split,
exact u,
exact mm,
end
theorem distr_conj_disj_converse :
(Pā§Q)āØ(Pā§R) ā Pā§(QāØR) :=
begin
intro h,
split,
cases h with p q,
cases p with pp f,
exact pp,
cases q with qq rr,
exact qq,
cases h with u v,
cases u with t y,
left,
exact y,
cases v with k l,
right,
exact l,
end
theorem distr_disj_conj :
PāØ(Qā§R) ā (PāØQ)ā§(PāØR) :=
begin
intro h,
cases h with u v,
split,
left,
exact u,
left,
exact u,
split,
cases v with w e,
right,
exact w,
right,
cases v with bb nn,
exact nn,
end
theorem distr_disj_conj_converse :
(PāØQ)ā§(PāØR) ā PāØ(Qā§R) :=
begin
intro f,
cases f with d e,
cases d with yy pp,
cases e with gg kk,
left,
exact yy,
left,
exact yy,
cases e with tt uu,
left,
exact tt,
right,
split,
exact pp,
exact uu,
end
------------------------------------------------
-- Currificação
------------------------------------------------
theorem curry_prop :
((Pā§Q)āR) ā (Pā(QāR)) :=
begin
intro h,
intro g,
intro f,
have k: P ā§ Q,
split,
exact g,
exact f,
have pp: R := h k,
exact pp,
end
theorem uncurry_prop :
(Pā(QāR)) ā ((Pā§Q)āR) :=
begin
intro h,
intro g,
cases g with p q,
have qr: Q ā R := h p,
have r: R := qr q,
exact r,
end
------------------------------------------------
-- Reflexividade da ā:
------------------------------------------------
theorem impl_refl :
P ā P :=
begin
intro h,
exact h,
end
------------------------------------------------
-- Weakening and contraction:
------------------------------------------------
theorem weaken_disj_right :
P ā (PāØQ) :=
begin
intro h,
left,
exact h,
end
theorem weaken_disj_left :
Q ā (PāØQ) :=
begin
intro h,
right,
exact h,
end
theorem weaken_conj_right :
(Pā§Q) ā P :=
begin
intro h,
cases h with u v,
exact u,
end
theorem weaken_conj_left :
(Pā§Q) ā Q :=
begin
intro h,
cases h with p q,
exact q,
end
theorem conj_idempot :
(Pā§P) ā P :=
begin
split,
intro h,
cases h with p hp,
exact p,
intro d,
split,
exact d,
exact d,
end
theorem disj_idempot :
(PāØP) ā P :=
begin
split,
intro h,
cases h with p hp,
exact p,
exact hp,
intro g,
left,
exact g,
end
end propositional
----------------------------------------------------------------
section predicate
variable U : Type
variables P Q : U -> Prop
------------------------------------------------
-- As leis de De Morgan para ā,ā:
------------------------------------------------
theorem demorgan_exists :
¬(āx, P x) ā (āx, ¬P x) :=
begin
intro h,
intro x,
intro p,
apply h,
existsi x,
exact p,
end
theorem demorgan_exists_converse :
(āx, ¬P x) ā ¬(āx, P x) :=
begin
intro h,
intro g,
cases g with x e,
have boom: ¬P x := h x,
contradiction,
end
theorem demorgan_forall :
¬(āx, P x) ā (āx, ¬P x) :=
begin
rw contrapositive_law,
rw doubleneg_law,
intro h,
intro x,
by_cases j: P x,
exact j,
have: ā (x : U), ¬P x,
existsi x,
exact j,
contradiction,
end
theorem demorgan_forall_converse :
(āx, ¬P x) ā ¬(āx, P x) :=
begin
intro h,
intro g,
cases h with x e,
have boom: P x := g x,
contradiction,
end
theorem demorgan_forall_law :
¬(āx, P x) ā (āx, ¬P x) :=
begin
split,
apply demorgan_forall,
apply demorgan_forall_converse,
end
theorem demorgan_exists_law :
¬(āx, P x) ā (āx, ¬P x) :=
begin
split,
apply demorgan_exists,
apply demorgan_exists_converse,
end
------------------------------------------------
-- ProposiƧƵes de interdefinabilidade dos ā,ā:
------------------------------------------------
theorem exists_as_neg_forall :
(āx, P x) ā ¬(āx, ¬P x) :=
begin
intro h,
intro g,
cases h with x e,
have boom: ¬P x := g x,
contradiction,
end
theorem forall_as_neg_exists :
(āx, P x) ā ¬(āx, ¬P x) :=
begin
intro h,
intro g,
cases g with x e,
have tt: P x := h x,
contradiction,
end
theorem forall_as_neg_exists_converse :
¬(āx, ¬P x) ā (āx, P x) :=
begin
intro h,
intro x,
have bt: ¬P x,
intro pp,
end
theorem exists_as_neg_forall_converse :
¬(āx, ¬P x) ā (āx, P x) :=
begin
sorry,
end
theorem forall_as_neg_exists_law :
(āx, P x) ā ¬(āx, ¬P x) :=
begin
sorry,
end
theorem exists_as_neg_forall_law :
(āx, P x) ā ¬(āx, ¬P x) :=
begin
split,
apply exists_as_neg_forall,
end
------------------------------------------------
-- ProposiƧƵes de distributividade de quantificadores:
------------------------------------------------
theorem exists_conj_as_conj_exists :
(āx, P x ā§ Q x) ā (āx, P x) ā§ (āx, Q x) :=
begin
intro h,
cases h with x l,
cases l with j m,
split,
existsi x,
exact j,
existsi x,
exact m,
end
theorem exists_disj_as_disj_exists :
(āx, P x ⨠Q x) ā (āx, P x) ⨠(āx, Q x) :=
begin
intro h,
cases h with x l,
cases l with u v,
left,
existsi x,
exact u,
right,
existsi x,
exact v,
end
theorem exists_disj_as_disj_exists_converse :
(āx, P x) ⨠(āx, Q x) ā (āx, P x ⨠Q x) :=
begin
intro h,
cases h with e k,
cases e with x m,
existsi x,
left,
exact m,
cases k with d f,
existsi d,
right,
exact f,
end
theorem forall_conj_as_conj_forall :
(āx, P x ā§ Q x) ā (āx, P x) ā§ (āx, Q x) :=
begin
intro h,
split,
intro x,
have m: P x ā§ Q x := h x,
cases m with t c,
exact t,
intro xx,
have mm: P xx ā§ Q xx := h xx,
cases mm with ee rr,
exact rr,
end
theorem forall_conj_as_conj_forall_converse :
(āx, P x) ā§ (āx, Q x) ā (āx, P x ā§ Q x) :=
begin
sorry,
end
theorem forall_disj_as_disj_forall_converse :
(āx, P x) ⨠(āx, Q x) ā (āx, P x ⨠Q x) :=
begin
sorry,
end
/- NOT THEOREMS --------------------------------
theorem forall_disj_as_disj_forall :
(āx, P x ⨠Q x) ā (āx, P x) ⨠(āx, Q x) :=
begin
end
theorem exists_conj_as_conj_exists_converse :
(āx, P x) ā§ (āx, Q x) ā (āx, P x ā§ Q x) :=
begin
end
---------------------------------------------- -/
end predicate
|
// (C) Copyright Jeremy Siek 2000.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/concept_check.hpp>
/*
This file verifies that the BOOST_CLASS_REQUIRE macro of the Boost
Concept Checking Library does not cause errors when it is not suppose
to.
*/
struct foo { bool operator()(int) { return true; } };
struct bar { bool operator()(int, char) { return true; } };
class class_requires_test
{
BOOST_CONCEPT_ASSERT((boost::EqualityComparable<int>));
typedef int* int_ptr; typedef const int* const_int_ptr;
BOOST_CONCEPT_ASSERT((boost::EqualOp<int_ptr,const_int_ptr>));
BOOST_CONCEPT_ASSERT((boost::UnaryFunction<foo,bool,int>));
BOOST_CONCEPT_ASSERT((boost::BinaryFunction<bar,bool,int,char>));
};
int
main()
{
class_requires_test x;
boost::ignore_unused_variable_warning(x);
return 0;
}
|
import MyNat
import MyNat.proposition_world
open MyNat
example (P Q : Prop) (p : P) (q : Q) : P ā§ Q := by
constructor
exact p
exact q
lemma and_symm (P Q : Prop) : P ā§ Q ā Q ā§ P := by
intro h
cases h with
| intro p q =>
constructor
exact q
exact p
lemma and_trans (P Q R : Prop) : P ā§ Q ā Q ā§ R ā P ā§ R := by
intro h1 h2
cases h1 with
| intro p q =>
cases h2 with
| intro q r =>
constructor
exact p
exact r
lemma iff_trans (P Q R : Prop) : (P ā Q) ā (Q ā R) ā (P ā R) := by
intro h1 h2
cases h1 with
| intro pq qp =>
cases h2 with
| intro qr rq =>
constructor
intro p
exact (qr (pq p))
intro r
exact (qp (rq r))
example (P Q R : Prop) : (P ā Q) ā (Q ā R) ā (P ā R) := by
intro hpq hqr
constructor
intro p
apply (Iff.mp hqr)
apply (Iff.mp hpq)
exact p
intro r
rewrite [hpq, hqr]
exact r
example (P Q : Prop) : Q ā (P ⨠Q) := by
intro q
exact (Or.inr q)
lemma or_symm (P Q : Prop) : P ⨠Q -> Q ⨠P := by
intro pq
exact (
Or.elim
pq
(Or.inr)
(Or.inl)
)
lemma alexs_discovery (P Q R : Prop) :
P ā (P ⨠Q) ā§ (P ⨠R) := by
intro p
exact āØOr.inl p, Or.inl pā©
lemma and_or_distrib_left (P Q R : Prop) :
P ā§ (Q ⨠R) ā (P ā§ Q) ⨠(P ā§ R) := by
constructor
intro p_and_qr
let p := (p_and_qr.left)
let qr := (p_and_qr.right)
exact (
Or.elim qr
(fun q => Or.inl (And.intro p q))
(fun r => Or.inr (And.intro p r))
)
intro p_and_q_or_p_and_r
exact (
Or.elim p_and_q_or_p_and_r
(fun pq =>
And.intro pq.left (Or.inl pq.right)
)
(fun pr =>
And.intro pr.left (Or.inr pr.right)
)
)
lemma contra (P Q : Prop) : (P ⧠¬ P) ā Q := by
intro pandnotp
let p := pandnotp.left
let notp := pandnotp.right
-- rewrite [not_iff_imp_false] at notp
-- let false := (notp p)
-- exact False.elim false
exact (absurd p notp)
lemma contrapositive2 (P Q : Prop) :
(¬Q ā ¬P) ā (P ā Q) := by
intro h p
by_cases p : P
case inl p' =>
. by_cases q : Q
. case inl => exact q
. case inr => exact absurd p (h q)
case inr p' =>
. by_cases q : Q
. case _ => exact q
. case inr => exact absurd p' p
lemma full_contrapositive (P Q : Prop) :
(¬Q ā ¬P) ā (P ā Q) := by
constructor
exact contrapositive2 P Q
exact contrapositive P Q |
[GOAL]
α : Type u_1
instā² : TopologicalSpace α
instā¹ : PartialOrder α
instā : PriestleySpace α
x y : α
h : x ā y
⢠ā U, IsClopen U ā§ (IsUpperSet U ⨠IsLowerSet U) ā§ x ā U ⧠¬y ā U
[PROOFSTEP]
obtain h | h := h.not_le_or_not_le
[GOAL]
case inl
α : Type u_1
instā² : TopologicalSpace α
instā¹ : PartialOrder α
instā : PriestleySpace α
x y : α
hā : x ā y
h : ¬x ⤠y
⢠ā U, IsClopen U ā§ (IsUpperSet U ⨠IsLowerSet U) ā§ x ā U ⧠¬y ā U
[PROOFSTEP]
exact (exists_clopen_upper_of_not_le h).imp fun _ ⦠And.imp_right <| And.imp_left Or.inl
[GOAL]
case inr
α : Type u_1
instā² : TopologicalSpace α
instā¹ : PartialOrder α
instā : PriestleySpace α
x y : α
hā : x ā y
h : ¬y ⤠x
⢠ā U, IsClopen U ā§ (IsUpperSet U ⨠IsLowerSet U) ā§ x ā U ⧠¬y ā U
[PROOFSTEP]
obtain āØU, hU, hU', hy, hxā© := exists_clopen_lower_of_not_le h
[GOAL]
case inr.intro.intro.intro.intro
α : Type u_1
instā² : TopologicalSpace α
instā¹ : PartialOrder α
instā : PriestleySpace α
x y : α
hā : x ā y
h : ¬y ⤠x
U : Set α
hU : IsClopen U
hU' : IsLowerSet U
hy : ¬y ā U
hx : x ā U
⢠ā U, IsClopen U ā§ (IsUpperSet U ⨠IsLowerSet U) ā§ x ā U ⧠¬y ā U
[PROOFSTEP]
exact āØU, hU, Or.inr hU', hx, hyā©
|
open import Type
module Relator.Equals.Proofs.Equiv {ā} {T : Type{ā}} where
import Relator.Equals.Proofs.Equivalence
open Relator.Equals.Proofs.Equivalence.One {T = T} public
open Relator.Equals.Proofs.Equivalence.Two {A = T} public
open Relator.Equals.Proofs.Equivalence.Three {A = T} public
open Relator.Equals.Proofs.Equivalence.Four {A = T} public
instance [ā”]-unary-relator-instance = [ā”]-unary-relator
instance [ā”]-binary-relator-instance = [ā”]-binary-relator
instance [ā”]-binary-operator-instance = [ā”]-binary-operator
instance [ā”]-trinary-operator-instance = [ā”]-trinary-operator
instance [ā”]-to-function-instance = [ā”]-to-function
instance [ā”]-equiv-instance = [ā”]-equiv
|
# ---
# title: 785. Is Graph Bipartite?
# id: problem785
# author: Indigo
# date: 2021-01-28
# difficulty: Medium
# categories: Depth-first Search, Breadth-first Search, Graph
# link: <https://leetcode.com/problems/is-graph-bipartite/description/>
# hidden: true
# ---
#
# Given an undirected `graph`, return `true` if and only if it is bipartite.
#
# Recall that a graph is _bipartite_ if we can split its set of nodes into two
# independent subsets A and B, such that every edge in the graph has one node in
# A and another node in B.
#
# The graph is given in the following form: `graph[i]` is a list of indexes `j`
# for which the edge between nodes `i` and `j` exists. Each node is an integer
# between `0` and `graph.length - 1`. There are no self edges or parallel
# edges: `graph[i]` does not contain `i`, and it doesn't contain any element
# twice.
#
#
#
# **Example 1:**
#
# 
#
#
#
# Input: graph = [[1,3],[0,2],[1,3],[0,2]]
# Output: true
# Explanation: We can divide the vertices into two groups: {0, 2} and {1, 3}.
#
#
#
# **Example 2:**
#
# 
#
#
#
# Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
# Output: false
# Explanation: We cannot find a way to divide the set of nodes into two independent subsets.
#
#
#
#
#
# **Constraints:**
#
# * `1 <= graph.length <= 100`
# * `0 <= graph[i].length < 100`
# * `0 <= graph[i][j] <= graph.length - 1`
# * `graph[i][j] != i`
# * All the values of `graph[i]` are **unique**.
# * The graph is **guaranteed** to be **undirected**.
#
#
## @lc code=start
using LeetCode
function is_bipartite(graph::Vector{Vector{Int}})
for edge in graph
edge .+= 1
end
color = fill(0, length(graph))
q = Queue{Int}()
for i in 1:length(graph)
if color[i] != 0
continue
end
color[i] = 1
enqueue!(q, i)
while !isempty(q)
root = dequeue!(q)
for neighbor in graph[root]
if color[neighbor] == 0
color[neighbor] = -color[root]
enqueue!(q, neighbor)
elseif color[neighbor] == color[root]
return false
end
end
end
end
return true
end
## @lc code=end
|
module Type.Category.ExtensionalFunctionsCategory.HomFunctor where
import Functional as Fn
open import Function.Proofs
open import Function.Equals
open import Function.Equals.Proofs
open import Logic.Predicate
import Lvl
import Relator.Equals.Proofs.Equiv
open import Structure.Category
open import Structure.Category.Dual
open import Structure.Category.Functor
open import Structure.Categorical.Properties
open import Structure.Function
open import Structure.Operator
open import Structure.Relator.Equivalence
open import Structure.Relator.Properties
open import Structure.Setoid
open import Syntax.Transitivity
open import Type.Category.ExtensionalFunctionsCategory
open import Type
private variable ā āā āā āā : Lvl.Level
-- Note: This is implicitly using the identity type as the equivalence for (_ā¶_).
module _ {Obj : Type{āā}} {_ā¶_ : Obj ā Obj ā Type{āā}} (C : Category(_ā¶_)) where
open Category(C)
covariantHomFunctor : Obj ā ((intro C) āį¶ įµāæį¶įµįµŹ³ typeExtensionalFnCategoryObject{āā})
ā.witness (covariantHomFunctor x) y = (x ā¶ y)
Functor.map (ā.proof (covariantHomFunctor _)) = (_ā_)
_ā_.proof (Function.congruence (Functor.map-function (ā.proof (covariantHomFunctor _))) {fā} {fā} fāfā) {g} = congruenceāā(_ā_) ⦠binaryOperator ⦠g fāfā
_ā_.proof (Functor.op-preserving (ā.proof (covariantHomFunctor _))) = Morphism.associativity(_ā_)
_ā_.proof (Functor.id-preserving (ā.proof (covariantHomFunctor _))) = Morphism.identityā(_ā_)(id)
contravariantHomFunctor : Obj ā (dual(intro C) āį¶ įµāæį¶įµįµŹ³ typeExtensionalFnCategoryObject{āā})
ā.witness (contravariantHomFunctor x) y = (y ā¶ x)
Functor.map (ā.proof (contravariantHomFunctor _)) = Fn.swap(_ā_)
_ā_.proof (Function.congruence (Functor.map-function (ā.proof (contravariantHomFunctor _))) {gā} {gā} gāgā) {f} = congruenceāįµ£(_ā_) ⦠binaryOperator ⦠f gāgā
_ā_.proof (Functor.op-preserving (ā.proof (contravariantHomFunctor _))) = symmetry(_) (Morphism.associativity(_ā_))
_ā_.proof (Functor.id-preserving (ā.proof (contravariantHomFunctor _))) = Morphism.identityįµ£(_ā_)(id)
|
[GOAL]
n : ā
⢠(n + 1)ā¼ = (n + 1) * (n - 1)ā¼
[PROOFSTEP]
cases n
[GOAL]
case zero
⢠(zero + 1)ā¼ = (zero + 1) * (zero - 1)ā¼
[PROOFSTEP]
rfl
[GOAL]
case succ
nā : ā
⢠(succ nā + 1)ā¼ = (succ nā + 1) * (succ nā - 1)ā¼
[PROOFSTEP]
rfl
[GOAL]
k : ā
⢠(k + 1 + 1)! = (k + 1 + 1)ā¼ * (k + 1)ā¼
[PROOFSTEP]
rw [doubleFactorial_add_two, factorial, factorial_eq_mul_doubleFactorial _, mul_comm _ kā¼, mul_assoc]
[GOAL]
n : ā
⢠(2 * (n + 1))⼠= 2 ^ (n + 1) * (n + 1)!
[PROOFSTEP]
rw [mul_add, mul_one, doubleFactorial_add_two, factorial, pow_succ, doubleFactorial_two_mul _, succ_eq_add_one]
[GOAL]
n : ā
⢠(2 * n + 2) * (2 ^ n * n !) = 2 ^ n * 2 * ((n + 1) * n !)
[PROOFSTEP]
ring
[GOAL]
n : ā
⢠(2 * (n + 1))ā¼ = ā i in Finset.range (n + 1), 2 * (i + 1)
[PROOFSTEP]
rw [Finset.prod_range_succ, ā doubleFactorial_eq_prod_even _, mul_comm (2 * n)ā¼, (by ring : 2 * (n + 1) = 2 * n + 2)]
[GOAL]
n : ā
⢠2 * (n + 1) = 2 * n + 2
[PROOFSTEP]
ring
[GOAL]
n : ā
⢠(2 * n + 2)ā¼ = (2 * n + 2) * (2 * n)ā¼
[PROOFSTEP]
rfl
[GOAL]
n : ā
⢠(2 * (n + 1) + 1)ā¼ = ā i in Finset.range (n + 1), (2 * (i + 1) + 1)
[PROOFSTEP]
rw [Finset.prod_range_succ, ā doubleFactorial_eq_prod_odd _, mul_comm (2 * n + 1)ā¼,
(by ring : 2 * (n + 1) + 1 = 2 * n + 1 + 2)]
[GOAL]
n : ā
⢠2 * (n + 1) + 1 = 2 * n + 1 + 2
[PROOFSTEP]
ring
[GOAL]
n : ā
⢠(2 * n + 1 + 2)ā¼ = (2 * n + 1 + 2) * (2 * n + 1)ā¼
[PROOFSTEP]
rfl
|
State Before: q : ā
⢠āexp ā qā = āexp ā q.reā State After: no goals Tactic: rw [norm_eq_sqrt_real_inner (exp ā q), inner_self, normSq_exp, Real.sqrt_sq_eq_abs,
Real.norm_eq_abs] |
Shortly after 20 : 00 , the German battleships engaged the 2nd Light Cruiser Squadron ; Markgraf fired primarily 15 cm shells . In this period , Markgraf was engaged by Agincourt 's 12 @-@ inch guns , which scored a single hit at 20 : 14 . The shell failed to explode and shattered on impact on the 8 @-@ inch side armor , causing minimal damage . Two of the adjoining 14 @-@ inch plates directly below the 8 @-@ inch armor were slightly forced inward and some minor flooding occurred . The heavy fire of the British fleet forced Scheer to order the fleet to turn away . Due to her reduced speed , Markgraf turned early in an attempt to maintain her place in the battle line ; this , however , forced Grosser Kurfürst to fall out of formation . Markgraf fell in behind Kronprinz while Grosser Kurfürst steamed ahead to return to her position behind König . After successfully withdrawing from the British , Scheer ordered the fleet to assume night cruising formation , though communication errors between Scheer aboard Friedrich der Grosse and Westfalen , the lead ship , caused delays . Several British light cruisers and destroyers stumbled into the German line around 21 : 20 . In the ensuing short engagement Markgraf hit the cruiser Calliope five times with her secondary guns . The fleet fell into formation by 23 : 30 , with Grosser Kurfürst the 13th vessel in the line of 24 capital ships .
|
module Feldspar.Frontend where
import Prelude (Integral, Ord, RealFloat, RealFrac)
import qualified Prelude as P
import Prelude.EDSL
import Control.Monad.Identity
import Data.Bits (Bits, FiniteBits)
import qualified Data.Bits as Bits
import Data.Complex (Complex)
import Data.Int
import Data.List (genericLength)
import Language.Syntactic (Internal)
import Language.Syntactic.Functional
import qualified Language.Syntactic as Syntactic
import qualified Control.Monad.Operational.Higher as Oper
import Language.Embedded.Imperative (IxRange)
import qualified Language.Embedded.Imperative as Imp
import qualified Data.Inhabited as Inhabited
import Data.TypedStruct
import Feldspar.Primitive.Representation
import Feldspar.Representation
import Feldspar.Sugar ()
--------------------------------------------------------------------------------
-- * Pure expressions
--------------------------------------------------------------------------------
----------------------------------------
-- ** General constructs
----------------------------------------
-- | Force evaluation of a value and share the result. Note that due to common
-- sub-expression elimination, this function is rarely needed in practice.
share :: (Syntax a, Syntax b)
=> a -- ^ Value to share
-> (a -> b) -- ^ Body in which to share the value
-> b
share = shareTag ""
-- Explicit sharing can be useful e.g. when the value to share contains a
-- function or when the code motion algorithm for some reason doesn't work
-- find opportunities for sharing.
-- | Explicit tagged sharing
shareTag :: (Syntax a, Syntax b)
=> String -- ^ A tag (that may be empty). May be used by a back end to
-- generate a sensible variable name.
-> a -- ^ Value to share
-> (a -> b) -- ^ Body in which to share the value
-> b
shareTag tag = sugarSymFeld (Let tag)
-- | For loop
forLoop :: Syntax st => Data Length -> st -> (Data Index -> st -> st) -> st
forLoop = sugarSymFeld ForLoop
-- | Conditional expression
cond :: Syntax a
=> Data Bool -- ^ Condition
-> a -- ^ True branch
-> a -- ^ False branch
-> a
cond = sugarSymFeld Cond
-- | Condition operator; use as follows:
--
-- @
-- cond1 `?` a $
-- cond2 `?` b $
-- cond3 `?` c $
-- default
-- @
(?) :: Syntax a
=> Data Bool -- ^ Condition
-> a -- ^ True branch
-> a -- ^ False branch
-> a
(?) = cond
infixl 1 ?
-- | Multi-way conditional expression
--
-- The first association @(a,b)@ in the list of cases for which @a@ is equal to
-- the scrutinee is selected, and the associated @b@ is returned as the result.
-- If no case matches, the default value is returned.
switch :: (Syntax a, Syntax b, PrimType (Internal a))
=> b -- ^ Default result
-> [(a,b)] -- ^ Cases (match, result)
-> a -- ^ Scrutinee
-> b -- ^ Result
switch def [] _ = def
switch def cs s = P.foldr
(\(c,a) b -> desugar c == desugar s ? a $ b)
def
cs
----------------------------------------
-- ** Literals
----------------------------------------
-- | Literal
value :: Syntax a => Internal a -> a
value = sugarSymFeld . Lit
false :: Data Bool
false = value False
true :: Data Bool
true = value True
instance Syntactic.Syntactic ()
where
type Domain () = FeldDomain
type Internal () = Int32
desugar () = unData 0
sugar _ = ()
-- | Example value
--
-- 'example' can be used similarly to 'undefined' in normal Haskell, i.e. to
-- create an expression whose value is irrelevant.
--
-- Note that it is generally not possible to use 'undefined' in Feldspar
-- expressions, as this will crash the compiler.
example :: Syntax a => a
example = value Inhabited.example
----------------------------------------
-- ** Primitive functions
----------------------------------------
instance (Bounded a, Type a) => Bounded (Data a)
where
minBound = value minBound
maxBound = value maxBound
instance (Num a, PrimType a) => Num (Data a)
where
fromInteger = value . fromInteger
(+) = sugarSymFeld Add
(-) = sugarSymFeld Sub
(*) = sugarSymFeld Mul
negate = sugarSymFeld Neg
abs = sugarSymFeld Abs
signum = sugarSymFeld Sign
instance (Fractional a, PrimType a) => Fractional (Data a)
where
fromRational = value . fromRational
(/) = sugarSymFeld FDiv
instance (Floating a, PrimType a) => Floating (Data a)
where
pi = sugarSymFeld Pi
exp = sugarSymFeld Exp
log = sugarSymFeld Log
sqrt = sugarSymFeld Sqrt
(**) = sugarSymFeld Pow
sin = sugarSymFeld Sin
cos = sugarSymFeld Cos
tan = sugarSymFeld Tan
asin = sugarSymFeld Asin
acos = sugarSymFeld Acos
atan = sugarSymFeld Atan
sinh = sugarSymFeld Sinh
cosh = sugarSymFeld Cosh
tanh = sugarSymFeld Tanh
asinh = sugarSymFeld Asinh
acosh = sugarSymFeld Acosh
atanh = sugarSymFeld Atanh
-- | Alias for 'pi'
Ļ :: (Floating a, PrimType a) => Data a
Ļ = pi
-- | Integer division truncated toward zero
quot :: (Integral a, PrimType a) => Data a -> Data a -> Data a
quot = sugarSymFeld Quot
-- | Integer remainder satisfying
--
-- > (x `quot` y)*y + (x `rem` y) == x
rem :: (Integral a, PrimType a) => Data a -> Data a -> Data a
rem = sugarSymFeld Rem
-- | Simultaneous @quot@ and @rem@
quotRem :: (Integral a, PrimType a) => Data a -> Data a -> (Data a, Data a)
quotRem a b = (q,r)
where
q = quot a b
r = a - b * q
-- | Integer division truncated toward negative infinity
div :: (Integral a, PrimType a) => Data a -> Data a -> Data a
div = sugarSymFeld Div
-- | Integer modulus, satisfying
--
-- > (x `div` y)*y + (x `mod` y) == x
mod :: (Integral a, PrimType a) => Data a -> Data a -> Data a
mod = sugarSymFeld Mod
-- | Integer division assuming `unsafeBalancedDiv x y * y == x` (i.e. no
-- remainder)
--
-- The advantage of using 'unsafeBalancedDiv' over 'quot' or 'div' is that the
-- above assumption can be used for simplifying the expression.
unsafeBalancedDiv :: (Integral a, PrimType a) => Data a -> Data a -> Data a
unsafeBalancedDiv a b = guardValLabel
InternalAssertion
(rem a b == 0)
"unsafeBalancedDiv: division not balanced"
(sugarSymFeld DivBalanced a b)
-- Note: We can't check that `result * b == a`, because `result * b` gets
-- simplified to `a`.
-- | Construct a complex number
complex :: (Num a, PrimType a, PrimType (Complex a))
=> Data a -- ^ Real part
-> Data a -- ^ Imaginary part
-> Data (Complex a)
complex = sugarSymFeld Complex
-- | Construct a complex number
polar :: (Floating a, PrimType a, PrimType (Complex a))
=> Data a -- ^ Magnitude
-> Data a -- ^ Phase
-> Data (Complex a)
polar = sugarSymFeld Polar
-- | Extract the real part of a complex number
realPart :: (PrimType a, PrimType (Complex a)) => Data (Complex a) -> Data a
realPart = sugarSymFeld Real
-- | Extract the imaginary part of a complex number
imagPart :: (PrimType a, PrimType (Complex a)) => Data (Complex a) -> Data a
imagPart = sugarSymFeld Imag
-- | Extract the magnitude of a complex number's polar form
magnitude :: (RealFloat a, PrimType a, PrimType (Complex a)) =>
Data (Complex a) -> Data a
magnitude = sugarSymFeld Magnitude
-- | Extract the phase of a complex number's polar form
phase :: (RealFloat a, PrimType a, PrimType (Complex a)) =>
Data (Complex a) -> Data a
phase = sugarSymFeld Phase
-- | Complex conjugate
conjugate :: (RealFloat a, PrimType (Complex a)) =>
Data (Complex a) -> Data (Complex a)
conjugate = sugarSymFeld Conjugate
-- `RealFloat` could be replaced by `Num` here, but it seems more consistent
-- to use `RealFloat` for all functions.
-- | Integral type casting
i2n :: (Integral i, Num n, PrimType i, PrimType n) => Data i -> Data n
i2n = sugarSymFeld I2N
-- | Cast integer to 'Bool'
i2b :: (Integral a, PrimType a) => Data a -> Data Bool
i2b = sugarSymFeld I2B
-- | Cast 'Bool' to integer
b2i :: (Integral a, PrimType a) => Data Bool -> Data a
b2i = sugarSymFeld B2I
-- | Round a floating-point number to an integer
round :: (RealFrac a, Num b, PrimType a, PrimType b) => Data a -> Data b
round = sugarSymFeld Round
-- | Boolean negation
not :: Data Bool -> Data Bool
not = sugarSymFeld Not
-- | Boolean conjunction
(&&) :: Data Bool -> Data Bool -> Data Bool
(&&) = sugarSymFeld And
infixr 3 &&
-- | Boolean disjunction
(||) :: Data Bool -> Data Bool -> Data Bool
(||) = sugarSymFeld Or
infixr 2 ||
-- | Equality
(==) :: PrimType a => Data a -> Data a -> Data Bool
(==) = sugarSymFeld Eq
-- | Inequality
(/=) :: PrimType a => Data a -> Data a -> Data Bool
a /= b = not (a==b)
-- | Less than
(<) :: (Ord a, PrimType a) => Data a -> Data a -> Data Bool
(<) = sugarSymFeld Lt
-- | Greater than
(>) :: (Ord a, PrimType a) => Data a -> Data a -> Data Bool
(>) = sugarSymFeld Gt
-- | Less than or equal
(<=) :: (Ord a, PrimType a) => Data a -> Data a -> Data Bool
(<=) = sugarSymFeld Le
-- | Greater than or equal
(>=) :: (Ord a, PrimType a) => Data a -> Data a -> Data Bool
(>=) = sugarSymFeld Ge
infix 4 ==, /=, <, >, <=, >=
-- | Return the smallest of two values
min :: (Ord a, PrimType a) => Data a -> Data a -> Data a
min a b = a<=b ? a $ b
-- There's no standard definition of min/max in C:
-- <http://stackoverflow.com/questions/3437404/min-and-max-in-c>
--
-- There is `fmin`/`fminf` for floating-point numbers, but these are
-- implemented essentially as above (except that they handle `NaN`
-- specifically:
-- <https://sourceware.org/git/?p=glibc.git;a=blob;f=math/s_fmin.c;hb=HEAD>
-- | Return the greatest of two values
max :: (Ord a, PrimType a) => Data a -> Data a -> Data a
max a b = a>=b ? a $ b
----------------------------------------
-- ** Bit manipulation
----------------------------------------
-- | Bit-wise \"and\"
(.&.) :: (Bits a, PrimType a) => Data a -> Data a -> Data a
(.&.) = sugarSymFeld BitAnd
-- | Bit-wise \"or\"
(.|.) :: (Bits a, PrimType a) => Data a -> Data a -> Data a
(.|.) = sugarSymFeld BitOr
-- | Bit-wise \"xor\"
xor :: (Bits a, PrimType a) => Data a -> Data a -> Data a
xor = sugarSymFeld BitXor
-- | Bit-wise \"xor\"
(ā) :: (Bits a, PrimType a) => Data a -> Data a -> Data a
(ā) = xor
-- | Bit-wise complement
complement :: (Bits a, PrimType a) => Data a -> Data a
complement = sugarSymFeld BitCompl
-- | Left shift
shiftL :: (Bits a, PrimType a)
=> Data a -- ^ Value to shift
-> Data Int32 -- ^ Shift amount (negative value gives right shift)
-> Data a
shiftL = sugarSymFeld ShiftL
-- | Right shift
shiftR :: (Bits a, PrimType a)
=> Data a -- ^ Value to shift
-> Data Int32 -- ^ Shift amount (negative value gives left shift)
-> Data a
shiftR = sugarSymFeld ShiftR
-- | Left shift
(.<<.) :: (Bits a, PrimType a)
=> Data a -- ^ Value to shift
-> Data Int32 -- ^ Shift amount (negative value gives right shift)
-> Data a
(.<<.) = shiftL
-- | Right shift
(.>>.) :: (Bits a, PrimType a)
=> Data a -- ^ Value to shift
-> Data Int32 -- ^ Shift amount (negative value gives left shift)
-> Data a
(.>>.) = shiftR
infixl 8 `shiftL`, `shiftR`, .<<., .>>.
infixl 7 .&.
infixl 6 `xor`
infixl 5 .|.
bitSize :: forall a . FiniteBits a => Data a -> Length
bitSize _ = P.fromIntegral $ Bits.finiteBitSize (a :: a)
where
a = P.error "finiteBitSize evaluates its argument"
-- | Set all bits to one
allOnes :: (Bits a, Num a, PrimType a) => Data a
allOnes = complement 0
-- | Set the @n@ lowest bits to one
oneBits :: (Bits a, Num a, PrimType a) => Data Int32 -> Data a
oneBits n = complement (allOnes .<<. n)
-- | Extract the @k@ lowest bits
lsbs :: (Bits a, Num a, PrimType a) => Data Int32 -> Data a -> Data a
lsbs k i = i .&. oneBits k
-- | Integer logarithm in base 2. Returns \(\lfloor log_2(x) \rfloor\).
-- Assumes \(x>0\).
ilog2 :: (FiniteBits a, Integral a, PrimType a) => Data a -> Data a
ilog2 a = guardValLabel InternalAssertion (a >= 1) "ilog2: argument < 1" $
snd $ P.foldr (\ffi vr -> share vr (step ffi)) (a,0) ffis
where
step (ff,i) (v,r) =
share (b2i (v > fromInteger ff) .<<. value i) $ \shift ->
(v .>>. i2n shift, r .|. shift)
-- [(0x1, 0), (0x3, 1), (0xF, 2), (0xFF, 3), (0xFFFF, 4), ...]
ffis
= (`P.zip` [0..])
$ P.takeWhile (P.<= (2 P.^ (bitSize a `P.div` 2) - 1 :: Integer))
$ P.map ((subtract 1) . (2 P.^) . (2 P.^))
$ [(0::Integer)..]
-- Based on this algorithm:
-- <http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog>
----------------------------------------
-- ** Arrays
----------------------------------------
-- | Index into an array
arrIx :: Syntax a => IArr a -> Data Index -> a
arrIx arr i = resugar $ mapStruct ix $ unIArr arr
where
ix :: forall b . PrimType' b => Imp.IArr Index b -> Data b
ix arr' = sugarSymFeldPrim
(GuardVal InternalAssertion "arrIx: index out of bounds")
(i < length arr)
(sugarSymFeldPrim (ArrIx arr') (i + iarrOffset arr) :: Data b)
class Indexed a
where
type IndexedElem a
-- | Indexing operator. If @a@ is 'Finite', it is assumed that
-- @i < `length` a@ in any expression @a `!` i@.
(!) :: a -> Data Index -> IndexedElem a
infixl 9 !
-- | Linear structures with a length. If the type is also 'Indexed', the length
-- is the successor of the maximal allowed index.
class Finite a
where
-- | The length of a finite structure
length :: a -> Data Length
instance Finite (Arr a) where length = arrLength
instance Finite (IArr a) where length = iarrLength
-- | Linear structures that can be sliced
class Slicable a
where
-- | Take a slice of a structure
slice
:: Data Index -- ^ Start index
-> Data Length -- ^ Slice length
-> a -- ^ Structure to slice
-> a
instance Syntax a => Indexed (IArr a)
where
type IndexedElem (IArr a) = a
(!) = arrIx
instance Slicable (Arr a)
where
slice from len (Arr o l arr) = Arr o' l' arr
where
o' = guardValLabel InternalAssertion (from<=l) "invalid Arr slice" (o+from)
l' = guardValLabel InternalAssertion (from+len<=l) "invalid Arr slice" len
instance Slicable (IArr a)
where
slice from len (IArr o l arr) = IArr o' l' arr
where
o' = guardValLabel InternalAssertion (from<=l) "invalid IArr slice" (o+from)
l' = guardValLabel InternalAssertion (from+len<=l) "invalid IArr slice" len
----------------------------------------
-- ** Syntactic conversion
----------------------------------------
desugar :: Syntax a => a -> Data (Internal a)
desugar = Data . Syntactic.desugar
sugar :: Syntax a => Data (Internal a) -> a
sugar = Syntactic.sugar . unData
-- | Cast between two values that have the same syntactic representation
resugar :: (Syntax a, Syntax b, Internal a ~ Internal b) => a -> b
resugar = Syntactic.resugar
----------------------------------------
-- ** Assertions
----------------------------------------
-- | Guard a value by an assertion (with implicit label @`UserAssertion` ""@)
guardVal :: Syntax a
=> Data Bool -- ^ Condition that is expected to be true
-> String -- ^ Error message
-> a -- ^ Value to attach the assertion to
-> a
guardVal = guardValLabel $ UserAssertion ""
-- | Like 'guardVal' but with an explicit assertion label
guardValLabel :: Syntax a
=> AssertionLabel -- ^ Assertion label
-> Data Bool -- ^ Condition that is expected to be true
-> String -- ^ Error message
-> a -- ^ Value to attach the assertion to
-> a
guardValLabel c cond msg = sugarSymFeld (GuardVal c msg) cond
----------------------------------------
-- ** Unsafe operations
----------------------------------------
-- | Turn a 'Comp' computation into a pure value. For this to be safe, the
-- computation should be free of side effects and independent of its
-- environment.
unsafePerform :: Syntax a => Comp a -> a
unsafePerform = sugarSymFeld . UnsafePerform . fmap desugar
--------------------------------------------------------------------------------
-- * Programs with computational effects
--------------------------------------------------------------------------------
-- | Monads that support computational effects: mutable data structures and
-- control flow
class Monad m => MonadComp m
where
-- | Lift a 'Comp' computation
liftComp :: Comp a -> m a
-- | Conditional statement
iff :: Data Bool -> m () -> m () -> m ()
-- | For loop
for :: (Integral n, PrimType n) =>
IxRange (Data n) -> (Data n -> m ()) -> m ()
-- | While loop
while :: m (Data Bool) -> m () -> m ()
instance MonadComp Comp
where
liftComp = id
iff c t f = Comp $ Imp.iff c (unComp t) (unComp f)
for range body = Comp $ Imp.for range (unComp . body)
while cont body = Comp $ Imp.while (unComp cont) (unComp body)
----------------------------------------
-- ** References
----------------------------------------
-- | Create an uninitialized reference
newRef :: (Syntax a, MonadComp m) => m (Ref a)
newRef = newNamedRef "r"
-- | Create an uninitialized named reference
--
-- The provided base name may be appended with a unique identifier to avoid name
-- collisions.
newNamedRef :: (Syntax a, MonadComp m)
=> String -- ^ Base name
-> m (Ref a)
newNamedRef base = liftComp $ fmap Ref $
mapStructA (const $ Comp $ Imp.newNamedRef base) typeRep
-- | Create an initialized named reference
initRef :: (Syntax a, MonadComp m) => a -> m (Ref a)
initRef = initNamedRef "r"
-- | Create an initialized reference
--
-- The provided base name may be appended with a unique identifier to avoid name
-- collisions.
initNamedRef :: (Syntax a, MonadComp m)
=> String -- ^ Base name
-> a -- ^ Initial value
-> m (Ref a)
initNamedRef base =
liftComp . fmap Ref . mapStructA (Comp . Imp.initNamedRef base) . resugar
-- | Get the contents of a reference.
getRef :: (Syntax a, MonadComp m) => Ref a -> m a
getRef = liftComp . fmap resugar . mapStructA (Comp . Imp.getRef) . unRef
-- | Set the contents of a reference.
setRef :: (Syntax a, MonadComp m) => Ref a -> a -> m ()
setRef r
= liftComp
. sequence_
. zipListStruct (\r' a' -> Comp $ Imp.setRef r' a') (unRef r)
. resugar
-- | Modify the contents of reference.
modifyRef :: (Syntax a, MonadComp m) => Ref a -> (a -> a) -> m ()
modifyRef r f = setRef r . f =<< unsafeFreezeRef r
-- | Freeze the contents of reference (only safe if the reference is not updated
-- as long as the resulting value is alive).
unsafeFreezeRef :: (Syntax a, MonadComp m) => Ref a -> m a
unsafeFreezeRef
= liftComp
. fmap resugar
. mapStructA (Comp . Imp.unsafeFreezeRef)
. unRef
----------------------------------------
-- ** Arrays
----------------------------------------
-- | Create an uninitialized array
newArr :: (Type (Internal a), MonadComp m) => Data Length -> m (Arr a)
newArr = newNamedArr "a"
-- | Create an uninitialized named array
--
-- The provided base name may be appended with a unique identifier to avoid name
-- collisions.
newNamedArr :: (Type (Internal a), MonadComp m)
=> String -- ^ Base name
-> Data Length
-> m (Arr a)
newNamedArr base l = liftComp $ fmap (Arr 0 l) $
mapStructA (const (Comp $ Imp.newNamedArr base l)) typeRep
-- | Create an array and initialize it with a constant list
constArr :: (PrimType (Internal a), MonadComp m)
=> [Internal a] -- ^ Initial contents
-> m (Arr a)
constArr = constNamedArr "a"
-- | Create a named array and initialize it with a constant list
--
-- The provided base name may be appended with a unique identifier to avoid name
-- collisions.
constNamedArr :: (PrimType (Internal a), MonadComp m)
=> String -- ^ Base name
-> [Internal a] -- ^ Initial contents
-> m (Arr a)
constNamedArr base as =
liftComp $ fmap (Arr 0 len . Single) $ Comp $ Imp.constNamedArr base as
where
len = value $ genericLength as
-- | Get an element of an array
getArr :: (Syntax a, MonadComp m) => Arr a -> Data Index -> m a
getArr arr i = do
assertLabel
InternalAssertion
(i < length arr)
"getArr: index out of bounds"
liftComp
$ fmap resugar
$ mapStructA (Comp . flip Imp.getArr (i + arrOffset arr))
$ unArr arr
-- | Set an element of an array
setArr :: forall m a . (Syntax a, MonadComp m) =>
Arr a -> Data Index -> a -> m ()
setArr arr i a = do
assertLabel
InternalAssertion
(i < length arr)
"setArr: index out of bounds"
liftComp
$ sequence_
$ zipListStruct
(\a' arr' -> Comp $ Imp.setArr arr' (i + arrOffset arr) a') rep
$ unArr arr
where
rep = resugar a :: Struct PrimType' Data (Internal a)
-- | Copy the contents of an array to another array. The length of the
-- destination array must not be less than that of the source array.
--
-- In order to copy only a part of an array, use 'slice' before calling
-- 'copyArr'.
copyArr :: MonadComp m
=> Arr a -- ^ Destination
-> Arr a -- ^ Source
-> m ()
copyArr arr1 arr2 = do
assertLabel
InternalAssertion
(length arr1 >= length arr2)
"copyArr: destination too small"
liftComp $ sequence_ $
zipListStruct
(\a1 a2 ->
Comp $ Imp.copyArr
(a1, arrOffset arr1)
(a2, arrOffset arr2)
(length arr2)
)
(unArr arr1)
(unArr arr2)
-- | Freeze a mutable array to an immutable one. This involves copying the array
-- to a newly allocated one.
freezeArr :: (Type (Internal a), MonadComp m) => Arr a -> m (IArr a)
freezeArr arr = liftComp $ do
arr2 <- newArr (length arr)
copyArr arr2 arr
unsafeFreezeArr arr2
-- This is better than calling `freezeArr` from imperative-edsl, since that
-- one copies without offset.
-- | A version of 'freezeArr' that slices the array from 0 to the given length
freezeSlice :: (Type (Internal a), MonadComp m) =>
Data Length -> Arr a -> m (IArr a)
freezeSlice len = fmap (slice 0 len) . freezeArr
-- | Freeze a mutable array to an immutable one without making a copy. This is
-- generally only safe if the the mutable array is not updated as long as the
-- immutable array is alive.
unsafeFreezeArr :: MonadComp m => Arr a -> m (IArr a)
unsafeFreezeArr arr
= liftComp
$ fmap (IArr (arrOffset arr) (length arr))
$ mapStructA (Comp . Imp.unsafeFreezeArr)
$ unArr arr
-- | A version of 'unsafeFreezeArr' that slices the array from 0 to the given
-- length
unsafeFreezeSlice :: MonadComp m => Data Length -> Arr a -> m (IArr a)
unsafeFreezeSlice len = fmap (slice 0 len) . unsafeFreezeArr
-- | Thaw an immutable array to a mutable one. This involves copying the array
-- to a newly allocated one.
thawArr :: (Type (Internal a), MonadComp m) => IArr a -> m (Arr a)
thawArr arr = liftComp $ do
arr2 <- unsafeThawArr arr
arr3 <- newArr (length arr)
copyArr arr3 arr2
return arr3
-- | Thaw an immutable array to a mutable one without making a copy. This is
-- generally only safe if the the mutable array is not updated as long as the
-- immutable array is alive.
unsafeThawArr :: MonadComp m => IArr a -> m (Arr a)
unsafeThawArr arr
= liftComp
$ fmap (Arr (iarrOffset arr) (length arr))
$ mapStructA (Comp . Imp.unsafeThawArr)
$ unIArr arr
-- | Create an immutable array and initialize it with a constant list
constIArr :: (PrimType (Internal a), MonadComp m) =>
[Internal a] -> m (IArr a)
constIArr = constArr >=> unsafeFreezeArr
----------------------------------------
-- ** Control-flow
----------------------------------------
-- | Conditional statement that returns an expression
ifE :: (Syntax a, MonadComp m)
=> Data Bool -- ^ Condition
-> m a -- ^ True branch
-> m a -- ^ False branch
-> m a
ifE c t f = do
res <- newRef
iff c (t >>= setRef res) (f >>= setRef res)
unsafeFreezeRef res
-- | Break out from a loop
break :: MonadComp m => m ()
break = liftComp $ Comp Imp.break
-- | Assertion (with implicit label @`UserAssertion` ""@)
assert :: MonadComp m
=> Data Bool -- ^ Expression that should be true
-> String -- ^ Message in case of failure
-> m ()
assert = assertLabel $ UserAssertion ""
-- | Like 'assert' but tagged with an explicit assertion label
assertLabel :: MonadComp m
=> AssertionLabel -- ^ Assertion label
-> Data Bool -- ^ Expression that should be true
-> String -- ^ Message in case of failure
-> m ()
assertLabel c cond msg =
liftComp $ Comp $ Oper.singleInj $ Assert c cond msg
----------------------------------------
-- ** Misc.
----------------------------------------
-- | Force evaluation of a value and share the result (monadic version of
-- 'share')
shareM :: (Syntax a, MonadComp m) => a -> m a
shareM = initRef >=> unsafeFreezeRef
-- This function is more commonly needed than `share`, since code motion
-- doesn't work across monadic binds.
|
#!/usr/bin/env python3
from flask import Flask, request, jsonify
import json
import pickle
import pandas as pd
import numpy as np
import drmodel
import pytest
import requests
url = 'http://0.0.0.0:8000/api'
feature = [[5.8, 4.0, 1.2, 0.2]]
labels ={
0: "setosa",
1: "versicolor",
2: "virginica"
}
def test_predict():
r = requests.post(url,json={'feature': feature})
print(labels[r.json()])
assert labels[r.json()] == "setosa" |
(*<*)
(*
Title: Theory stream.thy (FOCUS streams)
Author: Maria Spichkova <maria.spichkova at rmit.edu.au>, 2013
*)
(*>*)
header "FOCUS streams: operators and lemmas"
theory stream
imports ListExtras ArithExtras
begin
subsection {* Definition of the FOCUS stream types *}
-- "Finite timed FOCUS stream"
type_synonym 'a fstream = "'a list list"
-- "Infinite timed FOCUS stream"
type_synonym 'a istream = "nat \<Rightarrow> 'a list"
-- "Infinite untimed FOCUS stream"
type_synonym 'a iustream = "nat \<Rightarrow> 'a"
-- "FOCUS stream (general)"
datatype 'a stream =
FinT "'a fstream" -- "finite timed streams"
| FinU "'a list" -- "finite untimed streams"
| InfT "'a istream" -- "infinite timed streams"
| InfU "'a iustream" -- "infinite untimed streams"
subsection {* Definitions of operators *}
-- "domain of an infinite untimed stream"
definition
infU_dom :: "natInf set"
where
"infU_dom \<equiv> {x. \<exists> i. x = (Fin i)} \<union> {\<infinity>}"
-- "domain of a finite untimed stream (using natural numbers enriched by Infinity)"
definition
finU_dom_natInf :: "'a list \<Rightarrow> natInf set"
where
"finU_dom_natInf s \<equiv> {x. \<exists> i. x = (Fin i) \<and> i < (length s)}"
-- "domain of a finite untimed stream"
primrec
finU_dom :: "'a list \<Rightarrow> nat set"
where
"finU_dom [] = {}" |
"finU_dom (x#xs) = {length xs} \<union> (finU_dom xs)"
-- "range of a finite timed stream"
primrec
finT_range :: "'a fstream \<Rightarrow> 'a set"
where
"finT_range [] = {}" |
"finT_range (x#xs) = (set x) \<union> finT_range xs"
-- "range of a finite untimed stream"
definition
finU_range :: "'a list \<Rightarrow> 'a set"
where
"finU_range x \<equiv> set x"
-- "range of an infinite timed stream"
definition
infT_range :: "'a istream \<Rightarrow> 'a set"
where
"infT_range s \<equiv> {y. \<exists> i::nat. y mem (s i)}"
-- "range of a finite untimed stream"
definition
infU_range :: "(nat \<Rightarrow> 'a) \<Rightarrow> 'a set"
where
"infU_range s \<equiv> { y. \<exists> i::nat. y = (s i) }"
-- "range of a (general) stream"
definition
stream_range :: "'a stream \<Rightarrow> 'a set"
where
"stream_range s \<equiv> case s of
FinT x \<Rightarrow> finT_range x
| FinU x \<Rightarrow> finU_range x
| InfT x \<Rightarrow> infT_range x
| InfU x \<Rightarrow> infU_range x"
-- "finite timed stream that consists of n empty time intervals"
primrec
nticks :: "nat \<Rightarrow> 'a fstream"
where
"nticks 0 = []" |
"nticks (Suc i) = [] # (nticks i)"
-- "removing the first element from an infinite stream"
-- "in the case of an untimed stream: removing the first data element"
-- "in the case of a timed stream: removing the first time interval"
definition
inf_tl :: "(nat \<Rightarrow> 'a) \<Rightarrow> (nat \<Rightarrow> 'a)"
where
"inf_tl s \<equiv> (\<lambda> i. s (Suc i))"
-- "removing i first elements from an infinite stream s"
-- "in the case of an untimed stream: removing i first data elements"
-- "in the case of a timed stream: removing i first time intervals"
definition
inf_drop :: "nat \<Rightarrow> (nat \<Rightarrow> 'a) \<Rightarrow> (nat \<Rightarrow> 'a)"
where
"inf_drop i s \<equiv> \<lambda> j. s (i+j)"
-- "finding the first nonempty time interval in a finite timed stream"
primrec
fin_find1nonemp :: "'a fstream \<Rightarrow> 'a list"
where
"fin_find1nonemp [] = []" |
"fin_find1nonemp (x#xs) =
( if x = []
then fin_find1nonemp xs
else x )"
-- "finding the first nonempty time interval in an infinite timed stream"
definition
inf_find1nonemp :: "'a istream \<Rightarrow> 'a list"
where
"inf_find1nonemp s
\<equiv>
( if (\<exists> i. s i \<noteq> [])
then s (LEAST i. s i \<noteq> [])
else [] )"
-- "finding the index of the first nonempty time interval in a finite timed stream"
primrec
fin_find1nonemp_index :: "'a fstream \<Rightarrow> nat"
where
"fin_find1nonemp_index [] = 0" |
"fin_find1nonemp_index (x#xs) =
( if x = []
then Suc (fin_find1nonemp_index xs)
else 0 )"
-- "finding the index of the first nonempty time interval in an infinite timed stream"
definition
inf_find1nonemp_index :: "'a istream \<Rightarrow> nat"
where
"inf_find1nonemp_index s
\<equiv>
( if (\<exists> i. s i \<noteq> [])
then (LEAST i. s i \<noteq> [])
else 0 )"
-- "length of a finite timed stream: number of data elements in this stream"
primrec
fin_length :: "'a fstream \<Rightarrow> nat"
where
"fin_length [] = 0" |
"fin_length (x#xs) = (length x) + (fin_length xs)"
-- "length of a (general) stream"
definition
stream_length :: "'a stream \<Rightarrow> natInf"
where
"stream_length s \<equiv>
case s of
(FinT x) \<Rightarrow> Fin (fin_length x)
| (FinU x) \<Rightarrow> Fin (length x)
| (InfT x) \<Rightarrow> \<infinity>
| (InfU x) \<Rightarrow> \<infinity>"
-- "removing the first k elements from a finite (nonempty) timed stream"
axiomatization
fin_nth :: "'a fstream \<Rightarrow> nat \<Rightarrow> 'a"
where
fin_nth_Cons:
"fin_nth (hds # tls) k =
( if hds = []
then fin_nth tls k
else ( if (k < (length hds))
then nth hds k
else fin_nth tls (k - length hds) ))"
-- "removing i first data elements from an infinite timed stream s"
primrec
inf_nth :: "'a istream \<Rightarrow> nat \<Rightarrow> 'a"
where
"inf_nth s 0 = hd (s (LEAST i.(s i) \<noteq> []))" |
"inf_nth s (Suc k) =
( if ((Suc k) < (length (s 0)))
then (nth (s 0) (Suc k))
else ( if (s 0) = []
then (inf_nth (inf_tl (inf_drop
(LEAST i. (s i) \<noteq> []) s)) k )
else inf_nth (inf_tl s) k ))"
-- "removing the first k data elements from a (general) stream"
definition
stream_nth :: "'a stream \<Rightarrow> nat \<Rightarrow> 'a"
where
"stream_nth s k \<equiv>
case s of (FinT x) \<Rightarrow> fin_nth x k
| (FinU x) \<Rightarrow> nth x k
| (InfT x) \<Rightarrow> inf_nth x k
| (InfU x) \<Rightarrow> x k"
-- "prefix of an infinite stream"
primrec
inf_prefix :: "'a list \<Rightarrow> (nat \<Rightarrow> 'a) \<Rightarrow> nat \<Rightarrow> bool"
where
"inf_prefix [] s k = True" |
"inf_prefix (x#xs) s k = ( (x = (s k)) \<and> (inf_prefix xs s (Suc k)) )"
-- "prefix of a finite stream"
primrec
fin_prefix :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool"
where
"fin_prefix [] s = True" |
"fin_prefix (x#xs) s =
(if (s = [])
then False
else (x = (hd s)) \<and> (fin_prefix xs s) )"
-- "prefix of a (general) stream"
definition
stream_prefix :: "'a stream \<Rightarrow> 'a stream \<Rightarrow> bool"
where
"stream_prefix p s \<equiv>
(case p of
(FinT x) \<Rightarrow>
(case s of (FinT y) \<Rightarrow> (fin_prefix x y)
| (FinU y) \<Rightarrow> False
| (InfT y) \<Rightarrow> inf_prefix x y 0
| (InfU y) \<Rightarrow> False )
| (FinU x) \<Rightarrow>
(case s of (FinT y) \<Rightarrow> False
| (FinU y) \<Rightarrow> (fin_prefix x y)
| (InfT y) \<Rightarrow> False
| (InfU y) \<Rightarrow> inf_prefix x y 0 )
| (InfT x) \<Rightarrow>
(case s of (FinT y) \<Rightarrow> False
| (FinU y) \<Rightarrow> False
| (InfT y) \<Rightarrow> (\<forall> i. x i = y i)
| (InfU y) \<Rightarrow> False )
| (InfU x) \<Rightarrow>
(case s of (FinT y) \<Rightarrow> False
| (FinU y) \<Rightarrow> False
| (InfT y) \<Rightarrow> False
| (InfU y) \<Rightarrow> (\<forall> i. x i = y i) ) )"
-- "truncating a finite stream after the n-th element"
primrec
fin_truncate :: "'a list \<Rightarrow> nat \<Rightarrow> 'a list"
where
"fin_truncate [] n = []" |
"fin_truncate (x#xs) i =
(case i of 0 \<Rightarrow> []
| (Suc n) \<Rightarrow> x # (fin_truncate xs n))"
-- "truncating a finite stream after the n-th element"
-- "n is of type of natural numbers enriched by Infinity"
definition
fin_truncate_plus :: "'a list \<Rightarrow> natInf \<Rightarrow> 'a list"
where
"fin_truncate_plus s n
\<equiv>
case n of (Fin i) \<Rightarrow> fin_truncate s i
| \<infinity> \<Rightarrow> s "
-- "truncating an infinite stream after the n-th element"
primrec
inf_truncate :: "(nat \<Rightarrow> 'a) \<Rightarrow> nat \<Rightarrow> 'a list"
where
"inf_truncate s 0 = [ s 0 ]" |
"inf_truncate s (Suc k) = (inf_truncate s k) @ [s (Suc k)]"
-- "truncating an infinite stream after the n-th element"
-- "n is of type of natural numbers enriched by Infinity"
definition
inf_truncate_plus :: "'a istream \<Rightarrow> natInf \<Rightarrow> 'a stream"
where
"inf_truncate_plus s n
\<equiv>
case n of (Fin i) \<Rightarrow> FinT (inf_truncate s i)
| \<infinity> \<Rightarrow> InfT s"
-- "concatanation of a finite and an infinite stream"
definition
fin_inf_append ::
"'a list \<Rightarrow> (nat \<Rightarrow> 'a) \<Rightarrow> (nat \<Rightarrow> 'a)"
where
"fin_inf_append us s \<equiv>
(\<lambda> i. ( if (i < (length us))
then (nth us i)
else s (i - (length us)) ))"
-- "insuring that the infinite timed stream is time-synchronous"
definition
ts :: "'a istream \<Rightarrow> bool"
where
"ts s \<equiv> \<forall> i. (length (s i) = 1)"
-- "insuring that each time interval of an infinite timed stream contains at most n data elements"
definition
msg :: "nat \<Rightarrow> 'a istream \<Rightarrow> bool"
where
"msg n s \<equiv> \<forall> t. length (s t) \<le> n"
-- "insuring that each time interval of a finite timed stream contains at most n data elements"
primrec
fin_msg :: "nat \<Rightarrow> 'a list list \<Rightarrow> bool"
where
"fin_msg n [] = True" |
"fin_msg n (x#xs) = (((length x) \<le> n) \<and> (fin_msg n xs))"
-- "making a finite timed stream to a finite untimed stream"
definition
fin_make_untimed :: "'a fstream \<Rightarrow> 'a list"
where
"fin_make_untimed x \<equiv> concat x"
-- "making an infinite timed stream to an infinite untimed stream"
-- "(auxiliary function)"
primrec
inf_make_untimed1 :: "'a istream \<Rightarrow> nat \<Rightarrow> 'a "
where
inf_make_untimed1_0:
"inf_make_untimed1 s 0 = hd (s (LEAST i.(s i) \<noteq> []))" |
inf_make_untimed1_Suc:
"inf_make_untimed1 s (Suc k) =
( if ((Suc k) < length (s 0))
then nth (s 0) (Suc k)
else ( if (s 0) = []
then (inf_make_untimed1 (inf_tl (inf_drop
(LEAST i. \<forall> j. j < i \<longrightarrow> (s j) = [])
s)) k )
else inf_make_untimed1 (inf_tl s) k ))"
-- "making an infinite timed stream to an infinite untimed stream"
-- "(main function)"
definition
inf_make_untimed :: "'a istream \<Rightarrow> (nat \<Rightarrow> 'a) "
where
"inf_make_untimed s
\<equiv>
\<lambda> i. inf_make_untimed1 s i"
-- "making a (general) stream untimed"
definition
make_untimed :: "'a stream \<Rightarrow> 'a stream"
where
"make_untimed s \<equiv>
case s of (FinT x) \<Rightarrow> FinU (fin_make_untimed x)
| (FinU x) \<Rightarrow> FinU x
| (InfT x) \<Rightarrow>
(if (\<exists> i.\<forall> j. i < j \<longrightarrow> (x j) = [])
then FinU (fin_make_untimed (inf_truncate x
(LEAST i.\<forall> j. i < j \<longrightarrow> (x j) = [])))
else InfU (inf_make_untimed x))
| (InfU x) \<Rightarrow> InfU x"
-- "finding the index of the time interval that contains the k-th data element"
-- "defined over a finite timed stream"
primrec
fin_tm :: "'a fstream \<Rightarrow> nat \<Rightarrow> nat"
where
"fin_tm [] k = k" |
"fin_tm (x#xs) k =
(if k = 0
then 0
else (if (k \<le> length x)
then (Suc 0)
else Suc(fin_tm xs (k - length x))))"
-- "auxiliary lemma for the definition of the truncate operator"
lemma inf_tm_hint1:
assumes "i2 = Suc i - length a"
and "\<not> Suc i \<le> length a"
and "a \<noteq> []"
shows "i2 < Suc i"
using assms
by auto
-- "filtering a finite timed stream"
definition
finT_filter :: "'a set => 'a fstream => 'a fstream"
where
"finT_filter m s \<equiv> map (\<lambda> s. filter (\<lambda> y. y \<in> m) s) s"
-- "filtering an infinite timed stream"
definition
infT_filter :: "'a set => 'a istream => 'a istream"
where
"infT_filter m s \<equiv> (\<lambda>i.( filter (\<lambda> x. x \<in> m) (s i)))"
-- "removing duplications from a finite timed stream"
definition
finT_remdups :: "'a fstream => 'a fstream"
where
"finT_remdups s \<equiv> map (\<lambda> s. remdups s) s"
-- "removing duplications from an infinite timed stream"
definition
infT_remdups :: "'a istream => 'a istream"
where
"infT_remdups s \<equiv> (\<lambda>i.( remdups (s i)))"
-- "removing duplications from a time interval of a stream"
primrec
fst_remdups :: "'a list \<Rightarrow> 'a list"
where
"fst_remdups [] = []" |
"fst_remdups (x#xs) =
(if xs = []
then [x]
else (if x = (hd xs)
then fst_remdups xs
else (x#xs)))"
-- "time interval operator"
definition
ti :: "'a fstream \<Rightarrow> nat \<Rightarrow> 'a list"
where
"ti s i \<equiv>
(if s = []
then []
else (nth s i))"
-- "insuring that a sheaf of channels is correctly defined"
definition
CorrectSheaf :: "nat \<Rightarrow> bool"
where
"CorrectSheaf n \<equiv> 0 < n"
-- "insuring that all channels in a sheaf are disjunct"
-- "indices in the sheaf are represented using an extra specified set"
definition
inf_disjS :: "'b set \<Rightarrow> ('b \<Rightarrow> 'a istream) \<Rightarrow> bool"
where
"inf_disjS IdSet nS
\<equiv>
\<forall> (t::nat) i j. (i:IdSet) \<and> (j:IdSet) \<and>
((nS i) t) \<noteq> [] \<longrightarrow> ((nS j) t) = []"
-- "insuring that all channels in a sheaf are disjunct"
-- "indices in the sheaf are represented using natural numbers"
definition
inf_disj :: "nat \<Rightarrow> (nat \<Rightarrow> 'a istream) \<Rightarrow> bool"
where
"inf_disj n nS
\<equiv>
\<forall> (t::nat) (i::nat) (j::nat).
i < n \<and> j < n \<and> i \<noteq> j \<and> ((nS i) t) \<noteq> [] \<longrightarrow>
((nS j) t) = []"
-- "taking the prefix of n data elements from a finite timed stream"
-- "(defined over natural numbers)"
fun fin_get_prefix :: "('a fstream \<times> nat) \<Rightarrow> 'a fstream"
where
"fin_get_prefix([], n) = []" |
"fin_get_prefix(x#xs, i) =
( if (length x) < i
then x # fin_get_prefix(xs, (i - (length x)))
else [take i x] ) "
-- "taking the prefix of n data elements from a finite timed stream"
-- "(defined over natural numbers enriched by Infinity)"
definition
fin_get_prefix_plus :: "'a fstream \<Rightarrow> natInf \<Rightarrow> 'a fstream"
where
"fin_get_prefix_plus s n
\<equiv>
case n of (Fin i) \<Rightarrow> fin_get_prefix(s, i)
| \<infinity> \<Rightarrow> s "
-- "auxiliary lemmas "
lemma length_inf_drop_hint1:
assumes "s k \<noteq> []"
shows "length (inf_drop k s 0) \<noteq> 0"
using assms
by (auto simp: inf_drop_def)
-- "taking the prefix of n data elements from an infinite timed stream"
-- "(defined over natural numbers)"
fun infT_get_prefix :: "('a istream \<times> nat) \<Rightarrow> 'a fstream"
where
"infT_get_prefix(s, 0) = []"
|
"infT_get_prefix(s, Suc i) =
( if (s 0) = []
then ( if (\<forall> i. s i = [])
then []
else (let
k = (LEAST k. s k \<noteq> [] \<and> (\<forall>i. i < k \<longrightarrow> s i = []));
s2 = inf_drop (k+1) s
in (if (length (s k)=0)
then []
else (if (length (s k) < (Suc i))
then s k # infT_get_prefix (s2,Suc i - length (s k))
else [take (Suc i) (s k)] )))
)
else
(if ((length (s 0)) < (Suc i))
then (s 0) # infT_get_prefix( inf_drop 1 s, (Suc i) - (length (s 0)))
else [take (Suc i) (s 0)]
)
)"
-- "taking the prefix of n data elements from an infinite untimed stream"
-- "(defined over natural numbers)"
primrec
infU_get_prefix :: "(nat \<Rightarrow> 'a) \<Rightarrow> nat \<Rightarrow> 'a list"
where
"infU_get_prefix s 0 = []" |
"infU_get_prefix s (Suc i)
= (infU_get_prefix s i) @ [s i]"
-- "taking the prefix of n data elements from an infinite timed stream"
-- "(defined over natural numbers enriched by Infinity)"
definition
infT_get_prefix_plus :: "'a istream \<Rightarrow> natInf \<Rightarrow> 'a stream"
where
"infT_get_prefix_plus s n
\<equiv>
case n of (Fin i) \<Rightarrow> FinT (infT_get_prefix(s, i))
| \<infinity> \<Rightarrow> InfT s"
-- "taking the prefix of n data elements from an infinite untimed stream"
-- "(defined over natural numbers enriched by Infinity)"
definition
infU_get_prefix_plus :: "(nat \<Rightarrow> 'a) \<Rightarrow> natInf \<Rightarrow> 'a stream"
where
"infU_get_prefix_plus s n
\<equiv>
case n of (Fin i) \<Rightarrow> FinU (infU_get_prefix s i)
| \<infinity> \<Rightarrow> InfU s"
-- "taking the prefix of n data elements from an infinite stream"
-- "(defined over natural numbers enriched by Infinity)"
definition
take_plus :: "natInf \<Rightarrow> 'a list \<Rightarrow> 'a list"
where
"take_plus n s
\<equiv>
case n of (Fin i) \<Rightarrow> (take i s)
| \<infinity> \<Rightarrow> s"
-- "taking the prefix of n data elements from a (general) stream"
-- "(defined over natural numbers enriched by Infinity)"
definition
get_prefix :: "'a stream \<Rightarrow> natInf \<Rightarrow> 'a stream"
where
"get_prefix s k \<equiv>
case s of (FinT x) \<Rightarrow> FinT (fin_get_prefix_plus x k)
| (FinU x) \<Rightarrow> FinU (take_plus k x)
| (InfT x) \<Rightarrow> infT_get_prefix_plus x k
| (InfU x) \<Rightarrow> infU_get_prefix_plus x k"
-- "merging time intervals of two finite timed streams"
primrec
fin_merge_ti :: "'a fstream \<Rightarrow> 'a fstream \<Rightarrow> 'a fstream"
where
"fin_merge_ti [] y = y" |
"fin_merge_ti (x#xs) y =
( case y of [] \<Rightarrow> (x#xs)
| (z#zs) \<Rightarrow> (x@z) # (fin_merge_ti xs zs))"
-- "merging time intervals of two infinite timed streams"
definition
inf_merge_ti :: "'a istream \<Rightarrow> 'a istream \<Rightarrow> 'a istream"
where
"inf_merge_ti x y
\<equiv>
\<lambda> i. (x i)@(y i)"
-- "the last time interval of a finite timed stream"
primrec
fin_last_ti :: "('a list) list \<Rightarrow> nat \<Rightarrow> 'a list"
where
"fin_last_ti s 0 = hd s" |
"fin_last_ti s (Suc i) =
( if s!(Suc i) \<noteq> []
then s!(Suc i)
else fin_last_ti s i)"
-- "the last nonempty time interval of a finite timed stream"
-- "(can be applied to the streams which time intervals are empty from some moment)"
primrec
inf_last_ti :: "'a istream \<Rightarrow> nat \<Rightarrow> 'a list"
where
"inf_last_ti s 0 = s 0" |
"inf_last_ti s (Suc i) =
( if s (Suc i) \<noteq> []
then s (Suc i)
else inf_last_ti s i)"
subsection {* Properties of operators *}
lemma inf_last_ti_nonempty_k:
assumes "inf_last_ti dt t \<noteq> []"
shows "inf_last_ti dt (t + k) \<noteq> []"
using assms
by (induct k, auto)
lemma inf_last_ti_nonempty:
assumes "s t \<noteq> []"
shows "inf_last_ti s (t + k) \<noteq> []"
using assms
by (induct k, auto, induct t, auto)
lemma arith_sum_t2k:
"t + 2 + k = (Suc t) + (Suc k)"
by arith
lemma inf_last_ti_Suc2:
assumes "dt (Suc t) \<noteq> [] \<or> dt (Suc (Suc t)) \<noteq> []"
shows "inf_last_ti dt (t + 2 + k) \<noteq> []"
proof (cases "dt (Suc t) \<noteq> []")
assume a1:"dt (Suc t) \<noteq> []"
from a1 have sg2:"inf_last_ti dt ((Suc t) + (Suc k)) \<noteq> []"
by (rule inf_last_ti_nonempty)
from sg2 show ?thesis by (simp add: arith_sum_t2k)
next
assume a2:"\<not> dt (Suc t) \<noteq> []"
from a2 and assms have sg1:"dt (Suc (Suc t)) \<noteq> []" by simp
from sg1 have sg2:"inf_last_ti dt (Suc (Suc t) + k) \<noteq> []"
by (rule inf_last_ti_nonempty)
from sg2 show ?thesis by auto
qed
subsubsection {* Lemmas for concatenation operator *}
lemma fin_length_append:
"fin_length (x@y) = (fin_length x) + (fin_length y)"
by (induct x, auto)
lemma fin_append_Nil: "fin_inf_append [] z = z"
by (simp add: fin_inf_append_def)
lemma correct_fin_inf_append1:
assumes "s1 = fin_inf_append [x] s"
shows "s1 (Suc i) = s i"
using assms
by (simp add: fin_inf_append_def)
lemma correct_fin_inf_append2:
"fin_inf_append [x] s (Suc i) = s i"
by (simp add: fin_inf_append_def)
lemma fin_append_com_Nil1:
"fin_inf_append [] (fin_inf_append y z)
= fin_inf_append ([] @ y) z"
by (simp add: fin_append_Nil)
lemma fin_append_com_Nil2:
"fin_inf_append x (fin_inf_append [] z)
= fin_inf_append (x @ []) z"
by (simp add: fin_append_Nil)
lemma fin_append_com_i:
"fin_inf_append x (fin_inf_append y z) i = fin_inf_append (x @ y) z i "
proof (cases x)
assume Nil:"x = []"
thus ?thesis by (simp add: fin_append_com_Nil1)
next
fix a l assume Cons:"x = a # l"
thus ?thesis
proof (cases y)
assume "y = []"
thus ?thesis by (simp add: fin_append_com_Nil2)
next
fix aa la assume Cons2:"y = aa # la"
show ?thesis
apply (simp add: fin_inf_append_def, auto, simp add: list_nth_append0)
by (simp add: nth_append)
qed
qed
subsubsection {* Lemmas for operators $ts$ and $msg$ *}
lemma ts_msg1:
assumes "ts p"
shows "msg 1 p"
using assms
by (simp add: ts_def msg_def)
lemma ts_inf_tl:
assumes "ts x"
shows "ts (inf_tl x)"
using assms
by (simp add: ts_def inf_tl_def)
lemma ts_length_hint1:
assumes "ts x"
shows "x i \<noteq> []"
proof -
from assms have sg1:"length (x i) = Suc 0" by (simp add: ts_def)
thus ?thesis by auto
qed
lemma ts_length_hint2:
assumes "ts x"
shows "length (x i) = Suc (0::nat)"
using assms
by (simp add: ts_def)
lemma ts_Least_0:
assumes "ts x"
shows "(LEAST i. (x i) \<noteq> [] ) = (0::nat)"
proof -
from assms have sg1:"x 0 \<noteq> []" by (rule ts_length_hint1)
thus ?thesis
apply (simp add: Least_def)
by auto
qed
lemma inf_tl_Suc: "inf_tl x i = x (Suc i)"
by (simp add: inf_tl_def)
lemma ts_Least_Suc0:
assumes "ts x"
shows "(LEAST i. x (Suc i) \<noteq> []) = 0"
proof -
from assms have "x (Suc 0) \<noteq> []" by (simp add: ts_length_hint1)
thus ?thesis by (simp add: Least_def, auto)
qed
lemma ts_inf_make_untimed_inf_tl:
assumes "ts x"
shows "inf_make_untimed (inf_tl x) i = inf_make_untimed x (Suc i)"
using assms
apply (simp add: inf_make_untimed_def)
by (metis Suc_less_eq gr_implies_not0 ts_length_hint1 ts_length_hint2)
lemma ts_inf_make_untimed1_inf_tl:
assumes "ts x"
shows "inf_make_untimed1 (inf_tl x) i = inf_make_untimed1 x (Suc i)"
using assms
by (metis inf_make_untimed_def ts_inf_make_untimed_inf_tl)
lemma msg_nonempty1:
assumes h1:"msg (Suc 0) a"
and h2:"a t = aa # l"
shows "l = []"
proof -
from h1 have "length (a t) \<le> Suc 0" by (simp add: msg_def)
from h2 and this show ?thesis by auto
qed
lemma msg_nonempty2:
assumes h1:"msg (Suc 0) a"
and h2:"a t \<noteq> []"
shows "length (a t) = (Suc 0)"
proof -
from h1 have sg1:"length (a t) \<le> Suc 0" by (simp add: msg_def)
from h2 have sg2:"length (a t) \<noteq> 0" by auto
from sg1 and sg2 show ?thesis by arith
qed
subsubsection {* Lemmas for $inf\_truncate$ *}
lemma inf_truncate_nonempty:
assumes "z i \<noteq> []"
shows "inf_truncate z i \<noteq> []"
proof (induct i)
case 0
from assms show ?case by auto
next
case (Suc i)
from assms show ?case by auto
qed
lemma concat_inf_truncate_nonempty:
assumes "z i \<noteq> []"
shows "concat (inf_truncate z i) \<noteq> []"
using assms
proof (induct i)
case 0
thus ?case by auto
next
case (Suc i)
thus ?case by auto
qed
lemma concat_inf_truncate_nonempty_a:
assumes "z i = [a]"
shows "concat (inf_truncate z i) \<noteq> []"
using assms
by (metis concat_inf_truncate_nonempty list.distinct(1))
lemma concat_inf_truncate_nonempty_el:
assumes "z i \<noteq> []"
shows "concat (inf_truncate z i) \<noteq> []"
using assms
by (metis concat_inf_truncate_nonempty)
lemma inf_truncate_append:
"(inf_truncate z i @ [z (Suc i)]) = inf_truncate z (Suc i)"
using assms
by (metis inf_truncate.simps(2))
subsubsection {* Lemmas for $fin\_make\_untimed$ *}
lemma fin_make_untimed_append:
assumes "fin_make_untimed x \<noteq> []"
shows "fin_make_untimed (x @ y) \<noteq> []"
using assms by (simp add: fin_make_untimed_def)
lemma fin_make_untimed_inf_truncate_Nonempty:
assumes "z k \<noteq> []"
and "k \<le> i"
shows "fin_make_untimed (inf_truncate z i) \<noteq> []"
using assms
apply (simp add: fin_make_untimed_def)
proof (induct i)
case 0
thus ?case by auto
next
case (Suc i)
thus ?case
proof cases
assume "k \<le> i"
from Suc and this show "\<exists>xs\<in>set (inf_truncate z (Suc i)). xs \<noteq> []"
by auto
next
assume "\<not> k \<le> i"
from Suc and this have "k = Suc i" by arith
from Suc and this show "\<exists>xs\<in>set (inf_truncate z (Suc i)). xs \<noteq> []"
by auto
qed
qed
lemma last_fin_make_untimed_inf_truncate:
assumes "z i = [a]"
shows "last (fin_make_untimed (inf_truncate z i)) = a"
using assms
proof (induction i)
case 0 thus ?case by (simp add: fin_make_untimed_def)
next
case (Suc i) thus ?case by (simp add: fin_make_untimed_def)
qed
lemma fin_make_untimed_append_empty:
"fin_make_untimed (z @ [[]]) = fin_make_untimed z"
by (simp add: fin_make_untimed_def)
lemma fin_make_untimed_inf_truncate_append_a:
"fin_make_untimed (inf_truncate z i @ [[a]]) !
(length (fin_make_untimed (inf_truncate z i @ [[a]])) - Suc 0) = a"
by (simp add: fin_make_untimed_def)
lemma fin_make_untimed_inf_truncate_Nonempty_all:
assumes "z k \<noteq> []"
shows "\<forall> i. k \<le> i \<longrightarrow> fin_make_untimed (inf_truncate z i) \<noteq> []"
using assms by (simp add: fin_make_untimed_inf_truncate_Nonempty)
lemma fin_make_untimed_inf_truncate_Nonempty_all0:
assumes "z 0 \<noteq> []"
shows "\<forall> i. fin_make_untimed (inf_truncate z i) \<noteq> []"
using assms by (simp add: fin_make_untimed_inf_truncate_Nonempty)
lemma fin_make_untimed_inf_truncate_Nonempty_all0a:
assumes "z 0 = [a]"
shows "\<forall> i. fin_make_untimed (inf_truncate z i) \<noteq> []"
using assms by (simp add: fin_make_untimed_inf_truncate_Nonempty_all0)
lemma fin_make_untimed_inf_truncate_Nonempty_all_app:
assumes "z 0 = [a]"
shows "\<forall> i. fin_make_untimed (inf_truncate z i @ [z (Suc i)]) \<noteq> []"
proof
fix i
from assms have "fin_make_untimed (inf_truncate z i) \<noteq> []"
by (simp add: fin_make_untimed_inf_truncate_Nonempty_all0a)
from assms and this show
"fin_make_untimed (inf_truncate z i @ [z (Suc i)]) \<noteq> []"
by (simp add: fin_make_untimed_append)
qed
lemma fin_make_untimed_nth_length:
assumes "z i = [a]"
shows
"fin_make_untimed (inf_truncate z i) !
(length (fin_make_untimed (inf_truncate z i)) - Suc 0)
= a"
proof -
from assms have sg1:"last (fin_make_untimed (inf_truncate z i)) = a"
by (simp add: last_fin_make_untimed_inf_truncate)
from assms have sg2:"concat (inf_truncate z i) \<noteq> []"
by (rule concat_inf_truncate_nonempty_a)
from assms and sg1 and sg2 show ?thesis
by (simp add: fin_make_untimed_def last_nth_length)
qed
subsubsection {* Lemmas for $inf\_disj$ and $inf\_disjS$ *}
lemma inf_disj_index:
assumes h1:"inf_disj n nS"
and "nS k t \<noteq> []"
and "k < n"
shows "(SOME i. i < n \<and> nS i t \<noteq> []) = k"
proof -
from h1 have "\<forall> j. k < n \<and> j < n \<and> k \<noteq> j \<and> nS k t \<noteq> [] \<longrightarrow> nS j t = []"
by (simp add: inf_disj_def, auto)
from this and assms show ?thesis by auto
qed
lemma inf_disjS_index:
assumes h1:"inf_disjS IdSet nS"
and "k:IdSet"
and "nS k t \<noteq> []"
shows "(SOME i. (i:IdSet) \<and> nSend i t \<noteq> []) = k"
proof -
from h1 have "\<forall> j. k \<in> IdSet \<and> j \<in> IdSet \<and> nS k t \<noteq> [] \<longrightarrow> nS j t = []"
by (simp add: inf_disjS_def, auto)
from this and assms show ?thesis by auto
qed
end |
/-
Copyright (c) 2023 MarĆa InĆ©s de Frutos-FernĆ”ndez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : MarĆa InĆ©s de Frutos-FernĆ”ndez
-/
import tactic
import data.real.basic
/-
# Ejercicios sobre nĆŗmeros reales
Los siguientes ejercicios aparecen como pasos intermedios en algunos
de los problemas de `limites.lean`. Intenta resolverlos utilizando
las tƔcticas `library_search` y `linarith`.
NOTA: adaptado de los cursos de formalización de Kevin Buzzard.
-/
example (x : ā) : |(-x)| = |x| :=
begin
sorry
end
example (x y : ā) : |x - y| = |y - x| :=
begin
sorry
end
example (A B C : ā) : max A B ⤠C ā A ⤠C ā§ B ⤠C :=
begin
sorry
end
example (x y : ā) : |x| < y ā -y < x ā§ x < y :=
begin
sorry
end
example (ε : ā) (hε : 0 < ε) : 0 < ε / 2 :=
begin
sorry
end
example (a b x y : ā) (h1 : a < x) (h2 : b < y) : a + b < x + y :=
begin
sorry
end
example (ε : ā) (hε : 0 < ε) : 0 < ε / 3 :=
begin
sorry
end
example (a b c d x y : ā) (h1 : a + c < x) (h2 : b + d < y) :
a + b + c + d < x + y :=
begin
sorry,
end |
function varargout = aibcutpush(varargin)
% VL_AIBCUTPUSH Quantize based on VL_AIB cut
% Y = VL_AIBCUTPUSH(MAP, X) maps the data X to elements of the AIB
% cut specified by MAP.
%
% The function is equivalent to Y = MAP(X).
%
% See also: VL_HELP(), VL_AIB().
[varargout{1:nargout}] = vl_aibcutpush(varargin{:});
|
lemma tendsto_rabs_zero_cancel: "((\<lambda>x. \<bar>f x\<bar>) \<longlongrightarrow> (0::real)) F \<Longrightarrow> (f \<longlongrightarrow> 0) F" |
Require Import isla.isla.
Require Import isla.aarch64.aarch64.
Require Export isla.examples.pkvm_handler.a7414.
Lemma a7414_spec `{!islaG Σ} `{!threadG} pc:
instr pc (Some a7414) -ā
instr_body pc (ldp_mapsto_spec pc "R0" "R1" "SP_EL2" 0 None).
Proof.
iStartProof.
repeat liAStep; liShow.
Unshelve. all: prepare_sidecond.
all: bv_solve.
Qed.
Definition a7414_spec_inst `{!islaG Σ} `{!threadG} pc :=
entails_to_simplify_hyp 0 (a7414_spec pc).
Global Existing Instance a7414_spec_inst.
|
! =========================================================================
elemental function gsw_pt_from_entropy (sa, entropy)
! =========================================================================
!
! Calculates potential temperature with reference pressure p_ref = 0 dbar
! and with entropy as an input variable.
!
! SA = Absolute Salinity [ g/kg ]
! entropy = specific entropy [ deg C ]
!
! pt = potential temperature [ deg C ]
! with reference sea pressure (p_ref) = 0 dbar.
! Note. The reference sea pressure of the output, pt, is zero dbar.
!--------------------------------------------------------------------------
use gsw_mod_teos10_constants, only : gsw_cp0, gsw_sso, gsw_t0
use gsw_mod_toolbox, only : gsw_entropy_from_pt, gsw_gibbs_pt0_pt0
use gsw_mod_kinds
implicit none
real (r8), intent(in) :: sa, entropy
real (r8) :: gsw_pt_from_entropy
integer :: number_of_iterations
real (r8) :: c, dentropy, dentropy_dt, ent_sa, part1, part2, pt, ptm
real (r8) :: pt_old
! Find the initial value of pt
part1 = 1.0_r8 - sa/gsw_sso
part2 = 1.0_r8 - 0.05_r8*part1
ent_sa = (gsw_cp0/gsw_t0)*part1*(1.0_r8 - 1.01_r8*part1)
c = (entropy - ent_sa)*(part2/gsw_cp0)
pt = gsw_t0*(exp(c) - 1.0_r8)
dentropy_dt = gsw_cp0/((gsw_t0 + pt)*part2)
do number_of_iterations = 1, 2
pt_old = pt
dentropy = gsw_entropy_from_pt(sa,pt_old) - entropy
pt = pt_old - dentropy/dentropy_dt
ptm = 0.5_r8*(pt + pt_old)
dentropy_dt = -gsw_gibbs_pt0_pt0(sa,ptm)
pt = pt_old - dentropy/dentropy_dt
end do
! Maximum error of 2.2x10^-6 degrees C for one iteration.
! Maximum error is 1.4x10^-14 degrees C for two iterations
! (two iterations is the default, "for Number_of_iterations = 1:2").
gsw_pt_from_entropy = pt
return
end function
!--------------------------------------------------------------------------
|
# LU Decomposition
+ This notebook is part of lecture 4 *Factorization into LU* in the OCW MIT course 18.06 [1]
+ Created by me, Dr Juan H Klopper
+ Head of Acute Care Surgery
+ Groote Schuur Hospital
+ University Cape Town
+ <a href="mailto:[email protected]">Email me with your thoughts, comments, suggestions and corrections</a>
<a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/"></a><br /><span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/InteractiveResource" property="dct:title" rel="dct:type">Linear Algebra OCW MIT18.06</span> <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">IPython notebook [2] study notes by Dr Juan H Klopper</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">Creative Commons Attribution-NonCommercial 4.0 International License</a>.
+ [1] <a href="http://ocw.mit.edu/courses/mathematics/18-06sc-linear-algebra-fall-2011/index.htm">OCW MIT 18.06</a>
+ [2] Fernando PƩrez, Brian E. Granger, IPython: A System for Interactive Scientific Computing, Computing in Science and Engineering, vol. 9, no. 3, pp. 21-29, May/June 2007, doi:10.1109/MCSE.2007.53. URL: http://ipython.org
```python
from IPython.core.display import HTML, Image
css_file = 'style.css'
HTML(open(css_file, 'r').read())
```
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<style>
@font-face {
font-family: "Computer Modern";
src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');
}
#notebook_panel { /* main background */
background: #ddd;
color: #000000;
}
/* Formatting for header cells */
.text_cell_render h1 {
font-family: 'Philosopher', sans-serif;
font-weight: 400;
font-size: 2.2em;
line-height: 100%;
color: rgb(0, 80, 120);
margin-bottom: 0.1em;
margin-top: 0.1em;
display: block;
}
.text_cell_render h2 {
font-family: 'Philosopher', serif;
font-weight: 400;
font-size: 1.9em;
line-height: 100%;
color: rgb(200,100,0);
margin-bottom: 0.1em;
margin-top: 0.1em;
display: block;
}
.text_cell_render h3 {
font-family: 'Philosopher', serif;
margin-top:12px;
margin-bottom: 3px;
font-style: italic;
color: rgb(94,127,192);
}
.text_cell_render h4 {
font-family: 'Philosopher', serif;
}
.text_cell_render h5 {
font-family: 'Alegreya Sans', sans-serif;
font-weight: 300;
font-size: 16pt;
color: grey;
font-style: italic;
margin-bottom: .1em;
margin-top: 0.1em;
display: block;
}
.text_cell_render h6 {
font-family: 'PT Mono', sans-serif;
font-weight: 300;
font-size: 10pt;
color: grey;
margin-bottom: 1px;
margin-top: 1px;
}
.CodeMirror{
font-family: "PT Mono";
font-size: 100%;
}
</style>
```python
import numpy as np
from sympy import *
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import Image
from warnings import filterwarnings
init_printing(use_latex = 'mathjax')
%matplotlib inline
filterwarnings('ignore')
```
# LU decomposition of a matrix A
* We will decompose the matrix A into and upper and lower triangular matrix, such that multiplying these will result back into A
$$ A = LU $$
## Turning the matrix of coefficients into <u>U</u>pper triangular form
* Consider the following matrix of coefficients
$$ \begin{bmatrix} 1 & -2 & 1 \\ 3 & 2 & -2 \\ 6 & -1 & -1 \end{bmatrix} $$
* Successive elementary row operation follow
* Which is nothing other than matrix multiplication of the elementary matrices
* An elementary matrix is an identity matrix on which one elementary row operation was performed
```python
A = Matrix([[1, -2, 1], [3, 2, -2], [6, -1, -1]])
A
```
$$\left[\begin{matrix}1 & -2 & 1\\3 & 2 & -2\\6 & -1 & -1\end{matrix}\right]$$
```python
eye(3)
```
$$\left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$$
* We have to get a -3 in the first **pivot** (the 1 in row 1, column 1) to get rid of the 3 in position row 2, column 1 (we call the resulting matrix E21, referring to the row 2, column 1)
* Then we add the new row 1 to row two
Row one of the identity matrix is then (-3,0,0) (but we leave it (1,0,0) in E21) and adding this to row 2 leaves (-3,1,0)
```python
E21 = Matrix([[1, 0, 0], [-3, 1, 0], [0, 0, 1]])
E21
```
$$\left[\begin{matrix}1 & 0 & 0\\-3 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$$
```python
E21 * A # The resulting matrix after multiplication by E21
```
$$\left[\begin{matrix}1 & -2 & 1\\0 & 8 & -5\\6 & -1 & -1\end{matrix}\right]$$
* We do the same to get rid of the 6 in row 3, column 1
* Multiplying row 1 (of the identity matrix) by -6 and adding this new row to row 3 (but again leaving row 1 as (1,0,0) in E31)
```python
E31 = Matrix([[1, 0, 0], [0, 1, 0], [-6, 0, 1]])
E31
```
$$\left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\-6 & 0 & 1\end{matrix}\right]$$
```python
E31 * E21 * A # This got rid of the leading 6 in row 3
```
$$\left[\begin{matrix}1 & -2 & 1\\0 & 8 & -5\\0 & 11 & -7\end{matrix}\right]$$
* Now the 8 in row 2, column 2 is the **pivot** and we need to get rid of the 11 in row 3, column 2
* Unfortunately we have an 8 and an 11 to deal with
* We will have to do two elementary row operations
* -11 times row 2 of the identity matrix (0,-11,0)
* Added to 8 times row 3 (0,0,8) ∴ (0,-11,8)
```python
E32 = Matrix([[1, 0 , 0], [0, 1, 0], [0, -11, 8]])
E32
```
$$\left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & -11 & 8\end{matrix}\right]$$
```python
U = E32 * E31 * E21 * A
U # We call is U for upper triangular
```
$$\left[\begin{matrix}1 & -2 & 1\\0 & 8 & -5\\0 & 0 & -1\end{matrix}\right]$$
* The matrix is now in upper triangular form
$$ \left( { E }_{ 32 } \right) \left( { E }_{ 31 } \right) \left( { E }_{ 21 } \right) A=U $$
## Calculating the <u>L</u>ower triangular from
* Note, to reverse this process we would have to do the following:
$$ { \left( { E }_{ 21 } \right) }^{ -1 }{ \left( { E }_{ 31 } \right) }^{ -1 }{ \left( { E }_{ 32 } \right) }^{ -1 }\left( { E }_{ 32 } \right) \left( { E }_{ 31 } \right) \left( { E }_{ 21 } \right) A=A $$
* The inverse of a matrix can be calculated using the sympy method .*inv*()
* We can check this with a Boolean request
```python
E21.inv() * E31.inv() * E32.inv() * E32 * E31 * E21 * A == A # The Boolean double equal signs asks: Is the
# left-hand side equal to the right-hand side?
```
True
* Indeed, we will be back with the identity matrix just multiplying the inverse elementary matrices and the elementary matrices
```python
E21.inv() * E31.inv() * E32.inv() * E32 * E31 * E21
```
$$\left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$$
* Multiplying the inverse elementary matrices on the left, must also have it happen on the right
$$ { \left( { E }_{ 21 } \right) }^{ -1 }{ \left( { E }_{ 31 } \right) }^{ -1 }{ \left( { E }_{ 32 } \right) }^{ -1 }\left( { E }_{ 32 } \right) \left( { E }_{ 31 } \right) \left( { E }_{ 21 } \right) A={ \left( { E }_{ 21 } \right) }^{ -1 }{ \left( { E }_{ 31 } \right) }^{ -1 }{ \left( { E }_{ 32 } \right) }^{ -1 }U $$
* The multiplication of these inverse elementary matrices is <u>l</u>ower triangular
* We can call in L
$$ A=LU $$
```python
L = E21.inv() * E31.inv() * E32.inv()
L
```
$$\left[\begin{matrix}1 & 0 & 0\\3 & 1 & 0\\6 & \frac{11}{8} & \frac{1}{8}\end{matrix}\right]$$
```python
A == L * U # Checking this with a Boolean question
```
True
```python
A, L * U # They are identical
```
$$\left ( \left[\begin{matrix}1 & -2 & 1\\3 & 2 & -2\\6 & -1 & -1\end{matrix}\right], \quad \left[\begin{matrix}1 & -2 & 1\\3 & 2 & -2\\6 & -1 & -1\end{matrix}\right]\right )$$
## Doing this in one go using sympy
```python
L, U, _ = A.LUdecomposition()
```
```python
L
```
$$\left[\begin{matrix}1 & 0 & 0\\3 & 1 & 0\\6 & \frac{11}{8} & 1\end{matrix}\right]$$
```python
U # Note the difference from the U above
```
$$\left[\begin{matrix}1 & -2 & 1\\0 & 8 & -5\\0 & 0 & - \frac{1}{8}\end{matrix}\right]$$
```python
L * U # Back to A
```
$$\left[\begin{matrix}1 & -2 & 1\\3 & 2 & -2\\6 & -1 & -1\end{matrix}\right]$$
## What's special about L?
* This only works when no row interchange happens
* It also actually only works when doing the conventional subtracting the scalar multiplication of a row from another row, leaving the positive scalar as opposed to the negatives I use, allowing me to add the two rows (as opposed to subtraction)
* Note the 3 (in row 2, column 1) and the 6 (in row 3, column 1)
* They are the row multiplications we have to do for E21 and E31
* The ¹¹ / ₈ is what we did for E32 (we just did it in two steps so as not to use fractions)
## Row exchanges
* We have to allow row exchanges if the pivot contains a zero
* For an example, from a 3×3 identity matrix we could have:
```python
eye(3)
```
$$\left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$$
* Exchanging rows one and two would be:
```python
Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
```
$$\left[\begin{matrix}0 & 1 & 0\\1 & 0 & 0\\0 & 0 & 1\end{matrix}\right]$$
```python
A, Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) * A # Showing row exchange
```
$$\left ( \left[\begin{matrix}1 & -2 & 1\\3 & 2 & -2\\6 & -1 & -1\end{matrix}\right], \quad \left[\begin{matrix}3 & 2 & -2\\1 & -2 & 1\\6 & -1 & -1\end{matrix}\right]\right )$$
* How many permutations of row exchanges are there?
$$ {n!} $$
* In a 3×3 matrix there are 3! = 6 permutations
* Multiplying any of them will result in one of the 6
* They are inverses of each other
* The inverse are the transposes
* For 4×4 there are 4! = 24
## Example problems
### Example problem 01
* Perform LU decomposition of:
$$ \begin{bmatrix} 1 & 0 & 1 \\ a & a & a \\ b & b & a \end{bmatrix} $$
* For which values of *a* and *b* does L and U exist?
#### Solution
```python
a, b = symbols('a b')
```
```python
A = Matrix([[1, 0, 1], [a, a, a], [b, b, a]])
A
```
$$\left[\begin{matrix}1 & 0 & 1\\a & a & a\\b & b & a\end{matrix}\right]$$
```python
L,U, _ = A.LUdecomposition()
```
```python
L, U
```
$$\left ( \left[\begin{matrix}1 & 0 & 0\\a & 1 & 0\\b & \frac{b}{a} & 1\end{matrix}\right], \quad \left[\begin{matrix}1 & 0 & 1\\0 & a & 0\\0 & 0 & a - b\end{matrix}\right]\right )$$
* Checking
```python
L * U == A
```
True
* For existence:
* *a* ≠ 0
* It's easy to see why, since if a equals zero, we will have a zero in a pivot position and we will have to do row exchange, which is not allowed for LU-decomposition
## Hints and tips
```python
E21, E21.inv() # To take the inverse of an elementary matrix, simply change the sign of the off-diagonal elements and
# multiply each element by 1 over the determinant
# The determinant is easy to do for these *n* = 3 square matrices, since the top row is (1,0,0)
```
$$\left ( \left[\begin{matrix}1 & 0 & 0\\-3 & 1 & 0\\0 & 0 & 1\end{matrix}\right], \quad \left[\begin{matrix}1 & 0 & 0\\3 & 1 & 0\\0 & 0 & 1\end{matrix}\right]\right )$$
```python
E31, E31.inv()
```
$$\left ( \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\-6 & 0 & 1\end{matrix}\right], \quad \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\6 & 0 & 1\end{matrix}\right]\right )$$
```python
E32, E32.inv()
```
$$\left ( \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & -11 & 8\end{matrix}\right], \quad \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & \frac{11}{8} & \frac{1}{8}\end{matrix}\right]\right )$$
* By keeping track of the elementary matrices it is easy to get L and U
* It's easy to get the inverses of L and U
* This means it is easy to calculate **x**
$$ Ax=LUx=b\\ Ux={ L }^{ -1 }b\\ x={ U }^{ -1 }{ L }^{ -1 }b $$
```python
```
|
[GOAL]
⢠StableUnderComposition @Finite
[PROOFSTEP]
introv R hf hg
[GOAL]
R S T : Type u_1
instā² : CommRing R
instā¹ : CommRing S
instā : CommRing T
f : R ā+* S
g : S ā+* T
hf : Finite f
hg : Finite g
⢠Finite (comp g f)
[PROOFSTEP]
exact hg.comp hf
[GOAL]
⢠RespectsIso @Finite
[PROOFSTEP]
apply finite_stableUnderComposition.respectsIso
[GOAL]
⢠ā {R S : Type u_1} [inst : CommRing R] [inst_1 : CommRing S] (e : R ā+* S), Finite (RingEquiv.toRingHom e)
[PROOFSTEP]
intros
[GOAL]
Rā Sā : Type u_1
instā¹ : CommRing Rā
instā : CommRing Sā
eā : Rā ā+* Sā
⢠Finite (RingEquiv.toRingHom eā)
[PROOFSTEP]
exact Finite.of_surjective _ (RingEquiv.toEquiv _).surjective
[GOAL]
⢠StableUnderBaseChange @Finite
[PROOFSTEP]
refine StableUnderBaseChange.mk _ finite_respectsIso ?_
[GOAL]
⢠ā ā¦R S T : Type u_1⦠[inst : CommRing R] [inst_1 : CommRing S] [inst_2 : CommRing T] [inst_3 : Algebra R S]
[inst_4 : Algebra R T], Finite (algebraMap R T) ā Finite includeLeftRingHom
[PROOFSTEP]
classical
introv h
replace h : Module.Finite R T := by rw [RingHom.Finite] at h ; convert h; ext; intros; simp_rw [Algebra.smul_def]; rfl
suffices Module.Finite S (S ā[R] T) by rw [RingHom.Finite]; convert this; congr; ext; intros;
simp_rw [Algebra.smul_def]; rfl
exact inferInstance
[GOAL]
⢠ā ā¦R S T : Type u_1⦠[inst : CommRing R] [inst_1 : CommRing S] [inst_2 : CommRing T] [inst_3 : Algebra R S]
[inst_4 : Algebra R T], Finite (algebraMap R T) ā Finite includeLeftRingHom
[PROOFSTEP]
introv h
[GOAL]
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Finite (algebraMap R T)
⢠Finite includeLeftRingHom
[PROOFSTEP]
replace h : Module.Finite R T := by rw [RingHom.Finite] at h ; convert h; ext; intros; simp_rw [Algebra.smul_def]; rfl
[GOAL]
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Finite (algebraMap R T)
⢠Module.Finite R T
[PROOFSTEP]
rw [RingHom.Finite] at h
[GOAL]
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
⢠Module.Finite R T
[PROOFSTEP]
convert h
[GOAL]
case h.e'_5.h.e'_5
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
⢠instā = toAlgebra (algebraMap R T)
[PROOFSTEP]
ext
[GOAL]
case h.e'_5.h.e'_5.h
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
rā : R
xā : T
⢠(let_fun I := instā;
rā ⢠xā) =
rā ⢠xā
[PROOFSTEP]
intros
[GOAL]
case h.e'_5.h.e'_5.h
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
rā : R
xā : T
⢠(let_fun I := instā;
rā ⢠xā) =
rā ⢠xā
[PROOFSTEP]
simp_rw [Algebra.smul_def]
[GOAL]
case h.e'_5.h.e'_5.h
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
rā : R
xā : T
⢠ā(algebraMap R T) rā * xā = rā ⢠xā
[PROOFSTEP]
rfl
[GOAL]
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
⢠Finite includeLeftRingHom
[PROOFSTEP]
suffices Module.Finite S (S ā[R] T) by rw [RingHom.Finite]; convert this; congr; ext; intros;
simp_rw [Algebra.smul_def]; rfl
[GOAL]
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
this : Module.Finite S (S ā[R] T)
⢠Finite includeLeftRingHom
[PROOFSTEP]
rw [RingHom.Finite]
[GOAL]
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
this : Module.Finite S (S ā[R] T)
⢠Module.Finite S (S ā[R] T)
[PROOFSTEP]
convert this
[GOAL]
case h.e'_5.h
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
this : Module.Finite S (S ā[R] T)
e_4ā :
NonUnitalNonAssocSemiring.toAddCommMonoid =
instAddCommMonoidTensorProductToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToModuleToModule
⢠Algebra.toModule = leftModule
[PROOFSTEP]
congr
[GOAL]
case h.e'_5.h.h.e_5.h
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
this : Module.Finite S (S ā[R] T)
e_4ā :
NonUnitalNonAssocSemiring.toAddCommMonoid =
instAddCommMonoidTensorProductToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToModuleToModule
⢠toAlgebra includeLeftRingHom = leftAlgebra
[PROOFSTEP]
ext
[GOAL]
case h.e'_5.h.h.e_5.h.h
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
this : Module.Finite S (S ā[R] T)
e_4ā :
NonUnitalNonAssocSemiring.toAddCommMonoid =
instAddCommMonoidTensorProductToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToModuleToModule
rā : S
xā : S ā[R] T
⢠(let_fun I := toAlgebra includeLeftRingHom;
rā ⢠xā) =
rā ⢠xā
[PROOFSTEP]
intros
[GOAL]
case h.e'_5.h.h.e_5.h.h
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
this : Module.Finite S (S ā[R] T)
e_4ā :
NonUnitalNonAssocSemiring.toAddCommMonoid =
instAddCommMonoidTensorProductToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToModuleToModule
rā : S
xā : S ā[R] T
⢠(let_fun I := toAlgebra includeLeftRingHom;
rā ⢠xā) =
rā ⢠xā
[PROOFSTEP]
simp_rw [Algebra.smul_def]
[GOAL]
case h.e'_5.h.h.e_5.h.h
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
this : Module.Finite S (S ā[R] T)
e_4ā :
NonUnitalNonAssocSemiring.toAddCommMonoid =
instAddCommMonoidTensorProductToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToAddCommMonoidToNonUnitalNonAssocSemiringToNonAssocSemiringToModuleToModule
rā : S
xā : S ā[R] T
⢠rā ⢠xā = ā(algebraMap S (S ā[R] T)) rā * xā
[PROOFSTEP]
rfl
[GOAL]
R S T : Type u_1
instāā“ : CommRing R
instā³ : CommRing S
instā² : CommRing T
instā¹ : Algebra R S
instā : Algebra R T
h : Module.Finite R T
⢠Module.Finite S (S ā[R] T)
[PROOFSTEP]
exact inferInstance
|
Require Import Bool.
(* Please ignore:
negb is just another name for
the not function for booleans,
more on that later.
*)
Definition not := negb.
Theorem deMorgen: forall x y:bool,
not (x || y) = (not x) && (not y).
Proof.
Abort.
Theorem deMorgen_answer: forall x y:bool,
not (x || y) = (not x) && (not y).
Proof.
intros.
(* We can start by doing case analysis on x into its two cases.
Almost like a truth table for computer scientists or
A very lame induction for mathematicians.
*)
Print bool.
(*
We can see that a bool is either true of false
*)
case x.
(* Now we have two cases to prove,
lets focus on our first goal
*)
-
(* Seems like some of this equation is simply solvable.
simpl can partially apply functions,
for you have only supplied limited arguments. *)
simpl.
(* false = false is true by reflexivity *)
reflexivity.
(* Coq helps us remember all cases.
The proof cannot complete,
if we haven't proved it for all cases.
*)
- (* seems like this can also be simplified *)
simpl.
(* not y = not y, no matter what y is *)
reflexivity.
Qed.
(* Qed = Proven *)
|
module Program
import CommonTestingStuff
export
beforeString : String
beforeString = "before coop"
s150 : PrintString m => CanSleep m => (offset : Time) => m String
s150 = do
printTime offset "s150 proc, first"
for 5 $ do
printTime offset "s150 proc, before 1000"
sleepFor 1.seconds
printTime offset "s150 proc, before 2000"
sleepFor 2.seconds
"long" <$ printTime offset "s150 proc, last"
export
program : PrintString m => CanSleep m => Alternative m => m Unit
program = do
printString "\n------\n"
do
offset <- currentTime
printTime offset "start"
res <- empty <|> s150
printTime offset "top: \{res}"
printTime offset "end"
printString "\n------\n"
do
offset <- currentTime
printTime offset "start"
res <- s150 <|> empty
printTime offset "top: \{show res}"
printTime offset "end"
printString "\n------"
|
generic2arg = Dict{Symbol,Any}(
# :/ => (:(1./x2),:(-x1./abs2(x2))), # (*,N) (V,V) (M,M)
# :\ => (:(-x2./abs2(x1)),:(1./x1)), # (N,*) (V,V) (M,M) (M,V) (V,M)
)
# TODO:
# eval
# scale
# generic_scale!: Not exported
# scale!
# cross
# triu
# tril
# triu!
# tril!
# diff
# gradient
# diag
# generic_vecnormMinusInf: Not exported
# generic_vecnormInf: Not exported
# generic_vecnorm1: Not exported
# norm_sqr: Not exported
# generic_vecnorm2: Not exported
# generic_vecnormp: Not exported
# vecnormMinusInf: Not exported
# vecnormInf: Not exported
# vecnorm1: Not exported
# vecnorm2: Not exported
# vecnormp: Not exported
# vecnorm
# norm
# norm1: Not exported
# norm2: Not exported
# normInf: Not exported
# vecdot
# dot
# rank
# trace
# inv
# \
# /
# cond
# condskeel
# issym
# ishermitian
# istriu
# istril
# isdiag
# linreg
# peakflops
# axpy!: Not exported
# reflector!: Not exported
# reflectorApply!: Not exported
# det
# logdet
# logabsdet
# isapprox
|
[STATEMENT]
lemma sinh_real_neg_iff [simp]: "sinh (x :: real) < 0 \<longleftrightarrow> x < 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (sinh x < 0) = (x < 0)
[PROOF STEP]
by (simp add: sinh_def) |
If $X$ is a bounded sequence, then for every $K > 0$, if $\|X_n\| \leq K$ for all $n$, then $Q$. |
Formal statement is: lemma simply_connected_empty [iff]: "simply_connected {}" Informal statement is: The empty set is simply connected. |
module _ (A : Set) where
open import Common.Prelude
open import Common.Reflection
macro
foo : Tactic
foo _ = returnTC _
bar : ā¤
bar = foo
|
# 16 PDEs: Waves
(See *Computational Physics* Ch 21 and *Computational Modeling* Ch 6.5.)
## Background: waves on a string
Assume a 1D string of length $L$ with mass density per unit length $\rho$ along the $x$ direction. It is held under constant tension $T$ (force per unit length). Ignore frictional forces and the tension is so high that we can ignore sagging due to gravity.
### 1D wave equation
The string is displaced in the $y$ direction from its rest position, i.e., the displacement $y(x, t)$ is a function of space $x$ and time $t$.
For small relative displacements $y(x, t)/L \ll 1$ and therefore small slopes $\partial y/\partial x$ we can describe $y(x, t)$ with a *linear* equation of motion:
Newton's second law applied to short elements of the string with length $\Delta x$ and mass $\Delta m = \rho \Delta x$: the left hand side contains the *restoring force* that opposes the displacement, the right hand side is the acceleration of the string element:
\begin{align}
\sum F_{y}(x) &= \Delta m\, a(x, t)\\
T \sin\theta(x+\Delta x) - T \sin\theta(x) &= \rho \Delta x \frac{\partial^2 y(x, t)}{\partial t^2}
\end{align}
The angle $\theta$ measures by how much the string is bent away from the resting configuration.
Because we assume small relative displacements, the angles are small ($\theta \ll 1$) and we can make the small angle approximation
$$
\sin\theta \approx \tan\theta = \frac{\partial y}{\partial x}
$$
and hence
\begin{align}
T \left.\frac{\partial y}{\partial x}\right|_{x+\Delta x} - T \left.\frac{\partial y}{\partial x}\right|_{x} &= \rho \Delta x \frac{\partial^2 y(x, t)}{\partial t^2}\\
\frac{T \left.\frac{\partial y}{\partial x}\right|_{x+\Delta x} - T \left.\frac{\partial y}{\partial x}\right|_{x}}{\Delta x} &= \rho \frac{\partial^2 y}{\partial t^2}
\end{align}
or in the limit $\Delta x \rightarrow 0$ a linear hyperbolic PDE results:
\begin{gather}
\frac{\partial^2 y(x, t)}{\partial x^2} = \frac{1}{c^2} \frac{\partial^2 y(x, t)}{\partial t^2}, \quad c = \sqrt{\frac{T}{\rho}}
\end{gather}
where $c$ has the dimension of a velocity. This is the (linear) **wave equation**.
### General solution: waves
General solutions are propagating waves:
If $f(x)$ is a solution at $t=0$ then
$$
y_{\mp}(x, t) = f(x \mp ct)
$$
are also solutions at later $t > 0$.
Because of linearity, any linear combination is also a solution, so the most general solution contains both right and left propagating waves
$$
y(x, t) = A f(x - ct) + B g(x + ct)
$$
(If $f$ and/or $g$ are present depends on the initial conditions.)
In three dimensions the wave equation is
$$
\boldsymbol{\nabla}^2 y(\mathbf{x}, t) - \frac{1}{c^2} \frac{\partial^2 y(\mathbf{x}, t)}{\partial t^2} = 0\
$$
### Boundary and initial conditions
* The boundary conditions could be that the ends are fixed
$$y(0, t) = y(L, t) = 0$$
* The *initial condition* is a shape for the string, e.g., a Gaussian at the center
$$
y(x, t=0) = g(x) = y_0 \frac{1}{\sqrt{2\pi\sigma}} \exp\left[-\frac{(x - x_0)^2}{2\sigma^2}\right]
$$
at time 0.
* Because the wave equation is *second order in time* we need a second initial condition, for instance, the string is released from rest:
$$
\frac{\partial y(x, t=0)}{\partial t} = 0
$$
(The derivative, i.e., the initial displacement velocity is provided.)
### Analytical solution
Solve (as always) with *separation of variables*.
$$
y(x, t) = X(x) T(t)
$$
and this yields the general solution (with boundary conditions of fixed string ends and initial condition of zero velocity) as a superposition of normal modes
$$
y(x, t) = \sum_{n=0}^{+\infty} B_n \sin k_n x\, \cos\omega_n t,
\quad \omega_n = ck_n,\ k_n = n \frac{2\pi}{L} = n k_0.
$$
(The angular frequency $\omega$ and the wave vector $k$ are determined from the boundary conditions.)
The coefficients $B_n$ are obtained from the initial shape:
$$
y(x, t=0) = \sum_{n=0}^{+\infty} B_n \sin n k_0 x = g(x)
$$
In principle one can use the fact that $\int_0^L dx \sin m k_0 x \, \sin n k_0 x = \pi \delta_{mn}$ (orthogonality) to calculate the coefficients:
\begin{align}
\int_0^L dx \sin m k_0 x \sum_{n=0}^{+\infty} B_n \sin n k_0 x &= \int_0^L dx \sin(m k_0 x) \, g(x)\\
\pi \sum_{n=0}^{+\infty} B_n \delta_{mn} &= \dots \\
B_m &= \pi^{-1} \dots
\end{align}
(but the analytical solution is ugly and I cannot be bothered to put it down here.)
## Numerical solution
1. discretize wave equation
2. time stepping: leap frog algorithm (iterate)
Use the central difference approximation for the second order derivatives:
\begin{align}
\frac{\partial^2 y}{\partial t^2} &\approx \frac{y(x, t+\Delta t) + y(x, t-\Delta t) - 2y(x, t)}{\Delta t ^2} = \frac{y_{i, j+1} + y_{i, j-1} - 2y_{i,j}}{\Delta t^2}\\
\frac{\partial^2 y}{\partial x^2} &\approx \frac{y(x+\Delta x, t) + y(x-\Delta x, t) - 2y(x, t)}{\Delta x ^2} = \frac{y_{i+1, j} + y_{i-1, j} - 2y_{i,j}}{\Delta x^2}
\end{align}
and substitute into the wave equation to yield the *discretized* wave equation:
$$
\frac{y_{i+1, j} + y_{i-1, j} - 2y_{i,j}}{\Delta x^2} = \frac{1}{c^2} \frac{y_{i, j+1} + y_{i, j-1} - 2y_{i,j}}{\Delta t^2}
$$
Re-arrange so that the future terms $j+1$ can be calculated from the present $j$ and past $j-1$ terms:
$$
y_{i,j+1} = 2(1 - \beta^2)y_{i,j} - y_{i, j-1} + \beta^2 (y_{i+1,j} + y_{i-1,j}), \quad
\beta := \frac{c}{\Delta x/\Delta t}
$$
This is the time stepping algorithm for the wave equation.
## Numerical implementation
```python
# if you have plotting problems, try
# %matplotlib inline
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.style.use('ggplot')
```
### Student version
```python
L = 0.5 # m
Nx = 50
Nt = 100
Dx = L/Nx
Dt = 1e-4 # s
rho = 1.5e-2 # kg/m
tension = 150 # N
c = np.sqrt(tension/rho)
# TODO: calculate beta
beta = c*Dt/Dx
beta2 = beta**2
print("c = {0} m/s".format(c))
print("Dx = {0} m, Dt = {1} s, Dx/Dt = {2} m/s".format(Dx, Dt, Dx/Dt))
print("beta = {}".format(beta))
X = np.linspace(0, L, Nx+1) # need N+1!
def gaussian(x, y0=0.05, x0=L/2, sigma=0.1*L):
return y0/np.sqrt(2*np.pi*sigma) * np.exp(-(x-x0)**2/(2*sigma**2))
# displacements at j-1, j, j+1
y0 = np.zeros_like(X)
y1 = np.zeros_like(y0)
y2 = np.zeros_like(y0)
# save array
y_t = np.zeros((Nt+1, Nx+1))
# boundary conditions
y0[0] = y0[-1] = y1[0] = y1[-1] = 0
y2[:] = y0
# initial conditions: velocity 0, i.e. no difference between y0 and y1
y0[1:-1] = y1[1:-1] = gaussian(X)[1:-1]
# save initial
t_index = 0
y_t[t_index, :] = y0
t_index += 1
y_t[t_index, :] = y1
for jt in range(2, Nt):
y2[1:-1] = 2*(1-beta2)*y1[1:-1] - y0[1:-1] + beta2*(y1[2:] + y1[:-2])
y0[:], y1[:] = y1, y2
t_index += 1
y_t[t_index, :] = y2
print("Iteration {0:5d}".format(jt), end="\r")
else:
print("Completed {0:5d} iterations: t={1} s".format(jt, jt*Dt))
```
c = 100.0 m/s
Dx = 0.01 m, Dt = 0.0001 s, Dx/Dt = 100.0 m/s
beta = 1.0
Completed 99 iterations: t=0.0099 s
### Fancy version
Package as a function and can use `step` to only save every `step` time steps.
```python
def wave(L=0.5, Nx=50, Dt=1e-4, Nt=100, step=1,
rho=1.5e-2, tension=150.):
Dx = L/Nx
#rho = 1.5e-2 # kg/m
#tension = 150 # N
c = np.sqrt(tension/rho)
beta = c*Dt/Dx
beta2 = beta**2
print("c = {0} m/s".format(c))
print("Dx = {0} m, Dt = {1} s, Dx/Dt = {2} m/s".format(Dx, Dt, Dx/Dt))
print("beta = {}".format(beta))
X = np.linspace(0, L, Nx+1) # need N+1!
def gaussian(x, y0=0.05, x0=L/2, sigma=0.1*L):
return y0/np.sqrt(2*np.pi*sigma) * np.exp(-(x-x0)**2/(2*sigma**2))
# displacements at j-1, j, j+1
y0 = np.zeros_like(X)
y1 = np.zeros_like(y0)
y2 = np.zeros_like(y0)
# save array
y_t = np.zeros((int(np.ceil(Nt/step)) + 1, Nx+1))
# boundary conditions
y0[0] = y0[-1] = y1[0] = y1[-1] = 0
y2[:] = y0
# initial conditions: velocity 0, i.e. no difference between y0 and y1
y0[1:-1] = y1[1:-1] = gaussian(X)[1:-1]
# save initial
t_index = 0
y_t[t_index, :] = y0
if step == 1:
t_index += 1
y_t[t_index, :] = y1
for jt in range(2, Nt):
y2[1:-1] = 2*(1-beta2)*y1[1:-1] - y0[1:-1] + beta2*(y1[2:] + y1[:-2])
y0[:], y1[:] = y1, y2
if jt % step == 0 or jt == Nt-1:
t_index += 1
y_t[t_index, :] = y2
print("Iteration {0:5d}".format(jt), end="\r")
else:
print("Completed {0:5d} iterations: t={1} s".format(jt, jt*Dt))
return y_t, X, Dx, Dt, step
```
```python
y_t, X, Dx, Dt, step = wave()
```
c = 100.0 m/s
Dx = 0.01 m, Dt = 0.0001 s, Dx/Dt = 100.0 m/s
beta = 1.0
Completed 99 iterations: t=0.0099 s
### 1D plot
Plot the output in the save array `y_t`. Vary the time steps that you look at with `y_t[start:end]`.
We indicate time by color changing.
```python
ax = plt.subplot(111)
ax.set_prop_cycle("color", [plt.cm.viridis(i) for i in np.linspace(0, 1, len(y_t))])
ax.plot(X, y_t[:40].T, alpha=0.5);
```
<IPython.core.display.Javascript object>
### 1D Animation
For 1D animation to work in a Jupyter notebook, use
```python
%matplotlib notebook
```
If no animations are visible, restart kernel and execute the `%matplotlib notebook` cell as the very first one in the notebook.
We use `matplotlib.animation` to look at movies of our solution:
```python
import matplotlib.animation as animation
```
Generate one full period:
```python
y_t, X, Dx, Dt, step = wave(Nt=100)
```
c = 100.0 m/s
Dx = 0.01 m, Dt = 0.0001 s, Dx/Dt = 100.0 m/s
beta = 1.0
Completed 99 iterations: t=0.0099 s
The `update_wave()` function simply re-draws our image for every `frame`.
```python
y_limits = 1.05*y_t.min(), 1.05*y_t.max()
fig1 = plt.figure(figsize=(5,5))
ax = fig1.add_subplot(111)
ax.set_aspect(1)
def update_wave(frame, data):
global ax, Dt, y_limits
ax.clear()
ax.set_xlabel("x (m)")
ax.set_ylabel("y (m)")
ax.plot(X, data[frame])
ax.set_ylim(y_limits)
ax.text(0.1, 0.9, "t = {0:3.1f} ms".format(frame*Dt*1e3), transform=ax.transAxes)
wave_anim = animation.FuncAnimation(fig1, update_wave, frames=len(y_t), fargs=(y_t,),
interval=30, blit=True, repeat_delay=100)
```
<IPython.core.display.Javascript object>
If you have ffmpeg installed then you can export to a MP4 movie file:
```python
wave_anim.save("string.mp4", fps=30, dpi=300)
```
The whole video can be incoroporated into an html page (uses the HTML5 `<video>` tag).
```python
with open("string.html", "w") as html:
html.write(wave_anim.to_html5_video())
```
```python
```
### 3D plot
(Uses functions from previous lessons.)
```python
def plot_y(y_t, Dx, Dt, step=1):
X, Y = np.meshgrid(range(y_t.shape[0]), range(y_t.shape[1]))
Z = y_t.T[Y, X]
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.plot_wireframe(Y*Dx, X*Dt*step, Z)
ax.set_ylabel(r"time $t$ (s)")
ax.set_xlabel(r"position $x$ (m)")
ax.set_zlabel(r"displacement $y$ (m)")
fig.tight_layout()
return ax
def plot_surf(y_t, Dt, Dx, step=1, filename=None, offset=-1, zlabel=r'displacement',
elevation=40, azimuth=20, cmap=plt.cm.coolwarm):
"""Plot y_t as a 3D plot with contour plot underneath.
Arguments
---------
y_t : 2D array
displacement y(t, x)
filename : string or None, optional (default: None)
If `None` then show the figure and return the axes object.
If a string is given (like "contour.png") it will only plot
to the filename and close the figure but return the filename.
offset : float, optional (default: 20)
position the 2D contour plot by offset along the Z direction
under the minimum Z value
zlabel : string, optional
label for the Z axis and color scale bar
elevation : float, optional
choose elevation for initial viewpoint
azimuth : float, optional
chooze azimuth angle for initial viewpoint
"""
t = np.arange(y_t.shape[0])
x = np.arange(y_t.shape[1])
T, X = np.meshgrid(t, x)
Y = y_t.T[X, T]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X*Dx, T*Dt*step, Y, cmap=cmap, rstride=1, cstride=1, alpha=1)
cset = ax.contourf(X*Dx, T*Dt*step, Y, 20, zdir='z', offset=offset+Y.min(), cmap=cmap)
ax.set_xlabel('x')
ax.set_ylabel('t')
ax.set_zlabel(zlabel)
ax.set_zlim(offset + Y.min(), Y.max())
ax.view_init(elev=elevation, azim=azimuth)
cb = fig.colorbar(surf, shrink=0.5, aspect=5)
cb.set_label(zlabel)
if filename:
fig.savefig(filename)
plt.close(fig)
return filename
else:
return ax
```
```python
plot_y(y_t, Dx, Dt)
```
<IPython.core.display.Javascript object>
<matplotlib.axes._subplots.Axes3DSubplot at 0x115b5e470>
```python
plot_surf(y_t, Dt, Dx, offset=-0.04, cmap=plt.cm.coolwarm)
```
<IPython.core.display.Javascript object>
<matplotlib.axes._subplots.Axes3DSubplot at 0x116361c88>
## von Neumann stability analysis: Courant condition
Assume that the solutions of the discretized equation can be written as normal modes
$$
y_{m,j} = \xi(k)^j e^{ikm\Delta x}, \quad t=j\Delta t,\ x=m\Delta x
$$
The time stepping algorith is stable if
$$
|\xi(k)| < 1
$$
Insert normal modes into the discretized equation
$$
y_{i,j+1} = 2(1 - \beta^2)y_{i,j} - y_{i, j-1} + \beta^2 (y_{i+1,j} + y_{i-1,j}), \quad
\beta := \frac{c}{\Delta x/\Delta t}
$$
and simplify (use $1-\cos x = 2\sin^2\frac{x}{2}$):
$$
\xi^2 - 2(1-2\beta^2 s^2)\xi + 1 = 0, \quad s=\sin(k\Delta x/2)
$$
The characteristic equation has roots
$$
\xi_{\pm} = 1 - 2\beta^2 s^2 \pm \sqrt{(1-2\beta^2 s^2)^2 - 1}.
$$
It has one root for
$$
\left|1-2\beta^2 s^2\right| = 1,
$$
i.e., for
$$
\beta s = 1
$$
We have two real roots for
$$
\left|1-2\beta^2 s^2\right| < 1 \\
\beta s > 1
$$
but one of the roots is always $|\xi| > 1$ and hence these solutions will diverge and not be stable.
For
$$
\left|1-2\beta^2 s^2\right| ā„ 1 \\
\beta s ⤠1
$$
the roots will be *complex conjugates of each other*
$$
\xi_\pm = 1 - 2\beta^2s^2 \pm i\sqrt{1-(1-2\beta^2s^2)^2}
$$
and the *magnitude*
$$
|\xi_{\pm}|^2 = (1 - 2\beta^2s^2)^2 - (1-(1-2\beta^2s^2)^2) = 1
$$
is unity: Thus the solutions will not grow and will be *stable* for
$$
\beta s ⤠1\\
\frac{c}{\frac{\Delta x}{\Delta t}} \sin\frac{k \Delta x}{2} ⤠1
$$
Assuming the "worst case" for the $\sin$ factor (namely, 1), the **condition for stability** is
$$
c ⤠\frac{\Delta x}{\Delta t}
$$
or
$$
\beta ⤠1.
$$
This is also known as the **Courant condition**. When written as
$$
\Delta t ⤠\frac{\Delta x}{c}
$$
it means that the time step $\Delta t$ (for a given $\Delta x$) must be *smaller than the time that the wave takes to travel one grid step*.
## Simplified simulation
The above example used real numbers for a cello string. Below is bare-bones where we just set $\beta$.
```python
L = 10.0
Nx = 100
Nt = 200
step = 1
Dx = L/Nx
beta2 = 1.0
X = np.linspace(0, L, Nx+1) # need N+1!
def gaussian(x):
return np.exp(-(x-5)**2)
# displacements at j-1, j, j+1
y0 = np.zeros_like(X)
y1 = np.zeros_like(y0)
y2 = np.zeros_like(y0)
# save array
y_t = np.zeros((int(np.ceil(Nt/step)) + 1, Nx+1))
# boundary conditions
y0[0] = y0[-1] = y1[0] = y1[-1] = 0
y2[:] = y0
# initial conditions: velocity 0, i.e. no difference between y0 and y1
y0[:] = y1[:] = gaussian(X)
# save initial
t_index = 0
y_t[t_index, :] = y0
if step == 1:
t_index += 1
y_t[t_index, :] = y1
for jt in range(2, Nt):
y2[1:-1] = 2*(1-beta2)*y1[1:-1] - y0[1:-1] + beta2*(y1[2:] + y1[:-2])
y0[:], y1[:] = y1, y2
if jt % step == 0 or jt == Nt-1:
t_index += 1
y_t[t_index, :] = y2
print("Iteration {0:5d}".format(jt), end="\r")
else:
print("Completed {0:5d} iterations: t={1} s".format(jt, jt*Dt))
```
Completed 199 iterations: t=199 s
```python
%matplotlib inline
```
```python
ax = plt.subplot(111)
ax.set_prop_cycle("color", [plt.cm.viridis_r(i) for i in np.linspace(0, 1, len(y_t))])
ax.plot(X, y_t.T);
```
|
import datetime
import logging
from typing import List, Tuple
import numpy as np
import geopandas as gpd
import pandas as pd
from geoalchemy2 import WKTElement
from shapely import wkt
from shapely.geometry import Polygon, Point
from sklearn.base import TransformerMixin
from sqlalchemy import VARCHAR
from tqdm import tqdm
import socket
from contextlib import closing
from coord2vec.common.db.connectors import get_connection
from coord2vec.common.db.sqlalchemy_utils import get_df, merge_to_table, add_sdo_geo_to_table, insert_into_table, \
get_temp_table_name
from coord2vec.common.geographic.visualization_utils import get_image_overlay
from coord2vec.config import STEP_SIZE, ors_server_ip, ors_server_port
from coord2vec.feature_extraction.feature_table import FEATURE_NAME, GEOM, GEOM_WKT, FEATURE_VALUE, \
MODIFICATION_DATE, DTYPES, GEOM_WKT_HASH
# TODO: re-order file, too long
def load_features_using_geoms(input_gs: gpd.GeoSeries, features_table: str,
feature_names: List[str] = None) -> gpd.GeoDataFrame:
"""
Args:
input_gs: A geo series with geometries to load features on
features_table: the cache table to load features from
feature_names: optional. load only a set of features. if None, will load all the features in the table
Returns:
A GeoDataFrame with feature names as columns, and input_gs as samples.
The geometry column in the gdf is GEOM_WKT
"""
features_table = features_table.lower()
# create temporary hash table
input_wkt = input_gs.apply(lambda geo: geo.wkt)
input_hash = [str(h) for h in pd.util.hash_pandas_object(input_wkt)]
input_hash_df = pd.DataFrame({GEOM_WKT_HASH: input_hash})
eng = get_connection(db_name='POSTGRES')
if not eng.has_table(features_table): # cache table does not exist
return gpd.GeoDataFrame() # just an empty gdf
tmp_tbl_name = get_temp_table_name()
insert_into_table(eng, input_hash_df, tmp_tbl_name, dtypes={GEOM_WKT_HASH: VARCHAR(300)})
add_q = lambda l: ["'" + s + "'" for s in l]
feature_filter_sql = f"WHERE {FEATURE_NAME} in ({', '.join(add_q(feature_names))})" if feature_names is not None else ""
# extract the features
query = f"""
select {FEATURE_NAME}, {FEATURE_VALUE}, {GEOM_WKT}, f.{GEOM_WKT_HASH}
from {features_table} f
join {tmp_tbl_name} t
on t.{GEOM_WKT_HASH} = f.{GEOM_WKT_HASH}
{feature_filter_sql}
"""
results_df = get_df(query, eng)
pivot_results_df = _pivot_table(results_df)
# create the full results df
full_df = pd.DataFrame(data={GEOM_WKT: input_gs.tolist()}, index=input_hash, columns=pivot_results_df.columns)
assert pivot_results_df.index.isin(full_df.index).all(), "all loaded features should be from the input (according to hash)"
if not pivot_results_df.empty:
full_df[full_df.index.isin(pivot_results_df.index)] = pivot_results_df[
pivot_results_df.index.isin(full_df.index)].values
full_gdf = gpd.GeoDataFrame(full_df, geometry=GEOM_WKT)
full_gdf = full_gdf.astype({c: float for c in pivot_results_df.columns if c != GEOM_WKT})
with eng.begin() as con:
con.execute(f"DROP TABLE {tmp_tbl_name}")
return full_gdf
def load_features_in_polygon(polygon: Polygon, features_table: str,
feature_names: List[str] = None) -> gpd.GeoDataFrame:
"""
Extract all the features already calculated inside a polygon
Args:
:param polygon: a polygon to get features of all the geometries inside of it
:param features_table: the name of the features table in which the cache is saved
:param feature_names: The names of all the features you want to extract. if None, extract all features
Returns:
A GeoDataFrame with a features as columns
"""
features_table = features_table.lower()
eng = get_connection(db_name='POSTGRES')
if eng.has_table(features_table):
# extract data
add_q = lambda l: ["'" + s + "'" for s in l]
feature_filter_sql = f"and {FEATURE_NAME} in ({', '.join(add_q(feature_names))})" if feature_names is not None else ""
query = f"""
select {FEATURE_NAME}, {FEATURE_VALUE}, CAST(ST_AsText({GEOM}) as TEXT) as {GEOM_WKT}, {GEOM_WKT_HASH}
from {features_table}
where ST_Covers(ST_GeomFromText('{polygon.wkt}', 4326)::geography, {GEOM})
{feature_filter_sql}
"""
res_df = get_df(query, eng)
ret_df = _pivot_table(res_df) # rearrange the df
else:
ret_df = gpd.GeoDataFrame()
eng.dispose()
return ret_df
def load_all_features(features_table: str) -> gpd.GeoDataFrame:
"""
Load all the features from the features table in the oracle db
Returns:
A Geo Dataframe with all the features as columns
"""
features_table = features_table.lower()
eng = get_connection(db_name='POSTGRES')
query = f"""
select {FEATURE_NAME}, {FEATURE_VALUE}, CAST(ST_AsText({GEOM}) as TEXT) as {GEOM_WKT}
from {features_table}
"""
res_df = pd.read_sql(query, eng)
eng.dispose()
return _pivot_table(res_df)
def _pivot_table(df: pd.DataFrame) -> gpd.GeoDataFrame:
hash2wkt = df[[GEOM_WKT_HASH, GEOM_WKT]].set_index(GEOM_WKT_HASH).to_dict()[GEOM_WKT]
features_df = df.pivot(index=GEOM_WKT_HASH, columns=FEATURE_NAME,
values=FEATURE_VALUE)
features_df[GEOM_WKT] = [wkt.loads(hash2wkt[h]) for h in features_df.index]
features_gdf = gpd.GeoDataFrame(features_df, geometry=GEOM_WKT, index=features_df.index)
return features_gdf
def save_features_to_db(gs: gpd.GeoSeries, df: pd.DataFrame, table_name: str):
"""
Insert features into the Oracle DB
Args:
gs: The geometries of the features
df: the features, with columns as feature names
table_name: the features table name in oracle db
Returns:
None
"""
if len(gs) == 0:
return
table_name = table_name.lower()
eng = get_connection(db_name='POSTGRES')
for column in tqdm(df.columns, desc=f'Inserting Features to {table_name}', unit='feature', leave=False):
insert_df = pd.DataFrame(data={MODIFICATION_DATE: datetime.datetime.now(),
GEOM: gs.values,
FEATURE_NAME: column,
FEATURE_VALUE: df[column]})
insert_df[GEOM_WKT] = insert_df[GEOM].apply(lambda g: g.wkt)
# add hash column for the GEOM_WKT
insert_df[GEOM_WKT_HASH] = [str(h) for h in pd.util.hash_pandas_object(insert_df[GEOM_WKT])]
insert_df[GEOM] = insert_df[GEOM].apply(lambda x: WKTElement(x.wkt, srid=4326))
merge_to_table(eng, insert_df, table_name, compare_columns=[GEOM_WKT_HASH, FEATURE_NAME],
update_columns=[MODIFICATION_DATE, FEATURE_VALUE, GEOM, GEOM_WKT], dtypes=DTYPES)
eng.dispose()
def extract_feature_image(polygon: Polygon, features_table: str, step=STEP_SIZE,
feature_names: List[str] = None) -> Tuple[np.ndarray, np.ndarray]:
features_table = features_table.lower()
features_df = load_features_in_polygon(polygon, features_table, feature_names)
image_mask_list = [get_image_overlay(features_df.iloc[:, -1], features_df[col], step=step, return_array=True) for
col in tqdm(features_df.columns[:-1], desc="Creating image from features", unit='feature')]
images_list = [feature[0] for feature in image_mask_list]
image = np.transpose(np.stack(images_list), (1, 2, 0))
# create mask
mask_index = image_mask_list[0][1]
mask = np.zeros((image.shape[0], image.shape[1]))
mask[mask_index] = 1
return image, mask
def ors_is_up(host=ors_server_ip, port=ors_server_port) -> bool:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
return sock.connect_ex((host, port)) == 0
class FeatureFilter(TransformerMixin):
# TODO: typing + add test
# TODO: this is no longer used in pipeline, old bug
def __init__(self, bundle: list=None, importance=10):
if bundle is not None:
from coord2vec.feature_extraction.features_builders import FeaturesBuilder
from coord2vec.feature_extraction.feature_bundles import create_building_features
all_feats = create_building_features(bundle, importance)
builder = FeaturesBuilder(all_feats)
self.feat_names = builder.all_feat_names
def fit(self, X: pd.DataFrame, y=None, **kwargs):
return self
def transform(self, X: pd.DataFrame):
if self.feat_names is not None:
assert isinstance(X, pd.DataFrame), f"X is not a DataFrame \n {X}"
feat_names_after_filt = [c for c in X.columns if c in self.feat_names]
if len(feat_names_after_filt) != len(self.feat_names):
pass
# logging.warning(f"""Some features in FeatureFilter do not appear in X
# X: {X.columns}
# filt_feat_names: {self.feat_names}
# """)
try:
# TODO: old bug was that applying this after feature selection resulted in feature not being here
X_filt = X[feat_names_after_filt]
except:
print("Error in FeatureFilter: returing X")
X_filt = X
return X_filt
return X
def fit_transform(self, X: pd.DataFrame, y=None, **fit_params):
return self.transform(X)
|
\documentclass{clean_cv}
% Add a BibTeX-style file encoding all of your publications to include here. You can export this from Zotero. Only include
% publications you want to appear here!
\addbibresource{pub.bib}
\author{Kaiwen "Kevin" Dong}
\headlineposition{Ph.D student, University of Notre Dame}
\begin{document}
\maketitle
% In this section, you can use any of the FontAwesome icons. The commands \faCenter and \faCenterStyle have been defined to properly center the icons
% when using the default font settings.
%
% You can use any of the icons listed in the fontawesome5 package documentation (https://ctan.math.utah.edu/ctan/tex-archive/fonts/fontawesome5/doc/fontawesome5.pdf)
% If you need to specify a specific style (as is done here for the address card), you should use the two-argument \faCenterCycle command
\begin{center}
\begin{tabular}{lll}
% & \faCenter{phone-alt} 541-754-301
\faCenter{envelope} \href{mailto:[email protected]}{[email protected]} & \faCenterStyle{regular}{address-card} 384 Nieuwland Science Hall, Notre Dame, IN 46556 USA & \faCenter{linkedin} \href{https://www.linkedin.com/in/kaiwen-dong-ab0634103/}{kaiwen-dong-ab0634103} \\
\faCenter{orcid} \href{https://orcid.org/0000-0001-8244-9562}{0000-0001-8244-9562} & \faCenter{globe} \url{https://barcavin.github.io/} & \faCenter{github} \href{https://github.com/Barcavin}{Barcavin}\\
\end{tabular}
\end{center}
\vspace{-1.5em}
\section{Education}
% The datetabular environment takes one argument, which is the width of the left date column. As seen here:
% 9em is a good choice for "dual-date" formats (e.g. Sep 2015 - Nov 2019).
% 4em is a good choice for month/year dates (Sep 2014).
% 2em is a good choice for year-only dates (as seen in the publications)
\begin{datetabular}{9em}
% This is just a tabular environment, for the most part. The dateentry command has been defined for
% convienence. It takes two arguments, the first is the date and the second is whatever you wish placed to the right.
\dateentry{Aug 2021 -- Present}{
\textbf{University of Notre Dame}
\textit{Ph.D student in Computer Science, Teaching Assistant, Research Assistant longerr}
}
\dateentry{Aug 2016 -- May 2018}{
\textbf{University of Illinois at Urbana-Champaign}
\textit{Master of Science in Statistics}
}
\dateentry{Sep 2012 -- June 2016}{
\textbf{University of Illinois at Urbana-Champaign}
\textit{Bachelor of Science in Mathematics and Applied Mathematics}
}
\end{datetabular}
\section{Work Experience}
\begin{datetabular}{9em}
\dateentry{2021 - 2021}{
\textbf{University of Notre Dame}
\textit{Graduate Teaching Assistant}
\begin{itemize}
\item Data Structure(Fall 2021)
\end{itemize}\eatvspace
}
\dateentry{2018 - 2021}{
\textbf{Aunalytics}
\textit{Data Scientist}
\begin{itemize}
\item Leaded the development of the text-to-SQL product, which translates a natural language utterance to a machine-executable SQL query.
\end{itemize}\eatvspace
}
% There is something seriously funky happening between the tabular commands and the end of the itemize blocks.
% The command \eatvspace should be used if extra space appears at the end of a datetabular environment.
\end{datetabular}
% \section{Leadership and Teaching Experience}
% \section{Honors}
\section{Publications}
\nocite{*} % Loads every entry from the attached .bib file
% Highlight takes three entries, given name, given name initials, and family name.
% If you have a middle initial, this call looks like:
% \highlightauthorname{Bob H.}{B. H.}{Smith}
\highlightauthorname{Kaiwen}{K.}{Dong}
\begin{datetabular}{2em}
%printbibyear has been defined to only print entries from a given citation year.
\dateentry{2021}{\printallbib}
\end{datetabular}
\end{document}
|
/-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Chris Hughes
! This file was ported from Lean 3 source module ring_theory.multiplicity
! leanprover-community/mathlib commit ceb887ddf3344dab425292e497fa2af91498437c
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Algebra.Associated
import Mathlib.Algebra.BigOperators.Basic
import Mathlib.RingTheory.Valuation.Basic
/-!
# Multiplicity of a divisor
For a commutative monoid, this file introduces the notion of multiplicity of a divisor and proves
several basic results on it.
## Main definitions
* `multiplicity a b`: for two elements `a` and `b` of a commutative monoid returns the largest
number `n` such that `a ^ n ⣠b` or infinity, written `ā¤`, if `a ^ n ⣠b` for all natural numbers
`n`.
* `multiplicity.Finite a b`: a predicate denoting that the multiplicity of `a` in `b` is finite.
-/
variable {α : Type _}
open Nat Part
open BigOperators
/-- `multiplicity a b` returns the largest natural number `n` such that
`a ^ n ⣠b`, as an `PartENat` or natural with infinity. If `ā n, a ^ n ⣠b`,
then it returns `ā¤`-/
def multiplicity [Monoid α] [DecidableRel ((Ā· ⣠·) : α ā α ā Prop)] (a b : α) : PartENat :=
PartENat.find fun n => ¬a ^ (n + 1) ⣠b
#align multiplicity multiplicity
namespace multiplicity
section Monoid
variable [Monoid α]
/-- `multiplicity.Finite a b` indicates that the multiplicity of `a` in `b` is finite. -/
@[reducible]
def Finite (a b : α) : Prop :=
ā n : ā, ¬a ^ (n + 1) ⣠b
#align multiplicity.finite multiplicity.Finite
theorem finite_iff_dom [DecidableRel ((Ā· ⣠·) : α ā α ā Prop)] {a b : α} :
Finite a b ā (multiplicity a b).Dom :=
Iff.rfl
#align multiplicity.finite_iff_dom multiplicity.finite_iff_dom
theorem finite_def {a b : α} : Finite a b ā ā n : ā, ¬a ^ (n + 1) ⣠b :=
Iff.rfl
#align multiplicity.finite_def multiplicity.finite_def
theorem not_dvd_one_of_finite_one_right {a : α} : Finite a 1 ā ¬a ⣠1 := fun āØn, hnā© āØd, hdā© =>
hn āØd ^ (n + 1), (pow_mul_pow_eq_one (n + 1) hd.symm).symmā©
#align multiplicity.not_dvd_one_of_finite_one_right multiplicity.not_dvd_one_of_finite_one_right
@[norm_cast]
theorem Int.coe_nat_multiplicity (a b : ā) : multiplicity (a : ā¤) (b : ā¤) = multiplicity a b := by
apply Part.ext'
Ā· rw [ā @finite_iff_dom ā, @finite_def ā, ā @finite_iff_dom ā¤, @finite_def ā¤]
norm_cast
Ā· intro h1 h2
apply _root_.le_antisymm <;>
Ā· apply Nat.find_mono
norm_cast
simp
#align multiplicity.int.coe_nat_multiplicity multiplicity.Int.coe_nat_multiplicity
theorem not_finite_iff_forall {a b : α} : ¬Finite a b ā ā n : ā, a ^ n ⣠b :=
āØfun h n =>
Nat.casesOn n
(by
rw [_root_.pow_zero]
exact one_dvd _)
(by simpa [Finite, Classical.not_not] using h),
by simp [Finite, multiplicity, Classical.not_not]; tautoā©
#align multiplicity.not_finite_iff_forall multiplicity.not_finite_iff_forall
theorem not_unit_of_finite {a b : α} (h : Finite a b) : ¬IsUnit a :=
let āØn, hnā© := h
hn ā IsUnit.dvd ā IsUnit.pow (n + 1)
#align multiplicity.not_unit_of_finite multiplicity.not_unit_of_finite
theorem finite_of_finite_mul_right {a b c : α} : Finite a (b * c) ā Finite a b := fun āØn, hnā© =>
āØn, fun h => hn (h.trans (dvd_mul_right _ _))ā©
#align multiplicity.finite_of_finite_mul_right multiplicity.finite_of_finite_mul_right
variable [DecidableRel ((Ā· ⣠·) : α ā α ā Prop)]
theorem pow_dvd_of_le_multiplicity {a b : α} {k : ā} :
(k : PartENat) ⤠multiplicity a b ā a ^ k ⣠b := by
rw [ā PartENat.some_eq_natCast]
exact
Nat.casesOn k
(fun _ => by
rw [_root_.pow_zero]
exact one_dvd _)
fun k āØ_, hāā© => by_contradiction fun hk => Nat.find_min _ (lt_of_succ_le (hā āØk, hkā©)) hk
#align multiplicity.pow_dvd_of_le_multiplicity multiplicity.pow_dvd_of_le_multiplicity
theorem pow_multiplicity_dvd {a b : α} (h : Finite a b) : a ^ get (multiplicity a b) h ⣠b :=
pow_dvd_of_le_multiplicity (by rw [PartENat.natCast_get])
#align multiplicity.pow_multiplicity_dvd multiplicity.pow_multiplicity_dvd
theorem is_greatest {a b : α} {m : ā} (hm : multiplicity a b < m) : ¬a ^ m ⣠b := fun h => by
rw [PartENat.lt_coe_iff] at hm; exact Nat.find_spec hm.fst ((pow_dvd_pow _ hm.snd).trans h)
#align multiplicity.is_greatest multiplicity.is_greatest
theorem is_greatest' {a b : α} {m : ā} (h : Finite a b) (hm : get (multiplicity a b) h < m) :
¬a ^ m ⣠b :=
is_greatest (by rwa [ā PartENat.coe_lt_coe, PartENat.natCast_get] at hm)
#align multiplicity.is_greatest' multiplicity.is_greatest'
theorem pos_of_dvd {a b : α} (hfin : Finite a b) (hdiv : a ⣠b) : 0 < (multiplicity a b).get hfin :=
by
refine' zero_lt_iff.2 fun h => _
simpa [hdiv] using is_greatest' hfin (lt_one_iff.mpr h)
#align multiplicity.pos_of_dvd multiplicity.pos_of_dvd
theorem unique {a b : α} {k : ā} (hk : a ^ k ⣠b) (hsucc : ¬a ^ (k + 1) ⣠b) :
(k : PartENat) = multiplicity a b :=
le_antisymm (le_of_not_gt fun hk' => is_greatest hk' hk) <| by
have : Finite a b := āØk, hsuccā©
rw [PartENat.le_coe_iff]
exact āØthis, Nat.find_min' _ hsuccā©
#align multiplicity.unique multiplicity.unique
theorem unique' {a b : α} {k : ā} (hk : a ^ k ⣠b) (hsucc : ¬a ^ (k + 1) ⣠b) :
k = get (multiplicity a b) āØk, hsuccā© := by
rw [ā PartENat.natCast_inj, PartENat.natCast_get, unique hk hsucc]
#align multiplicity.unique' multiplicity.unique'
theorem le_multiplicity_of_pow_dvd {a b : α} {k : ā} (hk : a ^ k ⣠b) :
(k : PartENat) ⤠multiplicity a b :=
le_of_not_gt fun hk' => is_greatest hk' hk
#align multiplicity.le_multiplicity_of_pow_dvd multiplicity.le_multiplicity_of_pow_dvd
theorem pow_dvd_iff_le_multiplicity {a b : α} {k : ā} :
a ^ k ⣠b ā (k : PartENat) ⤠multiplicity a b :=
āØle_multiplicity_of_pow_dvd, pow_dvd_of_le_multiplicityā©
#align multiplicity.pow_dvd_iff_le_multiplicity multiplicity.pow_dvd_iff_le_multiplicity
theorem multiplicity_lt_iff_neg_dvd {a b : α} {k : ā} :
multiplicity a b < (k : PartENat) ā ¬a ^ k ⣠b := by rw [pow_dvd_iff_le_multiplicity, not_le]
#align multiplicity.multiplicity_lt_iff_neg_dvd multiplicity.multiplicity_lt_iff_neg_dvd
theorem eq_coe_iff {a b : α} {n : ā} :
multiplicity a b = (n : PartENat) ā a ^ n ⣠b ⧠¬a ^ (n + 1) ⣠b := by
rw [ā PartENat.some_eq_natCast]
exact
āØfun h =>
let āØhā, hāā© := eq_some_iff.1 h
hā āø āØpow_multiplicity_dvd _, is_greatest (by
rw [PartENat.lt_coe_iff]
exact āØhā, lt_succ_self _ā©)ā©,
fun h => eq_some_iff.2 āØāØn, h.2ā©, Eq.symm <| unique' h.1 h.2ā©ā©
#align multiplicity.eq_coe_iff multiplicity.eq_coe_iff
theorem eq_top_iff {a b : α} : multiplicity a b = ⤠ā ā n : ā, a ^ n ⣠b :=
(PartENat.find_eq_top_iff _).trans <|
by
simp only [Classical.not_not]
exact
āØfun h n =>
Nat.casesOn n
(by
rw [_root_.pow_zero]
exact one_dvd _)
fun n => h _,
fun h n => h _ā©
#align multiplicity.eq_top_iff multiplicity.eq_top_iff
@[simp]
theorem isUnit_left {a : α} (b : α) (ha : IsUnit a) : multiplicity a b = ⤠:=
eq_top_iff.2 fun _ => IsUnit.dvd (ha.pow _)
#align multiplicity.is_unit_left multiplicity.isUnit_left
-- @[simp] Porting note: simp can prove this
theorem one_left (b : α) : multiplicity 1 b = ⤠:=
isUnit_left b isUnit_one
#align multiplicity.one_left multiplicity.one_left
@[simp]
theorem get_one_right {a : α} (ha : Finite a 1) : get (multiplicity a 1) ha = 0 := by
rw [PartENat.get_eq_iff_eq_coe, eq_coe_iff, _root_.pow_zero]
simp [not_dvd_one_of_finite_one_right ha]
#align multiplicity.get_one_right multiplicity.get_one_right
-- @[simp] Porting note: simp can prove this
theorem unit_left (a : α) (u : αˣ) : multiplicity (u : α) a = ⤠:=
isUnit_left a u.isUnit
#align multiplicity.unit_left multiplicity.unit_left
theorem multiplicity_eq_zero {a b : α} : multiplicity a b = 0 ā ¬a ⣠b := by
rw [ā Nat.cast_zero, eq_coe_iff]
simp only [_root_.pow_zero, isUnit_one, IsUnit.dvd, zero_add, pow_one, true_and]
#align multiplicity.multiplicity_eq_zero multiplicity.multiplicity_eq_zero
theorem multiplicity_ne_zero {a b : α} : multiplicity a b ā 0 ā a ⣠b :=
multiplicity_eq_zero.not_left
#align multiplicity.multiplicity_ne_zero multiplicity.multiplicity_ne_zero
theorem eq_top_iff_not_finite {a b : α} : multiplicity a b = ⤠ā ¬Finite a b :=
Part.eq_none_iff'
#align multiplicity.eq_top_iff_not_finite multiplicity.eq_top_iff_not_finite
theorem ne_top_iff_finite {a b : α} : multiplicity a b ā ⤠ā Finite a b := by
rw [Ne.def, eq_top_iff_not_finite, Classical.not_not]
#align multiplicity.ne_top_iff_finite multiplicity.ne_top_iff_finite
theorem lt_top_iff_finite {a b : α} : multiplicity a b < ⤠ā Finite a b := by
rw [lt_top_iff_ne_top, ne_top_iff_finite]
#align multiplicity.lt_top_iff_finite multiplicity.lt_top_iff_finite
theorem exists_eq_pow_mul_and_not_dvd {a b : α} (hfin : Finite a b) :
ā c : α, b = a ^ (multiplicity a b).get hfin * c ⧠¬a ⣠c := by
obtain āØc, hcā© := multiplicity.pow_multiplicity_dvd hfin
refine' āØc, hc, _ā©
rintro āØk, hkā©
rw [hk, ā mul_assoc, ā _root_.pow_succ'] at hc
have hā : a ^ ((multiplicity a b).get hfin + 1) ⣠b := āØk, hcā©
exact (multiplicity.eq_coe_iff.1 (by simp)).2 hā
#align multiplicity.exists_eq_pow_mul_and_not_dvd multiplicity.exists_eq_pow_mul_and_not_dvd
open Classical
theorem multiplicity_le_multiplicity_iff {a b c d : α} :
multiplicity a b ⤠multiplicity c d ā ā n : ā, a ^ n ⣠b ā c ^ n ⣠d :=
āØfun h n hab => pow_dvd_of_le_multiplicity (le_trans (le_multiplicity_of_pow_dvd hab) h), fun h =>
if hab : Finite a b then by
rw [ā PartENat.natCast_get (finite_iff_dom.1 hab)];
exact le_multiplicity_of_pow_dvd (h _ (pow_multiplicity_dvd _))
else by
have : ā n : ā, c ^ n ⣠d := fun n => h n (not_finite_iff_forall.1 hab _)
rw [eq_top_iff_not_finite.2 hab, eq_top_iff_not_finite.2 (not_finite_iff_forall.2 this)]
apply le_reflā©
#align multiplicity.multiplicity_le_multiplicity_iff multiplicity.multiplicity_le_multiplicity_iff
theorem multiplicity_eq_multiplicity_iff {a b c d : α} :
multiplicity a b = multiplicity c d ā ā n : ā, a ^ n ⣠b ā c ^ n ⣠d :=
āØfun h n =>
āØmultiplicity_le_multiplicity_iff.mp h.le n, multiplicity_le_multiplicity_iff.mp h.ge nā©,
fun h =>
le_antisymm (multiplicity_le_multiplicity_iff.mpr fun n => (h n).mp)
(multiplicity_le_multiplicity_iff.mpr fun n => (h n).mpr)ā©
#align multiplicity.multiplicity_eq_multiplicity_iff multiplicity.multiplicity_eq_multiplicity_iff
theorem multiplicity_le_multiplicity_of_dvd_right {a b c : α} (h : b ⣠c) :
multiplicity a b ⤠multiplicity a c :=
multiplicity_le_multiplicity_iff.2 fun _ hb => hb.trans h
#align multiplicity.multiplicity_le_multiplicity_of_dvd_right multiplicity.multiplicity_le_multiplicity_of_dvd_right
theorem eq_of_associated_right {a b c : α} (h : Associated b c) :
multiplicity a b = multiplicity a c :=
le_antisymm (multiplicity_le_multiplicity_of_dvd_right h.dvd)
(multiplicity_le_multiplicity_of_dvd_right h.symm.dvd)
#align multiplicity.eq_of_associated_right multiplicity.eq_of_associated_right
theorem dvd_of_multiplicity_pos {a b : α} (h : (0 : PartENat) < multiplicity a b) : a ⣠b := by
rw [ā pow_one a]
apply pow_dvd_of_le_multiplicity
simpa only [Nat.cast_one, PartENat.pos_iff_one_le] using h
#align multiplicity.dvd_of_multiplicity_pos multiplicity.dvd_of_multiplicity_pos
theorem dvd_iff_multiplicity_pos {a b : α} : (0 : PartENat) < multiplicity a b ā a ⣠b :=
āØdvd_of_multiplicity_pos, fun hdvd =>
lt_of_le_of_ne (zero_le _) fun heq =>
is_greatest
(show multiplicity a b < ā1 by
simpa only [heq, Nat.cast_zero] using PartENat.coe_lt_coe.mpr zero_lt_one)
(by rwa [pow_one a])ā©
#align multiplicity.dvd_iff_multiplicity_pos multiplicity.dvd_iff_multiplicity_pos
theorem finite_nat_iff {a b : ā} : Finite a b ā a ā 1 ā§ 0 < b := by
rw [ā not_iff_not, not_finite_iff_forall, not_and_or, Ne.def, Classical.not_not, not_lt,
le_zero_iff]
exact
āØfun h =>
or_iff_not_imp_right.2 fun hb =>
have ha : a ā 0 := fun ha => hb <| zero_dvd_iff.mp <| by rw [ha] at h; exact h 1
Classical.by_contradiction fun ha1 : a ā 1 =>
have ha_gt_one : 1 < a :=
lt_of_not_ge fun _ =>
match a with
| 0 => ha rfl
| 1 => ha1 rfl
| b+2 => by linarith
not_lt_of_ge (le_of_dvd (Nat.pos_of_ne_zero hb) (h b)) (lt_pow_self ha_gt_one b),
fun h => by cases h <;> simp [*]ā©
#align multiplicity.finite_nat_iff multiplicity.finite_nat_iff
alias dvd_iff_multiplicity_pos ā _ _root_.has_dvd.dvd.multiplicity_pos
end Monoid
section CommMonoid
variable [CommMonoid α]
theorem finite_of_finite_mul_left {a b c : α} : Finite a (b * c) ā Finite a c := by
rw [mul_comm]; exact finite_of_finite_mul_right
#align multiplicity.finite_of_finite_mul_left multiplicity.finite_of_finite_mul_left
variable [DecidableRel ((Ā· ⣠·) : α ā α ā Prop)]
theorem isUnit_right {a b : α} (ha : ¬IsUnit a) (hb : IsUnit b) : multiplicity a b = 0 :=
eq_coe_iff.2
āØshow a ^ 0 ⣠b by simp only [_root_.pow_zero, one_dvd], by
rw [pow_one]
exact fun h => mt (isUnit_of_dvd_unit h) ha hbā©
#align multiplicity.is_unit_right multiplicity.isUnit_right
theorem one_right {a : α} (ha : ¬IsUnit a) : multiplicity a 1 = 0 :=
isUnit_right ha isUnit_one
#align multiplicity.one_right multiplicity.one_right
theorem unit_right {a : α} (ha : ¬IsUnit a) (u : αˣ) : multiplicity a u = 0 :=
isUnit_right ha u.isUnit
#align multiplicity.unit_right multiplicity.unit_right
open Classical
theorem multiplicity_le_multiplicity_of_dvd_left {a b c : α} (hdvd : a ⣠b) :
multiplicity b c ⤠multiplicity a c :=
multiplicity_le_multiplicity_iff.2 fun n h => (pow_dvd_pow_of_dvd hdvd n).trans h
#align multiplicity.multiplicity_le_multiplicity_of_dvd_left multiplicity.multiplicity_le_multiplicity_of_dvd_left
theorem eq_of_associated_left {a b c : α} (h : Associated a b) :
multiplicity b c = multiplicity a c :=
le_antisymm (multiplicity_le_multiplicity_of_dvd_left h.dvd)
(multiplicity_le_multiplicity_of_dvd_left h.symm.dvd)
#align multiplicity.eq_of_associated_left multiplicity.eq_of_associated_left
-- Porting note: this was doing nothing in mathlib3 also
-- alias dvd_iff_multiplicity_pos ā _ _root_.has_dvd.dvd.multiplicity_pos
end CommMonoid
section MonoidWithZero
variable [MonoidWithZero α]
theorem ne_zero_of_finite {a b : α} (h : Finite a b) : b ā 0 :=
let āØn, hnā© := h
fun hb => by simp [hb] at hn
#align multiplicity.ne_zero_of_finite multiplicity.ne_zero_of_finite
variable [DecidableRel ((Ā· ⣠·) : α ā α ā Prop)]
@[simp]
protected theorem zero (a : α) : multiplicity a 0 = ⤠:=
Part.eq_none_iff.2 fun _ āØāØ_, hkā©, _ā© => hk (dvd_zero _)
#align multiplicity.zero multiplicity.zero
@[simp]
theorem multiplicity_zero_eq_zero_of_ne_zero (a : α) (ha : a ā 0) : multiplicity 0 a = 0 :=
multiplicity.multiplicity_eq_zero.2 <| mt zero_dvd_iff.1 ha
#align multiplicity.multiplicity_zero_eq_zero_of_ne_zero multiplicity.multiplicity_zero_eq_zero_of_ne_zero
end MonoidWithZero
section CommMonoidWithZero
variable [CommMonoidWithZero α]
variable [DecidableRel ((Ā· ⣠·) : α ā α ā Prop)]
theorem multiplicity_mk_eq_multiplicity
[DecidableRel ((Ā· ⣠·) : Associates α ā Associates α ā Prop)] {a b : α} :
multiplicity (Associates.mk a) (Associates.mk b) = multiplicity a b := by
by_cases h : Finite a b
Ā· rw [ā PartENat.natCast_get (finite_iff_dom.mp h)]
refine'
(multiplicity.unique
(show Associates.mk a ^ (multiplicity a b).get h ⣠Associates.mk b from _) _).symm <;>
rw [ā Associates.mk_pow, Associates.mk_dvd_mk]
Ā· exact pow_multiplicity_dvd h
Ā· exact is_greatest
((PartENat.lt_coe_iff _ _).mpr (Exists.intro (finite_iff_dom.mp h) (Nat.lt_succ_self _)))
· suffices ¬Finite (Associates.mk a) (Associates.mk b) by
rw [finite_iff_dom, PartENat.not_dom_iff_eq_top] at h this
rw [h, this]
refine'
not_finite_iff_forall.mpr fun n =>
by
rw [ā Associates.mk_pow, Associates.mk_dvd_mk]
exact not_finite_iff_forall.mp h n
#align multiplicity.multiplicity_mk_eq_multiplicity multiplicity.multiplicity_mk_eq_multiplicity
end CommMonoidWithZero
section Semiring
variable [Semiring α] [DecidableRel ((Ā· ⣠·) : α ā α ā Prop)]
theorem min_le_multiplicity_add {p a b : α} :
min (multiplicity p a) (multiplicity p b) ⤠multiplicity p (a + b) :=
(le_total (multiplicity p a) (multiplicity p b)).elim
(fun h => by
rw [min_eq_left h, multiplicity_le_multiplicity_iff];
exact fun n hn => dvd_add hn (multiplicity_le_multiplicity_iff.1 h n hn))
fun h => by
rw [min_eq_right h, multiplicity_le_multiplicity_iff];
exact fun n hn => dvd_add (multiplicity_le_multiplicity_iff.1 h n hn) hn
#align multiplicity.min_le_multiplicity_add multiplicity.min_le_multiplicity_add
end Semiring
section Ring
variable [Ring α] [DecidableRel ((Ā· ⣠·) : α ā α ā Prop)]
@[simp]
protected theorem neg (a b : α) : multiplicity a (-b) = multiplicity a b :=
Part.ext' (by simp only [multiplicity, PartENat.find, dvd_neg]) fun hā hā =>
PartENat.natCast_inj.1 (by
rw [PartENat.natCast_get]
exact Eq.symm
(unique ((dvd_neg _ _).2 (pow_multiplicity_dvd _))
(mt (dvd_neg _ _).1 (is_greatest' _ (lt_succ_self _)))))
#align multiplicity.neg multiplicity.neg
theorem Int.natAbs (a : ā) (b : ā¤) : multiplicity a b.natAbs = multiplicity (a : ā¤) b := by
cases' Int.natAbs_eq b with h h <;> conv_rhs => rw [h]
Ā· rw [Int.coe_nat_multiplicity]
Ā· rw [multiplicity.neg, Int.coe_nat_multiplicity]
#align multiplicity.int.nat_abs multiplicity.Int.natAbs
theorem multiplicity_add_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) :
multiplicity p (a + b) = multiplicity p b := by
apply le_antisymm
Ā· apply PartENat.le_of_lt_add_one
cases' PartENat.ne_top_iff.mp (PartENat.ne_top_of_lt h) with k hk
rw [hk]
rw_mod_cast [multiplicity_lt_iff_neg_dvd]
intro h_dvd
rw [ā dvd_add_iff_right] at h_dvd
Ā· apply multiplicity.is_greatest _ h_dvd
rw [hk, āNat.succ_eq_add_one]
norm_cast
apply Nat.lt_succ_self k
Ā· rw [pow_dvd_iff_le_multiplicity, Nat.cast_add, ā hk, Nat.cast_one]
exact PartENat.add_one_le_of_lt h
· have := @min_le_multiplicity_add α _ _ p a b
rwa [ā min_eq_right (le_of_lt h)]
#align multiplicity.multiplicity_add_of_gt multiplicity.multiplicity_add_of_gt
theorem multiplicity_sub_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) :
multiplicity p (a - b) = multiplicity p b := by
rw [sub_eq_add_neg, multiplicity_add_of_gt] <;> rw [multiplicity.neg]; assumption
#align multiplicity.multiplicity_sub_of_gt multiplicity.multiplicity_sub_of_gt
theorem multiplicity_add_eq_min {p a b : α} (h : multiplicity p a ā multiplicity p b) :
multiplicity p (a + b) = min (multiplicity p a) (multiplicity p b) := by
rcases lt_trichotomy (multiplicity p a) (multiplicity p b) with (hab | hab | hab)
Ā· rw [add_comm, multiplicity_add_of_gt hab, min_eq_left]
exact le_of_lt hab
Ā· contradiction
Ā· rw [multiplicity_add_of_gt hab, min_eq_right]
exact le_of_lt hab
#align multiplicity.multiplicity_add_eq_min multiplicity.multiplicity_add_eq_min
end Ring
section CancelCommMonoidWithZero
variable [CancelCommMonoidWithZero α]
/- Porting note: removed previous wf recursion hints and added termination_by
Also pulled a b intro parameters since Lean parses that more easily -/
theorem finite_mul_aux {p : α} (hp : Prime p) {a b : α}:
ā {n m : ā}, ¬p ^ (n + 1) ⣠a ā ¬p ^ (m + 1) ⣠b ā ¬p ^ (n + m + 1) ⣠a * b
| n, m => fun ha hb āØs, hsā© =>
have : p ⣠a * b := āØp ^ (n + m) * s, by simp [hs, pow_add, mul_comm, mul_assoc, mul_left_comm]ā©
(hp.2.2 a b this).elim
(fun āØx, hxā© =>
have hn0 : 0 < n :=
Nat.pos_of_ne_zero fun hn0 => by simp [hx, hn0] at ha
have hpx : ¬p ^ (n - 1 + 1) ⣠x := fun āØy, hyā© =>
ha (hx.symm āø āØy, mul_right_cancelā hp.1 <| by
rw [tsub_add_cancel_of_le (succ_le_of_lt hn0)] at hy;
simp [hy, pow_add, mul_comm, mul_assoc, mul_left_comm]ā©)
have : 1 ⤠n + m := le_trans hn0 (Nat.le_add_right n m)
finite_mul_aux hp hpx hb
āØs, mul_right_cancelā hp.1 (by
rw [tsub_add_eq_add_tsub (succ_le_of_lt hn0), tsub_add_cancel_of_le this]
simp_all [mul_comm, mul_assoc, mul_left_comm, pow_add])ā©)
fun āØx, hxā© =>
have hm0 : 0 < m :=
Nat.pos_of_ne_zero fun hm0 => by simp [hx, hm0] at hb
have hpx : ¬p ^ (m - 1 + 1) ⣠x := fun āØy, hyā© =>
hb
(hx.symm āø
āØy,
mul_right_cancelā hp.1 <| by
rw [tsub_add_cancel_of_le (succ_le_of_lt hm0)] at hy;
simp [hy, pow_add, mul_comm, mul_assoc, mul_left_comm]ā©)
finite_mul_aux hp ha hpx
āØs, mul_right_cancelā hp.1 (by
rw [add_assoc, tsub_add_cancel_of_le (succ_le_of_lt hm0)]
simp_all [mul_comm, mul_assoc, mul_left_comm, pow_add])ā©
termination_by finite_mul_aux _ _ n m => n+m
#align multiplicity.finite_mul_aux multiplicity.finite_mul_aux
theorem finite_mul {p a b : α} (hp : Prime p) : Finite p a ā Finite p b ā Finite p (a * b) :=
fun āØn, hnā© āØm, hmā© => āØn + m, finite_mul_aux hp hn hmā©
#align multiplicity.finite_mul multiplicity.finite_mul
theorem finite_mul_iff {p a b : α} (hp : Prime p) : Finite p (a * b) ā Finite p a ā§ Finite p b :=
āØfun h => āØfinite_of_finite_mul_right h, finite_of_finite_mul_left hā©, fun h =>
finite_mul hp h.1 h.2ā©
#align multiplicity.finite_mul_iff multiplicity.finite_mul_iff
theorem finite_pow {p a : α} (hp : Prime p) : ā {k : ā} (_ : Finite p a), Finite p (a ^ k)
| 0, _ => āØ0, by simp [mt isUnit_iff_dvd_one.2 hp.2.1]ā©
| k + 1, ha => by rw [_root_.pow_succ]; exact finite_mul hp ha (finite_pow hp ha)
#align multiplicity.finite_pow multiplicity.finite_pow
variable [DecidableRel ((Ā· ⣠·) : α ā α ā Prop)]
@[simp]
theorem multiplicity_self {a : α} (ha : ¬IsUnit a) (ha0 : a ā 0) : multiplicity a a = 1 := by
rw [ā Nat.cast_one]
exact eq_coe_iff.2 āØby simp, fun āØb, hbā© => ha (isUnit_iff_dvd_one.2
āØb, mul_left_cancelā ha0 <| by simpa [_root_.pow_succ, mul_assoc] using hbā©)ā©
#align multiplicity.multiplicity_self multiplicity.multiplicity_self
@[simp]
theorem get_multiplicity_self {a : α} (ha : Finite a a) : get (multiplicity a a) ha = 1 :=
PartENat.get_eq_iff_eq_coe.2
(eq_coe_iff.2
āØby simp, fun āØb, hbā© => by
rw [ā mul_one a, pow_add, pow_one, mul_assoc, mul_assoc,
mul_right_inj' (ne_zero_of_finite ha)] at hb;
exact
mt isUnit_iff_dvd_one.2 (not_unit_of_finite ha) āØb, by simp_allā©ā©)
#align multiplicity.get_multiplicity_self multiplicity.get_multiplicity_self
protected theorem mul' {p a b : α} (hp : Prime p) (h : (multiplicity p (a * b)).Dom) :
get (multiplicity p (a * b)) h =
get (multiplicity p a) ((finite_mul_iff hp).1 h).1 +
get (multiplicity p b) ((finite_mul_iff hp).1 h).2 := by
have hdiva : p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 ⣠a := pow_multiplicity_dvd _
have hdivb : p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 ⣠b := pow_multiplicity_dvd _
have hpoweq :
p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 +
get (multiplicity p b) ((finite_mul_iff hp).1 h).2) =
p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 *
p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 :=
by simp [pow_add]
have hdiv :
p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 +
get (multiplicity p b) ((finite_mul_iff hp).1 h).2) ā£
a * b :=
by rw [hpoweq]; apply mul_dvd_mul <;> assumption
have hsucc :
¬p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 +
get (multiplicity p b) ((finite_mul_iff hp).1 h).2 +
1) ā£
a * b :=
fun h =>
not_or_of_not (is_greatest' _ (lt_succ_self _)) (is_greatest' _ (lt_succ_self _))
(_root_.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul hp hdiva hdivb h)
rw [ā PartENat.natCast_inj, PartENat.natCast_get, eq_coe_iff]; exact āØhdiv, hsuccā©
#align multiplicity.mul' multiplicity.mul'
open Classical
protected theorem mul {p a b : α} (hp : Prime p) :
multiplicity p (a * b) = multiplicity p a + multiplicity p b :=
if h : Finite p a ā§ Finite p b then by
rw [ā PartENat.natCast_get (finite_iff_dom.1 h.1), ā
PartENat.natCast_get (finite_iff_dom.1 h.2), ā
PartENat.natCast_get (finite_iff_dom.1 (finite_mul hp h.1 h.2)), ā Nat.cast_add,
PartENat.natCast_inj, multiplicity.mul' hp]
else by
rw [eq_top_iff_not_finite.2 (mt (finite_mul_iff hp).1 h)]
cases' not_and_or.1 h with h h <;> simp [eq_top_iff_not_finite.2 h]
#align multiplicity.mul multiplicity.mul
theorem Finset.prod {β : Type _} {p : α} (hp : Prime p) (s : Finset β) (f : β ā α) :
multiplicity p (ā x in s, f x) = ā x in s, multiplicity p (f x) := by
classical
induction' s using Finset.induction with a s has ih h
Ā· simp only [Finset.sum_empty, Finset.prod_empty]
convert one_right hp.not_unit
Ā· simp [has, ā ih]
convert multiplicity.mul hp
#align multiplicity.finset.prod multiplicity.Finset.prod
-- Porting note: with protected could not use pow' k in the succ branch
protected theorem pow' {p a : α} (hp : Prime p) (ha : Finite p a) :
ā {k : ā}, get (multiplicity p (a ^ k)) (finite_pow hp ha) = k * get (multiplicity p a) ha :=
by
intro k
induction' k with k hk
Ā· simp [one_right hp.not_unit]
Ā· have : multiplicity p (a ^ (k + 1)) = multiplicity p (a * a ^ k) := by rw [_root_.pow_succ]
rw [succ_eq_add_one, get_eq_get_of_eq _ _ this,
multiplicity.mul' hp, hk, add_mul, one_mul, add_comm]
#align multiplicity.pow' multiplicity.pow'
theorem pow {p a : α} (hp : Prime p) : ā {k : ā}, multiplicity p (a ^ k) = k ⢠multiplicity p a
| 0 => by simp [one_right hp.not_unit]
| succ k => by simp [_root_.pow_succ, succ_nsmul, pow hp, multiplicity.mul hp]
#align multiplicity.pow multiplicity.pow
theorem multiplicity_pow_self {p : α} (h0 : p ā 0) (hu : ¬IsUnit p) (n : ā) :
multiplicity p (p ^ n) = n := by
rw [eq_coe_iff]
use dvd_rfl
rw [pow_dvd_pow_iff h0 hu]
apply Nat.not_succ_le_self
#align multiplicity.multiplicity_pow_self multiplicity.multiplicity_pow_self
theorem multiplicity_pow_self_of_prime {p : α} (hp : Prime p) (n : ā) :
multiplicity p (p ^ n) = n :=
multiplicity_pow_self hp.ne_zero hp.not_unit n
#align multiplicity.multiplicity_pow_self_of_prime multiplicity.multiplicity_pow_self_of_prime
end CancelCommMonoidWithZero
section Valuation
variable {R : Type _} [CommRing R] [IsDomain R] {p : R} [DecidableRel (Dvd.dvd : R ā R ā Prop)]
/-- `multiplicity` of a prime in an integral domain as an additive valuation to `PartENat`. -/
noncomputable def addValuation (hp : Prime p) : AddValuation R PartENat :=
AddValuation.of (multiplicity p) (multiplicity.zero _) (one_right hp.not_unit)
(fun _ _ => min_le_multiplicity_add) fun _ _ => multiplicity.mul hp
#align multiplicity.add_valuation multiplicity.addValuation
@[simp]
theorem addValuation_apply {hp : Prime p} {r : R} : addValuation hp r = multiplicity p r :=
rfl
#align multiplicity.add_valuation_apply multiplicity.addValuation_apply
end Valuation
end multiplicity
section Nat
open multiplicity
theorem multiplicity_eq_zero_of_coprime {p a b : ā} (hp : p ā 1)
(hle : multiplicity p a ⤠multiplicity p b) (hab : Nat.coprime a b) : multiplicity p a = 0 := by
rw [multiplicity_le_multiplicity_iff] at hle
rw [ā nonpos_iff_eq_zero, ā not_lt, PartENat.pos_iff_one_le, ā Nat.cast_one, ā
pow_dvd_iff_le_multiplicity]
intro h
have := Nat.dvd_gcd h (hle _ h)
rw [coprime.gcd_eq_one hab, Nat.dvd_one, pow_one] at this
exact hp this
#align multiplicity_eq_zero_of_coprime multiplicity_eq_zero_of_coprime
end Nat
|
Note: Rijeka Challenger Men live on FlashScore.ca.
Follow Rijeka Challenger Men page for live scores, final results, fixtures and draws! Tennis live scores "point by point" on FlashScore.ca: Here you'll find the "Point by pointā tab with highlighted lost serves, break points, set- and match points in match details of all ATP and WTA matches. You can find Rijeka Challenger Men scores and brackets on FlashScore.ca Rijeka Challenger Men page, or click on the tennis scores page to see all today's tennis scores. |
(** This file extends the HeapLang program logic with some derived laws (not
using the lifting lemmas) about arrays and prophecies.
For utility functions on arrays (e.g., freeing/copying an array), see
[heap_lang.lib.array]. *)
From stdpp Require Import fin_maps.
From iris.bi Require Import lib.fractional.
From iris.proofmode Require Import tactics.
From iris.heap_lang Require Export primitive_laws.
From iris.heap_lang Require Import tactics notation.
From iris Require Import options.
(** The [array] connective is a version of [mapsto] that works
with lists of values. *)
Definition array `{!heapG Σ} (l : loc) (q : Qp) (vs : list val) : iProp Σ :=
([ā list] i ⦠v ā vs, (l +ā i) ā¦{q} v)%I.
Notation "l ā¦ā{ q } vs" := (array l q vs)
(at level 20, q at level 50, format "l ā¦ā{ q } vs") : bi_scope.
Notation "l ā¦ā vs" := (array l 1 vs)
(at level 20, format "l ā¦ā vs") : bi_scope.
(** We have [FromSep] and [IntoSep] instances to split the fraction (via the
[AsFractional] instance below), but not for splitting the list, as that would
lead to overlapping instances. *)
Section lifting.
Context `{!heapG Σ}.
Implicit Types P Q : iProp Σ.
Implicit Types Φ : val ā iProp Ī£.
Implicit Types Ļ : state.
Implicit Types v : val.
Implicit Types vs : list val.
Implicit Types q : Qp.
Implicit Types l : loc.
Implicit Types sz off : nat.
Global Instance array_timeless l q vs : Timeless (array l q vs) := _.
Global Instance array_fractional l vs : Fractional (Ī» q, l ā¦ā{q} vs)%I := _.
Global Instance array_as_fractional l q vs :
AsFractional (l ā¦ā{q} vs) (Ī» q, l ā¦ā{q} vs)%I q.
Proof. split; done || apply _. Qed.
Lemma array_nil l q : l ā¦ā{q} [] ā£ā¢ emp.
Proof. by rewrite /array. Qed.
Lemma array_singleton l q v : l ā¦ā{q} [v] ā£ā¢ l ā¦{q} v.
Proof. by rewrite /array /= right_id loc_add_0. Qed.
Lemma array_app l q vs ws :
l ā¦ā{q} (vs ++ ws) ā£ā¢ l ā¦ā{q} vs ā (l +ā length vs) ā¦ā{q} ws.
Proof.
rewrite /array big_sepL_app.
setoid_rewrite Nat2Z.inj_add.
by setoid_rewrite loc_add_assoc.
Qed.
Lemma array_cons l q v vs : l ā¦ā{q} (v :: vs) ā£ā¢ l ā¦{q} v ā (l +ā 1) ā¦ā{q} vs.
Proof.
rewrite /array big_sepL_cons loc_add_0.
setoid_rewrite loc_add_assoc.
setoid_rewrite Nat2Z.inj_succ.
by setoid_rewrite Z.add_1_l.
Qed.
Global Instance array_cons_frame l q v vs R Q :
Frame false R (l ā¦{q} v ā (l +ā 1) ā¦ā{q} vs) Q ā
Frame false R (l ā¦ā{q} (v :: vs)) Q.
Proof. by rewrite /Frame array_cons. Qed.
Lemma update_array l q vs off v :
vs !! off = Some v ā
⢠l ā¦ā{q} vs -ā ((l +ā off) ā¦{q} v ā ā v', (l +ā off) ā¦{q} v' -ā l ā¦ā{q} <[off:=v']>vs).
Proof.
iIntros (Hlookup) "Hl".
rewrite -[X in (l ā¦ā{_} X)%I](take_drop_middle _ off v); last done.
iDestruct (array_app with "Hl") as "[Hl1 Hl]".
iDestruct (array_cons with "Hl") as "[Hl2 Hl3]".
assert (off < length vs) as H by (apply lookup_lt_is_Some; by eexists).
rewrite take_length min_l; last by lia. iFrame "Hl2".
iIntros (w) "Hl2".
clear Hlookup. assert (<[off:=w]> vs !! off = Some w) as Hlookup.
{ apply list_lookup_insert. lia. }
rewrite -[in (l ā¦ā{_} <[off:=w]> vs)%I](take_drop_middle (<[off:=w]> vs) off w Hlookup).
iApply array_app. rewrite take_insert; last by lia. iFrame.
iApply array_cons. rewrite take_length min_l; last by lia. iFrame.
rewrite drop_insert_gt; last by lia. done.
Qed.
(** * Rules for allocation *)
Lemma mapsto_seq_array l q v n :
([ā list] i ā seq 0 n, (l +ā (i : nat)) ā¦{q} v) -ā
l ā¦ā{q} replicate n v.
Proof.
rewrite /array. iInduction n as [|n'] "IH" forall (l); simpl.
{ done. }
iIntros "[$ Hl]". rewrite -fmap_S_seq big_sepL_fmap.
setoid_rewrite Nat2Z.inj_succ. setoid_rewrite <-Z.add_1_l.
setoid_rewrite <-loc_add_assoc. iApply "IH". done.
Qed.
Lemma twp_allocN s E v n :
(0 < n)%Z ā
[[{ True }]] AllocN (Val $ LitV $ LitInt $ n) (Val v) @ s; E
[[{ l, RET LitV (LitLoc l); l ā¦ā replicate (Z.to_nat n) v ā
[ā list] i ā seq 0 (Z.to_nat n), meta_token (l +ā (i : nat)) ⤠}]].
Proof.
iIntros (Hzs Φ) "_ HΦ". iApply twp_allocN_seq; [done..|].
iIntros (l) "Hlm". iApply "HΦ".
iDestruct (big_sepL_sep with "Hlm") as "[Hl $]".
by iApply mapsto_seq_array.
Qed.
Lemma wp_allocN s E v n :
(0 < n)%Z ā
{{{ True }}} AllocN (Val $ LitV $ LitInt $ n) (Val v) @ s; E
{{{ l, RET LitV (LitLoc l); l ā¦ā replicate (Z.to_nat n) v ā
[ā list] i ā seq 0 (Z.to_nat n), meta_token (l +ā (i : nat)) ⤠}}}.
Proof.
iIntros (? Φ) "_ HΦ". iApply (twp_wp_step with "HΦ").
iApply twp_allocN; [auto..|]; iIntros (l) "H HΦ". by iApply "HΦ".
Qed.
Lemma twp_allocN_vec s E v n :
(0 < n)%Z ā
[[{ True }]]
AllocN #n v @ s ; E
[[{ l, RET #l; l ā¦ā vreplicate (Z.to_nat n) v ā
[ā list] i ā seq 0 (Z.to_nat n), meta_token (l +ā (i : nat)) ⤠}]].
Proof.
iIntros (Hzs Φ) "_ HΦ". iApply twp_allocN; [ lia | done | .. ].
iIntros (l) "[Hl Hm]". iApply "HΦ". rewrite vec_to_list_replicate. iFrame.
Qed.
Lemma wp_allocN_vec s E v n :
(0 < n)%Z ā
{{{ True }}}
AllocN #n v @ s ; E
{{{ l, RET #l; l ā¦ā vreplicate (Z.to_nat n) v ā
[ā list] i ā seq 0 (Z.to_nat n), meta_token (l +ā (i : nat)) ⤠}}}.
Proof.
iIntros (? Φ) "_ HΦ". iApply (twp_wp_step with "HΦ").
iApply twp_allocN_vec; [auto..|]; iIntros (l) "H HΦ". by iApply "HΦ".
Qed.
(** * Rules for accessing array elements *)
Lemma twp_load_offset s E l q off vs v :
vs !! off = Some v ā
[[{ l ā¦ā{q} vs }]] ! #(l +ā off) @ s; E [[{ RET v; l ā¦ā{q} vs }]].
Proof.
iIntros (Hlookup Φ) "Hl HΦ".
iDestruct (update_array l _ _ _ _ Hlookup with "Hl") as "[Hl1 Hl2]".
iApply (twp_load with "Hl1"). iIntros "Hl1". iApply "HΦ".
iDestruct ("Hl2" $! v) as "Hl2". rewrite list_insert_id; last done.
iApply "Hl2". iApply "Hl1".
Qed.
Lemma wp_load_offset s E l q off vs v :
vs !! off = Some v ā
{{{ ā· l ā¦ā{q} vs }}} ! #(l +ā off) @ s; E {{{ RET v; l ā¦ā{q} vs }}}.
Proof.
iIntros (? Φ) ">H HΦ". iApply (twp_wp_step with "HΦ").
iApply (twp_load_offset with "H"); [eauto..|]; iIntros "H HΦ". by iApply "HΦ".
Qed.
Lemma twp_load_offset_vec s E l q sz (off : fin sz) (vs : vec val sz) :
[[{ l ā¦ā{q} vs }]] ! #(l +ā off) @ s; E [[{ RET vs !!! off; l ā¦ā{q} vs }]].
Proof. apply twp_load_offset. by apply vlookup_lookup. Qed.
Lemma wp_load_offset_vec s E l q sz (off : fin sz) (vs : vec val sz) :
{{{ ā· l ā¦ā{q} vs }}} ! #(l +ā off) @ s; E {{{ RET vs !!! off; l ā¦ā{q} vs }}}.
Proof. apply wp_load_offset. by apply vlookup_lookup. Qed.
Lemma twp_store_offset s E l off vs v :
is_Some (vs !! off) ā
[[{ l ā¦ā vs }]] #(l +ā off) <- v @ s; E [[{ RET #(); l ā¦ā <[off:=v]> vs }]].
Proof.
iIntros ([w Hlookup] Φ) "Hl HΦ".
iDestruct (update_array l _ _ _ _ Hlookup with "Hl") as "[Hl1 Hl2]".
iApply (twp_store with "Hl1"). iIntros "Hl1".
iApply "HΦ". iApply "Hl2". iApply "Hl1".
Qed.
Lemma wp_store_offset s E l off vs v :
is_Some (vs !! off) ā
{{{ ā· l ā¦ā vs }}} #(l +ā off) <- v @ s; E {{{ RET #(); l ā¦ā <[off:=v]> vs }}}.
Proof.
iIntros (? Φ) ">H HΦ". iApply (twp_wp_step with "HΦ").
iApply (twp_store_offset with "H"); [eauto..|]; iIntros "H HΦ". by iApply "HΦ".
Qed.
Lemma twp_store_offset_vec s E l sz (off : fin sz) (vs : vec val sz) v :
[[{ l ā¦ā vs }]] #(l +ā off) <- v @ s; E [[{ RET #(); l ā¦ā vinsert off v vs }]].
Proof.
setoid_rewrite vec_to_list_insert. apply twp_store_offset.
eexists. by apply vlookup_lookup.
Qed.
Lemma wp_store_offset_vec s E l sz (off : fin sz) (vs : vec val sz) v :
{{{ ā· l ā¦ā vs }}} #(l +ā off) <- v @ s; E {{{ RET #(); l ā¦ā vinsert off v vs }}}.
Proof.
iIntros (Φ) ">H HΦ". iApply (twp_wp_step with "HΦ").
iApply (twp_store_offset_vec with "H"); [eauto..|]; iIntros "H HΦ". by iApply "HΦ".
Qed.
Lemma twp_cmpxchg_suc_offset s E l off vs v' v1 v2 :
vs !! off = Some v' ā
v' = v1 ā
vals_compare_safe v' v1 ā
[[{ l ā¦ā vs }]]
CmpXchg #(l +ā off) v1 v2 @ s; E
[[{ RET (v', #true); l ā¦ā <[off:=v2]> vs }]].
Proof.
iIntros (Hlookup ?? Φ) "Hl HΦ".
iDestruct (update_array l _ _ _ _ Hlookup with "Hl") as "[Hl1 Hl2]".
iApply (twp_cmpxchg_suc with "Hl1"); [done..|].
iIntros "Hl1". iApply "HΦ". iApply "Hl2". iApply "Hl1".
Qed.
Lemma wp_cmpxchg_suc_offset s E l off vs v' v1 v2 :
vs !! off = Some v' ā
v' = v1 ā
vals_compare_safe v' v1 ā
{{{ ā· l ā¦ā vs }}}
CmpXchg #(l +ā off) v1 v2 @ s; E
{{{ RET (v', #true); l ā¦ā <[off:=v2]> vs }}}.
Proof.
iIntros (??? Φ) ">H HΦ". iApply (twp_wp_step with "HΦ").
iApply (twp_cmpxchg_suc_offset with "H"); [eauto..|]; iIntros "H HΦ". by iApply "HΦ".
Qed.
Lemma twp_cmpxchg_suc_offset_vec s E l sz (off : fin sz) (vs : vec val sz) v1 v2 :
vs !!! off = v1 ā
vals_compare_safe (vs !!! off) v1 ā
[[{ l ā¦ā vs }]]
CmpXchg #(l +ā off) v1 v2 @ s; E
[[{ RET (vs !!! off, #true); l ā¦ā vinsert off v2 vs }]].
Proof.
intros. setoid_rewrite vec_to_list_insert. eapply twp_cmpxchg_suc_offset=> //.
by apply vlookup_lookup.
Qed.
Lemma wp_cmpxchg_suc_offset_vec s E l sz (off : fin sz) (vs : vec val sz) v1 v2 :
vs !!! off = v1 ā
vals_compare_safe (vs !!! off) v1 ā
{{{ ā· l ā¦ā vs }}}
CmpXchg #(l +ā off) v1 v2 @ s; E
{{{ RET (vs !!! off, #true); l ā¦ā vinsert off v2 vs }}}.
Proof.
iIntros (?? Φ) ">H HΦ". iApply (twp_wp_step with "HΦ").
iApply (twp_cmpxchg_suc_offset_vec with "H"); [eauto..|]; iIntros "H HΦ". by iApply "HΦ".
Qed.
Lemma twp_cmpxchg_fail_offset s E l q off vs v0 v1 v2 :
vs !! off = Some v0 ā
v0 ā v1 ā
vals_compare_safe v0 v1 ā
[[{ l ā¦ā{q} vs }]]
CmpXchg #(l +ā off) v1 v2 @ s; E
[[{ RET (v0, #false); l ā¦ā{q} vs }]].
Proof.
iIntros (Hlookup HNEq Hcmp Φ) "Hl HΦ".
iDestruct (update_array l _ _ _ _ Hlookup with "Hl") as "[Hl1 Hl2]".
iApply (twp_cmpxchg_fail with "Hl1"); first done.
{ destruct Hcmp; by [ left | right ]. }
iIntros "Hl1". iApply "HΦ". iDestruct ("Hl2" $! v0) as "Hl2".
rewrite list_insert_id; last done. iApply "Hl2". iApply "Hl1".
Qed.
Lemma wp_cmpxchg_fail_offset s E l q off vs v0 v1 v2 :
vs !! off = Some v0 ā
v0 ā v1 ā
vals_compare_safe v0 v1 ā
{{{ ā· l ā¦ā{q} vs }}}
CmpXchg #(l +ā off) v1 v2 @ s; E
{{{ RET (v0, #false); l ā¦ā{q} vs }}}.
Proof.
iIntros (??? Φ) ">H HΦ". iApply (twp_wp_step with "HΦ").
iApply (twp_cmpxchg_fail_offset with "H"); [eauto..|]; iIntros "H HΦ". by iApply "HΦ".
Qed.
Lemma twp_cmpxchg_fail_offset_vec s E l q sz (off : fin sz) (vs : vec val sz) v1 v2 :
vs !!! off ā v1 ā
vals_compare_safe (vs !!! off) v1 ā
[[{ l ā¦ā{q} vs }]]
CmpXchg #(l +ā off) v1 v2 @ s; E
[[{ RET (vs !!! off, #false); l ā¦ā{q} vs }]].
Proof. intros. eapply twp_cmpxchg_fail_offset=> //. by apply vlookup_lookup. Qed.
Lemma wp_cmpxchg_fail_offset_vec s E l q sz (off : fin sz) (vs : vec val sz) v1 v2 :
vs !!! off ā v1 ā
vals_compare_safe (vs !!! off) v1 ā
{{{ ā· l ā¦ā{q} vs }}}
CmpXchg #(l +ā off) v1 v2 @ s; E
{{{ RET (vs !!! off, #false); l ā¦ā{q} vs }}}.
Proof. intros. eapply wp_cmpxchg_fail_offset=> //. by apply vlookup_lookup. Qed.
Lemma twp_faa_offset s E l off vs (i1 i2 : Z) :
vs !! off = Some #i1 ā
[[{ l ā¦ā vs }]] FAA #(l +ā off) #i2 @ s; E
[[{ RET LitV (LitInt i1); l ā¦ā <[off:=#(i1 + i2)]> vs }]].
Proof.
iIntros (Hlookup Φ) "Hl HΦ".
iDestruct (update_array l _ _ _ _ Hlookup with "Hl") as "[Hl1 Hl2]".
iApply (twp_faa with "Hl1").
iIntros "Hl1". iApply "HΦ". iApply "Hl2". iApply "Hl1".
Qed.
Lemma wp_faa_offset s E l off vs (i1 i2 : Z) :
vs !! off = Some #i1 ā
{{{ ā· l ā¦ā vs }}} FAA #(l +ā off) #i2 @ s; E
{{{ RET LitV (LitInt i1); l ā¦ā <[off:=#(i1 + i2)]> vs }}}.
Proof.
iIntros (? Φ) ">H HΦ". iApply (twp_wp_step with "HΦ").
iApply (twp_faa_offset with "H"); [eauto..|]; iIntros "H HΦ". by iApply "HΦ".
Qed.
Lemma twp_faa_offset_vec s E l sz (off : fin sz) (vs : vec val sz) (i1 i2 : Z) :
vs !!! off = #i1 ā
[[{ l ā¦ā vs }]] FAA #(l +ā off) #i2 @ s; E
[[{ RET LitV (LitInt i1); l ā¦ā vinsert off #(i1 + i2) vs }]].
Proof.
intros. setoid_rewrite vec_to_list_insert. apply twp_faa_offset=> //.
by apply vlookup_lookup.
Qed.
Lemma wp_faa_offset_vec s E l sz (off : fin sz) (vs : vec val sz) (i1 i2 : Z) :
vs !!! off = #i1 ā
{{{ ā· l ā¦ā vs }}} FAA #(l +ā off) #i2 @ s; E
{{{ RET LitV (LitInt i1); l ā¦ā vinsert off #(i1 + i2) vs }}}.
Proof.
iIntros (? Φ) ">H HΦ". iApply (twp_wp_step with "HΦ").
iApply (twp_faa_offset_vec with "H"); [eauto..|]; iIntros "H HΦ". by iApply "HΦ".
Qed.
(** Derived prophecy laws *)
(** Lemmas for some particular expression inside the [Resolve]. *)
Lemma wp_resolve_proph s E (p : proph_id) (pvs : list (val * val)) v :
{{{ proph p pvs }}}
ResolveProph (Val $ LitV $ LitProphecy p) (Val v) @ s; E
{{{ pvs', RET (LitV LitUnit); āpvs = (LitV LitUnit, v)::pvs'ā ā proph p pvs' }}}.
Proof.
iIntros (Φ) "Hp HΦ". iApply (wp_resolve with "Hp"); first done.
iApply lifting.wp_pure_step_later=> //=. iApply wp_value.
iIntros "!>" (vs') "HEq Hp". iApply "HΦ". iFrame.
Qed.
Lemma wp_resolve_cmpxchg_suc s E l (p : proph_id) (pvs : list (val * val)) v1 v2 v :
vals_compare_safe v1 v1 ā
{{{ proph p pvs ā ā· l ⦠v1 }}}
Resolve (CmpXchg #l v1 v2) #p v @ s; E
{{{ RET (v1, #true) ; ā pvs', āpvs = ((v1, #true)%V, v)::pvs'ā ā proph p pvs' ā l ⦠v2 }}}.
Proof.
iIntros (Hcmp Φ) "[Hp Hl] HΦ".
iApply (wp_resolve with "Hp"); first done.
assert (val_is_unboxed v1) as Hv1; first by destruct Hcmp.
iApply (wp_cmpxchg_suc with "Hl"); [done..|]. iIntros "!> Hl".
iIntros (pvs' ->) "Hp". iApply "HΦ". eauto with iFrame.
Qed.
Lemma wp_resolve_cmpxchg_fail s E l (p : proph_id) (pvs : list (val * val)) q v' v1 v2 v :
v' ā v1 ā vals_compare_safe v' v1 ā
{{{ proph p pvs ā ā· l ā¦{q} v' }}}
Resolve (CmpXchg #l v1 v2) #p v @ s; E
{{{ RET (v', #false) ; ā pvs', āpvs = ((v', #false)%V, v)::pvs'ā ā proph p pvs' ā l ā¦{q} v' }}}.
Proof.
iIntros (NEq Hcmp Φ) "[Hp Hl] HΦ".
iApply (wp_resolve with "Hp"); first done.
iApply (wp_cmpxchg_fail with "Hl"); [done..|]. iIntros "!> Hl".
iIntros (pvs' ->) "Hp". iApply "HΦ". eauto with iFrame.
Qed.
End lifting.
Typeclasses Opaque array.
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
import Control.Applicative
import Control.Monad
import Control.Monad.Random
import Control.Monad.Trans.Except
import qualified Data.Attoparsec.Text as A
import Data.List ( foldl' )
#if ! MIN_VERSION_base(4,13,0)
import Data.Semigroup ( (<>) )
#endif
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Vector.Storable as V
import Numeric.LinearAlgebra ( maxIndex )
import qualified Numeric.LinearAlgebra.Static as SA
import Options.Applicative
import Grenade
import Grenade.Utils.OneHot
-- It's logistic regression!
--
-- This network is used to show how we can embed a Network as a layer in the larger MNIST
-- type.
type FL i o =
Network
'[ FullyConnected i o, Logit ]
'[ 'D1 i, 'D1 o, 'D1 o ]
-- The definition of our convolutional neural network.
-- In the type signature, we have a type level list of shapes which are passed between the layers.
-- One can see that the images we are inputing are two dimensional with 28 * 28 pixels.
-- It's important to keep the type signatures, as there's many layers which can "squeeze" into the gaps
-- between the shapes, so inference can't do it all for us.
-- With the mnist data from Kaggle normalised to doubles between 0 and 1, learning rate of 0.01 and 15 iterations,
-- this network should get down to about a 1.3% error rate.
--
-- /NOTE:/ This model is actually too complex for MNIST, and one should use the type given in the readme instead.
-- This one is just here to demonstrate Inception layers in use.
--
type MNIST =
Network
'[ Reshape,
Concat ('D3 28 28 1) Trivial ('D3 28 28 14) (InceptionMini 28 28 1 5 9),
Pooling 2 2 2 2, Relu,
Concat ('D3 14 14 3) (Convolution 15 3 1 1 1 1) ('D3 14 14 15) (InceptionMini 14 14 15 5 10), Crop 1 1 1 1, Pooling 3 3 3 3, Relu,
Reshape, FL 288 80, FL 80 10 ]
'[ 'D2 28 28, 'D3 28 28 1,
'D3 28 28 15, 'D3 14 14 15, 'D3 14 14 15, 'D3 14 14 18,
'D3 12 12 18, 'D3 4 4 18, 'D3 4 4 18,
'D1 288, 'D1 80, 'D1 10 ]
randomMnist :: MonadRandom m => m MNIST
randomMnist = randomNetwork
convTest :: Int -> FilePath -> FilePath -> LearningParameters -> ExceptT String IO ()
convTest iterations trainFile validateFile rate = do
net0 <- lift randomMnist
trainData <- readMNIST trainFile
validateData <- readMNIST validateFile
lift $ foldM_ (runIteration trainData validateData) net0 [1..iterations]
where
trainEach rate' !network (i, o) = train rate' network i o
runIteration trainRows validateRows net i = do
let trained' = foldl' (trainEach ( rate { learningRate = learningRate rate * 0.9 ^ i} )) net trainRows
let res = fmap (\(rowP,rowL) -> (rowL,) $ runNet trained' rowP) validateRows
let res' = fmap (\(S1D label, S1D prediction) -> (maxIndex (SA.extract label), maxIndex (SA.extract prediction))) res
print trained'
putStrLn $ "Iteration " ++ show i ++ ": " ++ show (length (filter ((==) <$> fst <*> snd) res')) ++ " of " ++ show (length res')
return trained'
data MnistOpts = MnistOpts FilePath FilePath Int LearningParameters
mnist' :: Parser MnistOpts
mnist' = MnistOpts <$> argument str (metavar "TRAIN")
<*> argument str (metavar "VALIDATE")
<*> option auto (long "iterations" <> short 'i' <> value 15)
<*> (LearningParameters
<$> option auto (long "train_rate" <> short 'r' <> value 0.01)
<*> option auto (long "momentum" <> value 0.9)
<*> option auto (long "l2" <> value 0.0005)
)
main :: IO ()
main = do
MnistOpts mnist vali iter rate <- execParser (info (mnist' <**> helper) idm)
putStrLn "Training convolutional neural network..."
res <- runExceptT $ convTest iter mnist vali rate
case res of
Right () -> pure ()
Left err -> putStrLn err
readMNIST :: FilePath -> ExceptT String IO [(S ('D2 28 28), S ('D1 10))]
readMNIST mnist = ExceptT $ do
mnistdata <- T.readFile mnist
return $ traverse (A.parseOnly parseMNIST) (T.lines mnistdata)
parseMNIST :: A.Parser (S ('D2 28 28), S ('D1 10))
parseMNIST = do
Just lab <- oneHot <$> A.decimal
pixels <- many (A.char ',' >> A.double)
image <- maybe (fail "Parsed row was of an incorrect size") pure (fromStorable . V.fromList $ pixels)
return (image, lab)
|
import sys
sys.path.append('../')
import cv2
import numpy as np
from rcnnpose.estimator import BodyPoseEstimator
from rcnnpose.utils import draw_body_connections, draw_keypoints, draw_masks
estimator = BodyPoseEstimator(pretrained=True)
image_src = cv2.imread('media/example.jpg')
pred_dict = estimator(image_src, masks=True, keypoints=True)
masks = estimator.get_masks(pred_dict['estimator_m'], score_threshold=0.99)
keypoints = estimator.get_keypoints(pred_dict['estimator_k'], score_threshold=0.99)
image_dst = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
image_dst = cv2.merge([image_dst] * 3)
overlay_m = draw_masks(image_dst, masks, color=(0, 255, 0), alpha=0.5)
overlay_k = draw_body_connections(image_src, keypoints, thickness=4, alpha=0.7)
overlay_k = draw_keypoints(overlay_k, keypoints, radius=5, alpha=0.8)
image_dst = np.hstack((image_src, overlay_m, overlay_k))
while True:
cv2.imshow('Image Demo', image_dst)
if cv2.waitKey(1) & 0xff == 27: # exit if pressed `ESC`
break
cv2.destroyAllWindows()
|
#pragma once
#include <api/ApiMetadata.hpp>
#include <client/Client.hpp>
#include <rpc/RpcServer.hpp>
#include <fc/variant.hpp>
#include <boost/optional.hpp>
namespace thinkyoung {
namespace rpc {
class RpcServer;
typedef std::shared_ptr<RpcServer> RpcServerPtr;
}
}
#define CLI_PROMPT_SUFFIX ">>> "
namespace thinkyoung {
namespace cli {
using namespace thinkyoung::client;
using namespace thinkyoung::rpc;
using namespace thinkyoung::wallet;
namespace detail { class CliImpl; }
extern bool FILTER_OUTPUT_FOR_TESTS;
class Cli
{
public:
Cli(thinkyoung::client::Client* client,
std::istream* command_script = nullptr,
std::ostream* output_stream = nullptr);
virtual ~Cli();
void start();
void set_input_stream_log(boost::optional<std::ostream&> input_stream_log);
void set_daemon_mode(bool enable_daemon_mode);
void display_status_message(const std::string& message);
void display_message(const std::string& message);
void process_commands(std::istream* input_stream);
void enable_output(bool enable_output);
void filter_output_for_tests(bool enable_flag);
//Parse and execute a command line. Returns false if line is a quit command.
bool execute_command_line(const std::string& line, std::ostream* output = nullptr);
void confirm_and_broadcast(SignedTransaction& tx);
// hooks to implement custom behavior for interactive command, if the default json-style behavior is undesirable
virtual fc::variant parse_argument_of_known_type(fc::buffered_istream& argument_stream,
const thinkyoung::api::MethodData& method_data,
unsigned parameter_index);
virtual fc::variants parse_unrecognized_interactive_command(fc::buffered_istream& argument_stream,
const std::string& command);
virtual fc::variants parse_recognized_interactive_command(fc::buffered_istream& argument_stream,
const thinkyoung::api::MethodData& method_data);
virtual fc::variants parse_interactive_command(fc::buffered_istream& argument_stream, const std::string& command);
virtual fc::variant execute_interactive_command(const std::string& command, const fc::variants& arguments);
virtual void format_and_print_result(const std::string& command,
const fc::variants& arguments,
const fc::variant& result);
private:
std::unique_ptr<detail::CliImpl> my;
};
typedef std::shared_ptr<Cli> CliPtr;
string get_line(
std::istream* input_stream,
std::ostream* out,
const string& prompt = CLI_PROMPT_SUFFIX,
bool no_echo = false,
fc::thread* cin_thread = nullptr,
bool saved_out = false,
std::ostream* input_stream_log = nullptr
);
}
} // thinkyoung::cli
|
(* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. *)
(* Copyright (C) 2018ā2020 ANSSI *)
From ExtLib Require Import StateMonad MonadTrans.
#[local] Existing Instance Monad_stateT.
From FreeSpec.Core Require Import Interface Semantics Contract.
Notation instrument Ī© i := (stateT Ī© (state (semantics i))).
Definition interface_to_instrument `{MayProvide ix i} `(c : contract i Ī©)
: ix ~> instrument Ī© ix :=
fun a e =>
let* x := lift $ interface_to_state _ e in
modify (fun Ļ => gen_witness_update c Ļ e x);;
ret x.
Definition to_instrument `{MayProvide ix i} `(c : contract i Ī©)
: impure ix ~> instrument Ī© ix :=
impure_lift $ interface_to_instrument c.
Arguments to_instrument {ix i _ Ω} (c) {α}.
Definition instrument_to_state {i} `(Ļ : Ī©) : instrument Ī© i ~> state (semantics i) :=
fun a instr => fst <$> runStateT instr Ļ.
Arguments instrument_to_state {i Ī©} (Ļ) {α}.
|
# Load the Adjust client
library(httr)
library(data.table)
library(adjust)
# Set Adjust user and app credentials
prepare_adjust <- function(usertoken, apptoken) {
adjust.setup(user.token=usertoken, app.token=apptoken)
} |
{-# OPTIONS --safe --warning=error --without-K #-}
open import LogicalFormulae
open import Orders.Total.Definition
open import Orders.Partial.Definition
open import Setoids.Setoids
open import Setoids.Orders.Partial.Definition
open import Setoids.Orders.Total.Definition
open import Functions.Definition
open import Sets.EquivalenceRelations
open import Agda.Primitive using (Level; lzero; lsuc; _ā_)
module Setoids.Orders.Total.Lemmas {a b : _} {A : Set a} {S : Setoid {a} {b} A} {c : _} {_<_ : A ā A ā Set c} {P : SetoidPartialOrder S _<_} (T : SetoidTotalOrder P) where
open SetoidTotalOrder T
open SetoidPartialOrder P
open Setoid S
open Equivalence eq
maxInequalitiesR : {a b c : A} ā (a < b) ā (a < c) ā (a < max b c)
maxInequalitiesR {a} {b} {c} a<b a<c with totality b c
... | inl (inl x) = a<c
... | inl (inr x) = a<b
... | inr x = a<c
minInequalitiesR : {a b c : A} ā (a < b) ā (a < c) ā (a < min b c)
minInequalitiesR {a} {b} {c} a<b a<c with totality b c
... | inl (inl x) = a<b
... | inl (inr x) = a<c
... | inr x = a<b
maxInequalitiesL : {a b c : A} ā (a < c) ā (b < c) ā (max a b < c)
maxInequalitiesL {a} {b} {c} a<b a<c with totality a b
... | inl (inl x) = a<c
... | inl (inr x) = a<b
... | inr x = a<c
minInequalitiesL : {a b c : A} ā (a < c) ā (b < c) ā (min a b < c)
minInequalitiesL {a} {b} {c} a<b a<c with totality a b
... | inl (inl x) = a<b
... | inl (inr x) = a<c
... | inr x = a<b
minLessL : (a b : A) ā min a b <= a
minLessL a b with totality a b
... | inl (inl x) = inr reflexive
... | inl (inr x) = inl x
... | inr x = inr reflexive
minLessR : (a b : A) ā min a b <= b
minLessR a b with totality a b
... | inl (inl x) = inl x
... | inl (inr x) = inr reflexive
... | inr x = inr x
maxGreaterL : (a b : A) ā a <= max a b
maxGreaterL a b with totality a b
... | inl (inl x) = inl x
... | inl (inr x) = inr reflexive
... | inr x = inr x
maxGreaterR : (a b : A) ā b <= max a b
maxGreaterR a b with totality a b
... | inl (inl x) = inr reflexive
... | inl (inr x) = inl x
... | inr x = inr reflexive
|
[GOAL]
R : Type u_1
instā : CommRing R
⢠bernsteinPolynomial ⤠3 2 = 3 * X ^ 2 - 3 * X ^ 3
[PROOFSTEP]
simp [bernsteinPolynomial, choose]
[GOAL]
R : Type u_1
instā : CommRing R
⢠(1 + 1 + 1) * X ^ 2 * (1 - X) = 3 * X ^ 2 - 3 * X ^ 3
[PROOFSTEP]
norm_num
[GOAL]
R : Type u_1
instā : CommRing R
⢠3 * X ^ 2 * (1 - X) = 3 * X ^ 2 - 3 * X ^ 3
[PROOFSTEP]
ring
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
h : n < ν
⢠bernsteinPolynomial R n ν = 0
[PROOFSTEP]
simp [bernsteinPolynomial, Nat.choose_eq_zero_of_lt h]
[GOAL]
R : Type u_1
instā¹ : CommRing R
S : Type u_2
instā : CommRing S
f : R ā+* S
n ν : ā
⢠Polynomial.map f (bernsteinPolynomial R n ν) = bernsteinPolynomial S n ν
[PROOFSTEP]
simp [bernsteinPolynomial]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
h : ν ⤠n
⢠Polynomial.comp (bernsteinPolynomial R n ν) (1 - X) = bernsteinPolynomial R n (n - ν)
[PROOFSTEP]
simp [bernsteinPolynomial, h, tsub_tsub_assoc, mul_right_comm]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
h : ν ⤠n
⢠bernsteinPolynomial R n ν = Polynomial.comp (bernsteinPolynomial R n (n - ν)) (1 - X)
[PROOFSTEP]
simp [ā flip _ _ _ h, Polynomial.comp_assoc]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠Polynomial.eval 0 (bernsteinPolynomial R n ν) = if ν = 0 then 1 else 0
[PROOFSTEP]
rw [bernsteinPolynomial]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠Polynomial.eval 0 (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)) = if ν = 0 then 1 else 0
[PROOFSTEP]
split_ifs with h
[GOAL]
case pos
R : Type u_1
instā : CommRing R
n ν : ā
h : ν = 0
⢠Polynomial.eval 0 (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)) = 1
[PROOFSTEP]
subst h
[GOAL]
case pos
R : Type u_1
instā : CommRing R
n : ā
⢠Polynomial.eval 0 (ā(choose n 0) * X ^ 0 * (1 - X) ^ (n - 0)) = 1
[PROOFSTEP]
simp
[GOAL]
case neg
R : Type u_1
instā : CommRing R
n ν : ā
h : ¬ν = 0
⢠Polynomial.eval 0 (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)) = 0
[PROOFSTEP]
simp [zero_pow (Nat.pos_of_ne_zero h)]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠Polynomial.eval 1 (bernsteinPolynomial R n ν) = if ν = n then 1 else 0
[PROOFSTEP]
rw [bernsteinPolynomial]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠Polynomial.eval 1 (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)) = if ν = n then 1 else 0
[PROOFSTEP]
split_ifs with h
[GOAL]
case pos
R : Type u_1
instā : CommRing R
n ν : ā
h : ν = n
⢠Polynomial.eval 1 (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)) = 1
[PROOFSTEP]
subst h
[GOAL]
case pos
R : Type u_1
instā : CommRing R
ν : ā
⢠Polynomial.eval 1 (ā(choose ν ν) * X ^ ν * (1 - X) ^ (ν - ν)) = 1
[PROOFSTEP]
simp
[GOAL]
case neg
R : Type u_1
instā : CommRing R
n ν : ā
h : ¬ν = n
⢠Polynomial.eval 1 (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)) = 0
[PROOFSTEP]
obtain w | w := (n - ν).eq_zero_or_pos
[GOAL]
case neg.inl
R : Type u_1
instā : CommRing R
n ν : ā
h : ¬ν = n
w : n - ν = 0
⢠Polynomial.eval 1 (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)) = 0
[PROOFSTEP]
simp [Nat.choose_eq_zero_of_lt ((tsub_eq_zero_iff_le.mp w).lt_of_ne (Ne.symm h))]
[GOAL]
case neg.inr
R : Type u_1
instā : CommRing R
n ν : ā
h : ¬ν = n
w : n - ν > 0
⢠Polynomial.eval 1 (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)) = 0
[PROOFSTEP]
simp [zero_pow w]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠āPolynomial.derivative (bernsteinPolynomial R (n + 1) (ν + 1)) =
(ān + 1) * (bernsteinPolynomial R n ν - bernsteinPolynomial R n (ν + 1))
[PROOFSTEP]
rw [bernsteinPolynomial]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠āPolynomial.derivative (ā(choose (n + 1) (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n + 1 - (ν + 1))) =
(ān + 1) * (bernsteinPolynomial R n ν - bernsteinPolynomial R n (ν + 1))
[PROOFSTEP]
suffices
((n + 1).choose (ν + 1) : R[X]) * ((ā(ν + 1 : ā) : R[X]) * X ^ ν) * (1 - X) ^ (n - ν) -
((n + 1).choose (ν + 1) : R[X]) * X ^ (ν + 1) * ((ā(n - ν) : R[X]) * (1 - X) ^ (n - ν - 1)) =
(ā(n + 1) : R[X]) *
((n.choose ν : R[X]) * X ^ ν * (1 - X) ^ (n - ν) -
(n.choose (ν + 1) : R[X]) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1)))
by
simpa [Polynomial.derivative_pow, ā sub_eq_add_neg, Nat.succ_sub_succ_eq_sub, Polynomial.derivative_mul,
Polynomial.derivative_nat_cast, zero_mul, Nat.cast_add, algebraMap.coe_one, Polynomial.derivative_X, mul_one,
zero_add, Polynomial.derivative_sub, Polynomial.derivative_one, zero_sub, mul_neg, Nat.sub_zero,
bernsteinPolynomial, map_add, map_natCast, Nat.cast_one]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
this :
ā(choose (n + 1) (ν + 1)) * (ā(ν + 1) * X ^ ν) * (1 - X) ^ (n - ν) -
ā(choose (n + 1) (ν + 1)) * X ^ (ν + 1) * (ā(n - ν) * (1 - X) ^ (n - ν - 1)) =
ā(n + 1) * (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν) - ā(choose n (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1)))
⢠āPolynomial.derivative (ā(choose (n + 1) (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n + 1 - (ν + 1))) =
(ān + 1) * (bernsteinPolynomial R n ν - bernsteinPolynomial R n (ν + 1))
[PROOFSTEP]
simpa [Polynomial.derivative_pow, ā sub_eq_add_neg, Nat.succ_sub_succ_eq_sub, Polynomial.derivative_mul,
Polynomial.derivative_nat_cast, zero_mul, Nat.cast_add, algebraMap.coe_one, Polynomial.derivative_X, mul_one,
zero_add, Polynomial.derivative_sub, Polynomial.derivative_one, zero_sub, mul_neg, Nat.sub_zero, bernsteinPolynomial,
map_add, map_natCast, Nat.cast_one]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(choose (n + 1) (ν + 1)) * (ā(ν + 1) * X ^ ν) * (1 - X) ^ (n - ν) -
ā(choose (n + 1) (ν + 1)) * X ^ (ν + 1) * (ā(n - ν) * (1 - X) ^ (n - ν - 1)) =
ā(n + 1) * (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν) - ā(choose n (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1)))
[PROOFSTEP]
conv_rhs =>
rw [mul_sub]
-- We'll prove the two terms match up separately.
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
| ā(n + 1) * (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν) - ā(choose n (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1)))
[PROOFSTEP]
rw [mul_sub]
-- We'll prove the two terms match up separately.
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
| ā(n + 1) * (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν) - ā(choose n (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1)))
[PROOFSTEP]
rw [mul_sub]
-- We'll prove the two terms match up separately.
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
| ā(n + 1) * (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν) - ā(choose n (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1)))
[PROOFSTEP]
rw [mul_sub]
-- We'll prove the two terms match up separately.
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(choose (n + 1) (ν + 1)) * (ā(ν + 1) * X ^ ν) * (1 - X) ^ (n - ν) -
ā(choose (n + 1) (ν + 1)) * X ^ (ν + 1) * (ā(n - ν) * (1 - X) ^ (n - ν - 1)) =
ā(n + 1) * (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)) -
ā(n + 1) * (ā(choose n (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1)))
[PROOFSTEP]
refine' congr (congr_arg Sub.sub _) _
[GOAL]
case refine'_1
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(choose (n + 1) (ν + 1)) * (ā(ν + 1) * X ^ ν) * (1 - X) ^ (n - ν) =
ā(n + 1) * (ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν))
[PROOFSTEP]
simp only [ā mul_assoc]
[GOAL]
case refine'_1
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(choose (n + 1) (ν + 1)) * ā(ν + 1) * X ^ ν * (1 - X) ^ (n - ν) =
ā(n + 1) * ā(choose n ν) * X ^ ν * (1 - X) ^ (n - ν)
[PROOFSTEP]
refine' congr (congr_arg (Ā· * Ā·) (congr (congr_arg (Ā· * Ā·) _) rfl)) rfl
[GOAL]
case refine'_1
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(choose (n + 1) (ν + 1)) * ā(ν + 1) = ā(n + 1) * ā(choose n ν)
[PROOFSTEP]
exact_mod_cast congr_arg (fun m : ā => (m : R[X])) (Nat.succ_mul_choose_eq n ν).symm
[GOAL]
case refine'_2
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(choose (n + 1) (ν + 1)) * X ^ (ν + 1) * (ā(n - ν) * (1 - X) ^ (n - ν - 1)) =
ā(n + 1) * (ā(choose n (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1)))
[PROOFSTEP]
rw [ā tsub_add_eq_tsub_tsub, ā mul_assoc, ā mul_assoc]
[GOAL]
case refine'_2
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(choose (n + 1) (ν + 1)) * X ^ (ν + 1) * ā(n - ν) * (1 - X) ^ (n - (ν + 1)) =
ā(n + 1) * (ā(choose n (ν + 1)) * X ^ (ν + 1)) * (1 - X) ^ (n - (ν + 1))
[PROOFSTEP]
congr 1
[GOAL]
case refine'_2.e_a
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(choose (n + 1) (ν + 1)) * X ^ (ν + 1) * ā(n - ν) = ā(n + 1) * (ā(choose n (ν + 1)) * X ^ (ν + 1))
[PROOFSTEP]
rw [mul_comm, ā mul_assoc, ā mul_assoc]
[GOAL]
case refine'_2.e_a
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(n - ν) * ā(choose (n + 1) (ν + 1)) * X ^ (ν + 1) = ā(n + 1) * ā(choose n (ν + 1)) * X ^ (ν + 1)
[PROOFSTEP]
congr 1
[GOAL]
case refine'_2.e_a.e_a
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā(n - ν) * ā(choose (n + 1) (ν + 1)) = ā(n + 1) * ā(choose n (ν + 1))
[PROOFSTEP]
norm_cast
[GOAL]
case refine'_2.e_a.e_a
R : Type u_1
instā : CommRing R
n ν : ā
⢠ā((n - ν) * choose (n + 1) (ν + 1)) = ā((n + 1) * choose n (ν + 1))
[PROOFSTEP]
congr 1
[GOAL]
case refine'_2.e_a.e_a.e_a
R : Type u_1
instā : CommRing R
n ν : ā
⢠(n - ν) * choose (n + 1) (ν + 1) = (n + 1) * choose n (ν + 1)
[PROOFSTEP]
convert (Nat.choose_mul_succ_eq n (ν + 1)).symm using 1
[GOAL]
case h.e'_2
R : Type u_1
instā : CommRing R
n ν : ā
⢠(n - ν) * choose (n + 1) (ν + 1) = choose (n + 1) (ν + 1) * (n + 1 - (ν + 1))
[PROOFSTEP]
rw [mul_comm, Nat.succ_sub_succ_eq_sub]
[GOAL]
case h.e'_3
R : Type u_1
instā : CommRing R
n ν : ā
⢠(n + 1) * choose n (ν + 1) = choose n (ν + 1) * (n + 1)
[PROOFSTEP]
apply mul_comm
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠āPolynomial.derivative (bernsteinPolynomial R n (ν + 1)) =
ān * (bernsteinPolynomial R (n - 1) ν - bernsteinPolynomial R (n - 1) (ν + 1))
[PROOFSTEP]
cases n
[GOAL]
case zero
R : Type u_1
instā : CommRing R
ν : ā
⢠āPolynomial.derivative (bernsteinPolynomial R Nat.zero (ν + 1)) =
āNat.zero * (bernsteinPolynomial R (Nat.zero - 1) ν - bernsteinPolynomial R (Nat.zero - 1) (ν + 1))
[PROOFSTEP]
simp [bernsteinPolynomial]
[GOAL]
case succ
R : Type u_1
instā : CommRing R
ν nā : ā
⢠āPolynomial.derivative (bernsteinPolynomial R (Nat.succ nā) (ν + 1)) =
ā(Nat.succ nā) * (bernsteinPolynomial R (Nat.succ nā - 1) ν - bernsteinPolynomial R (Nat.succ nā - 1) (ν + 1))
[PROOFSTEP]
rw [Nat.cast_succ]
[GOAL]
case succ
R : Type u_1
instā : CommRing R
ν nā : ā
⢠āPolynomial.derivative (bernsteinPolynomial R (Nat.succ nā) (ν + 1)) =
(ānā + 1) * (bernsteinPolynomial R (Nat.succ nā - 1) ν - bernsteinPolynomial R (Nat.succ nā - 1) (ν + 1))
[PROOFSTEP]
apply derivative_succ_aux
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
⢠āPolynomial.derivative (bernsteinPolynomial R n 0) = -ān * bernsteinPolynomial R (n - 1) 0
[PROOFSTEP]
simp [bernsteinPolynomial, Polynomial.derivative_pow]
[GOAL]
R : Type u_1
instā : CommRing R
n ν k : ā
⢠k < ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n ν)) = 0
[PROOFSTEP]
cases' ν with ν
[GOAL]
case zero
R : Type u_1
instā : CommRing R
n k : ā
⢠k < Nat.zero ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n Nat.zero)) = 0
[PROOFSTEP]
rintro āØā©
[GOAL]
case succ
R : Type u_1
instā : CommRing R
n k ν : ā
⢠k < Nat.succ ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n (Nat.succ ν))) = 0
[PROOFSTEP]
rw [Nat.lt_succ_iff]
[GOAL]
case succ
R : Type u_1
instā : CommRing R
n k ν : ā
⢠k ⤠ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n (Nat.succ ν))) = 0
[PROOFSTEP]
induction' k with k ih generalizing n ν
[GOAL]
case succ.zero
R : Type u_1
instā : CommRing R
nā νā n ν : ā
⢠Nat.zero ⤠ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[Nat.zero] (bernsteinPolynomial R n (Nat.succ ν))) = 0
[PROOFSTEP]
simp [eval_at_0]
[GOAL]
case succ.succ
R : Type u_1
instā : CommRing R
nā νā k : ā
ih : ā (n ν : ā), k ⤠ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n (Nat.succ ν))) = 0
n ν : ā
⢠Nat.succ k ⤠ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[Nat.succ k] (bernsteinPolynomial R n (Nat.succ ν))) = 0
[PROOFSTEP]
simp only [derivative_succ, Int.coe_nat_eq_zero, mul_eq_zero, Function.comp_apply, Function.iterate_succ,
Polynomial.iterate_derivative_sub, Polynomial.iterate_derivative_nat_cast_mul, Polynomial.eval_mul,
Polynomial.eval_nat_cast, Polynomial.eval_sub]
[GOAL]
case succ.succ
R : Type u_1
instā : CommRing R
nā νā k : ā
ih : ā (n ν : ā), k ⤠ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n (Nat.succ ν))) = 0
n ν : ā
⢠Nat.succ k ⤠ν ā
ān *
(Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R (n - 1) ν)) -
Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R (n - 1) (ν + 1)))) =
0
[PROOFSTEP]
intro h
[GOAL]
case succ.succ
R : Type u_1
instā : CommRing R
nā νā k : ā
ih : ā (n ν : ā), k ⤠ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n (Nat.succ ν))) = 0
n ν : ā
h : Nat.succ k ⤠ν
⢠ān *
(Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R (n - 1) ν)) -
Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R (n - 1) (ν + 1)))) =
0
[PROOFSTEP]
apply mul_eq_zero_of_right
[GOAL]
case succ.succ.h
R : Type u_1
instā : CommRing R
nā νā k : ā
ih : ā (n ν : ā), k ⤠ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n (Nat.succ ν))) = 0
n ν : ā
h : Nat.succ k ⤠ν
⢠Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R (n - 1) ν)) -
Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R (n - 1) (ν + 1))) =
0
[PROOFSTEP]
rw [ih _ _ (Nat.le_of_succ_le h), sub_zero]
[GOAL]
case succ.succ.h
R : Type u_1
instā : CommRing R
nā νā k : ā
ih : ā (n ν : ā), k ⤠ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n (Nat.succ ν))) = 0
n ν : ā
h : Nat.succ k ⤠ν
⢠Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R (n - 1) ν)) = 0
[PROOFSTEP]
convert ih _ _ (Nat.pred_le_pred h)
[GOAL]
case h.e'_2.h.e'_4.h.h.e'_4.h.e'_4
R : Type u_1
instā : CommRing R
nā νā k : ā
ih : ā (n ν : ā), k ⤠ν ā Polynomial.eval 0 ((āPolynomial.derivative)^[k] (bernsteinPolynomial R n (Nat.succ ν))) = 0
n ν : ā
h : Nat.succ k ⤠ν
e_2ā : Ring.toSemiring = CommSemiring.toSemiring
⢠ν = Nat.succ (Nat.pred ν)
[PROOFSTEP]
exact (Nat.succ_pred_eq_of_pos (k.succ_pos.trans_le h)).symm
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
⢠eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
[PROOFSTEP]
by_cases h : ν ⤠n
[GOAL]
case pos
R : Type u_1
instā : CommRing R
n ν : ā
h : ν ⤠n
⢠eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
[PROOFSTEP]
induction' ν with ν ih generalizing n
[GOAL]
case pos.zero
R : Type u_1
instā : CommRing R
nā ν : ā
hā : ν ⤠nā
n : ā
h : Nat.zero ⤠n
⢠eval 0 ((āderivative)^[Nat.zero] (bernsteinPolynomial R n Nat.zero)) =
eval (ā(n - (Nat.zero - 1))) (pochhammer R Nat.zero)
[PROOFSTEP]
simp [eval_at_0]
[GOAL]
case pos.succ
R : Type u_1
instā : CommRing R
nā νā : ā
hā : νā ⤠nā
ν : ā
ih : ā (n : ā), ν ⤠n ā eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
n : ā
h : Nat.succ ν ⤠n
⢠eval 0 ((āderivative)^[Nat.succ ν] (bernsteinPolynomial R n (Nat.succ ν))) =
eval (ā(n - (Nat.succ ν - 1))) (pochhammer R (Nat.succ ν))
[PROOFSTEP]
have h' : ν ⤠n - 1 := le_tsub_of_add_le_right h
[GOAL]
case pos.succ
R : Type u_1
instā : CommRing R
nā νā : ā
hā : νā ⤠nā
ν : ā
ih : ā (n : ā), ν ⤠n ā eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
n : ā
h : Nat.succ ν ⤠n
h' : ν ⤠n - 1
⢠eval 0 ((āderivative)^[Nat.succ ν] (bernsteinPolynomial R n (Nat.succ ν))) =
eval (ā(n - (Nat.succ ν - 1))) (pochhammer R (Nat.succ ν))
[PROOFSTEP]
simp only [derivative_succ, ih (n - 1) h', iterate_derivative_succ_at_0_eq_zero, Nat.succ_sub_succ_eq_sub, tsub_zero,
sub_zero, iterate_derivative_sub, iterate_derivative_nat_cast_mul, eval_one, eval_mul, eval_add, eval_sub, eval_X,
eval_comp, eval_nat_cast, Function.comp_apply, Function.iterate_succ, pochhammer_succ_left]
[GOAL]
case pos.succ
R : Type u_1
instā : CommRing R
nā νā : ā
hā : νā ⤠nā
ν : ā
ih : ā (n : ā), ν ⤠n ā eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
n : ā
h : Nat.succ ν ⤠n
h' : ν ⤠n - 1
⢠ān * eval (ā(n - 1 - (ν - 1))) (pochhammer R ν) = ā(n - ν) * eval (ā(n - ν) + 1) (pochhammer R ν)
[PROOFSTEP]
obtain rfl | h'' := ν.eq_zero_or_pos
[GOAL]
case pos.succ.inl
R : Type u_1
instā : CommRing R
nā ν : ā
hā : ν ⤠nā
n : ā
ih : ā (n : ā), 0 ⤠n ā eval 0 ((āderivative)^[0] (bernsteinPolynomial R n 0)) = eval (ā(n - (0 - 1))) (pochhammer R 0)
h : Nat.succ 0 ⤠n
h' : 0 ⤠n - 1
⢠ān * eval (ā(n - 1 - (0 - 1))) (pochhammer R 0) = ā(n - 0) * eval (ā(n - 0) + 1) (pochhammer R 0)
[PROOFSTEP]
simp
[GOAL]
case pos.succ.inr
R : Type u_1
instā : CommRing R
nā νā : ā
hā : νā ⤠nā
ν : ā
ih : ā (n : ā), ν ⤠n ā eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
n : ā
h : Nat.succ ν ⤠n
h' : ν ⤠n - 1
h'' : ν > 0
⢠ān * eval (ā(n - 1 - (ν - 1))) (pochhammer R ν) = ā(n - ν) * eval (ā(n - ν) + 1) (pochhammer R ν)
[PROOFSTEP]
have : n - 1 - (ν - 1) = n - ν := by
rw [gt_iff_lt, ā Nat.succ_le_iff] at h''
rw [ā tsub_add_eq_tsub_tsub, add_comm, tsub_add_cancel_of_le h'']
[GOAL]
R : Type u_1
instā : CommRing R
nā νā : ā
hā : νā ⤠nā
ν : ā
ih : ā (n : ā), ν ⤠n ā eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
n : ā
h : Nat.succ ν ⤠n
h' : ν ⤠n - 1
h'' : ν > 0
⢠n - 1 - (ν - 1) = n - ν
[PROOFSTEP]
rw [gt_iff_lt, ā Nat.succ_le_iff] at h''
[GOAL]
R : Type u_1
instā : CommRing R
nā νā : ā
hā : νā ⤠nā
ν : ā
ih : ā (n : ā), ν ⤠n ā eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
n : ā
h : Nat.succ ν ⤠n
h' : ν ⤠n - 1
h'' : Nat.succ 0 ⤠ν
⢠n - 1 - (ν - 1) = n - ν
[PROOFSTEP]
rw [ā tsub_add_eq_tsub_tsub, add_comm, tsub_add_cancel_of_le h'']
[GOAL]
case pos.succ.inr
R : Type u_1
instā : CommRing R
nā νā : ā
hā : νā ⤠nā
ν : ā
ih : ā (n : ā), ν ⤠n ā eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
n : ā
h : Nat.succ ν ⤠n
h' : ν ⤠n - 1
h'' : ν > 0
this : n - 1 - (ν - 1) = n - ν
⢠ān * eval (ā(n - 1 - (ν - 1))) (pochhammer R ν) = ā(n - ν) * eval (ā(n - ν) + 1) (pochhammer R ν)
[PROOFSTEP]
rw [this, pochhammer_eval_succ]
[GOAL]
case pos.succ.inr
R : Type u_1
instā : CommRing R
nā νā : ā
hā : νā ⤠nā
ν : ā
ih : ā (n : ā), ν ⤠n ā eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
n : ā
h : Nat.succ ν ⤠n
h' : ν ⤠n - 1
h'' : ν > 0
this : n - 1 - (ν - 1) = n - ν
⢠ān * eval (ā(n - ν)) (pochhammer R ν) = (ā(n - ν) + āν) * eval (ā(n - ν)) (pochhammer R ν)
[PROOFSTEP]
rw_mod_cast [tsub_add_cancel_of_le (h'.trans n.pred_le)]
[GOAL]
case neg
R : Type u_1
instā : CommRing R
n ν : ā
h : ¬ν ⤠n
⢠eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
[PROOFSTEP]
simp only [not_le] at h
[GOAL]
case neg
R : Type u_1
instā : CommRing R
n ν : ā
h : n < ν
⢠eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) = eval (ā(n - (ν - 1))) (pochhammer R ν)
[PROOFSTEP]
rw [tsub_eq_zero_iff_le.mpr (Nat.le_pred_of_lt h), eq_zero_of_lt R h]
[GOAL]
case neg
R : Type u_1
instā : CommRing R
n ν : ā
h : n < ν
⢠eval 0 ((āderivative)^[ν] 0) = eval (ā0) (pochhammer R ν)
[PROOFSTEP]
simp [pos_iff_ne_zero.mp (pos_of_gt h)]
[GOAL]
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n ν : ā
h : ν ⤠n
⢠eval 0 ((āderivative)^[ν] (bernsteinPolynomial R n ν)) ā 0
[PROOFSTEP]
simp only [Int.coe_nat_eq_zero, bernsteinPolynomial.iterate_derivative_at_0, Ne.def, Nat.cast_eq_zero]
[GOAL]
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n ν : ā
h : ν ⤠n
⢠¬eval (ā(n - (ν - 1))) (pochhammer R ν) = 0
[PROOFSTEP]
simp only [ā pochhammer_eval_cast]
[GOAL]
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n ν : ā
h : ν ⤠n
⢠¬ā(eval (n - (ν - 1)) (pochhammer ā ν)) = 0
[PROOFSTEP]
norm_cast
[GOAL]
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n ν : ā
h : ν ⤠n
⢠¬eval (n - (ν - 1)) (pochhammer ā ν) = 0
[PROOFSTEP]
apply ne_of_gt
[GOAL]
case h
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n ν : ā
h : ν ⤠n
⢠0 < eval (n - (ν - 1)) (pochhammer ā ν)
[PROOFSTEP]
obtain rfl | h' := Nat.eq_zero_or_pos ν
[GOAL]
case h.inl
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n : ā
h : 0 ⤠n
⢠0 < eval (n - (0 - 1)) (pochhammer ā 0)
[PROOFSTEP]
simp
[GOAL]
case h.inr
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n ν : ā
h : ν ⤠n
h' : ν > 0
⢠0 < eval (n - (ν - 1)) (pochhammer ā ν)
[PROOFSTEP]
rw [ā Nat.succ_pred_eq_of_pos h'] at h
[GOAL]
case h.inr
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n ν : ā
h : Nat.succ (Nat.pred ν) ⤠n
h' : ν > 0
⢠0 < eval (n - (ν - 1)) (pochhammer ā ν)
[PROOFSTEP]
exact pochhammer_pos _ _ (tsub_pos_of_lt (Nat.lt_of_succ_le h))
[GOAL]
R : Type u_1
instā : CommRing R
n ν k : ā
⢠k < n - ν ā eval 1 ((āderivative)^[k] (bernsteinPolynomial R n ν)) = 0
[PROOFSTEP]
intro w
[GOAL]
R : Type u_1
instā : CommRing R
n ν k : ā
w : k < n - ν
⢠eval 1 ((āderivative)^[k] (bernsteinPolynomial R n ν)) = 0
[PROOFSTEP]
rw [flip' _ _ _ (tsub_pos_iff_lt.mp (pos_of_gt w)).le]
[GOAL]
R : Type u_1
instā : CommRing R
n ν k : ā
w : k < n - ν
⢠eval 1 ((āderivative)^[k] (comp (bernsteinPolynomial R n (n - ν)) (1 - X))) = 0
[PROOFSTEP]
simp [Polynomial.eval_comp, iterate_derivative_at_0_eq_zero_of_lt R n w]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
h : ν ⤠n
⢠eval 1 ((āderivative)^[n - ν] (bernsteinPolynomial R n ν)) = (-1) ^ (n - ν) * eval (āν + 1) (pochhammer R (n - ν))
[PROOFSTEP]
rw [flip' _ _ _ h]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
h : ν ⤠n
⢠eval 1 ((āderivative)^[n - ν] (comp (bernsteinPolynomial R n (n - ν)) (1 - X))) =
(-1) ^ (n - ν) * eval (āν + 1) (pochhammer R (n - ν))
[PROOFSTEP]
simp [Polynomial.eval_comp, h]
[GOAL]
R : Type u_1
instā : CommRing R
n ν : ā
h : ν ⤠n
⢠(-1) ^ (n - ν) * eval (ā(n - (n - ν - 1))) (pochhammer R (n - ν)) =
(-1) ^ (n - ν) * eval (āν + 1) (pochhammer R (n - ν))
[PROOFSTEP]
obtain rfl | h' := h.eq_or_lt
[GOAL]
case inl
R : Type u_1
instā : CommRing R
ν : ā
h : ν ⤠ν
⢠(-1) ^ (ν - ν) * eval (ā(ν - (ν - ν - 1))) (pochhammer R (ν - ν)) =
(-1) ^ (ν - ν) * eval (āν + 1) (pochhammer R (ν - ν))
[PROOFSTEP]
simp
[GOAL]
case inr
R : Type u_1
instā : CommRing R
n ν : ā
h : ν ⤠n
h' : ν < n
⢠(-1) ^ (n - ν) * eval (ā(n - (n - ν - 1))) (pochhammer R (n - ν)) =
(-1) ^ (n - ν) * eval (āν + 1) (pochhammer R (n - ν))
[PROOFSTEP]
congr
[GOAL]
case inr.e_a.e_a
R : Type u_1
instā : CommRing R
n ν : ā
h : ν ⤠n
h' : ν < n
⢠ā(n - (n - ν - 1)) = āν + 1
[PROOFSTEP]
norm_cast
[GOAL]
case inr.e_a.e_a
R : Type u_1
instā : CommRing R
n ν : ā
h : ν ⤠n
h' : ν < n
⢠ā(n - (n - ν - 1)) = ā(ν + 1)
[PROOFSTEP]
rw [ā tsub_add_eq_tsub_tsub, tsub_tsub_cancel_of_le (Nat.succ_le_iff.mpr h')]
[GOAL]
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n ν : ā
h : ν ⤠n
⢠eval 1 ((āderivative)^[n - ν] (bernsteinPolynomial R n ν)) ā 0
[PROOFSTEP]
rw [bernsteinPolynomial.iterate_derivative_at_1 _ _ _ h, Ne.def, neg_one_pow_mul_eq_zero_iff, ā Nat.cast_succ, ā
pochhammer_eval_cast, ā Nat.cast_zero, Nat.cast_inj]
[GOAL]
R : Type u_1
instā¹ : CommRing R
instā : CharZero R
n ν : ā
h : ν ⤠n
⢠¬eval (Nat.succ ν) (pochhammer ā (n - ν)) = 0
[PROOFSTEP]
exact (pochhammer_pos _ _ (Nat.succ_pos ν)).ne'
[GOAL]
R : Type u_1
instā : CommRing R
n k : ā
h : k ⤠n + 1
⢠LinearIndependent ā fun ν => bernsteinPolynomial ā n āν
[PROOFSTEP]
induction' k with k ih
[GOAL]
case zero
R : Type u_1
instā : CommRing R
n k : ā
hā : k ⤠n + 1
h : Nat.zero ⤠n + 1
⢠LinearIndependent ā fun ν => bernsteinPolynomial ā n āν
[PROOFSTEP]
simp [Nat.zero_eq]
[GOAL]
case zero
R : Type u_1
instā : CommRing R
n k : ā
hā : k ⤠n + 1
h : Nat.zero ⤠n + 1
⢠LinearIndependent ā fun ν => bernsteinPolynomial ā n āν
[PROOFSTEP]
apply linearIndependent_empty_type
[GOAL]
case succ
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
ih : k ⤠n + 1 ā LinearIndependent ā fun ν => bernsteinPolynomial ā n āν
h : Nat.succ k ⤠n + 1
⢠LinearIndependent ā fun ν => bernsteinPolynomial ā n āν
[PROOFSTEP]
apply linearIndependent_fin_succ'.mpr
[GOAL]
case succ
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
ih : k ⤠n + 1 ā LinearIndependent ā fun ν => bernsteinPolynomial ā n āν
h : Nat.succ k ⤠n + 1
⢠LinearIndependent ā (Fin.init fun ν => bernsteinPolynomial ā n āν) ā§
¬bernsteinPolynomial ā n ā(Fin.last k) ā span ā (Set.range (Fin.init fun ν => bernsteinPolynomial ā n āν))
[PROOFSTEP]
fconstructor
[GOAL]
case succ.left
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
ih : k ⤠n + 1 ā LinearIndependent ā fun ν => bernsteinPolynomial ā n āν
h : Nat.succ k ⤠n + 1
⢠LinearIndependent ā (Fin.init fun ν => bernsteinPolynomial ā n āν)
[PROOFSTEP]
exact ih (le_of_lt h)
[GOAL]
case succ.right
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
ih : k ⤠n + 1 ā LinearIndependent ā fun ν => bernsteinPolynomial ā n āν
h : Nat.succ k ⤠n + 1
⢠¬bernsteinPolynomial ā n ā(Fin.last k) ā span ā (Set.range (Fin.init fun ν => bernsteinPolynomial ā n āν))
[PROOFSTEP]
clear ih
[GOAL]
case succ.right
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : Nat.succ k ⤠n + 1
⢠¬bernsteinPolynomial ā n ā(Fin.last k) ā span ā (Set.range (Fin.init fun ν => bernsteinPolynomial ā n āν))
[PROOFSTEP]
simp only [Nat.succ_eq_add_one, add_le_add_iff_right] at h
[GOAL]
case succ.right
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
⢠¬bernsteinPolynomial ā n ā(Fin.last k) ā span ā (Set.range (Fin.init fun ν => bernsteinPolynomial ā n āν))
[PROOFSTEP]
simp only [Fin.val_last, Fin.init_def]
[GOAL]
case succ.right
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
⢠¬bernsteinPolynomial ā n k ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n ā(Fin.castSucc k_1))
[PROOFSTEP]
dsimp
[GOAL]
case succ.right
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
⢠¬bernsteinPolynomial ā n k ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
[PROOFSTEP]
apply not_mem_span_of_apply_not_mem_span_image (@Polynomial.derivative ā _ ^ (n - k))
[GOAL]
case succ.right
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
⢠¬ā(derivative ^ (n - k)) (bernsteinPolynomial ā n k) ā
span ā (ā(derivative ^ (n - k)) '' Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
[PROOFSTEP]
simp only [not_exists, not_and, Submodule.mem_map, Submodule.span_image]
[GOAL]
case succ.right
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
⢠ā (x : ā[X]),
x ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1) ā
¬ā(derivative ^ (n - k)) x = ā(derivative ^ (n - k)) (bernsteinPolynomial ā n k)
[PROOFSTEP]
intro p m
[GOAL]
case succ.right
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
⢠¬ā(derivative ^ (n - k)) p = ā(derivative ^ (n - k)) (bernsteinPolynomial ā n k)
[PROOFSTEP]
apply_fun Polynomial.eval (1 : ā)
[GOAL]
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
⢠eval 1 (ā(derivative ^ (n - k)) p) ā eval 1 (ā(derivative ^ (n - k)) (bernsteinPolynomial ā n k))
[PROOFSTEP]
simp only [LinearMap.pow_apply]
-- The right hand side is nonzero,
-- so it will suffice to show the left hand side is always zero.
[GOAL]
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
⢠eval 1 ((āderivative)^[n - k] p) ā eval 1 ((āderivative)^[n - k] (bernsteinPolynomial ā n k))
[PROOFSTEP]
suffices (Polynomial.derivative^[n - k] p).eval 1 = 0 by
rw [this]
exact (iterate_derivative_at_1_ne_zero ā n k h).symm
[GOAL]
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
this : eval 1 ((āderivative)^[n - k] p) = 0
⢠eval 1 ((āderivative)^[n - k] p) ā eval 1 ((āderivative)^[n - k] (bernsteinPolynomial ā n k))
[PROOFSTEP]
rw [this]
[GOAL]
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
this : eval 1 ((āderivative)^[n - k] p) = 0
⢠0 ā eval 1 ((āderivative)^[n - k] (bernsteinPolynomial ā n k))
[PROOFSTEP]
exact (iterate_derivative_at_1_ne_zero ā n k h).symm
[GOAL]
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
⢠eval 1 ((āderivative)^[n - k] p) = 0
[PROOFSTEP]
refine span_induction m ?_ ?_ ?_ ?_
[GOAL]
case refine_1
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
⢠ā (x : ā[X]), (x ā Set.range fun k_1 => bernsteinPolynomial ā n āk_1) ā eval 1 ((āderivative)^[n - k] x) = 0
[PROOFSTEP]
simp
[GOAL]
case refine_1
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
⢠ā (a : Fin k), eval 1 ((āderivative)^[n - k] (bernsteinPolynomial ā n āa)) = 0
[PROOFSTEP]
rintro āØa, wā©
[GOAL]
case refine_1.mk
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
a : ā
w : a < k
⢠eval 1 ((āderivative)^[n - k] (bernsteinPolynomial ā n ā{ val := a, isLt := w })) = 0
[PROOFSTEP]
simp only [Fin.val_mk]
[GOAL]
case refine_1.mk
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
a : ā
w : a < k
⢠eval 1 ((āderivative)^[n - k] (bernsteinPolynomial ā n a)) = 0
[PROOFSTEP]
rw [iterate_derivative_at_1_eq_zero_of_lt ā n ((tsub_lt_tsub_iff_left_of_le h).mpr w)]
[GOAL]
case refine_2
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
⢠eval 1 ((āderivative)^[n - k] 0) = 0
[PROOFSTEP]
simp
[GOAL]
case refine_3
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
⢠ā (x y : ā[X]),
eval 1 ((āderivative)^[n - k] x) = 0 ā
eval 1 ((āderivative)^[n - k] y) = 0 ā eval 1 ((āderivative)^[n - k] (x + y)) = 0
[PROOFSTEP]
intro x y hx hy
[GOAL]
case refine_3
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
x y : ā[X]
hx : eval 1 ((āderivative)^[n - k] x) = 0
hy : eval 1 ((āderivative)^[n - k] y) = 0
⢠eval 1 ((āderivative)^[n - k] (x + y)) = 0
[PROOFSTEP]
simp [hx, hy]
[GOAL]
case refine_4
R : Type u_1
instā : CommRing R
n kā : ā
hā : kā ⤠n + 1
k : ā
h : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
⢠ā (a : ā) (x : ā[X]), eval 1 ((āderivative)^[n - k] x) = 0 ā eval 1 ((āderivative)^[n - k] (a ⢠x)) = 0
[PROOFSTEP]
intro a x h
[GOAL]
case refine_4
R : Type u_1
instā : CommRing R
n kā : ā
hā¹ : kā ⤠n + 1
k : ā
hā : k ⤠n
p : ā[X]
m : p ā span ā (Set.range fun k_1 => bernsteinPolynomial ā n āk_1)
a : ā
x : ā[X]
h : eval 1 ((āderivative)^[n - k] x) = 0
⢠eval 1 ((āderivative)^[n - k] (a ⢠x)) = 0
[PROOFSTEP]
simp [h]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
⢠ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν = (X + (1 - X)) ^ n
[PROOFSTEP]
rw [add_pow]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
⢠ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā m in Finset.range (n + 1), X ^ m * (1 - X) ^ (n - m) * ā(choose n m)
[PROOFSTEP]
simp only [bernsteinPolynomial, mul_comm, mul_assoc, mul_left_comm]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
⢠(X + (1 - X)) ^ n = 1
[PROOFSTEP]
simp
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
⢠ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν = n ⢠X
[PROOFSTEP]
let x : MvPolynomial Bool R := MvPolynomial.X true
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
⢠ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν = n ⢠X
[PROOFSTEP]
let y : MvPolynomial Bool R := MvPolynomial.X false
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
⢠ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν = n ⢠X
[PROOFSTEP]
have pderiv_true_x : pderiv true x = 1 := by rw [pderiv_X]; rfl
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
⢠ā(pderiv true) x = 1
[PROOFSTEP]
rw [pderiv_X]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
⢠Pi.single true 1 true = 1
[PROOFSTEP]
rfl
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
⢠ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν = n ⢠X
[PROOFSTEP]
have pderiv_true_y : pderiv true y = 0 := by rw [pderiv_X]; rfl
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
⢠ā(pderiv true) y = 0
[PROOFSTEP]
rw [pderiv_X]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
⢠Pi.single true 1 false = 0
[PROOFSTEP]
rfl
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
⢠ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν = n ⢠X
[PROOFSTEP]
let e : Bool ā R[X] := fun i =>
cond i X
(1 - X)
-- Start with `(x+y)^n = (x+y)^n`,
-- take the `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`:
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν = n ⢠X
[PROOFSTEP]
trans MvPolynomial.aeval e (pderiv true ((x + y) ^ n)) * X
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν =
ā(MvPolynomial.aeval e) (ā(pderiv true) ((x + y) ^ n)) * X
[PROOFSTEP]
have w :
ā k : ā,
k ⢠bernsteinPolynomial R n k =
(k : R[X]) * Polynomial.X ^ (k - 1) * (1 - Polynomial.X) ^ (n - k) * (n.choose k : R[X]) * Polynomial.X :=
by
rintro (_ | k)
Ā· simp
Ā· rw [bernsteinPolynomial]
simp only [ā nat_cast_mul, Nat.succ_eq_add_one, Nat.add_succ_sub_one, add_zero, pow_succ]
push_cast
ring
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠ā (k : ā), k ⢠bernsteinPolynomial R n k = āk * X ^ (k - 1) * (1 - X) ^ (n - k) * ā(choose n k) * X
[PROOFSTEP]
rintro (_ | k)
[GOAL]
case zero
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠Nat.zero ⢠bernsteinPolynomial R n Nat.zero =
āNat.zero * X ^ (Nat.zero - 1) * (1 - X) ^ (n - Nat.zero) * ā(choose n Nat.zero) * X
[PROOFSTEP]
simp
[GOAL]
case succ
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
k : ā
⢠Nat.succ k ⢠bernsteinPolynomial R n (Nat.succ k) =
ā(Nat.succ k) * X ^ (Nat.succ k - 1) * (1 - X) ^ (n - Nat.succ k) * ā(choose n (Nat.succ k)) * X
[PROOFSTEP]
rw [bernsteinPolynomial]
[GOAL]
case succ
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
k : ā
⢠Nat.succ k ⢠(ā(choose n (Nat.succ k)) * X ^ Nat.succ k * (1 - X) ^ (n - Nat.succ k)) =
ā(Nat.succ k) * X ^ (Nat.succ k - 1) * (1 - X) ^ (n - Nat.succ k) * ā(choose n (Nat.succ k)) * X
[PROOFSTEP]
simp only [ā nat_cast_mul, Nat.succ_eq_add_one, Nat.add_succ_sub_one, add_zero, pow_succ]
[GOAL]
case succ
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
k : ā
⢠ā(k + 1) * (ā(choose n (k + 1)) * (X * X ^ k) * (1 - X) ^ (n - (k + 1))) =
ā(k + 1) * X ^ k * (1 - X) ^ (n - (k + 1)) * ā(choose n (k + 1)) * X
[PROOFSTEP]
push_cast
[GOAL]
case succ
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
k : ā
⢠(āk + 1) * (ā(choose n (k + 1)) * (X * X ^ k) * (1 - X) ^ (n - (k + 1))) =
(āk + 1) * X ^ k * (1 - X) ^ (n - (k + 1)) * ā(choose n (k + 1)) * X
[PROOFSTEP]
ring
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
w : ā (k : ā), k ⢠bernsteinPolynomial R n k = āk * X ^ (k - 1) * (1 - X) ^ (n - k) * ā(choose n k) * X
⢠ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν =
ā(MvPolynomial.aeval e) (ā(pderiv true) ((x + y) ^ n)) * X
[PROOFSTEP]
rw [add_pow, (pderiv true).map_sum, (MvPolynomial.aeval e).map_sum, Finset.sum_mul]
-- Step inside the sum:
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
w : ā (k : ā), k ⢠bernsteinPolynomial R n k = āk * X ^ (k - 1) * (1 - X) ^ (n - k) * ā(choose n k) * X
⢠ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν =
ā x_1 in Finset.range (n + 1),
ā(MvPolynomial.aeval e) (ā(pderiv true) (x ^ x_1 * y ^ (n - x_1) * ā(choose n x_1))) * X
[PROOFSTEP]
refine' Finset.sum_congr rfl fun k _ => (w k).trans _
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
w : ā (k : ā), k ⢠bernsteinPolynomial R n k = āk * X ^ (k - 1) * (1 - X) ^ (n - k) * ā(choose n k) * X
k : ā
xā : k ā Finset.range (n + 1)
⢠āk * X ^ (k - 1) * (1 - X) ^ (n - k) * ā(choose n k) * X =
ā(MvPolynomial.aeval e) (ā(pderiv true) (x ^ k * y ^ (n - k) * ā(choose n k))) * X
[PROOFSTEP]
simp only [pderiv_true_x, pderiv_true_y, Algebra.id.smul_eq_mul, nsmul_eq_mul, Bool.cond_true, Bool.cond_false,
add_zero, mul_one, mul_zero, smul_zero, MvPolynomial.aeval_X, MvPolynomial.pderiv_mul, Derivation.leibniz_pow,
Derivation.map_coe_nat, map_natCast, map_pow, map_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠ā(MvPolynomial.aeval e) (ā(pderiv true) ((x + y) ^ n)) * X = n ⢠X
[PROOFSTEP]
rw [(pderiv true).leibniz_pow, (pderiv true).map_add, pderiv_true_x, pderiv_true_y]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠ā(MvPolynomial.aeval e) (n ⢠(x + y) ^ (n - 1) ⢠(1 + 0)) * X = n ⢠X
[PROOFSTEP]
simp only [Algebra.id.smul_eq_mul, nsmul_eq_mul, map_natCast, map_pow, map_add, map_mul, Bool.cond_true,
Bool.cond_false, MvPolynomial.aeval_X, add_sub_cancel'_right, one_pow, add_zero, mul_one]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
⢠ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν = (n * (n - 1)) ⢠X ^ 2
[PROOFSTEP]
let x : MvPolynomial Bool R := MvPolynomial.X true
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
⢠ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν = (n * (n - 1)) ⢠X ^ 2
[PROOFSTEP]
let y : MvPolynomial Bool R := MvPolynomial.X false
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
⢠ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν = (n * (n - 1)) ⢠X ^ 2
[PROOFSTEP]
have pderiv_true_x : pderiv true x = 1 := by rw [pderiv_X]; rfl
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
⢠ā(pderiv true) x = 1
[PROOFSTEP]
rw [pderiv_X]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
⢠Pi.single true 1 true = 1
[PROOFSTEP]
rfl
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
⢠ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν = (n * (n - 1)) ⢠X ^ 2
[PROOFSTEP]
have pderiv_true_y : pderiv true y = 0 := by rw [pderiv_X]; rfl
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
⢠ā(pderiv true) y = 0
[PROOFSTEP]
rw [pderiv_X]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
⢠Pi.single true 1 false = 0
[PROOFSTEP]
rfl
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
⢠ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν = (n * (n - 1)) ⢠X ^ 2
[PROOFSTEP]
let e : Bool ā R[X] := fun i =>
cond i X
(1 - X)
-- Start with `(x+y)^n = (x+y)^n`,
-- take the second `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`:
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν = (n * (n - 1)) ⢠X ^ 2
[PROOFSTEP]
trans
MvPolynomial.aeval e (pderiv true (pderiv true ((x + y) ^ n))) *
X ^
2
-- On the left hand side we'll use the binomial theorem, then simplify.
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν =
ā(MvPolynomial.aeval e) (ā(pderiv true) (ā(pderiv true) ((x + y) ^ n))) * X ^ 2
[PROOFSTEP]
have w :
ā k : ā,
(k * (k - 1)) ⢠bernsteinPolynomial R n k =
(n.choose k : R[X]) *
((1 - Polynomial.X) ^ (n - k) * ((k : R[X]) * ((ā(k - 1) : R[X]) * Polynomial.X ^ (k - 1 - 1)))) *
Polynomial.X ^ 2 :=
by
rintro (_ | _ | k)
Ā· simp
Ā· simp
Ā· rw [bernsteinPolynomial]
simp only [ā nat_cast_mul, Nat.succ_eq_add_one, Nat.add_succ_sub_one, add_zero, pow_succ]
push_cast
ring
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠ā (k : ā),
(k * (k - 1)) ⢠bernsteinPolynomial R n k =
ā(choose n k) * ((1 - X) ^ (n - k) * (āk * (ā(k - 1) * X ^ (k - 1 - 1)))) * X ^ 2
[PROOFSTEP]
rintro (_ | _ | k)
[GOAL]
case zero
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠(Nat.zero * (Nat.zero - 1)) ⢠bernsteinPolynomial R n Nat.zero =
ā(choose n Nat.zero) * ((1 - X) ^ (n - Nat.zero) * (āNat.zero * (ā(Nat.zero - 1) * X ^ (Nat.zero - 1 - 1)))) * X ^ 2
[PROOFSTEP]
simp
[GOAL]
case succ.zero
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠(Nat.succ Nat.zero * (Nat.succ Nat.zero - 1)) ⢠bernsteinPolynomial R n (Nat.succ Nat.zero) =
ā(choose n (Nat.succ Nat.zero)) *
((1 - X) ^ (n - Nat.succ Nat.zero) *
(ā(Nat.succ Nat.zero) * (ā(Nat.succ Nat.zero - 1) * X ^ (Nat.succ Nat.zero - 1 - 1)))) *
X ^ 2
[PROOFSTEP]
simp
[GOAL]
case succ.succ
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
k : ā
⢠(Nat.succ (Nat.succ k) * (Nat.succ (Nat.succ k) - 1)) ⢠bernsteinPolynomial R n (Nat.succ (Nat.succ k)) =
ā(choose n (Nat.succ (Nat.succ k))) *
((1 - X) ^ (n - Nat.succ (Nat.succ k)) *
(ā(Nat.succ (Nat.succ k)) * (ā(Nat.succ (Nat.succ k) - 1) * X ^ (Nat.succ (Nat.succ k) - 1 - 1)))) *
X ^ 2
[PROOFSTEP]
rw [bernsteinPolynomial]
[GOAL]
case succ.succ
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
k : ā
⢠(Nat.succ (Nat.succ k) * (Nat.succ (Nat.succ k) - 1)) ā¢
(ā(choose n (Nat.succ (Nat.succ k))) * X ^ Nat.succ (Nat.succ k) * (1 - X) ^ (n - Nat.succ (Nat.succ k))) =
ā(choose n (Nat.succ (Nat.succ k))) *
((1 - X) ^ (n - Nat.succ (Nat.succ k)) *
(ā(Nat.succ (Nat.succ k)) * (ā(Nat.succ (Nat.succ k) - 1) * X ^ (Nat.succ (Nat.succ k) - 1 - 1)))) *
X ^ 2
[PROOFSTEP]
simp only [ā nat_cast_mul, Nat.succ_eq_add_one, Nat.add_succ_sub_one, add_zero, pow_succ]
[GOAL]
case succ.succ
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
k : ā
⢠ā((k + 1 + 1) * (k + 1)) * (ā(choose n (k + 1 + 1)) * (X * (X * X ^ k)) * (1 - X) ^ (n - (k + 1 + 1))) =
ā(choose n (k + 1 + 1)) * ((1 - X) ^ (n - (k + 1 + 1)) * (ā(k + 1 + 1) * (ā(k + 1) * X ^ k))) * (X * (X * X ^ 0))
[PROOFSTEP]
push_cast
[GOAL]
case succ.succ
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
k : ā
⢠(āk + 1 + 1) * (āk + 1) * (ā(choose n (k + 1 + 1)) * (X * (X * X ^ k)) * (1 - X) ^ (n - (k + 1 + 1))) =
ā(choose n (k + 1 + 1)) * ((1 - X) ^ (n - (k + 1 + 1)) * ((āk + 1 + 1) * ((āk + 1) * X ^ k))) * (X * (X * X ^ 0))
[PROOFSTEP]
ring
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
w :
ā (k : ā),
(k * (k - 1)) ⢠bernsteinPolynomial R n k =
ā(choose n k) * ((1 - X) ^ (n - k) * (āk * (ā(k - 1) * X ^ (k - 1 - 1)))) * X ^ 2
⢠ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν =
ā(MvPolynomial.aeval e) (ā(pderiv true) (ā(pderiv true) ((x + y) ^ n))) * X ^ 2
[PROOFSTEP]
rw [add_pow, (pderiv true).map_sum, (pderiv true).map_sum, (MvPolynomial.aeval e).map_sum, Finset.sum_mul]
-- Step inside the sum:
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
w :
ā (k : ā),
(k * (k - 1)) ⢠bernsteinPolynomial R n k =
ā(choose n k) * ((1 - X) ^ (n - k) * (āk * (ā(k - 1) * X ^ (k - 1 - 1)))) * X ^ 2
⢠ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν =
ā x_1 in Finset.range (n + 1),
ā(MvPolynomial.aeval e) (ā(pderiv true) (ā(pderiv true) (x ^ x_1 * y ^ (n - x_1) * ā(choose n x_1)))) * X ^ 2
[PROOFSTEP]
refine' Finset.sum_congr rfl fun k _ => (w k).trans _
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
w :
ā (k : ā),
(k * (k - 1)) ⢠bernsteinPolynomial R n k =
ā(choose n k) * ((1 - X) ^ (n - k) * (āk * (ā(k - 1) * X ^ (k - 1 - 1)))) * X ^ 2
k : ā
xā : k ā Finset.range (n + 1)
⢠ā(choose n k) * ((1 - X) ^ (n - k) * (āk * (ā(k - 1) * X ^ (k - 1 - 1)))) * X ^ 2 =
ā(MvPolynomial.aeval e) (ā(pderiv true) (ā(pderiv true) (x ^ k * y ^ (n - k) * ā(choose n k)))) * X ^ 2
[PROOFSTEP]
simp only [pderiv_true_x, pderiv_true_y, Algebra.id.smul_eq_mul, nsmul_eq_mul, Bool.cond_true, Bool.cond_false,
add_zero, zero_add, mul_zero, smul_zero, mul_one, MvPolynomial.aeval_X, MvPolynomial.pderiv_X_self,
MvPolynomial.pderiv_X_of_ne, Derivation.leibniz_pow, Derivation.leibniz, Derivation.map_coe_nat, map_natCast, map_pow,
map_mul, map_add]
-- On the right hand side, we'll just simplify.
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
x : MvPolynomial Bool R := MvPolynomial.X true
y : MvPolynomial Bool R := MvPolynomial.X false
pderiv_true_x : ā(pderiv true) x = 1
pderiv_true_y : ā(pderiv true) y = 0
e : Bool ā R[X] := fun i => bif i then X else 1 - X
⢠ā(MvPolynomial.aeval e) (ā(pderiv true) (ā(pderiv true) ((x + y) ^ n))) * X ^ 2 = (n * (n - 1)) ⢠X ^ 2
[PROOFSTEP]
simp only [pderiv_one, pderiv_mul, (pderiv _).leibniz_pow, (pderiv _).map_coe_nat, (pderiv true).map_add, pderiv_true_x,
pderiv_true_y, Algebra.id.smul_eq_mul, add_zero, mul_one, Derivation.map_smul_of_tower, map_nsmul, map_pow, map_add,
Bool.cond_true, Bool.cond_false, MvPolynomial.aeval_X, add_sub_cancel'_right, one_pow, smul_smul, smul_one_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
⢠ā ν in Finset.range (n + 1), (n ⢠X - āν) ^ 2 * bernsteinPolynomial R n ν = n ⢠X * (1 - X)
[PROOFSTEP]
have p :
((((Finset.range (n + 1)).sum fun ν => (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν) +
(1 - (2 * n) ⢠Polynomial.X) * (Finset.range (n + 1)).sum fun ν => ν ⢠bernsteinPolynomial R n ν) +
n ^ 2 ⢠X ^ 2 * (Finset.range (n + 1)).sum fun ν => bernsteinPolynomial R n ν) =
_ :=
rfl
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
⢠ā ν in Finset.range (n + 1), (n ⢠X - āν) ^ 2 * bernsteinPolynomial R n ν = n ⢠X * (1 - X)
[PROOFSTEP]
conv at p =>
lhs
rw [Finset.mul_sum, Finset.mul_sum, ā Finset.sum_add_distrib, ā Finset.sum_add_distrib]
simp only [ā nat_cast_mul]
simp only [ā mul_assoc]
simp only [ā add_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
[PROOFSTEP]
lhs
rw [Finset.mul_sum, Finset.mul_sum, ā Finset.sum_add_distrib, ā Finset.sum_add_distrib]
simp only [ā nat_cast_mul]
simp only [ā mul_assoc]
simp only [ā add_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
[PROOFSTEP]
lhs
rw [Finset.mul_sum, Finset.mul_sum, ā Finset.sum_add_distrib, ā Finset.sum_add_distrib]
simp only [ā nat_cast_mul]
simp only [ā mul_assoc]
simp only [ā add_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
[PROOFSTEP]
lhs
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
[PROOFSTEP]
rw [Finset.mul_sum, Finset.mul_sum, ā Finset.sum_add_distrib, ā Finset.sum_add_distrib]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā x in Finset.range (n + 1),
((x * (x - 1)) ⢠bernsteinPolynomial R n x + (ā1 - (2 * n) ⢠X) * x ⢠bernsteinPolynomial R n x +
n ^ 2 ⢠X ^ 2 * bernsteinPolynomial R n x)
[PROOFSTEP]
simp only [ā nat_cast_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā x in Finset.range (n + 1),
(ā(x * (x - 1)) * bernsteinPolynomial R n x + (ā1 - ā(2 * n) * X) * (āx * bernsteinPolynomial R n x) +
ā(n ^ 2) * X ^ 2 * bernsteinPolynomial R n x)
[PROOFSTEP]
simp only [ā mul_assoc]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā x in Finset.range (n + 1),
(ā(x * (x - 1)) * bernsteinPolynomial R n x + (ā1 - ā(2 * n) * X) * āx * bernsteinPolynomial R n x +
ā(n ^ 2) * X ^ 2 * bernsteinPolynomial R n x)
[PROOFSTEP]
simp only [ā add_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
⢠ā ν in Finset.range (n + 1), (n ⢠X - āν) ^ 2 * bernsteinPolynomial R n ν = n ⢠X * (1 - X)
[PROOFSTEP]
conv at p =>
rhs
rw [sum, sum_smul, sum_mul_smul, ā nat_cast_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
[PROOFSTEP]
rhs
rw [sum, sum_smul, sum_mul_smul, ā nat_cast_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
[PROOFSTEP]
rhs
rw [sum, sum_smul, sum_mul_smul, ā nat_cast_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
[PROOFSTEP]
rhs
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
| ā ν in Finset.range (n + 1), (ν * (ν - 1)) ⢠bernsteinPolynomial R n ν +
(ā1 - (2 * n) ⢠X) * ā ν in Finset.range (n + 1), ν ⢠bernsteinPolynomial R n ν +
n ^ 2 ⢠X ^ 2 * ā ν in Finset.range (n + 1), bernsteinPolynomial R n ν
[PROOFSTEP]
rw [sum, sum_smul, sum_mul_smul, ā nat_cast_mul]
[GOAL]
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
⢠ā ν in Finset.range (n + 1), (n ⢠X - āν) ^ 2 * bernsteinPolynomial R n ν = n ⢠X * (1 - X)
[PROOFSTEP]
calc
_ = _ := Finset.sum_congr rfl fun k m => ?_
_ = _ := p
_ = _ := ?_
[GOAL]
case calc_1
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
k : ā
m : k ā Finset.range (n + 1)
⢠(n ⢠X - āk) ^ 2 * bernsteinPolynomial R n k =
(ā(k * (k - 1)) + (ā1 - ā(2 * n) * X) * āk + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n k
[PROOFSTEP]
congr 1
[GOAL]
case calc_1.e_a
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
k : ā
m : k ā Finset.range (n + 1)
⢠(n ⢠X - āk) ^ 2 = ā(k * (k - 1)) + (ā1 - ā(2 * n) * X) * āk + ā(n ^ 2) * X ^ 2
[PROOFSTEP]
simp only [ā nat_cast_mul, push_cast]
[GOAL]
case calc_1.e_a
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
k : ā
m : k ā Finset.range (n + 1)
⢠(ān * X - āk) ^ 2 = āk * ā(k - 1) + (1 - 2 * ān * X) * āk + ān ^ 2 * X ^ 2
[PROOFSTEP]
cases k
[GOAL]
case calc_1.e_a.zero
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
m : Nat.zero ā Finset.range (n + 1)
⢠(ān * X - āNat.zero) ^ 2 = āNat.zero * ā(Nat.zero - 1) + (1 - 2 * ān * X) * āNat.zero + ān ^ 2 * X ^ 2
[PROOFSTEP]
simp
[GOAL]
case calc_1.e_a.zero
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
m : Nat.zero ā Finset.range (n + 1)
⢠(ān * X) ^ 2 = ān ^ 2 * X ^ 2
[PROOFSTEP]
ring
[GOAL]
case calc_1.e_a.succ
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
nā : ā
m : Nat.succ nā ā Finset.range (n + 1)
⢠(ān * X - ā(Nat.succ nā)) ^ 2 =
ā(Nat.succ nā) * ā(Nat.succ nā - 1) + (1 - 2 * ān * X) * ā(Nat.succ nā) + ān ^ 2 * X ^ 2
[PROOFSTEP]
simp
[GOAL]
case calc_1.e_a.succ
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
nā : ā
m : Nat.succ nā ā Finset.range (n + 1)
⢠(ān * X - (ānā + 1)) ^ 2 = (ānā + 1) * ānā + (1 - 2 * ān * X) * (ānā + 1) + ān ^ 2 * X ^ 2
[PROOFSTEP]
ring
[GOAL]
case calc_2
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
⢠ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1 = n ⢠X * (1 - X)
[PROOFSTEP]
simp only [ā nat_cast_mul, push_cast]
[GOAL]
case calc_2
R : Type u_1
instā : CommRing R
n : ā
p :
ā x in Finset.range (n + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * n) * X) * āx + ā(n ^ 2) * X ^ 2) * bernsteinPolynomial R n x =
ā(n * (n - 1)) * X ^ 2 + (ā1 - (2 * n) ⢠X) * n ⢠X + n ^ 2 ⢠X ^ 2 * 1
⢠ān * ā(n - 1) * X ^ 2 + (1 - 2 * ān * X) * (ān * X) + ān ^ 2 * X ^ 2 * 1 = ān * X * (1 - X)
[PROOFSTEP]
cases n
[GOAL]
case calc_2.zero
R : Type u_1
instā : CommRing R
p :
ā x in Finset.range (Nat.zero + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * Nat.zero) * X) * āx + ā(Nat.zero ^ 2) * X ^ 2) * bernsteinPolynomial R Nat.zero x =
ā(Nat.zero * (Nat.zero - 1)) * X ^ 2 + (ā1 - (2 * Nat.zero) ⢠X) * Nat.zero ⢠X + Nat.zero ^ 2 ⢠X ^ 2 * 1
⢠āNat.zero * ā(Nat.zero - 1) * X ^ 2 + (1 - 2 * āNat.zero * X) * (āNat.zero * X) + āNat.zero ^ 2 * X ^ 2 * 1 =
āNat.zero * X * (1 - X)
[PROOFSTEP]
simp
[GOAL]
case calc_2.succ
R : Type u_1
instā : CommRing R
nā : ā
p :
ā x in Finset.range (Nat.succ nā + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * Nat.succ nā) * X) * āx + ā(Nat.succ nā ^ 2) * X ^ 2) *
bernsteinPolynomial R (Nat.succ nā) x =
ā(Nat.succ nā * (Nat.succ nā - 1)) * X ^ 2 + (ā1 - (2 * Nat.succ nā) ⢠X) * Nat.succ nā ⢠X +
Nat.succ nā ^ 2 ⢠X ^ 2 * 1
⢠ā(Nat.succ nā) * ā(Nat.succ nā - 1) * X ^ 2 + (1 - 2 * ā(Nat.succ nā) * X) * (ā(Nat.succ nā) * X) +
ā(Nat.succ nā) ^ 2 * X ^ 2 * 1 =
ā(Nat.succ nā) * X * (1 - X)
[PROOFSTEP]
simp
[GOAL]
case calc_2.succ
R : Type u_1
instā : CommRing R
nā : ā
p :
ā x in Finset.range (Nat.succ nā + 1),
(ā(x * (x - 1)) + (ā1 - ā(2 * Nat.succ nā) * X) * āx + ā(Nat.succ nā ^ 2) * X ^ 2) *
bernsteinPolynomial R (Nat.succ nā) x =
ā(Nat.succ nā * (Nat.succ nā - 1)) * X ^ 2 + (ā1 - (2 * Nat.succ nā) ⢠X) * Nat.succ nā ⢠X +
Nat.succ nā ^ 2 ⢠X ^ 2 * 1
⢠(ānā + 1) * ānā * X ^ 2 + (1 - 2 * (ānā + 1) * X) * ((ānā + 1) * X) + (ānā + 1) ^ 2 * X ^ 2 = (ānā + 1) * X * (1 - X)
[PROOFSTEP]
ring
|
dat <- expand.grid(rep=gl(2,1), NO3=factor(c(0,10)),field=gl(3,1) )
dat
Agropyron <- with(dat, as.numeric(field) + as.numeric(NO3)+2) +rnorm(12)/2
Schizachyrium <- with(dat, as.numeric(field) - as.numeric(NO3)+2) +rnorm(12)/2
total <- Agropyron + Schizachyrium
dotplot(total ~ NO3, dat, jitter.x=TRUE, groups=field,
type=c('p','a'), xlab="NO3", auto.key=list(columns=3, lines=TRUE) )
Y <- data.frame(Agropyron, Schizachyrium)
mod <- metaMDS(Y)
plot(mod)
### Hulls show treatment
with(dat, ordihull(mod, group=NO3, show="0"))
with(dat, ordihull(mod, group=NO3, show="10", col=3))
### Spider shows fields
with(dat, ordispider(mod, group=field, lty=3, col="red"))
### Correct hypothesis test (with strata)
adonis(Y ~ NO3, data=dat, strata=dat$field, perm=999)
library(dplyr)
data <- read.csv('/Users/glmarschmann/.julia/dev/DEBTrait/files/BatchC/adonis_BGE_select.csv')
X <- data.frame(data$response, as.factor(data$rX), data$concentration)
names(X) <- c('Response', 'rX', 'Concentration')
Y <- data.frame(data$BGE)
names(Y) <- c('BGE')
row_sub = apply(Y, 1, function(row) all(row !=0 ))
Yf <- Y[row_sub,]
Xf <- X[row_sub,]
mod <- metaMDS(Yf)
plot(mod)
with(Xf, ordihull(mod, group=rM, show="1"))
with(Xf, ordihull(mod, group=rM, show="2", col=3))
with(Xf, ordispider(mod, group=Response, lty=3, col="red"))
adonis(Yf ~ rX, data=Xf, perm=999)
|
open import Relation.Binary.Core
module InsertSort.Impl2.Correctness.Permutation.Base {A : Set}
(_ā¤_ : A ā A ā Set)
(tot⤠: Total _ā¤_) where
open import Bound.Lower A
open import Bound.Lower.Order _ā¤_
open import Data.List
open import Data.Sum
open import InsertSort.Impl2 _ā¤_ totā¤
open import List.Permutation.Base A
open import OList _ā¤_
lemma-forget-insert : {b : Bound} ā (x : A) ā (bā¤x : LeB b (val x)) ā (xs : OList b) ā forget (insert bā¤x xs) / x ā¶ forget xs
lemma-forget-insert x bā¤x onil = /head
lemma-forget-insert x bā¤x (:< {x = y} bā¤y ys)
with tot⤠x y
... | injā xā¤y = /head
... | injā yā¤x = /tail (lemma-forget-insert x (lexy yā¤x) ys)
theorem-insertSortā¼ : (xs : List A) ā xs ā¼ forget (insertSort xs)
theorem-insertSortā¼ [] = ā¼[]
theorem-insertSortā¼ (x ā· xs) = ā¼x /head (lemma-forget-insert x lebx (insertSort xs)) (theorem-insertSortā¼ xs)
|
/-
Copyright (c) 2022 Sebastian Monnet. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Monnet
! This file was ported from Lean 3 source module field_theory.krull_topology
! leanprover-community/mathlib commit 83f81aea33931a1edb94ce0f32b9a5d484de6978
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.FieldTheory.Galois
import Mathbin.Topology.Algebra.FilterBasis
import Mathbin.Topology.Algebra.OpenSubgroup
import Mathbin.Tactic.ByContra
/-!
# Krull topology
We define the Krull topology on `L āā[K] L` for an arbitrary field extension `L/K`. In order to do
this, we first define a `group_filter_basis` on `L āā[K] L`, whose sets are `E.fixing_subgroup` for
all intermediate fields `E` with `E/K` finite dimensional.
## Main Definitions
- `finite_exts K L`. Given a field extension `L/K`, this is the set of intermediate fields that are
finite-dimensional over `K`.
- `fixed_by_finite K L`. Given a field extension `L/K`, `fixed_by_finite K L` is the set of
subsets `Gal(L/E)` of `Gal(L/K)`, where `E/K` is finite
- `gal_basis K L`. Given a field extension `L/K`, this is the filter basis on `L āā[K] L` whose
sets are `Gal(L/E)` for intermediate fields `E` with `E/K` finite.
- `gal_group_basis K L`. This is the same as `gal_basis K L`, but with the added structure
that it is a group filter basis on `L āā[K] L`, rather than just a filter basis.
- `krull_topology K L`. Given a field extension `L/K`, this is the topology on `L āā[K] L`, induced
by the group filter basis `gal_group_basis K L`.
## Main Results
- `krull_topology_t2 K L`. For an integral field extension `L/K`, the topology `krull_topology K L`
is Hausdorff.
- `krull_topology_totally_disconnected K L`. For an integral field extension `L/K`, the topology
`krull_topology K L` is totally disconnected.
## Notations
- In docstrings, we will write `Gal(L/E)` to denote the fixing subgroup of an intermediate field
`E`. That is, `Gal(L/E)` is the subgroup of `L āā[K] L` consisting of automorphisms that fix
every element of `E`. In particular, we distinguish between `L āā[E] L` and `Gal(L/E)`, since the
former is defined to be a subgroup of `L āā[K] L`, while the latter is a group in its own right.
## Implementation Notes
- `krull_topology K L` is defined as an instance for type class inference.
-/
open Classical
/-- Mapping intermediate fields along algebra equivalences preserves the partial order -/
theorem IntermediateField.map_mono {K L M : Type _} [Field K] [Field L] [Field M] [Algebra K L]
[Algebra K M] {E1 E2 : IntermediateField K L} (e : L āā[K] M) (h12 : E1 ⤠E2) :
E1.map e.toAlgHom ⤠E2.map e.toAlgHom :=
Set.image_subset e h12
#align intermediate_field.map_mono IntermediateField.map_mono
/-- Mapping intermediate fields along the identity does not change them -/
theorem IntermediateField.map_id {K L : Type _} [Field K] [Field L] [Algebra K L]
(E : IntermediateField K L) : E.map (AlgHom.id K L) = E :=
SetLike.coe_injective <| Set.image_id _
#align intermediate_field.map_id IntermediateField.map_id
/-- Mapping a finite dimensional intermediate field along an algebra equivalence gives
a finite-dimensional intermediate field. -/
instance im_finiteDimensional {K L : Type _} [Field K] [Field L] [Algebra K L]
{E : IntermediateField K L} (Ļ : L āā[K] L) [FiniteDimensional K E] :
FiniteDimensional K (E.map Ļ.toAlgHom) :=
LinearEquiv.finiteDimensional (IntermediateField.intermediateFieldMap Ļ E).toLinearEquiv
#align im_finite_dimensional im_finiteDimensional
/-- Given a field extension `L/K`, `finite_exts K L` is the set of
intermediate field extensions `L/E/K` such that `E/K` is finite -/
def finiteExts (K : Type _) [Field K] (L : Type _) [Field L] [Algebra K L] :
Set (IntermediateField K L) :=
{ E | FiniteDimensional K E }
#align finite_exts finiteExts
/-- Given a field extension `L/K`, `fixed_by_finite K L` is the set of
subsets `Gal(L/E)` of `L āā[K] L`, where `E/K` is finite -/
def fixedByFinite (K L : Type _) [Field K] [Field L] [Algebra K L] : Set (Subgroup (L āā[K] L)) :=
IntermediateField.fixingSubgroup '' finiteExts K L
#align fixed_by_finite fixedByFinite
/-- For an field extension `L/K`, the intermediate field `K` is finite-dimensional over `K` -/
theorem IntermediateField.finiteDimensional_bot (K L : Type _) [Field K] [Field L] [Algebra K L] :
FiniteDimensional K (ā„ : IntermediateField K L) :=
finiteDimensional_of_dim_eq_one IntermediateField.dim_bot
#align intermediate_field.finite_dimensional_bot IntermediateField.finiteDimensional_bot
/-- This lemma says that `Gal(L/K) = L āā[K] L` -/
theorem IntermediateField.fixingSubgroup.bot {K L : Type _} [Field K] [Field L] [Algebra K L] :
IntermediateField.fixingSubgroup (℠: IntermediateField K L) = ⤠:=
by
ext f
refine' āØfun _ => Subgroup.mem_top _, fun _ => _ā©
rintro āØx, hx : x ā (ā„ : IntermediateField K L)ā©
rw [IntermediateField.mem_bot] at hx
rcases hx with āØy, rflā©
exact f.commutes y
#align intermediate_field.fixing_subgroup.bot IntermediateField.fixingSubgroup.bot
/-- If `L/K` is a field extension, then we have `Gal(L/K) ā fixed_by_finite K L` -/
theorem top_fixedByFinite {K L : Type _} [Field K] [Field L] [Algebra K L] :
⤠ā fixedByFinite K L :=
āØā„, IntermediateField.finiteDimensional_bot K L, IntermediateField.fixingSubgroup.botā©
#align top_fixed_by_finite top_fixedByFinite
/-- If `E1` and `E2` are finite-dimensional intermediate fields, then so is their compositum.
This rephrases a result already in mathlib so that it is compatible with our type classes -/
theorem finiteDimensional_sup {K L : Type _} [Field K] [Field L] [Algebra K L]
(E1 E2 : IntermediateField K L) (h1 : FiniteDimensional K E1) (h2 : FiniteDimensional K E2) :
FiniteDimensional K ā„(E1 ā E2) :=
IntermediateField.finiteDimensional_sup E1 E2
#align finite_dimensional_sup finiteDimensional_sup
/-- An element of `L āā[K] L` is in `Gal(L/E)` if and only if it fixes every element of `E`-/
theorem IntermediateField.mem_fixingSubgroup_iff {K L : Type _} [Field K] [Field L] [Algebra K L]
(E : IntermediateField K L) (Ļ : L āā[K] L) : Ļ ā E.fixingSubgroup ā ā x : L, x ā E ā Ļ x = x :=
āØfun hĻ x hx => hĻ āØx, hxā©, fun h āØx, hxā© => h x hxā©
#align intermediate_field.mem_fixing_subgroup_iff IntermediateField.mem_fixingSubgroup_iff
/-- The map `E ⦠Gal(L/E)` is inclusion-reversing -/
theorem IntermediateField.fixingSubgroup.antimono {K L : Type _} [Field K] [Field L] [Algebra K L]
{E1 E2 : IntermediateField K L} (h12 : E1 ⤠E2) : E2.fixingSubgroup ⤠E1.fixingSubgroup :=
by
rintro Ļ hĻ āØx, hxā©
exact hĻ āØx, h12 hxā©
#align intermediate_field.fixing_subgroup.antimono IntermediateField.fixingSubgroup.antimono
/-- Given a field extension `L/K`, `gal_basis K L` is the filter basis on `L āā[K] L` whose sets
are `Gal(L/E)` for intermediate fields `E` with `E/K` finite dimensional -/
def galBasis (K L : Type _) [Field K] [Field L] [Algebra K L] : FilterBasis (L āā[K] L)
where
sets := Subgroup.carrier '' fixedByFinite K L
Nonempty := āØā¤, ā¤, top_fixedByFinite, rflā©
inter_sets := by
rintro X Y āØH1, āØE1, h_E1, rflā©, rflā© āØH2, āØE2, h_E2, rflā©, rflā©
use (IntermediateField.fixingSubgroup (E1 ā E2)).carrier
refine' āØāØ_, āØ_, finiteDimensional_sup E1 E2 h_E1 h_E2, rflā©, rflā©, _ā©
rw [Set.subset_inter_iff]
exact
āØIntermediateField.fixingSubgroup.antimono le_sup_left,
IntermediateField.fixingSubgroup.antimono le_sup_rightā©
#align gal_basis galBasis
/-- A subset of `L āā[K] L` is a member of `gal_basis K L` if and only if it is the underlying set
of `Gal(L/E)` for some finite subextension `E/K`-/
theorem mem_galBasis_iff (K L : Type _) [Field K] [Field L] [Algebra K L] (U : Set (L āā[K] L)) :
U ā galBasis K L ā U ā Subgroup.carrier '' fixedByFinite K L :=
Iff.rfl
#align mem_gal_basis_iff mem_galBasis_iff
/-- For a field extension `L/K`, `gal_group_basis K L` is the group filter basis on `L āā[K] L`
whose sets are `Gal(L/E)` for finite subextensions `E/K` -/
def galGroupBasis (K L : Type _) [Field K] [Field L] [Algebra K L] : GroupFilterBasis (L āā[K] L)
where
toFilterBasis := galBasis K L
one' := fun U āØH, hH, h2ā© => h2 āø H.one_mem
mul' U hU :=
āØU, hU, by
rcases hU with āØH, hH, rflā©
rintro x āØa, b, haH, hbH, rflā©
exact H.mul_mem haH hbHā©
inv' U hU :=
āØU, hU, by
rcases hU with āØH, hH, rflā©
exact fun _ => H.inv_mem'ā©
conj' := by
rintro Ļ U āØH, āØE, hE, rflā©, rflā©
let F : IntermediateField K L := E.map Ļ.symm.to_alg_hom
refine' āØF.fixing_subgroup.carrier, āØāØF.fixing_subgroup, āØF, _, rflā©, rflā©, fun g hg => _ā©ā©
Ā· apply im_finiteDimensional Ļ.symm
exact hE
change Ļ * g * Ļā»Ā¹ ā E.fixing_subgroup
rw [IntermediateField.mem_fixingSubgroup_iff]
intro x hx
change Ļ (g (Ļā»Ā¹ x)) = x
have h_in_F : Ļā»Ā¹ x ā F :=
āØx, hx, by
dsimp
rw [ā AlgEquiv.invFun_eq_symm]
rflā©
have h_g_fix : g (Ļā»Ā¹ x) = Ļā»Ā¹ x :=
by
rw [Subgroup.mem_carrier, IntermediateField.mem_fixingSubgroup_iff F g] at hg
exact hg (Ļā»Ā¹ x) h_in_F
rw [h_g_fix]
change Ļ (Ļā»Ā¹ x) = x
exact AlgEquiv.apply_symm_apply Ļ x
#align gal_group_basis galGroupBasis
/-- For a field extension `L/K`, `krull_topology K L` is the topological space structure on
`L āā[K] L` induced by the group filter basis `gal_group_basis K L` -/
instance krullTopology (K L : Type _) [Field K] [Field L] [Algebra K L] :
TopologicalSpace (L āā[K] L) :=
GroupFilterBasis.topology (galGroupBasis K L)
#align krull_topology krullTopology
/-- For a field extension `L/K`, the Krull topology on `L āā[K] L` makes it a topological group. -/
instance (K L : Type _) [Field K] [Field L] [Algebra K L] : TopologicalGroup (L āā[K] L) :=
GroupFilterBasis.is_topologicalGroup (galGroupBasis K L)
section KrullT2
open Topology Filter
/-- Let `L/E/K` be a tower of fields with `E/K` finite. Then `Gal(L/E)` is an open subgroup of
`L āā[K] L`. -/
theorem IntermediateField.fixingSubgroup_isOpen {K L : Type _} [Field K] [Field L] [Algebra K L]
(E : IntermediateField K L) [FiniteDimensional K E] :
IsOpen (E.fixingSubgroup : Set (L āā[K] L)) :=
by
have h_basis : E.fixing_subgroup.carrier ā galGroupBasis K L :=
āØE.fixing_subgroup, āØE, ā¹_āŗ, rflā©, rflā©
have h_nhd := GroupFilterBasis.mem_nhds_one (galGroupBasis K L) h_basis
exact Subgroup.isOpen_of_mem_nhds _ h_nhd
#align intermediate_field.fixing_subgroup_is_open IntermediateField.fixingSubgroup_isOpen
/-- Given a tower of fields `L/E/K`, with `E/K` finite, the subgroup `Gal(L/E) ⤠L āā[K] L` is
closed. -/
theorem IntermediateField.fixingSubgroup_isClosed {K L : Type _} [Field K] [Field L] [Algebra K L]
(E : IntermediateField K L) [FiniteDimensional K E] :
IsClosed (E.fixingSubgroup : Set (L āā[K] L)) :=
OpenSubgroup.isClosed āØE.fixingSubgroup, E.fixingSubgroup_isOpenā©
#align intermediate_field.fixing_subgroup_is_closed IntermediateField.fixingSubgroup_isClosed
/-- If `L/K` is an algebraic extension, then the Krull topology on `L āā[K] L` is Hausdorff. -/
theorem krullTopology_t2 {K L : Type _} [Field K] [Field L] [Algebra K L]
(h_int : Algebra.IsIntegral K L) : T2Space (L āā[K] L) :=
{
t2 := fun f g hfg => by
let Ļ := fā»Ā¹ * g
cases' FunLike.exists_ne hfg with x hx
have hĻx : Ļ x ā x := by
apply ne_of_apply_ne f
change f (f.symm (g x)) ā f x
rw [AlgEquiv.apply_symm_apply f (g x), ne_comm]
exact hx
let E : IntermediateField K L := IntermediateField.adjoin K {x}
let h_findim : FiniteDimensional K E := IntermediateField.adjoin.finiteDimensional (h_int x)
let H := E.fixing_subgroup
have h_basis : (H : Set (L āā[K] L)) ā galGroupBasis K L := āØH, āØE, āØh_findim, rflā©ā©, rflā©
have h_nhd := GroupFilterBasis.mem_nhds_one (galGroupBasis K L) h_basis
rw [mem_nhds_iff] at h_nhd
rcases h_nhd with āØW, hWH, hW_open, hW_1ā©
refine'
āØleftCoset f W, leftCoset g W,
āØhW_open.left_coset f, hW_open.left_coset g, āØ1, hW_1, mul_one _ā©, āØ1, hW_1, mul_one _ā©,
_ā©ā©
rw [Set.disjoint_left]
rintro Ļ āØw1, hw1, hā© āØw2, hw2, rflā©
rw [eq_inv_mul_iff_mul_eq.symm, ā mul_assoc, mul_inv_eq_iff_eq_mul.symm] at h
have h_in_H : w1 * w2ā»Ā¹ ā H := H.mul_mem (hWH hw1) (H.inv_mem (hWH hw2))
rw [h] at h_in_H
change Ļ ā E.fixing_subgroup at h_in_H
rw [IntermediateField.mem_fixingSubgroup_iff] at h_in_H
specialize h_in_H x
have hxE : x ā E := by
apply IntermediateField.subset_adjoin
apply Set.mem_singleton
exact hĻx (h_in_H hxE) }
#align krull_topology_t2 krullTopology_t2
end KrullT2
section TotallyDisconnected
/-- If `L/K` is an algebraic field extension, then the Krull topology on `L āā[K] L` is
totally disconnected. -/
theorem krullTopology_totally_disconnected {K L : Type _} [Field K] [Field L] [Algebra K L]
(h_int : Algebra.IsIntegral K L) : IsTotallyDisconnected (Set.univ : Set (L āā[K] L)) :=
by
apply isTotallyDisconnected_of_clopen_set
intro Ļ Ļ h_diff
have hĻĻ : Ļā»Ā¹ * Ļ ā 1 := by rwa [Ne.def, inv_mul_eq_one]
rcases FunLike.exists_ne hĻĻ with āØx, hx : (Ļā»Ā¹ * Ļ) x ā xā©
let E := IntermediateField.adjoin K ({x} : Set L)
haveI := IntermediateField.adjoin.finiteDimensional (h_int x)
refine'
āØleftCoset Ļ E.fixing_subgroup,
āØE.fixing_subgroup_is_open.left_coset Ļ, E.fixing_subgroup_is_closed.left_coset Ļā©,
āØ1, E.fixing_subgroup.one_mem', mul_one Ļā©, _ā©
simp only [mem_leftCoset_iff, SetLike.mem_coe, IntermediateField.mem_fixingSubgroup_iff,
not_forall]
exact āØx, IntermediateField.mem_adjoin_simple_self K x, hxā©
#align krull_topology_totally_disconnected krullTopology_totally_disconnected
end TotallyDisconnected
|
postulate
A : Set
module _ where
{-# POLARITY A #-}
|
{-# Language TypeApplications #-}
module PointSpec where
import Test.Hspec
import Test.QuickCheck hiding (scale)
import Test.Invariant
import Data.Complex
import Geometry
import Geometry.Testing
spec :: Spec
spec = describe "Point" $ do
describe "Affinity" $ do
it "1" $ property $ cmp `inverts` Point
it "2" $ property $ Point `inverts` cmp
it "3" $ property $ cmp `inverts` (Point . cmp)
it "4" $ property $ (Point . cmp) `inverts` cmp
describe "pointOn" $ do
it "1" $ xy (pointOn (aCircle # scale 2) 0) ~= (2, 0)
it "2" $ xy (pointOn (aCircle # scale 2) 0.5) ~= (-2, 0)
it "3" $ property $ \(AnyCircle c) t -> c `isContaining` pointOn c t
it "4" $ property $ \(AnyLine l) t -> l `isContaining` pointOn l t
it "5" $ property $ \n t ->
let p = regularPoly (3 + abs n)
in p `isContaining` pointOn p t
describe "aligned" $ do
it "1" $ property $ \(AnyLine l) xs ->
length xs > 1 ==> aligned (param l <$> xs)
it "2" $ property $ \(Position a) (Position b) (Position c) ->
(aligned [a,b,c] ==> isDegenerate (Triangle [a,b,c])) .&.
(not (aligned [a,b,c]) ==> not (isDegenerate (Triangle [a,b,c])))
describe "APoint" $ do
it "1" $ property $ toPoint `inverts` (asPoint @XY)
it "2" $ property $ toPoint `inverts` (asPoint @Cmp)
it "3" $ property $ toPoint `inverts` (asPoint @(Maybe Point))
|
State Before: p : ā
R S : Type u
Ļ : Type ?u.597461
idx : Type ?u.597464
instā¹ : CommRing R
instā : CommRing S
g : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R
f : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R ā š R
hg : IsPoly p g
hf : IsPolyā p f
⢠IsPolyā p fun R _Rcr x y => g (f x y) State After: case mk'.intro
p : ā
R S : Type u
Ļ : Type ?u.597461
idx : Type ?u.597464
instā¹ : CommRing R
instā : CommRing S
g : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R
f : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R ā š R
hg : IsPoly p g
Ļ : ā ā MvPolynomial (Fin 2 Ć ā) ā¤
hf : ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R), (f x y).coeff = fun n => peval (Ļ n) ![x.coeff, y.coeff]
⢠IsPolyā p fun R _Rcr x y => g (f x y) Tactic: obtain āØĻ, hfā© := hf State Before: case mk'.intro
p : ā
R S : Type u
Ļ : Type ?u.597461
idx : Type ?u.597464
instā¹ : CommRing R
instā : CommRing S
g : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R
f : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R ā š R
hg : IsPoly p g
Ļ : ā ā MvPolynomial (Fin 2 Ć ā) ā¤
hf : ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R), (f x y).coeff = fun n => peval (Ļ n) ![x.coeff, y.coeff]
⢠IsPolyā p fun R _Rcr x y => g (f x y) State After: case mk'.intro.mk'.intro
p : ā
R S : Type u
Ļ : Type ?u.597461
idx : Type ?u.597464
instā¹ : CommRing R
instā : CommRing S
g : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R
f : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R ā š R
Ļ : ā ā MvPolynomial (Fin 2 Ć ā) ā¤
hf : ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R), (f x y).coeff = fun n => peval (Ļ n) ![x.coeff, y.coeff]
Ļ : ā ā MvPolynomial ā ā¤
hg : ā ā¦R : Type u_1⦠[inst : CommRing R] (x : š R), (g x).coeff = fun n => ā(aeval x.coeff) (Ļ n)
⢠IsPolyā p fun R _Rcr x y => g (f x y) Tactic: obtain āØĻ, hgā© := hg State Before: case mk'.intro.mk'.intro
p : ā
R S : Type u
Ļ : Type ?u.597461
idx : Type ?u.597464
instā¹ : CommRing R
instā : CommRing S
g : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R
f : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R ā š R
Ļ : ā ā MvPolynomial (Fin 2 Ć ā) ā¤
hf : ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R), (f x y).coeff = fun n => peval (Ļ n) ![x.coeff, y.coeff]
Ļ : ā ā MvPolynomial ā ā¤
hg : ā ā¦R : Type u_1⦠[inst : CommRing R] (x : š R), (g x).coeff = fun n => ā(aeval x.coeff) (Ļ n)
⢠IsPolyā p fun R _Rcr x y => g (f x y) State After: case mk'.intro.mk'.intro
p : ā
R S : Type u
Ļ : Type ?u.597461
idx : Type ?u.597464
instā¹ : CommRing R
instā : CommRing S
g : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R
f : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R ā š R
Ļ : ā ā MvPolynomial (Fin 2 Ć ā) ā¤
hf : ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R), (f x y).coeff = fun n => peval (Ļ n) ![x.coeff, y.coeff]
Ļ : ā ā MvPolynomial ā ā¤
hg : ā ā¦R : Type u_1⦠[inst : CommRing R] (x : š R), (g x).coeff = fun n => ā(aeval x.coeff) (Ļ n)
⢠ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R),
(g (f x y)).coeff = fun n => peval ((fun n => ā(bindā Ļ) (Ļ n)) n) ![x.coeff, y.coeff] Tactic: use fun n => bindā Ļ (Ļ n) State Before: case mk'.intro.mk'.intro
p : ā
R S : Type u
Ļ : Type ?u.597461
idx : Type ?u.597464
instā¹ : CommRing R
instā : CommRing S
g : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R
f : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R ā š R
Ļ : ā ā MvPolynomial (Fin 2 Ć ā) ā¤
hf : ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R), (f x y).coeff = fun n => peval (Ļ n) ![x.coeff, y.coeff]
Ļ : ā ā MvPolynomial ā ā¤
hg : ā ā¦R : Type u_1⦠[inst : CommRing R] (x : š R), (g x).coeff = fun n => ā(aeval x.coeff) (Ļ n)
⢠ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R),
(g (f x y)).coeff = fun n => peval ((fun n => ā(bindā Ļ) (Ļ n)) n) ![x.coeff, y.coeff] State After: case mk'.intro.mk'.intro
p : ā
R S : Type u
Ļ : Type ?u.597461
idx : Type ?u.597464
instā² : CommRing R
instā¹ : CommRing S
g : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R
f : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R ā š R
Ļ : ā ā MvPolynomial (Fin 2 Ć ā) ā¤
hf : ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R), (f x y).coeff = fun n => peval (Ļ n) ![x.coeff, y.coeff]
Ļ : ā ā MvPolynomial ā ā¤
hg : ā ā¦R : Type u_1⦠[inst : CommRing R] (x : š R), (g x).coeff = fun n => ā(aeval x.coeff) (Ļ n)
Rā : Type u_1
instā : CommRing Rā
xā yā : š Rā
⢠(g (f xā yā)).coeff = fun n => peval ((fun n => ā(bindā Ļ) (Ļ n)) n) ![xā.coeff, yā.coeff] Tactic: intros State Before: case mk'.intro.mk'.intro
p : ā
R S : Type u
Ļ : Type ?u.597461
idx : Type ?u.597464
instā² : CommRing R
instā¹ : CommRing S
g : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R
f : ā¦R : Type u_1⦠ā [inst : CommRing R] ā š R ā š R ā š R
Ļ : ā ā MvPolynomial (Fin 2 Ć ā) ā¤
hf : ā ā¦R : Type u_1⦠[inst : CommRing R] (x y : š R), (f x y).coeff = fun n => peval (Ļ n) ![x.coeff, y.coeff]
Ļ : ā ā MvPolynomial ā ā¤
hg : ā ā¦R : Type u_1⦠[inst : CommRing R] (x : š R), (g x).coeff = fun n => ā(aeval x.coeff) (Ļ n)
Rā : Type u_1
instā : CommRing Rā
xā yā : š Rā
⢠(g (f xā yā)).coeff = fun n => peval ((fun n => ā(bindā Ļ) (Ļ n)) n) ![xā.coeff, yā.coeff] State After: no goals Tactic: simp only [peval, aeval_bindā, Function.comp, hg, hf] |
! { dg-do run }
! { dg-options "-fno-range-check" }
! { dg-add-options ieee }
!
! PR fortran/34192
!
! Test compile-time implementation of NEAREST
!
program test
implicit none
! Single precision
! 0+ > 0
if (nearest(0.0, 1.0) &
<= 0.0) &
STOP 1
! 0++ > 0+
if (nearest(nearest(0.0, 1.0), 1.0) &
<= nearest(0.0, 1.0)) &
STOP 2
! 0+++ > 0++
if (nearest(nearest(nearest(0.0, 1.0), 1.0), 1.0) &
<= nearest(nearest(0.0, 1.0), 1.0)) &
STOP 3
! 0+- = 0
if (nearest(nearest(0.0, 1.0), -1.0) &
/= 0.0) &
STOP 4
! 0++- = 0+
if (nearest(nearest(nearest(0.0, 1.0), 1.0), -1.0) &
/= nearest(0.0, 1.0)) &
STOP 5
! 0++-- = 0
if (nearest(nearest(nearest(nearest(0.0, 1.0), 1.0), -1.0), -1.0) &
/= 0.0) &
STOP 6
! 0- < 0
if (nearest(0.0, -1.0) &
>= 0.0) &
STOP 7
! 0-- < 0+
if (nearest(nearest(0.0, -1.0), -1.0) &
>= nearest(0.0, -1.0)) &
STOP 8
! 0--- < 0--
if (nearest(nearest(nearest(0.0, -1.0), -1.0), -1.0) &
>= nearest(nearest(0.0, -1.0), -1.0)) &
STOP 9
! 0-+ = 0
if (nearest(nearest(0.0, -1.0), 1.0) &
/= 0.0) &
STOP 10
! 0--+ = 0-
if (nearest(nearest(nearest(0.0, -1.0), -1.0), 1.0) &
/= nearest(0.0, -1.0)) &
STOP 11
! 0--++ = 0
if (nearest(nearest(nearest(nearest(0.0, -1.0), -1.0), 1.0), 1.0) &
/= 0.0) &
STOP 12
! 42++ > 42+
if (nearest(nearest(42.0, 1.0), 1.0) &
<= nearest(42.0, 1.0)) &
STOP 13
! 42-- < 42-
if (nearest(nearest(42.0, -1.0), -1.0) &
>= nearest(42.0, -1.0)) &
STOP 14
! 42-+ = 42
if (nearest(nearest(42.0, -1.0), 1.0) &
/= 42.0) &
STOP 15
! 42+- = 42
if (nearest(nearest(42.0, 1.0), -1.0) &
/= 42.0) &
STOP 16
! INF+ = INF
if (nearest(1.0/0.0, 1.0) /= 1.0/0.0) STOP 17
! -INF- = -INF
if (nearest(-1.0/0.0, -1.0) /= -1.0/0.0) STOP 18
! NAN- = NAN
if (.not.isnan(nearest(0.0d0/0.0, 1.0))) STOP 19
! NAN+ = NAN
if (.not.isnan(nearest(0.0d0/0.0, -1.0))) STOP 20
! Double precision
! 0+ > 0
if (nearest(0.0d0, 1.0) &
<= 0.0d0) &
STOP 21
! 0++ > 0+
if (nearest(nearest(0.0d0, 1.0), 1.0) &
<= nearest(0.0d0, 1.0)) &
STOP 22
! 0+++ > 0++
if (nearest(nearest(nearest(0.0d0, 1.0), 1.0), 1.0) &
<= nearest(nearest(0.0d0, 1.0), 1.0)) &
STOP 23
! 0+- = 0
if (nearest(nearest(0.0d0, 1.0), -1.0) &
/= 0.0d0) &
STOP 24
! 0++- = 0+
if (nearest(nearest(nearest(0.0d0, 1.0), 1.0), -1.0) &
/= nearest(0.0d0, 1.0)) &
STOP 25
! 0++-- = 0
if (nearest(nearest(nearest(nearest(0.0d0, 1.0), 1.0), -1.0), -1.0) &
/= 0.0d0) &
STOP 26
! 0- < 0
if (nearest(0.0d0, -1.0) &
>= 0.0d0) &
STOP 27
! 0-- < 0+
if (nearest(nearest(0.0d0, -1.0), -1.0) &
>= nearest(0.0d0, -1.0)) &
STOP 28
! 0--- < 0--
if (nearest(nearest(nearest(0.0d0, -1.0), -1.0), -1.0) &
>= nearest(nearest(0.0d0, -1.0), -1.0)) &
STOP 29
! 0-+ = 0
if (nearest(nearest(0.0d0, -1.0), 1.0) &
/= 0.0d0) &
STOP 30
! 0--+ = 0-
if (nearest(nearest(nearest(0.0d0, -1.0), -1.0), 1.0) &
/= nearest(0.0d0, -1.0)) &
STOP 31
! 0--++ = 0
if (nearest(nearest(nearest(nearest(0.0d0, -1.0), -1.0), 1.0), 1.0) &
/= 0.0d0) &
STOP 32
! 42++ > 42+
if (nearest(nearest(42.0d0, 1.0), 1.0) &
<= nearest(42.0d0, 1.0)) &
STOP 33
! 42-- < 42-
if (nearest(nearest(42.0d0, -1.0), -1.0) &
>= nearest(42.0d0, -1.0)) &
STOP 34
! 42-+ = 42
if (nearest(nearest(42.0d0, -1.0), 1.0) &
/= 42.0d0) &
STOP 35
! 42+- = 42
if (nearest(nearest(42.0d0, 1.0), -1.0) &
/= 42.0d0) &
STOP 36
! INF+ = INF
if (nearest(1.0d0/0.0d0, 1.0) /= 1.0d0/0.0d0) STOP 37
! -INF- = -INF
if (nearest(-1.0d0/0.0d0, -1.0) /= -1.0d0/0.0d0) STOP 38
! NAN- = NAN
if (.not.isnan(nearest(0.0d0/0.0, 1.0))) STOP 39
! NAN+ = NAN
if (.not.isnan(nearest(0.0d0/0.0, -1.0))) STOP 40
end program test
|
/-
Copyright (c) 2018 Jan-David Salchow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow, Patrick Massot
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.bases
import Mathlib.topology.subset_properties
import Mathlib.topology.metric_space.basic
import Mathlib.PostPort
universes u_1 u_3 l u_2
namespace Mathlib
/-!
# Sequences in topological spaces
In this file we define sequences in topological spaces and show how they are related to
filters and the topology. In particular, we
* define the sequential closure of a set and prove that it's contained in the closure,
* define a type class "sequential_space" in which closure and sequential closure agree,
* define sequential continuity and show that it coincides with continuity in sequential spaces,
* provide an instance that shows that every first-countable (and in particular metric) space is
a sequential space.
* define sequential compactness, prove that compactness implies sequential compactness in first
countable spaces, and prove they are equivalent for uniform spaces having a countable uniformity
basis (in particular metric spaces).
-/
/-! ### Sequential closures, sequential continuity, and sequential spaces. -/
/-- A sequence converges in the sence of topological spaces iff the associated statement for filter
holds. -/
theorem topological_space.seq_tendsto_iff {α : Type u_1} [topological_space α] {x : ā ā α}
{limit : α} :
filter.tendsto x filter.at_top (nhds limit) ā
ā (U : set α), limit ā U ā is_open U ā ā (N : ā), ā (n : ā), n ā„ N ā x n ā U :=
sorry
/-- The sequential closure of a subset M ā α of a topological space α is
the set of all p ā α which arise as limit of sequences in M. -/
def sequential_closure {α : Type u_1} [topological_space α] (M : set α) : set α :=
set_of
fun (p : α) => ā (x : ā ā α), (ā (n : ā), x n ā M) ā§ filter.tendsto x filter.at_top (nhds p)
theorem subset_sequential_closure {α : Type u_1} [topological_space α] (M : set α) :
M ā sequential_closure M :=
fun (p : α) (_x : p ā M) =>
(fun (this : p ā sequential_closure M) => this)
(Exists.intro (fun (n : ā) => p) { left := fun (n : ā) => _x, right := tendsto_const_nhds })
/-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`,
the limit belongs to `s` as well. -/
def is_seq_closed {α : Type u_1} [topological_space α] (s : set α) := s = sequential_closure s
/-- A convenience lemma for showing that a set is sequentially closed. -/
theorem is_seq_closed_of_def {α : Type u_1} [topological_space α] {A : set α}
(h :
ā (x : ā ā α) (p : α),
(ā (n : ā), x n ā A) ā filter.tendsto x filter.at_top (nhds p) ā p ā A) :
is_seq_closed A :=
sorry
/-- The sequential closure of a set is contained in the closure of that set.
The converse is not true. -/
theorem sequential_closure_subset_closure {α : Type u_1} [topological_space α] (M : set α) :
sequential_closure M ā closure M :=
sorry
/-- A set is sequentially closed if it is closed. -/
theorem is_seq_closed_of_is_closed {α : Type u_1} [topological_space α] (M : set α)
(_x : is_closed M) : is_seq_closed M :=
(fun (this : sequential_closure M ā M) =>
set.eq_of_subset_of_subset (subset_sequential_closure M) this)
(trans_rel_left has_subset.subset (sequential_closure_subset_closure M)
(is_closed.closure_eq _x))
/-- The limit of a convergent sequence in a sequentially closed set is in that set.-/
theorem mem_of_is_seq_closed {α : Type u_1} [topological_space α] {A : set α} (_x : is_seq_closed A)
{x : ā ā α} :
(ā (n : ā), x n ā A) ā ā {limit : α}, filter.tendsto x filter.at_top (nhds limit) ā limit ā A :=
sorry
/-- The limit of a convergent sequence in a closed set is in that set.-/
theorem mem_of_is_closed_sequential {α : Type u_1} [topological_space α] {A : set α}
(_x : is_closed A) {x : ā ā α} :
(ā (n : ā), x n ā A) ā ā {limit : α}, filter.tendsto x filter.at_top (nhds limit) ā limit ā A :=
fun (_x_1 : ā (n : ā), x n ā A) {limit : α}
(_x_2 : filter.tendsto x filter.at_top (nhds limit)) =>
mem_of_is_seq_closed (is_seq_closed_of_is_closed A _x) _x_1 _x_2
/-- A sequential space is a space in which 'sequences are enough to probe the topology'. This can be
formalised by demanding that the sequential closure and the closure coincide. The following
statements show that other topological properties can be deduced from sequences in sequential
spaces. -/
class sequential_space (α : Type u_3) [topological_space α] where
sequential_closure_eq_closure : ā (M : set α), sequential_closure M = closure M
/-- In a sequential space, a set is closed iff it's sequentially closed. -/
theorem is_seq_closed_iff_is_closed {α : Type u_1} [topological_space α] [sequential_space α]
{M : set α} : is_seq_closed M ā is_closed M :=
sorry
/-- In a sequential space, a point belongs to the closure of a set iff it is a limit of a sequence
taking values in this set. -/
theorem mem_closure_iff_seq_limit {α : Type u_1} [topological_space α] [sequential_space α]
{s : set α} {a : α} :
a ā closure s ā ā (x : ā ā α), (ā (n : ā), x n ā s) ā§ filter.tendsto x filter.at_top (nhds a) :=
sorry
/-- A function between topological spaces is sequentially continuous if it commutes with limit of
convergent sequences. -/
def sequentially_continuous {α : Type u_1} {β : Type u_2} [topological_space α]
[topological_space β] (f : α ā β) :=
ā (x : ā ā α) {limit : α},
filter.tendsto x filter.at_top (nhds limit) ā
filter.tendsto (f ā x) filter.at_top (nhds (f limit))
/- A continuous function is sequentially continuous. -/
theorem continuous.to_sequentially_continuous {α : Type u_1} {β : Type u_2} [topological_space α]
[topological_space β] {f : α ā β} (_x : continuous f) : sequentially_continuous f :=
sorry
/-- In a sequential space, continuity and sequential continuity coincide. -/
theorem continuous_iff_sequentially_continuous {α : Type u_1} {β : Type u_2} [topological_space α]
[topological_space β] {f : α ā β} [sequential_space α] :
continuous f ā sequentially_continuous f :=
sorry
namespace topological_space
namespace first_countable_topology
/-- Every first-countable space is sequential. -/
protected instance sequential_space {α : Type u_1} [topological_space α]
[first_countable_topology α] : sequential_space α :=
sequential_space.mk
((fun (this : ā (M : set α), sequential_closure M = closure M) => this)
fun (M : set α) =>
(fun (this : closure M ā sequential_closure M) =>
set.subset.antisymm (sequential_closure_subset_closure M) this)
fun (p : α) (hp : p ā closure M) => sorry)
end first_countable_topology
end topological_space
/-- A set `s` is sequentially compact if every sequence taking values in `s` has a
converging subsequence. -/
def is_seq_compact {α : Type u_1} [topological_space α] (s : set α) :=
ā {u : ā ā α},
(ā (n : ā), u n ā s) ā
ā (x : α),
ā (H : x ā s), ā (Ļ : ā ā ā), strict_mono Ļ ā§ filter.tendsto (u ā Ļ) filter.at_top (nhds x)
/-- A space `α` is sequentially compact if every sequence in `α` has a
converging subsequence. -/
class seq_compact_space (α : Type u_3) [topological_space α] where
seq_compact_univ : is_seq_compact set.univ
theorem is_seq_compact.subseq_of_frequently_in {α : Type u_1} [topological_space α] {s : set α}
(hs : is_seq_compact s) {u : ā ā α}
(hu : filter.frequently (fun (n : ā) => u n ā s) filter.at_top) :
ā (x : α),
ā (H : x ā s),
ā (Ļ : ā ā ā), strict_mono Ļ ā§ filter.tendsto (u ā Ļ) filter.at_top (nhds x) :=
sorry
theorem seq_compact_space.tendsto_subseq {α : Type u_1} [topological_space α] [seq_compact_space α]
(u : ā ā α) :
ā (x : α), ā (Ļ : ā ā ā), strict_mono Ļ ā§ filter.tendsto (u ā Ļ) filter.at_top (nhds x) :=
sorry
theorem is_compact.is_seq_compact {α : Type u_1} [topological_space α]
[topological_space.first_countable_topology α] {s : set α} (hs : is_compact s) :
is_seq_compact s :=
sorry
theorem is_compact.tendsto_subseq' {α : Type u_1} [topological_space α]
[topological_space.first_countable_topology α] {s : set α} {u : ā ā α} (hs : is_compact s)
(hu : filter.frequently (fun (n : ā) => u n ā s) filter.at_top) :
ā (x : α),
ā (H : x ā s),
ā (Ļ : ā ā ā), strict_mono Ļ ā§ filter.tendsto (u ā Ļ) filter.at_top (nhds x) :=
is_seq_compact.subseq_of_frequently_in (is_compact.is_seq_compact hs) hu
theorem is_compact.tendsto_subseq {α : Type u_1} [topological_space α]
[topological_space.first_countable_topology α] {s : set α} {u : ā ā α} (hs : is_compact s)
(hu : ā (n : ā), u n ā s) :
ā (x : α),
ā (H : x ā s),
ā (Ļ : ā ā ā), strict_mono Ļ ā§ filter.tendsto (u ā Ļ) filter.at_top (nhds x) :=
is_compact.is_seq_compact hs hu
protected instance first_countable_topology.seq_compact_of_compact {α : Type u_1}
[topological_space α] [topological_space.first_countable_topology α] [compact_space α] :
seq_compact_space α :=
seq_compact_space.mk (is_compact.is_seq_compact compact_univ)
theorem compact_space.tendsto_subseq {α : Type u_1} [topological_space α]
[topological_space.first_countable_topology α] [compact_space α] (u : ā ā α) :
ā (x : α), ā (Ļ : ā ā ā), strict_mono Ļ ā§ filter.tendsto (u ā Ļ) filter.at_top (nhds x) :=
seq_compact_space.tendsto_subseq u
theorem lebesgue_number_lemma_seq {β : Type u_2} [uniform_space β] {s : set β} {ι : Type u_1}
{c : ι ā set β} (hs : is_seq_compact s) (hcā : ā (i : ι), is_open (c i))
(hcā : s ā set.Union fun (i : ι) => c i) (hU : filter.is_countably_generated (uniformity β)) :
ā (V : set (β à β)),
ā (H : V ā uniformity β),
symmetric_rel V ā§ ā (x : β), x ā s ā ā (i : ι), uniform_space.ball x V ā c i :=
sorry
theorem is_seq_compact.totally_bounded {β : Type u_2} [uniform_space β] {s : set β}
(h : is_seq_compact s) : totally_bounded s :=
sorry
protected theorem is_seq_compact.is_compact {β : Type u_2} [uniform_space β] {s : set β}
(h : filter.is_countably_generated (uniformity β)) (hs : is_seq_compact s) : is_compact s :=
sorry
protected theorem uniform_space.compact_iff_seq_compact {β : Type u_2} [uniform_space β] {s : set β}
(h : filter.is_countably_generated (uniformity β)) : is_compact s ā is_seq_compact s :=
{ mp := fun (H : is_compact s) => is_compact.is_seq_compact H,
mpr := fun (H : is_seq_compact s) => is_seq_compact.is_compact h H }
theorem uniform_space.compact_space_iff_seq_compact_space {β : Type u_2} [uniform_space β]
(H : filter.is_countably_generated (uniformity β)) : compact_space β ā seq_compact_space β :=
sorry
/-- A version of Bolzano-Weistrass: in a metric space, is_compact s ā is_seq_compact s -/
theorem metric.compact_iff_seq_compact {β : Type u_2} [metric_space β] {s : set β} :
is_compact s ā is_seq_compact s :=
uniform_space.compact_iff_seq_compact emetric.uniformity_has_countable_basis
/-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ā^n$),
every bounded sequence has a converging subsequence. This version assumes only
that the sequence is frequently in some bounded set. -/
theorem tendsto_subseq_of_frequently_bounded {β : Type u_2} [metric_space β] {s : set β}
[proper_space β] (hs : metric.bounded s) {u : ā ā β}
(hu : filter.frequently (fun (n : ā) => u n ā s) filter.at_top) :
ā (b : β),
ā (H : b ā closure s),
ā (Ļ : ā ā ā), strict_mono Ļ ā§ filter.tendsto (u ā Ļ) filter.at_top (nhds b) :=
sorry
/-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ā^n$),
every bounded sequence has a converging subsequence. -/
theorem tendsto_subseq_of_bounded {β : Type u_2} [metric_space β] {s : set β} [proper_space β]
(hs : metric.bounded s) {u : ā ā β} (hu : ā (n : ā), u n ā s) :
ā (b : β),
ā (H : b ā closure s),
ā (Ļ : ā ā ā), strict_mono Ļ ā§ filter.tendsto (u ā Ļ) filter.at_top (nhds b) :=
tendsto_subseq_of_frequently_bounded hs (filter.frequently_of_forall hu)
theorem metric.compact_space_iff_seq_compact_space {β : Type u_2} [metric_space β] :
compact_space β ā seq_compact_space β :=
uniform_space.compact_space_iff_seq_compact_space emetric.uniformity_has_countable_basis
theorem seq_compact.lebesgue_number_lemma_of_metric {β : Type u_2} [metric_space β] {s : set β}
{ι : Type u_1} {c : ι ā set β} (hs : is_seq_compact s) (hcā : ā (i : ι), is_open (c i))
(hcā : s ā set.Union fun (i : ι) => c i) :
ā (Ī“ : ā), ā (H : Ī“ > 0), ā (x : β), x ā s ā ā (i : ι), metric.ball x Ī“ ā c i :=
sorry
end Mathlib |
data IsS : (Nat -> Nat) -> Type where
Indeed : (s : Nat -> Nat) -> s === S -> IsS s
------------------------------------------------------------------------
-- 1.
-- the S pattern is forced by the fact the parameter is instantiated
-- so everything is fine
-- either left implicit
indeed : IsS S -> S === S
indeed (Indeed _ eq) = eq
-- or made explicit
indeed2 : IsS S -> S === S
indeed2 (Indeed S eq) = eq
------------------------------------------------------------------------
-- 2. The S pattern is not forced by the parameter (a generic variable)
-- either don't match on it
indeed3 : IsS s -> s === S
indeed3 (Indeed s eq) = eq
-- or match on the proof that forces it
indeed4 : IsS s -> s === S
indeed4 (Indeed S Refl) = Refl
-- ^ forced by Refl
-- If you don't: too bad!
fail : IsS s -> s === S
fail (Indeed S eq) = eq
-- ^ not Refl, S not forced! OUCH
|
Formal statement is: lemma (in first_countable_topology) first_countable_basis_Int_stableE: obtains \<A> where "countable \<A>" "\<And>A. A \<in> \<A> \<Longrightarrow> x \<in> A" "\<And>A. A \<in> \<A> \<Longrightarrow> open A" "\<And>S. open S \<Longrightarrow> x \<in> S \<Longrightarrow> (\<exists>A\<in>\<A>. A \<subseteq> S)" "\<And>A B. A \<in> \<A> \<Longrightarrow> B \<in> \<A> \<Longrightarrow> A \<inter> B \<in> \<A>" Informal statement is: If a topological space is first countable, then there exists a countable basis for the topology at every point. |
#define BOOST_TEST_MODULE TestrocFFT
#include "libraries/rocfft/rocfft_helper.hpp"
#include <hip/hip_runtime_api.h>
#include <hip/hip_vector_types.h>
#include <rocfft.h>
#include <boost/test/included/unit_test.hpp> // Single-header usage variant
#include <cstdint>
#include <iostream>
#include <vector>
#include <complex>
BOOST_AUTO_TEST_CASE( FFT1DSmall, * boost::unit_test::tolerance(0.0001f) )
{
// rocFFT gpu compute
// ========================================
CHECK_HIP(rocfft_setup());
std::size_t N = 2 << 10; //should be small enough to not need a work_buffer
std::size_t Nbytes = N * sizeof(float2);
// Create HIP device buffer
float2 *x;
CHECK_HIP(hipMalloc(&x, Nbytes));
// Initialize data
std::vector<float2> cx(N);
for (std::size_t i = 0; i < N; i++)
{
cx[i].x = 1;
cx[i].y = -1;
}
// Copy data to device
CHECK_HIP(hipMemcpy(x, cx.data(), Nbytes, hipMemcpyHostToDevice));
// Create fwd rocFFT fwd
rocfft_plan fwd = nullptr;
std::size_t length = N;
CHECK_HIP(
rocfft_plan_create(&fwd,
rocfft_placement_inplace,
rocfft_transform_type_complex_forward,
rocfft_precision_single,
1, &length, 1, nullptr));
// Create bwd rocFFT bwd
rocfft_plan bwd = nullptr;
CHECK_HIP(
rocfft_plan_create(&bwd,
rocfft_placement_inplace,
rocfft_transform_type_complex_inverse,
rocfft_precision_single,
1, &length, 1, nullptr));
// Execute fwd
CHECK_HIP(rocfft_execute(fwd, (void**) &x, nullptr, nullptr));
// Wait for execution to finish
CHECK_HIP(hipDeviceSynchronize());
// Destroy fwd
CHECK_HIP(rocfft_plan_destroy(fwd));
// Execute bwd
CHECK_HIP(rocfft_execute(bwd, (void**) &x, nullptr, nullptr));
// Wait for execution to finish
CHECK_HIP(hipDeviceSynchronize());
// Destroy bwd
CHECK_HIP(rocfft_plan_destroy(bwd));
// Copy result back to host
std::vector<float2> y(N);
CHECK_HIP(hipMemcpy(y.data(), x, Nbytes, hipMemcpyDeviceToHost));
// Print results
for (std::size_t i = 0; i < N; i++)
{
y[i].x *= 1.f/N;
y[i].y *= 1.f/N;
BOOST_TEST( cx[i].x == y[i].x );
BOOST_TEST( cx[i].y == y[i].y );
}
// Free device buffer
CHECK_HIP(hipFree(x));
CHECK_HIP(rocfft_cleanup());
}
BOOST_AUTO_TEST_CASE( FFT1D, * boost::unit_test::tolerance(0.0001f) )
{
// rocFFT gpu compute
// ========================================
CHECK_HIP(rocfft_setup());
std::size_t N = 128 << 10; //needs a work_buffer
std::size_t Nbytes = N * sizeof(float2);
// Create HIP device buffer
float2 *x;
CHECK_HIP(hipMalloc(&x, Nbytes));
// Initialize data
std::vector<float2> cx(N);
for (std::size_t i = 0; i < N; i++)
{
cx[i].x = 1;
cx[i].y = -1;
}
// Copy data to device
CHECK_HIP(hipMemcpy(x, cx.data(), Nbytes, hipMemcpyHostToDevice));
// Create fwd rocFFT fwd
rocfft_plan fwd = nullptr;
std::size_t length = N;
CHECK_HIP(
rocfft_plan_create(&fwd,
rocfft_placement_inplace,
rocfft_transform_type_complex_forward,
rocfft_precision_single,
1, &length, 1, nullptr));
// Create bwd rocFFT bwd
rocfft_plan bwd = nullptr;
CHECK_HIP(
rocfft_plan_create(&bwd,
rocfft_placement_inplace,
rocfft_transform_type_complex_inverse,
rocfft_precision_single,
1, &length, 1, nullptr));
// Setup work buffer
void *workBuffer = nullptr;
size_t workBufferSize_fwd = 0;
CHECK_HIP(rocfft_plan_get_work_buffer_size(fwd, &workBufferSize_fwd));
size_t workBufferSize_bwd = 0;
CHECK_HIP(rocfft_plan_get_work_buffer_size(bwd, &workBufferSize_bwd));
BOOST_REQUIRE_EQUAL(workBufferSize_bwd,workBufferSize_fwd);
// Setup exec info to pass work buffer to the library
rocfft_execution_info info = nullptr;
CHECK_HIP(rocfft_execution_info_create(&info));
if(workBufferSize_fwd > 0)
{
CHECK_HIP(hipMalloc(&workBuffer, workBufferSize_fwd));
CHECK_HIP(rocfft_execution_info_set_work_buffer(info, workBuffer, workBufferSize_fwd));
}
// Execute fwd
CHECK_HIP(rocfft_execute(fwd, (void**) &x, nullptr, info));
// Wait for execution to finish
CHECK_HIP(hipDeviceSynchronize());
// Destroy fwd
CHECK_HIP(rocfft_plan_destroy(fwd));
// Execute bwd
CHECK_HIP(rocfft_execute(bwd, (void**) &x, nullptr, info));
// Wait for execution to finish
CHECK_HIP(hipDeviceSynchronize());
// Destroy bwd
CHECK_HIP(rocfft_plan_destroy(bwd));
if(workBuffer)
CHECK_HIP(hipFree(workBuffer));
CHECK_HIP(rocfft_execution_info_destroy(info));
// Copy result back to host
std::vector<float2> y(N);
CHECK_HIP(hipMemcpy(y.data(), x, Nbytes, hipMemcpyDeviceToHost));
// Print results
for (std::size_t i = 0; i < N; i++)
{
y[i].x *= 1.f/N;
y[i].y *= 1.f/N;
BOOST_TEST( cx[i].x == y[i].x );
BOOST_TEST( cx[i].y == y[i].y );
}
// Free device buffer
CHECK_HIP(hipFree(x));
CHECK_HIP(rocfft_cleanup());
}
BOOST_AUTO_TEST_CASE( FFT1DSmall_stdcomplex, * boost::unit_test::tolerance(0.0001f) )
{
// rocFFT gpu compute
// ========================================
CHECK_HIP(rocfft_setup());
std::size_t N = 2 << 10; //should be small enough to not need a work_buffer
std::size_t Nbytes = N * sizeof(std::complex<float>);
// Create HIP device buffer
std::complex<float> *x;
CHECK_HIP(hipMalloc(&x, Nbytes));
// Initialize data
std::vector<std::complex<float>> cx(N);
for (std::size_t i = 0; i < N; i++)
{
cx[i].real( 1 );
cx[i].imag( -1);
}
// Copy data to device
CHECK_HIP(hipMemcpy(x, cx.data(), Nbytes, hipMemcpyHostToDevice));
// Create fwd rocFFT fwd
rocfft_plan fwd = nullptr;
std::size_t length = N;
CHECK_HIP(
rocfft_plan_create(&fwd,
rocfft_placement_inplace,
rocfft_transform_type_complex_forward,
rocfft_precision_single,
1, &length, 1, nullptr));
// Create bwd rocFFT bwd
rocfft_plan bwd = nullptr;
CHECK_HIP(
rocfft_plan_create(&bwd,
rocfft_placement_inplace,
rocfft_transform_type_complex_inverse,
rocfft_precision_single,
1, &length, 1, nullptr));
// Execute fwd
CHECK_HIP(rocfft_execute(fwd, (void**) &x, nullptr, nullptr));
// Wait for execution to finish
CHECK_HIP(hipDeviceSynchronize());
// Destroy fwd
CHECK_HIP(rocfft_plan_destroy(fwd));
// Execute bwd
CHECK_HIP(rocfft_execute(bwd, (void**) &x, nullptr, nullptr));
// Wait for execution to finish
CHECK_HIP(hipDeviceSynchronize());
// Destroy bwd
CHECK_HIP(rocfft_plan_destroy(bwd));
// Copy result back to host
std::vector<std::complex<float>> y(N);
CHECK_HIP(hipMemcpy(y.data(), x, Nbytes, hipMemcpyDeviceToHost));
// Print results
for (std::size_t i = 0; i < N; i++)
{
y[i].real ( y[i].real() * 1.f/N);
y[i].imag ( y[i].imag() * 1.f/N);
BOOST_TEST( cx[i].real() == y[i].real() );
BOOST_TEST( cx[i].imag() == y[i].imag() );
}
// Free device buffer
CHECK_HIP(hipFree(x));
CHECK_HIP(rocfft_cleanup());
}
BOOST_AUTO_TEST_CASE( failing_float_265841_Inplace_Real, * boost::unit_test::tolerance(0.0001f) )
{
// rocFFT gpu compute
// ========================================
CHECK_HIP(rocfft_setup());
std::size_t N = 265841;
std::size_t Nbytes = 2*(N/2 + 1) * sizeof(float);
BOOST_REQUIRE_GT(Nbytes, N*sizeof(float));
// Create HIP device buffer
float *x;
CHECK_HIP(hipMalloc(&x, Nbytes));
// Initialize data
std::vector<float> h_x(N,1.);
// Copy data to device
CHECK_HIP(hipMemcpy(x, h_x.data(), Nbytes, hipMemcpyHostToDevice));
// Create fwd rocFFT fwd
rocfft_plan fwd = nullptr;
std::size_t length = N;
CHECK_HIP(
rocfft_plan_create(&fwd,
rocfft_placement_inplace,
rocfft_transform_type_real_forward,
rocfft_precision_single,
1, &length, 1, nullptr));
// Create bwd rocFFT bwd
rocfft_plan bwd = nullptr;
CHECK_HIP(
rocfft_plan_create(&bwd,
rocfft_placement_inplace,
rocfft_transform_type_real_inverse,
rocfft_precision_single,
1, &length, 1, nullptr));
// Setup work buffer
void *workBuffer = nullptr;
size_t workBufferSize_fwd = 0;
CHECK_HIP(rocfft_plan_get_work_buffer_size(fwd, &workBufferSize_fwd));
size_t workBufferSize_bwd = 0;
CHECK_HIP(rocfft_plan_get_work_buffer_size(bwd, &workBufferSize_bwd));
BOOST_REQUIRE_EQUAL(workBufferSize_bwd,workBufferSize_fwd);
// Setup exec info to pass work buffer to the library
rocfft_execution_info info = nullptr;
CHECK_HIP(rocfft_execution_info_create(&info));
if(workBufferSize_fwd > 0)
{
CHECK_HIP(hipMalloc(&workBuffer, workBufferSize_fwd));
CHECK_HIP(rocfft_execution_info_set_work_buffer(info, workBuffer, workBufferSize_fwd));
}
// Execute fwd
CHECK_HIP(rocfft_execute(fwd, (void**) &x, nullptr, info));
// Wait for execution to finish
CHECK_HIP(hipDeviceSynchronize());
// Destroy fwd
CHECK_HIP(rocfft_plan_destroy(fwd));
// Execute bwd
CHECK_HIP(rocfft_execute(bwd, (void**) &x, nullptr, info));
// Wait for execution to finish
CHECK_HIP(hipDeviceSynchronize());
// Destroy bwd
CHECK_HIP(rocfft_plan_destroy(bwd));
if(workBuffer)
CHECK_HIP(hipFree(workBuffer));
CHECK_HIP(rocfft_execution_info_destroy(info));
// Copy result back to host
std::vector<float> h_y(N);
CHECK_HIP(hipMemcpy(h_y.data(), x, Nbytes, hipMemcpyDeviceToHost));
// Print results
for (std::size_t i = 0; i < N; i++)
{
h_y[i]*= 1.f/N;
BOOST_TEST( h_x[i] == h_y[i] );
}
// Free device buffer
CHECK_HIP(hipFree(x));
CHECK_HIP(rocfft_cleanup());
}
|
import Pkg; Pkg.add(Pkg.PackageSpec(url="https://github.com/JuliaComputing/JuliaAcademyData.jl"))
using JuliaAcademyData; activate("Foundations of machine learning")
# ## Intro to neurons
#
# At this point, we know how to build models and have a computer automatically learn how to match the model to data. This is the core of how any machine learning method works.
#
# Now, let's narrow our focus and look at **neural networks**. Neural networks (or "neural nets", for short) are a specific choice of a **model**. It's a network made up of **neurons**; this, in turn, leads to the question, "what is a neuron?"
#-
# ### Models with multiple inputs
#
# So far, we have been using the sigmoid function as our model. One of the forms of the sigmoid function we've used is
#
# $$\sigma_{w, b}(x) = \frac{1}{1 + \exp(-wx + b)},$$
#
# where `x` and `w` are both single numbers. We have been using this function to model how the amount of the color green in an image (`x`) can be used to determine if an image shows an apple or a banana.
#
# But what if we had multiple data features we wanted to fit?
#
# We could then extend our model to include multiple features like
#
# $$\sigma_{\mathbf{w},b}(\mathbf{x}) = \frac{1}{1 + \exp(-w_1 x_1 - w_2 x_2 - \cdots - w_n x_n + b)}$$
#
# Note that now $\mathbf{x}$ and $\mathbf{w}$ are vectors with many components, rather than a single number.
#
# For example, $x_1$ might be the amount of the color green in an image, $x_2$ could be the height of the object in the picture, $x_3$ could be the width, and so forth. We can add information for as many features as we have! Our model now has more parameters, but the same idea of gradient descent ("rolling the ball downhill") will still work to train our model.
#
# This version of the sigmoid model that takes multiple inputs is an example of a **neuron**.
#-
# In the video, we see that one huge class of learning techniques is based around neurons, that is, *artificial neurons*. These are caricatures of real, biological neurons. Both *artificial* and *biological* neurons have several inputs $x_1, \ldots, x_n$, and a single output, $y$. Schematically they look like this:
include(datapath("scripts/draw_neural_net.jl"))
number_inputs, number_neurons = 4, 1
draw_network([number_inputs, number_neurons])
# We should read this as showing how information flows from left to right:
# - 4 pieces of input information arrive (shown in green on the left);
#
# - the neuron (shown in red on the right) receives all the inputs, processes them, and outputs a single number to the right.
#-
# In other words, a neuron is just a type of function that takes multiple inputs and returns a single output.
#
# The simplest interesting case that we will look at in this notebook is when there are just two pieces of input data:
draw_network([2, 1])
# Each link between circles above represents a **weight** $w$ that can be modified to allow the neuron to learn, so in this case the neuron has two weights, $w_1$ and $w_2$.
#
# The neuron also has a single bias $b$, and an **activation function**, which we will take to be the $\sigma$ sigmoidal function that we have been using. (Note that other activation functions can be used!)
#
# Let's call our neuron $f_{w_1,w_2, b}(x_1, x_2)$, where
#
# $$f_{w_1,w_2, b}(x_1, x_2) := \sigma(w_1 x_1 + w_2 x_2 + b).$$
#
# Note that $f_{w_1,w_2, b}(x_1, x_2)$ has 3 parameters: two weights and a bias.
#
# To simplify the notation, and to prepare for more complicated scenarios later, we put the two weights into a vector, and the two data values into another vector:
#
# $$
# \mathbf{w} = \begin{pmatrix} w_1 \\ w_2 \end{pmatrix};
# \qquad
# \mathbf{x} = \begin{pmatrix} x_1 \\ x_2 \end{pmatrix}.
# $$
#
# We thus have
#
# $$f_{\mathbf{w}, b}(\mathbf{x}) = \sigma(\mathbf{w} \cdot \mathbf{x} + b),$$
#
# where the dot product $\mathbf{w} \cdot \mathbf{x}$ is an abbreviated syntax for $w_1 x_1 + w_2 x_2$.
#-
# #### Exercise 1
#
# Declare the function `f(x, w, b)` in Julia. `f` should take vectors `x` and `w` as vectors and `b` as a scalar. Furthermore `f` should call
#
# ```julia
# Ļ(x) = 1 / (1 + exp(-x))
# ```
#
# What output do you get for
#
# ```julia
# f(3, 4, 5)
# ```
# ?
#-
# #### Solution
Ļ(x) = 1 / (1 + exp(-x))
f(x, w, b) = Ļ(w ā
x + b) # use \cdot<TAB> to get "ā
"
## or alternatively, use juxtaposed multiplication with the transpose w'
## f(x, w, b) = Ļ(w'x + b) # use \cdot<TAB> to get "ā
"
# **Tests**
@assert f(3, 4, 5) ā 0.99999996
|
The current Romanian Land Forces were formed in 1859 , immediately after the unification of Wallachia with Moldavia , and were commanded by Alexandru Ioan Cuza , Domnitor of Romania until his abdication in 1866 . In 1877 , at the request of Nikolai Konstantinovich , Grand Duke of Russia the Romanian army fused with the Russian forces , and led by King Carol I , fought in what was to become the Romanian War of Independence . They participated in the Siege of Plevna and several other battles . The Romanians won the war , but suffered about 27 @,@ 000 casualties . Until World War I , the Romanian army didn 't face any other serious actions .
|
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9.
Copyright (c) 2021, Oracle and/or its affiliates.
Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl
-}
------------------------------------------------------------------------------
import LibraBFT.Impl.Consensus.SafetyRules.PersistentSafetyStorage as PersistentSafetyStorage
import LibraBFT.Impl.Consensus.SafetyRules.SafetyRules as SafetyRules
open import LibraBFT.ImplShared.Consensus.Types
open import Optics.All
open import Util.PKCS
open import Util.Prelude
------------------------------------------------------------------------------
module LibraBFT.Impl.Consensus.SafetyRules.SafetyRulesManager where
storage
: SafetyRulesConfig -> Author -> SK
ā Either ErrLog PersistentSafetyStorage
storage config obmMe obmSK = do
pure $ PersistentSafetyStorage.new -- internalStorage
obmMe
(config ^ā srcObmGenesisWaypoint)
obmSK
newLocal : PersistentSafetyStorage ā Bool ā Either ErrLog SafetyRulesManager
new
: SafetyRulesConfig ā Author ā SK
ā Either ErrLog SafetyRulesManager
new config obmMe obmSK = do
storage0 ā storage config obmMe obmSK
let exportConsensusKey = config ^ā srcExportConsensusKey
case config ^ā srcService of Ī» where
SRSLocal ā newLocal storage0 exportConsensusKey
newLocal storage0 exportConsensusKey = do
safetyRules ā SafetyRules.new storage0 exportConsensusKey
pure (mkSafetyRulesManager (SRWLocal safetyRules))
client : SafetyRulesManager ā SafetyRules
client self = case self ^ā srmInternalSafetyRules of Ī» where
(SRWLocal safetyRules) ā safetyRules
|
(** This file collects general purpose definitions and theorems on the option
data type that are not in the Coq standard library. *)
From stdpp Require Export tactics.
From stdpp Require Import options.
Inductive option_reflect {A} (P : A ā Prop) (Q : Prop) : option A ā Type :=
| ReflectSome x : P x ā option_reflect P Q (Some x)
| ReflectNone : Q ā option_reflect P Q None.
(** * General definitions and theorems *)
(** Basic properties about equality. *)
Lemma None_ne_Some {A} (x : A) : None ā Some x.
Proof. congruence. Qed.
Lemma Some_ne_None {A} (x : A) : Some x ā None.
Proof. congruence. Qed.
Lemma eq_None_ne_Some {A} (mx : option A) : (ā x, mx ā Some x) ā mx = None.
Proof. destruct mx; split; congruence. Qed.
Lemma eq_None_ne_Some_1 {A} (mx : option A) x : mx = None ā mx ā Some x.
Proof. intros ?. by apply eq_None_ne_Some. Qed.
Lemma eq_None_ne_Some_2 {A} (mx : option A) : (ā x, mx ā Some x) ā mx = None.
Proof. intros ?. by apply eq_None_ne_Some. Qed.
Global Instance Some_inj {A} : Inj (=) (=) (@Some A).
Proof. congruence. Qed.
(** The [from_option] is the eliminator for option. *)
Definition from_option {A B} (f : A ā B) (y : B) (mx : option A) : B :=
match mx with None => y | Some x => f x end.
Global Instance: Params (@from_option) 2 := {}.
Global Arguments from_option {_ _} _ _ !_ / : assert.
(** The eliminator with the identity function. *)
Notation default := (from_option id).
(** An alternative, but equivalent, definition of equality on the option
data type. This theorem is useful to prove that two options are the same. *)
Lemma option_eq {A} (mx my: option A): mx = my ā ā x, mx = Some x ā my = Some x.
Proof. split; [by intros; by subst |]. destruct mx, my; naive_solver. Qed.
Lemma option_eq_1 {A} (mx my: option A) x : mx = my ā mx = Some x ā my = Some x.
Proof. congruence. Qed.
Lemma option_eq_1_alt {A} (mx my : option A) x :
mx = my ā my = Some x ā mx = Some x.
Proof. congruence. Qed.
Definition is_Some {A} (mx : option A) := ā x, mx = Some x.
Global Instance: Params (@is_Some) 1 := {}.
(** We avoid calling [done] recursively as that can lead to an unresolved evar. *)
Global Hint Extern 0 (is_Some _) => eexists; fast_done : core.
Lemma is_Some_alt {A} (mx : option A) :
is_Some mx ā match mx with Some _ => True | None => False end.
Proof. unfold is_Some. destruct mx; naive_solver. Qed.
Lemma mk_is_Some {A} (mx : option A) x : mx = Some x ā is_Some mx.
Proof. by intros ->. Qed.
Global Hint Resolve mk_is_Some : core.
Lemma is_Some_None {A} : ¬is_Some (@None A).
Proof. by destruct 1. Qed.
Global Hint Resolve is_Some_None : core.
Lemma eq_None_not_Some {A} (mx : option A) : mx = None ā ¬is_Some mx.
Proof. rewrite is_Some_alt; destruct mx; naive_solver. Qed.
Lemma not_eq_None_Some {A} (mx : option A) : mx ā None ā is_Some mx.
Proof. rewrite is_Some_alt; destruct mx; naive_solver. Qed.
Global Instance is_Some_pi {A} (mx : option A) : ProofIrrel (is_Some mx).
Proof.
set (P (mx : option A) := match mx with Some _ => True | _ => False end).
set (f mx := match mx return P mx ā is_Some mx with
Some _ => Ī» _, ex_intro _ _ eq_refl | None => False_rect _ end).
set (g mx (H : is_Some mx) :=
match H return P mx with ex_intro _ _ p => eq_rect _ _ I _ (eq_sym p) end).
assert (ā mx H, f mx (g mx H) = H) as f_g by (by intros ? [??]; subst).
intros p1 p2. rewrite <-(f_g _ p1), <-(f_g _ p2). by destruct mx, p1.
Qed.
Global Instance is_Some_dec {A} (mx : option A) : Decision (is_Some mx) :=
match mx with
| Some x => left (ex_intro _ x eq_refl)
| None => right is_Some_None
end.
Definition is_Some_proj {A} {mx : option A} : is_Some mx ā A :=
match mx with Some x => Ī» _, x | None => False_rect _ ā is_Some_None end.
Definition Some_dec {A} (mx : option A) : { x | mx = Some x } + { mx = None } :=
match mx return { x | mx = Some x } + { mx = None } with
| Some x => inleft (x ā¾ eq_refl _)
| None => inright eq_refl
end.
(** Lifting a relation point-wise to option *)
Inductive option_Forall2 {A B} (R: A ā B ā Prop) : option A ā option B ā Prop :=
| Some_Forall2 x y : R x y ā option_Forall2 R (Some x) (Some y)
| None_Forall2 : option_Forall2 R None None.
Definition option_relation {A B} (R: A ā B ā Prop) (P: A ā Prop) (Q: B ā Prop)
(mx : option A) (my : option B) : Prop :=
match mx, my with
| Some x, Some y => R x y
| Some x, None => P x
| None, Some y => Q y
| None, None => True
end.
Section Forall2.
Context {A} (R : relation A).
Global Instance option_Forall2_refl : Reflexive R ā Reflexive (option_Forall2 R).
Proof. intros ? [?|]; by constructor. Qed.
Global Instance option_Forall2_sym : Symmetric R ā Symmetric (option_Forall2 R).
Proof. destruct 2; by constructor. Qed.
Global Instance option_Forall2_trans : Transitive R ā Transitive (option_Forall2 R).
Proof. destruct 2; inversion_clear 1; constructor; etrans; eauto. Qed.
Global Instance option_Forall2_equiv : Equivalence R ā Equivalence (option_Forall2 R).
Proof. destruct 1; split; apply _. Qed.
End Forall2.
(** Setoids *)
Global Instance option_equiv `{Equiv A} : Equiv (option A) := option_Forall2 (ā”).
Section setoids.
Context `{Equiv A}.
Implicit Types mx my : option A.
Lemma equiv_option_Forall2 mx my : mx ā” my ā option_Forall2 (ā”) mx my.
Proof. done. Qed.
Global Instance option_equivalence :
Equivalence (ā”@{A}) ā Equivalence (ā”@{option A}).
Proof. apply _. Qed.
Global Instance option_leibniz `{!LeibnizEquiv A} : LeibnizEquiv (option A).
Proof. intros x y; destruct 1; f_equal; by apply leibniz_equiv. Qed.
Global Instance Some_proper : Proper ((ā”) ==> (ā”@{option A})) Some.
Proof. by constructor. Qed.
Global Instance Some_equiv_inj : Inj (ā”) (ā”@{option A}) Some.
Proof. by inversion_clear 1. Qed.
Lemma None_equiv_eq mx : mx ā” None ā mx = None.
Proof. split; [by inversion_clear 1|intros ->; constructor]. Qed.
Lemma Some_equiv_eq mx y : mx ā” Some y ā ā y', mx = Some y' ā§ y' ā” y.
Proof. split; [inversion 1; naive_solver|naive_solver (by constructor)]. Qed.
Global Instance is_Some_proper : Proper ((ā”@{option A}) ==> iff) is_Some.
Proof. by inversion_clear 1. Qed.
Global Instance from_option_proper {B} (R : relation B) :
Proper (((ā”@{A}) ==> R) ==> R ==> (ā”) ==> R) from_option.
Proof. destruct 3; simpl; auto. Qed.
End setoids.
Typeclasses Opaque option_equiv.
(** Equality on [option] is decidable. *)
Global Instance option_eq_None_dec {A} (mx : option A) : Decision (mx = None) :=
match mx with Some _ => right (Some_ne_None _) | None => left eq_refl end.
Global Instance option_None_eq_dec {A} (mx : option A) : Decision (None = mx) :=
match mx with Some _ => right (None_ne_Some _) | None => left eq_refl end.
Global Instance option_eq_dec `{dec : EqDecision A} : EqDecision (option A).
Proof.
refine (Ī» mx my,
match mx, my with
| Some x, Some y => cast_if (decide (x = y))
| None, None => left _ | _, _ => right _
end); clear dec; abstract congruence.
Defined.
(** * Monadic operations *)
Global Instance option_ret: MRet option := @Some.
Global Instance option_bind: MBind option := Ī» A B f mx,
match mx with Some x => f x | None => None end.
Global Instance option_join: MJoin option := Ī» A mmx,
match mmx with Some mx => mx | None => None end.
Global Instance option_fmap: FMap option := @option_map.
Global Instance option_guard: MGuard option := Ī» P dec A f,
match dec with left H => f H | _ => None end.
Global Instance option_fmap_inj {A B} (f : A ā B) :
Inj (=) (=) f ā Inj (=@{option A}) (=@{option B}) (fmap f).
Proof. intros ? [x1|] [x2|] [=]; naive_solver. Qed.
Global Instance option_fmap_equiv_inj `{Equiv A, Equiv B} (f : A ā B) :
Inj (ā”) (ā”) f ā Inj (ā”@{option A}) (ā”@{option B}) (fmap f).
Proof. intros ? [x1|] [x2|]; inversion 1; subst; constructor; by apply (inj _). Qed.
Lemma fmap_is_Some {A B} (f : A ā B) mx : is_Some (f <$> mx) ā is_Some mx.
Proof. unfold is_Some; destruct mx; naive_solver. Qed.
Lemma fmap_Some {A B} (f : A ā B) mx y :
f <$> mx = Some y ā ā x, mx = Some x ā§ y = f x.
Proof. destruct mx; naive_solver. Qed.
Lemma fmap_Some_1 {A B} (f : A ā B) mx y :
f <$> mx = Some y ā ā x, mx = Some x ā§ y = f x.
Proof. apply fmap_Some. Qed.
Lemma fmap_Some_2 {A B} (f : A ā B) mx x : mx = Some x ā f <$> mx = Some (f x).
Proof. intros. apply fmap_Some; eauto. Qed.
Lemma fmap_Some_equiv {A B} `{Equiv B} `{!Equivalence (ā”@{B})} (f : A ā B) mx y :
f <$> mx ā” Some y ā ā x, mx = Some x ā§ y ā” f x.
Proof.
destruct mx; simpl; split.
- intros ?%(inj Some). eauto.
- intros (? & ->%(inj Some) & ?). constructor. done.
- intros [=]%symmetry%None_equiv_eq.
- intros (? & [=] & ?).
Qed.
Lemma fmap_Some_equiv_1 {A B} `{Equiv B} `{!Equivalence (ā”@{B})} (f : A ā B) mx y :
f <$> mx ā” Some y ā ā x, mx = Some x ā§ y ā” f x.
Proof. by rewrite fmap_Some_equiv. Qed.
Lemma fmap_None {A B} (f : A ā B) mx : f <$> mx = None ā mx = None.
Proof. by destruct mx. Qed.
Lemma option_fmap_id {A} (mx : option A) : id <$> mx = mx.
Proof. by destruct mx. Qed.
Lemma option_fmap_compose {A B} (f : A ā B) {C} (g : B ā C) (mx : option A) :
g ā f <$> mx = g <$> (f <$> mx).
Proof. by destruct mx. Qed.
Lemma option_fmap_ext {A B} (f g : A ā B) (mx : option A) :
(ā x, f x = g x) ā f <$> mx = g <$> mx.
Proof. intros; destruct mx; f_equal/=; auto. Qed.
Lemma option_fmap_equiv_ext {A} `{Equiv B} (f g : A ā B) (mx : option A) :
(ā x, f x ā” g x) ā f <$> mx ā” g <$> mx.
Proof. destruct mx; constructor; auto. Qed.
Lemma option_fmap_bind {A B C} (f : A ā B) (g : B ā option C) mx :
(f <$> mx) ā«= g = mx ā«= g ā f.
Proof. by destruct mx. Qed.
Lemma option_bind_assoc {A B C} (f : A ā option B)
(g : B ā option C) (mx : option A) : (mx ā«= f) ā«= g = mx ā«= (mbind g ā f).
Proof. by destruct mx; simpl. Qed.
Lemma option_bind_ext {A B} (f g : A ā option B) mx my :
(ā x, f x = g x) ā mx = my ā mx ā«= f = my ā«= g.
Proof. destruct mx, my; naive_solver. Qed.
Lemma option_bind_ext_fun {A B} (f g : A ā option B) mx :
(ā x, f x = g x) ā mx ā«= f = mx ā«= g.
Proof. intros. by apply option_bind_ext. Qed.
Lemma bind_Some {A B} (f : A ā option B) (mx : option A) y :
mx ā«= f = Some y ā ā x, mx = Some x ā§ f x = Some y.
Proof. destruct mx; naive_solver. Qed.
Lemma bind_Some_equiv {A} `{Equiv B} (f : A ā option B) (mx : option A) y :
mx ā«= f ā” Some y ā ā x, mx = Some x ā§ f x ā” Some y.
Proof. destruct mx; (split; [inversion 1|]); naive_solver. Qed.
Lemma bind_None {A B} (f : A ā option B) (mx : option A) :
mx ā«= f = None ā mx = None ⨠ā x, mx = Some x ā§ f x = None.
Proof. destruct mx; naive_solver. Qed.
Lemma bind_with_Some {A} (mx : option A) : mx ā«= Some = mx.
Proof. by destruct mx. Qed.
Global Instance option_fmap_proper `{Equiv A, Equiv B} :
Proper (((ā”) ==> (ā”)) ==> (ā”@{option A}) ==> (ā”@{option B})) fmap.
Proof. destruct 2; constructor; auto. Qed.
Global Instance option_bind_proper `{Equiv A, Equiv B} :
Proper (((ā”) ==> (ā”)) ==> (ā”@{option A}) ==> (ā”@{option B})) mbind.
Proof. destruct 2; simpl; try constructor; auto. Qed.
Global Instance option_join_proper `{Equiv A} :
Proper ((ā”) ==> (ā”@{option (option A)})) mjoin.
Proof. destruct 1 as [?? []|]; simpl; by constructor. Qed.
(** ** Inverses of constructors *)
(** We can do this in a fancy way using dependent types, but rewrite does
not particularly like type level reductions. *)
Class Maybe {A B : Type} (c : A ā B) :=
maybe : B ā option A.
Global Arguments maybe {_ _} _ {_} !_ / : assert.
Class Maybe2 {A1 A2 B : Type} (c : A1 ā A2 ā B) :=
maybe2 : B ā option (A1 * A2).
Global Arguments maybe2 {_ _ _} _ {_} !_ / : assert.
Class Maybe3 {A1 A2 A3 B : Type} (c : A1 ā A2 ā A3 ā B) :=
maybe3 : B ā option (A1 * A2 * A3).
Global Arguments maybe3 {_ _ _ _} _ {_} !_ / : assert.
Class Maybe4 {A1 A2 A3 A4 B : Type} (c : A1 ā A2 ā A3 ā A4 ā B) :=
maybe4 : B ā option (A1 * A2 * A3 * A4).
Global Arguments maybe4 {_ _ _ _ _} _ {_} !_ / : assert.
Global Instance maybe_comp `{Maybe B C c1, Maybe A B c2} : Maybe (c1 ā c2) := Ī» x,
maybe c1 x ā«= maybe c2.
Global Arguments maybe_comp _ _ _ _ _ _ _ !_ / : assert.
Global Instance maybe_inl {A B} : Maybe (@inl A B) := Ī» xy,
match xy with inl x => Some x | _ => None end.
Global Instance maybe_inr {A B} : Maybe (@inr A B) := Ī» xy,
match xy with inr y => Some y | _ => None end.
Global Instance maybe_Some {A} : Maybe (@Some A) := id.
Global Arguments maybe_Some _ !_ / : assert.
(** * Union, intersection and difference *)
Global Instance option_union_with {A} : UnionWith A (option A) := Ī» f mx my,
match mx, my with
| Some x, Some y => f x y
| Some x, None => Some x
| None, Some y => Some y
| None, None => None
end.
Global Instance option_intersection_with {A} : IntersectionWith A (option A) :=
Ī» f mx my, match mx, my with Some x, Some y => f x y | _, _ => None end.
Global Instance option_difference_with {A} : DifferenceWith A (option A) := Ī» f mx my,
match mx, my with
| Some x, Some y => f x y
| Some x, None => Some x
| None, _ => None
end.
Global Instance option_union {A} : Union (option A) := union_with (Ī» x _, Some x).
Lemma option_union_Some {A} (mx my : option A) z :
mx āŖ my = Some z ā mx = Some z ⨠my = Some z.
Proof. destruct mx, my; naive_solver. Qed.
Section union_intersection_difference.
Context {A} (f : A ā A ā option A).
Global Instance union_with_left_id : LeftId (=) None (union_with f).
Proof. by intros [?|]. Qed.
Global Instance union_with_right_id : RightId (=) None (union_with f).
Proof. by intros [?|]. Qed.
Global Instance union_with_comm :
Comm (=) f ā Comm (=@{option A}) (union_with f).
Proof. by intros ? [?|] [?|]; compute; rewrite 1?(comm f). Qed.
Global Instance intersection_with_left_ab : LeftAbsorb (=) None (intersection_with f).
Proof. by intros [?|]. Qed.
Global Instance intersection_with_right_ab : RightAbsorb (=) None (intersection_with f).
Proof. by intros [?|]. Qed.
Global Instance difference_with_comm :
Comm (=) f ā Comm (=@{option A}) (intersection_with f).
Proof. by intros ? [?|] [?|]; compute; rewrite 1?(comm f). Qed.
Global Instance difference_with_right_id : RightId (=) None (difference_with f).
Proof. by intros [?|]. Qed.
Global Instance union_with_proper `{Equiv A} :
Proper (((ā”) ==> (ā”) ==> (ā”)) ==> (ā”@{option A}) ==> (ā”) ==> (ā”)) union_with.
Proof. intros ?? Hf; do 2 destruct 1; try constructor; by try apply Hf. Qed.
Global Instance intersection_with_proper `{Equiv A} :
Proper (((ā”) ==> (ā”) ==> (ā”)) ==> (ā”@{option A}) ==> (ā”) ==> (ā”)) intersection_with.
Proof. intros ?? Hf; do 2 destruct 1; try constructor; by try apply Hf. Qed.
Global Instance difference_with_proper `{Equiv A} :
Proper (((ā”) ==> (ā”) ==> (ā”)) ==> (ā”@{option A}) ==> (ā”) ==> (ā”)) difference_with.
Proof. intros ?? Hf; do 2 destruct 1; try constructor; by try apply Hf. Qed.
Global Instance union_proper `{Equiv A} :
Proper ((ā”@{option A}) ==> (ā”) ==> (ā”)) union.
Proof. apply union_with_proper. by constructor. Qed.
End union_intersection_difference.
(** * Tactics *)
Tactic Notation "case_option_guard" "as" ident(Hx) :=
match goal with
| H : context C [@mguard option _ ?P ?dec] |- _ =>
change (@mguard option _ P dec) with (Ī» A (f : P ā option A),
match @decide P dec with left H' => f H' | _ => None end) in *;
destruct_decide (@decide P dec) as Hx
| |- context C [@mguard option _ ?P ?dec] =>
change (@mguard option _ P dec) with (Ī» A (f : P ā option A),
match @decide P dec with left H' => f H' | _ => None end) in *;
destruct_decide (@decide P dec) as Hx
end.
Tactic Notation "case_option_guard" :=
let H := fresh in case_option_guard as H.
Lemma option_guard_True {A} P `{Decision P} (mx : option A) :
P ā mguard P (Ī» _, mx) = mx.
Proof. intros. by case_option_guard. Qed.
Lemma option_guard_True_pi {A} P `{Decision P, ProofIrrel P} (f : P ā option A)
(HP : P) :
mguard P f = f HP.
Proof. intros. case_option_guard; [|done]. f_equal; apply proof_irrel. Qed.
Lemma option_guard_False {A} P `{Decision P} (f : P ā option A) :
¬P ā mguard P f = None.
Proof. intros. by case_option_guard. Qed.
Lemma option_guard_iff {A} P Q `{Decision P, Decision Q} (mx : option A) :
(P ā Q) ā (guard P; mx) = guard Q; mx.
Proof. intros [??]. repeat case_option_guard; intuition. Qed.
Tactic Notation "simpl_option" "by" tactic3(tac) :=
let assert_Some_None A mx H := first
[ let x := mk_evar A in
assert (mx = Some x) as H by tac
| assert (mx = None) as H by tac ]
in repeat match goal with
| H : context [@mret _ _ ?A] |- _ =>
change (@mret _ _ A) with (@Some A) in H
| |- context [@mret _ _ ?A] => change (@mret _ _ A) with (@Some A)
| H : context [mbind (M:=option) (A:=?A) ?f ?mx] |- _ =>
let Hx := fresh in assert_Some_None A mx Hx; rewrite Hx in H; clear Hx
| H : context [fmap (M:=option) (A:=?A) ?f ?mx] |- _ =>
let Hx := fresh in assert_Some_None A mx Hx; rewrite Hx in H; clear Hx
| H : context [from_option (A:=?A) _ _ ?mx] |- _ =>
let Hx := fresh in assert_Some_None A mx Hx; rewrite Hx in H; clear Hx
| H : context [ match ?mx with _ => _ end ] |- _ =>
match type of mx with
| option ?A =>
let Hx := fresh in assert_Some_None A mx Hx; rewrite Hx in H; clear Hx
end
| |- context [mbind (M:=option) (A:=?A) ?f ?mx] =>
let Hx := fresh in assert_Some_None A mx Hx; rewrite Hx; clear Hx
| |- context [fmap (M:=option) (A:=?A) ?f ?mx] =>
let Hx := fresh in assert_Some_None A mx Hx; rewrite Hx; clear Hx
| |- context [from_option (A:=?A) _ _ ?mx] =>
let Hx := fresh in assert_Some_None A mx Hx; rewrite Hx; clear Hx
| |- context [ match ?mx with _ => _ end ] =>
match type of mx with
| option ?A =>
let Hx := fresh in assert_Some_None A mx Hx; rewrite Hx; clear Hx
end
| H : context [decide _] |- _ => rewrite decide_True in H by tac
| H : context [decide _] |- _ => rewrite decide_False in H by tac
| H : context [mguard _ _] |- _ => rewrite option_guard_False in H by tac
| H : context [mguard _ _] |- _ => rewrite option_guard_True in H by tac
| _ => rewrite decide_True by tac
| _ => rewrite decide_False by tac
| _ => rewrite option_guard_True by tac
| _ => rewrite option_guard_False by tac
| H : context [None āŖ _] |- _ => rewrite (left_id_L None (āŖ)) in H
| H : context [_ āŖ None] |- _ => rewrite (right_id_L None (āŖ)) in H
| |- context [None āŖ _] => rewrite (left_id_L None (āŖ))
| |- context [_ āŖ None] => rewrite (right_id_L None (āŖ))
end.
Tactic Notation "simplify_option_eq" "by" tactic3(tac) :=
repeat match goal with
| _ => progress simplify_eq/=
| _ => progress simpl_option by tac
| _ : maybe _ ?x = Some _ |- _ => is_var x; destruct x
| _ : maybe2 _ ?x = Some _ |- _ => is_var x; destruct x
| _ : maybe3 _ ?x = Some _ |- _ => is_var x; destruct x
| _ : maybe4 _ ?x = Some _ |- _ => is_var x; destruct x
| H : _ āŖ _ = Some _ |- _ => apply option_union_Some in H; destruct H
| H : mbind (M:=option) ?f ?mx = ?my |- _ =>
match mx with Some _ => fail 1 | None => fail 1 | _ => idtac end;
match my with Some _ => idtac | None => idtac | _ => fail 1 end;
let x := fresh in destruct mx as [x|] eqn:?;
[change (f x = my) in H|change (None = my) in H]
| H : ?my = mbind (M:=option) ?f ?mx |- _ =>
match mx with Some _ => fail 1 | None => fail 1 | _ => idtac end;
match my with Some _ => idtac | None => idtac | _ => fail 1 end;
let x := fresh in destruct mx as [x|] eqn:?;
[change (my = f x) in H|change (my = None) in H]
| H : fmap (M:=option) ?f ?mx = ?my |- _ =>
match mx with Some _ => fail 1 | None => fail 1 | _ => idtac end;
match my with Some _ => idtac | None => idtac | _ => fail 1 end;
let x := fresh in destruct mx as [x|] eqn:?;
[change (Some (f x) = my) in H|change (None = my) in H]
| H : ?my = fmap (M:=option) ?f ?mx |- _ =>
match mx with Some _ => fail 1 | None => fail 1 | _ => idtac end;
match my with Some _ => idtac | None => idtac | _ => fail 1 end;
let x := fresh in destruct mx as [x|] eqn:?;
[change (my = Some (f x)) in H|change (my = None) in H]
| _ => progress case_decide
| _ => progress case_option_guard
end.
Tactic Notation "simplify_option_eq" := simplify_option_eq by eauto.
|
If $P$ is a transitive relation on the real numbers and $P$ is locally true, then $P$ is true. |
#!/usr/bin/Rscript
# Bhishan Poudel
# Jan 8, 2016
# clear; Rscript plot1.r; xdg-open ./plots/plot1.eps
# inputs: nothing
# outputs: figures/plot1.eps
# set the working directory
setwd("~/Copy/Programming/R/rprograms/plotting/2dplots/")
# Start device driver to save output to figure.pdf
#postscript(file="figures/plot1.eps", height=8.5, width=5)
# Define 2 vectors
cars <- c(1, 3, 6, 4, 9)
trucks <- c(2, 5, 4, 5, 12)
# Calculate range from 0 to max value of cars and trucks
g_range <- range(0, cars, trucks)
# Graph autos using y axis that ranges from 0 to max
# value in cars or trucks vector. Turn off axes and
# annotations (axis labels) so we can specify them ourself
plot(cars,
type="o",
col="blue",
ylim=g_range,
axes=FALSE,
ann=FALSE)
# Make x axis using Mon-Fri labels
axis(1, at=1:5, lab=c("Mon","Tue","Wed","Thu","Fri"))
# Make y axis with horizontal labels that display ticks at
# every 4 marks. 4*0:g_range[2] is equivalent to c(0,4,8,12).
axis(2, las=1, at=4*0:g_range[2])
# Create box around plot
box()
# Graph trucks with red dashed line and square points
lines(trucks, type="o", pch=22, lty=2, col="red")
# Create a title with a red, bold/italic font
title(main="Autos", col.main="red", font.main=4)
# Label the x and y axes with dark green text
title(xlab="Days", col.lab=rgb(0,0.5,0))
title(ylab="Total", col.lab=rgb(0,0.5,0))
# Create a legend at (1, g_range[2]) that is slightly smaller
# (cex) and uses the same line colors and points used by
# the actual plots
legend(1, g_range[2], c("cars","trucks"), cex=0.8,
col=c("blue","red"), pch=21:22, lty=1:2);
# Turn off device driver
#dev.off()
|
I have to create a form where the drop-down lists are filled according to our choices in the previous ones.
A Region may have several Cities (ManyToOne) relationship.
I followed the documentation from here How to Dynamically Modify Forms Using Form Events (Dynamic Generation for Submitted Forms) .
I retrieve the list of regions with the query_builder option but how do I retrieve the list of cities according to the choice of region. |
The quake created a landslide dam on the Rivière de Grand Goâve . As of February 2010 the water level was low , but engineer Yves <unk> believed the dam could collapse during the rainy season , which would flood Grand @-@ Goâve 12 km ( 7 @.@ 5 mi ) downstream .
|
import Graphics.UI.GLUT
import Data.Complex
iterations = 400
chunk :: Int -> [a] -> [[a]]
chunk n [] = []
chunk n xs = let (xs', rest) = splitAt n xs in xs' : chunk n rest
vertices :: IO [Vertex2 GLfloat]
vertices = get windowSize >>= \(Size w h) ->
return $ [pixel (Size w h) (x, y) | x <- [0..w-1], y <- [0..h-1]]
where
pixel (Size w h) (x, y) = Vertex2 ((fromIntegral 3 / fromIntegral w * fromIntegral x) - 2.0) ((fromIntegral 2 / fromIntegral h * fromIntegral y) - 1.0)
getcol :: Int -> Color3 Float
getcol iter | iter == iterations = Color3 0 0 0
| otherwise = Color3 (amt*0.5) amt (amt*0.5)
where
amt = fromIntegral iter / fromIntegral iterations
mandelbrot :: RealFloat a => Vertex2 a -> Int
mandelbrot (Vertex2 r i) = length . takeWhile (\z -> magnitude z <= 2) . take iterations $ iterate (\z -> z^2 + (r :+ i)) 0
drawVert :: (RealFloat a, VertexComponent a) => Vertex2 a -> IO ()
drawVert v = do color . getcol $ mandelbrot v
vertex v
display' :: [[Vertex2 GLfloat]] -> IO ()
display' chunks = do mapM_ (\vs -> do renderPrimitive Points $ mapM_ drawVert vs
flush) chunks
displayCallback $= display
display :: IO ()
display = do clear [ ColorBuffer ]
displayCallback $= (vertices >>= display' . chunk 256)
get currentWindow >>= postRedisplay
main :: IO ()
main = do
getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 1200 1024
initialWindowPosition $= Position 100 100
createWindow "Mandelbrot"
clearColor $= Color4 0 0 0 0
matrixMode $= Projection
loadIdentity
ortho (-2) 1 (-1) 1 (-1) 1
displayCallback $= display
mainLoop
|
The French government was more fastidious than Spanish and Neapolitan . Only three cardinals were considered good candidates : Conti , <unk> and Ganganelli
|
#include<iostream>
#define EIGEN_USE_MKL_ALL
#include"basis.hpp"
#include"operators.hpp"
#include"diag.h"
#include"tpoperators.hpp"
#include"files.hpp"
#include"timeev.hpp"
#include"ETH.hpp"
#include<iomanip>
#include <boost/program_options.hpp>
using namespace boost::program_options;
int main(int argc, char *argv[])
{
using namespace Eigen;
using namespace std;
using namespace Many_Body;
using HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;
// std::vector<size_t> ee(L, 0);
using Mat= Operators::Mat;
size_t M{};
size_t L{};
double t0{};
double omega{};
double gamma{};
double T{};
bool PB{};
try
{
options_description desc{"Options"};
desc.add_options()
("help,h", "Help screen")
("L", value(&L)->default_value(4), "L")
("M", value(&M)->default_value(2), "M")
("t", value(&t0)->default_value(1.), "t0")
("gam", value(&gamma)->default_value(1.), "gamma")
("omg", value(&omega)->default_value(1.), "omega")
("T", value(&T)->default_value(1.), "T")
("pb", value(&PB)->default_value(true), "PB");
variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if (vm.count("help"))
{std::cout << desc << '\n'; return 0;}
else{
if (vm.count("L"))
{ std::cout << "L: " << vm["L"].as<size_t>() << '\n';
}
if (vm.count("M,m"))
{
std::cout << "M: " << vm["M"].as<size_t>() << '\n';
}
if (vm.count("t"))
{
std::cout << "t0: " << vm["t"].as<double>() << '\n';
}
if (vm.count("omg"))
{
std::cout << "omega: " << vm["omg"].as<double>() << '\n';
}
if (vm.count("gam"))
{
std::cout << "gamma: " << vm["gam"].as<double>() << '\n';
}
if (vm.count("T"))
{
std::cout << "T: " << vm["T"].as<double>() << '\n';
}
if (vm.count("pb"))
{
std::cout << "PB: " << vm["pb"].as<bool>() << '\n';
}
}
}
catch (const error &ex)
{
std::cerr << ex.what() << '\n';
return 0;
}
ElectronBasis e( L, 1);
// std::cout<< e<<std::endl;
ElectronState e2( L, 0);
// std::cout<< e<<std::endl;
PhononBasis ph(L, M);
// std::cout<< ph<<std::endl;
HolsteinBasis TP(e, ph);
//HolsteinBasis TP2(e2, ph);
// std::cout<< TP<<std::endl;
e.insert(e2);
std::cout<< e<< std::endl;
// std::cout<< TP2<< std::endl;
std::cout<<"total dim "<< TP.dim << std::endl;
std::cout<<std::endl;
Mat E1=Operators::EKinOperatorL(TP, e, t0, PB);
Mat Ebdag=Operators::NBosonCOperator(TP, ph, gamma, PB);
Mat Eb=Operators::NBosonDOperator(TP, ph, gamma, PB);
Mat Eph=Operators::NumberOperator(TP, ph, omega, PB);
Mat H=E1 +Ebdag + Eb+ Eph;
Eigen::MatrixXcd HH=Eigen::MatrixXcd(H);
Eigen::VectorXd ev=Eigen::VectorXd(TP.dim);
diagMat(HH, ev);
return 0;
}
|
-- | see examples/
module DimMat (
-- * Quasiquotes
matD,
blockD,
-- * Data.Packed.Vector
(@>),
-- * Data.Packed.Matrix
-- ** dimension
cols, rows,
colsNT, rowsNT,
hasRows, hasCols,
-- (><),
trans,
-- reshape, flatten, fromLists, toLists, buildMatrix,
-- broken
ToHLists(toHLists), toHList, FromHLists(fromHLists), fromHList,
(@@>),
-- asRow, asColumn, fromRows, toRows, fromColumns, toColumns
-- fromBlocks
#if MIN_VERSION_hmatrix(0,15,0)
diagBlock,
#endif
-- toBlocks, toBlocksEvery, repmat, flipud, fliprl
-- subMatrix, takeRows, dropRows, takeColumns, dropColumns,
-- extractRows, diagRect, takeDiag, mapMatrix,
-- mapMatrixWithIndexM, mapMatrixWithIndexM_, liftMatrix,
-- liftMatrix2, liftMatrix2Auto, fromArray2D,
ident, -- where to put this?
-- * Numeric.Container
-- constant, linspace,
diag,
ctrans,
-- ** Container class
scalar,
conj,
scale, scaleRecip,
recipMat,
addConstant,
add,
sub,
mulMat, mulVec,
divideMat, divideVec,
equal,
arctan2,
hconcat,
vconcat,
cmap,
konst,
zeroes,
-- build, atIndex, minIndex, maxIndex, minElement, maxElement,
-- sumElements, prodElements, step, cond, find, assoc, accum,
-- Convert
-- ** Product class
Dot(..),
-- absSum, norm1, norm2, normInf,
-- norm1, normInf,
pnorm,
-- optimiseMult, mXm, mXv, vXm, (<.>),
-- (<>), (<\>), outer, kronecker,
-- ** Random numbers
-- ** Element conversion
-- ** Input/Output
-- ** Experimental
-- * Numeric.LinearAlgebra.Algorithms
-- | incomplete wrapper for "Numeric.LinearAlgebra.Algorithms"
-- ** Linear Systems
-- linearSolve, luSolve, cholSolve, linearSolveLS, linearSolveSVD,
inv,
PInv(pinv),
pinvTol,
det,
-- invlndet,
rank,
-- rcond,
-- ** Matrix factorizations
-- *** Singular value decomposition
-- *** Eigensystems
-- eigs
{-
wrapEig, wrapEigOnly,
EigV, EigE,
-- **** eigenvalues and eigenvectors
eig,
eigC,
eigH,
eigH',
eigR,
eigS,
eigS',
eigSH,
eigSH',
-- **** eigenvalues
eigOnlyC,
eigOnlyH,
eigOnlyR,
eigOnlyS,
eigenvalues,
eigenvaluesSH,
eigenvaluesSH',
-}
-- *** QR
-- *** Cholesky
-- *** Hessenberg
-- *** Schur
-- *** LU
-- ** Matrix functions
-- sqrtm, matFunc
expm,
-- ** Nullspace
-- ** Norms
-- ** Misc
-- ** Util
-- * Automatic Differentiation
-- ad
#ifdef WITH_Ad
diff,
#endif
-- * todo arrange
DotS,
MultEq,
-- * to keep types looking ok
D,
module Data.HList.CommonMain,
Complex,
-- ** "Numeric.NumType"
Pos, Neg, Succ, Zero, Neg1,
) where
import Numeric.NumType
import DimMat.Internal
import DimMat.QQ
import Data.HList.CommonMain
import Data.Complex
|
module sample
import extensible_records
import Data.List
-- All functions must be total
%default total
-- *** Initial records ***
r1 : Record [("surname", String), ("age", Int)]
r1 = ("surname" .=. "Bond") .*.
("age" .=. 30) .*.
emptyRec
r2 : Record [("surname", String), ("name", String)]
r2 = ("surname" .=. "Bond") .*.
("name" .=. "James") .*.
emptyRec
r3 : Record [("name", String), ("code", String)]
r3 = ("name" .=. "James") .*.
("code" .=. "007") .*.
emptyRec
-- *** Record Extension ***
rExtended : Record [("name", String), ("surname", String), ("age", Int)]
rExtended = ("name" .=. "James") .*. r1
-- *** Lookup ***
r1Surname : String
r1Surname = r1 .!. "surname"
-- "Bond"
r1Age : Int
r1Age = r1 .!. "age"
-- 30
-- *** Append ***
rAppend : Record [("surname", String), ("age", Int), ("name", String), ("code", String)]
rAppend = r1 .++. r3
-- { "surname" = "Bond", "age" = 30, "name" = "James", "code" = "007" }
-- *** Update ***
rUpdate : Record [("surname", String), ("age", Int)]
rUpdate = updR "surname" r1 "Dean"
-- { "surname" = "Dean", "age" = 30 }
-- *** Delete ***
rDelete : Record [("age", Int)]
rDelete = "surname" .//. r1
-- { "age" = 30 }
-- *** Delete Labels ***
rDeleteLabels1 : Record [("age", Int), ("name", String)]
rDeleteLabels1 = ["surname", "code"] .///. rAppend
-- { "age" = 30, "name" = "James" }
rDeleteLabels2 : Record [("age", Int), ("name", String)]
rDeleteLabels2 = ["code", "surname"] .///. rAppend
-- { "age" = 30, "name" = "James" }
-- *** Left Union ***
rLeftUnion1 : Record [("surname", String), ("age", Int), ("name", String), ("code", String)]
rLeftUnion1 = r1 .||. r3
-- { "surname" = "Bond", "age" = 30, "name" = "James", "code" = "007" }
r4 : Record [("name", String), ("code", String)]
r4 = ("name" .=. "Ronald") .*.
("code" .=. "007") .*.
emptyRec
rLeftUnion2 : Record [("surname", String), ("name", String), ("code", String)]
rLeftUnion2 = r2 .||. r4
-- { "surname" = "Bond", "name" = "James", "code" = "007" }
rLeftUnion3 : Record [("name", String), ("code", String), ("surname", String)]
rLeftUnion3 = r4 .||. r2
-- { "name" = "Ronald", "code" = "007", "surname" = "Bond" }
-- *** Projection ***
r5 : Record [("name", String), ("surname", String), ("age", Int), ("code", String), ("supervisor", String)]
r5 = ("name" .=. "James") .*.
("surname" .=. "Bond") .*.
("age" .=. 30) .*.
("code" .=. "007") .*.
("supervisor" .=. "M") .*.
emptyRec
rProjectLeft : Record [("name", String), ("age", Int), ("supervisor", String)]
rProjectLeft = ["name", "supervisor", "age"] .<. r5
-- { "name" = "James", "age" = 30, "supervisor" = "M" }
rProjectRight : Record [("surname", String), ("code", String)]
rProjectRight = ["name", "supervisor", "age"] .>. r5
-- { "surname" = "Bond", "code" = "007" }
|
lemma (in subset_class) smallest_closed_cdi2: "closed_cdi \<Omega> (smallest_ccdi_sets \<Omega> M)" |
module Main
import Data.List
main : IO ()
main = putStrLn "Hello world"
lst1 : List String
lst1 = ["as", "the"]
lst2 : List String
lst2 = ["as", "them", "the", "here"]
--lst3 : List String
--lst3 = lst1 \\ lst2
|
/-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.adjunction.limits
import category_theory.adjunction.opposites
import category_theory.elements
import category_theory.limits.functor_category
import category_theory.limits.kan_extension
import category_theory.limits.shapes.terminal
import category_theory.limits.types
/-!
# Colimit of representables
This file constructs an adjunction `yoneda_adjunction` between `(Cįµįµ ℤ Type u)` and `ā°` given a
functor `A : C ℤ ā°`, where the right adjoint sends `(E : ā°)` to `c ⦠(A.obj c ā¶ E)` (provided `ā°`
has colimits).
This adjunction is used to show that every presheaf is a colimit of representables.
Further, the left adjoint `colimit_adj.extend_along_yoneda : (Cįµįµ ℤ Type u) ℤ ā°` satisfies
`yoneda ā L ā
A`, that is, an extension of `A : C ℤ ā°` to `(Cįµįµ ℤ Type u) ℤ ā°` through
`yoneda : C ℤ Cįµįµ ℤ Type u`. It is the left Kan extension of `A` along the yoneda embedding,
sometimes known as the Yoneda extension, as proved in `extend_along_yoneda_iso_Kan`.
`unique_extension_along_yoneda` shows `extend_along_yoneda` is unique amongst cocontinuous functors
with this property, establishing the presheaf category as the free cocompletion of a small category.
## Tags
colimit, representable, presheaf, free cocompletion
## References
* [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92]
* https://ncatlab.org/nlab/show/Yoneda+extension
-/
namespace category_theory
noncomputable theory
open category limits
universes uā uā
variables {C : Type uā} [small_category C]
variables {ā° : Type uā} [category.{uā} ā°]
variable (A : C ℤ ā°)
namespace colimit_adj
/--
The functor taking `(E : ā°) (c : Cįµįµ)` to the homset `(A.obj C ā¶ E)`. It is shown in `L_adjunction`
that this functor has a left adjoint (provided `E` has colimits) given by taking colimits over
categories of elements.
In the case where `ā° = Cįµįµ ℤ Type u` and `A = yoneda`, this functor is isomorphic to the identity.
Defined as in [MM92], Chapter I, Section 5, Theorem 2.
-/
@[simps]
def restricted_yoneda : Ⱐℤ (Cįµįµ ℤ Type uā) :=
yoneda ā (whiskering_left _ _ (Type uā)).obj (functor.op A)
/--
The functor `restricted_yoneda` is isomorphic to the identity functor when evaluated at the yoneda
embedding.
-/
def restricted_yoneda_yoneda : restricted_yoneda (yoneda : C ℤ Cįµįµ ℤ Type uā) ā
š _ :=
nat_iso.of_components
(Ī» P, nat_iso.of_components (Ī» X, yoneda_sections_small X.unop _)
(Ī» X Y f, funext $ Ī» x,
begin
dsimp,
rw ā functor_to_types.naturality _ _ x f (š _),
dsimp,
simp,
end))
(Ī» _ _ _, rfl)
/--
(Implementation). The equivalence of homsets which helps construct the left adjoint to
`colimit_adj.restricted_yoneda`.
It is shown in `restrict_yoneda_hom_equiv_natural` that this is a natural bijection.
-/
def restrict_yoneda_hom_equiv (P : Cįµįµ ℤ Type uā) (E : ā°)
{c : cocone ((category_of_elements.Ļ P).left_op ā A)} (t : is_colimit c) :
(c.X ā¶ E) ā (P ā¶ (restricted_yoneda A).obj E) :=
((ulift_trivial _).symm āŖā« t.hom_iso' E).to_equiv.trans
{ to_fun := Ī» k,
{ app := Ī» c p, k.1 (opposite.op āØ_, pā©),
naturality' := Ī» c c' f, funext $ Ī» p,
(k.2 (quiver.hom.op āØf, rflā© :
(opposite.op āØc', P.map f pā© : P.elementsįµįµ) ā¶ opposite.op āØc, pā©)).symm },
inv_fun := Ī» Ļ,
{ val := Ī» p, Ļ.app p.unop.1 p.unop.2,
property := Ī» p p' f,
begin
simp_rw [ā f.unop.2],
apply (congr_fun (Ļ.naturality f.unop.1) p'.unop.2).symm,
end },
left_inv :=
begin
rintro āØkā, kāā©,
ext,
dsimp,
congr' 1,
simp,
end,
right_inv :=
begin
rintro āØ_, _ā©,
refl,
end }
/--
(Implementation). Show that the bijection in `restrict_yoneda_hom_equiv` is natural (on the right).
-/
lemma restrict_yoneda_hom_equiv_natural (P : Cįµįµ ℤ Type uā) (Eā Eā : ā°) (g : Eā ā¶ Eā)
{c : cocone _} (t : is_colimit c) (k : c.X ā¶ Eā) :
restrict_yoneda_hom_equiv A P Eā t (k ā« g) =
restrict_yoneda_hom_equiv A P Eā t k ā« (restricted_yoneda A).map g :=
begin
ext _ X p,
apply (assoc _ _ _).symm,
end
variables [has_colimits ā°]
/--
The left adjoint to the functor `restricted_yoneda` (shown in `yoneda_adjunction`). It is also an
extension of `A` along the yoneda embedding (shown in `is_extension_along_yoneda`), in particular
it is the left Kan extension of `A` through the yoneda embedding.
-/
def extend_along_yoneda : (Cįµįµ ℤ Type uā) ℤ ā° :=
adjunction.left_adjoint_of_equiv
(Ī» P E, restrict_yoneda_hom_equiv A P E (colimit.is_colimit _))
(Ī» P E E' g, restrict_yoneda_hom_equiv_natural A P E E' g _)
@[simp]
lemma extend_along_yoneda_obj (P : Cįµįµ ℤ Type uā) : (extend_along_yoneda A).obj P =
colimit ((category_of_elements.Ļ P).left_op ā A) := rfl
lemma extend_along_yoneda_map {X Y : Cįµįµ ℤ Type uā} (f : X ā¶ Y) :
(extend_along_yoneda A).map f = colimit.pre ((category_of_elements.Ļ Y).left_op ā A)
(category_of_elements.map f).op :=
begin
ext J,
erw colimit.ι_pre ((category_of_elements.Ļ Y).left_op ā A) (category_of_elements.map f).op,
dsimp only [extend_along_yoneda, restrict_yoneda_hom_equiv,
is_colimit.hom_iso', is_colimit.hom_iso, ulift_trivial],
simpa
end
/--
Show `extend_along_yoneda` is left adjoint to `restricted_yoneda`.
The construction of [MM92], Chapter I, Section 5, Theorem 2.
-/
def yoneda_adjunction : extend_along_yoneda A ⣠restricted_yoneda A :=
adjunction.adjunction_of_equiv_left _ _
/--
The initial object in the category of elements for a representable functor. In `is_initial` it is
shown that this is initial.
-/
def elements.initial (A : C) : (yoneda.obj A).elements :=
āØopposite.op A, š _ā©
/--
Show that `elements.initial A` is initial in the category of elements for the `yoneda` functor.
-/
def is_initial (A : C) : is_initial (elements.initial A) :=
{ desc := Ī» s, āØs.X.2.op, comp_id _ā©,
uniq' := Ī» s m w,
begin
simp_rw ā m.2,
dsimp [elements.initial],
simp,
end,
fac' := by rintros s āØāØā©ā©, }
/--
`extend_along_yoneda A` is an extension of `A` to the presheaf category along the yoneda embedding.
`unique_extension_along_yoneda` shows it is unique among functors preserving colimits with this
property (up to isomorphism).
The first part of [MM92], Chapter I, Section 5, Corollary 4.
See Property 1 of <https://ncatlab.org/nlab/show/Yoneda+extension#properties>.
-/
def is_extension_along_yoneda : (yoneda : C ℤ Cįµįµ ℤ Type uā) ā extend_along_yoneda A ā
A :=
nat_iso.of_components
(Ī» X, (colimit.is_colimit _).cocone_point_unique_up_to_iso
(colimit_of_diagram_terminal (terminal_op_of_initial (is_initial _)) _))
begin
intros X Y f,
change (colimit.desc _ āØ_, _ā© ā« colimit.desc _ _) = colimit.desc _ _ ā« _,
apply colimit.hom_ext,
intro j,
rw [colimit.ι_desc_assoc, colimit.ι_desc_assoc],
change (colimit.ι _ _ ā« š _) ā« colimit.desc _ _ = _,
rw [comp_id, colimit.ι_desc],
dsimp,
rw ā A.map_comp,
congr' 1,
end
/-- See Property 2 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/
instance : preserves_colimits (extend_along_yoneda A) :=
(yoneda_adjunction A).left_adjoint_preserves_colimits
/--
Show that the images of `X` after `extend_along_yoneda` and `Lan yoneda` are indeed isomorphic.
This follows from `category_theory.category_of_elements.costructured_arrow_yoneda_equivalence`.
-/
@[simps] def extend_along_yoneda_iso_Kan_app (X) :
(extend_along_yoneda A).obj X ā
((Lan yoneda : (_ ℤ ā°) ℤ _).obj A).obj X :=
let eq := category_of_elements.costructured_arrow_yoneda_equivalence X in
{ hom := colimit.pre (Lan.diagram (yoneda : C ℤ _ ℤ Type uā) A X) eq.functor,
inv := colimit.pre ((category_of_elements.Ļ X).left_op ā A) eq.inverse,
hom_inv_id' :=
begin
erw colimit.pre_pre ((category_of_elements.Ļ X).left_op ā A) eq.inverse,
transitivity colimit.pre ((category_of_elements.Ļ X).left_op ā A) (š _),
congr,
{ exact congr_arg functor.op (category_of_elements.from_to_costructured_arrow_eq X) },
{ ext, simp only [colimit.ι_pre], erw category.comp_id, congr }
end,
inv_hom_id' :=
begin
erw colimit.pre_pre (Lan.diagram (yoneda : C ℤ _ ℤ Type uā) A X) eq.functor,
transitivity colimit.pre (Lan.diagram (yoneda : C ℤ _ ℤ Type uā) A X) (š _),
congr,
{ exact category_of_elements.to_from_costructured_arrow_eq X },
{ ext, simp only [colimit.ι_pre], erw category.comp_id, congr }
end }
/--
Verify that `extend_along_yoneda` is indeed the left Kan extension along the yoneda embedding.
-/
@[simps]
def extend_along_yoneda_iso_Kan : extend_along_yoneda A ā
(Lan yoneda : (_ ℤ ā°) ℤ _).obj A :=
nat_iso.of_components (extend_along_yoneda_iso_Kan_app A)
begin
intros X Y f, simp,
rw extend_along_yoneda_map,
erw colimit.pre_pre (Lan.diagram (yoneda : C ℤ _ ℤ Type uā) A Y) (costructured_arrow.map f),
erw colimit.pre_pre (Lan.diagram (yoneda : C ℤ _ ℤ Type uā) A Y)
(category_of_elements.costructured_arrow_yoneda_equivalence Y).functor,
congr' 1,
apply category_of_elements.costructured_arrow_yoneda_equivalence_naturality,
end
/-- extending `F ā yoneda` along the yoneda embedding is isomorphic to `Lan F.op`. -/
@[simps] def extend_of_comp_yoneda_iso_Lan {D : Type uā} [small_category D] (F : C ℤ D) :
extend_along_yoneda (F ā yoneda) ā
Lan F.op :=
adjunction.nat_iso_of_right_adjoint_nat_iso
(yoneda_adjunction (F ā yoneda))
(Lan.adjunction (Type uā) F.op)
(iso_whisker_right curried_yoneda_lemma' ((whiskering_left Cįµįµ Dįµįµ (Type uā)).obj F.op : _))
end colimit_adj
open colimit_adj
/-- `F ā yoneda` is naturally isomorphic to `yoneda ā Lan F.op`. -/
@[simps] def comp_yoneda_iso_yoneda_comp_Lan {D : Type uā} [small_category D] (F : C ℤ D) :
F ā yoneda ā
yoneda ā Lan F.op :=
(is_extension_along_yoneda (F ā yoneda)).symm āŖā«
iso_whisker_left yoneda (extend_of_comp_yoneda_iso_Lan F)
/--
Since `extend_along_yoneda A` is adjoint to `restricted_yoneda A`, if we use `A = yoneda`
then `restricted_yoneda A` is isomorphic to the identity, and so `extend_along_yoneda A` is as well.
-/
def extend_along_yoneda_yoneda : extend_along_yoneda (yoneda : C ℤ _) ā
š _ :=
adjunction.nat_iso_of_right_adjoint_nat_iso
(yoneda_adjunction _)
adjunction.id
restricted_yoneda_yoneda
/--
A functor to the presheaf category in which everything in the image is representable (witnessed
by the fact that it factors through the yoneda embedding).
`cocone_of_representable` gives a cocone for this functor which is a colimit and has point `P`.
-/
-- Maybe this should be reducible or an abbreviation?
def functor_to_representables (P : Cįµįµ ℤ Type uā) :
(P.elements)įµįµ ℤ Cįµįµ ℤ Type uā :=
(category_of_elements.Ļ P).left_op ā yoneda
/--
This is a cocone with point `P` for the functor `functor_to_representables P`. It is shown in
`colimit_of_representable P` that this cocone is a colimit: that is, we have exhibited an arbitrary
presheaf `P` as a colimit of representables.
The construction of [MM92], Chapter I, Section 5, Corollary 3.
-/
def cocone_of_representable (P : Cįµįµ ℤ Type uā) :
cocone (functor_to_representables P) :=
cocone.extend (colimit.cocone _) (extend_along_yoneda_yoneda.hom.app P)
@[simp] lemma cocone_of_representable_X (P : Cįµįµ ℤ Type uā) :
(cocone_of_representable P).X = P :=
rfl
/-- An explicit formula for the legs of the cocone `cocone_of_representable`. -/
-- Marking this as a simp lemma seems to make things more awkward.
lemma cocone_of_representable_ι_app (P : Cįµįµ ℤ Type uā) (j : (P.elements)įµįµ):
(cocone_of_representable P).ι.app j = (yoneda_sections_small _ _).inv j.unop.2 :=
colimit.ι_desc _ _
/-- The legs of the cocone `cocone_of_representable` are natural in the choice of presheaf. -/
lemma cocone_of_representable_naturality {Pā Pā : Cįµįµ ℤ Type uā} (α : Pā ā¶ Pā)
(j : (Pā.elements)įµįµ) :
(cocone_of_representable Pā).ι.app j ⫠α =
(cocone_of_representable Pā).ι.app ((category_of_elements.map α).op.obj j) :=
begin
ext T f,
simpa [cocone_of_representable_ι_app] using functor_to_types.naturality _ _ α f.op _,
end
/--
The cocone with point `P` given by `the_cocone` is a colimit: that is, we have exhibited an
arbitrary presheaf `P` as a colimit of representables.
The result of [MM92], Chapter I, Section 5, Corollary 3.
-/
def colimit_of_representable (P : Cįµįµ ℤ Type uā) : is_colimit (cocone_of_representable P) :=
begin
apply is_colimit.of_point_iso (colimit.is_colimit (functor_to_representables P)),
change is_iso (colimit.desc _ (cocone.extend _ _)),
rw [colimit.desc_extend, colimit.desc_cocone],
apply_instance,
end
/--
Given two functors Lā and Lā which preserve colimits, if they agree when restricted to the
representable presheaves then they agree everywhere.
-/
def nat_iso_of_nat_iso_on_representables (Lā Lā : (Cįµįµ ℤ Type uā) ℤ ā°)
[preserves_colimits Lā] [preserves_colimits Lā]
(h : yoneda ā Lā ā
yoneda ā Lā) : Lā ā
Lā :=
begin
apply nat_iso.of_components _ _,
{ intro P,
refine (is_colimit_of_preserves Lā (colimit_of_representable P)).cocone_points_iso_of_nat_iso
(is_colimit_of_preserves Lā (colimit_of_representable P)) _,
apply functor.associator _ _ _ āŖā« _,
exact iso_whisker_left (category_of_elements.Ļ P).left_op h },
{ intros Pā Pā f,
apply (is_colimit_of_preserves Lā (colimit_of_representable Pā)).hom_ext,
intro j,
dsimp only [id.def, is_colimit.cocone_points_iso_of_nat_iso_hom, iso_whisker_left_hom],
have :
(Lā.map_cocone (cocone_of_representable Pā)).ι.app j ā« Lā.map f =
(Lā.map_cocone (cocone_of_representable Pā)).ι.app ((category_of_elements.map f).op.obj j),
{ dsimp,
rw [ā Lā.map_comp, cocone_of_representable_naturality],
refl },
rw [reassoc_of this, is_colimit.ι_map_assoc, is_colimit.ι_map],
dsimp,
rw [ā Lā.map_comp, cocone_of_representable_naturality],
refl }
end
variable [has_colimits ā°]
/--
Show that `extend_along_yoneda` is the unique colimit-preserving functor which extends `A` to
the presheaf category.
The second part of [MM92], Chapter I, Section 5, Corollary 4.
See Property 3 of https://ncatlab.org/nlab/show/Yoneda+extension#properties.
-/
def unique_extension_along_yoneda (L : (Cįµįµ ℤ Type uā) ℤ ā°) (hL : yoneda ā L ā
A)
[preserves_colimits L] :
L ā
extend_along_yoneda A :=
nat_iso_of_nat_iso_on_representables _ _ (hL āŖā« (is_extension_along_yoneda _).symm)
/--
If `L` preserves colimits and `ā°` has them, then it is a left adjoint. This is a special case of
`is_left_adjoint_of_preserves_colimits` used to prove that.
-/
def is_left_adjoint_of_preserves_colimits_aux (L : (Cįµįµ ℤ Type uā) ℤ ā°) [preserves_colimits L] :
is_left_adjoint L :=
{ right := restricted_yoneda (yoneda ā L),
adj := (yoneda_adjunction _).of_nat_iso_left
((unique_extension_along_yoneda _ L (iso.refl _)).symm) }
/--
If `L` preserves colimits and `ā°` has them, then it is a left adjoint. Note this is a (partial)
converse to `left_adjoint_preserves_colimits`.
-/
def is_left_adjoint_of_preserves_colimits (L : (C ℤ Type uā) ℤ ā°) [preserves_colimits L] :
is_left_adjoint L :=
let e : (_ ℤ Type uā) ā (_ ℤ Type uā) := (op_op_equivalence C).congr_left,
t := is_left_adjoint_of_preserves_colimits_aux (e.functor ā L : _)
in by exactI adjunction.left_adjoint_of_nat_iso (e.inv_fun_id_assoc _)
end category_theory
|
Formal statement is: lemma complex_cnj_fact [simp]: "cnj (fact n) = fact n" Informal statement is: The complex conjugate of the factorial of a natural number is the factorial of that natural number. |
#pragma once
#ifdef QP_SOLVER_SPARSE
#include <Eigen/Sparse>
#endif
#include <Eigen/Dense>
#include <limits>
#include <vector>
#define QP_SOLVER_PRINTING
namespace qp_solver {
/** Quadratic Problem
* minimize 0.5 x' P x + q' x
* subject to l <= A x <= u
*/
template <typename Scalar = double>
struct QuadraticProblem {
using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
#ifdef QP_SOLVER_SPARSE
using Matrix = Eigen::SparseMatrix<Scalar>;
Eigen::Matrix<int, Eigen::Dynamic, 1> P_col_nnz;
Eigen::Matrix<int, Eigen::Dynamic, 1> A_col_nnz;
#else
using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
#endif
const Matrix *P;
const Vector *q;
const Matrix *A;
const Vector *l;
const Vector *u;
};
template <typename Scalar>
struct QPSolverSettings {
Scalar rho = 1e-1; /**< ADMM rho step, 0 < rho */
Scalar sigma = 1e-6; /**< ADMM sigma step, 0 < sigma, (small) */
Scalar alpha = 1.0; /**< ADMM overrelaxation parameter, 0 < alpha < 2,
values in [1.5, 1.8] give good results (empirically) */
Scalar eps_rel = 1e-3; /**< Relative tolerance for termination, 0 < eps_rel */
Scalar eps_abs = 1e-3; /**< Absolute tolerance for termination, 0 < eps_abs */
int max_iter = 1000; /**< Maximal number of iteration, 0 < max_iter */
int check_termination = 25; /**< Check termination after every Nth iteration, 0 (disabled) or 0
< check_termination */
bool warm_start = false; /**< Warm start solver, reuses previous x,z,y */
bool adaptive_rho = false; /**< Adapt rho to optimal estimate */
Scalar adaptive_rho_tolerance =
5; /**< Minimal for rho update factor, 1 < adaptive_rho_tolerance */
int adaptive_rho_interval = 25; /**< change rho every Nth iteration, 0 < adaptive_rho_interval,
set equal to check_termination to save computation */
bool verbose = false;
#ifdef QP_SOLVER_PRINTING
void print() const {
printf("ADMM settings:\n");
printf(" sigma %.2e\n", sigma);
printf(" rho %.2e\n", rho);
printf(" alpha %.2f\n", alpha);
printf(" eps_rel %.1e\n", eps_rel);
printf(" eps_abs %.1e\n", eps_abs);
printf(" max_iter %d\n", max_iter);
printf(" adaptive_rho %d\n", adaptive_rho);
printf(" warm_start %d\n", warm_start);
}
#endif
};
typedef enum { SOLVED, MAX_ITER_EXCEEDED, UNSOLVED, NUMERICAL_ISSUES, UNINITIALIZED } QPSolverStatus;
template <typename Scalar>
struct QPSolverInfo {
QPSolverStatus status = UNINITIALIZED; /**< Solver status */
int iter = 0; /**< Number of iterations */
int rho_updates = 0; /**< Number of rho updates (factorizations) */
Scalar rho_estimate = 0; /**< Last rho estimate */
Scalar res_prim = 0; /**< Primal residual */
Scalar res_dual = 0; /**< Dual residual */
#ifdef QP_SOLVER_PRINTING
void print() const {
printf("ADMM info:\n");
printf(" status ");
switch (status) {
case SOLVED:
printf("SOLVED\n");
break;
case MAX_ITER_EXCEEDED:
printf("MAX_ITER_EXCEEDED\n");
break;
case UNSOLVED:
printf("UNSOLVED\n");
break;
case NUMERICAL_ISSUES:
printf("NUMERICAL_ISSUES\n");
break;
default:
printf("UNINITIALIZED\n");
};
printf(" iter %d\n", iter);
printf(" rho_updates %d\n", rho_updates);
printf(" rho_estimate %f\n", rho_estimate);
printf(" res_prim %f\n", res_prim);
printf(" res_dual %f\n", res_dual);
}
#endif
};
/**
* minimize 0.5 x' P x + q' x
* subject to l <= A x <= u
*
* with:
* x element of R^n
* Ax element of R^m
*/
template <typename SCALAR>
class QPSolver {
public:
using Scalar = SCALAR;
using QP = QuadraticProblem<Scalar>;
using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
#ifdef QP_SOLVER_SPARSE
using Matrix = Eigen::SparseMatrix<Scalar, Eigen::ColMajor>;
using LinearSolver = Eigen::SimplicialLDLT<Matrix, Eigen::Lower>;
#else
using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
using LinearSolver = Eigen::LDLT<Matrix, Eigen::Lower>;
#endif
using Settings = QPSolverSettings<Scalar>;
using Info = QPSolverInfo<Scalar>;
enum { INEQUALITY_CONSTRAINT, EQUALITY_CONSTRAINT, LOOSE_BOUNDS } ConstraintType;
static constexpr Scalar RHO_MIN = 1e-6;
static constexpr Scalar RHO_MAX = 1e+6;
static constexpr Scalar RHO_TOL = 1e-4;
static constexpr Scalar RHO_EQ_FACTOR = 1e+3;
static constexpr Scalar LOOSE_BOUNDS_THRESH = 1e+16;
static constexpr Scalar DIV_BY_ZERO_REGUL = std::numeric_limits<Scalar>::epsilon();
// enforce 16 byte alignment
// https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
/** Constructor */
QPSolver() = default;
/** Setup solver for QP. */
void setup(const QP &qp);
/** Update solver for QP of same size as initial setup. */
void update_qp(const QP &qp);
/** Solve the QP. */
void solve(const QP &qp);
inline const Vector &primal_solution() const { return x; }
inline Vector &primal_solution() { return x; }
inline const Vector &dual_solution() const { return y; }
inline Vector &dual_solution() { return y; }
inline const Settings &settings() const { return settings_; }
inline Settings &settings() { return settings_; }
inline const Info &info() const { return info_; }
inline Info &info() { return info_; }
/* Public funcitions for unit testing */
static void constr_type_init(const Vector& l, const Vector& u, Eigen::VectorXi &constr_type);
private:
/* Construct the KKT matrix of the form
*
* [[ P + sigma*I, A' ],
* [ A, -1/rho.*I ]]
*
* If LinearSolver_UpLo parameter is Eigen::Lower, then only the lower
* triangular part is constructed to optimize memory.
*
* Note: For Eigen::ConjugateGradient it is advised to set Upper|Lower for
* best performance.
*/
void construct_KKT_mat(const QP &qp);
/** KKT matrix value update, assumes same sparsity pattern */
void update_KKT_mat(const QP &qp);
void update_KKT_rho();
bool factorize_KKT();
bool compute_KKT();
#ifdef QP_SOLVER_SPARSE
void sparse_insert_at(Matrix &dst, int row, int col, const Matrix &src) const
#endif
void form_KKT_rhs(const QP &qp, Vector &rhs);
void box_projection(Vector &z, const Vector &l, const Vector &u);
void constr_type_init(const QP &qp);
void rho_vec_update(Scalar rho0);
void update_state(const QP &qp);
Scalar rho_estimate(const Scalar rho0, const QP &qp) const;
Scalar eps_prim(const QP &qp) const;
Scalar eps_dual(const QP &qp) const;
Scalar residual_prim(const QP &qp) const;
Scalar residual_dual(const QP &qp) const;
bool termination_criteria(const QP &qp);
#ifdef QP_SOLVER_PRINTING
void print_status(const QP &qp) const;
#endif
size_t n; //< number of variables
size_t m; //< number of constraints
// Solver state variables
int iter;
Vector x; //< primal variable, size n
Vector z; //< additional variable, size m
Vector y; //< dual variable, size m
Vector x_tilde;
Vector z_tilde;
Vector z_prev;
Vector rho_vec;
Vector rho_inv_vec;
Scalar rho;
Vector rhs;
Vector x_tilde_nu;
// State
Scalar res_prim;
Scalar res_dual;
Scalar max_Ax_z_norm_;
Scalar max_Px_ATy_q_norm_;
Eigen::VectorXi constr_type; /**< constraint type classification */
Settings settings_;
Info info_;
Matrix kkt_mat;
LinearSolver linear_solver;
};
extern template class QPSolver<double>;
extern template class QPSolver<float>;
} // namespace qp_solver
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.