text
stringlengths 0
3.34M
|
---|
using .PyPlot
export plotarea, plotarea_dem
"""
plotit(x, y, dem)
plotit(x, y, waterflows_output)
Plot DEM, uparea, flow-dir
"""
plotit(x, y, dem) = plotit(x, y, waterflows(dem))
function plotit(x, y, waterflows_output::Tuple)
area, slen, dir, nout, nin, pits = waterflows_output
fig, axs = subplots(3,1)
sca(axs[1])
mycontour(x, y, dem)
colorbar()
sca(axs[2])
heatmap(x, y, log10.(area))
sca(axs[3])
plotdir(x, y, dir)
end
function plotdir(x, y, dir)
vecfield = dir2vec.(dir)
vecfieldx = [v[1] for v in vecfield]
vecfieldy = [v[2] for v in vecfield]
quiver(repeat(x,1, length(y)), repeat(y,length(x),1), vecfieldx, vecfieldy)
end
pits2inds(pits) = ([p.I[1] for p in pits],
[p.I[2] for p in pits])
pits2vecs(x, y, pits) = (x[[p.I[1] for p in pits if p!=CartesianIndex(-1,-1)]],
y[[p.I[2] for p in pits if p!=CartesianIndex(-1,-1)]])
"""
plotarea(x, y, area, pits; prefn=log10)
Plot uparea, or another variable. If no pits should be plotted, use `[]`.
"""
function plotarea(x, y, area, pits; prefn=log10, cbar=true)
px, py = pits2vecs(x, y, pits)
fig, axs = subplots()
heatmap(x, y, prefn.(area), cbar=cbar)
scatter(px, py, 1, "r")
fig
end
function plotarea_dem(x, y, dem, area, pits; levels=50, threshold=1/100, prefn=log10)
fig, axs = subplots()
mycontour(x, y, dem, levels=levels)
threshold *= prod(size(area))
area = copy(area)
area[area.<threshold] .= NaN
px, py = pits2vecs(x, y, pits)
heatmap(x, y, prefn.(area))
scatter(px, py, 1, "r")
end
function plotbnds(x,y,bnds)
for b in bnds
px, py = pits2vecs(x, y, b)
scatter(px, py, 1, "g")
end
end
function plotlakedepth(x, y, dem)
area, slen, dir, nout, nin, pits = waterflows(dem)
demf = fill_dem(dem, pits, dir)
heatmap(x, y, demf.-dem)
end
function heatmap(x, y, mat; cbar=true)
dx2 = (x[2]-x[1])/2
imshow(Array(mat'), origin="lower", extent=(x[1]-dx2,x[end]+dx2,y[1]-dx2,y[end]+dx2))
cbar && colorbar()
end
function mycontour(x, y, mat; levels=50, cbar=true)
contour(x, y, Array(mat'), levels, linewidths=1)
cbar && colorbar()
end
function plot_catchments(x, y, c, lim=10)
c = copy(c)
tokeep = []
for cc =1:maximum(c)
inds = c.==cc
if sum(inds)<lim
c[inds] .= 0
else
push!(tokeep, inds)
end
end
for (i,inds) in enumerate(tokeep)
c[inds] .= i
end
heatmap(x,y,c)
end
|
import Debug.Trace
import Data.Complex
traceIdShow :: Show a => a -> a
traceIdShow x = trace (show x) x
tracef :: Show b => (a->b) -> a -> a
tracef f x = trace (show $ f x) x
type Coord = Complex Float
data Action = Turn Coord
| Forward Float
| Move Coord
deriving Show
data Ship = Ship Coord Coord
deriving Show
act :: Ship -> Action -> Ship
act (Ship orientation position) (Turn a)
= traceIdShow $
trace ("Turning "++ show a) $
Ship (orientation * a) position
act (Ship orientation position) (Forward d)
= traceIdShow $
trace ("Forward "++ show d) $
Ship orientation (position + orientation * (d:+0))
act (Ship orientation position) (Move p)
= traceIdShow $
trace ("Moving "++ show p) $
Ship orientation (position + p)
-- part 2 changes the orientation to be a waypoint. Because we
-- represent the orientation as a complex number, the changes we make
-- are minimal: we apply moves to the waypoint rather than the ship's
-- position. Also, when calling act, change the start position of the
-- waypoint.
act2 :: Ship -> Action -> Ship
act2 (Ship waypoint position) (Turn a)
= traceIdShow $
trace ("Turning "++ show a) $
Ship (waypoint * a) position
act2 (Ship waypoint position) (Forward d)
= traceIdShow $
trace ("Forward "++ show d) $
Ship waypoint (position + waypoint * (d:+0))
act2 (Ship waypoint position) (Move p)
= traceIdShow $
trace ("Moving "++ show p) $
Ship (waypoint + p) position
main = interact $ (++ "\n") . show . length
. tracef ((\d-> "Part 2: " ++ show d)
. manhatten
. foldl act2 (Ship (10:+1) (0:+0)))
. tracef ((\d-> "Part 1: " ++ show d)
. manhatten
. foldl act (Ship (1:+0) (0:+0)))
. map toAction . lines
toAction (a:vs) | a == 'N' = Move $ 0 :+ v
| a == 'S' = Move $ 0 :+ (-1 * v)
| a == 'E' = Move $ v :+ 0
| a == 'W' = Move $ (-1 * v) :+ 0
| a == 'L' = Turn $ cis $ v / 180 * pi
| a == 'R' = Turn $ cis $ -1 * v / 180 * pi
| a == 'F' = Forward $ v
| otherwise = error $ "unknown action "++ show a
where v = read vs :: Float
manhatten :: Ship -> Int
manhatten (Ship _ p) = round $ abs(realPart p) + abs(imagPart p)
|
"""
Takes a CSV file and makes it into a dataframe with reasonable header, etc.
"""
function importCSV(filename;header=3)
#Read File as Dataframe
df = CSV.read(filename,DataFrame,header=header)
return df
end
"""
Cleans a MACCOR file based on everything wrong I see so far
"""
function clean_df(df)
df = convertTestTime(df)
df = convertStepTime(df)
df = cleanGarbageCols(df)
end
"""
Converts a dataframe with raw time vector to usable date-time format
"""
function convertTestTime(df;start=DateTime(1,1,1,0,0))
testTime = df.TestTime
testTimes = split.(testTime)
newTestTimes = Array{DateTime,1}(undef,length(testTime))
for (i,time) in enumerate(testTimes)
testday = time[1]
#Since d is one letter, the day is 1:end-1
numTestDays = testday[1:end-1]
numTestDays = parse(Int,numTestDays)
testtime = time[2]
testtime = split(testtime,(':','.'))
testtime = parse.(Int,testtime)
testtime = start+Day(numTestDays)+Hour(testtime[1])+Minute(testtime[2])+Second(testtime[3])+Millisecond(testtime[4]*10)
newTestTimes[i] = testtime
end
df.TestTime = newTestTimes
return df
end
"""This converts the step times of the testing DF's to reasonable times"""
function convertStepTime(df;start=DateTime(1,1,1,0,0))
stepTime = df.StepTime
stepTimes = split.(stepTime)
newStepTimes = Array{DateTime,1}(undef,length(stepTime))
for (i,time) in enumerate(stepTimes)
stepday = time[1]
#Since d is one letter, the day is 1:end-1
numStepDays = stepday[1:end-1]
numStepDays = parse(Int,numStepDays)
steptime = time[2]
steptime = split(steptime,(':','.'))
steptime = parse.(Int,steptime)
steptime = start+Day(numStepDays)+Hour(steptime[1])+Minute(steptime[2])+Second(steptime[3])+Millisecond(steptime[4]*10)
newStepTimes[i] = steptime
end
df.StepTime = newStepTimes
return df
end
"""This gets rid of cols that are useless"""
function cleanGarbageCols(df)
df = deepcopy(df) #Don't want to mutate here
cols = names(df)
for col in cols
#My Current Best guess heuristic on what a garbage column looks like, LOL
if any(ismissing.(df[:,col]))
@warn "Deleted $col"
select!(df,Not(col))
continue
end
if all(df[:,col].==0)
select!(df,Not(col))
end
end
return df
end
|
Iref=(im2double(imread('test.jpg')));
tau=[0.2,0.3,0.1,0.2,200,100];
% tau=[0,0,0,0,50,100];
It=Iref;
for i=1:3
It(:,:,i)=warpImg(Iref(:,:,i),tau);
end
It=1.4*abs(It+0.0001)+0.1;
imshow([Iref,It])
tic
[ImTrans,tau,ImTrans_c] = align_c(It,Iref, zeros(6,1),2);
toc;
imshow([It,Iref,ImTrans,ImTrans_c,10*abs(ImTrans_c-Iref)]) |
lemma complex_cnj_mult [simp]: "cnj (x * y) = cnj x * cnj y" |
Belinda developed a passion for property and architecture from an early age. Whilst growing up, moving from home to home with her parents, she explored the various types of properties and the incredible breadth of interior and exterior styles that accompanied them. Naturally she witnessed all the pitfalls of moving house and renovations too!
Belinda studied interior design at the KLC School of Design and now runs Belinda Corani Interiors and Home Conscious Ltd, a bespoke property and interiors consultancy from her home in west London. Currently she is working on four properties in Earls Court, St John’s Wood, Ealing, Kensington and Marylebone.
Home Conscious Ltd is a bespoke property and interiors consultancy specialising in both residential and commercial refurbishment.
I offer complete design and project management of refurbishments or targeted help with designing your interiors and exteriors. I specialise in listed buildings, many of them large commercial buildings that need extensive refurbishment; contracts that are often needing confidentiality, discretion and diplomacy.
Following renovation, I regularly manage property for private, international individuals, developers, institutes and insurers.
Working mostly in London and the home counties I travel internationally where necessary.
In addition to this, I am a design entrepreneur that teaches interior designers and would be interior designers to make a full time living doing what they love. Using tried and tested methods, I explain the life of an interior designer and talk personally about my current projects.
Today, the Home Conscious podcast, blog and video channel reaches people through iTunes, YouTube, and SoundCloud.
Using case studies; past, current and future projects, I show how to become an interior designer and how you can build your company along the way. With interviews with specialist contractors and product reviews that will help you with your own projects, I show you what it’s like on the front line of interior design, the pitfalls and the successes. |
Formal statement is: lemma prime_factors_ge_0_int [elim]: (* FIXME !? *) fixes n :: int shows "p \<in> prime_factors n \<Longrightarrow> p \<ge> 0" Informal statement is: If $p$ is a prime factor of $n$, then $p \geq 0$. |
\subsection{((( data.title ))):}
\sectionsep
((* for item in data.skills *))
((( item )))
((* endfor *))
\sectionsep |
lemma prime_nat_iff_prime [simp]: "prime (nat k) \<longleftrightarrow> prime k" |
\documentclass[10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[font=small,labelfont=bf]{caption}
\usepackage{geometry}
\usepackage[sort&compress, numbers, super]{natbib}
\usepackage{pxfonts}
\usepackage{graphicx}
\usepackage{setspace}
\usepackage{hyperref}
\usepackage{lineno}
\newcommand{\argmax}{\mathop{\mathrm{argmax}}\limits}
\newcommand{\demo}{S1}
\doublespacing
\linenumbers
\title{Template paper}
\author{First Author\textsuperscript{1}, Middle Author\textsuperscript{1,2}, Senior Author\textsuperscript{*, 2}\\\textsuperscript{1}Affiliation 1\\\textsuperscript{2}Affiliation 2\\\textsuperscript{*}Corresponding author: [email protected]}
\date{}
\begin{document}
\maketitle
\begin{abstract}
Insert abstract here
\end{abstract}
\section*{Main text}
Insert text here (Figs.~\ref{fig:demo}, \demo).
\begin{figure}[tp]
\centering
\includegraphics[width=0.8\textwidth]{figs/trig}
\caption{\textbf{Two trigonometric functions. A. Sine wave.} Look at the pretty sine wave! \textbf{B. Cosine wave.} The cosine wave looks nice too.}
\label{fig:demo}
\end{figure}
\bibliographystyle{apa}
\bibliography{CDL-bibliography/cdl}
\end{document}
|
** Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
** See https://llvm.org/LICENSE.txt for license information.
** SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
* Real arithmetic operations (+, -, *, /) including constant
* folding and implied type conversions of integer operands.
programp
parameter(N = 33)
real rslts(N), expect(N)
c tests 1 - 3:
data expect /-2.0, 2.0, 3.0,
c tests 4 - 11:
+ 3.5, 5e-5, 5e-5, -1.0, 3.5, 0.0, 4.0, 4.0,
c tests 12 - 18:
+ -0.5, -0.5, 5.0, -8.0, 0.5, 1.0, 2.0,
c tests 19 - 25:
+ 1.5, -6.0, 1.0, 1.0, -9.0, 4.0, 4.0,
c tests 26 - 33:
+ 10.0, -1.5, 4.0, 1.0, -2.5, 4.0, 3.0, 1.0 /
data i2 / 2/, x2, xn3, x2en5 / 2.0, - 3.0, 2.0e-5 /
c tests 1 - 3, unary minus:
rslts(1) = -2.0
rslts(2) = - ( -x2)
rslts(3) = -xn3
c tests 4 - 11, addition:
rslts(4) = 1.5 + 2.0
rslts(5) = x2en5 + 3e-5
rslts(6) = 3e-5 + x2en5
rslts(7) = x2 + xn3
rslts(8) = 2 + 1.5
rslts(9) = xn3 + (+3)
rslts(10) = +x2 + i2
rslts(11) = i2 + x2
c tests 12 - 18, subtraction:
rslts(12) = 1.5 - 2.0
rslts(13) = 1.5 - x2
rslts(14) = x2 - xn3
rslts(15) = (-5) - (- xn3)
rslts(16) = i2 - 1.5
rslts(17) = 3.0 - i2
rslts(18) = 3.0 - 1
c tests 19 - 25, multiplication:
rslts(19) = 0.5 * 3.0
rslts(20) = x2 * xn3
rslts(21) = x2 * .5
rslts(22) = 2 * .5
rslts(23) = xn3 * 3
rslts(24) = x2 * i2
rslts(25) = i2 * x2
c tests 26 - 33, division:
rslts(26) = 5.0 / .5
rslts(27) = xn3 / x2
rslts(28) = x2 / .5
rslts(29) = 2.0 / x2
rslts(30) = 5 / (-x2)
rslts(31) = i2 / .5
rslts(32) = 3.0 / (i2 - 1)
rslts(33) = 5.0 / 5
c check results:
call check(rslts, expect, N)
end
|
SUBROUTINE ROM1 (N,SUM,NX)
C
C ROM1 INTEGRATES THE 6 SOMMERFELD INTEGRALS FROM A TO B IN LAMBDA.
C THE METHOD OF VARIABLE INTERVAL WIDTH ROMBERG INTEGRATION IS USED.
C
COMPLEX A,B,SUM,G1,G2,G3,G4,G5,T00,T01,T10,T02,T11,T20
COMMON /CNTOUR/ A,B
DIMENSION SUM(6), G1(6), G2(6), G3(6), G4(6), G5(6), T01(6), T10(6
1), T20(6)
DATA NM,NTS,RX/131072,4,1.E-4/
LSTEP=0
Z=0.
ZE=1.
S=1.
EP=S/(1.E4*NM)
ZEND=ZE-EP
DO 1 I=1,N
1 SUM(I)=(0.,0.)
NS=NX
NT=0
CALL SAOA (Z,G1)
2 DZ=S/NS
IF (Z+DZ.LE.ZE) GO TO 3
DZ=ZE-Z
IF (DZ.LE.EP) GO TO 17
3 DZOT=DZ*.5
CALL SAOA (Z+DZOT,G3)
CALL SAOA (Z+DZ,G5)
4 NOGO=0
DO 5 I=1,N
T00=(G1(I)+G5(I))*DZOT
T01(I)=(T00+DZ*G3(I))*.5
T10(I)=(4.*T01(I)-T00)/3.
C TEST CONVERGENCE OF 3 POINT ROMBERG RESULT
CALL TEST (REAL(T01(I)),REAL(T10(I)),TR,AIMAG(T01(I)),AIMAG(T10
1(I)),TI,0.)
IF (TR.GT.RX.OR.TI.GT.RX) NOGO=1
5 CONTINUE
IF (NOGO.NE.0) GO TO 7
DO 6 I=1,N
6 SUM(I)=SUM(I)+T10(I)
NT=NT+2
GO TO 11
7 CALL SAOA (Z+DZ*.25,G2)
CALL SAOA (Z+DZ*.75,G4)
NOGO=0
DO 8 I=1,N
T02=(T01(I)+DZOT*(G2(I)+G4(I)))*.5
T11=(4.*T02-T01(I))/3.
T20(I)=(16.*T11-T10(I))/15.
C TEST CONVERGENCE OF 5 POINT ROMBERG RESULT
CALL TEST (REAL(T11),REAL(T20(I)),TR,AIMAG(T11),AIMAG(T20(I)),TI
1,0.)
IF (TR.GT.RX.OR.TI.GT.RX) NOGO=1
8 CONTINUE
IF (NOGO.NE.0) GO TO 13
9 DO 10 I=1,N
10 SUM(I)=SUM(I)+T20(I)
NT=NT+1
11 Z=Z+DZ
IF (Z.GT.ZEND) GO TO 17
DO 12 I=1,N
12 G1(I)=G5(I)
IF (NT.LT.NTS.OR.NS.LE.NX) GO TO 2
NS=NS/2
NT=1
GO TO 2
13 NT=0
IF (NS.LT.NM) GO TO 15
IF (LSTEP.EQ.1) GO TO 9
LSTEP=1
CALL LAMBDA (Z,T00,T11)
PRINT 18, T00
PRINT 19, Z,DZ,A,B
DO 14 I=1,N
14 PRINT 19, G1(I),G2(I),G3(I),G4(I),G5(I)
GO TO 9
15 NS=NS*2
DZ=S/NS
DZOT=DZ*.5
DO 16 I=1,N
G5(I)=G3(I)
16 G3(I)=G2(I)
GO TO 4
17 CONTINUE
RETURN
C
18 FORMAT (38H ROM1 -- STEP SIZE LIMITED AT LAMBDA =,2E12.5)
19 FORMAT (10E12.5)
END |
# Return the list L after applying Knuth shuffle. GAP also has the function Shuffle, which does the same.
ShuffleAlt := function(a)
local i, j, n, t;
n := Length(a);
for i in [n, n - 1 .. 2] do
j := Random(1, i);
t := a[i];
a[i] := a[j];
a[j] := t;
od;
return a;
end;
# Return a "Permutation" object (a permutation of 1 .. n).
# They are printed in GAP, in cycle decomposition form.
PermShuffle := n -> PermList(ShuffleAlt([1 .. n]));
ShuffleAlt([1 .. 10]);
# [ 4, 7, 1, 5, 8, 2, 6, 9, 10, 3 ]
PermShuffle(10);
# (1,9)(2,3,6,4,5,10,8,7)
# One may also call the built-in random generator on the symmetric group :
Random(SymmetricGroup(10));
(1,8,2,5,9,6)(3,4,10,7)
|
------------------------------------------------------------------------------
-- Testing the existential quantifier
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module Existential where
postulate
D : Set
A : D → Set
∃ : (A : D → Set) → Set
postulate foo : (∃ λ x → A x) → (∃ λ x → A x)
{-# ATP prove foo #-}
|
lemma local_lipschitz_continuous_on: assumes local_lipschitz: "local_lipschitz T X f" assumes "t \<in> T" shows "continuous_on X (f t)" |
! ###############################################################################################################################
! Begin MIT license text.
! _______________________________________________________________________________________________________
! Copyright 2019 Dr William R Case, Jr ([email protected])
! 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 and documentation.
! 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.
! _______________________________________________________________________________________________________
! End MIT license text.
MODULE GEN_T0L_Interface
INTERFACE
SUBROUTINE GEN_T0L (RGRID_ROW, ICORD, THETAD, PHID, T0L )
USE PENTIUM_II_KIND, ONLY : BYTE, LONG, DOUBLE
USE CONSTANTS_1, ONLY : ZERO, ONE, ONE80, PI
USE IOUNT1, ONLY : WRT_ERR, WRT_LOG, F04, f06
USE SCONTR, ONLY : BLNK_SUB_NAM
USE PARAMS, ONLY : EPSIL
USE TIMDAT, ONLY : TSEC
USE SUBR_BEGEND_LEVELS, ONLY : GEN_T0L_BEGEND
USE MODEL_STUF, ONLY : RGRID, CORD, RCORD
IMPLICIT NONE
INTEGER(LONG), INTENT(IN) :: RGRID_ROW ! Row number in array RGRID where the RGRID data is stored for the grid
INTEGER(LONG), INTENT(IN) :: ICORD ! Internal coord ID for coord sys L
INTEGER(LONG), PARAMETER :: SUBR_BEGEND = GEN_T0L_BEGEND
REAL(DOUBLE), INTENT(OUT) :: THETAD,PHID ! Azimuth and elevation angles (deg) for cylindrical/spherical coord sys
REAL(DOUBLE), INTENT(OUT) :: T0L(3,3) ! 3 x 3 coord transformation matrix described above
END SUBROUTINE GEN_T0L
END INTERFACE
END MODULE GEN_T0L_Interface
|
{- reported by Guillaume Brunerie on 2015-09-17 -}
{-# OPTIONS --rewriting #-}
data _==_ {A : Set} (a : A) : A → Set where
idp : a == a
{-# BUILTIN REWRITE _==_ #-}
postulate
A B : Set
f g : A → B
module M (x : A) where
postulate
rx : f x == g x
{-# REWRITE rx #-}
-- This shouldn't work
test : (y : A) → f y == g y
test y = idp
|
/-
Copyright (c) 2022 Jannis Limperg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jannis Limperg
-/
import Aesop
example : True := by
aesop (options := { noSuchOption := true })
example : True := by
aesop (simp_options := { noSuchOption := true })
|
#include <chrono>
#include <iostream>
#include <boost/asio/io_context.hpp>
#include <boost/program_options.hpp>
#include <libp2p/injector/host_injector.hpp>
#include <libp2p/log/configurator.hpp>
#include <libp2p/log/logger.hpp>
#include <ipfs_pubsub/gossip_pubsub_topic.hpp>
int main(int argc, char *argv[])
{
using libp2p::crypto::Key;
using libp2p::crypto::KeyPair;
using libp2p::crypto::PrivateKey;
using libp2p::crypto::PublicKey;
using GossipPubSub = sgns::ipfs_pubsub::GossipPubSub;
using GossipPubSubTopic = sgns::ipfs_pubsub::GossipPubSubTopic;
namespace po = boost::program_options;
int portNumber = 0;
int runDurationSec = 0;
int numberOfClients = 0;
std::string multiAddress;
std::string topicName;
po::options_description desc("Input arguments:");
try
{
desc.add_options()
("help,h", "print help")
("port", po::value<int>(&portNumber)->default_value(33123), "Port number")
("duration", po::value<int>(&runDurationSec)->default_value(30), "Run duration in seconds")
("address", po::value<std::string>(&multiAddress), "Server address")
("topic", po::value<std::string>(&topicName)->default_value("globaldb-example"), "Topic name")
("clients", po::value<int>(&numberOfClients)->default_value(1), "Number of clients")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (multiAddress.empty())
{
std::cout << "Please, provide an address of the server" << "\n\n";
std::cout << desc << "\n";
return EXIT_FAILURE;
}
if (vm.count("help"))
{
std::cout << desc << "\n";
return EXIT_FAILURE;
}
}
catch (std::exception& e)
{
std::cerr << "Error parsing arguments: " << e.what() << "\n";
std::cout << desc << "\n";
return EXIT_FAILURE;
}
auto run_duration = std::chrono::seconds(runDurationSec);
const std::string logger_config(R"(
# ----------------
sinks:
- name: console
type: console
color: true
groups:
- name: echo_client
sink: console
level: info
children:
- name: libp2p
- name: Gossip
# ----------------
)");
// prepare log system
auto logging_system = std::make_shared<soralog::LoggingSystem>(
std::make_shared<soralog::ConfiguratorFromYAML>(
// Original LibP2P logging config
std::make_shared<libp2p::log::Configurator>(),
// Additional logging config for application
logger_config));
logging_system->configure();
libp2p::log::setLoggingSystem(logging_system);
// Create pubsub gossip node
auto pubsub = std::make_shared<GossipPubSub>();
pubsub->Start(portNumber, { multiAddress });
auto pubsTopic = pubsub->Subscribe(topicName, [&](boost::optional<const GossipPubSub::Message&> message)
{
if (message)
{
std::string strMessage(reinterpret_cast<const char*>(message->data.data()), message->data.size());
std::cout << strMessage << std::endl;
//pubsub->Publish(topicName, std::vector<uint8_t>(message.begin(), message.end()));
}
});
pubsTopic.wait();
// create a default Host via an injector
auto injector = libp2p::injector::makeHostInjector<BOOST_DI_CFG>();
// create io_context - in fact, thing, which allows us to execute async
// operations
auto context = injector.create<std::shared_ptr<boost::asio::io_context>>();
// run the IO context
context->run_for(run_duration);
// Wait for message transmitting
std::this_thread::sleep_for(run_duration);
}
|
#include <gsl/gsl_sf_bessel.h>
#include <stdio.h>
/**
* The example program from the GSL documentation
* http://www.gnu.org/software/gsl/doc/html/usage.html#an-example-program
*/
int main() {
double x = 5.0;
double y = gsl_sf_bessel_J0 (x);
printf ("J0(%g) = %.18e\n", x, y);
return 0;
}
|
(*************************************************************************)
(** A simple, typed language in Coq. *)
(*************************************************************************)
(** An interactive tutorial on developing programming language metatheory.
This file uses the language of PFPL Ch. 4 (called E) to demonstrate the
locally nameless representation of lambda terms and cofinite
quantification in judgments.
This tutorial concentrates on "how" to formalize languages; for more
details about "why" we use this style of development see: "Engineering
Formal Metatheory", Aydemir, Chargu'eraud, Pierce, Pollack, Weirich. POPL
2008.
Tutorial author: Stephanie Weirich Acknowledgement: based on a tutorial by
Brian Aydemir and Stephanie Weirich, with help from Aaron Bohannon, Nate
Foster, Benjamin Pierce, Jeffrey Vaughan, Dimitrios Vytiniotis, and Steve
Zdancewic. Adapted from code by Arthur Chargu'eraud.
*)
(*************************************************************************)
(** Background
The tutorial starts gently and assumes only general knowledge of
functional programming or programming language metatheory. It includes
deeper explorations (marked below as Challenge Problems) suitable for
those who have previously studied Software Foundations
(https://www.cis.upenn.edu/~bcpierce/sf/current/toc.html). If you are
new to Coq, you should prove the challenge problems on paper as their
proof scripts require more tactics than are presented here.
*)
(*************************************************************************)
(** First, we import a number of definitions from the Metatheory library (see
Metatheory.v). This library is available from
https://github.com/plclub/metalib.
The following command makes those definitions available in the rest of
this file. This command will only succeed if you have already run "make"
in the tutorial directory to compile the Metatheory library.
*)
Require Import Metalib.Metatheory.
(* Some examples require strings, so we also include those. *)
Require Import Strings.String.
(*************************************************************************)
(** * Syntax of E *)
(*************************************************************************)
(** The concrete syntax of E looks something like this:
Typ tau ::= num
string
Exp e ::= x variable
n numeral
"s" string
e1 + e2 addition
e1 * e2 multiplication
e1 ^ e2 concatenation
len (e) length
let x be e1 in e2 definition
We use a locally nameless representation, where bound variables are
represented as natural numbers (de Bruijn indices) and free variables are
represented as [atom]s. The type [atom], defined in the MetatheoryAtom
library, represents names. Equality on names is decidable
([eq_atom_dec]), and it is possible to generate an atom fresh for any
given finite set of atoms ([atom_fresh]).
*)
Inductive typ : Set :=
| typ_num : typ
| typ_string : typ.
(* binary operators. *)
Inductive op : Set :=
| plus
| times
| cat.
(* expressions of E *)
Inductive exp : Set :=
(* bound and free variables *)
| exp_bvar : nat -> exp
| exp_fvar : atom -> exp
(* constants *)
| exp_num : nat -> exp
| exp_str : string -> exp
(* binary operators *)
| exp_op : op -> exp -> exp -> exp
(* skip length *)
(* let expressions *)
| exp_let : exp -> exp -> exp.
(** For example, we can encode the expression
"let x be y + 1 in x" as below.
Because "y" is free variable in this term, we need to assume an
atom for this name.
*)
Parameter Y : atom.
Definition demo_rep1 :=
exp_let (exp_op plus (exp_fvar Y) (exp_num 1)) (exp_bvar 0).
(** Below is another example: the encoding of
"let x be 1 in let y be 2 in x + y"
*)
Definition demo_rep2 :=
exp_let (exp_num 1) (exp_let (exp_num 2) (exp_op plus (exp_bvar 1) (exp_bvar 0))).
(** *** Exercise [defns]
Uncomment and then complete the definitions of the following
terms using the locally nameless representation.
"one" : let x be let y be 1 in y in x
"two" : let x be 1 in let y be x + 1 in y
"three" : < make up your own >
*)
(** <<
Definition one :=
(* FILL IN HERE *)
Definition two :=
(* FILL IN HERE *)
Definition three :=
(* FILL IN HERE *)
>> *)
(** There are two important advantages of the locally nameless
representation:
- Alpha-equivalent terms have a unique representation.
We're always working up to alpha-equivalence.
- Operations such as free variable substitution and free
variable calculation have simple recursive definitions
(and therefore are simple to reason about).
Weighed against these advantages are two drawbacks:
- The [exp] datatype admits terms, such as
[let (exp_bvar 3) (exp_bvar 3)], where
indices are unbound.
A term is called "locally closed" when it contains
no unbound indices.
- We must define *both* bound variable & free variable
substitution and reason about how these operations
interact with each other.
*)
(*************************************************************************)
(** * Substitution *)
(*************************************************************************)
(** Substitution replaces a free variable with a term. The definition
below is simple for two reasons:
- Because bound variables are represented using indices, there
is no need to worry about variable capture.
- We assume that the term being substituted in is locally
closed. Thus, there is no need to shift indices when
passing under a binder.
*)
Fixpoint subst (z : atom) (u : exp) (e : exp)
{struct e} : exp :=
match e with
| exp_bvar i => e
| exp_fvar x => if x == z then u else e
| exp_num _ => e
| exp_str _ => e
| exp_let e1 e2 => exp_let (subst z u e1) (subst z u e2)
| exp_op o e1 e2 => exp_op o (subst z u e1) (subst z u e2)
end.
(** The [Fixpoint] keyword defines a Coq function. As all functions
in Coq must be total. The annotation [{struct e}] indicates the
termination metric---all recursive calls in this definition are
made to arguments that are structurally smaller than [e].
Note also that subst uses the notation [x == z] for decidable atom
equality. This notation is defined in the Metatheory library.
We define a notation for free variable substitution that mimics
standard mathematical notation.
*)
Notation "[ z ~> u ] e" := (subst z u e) (at level 68).
(** To demonstrate how free variable substitution works, we need to
reason about atom equality.
*)
Parameter Z : atom.
Check (Y == Z).
(** The decidable atom equality function returns a sum. If the two
atoms are equal, the left branch of the sum is returned, carrying
a proof of the proposition that the atoms are equal. If they are
not equal, the right branch includes a proof of the disequality.
The demo below uses three new tactics:
- The tactic [simpl] reduces a Coq expression to its normal
form.
- The tactic [destruct (Y==Y)] considers the two possible
results of the equality test.
- The tactic [Case] marks cases in the proof script.
It takes any string as its argument, and puts that string in
the hypothesis list until the case is finished.
*)
Lemma demo_subst1:
[Y ~> exp_fvar Z] (exp_let (exp_num 1) (exp_op plus (exp_bvar 0) (exp_fvar Y)))
= (exp_let (exp_num 1) (exp_op plus (exp_bvar 0) (exp_fvar Z))).
Proof.
simpl.
destruct (Y==Y).
- auto.
- destruct n. auto.
Qed.
(** *** Exercise [subst_eq_var]
We can use almost the same proof script as above to state how substitution
works in the variable case. Try it on your own. *)
Lemma subst_eq_var: forall (x : atom) u,
[x ~> u](exp_fvar x) = u.
Proof.
(* EXERCISE *) Admitted.
Lemma subst_neq_var : forall (x y : atom) u,
y <> x -> [x ~> u](exp_fvar y) = exp_fvar y.
Proof.
(* EXERCISE *) Admitted.
(*************************************************************************)
(** * Free variables *)
(*************************************************************************)
(** The function [fv], defined below, calculates the set of free
variables in an expression. Because we are using a locally
nameless representation, where bound variables are represented as
indices, any name we see is a free variable of a term.
*)
Fixpoint fv (e : exp) {struct e} : atoms :=
match e with
| exp_fvar x => singleton x
| exp_let e1 e2 => fv e1 `union` fv e2
| exp_op o e1 e2 => fv e1 `union` fv e2
| _ => empty
end.
(** The type [atoms] represents a finite set of elements of type
[atom]. The notation for infix union is defined in the Metatheory
library.
*)
(* Demo [f_equal]
The tactic [f_equal] converts a goal of the form [f e1 = f e1'] in
to one of the form [e1 = e1'], and similarly for [f e1 e2 = f e1'
e2'], etc.
*)
Lemma f_equal_demo : forall e1 e2, e1 = e2 -> fv e1 = fv e2.
Proof.
intros e1 e2 EQ.
f_equal.
assumption.
Qed.
(* Demo [fsetdec]
The tactic [fsetdec] solves a certain class of propositions
involving finite sets. See the documentation in [FSetWeakDecide]
for a full specification.
*)
Lemma fsetdec_demo : forall (x :atom) (S : atoms),
x `in` (singleton x `union` S).
Proof.
fsetdec.
Qed.
(** Demo [subst_fresh]
To show the ease of reasoning with these definitions, we will prove a
standard result from lambda calculus: if a variable does not
appear free in a term, then substituting for it has no effect.
HINTS: Prove this lemma by induction on [e].
- You will need to use [simpl] in many cases. You can [simpl]
everything everywhere (including hypotheses) with the
pattern [simpl in *].
- Part of this proof includes a false assumption about free
variables. Destructing this hypothesis produces a goal about
finite set membership that is solvable by [fsetdec].
*)
Lemma subst_fresh : forall (x : atom) e u,
x `notin` fv e -> [x ~> u] e = e.
Proof.
intros x e u H.
unfold not in H.
induction e.
- simpl. reflexivity.
- simpl. destruct (a == x).
+ rewrite e in H. simpl in H. fsetdec.
+ auto.
- simpl. auto.
- simpl. auto.
- simpl. f_equal. apply IHe1. simpl in H. fsetdec.
apply IHe2. simpl in H. fsetdec.
- simpl. f_equal. apply IHe1. simpl in H. fsetdec.
apply IHe2. simpl in H. fsetdec.
Qed.
(* FILL IN HERE (and delete "Admitted") *)
(* Take-home Demo: Prove that free variables are not introduced by
substitution.
This proof actually is very automatable ([simpl in *; auto.] takes
care of all but the fvar case), but the explicit proof below
demonstrates two parts of the finite set library. These two parts
are the tactic [destruct_notin] and the lemma [notin_union], both
defined in the module [FSetWeakNotin].
Before stepping through this proof, you should go to that module
to read about those definitions and see what other finite set
reasoning is available.
*)
Lemma subst_notin_fv : forall x y u e,
x `notin` fv e -> x `notin` fv u ->
x `notin` fv ([y ~> u]e).
Proof.
intros x y u e Fr1 Fr2.
induction e; simpl in *.
- assumption.
- destruct (a == y).
+ assumption.
+ simpl. assumption.
- assumption.
- assumption.
- destruct_notin.
apply notin_union. apply IHe1. assumption. apply IHe2. assumption.
- destruct_notin.
apply notin_union. apply IHe1. assumption. apply IHe2. assumption.
Qed.
(*************************************************************************)
(** * Opening *)
(*************************************************************************)
(** Opening replaces an index with a term. It corresponds to informal
substitution for a bound variable, such as in a rule for beta
reduction. Note that only "dangling" indices (those that do not
refer to any abstraction) can be opened. Opening has no effect
for terms that are locally closed.
Natural numbers are just an inductive datatype with two
constructors: [O] (as in the letter 'oh', not 'zero') and [S],
defined in Coq.Init.Datatypes. Coq allows literal natural numbers
to be written using standard decimal notation, e.g., 0, 1, 2, etc.
The notation [k == i] is the decidable equality function for
natural numbers (cf. [Coq.Peano_dec.eq_nat_dec]). This notation
is defined in the Metatheory library.
We make several simplifying assumptions in defining [open_rec].
First, we assume that the argument [u] is locally closed. This
assumption simplifies the implementation since we do not need to
shift indices in [u] when passing under a binder. Second, we
assume that this function is initially called with index zero and
that zero is the only unbound index in the term. This eliminates
the need to possibly subtract one in the case of indices.
There is no need to worry about variable capture because bound
variables are indices.
*)
Fixpoint open_rec (k : nat) (u : exp)(e : exp)
{struct e} : exp :=
match e with
| exp_bvar i => if k == i then u else (exp_bvar i)
| exp_let e1 e2 => exp_let (open_rec k u e1) (open_rec (S k) u e2)
| exp_op o e1 e2 => exp_op o (open_rec k u e1) (open_rec k u e2)
| _ => e
end.
(** Many common applications of opening replace index zero with an
expression or variable. The following definition provides a
convenient shorthand for such uses. Note that the order of
arguments is switched relative to the definition above. For
example, [(open e x)] can be read as "substitute the variable [x]
for index [0] in [e]" and "open [e] with the variable [x]."
Recall that the coercions above let us write [x] in place of
[(exp_fvar x)].
*)
Definition open e u := open_rec 0 u e.
(** This next demo shows the operation of [open] on the term
"let x be "a" in __ + x" where we replace the __ with Y.
*)
Lemma demo_open :
open (exp_let (exp_str "a") (exp_op plus (exp_bvar 1) (exp_bvar 0))) (exp_fvar Y) =
(exp_let (exp_str "a") (exp_op plus (exp_fvar Y) (exp_bvar 0))).
Proof.
unfold open. simpl. auto.
Qed.
(* Fill in here *)
(* HINT for demo: To show the equality of the two sides below, use the
tactics [unfold], which replaces a definition with its RHS and
reduces it to head form, and [simpl], which reduces the term the
rest of the way. Then finish up with [auto]. *)
(*************************************************************************)
(* *)
(* Stretch break (one week) *)
(* *)
(*************************************************************************)
(*************************************************************************)
(** * Local closure *)
(*************************************************************************)
(** Recall that [exp] admits terms that contain unbound indices. We
say that a term is locally closed when no indices appearing in it
are unbound. The proposition [lc_e e] holds when an expression [e]
is locally closed.
*)
Inductive lc_e : exp -> Prop :=
| lc_e_var : forall (x:atom),
lc_e (exp_fvar x)
| lc_e_num : forall n, lc_e (exp_num n)
| lc_e_str : forall s, lc_e (exp_str s)
| lc_e_let : forall (x : atom) e1 e2,
x `notin` fv e2 -> lc_e e1 -> lc_e (open e2 (exp_fvar x)) ->
lc_e (exp_let e1 e2)
| lc_e_app : forall e1 e2 op,
lc_e e1 -> lc_e e2 ->
lc_e (exp_op op e1 e2).
Hint Constructors lc_e.
Check lc_e_ind.
(* The primary use of the local closure proposition is to support induction on
the syntax of abstract binding trees, such as discussed in Chapter 1.2 of
PFPL. The induction principle for type [exp] won't do: it requires
reasoning about terms with dangling indices. The local closure predicate
ensures that each case of an inductive proof need only reason about
locally closed terms by replacing all bound variables with free variables
in its definition.
Further, when we do induction on the abstract syntax of expressions with
binding we need to be sure that we have a strong enough induction
principle, similar to the "structural induction modulo fresh renaming"
in PFPL.
Unfortunately, the lc_e definition above doesn't stack up.
*)
Check lc_e.
(*************************************************************************)
(** Cofinite quantification *)
(*************************************************************************)
(* In the next example, we will reexamine the definition of
local closure in the [let] case.
The lemma [subst_lc] says that local closure is preserved by
substitution. Let's start working through this proof.
*)
Lemma subst_lc_0 : forall (x : atom) u e,
lc_e e ->
lc_e u ->
lc_e ([x ~> u] e).
Proof.
intros x u e He Hu.
induction He.
- simpl.
destruct (x0 == x).
auto.
auto.
- simpl. auto.
- simpl. auto.
- simpl.
Print lc_e_let.
apply lc_e_let with (x:=x0).
apply subst_notin_fv.
auto.
Admitted.
(** Here we are stuck. We don't know that [x0] is not in the free
variables of [u].
The solution is to change the *definition* of local closure so
that we get a different induction principle. Currently, in the
[lc_let] case, we show that an abstraction is locally closed by
showing that the body is locally closed after it has been opened
with one particular variable.
<<
| lc_let : forall (x : atom) e1 e2,
lc_e e1 ->
x `notin` fv e2 ->
lc_e (open e2 x) ->
lc_e (exp_let e1 e2)
>>
Therefore, our induction hypothesis in this case only applies to
that variable. From the hypothesis list in the [lc_let] case:
x0 : atom,
IHHe2 : lc_e ([x ~> u]open e2 (exp_fvar x0))
The problem is that we don't have any assumptions about [x0]. It
could very well be equal to [x].
A stronger induction principle provides an IH that applies to many
variables. In that case, we could pick one that is "fresh enough".
To do so, we need to revise the above definition of lc and replace
the type of lc_let with this one:
<<
| lc_let : forall L e1 e2,
lc e1 ->
(forall x, x `notin` L -> lc (open e2 (exp_fvar x))) ->
lc (exp_let e1 e2)
>>
This rule says that to show that an abstraction is locally closed,
we need to show that the body is closed, after it has been opened by
any atom [x], *except* those in some set [L]. With this rule, the IH
in this proof is now:
H0 : forall x0 : atom, x0 `notin` L -> lc ([x ~> u]open e2 (exp_fvar x0)
Below, lc is the local closure judgment revised to use this new
rule in the abs case. We call this "cofinite quantification"
because the IH applies to an infinite number of atoms [x0], except
those in some finite set [L].
Changing the rule in this way does not change what terms are locally
closed. (For more details about cofinite-quantification see:
"Engineering Formal Metatheory", Aydemir, Chargu'eraud, Pierce,
Pollack, Weirich. POPL 2008.)
*)
Inductive lc : exp -> Prop :=
| lc_var : forall (x:atom), lc (exp_fvar x)
| lc_num : forall n : nat, lc (exp_num n)
| lc_str : forall s : string, lc (exp_str s)
| lc_let : forall (L:atoms) (e1 e2 : exp),
lc e1
-> (forall x, x `notin` L -> lc (open e2 (exp_fvar x)))
-> lc (exp_let e1 e2)
| lc_op : forall (e1 e2 : exp) (op : op),
lc e1
-> lc e2
-> lc (exp_op op e1 e2).
Hint Constructors lc.
(* Demo [subst_lc]:
Once we have changed the definition of lc, we can make progress on
the proof of subst_lc.
HINT: apply lc_let with cofinite set (L `union` singleton x).
This gives us an atom x0, and a hypothesis that
x0 is fresh for both L and x.
*)
Lemma subst_lc_1 : forall (x : atom) u e,
lc e ->
lc u ->
lc ([x ~> u] e).
Proof.
intros x u e He Hu.
induction He.
- simpl.
destruct (x0 == x).
auto.
auto.
- simpl. auto.
- simpl. auto.
- simpl.
Check lc_let.
apply lc_let with (L:= L). auto.
(* DEMO *) Admitted.
(* However, we get stuck here because we don't have any lemmas about the interaction between
subst and open. *)
(*************************************************************************)
(** Properties about basic operations *)
(*************************************************************************)
(** We also define a notation for [open_rec] to make stating some of
the properties simpler. However, we don't need to use open_rec
outside of this part of the tutorial so we make it a local
notation, confined to this section. *)
Section BasicOperations.
Notation Local "{ k ~> u } t" := (open_rec k u t) (at level 67).
(** The first property we would like to show is the analogue to
[subst_fresh]: index substitution has no effect for closed terms.
Here is an initial attempt at the proof.
*)
Lemma open_rec_lc_0 : forall k u e,
lc e ->
e = {k ~> u} e.
Proof.
intros k u e LC.
induction LC.
- simpl.
auto.
- simpl.
f_equal.
Admitted.
(** At this point there are two problems. Our goal is about
substitution for index [S k] in term [e], while our induction
hypothesis IHLC only tells use about index [k] in term [open e x].
To solve the first problem, we generalize our IH over all [k].
That way, when [k] is incremented in the [let] case, it will still
apply. Below, we use the tactic [generalize dependent] to
generalize over [k] before using induction.
*)
Lemma open_rec_lc_1 : forall k u e,
lc e ->
e = {k ~> u} e.
Proof.
intros k u e LC.
generalize dependent k.
induction LC.
- simpl. auto.
- simpl. auto.
- simpl. auto.
- simpl.
intro k.
f_equal. auto.
Admitted.
(** At this point we are still stuck because the IH concerns
[open e2 x] instead of [e2]. The result that we need is that if an
index substitution has no effect for an opened term, then it has
no effect for the raw term (as long as we are *not* substituting
for [0], hence [S k] below).
<<
open e x = {S k ~> u}(open e x) -> e = {S k ~> u} e
>>
In other words, expanding the definition of open:
<<
{0 ~> x}e = {S k ~> u}({0 ~> x} e) -> e = {S k ~> u} e
>>
Of course, to prove this result, we must generalize
[0] and [S k] to be any pair of inequal numbers to get a strong
enough induction hypothesis for the [let] case.
*)
Lemma open_rec_lc_core : forall e j v i u,
i <> j ->
{j ~> v} e = {i ~> u} ({j ~> v} e) ->
e = {i ~> u} e.
Proof.
induction e; intros j v i u Neq H; simpl in *.
- Case "exp_bvar".
destruct (j == n); destruct (i == n).
SCase "j = n = i".
subst n. destruct Neq. auto.
SCase "j = n, i <> n".
auto.
SCase "j <> n, i = n".
subst n. simpl in H.
destruct (i == i).
SSCase "i=i".
auto.
SSCase "i<>i".
destruct n. auto.
SCase "j <> n, i <> n".
auto.
- Case "exp_fvar". auto.
- Case "exp_num". auto.
- Case "exp_str". auto.
- Case "exp_op".
inversion H.
f_equal.
eapply IHe1; eauto.
eapply IHe2; eauto.
- Case "exp_let".
inversion H.
f_equal.
eapply IHe1; eauto.
apply IHe2 with (j := S j) (u := u) (i := S i) (v := v).
auto.
auto.
Qed.
(** Challenge Exercise [proof refactoring]
We've proven the above lemma very explicitly, so that you can step through
it slowly to see how it works. However, with automation, it is possible to
give a *much* shorter proof. Reprove this lemma on your own to see how
compact you can make it. *)
(** With the help of this lemma, we can complete the proof. *)
Lemma open_rec_lc : forall k u e,
lc e -> e = {k ~> u} e.
Proof.
intros k u e LC.
generalize dependent k.
induction LC.
- simpl.
auto.
- simpl. auto.
- simpl. auto.
- simpl.
intro k.
f_equal.
auto.
unfold open in *.
pick fresh x for L. (* tactic to choose a fresh x *)
apply open_rec_lc_core with
(i := S k) (j := 0) (u := u) (v := exp_fvar x).
auto.
auto.
- intro k.
simpl.
f_equal.
auto.
auto.
Qed.
(* Below are two more important properties of open and subst. *)
(** *** Exercise [subst_open_rec] *)
(** The next lemma demonstrates that free variable substitution
distributes over index substitution.
The proof of this lemma is by straightforward induction over
[e1]. When [e1] is a free variable, we need to appeal to
[open_rec_lc], proved above.
*)
Lemma subst_open_rec : forall e1 e2 u (x : atom) k,
lc u ->
[x ~> u] ({k ~> e2} e1) = {k ~> [x ~> u] e2} ([x ~> u] e1).
Proof.
(* EXERCISE *) Admitted.
(** *** Exercise [subst_open] *)
(** The lemma above is most often used with [k = 0].
Therefore, it simplifies matters
to define the following useful corollary.
HINT: Do not use induction.
Rewrite with [subst_open_rec].
*)
Lemma subst_open : forall (x : atom) u e1 e2,
lc u ->
open ([x ~> u] e1) ([x ~> u] e2) = [x ~> u] (open e1 e2).
Proof.
(* EXERCISE *) Admitted.
(** *** Exercise [subst_intro] *)
(** This lemma states that opening can be replaced with variable
opening and substitution.
HINT: Prove by induction on [e], first generalizing the
argument to [open_rec] by using the [generalize] tactic, e.g.,
[generalize 0].
*)
Lemma subst_intro : forall (x : atom) u e,
x `notin` (fv e) ->
open e u = [x ~> u](open e (exp_fvar x)).
Proof.
(* EXERCISE *) Admitted.
(** Challenge Exercise [fv_open]
We must show how open interacts with all functions defined over
expressions. We just saw an instance with substitution --- but we must
also say something about 'fv'.
Below, try to prove a similar property about the interaction between fv
and open. Note that we don't know for sure that the bound variable
actually appears in the term e1, so we get a subset, not an equivalence.
This exercise is challenging (more so than some of the other challenges
below), and fsetdec won't be able to help you right off the bat. You'll
need to generalize the induction hypothesis, break the problem down a bit
first and give fsetdec some extra information.
HINTS: Generalize the induction hypothsis Do some forward reasoning with
the "pose" tactic. Check AtomSetProperties.union_subset_3.
*)
Lemma fv_open : forall e1 e2,
fv (open e1 e2) [<=] fv e2 \u fv e1.
Proof.
(* CHALLENGE EXERCISE *) Admitted.
End BasicOperations.
(*************************************************************************)
(** * subst_lc *)
(*************************************************************************)
(** Finally, with subst_open, we can finally finish the proof of subst_lc. *)
Lemma subst_lc : forall (x : atom) u e,
lc e ->
lc u ->
lc ([x ~> u] e).
Proof.
intros x u e He Hu.
induction He.
- simpl.
destruct (x0 == x).
auto.
auto.
- simpl. auto.
- simpl. auto.
- simpl.
Check subst_open.
apply lc_let with (L := L \u {{x}} ).
auto.
intros x0 Fr.
replace (exp_fvar x0) with ([x ~> u] exp_fvar x0).
rewrite subst_open.
apply H0. auto.
auto.
simpl. destruct (x0 == x). subst. fsetdec.
auto.
- simpl. auto.
Qed.
(*************************************************************************)
(** * Induction principles for binding trees *)
(*************************************************************************)
Check lc_ind.
(* Going deeper:
Compare the induction principle with that of PFPL (specialized to the abt for E).
An Abstract Binding Tree, such as E, is parameterized by X, a set of free variables that
can appear in an abt. For example,
the (free) variable x is a member of E [ {{x}} ] and
x + y is a member of E [ {{ x }} \u {{ y }} ].
For a given term, indexed by a given set of free variables, the induction
principle modulo renaming reads:
To show a property P : forall X, E[X] -> Prop holds for an arbitrary
expression e in E[X] it suffices to show:
forall X x, x `in` X -> P X x
forall X n, P X n
forall X s, P X s
forall X x e1 e2,
P X e1 -> (forall x, such that x' notin X, P [X u {x'}] ([ x' / x ] e2))
-> P (let x be e1 in e2)
forall X e1 e2, P X e1 -> P X e2 -> P X (e1 `op` e2)
In other words, in the variable case, we need to show the property for
all variables that actually appear in the term (though often in the proof, this
set will be abstract).
In the let case, we need to show the property holds for the body of the
let expression for all arbitrary x' that do *not* appear in X.
When we use this induction principle in a proof,
we work with an arbitrary X. So in practice, this
induction principle looks like co-finite quantification.
*)
(*************************************************************************)
(* *)
(* Break *)
(* *)
(*************************************************************************)
(*************************************************************************)
(** * Typing environments *)
(*************************************************************************)
(** We represent environments as association lists (lists of pairs of
keys and values) whose keys are [atom]s.
*)
Notation env := (list (atom * typ)).
(** Environments bind [atom]s to [typ]s. We define an abbreviation [env] for
the type of these environments. Coq will print [list (atom * typ)] as
[env], and we can use [env] as a shorthand for writing [list (atom *
typ)]. Lists are defined in Coq's standard library, with the constructors
[nil] and [cons]. The list library includes the [::] notation for cons as
well as standard list operations such as append, map, and fold. The infix
operation "++" is list append. The Metatheory library extends this
reasoning by instantiating the AssocList library to provide support for
association lists whose keys are [atom]s. Everything in this library is
polymorphic over the type of objects bound in the environment. Look in
AssocList for additional details about the functions and predicates that
we mention below. *)
(** Environment equality *)
(** When reasoning about environments, we often need to talk about
bindings in the "middle" of an environment. Therefore, it is common
for lemmas and definitions to use list append in their statements.
Unfortunately, list append is associative, so two Coq expressions may
denote the same environment even though they are not equal.
The tactic [simpl_env] reassociates all concatenations of
environments to the right.
*)
Lemma append_assoc_demo : forall (E0 E1 E2 E3:env),
E0 ++ (E1 ++ E2) ++ E3 = E0 ++ E1 ++ E2 ++ E3.
Proof.
intros.
auto. (* Does nothing. *)
simpl_env.
reflexivity.
Qed.
(** To make environments easy to read, instead of building them from
[nil] and [cons], we prefer to build them from the following
components:
- [nil]: The empty list.
- [one]: Lists consisting of exactly one item.
- [++]: List append.
Furthermore, we introduce compact notation for one (singleton lists):
[(x ~ T)] is the same as [one (x, T)].
*)
(** The simpl_env tactic actually puts lists built from only nil, one
and [++] into a "normal form". This process reassociates all appends
to the right, removes extraneous nils converts cons to singleton
lists with an append.
*)
Lemma simpl_env_demo : forall (x y:atom) (T1 T2:typ) (E F:env),
((x ~ T1) ++ nil) ++ (y,T2) :: (nil ++ E) ++ F =
(x ~ T1) ++ (y ~ T2) ++ E ++ F.
Proof.
intros.
(* simpl_env puts the left side into the normal form. *)
simpl_env.
reflexivity.
Qed.
(** Note that the [simpl] tactic doesn't produce the "normal form" for
environments. It should always be followed up with [simpl_env].
Furthermore, to convert an environment to any equivalent form
other than the normal form (perhaps to apply a lemma) use the
tactic [rewrite_env].
*)
Lemma rewrite_env_demo : forall (x:atom) (T:typ) P,
(forall E, P ((x,T):: E) -> True) ->
P (x ~ T) ->
True.
Proof.
intros x T P H.
(* apply H. fails here. *)
rewrite_env ((x,T) :: nil).
apply H.
Qed.
(** Environment operations. *)
(** The ternary predicate [binds] holds when a given binding is
present somewhere in an environment. The metatheory
library adds operations for binds to the [auto] database.
*)
Lemma binds_demo : forall (x:atom) (T:typ) (E F:env),
binds x T (E ++ (x ~ T) ++ F).
Proof.
auto.
Defined.
Print binds_demo.
(** Note that binds doesn't care if multiple bindings are present
or anything about the order of the bindings. *)
Lemma binds_demo_2 : forall (x:atom) (T:typ) (U:typ) (E F:env),
binds x T (E ++ (x ~ U) ++ (x ~ T) ++ F).
Proof.
auto.
Qed.
(** The function [dom] computes the domain of an environment,
returning a finite set of [atom]s. Note that we cannot use Coq's
equality for finite sets, we must instead use a defined relation
[=] for atom set equality.
*)
Lemma dom_demo : forall (x y : atom) (T : typ),
dom (x ~ T) [=] singleton x.
Proof.
auto.
Qed.
(** The unary predicate [uniq] holds when each atom is bound at most
once in an environment.
*)
Lemma uniq_demo : forall (x y : atom) (T : typ),
x <> y -> uniq ((x ~ T) ++ (y ~ T)).
Proof.
auto.
Qed.
(*************************************************************************)
(** * Tactic support for freshness *)
(*************************************************************************)
(** When picking a fresh atom or applying a rule that uses cofinite
quantification, choosing a set of atoms to be fresh for can be
tedious. In practice, it is simpler to use a tactic to choose the
set to be as large as possible.
The tactic [gather_atoms] is used to collect together all the
atoms in the context. It relies on an auxiliary tactic,
[gather_atoms_with] (from MetatheoryAtom), which maps a function
that returns a finite set of atoms over all hypotheses with the
appropriate type.
*)
Ltac gather_atoms ::=
let A := gather_atoms_with (fun x : atoms => x) in
let B := gather_atoms_with (fun x : atom => singleton x) in
let C := gather_atoms_with (fun x : list (atom * typ) => dom x) in
let D := gather_atoms_with (fun x : exp => fv x) in
constr:(A `union` B `union` C `union` D).
(** A number of other, useful tactics are defined by the Metatheory
library, and each depends on [gather_atoms]. By redefining
[gather_atoms], denoted by the [::=] in its definition below, we
automatically update these tactics so that they use the proper
notion of "all atoms in the context."
For example, the tactic [(pick fresh x)] chooses an atom fresh for
"everything" in the context. It is the same as [(pick fresh x for
L)], except where [L] has been computed by [gather_atoms].
The tactic [(pick fresh x and apply H)] applies a rule [H] that is
defined using cofinite quantification. It automatically
instantiates the finite set of atoms to exclude using
[gather_atoms].
*)
(** *** Example
Below, we reprove [subst_lc] using [(pick fresh and apply)].
Step through the proof below to see how [(pick fresh and apply)]
works.
*)
Lemma subst_lc_alternate_proof : forall (x : atom) u e,
lc e ->
lc u ->
lc ([x ~> u] e).
Proof.
intros x u e He Hu.
induction He; simpl; auto.
- destruct (x0 == x).
auto.
auto.
- (* lc_let with (L := L \u fv e1 \u fv e2 \u fv u) *)
pick fresh y and apply lc_let. auto.
(* Here, take note of the hypothesis [Fr]. *)
rewrite <- (subst_neq_var x y u).
rewrite subst_open. auto. auto. auto.
Qed.
(** Challenge Exercise [subst_lc_inverse]
Try it yourself, for the following
"inverse" to subst_lc theorem.
Hint: do this proof by induction on the local closure judgement. You'll
need to generalize the theorem statement to get it in the right
form. You'll also need to [destruct] e in each case to see what it could
have been before the substitution.
*)
Lemma subst_lc_inverse : forall x u e, lc ([x ~> u] e) -> lc u -> lc e.
(* CHALLENGE EXERCISE *) Admitted.
(*************************************************************************)
(** * Typing relation (Section 4.2) *)
(*************************************************************************)
(** The definition of the typing relation is straightforward. In
order to ensure that the relation holds for only well-formed
environments, we check in the [typing_var] case that the
environment is [uniq]. The structure of typing derivations
implicitly ensures that the relation holds only for locally closed
expressions. Finally, note the use of cofinite quantification in
the [typing_let] case.
*)
Inductive typing : env -> exp -> typ -> Prop :=
| typing_var : forall E (x : atom) T,
uniq E ->
binds x T E ->
typing E (exp_fvar x) T
| typing_str : forall s E,
uniq E ->
typing E (exp_str s) typ_string
| typing_num : forall i E,
uniq E ->
typing E (exp_num i) typ_num
| typing_let : forall (L : atoms) E e1 e2 T1 T2,
typing E e1 T1 ->
(forall (x:atom), x `notin` L ->
typing ((x ~ T1) ++ E) (open e2 (exp_fvar x)) T2) ->
typing E (exp_let e1 e2) T2
| typing_plus : forall E e1 e2,
typing E e1 typ_num ->
typing E e2 typ_num ->
typing E (exp_op plus e1 e2) typ_num.
(* NOTE: no typing rules for times or cat. EXERCISE: You add them and
extend all proofs! *)
(** We add the constructors of the typing relation as hints to be used
by the [auto] and [eauto] tactics.
*)
Hint Constructors typing.
(* Note that the typing relation *only* includes locally closed terms. *)
Lemma typing_lc : forall G e T, typing G e T -> lc e.
Proof.
intros. induction H; eauto.
Qed.
(*************************************************************************)
(** * Unicity of Typing *)
(*************************************************************************)
(** *** Exercise [unicity]
As PFPL Lemma 4.1 shows, there is only one type for each given term. We can
state that property in Coq using the following lemma. The key part of this
proof is the lemma [binds_unique] from the metatheory library. This lemma
states that there is only one type for a particular variable in a
uniq context.
*)
Check binds_unique.
Lemma unicity : forall G e t1, typing G e t1 -> forall t2, typing G e t2 -> t1 = t2.
(* EXERCISE *) Admitted.
(*************************************************************************)
(** * Weakening (Lemma 4.3) *)
(*************************************************************************)
(** Weakening states that if an expression is typeable in some
environment, then it is typeable in any well-formed extension of
that environment. This property is needed to prove the
substitution lemma.
As stated below (and in PFPL), this lemma is not directly proveable. The
natural way to try proving this lemma proceeds by induction on the
typing derivation for [e].
*)
Lemma typing_weakening_0 : forall E F e T,
typing E e T ->
uniq (F ++ E) ->
typing (F ++ E) e T.
Proof.
intros E F e T H J.
induction H; eauto.
- Case "typing_let".
pick fresh x and apply typing_let.
eauto.
(* ... stuck here ... *)
Admitted.
(** We are stuck in the [typing_let] case because the induction
hypothesis [H0] applies only when we weaken the environment at its
head. In this case, however, we need to weaken the environment in
the middle; compare the conclusion at the point where we're stuck
to the hypothesis [H], which comes from the given typing derivation.
We can obtain a more useful induction hypothesis by changing the
statement to insert new bindings into the middle of the
environment, instead of at the head. However, the proof still
gets stuck, as can be seen by examining each of the cases in
the proof below.
Note: To view subgoal n in a proof, use the command "[Show n]".
To work on subgoal n instead of the first one, use the command
"[Focus n]".
*)
Lemma typing_weakening_strengthened_0 : forall (E F G : env) e T,
typing (G ++ E) e T ->
uniq (G ++ F ++ E) ->
typing (G ++ F ++ E) e T.
Proof.
intros E F G e T H J.
induction H.
Case "typing_var".
(* The E0 looks strange in the [typing_var] case. *)
Focus 4.
Case "typing_let".
(* The [typing_let] case still does not have a strong enough IH. *)
Admitted.
(** The hypotheses in the [typing_var] case include an environment
[E0] that that has no relation to what we need to prove. The
missing fact we need is that [E0 = (G ++ E)].
The problem here arises from the fact that Coq's [induction]
tactic let's us only prove something about all typing derivations.
While it's clear to us that weakening applies to all typing
derivations, it's not clear to Coq, because the environment is
written using concatenation. The [induction] tactic expects that
all arguments to a judgement are variables. So we see [E0] in the
proof instead of [(G ++ E)].
The solution is to restate the lemma. For example, we can prove
<<
forall E F E' e T, typing E' e T ->
forall G, E' = G ++ E -> uniq (G ++ F ++ E) -> typing (G ++ F ++ E) e T.
>>
The equality gets around the problem with Coq's [induction]
tactic. The placement of the [(forall G)] quantifier gives us a
sufficiently strong induction hypothesis in the [typing_let] case.
However, we prefer not to state the lemma in the way shown above,
since it is not as readable as the original statement. Instead,
we use a tactic to introduce the equality within the proof itself.
The tactic [(remember t as t')] replaces an object [t] with the
identifier [t'] everywhere in the goal and introduces an equality
[t' = t] into the context. It is often combined with [generalize
dependent], as illustrated below.
*)
(** *** Exercise [typing_weakening_strengthened]
See how we use [remember as] in the proof below for weakening.
Then, complete the proof below.
HINTS:
- The [typing_var] case follows from [binds_weaken], the
weakening lemma for the [binds] relation.
- The [typing_let] case follows from the induction
hypothesis, but the [apply] tactic may be unable to unify
things as you might expect.
-- Recall the [pick fresh and apply] tactic.
-- In order to apply the induction hypothesis, use
[rewrite_env] to reassociate the list operations.
-- After applying the induction hypothesis, use
[simpl_env] to use [uniq_push].
-- Here, use [auto] to solve facts about finite sets of
atoms, since it will simplify the [dom] function behind
the scenes. [fsetdec] does not work with the [dom]
function.
- The [typing_plus] case follows directly from the induction
hypotheses.
*)
Lemma typing_weakening_strengthened : forall (E F G : env) e T,
typing (G ++ E) e T ->
uniq (G ++ F ++ E) ->
typing (G ++ F ++ E) e T.
Proof.
intros E F G e T H.
remember (G ++ E) as E'.
generalize dependent G.
induction H; intros G Eq Uniq; subst.
Check binds_weaken.
(* EXERCISE *) Admitted.
(** *** Example
We can now prove our original statement of weakening. The only
interesting step is the use of the rewrite_env tactic.
*)
Lemma typing_weakening : forall (E F : env) e T,
typing E e T ->
uniq (F ++ E) ->
typing (F ++ E) e T.
Proof.
intros E F e T H J.
rewrite_env (nil ++ F ++ E).
apply typing_weakening_strengthened; auto.
Qed.
(**
NOTE: If we view typing contexts as ordered lists of typing assumptions, then
the type system shown in section 4.2 of PFPL does NOT satisfy the
weakening property. Why not?
*)
(*************************************************************************)
(** * Substitution *)
(*************************************************************************)
(** Having proved weakening, we can now prove the usual substitution
lemma, which we state both in the form we need and in the
strengthened form needed to make the proof go through.
<<
typing_subst_simple : forall E e u S T z,
typing ((z ~ S) ++ E) e T ->
typing E u S ->
typing E ([z ~> u] e) T
typing_subst : forall E F e u S T z,
typing (F ++ (z ~ S) ++ E) e T ->
typing E u S ->
typing (F ++ E) ([z ~> u] e) T
>>
The proof of the strengthened statement proceeds by induction on
the given typing derivation for [e]. The most involved case is
the one for variables; the others follow from the induction
hypotheses.
*)
(** *** Exercise [typing_subst_var_case]
Below, we state what needs to be proved in the [typing_var] case
of the substitution lemma. Fill in the proof.
Proof sketch: The proof proceeds by a case analysis on [(x == z)],
i.e., whether the two variables are the same or not.
- If [(x = z)], then we need to show [(typing (F ++ E) u T)].
This follows from the given typing derivation for [u] by
weakening and the fact that [T] must equal [S].
- If [(x <> z)], then we need to show [(typing (F ++ E) x T)].
This follows by the typing rule for variables.
HINTS: Lemmas [binds_mid_eq], [uniq_remove_mid],
and [binds_remove_mid] are useful.
*)
Lemma typing_subst_var_case : forall (E F : env) u S T (z x : atom),
binds x T (F ++ (z ~ S) ++ E) ->
uniq (F ++ (z ~ S) ++ E) ->
typing E u S ->
typing (F ++ E) ([z ~> u] (exp_fvar x)) T.
Proof.
intros E F u S T z x H J K.
simpl.
(* EXERCISE *) Admitted.
(** *** Note
The other two cases of the proof of the substitution lemma are
relatively straightforward. However, the case for [typing_let]
needs the fact that the typing relation holds only for
locally-closed expressions.
*)
(** *** Exercise [typing_subst]
Complete the proof of the substitution lemma. The proof proceeds
by induction on the typing derivation for [e]. The initial steps
should use [remember as] and [generalize dependent] in a manner
similar to the proof of weakening.
HINTS:
- Use the lemma proved above for the [typing_var] case.
- The [typing_let] case follows from the induction hypothesis.
-- Use [simpl] to simplify the substitution.
-- Recall the tactic [pick fresh and apply].
-- In order to use the induction hypothesis, use
[subst_open] to push the substitution under the
opening operation.
-- Recall the lemma [typing_to_lc] and the
[rewrite_env] and [simpl_env] tactics.
- The [typing_plus] case follows from the induction hypotheses.
Use [simpl] to simplify the substitution.
*)
Lemma typing_subst : forall (E F : env) e u S T (z : atom),
typing (F ++ (z ~ S) ++ E) e T ->
typing E u S ->
typing (F ++ E) ([z ~> u] e) T.
Proof.
intros E F e u S T z H.
remember (F ++ [(z, S)] ++ E) as G.
generalize dependent F.
generalize dependent S.
generalize dependent E.
induction H.
Focus 4.
intros. subst. simpl.
pick fresh x and apply typing_let.
eapply IHtyping. eauto. auto.
(* EXERCISE *) Admitted.
(** *** Exercise [typing_subst_simple]
Complete the proof of the substitution lemma stated in the form we
need it. The proof is similar to that of [typing_weakening].
HINT: You'll need to use [rewrite_env] to prepend [nil],
and [simpl_env] to simplify nil away.
*)
Lemma typing_subst_simple : forall (E : env) e u S T (z : atom),
typing ((z ~ S) ++ E) e T ->
typing E u S ->
typing E ([z ~> u] e) T.
Proof.
(* EXERCISE *) Admitted.
(*************************************************************************)
(** * Other structural properties *)
(*************************************************************************)
(* PFPL lists weakening and substitution, but there are two other important
structural properties of type systems: strengthening and exchange. *)
(* Challenge exercise [exchange]
The exchange lemma states that the order of bindings in the typing
context doesn't matter.
Hints:
- Don't forget to use the [remember as] tactic.
- The metalib tactic [solve_uniq] does what it claims.
- There are 4 subcases in the fvar case: x is in G1, x is x1 or x2 or x is in G2.
Access these four cases in succession using the lemma [binds_app_1].
- [SearchAbout binds.] to see lemmas available for reasoning about
bindings in the context.
- You'll need to rewrite_env to call the induction hypothesis in
the case for [exp_let].
*)
Lemma exchange : forall G1 G2 x1 x2 T1 T2 e T,
typing (G1 ++ (x1 ~ T1) ++ (x2 ~ T2) ++ G2) e T ->
typing (G1 ++ (x2 ~ T2) ++ (x1 ~ T1) ++ G2) e T.
Proof.
(* CHALLENGE EXERCISE *) Admitted.
(* Challenge exercise [strengthening]
Strengthening means that variables that are not actually used in
an expression can be removed from the typing context.
Hints:
- The metalib tactic [solve_uniq] does what it claims.
- [SearchAbout binds.] to see lemmas available for reasoning about
bindings in the context.
- Don't forget about fv_open.
*)
Lemma strengthening : forall G e T,
typing G e T
-> forall G1 G2 x U,
G = G1 ++ (x ~ U) ++ G2 -> x `notin` fv e -> typing (G1 ++ G2) e T.
Proof.
(* CHALLENGE EXERCISE *) Admitted.
(*************************************************************************)
(** * Decomposition (Lemma 4.5) *)
(*************************************************************************)
(** Challenge Exercise [decomposition]
Decomposition states that any (large) expression can be decomposed into a
client and implementor by introducing a variable to mediate the
interaction.
The proof of this lemma requires many of the lemmas shown above.
Hint: prove this lemma by induction on the first typing judgement
(after appropriately generalizing it).
*)
Lemma decomposition : forall e' e G x T',
typing G ([ x ~> e ] e') T'->
forall T, uniq ((x ~ T) ++ G) -> typing G e T -> typing ((x ~ T) ++ G) e' T'.
Proof.
(* CHALLENGE EXERCISE *) Admitted.
(*************************************************************************)
(** * Renaming *)
(*************************************************************************)
(* Substitution and weakening together give us a property we call
renaming: (see [typing_rename] below) that we can change the name
of the variable used to open an expression in a typing
derivation. In practice, this means that if a variable is not
"fresh enough" during a proof, we can use this lemma to rename it
to one with additional freshness constraints.
Renaming is used below to show the correspondence between the
exists-fresh version of the rules with the cofinite version, and
also to show that typechecking is decidable.
*)
(*
However, before we prove renaming, we need an auxiliary lemma about
typing judgments which says that terms are well-typed only in
unique environments.
*)
Lemma typing_uniq : forall E e T,
typing E e T -> uniq E.
Proof.
intros E e T H.
induction H; auto.
Qed.
(*
Demo: the proof of renaming.
Note that this proof does not proceed by induction: even if we add
new typing rules to the language, as long as the weakening and
substitution properties hold we can use this proof.
*)
Lemma typing_rename : forall (x y : atom) E e T1 T2,
x `notin` fv e -> y `notin` (dom E `union` fv e) ->
typing ((x ~ T1) ++ E) (open e (exp_fvar x)) T2 ->
typing ((y ~ T1) ++ E) (open e (exp_fvar y)) T2.
Proof.
intros x y E e T1 T2 Fr1 Fr2 H.
destruct (x == y).
- Case "x = y".
subst; eauto.
- Case "x <> y".
assert (J : uniq ((x ~ T1) ++ E)).
eapply typing_uniq; eauto.
assert (J' : uniq E).
inversion J; eauto.
rewrite (@subst_intro x); eauto.
rewrite_env (nil ++ (y ~ T1) ++ E).
apply typing_subst with (S := T1).
simpl_env.
+ SCase "(open x s) is well-typed".
apply typing_weakening_strengthened. eauto. auto.
+ SCase "y is well-typed".
eapply typing_var; eauto.
Qed.
(*************************************************************************)
(** * Exists-Fresh Definitions *)
(*************************************************************************)
(* The use of cofinite quantification in the exp_let typing rule may make some
people worry that we are not formalizing the "right" language.
Furthermore, although this rule has a strong induction principle, it can be
difficult to use it to *construct* typing derivations.
Below, we show that an "exists-fresh" version of the rules is the same as
the cofinite version, by showing that the "exists-fresh" typing rule for
let is admissible.
In otherwords, we will prove the lemma `typing_let_exists` below, which
states that we don't need to show that the body of the let expression type
checks for all but a finite number of variables --- instead we only need to
show that it type checks for a single variable, as long as that variable is
suitably fresh.
*)
Check typing_let.
Lemma typing_let_exists : forall x (E : env) (e1 e2 : exp) (T1 T2 : typ),
typing E e1 T1
-> x `notin` fv e2
-> typing ((x ~ T1) ++ E) (open e2 (exp_fvar x)) T2
-> typing E (exp_let e1 e2) T2.
Proof.
intros x E e1 e2 T1 T2 Te1 Fr Te2.
pick fresh y and apply typing_let.
- eauto.
- apply typing_rename with (x := x); auto.
Qed.
(* Similarly, we can use renaming to strengthen the inversion principle
that we get for typing an expression with binding.
The inversion principle that we want should say that the body of the
let is well-typed for any x that is not in the domain of the environment
or free in e2.
*)
Lemma typing_let_inversion : forall (E : env) (e1 e2 : exp) (T2 : typ),
typing E (exp_let e1 e2) T2
-> (exists T1, typing E e1 T1 /\
(forall x, x `notin` (fv e2 \u dom E)
-> typing ((x ~ T1) ++ E) (open e2 (exp_fvar x)) T2)).
Proof.
intros E e1 e2 T2 H.
inversion H. subst.
(* This is the automatic inversion principle. Compare what we know now in H5
with the statment above. *)
exists T1. split.
- auto.
- intros.
pick fresh y.
apply typing_rename with (x := y).
auto.
auto.
apply H5. auto.
Qed.
|
(* Stream programs with blocking pull.
No option of pull finished or not, just wait until something new comes along.
*)
Require Import Merges.Tactics.
Require Import Merges.Map.
Require Import Merges.List.List.
Require Import Coq.Lists.List.
Import ListNotations.
Set Implicit Arguments.
Require Import Coq.Logic.FunctionalExtensionality.
Module Base.
Section Machine.
Variable Label : Set.
Definition Value := nat.
(* Pred input_seen input_left output *)
(* I don't think predicate needs the peek of the stream before pull *)
Definition Pred := list Value -> list Value -> Prop.
(* No heap or variables, just constant values *)
Inductive Block : Type :=
(* Pull, ignore value, but note whether something was pulled *)
| BlockPull : Label -> Block
(* Push a constant value *)
| BlockPush : Value -> Label -> Block
(* Jump to another label without doing anything *)
| BlockJump : Label -> Block.
Hint Constructors Block.
Variable Blocks : Label -> Block.
Variable LabelPre : Label -> Pred.
Inductive EvalB : list Value -> list Value -> Label
-> list Value -> list Value -> Label -> Prop :=
| EvalBPull l lok i iss os
: Blocks l = BlockPull lok
-> EvalB iss os l
(iss++[i]) os lok
| EvalBPush l push l' iss os
: Blocks l = BlockPush push l'
-> EvalB iss os l
iss (os ++ [push]) l'
| EvalBJump l l' iss os
: Blocks l = BlockJump l'
-> EvalB iss os l
iss os l'
.
Variable Init : Label.
Variable InitPre : LabelPre Init [] [].
Inductive EvalBs : list Value -> list Value -> Label -> Prop :=
| EvalBs0
: EvalBs [] [] Init
| EvalBs1 l l' iss iss' os os'
: EvalBs iss os l
-> EvalB iss os l iss' os' l'
-> EvalBs iss' os' l'
.
Definition BlocksPreT :=
forall iss iss' os os' l l',
EvalBs iss os l ->
LabelPre l iss os ->
EvalB iss os l iss' os' l' ->
LabelPre l' iss' os'.
Hypothesis BlocksPre: BlocksPreT.
Theorem EvalBs_Hoare l iss os
(hEvB : EvalBs iss os l)
: LabelPre l iss os.
Proof.
!induction hEvB.
Qed.
End Machine.
End Base.
Module Program.
Module B := Base.
Record Program (Label : Set) : Type
:= mkProgram
{ Init : Label
; Blocks : Label -> B.Block Label
; LabelPre : Label -> B.Pred
; BlocksPre: B.BlocksPreT Blocks LabelPre Init
; InitPre : LabelPre Init [] []
}.
Definition EvalBs (Label : Set) (P : Program Label)
:= B.EvalBs (Blocks P) (Init P).
(*
Ltac Program_Block_destruct p l :=
let pre := fresh "block_pre" in
let eq := fresh "block_eq" in
destruct (Blocks p l) eqn:eq;
lets pre: (BlocksPre p l);
simpl;
rewrite eq in *. *)
End Program.
Module Fuse.
Module B := Base.
Module P := Program.
Parameter L1 : Set.
Parameter P1 : P.Program L1.
Parameter L2 : Set.
Parameter P2 : P.Program L2.
Inductive State :=
| Waiting
| Ok
.
Hint Constructors State.
Inductive L' :=
| LX (l1 : L1) (l2 : L2) (s1 : State) (s2 : State).
Hint Constructors L'.
Definition Blocks (l : L') : B.Block L' :=
match l with
| LX l1 l2 s1 s2
=> match P.Blocks P1 l1, P.Blocks P2 l2, s1, s2 with
(* try to run 1. for most it doesn't matter what state is, *)
(* as state can only be 'Waiting' if stuck on a push. *)
(* pulling is normal. *)
| B.BlockPull lok, _, _, _
=> B.BlockPull (LX lok l2 Ok s2)
(* trying to push while in 'Ok' marks this as 'Waiting' for other to pull *)
| B.BlockPush _ _, _, Ok, _
=> B.BlockJump (LX l1 l2 Waiting s2)
(* jump is normal *)
| B.BlockJump l', _, _, _
=> B.BlockJump (LX l' l2 Ok s2)
(* try to run 2 *)
(* pulling while 'Ok' marks as waiting. *)
| _, B.BlockPull _, _, Ok
=> B.BlockJump (LX l1 l2 s1 Waiting)
(* pushing is normal *)
| _, B.BlockPush f l', _, _
=> B.BlockPush f (LX l1 l' s1 Ok)
(* jump is normal *)
| _, B.BlockJump l', _, _
=> B.BlockJump (LX l1 l' s1 Ok)
(* Both machines are waiting on other one, so can progress *)
| B.BlockPush f1 l1', B.BlockPull lok, Waiting, Waiting
=> B.BlockJump (LX l1' lok Ok Ok)
end
end.
Check P.EvalBs.
Definition listOfOption (o : option nat) : list nat :=
match o with
| Some v => [v]
| None => []
end.
Definition LabelPre (l : L') : B.Pred :=
match l with
| LX l1 l2 s1 s2
=> fun iss os
=> exists (iss' : list nat),
P.EvalBs P1 iss iss' l1
/\ P.EvalBs P2 iss' os l2
end.
Hint Unfold LabelPre.
Program Definition r := {| P.Blocks := Blocks; P.LabelPre := LabelPre; P.Init := LX (P.Init P1) (P.Init P2) Ok Ok |}.
Next Obligation.
unfolds B.BlocksPreT.
introv hEvBs hLbl hEvB.
destruct l; destruct l'.
!inverts hEvB; simpls
; destruct (P.Blocks P1 l1) eqn:P1Block
; destruct (P.Blocks P2 l2) eqn:P2Block
; destruct s1; destruct s2
; (!inject_all; simpls; tryfalse)
; try solve [(!jauto_set)
; (!eapply B.EvalBs1)
; try solve [!eapply B.EvalBPull]
; try solve [!eapply B.EvalBPush]
; try solve [!eapply B.EvalBJump]
].
Qed.
Next Obligation.
jauto_set; eapply B.EvalBs0.
Qed.
Theorem fuse_ok (l1 : L1) (l2 : L2) (s1 s2 : State) iss oss:
P.EvalBs r iss oss (LX l1 l2 s1 s2)
->
exists (iss' : list nat),
P.LabelPre P1 l1 iss iss' /\ P.LabelPre P2 l2 iss' oss.
Proof.
introv hEvBs.
apply B.EvalBs_Hoare with (LabelPre := LabelPre) in hEvBs.
simpls; jauto_set.
!apply B.EvalBs_Hoare with (LabelPre := P.LabelPre P1) in H.
apply (P.InitPre P1).
apply (P.BlocksPre P1).
!apply B.EvalBs_Hoare with (LabelPre := P.LabelPre P2) in H0.
apply (P.InitPre P2).
apply (P.BlocksPre P2).
apply (P.InitPre r).
apply (P.BlocksPre r).
Qed.
End Fuse. |
-- Following A CUBICAL TYPE THEORY FOR HIGHER INDUCTIVE TYPES
-- by Simon Huber at https://simhu.github.io/misc/hcomp.pdf
-- as closely as possible.
open import Cubical.Core.Primitives
open import Cubical.Core.Glue
import Agda.Builtin.Cubical.HCompU as HCompU
open HCompU using (primFaceForall)
open HCompU.Helpers using (refl)
private
variable
ℓ ℓ₁ : Level
ℓ′ ℓ₁′ : I → Level
-- Section 2 : New Primitives
-- This is just a special case of transp where φ = i0. I include it as it
-- has a far simpler type.
transport : (A : ∀ i → Type (ℓ′ i)) → A i0 → A i1
transport A u₀ = transp A i0 u₀
transp' :
(φ : I)
{ℓ' : I → Level [ φ ↦ (λ _ → ℓ) ]}
{a : PartialP φ (λ _ → Type ℓ)}
(A : (i : I) → Type (outS (ℓ' i)) [ φ ↦ (λ { (φ = i1) → a 1=1 }) ])
(u₀ : outS (A i0))
→ outS (A i1) [ φ ↦ (λ { (φ = i1) → u₀ }) ]
transp' φ A u₀ = inS (transp (λ i → outS (A i)) φ u₀)
transportFill :
(A : ∀ i → Type (ℓ′ i))
(u₀ : A i0)
(i : I)
→ A i
transportFill A u₀ i = transp (λ j → A (i ∧ j)) (~ i) u₀
-- Note that I fix the universe of A to make the type simpler. From now on we
-- are going to do that for all code involving transp where φ is not just i0.
transpFill :
(φ : I)
{a : Partial φ (Type ℓ)}
(A : I → Type ℓ [ φ ↦ a ])
(u₀ : outS (A i0))
(i : I)
→ outS (A i)
transpFill φ A u₀ i = transp (λ j → outS (A (i ∧ j))) (φ ∨ ~ i) u₀
forward :
(A : ∀ i → Type (ℓ′ i))
(r : I)
(u : A r)
→ A i1
forward A r u = transp (λ i → A (i ∨ r)) r u
hcomp' :
{A : Type ℓ}
{φ : I}
(u : ∀ i → Partial φ A)
(u₀ : A [ φ ↦ u i0 ])
→ A [ φ ↦ u i1 ]
hcomp' u u₀ = inS (hcomp u (outS u₀))
module Comp
(A : ∀ i → Type (ℓ′ i))
{φ : I}
(u : ∀ i → Partial φ (A i))
(u₀ : A i0 [ φ ↦ u i0 ])
where
comp' : A i1 [ φ ↦ u i1 ]
comp' =
inS
(hcomp
(λ i o → forward A i (u i o))
(forward A i0 (outS u₀)))
compId : comp A {φ = φ} u (outS u₀) ≡ outS comp'
compId = refl
-- Section 3 : Recursive definition of transport
data ℕ : Type where
zero : ℕ
suc : ℕ → ℕ
transpZeroId : (φ : I) → transp (λ _ → ℕ) φ zero ≡ zero
transpZeroId φ = refl
transpSucId : (φ : I) (u₀ : ℕ)
→ transp (λ _ → ℕ) φ (suc u₀) ≡ suc (transp (λ _ → ℕ) φ u₀)
transpSucId φ u₀ = refl
transpℕId : (φ : I) (u₀ : ℕ) → transp (λ _ → ℕ) φ u₀ ≡ u₀
transpℕId φ u₀ = refl
transportPathPId :
(A : (i j : I) → Type (ℓ′ i))
(v : (i : I) → A i i0)
(w : (i : I) → A i i1)
(u₀ : PathP (A i0) (v i0) (w i0))
→ transport (λ i → PathP (A i) (v i) (w i)) u₀
≡ λ j → comp
(λ i → A i j)
(λ i → λ
{ (j = i0) → v i
; (j = i1) → w i })
(u₀ j)
transportPathPId A v w u₀ = refl
transpPathPId :
(φ : I)
{a : I → Partial φ (Type ℓ)}
(A : (i j : I) → Type ℓ [ φ ↦ a j ])
{vφ : PartialP φ (a i0)}
(v : (i : I) → outS (A i i0) [ φ ↦ (λ { (φ = i1) → vφ 1=1 }) ])
{wφ : PartialP φ (a i1)}
(w : (i : I) → outS (A i i1) [ φ ↦ (λ { (φ = i1) → wφ 1=1 }) ])
(u₀ : PathP (λ j → outS (A i0 j)) (outS (v i0)) (outS (w i0)))
→ transp (λ i → PathP (λ j → outS (A i j)) (outS (v i)) (outS (w i))) φ u₀
≡ λ j → comp
(λ i → outS (A i j))
(λ i → λ
{ (φ = i1) → u₀ j
; (j = i0) → outS (v i)
; (j = i1) → outS (w i) })
(u₀ j)
transpPathPId φ A v w u₀ = refl
transportΣId :
(A : ∀ i → Type (ℓ′ i))
(B : ∀ i → A i → Type (ℓ₁′ i))
(u₀ : Σ (A i0) (B i0))
→ transport (λ i → Σ (A i) (B i)) u₀
≡ (transport A (u₀ .fst) ,
let v = transportFill A (u₀ .fst)
in transport (λ i → B i (v i)) (u₀ .snd))
transportΣId A B u₀ = refl
transpΣId :
(φ : I)
{a : Partial φ (Type ℓ)}
(A : I → Type ℓ [ φ ↦ a ])
{b : Partial φ (Type ℓ₁)}
(B : (i : I) → outS (A i) → Type ℓ₁ [ φ ↦ b ])
(u₀ : Σ (outS (A i0)) (λ x → outS (B i0 x)))
→ transp (λ i → Σ (outS (A i)) (λ x → outS (B i x))) φ u₀
≡ (transp (λ i → outS (A i)) φ (u₀ .fst) ,
let v = transpFill φ A (u₀ .fst)
in transp (λ i → outS (B i (v i))) φ (u₀ .snd))
transpΣId φ A B u₀ = refl
transportΠId :
(A : ∀ i → Type (ℓ′ i))
(B : ∀ i → A i → Type (ℓ₁′ i))
(u₀ : (x : A i0) → B i0 x)
→ transport (λ i → (x : A i) → B i x) u₀
≡ λ v →
let
w : (i : I) → A i
w i = transportFill (λ j → A (~ j)) v (~ i)
in
transport (λ i → B i (w i)) (u₀ (w i0))
transportΠId A B u₀ = refl
transpΠId :
(φ : I)
{a : Partial φ (Type ℓ)}
(A : I → Type ℓ [ φ ↦ a ])
{b : Partial φ (Type ℓ₁)}
(B : (i : I) → outS (A i) → Type ℓ₁ [ φ ↦ b ])
(u₀ : ((x : outS (A i0)) → outS (B i0 x)))
→ transp (λ i → (x : outS (A i)) → outS (B i x)) φ u₀
≡ λ v →
let
w : (i : I) → outS (A i)
w i = transpFill φ (λ j → (A (~ j))) v (~ i)
in
transp (λ i → outS (B i (w i))) φ (u₀ (w i0))
transpΠId φ A B u₀ = refl
transpUniverseId : (φ : I) (A : Type ℓ) → transp (λ _ → Type ℓ) φ A ≡ A
transpUniverseId φ A = refl
module TransportGlue
(A : ∀ i → Type (ℓ′ i))
(φ : I → I)
(T : (i : I) → Partial (φ i) (Type (ℓ₁′ i)))
(w : (i : I) → PartialP (φ i) (λ o → T i o ≃ A i))
(u₀ : primGlue (A i0) (T i0) (w i0))
where
B : (i : I) → Type (ℓ₁′ i)
B i = primGlue (A i) (T i) (w i)
∀φ : I
∀φ = primFaceForall φ
t : (i : I) → PartialP ∀φ (λ { (∀φ = i1) → T i 1=1 })
t i (∀φ = i1) = {!!}
transportGlue : B i1
transportGlue = {!!}
transportGlueId : transport B u₀ ≡ transportGlue
transportGlueId = {!!}
-- Section 4 : Recursive Definition of Homogeneous Composition
hcompZeroId : {φ : I} → hcomp (λ i → λ { (φ = i1) → zero }) zero ≡ zero
hcompZeroId = refl
hcompSucId :
{φ : I}
(u : I → Partial φ ℕ)
(u₀ : ℕ [ φ ↦ u i0 ])
→ hcomp (λ i o → suc (u i o)) (suc (outS u₀)) ≡ suc (hcomp u (outS u₀))
hcompSucId u u₀ = refl
hcompPathPId :
(A : I → Type ℓ)
(v : A i0)
(w : A i1)
{φ : I}
(u : I → Partial φ (PathP A v w))
(u₀ : PathP A v w [ φ ↦ u i0 ])
→ hcomp u (outS u₀)
≡ λ j →
hcomp
(λ i → λ { (φ = i1) → u i 1=1 j ; (j = i0) → v ; (j = i1) → w })
(outS u₀ j)
hcompPathPId A v w u u₀ = refl
hcompΣId :
(A : Type ℓ)
(B : (x : A) → Type ℓ₁)
{φ : I}
(u : I → Partial φ (Σ A B))
(u₀ : Σ A B [ φ ↦ u i0 ])
→ hcomp u (outS u₀)
≡ let
v : (i : I) → A
-- should use hfill instead
v = fill (λ _ → A) (λ i o → u i o .fst) (inS (outS u₀ .fst))
in
(v i1 ,
comp (λ i → B (v i)) (λ i → λ { (φ = i1) → u i 1=1 .snd }) (outS u₀ .snd))
hcompΣId A B u u₀ = refl
hcompΠId :
(A : Type ℓ)
(B : (x : A) → Type ℓ₁)
{φ : I}
(u : I → Partial φ ((x : A) → B x))
(u₀ : ((x : A) → B x) [ φ ↦ u i0 ])
→ hcomp u (outS u₀)
≡ λ v → hcomp (λ i o → u i o v) (outS u₀ v)
hcompΠId A B u u₀ = refl
-- Unfortunately hcomp E (outS A) is not judgmentally equal to
-- outS (hcompUniverse E A) which I don't know why.
hcompUniverse :
{φ : I}
(E : I → Partial φ (Type ℓ))
(A : Type ℓ [ φ ↦ E i0 ])
→ Type ℓ [ φ ↦ E i1 ]
hcompUniverse {φ = φ} E A =
inS
(primGlue
(outS A)
(E i1)
(λ { (φ = i1) → lineToEquiv (λ i → E (~ i) 1=1) }))
module HcompGlue
(A : Type ℓ)
{φ : I}
(T : Partial φ (Type ℓ₁))
(w : PartialP φ (λ o → T o ≃ A))
{ψ : I}
(u : I → Partial ψ (primGlue A T w))
(u₀ : primGlue A T w [ ψ ↦ u i0 ])
where
t : (i : I) → PartialP φ T
t i (φ = i1) = hfill u u₀ i
a₁ : A
a₁ = hcomp (λ i → λ
{ (ψ = i1) → unglue φ (u i 1=1)
; (φ = i1) → w 1=1 .fst (t i 1=1) })
(unglue φ (outS u₀))
hcompGlue : primGlue A T w [ ψ ↦ u i1 ]
hcompGlue = inS (glue (t i1) a₁)
hcompGlueId : hcomp u (outS u₀) ≡ outS hcompGlue
hcompGlueId = refl
|
install.packages("tidyverse")
browseVignettes(“ggplot2”) |
# Generated using bssn_4d_spher_matter.mw
eq_evol_rPIb2:=
diff(rPIb2(t,x) ,t) =
expand( simplify (
(-mass*rpsi(t,x) + 2*(diff(rpsi(t, x), x))/(a1(t, x)^2*x)+(diff(diff(rpsi(t, x), x), x))/a1(t, x)^2-(diff(rpsi(t, x), x))*(diff(a1(t, x), x))/a1(t, x)^3+2*rPIb2(t, x)*beta(t, x)/(alpha(t, x)*b1(t, x)^2*a1(t, x)*x)+beta(t, x)*(diff(rPIb2(t, x), x))/(alpha(t, x)*b1(t, x)^2*a1(t, x))+rPIb2(t, x)*(diff(beta(t, x), x))/(alpha(t, x)*b1(t, x)^2*a1(t, x))+2*(diff(rpsi(t, x), x))*(diff(b1(t, x), x))/(b1(t, x)*a1(t, x)^2)+(diff(rpsi(t, x), x))*(diff(alpha(t, x), x))/(alpha(t, x)*a1(t, x)^2) ) * (alpha(t,x)*b1(t,x)^2*a1(t,x))
) );
eq_evol_iPIb2:=
(diff(iPIb2(t, x), t)) = expand( simplify (
( -mass*ipsi(t,x) + 2*(diff(ipsi(t, x), x))/(a1(t, x)^2*x)+(diff(diff(ipsi(t, x), x), x))/a1(t, x)^2-(diff(ipsi(t, x), x))*(diff(a1(t, x), x))/a1(t, x)^3+2*iPIb2(t, x)*beta(t, x)/(alpha(t, x)*b1(t, x)^2*a1(t, x)*x)+iPIb2(t, x)*(diff(beta(t, x), x))/(alpha(t, x)*b1(t, x)^2*a1(t, x))+2*(diff(ipsi(t, x), x))*(diff(b1(t, x), x))/(b1(t, x)*a1(t, x)^2)+(diff(ipsi(t, x), x))*(diff(alpha(t, x), x))/(alpha(t, x)*a1(t, x)^2)+beta(t, x)*(diff(iPIb2(t, x), x))/(alpha(t, x)*b1(t, x)^2*a1(t, x))) * (alpha(t,x)*b1(t,x)^2*a1(t,x))
) );
eq_evol_rpsi := diff(rpsi(t,x),t) = alpha(t,x)/a1(t,x)*rPI(t,x)+beta(t,x)*rPHI(t,x);
eq_evol_ipsi := diff(ipsi(t,x),t) = alpha(t,x)/a1(t,x)*iPI(t,x)+beta(t,x)*iPHI(t,x);
|
# (c) Copyright [2018] Micro Focus or one of its affiliates.
# 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.
#
# AUTHOR: BADR OUALI
#
############################################################################################################
# __ __ ___ ____ ______ ____ __ ____ ___ ___ _ ____ __ __ ______ __ __ ___ ____ #
# | | | / _| \| | | / ]/ | | | | | | \| | | | | |/ \| \ #
# | | |/ [_| D | || | / /| o | | _ _ | | | o | | | | | | | _ | #
# | | | _| /|_| |_|| |/ / | | | \_/ | |___ | _/| ~ |_| |_| _ | O | | | #
# | : | [_| \ | | | / \_| _ | | | | | | | |___, | | | | | | | | | #
# \ /| | . \ | | | \ | | | | | | | | | | | | | | | | | | | #
# \_/ |_____|__|\_| |__| |____\____|__|__| |___|___|_____| |__| |____/ |__| |__|__|\___/|__|__| #
# #
############################################################################################################
# Vertica-ML-Python allows user to create Virtual Dataframe. vDataframes simplify #
# data exploration, data cleaning and machine learning in Vertica. #
# It is an object which keeps in it all the actions that the user wants to achieve #
# and execute them when they are needed. #
# #
# The purpose is to bring the logic to the data and not the opposite #
#####################################################################################
#
# Libraries
import numpy as np
import os
import math
import time
from vertica_ml_python.vcolumn import vColumn
from vertica_ml_python.utilities import print_table
from vertica_ml_python.utilities import isnotebook
from vertica_ml_python.utilities import tablesample
from vertica_ml_python.utilities import to_tablesample
from vertica_ml_python.utilities import category_from_type
##
# _____
# _______ ______ ____________ ____ \ \
# \ | | |\ \ \ \ /____/|
# | / / /| \ \ | |/_____|/
# |\ \ \ |/ | /\ | | | ___
# \ \ \ | | | | | | | \__/ \
# \| \| | | \/ | / /\___/|
# |\ /| / /|/ /| | | |
# | \_______/ | /___________/ ||_____| /\|_|/
# \ | | / | | / | |/
# \|_____|/ |___________|/ |_____|
#
##
#
class vDataframe:
#
def __init__(self,
input_relation: str,
cursor = None,
dsn: str = "",
usecols: list = [],
empty: bool = False):
if not(empty):
if (cursor == None):
from vertica_ml_python import vertica_cursor
cursor = vertica_cursor(dsn)
self.dsn = dsn
schema_input_relation = input_relation.split(".")
if (len(schema_input_relation) == 1):
self.schema = "public"
self.input_relation = input_relation
else:
self.input_relation = schema_input_relation[1]
self.schema = schema_input_relation[0]
# Cursor to the Vertica Database
self.cursor = cursor
# All the columns of the vDataframe
if (usecols == []):
query = "(SELECT column_name FROM columns WHERE table_name='{}' AND table_schema='{}')".format(self.input_relation, self.schema)
query += " UNION (SELECT column_name FROM view_columns WHERE table_name='{}' AND table_schema='{}')".format(self.input_relation, self.schema)
cursor.execute(query)
columns = cursor.fetchall()
columns = [str(item) for sublist in columns for item in sublist]
columns = ['"' + item + '"' for item in columns]
if (columns != []):
self.columns = columns
else:
print("/!\\ Warning: No table or views '{}' found.\nNothing was created.".format(self.input_relation))
del self
return None
else:
self.columns = usecols
for column in self.columns:
new_vColumn = vColumn(column, parent = self)
setattr(self, column, new_vColumn)
setattr(self, column[1:-1], new_vColumn)
# Columns to not consider for the final query
self.exclude_columns = []
# Rules for the cleaned data
self.where = []
# Rules to sort the data
self.order_by = []
# Display the elapsed time during the query
self.time_on = False
# Display or not the sequal queries that are used during the vDataframe manipulation
self.query_on = False
# vDataframe history
self.history = []
# vDataframe saving
self.saving = []
# vDataframe main relation
self.main_relation = self.schema + "." + self.input_relation
#
def __getitem__(self, index):
return getattr(self, index)
def __setitem__(self, index, val):
setattr(self, index, val)
#
def __repr__(self):
return self.head(limit = 5).__repr__()
#
def __setattr__(self, attr, val):
self.__dict__[attr] = val
#
# SQL GEN = THE MOST IMPORTANT METHOD
#
def genSQL(self,
split: bool = False,
transformations: dict = {},
force_columns = [],
final_table_name = "final_table"):
# FINDING MAX FLOOR
all_imputations_grammar = []
force_columns = self.columns if not(force_columns) else force_columns
for column in force_columns:
all_imputations_grammar += [[item[0] for item in self[column].transformations]]
for column in transformations:
all_imputations_grammar += [transformations[column]]
# MAX FLOOR
max_len = len(max(all_imputations_grammar, key=len))
# TRANSFORMATIONS COMPLETION
for imputations in all_imputations_grammar:
diff = max_len - len(imputations)
if diff > 0:
imputations += ["{}"]*diff
# FILTER
where_positions = [item[1] for item in self.where]
max_where_pos = max(where_positions+[0])
all_where = [[] for item in range(max_where_pos+1)]
for i in range(0, len(self.where)):
all_where[where_positions[i]] += [self.where[i][0]]
all_where = [" AND ".join(item) for item in all_where]
for i in range(len(all_where)):
if (all_where[i] != ''):
all_where[i] = " WHERE " + all_where[i]
# ORDER BY
order_by_positions = [item[1] for item in self.order_by]
max_order_by_pos = max(order_by_positions+[0])
all_order_by = [[] for item in range(max_order_by_pos+1)]
for i in range(0, len(self.order_by)):
all_order_by[order_by_positions[i]] += [self.order_by[i][0]]
all_order_by = [", ".join(item) for item in all_order_by]
for i in range(len(all_order_by)):
if (all_order_by[i] != ''):
all_order_by[i] = " ORDER BY " + all_order_by[i]
# FIRST FLOOR
columns = force_columns + [column for column in transformations]
first_values = [item[0] for item in all_imputations_grammar]
for i in range(0, len(first_values)):
first_values[i] = "{} AS {}".format(first_values[i], columns[i])
table = "SELECT " + ", ".join(first_values) + " FROM " + self.main_relation
# OTHER FLOORS
for i in range(1, max_len):
values = [item[i] for item in all_imputations_grammar]
for j in range(0, len(values)):
values[j] = values[j].replace("{}", columns[j]) + " AS " + columns[j]
table = "SELECT " + ", ".join(values) + " FROM (" + table + ") t" + str(i)
try:
table += all_where[i - 1]
except:
pass
try:
table += all_order_by[i - 1]
except:
pass
try:
where_final = all_where[max_len - 1]
except:
where_final = ""
try:
order_final = all_order_by[max_len - 1]
except:
order_final = ""
split = ", RANDOM() AS __split_vpython__" if (split) else ""
if (where_final == "") and (order_final == ""):
if (split):
table = "(SELECT *{} FROM (".format(split) + table + ") " + final_table_name + ") split_final_table"
else:
table = "(" + table + ") " + final_table_name
else:
table = "(" + table + ") t" + str(max_len)
table += where_final + order_final
table = "(SELECT *{} FROM " + table + ") ".format(split) + final_table_name
if (self.exclude_columns):
table = "(SELECT " + ", ".join(self.get_columns()) + split + " FROM " + table + ") " + final_table_name
return table
#
#
#
# METHODS
#
def abs(self, columns: list = []):
func = {}
if not(columns):
columns = self.numcol()
for column in columns:
func[column] = "abs({})"
return (self.apply(func))
#
def agg(self, func: list, columns: list = []):
return (self.aggregate(func = func, columns = columns))
def aggregate(self, func: list, columns: list = []):
columns = self.numcol() if not(columns) else ['"' + column.replace('"', '') + '"' for column in columns]
query = []
for column in columns:
for fun in func:
if (fun.lower() == "median"):
expr = "APPROXIMATE_MEDIAN({})".format(column)
elif (fun.lower() == "std"):
expr = "STDDEV({})".format(column)
elif (fun.lower() == "var"):
expr = "VARIANCE({})".format(column)
elif (fun.lower() == "mean"):
expr = "AVG({})".format(column)
elif ('%' in fun):
expr = "APPROXIMATE_PERCENTILE({} USING PARAMETERS percentile = {})".format(column, float(fun[0:-1]) / 100)
elif (fun.lower() == "sem"):
expr = "STDDEV({}) / SQRT(COUNT({}))".format(column, column)
elif (fun.lower() == "mad"):
mean = self[column].mean()
expr = "SUM(ABS({} - {})) / COUNT({})".format(column, mean, column)
elif (fun.lower() in ("prod", "product")):
expr = "DECODE(ABS(MOD(SUM(CASE WHEN {} < 0 THEN 1 ELSE 0 END), 2)), 0, 1, -1) * POWER(10, SUM(LOG(ABS({}))))".format(column, column)
elif (fun.lower() in ("percent", "count_percent")):
expr = "ROUND(COUNT({}) / {} * 100, 3)".format(column, self.shape()[0])
else:
expr = "{}({})".format(fun.upper(), column)
query += [expr]
query = "SELECT {} FROM {}".format(', '.join(query), self.genSQL())
self.executeSQL(query, title = "COMPUTE AGGREGATION(S)")
result = [item for item in self.cursor.fetchone()]
try:
result = [float(item) for item in result]
except:
pass
values = {"index": func}
i = 0
for column in columns:
values[column] = result[i:i + len(func)]
i += len(func)
return (tablesample(values = values, table_info = False).transpose())
#
def aggregate_matrix(self,
method: str = "pearson",
columns: list = [],
cmap: str = "",
round_nb: int = 3,
show: bool = True):
if not(method in ("beta", "cov", "pearson", "kendall", "spearman", "biserial", "cramer")):
raise ValueError("The parameter 'method' must be in pearson|kendall|spearman|biserial|cramer|beta|cov")
columns = ['"' + column.replace('"', '') + '"' for column in columns]
for column_name in columns:
if not(column_name in self.get_columns()):
raise NameError("The parameter 'columns' must be a list of different columns name")
if (len(columns) == 1):
if (method in ("pearson", "beta", "spearman", "kendall", "biserial", "cramer")):
return 1.0
elif (method == "cov"):
return self[columns[0]].var()
elif (len(columns) == 2):
if (method in ("pearson", "spearman")):
if (columns[1] == columns[0]):
return 1
table = self.genSQL() if (method == "pearson") else "(SELECT RANK() OVER (ORDER BY {}) AS {}, RANK() OVER (ORDER BY {}) AS {} FROM {}) rank_spearman_table".format(columns[0], columns[0], columns[1], columns[1], self.genSQL())
query = "SELECT CORR({}, {}) FROM {}".format(columns[0], columns[1], table)
title = "Compute the {} Correlation between the two variables".format(method)
elif (method == "biserial"):
if (self[columns[1]].nunique() == 2 and self[columns[1]].min() == 0 and self[columns[1]].max() == 1):
if (columns[1] == columns[0]):
return 1
column_b = columns[1]
column_n = columns[0]
elif (self[columns[0]].nunique() == 2 and self[columns[0]].min() == 0 and self[columns[0]].max() == 1):
if (columns[1] == columns[0]):
return 1
column_b = columns[0]
column_n = columns[1]
else:
return None
query = "SELECT (AVG(DECODE({}, 1, {}, NULL)) - AVG(DECODE({}, 0, {}, NULL))) / STDDEV({}) * SQRT(SUM({}) * SUM(1 - {}) / COUNT(*) / COUNT(*)) FROM {} WHERE {} IS NOT NULL AND {} IS NOT NULL;".format(column_b, column_n, column_b, column_n, column_n, column_b, column_b, self.genSQL(), column_n, column_b)
title = "Compute the biserial Correlation between the two variables"
elif (method == "cramer"):
if (columns[1] == columns[0]):
return 1
k, r = self[columns[0]].nunique(), self[columns[1]].nunique()
table_0_1 = "SELECT {}, {}, COUNT(*) AS nij FROM {} WHERE {} IS NOT NULL AND {} IS NOT NULL GROUP BY 1, 2".format(columns[0], columns[1], self.genSQL(), columns[0], columns[1])
table_0 = "SELECT {}, COUNT(*) AS ni FROM {} WHERE {} IS NOT NULL GROUP BY 1".format(columns[0], self.genSQL(), columns[0])
table_1 = "SELECT {}, COUNT(*) AS nj FROM {} WHERE {} IS NOT NULL GROUP BY 1".format(columns[1], self.genSQL(), columns[1])
query_count = "SELECT COUNT(*) AS n FROM {} WHERE {} IS NOT NULL AND {} IS NOT NULL".format(self.genSQL(), columns[0], columns[1])
n = self.cursor.execute(query_count).fetchone()[0]
query = "SELECT SUM((nij - ni * nj / {}) * (nij - ni * nj / {}) / (ni * nj)) AS phi2 FROM (SELECT * FROM ({}) table_0_1 LEFT JOIN ({}) table_0 ON table_0_1.{} = table_0.{}) x LEFT JOIN ({}) table_1 ON x.{} = table_1.{}"
query = query.format(n, n, table_0_1, table_0, columns[0], columns[0], table_1, columns[1], columns[1])
phi2 = self.cursor.execute(query).fetchone()[0]
phi2 = max(0, float(phi2) - (r - 1) * (k - 1) / (n - 1))
k = k - (k - 1) * (k - 1) / (n - 1)
r = r - (r - 1) * (r - 1) / (n - 1)
return math.sqrt(phi2 / min(k, r))
elif (method == "kendall"):
if (columns[1] == columns[0]):
return 1
query = "SELECT (SUM(((x.{} < y.{} AND x.{} < y.{}) OR (x.{} > y.{} AND x.{} > y.{}))::int) - SUM(((x.{} > y.{} AND x.{} < y.{}) OR (x.{} < y.{} AND x.{} > y.{}))::int)) / SUM((x.{} != y.{} AND x.{} != y.{})::int) FROM (SELECT {}, {} FROM {}) x CROSS JOIN (SELECT {}, {} FROM {}) y"
query = query.format(columns[0], columns[0], columns[1], columns[1], columns[0], columns[0], columns[1], columns[1], columns[0], columns[0], columns[1], columns[1], columns[0], columns[0], columns[1], columns[1], columns[0], columns[0], columns[1], columns[1], columns[0], columns[1], self.genSQL(), columns[0], columns[1], self.genSQL())
title = "Compute the kendall Correlation between the two variables"
elif (method == "cov"):
query = "SELECT COVAR_POP({}, {}) FROM {}".format(columns[0], columns[1], self.genSQL())
title = "Compute the Covariance between the two variables"
elif (method == "beta"):
if (columns[1] == columns[0]):
return 1
query = "SELECT COVAR_POP({}, {}) / VARIANCE({}) FROM {}".format(columns[0], columns[1], columns[1], self.genSQL())
title = "Compute the elasticity Beta between the two variables"
try:
self.executeSQL(query = query, title = title)
return self.cursor.fetchone()[0]
except:
return None
elif (len(columns) >= 2):
if (method in ("pearson", "spearman", "kendall", "biserial", "cramer")):
title_query = "Compute all the Correlations in a single query"
title = 'Correlation Matrix ({})'.format(method)
if (method == "biserial"):
i0, step = 0, 1
else:
i0, step = 1, 0
elif (method == "cov"):
title_query = "Compute all the Covariances in a single query"
title = 'Covariance Matrix'
i0, step = 0, 1
elif (method == "beta"):
title_query = "Compute all the Beta Coefficients in a single query"
title = 'Elasticity Matrix'
i0, step = 1, 0
try:
all_list = []
n = len(columns)
for i in range(i0, n):
for j in range(0, i + step):
if (method in ("pearson", "spearman")):
all_list += ["ROUND(CORR({}, {}), {})".format(columns[i], columns[j], round_nb)]
elif (method == "kendall"):
all_list += ["(SUM(((x.{} < y.{} AND x.{} < y.{}) OR (x.{} > y.{} AND x.{} > y.{}))::int) - SUM(((x.{} > y.{} AND x.{} < y.{}) OR (x.{} < y.{} AND x.{} > y.{}))::int)) / NULLIFZERO(SUM((x.{} != y.{} AND x.{} != y.{})::int))".format(columns[i], columns[i], columns[j], columns[j], columns[i], columns[i], columns[j], columns[j], columns[i], columns[i], columns[j], columns[j], columns[i], columns[i], columns[j], columns[j], columns[i], columns[i], columns[j], columns[j])]
elif (method == "cov"):
all_list += ["COVAR_POP({}, {})".format(columns[i], columns[j])]
elif (method == "beta"):
all_list += ["COVAR_POP({}, {}) / VARIANCE({})".format(columns[i], columns[j], columns[j])]
else:
raise
if (method == "spearman"):
rank = ["RANK() OVER (ORDER BY {}) AS {}".format(column, column) for column in columns]
table = "(SELECT {} FROM {}) rank_spearman_table".format(", ".join(rank), self.genSQL())
elif (method == "kendall"):
table = "(SELECT {} FROM {}) x CROSS JOIN (SELECT {} FROM {}) y".format(", ".join(columns), self.genSQL(), ", ".join(columns), self.genSQL())
else:
table = self.genSQL()
self.executeSQL(query = "SELECT {} FROM {}".format(", ".join(all_list), table), title = title_query)
result = self.cursor.fetchone()
except:
n = len(columns)
result = []
for i in range(i0, n):
for j in range(0, i + step):
result += [self.aggregate_matrix(method, [columns[i], columns[j]])]
matrix = [[1 for i in range(0, n + 1)] for i in range(0, n + 1)]
matrix[0] = [""] + columns
for i in range(0, n + 1):
matrix[i][0] = columns[i - 1]
k = 0
for i in range(i0, n):
for j in range(0, i + step):
current = result[k]
k += 1
if (current == None):
current = 0
matrix[i + 1][j + 1] = current
matrix[j + 1][i + 1] = 1 / current if ((method == "beta") and (current != 0)) else current
if ((show) and (method in ("pearson", "spearman", "kendall", "biserial", "cramer"))):
from vertica_ml_python.plot import cmatrix
vmin = 0 if (method == "cramer") else -1
if not(cmap):
from matplotlib.colors import LinearSegmentedColormap
cm1 = LinearSegmentedColormap.from_list("vml", ["#FFFFFF", "#214579"], N = 1000)
cm2 = LinearSegmentedColormap.from_list("vml", ["#FFCC01", "#FFFFFF", "#214579"], N = 1000)
cmap = cm1 if (method == "cramer") else cm2
cmatrix(matrix, columns, columns, n, n, vmax = 1, vmin = vmin, cmap = cmap, title = title, mround = round_nb)
values = {"index" : matrix[0][1:len(matrix[0])]}
del(matrix[0])
for column in matrix:
values[column[0]] = column[1:len(column)]
return tablesample(values = values, table_info = False)
else:
if (method == "cramer"):
cols = self.catcol(100)
if (len(cols) == 0):
raise Exception("No categorical column found")
else:
cols = self.numcol()
if (len(cols) == 0):
raise Exception("No numerical column found")
return (self.aggregate_matrix(method = method, columns = cols, cmap = cmap, round_nb = round_nb, show = show))
#
def append(self,
vdf = None,
input_relation: str = ""):
first_relation = self.genSQL()
second_relation = input_relation if not(vdf) else vdf.genSQL()
table = "(SELECT * FROM {}) UNION ALL (SELECT * FROM {})".format(first_relation, second_relation)
query = "SELECT * FROM ({}) append_table LIMIT 1".format(table)
self.executeSQL(query = query, title = "Merging the two relation")
self.main_relation = "({}) append_table".format(table)
return (self)
#
def all(self, columns: list):
return (self.aggregate(func = ["bool_and"], columns = columns))
#
def any(self, columns: list):
return (self.aggregate(func = ["bool_or"], columns = columns))
#
def apply(self, func: dict):
for column in func:
self[column].apply(func[column])
return (self)
#
def applymap(self, func: str, numeric_only: bool = True):
function = {}
columns = self.numcol() if numeric_only else self.get_columns()
for column in columns:
function[column] = func
return (self.apply(function))
#
def asfreq(self,
ts: str,
rule: str,
method: dict,
by: list = []):
all_elements = []
for column in method:
if (method[column] not in ('bfill', 'backfill', 'pad', 'ffill', 'linear')):
raise ValueError("Each element of the 'method' dictionary must be in bfill|backfill|pad|ffill|linear")
if (method[column] in ('bfill', 'backfill')):
func = "TS_FIRST_VALUE"
interp = 'const'
elif (method[column] in ('pad', 'ffill')):
func = "TS_LAST_VALUE"
interp = 'const'
else:
func = "TS_FIRST_VALUE"
interp = 'linear'
all_elements += ["{}({}, '{}') AS {}".format(func, '"' + column.replace('"', '') + '"', interp, '"' + column.replace('"', '') + '"')]
table = "SELECT {} FROM {}".format("{}", self.genSQL())
tmp_query = ["slice_time AS {}".format('"' + ts.replace('"', '') + '"')]
tmp_query += ['"' + column.replace('"', '') + '"' for column in by]
tmp_query += all_elements
table = table.format(", ".join(tmp_query))
table += " TIMESERIES slice_time AS '{}' OVER (PARTITION BY {} ORDER BY {})".format(rule, ", ".join(['"' + column.replace('"', '') + '"' for column in by]), '"' + ts.replace('"', '') + '"')
return (self.vdf_from_relation("(" + table + ') resample_table', "resample", "[Resample]: The data was resampled"))
#
def astype(self, dtype: dict):
for column in dtype:
self[column].astype(dtype = dtype[column])
return (self)
#
def at_time(self,
ts: str,
time: str):
expr = "{}::time = '{}'".format('"' + ts.replace('"', '') + '"', time)
self.filter(expr)
return (self)
#
def avg(self, columns = []):
return (self.mean(columns = columns))
#
def bar(self,
columns: list,
method: str = "density",
of: str = "",
max_cardinality: tuple = (6, 6),
h: tuple = (None, None),
limit_distinct_elements: int = 200,
hist_type: str = "auto"):
if (len(columns) == 1):
self[columns[0]].bar(method, of, 6, 0, 0)
else:
stacked, fully_stacked = False, False
if (hist_type.lower() in ("fully", "fully stacked", "fully_stacked")):
fully_stacked = True
elif (hist_type.lower() == "stacked"):
stacked = True
from vertica_ml_python.plot import bar2D
bar2D(self, columns, method, of, max_cardinality, h, limit_distinct_elements, stacked, fully_stacked)
return (self)
#
def beta(self, columns: list = []):
return (self.aggregate_matrix(method = "beta", columns = columns))
#
def between_time(self,
ts: str,
start_time: str,
end_time: str):
expr = "{}::time BETWEEN '{}' AND '{}'".format('"' + ts.replace('"', '') + '"', start_time, end_time)
self.filter(expr)
return (self)
#
def boxplot(self, columns: list = []):
from vertica_ml_python.plot import boxplot2D
boxplot2D(self, columns)
return (self)
#
def catcol(self, max_cardinality: int = 12):
columns = []
for column in self.get_columns():
if (self[column].nunique() <= max_cardinality):
columns += [column]
return (columns)
#
def copy(self):
copy_vDataframe = vDataframe("", empty = True)
copy_vDataframe.dsn = self.dsn
copy_vDataframe.input_relation = self.input_relation
copy_vDataframe.main_relation = self.main_relation
copy_vDataframe.schema = self.schema
copy_vDataframe.cursor = self.cursor
copy_vDataframe.columns = [item for item in self.columns]
copy_vDataframe.where = [item for item in self.where]
copy_vDataframe.order_by = [item for item in self.order_by]
copy_vDataframe.exclude_columns = [item for item in self.exclude_columns]
copy_vDataframe.history = [item for item in self.history]
copy_vDataframe.saving = [item for item in self.saving]
copy_vDataframe.query_on = self.query_on
copy_vDataframe.time_on = self.time_on
for column in self.columns:
new_vColumn = vColumn(column, parent = copy_vDataframe, transformations = self[column].transformations)
setattr(copy_vDataframe, column, new_vColumn)
setattr(copy_vDataframe, column[1:-1], new_vColumn)
return (copy_vDataframe)
#
def corr(self,
columns: list = [],
method: str = "pearson",
cmap: str = "",
round_nb: int = 3,
show: bool = True):
return (self.aggregate_matrix(method = method, columns = columns, cmap = cmap, round_nb = round_nb, show = show))
#
def cov(self, columns: list = []):
return (self.aggregate_matrix(method = "cov", columns = columns))
#
def count(self,
columns = [],
percent: bool = True):
columns = self.get_columns() if not(columns) else columns
func = ["count", "percent"] if (percent) else ["count"]
return (self.aggregate(func = func, columns = columns))
#
def cummax(self,
name: str,
column: str,
by: list = [],
order_by: list = []):
return (self.rolling(name = name, aggr = "max", column = column, preceding = "UNBOUNDED", following = 0, by = by, order_by = order_by))
#
def cummin(self,
name: str,
column: str,
by: list = [],
order_by: list = []):
return (self.rolling(name = name, aggr = "min", column = column, preceding = "UNBOUNDED", following = 0, by = by, order_by = order_by))
#
def cumprod(self,
name: str,
column: str,
by: list = [],
order_by: list = []):
return (self.rolling(name = name, aggr = "", column = column, preceding = "UNBOUNDED", following = 0, expr = "DECODE(ABS(MOD(SUM(CASE WHEN {} < 0 THEN 1 ELSE 0 END) #, 2)), 0, 1, -1) * POWER(10, SUM(LOG(ABS({}))) #)", by = by, order_by = order_by))
#
def cumsum(self,
name: str,
column: str,
by: list = [],
order_by: list = []):
return (self.rolling(name = name, aggr = "sum", column = column, preceding = "UNBOUNDED", following = 0, by = by, order_by = order_by))
#
def current_relation(self):
return (self.genSQL())
#
def datecol(self):
columns = []
for column in self.get_columns():
if self[column].isdate():
columns += [column]
return (columns)
#
def describe(self,
method: str = "numerical",
columns: list = [],
unique: bool = True):
if (columns == []):
columns = self.get_columns()
else:
for i in range(len(columns)):
columns[i] = '"' + columns[i].replace('"', '') + '"'
if (method == "numerical"):
query = "SELECT SUMMARIZE_NUMCOL("
for column in columns:
if self[column].isnum():
if (self[column].transformations[-1][1] == "boolean"):
query += column + "::int,"
else:
query += column + ","
query = query[:-1]
query += ") OVER () FROM {}".format(self.genSQL())
self.executeSQL(query, title = "Compute the descriptive statistics of all the numerical columns")
query_result = self.cursor.fetchall()
data = [item for item in query_result]
matrix = [['column'], ['count'], ['mean'], ['std'], ['min'], ['25%'], ['50%'], ['75%'], ['max']]
for row in data:
for idx,val in enumerate(row):
matrix[idx] += [val]
if (unique):
query = []
try:
for column in matrix[0][1:]:
query += ["COUNT(DISTINCT {})".format('"' + column + '"')]
query= "SELECT "+",".join(query) + " FROM " + self.genSQL()
self.executeSQL(query, title = "Compute the cardinalities of all the elements in a single query")
cardinality=self.cursor.fetchone()
cardinality=[item for item in cardinality]
except:
cardinality = []
for column in matrix[0][1:]:
query = "SELECT COUNT(DISTINCT {}) FROM {}".format('"' + column + '"',self.genSQL())
self.executeSQL(query, title = "New attempt: Compute one per one all the cardinalities")
cardinality += [self.cursor.fetchone()[0]]
matrix += [['unique'] + cardinality]
values = {"index" : matrix[0][1:len(matrix[0])]}
del(matrix[0])
for column in matrix:
values[column[0]] = column[1:len(column)]
elif (method == "categorical"):
values = {"index" : [], "dtype" : [], "unique" : [], "count" : [], "top" : [], "top_percent" : []}
for column in columns:
values["index"] += [column]
values["dtype"] += [self[column].ctype()]
values["unique"] += [self[column].nunique()]
values["count"] += [self[column].count()]
query = "SELECT SUMMARIZE_CATCOL({}::varchar USING PARAMETERS TOPK = 1) OVER () FROM {} WHERE {} IS NOT NULL OFFSET 1".format(column, self.genSQL(), column)
self.executeSQL(query, title = "Compute the TOP1 feature")
result = self.cursor.fetchone()
values["top"] += [result[0]]
values["top_percent"] += [round(result[2], 3)]
else:
raise ValueError("The parameter 'method' must be in numerical|categorical")
return (tablesample(values, table_info = False))
#
def drop(self, columns: list = []):
for column in columns:
if ('"' + column.replace('"', '') + '"' in self.get_columns()):
self[column].drop()
else:
print("/!\\ Warning: Column '{}' is not in the vDataframe.".format(column))
return (self)
#
def drop_duplicates(self, columns: list = []):
count = self.duplicated(columns = columns, count = True)
if (count):
name = "_vpython_duplicated_index" + str(np.random.randint(10000000)) + "_"
columns = self.get_columns() if not(columns) else ['"' + column.replace('"', '') + '"' for column in columns]
self.eval(name = name, expr = "ROW_NUMBER() OVER (PARTITION BY {})".format(", ".join(columns)), print_info = False)
self.filter(expr = '"{}" = 1'.format(name))
self.exclude_columns += ['"{}"'.format(name)]
else:
print("/!\\ Warning: No duplicates detected")
return (self)
#
def dropna(self, columns: list = [], print_info: bool = True):
if (columns == []):
columns = self.get_columns()
total = self.shape()[0]
for column in columns:
self[column].dropna(print_info = False)
if (print_info):
total -= self.shape()[0]
if (total == 0):
print("/!\\ Warning: Nothing was dropped")
elif (total == 1):
print("1 element was dropped")
else:
print("{} elements were dropped".format(total))
return (self)
#
def dsn_restart(self):
from vertica_ml_python import vertica_cursor
self.cursor = vertica_cursor(self.dsn)
return (self)
#
def dtypes(self):
values = {"index" : [], "dtype" : []}
for column in self.get_columns():
values["index"] += [column]
values["dtype"] += [self[column].ctype()]
return (tablesample(values, table_info = False))
#
def duplicated(self, columns: list = [], count: bool = False):
columns = self.get_columns() if not(columns) else ['"' + column.replace('"', '') + '"' for column in columns]
query = "(SELECT *, ROW_NUMBER() OVER (PARTITION BY {}) AS duplicated_index FROM {}) duplicated_index_table WHERE duplicated_index > 1"
query = query.format(", ".join(columns), self.genSQL())
if (count):
query = "SELECT COUNT(*) FROM " + query
self.executeSQL(query = query, title = "Computing the Number of duplicates")
return self.cursor.fetchone()[0]
else:
query = "SELECT {}, MAX(duplicated_index) AS occurrence FROM ".format(", ".join(columns)) + query + " GROUP BY {}".format(", ".join(columns))
return (to_tablesample(query, self.cursor, name = "Duplicated Rows"))
#
def empty(self):
return (self.get_columns() == [])
#
def eval(self, name: str, expr: str, print_info: bool = True):
try:
name = '"' + name.replace('"', '') + '"'
tmp_name = "_vpython" + str(np.random.randint(10000000)) + "_"
self.executeSQL(query = "DROP TABLE IF EXISTS " + tmp_name, title = "Drop the existing generated table")
query = "CREATE TEMPORARY TABLE {} AS SELECT {} AS {} FROM {} LIMIT 20".format(tmp_name, expr, name, self.genSQL())
self.executeSQL(query = query, title = "Create a temporary table to test if the new feature is correct")
query = "SELECT data_type FROM columns WHERE column_name='{}' AND table_name='{}'".format(name.replace('"', ''), tmp_name)
self.executeSQL(query = query, title = "Catch the new feature's type")
ctype = self.cursor.fetchone()[0]
self.executeSQL(query = "DROP TABLE IF EXISTS " + tmp_name, title = "Drop the temporary table")
ctype = ctype if (ctype) else "undefined"
category = category_from_type(ctype = ctype)
vDataframe_maxfloor_length = len(max([self[column].transformations for column in self.get_columns()], key = len))
vDataframe_minfloor_length = 0
for column in self.get_columns():
if ((column in expr) or (column.replace('"','') in expr)):
vDataframe_minfloor_length = max(len(self[column].transformations), vDataframe_minfloor_length)
for eval_floor_length in range(vDataframe_minfloor_length, vDataframe_maxfloor_length):
try:
self.cursor.execute("SELECT * FROM {} LIMIT 0".format(
self.genSQL(transformations = {name : [1 for i in range(eval_floor_length)] + [expr]})))
floor_length = eval_floor_length
break
except:
floor_length = vDataframe_maxfloor_length
floor_length = vDataframe_maxfloor_length if (vDataframe_minfloor_length >= vDataframe_maxfloor_length) else floor_length
transformations = [('0', "undefined", "undefined") for i in range(floor_length)] + [(expr, ctype, category)]
new_vColumn = vColumn(name, parent = self, transformations = transformations)
setattr(self, name, new_vColumn)
setattr(self, name.replace('"', ''), new_vColumn)
self.columns += [name]
if (print_info):
print("The new vColumn {} was added to the vDataframe.".format(name))
self.history += ["{" + time.strftime("%c") + "} " + "[Eval]: A new vColumn '{}' was added to the vDataframe.".format(name)]
return (self)
except:
raise Exception("An error occurs during the creation of the new feature")
#
def executeSQL(self, query: str, title: str = ""):
if (self.query_on):
try:
import shutil
screen_columns = shutil.get_terminal_size().columns
except:
screen_rows, screen_columns = os.popen('stty size', 'r').read().split()
try:
import sqlparse
query_print = sqlparse.format(query, reindent=True)
except:
query_print = query
if (isnotebook()):
from IPython.core.display import HTML, display
display(HTML("<h4 style='color:#444444;text-decoration:underline;'>" + title + "</h4>"))
query_print = query_print.replace('\n',' <br>').replace(' ','   ')
display(HTML(query_print))
display(HTML("<div style = 'border : 1px dashed black; width : 100%'></div>"))
else:
print("$ " + title + " $\n")
print(query_print)
print("-" * int(screen_columns) + "\n")
start_time = time.time()
self.cursor.execute(query)
elapsed_time = time.time() - start_time
if (self.time_on):
try:
import shutil
screen_columns = shutil.get_terminal_size().columns
except:
screen_rows, screen_columns = os.popen('stty size', 'r').read().split()
if (isnotebook()):
from IPython.core.display import HTML,display
display(HTML("<div><b>Elapsed Time:</b> " + str(elapsed_time) + "</div>"))
display(HTML("<div style='border:1px dashed black;width:100%'></div>"))
else:
print("Elapsed Time: " + str(elapsed_time))
print("-" * int(screen_columns) + "\n")
return (self.cursor)
#
def expected_store_usage(self, unit = 'b'):
if (unit.lower() == 'kb'):
div_unit = 1024
elif (unit.lower() == 'mb'):
div_unit = 1024 * 1024
elif (unit.lower() == 'gb'):
div_unit = 1024 * 1024 * 1024
elif (unit.lower() == 'tb'):
div_unit = 1024 * 1024 * 1024 * 1024
else:
unit = 'b'
div_unit = 1
total = 0
total_expected = 0
columns = self.get_columns()
values = self.aggregate(func = ["count"], columns = columns).transpose().values
values["index"] = ["expected_size ({})".format(unit), "max_size ({})".format(unit), "type"]
for column in columns:
ctype = self[column].ctype()
if (ctype[0:4] == "date") or (ctype[0:4] == "time") or (ctype[0:8] == "interval"):
maxsize, expsize = 8, 8
elif (ctype[0:3] == "int"):
maxsize, expsize = 64, self[column].store_usage()
elif (ctype[0:4] == "bool"):
maxsize, expsize = 1, 1
elif (ctype[0:5] == "float"):
maxsize, expsize = 8, 8
elif (ctype[0:7] == "numeric"):
size = sum([int(item) for item in ctype.split("(")[1].split(")")[0].split(",")])
maxsize, expsize = size, size
elif (ctype[0:7] == "varchar"):
size = int(ctype.split("(")[1].split(")")[0])
maxsize, expsize = size, self[column].store_usage()
elif (ctype[0:4] == "char"):
size = int(ctype.split("(")[1].split(")")[0])
maxsize, expsize = size, size
else:
maxsize, expsize = 80, self[column].store_usage()
maxsize /= div_unit
expsize /= div_unit
values[column] = [expsize, values[column][0] * maxsize, ctype]
total_expected += values[column][0]
total += values[column][1]
values["separator"] = [len(columns) * self.shape()[0] / div_unit, len(columns) * self.shape()[0] / div_unit, ""]
total += values["separator"][0]
total_expected += values["separator"][0]
values["header"] = [(sum([len(item) for item in columns]) + len(columns)) / div_unit, (sum([len(item) for item in columns]) + len(columns)) / div_unit, ""]
total += values["header"][0]
total_expected += values["header"][0]
values["rawsize"] = [total_expected, total, ""]
return (tablesample(values = values, table_info = False).transpose())
#
def fillna(self,
val: dict = {},
method: dict = {},
numeric_only: bool = False,
print_info: bool = False):
if (not(val) and not(method)):
for column in self.get_columns():
if (numeric_only):
if self[column].isnum():
self[column].fillna(method = "auto", print_info = print_info)
else:
self[column].fillna(method = "auto", print_info = print_info)
else:
for column in val:
self[column].fillna(val = val[column], print_info = print_info)
for column in method:
self[column].fillna(method = method[column], print_info = print_info)
return (self)
#
def filter(self,
expr: str = "",
conditions: list = [],
print_info: bool = True):
count = self.shape()[0]
if not(expr):
for condition in conditions:
self.filter(expr = condition, print_info = False)
count -= self.shape()[0]
if (count > 1):
if (print_info):
print("{} elements were filtered".format(count))
self.history += ["{" + time.strftime("%c") + "} " + "[Filter]: {} elements were filtered using the filter '{}'".format(count, conditions)]
elif (count == 1):
if (print_info):
print("{} element was filtered".format(count))
self.history += ["{" + time.strftime("%c") + "} " + "[Filter]: {} element was filtered using the filter '{}'".format(count, conditions)]
else:
if (print_info):
print("Nothing was filtered.")
else:
max_pos = 0
for column in self.columns:
max_pos = max(max_pos, len(self[column].transformations) - 1)
self.where += [(expr, max_pos)]
try:
count -= self.shape()[0]
except:
del self.where[-1]
if (print_info):
print("/!\\ Warning: The expression '{}' is incorrect.\nNothing was filtered.".format(expr))
if (count > 1):
if (print_info):
print("{} elements were filtered".format(count))
self.history += ["{" + time.strftime("%c") + "} " + "[Filter]: {} elements were filtered using the filter '{}'".format(count, expr)]
elif (count == 1):
if (print_info):
print("{} element was filtered".format(count))
self.history += ["{" + time.strftime("%c") + "} " + "[Filter]: {} element was filtered using the filter '{}'".format(count, expr)]
else:
del self.where[-1]
if (print_info):
print("Nothing was filtered.")
return (self)
#
def first(self, ts: str, offset: str):
ts = '"' + ts.replace('"', '') + '"'
query = "SELECT (MIN({}) + '{}'::interval)::varchar FROM {}".format(ts, offset, self.genSQL())
first_date = self.cursor.execute(query).fetchone()[0]
expr = "{} <= '{}'".format(ts, first_date)
self.filter(expr)
return (self)
#
def get_columns(self):
columns = [column for column in self.columns]
for column in self.exclude_columns:
if column in columns:
columns.remove(column)
return(columns)
#
def groupby(self, columns: list, expr: list = []):
columns = ['"' + column.replace('"', '') + '"' for column in columns]
query = "SELECT {}".format(", ".join(columns + expr)) + " FROM {} GROUP BY {}".format(self.genSQL(), ", ".join(columns))
return (self.vdf_from_relation("(" + query + ") groupby_table", "groupby", "[Groupby]: The columns were group by {}".format(", ".join(columns))))
#
def head(self, limit: int = 5):
return (self.tail(limit = limit))
#
def hexbin(self,
columns: list,
method: str = "count",
of: str = "",
cmap: str = '',
gridsize: int = 10,
color: str = "white"):
if not(cmap):
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list("vml", ["#FFFFFF", "#214579"], N = 1000)
from vertica_ml_python.plot import hexbin
hexbin(self, columns, method, of, cmap, gridsize, color)
return (self)
#
def hist(self,
columns: list,
method: str = "density",
of: str = "",
max_cardinality: tuple = (6, 6),
h: tuple = (None, None),
limit_distinct_elements: int = 200,
hist_type: str = "auto"):
stacked = True if (hist_type.lower() == "stacked") else False
multi = True if (hist_type.lower() == "multi") else False
if (len(columns) == 1):
self[columns[0]].hist(method, of, 6, 0, 0)
else:
if (multi):
from vertica_ml_python.plot import multiple_hist
h_0 = h[0] if (h[0]) else 0
multiple_hist(self, columns, method, of, h_0)
else:
from vertica_ml_python.plot import hist2D
hist2D(self, columns, method, of, max_cardinality, h, limit_distinct_elements, stacked)
return (self)
#
def info(self):
if (len(self.history) == 0):
print("The vDataframe was never modified.")
elif (len(self.history)==1):
print("The vDataframe was modified with only one action: ")
print(" * "+self.history[0])
else:
print("The vDataframe was modified many times: ")
for modif in self.history:
print(" * "+modif)
return (self)
#
def isin(self, val: dict):
n = len(val[list(val.keys())[0]])
isin = []
for i in range(n):
tmp_query = []
for column in val:
if (val[column][i] == None):
tmp_query += ['"' + column.replace('"', '') + '"' + " IS NULL"]
else:
tmp_query += ['"' + column.replace('"', '') + '"' + " = '{}'".format(val[column][i])]
query = "SELECT * FROM {} WHERE ".format(self.genSQL()) + " AND ".join(tmp_query) + " LIMIT 1"
isin += [self.cursor.execute(query).fetchone() != None]
return (isin)
#
def join(self,
input_relation: str = "",
vdf = None,
on: dict = {},
how: str = 'natural',
expr1: list = [],
expr2: list = []):
on_join = ["x." + elem + " = y." + on[elem] for elem in on]
on_join = " AND ".join(on_join)
on_join = " ON " + on_join if (on_join) else ""
first_relation = self.genSQL(final_table_name = "x")
second_relation = input_relation + " AS y" if not(vdf) else vdf.genSQL(final_table_name = "y")
expr1 = ["x.{}".format(elem) for elem in expr1]
expr2 = ["y.{}".format(elem) for elem in expr2]
expr = expr1 + expr2
expr = "*" if not(expr) else ", ".join(expr)
table = "SELECT {} FROM {} {} JOIN {} {}".format(expr, first_relation, how.upper(), second_relation, on_join)
return (self.vdf_from_relation("(" + table + ") join_table", "join", "[Join]: Two relations were joined together"))
#
def kurt(self, columns: list = []):
return self.kurtosis(columns = columns)
def kurtosis(self, columns: list = []):
stats = self.statistics(columns = columns, skew_kurt_only = True)
for column in stats.values:
del(stats.values[column][0])
return (stats.transpose())
#
def last(self, ts: str, offset: str):
ts = '"' + ts.replace('"', '') + '"'
query = "SELECT (MAX({}) - '{}'::interval)::varchar FROM {}".format(ts, offset, self.genSQL())
last_date = self.cursor.execute(query).fetchone()[0]
expr = "{} >= '{}'".format(ts, last_date)
self.filter(expr)
return (self)
#
def load(self, offset: int = -1):
save = self.saving[offset]
vdf = {}
exec(save, globals(), vdf)
vdf = vdf["vdf_save"]
vdf.cursor = self.cursor
return (vdf)
#
def mad(self, columns = []):
return (self.aggregate(func = ["mad"], columns = columns))
#
def max(self, columns = []):
return (self.aggregate(func = ["max"], columns = columns))
#
def mean(self, columns = []):
return (self.aggregate(func = ["avg"], columns = columns))
#
def median(self, columns = []):
return (self.aggregate(func = ["median"], columns = columns))
#
def memory_usage(self):
import sys
total = sys.getsizeof(self.columns) + sys.getsizeof(self.where) + sys.getsizeof(self.history) + sys.getsizeof(self.main_relation)
total += sys.getsizeof(self.input_relation) + sys.getsizeof(self.schema) + sys.getsizeof(self.dsn) + sys.getsizeof(self)
total += sys.getsizeof(self.query_on) + sys.getsizeof(self.exclude_columns)
values = {"index": [], "value": []}
values["index"] += ["object"]
values["value"] += [total]
for column in self.columns:
values["index"] += [column]
values["value"] += [self[column].memory_usage()]
total += self[column].memory_usage()
values["index"] += ["total"]
values["value"] += [total]
return (tablesample(values = values, table_info = False))
#
def min(self, columns = []):
return (self.aggregate(func = ["min"], columns = columns))
#
def normalize(self, columns = [], method = "zscore"):
columns = self.numcol() if not(columns) else ['"' + column.replace('"', '') + '"' for column in columns]
for column in columns:
self[column].normalize(method = method)
return (self)
#
def numcol(self):
columns = []
for column in self.get_columns():
if self[column].isnum():
columns += [column]
return (columns)
#
def outliers(self,
columns: list = [],
name: str = "distribution_outliers",
threshold: float = 3.0):
columns = ['"' + column.replace('"', '') + '"' for column in columns] if (columns) else self.numcol()
result = self.aggregate(func = ["std", "avg"], columns = columns).values
conditions = []
for idx, elem in enumerate(result["index"]):
conditions += ["ABS({} - {}) / {} > {}".format(elem, result["avg"][idx], result["std"][idx], threshold)]
self.eval(name, "(CASE WHEN {} THEN 1 ELSE 0 END)".format(" OR ".join(conditions)))
return (self)
#
def pivot_table(self,
columns: list,
method: str = "count",
of: str = "",
h: tuple = (None, None),
max_cardinality: tuple = (20, 20),
show: bool = True,
cmap: str = '',
limit_distinct_elements: int = 1000,
with_numbers: bool = True):
if not(cmap):
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list("vml", ["#FFFFFF", "#214579"], N = 1000)
from vertica_ml_python.plot import pivot_table
return (pivot_table(self, columns, method, of, h, max_cardinality, show, cmap, limit_distinct_elements, with_numbers))
#
def plot(self,
ts: str,
columns: list = [],
start_date: str = "",
end_date: str = ""):
from vertica_ml_python.plot import multi_ts_plot
multi_ts_plot(self, ts, columns, start_date, end_date)
return (self)
#
def prod(self, columns = []):
return (self.product(columns = columns))
def product(self, columns = []):
return (self.aggregate(func = ["prod"], columns = columns))
#
def quantile(self, q: list, columns = []):
return (self.aggregate(func = ["{}%".format(float(item)*100) for item in q], columns = columns))
#
def rank(self, order_by: list, method: str = "first", by: list = [], name = ""):
if (method not in ('first', 'dense', 'percent')):
raise ValueError("The parameter 'method' must be in first|dense|percent")
elif (method == "first"):
func = "RANK"
elif (method == "dense"):
func = "DENSE_RANK"
elif (method == "percent"):
func = "PERCENT_RANK"
partition = "" if not(by) else "PARTITION BY " + ", ".join(['"' + column.replace('"', '') + '"' for column in by])
name_prefix = "_".join([column.replace('"', '') for column in order_by])
name_prefix += "_by_" + "_".join([column.replace('"', '') for column in by]) if (by) else ""
name = name if (name) else method + "_rank_" + name_prefix
order = "ORDER BY {}".format(", ".join(['"' + column.replace('"', '') + '"' for column in order_by]))
expr = "{}() OVER ({} {})".format(func, partition, order)
return (self.eval(name = name, expr = expr))
#
def rolling(self,
name: str,
aggr: str,
column: str,
preceding,
following,
expr: str = "",
by: list = [],
order_by: list = [],
method: str = "rows"):
rule_p, rule_f = "PRECEDING", "FOLLOWING"
if type(preceding) in (tuple, list):
rule_p = "FOLLOWING" if (preceding[1] in ("following", "f", 1)) else "PRECEDING"
preceding = preceding[0]
if type(following) in (tuple, list):
rule_f = "PRECEDING" if (following[1] in ("preceding", "p", 1)) else "FOLLOWING"
following = following[0]
if (method not in ('range', 'rows')):
raise ValueError("The parameter 'method' must be in rows|range")
column = '"' + column.replace('"', '') + '"'
by = "" if not(by) else "PARTITION BY " + ", ".join(['"' + col.replace('"', '') + '"' for col in by])
order_by = [column] if not(order_by) else ['"' + column.replace('"', '') + '"' for column in order_by]
expr = "{}({})".format(aggr.upper(), column) if not(expr) else expr.replace("{}", column)
expr = expr + " #" if '#' not in expr else expr
if (method == "rows"):
preceding = "{}".format(preceding) if (str(preceding).upper() != "UNBOUNDED") else "UNBOUNDED"
following = "{}".format(following) if (str(following).upper() != "UNBOUNDED") else "UNBOUNDED"
else:
preceding = "'{}'".format(preceding) if (str(preceding).upper() != "UNBOUNDED") else "UNBOUNDED"
following = "'{}'".format(following) if (str(following).upper() != "UNBOUNDED") else "UNBOUNDED"
preceding, following = "{} {}".format(preceding, rule_p), "{} {}".format(following, rule_f)
expr = expr.replace('#'," OVER ({} ORDER BY {} {} BETWEEN {} AND {})".format(by, ", ".join(order_by), method.upper(), preceding, following))
return (self.eval(name = name, expr = expr))
#
def sample(self, x: float):
query = "SELECT {} FROM (SELECT *, RANDOM() AS random FROM {}) x WHERE random < {}".format(", ".join(self.get_columns()), self.genSQL(), x)
sample = to_tablesample(query, self.cursor)
sample.name = "Sample({}) of ".format(x) + self.input_relation
for column in sample.values:
sample.dtype[column] = self[column].ctype()
return (sample)
#
def save(self):
save = 'vdf_save = vDataframe("", empty = True)'
save += '\nvdf_save.dsn = "{}"'.format(self.dsn)
save += '\nvdf_save.input_relation = "{}"'.format(self.input_relation)
save += '\nvdf_save.main_relation = "{}"'.format(self.main_relation)
save += '\nvdf_save.schema = "{}"'.format(self.schema)
save += '\nvdf_save.columns = {}'.format(self.columns)
save += '\nvdf_save.exclude_columns = {}'.format(self.exclude_columns)
save += '\nvdf_save.where = {}'.format(self.where)
save += '\nvdf_save.query_on = {}'.format(self.query_on)
save += '\nvdf_save.time_on = {}'.format(self.time_on)
save += '\nvdf_save.order_by = {}'.format(self.order_by)
save += '\nvdf_save.history = {}'.format(self.history)
save += '\nvdf_save.saving = {}'.format(self.saving)
for column in self.columns:
save += '\nsave_vColumn = vColumn(\'{}\', parent = vdf_save, transformations = {})'.format(column, self[column].transformations)
save += '\nsetattr(vdf_save, \'{}\', save_vColumn)'.format(column)
save += '\nsetattr(vdf_save, \'{}\', save_vColumn)'.format(column[1:-1])
self.saving += [save]
return (self)
#
def scatter(self,
columns: list,
catcol: str = "",
max_cardinality: int = 3,
cat_priority: list = [],
with_others: bool = True,
max_nb_points: int = 20000):
catcol = [catcol] if (catcol) else []
if (len(columns) == 2):
from vertica_ml_python.plot import scatter2D
scatter2D(self, columns + catcol, max_cardinality, cat_priority, with_others, max_nb_points)
elif (len(columns) == 3):
from vertica_ml_python.plot import scatter3D
scatter3D(self, columns + catcol, max_cardinality, cat_priority, with_others, max_nb_points)
else:
raise ValueError("The parameter 'columns' must be a list of 2 or 3 columns")
return (self)
#
def scatter_matrix(self, columns: list = []):
from vertica_ml_python.plot import scatter_matrix
scatter_matrix(self, columns)
return (self)
#
def select(self, columns: list):
copy_vDataframe = self.copy()
columns = ['"' + column.replace('"', '') + '"' for column in columns]
for column in copy_vDataframe.get_columns():
column_tmp = '"' + column.replace('"', '') + '"'
if (column_tmp not in columns):
copy_vDataframe[column_tmp].drop(add_history = False)
return (copy_vDataframe)
#
def sem(self, columns = []):
return (self.aggregate(func = ["sem"], columns = columns))
#
def sessionize(self,
ts: str,
by: list = [],
session_threshold = "30 minutes",
name = "session_id"):
partition = "PARTITION BY {}".format(", ".join(['"' + column.replace('"', '') + '"' for column in by])) if (by) else ""
expr = "CONDITIONAL_TRUE_EVENT({} - LAG({}) > '{}') OVER ({} ORDER BY {})".format(ts, ts, session_threshold, partition, ts)
return (self.eval(name = name, expr = expr))
#
def set_cursor(self, cursor):
self.cursor = cursor
return (self)
#
def set_dsn(self, dsn: str):
self.dsn = dsn
return (self)
#
def shape(self):
query = "SELECT COUNT(*) FROM {}".format(self.genSQL())
self.cursor.execute(query)
return (self.cursor.fetchone()[0], len(self.get_columns()))
#
def skew(self, columns: list = []):
return self.skewness(columns = columns)
def skewness(self, columns: list = []):
stats = self.statistics(columns = columns, skew_kurt_only = True)
for column in stats.values:
del(stats.values[column][1])
return (stats.transpose())
#
def sort(self, columns: list):
columns = ['"' + column.replace('"', '') + '"' for column in columns]
max_pos = 0
for column in columns:
if (column not in self.get_columns()):
raise NameError("The column {} doesn't exist".format(column))
for column in self.columns:
max_pos = max(max_pos, len(self[column].transformations) - 1)
for column in columns:
self.order_by += [(column, max_pos)]
return (self)
#
def sql_on_off(self):
self.query_on = not(self.query_on)
return (self)
#
def statistics(self,
columns: list = [],
skew_kurt_only: bool = False):
columns = self.numcol() if not(columns) else ['"' + column.replace('"', '') + '"' for column in columns]
query = []
if (skew_kurt_only):
stats = self.aggregate(func = ["count", "avg", "stddev"], columns = columns).transpose()
else:
stats = self.aggregate(func = ["count", "avg", "stddev", "min", "10%", "25%", "median", "75%", "90%", "max"], columns = columns).transpose()
for column in columns:
for k in range(3, 5):
expr = "AVG(POWER(({} - {}) / {}, {}))".format(column, stats.values[column][1], stats.values[column][2], k)
count = stats.values[column][0]
expr += "* {} - 3 * {}".format(count * count * (count + 1) / (count - 1) / (count - 2) / (count - 3), (count -1) * (count - 1) / (count - 2) / (count - 3)) if (k == 4) else "* {}".format(count * count / (count - 1) / (count - 2))
query += [expr]
query = "SELECT {} FROM {}".format(', '.join(query), self.genSQL())
self.executeSQL(query, title = "COMPUTE KURTOSIS AND SKEWNESS")
result = [item for item in self.cursor.fetchone()]
if (skew_kurt_only):
values = {"index" : []}
for column in columns:
values[column] = []
stats = tablesample(values = values, table_info = False)
i = 0
for column in columns:
stats.values[column] += result[i:i + 2]
i += 2
stats.values["index"] += ["skewness", "kurtosis"]
return (stats)
#
def std(self, columns = []):
return (self.aggregate(func = ["stddev"], columns = columns))
#
def sum(self, columns = []):
return (self.aggregate(func = ["sum"], columns = columns))
#
def tail(self, limit: int = 5, offset: int = 0):
tail = to_tablesample("SELECT * FROM {} LIMIT {} OFFSET {}".format(self.genSQL(), limit, offset), self.cursor)
tail.count = self.shape()[0]
tail.offset = offset
tail.name = self.input_relation
for column in tail.values:
tail.dtype[column] = self[column].ctype()
return (tail)
#
def time_on_off(self):
self.time_on = not(self.time_on)
return (self)
#
def to_csv(self,
name: str,
path: str = '',
sep: str = ',',
na_rep: str = '',
quotechar: str = '"',
usecols: list = [],
header: bool = True,
new_header: list = [],
order_by: list = [],
nb_row_per_work: int = 0):
file = open("{}{}.csv".format(path, name), "w+")
columns = self.get_columns() if not(usecols) else ['"' + column.replace('"', '') + '"' for column in usecols]
if (new_header) and (len(new_header) != len(columns)):
raise ValueError("The header has an incorrect number of columns")
elif (new_header):
file.write(sep.join(new_header))
elif (header):
file.write(sep.join([column.replace('"', '') for column in columns]))
total = self.shape()[0]
current_nb_rows_written = 0
limit = total if (nb_row_per_work <= 0) else nb_row_per_work
while (current_nb_rows_written < total):
result = self.cursor.execute("SELECT {} FROM {} LIMIT {} OFFSET {}".format(", ".join(columns), self.genSQL(), limit, current_nb_rows_written)).fetchall()
for row in result:
tmp_row = []
for item in row:
if (type(item) == str):
tmp_row += [quotechar + item + quotechar]
elif (item == None):
tmp_row += [na_rep]
else:
tmp_row += [str(item)]
file.write("\n" + sep.join(tmp_row))
current_nb_rows_written += limit
file.close()
return (self)
#
def to_db(self,
name: str,
usecols: list = [],
relation_type: str = "view",
inplace: bool = False):
if (relation_type not in ["view","temporary","table"]):
raise ValueError("The parameter mode must be in view|temporary|table\nNothing was saved.")
if (relation_type == "temporary"):
relation_type += " table"
usecols = "*" if not(usecols) else ", ".join(['"' + column.replace('"', '') + '"' for column in usecols])
query = "CREATE {} {} AS SELECT {} FROM {}".format(relation_type.upper(), name, usecols, self.genSQL())
self.executeSQL(query = query, title = "Create a new " + relation_type + " to save the vDataframe")
self.history += ["{" + time.strftime("%c") + "} " + "[Save]: The vDataframe was saved into a {} named '{}'.".format(relation_type, name)]
if (inplace):
query_on, time_on, history, saving = self.query_on, self.time_on, self.history, self.saving
self.__init__(name, self.cursor)
self.history = history
self.query_on = query_on
self.time_on = time_on
return (self)
#
def to_pandas(self):
import pandas as pd
query = "SELECT * FROM {}".format(self.genSQL())
self.cursor.execute(query)
column_names = [column[0] for column in self.cursor.description]
query_result = self.cursor.fetchall()
data = [list(item) for item in query_result]
df = pd.DataFrame(data)
df.columns = column_names
return (df)
#
def to_vdf(self, name: str):
self.save()
file = open("{}.vdf".format(name), "w+")
file.write(self.saving[-1])
file.close()
return (self)
#
def var(self, columns = []):
return (self.aggregate(func = ["variance"], columns = columns))
#
def vdf_from_relation(self, table: str, func: str, history: str):
vdf = vDataframe("", empty = True)
vdf.dsn = self.dsn
vdf.input_relation = self.input_relation
vdf.main_relation = table
vdf.schema = self.schema
vdf.cursor = self.cursor
vdf.query_on = self.query_on
vdf.time_on = self.time_on
self.executeSQL(query = "DROP TABLE IF EXISTS _vpython_{}_test_; CREATE TEMPORARY TABLE _vpython_{}_test_ AS SELECT * FROM {} LIMIT 10;".format(func, func, table), title = "Test {}".format(func))
self.executeSQL(query = "SELECT column_name, data_type FROM columns where table_name = '_vpython_{}_test_'".format(func), title = "SELECT NEW DATA TYPE AND THE COLUMNS NAME")
result = self.cursor.fetchall()
self.executeSQL(query = "DROP TABLE IF EXISTS _vpython_{}_test_;".format(func), title = "DROP TEMPORARY TABLE")
vdf.columns = ['"' + item[0] + '"' for item in result]
vdf.where = []
vdf.order_by = []
vdf.exclude_columns = []
vdf.history = [item for item in self.history] + [history]
vdf.saving = [item for item in self.saving]
for column, ctype in result:
column = '"' + column + '"'
new_vColumn = vColumn(column, parent = vdf, transformations = [(column, ctype, category_from_type(ctype = ctype))])
setattr(vdf, column, new_vColumn)
setattr(vdf, column[1:-1], new_vColumn)
return (vdf)
#
#
#
#
#
#
#
def help(self):
print("#############################")
print("# #")
print("# Vertica Virtual Dataframe #")
print("# #")
print("#############################")
print("")
print("The vDataframe is a Python object which will keep in mind all the user modifications in order "
+"to use an optimised SQL query. It will send the query to the database which will use its "
+"aggregations to compute fast results. It is created using a view or a table stored in the "
+"user database and a database cursor. It will create for each column of the table a vColumn (Vertica"
+" Virtual Column) which will store for each column its name, its imputations and allows to do easy "
+"modifications and explorations.")
print("")
print("vColumn and vDataframe coexist and one can not live without the other. vColumn will use the vDataframe information and reciprocally."
+" It is imperative to understand both structures to know how to use the entire object.")
print("")
print("When the user imputes or filters the data, the vDataframe gets in memory all the transformations to select for each query "
+"the needed data in the input relation.")
print("")
print("As the vDataframe will try to keep in mind where the transformations occurred in order to use the appropriate query,"
+" it is highly recommended to save the vDataframe when the user has done a lot of transformations in order to gain in efficiency"
+" (using the save method). We can also see all the modifications using the history method.")
print("")
print("If you find any difficulties using vertica_ml_python, please contact me: [email protected] / I'll be glad to help.")
print("")
print("For more information about the different methods or the entire vDataframe structure, please see the entire documentation")
#
def version(self):
version = self.cursor.execute("SELECT version();").fetchone()[0]
print("############################################################################################################")
print("# __ __ ___ ____ ______ ____ __ ____ ___ ___ _ ____ __ __ ______ __ __ ___ ____ #")
print("# | | | / _| \| | | / ]/ | | | | | | \| | | | | |/ \| \ #")
print("# | | |/ [_| D | || | / /| o | | _ _ | | | o | | | | | | | _ | #")
print("# | | | _| /|_| |_|| |/ / | | | \_/ | |___ | _/| ~ |_| |_| _ | O | | | #")
print("# | : | [_| \ | | | / \_| _ | | | | | | | |___, | | | | | | | | | #")
print("# \ /| | . \ | | | \ | | | | | | | | | | | | | | | | | | | #")
print("# \_/ |_____|__|\_| |__| |____\____|__|__| |___|___|_____| |__| |____/ |__| |__|__|\___/|__|__| #")
print("# #")
print("############################################################################################################")
print("#")
print("# Author: Badr Ouali, Datascientist at Vertica")
print("#")
print("# You are currently using "+version)
print("#")
version = version.split("Database v")
version_id = int(version[1][0])
version_release = int(version[1][2])
if (version_id > 8):
print("# You have a perfectly adapted version for using vDataframe and Vertica ML")
elif (version_id == 8):
if (version_release > 0):
print("# Your Vertica version is adapted for using vDataframe but you are quite limited for Vertica ML")
print("# Go to your Vertica version documentation for more information")
print("# /!\\ Some vDataframe queries can be really big because of the unavailability of a lot of functions")
print("# /!\\ Some vDataframe functions could not work")
else:
print("# Your Vertica version is adapted for using vDataframe but you can not use Vertica ML")
print("# Go to your Vertica version documentation for more information")
print("# /!\\ Some vDataframe queries can be really big because of the unavailability of a lot of functions")
print("# /!\\ Some vDataframe functions could not work")
print("#")
print("# For more information about the vDataframe you can use the help() method")
return (version_id, version_release)
|
------------------------------------------------------------------------
-- Document renderers
------------------------------------------------------------------------
{-# OPTIONS --guardedness #-}
module Renderer where
open import Algebra
open import Data.Bool
open import Data.Char using (Char)
open import Data.Empty
open import Data.Integer using (ℤ; +_; -[1+_]; _-_; _⊖_)
open import Data.List as List hiding ([_])
open import Data.List.NonEmpty using (_∷⁺_)
open import Data.List.Properties
open import Data.Nat
open import Data.Product
open import Data.String as String using (String)
open import Data.Unit
open import Function
open import Function.Equality using (_⟨$⟩_)
open import Function.Inverse using (module Inverse)
open import Relation.Binary.PropositionalEquality as P using (_≡_)
open import Relation.Nullary
open import Tactic.MonoidSolver
private
module LM {A : Set} = Monoid (++-monoid A)
open import Grammar.Infinite as G hiding (_⊛_; _<⊛_; _⊛>_)
open import Pretty using (Doc; Docs; Pretty-printer)
open Pretty.Doc
open Pretty.Docs
open import Utilities
------------------------------------------------------------------------
-- Renderers
record Renderer : Set₁ where
field
-- The function that renders.
render : ∀ {A} {g : Grammar A} {x : A} → Doc g x → List Char
-- The rendered string must be parsable.
parsable : ∀ {A} {g : Grammar A} {x : A}
(d : Doc g x) → x ∈ g · render d
----------------------------------------------------------------------
-- Some derived definitions and properties
-- Pretty-printers are correct by definition, for any renderer,
-- assuming that the underlying grammar is unambiguous.
correct :
∀ {A} {g : Grammar A} (pretty : Pretty-printer g) →
∀ x → x ∈ g · render (pretty x)
correct pretty x = parsable (pretty x)
correct-if-locally-unambiguous :
∀ {A} {g : Grammar A} →
(parse : Parser g) (pretty : Pretty-printer g) →
∀ x →
Locally-unambiguous g (render (pretty x)) →
∃ λ p → parse (render (pretty x)) ≡ yes (x , p)
correct-if-locally-unambiguous parse pretty x unambiguous = c
where
c : ∃ λ p → parse (render (pretty x)) ≡ yes (x , p)
c with parse (render (pretty x))
c | no no-parse = ⊥-elim (no-parse (x , correct pretty x))
c | yes (y , y∈g) with unambiguous y∈g (correct pretty x)
c | yes (.x , x∈g) | P.refl = (x∈g , P.refl)
correct-if-unambiguous :
∀ {A} {g : Grammar A} →
Unambiguous g → (parse : Parser g) (pretty : Pretty-printer g) →
∀ x → ∃ λ p → parse (render (pretty x)) ≡ yes (x , p)
correct-if-unambiguous unambiguous parse pretty x =
correct-if-locally-unambiguous parse pretty x unambiguous
-- If there is only one grammatically correct string, then the
-- renderer returns this string.
render-unique-string : ∀ {A} {g : Grammar A} {x s} →
(∀ {s′} → x ∈ g · s′ → s′ ≡ s) →
(d : Doc g x) → render d ≡ s
render-unique-string unique d = unique (parsable d)
-- Thus, in particular, documents for the grammar "string s" are
-- always rendered in the same way.
render-string : ∀ {s s′} (d : Doc (string s) s′) → render d ≡ s
render-string = render-unique-string λ s′∈ →
P.sym $ proj₂ (Inverse.to string-sem′ ⟨$⟩ s′∈)
-- The property of ignoring (top-level) emb constructors.
Ignores-emb : Set₁
Ignores-emb =
∀ {A B x y} {g₁ : Grammar A} {g₂ : Grammar B}
{f : ∀ {s} → x ∈ g₁ · s → y ∈ g₂ · s} {d : Doc g₁ x} →
render (emb f d) ≡ render d
-- If the renderer ignores emb constructors then, for every valid
-- string, there is a document that renders as that string. (The
-- renderers below ignore emb.)
every-string-possible :
Ignores-emb →
∀ {A} {g : Grammar A} {x s} →
x ∈ g · s → ∃ λ (d : Doc g x) → render d ≡ s
every-string-possible ignores-emb {g = g} {x} {s} x∈ =
(Pretty.embed lemma₁ text , lemma₂)
where
open P.≡-Reasoning
lemma₁ : ∀ {s′} → s ∈ string s · s′ → x ∈ g · s′
lemma₁ s∈ = cast (proj₂ (Inverse.to string-sem′ ⟨$⟩ s∈)) x∈
lemma₂ = begin
render (Pretty.embed lemma₁ text) ≡⟨ ignores-emb ⟩
render text ≡⟨ render-string _ ⟩
s ∎
------------------------------------------------------------------------
-- An example renderer
-- This renderer renders every occurrence of "line" as a single space
-- character.
ugly-renderer : Renderer
ugly-renderer = record
{ render = render
; parsable = parsable
}
where
mutual
render : ∀ {A} {g : Grammar A} {x} → Doc g x → List Char
render (d₁ ◇ d₂) = render d₁ ++ render d₂
render (text {s = s}) = s
render line = String.toList " "
render (group d) = render d
render (nest _ d) = render d
render (emb _ d) = render d
render (fill ds) = render-fills ds
render-fills : ∀ {A} {g : Grammar A} {x} → Docs g x → List Char
render-fills [ d ] = render d
render-fills (d ∷ ds) = render d ++ ' ' ∷ render-fills ds
mutual
parsable : ∀ {A x} {g : Grammar A}
(d : Doc g x) → x ∈ g · render d
parsable (d₁ ◇ d₂) = >>=-sem (parsable d₁) (parsable d₂)
parsable text = string-sem
parsable line = <$-sem single-space-sem
parsable (group d) = parsable d
parsable (nest _ d) = parsable d
parsable (emb f d) = f (parsable d)
parsable (fill ds) = parsable-fills ds
parsable-fills : ∀ {A xs} {g : Grammar A} (ds : Docs g xs) →
xs ∈ g sep-by whitespace + · render-fills ds
parsable-fills [ d ] = sep-by-sem-singleton (parsable d)
parsable-fills (d ∷ ds) =
sep-by-sem-∷ (parsable d) single-space-sem (parsable-fills ds)
-- The "ugly renderer" ignores emb constructors.
ugly-renderer-ignores-emb : Renderer.Ignores-emb ugly-renderer
ugly-renderer-ignores-emb = P.refl
------------------------------------------------------------------------
-- A general document property, proved using ugly-renderer
-- For every document of type Doc g x there is a string that witnesses
-- that the value x is generated by the grammar g.
string-exists : ∀ {A} {g : Grammar A} {x} →
Doc g x → ∃ λ s → x ∈ g · s
string-exists d = (render d , parsable d)
where open Renderer ugly-renderer
------------------------------------------------------------------------
-- An example renderer, based on the one in Wadler's "A prettier
-- printer"
module Wadler's-renderer where
-- Layouts (representations of certain strings).
data Layout-element : Set where
text : List Char → Layout-element
line : ℕ → Layout-element
Layout : Set
Layout = List Layout-element
-- Conversion of layouts into strings.
show-element : Layout-element → List Char
show-element (text s) = s
show-element (line i) = '\n' ∷ replicate i ' '
show : Layout → List Char
show = concat ∘ List.map show-element
-- Documents with unions instead of groups, and no fills. An extra
-- index—the nesting level—is also included, and the line
-- combinator's type is more precise (it can't be used for single
-- spaces, only for newline-plus-indentation).
infixr 20 _◇_
data DocN : ∀ {A} → ℕ → Grammar A → A → Set₁ where
_◇_ : ∀ {i c₁ c₂ A B x y}
{g₁ : ∞Grammar c₁ A} {g₂ : A → ∞Grammar c₂ B} →
DocN i (♭? g₁) x → DocN i (♭? (g₂ x)) y →
DocN i (g₁ >>= g₂) y
text : ∀ {i} (s : List Char) → DocN i (string s) s
line : (i : ℕ) →
let s = show-element (line i) in
DocN i (string s) s
union : ∀ {i A} {g : Grammar A} {x} →
DocN i g x → DocN i g x → DocN i g x
nest : ∀ {i A} {g : Grammar A} {x}
(j : ℕ) → DocN (j + i) g x → DocN i g x
emb : ∀ {i A B} {g₁ : Grammar A} {g₂ : Grammar B} {x y} →
(∀ {s} → x ∈ g₁ · s → y ∈ g₂ · s) →
DocN i g₁ x → DocN i g₂ y
-- Some derived combinators.
infix 21 <$>_
infixl 20 _⊛_ _⊛>_
embed : ∀ {i A B} {g₁ : Grammar A} {g₂ : Grammar B} {x y} →
(∀ {s} → x ∈ g₁ · s → y ∈ g₂ · s) → DocN i g₁ x → DocN i g₂ y
embed f (emb g d) = emb (f ∘ g) d
embed f d = emb f d
nil : ∀ {i A} {x : A} → DocN i (return x) x
nil = embed lemma (text [])
where
lemma : ∀ {x s} → [] ∈ string [] · s → x ∈ return x · s
lemma return-sem = return-sem
<$>_ : ∀ {i c A B} {f : A → B} {x} {g : ∞Grammar c A} →
DocN i (♭? g) x → DocN i (f <$> g) (f x)
<$> d = embed <$>-sem d
_⊛_ : ∀ {i c₁ c₂ A B f x} {g₁ : ∞Grammar c₁ (A → B)}
{g₂ : ∞Grammar c₂ A} →
DocN i (♭? g₁) f → DocN i (♭? g₂) x → DocN i (g₁ G.⊛ g₂) (f x)
_⊛_ {g₁ = g₁} {g₂} d₁ d₂ = embed lemma (d₁ ◇ <$> d₂)
where
lemma : ∀ {x s} →
x ∈ (g₁ >>= λ f → f <$> g₂) · s → x ∈ g₁ G.⊛ g₂ · s
lemma (>>=-sem f∈ (<$>-sem x∈)) = ⊛-sem f∈ x∈
_⊛>_ : ∀ {i c₁ c₂ A B x y} {g₁ : ∞Grammar c₁ A}
{g₂ : ∞Grammar c₂ B} →
DocN i (♭? g₁) x → DocN i (♭? g₂) y → DocN i (g₁ G.⊛> g₂) y
_⊛>_ {g₁ = g₁} {g₂} d₁ d₂ =
embed lemma (nil ⊛ d₁ ⊛ d₂)
where
lemma : ∀ {y s} →
y ∈ return (λ _ x → x) G.⊛ g₁ G.⊛ g₂ · s →
y ∈ g₁ G.⊛> g₂ · s
lemma (⊛-sem (⊛-sem return-sem x∈) y∈) = ⊛>-sem x∈ y∈
cons : ∀ {i A B} {g : Grammar A} {sep : Grammar B} {x xs} →
DocN i g x → DocN i (tt <$ sep) tt → DocN i (g sep-by sep) xs →
DocN i (g sep-by sep) (x ∷⁺ xs)
cons {g = g} {sep} d₁ d₂ d₃ =
embed lemma (<$> d₁ ⊛ (d₂ ⊛> d₃))
where
lemma : ∀ {ys s} →
ys ∈ _∷⁺_ <$> g G.⊛ ((tt <$ sep) G.⊛> (g sep-by sep)) · s →
ys ∈ g sep-by sep · s
lemma (⊛-sem (<$>-sem x∈) (⊛>-sem (<$-sem y∈) xs∈)) =
sep-by-sem-∷ x∈ y∈ xs∈
-- A single space character.
imprecise-space : ∀ {i} → DocN i (tt <$ whitespace +) tt
imprecise-space = embed lemma (text (String.toList " "))
where
lemma : ∀ {s} →
String.toList " " ∈ string′ " " · s →
tt ∈ tt <$ whitespace + · s
lemma s∈ =
cast (proj₂ (Inverse.to string-sem′ ⟨$⟩ s∈))
(<$-sem single-space-sem)
-- A variant of line that has the same type as Pretty.line (except
-- for the indentation index).
imprecise-line : (i : ℕ) → DocN i (tt <$ whitespace +) tt
imprecise-line i = embed lemma (line i)
where
replicate-lemma :
∀ i → replicate i ' ' ∈ whitespace ⋆ · replicate i ' '
replicate-lemma zero = ⋆-[]-sem
replicate-lemma (suc i) =
⋆-∷-sem (left-sem tok-sem) (replicate-lemma i)
lemma : ∀ {i s′} →
let s = show-element (line i) in
s ∈ string s · s′ → tt ∈ tt <$ whitespace + · s′
lemma s∈ =
cast (proj₂ (Inverse.to string-sem′ ⟨$⟩ s∈))
(<$-sem (+-sem (right-sem tok-sem) (replicate-lemma _)))
mutual
-- Replaces line constructors with single spaces, removes groups.
flatten : ∀ {i A} {g : Grammar A} {x} → Doc g x → DocN i g x
flatten (d₁ ◇ d₂) = flatten d₁ ◇ flatten d₂
flatten text = text _
flatten line = imprecise-space
flatten (group d) = flatten d
flatten (nest _ d) = flatten d
flatten (emb f d) = embed f (flatten d)
flatten (fill ds) = flatten-fills ds
flatten-fills : ∀ {i A} {g : Grammar A} {xs} →
Docs g xs → DocN i (g sep-by whitespace +) xs
flatten-fills [ d ] = embed sep-by-sem-singleton (flatten d)
flatten-fills (d ∷ ds) =
cons (flatten d) imprecise-space (flatten-fills ds)
mutual
-- Converts ("expands") groups to unions.
expand : ∀ {i A} {g : Grammar A} {x} → Doc g x → DocN i g x
expand (d₁ ◇ d₂) = expand d₁ ◇ expand d₂
expand text = text _
expand line = imprecise-line _
expand (group d) = union (flatten d) (expand d)
expand (nest j d) = nest j (expand d)
expand (emb f d) = embed f (expand d)
expand (fill ds) = expand-fills false ds
expand-fills : Bool → -- Unconditionally flatten the first document?
∀ {i A} {g : Grammar A} {xs} →
Docs g xs → DocN i (g sep-by whitespace +) xs
expand-fills fl [ d ] =
embed sep-by-sem-singleton (flatten/expand fl d)
expand-fills fl (d ∷ ds) =
union (cons (flatten d) imprecise-space (expand-fills true ds))
(cons (flatten/expand fl d) (imprecise-line _) (expand-fills false ds))
flatten/expand : Bool → -- Flatten?
∀ {i A} {g : Grammar A} {x} → Doc g x → DocN i g x
flatten/expand true d = flatten d
flatten/expand false d = expand d
-- Does the first line of the layout fit on a line with the given
-- number of characters?
fits : ℤ → Layout → Bool
fits -[1+ w ] _ = false
fits w [] = true
fits w (text s ∷ x) = fits (w - + length s) x
fits w (line i ∷ x) = true
module _ (width : ℕ) where
-- Chooses the first layout if it fits, otherwise the second. The
-- natural number is the current column number.
better : ℕ → Layout → Layout → Layout
better c x y = if fits (width ⊖ c) x then x else y
-- If, for any starting column c, κ c is the layout for some text,
-- then best i d κ c is the layout for the document d followed by
-- this text, given the current indentation i and the current column
-- number c.
best : ∀ {i A} {g : Grammar A} {x} →
DocN i g x → (ℕ → Layout) → (ℕ → Layout)
best (d₁ ◇ d₂) = best d₁ ∘ best d₂
best (text []) = id
best (text s) = λ κ c → text s ∷ κ (length s + c)
best (line i) = λ κ _ → line i ∷ κ i
best (union d₁ d₂) = λ κ c → better c (best d₁ κ c)
(best d₂ κ c)
best (nest _ d) = best d
best (emb _ d) = best d
-- Renders a document.
renderN : ∀ {A i} {g : Grammar A} {x} → DocN i g x → List Char
renderN d = show (best d (λ _ → []) 0)
-- Renders a document.
render : ∀ {A} {g : Grammar A} {x} → Doc g x → List Char
render d = renderN (expand {i = 0} d)
-- A simple lemma.
if-lemma :
∀ {A} {g : Grammar A} {x l₁ l₂} s b →
x ∈ g · s ++ show l₁ →
x ∈ g · s ++ show l₂ →
x ∈ g · s ++ show (if b then l₁ else l₂)
if-lemma _ true ∈l₁ ∈l₂ = ∈l₁
if-lemma _ false ∈l₁ ∈l₂ = ∈l₂
-- The main correctness property for best.
best-lemma :
∀ {c A B i} {g : Grammar A} {g′ : Grammar B} {x y κ}
s (d : DocN i g x) →
(∀ {s′ c′} → x ∈ g · s′ → y ∈ g′ · s ++ s′ ++ show (κ c′)) →
y ∈ g′ · s ++ show (best d κ c)
best-lemma s (text []) hyp = hyp return-sem
best-lemma s (text (_ ∷ _)) hyp = hyp string-sem
best-lemma s (line i) hyp = hyp string-sem
best-lemma {c} s (union d₁ d₂) hyp = if-lemma s
(fits (width ⊖ c) _)
(best-lemma s d₁ hyp)
(best-lemma s d₂ hyp)
best-lemma s (nest _ d) hyp = best-lemma s d hyp
best-lemma s (emb f d) hyp = best-lemma s d (hyp ∘ f)
best-lemma s (d₁ ◇ d₂) hyp =
best-lemma s d₁ λ {s′} f∈ →
cast (LM.assoc s _ _)
(best-lemma (s ++ s′) d₂ λ x∈ →
cast lemma
(hyp (>>=-sem f∈ x∈)))
where
lemma :
∀ {s′ s″ s‴} →
s ++ (s′ ++ s″) ++ s‴ ≡ (s ++ s′) ++ s″ ++ s‴
lemma = solve (++-monoid Char)
-- A corollary.
best-lemma′ :
∀ {A i} {g : Grammar A} {x}
(d : DocN i g x) → x ∈ g · renderN d
best-lemma′ d = best-lemma [] d (cast (P.sym $ proj₂ LM.identity _))
-- The renderer is correct.
parsable : ∀ {A} {g : Grammar A} {x}
(d : Doc g x) → x ∈ g · render d
parsable d = best-lemma′ (expand d)
-- The renderer.
wadler's-renderer : Renderer
wadler's-renderer = record
{ render = render
; parsable = parsable
}
-- The renderer ignores emb constructors.
ignores-emb :
∀ {w} → Renderer.Ignores-emb (wadler's-renderer w)
ignores-emb {d = d} with expand {i = 0} d
... | _ ◇ _ = P.refl
... | text _ = P.refl
... | line ._ = P.refl
... | union _ _ = P.refl
... | nest _ _ = P.refl
... | emb _ _ = P.refl
-- A (heterogeneous) notion of document equivalence.
infix 4 _≈_
_≈_ : ∀ {A₁ i₁ g₁} {x₁ : A₁}
{A₂ i₂ g₂} {x₂ : A₂} →
DocN i₁ g₁ x₁ → DocN i₂ g₂ x₂ → Set
d₁ ≈ d₂ = ∀ width → renderN width d₁ ≡ renderN width d₂
-- Some laws satisfied by the DocN combinators.
text-++ : ∀ {i₁ i₂} s₁ s₂ →
text {i = i₁} (s₁ ++ s₂) ≈
_⊛>_ {c₁ = false} {c₂ = false} (text {i = i₂} s₁) (text s₂)
text-++ [] [] _ = P.refl
text-++ [] (t₂ ∷ s₂) _ = P.refl
text-++ (t₁ ∷ s₁) [] _ = lemma
where
lemma : ∀ {s₁} → (s₁ ++ []) ++ [] ≡ s₁ ++ []
lemma = solve (++-monoid Char)
text-++ (t₁ ∷ s₁) (t₂ ∷ s₂) _ = lemma (_ ∷ s₁)
where
lemma : ∀ s₁ {s₂} → (s₁ ++ s₂) ++ [] ≡ s₁ ++ s₂ ++ []
lemma _ = solve (++-monoid Char)
nest-union : ∀ {A i j g} {x : A} {d₁ d₂ : DocN (j + i) g x} →
nest j (union d₁ d₂) ≈ union (nest j d₁) (nest j d₂)
nest-union _ = P.refl
union-◇ : ∀ {A B i x y c₁ c₂}
{g₁ : ∞Grammar c₁ A} {g₂ : A → ∞Grammar c₂ B}
{d₁ d₂ : DocN i (♭? g₁) x} {d₃ : DocN i (♭? (g₂ x)) y} →
_◇_ {g₁ = g₁} {g₂ = g₂} (union d₁ d₂) d₃ ≈
union (d₁ ◇ d₃) (_◇_ {g₁ = g₁} {g₂ = g₂} d₂ d₃)
union-◇ _ = P.refl
-- A law that is /not/ satisfied by the DocN combinators.
¬-◇-union :
¬ (∀ {A B i x y} c₁ c₂
{g₁ : ∞Grammar c₁ A} {g₂ : A → ∞Grammar c₂ B}
(d₁ : DocN i (♭? g₁) x) (d₂ d₃ : DocN i (♭? (g₂ x)) y) →
_◇_ {g₁ = g₁} {g₂ = g₂} d₁ (union d₂ d₃) ≈
union (d₁ ◇ d₂) (_◇_ {g₁ = g₁} {g₂ = g₂} d₁ d₃))
¬-◇-union hyp with hyp false false d₁ d₂ d₁ 0
where
d₁ = imprecise-line 0
d₂ = imprecise-space
-- The following four definitions are not part of the proof.
left : DocN 0 _ _
left = _◇_ {c₁ = false} {c₂ = false} d₁ (union d₂ d₁)
right : DocN 0 _ _
right = union (d₁ ◇ d₂) (_◇_ {c₁ = false} {c₂ = false} d₁ d₁)
-- Note that left and right are not rendered in the same way.
left-hand-string : renderN 0 left ≡ String.toList "\n\n"
left-hand-string = P.refl
right-hand-string : renderN 0 right ≡ String.toList "\n "
right-hand-string = P.refl
... | ()
-- Uses Wadler's-renderer.render to render a document using the
-- given line width.
render : ∀ {A} {g : Grammar A} {x} → ℕ → Doc g x → String
render w d = String.fromList (Wadler's-renderer.render w d)
|
C Copyright(c) 1997, Space Science and Engineering Center, UW-Madison
C Refer to "McIDAS Software Acquisition and Distribution Policies"
C in the file mcidas/data/license.txt
C *** $Id: gms5_nav.f,v 1.5 1999/04/29 17:55:13 robo Exp $ ***
*$ Name:
*$ gms5_nav - Collection of subsidary routines required by
*$ gms5.pgm and nvxgmsx.dlm/dll.
*$
SUBROUTINE SV0100( IWORD, IPOS, C, R4DAT, R8DAT)
C************************************************************
C TYPE CONVERT ROUTINE ( R-TYPE )
C************************************************************
C
implicit none
INTEGER IWORD,IPOS,IDATA1
CHARACTER C(*)*1
REAL R4DAT
DOUBLE PRECISION R8DAT
C
C=============================================================
C
R4DAT = 0.0
R8DAT = 0.D0
IF(IWORD.EQ.4) THEN
IDATA1 = ICHAR( C(1)(1:1) )/128
R8DAT = DFLOAT( MOD(ICHAR(C(1)(1:1)),128))*2.D0**(8*3)+
* DFLOAT( ICHAR(C(2)(1:1)) )*2.D0**(8*2)+
* DFLOAT( ICHAR(C(3)(1:1)) )*2.D0**(8*1)+
* DFLOAT( ICHAR(C(4)(1:1)) )
R8DAT = R8DAT/10.D0**IPOS
IF(IDATA1.EQ.1) R8DAT = -R8DAT
R4DAT = SNGL(R8DAT)
ELSEIF(IWORD.EQ.6) THEN
IDATA1 = ICHAR( C(1)(1:1) )/128
R8DAT = DFLOAT( MOD(ICHAR(C(1)(1:1)),128))*2.D0**(8*5)+
* DFLOAT( ICHAR(C(2)(1:1)) )*2.D0**(8*4)+
* DFLOAT( ICHAR(C(3)(1:1)) )*2.D0**(8*3)+
* DFLOAT( ICHAR(C(4)(1:1)) )*2.D0**(8*2)+
* DFLOAT( ICHAR(C(5)(1:1)) )*2.D0**(8*1)+
* DFLOAT( ICHAR(C(6)(1:1)) )
R8DAT = R8DAT/10.D0**IPOS
IF(IDATA1.EQ.1) R8DAT =-R8DAT
R4DAT = SNGL(R8DAT)
ENDIF
RETURN
END
SUBROUTINE SV0110( IWORD, C, I4DAT)
C******************************************************************
C TYPE CONVERT ROUTINE ( I-TYPE )
C******************************************************************
C
implicit none
INTEGER IWORD,I4DAT
CHARACTER C(*)*1
C
C====================================================================
C
I4DAT = 0
IF(IWORD.EQ.2) THEN
I4DAT = ICHAR( C(1)(1:1) )*2**(8*1)+
* ICHAR( C(2)(1:1) )
ELSEIF(IWORD.EQ.4) THEN
I4DAT = ICHAR( C(1)(1:1) )*2**(8*3)+
* ICHAR( C(2)(1:1) )*2**(8*2)+
* ICHAR( C(3)(1:1) )*2**(8*1)+
* ICHAR( C(4)(1:1) )
ENDIF
RETURN
END
SUBROUTINE SV0200( CSMT, ISMT )
C*********************************************************************
C SIMPLIFIED MAPPING DATA PROCESSING ROUTINE
C*********************************************************************
C
implicit none
CHARACTER CSMT(2500)*1
INTEGER ISMT(25,25,4)
integer il1,il2,il3,ilat,ilon,iline1,ipixe1
C
C======================================================================
C
DO 2100 IL1=1,25
DO 2200 IL2=1,25
ILAT = 60-(IL1-1)*5
ILON = 80+(IL2-1)*5
IL3 = (IL1-1)*100+(IL2-1)*4+1
ILINE1 = ICHAR(CSMT(IL3 )(1:1))*256+ICHAR(CSMT(IL3+1)(1:1))
IPIXE1 = ICHAR(CSMT(IL3+2)(1:1))*256+ICHAR(CSMT(IL3+3)(1:1))
ISMT(IL2,IL1,1) = ILAT
ISMT(IL2,IL1,2) = ILON
ISMT(IL2,IL1,3) = ILINE1
ISMT(IL2,IL1,4) = IPIXE1
2200 CONTINUE
2100 CONTINUE
RETURN
END
SUBROUTINE SV0400(RDL,RDP)
C-----------------------------------------------------------------
C MAPPING TABLE CORRECTION ROUTINE C
C-----------------------------------------------------------------
COMMON /MMAP1/DTIMS,RESLIN,RESELM,RLIC,RELMFC
COMMON /MMAP1/SENSSU,RLINE,RELMNT,VMIS,ELMIS
COMMON /MMAP1/DSPIN,ORBT1,ATIT
INTEGER ISMT(25,25,4)
REAL RESLIN(4),RESELM(4),VMIS(3),ELMIS(3,3)
REAL RLIC(4),RELMFC(4),SENSSU(4)
REAL RLINE(4),RELMNT(4)
DOUBLE PRECISION DSPIN,DTIMS,ATIT(10,10),
& ORBT1(35,8)
C
C *CORRECT ORBIT/ATTITUDE DATA
VMIS(2) = VMIS(2)-(RDL)*RESLIN(2)
VMIS(3) = VMIS(3)+(RDP)*RESELM(2)
WRITE(6,FMT='(A16,F12.8)') ' CORRECT Y-MIS :',VMIS(2)
WRITE(6,FMT='(A16,F12.8)') ' CORRECT Z-MIS :',VMIS(3)
CA = COS(VMIS(1))
CB = COS(VMIS(2))
CC = COS(VMIS(3))
SA = SIN(VMIS(1))
SB = SIN(VMIS(2))
SC = SIN(VMIS(3))
ELMIS(1,1) = CC*CB
ELMIS(2,1) = (-SC)*CB
ELMIS(3,1) = SB
ELMIS(1,2) = CC*SB*SA+SC*CA
ELMIS(2,2) = (-SC)*SB*SA+CC*CA
ELMIS(3,2) = (-CB)*SA
ELMIS(1,3) = CC*SB*CA+SC*SA
ELMIS(2,3) = (-SC)*SB*CA+CC*SA
ELMIS(3,3) = CB*CA
C *CORRECT MAPPING TABLE
DO 1000 IL1=1,25
DO 1100 IL2=1,25
ISMT(IL2,IL1,3) = ISMT(IL2,IL1,3)+NINT(RDL)
ISMT(IL2,IL1,4) = ISMT(IL2,IL1,4)+NINT(RDP)
1100 CONTINUE
1000 CONTINUE
C
RETURN
END
SUBROUTINE DECODE_OA_BLOCK( COBAT, FORM )
C************************************************************************
C ORBIT AND ATTITUDE DATA PROCESSING ROUTINE
C************************************************************************
C
implicit none
integer i,j
CHARACTER COBAT*3200, FORM*5
REAL R4DMY,RESLIN(4),RESELM(4),RLIC(4),RELMFC(4),SENSSU(4)
REAL VMIS(3),ELMIS(3,3),RLINE(4),RELMNT(4)
real SUBLAT,SUBLON
DOUBLE PRECISION R8DMY,DSPIN,DTIMS,ATIT(10,10),
& ORBT1(35,8)
C
COMMON /MMAP1/DTIMS,RESLIN,RESELM,RLIC,RELMFC
COMMON /MMAP1/SENSSU,RLINE,RELMNT,VMIS,ELMIS
COMMON /MMAP1/DSPIN,ORBT1,ATIT
COMMON /NAV1/SUBLAT, SUBLON
C
C
C=========================================================================
C
C
C Initialize Values in common block
DTIMS=0.0
DSPIN=0.0
DO 1000 I=1,4
RESLIN(I)=0.0
RESELM(I)=0.0
RLIC(I)=0.0
RELMFC(I)=0.0
SENSSU(I)=0.0
RLINE(I)=0.0
RELMNT(I)=0.0
1000 CONTINUE
DO 1100 I=1,3
VMIS(I)=0.0
DO 1200 J=1,3
ELMIS(I,J)=0.0
1200 CONTINUE
1100 CONTINUE
DO 1300 I=1,10
DO 1400 J=1,10
ATIT(I,J)=0.0
1400 CONTINUE
1300 CONTINUE
DO 1500 I=1,35
DO 1600 J=1,8
ORBT1(I,J)=0.0
1600 CONTINUE
1500 CONTINUE
CALL SV0100( 6, 8, COBAT( 1: 6), R4DMY , DTIMS )
CALL SV0100( 4, 8, COBAT( 7: 10), RESLIN(1), R8DMY )
CALL SV0100( 4, 8, COBAT( 11: 14), RESLIN(2), R8DMY )
CALL SV0100( 4, 8, COBAT( 11: 14), RESLIN(3), R8DMY )
CALL SV0100( 4, 8, COBAT( 11: 14), RESLIN(4), R8DMY )
CALL SV0100( 4,10, COBAT( 15: 18), RESELM(1), R8DMY )
CALL SV0100( 4,10, COBAT( 19: 22), RESELM(2), R8DMY )
CALL SV0100( 4,10, COBAT( 19: 22), RESELM(3), R8DMY )
CALL SV0100( 4,10, COBAT( 19: 22), RESELM(4), R8DMY )
CALL SV0100( 4, 4, COBAT( 23: 26), RLIC(1) , R8DMY )
CALL SV0100( 4, 4, COBAT( 27: 30), RLIC(2) , R8DMY )
CALL SV0100( 4, 4, COBAT(111:114), RLIC(3) , R8DMY )
CALL SV0100( 4, 4, COBAT(115:118), RLIC(4) , R8DMY )
CALL SV0100( 4, 4, COBAT( 31: 34), RELMFC(1), R8DMY )
CALL SV0100( 4, 4, COBAT( 35: 38), RELMFC(2), R8DMY )
CALL SV0100( 4, 4, COBAT(119:122), RELMFC(3), R8DMY )
CALL SV0100( 4, 4, COBAT(123:126), RELMFC(4), R8DMY )
CALL SV0100( 4, 0, COBAT( 39: 42), SENSSU(1), R8DMY )
CALL SV0100( 4, 0, COBAT( 43: 46), SENSSU(2), R8DMY )
CALL SV0100( 4, 0, COBAT( 43: 46), SENSSU(3), R8DMY )
CALL SV0100( 4, 0, COBAT( 43: 46), SENSSU(4), R8DMY )
CALL SV0100( 4, 0, COBAT( 47: 50), RLINE(1) , R8DMY )
CALL SV0100( 4, 0, COBAT( 51: 54), RLINE(2) , R8DMY )
CALL SV0100( 4, 0, COBAT( 51: 54), RLINE(3) , R8DMY )
CALL SV0100( 4, 0, COBAT( 51: 54), RLINE(4) , R8DMY )
CALL SV0100( 4, 0, COBAT( 55: 58), RELMNT(1), R8DMY )
CALL SV0100( 4, 0, COBAT( 59: 62), RELMNT(2), R8DMY )
CALL SV0100( 4, 0, COBAT( 59: 62), RELMNT(3), R8DMY )
CALL SV0100( 4, 0, COBAT( 59: 62), RELMNT(4), R8DMY )
CALL SV0100( 4,10, COBAT( 63: 66), VMIS(1) , R8DMY )
CALL SV0100( 4,10, COBAT( 67: 70), VMIS(2) , R8DMY )
CALL SV0100( 4,10, COBAT( 71: 74), VMIS(3) , R8DMY )
CALL SV0100( 4, 7, COBAT( 75: 78), ELMIS(1,1), R8DMY )
CALL SV0100( 4,10, COBAT( 79: 82), ELMIS(2,1), R8DMY )
CALL SV0100( 4,10, COBAT( 83: 86), ELMIS(3,1), R8DMY )
CALL SV0100( 4,10, COBAT( 87: 90), ELMIS(1,2), R8DMY )
CALL SV0100( 4, 7, COBAT( 91: 94), ELMIS(2,2), R8DMY )
CALL SV0100( 4,10, COBAT( 95: 98), ELMIS(3,2), R8DMY )
CALL SV0100( 4,10, COBAT( 99:102), ELMIS(1,3), R8DMY )
CALL SV0100( 4,10, COBAT(103:106), ELMIS(2,3), R8DMY )
CALL SV0100( 4, 7, COBAT(107:110), ELMIS(3,3), R8DMY )
CALL SV0100( 6, 8, COBAT(241:246), R4DMY , DSPIN )
CALL SV0100( 6, 6, COBAT(199:204), SUBLON , R8DMY )
CALL SV0100( 6, 6, COBAT(205:210), SUBLAT , R8DMY )
C
DO 2000 I=1,10
IF(FORM .EQ. 'long ') J = (I-1)*64+257-1
IF(FORM .EQ. 'short') J = (I-1)*48+257-1
CALL SV0100(6, 8,COBAT( 1+J: 6+J),R4DMY,ATIT(1,I))
CALL SV0100(6, 8,COBAT(13+J:18+J),R4DMY,ATIT(3,I))
CALL SV0100(6,11,COBAT(19+J:24+J),R4DMY,ATIT(4,I))
CALL SV0100(6, 8,COBAT(25+J:30+J),R4DMY,ATIT(5,I))
CALL SV0100(6, 8,COBAT(31+J:36+J),R4DMY,ATIT(6,I))
2000 CONTINUE
C
DO 3000 I=1,8
IF(FORM .EQ. 'long ') J = (I-1)*256+897-1
IF(FORM .EQ. 'short') J = (I-1)*200+737-1
CALL SV0100(6, 8,COBAT( 1+J: 6+J),R4DMY,ORBT1( 1,I))
CALL SV0100(6, 6,COBAT( 49+J: 54+J),R4DMY,ORBT1( 9,I))
CALL SV0100(6, 6,COBAT( 55+J: 60+J),R4DMY,ORBT1(10,I))
CALL SV0100(6, 6,COBAT( 61+J: 66+J),R4DMY,ORBT1(11,I))
CALL SV0100(6, 8,COBAT( 85+J: 90+J),R4DMY,ORBT1(15,I))
CALL SV0100(6, 8,COBAT(103+J:108+J),R4DMY,ORBT1(18,I))
CALL SV0100(6, 8,COBAT(109+J:114+J),R4DMY,ORBT1(19,I))
CALL SV0100(6, 12,COBAT(129+J:134+J),R4DMY,ORBT1(20,I))
CALL SV0100(6, 14,COBAT(135+J:140+J),R4DMY,ORBT1(21,I))
CALL SV0100(6, 14,COBAT(141+J:146+J),R4DMY,ORBT1(22,I))
CALL SV0100(6, 14,COBAT(147+J:152+J),R4DMY,ORBT1(23,I))
CALL SV0100(6, 12,COBAT(153+J:158+J),R4DMY,ORBT1(24,I))
CALL SV0100(6, 16,COBAT(159+J:164+J),R4DMY,ORBT1(25,I))
CALL SV0100(6, 12,COBAT(165+J:170+J),R4DMY,ORBT1(26,I))
CALL SV0100(6, 16,COBAT(171+J:176+J),R4DMY,ORBT1(27,I))
CALL SV0100(6, 12,COBAT(177+J:182+J),R4DMY,ORBT1(28,I))
3000 CONTINUE
RETURN
END
SUBROUTINE encode_OA_block( COBAT )
C************************************************************************
C************************************************************************
C
implicit none
INTEGER iret
INTEGER encode_real4
CHARACTER COBAT*3200
REAL RESLIN(4),RESELM(4),RLIC(4),RELMFC(4),SENSSU(4)
REAL VMIS(3),ELMIS(3,3),RLINE(4),RELMNT(4)
DOUBLE PRECISION DSPIN,DTIMS,ATIT(10,10),
& ORBT1(35,8)
COMMON /MMAP1/DTIMS,RESLIN,RESELM,RLIC,RELMFC
COMMON /MMAP1/SENSSU,RLINE,RELMNT,VMIS,ELMIS
COMMON /MMAP1/DSPIN,ORBT1,ATIT
iret = encode_real4(VMIS(1),10,COBAT(63:66))
iret = encode_real4(VMIS(2),10,COBAT(67:70))
iret = encode_real4(VMIS(3),10,COBAT(71:74))
iret = encode_real4(ELMIS(1,1),7,COBAT(75:78))
iret = encode_real4(ELMIS(2,1),10,COBAT(79:82))
iret = encode_real4(ELMIS(3,1),10,COBAT(83:86))
iret = encode_real4(ELMIS(1,2),10,COBAT(87:90))
iret = encode_real4(ELMIS(2,2),7,COBAT(91:94))
iret = encode_real4(ELMIS(3,2),10,COBAT(95:98))
iret = encode_real4(ELMIS(1,3),10,COBAT(99:102))
iret = encode_real4(ELMIS(2,3),10,COBAT(103:106))
iret = encode_real4(ELMIS(3,3),7,COBAT(107:110))
return
end
SUBROUTINE SUBLATLON(LONLAT)
REAL LONLAT(*)
REAL SUBLAT
REAL SUBLON
COMMON/NAV1/SUBLAT, SUBLON
LONLAT(1) = SUBLAT
LONLAT(2) = (-1.)*SUBLON
RETURN
END
SUBROUTINE MGIVSR( IMODE,RPIX,RLIN,RLON,RLAT,RHGT,
* RINF,DSCT,IRTN)
C**************************************************************
C**************************************************************
C**************************************************************
C**************************************************************
C**************************************************************
C
C THIS PROGRAM CONVERTS GEOGRAPHICAL CO-ORDINATES (LAT,LONG,
C HEIGHT) TO VISSR IMAGE CO-ORDINATES (LINE,PIXEL) AND VICE
C VERSA.
C
C THIS PROGRAM IS PROVIDED BY THE METEOROLOGICAL SATELLITE
C CENTRE OF THE JAPAN METEOROLOGICAL AGENCY TO USERS OF GMS
C DATA.
C
C MSC TECH. NOTE NO.23
C JMA/MSC 1991
C
C**************************************************************
C**************************************************************
C**************************************************************
C**************************************************************
C I/O TYPE
C IMODE I I*4 CONVERSION MODE & IMAGE KIND
C IMAGE KIND
C GMS-4 GMS-5
C 1,-1 VIS VIS
C 2,-2 IR IR1
C 3,-3 -- IR2
C 4,-4 -- WV
C CONVERSION MODE
C 1 TO 4 (LAT,LON,HGT)=>(LINE,PIXEL)
C -1 TO -4 (LAT,LON )<=(LINE,PIXEL)
C RPIX I/O R*4 PIXEL OF POINT
C RLIN I/O R*4 LINE OF POINT
C RLON I/0 R*4 LONG. OF POINT (DEGREES,EAST:+,WEST:-)
C RLAT I/O R*4 LAT. OF POINT (DEGREES,NORTH:+,SOURTH:-)
C RHGT I R*4 HEIGHT OF POINT (METER)
C RINF(8) O R*4 (1) SATELLITE ZENITH DISTANCE (DEGREES)
C (2) SATELLITE AZIMUTH ANGLE (DEGREES)
C (3) SUN ZENITH DISTANCE (DEGREES)
C (4) SUN AZIMUTH ANGLE (DEGREES)
C (5) SATELLITE-SUN DEPARTURE ANGLE (DEG)
C (6) SATELLITE DISTANCE (METER)
C (7) SUN DISTANCE (KILOMETER)
C (8) SUN GLINT ANLGLE (DEGREES)
C DSCT O R*8 SCAN TIME (MJD)
C IRTN O I*4 RETURN CODE (0 = OK)
C
C!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
C
C
C 1. COORDINATE TRANSFORMATION PARAMETERS SEGMENT
C MAP(1,1)-MAP(672,1)
C 2. ATTITUDE PREDICTION DATA SEGMENT MAP(1,2)-MAP(672,2)
C 3. ORBIT PREDICTION DATA 1 SEGMENT MAP(1,3)-MAP(672,3)
C 4. ORBIT PREDICTION DATA 2 SEGMENT MAP(1,4)-MAP(672,4)
C*****************************************************************
C
C!!!!!!!!!!!!!!!! DEFINITION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
C
implicit none
COMMON /MMAP1/DTIMS,RESLIN,RESELM,RLIC,RELMFC
COMMON /MMAP1/SENSSU,RLINE,RELMNT,VMIS,ELMIS
COMMON /MMAP1/DSPIN,ORBT1,ATIT
C
REAL RPIX,RLIN,RLON,RLAT,RHGT,RINF(8)
INTEGER IRTN,IMODE,LMODE
C
REAL EPS,RIO,RI,RJ,RSTEP,RSAMP,RFCL,RFCP,SENS,RFTL,RFTP
REAL RESLIN(4),RESELM(4),RLIC(4),RELMFC(4),SENSSU(4)
REAL VMIS(3),ELMIS(3,3),RLINE(4),RELMNT(4)
DOUBLE PRECISION ATIT(10,10),ORBT1(35,8)
DOUBLE PRECISION BC,BETA,BS,CDR,CRD,DD,DDA,DDB,
& DDC,DEF,DK,DK1,DK2,
& DLAT,DLON,DPAI,DSPIN,DTIMS,EA,EE,EF,EN,HPAI,PC,PI,PS,
& QC,QS,RTIM,TF,TL,TP,
& SAT(3),SL(3),SLV(3),SP(3),SS(3),STN1(3),STN2(3),
& SX(3),SY(3),SW1(3),SW2(3),SW3(3),
& DSCT,DSATZ,DSATA,DSUNZ,DSUNA,DSSDA,DSATD,SUNM,SDIS,
& DLATN,DLONN,STN3(3),DSUNG,
& WKCOS,WKSIN
C
C
C
C==================================================================
C
PI = 3.141592653D0
CDR = PI/180.D0
CRD = 180.D0/PI
HPAI = PI/2.D0
DPAI = PI*2.D0
EA = 6378136.D0
EF = 1.D0/298.257D0
EPS = 1.0
C!!!!!!!!!!!!!!!!!!!!!!PARAMETER CHECK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
IRTN = 0
IF(ABS(IMODE).GT.4) IRTN = 1
IF(ABS(RLAT).GT.90. .AND. IMODE.GT.0) IRTN = 2
IF(IRTN.NE.0) RETURN
C!!!!!!!!!!!!!!!!!!!!!!VISSR FRAME INFORMATION SET!!!!!!!!!!!!!!!!!!!!!!
LMODE = ABS(IMODE)
RSTEP = RESLIN(LMODE)
RSAMP = RESELM(LMODE)
RFCL = RLIC(LMODE)
RFCP = RELMFC(LMODE)
SENS = SENSSU(LMODE)
RFTL = RLINE(LMODE)+0.5
RFTP = RELMNT(LMODE)+0.5
C!!!!!!!!!!!!!!!!!!!!!TRANSFORMATION (GEOGRAPHICAL=>VISSR)!!!!!!!!!!!!!!!
IF( IMODE.GT.0 .AND. IMODE.LT.5 ) THEN
DLAT = DBLE(RLAT)*CDR
DLON = DBLE(RLON)*CDR
EE = 2.D0*EF-EF*EF
EN = EA/DSQRT(1.D0-EE*DSIN(DLAT)*DSIN(DLAT))
STN1(1) = (EN+DBLE(RHGT))*DCOS(DLAT)*DCOS(DLON)
STN1(2) = (EN+DBLE(RHGT))*DCOS(DLAT)*DSIN(DLON)
STN1(3) = (EN*(1.D0-EE)+DBLE(RHGT))*DSIN(DLAT)
C
RIO = RFCL-ATAN(SIN(SNGL(DLAT))/(6.610689-COS(SNGL(DLAT))))
* /RSTEP
RTIM = DTIMS+DBLE(RIO/SENS/1440.)/DSPIN
C
100 CONTINUE
CALL MG1100(RTIM,CDR,SAT,SP,SS,BETA)
C-----------------------------------------------------------------------
CALL MG1220(SP,SS,SW1)
CALL MG1220(SW1,SP,SW2)
BC = DCOS(BETA)
BS = DSIN(BETA)
SW3(1) = SW1(1)*BS+SW2(1)*BC
SW3(2) = SW1(2)*BS+SW2(2)*BC
SW3(3) = SW1(3)*BS+SW2(3)*BC
CALL MG1200(SW3,SX)
CALL MG1220(SP,SX,SY)
SLV(1) = STN1(1)-SAT(1)
SLV(2) = STN1(2)-SAT(2)
SLV(3) = STN1(3)-SAT(3)
CALL MG1200(SLV,SL)
CALL MG1210(SP,SL,SW2)
CALL MG1210(SY,SW2,SW3)
CALL MG1230(SY,SW2,TP)
TF = SP(1)*SW3(1)+SP(2)*SW3(2)+SP(3)*SW3(3)
IF(TF.LT.0.D0) TP=-TP
CALL MG1230(SP,SL,TL)
C
RI = SNGL(HPAI-TL)/RSTEP+RFCL-VMIS(2)/RSTEP
RJ = SNGL(TP)/RSAMP+RFCP
* +VMIS(3)/RSAMP-SNGL(HPAI-TL)*TAN(VMIS(1))/RSAMP
C
IF(ABS(RI-RIO).GE.EPS) THEN
RTIM = DBLE(AINT((RI-1.)/SENS)+RJ*RSAMP/SNGL(DPAI))/
* (DSPIN*1440.D0)+DTIMS
RIO = RI
GOTO 100
ENDIF
RLIN = RI
RPIX = RJ
DSCT = RTIM
IF(RLIN.LT.0.OR.RLIN.GT.RFTL) IRTN=4
IF(RPIX.LT.0.OR.RPIX.GT.RFTP) IRTN=5
C
C!!!!!!!!!!!!!!!!!TRANSFORMATION (VISSR=>GEOGRAPHICAL)!!!!!!!!!!!!!!!!!!
ELSEIF(IMODE.LT.0.AND.IMODE.GT.-5) THEN
RTIM = DBLE(AINT((RLIN-1.)/SENS)+RPIX*RSAMP/SNGL(DPAI))/
* (DSPIN*1440.D0)+DTIMS
CALL MG1100(RTIM,CDR,SAT,SP,SS,BETA)
CALL MG1220(SP,SS,SW1)
CALL MG1220(SW1,SP,SW2)
BC = DCOS(BETA)
BS = DSIN(BETA)
SW3(1) = SW1(1)*BS+SW2(1)*BC
SW3(2) = SW1(2)*BS+SW2(2)*BC
SW3(3) = SW1(3)*BS+SW2(3)*BC
CALL MG1200(SW3,SX)
CALL MG1220(SP,SX,SY)
PC = DCOS(DBLE(RSTEP*(RLIN-RFCL)))
PS = DSIN(DBLE(RSTEP*(RLIN-RFCL)))
QC = DCOS(DBLE(RSAMP*(RPIX-RFCP)))
QS = DSIN(DBLE(RSAMP*(RPIX-RFCP)))
SW1(1) = DBLE(ELMIS(1,1))*PC+DBLE(ELMIS(1,3))*PS
SW1(2) = DBLE(ELMIS(2,1))*PC+DBLE(ELMIS(2,3))*PS
SW1(3) = DBLE(ELMIS(3,1))*PC+DBLE(ELMIS(3,3))*PS
SW2(1) = QC*SW1(1)-QS*SW1(2)
SW2(2) = QS*SW1(1)+QC*SW1(2)
SW2(3) = SW1(3)
SW3(1) = SX(1)*SW2(1)+SY(1)*SW2(2)+SP(1)*SW2(3)
SW3(2) = SX(2)*SW2(1)+SY(2)*SW2(2)+SP(2)*SW2(3)
SW3(3) = SX(3)*SW2(1)+SY(3)*SW2(2)+SP(3)*SW2(3)
CALL MG1200(SW3,SL)
DEF = (1.D0-EF)*(1.D0-EF)
DDA = DEF*(SL(1)*SL(1)+SL(2)*SL(2))+SL(3)*SL(3)
DDB = DEF*(SAT(1)*SL(1)+SAT(2)*SL(2))+SAT(3)*SL(3)
DDC = DEF*(SAT(1)*SAT(1)+SAT(2)*SAT(2)-EA*EA)+SAT(3)*SAT(3)
DD = DDB*DDB-DDA*DDC
IF(DD.GE.0.D0 .AND. DDA.NE.0.D0) THEN
DK1 = (-DDB+DSQRT(DD))/DDA
DK2 = (-DDB-DSQRT(DD))/DDA
ELSE
IRTN = 6
GOTO 9000
ENDIF
IF(DABS(DK1).LE.DABS(DK2)) THEN
DK = DK1
ELSE
DK = DK2
ENDIF
STN1(1) = SAT(1)+DK*SL(1)
STN1(2) = SAT(2)+DK*SL(2)
STN1(3) = SAT(3)+DK*SL(3)
DLAT = DATAN(STN1(3)/(DEF*DSQRT(STN1(1)*STN1(1)+
* STN1(2)*STN1(2))))
IF(STN1(1).NE.0.D0) THEN
DLON = DATAN(STN1(2)/STN1(1))
IF(STN1(1).LT.0.D0 .AND. STN1(2).GE.0.D0) DLON=DLON+PI
IF(STN1(1).LT.0.D0 .AND. STN1(2).LT.0.D0) DLON=DLON-PI
ELSE
IF(STN1(2).GT.0.D0) THEN
DLON=HPAI
ELSE
DLON=-HPAI
ENDIF
ENDIF
RLAT = SNGL(DLAT*CRD)
RLON = SNGL(DLON*CRD)
DSCT = RTIM
ENDIF
C
C!!!!!!!!!!!!!!!!!!!TRANSFORMATION (ZENITH/AZIMUTH)!!!!!!!!!!!!!!!
STN2(1) = DCOS(DLAT)*DCOS(DLON)
STN2(2) = DCOS(DLAT)*DSIN(DLON)
STN2(3) = DSIN(DLAT)
SLV(1) = SAT(1) -STN1(1)
SLV(2) = SAT(2) -STN1(2)
SLV(3) = SAT(3) -STN1(3)
CALL MG1200(SLV,SL)
C
CALL MG1230(STN2,SL,DSATZ)
IF(DSATZ.GT.HPAI) IRTN = 7
c write(6,7011)dsatz,hpai
c7011 format(' irtn=7,dsatz,hpai:',2f10.4)
C
SUNM = 315.253D0+0.985600D0*RTIM
SUNM = DMOD(SUNM,360.D0)*CDR
SDIS = (1.0014D0-0.01672D0*DCOS(SUNM)-0.00014*DCOS(2.D0*
* SUNM))*1.49597870D8
C
IF(DLAT.GE.0.D0) THEN
DLATN = HPAI-DLAT
DLONN = DLON-PI
IF(DLONN.LE.-PI) DLONN=DLONN+DPAI
ELSE
DLATN = HPAI+DLAT
DLONN = DLON
ENDIF
STN3(1) = DCOS(DLATN)*DCOS(DLONN)
STN3(2) = DCOS(DLATN)*DSIN(DLONN)
STN3(3) = DSIN(DLATN)
SW1(1) = SLV(1)+SS(1)*SDIS*1.D3
SW1(2) = SLV(2)+SS(2)*SDIS*1.D3
SW1(3) = SLV(3)+SS(3)*SDIS*1.D3
CALL MG1200(SW1,SW2)
CALL MG1230(STN2,SW2,DSUNZ)
CALL MG1230(SL,SW2,DSSDA)
CALL MG1240(SL,STN2,STN3,DPAI,DSATA)
CALL MG1240(SW2,STN2,STN3,DPAI,DSUNA)
DSATD = DSQRT(SLV(1)*SLV(1)+SLV(2)*SLV(2)+SLV(3)*SLV(3))
C
C
CALL MG1200(STN1,SL)
CALL MG1230(SW2,SL,DSUNG)
CALL MG1220(SL, SW2,SW3)
CALL MG1220(SW3,SL, SW1)
WKCOS=DCOS(DSUNG)
WKSIN=DSIN(DSUNG)
SW2(1)=WKCOS*SL(1)-WKSIN*SW1(1)
SW2(2)=WKCOS*SL(2)-WKSIN*SW1(2)
SW2(3)=WKCOS*SL(3)-WKSIN*SW1(3)
CALL MG1230(SW2,SLV,DSUNG)
C
RINF(6) = SNGL(DSATD)
RINF(7) = SNGL(SDIS)
RINF(1) = SNGL(DSATZ*CRD)
RINF(2) = SNGL(DSATA*CRD)
RINF(3) = SNGL(DSUNZ*CRD)
RINF(4) = SNGL(DSUNA*CRD)
RINF(5) = SNGL(DSSDA*CRD)
RINF(8) = SNGL(DSUNG*CRD)
C!!!!!!!!!!!!!!!!!!!!!!!!!STOP/END!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
9000 CONTINUE
RETURN
END
SUBROUTINE MG1100(RTIM,CDR,SAT,SP,SS,BETA)
implicit none
COMMON /MMAP1/DTIMS,RESLIN,RESELM,RLIC,RELMFC
COMMON /MMAP1/SENSSU,RLINE,RELMNT,VMIS,ELMIS
COMMON /MMAP1/DSPIN,ORBT1,ATIT
REAL RESLIN(4),RESELM(4),RLIC(4),RELMFC(4),SENSSU(4)
REAL VMIS(3),ELMIS(3,3),RLINE(4),RELMNT(4)
DOUBLE PRECISION DSPIN,DTIMS
DOUBLE PRECISION ATTALP,ATTDEL,BETA,CDR,DELT,RTIM,
& SITAGT,SUNALP,SUNDEL,
& WKCOS,WKSIN,
& ATIT(10,10),ATT1(3),ATT2(3),ATT3(3),NPA(3,3),
& ORBT1(35,8),SAT(3),SP(3),SS(3),ORBT2(35,8)
integer i
C
C
DO 1000 I=1,7
IF(RTIM.GE.ORBT1(1,I).AND.RTIM.LT.ORBT1(1,I+1)) THEN
CALL MG1110
* (I,RTIM,CDR,ORBT1,ORBT2,SAT,SITAGT,SUNALP,SUNDEL,NPA)
GOTO 1200
ENDIF
1000 CONTINUE
1200 CONTINUE
C
DO 3000 I=1,9
IF(RTIM.GE.ATIT(1,I).AND.RTIM.LT.ATIT(1,I+1)) THEN
DELT = (RTIM-ATIT(1,I))/(ATIT(1,I+1)-ATIT(1,I))
ATTALP= ATIT(3,I)+(ATIT(3,I+1)-ATIT(3,I))*DELT
ATTDEL= ATIT(4,I)+(ATIT(4,I+1)-ATIT(4,I))*DELT
BETA = ATIT(5,I)+(ATIT(5,I+1)-ATIT(5,I))*DELT
IF( (ATIT(5,I+1)-ATIT(5,I)).GT.0.D0)
* BETA = ATIT(5,I)+(ATIT(5,I+1)-ATIT(5,I)-360.D0*CDR)*DELT
GOTO 3001
ENDIF
3000 CONTINUE
3001 CONTINUE
C
WKCOS = DCOS(ATTDEL)
ATT1(1) = DSIN(ATTDEL)
ATT1(2) = WKCOS * (-DSIN(ATTALP))
ATT1(3) = WKCOS * DCOS(ATTALP)
ATT2(1) = NPA(1,1)*ATT1(1)+NPA(1,2)*ATT1(2)+NPA(1,3)*ATT1(3)
ATT2(2) = NPA(2,1)*ATT1(1)+NPA(2,2)*ATT1(2)+NPA(2,3)*ATT1(3)
ATT2(3) = NPA(3,1)*ATT1(1)+NPA(3,2)*ATT1(2)+NPA(3,3)*ATT1(3)
WKSIN = DSIN(SITAGT)
WKCOS = DCOS(SITAGT)
ATT3(1) = WKCOS*ATT2(1)+WKSIN*ATT2(2)
ATT3(2) =(-WKSIN)*ATT2(1)+WKCOS*ATT2(2)
ATT3(3) = ATT2(3)
CALL MG1200(ATT3,SP)
C
WKCOS = DCOS(SUNDEL)
SS(1) = WKCOS * DCOS(SUNALP)
SS(2) = WKCOS * DSIN(SUNALP)
SS(3) = DSIN(SUNDEL)
C
RETURN
END
SUBROUTINE MG1110
* (I,RTIM,CDR,ORBTA,ORBTB,SAT,SITAGT,SUNALP,SUNDEL,NPA)
C
implicit none
DOUBLE PRECISION CDR,SAT(3),RTIM,ORBTA(35,8),ORBTB(35,8),
& SITAGT,SUNDEL,SUNALP,NPA(3,3),DELT
INTEGER I
c
IF(I.NE.8) THEN
DELT=(RTIM-ORBTA(1,I))/(ORBTA(1,I+1)-ORBTA(1,I))
SAT(1) = ORBTA( 9,I)+(ORBTA( 9,I+1)-ORBTA( 9,I))*DELT
SAT(2) = ORBTA(10,I)+(ORBTA(10,I+1)-ORBTA(10,I))*DELT
SAT(3) = ORBTA(11,I)+(ORBTA(11,I+1)-ORBTA(11,I))*DELT
SITAGT =(ORBTA(15,I)+(ORBTA(15,I+1)-ORBTA(15,I))*DELT)*CDR
IF( (ORBTA(15,I+1)-ORBTA(15,I)).LT.0.D0)
* SITAGT = (ORBTA(15,I)+(ORBTA(15,I+1)-ORBTA(15,I)+360.D0)
* *DELT)*CDR
SUNALP = (ORBTA(18,I)+(ORBTA(18,I+1)-ORBTA(18,I))*DELT)*CDR
IF( (ORBTA(18,I+1)-ORBTA(18,I)).GT.0.D0)
* SUNALP = (ORBTA(18,I)+(ORBTA(18,I+1)-ORBTA(18,I)-360.D0)
* *DELT)*CDR
SUNDEL = (ORBTA(19,I)+(ORBTA(19,I+1)-ORBTA(19,I))*DELT)*CDR
NPA(1,1) = ORBTA(20,I)
NPA(2,1) = ORBTA(21,I)
NPA(3,1) = ORBTA(22,I)
NPA(1,2) = ORBTA(23,I)
NPA(2,2) = ORBTA(24,I)
NPA(3,2) = ORBTA(25,I)
NPA(1,3) = ORBTA(26,I)
NPA(2,3) = ORBTA(27,I)
NPA(3,3) = ORBTA(28,I)
ENDIF
RETURN
END
SUBROUTINE MG1200(VECT,VECTU)
implicit none
DOUBLE PRECISION VECT(3),VECTU(3),RV1,RV2
RV1=VECT(1)*VECT(1)+VECT(2)*VECT(2)+VECT(3)*VECT(3)
IF(RV1.EQ.0.D0) RETURN
RV2=DSQRT(RV1)
VECTU(1)=VECT(1)/RV2
VECTU(2)=VECT(2)/RV2
VECTU(3)=VECT(3)/RV2
RETURN
END
SUBROUTINE MG1210(VA,VB,VC)
implicit none
DOUBLE PRECISION VA(3),VB(3),VC(3)
VC(1) = VA(2)*VB(3)-VA(3)*VB(2)
VC(2) = VA(3)*VB(1)-VA(1)*VB(3)
VC(3) = VA(1)*VB(2) -VA(2)*VB(1)
RETURN
END
SUBROUTINE MG1220(VA,VB,VD)
implicit none
DOUBLE PRECISION VA(3),VB(3),VC(3),VD(3)
VC(1) = VA(2)*VB(3)-VA(3)*VB(2)
VC(2) = VA(3)*VB(1)-VA(1)*VB(3)
VC(3) = VA(1)*VB(2)-VA(2)*VB(1)
CALL MG1200(VC,VD)
RETURN
END
SUBROUTINE MG1230(VA,VB,ASITA)
implicit none
DOUBLE PRECISION VA(3),VB(3),ASITA,AS1,AS2
AS1=VA(1)*VB(1)+VA(2)*VB(2)+VA(3)*VB(3)
AS2=(VA(1)*VA(1)+VA(2)*VA(2)+VA(3)*VA(3))*
* (VB(1)*VB(1)+VB(2)*VB(2)+VB(3)*VB(3))
IF(AS2.EQ.0.D0) RETURN
ASITA=DACOS(AS1/DSQRT(AS2))
RETURN
END
SUBROUTINE MG1240(VA,VH,VN,DPAI,AZI)
implicit none
DOUBLE PRECISION VA(3),VH(3),VN(3),VB(3),VC(3),VD(3),
& DPAI,AZI,DNAI
CALL MG1220(VN,VH,VB)
CALL MG1220(VA,VH,VC)
CALL MG1230(VB,VC,AZI)
CALL MG1220(VB,VC,VD)
DNAI = VD(1)*VH(1)+VD(2)*VH(2)+VD(3)*VH(3)
IF(DNAI.GT.0.D0) AZI=DPAI-AZI
RETURN
END
INTEGER FUNCTION ENCODE_REAL4( R4DAT, IPOS, C4)
real r4dat
integer iword
integer ipos
integer idat
integer tint
integer base
character c4(4)*1
base = 256
nflag = 0
iword = 4
if (r4dat .lt. 0.) nflag = 1
idat = abs(int(r4dat*(10.**ipos)))
do 100 i = 1, iword
tint = idat/(base**(iword-i))
if (i .eq. 1) then
if (tint .gt. 127) then
ENCODE_REAL4 = -1
goto 999
else if ( tint .ge. 1) then
idat = idat - tint*(base**(iword-i))
endif
if (nflag .eq. 0) c4(i) = char(tint)
if (nflag .eq. 1) c4(i) = char(tint + 128)
else
if (tint .ge. 1) then
idat = idat - tint*(base**(iword-i))
c4(i) = char(tint)
else
c4(i) = char(0)
endif
endif
100 continue
ENCODE_REAL4 = 0
999 continue
return
end
INTEGER FUNCTION ENCODE_REAL8( R8DAT, IPOS, C6)
double precision r8dat
double precision base
double precision FFLOOR
integer iword
integer ipos
integer tint
character c6(6)*1
base = 256.D0
nflag = 0
iword = 6
if (r8dat .lt. 0.D0) nflag = 1
r8dat = abs((r8dat*(10.D0**ipos)))
do 100 i = 1, iword
tint = int(r8dat/((base)**(iword-i)))
print *, r8dat, tint
if (i .eq. 1) then
if (tint .gt. 127) then
ENCODE_REAL8 = -1
goto 999
else if ( tint .ge. 1) then
r8dat = r8dat - (tint*1.D0)*(base**(iword-i))
r8dat = FFLOOR(r8dat + .5D0)
endif
if (nflag .eq. 0) c6(i) = char(tint)
if (nflag .eq. 1) c6(i) = char(tint + 128)
else
if (tint .ge. 1) then
r8dat = r8dat - (tint*1.D0)*(base**(iword-i))
r8dat = FFLOOR(r8dat + .5D0)
c6(i) = char(tint)
else
c6(i) = char(0)
endif
endif
100 continue
ENCODE_REAL8 = 0
999 continue
return
end
DOUBLE PRECISION FUNCTION FFLOOR(X)
C COMPUTES "FLOOR" FUNCTION
DOUBLE PRECISION X
IF (X.GE.0.0D0) THEN
FFLOOR=DINT(X)
ELSE
FFLOOR=DINT(X)-1.0D0
ENDIF
RETURN
END
|
[STATEMENT]
lemma conjug_Lyndon_ex': assumes "primitive w"
obtains v where "w \<sim> v" and "Lyndon v"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>v. \<lbrakk>w \<sim> v; Lyndon v\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
unfolding conjug_rotate_iff
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>v. \<lbrakk>\<exists>n. v = rotate n w; Lyndon v\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using conjug_Lyndon_ex[OF \<open>primitive w\<close>]
[PROOF STATE]
proof (prove)
using this:
(\<And>n. Lyndon (rotate n w) \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
goal (1 subgoal):
1. (\<And>v. \<lbrakk>\<exists>n. v = rotate n w; Lyndon v\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by metis |
% STD_UNIFORMSETINDS - Check uniform channel distribution across datasets
%
% Usage:
% >> boolval = std_uniformsetinds(STUDY);
% Inputs:
% STUDY - EEGLAB STUDY
%
% Outputs:
% boolval - [0|1] 1 if uniform
%
% Authors: Arnaud Delorme, SCCN/UCSD, CERCO/CNRS, 2010-
% Copyright (C) Arnaud Delorme
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.
function uniformchannels = std_uniformsetinds( STUDY );
uniformchannels = 1;
for c = 1:length(STUDY.changrp(1).setinds(:))
tmpind = cellfun(@(x)(length(x{c})), { STUDY.changrp(:).setinds });
if length(unique(tmpind)) ~= 1
uniformchannels = 0;
end
end
|
import qualified System.Environment as SE
import qualified Data.ByteString.Lazy.Char8 as LC
import qualified Data.ByteString.Char8 as BC
import qualified Data.List as DL
import qualified Data.Map as DM
import qualified Data.Vector as DV
import qualified Statistics.Sample as SS
import qualified Statistics.Quantile as SQ
import Text.Printf
main :: IO()
main = do
input <- LC.getContents
output (nums $ LC.lines input)
-- clean input into a list of numbers
nums :: [LC.ByteString] -> [Double]
nums llns = floats $ map BC.unpack $ slns llns
where
slns = map (BC.concat . LC.toChunks)
floats [] = []
floats [x] = [read x :: Double]
floats (x:xs) = [read x :: Double] ++ floats xs
-- | calculate the frequency of items in a set
-- [ [(number, frequency), ....
freqs xs = DM.toList $ DM.fromListWith (+) [(c, 1) | c <- xs]
-- | calculate the mode of a list of numbers
mode xs = (fst . DL.head) $ DL.sortBy sortGT $ freqs xs
where
sortGT (a1, b1) (a2, b2)
| b1 < b2 = GT
| b1 > b2 = LT
| b1 == b2 = compare b1 b2
-- | calculate a quantile point
qtile q t xs = (SQ.continuousBy SQ.medianUnbiased q t) $ DV.fromList xs
-- | calculate the midhinge
midhinge xs = (qtile 1 4 xs + qtile 3 4 xs) / 2
-- | calculate the trimean
trimean xs = (qtile 2 4 xs + midhinge xs) / 2
h :: (Floating a, Ord t) => [t] -> a
-- | calculate Shannon Entropy
h xs = negate . sum . map (\(i,j) -> (p j xs) * (logBase 2 $ p j xs)) $ freqs xs
where
p n lst = (/) n tot_len
tot_len = (fromIntegral $ length xs)
-- | string formatter: round to 4 decimal places
format f n = printf "%.4f" (f $ DV.fromList n)
-- | display output formatting
display xs = sequence_ [putStrLn (a++" : "++b) | (a,b) <- xs]
output :: [Double] -> IO ()
output xs = display table
where table = [("Length", show $ length xs)
,("Min", show $ minimum xs)
,("Max", show $ maximum xs)
,("Range", printf "%.4f" $ maximum xs - minimum xs)
,("Q1", format (SQ.continuousBy SQ.medianUnbiased 1 4) xs)
,("Q2", format (SQ.continuousBy SQ.medianUnbiased 2 4) xs)
,("Q3", format (SQ.continuousBy SQ.medianUnbiased 3 4) xs)
,("IQR", format (SQ.midspread SQ.medianUnbiased 4) xs)
,("Trimean", printf "%.4f" $ trimean xs)
,("Midhinge", printf "%.4f" $ midhinge xs)
,("Mean", format SS.mean xs)
,("Mode", show $ mode xs)
,("Kurtosis", format SS.kurtosis xs)
,("Skewness", format SS.skewness xs)
,("Entropy", printf "%.4f" ((h xs) :: Float))]
|
# take input from the user
num = as.integer(readline(prompt = "Enter a number: "))
if(num < 0) {
print("Enter a positive number")
} else {
sum = 0
# use while loop to iterate until zero
while(num > 0) {
sum = sum + num
num = num - 1
}
print(paste("The sum is", sum))
} |
Require Import List.
Import ListNotations.
(* 再帰関数の定義 *)
Fixpoint reverse {A : Type} (xs : list A) :=
match xs with
| nil => nil
| x :: xs' =>
reverse xs' ++ [x]
end.
Compute reverse [1; 2; 3]. (* = [3; 2; 1] : list nat *)
(* 補題 *)
Lemma reverse_append : forall (A : Type) (xs ys : list A),
reverse (xs ++ ys) = reverse ys ++ reverse xs.
Proof.
intros A xs ys.
induction xs.
- simpl.
rewrite app_nil_r.
reflexivity.
- simpl.
rewrite IHxs.
rewrite app_assoc.
reflexivity.
Qed.
Theorem reverse_reverse : forall (A : Type) (xs : list A),
reverse (reverse xs) = xs.
Proof.
intros A xs.
induction xs.
- simpl.
reflexivity.
- simpl.
rewrite reverse_append.
simpl.
rewrite IHxs.
reflexivity.
Qed.
|
/-
Instances of `Universe` that correspond to basic Lean types and universes, with structure such
as functors, products, ...
The actual universes are already defined in `Universes.lean` because they are occasionally
referenced without importing this file. They are:
* `sort.{u} := ⟨Sort u⟩`
* `prop := sort.{0}`
* `type.{u} := sort.{u + 1}`
* `tsort.{u} := sort.{max 1 u}`
The structure on all of these universes is "trivial" to varying degrees, compared to what is
allowed in principle. Therefore, in this file there is often an instance of a class that is
defined in `Utils/Trivial.lean`, and which indirectly generates instances of classes in
`Axioms/Universe`.
-/
import UniverseAbstractions.Axioms.Universes
import UniverseAbstractions.Axioms.Universe.Identity
import UniverseAbstractions.Axioms.Universe.Functors
import UniverseAbstractions.Axioms.Universe.FunctorExtensionality
import UniverseAbstractions.Axioms.Universe.Singletons
import UniverseAbstractions.Axioms.Universe.Products
import UniverseAbstractions.Axioms.Universe.Equivalences
import UniverseAbstractions.Axioms.Universe.DependentTypes.Properties
import UniverseAbstractions.Axioms.Universe.DependentTypes.DependentFunctors
import UniverseAbstractions.Axioms.Universe.DependentTypes.DependentProducts
import UniverseAbstractions.Instances.Utils.Trivial
import UniverseAbstractions.MathlibFragments.Init.CoreExt
import UniverseAbstractions.MathlibFragments.Data.Equiv.Basic
set_option autoBoundImplicitLocal false
-- TODO: It looks like there are bad instances.
set_option synthInstance.maxHeartbeats 100000
--set_option pp.universes true
universe u v w w' upv
-- Each Lean universe is also a universe according to our definition. Some definitions work
-- generically for `sort.{u}`, others need to be split between `prop` and `type.{u}`.
namespace sort
open MetaRelation HasFunctors HasInternalEquivalences HasDependentFunctors
-- Instance equivalences of all `sort.{u}` are given by equality.
-- For `prop`, we could define instance equivalences to be in `unit` instead of relying on proof
-- irrelevance, but it's easier to generalize over `prop` and `type` if we have a single
-- definition.
instance hasEquivalenceRelation (α : sort.{u}) : HasEquivalenceRelation α prop :=
⟨nativeRelation (@Eq α)⟩
instance hasInstanceEquivalences : HasInstanceEquivalences sort.{u} prop :=
⟨hasEquivalenceRelation⟩
-- Functors from `sort` to any universe are just functions: Instance equivalence in `sort` is
-- given by equality, so functors do not need to respect anything else besides equality.
instance hasOutFunctors (V : Universe.{v}) : HasFunctors sort.{u} V sort.{imax u v} :=
{ Fun := λ α B => α → B,
apply := id }
def defOutFun {α : sort.{u}} {V : Universe.{v}} [HasIdentity V] {B : V} (f : ⌈α ⟶ B⌉) :
α ⟶{f} B :=
toDefFun f
instance hasTrivialOutFunctoriality (V : Universe.{v}) [HasIdentity V] :
HasTrivialFunctoriality sort.{u} V :=
⟨defOutFun⟩
instance hasCongrArg : HasCongrArg sort.{u} sort.{v} := ⟨λ f => congrArg f⟩
instance (priority := low) hasOutCongrArg (V : Universe.{v}) [HasIdentity V] :
HasCongrArg sort.{u} V :=
⟨λ {_ _} f {a₁ a₂} h => h ▸ HasInstanceEquivalences.refl (f a₁)⟩
theorem hasOutCongrArg.reflEq {α : sort.{u}} {V : Universe.{v}} [HasIdentity V] {B : V}
(f : ⌈α ⟶ B⌉) (a : α) :
(hasOutCongrArg V).congrArg f (Eq.refl a) = HasInstanceEquivalences.refl (f a) :=
rfl
theorem hasOutCongrArg.symmEq {α : sort.{u}} {V : Universe.{v}} [HasIdentity V] {B : V}
(f : ⌈α ⟶ B⌉) {a₁ a₂ : α} (h : a₁ = a₂)
(hRefl : ∀ b : B, (HasInstanceEquivalences.refl b)⁻¹ = HasInstanceEquivalences.refl b) :
(hasOutCongrArg V).congrArg f (Eq.symm h) = ((hasOutCongrArg V).congrArg f h)⁻¹ :=
by subst h; exact Eq.symm (hRefl (f a₁))
theorem hasOutCongrArg.transEq {α : sort.{u}} {V : Universe.{v}} [HasIdentity V] {B : V}
(f : ⌈α ⟶ B⌉) {a₁ a₂ a₃ : α} (h : a₁ = a₂) (i : a₂ = a₃)
(hRefl : ∀ b : B, HasInstanceEquivalences.refl b • HasInstanceEquivalences.refl b = HasInstanceEquivalences.refl b) :
(hasOutCongrArg V).congrArg f (Eq.trans h i) = (hasOutCongrArg V).congrArg f i • (hasOutCongrArg V).congrArg f h :=
by subst h; subst i; exact Eq.symm (hRefl (f a₁))
instance hasCongrFun : HasCongrFun sort.{u} sort.{v} := ⟨congrFun⟩
instance (priority := low) hasOutCongrFun (V : Universe.{v}) [HasIdentity V] :
HasCongrFun sort.{u} V :=
⟨λ h _ => h ▸ HasInstanceEquivalences.refl _⟩
instance hasInternalFunctors : HasInternalFunctors sort.{u} := ⟨⟩
instance hasTrivialExtensionality : HasTrivialExtensionality sort.{u} sort.{v} := ⟨funext⟩
-- Functors into `sort` need to be well-defined.
structure InFunctor {U : Universe.{u}} [HasIdentity U] (A : U) (B : sort.{v}) :
Sort (max 1 u v) where
(f : A → B)
(congrArg {a₁ a₂ : A} : a₁ ≃ a₂ → f a₁ = f a₂)
instance (priority := low) hasInFunctors (U : Universe.{u}) [HasIdentity U] :
HasFunctors U sort.{v} sort.{max 1 u v} :=
{ Fun := InFunctor,
apply := InFunctor.f }
instance (priority := low) hasInCongrArg (U : Universe.{u}) [HasIdentity U] :
HasCongrArg U sort.{v} :=
⟨InFunctor.congrArg⟩
def defInFun {U : Universe.{u}} [HasIdentity U] {A : U} {B : sort.{v}} (F : InFunctor A B) :
A ⟶{F.f} B :=
toDefFun' F (λ _ => by rfl)
instance hasInCompFun (U : Universe.{u}) (V : Universe.{v}) {W : Universe.{w'}} [HasIdentity U]
[HasIdentity V] [HasFunctors U V W] [HasCongrArg U V] :
HasCompFun U V sort.{w} :=
⟨λ F G => defInFun ⟨λ a => G.f (F a), λ e => G.congrArg (HasCongrArg.congrArg F e)⟩⟩
-- There are top and bottom types that work generically for `sort`.
instance (priority := low) hasTop : HasTop sort.{u} :=
{ T := PUnit,
t := PUnit.unit }
instance (priority := low) hasTopEq : HasTop.HasTopEq sort.{u} :=
⟨λ _ => rfl⟩
instance (priority := low) hasBot : HasBot sort.{u} :=
{ B := PEmpty,
elim := PEmpty.elim }
noncomputable def byContradiction (α : sort.{u}) (f : HasInternalBot.Not (HasInternalBot.Not α)) : α :=
Classical.choice (Classical.byContradiction (λ h => PEmpty.elim (f (λ a => False.elim (h ⟨a⟩)))))
noncomputable instance (priority := low) hasClassicalLogic : HasClassicalLogic sort.{u} :=
{ byContradictionFun := byContradiction }
-- Same for products, but usually the specialized versions for `prop` and `type` should be used.
instance (priority := low) hasProducts : HasProducts sort.{u} sort.{v} tsort.{max u v} :=
{ Prod := PProd,
intro := PProd.mk,
fst := PProd.fst,
snd := PProd.snd }
instance (priority := low) hasProductEq :
HasProducts.HasProductEq sort.{u} sort.{v} (UxV := tsort.{max u v}) :=
{ introEq := λ _ => rfl,
fstEq := λ _ _ => rfl,
sndEq := λ _ _ => rfl }
-- `Equiv` also works for general `sort`, but is overridden for `prop`.
def equivDesc {α : sort.{u}} {β : sort.{v}} (e : Equiv α β) : α ⮂ β :=
{ toFun := e.toFun,
invFun := e.invFun,
left := ⟨e.leftInv⟩,
right := ⟨e.rightInv⟩ }
instance (priority := low) hasEquivalences : HasEquivalences sort.{u} sort.{v} sort.{max 1 u v} :=
{ Equiv := Equiv,
desc := equivDesc }
-- Properties out of `sort` are functorial.
-- TODO: Replace `subst` tactic with explicit recursor invocation.
instance (priority := low) hasOutPropCongrArg (V : Universe.{v}) [HasTypeIdentity V] :
HasPropCongrArg sort.{u} V :=
{ congrArgReflEq := λ φ a => HasInstanceEquivalences.refl (HasEquivOp.refl (φ a)),
congrArgSymmEq := λ {_} φ {a₁ a₂} h => by subst h; exact (HasEquivOp.symmRefl (φ a₁))⁻¹,
congrArgTransEq := λ {_} φ {a₁ a₂ a₃} h i => by subst h; subst i; exact (HasEquivOp.transReflRefl (φ a₁))⁻¹ }
-- Dependent functors are analogous to independent functors.
instance hasDependentOutFunctors (V : Universe.{v}) :
HasDependentFunctors sort.{u} V sort.{imax u v} :=
{ Pi := HasFunctors.Pi,
apply := id }
def defPi {α : sort.{u}} {V : Universe.{v}} [HasTypeIdentity V] {φ : ⌈α ⟶ ⌊V⌋⌉}
(f : HasFunctors.Pi φ) :
Π{f} (HasFunctors.toDefFun φ) :=
toDefPi' f (λ _ => HasInstanceEquivalences.refl _) (λ _ => DependentEquivalence.refl _)
instance hasTrivialDependentOutFunctoriality (V : Universe.{v}) [HasTypeIdentity V] :
HasTrivialDependentFunctoriality sort.{u} V :=
⟨defPi⟩
instance hasDependentCongrFun : HasDependentCongrFun sort.{u} sort.{v} := ⟨congrFun⟩
instance (priority := low) hasDependentOutCongrFun (V : Universe.{v}) [HasIdentity V] :
HasDependentCongrFun sort.{u} V :=
⟨λ e _ => e ▸ HasInstanceEquivalences.refl _⟩
end sort
namespace prop
open MetaRelation HasFunctors HasEquivOp HasEquivOpFun HasDependentFunctors
instance hasTrivialIdentity : HasTrivialIdentity prop := ⟨proofIrrel⟩
-- Mapping into `prop` is expecially simple.
instance hasInFunctors (U : Universe.{u}) : HasFunctors U prop prop :=
{ Fun := λ A q => A → q,
apply := id }
def defInFun {U : Universe.{u}} {A : U} {q : prop} (f : ⌈A ⟶ q⌉) : A ⟶{f} q :=
toDefFun f
instance hasTrivialInFunctoriality (U : Universe.{u}) : HasTrivialFunctoriality U prop :=
⟨defInFun⟩
-- Propositional trunction is functorial.
def Truncated {U : Universe.{u}} (A : U) : prop := Nonempty A
theorem trunc {U : Universe.{u}} {A : U} (a : A) : Truncated A := ⟨a⟩
theorem truncFun {U : Universe.{u}} (A : U) : A ⟶ Truncated A := trunc
instance trunc.isFunApp {U : Universe.{u}} {A : U} (a : A) : IsFunApp (V := prop) A (trunc a) :=
{ F := truncFun A,
a := a,
e := proofIrrel _ _ }
theorem truncProj {U : Universe.{u}} [HasFunctors U U U] {A B : U} (F : A ⟶ B) :
Truncated A ⟶ Truncated B :=
λ ⟨a⟩ => ⟨F a⟩
theorem truncProjFun {U : Universe.{u}} [HasFunctors U U U] (A B : U) :
(A ⟶ B) ⟶ (Truncated A ⟶ Truncated B) :=
truncProj
instance truncProj.isFunApp {U : Universe.{u}} [HasFunctors U U U] {A B : U} (F : A ⟶ B) :
IsFunApp (V := prop) (A ⟶ B) (truncProj F) :=
{ F := truncProjFun A B,
a := F,
e := proofIrrel _ _ }
theorem truncProjFun' {U : Universe.{u}} [HasFunctors U U U] (A B : U) :
Truncated (A ⟶ B) ⟶ (Truncated A ⟶ Truncated B) :=
λ ⟨F⟩ => truncProj F
-- In `prop`, `Top` is `True` and `Bot` is `False`.
instance hasTop : HasTop prop :=
{ T := True,
t := trivial }
instance hasBot : HasBot prop :=
{ B := False,
elim := False.elim }
-- `prop` has classical logic if we want.
instance hasClassicalLogic : HasClassicalLogic prop :=
{ byContradictionFun := @Classical.byContradiction }
-- Products are given by `And`.
instance hasProducts : HasProducts prop prop prop :=
{ Prod := And,
intro := And.intro,
fst := And.left,
snd := And.right }
-- Equivalences are given by `Iff`.
instance hasEquivalences : HasEquivalences prop prop prop :=
{ Equiv := Iff,
desc := λ h => HasTrivialIdentity.equivDesc h.mp h.mpr }
instance hasTrivialEquivalenceCondition : HasTrivialEquivalenceCondition prop :=
⟨λ e => HasTrivialIdentity.defEquiv (Iff.intro e.toFun e.invFun)⟩
-- Dependent incoming functors are analogous to independent incoming functors.
instance hasDependentInFunctors (U : Universe.{u}) {UpV : Universe.{upv}} [HasIdentity U]
[HasFunctors U {prop} UpV] :
HasDependentFunctors U prop prop :=
{ Pi := λ φ => ∀ a, φ a,
apply := id }
def defInPi {U : Universe.{u}} {UpV : Universe.{upv}} [HasIdentity U]
[HasFunctors U {prop} UpV] {A : U} {φ : A ⟶ ⌊prop⌋} (f : Π φ) :
Π{f} (HasFunctors.toDefFun φ) :=
-- `toDefPi` results in Lean bug.
toDefPi' f (λ a => HasInstanceEquivalences.refl (φ a)) (λ _ => proofIrrel _ _)
instance hasTrivialDependentInFunctoriality (U : Universe.{u}) {UpV : Universe.{upv}}
[HasIdentity U] [HasFunctors U {prop} UpV] :
HasTrivialDependentFunctoriality U prop :=
⟨defInPi⟩
-- Dependent products are given by `∃`, requiring choice to obtain a witness unless the witness
-- is in `prop`.
instance hasDependentProducts : HasDependentProducts prop prop prop :=
{ Sigma := λ φ => ∃ h₁, φ h₁,
intro := λ h₁ h₂ => ⟨h₁, h₂⟩,
fst := λ ⟨h₁, _⟩ => h₁,
snd := λ ⟨_, h₂⟩ => h₂ }
noncomputable instance (priority := low) hasClassicalDependentProducts :
HasDependentProducts sort.{u} prop prop :=
{ Sigma := λ φ => ∃ a, φ a,
intro := λ a h => ⟨a, h⟩,
fst := Classical.choose,
snd := Classical.choose_spec }
end prop
namespace tsort
open HasPropCongrArg HasDependentFunctors
-- `tsort` has internal equivalences given by `Equiv`. An `Equiv` essentially matches our
-- `EquivDesc`, so we can directly use the equivalence proofs from generic code.
instance (priority := low) hasInternalEquivalences : HasInternalEquivalences tsort.{u} :=
HasTrivialExtensionality.hasInternalEquivalences tsort (λ h => Equiv.inj h)
--instance (priority := low) hasInternalEquivalences : HasInternalEquivalences tsort.{u} :=
--{ defToFunFun := λ _ _ => HasTrivialFunctoriality.defFun,
-- isExt := λ E => HasTrivialExtensionality.equivDescExt tsort.{u} (HasEquivalences.desc E) }
instance hasTrivialEquivalenceCondition : HasTrivialEquivalenceCondition tsort.{u} :=
⟨λ e => ⟨⟨e.toFun, e.invFun, e.left.inv, e.right.inv⟩, rfl, rfl⟩⟩
-- Dependent incoming functors are analogous to independent incoming functors.
structure DependentInFunctor {U : Universe.{u}} {UpV : Universe.{upv}} [HasIdentity U]
[HasFunctors U {tsort.{v}} UpV] [HasPropCongrArg U tsort.{v}]
{A : U} (φ : A ⟶ ⌊tsort.{v}⌋) :
Sort (max 1 u v) where
(f : HasFunctors.Pi φ)
(congrArg {a₁ a₂ : A} (e : a₁ ≃ a₂) : f a₁ ≃[propCongrArg φ e] f a₂)
instance (priority := low) hasDependentInFunctors (U : Universe.{u}) {UpV : Universe.{upv}}
[HasIdentity U] [HasFunctors U {tsort.{v}} UpV]
[HasPropCongrArg U tsort.{v}] :
HasDependentFunctors U tsort.{v} tsort.{max u v} :=
{ Pi := DependentInFunctor,
apply := DependentInFunctor.f }
instance (priority := low) hasDependentInCongrArg (U : Universe.{u}) {UpV : Universe.{upv}}
[HasIdentity U] [HasFunctors U {tsort.{v}} UpV]
[HasPropCongrArg U tsort.{v}] :
HasDependentCongrArg U tsort.{v} :=
⟨DependentInFunctor.congrArg⟩
def defInPi {U : Universe.{u}} {UpV : Universe.{upv}} [HasIdentity U]
[HasFunctors U {tsort.{v}} UpV] [HasPropCongrArg U tsort.{v}]
{A : U} {φ : A ⟶ ⌊tsort.{v}⌋} (F : Π φ) :
Π{F.f} (HasFunctors.toDefFun φ) :=
toDefPi' F (λ a => HasInstanceEquivalences.refl (φ a)) (λ _ => by rfl)
-- Dependent products are given by either `PSigma` or `Subtype`, depending on the
-- universe levels.
instance (priority := low) hasDependentProducts :
HasDependentProducts sort.{u} tsort.{v} tsort.{max u v} :=
{ Sigma := PSigma,
intro := PSigma.mk,
fst := PSigma.fst,
snd := PSigma.snd }
instance (priority := low) hasDependentProductEq :
HasDependentProducts.HasDependentProductEq sort.{u} tsort.{v} (UxV := tsort.{max u v}) :=
{ introEq := λ _ => rfl,
fstEq := λ _ _ => rfl,
sndEq := λ _ _ => rfl }
instance (priority := low) hasSubtypes :
HasDependentProducts sort.{u} prop tsort.{u} :=
{ Sigma := Subtype,
intro := Subtype.mk,
fst := Subtype.val,
snd := Subtype.property }
instance (priority := low) hasSubtypeEq :
HasDependentProducts.HasDependentProductEq sort.{u} prop (UxV := tsort.{u}) :=
{ introEq := λ _ => rfl,
fstEq := λ _ _ => rfl,
sndEq := λ _ _ => HasTrivialIdentity.eq }
end tsort
namespace type
open MetaRelation
-- Use specialized types for `type.{0}`.
instance hasTop : HasTop type.{0} :=
{ T := Unit,
t := Unit.unit }
instance hasTopEq : HasTop.HasTopEq type.{0} :=
⟨λ _ => rfl⟩
instance hasBot : HasBot type.{0} :=
{ B := Empty,
elim := Empty.elim }
noncomputable def byContradiction (α : type.{0}) (f : HasInternalBot.Not (HasInternalBot.Not α)) : α :=
Classical.choice (Classical.byContradiction (λ h => Empty.elim (f (λ a => False.elim (h ⟨a⟩)))))
noncomputable instance hasClassicalLogic : HasClassicalLogic type.{0} :=
{ byContradictionFun := byContradiction }
-- Use `Prod` instead of `PProd` where possible.
instance hasProducts : HasProducts type.{u} type.{v} type.{max u v} :=
{ Prod := Prod,
intro := Prod.mk,
fst := Prod.fst,
snd := Prod.snd }
instance hasProductEq : HasProducts.HasProductEq type.{u} type.{v} :=
{ introEq := λ _ => rfl,
fstEq := λ _ _ => rfl,
sndEq := λ _ _ => rfl }
-- Internal equivalences of `type` are a special case of `tsort`.
instance hasInternalEquivalences : HasInternalEquivalences type.{u} :=
tsort.hasInternalEquivalences.{u + 1}
instance hasTrivialEquivalenceCondition : HasTrivialEquivalenceCondition type.{u} :=
tsort.hasTrivialEquivalenceCondition.{u + 1}
-- The target equality of dependent functors contains a cast (from `sort.hasOutCongrArg`),
-- but we can eliminate it easily.
instance hasDependentCongrArg : HasDependentCongrArg sort.{u} type.{v} :=
⟨λ {_ _} _ {_ _} e => by subst e; rfl⟩
-- Use `Sigma` instead of `PSigma` where possible.
instance hasDependentProducts : HasDependentProducts type.{u} type.{v} type.{max u v} :=
{ Sigma := Sigma,
intro := Sigma.mk,
fst := Sigma.fst,
snd := Sigma.snd }
instance hasDependentProductEq :
HasDependentProducts.HasDependentProductEq type.{u} type.{v} (UxV := type.{max u v}) :=
{ introEq := λ _ => rfl,
fstEq := λ _ _ => rfl,
sndEq := λ _ _ => rfl }
end type
|
\<^marker>\<open>creator "Kevin Kappelmann"\<close>
paragraph \<open>Reflexive\<close>
theory Binary_Relations_Reflexive
imports
Functions_Monotone
begin
consts reflexive_on :: "'a \<Rightarrow> ('b \<Rightarrow> 'b \<Rightarrow> bool) \<Rightarrow> bool"
overloading
reflexive_on_pred \<equiv> "reflexive_on :: ('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
begin
definition "reflexive_on_pred P R \<equiv> \<forall>x. P x \<longrightarrow> R x x"
end
lemma reflexive_onI [intro]:
assumes "\<And>x. P x \<Longrightarrow> R x x"
shows "reflexive_on P R"
using assms unfolding reflexive_on_pred_def by blast
lemma reflexive_onD [dest]:
assumes "reflexive_on P R"
and "P x"
shows "R x x"
using assms unfolding reflexive_on_pred_def by blast
lemma le_in_dom_if_reflexive_on:
assumes "reflexive_on P R"
shows "P \<le> in_dom R"
using assms by blast
lemma le_in_codom_if_reflexive_on:
assumes "reflexive_on P R"
shows "P \<le> in_codom R"
using assms by blast
lemma in_codom_eq_in_dom_if_reflexive_on_in_field:
assumes "reflexive_on (in_field R) R"
shows "in_codom R = in_dom R"
using assms by blast
lemma reflexive_on_rel_inv_iff_reflexive_on [iff]:
"reflexive_on P R\<inverse> \<longleftrightarrow> reflexive_on (P :: 'a \<Rightarrow> bool) (R :: 'a \<Rightarrow> _)"
by blast
lemma antimono_reflexive_on [iff]:
"antimono (\<lambda>(P :: 'a \<Rightarrow> bool). reflexive_on P (R :: 'a \<Rightarrow> _))"
by (intro antimonoI) auto
lemma reflexive_on_if_le_pred_if_reflexive_on:
fixes P P' :: "'a \<Rightarrow> bool" and R :: "'a \<Rightarrow> _"
assumes "reflexive_on P R"
and "P' \<le> P"
shows "reflexive_on P' R"
using assms by blast
lemma reflexive_on_sup_eq [simp]:
"(reflexive_on :: ('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> _) \<Rightarrow> _) ((P :: 'a \<Rightarrow> bool) \<squnion> Q)
= reflexive_on P \<sqinter> reflexive_on Q"
by (intro ext iffI reflexive_onI)
(auto intro: reflexive_on_if_le_pred_if_reflexive_on)
lemma reflexive_on_iff_eq_restrict_left_le:
"reflexive_on (P :: 'a \<Rightarrow> bool) (R :: 'a \<Rightarrow> _) \<longleftrightarrow> ((=)\<restriction>\<^bsub>P\<^esub> \<le> R)"
by blast
definition "reflexive (R :: 'a \<Rightarrow> _) \<equiv> reflexive_on (\<top> :: 'a \<Rightarrow> bool) R"
lemma reflexive_eq_reflexive_on:
"reflexive (R :: 'a \<Rightarrow> _) = reflexive_on (\<top> :: 'a \<Rightarrow> bool) R"
unfolding reflexive_def ..
lemma reflexiveI [intro]:
assumes "\<And>x. R x x"
shows "reflexive R"
unfolding reflexive_eq_reflexive_on using assms by (intro reflexive_onI)
lemma reflexiveD:
assumes "reflexive R"
shows "R x x"
using assms unfolding reflexive_eq_reflexive_on by (blast intro: top1I)
lemma reflexive_on_if_reflexive:
fixes P :: "'a \<Rightarrow> bool" and R :: "'a \<Rightarrow> _"
assumes "reflexive R"
shows "reflexive_on P R"
using assms by (intro reflexive_onI) (blast dest: reflexiveD)
lemma reflexive_rel_inv_iff_reflexive [iff]:
"reflexive R\<inverse> \<longleftrightarrow> reflexive R"
by (blast dest: reflexiveD)
lemma reflexive_iff_eq_le: "reflexive R \<longleftrightarrow> ((=) \<le> R)"
unfolding reflexive_eq_reflexive_on reflexive_on_iff_eq_restrict_left_le
by simp
paragraph \<open>Instantiations\<close>
lemma reflexive_eq: "reflexive (=)"
by (rule reflexiveI) (rule refl)
lemma reflexive_top: "reflexive \<top>"
by (rule reflexiveI) auto
end |
-- This is mainly a test of the quality of error messages for
-- termination problems.
module TerminationLambda where
postulate Id : Set → Set
F : Set → Set
F = λ A → F (Id A)
|
# https://github.com/SGL-UT/GPSTk/tree/master/core/lib/GNSSCore/ObsID.hpp
# https://github.com/SGL-UT/GPSTk/tree/master/core/lib/GNSSCore/ObsIDInitializer.cpp
@enum ObservationType begin
otUnknown
otAny # < Used to match any observation type
otRange # < pseudorange, in meters
otPhase # < accumulated phase, in cycles
otDoppler # < Doppler, in Hz
otSNR # < Signal strength, in dB-Hz
otChannel # < Channel number
otDemodStat # < Demodulator status
otIono # < Ionospheric delay (see RINEX3 section 5.12)
otSSI # < Signal Strength Indicator (RINEX)
otLLI # < Loss of Lock Indicator (RINEX)
otTrackLen # < Number of continuous epochs of 'good' tracking
otNavMsg # < Navigation Message data
otRngStdDev # < pseudorange standard deviation, in meters
otPhsStdDev # < phase standard deviation, in cycles
otFreqIndx # < GLONASS frequency offset index [-6..7]
otUndefined # < Undefined
otLast # < Used to verify that all items are described at compile time
end
# The frequency band this obs was collected from.
@enum CarrierBand begin
cbUnknown
cbAny # < Used to match any carrier band
cbZero # < Used with the channel observation type (see RINEx3 section 5.13)
cbL1 # < GPS L1, Galileo E2-L1-E1, SBAS L1, QZSS L1
cbL2 # < GPS L2, QZSS L2
cbL5 # < GPS L5, Galileo E5a, SBAS L5, QZSS L5, INRSS L5
cbG1 # < Glonass G1
cbG2 # < Glonass G2
cbG3 # < Glonass G3
cbE5b # < Galileo E5b, BeiDou L7
cbE5ab # < Galileo E5a+b
cbE6 # < Galileo E6, QZSS LEX
cbB1 # < BeiDou L1
cbB2 # < BeiDou L7
cbB3 # < BeiDou L6
cbI9 # < IRNSS S-band (RINEX '9')
cbL1L2 # < Combined L1L2 (like an ionosphere free obs)
cbUndefined
cbLast # < Used to verify that all items are described at compile time
end
#= /** The code used to collect the observation. Each of these
* should uniquely identify a code that was correlated
* against to track the signal. While the notation generally
* follows section 5.1 of RINEX 3, due to ambiguities in that
* specification some extensions are made. Note that as
* concrete specifications for the codes are released, this
* list may need to be adjusted. Specifically, this lists
* assumes that the same I & Q codes will be used on all
* three of the Galileo carriers. If that is not true, more
* identifiers need to be allocated */ =#
@enum TrackingCode begin
tcUnknown
tcAny # < Used to match any tracking code
tcCA # < Legacy GPS civil code
tcP # < Legacy GPS precise code
tcY # < Encrypted legacy GPS precise code
tcW # < Encrypted legacy GPS precise code, codeless Z tracking
tcN # < Encrypted legacy GPS precise code, squaring codeless tracking
tcD # < Encrypted legacy GPS precise code, other codeless tracking
tcM # < Modernized GPS military unique code
tcC2M # < Modernized GPS L2 civil M code
tcC2L # < Modernized GPS L2 civil L code
tcC2LM # < Modernized GPS L2 civil M+L combined tracking (such as Trimble NetRS, Septrentrio, and ITT)
tcI5 # < Modernized GPS L5 civil in-phase
tcQ5 # < Modernized GPS L5 civil quadrature
tcIQ5 # < Modernized GPS L5 civil I+Q combined tracking
tcG1P # < Modernized GPS L1C civil code tracking (pilot)
tcG1D # < Modernized GPS L1C civil code tracking (data)
tcG1X # < Modernized GPS L1C civil code tracking (pilot + data)
tcGCA # < Legacy Glonass civil signal
tcGP # < Legacy Glonass precise signal
tcIR3 # < Glonass L3 I code
tcQR3 # < Glonass L3 Q code
tcIQR3 # < Glonass L3 I+Q combined tracking
tcA # < Galileo L1 PRS code
tcB # < Galileo OS/CS/SoL code
tcC # < Galileo Dataless code
tcBC # < Galileo B+C combined tracking
tcABC # < Galileo A+B+C combined tracking
tcIE5 # < Galileo E5 I code
tcQE5 # < Galileo E5 Q code
tcIQE5 # < Galileo E5 I+Q combined tracking
tcIE5a # < Galileo E5a I code
tcQE5a # < Galileo E5a Q code
tcIQE5a # < Galileo E5a I+Q combined tracking
tcIE5b # < Galileo E5b I code
tcQE5b # < Galileo E5b Q code
tcIQE5b # < Galileo E5b I+Q combined tracking
tcSCA # < SBAS civil code
tcSI5 # < SBAS L5 I code
tcSQ5 # < SBAS L5 Q code
tcSIQ5 # < SBAS L5 I+Q code
tcJCA # < QZSS civil code
tcJD1 # < QZSS L1C(D)
tcJP1 # < QZSS L1C(P)
tcJX1 # < QZSS L1C(D+P)
tcJZ1 # < QZSS L1-SAIF
tcJM2 # < QZSS L2C(M)
tcJL2 # < QZSS L2C(L)
tcJX2 # < QZSS L2C(M+L)
tcJI5 # < QZSS L5 in-phase
tcJQ5 # < QZSS L5 quadrature
tcJIQ5 # < QZSS L5 I+Q combined tracking
tcJI6 # < QZSS LEX(6) in-phase
tcJQ6 # < QZSS LEX(6) quadrature
tcJIQ6 # < QZSS LEX(6) I+Q combined tracking
tcCI1 # < BeiDou B1 I code
tcCQ1 # < BeiDou B1 Q code
tcCIQ1 # < BeiDou B1 I code
tcCI7 # < BeiDou B2 I+Q code
tcCQ7 # < BeiDou B2 Q code
tcCIQ7 # < BeiDou B2 I+Q code
tcCI6 # < BeiDou B3 I code
tcCQ6 # < BeiDou B3 Q code
tcCIQ6 # < BeiDou B3 I+Q code
# Nomenclature follows RiNEX 3.03 Table 10
tcIA5 # < IRNSS L5 SPS
tcIB5 # < IRNSS L5 RS(D)
tcIC5 # < IRNSS L5 RS(P)
tcIX5 # < IRNSS L5 B+C
tcIA9 # < IRNSS S-band SPS
tcIB9 # < IRNSS S=band RS(D)
tcIC9 # < INRSS S-band RS(P)
tcIX9 # < IRNSS S-band B+C
tcUndefined
tcLast # < Used to verify that all items are described at compile time
end
# The following definitions really should only describe the items that are
# in the Rinex 3 specification. If an application needs additional ObsID
# types to be able to be translated to/from Rinex3, the additional types
# must be added by the application.
# ObsID::char2[a-z]{2}\[('.')\] = ObsID::(.+);
const char2ot = Dict{Char,ObservationType}(
' ' => otUnknown,
'*' => otAny,
'C' => otRange,
'L' => otPhase,
'D' => otDoppler,
'S' => otSNR,
'-' => otUndefined,
)
const char2cb = Dict{Char,CarrierBand}(
' ' => cbUnknown,
'*' => cbAny,
'1' => cbL1,
'2' => cbL2,
'3' => cbG3,
'5' => cbL5,
'6' => cbE6,
'7' => cbE5b,
'8' => cbE5ab,
'9' => cbI9,
'-' => cbUndefined,
)
const char2tc = Dict{Char,TrackingCode}(
' ' => tcUnknown,
'*' => tcAny,
'C' => tcCA,
'P' => tcP,
'W' => tcW,
'Y' => tcY,
'M' => tcM,
'N' => tcN,
'D' => tcD,
'S' => tcC2M,
'L' => tcC2L,
'X' => tcC2LM,
'I' => tcI5,
'Q' => tcQ5,
'A' => tcA,
'B' => tcB,
'Z' => tcABC,
'-' => tcUndefined,
)
# ObsID::otDesc\[ObsID::(ot[A-Za-z]+)\]( +)= +("[A-Za-z]+");( +)//(.+)
# $1$2=>$3,$4#$5
const otDesc = Dict{ObservationType,String}(
otUnknown => "UnknownType", # Rinex (sp)
otAny => "AnyType", # Rinex *
otRange => "pseudorange", # Rinex C
otPhase => "phase", # Rinex L
otDoppler => "doppler", # Rinex D
otSNR => "snr", # Rinex S
otChannel => "channel", # Rinex
otDemodStat => "demodStatus", # test
otIono => "iono", # Rinex
otSSI => "ssi", # Rinex
otLLI => "lli", # Rinex
otTrackLen => "tlen", # Rinex
otNavMsg => "navmsg", # Rinex
otRngStdDev => "rngSigma", # test
otPhsStdDev => "phsSigma", # test
otFreqIndx => "freqIndx", # test
otUndefined => "undefined", # Rinex -
)
# ObsID::cbDesc\[ObsID::(cb[A-Za-z0-9]+)\]( +)= +("[A-Za-z0-9\+]+");( +)//(.+)
# $1$2=>$3,$4#$5
const cbDesc = Dict{CarrierBand,String}(
cbUnknown => "UnknownBand", # Rinex (sp)
cbAny => "AnyBand", # Rinex *
cbZero => "0", # Rinex
cbL1 => "L1", # Rinex 1
cbL2 => "L2", # Rinex 2
cbL5 => "L5", # Rinex 5
cbG1 => "G1", # Rinex 1
cbG2 => "G2", # Rinex 2
cbG3 => "G3", # Rinex 3
cbE5b => "E5b", # Rinex 7
cbE5ab => "E5a+b", # Rinex 8
cbE6 => "E6", # Rinex 6
cbB1 => "B1", # Rinex 1 2 in RINEX 3.0[013]
cbB2 => "B2", # Rinex 7
cbB3 => "B3", # Rinex 6
cbI9 => "I9", # Rinex 9
cbL1L2 => "comboL1L2", # Rinex 3
cbUndefined => "undefined", # Rinex -
)
# ObsID::tcDesc\[ObsID::(tc[A-Za-z0-9]+)\]( +)= +(".+?");( +)//(.+)
# $1$2=>$3,$4#$5
const tcDesc = Dict{TrackingCode,String}(
tcUnknown => "UnknownCode", # Rinex (sp)
tcAny => "AnyCode", # Rinex *
tcCA => "GPSC/A", # Rinex C // GPScivil
tcP => "GPSP", # Rinex P // GPSprecise
tcY => "GPSY", # Rinex Y // GPSprecise_encrypted
tcW => "GPScodelessZ", # Rinex W // GPSprecise_encrypted_codeless_Z
tcN => "GPSsquare", # Rinex N // GPSprecise_encrypted_codeless_squaring
tcD => "GPScodeless", # Rinex D // GPSprecise_encrypted_codeless_other
tcM => "GPSM", # Rinex M // GPSmilitary
tcC2M => "GPSC2M", # Rinex S // GPScivil_M
tcC2L => "GPSC2L", # Rinex L // GPScivil_L
tcC2LM => "GPSC2L+M", # Rinex X // GPScivil_L+M
tcI5 => "GPSI5", # Rinex I // GPScivil_I
tcQ5 => "GPSQ5", # Rinex Q // GPScivil_Q
tcIQ5 => "GPSI+Q5", # Rinex X // GPScivil_I+Q
tcG1P => "GPSC1P", # Rinex L // GPScivil_L1P
tcG1D => "GPSC1D", # Rinex S // GPScivil_L1D
tcG1X => "GPSC1(D+P)", # Rinex X // GPScivil_L1D+P
tcGCA => "GLOC/A", # Rinex C // GLOcivil
tcGP => "GLOP", # Rinex P // GLOprecise
tcIR3 => "GLOIR5", # Rinex I // GLO L3 I code
tcQR3 => "GLOQR5", # Rinex Q // GLO L3 Q code
tcIQR3 => "GLOI+QR5", # Rinex X // GLO L3 I+Q code
tcA => "GALA", # Rinex A // GAL
tcB => "GALB", # Rinex B // GAL
tcC => "GALC", # Rinex C // GAL
tcBC => "GALB+C", # Rinex X // GAL
tcABC => "GALA+B+C", # Rinex Z // GAL
tcIE5 => "GALI5", # Rinex I // GAL
tcQE5 => "GALQ5", # Rinex Q // GAL
tcIQE5 => "GALI+Q5", # Rinex X // GAL
tcIE5a => "GALI5a", # Rinex I // GAL
tcQE5a => "GALQ5a", # Rinex Q // GAL
tcIQE5a => "GALI+Q5a", # Rinex X // GAL
tcIE5b => "GALI5b", # Rinex I // GAL
tcQE5b => "GALQ5b", # Rinex Q // GAL
tcIQE5b => "GALI+Q5b", # Rinex X // GAL
tcSCA => "SBASC/A", # Rinex C // SBAS civil code
tcSI5 => "SBASI5", # Rinex I // SBAS L5 I code
tcSQ5 => "SBASQ5", # Rinex Q // SBAS L5 Q code
tcSIQ5 => "SBASI+Q5", # Rinex X // SBAS L5 I+Q code
tcJCA => "QZSSC/A", # Rinex C // QZSS L1 civil code
tcJD1 => "QZSSL1C(D)", # Rinex S // QZSS L1C(D)
tcJP1 => "QZSSL1C(P)", # Rinex L // QZSS L1C(P)
tcJX1 => "QZSSL1C(D+P)", # Rinex X // QZSS L1C(D+P)
tcJZ1 => "QZSSL1-SAIF", # Rinex Z // QZSS L1-SAIF
tcJM2 => "QZSSL2C(M)", # Rinex S // QZSS L2 M code
tcJL2 => "QZSSL2C(L)", # Rinex L // QZSS L2 L code
tcJX2 => "QZSSL2C(M+L)", # Rinex X // QZSS L2 M+L code
tcJI5 => "QZSSL5I", # Rinex I // QZSS L5 I code
tcJQ5 => "QZSSL5Q", # Rinex Q // QZSS L5 Q code
tcJIQ5 => "QZSSL5I+Q", # Rinex X // QZSS L5 I+Q code
tcJI6 => "QZSSL6I", # Rinex S // QZSS LEX(6) I code
tcJQ6 => "QZSSL6Q", # Rinex L // QZSS LEX(6) Q code
tcJIQ6 => "QZSSL6I+Q", # Rinex X // QZSS LEX(6) I+Q code
tcCI1 => "BDSIB1", # Rinex I // BeiDou L1 I code
tcCQ1 => "BDSQB1", # Rinex Q // BeiDou L1 Q code
tcCIQ1 => "BDSI+QB1", # Rinex X // BeiDou L1 I+Q code
tcCI7 => "BDSIB2", # Rinex I // BeiDou B2 I code
tcCQ7 => "BDSQB2", # Rinex Q // BeiDou B2 Q code
tcCIQ7 => "BDSI+QB2", # Rinex X // BeiDou B2 I+Q code
tcCI6 => "BDSIB3", # Rinex I // BeiDou B3 I code
tcCQ6 => "BDSQB3", # Rinex Q // BeiDou B3 Q code
tcCIQ6 => "BDSI+QB3", # Rinex X // BeiDou B3 I+Q code
tcIA5 => "IRNSSL5A", # Rinex A // IRNSS L5 SPS
tcIB5 => "IRNSSL5B", # Rinex B // IRNSS L5 RS(D)
tcIC5 => "IRNSSL5C", # Rinex C // IRNSS L5 RS(P)
tcIX5 => "IRNSSL5B+C", # Rinex X // IRNSS L5 B+C
tcIA9 => "IRNSSL9A", # Rinex A // IRNSS S-band SPS
tcIB9 => "IRNSSL9B", # Rinex B // IRNSS S-band RS(D)
tcIC9 => "IRNSSL9C", # Rinex C // IRNSS S-band RS(P)
tcIX9 => "IRNSSL9B+C", # Rinex X // IRNSS S-band B+C
tcUndefined => "undefined", # test
)
export ObsID
struct ObsID
str::String
ot::ObservationType
cb::CarrierBand
tc::TrackingCode
ss::SatelliteSystemType
function ObsID(str::Union{String,SubString}, sys::SatelliteSystemType=sstUnknown)
length(str) == 3 || throw(error("ObsID |$str| error"))
cot, ccb, ctc = str
haskey(char2cb, ccb) || throw(error("no such CarrierBand: $ccb"))
haskey(char2ot, cot) || throw(error("no such ObservationType: $cot"))
haskey(char2tc, ctc) || throw(error("no such TrackingCode: $ctc"))
type = char2ot[cot]
band = char2cb[ccb]
code = char2tc[ctc]
# / This next block takes care of fixing up the codes that are reused
# / between the various signals
if sys == sstGPS
if band == cbL5
if code == tcC2LM code = tcIQ5 end
elseif band == cbL1
if (code == tcC2LM) code = tcG1X
elseif (code == tcC2M) code = tcG1D
elseif (code == tcC2L) code = tcG1P
end
end
elseif sys == sstGalileo
if band == cbL1 || band == cbE6
if code == tcCA code = tcC
elseif code == tcC2LM code = tcBC
end
elseif band == cbL5
if code == tcI5 code = tcIE5a
elseif code == tcQ5 code = tcQE5a
elseif code == tcC2LM code = tcIQE5a
end
elseif band == cbE5b
if code == tcI5 code = tcIE5b
elseif code == tcQ5 code = tcQE5b
elseif code == tcC2LM code = tcIQE5b
end
elseif band == cbE5ab
if code == tcI5 code = tcIE5
elseif code == tcQ5 code = tcQE5
elseif code == tcC2LM code = tcIQE5
end
end
elseif sys == sstGlonass
if code == tcCA code = tcGCA
elseif code == tcP code = tcGP
elseif code == tcI5 code = tcIR3
elseif code == tcQ5 code = tcQR3
elseif code == tcC2LM || code == tcG1X
code = tcIQR3
end
if band == cbL1 band = cbG1
elseif band == cbL2 band = cbG2
end
elseif sys == sstGeosync
if code == tcCA code = tcSCA # 'C'
elseif code == tcI5 code = tcSI5 # 'I'
elseif code == tcQ5 code = tcSQ5 # 'Q'
elseif code == tcC2LM || code == tcG1X
code = tcSIQ5 # 'X'
end
elseif sys == sstQZSS
if band == cbL1
if code == tcCA
code = tcJCA # 'C'
elseif code == tcC2M || code == tcG1D
code = tcJD1 # 'S'
elseif code == tcC2L || code == tcG1P
code = tcJP1 # 'L'
elseif code == tcC2LM || code == tcG1X
code = tcJX1 # 'X'
elseif code == tcABC
code = tcJZ1 # 'Z'
end
elseif band == cbL2
if code == tcC2M || code == tcG1D
code = tcJM2 # 'S'
elseif code == tcC2L || code == tcG1P
code = tcJL2 # 'L'
elseif code == tcC2LM || code == tcG1X
code = tcJX2 # 'X'
end
elseif band == cbL5
if code == tcI5 code = tcJI5 # 'I'
elseif code == tcQ5 code = tcJQ5 # 'Q'
elseif code == tcC2LM code = tcJIQ5 # 'X'
end
elseif band == cbE6
if code == tcC2M || code == tcG1D
code = tcJI6 # 'S'
elseif code == tcC2L || code == tcG1P
code = tcJQ6 # 'L'
elseif code == tcC2LM || code == tcG1X
code = tcJIQ6 # 'X'
end
end
elseif sys == sstBeiDou
if band == cbL1 band = cbB1 # RINEX 3.02
elseif band == cbL2 band = cbB1 # RINEX 3.0[013]
elseif band == cbE6 band = cbB3
elseif band == cbB1
if code == tcI5 code = tcCI1 # 'I'
elseif code == tcQ5 code = tcCQ1 # 'Q'
elseif code == tcC2LM || code == tcG1X
code = tcCIQ1 # 'X'
end
elseif band == cbB3
if code == tcI5 code = tcCI7 # 'I'
elseif code == tcQ5 code = tcCQ7 # 'Q'
elseif code == tcC2LM || code == tcG1X
code = tcCIQ7 # 'X'
end
elseif band == cbE5b
if code == tcI5 code = tcCI6 # 'I'
elseif code == tcQ5 code = tcCQ6 # 'Q'
elseif code == tcC2LM || code == tcG1X
code = tcCIQ6 # 'X'
end
end
elseif sys == sstIRNSS # IRNSS
if band == cbL5
if code == tcCA code = tcIA5 # 'A'
elseif code == tcA code = tcIB5 # 'B'
elseif code == tcB code = tcIC5 # 'B'
elseif code == tcC2LM || code == tcG1X
code = tcIX5 # 'X'
end
end
end
new(str, type, band, code, sys)
end
end
|
# ************************************************************************
# FAUST Architecture File
# Copyright (C) 2021 GRAME, Centre National de Creation Musicale
# ---------------------------------------------------------------------
# This is sample code. This file is provided as an example of minimal
# FAUST architecture file. Redistribution and use in source and binary
# forms, with or without modification, in part or in full are permitted.
# In particular you can create a derived work of this FAUST architecture
# and distribute that work under terms of your choice.
# This sample code 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.
# ************************************************************************
using Gtk, GtkObservables
# GTKUI: a basic GUI developed using the GtkObservables package
mutable struct GTKUI <: UI
GTKUI(dsp::dsp) = begin
gtk_ui = new()
gtk_ui.dsp = dsp
gtk_ui.box = GtkBox(:v)
gtk_ui.window = GtkWindow("Faust Program", 400, 200) |> gtk_ui.box
gtk_ui
end
dsp::dsp
window
box
end
function run!(ui_interface::GTKUI)
showall(ui_interface.window)
#=
if !isinteractive()
@async Gtk.gtk_main()
Gtk.waitforsignal(ui_interface.window, :destroy)
end =#
if !isinteractive()
c = Condition()
signal_connect(ui_interface.window, :destroy) do widget
notify(c)
end
@async Gtk.gtk_main()
wait(c)
end
end
# -- active widgets
function addButton!(ui_interface::GTKUI, label::String, param::Symbol)
button = GtkObservables.button(label)
obs_func = on(observable(button)) do val
setproperty!(ui_interface.dsp, param, FAUSTFLOAT(1.0))
# Hack to make it work...
sleep(0.1)
setproperty!(ui_interface.dsp, param, FAUSTFLOAT(0.0))
end
push!(ui_interface.box, button)
end
function addCheckButton!(ui_interface::GTKUI, label::String, param::Symbol)
checkbox = GtkObservables.checkbox()
obs_func = on(observable(checkbox)) do val
setproperty!(ui_interface.dsp, param, FAUSTFLOAT(val))
end
push!(ui_interface.box, checkbox)
end
function addHorizontalSlider!(ui_interface::GTKUI, label::String, param::Symbol, init::FAUSTFLOAT, min::FAUSTFLOAT, max::FAUSTFLOAT, step::FAUSTFLOAT)
slider = GtkObservables.slider(min:max, value=init, orientation="horizontal")
label_str = GtkObservables.label(label)
obs_func = on(observable(slider)) do val
setproperty!(ui_interface.dsp, param, val)
end
box = GtkBox(:h)
push!(box, slider)
push!(box, label_str)
push!(ui_interface.box, box)
end
function addVerticalSlider!(ui_interface::GTKUI, label::String, param::Symbol, init::FAUSTFLOAT, min::FAUSTFLOAT, max::FAUSTFLOAT, step::FAUSTFLOAT)
slider = GtkObservables.slider(min:max, value=init, orientation="vertical")
set_gtk_property!(slider, :expand, true)
label_str = GtkObservables.label(label)
obs_func = on(observable(slider)) do val
setproperty!(ui_interface.dsp, param, val)
end
box = GtkBox(:v)
push!(box, slider)
push!(box, label_str)
push!(ui_interface.box, box)
end
function addNumEntry!(ui_interface::GTKUI, label::String, param::Symbol, init::FAUSTFLOAT, min::FAUSTFLOAT, max::FAUSTFLOAT, step::FAUSTFLOAT)
nentry = GtkObservables.textbox(FAUSTFLOAT; range=min:max, value=string(init))
label_str = GtkObservables.label(label)
obs_func = on(observable(nentry)) do val
setproperty!(ui_interface.dsp, param, val)
end
box = GtkBox(:h)
push!(box, nentry)
push!(box, label_str)
push!(ui_interface.box, box)
end
|
import numpy as np
import matplotlib.pyplot as plt
def generate_anomaly(shape = (100, 100, 50), n_anomalies = 2, a_size = 10,
random_state = None, noise_scale = .1):
np.random.seed(random_state)
# Assigning shape of image
X = np.zeros(shape)
y = np.zeros(shape[:2])
# Establishing position of anomalies
positions_x = np.random.random_integers(shape[0] - a_size,
size = n_anomalies)
positions_y = np.random.random_integers(shape[1] - a_size,
size = n_anomalies)
# Drawing anomalies on ground_truth
for i in range(n_anomalies):
y[positions_x[i]:positions_x[i]+a_size,
positions_y[i]:positions_y[i]+a_size] = 1
# Making class signatures
s_attr = np.linspace(0, 2*3.1415, shape[2])
a = .5 + np.random.random_sample()
b = .5 + np.random.random_sample()
anomaly_signature = (np.cos(a * s_attr) + 1)/2
background_signature = (np.sin(b * s_attr) + 1)/2
# Building image from Signatures
X[y==0] = background_signature
X[y==1] = anomaly_signature
# Creating noise
noise = np.abs(np.random.normal(0, noise_scale, shape))
X += noise
return X, y
|
[STATEMENT]
lemma unreach_empty_on_same_path:
assumes "P\<in>\<P>" "Q\<in>\<P>" "P=Q"
shows "\<forall>x. unreach-via P on Q from a to x = {}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. unreach-via P on Q from a to x = {}
[PROOF STEP]
unfolding unreachable_subset_via_notation_def unreachable_subset_via_def unreachable_subset_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. {Qy. [x;Qy;a] \<and> (\<exists>Rw\<in>P. a \<in> {x \<in> Q. Q \<in> \<P> \<and> Rw \<in> \<E> \<and> Rw \<notin> Q \<and> (\<nexists>Q. path Q Rw x)} \<and> Qy \<in> {x \<in> Q. Q \<in> \<P> \<and> Rw \<in> \<E> \<and> Rw \<notin> Q \<and> (\<nexists>Q. path Q Rw x)})} = {}
[PROOF STEP]
by (simp add: assms(3)) |
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name :
// Author : Avi
// Revision : $Revision: #85 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
#include <algorithm> // for std::transform
#include <boost/python.hpp>
#include <boost/core/noncopyable.hpp>
#include <boost/algorithm/string.hpp>
#include "ClientInvoker.hpp"
#include "Defs.hpp"
#include "ClientDoc.hpp"
#include "WhyCmd.hpp"
#include "UrlCmd.hpp"
#include "NState.hpp"
#include "Version.hpp"
#include "BoostPythonUtil.hpp"
#include "Log.hpp"
#ifdef ECF_OPENSSL
#include "Openssl.hpp"
#endif
using namespace boost::python;
using namespace std;
namespace bp = boost::python;
// See: http://wiki.python.org/moin/boost.python/HowTo#boost.function_objects
void set_host_port(ClientInvoker* self, const std::string& host,int port){ self->set_host_port(host,boost::lexical_cast<std::string>(port));}
std::string version(ClientInvoker* self) { return ecf::Version::raw();}
std::string server_version(ClientInvoker* self) { self->server_version(); return self->get_string();}
const std::string& query(ClientInvoker* self,
const std::string& query_type,
const std::string& path_to_attribute,
const std::string& attribute) { self->query(query_type,path_to_attribute,attribute); return self->get_string();}
const std::string& query1(ClientInvoker* self,
const std::string& query_type,
const std::string& path_to_attribute) { self->query(query_type,path_to_attribute,""); return self->get_string();}
//const std::string& get_log(ClientInvoker* self) { self->getLog(); return self->get_string();}
const std::string& get_log(ClientInvoker* self, int lastLines)
{ self->getLog(lastLines); return self->get_string();}
const std::string& edit_script_edit(ClientInvoker* self,
const std::string& absNodePath )
{ self->edit_script_edit(absNodePath); return self->get_string(); }
const std::string& edit_script_preprocess(ClientInvoker* self,
const std::string& absNodePath )
{ self->edit_script_preprocess(absNodePath); return self->get_string(); }
int edit_script_submit(ClientInvoker* self,
const std::string& absNodePath,
const bp::list& name_values,
const bp::list& lines,
bool alias = false,
bool run = true
) {
std::vector<std::string> file_contents;
BoostPythonUtil::list_to_str_vec(lines, file_contents);
std::vector<std::string> namv;
BoostPythonUtil::list_to_str_vec(name_values, namv);
NameValueVec used_variables;
char sep = '=';
for (int i=0; i<namv.size(); ++i) {
string::size_type pos = namv[i].find(sep);
used_variables.push_back(std::make_pair(
namv[i].substr(0, pos-1),
namv[i].substr(pos+1, namv[i].length())));
}
return self->edit_script_submit(absNodePath,
used_variables,
file_contents,
alias,
run);
}
const std::string& get_file(ClientInvoker* self,
const std::string& absNodePath,
const std::string& file_type = "script",
const std::string& max_lines = "10000")
{ self->file(absNodePath,file_type,max_lines); return self->get_string(); }
const std::string& get_file_1(ClientInvoker* self,
const std::string& absNodePath,
const std::string& file_type = "script" )
{ self->file(absNodePath,file_type,"10000"); return self->get_string(); }
/// Set the CLI to enable output to standard out
class CliSetter {
public:
explicit CliSetter(ClientInvoker* self) : _self(self) { self->set_cli(true); }
~CliSetter() { _self->set_cli(false);}
private:
ClientInvoker* _self;
};
void stats(ClientInvoker* self) { CliSetter setter(self); self->stats(); }
void stats_reset(ClientInvoker* self) { self->stats_reset(); }
bp::list suites(ClientInvoker* self) {
self->suites();
const std::vector<std::string>& the_suites = self->server_reply().get_string_vec();
bp::list list;
size_t the_size = the_suites.size();
for(size_t i = 0; i < the_size; i++) list.append( the_suites[i] );
return list;
}
bool news_local(ClientInvoker* self) { self->news_local(); return self->get_news(); }
void free_trigger_dep(ClientInvoker* self, const std::string& path) { self->freeDep(path,true /*trigger*/,false/*all*/,false/*date*/,false/*time*/); }
void free_date_dep(ClientInvoker* self, const std::string& path) { self->freeDep(path,false/*trigger*/,false/*all*/,true /*date*/,false/*time*/); }
void free_time_dep(ClientInvoker* self, const std::string& path) { self->freeDep(path,false/*trigger*/,false/*all*/,false/*date*/,true /*time*/); }
void free_all_dep(ClientInvoker* self, const std::string& path) { self->freeDep(path,false/*trigger*/,true /*all*/,false/*date*/,false/*time*/); }
void free_trigger_dep1(ClientInvoker* self,const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->freeDep(paths,true /*trigger*/,false/*all*/,false/*date*/,false/*time*/); }
void free_date_dep1(ClientInvoker* self, const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->freeDep(paths,false/*trigger*/,false/*all*/,true /*date*/,false/*time*/); }
void free_time_dep1(ClientInvoker* self, const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->freeDep(paths,false/*trigger*/,false/*all*/,false/*date*/,true /*time*/); }
void free_all_dep1(ClientInvoker* self, const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->freeDep(paths,false/*trigger*/,true /*all*/,false/*date*/,false/*time*/); }
void force_state(ClientInvoker* self, const std::string& path, NState::State state) { self->force(path,NState::toString(state),false);}
void force_states(ClientInvoker* self, const bp::list& list, NState::State state){ std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->force(paths,NState::toString(state),false);}
void force_state_recursive(ClientInvoker* self, const std::string& path, NState::State state) { self->force(path,NState::toString(state),true);}
void force_states_recursive(ClientInvoker* self,const bp::list& list,NState::State state){ std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->force(paths,NState::toString(state),true);}
void force_event(ClientInvoker* self, const std::string& path, const std::string& set_or_clear) { self->force(path,set_or_clear);}
void force_events(ClientInvoker* self,const bp::list& list,const std::string& set_or_clear) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->force(paths,set_or_clear);}
void run(ClientInvoker* self, const std::string& path, bool force) { self->run(path,force);}
void runs(ClientInvoker* self,const bp::list& list, bool force) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths); self->run(paths,force);}
void requeue(ClientInvoker* self,std::string path, const std::string& option) { self->requeue(path,option);}
void requeues(ClientInvoker* self,const bp::list& list, const std::string& option) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->requeue(paths,option);}
void suspend(ClientInvoker* self, const std::string& path) { self->suspend(path);}
void suspends(ClientInvoker* self,const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->suspend(paths);}
void resume(ClientInvoker* self, const std::string& path) { self->resume(path);}
void resumes(ClientInvoker* self,const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->resume(paths);}
void archive(ClientInvoker* self, const std::string& path) { self->archive(path);}
void archives(ClientInvoker* self,const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->archive(paths);}
void restore(ClientInvoker* self, const std::string& path) { self->restore(path);}
void restores(ClientInvoker* self,const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->restore(paths);}
void the_status(ClientInvoker* self, const std::string& path) { self->status(path);}
void statuss(ClientInvoker* self,const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->status(paths);}
void do_kill(ClientInvoker* self, const std::string& path) { self->kill(path);}
void do_kills(ClientInvoker* self,const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->kill(paths);}
const std::string& check(ClientInvoker* self, const std::string& node_path) { self->check(node_path); return self->get_string(); }
const std::string& checks(ClientInvoker* self, const bp::list& list) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->check(paths); return self->get_string(); }
void delete_node(ClientInvoker* self,const bp::list& list, bool force) { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->delete_nodes(paths,force);}
void ch_suites(ClientInvoker* self){ CliSetter cli(self);self->ch_suites();}
void ch_register(ClientInvoker* self,bool auto_add_new_suites,const bp::list& list)
{std::vector<std::string> suites;BoostPythonUtil::list_to_str_vec(list,suites); self->ch_register(auto_add_new_suites,suites);}
void ch_add(ClientInvoker* self,int client_handle,const bp::list& list)
{std::vector<std::string> suites;BoostPythonUtil::list_to_str_vec(list,suites); self->ch_add(client_handle,suites);}
void ch1_add(ClientInvoker* self,const bp::list& list)
{std::vector<std::string> suites;BoostPythonUtil::list_to_str_vec(list,suites); self->ch1_add(suites);}
void ch_remove(ClientInvoker* self,int client_handle,const bp::list& list)
{std::vector<std::string> suites;BoostPythonUtil::list_to_str_vec(list,suites); self->ch_remove(client_handle,suites);}
void ch1_remove(ClientInvoker* self,const bp::list& list)
{std::vector<std::string> suites;BoostPythonUtil::list_to_str_vec(list,suites); self->ch1_remove(suites);}
/// Need to provide override since the boolean argument is optional.
/// This saves on client python code, on having to specify the optional arg
void replace_1(ClientInvoker* self,const std::string& absNodePath, defs_ptr client_defs) { self->replace_1(absNodePath,client_defs);}
void replace_2(ClientInvoker* self,const std::string& absNodePath, const std::string& path_to_client_defs) { self->replace(absNodePath,path_to_client_defs);}
void order(ClientInvoker* self,const std::string& absNodePath,const std::string& the_order){ self->order(absNodePath,the_order);}
void alters(ClientInvoker* self,
const bp::list& list,
const std::string& alterType, /* one of [ add | change | delete | set_flag | clear_flag ] */
const std::string& attrType,
const std::string& name = "",
const std::string& value = "") { std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->check(paths);self->alter(paths,alterType,attrType,name,value); }
void alter(ClientInvoker* self,
const std::string& path,
const std::string& alterType, /* one of [ add | change | delete | set_flag | clear_flag ] */
const std::string& attrType,
const std::string& name = "",
const std::string& value = "") { self->alter(path,alterType,attrType,name,value); }
void alter_sorts(ClientInvoker* self,
const bp::list& list,
const std::string& attribute_name,
bool recursive = true) {std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths);self->check(paths);self->alter_sort(paths,attribute_name,recursive); }
void alter_sort(ClientInvoker* self,
const std::string& path,
const std::string& attribute_name,
bool recursive = true) {self->alter_sort(std::vector<std::string>(1,path),attribute_name,recursive ); }
void set_child_pid(ClientInvoker* self,int pid) { self->set_child_pid( boost::lexical_cast<std::string>(pid)); }
void set_child_init_add_vars(ClientInvoker* self,const bp::dict& dict){
std::vector<std::pair<std::string,std::string> > vars;
BoostPythonUtil::dict_to_str_vec(dict,vars);
std::vector<Variable> vec;
std::transform(vars.begin(),vars.end(),std::back_inserter(vec),
[]( const std::pair<std::string,std::string>& var) { return Variable(var.first,var.second);});
self->set_child_init_add_vars(vec);
}
void set_child_init_add_vars2(ClientInvoker* self,const bp::list& dict){
std::vector<Variable> vec;
BoostPythonUtil::list_to_str_vec(dict,vec);
self->set_child_init_add_vars(vec);
}
void set_child_complete_del_vars(ClientInvoker* self,const bp::list& dict){
std::vector<std::string> vars;
BoostPythonUtil::list_to_str_vec(dict,vars);
self->set_child_complete_del_vars(vars);
}
// Context mgr. The expression is evaluated and should result in an object called a ``context manager''
// with expression [as variable]:
// with-block
//
// . The context manager must have __enter__() and __exit__() methods.
// . The context manager's __enter__() method is called.
// The value returned is assigned to VAR.
// If no 'as VAR' clause is present, the value is simply discarded.
// . The code in BLOCK is executed.
// . If BLOCK raises an exception, the __exit__(type, value, traceback)
// is called with the exception details, the same values returned by sys.exc_info().
// The method's return value controls whether the exception is re-raised:
// any false value re-raises the exception, and True will result in suppressing it.
// You'll only rarely want to suppress the exception, because if you do the author
// of the code containing the 'with' statement will never realize anything went wrong.
// . If BLOCK didn't raise an exception, the __exit__() method is still called, but type, value, and traceback are all None.
//
std::shared_ptr<ClientInvoker> client_enter(std::shared_ptr<ClientInvoker> self) { return self;}
bool client_exit(std::shared_ptr<ClientInvoker> self,const bp::object& type,const bp::object& value,const bp::object& traceback){
self->ch1_drop();
return false;
}
const std::vector<Zombie>& zombieGet(ClientInvoker* self,int pid) {
self->zombieGet();
return self->server_reply().zombies();
}
void zombieFobCli(ClientInvoker* self,const bp::list& list){std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths); self->zombieFobCliPaths(paths);}
void zombieFailCli(ClientInvoker* self,const bp::list& list){std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths); self->zombieFailCliPaths(paths);}
void zombieAdoptCli(ClientInvoker* self,const bp::list& list){std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths); self->zombieAdoptCliPaths(paths);}
void zombieBlockCli(ClientInvoker* self,const bp::list& list){std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths); self->zombieBlockCliPaths(paths);}
void zombieRemoveCli(ClientInvoker* self,const bp::list& list){std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths); self->zombieRemoveCliPaths(paths);}
void zombieKillCli(ClientInvoker* self,const bp::list& list){std::vector<std::string> paths;BoostPythonUtil::list_to_str_vec(list,paths); self->zombieKillCliPaths(paths);}
void export_Client()
{
// Need std::shared_ptr<ClientInvoker>, to add support for with( __enter__,__exit__)
class_<ClientInvoker,std::shared_ptr<ClientInvoker>,boost::noncopyable>("Client",ClientDoc::class_client())
.def( init<std::string>() /* host:port */)
.def( init<std::string,std::string>() /* host, port */)
.def( init<std::string,int>() /* host, port(int) */)
.def("__enter__", &client_enter) // allow with statement
.def("__exit__", &client_exit) // allow with statement, remove last handle
.def("version", &version, "Returns the current client version")
.def("set_user_name", &ClientInvoker::set_user_name,"set user name. A password must be provided in the file <host>.<port>.ecf.custom_passwd")
.def("server_version", &server_version, "Returns the server version, can throw for old servers, that did not implement this request.")
.def("set_host_port", &ClientInvoker::set_host_port, ClientDoc::set_host_port())
.def("set_host_port", &ClientInvoker::set_hostport )
.def("set_host_port", &set_host_port)
.def("get_host", &ClientInvoker::host, return_value_policy<copy_const_reference>(), "Return the host, assume set_host_port() has been set, otherwise return localhost" )
.def("get_port", &ClientInvoker::port, return_value_policy<copy_const_reference>(), "Return the port, assume set_host_port() has been set. otherwise returns 3141" )
.def("set_retry_connection_period",&ClientInvoker::set_retry_connection_period, ClientDoc::set_retry_connection_period())
.def("set_connection_attempts",&ClientInvoker::set_connection_attempts, ClientDoc::set_connection_attempts())
.def("set_auto_sync", &ClientInvoker::set_auto_sync,"If true automatically sync with local definition after each call.")
.def("is_auto_sync_enabled",&ClientInvoker::is_auto_sync_enabled,"Returns true if automatic syncing enabled")
.def("get_defs", &ClientInvoker::defs, ClientDoc::get_defs())
.def("reset", &ClientInvoker::reset, "reset client definition, and handle number")
.def("in_sync", &ClientInvoker::in_sync, ClientDoc::in_sync())
.def("get_log" , &get_log, return_value_policy<copy_const_reference>(), ClientDoc::get_log())
.def("edit_script_edit", &edit_script_edit, return_value_policy<copy_const_reference>(), ClientDoc::edit_script_edit())
.def("edit_script_preprocess", &edit_script_preprocess, return_value_policy<copy_const_reference>(), ClientDoc::edit_script_preprocess())
.def("edit_script_submit", &edit_script_submit, ClientDoc::edit_script_submit())
.def("new_log", &ClientInvoker::new_log, (bp::arg("path")=""),ClientDoc::new_log())
.def("clear_log", &ClientInvoker::clearLog, ClientDoc::clear_log())
.def("flush_log", &ClientInvoker::flushLog, ClientDoc::flush_log())
.def("log_msg", &ClientInvoker::logMsg, ClientDoc::log_msg())
.def("restart_server", &ClientInvoker::restartServer, ClientDoc::restart_server())
.def("halt_server", &ClientInvoker::haltServer, ClientDoc::halt_server())
.def("shutdown_server", &ClientInvoker::shutdownServer, ClientDoc::shutdown_server())
.def("terminate_server", &ClientInvoker::terminateServer, ClientDoc::terminate_server())
.def("wait_for_server_reply",&ClientInvoker::wait_for_server_reply,(bp::arg("time_out")=60), ClientDoc::wait_for_server_reply())
.def("load" , &ClientInvoker::loadDefs,(bp::arg("path_to_defs"),bp::arg("force")=false,bp::arg("check_only")=false,bp::arg("print")=false,bp::arg("stats")=false),ClientDoc::load_defs())
.def("load" , &ClientInvoker::load,(bp::arg("defs"), bp::arg("force")=false),ClientDoc::load())
.def("get_server_defs", &ClientInvoker::getDefs, ClientDoc::get_server_defs())
.def("sync_local", &ClientInvoker::sync_local,(bp::arg("sync_suite_clock")=false),ClientDoc::sync())
.def("news_local", &news_local, ClientDoc::news())
.add_property("changed_node_paths",bp::range( &ClientInvoker::changed_node_paths_begin, &ClientInvoker::changed_node_paths_end),ClientDoc::changed_node_paths())
.def("suites" , &suites, ClientDoc::suites())
.def("ch_register", &ch_register, ClientDoc::ch_register())
.def("ch_suites", &ch_suites, ClientDoc::ch_suites())
.def("ch_handle", &ClientInvoker::client_handle, ClientDoc::ch_register())
.def("ch_drop", &ClientInvoker::ch_drop, ClientDoc::ch_drop())
.def("ch_drop", &ClientInvoker::ch1_drop)
.def("ch_drop_user", &ClientInvoker::ch_drop_user, ClientDoc::ch_drop_user())
.def("ch_add", &ch_add, ClientDoc::ch_add())
.def("ch_add", &ch1_add )
.def("ch_remove", &ch_remove, ClientDoc::ch_remove())
.def("ch_remove", &ch1_remove)
.def("ch_auto_add", &ClientInvoker::ch_auto_add, ClientDoc::ch_auto_add())
.def("ch_auto_add", &ClientInvoker::ch1_auto_add)
.def("checkpt", &ClientInvoker::checkPtDefs, (bp::arg("mode")=ecf::CheckPt::UNDEFINED, bp::arg("check_pt_interval")=0,bp::arg("check_pt_save_alarm_time")=0), ClientDoc::checkpt())
.def("restore_from_checkpt",&ClientInvoker::restoreDefsFromCheckPt,ClientDoc::restore_from_checkpt())
.def("reload_wl_file" , &ClientInvoker::reloadwsfile, ClientDoc::reload_wl_file())
.def("reload_passwd_file",&ClientInvoker::reloadpasswdfile,"reload the passwd file. <host>.<port>.ecf.passwd")
.def("reload_custom_passwd_file",&ClientInvoker::reloadcustompasswdfile,"reload the custom passwd file. <host>.<port>.ecf.cusom_passwd. For users using ECF_USER or --user or set_user_name()")
.def("requeue" , &requeue, (bp::arg("abs_node_path"), bp::arg("option")=""), ClientDoc::requeue())
.def("requeue" , &requeues, (bp::arg("paths"), bp::arg("option")="") )
.def("free_trigger_dep", &free_trigger_dep, ClientDoc::free_trigger_dep())
.def("free_trigger_dep", &free_trigger_dep1 )
.def("free_date_dep", &free_date_dep, ClientDoc::free_date_dep())
.def("free_date_dep", &free_date_dep1 )
.def("free_time_dep", &free_time_dep, ClientDoc::free_time_dep())
.def("free_time_dep", &free_time_dep1)
.def("free_all_dep", &free_all_dep, ClientDoc::free_all_dep())
.def("free_all_dep", &free_all_dep1)
.def("ping" , &ClientInvoker::pingServer, ClientDoc::ping())
.def("stats" , &stats, ClientDoc::stats())
.def("stats_reset" , &stats_reset, ClientDoc::stats_reset())
.def("get_file" , &get_file, return_value_policy<copy_const_reference>(), ClientDoc::get_file())
.def("get_file" , &get_file_1, return_value_policy<copy_const_reference>())
.def("plug" , &ClientInvoker::plug, ClientDoc::plug())
.def("query" , &query, return_value_policy<copy_const_reference>(),ClientDoc::query())
.def("query" , &query1, return_value_policy<copy_const_reference>(),ClientDoc::query())
.def("alter" , &alters,(bp::arg("paths"),bp::arg("alter_type"),bp::arg("attribute_type"),bp::arg("name")="",bp::arg("value")=""), ClientDoc::alter())
.def("alter" , &alter,(bp::arg("abs_node_path"),bp::arg("alter_type"),bp::arg("attribute_type"),bp::arg("name")="",bp::arg("value")=""))
.def("sort_attributes" , &alter_sort,(bp::arg("abs_node_path"),bp::arg("attribute_name"),bp::arg("recursive")=true))
.def("sort_attributes" , &alter_sorts,(bp::arg("paths"),bp::arg("attribute_name"),bp::arg("recursive")=true))
.def("force_event" , &force_event, ClientDoc::force_event())
.def("force_event" , &force_events)
.def("force_state" , &force_state, ClientDoc::force_state())
.def("force_state" , &force_states)
.def("force_state_recursive",&force_state_recursive, ClientDoc::force_state_recursive())
.def("force_state_recursive",&force_states_recursive)
.def("replace" , &ClientInvoker::replace, ClientDoc::replace())
.def("replace" , &ClientInvoker::replace_1)
.def("replace" , &replace_1 )
.def("replace" , &replace_2 )
.def("order" , &order, ClientDoc::order())
.def("group" , &ClientInvoker::group, ClientDoc::group())
.def("begin_suite" , &ClientInvoker::begin, (bp::arg("suite_name"),bp::arg("force")=false), ClientDoc::begin_suite())
.def("begin_all_suites", &ClientInvoker::begin_all_suites,(bp::arg("force")=false), ClientDoc::begin_all())
.def("job_generation", &ClientInvoker::job_gen, ClientDoc::job_gen())
.def("run" , &run, ClientDoc::run())
.def("run" , &runs)
.def("check" , &check, return_value_policy<copy_const_reference>(), ClientDoc::check())
.def("check" , &checks, return_value_policy<copy_const_reference>())
.def("kill" , &do_kill, ClientDoc::kill())
.def("kill" , &do_kills)
.def("status" , &the_status, ClientDoc::status())
.def("status" , &statuss)
.def("suspend" , &suspend, ClientDoc::suspend())
.def("suspend" , &suspends)
.def("resume" , &resume, ClientDoc::resume())
.def("resume" , &resumes)
.def("archive" , &archive, ClientDoc::archive())
.def("archive" , &archives)
.def("restore" , &restore, ClientDoc::restore())
.def("restore" , &restores)
.def("delete" , &ClientInvoker::delete_node, (bp::arg("abs_node_path"),bp::arg("force")=false), ClientDoc::delete_node())
.def("delete" , &delete_node, (bp::arg("paths"),bp::arg("force")=false))
.def("delete_all", &ClientInvoker::delete_all, (bp::arg("force")=false), ClientDoc::delete_all())
.def("debug_server_on", &ClientInvoker::debug_server_on, "Enable server debug, Will dump to standard out on server host.")
.def("debug_server_off", &ClientInvoker::debug_server_off, "Disable server debug")
.def("debug", &ClientInvoker::debug, "enable/disable client api debug")
#ifdef ECF_OPENSSL
.def("enable_ssl", &ClientInvoker::enable_ssl, ecf::Openssl::ssl_info())
.def("disable_ssl", &ClientInvoker::disable_ssl, ecf::Openssl::ssl_info())
#endif
.def("zombie_get", &zombieGet, return_value_policy<copy_const_reference>())
.def("zombie_fob", &ClientInvoker::zombieFobCli )
.def("zombie_fail", &ClientInvoker::zombieFailCli )
.def("zombie_adopt", &ClientInvoker::zombieAdoptCli )
.def("zombie_block", &ClientInvoker::zombieBlockCli )
.def("zombie_remove", &ClientInvoker::zombieRemoveCli )
.def("zombie_kill", &ClientInvoker::zombieKillCli )
.def("zombie_fob", &zombieFobCli )
.def("zombie_fail", &zombieFailCli )
.def("zombie_adopt", &zombieAdoptCli )
.def("zombie_block", &zombieBlockCli )
.def("zombie_remove", &zombieRemoveCli )
.def("zombie_kill", &zombieKillCli )
.def("set_child_path", &ClientInvoker::set_child_path , ClientDoc::set_child_path())
.def("set_child_password", &ClientInvoker::set_child_password, ClientDoc::set_child_password())
.def("set_child_pid", &ClientInvoker::set_child_pid, ClientDoc::set_child_pid())
.def("set_child_pid", &set_child_pid, ClientDoc::set_child_pid())
.def("set_child_try_no", &ClientInvoker::set_child_try_no, ClientDoc::set_child_try_no())
.def("set_child_timeout", &ClientInvoker::set_child_timeout, ClientDoc::set_child_timeout())
.def("set_child_init_add_vars", &set_child_init_add_vars, ClientDoc::set_child_init_add_vars() )
.def("set_child_init_add_vars", &set_child_init_add_vars2, ClientDoc::set_child_init_add_vars() )
.def("set_child_complete_del_vars",&set_child_complete_del_vars,ClientDoc::set_child_complete_del_vars() )
.def("set_zombie_child_timeout",&ClientInvoker::set_zombie_child_timeout, "Set timeout for zombie child commands,that cannot connect to server, default is 24 hours. The input is required to be in seconds")
.def("child_init", &ClientInvoker::child_init, "Child command,notify server job has started")
.def("child_abort", &ClientInvoker::child_abort,(bp::arg("reason")=""), "Child command,notify server job has aborted, can provide an optional reason")
.def("child_event", &ClientInvoker::child_event,(bp::arg("event_name"),bp::arg("value")=true),"Child command,notify server event occurred, requires the event name")
.def("child_meter", &ClientInvoker::child_meter, "Child command,notify server meter changed, requires meter name and value")
.def("child_label", &ClientInvoker::child_label, "Child command,notify server label changed, requires label name, and new value")
.def("child_wait", &ClientInvoker::child_wait, "Child command,wait for expression to come true")
.def("child_queue", &ClientInvoker::child_queue,(bp::arg("queue_name"),bp::arg("action"),bp::arg("step")="",bp::arg("path_to_node_with_queue")=""),"Child command,active:return current step as string, then increment index, requires queue name, and optionally path to node with the queue")
.def("child_complete", &ClientInvoker::child_complete,"Child command,notify server job has complete")
;
class_<WhyCmd, boost::noncopyable >( "WhyCmd",
"The why command reports, the reason why a node is not running.\n\n"
"It needs the definition structure and the path to node\n"
"\nConstructor::\n\n"
" WhyCmd(defs, node_path)\n"
" defs_ptr defs : pointer to a definition structure\n"
" string node_path : The node path\n\n"
"\nExceptions:\n\n"
"- raises RuntimeError if the definition is empty\n"
"- raises RuntimeError if the node path is empty\n"
"- raises RuntimeError if the node path cannot be found in the definition\n"
"\nUsage::\n\n"
" try:\n"
" ci = Client()\n"
" ci.sync_local()\n"
" ask = WhyCmd(ci.get_defs(),'/suite/family')\n"
" print(ask.why())\n"
" except RuntimeError, e:\n"
" print(str(e))\n\n"
,
init<defs_ptr,std::string >()
)
.def("why", &WhyCmd::why, "returns a '/n' separated string, with reasons why node is not running")
;
class_<UrlCmd, boost::noncopyable >( "UrlCmd",
"Executes a command ECF_URL_CMD to display a url.\n\n"
"It needs the definition structure and the path to node.\n"
"\nConstructor::\n\n"
" UrlCmd(defs, node_path)\n"
" defs_ptr defs : pointer to a definition structure\n"
" string node_path : The node path.\n\n"
"\nExceptions\n\n"
"- raises RuntimeError if the definition is empty\n"
"- raises RuntimeError if the node path is empty\n"
"- raises RuntimeError if the node path cannot be found in the definition\n"
"- raises RuntimeError if ECF_URL_CMD not defined or if variable substitution fails\n"
"\nUsage:\n"
"Lets assume that the server has the following definition::\n\n"
" suite s\n"
" edit ECF_URL_CMD \"${BROWSER:=firefox} -new-tab %ECF_URL_BASE%/%ECF_URL%\"\n"
" edit ECF_URL_BASE \"http://www.ecmwf.int\"\n"
" family f\n"
" task t1\n"
" edit ECF_URL \"publications/manuals/ecflow\"\n"
" task t2\n"
" edit ECF_URL index.html\n\n"
"::\n\n"
" try:\n"
" ci = Client()\n"
" ci.sync_local()\n"
" url = UrlCmd(ci.get_defs(),'/suite/family/task')\n"
" print(url.execute())\n"
" except RuntimeError, e:\n"
" print(str(e))\n\n"
,
init<defs_ptr,std::string >()
)
.def("execute", &UrlCmd::execute, "Displays url in the chosen browser")
;
}
|
Garrison ( April 10 , 1998 ) son
|
// (C) Copyright 2015 - 2018 Christopher Beck
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
/***
* How to transfer `boost::optional` to and from the stack, using strict
* optional semantics
*/
#include <primer/base.hpp>
PRIMER_ASSERT_FILESCOPE;
//[ primer_example_boost_optional_decl
#include <boost/optional/optional.hpp>
#include <primer/container/optional_base.hpp>
namespace primer {
namespace traits {
template <typename T>
struct push<boost::optional<T>> //
: container::optional_push<boost::optional<T>> {};
template <typename T>
struct read<boost::optional<T>>
: container::optional_strict_read<boost::optional<T>> {};
} // end namespace traits
} // end namespace primer
//]
|
[STATEMENT]
lemma sqrt_zero [simp]: "sqrt 0 = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. local.sqrt 0 = 0
[PROOF STEP]
using sqrt_inverse_power2 [of 0]
[PROOF STATE]
proof (prove)
using this:
local.sqrt (0\<^sup>2) = 0
goal (1 subgoal):
1. local.sqrt 0 = 0
[PROOF STEP]
by simp |
#include <boost/test/unit_test.hpp>
#include <memory>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include "xmlutils.hpp"
#include "lineside/xml/xercesguard.hpp"
#include "lineside/xml/utilities.hpp"
#include "lineside/xml/settingsreader.hpp"
// =================================
const std::string simpleSettingsFragment = "settings-fragment.xml";
const std::string simpleSettingsCommentFragment = "settings-comment-fragment.xml";
// =================================
BOOST_AUTO_TEST_SUITE( xml )
BOOST_AUTO_TEST_SUITE( SettingsReader )
BOOST_AUTO_TEST_CASE( SmokeSimpleFragment )
{
// Use guard to initialise library
Lineside::xml::XercesGuard xg;
// Configure the parser
auto parser = GetParser();
auto rootElement = GetRootElementOfFile(parser, simpleSettingsFragment);
BOOST_REQUIRE(rootElement);
Lineside::xml::SettingsReader reader;
BOOST_REQUIRE( reader.HasSettings(rootElement) );
auto settingsElement = reader.GetSettingsElement(rootElement);
auto result = reader.Read(settingsElement);
BOOST_CHECK_EQUAL( result.size(), 2 );
BOOST_CHECK_EQUAL( result.at("a"), "b" );
BOOST_CHECK_EQUAL( result.at("1"), "2" );
}
BOOST_AUTO_TEST_CASE( SmokeSimpleFragmentWithComment )
{
// Use guard to initialise library
Lineside::xml::XercesGuard xg;
// Configure the parser
auto parser = GetParser();
auto rootElement = GetRootElementOfFile(parser, simpleSettingsCommentFragment);
BOOST_REQUIRE(rootElement);
Lineside::xml::SettingsReader reader;
BOOST_REQUIRE( reader.HasSettings(rootElement) );
auto settingsElement = reader.GetSettingsElement(rootElement);
auto result = reader.Read(settingsElement);
BOOST_CHECK_EQUAL( result.size(), 2 );
BOOST_CHECK_EQUAL( result.at("c"), "d" );
BOOST_CHECK_EQUAL( result.at("3"), "4" );
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
|
Require Export Order.
Theorem wellorder_subst {R A X} :
well_order R A -> X ⊂ A -> well_order R X.
Proof.
intros H XA.
induction H as [W T].
unfold well_found in W.
induction T as [trans_ T].
induction T as [notrefl tri].
split.
+ intros Y YX notY.
apply W.
- intros y yY.
apply (XA y (YX y yY)).
- done.
+ split.
intros x y z xX yX zX xyR yzR.
apply (trans_ x y z (XA x xX) (XA y yX) (XA z zX) xyR yzR).
split.
* intros x xX H.
apply ((notrefl x (XA x xX)) H) .
* intros x y xX yX.
induction (tri x y (XA x xX) (XA y yX)).
apply (or_introl H).
induction H.
apply (or_intror (or_introl H)).
apply (or_intror (or_intror H)).
Qed.
|
fid = fopen('list.txt');
C = textscan(fid, '%s %d');
all_class = 10575;
image_num_in_class = zeros(all_class,1);
image_in_class = cell(all_class,1);
for i = 1:all_class
image_in_class{i} = find(C{2} == i -1);
image_num_in_class(i) = length(image_in_class{i});
end;
fclose(fid);
% clear all;
% load('temp1.mat');
test_class = 2000-1;
test_num = sum(C{2}>all_class-test_class);
total = length(C{2});
train_num = total - test_num;
same_r = 0.5;
same_pair_l = floor(test_num / 2 * same_r);
same_in_class = randi(test_class,floor(same_pair_l * 2),1) + all_class-test_class;
same_in_class_unique = unique(same_in_class);
got_in_same = ones(total,1);
got_in_same(train_num+1:end) = 0;
pair1_same = zeros(same_pair_l * 10,1);
pair2_same = zeros(same_pair_l * 10,1);
p=1;
for i = 1: length(same_in_class_unique)
if mod(p,same_pair_l/100) == 0
disp([p same_pair_l]);
end;
c = same_in_class_unique(i);
n = sum(same_in_class == same_in_class_unique(i)) * 2;
s = image_num_in_class(c);
if n > s
n = floor(s / 2) * 2;
end;
idx_same = randperm(s);
for j = 1 : n / 2
pair1_same(p) = image_in_class{c}(idx_same(j*2-1));
pair2_same(p) = image_in_class{c}(idx_same(j*2));
% got_in_same(image_in_class{c}(idx_same(j*2-1))) = 1;
% got_in_same(image_in_class{c}(idx_same(j*2))) = 1;
% if p==same_pair_l
% break;
% end;
p = p + 1;
end;
end;
assert(p>same_pair_l);
idx = randperm(p-1);
pair1_same = pair1_same(idx(1:same_pair_l));
pair2_same = pair2_same(idx(1:same_pair_l));
assert(sum(C{2}(pair1_same) == C{2}(pair2_same)) == same_pair_l);
got_in_same(pair1_same) = 1;
got_in_same(pair2_same) = 1;
diff_num = test_num - length(pair1_same) * 2;
diff_sample = find(got_in_same==0);
idx = randperm(diff_num);
diff_sample = diff_sample(idx);
pair1_diff = diff_sample(1:(diff_num/2));
pair2_diff = diff_sample(diff_num/2 + 1:end);
err = find(C{2}(pair1_diff) == C{2}(pair2_diff));
% for i = 1 : length(err)
ridx = randperm(length(err));
pair1_diff(err) = pair1_diff(err(ridx));
% end;
assert(sum(C{2}(pair1_diff) == C{2}(pair2_diff)) == 0);
pair1 = [pair1_same;pair1_diff];
pair2 = [pair2_same;pair2_diff];
label_sim = [ones(length(pair1_same),1);zeros(length(pair1_diff),1)];
idx = randperm(length(pair1));
pair1 = pair1(idx);
pair2 = pair2(idx);
label_sim = label_sim(idx);
assert(sum((C{2}(pair1) == C{2}(pair2)) ~= label_sim) == 0);
fid1 = fopen('pair_data1_test.txt','w');
fid2 = fopen('pair_data2_test.txt','w');
fid3 = fopen('sim_label_test.txt','w');
for i = 1 : length(pair1)
fprintf(fid1,'%s %d\r\n',C{1}{pair1(i)},C{2}(pair1(i)));
fprintf(fid2,'%s %d\r\n',C{1}{pair2(i)},C{2}(pair2(i)));
fprintf(fid3,'%d\r\n',label_sim(i));
end;
fclose(fid1);
fclose(fid2);
fclose(fid3); |
lemma setdist_compact_closed: fixes A :: "'a::heine_borel set" assumes A: "compact A" and B: "closed B" and "A \<noteq> {}" "B \<noteq> {}" shows "\<exists>x \<in> A. \<exists>y \<in> B. dist x y = setdist A B" |
1560 River Pines Drive, Green Bay, WI 54311 (#50200306) :: Todd Wiese Homeselling System, Inc.
Luxury abounds in this custom-designed, one-of-a-kind condo located in the gated community of beautiful River Pines. This unique, 2 story condo overlooks Sunrise Lake, the property's largest fishing lake. Gourmet kitchen w/maple cabinets, granite countertops, center island, imported Italian glass backsplash, stainless appliances & extra large breakfast counter. Great room featuring tiled floors, vaulted ceilings, wetbar w/blt-in wine frig & onyx underlit countertop, fireplace, open staircase to upper level & panoramic views of the lake & golf course. Master bedrooms on both 1st & 2nd floors.
Listing provided courtesy of Tlc Advantage Real Estate, Llc. |
State Before: b x y : ℝ
b_pos : 0 < b
b_lt_one : b < 1
hx : 0 < x
⊢ logb b x < y ↔ b ^ y < x State After: no goals Tactic: rw [← rpow_lt_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hx] |
lemma complex_i_mult_minus [simp]: "\<i> * (\<i> * x) = - x" |
function gmmresults()
# example of GMM: draws from N(0,1). We estimate mean and variance.
y = randn(1000,1)
# 3 moment conditions implied by drawing from N(0,σ²):
# mean = 0, variance = constant, skew = 0
moments = θ -> [y.-θ[1] (y.^2.0).-θ[2] (y.-θ[1]).^3.0]
# first round consistent
W = Matrix{Float64}(I,3,3)
θ = [0.0, 1.0]
θhat, objvalue, D, ms, converged = gmm(moments, θ, W)
# second round efficient
Ωinv = inv(cov(ms))
gmmresults(moments, θhat, Ωinv, "GMM example, two step")
# CUE
gmmresults(moments, θhat)
return
end
function gmmresults(moments, θ, weight="", title="", names="", efficient=true)
n,g = size(moments(θ))
CUE = false
if weight !="" # if weight provided, use it
θhat, objvalue, D, ms, converged = gmm(moments, θ, weight)
else # do CUE
θhat, objvalue, D, ms, weight, converged = gmm(moments, θ)
CUE=true
end
k,g = size(D)
# estimate variance
efficient ? V = inv(D*weight*D')/n : V = V*D*weight*NeweyWest(ms)*weight*D'*V/n
if names==""
names = 1:k
names = names'
end
se = sqrt.(diag(V))
t = θhat ./ se
p = 2.0 .- 2.0*cdf.(Ref(TDist(n-k)),abs.(t))
PrintDivider()
if title !="" printstyled(title, color=:yellow); println() end
print("GMM Estimation Results Convergence: ")
printstyled(converged, color=:green)
CUE ? message=" (CUE)" : message=" (user weight matrix)"
printstyled(message, color=:cyan)
println()
println("Observations: ", n)
println("Hansen-Sargan statistic: ", round(n*objvalue, digits=5))
if g > k
println("Hansen-Sargan p-value: ", round(1.0 - cdf(Chisq(g-k),n*objvalue), digits=5))
end
a =[θhat se t p]
println("")
PrintEstimationResults(a, names)
println()
PrintDivider()
return θhat, objvalue, V, D, weight, converged
end
|
import Control.Indexed
import Control.Monad.Indexed.State
data State = One | Two | Three
data Transition : Type -> State -> State -> Type where
Pure : (x : a) -> Transition a s s
First : Transition () One Two
Second : Transition () Two Three
Third : Transition () Three One
Bind : Transition a x y -> (a -> Transition b y z) -> Transition b x z
IndexedFunctor State State Transition where
map f (Pure x) = Pure (f x)
map f First = Bind First (Pure . f)
map f Second = Bind Second (Pure . f)
map f Third = Bind Third (Pure . f)
map f (Bind x g) = Bind x (\x' => map f (g x'))
[n1] IndexedApplicative State Transition where
pure = Pure
ap (Pure f) x = map f x
ap (Bind y f) x =
Bind y $ \y' =>
Bind (f y') $ \f' =>
Bind x (\x' => Pure (f' x'))
IndexedMonad State Transition using n1 where
bind = Bind
data Meta = Description String
||| A Transition plus some metadata
TransitionPlus : Type -> State -> State -> Type
TransitionPlus = IndexedStateT Meta State State Transition
main : TransitionPlus () One One
main = do
put $ Description "meta text"
lift $ do
First
Second
x <- get
lift $ do
Indexed.ignore $ Pure x
Third
|
anom2regime <- function(ref, target, method = "distance", lat) {
posdim <- which(names(dim(ref)) == "nclust")
poslat <- which(names(dim(ref)) == "lat")
poslon <- which(names(dim(ref)) == "lon")
nclust <- dim(ref)[posdim]
if (all(dim(ref)[-posdim] != dim(target))) {
stop("The target should have the same dimensions [lat,lon] that
the reference ")
}
if (is.null(names(dim(ref))) | is.null(names(dim(target)))) {
stop(
"The arrays should include dimensions names ref[nclust,lat,lon]
and target [lat,lon]"
)
}
if (length(lat) != dim(ref)[poslat]) {
stop("latitudes do not match with the maps")
}
# This dimensions are reorganized
ref <- aperm(ref, c(posdim, poslat, poslon))
target <-
aperm(target, c(which(names(dim(
target
)) == "lat"), which(names(dim(
target
)) == "lon")))
# weights are defined
latWeights <- InsertDim(sqrt(cos(lat * pi / 180)), 2, dim(ref)[3]) #nolint
rmsdiff <- function(x, y) {
dims <- dim(x)
ndims <- length(dims)
if (ndims != 2 | ndims != length(dim(y))) {
stop("x and y should be maps")
}
map_diff <- NA * x
for (i in 1 : dims[1]) {
for (j in 1 : dims[2]) {
map_diff[i, j] <- (x[i, j] - y[i, j]) ^ 2
}
}
rmsdiff <- sqrt(mean(map_diff, na.rm = TRUE))
return(rmsdiff)
}
if (method == "ACC") {
corr <- rep(NA, nclust)
for (i in 1:nclust) {
corr[i] <-
ACC(InsertDim(InsertDim( #nolint
InsertDim(ref[i, , ] * latWeights, 1, 1), 2, 1 #nolint
), 3, 1),
InsertDim(InsertDim( #nolint
InsertDim(target * latWeights, 1, 1), 2, 1 #nolint
), 3, 1))$ACC[2]
}
assign <- which(corr == max(corr))
}
if (method == "distance") {
rms <- rep(NA, nclust)
for (i in 1 : nclust) {
rms[i] <- rmsdiff(ref[i, , ] * latWeights, target * latWeights)#nolint
}
assign <- which(rms == min(rms, na.rm = TRUE))
}
return(assign)
}
RegimesAssign <- function(var_ano, ref_maps, lats, #nolint
method = "distance") {
posdim <- which(names(dim(ref_maps)) == "nclust")
poslat <- which(names(dim(ref_maps)) == "lat")
poslon <- which(names(dim(ref_maps)) == "lon")
poslat_ano <- which(names(dim(var_ano)) == "lat")
poslon_ano <- which(names(dim(var_ano)) == "lon")
nclust <- dim(ref_maps)[posdim]
nlat <- dim(ref_maps)[poslat]
nlon <- dim(ref_maps)[poslon]
if (is.null(names(dim(ref_maps))) | is.null(names(dim(var_ano)))) {
stop(
"The arrays should include dimensions names ref[nclust,lat,lon]
and target [lat,lon]"
)
}
if (length(lats) != dim(ref_maps)[poslat]) {
stop("latitudes do not match with the maps")
}
print(str(var_ano))
assign <-
Apply(
data = list(target = var_ano),
margins = c( (1 : length(dim(var_ano)) )[-c(poslat_ano, poslon_ano)]),
fun = "anom2regime",
ref = ref_maps,
lat = lats,
method = method
)
if (poslat_ano < poslon_ano) {
dim_order <- c(nlat, nlon)
} else {
dim_order <- c(nlon, nlat)
}
anom_array <-
array(var_ano, dim = c(prod(dim(var_ano)[-c(poslat_ano, poslon_ano)]),
dim_order))
rm(var_ano)
index <- as.vector(assign$output1)
recon <- Composite(var = aperm(anom_array, c(3, 2, 1)), occ = index)
freqs <- rep(NA, nclust)
for (n in 1 : nclust) {
freqs[n] <- (length(which(index == n)) / length(index)) * 100
}
output <-
list(
composite = recon$composite,
pvalue = recon$pvalue,
cluster = assign$output1,
frequency = freqs
)
return(output)
}
|
/* randist/geometric.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
*
* 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.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* Geometric distribution (bernoulli trial with probability p)
prob(k) = p (1 - p)^(k-1) for n = 1, 2, 3, ...
It gives the distribution of "waiting times" for an event that
occurs with probability p. */
unsigned int
gsl_ran_geometric (const gsl_rng * r, const double p)
{
double u = gsl_rng_uniform_pos (r);
unsigned int k;
if (p == 1)
{
k = 1;
}
else
{
k = log (u) / log (1 - p) + 1;
}
return k;
}
double
gsl_ran_geometric_pdf (const unsigned int k, const double p)
{
if (k == 0)
{
return 0 ;
}
else if (k == 1)
{
return p ;
}
else
{
double P = p * pow (1 - p, k - 1.0);
return P;
}
}
|
/-
Copyright (c) 2021 Apurva Nakade. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Apurva Nakade
-/
import algebra.algebra.basic
import ring_theory.localization
import set_theory.surreal.basic
/-!
# Dyadic numbers
Dyadic numbers are obtained by localizing ℤ away from 2. They are the initial object in the category
of rings with no 2-torsion.
## Dyadic surreal numbers
We construct dyadic surreal numbers using the canonical map from ℤ[2 ^ {-1}] to surreals.
As we currently do not have a ring structure on `surreal` we construct this map explicitly. Once we
have the ring structure, this map can be constructed directly by sending `2 ^ {-1}` to `half`.
## Embeddings
The above construction gives us an abelian group embedding of ℤ into `surreal`. The goal is to
extend this to an embedding of dyadic rationals into `surreal` and use Cauchy sequences of dyadic
rational numbers to construct an ordered field embedding of ℝ into `surreal`.
-/
universes u
local infix ` ≈ ` := pgame.equiv
namespace pgame
/-- For a natural number `n`, the pre-game `pow_half (n + 1)` is recursively defined as
`{ 0 | pow_half n }`. These are the explicit expressions of powers of `half`. By definition, we have
`pow_half 0 = 0` and `pow_half 1 = half` and we prove later on that
`pow_half (n + 1) + pow_half (n + 1) ≈ pow_half n`.-/
def pow_half : ℕ → pgame
| 0 := mk punit pempty 0 pempty.elim
| (n + 1) := mk punit punit 0 (λ _, pow_half n)
@[simp] lemma pow_half_left_moves {n} : (pow_half n).left_moves = punit :=
by cases n; refl
@[simp] lemma pow_half_right_moves {n} : (pow_half (n + 1)).right_moves = punit :=
by cases n; refl
@[simp] lemma pow_half_move_left {n i} : (pow_half n).move_left i = 0 :=
by cases n; cases i; refl
@[simp] lemma pow_half_move_right {n i} : (pow_half (n + 1)).move_right i = pow_half n :=
by cases n; cases i; refl
lemma pow_half_move_left' (n) :
(pow_half n).move_left (equiv.cast (pow_half_left_moves.symm) punit.star) = 0 :=
by simp only [eq_self_iff_true, pow_half_move_left]
lemma pow_half_move_right' (n) :
(pow_half (n + 1)).move_right (equiv.cast (pow_half_right_moves.symm) punit.star) = pow_half n :=
by simp only [pow_half_move_right, eq_self_iff_true]
/-- For all natural numbers `n`, the pre-games `pow_half n` are numeric. -/
theorem numeric_pow_half {n} : (pow_half n).numeric :=
begin
induction n with n hn,
{ exact numeric_one },
{ split,
{ rintro ⟨ ⟩ ⟨ ⟩,
dsimp only [pi.zero_apply],
rw ← pow_half_move_left' n,
apply hn.move_left_lt },
{ exact ⟨λ _, numeric_zero, λ _, hn⟩ } }
end
theorem pow_half_succ_lt_pow_half {n : ℕ} : pow_half (n + 1) < pow_half n :=
(@numeric_pow_half (n + 1)).lt_move_right punit.star
theorem pow_half_succ_le_pow_half {n : ℕ} : pow_half (n + 1) ≤ pow_half n :=
le_of_lt numeric_pow_half numeric_pow_half pow_half_succ_lt_pow_half
theorem zero_lt_pow_half {n : ℕ} : 0 < pow_half n :=
by cases n; rw lt_def_le; use ⟨punit.star, pgame.le_refl 0⟩
theorem zero_le_pow_half {n : ℕ} : 0 ≤ pow_half n :=
le_of_lt numeric_zero numeric_pow_half zero_lt_pow_half
theorem add_pow_half_succ_self_eq_pow_half {n} : pow_half (n + 1) + pow_half (n + 1) ≈ pow_half n :=
begin
induction n with n hn,
{ exact half_add_half_equiv_one },
{ split; rw le_def_lt; split,
{ rintro (⟨⟨ ⟩⟩ | ⟨⟨ ⟩⟩),
{ calc 0 + pow_half (n.succ + 1) ≈ pow_half (n.succ + 1) : zero_add_equiv _
... < pow_half n.succ : pow_half_succ_lt_pow_half },
{ calc pow_half (n.succ + 1) + 0 ≈ pow_half (n.succ + 1) : add_zero_equiv _
... < pow_half n.succ : pow_half_succ_lt_pow_half } },
{ rintro ⟨ ⟩,
rw lt_def_le,
right,
use sum.inl punit.star,
calc pow_half (n.succ) + pow_half (n.succ + 1)
≤ pow_half (n.succ) + pow_half (n.succ) : add_le_add_left pow_half_succ_le_pow_half
... ≈ pow_half n : hn },
{ rintro ⟨ ⟩,
calc 0 ≈ 0 + 0 : (add_zero_equiv _).symm
... ≤ pow_half (n.succ + 1) + 0 : add_le_add_right zero_le_pow_half
... < pow_half (n.succ + 1) + pow_half (n.succ + 1) : add_lt_add_left zero_lt_pow_half },
{ rintro (⟨⟨ ⟩⟩ | ⟨⟨ ⟩⟩),
{ calc pow_half n.succ
≈ pow_half n.succ + 0 : (add_zero_equiv _).symm
... < pow_half (n.succ) + pow_half (n.succ + 1) : add_lt_add_left zero_lt_pow_half },
{ calc pow_half n.succ
≈ 0 + pow_half n.succ : (zero_add_equiv _).symm
... < pow_half (n.succ + 1) + pow_half (n.succ) : add_lt_add_right zero_lt_pow_half }}}
end
end pgame
namespace surreal
open pgame
/-- The surreal number `half`. -/
def half : surreal := ⟦⟨pgame.half, pgame.numeric_half⟩⟧
/-- Powers of the surreal number `half`. -/
def pow_half (n : ℕ) : surreal := ⟦⟨pgame.pow_half n, pgame.numeric_pow_half⟩⟧
@[simp] lemma pow_half_zero : pow_half 0 = 1 := rfl
@[simp] lemma pow_half_one : pow_half 1 = half := rfl
@[simp] theorem add_half_self_eq_one : half + half = 1 :=
quotient.sound pgame.half_add_half_equiv_one
lemma double_pow_half_succ_eq_pow_half (n : ℕ) : 2 • pow_half n.succ = pow_half n :=
begin
rw two_nsmul,
apply quotient.sound,
exact pgame.add_pow_half_succ_self_eq_pow_half,
end
lemma nsmul_pow_two_pow_half (n : ℕ) : 2 ^ n • pow_half n = 1 :=
begin
induction n with n hn,
{ simp only [nsmul_one, pow_half_zero, nat.cast_one, pow_zero] },
{ rw [← hn, ← double_pow_half_succ_eq_pow_half n, smul_smul (2^n) 2 (pow_half n.succ),
mul_comm, pow_succ] }
end
lemma nsmul_pow_two_pow_half' (n k : ℕ) : 2 ^ n • pow_half (n + k) = pow_half k :=
begin
induction k with k hk,
{ simp only [add_zero, surreal.nsmul_pow_two_pow_half, nat.nat_zero_eq_zero, eq_self_iff_true,
surreal.pow_half_zero] },
{ rw [← double_pow_half_succ_eq_pow_half (n + k), ← double_pow_half_succ_eq_pow_half k,
smul_algebra_smul_comm] at hk,
rwa ← (zsmul_eq_zsmul_iff' two_ne_zero) }
end
lemma zsmul_pow_two_pow_half (m : ℤ) (n k : ℕ) :
(m * 2 ^ n) • pow_half (n + k) = m • pow_half k :=
begin
rw mul_zsmul,
congr,
norm_cast,
exact nsmul_pow_two_pow_half' n k,
end
lemma dyadic_aux {m₁ m₂ : ℤ} {y₁ y₂ : ℕ} (h₂ : m₁ * (2 ^ y₁) = m₂ * (2 ^ y₂)) :
m₁ • pow_half y₂ = m₂ • pow_half y₁ :=
begin
revert m₁ m₂,
wlog h : y₁ ≤ y₂,
intros m₁ m₂ h₂,
obtain ⟨c, rfl⟩ := le_iff_exists_add.mp h,
rw [add_comm, pow_add, ← mul_assoc, mul_eq_mul_right_iff] at h₂,
cases h₂,
{ rw [h₂, add_comm, zsmul_pow_two_pow_half m₂ c y₁] },
{ have := nat.one_le_pow y₁ 2 nat.succ_pos',
linarith },
end
/-- The additive monoid morphism `dyadic_map` sends ⟦⟨m, 2^n⟩⟧ to m • half ^ n. -/
def dyadic_map : localization.away (2 : ℤ) →+ surreal :=
{ to_fun :=
λ x, localization.lift_on x (λ x y, x • pow_half (submonoid.log y)) $
begin
intros m₁ m₂ n₁ n₂ h₁,
obtain ⟨⟨n₃, y₃, hn₃⟩, h₂⟩ := localization.r_iff_exists.mp h₁,
simp only [subtype.coe_mk, mul_eq_mul_right_iff] at h₂,
cases h₂,
{ simp only,
obtain ⟨a₁, ha₁⟩ := n₁.prop,
obtain ⟨a₂, ha₂⟩ := n₂.prop,
have hn₁ : n₁ = submonoid.pow 2 a₁ := subtype.ext ha₁.symm,
have hn₂ : n₂ = submonoid.pow 2 a₂ := subtype.ext ha₂.symm,
have h₂ : 1 < (2 : ℤ).nat_abs, from one_lt_two,
rw [hn₁, hn₂, submonoid.log_pow_int_eq_self h₂, submonoid.log_pow_int_eq_self h₂],
apply dyadic_aux,
rwa [ha₁, ha₂] },
{ have := nat.one_le_pow y₃ 2 nat.succ_pos',
linarith }
end,
map_zero' := localization.lift_on_zero _ _,
map_add' := λ x y, localization.induction_on₂ x y $
begin
rintro ⟨a, ⟨b, ⟨b', rfl⟩⟩⟩ ⟨c, ⟨d, ⟨d', rfl⟩⟩⟩,
have h₂ : 1 < (2 : ℤ).nat_abs, from one_lt_two,
have hpow₂ := submonoid.log_pow_int_eq_self h₂,
simp_rw submonoid.pow_apply at hpow₂,
simp_rw [localization.add_mk, localization.lift_on_mk, subtype.coe_mk,
submonoid.log_mul (int.pow_right_injective h₂), hpow₂],
calc (2 ^ b' * c + 2 ^ d' * a) • pow_half (b' + d')
= (c * 2 ^ b') • pow_half (b' + d') + (a * 2 ^ d') • pow_half (d' + b')
: by simp only [add_smul, mul_comm,add_comm]
... = c • pow_half d' + a • pow_half b' : by simp only [zsmul_pow_two_pow_half]
... = a • pow_half b' + c • pow_half d' : add_comm _ _,
end }
@[simp] lemma dyadic_map_apply (m : ℤ) (p : submonoid.powers (2 : ℤ)) :
dyadic_map (is_localization.mk' (localization (submonoid.powers 2)) m p) =
m • pow_half (submonoid.log p) :=
begin
rw ← localization.mk_eq_mk',
refl,
end
@[simp] lemma dyadic_map_apply_pow (m : ℤ) (n : ℕ) :
dyadic_map (is_localization.mk' (localization (submonoid.powers 2)) m (submonoid.pow 2 n)) =
m • pow_half n :=
by rw [dyadic_map_apply, @submonoid.log_pow_int_eq_self 2 one_lt_two]
/-- We define dyadic surreals as the range of the map `dyadic_map`. -/
def dyadic : set surreal := set.range dyadic_map
-- We conclude with some ideas for further work on surreals; these would make fun projects.
-- TODO show that the map from dyadic rationals to surreals is injective
-- TODO map the reals into the surreals, using dyadic Dedekind cuts
-- TODO show this is a group homomorphism, and injective
-- TODO show the maps from the dyadic rationals and from the reals
-- into the surreals are multiplicative
end surreal
|
module Data.Morphisms
public export
record Morphism a b where
constructor Mor
applyMor : a -> b
infixr 1 ~>
public export
(~>) : Type -> Type -> Type
(~>) = Morphism
public export
record Endomorphism a where
constructor Endo
applyEndo : a -> a
public export
record Kleislimorphism (f : Type -> Type) a b where
constructor Kleisli
applyKleisli : a -> f b
export
Functor (Morphism r) where
map f (Mor a) = Mor $ f . a
export
Applicative (Morphism r) where
pure a = Mor $ const a
(Mor f) <*> (Mor a) = Mor $ \r => f r $ a r
export
Monad (Morphism r) where
(Mor h) >>= f = Mor $ \r => applyMor (f $ h r) r
export
Semigroup a => Semigroup (Morphism r a) where
f <+> g = Mor $ \r => (applyMor f) r <+> (applyMor g) r
export
Monoid a => Monoid (Morphism r a) where
neutral = Mor \r => neutral
export
Semigroup (Endomorphism a) where
(Endo f) <+> (Endo g) = Endo $ g . f
export
Monoid (Endomorphism a) where
neutral = Endo id
export
Functor f => Functor (Kleislimorphism f a) where
map f (Kleisli g) = Kleisli (map f . g)
export
Applicative f => Applicative (Kleislimorphism f a) where
pure a = Kleisli $ const $ pure a
(Kleisli f) <*> (Kleisli a) = Kleisli $ \r => f r <*> a r
export
Monad f => Monad (Kleislimorphism f a) where
(Kleisli f) >>= g = Kleisli $ \r => do
k1 <- f r
applyKleisli (g k1) r
-- Applicative is a bit too strong, but there is no suitable superclass
export
(Semigroup a, Applicative f) => Semigroup (Kleislimorphism f r a) where
f <+> g = Kleisli \r => (<+>) <$> (applyKleisli f) r <*> (applyKleisli g) r
export
(Monoid a, Applicative f) => Monoid (Kleislimorphism f r a) where
neutral = Kleisli \r => pure neutral
export
Cast (Endomorphism a) (Morphism a a) where
cast (Endo f) = Mor f
export
Cast (Morphism a a) (Endomorphism a) where
cast (Mor f) = Endo f
export
Cast (Morphism a (f b)) (Kleislimorphism f a b) where
cast (Mor f) = Kleisli f
export
Cast (Kleislimorphism f a b) (Morphism a (f b)) where
cast (Kleisli f) = Mor f
|
SUBROUTINE BMG2_SymStd_COPY_cg_rV_G_L(
& Q_SER, NGx, NGy,
& Q, NLx, NLy, iGs, jGs,
& ProcCoord, NProcI, NProcJ,
& Nproc, MyProc
& )
C ==========================================================================
C --------------------
C DESCRIPTION:
C --------------------
C
C Copy the solution of the coarse-grid solve, back into the
C MPI-based BoxMG solution vector.
C
C =======================================================================
C $license_flag$
C =======================================================================
C --------------------
C INPUT:
C --------------------
C
C
C =======================================================================
C --------------------
C OUTPUT:
C --------------------
C
C
C
C =======================================================================
C --------------------
C LOCAL:
C --------------------
C
C
C ==========================================================================
IMPLICIT NONE
C ----------------------------
C Argument Declarations
C
!
! Global/Local indexing
!
INTEGER NLx, NLy,
& NGx, NGy,
& iGs, jGs
!
! Global Solution: SER
!
REAL*8 Q_SER(NGx,NGy)
!
! Local Solution: MPI
!
REAL*8 Q(NLx,NLy)
!
! Processor grid
!
INTEGER NProcI, NProcJ, NProcK, NProc, MyProc
INTEGER ProcCoord(2, NProc)
C ----------------------------
C Local Declarations
C
INTEGER iG, iL, jG, jL, kG, kL,
& MyProcI, MyProcJ, MyProcK
INTEGER iBEG, iEND, jBEG, jEND, kBEG, kEND
C =========================================================================
MyProcI = ProcCoord(1,MyProc)
MyProcJ = ProcCoord(2,MyProc)
!
! Setup loop boundaries in x
!
IF ( MyProcI.EQ.1 ) THEN
iBEG = 2
ELSE
iBEG = 1
END IF
IF ( MyProcI.EQ.NProcI ) THEN
iEND = NLx-1
ELSE
iEND = NLx
END IF
!
! Setup loop boundaries in y
!
IF ( MyProcJ.EQ.1 ) THEN
jBEG = 2
ELSE
jBEG = 1
END IF
IF ( MyProcJ.EQ.NProcJ ) THEN
jEND = NLy-1
ELSE
jEND = NLy
ENDIF
DO jL=jBEG, jEND
jG = jGs + jL - 1
DO iL=iBEG, iEND
iG = iGs + iL - 1
Q(iL,jL) = Q_SER(iG,jG)
ENDDO
ENDDO
C =========================================================================
RETURN
END
|
State Before: R : Type u_1
inst✝¹⁴ : CommRing R
M₁ : Type u_2
M₂ : Type u_3
M : Type u_4
M' : Type u_5
inst✝¹³ : AddCommMonoid M₁
inst✝¹² : AddCommMonoid M₂
inst✝¹¹ : AddCommMonoid M
inst✝¹⁰ : AddCommMonoid M'
inst✝⁹ : Module R M₁
inst✝⁸ : Module R M₂
inst✝⁷ : Module R M
inst✝⁶ : Module R M'
f : M₁ →ₗ[R] M₂ →ₗ[R] M
N₁ : Type ?u.87557
N₂ : Type ?u.87560
N : Type ?u.87563
inst✝⁵ : AddCommMonoid N₁
inst✝⁴ : AddCommMonoid N₂
inst✝³ : AddCommMonoid N
inst✝² : Module R N₁
inst✝¹ : Module R N₂
inst✝ : Module R N
g : N₁ →ₗ[R] N₂ →ₗ[R] N
h : IsTensorProduct f
f' : M₁ →ₗ[R] M₂ →ₗ[R] M'
x₁ : M₁
x₂ : M₂
⊢ ↑(lift h f') (↑(↑f x₁) x₂) = ↑(↑f' x₁) x₂ State After: R : Type u_1
inst✝¹⁴ : CommRing R
M₁ : Type u_2
M₂ : Type u_3
M : Type u_4
M' : Type u_5
inst✝¹³ : AddCommMonoid M₁
inst✝¹² : AddCommMonoid M₂
inst✝¹¹ : AddCommMonoid M
inst✝¹⁰ : AddCommMonoid M'
inst✝⁹ : Module R M₁
inst✝⁸ : Module R M₂
inst✝⁷ : Module R M
inst✝⁶ : Module R M'
f : M₁ →ₗ[R] M₂ →ₗ[R] M
N₁ : Type ?u.87557
N₂ : Type ?u.87560
N : Type ?u.87563
inst✝⁵ : AddCommMonoid N₁
inst✝⁴ : AddCommMonoid N₂
inst✝³ : AddCommMonoid N
inst✝² : Module R N₁
inst✝¹ : Module R N₂
inst✝ : Module R N
g : N₁ →ₗ[R] N₂ →ₗ[R] N
h : IsTensorProduct f
f' : M₁ →ₗ[R] M₂ →ₗ[R] M'
x₁ : M₁
x₂ : M₂
⊢ ↑(LinearMap.comp (TensorProduct.lift f') ↑(LinearEquiv.symm (equiv h))) (↑(↑f x₁) x₂) = ↑(↑f' x₁) x₂ Tactic: delta IsTensorProduct.lift State Before: R : Type u_1
inst✝¹⁴ : CommRing R
M₁ : Type u_2
M₂ : Type u_3
M : Type u_4
M' : Type u_5
inst✝¹³ : AddCommMonoid M₁
inst✝¹² : AddCommMonoid M₂
inst✝¹¹ : AddCommMonoid M
inst✝¹⁰ : AddCommMonoid M'
inst✝⁹ : Module R M₁
inst✝⁸ : Module R M₂
inst✝⁷ : Module R M
inst✝⁶ : Module R M'
f : M₁ →ₗ[R] M₂ →ₗ[R] M
N₁ : Type ?u.87557
N₂ : Type ?u.87560
N : Type ?u.87563
inst✝⁵ : AddCommMonoid N₁
inst✝⁴ : AddCommMonoid N₂
inst✝³ : AddCommMonoid N
inst✝² : Module R N₁
inst✝¹ : Module R N₂
inst✝ : Module R N
g : N₁ →ₗ[R] N₂ →ₗ[R] N
h : IsTensorProduct f
f' : M₁ →ₗ[R] M₂ →ₗ[R] M'
x₁ : M₁
x₂ : M₂
⊢ ↑(LinearMap.comp (TensorProduct.lift f') ↑(LinearEquiv.symm (equiv h))) (↑(↑f x₁) x₂) = ↑(↑f' x₁) x₂ State After: no goals Tactic: simp |
[<html>] "^/" [<head>] "^/" [<META> NAME "Description" CONTENT {REBOL: a Web 3.0 language and system based on new lightweight computing methods. Site includes products, downloads, documentation, and support.}] "^/" [<META> NAME "Keywords" CONTENT {REBOL, Web 3.0, Web 2.0, programming, Internet, software, domain specific language, distributed computing, collaboration, operating systems, development, rebel}] "^/^/" [<meta> http-equiv "content-type" content "text/html;charset=iso-8859-1"] "^/" [<title>] "REBOL Technologies" </title> "^/" [<style> type "text/css"] {
body, p, td, ol, ul {font-family: arial, sans-serif, helvetica; font-size: 10pt;}
h1 {font-size: 14pt;}
h2 {font-size: 12pt; color: #2030a0; width: 100%; border-bottom: 1px solid #c09060;}
h3 {font-size: 11pt; color: #2030a0;}
h4 {font-size: 10pt;}
tt {font-family: "courier new", monospace, courier; font-size: 9pt;}
pre {
^-font: bold 10pt "courier new", monospace, console; overflow: auto;
^-background-color: #f0f0f0; padding: 16px; border: solid #a0a0a0 1px;
}
li {margin-bottom: 10px}
.title {font-size: 16pt; font-weight: bold;}
.output {color: #803020}
.hdline {font-size: 10pt; color: gray; font-family: verdana, arial, sans-serif; font-weight: bold;}
input {font-size: 9pt;}
.note {font-size: 8pt; color: white;}
.tail {font-size: 8pt; color: gray;}
.navbar {font-family: verdana, arial, sans-serif; font-size: 8pt; font-weight: bold; color: white; margin-left: 10px;}
.nav {font-family: arial, sans-serif, helvetica; font-size: 8pt; font-weight: bold; color: #ffc070; text-decoration: none;}
.ind {margin-left: 14px; margin-top: 4px;}
.fset {background-color: #fff8e0;}
legend {Color: #006000; Font-Weight: bold;}
} </style> "^/" [<link> rel "stylesheet" href "/main.css" type "text/css" charset "utf-8"] "^/" </head> "^/^/" [<body> background "/graphics/backlined.gif" bgcolor "#80887a" LINK "maroon" ALINK "#9F9466" VLINK "#506027" leftmargin "8" topmargin "8" rightmargin "8" marginwidth "8"] "^/" [<p> align "center"] "^/" [<table> border "0" cellpadding "0" cellspacing "0" width "700" bgcolor "white"] "^/^/" [<tr>] "^/" [<td> width "176" rowspan "2"] [<a> href "http://www.rebol.com"] [<img> src "/graphics/reb-logo.gif" width "176" height "44" align "bottom" border "0" alt "REBOL logo"] </a> </td> "^/" [<td> height "32"] [<p> align "center" class "hdline"] "Web 3.0 starts here. Smarter, faster, better." </p> </td> "^/" </tr> "^/^/" [<tr>] "^/" [<td> height "18" width "100%" nowrap "nowrap"] [<img> src "/graphics/round.gif" width "16" height "18" align "bottom" border "0"] [<img> src "/graphics/bar18.gif" width "520" height "18" align "bottom" border "0"] </td> "^/" </tr> "^/^/" <!-- Navigation bar --> "^/" [<tr>] "^/" [<td> width "176" bgcolor "#607040" valign "top"] "^/" [<table> border "0" cellpadding "0" cellspacing "0" width "100%"] "^/" [<tr> bgcolor "black"] "^/" [<td> width "16" height "18" nowrap "nowrap"] [<img> src "/graphics/round.gif" width "16" height "18" align "bottom" border "0"] </td> "^/" [<td> width "160" height "18" nowrap "nowrap"] [<img> src "/graphics/bar18.gif" width "160" height "18" align "bottom" border "0"] </td> "^/" </tr> "^/^/" [<tr>] "^/" [<td> width "16"] " " </td> "^/" [<td>] [<br>] "^/" [<span> class "navbar"] "LANGUAGE" </span> [<br>] "^/" [<div> class "ind"] "^/" [<a> href "/index-lang.html"] [<span> class "nav"] "Overview" </span> </a> [<br>] "^/" [<a> href "/download.html"] [<span> class "nav"] "Downloads" </span> </a> [<br>] "^/" [<a> href "/docs.html"] [<span> class "nav"] "Documents" </span> </a> [<br>] "^/" [<a> href "http://www.rebol.net"] [<span> class "nav"] "Developer" </span> </a> [<br>] "^/" [<a> href "http://www.rebol.org"] [<span> class "nav"] "Library" </span> </a> [<br>] "^/" [<a> href "/license.html"] [<span> class "nav"] "License" </span> </a> [<br>] "^/" </div> "^/" [<br>] "^/" [<span> class "navbar"] "COMPANY" </span> [<br>] "^/" [<div> class "ind"] "^/" [<a> href "/mission.html"] [<span> class "nav"] "About" </span> </a> [<br>] "^/" [<a> href "/support.html"] [<span> class "nav"] "Support" </span> </a> [<br>] "^/" [<a> href "/feedback.html"] [<span> class "nav"] "Feedback" </span> </a> [<br>] "^/" [<a> href "/contacts.html"] [<span> class "nav"] "Contact" </span> </a> [<br>] "^/" </div> "^/" [<br>] "^/" </td> </tr> "^/^/" [<tr>] "^/" [<td> width "16"] " " </td> "^/" [<td>] [<br>] "^/" [<FORM> method "GET" action "http://www.google.com/custom"] "^/" [<p> class "note"] "^/" [<INPUT> TYPE "text" name "q" size "18" maxlength "255" value "Search"] "^/" [<br>] [<input> type "radio" name "sitesearch" value "rebol.com" checked "checked"] " REBOL.COM^/" [<br>] [<input> type "radio" name "sitesearch" value "rebol.net"] " REBOL.NET ^/" [<br>] " " [<INPUT> type "submit" name "sa" VALUE "Search Site"] "^/" [<INPUT> type "hidden" name "cof" VALUE {S:http://www.rebol.net;AH:left;LH:28;L:http://www.rebol.net/graphics/reb-bare.jpg;LW:680;AWFID:a7e2df1bd458cfc6;}] "^/" [<input> type "hidden" name "domains" value "REBOL.com;REBOL.net"] "^/" </p> "^/" </FORM> "^/" [<br>] "^/" </td> "^/" </tr> "^/" </table> "^/" </td> "^/^/" [<td> valign "top"] "^/" [<table> border "0" CELLPADDING "0" cellspacing "0" width "100%"] "^/" [<tr>] [<td> valign "top"] "^/" [<table> border "0" cellpadding "0" cellspacing "0"] "^/^/" <!--Banner--> "^/" [<tr>] "^/" [<td> height "120" valign "top"] "^/" [<table> border "0" cellpadding "0" cellspacing "0" width "100%"] "^/" [<tr>] "^/" [<td> width "300"] [<img> src "/graphics/kits.jpg" width "300" height "120" align "bottom" border "0" alt "Keep IT Simple"] </td> "^/" [<td> width "8"] " " </td> "^/" [<td> width "150"] "^/" [<p> align "center"] "^/" [<a> href "sdk.html"] [<img> src "http://www.rebol.com/graphics/pwr-sdk100.gif" align "middle" border "0" alt "REBOL SDK"] </a> "^/" </p> "^/" </td> "^/" </tr> </table> "^/" </td> "^/" </tr> "^/^/" <!--Bar--> "^/" [<tr>] "^/" [<td> bgcolor "black"] [<img> src "graphics/black.gif" width "520" height "8" align "bottom" border "0"] </td> "^/" </tr> "^/^/" <!--Content Table--> "^/" [<tr>] [<td> valign "top"] [<table> border "0" cellpadding "3" width "520"] "^/^/" <!--Main Content--> "^/" [<tr>] "^/" [<td> width "340" valign "top"] "^/^/" [<b>] [<font> size "3"] "REBOL rebels against software complexity." </font> </b> "^/" [<br>] [<b>] [<font> color "gray"] "Do it in 1MB, not 200MB." </font> </b> "^/" [<p>] "^/^/" [<hr>] "^/^/" [<p> align "center"] "^/The new release is here...^/" [<br>] [<a> href "http://www.rebol.com/view-platforms.html"] [<image> src "/graphics/download276.png" alt "Download REBOL 2.7.6" border "0"] </a> "^/" [<br>] "Vista, XP, OSX, Linux, BSD, and more." </p> "^/^/" [<hr>] "^/^/" [<p>] "^/" [<table>] "^/" [<tr>] "^/" [<td> width "66" align "center" valign "top"] "^/" [<a> href "rebol3/"] [<img> src "/graphics/r3-prelogo.png" border "0"] </a> "^/" </td> "^/" [<td>] "^/" [<p>] "^/" [<b>] [<a> href "rebol3/"] "REBOL 3 (3.0) Project Home Page" </a> </b> "^/" </p> [<p>] [<b>] "Redesigned, optimized, and enhanced." </b> "^/" </p> [<p>] {
The main goal of REBOL 3.0 is to build a lightweight, extensible platform that operates over a variety of operating systems and devices.
} </p> "^/" </td> "^/" </tr> "^/" </table> "^/" [<p>] "^/^/" [<hr>] "^/^/" [<table> border "0" cellspacing "3"] [<tr>] "^/" [<td>] [<a> href "http://www.rebol.com/article/0324.html"] [<img> src "/graphics/rebol-programmeur-book.jpg" border "0" alt "REBOL book"] </a> </td> "^/" [<td> width "80%"] [<a> href "http://www.rebol.com/article/0324.html"] [<b>] [<i>] "REBOL Guide du programmeur" </i> </b> </a> "^/" [<br>] "By Olivier Auverlot^/" [<br>] "REBOL book in French^/" [<p>] [<A> HREF "http://www.rebol.com/books.html"] [<font> color "gray"] [<b>] "Other REBOL books..." </b> </font> </a> "^/" </td> </tr> </table> "^/" [<p>] "^/" [<A> HREF "more.html"] [<font> color "gray"] [<b>] [<i>] "More stuff..." </i> </b> </font> </a> "^/^/" </td> "^/^/" <!--Divider--> "^/" [<td> width "2" valign "top"] </td> "^/" <!--img src="graphics/gray.gif" width="2" height="420" align="bottom" border="0"--> "^/^/" <!--Info Column--> "^/" [<td> width "160" valign "top"] "^/^/" [<DIV> CLASS "sidebar"] [<TABLE> CELLSPACING "0" CELLPADDING "0"] [<TR>] [<TD> ID "leftcorner"] </TD> [<TD> ID "header" WIDTH "150"] "New Stuff..." </TD> [<TD> ID "rightcorner"] </TD> </TR> [<TR>] [<TD> COLSPAN "3" ID "content" nowrap "nowrap"] "^/" [<tt>] "27-Sep-2008" </tt> "^/^/" [<p>] [<A> HREF "http://www.rebol.net/upnews/0026.html"] [<b>] "V2.7.6 Released" </b> </a> "^/" [<br>] "Download it now!^/" [<br>] "Includes SDK tools.^/^/" [<p>] [<A> HREF "http://www.rebol.net/r3blogs/0117.html"] [<b>] "V3.0 Unicode Alpha" </b> </a> "^/" [<br>] "First words of Chinese,^/" [<br>] "other languages too.^/^/" </TD> </TR> </TABLE> </DIV> "^/^/" [<DIV> CLASS "sidebar"] [<TABLE> CELLSPACING "0" CELLPADDING "0"] [<TR>] [<TD> ID "leftcorner"] </TD> [<TD> ID "header" WIDTH "150"] "Learn Stuff..." </TD> [<TD> ID "rightcorner"] </TD> </TR> [<TR>] [<TD> COLSPAN "3" ID "content" nowrap "nowrap"] "^/" [<A> HREF "what-rebol.html"] [<b>] "What is REBOL?" </b> </a> "^/" [<br>] "A quick description." </b> "^/^/" [<p>] [<A> HREF "tutorials.html"] [<b>] "Learn REBOL" </b> </a> "^/" [<br>] "Quick, light, and easy." </p> "^/^/" </TD> </TR> </TABLE> </DIV> "^/^/" [<DIV> CLASS "sidebar"] [<TABLE> CELLSPACING "0" CELLPADDING "0"] [<TR>] [<TD> ID "leftcorner"] </TD> [<TD> ID "header" WIDTH "150"] "Community..." </TD> [<TD> ID "rightcorner"] </TD> </TR> [<TR>] [<TD> COLSPAN "3" ID "content" nowrap "nowrap"] "^/" [<a> HREF "http://www.rebol.com/cgi-bin/blog.r"] [<b>] "Vive la REBOLution" </b> </a> "^/" [<br>] "Carl's main blog" </p> "^/^/" [<p>] [<a> HREF "http://rebolweek.blogspot.com/"] [<b>] "The REBOL Week" </b> </a> "^/" [<br>] "News and events." </p> "^/^/" [<p>] [<a> HREF "http://www.rebol.net"] [<b>] "Developer Central" </b> </a> "^/" [<br>] "For techies only." </p> "^/^/" [<p>] [<a> HREF "http://www.rebol.net/cgi-bin/r3blog.r"] [<b>] "REBOL 3.0 Design" </b> </a> "^/" [<br>] "Gurus building the^/" [<br>] "future." </p> "^/^/" </TD> </TR> </TABLE> </DIV> "^/^/" [<p>] "^/" [<a> href {http://www4.clustrmaps.com/counter/maps.php?url=http://www.rebol.com} id "clustrMapsLink"] [<img> src {http://www4.clustrmaps.com/counter/index2.php?url=http://www.rebol.com} style "border:0px;" alt "Locations of visitors to this page" title "Locations of visitors to this page" id "clustrMapsImg" onError {this.onError=null; this.src='http://www2.clustrmaps.com/images/clustrmaps-back-soon.jpg'; document.getElementById('clustrMapsLink').href='http://www2.clustrmaps.com'}] "^/" </a> "^/^/" </td> "^/" </tr> "^/" </table> "^/" <!--End Content--> "^/^/" </td> "^/" </tr> "^/" </table> "^/" </td> </tr> "^/" </table> "^/^/" </td> </tr> "^/^/" [<tr>] "^/" [<td> width "176" height "18" bgcolor "black" align "center" valign "top"] "^/" [<span> class "tail"] "Updated 27-Sep-2008 [" [<A> HREF "/cgi-bin/wip.r?r=edit+%25web/index.html&"] "Edit" </A> "]" </span> "^/" </td> "^/" [<td> height "18" bgcolor "black" align "center" valign "top"] "^/" [<span> class "tail"] "Copyright 2008 REBOL Technologies" </span> "^/" </td> "^/" </tr> "^/^/" </table> "^/" </body> "^/" </html> "^/" |
19th century physicist , John Tyndall , discovered the Tyndall effect . Father Nicholas Joseph Callan , Professor of Natural Philosophy in Maynooth College , is best known for his invention of the induction coil , transformer and he discovered an early method of <unk> in the 19th century .
|
import LMT
variable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)]
example {a1 a2 a3 : A I E} :
((((a2).write i1 (v3)).write i2 (v3)).read i1) ≠ (v3) → False := by
arr
|
import Clustering
import Distances
import LinearAlgebra: dot
"""
noselection(algo, data)
Perform no clustering selection.
"""
noselection(algo::Function, data::AbstractMatrix{<:Real}) = Clustering.assignments(algo(data))
"""
Knee point detection
"""
function knee(x)
n = length(x)
pts = hcat(1:n, x)'
# calculate line vector
lvec = pts[:,end] - pts[:,1]
lvec ./= sqrt(sum(lvec.^2))
# find a vector parallel to the line vector
vecfst = pts .- pts[:,1]
vecfstpar = lvec * mapslices(v->dot(v, lvec), vecfst, dims=1)
# calculate a length of a projection to the line vector
ldist = vec(sqrt.(sum((vecfst - vecfstpar).^2, dims=1)))
# get maximal projection
return findmax(ldist)
end
function getmaxk(N::Int; kwargs...)
N <= 5 && return 2
# setup parameters
Kmax = 10 # default
for (p,v) in kwargs
if p == :maxk
Kmax = v
end
end
return min(floor(Int, N/2), Kmax)
end
"""
elbow(algo, data)
Perform automatic selection of the best clustering of `data` by `algo` using elbow method.
Clustering algorithm `algo` must be a function with one argument which determines number of clusters.
"""
function elbow(algo::Function, data::AbstractMatrix{<:Real}; kwargs...)
N = size(data,2)
Kmax = getmaxk(N; kwargs...)
S = [let C = algo(data, k)
# println("$k => ", C.centers)
# println("$k => ", C.costs)
C.totalcost => Clustering.assignments(C)
end
for k in 2:Kmax]
pushfirst!(S, sum(mapslices(p->sum(p.^2), data .- mean(data, dims=2), dims=1))=>fill(1,N))
# return a clustering corespondig to an elbow point
return S[knee(map(first, S)) |> last] |> last
end
"""
silhouette(algo, data)
Perform automatic selection of the best clustering of `data` by `algo` using silhouette method.
Clustering algorithm `algo` must be a function with one argument which determines number of clusters.
"""
function silhouette(algo::Function, data::AbstractMatrix{<:Real}; kwargs...)
N = size(data,2)
Kmax = getmaxk(N; kwargs...)
S = [let C = algo(data, k),
D = Distances.pairwise(Distances.Euclidean(), data)
mean(Clustering.silhouettes(C, D)) => Clustering.assignments(C)
end
for k in 2:Kmax]
# return a clustering corespondig to a maximum average silhouette
return S[findmax(map(first, S)) |> last] |> last
end
|
lemma bounded_linear_Re: "bounded_linear Re" |
import analysis.normed_space.conformal_linear_map
import complex_conformal_prep
/-
Copyright (c) 2021 Yourong Zang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yourong Zang
-/
/-!
# Complex Conformal Maps
We prove the sufficient and necessary conditions for a complex function to be conformal.
## Main results
* `is_complex_or_conj_complex_linear_iff_is_conformal_map`: the main theorem for linear maps.
* `conformal_at_iff_holomorphic_or_antiholomorphic_at`: the main theorem for complex functions.
## Warning
Antiholomorphic functions such as the complex conjugate are considered as conformal functions in
this file.
-/
noncomputable theory
open complex linear_isometry linear_isometry_equiv continuous_linear_map
finite_dimensional linear_map
section complex_normed_space
variables {E : Type*} [normed_group E] [normed_space ℝ E] [normed_space ℂ E]
[is_scalar_tower ℝ ℂ E] {z : ℂ} {g : ℂ →L[ℝ] E} {f : ℂ → E}
lemma is_conformal_map_of_eq_complex_linear (nonzero : g ≠ 0)
(H : ∃ (map : ℂ →L[ℂ] E), map.restrict_scalars ℝ = g) : is_conformal_map g :=
begin
rcases H with ⟨map, h⟩,
have minor₀ : ∀ x, g x = x • g 1,
{ intro x,
nth_rewrite 0 ← mul_one x,
rw [← smul_eq_mul, ← h, coe_restrict_scalars', map.map_smul], },
have minor₁ : ∥g 1∥ ≠ 0,
{ contrapose! nonzero with w,
ext1 x,
rw [continuous_linear_map.zero_apply, minor₀ x, norm_eq_zero.mp w, smul_zero], },
refine ⟨∥g 1∥, minor₁, _⟩,
let li' := ∥g 1∥⁻¹ • g,
have key : ∀ (x : ℂ), ∥li' x∥ = ∥x∥,
{ intros x,
simp only [li', continuous_linear_map.smul_apply, minor₀ x,
norm_smul, normed_field.norm_inv, norm_norm],
field_simp [minor₁], },
let li : ℂ →ₗᵢ[ℝ] E := ⟨li', key⟩,
have minor₂ : (li : ℂ → E) = li' := rfl,
refine ⟨li, _⟩,
ext1,
simp only [minor₂, li', pi.smul_apply, continuous_linear_map.smul_apply, smul_smul],
field_simp [minor₁],
end
lemma is_conformal_map_of_eq_linear_conj (nonzero : g ≠ 0)
(h : ∃ (map : ℂ →L[ℂ] E), map.restrict_scalars ℝ = g.comp conj_cle.to_continuous_linear_map) :
is_conformal_map g :=
begin
have nonzero' : g.comp conj_cle.to_continuous_linear_map ≠ 0,
{ contrapose! nonzero with w,
simp only [continuous_linear_map.ext_iff, continuous_linear_map.zero_apply,
continuous_linear_map.coe_comp', function.comp_app,
continuous_linear_equiv.coe_def_rev, continuous_linear_equiv.coe_apply,
conj_cle_apply] at w,
ext1,
rw [← conj_conj x, w, continuous_linear_map.zero_apply], },
rcases is_conformal_map_of_eq_complex_linear nonzero' h with ⟨c, hc, li, hg'⟩,
refine ⟨c, hc, li.comp conj_lie.to_linear_isometry, _⟩,
have key : (g : ℂ → E) = (c • li) ∘ conj_lie,
{ rw ← hg',
funext,
simp only [continuous_linear_map.coe_comp',function.comp_app,
continuous_linear_equiv.coe_def_rev, continuous_linear_equiv.coe_apply,
conj_lie_apply, conj_cle_apply, conj_conj], },
funext,
simp only [conj_cle_apply, pi.smul_apply,
linear_isometry.coe_comp, coe_to_linear_isometry],
rw [key, function.comp_app, pi.smul_apply],
end
/-- A real differentiable function of the complex plane into some complex normed space `E` is
conformal at a point `z` if it is holomorphic or antiholomorphic at that point -/
lemma conformal_at_of_holomorph_or_antiholomorph_at_aux
(hf : differentiable_at ℝ f z) (hf' : fderiv ℝ f z ≠ 0)
(h : differentiable_at ℂ f z ∨ differentiable_at ℂ (f ∘ conj) (conj z)) :
conformal_at f z :=
begin
rw [conformal_at_iff_is_conformal_map_fderiv],
rw [differentiable_at_iff_exists_linear_map hf,
antiholomorph_at_iff_exists_complex_linear_conj hf] at h,
cases h,
{ exact is_conformal_map_of_eq_complex_linear hf' h, },
{ exact is_conformal_map_of_eq_linear_conj hf' h, },
end
end complex_normed_space
section complex_conformal_linear_map
variables {f : ℂ → ℂ} {z : ℂ} {g : ℂ →L[ℝ] ℂ}
lemma is_complex_or_conj_complex_linear (h : is_conformal_map g) :
(∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g) ∨
(∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g.comp conj_cle.to_continuous_linear_map) :=
begin
rcases h with ⟨c, hc, li, hg⟩,
rcases linear_isometry_complex (li.to_linear_isometry_equiv rfl) with ⟨a, ha⟩,
cases ha,
{ refine or.intro_left _ ⟨c • rotation_clm a, _⟩,
ext1,
simp only [coe_restrict_scalars', continuous_linear_map.smul_apply, coe_rotation_clm, ← ha,
li.coe_to_linear_isometry_equiv, hg, pi.smul_apply], },
{ let map := c • (rotation_clm a),
refine or.intro_right _ ⟨map, _⟩,
ext1,
rw [continuous_linear_map.coe_comp', hg, ← li.coe_to_linear_isometry_equiv, ha],
simp only [coe_restrict_scalars', function.comp_app, pi.smul_apply,
linear_isometry_equiv.coe_trans, conj_lie_apply,
rotation_apply, map, continuous_linear_equiv.coe_def_rev,
continuous_linear_equiv.coe_apply, conj_cle_apply],
simp only [smul_coe, smul_eq_mul, function.comp_app, continuous_linear_map.smul_apply,
rotation_clm_apply, linear_map.coe_to_continuous_linear_map',
rotation_apply, conj.map_mul, conj_conj], },
end
/-- A real continuous linear map on the complex plane is conformal if and only if the map or its
conjugate is complex linear, and the map is nonvanishing. -/
lemma is_complex_or_conj_complex_linear_iff_is_conformal_map :
((∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g) ∨
(∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g.comp conj_cle.to_continuous_linear_map))
∧ g ≠ 0 ↔ is_conformal_map g :=
iff.intro
(λ h, h.1.rec_on
(is_conformal_map_of_eq_complex_linear h.2)
$ is_conformal_map_of_eq_linear_conj h.2)
(λ h, ⟨is_complex_or_conj_complex_linear h, h.ne_zero⟩)
end complex_conformal_linear_map
section complex_conformal_map
variables {f : ℂ → ℂ} {z : ℂ}
lemma conformal_at_iff_holomorphic_or_antiholomorph_at_aux (hf : differentiable_at ℝ f z) :
conformal_at f z ↔
(differentiable_at ℂ f z ∨ differentiable_at ℂ (f ∘ conj) (conj z)) ∧ fderiv ℝ f z ≠ 0 :=
by rw [conformal_at_iff_is_conformal_map_fderiv,
← is_complex_or_conj_complex_linear_iff_is_conformal_map,
differentiable_at_iff_exists_linear_map hf,
antiholomorph_at_iff_exists_complex_linear_conj hf]
/-- A complex function is conformal if and only if the function is holomorphic or antiholomorphic
with a nonvanishing differential. -/
lemma conformal_at_iff_holomorphic_or_antiholomorphic_at :
conformal_at f z ↔
(differentiable_at ℂ f z ∨ differentiable_at ℂ (f ∘ conj) (conj z)) ∧ fderiv ℝ f z ≠ 0 :=
iff.intro
(λ h, (conformal_at_iff_holomorphic_or_antiholomorph_at_aux h.differentiable_at).mp h)
(λ h, by
{ have : differentiable_at ℝ f z :=
by_contra (λ w, h.2 $ fderiv_zero_of_not_differentiable_at w),
exact (conformal_at_iff_holomorphic_or_antiholomorph_at_aux this).mpr h, } )
end complex_conformal_map |
#ifndef libceed_petsc_examples_setup_h
#define libceed_petsc_examples_setup_h
#include <ceed.h>
#include <petsc.h>
#include "structs.h"
PetscErrorCode CeedDataDestroy(CeedInt i, CeedData data);
PetscErrorCode SetupLibceedByDegree(DM dm, Ceed ceed, CeedInt degree,
CeedInt topo_dim, CeedInt q_extra,
PetscInt num_comp_x, PetscInt num_comp_u,
PetscInt g_size, PetscInt xl_size,
BPData bp_data, CeedData data,
PetscBool setup_rhs, CeedVector rhs_ceed,
CeedVector *target);
PetscErrorCode CeedLevelTransferSetup(Ceed ceed, CeedInt num_levels,
CeedInt num_comp_u, CeedData *data, CeedInt *leveldegrees,
CeedQFunction qf_restrict, CeedQFunction qf_prolong);
#endif // libceed_petsc_examples_setup_h
|
PROGRAM QE2LUS
IMPLICIT NONE
INTEGER ARGC
INTEGER NATOM
INTEGER IO
DOUBLE PRECISION E
CHARACTER*80 LINE
CHARACTER*80 ARGV
LOGICAL FIRST
ARGC = IARGC()
CALL GETARG(ARGC, ARGV)
OPEN(UNIT=26, FILE=ARGV(1:INDEX(ARGV,'.out')-1)//'.lus',
+ STATUS='UNKNOWN')
NATOM = 0
E = 0.0D0
FIRST = .FALSE.
OPEN(UNIT=55, IOSTAT=IO, FILE=ARGV)
DO WHILE(IO .EQ. 0)
READ(UNIT=55, IOSTAT=IO, FMT='(A80)') LINE
IF (IO .EQ. 0) THEN
IF (INDEX(LINE,'number of atoms') .NE. 0) THEN
READ(LINE(INDEX(LINE,'=')+1:LEN_TRIM(LINE)),*) NATOM
END IF
IF (INDEX(LINE,'! total energy') .NE. 0) THEN
READ(LINE(INDEX(LINE,'=')+1:LEN_TRIM(LINE)),*) E
END IF
IF (INDEX(LINE,'ATOMIC_POSITIONS') .NE. 0) THEN
IF (.NOT. FIRST) THEN
FIRST = .TRUE.
ELSE
WRITE(26,1001)
END IF
CALL RDGEO(NATOM, IO)
IF (E .NE. 0.0D0) THEN
WRITE(26,1000) E
E = 0.0D0
END IF
END IF
END IF
END DO
CLOSE(55)
CLOSE(26)
1000 FORMAT(1X,'<ENERGY>',/,2X,F15.8,/,1X,'</ENERGY>')
1001 FORMAT(1X,'<END>',/,1X,'<EDITABLE>',/,2X,'NO',/,1X,'</EDITABLE>')
END
SUBROUTINE RDGEO(NATOM, IO)
IMPLICIT NONE
INTEGER I
INTEGER NATOM
DOUBLE PRECISION XYZ(3)
INTEGER IO
CHARACTER*80 LINE
WRITE(26,1000) NATOM
DO 10 I = 1, NATOM
READ(UNIT=55, IOSTAT=IO, FMT='(A80)') LINE
IF (IO .EQ. 0) THEN
WRITE(26,*) ' ',LINE(1:LEN_TRIM(LINE))
END IF
10 CONTINUE
1000 FORMAT(2X,I5,/)
END
|
[STATEMENT]
lemma splus_comm:
"splus a b = splus b a"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. splus a b = splus b a
[PROOF STEP]
apply (cases a)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. a = None \<Longrightarrow> splus a b = splus b a
2. \<And>aa. a = Some aa \<Longrightarrow> splus a b = splus b a
[PROOF STEP]
apply (cases b)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<lbrakk>a = None; b = None\<rbrakk> \<Longrightarrow> splus a b = splus b a
2. \<And>aa. \<lbrakk>a = None; b = Some aa\<rbrakk> \<Longrightarrow> splus a b = splus b a
3. \<And>aa. a = Some aa \<Longrightarrow> splus a b = splus b a
[PROOF STEP]
apply simp_all
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>aa. a = Some aa \<Longrightarrow> splus (Some aa) b = splus b (Some aa)
[PROOF STEP]
apply (cases b)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>aa. \<lbrakk>a = Some aa; b = None\<rbrakk> \<Longrightarrow> splus (Some aa) b = splus b (Some aa)
2. \<And>aa aaa. \<lbrakk>a = Some aa; b = Some aaa\<rbrakk> \<Longrightarrow> splus (Some aa) b = splus b (Some aa)
[PROOF STEP]
by (simp_all add: commutative) |
# Gets the logs messages associated with a AWSBatch BatchJob as a single string
function log_messages(job::BatchJob; retries=5, wait_interval=7)
i = 0
events = log_events(job)
# Retry if no logs are found
while i < retries && (events === nothing || isempty(events))
i += 1
sleep(wait_interval)
events = log_events(job)
end
events === nothing && return ""
return join([string(event.timestamp, " ", event.message) for event in events], '\n')
end
function report(io::IO, job::BatchJob)
println(io, "Job ID: $(job.id)")
print(io, "Status: $(status(job))")
reason = status_reason(job)
reason !== nothing && print(io, " ($reason)")
println(io)
log_str = log_messages(job)
return !isempty(log_str) && println(io, '\n', log_str)
end
report(job::BatchJob) = sprint(report, job)
function job_duration(job::BatchJob)
d = describe(job)
if haskey(d, "createdAt") && haskey(d, "stoppedAt")
Millisecond(d["stoppedAt"] - d["createdAt"])
else
nothing
end
end
function job_runtime(job::BatchJob)
d = describe(job)
if haskey(d, "startedAt") && haskey(d, "stoppedAt")
Millisecond(d["stoppedAt"] - d["startedAt"])
else
nothing
end
end
function time_str(secs::Real)
@sprintf("%02d:%02d:%02d", div(secs, 3600), rem(div(secs, 60), 60), rem(secs, 60))
end
time_str(seconds::Second) = time_str(Dates.value(seconds))
time_str(p::Period) = time_str(floor(p, Second))
time_str(::Nothing) = "N/A" # Unable to determine duration
function register_job_definition(job_definition::AbstractDict)
output = Batch.register_job_definition(
job_definition["jobDefinitionName"], job_definition["type"], job_definition
)
return output["jobDefinitionArn"]
end
function submit_job(;
job_name::AbstractString,
job_definition::AbstractString,
job_queue::AbstractString=STACK["WorkerJobQueueArn"],
node_overrides::Dict=Dict(),
retry_strategy::Dict=Dict(),
)
options = Dict{String,Any}()
if !isempty(node_overrides)
options["nodeOverrides"] = node_overrides
end
if !isempty(retry_strategy)
options["retryStrategy"] = retry_strategy
end
print(JSON.json(options, 4))
output = Batch.submit_job(job_definition, job_name, job_queue, options)
return BatchJob(output["jobId"])
end
function describe_compute_environment(compute_environment::AbstractString)
# Equivalent to running the following on the AWS CLI
# ```
# aws batch describe-compute-environments
# --compute-environments $(STACK["ComputeEnvironmentArn"])
# --query computeEnvironments[0]
# ```
output = Batch.describe_compute_environments(
Dict("computeEnvironments" => [compute_environment])
)
details = if !isempty(output["computeEnvironments"])
output["computeEnvironments"][1]
else
nothing
end
return details
end
function wait_finish(job::BatchJob; timeout::Period=Minute(20))
timeout_secs = Dates.value(Second(timeout))
info(LOGGER, "Waiting for AWS Batch job to finish (~5 minutes)")
# TODO: Disable logging from wait? Or at least emit timestamps
wait(job, [AWSBatch.FAILED, AWSBatch.SUCCEEDED]; timeout=timeout_secs) # TODO: Support timeout as Period
duration = job_duration(job)
runtime = job_runtime(job)
info(LOGGER, "Job duration: $(time_str(duration)), Job runtime: $(time_str(runtime))")
return nothing
end
|
[GOAL]
x : ℂ
⊢ HasStrictDerivAt sin (cos x) x
[PROOFSTEP]
simp only [cos, div_eq_mul_inv]
[GOAL]
x : ℂ
⊢ HasStrictDerivAt sin ((exp (x * I) + exp (-x * I)) * 2⁻¹) x
[PROOFSTEP]
convert
((((hasStrictDerivAt_id x).neg.mul_const I).cexp.sub ((hasStrictDerivAt_id x).mul_const I).cexp).mul_const
I).mul_const
(2 : ℂ)⁻¹ using
1
[GOAL]
case h.e'_7
x : ℂ
⊢ (exp (x * I) + exp (-x * I)) * 2⁻¹ = (exp (-id x * I) * (-1 * I) - exp (id x * I) * (1 * I)) * I * 2⁻¹
[PROOFSTEP]
simp only [Function.comp, id]
[GOAL]
case h.e'_7
x : ℂ
⊢ (exp (x * I) + exp (-x * I)) * 2⁻¹ = (exp (-x * I) * (-1 * I) - exp (x * I) * (1 * I)) * I * 2⁻¹
[PROOFSTEP]
rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc, I_mul_I, mul_neg_one,
sub_neg_eq_add, add_comm]
[GOAL]
x : ℂ
⊢ HasStrictDerivAt cos (-sin x) x
[PROOFSTEP]
simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul]
[GOAL]
x : ℂ
⊢ HasStrictDerivAt cos (-(exp (-x * I) - exp (x * I)) * I * 2⁻¹) x
[PROOFSTEP]
convert
(((hasStrictDerivAt_id x).mul_const I).cexp.add ((hasStrictDerivAt_id x).neg.mul_const I).cexp).mul_const
(2 : ℂ)⁻¹ using
1
[GOAL]
case h.e'_7
x : ℂ
⊢ -(exp (-x * I) - exp (x * I)) * I * 2⁻¹ = (exp (id x * I) * (1 * I) + exp (-id x * I) * (-1 * I)) * 2⁻¹
[PROOFSTEP]
simp only [Function.comp, id]
[GOAL]
case h.e'_7
x : ℂ
⊢ -(exp (-x * I) - exp (x * I)) * I * 2⁻¹ = (exp (x * I) * (1 * I) + exp (-x * I) * (-1 * I)) * 2⁻¹
[PROOFSTEP]
ring
[GOAL]
x : ℂ
⊢ HasStrictDerivAt sinh (cosh x) x
[PROOFSTEP]
simp only [cosh, div_eq_mul_inv]
[GOAL]
x : ℂ
⊢ HasStrictDerivAt sinh ((exp x + exp (-x)) * 2⁻¹) x
[PROOFSTEP]
convert ((hasStrictDerivAt_exp x).sub (hasStrictDerivAt_id x).neg.cexp).mul_const (2 : ℂ)⁻¹ using 1
[GOAL]
case h.e'_7
x : ℂ
⊢ (exp x + exp (-x)) * 2⁻¹ = (exp x - exp (-id x) * -1) * 2⁻¹
[PROOFSTEP]
rw [id, mul_neg_one, sub_eq_add_neg, neg_neg]
[GOAL]
x : ℂ
⊢ HasStrictDerivAt cosh (sinh x) x
[PROOFSTEP]
simp only [sinh, div_eq_mul_inv]
[GOAL]
x : ℂ
⊢ HasStrictDerivAt cosh ((exp x - exp (-x)) * 2⁻¹) x
[PROOFSTEP]
convert ((hasStrictDerivAt_exp x).add (hasStrictDerivAt_id x).neg.cexp).mul_const (2 : ℂ)⁻¹ using 1
[GOAL]
case h.e'_7
x : ℂ
⊢ (exp x - exp (-x)) * 2⁻¹ = (exp x + exp (-id x) * -1) * 2⁻¹
[PROOFSTEP]
rw [id, mul_neg_one, sub_eq_add_neg]
[GOAL]
x y z : ℝ
⊢ ∀ (x : ℝ), 0 < deriv sinh x
[PROOFSTEP]
rw [Real.deriv_sinh]
[GOAL]
x y z : ℝ
⊢ ∀ (x : ℝ), 0 < cosh x
[PROOFSTEP]
exact cosh_pos
[GOAL]
x y z : ℝ
⊢ 0 < sinh x ↔ 0 < x
[PROOFSTEP]
simpa only [sinh_zero] using @sinh_lt_sinh 0 x
[GOAL]
x y z : ℝ
⊢ sinh x ≤ 0 ↔ x ≤ 0
[PROOFSTEP]
simpa only [sinh_zero] using @sinh_le_sinh x 0
[GOAL]
x y z : ℝ
⊢ sinh x < 0 ↔ x < 0
[PROOFSTEP]
simpa only [sinh_zero] using @sinh_lt_sinh x 0
[GOAL]
x y z : ℝ
⊢ 0 ≤ sinh x ↔ 0 ≤ x
[PROOFSTEP]
simpa only [sinh_zero] using @sinh_le_sinh 0 x
[GOAL]
x✝ y z x : ℝ
⊢ |sinh x| = sinh |x|
[PROOFSTEP]
cases le_total x 0
[GOAL]
case inl
x✝ y z x : ℝ
h✝ : x ≤ 0
⊢ |sinh x| = sinh |x|
[PROOFSTEP]
simp [abs_of_nonneg, abs_of_nonpos, *]
[GOAL]
case inr
x✝ y z x : ℝ
h✝ : 0 ≤ x
⊢ |sinh x| = sinh |x|
[PROOFSTEP]
simp [abs_of_nonneg, abs_of_nonpos, *]
[GOAL]
x✝ y z x : ℝ
hx : x ∈ interior (Ici 0)
⊢ 0 < deriv cosh x
[PROOFSTEP]
rw [interior_Ici, mem_Ioi] at hx
[GOAL]
x✝ y z x : ℝ
hx : 0 < x
⊢ 0 < deriv cosh x
[PROOFSTEP]
rwa [deriv_cosh, sinh_pos_iff]
[GOAL]
x✝ y z x : ℝ
⊢ |0| ≤ |x|
[PROOFSTEP]
simp only [_root_.abs_zero, _root_.abs_nonneg]
[GOAL]
x y z : ℝ
⊢ |0| < |x| ↔ x ≠ 0
[PROOFSTEP]
simp only [_root_.abs_zero, abs_pos]
[GOAL]
x y z : ℝ
⊢ StrictMono fun x => sinh x - x
[PROOFSTEP]
refine' strictMono_of_odd_strictMonoOn_nonneg (fun x => by simp; abel) _
[GOAL]
x✝ y z x : ℝ
⊢ sinh (-x) - -x = -(sinh x - x)
[PROOFSTEP]
simp
[GOAL]
x✝ y z x : ℝ
⊢ -sinh x + x = x - sinh x
[PROOFSTEP]
abel
[GOAL]
x✝ y z x : ℝ
⊢ -sinh x + x = x - sinh x
[PROOFSTEP]
abel
[GOAL]
x y z : ℝ
⊢ StrictMonoOn (fun x => sinh x - x) (Ici 0)
[PROOFSTEP]
refine' (convex_Ici _).strictMonoOn_of_deriv_pos _ fun x hx => _
[GOAL]
case refine'_1
x y z : ℝ
⊢ ContinuousOn (fun x => sinh x - x) (Ici 0)
[PROOFSTEP]
exact (continuous_sinh.sub continuous_id).continuousOn
[GOAL]
case refine'_2
x✝ y z x : ℝ
hx : x ∈ interior (Ici 0)
⊢ 0 < deriv (fun x => sinh x - x) x
[PROOFSTEP]
rw [interior_Ici, mem_Ioi] at hx
[GOAL]
case refine'_2
x✝ y z x : ℝ
hx : 0 < x
⊢ 0 < deriv (fun x => sinh x - x) x
[PROOFSTEP]
rw [deriv_sub, deriv_sinh, deriv_id'', sub_pos, one_lt_cosh]
[GOAL]
case refine'_2
x✝ y z x : ℝ
hx : 0 < x
⊢ x ≠ 0
case refine'_2.hf
x✝ y z x : ℝ
hx : 0 < x
⊢ DifferentiableAt ℝ (fun x => sinh x) x
case refine'_2.hg x✝ y z x : ℝ hx : 0 < x ⊢ DifferentiableAt ℝ (fun x => x) x
[PROOFSTEP]
exacts [hx.ne', differentiableAt_sinh, differentiableAt_id]
[GOAL]
x y z : ℝ
⊢ x ≤ sinh x ↔ sinh 0 - 0 ≤ sinh x - x
[PROOFSTEP]
simp
[GOAL]
x y z : ℝ
⊢ sinh x ≤ x ↔ sinh x - x ≤ sinh 0 - 0
[PROOFSTEP]
simp
|
The clinical signs and symptoms of AML result from the growth of leukemic clone cells , which tends to displace or interfere with the development of normal blood cells in the bone marrow . This leads to neutropenia , anemia , and thrombocytopenia . The symptoms of AML are , in turn , often due to the low numbers of these normal blood elements . In rare cases , people with AML can develop a <unk> , or solid tumor of leukemic cells outside the bone marrow , which can cause various symptoms depending on its location .
|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01_randaugment.ipynb (unless otherwise specified).
__all__ = ['float_parameter', 'int_parameter', 'PARAMETER_MAX', 'flip_lr', 'flip_ud', 'rotate', 'scale', 'shift',
'cutout', 'find_coeffs', 'perspective', 'invert', 'equalize', 'posterize', 'contrast', 'color', 'brightness',
'sharpness', 'ALL_TRANSFORMS', 'RandAugment']
# Cell
import random
import cv2
import numpy as np
from fastai2.data.core import Transform
from fastai2.vision.core import PILImage
from PIL import ImageOps, ImageEnhance, ImageFilter, Image
from albumentations import Cutout
from albumentations.augmentations.functional import shift_scale_rotate
# Cell
PARAMETER_MAX=10
def float_parameter(level, maxval):
"Helper function to scale `val` between 0 and maxval."
return float(level) * maxval / PARAMETER_MAX
def int_parameter(level, maxval):
"Helper function to scale `val` between 0 and maxval."
return int(level * maxval / PARAMETER_MAX)
# Cell
def flip_lr(img, level):
return img.transpose(Image.FLIP_LEFT_RIGHT)
def flip_ud(img, level):
return img.transpose(Image.FLIP_TOP_BOTTOM)
def rotate(img, level):
"Rotate for 30 degrees max"
degrees = int_parameter(level, 30)
if random.random() < 0.5:
degrees = -degrees
return Image.fromarray(shift_scale_rotate(np.array(img), degrees, 1.0, 0, 0))
def scale(img, level):
"Scale image with level. Zoom in/out at random"
v = float_parameter(level, 1.0)
if random.random() < 0.5:
v = -v * 0.4
return Image.fromarray(shift_scale_rotate(np.array(img), 0, v + 1.0, 0, 0))
def shift(img, level):
"Do shift with level strength in random directions"
s = int_parameter(level, 10)
do_x, do_y = random.choice([(0,1), (0,-1), (1,0), (-1,0), (1,1), (-1,1), (1,-1)])
return Image.fromarray(shift_scale_rotate(np.array(img), 0, 1.0, do_x * s, do_y * s))
def cutout(img, level):
"Cutout `level` blocks from image"
level = int_parameter(level, 10)
aug = Cutout(num_holes=level, always_apply=True)
return Image.fromarray(aug(image=np.array(img))["image"])
# Random perspective
def find_coeffs(pa, pb):
matrix = []
for p1, p2 in zip(pa, pb):
matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])
matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])
A = np.matrix(matrix, dtype=np.float32)
B = np.array(pb).reshape(8)
res = np.linalg.inv(A.T * A) * A.T @ B
return np.r_[np.array(res).flatten(), 1].reshape(3,3)
def perspective(img, level):
w, h = img.size
y, x = float_parameter(level, 8), float_parameter(level, 8)
if random.random() < 0.5: y = -y
if random.random() < 0.5: x = -x
# Compute perspective warp coordinates
orig = [(0, 0), (h, 0), (h, w), (0, w)]
persp = [(0-y, 0-x), (h+y, 0+x), (h+y, w+x), (0-y, w-x)]
coefs = find_coeffs(orig, persp)
img = np.array(img).astype(np.float32) / 255.
persp_img = cv2.warpPerspective(
img,
coefs,
(h,w),
cv2.INTER_CUBIC,
borderMode=cv2.BORDER_REFLECT101
)
return Image.fromarray((persp_img * 255.).astype(np.uint8))
# Cell
def invert(img, level):
"Negative image"
return ImageOps.invert(img)
def equalize(img, level):
"Equalize image histogram"
return ImageOps.equalize(img)
def posterize(img, level):
"Control bits count used to store colors"
bits = 5 - int_parameter(level, 4)
return ImageOps.posterize(img, bits)
def contrast(img, level):
"Change contrast with param in [0.5, 1.0, 3.0]"
v = float_parameter(level, 2.0)
if random.random() < 0.5:
v = -v / 4.0
return ImageEnhance.Contrast(img).enhance(v + 1.0)
def color(img, level):
"Change color with param in [0, 1.0, 3.0]"
v = float_parameter(level, 2.0)
if random.random() < 0.5:
v = -v / 2.0
return ImageEnhance.Color(img).enhance(v + 1.0)
def brightness(img, level):
"Controll brightness with param in [1/3, 2.0]"
v = float_parameter(level, 1.0)
if random.random() < 0.5:
v = -v / 1.5
return ImageEnhance.Brightness(img).enhance(v + 1.0)
def sharpness(img, level):
"Controll sharpness with param in [0, 4]"
v = float_parameter(level, 3.0)
if random.random() < 0.5:
v = -v / 3.0
return ImageEnhance.Sharpness(img).enhance(v + 1.0)
# Cell
ALL_TRANSFORMS = [
flip_lr,
flip_ud,
rotate,
scale,
shift,
cutout,
perspective,
invert,
equalize,
posterize,
contrast,
color,
brightness,
sharpness
]
# Cell
class RandAugment(Transform):
"Apply randaugment augmentation policy"
def __init__(self):
ops = []
self.policies = []
for t in ALL_TRANSFORMS:
for m in range(1, 11):
ops += [(t, 0.5, m)]
for op1 in ops:
for op2 in ops:
self.policies += [[op1, op2]]
def encodes(self, img: PILImage):
policy = random.choice(self.policies)
x = img
for op, p, m in policy:
if random.random() < p:
x = op(x, m)
return x |
(* Author: Johannes Hölzl <[email protected]> *)
section \<open>Discrete-time Markov Processes\<close>
text \<open>In this file we construct discrete-time Markov processes, e.g. with arbitrary state spaces.\<close>
theory Discrete_Time_Markov_Process
imports Markov_Models_Auxiliary
begin
lemma measure_eqI_PiM_sequence:
fixes M :: "nat \<Rightarrow> 'a measure"
assumes *[simp]: "sets P = PiM UNIV M" "sets Q = PiM UNIV M"
assumes eq: "\<And>A n. (\<And>i. A i \<in> sets (M i)) \<Longrightarrow>
P (prod_emb UNIV M {..n} (Pi\<^sub>E {..n} A)) = Q (prod_emb UNIV M {..n} (Pi\<^sub>E {..n} A))"
assumes A: "finite_measure P"
shows "P = Q"
proof (rule measure_eqI_PiM_infinite[OF * _ A])
fix J :: "nat set" and F'
assume J: "finite J" "\<And>i. i \<in> J \<Longrightarrow> F' i \<in> sets (M i)"
define n where "n = (if J = {} then 0 else Max J)"
define F where "F i = (if i \<in> J then F' i else space (M i))" for i
then have F[simp, measurable]: "F i \<in> sets (M i)" for i
using J by auto
have emb_eq: "prod_emb UNIV M J (Pi\<^sub>E J F') = prod_emb UNIV M {..n} (Pi\<^sub>E {..n} F)"
proof cases
assume "J = {}" then show ?thesis
by (auto simp add: n_def F_def[abs_def] prod_emb_def PiE_def)
next
assume "J \<noteq> {}" then show ?thesis
by (auto simp: prod_emb_def PiE_iff F_def n_def less_Suc_eq_le \<open>finite J\<close> split: if_split_asm)
qed
show "emeasure P (prod_emb UNIV M J (Pi\<^sub>E J F')) = emeasure Q (prod_emb UNIV M J (Pi\<^sub>E J F'))"
unfolding emb_eq by (rule eq) fact
qed
lemma distr_cong_simp:
"M = K \<Longrightarrow> sets N = sets L \<Longrightarrow> (\<And>x. x \<in> space M =simp=> f x = g x) \<Longrightarrow> distr M N f = distr K L g"
unfolding simp_implies_def by (rule distr_cong)
subsection \<open>Constructing Discrete-Time Markov Processes\<close>
locale discrete_Markov_process =
fixes M :: "'a measure" and K :: "'a \<Rightarrow> 'a measure"
assumes K[measurable]: "K \<in> M \<rightarrow>\<^sub>M prob_algebra M"
begin
lemma space_K: "x \<in> space M \<Longrightarrow> space (K x) = space M"
using K unfolding prob_algebra_def unfolding measurable_restrict_space2_iff
by (auto dest: subprob_measurableD)
lemma sets_K[measurable_cong]: "x \<in> space M \<Longrightarrow> sets (K x) = sets M"
using K unfolding prob_algebra_def unfolding measurable_restrict_space2_iff
by (auto dest: subprob_measurableD)
lemma prob_space_K: "x \<in> space M \<Longrightarrow> prob_space (K x)"
using measurable_space[OF K] by (simp add: space_prob_algebra)
definition K' :: "'a \<Rightarrow> nat \<Rightarrow> (nat \<Rightarrow> 'a) \<Rightarrow> 'a measure"
where
"K' x n' \<omega>' = K (case_nat x \<omega>' n')"
lemma IT_K':
assumes x: "x \<in> space M" shows "Ionescu_Tulcea (K' x) (\<lambda>_. M)"
unfolding Ionescu_Tulcea_def K'_def[abs_def]
proof safe
fix i show "(\<lambda>\<omega>'. K (case i of 0 \<Rightarrow> x | Suc x \<Rightarrow> \<omega>' x)) \<in> Pi\<^sub>M {0..<i} (\<lambda>_. M) \<rightarrow>\<^sub>M subprob_algebra M"
using x by (intro measurable_prob_algebraD measurable_compose[OF _ K]) measurable
next
fix i :: nat and \<omega> assume \<omega>: "\<omega> \<in> space (Pi\<^sub>M {0..<i} (\<lambda>_. M))"
with x have "(case i of 0 \<Rightarrow> x | Suc x \<Rightarrow> \<omega> x) \<in> space M"
by (auto simp: space_PiM split: nat.split)
then show "prob_space (K (case i of 0 \<Rightarrow> x | Suc x \<Rightarrow> \<omega> x))"
using K unfolding measurable_restrict_space2_iff prob_algebra_def by auto
qed
definition lim_sequence :: "'a \<Rightarrow> (nat \<Rightarrow> 'a) measure"
where
"lim_sequence x = projective_family.lim UNIV (Ionescu_Tulcea.CI (K' x) (\<lambda>_. M)) (\<lambda>_. M)"
lemma
assumes x: "x \<in> space M"
shows space_lim_sequence: "space (lim_sequence x) = space (\<Pi>\<^sub>M i\<in>UNIV. M)"
and sets_lim_sequence[measurable_cong]: "sets (lim_sequence x) = sets (\<Pi>\<^sub>M i\<in>UNIV. M)"
and emeasure_lim_sequence_emb: "\<And>J X. finite J \<Longrightarrow> X \<in> sets (\<Pi>\<^sub>M j\<in>J. M) \<Longrightarrow>
emeasure (lim_sequence x) (prod_emb UNIV (\<lambda>_. M) J X) =
emeasure (Ionescu_Tulcea.CI (K' x) (\<lambda>_. M) J) X"
and emeasure_lim_sequence_emb_I0o: "\<And>n X. X \<in> sets (\<Pi>\<^sub>M i \<in> {0..<n}. M) \<Longrightarrow>
emeasure (lim_sequence x) (prod_emb UNIV (\<lambda>_. M) {0..<n} X) =
emeasure (Ionescu_Tulcea.C (K' x) (\<lambda>_. M) 0 n (\<lambda>x. undefined)) X"
proof -
interpret Ionescu_Tulcea "K' x" "\<lambda>_. M"
using x by (rule IT_K')
show "space (lim_sequence x) = space (\<Pi>\<^sub>M i\<in>UNIV. M)"
unfolding lim_sequence_def by simp
show "sets (lim_sequence x) = sets (\<Pi>\<^sub>M i\<in>UNIV. M)"
unfolding lim_sequence_def by simp
{ fix J :: "nat set" and X assume "finite J" "X \<in> sets (\<Pi>\<^sub>M j\<in>J. M)"
then show "emeasure (lim_sequence x) (PF.emb UNIV J X) = emeasure (CI J) X"
unfolding lim_sequence_def by (rule lim) }
note emb = this
have up_to_I0o[simp]: "up_to {0..<n} = n" for n
unfolding up_to_def by (rule Least_equality) auto
{ fix n :: nat and X assume "X \<in> sets (\<Pi>\<^sub>M j\<in>{0..<n}. M)"
then show "emeasure (lim_sequence x) (PF.emb UNIV {0..<n} X) = emeasure (C 0 n (\<lambda>x. undefined)) X"
by (simp add: space_C emb CI_def space_PiM distr_id2 sets_C cong: distr_cong_simp) }
qed
lemma lim_sequence[measurable]: "lim_sequence \<in> M \<rightarrow>\<^sub>M prob_algebra (\<Pi>\<^sub>M i\<in>UNIV. M)"
proof (intro measurable_prob_algebra_generated[OF sets_PiM Int_stable_prod_algebra prod_algebra_sets_into_space])
fix a assume [simp]: "a \<in> space M"
interpret Ionescu_Tulcea "K' a" "\<lambda>_. M"
by (rule IT_K') simp
have sp: "space (lim_sequence a) = prod_emb UNIV (\<lambda>_. M) {} (\<Pi>\<^sub>E j\<in>{}. space M)" "space (CI {}) = {} \<rightarrow>\<^sub>E space M"
by (auto simp: space_lim_sequence space_PiM prod_emb_def PF.space_P)
show "prob_space (lim_sequence a)"
apply standard
using PF.prob_space_P[THEN prob_space.emeasure_space_1, of "{}"]
apply (simp add: sp emeasure_lim_sequence_emb del: PiE_empty_domain)
done
show "sets (lim_sequence a) = sets (Pi\<^sub>M UNIV (\<lambda>i. M))"
by (simp add: sets_lim_sequence)
next
fix X :: "(nat \<Rightarrow> 'a) set" assume "X \<in> prod_algebra UNIV (\<lambda>i. M)"
then obtain J :: "nat set" and F where J: "J \<noteq> {}" "finite J" "F \<in> J \<rightarrow> sets M"
and X: "X = prod_emb UNIV (\<lambda>_. M) J (Pi\<^sub>E J F)"
unfolding prod_algebra_def by auto
then have Pi_F: "finite J" "Pi\<^sub>E J F \<in> sets (Pi\<^sub>M J (\<lambda>_. M))"
by (auto intro: sets_PiM_I_finite)
define n where "n = (LEAST n. \<forall>i\<ge>n. i \<notin> J)"
have J_le_n: "J \<subseteq> {0..<n}"
unfolding n_def
using \<open>finite J\<close>
apply -
apply (rule LeastI2[of _ "Suc (Max J)"])
apply (auto simp: Suc_le_eq not_le[symmetric])
done
have C: "(\<lambda>x. Ionescu_Tulcea.C (K' x) (\<lambda>_. M) 0 n (\<lambda>x. undefined)) \<in> M \<rightarrow>\<^sub>M subprob_algebra (Pi\<^sub>M {0..<n} (\<lambda>_. M))"
apply (induction n)
apply (subst measurable_cong)
apply (rule Ionescu_Tulcea.C.simps[OF IT_K'])
apply assumption
apply (rule measurable_compose[OF _ return_measurable])
apply simp
apply (subst measurable_cong)
apply (rule Ionescu_Tulcea.C.simps[OF IT_K'])
apply assumption
apply (rule measurable_bind')
apply assumption
apply (subst measurable_cong)
proof -
fix n :: nat and w assume "w \<in> space (M \<Otimes>\<^sub>M Pi\<^sub>M {0..<n} (\<lambda>_. M))"
then show "(case w of (x, xa) \<Rightarrow> Ionescu_Tulcea.eP (K' x) (\<lambda>_. M) (0 + n) xa) =
(case w of (x, xa) \<Rightarrow> distr (K' x n xa) (\<Pi>\<^sub>M i\<in>{0..<Suc n}. M) (fun_upd xa n))"
by (auto simp: space_pair_measure Ionescu_Tulcea.eP_def[OF IT_K'] split: prod.split)
next
fix n show "(\<lambda>w. case w of (x, xa) \<Rightarrow> distr (K' x n xa) (Pi\<^sub>M {0..<Suc n} (\<lambda>i. M)) (fun_upd xa n))
\<in> M \<Otimes>\<^sub>M Pi\<^sub>M {0..<n} (\<lambda>_. M) \<rightarrow>\<^sub>M subprob_algebra (Pi\<^sub>M {0..<Suc n} (\<lambda>_. M))"
unfolding K'_def
apply measurable
apply (rule measurable_distr2[where M=M])
apply (rule measurable_PiM_single')
apply (simp add: split_beta')
subgoal for i by (cases "i = n") auto
subgoal by (auto simp: split_beta' PiE_iff extensional_def Pi_iff space_pair_measure space_PiM)
apply (rule measurable_prob_algebraD)
apply (rule measurable_compose[OF _ K])
apply measurable
done
qed
have "(\<lambda>a. emeasure (lim_sequence a) X) \<in> borel_measurable M \<longleftrightarrow>
(\<lambda>a. emeasure (Ionescu_Tulcea.CI (K' a) (\<lambda>_. M) J) (Pi\<^sub>E J F)) \<in> borel_measurable M"
unfolding X using J Pi_F by (intro measurable_cong emeasure_lim_sequence_emb) auto
also have "\<dots>"
apply (intro measurable_compose[OF _ measurable_emeasure_subprob_algebra[OF Pi_F(2)]])
apply (subst measurable_cong)
apply (subst Ionescu_Tulcea.CI_def[OF IT_K'])
apply assumption
apply (subst Ionescu_Tulcea.up_to_def[OF IT_K'])
apply assumption
unfolding n_def[symmetric]
apply (rule refl)
apply (rule measurable_compose[OF _ measurable_distr[OF measurable_restrict_subset[OF J_le_n]]])
apply (rule C)
done
finally show "(\<lambda>a. emeasure (lim_sequence a) X) \<in> borel_measurable M" .
qed
have [simp]: "space (K x) \<noteq> {}"
using space_K[OF x] x by auto
have [simp]: "((\<lambda>_. undefined::'a)(0 := x)) = case_nat x (\<lambda>_. undefined)" for x
by (auto simp: fun_eq_iff split: nat.split)
have "C 0 1 (\<lambda>_. undefined) \<bind> C 1 n = eP 0 (\<lambda>_. undefined) \<bind> C 1 n"
using measurable_eP[of 0] measurable_C[of 1 n, measurable del]
by (simp add: bind_return[where N="Pi\<^sub>M {0} (\<lambda>_. M)"])
also have "\<dots> = K x \<bind> (\<lambda>y. C 1 n (case_nat y (\<lambda>_. undefined)))"
using measurable_C[of 1 n, measurable del] x[THEN sets_K]
by (simp add: eP_def K'_def bind_distr cong: measurable_cong_sets)
finally show "C 0 1 (\<lambda>_. undefined) \<bind> C 1 n = K x \<bind> (\<lambda>y. C 1 n (case_nat y (\<lambda>_. undefined)))" .
qed
lemma lim_sequence_eq:
assumes x: "x \<in> space M"
shows "lim_sequence x = bind (K x) (\<lambda>y. distr (lim_sequence y) (\<Pi>\<^sub>M j\<in>UNIV. M) (case_nat y))"
(is "_ = ?B x")
proof (rule measure_eqI_PiM_infinite)
show "sets (lim_sequence x) = sets (\<Pi>\<^sub>M j\<in>UNIV. M)"
using x by (rule sets_lim_sequence)
have [simp]: "space (K x) \<noteq> {}"
using space_K[OF x] x by auto
show "sets (?B x) = sets (Pi\<^sub>M UNIV (\<lambda>j. M))"
using x by (subst sets_bind) auto
interpret lim_sequence: prob_space "lim_sequence x"
using lim_sequence x by (auto simp: measurable_restrict_space2_iff prob_algebra_def)
show "finite_measure (lim_sequence x)"
by (rule lim_sequence.finite_measure)
interpret Ionescu_Tulcea "K' x" "\<lambda>_. M"
using x by (rule IT_K')
let ?U = "\<lambda>_::nat. undefined :: 'a"
fix J :: "nat set" and F'
assume J: "finite J" "\<And>i. i \<in> J \<Longrightarrow> F' i \<in> sets M"
define n where "n = (if J = {} then 0 else Max J)"
define F where "F i = (if i \<in> J then F' i else space M)" for i
then have F[simp, measurable]: "F i \<in> sets M" for i
using J by auto
have emb_eq: "PF.emb UNIV J (Pi\<^sub>E J F') = PF.emb UNIV {0..<Suc n} (Pi\<^sub>E {0..<Suc n} F)"
proof cases
assume "J = {}" then show ?thesis
by (auto simp add: n_def F_def[abs_def] prod_emb_def PiE_def)
next
assume "J \<noteq> {}" then show ?thesis
by (auto simp: prod_emb_def PiE_iff F_def n_def less_Suc_eq_le \<open>finite J\<close> split: if_split_asm)
qed
have "emeasure (lim_sequence x) (PF.emb UNIV J (Pi\<^sub>E J F')) = emeasure (C 0 (Suc n) ?U) (Pi\<^sub>E {0..<Suc n} F)"
using x unfolding emb_eq by (rule emeasure_lim_sequence_emb_I0o) (auto intro!: sets_PiM_I_finite)
also have "C 0 (Suc n) ?U = K x \<bind> (\<lambda>y. C 1 n (case_nat y ?U))"
using split_C[of ?U 0 "Suc 0" n] step_C[OF x] by simp
also have "emeasure (K x \<bind> (\<lambda>y. C 1 n (case_nat y ?U))) (Pi\<^sub>E {0..<Suc n} F) =
(\<integral>\<^sup>+y. C 1 n (case_nat y ?U) (Pi\<^sub>E {0..<Suc n} F) \<partial>K x)"
using measurable_C[of 1 n, measurable del] x[THEN sets_K] F x
by (intro emeasure_bind[OF _ measurable_compose[OF _ measurable_C]])
(auto cong: measurable_cong_sets intro!: measurable_PiM_single' split: nat.split_asm)
also have "\<dots> = (\<integral>\<^sup>+y. distr (lim_sequence y) (Pi\<^sub>M UNIV (\<lambda>j. M)) (case_nat y) (PF.emb UNIV J (Pi\<^sub>E J F')) \<partial>K x)"
proof (intro nn_integral_cong)
fix y assume "y \<in> space (K x)"
then have y: "y \<in> space M"
using x by (simp add: space_K)
then interpret y: Ionescu_Tulcea "K' y" "\<lambda>_. M"
by (rule IT_K')
let ?y = "case_nat y"
have [simp]: "?y ?U \<in> space (Pi\<^sub>M {0} (\<lambda>i. M))"
using y by (auto simp: space_PiM PiE_iff extensional_def split: nat.split)
have yM[measurable]: "?y \<in> Pi\<^sub>M {0..<m} (\<lambda>_. M) \<rightarrow>\<^sub>M Pi\<^sub>M {0..<Suc m} (\<lambda>i. M)" for m
using y by (intro measurable_PiM_single') (auto simp: space_PiM PiE_iff extensional_def split: nat.split)
have y': "?y ?U \<in> space (Pi\<^sub>M {0..<1} (\<lambda>i. M))"
by (simp add: space_PiM PiE_def y extensional_def split: nat.split)
have eq1: "?y -` Pi\<^sub>E {0..<Suc n} F \<inter> space (Pi\<^sub>M {0..<n} (\<lambda>_. M)) =
(if y \<in> F 0 then Pi\<^sub>E {0..<n} (F\<circ>Suc) else {})"
unfolding set_eq_iff using y sets.sets_into_space[OF F]
by (auto simp: space_PiM PiE_iff extensional_def Ball_def split: nat.split nat.split_asm)
have eq2: "?y -` PF.emb UNIV {0..<Suc n} (Pi\<^sub>E {0..<Suc n} F) \<inter> space (Pi\<^sub>M UNIV (\<lambda>_. M)) =
(if y \<in> F 0 then PF.emb UNIV {0..<n} (Pi\<^sub>E {0..<n} (F\<circ>Suc)) else {})"
unfolding set_eq_iff using y sets.sets_into_space[OF F]
by (auto simp: space_PiM PiE_iff prod_emb_def extensional_def Ball_def split: nat.split nat.split_asm)
let ?I = "indicator (F 0) y"
have "C 1 n (?y ?U) = distr (y.C 0 n ?U) (\<Pi>\<^sub>M i\<in>{0..<Suc n}. M) ?y"
proof (induction n)
case (Suc m)
have "C 1 (Suc m) (?y ?U) = distr (y.C 0 m ?U) (Pi\<^sub>M {0..<Suc m} (\<lambda>i. M)) ?y \<bind> eP (Suc m)"
using Suc by simp
also have "\<dots> = y.C 0 m ?U \<bind> (\<lambda>x. eP (Suc m) (?y x))"
by (intro bind_distr[where K="Pi\<^sub>M {0..<Suc (Suc m)} (\<lambda>_. M)"]) (simp_all add: y y.space_C y.sets_C cong: measurable_cong_sets)
also have "\<dots> = y.C 0 m ?U \<bind> (\<lambda>x. distr (y.eP m x) (Pi\<^sub>M {0..<Suc (Suc m)} (\<lambda>i. M)) ?y)"
proof (intro bind_cong refl)
fix \<omega>' assume \<omega>': "\<omega>' \<in> space (y.C 0 m ?U)"
moreover have "K' x (Suc m) (?y \<omega>') = K' y m \<omega>'"
by (auto simp: K'_def)
ultimately show "eP (Suc m) (?y \<omega>') = distr (y.eP m \<omega>') (Pi\<^sub>M {0..<Suc (Suc m)} (\<lambda>i. M)) ?y"
unfolding eP_def y.eP_def
by (subst distr_distr)
(auto simp: y.space_C y.sets_P split: nat.split cong: measurable_cong_sets
intro!: distr_cong measurable_fun_upd[where J="{0..<m}"])
qed
also have "\<dots> = distr (y.C 0 m ?U \<bind> y.eP m) (Pi\<^sub>M {0..<Suc (Suc m)} (\<lambda>i. M)) ?y"
by (intro distr_bind[symmetric, OF _ _ yM]) (auto simp: y.space_C y.sets_C cong: measurable_cong_sets)
finally show ?case
by simp
qed (use y in \<open>simp add: PiM_empty distr_return\<close>)
then have "C 1 n (case_nat y ?U) (Pi\<^sub>E {0..<Suc n} F) =
(distr (y.C 0 n ?U) (\<Pi>\<^sub>M i\<in>{0..<Suc n}. M) ?y) (Pi\<^sub>E {0..<Suc n} F)" by simp
also have "\<dots> = ?I * y.C 0 n ?U (Pi\<^sub>E {0..<n} (F \<circ> Suc))"
by (subst emeasure_distr) (auto simp: y.sets_C y.space_C eq1 cong: measurable_cong_sets)
also have "\<dots> = ?I * lim_sequence y (PF.emb UNIV {0..<n} (Pi\<^sub>E {0..<n} (F \<circ> Suc)))"
using y by (simp add: emeasure_lim_sequence_emb_I0o sets_PiM_I_finite)
also have "\<dots> = distr (lim_sequence y) (Pi\<^sub>M UNIV (\<lambda>j. M)) ?y (PF.emb UNIV {0..<Suc n} (Pi\<^sub>E {0..<Suc n} F))"
using y by (subst emeasure_distr) (simp_all add: eq2 space_lim_sequence)
finally show "emeasure (C 1 n (case_nat y (\<lambda>_. undefined))) (Pi\<^sub>E {0..<Suc n} F) =
emeasure (distr (lim_sequence y) (Pi\<^sub>M UNIV (\<lambda>j. M)) (case_nat y)) (PF.emb UNIV J (Pi\<^sub>E J F'))"
unfolding emb_eq .
qed
also have "\<dots> =
emeasure (K x \<bind> (\<lambda>y. distr (lim_sequence y) (Pi\<^sub>M UNIV (\<lambda>j. M)) (case_nat y))) (PF.emb UNIV J (Pi\<^sub>E J F'))"
using J
by (subst emeasure_bind[where N="PiM UNIV (\<lambda>_. M)"])
(auto simp: sets_K x intro!: measurable_distr2[OF _ measurable_prob_algebraD[OF lim_sequence]] cong: measurable_cong_sets)
finally show "emeasure (lim_sequence x) (PF.emb UNIV J (Pi\<^sub>E J F')) =
emeasure (K x \<bind> (\<lambda>y. distr (lim_sequence y) (Pi\<^sub>M UNIV (\<lambda>j. M)) (case_nat y)))
(PF.emb UNIV J (Pi\<^sub>E J F'))" .
qed
lemma AE_lim_sequence:
assumes x[simp]: "x \<in> space M" and P[measurable]: "Measurable.pred (\<Pi>\<^sub>M i\<in>UNIV. M) P"
shows "(AE \<omega> in lim_sequence x. P \<omega>) \<longleftrightarrow> (AE y in K x. AE \<omega> in lim_sequence y. P (case_nat y \<omega>))"
apply (simp add: lim_sequence_eq cong del: AE_cong)
apply (subst AE_bind)
apply (rule measurable_prob_algebraD)
apply measurable
apply (auto intro!: AE_cong simp add: space_K AE_distr_iff)
done
definition lim_stream :: "'a \<Rightarrow> 'a stream measure"
where
"lim_stream x = distr (lim_sequence x) (stream_space M) to_stream"
lemma space_lim_stream: "space (lim_stream x) = streams (space M)"
unfolding lim_stream_def by (simp add: space_stream_space)
lemma sets_lim_stream[measurable_cong]: "sets (lim_stream x) = sets (stream_space M)"
unfolding lim_stream_def by simp
lemma lim_stream[measurable]: "lim_stream \<in> M \<rightarrow>\<^sub>M prob_algebra (stream_space M)"
unfolding lim_stream_def[abs_def] by (intro measurable_distr_prob_space2[OF lim_sequence]) auto
lemma space_stream_space_M_ne: "x \<in> space M \<Longrightarrow> space (stream_space M) \<noteq> {}"
using sconst_streams[of x "space M"] by (auto simp: space_stream_space)
lemma prob_space_lim_stream: "x \<in> space M \<Longrightarrow> prob_space (lim_stream x)"
using measurable_space[OF lim_stream, of x] by (simp add: space_prob_algebra)
lemma lim_stream_eq:
assumes x: "x \<in> space M"
shows "lim_stream x = do { y \<leftarrow> K x; \<omega> \<leftarrow> lim_stream y; return (stream_space M) (y ## \<omega>) }"
unfolding lim_stream_def
apply (subst lim_sequence_eq[OF x])
apply (subst distr_bind[OF _ _ measurable_to_stream])
subgoal
by (auto simp: sets_K x cong: measurable_cong_sets
intro!: measurable_prob_algebraD measurable_distr_prob_space2[where M="Pi\<^sub>M UNIV (\<lambda>j. M)"] lim_sequence) []
subgoal
using x by (auto simp add: space_K)
apply (intro bind_cong refl)
apply (subst distr_distr)
apply (auto simp: space_K sets_lim_sequence x cong: measurable_cong_sets intro!: distr_cong)
apply (subst bind_return_distr')
apply (auto simp: space_stream_space_M_ne)
apply (subst distr_distr)
apply (auto simp: space_K sets_lim_sequence x to_stream_nat_case cong: measurable_cong_sets intro!: distr_cong)
done
lemma AE_lim_stream:
assumes x[simp]: "x \<in> space M" and P[measurable]: "Measurable.pred (stream_space M) P"
shows "(AE \<omega> in lim_stream x. P \<omega>) \<longleftrightarrow> (AE y in K x. AE \<omega> in lim_stream y. P (y ## \<omega>))"
unfolding lim_stream_eq[OF x]
by (simp_all add: space_K space_lim_stream space_stream_space AE_return AE_bind[OF measurable_prob_algebraD P] cong: AE_cong_simp)
lemma emeasure_lim_stream:
assumes x[measurable, simp]: "x \<in> space M" and A[measurable, simp]: "A \<in> sets (stream_space M)"
shows "lim_stream x A = (\<integral>\<^sup>+y. emeasure (lim_stream y) (((##) y) -` A \<inter> space (stream_space M)) \<partial>K x)"
apply (subst lim_stream_eq, simp)
apply (subst emeasure_bind[OF _ _ A], simp add: prob_space.not_empty prob_space_K)
apply (rule measurable_prob_algebraD)
apply measurable
apply (intro nn_integral_cong)
apply (subst bind_return_distr')
apply (auto intro!: prob_space.not_empty prob_space_lim_stream simp: space_K emeasure_distr)
apply (simp add: space_lim_stream space_stream_space)
done
lemma lim_stream_eq_coinduct[case_names in_space step]:
fixes R :: "'a \<Rightarrow> 'a stream measure \<Rightarrow> bool"
assumes x: "R x B" "x \<in> space M"
assumes R: "\<And>x B. R x B \<Longrightarrow> \<exists>B'\<in>M \<rightarrow>\<^sub>M prob_algebra (stream_space M).
(AE y in K x. R y (B' y) \<or> lim_stream y = B' y) \<and>
B = do { y \<leftarrow> K x; \<omega> \<leftarrow> B' y; return (stream_space M) (y ## \<omega>) }"
shows "lim_stream x = B"
using x
proof (coinduction arbitrary: x B rule: stream_space_coinduct[where M=M, case_names step])
case (step x B)
from R[OF \<open>R x B\<close>] obtain B' where B': "B' \<in> M \<rightarrow>\<^sub>M prob_algebra (stream_space M)"
and ae: "AE y in K x. R y (B' y) \<or> lim_stream y = B' y"
and eq: "B = K x \<bind> (\<lambda>y. B' y \<bind> (\<lambda>\<omega>. return (stream_space M) (y ## \<omega>)))"
by blast
show ?case
apply (rule bexI[of _ "K x"], rule bexI[OF _ lim_stream], rule bexI[OF _ B'])
apply (intro conjI)
subgoal
using ae AE_space by eventually_elim (insert \<open>x\<in>space M\<close>, auto simp: space_K)
subgoal
by (rule lim_stream_eq) fact
subgoal
by (rule eq)
subgoal
using K \<open>x \<in> space M\<close> by (rule measurable_space)
done
qed
lemma prob_space_lim_sequence: "x \<in> space M \<Longrightarrow> prob_space (lim_sequence x)"
using measurable_space[OF lim_sequence, of x] by (simp add: space_prob_algebra)
end
subsection \<open>Strong Markov Property for Discrete-Time Markov Processes\<close>
text \<open>The filtration adopted to streams, i.e. to the $n$-th projection.\<close>
definition stream_filtration :: "'a measure \<Rightarrow> enat \<Rightarrow> 'a stream measure"
where "stream_filtration M n = (SUP i\<in>{i::nat. i \<le> n}. vimage_algebra (streams (space M)) (\<lambda>\<omega> . \<omega> !! i) M)"
lemma measurable_stream_filtration1: "enat i \<le> n \<Longrightarrow> (\<lambda>\<omega>. \<omega> !! i) \<in> stream_filtration M n \<rightarrow>\<^sub>M M"
by (auto intro!: measurable_SUP1 measurable_vimage_algebra1 snth_in simp: stream_filtration_def)
lemma measurable_stream_filtration2:
"f \<in> space N \<rightarrow> streams (space M) \<Longrightarrow> (\<And>i. enat i \<le> n \<Longrightarrow> (\<lambda>x. f x !! i) \<in> N \<rightarrow>\<^sub>M M) \<Longrightarrow> f \<in> N \<rightarrow>\<^sub>M stream_filtration M n"
by (auto simp: stream_filtration_def enat_0
intro!: measurable_SUP2 measurable_vimage_algebra2 elim!: allE[of _ "0::nat"])
lemma space_stream_filtration: "space (stream_filtration M n) = space (stream_space M)"
by (auto simp add: space_stream_space space_Sup_eq_UN stream_filtration_def enat_0 elim!: allE[of _ 0])
lemma sets_stream_filteration_le_stream_space: "sets (stream_filtration M n) \<subseteq> sets (stream_space M)"
unfolding sets_stream_space_eq stream_filtration_def
by (intro SUP_subset_mono le_measureD2) (auto simp: space_Sup_eq_UN enat_0 elim!: allE[of _ 0])
interpretation stream_filtration: filtration "space (stream_space M)" "stream_filtration M"
proof
show "space (stream_filtration M i) = space (stream_space M)" for i
by (simp add: space_stream_filtration)
show "sets (stream_filtration M i) \<subseteq> sets (stream_filtration M j)" if "i \<le> j" for i j
proof (rule le_measureD2)
show "stream_filtration M i \<le> stream_filtration M j"
using \<open>i \<le> j\<close> unfolding stream_filtration_def by (intro SUP_subset_mono) auto
qed (simp add: space_stream_filtration)
qed
lemma measurable_stopping_time_stream:
"stopping_time (stream_filtration M) T \<Longrightarrow> T \<in> stream_space M \<rightarrow>\<^sub>M count_space UNIV"
using sets_stream_filteration_le_stream_space
by (subst measurable_cong_sets[OF refl sets_borel_eq_count_space[symmetric, where 'a=enat]])
(auto intro!: measurable_stopping_time simp: space_stream_filtration)
lemma measurable_stopping_time_All_eq_0:
assumes T: "stopping_time (stream_filtration M) T"
shows "{x\<in>space M. \<forall>\<omega>\<in>streams (space M). T (x ## \<omega>) = 0} \<in> sets M"
proof -
have "{\<omega>\<in>streams (space M). T \<omega> = 0} \<in> vimage_algebra (streams (space M)) (\<lambda>\<omega>. \<omega> !! 0) M"
using stopping_timeD[OF T, of 0] by (simp add: stream_filtration_def pred_def enat_0_iff)
then obtain A
where A: "A \<in> sets M"
and *: "{\<omega> \<in> streams (space M). T \<omega> = 0} = (\<lambda>\<omega>. \<omega> !! 0) -` A \<inter> streams (space M)"
by (auto simp: sets_vimage_algebra2 streams_shd)
have "A = {x\<in>space M. \<forall>\<omega>\<in>streams (space M). T (x ## \<omega>) = 0}"
proof safe
fix x \<omega> assume "x \<in> A" "\<omega> \<in> streams (space M)"
then have "x ## \<omega> \<in> {\<omega> \<in> streams (space M). T \<omega> = 0}"
unfolding * using A[THEN sets.sets_into_space] by auto
then show "T (x ## \<omega>) = 0" by auto
next
fix x assume "x \<in> space M" "\<forall>\<omega>\<in>streams (space M). T (x ## \<omega>) = 0 "
then have "\<forall>\<omega>\<in>streams (space M). x ## \<omega> \<in> {\<omega> \<in> streams (space M). T \<omega> = 0}"
by simp
with \<open>x\<in>space M\<close> show "x \<in> A"
unfolding * by (auto simp: streams_empty_iff)
qed (use A[THEN sets.sets_into_space] in auto)
with \<open>A \<in> sets M\<close> show ?thesis by auto
qed
lemma stopping_time_0:
assumes T: "stopping_time (stream_filtration M) T"
and x: "x \<in> space M" and \<omega>: "\<omega> \<in> streams (space M)" "T (x ## \<omega>) > 0"
and \<omega>': "\<omega>' \<in> streams (space M)"
shows "T (x ## \<omega>') > 0"
unfolding zero_less_iff_neq_zero
proof
assume "T (x ## \<omega>') = 0"
with x \<omega>' have x': "x ## \<omega>' \<in> {\<omega> \<in> streams (space M). T \<omega> = 0}"
by auto
have "{\<omega>\<in>streams (space M). T \<omega> = 0} \<in> vimage_algebra (streams (space M)) (\<lambda>\<omega>. \<omega> !! 0) M"
using stopping_timeD[OF T, of 0] by (simp add: stream_filtration_def pred_def enat_0_iff)
then obtain A
where A: "A \<in> sets M"
and *: "{\<omega> \<in> streams (space M). T \<omega> = 0} = (\<lambda>\<omega>. \<omega> !! 0) -` A \<inter> streams (space M)"
by (auto simp: sets_vimage_algebra2 streams_shd)
with x' have "x \<in> A"
by auto
with \<omega> x have "x ## \<omega> \<in> (\<lambda>\<omega>. \<omega> !! 0) -` A \<inter> streams (space M)"
by auto
with \<omega> show False
unfolding *[symmetric] by auto
qed
lemma stopping_time_epred_SCons:
assumes T: "stopping_time (stream_filtration M) T"
and x: "x \<in> space M" and \<omega>: "\<omega> \<in> streams (space M)" "T (x ## \<omega>) > 0"
shows "stopping_time (stream_filtration M) (\<lambda>\<omega>. epred (T (x ## \<omega>)))"
proof (rule stopping_timeI, rule measurable_cong[THEN iffD2])
show "\<omega> \<in> space (stream_filtration M t) \<Longrightarrow> (epred (T (x ## \<omega>)) \<le> t) = (T (x ## \<omega>) \<le> eSuc t)" for t \<omega>
by (cases "T (x ## \<omega>)" rule: enat_coexhaust)
(auto simp add: space_stream_filtration space_stream_space dest!: stopping_time_0[OF T x \<omega>])
show "Measurable.pred (stream_filtration M t) (\<lambda>w. T (x ## w) \<le> eSuc t)" for t
proof (rule measurable_compose[of "SCons x"])
show "(##) x \<in> stream_filtration M t \<rightarrow>\<^sub>M stream_filtration M (eSuc t)"
proof (intro measurable_stream_filtration2)
show "enat i \<le> eSuc t \<Longrightarrow> (\<lambda>xa. (x ## xa) !! i) \<in> stream_filtration M t \<rightarrow>\<^sub>M M" for i
using \<open>x\<in>space M\<close>
by (cases i) (auto simp: eSuc_enat[symmetric] intro!: measurable_stream_filtration1)
qed (auto simp: space_stream_filtration space_stream_space \<open>x\<in>space M\<close>)
qed (rule T[THEN stopping_timeD])
qed
context discrete_Markov_process
begin
lemma lim_stream_strong_Markov:
assumes x: "x \<in> space M" and T: "stopping_time (stream_filtration M) T"
shows "lim_stream x =
lim_stream x \<bind> (\<lambda>\<omega>. case T \<omega> of
enat i \<Rightarrow> distr (lim_stream (\<omega> !! i)) (stream_space M) (\<lambda>\<omega>'. stake (Suc i) \<omega> @- \<omega>')
| \<infinity> \<Rightarrow> return (stream_space M) \<omega>)"
(is "_ = ?L T x")
using assms
proof (coinduction arbitrary: x T rule: lim_stream_eq_coinduct)
case (step x T)
note T = \<open>stopping_time (stream_filtration M) T\<close>[THEN measurable_stopping_time_stream, measurable]
define L where "L T x = ?L T x" for T x
have L[measurable (raw)]:
"(\<lambda>(x, \<omega>). T x \<omega>) \<in> N \<Otimes>\<^sub>M stream_space M \<rightarrow>\<^sub>M count_space UNIV \<Longrightarrow>
f \<in> N \<rightarrow>\<^sub>M M \<Longrightarrow> (\<lambda>x. L (T x) (f x)) \<in> N \<rightarrow>\<^sub>M prob_algebra (stream_space M)" for f :: "'a \<Rightarrow> 'a" and N T
unfolding L_def
by (intro measurable_bind_prob_space2[OF measurable_compose[OF _ lim_stream]] measurable_case_enat
measurable_distr_prob_space2[OF measurable_compose[OF _ lim_stream]]
measurable_return_prob_space measurable_stopping_time_stream)
auto
define S where "S x = (if \<forall>\<omega>\<in>streams (space M). T (x##\<omega>) = 0 then lim_stream x else L (\<lambda>\<omega>. epred (T (x ## \<omega>))) x)" for x
then have S_eq: "\<forall>\<omega>\<in>streams (space M). T (x##\<omega>) = 0 \<Longrightarrow> S x = lim_stream x"
"\<not> (\<forall>\<omega>\<in>streams (space M). T (x##\<omega>) = 0) \<Longrightarrow> S x = L (\<lambda>\<omega>. epred (T (x ## \<omega>))) x" for x
by auto
have [measurable]: "S \<in> M \<rightarrow>\<^sub>M prob_algebra (stream_space M)"
unfolding S_def[abs_def]
by (subst measurable_If_restrict_space_iff, safe intro!: L)
(auto intro!: measurable_stopping_time_All_eq_0 step measurable_restrict_space1 lim_stream
measurable_compose[OF _ measurable_epred] measurable_compose[OF _ T]
measurable_Stream measurable_compose[OF measurable_fst]
simp: measurable_split_conv)
show ?case
unfolding L_def[symmetric]
proof (intro bexI[of _ S] conjI AE_I2)
fix y assume "y \<in> space (K x)"
then show "(\<exists>x T. y = x \<and> S y = L T x \<and> x \<in> space M \<and> stopping_time (stream_filtration M) T) \<or>
lim_stream y = S y"
using \<open>x\<in>space M\<close>
by (cases "\<forall>\<omega>\<in>streams (space M). T (y##\<omega>) = 0")
(auto simp add: S_eq space_K intro!: exI[of _ "\<lambda>\<omega>. epred (T (y ## \<omega>))"] stopping_time_epred_SCons step)
next
note \<open>x\<in>space M\<close>[simp]
have "L T x = K x \<bind>
(\<lambda>y. lim_stream y \<bind> (\<lambda>\<omega>. case T (y##\<omega>) of
enat i \<Rightarrow> distr (lim_stream ((y##\<omega>) !! i)) (stream_space M) (\<lambda>\<omega>'. stake (Suc i) (y##\<omega>) @- \<omega>')
| \<infinity> \<Rightarrow> return (stream_space M) (y##\<omega>)))" (is "_ = K x \<bind> ?L'")
unfolding L_def
apply (subst lim_stream_eq[OF \<open>x\<in>space M\<close>])
apply (subst bind_assoc[where N="stream_space M" and R="stream_space M", OF measurable_prob_algebraD measurable_prob_algebraD];
measurable)
apply (rule bind_cong[OF refl])
apply (simp add: space_K)
apply (subst bind_assoc[where N="stream_space M" and R="stream_space M", OF measurable_prob_algebraD measurable_prob_algebraD];
measurable)
apply (rule bind_cong[OF refl])
apply (simp add: space_lim_stream)
apply (subst bind_return[where N="stream_space M", OF measurable_prob_algebraD])
apply (measurable; fail) []
apply (simp add: space_stream_space)
apply rule
done
also have "\<dots> = K x \<bind> (\<lambda>y. S y \<bind> (\<lambda>\<omega>. return (stream_space M) (y ## \<omega>)))"
proof (intro bind_cong[of "K x"] refl)
fix y assume "y \<in> space (K x)"
then have [simp]: "y \<in> space M"
by (simp add: space_K)
show "?L' y = S y \<bind> (\<lambda>\<omega>. return (stream_space M) (y ## \<omega>))"
proof cases
assume "\<forall>\<omega>\<in>streams (space M). T (y##\<omega>) = 0"
with x show ?thesis
by (auto simp: S_eq space_lim_stream shift.simps[abs_def] streams_empty_iff
bind_const'[OF _ prob_space_imp_subprob_space] prob_space_lim_stream prob_space.prob_space_distr
intro!: bind_return_distr'[symmetric]
cong: bind_cong_simp)
next
assume *: "\<not> (\<forall>\<omega>\<in>streams (space M). T (y##\<omega>) = 0)"
then have T_pos: "\<omega> \<in> streams (space M) \<Longrightarrow> T (y ## \<omega>) \<noteq> 0" for \<omega>
using stopping_time_0[OF \<open>stopping_time (stream_filtration M) T\<close>, of y _ \<omega>] by auto
show ?thesis
apply (simp add: S_eq(2)[OF *] L_def)
apply (subst bind_assoc[where N="stream_space M" and R="stream_space M", OF measurable_prob_algebraD measurable_prob_algebraD];
measurable)
apply (intro bind_cong refl)
apply (auto simp: T_pos enat_0 space_lim_stream shift.simps[abs_def] diff_Suc space_stream_space
intro!: bind_return[where N="stream_space M", OF measurable_prob_algebraD, symmetric]
bind_distr_return[symmetric]
split: nat.split enat.split)
done
qed
qed
finally show "L T x = K x \<bind> (\<lambda>y. S y \<bind> (\<lambda>\<omega>. return (stream_space M) (y ## \<omega>)))" .
qed fact
qed fact
end
end
|
section\<open>Pseudo-Hoops\<close>
theory PseudoHoops
imports RightComplementedMonoid
begin
lemma drop_assumption:
"p \<Longrightarrow> True"
by simp
class pseudo_hoop_algebra = left_complemented_monoid_algebra + right_complemented_monoid_nole_algebra +
assumes left_right_impl_times: "(a l\<rightarrow> b) * a = a * (a r\<rightarrow> b)"
begin
definition
"inf_rr a b = a * (a r\<rightarrow> b)"
definition
"lesseq_r a b = (a r\<rightarrow> b = 1)"
definition
"less_r a b = (lesseq_r a b \<and> \<not> lesseq_r b a)"
end
(*
sublocale pseudo_hoop_algebra < right: right_complemented_monoid_algebra lesseq_r less_r 1 "( * )" inf_rr "(r\<rightarrow>)";
apply unfold_locales;
apply simp_all;
apply (simp add: less_r_def);
apply (simp add: inf_rr_def);
apply (rule right_impl_times, rule right_impl_ded);
by (simp add: lesseq_r_def);
*)
context pseudo_hoop_algebra begin
lemma inf_rr_inf [simp]: "inf_rr = (\<sqinter>)"
by (unfold fun_eq_iff, simp add: inf_rr_def inf_l_def left_right_impl_times)
lemma lesseq_lesseq_r: "lesseq_r a b = (a \<le> b)"
proof -
interpret A: right_complemented_monoid_algebra lesseq_r less_r 1 "(*)" inf_rr "(r\<rightarrow>)"
by (rule right_complemented_monoid_algebra)
show "lesseq_r a b = (a \<le> b)"
apply (subst le_iff_inf)
apply (subst A.dual_algebra.inf.absorb_iff1 [of a b])
apply (unfold inf_rr_inf [THEN sym])
by simp
qed
lemma [simp]: "less_r = (<)"
by (unfold fun_eq_iff, simp add: less_r_def less_le_not_le)
subclass right_complemented_monoid_algebra
apply (cut_tac right_complemented_monoid_algebra)
by simp
end
sublocale pseudo_hoop_algebra <
pseudo_hoop_dual: pseudo_hoop_algebra "\<lambda> a b . b * a" "(\<sqinter>)" "(r\<rightarrow>)" "(\<le>)" "(<)" 1 "(l\<rightarrow>)"
apply unfold_locales
apply (simp add: inf_l_def)
apply simp
apply (simp add: left_impl_times)
apply (simp add: left_impl_ded)
by (simp add: left_right_impl_times)
context pseudo_hoop_algebra begin
lemma commutative_ps: "(\<forall> a b . a * b = b * a) = ((l\<rightarrow>) = (r\<rightarrow>))"
apply (simp add: fun_eq_iff)
apply safe
apply (rule antisym)
apply (simp add: right_residual [THEN sym])
apply (subgoal_tac "x * (x l\<rightarrow> xa) = (x l\<rightarrow> xa) * x")
apply (drule drop_assumption)
apply simp
apply (simp add: left_residual)
apply simp
apply (simp add: left_residual [THEN sym])
apply (simp add: right_residual)
apply (rule antisym)
apply (simp add: left_residual)
apply (simp add: right_residual [THEN sym])
apply (simp add: left_residual)
by (simp add: right_residual [THEN sym])
lemma lemma_2_4_5: "a l\<rightarrow> b \<le> (c l\<rightarrow> a) l\<rightarrow> (c l\<rightarrow> b)"
apply (simp add: left_residual [THEN sym] mult.assoc)
apply (rule_tac y = "(a l\<rightarrow> b) * a" in order_trans)
apply (rule mult_left_mono)
by (simp_all add: left_residual)
end
context pseudo_hoop_algebra begin
lemma lemma_2_4_6: "a r\<rightarrow> b \<le> (c r\<rightarrow> a) r\<rightarrow> (c r\<rightarrow> b)"
by (rule pseudo_hoop_dual.lemma_2_4_5)
primrec
imp_power_l:: "'a => nat \<Rightarrow> 'a \<Rightarrow> 'a" ("(_) l-(_)\<rightarrow> (_)" [65,0,65] 65) where
"a l-0\<rightarrow> b = b" |
"a l-(Suc n)\<rightarrow> b = (a l\<rightarrow> (a l-n\<rightarrow> b))"
primrec
imp_power_r:: "'a => nat \<Rightarrow> 'a \<Rightarrow> 'a" ("(_) r-(_)\<rightarrow> (_)" [65,0,65] 65) where
"a r-0\<rightarrow> b = b" |
"a r-(Suc n)\<rightarrow> b = (a r\<rightarrow> (a r-n\<rightarrow> b))"
lemma lemma_2_4_7_a: "a l-n\<rightarrow> b = a ^ n l\<rightarrow> b"
apply (induct_tac n)
by (simp_all add: left_impl_ded)
lemma lemma_2_4_7_b: "a r-n\<rightarrow> b = a ^ n r\<rightarrow> b"
apply (induct_tac n)
by (simp_all add: right_impl_ded [THEN sym] power_commutes)
lemma lemma_2_5_8_a [simp]: "a * b \<le> a"
by (rule dual_algebra.H)
lemma lemma_2_5_8_b [simp]: "a * b \<le> b"
by (rule H)
lemma lemma_2_5_9_a: "a \<le> b l\<rightarrow> a"
by (simp add: left_residual [THEN sym] dual_algebra.H)
lemma lemma_2_5_9_b: "a \<le> b r\<rightarrow> a"
by (simp add: right_residual [THEN sym] H)
lemma lemma_2_5_11: "a * b \<le> a \<sqinter> b"
by simp
lemma lemma_2_5_12_a: "a \<le> b \<Longrightarrow> c l\<rightarrow> a \<le> c l\<rightarrow> b"
apply (subst left_residual [THEN sym])
apply (subst left_impl_times)
apply (rule_tac y = "(a l\<rightarrow> c) * b" in order_trans)
apply (simp add: mult_left_mono)
by (rule H)
lemma lemma_2_5_13_a: "a \<le> b \<Longrightarrow> b l\<rightarrow> c \<le> a l\<rightarrow> c"
apply (simp add: left_residual [THEN sym])
apply (rule_tac y = "(b l\<rightarrow> c) * b" in order_trans)
apply (simp add: mult_left_mono)
by (simp add: left_residual)
lemma lemma_2_5_14: "(b l\<rightarrow> c) * (a l\<rightarrow> b) \<le> a l\<rightarrow> c"
apply (simp add: left_residual [THEN sym])
apply (simp add: mult.assoc)
apply (subst left_impl_times)
apply (subst mult.assoc [THEN sym])
apply (subst left_residual)
by (rule dual_algebra.H)
lemma lemma_2_5_16: "(a l\<rightarrow> b) \<le> (b l\<rightarrow> c) r\<rightarrow> (a l\<rightarrow> c)"
apply (simp add: right_residual [THEN sym])
by (rule lemma_2_5_14)
lemma lemma_2_5_18: "(a l\<rightarrow> b) \<le> a * c l\<rightarrow> b * c"
apply (simp add: left_residual [THEN sym])
apply (subst mult.assoc [THEN sym])
apply (rule mult_right_mono)
apply (subst left_impl_times)
by (rule H)
end
context pseudo_hoop_algebra begin
lemma lemma_2_5_12_b: "a \<le> b \<Longrightarrow> c r\<rightarrow> a \<le> c r\<rightarrow> b"
by (rule pseudo_hoop_dual.lemma_2_5_12_a)
lemma lemma_2_5_13_b: "a \<le> b \<Longrightarrow> b r\<rightarrow> c \<le> a r\<rightarrow> c"
by (rule pseudo_hoop_dual.lemma_2_5_13_a)
lemma lemma_2_5_15: "(a r\<rightarrow> b) * (b r\<rightarrow> c) \<le> a r\<rightarrow> c"
by (rule pseudo_hoop_dual.lemma_2_5_14)
lemma lemma_2_5_17: "(a r\<rightarrow> b) \<le> (b r\<rightarrow> c) l\<rightarrow> (a r\<rightarrow> c)"
by (rule pseudo_hoop_dual.lemma_2_5_16)
lemma lemma_2_5_19: "(a r\<rightarrow> b) \<le> c * a r\<rightarrow> c * b"
by (rule pseudo_hoop_dual.lemma_2_5_18)
definition
"lower_bound A = {a . \<forall> x \<in> A . a \<le> x}"
definition
"infimum A = {a \<in> lower_bound A . (\<forall> x \<in> lower_bound A . x \<le> a)}"
lemma infimum_unique: "(infimum A = {x}) = (x \<in> infimum A)"
apply safe
apply simp
apply (rule antisym)
by (simp_all add: infimum_def)
lemma lemma_2_6_20:
"a \<in> infimum A \<Longrightarrow> b l\<rightarrow> a \<in> infimum (((l\<rightarrow>) b)`A)"
apply (subst infimum_def)
apply safe
apply (simp add: infimum_def lower_bound_def lemma_2_5_12_a)
by (simp add: infimum_def lower_bound_def left_residual [THEN sym])
end
context pseudo_hoop_algebra begin
lemma lemma_2_6_21:
"a \<in> infimum A \<Longrightarrow> b r\<rightarrow> a \<in> infimum (((r\<rightarrow>) b)`A)"
by (rule pseudo_hoop_dual.lemma_2_6_20)
lemma infimum_pair: "a \<in> infimum {x . x = b \<or> x = c} = (a = b \<sqinter> c)"
apply (simp add: infimum_def lower_bound_def)
apply safe
apply (rule antisym)
by simp_all
lemma lemma_2_6_20_a:
"a l\<rightarrow> (b \<sqinter> c) = (a l\<rightarrow> b) \<sqinter> (a l\<rightarrow> c)"
apply (subgoal_tac "b \<sqinter> c \<in> infimum {x . x = b \<or> x = c}")
apply (drule_tac b = a in lemma_2_6_20)
apply (case_tac "((l\<rightarrow>) a) ` {x . ((x = b) \<or> (x = c))} = {x . x = a l\<rightarrow> b \<or> x = a l\<rightarrow> c}")
apply (simp_all add: infimum_pair)
by auto
end
context pseudo_hoop_algebra begin
lemma lemma_2_6_21_a:
"a r\<rightarrow> (b \<sqinter> c) = (a r\<rightarrow> b) \<sqinter> (a r\<rightarrow> c)"
by (rule pseudo_hoop_dual.lemma_2_6_20_a)
lemma mult_mono: "a \<le> b \<Longrightarrow> c \<le> d \<Longrightarrow> a * c \<le> b * d"
apply (rule_tac y = "a * d" in order_trans)
by (simp_all add: mult_right_mono mult_left_mono)
lemma lemma_2_7_22: "(a l\<rightarrow> b) * (c l\<rightarrow> d) \<le> (a \<sqinter> c) l\<rightarrow> (b \<sqinter> d)"
apply (rule_tac y = "(a \<sqinter> c l\<rightarrow> b) * (a \<sqinter> c l\<rightarrow> d)" in order_trans)
apply (rule mult_mono)
apply (simp_all add: lemma_2_5_13_a)
apply (rule_tac y = "(a \<sqinter> c l\<rightarrow> b) \<sqinter> (a \<sqinter> c l\<rightarrow> d)" in order_trans)
apply (rule lemma_2_5_11)
by (simp add: lemma_2_6_20_a)
end
context pseudo_hoop_algebra begin
lemma lemma_2_7_23: "(a r\<rightarrow> b) * (c r\<rightarrow> d) \<le> (a \<sqinter> c) r\<rightarrow> (b \<sqinter> d)"
apply (rule_tac y = "(c \<sqinter> a) r\<rightarrow> (d \<sqinter> b)" in order_trans)
apply (rule pseudo_hoop_dual.lemma_2_7_22)
by (simp add: inf_commute)
definition
"upper_bound A = {a . \<forall> x \<in> A . x \<le> a}"
definition
"supremum A = {a \<in> upper_bound A . (\<forall> x \<in> upper_bound A . a \<le> x)}"
lemma supremum_unique:
"a \<in> supremum A \<Longrightarrow> b \<in> supremum A \<Longrightarrow> a = b"
apply (simp add: supremum_def upper_bound_def)
apply (rule antisym)
by auto
lemma lemma_2_8_i:
"a \<in> supremum A \<Longrightarrow> a l\<rightarrow> b \<in> infimum ((\<lambda> x . x l\<rightarrow> b)`A)"
apply (subst infimum_def)
apply safe
apply (simp add: supremum_def upper_bound_def lower_bound_def lemma_2_5_13_a)
apply (simp add: supremum_def upper_bound_def lower_bound_def left_residual [THEN sym])
by (simp add: right_residual)
end
context pseudo_hoop_algebra begin
lemma lemma_2_8_i1:
"a \<in> supremum A \<Longrightarrow> a r\<rightarrow> b \<in> infimum ((\<lambda> x . x r\<rightarrow> b)`A)"
by (rule pseudo_hoop_dual.lemma_2_8_i, simp)
definition
times_set :: "'a set \<Rightarrow> 'a set \<Rightarrow> 'a set" (infixl "**" 70) where
"(A ** B) = {a . \<exists> x \<in> A . \<exists> y \<in> B . a = x * y}"
lemma times_set_assoc: "A ** (B ** C) = (A ** B) ** C"
apply (simp add: times_set_def)
apply safe
apply (rule_tac x = "xa * xb" in exI)
apply safe
apply (rule_tac x = xa in bexI)
apply (rule_tac x = xb in bexI)
apply simp_all
apply (subst mult.assoc)
apply (rule_tac x = ya in bexI)
apply simp_all
apply (rule_tac x = xb in bexI)
apply simp_all
apply (rule_tac x = "ya * y" in exI)
apply (subst mult.assoc)
apply simp
by auto
primrec power_set :: "'a set \<Rightarrow> nat \<Rightarrow> 'a set" (infixr "*^" 80) where
power_set_0: "(A *^ 0) = {1}"
| power_set_Suc: "(A *^ (Suc n)) = (A ** (A *^ n))"
lemma infimum_singleton [simp]: "infimum {a} = {a}"
apply (simp add: infimum_def lower_bound_def)
by auto
lemma lemma_2_8_ii:
"a \<in> supremum A \<Longrightarrow> (a ^ n) l\<rightarrow> b \<in> infimum ((\<lambda> x . x l\<rightarrow> b)`(A *^ n))"
apply (induct_tac n)
apply simp
apply (simp add: left_impl_ded)
apply (drule_tac a = "a ^ n l\<rightarrow> b" and b = a in lemma_2_6_20)
apply (simp add: infimum_def lower_bound_def times_set_def)
apply safe
apply (drule_tac b = "y l\<rightarrow> b" in lemma_2_8_i)
apply (simp add: infimum_def lower_bound_def times_set_def left_impl_ded)
apply (rule_tac y = "a l\<rightarrow> y l\<rightarrow> b" in order_trans)
apply simp_all
apply (subgoal_tac "(\<forall>xa \<in> A *^ n. x \<le> a l\<rightarrow> xa l\<rightarrow> b)")
apply simp
apply safe
apply (drule_tac b = "xa l\<rightarrow> b" in lemma_2_8_i)
apply (simp add: infimum_def lower_bound_def)
apply safe
apply (subgoal_tac "(\<forall>xb \<in> A. x \<le> xb l\<rightarrow> xa l\<rightarrow> b)")
apply simp
apply safe
apply (subgoal_tac "x \<le> xb * xa l\<rightarrow> b")
apply (simp add: left_impl_ded)
apply (subgoal_tac "(\<exists>x \<in> A. \<exists>y \<in> A *^ n. xb * xa = x * y)")
by auto
lemma power_set_Suc2:
"A *^ (Suc n) = A *^ n ** A"
apply (induct_tac n)
apply (simp add: times_set_def)
apply simp
apply (subst times_set_assoc)
by simp
lemma power_set_add:
"A *^ (n + m) = (A *^ n) ** (A *^ m)"
apply (induct_tac m)
apply simp
apply (simp add: times_set_def)
apply simp
apply (subst times_set_assoc)
apply (subst times_set_assoc)
apply (subst power_set_Suc2 [THEN sym])
by simp
end
context pseudo_hoop_algebra begin
lemma lemma_2_8_ii1:
"a \<in> supremum A \<Longrightarrow> (a ^ n) r\<rightarrow> b \<in> infimum ((\<lambda> x . x r\<rightarrow> b)`(A *^ n))"
apply (induct_tac n)
apply simp
apply (subst power_Suc2)
apply (subst power_set_Suc2)
apply (simp add: right_impl_ded)
apply (drule_tac a = "a ^ n r\<rightarrow> b" and b = a in lemma_2_6_21)
apply (simp add: infimum_def lower_bound_def times_set_def)
apply safe
apply (drule_tac b = "xa r\<rightarrow> b" in lemma_2_8_i1)
apply (simp add: infimum_def lower_bound_def times_set_def right_impl_ded)
apply (rule_tac y = "a r\<rightarrow> xa r\<rightarrow> b" in order_trans)
apply simp_all
apply (subgoal_tac "(\<forall>xa \<in> A *^ n. x \<le> a r\<rightarrow> xa r\<rightarrow> b)")
apply simp
apply safe
apply (drule_tac b = "xa r\<rightarrow> b" in lemma_2_8_i1)
apply (simp add: infimum_def lower_bound_def)
apply safe
apply (subgoal_tac "(\<forall>xb \<in> A. x \<le> xb r\<rightarrow> xa r\<rightarrow> b)")
apply simp
apply safe
apply (subgoal_tac "x \<le> xa * xb r\<rightarrow> b")
apply (simp add: right_impl_ded)
apply (subgoal_tac "(\<exists>x \<in> A *^ n. \<exists>y \<in> A . xa * xb = x * y)")
by auto
lemma lemma_2_9_i:
"b \<in> supremum A \<Longrightarrow> a * b \<in> supremum ((*) a ` A)"
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (simp add: mult_left_mono)
by (simp add: right_residual)
lemma lemma_2_9_i1:
"b \<in> supremum A \<Longrightarrow> b * a \<in> supremum ((\<lambda> x . x * a) ` A)"
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (simp add: mult_right_mono)
by (simp add: left_residual)
lemma lemma_2_9_ii:
"b \<in> supremum A \<Longrightarrow> a \<sqinter> b \<in> supremum ((\<sqinter>) a ` A)"
apply (subst supremum_def)
apply safe
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (rule_tac y = x in order_trans)
apply simp_all
apply (subst inf_commute)
apply (subst inf_l_def)
apply (subst left_right_impl_times)
apply (frule_tac a = "(b r\<rightarrow> a)" in lemma_2_9_i1)
apply (simp add: right_residual)
apply (simp add: supremum_def upper_bound_def)
apply (simp add: right_residual)
apply safe
apply (subgoal_tac "(\<forall>xa \<in> A. b r\<rightarrow> a \<le> xa r\<rightarrow> x)")
apply simp
apply safe
apply (simp add: inf_l_def)
apply (simp add: left_right_impl_times)
apply (rule_tac y = "xa r\<rightarrow> b * (b r\<rightarrow> a)" in order_trans)
apply simp
apply (rule lemma_2_5_12_b)
apply (subst left_residual)
apply (subgoal_tac "(\<forall>xa\<in>A. xa \<le> (b r\<rightarrow> a) l\<rightarrow> x)")
apply simp
apply safe
apply (subst left_residual [THEN sym])
apply (rule_tac y = "xaa * (xaa r\<rightarrow> a)" in order_trans)
apply (rule mult_left_mono)
apply (rule lemma_2_5_13_b)
apply simp
apply (subst right_impl_times)
by simp
lemma lemma_2_10_24:
"a \<le> (a l\<rightarrow> b) r\<rightarrow> b"
by (simp add: right_residual [THEN sym] inf_l_def [THEN sym])
lemma lemma_2_10_25:
"a \<le> (a l\<rightarrow> b) r\<rightarrow> a"
by (rule lemma_2_5_9_b)
end
context pseudo_hoop_algebra begin
lemma lemma_2_10_26:
"a \<le> (a r\<rightarrow> b) l\<rightarrow> b"
by (rule pseudo_hoop_dual.lemma_2_10_24)
lemma lemma_2_10_27:
"a \<le> (a r\<rightarrow> b) l\<rightarrow> a"
by (rule lemma_2_5_9_a)
lemma lemma_2_10_28:
"b l\<rightarrow> ((a l\<rightarrow> b) r\<rightarrow> a) = b l\<rightarrow> a"
apply (rule antisym)
apply (subst left_residual [THEN sym])
apply (rule_tac y = "((a l\<rightarrow> b) r\<rightarrow> a) \<sqinter> a" in order_trans)
apply (subst inf_l_def)
apply (rule_tac y = "(((a l\<rightarrow> b) r\<rightarrow> a) l\<rightarrow> b) * ((a l\<rightarrow> b) r\<rightarrow> a)" in order_trans)
apply (subst left_impl_times)
apply simp_all
apply (rule mult_right_mono)
apply (rule_tac y = "a l\<rightarrow> b" in order_trans)
apply (rule lemma_2_5_13_a)
apply (fact lemma_2_10_25)
apply (fact lemma_2_10_26)
apply (rule lemma_2_5_12_a)
by (fact lemma_2_10_25)
end
context pseudo_hoop_algebra begin
lemma lemma_2_10_29:
"b r\<rightarrow> ((a r\<rightarrow> b) l\<rightarrow> a) = b r\<rightarrow> a"
by (rule pseudo_hoop_dual.lemma_2_10_28)
lemma lemma_2_10_30:
"((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> a = b l\<rightarrow> a"
apply (rule antisym)
apply (simp_all add: lemma_2_10_26)
apply (rule lemma_2_5_13_a)
by (rule lemma_2_10_24)
end
context pseudo_hoop_algebra begin
lemma lemma_2_10_31:
"((b r\<rightarrow> a) l\<rightarrow> a) r\<rightarrow> a = b r\<rightarrow> a"
by (rule pseudo_hoop_dual.lemma_2_10_30)
lemma lemma_2_10_32:
"(((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> b) l\<rightarrow> (b l\<rightarrow> a) = b l\<rightarrow> a"
proof -
have "((((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> b) l\<rightarrow> (b l\<rightarrow> a) = (((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> b) l\<rightarrow> (((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> a))"
by (simp add: lemma_2_10_30)
also have "\<dots> = ((((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> b) * ((b l\<rightarrow> a) r\<rightarrow> a) l\<rightarrow> a)"
by (simp add: left_impl_ded)
also have "\<dots> = (((b l\<rightarrow> a) r\<rightarrow> a) \<sqinter> b) l\<rightarrow> a"
by (simp add: inf_l_def)
also have "\<dots> = b l\<rightarrow> a" apply (subgoal_tac "((b l\<rightarrow> a) r\<rightarrow> a) \<sqinter> b = b", simp, rule antisym)
by (simp_all add: lemma_2_10_24)
finally show ?thesis .
qed
end
context pseudo_hoop_algebra begin
lemma lemma_2_10_33:
"(((b r\<rightarrow> a) l\<rightarrow> a) r\<rightarrow> b) r\<rightarrow> (b r\<rightarrow> a) = b r\<rightarrow> a"
by (rule pseudo_hoop_dual.lemma_2_10_32)
end
class pseudo_hoop_sup_algebra = pseudo_hoop_algebra + sup +
assumes
sup_comute: "a \<squnion> b = b \<squnion> a"
and sup_le [simp]: "a \<le> a \<squnion> b"
and le_sup_equiv: "(a \<le> b) = (a \<squnion> b = b)"
begin
lemma sup_le_2 [simp]:
"b \<le> a \<squnion> b"
by (subst sup_comute, simp)
lemma le_sup_equiv_r:
"(a \<squnion> b = b) = (a \<le> b)"
by (simp add: le_sup_equiv)
lemma sup_idemp [simp]:
"a \<squnion> a = a"
by (simp add: le_sup_equiv_r)
end
class pseudo_hoop_sup1_algebra = pseudo_hoop_algebra + sup +
assumes
sup_def: "a \<squnion> b = ((a l\<rightarrow> b) r\<rightarrow> b) \<sqinter> ((b l\<rightarrow> a) r\<rightarrow> a)"
begin
lemma sup_comute1: "a \<squnion> b = b \<squnion> a"
apply (simp add: sup_def)
apply (rule antisym)
by simp_all
lemma sup_le1 [simp]: "a \<le> a \<squnion> b"
by (simp add: sup_def lemma_2_10_24 lemma_2_5_9_b)
lemma le_sup_equiv1: "(a \<le> b) = (a \<squnion> b = b)"
apply safe
apply (simp add: left_lesseq)
apply (rule antisym)
apply (simp add: sup_def)
apply (simp add: sup_def)
apply (simp_all add: lemma_2_10_24)
apply (simp add: le_iff_inf)
apply (subgoal_tac "(a \<sqinter> b = a \<sqinter> (a \<squnion> b)) \<and> (a \<sqinter> (a \<squnion> b) = a)")
apply simp
apply safe
apply simp
apply (rule antisym)
apply simp
apply (drule drop_assumption)
by (simp add: sup_comute1)
subclass pseudo_hoop_sup_algebra
apply unfold_locales
apply (simp add: sup_comute1)
apply simp
by (simp add: le_sup_equiv1)
end
class pseudo_hoop_sup2_algebra = pseudo_hoop_algebra + sup +
assumes
sup_2_def: "a \<squnion> b = ((a r\<rightarrow> b) l\<rightarrow> b) \<sqinter> ((b r\<rightarrow> a) l\<rightarrow> a)"
context pseudo_hoop_sup1_algebra begin end
sublocale pseudo_hoop_sup2_algebra < sup1_dual: pseudo_hoop_sup1_algebra "(\<squnion>)" "\<lambda> a b . b * a" "(\<sqinter>)" "(r\<rightarrow>)" "(\<le>)" "(<)" 1 "(l\<rightarrow>)"
apply unfold_locales
by (simp add: sup_2_def)
context pseudo_hoop_sup2_algebra begin
lemma sup_comute_2: "a \<squnion> b = b \<squnion> a"
by (rule sup1_dual.sup_comute)
lemma sup_le2 [simp]: "a \<le> a \<squnion> b"
by (rule sup1_dual.sup_le)
lemma le_sup_equiv2: "(a \<le> b) = (a \<squnion> b = b)"
by (rule sup1_dual.le_sup_equiv)
subclass pseudo_hoop_sup_algebra
apply unfold_locales
apply (simp add: sup_comute_2)
apply simp
by (simp add: le_sup_equiv2)
end
class pseudo_hoop_lattice_a = pseudo_hoop_sup_algebra +
assumes sup_inf_le_distr: "a \<squnion> (b \<sqinter> c) \<le> (a \<squnion> b) \<sqinter> (a \<squnion> c)"
begin
lemma sup_lower_upper_bound [simp]:
"a \<le> c \<Longrightarrow> b \<le> c \<Longrightarrow> a \<squnion> b \<le> c"
apply (subst le_iff_inf)
apply (subgoal_tac "(a \<squnion> b) \<sqinter> c = (a \<squnion> b) \<sqinter> (a \<squnion> c) \<and> a \<squnion> (b \<sqinter> c) \<le> (a \<squnion> b) \<sqinter> (a \<squnion> c) \<and> a \<squnion> (b \<sqinter> c) = a \<squnion> b")
apply (rule antisym)
apply simp
apply safe
apply auto[1]
apply (simp add: le_sup_equiv)
apply (rule sup_inf_le_distr)
by (simp add: le_iff_inf)
end
sublocale pseudo_hoop_lattice_a < lattice "(\<sqinter>)" "(\<le>)" "(<)" "(\<squnion>)"
by (unfold_locales, simp_all)
class pseudo_hoop_lattice_b = pseudo_hoop_sup_algebra +
assumes le_sup_cong: "a \<le> b \<Longrightarrow> a \<squnion> c \<le> b \<squnion> c"
begin
lemma sup_lower_upper_bound_b [simp]:
"a \<le> c \<Longrightarrow> b \<le> c \<Longrightarrow> a \<squnion> b \<le> c"
proof -
assume A: "a \<le> c"
assume B: "b \<le> c"
have "a \<squnion> b \<le> c \<squnion> b" by (cut_tac A, simp add: le_sup_cong)
also have "\<dots> = b \<squnion> c" by (simp add: sup_comute)
also have "\<dots> \<le> c \<squnion> c" by (cut_tac B, rule le_sup_cong, simp)
also have "\<dots> = c" by simp
finally show ?thesis .
qed
lemma sup_inf_le_distr_b:
"a \<squnion> (b \<sqinter> c) \<le> (a \<squnion> b) \<sqinter> (a \<squnion> c)"
apply (rule sup_lower_upper_bound_b)
apply simp
apply simp
apply safe
apply (subst sup_comute)
apply (rule_tac y = "b" in order_trans)
apply simp_all
apply (rule_tac y = "c" in order_trans)
by simp_all
end
context pseudo_hoop_lattice_a begin end
sublocale pseudo_hoop_lattice_b < pseudo_hoop_lattice_a "(\<squnion>)" "(*)" "(\<sqinter>)" "(l\<rightarrow>)" "(\<le>)" "(<)" 1 "(r\<rightarrow>)"
by (unfold_locales, rule sup_inf_le_distr_b)
class pseudo_hoop_lattice = pseudo_hoop_sup_algebra +
assumes sup_assoc_1: "a \<squnion> (b \<squnion> c) = (a \<squnion> b) \<squnion> c"
begin
lemma le_sup_cong_c:
"a \<le> b \<Longrightarrow> a \<squnion> c \<le> b \<squnion> c"
proof -
assume A: "a \<le> b"
have "a \<squnion> c \<squnion> (b \<squnion> c) = a \<squnion> (c \<squnion> (b \<squnion> c))" by (simp add: sup_assoc_1)
also have "\<dots> = a \<squnion> ((b \<squnion> c) \<squnion> c)" by (simp add: sup_comute)
also have "\<dots> = a \<squnion> (b \<squnion> (c \<squnion> c))" by (simp add: sup_assoc_1 [THEN sym])
also have "\<dots> = (a \<squnion> b) \<squnion> c" by (simp add: sup_assoc_1)
also have "\<dots> = b \<squnion> c" by (cut_tac A, simp add: le_sup_equiv)
finally show ?thesis by (simp add: le_sup_equiv)
qed
end
sublocale pseudo_hoop_lattice < pseudo_hoop_lattice_b "(\<squnion>)" "(*)" "(\<sqinter>)" "(l\<rightarrow>)" "(\<le>)" "(<)" 1 "(r\<rightarrow>)"
by (unfold_locales, rule le_sup_cong_c)
sublocale pseudo_hoop_lattice < semilattice_sup "(\<squnion>)" "(\<le>)" "(<)"
by (unfold_locales, simp_all)
sublocale pseudo_hoop_lattice < lattice "(\<sqinter>)" "(\<le>)" "(<)" "(\<squnion>)"
by unfold_locales
lemma (in pseudo_hoop_lattice_a) supremum_pair [simp]:
"supremum {a, b} = {a \<squnion> b}"
apply (simp add: supremum_def upper_bound_def)
apply safe
apply simp_all
apply (rule antisym)
by simp_all
sublocale pseudo_hoop_lattice < distrib_lattice "(\<sqinter>)" "(\<le>)" "(<)" "(\<squnion>)"
apply unfold_locales
apply (rule distrib_imp1)
apply (case_tac "xa \<sqinter> (ya \<squnion> za) \<in> supremum ((\<sqinter>) xa ` {ya, za})")
apply (simp add: supremum_pair)
apply (erule notE)
apply (rule lemma_2_9_ii)
by (simp add: supremum_pair)
class bounded_semilattice_inf_top = semilattice_inf + order_top
begin
lemma inf_eq_top_iff [simp]:
"(inf x y = top) = (x = top \<and> y = top)"
by (simp add: eq_iff)
end
sublocale pseudo_hoop_algebra < bounded_semilattice_inf_top "(\<sqinter>)" "(\<le>)" "(<)" "1"
by unfold_locales simp
definition (in pseudo_hoop_algebra)
sup1::"'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "\<squnion>1" 70) where
"a \<squnion>1 b = ((a l\<rightarrow> b) r\<rightarrow> b) \<sqinter> ((b l\<rightarrow> a) r\<rightarrow> a)"
sublocale pseudo_hoop_algebra < sup1: pseudo_hoop_sup1_algebra "(\<squnion>1)" "(*)" "(\<sqinter>)" "(l\<rightarrow>)" "(\<le>)" "(<)" 1 "(r\<rightarrow>)"
apply unfold_locales
by (simp add: sup1_def)
definition (in pseudo_hoop_algebra)
sup2::"'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "\<squnion>2" 70) where
"a \<squnion>2 b = ((a r\<rightarrow> b) l\<rightarrow> b) \<sqinter> ((b r\<rightarrow> a) l\<rightarrow> a)"
sublocale pseudo_hoop_algebra < sup2: pseudo_hoop_sup2_algebra "(\<squnion>2)" "(*)" "(\<sqinter>)" "(l\<rightarrow>)" "(\<le>)" "(<)" 1 "(r\<rightarrow>)"
apply unfold_locales
by (simp add: sup2_def)
context pseudo_hoop_algebra
begin
lemma lemma_2_15_i:
"1 \<in> supremum {a, b} \<Longrightarrow> a * b = a \<sqinter> b"
apply (rule antisym)
apply (rule lemma_2_5_11)
apply (simp add: inf_l_def)
apply (subst left_impl_times)
apply (rule mult_right_mono)
apply (subst right_lesseq)
apply (subgoal_tac "a \<squnion>1 b = 1")
apply (simp add: sup1_def)
apply (rule antisym)
apply simp
by (simp add: supremum_def upper_bound_def)
lemma lemma_2_15_ii:
"1 \<in> supremum {a, b} \<Longrightarrow> a \<le> c \<Longrightarrow> b \<le> d \<Longrightarrow> 1 \<in> supremum {c, d}"
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (drule_tac x = x in spec)
apply safe
by simp_all
lemma sup_union:
"a \<in> supremum A \<Longrightarrow> b \<in> supremum B \<Longrightarrow> supremum {a, b} = supremum (A \<union> B)"
apply safe
apply (simp_all add: supremum_def upper_bound_def)
apply safe
apply auto
apply (subgoal_tac "(\<forall>x \<in> A \<union> B. x \<le> xa)")
by auto
lemma sup_singleton [simp]: "a \<in> supremum {a}"
by (simp add: supremum_def upper_bound_def)
lemma sup_union_singleton: "a \<in> supremum X \<Longrightarrow> supremum {a, b} = supremum (X \<union> {b})"
apply (rule_tac B = "{b}" in sup_union)
by simp_all
lemma sup_le_union [simp]: "a \<le> b \<Longrightarrow> supremum (A \<union> {a, b}) = supremum (A \<union> {b})"
apply (simp add: supremum_def upper_bound_def)
by auto
lemma sup_sup_union: "a \<in> supremum A \<Longrightarrow> b \<in> supremum (B \<union> {a}) \<Longrightarrow> b \<in> supremum (A \<union> B)"
apply (simp add: supremum_def upper_bound_def)
by auto
end
(*
context monoid_mult
begin
lemma "a ^ 2 = a * a"
by (simp add: power2_eq_square)
end
*)
lemma [simp]:
"n \<le> 2 ^ n"
apply (induct_tac n)
apply auto
apply (rule_tac y = "1 + 2 ^ n" in order_trans)
by auto
context pseudo_hoop_algebra
begin
lemma sup_le_union_2:
"a \<le> b \<Longrightarrow> a \<in> A \<Longrightarrow> b \<in> A \<Longrightarrow> supremum A = supremum ((A - {a}) \<union> {b})"
apply (case_tac "supremum ((A - {a , b}) \<union> {a, b}) = supremum ((A - {a, b}) \<union> {b})")
apply (case_tac "((A - {a, b}) \<union> {a, b} = A) \<and> ((A - {a, b}) \<union> {b} = (A - {a}) \<union> {b})")
apply safe[1]
apply simp
apply simp
apply (erule notE)
apply safe [1]
apply (erule notE)
apply (rule sup_le_union)
by simp
lemma lemma_2_15_iii_0:
"1 \<in> supremum {a, b} \<Longrightarrow> 1 \<in> supremum {a ^ 2, b ^ 2}"
apply (frule_tac a = a in lemma_2_9_i)
apply simp
apply (frule_tac a = a and b = b in sup_union_singleton)
apply (subgoal_tac "supremum ({a * a, a * b} \<union> {b}) = supremum ({a * a, b})")
apply simp_all
apply (frule_tac a = b in lemma_2_9_i)
apply simp
apply (drule_tac a = b and A = "{b * (a * a), b * b}" and b = 1 and B = "{a * a}" in sup_sup_union)
apply simp
apply (case_tac "{a * a, b} = {b, a * a}")
apply simp
apply auto [1]
apply simp
apply (subgoal_tac "supremum {a * a, b * (a * a), b * b} = supremum {a * a, b * b}")
apply(simp add: power2_eq_square)
apply (case_tac "b * (a * a) = b * b")
apply auto[1]
apply (cut_tac A = "{a * a, b * (a * a), b * b}" and a = "b * (a * a)" and b = "a * a" in sup_le_union_2)
apply simp
apply simp
apply simp
apply (subgoal_tac "({a * a, b * (a * a), b * b} - {b * (a * a)} \<union> {a * a}) = {a * a, b * b}")
apply simp
apply auto[1]
apply (case_tac "a * a = a * b")
apply (subgoal_tac "{b, a * a, a * b} = {a * a, b}")
apply simp
apply auto[1]
apply (cut_tac A = "{b, a * a, a * b}" and a = "a * b" and b = "b" in sup_le_union_2)
apply simp
apply simp
apply simp
apply (subgoal_tac "{b, a * a, a * b} - {a * b} \<union> {b} = {a * a, b}")
apply simp
by auto
lemma [simp]: "m \<le> n \<Longrightarrow> a ^ n \<le> a ^ m"
apply (subgoal_tac "a ^ n = (a ^ m) * (a ^ (n-m))")
apply simp
apply (cut_tac a = a and m = "m" and n = "n - m" in power_add)
by simp
lemma [simp]: "a ^ (2 ^ n) \<le> a ^ n"
by simp
lemma lemma_2_15_iii_1: "1 \<in> supremum {a, b} \<Longrightarrow> 1 \<in> supremum {a ^ (2 ^ n), b ^ (2 ^ n)}"
apply (induct_tac n)
apply auto[1]
apply (drule drop_assumption)
apply (drule lemma_2_15_iii_0)
apply (subgoal_tac "\<forall>a . (a ^ (2::nat) ^ n)\<^sup>2 = a ^ (2::nat) ^ Suc n")
apply simp
apply safe
apply (cut_tac a = aa and m = "2 ^ n" and n = 2 in power_mult)
apply auto
apply (subgoal_tac "((2::nat) ^ n * (2::nat)) = ((2::nat) * (2::nat) ^ n)")
by simp_all
lemma lemma_2_15_iii:
"1 \<in> supremum {a, b} \<Longrightarrow> 1 \<in> supremum {a ^ n, b ^ n}"
apply (drule_tac n = n in lemma_2_15_iii_1)
apply (simp add: supremum_def upper_bound_def)
apply safe
apply (drule_tac x = x in spec)
apply safe
apply (rule_tac y = "a ^ n" in order_trans)
apply simp_all
apply (rule_tac y = "b ^ n" in order_trans)
by simp_all
end
end
|
<p>
<div align="right">
Massimo Nocentini<br>
<small>
<br>April 20, 2018: cleanup, `sin` and `cos` $g$ poly
<br>November 16 and 18, 2016: `expt` and `log` $g$ poly
<br>November 9, 2016: splitting from "big" notebook
</small>
</div>
</p>
<br>
<br>
<div align="center">
<b>Abstract</b><br>
Theory of matrix functions, with applications to Catalan array $\mathcal{C}$.
</div>
```python
from sympy import *
from sympy.abc import n, i, N, x, lamda, phi, z, j, r, k, a, alpha
from commons import *
from matrix_functions import *
from sequences import *
import functions_catalog
init_printing()
```
# Catalan array $\mathcal{C}$
```python
m=8
```
```python
C = define(let=Symbol(r'\mathcal{{C}}_{{ {} }}'.format(m)),
be=Matrix(m, m, lambda n,k: (k+1)*binomial(2*n-k, n-k)/(n+1) if n > 0 else int(not k)))
C
```
```python
eigendata = spectrum(C)
eigendata
```
```python
data, eigenvals, multiplicities = eigendata.rhs
```
```python
Phi_poly = Phi_poly_ctor(deg=m-1)
Phi_poly
```
```python
Phi_polynomials = component_polynomials(eigendata, early_eigenvals_subs=True)
Phi_polynomials
```
```python
cmatrices = component_matrices(C, Phi_polynomials)
list(cmatrices.values())
```
## `power` function
```python
f_power, g_power, G_power = functions_catalog.power(eigendata, Phi_polynomials)
```
```python
C_power = G_power(C)
C_power
```
```python
define(C_power.lhs, C_power.rhs.applyfunc(factor)) # factored
```
```python
assert C_power.rhs == (C.rhs**r).applyfunc(simplify)
```
```python
inspect(C_power.rhs)
```
nature(is_ordinary=True, is_exponential=False)
```python
production_matrix(C_power.rhs).applyfunc(factor)
```
## `inverse` function
```python
f_inverse, g_inverse, G_inverse = functions_catalog.inverse(eigendata, Phi_polynomials)
```
```python
C_inverse = G_inverse(C)
C_inverse, G_inverse(C_inverse)
```
```python
inspect(C_inverse.rhs)
```
nature(is_ordinary=True, is_exponential=False)
```python
production_matrix(C_inverse.rhs)
```
```python
assert C_inverse.rhs*C.rhs == Matrix(m, m, identity_matrix())
assert C_inverse.rhs == C_power.rhs.subs({r:-1})
```
## `sqrt` function
```python
f_sqrt, g_sqrt, G_sqrt = functions_catalog.square_root(eigendata, Phi_polynomials)
```
```python
C_sqrt = G_sqrt(C)
C_sqrt
```
```python
inspect(C_sqrt.rhs)
```
nature(is_ordinary=True, is_exponential=False)
```python
production_matrix(C_sqrt.rhs)
```
```python
assert C.rhs**(S(1)/2) == C_sqrt.rhs
assert C_sqrt.rhs == C_power.rhs.subs({r:S(1)/2})
```
## `expt` function
```python
f_exp, g_exp, G_exp = functions_catalog.exp(eigendata, Phi_polynomials)
```
```python
C_exp = G_exp(C)
C_exp
```
```python
define(C_exp.lhs, C_exp.rhs.applyfunc(factor))
```
```python
C_exp1 = define(let=Subs(C_exp.lhs, alpha, 1), be=C_exp.rhs.subs({alpha:1}))
C_exp1
```
```python
inspect(C_exp.rhs)
```
nature(is_ordinary=False, is_exponential=False)
```python
inspect(C_exp1.rhs)
```
nature(is_ordinary=False, is_exponential=False)
```python
eigendata_Cexpt = spectrum(C_exp1)
eigendata_Cexpt
```
```python
Phi_polynomials_Cexpt = component_polynomials(eigendata_Cexpt, early_eigenvals_subs=True)
Phi_polynomials_Cexpt
```
## `log` function
```python
f_log, g_log, G_log = functions_catalog.log(eigendata, Phi_polynomials)
```
```python
C_log = G_log(C)
C_log
```
```python
inspect(C_log.rhs[1:,:-1])
```
nature(is_ordinary=False, is_exponential=True)
```python
production_matrix(C_log.rhs[1:,:-1])
```
```python
g_log_Cexpt = Hermite_interpolation_polynomial(f_log, eigendata_Cexpt, Phi_polynomials_Cexpt)
g_log_Cexpt
```
```python
g_log_Cexpt = g_log_Cexpt.subs(eigendata_Cexpt.rhs[1])
g_log_Cexpt
```
```python
with lift_to_matrix_function(g_log_Cexpt) as G_log_Cexpt:
CC = G_log_Cexpt(C_exp1)
CC
```
## `sin` function
```python
f_sin, g_sin, G_sin = functions_catalog.sin(eigendata, Phi_polynomials)
```
```python
C_sin = G_sin(C)
C_sin
```
```python
inspect(C_sin.rhs) # takes long to evaluate
```
## `cos` function
```python
f_cos, g_cos, G_cos = functions_catalog.cos(eigendata, Phi_polynomials)
```
```python
C_cos = G_cos(C)
C_cos
```
```python
inspect(C_sin.rhs) # takes long to evaluate
```
```python
assert (C_sin.rhs**2 + C_cos.rhs**2).applyfunc(trigsimp) == Matrix(m,m, identity_matrix())
```
---
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.
|
/-
Copyright (c) 2022 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Lean
import Std.Lean.Parser
/-! # `simp_intro` tactic -/
namespace Mathlib.Tactic
open Lean Meta Elab Tactic
/--
Main loop of the `simp_intro` tactic.
* `g`: the original goal
* `ctx`: the simp context, which is extended with local variables as we enter the binders
* `discharge?`: the discharger
* `more`: if true, we will keep introducing binders as long as we can
* `ids`: the list of binder identifiers
-/
partial def simpIntroCore (g : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge)
(more : Bool) (ids : List (TSyntax ``binderIdent)) : TermElabM (Option MVarId) := do
let done := return (← simpTargetCore g ctx discharge?).1
let (transp, var, ids') ← match ids with
| [] => if more then pure (.reducible, mkHole (← getRef), []) else return ← done
| v::ids => pure (.default, v.raw[0], ids)
let t ← withTransparency transp g.getType'
let n := if var.isIdent then var.getId else `_
let withFVar := fun (fvar, g) ↦ g.withContext do
Term.addLocalVarInfo var (mkFVar fvar)
let simpTheorems ← ctx.simpTheorems.addTheorem (.fvar fvar) (.fvar fvar)
simpIntroCore g { ctx with simpTheorems } discharge? more ids'
match t with
| .letE .. => withFVar (← g.intro n)
| .forallE (body := body) .. =>
let (fvar, g) ← g.intro n
if body.hasLooseBVars then withFVar (fvar, g) else
match (← simpLocalDecl g fvar ctx discharge?).1 with
| none =>
g.withContext <| Term.addLocalVarInfo var (mkFVar fvar)
return none
| some g' => withFVar g'
| _ =>
if more && ids.isEmpty then done else
throwErrorAt var "simp_intro failed to introduce {var}\n{g}"
open Parser.Tactic
/--
The `simp_intro` tactic is a combination of `simp` and `intro`: it will simplify the types of
variables as it introduces them and uses the new variables to simplify later arguments
and the goal.
* `simp_intro x y z` introduces variables named `x y z`
* `simp_intro x y z ..` introduces variables named `x y z` and then keeps introducing `_` binders
* `simp_intro (config := cfg) (discharger := tac) x y .. only [h₁, h₂]`:
`simp_intro` takes the same options as `simp` (see `simp`)
```
example : x + 0 = y → x = z := by
simp_intro h
-- h: x = y ⊢ y = z
sorry
```
-/
elab "simp_intro" cfg:(config)? disch:(discharger)?
ids:(ppSpace colGt binderIdent)* more:" .."? only:(&" only")? args:(simpArgs)? : tactic => do
let args := args.map fun args ↦ ⟨args.raw[1].getArgs⟩
let stx ← `(tactic| simp $(cfg)? $(disch)? $[only%$only]? $[[$args,*]]?)
let { ctx, dischargeWrapper } ← withMainContext <| mkSimpContext stx (eraseLocal := false)
dischargeWrapper.with fun discharge? ↦ do
let g ← getMainGoal
g.checkNotAssigned `simp_intro
g.withContext do
let g? ← simpIntroCore g ctx discharge? more.isSome ids.toList
replaceMainGoal <| if let some g := g? then [g] else []
|
(*
Author: Christian Sternagel <[email protected]>
Author: René Thiemann <[email protected]>
License: LGPL
*)
section \<open>First-Order Terms\<close>
theory Term
imports Main
begin
datatype (funs_term : 'f, vars_term : 'v) "term" =
is_Var: Var (the_Var: 'v) |
Fun 'f (args : "('f, 'v) term list")
where
"args (Var _) = []"
abbreviation "is_Fun t \<equiv> \<not> is_Var t"
lemma is_VarE [elim]:
"is_Var t \<Longrightarrow> (\<And>x. t = Var x \<Longrightarrow> P) \<Longrightarrow> P"
by (cases t) auto
lemma is_FunE [elim]:
"is_Fun t \<Longrightarrow> (\<And>f ts. t = Fun f ts \<Longrightarrow> P) \<Longrightarrow> P"
by (cases t) auto
lemma inj_on_Var[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"inj_on Var A"
by (rule inj_onI) simp
lemma member_image_the_Var_image_subst: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes is_var_\<sigma>: "\<forall>x. is_Var (\<sigma> x)"
shows "x \<in> the_Var ` \<sigma> ` V \<longleftrightarrow> Var x \<in> \<sigma> ` V"
using is_var_\<sigma> image_iff
by (metis (no_types, opaque_lifting) term.collapse(1) term.sel(1))
lemma image_the_Var_image_subst_renaming_eq: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes is_var_\<sigma>: "\<forall>x. is_Var (\<rho> x)"
shows "the_Var ` \<rho> ` V = (\<Union>x \<in> V. vars_term (\<rho> x))"
proof (rule Set.equalityI; rule Set.subsetI)
from is_var_\<sigma> show "\<And>x. x \<in> the_Var ` \<rho> ` V \<Longrightarrow> x \<in> (\<Union>x\<in>V. vars_term (\<rho> x))"
using term.set_sel(3) by force
next
from is_var_\<sigma> show "\<And>x. x \<in> (\<Union>x\<in>V. vars_term (\<rho> x)) \<Longrightarrow> x \<in> the_Var ` \<rho> ` V"
by (smt (verit, best) Term.term.simps(17) UN_iff image_eqI singletonD term.collapse(1))
qed
text \<open>Reorient equations of the form @{term "Var x = t"} and @{term "Fun f ss = t"} to facilitate
simplification.\<close>
setup \<open>
Reorient_Proc.add
(fn Const (@{const_name Var}, _) $ _ => true | _ => false)
#> Reorient_Proc.add
(fn Const (@{const_name Fun}, _) $ _ $ _ => true | _ => false)
\<close>
simproc_setup reorient_Var ("Var x = t") = Reorient_Proc.proc
simproc_setup reorient_Fun ("Fun f ss = t") = Reorient_Proc.proc
text \<open>The \emph{root symbol} of a term is defined by:\<close>
fun root :: "('f, 'v) term \<Rightarrow> ('f \<times> nat) option"
where
"root (Var x) = None" |
"root (Fun f ts) = Some (f, length ts)"
lemma finite_vars_term [simp]:
"finite (vars_term t)"
by (induct t) simp_all
lemma finite_Union_vars_term:
"finite (\<Union>t \<in> set ts. vars_term t)"
by auto
text \<open>A substitution is a mapping \<open>\<sigma>\<close> from variables to terms. We call a substitution that
alters the type of variables a generalized substitution, since it does not have all properties
that are expected of (standard) substitutions (e.g., there is no empty substitution).\<close>
type_synonym ('f, 'v, 'w) gsubst = "'v \<Rightarrow> ('f, 'w) term"
type_synonym ('f, 'v) subst = "('f, 'v, 'v) gsubst"
fun subst_apply_term :: "('f, 'v) term \<Rightarrow> ('f, 'v, 'w) gsubst \<Rightarrow> ('f, 'w) term" (infixl "\<cdot>" 67)
where
"Var x \<cdot> \<sigma> = \<sigma> x"
| "Fun f ss \<cdot> \<sigma> = Fun f (map (\<lambda>t. t \<cdot> \<sigma>) ss)"
definition
subst_compose :: "('f, 'u, 'v) gsubst \<Rightarrow> ('f, 'v, 'w) gsubst \<Rightarrow> ('f, 'u, 'w) gsubst"
(infixl "\<circ>\<^sub>s" 75)
where
"\<sigma> \<circ>\<^sub>s \<tau> = (\<lambda>x. (\<sigma> x) \<cdot> \<tau>)"
lemma subst_subst_compose [simp]:
"t \<cdot> (\<sigma> \<circ>\<^sub>s \<tau>) = t \<cdot> \<sigma> \<cdot> \<tau>"
by (induct t \<sigma> rule: subst_apply_term.induct) (simp_all add: subst_compose_def)
lemma subst_compose_assoc:
"\<sigma> \<circ>\<^sub>s \<tau> \<circ>\<^sub>s \<mu> = \<sigma> \<circ>\<^sub>s (\<tau> \<circ>\<^sub>s \<mu>)"
proof (rule ext)
fix x show "(\<sigma> \<circ>\<^sub>s \<tau> \<circ>\<^sub>s \<mu>) x = (\<sigma> \<circ>\<^sub>s (\<tau> \<circ>\<^sub>s \<mu>)) x"
proof -
have "(\<sigma> \<circ>\<^sub>s \<tau> \<circ>\<^sub>s \<mu>) x = \<sigma>(x) \<cdot> \<tau> \<cdot> \<mu>" by (simp add: subst_compose_def)
also have "\<dots> = \<sigma>(x) \<cdot> (\<tau> \<circ>\<^sub>s \<mu>)" by simp
finally show ?thesis by (simp add: subst_compose_def)
qed
qed
lemma subst_apply_term_empty [simp]:
"t \<cdot> Var = t"
proof (induct t)
case (Fun f ts)
from map_ext [rule_format, of ts _ id, OF Fun] show ?case by simp
qed simp
interpretation subst_monoid_mult: monoid_mult "Var" "(\<circ>\<^sub>s)"
by (unfold_locales) (simp add: subst_compose_assoc, simp_all add: subst_compose_def)
lemma term_subst_eq:
assumes "\<And>x. x \<in> vars_term t \<Longrightarrow> \<sigma> x = \<tau> x"
shows "t \<cdot> \<sigma> = t \<cdot> \<tau>"
using assms by (induct t) (auto)
lemma term_subst_eq_rev:
"t \<cdot> \<sigma> = t \<cdot> \<tau> \<Longrightarrow> \<forall>x \<in> vars_term t. \<sigma> x = \<tau> x"
by (induct t) simp_all
lemma term_subst_eq_conv:
"t \<cdot> \<sigma> = t \<cdot> \<tau> \<longleftrightarrow> (\<forall>x \<in> vars_term t. \<sigma> x = \<tau> x)"
using term_subst_eq [of t \<sigma> \<tau>] and term_subst_eq_rev [of t \<sigma> \<tau>] by auto
lemma subst_term_eqI:
assumes "(\<And>t. t \<cdot> \<sigma> = t \<cdot> \<tau>)"
shows "\<sigma> = \<tau>"
using assms [of "Var x" for x] by (intro ext) simp
definition subst_domain :: "('f, 'v) subst \<Rightarrow> 'v set"
where
"subst_domain \<sigma> = {x. \<sigma> x \<noteq> Var x}"
fun subst_range :: "('f, 'v) subst \<Rightarrow> ('f, 'v) term set"
where
"subst_range \<sigma> = \<sigma> ` subst_domain \<sigma>"
text \<open>The variables introduced by a substitution.\<close>
definition range_vars :: "('f, 'v) subst \<Rightarrow> 'v set"
where
"range_vars \<sigma> = \<Union>(vars_term ` subst_range \<sigma>)"
lemma mem_range_varsI: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes "\<sigma> x = Var y" and "x \<noteq> y"
shows "y \<in> range_vars \<sigma>"
unfolding range_vars_def UN_iff
proof (rule bexI[of _ "Var y"])
show "y \<in> vars_term (Var y)"
by simp
next
from assms show "Var y \<in> subst_range \<sigma>"
by (simp_all add: subst_domain_def)
qed
lemma subst_domain_Var [simp]:
"subst_domain Var = {}"
by (simp add: subst_domain_def)
lemma subst_range_Var[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"subst_range Var = {}"
by simp
lemma range_vars_Var[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"range_vars Var = {}"
by (simp add: range_vars_def)
lemma subst_apply_term_ident: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"vars_term t \<inter> subst_domain \<sigma> = {} \<Longrightarrow> t \<cdot> \<sigma> = t"
proof (induction t)
case (Var x)
thus ?case
by (simp add: subst_domain_def)
next
case (Fun f ts)
thus ?case
by (auto intro: list.map_ident_strong)
qed
lemma vars_term_subst_apply_term: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"vars_term (t \<cdot> \<sigma>) = (\<Union>x \<in> vars_term t. vars_term (\<sigma> x))"
by (induction t) (auto simp add: insert_Diff_if subst_domain_def)
corollary vars_term_subst_apply_term_subset: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"vars_term (t \<cdot> \<sigma>) \<subseteq> vars_term t - subst_domain \<sigma> \<union> range_vars \<sigma>"
unfolding vars_term_subst_apply_term
proof (induction t)
case (Var x)
show ?case
by (cases "\<sigma> x = Var x") (auto simp add: range_vars_def subst_domain_def)
next
case (Fun f xs)
thus ?case by auto
qed
definition is_renaming :: "('f, 'v) subst \<Rightarrow> bool"
where
"is_renaming \<sigma> \<longleftrightarrow> (\<forall>x. is_Var (\<sigma> x)) \<and> inj_on \<sigma> (subst_domain \<sigma>)"
lemma inv_renaming_sound: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes is_var_\<rho>: "\<forall>x. is_Var (\<rho> x)" and "inj \<rho>"
shows "\<rho> \<circ>\<^sub>s (Var \<circ> (inv (the_Var \<circ> \<rho>))) = Var"
proof -
define \<rho>' where "\<rho>' = the_Var \<circ> \<rho>"
have \<rho>_def: "\<rho> = Var \<circ> \<rho>'"
unfolding \<rho>'_def using is_var_\<rho> by auto
from is_var_\<rho> \<open>inj \<rho>\<close> have "inj \<rho>'"
unfolding inj_def \<rho>_def comp_def by fast
hence "inv \<rho>' \<circ> \<rho>' = id"
using inv_o_cancel[of \<rho>'] by simp
hence "Var \<circ> (inv \<rho>' \<circ> \<rho>') = Var"
by simp
hence "\<forall>x. (Var \<circ> (inv \<rho>' \<circ> \<rho>')) x = Var x"
by metis
hence "\<forall>x. ((Var \<circ> \<rho>') \<circ>\<^sub>s (Var \<circ> (inv \<rho>'))) x = Var x"
unfolding subst_compose_def by auto
thus "\<rho> \<circ>\<^sub>s (Var \<circ> (inv \<rho>')) = Var"
using \<rho>_def by auto
qed
lemma ex_inverse_of_renaming: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes "\<forall>x. is_Var (\<rho> x)" and "inj \<rho>"
shows "\<exists>\<tau>. \<rho> \<circ>\<^sub>s \<tau> = Var"
using inv_renaming_sound[OF assms] by blast
lemma vars_term_subst:
"vars_term (t \<cdot> \<sigma>) = \<Union>(vars_term ` \<sigma> ` vars_term t)"
by (induct t) simp_all
lemma range_varsE [elim]:
assumes "x \<in> range_vars \<sigma>"
and "\<And>t. x \<in> vars_term t \<Longrightarrow> t \<in> subst_range \<sigma> \<Longrightarrow> P"
shows "P"
using assms by (auto simp: range_vars_def)
lemma range_vars_subst_compose_subset:
"range_vars (\<sigma> \<circ>\<^sub>s \<tau>) \<subseteq> (range_vars \<sigma> - subst_domain \<tau>) \<union> range_vars \<tau>" (is "?L \<subseteq> ?R")
proof
fix x
assume "x \<in> ?L"
then obtain y where "y \<in> subst_domain (\<sigma> \<circ>\<^sub>s \<tau>)"
and "x \<in> vars_term ((\<sigma> \<circ>\<^sub>s \<tau>) y)" by (auto simp: range_vars_def)
then show "x \<in> ?R"
proof (cases)
assume "y \<in> subst_domain \<sigma>" and "x \<in> vars_term ((\<sigma> \<circ>\<^sub>s \<tau>) y)"
moreover then obtain v where "v \<in> vars_term (\<sigma> y)"
and "x \<in> vars_term (\<tau> v)" by (auto simp: subst_compose_def vars_term_subst)
ultimately show ?thesis
by (cases "v \<in> subst_domain \<tau>") (auto simp: range_vars_def subst_domain_def)
qed (auto simp: range_vars_def subst_compose_def subst_domain_def)
qed
definition "subst x t = Var (x := t)"
lemma subst_simps [simp]:
"subst x t x = t"
"subst x (Var x) = Var"
by (auto simp: subst_def)
lemma subst_subst_domain [simp]:
"subst_domain (subst x t) = (if t = Var x then {} else {x})"
proof -
{ fix y
have "y \<in> {y. subst x t y \<noteq> Var y} \<longleftrightarrow> y \<in> (if t = Var x then {} else {x})"
by (cases "x = y", auto simp: subst_def) }
then show ?thesis by (simp add: subst_domain_def)
qed
lemma subst_subst_range [simp]:
"subst_range (subst x t) = (if t = Var x then {} else {t})"
by (cases "t = Var x") (auto simp: subst_domain_def subst_def)
lemma subst_apply_left_idemp [simp]:
assumes "\<sigma> x = t \<cdot> \<sigma>"
shows "s \<cdot> subst x t \<cdot> \<sigma> = s \<cdot> \<sigma>"
using assms by (induct s) (auto simp: subst_def)
lemma subst_compose_left_idemp [simp]:
assumes "\<sigma> x = t \<cdot> \<sigma>"
shows "subst x t \<circ>\<^sub>s \<sigma> = \<sigma>"
by (rule subst_term_eqI) (simp add: assms)
lemma subst_ident [simp]:
assumes "x \<notin> vars_term t"
shows "t \<cdot> subst x u = t"
proof -
have "t \<cdot> subst x u = t \<cdot> Var"
by (rule term_subst_eq) (auto simp: assms subst_def)
then show ?thesis by simp
qed
lemma subst_self_idemp [simp]:
"x \<notin> vars_term t \<Longrightarrow> subst x t \<circ>\<^sub>s subst x t = subst x t"
by (metis subst_simps(1) subst_compose_left_idemp subst_ident)
type_synonym ('f, 'v) terms = "('f, 'v) term set"
text \<open>Applying a substitution to every term of a given set.\<close>
abbreviation
subst_apply_set :: "('f, 'v) terms \<Rightarrow> ('f, 'v, 'w) gsubst \<Rightarrow> ('f, 'w) terms" (infixl "\<cdot>\<^sub>s\<^sub>e\<^sub>t" 60)
where
"T \<cdot>\<^sub>s\<^sub>e\<^sub>t \<sigma> \<equiv> (\<lambda>t. t \<cdot> \<sigma>) ` T"
text \<open>Composition of substitutions\<close>
lemma subst_compose: "(\<sigma> \<circ>\<^sub>s \<tau>) x = \<sigma> x \<cdot> \<tau>" by (auto simp: subst_compose_def)
lemmas subst_subst = subst_subst_compose [symmetric]
lemma subst_apply_eq_Var:
assumes "s \<cdot> \<sigma> = Var x"
obtains y where "s = Var y" and "\<sigma> y = Var x"
using assms by (induct s) auto
lemma subst_domain_subst_compose:
"subst_domain (\<sigma> \<circ>\<^sub>s \<tau>) =
(subst_domain \<sigma> - {x. \<exists>y. \<sigma> x = Var y \<and> \<tau> y = Var x}) \<union>
(subst_domain \<tau> - subst_domain \<sigma>)"
by (auto simp: subst_domain_def subst_compose_def elim: subst_apply_eq_Var)
text \<open>A substitution is idempotent iff the variables in its range are disjoint from its domain.
(See also "Term Rewriting and All That" \<^cite>\<open>\<open>Lemma 4.5.7\<close> in "AllThat"\<close>.)\<close>
lemma subst_idemp_iff:
"\<sigma> \<circ>\<^sub>s \<sigma> = \<sigma> \<longleftrightarrow> subst_domain \<sigma> \<inter> range_vars \<sigma> = {}"
proof
assume "\<sigma> \<circ>\<^sub>s \<sigma> = \<sigma>"
then have "\<And>x. \<sigma> x \<cdot> \<sigma> = \<sigma> x \<cdot> Var" by simp (metis subst_compose_def)
then have *: "\<And>x. \<forall>y\<in>vars_term (\<sigma> x). \<sigma> y = Var y"
unfolding term_subst_eq_conv by simp
{ fix x y
assume "\<sigma> x \<noteq> Var x" and "x \<in> vars_term (\<sigma> y)"
with * [of y] have False by simp }
then show "subst_domain \<sigma> \<inter> range_vars \<sigma> = {}"
by (auto simp: subst_domain_def range_vars_def)
next
assume "subst_domain \<sigma> \<inter> range_vars \<sigma> = {}"
then have *: "\<And>x y. \<sigma> x = Var x \<or> \<sigma> y = Var y \<or> x \<notin> vars_term (\<sigma> y)"
by (auto simp: subst_domain_def range_vars_def)
have "\<And>x. \<forall>y\<in>vars_term (\<sigma> x). \<sigma> y = Var y"
proof
fix x y
assume "y \<in> vars_term (\<sigma> x)"
with * [of y x] show "\<sigma> y = Var y" by auto
qed
then show "\<sigma> \<circ>\<^sub>s \<sigma> = \<sigma>"
by (simp add: subst_compose_def term_subst_eq_conv [symmetric])
qed
lemma subst_compose_apply_eq_apply_lhs: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes
"range_vars \<sigma> \<inter> subst_domain \<delta> = {}"
"x \<notin> subst_domain \<delta>"
shows "(\<sigma> \<circ>\<^sub>s \<delta>) x = \<sigma> x"
proof (cases "\<sigma> x")
case (Var y)
show ?thesis
proof (cases "x = y")
case True
with Var have \<open>\<sigma> x = Var x\<close>
by simp
moreover from \<open>x \<notin> subst_domain \<delta>\<close> have "\<delta> x = Var x"
by (simp add: disjoint_iff subst_domain_def)
ultimately show ?thesis
by (simp add: subst_compose_def)
next
case False
have "y \<in> range_vars \<sigma>"
unfolding range_vars_def UN_iff
proof (rule bexI)
show "y \<in> vars_term (Var y)"
by simp
next
from Var False show "Var y \<in> subst_range \<sigma>"
by (simp_all add: subst_domain_def)
qed
hence "y \<notin> subst_domain \<delta>"
using \<open>range_vars \<sigma> \<inter> subst_domain \<delta> = {}\<close>
by (simp add: disjoint_iff)
with Var show ?thesis
unfolding subst_compose_def
by (simp add: subst_domain_def)
qed
next
case (Fun f ys)
hence "Fun f ys \<in> subst_range \<sigma> \<or> (\<forall>y\<in>set ys. y \<in> subst_range \<sigma>)"
using subst_domain_def by fastforce
hence "\<forall>x \<in> vars_term (Fun f ys). x \<in> range_vars \<sigma>"
by (metis UN_I range_vars_def term.distinct(1) term.sel(4) term.set_cases(2))
hence "Fun f ys \<cdot> \<delta> = Fun f ys \<cdot> Var"
unfolding term_subst_eq_conv
using \<open>range_vars \<sigma> \<inter> subst_domain \<delta> = {}\<close>
by (simp add: disjoint_iff subst_domain_def)
hence "Fun f ys \<cdot> \<delta> = Fun f ys"
by simp
with Fun show ?thesis
by (simp add: subst_compose_def)
qed
lemma subst_apply_term_subst_apply_term_eq_subst_apply_term_lhs: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes "range_vars \<sigma> \<inter> subst_domain \<delta> = {}" and "vars_term t \<inter> subst_domain \<delta> = {}"
shows "t \<cdot> \<sigma> \<cdot> \<delta> = t \<cdot> \<sigma>"
proof -
from assms have "\<And>x. x \<in> vars_term t \<Longrightarrow> (\<sigma> \<circ>\<^sub>s \<delta>) x = \<sigma> x"
using subst_compose_apply_eq_apply_lhs by fastforce
hence "t \<cdot> \<sigma> \<circ>\<^sub>s \<delta> = t \<cdot> \<sigma>"
using term_subst_eq_conv[of t "\<sigma> \<circ>\<^sub>s \<delta>" \<sigma>] by metis
thus ?thesis
by simp
qed
fun num_funs :: "('f, 'v) term \<Rightarrow> nat"
where
"num_funs (Var x) = 0" |
"num_funs (Fun f ts) = Suc (sum_list (map num_funs ts))"
lemma num_funs_0:
assumes "num_funs t = 0"
obtains x where "t = Var x"
using assms by (induct t) auto
lemma num_funs_subst:
"num_funs (t \<cdot> \<sigma>) \<ge> num_funs t"
by (induct t) (simp_all, metis comp_apply sum_list_mono)
lemma sum_list_map_num_funs_subst:
assumes "sum_list (map (num_funs \<circ> (\<lambda>t. t \<cdot> \<sigma>)) ts) = sum_list (map num_funs ts)"
shows "\<forall>i < length ts. num_funs (ts ! i \<cdot> \<sigma>) = num_funs (ts ! i)"
using assms
proof (induct ts)
case (Cons t ts)
then have "num_funs (t \<cdot> \<sigma>) + sum_list (map (num_funs \<circ> (\<lambda>t. t \<cdot> \<sigma>)) ts)
= num_funs t + sum_list (map num_funs ts)" by (simp add: o_def)
moreover have "num_funs (t \<cdot> \<sigma>) \<ge> num_funs t" by (metis num_funs_subst)
moreover have "sum_list (map (num_funs \<circ> (\<lambda>t. t \<cdot> \<sigma>)) ts) \<ge> sum_list (map num_funs ts)"
using num_funs_subst [of _ \<sigma>] by (induct ts) (auto intro: add_mono)
ultimately show ?case using Cons by (auto) (case_tac i, auto)
qed simp
lemma is_Fun_num_funs_less:
assumes "x \<in> vars_term t" and "is_Fun t"
shows "num_funs (\<sigma> x) < num_funs (t \<cdot> \<sigma>)"
using assms
proof (induct t)
case (Fun f ts)
then obtain u where u: "u \<in> set ts" "x \<in> vars_term u" by auto
then have "num_funs (u \<cdot> \<sigma>) \<le> sum_list (map (num_funs \<circ> (\<lambda>t. t \<cdot> \<sigma>)) ts)"
by (intro member_le_sum_list) simp
moreover have "num_funs (\<sigma> x) \<le> num_funs (u \<cdot> \<sigma>)"
using Fun.hyps [OF u] and u by (cases u; simp)
ultimately show ?case by simp
qed simp
lemma finite_subst_domain_subst:
"finite (subst_domain (subst x y))"
by simp
lemma subst_domain_compose:
"subst_domain (\<sigma> \<circ>\<^sub>s \<tau>) \<subseteq> subst_domain \<sigma> \<union> subst_domain \<tau>"
by (auto simp: subst_domain_def subst_compose_def)
lemma vars_term_disjoint_imp_unifier:
fixes \<sigma> :: "('f, 'v, 'w) gsubst"
assumes "vars_term s \<inter> vars_term t = {}"
and "s \<cdot> \<sigma> = t \<cdot> \<tau>"
shows "\<exists>\<mu> :: ('f, 'v, 'w) gsubst. s \<cdot> \<mu> = t \<cdot> \<mu>"
proof -
let ?\<mu> = "\<lambda>x. if x \<in> vars_term s then \<sigma> x else \<tau> x"
have "s \<cdot> \<sigma> = s \<cdot> ?\<mu>"
unfolding term_subst_eq_conv
by (induct s) (simp_all)
moreover have "t \<cdot> \<tau> = t \<cdot> ?\<mu>"
using assms(1)
unfolding term_subst_eq_conv
by (induct s arbitrary: t) (auto)
ultimately have "s \<cdot> ?\<mu> = t \<cdot> ?\<mu>" using assms(2) by simp
then show ?thesis by blast
qed
lemma vars_term_subset_subst_eq:
assumes "vars_term t \<subseteq> vars_term s"
and "s \<cdot> \<sigma> = s \<cdot> \<tau>"
shows "t \<cdot> \<sigma> = t \<cdot> \<tau>"
using assms by (induct t) (induct s, auto)
subsection \<open>Restrict the Domain of a Substitution\<close>
definition restrict_subst_domain where \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"restrict_subst_domain V \<sigma> x \<equiv> (if x \<in> V then \<sigma> x else Var x)"
lemma restrict_subst_domain_empty[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"restrict_subst_domain {} \<sigma> = Var"
unfolding restrict_subst_domain_def by auto
lemma restrict_subst_domain_Var[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"restrict_subst_domain V Var = Var"
unfolding restrict_subst_domain_def by auto
lemma subst_domain_restrict_subst_domain[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"subst_domain (restrict_subst_domain V \<sigma>) = V \<inter> subst_domain \<sigma>"
unfolding restrict_subst_domain_def subst_domain_def by auto
lemma subst_apply_term_restrict_subst_domain: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"vars_term t \<subseteq> V \<Longrightarrow> t \<cdot> restrict_subst_domain V \<sigma> = t \<cdot> \<sigma>"
by (rule term_subst_eq) (simp add: restrict_subst_domain_def subsetD)
subsection \<open>Rename the Domain of a Substitution\<close>
definition rename_subst_domain where \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"rename_subst_domain \<rho> \<sigma> x =
(if Var x \<in> \<rho> ` subst_domain \<sigma> then
\<sigma> (the_inv \<rho> (Var x))
else
Var x)"
lemma rename_subst_domain_Var_lhs[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"rename_subst_domain Var \<sigma> = \<sigma>"
by (rule ext) (simp add: rename_subst_domain_def inj_image_mem_iff the_inv_f_f subst_domain_def)
lemma rename_subst_domain_Var_rhs[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"rename_subst_domain \<rho> Var = Var"
by (rule ext) (simp add: rename_subst_domain_def)
lemma subst_domain_rename_subst_domain_subset: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes is_var_\<rho>: "\<forall>x. is_Var (\<rho> x)"
shows "subst_domain (rename_subst_domain \<rho> \<sigma>) \<subseteq> the_Var ` \<rho> ` subst_domain \<sigma>"
by (auto simp add: subst_domain_def rename_subst_domain_def
member_image_the_Var_image_subst[OF is_var_\<rho>])
lemma subst_range_rename_subst_domain_subset: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes "inj \<rho>"
shows "subst_range (rename_subst_domain \<rho> \<sigma>) \<subseteq> subst_range \<sigma>"
proof (intro Set.equalityI Set.subsetI)
fix t assume "t \<in> subst_range (rename_subst_domain \<rho> \<sigma>)"
then obtain x where
t_def: "t = rename_subst_domain \<rho> \<sigma> x" and
"rename_subst_domain \<rho> \<sigma> x \<noteq> Var x"
by (auto simp: image_iff subst_domain_def)
show "t \<in> subst_range \<sigma>"
proof (cases \<open>Var x \<in> \<rho> ` subst_domain \<sigma>\<close>)
case True
then obtain x' where "\<rho> x' = Var x" and "x' \<in> subst_domain \<sigma>"
by auto
then show ?thesis
using the_inv_f_f[OF \<open>inj \<rho>\<close>, of x']
by (simp add: t_def rename_subst_domain_def)
next
case False
hence False
using \<open>rename_subst_domain \<rho> \<sigma> x \<noteq> Var x\<close>
by (simp add: t_def rename_subst_domain_def)
thus ?thesis ..
qed
qed
lemma range_vars_rename_subst_domain_subset: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes "inj \<rho>"
shows "range_vars (rename_subst_domain \<rho> \<sigma>) \<subseteq> range_vars \<sigma>"
unfolding range_vars_def
using subst_range_rename_subst_domain_subset[OF \<open>inj \<rho>\<close>]
by (metis Union_mono image_mono)
lemma renaming_cancels_rename_subst_domain: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
assumes is_var_\<rho>: "\<forall>x. is_Var (\<rho> x)" and "inj \<rho>" and vars_t: "vars_term t \<subseteq> subst_domain \<sigma>"
shows "t \<cdot> \<rho> \<cdot> rename_subst_domain \<rho> \<sigma> = t \<cdot> \<sigma>"
unfolding subst_subst
proof (intro term_subst_eq ballI)
fix x assume "x \<in> vars_term t"
with vars_t have x_in: "x \<in> subst_domain \<sigma>"
by blast
obtain x' where \<rho>_x: "\<rho> x = Var x'"
using is_var_\<rho> by (meson is_Var_def)
with x_in have x'_in: "Var x' \<in> \<rho> ` subst_domain \<sigma>"
by (metis image_eqI)
have "(\<rho> \<circ>\<^sub>s rename_subst_domain \<rho> \<sigma>) x = \<rho> x \<cdot> rename_subst_domain \<rho> \<sigma>"
by (simp add: subst_compose_def)
also have "\<dots> = rename_subst_domain \<rho> \<sigma> x'"
using \<rho>_x by simp
also have "\<dots> = \<sigma> (the_inv \<rho> (Var x'))"
by (simp add: rename_subst_domain_def if_P[OF x'_in])
also have "\<dots> = \<sigma> (the_inv \<rho> (\<rho> x))"
by (simp add: \<rho>_x)
also have "\<dots> = \<sigma> x"
using \<open>inj \<rho>\<close> by (simp add: the_inv_f_f)
finally show "(\<rho> \<circ>\<^sub>s rename_subst_domain \<rho> \<sigma>) x = \<sigma> x"
by simp
qed
subsection \<open>Rename the Domain and Range of a Substitution\<close>
definition rename_subst_domain_range where \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"rename_subst_domain_range \<rho> \<sigma> x =
(if Var x \<in> \<rho> ` subst_domain \<sigma> then
((Var o the_inv \<rho>) \<circ>\<^sub>s \<sigma> \<circ>\<^sub>s \<rho>) (Var x)
else
Var x)"
lemma rename_subst_domain_range_Var_lhs[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"rename_subst_domain_range Var \<sigma> = \<sigma>"
by (rule ext) (simp add: rename_subst_domain_range_def inj_image_mem_iff the_inv_f_f
subst_domain_def subst_compose_def)
lemma rename_subst_domain_range_Var_rhs[simp]: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
"rename_subst_domain_range \<rho> Var = Var"
by (rule ext) (simp add: rename_subst_domain_range_def)
lemma subst_compose_renaming_rename_subst_domain_range: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
fixes \<sigma> \<rho> :: "('f, 'v) subst"
assumes is_var_\<rho>: "\<forall>x. is_Var (\<rho> x)" and "inj \<rho>"
shows "\<rho> \<circ>\<^sub>s rename_subst_domain_range \<rho> \<sigma> = \<sigma> \<circ>\<^sub>s \<rho>"
proof (rule ext)
fix x
from is_var_\<rho> obtain x' where "\<rho> x = Var x'"
by (meson is_Var_def is_renaming_def)
with \<open>inj \<rho>\<close> have inv_\<rho>_x': "the_inv \<rho> (Var x') = x"
by (metis the_inv_f_f)
show "(\<rho> \<circ>\<^sub>s rename_subst_domain_range \<rho> \<sigma>) x = (\<sigma> \<circ>\<^sub>s \<rho>) x"
proof (cases "x \<in> subst_domain \<sigma>")
case True
hence "Var x' \<in> \<rho> ` subst_domain \<sigma>"
using \<open>\<rho> x = Var x'\<close> by (metis imageI)
thus ?thesis
by (simp add: \<open>\<rho> x = Var x'\<close> rename_subst_domain_range_def subst_compose_def inv_\<rho>_x')
next
case False
hence "Var x' \<notin> \<rho> ` subst_domain \<sigma>"
proof (rule contrapos_nn)
assume "Var x' \<in> \<rho> ` subst_domain \<sigma>"
hence "\<rho> x \<in> \<rho> ` subst_domain \<sigma>"
unfolding \<open>\<rho> x = Var x'\<close> .
thus "x \<in> subst_domain \<sigma>"
unfolding inj_image_mem_iff[OF \<open>inj \<rho>\<close>] .
qed
with False \<open>\<rho> x = Var x'\<close> show ?thesis
by (simp add: subst_compose_def subst_domain_def rename_subst_domain_range_def)
qed
qed
corollary subst_apply_term_renaming_rename_subst_domain_range: \<^marker>\<open>contributor \<open>Martin Desharnais\<close>\<close>
\<comment> \<open>This might be easier to find with @{command find_theorems}.\<close>
fixes t :: "('f, 'v) term" and \<sigma> \<rho> :: "('f, 'v) subst"
assumes is_var_\<rho>: "\<forall>x. is_Var (\<rho> x)" and "inj \<rho>"
shows "t \<cdot> \<rho> \<cdot> rename_subst_domain_range \<rho> \<sigma> = t \<cdot> \<sigma> \<cdot> \<rho>"
unfolding subst_subst
unfolding subst_compose_renaming_rename_subst_domain_range[OF assms]
by (rule refl)
end
|
import Mathlib
/-!
# Formal Calculus
We introduce formal structures for integration and differentiation. Properties should be added to make these mathematically sound. But correctness can be ensured temporarily by making sure individual definitions are correct.
## Formal Integrals
-/
/--
Integrability of `f`, i.e., given an interval `[a, b]`, we can compute the integral of `f` over that interval. Additivity over intervals is also required.
-/
class Integrable (f: ℝ → ℝ) where
integral (a b : ℝ) : ℝ
interval_union (a b c : ℝ) :
integral a c = integral a b + integral b c
/-- The integral of a function, with the typeclass derived -/
def integral (f: ℝ → ℝ)[int : Integrable f]
(a b : ℝ ) :=
int.integral a b
/-- The integral over a single point is zero, proved as an illustration. -/
theorem integral_point(f: ℝ → ℝ)[int : Integrable f]
(a : ℝ ) : integral f a a = 0 := by
unfold integral
have l := int.interval_union a a a
simp at l
assumption
/-!
As an exercise, prove that flip ends of an interval gives the negative of the integral.
-/
/-!
## Formal Derivatives
We define so called __one-jets__ as a value and a derivative at a point. A differentiable function has values a one-jet at each point.
-/
/--
A _one-jet_ is a value and a derivative at a point.
-/
structure OneJet where
value : ℝ
derivative : ℝ
/--
A differentiable function is a function that has a one-jet at each point.
-/
structure SmoothFunction where
jet: ℝ → OneJet
/--
Derivative of a smooth function, i.e., the derivative of the one-jet at a point.
-/
def SmoothFunction.derivative (f: SmoothFunction) : ℝ → ℝ :=
fun x ↦ f.jet (x) |>.derivative
/--
The value of a smooth function, i.e., the value of the one-jet at a point.
-/
def SmoothFunction.value (f: SmoothFunction) : ℝ → ℝ :=
fun x ↦ f.jet (x) |>.value
/--
Integrable functions can be obtained from smooth functions via the fundamental theorem of calculus.
-/
instance fundThm (f: SmoothFunction) :
Integrable (f.derivative) where
integral (a b) := f.value b - f.value a
interval_union (a b c) := by
simp [integral]
/-!
## Constructions of smooth functions
To use the above we need to construct a few smooth functions
-/
namespace SmoothFunction
/--
Constant functions as smooth functions.
-/
def constant (c : ℝ) : SmoothFunction :=
⟨fun _ ↦ ⟨c, 0⟩⟩
/--
Sum of smooth functions.
-/
def sum (f g : SmoothFunction) : SmoothFunction :=
⟨fun x ↦ ⟨f.value x + g.value x, f.derivative x + g.derivative x⟩⟩
/--
Product of smooth functions using Liebnitz rule.
-/
def prod (f g : SmoothFunction) : SmoothFunction :=
⟨fun x ↦ ⟨f.value x * g.value x, f.derivative x * g.value x + f.value x * g.derivative x⟩⟩
/--
Product of a scalar and a smooth function.
-/
def scalarProd (c : ℝ) (f : SmoothFunction) : SmoothFunction :=
⟨fun x ↦ ⟨c * f.value x, c * f.derivative x⟩⟩
/-- Addition operation on smooth functions -/
instance : Add SmoothFunction := ⟨sum⟩
/-- Multiplication operation on smooth functions -/
instance : Mul SmoothFunction := ⟨prod⟩
/-- Scalar multiplication for smooth functions -/
instance : SMul ℝ SmoothFunction := ⟨scalarProd⟩
/-!
This gives polynomial functions as a special case. As an exercise, prove that smooth functions form a Ring (indeed an Algebra over ℝ).
We will define some polynomials as smooth functions as an example.
-/
/-- The coordinate function -/
def x : SmoothFunction := ⟨fun x ↦ ⟨x, 1⟩⟩
/-- The power function for a smooth function (automatic if ring is proved) -/
def pow (f: SmoothFunction): ℕ → SmoothFunction
| 0 => constant 1
| n + 1 => f * (pow f n)
instance : HPow SmoothFunction ℕ SmoothFunction := ⟨pow⟩
instance : Coe ℝ SmoothFunction := ⟨constant⟩
/-- A polynomial. We can have cleaner notation but the goal is to illustrate the construction -/
def poly := (2 : ℝ) • x + (3 : ℝ) • x^3 + (7: ℝ)
end SmoothFunction
|
#ifndef QDM_CONFIG_H
#define QDM_CONFIG_H 1
#include <gsl/gsl_vector.h>
typedef struct {
unsigned long int rng_seed;
int acc_check;
int burn_discovery;
int iter_discovery;
int burn_analysis;
int iter_analysis;
int knot_try;
int spline_df;
int thin;
gsl_vector *months;
gsl_vector *knots;
gsl_vector *tau_highs;
gsl_vector *tau_lows;
double theta_min;
double theta_tune_sd;
double xi_high;
double xi_low;
double xi_prior_mean;
double xi_prior_var;
double xi_tune_sd;
double bound;
int debug;
int tau_table;
} qdm_config;
int
qdm_config_read(
qdm_config **config,
const char *file_path,
const char *group_path
);
void
qdm_config_fwrite(
FILE *f,
const qdm_config *cfg
);
#endif /* QDM_CONFIG_H */
|
include("../src/PyEnum_test.jl")
using .PyEnum
@pyenum Colors::String begin
RED="RED"
GREEN="GREEN"
BLUE="BLUE"
end
@pyenum Cor begin
NOT_RED=1
NOT_GREEN=2
NOT_BLUE=3
end
# For comparison
@enum WorkingColors begin
TRUE_RED
TRUE_GREEN
TRUE_BLUE
end
function show()
color_map = Dict(Colors.RED => "1", Colors.GREEN => "2", Colors.BLUE => "3")
a = Colors.GREEN
if a == Colors.GREEN
println(join(["green"], " "));
else
println(join(["Not green"], " "));
end
println(join([length(color_map)], " "));
end
function main()
show();
end
main()
|
[STATEMENT]
lemma set_mset_eqvt [eqvt]:
shows "p \<bullet> (set_mset M) = set_mset (p \<bullet> M)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. p \<bullet> set_mset M = set_mset (p \<bullet> M)
[PROOF STEP]
by (induct M) (simp_all add: insert_eqvt empty_eqvt) |
/-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import for_mathlib.dold_kan.homotopies
import tactic.ring_exp
/-!
# Study of face maps for the Dold-Kan correspondence
TODO (@joelriou) continue adding the various files referenced below
In this file, we obtain the technical lemmas that are used in the file
`projections.lean` in order to get basic properties of the endomorphisms
`P q : K[X] ⟶ K[X]` with respect to face maps (see `homotopies.lean` for the
role of these endomorphisms in the overall strategy of proof).
The main lemma in this file is `higher_faces_vanish.induction`. It is based
on two technical lemmas `higher_faces_vanish.comp_Hσ_eq` and
`higher_faces_vanish.comp_Hσ_eq_zero`.
-/
open nat
open category_theory
open category_theory.limits
open category_theory.category
open category_theory.preadditive
open category_theory.simplicial_object
open_locale simplicial dold_kan
namespace algebraic_topology
namespace dold_kan
variables {C : Type*} [category C] [preadditive C]
variables {X : simplicial_object C}
/-- A morphism `φ : Y ⟶ X _[n+1]` satisfies `higher_faces_vanish q φ`
when the compositions `φ ≫ X.δ j` are `0` for `j ≥ max 1 (n+2-q)`. When `q ≤ n+1`,
it basically means that the composition `φ ≫ X.δ j` are `0` for the `q` highest
possible values of a nonzero `j`. Otherwise, when `q ≥ n+2`, all the compositions
`φ ≫ X.δ j` for nonzero `j` vanish. See also the lemma `comp_P_eq_self_iff` in
`projections.lean` which states that `higher_faces_vanish q φ` is equivalent to
the identity `φ ≫ (P q).f (n+1) = φ`. -/
def higher_faces_vanish {Y : C} {n : ℕ} (q : ℕ) (φ : Y ⟶ X _[n+1]) : Prop :=
∀ (j : fin (n+1)), (n+1 ≤ (j : ℕ) + q) → φ ≫ X.δ j.succ = 0
namespace higher_faces_vanish
@[reassoc]
lemma comp_δ_eq_zero {Y : C} {n : ℕ} {q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) (j : fin (n+2)) (hj₁ : j ≠ 0) (hj₂ : n+2 ≤ (j : ℕ) + q) :
φ ≫ X.δ j = 0 :=
begin
obtain ⟨i, hi⟩ := fin.eq_succ_of_ne_zero hj₁,
subst hi,
apply v i,
rw [← @nat.add_le_add_iff_right 1, add_assoc],
simpa only [fin.coe_succ, add_assoc, add_comm 1] using hj₂,
end
lemma of_succ {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish (q+1) φ) : higher_faces_vanish q φ :=
λ j hj, v j (by simpa only [← add_assoc] using le_add_right hj)
lemma of_comp {Y Z : C} {q n : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) (f : Z ⟶ Y) :
higher_faces_vanish q (f ≫ φ) := λ j hj,
by rw [assoc, v j hj, comp_zero]
lemma comp_Hσ_eq {Y : C} {n a q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) (hnaq : n=a+q) : φ ≫ (Hσ q).f (n+1) =
- φ ≫ X.δ ⟨a+1, nat.succ_lt_succ (nat.lt_succ_iff.mpr (nat.le.intro hnaq.symm))⟩ ≫
X.σ ⟨a, nat.lt_succ_iff.mpr (nat.le.intro hnaq.symm)⟩ :=
begin
have hnaq_shift : Π d : ℕ, n+d=(a+d)+q,
{ intro d, rw [add_assoc, add_comm d, ← add_assoc, hnaq], },
rw [Hσ, homotopy.null_homotopic_map'_f (c_mk (n+2) (n+1) rfl) (c_mk (n+1) n rfl),
hσ'_eq hnaq (c_mk (n+1) n rfl), hσ'_eq (hnaq_shift 1) (c_mk (n+2) (n+1) rfl)],
simp only [alternating_face_map_complex.obj_d_eq, eq_to_hom_refl,
comp_id, comp_sum, sum_comp, comp_add],
simp only [comp_zsmul, zsmul_comp, ← assoc, ← mul_zsmul],
/- cleaning up the first sum -/
rw [← fin.sum_congr' _ (hnaq_shift 2).symm, fin.sum_trunc], swap,
{ rintro ⟨k, hk⟩,
suffices : φ ≫ X.δ (⟨a+2+k, by linarith⟩ : fin (n+2)) = 0,
{ simp only [this, fin.nat_add_mk, fin.cast_mk, zero_comp, smul_zero], },
convert v ⟨a+k+1, by linarith⟩ (by { rw fin.coe_mk, linarith, }),
rw [nat.succ_eq_add_one],
linarith, },
/- cleaning up the second sum -/
rw [← fin.sum_congr' _ (hnaq_shift 3).symm, @fin.sum_trunc _ _ (a+3)], swap,
{ rintros ⟨k, hk⟩,
rw [assoc, X.δ_comp_σ_of_gt', v.comp_δ_eq_zero_assoc, zero_comp, zsmul_zero],
{ intro h,
rw [fin.pred_eq_iff_eq_succ, fin.ext_iff] at h,
dsimp at h,
linarith, },
{ dsimp,
simp only [fin.coe_pred, fin.coe_mk, succ_add_sub_one],
linarith, },
{ dsimp,
linarith, }, },
/- leaving out three specific terms -/
conv_lhs { congr, skip, rw [fin.sum_univ_cast_succ, fin.sum_univ_cast_succ], },
rw fin.sum_univ_cast_succ,
simp only [fin.last, fin.cast_le_mk, fin.coe_cast, fin.cast_mk,
fin.coe_cast_le, fin.coe_mk, fin.cast_succ_mk, fin.coe_cast_succ],
/- the purpose of the following `simplif` is to create three subgoals in order
to finish the proof -/
have simplif : ∀ (a b c d e f : Y ⟶ X _[n+1]), b=f → d+e=0 → c+a=0 → a+b+(c+d+e) = f,
{ intros a b c d e f h1 h2 h3,
rw [add_assoc c d e, h2, add_zero, add_comm a b, add_assoc,
add_comm a c, h3, add_zero, h1], },
apply simplif,
{ /- b=f -/
rw [← pow_add, odd.neg_one_pow, neg_smul, one_zsmul],
use a,
linarith, },
{ /- d+e = 0 -/
rw [assoc, assoc, X.δ_comp_σ_self' (fin.cast_succ_mk _ _ _).symm,
X.δ_comp_σ_succ' (fin.succ_mk _ _ _).symm],
simp only [comp_id, pow_add _ (a+1) 1, pow_one, mul_neg, mul_one, neg_smul,
add_right_neg], },
{ /- c+a = 0 -/
rw ← finset.sum_add_distrib,
apply finset.sum_eq_zero,
rintros ⟨i, hi⟩ h₀,
have hia : (⟨i, by linarith⟩ : fin (n+2)) ≤ fin.cast_succ (⟨a, by linarith⟩ : fin (n+1)) :=
by simpa only [fin.le_iff_coe_le_coe, fin.coe_mk, fin.cast_succ_mk, ← lt_succ_iff] using hi,
simp only [fin.coe_mk, fin.cast_le_mk, fin.cast_succ_mk, fin.succ_mk, assoc, fin.cast_mk,
← δ_comp_σ_of_le X hia, add_eq_zero_iff_eq_neg, ← neg_zsmul],
congr,
ring_exp, },
end
lemma comp_Hσ_eq_zero {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) (hqn : n<q) : φ ≫ (Hσ q).f (n+1) = 0 :=
begin
simp only [Hσ, homotopy.null_homotopic_map'_f (c_mk (n+2) (n+1) rfl) (c_mk (n+1) n rfl)],
rw [hσ'_eq_zero hqn (c_mk (n+1) n rfl), comp_zero, zero_add],
by_cases hqn' : n+1<q,
{ rw [hσ'_eq_zero hqn' (c_mk (n+2) (n+1) rfl), zero_comp, comp_zero], },
{ simp only [hσ'_eq (show n+1=0+q, by linarith) (c_mk (n+2) (n+1) rfl),
pow_zero, fin.mk_zero, one_zsmul, eq_to_hom_refl, comp_id,
comp_sum, alternating_face_map_complex.obj_d_eq],
rw [← fin.sum_congr' _ (show 2+(n+1)=n+1+2, by linarith), fin.sum_trunc],
{ simp only [fin.sum_univ_cast_succ, fin.sum_univ_zero, zero_add, fin.last,
fin.cast_le_mk, fin.cast_mk, fin.cast_succ_mk],
simp only [fin.mk_zero, fin.coe_zero, pow_zero, one_zsmul, fin.mk_one,
fin.coe_one, pow_one, neg_smul, comp_neg],
erw [δ_comp_σ_self, δ_comp_σ_succ, add_right_neg], },
{ intro j,
rw [comp_zsmul, comp_zsmul, δ_comp_σ_of_gt', v.comp_δ_eq_zero_assoc, zero_comp, zsmul_zero],
{ intro h,
rw [fin.pred_eq_iff_eq_succ, fin.ext_iff] at h,
dsimp at h,
linarith, },
{ dsimp,
simp only [fin.cast_nat_add, fin.coe_pred, fin.coe_add_nat, add_succ_sub_one],
linarith, },
{ rw fin.lt_iff_coe_lt_coe,
dsimp,
linarith, }, }, },
end
lemma induction {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) : higher_faces_vanish (q+1) (φ ≫ (𝟙 _ + Hσ q).f (n+1)) :=
begin
intros j hj₁,
dsimp,
simp only [comp_add, add_comp, comp_id],
-- when n < q, the result follows immediately from the assumption
by_cases hqn : n<q,
{ rw [v.comp_Hσ_eq_zero hqn, zero_comp, add_zero, v j (by linarith)], },
-- we now assume that n≥q, and write n=a+q
cases nat.le.dest (not_lt.mp hqn) with a ha,
rw [v.comp_Hσ_eq (show n=a+q, by linarith), neg_comp, add_neg_eq_zero, assoc, assoc],
cases n with m hm,
-- the boundary case n=0
{ simpa only [nat.eq_zero_of_add_eq_zero_left ha, fin.eq_zero j,
fin.mk_zero, fin.mk_one, δ_comp_σ_succ, comp_id], },
-- in the other case, we need to write n as m+1
-- then, we first consider the particular case j = a
by_cases hj₂ : a = (j : ℕ),
{ simp only [hj₂, fin.eta, δ_comp_σ_succ, comp_id],
congr,
ext,
simp only [fin.coe_succ, fin.coe_mk], },
-- now, we assume j ≠ a (i.e. a < j)
have haj : a<j := (ne.le_iff_lt hj₂).mp (by linarith),
have hj₃ := j.is_lt,
have ham : a≤m,
{ by_contradiction,
rw [not_le, ← nat.succ_le_iff] at h,
linarith, },
rw [X.δ_comp_σ_of_gt', j.pred_succ], swap,
{ rw fin.lt_iff_coe_lt_coe,
simpa only [fin.coe_mk, fin.coe_succ, add_lt_add_iff_right] using haj, },
obtain (ham' | ham'') := ham.lt_or_eq,
{ -- case where `a<m`
rw ← X.δ_comp_δ''_assoc, swap,
{ rw fin.le_iff_coe_le_coe,
dsimp,
linarith, },
simp only [← assoc, v j (by linarith), zero_comp], },
{ -- in the last case, a=m, q=1 and j=a+1
rw X.δ_comp_δ_self'_assoc, swap,
{ ext,
dsimp,
have hq : q = 1 := by rw [← add_left_inj a, ha, ham'', add_comm],
linarith, },
simp only [← assoc, v j (by linarith), zero_comp], },
end
@[reassoc]
lemma d_eq {Y : C} (n : ℕ) {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish (n+1) φ) :
φ ≫ K[X].d (n+1) n = φ ≫ X.δ 0 :=
begin
simp only [alternating_face_map_complex.obj_d_eq, comp_sum],
rw [finset.sum_eq_single (0 : fin (n+2)), fin.coe_zero, pow_zero, one_zsmul],
{ intros b h hb,
rw [preadditive.comp_zsmul, ← fin.succ_pred b hb, v, zsmul_zero],
linarith, },
{ intro h,
exfalso,
exact h (finset.mem_univ _), },
end
end higher_faces_vanish
end dold_kan
end algebraic_topology
|
Formal statement is: lemma open_Inter [continuous_intros, intro]: "finite S \<Longrightarrow> \<forall>T\<in>S. open T \<Longrightarrow> open (\<Inter>S)" Informal statement is: If $S$ is a finite set of open sets, then $\bigcap S$ is open. |
import tactic -- hide
/-
If we know `P`, and we also know `P → Q`, we can deduce `Q`.
This is called "Modus Ponens" by logicians.
-/
/- Lemma
If $P$ is true and $P \implies Q$ is true, then $Q$ is true.
-/
lemma Modus_Ponens (P Q : Prop) : P → (P → Q) → Q :=
begin
intros hP hPQ,
apply hPQ,
exact hP,
end |
function cleanup(obj)
% remove temporary files created by prepare
%
% cleanup(obj)
%
% Inputs:
% obj MOcovMFileCollection instance
%
% Notes:
% - this function should be called after coverage has been determined.
%
% See also: rewrite_mfiles, prepare
notify(obj.monitor,'Cleanup');
if ~isempty(obj.orig_path)
notify(obj.monitor,'','Resetting path');
path(obj.orig_path);
end
if ~isempty(obj.temp_dir)
msg=sprintf('Removing temporary files in %s',obj.temp_dir);
notify(obj.monitor,'',msg);
if mocov_util_platform_is_octave()
% GNU Octave requires, by default, confirmation when using
% rmdir. The state of confirm_recursive_rmdir is stored,
% and set back to its original value when leaving this
% function.
confirm_val=confirm_recursive_rmdir(false);
cleaner=onCleanup(@()confirm_recursive_rmdir(confirm_val));
end
rmdir(obj.temp_dir,'s');
end
|
[GOAL]
x : ℝ
n_large : 512 ≤ x
⊢ x * (2 * x) ^ sqrt (2 * x) * 4 ^ (2 * x / 3) ≤ 4 ^ x
[PROOFSTEP]
let f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
⊢ x * (2 * x) ^ sqrt (2 * x) * 4 ^ (2 * x / 3) ≤ 4 ^ x
[PROOFSTEP]
have hf' : ∀ x, 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3) := fun x h =>
div_pos (mul_pos h (rpow_pos_of_pos (mul_pos two_pos h) _)) (rpow_pos_of_pos four_pos _)
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
⊢ x * (2 * x) ^ sqrt (2 * x) * 4 ^ (2 * x / 3) ≤ 4 ^ x
[PROOFSTEP]
have hf : ∀ x, 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)) :=
by
intro x h5
have h6 := mul_pos (zero_lt_two' ℝ) h5
have h7 := rpow_pos_of_pos h6 (sqrt (2 * x))
rw [log_div (mul_pos h5 h7).ne' (rpow_pos_of_pos four_pos _).ne', log_mul h5.ne' h7.ne', log_rpow h6,
log_rpow zero_lt_four, ← mul_div_right_comm, ← mul_div, mul_comm x]
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
⊢ ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
[PROOFSTEP]
intro x h5
[GOAL]
x✝ : ℝ
n_large : 512 ≤ x✝
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
x : ℝ
h5 : 0 < x
⊢ f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
[PROOFSTEP]
have h6 := mul_pos (zero_lt_two' ℝ) h5
[GOAL]
x✝ : ℝ
n_large : 512 ≤ x✝
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
x : ℝ
h5 : 0 < x
h6 : 0 < 2 * x
⊢ f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
[PROOFSTEP]
have h7 := rpow_pos_of_pos h6 (sqrt (2 * x))
[GOAL]
x✝ : ℝ
n_large : 512 ≤ x✝
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
x : ℝ
h5 : 0 < x
h6 : 0 < 2 * x
h7 : 0 < (2 * x) ^ sqrt (2 * x)
⊢ f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
[PROOFSTEP]
rw [log_div (mul_pos h5 h7).ne' (rpow_pos_of_pos four_pos _).ne', log_mul h5.ne' h7.ne', log_rpow h6,
log_rpow zero_lt_four, ← mul_div_right_comm, ← mul_div, mul_comm x]
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
⊢ x * (2 * x) ^ sqrt (2 * x) * 4 ^ (2 * x / 3) ≤ 4 ^ x
[PROOFSTEP]
have h5 : 0 < x := lt_of_lt_of_le (by norm_num1) n_large
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
⊢ 0 < 512
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ x * (2 * x) ^ sqrt (2 * x) * 4 ^ (2 * x / 3) ≤ 4 ^ x
[PROOFSTEP]
rw [← div_le_one (rpow_pos_of_pos four_pos x), ← div_div_eq_mul_div, ← rpow_sub four_pos, ← mul_div 2 x,
mul_div_left_comm, ← mul_one_sub, (by norm_num1 : (1 : ℝ) - 2 / 3 = 1 / 3), mul_one_div, ← log_nonpos_iff (hf' x h5),
← hf x h5]
-- porting note: the proof was rewritten, because it was too slow
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ 1 - 2 / 3 = 1 / 3
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ f x ≤ 0
[PROOFSTEP]
have h : ConcaveOn ℝ (Set.Ioi 0.5) f := by
apply ConcaveOn.sub
apply ConcaveOn.add
exact strictConcaveOn_log_Ioi.concaveOn.subset (Set.Ioi_subset_Ioi (by norm_num)) (convex_Ioi 0.5)
convert ((strictConcaveOn_sqrt_mul_log_Ioi.concaveOn.comp_linearMap ((2 : ℝ) • LinearMap.id))) using 1
· ext x
simp only [Set.mem_Ioi, Set.mem_preimage, LinearMap.smul_apply, LinearMap.id_coe, id_eq, smul_eq_mul]
rw [← mul_lt_mul_left (two_pos)]
norm_num1
rfl
apply ConvexOn.smul
refine div_nonneg (log_nonneg (by norm_num1)) (by norm_num1)
exact convexOn_id (convex_Ioi (0.5 : ℝ))
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConcaveOn ℝ (Set.Ioi 0.5) f
[PROOFSTEP]
apply ConcaveOn.sub
[GOAL]
case hf
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConcaveOn ℝ (Set.Ioi 0.5) fun x => log x + sqrt (2 * x) * log (2 * x)
case hg
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConvexOn ℝ (Set.Ioi 0.5) fun x => log 4 / 3 * x
[PROOFSTEP]
apply ConcaveOn.add
[GOAL]
case hf.hf
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConcaveOn ℝ (Set.Ioi 0.5) fun x => log x
case hf.hg
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConcaveOn ℝ (Set.Ioi 0.5) fun x => sqrt (2 * x) * log (2 * x)
case hg
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConvexOn ℝ (Set.Ioi 0.5) fun x => log 4 / 3 * x
[PROOFSTEP]
exact strictConcaveOn_log_Ioi.concaveOn.subset (Set.Ioi_subset_Ioi (by norm_num)) (convex_Ioi 0.5)
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ 0 ≤ 0.5
[PROOFSTEP]
norm_num
[GOAL]
case hf.hg
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConcaveOn ℝ (Set.Ioi 0.5) fun x => sqrt (2 * x) * log (2 * x)
case hg
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConvexOn ℝ (Set.Ioi 0.5) fun x => log 4 / 3 * x
[PROOFSTEP]
convert ((strictConcaveOn_sqrt_mul_log_Ioi.concaveOn.comp_linearMap ((2 : ℝ) • LinearMap.id))) using 1
[GOAL]
case h.e'_9
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ Set.Ioi 0.5 = ↑(2 • LinearMap.id) ⁻¹' Set.Ioi 1
[PROOFSTEP]
ext x
[GOAL]
case h.e'_9.h
x✝ : ℝ
n_large : 512 ≤ x✝
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x✝
x : ℝ
⊢ x ∈ Set.Ioi 0.5 ↔ x ∈ ↑(2 • LinearMap.id) ⁻¹' Set.Ioi 1
[PROOFSTEP]
simp only [Set.mem_Ioi, Set.mem_preimage, LinearMap.smul_apply, LinearMap.id_coe, id_eq, smul_eq_mul]
[GOAL]
case h.e'_9.h
x✝ : ℝ
n_large : 512 ≤ x✝
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x✝
x : ℝ
⊢ OfScientific.ofScientific 5 true 1 < x ↔ 1 < 2 * x
[PROOFSTEP]
rw [← mul_lt_mul_left (two_pos)]
[GOAL]
case h.e'_9.h
x✝ : ℝ
n_large : 512 ≤ x✝
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x✝
x : ℝ
⊢ 2 * OfScientific.ofScientific 5 true 1 < 2 * x ↔ 1 < 2 * x
[PROOFSTEP]
norm_num1
[GOAL]
case h.e'_9.h
x✝ : ℝ
n_large : 512 ≤ x✝
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x✝
x : ℝ
⊢ 1 < 2 * x ↔ 1 < 2 * x
[PROOFSTEP]
rfl
[GOAL]
case hg
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConvexOn ℝ (Set.Ioi 0.5) fun x => log 4 / 3 * x
[PROOFSTEP]
apply ConvexOn.smul
[GOAL]
case hg.hc
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ 0 ≤ log 4 / 3
case hg.hf
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConvexOn ℝ (Set.Ioi 0.5) fun x => x
[PROOFSTEP]
refine div_nonneg (log_nonneg (by norm_num1)) (by norm_num1)
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ 1 ≤ 4
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ 0 ≤ 3
[PROOFSTEP]
norm_num1
[GOAL]
case hg.hf
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
⊢ ConvexOn ℝ (Set.Ioi 0.5) fun x => x
[PROOFSTEP]
exact convexOn_id (convex_Ioi (0.5 : ℝ))
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ f x ≤ 0
[PROOFSTEP]
suffices ∃ x1 x2, 0.5 < x1 ∧ x1 < x2 ∧ x2 ≤ x ∧ 0 ≤ f x1 ∧ f x2 ≤ 0
by
obtain ⟨x1, x2, h1, h2, h0, h3, h4⟩ := this
exact (h.right_le_of_le_left'' h1 ((h1.trans h2).trans_le h0) h2 h0 (h4.trans h3)).trans h4
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : ∃ x1 x2, 0.5 < x1 ∧ x1 < x2 ∧ x2 ≤ x ∧ 0 ≤ f x1 ∧ f x2 ≤ 0
⊢ f x ≤ 0
[PROOFSTEP]
obtain ⟨x1, x2, h1, h2, h0, h3, h4⟩ := this
[GOAL]
case intro.intro.intro.intro.intro.intro
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
x1 x2 : ℝ
h1 : 0.5 < x1
h2 : x1 < x2
h0 : x2 ≤ x
h3 : 0 ≤ f x1
h4 : f x2 ≤ 0
⊢ f x ≤ 0
[PROOFSTEP]
exact (h.right_le_of_le_left'' h1 ((h1.trans h2).trans_le h0) h2 h0 (h4.trans h3)).trans h4
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ ∃ x1 x2, 0.5 < x1 ∧ x1 < x2 ∧ x2 ≤ x ∧ 0 ≤ f x1 ∧ f x2 ≤ 0
[PROOFSTEP]
refine' ⟨18, 512, by norm_num1, by norm_num1, n_large, _, _⟩
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ 0.5 < 18
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ 18 < 512
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ 0 ≤ f 18
[PROOFSTEP]
have : sqrt (2 * 18) = 6 := (sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1)
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ 0 < 6
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ 6 * 6 = 2 * 18
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 ≤ f 18
[PROOFSTEP]
rw [hf, log_nonneg_iff, this]
[GOAL]
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 1 ≤ 18 * (2 * 18) ^ 6 / 4 ^ (18 / 3)
[PROOFSTEP]
rw [one_le_div]
[GOAL]
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 4 ^ (18 / 3) ≤ 18 * (2 * 18) ^ 6
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 4 ^ (18 / 3)
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 4 ^ 6 ≤ 18 * 36 ^ 6
[PROOFSTEP]
apply le_trans _ (le_mul_of_one_le_left _ _)
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 4 ^ 6 ≤ 36 ^ 6
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 ≤ 36 ^ 6
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 1 ≤ 18
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 4 ^ 6 ≤ 36 ^ 6
[PROOFSTEP]
apply Real.rpow_le_rpow
[GOAL]
case h
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 ≤ 4
[PROOFSTEP]
norm_num1
[GOAL]
case h₁
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 4 ≤ 36
[PROOFSTEP]
norm_num1
[GOAL]
case h₂
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 ≤ 6
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 ≤ 36 ^ 6
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 4 ^ 6
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18 * (2 * 18) ^ sqrt (2 * 18) / 4 ^ (18 / 3)
case refine'_1.a
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18
[PROOFSTEP]
apply rpow_nonneg_of_nonneg
[GOAL]
case hx
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 ≤ 36
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 4 ^ 6
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18 * (2 * 18) ^ sqrt (2 * 18) / 4 ^ (18 / 3)
case refine'_1.a
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 4 ^ 6
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18 * (2 * 18) ^ sqrt (2 * 18) / 4 ^ (18 / 3)
case refine'_1.a
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18
[PROOFSTEP]
apply rpow_pos_of_pos
[GOAL]
case refine'_1.hx
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 4
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18 * (2 * 18) ^ sqrt (2 * 18) / 4 ^ (18 / 3)
case refine'_1.a
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18 * (2 * 18) ^ sqrt (2 * 18) / 4 ^ (18 / 3)
case refine'_1.a
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18
[PROOFSTEP]
apply hf' 18
[GOAL]
case refine'_1
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18
case refine'_1.a
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_1.a
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 18) = 6
⊢ 0 < 18
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ f 512 ≤ 0
[PROOFSTEP]
have : sqrt (2 * 512) = 32 := (sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1)
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ 0 < 32
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
⊢ 32 * 32 = 2 * 512
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ f 512 ≤ 0
[PROOFSTEP]
rw [hf, log_nonpos_iff (hf' _ _), this, div_le_one]
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 512 * (2 * 512) ^ 32 ≤ 4 ^ (512 / 3)
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 0 < 4 ^ (512 / 3)
[PROOFSTEP]
norm_num1
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 0 < 512
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2.a
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 0 < 512
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 512 * 1024 ^ 32 ≤ 4 ^ (512 / 3)
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 0 < 4 ^ (512 / 3)
[PROOFSTEP]
have : (512 : ℝ) = 2 ^ (9 : ℕ)
[GOAL]
case this
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 512 = 2 ^ ↑9
[PROOFSTEP]
rw [rpow_nat_cast 2 9]
[GOAL]
case this
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 512 = 2 ^ 9
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝ : sqrt (2 * 512) = 32
this : 512 = 2 ^ ↑9
⊢ 512 * 1024 ^ 32 ≤ 4 ^ (512 / 3)
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 0 < 4 ^ (512 / 3)
[PROOFSTEP]
conv_lhs => rw [this]
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝ : sqrt (2 * 512) = 32
this : 512 = 2 ^ ↑9
| 512 * 1024 ^ 32
[PROOFSTEP]
rw [this]
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝ : sqrt (2 * 512) = 32
this : 512 = 2 ^ ↑9
| 512 * 1024 ^ 32
[PROOFSTEP]
rw [this]
[GOAL]
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝ : sqrt (2 * 512) = 32
this : 512 = 2 ^ ↑9
| 512 * 1024 ^ 32
[PROOFSTEP]
rw [this]
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝ : sqrt (2 * 512) = 32
this : 512 = 2 ^ ↑9
⊢ 2 ^ ↑9 * 1024 ^ 32 ≤ 4 ^ (512 / 3)
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 0 < 4 ^ (512 / 3)
[PROOFSTEP]
have : (1024 : ℝ) = 2 ^ (10 : ℕ)
[GOAL]
case this
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝ : sqrt (2 * 512) = 32
this : 512 = 2 ^ ↑9
⊢ 1024 = 2 ^ ↑10
[PROOFSTEP]
rw [rpow_nat_cast 2 10]
[GOAL]
case this
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝ : sqrt (2 * 512) = 32
this : 512 = 2 ^ ↑9
⊢ 1024 = 2 ^ 10
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝¹ : sqrt (2 * 512) = 32
this✝ : 512 = 2 ^ ↑9
this : 1024 = 2 ^ ↑10
⊢ 2 ^ ↑9 * 1024 ^ 32 ≤ 4 ^ (512 / 3)
[PROOFSTEP]
rw [this, ← rpow_mul, ← rpow_add]
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝¹ : sqrt (2 * 512) = 32
this✝ : 512 = 2 ^ ↑9
this : 1024 = 2 ^ ↑10
⊢ 2 ^ (↑9 + ↑10 * 32) ≤ 4 ^ (512 / 3)
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2.hx
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝¹ : sqrt (2 * 512) = 32
this✝ : 512 = 2 ^ ↑9
this : 1024 = 2 ^ ↑10
⊢ 0 < 2
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2.hx
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝¹ : sqrt (2 * 512) = 32
this✝ : 512 = 2 ^ ↑9
this : 1024 = 2 ^ ↑10
⊢ 0 ≤ 2
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝¹ : sqrt (2 * 512) = 32
this✝ : 512 = 2 ^ ↑9
this : 1024 = 2 ^ ↑10
⊢ 2 ^ 329 ≤ 4 ^ (512 / 3)
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 0 < 4 ^ (512 / 3)
[PROOFSTEP]
have : (4 : ℝ) = 2 ^ (2 : ℕ)
[GOAL]
case this
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝¹ : sqrt (2 * 512) = 32
this✝ : 512 = 2 ^ ↑9
this : 1024 = 2 ^ ↑10
⊢ 4 = 2 ^ ↑2
[PROOFSTEP]
rw [rpow_nat_cast 2 2]
[GOAL]
case this
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝¹ : sqrt (2 * 512) = 32
this✝ : 512 = 2 ^ ↑9
this : 1024 = 2 ^ ↑10
⊢ 4 = 2 ^ 2
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝² : sqrt (2 * 512) = 32
this✝¹ : 512 = 2 ^ ↑9
this✝ : 1024 = 2 ^ ↑10
this : 4 = 2 ^ ↑2
⊢ 2 ^ 329 ≤ 4 ^ (512 / 3)
[PROOFSTEP]
rw [this, ← rpow_mul]
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝² : sqrt (2 * 512) = 32
this✝¹ : 512 = 2 ^ ↑9
this✝ : 1024 = 2 ^ ↑10
this : 4 = 2 ^ ↑2
⊢ 2 ^ 329 ≤ 2 ^ (↑2 * (512 / 3))
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2.hx
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝² : sqrt (2 * 512) = 32
this✝¹ : 512 = 2 ^ ↑9
this✝ : 1024 = 2 ^ ↑10
this : 4 = 2 ^ ↑2
⊢ 0 ≤ 2
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝² : sqrt (2 * 512) = 32
this✝¹ : 512 = 2 ^ ↑9
this✝ : 1024 = 2 ^ ↑10
this : 4 = 2 ^ ↑2
⊢ 2 ^ 329 ≤ 2 ^ (1024 / 3)
[PROOFSTEP]
apply rpow_le_rpow_of_exponent_le
[GOAL]
case refine'_2.hx
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝² : sqrt (2 * 512) = 32
this✝¹ : 512 = 2 ^ ↑9
this✝ : 1024 = 2 ^ ↑10
this : 4 = 2 ^ ↑2
⊢ 1 ≤ 2
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2.hyz
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this✝² : sqrt (2 * 512) = 32
this✝¹ : 512 = 2 ^ ↑9
this✝ : 1024 = 2 ^ ↑10
this : 4 = 2 ^ ↑2
⊢ 329 ≤ 1024 / 3
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_2
x : ℝ
n_large : 512 ≤ x
f : ℝ → ℝ := fun x => log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x
hf' : ∀ (x : ℝ), 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)
hf : ∀ (x : ℝ), 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3))
h5 : 0 < x
h : ConcaveOn ℝ (Set.Ioi 0.5) f
this : sqrt (2 * 512) = 32
⊢ 0 < 4 ^ (512 / 3)
[PROOFSTEP]
apply rpow_pos_of_pos four_pos
[GOAL]
n : ℕ
n_large : 512 ≤ n
⊢ n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n
[PROOFSTEP]
rw [← @cast_le ℝ]
[GOAL]
n : ℕ
n_large : 512 ≤ n
⊢ ↑(n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)) ≤ ↑(4 ^ n)
[PROOFSTEP]
simp only [cast_add, cast_one, cast_mul, cast_pow, ← Real.rpow_nat_cast]
[GOAL]
n : ℕ
n_large : 512 ≤ n
⊢ ↑n * (↑2 * ↑n) ^ ↑(sqrt (2 * n)) * ↑4 ^ ↑(2 * n / 3) ≤ ↑4 ^ ↑n
[PROOFSTEP]
have n_pos : 0 < n := (by decide : 0 < 512).trans_le n_large
[GOAL]
n : ℕ
n_large : 512 ≤ n
⊢ 0 < 512
[PROOFSTEP]
decide
[GOAL]
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
⊢ ↑n * (↑2 * ↑n) ^ ↑(sqrt (2 * n)) * ↑4 ^ ↑(2 * n / 3) ≤ ↑4 ^ ↑n
[PROOFSTEP]
have n2_pos : 1 ≤ 2 * n := mul_pos (by decide) n_pos
[GOAL]
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
⊢ 0 < 2
[PROOFSTEP]
decide
[GOAL]
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ ↑n * (↑2 * ↑n) ^ ↑(sqrt (2 * n)) * ↑4 ^ ↑(2 * n / 3) ≤ ↑4 ^ ↑n
[PROOFSTEP]
refine' _root_.trans (mul_le_mul _ _ _ _) (Bertrand.real_main_inequality (by exact_mod_cast n_large))
[GOAL]
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ 512 ≤ ↑n
[PROOFSTEP]
exact_mod_cast n_large
[GOAL]
case refine'_1
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ ↑n * (↑2 * ↑n) ^ ↑(sqrt (2 * n)) ≤ ↑n * (2 * ↑n) ^ Real.sqrt (2 * ↑n)
[PROOFSTEP]
refine' mul_le_mul_of_nonneg_left _ (Nat.cast_nonneg _)
[GOAL]
case refine'_1
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ (↑2 * ↑n) ^ ↑(sqrt (2 * n)) ≤ (2 * ↑n) ^ Real.sqrt (2 * ↑n)
[PROOFSTEP]
refine' Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast n2_pos) _
[GOAL]
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ 1 ≤ ↑2 * ↑n
[PROOFSTEP]
exact_mod_cast n2_pos
[GOAL]
case refine'_1
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ ↑(sqrt (2 * n)) ≤ Real.sqrt (2 * ↑n)
[PROOFSTEP]
exact_mod_cast Real.nat_sqrt_le_real_sqrt
[GOAL]
case refine'_2
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ ↑4 ^ ↑(2 * n / 3) ≤ 4 ^ (2 * ↑n / 3)
[PROOFSTEP]
exact Real.rpow_le_rpow_of_exponent_le (by norm_num1) (cast_div_le.trans (by norm_cast))
[GOAL]
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ 1 ≤ ↑4
[PROOFSTEP]
norm_num1
[GOAL]
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ ↑(2 * n) / ↑3 ≤ 2 * ↑n / 3
[PROOFSTEP]
norm_cast
[GOAL]
case refine'_3
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ 0 ≤ ↑4 ^ ↑(2 * n / 3)
[PROOFSTEP]
exact Real.rpow_nonneg_of_nonneg (by norm_num1) _
[GOAL]
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ 0 ≤ ↑4
[PROOFSTEP]
norm_num1
[GOAL]
case refine'_4
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ 0 ≤ ↑n * (2 * ↑n) ^ Real.sqrt (2 * ↑n)
[PROOFSTEP]
refine' mul_nonneg (Nat.cast_nonneg _) _
[GOAL]
case refine'_4
n : ℕ
n_large : 512 ≤ n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ 0 ≤ (2 * ↑n) ^ Real.sqrt (2 * ↑n)
[PROOFSTEP]
exact Real.rpow_nonneg_of_nonneg (mul_nonneg zero_le_two (Nat.cast_nonneg _)) _
[GOAL]
n : ℕ
n_large : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
⊢ centralBinom n = ∏ p in Finset.range (2 * n / 3 + 1), p ^ ↑(Nat.factorization (centralBinom n)) p
[PROOFSTEP]
refine' (Eq.trans _ n.prod_pow_factorization_centralBinom).symm
[GOAL]
n : ℕ
n_large : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
⊢ ∏ p in Finset.range (2 * n / 3 + 1), p ^ ↑(Nat.factorization (centralBinom n)) p =
∏ p in Finset.range (2 * n + 1), p ^ ↑(Nat.factorization (centralBinom n)) p
[PROOFSTEP]
apply Finset.prod_subset
[GOAL]
case h
n : ℕ
n_large : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
⊢ Finset.range (2 * n / 3 + 1) ⊆ Finset.range (2 * n + 1)
[PROOFSTEP]
exact Finset.range_subset.2 (add_le_add_right (Nat.div_le_self _ _) _)
[GOAL]
case hf
n : ℕ
n_large : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
⊢ ∀ (x : ℕ),
x ∈ Finset.range (2 * n + 1) → ¬x ∈ Finset.range (2 * n / 3 + 1) → x ^ ↑(Nat.factorization (centralBinom n)) x = 1
[PROOFSTEP]
intro x hx h2x
[GOAL]
case hf
n : ℕ
n_large : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
x : ℕ
hx : x ∈ Finset.range (2 * n + 1)
h2x : ¬x ∈ Finset.range (2 * n / 3 + 1)
⊢ x ^ ↑(Nat.factorization (centralBinom n)) x = 1
[PROOFSTEP]
rw [Finset.mem_range, lt_succ_iff] at hx h2x
[GOAL]
case hf
n : ℕ
n_large : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
x : ℕ
hx : x ≤ 2 * n
h2x : ¬x ≤ 2 * n / 3
⊢ x ^ ↑(Nat.factorization (centralBinom n)) x = 1
[PROOFSTEP]
rw [not_le, div_lt_iff_lt_mul' three_pos, mul_comm x] at h2x
[GOAL]
case hf
n : ℕ
n_large : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
x : ℕ
hx : x ≤ 2 * n
h2x : 2 * n < 3 * x
⊢ x ^ ↑(Nat.factorization (centralBinom n)) x = 1
[PROOFSTEP]
replace no_prime := not_exists.mp no_prime x
[GOAL]
case hf
n : ℕ
n_large : 2 < n
x : ℕ
hx : x ≤ 2 * n
h2x : 2 * n < 3 * x
no_prime : ¬(Nat.Prime x ∧ n < x ∧ x ≤ 2 * n)
⊢ x ^ ↑(Nat.factorization (centralBinom n)) x = 1
[PROOFSTEP]
rw [← and_assoc, not_and', not_and_or, not_lt] at no_prime
[GOAL]
case hf
n : ℕ
n_large : 2 < n
x : ℕ
hx : x ≤ 2 * n
h2x : 2 * n < 3 * x
no_prime : x ≤ 2 * n → ¬Nat.Prime x ∨ x ≤ n
⊢ x ^ ↑(Nat.factorization (centralBinom n)) x = 1
[PROOFSTEP]
cases' no_prime hx with h h
[GOAL]
case hf.inl
n : ℕ
n_large : 2 < n
x : ℕ
hx : x ≤ 2 * n
h2x : 2 * n < 3 * x
no_prime : x ≤ 2 * n → ¬Nat.Prime x ∨ x ≤ n
h : ¬Nat.Prime x
⊢ x ^ ↑(Nat.factorization (centralBinom n)) x = 1
[PROOFSTEP]
rw [factorization_eq_zero_of_non_prime n.centralBinom h, Nat.pow_zero]
[GOAL]
case hf.inr
n : ℕ
n_large : 2 < n
x : ℕ
hx : x ≤ 2 * n
h2x : 2 * n < 3 * x
no_prime : x ≤ 2 * n → ¬Nat.Prime x ∨ x ≤ n
h : x ≤ n
⊢ x ^ ↑(Nat.factorization (centralBinom n)) x = 1
[PROOFSTEP]
rw [factorization_centralBinom_of_two_mul_self_lt_three_mul n_large h h2x, Nat.pow_zero]
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
⊢ centralBinom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)
[PROOFSTEP]
have n_pos : 0 < n := (Nat.zero_le _).trans_lt n_big
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
⊢ centralBinom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)
[PROOFSTEP]
have n2_pos : 1 ≤ 2 * n := mul_pos (zero_lt_two' ℕ) n_pos
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
⊢ centralBinom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)
[PROOFSTEP]
let S := (Finset.range (2 * n / 3 + 1)).filter Nat.Prime
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
⊢ centralBinom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)
[PROOFSTEP]
let f x := x ^ n.centralBinom.factorization x
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
⊢ centralBinom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)
[PROOFSTEP]
have : ∏ x : ℕ in S, f x = ∏ x : ℕ in Finset.range (2 * n / 3 + 1), f x :=
by
refine' Finset.prod_filter_of_ne fun p _ h => _
contrapose! h; dsimp only
rw [factorization_eq_zero_of_non_prime n.centralBinom h, _root_.pow_zero]
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
⊢ ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
[PROOFSTEP]
refine' Finset.prod_filter_of_ne fun p _ h => _
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
p : ℕ
x✝ : p ∈ Finset.range (2 * n / 3 + 1)
h : f p ≠ 1
⊢ Nat.Prime p
[PROOFSTEP]
contrapose! h
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
p : ℕ
x✝ : p ∈ Finset.range (2 * n / 3 + 1)
h : ¬Nat.Prime p
⊢ (fun x => x ^ ↑(Nat.factorization (centralBinom n)) x) p = 1
[PROOFSTEP]
dsimp only
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
p : ℕ
x✝ : p ∈ Finset.range (2 * n / 3 + 1)
h : ¬Nat.Prime p
⊢ p ^ ↑(Nat.factorization (centralBinom n)) p = 1
[PROOFSTEP]
rw [factorization_eq_zero_of_non_prime n.centralBinom h, _root_.pow_zero]
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
⊢ centralBinom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)
[PROOFSTEP]
rw [centralBinom_factorization_small n n_big no_prime, ← this, ←
Finset.prod_filter_mul_prod_filter_not S (· ≤ sqrt (2 * n))]
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
⊢ (∏ x in Finset.filter (fun x => x ≤ sqrt (2 * n)) S, f x) * ∏ x in Finset.filter (fun x => ¬x ≤ sqrt (2 * n)) S, f x ≤
(2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)
[PROOFSTEP]
apply mul_le_mul'
[GOAL]
case h₁
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
⊢ ∏ x in Finset.filter (fun x => x ≤ sqrt (2 * n)) S, f x ≤ (2 * n) ^ sqrt (2 * n)
[PROOFSTEP]
refine' (Finset.prod_le_prod' fun p _ => (_ : f p ≤ 2 * n)).trans _
[GOAL]
case h₁.refine'_1
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
p : ℕ
x✝ : p ∈ Finset.filter (fun x => x ≤ sqrt (2 * n)) S
⊢ f p ≤ 2 * n
[PROOFSTEP]
exact pow_factorization_choose_le (mul_pos two_pos n_pos)
[GOAL]
case h₁.refine'_2
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
⊢ ∏ i in Finset.filter (fun x => x ≤ sqrt (2 * n)) S, 2 * n ≤ (2 * n) ^ sqrt (2 * n)
[PROOFSTEP]
have : (Finset.Icc 1 (sqrt (2 * n))).card = sqrt (2 * n) := by rw [card_Icc, Nat.add_sub_cancel]
[GOAL]
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
⊢ Finset.card (Finset.Icc 1 (sqrt (2 * n))) = sqrt (2 * n)
[PROOFSTEP]
rw [card_Icc, Nat.add_sub_cancel]
[GOAL]
case h₁.refine'_2
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this✝ : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
this : Finset.card (Finset.Icc 1 (sqrt (2 * n))) = sqrt (2 * n)
⊢ ∏ i in Finset.filter (fun x => x ≤ sqrt (2 * n)) S, 2 * n ≤ (2 * n) ^ sqrt (2 * n)
[PROOFSTEP]
rw [Finset.prod_const]
[GOAL]
case h₁.refine'_2
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this✝ : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
this : Finset.card (Finset.Icc 1 (sqrt (2 * n))) = sqrt (2 * n)
⊢ (2 * n) ^ Finset.card (Finset.filter (fun x => x ≤ sqrt (2 * n)) S) ≤ (2 * n) ^ sqrt (2 * n)
[PROOFSTEP]
refine' pow_le_pow n2_pos ((Finset.card_le_of_subset fun x hx => _).trans this.le)
[GOAL]
case h₁.refine'_2
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this✝ : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
this : Finset.card (Finset.Icc 1 (sqrt (2 * n))) = sqrt (2 * n)
x : ℕ
hx : x ∈ Finset.filter (fun x => x ≤ sqrt (2 * n)) S
⊢ x ∈ Finset.Icc 1 (sqrt (2 * n))
[PROOFSTEP]
obtain ⟨h1, h2⟩ := Finset.mem_filter.1 hx
[GOAL]
case h₁.refine'_2.intro
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this✝ : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
this : Finset.card (Finset.Icc 1 (sqrt (2 * n))) = sqrt (2 * n)
x : ℕ
hx : x ∈ Finset.filter (fun x => x ≤ sqrt (2 * n)) S
h1 : x ∈ S
h2 : x ≤ sqrt (2 * n)
⊢ x ∈ Finset.Icc 1 (sqrt (2 * n))
[PROOFSTEP]
exact Finset.mem_Icc.mpr ⟨(Finset.mem_filter.1 h1).2.one_lt.le, h2⟩
[GOAL]
case h₂
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
⊢ ∏ x in Finset.filter (fun x => ¬x ≤ sqrt (2 * n)) S, f x ≤ 4 ^ (2 * n / 3)
[PROOFSTEP]
refine' le_trans _ (primorial_le_4_pow (2 * n / 3))
[GOAL]
case h₂
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
⊢ ∏ x in Finset.filter (fun x => ¬x ≤ sqrt (2 * n)) S, f x ≤ primorial (2 * n / 3)
[PROOFSTEP]
refine' (Finset.prod_le_prod' fun p hp => (_ : f p ≤ p)).trans _
[GOAL]
case h₂.refine'_1
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
p : ℕ
hp : p ∈ Finset.filter (fun x => ¬x ≤ sqrt (2 * n)) S
⊢ f p ≤ p
[PROOFSTEP]
obtain ⟨h1, h2⟩ := Finset.mem_filter.1 hp
[GOAL]
case h₂.refine'_1.intro
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
p : ℕ
hp : p ∈ Finset.filter (fun x => ¬x ≤ sqrt (2 * n)) S
h1 : p ∈ S
h2 : ¬p ≤ sqrt (2 * n)
⊢ f p ≤ p
[PROOFSTEP]
refine' (pow_le_pow (Finset.mem_filter.1 h1).2.one_lt.le _).trans (pow_one p).le
[GOAL]
case h₂.refine'_1.intro
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
p : ℕ
hp : p ∈ Finset.filter (fun x => ¬x ≤ sqrt (2 * n)) S
h1 : p ∈ S
h2 : ¬p ≤ sqrt (2 * n)
⊢ ↑(Nat.factorization (centralBinom n)) p ≤ 1
[PROOFSTEP]
exact Nat.factorization_choose_le_one (sqrt_lt'.mp <| not_le.1 h2)
[GOAL]
case h₂.refine'_2
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
⊢ ∏ i in Finset.filter (fun x => ¬x ≤ sqrt (2 * n)) S, i ≤ primorial (2 * n / 3)
[PROOFSTEP]
refine' Finset.prod_le_prod_of_subset_of_one_le' (Finset.filter_subset _ _) _
[GOAL]
case h₂.refine'_2
n : ℕ
n_big : 2 < n
no_prime : ¬∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n
n_pos : 0 < n
n2_pos : 1 ≤ 2 * n
S : Finset ℕ := Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1))
f : ℕ → ℕ := fun x => x ^ ↑(Nat.factorization (centralBinom n)) x
this : ∏ x in S, f x = ∏ x in Finset.range (2 * n / 3 + 1), f x
⊢ ∀ (i : ℕ),
i ∈ Finset.filter Nat.Prime (Finset.range (2 * n / 3 + 1)) →
¬i ∈ Finset.filter (fun x => ¬x ≤ sqrt (2 * n)) S → 1 ≤ i
[PROOFSTEP]
exact fun p hp _ => (Finset.mem_filter.1 hp).2.one_lt.le
[GOAL]
n : ℕ
n_big : 512 ≤ n
⊢ ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
by_contra no_prime
[GOAL]
n : ℕ
n_big : 512 ≤ n
no_prime : ¬∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
⊢ False
[PROOFSTEP]
have H1 : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n := bertrand_main_inequality n_big
[GOAL]
n : ℕ
n_big : 512 ≤ n
no_prime : ¬∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
H1 : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n
⊢ False
[PROOFSTEP]
have H2 : 4 ^ n < n * n.centralBinom := Nat.four_pow_lt_mul_centralBinom n (le_trans (by norm_num1) n_big)
[GOAL]
n : ℕ
n_big : 512 ≤ n
no_prime : ¬∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
H1 : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n
⊢ 4 ≤ 512
[PROOFSTEP]
norm_num1
[GOAL]
n : ℕ
n_big : 512 ≤ n
no_prime : ¬∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
H1 : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n
H2 : 4 ^ n < n * centralBinom n
⊢ False
[PROOFSTEP]
have H3 : n.centralBinom ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) :=
centralBinom_le_of_no_bertrand_prime n (lt_of_lt_of_le (by norm_num1) n_big) no_prime
[GOAL]
n : ℕ
n_big : 512 ≤ n
no_prime : ¬∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
H1 : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n
H2 : 4 ^ n < n * centralBinom n
⊢ 2 < 512
[PROOFSTEP]
norm_num1
[GOAL]
n : ℕ
n_big : 512 ≤ n
no_prime : ¬∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
H1 : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n
H2 : 4 ^ n < n * centralBinom n
H3 : centralBinom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)
⊢ False
[PROOFSTEP]
rw [mul_assoc] at H1
[GOAL]
n : ℕ
n_big : 512 ≤ n
no_prime : ¬∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
H1 : n * ((2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)) ≤ 4 ^ n
H2 : 4 ^ n < n * centralBinom n
H3 : centralBinom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3)
⊢ False
[PROOFSTEP]
exact not_le.2 H2 ((mul_le_mul_left' H3 n).trans H1)
[GOAL]
n q p : ℕ
prime_p : Prime p
covering : p ≤ 2 * q
H : n < q → ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
hn : n < p
⊢ ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
by_cases p ≤ 2 * n
[GOAL]
n q p : ℕ
prime_p : Prime p
covering : p ≤ 2 * q
H : n < q → ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
hn : n < p
⊢ ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
by_cases p ≤ 2 * n
[GOAL]
case pos
n q p : ℕ
prime_p : Prime p
covering : p ≤ 2 * q
H : n < q → ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
hn : n < p
h : p ≤ 2 * n
⊢ ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
exact ⟨p, prime_p, hn, h⟩
[GOAL]
case neg
n q p : ℕ
prime_p : Prime p
covering : p ≤ 2 * q
H : n < q → ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
hn : n < p
h : ¬p ≤ 2 * n
⊢ ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
exact H (lt_of_mul_lt_mul_left' (lt_of_lt_of_le (not_le.1 h) covering))
[GOAL]
n : ℕ
hn0 : n ≠ 0
⊢ ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
cases' lt_or_le 511 n with h h
[GOAL]
case inl
n : ℕ
hn0 : n ≠ 0
h : 511 < n
⊢ ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
exact exists_prime_lt_and_le_two_mul_eventually n h
[GOAL]
case inr
n : ℕ
hn0 : n ≠ 0
h : n ≤ 511
⊢ ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
replace h : n < 521 := h.trans_lt (by norm_num1)
[GOAL]
n : ℕ
hn0 : n ≠ 0
h : n ≤ 511
⊢ 511 < 521
[PROOFSTEP]
norm_num1
[GOAL]
case inr
n : ℕ
hn0 : n ≠ 0
h : n < 521
⊢ ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
revert h
[GOAL]
case inr
n : ℕ
hn0 : n ≠ 0
⊢ n < 521 → ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
open Lean Elab
Tactic in
run_tac
do
for i in [317, 163, 83, 43, 23, 13, 7, 5, 3, 2]do
let i : Term := quote i
evalTactic <| ← `(tactic| refine' exists_prime_lt_and_le_two_mul_succ $i (by norm_num1) (by norm_num1) _)
exact fun h2 => ⟨2, prime_two, h2, Nat.mul_le_mul_left 2 (Nat.pos_of_ne_zero hn0)⟩
[GOAL]
case inr
n : ℕ
hn0 : n ≠ 0
⊢ n < 521 → ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
run_tac
do
for i in [317, 163, 83, 43, 23, 13, 7, 5, 3, 2]do
let i : Term := quote i
evalTactic <| ← `(tactic| refine' exists_prime_lt_and_le_two_mul_succ $i (by norm_num1) (by norm_num1) _)
[GOAL]
case inr
n : ℕ
hn0 : n ≠ 0
⊢ n < 2 → ∃ p, Prime p ∧ n < p ∧ p ≤ 2 * n
[PROOFSTEP]
exact fun h2 => ⟨2, prime_two, h2, Nat.mul_le_mul_left 2 (Nat.pos_of_ne_zero hn0)⟩
|
import tactic
open_locale classical
-- tells Lean to allow the law of excluded middle
variables P Q R : Prop
/--------------------------------------------------------------------------
``push_neg``
Simplifies negations in the target, if possible.
If ``hp : P`` is a hypothesis, then
``push_neg at hp,`` simplyfies the negations at ``hp``, if possible.
--------------------------------------------------------------------------/
theorem ex1 : ¬ ¬ P → P :=
begin
push_neg,
intro hp,
exact hp,
end
theorem ex2 : ¬ ¬ P → P :=
begin
intro hp,
push_neg at hp,
exact hp,
end
/--------------------------------------------------------------------------
``by_contradiction``
If the current target is ``P``,
then ``by_contradiction hnp,`` changes the target to ``false``
and adds a hypothesis ``hnp : ¬P``.
--------------------------------------------------------------------------/
theorem ex3 : P ∨ ¬ P :=
begin
by_contradiction h,
push_neg at h,
cases h,
apply h_left,
exact h_right,
end
/--------------------------------------------------------------------------
``by_cases``
If ``P`` is a proposition,
then ``by_cases P,`` creates two hypothesis ``h : P`` and ``h : ¬P``.
This is the law of excluded middle.
--------------------------------------------------------------------------/
theorem ex4 : P ∨ ¬ P :=
begin
by_cases P,
left,
exact h,
right,
exact h,
end
/--------------------------------------------------------------------------
Delete the ``sorry,`` below and replace them with valid proofs.
--------------------------------------------------------------------------/
theorem de_morgan1 : ¬P ∧ ¬Q → ¬(P ∨ Q) :=
begin
sorry,
end
theorem de_morgan1_converse : ¬(P ∨ Q) → ¬P ∧ ¬Q :=
begin
sorry,
end
theorem de_morgan2 : ¬P ∨ ¬Q → ¬(P ∧ Q) :=
begin
sorry,
end
theorem de_morgan2_converse : ¬(P ∧ Q) → (¬P ∨ ¬Q):=
begin
sorry,
end
theorem contrapositive_converse : (¬Q → ¬P) → (P → Q) :=
begin
sorry,
end |
import smt2
lemma int_ctor (n : nat) :
int.of_nat n >= 0 :=
begin
z3
end
|
#! /usr/bin/Rscript
# license: BSD 3-Clause License
# author: https://github.com/ywd5
# revision to be done-----------------------------------------------------------
# Remove the path of "backup table.txt" in script, and make the user specify it like "Rscript backup.r x='backup table.txt'" in the shell.
# add .sh scripts, with the same function as r scripts
# add --noatime?s?, try --quiet --stats, in x$args
# for remote synchronization, try: --compress --skip-compress=tar,zip,rar,xz,gz,bz2
# although --human-readable already take effect, try --human-readable=1 and --human-readable=3
# merge "teclast1.0" and "teclast0.5" scripts
# get dependencies--------------------------------------------------------------
library(magrittr); library(tibble); library(dplyr); library(stringr); library(parallel);
if(Sys.which(names="rsync")[1] == ""){stop("rsync isn't available in the shell");}
# may need modification: mount disk---------------------------------------------
if(system2(command="cryptsetup", args="status teclast0.5", stdout=NULL) != 0){
message("decrypting the disk\n")
system2(command="cryptsetup", args="open UUID=aeefc3f1-2ca9-4399-ab6c-5c85c0c66d98 --type luks2 teclast0.5")
}
if(system2(command="findmnt", args="--source UUID=5ecb7176-a61d-4619-a6b0-a7f572668dad", stdout=NULL) != 0){
message("mounting the disk\n")
system2(command="mount", args="--source UUID=5ecb7176-a61d-4619-a6b0-a7f572668dad --target /mnt/teclast0.5")
# system2(command="mount", args="--source /dev/mapper/teclast0.5 --target /mnt/teclast0.5")
}
# may need modification: specify source, destination and log--------------------
destination_prefix <- "/mnt/teclast0.5/backup_zm/"
#
source_prefix <- "/mnt/"
x <- readLines(con="/home/user1/synchronization/backup table.txt") %>% str_trim(side="both") %>%
{.[. != ""]} %>% grep(pattern="^#", x=., invert=TRUE, value=TRUE) %>% strsplit(split=" {5,}")
log_file <- c("/home/user1/synchronization/backup log.xml", "/mnt/c/Users/wangz/Downloads/backup log.xml")
# control input-----------------------------------------------------------------
if(!dir.exists(source_prefix)){stop("source_prefix doesn't exist");}
if(!dir.exists(destination_prefix)){stop("destination_prefix doesn't exist");}
if(length(log_file) != 0) if(any(nchar(log_file) == 0)){
stop("log_file can't contain empty strings, but cat be character().")
}
lengths(x) %>% {. == 2} %>% {if(!all(.)){stop("not all lines contain 2 fileds");}}
unlist(x) %>% grepl(pattern="^\'(.+)\'$") %>% {if(!all(.)){stop("not all items are quoted by \'");}}
# add default log file----------------------------------------------------------
log_file %<>% c(paste0(destination_prefix, "backup log.xml"), .)
# prepare rsync commands--------------------------------------------------------
x %<>% lapply(FUN=base::sub, pattern="^\'(.+)\'$", replacement="\\1") %>%
simplify2array() %>% base::t() %>%
as_tibble(.name_repair="minimal") %>% setNames(nm=c("source", "destination")) %>%
dplyr::mutate(source=paste0(source_prefix, source),
destination=paste0(destination_prefix, destination),
log=paste0(tempfile(), " ", 1:length(x)), args="")
x$args <- paste0("--recursive --delete-before --preallocate --times --human-readable",
if(FALSE){" --modify-window=1"}else{" --checksum"},
" --log-file=\'", x$log, "\' --links --verbose \'",
x$source, "\' \'", x$destination, "\'")
remove(source_prefix, destination_prefix)
x$source %>% {.[!file.exists(.)]} %>% paste0(collapse="\n") %>%
{if(. != ""){stop("the following source directories don't exist:\n", .);}}
x$destination %>% unique() %>% {.[!dir.exists(.)]} %>%
{if(length(.) != 0){lapply(X=., FUN=dir.create, recursive=TRUE);}}
x$destination %>% unique() %>% {.[!dir.exists(.)]} %>% paste0(collapse="\n") %>%
{if(. != ""){stop("can't create the following destination directories:\n", .);}}
# run rsync---------------------------------------------------------------------
message("\n\n\nbegin synchronizing\n\n\n"); base::Sys.sleep(time=3);
tulip <- parallel::makeCluster(spec=2)
parallel::clusterApplyLB(cl=tulip, x=x$args, fun=base::system2, command="rsync")
parallel::stopCluster(cl=tulip)
remove(tulip)
# get log(s)--------------------------------------------------------------------
"<root time=\"%Y%m%d-%H%M%S\">\n" %>% strftime(x=Sys.time(),format=.) %>%
cat(sep="", file=log_file[1], append=FALSE)
for(i in 1:nrow(x)){
if(i != 1){cat("\n\n\n\n\n", sep="", file=log_file[1], append=TRUE);}
cat("<trunk command=\"rsync ", x$args[i], "\">\n", sep="", file=log_file[1], append=TRUE)
file.append(file1=log_file[1], file2=x$log[i])
cat("</trunk>\n", sep="", file=log_file[1], append=TRUE)
}; remove(i);
cat("</root>\n\n", sep="", file=log_file[1], append=TRUE)
if(length(log_file) > 1) for(i in 2:length(log_file)){
file.copy(from=log_file[1], to=log_file[i], overwrite=TRUE)
}; i <- 0; remove(i);
message("the log(s) is(are) written to:\n", paste0(log_file, collapse="\n"))
# may need modification: clean environment and un-mount disk--------------------
remove(x, log_file)
system2(command="umount", args="UUID=5ecb7176-a61d-4619-a6b0-a7f572668dad")
system2(command="cryptsetup", args="close teclast0.5")
|
lemma closed_nonneg_Reals_complex [simp]: "closed (\<real>\<^sub>\<ge>\<^sub>0 :: complex set)" |
(*
* Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: GPL-2.0-only
*)
(* seL4-specific lemmas for automation framework for C refinement *)
theory Ctac_lemmas_C
imports
Ctac
begin
context kernel
begin
lemma c_guard_abs_cte:
fixes p :: "cte_C ptr"
shows "\<forall>s s'. (s, s') \<in> rf_sr \<and> cte_at' (ptr_val p) s \<and> True \<longrightarrow> s' \<Turnstile>\<^sub>c p"
apply (cases p)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (erule (1) rf_sr_ctes_of_cliftE)
apply (simp add: typ_heap_simps')
done
lemmas ccorres_move_c_guard_cte [corres_pre] = ccorres_move_c_guards [OF c_guard_abs_cte]
lemma c_guard_abs_tcb:
fixes p :: "tcb_C ptr"
shows "\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' (ctcb_ptr_to_tcb_ptr p) s \<and> True \<longrightarrow> s' \<Turnstile>\<^sub>c p"
apply clarsimp
apply (drule (1) tcb_at_h_t_valid)
apply simp
done
lemmas ccorres_move_c_guard_tcb [corres_pre] = ccorres_move_c_guards [OF c_guard_abs_tcb]
lemma cte_array_relation_array_assertion:
"gsCNodes s p = Some n \<Longrightarrow> cte_array_relation s cstate
\<Longrightarrow> array_assertion (cte_Ptr p) (2 ^ n) (hrs_htd (t_hrs_' cstate))"
apply (rule h_t_array_valid_array_assertion)
apply (clarsimp simp: cvariable_array_map_relation_def)
apply simp
done
lemma rf_sr_tcb_ctes_array_assertion':
"\<lbrakk> (s, s') \<in> rf_sr; tcb_at' (ctcb_ptr_to_tcb_ptr tcb) s \<rbrakk>
\<Longrightarrow> array_assertion (cte_Ptr (ptr_val tcb && ~~mask tcbBlockSizeBits))
(unat tcbCNodeEntries) (hrs_htd (t_hrs_' (globals s')))"
apply (rule h_t_array_valid_array_assertion, simp_all add: tcbCNodeEntries_def)
apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def
cvariable_array_map_relation_def
cpspace_relation_def)
apply (drule obj_at_ko_at', clarsimp)
apply (drule spec, drule mp, rule exI, erule ko_at_projectKO_opt)
apply (frule ptr_val_tcb_ptr_mask)
apply (simp add: mask_def)
done
lemmas rf_sr_tcb_ctes_array_assertion
= rf_sr_tcb_ctes_array_assertion'[simplified objBits_defs mask_def, simplified]
lemma rf_sr_tcb_ctes_array_assertion2:
"\<lbrakk> (s, s') \<in> rf_sr; tcb_at' tcb s \<rbrakk>
\<Longrightarrow> array_assertion (cte_Ptr tcb)
(unat tcbCNodeEntries) (hrs_htd (t_hrs_' (globals s')))"
apply (frule(1) rf_sr_tcb_ctes_array_assertion[where
tcb="tcb_ptr_to_ctcb_ptr t" for t, simplified])
apply (simp add: ptr_val_tcb_ptr_mask)
done
lemma array_assertion_abs_tcb_ctes':
"\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' (ctcb_ptr_to_tcb_ptr (tcb s')) s \<and> (n s' \<le> unat tcbCNodeEntries)
\<longrightarrow> (x s' = 0 \<or> array_assertion (cte_Ptr (ptr_val (tcb s') && ~~mask tcbBlockSizeBits)) (n s') (hrs_htd (t_hrs_' (globals s'))))"
"\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' tcb' s \<and> (n s' \<le> unat tcbCNodeEntries)
\<longrightarrow> (x s' = 0 \<or> array_assertion (cte_Ptr tcb') (n s') (hrs_htd (t_hrs_' (globals s'))))"
apply (safe intro!: disjCI2)
apply (drule(1) rf_sr_tcb_ctes_array_assertion' rf_sr_tcb_ctes_array_assertion2
| erule array_assertion_shrink_right | simp)+
done
lemmas array_assertion_abs_tcb_ctes
= array_assertion_abs_tcb_ctes'[simplified objBits_defs mask_def, simplified]
lemma array_assertion_abs_tcb_ctes_add':
"\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' (ctcb_ptr_to_tcb_ptr (tcb s')) s
\<and> (n s' \<ge> 0 \<and> (case strong of True \<Rightarrow> n s' + 1 | False \<Rightarrow> n s') \<le> uint tcbCNodeEntries)
\<longrightarrow> ptr_add_assertion (cte_Ptr (ptr_val (tcb s') && ~~mask tcbBlockSizeBits)) (n s')
strong (hrs_htd (t_hrs_' (globals s')))"
apply (clarsimp, drule(1) rf_sr_tcb_ctes_array_assertion')
apply (simp add: ptr_add_assertion_positive, rule disjCI2)
apply (erule array_assertion_shrink_right)
apply (cases strong, simp_all add: unat_def del: nat_uint_eq)
done
lemmas array_assertion_abs_tcb_ctes_add
= array_assertion_abs_tcb_ctes_add'[simplified objBits_defs mask_def, simplified]
lemmas ccorres_move_array_assertion_tcb_ctes [corres_pre]
= ccorres_move_array_assertions [OF array_assertion_abs_tcb_ctes(1)]
ccorres_move_array_assertions [OF array_assertion_abs_tcb_ctes(2)]
ccorres_move_Guard_Seq[OF array_assertion_abs_tcb_ctes_add]
ccorres_move_Guard[OF array_assertion_abs_tcb_ctes_add]
lemma c_guard_abs_tcb_ctes':
fixes p :: "cte_C ptr"
shows "\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' (ctcb_ptr_to_tcb_ptr (tcb s')) s
\<and> (n < ucast tcbCNodeEntries) \<longrightarrow> s' \<Turnstile>\<^sub>c cte_Ptr (((ptr_val (tcb s') && ~~mask tcbBlockSizeBits)
+ n * 2^cteSizeBits))"
apply (clarsimp)
apply (rule c_guard_abs_cte[rule_format], intro conjI, simp_all)
apply (simp add: cte_at'_obj_at', rule disjI2)
apply (frule ptr_val_tcb_ptr_mask)
apply (rule_tac x="n * 2^cteSizeBits" in bexI)
apply (simp add: mask_def)
apply (simp add: word_less_nat_alt tcbCNodeEntries_def tcb_cte_cases_def objBits_defs)
apply (case_tac "unat n", simp_all add: unat_eq_of_nat, rename_tac n_rem)
apply (case_tac "n_rem", simp_all add: unat_eq_of_nat, (rename_tac n_rem)?)+
done
lemmas c_guard_abs_tcb_ctes = c_guard_abs_tcb_ctes'[simplified objBits_defs mask_def, simplified]
lemmas ccorres_move_c_guard_tcb_ctes [corres_pre] = ccorres_move_c_guards [OF c_guard_abs_tcb_ctes]
lemma c_guard_abs_pte:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> pte_at' (ptr_val p) s \<and> True
\<longrightarrow> s' \<Turnstile>\<^sub>c (p :: pte_C ptr)"
apply (clarsimp simp: typ_at_to_obj_at_arches)
apply (drule obj_at_ko_at', clarsimp)
apply (erule cmap_relationE1[OF rf_sr_cpte_relation])
apply (erule ko_at_projectKO_opt)
apply (fastforce intro: typ_heap_simps)
done
lemmas ccorres_move_c_guard_pte = ccorres_move_c_guards [OF c_guard_abs_pte]
lemma array_assertion_abs_pt:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> (page_table_at' pd s)
\<and> (n s' \<le> 2 ^ (ptBits - 3) \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0))
\<longrightarrow> (x s' = 0 \<or> array_assertion (pte_Ptr pd) (n s') (hrs_htd (t_hrs_' (globals s'))))"
apply (intro allI impI disjCI2, clarsimp)
apply (drule(1) page_table_at_rf_sr, clarsimp)
apply (erule clift_array_assertion_imp,
simp_all add: bit_simps)
apply (rule_tac x=0 in exI, simp)
done
lemmas ccorres_move_array_assertion_pt
= ccorres_move_array_assertions[OF array_assertion_abs_pt]
lemma c_guard_abs_pde:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> pde_at' (ptr_val p) s \<and> True
\<longrightarrow> s' \<Turnstile>\<^sub>c (p :: pde_C ptr)"
apply (clarsimp simp: typ_at_to_obj_at_arches)
apply (drule obj_at_ko_at', clarsimp)
apply (erule cmap_relationE1[OF rf_sr_cpde_relation])
apply (erule ko_at_projectKO_opt)
apply (fastforce intro: typ_heap_simps)
done
lemmas ccorres_move_c_guard_pde = ccorres_move_c_guards [OF c_guard_abs_pde]
lemma array_assertion_abs_pd:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> (page_directory_at' pd s)
\<and> (n s' \<le> 2 ^ (pdBits - 3) \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0))
\<longrightarrow> (x s' = 0 \<or> array_assertion (pde_Ptr pd) (n s') (hrs_htd (t_hrs_' (globals s'))))"
apply (intro allI impI disjCI2, clarsimp)
apply (drule(1) page_directory_at_rf_sr, clarsimp)
apply (erule clift_array_assertion_imp, simp_all add: bit_simps)
apply (rule_tac x=0 in exI, simp)
done
lemmas ccorres_move_array_assertion_pd
= ccorres_move_array_assertions[OF array_assertion_abs_pd]
lemma c_guard_abs_pdpte:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> pdpte_at' (ptr_val p) s \<and> True
\<longrightarrow> s' \<Turnstile>\<^sub>c (p :: pdpte_C ptr)"
apply (clarsimp simp: typ_at_to_obj_at_arches)
apply (drule obj_at_ko_at', clarsimp)
apply (erule cmap_relationE1[OF rf_sr_cpdpte_relation])
apply (erule ko_at_projectKO_opt)
apply (fastforce intro: typ_heap_simps)
done
lemmas ccorres_move_c_guard_pdpte = ccorres_move_c_guards [OF c_guard_abs_pdpte]
lemma array_assertion_abs_pdpt:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> (pd_pointer_table_at' pd s)
\<and> (n s' \<le> 2 ^ (pdptBits - 3) \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0))
\<longrightarrow> (x s' = 0 \<or> array_assertion (pdpte_Ptr pd) (n s') (hrs_htd (t_hrs_' (globals s'))))"
apply (intro allI impI disjCI2, clarsimp)
apply (drule(1) pd_pointer_table_at_rf_sr, clarsimp)
apply (erule clift_array_assertion_imp,
simp_all add: bit_simps)
apply (rule_tac x=0 in exI, simp)
done
lemmas ccorres_move_array_assertion_pdpt
= ccorres_move_array_assertions[OF array_assertion_abs_pdpt]
lemma c_guard_abs_pml4e:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> pml4e_at' (ptr_val p) s \<and> True
\<longrightarrow> s' \<Turnstile>\<^sub>c (p :: pml4e_C ptr)"
apply (clarsimp simp: typ_at_to_obj_at_arches)
apply (drule obj_at_ko_at', clarsimp)
apply (erule cmap_relationE1[OF rf_sr_cpml4e_relation])
apply (erule ko_at_projectKO_opt)
apply (fastforce intro: typ_heap_simps)
done
lemmas ccorres_move_c_guard_pml4e = ccorres_move_c_guards [OF c_guard_abs_pml4e]
lemma array_assertion_abs_pml4:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> (page_map_l4_at' pd s)
\<and> (n s' \<le> 2 ^ (pml4Bits - 3) \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0))
\<longrightarrow> (x s' = 0 \<or> array_assertion (pml4e_Ptr pd) (n s') (hrs_htd (t_hrs_' (globals s'))))"
apply (intro allI impI disjCI2, clarsimp)
apply (drule(1) page_map_l4_at_rf_sr, clarsimp)
apply (erule clift_array_assertion_imp, simp_all add: bit_simps)
apply (rule_tac x=0 in exI, simp)
done
lemmas ccorres_move_array_assertion_pml4
= ccorres_move_array_assertions[OF array_assertion_abs_pml4]
lemma move_c_guard_ap:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> asid_pool_at' (ptr_val p) s \<and> True
\<longrightarrow> s' \<Turnstile>\<^sub>c (p :: asid_pool_C ptr)"
apply (clarsimp simp: typ_at_to_obj_at_arches)
apply (drule obj_at_ko_at', clarsimp)
apply (erule cmap_relationE1 [OF rf_sr_cpspace_asidpool_relation])
apply (erule ko_at_projectKO_opt)
apply (fastforce intro: typ_heap_simps)
done
lemmas ccorres_move_c_guard_ap = ccorres_move_c_guards [OF move_c_guard_ap]
lemma array_assertion_abs_irq:
"\<forall>s s'. (s, s') \<in> rf_sr \<and> True
\<and> (n s' \<le> 256 \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0))
\<longrightarrow> (x s' = 0 \<or> array_assertion intStateIRQNode_Ptr (n s') (hrs_htd (t_hrs_' (globals s'))))"
apply (intro allI impI disjCI2)
apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def)
apply (clarsimp simp: h_t_valid_clift_Some_iff)
apply (erule clift_array_assertion_imp, (simp add: exI[where x=0])+)
done
lemmas ccorres_move_array_assertion_irq
= ccorres_move_array_assertions [OF array_assertion_abs_irq]
lemma ccorres_Guard_intStateIRQNode_array_Ptr_Seq:
assumes "ccorres_underlying rf_sr \<Gamma> r xf arrel axf A C hs a (c;; d)"
shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf A C hs a (Guard F {s. s \<Turnstile>\<^sub>c intStateIRQNode_array_Ptr} c;; d)"
by (rule ccorres_guard_imp2[OF ccorres_move_Guard_Seq[where P=\<top> and P'=\<top>, OF _ assms]]
; simp add: rf_sr_def cstate_relation_def Let_def)
lemmas ccorres_Guard_intStateIRQNode_array_Ptr =
ccorres_Guard_intStateIRQNode_array_Ptr_Seq[where d=SKIP, simplified ccorres_seq_skip']
ccorres_Guard_intStateIRQNode_array_Ptr_Seq
lemma rf_sr_gsCNodes_array_assertion:
"gsCNodes s p = Some n \<Longrightarrow> (s, s') \<in> rf_sr
\<Longrightarrow> array_assertion (cte_Ptr p) (2 ^ n) (hrs_htd (t_hrs_' (globals s')))"
by (clarsimp simp: rf_sr_def cstate_relation_def Let_def
cte_array_relation_array_assertion)
end
end
|
(*
File: SDS_Automation.thy
Author: Manuel Eberl <[email protected]>
This theory provides a number of commands to automatically derive restrictions on the
results of Social Decision Schemes fulfilling properties like Anonymity, Neutrality,
Ex-post- or SD-efficiency, and SD-Strategy-Proofness.
*)
section \<open>Automatic Fact Gathering for Social Decision Schemes\<close>
theory SDS_Automation
imports Preference_Profile_Cmd
keywords
"derive_orbit_equations"
"derive_support_conditions"
"derive_ex_post_conditions"
"find_inefficient_supports"
"prove_inefficient_supports"
"derive_strategyproofness_conditions" :: thy_goal
begin
text \<open>
We now provide the following commands to automatically derive restrictions on the results
of Social Decision Schemes satisfying Anonymity, Neutrality, Efficiency, or Strategy-Proofness:
\begin{description}
\item[@{command derive_orbit_equations}] to derive equalities arising from automorphisms of the
given profiles due to Anonymity and Neutrality
\item[@{command derive_ex_post_conditions}] to find all Pareto losers and the given profiles and
derive the facts that they must be assigned probability 0 by any \textit{ex-post}-efficient
SDS
\item[@{command find_inefficient_supports}] to use Linear Programming to find all minimal SD-inefficient
(but not \textit{ex-post}-inefficient) supports in the given profiles and output a
corresponding witness lottery for each of them
\item[@{command prove_inefficient_supports}] to prove a specified set of support conditions arising from
\textit{ex-post}- or \textit{SD}-Efficiency. For conditions arising from \textit{SD}-Efficiency,
a witness lottery must be specified (e.\,g. as computed by @{command derive_orbit_equations}).
\item[@{command derive_support_conditions}] to automatically find and prove all support conditions
arising from \textit{ex-post-} and \textit{SD}-Efficiency
\item [@{command derive_strategyproofness_conditions}] to automatically derive all conditions
arising from weak Strategy-Proofness and any manipulations between the given preference
profiles. An optional maximum manipulation size can be specified.
\end{description}
All commands except @{command find_inefficient_supports} open a proof state and leave behind
proof obligations for the user to discharge. This should always be possible using the Simplifier,
possibly with a few additional rules, depending on the context.
\<close>
lemma disj_False_right: "P \<or> False \<longleftrightarrow> P" by simp
lemmas multiset_add_ac = add_ac[where ?'a = "'a multiset"]
lemma less_or_eq_real:
"(x::real) < y \<or> x = y \<longleftrightarrow> x \<le> y" "x < y \<or> y = x \<longleftrightarrow> x \<le> y" by linarith+
lemma multiset_Diff_single_normalize:
fixes a c assumes "a \<noteq> c"
shows "({#a#} + B) - {#c#} = {#a#} + (B - {#c#})"
using assms by (metis diff_union_swap multiset_add_ac(2))
lemma ex_post_efficient_aux:
assumes "prefs_from_table_wf agents alts xss" "R \<equiv> prefs_from_table xss"
assumes "i \<in> agents" "\<forall>i\<in>agents. y \<succeq>[prefs_from_table xss i] x" "\<not>y \<preceq>[prefs_from_table xss i] x"
shows "ex_post_efficient_sds agents alts sds \<longrightarrow> pmf (sds R) x = 0"
proof
assume ex_post: "ex_post_efficient_sds agents alts sds"
from assms(1,2) have wf: "pref_profile_wf agents alts R"
by (simp add: pref_profile_from_tableI')
from ex_post interpret ex_post_efficient_sds agents alts sds .
from assms(2-) show "pmf (sds R) x = 0"
by (intro ex_post_efficient''[OF wf, of i x y]) simp_all
qed
lemma SD_inefficient_support_aux:
assumes R: "prefs_from_table_wf agents alts xss" "R \<equiv> prefs_from_table xss"
assumes as: "as \<noteq> []" "set as \<subseteq> alts" "distinct as" "A = set as"
assumes ys: "\<forall>x\<in>set (map snd ys). 0 \<le> x" "listsum (map snd ys) = 1" "set (map fst ys) \<subseteq> alts"
assumes i: "i \<in> agents"
assumes SD1: "\<forall>i\<in>agents. \<forall>x\<in>alts.
listsum (map snd (filter (\<lambda>y. prefs_from_table xss i x (fst y)) ys)) \<ge>
real (length (filter (prefs_from_table xss i x) as)) / real (length as)"
assumes SD2: "\<exists>x\<in>alts. listsum (map snd (filter (\<lambda>y. prefs_from_table xss i x (fst y)) ys)) >
real (length (filter (prefs_from_table xss i x) as)) / real (length as)"
shows "sd_efficient_sds agents alts sds \<longrightarrow> (\<exists>x\<in>A. pmf (sds R) x = 0)"
proof
assume "sd_efficient_sds agents alts sds"
from R have wf: "pref_profile_wf agents alts R"
by (simp add: pref_profile_from_tableI')
then interpret pref_profile_wf agents alts R .
interpret sd_efficient_sds agents alts sds by fact
from ys have ys': "pmf_of_list_wf ys" by (intro pmf_of_list_wfI) auto
{
fix i x assume "x \<in> alts" "i \<in> agents"
with ys' have "lottery_prob (pmf_of_list ys) (preferred_alts (R i) x) =
listsum (map snd (filter (\<lambda>y. prefs_from_table xss i x (fst y)) ys))"
by (subst measure_pmf_of_list) (simp_all add: preferred_alts_def R)
} note A = this
{
fix i x assume "x \<in> alts" "i \<in> agents"
with as have "lottery_prob (pmf_of_set (set as)) (preferred_alts (R i) x) =
real (card (set as \<inter> preferred_alts (R i) x)) / real (card (set as))"
by (subst measure_pmf_of_set) simp_all
also have "set as \<inter> preferred_alts (R i) x = set (filter (\<lambda>y. R i x y) as)"
by (auto simp add: preferred_alts_def)
also have "card \<dots> = length (filter (\<lambda>y. R i x y) as)"
by (intro distinct_card distinct_filter assms)
also have "card (set as) = length as" by (intro distinct_card assms)
finally have "lottery_prob (pmf_of_set (set as)) (preferred_alts (R i) x) =
real (length (filter (prefs_from_table xss i x) as)) / real (length as)"
by (simp add: R)
} note B = this
from wf show "\<exists>x\<in>A. pmf (sds R) x = 0"
proof (rule SD_inefficient_support')
from ys ys' show lottery1: "pmf_of_list ys \<in> lotteries" by (intro pmf_of_list_lottery)
show i: "i \<in> agents" by fact
from as have lottery2: "pmf_of_set (set as) \<in> lotteries"
by (intro pmf_of_set_lottery) simp_all
from i as SD2 lottery1 lottery2 show "\<not>SD (R i) (pmf_of_list ys) (pmf_of_set A)"
by (subst preorder_on.SD_preorder[of alts]) (auto simp: A B not_le)
from as SD1 lottery1 lottery2
show "\<forall>i\<in>agents. SD (R i) (pmf_of_set A) (pmf_of_list ys)"
by safe (auto simp: preorder_on.SD_preorder[of alts] A B)
qed (insert as, simp_all)
qed
definition pref_classes where
"pref_classes alts le = preferred_alts le ` alts - {alts}"
primrec pref_classes_lists where
"pref_classes_lists [] = {}"
| "pref_classes_lists (xs#xss) = insert (\<Union>(set (xs#xss))) (pref_classes_lists xss)"
fun pref_classes_lists_aux where
"pref_classes_lists_aux acc [] = {}"
| "pref_classes_lists_aux acc (xs#xss) = insert acc (pref_classes_lists_aux (acc \<union> xs) xss)"
lemma pref_classes_lists_append:
"pref_classes_lists (xs @ ys) = (op \<union> (\<Union>set ys)) ` pref_classes_lists xs \<union> pref_classes_lists ys"
by (induction xs) auto
lemma pref_classes_lists_aux:
assumes "is_weak_ranking xss" "acc \<inter> (\<Union>set xss) = {}"
shows "pref_classes_lists_aux acc xss =
(insert acc ((\<lambda>A. A \<union> acc) ` pref_classes_lists (rev xss)) - {acc \<union> \<Union>(set xss)})"
using assms
proof (induction acc xss rule: pref_classes_lists_aux.induct [case_names Nil Cons])
case (Cons acc xs xss)
from Cons.prems have A: "acc \<inter> (xs \<union> \<Union>set xss) = {}" "xs \<noteq> {}"
by (simp_all add: is_weak_ranking_Cons)
from Cons.prems have "pref_classes_lists_aux (acc \<union> xs) xss =
insert (acc \<union> xs) ((\<lambda>A. A \<union> (acc \<union> xs)) `pref_classes_lists (rev xss)) -
{acc \<union> xs \<union> \<Union>set xss}"
by (intro Cons.IH) (auto simp: is_weak_ranking_Cons)
with Cons.prems have "pref_classes_lists_aux acc (xs # xss) =
insert acc (insert (acc \<union> xs) ((\<lambda>A. A \<union> (acc \<union> xs)) ` pref_classes_lists (rev xss)) -
{acc \<union> (xs \<union> \<Union>set xss)})"
by (simp_all add: is_weak_ranking_Cons pref_classes_lists_append image_image Un_ac)
also from A have "\<dots> = insert acc (insert (acc \<union> xs) ((\<lambda>x. x \<union> (acc \<union> xs)) `
pref_classes_lists (rev xss))) - {acc \<union> (xs \<union> \<Union>set xss)}"
by blast
finally show ?case
by (simp_all add: pref_classes_lists_append image_image Un_ac)
qed simp_all
lemma pref_classes_list_aux_hd_tl:
assumes "is_weak_ranking xss" "xss \<noteq> []"
shows "pref_classes_lists_aux (hd xss) (tl xss) = pref_classes_lists (rev xss) - {\<Union>set xss}"
proof -
from assms have A: "xss = hd xss # tl xss" by simp
from assms have "hd xss \<inter> \<Union>set (tl xss) = {} \<and> is_weak_ranking (tl xss)"
by (subst (asm) A, subst (asm) is_weak_ranking_Cons) simp_all
hence "pref_classes_lists_aux (hd xss) (tl xss) =
insert (hd xss) ((\<lambda>A. A \<union> hd xss) ` pref_classes_lists (rev (tl xss))) -
{hd xss \<union> \<Union>set (tl xss)}" by (intro pref_classes_lists_aux) simp_all
also have "hd xss \<union> \<Union>set (tl xss) = \<Union>(set xss)" by (subst (3) A, subst set_simps) simp_all
also have "insert (hd xss) ((\<lambda>A. A \<union> hd xss) ` pref_classes_lists (rev (tl xss))) =
pref_classes_lists (rev (tl xss) @ [hd xss])"
by (subst pref_classes_lists_append) auto
also have "rev (tl xss) @ [hd xss] = rev xss" by (subst (3) A) (simp only: rev.simps)
finally show ?thesis .
qed
lemma pref_classes_of_weak_ranking_aux:
assumes "is_weak_ranking xss"
shows "of_weak_ranking_Collect_ge xss ` (\<Union>(set xss)) = pref_classes_lists xss"
proof safe
fix X x assume "x \<in> X" "X \<in> set xss"
with assms show "of_weak_ranking_Collect_ge xss x \<in> pref_classes_lists xss"
by (induction xss) (auto simp: is_weak_ranking_Cons of_weak_ranking_Collect_ge_Cons')
next
fix x assume "x \<in> pref_classes_lists xss"
with assms show "x \<in> of_weak_ranking_Collect_ge xss ` \<Union>set xss"
proof (induction xss)
case (Cons xs xss)
from Cons.prems consider "x = xs \<union> \<Union>set xss" | "x \<in> pref_classes_lists xss" by auto
thus ?case
proof cases
assume "x = xs \<union> \<Union>set xss"
with Cons.prems show ?thesis
by (auto simp: is_weak_ranking_Cons of_weak_ranking_Collect_ge_Cons')
next
assume x: "x \<in> pref_classes_lists xss"
from Cons.prems x have "x \<in> of_weak_ranking_Collect_ge xss ` \<Union>set xss"
by (intro Cons.IH) (simp_all add: is_weak_ranking_Cons)
moreover from Cons.prems have "xs \<inter> \<Union>set xss = {}"
by (simp add: is_weak_ranking_Cons)
ultimately have "x \<in> of_weak_ranking_Collect_ge xss `
((xs \<union> \<Union>set xss) \<inter> {x. x \<notin> xs})" by blast
thus ?thesis by (simp add: of_weak_ranking_Collect_ge_Cons')
qed
qed simp_all
qed
(* TODO: Move *)
lemma is_weak_ranking_rev [simp]: "is_weak_ranking (rev xs) \<longleftrightarrow> is_weak_ranking xs"
by (simp add: is_weak_ranking_iff)
lemma eval_pref_classes_of_weak_ranking:
assumes "\<Union>(set xss) = alts" "is_weak_ranking xss" "alts \<noteq> {}"
shows "pref_classes alts (of_weak_ranking xss) = pref_classes_lists_aux (hd xss) (tl xss)"
proof -
have "pref_classes alts (of_weak_ranking xss) =
preferred_alts (of_weak_ranking xss) ` (\<Union>(set (rev xss))) - {\<Union>set xss}"
by (simp add: pref_classes_def assms)
also {
have "of_weak_ranking_Collect_ge (rev xss) ` (\<Union>(set (rev xss))) = pref_classes_lists (rev xss)"
using assms by (intro pref_classes_of_weak_ranking_aux) simp_all
also have "of_weak_ranking_Collect_ge (rev xss) = preferred_alts (of_weak_ranking xss)"
by (intro ext) (simp_all add: of_weak_ranking_Collect_ge_def preferred_alts_def)
finally have "preferred_alts (of_weak_ranking xss) ` (\<Union>(set (rev xss))) =
pref_classes_lists (rev xss)" .
}
also from assms have "pref_classes_lists (rev xss) - {\<Union>set xss} =
pref_classes_lists_aux (hd xss) (tl xss)"
by (intro pref_classes_list_aux_hd_tl [symmetric]) auto
finally show ?thesis by simp
qed
context preorder_on
begin
(* TODO: Move *)
lemma preferred_alts_subset: "preferred_alts le x \<subseteq> carrier"
unfolding preferred_alts_def using not_outside by blast
lemma SD_iff_pref_classes:
assumes "p \<in> lotteries_on carrier" "q \<in> lotteries_on carrier"
shows "p \<preceq>[SD(le)] q \<longleftrightarrow>
(\<forall>A\<in>pref_classes carrier le. measure_pmf.prob p A \<le> measure_pmf.prob q A)"
proof safe
fix A assume "p \<preceq>[SD(le)] q" "A \<in> pref_classes carrier le"
thus "measure_pmf.prob p A \<le> measure_pmf.prob q A"
by (auto simp: SD_preorder pref_classes_def)
next
assume A: "\<forall>A\<in>pref_classes carrier le. measure_pmf.prob p A \<le> measure_pmf.prob q A"
show "p \<preceq>[SD(le)] q"
proof (rule SD_preorderI)
fix x assume x: "x \<in> carrier"
show "measure_pmf.prob p (preferred_alts le x)
\<le> measure_pmf.prob q (preferred_alts le x)"
proof (cases "preferred_alts le x = carrier")
case False
with x have "preferred_alts le x \<in> pref_classes carrier le"
unfolding pref_classes_def by (intro DiffI imageI) simp_all
with A show ?thesis by simp
next
case True
from assms have "measure_pmf.prob p carrier = 1" "measure_pmf.prob q carrier = 1"
by (auto simp: measure_pmf.prob_eq_1 lotteries_on_def AE_measure_pmf_iff)
with True show ?thesis by simp
qed
qed (insert assms, simp_all)
qed
end
lemma (in strategyproof_an_sds) strategyproof':
assumes wf: "is_pref_profile R" "total_preorder_on alts Ri'" and i: "i \<in> agents"
shows "(\<exists>A\<in>pref_classes alts (R i). lottery_prob (sds (R(i := Ri'))) A <
lottery_prob (sds R) A) \<or>
(\<forall>A\<in>pref_classes alts (R i). lottery_prob (sds (R(i := Ri'))) A =
lottery_prob (sds R) A)"
proof -
from wf(1) interpret R: pref_profile_wf agents alts R .
from i interpret total_preorder_on alts "R i" by simp
from assms have "\<not> manipulable_profile R i Ri'" by (intro strategyproof)
moreover from wf i have "sds R \<in> lotteries" "sds (R(i := Ri')) \<in> lotteries"
by (simp_all add: sds_wf)
ultimately show ?thesis
by (fastforce simp: manipulable_profile_def strongly_preferred_def
SD_iff_pref_classes not_le not_less)
qed
lemma pref_classes_lists_aux_finite:
"A \<in> pref_classes_lists_aux acc xss \<Longrightarrow> finite acc \<Longrightarrow> (\<And>A. A \<in> set xss \<Longrightarrow> finite A)
\<Longrightarrow> finite A"
by (induction acc xss rule: pref_classes_lists_aux.induct) auto
lemma strategyproof_aux:
assumes wf: "prefs_from_table_wf agents alts xss1" "R1 = prefs_from_table xss1"
"prefs_from_table_wf agents alts xss2" "R2 = prefs_from_table xss2"
assumes sds: "strategyproof_an_sds agents alts sds" and i: "i \<in> agents" and j: "j \<in> agents"
assumes eq: "R1(i := R2 j) = R2" "the (map_of xss1 i) = xs"
"pref_classes_lists_aux (hd xs) (tl xs) = ps"
shows "(\<exists>A\<in>ps. (\<Sum>x\<in>A. pmf (sds R2) x) < (\<Sum>x\<in>A. pmf (sds R1) x)) \<or>
(\<forall>A\<in>ps. (\<Sum>x\<in>A. pmf (sds R2) x) = (\<Sum>x\<in>A. pmf (sds R1) x))"
proof -
from sds interpret strategyproof_an_sds agents alts sds .
let ?Ri' = "R2 j"
from wf j have wf': "is_pref_profile R1" "total_preorder_on alts ?Ri'"
by (auto intro: pref_profile_from_tableI pref_profile_wf.prefs_wf'(1))
from wf(1) i have "i \<in> set (map fst xss1)" by (simp add: prefs_from_table_wf_def)
with prefs_from_table_wfD(3)[OF wf(1)] eq
have "xs \<in> set (map snd xss1)" by force
note xs = prefs_from_table_wfD(2)[OF wf(1)] prefs_from_table_wfD(5,6)[OF wf(1) this]
{
fix p A assume A: "A \<in> pref_classes_lists_aux (hd xs) (tl xs)"
from xs have "xs \<noteq> []" by auto
with xs have "finite A"
by (intro pref_classes_lists_aux_finite[OF A])
(auto simp: is_finite_weak_ranking_def list.set_sel)
hence "lottery_prob p A = (\<Sum>x\<in>A. pmf p x)"
by (rule measure_measure_pmf_finite)
} note A = this
from strategyproof'[OF wf' i] eq have
"(\<exists>A\<in>pref_classes alts (R1 i). lottery_prob (sds R2) A < lottery_prob (sds R1) A) \<or>
(\<forall>A\<in>pref_classes alts (R1 i). lottery_prob (sds R2) A = lottery_prob (sds R1) A)"
by simp
also from wf eq i have "R1 i = of_weak_ranking xs"
by (simp add: prefs_from_table_map_of)
also from xs have "pref_classes alts (of_weak_ranking xs) = pref_classes_lists_aux (hd xs) (tl xs)"
unfolding is_finite_weak_ranking_def by (intro eval_pref_classes_of_weak_ranking) simp_all
finally show ?thesis by (simp add: A eq)
qed
lemma strategyproof_aux':
assumes wf: "prefs_from_table_wf agents alts xss1" "R1 \<equiv> prefs_from_table xss1"
"prefs_from_table_wf agents alts xss2" "R2 \<equiv> prefs_from_table xss2"
assumes sds: "strategyproof_an_sds agents alts sds" and i: "i \<in> agents" and j: "j \<in> agents"
assumes perm: "list_permutes ys alts"
defines "\<sigma> \<equiv> permutation_of_list ys" and "\<sigma>' \<equiv> inverse_permutation_of_list ys"
defines "xs \<equiv> the (map_of xss1 i)"
defines xs': "xs' \<equiv> map (op ` \<sigma>) (the (map_of xss2 j))"
defines "Ri' \<equiv> of_weak_ranking xs'"
assumes distinct_ps: "\<forall>A\<in>ps. distinct A"
assumes eq: "mset (map snd xss1) - {#the (map_of xss1 i)#} + {#xs'#} =
mset (map (map (op ` \<sigma>) \<circ> snd) xss2)"
"pref_classes_lists_aux (hd xs) (tl xs) = set ` ps"
shows "list_permutes ys alts \<and>
((\<exists>A\<in>ps. (\<Sum>x\<leftarrow>A. pmf (sds R2) (\<sigma>' x)) < (\<Sum>x\<leftarrow>A. pmf (sds R1) x)) \<or>
(\<forall>A\<in>ps. (\<Sum>x\<leftarrow>A. pmf (sds R2) (\<sigma>' x)) = (\<Sum>x\<leftarrow>A. pmf (sds R1) x)))"
(is "_ \<and> ?th")
proof
from perm have perm': "\<sigma> permutes alts" by (simp add: \<sigma>_def)
from sds interpret strategyproof_an_sds agents alts sds .
from wf(3) j have "j \<in> set (map fst xss2)" by (simp add: prefs_from_table_wf_def)
with prefs_from_table_wfD(3)[OF wf(3)]
have xs'_aux: "the (map_of xss2 j) \<in> set (map snd xss2)" by force
with wf(3) have xs'_aux': "is_finite_weak_ranking (the (map_of xss2 j))"
by (auto simp: prefs_from_table_wf_def)
hence "is_weak_ranking xs'" unfolding xs'
by (intro is_weak_ranking_map_inj permutes_inj_on[OF perm'])
(auto simp add: is_finite_weak_ranking_def)
moreover from this xs'_aux' have "is_finite_weak_ranking xs'"
by (auto simp: xs' is_finite_weak_ranking_def)
moreover from prefs_from_table_wfD(5)[OF wf(3) xs'_aux]
have "\<Union>set xs' = alts" unfolding xs'
by (simp add: image_Union [symmetric] permutes_image[OF perm'])
ultimately have wf_xs': "is_weak_ranking xs'" "is_finite_weak_ranking xs'" "\<Union>set xs' = alts"
by (simp_all add: is_finite_weak_ranking_def)
from this wf j have wf': "is_pref_profile R1" "total_preorder_on alts Ri'"
"is_pref_profile R2" "finite_total_preorder_on alts Ri'"
unfolding Ri'_def by (auto intro: pref_profile_from_tableI pref_profile_wf.prefs_wf'(1)
total_preorder_of_weak_ranking)
interpret R1: pref_profile_wf agents alts R1 by fact
interpret R2: pref_profile_wf agents alts R2 by fact
from wf(1) i have "i \<in> set (map fst xss1)" by (simp add: prefs_from_table_wf_def)
with prefs_from_table_wfD(3)[OF wf(1)] eq(2)
have "xs \<in> set (map snd xss1)" unfolding xs_def by force
note xs = prefs_from_table_wfD(2)[OF wf(1)] prefs_from_table_wfD(5,6)[OF wf(1) this]
from wf i wf' wf_xs' xs eq
have eq': "anonymous_profile (R1(i := Ri')) = image_mset (map (op ` \<sigma>)) (anonymous_profile R2)"
by (subst R1.anonymous_profile_update)
(simp_all add: Ri'_def weak_ranking_of_weak_ranking mset_map multiset.map_comp xs_def
anonymise_prefs_from_table prefs_from_table_map_of)
{
fix p A assume A: "A \<in> pref_classes_lists_aux (hd xs) (tl xs)"
from xs have "xs \<noteq> []" by auto
with xs have "finite A"
by (intro pref_classes_lists_aux_finite[OF A])
(auto simp: is_finite_weak_ranking_def list.set_sel)
hence "lottery_prob p A = (\<Sum>x\<in>A. pmf p x)"
by (rule measure_measure_pmf_finite)
} note A = this
from strategyproof'[OF wf'(1,2) i] eq' have
"(\<exists>A\<in>pref_classes alts (R1 i). lottery_prob (sds (R1(i := Ri'))) A < lottery_prob (sds R1) A) \<or>
(\<forall>A\<in>pref_classes alts (R1 i). lottery_prob (sds (R1(i := Ri'))) A = lottery_prob (sds R1) A)"
by simp
also from eq' i have "sds (R1(i := Ri')) = map_pmf \<sigma> (sds R2)"
unfolding \<sigma>_def by (intro sds_anonymous_neutral permutation_of_list_permutes perm wf'
pref_profile_wf.wf_update eq)
also from wf eq i have "R1 i = of_weak_ranking xs"
by (simp add: prefs_from_table_map_of xs_def)
also from xs have "pref_classes alts (of_weak_ranking xs) = pref_classes_lists_aux (hd xs) (tl xs)"
unfolding is_finite_weak_ranking_def by (intro eval_pref_classes_of_weak_ranking) simp_all
finally have "(\<exists>A\<in>ps. (\<Sum>x\<leftarrow>A. pmf (map_pmf \<sigma> (sds R2)) x) < (\<Sum>x\<leftarrow>A. pmf (sds R1) x)) \<or>
(\<forall>A\<in>ps. (\<Sum>x\<leftarrow>A. pmf (map_pmf \<sigma> (sds R2)) x) = (\<Sum>x\<leftarrow>A. pmf (sds R1) x))"
using distinct_ps
by (simp add: A eq setsum.distinct_set_conv_list del: measure_map_pmf)
also from perm' have "pmf (map_pmf \<sigma> (sds R2)) = (\<lambda>x. pmf (sds R2) (inv \<sigma> x))"
using pmf_map_inj'[of \<sigma> _ "inv \<sigma> x" for x]
by (simp add: fun_eq_iff permutes_inj permutes_inverses)
also from perm have "inv \<sigma> = \<sigma>'" unfolding \<sigma>_def \<sigma>'_def
by (rule inverse_permutation_of_list_correct [symmetric])
finally show ?th .
qed fact+
ML_file "sds_automation.ML"
end |
[STATEMENT]
lemma scale_add3[simp]: "ccw 0 a (x *\<^sub>R a + b) \<longleftrightarrow> ccw 0 a b"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
{
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
assume "x = 0"
[PROOF STATE]
proof (state)
this:
x = 0
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
hence ?thesis
[PROOF STATE]
proof (prove)
using this:
x = 0
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
x = 0 \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
x = 0 \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
{
[PROOF STATE]
proof (state)
this:
x = 0 \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
assume "x > 0"
[PROOF STATE]
proof (state)
this:
0 < x
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
hence ?thesis
[PROOF STATE]
proof (prove)
using this:
0 < x
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
using add3_self scaleR1_eq
[PROOF STATE]
proof (prove)
using this:
0 < x
ccw (0::'a) ?p (?p + ?q) = ccw (0::'a) ?p ?q
0 < ?e \<Longrightarrow> ccw (0::'a) (?e *\<^sub>R ?a) ?b = ccw (0::'a) ?a ?b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
0 < x \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
0 < x \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
{
[PROOF STATE]
proof (state)
this:
0 < x \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
assume "x < 0"
[PROOF STATE]
proof (state)
this:
x < 0
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
define x' where "x' = - x"
[PROOF STATE]
proof (state)
this:
x' = - x
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
hence "x = -x'" "x' > 0"
[PROOF STATE]
proof (prove)
using this:
x' = - x
goal (1 subgoal):
1. x = - x' &&& 0 < x'
[PROOF STEP]
using \<open>x < 0\<close>
[PROOF STATE]
proof (prove)
using this:
x' = - x
x < 0
goal (1 subgoal):
1. x = - x' &&& 0 < x'
[PROOF STEP]
by simp_all
[PROOF STATE]
proof (state)
this:
x = - x'
0 < x'
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
hence "ccw 0 a (x *\<^sub>R a + b) = ccw 0 (x' *\<^sub>R a + - b) (x' *\<^sub>R a)"
[PROOF STATE]
proof (prove)
using this:
x = - x'
0 < x'
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) (x' *\<^sub>R a + - b) (x' *\<^sub>R a)
[PROOF STEP]
by (subst uminus1[symmetric]) simp
[PROOF STATE]
proof (state)
this:
ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) (x' *\<^sub>R a + - b) (x' *\<^sub>R a)
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) (x' *\<^sub>R a + - b) (x' *\<^sub>R a)
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
have "\<dots> = ccw 0 (- b) a"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ccw (0::'a) (x' *\<^sub>R a + - b) (x' *\<^sub>R a) = ccw (0::'a) (- b) a
[PROOF STEP]
unfolding add2_self
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ccw (0::'a) (- b) (x' *\<^sub>R a) = ccw (0::'a) (- b) a
[PROOF STEP]
by (simp add: \<open>x' > 0\<close>)
[PROOF STATE]
proof (state)
this:
ccw (0::'a) (x' *\<^sub>R a + - b) (x' *\<^sub>R a) = ccw (0::'a) (- b) a
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
ccw (0::'a) (x' *\<^sub>R a + - b) (x' *\<^sub>R a) = ccw (0::'a) (- b) a
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
have "\<dots> = ccw 0 a b"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ccw (0::'a) (- b) a = ccw (0::'a) a b
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
ccw (0::'a) (- b) a = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
have ?thesis
[PROOF STATE]
proof (prove)
using this:
ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
x < 0 \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
x = 0 \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
0 < x \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
x < 0 \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
x = 0 \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
0 < x \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
x < 0 \<Longrightarrow> ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal (1 subgoal):
1. ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
[PROOF STEP]
by arith
[PROOF STATE]
proof (state)
this:
ccw (0::'a) a (x *\<^sub>R a + b) = ccw (0::'a) a b
goal:
No subgoals!
[PROOF STEP]
qed |
{-# LANGUAGE ForeignFunctionInterface, GeneralizedNewtypeDeriving #-}
module Numerical.HBLAS.BLAS.FFI.Level2 where
import Foreign.Ptr
import Foreign()
import Foreign.C.Types
import Data.Complex
import Numerical.HBLAS.BLAS.FFI
type GbmvFunFFI sc el =
CBLAS_ORDERT -> CBLAS_TRANSPOSET -> CInt -> CInt
-> CInt -> CInt -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_sgbmv"
cblas_sgbmv_unsafe :: GbmvFunFFI Float Float
foreign import ccall unsafe "cblas_dgbmv"
cblas_dgbmv_unsafe :: GbmvFunFFI Double Double
foreign import ccall unsafe "cblas_cgbmv"
cblas_cgbmv_unsafe :: GbmvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall unsafe "cblas_zgbmv"
cblas_zgbmv_unsafe :: GbmvFunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall "cblas_sgbmv"
cblas_sgbmv_safe :: GbmvFunFFI Float Float
foreign import ccall "cblas_dgbmv"
cblas_dgbmv_safe :: GbmvFunFFI Double Double
foreign import ccall "cblas_cgbmv"
cblas_cgbmv_safe :: GbmvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall "cblas_zgbmv"
cblas_zgbmv_safe :: GbmvFunFFI (Ptr (Complex Double)) (Complex Double)
--void cblas_sgbmv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE TransA, CInt M, CInt N,
-- CInt KL, CInt KU, Float alpha, Float *A, CInt lda, Float *X, CInt incX, Float beta, Float *Y, CInt incY);
--void cblas_dgbmv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE TransA, CInt M, CInt N,
-- CInt KL, CInt KU, Double alpha, Double *A, CInt lda, Double *X, CInt incX, Double beta, Double *Y, CInt incY);
--void cblas_cgbmv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE TransA, CInt M, CInt N,
-- CInt KL, CInt KU, Float *alpha, Float *A, CInt lda, Float *X, CInt incX, Float *beta, Float *Y, CInt incY);
--void cblas_zgbmv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE TransA, CInt M, CInt N,
-- CInt KL, CInt KU, Double *alpha, Double *A, CInt lda, Double *X, CInt incX, Double *beta, Double *Y, CInt incY);
{-
matrix vector product for general matrices
perform one of the matrix-vector operations y :=
alpha*A*x + beta*y, or y := alpha*A'*x + beta*y,
-}
type GemvFunFFI sc el =
CBLAS_ORDERT -> CBLAS_TRANSPOSET -> CInt -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_sgemv"
cblas_sgemv_unsafe :: GemvFunFFI Float Float
foreign import ccall safe "cblas_sgemv"
cblas_sgemv_safe :: GemvFunFFI Float Float
foreign import ccall unsafe "cblas_dgemv"
cblas_dgemv_unsafe :: GemvFunFFI Double Double
foreign import ccall safe "cblas_dgemv"
cblas_dgemv_safe :: GemvFunFFI Double Double
foreign import ccall unsafe "cblas_cgemv"
cblas_cgemv_unsafe :: GemvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall safe "cblas_cgemv"
cblas_cgemv_safe :: GemvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall unsafe "cblas_zgemv"
cblas_zgemv_unsafe :: GemvFunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall safe "cblas_zgemv"
cblas_zgemv_safe :: GemvFunFFI (Ptr (Complex Double)) (Complex Double)
--void cblas_sgemv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE trans, CInt m, CInt n,
-- Float alpha, Float *a, CInt lda, Float *x, CInt incx, Float beta, Float *y, CInt incy);
--void cblas_dgemv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE trans, CInt m, CInt n,
-- Double alpha, Double *a, CInt lda, Double *x, CInt incx, Double beta, Double *y, CInt incy);
--void cblas_cgemv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE trans, CInt m, CInt n,
-- Float *alpha, Float *a, CInt lda, Float *x, CInt incx, Float *beta, Float *y, CInt incy);
--void cblas_zgemv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE trans, CInt m, CInt n,
-- Double *alpha, Double *a, CInt lda, Double *x, CInt incx, Double *beta, Double *y, CInt incy);
-- perform the rank 1 operation A := alpha*x*y' + A,
type GerxFunFFI scale el = CBLAS_ORDERT -> CInt -> CInt -> scale -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_sger" cblas_sger_unsafe ::
GerxFunFFI Float Float
foreign import ccall safe "cblas_sger" cblas_sger_safe ::
GerxFunFFI Float Float
foreign import ccall unsafe "cblas_dger" cblas_dger_unsafe ::
GerxFunFFI Double Double
foreign import ccall safe "cblas_dger" cblas_dger_safe ::
GerxFunFFI Double Double
foreign import ccall unsafe "cblas_cgerc" cblas_cgerc_unsafe ::
GerxFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall unsafe "cblas_zgerc" cblas_zgerc_unsafe ::
GerxFunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall safe "cblas_cgerc" cblas_cgerc_safe ::
GerxFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall safe "cblas_zgerc" cblas_zgerc_safe ::
GerxFunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall unsafe "cblas_cgeru" cblas_cgeru_unsafe ::
GerxFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall unsafe "cblas_zgeru" cblas_zgeru_unsafe ::
GerxFunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall safe "cblas_cgeru" cblas_cgeru_safe ::
GerxFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall safe "cblas_zgeru" cblas_zgeru_safe ::
GerxFunFFI (Ptr (Complex Double)) (Complex Double)
--void cblas_sger ( enum CBLAS_ORDER order, CInt M, CInt N, Float alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *A, CInt lda);
--void cblas_dger ( enum CBLAS_ORDER order, CInt M, CInt N, Double alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *A, CInt lda);
--void cblas_cgeru( enum CBLAS_ORDER order, CInt M, CInt N, Float *alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *A, CInt lda);
--void cblas_cgerc( enum CBLAS_ORDER order, CInt M, CInt N, Float *alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *A, CInt lda);
--void cblas_zgeru( enum CBLAS_ORDER order, CInt M, CInt N, Double *alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *A, CInt lda);
--void cblas_zgerc( enum CBLAS_ORDER order, CInt M, CInt N, Double *alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *A, CInt lda);
type HbmvFunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_chbmv"
cblas_chbmv_unsafe :: HbmvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall safe "cblas_chbmv"
cblas_chbmv_safe :: HbmvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall unsafe "cblas_zhbmv"
cblas_zhbmv_unsafe :: HbmvFunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall safe "cblas_zhbmv"
cblas_zhbmv_safe :: HbmvFunFFI (Ptr (Complex Double)) (Complex Double)
--void cblas_chbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, CInt K,
-- Float *alpha, Float *A, CInt lda, Float *X, CInt incX, Float *beta, Float *Y, CInt incY);
--void cblas_zhbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, CInt K,
-- Double *alpha, Double *A, CInt lda, Double *X, CInt incX, Double *beta, Double *Y, CInt incY);
type HemvFunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_chemv"
cblas_chemv_unsafe :: HemvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall safe "cblas_chemv"
cblas_chemv_safe :: HemvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall unsafe "cblas_zhemv"
cblas_zhemv_unsafe :: HemvFunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall safe "cblas_zhemv"
cblas_zhemv_safe :: HemvFunFFI (Ptr (Complex Double)) (Complex Double)
--void cblas_chemv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float *alpha, Float *A,
-- CInt lda, Float *X, CInt incX, Float *beta, Float *Y, CInt incY);
--void cblas_zhemv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double *alpha, Double *A,
-- CInt lda, Double *X, CInt incX, Double *beta, Double *Y, CInt incY);
type HerFunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_cher"
cblas_cher_unsafe :: HerFunFFI Float (Complex Float)
foreign import ccall safe "cblas_cher"
cblas_cher_safe :: HerFunFFI Float (Complex Float)
foreign import ccall unsafe "cblas_zher"
cblas_zher_unsafe :: HerFunFFI Double (Complex Double)
foreign import ccall safe "cblas_zher"
cblas_zher_safe :: HerFunFFI Double (Complex Double)
--void cblas_cher( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *A, CInt lda);
--void cblas_zher( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *A, CInt lda);
type Her2FunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_cher2"
cblas_cher2_unsafe :: Her2FunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall safe "cblas_cher2"
cblas_cher2_safe :: Her2FunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall unsafe "cblas_zher2"
cblas_zher2_unsafe :: Her2FunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall safe "cblas_zher2"
cblas_zher2_safe :: Her2FunFFI (Ptr (Complex Double)) (Complex Double)
--void cblas_cher2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float *alpha, Float *X, CInt incX,
-- Float *Y, CInt incY, Float *A, CInt lda);
--void cblas_zher2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double *alpha, Double *X, CInt incX,
-- Double *Y, CInt incY, Double *A, CInt lda);
type HpmvFunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt
-> sc -> Ptr el -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_chpmv"
cblas_chpmv_unsafe :: HpmvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall safe "cblas_chpmv"
cblas_chpmv_safe :: HpmvFunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall unsafe "cblas_zhpmv"
cblas_zhpmv_unsafe :: HpmvFunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall safe "cblas_zhpmv"
cblas_zhpmv_safe :: HpmvFunFFI (Ptr (Complex Double)) (Complex Double)
--void cblas_chpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N,
-- Float *alpha, Float *Ap, Float *X, CInt incX, Float *beta, Float *Y, CInt incY);
--void cblas_zhpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N,
-- Double *alpha, Double *Ap, Double *X, CInt incX, Double *beta, Double *Y, CInt incY);
type HprFunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> IO ()
foreign import ccall unsafe "cblas_chpr"
cblas_chpr_unsafe :: HprFunFFI Float (Complex Float)
foreign import ccall safe "cblas_chpr"
cblas_chpr_safe :: HprFunFFI Float (Complex Float)
foreign import ccall unsafe "cblas_zhpr"
cblas_zhpr_unsafe :: HprFunFFI Double (Complex Double)
foreign import ccall safe "cblas_zhpr"
cblas_zhpr_safe :: HprFunFFI Double (Complex Double)
--void cblas_chpr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *A);
--void cblas_zhpr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *A);
type Hpr2FunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> IO ()
foreign import ccall unsafe "cblas_chpr2"
cblas_chpr2_unsafe :: Hpr2FunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall safe "cblas_chpr2"
cblas_chpr2_safe :: Hpr2FunFFI (Ptr (Complex Float)) (Complex Float)
foreign import ccall unsafe "cblas_zhpr2"
cblas_zhpr2_unsafe :: Hpr2FunFFI (Ptr (Complex Double)) (Complex Double)
foreign import ccall safe "cblas_zhpr2"
cblas_zhpr2_safe :: Hpr2FunFFI (Ptr (Complex Double)) (Complex Double)
--void cblas_chpr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float *alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *Ap);
--void cblas_zhpr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double *alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *Ap);
type SbmvFunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_ssbmv"
cblas_ssbmv_unsafe :: SbmvFunFFI Float Float
foreign import ccall safe "cblas_ssbmv"
cblas_ssbmv_safe :: SbmvFunFFI Float Float
foreign import ccall unsafe "cblas_dsbmv"
cblas_dsbmv_unsafe :: SbmvFunFFI Double Double
foreign import ccall safe "cblas_dsbmv"
cblas_dsbmv_safe :: SbmvFunFFI Double Double
--void cblas_ssbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, CInt K, Float alpha, Float *A,
-- CInt lda, Float *X, CInt incX, Float beta, Float *Y, CInt incY);
--void cblas_dsbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, CInt K, Double alpha, Double *A,
-- CInt lda, Double *X, CInt incX, Double beta, Double *Y, CInt incY);
---------------
--- | packed symmetric matrix * vector product y:= alpha * Av + beta * y
---------------
type SpmvFunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt
-> sc -> Ptr el -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_sspmv"
cblas_sspmv_unsafe :: SpmvFunFFI Float Float
foreign import ccall safe "cblas_sspmv"
cblas_sspmv_safe :: SpmvFunFFI Float Float
foreign import ccall unsafe "cblas_dspmv"
cblas_dspmv_unsafe :: SpmvFunFFI Double Double
foreign import ccall safe "cblas_dspmv"
cblas_dspmv_safe :: SpmvFunFFI Double Double
--void cblas_sspmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *Ap,
-- Float *X, CInt incX, Float beta, Float *Y, CInt incY);
--void cblas_dspmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *Ap,
-- Double *X, CInt incX, Double beta, Double *Y, CInt incY);
type SprFunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> IO ()
foreign import ccall unsafe "cblas_sspr"
cblas_sspr_unsafe :: SprFunFFI Float Float
foreign import ccall safe "cblas_sspr"
cblas_sspr_safe :: SprFunFFI Float Float
foreign import ccall unsafe "cblas_dspr"
cblas_dspr_unsafe :: SprFunFFI Double Double
foreign import ccall safe "cblas_dspr"
cblas_dspr_safe :: SprFunFFI Double Double
--void cblas_sspr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *Ap);
--void cblas_dspr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *Ap);
type Spr2FunFFI sc el =
CBLAS_ORDERT -> CBLAS_UPLOT -> CInt
-> sc -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> IO ()
foreign import ccall unsafe "cblas_sspr2"
cblas_sspr2_unsafe :: Spr2FunFFI Float Float
foreign import ccall safe "cblas_sspr2"
cblas_sspr2_safe :: Spr2FunFFI Float Float
foreign import ccall unsafe "cblas_dspr2"
cblas_dspr2_unsafe :: Spr2FunFFI Double Double
foreign import ccall safe "cblas_dspr2"
cblas_dspr2_safe :: Spr2FunFFI Double Double
--void cblas_sspr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *A);
--void cblas_dspr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *A);
----------------------------------
---- | (unpacked) symmetric matrix vector product x:=Av, writes result x into v
---------------------------------
type SymvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> el -> Ptr el -> CInt ->
Ptr el -> CInt -> el -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_ssymv"
cblas_ssymv_unsafe :: SymvFunFFI Float
foreign import ccall safe "cblas_ssymv"
cblas_ssymv_safe :: SymvFunFFI Float
foreign import ccall unsafe "cblas_dsymv"
cblas_dsymv_unsafe :: SymvFunFFI Double
foreign import ccall safe "cblas_dsymv"
cblas_dsymv_safe :: SymvFunFFI Double
--void cblas_ssymv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *A,
-- CInt lda, Float *X, CInt incX, Float beta, Float *Y, CInt incY);
--void cblas_dsymv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *A,
-- CInt lda, Double *X, CInt incX, Double beta, Double *Y, CInt incY);
type SyrFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> el -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_ssyr"
cblas_ssyr_unsafe :: SyrFunFFI Float
foreign import ccall safe "cblas_ssyr"
cblas_ssyr_safe :: SyrFunFFI Float
foreign import ccall unsafe "cblas_dsyr"
cblas_dsyr_unsafe :: SyrFunFFI Double
foreign import ccall safe "cblas_dsyr"
cblas_dsyr_safe :: SyrFunFFI Double
--void cblas_ssyr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *A, CInt lda);
--void cblas_dsyr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *A, CInt lda);
type Syr2FunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> el -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_ssyr2"
cblas_ssyr2_unsafe :: Syr2FunFFI Float
foreign import ccall safe "cblas_ssyr2"
cblas_ssyr2_safe :: Syr2FunFFI Float
foreign import ccall unsafe "cblas_dsyr2"
cblas_dsyr2_unsafe :: Syr2FunFFI Double
foreign import ccall safe "cblas_dsyr2"
cblas_dsyr2_safe :: Syr2FunFFI Double
--void cblas_ssyr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X,
-- CInt incX, Float *Y, CInt incY, Float *A, CInt lda);
--void cblas_dsyr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X,
-- CInt incX, Double *Y, CInt incY, Double *A, CInt lda);
type TbmvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->
CInt -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_stbmv"
cblas_stbmv_unsafe :: TbmvFunFFI Float
foreign import ccall safe "cblas_stbmv"
cblas_stbmv_safe :: TbmvFunFFI Float
foreign import ccall unsafe "cblas_dtbmv"
cblas_dtbmv_unsafe :: TbmvFunFFI Double
foreign import ccall safe "cblas_dtbmv"
cblas_dtbmv_safe :: TbmvFunFFI Double
foreign import ccall unsafe "cblas_ctbmv"
cblas_ctbmv_unsafe :: TbmvFunFFI (Complex Float)
foreign import ccall safe "cblas_ctbmv"
cblas_ctbmv_safe :: TbmvFunFFI (Complex Float)
foreign import ccall unsafe "cblas_ztbmv"
cblas_ztbmv_unsafe :: TbmvFunFFI (Complex Double)
foreign import ccall safe "cblas_ztbmv"
cblas_ztbmv_safe :: TbmvFunFFI (Complex Double)
--void cblas_stbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, CInt K, Float *A, CInt lda, Float *X, CInt incX);
--void cblas_dtbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, CInt K, Double *A, CInt lda, Double *X, CInt incX);
--void cblas_ctbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, CInt K, Float *A, CInt lda, Float *X, CInt incX);
--void cblas_ztbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, CInt K, Double *A, CInt lda, Double *X, CInt incX);
----------------
--- | solves Ax=v where A is k+1 banded triangular matrix, and x and
----------------
type TbsvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->
CInt -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_stbsv"
cblas_stbsv_unsafe :: TbsvFunFFI Float
foreign import ccall safe "cblas_stbsv"
cblas_stbsv_safe :: TbsvFunFFI Float
foreign import ccall unsafe "cblas_dtbsv"
cblas_dtbsv_unsafe :: TbsvFunFFI Double
foreign import ccall safe "cblas_dtbsv"
cblas_dtbsv_safe :: TbsvFunFFI Double
foreign import ccall unsafe "cblas_ctbsv"
cblas_ctbsv_unsafe :: TbsvFunFFI (Complex Float)
foreign import ccall safe "cblas_ctbsv"
cblas_ctbsv_safe :: TbsvFunFFI (Complex Float)
foreign import ccall unsafe "cblas_ztbsv"
cblas_ztbsv_unsafe :: TbsvFunFFI (Complex Double)
foreign import ccall safe "cblas_ztbsv"
cblas_ztbsv_safe :: TbsvFunFFI (Complex Double)
--void cblas_stbsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, CInt K, Float *A, CInt lda, Float *X, CInt incX);
--void cblas_dtbsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, CInt K, Double *A, CInt lda, Double *X, CInt incX);
--void cblas_ctbsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, CInt K, Float *A, CInt lda, Float *X, CInt incX);
--void cblas_ztbsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, CInt K, Double *A, CInt lda, Double *X, CInt incX);
-------------------------------------------------------------------------
-- | matrix vector product Av, writes result into v, where A is a packed triangular nxn matrix
-------------------------------------------------------------------------
type TpmvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->
CInt -> Ptr el -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_stpmv"
cblas_stpmv_unsafe :: TpmvFunFFI Float
foreign import ccall safe "cblas_stpmv"
cblas_stpmv_safe :: TpmvFunFFI Float
foreign import ccall unsafe "cblas_dtpmv"
cblas_dtpmv_unsafe :: TpmvFunFFI Double
foreign import ccall safe "cblas_dtpmv"
cblas_dtpmv_safe :: TpmvFunFFI Double
foreign import ccall unsafe "cblas_ctpmv"
cblas_ctpmv_unsafe :: TpmvFunFFI (Complex Float)
foreign import ccall safe "cblas_ctpmv"
cblas_ctpmv_safe :: TpmvFunFFI (Complex Float)
foreign import ccall unsafe "cblas_ztpmv"
cblas_ztpmv_unsafe :: TpmvFunFFI (Complex Double)
foreign import ccall safe "cblas_ztpmv"
cblas_ztpmv_safe :: TpmvFunFFI (Complex Double)
--void cblas_stpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, Float *Ap, Float *X, CInt incX);
--void cblas_dtpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, Double *Ap, Double *X, CInt incX);
--void cblas_ctpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, Float *Ap, Float *X, CInt incX);
--void cblas_ztpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, Double *Ap, Double *X, CInt incX);
--------------------------------------------------
--- | solve Ax=v where A is a nxn packed triangular matrix, v vector input, writes the solution into x.
--------------------------------------------------
type TpsvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->
CInt -> Ptr el -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_stpsv"
cblas_stpsv_unsafe :: TpsvFunFFI Float
foreign import ccall safe "cblas_stpsv"
cblas_stpsv_safe :: TpsvFunFFI Float
foreign import ccall unsafe "cblas_dtpsv"
cblas_dtpsv_unsafe :: TpsvFunFFI Double
foreign import ccall safe "cblas_dtpsv"
cblas_dtpsv_safe :: TpsvFunFFI Double
foreign import ccall unsafe "cblas_ctpsv"
cblas_ctpsv_unsafe :: TpsvFunFFI (Complex Float)
foreign import ccall safe "cblas_ctpsv"
cblas_ctpsv_safe :: TpsvFunFFI (Complex Float)
foreign import ccall unsafe "cblas_ztpsv"
cblas_ztpsv_unsafe :: TpsvFunFFI (Complex Double)
foreign import ccall safe "cblas_ztpsv"
cblas_ztpsv_safe :: TpsvFunFFI (Complex Double)
--void cblas_stpsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, Float *Ap, Float *X, CInt incX);
--void cblas_dtpsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, Double *Ap, Double *X, CInt incX);
--void cblas_ctpsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, Float *Ap, Float *X, CInt incX);
--void cblas_ztpsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,
-- CInt N, Double *Ap, Double *X, CInt incX);
type TrmvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->
CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_strmv"
cblas_strmv_unsafe :: TrmvFunFFI Float
foreign import ccall safe "cblas_strmv"
cblas_strmv_safe :: TrmvFunFFI Float
foreign import ccall unsafe "cblas_dtrmv"
cblas_dtrmv_unsafe :: TrmvFunFFI Double
foreign import ccall safe "cblas_dtrmv"
cblas_dtrmv_safe :: TrmvFunFFI Double
foreign import ccall unsafe "cblas_ctrmv"
cblas_ctrmv_unsafe :: TrmvFunFFI (Complex Float)
foreign import ccall safe "cblas_ctrmv"
cblas_ctrmv_safe :: TrmvFunFFI (Complex Float)
foreign import ccall unsafe "cblas_ztrmv"
cblas_ztrmv_unsafe :: TrmvFunFFI (Complex Double)
foreign import ccall safe "cblas_ztrmv"
cblas_ztrmv_safe :: TrmvFunFFI (Complex Double)
--void cblas_strmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Float *A, CInt lda, Float *X, CInt incX);
--void cblas_dtrmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Double *A, CInt lda, Double *X, CInt incX);
--void cblas_ctrmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Float *A, CInt lda, Float *X, CInt incX);
--void cblas_ztrmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Double *A, CInt lda, Double *X, CInt incX);
--STRSV - solve one of the systems of equations A*x = b, or A'*x = b, where A is a (non)unit upper(/lower) triangular matrix
type TrsvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->
CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()
foreign import ccall unsafe "cblas_strsv"
cblas_strsv_unsafe :: TrsvFunFFI Float
foreign import ccall safe "cblas_strsv"
cblas_strsv_safe :: TrsvFunFFI Float
foreign import ccall unsafe "cblas_dtrsv"
cblas_dtrsv_unsafe :: TrsvFunFFI Double
foreign import ccall safe "cblas_dtrsv"
cblas_dtrsv_safe :: TrsvFunFFI Double
foreign import ccall unsafe "cblas_ctrsv"
cblas_ctrsv_unsafe :: TrsvFunFFI (Complex Float)
foreign import ccall safe "cblas_ctrsv"
cblas_ctrsv_safe :: TrsvFunFFI (Complex Float)
foreign import ccall unsafe "cblas_ztrsv"
cblas_ztrsv_unsafe :: TrsvFunFFI (Complex Double)
foreign import ccall safe "cblas_ztrsv"
cblas_ztrsv_safe :: TrsvFunFFI (Complex Double)
--void cblas_strsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Float *A, CInt lda, Float *X, CInt incX);
--void cblas_dtrsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Double *A, CInt lda, Double *X, CInt incX);
--void cblas_ctrsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Float *A, CInt lda, Float *X, CInt incX);
--void cblas_ztrsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Double *A, CInt lda, Double *X, CInt incX);
|
namespace Foo
def x := 10
end Foo
#check Foo.x
open Foo
#check x
theorem ex1 : x = Foo.x := rfl
namespace Foo
def f x y := x + y + 1
scoped infix:70 "^^" => f
#check 1 ^^ 2
theorem ex1 : x ^^ y = f x y := rfl
end Foo
#check 1 ^^ 2 -- works because we have an `open Foo` above
theorem ex2 : x ^^ y = f x y := rfl
theorem ex3 : x ^^ y = Foo.f x y := rfl
|
I have a lot of experience about swimming pool. I have worked for 10 years with it. Today i come here to share my experience to you guys.If you have any question about swimming pool.Please leave comment here, I will answer everything.
I am leaving in Quang Binh, Vietnam and I am building a boat shape swimming pool next to a lake. Half of the swimming pool inground and other half above the ground to look like a boat. I ask a local contractor to do it, but they never did this kind of swimming pool, only conventional inground swimming pool. They usually do all the swimming pool with concrete pillar every 4 meters (13ft) and brick wall in between. I am worry that the bricks are not strong enough to support the water pressure. Do you think it will be ok like that?
I wonder why you decided to choose this particular profession? Do you like it really? I just do research, on the basis of which people choose their profession. if interested, you can read my previous research papers PapersWizard it seems to me that it will be very informative for you. |
SUBROUTINE CONPDV (XD,YD,ZD,NDP)
C
C +-----------------------------------------------------------------+
C | |
C | Copyright (C) 1986 by UCAR |
C | University Corporation for Atmospheric Research |
C | All Rights Reserved |
C | |
C | NCARGRAPHICS Version 1.00 |
C | |
C +-----------------------------------------------------------------+
C
C
C
C PLOT THE DATA VALUES ON THE CONTOUR MAP
C CURRENTLY UP TO 10 CHARACTERS FOR EACH VALUE ARE DISPLAYED
C
C
C
COMMON /CONRA1/ CL(30) ,NCL ,OLDZ ,PV(210) ,
1 FINC ,HI ,FLO
COMMON /CONRA2/ REPEAT ,EXTRAP ,PER ,MESS ,
1 ISCALE ,LOOK ,PLDVLS ,GRD ,
2 CINC ,CHILO ,CON ,LABON ,
3 PMIMX ,SCALE ,FRADV ,EXTRI ,
4 BPSIZ ,LISTOP
COMMON /CONRA3/ IREC
COMMON /CONRA4/ NCP ,NCPSZ
COMMON /CONRA5/ NIT ,ITIPV
COMMON /CONRA6/ XST ,YST ,XED ,YED ,
1 STPSZ ,IGRAD ,IG ,XRG ,
2 YRG ,BORD ,PXST ,PYST ,
3 PXED ,PYED ,ITICK
COMMON /CONRA7/ TITLE ,ICNT ,ITLSIZ
COMMON /CONRA8/ IHIGH ,INMAJ ,INLAB ,INDAT ,
1 LEN ,IFMT ,LEND ,
2 IFMTD ,ISIZEP ,INMIN
COMMON /CONRA9/ ICOORD(500),NP ,MXXY ,TR ,
1 BR ,TL ,BL ,CONV ,
2 XN ,YN ,ITLL ,IBLL ,
3 ITRL ,IBRL ,XC ,YC ,
4 ITLOC(210) ,JX ,JY ,ILOC ,
5 ISHFCT ,XO ,YO ,IOC ,NC
COMMON /CONR10/ NT ,NL ,NTNL ,JWIPT ,
1 JWIWL ,JWIWP ,JWIPL ,IPR ,
2 ITPV
COMMON /CONR11/ NREP ,NCRT ,ISIZEL ,
1 MINGAP ,ISIZEM ,
2 TENS
COMMON /CONR12/ IXMAX ,IYMAX ,XMAX ,YMAX
LOGICAL REPEAT ,EXTRAP ,PER ,MESS ,
1 LOOK ,PLDVLS ,GRD ,LABON ,
2 PMIMX ,FRADV ,EXTRI ,CINC ,
3 TITLE ,LISTOP ,CHILO ,CON
COMMON /CONR15/ ISTRNG
CHARACTER*64 ISTRNG
COMMON /CONR16/ FORM
CHARACTER*10 FORM
COMMON /CONR17/ NDASH, IDASH, EDASH
CHARACTER*10 NDASH, IDASH, EDASH
COMMON /RANINT/ IRANMJ, IRANMN, IRANTX
COMMON /RAQINT/ IRAQMJ, IRAQMN, IRAQTX
COMMON /RASINT/ IRASMJ, IRASMN, IRASTX
C
C
CHARACTER*10 ISTR
DIMENSION XD(1) ,YD(1) ,ZD(1)
C
SAVE
C
C DATA TO CONVERT 0-32767 COORIDNATES TO 1-1024 VALUES
C
DATA TRANS/32./
C
C SET INTENSITY
C
IF (INDAT .NE. 1) THEN
CALL GSTXCI (INDAT)
ELSE
CALL GSTXCI (IRANTX)
ENDIF
C
C SET FORMAT IF NONE SPECIFIED
C
IF (LEN .NE. 0) GO TO 110
FORM = '(G10.3)'
LEN = LEND
IFMT = IFMTD
C
C LOOP AND PLOT ALL VALUES
C
110 DO 120 K=1,NDP
CALL FL2INT (XD(K),YD(K),MX,MY)
MX = IFIX(FLOAT(MX)/TRANS)+1
MY = IFIX(FLOAT(MY)/TRANS)+1
C
C + NOAO - FTN internal write rewritten as call to encode for IRAF
C
C WRITE(ISTR,FORM)ZD(K)
call encode (len, form, istr, zd(k))
C
C - NOAO
C
C POSITION STRINGS PROPERLY IF COORDS ARE IN PAU'S
C
CALL GQCNTN(IER,ICN)
CALL GSELNT(0)
XC = CPUX(MX)
YC = CPUY(MY)
C
CALL WTSTR(XC,YC,ISTR,ISIZEP,0,0)
CALL GSELNT(ICN)
120 CONTINUE
IF (INDAT .NE. 1) THEN
CALL GSTXCI (IRANTX)
ENDIF
RETURN
END
|
[STATEMENT]
lemma auto_weaken_pre_to_imp_nf:
"(A\<longrightarrow>B\<longrightarrow>C) = (A\<and>B \<longrightarrow> C)"
"((A\<and>B)\<and>C) = (A\<and>B\<and>C)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (A \<longrightarrow> B \<longrightarrow> C) = (A \<and> B \<longrightarrow> C) &&& ((A \<and> B) \<and> C) = (A \<and> B \<and> C)
[PROOF STEP]
by auto |
section {*FUNCTION\_CONT\_\_Enforce\_Controllability*}
theory
FUNCTION_CONT__Enforce_Controllability
imports
PRJ_13_06__ENTRY
begin
definition F_DPDA_EC__SpecInput :: "
('stateA, 'event, 'stackA) epda
\<Rightarrow> (('stateB, 'event, nat) epda \<times> 'event set)
\<Rightarrow> bool"
where
"F_DPDA_EC__SpecInput G X \<equiv>
case X of
(P, \<Sigma>UC) \<Rightarrow>
valid_dpda G
\<and> valid_dfa P
\<and> epdaS.marked_language G \<subseteq> epdaS.marked_language P
\<and> epdaS.unmarked_language G \<subseteq> epdaS.unmarked_language P
\<and> nonblockingness_language (epdaS.unmarked_language G) (epdaS.marked_language G)
\<and> \<not> epdaH_livelock G
\<and> epdaH.accessible G"
definition F_DPDA_EC__SpecOutput :: "
('stateA, 'event, 'stackA) epda
\<Rightarrow> (('stateA, 'event, 'stackA) epda \<times> ('stateB, 'event, nat) epda \<times> 'event set)
\<Rightarrow> (('stateA, 'event, 'stackA) epda option \<times> bool)
\<Rightarrow> bool"
where
"F_DPDA_EC__SpecOutput Gi X R \<equiv>
case X of
(G0, P, \<Sigma>UC) \<Rightarrow>
(case R of
(None, b) \<Rightarrow>
des_langM
(Enforce_Marked_Controllable_Subset
\<Sigma>UC
(epdaH.unmarked_language P)
(epda_to_des Gi))
= {}
\<and> \<not> b
| (Some Go, b) \<Rightarrow>
valid_dpda Go
\<and> Enforce_Marked_Controllable_Subset
\<Sigma>UC
(epdaH.unmarked_language P)
(epda_to_des Gi)
= epda_to_des Go
\<and> \<not> epdaH_livelock Go
\<and> (b \<longrightarrow> Gi = Go)
\<and> b = epda_operational_controllable Gi P \<Sigma>UC
\<and> (b \<longleftrightarrow> epda_to_des Gi = epda_to_des Go))"
definition F_DPDA_EC__F_DPDA_OTS__SpecInput :: "
(('stateA, 'stateB) DT_tuple2, 'event, 'stackA) epda
\<Rightarrow> (('stateA, 'event, 'stackA) epda \<times> ('stateB, 'event, nat) epda)
\<Rightarrow> bool"
where
"F_DPDA_EC__F_DPDA_OTS__SpecInput G X \<equiv>
case X of
(S, D) \<Rightarrow>
valid_dpda G
\<and> valid_dfa D
\<and> nonblockingness_language (epdaH.unmarked_language G) (epdaH.marked_language G)
\<and> epdaH_reflection_to_DFA_exists G D sel_tuple2_2
\<and> \<not> epdaH_livelock G
\<and> epda_to_des G = epda_to_des S"
definition F_DPDA_EC__F_DPDA_OTS__SpecOutput :: "
('stateC, 'event, 'stackC) epda
\<Rightarrow> (('stateA, 'event, 'stackA) epda \<times> ('stateB, 'event, nat) epda \<times> 'event set)
\<Rightarrow> (('stateA, 'event, 'stackA) epda option \<times> bool)
\<Rightarrow> bool"
where
"F_DPDA_EC__F_DPDA_OTS__SpecOutput Gi X R \<equiv>
case X of
(G0, P, \<Sigma>UC) \<Rightarrow>
(case R of
(None, b) \<Rightarrow>
des_langM
(Enforce_Marked_Controllable_Subset
\<Sigma>UC
(epdaH.unmarked_language P)
(epda_to_des Gi))
= {}
\<and> b = False
| (Some Go, b) \<Rightarrow>
valid_dpda Go
\<and> Enforce_Marked_Controllable_Subset
\<Sigma>UC
(epdaH.unmarked_language P)
(epda_to_des Gi)
= (epda_to_des Go)
\<and> \<not> epdaH_livelock Go
\<and> (b \<longrightarrow> G0 = Go)
\<and> b = epda_operational_controllable Gi P \<Sigma>UC
\<and> (b \<longleftrightarrow> epda_to_des Gi = epda_to_des Go))"
definition F_DPDA_EC__F_DPDA_EUML__SpecInput :: "
((('stateA, 'stateB) DT_tuple2, 'stackA) DT_state_and_stack_or_state, 'event, 'stackA) epda
\<Rightarrow> (('stateA, 'event, 'stackA) epda \<times> ('stateB, 'event, nat) epda)
\<Rightarrow> bool"
where
"F_DPDA_EC__F_DPDA_EUML__SpecInput G X \<equiv>
case X of
(S, D) \<Rightarrow>
valid_dpda G
\<and> valid_dfa D
\<and> nonblockingness_language (epdaH.unmarked_language G) (epdaH.marked_language G)
\<and> state_stack_unique_for_marking_states G
\<and> state_stack_unique_for_stable_states G
\<and> always_applicable_for_stable_states G
\<and> some_edge_applicable G
\<and> \<not> epdaH_livelock G
\<and> epdaH_reflection_to_DFA_exists G D (sel_tuple2_2 \<circ> F_DPDA_OTS__get_state)
\<and> corresponds_to_top_stack G F_DPDA_OTS__is_auxiliary F_DPDA_OTS__get_stack
\<and> main_states_have_only_empty_steps G F_DPDA_OTS__is_main
\<and> main_states_have_all_empty_steps G F_DPDA_OTS__is_main
\<and> executing_edge_from_auxiliary_to_main_state G F_DPDA_OTS__is_auxiliary F_DPDA_OTS__is_main
\<and> always_applicable_for_auxiliary_states G F_DPDA_OTS__is_auxiliary
\<and> main_to_auxiliary_or_auxiliary_to_main G F_DPDA_OTS__is_main
\<and> epda_to_des G = epda_to_des S"
definition F_DPDA_EC__F_DPDA_EUML__SpecOutput :: "
('stateC, 'event, 'stackC) epda
\<Rightarrow> (('stateA, 'event, 'stackA) epda \<times> ('stateB, 'event, nat) epda \<times> 'event set)
\<Rightarrow> (('stateA, 'event, 'stackA) epda option \<times> bool)
\<Rightarrow> bool"
where
"F_DPDA_EC__F_DPDA_EUML__SpecOutput \<equiv>
F_DPDA_EC__F_DPDA_OTS__SpecOutput"
definition F_DPDA_EC__F_DPDA_EA_OPT__SpecInput :: "
(((('stateA, 'stateB) DT_tuple2, 'stackA) DT_state_and_stack_or_state) DT_state_or_state, 'event, 'stackA) epda
\<Rightarrow> (('stateA, 'event, 'stackA) epda \<times> ('stateB, 'event, nat) epda)
\<Rightarrow> bool"
where
"F_DPDA_EC__F_DPDA_EA_OPT__SpecInput G X \<equiv>
case X of
(S, D) \<Rightarrow>
valid_dpda G
\<and> valid_dfa D
\<and> nonblockingness_language (epdaH.unmarked_language G) (epdaH.marked_language G)
\<and> state_stack_unique_for_marking_states G
\<and> only_executing_edges_from_marking_states G
\<and> \<not> epdaH_livelock G
\<and> epdaH_reflection_to_DFA_exists G D (sel_tuple2_2 \<circ> F_DPDA_OTS__get_state \<circ> F_DPDA_EUML__get_state)
\<and> corresponds_to_top_stack G F_DPDA_EUML__is_auxiliary F_DPDA_EUML__get_stack
\<and> main_states_have_only_empty_steps G F_DPDA_EUML__is_main
\<and> main_states_have_all_empty_steps G F_DPDA_EUML__is_main
\<and> executing_edge_from_auxiliary_to_main_state G F_DPDA_EUML__is_auxiliary F_DPDA_EUML__is_main
\<and> always_applicable_for_auxiliary_states G F_DPDA_EUML__is_auxiliary
\<and> main_to_auxiliary_or_auxiliary_to_main G F_DPDA_EUML__is_main
\<and> epda_to_des G = epda_to_des S"
definition F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput :: "
('stateC, 'event, 'stackC) epda
\<Rightarrow> (('stateA, 'event, 'stackA) epda \<times> ('stateB, 'event, nat) epda \<times> 'event set)
\<Rightarrow> (('stateA, 'event, 'stackA) epda option \<times> bool)
\<Rightarrow> bool"
where
"F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput \<equiv>
F_DPDA_EC__F_DPDA_OTS__SpecOutput"
definition F_DPDA_EC__F_DPDA_RCS__SpecInput :: "
(((('stateA, 'stateB) DT_tuple2, 'stackA) DT_state_and_stack_or_state) DT_state_or_state, 'event, 'stackA) epda
\<Rightarrow> (('stateA, 'event, 'stackA) epda \<times> ('stateB, 'event, nat) epda)
\<Rightarrow> bool"
where
"F_DPDA_EC__F_DPDA_RCS__SpecInput G X \<equiv>
case X of
(S, D) \<Rightarrow>
valid_dpda G
\<and> valid_dfa D
\<and> nonblockingness_language (epdaS.unmarked_language G) (epdaS.marked_language G)
\<and> state_stack_unique_for_marking_states G
\<and> only_executing_edges_from_marking_states G
\<and> \<not> epdaH_livelock G
\<and> epdaH_reflection_to_DFA_exists G D (sel_tuple2_2 \<circ> F_DPDA_OTS__get_state \<circ> F_DPDA_EUML__get_state)
\<and> corresponds_to_top_stack G F_DPDA_EUML__is_auxiliary F_DPDA_EUML__get_stack
\<and> epdaH.accessible G
\<and> main_states_can_be_left_with_empty_step G F_DPDA_EUML__is_main
\<and> main_states_have_only_empty_steps G F_DPDA_EUML__is_main
\<and> executing_edge_from_auxiliary_to_main_state G F_DPDA_EUML__is_auxiliary F_DPDA_EUML__is_main
\<and> always_applicable_for_auxiliary_states G F_DPDA_EUML__is_auxiliary
\<and> main_to_auxiliary_or_auxiliary_to_main G F_DPDA_EUML__is_main
\<and> epda_to_des G = epda_to_des S"
definition F_DPDA_EC__F_DPDA_RCS__SpecOutput :: "
('stateC, 'event, 'stackC) epda
\<Rightarrow> (('stateA, 'event, 'stackA) epda \<times> ('stateB, 'event, nat) epda \<times> 'event set)
\<Rightarrow> (('stateA, 'event, 'stackA) epda option \<times> bool)
\<Rightarrow> bool"
where
"F_DPDA_EC__F_DPDA_RCS__SpecOutput \<equiv>
F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput"
theorem F_DPDA_EC__SOUND: "
F_DPDA_EC__SpecInput S (P, \<Sigma>UC)
\<Longrightarrow> R = F_DPDA_EC S P \<Sigma>UC
\<Longrightarrow> F_DPDA_EC__SpecOutput S (S, P, \<Sigma>UC) R"
apply(simp add: F_DPDA_EC_def)
apply(clarsimp)
apply(rule_tac
SPo_F="F_DPDA_EC__SpecOutput"
and SPi_F="F_DPDA_EC__SpecInput"
and X="S"
and Y="(S, P, \<Sigma>UC)"
and SEL_iF="\<lambda>(S, P, \<Sigma>UC). (P, \<Sigma>UC)"
and SEL_iH="\<lambda>(S, P, \<Sigma>UC). P"
and SEL_iFH="\<lambda>(S, P, \<Sigma>UC). (S, P)"
and SEL_oF="\<lambda>(S, P, \<Sigma>UC). (S, P, \<Sigma>UC)"
and SEL_oH="\<lambda>(S, P, \<Sigma>UC). (P, \<Sigma>UC)"
and SEL_oFH="\<lambda>(S, P, \<Sigma>UC). (S, P, \<Sigma>UC)"
and SPi_H="FUN_DPDA_DFA_PRODUCT__SpecInput2"
and SPo_H="FUN_DPDA_DFA_PRODUCT__SpecOutput2"
and SPi_FH="F_DPDA_EC__F_DPDA_OTS__SpecInput"
and SPo_FH="F_DPDA_EC__F_DPDA_OTS__SpecOutput"
and H="F_DPDA_DFA_PRODUCT"
in decompose_sequential_execution_input_output_specification_args)
apply(force)
apply(force)
apply(force)
apply(force)
apply(force)
apply(force)
apply(force)
apply(simp add: FUN_DPDA_DFA_PRODUCT__SpecInput2_def F_DPDA_EC__SpecInput_def)
apply(clarsimp)
apply(rule_tac
t="epdaH.unmarked_language S"
and s="epdaS.unmarked_language S"
in ssubst)
apply (metis valid_dpda_to_valid_pda PDA_to_epda epdaS_to_epdaH_unmarked_language)
apply(rule_tac
t="epdaH.marked_language S"
and s="epdaS.marked_language S"
in ssubst)
apply (metis valid_dpda_to_valid_pda PDA_to_epda epdaS_to_epdaH_mlang)
apply(rule_tac
t="epdaH.marked_language P"
and s="epdaS.marked_language P"
in ssubst)
apply(simp add: valid_dfa_def)
apply (metis valid_dpda_to_valid_pda PDA_to_epda epdaS_to_epdaH_mlang)
apply(rule_tac
t="epdaH.unmarked_language P"
and s="epdaS.unmarked_language P"
in ssubst)
apply(simp add: valid_dfa_def)
apply (metis valid_dpda_to_valid_pda PDA_to_epda epdaS_to_epdaH_unmarked_language)
apply(force)
apply(rule_tac
?Gi="S"
and P="P"
in F_DPDA_DFA_PRODUCT__SOUND2)
apply(force)
apply(simp add: FUN_DPDA_DFA_PRODUCT__SpecInput2_def F_DPDA_EC__SpecInput_def F_DPDA_EC__F_DPDA_OTS__SpecInput_def FUN_DPDA_DFA_PRODUCT__SpecOutput2_def epda_to_des_def)
apply(clarsimp)
apply(rule_tac
t="epdaH.unmarked_language S"
and s="epdaS.unmarked_language S"
in subst)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rule_tac
t="epdaH.marked_language S"
and s="epdaS.marked_language S"
in subst)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rule_tac
t="epdaH.marked_language P"
and s="epdaS.marked_language P"
in subst)
apply(rule epdaS_to_epdaH_mlang)
apply(simp add: valid_dfa_def)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rule_tac
t="epdaH.unmarked_language P"
and s="epdaS.unmarked_language P"
in subst)
apply(rule epdaS_to_epdaH_unmarked_language)
apply(simp add: valid_dfa_def)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(force)
apply(rename_tac Pa)(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_OTS__SpecOutput_def F_DPDA_EC__SpecOutput_def)
apply(clarsimp)
apply(rename_tac Pa x y)(*strict*)
apply(subgoal_tac "epdaH.unmarked_language (F_DPDA_DFA_PRODUCT S P) = epdaH.unmarked_language S")
apply(rename_tac Pa x y)(*strict*)
prefer 2
apply(simp add: FUN_DPDA_DFA_PRODUCT__SpecOutput2_def F_DPDA_EC__SpecInput_def)
apply(clarsimp)
apply(rule_tac
t="epdaH.unmarked_language S"
and s="epdaS.unmarked_language S"
in subst)
apply(rename_tac Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac Pa x y)(*strict*)
apply(rule_tac
t="epdaH.marked_language S"
and s="epdaS.marked_language S"
in subst)
apply(rename_tac Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac Pa x y)(*strict*)
apply(rule_tac
t="epdaH.marked_language P"
and s="epdaS.marked_language P"
in subst)
apply(rename_tac Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply(simp add: valid_dfa_def)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac Pa x y)(*strict*)
apply(rule_tac
t="epdaH.unmarked_language P"
and s="epdaS.unmarked_language P"
in subst)
apply(rename_tac Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply(simp add: valid_dfa_def)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac Pa x y)(*strict*)
apply(force)
apply(rename_tac Pa x y)(*strict*)
apply(subgoal_tac "epdaH.marked_language (F_DPDA_DFA_PRODUCT S P) = epdaH.marked_language S")
apply(rename_tac Pa x y)(*strict*)
prefer 2
apply(thin_tac "epdaH.unmarked_language (F_DPDA_DFA_PRODUCT S P) = epdaH.unmarked_language S")
apply(unfold FUN_DPDA_DFA_PRODUCT__SpecOutput2_def F_DPDA_EC__SpecInput_def)[1]
apply(clarsimp)
apply(rule_tac
t="epdaH.unmarked_language S"
and s="epdaS.unmarked_language S"
in subst)
apply(rename_tac Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac Pa x y)(*strict*)
apply(rule_tac
t="epdaH.marked_language S"
and s="epdaS.marked_language S"
in subst)
apply(rename_tac Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac Pa x y)(*strict*)
apply(rule_tac
t="epdaH.marked_language P"
and s="epdaS.marked_language P"
in subst)
apply(rename_tac Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply(simp add: valid_dfa_def)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac Pa x y)(*strict*)
apply(rule_tac
t="epdaH.unmarked_language P"
and s="epdaS.unmarked_language P"
in subst)
apply(rename_tac Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply(simp add: valid_dfa_def)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac Pa x y)(*strict*)
apply(force)
apply(rename_tac Pa x y)(*strict*)
apply(subgoal_tac "epda_to_des (F_DPDA_DFA_PRODUCT S P) = epda_to_des S")
apply(rename_tac Pa x y)(*strict*)
prefer 2
apply(simp add: epda_to_des_def)
apply(rename_tac Pa x y)(*strict*)
apply(case_tac x)
apply(rename_tac Pa x y)(*strict*)
apply(clarsimp)
apply(rename_tac Pa x y a)(*strict*)
apply(clarsimp)
apply(rename_tac Pa a)(*strict*)
apply(rule_tac
t="epda_operational_controllable S P \<Sigma>UC"
and s="epda_operational_controllable (F_DPDA_DFA_PRODUCT S P) P \<Sigma>UC"
in ssubst)
apply(rename_tac Pa a)(*strict*)
prefer 2
apply(force)
apply(rename_tac Pa a)(*strict*)
apply(rule epda_Cont_eq_to_epda_operational_controllable_eq2)
apply(rename_tac Pa a)(*strict*)
apply(simp add: F_DPDA_EC__SpecInput_def FUN_DPDA_DFA_PRODUCT__SpecOutput2_def)
apply(rename_tac Pa a)(*strict*)
apply(simp add: F_DPDA_EC__SpecInput_def FUN_DPDA_DFA_PRODUCT__SpecOutput2_def)
apply(rename_tac Pa a)(*strict*)
apply(simp add: F_DPDA_EC__SpecInput_def FUN_DPDA_DFA_PRODUCT__SpecOutput2_def)
apply(rename_tac Pa a)(*strict*)
apply(simp add: F_DPDA_EC__SpecInput_def FUN_DPDA_DFA_PRODUCT__SpecOutput2_def)
apply(rename_tac X)(*strict*)
apply(rename_tac S')
apply(rename_tac S')(*strict*)
apply(rule_tac
SPo_F="F_DPDA_EC__F_DPDA_OTS__SpecOutput"
and SPi_F="F_DPDA_EC__F_DPDA_OTS__SpecInput"
and H="F_DPDA_OTS"
and X="S'"
and Y="(S, P, \<Sigma>UC)"
and SEL_iF="\<lambda>(S, P, \<Sigma>UC). (S, P)"
and SEL_iH="\<lambda>(S, P, \<Sigma>UC). P"
and SEL_iFH="\<lambda>(S, P, \<Sigma>UC). (S, P)"
and SEL_oF="\<lambda>(S, P, \<Sigma>UC). (S, P, \<Sigma>UC)"
and SEL_oH="\<lambda>(S, P, \<Sigma>UC). (P, \<Sigma>UC)"
and SEL_oFH="\<lambda>(S, P, \<Sigma>UC). (S, P, \<Sigma>UC)"
and SPi_H="F_DPDA_OTS__SpecInput"
and SPo_H="F_DPDA_OTS__SpecOutput"
and SPi_FH="F_DPDA_EC__F_DPDA_EUML__SpecInput"
and SPo_FH="F_DPDA_EC__F_DPDA_EUML__SpecOutput"
in decompose_sequential_execution_input_output_specification_args2_noHargs)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_OTS__SpecInput_def F_DPDA_OTS__SpecInput_def)
apply(rename_tac S')(*strict*)
apply(rule F_DPDA_OTS__SOUND)
apply(force)
apply(rename_tac S')(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_EUML__SpecInput_def F_DPDA_OTS__SpecOutput_def F_DPDA_EC__F_DPDA_OTS__SpecInput_def epda_to_des_def)
apply(rename_tac S' Pa)(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_EUML__SpecOutput_def F_DPDA_EC__F_DPDA_EUML__SpecInput_def F_DPDA_OTS__SpecOutput_def F_DPDA_EC__F_DPDA_OTS__SpecInput_def F_DPDA_EC__F_DPDA_OTS__SpecOutput_def)
apply(clarsimp)
apply(rename_tac S' Pa x y)(*strict*)
apply(subgoal_tac "epdaH.unmarked_language (F_DPDA_OTS S') = epdaH.unmarked_language S'")
apply(rename_tac S' Pa x y)(*strict*)
prefer 2
apply(clarsimp)
apply(rename_tac S' Pa x y)(*strict*)
apply(subgoal_tac "epdaH.marked_language (F_DPDA_OTS S') = epdaH.marked_language S'")
apply(rename_tac S' Pa x y)(*strict*)
prefer 2
apply(clarsimp)
apply(rename_tac S' Pa x y)(*strict*)
apply(subgoal_tac "epda_to_des (F_DPDA_OTS S') = epda_to_des S'")
apply(rename_tac S' Pa x y)(*strict*)
prefer 2
apply(simp add: epda_to_des_def)
apply(rename_tac S' Pa x y)(*strict*)
apply(case_tac x)
apply(rename_tac S' Pa x y)(*strict*)
apply(clarify)
apply(simp (no_asm))
apply(rename_tac S' Pa y)(*strict*)
apply(simp (no_asm_use))
apply(rule conjI)
apply(rename_tac S' Pa y)(*strict*)
prefer 2
apply(force)
apply(rename_tac S' Pa y)(*strict*)
apply(rule_tac
t="epda_to_des S'"
and s="epda_to_des (F_DPDA_OTS S')"
in ssubst)
apply(rename_tac S' Pa y)(*strict*)
apply(force)
apply(rename_tac S' Pa y)(*strict*)
apply(rule_tac
t="epdaH.unmarked_language S'"
and s="epdaH.unmarked_language (F_DPDA_OTS S')"
in ssubst)
apply(rename_tac S' Pa y)(*strict*)
apply(force)
apply(rename_tac S' Pa y)(*strict*)
apply(force)
apply(rename_tac S' Pa x y a)(*strict*)
apply(clarify)
apply(simp (no_asm))
apply(rename_tac S' Pa y a)(*strict*)
apply(simp (no_asm_use))
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
prefer 2
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule_tac
t="epda_operational_controllable S' P \<Sigma>UC"
and s="epda_operational_controllable (F_DPDA_OTS S') P \<Sigma>UC"
in ssubst)
apply(rename_tac S' Pa y a)(*strict*)
prefer 2
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule epda_Cont_eq_to_epda_operational_controllable_eq2)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' X)(*strict*)
apply(thin_tac "F_DPDA_EC__F_DPDA_OTS__SpecInput S' (S, P)")
apply(clarsimp)
apply(rename_tac X)(*strict*)
apply(rename_tac S')
apply(rename_tac S')(*strict*)
apply(rule_tac
SPo_F="F_DPDA_EC__F_DPDA_EUML__SpecOutput"
and SPi_F="F_DPDA_EC__F_DPDA_EUML__SpecInput"
and H="F_DPDA_EUML"
and X="S'"
and Y="(S, P, \<Sigma>UC)"
and SEL_iF="\<lambda>(S, P, \<Sigma>UC). (S, P)"
and SEL_iH="\<lambda>(S, P, \<Sigma>UC). P"
and SEL_iFH="\<lambda>(S, P, \<Sigma>UC). (S, P)"
and SEL_oF="\<lambda>(S, P, \<Sigma>UC). (S, P, \<Sigma>UC)"
and SEL_oH="\<lambda>(S, P, \<Sigma>UC). (P, \<Sigma>UC)"
and SEL_oFH="\<lambda>(S, P, \<Sigma>UC). (S, P, \<Sigma>UC)"
and SPi_H="F_DPDA_EUML__SpecInput"
and SPo_H="F_DPDA_EUML__SpecOutput"
and SPi_FH="F_DPDA_EC__F_DPDA_EA_OPT__SpecInput"
and SPo_FH="F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput"
in decompose_sequential_execution_input_output_specification_args2_noHargs)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(simp add: F_DPDA_EUML__SpecInput_def F_DPDA_EC__F_DPDA_EUML__SpecInput_def)
apply(rename_tac S')(*strict*)
apply(rule F_DPDA_EUML__SOUND)
apply(force)
apply(rename_tac S')(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_EA_OPT__SpecInput_def F_DPDA_EUML__SpecOutput_def F_DPDA_EC__F_DPDA_EUML__SpecInput_def epda_to_des_def)
apply(rename_tac S' Pa)(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_EUML__SpecOutput_def F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput_def F_DPDA_EC__F_DPDA_EUML__SpecInput_def F_DPDA_EUML__SpecOutput_def F_DPDA_EC__F_DPDA_OTS__SpecOutput_def)
apply(clarsimp)
apply(rename_tac S' Pa x y)(*strict*)
apply(subgoal_tac "epdaH.unmarked_language (F_DPDA_EUML S') = epdaH.unmarked_language S'")
apply(rename_tac S' Pa x y)(*strict*)
prefer 2
apply(clarsimp)
apply(rename_tac S' Pa x y)(*strict*)
apply(subgoal_tac "epdaH.marked_language (F_DPDA_EUML S') = epdaH.marked_language S'")
apply(rename_tac S' Pa x y)(*strict*)
prefer 2
apply(clarsimp)
apply(rename_tac S' Pa x y)(*strict*)
apply(subgoal_tac "epda_to_des (F_DPDA_EUML S') = epda_to_des S'")
apply(rename_tac S' Pa x y)(*strict*)
prefer 2
apply(simp add: epda_to_des_def)
apply(rename_tac S' Pa x y)(*strict*)
apply(case_tac x)
apply(rename_tac S' Pa x y)(*strict*)
apply(clarify)
apply(simp (no_asm))
apply(rename_tac S' Pa y)(*strict*)
apply(simp (no_asm_use))
apply(rule conjI)
apply(rename_tac S' Pa y)(*strict*)
prefer 2
apply(force)
apply(rename_tac S' Pa y)(*strict*)
apply(rule_tac
t="epda_to_des S'"
and s="epda_to_des (F_DPDA_EUML S')"
in ssubst)
apply(rename_tac S' Pa y)(*strict*)
apply(force)
apply(rename_tac S' Pa y)(*strict*)
apply(rule_tac
t="epdaH.unmarked_language S'"
and s="epdaH.unmarked_language (F_DPDA_EUML S')"
in ssubst)
apply(rename_tac S' Pa y)(*strict*)
apply(force)
apply(rename_tac S' Pa y)(*strict*)
apply(force)
apply(rename_tac S' Pa x y a)(*strict*)
apply(clarify)
apply(simp (no_asm))
apply(rename_tac S' Pa y a)(*strict*)
apply(simp (no_asm_use))
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule conjI)
apply(rename_tac S' Pa y a)(*strict*)
prefer 2
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule_tac
t="epda_operational_controllable S' P \<Sigma>UC"
and s="epda_operational_controllable (F_DPDA_EUML S') P \<Sigma>UC"
in ssubst)
apply(rename_tac S' Pa y a)(*strict*)
prefer 2
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(rule epda_Cont_eq_to_epda_operational_controllable_eq2)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' Pa y a)(*strict*)
apply(force)
apply(rename_tac S' X)(*strict*)
apply(thin_tac "F_DPDA_EC__F_DPDA_EUML__SpecInput S' (S, P)")
apply(clarsimp)
apply(rename_tac X)(*strict*)
apply(rename_tac S')
apply(rename_tac S')(*strict*)
apply(rule_tac
SPo_F="F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput"
and SPi_F="F_DPDA_EC__F_DPDA_EA_OPT__SpecInput"
and H="F_DPDA_EA_OPT"
and X="S'"
and Y="(S, P, \<Sigma>UC)"
and SEL_iF="\<lambda>(S, P, \<Sigma>UC). (S, P)"
and SEL_iH="\<lambda>(S, P, \<Sigma>UC). P"
and SEL_iFH="\<lambda>(S, P, \<Sigma>UC). (S, P)"
and SEL_oF="\<lambda>(S, P, \<Sigma>UC). (S, P, \<Sigma>UC)"
and SEL_oH="\<lambda>(S, P, \<Sigma>UC). (P, \<Sigma>UC)"
and SEL_oFH="\<lambda>(S, P, \<Sigma>UC). (S, P, \<Sigma>UC)"
and SPi_H="F_DPDA_EA_OPT__SpecInput2"
and SPo_H="F_DPDA_EA_OPT__SpecOutput2"
and SPi_FH="F_DPDA_EC__F_DPDA_RCS__SpecInput"
and SPo_FH="F_DPDA_EC__F_DPDA_RCS__SpecOutput"
in decompose_sequential_execution_input_output_specification_args2_noHargs)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(simp add: F_DPDA_EA_OPT__SpecInput2_def F_DPDA_EC__F_DPDA_EA_OPT__SpecInput_def)
apply(clarsimp)
apply(rule_tac
s="epdaH.unmarked_language S'"
and t="epdaS.unmarked_language S'"
in ssubst)
apply(rename_tac S')(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S')(*strict*)
apply(rule_tac
s="epdaH.marked_language S'"
and t="epdaS.marked_language S'"
in ssubst)
apply(rename_tac S')(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(rule F_DPDA_EA_OPT__SOUND2)
apply(force)
apply(rename_tac S')(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_RCS__SpecInput_def F_DPDA_EA_OPT__SpecOutput2_def F_DPDA_EC__F_DPDA_EA_OPT__SpecInput_def epda_to_des_def F_DPDA_EC__SpecInput_def)
apply(clarsimp)
apply(rule_tac
t="epdaH.unmarked_language S"
and s="epdaH.unmarked_language S'"
in ssubst)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(rule_tac
t="epdaH.marked_language S"
and s="epdaH.marked_language S'"
in ssubst)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S')(*strict*)
apply(rule_tac
t="epdaH.unmarked_language S'"
and s="epdaS.unmarked_language S'"
in subst)
apply(rename_tac S')(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S')(*strict*)
apply(rule_tac
t="epdaH.unmarked_language (F_DPDA_EA_OPT S')"
and s="epdaS.unmarked_language (F_DPDA_EA_OPT S')"
in subst)
apply(rename_tac S')(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S')(*strict*)
apply(rule_tac
t="epdaH.marked_language S'"
and s="epdaS.marked_language S'"
in subst)
apply(rename_tac S')(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S')(*strict*)
apply(rule_tac
t="epdaH.marked_language (F_DPDA_EA_OPT S')"
and s="epdaS.marked_language (F_DPDA_EA_OPT S')"
in subst)
apply(rename_tac S')(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S')(*strict*)
apply(force)
apply(rename_tac S' Pa)(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_RCS__SpecOutput_def F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput_def F_DPDA_EC__F_DPDA_EA_OPT__SpecInput_def F_DPDA_EA_OPT__SpecOutput2_def F_DPDA_EC__SpecInput_def F_DPDA_EC__F_DPDA_EUML__SpecOutput_def F_DPDA_EC__F_DPDA_OTS__SpecOutput_def)
apply(clarsimp)
apply(rename_tac S' Pa x y)(*strict*)
apply(subgoal_tac "epdaH.unmarked_language (F_DPDA_EA_OPT S') = epdaH.unmarked_language S'")
apply(rename_tac S' Pa x y)(*strict*)
prefer 2
apply(rule_tac
t="epdaH.unmarked_language S'"
and s="epdaS.unmarked_language S'"
in subst)
apply(rename_tac S' Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S' Pa x y)(*strict*)
apply(rule_tac
t="epdaH.unmarked_language (F_DPDA_EA_OPT S')"
and s="epdaS.unmarked_language (F_DPDA_EA_OPT S')"
in subst)
apply(rename_tac S' Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S' Pa x y)(*strict*)
apply(force)
apply(rename_tac S' Pa x y)(*strict*)
apply(subgoal_tac "epdaH.marked_language (F_DPDA_EA_OPT S') = epdaH.marked_language S'")
apply(rename_tac S' Pa x y)(*strict*)
prefer 2
apply(rule_tac
t="epdaH.marked_language S'"
and s="epdaS.marked_language S'"
in subst)
apply(rename_tac S' Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S' Pa x y)(*strict*)
apply(rule_tac
t="epdaH.marked_language (F_DPDA_EA_OPT S')"
and s="epdaS.marked_language (F_DPDA_EA_OPT S')"
in subst)
apply(rename_tac S' Pa x y)(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S' Pa x y)(*strict*)
apply(force)
apply(rename_tac S' Pa x y)(*strict*)
apply(subgoal_tac "epda_to_des (F_DPDA_EA_OPT S') = epda_to_des S'")
apply(rename_tac S' Pa x y)(*strict*)
prefer 2
apply(simp add: epda_to_des_def)
apply(rename_tac S' Pa x y)(*strict*)
apply(case_tac x)
apply(rename_tac S' Pa x y)(*strict*)
apply(clarsimp)
apply(rename_tac S' Pa x y a)(*strict*)
apply(clarsimp)
apply(rename_tac S' Pa a)(*strict*)
apply(rule_tac
t="epda_operational_controllable S' P \<Sigma>UC"
and s="epda_operational_controllable (F_DPDA_EA_OPT S') P \<Sigma>UC"
in ssubst)
apply(rename_tac S' Pa a)(*strict*)
apply(rule epda_Cont_eq_to_epda_operational_controllable_eq2)
apply(rename_tac S' Pa a)(*strict*)
apply(simp add: F_DPDA_EC__SpecInput_def FUN_DPDA_DFA_PRODUCT__SpecOutput2_def)
apply(rename_tac S' Pa a)(*strict*)
apply(simp add: F_DPDA_EC__SpecInput_def FUN_DPDA_DFA_PRODUCT__SpecOutput2_def)
apply(rename_tac S' Pa a)(*strict*)
apply(simp add: F_DPDA_EC__SpecInput_def FUN_DPDA_DFA_PRODUCT__SpecOutput2_def)
apply(rename_tac S' Pa a)(*strict*)
apply(simp add: F_DPDA_EC__SpecInput_def FUN_DPDA_DFA_PRODUCT__SpecOutput2_def)
apply(rename_tac S' Pa a)(*strict*)
apply(force)
apply(rename_tac S' X)(*strict*)
apply(thin_tac "F_DPDA_EC__F_DPDA_EA_OPT__SpecInput S' (S, P)")
apply(clarsimp)
apply(rename_tac X)(*strict*)
apply(rename_tac S')
apply(rename_tac S')(*strict*)
apply(subgoal_tac "X" for X)
apply(rename_tac S')(*strict*)
prefer 2
apply(rule_tac
S="S'"
and P="P"
and \<Sigma>UC="\<Sigma>UC"
in F_DPDA_RCS__SOUND)
apply(simp add: F_DPDA_EC__F_DPDA_RCS__SpecInput_def F_DPDA_RCS__SpecInput_def)
apply(rename_tac S')(*strict*)
apply(case_tac "F_DPDA_RCS S' P \<Sigma>UC")
apply(rename_tac S' a b)(*strict*)
apply(clarsimp)
apply(case_tac a)
apply(rename_tac S' a b)(*strict*)
apply(clarsimp)
apply(rename_tac S' b)(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput_def F_DPDA_EC__F_DPDA_RCS__SpecOutput_def F_DPDA_RCS__SpecOutput_def F_DPDA_EC__F_DPDA_RCS__SpecInput_def F_DPDA_EC__SpecInput_def F_DPDA_EC__F_DPDA_EUML__SpecOutput_def F_DPDA_EC__F_DPDA_OTS__SpecOutput_def)
apply(rename_tac S' a b aa)(*strict*)
apply(clarsimp)
apply(rename_tac S' b aa)(*strict*)
apply(thin_tac "F_DPDA_RCS S' P \<Sigma>UC = (Some aa, b)")
apply(rename_tac S' b aa)(*strict*)
apply(simp add: F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput_def F_DPDA_EC__F_DPDA_RCS__SpecOutput_def)
apply(case_tac b)
apply(rename_tac S' b aa)(*strict*)
apply(clarsimp)
apply(simp only: F_DPDA_EC__SpecInput_def F_DPDA_EC__F_DPDA_RCS__SpecInput_def F_DPDA_EC__F_DPDA_RCS__SpecOutput_def F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput_def F_DPDA_RCS__SpecOutput_def F_DPDA_EC__F_DPDA_EUML__SpecOutput_def F_DPDA_EC__F_DPDA_OTS__SpecOutput_def)
apply(clarsimp)
apply(rename_tac S' b aa)(*strict*)
apply(clarsimp)
apply(simp only: F_DPDA_EC__SpecInput_def F_DPDA_EC__F_DPDA_RCS__SpecInput_def F_DPDA_EC__F_DPDA_RCS__SpecOutput_def F_DPDA_EC__F_DPDA_EA_OPT__SpecOutput_def F_DPDA_RCS__SpecOutput_def F_DPDA_EC__F_DPDA_EUML__SpecOutput_def F_DPDA_EC__F_DPDA_OTS__SpecOutput_def)
apply(clarsimp)
apply(rename_tac S'')
apply(rename_tac S' b S'')(*strict*)
apply(rule context_conjI)
apply(rename_tac S' b S'')(*strict*)
apply(rule F_EPDA_TC__preserves_DPDA)
apply(force)
apply(rename_tac S' b S'')(*strict*)
apply(rule context_conjI)
apply(rename_tac S' b S'')(*strict*)
apply(simp add: epda_to_des_def)
apply(rule conjI)
apply(rename_tac S' b S'')(*strict*)
apply(rule_tac
t="epdaH.unmarked_language S''"
and s="epdaS.unmarked_language S''"
in subst)
apply(rename_tac S' b S'')(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S' b S'')(*strict*)
apply(rule_tac
t="epdaH.unmarked_language (F_EPDA_TC S'')"
and s="epdaS.unmarked_language (F_EPDA_TC S'')"
in subst)
apply(rename_tac S' b S'')(*strict*)
apply(rule epdaS_to_epdaH_unmarked_language)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S' b S'')(*strict*)
apply(rule F_EPDA_TC__preserves_unmarked_language)
apply (metis valid_dpda_to_valid_pda)
apply(rename_tac S' b S'')(*strict*)
apply(rule_tac
t="epdaH.marked_language S''"
and s="epdaS.marked_language S''"
in subst)
apply(rename_tac S' b S'')(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S' b S'')(*strict*)
apply(rule_tac
t="epdaH.marked_language (F_EPDA_TC S'')"
and s="epdaS.marked_language (F_EPDA_TC S'')"
in subst)
apply(rename_tac S' b S'')(*strict*)
apply(rule epdaS_to_epdaH_mlang)
apply (metis valid_dpda_to_valid_pda PDA_to_epda)
apply(rename_tac S' b S'')(*strict*)
apply(rule F_EPDA_TC__preserves_lang)
apply (metis valid_dpda_to_valid_pda)
apply(rename_tac S' b S'')(*strict*)
apply(rule conjI)
apply(rename_tac S' b S'')(*strict*)
prefer 2
apply(force)
apply(rename_tac S' b S'')(*strict*)
apply(rule F_EPDA_TC__preserves_no_livelock)
apply(rename_tac S' b S'')(*strict*)
apply (metis valid_dpda_to_valid_pda)
apply(rename_tac S' b S'')(*strict*)
apply(force)
done
end
|
(* Title: Applications of Modal Kleene Algebras
Author: Victor B. F. Gomes, Walter Guttmann, Peter Höfner, Georg Struth, Tjark Weber
Maintainer: Walter Guttmann <walter.guttman at canterbury.ac.nz>
Georg Struth <g.struth at sheffield.ac.uk>
Tjark Weber <tjark.weber at it.uu.se>
*)
section \<open>Applications of Modal Kleene Algebras\<close>
theory Modal_Kleene_Algebra_Applications
imports Antidomain_Semiring
begin
text \<open>This file collects some applications of the theories developed so far. These are described
in~\<^cite>\<open>"guttmannstruthweber11algmeth"\<close>.\<close>
context antidomain_kleene_algebra
begin
subsection \<open>A Reachability Result\<close>
text \<open>This example is taken from~\<^cite>\<open>"desharnaismoellerstruth06kad"\<close>.\<close>
lemma opti_iterate_var [simp]: "|(ad y \<cdot> x)\<^sup>\<star>\<rangle> y = |x\<^sup>\<star>\<rangle> y"
proof (rule order.antisym)
show "|(ad y \<cdot> x)\<^sup>\<star>\<rangle> y \<le> |x\<^sup>\<star>\<rangle> y"
by (simp add: a_subid_aux1' ds.fd_iso2 star_iso)
have "d y + |x\<rangle> |(ad y \<cdot> x)\<^sup>\<star>\<rangle> y = d y + ad y \<cdot> |x\<rangle> |(ad y \<cdot> x)\<^sup>\<star>\<rangle> y"
using local.ads_d_def local.d_6 local.fdia_def by auto
also have "... = d y + |ad y \<cdot> x\<rangle> |(ad y \<cdot> x)\<^sup>\<star>\<rangle> y"
by (simp add: fdia_export_2)
finally have "d y + |x\<rangle> |(ad y \<cdot> x)\<^sup>\<star>\<rangle> y = |(ad y \<cdot> x)\<^sup>\<star>\<rangle> y"
by simp
thus "|x\<^sup>\<star>\<rangle> y \<le> |(ad y \<cdot> x)\<^sup>\<star>\<rangle> y"
using local.dka.fd_def local.dka.fdia_star_induct_eq by auto
qed
lemma opti_iterate [simp]: "d y + |(x \<cdot> ad y)\<^sup>\<star>\<rangle> |x\<rangle> y = |x\<^sup>\<star>\<rangle> y"
proof -
have "d y + |(x \<cdot> ad y)\<^sup>\<star>\<rangle> |x\<rangle> y = d y + |x\<rangle> |(ad y \<cdot> x)\<^sup>\<star>\<rangle> y"
by (metis local.conway.dagger_slide local.ds.fdia_mult)
also have "... = d y + |x\<rangle> |x\<^sup>\<star>\<rangle> y"
by simp
finally show ?thesis
by force
qed
lemma opti_iterate_var_2 [simp]: "d y + |ad y \<cdot> x\<rangle> |x\<^sup>\<star>\<rangle> y = |x\<^sup>\<star>\<rangle> y"
by (metis local.dka.fdia_star_unfold_var opti_iterate_var)
subsection \<open>Derivation of Segerberg's Formula\<close>
text \<open>This example is taken from~\<^cite>\<open>"DesharnaisMoellerStruthLMCS"\<close>.\<close>
definition Alpha :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" ("A")
where "A x y = d (x \<cdot> y) \<cdot> ad y"
lemma A_dom [simp]: "d (A x y) = A x y"
using Alpha_def local.a_d_closed local.ads_d_def local.apd_d_def by auto
lemma A_fdia: "A x y = |x\<rangle> y \<cdot> ad y"
by (simp add: Alpha_def local.dka.fd_def)
lemma A_fdia_var: "A x y = |x\<rangle> d y \<cdot> ad y"
by (simp add: A_fdia)
lemma a_A: "ad (A x (ad y)) = |x] y + ad y"
using Alpha_def local.a_6 local.a_d_closed local.apd_d_def local.fbox_def by force
lemma fsegerberg [simp]: "d y + |x\<^sup>\<star>\<rangle> A x y = |x\<^sup>\<star>\<rangle> y"
proof (rule order.antisym)
have "d y + |x\<rangle> (d y + |x\<^sup>\<star>\<rangle> A x y) = d y + |x\<rangle> y + |x\<rangle> |x\<^sup>\<star>\<rangle> ( |x\<rangle> y \<cdot> ad y )"
by (simp add: A_fdia add_assoc local.ds.fdia_add1)
also have "... = d y + |x\<rangle> y \<cdot> ad y + |x\<rangle> |x\<^sup>\<star>\<rangle> ( |x\<rangle> y \<cdot> ad y )"
by (metis local.am2 local.d_6 local.dka.fd_def local.fdia_def)
finally have "d y + |x\<rangle> (d y + |x\<^sup>\<star>\<rangle> A x y) = d y + |x\<^sup>\<star>\<rangle> A x y"
by (metis A_dom A_fdia add_assoc local.dka.fdia_star_unfold_var)
thus "|x\<^sup>\<star>\<rangle> y \<le> d y + |x\<^sup>\<star>\<rangle> A x y"
by (metis local.a_d_add_closure local.ads_d_def local.dka.fdia_star_induct_eq local.fdia_def)
have "d y + |x\<^sup>\<star>\<rangle> A x y = d y + |x\<^sup>\<star>\<rangle> ( |x\<rangle> y \<cdot> ad y )"
by (simp add: A_fdia)
also have "... \<le> d y + |x\<^sup>\<star>\<rangle> |x\<rangle> y"
using local.dpdz.domain_1'' local.ds.fd_iso1 local.join.sup_mono by blast
finally show "d y + |x\<^sup>\<star>\<rangle> A x y \<le> |x\<^sup>\<star>\<rangle> y"
by simp
qed
lemma fbox_segerberg [simp]: "d y \<cdot> |x\<^sup>\<star>] ( |x] y + ad y ) = |x\<^sup>\<star>] y"
proof -
have "|x\<^sup>\<star>] ( |x] y + ad y ) = d ( |x\<^sup>\<star>] ( |x] y + ad y ) )"
using local.a_d_closed local.ads_d_def local.apd_d_def local.fbox_def by auto
hence f1: "|x\<^sup>\<star>] ( |x] y + ad y ) = ad ( |x\<^sup>\<star>\<rangle> (A x (ad y)) )"
by (simp add: a_A local.fdia_fbox_de_morgan_2)
have "ad y + |x\<^sup>\<star>\<rangle> (A x (ad y)) = |x\<^sup>\<star>\<rangle> ad y"
by (metis fsegerberg local.a_d_closed local.ads_d_def local.apd_d_def)
thus ?thesis
by (metis f1 local.ads_d_def local.ans4 local.fbox_simp local.fdia_fbox_de_morgan_2)
qed
subsection \<open>Wellfoundedness and Loeb's Formula\<close>
text \<open>This example is taken from~\<^cite>\<open>"DesharnaisStruthSCP"\<close>.\<close>
definition Omega :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" ("\<Omega>")
where "\<Omega> x y = d y \<cdot> ad (x \<cdot> y)"
text \<open>If $y$ is a set, then $\Omega(x,y)$ describes those elements in $y$ from which no further $x$ transitions are possible.\<close>
lemma omega_fdia: "\<Omega> x y = d y \<cdot> ad ( |x\<rangle> y )"
using Omega_def local.a_d_closed local.ads_d_def local.apd_d_def local.dka.fd_def by auto
lemma omega_fbox: "\<Omega> x y = d y \<cdot> |x] (ad y)"
by (simp add: fdia_fbox_de_morgan_2 omega_fdia)
lemma omega_absorb1 [simp]: "\<Omega> x y \<cdot> ad ( |x\<rangle> y ) = \<Omega> x y"
by (simp add: mult_assoc omega_fdia)
lemma omega_absorb2 [simp]: "\<Omega> x y \<cdot> ad (x \<cdot> y) = \<Omega> x y"
by (simp add: Omega_def mult_assoc)
lemma omega_le_1: "\<Omega> x y \<le> d y"
by (simp add: Omega_def d_a_galois1)
lemma omega_subid: "\<Omega> x (d y) \<le> d y"
by (simp add: Omega_def local.a_subid_aux2)
lemma omega_le_2: "\<Omega> x y \<le> ad ( |x\<rangle> y )"
by (simp add: local.dka.dom_subid_aux2 omega_fdia)
lemma omega_dom [simp]: "d (\<Omega> x y) = \<Omega> x y"
using Omega_def local.a_d_closed local.ads_d_def local.apd_d_def by auto
lemma a_omega: "ad (\<Omega> x y) = ad y + |x\<rangle> y"
by (simp add: Omega_def local.a_6 local.ds.fd_def)
lemma omega_fdia_3 [simp]: "d y \<cdot> ad (\<Omega> x y) = d y \<cdot> |x\<rangle> y"
using Omega_def local.ads_d_def local.fdia_def local.s4 by presburger
lemma omega_zero_equiv_1: "\<Omega> x y = 0 \<longleftrightarrow> d y \<le> |x\<rangle> y"
by (simp add: Omega_def local.a_gla local.ads_d_def local.fdia_def)
definition Loebian :: "'a \<Rightarrow> bool"
where "Loebian x = (\<forall>y. |x\<rangle> y \<le> |x\<rangle> \<Omega> x y)"
definition PreLoebian :: "'a \<Rightarrow> bool"
where "PreLoebian x = (\<forall>y. d y \<le> |x\<^sup>\<star>\<rangle> \<Omega> x y)"
definition Noetherian :: "'a \<Rightarrow> bool"
where "Noetherian x = (\<forall>y. \<Omega> x y = 0 \<longrightarrow> d y = 0)"
lemma noetherian_alt: "Noetherian x \<longleftrightarrow> (\<forall>y. d y \<le> |x\<rangle> y \<longrightarrow> d y = 0)"
by (simp add: Noetherian_def omega_zero_equiv_1)
lemma Noetherian_iff_PreLoebian: "Noetherian x \<longleftrightarrow> PreLoebian x"
proof
assume hyp: "Noetherian x"
{
fix y
have "d y \<cdot> ad ( |x\<^sup>\<star>\<rangle> \<Omega> x y ) = d y \<cdot> ad (\<Omega> x y + |x\<rangle> |x\<^sup>\<star>\<rangle> \<Omega> x y)"
by (metis local.dka.fdia_star_unfold_var omega_dom)
also have "... = d y \<cdot> ad (\<Omega> x y) \<cdot> ad ( |x\<rangle> |x\<^sup>\<star>\<rangle> \<Omega> x y )"
using ans4 mult_assoc by presburger
also have "... \<le> |x\<rangle> d y \<cdot> ad ( |x\<rangle> |x\<^sup>\<star>\<rangle> \<Omega> x y )"
by (simp add: local.dka.dom_subid_aux2 local.mult_isor)
also have "... \<le> |x\<rangle> (d y \<cdot> ad ( |x\<^sup>\<star>\<rangle> \<Omega> x y ))"
by (simp add: local.dia_diff)
finally have "d y \<cdot> ad ( |x\<^sup>\<star>\<rangle> \<Omega> x y ) \<le> |x\<rangle> (d y \<cdot> ad ( |x\<^sup>\<star>\<rangle> \<Omega> x y ))"
by blast
hence "d y \<cdot> ad ( |x\<^sup>\<star>\<rangle> \<Omega> x y ) = 0"
by (metis hyp local.ads_d_def local.dpdz.dom_mult_closed local.fdia_def noetherian_alt)
hence "d y \<le> |x\<^sup>\<star>\<rangle> \<Omega> x y"
by (simp add: local.a_gla local.ads_d_def local.dka.fd_def)
}
thus "PreLoebian x"
using PreLoebian_def by blast
next
assume a: "PreLoebian x"
{
fix y
assume b: "\<Omega> x y = 0"
hence "d y \<le> |x\<rangle> d y"
using omega_zero_equiv_1 by auto
hence "d y = 0"
by (metis (no_types) PreLoebian_def a b a_one a_zero add_zeror annir fdia_def less_eq_def)
}
thus "Noetherian x"
by (simp add: Noetherian_def)
qed
lemma Loebian_imp_Noetherian: "Loebian x \<Longrightarrow> Noetherian x"
proof -
assume a: "Loebian x"
{
fix y
assume b: "\<Omega> x y = 0"
hence "d y \<le> |x\<rangle> d y"
using omega_zero_equiv_1 by auto
also have "... \<le> |x\<rangle> (\<Omega> x y)"
using Loebian_def a by auto
finally have "d y = 0"
by (simp add: b order.antisym fdia_def)
}
thus "Noetherian x"
by (simp add: Noetherian_def)
qed
lemma d_transitive: "(\<forall>y. |x\<rangle> |x\<rangle> y \<le> |x\<rangle> y) \<Longrightarrow> (\<forall>y. |x\<rangle> y = |x\<^sup>\<star>\<rangle> |x\<rangle> y)"
proof -
assume a: "\<forall>y. |x\<rangle> |x\<rangle> y \<le> |x\<rangle> y"
{
fix y
have "|x\<rangle> y + |x\<rangle> |x\<rangle> y \<le> |x\<rangle> y"
by (simp add: a)
hence "|x\<^sup>\<star>\<rangle> |x\<rangle> y \<le> |x\<rangle> y"
using local.dka.fd_def local.dka.fdia_star_induct_var by auto
have "|x\<rangle> y \<le> |x\<^sup>\<star>\<rangle> |x\<rangle> y"
using local.dka.fd_def local.order_prop opti_iterate by force
}
thus ?thesis
using a order.antisym dka.fd_def dka.fdia_star_induct_var by auto
qed
lemma d_transitive_var: "(\<forall>y. |x\<rangle> |x\<rangle> y \<le> |x\<rangle> y) \<Longrightarrow> (\<forall>y. |x\<rangle> y = |x\<rangle> |x\<^sup>\<star>\<rangle> y)"
proof -
assume "\<forall>y. |x\<rangle> |x\<rangle> y \<le> |x\<rangle> y"
then have "\<forall>a. |x\<rangle> |x\<^sup>\<star>\<rangle> a = |x\<rangle> a"
by (metis (full_types) d_transitive local.dka.fd_def local.dka.fdia_d_simp local.star_slide_var mult_assoc)
then show ?thesis
by presburger
qed
lemma d_transitive_PreLoebian_imp_Loebian: "(\<forall>y. |x\<rangle> |x\<rangle> y \<le> |x\<rangle> y) \<Longrightarrow> PreLoebian x \<Longrightarrow> Loebian x"
proof -
assume wt: "(\<forall>y. |x\<rangle> |x\<rangle> y \<le> |x\<rangle> y)"
and "PreLoebian x"
hence "\<forall>y. |x\<rangle> y \<le> |x\<rangle> |x\<^sup>\<star>\<rangle> \<Omega> x y"
using PreLoebian_def local.ads_d_def local.dka.fd_def local.ds.fd_iso1 by auto
hence "\<forall>y. |x\<rangle> y \<le> |x\<rangle> \<Omega> x y"
by (metis wt d_transitive_var)
then show "Loebian x"
using Loebian_def fdia_def by auto
qed
lemma d_transitive_Noetherian_iff_Loebian: "\<forall>y. |x\<rangle> |x\<rangle> y \<le> |x\<rangle> y \<Longrightarrow> Noetherian x \<longleftrightarrow> Loebian x"
using Loebian_imp_Noetherian Noetherian_iff_PreLoebian d_transitive_PreLoebian_imp_Loebian by blast
lemma Loeb_iff_box_Loeb: "Loebian x \<longleftrightarrow> (\<forall>y. |x] (ad ( |x] y ) + d y) \<le> |x] y)"
proof -
have "Loebian x \<longleftrightarrow> (\<forall>y. |x\<rangle> y \<le> |x\<rangle> (d y \<cdot> |x] (ad y)))"
using Loebian_def omega_fbox by auto
also have "... \<longleftrightarrow> (\<forall>y. ad ( |x\<rangle> (d y \<cdot> |x] (ad y)) ) \<le> ad ( |x\<rangle> y ))"
using a_antitone' fdia_def by fastforce
also have "... \<longleftrightarrow> (\<forall>y. |x] ad (d y \<cdot> |x] (ad y)) \<le> |x] (ad y))"
by (simp add: fdia_fbox_de_morgan_2)
also have "... \<longleftrightarrow> (\<forall>y. |x] (d (ad y) + ad ( |x] (ad y) )) \<le> |x] (ad y))"
by (simp add: local.ads_d_def local.fbox_def)
finally show ?thesis
by (metis add_commute local.a_d_closed local.ads_d_def local.apd_d_def local.fbox_def)
qed
end
subsection \<open>Divergence Kleene Algebras and Separation of Termination\<close>
text \<open>The notion of divergence has been added to modal Kleene algebras in~\<^cite>\<open>"DesharnaisMoellerStruthLMCS"\<close>.
More facts about divergence could be added in the future. Some could be adapted from omega algebras.\<close>
class nabla_op =
fixes nabla :: "'a \<Rightarrow> 'a" ("\<nabla>_" [999] 1000)
class fdivergence_kleene_algebra = antidomain_kleene_algebra + nabla_op +
assumes nabla_closure [simp]: "d \<nabla> x = \<nabla> x"
and nabla_unfold: "\<nabla> x \<le> |x\<rangle> \<nabla> x"
and nabla_coinduction: "d y \<le> |x\<rangle> y + d z \<Longrightarrow> d y \<le> \<nabla> x + |x\<^sup>\<star>\<rangle> z"
begin
lemma nabla_coinduction_var: "d y \<le> |x\<rangle> y \<Longrightarrow> d y \<le> \<nabla> x"
proof -
assume "d y \<le> |x\<rangle> y"
hence "d y \<le> |x\<rangle> y + d 0"
by simp
hence "d y \<le> \<nabla> x + |x\<^sup>\<star>\<rangle> 0"
using nabla_coinduction by blast
thus "d y \<le> \<nabla> x"
by (simp add: fdia_def)
qed
lemma nabla_unfold_eq [simp]: "|x\<rangle> \<nabla> x = \<nabla> x"
proof -
have f1: "ad (ad (x \<cdot> \<nabla>x)) = ad (ad (x \<cdot> \<nabla>x)) + \<nabla>x"
using local.ds.fd_def local.join.sup.order_iff local.nabla_unfold by presburger
then have "ad (ad (x \<cdot> \<nabla>x)) \<cdot> ad (ad \<nabla>x) = \<nabla>x"
by (metis local.ads_d_def local.dpdz.dns5 local.dpdz.dsg4 local.join.sup_commute local.nabla_closure)
then show ?thesis
using f1 by (metis local.ads_d_def local.ds.fd_def local.ds.fd_subdist_2 local.join.sup.order_iff local.join.sup_commute nabla_coinduction_var)
qed
lemma nabla_subdist: "\<nabla> x \<le> \<nabla> (x + y)"
proof -
have "d \<nabla> x \<le> \<nabla> (x + y)"
by (metis local.ds.fd_iso2 local.join.sup.cobounded1 local.nabla_closure nabla_coinduction_var nabla_unfold_eq)
thus ?thesis
by simp
qed
lemma nabla_iso: "x \<le> y \<Longrightarrow> \<nabla> x \<le> \<nabla> y"
by (metis less_eq_def nabla_subdist)
lemma nabla_omega: "\<Omega> x (d y) = 0 \<Longrightarrow> d y \<le> \<nabla> x"
using omega_zero_equiv_1 nabla_coinduction_var by fastforce
lemma nabla_noether: "\<nabla> x = 0 \<Longrightarrow> Noetherian x"
using local.join.le_bot local.noetherian_alt nabla_coinduction_var by blast
lemma nabla_preloeb: "\<nabla> x = 0 \<Longrightarrow> PreLoebian x"
using Noetherian_iff_PreLoebian nabla_noether by auto
lemma star_nabla_1 [simp]: "|x\<^sup>\<star>\<rangle> \<nabla> x = \<nabla> x"
proof (rule order.antisym)
show "|x\<^sup>\<star>\<rangle> \<nabla> x \<le> \<nabla> x"
by (metis dka.fdia_star_induct_var order.eq_iff nabla_closure nabla_unfold_eq)
show "\<nabla> x \<le> |x\<^sup>\<star>\<rangle> \<nabla> x"
by (metis ds.fd_iso2 star_ext nabla_unfold_eq)
qed
lemma nabla_sum_expand [simp]: "|x\<rangle> \<nabla> (x + y) + |y\<rangle> \<nabla> (x + y) = \<nabla> (x + y)"
proof -
have "d ((x + y) \<cdot> \<nabla>(x + y)) = \<nabla>(x + y)"
using local.dka.fd_def nabla_unfold_eq by presburger
thus ?thesis
by (simp add: local.dka.fd_def)
qed
lemma wagner_3:
assumes "d z + |x\<rangle> \<nabla> (x + y) = \<nabla> (x + y)"
shows "\<nabla> (x + y) = \<nabla> x + |x\<^sup>\<star>\<rangle> z"
proof (rule order.antisym)
have "d \<nabla>(x + y) \<le> d z + |x\<rangle> \<nabla>(x + y)"
by (simp add: assms)
thus "\<nabla> (x + y) \<le> \<nabla> x + |x\<^sup>\<star>\<rangle> z"
by (metis add_commute nabla_closure nabla_coinduction)
have "d z + |x\<rangle> \<nabla> (x + y) \<le> \<nabla> (x + y)"
using assms by auto
hence "|x\<^sup>\<star>\<rangle> z \<le> \<nabla> (x + y)"
by (metis local.dka.fdia_star_induct local.nabla_closure)
thus "\<nabla> x + |x\<^sup>\<star>\<rangle> z \<le> \<nabla> (x + y)"
by (simp add: sup_least nabla_subdist)
qed
lemma nabla_sum_unfold [simp]: "\<nabla> x + |x\<^sup>\<star>\<rangle> |y\<rangle> \<nabla> (x + y) = \<nabla> (x + y)"
proof -
have "\<nabla> (x + y) = |x\<rangle> \<nabla> (x + y) + |y\<rangle> \<nabla> (x + y)"
by simp
thus ?thesis
by (metis add_commute local.dka.fd_def local.ds.fd_def local.ds.fdia_d_simp wagner_3)
qed
lemma nabla_separation: "y \<cdot> x \<le> x \<cdot> (x + y)\<^sup>\<star> \<Longrightarrow> (\<nabla> (x + y) = \<nabla> x + |x\<^sup>\<star>\<rangle> \<nabla> y)"
proof (rule order.antisym)
assume quasi_comm: "y \<cdot> x \<le> x \<cdot> (x + y)\<^sup>\<star>"
hence a: "y\<^sup>\<star> \<cdot> x \<le> x \<cdot> (x + y)\<^sup>\<star>"
using quasicomm_var by blast
have "\<nabla> (x + y) = \<nabla> y + |y\<^sup>\<star>\<cdot> x\<rangle> \<nabla> (x + y)"
by (metis local.ds.fdia_mult local.join.sup_commute nabla_sum_unfold)
also have "... \<le> \<nabla> y + |x \<cdot> (x + y)\<^sup>\<star>\<rangle> \<nabla> (x + y)"
using a local.ds.fd_iso2 local.join.sup.mono by blast
also have "... = \<nabla> y + |x\<rangle> |(x + y)\<^sup>\<star>\<rangle> \<nabla> (x + y)"
by (simp add: fdia_def mult_assoc)
finally have "\<nabla> (x + y) \<le> \<nabla> y + |x\<rangle> \<nabla> (x + y)"
by (metis star_nabla_1)
thus "\<nabla> (x + y) \<le> \<nabla> x + |x\<^sup>\<star>\<rangle> \<nabla> y"
by (metis add_commute nabla_closure nabla_coinduction)
next
have "\<nabla> x + |x\<^sup>\<star>\<rangle> \<nabla> y = \<nabla> x + |x\<^sup>\<star>\<rangle> |y\<rangle> \<nabla> y"
by simp
also have "... = \<nabla> x + |x\<^sup>\<star> \<cdot> y\<rangle> \<nabla> y"
by (simp add: fdia_def mult_assoc)
also have "... \<le> \<nabla> x + |x\<^sup>\<star> \<cdot> y\<rangle> \<nabla> (x + y)"
using dpdz.dom_iso eq_refl fdia_def join.sup_ge2 join.sup_mono mult_isol nabla_iso by presburger
also have "... = \<nabla> x + |x\<^sup>\<star>\<rangle> |y\<rangle> \<nabla> (x + y)"
by (simp add: fdia_def mult_assoc)
finally show "\<nabla> x + |x\<^sup>\<star>\<rangle> \<nabla> y \<le> \<nabla> (x + y)"
by (metis nabla_sum_unfold)
qed
text \<open>The next lemma is a separation of termination theorem by Bachmair and Dershowitz~\<^cite>\<open>"bachmair86commutation"\<close>.\<close>
lemma bachmair_dershowitz: "y \<cdot> x \<le> x \<cdot> (x + y)\<^sup>\<star> \<Longrightarrow> \<nabla> x + \<nabla> y = 0 \<longleftrightarrow> \<nabla> (x + y) = 0"
proof -
assume quasi_comm: "y \<cdot> x \<le> x \<cdot> (x + y)\<^sup>\<star>"
have "\<forall>x. |x\<rangle> 0 = 0"
by (simp add: fdia_def)
hence "\<nabla>y = 0 \<Longrightarrow> \<nabla>x + \<nabla>y = 0 \<longleftrightarrow> \<nabla>(x + y) = 0"
using quasi_comm nabla_separation by presburger
thus ?thesis
using add_commute local.join.le_bot nabla_subdist by fastforce
qed
text \<open>The next lemma is a more complex separation of termination theorem by Doornbos,
Backhouse and van der Woude~\<^cite>\<open>"doornbos97calculational"\<close>.\<close>
lemma separation_of_termination:
assumes "y \<cdot> x \<le> x \<cdot> (x + y)\<^sup>\<star> + y"
shows "\<nabla> x + \<nabla> y = 0 \<longleftrightarrow> \<nabla> (x + y) = 0"
proof
assume xy_wf: "\<nabla> x + \<nabla> y = 0"
hence x_preloeb: "\<nabla> (x + y) \<le> |x\<^sup>\<star>\<rangle> \<Omega> x (\<nabla> (x + y))"
by (metis PreLoebian_def no_trivial_inverse nabla_closure nabla_preloeb)
hence y_div: "\<nabla> y = 0"
using add_commute no_trivial_inverse xy_wf by blast
have "\<nabla> (x + y) \<le> |y\<rangle> \<nabla> (x + y) + |x\<rangle> \<nabla> (x + y)"
by (simp add: local.join.sup_commute)
hence "\<nabla> (x + y) \<cdot> ad ( |x\<rangle> \<nabla> (x + y) ) \<le> |y\<rangle> \<nabla>(x + y)"
by (simp add: local.da_shunt1 local.dka.fd_def local.join.sup_commute)
hence "\<Omega> x \<nabla>(x + y) \<le> |y\<rangle> \<nabla> (x + y)"
by (simp add: fdia_def omega_fdia)
also have "... \<le> |y\<rangle> |x\<^sup>\<star>\<rangle> (\<Omega> x \<nabla>(x + y))"
using local.dpdz.dom_iso local.ds.fd_iso1 x_preloeb by blast
also have "... = |y \<cdot> x\<^sup>\<star>\<rangle> (\<Omega> x \<nabla>(x + y))"
by (simp add: fdia_def mult_assoc)
also have "... \<le> |x \<cdot> (x + y)\<^sup>\<star> + y\<rangle> (\<Omega> x \<nabla>(x + y))"
using assms local.ds.fd_iso2 local.lazycomm_var by blast
also have "... = |x \<cdot> (x + y)\<^sup>\<star>\<rangle> (\<Omega> x \<nabla>(x + y)) + |y\<rangle> (\<Omega> x \<nabla>(x + y))"
by (simp add: local.dka.fd_def)
also have "... \<le> |(x \<cdot> (x + y)\<^sup>\<star>)\<rangle> \<nabla>(x + y) + |y\<rangle> (\<Omega> x \<nabla>(x + y))"
using local.add_iso local.dpdz.domain_1'' local.ds.fd_iso1 local.omega_fdia by auto
also have "... \<le> |x\<rangle> |(x + y)\<^sup>\<star>\<rangle> \<nabla>(x + y) + |y\<rangle> (\<Omega> x \<nabla>(x + y))"
by (simp add: fdia_def mult_assoc)
finally have "\<Omega> x \<nabla>(x + y) \<le> |x\<rangle> \<nabla>(x + y) + |y\<rangle> (\<Omega> x \<nabla>(x + y))"
by (metis star_nabla_1)
hence "\<Omega> x \<nabla>(x + y) \<cdot> ad ( |x\<rangle> \<nabla>(x + y) ) \<le> |y\<rangle> (\<Omega> x \<nabla>(x + y))"
by (simp add: local.da_shunt1 local.dka.fd_def)
hence "\<Omega> x \<nabla>(x + y) \<le> |y\<rangle> (\<Omega> x \<nabla>(x + y))"
by (simp add: omega_fdia mult_assoc)
hence "(\<Omega> x \<nabla>(x + y)) = 0"
by (metis noetherian_alt omega_dom nabla_noether y_div)
thus "\<nabla> (x + y) = 0"
using local.dka.fd_def local.join.le_bot x_preloeb by auto
next
assume "\<nabla> (x + y) = 0"
thus "(\<nabla> x) + (\<nabla> y) = 0"
by (metis local.join.le_bot local.join.sup.order_iff local.join.sup_commute nabla_subdist)
qed
text \<open>The final examples can be found in~\<^cite>\<open>"guttmannstruthweber11algmeth"\<close>.\<close>
definition T :: "'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a" ("_ \<leadsto> _ \<leadsto> _" [61,61,61] 60)
where "p\<leadsto>x\<leadsto>q \<equiv> ad p + |x] d q"
lemma T_d [simp]: "d (p\<leadsto>x\<leadsto>q) = p\<leadsto>x\<leadsto>q"
using T_def local.a_d_add_closure local.fbox_def by auto
lemma T_p: "d p \<cdot> (p\<leadsto>x\<leadsto>q) = d p \<cdot> |x] d q"
proof -
have "d p \<cdot> (p\<leadsto>x\<leadsto>q) = ad (ad p + ad (p\<leadsto>x\<leadsto>q))"
using T_d local.ads_d_def by auto
thus ?thesis
using T_def add_commute local.a_mult_add local.ads_d_def by auto
qed
lemma T_a [simp]: "ad p \<cdot> (p\<leadsto>x\<leadsto>q) = ad p"
by (metis T_d T_def local.a_d_closed local.ads_d_def local.apd_d_def local.dpdz.dns5 local.join.sup.left_idem)
lemma T_seq: "(p\<leadsto>x\<leadsto>q) \<cdot> |x](q\<leadsto>y\<leadsto>s) \<le> p\<leadsto>x \<cdot> y\<leadsto>s"
proof -
have f1: "|x] q = |x] d q"
using local.fbox_simp by auto
have "ad p \<cdot> ad (x \<cdot> ad (q\<leadsto>y\<leadsto>s)) + |x] d q \<cdot> |x] (ad q + |y] d s) \<le> ad p + |x] d q \<cdot> |x] (ad q + |y] d s)"
using local.a_subid_aux2 local.add_iso by blast
hence "(p\<leadsto>x\<leadsto>q) \<cdot> |x](q\<leadsto>y\<leadsto>s) \<le> ad p + |x](d q \<cdot> (q\<leadsto>y\<leadsto>s))"
by (metis T_d T_def f1 local.distrib_right' local.fbox_add1 local.fbox_def)
also have "... = ad p + |x](d q \<cdot> (ad q + |y] d s))"
by (simp add: T_def)
also have "... = ad p + |x](d q \<cdot> |y] d s)"
using T_def T_p by auto
also have "... \<le> ad p + |x] |y] d s"
by (metis (no_types, lifting) dka.dom_subid_aux2 dka.dsg3 order.eq_iff fbox_iso join.sup.mono)
finally show ?thesis
by (simp add: T_def fbox_mult)
qed
lemma T_square: "(p\<leadsto>x\<leadsto>q) \<cdot> |x](q\<leadsto>x\<leadsto>p) \<le> p\<leadsto>x\<cdot>x\<leadsto>p"
by (simp add: T_seq)
lemma T_segerberg [simp]: "d p \<cdot> |x\<^sup>\<star>](p\<leadsto>x\<leadsto>p) = |x\<^sup>\<star>] d p"
using T_def add_commute local.fbox_segerberg local.fbox_simp by force
lemma lookahead [simp]: "|x\<^sup>\<star>](d p \<cdot> |x] d p) = |x\<^sup>\<star>] d p"
by (metis (full_types) local.dka.dsg3 local.fbox_add1 local.fbox_mult local.fbox_simp local.fbox_star_unfold_var local.star_slide_var local.star_trans_eq)
lemma alternation: "d p \<cdot> |x\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p)) = |(x\<cdot>x)\<^sup>\<star>](d p \<cdot> (q\<leadsto>x\<leadsto>p)) \<cdot> |x\<cdot>(x\<cdot>x)\<^sup>\<star>](d q \<cdot> (p\<leadsto>x\<leadsto>q))"
proof -
have fbox_simp_2: "\<And>x p. |x]p = d( |x] p )"
using local.a_d_closed local.ads_d_def local.apd_d_def local.fbox_def by fastforce
have "|(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> |x](q\<leadsto>x\<leadsto>p) \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x](p\<leadsto>x\<leadsto>q)) \<le> |(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> |x](q\<leadsto>x\<leadsto>p))"
using local.dka.domain_1'' local.fbox_iso local.order_trans by blast
also have "... \<le> |(x\<cdot>x)\<^sup>\<star>](p\<leadsto>x\<cdot>x\<leadsto>p)"
using T_seq local.dka.dom_iso local.fbox_iso by blast
finally have 1: "|(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> |x](q\<leadsto>x\<leadsto>p) \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x](p\<leadsto>x\<leadsto>q)) \<le> |(x\<cdot>x)\<^sup>\<star>](p\<leadsto>x\<cdot>x\<leadsto>p)".
have "d p \<cdot> |x\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p)) = d p \<cdot> |1+x] |(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p))"
by (metis (full_types) fbox_mult meyer_1)
also have "... = d p \<cdot> |(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p)) \<cdot> |x\<cdot>(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p))"
using fbox_simp_2 fbox_mult fbox_add2 mult_assoc by auto
also have "... = d p \<cdot> |(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p)) \<cdot> |(x\<cdot>x)\<^sup>\<star>\<cdot>x]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p))"
by (simp add: star_slide)
also have "... = d p \<cdot> |(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p)) \<cdot> |(x\<cdot>x)\<^sup>\<star>] |x]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p))"
by (simp add: fbox_mult)
also have "... = d p \<cdot> |(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x]((p\<leadsto>x\<leadsto>q) \<cdot> (q\<leadsto>x\<leadsto>p)))"
by (metis T_d fbox_simp_2 local.dka.dom_mult_closed local.fbox_add1 mult_assoc)
also have "... = d p \<cdot> |(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> |x](q\<leadsto>x\<leadsto>p) \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x](p\<leadsto>x\<leadsto>q))"
proof -
have f1: "d ((q \<leadsto> x \<leadsto> p) \<cdot> |x] (p \<leadsto> x \<leadsto> q)) = (q \<leadsto> x \<leadsto> p) \<cdot> |x] (p \<leadsto> x \<leadsto> q)"
by (metis (full_types) T_d fbox_simp_2 local.dka.dsg3)
then have "|(x \<cdot> x)\<^sup>\<star>] (d ( |x] (q \<leadsto> x \<leadsto> p)) \<cdot> ((q \<leadsto> x \<leadsto> p) \<cdot> |x] (p \<leadsto> x \<leadsto> q))) = |(x \<cdot> x)\<^sup>\<star>] d ( |x] (q \<leadsto> x \<leadsto> p)) \<cdot> |(x \<cdot> x)\<^sup>\<star>] ((q \<leadsto> x \<leadsto> p) \<cdot> |x] (p \<leadsto> x \<leadsto> q))"
by (metis (full_types) fbox_simp_2 local.fbox_add1)
then have f2: "|(x \<cdot> x)\<^sup>\<star>] (d ( |x] (q \<leadsto> x \<leadsto> p)) \<cdot> ((q \<leadsto> x \<leadsto> p) \<cdot> |x] (p \<leadsto> x \<leadsto> q))) = ad ((x \<cdot> x)\<^sup>\<star> \<cdot> ad ((q \<leadsto> x \<leadsto> p) \<cdot> |x] (p \<leadsto> x \<leadsto> q)) + (x \<cdot> x)\<^sup>\<star> \<cdot> ad (d ( |x] (q \<leadsto> x \<leadsto> p))))"
by (simp add: add_commute local.fbox_def)
have "d ( |x] (p \<leadsto> x \<leadsto> q)) \<cdot> d ( |x] (q \<leadsto> x \<leadsto> p)) = |x] ((p \<leadsto> x \<leadsto> q) \<cdot> (q \<leadsto> x \<leadsto> p))"
by (metis (no_types) T_d fbox_simp_2 local.fbox_add1)
then have "d ((q \<leadsto> x \<leadsto> p) \<cdot> |x] (p \<leadsto> x \<leadsto> q)) \<cdot> d (d ( |x] (q \<leadsto> x \<leadsto> p))) = (q \<leadsto> x \<leadsto> p) \<cdot> |x] ((p \<leadsto> x \<leadsto> q) \<cdot> (q \<leadsto> x \<leadsto> p))"
using f1 fbox_simp_2 mult_assoc by force
then have "|(x \<cdot> x)\<^sup>\<star>] (d ( |x] (q \<leadsto> x \<leadsto> p)) \<cdot> ((q \<leadsto> x \<leadsto> p) \<cdot> |x] (p \<leadsto> x \<leadsto> q))) = |(x \<cdot> x)\<^sup>\<star>] ((q \<leadsto> x \<leadsto> p) \<cdot> |x] ((p \<leadsto> x \<leadsto> q) \<cdot> (q \<leadsto> x \<leadsto> p)))"
using f2 by (metis (no_types) local.ans4 local.fbox_add1 local.fbox_def)
then show ?thesis
by (metis (no_types) T_d fbox_simp_2 local.dka.dsg3 local.fbox_add1 mult_assoc)
qed
also have "... = d p \<cdot> |(x\<cdot>x)\<^sup>\<star>](p\<leadsto>x\<cdot>x\<leadsto>p) \<cdot> |(x\<cdot>x)\<^sup>\<star>]((p\<leadsto>x\<leadsto>q) \<cdot> |x](q\<leadsto>x\<leadsto>p) \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x](p\<leadsto>x\<leadsto>q))" using "1"
by (metis fbox_simp_2 dka.dns5 dka.dsg4 join.sup.absorb2 mult_assoc)
also have "... = |(x\<cdot>x)\<^sup>\<star>](d p \<cdot> (p\<leadsto>x\<leadsto>q) \<cdot> |x](q\<leadsto>x\<leadsto>p) \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x](p\<leadsto>x\<leadsto>q))"
using T_segerberg local.a_d_closed local.ads_d_def local.apd_d_def local.distrib_left local.fbox_def mult_assoc by auto
also have "... = |(x\<cdot>x)\<^sup>\<star>](d p \<cdot> |x] d q \<cdot> |x](q\<leadsto>x\<leadsto>p) \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x](p\<leadsto>x\<leadsto>q))"
by (simp add: T_p)
also have "... = |(x\<cdot>x)\<^sup>\<star>](d p \<cdot> |x] d q \<cdot> |x] |x] d p \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x](p\<leadsto>x\<leadsto>q))"
by (metis T_d T_p fbox_simp_2 fbox_add1 fbox_simp mult_assoc)
also have "... = |(x\<cdot>x)\<^sup>\<star>](d p \<cdot> |x\<cdot>x] d p \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x] d q \<cdot> |x](p\<leadsto>x\<leadsto>q))"
proof -
have f1: "ad (x \<cdot> ad ( |x] d p)) = |x \<cdot> x] d p"
using local.fbox_def local.fbox_mult by presburger
have f2: "ad (d q \<cdot> d (x \<cdot> ad (d p))) = q \<leadsto> x \<leadsto> p"
by (simp add: T_def local.a_de_morgan_var_4 local.fbox_def)
have "ad q + |x] d p = ad (d q \<cdot> d (x \<cdot> ad (d p)))"
by (simp add: local.a_de_morgan_var_4 local.fbox_def)
then have "ad (x \<cdot> ad ( |x] d p)) \<cdot> ((q \<leadsto> x \<leadsto> p) \<cdot> |x] d q) = ad (x \<cdot> ad ( |x] d p)) \<cdot> ad (x \<cdot> ad (d q)) \<cdot> (ad q + |x] d p)"
using f2 by (metis (no_types) local.am2 local.fbox_def mult_assoc)
then show ?thesis
using f1 by (simp add: T_def local.am2 local.fbox_def mult_assoc)
qed
also have "... = |(x\<cdot>x)\<^sup>\<star>](d p \<cdot> |x\<cdot>x] d p \<cdot> (q\<leadsto>x\<leadsto>p) \<cdot> |x](d q \<cdot> (p\<leadsto>x\<leadsto>q)))"
using local.a_d_closed local.ads_d_def local.apd_d_def local.distrib_left local.fbox_def mult_assoc by auto
also have "... = |(x\<cdot>x)\<^sup>\<star>](d p \<cdot> |x\<cdot>x] d p) \<cdot> |(x\<cdot>x)\<^sup>\<star>](q\<leadsto>x\<leadsto>p) \<cdot> |(x\<cdot>x)\<^sup>\<star>] |x](d q \<cdot> (p\<leadsto>x\<leadsto>q))"
by (metis T_d fbox_simp_2 local.dka.dom_mult_closed local.fbox_add1)
also have "... = |(x\<cdot>x)\<^sup>\<star>](d p \<cdot> (q\<leadsto>x\<leadsto>p)) \<cdot> |(x\<cdot>x)\<^sup>\<star>] |x] (d q \<cdot> (p\<leadsto>x\<leadsto>q))"
by (metis T_d local.fbox_add1 local.fbox_simp lookahead)
finally show ?thesis
by (metis fbox_mult star_slide)
qed
lemma "|(x\<cdot>x)\<^sup>\<star>] d p \<cdot> |x\<cdot>(x\<cdot>x)\<^sup>\<star>] ad p = d p \<cdot> |x\<^sup>\<star>]((p\<leadsto>x\<leadsto>ad p) \<cdot> (ad p\<leadsto>x\<leadsto>p))"
using alternation local.a_d_closed local.ads_d_def local.apd_d_def by auto
lemma "|x\<^sup>\<star>] d p = d p \<cdot> |x\<^sup>\<star>](p\<leadsto>x\<leadsto>p)"
by (simp add: alternation)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.