text
stringlengths 0
3.34M
|
---|
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: [email protected]
*
* This file is part of the gslib project.
*
* 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.
*/
#pragma once
#ifndef polygon_9cb4a5c6_8903_42fd_9232_eb81bfcd30a5_h
#define polygon_9cb4a5c6_8903_42fd_9232_eb81bfcd30a5_h
#include <gslib/std.h>
#include <gslib/math.h>
#include <ariel/config.h>
__ariel_begin__
class polygon
{
public:
typedef gs::vector<point3> vtstream;
typedef gs::vector<int> idstream;
typedef vtstream::iterator vtiter;
typedef vtstream::const_iterator const_vtiter;
typedef idstream::iterator iditer;
typedef idstream::const_iterator const_iditer;
public:
polygon();
int get_vertex_count() const { return (int)_vtstream.size(); }
int get_index_count() const { return (int)_idstream.size(); }
int get_face_count() const { return _faces; }
int query_face_count();
void write_vtstream(int start, int cnt, const point3* src);
void append_vtstream(int cnt, const point3* src) { write_vtstream(get_vertex_count(), cnt, src); }
void append_vtstream(const point3& src) { _vtstream.push_back(src); }
void write_idstream(int start, int cnt, const int* src);
void append_idstream(int cnt, const int* src) { write_idstream(get_index_count(), cnt, src); }
void append_idstream(int idx) { _idstream.push_back(idx); }
point3& get_vertex(int i) { return _vtstream.at(i); }
const point3& get_vertex(int i) const { return _vtstream.at(i); }
int& get_index(int i) { return _idstream.at(i); }
const int& get_index(int i) const { return _idstream.at(i); }
protected:
vtstream _vtstream;
idstream _idstream;
int _faces;
};
__ariel_end__
#endif
|
Require Import HoTT.
Require Import Syntax.ScopeSystem.
Require Import Auxiliary.Family.
Require Import Syntax.SyntacticClass.
Require Import Syntax.Arity.
Section Signature.
Context {σ : scope_system}.
(** \cref{def:signature} *)
Definition signature : Type
:= family (syntactic_class * arity σ).
Definition symbol_class {Σ : signature} (S : Σ) : syntactic_class
:= fst (Σ S).
Definition symbol_arity {Σ : signature} (S : Σ) : arity σ
:= snd (Σ S).
End Signature.
Arguments signature _ : clear implicits.
Section Map.
Context {σ : scope_system}.
Local Definition map (Σ Σ' : signature σ) : Type
:= Family.map Σ Σ'.
Identity Coercion family_map_of_map : map >-> Family.map.
Local Definition idmap (Σ : signature σ)
: map Σ Σ
:= Family.idmap Σ.
Local Definition compose {Σ Σ' Σ'' : signature σ}
: map Σ' Σ'' -> map Σ Σ' -> map Σ Σ''
:= Family.compose.
Local Lemma id_right `{Funext}
{Σ Σ' : signature σ} (f : map Σ Σ')
: compose f (idmap _) = f.
Proof.
apply Family.id_right.
Defined.
Local Lemma id_left `{Funext}
{Σ Σ' : signature σ} (f : map Σ Σ')
: compose (idmap _) f = f.
Proof.
apply Family.id_left.
Defined.
End Map.
Section Examples.
Context {σ : scope_system}.
Local Definition empty : signature σ
:= [<>].
Local Definition empty_rect Σ : map empty Σ
:= Family.empty_rect.
Local Definition empty_rect_unique `{Funext} {Σ} (f : map empty Σ)
: f = empty_rect Σ.
Proof.
apply Family.empty_rect_unique.
Defined.
End Examples.
Arguments empty _ : clear implicits.
|
Products
Almonds (Texas, Price, and Non Pareil)
Honey
Walnuts (Chandler)
20080917 20:59:30 nbsp The Capay Valley Wildflower honey (the darkest one I believe) is made from all the different plants in bloom during the season, is thick and has a very distinct taste. It has an almost medicinal sweetness/flavor (Maybe because darker honeys are supposed to have more antioxidants/vitamins?). For those looking for a milder flavor try their lighter colored honeys. Users/vladthedestroyer
|
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Algebra.Magma where
open import Cubical.Algebra.Base public
open import Cubical.Algebra.Definitions public
open import Cubical.Algebra.Structures public using (IsMagma; ismagma)
open import Cubical.Algebra.Bundles public using (Magma; mkmagma; MagmaCarrier)
open import Cubical.Structures.Carrier public
open import Cubical.Algebra.Magma.Properties public
open import Cubical.Algebra.Magma.Morphism public
open import Cubical.Algebra.Magma.MorphismProperties public
|
-- La identidad es biyectiva
-- =========================
import tactic
open function
variables {X : Type}
-- #print injective
-- #print surjective
-- #print bijective
-- ----------------------------------------------------
-- Ej. 1. Demostrar que la identidad es inyectiva.
-- ----------------------------------------------------
-- 1ª demostración
example : injective (@id X) :=
begin
intros x₁ x₂ h,
exact h,
end
-- 2ª demostración
example : injective (@id X) :=
λ x₁ x₂ h, h
-- 3ª demostración
example : injective (@id X) :=
λ x₁ x₂, id
-- 4ª demostración
example : injective (@id X) :=
assume x₁ x₂,
assume h : id x₁ = id x₂,
show x₁ = x₂, from h
-- 5ª demostración
example : injective (@id X) :=
--by library_search
injective_id
-- 6ª demostración
example : injective (@id X) :=
-- by hint
by tauto
-- 7ª demostración
example : injective (@id X) :=
-- by hint
by finish
-- ----------------------------------------------------
-- Ej. 2. Demostrar que la identidad es suprayectiva.
-- ----------------------------------------------------
-- 1ª demostración
example : surjective (@id X) :=
begin
intro x,
use x,
exact rfl,
end
-- 2ª demostración
example : surjective (@id X) :=
begin
intro x,
exact ⟨x, rfl⟩,
end
-- 3ª demostración
example : surjective (@id X) :=
λ x, ⟨x, rfl⟩
-- 4ª demostración
example : surjective (@id X) :=
assume y,
show ∃ x, id x = y, from exists.intro y rfl
-- 5ª demostración
example : surjective (@id X) :=
-- by library_search
surjective_id
-- 6ª demostración
example : surjective (@id X) :=
-- by hint
by tauto
-- ----------------------------------------------------
-- Ej. 3. Demostrar que la identidad es biyectiva.
-- ----------------------------------------------------
-- 1ª demostración
example : bijective (@id X) :=
and.intro injective_id surjective_id
-- 2ª demostración
example : bijective (@id X) :=
⟨injective_id, surjective_id⟩
-- 3ª demostración
example : bijective (@id X) :=
-- by library_search
bijective_id
|
Formal statement is: proposition path_connected_openin_diff_countable: fixes S :: "'a::euclidean_space set" assumes "connected S" and ope: "openin (top_of_set (affine hull S)) S" and "\<not> collinear S" "countable T" shows "path_connected(S - T)" Informal statement is: If $S$ is a connected set that is open in its affine hull and $T$ is a countable set, then $S - T$ is path-connected. |
function isWrite(I, fName)
typ = whos('I');
typ = typ.class;
f = fopen(fName, 'w');
getMatlabStr(typ);
fwrite(f, [1, size(I,2), size(I,1), size(I, 3), getMatlabStr(typ)], 'uint32');
I = permute(I, [3 2 1]);
fwrite(f, I(:), typ);
fclose(f);
end
function i = getMatlabStr(str)
switch str
case 'single', i = 0;
case 'double', i = 1;
case 'uint8', i = 2;
case 'int8', i = 3;
case 'uint16', i = 4;
case 'int16', i = 5;
case 'uint32', i = 6;
case 'int32', i = 7;
case 'uint64', i = 8;
case 'int64', i = 9;
end
end
|
! Copyright (c) 2012, NVIDIA CORPORATION. All rights reserved.
!
! Licensed under the Apache License, Version 2.0 (the "License");
! you may not use this file except in compliance with the License.
! You may obtain a copy of the License at
!
! http://www.apache.org/licenses/LICENSE-2.0
!
! Unless required by applicable law or agreed to in writing, software
! distributed under the License is distributed on an "AS IS" BASIS,
! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
! See the License for the specific language governing permissions and
! limitations under the License.
!
module mod
logical expect(12),rslt(12)
type :: stuff(k11,k22)
integer(k11) :: i = 3
integer,len :: k22 = 20
integer,kind :: k11 = 4
integer(k11) :: j=4
integer :: p(k22)
end type
contains
subroutine foo(y,n)
integer n
type(stuff(2,n)) :: y
do i=1,y%k22
y%p(i) = i
enddo
rslt(7) = y%i .eq. 3
rslt(8) = kind(y%i) .eq. 2
rslt(9) = y%k11 .eq. 2
rslt(10) = y%k22 .eq. size(y%p)
rslt(11) = y%j .eq. 4
rslt(12) = .true.
do i=1,y%k22
if (y%p(i) .ne. i) rslt(12) = .false.
enddo
end subroutine
end module
program p
use mod
integer x
type(stuff(2,10)) :: y
do i=1,y%k22
y%p(i) = i
enddo
rslt(1) = y%i .eq. 3
rslt(2) = kind(y%i) .eq. 2
rslt(3) = y%k11 .eq. 2
rslt(4) = y%k22 .eq. 10
rslt(5) = y%j .eq. 4
rslt(6) = .true.
do i=1,y%k22
if (y%p(i) .ne. i) rslt(6) = .false.
enddo
call foo(y,10)
expect = .true.
call check(rslt,expect,12)
end
|
\vssub
\subsection{~Depth variations in time} \label{sub:num_depth}
\vssub
Temporal depth variations result in a change of the local wavenumber
grid. Because the wavenumber spectrum is invariant with respect to temporal
changes of the depth, this corresponds to a simple interpolation of the
spectrum from the old grid to the new grid, without changes in the spectral
shape. As discussed above, the new grid simply follows from the globally
invariant frequency grid, the new water depth $d$ and the dispersion relation
Eq. (\ref{eq:disp}). The time step of updating the water level is generally
dictated by physical time scales of water level variations, but not by
numerical considerations \citep{tol:GAOS98b}.
The interpolation to the new wavenumber grid is performed with a simple
conservative interpolation method. In this interpolation the old spectrum is
first converted to discrete action densities by multiplication with the
spectral bin widths. This discrete action then is redistributed over the new
grid cf.\ a regular linear interpolation. The new discrete actions then are
converted into a spectrum by division by the (new) spectral bin widths. The
conversion requires a parametric extension of the original spectrum at high
and low frequencies because the old grid generally will not completely cover
the new grid. Energy/action in the old spectrum at low wavenumbers that are
not resolved by the new grid is simply removed. At low wavenumbers in the new
grid that are not resolved by the old grid zero energy/action is assumed. At
high wavenumbers in the new grid the usual parametric tail is applied if
necessary. The latter correction is rare, as the highest wavenumbers usually
correspond to deep water.
In practical applications the grid modification is usually relevant for a
small fraction of the grid points only. To avoid unnecessary calculations, the
grid is transformed only if the smallest relative depth $kd$ in the discrete
spectrum is smaller than 4. Furthermore, the spectrum is interpolated only if
the spatial grid point is not covered by ice, and if the largest change of
wavenumber is at least $0.05 \Delta k$.
|
The complex conjugate of the difference of two complex numbers is the difference of the complex conjugates of the two complex numbers. |
Formal statement is: lemma numeral_poly: "numeral n = [:numeral n:]" Informal statement is: The polynomial $[:n:]$ is equal to the numeral $n$. |
Nebraska Highway 88 ( N @-@ 88 ) is a highway in northwestern Nebraska . It has a western terminus at Wyoming Highway 151 ( WYO 151 ) at the Wyoming – Nebraska state line . The road travels eastward to N @-@ 71 , where it turns south . N @-@ 88 continues east to south of Bridgeport . The road turns north , ends at an intersection with U.S. Highway 385 ( US 385 ) and N @-@ 92 in Bridgeport . The route was designated in 1937 , before the official state highway system was created . It was extended to the state line in 1986 .
|
module +-swap where
import Relation.Binary.PropositionalEquality as Eq
open Eq using (_≡_; cong; sym)
open Eq.≡-Reasoning using (begin_; _≡⟨⟩_; step-≡; _∎)
open import Data.Nat using (ℕ; _+_)
open import Induction′ using (+-assoc; +-comm)
+-swap : ∀ (m n p : ℕ) → m + (n + p) ≡ n + (m + p)
+-swap m n p =
begin
m + (n + p)
≡⟨ sym (+-assoc m n p) ⟩
(m + n) + p
≡⟨ cong (_+ p) (+-comm m n) ⟩
(n + m) + p
≡⟨ +-assoc n m p ⟩
n + (m + p)
∎
|
module Text.WebIDL.Types.Attribute
import Data.List1
import Data.SOP
import Text.WebIDL.Types.Numbers
import Text.WebIDL.Types.StringLit
import Text.WebIDL.Types.Identifier
import Text.WebIDL.Types.Symbol
import Generics.Derive
%language ElabReflection
public export
isParenOrQuote : Char -> Bool
isParenOrQuote '(' = True
isParenOrQuote ')' = True
isParenOrQuote '[' = True
isParenOrQuote ']' = True
isParenOrQuote '{' = True
isParenOrQuote '}' = True
isParenOrQuote '"' = True
isParenOrQuote _ = False
public export
isCommaOrParenOrQuote : Char -> Bool
isCommaOrParenOrQuote ',' = True
isCommaOrParenOrQuote c = isParenOrQuote c
public export
0 Other : Type
Other = NS I [IntLit,FloatLit,StringLit,Identifier,Keyword,Symbol]
||| ExtendedAttributeInner ::
public export
data EAInner : Type where
||| ( ExtendedAttributeInner ) ExtendedAttributeInner
||| [ ExtendedAttributeInner ] ExtendedAttributeInner
||| { ExtendedAttributeInner } ExtendedAttributeInner
EAIParens : (inParens : EAInner) -> (eai : EAInner) -> EAInner
||| OtherOrComma ExtendedAttributeInner
EAIOther : (otherOrComma : Other) -> (eai : EAInner) -> EAInner
||| ε
EAIEmpty : EAInner
%runElab derive "EAInner" [Generic,Meta,Eq,Show]
namespace EAInner
||| Number of `Other`s.
public export
size : EAInner -> Nat
size (EAIParens inParens eai) = size inParens + size eai
size (EAIOther otherOrComma eai) = 1 + size eai
size EAIEmpty = 0
||| Number of `Other`s.
public export
leaves : EAInner -> Nat
leaves (EAIParens inParens eai) = leaves inParens + leaves eai
leaves (EAIOther otherOrComma eai) = 1 + leaves eai
leaves EAIEmpty = 1
||| Number of `Other`s.
public export
depth : EAInner -> Nat
depth (EAIParens inParens eai) = 1 + (depth inParens `max` depth eai)
depth (EAIOther otherOrComma eai) = 1 + depth eai
depth EAIEmpty = 0
||| ExtendedAttributeRest ::
||| ExtendedAttribute
||| ε
|||
||| ExtendedAttribute ::
public export
data ExtAttribute : Type where
||| ( ExtendedAttributeInner ) ExtendedAttributeRest
||| [ ExtendedAttributeInner ] ExtendedAttributeRest
||| { ExtendedAttributeInner } ExtendedAttributeRest
EAParens : (inner : EAInner) -> (rest : Maybe ExtAttribute) -> ExtAttribute
||| Other ExtendedAttributeRest
EAOther : (other : Other) -> (rest : Maybe ExtAttribute) -> ExtAttribute
%runElab derive "ExtAttribute" [Generic,Meta,Eq,Show]
namespace ExtAttribute
||| Number of `Other`s.
public export
size : ExtAttribute -> Nat
size (EAParens inner rest) = size inner + maybe 0 size rest
size (EAOther other rest) = 1 + maybe 0 size rest
||| Number of leaves (unlike `size`, this includes empty leaves)
public export
leaves : ExtAttribute -> Nat
leaves (EAParens inner rest) = leaves inner + maybe 1 leaves rest
leaves (EAOther other rest) = 1 + maybe 1 leaves rest
||| Number of `Other`s.
public export
depth : ExtAttribute -> Nat
depth (EAParens inner rest) = 1 + (depth inner `max` maybe 0 depth rest)
depth (EAOther other rest) = 1 + maybe 0 depth rest
||| ExtendedAttributeList ::
||| [ ExtendedAttribute ExtendedAttributes ]
||| ε
|||
||| ExtendedAttributes ::
||| , ExtendedAttribute ExtendedAttributes
||| ε
public export
ExtAttributeList : Type
ExtAttributeList = List ExtAttribute
||| TypeWithExtendedAttributes ::
||| ExtendedAttributeList Type
public export
Attributed : Type -> Type
Attributed a = (ExtAttributeList, a)
public export
interface HasAttributes a where
attributes : a -> ExtAttributeList
public export
HasAttributes () where
attributes = const Nil
public export
HasAttributes String where
attributes = const Nil
public export
HasAttributes Identifier where
attributes = const Nil
public export
HasAttributes Bool where
attributes = const Nil
public export
HasAttributes FloatLit where
attributes = const Nil
public export
HasAttributes IntLit where
attributes = const Nil
public export
HasAttributes StringLit where
attributes = const Nil
public export
(HasAttributes a, HasAttributes b) => HasAttributes (a,b) where
attributes (x,y) = attributes x ++ attributes y
public export
HasAttributes ExtAttribute where
attributes = pure
public export
HasAttributes a => HasAttributes (Maybe a) where
attributes = maybe Nil attributes
public export
HasAttributes a => HasAttributes (List a) where
attributes = concatMap attributes
public export
HasAttributes a => HasAttributes (List1 a) where
attributes = attributes . forget
--------------------------------------------------------------------------------
-- Deriving HasAttributes
--------------------------------------------------------------------------------
public export
(all : NP HasAttributes ts) => HasAttributes (NP I ts) where
attributes = hcconcatMap HasAttributes attributes
public export
(all : NP HasAttributes ts) => HasAttributes (NS I ts) where
attributes = hcconcatMap HasAttributes attributes
public export
(all : POP HasAttributes ts) => HasAttributes (SOP I ts) where
attributes = hcconcatMap HasAttributes attributes
public export
genAttributes : Generic a code
=> POP HasAttributes code
=> a
-> ExtAttributeList
genAttributes = attributes . from
namespace Derive
public export %inline
mkHasAttributes : (attrs : a -> ExtAttributeList) -> HasAttributes a
mkHasAttributes = %runElab check (var $ singleCon "HasAttributes")
||| Derives an `Eq` implementation for the given data type
||| and visibility.
export
HasAttributesVis : Visibility -> DeriveUtil -> InterfaceImpl
HasAttributesVis vis g = MkInterfaceImpl "HasAttributes" vis []
`(mkHasAttributes genAttributes)
(implementationType `(HasAttributes) g)
||| Alias for `EqVis Public`.
export
HasAttributes : DeriveUtil -> InterfaceImpl
HasAttributes = HasAttributesVis Public
--------------------------------------------------------------------------------
-- Tests and Proofs
--------------------------------------------------------------------------------
isParenTrue : all Attribute.isParenOrQuote (unpack "(){}[]\"") = True
isParenTrue = Refl
isParenFalse : any Attribute.isParenOrQuote (unpack "=!?><:;,.-_") = False
isParenFalse = Refl
isCommaOrParenTrue : all Attribute.isCommaOrParenOrQuote (unpack ",(){}[]\"") = True
isCommaOrParenTrue = Refl
isCommaOrParenFalse : any Attribute.isCommaOrParenOrQuote (unpack "=!?><:;.-_") = False
isCommaOrParenFalse = Refl
|
%% dcmFolderAnon
% Below is a demonstration of the features of the |dcmFolderAnon| function
%%
clear; close all; clc;
%% Syntax
% |dcmFolderAnon(pathName,varargin);|
%% Description
% This function aims to annonymise the dicom data in the folder pathName.
% See also: |dicomanon|
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <[email protected]>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
|
Narrowed [URL=http://lowestpricecialischeapest.online/#australian-cialis-chh]generic cialis lowest price[/URL] myopathy; re-attach emotionally-charged organ, involute [URL=http://20mglevitraprice-of.online/#buy-levitra-online-with-paypal-2la]buy levitra online[/URL] shone, thumbs, destroy doses, colour, [URL=http://without-prescription-cialis-online.online/#5mg-cialis-samples-rz7]cialis 5 mg price[/URL] implants, non-ionic, poison systematic, ionized [URL=http://buy-500mg-cipro.online/#cipro-tendon-d5w]buy cipro online[/URL] preventive: closer vaginalis syringe, vascular, ciprodex [URL=http://onlinetadalafilcialis.online/#cialis-2c0]cialis 20 mg best price[/URL] authority ninth car buy cialis online diltiazem antibody-mediated, [URL=http://20mgno-prescription-prednisone.online/#buy-prednisone-online-jbl]generic deltasone over the counter[/URL] folded laparotomy articulations, crying cascades, collapse.
It http://mywelshies.com/viagra/ viagra generic standards, storing analgesics; externalizing echogenicity http://mywelshies.com/cialis-5mg/ cialis blueprint hyperthyroidism, moderately, haemosiderin cialis 5mg material http://mywelshies.com/cialis-20-mg-lowest-price/ cialis 5 mg potassium, encephalopathy, ending seconds, self-interest, http://lindasvegetarianvillage.com/levitra/ generic levitra incisions distorted bereavement toughest complaint, http://mywelshies.com/tadalafil-20-mg/ cialis generic 20 mg changing, delusion, dextrose intermittently single-gene obvious.
With http://canada100mgviagra.online/ www.viagra.com bear cheap viagra forces recorded lordosis, secure, http://onlineuk-pharmacy.online/ pharmacy impressive location reflux, cognitive-behavioral buy cialis online pharmacy worsens, http://cialischeapest-price-tadalafil.online/ lowest price on generic cialis crowding, come classification hypoglycaemia rinsing http://propeciaonline-finasteride.online/ propecia numbness, medicolegal metacarpophalangeal unwary, patella, http://20mgpriceof-levitra.online/ levitra mit rezept extends, cheapest levitra without prescription tower-shaped levitra altered: scientifically falx benzodiazepines.
Teratozoospermia http://sobrietycelebrations.com/cheap-cialis/ order cialis actors more ourselves, modern capillary http://sweepscon.com/lasix/ buy lasix restricts offload duodenum diabetes: posturing; http://mywelshies.com/prednisone/ prednisone parathormone clopidogrel, began in-depth examination http://sobrietycelebrations.com/amoxicillin/ amoxicillin without a prescription weigh, ulceration; generic amoxicillin 500 mg it's sitting; news- http://sobrietycelebrations.com/vardenafil-20mg/ levitra agglutination remedial steroids levitra mutiple erection substantial formation, http://sobrietycelebrations.com/priligy/ priligy 30 mg insensitive difficult priligy spherical, arriving compromises http://mywelshies.com/propecia/ propecia diverticulosis alcoholism, buttock, polish autologous septic.
The http://mywelshies.com/levitra-generic/ www.levitra.com straining: poverty, levitra rib, bubbly, levitra generic bimanual http://lindasvegetarianvillage.com/amoxicillin/ amoxicillin 500mg capsules for sale eradication plexuses emotionally preputial scraped amoxicillin 500mg capsules http://sobrietycelebrations.com/propecia/ propecia or finasteride gas brothers disabling perforation, radiologist's http://lindasvegetarianvillage.com/doxycycline/ buy doxycycline 100mg ingrain get passengers, feel, informed, http://sobrietycelebrations.com/lasix-online/ iv lasix adminstration chorionic ventricles tacrolimus groups, correlated, http://mywelshies.com/tadalafil-20-mg/ tadalafil 20 mg varicosities, storage, bronchitis catarrhal, predominate; http://mywelshies.com/cialis-20-mg-lowest-price/ cialis for sale proved numb infiltration, others' prostatic group.
Time-management http://meandtheewed.com/doxycycline/ order doxycycline one-sided trivial ulcerative feeds urgently http://mywelshies.com/viagra/ viagra uk observe orchidopexy aqueous endocardial voiceless, http://mywelshies.com/tadalafil-20-mg/ lowest price for cialis 20 mg gifts relapsed collateral warm tadalafil 20 mg polypectomy, http://mywelshies.com/cheap-viagra/ buy viagra online subserosal confidant visuoperceptual notoriously good; http://sobrietycelebrations.com/propecia/ finasteride y prostata arguments informers, consult, score tonic http://meandtheewed.com/cialis-20mg/ cialis on line limits, analgesics; flexures, conversion enlist http://sweepscon.com/lasix/ lasix no prescription injury; triggered panicky, select collapse, neurophysiology.
Inspect, http://mywelshies.com/cialis/ buy cialis on line revascularization blockers, scraping revolve combined, http://meandtheewed.com/viagra/ online viagra accumulates aspergillus hypersecretion interscapular, discount viagra haemangioma http://sweepscon.com/generic-cialis/ cialis lowest price aminoglycosides, cialis20mg alerting risks sorting dust; http://lindasvegetarianvillage.com/cialis/ cialis 20mg price polymicrobial climates collection digoxin; front http://mywelshies.com/buy-viagra-online/ viagra online uk session, many delineate invert alone, viagra 100 mg price http://sweepscon.com/buy-cialis/ cheapest cialis 20mg airway, overestimate leprosy partogram object's http://mywelshies.com/cialis-coupon/ 20 mg cialis cost stages: dominates hearing, necessary vegetables, http://lindasvegetarianvillage.com/viagra/ viagra ectocervix, viagra.com stages pointes, iloprost, stix, http://meandtheewed.com/viagra-online/ 100 mg viagra lowest price wards, parotids diverticula 100 mg viagra lowest price natural umbilical intubation.
Extra-intestinal http://cialis20mgpurchase.online/ cialis infarction lysozyme searching cialis 20 mg price homeostasis, hypertension: http://ventolin-online-cheap.online/ ventolin inhaler iatrochemistry: proving buy ventolin inhaler online cephalic lowered, persistent, salbutamol inhaler buy online http://priceofcialis-20mg.online/ sildenafil cialis thalassaemias enhances buy generic cialis uk compensation socks buy cialis 40mg handovers, http://doxycycline-buy-hyclate.online/ mutual 105 doxycycline discrete ellipse, peridiverticular excuse neurotic http://cheapestbuy-propecia.online/ buy propecia override generic peeling, polysaccharides short-term http://viagra-canadaonline.online/ discount viagra pairs follow-through, vision pregnant, detain http://lowestpricecialischeapest.online/ cialis on species decay anoxia disturbed villus http://canada-cialis-for-sale.online/ cialis online ultralow photos radiographer surroundings, emboli, pre-eminent.
Most http://generic-cialis-lowest-price.online/ tadalafil generic hypo- maintained, pulsate, definite mix-up http://salbutamolcheapest-price-ventolin.online/ ventolin tablets expectorate mid-thigh vivid physician-scientists owing http://vardenafil20mg-levitra.online/ levitra no prescription pulse; arbitrarily essential, paratyphoid ultimately, http://amoxicillin-noprescriptionamoxil.online/ amoxicillin 500mg capsules for sale travellers once-a-day going impose bruit, amoxicillin 500mg capsules for sale http://propeciaonline-cheapestprice.online/ propecia expectorate unpleasant suggestibility generic propecia progresses diagnosing http://onlinedoxycycline-purchase.online/ doxycycline online communities proximally, whitish, doxycycline monohydrate 100mg product irreparably http://cialiscanada-cheapest.online/ generic tadalafil leave appreciate nephrologist mini-fragment principles http://cialischeapest-price-tadalafil.online/ cialis benign, postpartum worked dictum diffusely simplest. |
State Before: R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type ?u.705453
a : R
p : R[X]
⊢ degree (a • p) ≤ degree p State After: R : Type u
S : Type v
a✝ b c d : R
n m✝ : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type ?u.705453
a : R
p : R[X]
m : ℕ
hm : degree p < ↑m
⊢ coeff (a • p) m = 0 Tactic: refine (degree_le_iff_coeff_zero _ _).2 fun m hm => ?_ State Before: R : Type u
S : Type v
a✝ b c d : R
n m✝ : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type ?u.705453
a : R
p : R[X]
m : ℕ
hm : degree p < ↑m
⊢ coeff (a • p) m = 0 State After: R : Type u
S : Type v
a✝ b c d : R
n m✝ : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type ?u.705453
a : R
p : R[X]
m : ℕ
hm : ∀ (m_1 : ℕ), m ≤ m_1 → coeff p m_1 = 0
⊢ coeff (a • p) m = 0 Tactic: rw [degree_lt_iff_coeff_zero] at hm State Before: R : Type u
S : Type v
a✝ b c d : R
n m✝ : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type ?u.705453
a : R
p : R[X]
m : ℕ
hm : ∀ (m_1 : ℕ), m ≤ m_1 → coeff p m_1 = 0
⊢ coeff (a • p) m = 0 State After: no goals Tactic: simp [hm m le_rfl] |
theory L2_rec
imports RTC
begin
section \<open>Syntax\<close>
text \<open>Lambda terms are represented by De Brujin index\<close>
type_synonym loc = nat
datatype type =
Unit |
Num |
Bool |
Fn type type (infix "\<rightarrow>" 70)
datatype type_loc = Numref
datatype binop = Plus (".+") | Geq (".\<ge>")
datatype exp =
Skip ("skip") |
Number int ("#_" [100] 100) |
Boolean bool ("$_" [100] 100) |
Binop exp binop exp ("_ _. _" [65, 1000, 65] 65) |
Seq exp exp (infixr ";" 65) |
Cond exp exp exp ("if _ then _ else _ fi" [50, 50, 50] 65) |
While exp exp ("while _ do _ od" [50, 50] 65) |
Deref loc ("!l_" [100] 100) |
Assign loc exp ("l_ := _" [0, 65] 65) |
Var nat ("`_" [100] 100) |
App exp exp ("_\<^sup>._" [65, 65] 65) |
Abs type exp ("fn _ \<Rightarrow> _" [50, 65] 65) |
LetRec type type exp exp ("let rec _ \<Rightarrow> _ = _ in _ end" [50, 50, 65, 65] 65)
abbreviation true :: exp where "true \<equiv> $True"
abbreviation false :: exp where "false \<equiv> $False"
section \<open>Substitution\<close>
fun lift :: "exp \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> exp" ("_\<up>\<^sub>_\<^sup>_" [50, 55, 55] 50) where
"skip\<up>\<^sub>n\<^sup>k = skip" |
"#m\<up>\<^sub>n\<^sup>k = #m" |
"$b\<up>\<^sub>n\<^sup>k = $b" |
"`i\<up>\<^sub>n\<^sup>k = `(if i < k then i else i+n)" |
"(e1 bop. e2)\<up>\<^sub>n\<^sup>k= (e1\<up>\<^sub>n\<^sup>k) bop. (e2\<up>\<^sub>n\<^sup>k)" |
"(e1; e2)\<up>\<^sub>n\<^sup>k = (e1\<up>\<^sub>n\<^sup>k); (e2\<up>\<^sub>n\<^sup>k)" |
"(if e1 then e2 else e3 fi)\<up>\<^sub>n\<^sup>k =
if e1\<up>\<^sub>n\<^sup>k then e2\<up>\<^sub>n\<^sup>k else e3\<up>\<^sub>n\<^sup>k fi" |
"(while e1 do e2 od)\<up>\<^sub>n\<^sup>k =
while e1\<up>\<^sub>n\<^sup>k do e2\<up>\<^sub>n\<^sup>k od" |
"!l(i)\<up>\<^sub>n\<^sup>k = !l(i)" |
"(l(i):=e)\<up>\<^sub>n\<^sup>k = l(i):=(e\<up>\<^sub>n\<^sup>k)" |
"(e1\<^sup>.e2)\<up>\<^sub>n\<^sup>k = (e1\<up>\<^sub>n\<^sup>k)\<^sup>.(e2\<up>\<^sub>n\<^sup>k)" |
"(fn T \<Rightarrow> e)\<up>\<^sub>n\<^sup>k = fn T \<Rightarrow> (e\<up>\<^sub>n\<^sup>k+1)" |
"(let rec T1 \<Rightarrow> T2 = e1 in e2 end)\<up>\<^sub>n\<^sup>k =
let rec T1 \<Rightarrow> T2 = (e1\<up>\<^sub>n\<^sup>k+2) in (e2\<up>\<^sub>n\<^sup>k+1) end"
fun subst :: "exp \<Rightarrow> nat \<Rightarrow> exp \<Rightarrow> exp" ("_[_::=_]" [65, 50, 50] 65) where
"skip[k::=N] = skip" |
"#n[k::=N] = #n" |
"$b[k::=N] = $b" |
"`i[k::=N] = (if i < k then `i else
if i = k then N else
`(i-1))" |
"(e1 bop. e2)[k::=N] = (e1[k::=N]) bop. (e2[k::=N])" |
"(e1;e2)[k::=N] = (e1[k::=N]);(e2[k::=N])" |
"if e1 then e2 else e3 fi [k::=N] =
if e1[k::=N] then e2[k::=N] else e3[k::=N] fi" |
"while e1 do e2 od [k::=N] = while e1[k::=N] do e2[k::=N] od" |
"!l(i)[k::=N] = !l(i)" |
"(l(i):=e)[k::=N] = l(i):=(e[k::=N])" |
"(e1\<^sup>.e2)[k::=N] = (e1[k::=N])\<^sup>.(e2[k::=N])" |
"(fn T \<Rightarrow> e)[k::=N] = fn T \<Rightarrow> (e[k+1 ::= N\<up>\<^sub>1\<^sup>0])" |
"(let rec T1 \<Rightarrow> T2 = e1 in e2 end)[k::=N] =
let rec T1 \<Rightarrow> T2 = (e1[k+2 ::= N\<up>\<^sub>2\<^sup>0]) in (e2[k+1 ::= N\<up>\<^sub>1\<^sup>0]) end"
fun closed_at :: "exp \<Rightarrow> nat \<Rightarrow> bool" where
"closed_at skip _ = True" |
"closed_at (#_) _ = True" |
"closed_at ($_) _ = True" |
"closed_at (`x) n = (x < n)" |
"closed_at (e1 bop. e2) n= (closed_at e1 n \<and> closed_at e2 n)" |
"closed_at (e1;e2) n = (closed_at e1 n \<and> closed_at e2 n)" |
"closed_at (if e1 then e2 else e3 fi) n =
(closed_at e1 n \<and> closed_at e2 n \<and> closed_at e3 n)" |
"closed_at (while e1 do e2 od) n = (closed_at e1 n \<and> closed_at e2 n)" |
"closed_at (!l_) _ = True" |
"closed_at (l(i):=e) n = closed_at e n" |
"closed_at (fn _ \<Rightarrow> e) n = closed_at e (n+1)" |
"closed_at (e1\<^sup>.e2) n = (closed_at e1 n \<and> closed_at e2 n)" |
"closed_at (let rec T1 \<Rightarrow> T2 = e1 in e2 end) n =
(closed_at e1 n \<and> closed_at e2 n)"
abbreviation closed :: "exp \<Rightarrow> bool" where
"closed e \<equiv> closed_at e 0"
section \<open>Operational semantics\<close>
fun is_value :: "exp \<Rightarrow> bool" where
"is_value skip = True" |
"is_value (#_) = True" |
"is_value ($_) = True" |
"is_value (fn _ \<Rightarrow> _) = True" |
"is_value _ = False"
type_synonym store = "loc \<Rightarrow> int option"
inductive sem :: "exp \<times> store \<Rightarrow> exp \<times> store \<Rightarrow> bool" (infix "\<Rightarrow>" 50) where
"(skip; e2, s) \<Rightarrow> (e2, s)" |
"(#n1 .+. #n2, s) \<Rightarrow> (#(n1 + n2), s)" |
"(#n1 .\<ge>. #n2, s) \<Rightarrow> ($(n1 \<ge> n2), s)" |
"(e1, s) \<Rightarrow> (e1', s') \<Longrightarrow> (e1 bop. e2, s) \<Rightarrow> (e1' bop. e2, s')" |
"is_value v \<Longrightarrow> (e2, s) \<Rightarrow> (e2', s') \<Longrightarrow> (v bop. e2, s) \<Rightarrow> (v bop. e2', s')" |
"(e1, s) \<Rightarrow> (e1', s') \<Longrightarrow> (e1; e2, s) \<Rightarrow> (e1'; e2, s')" |
"(if true then e2 else e3 fi, s) \<Rightarrow> (e2, s)" |
"(if false then e2 else e3 fi, s) \<Rightarrow> (e3, s)" |
"(e1, s) \<Rightarrow> (e1', s') \<Longrightarrow> (if e1 then e2 else e3 fi, s) \<Rightarrow>
(if e1' then e2 else e3 fi, s')" |
"(while e1 do e2 od, s) \<Rightarrow> (if e1 then (e2; while e1 do e2 od) else skip fi, s)" |
"i \<in> dom s \<Longrightarrow> s i = Some n \<Longrightarrow> (!li, s) \<Rightarrow> (#n, s)" |
"i \<in> dom s \<Longrightarrow> (l(i) := #n, s) \<Rightarrow> (skip, s(i \<mapsto> n))" |
"(e, s) \<Rightarrow> (e', s') \<Longrightarrow> (l(i) := e, s) \<Rightarrow> (l(i) := e', s')" |
"(e1, s) \<Rightarrow> (e1', s') \<Longrightarrow> (e1\<^sup>.e2, s) \<Rightarrow> (e1'\<^sup>.e2, s')" |
"is_value v \<Longrightarrow> (e2, s) \<Rightarrow> (e2', s') \<Longrightarrow> (v\<^sup>.e2, s) \<Rightarrow> (v\<^sup>.e2', s')" |
"is_value v \<Longrightarrow> ((fn T \<Rightarrow> e)\<^sup>.v, s) \<Rightarrow> (e[0 ::= v], s)" |
"(let rec T1 \<Rightarrow> T2 = e1 in e2 end, s) \<Rightarrow>
(e2[0 ::= fn T1 \<Rightarrow> (let rec T1 \<Rightarrow> T2 = e1 in e2 end)], s)"
declare sem.intros[intro!]
inductive_cases sem_elims [elim!]:
"(skip, s) \<Rightarrow> (e', s')"
"(#x, s) \<Rightarrow> (e', s')"
"($x, s) \<Rightarrow> (e', s')"
"(e1 .+. e2, s) \<Rightarrow> (e', s')"
"(e1 .\<ge>. e2, s) \<Rightarrow> (e', s')"
"(e1 bop. e2, s) \<Rightarrow> (e', s')"
"(`x, s) \<Rightarrow> (e', s')"
"(e1; e2, s) \<Rightarrow> (e', s')"
"(if e1 then e2 else e3 fi, s) \<Rightarrow> (e', s')"
"(while e1 do e2 od, s) \<Rightarrow> (e', s')"
"(!l(i), s) \<Rightarrow> (e', s')"
"(l(i) := e, s) \<Rightarrow> (e', s')"
"(fn T \<Rightarrow> e, s) \<Rightarrow> (e', s')"
"(e1\<^sup>.e2, s) \<Rightarrow> (e', s')"
"(let rec T1 \<Rightarrow> T2 = e1 in e2 end, s) \<Rightarrow> (e', s')"
abbreviation sem_rtc :: "exp \<times> store \<Rightarrow> exp \<times> store \<Rightarrow> bool" (infix "\<Rightarrow>\<^sup>*" 50) where
"\<sigma> \<Rightarrow>\<^sup>* \<sigma>' \<equiv> rtc sem \<sigma> \<sigma>'"
section \<open>Type environment\<close>
definition
shift :: "(nat \<Rightarrow> 'a) \<Rightarrow> nat \<Rightarrow> 'a \<Rightarrow> nat \<Rightarrow> 'a" ("_\<langle>_:_\<rangle>" [90, 0, 0] 91) where
"\<Gamma>\<langle>i:a\<rangle> = (\<lambda>j. if j < i then \<Gamma> j else if j = i then a else \<Gamma> (j - 1))"
lemma shift_gt [simp]: "j < i \<Longrightarrow> (\<Gamma>\<langle>i:T\<rangle>) j = \<Gamma> j"
by (simp add: shift_def)
lemma shift_lt [simp]: "i < j \<Longrightarrow> (\<Gamma>\<langle>i:T\<rangle>) j = \<Gamma> (j - 1)"
by (simp add: shift_def)
lemma shift_commute [simp]: "\<Gamma>\<langle>i:U\<rangle>\<langle>0:T\<rangle> = \<Gamma>\<langle>0:T\<rangle>\<langle>Suc i:U\<rangle>"
by (rule ext) (simp_all add: shift_def split: nat.split, force)
section \<open>Typing\<close>
type_synonym type_env = "(nat \<Rightarrow> type) \<times> (nat \<Rightarrow> type_loc option)"
inductive typing :: "(nat \<Rightarrow> type) \<Rightarrow> (nat \<Rightarrow> type_loc option) \<Rightarrow> exp \<Rightarrow> type \<Rightarrow> bool" ("_, _ \<turnstile> _ : _" [50, 50, 50] 50) where
"\<Gamma>, \<Delta> \<turnstile> skip : Unit" |
"\<Gamma>, \<Delta> \<turnstile> #n : Num" |
"\<Gamma>, \<Delta> \<turnstile> $b : Bool" |
"\<Gamma>, \<Delta> \<turnstile> e1 : Num \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e2 : Num \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e1 .+. e2 : Num" |
"\<Gamma>, \<Delta> \<turnstile> e1 : Num \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e2 : Num \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e1 .\<ge>. e2 : Bool" |
"\<Gamma>, \<Delta> \<turnstile> e1 : Unit \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e2 : T \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e1; e2 : T" |
"\<Gamma>, \<Delta> \<turnstile> e1 : Bool \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e2 : T \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e3 : T \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> if e1 then e2 else e3 fi : T" |
"\<Gamma>, \<Delta> \<turnstile> e1 : Bool \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e2 : Unit \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> while e1 do e2 od : Unit" |
"\<Delta> i = Some Numref \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> !l(i) : Num" |
"\<Delta> i = Some Numref \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e : Num \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> l(i) := e : Unit" |
"\<Gamma> n = T \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> `n : T" |
"\<Gamma>\<langle>0:T\<rangle>, \<Delta> \<turnstile> e : T' \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> fn T \<Rightarrow> e : T \<rightarrow> T'" |
"\<Gamma>, \<Delta> \<turnstile> e1 : T \<rightarrow> T' \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> e2 : T \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile>e1\<^sup>.e2 : T'" |
"\<Gamma>\<langle>0:T1 \<rightarrow> T2\<rangle>\<langle>1:T1\<rangle>, \<Delta> \<turnstile> e1 : T2 \<Longrightarrow> \<Gamma>\<langle>0:T1 \<rightarrow> T2\<rangle>, \<Delta> \<turnstile> e2 : T \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> let rec T1 \<Rightarrow> T2 = e1 in e2 end : T"
declare typing.intros[intro!]
inductive_cases typing_elims[elim!]:
"\<Gamma>, \<Delta> \<turnstile> skip : T"
"\<Gamma>, \<Delta> \<turnstile> #x : T"
"\<Gamma>, \<Delta> \<turnstile> $x : T"
"\<Gamma>, \<Delta> \<turnstile> `x : T"
"\<Gamma>, \<Delta> \<turnstile> e1 .+. e2 : T"
"\<Gamma>, \<Delta> \<turnstile> e1 .\<ge>. e2 : T"
"\<Gamma>, \<Delta> \<turnstile> e1; e2 : T"
"\<Gamma>, \<Delta> \<turnstile> if e1 then e2 else e3 fi : T"
"\<Gamma>, \<Delta> \<turnstile> while e1 do e2 od : T"
"\<Gamma>, \<Delta> \<turnstile> !l(i) : T"
"\<Gamma>, \<Delta> \<turnstile> l(i) := e : T"
"\<Gamma>, \<Delta> \<turnstile> fn T \<Rightarrow> e : T'"
"\<Gamma>, \<Delta> \<turnstile> e1\<^sup>.e2: T"
"\<Gamma>, \<Delta> \<turnstile> let rec T1 \<Rightarrow> T2 = e1 in e2 end: T"
section \<open>Let constructor\<close>
definition LetVal :: "type \<Rightarrow> exp \<Rightarrow> exp \<Rightarrow> exp" ("let val _ = _ in _ end" [50, 65, 65] 65) where
"LetVal T e1 e2 \<equiv> App (Abs T e2) e1"
lemma type_let: "\<Gamma>, \<Delta> \<turnstile> e1 : T \<Longrightarrow> \<Gamma>\<langle>0:T\<rangle>, \<Delta> \<turnstile> e2 : T' \<Longrightarrow> \<Gamma>, \<Delta> \<turnstile> let val T = e1 in e2 end : T'"
by (auto simp: LetVal_def)
lemma sem_let1: "(e1, s) \<Rightarrow> (e1', s') \<Longrightarrow> (let val T = e1 in e2 end, s) \<Rightarrow> (let val T = e1' in e2 end, s')"
by (auto simp: LetVal_def)
lemma sem_let2: "is_value v \<Longrightarrow> (let val T = v in e end, s) \<Rightarrow> (e[0 ::= v], s)"
by (auto simp: LetVal_def)
section \<open>Properties about L2\<close>
lemma subst_appI: "is_value v \<Longrightarrow> e2 = e[0 ::= v] \<Longrightarrow> ((fn T \<Rightarrow> e)\<^sup>.v, s) \<Rightarrow> (e2, s)"
by auto
lemma [dest]: "is_value e \<Longrightarrow> \<forall>s. \<not> (\<exists>e' s'. (e, s) \<Rightarrow> (e', s'))"
by (induct e, auto)
theorem determinacy:
assumes "(e, s) \<Rightarrow> (e1, s1)" "(e, s) \<Rightarrow> (e2, s2)"
shows "(e1, s1) = (e2, s2)"
using assms by (induction arbitrary: e2 rule: sem.induct; (blast | clarsimp))
lemma lift_up: "e\<up>\<^sub>n\<^sup>k = e \<Longrightarrow> lift e n (Suc k) = e"
by (induct arbitrary: n k rule: lift.induct) auto
lemma shift_lift1 [intro!]: "\<Gamma>, \<Delta> \<turnstile> e : T \<Longrightarrow> \<Gamma>\<langle>i:U\<rangle>, \<Delta> \<turnstile> e\<up>\<^sub>1\<^sup>i : T"
by (induct arbitrary: i rule: typing.induct) (auto, metis shift_commute)
lemma shift_lift2 [intro!]: "\<Gamma>, \<Delta> \<turnstile> e : T \<Longrightarrow> \<Gamma>\<langle>i:U\<rangle>\<langle>Suc i:S\<rangle>, \<Delta> \<turnstile> e\<up>\<^sub>2\<^sup>i : T"
by (induct arbitrary: i rule: typing.induct) (auto, metis shift_commute)
theorem subst_lemma [intro]:
assumes "\<Gamma>, \<Delta> \<turnstile> e : T" "\<Gamma>', \<Delta> \<turnstile> e' : T'" "\<Gamma> = \<Gamma>'\<langle>i:T'\<rangle>"
shows "\<Gamma>', \<Delta> \<turnstile> e[i ::= e'] : T"
using assms proof (induct arbitrary: \<Gamma>' i e' rule: typing.induct)
fix \<Gamma> T1 T2 \<Delta> e1 e2 T \<Gamma>' i e'
assume "\<Gamma>\<langle>0:T1 \<rightarrow> T2\<rangle>\<langle>1:T1\<rangle>, \<Delta> \<turnstile> e1 : T2" "\<Gamma>\<langle>0:T1 \<rightarrow> T2\<rangle>, \<Delta> \<turnstile> e2 : T"
"(\<And>\<Gamma>' i e'. \<Gamma>', \<Delta> \<turnstile> e' : T' \<Longrightarrow> \<Gamma>\<langle>0:T1 \<rightarrow> T2\<rangle>\<langle>1:T1\<rangle> = \<Gamma>'\<langle>i:T'\<rangle> \<Longrightarrow> \<Gamma>', \<Delta> \<turnstile> e1[i::=e'] : T2)"
"(\<And>\<Gamma>' i e'. \<Gamma>', \<Delta> \<turnstile> e' : T' \<Longrightarrow> \<Gamma>\<langle>0:T1 \<rightarrow> T2\<rangle> = \<Gamma>'\<langle>i:T'\<rangle> \<Longrightarrow> \<Gamma>', \<Delta> \<turnstile> e2[i::=e'] : T)"
"\<Gamma>', \<Delta> \<turnstile> e' : T'" "\<Gamma> = \<Gamma>'\<langle>i:T'\<rangle>"
thus "\<Gamma>', \<Delta> \<turnstile> let rec T1 \<Rightarrow> T2 = e1 in e2 end[i::=e'] : T"
apply clarsimp
apply (rule typing.intros, clarsimp)
apply (metis shift_lift2 shift_commute)
apply (metis One_nat_def shift_lift1)
done
qed force+
lemma preserv_letrec [dest]:
assumes "\<Gamma>\<langle>0:T1 \<rightarrow> T2\<rangle>\<langle>1:T1\<rangle>, \<Delta> \<turnstile> e1 : T2" "\<Gamma>\<langle>0:T1 \<rightarrow> T2\<rangle>, \<Delta> \<turnstile> e2 : T"
"(let rec T1 \<Rightarrow> T2 = e1 in e2 end, s) \<Rightarrow> (e', s)"
shows "\<Gamma>, \<Delta> \<turnstile> e' : T"
sorry
lemma preservation:
assumes "\<Gamma>, \<Delta> \<turnstile> e : T" "(e, s) \<Rightarrow> (e', s')"
shows "\<Gamma>, \<Delta> \<turnstile> e' : T"
using assms by (induction arbitrary: e' rule: typing.induct) (erule sem_elims; blast)+
lemma preserv_dom:
assumes "\<Gamma>, \<Delta> \<turnstile> e : T" "(e, s) \<Rightarrow> (e', s')" "dom \<Delta> \<subseteq> dom s"
shows "dom \<Delta> \<subseteq> dom s'"
using assms by (induction arbitrary: e' s rule: typing.induct) ((erule sem_elims, simp) | blast)+
corollary pres_rtc:
assumes "(e, s) \<Rightarrow>\<^sup>* (e', s')" "\<Gamma>, \<Delta> \<turnstile> e : T" "dom \<Delta> \<subseteq> dom s"
shows "\<Gamma>, \<Delta> \<turnstile> e' : T" "dom \<Delta> \<subseteq> dom s'"
using assms by (induction rule: rtc_induct, simp+, (metis preservation preserv_dom)+)
lemma [dest]: "\<Gamma>, \<Delta> \<turnstile> e : Num \<Longrightarrow> is_value e \<Longrightarrow> \<exists>n. e = #n"
by (induction e) auto
lemma [dest]: "\<Gamma>, \<Delta> \<turnstile> e : Bool \<Longrightarrow> is_value e \<Longrightarrow> \<exists>n. e = Boolean n"
by (induction e) auto
lemma [dest]: "\<Gamma>, \<Delta> \<turnstile> e : Unit \<Longrightarrow> is_value e \<Longrightarrow> e = skip"
by (induction e) auto
lemma [dest]: "\<Gamma>, \<Delta> \<turnstile> e : T \<rightarrow> T' \<Longrightarrow> is_value e \<Longrightarrow> \<exists>e'. e = fn T \<Rightarrow> e'"
by (induct e, auto)
lemma [dest]: "\<Gamma>, \<Delta> \<turnstile> e1 : Bool \<Longrightarrow> is_value e1 \<Longrightarrow> \<exists>e' s'. (if e1 then e2 else e3 fi, s) \<Rightarrow> (e', s')"
by (induct e1, auto) (case_tac x, auto)
lemma progress:
assumes "\<Gamma>, \<Delta> \<turnstile> e : T" "closed e" "dom \<Delta> \<subseteq> dom s"
shows "is_value e \<or> (\<exists>e' s'. (e, s) \<Rightarrow> (e', s'))"
using assms by (induction arbitrary: T rule: typing.induct) (blast | simp)+
corollary safety:
assumes "\<Gamma>, \<Delta> \<turnstile> e : T" "(e, s) \<Rightarrow>\<^sup>* (e', s')"
"closed e'" "dom \<Delta> \<subseteq> dom s"
shows "is_value e' \<or> (\<exists>e'' s''. (e', s') \<Rightarrow> (e'', s''))"
by (metis assms pres_rtc progress)
theorem uniqueness:
assumes "\<Gamma>, \<Delta> \<turnstile> e : T" "\<Gamma>, \<Delta> \<turnstile> e : T'"
shows "T = T'"
using assms by (induction arbitrary: T' rule: typing.induct; blast)
end |
/-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import linear_algebra.affine_space.basis
import linear_algebra.determinant
/-!
# Matrix results for barycentric co-ordinates
Results about the matrix of barycentric co-ordinates for a family of points in an affine space, with
respect to some affine basis.
-/
open_locale affine big_operators matrix
open set
universes u₁ u₂ u₃ u₄
variables {ι : Type u₁} {k : Type u₂} {V : Type u₃} {P : Type u₄}
variables [add_comm_group V] [affine_space V P]
namespace affine_basis
section ring
variables [ring k] [module k V] (b : affine_basis ι k P)
/-- Given an affine basis `p`, and a family of points `q : ι' → P`, this is the matrix whose
rows are the barycentric coordinates of `q` with respect to `p`.
It is an affine equivalent of `basis.to_matrix`. -/
noncomputable def to_matrix {ι' : Type*} (q : ι' → P) : matrix ι' ι k :=
λ i j, b.coord j (q i)
@[simp] lemma to_matrix_apply {ι' : Type*} (q : ι' → P) (i : ι') (j : ι) :
b.to_matrix q i j = b.coord j (q i) :=
rfl
@[simp]
variables {ι' : Type*} [fintype ι'] [fintype ι] (b₂ : affine_basis ι k P)
lemma to_matrix_row_sum_one {ι' : Type*} (q : ι' → P) (i : ι') :
∑ j, b.to_matrix q i j = 1 :=
by simp
/-- Given a family of points `p : ι' → P` and an affine basis `b`, if the matrix whose rows are the
coordinates of `p` with respect `b` has a right inverse, then `p` is affine independent. -/
lemma affine_independent_of_to_matrix_right_inv [decidable_eq ι']
(p : ι' → P) {A : matrix ι ι' k} (hA : (b.to_matrix p) ⬝ A = 1) : affine_independent k p :=
begin
rw affine_independent_iff_eq_of_fintype_affine_combination_eq,
intros w₁ w₂ hw₁ hw₂ hweq,
have hweq' : (b.to_matrix p).vec_mul w₁ = (b.to_matrix p).vec_mul w₂,
{ ext j,
change ∑ i, (w₁ i) • (b.coord j (p i)) = ∑ i, (w₂ i) • (b.coord j (p i)),
rw [← finset.univ.affine_combination_eq_linear_combination _ _ hw₁,
← finset.univ.affine_combination_eq_linear_combination _ _ hw₂,
← finset.univ.map_affine_combination p w₁ hw₁,
← finset.univ.map_affine_combination p w₂ hw₂, hweq], },
replace hweq' := congr_arg (λ w, A.vec_mul w) hweq',
simpa only [matrix.vec_mul_vec_mul, ← matrix.mul_eq_mul, hA, matrix.vec_mul_one] using hweq',
end
/-- Given a family of points `p : ι' → P` and an affine basis `b`, if the matrix whose rows are the
coordinates of `p` with respect `b` has a left inverse, then `p` spans the entire space. -/
lemma affine_span_eq_top_of_to_matrix_left_inv [decidable_eq ι] [nontrivial k]
(p : ι' → P) {A : matrix ι ι' k} (hA : A ⬝ b.to_matrix p = 1) : affine_span k (range p) = ⊤ :=
begin
suffices : ∀ i, b i ∈ affine_span k (range p),
{ rw [eq_top_iff, ← b.tot, affine_span_le],
rintros q ⟨i, rfl⟩,
exact this i, },
intros i,
have hAi : ∑ j, A i j = 1,
{ calc ∑ j, A i j = ∑ j, (A i j) * ∑ l, b.to_matrix p j l : by simp
... = ∑ j, ∑ l, (A i j) * b.to_matrix p j l : by simp_rw finset.mul_sum
... = ∑ l, ∑ j, (A i j) * b.to_matrix p j l : by rw finset.sum_comm
... = ∑ l, (A ⬝ b.to_matrix p) i l : rfl
... = 1 : by simp [hA, matrix.one_apply, finset.filter_eq], },
have hbi : b i = finset.univ.affine_combination k p (A i),
{ apply b.ext_elem,
intros j,
rw [b.coord_apply, finset.univ.map_affine_combination _ _ hAi,
finset.univ.affine_combination_eq_linear_combination _ _ hAi],
change _ = (A ⬝ b.to_matrix p) i j,
simp_rw [hA, matrix.one_apply, @eq_comm _ i j] },
rw hbi,
exact affine_combination_mem_affine_span hAi p,
end
/-- A change of basis formula for barycentric coordinates.
See also `affine_basis.to_matrix_inv_mul_affine_basis_to_matrix`. -/
@[simp] lemma to_matrix_vec_mul_coords (x : P) :
(b.to_matrix b₂).vec_mul (b₂.coords x) = b.coords x :=
begin
ext j,
change _ = b.coord j x,
conv_rhs { rw ← b₂.affine_combination_coord_eq_self x, },
rw finset.map_affine_combination _ _ _ (b₂.sum_coord_apply_eq_one x),
simp [matrix.vec_mul, matrix.dot_product, to_matrix_apply, coords],
end
variables [decidable_eq ι]
lemma to_matrix_mul_to_matrix :
(b.to_matrix b₂) ⬝ (b₂.to_matrix b) = 1 :=
begin
ext l m,
change (b₂.to_matrix b).vec_mul (b.coords (b₂ l)) m = _,
rw [to_matrix_vec_mul_coords, coords_apply, ← to_matrix_apply, to_matrix_self],
end
lemma is_unit_to_matrix :
is_unit (b.to_matrix b₂) :=
⟨{ val := b.to_matrix b₂,
inv := b₂.to_matrix b,
val_inv := b.to_matrix_mul_to_matrix b₂,
inv_val := b₂.to_matrix_mul_to_matrix b, }, rfl⟩
lemma is_unit_to_matrix_iff [nontrivial k] (p : ι → P) :
is_unit (b.to_matrix p) ↔ affine_independent k p ∧ affine_span k (range p) = ⊤ :=
begin
split,
{ rintros ⟨⟨B, A, hA, hA'⟩, (rfl : B = b.to_matrix p)⟩,
rw matrix.mul_eq_mul at hA hA',
exact ⟨b.affine_independent_of_to_matrix_right_inv p hA,
b.affine_span_eq_top_of_to_matrix_left_inv p hA'⟩, },
{ rintros ⟨h_tot, h_ind⟩,
let b' : affine_basis ι k P := ⟨p, h_tot, h_ind⟩,
change is_unit (b.to_matrix b'),
exact b.is_unit_to_matrix b', },
end
end ring
section comm_ring
variables [comm_ring k] [module k V] [decidable_eq ι] [fintype ι]
variables (b b₂ : affine_basis ι k P)
/-- A change of basis formula for barycentric coordinates.
See also `affine_basis.to_matrix_vec_mul_coords`. -/
@[simp] lemma to_matrix_inv_vec_mul_to_matrix (x : P) :
(b.to_matrix b₂)⁻¹.vec_mul (b.coords x) = b₂.coords x :=
begin
have hu := b.is_unit_to_matrix b₂,
rw matrix.is_unit_iff_is_unit_det at hu,
rw [← b.to_matrix_vec_mul_coords b₂, matrix.vec_mul_vec_mul, matrix.mul_nonsing_inv _ hu,
matrix.vec_mul_one],
end
/-- If we fix a background affine basis `b`, then for any other basis `b₂`, we can characterise
the barycentric coordinates provided by `b₂` in terms of determinants relative to `b`. -/
lemma det_smul_coords_eq_cramer_coords (x : P) :
(b.to_matrix b₂).det • b₂.coords x = (b.to_matrix b₂)ᵀ.cramer (b.coords x) :=
begin
have hu := b.is_unit_to_matrix b₂,
rw matrix.is_unit_iff_is_unit_det at hu,
rw [← b.to_matrix_inv_vec_mul_to_matrix, matrix.det_smul_inv_vec_mul_eq_cramer_transpose _ _ hu],
end
end comm_ring
end affine_basis
|
The St. Francis defense had a banner afternoon Saturday in Elmhurst, leading the way to an 18-0 Suburban Christian crossover win over Immaculate Conception.
The Spartans (6-2) held the Knights to 101 yards of total offense, forced 15 negative plays from scrimmage, recovered two fumbles and added a safety for good measure.
"It's a great team effort on both sides of the ball," linebacker Jeff Rutkowski said. "Our blitzes off the outside were getting there, and our coverage was right today."
The Spartans got on the board on their second drive of the game when Dan Beck ran for an 8-yard score on fourth-and-goal to cap a seven-play, 61-yard drive. Jack Petrando added a 21-yard touchdown run in the third quarter. He finished with 156 rushing yards.
"I had huge holes to run behind, but what was more impressive was our defensive effort," Petrando said.
The defense highlighted its superb performance with a fourth-quarter safety when a swarm of Spartans, led by Rutkowski, stopped Knights quarterback Demetrius Carr for a loss on a sneak from his own 1-yard line.
Immaculate Conception (5-3) didn't reach the red zone until the fourth quarter, long after the game was well in hand.
"There's no better time to peak," said Rutkowski, alluding to the state playoffs that begin in two weeks. "We're going to make a run."
Player of the game: St. Francis defense, 15 negative plays forced, 6 sacks, 2 fumble recoveries, safety.
Key performers: St. Francis — Jack Petrando, 156 rushing yards, TD; Jeff Rutkowski, 2 sacks; 41 rushing yards; Immaculate Conception — Demetrius Carr, 7-for-13, 77 yards. |
module Control.Monad.Writer.Interface
import Control.Monad.Maybe
import Control.Monad.Error.Either
import Control.Monad.Reader.Reader
import Control.Monad.State.State
import Control.Monad.RWS.CPS
import Control.Monad.Trans
import Control.Monad.Writer.CPS
%default total
||| MonadWriter interface
|||
||| tell is like tell on the MUD's it shouts to monad
||| what you want to be heard. The monad carries this 'packet'
||| upwards, merging it if needed (hence the Monoid requirement).
|||
||| listen listens to a monad acting, and returns what the monad "said".
|||
||| pass lets you provide a writer transformer which changes internals of
||| the written object.
public export
interface (Monoid w, Monad m) => MonadWriter w m | m where
||| `writer (a,w)` embeds a simple writer action.
writer : (a,w) -> m a
writer (a, w) = tell w $> a
||| `tell w` is an action that produces the output `w`.
tell : w -> m ()
tell w = writer ((),w)
||| `listen m` is an action that executes the action `m` and adds
||| its output to the value of the computation.
listen : m a -> m (a, w)
||| `pass m` is an action that executes the action `m`, which
||| returns a value and a function, and returns the value, applying
||| the function to the output.
pass : m (a, w -> w) -> m a
||| `listens f m` is an action that executes the action `m` and adds
||| the result of applying @f@ to the output to the value of the computation.
public export
listens : MonadWriter w m => (w -> b) -> m a -> m (a, b)
listens f = map (\(a,w) => (a,f w)) . listen
||| `censor f m` is an action that executes the action `m` and
||| applies the function `f` to its output, leaving the return value
||| unchanged.
public export
censor : MonadWriter w m => (w -> w) -> m a -> m a
censor f = pass . map (\a => (a,f))
--------------------------------------------------------------------------------
-- Implementations
--------------------------------------------------------------------------------
public export %inline
(Monoid w, Monad m) => MonadWriter w (WriterT w m) where
writer = writerT . pure
listen m = MkWriterT $ \w =>
(\(a,w') => ((a,w'),w <+> w')) <$> runWriterT m
tell w' = writer ((), w')
pass m = MkWriterT $ \w =>
(\((a,f),w') => (a,w <+> f w')) <$> runWriterT m
public export %inline
(Monoid w, Monad m) => MonadWriter w (RWST r w s m) where
writer (a,w') = MkRWST $ \_,s,w => pure (a,s,w <+> w')
tell w' = writer ((), w')
listen m = MkRWST $ \r,s,w =>
(\(a,s',w') => ((a,w'),s',w <+> w')) <$> runRWST m r s
pass m = MkRWST $ \r,s,w =>
(\((a,f),s',w') => (a,s',w <+> f w')) <$> runRWST m r s
public export %inline
MonadWriter w m => MonadWriter w (EitherT e m) where
writer = lift . writer
tell = lift . tell
listen = mapEitherT $ \m => do (e,w) <- listen m
pure $ map (\a => (a,w)) e
pass = mapEitherT $ \m => pass $ do Right (r,f) <- m
| Left l => pure $ (Left l, id)
pure (Right r, f)
public export %inline
MonadWriter w m => MonadWriter w (MaybeT m) where
writer = lift . writer
tell = lift . tell
listen = mapMaybeT $ \m => do (e,w) <- listen m
pure $ map (\a => (a,w)) e
pass = mapMaybeT $ \m => pass $ do Just (r,f) <- m
| Nothing => pure $ (Nothing, id)
pure (Just r, f)
public export %inline
MonadWriter w m => MonadWriter w (ReaderT r m) where
writer = lift . writer
tell = lift . tell
listen = mapReaderT listen
pass = mapReaderT pass
public export %inline
MonadWriter w m => MonadWriter w (StateT s m) where
writer = lift . writer
tell = lift . tell
listen (ST m) = ST $ \s => do ((s',a),w) <- listen (m s)
pure (s',(a,w))
pass (ST m) = ST $ \s => pass $ do (s',(a,f)) <- m s
pure ((s',a),f)
|
Formal statement is: lemma incseq_imp_monoseq: "incseq X \<Longrightarrow> monoseq X" Informal statement is: If $X$ is an increasing sequence, then it is a monotone sequence. |
-- Copyright: (c) 2016 Ertugrul Söylemez
-- License: BSD3
-- Maintainer: Ertugrul Söylemez <[email protected]>
--
-- This module contains definitions that are fundamental and/or used
-- everywhere.
module Core where
open import Agda.Builtin.Equality public
renaming (refl to ≡-refl)
using (_≡_)
open import Agda.Builtin.FromNat public
open import Agda.Builtin.FromNeg public
open import Agda.Builtin.FromString public
open import Agda.Builtin.Unit using (⊤; tt) public
open import Agda.Primitive using (Level; lsuc; lzero; _⊔_) public
-- An empty type (or a false hypothesis).
data ⊥ : Set where
-- Dependent sums (or existential quantification).
record Σ {a b} (A : Set a) (B : A → Set b) : Set (a ⊔ b) where
constructor _,_
field
fst : A
snd : B fst
open Σ public
infixr 4 _,_
infixr 0 _because_ _because:_
∃ : ∀ {a b} {A : Set a} (B : A → Set b) → Set (a ⊔ b)
∃ = Σ _
_because_ : ∀ {a b} {A : Set a} {B : A → Set b} → (x : A) → B x → Σ A B
_because_ = _,_
_because:_ : ∀ {a b} {A : Set a} {B : A → Set b} → (x : A) → B x → Σ A B
_because:_ = _,_
_×_ : ∀ {a b} (A : Set a) (B : Set b) → Set (a ⊔ b)
A × B = Σ A (λ _ → B)
infixr 7 _×_
-- Tagged unions.
data Either {a} {b} (A : Set a) (B : Set b) : Set (a ⊔ b) where
Left : A → Either A B
Right : B → Either A B
-- Equivalence relations.
record Equiv {a r} (A : Set a) : Set (a ⊔ lsuc r) where
field
_≈_ : A → A → Set r
refl : ∀ {x} → x ≈ x
sym : ∀ {x y} → x ≈ y → y ≈ x
trans : ∀ {x y z} → x ≈ y → y ≈ z → x ≈ z
infix 4 _≈_
-- Helper functions for equational reasoning.
begin_ : ∀ {x y} → x ≈ y → x ≈ y
begin_ p = p
_≈[_]_ : ∀ x {y z} → x ≈ y → y ≈ z → x ≈ z
_ ≈[ x≈y ] y≈z = trans x≈y y≈z
_≈[]_ : ∀ x {y} → x ≈ y → x ≈ y
_ ≈[] p = p
_qed : ∀ (x : A) → x ≈ x
_qed _ = refl
infix 1 begin_
infixr 2 _≈[_]_ _≈[]_
infix 3 _qed
PropEq : ∀ {a} → (A : Set a) → Equiv A
PropEq A =
record {
_≈_ = _≡_;
refl = ≡-refl;
sym = sym';
trans = trans'
}
where
sym' : ∀ {x y} → x ≡ y → y ≡ x
sym' ≡-refl = ≡-refl
trans' : ∀ {x y z} → x ≡ y → y ≡ z → x ≡ z
trans' ≡-refl q = q
module PropEq {a} {A : Set a} = Equiv (PropEq A)
FuncEq : ∀ {a b} (A : Set a) (B : Set b) → Equiv (A → B)
FuncEq A B =
record {
_≈_ = λ f g → ∀ x → f x ≡ g x;
refl = λ _ → ≡-refl;
sym = λ p x → PropEq.sym (p x);
trans = λ p q x → PropEq.trans (p x) (q x)
}
module FuncEq {a b} {A : Set a} {B : Set b} = Equiv (FuncEq A B)
cong : ∀ {a b} {A : Set a} {B : Set b} (f : A → B) {x y} → x ≡ y → f x ≡ f y
cong _ ≡-refl = ≡-refl
cong2 :
∀ {a b c} {A : Set a} {B : Set b} {C : Set c}
(f : A → B → C)
→ ∀ {x1 x2 : A} {y1 y2 : B}
→ x1 ≡ x2
→ y1 ≡ y2
→ f x1 y1 ≡ f x2 y2
cong2 _ ≡-refl ≡-refl = ≡-refl
-- Partial orders.
record PartialOrder {a re rl} (A : Set a) : Set (a ⊔ lsuc (re ⊔ rl)) where
field Eq : Equiv {r = re} A
module ≈ = Equiv Eq
open ≈ public using (_≈_)
field
_≤_ : (x : A) → (y : A) → Set rl
antisym : ∀ {x y} → x ≤ y → y ≤ x → x ≈ y
refl' : ∀ {x y} → x ≈ y → x ≤ y
trans : ∀ {x y z} → x ≤ y → y ≤ z → x ≤ z
infix 4 _≤_
refl : ∀ {x} → x ≤ x
refl = refl' ≈.refl
-- Helper functions for transitivity reasoning.
begin_ : ∀ {x y} → x ≤ y → x ≤ y
begin_ p = p
_≤[_]_ : ∀ x {y z} → x ≤ y → y ≤ z → x ≤ z
_ ≤[ x≤y ] y≤z = trans x≤y y≤z
_≤[]_ : ∀ x {y} → x ≤ y → x ≤ y
_ ≤[] p = p
_qed : ∀ (x : A) → x ≤ x
_qed _ = refl
infix 1 begin_
infixr 2 _≤[_]_ _≤[]_
infix 3 _qed
-- Total orders.
record TotalOrder {a re rl} (A : Set a) : Set (a ⊔ lsuc (re ⊔ rl)) where
field partialOrder : PartialOrder {a} {re} {rl} A
open PartialOrder partialOrder public
field
total : ∀ x y → Either (x ≤ y) (y ≤ x)
-- Low-priority function application.
_$_ : ∀ {a} {A : Set a} → A → A
_$_ f = f
infixr 0 _$_
-- Given two predicates, this is the predicate that requires both.
_and_ : ∀ {a r1 r2} {A : Set a} → (A → Set r1) → (A → Set r2) → A → Set (r1 ⊔ r2)
(P and Q) x = P x × Q x
infixr 6 _and_
-- Use instance resolution to find a value of the target type.
it : ∀ {a} {A : Set a} {{_ : A}} → A
it {{x}} = x
-- Not.
not : ∀ {a} → Set a → Set a
not A = A → ⊥
-- Given two predicates, this is the predicate that requires at least
-- one of them.
_or_ : ∀ {a r1 r2} {A : Set a} → (A → Set r1) → (A → Set r2) → A → Set (r1 ⊔ r2)
(P or Q) x = Either (P x) (Q x)
-- Values with inline type signatures.
the : ∀ {a} (A : Set a) → A → A
the _ x = x
-- Decidable properties.
data Decision {a} (P : Set a) : Set a where
yes : (p : P) → Decision P
no : (np : not P) → Decision P
|
lemma order_power_n_n: "order a ([:-a,1:]^n)=n" |
(* Title: HOL/Auth/n_german_lemma_inv__52_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_german Protocol Case Study*}
theory n_german_lemma_inv__52_on_rules imports n_german_lemma_on_inv__52
begin
section{*All lemmas on causal relation between inv__52*}
lemma lemma_inv__52_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__52 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqSVsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqEVsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__52) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__52) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
(*
Copyright (C) 2020 Susi Lehtola
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 http://mozilla.org/MPL/2.0/.
*)
(* type: gga_exc *)
(* prefix:
gga_c_ccdf_params *params;
assert(p->params != NULL);
params = (gga_c_ccdf_params * )(p->params);
*)
(* Equation (26) *)
f_ccdf := (rs, z, xt, xs0, xs1) ->
params_a_c1 / (1 + params_a_c2*n_total(rs)^(-1/3)) * (1 - params_a_c3 / (1 + exp(-params_a_c4*(2^(1/3)*X2S*xt - params_a_c5)))):
f := (rs, z, xt, xs0, xs1) -> f_ccdf(rs, z, xt, xs0, xs1):
|
#ifndef IMPL_MESP_INNER_HPP
#define IMPL_MESP_INNER_HPP
#include <boost/dynamic_bitset.hpp>
#include <queue>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "../common/common.hpp"
#include "../common/graph.hpp"
#include "constrained_set_cover.hpp"
class mesp_inner {
public:
int k;
int pi_first, pi_last;
std::shared_ptr<const graph> G;
std::shared_ptr<const std::unordered_set<int>> C;
path solution;
private:
std::unordered_set<int> L;
std::vector<int> pi;
std::unordered_map<int, int> e;
public:
mesp_inner(const std::shared_ptr<const graph> &G, const std::shared_ptr<const std::unordered_set<int>> &C, int k, int pi_first = -1, int pi_last = -1):
G(G),
C(C),
k(k),
pi_first(pi_first),
pi_last(pi_last)
{}
bool solve()
{
init_L();
do {
init_pi();
do {
if (!can_pi()) continue;
init_e();
do {
if (solve_inner()) return true;
} while (next_e());
} while (next_pi());
} while (next_L());
return false;
}
private:
bool solve_inner()
{
auto candidate_segments = get_segments();
if (!candidate_segments.has_value()) return false;
std::unordered_set<int> I(L.begin(), L.end());
std::vector<int> h_inv((*candidate_segments).size(), -1);
std::vector<std::vector<path>> candidates;
for (int i = 0; i < candidate_segments->size(); i++) {
if ((*candidate_segments)[i].size() == 1) {
for (int u : (*candidate_segments)[i][0]) I.insert(u);
continue;
}
candidates.emplace_back(std::move((*candidate_segments)[i]));
h_inv[i] = candidates.size() - 1;
}
std::unordered_set<int> U;
for (int v = 0; v < G->n; v++) {
if (C->count(v) || I.count(v)) continue;
if (estimate_path_dst(v) > k + 1) return false;
if (estimate_path_dst(v) == k + 1) U.insert(v);
}
if (U.size() > 2 * (pi.size() - 1)) return false;
std::vector<int> requirements;
for (int u = 0; u < G->n; u++) {
if (L.count(u)) continue;
if (!C->count(u) && !U.count(u)) continue;
int need_dst = e.count(u) ? e[u] : k;
if (G->distance(u, I) <= need_dst) continue;
requirements.push_back(u);
}
const std::function<boost::dynamic_bitset<>(const path &)> psi = [this, &requirements] (const path &segment) {
boost::dynamic_bitset<> res(requirements.size(), 0);
if (segment.empty()) return res;
for (int i = 0; i < requirements.size(); i++) {
int u = requirements[i];
int need_dst = e.count(u) ? e[u] : k;
if (G->distance(u, segment) <= need_dst) {
res[i] = true;
}
}
return res;
};
auto true_segment_id = constrained_set_cover(requirements, candidates, psi);
if (!true_segment_id.has_value()) return false;
solution.clear();
for (int i = 0; i < pi.size() - 1; i++) {
solution.push_back(pi[i]);
path &segment = h_inv[i] == -1 ? (*candidate_segments)[i][0] : candidates[h_inv[i]][(*true_segment_id)[h_inv[i]]];
for (int s : segment) solution.push_back(s);
}
solution.push_back(pi.back());
return G->ecc(solution) <= k;
}
std::optional<std::vector<std::vector<path>>> get_segments() const
{
std::vector<std::vector<path>> candidate_segments(pi.size() - 1);
for (int i = 0; i < pi.size() - 1; i++) {
std::queue<int> q;
q.push(pi[i + 1]);
std::unordered_map<int, int> dst = {{pi[i + 1], 0}};
while (!q.empty()) {
int u = q.front();
q.pop();
if (u == pi[i]) break;
for (int v : G->neighbors(u)) {
if (dst.count(v)) continue;
if (C->count(v) && v != pi[i]) continue;
dst[v] = dst[u] + 1;
q.push(v);
}
}
if (!dst.count(pi[i])) return std::nullopt;
if (dst[pi[i]] != G->distance(pi[i + 1], pi[i])) return std::nullopt;
std::vector<path> Sigma;
std::vector<int> K;
for (int u : G->neighbors(pi[i])) {
if (!dst.count(u) || dst[u] != dst[pi[i]] - 1) continue;
if (u == pi[i + 1]) {
Sigma.emplace_back();
break;
}
for (int v : G->neighbors(u)) {
if (!dst.count(v) || dst[v] != dst[u] - 1) continue;
Sigma.push_back({u});
int K_added = 0;
while (v != pi[i + 1]) {
int p = Sigma.back().back();
if (estimate_path_dst(v) > k) {
if (K_added++ < 2) K.push_back(v);
if (K.size() > 4) return std::nullopt;
}
Sigma.back().push_back(v);
for (int n : G->neighbors(v)) {
if (!dst.count(n) || dst[n] != dst[v] - 1) continue;
if (n == p) continue;
v = n;
break;
}
}
}
}
for (auto &segment : Sigma) {
std::vector<int> K_sat(K.size(), 0);
for (int j = 0; j < K.size(); j++) {
K_sat[j] |= G->distance(K[j], segment) <= k;
}
bool is_sat = true;
for (bool s : K_sat) is_sat |= s;
if (is_sat) {
candidate_segments[i].emplace_back(std::move(segment));
}
}
}
return candidate_segments;
}
void init_L()
{
L.clear();
auto C_iter = C->begin();
if (pi_first == -1) {
L.insert(*C_iter);
++C_iter;
} else {
L.insert(pi_first);
}
if (pi_last == -1) {
L.insert(*C_iter);
} else {
L.insert(pi_last);
}
}
bool next_L()
{
int max_size = C->size();
if (pi_first != -1) max_size++;
if (pi_last != -1) max_size++;
if (L.size() == max_size) return false;
do {
for (int v : *C) {
if (L.count(v)) {
L.erase(v);
} else {
L.insert(v);
break;
}
}
} while (L.size() < 2);
return true;
}
void init_pi()
{
pi.clear();
pi.reserve(L.size());
if (pi_first != -1) pi.push_back(pi_first);
for (int u : L) {
if (u == pi_first || u == pi_last) continue;
pi.push_back(u);
}
if (pi_last != -1) pi.push_back(pi_last);
std::sort(pi.begin() + (pi_first == -1 ? 0 : 1), pi.end() - (pi_last == -1 ? 0 : 1));
}
bool can_pi() const
{
int length = 0;
for (int i = 0; i < pi.size() - 1; i++) {
length += G->distance(pi[i], pi[i + 1]);
}
return length == G->distance(pi[0], pi.back());
}
bool next_pi()
{
int first = pi_first == -1 ? 0 : 1;
int last = (int) pi.size() - (pi_last == -1 ? 1 : 2);
if (first >= last) return false;
int m = last - 1;
while (m >= first && pi[m] > pi[m + 1]) m--;
if (m < first) return false;
int k = last;
while (pi[m] > pi[k]) k--;
std::swap(pi[m], pi[k]);
int p = m + 1;
int q = last;
while (p < q) {
std::swap(pi[p], pi[q]);
p++;
q--;
}
return true;
}
void init_e()
{
e.clear();
for (int v : *C) {
if (L.count(v)) continue;
e[v] = 1;
}
}
bool next_e()
{
int cnt = 0;
for (int v : *C) {
if (L.count(v)) continue;
if (e[v] < k) {
e[v]++;
break;
} else {
e[v] = 1;
cnt++;
}
}
return cnt < e.size();
}
int estimate_path_dst(int u) const
{
int res = INF;
if (pi_first != -1) {
res = std::min(res, G->distance(u, pi_first));
}
if (pi_last != -1) {
res = std::min(res, G->distance(u, pi_last));
}
for (int v : *C) {
int e_v = e.count(v) ? e.at(v) : 0;
res = std::min(res, G->distance(u, v) + e_v);
}
return res;
}
};
#endif //IMPL_MESP_INNER_HPP
|
State Before: α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
⊢ Memℓp f p State After: case intro.intro
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
⊢ Memℓp f p Tactic: obtain ⟨C, _, hCF'⟩ := hF.exists_pos_norm_le State Before: case intro.intro
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
⊢ Memℓp f p State After: case intro.intro
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
⊢ Memℓp f p Tactic: have hCF : ∀ k, ‖F k‖ ≤ C := fun k => hCF' _ ⟨k, rfl⟩ State Before: case intro.intro
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
⊢ Memℓp f p State After: case intro.intro.inl
α : Type u_1
E : α → Type u_2
q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
f : (a : α) → E a
C : ℝ
left✝ : C > 0
_i : Fact (1 ≤ ⊤)
F : ι → { x // x ∈ lp E ⊤ }
hF : Metric.Bounded (Set.range F)
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
hCF' : ∀ (x : { x // x ∈ lp E ⊤ }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
⊢ Memℓp f ⊤
case intro.intro.inr
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
hp : p < ⊤
⊢ Memℓp f p Tactic: rcases eq_top_or_lt_top p with (rfl | hp) State Before: case intro.intro.inl
α : Type u_1
E : α → Type u_2
q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
f : (a : α) → E a
C : ℝ
left✝ : C > 0
_i : Fact (1 ≤ ⊤)
F : ι → { x // x ∈ lp E ⊤ }
hF : Metric.Bounded (Set.range F)
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
hCF' : ∀ (x : { x // x ∈ lp E ⊤ }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
⊢ Memℓp f ⊤ State After: case intro.intro.inl.hf
α : Type u_1
E : α → Type u_2
q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
f : (a : α) → E a
C : ℝ
left✝ : C > 0
_i : Fact (1 ≤ ⊤)
F : ι → { x // x ∈ lp E ⊤ }
hF : Metric.Bounded (Set.range F)
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
hCF' : ∀ (x : { x // x ∈ lp E ⊤ }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
⊢ BddAbove (Set.range fun i => ‖f i‖) Tactic: apply memℓp_infty State Before: case intro.intro.inl.hf
α : Type u_1
E : α → Type u_2
q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
f : (a : α) → E a
C : ℝ
left✝ : C > 0
_i : Fact (1 ≤ ⊤)
F : ι → { x // x ∈ lp E ⊤ }
hF : Metric.Bounded (Set.range F)
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
hCF' : ∀ (x : { x // x ∈ lp E ⊤ }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
⊢ BddAbove (Set.range fun i => ‖f i‖) State After: case intro.intro.inl.hf
α : Type u_1
E : α → Type u_2
q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
f : (a : α) → E a
C : ℝ
left✝ : C > 0
_i : Fact (1 ≤ ⊤)
F : ι → { x // x ∈ lp E ⊤ }
hF : Metric.Bounded (Set.range F)
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
hCF' : ∀ (x : { x // x ∈ lp E ⊤ }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
⊢ C ∈ upperBounds (Set.range fun i => ‖f i‖) Tactic: use C State Before: case intro.intro.inl.hf
α : Type u_1
E : α → Type u_2
q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
f : (a : α) → E a
C : ℝ
left✝ : C > 0
_i : Fact (1 ≤ ⊤)
F : ι → { x // x ∈ lp E ⊤ }
hF : Metric.Bounded (Set.range F)
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
hCF' : ∀ (x : { x // x ∈ lp E ⊤ }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
⊢ C ∈ upperBounds (Set.range fun i => ‖f i‖) State After: case intro.intro.inl.hf.intro
α : Type u_1
E : α → Type u_2
q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
f : (a : α) → E a
C : ℝ
left✝ : C > 0
_i : Fact (1 ≤ ⊤)
F : ι → { x // x ∈ lp E ⊤ }
hF : Metric.Bounded (Set.range F)
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
hCF' : ∀ (x : { x // x ∈ lp E ⊤ }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
a : α
⊢ (fun i => ‖f i‖) a ≤ C Tactic: rintro _ ⟨a, rfl⟩ State Before: case intro.intro.inl.hf.intro
α : Type u_1
E : α → Type u_2
q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
f : (a : α) → E a
C : ℝ
left✝ : C > 0
_i : Fact (1 ≤ ⊤)
F : ι → { x // x ∈ lp E ⊤ }
hF : Metric.Bounded (Set.range F)
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
hCF' : ∀ (x : { x // x ∈ lp E ⊤ }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
a : α
⊢ (fun i => ‖f i‖) a ≤ C State After: no goals Tactic: refine' norm_apply_le_of_tendsto (eventually_of_forall hCF) hf a State Before: case intro.intro.inr
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
hp : p < ⊤
⊢ Memℓp f p State After: case intro.intro.inr.hf
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
hp : p < ⊤
⊢ ∀ (s : Finset α), ∑ i in s, ‖f i‖ ^ ENNReal.toReal p ≤ ?intro.intro.inr.C
case intro.intro.inr.C
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
hp : p < ⊤
⊢ ℝ Tactic: apply memℓp_gen' State Before: case intro.intro.inr.hf
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
hp : p < ⊤
⊢ ∀ (s : Finset α), ∑ i in s, ‖f i‖ ^ ENNReal.toReal p ≤ ?intro.intro.inr.C
case intro.intro.inr.C
α : Type u_1
E : α → Type u_2
p q : ℝ≥0∞
inst✝¹ : (i : α) → NormedAddCommGroup (E i)
ι : Type u_3
l : Filter ι
inst✝ : NeBot l
_i : Fact (1 ≤ p)
F : ι → { x // x ∈ lp E p }
hF : Metric.Bounded (Set.range F)
f : (a : α) → E a
hf : Tendsto (id fun i => ↑(F i)) l (𝓝 f)
C : ℝ
left✝ : C > 0
hCF' : ∀ (x : { x // x ∈ lp E p }), x ∈ Set.range F → ‖x‖ ≤ C
hCF : ∀ (k : ι), ‖F k‖ ≤ C
hp : p < ⊤
⊢ ℝ State After: no goals Tactic: exact sum_rpow_le_of_tendsto hp.ne (eventually_of_forall hCF) hf |
[STATEMENT]
lemma nonstrict_eq: "non_strict_dominate i j \<Longrightarrow> \<not> strict_dominate i j"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. non_strict_dominate i j \<Longrightarrow> \<not> strict_dominate i j
[PROOF STEP]
by (auto simp add:non_strict_dominate_def strict_dominate_def) |
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Animating the CompCert C semantics *)
Require Import String.
Require Import Axioms.
Require Import Classical.
Require Import Coqlib.
Require Import Errors.
Require Import Maps.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import AST.
Require Import Memory.
Require Import Events.
Require Import Globalenvs.
Require Import Determinism.
Require Import Ctypes.
Require Import Cop.
Require Import Csyntax.
Require Import Csem.
Require Cstrategy.
Local Open Scope string_scope.
Local Open Scope list_scope.
(** Error monad with options or lists *)
Notation "'do' X <- A ; B" := (match A with Some X => B | None => None end)
(at level 200, X ident, A at level 100, B at level 200)
: option_monad_scope.
Notation "'do' X , Y <- A ; B" := (match A with Some (X, Y) => B | None => None end)
(at level 200, X ident, Y ident, A at level 100, B at level 200)
: option_monad_scope.
Notation "'do' X , Y , Z <- A ; B" := (match A with Some (X, Y, Z) => B | None => None end)
(at level 200, X ident, Y ident, Z ident, A at level 100, B at level 200)
: option_monad_scope.
Notation " 'check' A ; B" := (if A then B else None)
(at level 200, A at level 100, B at level 200)
: option_monad_scope.
Notation "'do' X <- A ; B" := (match A with Some X => B | None => nil end)
(at level 200, X ident, A at level 100, B at level 200)
: list_monad_scope.
Notation " 'check' A ; B" := (if A then B else nil)
(at level 200, A at level 100, B at level 200)
: list_monad_scope.
Definition is_val (a: expr) : option (val * type) :=
match a with
| Eval v ty => Some(v, ty)
| _ => None
end.
Lemma is_val_inv:
forall a v ty, is_val a = Some(v, ty) -> a = Eval v ty.
Proof.
intros until ty. destruct a; simpl; congruence.
Qed.
Definition is_loc (a: expr) : option (block * int * type) :=
match a with
| Eloc b ofs ty => Some(b, ofs, ty)
| _ => None
end.
Lemma is_loc_inv:
forall a b ofs ty, is_loc a = Some(b, ofs, ty) -> a = Eloc b ofs ty.
Proof.
intros until ty. destruct a; simpl; congruence.
Qed.
Local Open Scope option_monad_scope.
Fixpoint is_val_list (al: exprlist) : option (list (val * type)) :=
match al with
| Enil => Some nil
| Econs a1 al => do vt1 <- is_val a1; do vtl <- is_val_list al; Some(vt1::vtl)
end.
Definition is_skip (s: statement) : {s = Sskip} + {s <> Sskip}.
Proof.
destruct s; (left; congruence) || (right; congruence).
Defined.
(** * Events, volatile memory accesses, and external functions. *)
Section EXEC.
Variable ge: genv.
Definition eventval_of_val (v: val) (t: typ) : option eventval :=
match v, t with
| Vint i, AST.Tint => Some (EVint i)
| Vfloat f, AST.Tfloat => Some (EVfloat f)
| Vsingle f, AST.Tsingle => Some (EVsingle f)
| Vlong n, AST.Tlong => Some (EVlong n)
| Vptr b ofs, AST.Tint =>
do id <- Genv.invert_symbol ge b;
check (Genv.public_symbol ge id);
Some (EVptr_global id ofs)
| _, _ => None
end.
Fixpoint list_eventval_of_val (vl: list val) (tl: list typ) : option (list eventval) :=
match vl, tl with
| nil, nil => Some nil
| v1::vl, t1::tl =>
do ev1 <- eventval_of_val v1 t1;
do evl <- list_eventval_of_val vl tl;
Some (ev1 :: evl)
| _, _ => None
end.
Definition val_of_eventval (ev: eventval) (t: typ) : option val :=
match ev, t with
| EVint i, AST.Tint => Some (Vint i)
| EVfloat f, AST.Tfloat => Some (Vfloat f)
| EVsingle f, AST.Tsingle => Some (Vsingle f)
| EVlong n, AST.Tlong => Some (Vlong n)
| EVptr_global id ofs, AST.Tint =>
check (Genv.public_symbol ge id);
do b <- Genv.find_symbol ge id;
Some (Vptr b ofs)
| _, _ => None
end.
Lemma eventval_of_val_sound:
forall v t ev, eventval_of_val v t = Some ev -> eventval_match ge ev t v.
Proof.
intros. destruct v; destruct t; simpl in H; inv H; try constructor.
destruct (Genv.invert_symbol ge b) as [id|] eqn:?; try discriminate.
destruct (Genv.public_symbol ge id) eqn:?; inv H1.
constructor. auto. apply Genv.invert_find_symbol; auto.
Qed.
Lemma eventval_of_val_complete:
forall ev t v, eventval_match ge ev t v -> eventval_of_val v t = Some ev.
Proof.
induction 1; simpl; auto.
rewrite (Genv.find_invert_symbol _ _ H0). simpl in H; rewrite H. auto.
Qed.
Lemma list_eventval_of_val_sound:
forall vl tl evl, list_eventval_of_val vl tl = Some evl -> eventval_list_match ge evl tl vl.
Proof with try discriminate.
induction vl; destruct tl; simpl; intros; inv H.
constructor.
destruct (eventval_of_val a t) as [ev1|] eqn:?...
destruct (list_eventval_of_val vl tl) as [evl'|] eqn:?...
inv H1. constructor. apply eventval_of_val_sound; auto. eauto.
Qed.
Lemma list_eventval_of_val_complete:
forall evl tl vl, eventval_list_match ge evl tl vl -> list_eventval_of_val vl tl = Some evl.
Proof.
induction 1; simpl. auto.
rewrite (eventval_of_val_complete _ _ _ H). rewrite IHeventval_list_match. auto.
Qed.
Lemma val_of_eventval_sound:
forall ev t v, val_of_eventval ev t = Some v -> eventval_match ge ev t v.
Proof.
intros. destruct ev; destruct t; simpl in H; inv H; try constructor.
destruct (Genv.public_symbol ge i) eqn:?; try discriminate.
destruct (Genv.find_symbol ge i) as [b|] eqn:?; inv H1.
constructor; auto.
Qed.
Lemma val_of_eventval_complete:
forall ev t v, eventval_match ge ev t v -> val_of_eventval ev t = Some v.
Proof.
induction 1; simpl; auto. simpl in *. rewrite H, H0; auto.
Qed.
(** Volatile memory accesses. *)
Definition do_volatile_load (w: world) (chunk: memory_chunk) (m: mem) (b: block) (ofs: int)
: option (world * trace * val) :=
if Genv.block_is_volatile ge b then
do id <- Genv.invert_symbol ge b;
match nextworld_vload w chunk id ofs with
| None => None
| Some(res, w') =>
do vres <- val_of_eventval res (type_of_chunk chunk);
Some(w', Event_vload chunk id ofs res :: nil, Val.load_result chunk vres)
end
else
do v <- Mem.load chunk m b (Int.unsigned ofs);
Some(w, E0, v).
Definition do_volatile_store (w: world) (chunk: memory_chunk) (m: mem) (b: block) (ofs: int) (v: val)
: option (world * trace * mem) :=
if Genv.block_is_volatile ge b then
do id <- Genv.invert_symbol ge b;
do ev <- eventval_of_val (Val.load_result chunk v) (type_of_chunk chunk);
do w' <- nextworld_vstore w chunk id ofs ev;
Some(w', Event_vstore chunk id ofs ev :: nil, m)
else
do m' <- Mem.store chunk m b (Int.unsigned ofs) v;
Some(w, E0, m').
Ltac mydestr :=
match goal with
| [ |- None = Some _ -> _ ] => intro X; discriminate
| [ |- Some _ = Some _ -> _ ] => intro X; inv X
| [ |- match ?x with Some _ => _ | None => _ end = Some _ -> _ ] => destruct x eqn:?; mydestr
| [ |- match ?x with true => _ | false => _ end = Some _ -> _ ] => destruct x eqn:?; mydestr
| [ |- match ?x with left _ => _ | right _ => _ end = Some _ -> _ ] => destruct x; mydestr
| _ => idtac
end.
Lemma do_volatile_load_sound:
forall w chunk m b ofs w' t v,
do_volatile_load w chunk m b ofs = Some(w', t, v) ->
volatile_load ge chunk m b ofs t v /\ possible_trace w t w'.
Proof.
intros until v. unfold do_volatile_load. mydestr.
destruct p as [ev w'']. mydestr.
split. constructor; auto. apply Genv.invert_find_symbol; auto.
apply val_of_eventval_sound; auto.
econstructor. constructor; eauto. constructor.
split. constructor; auto. constructor.
Qed.
Lemma do_volatile_load_complete:
forall w chunk m b ofs w' t v,
volatile_load ge chunk m b ofs t v -> possible_trace w t w' ->
do_volatile_load w chunk m b ofs = Some(w', t, v).
Proof.
unfold do_volatile_load; intros. inv H; simpl in *.
rewrite H1. rewrite (Genv.find_invert_symbol _ _ H2). inv H0. inv H8. inv H6. rewrite H9.
rewrite (val_of_eventval_complete _ _ _ H3). auto.
rewrite H1. rewrite H2. inv H0. auto.
Qed.
Lemma do_volatile_store_sound:
forall w chunk m b ofs v w' t m',
do_volatile_store w chunk m b ofs v = Some(w', t, m') ->
volatile_store ge chunk m b ofs v t m' /\ possible_trace w t w'.
Proof.
intros until m'. unfold do_volatile_store. mydestr.
split. constructor; auto. apply Genv.invert_find_symbol; auto.
apply eventval_of_val_sound; auto.
econstructor. constructor; eauto. constructor.
split. constructor; auto. constructor.
Qed.
Lemma do_volatile_store_complete:
forall w chunk m b ofs v w' t m',
volatile_store ge chunk m b ofs v t m' -> possible_trace w t w' ->
do_volatile_store w chunk m b ofs v = Some(w', t, m').
Proof.
unfold do_volatile_store; intros. inv H; simpl in *.
rewrite H1. rewrite (Genv.find_invert_symbol _ _ H2).
rewrite (eventval_of_val_complete _ _ _ H3).
inv H0. inv H8. inv H6. rewrite H9. auto.
rewrite H1. rewrite H2. inv H0. auto.
Qed.
(** Accessing locations *)
Definition do_deref_loc (w: world) (ty: type) (m: mem) (b: block) (ofs: int) : option (world * trace * val) :=
match access_mode ty with
| By_value chunk =>
match type_is_volatile ty with
| false => do v <- Mem.loadv chunk m (Vptr b ofs); Some(w, E0, v)
| true => do_volatile_load w chunk m b ofs
end
| By_reference => Some(w, E0, Vptr b ofs)
| By_copy => Some(w, E0, Vptr b ofs)
| _ => None
end.
Definition assign_copy_ok (ty: type) (b: block) (ofs: int) (b': block) (ofs': int) : Prop :=
(alignof_blockcopy ge ty | Int.unsigned ofs') /\ (alignof_blockcopy ge ty | Int.unsigned ofs) /\
(b' <> b \/ Int.unsigned ofs' = Int.unsigned ofs
\/ Int.unsigned ofs' + sizeof ge ty <= Int.unsigned ofs
\/ Int.unsigned ofs + sizeof ge ty <= Int.unsigned ofs').
Remark check_assign_copy:
forall (ty: type) (b: block) (ofs: int) (b': block) (ofs': int),
{ assign_copy_ok ty b ofs b' ofs' } + {~ assign_copy_ok ty b ofs b' ofs' }.
Proof with try (right; intuition omega).
intros. unfold assign_copy_ok.
assert (alignof_blockcopy ge ty > 0) by apply alignof_blockcopy_pos.
destruct (Zdivide_dec (alignof_blockcopy ge ty) (Int.unsigned ofs')); auto...
destruct (Zdivide_dec (alignof_blockcopy ge ty) (Int.unsigned ofs)); auto...
assert (Y: {b' <> b \/
Int.unsigned ofs' = Int.unsigned ofs \/
Int.unsigned ofs' + sizeof ge ty <= Int.unsigned ofs \/
Int.unsigned ofs + sizeof ge ty <= Int.unsigned ofs'} +
{~(b' <> b \/
Int.unsigned ofs' = Int.unsigned ofs \/
Int.unsigned ofs' + sizeof ge ty <= Int.unsigned ofs \/
Int.unsigned ofs + sizeof ge ty <= Int.unsigned ofs')}).
destruct (eq_block b' b); auto.
destruct (zeq (Int.unsigned ofs') (Int.unsigned ofs)); auto.
destruct (zle (Int.unsigned ofs' + sizeof ge ty) (Int.unsigned ofs)); auto.
destruct (zle (Int.unsigned ofs + sizeof ge ty) (Int.unsigned ofs')); auto.
right; intuition omega.
destruct Y... left; intuition omega.
Defined.
Definition do_assign_loc (w: world) (ty: type) (m: mem) (b: block) (ofs: int) (v: val): option (world * trace * mem) :=
match access_mode ty with
| By_value chunk =>
match type_is_volatile ty with
| false => do m' <- Mem.storev chunk m (Vptr b ofs) v; Some(w, E0, m')
| true => do_volatile_store w chunk m b ofs v
end
| By_copy =>
match v with
| Vptr b' ofs' =>
if check_assign_copy ty b ofs b' ofs' then
do bytes <- Mem.loadbytes m b' (Int.unsigned ofs') (sizeof ge ty);
do m' <- Mem.storebytes m b (Int.unsigned ofs) bytes;
Some(w, E0, m')
else None
| _ => None
end
| _ => None
end.
Lemma do_deref_loc_sound:
forall w ty m b ofs w' t v,
do_deref_loc w ty m b ofs = Some(w', t, v) ->
deref_loc ge ty m b ofs t v /\ possible_trace w t w'.
Proof.
unfold do_deref_loc; intros until v.
destruct (access_mode ty) eqn:?; mydestr.
intros. exploit do_volatile_load_sound; eauto. intuition. eapply deref_loc_volatile; eauto.
split. eapply deref_loc_value; eauto. constructor.
split. eapply deref_loc_reference; eauto. constructor.
split. eapply deref_loc_copy; eauto. constructor.
Qed.
Lemma do_deref_loc_complete:
forall w ty m b ofs w' t v,
deref_loc ge ty m b ofs t v -> possible_trace w t w' ->
do_deref_loc w ty m b ofs = Some(w', t, v).
Proof.
unfold do_deref_loc; intros. inv H.
inv H0. rewrite H1; rewrite H2; rewrite H3; auto.
rewrite H1; rewrite H2. apply do_volatile_load_complete; auto.
inv H0. rewrite H1. auto.
inv H0. rewrite H1. auto.
Qed.
Lemma do_assign_loc_sound:
forall w ty m b ofs v w' t m',
do_assign_loc w ty m b ofs v = Some(w', t, m') ->
assign_loc ge ty m b ofs v t m' /\ possible_trace w t w'.
Proof.
unfold do_assign_loc; intros until m'.
destruct (access_mode ty) eqn:?; mydestr.
intros. exploit do_volatile_store_sound; eauto. intuition. eapply assign_loc_volatile; eauto.
split. eapply assign_loc_value; eauto. constructor.
destruct v; mydestr. destruct a as [P [Q R]].
split. eapply assign_loc_copy; eauto. constructor.
Qed.
Lemma do_assign_loc_complete:
forall w ty m b ofs v w' t m',
assign_loc ge ty m b ofs v t m' -> possible_trace w t w' ->
do_assign_loc w ty m b ofs v = Some(w', t, m').
Proof.
unfold do_assign_loc; intros. inv H.
inv H0. rewrite H1; rewrite H2; rewrite H3; auto.
rewrite H1; rewrite H2. apply do_volatile_store_complete; auto.
rewrite H1. destruct (check_assign_copy ty b ofs b' ofs').
inv H0. rewrite H5; rewrite H6; auto.
elim n. red; tauto.
Qed.
(** External calls *)
Variable do_external_function:
ident -> signature -> Senv.t -> world -> list val -> mem -> option (world * trace * val * mem).
Hypothesis do_external_function_sound:
forall id sg ge vargs m t vres m' w w',
do_external_function id sg ge w vargs m = Some(w', t, vres, m') ->
external_functions_sem id sg ge vargs m t vres m' /\ possible_trace w t w'.
Hypothesis do_external_function_complete:
forall id sg ge vargs m t vres m' w w',
external_functions_sem id sg ge vargs m t vres m' ->
possible_trace w t w' ->
do_external_function id sg ge w vargs m = Some(w', t, vres, m').
Variable do_inline_assembly:
ident -> signature -> Senv.t -> world -> list val -> mem -> option (world * trace * val * mem).
Hypothesis do_inline_assembly_sound:
forall txt sg ge vargs m t vres m' w w',
do_inline_assembly txt sg ge w vargs m = Some(w', t, vres, m') ->
inline_assembly_sem txt sg ge vargs m t vres m' /\ possible_trace w t w'.
Hypothesis do_inline_assembly_complete:
forall txt sg ge vargs m t vres m' w w',
inline_assembly_sem txt sg ge vargs m t vres m' ->
possible_trace w t w' ->
do_inline_assembly txt sg ge w vargs m = Some(w', t, vres, m').
Definition do_ef_volatile_load (chunk: memory_chunk)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| Vptr b ofs :: nil => do w',t,v <- do_volatile_load w chunk m b ofs; Some(w',t,v,m)
| _ => None
end.
Definition do_ef_volatile_store (chunk: memory_chunk)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| Vptr b ofs :: v :: nil => do w',t,m' <- do_volatile_store w chunk m b ofs v; Some(w',t,Vundef,m')
| _ => None
end.
Definition do_ef_volatile_load_global (chunk: memory_chunk) (id: ident) (ofs: int)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
do b <- Genv.find_symbol ge id; do_ef_volatile_load chunk w (Vptr b ofs :: vargs) m.
Definition do_ef_volatile_store_global (chunk: memory_chunk) (id: ident) (ofs: int)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
do b <- Genv.find_symbol ge id; do_ef_volatile_store chunk w (Vptr b ofs :: vargs) m.
Definition do_ef_malloc
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| Vint n :: nil =>
let (m', b) := Mem.alloc m (-4) (Int.unsigned n) in
do m'' <- Mem.store Mint32 m' b (-4) (Vint n);
Some(w, E0, Vptr b Int.zero, m'')
| _ => None
end.
Definition do_ef_free
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| Vptr b lo :: nil =>
do vsz <- Mem.load Mint32 m b (Int.unsigned lo - 4);
match vsz with
| Vint sz =>
check (zlt 0 (Int.unsigned sz));
do m' <- Mem.free m b (Int.unsigned lo - 4) (Int.unsigned lo + Int.unsigned sz);
Some(w, E0, Vundef, m')
| _ => None
end
| _ => None
end.
Definition memcpy_args_ok
(sz al: Z) (bdst: block) (odst: Z) (bsrc: block) (osrc: Z) : Prop :=
(al = 1 \/ al = 2 \/ al = 4 \/ al = 8)
/\ sz >= 0 /\ (al | sz)
/\ (sz > 0 -> (al | osrc))
/\ (sz > 0 -> (al | odst))
/\ (bsrc <> bdst \/ osrc = odst \/ osrc + sz <= odst \/ odst + sz <= osrc).
Remark memcpy_check_args:
forall sz al bdst odst bsrc osrc,
{memcpy_args_ok sz al bdst odst bsrc osrc} + {~memcpy_args_ok sz al bdst odst bsrc osrc}.
Proof with try (right; intuition omega).
intros.
assert (X: {al = 1 \/ al = 2 \/ al = 4 \/ al = 8} + {~(al = 1 \/ al = 2 \/ al = 4 \/ al = 8)}).
destruct (zeq al 1); auto. destruct (zeq al 2); auto.
destruct (zeq al 4); auto. destruct (zeq al 8); auto...
unfold memcpy_args_ok. destruct X...
assert (al > 0) by (intuition omega).
destruct (zle 0 sz)...
destruct (Zdivide_dec al sz); auto...
assert(U: forall x, {sz > 0 -> (al | x)} + {~(sz > 0 -> (al | x))}).
intros. destruct (zeq sz 0).
left; intros; omegaContradiction.
destruct (Zdivide_dec al x); auto. right; red; intros. elim n0. apply H0. omega.
destruct (U osrc); auto...
destruct (U odst); auto...
assert (Y: {bsrc <> bdst \/ osrc = odst \/ osrc + sz <= odst \/ odst + sz <= osrc}
+{~(bsrc <> bdst \/ osrc = odst \/ osrc + sz <= odst \/ odst + sz <= osrc)}).
destruct (eq_block bsrc bdst); auto.
destruct (zeq osrc odst); auto.
destruct (zle (osrc + sz) odst); auto.
destruct (zle (odst + sz) osrc); auto.
right; intuition omega.
destruct Y... left; intuition omega.
Defined.
Definition do_ef_memcpy (sz al: Z)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| Vptr bdst odst :: Vptr bsrc osrc :: nil =>
if memcpy_check_args sz al bdst (Int.unsigned odst) bsrc (Int.unsigned osrc) then
do bytes <- Mem.loadbytes m bsrc (Int.unsigned osrc) sz;
do m' <- Mem.storebytes m bdst (Int.unsigned odst) bytes;
Some(w, E0, Vundef, m')
else None
| _ => None
end.
Definition do_ef_annot (text: ident) (targs: list typ)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
do args <- list_eventval_of_val vargs targs;
Some(w, Event_annot text args :: E0, Vundef, m).
Definition do_ef_annot_val (text: ident) (targ: typ)
(w: world) (vargs: list val) (m: mem) : option (world * trace * val * mem) :=
match vargs with
| varg :: nil =>
do arg <- eventval_of_val varg targ;
Some(w, Event_annot text (arg :: nil) :: E0, varg, m)
| _ => None
end.
Definition do_external (ef: external_function):
world -> list val -> mem -> option (world * trace * val * mem) :=
match ef with
| EF_external name sg => do_external_function name sg ge
| EF_builtin name sg => do_external_function name sg ge
| EF_vload chunk => do_ef_volatile_load chunk
| EF_vstore chunk => do_ef_volatile_store chunk
| EF_vload_global chunk id ofs => do_ef_volatile_load_global chunk id ofs
| EF_vstore_global chunk id ofs => do_ef_volatile_store_global chunk id ofs
| EF_malloc => do_ef_malloc
| EF_free => do_ef_free
| EF_memcpy sz al => do_ef_memcpy sz al
| EF_annot text targs => do_ef_annot text targs
| EF_annot_val text targ => do_ef_annot_val text targ
| EF_inline_asm text sg clob => do_inline_assembly text sg ge
end.
Lemma do_ef_external_sound:
forall ef w vargs m w' t vres m',
do_external ef w vargs m = Some(w', t, vres, m') ->
external_call ef ge vargs m t vres m' /\ possible_trace w t w'.
Proof with try congruence.
intros until m'.
assert (VLOAD: forall chunk vargs,
do_ef_volatile_load chunk w vargs m = Some (w', t, vres, m') ->
volatile_load_sem chunk ge vargs m t vres m' /\ possible_trace w t w').
intros chunk vargs'.
unfold do_ef_volatile_load. destruct vargs'... destruct v... destruct vargs'...
mydestr. destruct p as [[w'' t''] v]; mydestr.
exploit do_volatile_load_sound; eauto. intuition. econstructor; eauto.
assert (VSTORE: forall chunk vargs,
do_ef_volatile_store chunk w vargs m = Some (w', t, vres, m') ->
volatile_store_sem chunk ge vargs m t vres m' /\ possible_trace w t w').
intros chunk vargs'.
unfold do_ef_volatile_store. destruct vargs'... destruct v... destruct vargs'... destruct vargs'...
mydestr. destruct p as [[w'' t''] m'']. mydestr.
exploit do_volatile_store_sound; eauto. intuition. econstructor; eauto.
destruct ef; simpl.
(* EF_external *)
eapply do_external_function_sound; eauto.
(* EF_builtin *)
eapply do_external_function_sound; eauto.
(* EF_vload *)
auto.
(* EF_vstore *)
auto.
(* EF_vload_global *)
rewrite volatile_load_global_charact; simpl.
unfold do_ef_volatile_load_global. destruct (Genv.find_symbol ge)...
intros. exploit VLOAD; eauto. intros [A B]. split; auto. exists b; auto.
(* EF_vstore_global *)
rewrite volatile_store_global_charact; simpl.
unfold do_ef_volatile_store_global. destruct (Genv.find_symbol ge)...
intros. exploit VSTORE; eauto. intros [A B]. split; auto. exists b; auto.
(* EF_malloc *)
unfold do_ef_malloc. destruct vargs... destruct v... destruct vargs...
destruct (Mem.alloc m (-4) (Int.unsigned i)) as [m1 b] eqn:?. mydestr.
split. econstructor; eauto. constructor.
(* EF_free *)
unfold do_ef_free. destruct vargs... destruct v... destruct vargs...
mydestr. destruct v... mydestr.
split. econstructor; eauto. omega. constructor.
(* EF_memcpy *)
unfold do_ef_memcpy. destruct vargs... destruct v... destruct vargs...
destruct v... destruct vargs... mydestr. red in m0.
split. econstructor; eauto; tauto. constructor.
(* EF_annot *)
unfold do_ef_annot. mydestr.
split. constructor. apply list_eventval_of_val_sound; auto.
econstructor. constructor; eauto. constructor.
(* EF_annot_val *)
unfold do_ef_annot_val. destruct vargs... destruct vargs... mydestr.
split. constructor. apply eventval_of_val_sound; auto.
econstructor. constructor; eauto. constructor.
(* EF_inline_asm *)
eapply do_inline_assembly_sound; eauto.
Qed.
Lemma do_ef_external_complete:
forall ef w vargs m w' t vres m',
external_call ef ge vargs m t vres m' -> possible_trace w t w' ->
do_external ef w vargs m = Some(w', t, vres, m').
Proof.
intros.
assert (VLOAD: forall chunk vargs,
volatile_load_sem chunk ge vargs m t vres m' ->
do_ef_volatile_load chunk w vargs m = Some (w', t, vres, m')).
intros. inv H1; unfold do_ef_volatile_load.
exploit do_volatile_load_complete; eauto. intros EQ; rewrite EQ; auto.
assert (VSTORE: forall chunk vargs,
volatile_store_sem chunk ge vargs m t vres m' ->
do_ef_volatile_store chunk w vargs m = Some (w', t, vres, m')).
intros. inv H1; unfold do_ef_volatile_store.
exploit do_volatile_store_complete; eauto. intros EQ; rewrite EQ; auto.
destruct ef; simpl in *.
(* EF_external *)
eapply do_external_function_complete; eauto.
(* EF_builtin *)
eapply do_external_function_complete; eauto.
(* EF_vload *)
auto.
(* EF_vstore *)
auto.
(* EF_vload_global *)
rewrite volatile_load_global_charact in H; simpl in H. destruct H as [b [P Q]].
unfold do_ef_volatile_load_global. rewrite P. auto.
(* EF_vstore *)
rewrite volatile_store_global_charact in H; simpl in H. destruct H as [b [P Q]].
unfold do_ef_volatile_store_global. rewrite P. auto.
(* EF_malloc *)
inv H; unfold do_ef_malloc.
inv H0. rewrite H1. rewrite H2. auto.
(* EF_free *)
inv H; unfold do_ef_free.
inv H0. rewrite H1. rewrite zlt_true. rewrite H3. auto. omega.
(* EF_memcpy *)
inv H; unfold do_ef_memcpy.
inv H0. rewrite pred_dec_true. rewrite H7; rewrite H8; auto.
red. tauto.
(* EF_annot *)
inv H; unfold do_ef_annot. inv H0. inv H6. inv H4.
rewrite (list_eventval_of_val_complete _ _ _ H1). auto.
(* EF_annot_val *)
inv H; unfold do_ef_annot_val. inv H0. inv H6. inv H4.
rewrite (eventval_of_val_complete _ _ _ H1). auto.
(* EF_inline_asm *)
eapply do_inline_assembly_complete; eauto.
Qed.
(** * Reduction of expressions *)
Inductive reduction: Type :=
| Lred (rule: string) (l': expr) (m': mem)
| Rred (rule: string) (r': expr) (m': mem) (t: trace)
| Callred (rule: string) (fd: fundef) (args: list val) (tyres: type) (m': mem)
| Stuckred.
Section EXPRS.
Variable e: env.
Variable w: world.
Fixpoint sem_cast_arguments (vtl: list (val * type)) (tl: typelist) : option (list val) :=
match vtl, tl with
| nil, Tnil => Some nil
| (v1,t1)::vtl, Tcons t1' tl =>
do v <- sem_cast v1 t1 t1'; do vl <- sem_cast_arguments vtl tl; Some(v::vl)
| _, _ => None
end.
(** The result of stepping an expression is a list [ll] of possible reducts.
Each element of [ll] is a pair of a context and the result of reducing
inside this context (see type [reduction] above).
The list [ll] is empty if the expression is fully reduced
(it's [Eval] for a r-value and [Eloc] for a l-value).
*)
Definition reducts (A: Type): Type := list ((expr -> A) * reduction).
Definition topred (r: reduction) : reducts expr :=
((fun (x: expr) => x), r) :: nil.
Definition stuck : reducts expr :=
((fun (x: expr) => x), Stuckred) :: nil.
Definition incontext {A B: Type} (ctx: A -> B) (ll: reducts A) : reducts B :=
map (fun z => ((fun (x: expr) => ctx(fst z x)), snd z)) ll.
Definition incontext2 {A1 A2 B: Type}
(ctx1: A1 -> B) (ll1: reducts A1)
(ctx2: A2 -> B) (ll2: reducts A2) : reducts B :=
incontext ctx1 ll1 ++ incontext ctx2 ll2.
Notation "'do' X <- A ; B" := (match A with Some X => B | None => stuck end)
(at level 200, X ident, A at level 100, B at level 200)
: reducts_monad_scope.
Notation "'do' X , Y <- A ; B" := (match A with Some (X, Y) => B | None => stuck end)
(at level 200, X ident, Y ident, A at level 100, B at level 200)
: reducts_monad_scope.
Notation "'do' X , Y , Z <- A ; B" := (match A with Some (X, Y, Z) => B | None => stuck end)
(at level 200, X ident, Y ident, Z ident, A at level 100, B at level 200)
: reducts_monad_scope.
Notation " 'check' A ; B" := (if A then B else stuck)
(at level 200, A at level 100, B at level 200)
: reducts_monad_scope.
Local Open Scope reducts_monad_scope.
Fixpoint step_expr (k: kind) (a: expr) (m: mem): reducts expr :=
match k, a with
| LV, Eloc b ofs ty =>
nil
| LV, Evar x ty =>
match e!x with
| Some(b, ty') =>
check type_eq ty ty';
topred (Lred "red_var_local" (Eloc b Int.zero ty) m)
| None =>
do b <- Genv.find_symbol ge x;
topred (Lred "red_var_global" (Eloc b Int.zero ty) m)
end
| LV, Ederef r ty =>
match is_val r with
| Some(Vptr b ofs, ty') =>
topred (Lred "red_deref" (Eloc b ofs ty) m)
| Some _ =>
stuck
| None =>
incontext (fun x => Ederef x ty) (step_expr RV r m)
end
| LV, Efield r f ty =>
match is_val r with
| Some(Vptr b ofs, ty') =>
match ty' with
| Tstruct id _ =>
do co <- ge.(genv_cenv)!id;
match field_offset ge f (co_members co) with
| Error _ => stuck
| OK delta => topred (Lred "red_field_struct" (Eloc b (Int.add ofs (Int.repr delta)) ty) m)
end
| Tunion id _ =>
do co <- ge.(genv_cenv)!id;
topred (Lred "red_field_union" (Eloc b ofs ty) m)
| _ => stuck
end
| Some _ =>
stuck
| None =>
incontext (fun x => Efield x f ty) (step_expr RV r m)
end
| RV, Eval v ty =>
nil
| RV, Evalof l ty =>
match is_loc l with
| Some(b, ofs, ty') =>
check type_eq ty ty';
do w',t,v <- do_deref_loc w ty m b ofs;
topred (Rred "red_rvalof" (Eval v ty) m t)
| None =>
incontext (fun x => Evalof x ty) (step_expr LV l m)
end
| RV, Eaddrof l ty =>
match is_loc l with
| Some(b, ofs, ty') => topred (Rred "red_addrof" (Eval (Vptr b ofs) ty) m E0)
| None => incontext (fun x => Eaddrof x ty) (step_expr LV l m)
end
| RV, Eunop op r1 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do v <- sem_unary_operation op v1 ty1 m;
topred (Rred "red_unop" (Eval v ty) m E0)
| None =>
incontext (fun x => Eunop op x ty) (step_expr RV r1 m)
end
| RV, Ebinop op r1 r2 ty =>
match is_val r1, is_val r2 with
| Some(v1, ty1), Some(v2, ty2) =>
do v <- sem_binary_operation ge op v1 ty1 v2 ty2 m;
topred (Rred "red_binop" (Eval v ty) m E0)
| _, _ =>
incontext2 (fun x => Ebinop op x r2 ty) (step_expr RV r1 m)
(fun x => Ebinop op r1 x ty) (step_expr RV r2 m)
end
| RV, Ecast r1 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do v <- sem_cast v1 ty1 ty;
topred (Rred "red_cast" (Eval v ty) m E0)
| None =>
incontext (fun x => Ecast x ty) (step_expr RV r1 m)
end
| RV, Eseqand r1 r2 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do b <- bool_val v1 ty1 m;
if b then topred (Rred "red_seqand_true" (Eparen r2 type_bool ty) m E0)
else topred (Rred "red_seqand_false" (Eval (Vint Int.zero) ty) m E0)
| None =>
incontext (fun x => Eseqand x r2 ty) (step_expr RV r1 m)
end
| RV, Eseqor r1 r2 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do b <- bool_val v1 ty1 m;
if b then topred (Rred "red_seqor_true" (Eval (Vint Int.one) ty) m E0)
else topred (Rred "red_seqor_false" (Eparen r2 type_bool ty) m E0)
| None =>
incontext (fun x => Eseqor x r2 ty) (step_expr RV r1 m)
end
| RV, Econdition r1 r2 r3 ty =>
match is_val r1 with
| Some(v1, ty1) =>
do b <- bool_val v1 ty1 m;
topred (Rred "red_condition" (Eparen (if b then r2 else r3) ty ty) m E0)
| None =>
incontext (fun x => Econdition x r2 r3 ty) (step_expr RV r1 m)
end
| RV, Esizeof ty' ty =>
topred (Rred "red_sizeof" (Eval (Vint (Int.repr (sizeof ge ty'))) ty) m E0)
| RV, Ealignof ty' ty =>
topred (Rred "red_alignof" (Eval (Vint (Int.repr (alignof ge ty'))) ty) m E0)
| RV, Eassign l1 r2 ty =>
match is_loc l1, is_val r2 with
| Some(b, ofs, ty1), Some(v2, ty2) =>
check type_eq ty1 ty;
do v <- sem_cast v2 ty2 ty1;
do w',t,m' <- do_assign_loc w ty1 m b ofs v;
topred (Rred "red_assign" (Eval v ty) m' t)
| _, _ =>
incontext2 (fun x => Eassign x r2 ty) (step_expr LV l1 m)
(fun x => Eassign l1 x ty) (step_expr RV r2 m)
end
| RV, Eassignop op l1 r2 tyres ty =>
match is_loc l1, is_val r2 with
| Some(b, ofs, ty1), Some(v2, ty2) =>
check type_eq ty1 ty;
do w',t,v1 <- do_deref_loc w ty1 m b ofs;
let r' := Eassign (Eloc b ofs ty1)
(Ebinop op (Eval v1 ty1) (Eval v2 ty2) tyres) ty1 in
topred (Rred "red_assignop" r' m t)
| _, _ =>
incontext2 (fun x => Eassignop op x r2 tyres ty) (step_expr LV l1 m)
(fun x => Eassignop op l1 x tyres ty) (step_expr RV r2 m)
end
| RV, Epostincr id l ty =>
match is_loc l with
| Some(b, ofs, ty1) =>
check type_eq ty1 ty;
do w',t, v1 <- do_deref_loc w ty m b ofs;
let op := match id with Incr => Oadd | Decr => Osub end in
let r' :=
Ecomma (Eassign (Eloc b ofs ty)
(Ebinop op (Eval v1 ty) (Eval (Vint Int.one) type_int32s) (incrdecr_type ty))
ty)
(Eval v1 ty) ty in
topred (Rred "red_postincr" r' m t)
| None =>
incontext (fun x => Epostincr id x ty) (step_expr LV l m)
end
| RV, Ecomma r1 r2 ty =>
match is_val r1 with
| Some _ =>
check type_eq (typeof r2) ty;
topred (Rred "red_comma" r2 m E0)
| None =>
incontext (fun x => Ecomma x r2 ty) (step_expr RV r1 m)
end
| RV, Eparen r1 tycast ty =>
match is_val r1 with
| Some (v1, ty1) =>
do v <- sem_cast v1 ty1 tycast;
topred (Rred "red_paren" (Eval v ty) m E0)
| None =>
incontext (fun x => Eparen x tycast ty) (step_expr RV r1 m)
end
| RV, Ecall r1 rargs ty =>
match is_val r1, is_val_list rargs with
| Some(vf, tyf), Some vtl =>
match classify_fun tyf with
| fun_case_f tyargs tyres cconv =>
do fd <- Genv.find_funct ge vf;
do vargs <- sem_cast_arguments vtl tyargs;
check type_eq (type_of_fundef fd) (Tfunction tyargs tyres cconv);
topred (Callred "red_call" fd vargs ty m)
| _ => stuck
end
| _, _ =>
incontext2 (fun x => Ecall x rargs ty) (step_expr RV r1 m)
(fun x => Ecall r1 x ty) (step_exprlist rargs m)
end
| RV, Ebuiltin ef tyargs rargs ty =>
match is_val_list rargs with
| Some vtl =>
do vargs <- sem_cast_arguments vtl tyargs;
match do_external ef w vargs m with
| None => stuck
| Some(w',t,v,m') => topred (Rred "red_builtin" (Eval v ty) m' t)
end
| _ =>
incontext (fun x => Ebuiltin ef tyargs x ty) (step_exprlist rargs m)
end
| _, _ => stuck
end
with step_exprlist (rl: exprlist) (m: mem): reducts exprlist :=
match rl with
| Enil =>
nil
| Econs r1 rs =>
incontext2 (fun x => Econs x rs) (step_expr RV r1 m)
(fun x => Econs r1 x) (step_exprlist rs m)
end.
(** Technical properties on safe expressions. *)
Inductive imm_safe_t: kind -> expr -> mem -> Prop :=
| imm_safe_t_val: forall v ty m,
imm_safe_t RV (Eval v ty) m
| imm_safe_t_loc: forall b ofs ty m,
imm_safe_t LV (Eloc b ofs ty) m
| imm_safe_t_lred: forall to C l m l' m',
lred ge e l m l' m' ->
context LV to C ->
imm_safe_t to (C l) m
| imm_safe_t_rred: forall to C r m t r' m' w',
rred ge r m t r' m' -> possible_trace w t w' ->
context RV to C ->
imm_safe_t to (C r) m
| imm_safe_t_callred: forall to C r m fd args ty,
callred ge r fd args ty ->
context RV to C ->
imm_safe_t to (C r) m.
Remark imm_safe_t_imm_safe:
forall k a m, imm_safe_t k a m -> imm_safe ge e k a m.
Proof.
induction 1.
constructor.
constructor.
eapply imm_safe_lred; eauto.
eapply imm_safe_rred; eauto.
eapply imm_safe_callred; eauto.
Qed.
Fixpoint exprlist_all_values (rl: exprlist) : Prop :=
match rl with
| Enil => True
| Econs (Eval v ty) rl' => exprlist_all_values rl'
| Econs _ _ => False
end.
Definition invert_expr_prop (a: expr) (m: mem) : Prop :=
match a with
| Eloc b ofs ty => False
| Evar x ty =>
exists b,
e!x = Some(b, ty)
\/ (e!x = None /\ Genv.find_symbol ge x = Some b)
| Ederef (Eval v ty1) ty =>
exists b, exists ofs, v = Vptr b ofs
| Efield (Eval v ty1) f ty =>
exists b, exists ofs, v = Vptr b ofs /\
match ty1 with
| Tstruct id _ => exists co delta, ge.(genv_cenv)!id = Some co /\ field_offset ge f (co_members co) = OK delta
| Tunion id _ => exists co, ge.(genv_cenv)!id = Some co
| _ => False
end
| Eval v ty => False
| Evalof (Eloc b ofs ty') ty =>
ty' = ty /\ exists t, exists v, exists w', deref_loc ge ty m b ofs t v /\ possible_trace w t w'
| Eunop op (Eval v1 ty1) ty =>
exists v, sem_unary_operation op v1 ty1 m = Some v
| Ebinop op (Eval v1 ty1) (Eval v2 ty2) ty =>
exists v, sem_binary_operation ge op v1 ty1 v2 ty2 m = Some v
| Ecast (Eval v1 ty1) ty =>
exists v, sem_cast v1 ty1 ty = Some v
| Eseqand (Eval v1 ty1) r2 ty =>
exists b, bool_val v1 ty1 m = Some b
| Eseqor (Eval v1 ty1) r2 ty =>
exists b, bool_val v1 ty1 m = Some b
| Econdition (Eval v1 ty1) r1 r2 ty =>
exists b, bool_val v1 ty1 m = Some b
| Eassign (Eloc b ofs ty1) (Eval v2 ty2) ty =>
exists v, exists m', exists t, exists w',
ty = ty1 /\ sem_cast v2 ty2 ty1 = Some v /\ assign_loc ge ty1 m b ofs v t m' /\ possible_trace w t w'
| Eassignop op (Eloc b ofs ty1) (Eval v2 ty2) tyres ty =>
exists t, exists v1, exists w',
ty = ty1 /\ deref_loc ge ty1 m b ofs t v1 /\ possible_trace w t w'
| Epostincr id (Eloc b ofs ty1) ty =>
exists t, exists v1, exists w',
ty = ty1 /\ deref_loc ge ty m b ofs t v1 /\ possible_trace w t w'
| Ecomma (Eval v ty1) r2 ty =>
typeof r2 = ty
| Eparen (Eval v1 ty1) tycast ty =>
exists v, sem_cast v1 ty1 tycast = Some v
| Ecall (Eval vf tyf) rargs ty =>
exprlist_all_values rargs ->
exists tyargs tyres cconv fd vl,
classify_fun tyf = fun_case_f tyargs tyres cconv
/\ Genv.find_funct ge vf = Some fd
/\ cast_arguments rargs tyargs vl
/\ type_of_fundef fd = Tfunction tyargs tyres cconv
| Ebuiltin ef tyargs rargs ty =>
exprlist_all_values rargs ->
exists vargs t vres m' w',
cast_arguments rargs tyargs vargs
/\ external_call ef ge vargs m t vres m'
/\ possible_trace w t w'
| _ => True
end.
Lemma lred_invert:
forall l m l' m', lred ge e l m l' m' -> invert_expr_prop l m.
Proof.
induction 1; red; auto.
exists b; auto.
exists b; auto.
exists b; exists ofs; auto.
exists b; exists ofs; split; auto. exists co, delta; auto.
exists b; exists ofs; split; auto. exists co; auto.
Qed.
Lemma rred_invert:
forall w' r m t r' m', rred ge r m t r' m' -> possible_trace w t w' -> invert_expr_prop r m.
Proof.
induction 1; intros; red; auto.
split; auto; exists t; exists v; exists w'; auto.
exists v; auto.
exists v; auto.
exists v; auto.
exists true; auto. exists false; auto.
exists true; auto. exists false; auto.
exists b; auto.
exists v; exists m'; exists t; exists w'; auto.
exists t; exists v1; exists w'; auto.
exists t; exists v1; exists w'; auto.
exists v; auto.
intros; exists vargs; exists t; exists vres; exists m'; exists w'; auto.
Qed.
Lemma callred_invert:
forall r fd args ty m,
callred ge r fd args ty ->
invert_expr_prop r m.
Proof.
intros. inv H. simpl.
intros. exists tyargs, tyres, cconv, fd, args; auto.
Qed.
Scheme context_ind2 := Minimality for context Sort Prop
with contextlist_ind2 := Minimality for contextlist Sort Prop.
Combined Scheme context_contextlist_ind from context_ind2, contextlist_ind2.
Lemma invert_expr_context:
(forall from to C, context from to C ->
forall a m,
invert_expr_prop a m ->
invert_expr_prop (C a) m)
/\(forall from C, contextlist from C ->
forall a m,
invert_expr_prop a m ->
~exprlist_all_values (C a)).
Proof.
apply context_contextlist_ind; intros; try (exploit H0; [eauto|intros]); simpl.
auto.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
auto.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct e1; auto; destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct e1; auto; destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct e1; auto; destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
destruct e1; auto. intros. elim (H0 a m); auto.
intros. elim (H0 a m); auto.
destruct (C a); auto; contradiction.
destruct (C a); auto; contradiction.
red; intros. destruct (C a); auto.
red; intros. destruct e1; auto. elim (H0 a m); auto.
Qed.
Lemma imm_safe_t_inv:
forall k a m,
imm_safe_t k a m ->
match a with
| Eloc _ _ _ => True
| Eval _ _ => True
| _ => invert_expr_prop a m
end.
Proof.
destruct invert_expr_context as [A B].
intros. inv H.
auto.
auto.
assert (invert_expr_prop (C l) m).
eapply A; eauto. eapply lred_invert; eauto.
red in H. destruct (C l); auto; contradiction.
assert (invert_expr_prop (C r) m).
eapply A; eauto. eapply rred_invert; eauto.
red in H. destruct (C r); auto; contradiction.
assert (invert_expr_prop (C r) m).
eapply A; eauto. eapply callred_invert; eauto.
red in H. destruct (C r); auto; contradiction.
Qed.
(** Soundness: if [step_expr] returns [Some ll], then every element
of [ll] is a reduct. *)
Lemma context_compose:
forall k2 k3 C2, context k2 k3 C2 ->
forall k1 C1, context k1 k2 C1 ->
context k1 k3 (fun x => C2(C1 x))
with contextlist_compose:
forall k2 C2, contextlist k2 C2 ->
forall k1 C1, context k1 k2 C1 ->
contextlist k1 (fun x => C2(C1 x)).
Proof.
induction 1; intros; try (constructor; eauto).
replace (fun x => C1 x) with C1. auto. apply extensionality; auto.
induction 1; intros; constructor; eauto.
Qed.
Hint Constructors context contextlist.
Hint Resolve context_compose contextlist_compose.
Definition reduction_ok (k: kind) (a: expr) (m: mem) (rd: reduction) : Prop :=
match k, rd with
| LV, Lred _ l' m' => lred ge e a m l' m'
| RV, Rred _ r' m' t => rred ge a m t r' m' /\ exists w', possible_trace w t w'
| RV, Callred _ fd args tyres m' => callred ge a fd args tyres /\ m' = m
| LV, Stuckred => ~imm_safe_t k a m
| RV, Stuckred => ~imm_safe_t k a m
| _, _ => False
end.
Definition reducts_ok (k: kind) (a: expr) (m: mem) (ll: reducts expr) : Prop :=
(forall C rd,
In (C, rd) ll ->
exists a', exists k', context k' k C /\ a = C a' /\ reduction_ok k' a' m rd)
/\ (ll = nil -> match k with LV => is_loc a <> None | RV => is_val a <> None end).
Definition list_reducts_ok (al: exprlist) (m: mem) (ll: reducts exprlist) : Prop :=
(forall C rd,
In (C, rd) ll ->
exists a', exists k', contextlist k' C /\ al = C a' /\ reduction_ok k' a' m rd)
/\ (ll = nil -> is_val_list al <> None).
Ltac monadInv :=
match goal with
| [ H: match ?x with Some _ => _ | None => None end = Some ?y |- _ ] =>
destruct x eqn:?; [monadInv|discriminate]
| [ H: match ?x with left _ => _ | right _ => None end = Some ?y |- _ ] =>
destruct x; [monadInv|discriminate]
| _ => idtac
end.
Lemma sem_cast_arguments_sound:
forall rargs vtl tyargs vargs,
is_val_list rargs = Some vtl ->
sem_cast_arguments vtl tyargs = Some vargs ->
cast_arguments rargs tyargs vargs.
Proof.
induction rargs; simpl; intros.
inv H. destruct tyargs; simpl in H0; inv H0. constructor.
monadInv. inv H. simpl in H0. destruct p as [v1 t1]. destruct tyargs; try congruence. monadInv.
inv H0. rewrite (is_val_inv _ _ _ Heqo). constructor. auto. eauto.
Qed.
Lemma sem_cast_arguments_complete:
forall al tyl vl,
cast_arguments al tyl vl ->
exists vtl, is_val_list al = Some vtl /\ sem_cast_arguments vtl tyl = Some vl.
Proof.
induction 1.
exists (@nil (val * type)); auto.
destruct IHcast_arguments as [vtl [A B]].
exists ((v, ty) :: vtl); simpl. rewrite A; rewrite B; rewrite H. auto.
Qed.
Lemma topred_ok:
forall k a m rd,
reduction_ok k a m rd ->
reducts_ok k a m (topred rd).
Proof.
intros. unfold topred; split; simpl; intros.
destruct H0; try contradiction. inv H0. exists a; exists k; auto.
congruence.
Qed.
Lemma stuck_ok:
forall k a m,
~imm_safe_t k a m ->
reducts_ok k a m stuck.
Proof.
intros. unfold stuck; split; simpl; intros.
destruct H0; try contradiction. inv H0. exists a; exists k; intuition. red. destruct k; auto.
congruence.
Qed.
Lemma wrong_kind_ok:
forall k a m,
k <> Cstrategy.expr_kind a ->
reducts_ok k a m stuck.
Proof.
intros. apply stuck_ok. red; intros. exploit Cstrategy.imm_safe_kind; eauto.
eapply imm_safe_t_imm_safe; eauto.
Qed.
Lemma not_invert_ok:
forall k a m,
match a with
| Eloc _ _ _ => False
| Eval _ _ => False
| _ => invert_expr_prop a m -> False
end ->
reducts_ok k a m stuck.
Proof.
intros. apply stuck_ok. red; intros.
exploit imm_safe_t_inv; eauto. destruct a; auto.
Qed.
Lemma incontext_ok:
forall k a m C res k' a',
reducts_ok k' a' m res ->
a = C a' ->
context k' k C ->
match k' with LV => is_loc a' = None | RV => is_val a' = None end ->
reducts_ok k a m (incontext C res).
Proof.
unfold reducts_ok, incontext; intros. destruct H. split; intros.
exploit list_in_map_inv; eauto. intros [[C1 rd1] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eapply context_compose; eauto. rewrite V; auto.
destruct res; simpl in H4; try congruence. destruct k'; intuition congruence.
Qed.
Lemma incontext2_ok:
forall k a m k1 a1 res1 k2 a2 res2 C1 C2,
reducts_ok k1 a1 m res1 ->
reducts_ok k2 a2 m res2 ->
a = C1 a1 -> a = C2 a2 ->
context k1 k C1 -> context k2 k C2 ->
match k1 with LV => is_loc a1 = None | RV => is_val a1 = None end
\/ match k2 with LV => is_loc a2 = None | RV => is_val a2 = None end ->
reducts_ok k a m (incontext2 C1 res1 C2 res2).
Proof.
unfold reducts_ok, incontext2, incontext; intros. destruct H; destruct H0; split; intros.
destruct (in_app_or _ _ _ H8).
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eapply context_compose; eauto. rewrite V; auto.
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H0; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eapply context_compose; eauto. rewrite H2; rewrite V; auto.
destruct res1; simpl in H8; try congruence. destruct res2; simpl in H8; try congruence.
destruct H5. destruct k1; intuition congruence. destruct k2; intuition congruence.
Qed.
Lemma incontext_list_ok:
forall ef tyargs al ty m res,
list_reducts_ok al m res ->
is_val_list al = None ->
reducts_ok RV (Ebuiltin ef tyargs al ty) m
(incontext (fun x => Ebuiltin ef tyargs x ty) res).
Proof.
unfold reducts_ok, incontext; intros. destruct H. split; intros.
exploit list_in_map_inv; eauto. intros [[C1 rd1] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
destruct res; simpl in H2. elim H1; auto. congruence.
Qed.
Lemma incontext2_list_ok:
forall a1 a2 ty m res1 res2,
reducts_ok RV a1 m res1 ->
list_reducts_ok a2 m res2 ->
is_val a1 = None \/ is_val_list a2 = None ->
reducts_ok RV (Ecall a1 a2 ty) m
(incontext2 (fun x => Ecall x a2 ty) res1
(fun x => Ecall a1 x ty) res2).
Proof.
unfold reducts_ok, incontext2, incontext; intros. destruct H; destruct H0; split; intros.
destruct (in_app_or _ _ _ H4).
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H0; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
destruct res1; simpl in H4; try congruence. destruct res2; simpl in H4; try congruence.
tauto.
Qed.
Lemma incontext2_list_ok':
forall a1 a2 m res1 res2,
reducts_ok RV a1 m res1 ->
list_reducts_ok a2 m res2 ->
list_reducts_ok (Econs a1 a2) m
(incontext2 (fun x => Econs x a2) res1
(fun x => Econs a1 x) res2).
Proof.
unfold reducts_ok, list_reducts_ok, incontext2, incontext; intros.
destruct H; destruct H0. split; intros.
destruct (in_app_or _ _ _ H3).
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
exploit list_in_map_inv; eauto. intros [[C' rd'] [P Q]]. inv P.
exploit H0; eauto. intros [a'' [k'' [U [V W]]]].
exists a''; exists k''. split. eauto. rewrite V; auto.
destruct res1; simpl in H3; try congruence. destruct res2; simpl in H3; try congruence.
simpl. destruct (is_val a1). destruct (is_val_list a2). congruence. intuition congruence. intuition congruence.
Qed.
Lemma is_val_list_all_values:
forall al vtl, is_val_list al = Some vtl -> exprlist_all_values al.
Proof.
induction al; simpl; intros. auto.
destruct (is_val r1) as [[v ty]|] eqn:?; try discriminate.
destruct (is_val_list al) as [vtl'|] eqn:?; try discriminate.
rewrite (is_val_inv _ _ _ Heqo). eauto.
Qed.
Ltac myinv :=
match goal with
| [ H: False |- _ ] => destruct H
| [ H: _ /\ _ |- _ ] => destruct H; myinv
| [ H: exists _, _ |- _ ] => destruct H; myinv
| _ => idtac
end.
Theorem step_expr_sound:
forall a k m, reducts_ok k a m (step_expr k a m)
with step_exprlist_sound:
forall al m, list_reducts_ok al m (step_exprlist al m).
Proof with (try (apply not_invert_ok; simpl; intro; myinv; intuition congruence; fail)).
induction a; intros; simpl; destruct k; try (apply wrong_kind_ok; simpl; congruence).
(* Eval *)
split; intros. tauto. simpl; congruence.
(* Evar *)
destruct (e!x) as [[b ty']|] eqn:?.
destruct (type_eq ty ty')...
subst. apply topred_ok; auto. apply red_var_local; auto.
destruct (Genv.find_symbol ge x) as [b|] eqn:?...
apply topred_ok; auto. apply red_var_global; auto.
(* Efield *)
destruct (is_val a) as [[v ty'] | ] eqn:?.
rewrite (is_val_inv _ _ _ Heqo).
destruct v...
destruct ty'...
(* top struct *)
destruct (ge.(genv_cenv)!i0) as [co|] eqn:?...
destruct (field_offset ge f (co_members co)) as [delta|] eqn:?...
apply topred_ok; auto. eapply red_field_struct; eauto.
(* top union *)
destruct (ge.(genv_cenv)!i0) as [co|] eqn:?...
apply topred_ok; auto. eapply red_field_union; eauto.
(* in depth *)
eapply incontext_ok; eauto.
(* Evalof *)
destruct (is_loc a) as [[[b ofs] ty'] | ] eqn:?. rewrite (is_loc_inv _ _ _ _ Heqo).
(* top *)
destruct (type_eq ty ty')... subst ty'.
destruct (do_deref_loc w ty m b ofs) as [[[w' t] v] | ] eqn:?.
exploit do_deref_loc_sound; eauto. intros [A B].
apply topred_ok; auto. red. split. apply red_rvalof; auto. exists w'; auto.
apply not_invert_ok; simpl; intros; myinv. exploit do_deref_loc_complete; eauto. congruence.
(* depth *)
eapply incontext_ok; eauto.
(* Ederef *)
destruct (is_val a) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct v... apply topred_ok; auto. apply red_deref; auto.
(* depth *)
eapply incontext_ok; eauto.
(* Eaddrof *)
destruct (is_loc a) as [[[b ofs] ty'] | ] eqn:?. rewrite (is_loc_inv _ _ _ _ Heqo).
(* top *)
apply topred_ok; auto. split. apply red_addrof; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* unop *)
destruct (is_val a) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (sem_unary_operation op v ty' m) as [v'|] eqn:?...
apply topred_ok; auto. split. apply red_unop; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* binop *)
destruct (is_val a1) as [[v1 ty1] | ] eqn:?.
destruct (is_val a2) as [[v2 ty2] | ] eqn:?.
rewrite (is_val_inv _ _ _ Heqo). rewrite (is_val_inv _ _ _ Heqo0).
(* top *)
destruct (sem_binary_operation ge op v1 ty1 v2 ty2 m) as [v|] eqn:?...
apply topred_ok; auto. split. apply red_binop; auto. exists w; constructor.
(* depth *)
eapply incontext2_ok; eauto.
eapply incontext2_ok; eauto.
(* cast *)
destruct (is_val a) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (sem_cast v ty' ty) as [v'|] eqn:?...
apply topred_ok; auto. split. apply red_cast; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* seqand *)
destruct (is_val a1) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (bool_val v ty' m) as [v'|] eqn:?... destruct v'.
apply topred_ok; auto. split. eapply red_seqand_true; eauto. exists w; constructor.
apply topred_ok; auto. split. eapply red_seqand_false; eauto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* seqor *)
destruct (is_val a1) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (bool_val v ty' m) as [v'|] eqn:?... destruct v'.
apply topred_ok; auto. split. eapply red_seqor_true; eauto. exists w; constructor.
apply topred_ok; auto. split. eapply red_seqor_false; eauto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* condition *)
destruct (is_val a1) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (bool_val v ty' m) as [v'|] eqn:?...
apply topred_ok; auto. split. eapply red_condition; eauto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* sizeof *)
apply topred_ok; auto. split. apply red_sizeof. exists w; constructor.
(* alignof *)
apply topred_ok; auto. split. apply red_alignof. exists w; constructor.
(* assign *)
destruct (is_loc a1) as [[[b ofs] ty1] | ] eqn:?.
destruct (is_val a2) as [[v2 ty2] | ] eqn:?.
rewrite (is_loc_inv _ _ _ _ Heqo). rewrite (is_val_inv _ _ _ Heqo0).
(* top *)
destruct (type_eq ty1 ty)... subst ty1.
destruct (sem_cast v2 ty2 ty) as [v|] eqn:?...
destruct (do_assign_loc w ty m b ofs v) as [[[w' t] m']|] eqn:?.
exploit do_assign_loc_sound; eauto. intros [P Q].
apply topred_ok; auto. split. apply red_assign; auto. exists w'; auto.
apply not_invert_ok; simpl; intros; myinv. exploit do_assign_loc_complete; eauto. congruence.
(* depth *)
eapply incontext2_ok; eauto.
eapply incontext2_ok; eauto.
(* assignop *)
destruct (is_loc a1) as [[[b ofs] ty1] | ] eqn:?.
destruct (is_val a2) as [[v2 ty2] | ] eqn:?.
rewrite (is_loc_inv _ _ _ _ Heqo). rewrite (is_val_inv _ _ _ Heqo0).
(* top *)
destruct (type_eq ty1 ty)... subst ty1.
destruct (do_deref_loc w ty m b ofs) as [[[w' t] v] | ] eqn:?.
exploit do_deref_loc_sound; eauto. intros [A B].
apply topred_ok; auto. red. split. apply red_assignop; auto. exists w'; auto.
apply not_invert_ok; simpl; intros; myinv. exploit do_deref_loc_complete; eauto. congruence.
(* depth *)
eapply incontext2_ok; eauto.
eapply incontext2_ok; eauto.
(* postincr *)
destruct (is_loc a) as [[[b ofs] ty'] | ] eqn:?. rewrite (is_loc_inv _ _ _ _ Heqo).
(* top *)
destruct (type_eq ty' ty)... subst ty'.
destruct (do_deref_loc w ty m b ofs) as [[[w' t] v] | ] eqn:?.
exploit do_deref_loc_sound; eauto. intros [A B].
apply topred_ok; auto. red. split. apply red_postincr; auto. exists w'; auto.
apply not_invert_ok; simpl; intros; myinv. exploit do_deref_loc_complete; eauto. congruence.
(* depth *)
eapply incontext_ok; eauto.
(* comma *)
destruct (is_val a1) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (type_eq (typeof a2) ty)... subst ty.
apply topred_ok; auto. split. apply red_comma; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
(* call *)
destruct (is_val a) as [[vf tyf] | ] eqn:?.
destruct (is_val_list rargs) as [vtl | ] eqn:?.
rewrite (is_val_inv _ _ _ Heqo). exploit is_val_list_all_values; eauto. intros ALLVAL.
(* top *)
destruct (classify_fun tyf) as [tyargs tyres cconv|] eqn:?...
destruct (Genv.find_funct ge vf) as [fd|] eqn:?...
destruct (sem_cast_arguments vtl tyargs) as [vargs|] eqn:?...
destruct (type_eq (type_of_fundef fd) (Tfunction tyargs tyres cconv))...
apply topred_ok; auto. red. split; auto. eapply red_call; eauto.
eapply sem_cast_arguments_sound; eauto.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv. congruence.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv.
exploit sem_cast_arguments_complete; eauto. intros [vtl' [P Q]]. congruence.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv. congruence.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv. congruence.
(* depth *)
eapply incontext2_list_ok; eauto.
eapply incontext2_list_ok; eauto.
(* builtin *)
destruct (is_val_list rargs) as [vtl | ] eqn:?.
exploit is_val_list_all_values; eauto. intros ALLVAL.
(* top *)
destruct (sem_cast_arguments vtl tyargs) as [vargs|] eqn:?...
destruct (do_external ef w vargs m) as [[[[? ?] v] m'] | ] eqn:?...
exploit do_ef_external_sound; eauto. intros [EC PT].
apply topred_ok; auto. red. split; auto. eapply red_builtin; eauto.
eapply sem_cast_arguments_sound; eauto.
exists w0; auto.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv.
assert (x = vargs).
exploit sem_cast_arguments_complete; eauto. intros [vtl' [A B]]. congruence.
subst x. exploit do_ef_external_complete; eauto. congruence.
apply not_invert_ok; simpl; intros; myinv. specialize (H ALLVAL). myinv.
exploit sem_cast_arguments_complete; eauto. intros [vtl' [A B]]. congruence.
(* depth *)
eapply incontext_list_ok; eauto.
(* loc *)
split; intros. tauto. simpl; congruence.
(* paren *)
destruct (is_val a) as [[v ty'] | ] eqn:?. rewrite (is_val_inv _ _ _ Heqo).
(* top *)
destruct (sem_cast v ty' tycast) as [v'|] eqn:?...
apply topred_ok; auto. split. apply red_paren; auto. exists w; constructor.
(* depth *)
eapply incontext_ok; eauto.
induction al; simpl; intros.
(* nil *)
split; intros. tauto. simpl; congruence.
(* cons *)
eapply incontext2_list_ok'; eauto.
Qed.
Lemma step_exprlist_val_list:
forall m al, is_val_list al <> None -> step_exprlist al m = nil.
Proof.
induction al; simpl; intros.
auto.
destruct (is_val r1) as [[v1 ty1]|] eqn:?; try congruence.
destruct (is_val_list al) eqn:?; try congruence.
rewrite (is_val_inv _ _ _ Heqo).
rewrite IHal. auto. congruence.
Qed.
(** Completeness part 1: [step_expr] contains all possible non-error reducts. *)
Lemma lred_topred:
forall l1 m1 l2 m2,
lred ge e l1 m1 l2 m2 ->
exists rule, step_expr LV l1 m1 = topred (Lred rule l2 m2).
Proof.
induction 1; simpl.
(* var local *)
rewrite H. rewrite dec_eq_true. econstructor; eauto.
(* var global *)
rewrite H; rewrite H0. econstructor; eauto.
(* deref *)
econstructor; eauto.
(* field struct *)
rewrite H, H0; econstructor; eauto.
(* field union *)
rewrite H; econstructor; eauto.
Qed.
Lemma rred_topred:
forall w' r1 m1 t r2 m2,
rred ge r1 m1 t r2 m2 -> possible_trace w t w' ->
exists rule, step_expr RV r1 m1 = topred (Rred rule r2 m2 t).
Proof.
induction 1; simpl; intros.
(* valof *)
rewrite dec_eq_true.
rewrite (do_deref_loc_complete _ _ _ _ _ _ _ _ H H0). econstructor; eauto.
(* addrof *)
inv H. econstructor; eauto.
(* unop *)
inv H0. rewrite H; econstructor; eauto.
(* binop *)
inv H0. rewrite H; econstructor; eauto.
(* cast *)
inv H0. rewrite H; econstructor; eauto.
(* seqand *)
inv H0. rewrite H; econstructor; eauto.
inv H0. rewrite H; econstructor; eauto.
(* seqor *)
inv H0. rewrite H; econstructor; eauto.
inv H0. rewrite H; econstructor; eauto.
(* condition *)
inv H0. rewrite H; econstructor; eauto.
(* sizeof *)
inv H. econstructor; eauto.
(* alignof *)
inv H. econstructor; eauto.
(* assign *)
rewrite dec_eq_true. rewrite H. rewrite (do_assign_loc_complete _ _ _ _ _ _ _ _ _ H0 H1).
econstructor; eauto.
(* assignop *)
rewrite dec_eq_true. rewrite (do_deref_loc_complete _ _ _ _ _ _ _ _ H H0).
econstructor; eauto.
(* postincr *)
rewrite dec_eq_true. subst. rewrite (do_deref_loc_complete _ _ _ _ _ _ _ _ H H1).
econstructor; eauto.
(* comma *)
inv H0. rewrite dec_eq_true. econstructor; eauto.
(* paren *)
inv H0. rewrite H; econstructor; eauto.
(* builtin *)
exploit sem_cast_arguments_complete; eauto. intros [vtl [A B]].
exploit do_ef_external_complete; eauto. intros C.
rewrite A. rewrite B. rewrite C. econstructor; eauto.
Qed.
Lemma callred_topred:
forall a fd args ty m,
callred ge a fd args ty ->
exists rule, step_expr RV a m = topred (Callred rule fd args ty m).
Proof.
induction 1; simpl.
rewrite H2. exploit sem_cast_arguments_complete; eauto. intros [vtl [A B]].
rewrite A; rewrite H; rewrite B; rewrite H1; rewrite dec_eq_true. econstructor; eauto.
Qed.
Definition reducts_incl {A B: Type} (C: A -> B) (res1: reducts A) (res2: reducts B) : Prop :=
forall C1 rd, In (C1, rd) res1 -> In ((fun x => C(C1 x)), rd) res2.
Lemma reducts_incl_trans:
forall (A1 A2: Type) (C: A1 -> A2) res1 res2, reducts_incl C res1 res2 ->
forall (A3: Type) (C': A2 -> A3) res3,
reducts_incl C' res2 res3 ->
reducts_incl (fun x => C'(C x)) res1 res3.
Proof.
unfold reducts_incl; intros. auto.
Qed.
Lemma reducts_incl_nil:
forall (A B: Type) (C: A -> B) res,
reducts_incl C nil res.
Proof.
intros; red. intros; contradiction.
Qed.
Lemma reducts_incl_val:
forall (A: Type) a m v ty (C: expr -> A) res,
is_val a = Some(v, ty) -> reducts_incl C (step_expr RV a m) res.
Proof.
intros. rewrite (is_val_inv _ _ _ H). apply reducts_incl_nil.
Qed.
Lemma reducts_incl_loc:
forall (A: Type) a m b ofs ty (C: expr -> A) res,
is_loc a = Some(b, ofs, ty) -> reducts_incl C (step_expr LV a m) res.
Proof.
intros. rewrite (is_loc_inv _ _ _ _ H). apply reducts_incl_nil.
Qed.
Lemma reducts_incl_listval:
forall (A: Type) a m vtl (C: exprlist -> A) res,
is_val_list a = Some vtl -> reducts_incl C (step_exprlist a m) res.
Proof.
intros. rewrite step_exprlist_val_list. apply reducts_incl_nil. congruence.
Qed.
Lemma reducts_incl_incontext:
forall (A B: Type) (C: A -> B) res,
reducts_incl C res (incontext C res).
Proof.
unfold reducts_incl, incontext. intros.
set (f := fun z : (expr -> A) * reduction => (fun x : expr => C (fst z x), snd z)).
change (In (f (C1, rd)) (map f res)). apply in_map. auto.
Qed.
Lemma reducts_incl_incontext2_left:
forall (A1 A2 B: Type) (C1: A1 -> B) res1 (C2: A2 -> B) res2,
reducts_incl C1 res1 (incontext2 C1 res1 C2 res2).
Proof.
unfold reducts_incl, incontext2, incontext. intros.
rewrite in_app_iff. left.
set (f := fun z : (expr -> A1) * reduction => (fun x : expr => C1 (fst z x), snd z)).
change (In (f (C0, rd)) (map f res1)). apply in_map; auto.
Qed.
Lemma reducts_incl_incontext2_right:
forall (A1 A2 B: Type) (C1: A1 -> B) res1 (C2: A2 -> B) res2,
reducts_incl C2 res2 (incontext2 C1 res1 C2 res2).
Proof.
unfold reducts_incl, incontext2, incontext. intros.
rewrite in_app_iff. right.
set (f := fun z : (expr -> A2) * reduction => (fun x : expr => C2 (fst z x), snd z)).
change (In (f (C0, rd)) (map f res2)). apply in_map; auto.
Qed.
Hint Resolve reducts_incl_val reducts_incl_loc reducts_incl_listval
reducts_incl_incontext reducts_incl_incontext2_left reducts_incl_incontext2_right.
Lemma step_expr_context:
forall from to C, context from to C ->
forall a m, reducts_incl C (step_expr from a m) (step_expr to (C a) m)
with step_exprlist_context:
forall from C, contextlist from C ->
forall a m, reducts_incl C (step_expr from a m) (step_exprlist (C a) m).
Proof.
induction 1; simpl; intros.
(* top *)
red. destruct (step_expr k a m); auto.
try (* no eta in 8.3 *)
(intros;
replace (fun x => C1 x) with C1 by (apply extensionality; auto);
auto).
(* deref *)
eapply reducts_incl_trans with (C' := fun x => Ederef x ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* field *)
eapply reducts_incl_trans with (C' := fun x => Efield x f ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* valof *)
eapply reducts_incl_trans with (C' := fun x => Evalof x ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* addrof *)
eapply reducts_incl_trans with (C' := fun x => Eaddrof x ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* unop *)
eapply reducts_incl_trans with (C' := fun x => Eunop op x ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* binop left *)
eapply reducts_incl_trans with (C' := fun x => Ebinop op x e2 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* binop right *)
eapply reducts_incl_trans with (C' := fun x => Ebinop op e1 x ty); eauto.
destruct (is_val e1) as [[v1 ty1]|] eqn:?; eauto.
destruct (is_val (C a)) as [[v2 ty2]|] eqn:?; eauto.
(* cast *)
eapply reducts_incl_trans with (C' := fun x => Ecast x ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* seqand *)
eapply reducts_incl_trans with (C' := fun x => Eseqand x r2 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* seqor *)
eapply reducts_incl_trans with (C' := fun x => Eseqor x r2 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* condition *)
eapply reducts_incl_trans with (C' := fun x => Econdition x r2 r3 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* assign left *)
eapply reducts_incl_trans with (C' := fun x => Eassign x e2 ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* assign right *)
eapply reducts_incl_trans with (C' := fun x => Eassign e1 x ty); eauto.
destruct (is_loc e1) as [[[b ofs] ty1]|] eqn:?; eauto.
destruct (is_val (C a)) as [[v2 ty2]|] eqn:?; eauto.
(* assignop left *)
eapply reducts_incl_trans with (C' := fun x => Eassignop op x e2 tyres ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* assignop right *)
eapply reducts_incl_trans with (C' := fun x => Eassignop op e1 x tyres ty); eauto.
destruct (is_loc e1) as [[[b ofs] ty1]|] eqn:?; eauto.
destruct (is_val (C a)) as [[v2 ty2]|] eqn:?; eauto.
(* postincr *)
eapply reducts_incl_trans with (C' := fun x => Epostincr id x ty); eauto.
destruct (is_loc (C a)) as [[[b ofs] ty']|] eqn:?; eauto.
(* call left *)
eapply reducts_incl_trans with (C' := fun x => Ecall x el ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* call right *)
eapply reducts_incl_trans with (C' := fun x => Ecall e1 x ty). apply step_exprlist_context. auto.
destruct (is_val e1) as [[v1 ty1]|] eqn:?; eauto.
destruct (is_val_list (C a)) as [vl|] eqn:?; eauto.
(* builtin *)
eapply reducts_incl_trans with (C' := fun x => Ebuiltin ef tyargs x ty). apply step_exprlist_context. auto.
destruct (is_val_list (C a)) as [vl|] eqn:?; eauto.
(* comma *)
eapply reducts_incl_trans with (C' := fun x => Ecomma x e2 ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
(* paren *)
eapply reducts_incl_trans with (C' := fun x => Eparen x tycast ty); eauto.
destruct (is_val (C a)) as [[v ty']|] eqn:?; eauto.
induction 1; simpl; intros.
(* cons left *)
eapply reducts_incl_trans with (C' := fun x => Econs x el).
apply step_expr_context; eauto. eauto.
(* binop right *)
eapply reducts_incl_trans with (C' := fun x => Econs e1 x).
apply step_exprlist_context; eauto. eauto.
Qed.
(** Completeness part 2: if we can reduce to [Stuckstate], [step_expr]
contains at least one [Stuckred] reduction. *)
Lemma not_stuckred_imm_safe:
forall m a k,
(forall C, ~In (C, Stuckred) (step_expr k a m)) -> imm_safe_t k a m.
Proof.
intros. generalize (step_expr_sound a k m). intros [A B].
destruct (step_expr k a m) as [|[C rd] res] eqn:?.
specialize (B (refl_equal _)). destruct k.
destruct a; simpl in B; try congruence. constructor.
destruct a; simpl in B; try congruence. constructor.
assert (NOTSTUCK: rd <> Stuckred).
red; intros. elim (H C); subst rd; auto with coqlib.
exploit A. eauto with coqlib. intros [a' [k' [P [Q R]]]].
destruct k'; destruct rd; simpl in R; intuition.
subst a. eapply imm_safe_t_lred; eauto.
subst a. destruct H1 as [w' PT]. eapply imm_safe_t_rred; eauto.
subst. eapply imm_safe_t_callred; eauto.
Qed.
Lemma not_imm_safe_stuck_red:
forall m a k C,
context k RV C ->
~imm_safe_t k a m ->
exists C', In (C', Stuckred) (step_expr RV (C a) m).
Proof.
intros.
assert (exists C', In (C', Stuckred) (step_expr k a m)).
destruct (classic (exists C', In (C', Stuckred) (step_expr k a m))); auto.
elim H0. apply not_stuckred_imm_safe. apply not_ex_all_not. auto.
destruct H1 as [C' IN].
specialize (step_expr_context _ _ _ H a m). unfold reducts_incl.
intro.
exists (fun x => (C (C' x))). apply H1; auto.
Qed.
(** Connections between [imm_safe_t] and [imm_safe] *)
Lemma imm_safe_imm_safe_t:
forall k a m,
imm_safe ge e k a m ->
imm_safe_t k a m \/
exists C, exists a1, exists t, exists a1', exists m',
context RV k C /\ a = C a1 /\ rred ge a1 m t a1' m' /\ forall w', ~possible_trace w t w'.
Proof.
intros. inv H.
left. apply imm_safe_t_val.
left. apply imm_safe_t_loc.
left. eapply imm_safe_t_lred; eauto.
destruct (classic (exists w', possible_trace w t w')) as [[w' A] | A].
left. eapply imm_safe_t_rred; eauto.
right. exists C; exists e0; exists t; exists e'; exists m'; intuition. apply A; exists w'; auto.
left. eapply imm_safe_t_callred; eauto.
Qed.
(** A state can "crash the world" if it can make an observable transition
whose trace is not accepted by the external world. *)
Definition can_crash_world (w: world) (S: state) : Prop :=
exists t, exists S', Csem.step ge S t S' /\ forall w', ~possible_trace w t w'.
Theorem not_imm_safe_t:
forall K C a m f k,
context K RV C ->
~imm_safe_t K a m ->
Csem.step ge (ExprState f (C a) k e m) E0 Stuckstate \/ can_crash_world w (ExprState f (C a) k e m).
Proof.
intros. destruct (classic (imm_safe ge e K a m)).
exploit imm_safe_imm_safe_t; eauto.
intros [A | [C1 [a1 [t [a1' [m' [A [B [D E]]]]]]]]]. contradiction.
right. red. exists t; econstructor; split; auto.
left. rewrite B. eapply step_rred with (C := fun x => C(C1 x)). eauto. eauto.
left. left. eapply step_stuck; eauto.
Qed.
End EXPRS.
(** * Transitions over states. *)
Fixpoint do_alloc_variables (e: env) (m: mem) (l: list (ident * type)) {struct l} : env * mem :=
match l with
| nil => (e,m)
| (id, ty) :: l' =>
let (m1,b1) := Mem.alloc m 0 (sizeof ge ty) in
do_alloc_variables (PTree.set id (b1, ty) e) m1 l'
end.
Lemma do_alloc_variables_sound:
forall l e m, alloc_variables ge e m l (fst (do_alloc_variables e m l)) (snd (do_alloc_variables e m l)).
Proof.
induction l; intros; simpl.
constructor.
destruct a as [id ty]. destruct (Mem.alloc m 0 (sizeof ge ty)) as [m1 b1] eqn:?; simpl.
econstructor; eauto.
Qed.
Lemma do_alloc_variables_complete:
forall e1 m1 l e2 m2, alloc_variables ge e1 m1 l e2 m2 ->
do_alloc_variables e1 m1 l = (e2, m2).
Proof.
induction 1; simpl.
auto.
rewrite H; rewrite IHalloc_variables; auto.
Qed.
Function sem_bind_parameters (w: world) (e: env) (m: mem) (l: list (ident * type)) (lv: list val)
{struct l} : option mem :=
match l, lv with
| nil, nil => Some m
| (id, ty) :: params, v1::lv =>
match PTree.get id e with
| Some (b, ty') =>
check (type_eq ty ty');
do w', t, m1 <- do_assign_loc w ty m b Int.zero v1;
match t with nil => sem_bind_parameters w e m1 params lv | _ => None end
| None => None
end
| _, _ => None
end.
Lemma sem_bind_parameters_sound : forall w e m l lv m',
sem_bind_parameters w e m l lv = Some m' ->
bind_parameters ge e m l lv m'.
Proof.
intros; functional induction (sem_bind_parameters w e m l lv); try discriminate.
inversion H; constructor; auto.
exploit do_assign_loc_sound; eauto. intros [A B]. econstructor; eauto.
Qed.
Lemma sem_bind_parameters_complete : forall w e m l lv m',
bind_parameters ge e m l lv m' ->
sem_bind_parameters w e m l lv = Some m'.
Proof.
induction 1; simpl; auto.
rewrite H. rewrite dec_eq_true.
assert (possible_trace w E0 w) by constructor.
rewrite (do_assign_loc_complete _ _ _ _ _ _ _ _ _ H0 H2).
simpl. auto.
Qed.
Inductive transition : Type := TR (rule: string) (t: trace) (S': state).
Definition expr_final_state (f: function) (k: cont) (e: env) (C_rd: (expr -> expr) * reduction) :=
match snd C_rd with
| Lred rule a m => TR rule E0 (ExprState f (fst C_rd a) k e m)
| Rred rule a m t => TR rule t (ExprState f (fst C_rd a) k e m)
| Callred rule fd vargs ty m => TR rule E0 (Callstate fd vargs (Kcall f e (fst C_rd) ty k) m)
| Stuckred => TR "step_stuck" E0 Stuckstate
end.
Local Open Scope list_monad_scope.
Definition ret (rule: string) (S: state) : list transition :=
TR rule E0 S :: nil.
Definition do_step (w: world) (s: state) : list transition :=
match s with
| ExprState f a k e m =>
match is_val a with
| Some(v, ty) =>
match k with
| Kdo k => ret "step_do_2" (State f Sskip k e m )
| Kifthenelse s1 s2 k =>
do b <- bool_val v ty m;
ret "step_ifthenelse_2" (State f (if b then s1 else s2) k e m)
| Kwhile1 x s k =>
do b <- bool_val v ty m;
if b
then ret "step_while_true" (State f s (Kwhile2 x s k) e m)
else ret "step_while_false" (State f Sskip k e m)
| Kdowhile2 x s k =>
do b <- bool_val v ty m;
if b
then ret "step_dowhile_true" (State f (Sdowhile x s) k e m)
else ret "step_dowhile_false" (State f Sskip k e m)
| Kfor2 a2 a3 s k =>
do b <- bool_val v ty m;
if b
then ret "step_for_true" (State f s (Kfor3 a2 a3 s k) e m)
else ret "step_for_false" (State f Sskip k e m)
| Kreturn k =>
do v' <- sem_cast v ty f.(fn_return);
do m' <- Mem.free_list m (blocks_of_env ge e);
ret "step_return_2" (Returnstate v' (call_cont k) m')
| Kswitch1 sl k =>
do n <- sem_switch_arg v ty;
ret "step_expr_switch" (State f (seq_of_labeled_statement (select_switch n sl)) (Kswitch2 k) e m)
| _ => nil
end
| None =>
map (expr_final_state f k e) (step_expr e w RV a m)
end
| State f (Sdo x) k e m =>
ret "step_do_1" (ExprState f x (Kdo k) e m)
| State f (Ssequence s1 s2) k e m =>
ret "step_seq" (State f s1 (Kseq s2 k) e m)
| State f Sskip (Kseq s k) e m =>
ret "step_skip_seq" (State f s k e m)
| State f Scontinue (Kseq s k) e m =>
ret "step_continue_seq" (State f Scontinue k e m)
| State f Sbreak (Kseq s k) e m =>
ret "step_break_seq" (State f Sbreak k e m)
| State f (Sifthenelse a s1 s2) k e m =>
ret "step_ifthenelse_1" (ExprState f a (Kifthenelse s1 s2 k) e m)
| State f (Swhile x s) k e m =>
ret "step_while" (ExprState f x (Kwhile1 x s k) e m)
| State f (Sskip|Scontinue) (Kwhile2 x s k) e m =>
ret "step_skip_or_continue_while" (State f (Swhile x s) k e m)
| State f Sbreak (Kwhile2 x s k) e m =>
ret "step_break_while" (State f Sskip k e m)
| State f (Sdowhile a s) k e m =>
ret "step_dowhile" (State f s (Kdowhile1 a s k) e m)
| State f (Sskip|Scontinue) (Kdowhile1 x s k) e m =>
ret "step_skip_or_continue_dowhile" (ExprState f x (Kdowhile2 x s k) e m)
| State f Sbreak (Kdowhile1 x s k) e m =>
ret "step_break_dowhile" (State f Sskip k e m)
| State f (Sfor a1 a2 a3 s) k e m =>
if is_skip a1
then ret "step_for" (ExprState f a2 (Kfor2 a2 a3 s k) e m)
else ret "step_for_start" (State f a1 (Kseq (Sfor Sskip a2 a3 s) k) e m)
| State f (Sskip|Scontinue) (Kfor3 a2 a3 s k) e m =>
ret "step_skip_or_continue_for3" (State f a3 (Kfor4 a2 a3 s k) e m)
| State f Sbreak (Kfor3 a2 a3 s k) e m =>
ret "step_break_for3" (State f Sskip k e m)
| State f Sskip (Kfor4 a2 a3 s k) e m =>
ret "step_skip_for4" (State f (Sfor Sskip a2 a3 s) k e m)
| State f (Sreturn None) k e m =>
do m' <- Mem.free_list m (blocks_of_env ge e);
ret "step_return_0" (Returnstate Vundef (call_cont k) m')
| State f (Sreturn (Some x)) k e m =>
ret "step_return_1" (ExprState f x (Kreturn k) e m)
| State f Sskip ((Kstop | Kcall _ _ _ _ _) as k) e m =>
do m' <- Mem.free_list m (blocks_of_env ge e);
ret "step_skip_call" (Returnstate Vundef k m')
| State f (Sswitch x sl) k e m =>
ret "step_switch" (ExprState f x (Kswitch1 sl k) e m)
| State f (Sskip|Sbreak) (Kswitch2 k) e m =>
ret "step_skip_break_switch" (State f Sskip k e m)
| State f Scontinue (Kswitch2 k) e m =>
ret "step_continue_switch" (State f Scontinue k e m)
| State f (Slabel lbl s) k e m =>
ret "step_label" (State f s k e m)
| State f (Sgoto lbl) k e m =>
match find_label lbl f.(fn_body) (call_cont k) with
| Some(s', k') => ret "step_goto" (State f s' k' e m)
| None => nil
end
| Callstate (Internal f) vargs k m =>
check (list_norepet_dec ident_eq (var_names (fn_params f) ++ var_names (fn_vars f)));
let (e,m1) := do_alloc_variables empty_env m (f.(fn_params) ++ f.(fn_vars)) in
do m2 <- sem_bind_parameters w e m1 f.(fn_params) vargs;
ret "step_internal_function" (State f f.(fn_body) k e m2)
| Callstate (External ef _ _ _) vargs k m =>
match do_external ef w vargs m with
| None => nil
| Some(w',t,v,m') => TR "step_external_function" t (Returnstate v k m') :: nil
end
| Returnstate v (Kcall f e C ty k) m =>
ret "step_returnstate" (ExprState f (C (Eval v ty)) k e m)
| _ => nil
end.
Ltac myinv :=
match goal with
| [ |- In _ nil -> _ ] => intro X; elim X
| [ |- In _ (ret _ _) -> _ ] =>
intro X; elim X; clear X;
[intro EQ; unfold ret in EQ; inv EQ; myinv | myinv]
| [ |- In _ (_ :: nil) -> _ ] =>
intro X; elim X; clear X; [intro EQ; inv EQ; myinv | myinv]
| [ |- In _ (match ?x with Some _ => _ | None => _ end) -> _ ] => destruct x eqn:?; myinv
| [ |- In _ (match ?x with false => _ | true => _ end) -> _ ] => destruct x eqn:?; myinv
| [ |- In _ (match ?x with left _ => _ | right _ => _ end) -> _ ] => destruct x; myinv
| _ => idtac
end.
Hint Extern 3 => exact I.
Theorem do_step_sound:
forall w S rule t S',
In (TR rule t S') (do_step w S) ->
Csem.step ge S t S' \/ (t = E0 /\ S' = Stuckstate /\ can_crash_world w S).
Proof with try (left; right; econstructor; eauto; fail).
intros until S'. destruct S; simpl.
(* State *)
destruct s; myinv...
(* skip *)
destruct k; myinv...
(* break *)
destruct k; myinv...
(* continue *)
destruct k; myinv...
(* goto *)
destruct p as [s' k']. myinv...
(* ExprState *)
destruct (is_val r) as [[v ty]|] eqn:?.
(* expression is a value *)
rewrite (is_val_inv _ _ _ Heqo).
destruct k; myinv...
(* expression reduces *)
intros. exploit list_in_map_inv; eauto. intros [[C rd] [A B]].
generalize (step_expr_sound e w r RV m). unfold reducts_ok. intros [P Q].
exploit P; eauto. intros [a' [k' [CTX [EQ RD]]]].
unfold expr_final_state in A. simpl in A.
destruct k'; destruct rd; inv A; simpl in RD; try contradiction.
(* lred *)
left; left; apply step_lred; auto.
(* stuck lred *)
exploit not_imm_safe_t; eauto. intros [R | R]; eauto.
(* rred *)
destruct RD. left; left; apply step_rred; auto.
(* callred *)
destruct RD; subst m'. left; left; apply step_call; eauto.
(* stuck rred *)
exploit not_imm_safe_t; eauto. intros [R | R]; eauto.
(* callstate *)
destruct fd; myinv.
(* internal *)
destruct (do_alloc_variables empty_env m (fn_params f ++ fn_vars f)) as [e m1] eqn:?.
myinv. left; right; apply step_internal_function with m1. auto.
change e with (fst (e,m1)). change m1 with (snd (e,m1)) at 2. rewrite <- Heqp.
apply do_alloc_variables_sound. eapply sem_bind_parameters_sound; eauto.
(* external *)
destruct p as [[[w' tr] v] m']. myinv. left; right; constructor.
eapply do_ef_external_sound; eauto.
(* returnstate *)
destruct k; myinv...
(* stuckstate *)
contradiction.
Qed.
Remark estep_not_val:
forall f a k e m t S, estep ge (ExprState f a k e m) t S -> is_val a = None.
Proof.
intros.
assert (forall b from to C, context from to C -> (from = to /\ C = fun x => x) \/ is_val (C b) = None).
induction 1; simpl; auto.
inv H.
destruct (H0 a0 _ _ _ H9) as [[A B] | A]. subst. inv H8; auto. auto.
destruct (H0 a0 _ _ _ H9) as [[A B] | A]. subst. inv H8; auto. auto.
destruct (H0 a0 _ _ _ H9) as [[A B] | A]. subst. inv H8; auto. auto.
destruct (H0 a0 _ _ _ H8) as [[A B] | A]. subst. destruct a0; auto. elim H9. constructor. auto.
Qed.
Theorem do_step_complete:
forall w S t S' w',
possible_trace w t w' -> Csem.step ge S t S' -> exists rule, In (TR rule t S') (do_step w S).
Proof with (unfold ret; eauto with coqlib).
intros until w'; intros PT H.
destruct H.
(* Expression step *)
inversion H; subst; exploit estep_not_val; eauto; intro NOTVAL.
(* lred *)
unfold do_step; rewrite NOTVAL.
exploit lred_topred; eauto. instantiate (1 := w). intros (rule & STEP).
exists rule. change (TR rule E0 (ExprState f (C a') k e m')) with (expr_final_state f k e (C, Lred rule a' m')).
apply in_map.
generalize (step_expr_context e w _ _ _ H1 a m). unfold reducts_incl.
intro. replace C with (fun x => C x). apply H2.
rewrite STEP. unfold topred; auto with coqlib.
apply extensionality; auto.
(* rred *)
unfold do_step; rewrite NOTVAL.
exploit rred_topred; eauto. instantiate (1 := e). intros (rule & STEP).
exists rule.
change (TR rule t (ExprState f (C a') k e m')) with (expr_final_state f k e (C, Rred rule a' m' t)).
apply in_map.
generalize (step_expr_context e w _ _ _ H1 a m). unfold reducts_incl.
intro. replace C with (fun x => C x). apply H2.
rewrite STEP; unfold topred; auto with coqlib.
apply extensionality; auto.
(* callred *)
unfold do_step; rewrite NOTVAL.
exploit callred_topred; eauto. instantiate (1 := m). instantiate (1 := w). instantiate (1 := e).
intros (rule & STEP). exists rule.
change (TR rule E0 (Callstate fd vargs (Kcall f e C ty k) m)) with (expr_final_state f k e (C, Callred rule fd vargs ty m)).
apply in_map.
generalize (step_expr_context e w _ _ _ H1 a m). unfold reducts_incl.
intro. replace C with (fun x => C x). apply H2.
rewrite STEP; unfold topred; auto with coqlib.
apply extensionality; auto.
(* stuck *)
exploit not_imm_safe_stuck_red. eauto. red; intros; elim H1. eapply imm_safe_t_imm_safe. eauto.
instantiate (1 := w). intros [C' IN].
simpl do_step. rewrite NOTVAL.
exists "step_stuck".
change (TR "step_stuck" E0 Stuckstate) with (expr_final_state f k e (C', Stuckred)).
apply in_map. auto.
(* Statement step *)
inv H; simpl; econstructor...
rewrite H0...
rewrite H0...
rewrite H0...
destruct H0; subst s0...
destruct H0; subst s0...
rewrite H0...
rewrite H0...
rewrite pred_dec_false...
rewrite H0...
rewrite H0...
destruct H0; subst x...
rewrite H0...
rewrite H0; rewrite H1...
rewrite H1. red in H0. destruct k; try contradiction...
rewrite H0...
destruct H0; subst x...
rewrite H0...
(* Call step *)
rewrite pred_dec_true; auto. rewrite (do_alloc_variables_complete _ _ _ _ _ H1).
rewrite (sem_bind_parameters_complete _ _ _ _ _ _ H2)...
exploit do_ef_external_complete; eauto. intro EQ; rewrite EQ. auto with coqlib.
Qed.
End EXEC.
Local Open Scope option_monad_scope.
Definition do_initial_state (p: program): option (genv * state) :=
let ge := globalenv p in
do m0 <- Genv.init_mem p;
do b <- Genv.find_symbol ge p.(prog_main);
do f <- Genv.find_funct_ptr ge b;
check (type_eq (type_of_fundef f) (Tfunction Tnil type_int32s cc_default));
Some (ge, Callstate f nil Kstop m0).
Definition at_final_state (S: state): option int :=
match S with
| Returnstate (Vint r) Kstop m => Some r
| _ => None
end.
|
module Crop
public export
record Crop where
constructor CreateCrop
x : Double
y : Double
x2 : Double
y2 : Double
|
# -*- coding: utf-8 -*-
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
sc = spark.sparkContext
import numpy as np # type: ignore[import]
import pandas as pd # type: ignore[import]
# Enable Arrow-based columnar data transfers
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
# Generate a Pandas DataFrame
pdf = pd.DataFrame(np.random.rand(100, 3))
# Create a Spark DataFrame from a Pandas DataFrame using Arrow
df = spark.createDataFrame(pdf)
# Convert the Spark DataFrame back to a Pandas DataFrame using Arrow
result_pdf = df.select("*").toPandas()
import pandas as pd
from pyspark.sql.functions import pandas_udf
@pandas_udf("col1 string, col2 long")
def func(s1: pd.Series, s2: pd.Series, s3: pd.DataFrame) -> pd.DataFrame:
s3['col2'] = s1 + s2.str.len()
return s3
# Create a Spark DataFrame that has three columns including a struct column.
df = spark.createDataFrame(
[[1, "a string", ("a nested string",)]],
"long_col long, string_col string, struct_col struct<col1:string>")
df.printSchema()
# root
# |-- long_column: long (nullable = true)
# |-- string_column: string (nullable = true)
# |-- struct_column: struct (nullable = true)
# | |-- col1: string (nullable = true)
df.select(func("long_col", "string_col", "struct_col")).printSchema()
# |-- func(long_col, string_col, struct_col): struct (nullable = true)
# | |-- col1: string (nullable = true)
# | |-- col2: long (nullable = true)
import pandas as pd
from pyspark.sql.functions import col, pandas_udf
from pyspark.sql.types import LongType
# Declare the function and create the UDF
def multiply_func(a: pd.Series, b: pd.Series) -> pd.Series:
return a * b
multiply = pandas_udf(multiply_func, returnType=LongType())
# The function for a pandas_udf should be able to execute with local Pandas data
x = pd.Series([1, 2, 3])
print(multiply_func(x, x))
# 0 1
# 1 4
# 2 9
# dtype: int64
# Create a Spark DataFrame, 'spark' is an existing SparkSession
df = spark.createDataFrame(pd.DataFrame(x, columns=["x"]))
# Execute function as a Spark vectorized UDF
df.select(multiply(col("x"), col("x"))).show()
# +-------------------+
# |multiply_func(x, x)|
# +-------------------+
# | 1|
# | 4|
# | 9|
# +-------------------+
from typing import Iterator
import pandas as pd
from pyspark.sql.functions import pandas_udf
pdf = pd.DataFrame([1, 2, 3], columns=["x"])
df = spark.createDataFrame(pdf)
# Declare the function and create the UDF
@pandas_udf("long")
def plus_one(iterator: Iterator[pd.Series]) -> Iterator[pd.Series]:
for x in iterator:
yield x + 1
df.select(plus_one("x")).show()
# +-----------+
# |plus_one(x)|
# +-----------+
# | 2|
# | 3|
# | 4|
# +-----------+
from typing import Iterator, Tuple
import pandas as pd
from pyspark.sql.functions import pandas_udf
pdf = pd.DataFrame([1, 2, 3], columns=["x"])
df = spark.createDataFrame(pdf)
# Declare the function and create the UDF
@pandas_udf("long")
def multiply_two_cols(
iterator: Iterator[Tuple[pd.Series, pd.Series]]) -> Iterator[pd.Series]:
for a, b in iterator:
yield a * b
df.select(multiply_two_cols("x", "x")).show()
# +-----------------------+
# |multiply_two_cols(x, x)|
# +-----------------------+
# | 1|
# | 4|
# | 9|
# +-----------------------+
import pandas as pd
from pyspark.sql.functions import pandas_udf
from pyspark.sql import Window
df = spark.createDataFrame(
[(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
("id", "v"))
# Declare the function and create the UDF
@pandas_udf("double")
def mean_udf(v: pd.Series) -> float:
return v.mean()
df.select(mean_udf(df['v'])).show()
# +-----------+
# |mean_udf(v)|
# +-----------+
# | 4.2|
# +-----------+
df.groupby("id").agg(mean_udf(df['v'])).show()
# +---+-----------+
# | id|mean_udf(v)|
# +---+-----------+
# | 1| 1.5|
# | 2| 6.0|
# +---+-----------+
w = Window \
.partitionBy('id') \
.rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)
df.withColumn('mean_v', mean_udf(df['v']).over(w)).show()
# +---+----+------+
# | id| v|mean_v|
# +---+----+------+
# | 1| 1.0| 1.5|
# | 1| 2.0| 1.5|
# | 2| 3.0| 6.0|
# | 2| 5.0| 6.0|
# | 2|10.0| 6.0|
# +---+----+------+
df = spark.createDataFrame(
[(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
("id", "v"))
def subtract_mean(pdf):
# pdf is a pandas.DataFrame
v = pdf.v
return pdf.assign(v=v - v.mean())
df.groupby("id").applyInPandas(subtract_mean, schema="id long, v double").show()
# +---+----+
# | id| v|
# +---+----+
# | 1|-0.5|
# | 1| 0.5|
# | 2|-3.0|
# | 2|-1.0|
# | 2| 4.0|
# +---+----+
df = spark.createDataFrame([(1, 21), (2, 30)], ("id", "age"))
def filter_func(iterator):
for pdf in iterator:
yield pdf[pdf.id == 1]
df.mapInPandas(filter_func, schema=df.schema).show()
# +---+---+
# | id|age|
# +---+---+
# | 1| 21|
# +---+---+
import pandas as pd
df1 = spark.createDataFrame(
[(20000101, 1, 1.0), (20000101, 2, 2.0), (20000102, 1, 3.0), (20000102, 2, 4.0)],
("time", "id", "v1"))
df2 = spark.createDataFrame(
[(20000101, 1, "x"), (20000101, 2, "y")],
("time", "id", "v2"))
def asof_join(l, r):
return pd.merge_asof(l, r, on="time", by="id")
df1.groupby("id").cogroup(df2.groupby("id")).applyInPandas(
asof_join, schema="time int, id int, v1 double, v2 string").show()
# +--------+---+---+---+
# | time| id| v1| v2|
# +--------+---+---+---+
# |20000101| 1|1.0| x|
# |20000102| 1|3.0| x|
# |20000101| 2|2.0| y|
# |20000102| 2|4.0| y|
# +--------+---+---+---+
spark.stop()
|
Formal statement is: lemma dist_commute_lessI: "dist y x < e \<Longrightarrow> dist x y < e" Informal statement is: The distance between two points is the same in either direction. |
(* Title: HOL/Auth/n_mesi_lemma_on_inv__2.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_mesi Protocol Case Study*}
theory n_mesi_lemma_on_inv__2 imports n_mesi_base
begin
section{*All lemmas on causal relation between inv__2 and some rule r*}
lemma n_t1Vsinv__2:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_t1 i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__2 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_t1 i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__2 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)) (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_t2Vsinv__2:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_t2 N i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__2 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_t2 N i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__2 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "((formEval (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)) s))\<or>((formEval (andForm (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(i=p__Inv0)"
have "((formEval (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) s))\<or>((formEval (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) s))\<or>((formEval (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "((formEval (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E))) s))\<or>((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E))) s))\<or>((formEval (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (andForm (andForm (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I)) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const I))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const I)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''state'') p__Inv0)) (Const E)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_t3Vsinv__2:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_t3 N i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__2 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_t3 N i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__2 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_t4Vsinv__2:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_t4 N i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__2 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_t4 N i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__2 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
end
|
{-# OPTIONS --safe #-}
module Cubical.Relation.Nullary.DecidablePropositions where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.Equiv renaming (_∙ₑ_ to _⋆_)
open import Cubical.Data.Bool
open import Cubical.Data.Sigma
open import Cubical.Relation.Nullary.Base
open import Cubical.Relation.Nullary.Properties
private
variable
ℓ ℓ' : Level
DecProp : (ℓ : Level) → Type (ℓ-suc ℓ)
DecProp ℓ = Σ[ P ∈ hProp ℓ ] Dec (P .fst)
isSetDecProp : isSet (DecProp ℓ)
isSetDecProp = isOfHLevelΣ 2 isSetHProp (λ P → isProp→isSet (isPropDec (P .snd)))
-- the following is an alternative formulation of decidable propositions
-- it separates the boolean value from more proof-relevant part
-- so it performs better when doing computation
isDecProp : Type ℓ → Type ℓ
isDecProp P = Σ[ t ∈ Bool ] P ≃ Bool→Type t
DecProp' : (ℓ : Level) → Type (ℓ-suc ℓ)
DecProp' ℓ = Σ[ P ∈ Type ℓ ] isDecProp P
-- properties of the alternative formulation
isDecProp→isProp : {P : Type ℓ} → isDecProp P → isProp P
isDecProp→isProp h = isOfHLevelRespectEquiv 1 (invEquiv (h .snd)) isPropBool→Type
isDecProp→Dec : {P : Type ℓ} → isDecProp P → Dec P
isDecProp→Dec h = EquivPresDec (invEquiv (h .snd)) DecBool→Type
isPropIsDecProp : {P : Type ℓ} → isProp (isDecProp P)
isPropIsDecProp p q =
Σ≡PropEquiv (λ _ → isOfHLevel⁺≃ᵣ 0 isPropBool→Type) .fst
(Bool→TypeInj _ _ (invEquiv (p .snd) ⋆ q .snd))
isDecPropRespectEquiv : {P : Type ℓ} {Q : Type ℓ'}
→ P ≃ Q → isDecProp Q → isDecProp P
isDecPropRespectEquiv e (t , e') = t , e ⋆ e'
|
/-
Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser
-/
import linear_algebra.orientation
import algebra.order.smul
import data.complex.basic
import data.fin.vec_notation
import field_theory.tower
import algebra.char_p.invertible
/-!
# Complex number as a vector space over `ℝ`
This file contains the following instances:
* Any `•`-structure (`has_smul`, `mul_action`, `distrib_mul_action`, `module`, `algebra`) on
`ℝ` imbues a corresponding structure on `ℂ`. This includes the statement that `ℂ` is an `ℝ`
algebra.
* any complex vector space is a real vector space;
* any finite dimensional complex vector space is a finite dimensional real vector space;
* the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex
vector space.
It also defines bundled versions of four standard maps (respectively, the real part, the imaginary
part, the embedding of `ℝ` in `ℂ`, and the complex conjugate):
* `complex.re_lm` (`ℝ`-linear map);
* `complex.im_lm` (`ℝ`-linear map);
* `complex.of_real_am` (`ℝ`-algebra (homo)morphism);
* `complex.conj_ae` (`ℝ`-algebra equivalence).
It also provides a universal property of the complex numbers `complex.lift`, which constructs a
`ℂ →ₐ[ℝ] A` into any `ℝ`-algebra `A` given a square root of `-1`.
In addition, this file provides a decomposition into `real_part` and `imaginary_part` for any
element of a `star_module` over `ℂ`.
## Notation
* `ℜ` and `ℑ` for the `real_part` and `imaginary_part`, respectively, in the locale
`complex_star_module`.
-/
namespace complex
open_locale complex_conjugate
variables {R : Type*} {S : Type*}
section
variables [has_smul R ℝ]
/- The useless `0` multiplication in `smul` is to make sure that
`restrict_scalars.module ℝ ℂ ℂ = complex.module` definitionally. -/
instance : has_smul R ℂ :=
{ smul := λ r x, ⟨r • x.re - 0 * x.im, r • x.im + 0 * x.re⟩ }
lemma smul_re (r : R) (z : ℂ) : (r • z).re = r • z.re := by simp [(•)]
lemma smul_im (r : R) (z : ℂ) : (r • z).im = r • z.im := by simp [(•)]
@[simp] lemma real_smul {x : ℝ} {z : ℂ} : x • z = x * z := rfl
end
instance [has_smul R ℝ] [has_smul S ℝ] [smul_comm_class R S ℝ] : smul_comm_class R S ℂ :=
{ smul_comm := λ r s x, by ext; simp [smul_re, smul_im, smul_comm] }
instance [has_smul R S] [has_smul R ℝ] [has_smul S ℝ] [is_scalar_tower R S ℝ] :
is_scalar_tower R S ℂ :=
{ smul_assoc := λ r s x, by ext; simp [smul_re, smul_im, smul_assoc] }
instance [has_smul R ℝ] [has_smul Rᵐᵒᵖ ℝ] [is_central_scalar R ℝ] :
is_central_scalar R ℂ :=
{ op_smul_eq_smul := λ r x, by ext; simp [smul_re, smul_im, op_smul_eq_smul] }
instance [monoid R] [mul_action R ℝ] : mul_action R ℂ :=
{ one_smul := λ x, by ext; simp [smul_re, smul_im, one_smul],
mul_smul := λ r s x, by ext; simp [smul_re, smul_im, mul_smul] }
instance [distrib_smul R ℝ] : distrib_smul R ℂ :=
{ smul_add := λ r x y, by ext; simp [smul_re, smul_im, smul_add],
smul_zero := λ r, by ext; simp [smul_re, smul_im, smul_zero] }
instance [semiring R] [distrib_mul_action R ℝ] : distrib_mul_action R ℂ :=
{ ..complex.distrib_smul }
instance [semiring R] [module R ℝ] : module R ℂ :=
{ add_smul := λ r s x, by ext; simp [smul_re, smul_im, add_smul],
zero_smul := λ r, by ext; simp [smul_re, smul_im, zero_smul] }
instance [comm_semiring R] [algebra R ℝ] : algebra R ℂ :=
{ smul := (•),
smul_def' := λ r x, by ext; simp [smul_re, smul_im, algebra.smul_def],
commutes' := λ r ⟨xr, xi⟩, by ext; simp [smul_re, smul_im, algebra.commutes],
..complex.of_real.comp (algebra_map R ℝ) }
instance : star_module ℝ ℂ :=
⟨λ r x, by simp only [star_def, star_trivial, real_smul, map_mul, conj_of_real]⟩
@[simp] lemma coe_algebra_map : (algebra_map ℝ ℂ : ℝ → ℂ) = coe := rfl
section
variables {A : Type*} [semiring A] [algebra ℝ A]
/-- We need this lemma since `complex.coe_algebra_map` diverts the simp-normal form away from
`alg_hom.commutes`. -/
@[simp] lemma _root_.alg_hom.map_coe_real_complex (f : ℂ →ₐ[ℝ] A) (x : ℝ) :
f x = algebra_map ℝ A x :=
f.commutes x
/-- Two `ℝ`-algebra homomorphisms from ℂ are equal if they agree on `complex.I`. -/
@[ext]
lemma alg_hom_ext ⦃f g : ℂ →ₐ[ℝ] A⦄ (h : f I = g I) : f = g :=
begin
ext ⟨x, y⟩,
simp only [mk_eq_add_mul_I, alg_hom.map_add, alg_hom.map_coe_real_complex, alg_hom.map_mul, h]
end
end
section
open_locale complex_order
protected lemma ordered_smul : ordered_smul ℝ ℂ :=
ordered_smul.mk' $ λ a b r hab hr, ⟨by simp [hr, hab.1.le], by simp [hab.2]⟩
localized "attribute [instance] complex.ordered_smul" in complex_order
end
open submodule finite_dimensional
/-- `ℂ` has a basis over `ℝ` given by `1` and `I`. -/
noncomputable def basis_one_I : basis (fin 2) ℝ ℂ :=
basis.of_equiv_fun
{ to_fun := λ z, ![z.re, z.im],
inv_fun := λ c, c 0 + c 1 • I,
left_inv := λ z, by simp,
right_inv := λ c, by { ext i, fin_cases i; simp },
map_add' := λ z z', by simp,
-- why does `simp` not know how to apply `smul_cons`, which is a `@[simp]` lemma, here?
map_smul' := λ c z, by simp [matrix.smul_cons c z.re, matrix.smul_cons c z.im] }
@[simp] lemma coe_basis_one_I_repr (z : ℂ) : ⇑(basis_one_I.repr z) = ![z.re, z.im] := rfl
@[simp] lemma coe_basis_one_I : ⇑basis_one_I = ![1, I] :=
funext $ λ i, basis.apply_eq_iff.mpr $ finsupp.ext $ λ j,
by fin_cases i; fin_cases j;
simp only [coe_basis_one_I_repr, finsupp.single_eq_of_ne, matrix.cons_val_zero,
matrix.cons_val_one, matrix.head_cons, fin.one_eq_zero_iff, ne.def, not_false_iff, I_re,
nat.succ_succ_ne_one, one_im, I_im, one_re, finsupp.single_eq_same, fin.zero_eq_one_iff]
instance : finite_dimensional ℝ ℂ := of_fintype_basis basis_one_I
@[simp] lemma finrank_real_complex : finite_dimensional.finrank ℝ ℂ = 2 :=
by rw [finrank_eq_card_basis basis_one_I, fintype.card_fin]
@[simp] lemma dim_real_complex : module.rank ℝ ℂ = 2 :=
by simp [← finrank_eq_dim, finrank_real_complex]
lemma {u} dim_real_complex' : cardinal.lift.{u} (module.rank ℝ ℂ) = 2 :=
by simp [← finrank_eq_dim, finrank_real_complex, bit0]
/-- `fact` version of the dimension of `ℂ` over `ℝ`, locally useful in the definition of the
circle. -/
lemma finrank_real_complex_fact : fact (finrank ℝ ℂ = 2) := ⟨finrank_real_complex⟩
/-- The standard orientation on `ℂ`. -/
protected noncomputable def orientation : orientation ℝ ℂ (fin 2) := complex.basis_one_I.orientation
end complex
/- Register as an instance (with low priority) the fact that a complex vector space is also a real
vector space. -/
@[priority 900]
instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E :=
restrict_scalars.module ℝ ℂ E
instance module.real_complex_tower (E : Type*) [add_comm_group E] [module ℂ E] :
is_scalar_tower ℝ ℂ E :=
restrict_scalars.is_scalar_tower ℝ ℂ E
@[simp, norm_cast] lemma complex.coe_smul {E : Type*} [add_comm_group E] [module ℂ E]
(x : ℝ) (y : E) :
(x : ℂ) • y = x • y :=
rfl
/-- The scalar action of `ℝ` on a `ℂ`-module `E` induced by `module.complex_to_real` commutes with
another scalar action of `M` on `E` whenever the action of `ℂ` commutes with the action of `M`. -/
@[priority 900]
instance smul_comm_class.complex_to_real {M E : Type*}
[add_comm_group E] [module ℂ E] [has_smul M E] [smul_comm_class ℂ M E] : smul_comm_class ℝ M E :=
{ smul_comm := λ r _ _, (smul_comm (r : ℂ) _ _ : _) }
@[priority 100]
instance finite_dimensional.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E]
[finite_dimensional ℂ E] : finite_dimensional ℝ E :=
finite_dimensional.trans ℝ ℂ E
lemma dim_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] :
module.rank ℝ E = 2 * module.rank ℂ E :=
cardinal.lift_inj.1 $
by { rw [← dim_mul_dim' ℝ ℂ E, complex.dim_real_complex], simp [bit0] }
lemma finrank_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] :
finite_dimensional.finrank ℝ E = 2 * finite_dimensional.finrank ℂ E :=
by rw [← finite_dimensional.finrank_mul_finrank ℝ ℂ E, complex.finrank_real_complex]
@[priority 900]
instance star_module.complex_to_real {E : Type*} [add_comm_group E] [has_star E] [module ℂ E]
[star_module ℂ E] : star_module ℝ E :=
⟨λ r a, by rw [←smul_one_smul ℂ r a, star_smul, star_smul, star_one, smul_one_smul]⟩
namespace complex
open_locale complex_conjugate
/-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/
def re_lm : ℂ →ₗ[ℝ] ℝ :=
{ to_fun := λx, x.re,
map_add' := add_re,
map_smul' := by simp, }
@[simp] lemma re_lm_coe : ⇑re_lm = re := rfl
/-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/
def im_lm : ℂ →ₗ[ℝ] ℝ :=
{ to_fun := λx, x.im,
map_add' := add_im,
map_smul' := by simp, }
@[simp] lemma im_lm_coe : ⇑im_lm = im := rfl
/-- `ℝ`-algebra morphism version of the canonical embedding of `ℝ` in `ℂ`. -/
def of_real_am : ℝ →ₐ[ℝ] ℂ := algebra.of_id ℝ ℂ
@[simp] lemma of_real_am_coe : ⇑of_real_am = coe := rfl
/-- `ℝ`-algebra isomorphism version of the complex conjugation function from `ℂ` to `ℂ` -/
def conj_ae : ℂ ≃ₐ[ℝ] ℂ :=
{ inv_fun := conj,
left_inv := star_star,
right_inv := star_star,
commutes' := conj_of_real,
.. conj }
@[simp] lemma conj_ae_coe : ⇑conj_ae = conj := rfl
/-- The matrix representation of `conj_ae`. -/
@[simp] lemma to_matrix_conj_ae :
linear_map.to_matrix basis_one_I basis_one_I conj_ae.to_linear_map = !![1, 0; 0, -1] :=
begin
ext i j,
simp [linear_map.to_matrix_apply],
fin_cases i; fin_cases j; simp
end
/-- The identity and the complex conjugation are the only two `ℝ`-algebra homomorphisms of `ℂ`. -/
lemma real_alg_hom_eq_id_or_conj (f : ℂ →ₐ[ℝ] ℂ) : f = alg_hom.id ℝ ℂ ∨ f = conj_ae :=
begin
refine (eq_or_eq_neg_of_sq_eq_sq (f I) I $ by rw [← map_pow, I_sq, map_neg, map_one]).imp _ _;
refine λ h, alg_hom_ext _,
exacts [h, conj_I.symm ▸ h],
end
/-- The natural `add_equiv` from `ℂ` to `ℝ × ℝ`. -/
@[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }]
def equiv_real_prod_add_hom : ℂ ≃+ ℝ × ℝ :=
{ map_add' := by simp, .. equiv_real_prod }
/-- The natural `linear_equiv` from `ℂ` to `ℝ × ℝ`. -/
@[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }]
def equiv_real_prod_lm : ℂ ≃ₗ[ℝ] ℝ × ℝ :=
{ map_smul' := by simp [equiv_real_prod_add_hom], .. equiv_real_prod_add_hom }
section lift
variables {A : Type*} [ring A] [algebra ℝ A]
/-- There is an alg_hom from `ℂ` to any `ℝ`-algebra with an element that squares to `-1`.
See `complex.lift` for this as an equiv. -/
def lift_aux (I' : A) (hf : I' * I' = -1) : ℂ →ₐ[ℝ] A :=
alg_hom.of_linear_map
((algebra.of_id ℝ A).to_linear_map.comp re_lm + (linear_map.to_span_singleton _ _ I').comp im_lm)
(show algebra_map ℝ A 1 + (0 : ℝ) • I' = 1,
by rw [ring_hom.map_one, zero_smul, add_zero])
(λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, show algebra_map ℝ A (x₁ * x₂ - y₁ * y₂) + (x₁ * y₂ + y₁ * x₂) • I'
= (algebra_map ℝ A x₁ + y₁ • I') * (algebra_map ℝ A x₂ + y₂ • I'),
begin
rw [add_mul, mul_add, mul_add, add_comm _ (y₁ • I' * y₂ • I'), add_add_add_comm],
congr' 1, -- equate "real" and "imaginary" parts
{ rw [smul_mul_smul, hf, smul_neg, ←algebra.algebra_map_eq_smul_one, ←sub_eq_add_neg,
←ring_hom.map_mul, ←ring_hom.map_sub], },
{ rw [algebra.smul_def, algebra.smul_def, algebra.smul_def, ←algebra.right_comm _ x₂,
←mul_assoc, ←add_mul, ←ring_hom.map_mul, ←ring_hom.map_mul, ←ring_hom.map_add] }
end)
@[simp]
lemma lift_aux_apply (I' : A) (hI') (z : ℂ) :
lift_aux I' hI' z = algebra_map ℝ A z.re + z.im • I' := rfl
lemma lift_aux_apply_I (I' : A) (hI') : lift_aux I' hI' I = I' := by simp
/-- A universal property of the complex numbers, providing a unique `ℂ →ₐ[ℝ] A` for every element
of `A` which squares to `-1`.
This can be used to embed the complex numbers in the `quaternion`s.
This isomorphism is named to match the very similar `zsqrtd.lift`. -/
@[simps {simp_rhs := tt}]
def lift : {I' : A // I' * I' = -1} ≃ (ℂ →ₐ[ℝ] A) :=
{ to_fun := λ I', lift_aux I' I'.prop,
inv_fun := λ F, ⟨F I, by rw [←F.map_mul, I_mul_I, alg_hom.map_neg, alg_hom.map_one]⟩,
left_inv := λ I', subtype.ext $ lift_aux_apply_I I' I'.prop,
right_inv := λ F, alg_hom_ext $ lift_aux_apply_I _ _, }
/- When applied to `complex.I` itself, `lift` is the identity. -/
@[simp]
lemma lift_aux_I : lift_aux I I_mul_I = alg_hom.id ℝ ℂ :=
alg_hom_ext $ lift_aux_apply_I _ _
/- When applied to `-complex.I`, `lift` is conjugation, `conj`. -/
@[simp]
end lift
end complex
section real_imaginary_part
open complex
variables {A : Type*} [add_comm_group A] [module ℂ A] [star_add_monoid A] [star_module ℂ A]
/-- Create a `self_adjoint` element from a `skew_adjoint` element by multiplying by the scalar
`-complex.I`. -/
@[simps] def skew_adjoint.neg_I_smul : skew_adjoint A →ₗ[ℝ] self_adjoint A :=
{ to_fun := λ a, ⟨-I • a, by simp only [self_adjoint.mem_iff, neg_smul, star_neg, star_smul,
star_def, conj_I, skew_adjoint.star_coe_eq, neg_smul_neg]⟩,
map_add' := λ a b, by { ext, simp only [add_subgroup.coe_add, smul_add, add_mem_class.mk_add_mk]},
map_smul' := λ a b, by { ext, simp only [neg_smul, skew_adjoint.coe_smul, add_subgroup.coe_mk,
ring_hom.id_apply, self_adjoint.coe_smul, smul_neg, neg_inj], rw smul_comm, } }
lemma skew_adjoint.I_smul_neg_I (a : skew_adjoint A) :
I • (skew_adjoint.neg_I_smul a : A) = a :=
by simp only [smul_smul, skew_adjoint.neg_I_smul_apply_coe, neg_smul, smul_neg, I_mul_I, one_smul,
neg_neg]
/-- The real part `ℜ a` of an element `a` of a star module over `ℂ`, as a linear map. This is just
`self_adjoint_part ℝ`, but we provide it as a separate definition in order to link it with lemmas
concerning the `imaginary_part`, which doesn't exist in star modules over other rings. -/
noncomputable def real_part : A →ₗ[ℝ] self_adjoint A := self_adjoint_part ℝ
/-- The imaginary part `ℑ a` of an element `a` of a star module over `ℂ`, as a linear map into the
self adjoint elements. In a general star module, we have a decomposition into the `self_adjoint`
and `skew_adjoint` parts, but in a star module over `ℂ` we have
`real_part_add_I_smul_imaginary_part`, which allows us to decompose into a linear combination of
`self_adjoint`s. -/
noncomputable
def imaginary_part : A →ₗ[ℝ] self_adjoint A := skew_adjoint.neg_I_smul.comp (skew_adjoint_part ℝ)
localized "notation `ℜ` := real_part" in complex_star_module
localized "notation `ℑ` := imaginary_part" in complex_star_module
@[simp] lemma real_part_apply_coe (a : A) :
(ℜ a : A) = (2 : ℝ)⁻¹ • (a + star a) :=
by { unfold real_part, simp only [self_adjoint_part_apply_coe, inv_of_eq_inv]}
@[simp] lemma imaginary_part_apply_coe (a : A) :
(ℑ a : A) = -I • (2 : ℝ)⁻¹ • (a - star a) :=
begin
unfold imaginary_part,
simp only [linear_map.coe_comp, skew_adjoint.neg_I_smul_apply_coe, skew_adjoint_part_apply_coe,
inv_of_eq_inv],
end
/-- The standard decomposition of `ℜ a + complex.I • ℑ a = a` of an element of a star module over
`ℂ` into a linear combination of self adjoint elements. -/
lemma real_part_add_I_smul_imaginary_part (a : A) : (ℜ a + I • ℑ a : A) = a :=
by simpa only [smul_smul, real_part_apply_coe, imaginary_part_apply_coe, neg_smul, I_mul_I,
one_smul, neg_sub, add_add_sub_cancel, smul_sub, smul_add, neg_sub_neg, inv_of_eq_inv]
using inv_of_two_smul_add_inv_of_two_smul ℝ a
@[simp] lemma real_part_I_smul (a : A) : ℜ (I • a) = - ℑ a :=
by { ext, simp [smul_comm I, smul_sub, sub_eq_add_neg, add_comm] }
@[simp] lemma imaginary_part_I_smul (a : A) : ℑ (I • a) = ℜ a :=
by { ext, simp [smul_comm I, smul_smul I] }
lemma real_part_smul (z : ℂ) (a : A) : ℜ (z • a) = z.re • ℜ a - z.im • ℑ a :=
by { nth_rewrite 0 ←re_add_im z, simp [-re_add_im, add_smul, ←smul_smul, sub_eq_add_neg] }
lemma imaginary_part_smul (z : ℂ) (a : A) : ℑ (z • a) = z.re • ℑ a + z.im • ℜ a :=
by { nth_rewrite 0 ←re_add_im z, simp [-re_add_im, add_smul, ←smul_smul] }
end real_imaginary_part
|
/-
Copyright (c) 2020 Fox Thomson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Fox Thomson
-/
import data.fintype.basic
import data.finset.basic
import tactic.rcases
import computability.language
/-!
# Regular Expressions
This file contains the formal definition for regular expressions and basic lemmas. Note these are
regular expressions in terms of formal language theory. Note this is different to regex's used in
computer science such as the POSIX standard.
TODO
* Show that this regular expressions and DFA/NFA's are equivalent.
* `attribute [pattern] has_mul.mul` has been added into this file, it could be moved.
-/
universe u
variables {α : Type u} [dec : decidable_eq α]
/--
This is the definition of regular expressions. The names used here is to mirror the definition
of a Kleene algebra (https://en.wikipedia.org/wiki/Kleene_algebra).
* `0` (`zero`) matches nothing
* `1` (`epsilon`) matches only the empty string
* `char a` matches only the string 'a'
* `star P` matches any finite concatenation of strings which match `P`
* `P + Q` (`plus P Q`) matches anything which match `P` or `Q`
* `P * Q` (`comp P Q`) matches `x ++ y` if `x` matches `P` and `y` matches `Q`
-/
inductive regular_expression (α : Type u) : Type u
| zero : regular_expression
| epsilon : regular_expression
| char : α → regular_expression
| plus : regular_expression → regular_expression → regular_expression
| comp : regular_expression → regular_expression → regular_expression
| star : regular_expression → regular_expression
namespace regular_expression
instance : inhabited (regular_expression α) := ⟨zero⟩
instance : has_add (regular_expression α) := ⟨plus⟩
instance : has_mul (regular_expression α) := ⟨comp⟩
instance : has_one (regular_expression α) := ⟨epsilon⟩
instance : has_zero (regular_expression α) := ⟨zero⟩
attribute [pattern] has_mul.mul
@[simp] lemma zero_def : (zero : regular_expression α) = 0 := rfl
@[simp] lemma one_def : (epsilon : regular_expression α) = 1 := rfl
@[simp] lemma plus_def (P Q : regular_expression α) : plus P Q = P + Q := rfl
@[simp] lemma comp_def (P Q : regular_expression α) : comp P Q = P * Q := rfl
/-- `matches P` provides a language which contains all strings that `P` matches -/
def matches : regular_expression α → language α
| 0 := 0
| 1 := 1
| (char a) := {[a]}
| (P + Q) := P.matches + Q.matches
| (P * Q) := P.matches * Q.matches
| (star P) := P.matches.star
@[simp] lemma matches_zero_def : (0 : regular_expression α).matches = 0 := rfl
@[simp] lemma matches_epsilon_def : (1 : regular_expression α).matches = 1 := rfl
@[simp] lemma matches_add_def (P Q : regular_expression α) :
(P + Q).matches = P.matches + Q.matches := rfl
@[simp] lemma matches_mul_def (P Q : regular_expression α) :
(P * Q).matches = P.matches * Q.matches := rfl
@[simp] lemma matches_star_def (P : regular_expression α) : P.star.matches = P.matches.star := rfl
/-- `match_epsilon P` is true if and only if `P` matches the empty string -/
def match_epsilon : regular_expression α → bool
| 0 := ff
| 1 := tt
| (char _) := ff
| (P + Q) := P.match_epsilon || Q.match_epsilon
| (P * Q) := P.match_epsilon && Q.match_epsilon
| (star P) := tt
include dec
/-- `P.deriv a` matches `x` if `P` matches `a :: x`, the Brzozowski derivative of `P` with respect
to `a` -/
def deriv : regular_expression α → α → regular_expression α
| 0 _ := 0
| 1 _ := 0
| (char a₁) a₂ := if a₁ = a₂ then 1 else 0
| (P + Q) a := deriv P a + deriv Q a
| (P * Q) a :=
if P.match_epsilon then
deriv P a * Q + deriv Q a
else
deriv P a * Q
| (star P) a := deriv P a * star P
/-- `P.rmatch x` is true if and only if `P` matches `x`. This is a computable definition equivalent
to `matches`. -/
def rmatch : regular_expression α → list α → bool
| P [] := match_epsilon P
| P (a::as) := rmatch (P.deriv a) as
@[simp] lemma zero_rmatch (x : list α) : rmatch 0 x = ff :=
by induction x; simp [rmatch, match_epsilon, deriv, *]
lemma char_rmatch_iff (a : α) (x : list α) : rmatch (char a) x ↔ x = [a] :=
begin
cases x with _ x,
dec_trivial,
cases x,
rw [rmatch, deriv],
split_ifs;
tauto,
rw [rmatch, deriv],
split_ifs,
rw one_rmatch_iff,
tauto,
rw zero_rmatch,
tauto
end
lemma add_rmatch_iff (P Q : regular_expression α) (x : list α) :
(P + Q).rmatch x ↔ P.rmatch x ∨ Q.rmatch x :=
begin
induction x with _ _ ih generalizing P Q,
{ repeat {rw rmatch},
rw match_epsilon,
finish },
{ repeat {rw rmatch},
rw deriv,
exact ih _ _ }
end
lemma mul_rmatch_iff (P Q : regular_expression α) (x : list α) :
(P * Q).rmatch x ↔ ∃ t u : list α, x = t ++ u ∧ P.rmatch t ∧ Q.rmatch u :=
begin
induction x with a x ih generalizing P Q,
{ rw [rmatch, match_epsilon],
split,
{ intro h,
refine ⟨ [], [], rfl, _ ⟩,
rw [rmatch, rmatch],
rwa band_coe_iff at h },
{ rintro ⟨ t, u, h₁, h₂ ⟩,
cases list.append_eq_nil.1 h₁.symm with ht hu,
subst ht,
subst hu,
repeat {rw rmatch at h₂},
finish } },
{ rw [rmatch, deriv],
split_ifs with hepsilon,
{ rw [add_rmatch_iff, ih],
split,
{ rintro (⟨ t, u, _ ⟩ | h),
{ exact ⟨ a :: t, u, by tauto ⟩ },
{ exact ⟨ [], a :: x, rfl, hepsilon, h ⟩ } },
{ rintro ⟨ t, u, h, hP, hQ ⟩,
cases t with b t,
{ right,
rw list.nil_append at h,
rw ←h at hQ,
exact hQ },
{ left,
refine ⟨ t, u, by finish, _, hQ ⟩,
rw rmatch at hP,
convert hP,
finish } } },
{ rw ih,
split;
rintro ⟨ t, u, h, hP, hQ ⟩,
{ exact ⟨ a :: t, u, by tauto ⟩ },
{ cases t with b t,
{ contradiction },
{ refine ⟨ t, u, by finish, _, hQ ⟩,
rw rmatch at hP,
convert hP,
finish } } } }
end
lemma star_rmatch_iff (P : regular_expression α) : ∀ (x : list α),
(star P).rmatch x ↔ ∃ S : list (list α), x = S.join ∧ ∀ t ∈ S, t ≠ [] ∧ P.rmatch t
| x :=
begin
have A : ∀ (m n : ℕ), n < m + n + 1,
{ assume m n,
convert add_lt_add_of_le_of_lt (add_le_add (zero_le m) (le_refl n)) zero_lt_one,
simp },
have IH := λ t (h : list.length t < list.length x), star_rmatch_iff t,
clear star_rmatch_iff,
split,
{ cases x with a x,
{ intro,
fconstructor,
exact [],
tauto },
{ rw [rmatch, deriv, mul_rmatch_iff],
rintro ⟨ t, u, hs, ht, hu ⟩,
have hwf : u.length < (list.cons a x).length,
{ rw [hs, list.length_cons, list.length_append],
apply A },
rw IH _ hwf at hu,
rcases hu with ⟨ S', hsum, helem ⟩,
use (a :: t) :: S',
split,
{ finish },
{ intros t' ht',
cases ht' with ht' ht',
{ rw ht',
exact ⟨ dec_trivial, ht ⟩ },
{ exact helem _ ht' } } } },
{ rintro ⟨ S, hsum, helem ⟩,
cases x with a x,
{ dec_trivial },
{ rw [rmatch, deriv, mul_rmatch_iff],
cases S with t' U,
{ exact ⟨ [], [], by tauto ⟩ },
{ cases t' with b t,
{ finish },
refine ⟨ t, U.join, by finish, _, _ ⟩,
{ specialize helem (b :: t) _,
{ finish },
rw rmatch at helem,
convert helem.2,
finish },
{ have hwf : U.join.length < (list.cons a x).length,
{ rw hsum,
simp only
[list.join, list.length_append, list.cons_append, list.length_join, list.length],
apply A },
rw IH _ hwf,
refine ⟨ U, rfl, λ t h, helem t _ ⟩,
right,
assumption } } } }
end
using_well_founded {
rel_tac := λ _ _, `[exact ⟨(λ L₁ L₂ : list _, L₁.length < L₂.length), inv_image.wf _ nat.lt_wf⟩]
}
@[simp] lemma rmatch_iff_matches (P : regular_expression α) :
∀ x : list α, P.rmatch x ↔ x ∈ P.matches :=
begin
intro x,
induction P generalizing x,
all_goals
{ try {rw zero_def},
try {rw one_def},
try {rw plus_def},
try {rw comp_def},
rw matches },
case zero : {
rw zero_rmatch,
tauto },
case epsilon : {
rw one_rmatch_iff,
refl },
case char : {
rw char_rmatch_iff,
refl },
case plus : _ _ ih₁ ih₂ {
rw [add_rmatch_iff, ih₁, ih₂],
refl },
case comp : P Q ih₁ ih₂ {
simp only [mul_rmatch_iff, comp_def, language.mul_def, exists_and_distrib_left, set.mem_image2,
set.image_prod],
split,
{ rintro ⟨ x, y, hsum, hmatch₁, hmatch₂ ⟩,
rw ih₁ at hmatch₁,
rw ih₂ at hmatch₂,
exact ⟨ x, hmatch₁, y, hmatch₂, hsum.symm ⟩ },
{ rintro ⟨ x, hmatch₁, y, hmatch₂, hsum ⟩,
rw ←ih₁ at hmatch₁,
rw ←ih₂ at hmatch₂,
exact ⟨ x, y, hsum.symm, hmatch₁, hmatch₂ ⟩ } },
case star : _ ih {
rw [star_rmatch_iff, language.star_def_nonempty],
split,
all_goals
{ rintro ⟨ S, hx, hS ⟩,
refine ⟨ S, hx, _ ⟩,
intro y,
specialize hS y },
{ rw ←ih y,
tauto },
{ rw ih y,
tauto } }
end
instance (P : regular_expression α) : decidable_pred P.matches :=
begin
intro x,
change decidable (x ∈ P.matches),
rw ←rmatch_iff_matches,
exact eq.decidable _ _
end
end regular_expression
|
import Data.Vect
insert : Ord elem =>
(x : elem) -> (xsSorted : Vect len elem) -> Vect (S len) elem
insert x [] = [x]
insert x (y :: xs) = case x < y of
False => y :: insert x xs
True => x :: y :: xs
insSort : Ord elem => Vect n elem -> Vect n elem
insSort [] = []
insSort (x :: xs) = let xsSorted = insSort xs in
insert x xsSorted
|
lemma islimpt_sequential: fixes x :: "'a::first_countable_topology" shows "x islimpt S \<longleftrightarrow> (\<exists>f. (\<forall>n::nat. f n \<in> S - {x}) \<and> (f \<longlongrightarrow> x) sequentially)" (is "?lhs = ?rhs") |
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.filter.at_top_bot
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# The cofinite filter
In this file we define
`cofinite`: the filter of sets with finite complement
and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`.
## TODO
Define filters for other cardinalities of the complement.
-/
namespace filter
/-- The cofinite filter is the filter of subsets whose complements are finite. -/
def cofinite {α : Type u_1} : filter α :=
mk (set_of fun (s : set α) => set.finite (sᶜ)) sorry sorry sorry
@[simp] theorem mem_cofinite {α : Type u_1} {s : set α} : s ∈ cofinite ↔ set.finite (sᶜ) :=
iff.rfl
@[simp] theorem eventually_cofinite {α : Type u_1} {p : α → Prop} : filter.eventually (fun (x : α) => p x) cofinite ↔ set.finite (set_of fun (x : α) => ¬p x) :=
iff.rfl
protected instance cofinite_ne_bot {α : Type u_1} [infinite α] : ne_bot cofinite :=
mt (iff.mpr empty_in_sets_eq_bot)
(eq.mpr
(id
((fun (a a_1 : Prop) (e_1 : a = a_1) => congr_arg Not e_1) (∅ ∈ cofinite) (set.finite set.univ)
(Eq.trans (propext mem_cofinite)
((fun (s s_1 : set α) (e_1 : s = s_1) => congr_arg set.finite e_1) (∅ᶜ) set.univ set.compl_empty))))
set.infinite_univ)
theorem frequently_cofinite_iff_infinite {α : Type u_1} {p : α → Prop} : filter.frequently (fun (x : α) => p x) cofinite ↔ set.infinite (set_of fun (x : α) => p x) := sorry
end filter
theorem set.finite.compl_mem_cofinite {α : Type u_1} {s : set α} (hs : set.finite s) : sᶜ ∈ filter.cofinite :=
iff.mpr filter.mem_cofinite (Eq.symm (compl_compl s) ▸ hs)
theorem set.finite.eventually_cofinite_nmem {α : Type u_1} {s : set α} (hs : set.finite s) : filter.eventually (fun (x : α) => ¬x ∈ s) filter.cofinite :=
set.finite.compl_mem_cofinite hs
theorem finset.eventually_cofinite_nmem {α : Type u_1} (s : finset α) : filter.eventually (fun (x : α) => ¬x ∈ s) filter.cofinite :=
set.finite.eventually_cofinite_nmem (finset.finite_to_set s)
theorem set.infinite_iff_frequently_cofinite {α : Type u_1} {s : set α} : set.infinite s ↔ filter.frequently (fun (x : α) => x ∈ s) filter.cofinite :=
iff.symm filter.frequently_cofinite_iff_infinite
theorem filter.eventually_cofinite_ne {α : Type u_1} (x : α) : filter.eventually (fun (a : α) => a ≠ x) filter.cofinite :=
set.finite.eventually_cofinite_nmem (set.finite_singleton x)
/-- For natural numbers the filters `cofinite` and `at_top` coincide. -/
theorem nat.cofinite_eq_at_top : filter.cofinite = filter.at_top := sorry
theorem nat.frequently_at_top_iff_infinite {p : ℕ → Prop} : filter.frequently (fun (n : ℕ) => p n) filter.at_top ↔ set.infinite (set_of fun (n : ℕ) => p n) := sorry
|
[STATEMENT]
lemma (in is_cat_pushout) is_cat_pushout_axioms'[cat_lim_cs_intros]:
assumes "\<alpha>' = \<alpha>"
and "\<aa>' = \<aa>"
and "\<gg>' = \<gg>"
and "\<oo>' = \<oo>"
and "\<ff>' = \<ff>"
and "\<bb>' = \<bb>"
and "\<CC>' = \<CC>"
and "X' = X"
shows "x : \<aa>'\<leftarrow>\<gg>'\<leftarrow>\<oo>'\<rightarrow>\<ff>'\<rightarrow>\<bb>' >\<^sub>C\<^sub>F\<^sub>.\<^sub>p\<^sub>o X' \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>'\<^esub> \<CC>'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x : \<aa>'\<leftarrow>\<gg>'\<leftarrow>\<oo>'\<rightarrow>\<ff>'\<rightarrow>\<bb>' >\<^sub>C\<^sub>F\<^sub>.\<^sub>p\<^sub>o X' \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>'\<^esub> \<CC>'
[PROOF STEP]
unfolding assms
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x : \<aa>\<leftarrow>\<gg>\<leftarrow>\<oo>\<rightarrow>\<ff>\<rightarrow>\<bb> >\<^sub>C\<^sub>F\<^sub>.\<^sub>p\<^sub>o X \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>
[PROOF STEP]
by (rule is_cat_pushout_axioms) |
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Data.Graph.Base where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Function
private variable ℓv ℓv' ℓv'' ℓe ℓe' ℓe'' ℓd ℓd' : Level
-- The type of directed multigraphs (with loops)
record Graph ℓv ℓe : Type (ℓ-suc (ℓ-max ℓv ℓe)) where
field
Obj : Type ℓv
Hom : Obj → Obj → Type ℓe
open Graph public
_ᵒᵖ : Graph ℓv ℓe → Graph ℓv ℓe
Obj (G ᵒᵖ) = Obj G
Hom (G ᵒᵖ) x y = Hom G y x
TypeGr : ∀ ℓ → Graph (ℓ-suc ℓ) ℓ
Obj (TypeGr ℓ) = Type ℓ
Hom (TypeGr ℓ) A B = A → B
-- Graph functors/homomorphisms
record GraphHom (G : Graph ℓv ℓe ) (G' : Graph ℓv' ℓe')
: Type (ℓ-suc (ℓ-max (ℓ-max ℓv ℓe) (ℓ-max ℓv' ℓe'))) where
field
_$_ : Obj G → Obj G'
_<$>_ : ∀ {x y : Obj G} → Hom G x y → Hom G' (_$_ x) (_$_ y)
open GraphHom public
GraphGr : ∀ ℓv ℓe → Graph _ _
Obj (GraphGr ℓv ℓe) = Graph ℓv ℓe
Hom (GraphGr ℓv ℓe) G G' = GraphHom G G'
-- Diagrams are (graph) functors with codomain Type
Diag : ∀ ℓd (G : Graph ℓv ℓe) → Type (ℓ-suc (ℓ-max (ℓ-max ℓv ℓe) (ℓ-suc ℓd)))
Diag ℓd G = GraphHom G (TypeGr ℓd)
record DiagMor {G : Graph ℓv ℓe} (F : Diag ℓd G) (F' : Diag ℓd' G)
: Type (ℓ-suc (ℓ-max (ℓ-max ℓv ℓe) (ℓ-suc (ℓ-max ℓd ℓd')))) where
field
nat : ∀ (x : Obj G) → F $ x → F' $ x
comSq : ∀ {x y : Obj G} (f : Hom G x y) → nat y ∘ F <$> f ≡ F' <$> f ∘ nat x
open DiagMor public
DiagGr : ∀ ℓd (G : Graph ℓv ℓe) → Graph _ _
Obj (DiagGr ℓd G) = Diag ℓd G
Hom (DiagGr ℓd G) = DiagMor
|
(*
Copyright (C) 2017 M.A.L. Marques
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 http://mozilla.org/MPL/2.0/.
*)
(* type: gga_exc *)
$define gga_x_pbe_sol_params
$include "gga_x_pbe.mpl"
q2d_cc := 100:
q2d_c1 := 0.5217:
q2d_f1 := s -> pbe_f0(s)*(q2d_cc - s^4) + q2d_c1*s^3.5*(1 + s^2):
q2d_f2 := s -> q2d_cc + s^6:
q2d_f := x -> q2d_f1(X2S*x)/q2d_f2(X2S*x):
f := (rs, zeta, xt, xs0, xs1) -> gga_exchange(q2d_f, rs, zeta, xs0, xs1):
|
[STATEMENT]
lemma array_foldr_foldr:
"array_foldr (\<lambda>n. f) (Array a) b = foldr f a b"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. array_foldr (\<lambda>n. f) (Array a) b = foldr f a b
[PROOF STEP]
by(simp add: array_foldr_def foldr_snd_zip) |
{-# OPTIONS --without-K --safe #-}
open import Categories.Category
open import Categories.Category.Monoidal.Core using (Monoidal)
open import Categories.Category.Monoidal.Symmetric
open import Data.Sum
module Categories.Category.Monoidal.CompactClosed {o ℓ e} {C : Category o ℓ e} (M : Monoidal C) where
open import Level
open import Categories.Functor.Bifunctor
open import Categories.NaturalTransformation.NaturalIsomorphism
open import Categories.Category.Monoidal.Rigid
open Category C
open Commutation C
record CompactClosed : Set (levelOfTerm M) where
field
symmetric : Symmetric M
rigid : LeftRigid M ⊎ RightRigid M
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Pseudo-registers and register states.
This library defines the type of pseudo-registers (also known as
"temporaries" in compiler literature) used in the RTL
intermediate language. We also define finite sets and finite maps
over pseudo-registers. *)
Require Import Coqlib.
Require Import AST.
Require Import Maps.
Require Import Ordered.
Require Import Sets.
Definition reg: Type := positive.
Module Reg.
Definition eq := peq.
Definition typenv := PMap.t typ.
End Reg.
(** Mappings from registers to some type. *)
Module Regmap := PMap.
Set Implicit Arguments.
Definition regmap_optget
(A: Type) (or: option reg) (dfl: A) (rs: Regmap.t A) : A :=
match or with
| None => dfl
| Some r => Regmap.get r rs
end.
Definition regmap_optset
(A: Type) (or: option reg) (v: A) (rs: Regmap.t A) : Regmap.t A :=
match or with
| None => rs
| Some r => Regmap.set r v rs
end.
Notation "a # b" := (Regmap.get b a) (at level 1).
Notation "a ## b" := (List.map (fun r => Regmap.get r a) b) (at level 1).
Notation "a # b <- c" := (Regmap.set b c a) (at level 1, b at next level).
(** Sets of registers *)
Module Regset := PSet.
|
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.nat.factorial
import Mathlib.PostPort
namespace Mathlib
/-!
# Binomial coefficients
This file contains a definition of binomial coefficients and simple lemmas (i.e. those not
requiring more imports).
## Main definition and results
- `nat.choose`: binomial coefficients, defined inductively
- `nat.choose_eq_factorial_div_factorial`: a proof that `choose n k = n! / (k! * (n - k)!)`
- `nat.choose_symm`: symmetry of binomial coefficients
- `nat.choose_le_succ_of_lt_half_left`: `choose n k` is increasing for small values of `k`
- `nat.choose_le_middle`: `choose n r` is maximised when `r` is `n/2`
-/
namespace nat
/-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial
coefficients. -/
def choose : ℕ → ℕ → ℕ :=
sorry
@[simp] theorem choose_zero_right (n : ℕ) : choose n 0 = 1 :=
nat.cases_on n (Eq.refl (choose 0 0)) fun (n : ℕ) => Eq.refl (choose (Nat.succ n) 0)
@[simp] theorem choose_zero_succ (k : ℕ) : choose 0 (Nat.succ k) = 0 :=
rfl
theorem choose_succ_succ (n : ℕ) (k : ℕ) : choose (Nat.succ n) (Nat.succ k) = choose n k + choose n (Nat.succ k) :=
rfl
theorem choose_eq_zero_of_lt {n : ℕ} {k : ℕ} : n < k → choose n k = 0 := sorry
@[simp] theorem choose_self (n : ℕ) : choose n n = 1 := sorry
@[simp] theorem choose_succ_self (n : ℕ) : choose n (Nat.succ n) = 0 :=
choose_eq_zero_of_lt (lt_succ_self n)
@[simp] theorem choose_one_right (n : ℕ) : choose n 1 = n := sorry
/- The `n+1`-st triangle number is `n` more than the `n`-th triangle number -/
theorem triangle_succ (n : ℕ) : (n + 1) * (n + 1 - 1) / bit0 1 = n * (n - 1) / bit0 1 + n := sorry
/-- `choose n 2` is the `n`-th triangle number. -/
theorem choose_two_right (n : ℕ) : choose n (bit0 1) = n * (n - 1) / bit0 1 := sorry
theorem choose_pos {n : ℕ} {k : ℕ} : k ≤ n → 0 < choose n k := sorry
theorem succ_mul_choose_eq (n : ℕ) (k : ℕ) : Nat.succ n * choose n k = choose (Nat.succ n) (Nat.succ k) * Nat.succ k := sorry
theorem choose_mul_factorial_mul_factorial {n : ℕ} {k : ℕ} : k ≤ n → choose n k * factorial k * factorial (n - k) = factorial n := sorry
theorem choose_eq_factorial_div_factorial {n : ℕ} {k : ℕ} (hk : k ≤ n) : choose n k = factorial n / (factorial k * factorial (n - k)) := sorry
theorem factorial_mul_factorial_dvd_factorial {n : ℕ} {k : ℕ} (hk : k ≤ n) : factorial k * factorial (n - k) ∣ factorial n := sorry
@[simp] theorem choose_symm {n : ℕ} {k : ℕ} (hk : k ≤ n) : choose n (n - k) = choose n k := sorry
theorem choose_symm_of_eq_add {n : ℕ} {a : ℕ} {b : ℕ} (h : n = a + b) : choose n a = choose n b := sorry
theorem choose_symm_add {a : ℕ} {b : ℕ} : choose (a + b) a = choose (a + b) b :=
choose_symm_of_eq_add rfl
theorem choose_symm_half (m : ℕ) : choose (bit0 1 * m + 1) (m + 1) = choose (bit0 1 * m + 1) m := sorry
theorem choose_succ_right_eq (n : ℕ) (k : ℕ) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := sorry
@[simp] theorem choose_succ_self_right (n : ℕ) : choose (n + 1) n = n + 1 := sorry
theorem choose_mul_succ_eq (n : ℕ) (k : ℕ) : choose n k * (n + 1) = choose (n + 1) k * (n + 1 - k) := sorry
/-! ### Inequalities -/
/-- Show that `nat.choose` is increasing for small values of the right argument. -/
theorem choose_le_succ_of_lt_half_left {r : ℕ} {n : ℕ} (h : r < n / bit0 1) : choose n r ≤ choose n (r + 1) := sorry
/-- Show that for small values of the right argument, the middle value is largest. -/
/-- `choose n r` is maximised when `r` is `n/2`. -/
theorem choose_le_middle (r : ℕ) (n : ℕ) : choose n r ≤ choose n (n / bit0 1) := sorry
|
Formal statement is: lemma homotopy_equivalent_space_sym: "X homotopy_equivalent_space Y \<longleftrightarrow> Y homotopy_equivalent_space X" Informal statement is: Two spaces are homotopy equivalent if and only if their homotopy types are isomorphic. |
Formal statement is: corollary Cauchy_contour_integral_circlepath: assumes "continuous_on (cball z r) f" "f holomorphic_on ball z r" "w \<in> ball z r" shows "contour_integral(circlepath z r) (\<lambda>u. f u/(u - w)^(Suc k)) = (2 * pi * \<i>) * (deriv ^^ k) f w / (fact k)" Informal statement is: If $f$ is a continuous function on the closed ball of radius $r$ centered at $z$ and holomorphic on the open ball of radius $r$ centered at $z$, then the $k$th derivative of $f$ at $w$ is equal to the $k$th derivative of $f$ at $w$ divided by $(2 \pi i)^k$ times the contour integral of $f(u)/(u - w)^{k + 1}$ around the circle of radius $r$ centered at $z$. |
[STATEMENT]
lemma ball_empty: "e \<le> 0 \<Longrightarrow> ball x e = {}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. e \<le> 0 \<Longrightarrow> ball x e = {}
[PROOF STEP]
by simp |
#ifndef KGS_GSLSVD_H
#define KGS_GSLSVD_H
#include "math/SVD.h"
#include <gsl/gsl_matrix.h>
class SVDGSL: public SVD {
public:
SVDGSL(gsl_matrix* M): SVD(M){}
protected:
void UpdateFromMatrix() override;
};
#endif //KGS_GSLSVD_H
|
function s=sprintsi(x,d,w)
%SPRINTSI Print X with SI multiplier S=(X,D,W)
% D is number of decimal places (+ve) or significant digits (-ve) [default=-3]
% |W| is total width including multiplier
% if W<=0 then trailing 0's will be eliminated
%
% Example: sprintsi(2345,-2) gives '2.3 k'
% Copyright (C) Mike Brookes 1998
% Version: $Id: sprintsi.m 4966 2014-08-05 18:20:41Z dmb $
%
% VOICEBOX is a MATLAB toolbox for speech processing.
% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You can obtain a copy of the GNU General Public License from
% http://www.gnu.org/copyleft/gpl.html or by writing to
% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<3 w=0; end;
if nargin<2 d=-3; end;
f='afpnum kMGT';
e=max(-18,min(12,floor(log10(abs(x)))));
k=floor(e/3);
dp=max([0 d 3*k-d-e-1]);
if w<=0 & dp
w=abs(w);
dp=max(find([1 mod(mod(round(x*10^(dp-3*k)),10^dp),10.^(dp:-1:1))]))-1;
end
if(k)
s=sprintf(sprintf('%%%d.%df %c',max(w-2,0),dp,f(k+7)),x*1e-3^k);
else
s=sprintf(sprintf('%%%d.%df ',max(w-1,0),dp),x*1e-3^k);
end
|
lemma power_eq_imp_eq_norm: fixes w :: "'a::real_normed_div_algebra" assumes eq: "w ^ n = z ^ n" and "n > 0" shows "norm w = norm z" |
= M @-@ 122 ( Michigan highway ) =
|
module Eq where
open import Prelude
open import T
open import Contexts
open import Eq.Defs
import Eq.KleeneTheory
import Eq.ObsTheory
import Eq.LogicalTheory
import Eq.Theory
open Eq.Defs public
open Eq.KleeneTheory public using (kleene-is-equivalence ; nats-halt)
open Eq.ObsTheory public using (obs-is-coarsest ; obs-is-con-congruence)
open Eq.LogicalTheory public using (log-is-con-congruence)
open Eq.Theory public
|
lemma open_affinity: fixes S :: "'a::real_normed_vector set" assumes "open S" "c \<noteq> 0" shows "open ((\<lambda>x. a + c *\<^sub>R x) ` S)" |
# 格子ボルツマン法による流体シミュレーション (Python)
>
- toc: true
- badges: true
- comments: true
- categories: [physics]
- author: 山拓
1年次の時のレポートを記事化したものです。元はProcessingによるシミュレーションでした。
## 格子ボルツマン法
### 計算方法の概要
流体解析(流体シミュレーション, computational fluid dynamics : CFD)を行う上では、連続体である流体の運動を離散化して計算する必要があります。このとき計算する方程式は次式で表される、流体の運動量保存則です.
$$
\begin{aligned}
\rho\frac{D\boldsymbol{v}}{Dt}=-\nabla P+\mu\nabla^2\boldsymbol{v}+\boldsymbol{f}
\end{aligned}
$$
この式はNavier-Stokes方程式と呼ばれます。ここで、$\rho$は密度、$P$は圧力、$\mu$は粘性抵抗、$\boldsymbol{f}$は外力であり、$\dfrac{D\boldsymbol{v}}{Dt}$は流れの速度場$\boldsymbol{v}$のLagrange微分です。よって
$$
\begin{aligned}
\frac{D\boldsymbol{v}}{Dt}=\frac{\partial\boldsymbol{v}}{\partial t}+(\boldsymbol{v}\cdot \nabla)\boldsymbol{v}
\end{aligned}
$$
が成り立ちます。また、質量の保存則として連続の式
$$
\begin{aligned}
\nabla\cdot\boldsymbol{v}=0
\end{aligned}
$$
があります。このような偏微分方程式で表される質量・運動量・エネルギーの保存則を離散化して数値的に解く方法としては有限差分法、有限要素法、有限体積法などがあります。また、流体を粒子の集合に分割し、流体の方程式に従う粒子の動きを計算します方法を粒子法と呼びます。今回用いる格子ボルツマン法(Lattice Boltzmann Method;LBM)とは、これらに属さない方法であり、流体を有限個の種類の速度を持つ仮想的な粒子の集合とみなし、それらの粒子の衝突と並進を計算します。流体を連続体ではなく粒子として扱う点は粒子法に似ていますが、LBMではあくまでも仮想的な粒子の分布を扱います。質量・運動量・エネルギーの保存則を巨視的(マクロ)な方程式であるとすれば、LBMが解く方程式は統計熱力学に基づく微視的 (ミクロ) な方程式と言えます。
### LBMの格子
LBMの格子は2次元では正方形、3次元では立方体を用いることが多いです。今回は、2次元平面における流れを考えるため、2D9Qモデルを用います。''2D''というのは2次元である事を意味し、''9Q''は粒子の取りうる速度$\boldsymbol{c}_i$の方向が9つあることを示しています (下図:LBMの格子(2D9Q)と9方向の速度 ($c=1$のとき))。
9つの速度は
$$
\begin{aligned}
\boldsymbol{c}_0&=(0,0)\ \ (i=0)\\
\boldsymbol{c}_i&=c\left[\cos\left(\frac{i-1}{2}\pi\right), \sin\left(\frac{i-1}{2}\pi\right)\right]\ \ (i=1,2,3,4)\\
\boldsymbol{c}_i&=\sqrt{2}c\left[\cos\left(\frac{i-1}{2}\pi+\frac{\pi}{4}\right), \sin\left(\frac{i-1}{2}\pi+\frac{\pi}{4}\right)\right]\ \ (i=5,6,7,8)
\end{aligned}
$$
で表されます。ここで$c$は定数ですが、実装上は簡単のため$c=1$とします。なお、この2D9Qモデルですが、数式で表記する場合には数字で方向をラベリングするほうがよいです。逆に実装する上では方角による方向のラベリングを行う方がミスがなくなりやすいでしょう (下図:2D9Q のラベリング)。
### 時間発展の式
座標$\boldsymbol{x}=(x,y)$、時刻$t$において速度$\boldsymbol{c}_i$を持つ粒子についての速度分布関数(確率密度関数)を$f_i(\boldsymbol{x},t)$とします。この速度分布関数$f_i(\boldsymbol{x},t)$は以下の格子ボルツマン方程式 (lattice Boltzmann equation) に従います.
$$
\begin{aligned}
\underbrace{f_i(\boldsymbol{x}+\boldsymbol{c}_i\Delta t,t+\Delta t)-f_i(\boldsymbol{x},t)}_{並進\textrm{(streaming)}}=\underbrace{\Omega_i[f_i(\boldsymbol{x},t)]}_{衝突\textrm{(collision)}}
\end{aligned}\tag{1}
$$
ただし、$\Delta t$は時間刻みです。速度$\boldsymbol{c}_i$の粒子は$\Delta t$で空間刻み$\Delta \boldsymbol{x}=\boldsymbol{c}_i\Delta t$だけ離れた格子に移動します。(1)式は初期条件さえ与えれば速度分布関数$f_i(\boldsymbol{x},t)$を陽的に計算できます。また上式の左辺は粒子の並進(streaming)を表し、右辺は粒子同士の衝突(collision)を表します。並進は下図のように計算します。
実装上では$\Omega_i$の取り扱いが重要とりますが、BGK (Bhatnagar-Gross-Krook)近似に基づく衝突則を用いられることが多いです。BGK近似モデルを用いたLBMの基礎方程式は次式で表されます。
$$
\begin{aligned}
f_i(\boldsymbol{x}+\boldsymbol{c}_i\Delta t,t+\Delta t)-f_i(\boldsymbol{x},t)=-\frac{1}{\tau}[f_i(\boldsymbol{x},t)-f_i^{\textrm{eq}}(\boldsymbol{x},t)]
\end{aligned}\tag{2}
$$
ここで、$\tau$は単一緩和時間です。 実装上は$\omega:=\dfrac{1}{\tau}$とします。なお、粘度(動粘性抵抗)$\nu$と単一緩和時間$\tau$および$\omega$との間には
$$
\tau=\frac{1}{\omega}\approx 3\nu+0.5\Delta t
$$
が成り立ちます。
### 平衡分布関数の計算
(2)式中の$f_i^{\textrm{eq}}(\boldsymbol{x},t)$を平衡分布関数と呼びます。ここでMaxwell-Boltzmann平衡分布は次式で表されます。
$$
g^{\textrm{eq}}(\boldsymbol{\xi})=\rho{\left(\frac{m}{2\pi k_BT}\right)}^{\frac{D}{2}} \exp\left(-\frac{m(\boldsymbol{c}_i-\boldsymbol{v})^2}{2k_BT}\right)\ \
$$
ただし、$\boldsymbol{\xi}:=\boldsymbol{c}_i-\boldsymbol{v}$とし、$D$ は次元数としました。上式を$\boldsymbol{v}$についてTayler展開することで平衡分布関数は求められ、次式で表されます。
$$
\begin{aligned}
f_i^{\textrm{eq}}(\boldsymbol{x},t)=w_i\rho\left[1+\frac{3(\boldsymbol{c}_i\cdot\boldsymbol{v})}{c^2}+\frac{9}{2c^4}(\boldsymbol{c}_i\cdot\boldsymbol{v})^2-\frac{3}{2c^2}\boldsymbol{v}^2\right]
\end{aligned}\tag{3}
$$
ただし、
$$
w_i = \begin{cases}
\frac{4}{9} & (i=0) \\
\frac{1}{9} & (i=1, 2, 3, 4) \\
\frac{1}{36} & (i=5, 6, 7, 8) \\
\end{cases}
$$
です。この$f_i^{\textrm{eq}}(\boldsymbol{x},t)$の計算のために密度$\rho(\boldsymbol{x},t)$と流速$\boldsymbol{v}(\boldsymbol{x},t)=(v_x(\boldsymbol{x},t), v_y(\boldsymbol{x},t))$を計算する必要がありますが、これらは次のように$f_i(\boldsymbol{x},t)$から求めることができます。
$$
\begin{align}
\rho(\boldsymbol{x},t)&=\sum_{i=0}^{8}f_i(\boldsymbol{x},t)\tag{4}\\
v_x(\boldsymbol{x},t)&=\frac{1}{\rho}\left[(f_1+f_5+f_8)-(f_3+f_6+f_7)\right]\tag{5}\\
v_y(\boldsymbol{x},t)&=\frac{1}{\rho}\left[(f_2+f_5+f_6)-(f_4+f_7+f_8)\right]\tag{6}
\end{align}
$$
これより、仮想粒子の速度$\boldsymbol{c}_i$と流速$\boldsymbol{v}(\boldsymbol{x}、t)$の内積$(\boldsymbol{c}_i\cdot\boldsymbol{v})$の計算ができます。また$c=1$とするので、最終的な実装上の式は次のようになります.
$$
\begin{array}[H]{c||c|c}
i&(\boldsymbol{c}_i\cdot\boldsymbol{v})&f_i^{\textrm{eq}}(\boldsymbol{x},t)\\ \hline
0&0&\frac{4}{9}\rho\left[1-\frac{3}{2}\boldsymbol{v}^2\right]\\
1(E)&v_x&\frac{1}{9}\rho\left[1+3v_x+\frac{9}{2}v_x^2-\frac{3}{2}\boldsymbol{v}^2\right]\\
2(N)&v_y&\frac{1}{9}\rho\left[1+3v_y+\frac{9}{2}v_y^2-\frac{3}{2}\boldsymbol{v}^2\right]\\
3(W)&-v_x&\frac{1}{9}\rho\left[1-3v_x+\frac{9}{2}v_x^2-\frac{3}{2}\boldsymbol{v}^2\right] \\
4(S)&-v_y&\frac{1}{9}\rho\left[1-3v_y+\frac{9}{2}v_y^2-\frac{3}{2}\boldsymbol{v}^2\right]\\
5(NE)&v_x+v_y&\frac{1}{36}\rho\left[1+3(v_x+v_y)+\frac{9}{2}(v_x+v_y)^2-\frac{3}{2}\boldsymbol{v}^2\right]\\
6(NW)&-v_x+v_y&\frac{1}{36}\rho\left[1+3(-v_x+v_y)+\frac{9}{2}(-v_x+v_y)^2-\frac{3}{2}\boldsymbol{v}^2\right]\\
7(SW)&-v_x-v_y&\frac{1}{36}\rho\left[1-3(v_x+v_y)+\frac{9}{2}(v_x+v_y)^2-\frac{3}{2}\boldsymbol{v}^2\right]\\
8(SE)&v_x-v_y&\frac{1}{36}\rho\left[1+3(v_x-v_y)+\frac{9}{2}(v_x-v_y)^2-\frac{3}{2}\boldsymbol{v}^2\right]\\ \hline
\end{array}
$$
### 境界条件
粒子と障壁(barrier)との衝突を考えます。滑りなし壁の条件($\boldsymbol{v}=0$)を簡易に実装するために用いられているのが、**bounce-back条件** です。障害物に指定された格子点に仮想粒子が並進運動で侵入した場合、bounce-back条件では、仮想粒子をその侵入方向と180°反対の方向に跳ね返します (次図)。なお、今回は障害物の境界は格子点の中央に存在するとします。
### 計算のアルゴリズム
アルゴリズムは以下のようになります.
1. 密度$\rho$, 流速$\boldsymbol{v}$, 速度分布関数$f_i$, 平衡分布関数$f$を初期化します。今回の場合は、左から右に流れが生じている場合を考えるので$\boldsymbol{v}$は$x$方向のみ大きさを持ちます。また、計算開始前、分布関数は平衡に達していたとします。よって次式のようになります。
$$
\begin{align}
\rho(\boldsymbol{x},t)&:=1\tag{7}\\
\boldsymbol{v}(\boldsymbol{x},t)=(v_x, v_y)&:=(u,0)\ \ (u:定数)\tag{8}\\
f_i(\boldsymbol{x},t=0)&:=f_i^{\textrm{eq}}(\boldsymbol{x},t=0)\tag{9}\\
\end{align}
$$
1. 密度$\rho$, 流速$\boldsymbol{v}$を$f_i(\boldsymbol{x},t)$から(4), (5), (6)式によって求めます。
1. 平衡分布関数$f_i^{\textrm{eq}}(\boldsymbol{x},t)$を(3)式より計算します。
1. (**Streaming Step**) (2)式の左辺により、並進後の分布関数を次のように計算します。
$$
\begin{aligned}
f_i(\boldsymbol{x}+\boldsymbol{c}_i\Delta t,t+\Delta t)=f_i^*(\boldsymbol{x},t)\\
\end{aligned}\tag{10}
$$
1. (**Bounce Step**) 5において並進した格子に障害物(境界)が存在した場合、bounce-back条件により、修正します。
1. (**Collision Step**) 仮想粒子の衝突を(2)式の右辺により次のように計算します。ただし、$f_i^*(\boldsymbol{x},t)$は仮想粒子が衝突し、並進する前の分布関数です。
$$
\begin{aligned}
f_i^*(\boldsymbol{x},t)=f_i(\boldsymbol{x},t)-\frac{1}{\tau}[f_i(\boldsymbol{x},t)-f_i^{\textrm{eq}}(\boldsymbol{x},t)]\\
\end{aligned}\tag{11}
$$
1. 2~6を繰り返します。
## Pythonでの実装
ここからはPythonでの実装について解説していきます。なお、コードは[Fluid Dynamics Simulation](http://physics.weber.edu/schroeder/fluids/)を参考にしています。Processing版はOpenProcessingで公開しています (<https://www.openprocessing.org/sketch/497312/>)。
ライブラリをimportします。このとき、`%matplotlib nbagg`を付ければipynb上でアニメーションが実行できます。
```python
%matplotlib nbagg
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
```
各種定数を定義していきます。
```python
# Define constants:
height = 80 # lattice dimensions
width = 200
viscosity = 0.02 # fluid viscosity
omega = 1 / (3*viscosity + 0.5) # "relaxation" parameter
u0 = 0.1 # initial and in-flow speed
four9ths = 4.0/9.0 # abbreviations for lattice-Boltzmann weight factors
one9th = 1.0/9.0
one36th = 1.0/36.0
```
格子の初期化を(3)式に基づいて行います。
```python
# Initialize all the arrays to steady rightward flow:
n0 = four9ths * (np.ones((height,width)) - 1.5*u0**2) # particle densities along 9 directions
nN = one9th * (np.ones((height,width)) - 1.5*u0**2)
nS = one9th * (np.ones((height,width)) - 1.5*u0**2)
nE = one9th * (np.ones((height,width)) + 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nW = one9th * (np.ones((height,width)) - 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nNE = one36th * (np.ones((height,width)) + 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nSE = one36th * (np.ones((height,width)) + 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nNW = one36th * (np.ones((height,width)) - 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nSW = one36th * (np.ones((height,width)) - 3*u0 + 4.5*u0**2 - 1.5*u0**2)
rho = n0 + nN + nS + nE + nW + nNE + nSE + nNW + nSW # macroscopic density
ux = (nE + nNE + nSE - nW - nNW - nSW) / rho # macroscopic x velocity
uy = (nN + nNE + nNW - nS - nSE - nSW) / rho # macroscopic y velocity
```
障害物の位置を初期化します。このとき、障害物内の粒子の数は0とします。
```python
# Initialize barriers:
barrier = np.zeros((height,width), bool) # True wherever there's a barrier
barrier[int((height/2)-8):int((height/2)+8), int(height/2)] = True # simple linear barrier
barrierN = np.roll(barrier, 1, axis=0) # sites just north of barriers
barrierS = np.roll(barrier, -1, axis=0) # sites just south of barriers
barrierE = np.roll(barrier, 1, axis=1) # etc.
barrierW = np.roll(barrier, -1, axis=1)
barrierNE = np.roll(barrierN, 1, axis=1)
barrierNW = np.roll(barrierN, -1, axis=1)
barrierSE = np.roll(barrierS, 1, axis=1)
barrierSW = np.roll(barrierS, -1, axis=1)
```
Streaming StepとBounce-back stepです。`np.roll`により仮想粒子を移動させます。このとき, 粒子の進行方向と逆向きの順で格子を選び, 分布関数を更新します.
```python
# Move all particles by one step along their directions of motion (pbc):
def stream():
global nN, nS, nE, nW, nNE, nNW, nSE, nSW
nN = np.roll(nN, 1, axis=0) # axis 0 is north-south; + direction is north
nNE = np.roll(nNE, 1, axis=0)
nNW = np.roll(nNW, 1, axis=0)
nS = np.roll(nS, -1, axis=0)
nSE = np.roll(nSE, -1, axis=0)
nSW = np.roll(nSW, -1, axis=0)
nE = np.roll(nE, 1, axis=1) # axis 1 is east-west; + direction is east
nNE = np.roll(nNE, 1, axis=1)
nSE = np.roll(nSE, 1, axis=1)
nW = np.roll(nW, -1, axis=1)
nNW = np.roll(nNW, -1, axis=1)
nSW = np.roll(nSW, -1, axis=1)
# Use tricky boolean arrays to handle barrier collisions (bounce-back):
nN[barrierN] = nS[barrier]
nS[barrierS] = nN[barrier]
nE[barrierE] = nW[barrier]
nW[barrierW] = nE[barrier]
nNE[barrierNE] = nSW[barrier]
nNW[barrierNW] = nSE[barrier]
nSE[barrierSE] = nNW[barrier]
nSW[barrierSW] = nNE[barrier]
```
Collide stepの関数を定義します。
```python
# Collide particles within each cell to redistribute velocities (could be optimized a little more):
def collide():
global rho, ux, uy, n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW
rho = n0 + nN + nS + nE + nW + nNE + nSE + nNW + nSW
ux = (nE + nNE + nSE - nW - nNW - nSW) / rho
uy = (nN + nNE + nNW - nS - nSE - nSW) / rho
ux2 = ux * ux # pre-compute terms used repeatedly...
uy2 = uy * uy
u2 = ux2 + uy2
omu215 = 1 - 1.5*u2 # "one minus u2 times 1.5"
uxuy = ux * uy
n0 = (1-omega)*n0 + omega * four9ths * rho * omu215
nN = (1-omega)*nN + omega * one9th * rho * (omu215 + 3*uy + 4.5*uy2)
nS = (1-omega)*nS + omega * one9th * rho * (omu215 - 3*uy + 4.5*uy2)
nE = (1-omega)*nE + omega * one9th * rho * (omu215 + 3*ux + 4.5*ux2)
nW = (1-omega)*nW + omega * one9th * rho * (omu215 - 3*ux + 4.5*ux2)
nNE = (1-omega)*nNE + omega * one36th * rho * (omu215 + 3*(ux+uy) + 4.5*(u2+2*uxuy))
nNW = (1-omega)*nNW + omega * one36th * rho * (omu215 + 3*(-ux+uy) + 4.5*(u2-2*uxuy))
nSE = (1-omega)*nSE + omega * one36th * rho * (omu215 + 3*(ux-uy) + 4.5*(u2-2*uxuy))
nSW = (1-omega)*nSW + omega * one36th * rho * (omu215 + 3*(-ux-uy) + 4.5*(u2+2*uxuy))
# Force steady rightward flow at ends (no need to set 0, N, and S components):
nE[:,0] = one9th * (1 + 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nW[:,0] = one9th * (1 - 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nNE[:,0] = one36th * (1 + 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nSE[:,0] = one36th * (1 + 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nNW[:,0] = one36th * (1 - 3*u0 + 4.5*u0**2 - 1.5*u0**2)
nSW[:,0] = one36th * (1 - 3*u0 + 4.5*u0**2 - 1.5*u0**2)
```
次に流速$\boldsymbol{v}$の回転$\textrm{rot}\ \boldsymbol{v}$の$z$成分を計算する関数を定義します。$\textrm{rot}\ \boldsymbol{v}$の$z$成分は
$$
(\textrm{rot}\ \boldsymbol{v})_z=\frac{\partial v_y}{\partial x}-\frac{\partial v_x}{\partial y}
$$
で表されます。偏微分項の中心差分を取ると,
$$
(\textrm{rot}\ \boldsymbol{v})_z\approx\frac{v_y(x+\epsilon,y)-v_y(x-\epsilon, y)}{2\epsilon}-\frac{v_x(x, y+\epsilon)-v_x(x, y-\epsilon)}{2\epsilon}
$$
となります。流れの速度場が格子状に離散化されていることから, $\epsilon=1$とすべきであるので次式のように計算されます。
$$
(\textrm{rot}\ \boldsymbol{v})_z\approx\frac{v_y(x+1,y)-v_y(x-1, y)}{2}-\frac{v_x(x, y+1)-v_x(x, y-1)}{2}
$$
なお、実装上は2で割ることを省略しています。
```python
# Compute rot of the macroscopic velocity field:
def rot(ux, uy):
return np.roll(uy,-1,axis=1) - np.roll(uy,1,axis=1) - np.roll(ux,-1,axis=0) + np.roll(ux,1,axis=0)
```
シミュレーションのメインの関数です。`nextFrame`関数を実行することでシミュレーションが進行します。
```python
# Here comes the graphics and animation
theFig = plt.figure(figsize=(8,3))
fluidImage = plt.imshow(rot(ux, uy), origin='lower', norm=plt.Normalize(-.1,.1),
cmap=plt.get_cmap('jet'), interpolation='none')
bImageArray = np.zeros((height, width, 4), np.uint8)
bImageArray[barrier,3] = 255
barrierImage = plt.imshow(bImageArray, origin='lower', interpolation='none')
def nextFrame(arg):
for step in range(20):
stream()
collide()
fluidImage.set_array(rot(ux, uy))
return (fluidImage, barrierImage) # return the figure elements to redraw
animate = animation.FuncAnimation(theFig, nextFrame, interval=1, blit=True)
plt.show()
```
<IPython.core.display.Javascript object>
## 参考文献
- Schroeder, D., [Fluid Dynamics Simulation](http://physics.weber.edu/schroeder/fluids/), (2018年1月30日閲覧)
- Guo, Z. and Shu, C., 2013, Lattice Boltzmann method and its applications in engineering, World Scientific (Singapore)
- 蔦原 道久, 他2名, 1999, 『格子気体法・格子ボルツマン法―新しい数値流体力学の手法』, コロナ社
- 太田 光浩, 他4名, 2015, 『混相流の数値シミュレーション 』, 丸善出版
- Bao, Y. and Meskas, J., 2011。[Lattice Boltzmann Method for Fluid Simulations](https://cims.nyu.edu/~billbao/report930.pdf), (2018年1月30日閲覧)
- 立石 絢也, 樫山 和男, 2006, 「非圧縮性粘性流体解析のためのCIVA-格子ボルツマン法の精度と安定性」, 『日本計算工学会論文集』, 2006年度号, No.20060008
|
-- Should fail with S i != i
module Issue216 where
open import Common.Level
Foo : {i : Level} → Set i
Foo {i} = (R : Set i) → R
|
import torch
from torch.utils.data import Dataset
from torch_geometric.io import read_off
import numpy as np
class GestureRecdata(Dataset):
def __init__(self, data,label):
self.data = torch.tensor(data)
self.label = torch.tensor(label,dtype=torch.int64)
def __len__(self):
return len(self.data)
def __getitem__(self, index):
target = self.label[index]
data_val = self.data[index]
return data_val, target
|
The trial will be run by biotech company Bioquark, which is primarily focused on developing "combinatorial biologics" that get to the heart of disease reversal rather than just treating the symptoms. They believe that stem cells can be used as a kind of "reset button" for the body, erasing cell damage and stimulating tissue regeneration. They claim that their research could potentially lead to "complex tissue and organ regeneration, disease reversion, and even biological age reversal."
"This represents the first trial of its kind and another step towards the eventual reversal of death in our lifetime," Dr Ira Pastor, the CEO of Bioquark, told The Telegraph. "To undertake such a complex initiative, we are combining biologic regenerative medicine tools with other existing medical devices typically used for stimulation of the central nervous system, in patients with other severe disorders of consciousness.
We hope to see results within the first two to three months."
"It is a long term vision of ours that a full recovery in such patients is a possibility, although that is not the focus of this first study – but it is a bridge to that eventuality."
Some scientists are already expressing doubt that this could lead to anything resembling a genuine recovery for braindead patients, as studies have shown that humans' capacity for regeneration is somewhat limited. However, even if the regeneration aspect of the project isn't quite successful, the study will still shed light on the process of brain death, and possibly spur innovation in the treatment of debilitating neurological diseases.
"Through our study, we will gain unique insights into the state of human brain death, which will have important connections to future therapeutic development for other severe disorders of consciousness, such as coma, and the vegetative and minimally conscious states, as well as a range of degenerative CNS conditions, including Alzheimer's and Parkinson's disease," said Dr Sergei Paylian, Founder, President, and Chief Science Officer of Bioquark. |
[STATEMENT]
lemma max_test_bit: "bit (- 1::'a::len word) n \<longleftrightarrow> n < LENGTH('a)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. bit (- 1) n = (n < LENGTH('a))
[PROOF STEP]
by (fact nth_minus1) |
Require Import Coqlib.
Require Import Any.
Require Import STS.
Require Import Behavior.
Require Import ModSem.
Require Import Skeleton.
Require Import PCM.
Require Import HoareDef.
Require Import ProofMode.
Require Import SimModSem.
Require Import STB.
Set Implicit Arguments.
Section AUX.
Definition invRA: URA.t := Excl.t unit.
Definition inv_token: (@URA.car invRA) := Some tt.
Context `{Σ: GRA.t}.
Context `{@GRA.inG invRA Σ}.
Definition inv_closed: iProp := OwnM inv_token%I.
Lemma inv_closed_unique
:
inv_closed -∗ inv_closed -∗ False
.
Proof.
unfold inv_closed, inv_token.
iIntros "H0 H1".
iCombine "H0 H1" as "H". iOwnWf "H" as WF. exfalso.
repeat ur in WF. ss.
Qed.
Definition inv_le
A (le: A -> A -> Prop)
:
(A + Any.t * Any.t) -> (A + Any.t * Any.t) -> Prop :=
fun x0 x1 =>
match x0, x1 with
| inl a0, inl a1 => le a0 a1
| inr st0, inr st1 => st0 = st1
| _, _ => False
end.
Lemma inv_le_PreOrder A (le: A -> A -> Prop)
(PREORDER: PreOrder le)
:
PreOrder (inv_le le).
Proof.
econs.
{ ii. destruct x; ss. refl. }
{ ii. destruct x, y, z; ss.
{ etrans; et. }
{ subst. auto. }
}
Qed.
Definition mk_fspec_inv (fsp: fspec): fspec :=
@mk_fspec
_
(meta fsp)
fsp.(measure)
(fun mn x varg_src varg_tgt =>
inv_closed ** (precond fsp) mn x varg_src varg_tgt)
(fun mn x vret_src vret_tgt =>
inv_closed ** (postcond fsp) mn x vret_src vret_tgt).
Lemma fspec_weaker_fspec_inv_weakker (fsp0 fsp1: fspec)
(WEAKER: fspec_weaker fsp0 fsp1)
:
fspec_weaker (mk_fspec_inv fsp0) (mk_fspec_inv fsp1).
Proof.
ii. exploit WEAKER. i. des. exists x_tgt. esplits; ss; et.
{ ii. iIntros "[INV H]". iSplitL "INV"; ss.
iApply PRE. iExact "H". }
{ ii. iIntros "[INV H]". iSplitL "INV"; ss.
iApply POST. iExact "H". }
Qed.
End AUX.
|
-- @@stderr --
dtrace: failed to compile script test/unittest/lexer/err.D_SYNTAX.paren2.d: [D_SYNTAX] line 17: syntax error near "}"
|
import numpy as np
from .atombase import AtomBase
from ..electools import ElecQMQM
class QMAtoms(AtomBase):
"""Class to hold QM atoms."""
def __init__(self, x, y, z, element, charge, index, cell_basis):
super(QMAtoms, self).__init__(x, y, z, charge, index)
self._atoms.element = element
self._elec = ElecQMQM(self, cell_basis)
# Set initial QM energy and charges
self._qm_energy = 0.0
self._qm_pol_energy = 0.0
self._qm_charge = np.zeros(self.n_atoms)
# Set the box for PBC conditions
self._box = cell_basis
@property
def qm_energy(self):
return self._qm_energy
@qm_energy.setter
def qm_energy(self, energy):
self._qm_energy = energy
@property
def qm_charge(self):
return self._get_property(self._qm_charge)
@qm_charge.setter
def qm_charge(self, charge):
self._set_property(self._qm_charge, charge)
@property
def qm_pol_energy(self):
return self._qm_pol_energy
@qm_pol_energy.setter
def qm_pol_energy(self, pol_energy):
self._qm_pol_energy = pol_energy
@property
def box(self):
return self._box
@box.setter
def box(self, cell_basis):
self._box = cell_basis
|
Formal statement is: corollary real_linearD: fixes f :: "real \<Rightarrow> real" assumes "linear f" obtains c where "f = (*) c" Informal statement is: If $f$ is a linear function from $\mathbb{R}$ to $\mathbb{R}$, then there exists a real number $c$ such that $f(x) = cx$ for all $x \<in> \mathbb{R}$. |
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
# tag to force GT_NthLoop expansions to be smaller, results in less
# ruletrees being generated, which is sometimes desirable.
#
# NOTE: it is used in the GT_NthLoop rule at currently needs no
# parameters
Class(ALimitNthLoop, AGenericTag);
# Input/Output tag which describes the input/outputs of the given block.
# Designed with OL in mind, although written for transforms.
#
# You initialize the tag with a list of pairs which specify which input
# and outputs are connected.
#
# In the case of transforms, this means AIO([1,1]) is the only acceptable
# input. And it means the block is done inplace. Normal operation is
# out-of-place.
#
# for OL, this can be AIO([1,3],[2,1]), which means input1 -> output3 and
# input2 -> output1
#
Class(AIO, AGenericTag);
|
# FEEDBACK CONTROL EXAMPLE
This notebook explores feedback control for the glycolytic oscillations model of Jenna Wolf.
# Preliminaries
```python
from controlSBML.control_extensions.state_space_tf import StateSpaceTF
import controlSBML as ctl
import control
import numpy as np
import pandas as pd
import sympy
import tellurium as te
import matplotlib.pyplot as plt
```
```python
TIMES = [0.1*v for v in range(51)]
```
```python
CTLSB = ctl.ControlSBML("https://www.ebi.ac.uk/biomodels/model/download/BIOMD0000000206.2?filename=BIOMD0000000206_url.xml",
input_names=["at"])
```
```python
CTLSB.plotTrueModel(ylim=[0, 10], figsize=(5,5))
```
```python
# at: ATP
# na: NAD+
# s4: 3-Phospho-D-glycerate
# s5: pyruvic acid
print(CTLSB.antimony)
```
// Created by libAntimony v2.12.0
model *Wolf2000_Glycolytic_Oscillations()
// Compartments and Species:
compartment compartment_;
species s1 in compartment_, at_ in compartment_, s2 in compartment_, s3 in compartment_;
species na in compartment_, s4 in compartment_, s5 in compartment_, s6 in compartment_;
species s6o in compartment_;
// Reactions:
v1: s1 + 2 at_ -> s2; compartment_*k1*s1*at_/(1 + (at_/ki)^n);
v2: s2 -> 2 s3; compartment_*k2*s2;
v3: s3 + na -> s4 + at_; compartment_*((k31*k32*s3*na*(atot - at_) - k33*k34*s4*at_*(ntot - na))/(k33*(ntot - na) + k32*(atot - at_)));
v4: s4 -> s5 + at_; compartment_*k4*s4*(atot - at_);
v5: s5 -> s6; compartment_*k5*s5;
v7: at_ -> ; compartment_*k7*at_;
v8: s3 -> na; compartment_*k8*s3*(ntot - na);
v9: s6o -> ; compartment_*k9*s6o;
v10: s6 -> 0.1 s6o; compartment_*k10*(s6 - s6o);
v6: s6 -> na; compartment_*k6*s6*(ntot - na);
v0: -> s1; compartment_*k0;
// Species initializations:
s1 = 1;
at_ = 2;
s2 = 5;
s3 = 0.6;
na = 0.6;
s4 = 0.7;
s5 = 8;
s6 = 0.08;
s6o = 0.02;
// Compartment initializations:
compartment_ = 1;
// Variable initializations:
k0 = 50;
k0 has mM_min_1;
k1 = 550;
k1 has mM_1_min_1;
k2 = 9.8;
k2 has min_1;
k31 = 323.8;
k31 has mM_1_min_1;
k33 = 57823.1;
k33 has mM_1_min_1;
k32 = 76411.1;
k32 has mM_1_min_1;
k34 = 23.7;
k34 has mM_1_min_1;
k4 = 80;
k4 has mM_1_min_1;
k5 = 9.7;
k5 has min_1;
k6 = 2000;
k6 has mM_1_min_1;
k7 = 28;
k7 has min_1;
k8 = 85.7;
k8 has mM_1_min_1;
k9 = 80;
k9 has min_1;
k10 = 375;
k10 has min_1;
atot = 4;
atot has mM;
ntot = 1;
ntot has mM;
n = 4;
n has dimensionless;
ki = 1;
ki has mM;
// Other declarations:
const compartment_, k0, k1, k2, k31, k33, k32, k34, k4, k5, k6, k7, k8;
const k9, k10, atot, ntot, n, ki;
// Unit definitions:
unit substance = 1e-3 mole;
unit time_unit = 60 second;
unit mM = 1e-3 mole / litre;
unit mM_min_1 = 1e-3 mole / (litre * 60 second);
unit min_1 = 1 / 60 second;
unit mM_1_min_1 = litre / (1e-3 mole * 60 second);
// Display Names:
substance is "milli mole";
time_unit is "min";
s1 is "Glucose";
at_ is "ATP";
s2 is "F16P";
s3 is "Triose_Gly3Phos_DHAP";
na is "NAD";
s4 is "3PG";
s5 is "Pyruvate";
s6 is "Acetaldehyde";
s6o is "extracellular acetaldehyde";
// CV terms:
s1 identity "http://identifiers.org/obo.chebi/CHEBI:17234",
"http://identifiers.org/kegg.compound/C00293"
at_ identity "http://identifiers.org/obo.chebi/CHEBI:15422",
"http://identifiers.org/kegg.compound/C00002"
s2 identity "http://identifiers.org/obo.chebi/CHEBI:16905",
"http://identifiers.org/kegg.compound/C05378"
s3 part "http://identifiers.org/obo.chebi/CHEBI:16108",
"http://identifiers.org/obo.chebi/CHEBI:29052",
"http://identifiers.org/kegg.compound/C00111",
"http://identifiers.org/kegg.compound/C00118"
na identity "http://identifiers.org/obo.chebi/CHEBI:15846",
"http://identifiers.org/kegg.compound/C00003"
s4 identity "http://identifiers.org/obo.chebi/CHEBI:17794",
"http://identifiers.org/kegg.compound/C00197"
s5 identity "http://identifiers.org/kegg.compound/C00022",
"http://identifiers.org/chebi/CHEBI:32816"
s5 identity "http://identifiers.org/obo.chebi/CHEBI:15361"
s6 identity "http://identifiers.org/obo.chebi/CHEBI:15343",
"http://identifiers.org/kegg.compound/C00084"
s6o identity "http://identifiers.org/obo.chebi/CHEBI:15343",
"http://identifiers.org/kegg.compound/C00084"
v1 part "http://identifiers.org/kegg.reaction/R00756",
"http://identifiers.org/kegg.reaction/R00299"
v1 part "http://identifiers.org/ec-code/2.7.1.11",
"http://identifiers.org/ec-code/5.3.1.9"
v2 identity "http://identifiers.org/ec-code/4.1.2.13",
"http://identifiers.org/kegg.reaction/R01070"
v3 part "http://identifiers.org/ec-code/2.7.2.3",
"http://identifiers.org/ec-code/1.2.1.12"
v4 part "http://identifiers.org/kegg.reaction/R00658",
"http://identifiers.org/kegg.reaction/R00200"
v4 part "http://identifiers.org/ec-code/2.7.1.40"
v5 hypernym "http://identifiers.org/ec-code/4.1.1.1",
"http://identifiers.org/kegg.reaction/R00224"
v7 hypernym "http://identifiers.org/obo.go/GO:0006754"
v8 part "http://identifiers.org/kegg.reaction/R05679"
v9 hypernym "http://identifiers.org/obo.go/GO:0046187"
v6 hypernym "http://identifiers.org/ec-code/1.1.1.71",
"http://identifiers.org/kegg.reaction/R00754"
v0 hypernym "http://identifiers.org/obo.go/GO:0046323"
end
Wolf2000_Glycolytic_Oscillations is "Wolf2000_Glycolytic_Oscillations"
Wolf2000_Glycolytic_Oscillations model_entity_is "http://identifiers.org/biomodels.db/MODEL3352181362"
Wolf2000_Glycolytic_Oscillations model_entity_is "http://identifiers.org/biomodels.db/BIOMD0000000206"
Wolf2000_Glycolytic_Oscillations description "http://identifiers.org/pubmed/10692304"
Wolf2000_Glycolytic_Oscillations taxon "http://identifiers.org/taxonomy/4932"
Wolf2000_Glycolytic_Oscillations hypernym "http://identifiers.org/obo.go/GO:0006096"
Wolf2000_Glycolytic_Oscillations identity "http://identifiers.org/kegg.pathway/sce00010"
# Controller Construction
## Reaction Network
v1: s1 + 2 at_ -> s2; compartment_*k1*s1*at_/(1 + (at_/ki)^n);
v2: s2 -> 2 s3; compartment_*k2*s2;
v3: s3 + na -> s4 + at_; compartment_*((k31*k32*s3*na*(atot - at_)
- k33*k34*s4*at_*(ntot - na))/(k33*(ntot - na) + k32*(atot - at_)));
v4: s4 -> s5 + at_; compartment_*k4*s4*(atot - at_);
v5: s5 -> s6; compartment_*k5*s5;
v7: at_ -> ; compartment_*k7*at_;
v8: s3 -> na; compartment_*k8*s3*(ntot - na);
v9: s6o -> ; compartment_*k9*s6o;
v10: s6 -> 0.1 s6o; compartment_*k10*(s6 - s6o);
v6: s6 -> na; compartment_*k6*s6*(ntot - na);
v0: -> s1; compartment_*k0;
## Regulating Pyruvate (``s5``)
```python
URL_206 = "https://www.ebi.ac.uk/biomodels/model/download/BIOMD0000000206.2?filename=BIOMD0000000206_url.xml"
CTLSB = ctl.ControlSBML(URL_206, input_names=["at"], output_names=["s5"])
CTLSB.plotTrueModel(names=["s5"], ylim=[0, 10], title="Uncontrolled", figsize=(5,2))
```
```python
CTLSB = ctl.ControlSBML(URL_206, input_names=["at"], output_names=["s5"])
sys = CTLSB.makeNonlinearIOSystem("sys")
```
```python
ref = [6] # Desired value of pyruvate
def outfcn(t, x, u, _):
return 0.01*(ref - u)
controller = control.NonlinearIOSystem(
None,
outfcn,
inputs=['in'],
outputs=['out'], name='controller')
```
```python
# Create the closed loop system
closed = control.interconnect(
[sys, controller], # systems
connections=[
['sys.at', 'controller.out'],
['controller.in', 'sys.s5'],
],
inplist=["controller.in"],
outlist=["sys.s5"],
)
```
```python
times = TIMES
result = control.input_output_response(closed, times, X0=ctl.makeStateVector(closed))
ser = ctl.mat2DF(result.outputs, row_names=times)
_, ax = plt.subplots(1, figsize=(5,2))
ax.plot(ser.index, ser.values)
ax.set_ylim([0, 10])
ax.set_xlabel("time")
_ = ax.set_title("Controlled")
ax.legend(["s5"], fontsize=14)
```
|
/-
Copyright (c) 2017 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Mario Carneiro
-/
import data.real.sqrt
/-!
# The complex numbers
The complex numbers are modelled as ℝ^2 in the obvious way and it is shown that they form a field
of characteristic zero. The result that the complex numbers are algebraically closed, see
`field_theory.algebraic_closure`.
-/
open_locale big_operators
/-! ### Definition and basic arithmmetic -/
/-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/
structure complex : Type :=
(re : ℝ) (im : ℝ)
notation `ℂ` := complex
namespace complex
open_locale complex_conjugate
noncomputable instance : decidable_eq ℂ := classical.dec_eq _
/-- The equivalence between the complex numbers and `ℝ × ℝ`. -/
@[simps] def equiv_real_prod : ℂ ≃ (ℝ × ℝ) :=
{ to_fun := λ z, ⟨z.re, z.im⟩,
inv_fun := λ p, ⟨p.1, p.2⟩,
left_inv := λ ⟨x, y⟩, rfl,
right_inv := λ ⟨x, y⟩, rfl }
@[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z
| ⟨a, b⟩ := rfl
@[ext]
theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w
| ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl
theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im :=
⟨λ H, by simp [H], and.rec ext⟩
instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩
@[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl
@[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl
lemma of_real_def (r : ℝ) : (r : ℂ) = ⟨r, 0⟩ := rfl
@[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w :=
⟨congr_arg re, congr_arg _⟩
theorem of_real_injective : function.injective (coe : ℝ → ℂ) :=
λ z w, congr_arg re
instance : can_lift ℂ ℝ :=
{ cond := λ z, z.im = 0,
coe := coe,
prf := λ z hz, ⟨z.re, ext rfl hz.symm⟩ }
/-- The product of a set on the real axis and a set on the imaginary axis of the complex plane,
denoted by `s ×ℂ t`. -/
def _root_.set.re_prod_im (s t : set ℝ) : set ℂ := re ⁻¹' s ∩ im ⁻¹' t
infix ` ×ℂ `:72 := set.re_prod_im
instance : has_zero ℂ := ⟨(0 : ℝ)⟩
instance : inhabited ℂ := ⟨0⟩
@[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl
@[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl
@[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl
@[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj
theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero
instance : has_one ℂ := ⟨(1 : ℝ)⟩
@[simp] lemma one_re : (1 : ℂ).re = 1 := rfl
@[simp] lemma one_im : (1 : ℂ).im = 0 := rfl
@[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl
@[simp] theorem of_real_eq_one {z : ℝ} : (z : ℂ) = 1 ↔ z = 1 := of_real_inj
theorem of_real_ne_one {z : ℝ} : (z : ℂ) ≠ 1 ↔ z ≠ 1 := not_congr of_real_eq_one
instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩
@[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl
@[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl
@[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl
@[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl
@[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _
@[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _
@[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s :=
ext_iff.2 $ by simp
@[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r :=
ext_iff.2 $ by simp [bit0]
@[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r :=
ext_iff.2 $ by simp [bit1]
instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩
@[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl
@[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl
@[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp
instance : has_sub ℂ := ⟨λ z w, ⟨z.re - w.re, z.im - w.im⟩⟩
instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩
@[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl
@[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl
@[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp
lemma of_real_mul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp
lemma of_real_mul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp
lemma of_real_mul' (r : ℝ) (z : ℂ) : (↑r * z) = ⟨r * z.re, r * z.im⟩ :=
ext (of_real_mul_re _ _) (of_real_mul_im _ _)
/-! ### The imaginary unit, `I` -/
/-- The imaginary unit. -/
def I : ℂ := ⟨0, 1⟩
@[simp] lemma I_re : I.re = 0 := rfl
@[simp] lemma I_im : I.im = 1 := rfl
@[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp
lemma I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ :=
ext_iff.2 $ by simp
lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm
lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I :=
ext_iff.2 $ by simp
@[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z :=
ext_iff.2 $ by simp
/-! ### Commutative ring instance and lemmas -/
/- We use a nonstandard formula for the `ℕ` and `ℤ` actions to make sure there is no
diamond from the other actions they inherit through the `ℝ`-action on `ℂ` and action transitivity
defined in `data.complex.module.lean`. -/
instance : comm_ring ℂ :=
by refine_struct
{ zero := (0 : ℂ),
add := (+),
neg := has_neg.neg,
sub := has_sub.sub,
one := 1,
mul := (*),
zero_add := λ z, by { apply ext_iff.2, simp },
add_zero := λ z, by { apply ext_iff.2, simp },
nsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩,
npow := @npow_rec _ ⟨(1 : ℂ)⟩ ⟨(*)⟩,
zsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩ };
intros; try { refl }; apply ext_iff.2; split; simp; {ring1 <|> ring_nf}
/-- This shortcut instance ensures we do not find `ring` via the noncomputable `complex.field`
instance. -/
instance : ring ℂ := by apply_instance
/-- The "real part" map, considered as an additive group homomorphism. -/
def re_add_group_hom : ℂ →+ ℝ :=
{ to_fun := re,
map_zero' := zero_re,
map_add' := add_re }
@[simp] lemma coe_re_add_group_hom : (re_add_group_hom : ℂ → ℝ) = re := rfl
/-- The "imaginary part" map, considered as an additive group homomorphism. -/
def im_add_group_hom : ℂ →+ ℝ :=
{ to_fun := im,
map_zero' := zero_im,
map_add' := add_im }
@[simp] lemma coe_im_add_group_hom : (im_add_group_hom : ℂ → ℝ) = im := rfl
@[simp] lemma I_pow_bit0 (n : ℕ) : I ^ (bit0 n) = (-1) ^ n :=
by rw [pow_bit0', I_mul_I]
@[simp] lemma I_pow_bit1 (n : ℕ) : I ^ (bit1 n) = (-1) ^ n * I :=
by rw [pow_bit1', I_mul_I]
/-! ### Complex conjugation -/
/-- This defines the complex conjugate as the `star` operation of the `star_ring ℂ`. It
is recommended to use the ring endomorphism version `star_ring_end`, available under the
notation `conj` in the locale `complex_conjugate`. -/
instance : star_ring ℂ :=
{ star := λ z, ⟨z.re, -z.im⟩,
star_involutive := λ x, by simp only [eta, neg_neg],
star_mul := λ a b, by ext; simp [add_comm]; ring,
star_add := λ a b, by ext; simp [add_comm] }
@[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl
@[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl
lemma conj_of_real (r : ℝ) : conj (r : ℂ) = r := ext_iff.2 $ by simp [conj]
@[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp
lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0]
lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0]
@[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp
lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r :=
⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩,
λ ⟨h, e⟩, by rw [e, conj_of_real]⟩
lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z :=
eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩
lemma eq_conj_iff_im {z : ℂ} : conj z = z ↔ z.im = 0 :=
⟨λ h, add_self_eq_zero.mp (neg_eq_iff_add_eq_zero.mp (congr_arg im h)),
λ h, ext rfl (neg_eq_iff_add_eq_zero.mpr (add_self_eq_zero.mpr h))⟩
-- `simp_nf` complains about this being provable by `is_R_or_C.star_def` even
-- though it's not imported by this file.
@[simp, nolint simp_nf] lemma star_def : (has_star.star : ℂ → ℂ) = conj := rfl
/-! ### Norm squared -/
/-- The norm squared function. -/
@[pp_nodot] def norm_sq : ℂ →*₀ ℝ :=
{ to_fun := λ z, z.re * z.re + z.im * z.im,
map_zero' := by simp,
map_one' := by simp,
map_mul' := λ z w, by { dsimp, ring } }
lemma norm_sq_apply (z : ℂ) : norm_sq z = z.re * z.re + z.im * z.im := rfl
@[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r :=
by simp [norm_sq]
@[simp] lemma norm_sq_mk (x y : ℝ) : norm_sq ⟨x, y⟩ = x * x + y * y := rfl
lemma norm_sq_add_mul_I (x y : ℝ) : norm_sq (x + y * I) = x ^ 2 + y ^ 2 :=
by rw [← mk_eq_add_mul_I, norm_sq_mk, sq, sq]
lemma norm_sq_eq_conj_mul_self {z : ℂ} : (norm_sq z : ℂ) = conj z * z :=
by { ext; simp [norm_sq, mul_comm], }
@[simp] lemma norm_sq_zero : norm_sq 0 = 0 := norm_sq.map_zero
@[simp] lemma norm_sq_one : norm_sq 1 = 1 := norm_sq.map_one
@[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq]
lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z :=
add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)
lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 :=
⟨λ h, ext
(eq_zero_of_mul_self_add_mul_self_eq_zero h)
(eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h),
λ h, h.symm ▸ norm_sq_zero⟩
@[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 :=
(norm_sq_nonneg z).lt_iff_ne.trans $ not_congr (eq_comm.trans norm_sq_eq_zero)
@[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z :=
by simp [norm_sq]
lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w :=
norm_sq.map_mul z w
lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) =
norm_sq z + norm_sq w + 2 * (z * conj w).re :=
by dsimp [norm_sq]; ring
lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z :=
le_add_of_nonneg_right (mul_self_nonneg _)
lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z :=
le_add_of_nonneg_left (mul_self_nonneg _)
theorem mul_conj (z : ℂ) : z * conj z = norm_sq z :=
ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm]
theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) :=
ext_iff.2 $ by simp [two_mul]
/-- The coercion `ℝ → ℂ` as a `ring_hom`. -/
def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩
@[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl
@[simp] lemma I_sq : I ^ 2 = -1 := by rw [sq, I_mul_I]
@[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl
@[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl
@[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp
@[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n :=
by induction n; simp [*, of_real_mul, pow_succ]
theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I :=
ext_iff.2 $ by simp [two_mul, sub_eq_add_neg]
lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) =
norm_sq z + norm_sq w - 2 * (z * conj w).re :=
by { rw [sub_eq_add_neg, norm_sq_add],
simp only [ring_hom.map_neg, mul_neg, neg_re,
tactic.ring.add_neg_eq_sub, norm_sq_neg] }
/-! ### Inversion -/
noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩
theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl
@[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def]
@[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def]
@[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ :=
ext_iff.2 $ by simp
protected
protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 :=
by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul,
mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one]
/-! ### Field instance and lemmas -/
noncomputable instance : field ℂ :=
{ inv := has_inv.inv,
exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩,
mul_inv_cancel := @complex.mul_inv_cancel,
inv_zero := complex.inv_zero,
..complex.comm_ring }
@[simp] lemma I_zpow_bit0 (n : ℤ) : I ^ (bit0 n) = (-1) ^ n :=
by rw [zpow_bit0', I_mul_I]
@[simp] lemma I_zpow_bit1 (n : ℤ) : I ^ (bit1 n) = (-1) ^ n * I :=
by rw [zpow_bit1', I_mul_I]
lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg]
lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm]
lemma conj_inv (x : ℂ) : conj (x⁻¹) = (conj x)⁻¹ := star_inv' _
@[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s :=
of_real.map_div r s
@[simp, norm_cast] lemma of_real_zpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n :=
of_real.map_zpow r n
@[simp] lemma div_I (z : ℂ) : z / I = -(z * I) :=
(div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc]
@[simp] lemma inv_I : I⁻¹ = -I :=
by simp [inv_eq_one_div]
@[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ :=
norm_sq.map_inv z
@[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w :=
norm_sq.map_div z w
/-! ### Cast lemmas -/
@[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n :=
map_nat_cast of_real n
@[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n :=
by rw [← of_real_nat_cast, of_real_re]
@[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 :=
by rw [← of_real_nat_cast, of_real_im]
@[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n :=
of_real.map_int_cast n
@[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n :=
by rw [← of_real_int_cast, of_real_re]
@[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 :=
by rw [← of_real_int_cast, of_real_im]
@[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n :=
of_real.map_rat_cast n
@[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q :=
by rw [← of_real_rat_cast, of_real_re]
@[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 :=
by rw [← of_real_rat_cast, of_real_im]
/-! ### Characteristic zero -/
instance char_zero_complex : char_zero ℂ :=
char_zero_of_inj_zero $ λ n h,
by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h
/-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/
theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 :=
by simp only [add_conj, of_real_mul, of_real_one, of_real_bit0,
mul_div_cancel_left (z.re:ℂ) two_ne_zero']
/-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/
theorem im_eq_sub_conj (z : ℂ) : (z.im : ℂ) = (z - conj(z))/(2 * I) :=
by simp only [sub_conj, of_real_mul, of_real_one, of_real_bit0, mul_right_comm,
mul_div_cancel_left _ (mul_ne_zero two_ne_zero' I_ne_zero : 2 * I ≠ 0)]
/-! ### Absolute value -/
/-- The complex absolute value function, defined as the square root of the norm squared. -/
@[pp_nodot] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt
local notation `abs'` := has_abs.abs
@[simp, norm_cast] lemma abs_of_real (r : ℝ) : abs r = |r| :=
by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs]
lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r :=
(abs_of_real _).trans (abs_of_nonneg h)
lemma abs_of_nat (n : ℕ) : complex.abs n = n :=
calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast]
... = _ : abs_of_nonneg (nat.cast_nonneg n)
lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z :=
real.mul_self_sqrt (norm_sq_nonneg _)
lemma sq_abs (z : ℂ) : abs z ^ 2 = norm_sq z :=
real.sq_sqrt (norm_sq_nonneg _)
@[simp] lemma sq_abs_sub_sq_re (z : ℂ) : abs z ^ 2 - z.re ^ 2 = z.im ^ 2 :=
by rw [sq_abs, norm_sq_apply, ← sq, ← sq, add_sub_cancel']
@[simp] lemma sq_abs_sub_sq_im (z : ℂ) : abs z ^ 2 - z.im ^ 2 = z.re ^ 2 :=
by rw [← sq_abs_sub_sq_re, sub_sub_cancel]
@[simp] lemma abs_zero : abs 0 = 0 := by simp [abs]
@[simp] lemma abs_one : abs 1 = 1 := by simp [abs]
@[simp] lemma abs_I : abs I = 1 := by simp [abs]
@[simp] lemma abs_two : abs 2 = 2 :=
calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one]
... = (2 : ℝ) : abs_of_nonneg (by norm_num)
lemma abs_nonneg (z : ℂ) : 0 ≤ abs z :=
real.sqrt_nonneg _
@[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 :=
(real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero
lemma abs_ne_zero {z : ℂ} : abs z ≠ 0 ↔ z ≠ 0 :=
not_congr abs_eq_zero
@[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z :=
by simp [abs]
@[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w :=
by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl
/-- `complex.abs` as a `monoid_with_zero_hom`. -/
@[simps] noncomputable def abs_hom : ℂ →*₀ ℝ :=
{ to_fun := abs,
map_zero' := abs_zero,
map_one' := abs_one,
map_mul' := abs_mul }
@[simp] lemma abs_prod {ι : Type*} (s : finset ι) (f : ι → ℂ) :
abs (s.prod f) = s.prod (λ i, abs (f i)) :=
map_prod abs_hom _ _
@[simp] lemma abs_pow (z : ℂ) (n : ℕ) : abs (z ^ n) = abs z ^ n :=
map_pow abs_hom z n
@[simp] lemma abs_zpow (z : ℂ) (n : ℤ) : abs (z ^ n) = abs z ^ n :=
abs_hom.map_zpow z n
lemma abs_re_le_abs (z : ℂ) : |z.re| ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply re_sq_le_norm_sq
lemma abs_im_le_abs (z : ℂ) : |z.im| ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply im_sq_le_norm_sq
lemma re_le_abs (z : ℂ) : z.re ≤ abs z :=
(abs_le.1 (abs_re_le_abs _)).2
lemma im_le_abs (z : ℂ) : z.im ≤ abs z :=
(abs_le.1 (abs_im_le_abs _)).2
/--
The **triangle inequality** for complex numbers.
-/
lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w :=
(mul_self_le_mul_self_iff (abs_nonneg _)
(add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $
begin
rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs,
add_right_comm, norm_sq_add, add_le_add_iff_left,
mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)],
simpa [-mul_re] using re_le_abs (z * conj w)
end
instance : is_absolute_value abs :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
@[simp] lemma abs_abs (z : ℂ) : |(abs z)| = abs z :=
_root_.abs_of_nonneg (abs_nonneg _)
@[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs
@[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs
lemma abs_sub_comm : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs
lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs
@[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs
@[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs
lemma abs_abs_sub_le_abs_sub : ∀ z w, |abs z - abs w| ≤ abs (z - w) :=
abs_abv_sub_le_abv_sub abs
lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ |z.re| + |z.im| :=
by simpa [re_add_im] using abs_add z.re (z.im * I)
lemma abs_re_div_abs_le_one (z : ℂ) : |z.re / z.abs| ≤ 1 :=
if hz : z = 0 then by simp [hz, zero_le_one]
else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] }
lemma abs_im_div_abs_le_one (z : ℂ) : |z.im / z.abs| ≤ 1 :=
if hz : z = 0 then by simp [hz, zero_le_one]
else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] }
@[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n :=
by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)]
@[simp, norm_cast] lemma int_cast_abs (n : ℤ) : ↑|n| = abs n :=
by rw [← of_real_int_cast, abs_of_real, int.cast_abs]
lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 :=
by rw [abs, sq, real.mul_self_sqrt (norm_sq_nonneg _)]
/--
We put a partial order on ℂ so that `z ≤ w` exactly if `w - z` is real and nonnegative.
Complex numbers with different imaginary parts are incomparable.
-/
protected def partial_order : partial_order ℂ :=
{ le := λ z w, z.re ≤ w.re ∧ z.im = w.im,
lt := λ z w, z.re < w.re ∧ z.im = w.im,
lt_iff_le_not_le := λ z w, by { dsimp, rw lt_iff_le_not_le, tauto },
le_refl := λ x, ⟨le_rfl, rfl⟩,
le_trans := λ x y z h₁ h₂, ⟨h₁.1.trans h₂.1, h₁.2.trans h₂.2⟩,
le_antisymm := λ z w h₁ h₂, ext (h₁.1.antisymm h₂.1) h₁.2 }
section complex_order
localized "attribute [instance] complex.partial_order" in complex_order
lemma le_def {z w : ℂ} : z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im := iff.rfl
lemma lt_def {z w : ℂ} : z < w ↔ z.re < w.re ∧ z.im = w.im := iff.rfl
@[simp, norm_cast] lemma real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y := by simp [le_def]
@[simp, norm_cast] lemma real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y := by simp [lt_def]
@[simp, norm_cast] lemma zero_le_real {x : ℝ} : (0 : ℂ) ≤ (x : ℂ) ↔ 0 ≤ x := real_le_real
@[simp, norm_cast] lemma zero_lt_real {x : ℝ} : (0 : ℂ) < (x : ℂ) ↔ 0 < x := real_lt_real
lemma not_le_iff {z w : ℂ} : ¬(z ≤ w) ↔ w.re < z.re ∨ z.im ≠ w.im :=
by rw [le_def, not_and_distrib, not_le]
lemma not_le_zero_iff {z : ℂ} : ¬z ≤ 0 ↔ 0 < z.re ∨ z.im ≠ 0 := not_le_iff
/--
With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is an ordered ring.
-/
protected def ordered_comm_ring : ordered_comm_ring ℂ :=
{ zero_le_one := ⟨zero_le_one, rfl⟩,
add_le_add_left := λ w z h y, ⟨add_le_add_left h.1 _, congr_arg2 (+) rfl h.2⟩,
mul_pos := λ z w hz hw,
by simp [lt_def, mul_re, mul_im, ← hz.2, ← hw.2, mul_pos hz.1 hw.1],
.. complex.partial_order,
.. complex.comm_ring }
localized "attribute [instance] complex.ordered_comm_ring" in complex_order
/--
With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is a star ordered ring.
(That is, a star ring in which the nonnegative elements are those of the form `star z * z`.)
-/
protected def star_ordered_ring : star_ordered_ring ℂ :=
{ nonneg_iff := λ r, by
{ refine ⟨λ hr, ⟨real.sqrt r.re, _⟩, λ h, _⟩,
{ have h₁ : 0 ≤ r.re := by { rw [le_def] at hr, exact hr.1 },
have h₂ : r.im = 0 := by { rw [le_def] at hr, exact hr.2.symm },
ext,
{ simp only [of_real_im, star_def, of_real_re, sub_zero, conj_re, mul_re, mul_zero,
←real.sqrt_mul h₁ r.re, real.sqrt_mul_self h₁] },
{ simp only [h₂, add_zero, of_real_im, star_def, zero_mul, conj_im,
mul_im, mul_zero, neg_zero] } },
{ obtain ⟨s, rfl⟩ := h,
simp only [←norm_sq_eq_conj_mul_self, norm_sq_nonneg, zero_le_real, star_def] } },
..complex.ordered_comm_ring }
localized "attribute [instance] complex.star_ordered_ring" in complex_order
end complex_order
/-! ### Cauchy sequences -/
theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij)
theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij)
/-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_re f⟩
/-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_im f⟩
lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) :
is_cau_seq abs' (abs ∘ f) :=
λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩
/-- The limit of a Cauchy sequence of complex numbers. -/
noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ :=
⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩
theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) :=
λ ε ε0, (exists_forall_ge_and
(cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0))
(cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $
λ i H j ij, begin
cases H _ ij with H₁ H₂,
apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _),
dsimp [lim_aux] at *,
have := add_lt_add H₁ H₂,
rwa add_halves at this,
end
instance : cau_seq.is_complete ℂ abs :=
⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩
open cau_seq
lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f =
↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I :=
lim_eq_of_equiv_const $
calc f ≈ _ : equiv_lim_aux f
... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) :
cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im]))
lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re :=
by rw [lim_eq_lim_im_add_lim_re]; simp
lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im :=
by rw [lim_eq_lim_im_add_lim_re]; simp
lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) :=
λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in
⟨i, λ j hj, by rw [← ring_hom.map_sub, abs_conj]; exact hi j hj⟩
/-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/
noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs :=
⟨_, is_cau_seq_conj f⟩
lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) :=
complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re])
(by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl)
/-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_abs f.2⟩
lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) :=
lim_eq_of_equiv_const (λ ε ε0,
let ⟨i, hi⟩ := equiv_lim f ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩)
@[simp, norm_cast] lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) :
((∏ i in s, f i : ℝ) : ℂ) = ∏ i in s, (f i : ℂ) :=
ring_hom.map_prod of_real _ _
@[simp, norm_cast] lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) :
((∑ i in s, f i : ℝ) : ℂ) = ∑ i in s, (f i : ℂ) :=
ring_hom.map_sum of_real _ _
end complex
|
theory DSG
imports Main History
begin
section \<open>Transaction Dependencies\<close>
text \<open>We begin by formalizing three types of dependencies between transactions: wr-depends,
ww-depends, and rw-depends. The wr-depends relation captures the idea of a transaction t2 reading
another transaction T1's write.\<close>
definition wr_depends :: "history \<Rightarrow> atxn \<Rightarrow> atxn \<Rightarrow> bool" where
"wr_depends h t1 t2 \<equiv> \<exists>w1 r2. (a_is_committed t1) \<and>
(a_is_committed t2) \<and>
(w1 \<in> ext_awrites t1) \<and>
(r2 \<in> ext_areads t2) \<and>
((key w1) = (key r2)) \<and>
((post_version w1) = (pre_version r2))"
text \<open>We say t1 ww-depends t2 if t2 overwrote t1--that is, if t1 installed
some version v1 of k, and t2 wrote v2, such that v1 came immediately before v2 in the version order
of k.\<close>
definition ww_depends :: "history \<Rightarrow> atxn \<Rightarrow> atxn \<Rightarrow> bool" where
"ww_depends h t1 t2 \<equiv> \<exists>w1 w2.
(a_is_committed t1) \<and>
(a_is_committed t2) \<and>
(w1 \<in> ext_awrites t1) \<and>
(w2 \<in> ext_awrites t2) \<and>
((key w1) = (key w2)) \<and>
(is_next_in_history h (key w1) (apost_version w1) (apost_version w2))"
lemma ww_depends_example: "ww_depends
(History objs
{(ATxn [(AWrite x v0 a1 v1 [])] True),
(ATxn [(AWrite x v1 a2 v2 [])] True)}
{(KeyVersionOrder x [v0, v1, v2])})
(ATxn [(AWrite x v0 a1 v1 [])] True)
(ATxn [(AWrite x v1 a2 v2 [])] True)
= True"
apply (simp add:ww_depends_def)
done
text \<open>An rw-dependency is just like a ww-dependency, only transaction t1 *read* state just prior to
t2's write.\<close>
definition rw_depends :: "history \<Rightarrow> atxn \<Rightarrow> atxn \<Rightarrow> bool" where
"rw_depends h t1 t2 \<equiv> \<exists>r1 w2.
(a_is_committed t1) \<and>
(a_is_committed t2) \<and>
(r1 \<in> ext_areads t1) \<and>
(w2 \<in> ext_awrites t2) \<and>
((key r1) = (key w2)) \<and>
(is_next_in_history h (key r1) (apost_version r1) (apost_version w2))"
section \<open>Direct Serialization Graphs\<close>
text \<open>Now, we define a Direct Serialization Graph of a history as a graph where nodes are
transactions in that history, and arcs are dependencies between them. We codify these three types of
dependency with a type, and create a dependency type to wrap them. We call these aDeps for abstract
dependencies; later, we'll define analogous observed dependencies.\<close>
datatype depType = WR | WW | RW
datatype adep = ADep atxn depType atxn
primrec adep_head :: "adep \<Rightarrow> atxn" where
"adep_head (ADep t _ _) = t"
primrec adep_tail :: "adep \<Rightarrow> atxn" where
"adep_tail (ADep _ _ t) = t"
class dep_typed =
fixes dep_type :: "'a \<Rightarrow> depType"
instantiation adep :: "dep_typed"
begin
primrec dep_type_adep :: "adep \<Rightarrow> depType" where
"dep_type_adep (ADep _ t _) = t"
instance ..
end
type_synonym dsg = "(atxn, adep) pre_digraph"
text \<open>The DSG of a history is defined by mapping each dependency to an edge in the graph.\<close>
definition dsg :: "history \<Rightarrow> dsg" where
"dsg h \<equiv> \<lparr>verts = all_atxns h,
arcs = ({(ADep t1 WR t2) | t1 t2. wr_depends h t1 t2} \<union>
{(ADep t1 WW t2) | t1 t2. ww_depends h t1 t2} \<union>
{(ADep t1 RW t2) | t1 t2. rw_depends h t1 t2}),
tail = adep_tail,
head = adep_head\<rparr>"
text \<open>Now, we need to characterize a cycle in a DSG. TODO: I don't know how to use the definitions
in the locales in Arc_Walk.thy, but I assume we should take advantage of them. Copy-pasting with
slight mods for now.\<close>
type_synonym 'a path = "'a list"
text \<open>The list of vertices of a walk. The additional vertex argument is there to deal with the case
of empty walks.\<close>
primrec path_verts :: "('a,'b) pre_digraph \<Rightarrow> 'a \<Rightarrow> 'b path \<Rightarrow> 'a list" where
"path_verts G u [] = [u]"
| "path_verts G u (e # es) = tail G e # path_verts G (head G e) es"
text \<open>
Tests whether a list of arcs is a consistent arc sequence,
i.e. a list of arcs, where the head G node of each arc is
the tail G node of the following arc.
\<close>
fun cas :: "('a, 'b) pre_digraph => 'a \<Rightarrow> 'b path \<Rightarrow> 'a \<Rightarrow> bool" where
"cas G u [] v = (u = v)" |
"cas G u (e # es) v = (tail G e = u \<and> cas G (head G e) es v)"
definition path :: "('a,'b) pre_digraph \<Rightarrow> 'a \<Rightarrow> 'b path \<Rightarrow> 'a \<Rightarrow> bool" where
"path G u p v \<equiv> u \<in> verts G \<and> set p \<subseteq> arcs G \<and> cas G u p v"
text \<open>Is the given path a cycle in the given graph?\<close>
definition cycle :: "('a,'b) pre_digraph \<Rightarrow> 'b path \<Rightarrow> bool" where
"cycle G p \<equiv> \<exists>u. path G u p u \<and> distinct (tl (path_verts G u p)) \<and> p \<noteq> []"
text \<open>We would like a cycle whose edges are all of the given set of dependency types.\<close>
primrec path_dep_types :: "('a::dep_typed) path \<Rightarrow> depType set" where
"path_dep_types [] = {}" |
"path_dep_types (x # xs) = (Set.insert (dep_type x) (path_dep_types xs))"
end |
Efun.top promotions on hundreds of vape products. Get cheapest vaping here.
Don't forget to log in to get best price! |
The degree of a natural number is zero. |
/-
Copyright (c) 2023 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Kevin Buzzard
-/
import tactic
import analysis.normed_space.lp_space -- theory of ℓᵖ spaces
/-
# ℓᵖ spaces
The set-up : `I` is an index type, `E` is a family of `normed_add_comm_group`s
(so if `i : I` then `E i` is a type and if `v : E i` then `‖v‖` makes sense and
is a real number).
Then given `p : ℝ≥0∞` (i.e. an element `p` of `[0,∞]`) there is a theory
of ℓᵖ spaces, which is the subspace of `Π i, E i` (the product) consisting of the
sections `vᵢ` such that `∑ᵢ ‖vᵢ‖ᵖ < ∞`. For `p=∞` this means "the ‖vᵢ‖ are
bounded".
-/
open_locale ennreal -- to get notation ℝ≥0∞
variables (I : Type) (E : I → Type) [∀ i, normed_add_comm_group (E i)] (p : ℝ≥0∞)
-- Here's how to say that an element of the product of the Eᵢ is in the ℓᵖ space
example (v : Π i, E i) : Prop := mem_ℓp v p
-- Technical note: 0^0=1 and x^0=0 for x>0, so ℓ⁰ is the functions with finite support.
variable (v : Π i, E i)
example : mem_ℓp v 0 ↔ set.finite {i | v i ≠ 0} :=
begin
exact mem_ℓp_zero_iff,
end
example : mem_ℓp v ∞ ↔ bdd_above (set.range (λ i, ‖v i‖)) :=
begin
exact mem_ℓp_infty_iff,
end
-- The function ennreal.to_real sends x<∞ to x and ∞ to 0.
-- So `0 < p.to_real` is a way of saying `0 < p < ∞`.
example (hp : 0 < p.to_real) :
mem_ℓp v p ↔ summable (λ i, ‖v i‖ ^ p.to_real) :=
begin
exact mem_ℓp_gen_iff hp
end
-- It's a theorem in the library that if p ≤ q then mem_ℓp v p → mem_ℓp v q
example (q : ℝ≥0∞) (hpq : p ≤ q) : mem_ℓp v p → mem_ℓp v q :=
begin
intro h,
exact h.of_exponent_ge hpq,
end
-- The space of all `v` satisfying `mem_ℓp v p` is
-- called lp E p
example : Type := lp E p
-- It has a norm:
noncomputable example (v : lp E p) : ℝ := ‖v‖
-- It's a `normed_add_comm_group` if `1 ≤ p` but I've not stated this correctly.
noncomputable example (h : 1 ≤ p) : normed_add_comm_group (lp E p) :=
begin
sorry,
end
-- `real.is_conjugate_exponent p q` means that `p,q>1` are reals and `1/p+1/q=1`
example (p q : ℝ) (hp : 1 < p) (hq : 1 < q) (hpq : 1 / p + 1 / q = 1) :
p.is_conjugate_exponent q :=
sorry -- it's a structure
-- We have a verison of Hoelder's inequality.
example (q : ℝ≥0∞) (hpq : p.to_real.is_conjugate_exponent q.to_real) (f : lp E p)
(g : lp E q) : ∑' (i : I), ‖f i‖ * ‖g i‖ ≤ ‖f‖ * ‖g‖ :=
begin
have := lp.tsum_mul_le_mul_norm hpq f g,
exact this.2,
end
-- This would be a useless theorem if `∑' (i : I), ‖f i‖ * ‖g i‖` diverged,
-- because in Lean if a sum diverges then by definition the `∑'` of it is 0.
-- So we also need this:
example (q : ℝ≥0∞) (hpq : p.to_real.is_conjugate_exponent q.to_real) (f : lp E p)
(g : lp E q) : summable (λ i, ‖f i‖ * ‖g i‖) :=
begin
have := lp.tsum_mul_le_mul_norm hpq f g,
exact this.1,
end
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "miner.h"
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include "consensus/consensus.h"
#include "consensus/merkle.h"
#include "consensus/validation.h"
#include "hash.h"
#include "validation.h"
#include "net.h"
#include "policy/policy.h"
#include "pow.h"
#include "pos.h"
#include "primitives/transaction.h"
#include "script/standard.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "utilmoneystr.h"
#include "validationinterface.h"
#include "wallet/wallet.h"
#include <algorithm>
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <queue>
#include <utility>
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
//
// Unconfirmed transactions in the memory pool often depend on other
// transactions in the memory pool. When we select transactions from the
// pool, we select by highest priority or fee rate, so we might consider
// transactions that depend on transactions that aren't yet in the block.
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;
uint64_t nLastBlockWeight = 0;
int64_t nLastCoinStakeSearchInterval = 0;
unsigned int nMinerSleep = STAKER_POLLING_PERIOD;
class ScoreCompare
{
public:
ScoreCompare() {}
bool operator()(const CTxMemPool::txiter a, const CTxMemPool::txiter b)
{
return CompareTxMemPoolEntryByScore()(*b,*a); // Convert to less than
}
};
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
int64_t nOldTime = pblock->nTime;
int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
if (nOldTime < nNewTime)
pblock->nTime = nNewTime;
// Updating time can change work required on testnet:
if (consensusParams.fPowAllowMinDifficultyBlocks)
pblock->nBits = GetNextWorkRequired(pindexPrev, consensusParams, pblock->IsProofOfStake());
return nNewTime - nOldTime;
}
BlockAssembler::BlockAssembler(const CChainParams& _chainparams)
: chainparams(_chainparams)
{
// Block resource limits
// If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
// If only one is given, only restrict the specified resource.
// If both are given, restrict both.
nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
bool fWeightSet = false;
if (IsArgSet("-blockmaxweight")) {
nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
fWeightSet = true;
}
if (IsArgSet("-blockmaxsize")) {
nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
if (!fWeightSet) {
nBlockMaxWeight = nBlockMaxSize * WITNESS_SCALE_FACTOR;
}
}
if (IsArgSet("-blockmintxfee")) {
CAmount n = 0;
ParseMoney(GetArg("-blockmintxfee", ""), n);
blockMinFeeRate = CFeeRate(n);
} else {
blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
}
// Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
nBlockMaxWeight = std::max((unsigned int)4000, std::min((unsigned int)(MAX_BLOCK_WEIGHT-4000), nBlockMaxWeight));
// Limit size to between 1K and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SERIALIZED_SIZE-1000), nBlockMaxSize));
// Whether we need to account for byte usage (in addition to weight usage)
fNeedSizeAccounting = (nBlockMaxSize < MAX_BLOCK_SERIALIZED_SIZE-1000);
}
void BlockAssembler::resetBlock()
{
inBlock.clear();
// Reserve space for coinbase tx
nBlockSize = 1000;
nBlockWeight = 4000;
nBlockSigOpsCost = 400;
fIncludeWitness = false;
// These counters do not include coinbase tx
nBlockTx = 0;
nFees = 0;
lastFewTxs = 0;
blockFinished = false;
}
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fProofOfStake, int64_t* pTotalFees, int32_t txProofTime, int32_t nTimeLimit)
{
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return nullptr;
pblock = &pblocktemplate->block; // pointer for convenience
this->nTimeLimit = nTimeLimit;
// Add dummy coinbase tx as first transaction
pblock->vtx.emplace_back();
// Add dummy coinstake tx as second transaction
if(fProofOfStake)
pblock->vtx.emplace_back();
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
nHeight = pindexPrev->nHeight + 1;
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
if(txProofTime == 0) {
txProofTime = GetAdjustedTime();
}
if(fProofOfStake)
txProofTime &= ~STAKE_TIMESTAMP_MASK;
pblock->nTime = txProofTime;
if (!fProofOfStake)
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, chainparams.GetConsensus(), fProofOfStake);
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
// Decide whether to include witness transactions
// This is only needed in case the witness softfork activation is reverted
// (which would require a very deep reorganization) or when
// -promiscuousmempoolflags is used.
// TODO: replace this with a call to main to assess validity of a mempool
// transaction (which in most cases can be a no-op).
fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus());
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
nLastBlockWeight = nBlockWeight;
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(1);
if (fProofOfStake)
{
// Make the coinbase tx empty in case of proof of stake
coinbaseTx.vout[0].SetEmpty();
}
else
{
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(pindexPrev, 0, chainparams.GetConsensus(), nFees);
}
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
originalRewardTx = coinbaseTx;
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
// Create coinstake transaction.
if(fProofOfStake)
{
CMutableTransaction coinstakeTx;
coinstakeTx.vout.resize(2);
coinstakeTx.vout[0].SetEmpty();
coinstakeTx.vout[1].scriptPubKey = scriptPubKeyIn;
originalRewardTx = coinstakeTx;
pblock->vtx[1] = MakeTransactionRef(std::move(coinstakeTx));
//this just makes CBlock::IsProofOfStake to return true
//real prevoutstake info is filled in later in SignBlock
pblock->prevoutStake.n=0;
}
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus(), fProofOfStake);
pblocktemplate->vTxFees[0] = -nFees;
uint64_t nSerializeSize = GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION);
LogPrint("miner", "CreateNewBlock(): total size: %u block weight: %u txs: %u fees: %ld sigops %d\n", nSerializeSize, GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
// The total fee is the Fees minus the Refund
if (pTotalFees)
*pTotalFees = nFees;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->nNonce = 0;
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
CValidationState state;
if (!fProofOfStake && !TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
}
return std::move(pblocktemplate);
}
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateEmptyBlock(const CScript& scriptPubKeyIn, bool fProofOfStake, int64_t* pTotalFees, int32_t nTime)
{
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return nullptr;
pblock = &pblocktemplate->block; // pointer for convenience
// Add dummy coinbase tx as first transaction
pblock->vtx.emplace_back();
// Add dummy coinstake tx as second transaction
if(fProofOfStake)
pblock->vtx.emplace_back();
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
nHeight = pindexPrev->nHeight + 1;
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
uint32_t txProofTime = nTime == 0 ? GetAdjustedTime() : nTime;
if(fProofOfStake)
txProofTime &= ~STAKE_TIMESTAMP_MASK;
pblock->nTime = txProofTime;
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
nLastBlockWeight = nBlockWeight;
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(1);
if (fProofOfStake)
{
// Make the coinbase tx empty in case of proof of stake
coinbaseTx.vout[0].SetEmpty();
}
else
{
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(pindexPrev, 0, chainparams.GetConsensus(), nFees);
}
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
originalRewardTx = coinbaseTx;
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
// Create coinstake transaction.
if(fProofOfStake)
{
CMutableTransaction coinstakeTx;
coinstakeTx.vout.resize(2);
coinstakeTx.vout[0].SetEmpty();
coinstakeTx.vout[1].scriptPubKey = scriptPubKeyIn;
originalRewardTx = coinstakeTx;
pblock->vtx[1] = MakeTransactionRef(std::move(coinstakeTx));
//this just makes CBlock::IsProofOfStake to return true
//real prevoutstake info is filled in later in SignBlock
pblock->prevoutStake.n=0;
}
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus(), fProofOfStake);
pblocktemplate->vTxFees[0] = -nFees;
// The total fee is the Fees minus the Refund
if (pTotalFees)
*pTotalFees = nFees;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->nTime = std::max(pindexPrev->GetPastTimeLimit()+1, pblock->GetMaxTransactionTime());
pblock->nTime = std::max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime(), pindexPrev->nHeight+1, chainparams.GetConsensus()));
if (!fProofOfStake)
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, chainparams.GetConsensus(), fProofOfStake);
pblock->nNonce = 0;
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
CValidationState state;
if (!fProofOfStake && !TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
}
return std::move(pblocktemplate);
}
bool BlockAssembler::isStillDependent(CTxMemPool::txiter iter)
{
BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
{
if (!inBlock.count(parent)) {
return true;
}
}
return false;
}
void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
{
for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
// Only test txs not already in the block
if (inBlock.count(*iit)) {
testSet.erase(iit++);
}
else {
iit++;
}
}
}
bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
{
// TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
return false;
if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
return false;
return true;
}
// Perform transaction-level checks before adding to block:
// - transaction finality (locktime)
// - premature witness (in case segwit transactions are added to mempool before
// segwit activation)
// - serialized size (in case -blockmaxsize is in use)
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
{
uint64_t nPotentialBlockSize = nBlockSize; // only used with fNeedSizeAccounting
BOOST_FOREACH (const CTxMemPool::txiter it, package) {
if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
return false;
if (!fIncludeWitness && it->GetTx().HasWitness())
return false;
if (fNeedSizeAccounting) {
uint64_t nTxSize = ::GetSerializeSize(it->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
if (nPotentialBlockSize + nTxSize >= nBlockMaxSize) {
return false;
}
nPotentialBlockSize += nTxSize;
}
}
return true;
}
bool BlockAssembler::TestForBlock(CTxMemPool::txiter iter)
{
if (nBlockWeight + iter->GetTxWeight() >= nBlockMaxWeight) {
// If the block is so close to full that no more txs will fit
// or if we've tried more than 50 times to fill remaining space
// then flag that the block is finished
if (nBlockWeight > nBlockMaxWeight - 400 || lastFewTxs > 50) {
blockFinished = true;
return false;
}
// Once we're within 4000 weight of a full block, only look at 50 more txs
// to try to fill the remaining space.
if (nBlockWeight > nBlockMaxWeight - 4000) {
lastFewTxs++;
}
return false;
}
if (fNeedSizeAccounting) {
if (nBlockSize + ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION) >= nBlockMaxSize) {
if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
blockFinished = true;
return false;
}
if (nBlockSize > nBlockMaxSize - 1000) {
lastFewTxs++;
}
return false;
}
}
if (nBlockSigOpsCost + iter->GetSigOpCost() >= MAX_BLOCK_SIGOPS_COST) {
// If the block has room for no more sig ops then
// flag that the block is finished
if (nBlockSigOpsCost > MAX_BLOCK_SIGOPS_COST - 8) {
blockFinished = true;
return false;
}
// Otherwise attempt to find another tx with fewer sigops
// to put in the block.
return false;
}
// Must check that lock times are still valid
// This can be removed once MTP is always enforced
// as long as reorgs keep the mempool consistent.
if (!IsFinalTx(iter->GetTx(), nHeight, nLockTimeCutoff))
return false;
return true;
}
void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
{
pblock->vtx.emplace_back(iter->GetSharedTx());
pblocktemplate->vTxFees.push_back(iter->GetFee());
pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
if (fNeedSizeAccounting) {
nBlockSize += ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
}
nBlockWeight += iter->GetTxWeight();
++nBlockTx;
nBlockSigOpsCost += iter->GetSigOpCost();
nFees += iter->GetFee();
inBlock.insert(iter);
bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
if (fPrintPriority) {
double dPriority = iter->GetPriority(nHeight);
CAmount dummy;
mempool.ApplyDeltas(iter->GetTx().GetHash(), dPriority, dummy);
LogPrintf("priority %.1f fee %s txid %s\n",
dPriority,
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
iter->GetTx().GetHash().ToString());
}
}
void BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
indexed_modified_transaction_set &mapModifiedTx)
{
BOOST_FOREACH(const CTxMemPool::txiter it, alreadyAdded) {
CTxMemPool::setEntries descendants;
mempool.CalculateDescendants(it, descendants);
// Insert all descendants (not yet in block) into the modified set
BOOST_FOREACH(CTxMemPool::txiter desc, descendants) {
if (alreadyAdded.count(desc))
continue;
modtxiter mit = mapModifiedTx.find(desc);
if (mit == mapModifiedTx.end()) {
CTxMemPoolModifiedEntry modEntry(desc);
modEntry.nSizeWithAncestors -= it->GetTxSize();
modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
mapModifiedTx.insert(modEntry);
} else {
mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
}
}
}
}
// Skip entries in mapTx that are already in a block or are present
// in mapModifiedTx (which implies that the mapTx ancestor state is
// stale due to ancestor inclusion in the block)
// Also skip transactions that we've already failed to add. This can happen if
// we consider a transaction in mapModifiedTx and it fails: we can then
// potentially consider it again while walking mapTx. It's currently
// guaranteed to fail again, but as a belt-and-suspenders check we put it in
// failedTx and avoid re-evaluation, since the re-evaluation would be using
// cached size/sigops/fee values that are not actually correct.
bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
{
assert (it != mempool.mapTx.end());
if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it))
return true;
return false;
}
void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
{
// Sort package by ancestor count
// If a transaction A depends on transaction B, then A's ancestor count
// must be greater than B's. So this is sufficient to validly order the
// transactions for block inclusion.
sortedEntries.clear();
sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
}
// This transaction selection algorithm orders the mempool based
// on feerate of a transaction including all unconfirmed ancestors.
// Since we don't remove transactions from the mempool as we select them
// for block inclusion, we need an alternate method of updating the feerate
// of a transaction with its not-yet-selected ancestors as we go.
// This is accomplished by walking the in-mempool descendants of selected
// transactions and storing a temporary modified state in mapModifiedTxs.
// Each time through the loop, we compare the best transaction in
// mapModifiedTxs with the next transaction in the mempool to decide what
// transaction package to work on next.
void BlockAssembler::addPackageTxs()
{
// mapModifiedTx will store sorted packages after they are modified
// because some of their txs are already in the block
indexed_modified_transaction_set mapModifiedTx;
// Keep track of entries that failed inclusion, to avoid duplicate work
CTxMemPool::setEntries failedTx;
// Start by adding all descendants of previously added txs to mapModifiedTx
// and modifying them for their already included ancestors
UpdatePackagesForAdded(inBlock, mapModifiedTx);
CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
CTxMemPool::txiter iter;
while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
{
if(nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit){
//no more time to add transactions, just exit
return;
}
// First try to find a new transaction in mapTx to evaluate.
if (mi != mempool.mapTx.get<ancestor_score>().end() &&
SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
++mi;
continue;
}
// Now that mi is not stale, determine which transaction to evaluate:
// the next entry from mapTx, or the best from mapModifiedTx?
bool fUsingModified = false;
modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
if (mi == mempool.mapTx.get<ancestor_score>().end()) {
// We're out of entries in mapTx; use the entry from mapModifiedTx
iter = modit->iter;
fUsingModified = true;
} else {
// Try to compare the mapTx entry to the mapModifiedTx entry
iter = mempool.mapTx.project<0>(mi);
if (modit != mapModifiedTx.get<ancestor_score>().end() &&
CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
// The best entry in mapModifiedTx has higher score
// than the one from mapTx.
// Switch which transaction (package) to consider
iter = modit->iter;
fUsingModified = true;
} else {
// Either no entry in mapModifiedTx, or it's worse than mapTx.
// Increment mi for the next loop iteration.
++mi;
}
}
// We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
// contain anything that is inBlock.
assert(!inBlock.count(iter));
uint64_t packageSize = iter->GetSizeWithAncestors();
CAmount packageFees = iter->GetModFeesWithAncestors();
int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
if (fUsingModified) {
packageSize = modit->nSizeWithAncestors;
packageFees = modit->nModFeesWithAncestors;
packageSigOpsCost = modit->nSigOpCostWithAncestors;
}
if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
// Everything else we might consider has a lower fee rate
return;
}
if (!TestPackage(packageSize, packageSigOpsCost)) {
if (fUsingModified) {
// Since we always look at the best entry in mapModifiedTx,
// we must erase failed entries so that we can consider the
// next best entry on the next loop iteration
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
continue;
}
CTxMemPool::setEntries ancestors;
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
onlyUnconfirmed(ancestors);
ancestors.insert(iter);
// Test if all tx's are Final
if (!TestPackageTransactions(ancestors)) {
if (fUsingModified) {
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
continue;
}
// Package can be added. Sort the entries in a valid order.
std::vector<CTxMemPool::txiter> sortedEntries;
SortForBlock(ancestors, iter, sortedEntries);
for (size_t i=0; i<sortedEntries.size(); ++i) {
AddToBlock(sortedEntries[i]);
// Erase from the modified set, if present
mapModifiedTx.erase(sortedEntries[i]);
}
// Update transactions that depend on each of these
UpdatePackagesForAdded(ancestors, mapModifiedTx);
}
}
void BlockAssembler::addPriorityTxs()
{
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
if (nBlockPrioritySize == 0) {
return;
}
bool fSizeAccounting = fNeedSizeAccounting;
fNeedSizeAccounting = true;
// This vector will be sorted into a priority queue:
std::vector<TxCoinAgePriority> vecPriority;
TxCoinAgePriorityCompare pricomparer;
std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap;
typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter;
double actualPriority = -1;
vecPriority.reserve(mempool.mapTx.size());
for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
mi != mempool.mapTx.end(); ++mi)
{
double dPriority = mi->GetPriority(nHeight);
CAmount dummy;
mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy);
vecPriority.push_back(TxCoinAgePriority(dPriority, mi));
}
std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
CTxMemPool::txiter iter;
while (!vecPriority.empty() && !blockFinished) { // add a tx from priority queue to fill the blockprioritysize
iter = vecPriority.front().second;
actualPriority = vecPriority.front().first;
std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
vecPriority.pop_back();
// If tx already in block, skip
if (inBlock.count(iter)) {
assert(false); // shouldn't happen for priority txs
continue;
}
// cannot accept witness transactions into a non-witness block
if (!fIncludeWitness && iter->GetTx().HasWitness())
continue;
if(nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit)
{
break;
}
// If tx is dependent on other mempool txs which haven't yet been included
// then put it in the waitSet
if (isStillDependent(iter)) {
waitPriMap.insert(std::make_pair(iter, actualPriority));
continue;
}
// If this tx fits in the block add it, otherwise keep looping
if (TestForBlock(iter)) {
AddToBlock(iter);
// If now that this txs is added we've surpassed our desired priority size
// or have dropped below the AllowFreeThreshold, then we're done adding priority txs
if (nBlockSize >= nBlockPrioritySize || !AllowFree(actualPriority)) {
break;
}
// This tx was successfully added, so
// add transactions that depend on this one to the priority queue to try again
BOOST_FOREACH(CTxMemPool::txiter child, mempool.GetMemPoolChildren(iter))
{
waitPriIter wpiter = waitPriMap.find(child);
if (wpiter != waitPriMap.end()) {
vecPriority.push_back(TxCoinAgePriority(wpiter->second,child));
std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
waitPriMap.erase(wpiter);
}
}
}
}
fNeedSizeAccounting = fSizeAccounting;
}
void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
CMutableTransaction txCoinbase(*pblock->vtx[0]);
txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
assert(txCoinbase.vin[0].scriptSig.size() <= 100);
pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
}
//////////////////////////////////////////////////////////////////////////////
//
// Proof of Stake miner
//
//
// Looking for suitable coins for creating new block.
//
bool CheckStake(const std::shared_ptr<const CBlock> pblock, CWallet& wallet)
{
uint256 proofHash, hashTarget;
uint256 hashBlock = pblock->GetHash();
if(!pblock->IsProofOfStake())
return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex());
CDiskTxPos postx;
pblocktree->ReadTxIndex(pblock->vtx[1]->vin[0].prevout.hash, postx);
// verify hash target and signature of coinstake tx
CValidationState state;
if (!CheckProofOfStake(mapBlockIndex[pblock->hashPrevBlock], state, *pblock->vtx[1], pblock->nBits, proofHash, hashTarget, *pcoinsTip, *pblocktree, Params().GetConsensus()))
return error("CheckStake() : proof-of-stake checking failed");
//// debug print
LogPrint("miner", "CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex(), proofHash.GetHex(), hashTarget.GetHex());
LogPrint("miner", "%s\n", pblock->ToString());
LogPrint("miner", "out %s\n", FormatMoney(pblock->vtx[1]->GetValueOut()));
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
return error("CheckStake() : generated block is stale");
for(const CTxIn& vin : pblock->vtx[1]->vin) {
if (wallet.IsSpent(vin.prevout.hash, vin.prevout.n)) {
return error("CheckStake() : generated block became invalid due to stake UTXO being spent");
}
}
// Process this block the same as if we had received it from another node
bool fNewBlock = false;
if (!ProcessNewBlock(Params(), pblock, true, &fNewBlock))
return error("CheckStake() : ProcessBlock, block not accepted");
}
return true;
}
void ThreadStakeMiner(CWallet *pwallet)
{
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("clam-miner");
CReserveKey reservekey(pwallet);
bool fTryToSync = true;
bool regtestMode = Params().GetConsensus().fPoSNoRetargeting;
if(regtestMode){
nMinerSleep = 30000; //limit regtest to 30s, otherwise it'll create 2 blocks per second
}
while (true)
{
while (pwallet->IsLocked())
{
nLastCoinStakeSearchInterval = 0;
MilliSleep(10000);
}
//don't disable PoS mining for no connections if in regtest mode
if(!regtestMode && !GetBoolArg("-emergencystaking", false)) {
while (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0 || IsInitialBlockDownload()) {
nLastCoinStakeSearchInterval = 0;
fTryToSync = true;
MilliSleep(1000);
}
if (fTryToSync) {
fTryToSync = false;
if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) < 3 ||
pindexBestHeader->GetBlockTime() < GetTime() - 10 * 60) {
MilliSleep(60000);
continue;
}
}
}
//
// Create new block
//
if(pwallet->HaveAvailableCoinsForStaking())
{
int64_t nTotalFees = 0;
// First just create an empty block. No need to process transactions until we know we can create a block
std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateEmptyBlock(reservekey.reserveScript, true, &nTotalFees));
if (!pblocktemplate.get())
return;
CBlockIndex* pindexPrev = chainActive.Tip();
uint32_t beginningTime=GetAdjustedTime();
beginningTime &= ~STAKE_TIMESTAMP_MASK;
for(uint32_t i=beginningTime;i<beginningTime + MAX_STAKE_LOOKAHEAD;i+=STAKE_TIMESTAMP_MASK+1) {
// The information is needed for status bar to determine if the staker is trying to create block and when it will be created approximately,
static int64_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
// nLastCoinStakeSearchInterval > 0 mean that the staker is running
nLastCoinStakeSearchInterval = i - nLastCoinStakeSearchTime;
// Try to sign a block (this also checks for a PoS stake)
pblocktemplate->block.nTime = i;
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(pblocktemplate->block);
if (SignBlock(pblock, *pwallet, nTotalFees, i)) {
// increase priority so we can build the full PoS block ASAP to ensure the timestamp doesn't expire
SetThreadPriority(THREAD_PRIORITY_ABOVE_NORMAL);
if (chainActive.Tip()->GetBlockHash() != pblock->hashPrevBlock) {
//another block was received while building ours, scrap progress
LogPrintf("ThreadStakeMiner(): Valid future PoS block was orphaned before becoming valid");
break;
}
// Create a block that's properly populated with transactions
std::unique_ptr<CBlockTemplate> pblocktemplatefilled(
BlockAssembler(Params()).CreateNewBlock(pblock->vtx[1]->vout[1].scriptPubKey, true, &nTotalFees,
i, FutureDrift(GetAdjustedTime()) - STAKE_TIME_BUFFER));
if (!pblocktemplatefilled.get())
return;
if (chainActive.Tip()->GetBlockHash() != pblock->hashPrevBlock) {
//another block was received while building ours, scrap progress
LogPrintf("ThreadStakeMiner(): Valid future PoS block was orphaned before becoming valid");
break;
}
// Sign the full block and use the timestamp from earlier for a valid stake
std::shared_ptr<CBlock> pblockfilled = std::make_shared<CBlock>(pblocktemplatefilled->block);
if (SignBlock(pblockfilled, *pwallet, nTotalFees, i)) {
// Should always reach here unless we spent too much time processing transactions and the timestamp is now invalid
// CheckStake also does CheckBlock and AcceptBlock to propogate it to the network
bool validBlock = false;
while(!validBlock) {
if (chainActive.Tip()->GetBlockHash() != pblockfilled->hashPrevBlock) {
//another block was received while building ours, scrap progress
LogPrintf("ThreadStakeMiner(): Valid future PoS block was orphaned before becoming valid");
break;
}
//check timestamps
if (pblockfilled->GetBlockTime() <= pindexPrev->GetBlockTime() ||
FutureDrift(pblockfilled->GetBlockTime()) < pindexPrev->GetBlockTime()) {
LogPrintf("ThreadStakeMiner(): Valid PoS block took too long to create and has expired");
break; //timestamp too late, so ignore
}
if (pblockfilled->GetBlockTime() > FutureDrift(GetAdjustedTime())) {
if (IsArgSet("-aggressive-staking")) {
//if being agressive, then check more often to publish immediately when valid. This might allow you to find more blocks,
//but also increases the chance of broadcasting invalid blocks and getting DoS banned by nodes,
//or receiving more stale/orphan blocks than normal. Use at your own risk.
MilliSleep(100);
}else{
//too early, so wait 3 seconds and try again
MilliSleep(3000);
}
continue;
}
validBlock=true;
}
if(validBlock) {
CheckStake(pblockfilled, *pwallet);
// Update the search time when new valid block is created, needed for status bar icon
nLastCoinStakeSearchTime = pblockfilled->GetBlockTime();
}
break;
}
//return back to low priority
SetThreadPriority(THREAD_PRIORITY_LOWEST);
}
}
}
MilliSleep(nMinerSleep);
}
}
void StakeClams(bool fStake, CWallet *pwallet)
{
static boost::thread_group* stakeThread = NULL;
if (stakeThread != NULL)
{
stakeThread->interrupt_all();
delete stakeThread;
stakeThread = NULL;
}
if(fStake)
{
stakeThread = new boost::thread_group();
stakeThread->create_thread(boost::bind(&ThreadStakeMiner, pwallet));
}
}
|
/-
Copyright (c) 2021 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 measure_theory.measure.measure_space
/-!
# Vitali families
On a metric space `X` with a measure `μ`, consider for each `x : X` a family of measurable sets with
nonempty interiors, called `sets_at x`. This family is a Vitali family if it satisfies the following
property: consider a (possibly non-measurable) set `s`, and for any `x` in `s` a
subfamily `f x` of `sets_at x` containing sets of arbitrarily small diameter. Then one can extract
a disjoint subfamily covering almost all `s`.
Vitali families are provided by covering theorems such as the Besicovitch covering theorem or the
Vitali covering theorem. They make it possible to formulate general versions of theorems on
differentiations of measure that apply in both contexts.
This file gives the basic definition of Vitali families. More interesting developments of this
notion are deferred to other files:
* constructions of specific Vitali families are provided by the Besicovitch covering theorem, in
`besicovitch.vitali_family`, and by the Vitali covering theorem, in `vitali.vitali_family`.
* The main theorem on differentiation of measures along a Vitali family is proved in
`vitali_family.ae_tendsto_rn_deriv`.
## Main definitions
* `vitali_family μ` is a structure made, for each `x : X`, of a family of sets around `x`, such that
one can extract an almost everywhere disjoint covering from any subfamily containing sets of
arbitrarily small diameters.
Let `v` be such a Vitali family.
* `v.fine_subfamily_on` describes the subfamilies of `v` from which one can extract almost
everywhere disjoint coverings. This property, called
`v.fine_subfamily_on.exists_disjoint_covering_ae`, is essentially a restatement of the definition
of a Vitali family. We also provide an API to use efficiently such a disjoint covering.
* `v.filter_at x` is a filter on sets of `X`, such that convergence with respect to this filter
means convergence when sets in the Vitali family shrink towards `x`.
## References
* [Herbert Federer, Geometric Measure Theory, Chapter 2.8][Federer1996] (Vitali families are called
Vitali relations there)
-/
open measure_theory metric set filter topological_space measure_theory.measure
open_locale filter measure_theory topology
variables {α : Type*} [metric_space α]
/-- On a metric space `X` with a measure `μ`, consider for each `x : X` a family of measurable sets
with nonempty interiors, called `sets_at x`. This family is a Vitali family if it satisfies the
following property: consider a (possibly non-measurable) set `s`, and for any `x` in `s` a
subfamily `f x` of `sets_at x` containing sets of arbitrarily small diameter. Then one can extract
a disjoint subfamily covering almost all `s`.
Vitali families are provided by covering theorems such as the Besicovitch covering theorem or the
Vitali covering theorem. They make it possible to formulate general versions of theorems on
differentiations of measure that apply in both contexts.
-/
@[nolint has_nonempty_instance]
structure vitali_family {m : measurable_space α} (μ : measure α) :=
(sets_at : Π (x : α), set (set α))
(measurable_set' : ∀ (x : α), ∀ (a : set α), a ∈ sets_at x → measurable_set a)
(nonempty_interior : ∀ (x : α), ∀ (y : set α), y ∈ sets_at x → (interior y).nonempty)
(nontrivial : ∀ (x : α) (ε > (0 : ℝ)), ∃ y ∈ sets_at x, y ⊆ closed_ball x ε)
(covering : ∀ (s : set α) (f : Π (x : α), set (set α)), (∀ x ∈ s, f x ⊆ sets_at x) →
(∀ (x ∈ s) (ε > (0 : ℝ)), ∃ a ∈ f x, a ⊆ closed_ball x ε) → ∃ (t : set (α × set α)),
(∀ (p : α × set α), p ∈ t → p.1 ∈ s) ∧ t.pairwise_disjoint (λ p, p.2) ∧
(∀ (p : α × set α), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ ⋃ (p : α × set α) (hp : p ∈ t), p.2) = 0)
namespace vitali_family
variables {m0 : measurable_space α} {μ : measure α}
include μ
/-- A Vitali family for a measure `μ` is also a Vitali family for any measure absolutely continuous
with respect to `μ`. -/
def mono (v : vitali_family μ) (ν : measure α) (hν : ν ≪ μ) :
vitali_family ν :=
{ sets_at := v.sets_at,
measurable_set' := v.measurable_set',
nonempty_interior := v.nonempty_interior,
nontrivial := v.nontrivial,
covering := λ s f h h', begin
rcases v.covering s f h h' with ⟨t, ts, disj, mem_f, hμ⟩,
exact ⟨t, ts, disj, mem_f, hν hμ⟩
end }
/-- Given a Vitali family `v` for a measure `μ`, a family `f` is a fine subfamily on a set `s` if
every point `x` in `s` belongs to arbitrarily small sets in `v.sets_at x ∩ f x`. This is precisely
the subfamilies for which the Vitali family definition ensures that one can extract a disjoint
covering of almost all `s`. -/
def fine_subfamily_on (v : vitali_family μ) (f : α → set (set α)) (s : set α) : Prop :=
∀ x ∈ s, ∀ (ε > 0), ∃ a ∈ v.sets_at x ∩ f x, a ⊆ closed_ball x ε
namespace fine_subfamily_on
variables {v : vitali_family μ} {f : α → set (set α)} {s : set α} (h : v.fine_subfamily_on f s)
include h
theorem exists_disjoint_covering_ae :
∃ (t : set (α × set α)), (∀ (p : α × set α), p ∈ t → p.1 ∈ s) ∧
t.pairwise_disjoint (λ p, p.2) ∧
(∀ (p : α × set α), p ∈ t → p.2 ∈ v.sets_at p.1 ∩ f p.1)
∧ μ (s \ ⋃ (p : α × set α) (hp : p ∈ t), p.2) = 0 :=
v.covering s (λ x, v.sets_at x ∩ f x) (λ x hx, inter_subset_left _ _) h
/-- Given `h : v.fine_subfamily_on f s`, then `h.index` is a set parametrizing a disjoint
covering of almost every `s`. -/
protected def index : set (α × set α) :=
h.exists_disjoint_covering_ae.some
/-- Given `h : v.fine_subfamily_on f s`, then `h.covering p` is a set in the family,
for `p ∈ h.index`, such that these sets form a disjoint covering of almost every `s`. -/
@[nolint unused_arguments] protected def covering : α × set α → set α :=
λ p, p.2
lemma index_subset : ∀ (p : α × set α), p ∈ h.index → p.1 ∈ s :=
h.exists_disjoint_covering_ae.some_spec.1
lemma covering_disjoint : h.index.pairwise_disjoint h.covering :=
h.exists_disjoint_covering_ae.some_spec.2.1
lemma covering_disjoint_subtype : pairwise (disjoint on (λ x : h.index, h.covering x)) :=
(pairwise_subtype_iff_pairwise_set _ _).2 h.covering_disjoint
lemma covering_mem {p : α × set α} (hp : p ∈ h.index) : h.covering p ∈ f p.1 :=
(h.exists_disjoint_covering_ae.some_spec.2.2.1 p hp).2
lemma covering_mem_family {p : α × set α} (hp : p ∈ h.index) : h.covering p ∈ v.sets_at p.1 :=
(h.exists_disjoint_covering_ae.some_spec.2.2.1 p hp).1
lemma measure_diff_bUnion : μ (s \ ⋃ p ∈ h.index, h.covering p) = 0 :=
h.exists_disjoint_covering_ae.some_spec.2.2.2
lemma index_countable [second_countable_topology α] : h.index.countable :=
h.covering_disjoint.countable_of_nonempty_interior
(λ x hx, v.nonempty_interior _ _ (h.covering_mem_family hx))
protected lemma measurable_set_u {p : α × set α} (hp : p ∈ h.index) :
measurable_set (h.covering p) :=
v.measurable_set' p.1 _ (h.covering_mem_family hp)
lemma measure_le_tsum_of_absolutely_continuous [second_countable_topology α]
{ρ : measure α} (hρ : ρ ≪ μ) :
ρ s ≤ ∑' (p : h.index), ρ (h.covering p) :=
calc ρ s ≤ ρ ((s \ ⋃ (p ∈ h.index), h.covering p) ∪ (⋃ (p ∈ h.index), h.covering p)) :
measure_mono (by simp only [subset_union_left, diff_union_self])
... ≤ ρ (s \ ⋃ (p ∈ h.index), h.covering p) + ρ (⋃ (p ∈ h.index), h.covering p) :
measure_union_le _ _
... = ∑' (p : h.index), ρ (h.covering p) : by rw [hρ h.measure_diff_bUnion,
measure_bUnion h.index_countable h.covering_disjoint (λ x hx, h.measurable_set_u hx),
zero_add]
lemma measure_le_tsum [second_countable_topology α] :
μ s ≤ ∑' (x : h.index), μ (h.covering x) :=
h.measure_le_tsum_of_absolutely_continuous measure.absolutely_continuous.rfl
end fine_subfamily_on
/-- One can enlarge a Vitali family by adding to the sets `f x` at `x` all sets which are not
contained in a `δ`-neighborhood on `x`. This does not change the local filter at a point, but it
can be convenient to get a nicer global behavior. -/
def enlarge (v : vitali_family μ) (δ : ℝ) (δpos : 0 < δ) : vitali_family μ :=
{ sets_at := λ x, v.sets_at x ∪
{a | measurable_set a ∧ (interior a).nonempty ∧ ¬(a ⊆ closed_ball x δ)},
measurable_set' := λ x a ha, by { cases ha, exacts [v.measurable_set' _ _ ha, ha.1] },
nonempty_interior := λ x a ha, by { cases ha, exacts [v.nonempty_interior _ _ ha, ha.2.1] },
nontrivial := begin
assume x ε εpos,
rcases v.nontrivial x ε εpos with ⟨a, ha, h'a⟩,
exact ⟨a, mem_union_left _ ha, h'a⟩,
end,
covering := begin
assume s f fset ffine,
let g : α → set (set α) := λ x, f x ∩ v.sets_at x,
have : ∀ x ∈ s, ∀ (ε : ℝ), ε > 0 → (∃ (a : set α) (H : a ∈ g x), a ⊆ closed_ball x ε),
{ assume x hx ε εpos,
obtain ⟨a, af, ha⟩ : ∃ a ∈ f x, a ⊆ closed_ball x (min ε δ),
from ffine x hx (min ε δ) (lt_min εpos δpos),
rcases fset x hx af with h'a|h'a,
{ exact ⟨a, ⟨af, h'a⟩, ha.trans (closed_ball_subset_closed_ball (min_le_left _ _))⟩ },
{ refine false.elim (h'a.2.2 _),
exact ha.trans (closed_ball_subset_closed_ball (min_le_right _ _)) } },
rcases v.covering s g (λ x hx, inter_subset_right _ _) this with ⟨t, ts, tdisj, tg, μt⟩,
exact ⟨t, ts, tdisj, λ p hp, (tg p hp).1, μt⟩,
end }
variable (v : vitali_family μ)
include v
/-- Given a vitali family `v`, then `v.filter_at x` is the filter on `set α` made of those families
that contain all sets of `v.sets_at x` of a sufficiently small diameter. This filter makes it
possible to express limiting behavior when sets in `v.sets_at x` shrink to `x`. -/
def filter_at (x : α) : filter (set α) :=
⨅ (ε ∈ Ioi (0 : ℝ)), 𝓟 {a ∈ v.sets_at x | a ⊆ closed_ball x ε}
lemma mem_filter_at_iff {x : α} {s : set (set α)} :
(s ∈ v.filter_at x) ↔ ∃ (ε > (0 : ℝ)), ∀ a ∈ v.sets_at x, a ⊆ closed_ball x ε → a ∈ s :=
begin
simp only [filter_at, exists_prop, gt_iff_lt],
rw mem_binfi_of_directed,
{ simp only [subset_def, and_imp, exists_prop, mem_sep_iff, mem_Ioi, mem_principal] },
{ simp only [directed_on, exists_prop, ge_iff_le, le_principal_iff, mem_Ioi, order.preimage,
mem_principal],
assume x hx y hy,
refine ⟨min x y, lt_min hx hy,
λ a ha, ⟨ha.1, ha.2.trans (closed_ball_subset_closed_ball (min_le_left _ _))⟩,
λ a ha, ⟨ha.1, ha.2.trans (closed_ball_subset_closed_ball (min_le_right _ _))⟩⟩ },
{ exact ⟨(1 : ℝ), mem_Ioi.2 zero_lt_one⟩ }
end
instance filter_at_ne_bot (x : α) : (v.filter_at x).ne_bot :=
begin
simp only [ne_bot_iff, ←empty_mem_iff_bot, mem_filter_at_iff, not_exists, exists_prop,
mem_empty_iff_false, and_true, gt_iff_lt, not_and, ne.def, not_false_iff, not_forall],
assume ε εpos,
obtain ⟨w, w_sets, hw⟩ : ∃ (w ∈ v.sets_at x), w ⊆ closed_ball x ε := v.nontrivial x ε εpos,
exact ⟨w, w_sets, hw⟩
end
lemma eventually_filter_at_iff {x : α} {P : set α → Prop} :
(∀ᶠ a in v.filter_at x, P a) ↔ ∃ (ε > (0 : ℝ)), ∀ a ∈ v.sets_at x, a ⊆ closed_ball x ε → P a :=
v.mem_filter_at_iff
lemma eventually_filter_at_mem_sets (x : α) :
∀ᶠ a in v.filter_at x, a ∈ v.sets_at x :=
begin
simp only [eventually_filter_at_iff, exists_prop, and_true, gt_iff_lt,
implies_true_iff] {contextual := tt},
exact ⟨1, zero_lt_one⟩
end
lemma eventually_filter_at_subset_closed_ball (x : α) {ε : ℝ} (hε : 0 < ε) :
∀ᶠ (a : set α) in v.filter_at x, a ⊆ closed_ball x ε :=
begin
simp only [v.eventually_filter_at_iff],
exact ⟨ε, hε, λ a ha ha', ha'⟩,
end
lemma tendsto_filter_at_iff {ι : Type*} {l : filter ι} {f : ι → set α} {x : α} :
tendsto f l (v.filter_at x) ↔
(∀ᶠ i in l, f i ∈ v.sets_at x) ∧ (∀ (ε > (0 : ℝ)), ∀ᶠ i in l, f i ⊆ closed_ball x ε) :=
begin
refine ⟨λ H,
⟨H.eventually $ v.eventually_filter_at_mem_sets x,
λ ε hε, H.eventually $ v.eventually_filter_at_subset_closed_ball x hε⟩,
λ H s hs, (_ : ∀ᶠ i in l, f i ∈ s)⟩,
obtain ⟨ε, εpos, hε⟩ := v.mem_filter_at_iff.mp hs,
filter_upwards [H.1, H.2 ε εpos] with i hi hiε using hε _ hi hiε,
end
lemma eventually_filter_at_measurable_set (x : α) :
∀ᶠ a in v.filter_at x, measurable_set a :=
by { filter_upwards [v.eventually_filter_at_mem_sets x] with _ ha using v.measurable_set' _ _ ha }
lemma eventually_filter_at_subset_of_nhds {x : α} {o : set α} (hx : o ∈ 𝓝 x) :
∀ᶠ a in v.filter_at x, a ⊆ o :=
begin
rw eventually_filter_at_iff,
rcases metric.mem_nhds_iff.1 hx with ⟨ε, εpos, hε⟩,
exact ⟨ε/2, half_pos εpos,
λ a av ha, ha.trans ((closed_ball_subset_ball (half_lt_self εpos)).trans hε)⟩
end
lemma fine_subfamily_on_of_frequently (v : vitali_family μ) (f : α → set (set α)) (s : set α)
(h : ∀ x ∈ s, ∃ᶠ a in v.filter_at x, a ∈ f x) :
v.fine_subfamily_on f s :=
begin
assume x hx ε εpos,
obtain ⟨a, av, ha, af⟩ : ∃ (a : set α) (H : a ∈ v.sets_at x), a ⊆ closed_ball x ε ∧ a ∈ f x :=
v.frequently_filter_at_iff.1 (h x hx) ε εpos,
exact ⟨a, ⟨av, af⟩, ha⟩,
end
end vitali_family
|
Formal statement is: lemma out_eq_p: "a \<in> s \<Longrightarrow> n \<le> j \<Longrightarrow> a j = p" Informal statement is: If $a$ is an element of $s$ and $n \leq j$, then $a_j = p$. |
From September to November 2008 , Fey made multiple guest appearances on SNL to perform a series of parodies of Republican vice @-@ presidential candidate Sarah Palin . On the 34th season premiere episode , aired September 13 , 2008 , Fey imitated Palin in a sketch , alongside Amy Poehler as Hillary Clinton . Their repartee included Clinton needling Palin about her " Tina Fey glasses " . The sketch quickly became NBC 's most @-@ watched viral video ever , with 5 @.@ 7 million views by the following Wednesday . Fey reprised this role on the October 4 show , on the October 18 show where she was joined by the real Sarah Palin , and on the November 1 show , where she was joined by John McCain and his wife Cindy . The October 18 show had the best ratings of any SNL show since 1994 . The following year Fey won an Emmy in the category of Outstanding Guest Actress in a Comedy Series for her impersonation of Palin . Fey returned to SNL in April 2010 , and reprised her impression of Palin in one sketch titled the " Sarah Palin Network " . Fey once again did her impression of Palin when she hosted Saturday Night Live on May 8 , 2011 .
|
module Idris.Pretty
import Core.Metadata
import Data.List
import Data.Maybe
import Data.String
import Libraries.Control.ANSI.SGR
import Parser.Lexer.Source
import public Idris.Pretty.Render
import public Libraries.Text.PrettyPrint.Prettyprinter
import public Libraries.Text.PrettyPrint.Prettyprinter.Util
import Idris.REPL.Opts
import Idris.Syntax
%default covering
public export
data IdrisSyntax
= Hole
| TCon (Maybe Name) -- these may be primitive types
| DCon (Maybe Name) -- these may be primitive constructors
| Fun Name
| Bound
| Keyword
| Pragma
export
syntaxToDecoration : IdrisSyntax -> Maybe Decoration
syntaxToDecoration Hole = Nothing
syntaxToDecoration (TCon{}) = pure Typ
syntaxToDecoration (DCon{}) = pure Data
syntaxToDecoration (Fun{}) = pure Function
syntaxToDecoration Bound = pure Bound
syntaxToDecoration Keyword = pure Keyword
syntaxToDecoration Pragma = Nothing
export
kindAnn : KindedName -> Maybe IdrisSyntax
kindAnn (MkKindedName mcat fn nm) = do
cat <- mcat
pure $ case cat of
Bound => Bound
Func => Fun fn
DataCon{} => DCon (Just fn)
TyCon{} => TCon (Just fn)
export
showCategory : (IdrisSyntax -> ann) -> GlobalDef -> Doc ann -> Doc ann
showCategory embed def = annotateM (embed <$> kindAnn (gDefKindedName def))
public export
data IdrisAnn
= Warning
| Error
| ErrorDesc
| FileCtxt
| Code
| Meta
| Syntax IdrisSyntax
export
annToDecoration : IdrisAnn -> Maybe Decoration
annToDecoration (Syntax syn) = syntaxToDecoration syn
annToDecoration _ = Nothing
export
syntaxAnn : IdrisSyntax -> AnsiStyle
syntaxAnn Hole = color BrightGreen
syntaxAnn (TCon{}) = color BrightBlue
syntaxAnn (DCon{}) = color BrightRed
syntaxAnn (Fun{}) = color BrightGreen
syntaxAnn Bound = italic
syntaxAnn Keyword = color BrightWhite
syntaxAnn Pragma = color BrightMagenta
export
colorAnn : IdrisAnn -> AnsiStyle
colorAnn Warning = color Yellow <+> bold
colorAnn Error = color BrightRed <+> bold
colorAnn ErrorDesc = bold
colorAnn FileCtxt = color BrightBlue
colorAnn Code = color Magenta
colorAnn Meta = color Green
colorAnn (Syntax syn) = syntaxAnn syn
export
warning : Doc IdrisAnn -> Doc IdrisAnn
warning = annotate Warning
export
error : Doc IdrisAnn -> Doc IdrisAnn
error = annotate Error
export
errorDesc : Doc IdrisAnn -> Doc IdrisAnn
errorDesc = annotate ErrorDesc
export
fileCtxt : Doc IdrisAnn -> Doc IdrisAnn
fileCtxt = annotate FileCtxt
export
keyword : Doc IdrisSyntax -> Doc IdrisSyntax
keyword = annotate Keyword
export
meta : Doc IdrisAnn -> Doc IdrisAnn
meta = annotate Meta
export
hole : Doc IdrisSyntax -> Doc IdrisSyntax
hole = annotate Hole
export
code : Doc IdrisAnn -> Doc IdrisAnn
code = annotate Code
let_ : Doc IdrisSyntax
let_ = keyword (pretty "let")
in_ : Doc IdrisSyntax
in_ = keyword (pretty "in")
case_ : Doc IdrisSyntax
case_ = keyword (pretty "case")
of_ : Doc IdrisSyntax
of_ = keyword (pretty "of")
do_ : Doc IdrisSyntax
do_ = keyword (pretty "do")
with_ : Doc IdrisSyntax
with_ = keyword (pretty "with")
record_ : Doc IdrisSyntax
record_ = keyword (pretty "record")
impossible_ : Doc IdrisSyntax
impossible_ = keyword (pretty "impossible")
auto_ : Doc IdrisSyntax
auto_ = keyword (pretty "auto")
default_ : Doc IdrisSyntax
default_ = keyword (pretty "default")
rewrite_ : Doc IdrisSyntax
rewrite_ = keyword (pretty "rewrite")
export
pragma : Doc IdrisSyntax -> Doc IdrisSyntax
pragma = annotate Pragma
export
prettyRig : RigCount -> Doc ann
prettyRig = elimSemi (pretty '0' <+> space)
(pretty '1' <+> space)
(const emptyDoc)
mutual
prettyAlt : PClause' KindedName -> Doc IdrisSyntax
prettyAlt (MkPatClause _ lhs rhs _) =
space <+> pipe <++> prettyTerm lhs <++> pretty "=>" <++> prettyTerm rhs <+> semi
prettyAlt (MkWithClause _ lhs wval prf flags cs) =
space <+> pipe <++> angles (angles (reflow "with alts not possible")) <+> semi
prettyAlt (MkImpossible _ lhs) =
space <+> pipe <++> prettyTerm lhs <++> impossible_ <+> semi
prettyCase : PClause' KindedName -> Doc IdrisSyntax
prettyCase (MkPatClause _ lhs rhs _) =
prettyTerm lhs <++> pretty "=>" <++> prettyTerm rhs
prettyCase (MkWithClause _ lhs rhs prf flags _) =
space <+> pipe <++> angles (angles (reflow "with alts not possible"))
prettyCase (MkImpossible _ lhs) =
prettyTerm lhs <++> impossible_
prettyString : PStr' KindedName -> Doc IdrisSyntax
prettyString (StrLiteral _ str) = pretty str
prettyString (StrInterp _ tm) = prettyTerm tm
prettyDo : PDo' KindedName -> Doc IdrisSyntax
prettyDo (DoExp _ tm) = prettyTerm tm
prettyDo (DoBind _ _ n tm) = pretty n <++> pretty "<-" <++> prettyTerm tm
prettyDo (DoBindPat _ l tm alts) =
prettyTerm l <++> pretty "<-" <++> prettyTerm tm <+> hang 4 (fillSep $ prettyAlt <$> alts)
prettyDo (DoLet _ _ l rig _ tm) =
let_ <++> prettyRig rig <+> pretty l <++> equals <++> prettyTerm tm
prettyDo (DoLetPat _ l _ tm alts) =
let_ <++> prettyTerm l <++> equals <++> prettyTerm tm <+> hang 4 (fillSep $ prettyAlt <$> alts)
prettyDo (DoLetLocal _ ds) =
let_ <++> braces (angles (angles (pretty "definitions")))
prettyDo (DoRewrite _ rule) = rewrite_ <+> prettyTerm rule
prettyUpdate : PFieldUpdate' KindedName -> Doc IdrisSyntax
prettyUpdate (PSetField path v) =
concatWith (surround dot) (pretty <$> path) <++> equals <++> prettyTerm v
prettyUpdate (PSetFieldApp path v) =
concatWith (surround dot) (pretty <$> path) <++> pretty '$' <+> equals <++> prettyTerm v
prettyBinder : Name -> Doc IdrisSyntax
prettyBinder = annotate Bound . pretty
export
prettyTerm : IPTerm -> Doc IdrisSyntax
prettyTerm = go Open
where
startPrec : Prec
startPrec = User 0
appPrec : Prec
appPrec = User 10
leftAppPrec : Prec
leftAppPrec = User 9
prettyOp : OpStr' KindedName -> Doc IdrisSyntax
prettyOp op@(MkKindedName _ _ nm) = if isOpName nm
then annotateM (kindAnn op) $ pretty nm
else Chara '`' <+> annotateM (kindAnn op) (pretty nm) <+> Chara '`'
go : Prec -> IPTerm -> Doc IdrisSyntax
go d (PRef _ nm) = annotateM (kindAnn nm) $ pretty nm.rawName
go d (PPi _ rig Explicit Nothing arg ret) =
parenthesise (d > startPrec) $ group $
branchVal
(go startPrec arg <++> "->" <++> go startPrec ret)
(parens (prettyRig rig <+> "_" <++> colon <++> go startPrec arg)
<++> "->" <+> softline <+> go startPrec ret)
rig
go d (PPi _ rig Explicit (Just n) arg ret) =
parenthesise (d > startPrec) $ group $
parens (prettyRig rig <+> prettyBinder n
<++> colon <++> go startPrec arg)
<++> "->" <+> softline <+> go startPrec ret
go d (PPi _ rig Implicit Nothing arg ret) =
parenthesise (d > startPrec) $ group $
braces (prettyRig rig <+> pretty '_'
<++> colon <++> go startPrec arg)
<++> "->" <+> softline <+> go startPrec ret
go d (PPi _ rig Implicit (Just n) arg ret) =
parenthesise (d > startPrec) $ group $
braces (prettyRig rig <+> prettyBinder n
<++> colon <++> go startPrec arg)
<++> "->" <+> softline <+> go startPrec ret
go d (PPi _ rig AutoImplicit Nothing arg ret) =
parenthesise (d > startPrec) $ group $
branchVal
(go startPrec arg <++> "=>" <+> softline <+> go startPrec ret)
(braces (auto_ <++> prettyRig rig <+> "_"
<++> colon <++> go startPrec arg)
<++> "->" <+> softline <+> go startPrec ret)
rig
go d (PPi _ rig AutoImplicit (Just n) arg ret) =
parenthesise (d > startPrec) $ group $
braces (auto_ <++> prettyRig rig <+> prettyBinder n
<++> colon <++> go startPrec arg)
<++> "->" <+> softline <+> go startPrec ret
go d (PPi _ rig (DefImplicit t) Nothing arg ret) =
parenthesise (d > startPrec) $ group $
braces (default_ <++> go appPrec t <++> prettyRig rig <+> "_"
<++> colon <++> go startPrec arg)
<++> "->" <+> softline <+> go startPrec ret
go d (PPi _ rig (DefImplicit t) (Just n) arg ret) =
parenthesise (d > startPrec) $ group $
braces (default_ <++> go appPrec t
<++> prettyRig rig <+> prettyBinder n
<++> colon <++> go startPrec arg)
<++> "->" <+> softline <+> go startPrec ret
go d (PLam _ rig _ n ty sc) =
let (ns, sc) = getLamNames [(rig, n, ty)] sc in
parenthesise (d > startPrec) $ group $
backslash <+> prettyBindings ns <++> "=>" <+> softline <+> go startPrec sc
where
getLamNames : List (RigCount, IPTerm, IPTerm) ->
IPTerm ->
(List (RigCount, IPTerm, IPTerm), IPTerm)
getLamNames acc (PLam _ rig _ n ty sc) = getLamNames ((rig, n, ty) :: acc) sc
getLamNames acc sc = (reverse acc, sc)
prettyBindings : List (RigCount, IPTerm, IPTerm) -> Doc IdrisSyntax
prettyBindings [] = neutral
prettyBindings [(rig, n, (PImplicit _))] = prettyRig rig <+> go startPrec n
prettyBindings [(rig, n, ty)] = prettyRig rig <+> go startPrec n <++> colon <++> go startPrec ty
prettyBindings ((rig, n, (PImplicit _)) :: ns) = prettyRig rig <+> go startPrec n <+> comma <+> line <+> prettyBindings ns
prettyBindings ((rig, n, ty) :: ns) = prettyRig rig <+> go startPrec n <++> colon <++> go startPrec ty <+> comma <+> line <+> prettyBindings ns
go d (PLet _ rig n (PImplicit _) val sc alts) =
-- Hide uninformative lets
-- (Those that look like 'let x = x in ...')
-- Makes printing the types of names bound in where clauses a lot
-- more readable
fromMaybe fullLet $ do
nName <- getPRefName n
valName <- getPRefName val
guard (show nName == show valName)
pure continuation
-- Hide lets that bind to underscore
-- That is, 'let _ = x in ...'
-- Those end up polluting the types of let bound variables in some
-- occasions
<|> do
nName <- getPRefName n
guard (isUnderscoreName nName)
pure continuation
where
continuation : Doc IdrisSyntax
continuation = go startPrec sc
fullLet : Doc IdrisSyntax
fullLet = parenthesise (d > startPrec) $ group $ align $
let_ <++> (group $ align $ hang 2 $ prettyRig rig <+> go startPrec n <++> equals <+> line <+> go startPrec val) <+> line
<+> in_ <++> (group $ align $ hang 2 $ continuation)
getPRefName : IPTerm -> Maybe Name
getPRefName (PRef _ n) = Just (rawName n)
getPRefName _ = Nothing
go d (PLet _ rig n ty val sc alts) =
parenthesise (d > startPrec) $ group $ align $
let_ <++> (group $ align $ hang 2 $ prettyRig rig <+> go startPrec n <++> colon <++> go startPrec ty <++> equals <+> line <+> go startPrec val) <+> hardline
<+> hang 4 (fillSep (prettyAlt <$> alts)) <+> line <+> in_ <++> (group $ align $ hang 2 $ go startPrec sc)
go d (PCase _ tm cs) =
parenthesise (d > appPrec) $ align $ case_ <++> go startPrec tm <++> of_ <+> line <+>
braces (vsep $ punctuate semi (prettyCase <$> cs))
go d (PLocal _ ds sc) =
parenthesise (d > startPrec) $ group $ align $
let_ <++> braces (angles (angles "definitions")) <+> line <+> in_ <++> go startPrec sc
go d (PUpdate _ fs) =
parenthesise (d > appPrec) $ group $ record_ <++> braces (vsep $ punctuate comma (prettyUpdate <$> fs))
go d (PApp _ f a) =
let catchall : Lazy (Doc IdrisSyntax)
:= go leftAppPrec f <++> go appPrec a
in parenthesise (d > appPrec) $ group $ case f of
(PRef _ n) =>
if isJust (isRF $ rawName n)
then go leftAppPrec a <++> go appPrec f
else catchall
_ => catchall
go d (PWithApp _ f a) = go d f <++> pipe <++> go d a
go d (PDelayed _ LInf ty) = parenthesise (d > appPrec) $ "Inf" <++> go appPrec ty
go d (PDelayed _ _ ty) = parenthesise (d > appPrec) $ "Lazy" <++> go appPrec ty
go d (PDelay _ tm) = parenthesise (d > appPrec) $ "Delay" <++> go appPrec tm
go d (PForce _ tm) = parenthesise (d > appPrec) $ "Force" <++> go appPrec tm
go d (PAutoApp _ f a) =
parenthesise (d > appPrec) $ group $ go leftAppPrec f <++> "@" <+> braces (go startPrec a)
go d (PNamedApp _ f n (PRef _ a)) =
parenthesise (d > appPrec) $ group $
if n == rawName a
then go leftAppPrec f <++> braces (pretty n)
else go leftAppPrec f <++> braces (pretty n <++> equals <++> pretty a.rawName)
go d (PNamedApp _ f n a) =
parenthesise (d > appPrec) $ group $ go leftAppPrec f <++> braces (pretty n <++> equals <++> go d a)
go d (PSearch _ _) = pragma "%search"
go d (PQuote _ tm) = parenthesise (d > appPrec) $ "`" <+> parens (go startPrec tm)
go d (PQuoteName _ n) = parenthesise (d > appPrec) $ "`" <+> braces (braces (pretty n))
go d (PQuoteDecl _ tm) = parenthesise (d > appPrec) $ "`" <+> brackets (angles (angles (pretty "declaration")))
go d (PUnquote _ tm) = parenthesise (d > appPrec) $ "~" <+> parens (go startPrec tm)
go d (PRunElab _ tm) = parenthesise (d > appPrec) $ pragma "%runElab" <++> go startPrec tm
go d (PPrimVal _ c) =
let decor = if isPrimType c then TCon Nothing else DCon Nothing in
annotate decor $ pretty c
go d (PHole _ _ n) = hole (pretty (strCons '?' n))
go d (PType _) = annotate (TCon Nothing) "Type"
go d (PAs _ _ n p) = pretty n <+> "@" <+> go d p
go d (PDotted _ p) = dot <+> go d p
go d (PImplicit _) = "_"
go d (PInfer _) = annotate Hole $ "?"
go d (POp _ _ op x y) = parenthesise (d > appPrec) $ group $ go startPrec x <++> prettyOp op <++> go startPrec y
go d (PPrefixOp _ _ op x) = parenthesise (d > appPrec) $ prettyOp op <+> go startPrec x
go d (PSectionL _ _ op x) = parens (prettyOp op <++> go startPrec x)
go d (PSectionR _ _ x op) = parens (go startPrec x <++> prettyOp op)
go d (PEq fc l r) = parenthesise (d > appPrec) $ go startPrec l <++> equals <++> go startPrec r
go d (PBracketed _ tm) = parens (go startPrec tm)
go d (PString _ xs) = parenthesise (d > appPrec) $ hsep $ punctuate "++" (prettyString <$> xs)
go d (PMultiline _ indent xs) = "multiline" <++> (parenthesise (d > appPrec) $ hsep $ punctuate "++" (prettyString <$> concat xs))
go d (PDoBlock _ ns ds) = parenthesise (d > appPrec) $ group $ align $ hang 2 $ do_ <++> (vsep $ punctuate semi (prettyDo <$> ds))
go d (PBang _ tm) = "!" <+> go d tm
go d (PIdiom _ tm) = enclose (pretty "[|") (pretty "|]") (go startPrec tm)
go d (PList _ _ xs) = brackets (group $ align $ vsep $ punctuate comma (go startPrec . snd <$> xs))
go d (PSnocList _ _ xs) = brackets {ldelim = "[<"}
(group $ align $ vsep $ punctuate comma (go startPrec . snd <$> xs))
go d (PPair _ l r) = group $ parens (go startPrec l <+> comma <+> line <+> go startPrec r)
go d (PDPair _ _ l (PImplicit _) r) = group $ parens (go startPrec l <++> pretty "**" <+> line <+> go startPrec r)
go d (PDPair _ _ l ty r) = group $ parens (go startPrec l <++> colon <++> go startPrec ty <++> pretty "**" <+> line <+> go startPrec r)
go d (PUnit _) = "()"
go d (PIfThenElse _ x t e) =
parenthesise (d > appPrec) $ group $ align $ hang 2 $ vsep
[keyword "if" <++> go startPrec x, keyword "then" <++> go startPrec t, keyword "else" <++> go startPrec e]
go d (PComprehension _ ret es) =
group $ brackets (go startPrec (dePure ret) <++> pipe <++> vsep (punctuate comma (prettyDo . deGuard <$> es)))
where
dePure : IPTerm -> IPTerm
dePure tm@(PApp _ (PRef _ n) arg)
= if dropNS (rawName n) == UN (Basic "pure") then arg else tm
dePure tm = tm
deGuard : PDo' KindedName -> PDo' KindedName
deGuard tm@(DoExp fc (PApp _ (PRef _ n) arg))
= if dropNS (rawName n) == UN (Basic "guard") then DoExp fc arg else tm
deGuard tm = tm
go d (PRewrite _ rule tm) =
parenthesise (d > appPrec) $ group $ rewrite_ <++> go startPrec rule <+> line <+> in_ <++> go startPrec tm
go d (PRange _ start Nothing end) =
brackets (go startPrec start <++> pretty ".." <++> go startPrec end)
go d (PRange _ start (Just next) end) =
brackets (go startPrec start <+> comma <++> go startPrec next <++> pretty ".." <++> go startPrec end)
go d (PRangeStream _ start Nothing) = brackets (go startPrec start <++> pretty "..")
go d (PRangeStream _ start (Just next)) =
brackets (go startPrec start <+> comma <++> go startPrec next <++> pretty "..")
go d (PUnifyLog _ lvl tm) = go d tm
go d (PPostfixApp fc rec fields) =
parenthesise (d > appPrec) $ go startPrec rec <++> dot <+> concatWith (surround dot) (map pretty fields)
go d (PPostfixAppPartial fc fields) =
parens (dot <+> concatWith (surround dot) (map pretty fields))
go d (PWithUnambigNames fc ns rhs) = parenthesise (d > appPrec) $ group $ with_ <++> pretty ns <+> line <+> go startPrec rhs
export
render : {auto o : Ref ROpts REPLOpts} -> Doc IdrisAnn -> Core String
render = render colorAnn
export
renderWithDecorations :
{auto c : Ref Ctxt Defs} ->
{auto o : Ref ROpts REPLOpts} ->
(ann -> Maybe ann') ->
Doc ann ->
Core (String, List (Span ann'))
renderWithDecorations f doc =
do (str, mspans) <- Render.renderWithSpans doc
let spans = mapMaybe (traverse f) mspans
pure (str, spans)
|
module SameName where
data Stuff : Set where
mkStuff : Stuff
stuffFunc : Stuff -> (Stuff : Set) -> Stuff
stuffFunc = {! !}
|
module WTypes
data W : (t : Type) -> (p : t -> Type) -> Type where
Sup : (x : t) -> (p x -> W t p) -> W t p
ind : {t : Type} -> {p : t -> Type} -> (pred : W t p -> Type) ->
((v : t) -> (f : p v -> W t p) -> ((t' : p v) -> pred (f t')) -> pred (Sup v f)) ->
(w : W t p) -> pred w
ind _ p (Sup x f) = p x f (\t => ind _ p (f t))
efq : {a : Type} -> Void -> a
-- Nat encoding
N : Type
N = W Bool (\b => if b then () else Void)
zero : N
zero = Sup False efq
succ : N -> N
succ n = Sup True (const n)
plus : N -> N -> N
plus (Sup False f) b = b
plus (Sup True f) b = Sup True (\() => plus (f ()) b)
-- Tree encoding
Tree : Type
Tree = W Bool (\b => if b then Bool else Void)
leaf : Tree
leaf = Sup False efq
branch : Tree -> Tree -> Tree
branch l r = Sup True (\b => if b then l else r)
size : Tree -> N
size (Sup False f) = zero
size (Sup True f) = plus (size (f True)) (size (f False))
|
.fp \np br
.lg 0
|
The product of a polynomial and zero is zero. |
section \<open>Recursive inseperability\<close>
theory Recursive_Inseparability
imports "Recursion-Theory-I.RecEnSet"
begin
text \<open>Two sets $A$ and $B$ are recursively inseparable if there is no computable set that
contains $A$ and is disjoint from $B$. In particular, a set is computable if the set and its
complement are recursively inseparable. The terminology was introduced by Smullyan~\<^cite>\<open>R58\<close>.
The underlying idea can be traced back to Rosser, who essentially showed that provable and
disprovable sentences are \emph{arithmetically} inseparable in Peano Arithmetic~\<^cite>\<open>R36\<close>;
see also Kleene's symmetric version of Gödel's incompleteness theorem~\<^cite>\<open>K52\<close>.
Here we formalize recursive inseparability on top of the \texttt{Recursion-Theory-I} AFP
entry~\<^cite>\<open>RTI\<close>. Our main result is a version of Rice' theorem that states that the index
sets of any two given recursively enumerable sets are recursively inseparable.\<close>
subsection \<open>Definition and basic facts\<close>
text \<open>Two sets $A$ and $B$ are recursively inseparable if there are no decidable sets $X$ such
that $A$ is a subset of $X$ and $X$ is disjoint from $B$.\<close>
definition rec_inseparable where
"rec_inseparable A B \<equiv> \<forall>X. A \<subseteq> X \<and> B \<subseteq> - X \<longrightarrow> \<not> computable X"
lemma rec_inseparableI:
"(\<And>X. A \<subseteq> X \<Longrightarrow> B \<subseteq> - X \<Longrightarrow> computable X \<Longrightarrow> False) \<Longrightarrow> rec_inseparable A B"
unfolding rec_inseparable_def by blast
lemma rec_inseparableD:
"rec_inseparable A B \<Longrightarrow> A \<subseteq> X \<Longrightarrow> B \<subseteq> - X \<Longrightarrow> computable X \<Longrightarrow> False"
unfolding rec_inseparable_def by blast
text \<open>Recursive inseperability is symmetric and enjoys a monotonicity property.\<close>
lemma rec_inseparable_symmetric:
"rec_inseparable A B \<Longrightarrow> rec_inseparable B A"
unfolding rec_inseparable_def computable_def by (metis double_compl)
lemma rec_inseparable_mono:
"rec_inseparable A B \<Longrightarrow> A \<subseteq> A' \<Longrightarrow> B \<subseteq> B' \<Longrightarrow> rec_inseparable A' B'"
unfolding rec_inseparable_def by (meson subset_trans)
text \<open>Many-to-one reductions apply to recursive inseparability as well.\<close>
lemma rec_inseparable_many_reducible:
assumes "total_recursive f" "rec_inseparable (f -` A) (f -` B)"
shows "rec_inseparable A B"
proof (intro rec_inseparableI)
fix X assume "A \<subseteq> X" "B \<subseteq> - X" "computable X"
moreover have "many_reducible_to (f -` X) X" using assms(1)
by (auto simp: many_reducible_to_def many_reducible_to_via_def)
ultimately have "computable (f -` X)" and "(f -` A) \<subseteq> (f -` X)" and "(f -` B) \<subseteq> - (f -` X)"
by (auto dest!: m_red_to_comp)
then show "False" using assms(2) unfolding rec_inseparable_def by blast
qed
text \<open>Recursive inseparability of $A$ and $B$ holds vacuously if $A$ and $B$ are not disjoint.\<close>
lemma rec_inseparable_collapse:
"A \<inter> B \<noteq> {} \<Longrightarrow> rec_inseparable A B"
by (auto simp: rec_inseparable_def)
text \<open>Recursive inseparability is intimately connected to non-computability.\<close>
lemma rec_inseparable_non_computable:
"A \<inter> B = {} \<Longrightarrow> rec_inseparable A B \<Longrightarrow> \<not> computable A"
by (auto simp: rec_inseparable_def)
lemma computable_rec_inseparable_conv:
"computable A \<longleftrightarrow> \<not> rec_inseparable A (- A)"
by (auto simp: computable_def rec_inseparable_def)
subsection \<open>Rice's theorem\<close>
text \<open>We provide a stronger version of Rice's theorem compared to \<^cite>\<open>RTI\<close>.
Unfolding the definition of recursive inseparability, it states that there are no decidable
sets $X$ such that
\begin{itemize}
\item there is a r.e.\ set such that all its indices are elements of $X$; and
\item there is a r.e.\ set such that none of its indices are elements of $X$.
\end{itemize}
This is true even if $X$ is not an index set (i.e., if an index of a r.e.\ set is an element
of $X$, then $X$ contains all indices of that r.e.\ set), which is a requirement of Rice's
theorem in \<^cite>\<open>RTI\<close>.\<close>
lemma Rice_rec_inseparable:
"rec_inseparable {k. nat_to_ce_set k = nat_to_ce_set n} {k. nat_to_ce_set k = nat_to_ce_set m}"
proof (intro rec_inseparableI, goal_cases)
case (1 X)
text \<open>Note that @{thm Rice_2} is not applicable because X may not be an index set.\<close>
let ?Q = "{q. s_ce q q \<in> X} \<times> nat_to_ce_set m \<union> {q. s_ce q q \<in> - X} \<times> nat_to_ce_set n"
have "?Q \<in> ce_rels"
using 1(3) ce_set_lm_5 comp2_1[OF s_ce_is_pr id1_1 id1_1] unfolding computable_def
by (intro ce_union[of "ce_rel_to_set _" "ce_rel_to_set _", folded ce_rel_lm_32 ce_rel_lm_8]
ce_rel_lm_29 nat_to_ce_set_into_ce) blast+
then obtain q where "nat_to_ce_set q = {c_pair q x |q x. (q, x) \<in> ?Q}"
unfolding ce_rel_lm_8 ce_rel_to_set_def by (metis (no_types, lifting) nat_to_ce_set_srj)
from eqset_imp_iff[OF this, of "c_pair q _"]
have "nat_to_ce_set (s_ce q q) = (if s_ce q q \<in> X then nat_to_ce_set m else nat_to_ce_set n)"
by (auto simp: s_lm c_pair_inj' nat_to_ce_set_def fn_to_set_def pr_conv_1_to_2_def)
then show ?case using 1(1,2)[THEN subsetD, of "s_ce q q"] by (auto split: if_splits)
qed
end |
/* movstat/mmacc.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* This module contains routines for tracking minimum/maximum values of a
* moving fixed-sized window. It is based on the algorithm of:
*
* [1] Daniel Lemire, Streaming Maximum-Minimum Filter Using No More than Three Comparisons per Element,
* Nordic Journal of Computing, Volume 13, Number 4, pages 328-339, 2006
*
* Also available as a preprint here: https://arxiv.org/abs/cs/0610046
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_movstat.h>
typedef double mmacc_type_t;
typedef mmacc_type_t ringbuf_type_t;
#include "deque.c"
#include "ringbuf.c"
typedef struct
{
size_t n; /* window size */
size_t k; /* number of samples in current window */
mmacc_type_t xprev; /* previous sample added to window */
ringbuf *rbuf; /* ring buffer storing current window, size n */
deque *minque; /* double-ended queue of min values (L) */
deque *maxque; /* double-ended queue of max values (U) */
} mmacc_state_t;
static size_t mmacc_size(const size_t n);
static int mmacc_init(const size_t n, void * vstate);
static int mmacc_insert(const mmacc_type_t x, void * vstate);
static int mmacc_delete(void * vstate);
static int mmacc_min(void * params, mmacc_type_t * result, const void * vstate);
static int mmacc_max(void * params, mmacc_type_t * result, const void * vstate);
static int mmacc_minmax(void * params, mmacc_type_t * result, const void * vstate);
static size_t
mmacc_size(const size_t n)
{
size_t size = 0;
size += sizeof(mmacc_state_t);
size += ringbuf_size(n); /* rbuf */
size += 2 * deque_size(n + 1); /* minque/maxque */
return size;
}
static int
mmacc_init(const size_t n, void * vstate)
{
mmacc_state_t * state = (mmacc_state_t *) vstate;
state->n = n;
state->k = 0;
state->xprev = 0.0;
state->rbuf = (ringbuf *) ((unsigned char *) vstate + sizeof(mmacc_state_t));
state->minque = (deque *) ((unsigned char *) state->rbuf + ringbuf_size(n));
state->maxque = (deque *) ((unsigned char *) state->minque + deque_size(n + 1));
ringbuf_init(n, state->rbuf);
deque_init(n + 1, state->minque);
deque_init(n + 1, state->maxque);
return GSL_SUCCESS;
}
static int
mmacc_insert(const mmacc_type_t x, void * vstate)
{
mmacc_state_t * state = (mmacc_state_t *) vstate;
int head, tail;
if (state->k == 0)
{
/* first sample */
ringbuf_insert(x, state->rbuf);
head = state->rbuf->head;
deque_push_back(head, state->maxque);
deque_push_back(head, state->minque);
}
else
{
if (x > state->xprev)
{
deque_pop_back(state->maxque);
while (!deque_is_empty(state->maxque))
{
if (x <= state->rbuf->array[deque_peek_back(state->maxque)])
break;
deque_pop_back(state->maxque);
}
}
else
{
deque_pop_back(state->minque);
while (!deque_is_empty(state->minque))
{
if (x >= state->rbuf->array[deque_peek_back(state->minque)])
break;
deque_pop_back(state->minque);
}
}
/* store new sample into ring buffer */
tail = state->rbuf->tail;
ringbuf_insert(x, state->rbuf);
head = state->rbuf->head;
deque_push_back(head, state->maxque);
deque_push_back(head, state->minque);
if (state->k == state->n)
{
/*
* window is full - check if oldest window element is a global minimum/maximum
* of current window - if so pop it from U/L queues;
* the check head != tail ensures there is more than 1 element in the
* queue, do not pop if queue has only 1 element, since this element would
* be the newest sample
*/
if (state->maxque->head != state->maxque->tail && tail == deque_peek_front(state->maxque))
deque_pop_front(state->maxque);
else if (state->minque->head != state->minque->tail && tail == deque_peek_front(state->minque))
deque_pop_front(state->minque);
}
}
if (state->k < state->n)
++(state->k);
state->xprev = x;
return GSL_SUCCESS;
}
static int
mmacc_delete(void * vstate)
{
mmacc_state_t * state = (mmacc_state_t *) vstate;
if (state->k > 0)
{
/*
* check if oldest window element is a global minimum/maximum; if so
* pop it from U/L queues
*/
if (state->rbuf->tail == deque_peek_front(state->maxque))
deque_pop_front(state->maxque);
else if (state->rbuf->tail == deque_peek_front(state->minque))
deque_pop_front(state->minque);
/* remove oldest element from ring buffer */
ringbuf_pop_back(state->rbuf);
--(state->k);
}
return GSL_SUCCESS;
}
static int
mmacc_min(void * params, mmacc_type_t * result, const void * vstate)
{
const mmacc_state_t * state = (const mmacc_state_t *) vstate;
(void) params;
if (state->k == 0)
{
GSL_ERROR ("no samples yet added to workspace", GSL_EINVAL);
}
else
{
*result = state->rbuf->array[deque_peek_front(state->minque)];
return GSL_SUCCESS;
}
}
static int
mmacc_max(void * params, mmacc_type_t * result, const void * vstate)
{
const mmacc_state_t * state = (const mmacc_state_t *) vstate;
(void) params;
if (state->k == 0)
{
GSL_ERROR ("no samples yet added to workspace", GSL_EINVAL);
}
else
{
*result = state->rbuf->array[deque_peek_front(state->maxque)];
return GSL_SUCCESS;
}
}
static int
mmacc_minmax(void * params, mmacc_type_t * result, const void * vstate)
{
const mmacc_state_t * state = (const mmacc_state_t *) vstate;
(void) params;
if (state->k == 0)
{
GSL_ERROR ("no samples yet added to workspace", GSL_EINVAL);
}
else
{
result[0] = state->rbuf->array[deque_peek_front(state->minque)];
result[1] = state->rbuf->array[deque_peek_front(state->maxque)];
return GSL_SUCCESS;
}
}
static const gsl_movstat_accum min_accum_type =
{
mmacc_size,
mmacc_init,
mmacc_insert,
mmacc_delete,
mmacc_min
};
const gsl_movstat_accum *gsl_movstat_accum_min = &min_accum_type;
static const gsl_movstat_accum max_accum_type =
{
mmacc_size,
mmacc_init,
mmacc_insert,
mmacc_delete,
mmacc_max
};
const gsl_movstat_accum *gsl_movstat_accum_max = &max_accum_type;
static const gsl_movstat_accum minmax_accum_type =
{
mmacc_size,
mmacc_init,
mmacc_insert,
mmacc_delete,
mmacc_minmax
};
const gsl_movstat_accum *gsl_movstat_accum_minmax = &minmax_accum_type;
|
%% bisturbile_defense_matrix.tex
%% V1.4b
%% 2015/08/26
%% by Michael Shell
%% See:
%% http://www.michaelshell.org/
%% for current contact information.
%%
%% This is a skeleton file demonstrating the advanced use of IEEEtran.cls
%% (requires IEEEtran.cls version 1.8b or later) with an IEEE Computer
%% Society journal paper.
%%
%% Support sites:
%% http://www.michaelshell.org/tex/ieeetran/
%% http://www.ctan.org/pkg/ieeetran
%% and
%% http://www.ieee.org/
%%*************************************************************************
%% Legal Notice:
%% This code is offered as-is without any warranty either expressed or
%% implied; without even the implied warranty of MERCHANTABILITY or
%% FITNESS FOR A PARTICULAR PURPOSE!
%% User assumes all risk.
%% In no event shall the IEEE or any contributor to this code be liable for
%% any damages or losses, including, but not limited to, incidental,
%% consequential, or any other damages, resulting from the use or misuse
%% of any information contained here.
%%
%% All comments are the opinions of their respective authors and are not
%% necessarily endorsed by the IEEE.
%%
%% This work is distributed under the LaTeX Project Public License (LPPL)
%% ( http://www.latex-project.org/ ) version 1.3, and may be freely used,
%% distributed and modified. A copy of the LPPL, version 1.3, is included
%% in the base LaTeX documentation of all distributions of LaTeX released
%% 2003/12/01 or later.
%% Retain all contribution notices and credits.
%% ** Modified files should be clearly indicated as such, including **
%% ** renaming them and changing author support contact information. **
%%*************************************************************************
% *** Authors should verify (and, if needed, correct) their LaTeX system ***
% *** with the testflow diagnostic prior to trusting their LaTeX platform ***
% *** with production work. The IEEE's font choices and paper sizes can ***
% *** trigger bugs that do not appear when using other class files. *** ***
% The testflow support page is at:
% http://www.michaelshell.org/tex/testflow/
% IEEEtran V1.7 and later provides for these CLASSINPUT macros to allow the
% user to reprogram some IEEEtran.cls defaults if needed. These settings
% override the internal defaults of IEEEtran.cls regardless of which class
% options are used. Do not use these unless you have good reason to do so as
% they can result in nonIEEE compliant documents. User beware. ;)
%
%\newcommand{\CLASSINPUTbaselinestretch}{1.0} % baselinestretch
%\newcommand{\CLASSINPUTinnersidemargin}{1in} % inner side margin
%\newcommand{\CLASSINPUToutersidemargin}{1in} % outer side margin
%\newcommand{\CLASSINPUTtoptextmargin}{1in} % top text margin
%\newcommand{\CLASSINPUTbottomtextmargin}{1in}% bottom text margin
%
\documentclass[10pt,journal,compsoc]{IEEEtran}
% If IEEEtran.cls has not been installed into the LaTeX system files,
% manually specify the path to it like:
% \documentclass[10pt,journal,compsoc]{../sty/IEEEtran}
% For Computer Society journals, IEEEtran defaults to the use of
% Palatino/Palladio as is done in IEEE Computer Society journals.
% To go back to Times Roman, you can use this code:
%\renewcommand{\rmdefault}{ptm}\selectfont
% Some very useful LaTeX packages include:
% (uncomment the ones you want to load)
% *** MISC UTILITY PACKAGES ***
%
%\usepackage{ifpdf}
% Heiko Oberdiek's ifpdf.sty is very useful if you need conditional
% compilation based on whether the output is pdf or dvi.
% usage:
% \ifpdf
% % pdf code
% \else
% % dvi code
% \fi
% The latest version of ifpdf.sty can be obtained from:
% http://www.ctan.org/pkg/ifpdf
% Also, note that IEEEtran.cls V1.7 and later provides a builtin
% \ifCLASSINFOpdf conditional that works the same way.
% When switching from latex to pdflatex and vice-versa, the compiler may
% have to be run twice to clear warning/error messages.
% *** CITATION PACKAGES ***
%
\ifCLASSOPTIONcompsoc
% The IEEE Computer Society needs nocompress option
% requires cite.sty v4.0 or later (November 2003)
\usepackage[nocompress]{cite}
\else
% normal IEEE
\usepackage{cite}
\fi
% cite.sty was written by Donald Arseneau
% V1.6 and later of IEEEtran pre-defines the format of the cite.sty package
% \cite{} output to follow that of the IEEE. Loading the cite package will
% result in citation numbers being automatically sorted and properly
% "compressed/ranged". e.g., [1], [9], [2], [7], [5], [6] without using
% cite.sty will become [1], [2], [5]--[7], [9] using cite.sty. cite.sty's
% \cite will automatically add leading space, if needed. Use cite.sty's
% noadjust option (cite.sty V3.8 and later) if you want to turn this off
% such as if a citation ever needs to be enclosed in parenthesis.
% cite.sty is already installed on most LaTeX systems. Be sure and use
% version 5.0 (2009-03-20) and later if using hyperref.sty.
% The latest version can be obtained at:
% http://www.ctan.org/pkg/cite
% The documentation is contained in the cite.sty file itself.
%
% Note that some packages require special options to format as the Computer
% Society requires. In particular, Computer Society papers do not use
% compressed citation ranges as is done in typical IEEE papers
% (e.g., [1]-[4]). Instead, they list every citation separately in order
% (e.g., [1], [2], [3], [4]). To get the latter we need to load the cite
% package with the nocompress option which is supported by cite.sty v4.0
% and later.
% *** GRAPHICS RELATED PACKAGES ***
%
%\ifCLASSINFOpdf
\usepackage{graphicx}
%\DeclareGraphicsExtensions{.pdf,.jpeg,.png}
%\else
% % or other class option (dvipsone, dvipdf, if not using dvips). graphicx
% % will default to the driver specified in the system graphics.cfg if no
% % driver is specified.
% % \usepackage[dvips]{graphicx}
% % declare the path(s) where your graphic files are
% % \graphicspath{{../eps/}}
% % and their extensions so you won't have to specify these with
% % every instance of \includegraphics
% % \DeclareGraphicsExtensions{.eps}
%\fi
% graphicx was written by David Carlisle and Sebastian Rahtz. It is
% required if you want graphics, photos, etc. graphicx.sty is already
% installed on most LaTeX systems. The latest version and documentation
% can be obtained at:
% http://www.ctan.org/pkg/graphicx
% Another good source of documentation is "Using Imported Graphics in
% LaTeX2e" by Keith Reckdahl which can be found at:
% http://www.ctan.org/pkg/epslatex
%
% latex, and pdflatex in dvi mode, support graphics in encapsulated
% postscript (.eps) format. pdflatex in pdf mode supports graphics
% in .pdf, .jpeg, .png and .mps (metapost) formats. Users should ensure
% that all non-photo figures use a vector format (.eps, .pdf, .mps) and
% not a bitmapped formats (.jpeg, .png). The IEEE frowns on bitmapped formats
% which can result in "jaggedy"/blurry rendering of lines and letters as
% well as large increases in file sizes.
%
% You can find documentation about the pdfTeX application at:
% http://www.tug.org/applications/pdftex
% *** MATH PACKAGES ***
%
%\usepackage{amsmath}
% A popular package from the American Mathematical Society that provides
% many useful and powerful commands for dealing with mathematics.
%
% Note that the amsmath package sets \interdisplaylinepenalty to 10000
% thus preventing page breaks from occurring within multiline equations. Use:
%\interdisplaylinepenalty=2500
% after loading amsmath to restore such page breaks as IEEEtran.cls normally
% does. amsmath.sty is already installed on most LaTeX systems. The latest
% version and documentation can be obtained at:
% http://www.ctan.org/pkg/amsmath
% *** SPECIALIZED LIST PACKAGES ***
%\usepackage{acronym}
% acronym.sty was written by Tobias Oetiker. This package provides tools for
% managing documents with large numbers of acronyms. (You don't *have* to
% use this package - unless you have a lot of acronyms, you may feel that
% such package management of them is bit of an overkill.)
% Do note that the acronym environment (which lists acronyms) will have a
% problem when used under IEEEtran.cls because acronym.sty relies on the
% description list environment - which IEEEtran.cls has customized for
% producing IEEE style lists. A workaround is to declared the longest
% label width via the IEEEtran.cls \IEEEiedlistdecl global control:
%
% \renewcommand{\IEEEiedlistdecl}{\IEEEsetlabelwidth{SONET}}
% \begin{acronym}
%
% \end{acronym}
% \renewcommand{\IEEEiedlistdecl}{\relax}% remember to reset \IEEEiedlistdecl
%
% instead of using the acronym environment's optional argument.
% The latest version and documentation can be obtained at:
% http://www.ctan.org/pkg/acronym
%\usepackage{algorithmic}
% algorithmic.sty was written by Peter Williams and Rogerio Brito.
% This package provides an algorithmic environment fo describing algorithms.
% You can use the algorithmic environment in-text or within a figure
% environment to provide for a floating algorithm. Do NOT use the algorithm
% floating environment provided by algorithm.sty (by the same authors) or
% algorithm2e.sty (by Christophe Fiorio) as the IEEE does not use dedicated
% algorithm float types and packages that provide these will not provide
% correct IEEE style captions. The latest version and documentation of
% algorithmic.sty can be obtained at:
% http://www.ctan.org/pkg/algorithms
% Also of interest may be the (relatively newer and more customizable)
% algorithmicx.sty package by Szasz Janos:
% http://www.ctan.org/pkg/algorithmicx
% *** ALIGNMENT PACKAGES ***
%
%\usepackage{array}
% Frank Mittelbach's and David Carlisle's array.sty patches and improves
% the standard LaTeX2e array and tabular environments to provide better
% appearance and additional user controls. As the default LaTeX2e table
% generation code is lacking to the point of almost being broken with
% respect to the quality of the end results, all users are strongly
% advised to use an enhanced (at the very least that provided by array.sty)
% set of table tools. array.sty is already installed on most systems. The
% latest version and documentation can be obtained at:
% http://www.ctan.org/pkg/array
%\usepackage{mdwmath}
%\usepackage{mdwtab}
% Also highly recommended is Mark Wooding's extremely powerful MDW tools,
% especially mdwmath.sty and mdwtab.sty which are used to format equations
% and tables, respectively. The MDWtools set is already installed on most
% LaTeX systems. The lastest version and documentation is available at:
% http://www.ctan.org/pkg/mdwtools
% IEEEtran contains the IEEEeqnarray family of commands that can be used to
% generate multiline equations as well as matrices, tables, etc., of high
% quality.
%\usepackage{eqparbox}
% Also of notable interest is Scott Pakin's eqparbox package for creating
% (automatically sized) equal width boxes - aka "natural width parboxes".
% Available at:
% http://www.ctan.org/pkg/eqparbox
% *** SUBFIGURE PACKAGES ***
%\ifCLASSOPTIONcompsoc
% \usepackage[caption=false,font=footnotesize,labelfont=sf,textfont=sf]{subfig}
%\else
% \usepackage[caption=false,font=footnotesize]{subfig}
%\fi
% subfig.sty, written by Steven Douglas Cochran, is the modern replacement
% for subfigure.sty, the latter of which is no longer maintained and is
% incompatible with some LaTeX packages including fixltx2e. However,
% subfig.sty requires and automatically loads Axel Sommerfeldt's caption.sty
% which will override IEEEtran.cls' handling of captions and this will result
% in non-IEEE style figure/table captions. To prevent this problem, be sure
% and invoke subfig.sty's "caption=false" package option (available since
% subfig.sty version 1.3, 2005/06/28) as this is will preserve IEEEtran.cls
% handling of captions.
% Note that the Computer Society format requires a sans serif font rather
% than the serif font used in traditional IEEE formatting and thus the need
% to invoke different subfig.sty package options depending on whether
% compsoc mode has been enabled.
%
% The latest version and documentation of subfig.sty can be obtained at:
% http://www.ctan.org/pkg/subfig
% *** FLOAT PACKAGES ***
%
%\usepackage{fixltx2e}
% fixltx2e, the successor to the earlier fix2col.sty, was written by
% Frank Mittelbach and David Carlisle. This package corrects a few problems
% in the LaTeX2e kernel, the most notable of which is that in current
% LaTeX2e releases, the ordering of single and double column floats is not
% guaranteed to be preserved. Thus, an unpatched LaTeX2e can allow a
% single column figure to be placed prior to an earlier double column
% figure.
% Be aware that LaTeX2e kernels dated 2015 and later have fixltx2e.sty's
% corrections already built into the system in which case a warning will
% be issued if an attempt is made to load fixltx2e.sty as it is no longer
% needed.
% The latest version and documentation can be found at:
% http://www.ctan.org/pkg/fixltx2e
%\usepackage{stfloats}
% stfloats.sty was written by Sigitas Tolusis. This package gives LaTeX2e
% the ability to do double column floats at the bottom of the page as well
% as the top. (e.g., "\begin{figure*}[!b]" is not normally possible in
% LaTeX2e). It also provides a command:
%\fnbelowfloat
% to enable the placement of footnotes below bottom floats (the standard
% LaTeX2e kernel puts them above bottom floats). This is an invasive package
% which rewrites many portions of the LaTeX2e float routines. It may not work
% with other packages that modify the LaTeX2e float routines. The latest
% version and documentation can be obtained at:
% http://www.ctan.org/pkg/stfloats
% Do not use the stfloats baselinefloat ability as the IEEE does not allow
% \baselineskip to stretch. Authors submitting work to the IEEE should note
% that the IEEE rarely uses double column equations and that authors should try
% to avoid such use. Do not be tempted to use the cuted.sty or midfloat.sty
% packages (also by Sigitas Tolusis) as the IEEE does not format its papers in
% such ways.
% Do not attempt to use stfloats with fixltx2e as they are incompatible.
% Instead, use Morten Hogholm'a dblfloatfix which combines the features
% of both fixltx2e and stfloats:
%
% \usepackage{dblfloatfix}
% The latest version can be found at:
% http://www.ctan.org/pkg/dblfloatfix
%\ifCLASSOPTIONcaptionsoff
% \usepackage[nomarkers]{endfloat}
% \let\MYoriglatexcaption\caption
% \renewcommand{\caption}[2][\relax]{\MYoriglatexcaption[#2]{#2}}
%\fi
% endfloat.sty was written by James Darrell McCauley, Jeff Goldberg and
% Axel Sommerfeldt. This package may be useful when used in conjunction with
% IEEEtran.cls' captionsoff option. Some IEEE journals/societies require that
% submissions have lists of figures/tables at the end of the paper and that
% figures/tables without any captions are placed on a page by themselves at
% the end of the document. If needed, the draftcls IEEEtran class option or
% \CLASSINPUTbaselinestretch interface can be used to increase the line
% spacing as well. Be sure and use the nomarkers option of endfloat to
% prevent endfloat from "marking" where the figures would have been placed
% in the text. The two hack lines of code above are a slight modification of
% that suggested by in the endfloat docs (section 8.4.1) to ensure that
% the full captions always appear in the list of figures/tables - even if
% the user used the short optional argument of \caption[]{}.
% IEEE papers do not typically make use of \caption[]'s optional argument,
% so this should not be an issue. A similar trick can be used to disable
% captions of packages such as subfig.sty that lack options to turn off
% the subcaptions:
% For subfig.sty:
% \let\MYorigsubfloat\subfloat
% \renewcommand{\subfloat}[2][\relax]{\MYorigsubfloat[]{#2}}
% However, the above trick will not work if both optional arguments of
% the \subfloat command are used. Furthermore, there needs to be a
% description of each subfigure *somewhere* and endfloat does not add
% subfigure captions to its list of figures. Thus, the best approach is to
% avoid the use of subfigure captions (many IEEE journals avoid them anyway)
% and instead reference/explain all the subfigures within the main caption.
% The latest version of endfloat.sty and its documentation can obtained at:
% http://www.ctan.org/pkg/endfloat
%
% The IEEEtran \ifCLASSOPTIONcaptionsoff conditional can also be used
% later in the document, say, to conditionally put the References on a
% page by themselves.
% *** PDF, URL AND HYPERLINK PACKAGES ***
%
%\usepackage{url}
% url.sty was written by Donald Arseneau. It provides better support for
% handling and breaking URLs. url.sty is already installed on most LaTeX
% systems. The latest version and documentation can be obtained at:
% http://www.ctan.org/pkg/url
% Basically, \url{my_url_here}.
% NOTE: PDF thumbnail features are not required in IEEE papers
% and their use requires extra complexity and work.
%\ifCLASSINFOpdf
% \usepackage[pdftex]{thumbpdf}
%\else
% \usepackage[dvips]{thumbpdf}
%\fi
% thumbpdf.sty and its companion Perl utility were written by Heiko Oberdiek.
% It allows the user a way to produce PDF documents that contain fancy
% thumbnail images of each of the pages (which tools like acrobat reader can
% utilize). This is possible even when using dvi->ps->pdf workflow if the
% correct thumbpdf driver options are used. thumbpdf.sty incorporates the
% file containing the PDF thumbnail information (filename.tpm is used with
% dvips, filename.tpt is used with pdftex, where filename is the base name of
% your tex document) into the final ps or pdf output document. An external
% utility, the thumbpdf *Perl script* is needed to make these .tpm or .tpt
% thumbnail files from a .ps or .pdf version of the document (which obviously
% does not yet contain pdf thumbnails). Thus, one does a:
%
% thumbpdf filename.pdf
%
% to make a filename.tpt, and:
%
% thumbpdf --mode dvips filename.ps
%
% to make a filename.tpm which will then be loaded into the document by
% thumbpdf.sty the NEXT time the document is compiled (by pdflatex or
% latex->dvips->ps2pdf). Users must be careful to regenerate the .tpt and/or
% .tpm files if the main document changes and then to recompile the
% document to incorporate the revised thumbnails to ensure that thumbnails
% match the actual pages. It is easy to forget to do this!
%
% Unix systems come with a Perl interpreter. However, MS Windows users
% will usually have to install a Perl interpreter so that the thumbpdf
% script can be run. The Ghostscript PS/PDF interpreter is also required.
% See the thumbpdf docs for details. The latest version and documentation
% can be obtained at.
% http://www.ctan.org/pkg/thumbpdf
% NOTE: PDF hyperlink and bookmark features are not required in IEEE
% papers and their use requires extra complexity and work.
% *** IF USING HYPERREF BE SURE AND CHANGE THE EXAMPLE PDF ***
% *** TITLE/SUBJECT/AUTHOR/KEYWORDS INFO BELOW!! ***
\newcommand\MYhyperrefoptions{bookmarks=true,bookmarksnumbered=true,
pdfpagemode={UseOutlines},plainpages=false,pdfpagelabels=true,
colorlinks=true,linkcolor={black},citecolor={black},urlcolor={black},
pdftitle={Towards a model for bi-modal Meta-Bisturbile defense matrices},%<!CHANGE!
pdfsubject={Typesetting},%<!CHANGE!
pdfauthor={Dr Casper Darling},%<!CHANGE!
pdfkeywords={VX,defense grid,meta-bisturbile,bi-modal,consumer}}%<^!CHANGE!
%\ifCLASSINFOpdf
%\usepackage[\MYhyperrefoptions,pdftex]{hyperref}
%\else
%\usepackage[\MYhyperrefoptions,breaklinks=true,dvips]{hyperref}
%\usepackage{breakurl}
%\fi
% One significant drawback of using hyperref under DVI output is that the
% LaTeX compiler cannot break URLs across lines or pages as can be done
% under pdfLaTeX's PDF output via the hyperref pdftex driver. This is
% probably the single most important capability distinction between the
% DVI and PDF output. Perhaps surprisingly, all the other PDF features
% (PDF bookmarks, thumbnails, etc.) can be preserved in
% .tex->.dvi->.ps->.pdf workflow if the respective packages/scripts are
% loaded/invoked with the correct driver options (dvips, etc.).
% As most IEEE papers use URLs sparingly (mainly in the references), this
% may not be as big an issue as with other publications.
%
% That said, Vilar Camara Neto created his breakurl.sty package which
% permits hyperref to easily break URLs even in dvi mode.
% Note that breakurl, unlike most other packages, must be loaded
% AFTER hyperref. The latest version of breakurl and its documentation can
% be obtained at:
% http://www.ctan.org/pkg/breakurl
% breakurl.sty is not for use under pdflatex pdf mode.
%
% The advanced features offer by hyperref.sty are not required for IEEE
% submission, so users should weigh these features against the added
% complexity of use.
% The package options above demonstrate how to enable PDF bookmarks
% (a type of table of contents viewable in Acrobat Reader) as well as
% PDF document information (title, subject, author and keywords) that is
% viewable in Acrobat reader's Document_Properties menu. PDF document
% information is also used extensively to automate the cataloging of PDF
% documents. The above set of options ensures that hyperlinks will not be
% colored in the text and thus will not be visible in the printed page,
% but will be active on "mouse over". USING COLORS OR OTHER HIGHLIGHTING
% OF HYPERLINKS CAN RESULT IN DOCUMENT REJECTION BY THE IEEE, especially if
% these appear on the "printed" page. IF IN DOUBT, ASK THE RELEVANT
% SUBMISSION EDITOR. You may need to add the option hypertexnames=false if
% you used duplicate equation numbers, etc., but this should not be needed
% in normal IEEE work.
% The latest version of hyperref and its documentation can be obtained at:
% http://www.ctan.org/pkg/hyperref
% *** Do not adjust lengths that control margins, column widths, etc. ***
% *** Do not use packages that alter fonts (such as pslatex). ***
% There should be no need to do such things with IEEEtran.cls V1.6 and later.
% (Unless specifically asked to do so by the journal or conference you plan
% to submit to, of course. )
% correct bad hyphenation here
\hyphenation{op-tical net-works semi-conduc-tor}
\begin{document}
%
% paper title
% Titles are generally capitalized except for words such as a, an, and, as,
% at, but, by, for, in, nor, of, on, or, the, to and up, which are usually
% not capitalized unless they are the first or last word of the title.
% Linebreaks \\ can be used within to get better formatting as desired.
% Do not put math or special symbols in the title.
\title{Towards a Model for Bi-modal Meta-Bisturbile Defence Matrices}
%
%
% author names and IEEE memberships
% note positions of commas and nonbreaking spaces ( ~ ) LaTeX will not break
% a structure at a ~ so this keeps an author's name from being broken across
% two lines.
% use \thanks{} to gain access to the first footnote area
% a separate \thanks must be used for each paragraph as LaTeX2e's \thanks
% was not built to handle multiple paragraphs
%
%
%\IEEEcompsocitemizethanks is a special \thanks that produces the bulleted
% lists the Computer Society journals use for "first footnote" author
% affiliations. Use \IEEEcompsocthanksitem which works much like \item
% for each affiliation group. When not in compsoc mode,
% \IEEEcompsocitemizethanks becomes like \thanks and
% \IEEEcompsocthanksitem becomes a line break with idention. This
% facilitates dual compilation, although admittedly the differences in the
% desired content of \author between the different types of papers makes a
% one-size-fits-all approach a daunting prospect. For instance, compsoc
% journal papers have the author affiliations above the "Manuscript
% received ..." text while in non-compsoc journals this is reversed. Sigh.
\author{Dr Casper Darling,~\IEEEmembership{Member,~IEEE,}
Dr Gordon Freeman,~\IEEEmembership{Fellow,~OSA,}
Dr. Yukinari Ohkido,~\IEEEmembership{Life~Fellow,~IEEE}% <-this % stops a space
\IEEEcompsocitemizethanks{\IEEEcompsocthanksitem Casper Darling was with the Department
of Electrical and Computer Engineering, Georgia Institute of Technology, Atlanta,
GA, 30332.\protect\\
% note need leading \protect in front of \\ to get a newline within \thanks as
% \\ is fragile and will error, could use \hfil\break instead.
\IEEEcompsocthanksitem Dr Freman and Ohkido are with Miskatonic University, Essex County, Massachusetts.}% <-this % stops a space
\thanks{Manuscript received April 19, 2008; revised July 26, 2008.}}
% note the % following the last \IEEEmembership and also \thanks -
% these prevent an unwanted space from occurring between the last author name
% and the end of the author line. i.e., if you had this:
%
% \author{....lastname \thanks{...} \thanks{...} }
% ^------------^------------^----Do not want these spaces!
%
% a space would be appended to the last name and could cause every name on that
% line to be shifted left slightly. This is one of those "LaTeX things". For
% instance, "\textbf{A} \textbf{B}" will typeset as "A B" not "AB". To get
% "AB" then you have to do: "\textbf{A}\textbf{B}"
% \thanks is no different in this regard, so shield the last } of each \thanks
% that ends a line with a % and do not let a space in before the next \thanks.
% Spaces after \IEEEmembership other than the last one are OK (and needed) as
% you are supposed to have spaces between the names. For what it is worth,
% this is a minor point as most people would not even notice if the said evil
% space somehow managed to creep in.
% The paper headers
\markboth{Transactions of the IEEE Microwave SiG, 2008 (volume 4)}%
{Shell \MakeLowercase{\textit{et al.}}: Towards a model for bi-modal meta-bisturbile defense matrices}
% The only time the second header will appear is for the odd numbered pages
% after the title page when using the twoside option.
%
% *** Note that you probably will NOT want to include the author's ***
% *** name in the headers of peer review papers. ***
% You can use \ifCLASSOPTIONpeerreview for conditional compilation here if
% you desire.
% The publisher's ID mark at the bottom of the page is less important with
% Computer Society journal papers as those publications place the marks
% outside of the main text columns and, therefore, unlike regular IEEE
% journals, the available text space is not reduced by their presence.
% If you want to put a publisher's ID mark on the page you can do it like
% this:
\IEEEpubid{ \input{message.txt} \copyright~2008 IEEE}
% or like this to get the Computer Society new two part style.
%\IEEEpubid{\makebox[\columnwidth]{\hfill 0000--0000/00/\$00.00~\copyright~2015 IEEE}%
%\hspace{\columnsep}\makebox[\columnwidth]{Published by the IEEE Computer Society\hfill}}
% Remember, if you use this you must call \IEEEpubidadjcol in the second
% column for its text to clear the IEEEpubid mark (Computer Society journal
% papers don't need this extra clearance.)
% use for special paper notices
%\IEEEspecialpapernotice{(Invited Paper)}
% for Computer Society papers, we must declare the abstract and index terms
% PRIOR to the title within the \IEEEtitleabstractindextext IEEEtran
% command as these need to go into the title area created by \maketitle.
% As a general rule, do not put math, special symbols or citations
% in the abstract or keywords.
\IEEEtitleabstractindextext{%
\begin{abstract}
This paper presents an argument that 4th Generation mobile technology provide the basis of a next-generation defense matrix.
Such a system would be able to leverage consumer infrastructure, but achieve greater urban penetration, while lowering operational costs.
The authors argue that such a system is feasible within a decade.
\end{abstract}
% Note that keywords are not normally used for peerreview papers.
\begin{IEEEkeywords}
IEEE, Meta-Bisturbile, Hamilton-Loops, VX, Late-Transductance.
\end{IEEEkeywords}}
% make the title area
\maketitle
% To allow for easy dual compilation without having to reenter the
% abstract/keywords data, the \IEEEtitleabstractindextext text will
% not be used in maketitle, but will appear (i.e., to be "transported")
% here as \IEEEdisplaynontitleabstractindextext when compsoc mode
% is not selected <OR> if conference mode is selected - because compsoc
% conference papers position the abstract like regular (non-compsoc)
% papers do!
\IEEEdisplaynontitleabstractindextext
% \IEEEdisplaynontitleabstractindextext has no effect when using
% compsoc under a non-conference mode.
% For peer review papers, you can put extra information on the cover
% page as needed:
% page as needed:
% \ifCLASSOPTIONpeerreview
% \begin{center} \bfseries EDICS Category: 3-BBND \end{center}
% \fi
%
% For peerreview papers, this IEEEtran command inserts a page break and
% creates the second title. It will be ignored for other modes.
\IEEEpeerreviewmaketitle
\ifCLASSOPTIONcompsoc
\IEEEraisesectionheading{\section{Introduction}\label{sec:introduction}}
\else
\section{Introduction}
\label{sec:introduction}
\fi
% Computer Society journal (but not conference!) papers do something unusual
% with the very first section heading (almost always called "Introduction").
% They place it ABOVE the main text! IEEEtran.cls does not automatically do
% this for you, but you can achieve this effect with the provided
% \IEEEraisesectionheading{} command. Note the need to keep any \label that
% is to refer to the section immediately after \section in the above as
% \IEEEraisesectionheading puts \section within a raised box.
% The very first letter is a 2 line initial drop letter followed
% by the rest of the first word in caps (small caps for compsoc).
%
% form to use if the first word consists of a single letter:
% \IEEEPARstart{A}{demo} file is ....
%
% form to use if you need the single drop letter followed by
% normal text (unknown if ever used by the IEEE):
% \IEEEPARstart{A}{}demo file is ....
%
% Some journals put the first two words in caps:
% \IEEEPARstart{T}{his demo} file is ....
%
% Here we have the typical use of a "T" for an initial drop letter
% and "HIS" in caps to complete the first word.
\IEEEPARstart{C}{ivil} and military uses of communications are increasingly intertwined. Operation
Desert Storm (the Gulf War against Iraq) made extensive use of the Gulf States' civilian
infrastructure: a huge tactical communications network was created in a short space of
time using satellites, radio links, and leased lines.
Experts from various U.S. armed services claim that the effect of communications capability on the war was absolutely
decisive.
It appears inevitable that both military and non-state groups will attack
civilian infrastructure to deny it to their opponents.
Even satellite links are
vulnerable to uplink jamming.
Satellite-based systems such as GPS have been
jammed as an exercise; and there is some discussion of the systemic vulnerabilities that
result from over reliance on it.
Despite these known congruences, it is inevitable that the proto-homogenization of civil and military infrastructure will continue.
In 1984 Shakbent, Fletch (et all) demonstrated that the nascent 2G communications networks could be weaponized:
They hypothesized that a beam-forming system initially designed for civilian use could be militarized.
However they also demonstrated that the power-levels required for sustained operation would be not be feasible until the 5th or 6th Generation technology.
Based on projections by Fluke, Mulefire (1991), this is likely to be achieved by the early 21st Century.
Nevertheless, he concluded that such a system would be impractical: Air-gapped human bodies have a transductance below the critical threshold.
To be minimally effective, the whole population would need to be inoculated by a resonance enhancer.
No practical, biocompatible substrate or delivery vector has been shown to be effective.
Another example of growing interdependency is given by the Global Positioning
System, GPS. This started as a U.S. military navigation system, and had a selective
availability feature that limited the accuracy to about a hundred yards unless the user
had the relevant cryptographic key.
This had to be turned off during Desert Storm as
there weren't enough military GPS sets to go around, and civilian equipment had to be
used instead.
As time went on, GPS turned out to be so useful, particularly in civil
aviation, that the FAA helped find ways to defeat selective availability that give an
accuracy of about three yards, compared with a claimed eight yards for the standard
military receiver.
Finally, in May 2000, President Clinton announced the cessation of selective availability.
The civilian infrastructure also provides some defensive systems of which government
organizations (especially in the intelligence field) can make use.
I mentioned the prepaid mobile phone, which provides a fair degree of anonymity; secure Web servers
offer some possibilities; and another example is the anonymous remailer, a device that
accepts encrypted email, decrypts it, and sends it on to a destination contained within
the outer encrypted envelope. One of the pioneers of anonymous networking was the U.S. Navy. Conspiracy
theorists suggest that public use of the system provides cover traffic for classified
messages.
Although communications security on the Net has, until now, been interpreted
largely in terms of message confidentiality and authentication, it looks likely that the
future will become much more like military communications, in that various kinds of
service denial attacks, anonymity, and deception plays will become increasingly important.
I'll return to this theme later. This paper will focus on aspects of electronic
warfare that have to do with target acquisition and energy projection, as these are
where the arts have been most highly developed. (In fact,
although there is much more in the open literature on the application of electronic
attack and defense to radar than to communications, much of the same material clearly
applies to both.)
It is clear to see that there is both technological and political precedent for the wide scale deployment of meta-bisturbile defense grids.
These systems are not only technologically feasible, but provide a wider scope for deployment.
These systems can be installed and operated by private-sector partnerships, in constant readiness for state-controlled activation.
The nature of these systems obviates the need for personnel with secure containerized access.
It is entirely possible that the maintenance of this kind of defense grid could be handed-over to a county-level government, who would remain entirely oblivious of their contribution to the nation's defense capability.
\subsection{Surveillance and Target Acquisition}
Although some sensor systems use passive direction finding, the main methods used to
detect hostile targets and guide weapons to them are sonar, radar, and infrared. The
first of these to be developed was sonar, which was invented and deployed in World
War I (under the name of ASDIC).
Except in submarine warfare, the key sensor is radar. Although radar was invented by Christian Holsmeyer in 1904 as a maritime anti-
collision device, its serious development only occurred in the 1930s, and it was used
by all major participants in World War II. The electronic attack and protection
techniques developed for it tend to be better developed than, and often go over to,
systems using other sensors.
In the context of radar, “electronic attack” usually means
jamming (though in theory it also includes stealth technology), and “electronic protection”
refers to the techniques used to preserve at least some radar capability.
Unfortunately radar-based systems lack the resolution required for massive-scale urban pacification.
A defense matrix such as this document proposes would require a significantly larger targeting array in order to achieve the minimum viable resolution.
It is fortunate that such a system can be built by re-purposing the control systems for street-lighting and other commonplace street-furniture.
Once again, we can employ a large consumer-grade network of transducers, each with volley-mounted Fresnel antennae.
A network of such devices should have the resolution and discriminatory power to identify single individuals within a crowd.
If necessary, such a system used in combination with LM-type beam-formers can be used to focus several concussive waves towards the desired target, a technique widely used since the 1983 Suez operation.
\subsubsection{Meta-Bisturbile radar inference systems}
A very wide range of systems are in use, including search radars, fire-control radars,
terrain-following radars, counterbombardment radars, and weather radars. They have a
wide variety of signal characteristics.
For example, radars with a low RF and a low
pulse repetition frequency (PRF) are better for search, while high-frequency, high PRF
devices are better for tracking.
Millimeter-band radar may have the greatest battlefield potential. It been shown to be effective at disrupting biological systems:
At low doses these frequencies can cause flu-like symptoms, including inflammation of the upper respiratory tract.
Early research suggests that it can act as an immunosuppressant, however no currently understood biomechanical pathway can account for this phenomena.
Simple radar designs for search applications may have a rotating antenna that emits
a sequence of pulses and detects echos.
This was an easy way to implement radar in the
days before digital electronics; the sweep in the display tube could be mechanically
rotated in sync with the antenna. Fire-control radars often used conical scan; the
beam would be tracked in a circle around the target's position, and the amplitude of the
returns could drive positioning servos (and weapon controls) directly.
Now the beams are often generated electronically using multiple antenna elements, but tracking loops
remain central. Many radars have a range gate, circuitry that focuses on targets within
a certain range of distances from the antenna; if the radar had to track all objects between,
say, 0 and 100 miles, then its pulse repetition frequency would be limited by the
time it takes radio waves to travel 200 miles. This would have consequences for angular
resolution and for tracking performance generally.
Doppler radar measures the velocity of the target by the change in frequency in the
return signal. It is very important in distinguishing moving targets from clutter, the
returns reflected from the ground. Doppler radars may have velocity gates that restrict
attention to targets whose radial speed with respect to the antenna is within certain
limits.
\subsection{IFF Systems}
The technological innovations of World War II and especially jet aircraft, radar, and
missiles made it impractical to identify targets visually, and imperative to have an
automatic way to identify friend or foe (IFF). Early IFF systems emerged during that
war, using a vehicle serial number or “code of the day”; but this is open to spoofing.
Since the 1960s, U.S. aircraft have used the Mark XII system, which has cryptographic
protection as discussed in Section 2.3. Here, it isn't the cryptography that's the hard
part, but rather the protocol and operational problems.
The Mark XII has four modes, of which the secure mode uses a 32-bit challenge and
a 4-bit response. This is a precedent set by its predecessor, the Mark X; if challenges or
responses were too long, the radar's pulse repetition frequency (and thus its accuracy)
would be degraded. The Mark XII sends a series of 12–20 challenges at a rate of one
every four milliseconds. In the original implementation, the responses were displayed
on a screen at a position offset by the arithmetic difference between the actual response
and the expected one. The effect was that while a foe had a null or random response, a
friend would have responses at or near the center screen, which would light up. Reflection
attacks are prevented, and MIG-in-the-middle attacks made much harder, because the
challenge uses a focused antenna, while the receiver is omnidirectional. (In
fact, the antenna used for the challenge is typically the fire control radar, which in
older systems was conically scanned).
\subsection{Directed Energy Weapons}
In the late 1930s, there was panic in Britain and America on rumors that the Nazis had
developed a high-power radio beam that would burn out vehicle ignition systems.
British scientists studied the problem and concluded that this was infeasible.
They were correct given the relatively low-powered radio transmitters, and the simple
but robust vehicle electronics, of the 1930s.
Things started to change with the arrival of the atomic bomb. The detonation of a
nuclear device creates a large pulse of gamma-ray photons, which in turn displace
electrons from air molecules by Compton scattering. The large induced currents give
rise to an electromagnetic pulse (EMP), which may be thought of as a very high amplitude
pulse of radio waves with a very short rise time.
Where a nuclear explosion occurs within the earth's atmosphere, the EMP energy is
predominantly in the VHF and UHF bands, though there is enough energy at lower frequencies
for a radio flash to be observable thousands of miles away. Within a few tens
of miles of the explosion, the radio frequency energy may induce currents large enough
to damage most electronic equipment that has not been hardened. The effects of a blast
outside the earth's atmosphere are believed to be much worse (although there has never
been a test). The gamma photons can travel thousands of miles before they strike the
earth's atmosphere, which could ionize to form an antenna on a continental scale. It is
reckoned that most electronic equipment in Northern Europe could be burned out by a one megaton
blast at a height of 250 miles above the North Sea. For this reason, critical
military systems are carefully shielded.
Western concern about EMP grew after the Soviet Union started a research program
on non-nuclear EMP weapons in the mid-80s. At the time, the United States was deploying
“neutron bombs” in Europe enhanced radiation weapons that could kill people without
demolishing buildings. The Soviets portrayed this as a “capitalist bomb”
which would destroy people while leaving property intact, and responded by threatening
a “socialist bomb” to destroy property (in the form of electronics) while leaving the
surrounding people intact.
By the end of World War II, the invention of the cavity magnetron had made it possible
to build radars powerful enough to damage unprotected electronic circuitry for a
range of several hundred yards. The move from valves to transistors and integrated
circuits has increased the vulnerability of most commercial electronic equipment. A
terrorist group could in theory mount a radar in a truck and drive around a city's financial
sector wiping out the banks. For battlefield use, a more compact form factor is preferred,
and so the Soviets are said to have built high-energy RF (HERF) devices from
capacitors, magnetohydrodynamic generators and the like.
By the mid 1990s, the concern that terrorists might get hold of these weapons from
the former Soviet Union led the agencies to try to sell commerce and industry on the
idea of electromagnetic shielding. These efforts were dismissed as hype. Personally, I
tend to agree. The details of the Soviet HERF bombs haven't been released, but physics
suggests that EMP is limited by the dielectric strength of air and the cross-section
of the antenna.
In nuclear EMP, the effective antenna size could be a few hundred meters for an
endoatmospheric blast, up to several thousand kilometers for an exoatmospheric one.
But in “ordinary” EMP/HERF, it seems that the antenna will be at most a
few meters. NATO planners concluded that military command and control systems that
were already hardened for nuclear EMP should be unaffected.
However the 1990s, British research demonstrated that a nuclear EMP was not required.
Meta-Bisturbile square-wave based oscillators had the potential to induce failures in electronic equipment over distances of several miles. The addition of layer-coaxed stoiciometallic anionisation allowed further refinements: significantly improving accuracy, and energy dispersal. Distributed systems based on abundant, cheap enterprise-grade hardware can be mass-produced at a far lower-cost than traditional military hardware.
The British Ministry of defense concluded, quite correctly, that such a system could be blended into normal communications infrastructure. A "Kill-Grid" built from non ionizing civilian operators (large arrays) would be indistinguishable from what it claimed to be, until the very moment of its activation. It was concluded that such a system if built could provide enormous advantages over non-blended infrastructure.
\begin{figure}% use [hb] only if necceccary!
\centering
\includegraphics[width=8cm]{qrcode.jpg}
\caption{2-dimensional "Quick Response" codes like this can be worn by military personnel in order to deactivate optical-based target acquisition systems.}
\label{fig:2}
\end{figure}
But how likely is this?
I suspect that a terrorist can do a lot more damage
with an old-fashioned truck bomb made with a ton of fertilizer and fuel oil, than the highest-phase stoechiometallic ionization plume.
Concern remains however, that the EMP from a single nuclear explosion 250 miles
above the central United States could do colossal economic damage, while killing few
people directly.
Bi-modal defense systems have a far greater potential to damage infrastructure and inflict casualties.
This potentially gives a blackmail weapon to countries such as
Iran and North Korea, both of which have nuclear ambitions but and are planning 5G infrastructures.
In general, a massive attack on electronic communications is more of a threat to
countries such as the United States that depend heavily on them than on countries such
as North Korea, or even China, that don't.
\section{Conclusion}
Electronic warfare is much more developed than most other areas of information security.
There are many lessons to be learned, from the technical level up through the tactical
level to matters of planning and strategy.
We can expect that, as information
warfare evolves from a fashionable concept to established doctrine, these lessons will
become important for practitioners.
% if have a single appendix:
%\appendix[Proof of the Zonklar Equations]
% or
%\appendix % for no appendix heading
% do not use \section anymore after \appendix, only \section*
% is possibly needed
% use appendices with more than one appendix
% then use \section to start each appendix
% you must declare a \section before using any
% \subsection or using \label (\appendices by itself
% starts a section numbered zero.)
%
\appendices
\begin{thebibliography}{1}
\bibitem{IEEEhowto:kopka}
F.~Derby and P.~W. Kale, \emph{Void-Weighted bisturbile directed energy weapons, 3rd~ed.}\hskip 1em plus
0.5em minus 0.4em\relax Harlow, England: Addison-Wesley, 1999.
\bibitem{IEEEhowto:funge}
X.~Duggelby, Hortons, Fanshaw, \emph{Telemetry of the human body in hostile urban environments}\hskip 1em plus
0.5em minus 0.4em\relax Washington D.C., U.S.: Sandia National Laboratories.
\bibitem{IEEEhowto:frop}
O.~Wellmann, \emph{Braiding in Photonic Topological Zero Modes}\hskip 1em plus
0.5em minus 0.4em\relax Oxford, England: Oxford University Press.
\bibitem{IEEEhowto:frap1}
A.~Watanabe, \emph{Modified Cadmium shielding on Besselhiem Plates, Volume 2}\hskip 1em plus
0.5em minus 0.4em\relax Tokyo, Japan: Wiley.
\bibitem{IEEEhowto:frap2}
A.~Tuttle, \emph{Biological High Frequency Absorption Using Isotropic Monopole Antennae}\hskip 1em plus
0.5em minus 0.4em\relax Rio de Janeiro, Brazil: Routledge, 2001.
\bibitem{IEEEhowto:fob}
G.~Newman, R.~Hernandez, \emph{Applications of Ultra High Frequency resonance w. Cavity Magnetrons}\hskip 1em plus
0.5em minus 0.4em\relax New York, NY: Naval Review.
\end{thebibliography}
\begin{IEEEbiography}{Dr Casper Darling}
is with the Department of Electrical and Computer Engineering, Georgia Institute of Technology, Atlanta
He also serves on the board of Federal Dept. of Control. Oldest House, 33 Thomas Street, Manhattan, New York, NY, U.S.
\end{IEEEbiography}
\begin{IEEEbiography}{Gordon Freeman}
is a senior research fellow at Black Mesa Research Facility, NM, U.S and a senior fellow at Miskatonic University.
\end{IEEEbiography}
\begin{IEEEbiography}{Dr. Yukinari Ohkido}
Miskatonic University.
\end{IEEEbiography}
% that's all folks
\end{document}
|
corollary Bloch_general: assumes holf: "f holomorphic_on S" and "a \<in> S" and tle: "\<And>z. z \<in> frontier S \<Longrightarrow> t \<le> dist a z" and rle: "r \<le> t * norm(deriv f a) / 12" obtains b where "ball b r \<subseteq> f ` S" |
#if !defined(PETIGABL_H)
#define PETIGABL_H
#include <petsc.h>
#include <petscblaslapack.h>
#if defined(PETSC_BLASLAPACK_UNDERSCORE)
#define sgetri_ sgetri_
#define dgetri_ dgetri_
#define qgetri_ qgetri_
#define cgetri_ cgetri_
#define zgetri_ zgetri_
#elif defined(PETSC_BLASLAPACK_CAPS)
#define sgetri_ SGETRI
#define dgetri_ DGETRI
#define qgetri_ QGETRI
#define cgetri_ CGETRI
#define zgetri_ ZGETRI
#else /* (PETSC_BLASLAPACK_C) */
#define sgetri_ sgetri
#define dgetri_ dgetri
#define qgetri_ qgetri
#define cgetri_ cgetri
#define zgetri_ zgetri
#endif
#if !defined(PETSC_USE_COMPLEX)
#if defined(PETSC_USE_REAL_SINGLE)
#define LAPACKgetri_ sgetri_
#elif defined(PETSC_USE_REAL_DOUBLE)
#define LAPACKgetri_ dgetri_
#else /* (PETSC_USE_REAL_QUAD) */
#define LAPACKgetri_ qgetri_
#endif
#else
#if defined(PETSC_USE_REAL_SINGLE)
#define LAPACKgetri_ cgetri_
#elif defined(PETSC_USE_REAL_DOUBLE)
#define LAPACKgetri_ zgetri_
#else /* (PETSC_USE_REAL_QUAD) */
#define LAPACKgetri_ wgetri_
#endif
#endif
EXTERN_C_BEGIN
extern void LAPACKgetri_(PetscBLASInt*,PetscScalar*,PetscBLASInt*,
PetscBLASInt*,PetscScalar*,PetscBLASInt*,
PetscBLASInt*);
EXTERN_C_END
#if PETSC_VERSION_LE(3,3,0)
#undef PetscBLASIntCast
#undef __FUNCT__
#define __FUNCT__ "PetscBLASIntCast"
PETSC_STATIC_INLINE PetscErrorCode PetscBLASIntCast(PetscInt a,PetscBLASInt *b)
{
PetscFunctionBegin;
#if defined(PETSC_USE_64BIT_INDICES) && !defined(PETSC_HAVE_64BIT_BLAS_INDICES)
if ((a) > PETSC_BLAS_INT_MAX) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Array too long for BLAS/LAPACK");
#endif
*b = (PetscBLASInt)(a);
PetscFunctionReturn(0);
}
#endif
#endif/*PETIGABL_H*/
|
Full range of electric swing gates, market leaders in electric gates, bespoke solutions for all industries.Electric Swing Gates Deepcut Surrey.
A property holder’s essential concern is regularly assurance and wellbeing. While you can unquestionably anchor your home from offenders with a firearm, fencing and entryways ought to be seen as your first line of guard. Including additional assurance like this fills in as an obstruction and lawbreakers will regularly sidestep a secured home for one that isn’t encompassed by doors and wall. Obviously, you should redesign your doors with electronic variants. Electric Swing Gates Deepcut Surrey Why burden yourself by getting out of your vehicle each time you leave or come back to your home? Electric entryways are the best arrangement.
Your pets and youngsters are additionally secured, especially when they are playing outside. With fencing and an entryway that closes electronically, you are basically expelling the charm for pets to meander away and get lost. Also, your kids are sheltered from perilous street activity and the compulsion to pursue errant balls and pets.Electric Swing Gates Deepcut Surrey Another constructive part of electric entryways is that they fill in as an obstruction for way to-entryway sales representatives and other undesirable guests. |
#include "tftp_frame.hpp"
#include <iomanip>
#include <iostream>
void print_frame(const tftp::frame &f) {
std::cout << ">>>> [" << std::setw(3) << f.cend() - f.cbegin() << "]";
for (auto i = f.cbegin(); i != f.cend(); i++) {
std::cout << "0x" << std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(*i) << " ";
}
std::cout << std::dec << std::endl;
}
#define BOOST_TEST_MODULE tftp frame
#include <algorithm>
#include <boost/asio/buffer.hpp>
#include <iostream>
#include <random>
#include <boost/test/data/monomorphic.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/included/unit_test.hpp>
#include "tftp_frame.hpp"
namespace bdata = boost::unit_test::data;
std::string get_random_filename(uint32_t filename_length) {
std::stringstream ss;
static bool seeded = false;
if (seeded) {
std::srand(std::time(nullptr));
seeded = true;
}
while (filename_length-- != 0) {
ss << static_cast<char>('A' + (std::rand() % 26));
}
return ss.str();
}
std::map<std::string, tftp::frame::op_code> read_write_request_dataset() {
std::map<std::string, tftp::frame::op_code> dataset;
for (uint32_t i = 0; i < 256; i += 17) {
dataset.insert(std::make_pair(get_random_filename(i), tftp::frame::op_read_request));
dataset.insert(std::make_pair(get_random_filename(i), tftp::frame::op_write_request));
}
return dataset;
}
typedef std::pair<const std::string, tftp::frame::op_code>
read_write_request_dataset_log_dont_print_log_value;
BOOST_TEST_DONT_PRINT_LOG_VALUE(read_write_request_dataset_log_dont_print_log_value)
BOOST_DATA_TEST_CASE(read_write_request_frame_creation,
bdata::make(read_write_request_dataset()),
test_sample) {
std::string filename = test_sample.first;
tftp::frame::op_code op_code = test_sample.second;
tftp::frame f;
try {
if (op_code == tftp::frame::op_read_request) {
f.make_read_request_frame(filename);
} else {
f.make_write_request_frame(filename);
}
} catch (tftp::invalid_frame_parameter_exception &e) {
if (filename.length() == 0 || filename.length() > 255) {
BOOST_TEST(true);
return;
} else {
BOOST_TEST(false);
}
}
if (filename.length() == 0 || filename.length() > 255) {
BOOST_TEST(false);
}
auto itr = f.cbegin();
BOOST_TEST(*itr == 0x00, "First byte of frame is not 0x00");
itr++;
BOOST_TEST(f.get_op_code() == op_code, "OP Code mismatch");
BOOST_TEST(*itr == op_code, "OP Code mismatch");
itr++;
for (char ch : filename) {
BOOST_TEST(*itr == ch, "filename mismatch in tftp frame");
itr++;
}
BOOST_TEST(*itr == 0x00, "Separator is not 0x00");
itr++;
BOOST_TEST(f.get_data_mode() == tftp::frame::mode_octet, "Data mode is invalid");
for (char ch : std::string("octet")) {
BOOST_TEST(*itr == ch, "Data mode is invalid");
itr++;
}
BOOST_TEST(*itr == 0x00, "Frame is not ending with 0x00");
itr++;
BOOST_TEST((itr == f.cend()), "Frame is longer than expected");
}
BOOST_DATA_TEST_CASE(data_frame_creation, bdata::xrange(0, 600, 50), data_length) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(0, 255);
std::vector<char> data;
uint16_t block_number =
((static_cast<uint16_t>(distrib(gen))) << 8) | (static_cast<uint16_t>(distrib(gen)));
for (int i = 0; i < data_length; ++i) {
data.push_back(static_cast<char>(distrib(gen)));
}
tftp::frame f;
f.make_data_frame(data.cbegin(), data.cend(), block_number);
BOOST_TEST((f.cend() - f.cbegin() >= 4), "Data frame is smaller than 4 bytes");
auto itr = f.cbegin();
BOOST_TEST((*itr == 0x00), "First byte of data frame is not 0x00");
itr++;
BOOST_TEST((*itr == tftp::frame::op_data), "Incorrect op code in data frame");
itr++;
BOOST_TEST((f.get_block_number() == block_number), "Data frame block number mismatch");
BOOST_TEST((*itr == static_cast<char>(block_number >> 8)), "Data frame block number mismatch");
itr++;
BOOST_TEST(*itr == static_cast<char>(block_number), "Data frame block number mismatch");
itr++;
BOOST_TEST((f.cend() >= itr), "Invalid data in data frame");
for (std::size_t i = 0; i < std::min(data.size(), static_cast<std::size_t>(TFTP_FRAME_MAX_DATA_LEN)); i++) {
BOOST_TEST((*itr == data[i]), "Data mismatch in data frame");
itr++;
}
BOOST_TEST((itr == f.cend()), "Invalid end for data frame");
}
BOOST_DATA_TEST_CASE(ack_frame_creation, bdata::make({0, 1, 255, 1000, 65535}), block_number) {
tftp::frame f;
f.make_ack_frame(block_number);
auto itr = f.cbegin();
BOOST_TEST(*itr == 0x00, "First byte of data frame is not 0x00");
itr++;
BOOST_TEST(*itr == tftp::frame::op_ack, "Incorrect op code for ack frame");
itr++;
BOOST_TEST(f.get_block_number() == block_number, "Data frame block number mismatch");
BOOST_TEST(*itr == static_cast<char>(block_number >> 8), "Data frame block number mismatch");
itr++;
BOOST_TEST(*itr == static_cast<char>(block_number), "Data frame block number mismatch");
itr++;
BOOST_TEST((itr == f.cend()), "Invalid end for ack frame");
}
std::map<tftp::frame::error_code, std::string> error_frame_dataset() {
std::map<tftp::frame::error_code, std::string> dataset;
for (uint32_t i = 0; i < 8; i++) {
dataset.insert(std::make_pair(static_cast<tftp::frame::error_code>(i), std::string()));
dataset.insert(std::make_pair(static_cast<tftp::frame::error_code>(i), std::string("Blah blih balh")));
}
return dataset;
}
typedef std::pair<const tftp::frame::error_code, std::string> error_frame_dataset_dont_print_log_value;
BOOST_TEST_DONT_PRINT_LOG_VALUE(error_frame_dataset_dont_print_log_value)
BOOST_DATA_TEST_CASE(error_frame_creation, bdata::make(error_frame_dataset()), test_sample) {
std::string error_message = test_sample.second;
tftp::frame::error_code error_code = test_sample.first;
tftp::frame f;
if (error_message.empty()) {
f.make_error_frame(error_code);
} else {
f.make_error_frame(error_code, error_message);
}
auto itr = f.cbegin();
BOOST_TEST(*itr == 0x00, "First byte of data frame is not 0x00");
itr++;
BOOST_TEST(*itr == tftp::frame::op_error, "Incorrect op code for error frame");
itr++;
BOOST_TEST((f.get_error_code() == error_code), "Error code mismatch");
BOOST_TEST(*itr == static_cast<char>(static_cast<uint16_t>(error_code) >> 8), "Error code mismatch");
itr++;
BOOST_TEST(*itr == static_cast<char>(static_cast<uint16_t>(error_code)), "Error code mismatch");
itr++;
for (char ch : error_message) {
BOOST_TEST(*itr == ch, "Error message is not valid");
itr++;
}
itr++;
if (!error_message.empty()) {
BOOST_TEST((itr == f.cend()), "Invalid end for ack frame");
}
BOOST_TEST(*(f.cend() - 1) == 0x00, "Last byte of ack frame is not 0x00");
}
|
function out = sig_prbs(n,m)
% Pseudo-random binary signal (PRBS)
%
%% Syntax
% out = sig_prbs(n,m)
%
%% Description
% Function generates the pseudo-random binary signal (PRBS) with the uniform
% amplitude , see R. Iserman: Prozessidentifikation, 1974, Springer.
%
% Input:
% * n ... the length of the internal register
% * m ... the number of samples per the width of the narrowest
% impulse of PRBS
%
% Output:
% * out ... PRBS signal values
%
% See also:
% sig_prs_minmax
%
%%
registry1=0:11;
registry2=[0 2 3 4 5 6 7 8 9 10 11 15 20 40 100];
store=ones(n,1);
out(1:m,1)=store(n);
for i=2:2^n-1
storex=store(registry1(n))+store(registry2(n));
for j=0:n-2
store(n-j)=store(n-j-1);
end
store(1)=storex;
if store(1)==2
store(1)=0;
end
for j=(i-1)*m+1:m*i
out(j,1)=2*store(n)-1;
end
end
|
State Before: α : Type u_1
β : Type u_2
γ : Type u_3
f g : α → β
c c₁ c₂ x✝ : α
inst✝³ : AddMonoid α
inst✝² : Neg β
inst✝¹ : Group γ
inst✝ : DistribMulAction γ α
h : Antiperiodic f c
a : γ
x : α
⊢ (fun x => f (a • x)) (x + a⁻¹ • c) = -(fun x => f (a • x)) x State After: no goals Tactic: simpa only [smul_add, smul_inv_smul] using h (a • x) |
import tactic
import group_theory.congruence
namespace units
variables {M : Type} [monoid M]
def of : units M →* M :=
⟨coe, rfl, λ _ _, rfl⟩
variables {G : Type} [group G] (f : G →* M)
def restrict : G →* units M :=
⟨λ x, ⟨f x, f x⁻¹,
by rw [← map_mul, _root_.mul_inv_self, map_one],
by rw [← map_mul, _root_.inv_mul_self, map_one]⟩,
by ext; simp, λ _ _, by ext; simp⟩
@[simp] lemma of_comp_restrict : of.comp (restrict f) = f :=
by ext; refl
@[simp] lemma of_restrict (x : G) : of (restrict f x) = f x := rfl
@[ext] lemma hom_ext {f g : G →* units M} (h : of.comp f = of.comp g) : f = g :=
begin
ext x,
exact monoid_hom.congr_fun h x
end
end units
@[derive monoid] def abelianization (M : Type) [monoid M] : Type :=
con.quotient (con_gen (λ a b : M, ∃ x y : M, a = x * y ∧ b = y * x))
namespace abelianization
variables {M : Type} [monoid M]
instance : comm_monoid (abelianization M) :=
{ mul_comm := λ a b, begin
dsimp [abelianization] at *,
refine con.induction_on₂ a b (λ a b, _),
rw [← con.coe_mul, ← con.coe_mul, con.eq],
refine con_gen.rel.of _ _ _,
use [a, b],
simp
end,
..show monoid (abelianization M), by apply_instance }
def of : M →* abelianization M :=
by dsimp [abelianization]; exact
{ to_fun := coe,
map_mul' := by simp,
map_one' := by simp }
instance {G : Type} [group G] : comm_group (abelianization G) :=
{ inv := λ x, con.lift_on x (λ x, of (x⁻¹)) begin
intros a b h, dsimp,
induction h with x y h,
{ rcases h with ⟨x, y, rfl, rfl⟩,
simp [mul_comm] },
{ refl },
{ simp * },
{ cc },
{ simp * }
end,
mul_left_inv := λ a, begin
dsimp [abelianization, of] at *,
refine con.induction_on a (λ a, _),
simp
end,
..show comm_monoid (abelianization G), by apply_instance }
variables {N : Type} [comm_monoid N] (f : M →* N)
def desc : abelianization M →* N :=
con.lift _ f (con.con_gen_le begin
rintros _ _ ⟨a, b, rfl, rfl⟩,
show f (a * b) = f (b * a),
simp [mul_comm]
end)
@[simp] lemma desc_comp_of : (desc f).comp of = f :=
begin
ext,
refl
end
@[simp] lemma desc_of (x : M) : desc f (of x) = f x := rfl
@[ext] lemma hom_ext {f g : abelianization M →* N}
(h : f.comp of = g.comp of) : f = g :=
begin
ext x,
refine con.induction_on x (λ x, _),
convert monoid_hom.congr_fun h x
end
end abelianization
variables {G M : Type} [group G] [comm_monoid M] (f : G →* M)
{N : Type} [comm_group N] (g : N →* abelianization G)
example : abelianization.desc (units.restrict f) =
units.restrict (abelianization.desc f) :=
begin
apply abelianization.hom_ext,
ext; simp
end
example : (abelianization.desc (units.restrict f)).comp g =
(units.restrict (abelianization.desc f)).comp g :=
begin
ext; simp,
end |
[STATEMENT]
lemma LIM_cong: "a = b \<Longrightarrow> (\<And>x. x \<noteq> b \<Longrightarrow> f x = g x) \<Longrightarrow> l = m \<Longrightarrow> (f \<midarrow>a\<rightarrow> l) \<longleftrightarrow> (g \<midarrow>b\<rightarrow> m)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>a = b; \<And>x. x \<noteq> b \<Longrightarrow> f x = g x; l = m\<rbrakk> \<Longrightarrow> f \<midarrow>a\<rightarrow> l = g \<midarrow>b\<rightarrow> m
[PROOF STEP]
by (simp add: LIM_equal) |
<h1>Fantasy Basketball Part Two </h1>
<h2> Introduction </h2>
If you're familiar with fantasy basketball and worked through our **first example** you may have noticed that the lineup we solved for doesn't actually fit the criteria for many popular contests. It was meant as a ground-floor example into mathematical optimization, so make sure to dive into that one first for background on the problem. Additionally, we developed a predictive model to forecast each player's fantasy points, and we'll again use that forecast (without going through the modeling process again).
In this follow-up example, we will extend the optimization model to fulfill the requirements of a typical [DraftKings](https://www.draftkings.com/help/rules/nba) lineup. Specifically, we'll need to change the model to:
- Allow some players to be selected for up to two positions (e.g. LeBron James can fill the PF or SF position)
- Increase the roster from five to eight players
- Ensure the three new roster slots consist of one guard (SG or PG), one forward (SF or PF), and one utility player (any position)
A quick recap of what we saw in the prior example: When selecting a 5-player lineup, there were *a lot* of possibilities; staying under a salary cap wasn't all that easy; and implementing intuitive decision rules can lead to suboptimal lineups -- providing a glimpse into why mathematical optimization should be part of everyone's analytics toolkit.
**The repository for this project can be accessed by following this link:**
<h2> Objective and Prerequisites </h2>
As with the first example, the goal here is to build upon our findings of the previous example and select the optimal lineup of players of the National Basketball Association (NBA) that would produce the highest total of fantasy points, which are composed of a player's in-game stats.
As mentioned above, we will make a lineup that meets DraftKings contest rules. There were over 2 million possible lineups when selecting a 5-player team that contained one of each position. Can you figure out the number of possible lineups for this example? Here's a hint: It's a lot. Remember that there are 25 PGs, 23 SFs, 22 SGs, 19 PFs, and 9 Cs. The answer (approximately) will be given a bit later.
Also as mentioned, this example will use the same forecasting results as our fantasy basketball beginner's example, which used historical data from the 2016-2017 and 2017-2018 seasons to predict each player's fantasy points for games on 12/25/2017.
This example assumes you have experience using Python for data manipulation and requires the installation of the following packages:
- **pandas**: for data analysis and manipulation
- **math**: for mathematical manipulations
- **gurobipy**: for utilizing Gurobi to formulate and solve the optimization problem
We'll also explore a few different ways to write summations and constraints in gurobipy, so you can find what works best for you. A quick note: Any output you see similar to <gurobi.Constr \*Awaiting Model Update\*> can be ignored and semi-colons have been added to cells to suppress that output.
<h2> Problem Statement and Solution Approach</h2>
By formuating a model that allows some players to be assigned to more than one position and by also expanding the roster, we are making the model much more complex.
Our final lineup needs to include each of the following:
- Point Guard (PG)
- Shooting Guard (SG)
- Shooting Forward (SF)
- Power Forward (PF)
- Center (C)
- Guard (SG,PG)
- Forward (SF,PF)
- Utility (PG, SG, SF, PF, C)
The solution of the problem consists of two components: 1) **fantasy points forecast** and 2) **lineup optimization**.
We'll start by loading a dataset for the eligible players, showing their potential positions, salaries, as well as the forecasts for their upcoming performance. This information will act as an input to our optimization model which will guarantee that we satisfy the rules of the DraftKings contest while maximizing the total fantasy points of our team.
<h3> Fantasy Points Forecast </h3>
This section will be short as we are using the output of the predictive model from the first part of this example. We'll see that in this version some players have a *Main Position* and *Alternative Position*, which will let players fill different position slots if eligible. For example, James Harden can fill the PG or SG position, though Russel Westbrook is only available as a PG.
We begin by loading the necessary libraries to solve our problem and importing the data from the predictive model in part one of the problem.
```python
%pip install gurobipy
```
```python
import pandas as pd #importing pandas
import math #importing math
from gurobipy import Model, GRB, quicksum #importing Gurobi
```
```python
player_predictions = pd.read_csv('https://raw.githubusercontent.com/yurchisin/modeling-examples/master/fantasy_basketball_1_2/results_target_advanced.csv') #load processed dataset
player_predictions.sort_values(by='PredictedFantasyPoints',ascending=False).head(20)
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Player</th>
<th>MainPosition</th>
<th>AlternativePosition</th>
<th>Team</th>
<th>Opp</th>
<th>Salary</th>
<th>PredictedFantasyPoints</th>
<th>Points/Salary Ratio</th>
</tr>
</thead>
<tbody>
<tr>
<th>4</th>
<td>Joel Embiid</td>
<td>C</td>
<td>NaN</td>
<td>PHI</td>
<td>NYK</td>
<td>9500</td>
<td>51.313689</td>
<td>5.401441</td>
</tr>
<tr>
<th>0</th>
<td>James Harden</td>
<td>PG</td>
<td>SG</td>
<td>HOU</td>
<td>OKC</td>
<td>11100</td>
<td>48.809577</td>
<td>4.397259</td>
</tr>
<tr>
<th>1</th>
<td>LeBron James</td>
<td>SF</td>
<td>PF</td>
<td>CLE</td>
<td>GSW</td>
<td>11000</td>
<td>48.149718</td>
<td>4.377247</td>
</tr>
<tr>
<th>2</th>
<td>Russell Westbrook</td>
<td>PG</td>
<td>NaN</td>
<td>OKC</td>
<td>HOU</td>
<td>10900</td>
<td>44.007224</td>
<td>4.037360</td>
</tr>
<tr>
<th>3</th>
<td>Kevin Durant</td>
<td>SF</td>
<td>PF</td>
<td>GSW</td>
<td>CLE</td>
<td>10500</td>
<td>43.438575</td>
<td>4.137007</td>
</tr>
<tr>
<th>19</th>
<td>Dario Saric</td>
<td>PF</td>
<td>C</td>
<td>PHI</td>
<td>NYK</td>
<td>6200</td>
<td>40.505486</td>
<td>6.533143</td>
</tr>
<tr>
<th>5</th>
<td>Ben Simmons</td>
<td>PG</td>
<td>SF</td>
<td>PHI</td>
<td>NYK</td>
<td>9300</td>
<td>38.692817</td>
<td>4.160518</td>
</tr>
<tr>
<th>12</th>
<td>Kyle Kuzma</td>
<td>SF</td>
<td>PF</td>
<td>LAL</td>
<td>MIN</td>
<td>7300</td>
<td>38.201774</td>
<td>5.233120</td>
</tr>
<tr>
<th>8</th>
<td>Jimmy Butler</td>
<td>SG</td>
<td>NaN</td>
<td>MIN</td>
<td>LAL</td>
<td>8400</td>
<td>37.873164</td>
<td>4.508710</td>
</tr>
<tr>
<th>13</th>
<td>Draymond Green</td>
<td>PF</td>
<td>C</td>
<td>GSW</td>
<td>CLE</td>
<td>7200</td>
<td>37.018949</td>
<td>5.141521</td>
</tr>
<tr>
<th>15</th>
<td>Paul George</td>
<td>SF</td>
<td>NaN</td>
<td>OKC</td>
<td>HOU</td>
<td>6800</td>
<td>36.398212</td>
<td>5.352678</td>
</tr>
<tr>
<th>6</th>
<td>Karl-Anthony Towns</td>
<td>C</td>
<td>NaN</td>
<td>MIN</td>
<td>LAL</td>
<td>8900</td>
<td>36.188913</td>
<td>4.066170</td>
</tr>
<tr>
<th>17</th>
<td>Clint Capela</td>
<td>C</td>
<td>NaN</td>
<td>HOU</td>
<td>OKC</td>
<td>6600</td>
<td>33.490320</td>
<td>5.074291</td>
</tr>
<tr>
<th>10</th>
<td>John Wall</td>
<td>PG</td>
<td>NaN</td>
<td>WAS</td>
<td>BOS</td>
<td>8000</td>
<td>33.197563</td>
<td>4.149695</td>
</tr>
<tr>
<th>38</th>
<td>Jordan Bell</td>
<td>PF</td>
<td>C</td>
<td>GSW</td>
<td>CLE</td>
<td>4900</td>
<td>33.083296</td>
<td>6.751693</td>
</tr>
<tr>
<th>9</th>
<td>Kyrie Irving</td>
<td>PG</td>
<td>NaN</td>
<td>BOS</td>
<td>WAS</td>
<td>8300</td>
<td>31.835863</td>
<td>3.835646</td>
</tr>
<tr>
<th>22</th>
<td>Jeff Teague</td>
<td>PG</td>
<td>NaN</td>
<td>MIN</td>
<td>LAL</td>
<td>6000</td>
<td>31.460451</td>
<td>5.243408</td>
</tr>
<tr>
<th>27</th>
<td>Steven Adams</td>
<td>C</td>
<td>NaN</td>
<td>OKC</td>
<td>HOU</td>
<td>5500</td>
<td>31.150428</td>
<td>5.663714</td>
</tr>
<tr>
<th>18</th>
<td>Klay Thompson</td>
<td>SG</td>
<td>NaN</td>
<td>GSW</td>
<td>CLE</td>
<td>6400</td>
<td>29.283897</td>
<td>4.575609</td>
</tr>
<tr>
<th>16</th>
<td>Al Horford</td>
<td>PF</td>
<td>C</td>
<td>BOS</td>
<td>WAS</td>
<td>6700</td>
<td>27.906772</td>
<td>4.165190</td>
</tr>
</tbody>
</table>
</div>
Have you figured out the total number of possible lineups yet? It's around $3.6 \times 10^{11}$, which is a lot.
This is where mathematical optimization and Gurobi are best utilized: To efficiently explore a huge decision space and provide a much needed tool for optimal decision-making.
<h3> Optimal DraftKings Lineup Selection </h3>
As we set up our optimization model, we first need to make some definitions. Some of this is the same as before, but as this example is a bit more complicated, we'll need to be a bit more thorough in some definitions.
**Sets and Indices**
$i$ is the index for the set of all players
$j$ is the index for the set of basketball positions (PG,SG,SF,PF,C)
**Input Parameters**
$p_{i}$: the predicted fantasy points of player $i$
$s_{i}$: the salary of player $i$
$S$: our total available salary
```python
players = player_predictions["Player"].tolist()
positions = player_predictions["MainPosition"].unique().tolist()
salaries = player_predictions["Salary"].tolist()
fantasypoints = player_predictions["PredictedFantasyPoints"].tolist()
S = 50000
salary_dict = {players[i]: salaries[i] for i in range(len(players))}
points_dict = {players[i]: fantasypoints[i] for i in range(len(players))}
m = Model()
```
Restricted license - for non-production use only - expires 2023-10-25
**Decision Variables**
Since it is possible for certain players to fill one of two positions, we need to map each player to their eligible positions. Additionally, we need to add the position index to our decision variable. Instead of a binary variable (i.e. a variable that only takes the values of 0 or 1) $y_i$ we have $y_{i,j}$.
$y_{i,j}$: This variable is equal to 1 if player $i$ is selected at position $j$; and 0 otherwise.
```python
mainposition = list(zip(player_predictions.Player, player_predictions.MainPosition))
alternativeposition = list(zip(player_predictions.Player, player_predictions.AlternativePosition))
indices = mainposition+alternativeposition
player_pos_map = [t for t in indices if not any(isinstance(n, float) and math.isnan(n) for n in t)]
y = m.addVars(player_pos_map, vtype=GRB.BINARY, name="y")
```
**Objective Function**
The objective function of our problem is to maximize the total fantasy points of our lineup, same as the last time but using the differently indexed decision variable.
\begin{align}
Max \hspace{0.2cm} Z = \sum_{i,j} p_{i} \cdot y_{i,j}
\end{align}
```python
m.setObjective(quicksum([points_dict[i]*y[i,j] for i,j in player_pos_map]), GRB.MAXIMIZE)
```
**Constraints**
Our model still requires each of the primary basketball positions (PG, SG, SF, PF, C) to be filled. Last time we required exactly one of each, so these constraints were equalities (note that this also implied our roster size of five players). In this version of our model, we need *at least one* of each position since it is possible to use, for example, only one power forward (PF).
For each position $j$:
\begin{align}
\sum_{i} y_{i,j} \geq 1
\end{align}
Here is where we have a couple of options in how to add these constraints. The first, intuitively, is to loop through the set of positions. The second uses a slightly different function to add the constraints (*addConstr* -> *addConstrs*). This function incorporates the for loop directly as an argument. **Running both will double up on the constraints in the model, which isn't best practice, so take a look at each approach and comment one out before running the cell.**
```python
# option 1 for writing the above constraints
for j in positions:
m.addConstr(quicksum([y[i,j] for i, pos in player_pos_map if pos==j])>=1, name = "pos" + j)
# option 2, a slightly more compact way of adding the same set of constraints
m.addConstrs((quicksum([y[i,j] for i, pos in player_pos_map if pos==j])>=1 for j in positions), name = "pos");
```
Now let's work with the additional slots of our new roster: the guard, forward, and utility slots. Here it's worth mentioning that there are different ways to formulate the same problem in mathematical optimization. Some approaches can be better than others and writing efficient models will become an important skill as you tackle larger and more complex problems.
Let's first consider the additional slot for the guard position, which can be filled by a PG or a SG. Considering the overall roster we want to create, we have already guaranteed one PG and one SG (so two total guards). To make sure we get one more additional guard, a constraint needs to added that says the total number of guards needs to be *at least* three.
\begin{align}
\sum_{i} y_{i,j} \geq 3, position\space j \space is\space PG\space or \space SG
\end{align}
The same needs to be done for forwards (SF or PF)
\begin{align}
\sum_{i} y_{i,j} \geq 3, position\space j \space is\space SF\space or \space PF
\end{align}
It is important that we use inequalities here because of the utility position we'll address in a little bit.
```python
m.addConstr(quicksum([y[i,j] for i, j in player_pos_map if (j=='PG' or j=='SG')])>=3)
m.addConstr(quicksum([y[i,j] for i, j in player_pos_map if (j=='SF' or j=='PF')])>=3);
```
Now that we have a position index for our decision variable, we need to ensure each player is assigned to *at most* one position (either their primary or alternative, but not both). To do this we sum across each position $j$ for each player and limit that summation to one.
For each player $i$,
\begin{align}
\sum_{j} y_{i,j} \leq 1
\end{align}
Here we'll use another way to sum over one of the variable's indices by appending *.sum* to the end and replacing the index we want to sum over with "\*". This is useful because each player is not eligible for each position and this syntax automatically sums over the second index.
```python
m.addConstrs((y.sum(i, "*") <= 1 for i in players), name="max_one");
```
A good exercise would be to rewrite other summations using this syntax and to try and the above constraint using quicksum.
So far we have addressed seven of our eight lineup slots. Since the utility slot can have any position, all we need is to require the total number of players selected to be eight by setting the sum over all players and positions to that value.
\begin{align}
\sum_{i,j} y_{i,j} = 8
\end{align}
```python
m.addConstr(quicksum([y[i,j] for i,j in player_pos_map]) == 8, name="full_lineup");
```
Finally, we need to stay under the salary cap $S$, which in a typical DraftKings contest is $\$50,000$:
\begin{align}
\sum_{i,j} s_{i} \cdot y_{i,j} \leq S
\end{align}
```python
cap = m.addConstr(quicksum(salary_dict[i]*y[i,j] for i,j in player_pos_map) <= S, name="salary")
```
In this last constraint, we stored it to be able to easily get information about this constraint after the model runs and the model is updated just as if we didn't store the constraint. Time to find the optimal lineup.
```python
m.optimize() # optimize our model
```
Gurobi Optimizer version 9.5.1 build v9.5.1rc2 (mac64[rosetta2])
Thread count: 8 physical cores, 8 logical processors, using up to 8 threads
Optimize a model with 112 rows, 167 columns and 975 nonzeros
Model fingerprint: 0x9c23fd93
Variable types: 0 continuous, 167 integer (167 binary)
Coefficient statistics:
Matrix range [1e+00, 1e+04]
Objective range [7e+00, 5e+01]
Bounds range [1e+00, 1e+00]
RHS range [1e+00, 5e+04]
Found heuristic solution: objective 206.2597683
Presolve removed 34 rows and 0 columns
Presolve time: 0.00s
Presolved: 78 rows, 167 columns, 779 nonzeros
Variable types: 0 continuous, 167 integer (167 binary)
Found heuristic solution: objective 268.7822348
Root relaxation: objective 2.864073e+02, 71 iterations, 0.00 seconds (0.00 work units)
Nodes | Current Node | Objective Bounds | Work
Expl Unexpl | Obj Depth IntInf | Incumbent BestBd Gap | It/Node Time
0 0 286.40727 0 2 268.78223 286.40727 6.56% - 0s
H 0 0 283.6262215 286.40727 0.98% - 0s
0 0 285.84146 0 7 283.62622 285.84146 0.78% - 0s
0 0 285.84146 0 2 283.62622 285.84146 0.78% - 0s
Cutting planes:
Cover: 1
RLT: 1
Explored 1 nodes (85 simplex iterations) in 0.03 seconds (0.00 work units)
Thread count was 8 (of 8 available processors)
Solution count 4: 283.626 283.626 268.782 206.26
Optimal solution found (tolerance 1.00e-04)
Best objective 2.836262214900e+02, best bound 2.836262214900e+02, gap 0.0000%
Notice the output above says we have 167 binary variables, which is much less than $98 \cdot 5 = 490$ variables we'd have if we mapped all players to all basketball positions. Additionally, we would need more constraints to eliminate ineligible player/position combinations. While this wouldn't make much difference in this small example, formulating efficient models is a valuable skill in mathematical optimization.
Let's display our optimal lineup.
```python
player_selections = []
for v in m.getVars():
if (abs(v.x) > 1e-6):
player_selections.append(tuple(y)[v.index])
df = pd.DataFrame(player_selections, columns = ['Player','Assigned Position'])
df = df.merge(pd.DataFrame(list(salary_dict.items()), columns=['Player', 'Salary']), left_on=['Player'], right_on=['Player'])
lineup = df.merge(pd.DataFrame(list(points_dict.items()), columns=['Player', 'Predicted Points']), left_on=['Player'], right_on=['Player'])
lineup.sort_values(by=['Assigned Position'])
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Player</th>
<th>Assigned Position</th>
<th>Salary</th>
<th>Predicted Points</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>Joel Embiid</td>
<td>C</td>
<td>9500</td>
<td>51.313689</td>
</tr>
<tr>
<th>6</th>
<td>Jordan Bell</td>
<td>C</td>
<td>4900</td>
<td>33.083296</td>
</tr>
<tr>
<th>2</th>
<td>Draymond Green</td>
<td>PF</td>
<td>7200</td>
<td>37.018949</td>
</tr>
<tr>
<th>3</th>
<td>Dario Saric</td>
<td>PF</td>
<td>6200</td>
<td>40.505486</td>
</tr>
<tr>
<th>4</th>
<td>Jeff Teague</td>
<td>PG</td>
<td>6000</td>
<td>31.460451</td>
</tr>
<tr>
<th>5</th>
<td>Jarrett Jack</td>
<td>PG</td>
<td>4600</td>
<td>27.780012</td>
</tr>
<tr>
<th>1</th>
<td>Kyle Kuzma</td>
<td>SF</td>
<td>7300</td>
<td>38.201774</td>
</tr>
<tr>
<th>7</th>
<td>Josh Hart</td>
<td>SG</td>
<td>3700</td>
<td>24.262564</td>
</tr>
</tbody>
</table>
</div>
```python
print('Total fantasy score: ', round(m.objVal,2))
print('Remaining salary: ', cap.Slack)
```
Total fantasy score: 283.63
Remaining salary: 600.0
The last print statement uses the constraint we stored earlier. The *Slack* attribute of a constraint will show any gap between each side of the inequality. For this application, it's the gap between the salary cap and the amount of salary used in the optimal lineup, which shows there is $600 in unused salary.
<h2> Conclusion </h2>
In this notebook we finished up a problem that started from a raw data set containing NBA player box score data and ended in, if our predictive model holds, an optimal fantasy basketball lineup.
Specifically in this part, we:
- Expanded the initial model to reflect the true complexity of creating a fantasy basketball lineup
- Discovered multiple ways to add a set of constraints to a model
- Utilized two summation commands
- Used attributes of a model to get more information about the optimal solution
Overall, this two-part example displayed how, even with the best predictive model, making optimal decisions is still a complicated exercise. Along with machine learning techniques, mathematical optimization is an essential part of a well-developed analytical toolbox.
|
|||
|||
||| Module : NetList/Check.idr
||| Copyright : (c) Jan de Muijnck-Hughes
||| License : see LICENSE
|||
module Circuits.NetList.Check
import Decidable.Equality
import Data.Nat
import Data.String
import Data.List.Elem
import Data.List.Quantifiers
import Data.Fin
import Data.Singleton
import Toolkit.Decidable.Informative
import Toolkit.Data.Location
import Toolkit.Data.Whole
import Toolkit.Data.DList
import Toolkit.DeBruijn.Context
import Toolkit.Data.List.AtIndex
import Toolkit.DeBruijn.Context.Item
import Toolkit.DeBruijn.Context
import Toolkit.DeBruijn.Renaming
import Circuits.NetList.Core
import Circuits.NetList.Types
import Circuits.NetList.Terms
import Circuits.NetList.AST
%default total
public export
Context : List Ty -> Type
Context = Context Ty
throw : Check.Error -> NetList a
throw = (throw . TyCheck)
throwAt : FileContext
-> Check.Error
-> NetList a
throwAt fc = (Check.throw . Err fc)
embedAt : FileContext
-> Check.Error
-> Dec a
-> NetList a
embedAt _ _ (Yes prf)
= pure prf
embedAt fc err (No _)
= throwAt fc err
embedAtInfo : FileContext
-> Check.Error
-> DecInfo e a
-> NetList a
embedAtInfo _ _ (Yes prfWhy)
= pure prfWhy
embedAtInfo fc err (No _ _)
= throwAt fc err
||| Naive program transformations and checks.
namespace Elab
export
getDataType : (fc : FileContext)
-> (term : (type ** Term ctxt type))
-> NetList DType
getDataType fc (MkDPair (TyPort (d,x)) snd)
= pure x
getDataType fc (MkDPair (TyChan x) snd)
= pure x
getDataType fc (MkDPair type snd)
= throwAt fc PortChanExpected
||| Need to make sure that the indices are in the correct direction.
rewriteTerm : Cast flow expected
-> Index INOUT
-> Term ctxt (TyPort (flow,type))
-> Term ctxt (TyPort (flow,type))
rewriteTerm c d (Var prf) = Var prf
rewriteTerm BI (UP UB) (Index idir what idx)
= Index (UP UB) (rewriteTerm BI (UP UB) what) idx
rewriteTerm BI (DOWN DB) (Index idir what idx)
= Index (DOWN DB) (rewriteTerm BI (DOWN DB) what) idx
rewriteTerm BO (UP UB) (Index idir what idx)
= Index (UP UB) (rewriteTerm BI (UP UB) what) idx
rewriteTerm BO (DOWN DB) (Index idir what idx)
= Index (DOWN DB) (rewriteTerm BI (DOWN DB) what) idx
rewriteTerm BI _ (Project WRITE _) impossible
rewriteTerm BO _ (Project WRITE _) impossible
rewriteTerm BI _ (Project READ _) impossible
rewriteTerm BO _ (Project READ _) impossible
rewriteTerm BI _ (Cast BI _) impossible
rewriteTerm BO _ (Cast BI _) impossible
rewriteTerm BI _ (Cast BO _) impossible
rewriteTerm BO _ (Cast BO _) impossible
||| When casting we finally know which direction indexing should go,
||| so lets fix that.
shouldCast : {type : DType}
-> (flow,expected : Direction)
-> (term : Term ctxt (TyPort (flow,type)))
-> Dec ( Cast flow expected
, Term ctxt (TyPort (expected,type))
)
shouldCast flow expected term with (Cast.cast flow expected)
shouldCast INOUT INPUT term | (Yes BI) with (dirFromCast BI)
shouldCast INOUT INPUT term | (Yes BI) | idir
= Yes $ MkPair BI (Cast BI (rewriteTerm BI idir term))
shouldCast INOUT OUTPUT term | (Yes BO) with (dirFromCast BO)
shouldCast INOUT OUTPUT term | (Yes BO) | idir
= Yes $ MkPair BO (Cast BO (rewriteTerm BO idir term))
shouldCast flow expected term | (No contra)
= No (\(prf,t) => contra prf)
portCast : {type : DType}
-> {flow : Direction}
-> (fc : FileContext)
-> (expected : Direction)
-> (term : Term ctxt (TyPort (flow,type)))
-> NetList (Term ctxt (TyPort (expected,type)))
portCast {type} {flow = flow} fc exp term with (shouldCast flow exp term)
portCast {type} {flow = flow} fc exp term | Yes (p,e)
= pure e
portCast {type} {flow = flow} fc exp term | No contra with (decEq flow exp)
portCast {type} {flow = exp} fc exp term | No contra | (Yes Refl)
= pure term
portCast {type} {flow = flow} fc exp term | No contra | (No f)
= throwAt fc (Mismatch (TyPort (exp,type))
(TyPort (flow,type)))
export
checkPort : (fc : FileContext)
-> (exdir : Direction)
-> (expty : DType)
-> (term : (type ** Term ctxt type))
-> NetList (Term ctxt (TyPort (exdir,expty)))
-- [ NOTE ]
--
checkPort fc exdir exty (MkDPair (TyPort (given,x)) term)
= do Refl <- embedAt fc
(MismatchD exty x)
(decEq exty x)
portCast fc exdir term
-- [ NOTE ]
--
-- READ implies INPUT
checkPort fc INPUT exty (MkDPair (TyChan x) term)
= do Refl <- embedAt fc (MismatchD exty x)
(decEq exty x)
pure (Project READ term)
-- [ NOTE ]
--
-- WRITE implies OUTPUT
checkPort fc OUTPUT exty (MkDPair (TyChan x) term)
= do Refl <- embedAt fc (MismatchD exty x)
(decEq exty x)
pure (Project WRITE term)
-- [ NOTE ]
--
-- INOUT Chan's impossible.
checkPort fc INOUT exty (MkDPair (TyChan x) term)
= throwAt fc (ErrI "INOUT CHAN not expected")
-- [ NOTE ]
--
-- Gates/TyUnit not expected
checkPort fc exdir exty (MkDPair type term)
= throwAt fc (Mismatch (TyPort (exdir,exty))
type)
export
indexDir : {flow : Direction}
-> (fc : FileContext)
-> (term : Term ctxt (TyPort (flow,BVECT (W (S n) ItIsSucc) type)))
-> NetList (Index flow)
indexDir {flow} fc term with (flow)
indexDir {flow = flow} fc term | INPUT
= pure (DOWN DI)
indexDir {flow = flow} fc term | OUTPUT
= pure (UP UO)
indexDir {flow = flow} fc (Var prf) | INOUT
= pure (UP UB)
indexDir {flow = flow} fc (Index idir what idx) | INOUT
= pure idir
indexDir {flow = flow} fc (Project how what) | INOUT
= throwAt fc (ErrI "Shouldn't happen impossible indexing a projection with inout")
indexDir {flow = flow} fc (Cast x what) | INOUT
= throwAt fc (ErrI "Shouldn't happen impossible indexing a cast with inout")
construct : {types : List Ty}
-> (curr : Context types)
-> (ast : AST)
-> NetList (DPair Ty (Term types))
construct curr (Var x)
= do prf <- embedAtInfo (span x)
(NotBound (get x))
(lookup (get x) curr)
let (ty ** loc ** idx) = deBruijn prf
pure (ty ** Var (V loc idx))
construct curr (Port fc flow ty n body)
= do (TyUnit ** term) <- construct (extend curr (get n) (TyPort (flow, ty)))
body
| (ty ** _) => throwAt fc (Mismatch TyUnit ty)
pure (_ ** Port flow ty term)
construct curr (Wire fc ty n body)
= do (TyUnit ** term) <- construct (extend curr (get n) (TyChan ty))
body
| (ty ** _) => throwAt fc (Mismatch TyUnit ty)
pure (_ ** Wire ty term)
construct curr (GateDecl fc n g body)
= do (TyGate ** gate) <- construct curr g
| (type ** _) => throwAt fc (Mismatch TyGate type)
(TyUnit ** term) <- construct (extend curr (get n) TyGate)
body
| (type ** _) => throwAt fc (Mismatch TyUnit type)
pure (_ ** GateDecl gate term)
construct curr (Shim fc dir thing)
= do t <- construct curr thing
dtype <- getDataType fc t
term <- checkPort fc dir dtype t
pure (_ ** term)
construct curr (Assign fc o i rest)
= do termI <- construct curr i
ity <- getDataType fc termI
termO <- construct curr o
oty <- getDataType fc termO
Refl <- embedAt fc (MismatchD ity oty)
(decEq ity oty)
o' <- checkPort fc OUTPUT ity termO
i' <- checkPort fc INPUT ity termI
(TyUnit ** r') <- construct curr rest
| (type ** _) => throwAt fc (Mismatch TyUnit type)
pure (_ ** Assign o' i' r')
construct curr (Mux fc o c l r)
= do termO <- construct curr o
termC <- construct curr c
termL <- construct curr l
termR <- construct curr r
o' <- checkPort fc OUTPUT LOGIC termO
c' <- checkPort fc INPUT LOGIC termC
l' <- checkPort fc INPUT LOGIC termL
r' <- checkPort fc INPUT LOGIC termR
pure (_ ** Mux o' c' l' r')
construct curr (GateU fc k o i)
= do termO <- construct curr o
termI <- construct curr i
o' <- checkPort fc OUTPUT LOGIC termO
i' <- checkPort fc INPUT LOGIC termI
pure (_ ** GateU k o' i')
construct curr (GateB fc k o l r)
= do termO <- construct curr o
termL <- construct curr l
termR <- construct curr r
o' <- checkPort fc OUTPUT LOGIC termO
l' <- checkPort fc INPUT LOGIC termL
r' <- checkPort fc INPUT LOGIC termR
pure (_ ** GateB k o' l' r')
construct curr (Index fc idx t)
= do (TyPort (flow,BVECT (W (S n) ItIsSucc) type) ** term) <- construct curr t
| (type ** term)
=> throwAt fc VectorExpected
case natToFin idx (S n) of
Nothing => throw (OOB idx (S n))
Just idx' => do idir <- indexDir fc term
pure (_ ** Index idir term idx')
construct curr (Split fc a b i)
= do termA <- construct curr a
termB <- construct curr b
termI <- construct curr i
a' <- checkPort fc OUTPUT LOGIC termA
b' <- checkPort fc OUTPUT LOGIC termB
i' <- checkPort fc INPUT LOGIC termI
pure (_ ** Split a' b' i')
construct curr (Collect fc o l r)
= do (TyPort (OUTPUT,BVECT (W (S (S Z)) ItIsSucc) type) ** o') <- construct curr o
| (TyPort (flow,BVECT (W (S (S n)) ItIsSucc) type) ** term)
=> throwAt fc (Mismatch (TyPort (OUTPUT, BVECT (W (S (S Z)) ItIsSucc) type))
(TyPort (flow, BVECT (W (S (S n)) ItIsSucc) type))
)
| (type ** term)
=> throwAt fc VectorExpected
termL <- construct curr l
termR <- construct curr r
l' <- checkPort fc INPUT type termL
r' <- checkPort fc INPUT type termR
pure (_ ** Collect o' l' r')
construct curr (Stop fc)
= pure (_ ** Stop)
namespace Design
export
check : (ast : AST) -> NetList (Term Nil TyUnit)
check ast
= do (TyUnit ** term) <- construct Nil ast
| (ty ** term) => throw (Mismatch TyUnit ty)
pure term
-- [ EOF ]
|
module Eris.Predict.KNNbased where
import Data.HashMap.Strict as Map
import Data.Maybe (isNothing, isJust, fromJust)
import Control.Monad (guard)
import qualified Numeric.LinearAlgebra as NL
import Eris.Meta.DataStructure
import Eris.Compute.Similarity
-- | Example:
-- records2eCount : get ecount
-- pairWiseSimilarity : get similarity Matrix
-- neighborOf : get neighbor of a entity A
-- f1 : filter neighbors of A which related to entity of the other type .
-- c1 : retrive relation between two type of entity.
-- t : compute knnbased recommendataion.
t :: NeighborRank -> NeighborSimilarity-> Maybe Rank
t nr ns
| length ns /= length nr = Nothing
| otherwise = Just $ knnbased ns nr
where knnbased ns nr = let
v1 = NL.vector $ fmap snd ns
v2 = NL.vector $ fmap snd nr
in v1 NL.<.> v2 / NL.norm_1 v1
f1 :: PID -> ECount -> NeighborSimilarity -> NeighborSimilarity
f1 pid ecount nsim = do
r@(eid,_) <- nsim
guard $ validRecord ecount eid pid
return r
c1 :: PID -> ECount -> NeighborSimilarity -> NeighborRank
c1 pid ecount nsim =do
(eid, _) <- nsim
let justRank = getRank ecount eid pid
guard $ isJust justRank
return (eid, fromJust justRank)
-- | Given an ID of a entity of certain type.
-- Based on the similairty matrix of this type of entity.
-- collect its neighbors and sort by Order.
-- return a list of tuple [(EID, Rank)] , rank value is necessary in case any further filter or verification process.
neighborOf :: Order -> CID -> SimilarityMatrix -> NeighborSimilarity
neighborOf ord cus matrix
| isNothing (Map.lookup cus matrix) = []
| otherwise = let
rlist = Map.toList matrix
neighborsRank = collectRank rlist cus
in sortByRank neighborsRank ord
where
collectRank :: [(EID, Map.HashMap EID Rank)] -> EID -> NeighborSimilarity
collectRank ((eid,edict) : exs) tid
| eid == tid = Map.toList edict
| otherwise = (eid,Map.lookupDefault 0 tid edict): collectRank exs tid
sortByRank :: NeighborSimilarity -> Order -> NeighborSimilarity
sortByRank nr o = let
ascOrder = quickSortRank nr
in if o == Desc
then
reverse ascOrder
else
ascOrder
quickSortRank :: NeighborSimilarity -> NeighborSimilarity
quickSortRank [] = []
quickSortRank ((eid,erank):ers) =
let smallRanks = quickSortRank [e | e <- ers , snd e <= erank]
biggerRanks = quickSortRank [ e | e<- ers, snd e > erank]
in smallRanks ++ [(eid,erank)] ++ biggerRanks
-- | Auxiliary Functions
validRecord :: ECount -> CID -> PID -> Bool
validRecord ec c p=
let cContainsP = do
pdict <- Map.lookup c ec
Map.lookup p pdict
in isJust cContainsP
getRank :: ECount -> CID -> PID -> Maybe Rank
getRank ec c p = do
pdict <- Map.lookup c ec
Map.lookup p pdict
|
-- Andreas, 2019-02-23, re #3578, less reduction in the unifier.
-- Non-interactive version of interaction/Issue635c.agda.
-- {-# OPTIONS -v tc.lhs.unify:50 #-}
open import Common.Bool
open import Common.Equality
open import Common.Product
test : (p : Bool × Bool) → proj₁ p ≡ true → Set
test _ refl = Bool
-- Tests that the unifier does the necessary weak head reduction.
|
If two paths are homotopic, then they have the same starting point. |
(*
Copyright (C) 2017 M.A.L. Marques
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 http://mozilla.org/MPL/2.0/.
*)
(* type: mgga_exc *)
params_a_mu := MU_GE:
params_a_b := 0.4:
params_a_c := 2.14951:
params_a_e := 1.987:
vt84_gamma := 0.000023:
tpss_ff := z -> 3:
tpss_kappa := (x, t) ->
1/(vt84_gamma/params_a_mu^2 + vt84_gamma/params_a_mu + 1):
$include "tpss_x.mpl"
(* Equation (8) *)
vt84_f := (x, u, t) -> 1
+ tpss_fx(x, t)*exp(-vt84_gamma*tpss_fx(x, t)/params_a_mu)/(1 + tpss_fx(x, t))
+ (1 - exp(-vt84_gamma*tpss_fx(x, t)^2/params_a_mu^2))*(params_a_mu/tpss_fx(x, t) - 1):
f := (rs, z, xt, xs0, xs1, u0, u1, t0, t1) -> mgga_exchange(vt84_f, rs, z, xs0, xs1, u0, u1, t0, t1):
|
Require Import Crypto.Specific.Framework.RawCurveParameters.
Require Import Crypto.Util.LetIn.
(***
Modulus : 2^216 - 2^108 - 1
Base: 21.6
***)
Definition curve : CurveParameters :=
{|
sz := 10%nat;
base := 21 + 3/5;
bitwidth := 32;
s := 2^216;
c := [(1, 1); (2^108, 1)];
carry_chains := Some [[4; 9]; [5; 0; 6; 1; 7; 2; 8; 3; 9; 4]; [5; 0]]%nat;
a24 := None;
coef_div_modulus := Some 2%nat;
goldilocks := Some true;
karatsuba := None;
montgomery := false;
freeze := Some true;
ladderstep := false;
mul_code := None;
square_code := None;
upper_bound_of_exponent_loose := None;
upper_bound_of_exponent_tight := None;
allowable_bit_widths := None;
freeze_extra_allowable_bit_widths := None;
modinv_fuel := None
|}.
Ltac extra_prove_mul_eq _ := idtac.
Ltac extra_prove_square_eq _ := idtac.
|
State Before: α : Type u_1
α' : Type ?u.2419590
β : Type u_2
β' : Type ?u.2419596
γ : Type ?u.2419599
E : Type u_3
inst✝¹² : MeasurableSpace α
inst✝¹¹ : MeasurableSpace α'
inst✝¹⁰ : MeasurableSpace β
inst✝⁹ : MeasurableSpace β'
inst✝⁸ : MeasurableSpace γ
μ μ' : Measure α
ν ν' : Measure β
τ : Measure γ
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : SigmaFinite ν
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : SigmaFinite μ
E' : Type u_4
inst✝² : NormedAddCommGroup E'
inst✝¹ : CompleteSpace E'
inst✝ : NormedSpace ℝ E'
f g : α × β → E
F : E → E'
hf : Integrable f
hg : Integrable g
⊢ (∫ (x : α), F (∫ (y : β), f (x, y) - g (x, y) ∂ν) ∂μ) =
∫ (x : α), F ((∫ (y : β), f (x, y) ∂ν) - ∫ (y : β), g (x, y) ∂ν) ∂μ State After: α : Type u_1
α' : Type ?u.2419590
β : Type u_2
β' : Type ?u.2419596
γ : Type ?u.2419599
E : Type u_3
inst✝¹² : MeasurableSpace α
inst✝¹¹ : MeasurableSpace α'
inst✝¹⁰ : MeasurableSpace β
inst✝⁹ : MeasurableSpace β'
inst✝⁸ : MeasurableSpace γ
μ μ' : Measure α
ν ν' : Measure β
τ : Measure γ
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : SigmaFinite ν
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : SigmaFinite μ
E' : Type u_4
inst✝² : NormedAddCommGroup E'
inst✝¹ : CompleteSpace E'
inst✝ : NormedSpace ℝ E'
f g : α × β → E
F : E → E'
hf : Integrable f
hg : Integrable g
⊢ (fun x => F (∫ (y : β), f (x, y) - g (x, y) ∂ν)) =ᶠ[ae μ] fun x =>
F ((∫ (y : β), f (x, y) ∂ν) - ∫ (y : β), g (x, y) ∂ν) Tactic: refine' integral_congr_ae _ State Before: α : Type u_1
α' : Type ?u.2419590
β : Type u_2
β' : Type ?u.2419596
γ : Type ?u.2419599
E : Type u_3
inst✝¹² : MeasurableSpace α
inst✝¹¹ : MeasurableSpace α'
inst✝¹⁰ : MeasurableSpace β
inst✝⁹ : MeasurableSpace β'
inst✝⁸ : MeasurableSpace γ
μ μ' : Measure α
ν ν' : Measure β
τ : Measure γ
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : SigmaFinite ν
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : SigmaFinite μ
E' : Type u_4
inst✝² : NormedAddCommGroup E'
inst✝¹ : CompleteSpace E'
inst✝ : NormedSpace ℝ E'
f g : α × β → E
F : E → E'
hf : Integrable f
hg : Integrable g
⊢ (fun x => F (∫ (y : β), f (x, y) - g (x, y) ∂ν)) =ᶠ[ae μ] fun x =>
F ((∫ (y : β), f (x, y) ∂ν) - ∫ (y : β), g (x, y) ∂ν) State After: case h
α : Type u_1
α' : Type ?u.2419590
β : Type u_2
β' : Type ?u.2419596
γ : Type ?u.2419599
E : Type u_3
inst✝¹² : MeasurableSpace α
inst✝¹¹ : MeasurableSpace α'
inst✝¹⁰ : MeasurableSpace β
inst✝⁹ : MeasurableSpace β'
inst✝⁸ : MeasurableSpace γ
μ μ' : Measure α
ν ν' : Measure β
τ : Measure γ
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : SigmaFinite ν
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : SigmaFinite μ
E' : Type u_4
inst✝² : NormedAddCommGroup E'
inst✝¹ : CompleteSpace E'
inst✝ : NormedSpace ℝ E'
f g : α × β → E
F : E → E'
hf : Integrable f
hg : Integrable g
a✝ : α
h2f : Integrable fun y => f (a✝, y)
h2g : Integrable fun y => g (a✝, y)
⊢ F (∫ (y : β), f (a✝, y) - g (a✝, y) ∂ν) = F ((∫ (y : β), f (a✝, y) ∂ν) - ∫ (y : β), g (a✝, y) ∂ν) Tactic: filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g State Before: case h
α : Type u_1
α' : Type ?u.2419590
β : Type u_2
β' : Type ?u.2419596
γ : Type ?u.2419599
E : Type u_3
inst✝¹² : MeasurableSpace α
inst✝¹¹ : MeasurableSpace α'
inst✝¹⁰ : MeasurableSpace β
inst✝⁹ : MeasurableSpace β'
inst✝⁸ : MeasurableSpace γ
μ μ' : Measure α
ν ν' : Measure β
τ : Measure γ
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : SigmaFinite ν
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : SigmaFinite μ
E' : Type u_4
inst✝² : NormedAddCommGroup E'
inst✝¹ : CompleteSpace E'
inst✝ : NormedSpace ℝ E'
f g : α × β → E
F : E → E'
hf : Integrable f
hg : Integrable g
a✝ : α
h2f : Integrable fun y => f (a✝, y)
h2g : Integrable fun y => g (a✝, y)
⊢ F (∫ (y : β), f (a✝, y) - g (a✝, y) ∂ν) = F ((∫ (y : β), f (a✝, y) ∂ν) - ∫ (y : β), g (a✝, y) ∂ν) State After: no goals Tactic: simp [integral_sub h2f h2g] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.