text
stringlengths 0
3.34M
|
---|
function change(file)
[np,nf]=num(file);
fprintf('Number_of_point:%d\n',np);
fprintf('Number_of_face:%d\n',nf);
fid=fopen('OFF','w');
fprintf(fid,'OFF\n');
fprintf(fid,'%d %d 0\n',np,nf);
fid2=fopen(file);
H=0;
while 1
tline=fgetl(fid2);
H=H+1;
if ~ischar(tline) , break , end
if H > 1
disp(tline)
fprintf(fid,'%s\n',tline);
end
end
fclose(fid2);
fclose(fid);
function [np,nf]=num(file)
fid=fopen(file);
C=0;
while 1
tline=fgetl(fid);
C=C+1;
if C==1
num=textscan(tline,'%s %d %d %d');
break;
end
if ~ischar(tline) , break , end
end
fclose(fid);
np=num{1,2};
nf=num{1,3};
|
import data.real.basic
import data.int.parity
/-
In this file, we learn how to handle the ∃ quantifier.
In order to prove `∃ x, P x`, we give some x₀ using tactic `use x₀` and
then prove `P x₀`. This x₀ can be an object from the local context
or a more complicated expression.
-/
example : ∃ n : ℕ, 8 = 2*n :=
begin
use 4,
refl, -- this is the tactic analogue of the rfl proof term
end
/-
In order to use `h : ∃ x, P x`, we use the `cases` tactic to fix
one x₀ that works.
Again h can come straight from the local context or can be a more
complicated expression.
-/
example (n : ℕ) (h : ∃ k : ℕ, n = k + 1) : n > 0 :=
begin
-- Let's fix k₀ such that n = k₀ + 1.
cases h with k₀ hk₀,
-- It now suffices to prove k₀ + 1 > 0.
rw hk₀,
-- and we have a lemma about this
exact nat.succ_pos k₀,
end
/-
The next exercises use divisibility in ℤ (beware the ∣ symbol which is
not ASCII).
By definition, a ∣ b ↔ ∃ k, b = a*k, so you can prove a ∣ b using the
`use` tactic.
-/
-- Until the end of this file, a, b and c will denote integers, unless
-- explicitly stated otherwise
variables (a b c : ℤ)
-- 0029
example (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c :=
begin
-- sorry
cases h₁ with k hk,
cases h₂ with l hl,
use k*l,
calc c = b*l : hl
... = (a*k)*l : by rw hk
... = a*(k*l) : by ring,
-- sorry
end
/-
A very common pattern is to have an assumption or lemma asserting
h : ∃ x, y = ...
and this is used through the combo:
cases h with x hx,
rw hx at ...
The tactic `rcases` allows us to do recursive `cases`, as indicated by its name,
and also simplifies the above combo when the name hx is replaced by the special
name `rfl`, as in the following example.
It uses the anonymous constructor angle brackets syntax.
-/
example (h1 : a ∣ b) (h2 : a ∣ c) : a ∣ b+c :=
begin
rcases h1 with ⟨k, rfl⟩,
rcases h2 with ⟨l, rfl⟩,
use k+l,
ring,
end
/-
You can use the same `rfl` trick with the `rintros` tactic.
-/
example : a ∣ b → a ∣ c → a ∣ b+c :=
begin
rintros ⟨k, rfl⟩ ⟨l, rfl⟩,
use k+l,
ring,
end
-- 0030
example : 0 ∣ a ↔ a = 0 :=
begin
-- sorry
split,
{ rintro ⟨k, rfl⟩,
ring, },
{ rintro rfl,
use 0,
refl, },
-- sorry
end
/-
We can now start combining quantifiers, using the definition
surjective (f : X → Y) := ∀ y, ∃ x, f x = y
-/
open function
-- In the remaining of this file, f and g will denote functions from
-- ℝ to ℝ.
variables (f g : ℝ → ℝ)
-- 0031
example (h : surjective (g ∘ f)) : surjective g :=
begin
-- sorry
intro y,
rcases h y with ⟨w, rfl⟩,
use f w,
-- sorry
end
/-
The above exercise can be done in three lines. Try to do the
next exercise in four lines.
-/
-- 0032
example (hf : surjective f) (hg : surjective g) : surjective (g ∘ f) :=
begin
-- sorry
intro z,
rcases hg z with ⟨y, rfl⟩,
rcases hf y with ⟨x, rfl⟩,
use x,
-- sorry
end
|
pdf_file<-"pdf/maps_world_great_circles.pdf"
cairo_pdf(bg="grey98", pdf_file,width=13.75,height=8)
par(omi=c(0.5,0.5,1.25,0.5),mai=c(0,0,0,0),lend=1,bg="antiquewhite",family="Lato Light")
library(mapdata)
library(geosphere)
library(gdata)
# library(mapproj)
# Import data and prepare chart
myProj.type<-"mercator"
myProj.orient<-c(90,0,30)
x<-map(proj=myProj.type,orient=myProj.orient,wrap=T)
# Create chart and other elements
plot(x,xlim=c(-3,3),ylim=c(-1,2),type="n",axes=F,xaxs="i",yaxs="i")
rect(-3,-1,3,3,col="aliceblue",border=NA)
map("worldHires","Germany",fill=T,add=T,col="antiquewhite",proj=myProj.type,orient=myProj.orient)
lines(x,col="darkgrey")
data(world.cities)
myData<-read.xls("myData/orthodat.xlsx", encoding="latin1")
attach(myData)
myTColour<-rgb(128,128,128,100,maxColorValue=255)
for (i in 1:nrow(myData))
{
myStart<-world.cities[11769,] # Frankfurt
myDestination<-subset(world.cities,name==stadt[i] & country.etc==land[i])
myGC1<-gcIntermediate(c(myStart$long,myStart$lat),c(myDestination$long,myDestination$lat),addStartEnd=T, n=50)
merc<-mapproject(myGC1[,1],myGC1[,2],projection=myProj.type,orientation=myProj.orient)
lines(merc$x,merc$y,lwd=10,col=myTColour)
myDestP<-mapproject(myDestination$long,myDestination$lat,proj=myProj.type,orient=myProj.orient)
points(myDestP,col="darkred",pch=19,cex=2)
}
myStartP<-mapproject(myStart$long,myStart$lat,proj=myProj.type,orient=myProj.orient)
points(myStartP,col="darkblue",pch=19,cex=2)
# Titling
mtext("Destination Airports of Airbus A380 (Lufthansa)",3,line=3,adj=0,cex=3,family="Lato Black",outer=T)
mtext("As of: August 2013",3,line=1,adj=0,cex=1.75,font=3,outer=T)
mtext("Source: de.wikipedia.org/wiki/Lufthansa",1,line=0.8,adj=1.0,cex=1.25,font=3)
dev.off()
|
lemma lebesgue_real_scale: assumes "c \<noteq> 0" shows "lebesgue = density (distr lebesgue lebesgue (\<lambda>x. c * x)) (\<lambda>x. ennreal \<bar>c\<bar>)"
|
Polish music , including orchestras , also went underground . Top Polish musicians and directors ( Adam <unk> , Zbigniew <unk> , Jan <unk> , Barbara <unk> , Zygmunt <unk> , Jerzy <unk> , Witold Lutosławski , Andrzej Panufnik , Piotr <unk> , Edmund Rudnicki , Eugenia <unk> , Jerzy <unk> , Kazimierz <unk> , Maria <unk> , Bolesław Woytowicz , Mira <unk> ) performed in restaurants , cafes , and private homes , with the most daring singing patriotic ballads on the streets while evading German patrols . Patriotic songs were written , such as <unk> , <unk> , the most popular song of occupied Warsaw . Patriotic puppet shows were staged . Jewish musicians ( e.g. Władysław Szpilman ) and artists likewise performed in ghettos and even in concentration camps . Although many of them died , some survived abroad , like Alexandre <unk> in the United States , and Eddie Rosner and Henryk Wars in the Soviet Union .
|
/// @file MPIComms.cc
///
/// @copyright (c) 2012 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// [email protected]
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Ben Humphreys <[email protected]>
// Include own header file first
#include "MPIComms.h"
// Include package level header file
#include "askap_askapparallel.h"
// System includes
#include <string>
#include <cstring>
#include <sstream>
#include <stdexcept>
#include <stdint.h>
#include <limits>
#include <algorithm>
// boost
#include <boost/shared_array.hpp>
// MPI includes
#ifdef HAVE_MPI
#include <mpi.h>
#endif
// ASKAPsoft includes
#include "askap/AskapLogging.h"
#include "askap/AskapError.h"
using namespace askap::askapparallel;
ASKAP_LOGGER(logger, ".MPIComms");
#ifdef HAVE_MPI
MPIComms::MPIComms(int argc, char *argv[]) : itsCommunicators(1, MPI_COMM_NULL)
{
int rc = MPI_Init(&argc, &argv);
if (rc != MPI_SUCCESS) {
ASKAPTHROW(AskapError, "Error starting MPI. Terminating.");
MPI_Abort(MPI_COMM_WORLD, rc);
}
// Duplicate the communicator so this class
// doesn't conflict with other uses of MPI
// this is the default communicator with index 0,
// the only one available up front
MPI_Comm_dup(MPI_COMM_WORLD, &itsCommunicators[0]);
}
MPIComms::~MPIComms()
{
for (size_t comm = itsCommunicators.size(); comm>0; --comm) {
if (itsCommunicators[comm-1] != MPI_COMM_NULL) {
MPI_Comm_free(&itsCommunicators[comm-1]);
}
}
MPI_Finalize();
}
std::string MPIComms::nodeName(void) const
{
char name[MPI_MAX_PROCESSOR_NAME];
int resultlen;
MPI_Get_processor_name(name, &resultlen);
std::string pname(name);
std::string::size_type idx = pname.find_first_of('.');
if (idx != std::string::npos) {
// Extract just the hostname part
pname = pname.substr(0, idx);
}
return pname;
}
int MPIComms::rank(size_t comm) const
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
int rank = -1;
int result = MPI_Comm_rank(itsCommunicators[comm], &rank);
checkError(result, "MPI_Comm_rank");
return rank;
}
int MPIComms::nProcs(size_t comm) const
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
int numtasks = -1;
int result = MPI_Comm_size(itsCommunicators[comm], &numtasks);
checkError(result, "MPI_Comm_size");
return numtasks;
}
void MPIComms::abort(size_t comm)
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
int result = MPI_Abort(itsCommunicators[comm], 0);
checkError(result, "MPI_Abort");
}
void MPIComms::barrier(size_t comm)
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
int result = MPI_Barrier(itsCommunicators[comm]);
checkError(result, "MPI_Abort");
}
/// @brief create a new communicator
/// @details This method creates a new communicator and returns the index.
/// This index can later be used as a parameter for communication methods
/// instead of the default one.
/// @param[in] group ranks to include in the new communicator
/// @param[in] comm communicator index where a new subgroup is created,
/// defaults to 0 (copy of the default world communicator)
/// @return new communicator index
size_t MPIComms::createComm(const std::vector<int> &group, size_t comm)
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(group.size() > 0);
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
MPI_Comm newComm = MPI_COMM_NULL;
MPI_Group origGroup = MPI_GROUP_NULL, newGroup = MPI_GROUP_NULL;
int result = MPI_Comm_group(itsCommunicators[comm], &origGroup);
checkError(result, "MPI_Comm_Group");
boost::shared_array<int> ranksBuf(new int[group.size()]);
std::copy(group.begin(),group.end(),ranksBuf.get());
result = MPI_Group_incl(origGroup, int(group.size()), ranksBuf.get(), &newGroup);
checkError(result, "MPI_Group_incl");
result = MPI_Comm_create(itsCommunicators[comm], newGroup, &newComm);
checkError(result, "MPI_Comm_create");
ASKAPDEBUGASSERT(newGroup != MPI_GROUP_NULL);
result = MPI_Group_free(&newGroup);
checkError(result, "MPI_Group_free");
ASKAPDEBUGASSERT(origGroup != MPI_GROUP_NULL);
result = MPI_Group_free(&origGroup);
checkError(result, "MPI_Group_free");
const size_t newIndex = itsCommunicators.size();
itsCommunicators.push_back(newComm);
return newIndex;
}
void MPIComms::send(const void* buf, size_t size, int dest, int tag, size_t comm)
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
const unsigned int c_maxint = std::numeric_limits<int>::max();
// First send the size of the buffer.
unsigned long lsize = size; // Promote for simplicity
int result = MPI_Send(&lsize, 1, MPI_UNSIGNED_LONG, dest, tag, itsCommunicators[comm]);
checkError(result, "MPI_Send");
// Send in chunks of size MAXINT until complete
size_t remaining = size;
while (remaining > 0) {
size_t offset = size - remaining;
void* addr = addOffset(buf, offset);
if (remaining >= c_maxint) {
result = MPI_Send(addr, c_maxint, MPI_BYTE,
dest, tag, itsCommunicators[comm]);
remaining -= c_maxint;
} else {
result = MPI_Send(addr, remaining, MPI_BYTE,
dest, tag, itsCommunicators[comm]);
remaining = 0;
}
checkError(result, "MPI_Send");
}
ASKAPCHECK(remaining == 0, "MPIComms::send() Didn't send all data");
}
void MPIComms::receive(void* buf, size_t size, int source, int tag, size_t comm)
{
receiveImpl(buf, size, source, tag, comm);
}
int MPIComms::receiveAnySrc(void* buf, size_t size, int tag, size_t comm)
{
return receiveImpl(buf, size, MPI_ANY_SOURCE, tag, comm);
}
int MPIComms::receiveImpl(void* buf, size_t size, int source, int tag, size_t comm)
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
const unsigned int c_maxint = std::numeric_limits<int>::max();
// First receive the size of the payload to be received,
// remembering the size parameter passed to this function is
// just the maximum size of the buffer, and hence the maximum
// number of bytes that can be received.
unsigned long payloadSize;
MPI_Status status;
int result = MPI_Recv(&payloadSize, 1, MPI_UNSIGNED_LONG,
source, tag, itsCommunicators[comm], &status);
checkError(result, "MPI_Recv");
// The source parameter may be MPI_ANY_SOURCE, so the actual
// source needs to be recorded for later use.
const int actualSource = status.MPI_SOURCE;
if (source != MPI_ANY_SOURCE) {
ASKAPCHECK(actualSource == source,
"Actual source of message differs from requested source");
}
// Receive the smaller of size or payloadSize
size_t remaining = (payloadSize > size) ? size : payloadSize;
while (remaining > 0) {
size_t offset = size - remaining;
void* addr = addOffset(buf, offset);
if (remaining >= c_maxint) {
result = MPI_Recv(addr, c_maxint, MPI_BYTE,
actualSource, tag, itsCommunicators[comm], MPI_STATUS_IGNORE);
remaining -= c_maxint;
} else {
result = MPI_Recv(addr, remaining, MPI_BYTE,
actualSource, tag, itsCommunicators[comm], MPI_STATUS_IGNORE);
remaining = 0;
}
checkError(result, "MPI_Recv");
}
ASKAPCHECK(remaining == 0, "MPIComms::receive() Didn't receive all data");
return actualSource;
}
void MPIComms::broadcast(void* buf, size_t size, int root, size_t comm)
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
const unsigned int c_maxint = std::numeric_limits<int>::max();
// Broadcast in chunks of size MAXINT until complete
size_t remaining = size;
int result;
while (remaining > 0) {
size_t offset = size - remaining;
void* addr = addOffset(buf, offset);
if (remaining >= c_maxint) {
result = MPI_Bcast(addr, c_maxint, MPI_BYTE, root, itsCommunicators[comm]);
remaining -= c_maxint;
} else {
result = MPI_Bcast(addr, remaining, MPI_BYTE, root, itsCommunicators[comm]);
remaining = 0;
}
checkError(result, "MPI_Bcast");
}
}
/// @brief sum raw float buffers across all ranks of the communicator via MPI_Allreduce
/// @details This method does an in place operation, so all buffers will have the
/// same content equal to the sum of initial values (element-wise) sent to individual ranks
/// @param[in,out] buf data buffer (float type is assumed)
/// @param[in] size number of elements in the buffer (float type is assumed)
/// @param[in] comm communicator index
void MPIComms::sumAndBroadcast(float *buf, size_t size, size_t comm)
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
const int result = MPI_Allreduce(MPI_IN_PLACE,(void*)buf,
int(size), MPI_FLOAT, MPI_SUM, itsCommunicators[comm]);
checkError(result,"MPI_Allreduce");
}
/// @brief reduce a boolean flag across the number of ranks
/// @details This method aggregates a flag (i.e. single boolean variable) across
/// a number of ranks with the logical or operation. All ranks will have the same
/// value of the flag at the end. The main use case is checking before a collective
/// call that at least one rank has some data.
/// @param[in,out] flag flag to reduce
/// @param[in] comm communicator index
void MPIComms::aggregateFlag(bool &flag, size_t comm)
{
ASKAPDEBUGASSERT(comm < itsCommunicators.size());
ASKAPDEBUGASSERT(itsCommunicators[comm] != MPI_COMM_NULL);
int buf = int(flag);
const int result = MPI_Allreduce(MPI_IN_PLACE,(void*)&buf,
1, MPI_INT, MPI_LOR, itsCommunicators[comm]);
checkError(result,"MPI_Allreduce");
flag = bool(buf);
}
void MPIComms::checkError(const int error, const std::string location) const
{
if (error == MPI_SUCCESS) {
return;
}
char estring[MPI_MAX_ERROR_STRING];
int eclass;
int len;
MPI_Error_class(error, &eclass);
MPI_Error_string(error, estring, &len);
ASKAPTHROW(std::runtime_error, "" << location << " failed. Error "
<< eclass << ": " << estring);
}
#else
MPIComms::MPIComms(int argc, char *argv[])
{
}
MPIComms::~MPIComms()
{
}
std::string MPIComms::nodeName(void) const
{
const int MAX_HOSTNAME_LEN = 1024;
char name[MAX_HOSTNAME_LEN];
name[MAX_HOSTNAME_LEN - 1] = '\0';
const int error = gethostname(name, MAX_HOSTNAME_LEN - 1);
if (error) {
ASKAPTHROW(AskapError, "MPIComms::nodeName() returned error: " << error);
}
std::string pname(name);
std::string::size_type idx = pname.find_first_of('.');
if (idx != std::string::npos) {
// Extract just the hostname part
pname = pname.substr(0, idx);
}
return pname;
}
int MPIComms::rank(size_t) const
{
return 0;
}
int MPIComms::nProcs(size_t) const
{
return 1;
}
void MPIComms::abort(size_t)
{
exit(1);
}
/// @brief sum raw float buffers across all ranks of the communicator via MPI_Allreduce
/// @details This method does an in place operation, so all buffers will have the
/// same content equal to the sum of initial values (element-wise) sent to individual ranks
/// @param[in,out] buf data buffer (float type is assumed)
/// @param[in] size number of elements in the buffer (float type is assumed)
/// @param[in] comm communicator index
void MPIComms::sumAndBroadcast(float *, size_t, size_t)
{
ASKAPTHROW(AskapError, "MPIComms::sumAndBroadcast() cannot be used - configured without MPI");
}
/// @brief reduce a boolean flag across the number of ranks
/// @details This method aggregates a flag (i.e. single boolean variable) across
/// a number of ranks with the logical or operation. All ranks will have the same
/// value of the flag at the end. The main use case is checking before a collective
/// call that at least one rank has some data.
/// @param[in,out] flag flag to reduce
/// @param[in] comm communicator index
void MPIComms::aggregateFlag(bool &, size_t)
{
ASKAPTHROW(AskapError, "MPIComms::aggregateFlag() cannot be used - configured without MPI");
}
/// @brief create a new communicator
/// @details This method creates a new communicator and returns the index.
/// This index can later be used as a parameter for communication methods
/// instead of the default one.
/// @param[in] group ranks to include in the new communicator
/// @param[in] comm communicator index where a new subgroup is created,
/// defaults to 0 (copy of the default world communicator)
/// @return new communicator index
size_t MPIComms::createComm(const std::vector<int> &, size_t)
{
ASKAPTHROW(AskapError, "MPIComms::createComm() cannot be used - configured without MPI");
}
void MPIComms::send(const void* buf, size_t size, int dest, int tag, size_t)
{
ASKAPTHROW(AskapError, "MPIComms::send() cannot be used - configured without MPI");
}
void MPIComms::receive(void* buf, size_t size, int source, int tag, size_t)
{
ASKAPTHROW(AskapError, "MPIComms::receive() cannot be used - configured without MPI");
}
int MPIComms::receiveAnySrc(void* buf, size_t size, int tag, size_t)
{
ASKAPTHROW(AskapError, "MPIComms::receiveAnySrc() cannot be used - configured without MPI");
}
void MPIComms::broadcast(void* buf, size_t size, int root, size_t)
{
ASKAPTHROW(AskapError, "MPIComms::broadcast() cannot be used - configured without MPI");
}
void MPIComms::checkError(const int error, const std::string location) const
{
ASKAPTHROW(AskapError, "MPIComms::checkError() cannot be used - configured without MPI");
}
void MPIComms::barrier(size_t comm)
{
ASKAPTHROW(AskapError, "MPIComms::barrier() cannot be used - configured without MPI");
}
#endif
//////////////////////////////////////////////////////////////////////////
// Shared methods (i.e. by both MPI and non-mpi implementations go below
//////////////////////////////////////////////////////////////////////////
void* MPIComms::addOffset(const void *ptr, size_t offset) const
{
char *cptr = static_cast<char*>(const_cast<void*>(ptr));
cptr += offset;
return cptr;
}
|
Formal statement is: lemma local_lipschitzE: assumes local_lipschitz: "local_lipschitz T X f" assumes "t \<in> T" "x \<in> X" obtains u L where "u > 0" "\<And>s. s \<in> cball t u \<inter> T \<Longrightarrow> L-lipschitz_on (cball x u \<inter> X) (f s)" Informal statement is: Suppose $f$ is a local Lipschitz function from a topological space $X$ to a metric space $Y$. Then for every $x \in X$ and $t \in T$, there exists a neighborhood $U$ of $x$ and a neighborhood $V$ of $t$ such that $f$ is Lipschitz on $U \times V$.
|
# const SURFACE_BUFFER_FACTOR = 0/4 # abandoned for now
# """
# Cavity(boundary,lattice,[dielectric,pump];align=false,[name]) -> domain
# Cavity(lattice,boundary,[dielectric,pump];align=false,[name]) -> domain
# """
# Cavity(args...;kwargs...) = Domain(:Cavity,args...;kwargs...)
# """
# Resonator(boundary,lattice,[dielectric,pump];align=false,[name]) -> domain
# Resonator(lattice,boundary,[dielectric,pump];align=false,[name]) -> domain
# """
# Resonator(args...;kwargs...) = Domain(:Resonator,args...;kwargs...)
# """
# Void(boundary,lattice;align=false,[name]) -> domain
# Void(lattice,boundary;align=false,[name]) -> domain
# """
# Void(args...; align=false, kwargs...) = Domain(:Void,args...; align=align, kwargs...)
# """
# Dielectric(lattice,boundary,[ε=1,F=0];align=false,[name]) -> domain
# Dielectric(boundary,lattice,[ε=1,F=0];align=false,[name]) -> domain
# """
# Dielectric(args...;kwargs...) = Domain(:Dielectric,args...;kwargs...)
# Dielectric(bnd::Union{Boundary,Lattice},lat::Union{Boundary,Lattice},ε::Number,args...;kwargs...) = Domain(:Dielectric,bnd,lat,DielectricFunction(ε),args...;kwargs...)
# Dielectric(bnd::Union{Boundary,Lattice},lat::Union{Boundary,Lattice},ε,F::Number;kwargs...) = Domain(:Dielectric,bnd,lat,ε,PumpFunction(F);kwargs...)
# """
# Resonator(boundary,lattice,[dielectric,pump];align=true,[name]) -> domain
# Resonator(lattice,boundary,[dielectric,pump];align=true,[name]) -> domain
# """
# Waveguide(args...; kwargs...) = Domain(:Waveguide,args...; align=true, kwargs...)
# """
# Lead(boundary,lattice,[dielectric,pump];align=true,[name]) -> domain
# Lead(lattice,boundary,[dielectric,pump];align=true,[name]) -> domain
# """
# Lead(args...; kwargs...) = Domain(:Lead,args...; align=true, kwargs...)
# # polar spanning indices
# function generate_spanning_indices_polar(bnd::Boundary, lat::Lattice)
# @assert typeof(bnd.shape)<:Union{Circle,Annulus} "polar coordinates only for circular outermost region"
# @assert lat.x0==bnd.shape.x0 && lat.y0==bnd.shape.y0 "polar lattice origin $((lat.x0,lat.y0)) must be same as circle origin $((bnd.shape.x0,bnd.shape.y0))"
# # i,j = get_lattice_index(lat,bnd.shape.x0,bnd.shape.y0)
# # imin, imax = floor(Int,i), ceil(Int,i)
# # jmin, jmax = floor(Int,j), ceil(Int,j)
# # imin ≤ 0 ? imin = 0 : nothing
# # jmin ≤ 0 ? jmin = 0 : nothing
# imin = 0
# imax = 1
# jmin = 0
# jmax = floor(Int,2π/lat.dθ)
#
# flag_rmin = flag_rmax = flag_θmin = flag_θmax = true
# init_flag = false
# while flag_rmin || flag_rmax || flag_θmin|| flag_θmax
# I = imin:imax
# J = jmin:jmax
# XYBool = BitArray(undef,2length(I)+2length(J))
# count1 = 0
# count2 = 0
# temp = Array{Float64}(undef,2)
# for i ∈ I
# count2 += 1
# X, Y = lat(i,J[1])
# XYBool[1+count1+i-I[1]] = bnd.shape(X,Y)
# end
# (!init_flag || any(XYBool[(count1+1):count2])) && jmin≥1 ? (jmin -= 1; flag_θmin=true) : flag_θmin=false
# !init_flag ? init_flag = any(XYBool[(count1+1):count2]) : nothing
# count1 = count2
# for i ∈ I
# count2 += 1
# X,Y = lat(i,J[end])
# XYBool[1+count1+i-I[1]] = bnd.shape(X,Y)
# end
# (!init_flag || any(XYBool[(count1+1):count2])) && (jmax+1)*lat.dθ≤2π ? (jmax += 1; flag_θmax=true) : flag_θmax=false
# !init_flag ? init_flag = any(XYBool[(count1+1):count2]) : nothing
# count1 = count2
# for j ∈ J
# count2 += 1
# X,Y = lat(I[1],j)
# XYBool[1+count1+j-J[1]] = bnd.shape(X,Y)
# end
# (!init_flag || any(XYBool[(count1+1):count2])) && imin≥1 ? (imin -= 1; flag_rmin=true) : flag_rmin=false
# !init_flag ? init_flag = any(XYBool[(count1+1):count2]) : nothing
# count1 = count2
# for j ∈ J
# count2 += 1
# X,Y = lat(I[end],j)
# XYBool[2length(I) + length(J) + j+1-J[1]] = bnd.shape(X,Y)
# end
# !init_flag || any(XYBool[(count1+1):count2]) ? (imax += 1; flag_rmax=true) : flag_rmax=false
# !init_flag ? init_flag = any(XYBool[(count1+1):count2]) : nothing
# end
# return imin, imax, jmin, jmax
# end
# function generate_xy(bnd::Boundary,lat::Lattice,imin,imax,jmin,jmax)
# I, J = imin:imax, jmin:jmax
# X = Array{Float64}(undef,length(I),length(J))
# Y = Array{Float64}(undef,length(I),length(J))
# for k ∈ CartesianIndices(X)
# i,j = k[1],k[2]
# X[k],Y[k] = lat(I[i],J[j])
# end
# return X, Y
# end
# function generate_interior(bnd::Boundary,lat::Lattice,x::Array,y::Array)
# interior = BitArray(undef,size(x)...)
# for k ∈ CartesianIndices(x)
# interior[k] = bnd.shape(x[k],y[k])
# end
# return interior
# end
# function generate_translations(lat::Lattice,imin,imax,jmin,jmax)
# I, J = imin:imax, jmin:jmax
# x1 = Array{Float64}(undef,length(I),length(J))
# x2 = Array{Float64}(undef,length(I),length(J))
# x3 = Array{Float64}(undef,length(I),length(J))
# x4 = Array{Float64}(undef,length(I),length(J))
# y1 = Array{Float64}(undef,length(I),length(J))
# y2 = Array{Float64}(undef,length(I),length(J))
# y3 = Array{Float64}(undef,length(I),length(J))
# y4 = Array{Float64}(undef,length(I),length(J))
# for k ∈ CartesianIndices(x1)
# i,j = k[1],k[2]
# x1[k],y1[k] = lat(I[i]-1,J[j])
# x2[k],y2[k] = lat(I[i]+1,J[j])
# x3[k],y3[k] = lat(I[i],J[j]-1)
# x4[k],y4[k] = lat(I[i],J[j]+1)
# end
# return (x1,y1),(x2,y2),(x3,y3),(x4,y4)
# end
function generate_surface!(interior::BitArray,lat::Lattice,bnd::Boundary,t1,t2,t3,t4,x,y)
surface = falses(size(interior)...)
surface_temp = BitArray(undef,size(interior)...)
for k ∈ CartesianIndices(interior)
surface_temp[k] = interior[k] &&
(!bnd.shape(t1[1][k],t1[2][k]) ||
!bnd.shape(t2[1][k],t2[2][k]) ||
!bnd.shape(t3[1][k],t3[2][k]) ||
!bnd.shape(t4[1][k],t4[2][k])
)
if surface_temp[k]
# n,t,d = normal_distance(bnd.shape,x[k],y[k])
# if d[1]<min(lat.dx*SURFACE_BUFFER_FACTOR,lat.dy*SURFACE_BUFFER_FACTOR)
# interior[k] = false
# surface[k] = false
# surface[k+CartesianIndex( 1, 0)]=true
# surface[k+CartesianIndex(-1, 0)]=true
# surface[k+CartesianIndex( 0, 1)]=true
# surface[k+CartesianIndex( 0,-1)]=true
# else
surface[k] = true
# end
end
end
return surface
end
function generate_neighbor_indices(interior,lat::Lattice)
if lat.type==:Cartesian
return generate_neighbor_indices_cartesian(interior)
elseif lat.type==:Polar
return generate_neighbor_indices_polar(interior)
else
throw(LatticeError(lat))
end
end
function generate_neighbor_indices_cartesian(interior)
NN = LinearIndices(interior) - reshape(cumsum(.!interior[:]),size(interior)...)
nnxm = vcat(zeros(Int,1,size(interior,2)),NN[1:end-1,:])
nnxp = vcat(NN[2:end,:],zeros(Int,1,size(interior,2)))
nnym = hcat(zeros(Int,size(interior,1),1),NN[:,1:end-1])
nnyp = hcat(NN[:,2:end],zeros(Int,size(interior,1),1))
return nnxm,nnxp,nnym,nnyp
end
function generate_neighbor_indices_polar(interior)
NN = LinearIndices(interior) - reshape(cumsum(.!interior[:]),size(interior)...)
nnrm = vcat(zeros(Int,1,size(interior,2)),NN[1:end-1,:])
nnrp = vcat(NN[2:end,:],zeros(Int,1,size(interior,2)))
nnθm = hcat(NN[:,end],NN[:,1:end-1])
nnθp = hcat(NN[:,2:end],NN[:,1])
return nnrm,nnrp,nnθm,nnθp
end
function generate_corner(x,y,bnd::Boundary,lat::Lattice,surface,interior)
if lat.type==:Cartesian
return generate_corner_cartesian(x,y,bnd,lat,surface,interior)
elseif lat.type==:Polar
return generate_corner_polar(x,y,bnd,lat,surface,interior)
else
throw(LatticeError(lat))
end
end
function generate_corner_cartesian(x,y,bnd::Boundary,lat::Lattice,surface,interior)
corner = falses(size(surface)...)
c = bnd.shape.corners
dx = hypot(lat.dx,lat.dy)#*(1+SURFACE_BUFFER_FACTOR)
if length(c)>0
for k ∈ CartesianIndices(surface)
if surface[k]
d = map(z->hypot(x[k]-z[1],y[k]-z[2]),c)
corner[k] = minimum(d) ≤ dx+eps(dx)
X1, Y1 = x[k+CartesianIndex( 2, 0)], y[k+CartesianIndex( 2, 0)]
X2, Y2 = x[k+CartesianIndex(-2, 0)], y[k+CartesianIndex(-2, 0)]
X3, Y3 = x[k+CartesianIndex( 0, 2)], y[k+CartesianIndex( 0, 2)]
X4, Y4 = x[k+CartesianIndex( 0,-2)], y[k+CartesianIndex( 0,-2)]
count = sum(
(!bnd.shape(X1,Y1) && !interior[k+CartesianIndex( 1, 0)],
!bnd.shape(X2,Y2) && !interior[k+CartesianIndex(-1, 0)],
!bnd.shape(X3,Y3) && !interior[k+CartesianIndex( 0, 1)],
!bnd.shape(X4,Y4) && !interior[k+CartesianIndex( 0,-1)],)
)
corner[k] = corner[k] && (count>1)
end
end
end
return corner
end
function generate_corner_polar(x,y,bnd,lat,surface,interior)
return falses(size(surface)...)
end
|
MODULE dcbsrw_I
INTERFACE
!...Generated by Pacific-Sierra Research 77to90 4.3E 10:47:15 2/14/04
!...Modified by Charlotte Froese Fischer
! Gediminas Gaigalas 10/05/17
SUBROUTINE dcbsrw (N, KAPPA, Z, E, RG0, RG, RF, MTP)
USE vast_kind_param,ONLY: DOUBLE
USE parameter_def, ONLY: NNNP
INTEGER, INTENT(IN) :: N
INTEGER, INTENT(IN) :: KAPPA
REAL(DOUBLE), INTENT(IN) :: Z
REAL(DOUBLE), INTENT(OUT) :: E
REAL(DOUBLE), INTENT(OUT) :: RG0
REAL(DOUBLE), DIMENSION(NNNP), INTENT(INOUT) :: RG
REAL(DOUBLE), DIMENSION(NNNP), INTENT(OUT) :: RF
INTEGER, INTENT(OUT) :: MTP
!VAST.../DEF2/ C(IN)
!VAST.../DEF4/ ACCY(IN)
!VAST.../GRID/ R(IN), NTP(IN)
!VAST.../TATB/ TA(INOUT), TB(INOUT)
!VAST...Calls: CGAMMA
!...This routine performs I/O.
END SUBROUTINE
END INTERFACE
END MODULE
|
The Ultimate Copywriting Masterclass Pro Secrets To Success | Free eBooks Download - EBOOKEE!
In this course, you will learn how to write copy that connects and converts. In other words you're going to learn to craft copywriting that actually sounds like you, that comes from your heart and makes people excited to buy what you sell.
My teaching style is straight forward, clear, concise and to-the-point. I use practical real-life advice that you can apply straight away. I can't wait to get started with you on your journey to copywriting success.
No comments for "The Ultimate Copywriting Masterclass Pro Secrets To Success".
|
section "Arithmetic and Boolean Expressions"
theory AExp imports Main begin
subsection "Arithmetic Expressions"
type_synonym vname = string
type_synonym val = int
type_synonym state = "vname ⇒ val"
text_raw{*\snip{AExpaexpdef}{2}{1}{% *}
datatype aexp = N int | V vname | Plus aexp aexp
text_raw{*}%endsnip*}
text_raw{*\snip{AExpavaldef}{1}{2}{% *}
fun aval :: "aexp ⇒ state ⇒ val" where
"aval (N n) s = n" |
"aval (V x) s = s x" |
"aval (Plus a⇩1 a⇩2) s = aval a⇩1 s + aval a⇩2 s"
text_raw{*}%endsnip*}
value "aval (Plus (V ''x'') (N 5)) (λx. if x = ''x'' then 7 else 0)"
text {* The same state more concisely: *}
value "aval (Plus (V ''x'') (N 5)) ((λx. 0) (''x'':= 7))"
text {* A little syntax magic to write larger states compactly: *}
definition null_state ("<>") where
"null_state ≡ λx. 0"
syntax
"_State" :: "updbinds => 'a" ("<_>")
translations
"_State ms" == "_Update <> ms"
"_State (_updbinds b bs)" <= "_Update (_State b) bs"
text {* \noindent
We can now write a series of updates to the function @{text "λx. 0"} compactly:
*}
lemma "<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))"
by (rule refl)
value "aval (Plus (V ''x'') (N 5)) <''x'' := 7>"
text {* In the @{term[source] "<a := b>"} syntax, variables that are not mentioned are 0 by default:
*}
value "aval (Plus (V ''x'') (N 5)) <''y'' := 7>"
text{* Note that this @{text"<…>"} syntax works for any function space
@{text"τ⇩1 ⇒ τ⇩2"} where @{text "τ⇩2"} has a @{text 0}. *}
subsection "Constant Folding"
text{* Evaluate constant subsexpressions: *}
text_raw{*\snip{AExpasimpconstdef}{0}{2}{% *}
fun asimp_const :: "aexp ⇒ aexp" where
"asimp_const (N n) = N n" |
"asimp_const (V x) = V x" |
"asimp_const (Plus a⇩1 a⇩2) =
(case (asimp_const a⇩1, asimp_const a⇩2) of
(N n⇩1, N n⇩2) ⇒ N(n⇩1+n⇩2) |
(b⇩1,b⇩2) ⇒ Plus b⇩1 b⇩2)"
text_raw{*}%endsnip*}
theorem aval_asimp_const:
"aval (asimp_const a) s = aval a s"
apply(induction a)
apply (auto split: aexp.split)
done
text{* Now we also eliminate all occurrences 0 in additions. The standard
method: optimized versions of the constructors: *}
text_raw{*\snip{AExpplusdef}{0}{2}{% *}
fun plus :: "aexp ⇒ aexp ⇒ aexp" where
"plus (N i⇩1) (N i⇩2) = N(i⇩1+i⇩2)" |
"plus (N i) a = (if i=0 then a else Plus (N i) a)" |
"plus a (N i) = (if i=0 then a else Plus a (N i))" |
"plus a⇩1 a⇩2 = Plus a⇩1 a⇩2"
text_raw{*}%endsnip*}
lemma aval_plus[simp]:
"aval (plus a1 a2) s = aval a1 s + aval a2 s"
(* apply(induction a1 a2 rule: plus.induct) Original. The 'a1 a2' is extraneous. *)
apply(induction rule: plus.induct)
(* apply(induction a1) apply(induction a2) Does not work*)
apply simp_all (* just for a change from auto *)
done
text_raw{*\snip{AExpasimpdef}{2}{0}{% *}
fun asimp :: "aexp ⇒ aexp" where
"asimp (N n) = N n" |
"asimp (V x) = V x" |
"asimp (Plus a⇩1 a⇩2) = plus (asimp a⇩1) (asimp a⇩2)"
text_raw{*}%endsnip*}
text{* Note that in @{const asimp_const} the optimized constructor was
inlined. Making it a separate function @{const plus} improves modularity of
the code and the proofs. *}
value "asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))"
theorem aval_asimp[simp]:
"aval (asimp a) s = aval a s"
apply(induction a)
apply simp_all
done
(* exercise 3.1 *)
fun is_N :: "aexp ⇒ bool" where
"is_N (N _) = True"|
"is_N _ = False"
(* check that expression does not contain any unoptimized sub-expressions,
i.e. Plus (N i) (N j) *)
fun optimal :: "aexp ⇒ bool" where
(* TODO why won't this, the ∧ function, work? *)
(* "optimal (Plus e1 e2) = (is_N e1) ∧ (is_N e2)" | *)
(* definition conj :: "[bool, bool] ⇒ bool" (infixr "∧" 35) *)
"optimal (Plus e1 e2) = Not(conj (is_N e1) (is_N e2))" |
"optimal _ = True"
theorem asimp_const_is_optimal:
"optimal (asimp_const e)"
apply(induction e)
apply(auto)
apply(simp split:aexp.split)
done
(* Sum all N's found in expression. Change all values of (N x) to (N 0) in expression.
Assume that asimp will be run later to cleanup expressions like (Plus (N 0) (V v))
Because the only operator is '+' , we can blindly sum all N's.
helper for full_asimp *)
fun sum_Ns :: "aexp ⇒ int ⇒ (aexp × int)" where
"sum_Ns (N n) s = (Plus (N 0) (N 0), s+n)"|
"sum_Ns (V v) s = (V v, s)"|
"sum_Ns (Plus e⇩1 e⇩2) s =
(let (re⇩1, s⇩1) = sum_Ns e⇩1 0;
(re⇩2, s⇩2) = sum_Ns e⇩2 0
in (Plus re⇩1 re⇩2, s⇩1 + s⇩2))"
(* When all variables are 0, aval = sum_Ns *)
lemma aval_sum_Ns:"aval e <> = snd (sum_Ns e 0)"
apply(induction e)
apply(auto)
apply (simp add: null_state_def)
by (simp add: case_prod_beta)
(* constant folding for aexp where we sum up all constants, even if they are not next to
each other. For example, Plus (N 1) (Plus (V x ) (N 2)) becomes Plus (V x ) (N 3). *)
fun full_asimp :: "aexp ⇒ aexp" where
"full_asimp e⇩1 = (
let (e⇩2, s) = sum_Ns e⇩1 0;
e⇩3 = Plus (N s) e⇩2
in asimp e⇩3)"
value "full_asimp (Plus (N 1) (Plus (V x ) (N 2)))"
theorem aval_full_asimp[simp]:
"aval (full_asimp e) s = aval e s"
apply(induction e)
apply(auto)
by (simp add: case_prod_beta)
(* by (simp add: case_prod_unfold) *)
(* Define a substitution function
subst :: vname ⇒ aexp ⇒ aexp ⇒ aexp
such that
subst x a e
is the result of replacing every
occurrence of variable x by a in e *)
fun subst :: "vname ⇒ aexp ⇒ aexp ⇒ aexp" where
"subst matchMe replaceWith (V vname) =
(if matchMe = vname
then replaceWith
else V vname)"|
"subst matchMe replaceWith (N n) = N n"|
"subst matchMe replaceWith (Plus e⇩1 e⇩2) =
Plus (subst matchMe replaceWith e⇩1) (subst matchMe replaceWith e⇩2)"
value "subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'')"
(* Prove the so-called substitution lemma that says that we can either
substitute first and evaluate afterwards or evaluate with an updated state:
aval (subst x a e) s = aval e (s(x := aval a s)). As a consequence prove
aval a1 s = aval a2 s =⇒ aval (subst x a1 e) s = aval (subst x a2 e) s. *)
lemma substitution:"aval (subst x a e) s = aval e (s(x := aval a s))"
apply(induction e)
by auto
theorem foo:
"aval a⇩1 s = aval a⇩2 s
⟹ aval (subst x a⇩1 e) s = aval (subst x a⇩2 e) s"
apply(induction e)
by auto
end
|
(* Title: ZF/AC/WO6_WO1.thy
Author: Krzysztof Grabczewski
Proofs needed to state that formulations WO1,...,WO6 are all equivalent.
The only hard one is WO6 ==> WO1.
Every proof (except WO6 ==> WO1 and WO1 ==> WO2) are described as "clear"
by Rubin & Rubin (page 2).
They refer reader to a book by Gödel to see the proof WO1 ==> WO2.
Fortunately order types made this proof also very easy.
*)
theory WO6_WO1
imports Cardinal_aux
begin
(* Auxiliary definitions used in proof *)
definition
NN :: "i => i" where
"NN(y) == {m \<in> nat. \<exists>a. \<exists>f. Ord(a) & domain(f)=a &
(\<Union>b<a. f`b) = y & (\<forall>b<a. f`b \<lesssim> m)}"
definition
uu :: "[i, i, i, i] => i" where
"uu(f, beta, gamma, delta) == (f`beta * f`gamma) \<inter> f`delta"
(** Definitions for case 1 **)
definition
vv1 :: "[i, i, i] => i" where
"vv1(f,m,b) ==
let g = \<mu> g. (\<exists>d. Ord(d) & (domain(uu(f,b,g,d)) \<noteq> 0 &
domain(uu(f,b,g,d)) \<lesssim> m));
d = \<mu> d. domain(uu(f,b,g,d)) \<noteq> 0 &
domain(uu(f,b,g,d)) \<lesssim> m
in if f`b \<noteq> 0 then domain(uu(f,b,g,d)) else 0"
definition
ww1 :: "[i, i, i] => i" where
"ww1(f,m,b) == f`b - vv1(f,m,b)"
definition
gg1 :: "[i, i, i] => i" where
"gg1(f,a,m) == \<lambda>b \<in> a++a. if b<a then vv1(f,m,b) else ww1(f,m,b--a)"
(** Definitions for case 2 **)
definition
vv2 :: "[i, i, i, i] => i" where
"vv2(f,b,g,s) ==
if f`g \<noteq> 0 then {uu(f, b, g, \<mu> d. uu(f,b,g,d) \<noteq> 0)`s} else 0"
definition
ww2 :: "[i, i, i, i] => i" where
"ww2(f,b,g,s) == f`g - vv2(f,b,g,s)"
definition
gg2 :: "[i, i, i, i] => i" where
"gg2(f,a,b,s) ==
\<lambda>g \<in> a++a. if g<a then vv2(f,b,g,s) else ww2(f,b,g--a,s)"
lemma WO2_WO3: "WO2 ==> WO3"
by (unfold WO2_def WO3_def, fast)
(* ********************************************************************** *)
lemma WO3_WO1: "WO3 ==> WO1"
apply (unfold eqpoll_def WO1_def WO3_def)
apply (intro allI)
apply (drule_tac x=A in spec)
apply (blast intro: bij_is_inj well_ord_rvimage
well_ord_Memrel [THEN well_ord_subset])
done
(* ********************************************************************** *)
lemma WO1_WO2: "WO1 ==> WO2"
apply (unfold eqpoll_def WO1_def WO2_def)
apply (blast intro!: Ord_ordertype ordermap_bij)
done
(* ********************************************************************** *)
lemma lam_sets: "f \<in> A->B ==> (\<lambda>x \<in> A. {f`x}): A -> {{b}. b \<in> B}"
by (fast intro!: lam_type apply_type)
lemma surj_imp_eq': "f \<in> surj(A,B) ==> (\<Union>a \<in> A. {f`a}) = B"
apply (unfold surj_def)
apply (fast elim!: apply_type)
done
lemma surj_imp_eq: "[| f \<in> surj(A,B); Ord(A) |] ==> (\<Union>a<A. {f`a}) = B"
by (fast dest!: surj_imp_eq' intro!: ltI elim!: ltE)
lemma WO1_WO4: "WO1 ==> WO4(1)"
apply (unfold WO1_def WO4_def)
apply (rule allI)
apply (erule_tac x = A in allE)
apply (erule exE)
apply (intro exI conjI)
apply (erule Ord_ordertype)
apply (erule ordermap_bij [THEN bij_converse_bij, THEN bij_is_fun, THEN lam_sets, THEN domain_of_fun])
apply (simp_all add: singleton_eqpoll_1 eqpoll_imp_lepoll Ord_ordertype
ordermap_bij [THEN bij_converse_bij, THEN bij_is_surj, THEN surj_imp_eq]
ltD)
done
(* ********************************************************************** *)
lemma WO4_mono: "[| m\<le>n; WO4(m) |] ==> WO4(n)"
apply (unfold WO4_def)
apply (blast dest!: spec intro: lepoll_trans [OF _ le_imp_lepoll])
done
(* ********************************************************************** *)
lemma WO4_WO5: "[| m \<in> nat; 1\<le>m; WO4(m) |] ==> WO5"
by (unfold WO4_def WO5_def, blast)
(* ********************************************************************** *)
lemma WO5_WO6: "WO5 ==> WO6"
by (unfold WO4_def WO5_def WO6_def, blast)
(* **********************************************************************
The proof of "WO6 ==> WO1". Simplified by L C Paulson.
From the book "Equivalents of the Axiom of Choice" by Rubin & Rubin,
pages 2-5
************************************************************************* *)
lemma lt_oadd_odiff_disj:
"[| k < i++j; Ord(i); Ord(j) |]
==> k < i | (~ k<i & k = i ++ (k--i) & (k--i)<j)"
apply (rule_tac i = k and j = i in Ord_linear2)
prefer 4
apply (drule odiff_lt_mono2, assumption)
apply (simp add: oadd_odiff_inverse odiff_oadd_inverse)
apply (auto elim!: lt_Ord)
done
(* ********************************************************************** *)
(* The most complicated part of the proof - lemma ii - p. 2-4 *)
(* ********************************************************************** *)
(* ********************************************************************** *)
(* some properties of relation uu(beta, gamma, delta) - p. 2 *)
(* ********************************************************************** *)
lemma domain_uu_subset: "domain(uu(f,b,g,d)) \<subseteq> f`b"
by (unfold uu_def, blast)
lemma quant_domain_uu_lepoll_m:
"\<forall>b<a. f`b \<lesssim> m ==> \<forall>b<a. \<forall>g<a. \<forall>d<a. domain(uu(f,b,g,d)) \<lesssim> m"
by (blast intro: domain_uu_subset [THEN subset_imp_lepoll] lepoll_trans)
lemma uu_subset1: "uu(f,b,g,d) \<subseteq> f`b * f`g"
by (unfold uu_def, blast)
lemma uu_subset2: "uu(f,b,g,d) \<subseteq> f`d"
by (unfold uu_def, blast)
lemma uu_lepoll_m: "[| \<forall>b<a. f`b \<lesssim> m; d<a |] ==> uu(f,b,g,d) \<lesssim> m"
by (blast intro: uu_subset2 [THEN subset_imp_lepoll] lepoll_trans)
(* ********************************************************************** *)
(* Two cases for lemma ii *)
(* ********************************************************************** *)
lemma cases:
"\<forall>b<a. \<forall>g<a. \<forall>d<a. u(f,b,g,d) \<lesssim> m
==> (\<forall>b<a. f`b \<noteq> 0 \<longrightarrow>
(\<exists>g<a. \<exists>d<a. u(f,b,g,d) \<noteq> 0 & u(f,b,g,d) \<prec> m))
| (\<exists>b<a. f`b \<noteq> 0 & (\<forall>g<a. \<forall>d<a. u(f,b,g,d) \<noteq> 0 \<longrightarrow>
u(f,b,g,d) \<approx> m))"
apply (unfold lesspoll_def)
apply (blast del: equalityI)
done
(* ********************************************************************** *)
(* Lemmas used in both cases *)
(* ********************************************************************** *)
lemma UN_oadd: "Ord(a) ==> (\<Union>b<a++a. C(b)) = (\<Union>b<a. C(b) \<union> C(a++b))"
by (blast intro: ltI lt_oadd1 oadd_lt_mono2 dest!: lt_oadd_disj)
(* ********************************************************************** *)
(* Case 1: lemmas *)
(* ********************************************************************** *)
lemma vv1_subset: "vv1(f,m,b) \<subseteq> f`b"
by (simp add: vv1_def Let_def domain_uu_subset)
(* ********************************************************************** *)
(* Case 1: Union of images is the whole "y" *)
(* ********************************************************************** *)
lemma UN_gg1_eq:
"[| Ord(a); m \<in> nat |] ==> (\<Union>b<a++a. gg1(f,a,m)`b) = (\<Union>b<a. f`b)"
by (simp add: gg1_def UN_oadd lt_oadd1 oadd_le_self [THEN le_imp_not_lt]
lt_Ord odiff_oadd_inverse ltD vv1_subset [THEN Diff_partition]
ww1_def)
lemma domain_gg1: "domain(gg1(f,a,m)) = a++a"
by (simp add: lam_funtype [THEN domain_of_fun] gg1_def)
(* ********************************************************************** *)
(* every value of defined function is less than or equipollent to m *)
(* ********************************************************************** *)
lemma nested_LeastI:
"[| P(a, b); Ord(a); Ord(b);
Least_a = (\<mu> a. \<exists>x. Ord(x) & P(a, x)) |]
==> P(Least_a, \<mu> b. P(Least_a, b))"
apply (erule ssubst)
apply (rule_tac Q = "%z. P (z, \<mu> b. P (z, b))" in LeastI2)
apply (fast elim!: LeastI)+
done
lemmas nested_Least_instance =
nested_LeastI [of "%g d. domain(uu(f,b,g,d)) \<noteq> 0 &
domain(uu(f,b,g,d)) \<lesssim> m"] for f b m
lemma gg1_lepoll_m:
"[| Ord(a); m \<in> nat;
\<forall>b<a. f`b \<noteq>0 \<longrightarrow>
(\<exists>g<a. \<exists>d<a. domain(uu(f,b,g,d)) \<noteq> 0 &
domain(uu(f,b,g,d)) \<lesssim> m);
\<forall>b<a. f`b \<lesssim> succ(m); b<a++a |]
==> gg1(f,a,m)`b \<lesssim> m"
apply (simp add: gg1_def empty_lepollI)
apply (safe dest!: lt_oadd_odiff_disj)
(*Case b<a \<in> show vv1(f,m,b) \<lesssim> m *)
apply (simp add: vv1_def Let_def empty_lepollI)
apply (fast intro: nested_Least_instance [THEN conjunct2]
elim!: lt_Ord)
(*Case a\<le>b \<in> show ww1(f,m,b--a) \<lesssim> m *)
apply (simp add: ww1_def empty_lepollI)
apply (case_tac "f` (b--a) = 0", simp add: empty_lepollI)
apply (rule Diff_lepoll, blast)
apply (rule vv1_subset)
apply (drule ospec [THEN mp], assumption+)
apply (elim oexE conjE)
apply (simp add: vv1_def Let_def lt_Ord nested_Least_instance [THEN conjunct1])
done
(* ********************************************************************** *)
(* Case 2: lemmas *)
(* ********************************************************************** *)
(* ********************************************************************** *)
(* Case 2: vv2_subset *)
(* ********************************************************************** *)
lemma ex_d_uu_not_empty:
"[| b<a; g<a; f`b\<noteq>0; f`g\<noteq>0;
y*y \<subseteq> y; (\<Union>b<a. f`b)=y |]
==> \<exists>d<a. uu(f,b,g,d) \<noteq> 0"
by (unfold uu_def, blast)
lemma uu_not_empty:
"[| b<a; g<a; f`b\<noteq>0; f`g\<noteq>0; y*y \<subseteq> y; (\<Union>b<a. f`b)=y |]
==> uu(f,b,g,\<mu> d. (uu(f,b,g,d) \<noteq> 0)) \<noteq> 0"
apply (drule ex_d_uu_not_empty, assumption+)
apply (fast elim!: LeastI lt_Ord)
done
lemma not_empty_rel_imp_domain: "[| r \<subseteq> A*B; r\<noteq>0 |] ==> domain(r)\<noteq>0"
by blast
lemma Least_uu_not_empty_lt_a:
"[| b<a; g<a; f`b\<noteq>0; f`g\<noteq>0; y*y \<subseteq> y; (\<Union>b<a. f`b)=y |]
==> (\<mu> d. uu(f,b,g,d) \<noteq> 0) < a"
apply (erule ex_d_uu_not_empty [THEN oexE], assumption+)
apply (blast intro: Least_le [THEN lt_trans1] lt_Ord)
done
lemma subset_Diff_sing: "[| B \<subseteq> A; a\<notin>B |] ==> B \<subseteq> A-{a}"
by blast
(*Could this be proved more directly?*)
lemma supset_lepoll_imp_eq:
"[| A \<lesssim> m; m \<lesssim> B; B \<subseteq> A; m \<in> nat |] ==> A=B"
apply (erule natE)
apply (fast dest!: lepoll_0_is_0 intro!: equalityI)
apply (safe intro!: equalityI)
apply (rule ccontr)
apply (rule succ_lepoll_natE)
apply (erule lepoll_trans)
apply (rule lepoll_trans)
apply (erule subset_Diff_sing [THEN subset_imp_lepoll], assumption)
apply (rule Diff_sing_lepoll, assumption+)
done
lemma uu_Least_is_fun:
"[| \<forall>g<a. \<forall>d<a. domain(uu(f, b, g, d))\<noteq>0 \<longrightarrow>
domain(uu(f, b, g, d)) \<approx> succ(m);
\<forall>b<a. f`b \<lesssim> succ(m); y*y \<subseteq> y;
(\<Union>b<a. f`b)=y; b<a; g<a; d<a;
f`b\<noteq>0; f`g\<noteq>0; m \<in> nat; s \<in> f`b |]
==> uu(f, b, g, \<mu> d. uu(f,b,g,d)\<noteq>0) \<in> f`b -> f`g"
apply (drule_tac x2=g in ospec [THEN ospec, THEN mp])
apply (rule_tac [3] not_empty_rel_imp_domain [OF uu_subset1 uu_not_empty])
apply (rule_tac [2] Least_uu_not_empty_lt_a, assumption+)
apply (rule rel_is_fun)
apply (erule eqpoll_sym [THEN eqpoll_imp_lepoll])
apply (erule uu_lepoll_m)
apply (rule Least_uu_not_empty_lt_a, assumption+)
apply (rule uu_subset1)
apply (rule supset_lepoll_imp_eq [OF _ eqpoll_sym [THEN eqpoll_imp_lepoll]])
apply (fast intro!: domain_uu_subset)+
done
lemma vv2_subset:
"[| \<forall>g<a. \<forall>d<a. domain(uu(f, b, g, d))\<noteq>0 \<longrightarrow>
domain(uu(f, b, g, d)) \<approx> succ(m);
\<forall>b<a. f`b \<lesssim> succ(m); y*y \<subseteq> y;
(\<Union>b<a. f`b)=y; b<a; g<a; m \<in> nat; s \<in> f`b |]
==> vv2(f,b,g,s) \<subseteq> f`g"
apply (simp add: vv2_def)
apply (blast intro: uu_Least_is_fun [THEN apply_type])
done
(* ********************************************************************** *)
(* Case 2: Union of images is the whole "y" *)
(* ********************************************************************** *)
lemma UN_gg2_eq:
"[| \<forall>g<a. \<forall>d<a. domain(uu(f,b,g,d)) \<noteq> 0 \<longrightarrow>
domain(uu(f,b,g,d)) \<approx> succ(m);
\<forall>b<a. f`b \<lesssim> succ(m); y*y \<subseteq> y;
(\<Union>b<a. f`b)=y; Ord(a); m \<in> nat; s \<in> f`b; b<a |]
==> (\<Union>g<a++a. gg2(f,a,b,s) ` g) = y"
apply (unfold gg2_def)
apply (drule sym)
apply (simp add: ltD UN_oadd oadd_le_self [THEN le_imp_not_lt]
lt_Ord odiff_oadd_inverse ww2_def
vv2_subset [THEN Diff_partition])
done
lemma domain_gg2: "domain(gg2(f,a,b,s)) = a++a"
by (simp add: lam_funtype [THEN domain_of_fun] gg2_def)
(* ********************************************************************** *)
(* every value of defined function is less than or equipollent to m *)
(* ********************************************************************** *)
lemma vv2_lepoll: "[| m \<in> nat; m\<noteq>0 |] ==> vv2(f,b,g,s) \<lesssim> m"
apply (unfold vv2_def)
apply (simp add: empty_lepollI)
apply (fast dest!: le_imp_subset [THEN subset_imp_lepoll, THEN lepoll_0_is_0]
intro!: singleton_eqpoll_1 [THEN eqpoll_imp_lepoll, THEN lepoll_trans]
not_lt_imp_le [THEN le_imp_subset, THEN subset_imp_lepoll]
nat_into_Ord nat_1I)
done
lemma ww2_lepoll:
"[| \<forall>b<a. f`b \<lesssim> succ(m); g<a; m \<in> nat; vv2(f,b,g,d) \<subseteq> f`g |]
==> ww2(f,b,g,d) \<lesssim> m"
apply (unfold ww2_def)
apply (case_tac "f`g = 0")
apply (simp add: empty_lepollI)
apply (drule ospec, assumption)
apply (rule Diff_lepoll, assumption+)
apply (simp add: vv2_def not_emptyI)
done
lemma gg2_lepoll_m:
"[| \<forall>g<a. \<forall>d<a. domain(uu(f,b,g,d)) \<noteq> 0 \<longrightarrow>
domain(uu(f,b,g,d)) \<approx> succ(m);
\<forall>b<a. f`b \<lesssim> succ(m); y*y \<subseteq> y;
(\<Union>b<a. f`b)=y; b<a; s \<in> f`b; m \<in> nat; m\<noteq> 0; g<a++a |]
==> gg2(f,a,b,s) ` g \<lesssim> m"
apply (simp add: gg2_def empty_lepollI)
apply (safe elim!: lt_Ord2 dest!: lt_oadd_odiff_disj)
apply (simp add: vv2_lepoll)
apply (simp add: ww2_lepoll vv2_subset)
done
(* ********************************************************************** *)
(* lemma ii *)
(* ********************************************************************** *)
lemma lemma_ii: "[| succ(m) \<in> NN(y); y*y \<subseteq> y; m \<in> nat; m\<noteq>0 |] ==> m \<in> NN(y)"
apply (unfold NN_def)
apply (elim CollectE exE conjE)
apply (rule quant_domain_uu_lepoll_m [THEN cases, THEN disjE], assumption)
(* case 1 *)
apply (simp add: lesspoll_succ_iff)
apply (rule_tac x = "a++a" in exI)
apply (fast intro!: Ord_oadd domain_gg1 UN_gg1_eq gg1_lepoll_m)
(* case 2 *)
apply (elim oexE conjE)
apply (rule_tac A = "f`B" for B in not_emptyE, assumption)
apply (rule CollectI)
apply (erule succ_natD)
apply (rule_tac x = "a++a" in exI)
apply (rule_tac x = "gg2 (f,a,b,x) " in exI)
apply (simp add: Ord_oadd domain_gg2 UN_gg2_eq gg2_lepoll_m)
done
(* ********************************************************************** *)
(* lemma iv - p. 4: *)
(* For every set x there is a set y such that x \<union> (y * y) \<subseteq> y *)
(* ********************************************************************** *)
(* The leading \<forall>-quantifier looks odd but makes the proofs shorter
(used only in the following two lemmas) *)
lemma z_n_subset_z_succ_n:
"\<forall>n \<in> nat. rec(n, x, %k r. r \<union> r*r) \<subseteq> rec(succ(n), x, %k r. r \<union> r*r)"
by (fast intro: rec_succ [THEN ssubst])
lemma le_subsets:
"[| \<forall>n \<in> nat. f(n)<=f(succ(n)); n\<le>m; n \<in> nat; m \<in> nat |]
==> f(n)<=f(m)"
apply (erule_tac P = "n\<le>m" in rev_mp)
apply (rule_tac P = "%z. n\<le>z \<longrightarrow> f (n) \<subseteq> f (z) " in nat_induct)
apply (auto simp add: le_iff)
done
lemma le_imp_rec_subset:
"[| n\<le>m; m \<in> nat |]
==> rec(n, x, %k r. r \<union> r*r) \<subseteq> rec(m, x, %k r. r \<union> r*r)"
apply (rule z_n_subset_z_succ_n [THEN le_subsets])
apply (blast intro: lt_nat_in_nat)+
done
lemma lemma_iv: "\<exists>y. x \<union> y*y \<subseteq> y"
apply (rule_tac x = "\<Union>n \<in> nat. rec (n, x, %k r. r \<union> r*r) " in exI)
apply safe
apply (rule nat_0I [THEN UN_I], simp)
apply (rule_tac a = "succ (n \<union> na) " in UN_I)
apply (erule Un_nat_type [THEN nat_succI], assumption)
apply (auto intro: le_imp_rec_subset [THEN subsetD]
intro!: Un_upper1_le Un_upper2_le Un_nat_type
elim!: nat_into_Ord)
done
(* ********************************************************************** *)
(* Rubin & Rubin wrote, *)
(* "It follows from (ii) and mathematical induction that if y*y \<subseteq> y then *)
(* y can be well-ordered" *)
(* In fact we have to prove *)
(* * WO6 ==> NN(y) \<noteq> 0 *)
(* * reverse induction which lets us infer that 1 \<in> NN(y) *)
(* * 1 \<in> NN(y) ==> y can be well-ordered *)
(* ********************************************************************** *)
(* ********************************************************************** *)
(* WO6 ==> NN(y) \<noteq> 0 *)
(* ********************************************************************** *)
lemma WO6_imp_NN_not_empty: "WO6 ==> NN(y) \<noteq> 0"
by (unfold WO6_def NN_def, clarify, blast)
(* ********************************************************************** *)
(* 1 \<in> NN(y) ==> y can be well-ordered *)
(* ********************************************************************** *)
lemma lemma1:
"[| (\<Union>b<a. f`b)=y; x \<in> y; \<forall>b<a. f`b \<lesssim> 1; Ord(a) |] ==> \<exists>c<a. f`c = {x}"
by (fast elim!: lepoll_1_is_sing)
lemma lemma2:
"[| (\<Union>b<a. f`b)=y; x \<in> y; \<forall>b<a. f`b \<lesssim> 1; Ord(a) |]
==> f` (\<mu> i. f`i = {x}) = {x}"
apply (drule lemma1, assumption+)
apply (fast elim!: lt_Ord intro: LeastI)
done
lemma NN_imp_ex_inj: "1 \<in> NN(y) ==> \<exists>a f. Ord(a) & f \<in> inj(y, a)"
apply (unfold NN_def)
apply (elim CollectE exE conjE)
apply (rule_tac x = a in exI)
apply (rule_tac x = "\<lambda>x \<in> y. \<mu> i. f`i = {x}" in exI)
apply (rule conjI, assumption)
apply (rule_tac d = "%i. THE x. x \<in> f`i" in lam_injective)
apply (drule lemma1, assumption+)
apply (fast elim!: Least_le [THEN lt_trans1, THEN ltD] lt_Ord)
apply (rule lemma2 [THEN ssubst], assumption+, blast)
done
lemma y_well_ord: "[| y*y \<subseteq> y; 1 \<in> NN(y) |] ==> \<exists>r. well_ord(y, r)"
apply (drule NN_imp_ex_inj)
apply (fast elim!: well_ord_rvimage [OF _ well_ord_Memrel])
done
(* ********************************************************************** *)
(* reverse induction which lets us infer that 1 \<in> NN(y) *)
(* ********************************************************************** *)
lemma rev_induct_lemma [rule_format]:
"[| n \<in> nat; !!m. [| m \<in> nat; m\<noteq>0; P(succ(m)) |] ==> P(m) |]
==> n\<noteq>0 \<longrightarrow> P(n) \<longrightarrow> P(1)"
by (erule nat_induct, blast+)
lemma rev_induct:
"[| n \<in> nat; P(n); n\<noteq>0;
!!m. [| m \<in> nat; m\<noteq>0; P(succ(m)) |] ==> P(m) |]
==> P(1)"
by (rule rev_induct_lemma, blast+)
lemma NN_into_nat: "n \<in> NN(y) ==> n \<in> nat"
by (simp add: NN_def)
lemma lemma3: "[| n \<in> NN(y); y*y \<subseteq> y; n\<noteq>0 |] ==> 1 \<in> NN(y)"
apply (rule rev_induct [OF NN_into_nat], assumption+)
apply (rule lemma_ii, assumption+)
done
(* ********************************************************************** *)
(* Main theorem "WO6 ==> WO1" *)
(* ********************************************************************** *)
(* another helpful lemma *)
lemma NN_y_0: "0 \<in> NN(y) ==> y=0"
apply (unfold NN_def)
apply (fast intro!: equalityI dest!: lepoll_0_is_0 elim: subst)
done
lemma WO6_imp_WO1: "WO6 ==> WO1"
apply (unfold WO1_def)
apply (rule allI)
apply (case_tac "A=0")
apply (fast intro!: well_ord_Memrel nat_0I [THEN nat_into_Ord])
apply (rule_tac x = A in lemma_iv [elim_format])
apply (erule exE)
apply (drule WO6_imp_NN_not_empty)
apply (erule Un_subset_iff [THEN iffD1, THEN conjE])
apply (erule_tac A = "NN (y) " in not_emptyE)
apply (frule y_well_ord)
apply (fast intro!: lemma3 dest!: NN_y_0 elim!: not_emptyE)
apply (fast elim: well_ord_subset)
done
end
|
#include <stdio.h>
#include <gsl/gsl_permutation.h>
int
main (void)
{
gsl_permutation * p = gsl_permutation_alloc (3);
gsl_permutation_init (p);
do
{
gsl_permutation_fprintf (stdout, p, " %u");
printf ("\n");
}
while (gsl_permutation_next(p) == GSL_SUCCESS);
gsl_permutation_free (p);
return 0;
}
|
using Quadrant_Data
# Volatile
center = [310, 265]
filename = "C:\\Users\\diant\\OneDrive\\Documents\\Summer_Project_2021\\Quadrant_Data\\Volatile\\0714mouse04trajectories.mat"
quadrantdf = openmatdata(filename, center)
quadcarlo = createquadcarlo(quadrantdf)
quad1total, quad1teststat, quad1pvalue = totaltime(quadcarlo,"quad 1"), testdata(quadcarlo, "quad 1"), calculatepvalue(quadrantdf, "quad 1")
quad2total, quad2teststat, quad2pvalue = totaltime(quadcarlo,"quad 2"), testdata(quadcarlo, "quad 2"), calculatepvalue(quadrantdf, "quad 2")
quad3total, quad3teststat, quad3pvalue = totaltime(quadcarlo,"quad 3"), testdata(quadcarlo, "quad 3"), calculatepvalue(quadrantdf, "quad 3")
quad4total, quad4teststat, quad4pvalue = totaltime(quadcarlo,"quad 4"), testdata(quadcarlo, "quad 4"), calculatepvalue(quadrantdf, "quad 4")
println("Test Results")
println("Quadrant 1: Total Time = $quad1total time steps. Test Stat = $quad1teststat p = $quad1pvalue")
println("Quadrant 2: Total Time = $quad2total time steps. Test Stat = $quad2teststat p = $quad2pvalue")
println("Quadrant 3: Total Time = $quad3total time steps. Test Stat = $quad3teststat p = $quad3pvalue")
println("Quadrant 4: Total Time = $quad4total time steps. Test Stat = $quad4teststat p = $quad4pvalue")
if(quad1pvalue < 0.05)
if(quad1teststat > 0)
println("The mouse shows a statistically significant bias towards quadrant 1")
else
println("The mouse shows a statistically significant bias away from quadrant 1")
end
end
if(quad2pvalue < 0.05)
if(quad2teststat > 0)
println("The mouse shows a statistically significant bias towards quadrant 2")
else
println("The mouse shows a statistically significant bias away from quadrant 2")
end
end
if(quad3pvalue < 0.05)
if(quad3teststat > 0)
println("The mouse shows a statistically significant bias towards quadrant 3")
else
println("The mouse shows a statistically significant bias away from quadrant 3")
end
end
if(quad4pvalue < 0.05)
if(quad4teststat > 0)
println("The mouse shows a statistically significant bias towards quadrant 4")
else
println("The mouse shows a statistically significant bias away from quadrant 4")
end
end
if(quad1pvalue > 0.05 && quad2pvalue > 0.05 && quad3pvalue > 0.05 && quad4pvalue > 0.05)
println("The mouse shows no statistically significant bias towards any quadrant")
end
|
% set default value for a field if not set yet.
function para = SetDefaultValue(para, fieldName, defaultValue)
if ~isfield(para, fieldName)
para.(fieldName) = defaultValue;
end
end
|
\newcommand{\fetchUML}[4] {
\begin{figure}[h!]
\centering
\hspace*{-#4cm}
\includegraphics[width=#3\textwidth]{img/UML/#1.jpg}
\caption{#2}
\label{fig:#1}
\end{figure}
}
\section{Requirement level UML diagrams}
\label{sec:graph}
\subsection{Class diagram}
\fetchUML
{RequirementLevelClassDiagram}
{Shows the main machine-world interaction entities}
{1} % scale
{0} % move left
\clearpage
\subsection{State diagrams}
\fetchUML
{UserStateDiagram}
{Shows the system state while logged in a user account; \texttt{AutomatedSOS} may be enabled}
{0.6} % scale
{0} % move left
\fetchUML
{ThirdPartyStateDiagram}
{Shows the system state while logged in a third party account; new data may be produced by the system and forwarded to the third party}
{0.6} % scale
{0} % move left
\clearpage
\subsection{Use case diagrams}
\fetchUML
{SignIn}
{Registration use case}
{.7} % scale
{0} % move left
\fetchUML
{NormalBehaviour}
{Use cases after registration}
{1} % scale
{0} % move left
\clearpage
\subsection{Sequence diagrams}
\fetchUML
{Seq_UserRegistration}
{User registration}
{.5} % scale
{0} % move left
\fetchUML
{Seq_Ambulance}
{Shows the SOS calling procedure}
{.7} % scale
{0} % move left
\fetchUML
{Seq_ThirdPartyRequest}
{Shows the third party request procedure}
{.7} % scale
{0} % move left
|
! =====================================================
subroutine rpt2(ixy,imp,maxm,meqn,mwaves,maux,mbc,mx,ql,qr,aux1,aux2,aux3,asdq,bmasdq,bpasdq)
! =====================================================
! # Riemann solver in the transverse direction.
! # This is a dummy routine that returns zeros and is only intended
! # to illustrate the format of this routine. See various example
! # directories for better examples.
! # This dummy routine can be used if transverse solves are not being
! # used, i.e. if method(3)=0.
! # Split asdq (= A^* \Delta q, where * = + or -)
! # into down-going flux difference bmasdq (= B^- A^* \Delta q)
! # and up-going flux difference bpasdq (= B^+ A^* \Delta q)
implicit double precision (a-h,o-z)
dimension ql(meqn,1-mbc:maxm+mbc)
dimension qr(meqn,1-mbc:maxm+mbc)
dimension asdq(meqn,1-mbc:maxm+mbc)
dimension bmasdq(meqn,1-mbc:maxm+mbc)
dimension bpasdq(meqn,1-mbc:maxm+mbc)
dimension aux1(maux,1-mbc:maxm+mbc)
dimension aux2(maux,1-mbc:maxm+mbc)
dimension aux3(maux,1-mbc:maxm+mbc)
dimension s (2,1-mbc:maxm+mbc)
do 10 i = 2-mbc, mx+mbc
if (imp == 1) then !left going fluctuation
ix = i-1
else !right going fluctuation
ix = i
endif
! material properties
pjm=aux1(1,ix) !density at (ix, j-1) where ix=i or i-1
pj=aux2(1,ix)
pjp=aux3(1,ix)
Ejm=aux1(2,ix)
Ej=aux2(2,ix)
Ejp=aux3(2,ix)
! linearity of the material
linearity_matjm=aux1(3,ix)
linearity_matj=aux2(3,ix)
linearity_matjp=aux3(3,ix)
! eps (strain) at different rows
epsjm=aux1(4,ix)
epsj=aux2(4,ix)
epsjp=aux3(4,ix)
! sigmap
sigmapjm=sigmap(epsjm,Ejm,linearity_matjm)
sigmapj=sigmap(epsj,Ej,linearity_matj)
sigmapjp=sigmap(epsjp,Ejp,linearity_matjp)
! computation of components of eigenvectors
r11=1/dsqrt(sigmapjm*pjm)
r13=-1/dsqrt(sigmapjp*pjp)
! shock speeds (eigenvalues of A and B)
s(1,i)=-dsqrt(sigmapjm/pjm) !lambda_1, lambda_2=0
s(2,i)=dsqrt(sigmapjp/pjp) !lambda_3
if(ixy == 1) then !x direction, use eigenvectors of matrix B
! or the decomposition of the fluctuations
! computation of coefficients of the decomposition of the fluctuations.
! I called them gamma since beta is used in the decomposition
! of the flux difference (notation used in paper for the f-wave)
gamma1=(asdq(1,i)-r13*asdq(3,i))/(r11-r13)
gamma3=(-asdq(1,i)+r11*asdq(3,i))/(r11-r13)
! computation of the fluctuations
! own going part of the normal fluctuation
bmasdq(1,i)=s(1,i)*gamma1*r11
bmasdq(2,i)=s(1,i)*gamma1*0
bmasdq(3,i)=s(1,i)*gamma1*1
! p going part of the normal fluctuation
bpasdq(1,i)=s(2,i)*gamma3*r13
bpasdq(2,i)=s(2,i)*gamma3*0
bpasdq(3,i)=s(2,i)*gamma3*1
else !y direction, use eigenvectors of matrix A
! or the decomposition of the fluctuations
gamma1=(asdq(1,i)-r13*asdq(2,i))/(r11-r13)
gamma3=(-asdq(1,i)+r11*asdq(2,i))/(r11-r13)
! computation of fluctuations
! down" going part
bmasdq(1,i)=s(1,i)*gamma1*r11
bmasdq(2,i)=s(1,i)*gamma1*1
bmasdq(3,i)=s(1,i)*gamma1*0
! up" going part
bpasdq(1,i)=s(2,i)*gamma3*r13
bpasdq(2,i)=s(2,i)*gamma3*1
bpasdq(3,i)=s(2,i)*gamma3*0
endif
10 END DO
return
end subroutine rpt2
|
Require Import Notations.
Require Import Coq.ZArith.ZArith.
Require Import Coq.Lists.List.
Require Import Coq.Logic.FinFun.
Require Import Coq.Program.Basics.
Require Import Cand.
Require Import Keys.
Import ListNotations.
Open Scope Z.
Notation "'existsT' x .. y , p" :=
(sigT (fun x => .. (sigT (fun y => p)) ..))
(at level 200, x binder, right associativity,
format "'[' 'existsT' '/ ' x .. y , '/ ' p ']'") : type_scope.
(* https://stackoverflow.com/questions/8869678/polymorphic-type-inside-a-module-ocaml *)
(* The reason for moving these abstract types is precisly the reason explaned in above link *)
Module Type Abstype.
(* Ciphertext is abstract type *)
Parameter ciphertext : Type.
(* Pedersan's commitment for a given permutation *)
Parameter Commitment : Type.
(* Permutation Zero Knowledge Proof. *)
Parameter PermZkp : Type.
(* Randomeness added during the commitment computation *)
Parameter S : Type.
(* Randomeness needed for shuffling the row/column *)
Parameter R : Type.
(* Zero knowledge proof of Shuffle *)
Parameter ShuffleZkp : Type.
(* Honest Decryption Zero knowledge Proof *)
Parameter DecZkp : Type.
End Abstype.
(* This module type is interface for all the data, and functions. The axioms about
these functions are assumed in CAxioms module *)
Module Type Crypto (Import C : Cand) (Import K : Keys) (Import Abst : Abstype).
(* Plain text is integer. *)
Definition plaintext := Z.
(* ballot is plain text value *)
Definition pballot := cand -> cand -> plaintext.
(* eballot is encrypted value *)
Definition eballot := cand -> cand -> ciphertext.
Definition Group := (Prime * Generator * Pubkey)%type.
(* Construct a instance of group *)
Let grp := (prime, gen, publickey).
(* This function encrypts the message. It will be instantiated
by Crypto library function. In our case, Unicrypt library functions *)
Parameter encrypt_message :
Group -> plaintext -> ciphertext.
(* This function decrypts the message *)
Parameter decrypt_message :
Group -> Prikey -> ciphertext -> plaintext.
(* This function returns zero knowledge proof of encrypted message (c1, c2) *)
Parameter construct_zero_knowledge_decryption_proof :
Group -> Prikey -> ciphertext -> DecZkp.
(* This function verifies the zero knowledge proof of plaintext, m, is honest decryption
of ciphertext *)
Parameter verify_zero_knowledge_decryption_proof :
Group -> plaintext -> ciphertext -> DecZkp -> bool.
(* permutation is Bijective function *)
Definition Permutation := existsT (pi : cand -> cand), (Bijective pi).
(* The idea is for each ballot u, we are going to count
we generate pi, cpi, and zkpcpi. We call row permute function
u and pi and it returns v. Then We call column permutation
on v and pi and it returns w. We decryp w as b with zero knowledge
proof. *)
(* We call a java function which returns permutation. Basically java function returns
array which is converted back to function in OCaml land *)
Parameter generatePermutation :
Group -> (* group *)
nat -> (* length *)
list cand -> (* cand_all *)
Permutation.
(* Generate randomness used in permutation commitment.
Tuple s = pcs.getRandomizeSpace().getrandomElement() *)
Parameter generateS : Group -> nat -> S.
(* Pass the permutation and randomness, it returns commitment. The S used here
will be used in zero knowledge proof *)
Parameter generatePermutationCommitment :
Group -> (* group *)
nat -> (* length *)
list cand -> (* cand_all *)
Permutation -> (* pi *)
S -> (*randomness *)
Commitment. (* cpi *)
(* This function takes Permutation Commitment and S and returns ZKP *)
Parameter zkpPermutationCommitment :
Group -> (* group *)
nat -> (* length *)
list cand -> (* cand_all *)
Permutation -> (* pi *)
Commitment -> (* cpi *)
S -> (* randomness *)
PermZkp.
Parameter verify_permutation_commitment :
Group -> (* group *)
nat -> (* length *)
Commitment -> (* cpi *)
PermZkp -> (* zero knowledge proof *)
bool. (* pcps.verify offlineProof offlinePublicInpu *)
Parameter homomorphic_addition :
Group -> ciphertext -> ciphertext -> ciphertext.
(* Start of Shuffle code *)
(* Generate Randomness R by passing group and length of candidate list*)
Parameter generateR : Group -> nat -> R.
(* We need List.length cand_all because mixer object is created using
elGamal, publickey and n *)
Parameter shuffle :
Group -> (* group *)
nat -> (* Length of list cand *)
list cand -> (* cand_all because we need to convert function into list *)
(forall n m : cand, {n = m} + {n <> m}) -> (* This is need because we want to construct the ballot *)
(cand -> ciphertext) -> (* ciphertext *)
Permutation -> (* pi *)
R -> (* Randomness R *)
(cand -> ciphertext).
(* Construct zero knowledge proof from original and shuffled ballot *)
(* Each row of ballot is represented by function *)
Parameter shuffle_zkp :
Group -> (* group *)
nat -> (* length *)
list cand -> (* cand_all *)
(cand -> ciphertext) -> (* cipertext *)
(cand -> ciphertext) -> (* shuffle cipertext *)
Permutation -> (* pi *)
Commitment -> (* cpi *)
S -> (* s, permutation commitment randomness *)
R -> (* r, shuffle randomness *)
ShuffleZkp. (* zero knowledge proof of shuffle *)
(* verify shuffle. This function checks the claim about a shuffled ciphertext is
shuffling of a given ciphertext by a permutation whose commitment is given *)
Parameter verify_shuffle:
Group -> (* group *)
nat -> (* length *)
list cand ->
(cand -> ciphertext) -> (* cipertext *)
(cand -> ciphertext) -> (* shuffled cipertext *)
Commitment -> (* permutation commitment *)
ShuffleZkp -> (* zero knowledge proof of shuffle *)
bool. (* true or false *)
End Crypto.
(* The reason for separating the Axioms from functions is that these axioms
no longer need to instantiate for extraction *)
Module CAxioms (Import C : Cand) (Import K : Keys) (Import Abst : Abstype)
(Import Crp : Crypto C K Abst).
(* Relation between Public and Private key. This axiom enforces that
publickey and privatekey are generated in pair according to
key generation protocol. *)
Axiom Keypair : Pubkey -> Prikey -> Prop.
(* Coherence Axiom that states that publickey and privatekey are related *)
Axiom keypair : Keypair publickey privatekey.
(* Coherence axiom about honest decryption zero knowledge proof *)
Axiom verify_honest_decryption_zkp :
forall (pt : plaintext) (ct : ciphertext)
(H : pt = decrypt_message Crp.grp privatekey ct),
verify_zero_knowledge_decryption_proof
Crp.grp pt ct
(construct_zero_knowledge_decryption_proof Crp.grp privatekey ct) = true.
(* Decryption is left inverse, and we can only decrypt when the keys are
related *)
Axiom decryption_deterministic :
forall (pt : plaintext),
decrypt_message Crp.grp privatekey (encrypt_message Crp.grp pt) = pt.
Axiom permutation_commitment_axiom :
forall (pi : Permutation) (cpi : Commitment) (s : S) (zkppermcommit : PermZkp)
(H1 : cpi = generatePermutationCommitment Crp.grp (List.length cand_all) cand_all pi s)
(H2 : zkppermcommit = zkpPermutationCommitment
Crp.grp (List.length cand_all) cand_all pi cpi s),
verify_permutation_commitment Crp.grp (List.length cand_all)
cpi zkppermcommit = true.
(* Property of Homomorphic addition *)
Axiom homomorphic_addition_axiom :
forall (c d : ciphertext),
decrypt_message Crp.grp privatekey (homomorphic_addition Crp.grp c d) =
decrypt_message Crp.grp privatekey c + decrypt_message Crp.grp privatekey d.
(* Coherence Axiom about shuffle. If every thing is
followed according to protocol then verify_shuffle function
returns true *)
Axiom verify_shuffle_axiom :
forall (pi : Permutation) (cpi : Commitment) (s : S)
(cp shuffledcp : cand -> ciphertext)
(r : R) (zkprowshuffle : ShuffleZkp)
(H1 : cpi = generatePermutationCommitment Crp.grp (List.length cand_all) cand_all pi s)
(H2 : shuffledcp = shuffle Crp.grp (List.length cand_all) cand_all dec_cand cp pi r)
(H3 : zkprowshuffle = shuffle_zkp Crp.grp (List.length cand_all)
cand_all cp shuffledcp pi cpi s r),
verify_shuffle Crp.grp (List.length cand_all)
cand_all cp shuffledcp cpi zkprowshuffle = true.
(* Coherence about shuffle introducing reencryption *)
Axiom shuffle_perm :
forall n f pi r g,
shuffle Crp.grp n cand_all dec_cand (f : cand -> ciphertext) (pi : Permutation) r = g ->
forall c, decrypt_message Crp.grp privatekey (g c) =
decrypt_message Crp.grp privatekey (compose f (projT1 pi) c).
(* end of axioms about shuffle. *)
(* This axiom states that
if verify_zero_knowledge_decryption_proof grp d c zkp = true then
d is honest decryption of c *)
Axiom decryption_from_zkp_proof :
forall c d zkp,
verify_zero_knowledge_decryption_proof Crp.grp d c zkp = true ->
d = decrypt_message Crp.grp privatekey c.
(* Coherence axiom about Permutation *)
Axiom perm_axiom :
forall cpi zkpcpi,
verify_permutation_commitment Crp.grp (Datatypes.length cand_all) cpi zkpcpi = true ->
existsT (pi : Permutation), forall (f g : cand -> ciphertext) (zkppf : ShuffleZkp),
verify_shuffle Crp.grp (Datatypes.length cand_all) cand_all f g cpi zkppf = true ->
forall c, decrypt_message Crp.grp privatekey (g c) =
decrypt_message Crp.grp privatekey (compose f (projT1 pi) c).
(* End of Axioms *)
End CAxioms.
|
/-!
==========
Hello
==========
Inspecting Lean
=================
-/
#eval Lean.versionString
#eval Lean.versionStringCore
#eval Lean.toolchain
#eval Lean.origin
#eval Lean.githash
/-!
Proofs
=======
-/
theorem test (p q : Prop) (hp : p) (hq : q): p ∧ q ↔ q ∧ p := by
apply Iff.intro
. intro h
apply And.intro
. exact hq
. exact hp
. intro h
apply And.intro
. exact hp
. exact hq
|
[STATEMENT]
lemma cycle_decomp: "u \<noteq> [] \<Longrightarrow> cycle u = u @- cycle u"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. u \<noteq> [] \<Longrightarrow> cycle u = u @- cycle u
[PROOF STEP]
proof (coinduction arbitrary: u)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>u. u \<noteq> [] \<Longrightarrow> shd (cycle u) = shd (u @- cycle u) \<and> (\<exists>ua. stl (cycle u) = cycle ua \<and> stl (u @- cycle u) = ua @- cycle ua \<and> ua \<noteq> [])
[PROOF STEP]
case Eq_stream
[PROOF STATE]
proof (state)
this:
u \<noteq> []
goal (1 subgoal):
1. \<And>u. u \<noteq> [] \<Longrightarrow> shd (cycle u) = shd (u @- cycle u) \<and> (\<exists>ua. stl (cycle u) = cycle ua \<and> stl (u @- cycle u) = ua @- cycle ua \<and> ua \<noteq> [])
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
u \<noteq> []
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
u \<noteq> []
goal (1 subgoal):
1. shd (cycle u) = shd (u @- cycle u) \<and> (\<exists>u. stl (cycle u) = cycle u \<and> stl (u @- cycle u) = u @- cycle u \<and> u \<noteq> [])
[PROOF STEP]
using stream.collapse[of "cycle u"]
[PROOF STATE]
proof (prove)
using this:
u \<noteq> []
shd (cycle u) ## stl (cycle u) = cycle u
goal (1 subgoal):
1. shd (cycle u) = shd (u @- cycle u) \<and> (\<exists>u. stl (cycle u) = cycle u \<and> stl (u @- cycle u) = u @- cycle u \<and> u \<noteq> [])
[PROOF STEP]
by (auto intro!: exI[of _ "tl u @ [hd u]"])
[PROOF STATE]
proof (state)
this:
shd (cycle u) = shd (u @- cycle u) \<and> (\<exists>u. stl (cycle u) = cycle u \<and> stl (u @- cycle u) = u @- cycle u \<and> u \<noteq> [])
goal:
No subgoals!
[PROOF STEP]
qed
|
#pragma once
#include <gsl/gsl>
#include <DirectXMath.h>
#include <vector>
#include <memory>
#include <string>
#include <cstdint>
namespace Library
{
class Model;
class Bone;
class Keyframe;
class OutputStreamHelper;
class InputStreamHelper;
struct BoneAnimationData final
{
std::uint32_t BoneIndex{ 0 };
std::vector<std::shared_ptr<Keyframe>> Keyframes;
};
class BoneAnimation final
{
public:
BoneAnimation(Model& model, InputStreamHelper& streamHelper);
BoneAnimation(Model& model, const BoneAnimationData& boneAnimationData);
BoneAnimation(Model& model, BoneAnimationData&& boneAnimationData);
BoneAnimation(const BoneAnimation&) = default;
BoneAnimation(BoneAnimation&& rhs) = default;
BoneAnimation& operator=(const BoneAnimation& rhs) = default;
BoneAnimation& operator=(BoneAnimation&& rhs) = default;
~BoneAnimation() = default;
Bone& GetBone();
std::vector<std::shared_ptr<Keyframe>>& Keyframes();
std::uint32_t GetTransform(float time, DirectX::XMFLOAT4X4& transform) const;
void GetTransformAtKeyframe(std::uint32_t keyframeIndex, DirectX::XMFLOAT4X4& transform) const;
void GetInteropolatedTransform(float time, DirectX::XMFLOAT4X4& transform) const;
void Save(OutputStreamHelper& streamHelper);
private:
void Load(InputStreamHelper& streamHelper);
std::uint32_t FindKeyframeIndex(float time) const;
Model* mModel;
std::weak_ptr<Bone> mBone;
std::vector<std::shared_ptr<Keyframe>> mKeyframes;
};
}
|
State Before: α : Type u_1
β : Type ?u.83376
γ : Type ?u.83379
ι : Sort ?u.83382
π : α → Type ?u.83387
δ : α → Sort u_2
s : Set α
f g : (i : α) → δ i
inst✝¹ : (j : α) → Decidable (j ∈ s)
inst✝ : (i : α) → Decidable (i ∈ sᶜ)
x : α
hx : x ∈ s
⊢ piecewise (sᶜ) f g x = piecewise s g f x State After: no goals Tactic: simp [hx] State Before: α : Type u_1
β : Type ?u.83376
γ : Type ?u.83379
ι : Sort ?u.83382
π : α → Type ?u.83387
δ : α → Sort u_2
s : Set α
f g : (i : α) → δ i
inst✝¹ : (j : α) → Decidable (j ∈ s)
inst✝ : (i : α) → Decidable (i ∈ sᶜ)
x : α
hx : ¬x ∈ s
⊢ piecewise (sᶜ) f g x = piecewise s g f x State After: no goals Tactic: simp [hx]
|
[STATEMENT]
lemma unitary_between_apply:
fixes E F :: \<open>'a::chilbert_space set\<close>
assumes \<open>is_onb E\<close> \<open>is_onb F\<close> \<open>e \<in> E\<close>
shows \<open>unitary_between E F *\<^sub>V e = bij_between_bases E F e\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. unitary_between E F *\<^sub>V e = bij_between_bases E F e
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. unitary_between E F *\<^sub>V e = bij_between_bases E F e
[PROOF STEP]
from \<open>is_onb E\<close> \<open>is_onb F\<close>
[PROOF STATE]
proof (chain)
picking this:
is_onb E
is_onb F
[PROOF STEP]
have EF: \<open>bij_between_bases E F e \<in> F\<close> if \<open>e \<in> E\<close> for e
[PROOF STATE]
proof (prove)
using this:
is_onb E
is_onb F
goal (1 subgoal):
1. bij_between_bases E F e \<in> F
[PROOF STEP]
by (meson bij_betwE bij_between_bases_bij that)
[PROOF STATE]
proof (state)
this:
?e \<in> E \<Longrightarrow> bij_between_bases E F ?e \<in> F
goal (1 subgoal):
1. unitary_between E F *\<^sub>V e = bij_between_bases E F e
[PROOF STEP]
have ortho: \<open>is_orthogonal (bij_between_bases E F x) (bij_between_bases E F y)\<close> if \<open>x \<noteq> y\<close> and \<open>x \<in> E\<close> and \<open>y \<in> E\<close> for x y
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. is_orthogonal (bij_between_bases E F x) (bij_between_bases E F y)
[PROOF STEP]
by (smt (verit, del_insts) assms(1) assms(2) bij_betw_iff_bijections bij_between_bases_bij is_onb_def is_ortho_set_def that(1) that(2) that(3))
[PROOF STATE]
proof (state)
this:
\<lbrakk>?x \<noteq> ?y; ?x \<in> E; ?y \<in> E\<rbrakk> \<Longrightarrow> is_orthogonal (bij_between_bases E F ?x) (bij_between_bases E F ?y)
goal (1 subgoal):
1. unitary_between E F *\<^sub>V e = bij_between_bases E F e
[PROOF STEP]
have spanE: \<open>closure (cspan E) = UNIV\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. closure (cspan E) = UNIV
[PROOF STEP]
by (metis assms(1) ccspan.rep_eq is_onb_def top_ccsubspace.rep_eq)
[PROOF STATE]
proof (state)
this:
closure (cspan E) = UNIV
goal (1 subgoal):
1. unitary_between E F *\<^sub>V e = bij_between_bases E F e
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. unitary_between E F *\<^sub>V e = bij_between_bases E F e
[PROOF STEP]
unfolding unitary_between_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cblinfun_extension E (bij_between_bases E F) *\<^sub>V e = bij_between_bases E F e
[PROOF STEP]
apply (rule cblinfun_extension_apply)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. cblinfun_extension_exists E (bij_between_bases E F)
2. e \<in> E
[PROOF STEP]
apply (rule cblinfun_extension_exists_ortho[where B=1])
[PROOF STATE]
proof (prove)
goal (5 subgoals):
1. is_ortho_set E
2. closure (cspan E) = UNIV
3. \<And>x y. \<lbrakk>x \<in> E; y \<in> E; x \<noteq> y\<rbrakk> \<Longrightarrow> is_orthogonal (bij_between_bases E F x) (bij_between_bases E F y)
4. \<And>x. x \<in> E \<Longrightarrow> norm (bij_between_bases E F x) \<le> 1 * norm x
5. e \<in> E
[PROOF STEP]
using assms EF ortho spanE
[PROOF STATE]
proof (prove)
using this:
is_onb E
is_onb F
e \<in> E
?e \<in> E \<Longrightarrow> bij_between_bases E F ?e \<in> F
\<lbrakk>?x \<noteq> ?y; ?x \<in> E; ?y \<in> E\<rbrakk> \<Longrightarrow> is_orthogonal (bij_between_bases E F ?x) (bij_between_bases E F ?y)
closure (cspan E) = UNIV
goal (5 subgoals):
1. is_ortho_set E
2. closure (cspan E) = UNIV
3. \<And>x y. \<lbrakk>x \<in> E; y \<in> E; x \<noteq> y\<rbrakk> \<Longrightarrow> is_orthogonal (bij_between_bases E F x) (bij_between_bases E F y)
4. \<And>x. x \<in> E \<Longrightarrow> norm (bij_between_bases E F x) \<le> 1 * norm x
5. e \<in> E
[PROOF STEP]
by (auto simp: is_onb_def)
[PROOF STATE]
proof (state)
this:
unitary_between E F *\<^sub>V e = bij_between_bases E F e
goal:
No subgoals!
[PROOF STEP]
qed
|
[STATEMENT]
lemma floor_le_zero [simp]: "\<lfloor>x\<rfloor> \<le> 0 \<longleftrightarrow> x < 1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<lfloor>x\<rfloor> \<le> 0) = (x < (1::'a))
[PROOF STEP]
by (simp add: floor_le_iff)
|
/-
Copyright (c) 2021 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Fin.Basic
/-- A max-heap data structure. -/
structure BinaryHeap (α) (lt : α → α → Bool) where
arr : Array α
namespace BinaryHeap
/-- Core operation for binary heaps, expressed directly on arrays.
Given an array which is a max-heap, push item `i` down to restore the max-heap property. -/
def heapifyDown (lt : α → α → Bool) (a : Array α) (i : Fin a.size) :
{a' : Array α // a'.size = a.size} :=
let left := 2 * i.1 + 1
let right := left + 1
have left_le : i ≤ left := Nat.le_trans
(by rw [Nat.succ_mul, Nat.one_mul]; exact Nat.le_add_left i i)
(Nat.le_add_right ..)
have right_le : i ≤ right := Nat.le_trans left_le (Nat.le_add_right ..)
have i_le : i ≤ i := Nat.le_refl _
have j : {j : Fin a.size // i ≤ j} := if h : left < a.size then
if lt (a.get i) (a.get ⟨left, h⟩) then ⟨⟨left, h⟩, left_le⟩ else ⟨i, i_le⟩ else ⟨i, i_le⟩
have j := if h : right < a.size then
if lt (a.get j) (a.get ⟨right, h⟩) then ⟨⟨right, h⟩, right_le⟩ else j else j
if h : i.1 = j then ⟨a, rfl⟩ else
let a' := a.swap i j
let j' := ⟨j, by rw [a.size_swap i j]; exact j.1.2⟩
have : a'.size - j < a.size - i := by
rw [a.size_swap i j]; exact Nat.sub_lt_sub_left i.2 <| Nat.lt_of_le_and_ne j.2 h
let ⟨a₂, h₂⟩ := heapifyDown lt a' j'
⟨a₂, h₂.trans (a.size_swap i j)⟩
termination_by _ => a.size - i
decreasing_by assumption
@[simp] theorem size_heapifyDown (lt : α → α → Bool) (a : Array α) (i : Fin a.size) :
(heapifyDown lt a i).1.size = a.size := (heapifyDown lt a i).2
/-- Core operation for binary heaps, expressed directly on arrays.
Construct a heap from an unsorted array, by heapifying all the elements. -/
def mkHeap (lt : α → α → Bool) (a : Array α) : {a' : Array α // a'.size = a.size} :=
let rec loop : (i : Nat) → (a : Array α) → i ≤ a.size → {a' : Array α // a'.size = a.size}
| 0, a, _ => ⟨a, rfl⟩
| i+1, a, h =>
let h := Nat.lt_of_succ_le h
let a' := heapifyDown lt a ⟨i, h⟩
let ⟨a₂, h₂⟩ := loop i a' ((heapifyDown ..).2.symm ▸ le_of_lt h)
⟨a₂, h₂.trans a'.2⟩
loop (a.size / 2) a (Nat.div_le_self ..)
@[simp] theorem size_mkHeap (lt : α → α → Bool) (a : Array α) (i : Fin a.size) :
(mkHeap lt a).1.size = a.size := (mkHeap lt a).2
/-- Core operation for binary heaps, expressed directly on arrays.
Given an array which is a max-heap, push item `i` up to restore the max-heap property. -/
def heapifyUp (lt : α → α → Bool) (a : Array α) (i : Fin a.size) :
{a' : Array α // a'.size = a.size} :=
if i0 : i.1 = 0 then ⟨a, rfl⟩ else
have : (i.1 - 1) / 2 < i := lt_of_le_of_lt (Nat.div_le_self ..) $
Nat.sub_lt (Nat.pos_iff_ne_zero.2 i0) Nat.one_pos
let j := ⟨(i.1 - 1) / 2, lt_trans this i.2⟩
if lt (a.get j) (a.get i) then
let a' := a.swap i j
let ⟨a₂, h₂⟩ := heapifyUp lt a' ⟨j.1, by rw [a.size_swap i j]; exact j.2⟩
⟨a₂, h₂.trans (a.size_swap i j)⟩
else ⟨a, rfl⟩
termination_by _ => i.1
decreasing_by assumption
@[simp] theorem size_heapifyUp (lt : α → α → Bool) (a : Array α) (i : Fin a.size) :
(heapifyUp lt a i).1.size = a.size := (heapifyUp lt a i).2
/-- `O(1)`. Build a new empty heap. -/
def empty (lt) : BinaryHeap α lt := ⟨#[]⟩
instance (lt) : Inhabited (BinaryHeap α lt) := ⟨empty _⟩
instance (lt) : EmptyCollection (BinaryHeap α lt) := ⟨empty _⟩
/-- `O(1)`. Build a one-element heap. -/
def singleton (lt) (x : α) : BinaryHeap α lt := ⟨#[x]⟩
/-- `O(1)`. Get the number of elements in a `BinaryHeap`. -/
def size {lt} (self : BinaryHeap α lt) : Nat := self.1.size
/-- `O(1)`. Get an element in the heap by index. -/
def get {lt} (self : BinaryHeap α lt) (i : Fin self.size) : α := self.1.get i
/-- `O(log n)`. Insert an element into a `BinaryHeap`, preserving the max-heap property. -/
def insert {lt} (self : BinaryHeap α lt) (x : α) : BinaryHeap α lt where
arr := let n := self.size;
heapifyUp lt (self.1.push x) ⟨n, by rw [Array.size_push]; apply Nat.lt_succ_self⟩
@[simp] theorem size_insert {lt} (self : BinaryHeap α lt) (x : α) :
(self.insert x).size = self.size + 1 := by
simp [insert, size, size_heapifyUp]
/-- `O(1)`. Get the maximum element in a `BinaryHeap`. -/
def max {lt} (self : BinaryHeap α lt) : Option α := self.1.get? 0
/-- Auxiliary for `popMax`. -/
def popMaxAux {lt} (self : BinaryHeap α lt) : {a' : BinaryHeap α lt // a'.size = self.size - 1} :=
match e: self.1.size with
| 0 => ⟨self, by simp [size, e]⟩
| n+1 =>
have h0 := by rw [e]; apply Nat.succ_pos
have hn := by rw [e]; apply Nat.lt_succ_self
if hn0 : 0 < n then
let a := self.1.swap ⟨0, h0⟩ ⟨n, hn⟩ |>.pop
⟨⟨heapifyDown lt a ⟨0, by rwa [Array.size_pop, Array.size_swap, e, Nat.add_sub_cancel]⟩⟩,
by simp [size]⟩
else
⟨⟨self.1.pop⟩, by simp [size]⟩
/-- `O(log n)`. Remove the maximum element from a `BinaryHeap`.
Call `max` first to actually retrieve the maximum element. -/
def popMax {lt} (self : BinaryHeap α lt) : BinaryHeap α lt := self.popMaxAux
@[simp] theorem size_popMax {lt} (self : BinaryHeap α lt) :
self.popMax.size = self.size - 1 := self.popMaxAux.2
/-- `O(log n)`. Return and remove the maximum element from a `BinaryHeap`. -/
def extractMax {lt} (self : BinaryHeap α lt) : Option α × BinaryHeap α lt :=
(self.max, self.popMax)
theorem size_pos_of_max {lt} {self : BinaryHeap α lt} (e : self.max = some x) : 0 < self.size :=
Decidable.of_not_not fun h: ¬ 0 < self.1.size => by simp [BinaryHeap.max, Array.get?, h] at e
/-- `O(log n)`. Equivalent to `extractMax (self.insert x)`, except that extraction cannot fail. -/
def insertExtractMax {lt} (self : BinaryHeap α lt) (x : α) : α × BinaryHeap α lt :=
match e: self.max with
| none => (x, self)
| some m =>
if lt x m then
let a := self.1.set ⟨0, size_pos_of_max e⟩ x
(m, ⟨heapifyDown lt a ⟨0, by simp; exact size_pos_of_max e⟩⟩)
else (x, self)
/-- `O(log n)`. Equivalent to `(self.max, self.popMax.insert x)`. -/
def replaceMax {lt} (self : BinaryHeap α lt) (x : α) : Option α × BinaryHeap α lt :=
match e: self.max with
| none => (none, ⟨self.1.push x⟩)
| some m =>
let a := self.1.set ⟨0, size_pos_of_max e⟩ x
(some m, ⟨heapifyDown lt a ⟨0, by simp; exact size_pos_of_max e⟩⟩)
/-- `O(log n)`. Replace the value at index `i` by `x`. Assumes that `x ≤ self.get i`. -/
def decreaseKey {lt} (self : BinaryHeap α lt) (i : Fin self.size) (x : α) : BinaryHeap α lt where
arr := heapifyDown lt (self.1.set i x) ⟨i, by rw [self.1.size_set]; exact i.2⟩
/-- `O(log n)`. Replace the value at index `i` by `x`. Assumes that `self.get i ≤ x`. -/
def increaseKey {lt} (self : BinaryHeap α lt) (i : Fin self.size) (x : α) : BinaryHeap α lt where
arr := heapifyUp lt (self.1.set i x) ⟨i, by rw [self.1.size_set]; exact i.2⟩
end BinaryHeap
/-- `O(n)`. Convert an unsorted array to a `BinaryHeap`. -/
def Array.toBinaryHeap (lt : α → α → Bool) (a : Array α) : BinaryHeap α lt where
arr := BinaryHeap.mkHeap lt a
/-- `O(n log n)`. Sort an array using a `BinaryHeap`. -/
@[specialize] def Array.heapSort (a : Array α) (lt : α → α → Bool) : Array α :=
let gt y x := lt x y
let rec loop (a : BinaryHeap α gt) (out : Array α) : Array α :=
match e: a.max with
| none => out
| some x =>
have : a.popMax.size < a.size := by
simp; exact Nat.sub_lt (BinaryHeap.size_pos_of_max e) Nat.zero_lt_one
loop a.popMax (out.push x)
loop (a.toBinaryHeap gt) #[]
termination_by _ => a.size
decreasing_by assumption
|
from matplotlib import pyplot as plt
import numpy as np
import afterpulse_tile21
import textmatrix
import uncertainties
table = []
def uformat(x):
ux = uncertainties.ufloat(x.mean, x.sdev)
return f'{ux:.2u}'.replace('+/-', ' \\pm ')
def pformat(p, limit=1e-6):
if p < limit:
return f'{{<{limit:.1g}}}'.replace('e-0', 'e-')
else:
return f'{p:#.2g}'
for j, vov in enumerate(afterpulse_tile21.AfterPulseTile21.defaultparams):
ap21 = afterpulse_tile21.AfterPulseTile21(vov)
(fit1, fit2), fig1, fig2 = ap21.apfittau()
plt.close(fig1)
plt.close(fig2)
# table columns:
# Delay cut Fit parameters Fit quality
# vov lcut rcut events count time bkg const tau1 tau2 p1 factor prob chi2 dof pv
row1 = [
vov,
ap21.params['dcut'],
ap21.params['dcutr'],
ap21.apnevents,
int(ap21.apcount.mean),
f'{ap21.aptime:#.2g}',
ap21.apbkg,
]
row2a = [
ap21.apbkgfit,
fit1.palt['tau'],
'',
'',
ap21.apfactor,
ap21.approb * 100,
f'{fit1.chi2:.0f}',
fit1.dof,
pformat(fit1.Q),
]
row2b = [
ap21.apbkgfit2,
fit2.palt['tau'][0],
fit2.palt['tau'][1] * 1e-3,
fit2.palt['p1'] * 100,
ap21.apfactor2,
ap21.approb2 * 100,
f'{fit2.chi2:.0f}',
fit2.dof,
pformat(fit2.Q),
]
table += [
row1 + row2a,
row1 + row2b,
]
for row in table:
for i, x in enumerate(row):
if hasattr(x, 'mean'):
row[i] = uformat(x)
matrix = textmatrix.TextMatrix(table)
print(matrix.latex())
|
(* Title: HOL/Euclidean_Division.thy
Author: Manuel Eberl, TU Muenchen
Author: Florian Haftmann, TU Muenchen
*)
section \<open>Division in euclidean (semi)rings\<close>
theory Euclidean_Division
imports Int Lattices_Big
begin
subsection \<open>Euclidean (semi)rings with explicit division and remainder\<close>
class euclidean_semiring = semidom_modulo +
fixes euclidean_size :: "'a \<Rightarrow> nat"
assumes size_0 [simp]: "euclidean_size 0 = 0"
assumes mod_size_less:
"b \<noteq> 0 \<Longrightarrow> euclidean_size (a mod b) < euclidean_size b"
assumes size_mult_mono:
"b \<noteq> 0 \<Longrightarrow> euclidean_size a \<le> euclidean_size (a * b)"
begin
lemma euclidean_size_eq_0_iff [simp]:
"euclidean_size b = 0 \<longleftrightarrow> b = 0"
proof
assume "b = 0"
then show "euclidean_size b = 0"
by simp
next
assume "euclidean_size b = 0"
show "b = 0"
proof (rule ccontr)
assume "b \<noteq> 0"
with mod_size_less have "euclidean_size (b mod b) < euclidean_size b" .
with \<open>euclidean_size b = 0\<close> show False
by simp
qed
qed
lemma euclidean_size_greater_0_iff [simp]:
"euclidean_size b > 0 \<longleftrightarrow> b \<noteq> 0"
using euclidean_size_eq_0_iff [symmetric, of b] by safe simp
lemma size_mult_mono': "b \<noteq> 0 \<Longrightarrow> euclidean_size a \<le> euclidean_size (b * a)"
by (subst mult.commute) (rule size_mult_mono)
lemma dvd_euclidean_size_eq_imp_dvd:
assumes "a \<noteq> 0" and "euclidean_size a = euclidean_size b"
and "b dvd a"
shows "a dvd b"
proof (rule ccontr)
assume "\<not> a dvd b"
hence "b mod a \<noteq> 0" using mod_0_imp_dvd [of b a] by blast
then have "b mod a \<noteq> 0" by (simp add: mod_eq_0_iff_dvd)
from \<open>b dvd a\<close> have "b dvd b mod a" by (simp add: dvd_mod_iff)
then obtain c where "b mod a = b * c" unfolding dvd_def by blast
with \<open>b mod a \<noteq> 0\<close> have "c \<noteq> 0" by auto
with \<open>b mod a = b * c\<close> have "euclidean_size (b mod a) \<ge> euclidean_size b"
using size_mult_mono by force
moreover from \<open>\<not> a dvd b\<close> and \<open>a \<noteq> 0\<close>
have "euclidean_size (b mod a) < euclidean_size a"
using mod_size_less by blast
ultimately show False using \<open>euclidean_size a = euclidean_size b\<close>
by simp
qed
lemma euclidean_size_times_unit:
assumes "is_unit a"
shows "euclidean_size (a * b) = euclidean_size b"
proof (rule antisym)
from assms have [simp]: "a \<noteq> 0" by auto
thus "euclidean_size (a * b) \<ge> euclidean_size b" by (rule size_mult_mono')
from assms have "is_unit (1 div a)" by simp
hence "1 div a \<noteq> 0" by (intro notI) simp_all
hence "euclidean_size (a * b) \<le> euclidean_size ((1 div a) * (a * b))"
by (rule size_mult_mono')
also from assms have "(1 div a) * (a * b) = b"
by (simp add: algebra_simps unit_div_mult_swap)
finally show "euclidean_size (a * b) \<le> euclidean_size b" .
qed
lemma euclidean_size_unit:
"is_unit a \<Longrightarrow> euclidean_size a = euclidean_size 1"
using euclidean_size_times_unit [of a 1] by simp
lemma unit_iff_euclidean_size:
"is_unit a \<longleftrightarrow> euclidean_size a = euclidean_size 1 \<and> a \<noteq> 0"
proof safe
assume A: "a \<noteq> 0" and B: "euclidean_size a = euclidean_size 1"
show "is_unit a"
by (rule dvd_euclidean_size_eq_imp_dvd [OF A B]) simp_all
qed (auto intro: euclidean_size_unit)
lemma euclidean_size_times_nonunit:
assumes "a \<noteq> 0" "b \<noteq> 0" "\<not> is_unit a"
shows "euclidean_size b < euclidean_size (a * b)"
proof (rule ccontr)
assume "\<not>euclidean_size b < euclidean_size (a * b)"
with size_mult_mono'[OF assms(1), of b]
have eq: "euclidean_size (a * b) = euclidean_size b" by simp
have "a * b dvd b"
by (rule dvd_euclidean_size_eq_imp_dvd [OF _ eq])
(use assms in simp_all)
hence "a * b dvd 1 * b" by simp
with \<open>b \<noteq> 0\<close> have "is_unit a" by (subst (asm) dvd_times_right_cancel_iff)
with assms(3) show False by contradiction
qed
lemma dvd_imp_size_le:
assumes "a dvd b" "b \<noteq> 0"
shows "euclidean_size a \<le> euclidean_size b"
using assms by (auto simp: size_mult_mono)
lemma dvd_proper_imp_size_less:
assumes "a dvd b" "\<not> b dvd a" "b \<noteq> 0"
shows "euclidean_size a < euclidean_size b"
proof -
from assms(1) obtain c where "b = a * c" by (erule dvdE)
hence z: "b = c * a" by (simp add: mult.commute)
from z assms have "\<not>is_unit c" by (auto simp: mult.commute mult_unit_dvd_iff)
with z assms show ?thesis
by (auto intro!: euclidean_size_times_nonunit)
qed
lemma unit_imp_mod_eq_0:
"a mod b = 0" if "is_unit b"
using that by (simp add: mod_eq_0_iff_dvd unit_imp_dvd)
lemma mod_eq_self_iff_div_eq_0:
"a mod b = a \<longleftrightarrow> a div b = 0" (is "?P \<longleftrightarrow> ?Q")
proof
assume ?P
with div_mult_mod_eq [of a b] show ?Q
by auto
next
assume ?Q
with div_mult_mod_eq [of a b] show ?P
by simp
qed
lemma coprime_mod_left_iff [simp]:
"coprime (a mod b) b \<longleftrightarrow> coprime a b" if "b \<noteq> 0"
by (rule iffI; rule coprimeI)
(use that in \<open>auto dest!: dvd_mod_imp_dvd coprime_common_divisor simp add: dvd_mod_iff\<close>)
lemma coprime_mod_right_iff [simp]:
"coprime a (b mod a) \<longleftrightarrow> coprime a b" if "a \<noteq> 0"
using that coprime_mod_left_iff [of a b] by (simp add: ac_simps)
end
class euclidean_ring = idom_modulo + euclidean_semiring
begin
lemma dvd_diff_commute [ac_simps]:
"a dvd c - b \<longleftrightarrow> a dvd b - c"
proof -
have "a dvd c - b \<longleftrightarrow> a dvd (c - b) * - 1"
by (subst dvd_mult_unit_iff) simp_all
then show ?thesis
by simp
qed
end
subsection \<open>Euclidean (semi)rings with cancel rules\<close>
class euclidean_semiring_cancel = euclidean_semiring +
assumes div_mult_self1 [simp]: "b \<noteq> 0 \<Longrightarrow> (a + c * b) div b = c + a div b"
and div_mult_mult1 [simp]: "c \<noteq> 0 \<Longrightarrow> (c * a) div (c * b) = a div b"
begin
lemma div_mult_self2 [simp]:
assumes "b \<noteq> 0"
shows "(a + b * c) div b = c + a div b"
using assms div_mult_self1 [of b a c] by (simp add: mult.commute)
lemma div_mult_self3 [simp]:
assumes "b \<noteq> 0"
shows "(c * b + a) div b = c + a div b"
using assms by (simp add: add.commute)
lemma div_mult_self4 [simp]:
assumes "b \<noteq> 0"
shows "(b * c + a) div b = c + a div b"
using assms by (simp add: add.commute)
lemma mod_mult_self1 [simp]: "(a + c * b) mod b = a mod b"
proof (cases "b = 0")
case True then show ?thesis by simp
next
case False
have "a + c * b = (a + c * b) div b * b + (a + c * b) mod b"
by (simp add: div_mult_mod_eq)
also from False div_mult_self1 [of b a c] have
"\<dots> = (c + a div b) * b + (a + c * b) mod b"
by (simp add: algebra_simps)
finally have "a = a div b * b + (a + c * b) mod b"
by (simp add: add.commute [of a] add.assoc distrib_right)
then have "a div b * b + (a + c * b) mod b = a div b * b + a mod b"
by (simp add: div_mult_mod_eq)
then show ?thesis by simp
qed
lemma mod_mult_self2 [simp]:
"(a + b * c) mod b = a mod b"
by (simp add: mult.commute [of b])
lemma mod_mult_self3 [simp]:
"(c * b + a) mod b = a mod b"
by (simp add: add.commute)
lemma mod_mult_self4 [simp]:
"(b * c + a) mod b = a mod b"
by (simp add: add.commute)
lemma mod_mult_self1_is_0 [simp]:
"b * a mod b = 0"
using mod_mult_self2 [of 0 b a] by simp
lemma mod_mult_self2_is_0 [simp]:
"a * b mod b = 0"
using mod_mult_self1 [of 0 a b] by simp
lemma div_add_self1:
assumes "b \<noteq> 0"
shows "(b + a) div b = a div b + 1"
using assms div_mult_self1 [of b a 1] by (simp add: add.commute)
lemma div_add_self2:
assumes "b \<noteq> 0"
shows "(a + b) div b = a div b + 1"
using assms div_add_self1 [of b a] by (simp add: add.commute)
lemma mod_add_self1 [simp]:
"(b + a) mod b = a mod b"
using mod_mult_self1 [of a 1 b] by (simp add: add.commute)
lemma mod_add_self2 [simp]:
"(a + b) mod b = a mod b"
using mod_mult_self1 [of a 1 b] by simp
lemma mod_div_trivial [simp]:
"a mod b div b = 0"
proof (cases "b = 0")
assume "b = 0"
thus ?thesis by simp
next
assume "b \<noteq> 0"
hence "a div b + a mod b div b = (a mod b + a div b * b) div b"
by (rule div_mult_self1 [symmetric])
also have "\<dots> = a div b"
by (simp only: mod_div_mult_eq)
also have "\<dots> = a div b + 0"
by simp
finally show ?thesis
by (rule add_left_imp_eq)
qed
lemma mod_mod_trivial [simp]:
"a mod b mod b = a mod b"
proof -
have "a mod b mod b = (a mod b + a div b * b) mod b"
by (simp only: mod_mult_self1)
also have "\<dots> = a mod b"
by (simp only: mod_div_mult_eq)
finally show ?thesis .
qed
lemma mod_mod_cancel:
assumes "c dvd b"
shows "a mod b mod c = a mod c"
proof -
from \<open>c dvd b\<close> obtain k where "b = c * k"
by (rule dvdE)
have "a mod b mod c = a mod (c * k) mod c"
by (simp only: \<open>b = c * k\<close>)
also have "\<dots> = (a mod (c * k) + a div (c * k) * k * c) mod c"
by (simp only: mod_mult_self1)
also have "\<dots> = (a div (c * k) * (c * k) + a mod (c * k)) mod c"
by (simp only: ac_simps)
also have "\<dots> = a mod c"
by (simp only: div_mult_mod_eq)
finally show ?thesis .
qed
lemma div_mult_mult2 [simp]:
"c \<noteq> 0 \<Longrightarrow> (a * c) div (b * c) = a div b"
by (drule div_mult_mult1) (simp add: mult.commute)
lemma div_mult_mult1_if [simp]:
"(c * a) div (c * b) = (if c = 0 then 0 else a div b)"
by simp_all
lemma mod_mult_mult1:
"(c * a) mod (c * b) = c * (a mod b)"
proof (cases "c = 0")
case True then show ?thesis by simp
next
case False
from div_mult_mod_eq
have "((c * a) div (c * b)) * (c * b) + (c * a) mod (c * b) = c * a" .
with False have "c * ((a div b) * b + a mod b) + (c * a) mod (c * b)
= c * a + c * (a mod b)" by (simp add: algebra_simps)
with div_mult_mod_eq show ?thesis by simp
qed
lemma mod_mult_mult2:
"(a * c) mod (b * c) = (a mod b) * c"
using mod_mult_mult1 [of c a b] by (simp add: mult.commute)
lemma mult_mod_left: "(a mod b) * c = (a * c) mod (b * c)"
by (fact mod_mult_mult2 [symmetric])
lemma mult_mod_right: "c * (a mod b) = (c * a) mod (c * b)"
by (fact mod_mult_mult1 [symmetric])
lemma dvd_mod: "k dvd m \<Longrightarrow> k dvd n \<Longrightarrow> k dvd (m mod n)"
unfolding dvd_def by (auto simp add: mod_mult_mult1)
lemma div_plus_div_distrib_dvd_left:
"c dvd a \<Longrightarrow> (a + b) div c = a div c + b div c"
by (cases "c = 0") auto
lemma div_plus_div_distrib_dvd_right:
"c dvd b \<Longrightarrow> (a + b) div c = a div c + b div c"
using div_plus_div_distrib_dvd_left [of c b a]
by (simp add: ac_simps)
lemma sum_div_partition:
\<open>(\<Sum>a\<in>A. f a) div b = (\<Sum>a\<in>A \<inter> {a. b dvd f a}. f a div b) + (\<Sum>a\<in>A \<inter> {a. \<not> b dvd f a}. f a) div b\<close>
if \<open>finite A\<close>
proof -
have \<open>A = A \<inter> {a. b dvd f a} \<union> A \<inter> {a. \<not> b dvd f a}\<close>
by auto
then have \<open>(\<Sum>a\<in>A. f a) = (\<Sum>a\<in>A \<inter> {a. b dvd f a} \<union> A \<inter> {a. \<not> b dvd f a}. f a)\<close>
by simp
also have \<open>\<dots> = (\<Sum>a\<in>A \<inter> {a. b dvd f a}. f a) + (\<Sum>a\<in>A \<inter> {a. \<not> b dvd f a}. f a)\<close>
using \<open>finite A\<close> by (auto intro: sum.union_inter_neutral)
finally have *: \<open>sum f A = sum f (A \<inter> {a. b dvd f a}) + sum f (A \<inter> {a. \<not> b dvd f a})\<close> .
define B where B: \<open>B = A \<inter> {a. b dvd f a}\<close>
with \<open>finite A\<close> have \<open>finite B\<close> and \<open>a \<in> B \<Longrightarrow> b dvd f a\<close> for a
by simp_all
then have \<open>(\<Sum>a\<in>B. f a) div b = (\<Sum>a\<in>B. f a div b)\<close> and \<open>b dvd (\<Sum>a\<in>B. f a)\<close>
by induction (simp_all add: div_plus_div_distrib_dvd_left)
then show ?thesis using *
by (simp add: B div_plus_div_distrib_dvd_left)
qed
named_theorems mod_simps
text \<open>Addition respects modular equivalence.\<close>
lemma mod_add_left_eq [mod_simps]:
"(a mod c + b) mod c = (a + b) mod c"
proof -
have "(a + b) mod c = (a div c * c + a mod c + b) mod c"
by (simp only: div_mult_mod_eq)
also have "\<dots> = (a mod c + b + a div c * c) mod c"
by (simp only: ac_simps)
also have "\<dots> = (a mod c + b) mod c"
by (rule mod_mult_self1)
finally show ?thesis
by (rule sym)
qed
lemma mod_add_right_eq [mod_simps]:
"(a + b mod c) mod c = (a + b) mod c"
using mod_add_left_eq [of b c a] by (simp add: ac_simps)
lemma mod_add_eq:
"(a mod c + b mod c) mod c = (a + b) mod c"
by (simp add: mod_add_left_eq mod_add_right_eq)
lemma mod_sum_eq [mod_simps]:
"(\<Sum>i\<in>A. f i mod a) mod a = sum f A mod a"
proof (induct A rule: infinite_finite_induct)
case (insert i A)
then have "(\<Sum>i\<in>insert i A. f i mod a) mod a
= (f i mod a + (\<Sum>i\<in>A. f i mod a)) mod a"
by simp
also have "\<dots> = (f i + (\<Sum>i\<in>A. f i mod a) mod a) mod a"
by (simp add: mod_simps)
also have "\<dots> = (f i + (\<Sum>i\<in>A. f i) mod a) mod a"
by (simp add: insert.hyps)
finally show ?case
by (simp add: insert.hyps mod_simps)
qed simp_all
lemma mod_add_cong:
assumes "a mod c = a' mod c"
assumes "b mod c = b' mod c"
shows "(a + b) mod c = (a' + b') mod c"
proof -
have "(a mod c + b mod c) mod c = (a' mod c + b' mod c) mod c"
unfolding assms ..
then show ?thesis
by (simp add: mod_add_eq)
qed
text \<open>Multiplication respects modular equivalence.\<close>
lemma mod_mult_left_eq [mod_simps]:
"((a mod c) * b) mod c = (a * b) mod c"
proof -
have "(a * b) mod c = ((a div c * c + a mod c) * b) mod c"
by (simp only: div_mult_mod_eq)
also have "\<dots> = (a mod c * b + a div c * b * c) mod c"
by (simp only: algebra_simps)
also have "\<dots> = (a mod c * b) mod c"
by (rule mod_mult_self1)
finally show ?thesis
by (rule sym)
qed
lemma mod_mult_right_eq [mod_simps]:
"(a * (b mod c)) mod c = (a * b) mod c"
using mod_mult_left_eq [of b c a] by (simp add: ac_simps)
lemma mod_mult_eq:
"((a mod c) * (b mod c)) mod c = (a * b) mod c"
by (simp add: mod_mult_left_eq mod_mult_right_eq)
lemma mod_prod_eq [mod_simps]:
"(\<Prod>i\<in>A. f i mod a) mod a = prod f A mod a"
proof (induct A rule: infinite_finite_induct)
case (insert i A)
then have "(\<Prod>i\<in>insert i A. f i mod a) mod a
= (f i mod a * (\<Prod>i\<in>A. f i mod a)) mod a"
by simp
also have "\<dots> = (f i * ((\<Prod>i\<in>A. f i mod a) mod a)) mod a"
by (simp add: mod_simps)
also have "\<dots> = (f i * ((\<Prod>i\<in>A. f i) mod a)) mod a"
by (simp add: insert.hyps)
finally show ?case
by (simp add: insert.hyps mod_simps)
qed simp_all
lemma mod_mult_cong:
assumes "a mod c = a' mod c"
assumes "b mod c = b' mod c"
shows "(a * b) mod c = (a' * b') mod c"
proof -
have "(a mod c * (b mod c)) mod c = (a' mod c * (b' mod c)) mod c"
unfolding assms ..
then show ?thesis
by (simp add: mod_mult_eq)
qed
text \<open>Exponentiation respects modular equivalence.\<close>
lemma power_mod [mod_simps]:
"((a mod b) ^ n) mod b = (a ^ n) mod b"
proof (induct n)
case 0
then show ?case by simp
next
case (Suc n)
have "(a mod b) ^ Suc n mod b = (a mod b) * ((a mod b) ^ n mod b) mod b"
by (simp add: mod_mult_right_eq)
with Suc show ?case
by (simp add: mod_mult_left_eq mod_mult_right_eq)
qed
lemma power_diff_power_eq:
\<open>a ^ m div a ^ n = (if n \<le> m then a ^ (m - n) else 1 div a ^ (n - m))\<close>
if \<open>a \<noteq> 0\<close>
proof (cases \<open>n \<le> m\<close>)
case True
with that power_diff [symmetric, of a n m] show ?thesis by simp
next
case False
then obtain q where n: \<open>n = m + Suc q\<close>
by (auto simp add: not_le dest: less_imp_Suc_add)
then have \<open>a ^ m div a ^ n = (a ^ m * 1) div (a ^ m * a ^ Suc q)\<close>
by (simp add: power_add ac_simps)
moreover from that have \<open>a ^ m \<noteq> 0\<close>
by simp
ultimately have \<open>a ^ m div a ^ n = 1 div a ^ Suc q\<close>
by (subst (asm) div_mult_mult1) simp
with False n show ?thesis
by simp
qed
end
class euclidean_ring_cancel = euclidean_ring + euclidean_semiring_cancel
begin
subclass idom_divide ..
lemma div_minus_minus [simp]: "(- a) div (- b) = a div b"
using div_mult_mult1 [of "- 1" a b] by simp
lemma mod_minus_minus [simp]: "(- a) mod (- b) = - (a mod b)"
using mod_mult_mult1 [of "- 1" a b] by simp
lemma div_minus_right: "a div (- b) = (- a) div b"
using div_minus_minus [of "- a" b] by simp
lemma mod_minus_right: "a mod (- b) = - ((- a) mod b)"
using mod_minus_minus [of "- a" b] by simp
lemma div_minus1_right [simp]: "a div (- 1) = - a"
using div_minus_right [of a 1] by simp
lemma mod_minus1_right [simp]: "a mod (- 1) = 0"
using mod_minus_right [of a 1] by simp
text \<open>Negation respects modular equivalence.\<close>
lemma mod_minus_eq [mod_simps]:
"(- (a mod b)) mod b = (- a) mod b"
proof -
have "(- a) mod b = (- (a div b * b + a mod b)) mod b"
by (simp only: div_mult_mod_eq)
also have "\<dots> = (- (a mod b) + - (a div b) * b) mod b"
by (simp add: ac_simps)
also have "\<dots> = (- (a mod b)) mod b"
by (rule mod_mult_self1)
finally show ?thesis
by (rule sym)
qed
lemma mod_minus_cong:
assumes "a mod b = a' mod b"
shows "(- a) mod b = (- a') mod b"
proof -
have "(- (a mod b)) mod b = (- (a' mod b)) mod b"
unfolding assms ..
then show ?thesis
by (simp add: mod_minus_eq)
qed
text \<open>Subtraction respects modular equivalence.\<close>
lemma mod_diff_left_eq [mod_simps]:
"(a mod c - b) mod c = (a - b) mod c"
using mod_add_cong [of a c "a mod c" "- b" "- b"]
by simp
lemma mod_diff_right_eq [mod_simps]:
"(a - b mod c) mod c = (a - b) mod c"
using mod_add_cong [of a c a "- b" "- (b mod c)"] mod_minus_cong [of "b mod c" c b]
by simp
lemma mod_diff_eq:
"(a mod c - b mod c) mod c = (a - b) mod c"
using mod_add_cong [of a c "a mod c" "- b" "- (b mod c)"] mod_minus_cong [of "b mod c" c b]
by simp
lemma mod_diff_cong:
assumes "a mod c = a' mod c"
assumes "b mod c = b' mod c"
shows "(a - b) mod c = (a' - b') mod c"
using assms mod_add_cong [of a c a' "- b" "- b'"] mod_minus_cong [of b c "b'"]
by simp
lemma minus_mod_self2 [simp]:
"(a - b) mod b = a mod b"
using mod_diff_right_eq [of a b b]
by (simp add: mod_diff_right_eq)
lemma minus_mod_self1 [simp]:
"(b - a) mod b = - a mod b"
using mod_add_self2 [of "- a" b] by simp
lemma mod_eq_dvd_iff:
"a mod c = b mod c \<longleftrightarrow> c dvd a - b" (is "?P \<longleftrightarrow> ?Q")
proof
assume ?P
then have "(a mod c - b mod c) mod c = 0"
by simp
then show ?Q
by (simp add: dvd_eq_mod_eq_0 mod_simps)
next
assume ?Q
then obtain d where d: "a - b = c * d" ..
then have "a = c * d + b"
by (simp add: algebra_simps)
then show ?P by simp
qed
lemma mod_eqE:
assumes "a mod c = b mod c"
obtains d where "b = a + c * d"
proof -
from assms have "c dvd a - b"
by (simp add: mod_eq_dvd_iff)
then obtain d where "a - b = c * d" ..
then have "b = a + c * - d"
by (simp add: algebra_simps)
with that show thesis .
qed
lemma invertible_coprime:
"coprime a c" if "a * b mod c = 1"
by (rule coprimeI) (use that dvd_mod_iff [of _ c "a * b"] in auto)
end
subsection \<open>Uniquely determined division\<close>
class unique_euclidean_semiring = euclidean_semiring +
assumes euclidean_size_mult: \<open>euclidean_size (a * b) = euclidean_size a * euclidean_size b\<close>
fixes division_segment :: \<open>'a \<Rightarrow> 'a\<close>
assumes is_unit_division_segment [simp]: \<open>is_unit (division_segment a)\<close>
and division_segment_mult:
\<open>a \<noteq> 0 \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> division_segment (a * b) = division_segment a * division_segment b\<close>
and division_segment_mod:
\<open>b \<noteq> 0 \<Longrightarrow> \<not> b dvd a \<Longrightarrow> division_segment (a mod b) = division_segment b\<close>
assumes div_bounded:
\<open>b \<noteq> 0 \<Longrightarrow> division_segment r = division_segment b
\<Longrightarrow> euclidean_size r < euclidean_size b
\<Longrightarrow> (q * b + r) div b = q\<close>
begin
lemma division_segment_not_0 [simp]:
\<open>division_segment a \<noteq> 0\<close>
using is_unit_division_segment [of a] is_unitE [of \<open>division_segment a\<close>] by blast
lemma euclidean_relationI [case_names by0 divides euclidean_relation]:
\<open>(a div b, a mod b) = (q, r)\<close>
if by0: \<open>b = 0 \<Longrightarrow> q = 0 \<and> r = a\<close>
and divides: \<open>b \<noteq> 0 \<Longrightarrow> b dvd a \<Longrightarrow> r = 0 \<and> a = q * b\<close>
and euclidean_relation: \<open>b \<noteq> 0 \<Longrightarrow> \<not> b dvd a \<Longrightarrow> division_segment r = division_segment b
\<and> euclidean_size r < euclidean_size b \<and> a = q * b + r\<close>
proof (cases \<open>b = 0\<close>)
case True
with by0 show ?thesis
by simp
next
case False
show ?thesis
proof (cases \<open>b dvd a\<close>)
case True
with \<open>b \<noteq> 0\<close> divides
show ?thesis
by simp
next
case False
with \<open>b \<noteq> 0\<close> euclidean_relation
have \<open>division_segment r = division_segment b\<close>
\<open>euclidean_size r < euclidean_size b\<close> \<open>a = q * b + r\<close>
by simp_all
from \<open>b \<noteq> 0\<close> \<open>division_segment r = division_segment b\<close>
\<open>euclidean_size r < euclidean_size b\<close>
have \<open>(q * b + r) div b = q\<close>
by (rule div_bounded)
with \<open>a = q * b + r\<close>
have \<open>q = a div b\<close>
by simp
from \<open>a = q * b + r\<close>
have \<open>a div b * b + a mod b = q * b + r\<close>
by (simp add: div_mult_mod_eq)
with \<open>q = a div b\<close>
have \<open>q * b + a mod b = q * b + r\<close>
by simp
then have \<open>r = a mod b\<close>
by simp
with \<open>q = a div b\<close>
show ?thesis
by simp
qed
qed
subclass euclidean_semiring_cancel
proof
fix a b c
assume \<open>b \<noteq> 0\<close>
have \<open>((a + c * b) div b, (a + c * b) mod b) = (c + a div b, a mod b)\<close>
proof (cases b \<open>c + a div b\<close> \<open>a mod b\<close> \<open>a + c * b\<close> rule: euclidean_relationI)
case by0
with \<open>b \<noteq> 0\<close>
show ?case
by simp
next
case divides
then show ?case
by (simp add: algebra_simps dvd_add_left_iff)
next
case euclidean_relation
then have \<open>\<not> b dvd a\<close>
by (simp add: dvd_add_left_iff)
have \<open>a mod b + (b * c + b * (a div b)) = b * c + ((a div b) * b + a mod b)\<close>
by (simp add: ac_simps)
with \<open>b \<noteq> 0\<close> have *: \<open>a mod b + (b * c + b * (a div b)) = b * c + a\<close>
by (simp add: div_mult_mod_eq)
from \<open>\<not> b dvd a\<close> euclidean_relation show ?case
by (simp_all add: algebra_simps division_segment_mod mod_size_less *)
qed
then show \<open>(a + c * b) div b = c + a div b\<close>
by simp
next
fix a b c
assume \<open>c \<noteq> 0\<close>
have \<open>((c * a) div (c * b), (c * a) mod (c * b)) = (a div b, c * (a mod b))\<close>
proof (cases \<open>c * b\<close> \<open>a div b\<close> \<open>c * (a mod b)\<close> \<open>c * a\<close> rule: euclidean_relationI)
case by0
with \<open>c \<noteq> 0\<close> show ?case
by simp
next
case divides
then show ?case
by (auto simp add: algebra_simps)
next
case euclidean_relation
then have \<open>b \<noteq> 0\<close> \<open>a mod b \<noteq> 0\<close>
by (simp_all add: mod_eq_0_iff_dvd)
have \<open>c * (a mod b) + b * (c * (a div b)) = c * ((a div b) * b + a mod b)\<close>
by (simp add: algebra_simps)
with \<open>b \<noteq> 0\<close> have *: \<open>c * (a mod b) + b * (c * (a div b)) = c * a\<close>
by (simp add: div_mult_mod_eq)
from \<open>b \<noteq> 0\<close> \<open>c \<noteq> 0\<close> have \<open>euclidean_size c * euclidean_size (a mod b)
< euclidean_size c * euclidean_size b\<close>
using mod_size_less [of b a] by simp
with euclidean_relation \<open>b \<noteq> 0\<close> \<open>a mod b \<noteq> 0\<close> show ?case
by (simp add: algebra_simps division_segment_mult division_segment_mod euclidean_size_mult *)
qed
then show \<open>(c * a) div (c * b) = a div b\<close>
by simp
qed
lemma div_eq_0_iff:
\<open>a div b = 0 \<longleftrightarrow> euclidean_size a < euclidean_size b \<or> b = 0\<close> (is "_ \<longleftrightarrow> ?P")
if \<open>division_segment a = division_segment b\<close>
proof (cases \<open>a = 0 \<or> b = 0\<close>)
case True
then show ?thesis by auto
next
case False
then have \<open>a \<noteq> 0\<close> \<open>b \<noteq> 0\<close>
by simp_all
have \<open>a div b = 0 \<longleftrightarrow> euclidean_size a < euclidean_size b\<close>
proof
assume \<open>a div b = 0\<close>
then have \<open>a mod b = a\<close>
using div_mult_mod_eq [of a b] by simp
with \<open>b \<noteq> 0\<close> mod_size_less [of b a]
show \<open>euclidean_size a < euclidean_size b\<close>
by simp
next
assume \<open>euclidean_size a < euclidean_size b\<close>
have \<open>(a div b, a mod b) = (0, a)\<close>
proof (cases b 0 a a rule: euclidean_relationI)
case by0
show ?case
by simp
next
case divides
with \<open>euclidean_size a < euclidean_size b\<close> show ?case
using dvd_imp_size_le [of b a] \<open>a \<noteq> 0\<close> by simp
next
case euclidean_relation
with \<open>euclidean_size a < euclidean_size b\<close> that
show ?case
by simp
qed
then show \<open>a div b = 0\<close>
by simp
qed
with \<open>b \<noteq> 0\<close> show ?thesis
by simp
qed
lemma div_mult1_eq:
\<open>(a * b) div c = a * (b div c) + a * (b mod c) div c\<close>
proof -
have *: \<open>(a * b) mod c + (a * (c * (b div c)) + c * (a * (b mod c) div c)) = a * b\<close> (is \<open>?A + (?B + ?C) = _\<close>)
proof -
have \<open>?A = a * (b mod c) mod c\<close>
by (simp add: mod_mult_right_eq)
then have \<open>?C + ?A = a * (b mod c)\<close>
by (simp add: mult_div_mod_eq)
then have \<open>?B + (?C + ?A) = a * (c * (b div c) + (b mod c))\<close>
by (simp add: algebra_simps)
also have \<open>\<dots> = a * b\<close>
by (simp add: mult_div_mod_eq)
finally show ?thesis
by (simp add: algebra_simps)
qed
have \<open>((a * b) div c, (a * b) mod c) = (a * (b div c) + a * (b mod c) div c, (a * b) mod c)\<close>
proof (cases c \<open>a * (b div c) + a * (b mod c) div c\<close> \<open>(a * b) mod c\<close> \<open>a * b\<close> rule: euclidean_relationI)
case by0
then show ?case by simp
next
case divides
with * show ?case
by (simp add: algebra_simps)
next
case euclidean_relation
with * show ?case
by (simp add: division_segment_mod mod_size_less algebra_simps)
qed
then show ?thesis
by simp
qed
lemma div_add1_eq:
\<open>(a + b) div c = a div c + b div c + (a mod c + b mod c) div c\<close>
proof -
have *: \<open>(a + b) mod c + (c * (a div c) + (c * (b div c) + c * ((a mod c + b mod c) div c))) = a + b\<close>
(is \<open>?A + (?B + (?C + ?D)) = _\<close>)
proof -
have \<open>?A + (?B + (?C + ?D)) = ?A + ?D + (?B + ?C)\<close>
by (simp add: ac_simps)
also have \<open>?A + ?D = (a mod c + b mod c) mod c + ?D\<close>
by (simp add: mod_add_eq)
also have \<open>\<dots> = a mod c + b mod c\<close>
by (simp add: mod_mult_div_eq)
finally have \<open>?A + (?B + (?C + ?D)) = (a mod c + ?B) + (b mod c + ?C)\<close>
by (simp add: ac_simps)
then show ?thesis
by (simp add: mod_mult_div_eq)
qed
have \<open>((a + b) div c, (a + b) mod c) = (a div c + b div c + (a mod c + b mod c) div c, (a + b) mod c)\<close>
proof (cases c \<open>a div c + b div c + (a mod c + b mod c) div c\<close> \<open>(a + b) mod c\<close> \<open>a + b\<close> rule: euclidean_relationI)
case by0
then show ?case
by simp
next
case divides
with * show ?case
by (simp add: algebra_simps)
next
case euclidean_relation
with * show ?case
by (simp add: division_segment_mod mod_size_less algebra_simps)
qed
then show ?thesis
by simp
qed
end
class unique_euclidean_ring = euclidean_ring + unique_euclidean_semiring
begin
subclass euclidean_ring_cancel ..
end
subsection \<open>Euclidean division on \<^typ>\<open>nat\<close>\<close>
instantiation nat :: normalization_semidom
begin
definition normalize_nat :: \<open>nat \<Rightarrow> nat\<close>
where [simp]: \<open>normalize = (id :: nat \<Rightarrow> nat)\<close>
definition unit_factor_nat :: \<open>nat \<Rightarrow> nat\<close>
where \<open>unit_factor n = of_bool (n > 0)\<close> for n :: nat
lemma unit_factor_simps [simp]:
\<open>unit_factor 0 = (0::nat)\<close>
\<open>unit_factor (Suc n) = 1\<close>
by (simp_all add: unit_factor_nat_def)
definition divide_nat :: \<open>nat \<Rightarrow> nat \<Rightarrow> nat\<close>
where \<open>m div n = (if n = 0 then 0 else Max {k. k * n \<le> m})\<close> for m n :: nat
instance
by standard (auto simp add: divide_nat_def ac_simps unit_factor_nat_def intro: Max_eqI)
end
lemma coprime_Suc_0_left [simp]:
"coprime (Suc 0) n"
using coprime_1_left [of n] by simp
lemma coprime_Suc_0_right [simp]:
"coprime n (Suc 0)"
using coprime_1_right [of n] by simp
lemma coprime_common_divisor_nat: "coprime a b \<Longrightarrow> x dvd a \<Longrightarrow> x dvd b \<Longrightarrow> x = 1"
for a b :: nat
by (drule coprime_common_divisor [of _ _ x]) simp_all
instantiation nat :: unique_euclidean_semiring
begin
definition euclidean_size_nat :: \<open>nat \<Rightarrow> nat\<close>
where [simp]: \<open>euclidean_size_nat = id\<close>
definition division_segment_nat :: \<open>nat \<Rightarrow> nat\<close>
where [simp]: \<open>division_segment n = 1\<close> for n :: nat
definition modulo_nat :: \<open>nat \<Rightarrow> nat \<Rightarrow> nat\<close>
where \<open>m mod n = m - (m div n * n)\<close> for m n :: nat
instance proof
fix m n :: nat
have ex: "\<exists>k. k * n \<le> l" for l :: nat
by (rule exI [of _ 0]) simp
have fin: "finite {k. k * n \<le> l}" if "n > 0" for l
proof -
from that have "{k. k * n \<le> l} \<subseteq> {k. k \<le> l}"
by (cases n) auto
then show ?thesis
by (rule finite_subset) simp
qed
have mult_div_unfold: "n * (m div n) = Max {l. l \<le> m \<and> n dvd l}"
proof (cases "n = 0")
case True
moreover have "{l. l = 0 \<and> l \<le> m} = {0::nat}"
by auto
ultimately show ?thesis
by simp
next
case False
with ex [of m] fin have "n * Max {k. k * n \<le> m} = Max (times n ` {k. k * n \<le> m})"
by (auto simp add: nat_mult_max_right intro: hom_Max_commute)
also have "times n ` {k. k * n \<le> m} = {l. l \<le> m \<and> n dvd l}"
by (auto simp add: ac_simps elim!: dvdE)
finally show ?thesis
using False by (simp add: divide_nat_def ac_simps)
qed
have less_eq: "m div n * n \<le> m"
by (auto simp add: mult_div_unfold ac_simps intro: Max.boundedI)
then show "m div n * n + m mod n = m"
by (simp add: modulo_nat_def)
assume "n \<noteq> 0"
show "euclidean_size (m mod n) < euclidean_size n"
proof -
have "m < Suc (m div n) * n"
proof (rule ccontr)
assume "\<not> m < Suc (m div n) * n"
then have "Suc (m div n) * n \<le> m"
by (simp add: not_less)
moreover from \<open>n \<noteq> 0\<close> have "Max {k. k * n \<le> m} < Suc (m div n)"
by (simp add: divide_nat_def)
with \<open>n \<noteq> 0\<close> ex fin have "\<And>k. k * n \<le> m \<Longrightarrow> k < Suc (m div n)"
by auto
ultimately have "Suc (m div n) < Suc (m div n)"
by blast
then show False
by simp
qed
with \<open>n \<noteq> 0\<close> show ?thesis
by (simp add: modulo_nat_def)
qed
show "euclidean_size m \<le> euclidean_size (m * n)"
using \<open>n \<noteq> 0\<close> by (cases n) simp_all
fix q r :: nat
show "(q * n + r) div n = q" if "euclidean_size r < euclidean_size n"
proof -
from that have "r < n"
by simp
have "k \<le> q" if "k * n \<le> q * n + r" for k
proof (rule ccontr)
assume "\<not> k \<le> q"
then have "q < k"
by simp
then obtain l where "k = Suc (q + l)"
by (auto simp add: less_iff_Suc_add)
with \<open>r < n\<close> that show False
by (simp add: algebra_simps)
qed
with \<open>n \<noteq> 0\<close> ex fin show ?thesis
by (auto simp add: divide_nat_def Max_eq_iff)
qed
qed simp_all
end
lemma euclidean_relation_natI [case_names by0 divides euclidean_relation]:
\<open>(m div n, m mod n) = (q, r)\<close>
if by0: \<open>n = 0 \<Longrightarrow> q = 0 \<and> r = m\<close>
and divides: \<open>n > 0 \<Longrightarrow> n dvd m \<Longrightarrow> r = 0 \<and> m = q * n\<close>
and euclidean_relation: \<open>n > 0 \<Longrightarrow> \<not> n dvd m \<Longrightarrow> r < n \<and> m = q * n + r\<close> for m n q r :: nat
by (rule euclidean_relationI) (use that in simp_all)
lemma div_nat_eqI:
\<open>m div n = q\<close> if \<open>n * q \<le> m\<close> and \<open>m < n * Suc q\<close> for m n q :: nat
proof -
have \<open>(m div n, m mod n) = (q, m - n * q)\<close>
proof (cases n q \<open>m - n * q\<close> m rule: euclidean_relation_natI)
case by0
with that show ?case
by simp
next
case divides
from \<open>n dvd m\<close> obtain s where \<open>m = n * s\<close> ..
with \<open>n > 0\<close> that have \<open>s < Suc q\<close>
by (simp only: mult_less_cancel1)
with \<open>m = n * s\<close> \<open>n > 0\<close> that have \<open>q = s\<close>
by simp
with \<open>m = n * s\<close> show ?case
by (simp add: ac_simps)
next
case euclidean_relation
with that show ?case
by (simp add: ac_simps)
qed
then show ?thesis
by simp
qed
lemma mod_nat_eqI:
\<open>m mod n = r\<close> if \<open>r < n\<close> and \<open>r \<le> m\<close> and \<open>n dvd m - r\<close> for m n r :: nat
proof -
have \<open>(m div n, m mod n) = ((m - r) div n, r)\<close>
proof (cases n \<open>(m - r) div n\<close> r m rule: euclidean_relation_natI)
case by0
with that show ?case
by simp
next
case divides
from that dvd_minus_add [of r \<open>m\<close> 1 n]
have \<open>n dvd m + (n - r)\<close>
by simp
with divides have \<open>n dvd n - r\<close>
by (simp add: dvd_add_right_iff)
then have \<open>n \<le> n - r\<close>
by (rule dvd_imp_le) (use \<open>r < n\<close> in simp)
with \<open>n > 0\<close> have \<open>r = 0\<close>
by simp
with \<open>n > 0\<close> that show ?case
by simp
next
case euclidean_relation
with that show ?case
by (simp add: ac_simps)
qed
then show ?thesis
by simp
qed
text \<open>Tool support\<close>
ML \<open>
structure Cancel_Div_Mod_Nat = Cancel_Div_Mod
(
val div_name = \<^const_name>\<open>divide\<close>;
val mod_name = \<^const_name>\<open>modulo\<close>;
val mk_binop = HOLogic.mk_binop;
val dest_plus = HOLogic.dest_bin \<^const_name>\<open>Groups.plus\<close> HOLogic.natT;
val mk_sum = Arith_Data.mk_sum;
fun dest_sum tm =
if HOLogic.is_zero tm then []
else
(case try HOLogic.dest_Suc tm of
SOME t => HOLogic.Suc_zero :: dest_sum t
| NONE =>
(case try dest_plus tm of
SOME (t, u) => dest_sum t @ dest_sum u
| NONE => [tm]));
val div_mod_eqs = map mk_meta_eq @{thms cancel_div_mod_rules};
val prove_eq_sums = Arith_Data.prove_conv2 all_tac
(Arith_Data.simp_all_tac @{thms add_0_left add_0_right ac_simps})
)
\<close>
simproc_setup cancel_div_mod_nat ("(m::nat) + n") =
\<open>K Cancel_Div_Mod_Nat.proc\<close>
lemma div_mult_self_is_m [simp]:
"m * n div n = m" if "n > 0" for m n :: nat
using that by simp
lemma div_mult_self1_is_m [simp]:
"n * m div n = m" if "n > 0" for m n :: nat
using that by simp
lemma mod_less_divisor [simp]:
"m mod n < n" if "n > 0" for m n :: nat
using mod_size_less [of n m] that by simp
lemma mod_le_divisor [simp]:
"m mod n \<le> n" if "n > 0" for m n :: nat
using that by (auto simp add: le_less)
lemma div_times_less_eq_dividend [simp]:
"m div n * n \<le> m" for m n :: nat
by (simp add: minus_mod_eq_div_mult [symmetric])
lemma times_div_less_eq_dividend [simp]:
"n * (m div n) \<le> m" for m n :: nat
using div_times_less_eq_dividend [of m n]
by (simp add: ac_simps)
lemma dividend_less_div_times:
"m < n + (m div n) * n" if "0 < n" for m n :: nat
proof -
from that have "m mod n < n"
by simp
then show ?thesis
by (simp add: minus_mod_eq_div_mult [symmetric])
qed
lemma dividend_less_times_div:
"m < n + n * (m div n)" if "0 < n" for m n :: nat
using dividend_less_div_times [of n m] that
by (simp add: ac_simps)
lemma mod_Suc_le_divisor [simp]:
"m mod Suc n \<le> n"
using mod_less_divisor [of "Suc n" m] by arith
lemma mod_less_eq_dividend [simp]:
"m mod n \<le> m" for m n :: nat
proof (rule add_leD2)
from div_mult_mod_eq have "m div n * n + m mod n = m" .
then show "m div n * n + m mod n \<le> m" by auto
qed
lemma
div_less [simp]: "m div n = 0"
and mod_less [simp]: "m mod n = m"
if "m < n" for m n :: nat
using that by (auto intro: div_nat_eqI mod_nat_eqI)
lemma split_div:
\<open>P (m div n) \<longleftrightarrow>
(n = 0 \<longrightarrow> P 0) \<and>
(n \<noteq> 0 \<longrightarrow> (\<forall>i j. j < n \<and> m = n * i + j \<longrightarrow> P i))\<close> (is ?div)
and split_mod:
\<open>Q (m mod n) \<longleftrightarrow>
(n = 0 \<longrightarrow> Q m) \<and>
(n \<noteq> 0 \<longrightarrow> (\<forall>i j. j < n \<and> m = n * i + j \<longrightarrow> Q j))\<close> (is ?mod)
for m n :: nat
proof -
have *: \<open>R (m div n) (m mod n) \<longleftrightarrow>
(n = 0 \<longrightarrow> R 0 m) \<and>
(n \<noteq> 0 \<longrightarrow> (\<forall>i j. j < n \<and> m = n * i + j \<longrightarrow> R i j))\<close> for R
by (cases \<open>n = 0\<close>) auto
from * [of \<open>\<lambda>q _. P q\<close>] show ?div .
from * [of \<open>\<lambda>_ r. Q r\<close>] show ?mod .
qed
declare split_div [of _ _ \<open>numeral n\<close>, linarith_split] for n
declare split_mod [of _ _ \<open>numeral n\<close>, linarith_split] for n
lemma split_div':
"P (m div n) \<longleftrightarrow> n = 0 \<and> P 0 \<or> (\<exists>q. (n * q \<le> m \<and> m < n * Suc q) \<and> P q)"
proof (cases "n = 0")
case True
then show ?thesis
by simp
next
case False
then have "n * q \<le> m \<and> m < n * Suc q \<longleftrightarrow> m div n = q" for q
by (auto intro: div_nat_eqI dividend_less_times_div)
then show ?thesis
by auto
qed
lemma le_div_geq:
"m div n = Suc ((m - n) div n)" if "0 < n" and "n \<le> m" for m n :: nat
proof -
from \<open>n \<le> m\<close> obtain q where "m = n + q"
by (auto simp add: le_iff_add)
with \<open>0 < n\<close> show ?thesis
by (simp add: div_add_self1)
qed
lemma le_mod_geq:
"m mod n = (m - n) mod n" if "n \<le> m" for m n :: nat
proof -
from \<open>n \<le> m\<close> obtain q where "m = n + q"
by (auto simp add: le_iff_add)
then show ?thesis
by simp
qed
lemma div_if:
"m div n = (if m < n \<or> n = 0 then 0 else Suc ((m - n) div n))"
by (simp add: le_div_geq)
lemma mod_if:
"m mod n = (if m < n then m else (m - n) mod n)" for m n :: nat
by (simp add: le_mod_geq)
lemma div_eq_0_iff:
"m div n = 0 \<longleftrightarrow> m < n \<or> n = 0" for m n :: nat
by (simp add: div_eq_0_iff)
lemma div_greater_zero_iff:
"m div n > 0 \<longleftrightarrow> n \<le> m \<and> n > 0" for m n :: nat
using div_eq_0_iff [of m n] by auto
lemma mod_greater_zero_iff_not_dvd:
"m mod n > 0 \<longleftrightarrow> \<not> n dvd m" for m n :: nat
by (simp add: dvd_eq_mod_eq_0)
lemma div_by_Suc_0 [simp]:
"m div Suc 0 = m"
using div_by_1 [of m] by simp
lemma mod_by_Suc_0 [simp]:
"m mod Suc 0 = 0"
using mod_by_1 [of m] by simp
lemma div2_Suc_Suc [simp]:
"Suc (Suc m) div 2 = Suc (m div 2)"
by (simp add: numeral_2_eq_2 le_div_geq)
lemma Suc_n_div_2_gt_zero [simp]:
"0 < Suc n div 2" if "n > 0" for n :: nat
using that by (cases n) simp_all
lemma div_2_gt_zero [simp]:
"0 < n div 2" if "Suc 0 < n" for n :: nat
using that Suc_n_div_2_gt_zero [of "n - 1"] by simp
lemma mod2_Suc_Suc [simp]:
"Suc (Suc m) mod 2 = m mod 2"
by (simp add: numeral_2_eq_2 le_mod_geq)
lemma add_self_div_2 [simp]:
"(m + m) div 2 = m" for m :: nat
by (simp add: mult_2 [symmetric])
lemma add_self_mod_2 [simp]:
"(m + m) mod 2 = 0" for m :: nat
by (simp add: mult_2 [symmetric])
lemma mod2_gr_0 [simp]:
"0 < m mod 2 \<longleftrightarrow> m mod 2 = 1" for m :: nat
proof -
have "m mod 2 < 2"
by (rule mod_less_divisor) simp
then have "m mod 2 = 0 \<or> m mod 2 = 1"
by arith
then show ?thesis
by auto
qed
lemma mod_Suc_eq [mod_simps]:
"Suc (m mod n) mod n = Suc m mod n"
proof -
have "(m mod n + 1) mod n = (m + 1) mod n"
by (simp only: mod_simps)
then show ?thesis
by simp
qed
lemma mod_Suc_Suc_eq [mod_simps]:
"Suc (Suc (m mod n)) mod n = Suc (Suc m) mod n"
proof -
have "(m mod n + 2) mod n = (m + 2) mod n"
by (simp only: mod_simps)
then show ?thesis
by simp
qed
lemma
Suc_mod_mult_self1 [simp]: "Suc (m + k * n) mod n = Suc m mod n"
and Suc_mod_mult_self2 [simp]: "Suc (m + n * k) mod n = Suc m mod n"
and Suc_mod_mult_self3 [simp]: "Suc (k * n + m) mod n = Suc m mod n"
and Suc_mod_mult_self4 [simp]: "Suc (n * k + m) mod n = Suc m mod n"
by (subst mod_Suc_eq [symmetric], simp add: mod_simps)+
lemma Suc_0_mod_eq [simp]:
"Suc 0 mod n = of_bool (n \<noteq> Suc 0)"
by (cases n) simp_all
lemma div_mult2_eq:
\<open>m div (n * q) = (m div n) div q\<close> (is ?Q)
and mod_mult2_eq:
\<open>m mod (n * q) = n * (m div n mod q) + m mod n\<close> (is ?R)
for m n q :: nat
proof -
have \<open>(m div (n * q), m mod (n * q)) = ((m div n) div q, n * (m div n mod q) + m mod n)\<close>
proof (cases \<open>n * q\<close> \<open>(m div n) div q\<close> \<open>n * (m div n mod q) + m mod n\<close> m rule: euclidean_relation_natI)
case by0
then show ?case
by auto
next
case divides
from \<open>n * q dvd m\<close> obtain t where \<open>m = n * q * t\<close> ..
with \<open>n * q > 0\<close> show ?case
by (simp add: algebra_simps)
next
case euclidean_relation
then have \<open>n > 0\<close> \<open>q > 0\<close>
by simp_all
from \<open>n > 0\<close> have \<open>m mod n < n\<close>
by (rule mod_less_divisor)
from \<open>q > 0\<close> have \<open>m div n mod q < q\<close>
by (rule mod_less_divisor)
then obtain s where \<open>q = Suc (m div n mod q + s)\<close>
by (blast dest: less_imp_Suc_add)
moreover have \<open>m mod n + n * (m div n mod q) < n * Suc (m div n mod q + s)\<close>
using \<open>m mod n < n\<close> by (simp add: add_mult_distrib2)
ultimately have \<open>m mod n + n * (m div n mod q) < n * q\<close>
by simp
then show ?case
by (simp add: algebra_simps flip: add_mult_distrib2)
qed
then show ?Q and ?R
by simp_all
qed
lemma div_le_mono:
"m div k \<le> n div k" if "m \<le> n" for m n k :: nat
proof -
from that obtain q where "n = m + q"
by (auto simp add: le_iff_add)
then show ?thesis
by (simp add: div_add1_eq [of m q k])
qed
text \<open>Antimonotonicity of \<^const>\<open>divide\<close> in second argument\<close>
lemma div_le_mono2:
"k div n \<le> k div m" if "0 < m" and "m \<le> n" for m n k :: nat
using that proof (induct k arbitrary: m rule: less_induct)
case (less k)
show ?case
proof (cases "n \<le> k")
case False
then show ?thesis
by simp
next
case True
have "(k - n) div n \<le> (k - m) div n"
using less.prems
by (blast intro: div_le_mono diff_le_mono2)
also have "\<dots> \<le> (k - m) div m"
using \<open>n \<le> k\<close> less.prems less.hyps [of "k - m" m]
by simp
finally show ?thesis
using \<open>n \<le> k\<close> less.prems
by (simp add: le_div_geq)
qed
qed
lemma div_le_dividend [simp]:
"m div n \<le> m" for m n :: nat
using div_le_mono2 [of 1 n m] by (cases "n = 0") simp_all
lemma div_less_dividend [simp]:
"m div n < m" if "1 < n" and "0 < m" for m n :: nat
using that proof (induct m rule: less_induct)
case (less m)
show ?case
proof (cases "n < m")
case False
with less show ?thesis
by (cases "n = m") simp_all
next
case True
then show ?thesis
using less.hyps [of "m - n"] less.prems
by (simp add: le_div_geq)
qed
qed
lemma div_eq_dividend_iff:
"m div n = m \<longleftrightarrow> n = 1" if "m > 0" for m n :: nat
proof
assume "n = 1"
then show "m div n = m"
by simp
next
assume P: "m div n = m"
show "n = 1"
proof (rule ccontr)
have "n \<noteq> 0"
by (rule ccontr) (use that P in auto)
moreover assume "n \<noteq> 1"
ultimately have "n > 1"
by simp
with that have "m div n < m"
by simp
with P show False
by simp
qed
qed
lemma less_mult_imp_div_less:
"m div n < i" if "m < i * n" for m n i :: nat
proof -
from that have "i * n > 0"
by (cases "i * n = 0") simp_all
then have "i > 0" and "n > 0"
by simp_all
have "m div n * n \<le> m"
by simp
then have "m div n * n < i * n"
using that by (rule le_less_trans)
with \<open>n > 0\<close> show ?thesis
by simp
qed
lemma div_less_iff_less_mult:
\<open>m div q < n \<longleftrightarrow> m < n * q\<close> (is \<open>?P \<longleftrightarrow> ?Q\<close>)
if \<open>q > 0\<close> for m n q :: nat
proof
assume ?Q then show ?P
by (rule less_mult_imp_div_less)
next
assume ?P
then obtain h where \<open>n = Suc (m div q + h)\<close>
using less_natE by blast
moreover have \<open>m < m + (Suc h * q - m mod q)\<close>
using that by (simp add: trans_less_add1)
ultimately show ?Q
by (simp add: algebra_simps flip: minus_mod_eq_mult_div)
qed
lemma less_eq_div_iff_mult_less_eq:
\<open>m \<le> n div q \<longleftrightarrow> m * q \<le> n\<close> if \<open>q > 0\<close> for m n q :: nat
using div_less_iff_less_mult [of q n m] that by auto
lemma div_Suc:
\<open>Suc m div n = (if Suc m mod n = 0 then Suc (m div n) else m div n)\<close> (is "_ = ?rhs")
proof (cases \<open>n = 0 \<or> n = 1\<close>)
case True
then show ?thesis by auto
next
case False
then have \<open>n > 1\<close>
by simp
then have *: \<open>Suc 0 div n = 0\<close>
by (simp add: div_eq_0_iff)
have \<open>(m + 1) div n = ?rhs\<close>
proof (cases \<open>n dvd Suc m\<close>)
case True
then obtain q where \<open>Suc m = n * q\<close> ..
then have m: \<open>m = n * q - 1\<close>
by simp
have \<open>q > 0\<close> by (rule ccontr)
(use \<open>Suc m = n * q\<close> in simp)
from m have \<open>m mod n = (n * q - 1) mod n\<close>
by simp
also have \<open>\<dots> = (n * q - 1 + n) mod n\<close>
by simp
also have \<open>n * q - 1 + n = n * q + (n - 1)\<close>
using \<open>n > 1\<close> \<open>q > 0\<close> by (simp add: algebra_simps)
finally have \<open>m mod n = (n - 1) mod n\<close>
by simp
with \<open>n > 1\<close> have \<open>m mod n = n - 1\<close>
by simp
with True \<open>n > 1\<close> show ?thesis
by (subst div_add1_eq) auto
next
case False
have \<open>Suc (m mod n) \<noteq> n\<close>
proof (rule ccontr)
assume \<open>\<not> Suc (m mod n) \<noteq> n\<close>
then have \<open>m mod n = n - 1\<close>
by simp
with \<open>n > 1\<close> have \<open>(m + 1) mod n = 0\<close>
by (subst mod_add_left_eq [symmetric]) simp
then have \<open>n dvd Suc m\<close>
by auto
with False show False ..
qed
moreover have \<open>Suc (m mod n) \<le> n\<close>
using \<open>n > 1\<close> by (simp add: Suc_le_eq)
ultimately have \<open>Suc (m mod n) < n\<close>
by simp
with False \<open>n > 1\<close> show ?thesis
by (subst div_add1_eq) (auto simp add: div_eq_0_iff mod_greater_zero_iff_not_dvd)
qed
then show ?thesis
by simp
qed
lemma mod_Suc:
\<open>Suc m mod n = (if Suc (m mod n) = n then 0 else Suc (m mod n))\<close> (is "_ = ?rhs")
proof (cases "n = 0")
case True
then show ?thesis
by simp
next
case False
have "Suc m mod n = Suc (m mod n) mod n"
by (simp add: mod_simps)
also have "\<dots> = ?rhs"
using False by (auto intro!: mod_nat_eqI intro: neq_le_trans simp add: Suc_le_eq)
finally show ?thesis .
qed
lemma Suc_times_mod_eq:
"Suc (m * n) mod m = 1" if "Suc 0 < m"
using that by (simp add: mod_Suc)
lemma Suc_times_numeral_mod_eq [simp]:
"Suc (numeral k * n) mod numeral k = 1" if "numeral k \<noteq> (1::nat)"
by (rule Suc_times_mod_eq) (use that in simp)
lemma Suc_div_le_mono [simp]:
"m div n \<le> Suc m div n"
by (simp add: div_le_mono)
text \<open>These lemmas collapse some needless occurrences of Suc:
at least three Sucs, since two and fewer are rewritten back to Suc again!
We already have some rules to simplify operands smaller than 3.\<close>
lemma div_Suc_eq_div_add3 [simp]:
"m div Suc (Suc (Suc n)) = m div (3 + n)"
by (simp add: Suc3_eq_add_3)
lemma mod_Suc_eq_mod_add3 [simp]:
"m mod Suc (Suc (Suc n)) = m mod (3 + n)"
by (simp add: Suc3_eq_add_3)
lemma Suc_div_eq_add3_div:
"Suc (Suc (Suc m)) div n = (3 + m) div n"
by (simp add: Suc3_eq_add_3)
lemma Suc_mod_eq_add3_mod:
"Suc (Suc (Suc m)) mod n = (3 + m) mod n"
by (simp add: Suc3_eq_add_3)
lemmas Suc_div_eq_add3_div_numeral [simp] =
Suc_div_eq_add3_div [of _ "numeral v"] for v
lemmas Suc_mod_eq_add3_mod_numeral [simp] =
Suc_mod_eq_add3_mod [of _ "numeral v"] for v
lemma (in field_char_0) of_nat_div:
"of_nat (m div n) = ((of_nat m - of_nat (m mod n)) / of_nat n)"
proof -
have "of_nat (m div n) = ((of_nat (m div n * n + m mod n) - of_nat (m mod n)) / of_nat n :: 'a)"
unfolding of_nat_add by (cases "n = 0") simp_all
then show ?thesis
by simp
qed
text \<open>An ``induction'' law for modulus arithmetic.\<close>
lemma mod_induct [consumes 3, case_names step]:
"P m" if "P n" and "n < p" and "m < p"
and step: "\<And>n. n < p \<Longrightarrow> P n \<Longrightarrow> P (Suc n mod p)"
using \<open>m < p\<close> proof (induct m)
case 0
show ?case
proof (rule ccontr)
assume "\<not> P 0"
from \<open>n < p\<close> have "0 < p"
by simp
from \<open>n < p\<close> obtain m where "0 < m" and "p = n + m"
by (blast dest: less_imp_add_positive)
with \<open>P n\<close> have "P (p - m)"
by simp
moreover have "\<not> P (p - m)"
using \<open>0 < m\<close> proof (induct m)
case 0
then show ?case
by simp
next
case (Suc m)
show ?case
proof
assume P: "P (p - Suc m)"
with \<open>\<not> P 0\<close> have "Suc m < p"
by (auto intro: ccontr)
then have "Suc (p - Suc m) = p - m"
by arith
moreover from \<open>0 < p\<close> have "p - Suc m < p"
by arith
with P step have "P ((Suc (p - Suc m)) mod p)"
by blast
ultimately show False
using \<open>\<not> P 0\<close> Suc.hyps by (cases "m = 0") simp_all
qed
qed
ultimately show False
by blast
qed
next
case (Suc m)
then have "m < p" and mod: "Suc m mod p = Suc m"
by simp_all
from \<open>m < p\<close> have "P m"
by (rule Suc.hyps)
with \<open>m < p\<close> have "P (Suc m mod p)"
by (rule step)
with mod show ?case
by simp
qed
lemma funpow_mod_eq: \<^marker>\<open>contributor \<open>Lars Noschinski\<close>\<close>
\<open>(f ^^ (m mod n)) x = (f ^^ m) x\<close> if \<open>(f ^^ n) x = x\<close>
proof -
have \<open>(f ^^ m) x = (f ^^ (m mod n + m div n * n)) x\<close>
by simp
also have \<open>\<dots> = (f ^^ (m mod n)) (((f ^^ n) ^^ (m div n)) x)\<close>
by (simp only: funpow_add funpow_mult ac_simps) simp
also have \<open>((f ^^ n) ^^ q) x = x\<close> for q
by (induction q) (use \<open>(f ^^ n) x = x\<close> in simp_all)
finally show ?thesis
by simp
qed
lemma mod_eq_dvd_iff_nat:
\<open>m mod q = n mod q \<longleftrightarrow> q dvd m - n\<close> (is \<open>?P \<longleftrightarrow> ?Q\<close>)
if \<open>m \<ge> n\<close> for m n q :: nat
proof
assume ?Q
then obtain s where \<open>m - n = q * s\<close> ..
with that have \<open>m = q * s + n\<close>
by simp
then show ?P
by simp
next
assume ?P
have \<open>m - n = m div q * q + m mod q - (n div q * q + n mod q)\<close>
by simp
also have \<open>\<dots> = q * (m div q - n div q)\<close>
by (simp only: algebra_simps \<open>?P\<close>)
finally show ?Q ..
qed
lemma mod_eq_iff_dvd_symdiff_nat:
\<open>m mod q = n mod q \<longleftrightarrow> q dvd nat \<bar>int m - int n\<bar>\<close>
by (auto simp add: abs_if mod_eq_dvd_iff_nat nat_diff_distrib dest: sym intro: sym)
lemma mod_eq_nat1E:
fixes m n q :: nat
assumes "m mod q = n mod q" and "m \<ge> n"
obtains s where "m = n + q * s"
proof -
from assms have "q dvd m - n"
by (simp add: mod_eq_dvd_iff_nat)
then obtain s where "m - n = q * s" ..
with \<open>m \<ge> n\<close> have "m = n + q * s"
by simp
with that show thesis .
qed
lemma mod_eq_nat2E:
fixes m n q :: nat
assumes "m mod q = n mod q" and "n \<ge> m"
obtains s where "n = m + q * s"
using assms mod_eq_nat1E [of n q m] by (auto simp add: ac_simps)
lemma nat_mod_eq_iff:
"(x::nat) mod n = y mod n \<longleftrightarrow> (\<exists>q1 q2. x + n * q1 = y + n * q2)" (is "?lhs = ?rhs")
proof
assume H: "x mod n = y mod n"
{ assume xy: "x \<le> y"
from H have th: "y mod n = x mod n" by simp
from mod_eq_nat1E [OF th xy] obtain q where "y = x + n * q" .
then have "x + n * q = y + n * 0"
by simp
then have "\<exists>q1 q2. x + n * q1 = y + n * q2"
by blast
}
moreover
{ assume xy: "y \<le> x"
from mod_eq_nat1E [OF H xy] obtain q where "x = y + n * q" .
then have "x + n * 0 = y + n * q"
by simp
then have "\<exists>q1 q2. x + n * q1 = y + n * q2"
by blast
}
ultimately show ?rhs using linear[of x y] by blast
next
assume ?rhs then obtain q1 q2 where q12: "x + n * q1 = y + n * q2" by blast
hence "(x + n * q1) mod n = (y + n * q2) mod n" by simp
thus ?lhs by simp
qed
subsection \<open>Elementary euclidean division on \<^typ>\<open>int\<close>\<close>
subsubsection \<open>Basic instantiation\<close>
instantiation int :: "{normalization_semidom, idom_modulo}"
begin
definition normalize_int :: \<open>int \<Rightarrow> int\<close>
where [simp]: \<open>normalize = (abs :: int \<Rightarrow> int)\<close>
definition unit_factor_int :: \<open>int \<Rightarrow> int\<close>
where [simp]: \<open>unit_factor = (sgn :: int \<Rightarrow> int)\<close>
definition divide_int :: \<open>int \<Rightarrow> int \<Rightarrow> int\<close>
where \<open>k div l = (sgn k * sgn l * int (nat \<bar>k\<bar> div nat \<bar>l\<bar>)
- of_bool (l \<noteq> 0 \<and> sgn k \<noteq> sgn l \<and> \<not> l dvd k))\<close>
lemma divide_int_unfold:
\<open>(sgn k * int m) div (sgn l * int n) = (sgn k * sgn l * int (m div n)
- of_bool ((k = 0 \<longleftrightarrow> m = 0) \<and> l \<noteq> 0 \<and> n \<noteq> 0 \<and> sgn k \<noteq> sgn l \<and> \<not> n dvd m))\<close>
by (simp add: divide_int_def sgn_mult nat_mult_distrib abs_mult sgn_eq_0_iff ac_simps)
definition modulo_int :: \<open>int \<Rightarrow> int \<Rightarrow> int\<close>
where \<open>k mod l = sgn k * int (nat \<bar>k\<bar> mod nat \<bar>l\<bar>) + l * of_bool (sgn k \<noteq> sgn l \<and> \<not> l dvd k)\<close>
lemma modulo_int_unfold:
\<open>(sgn k * int m) mod (sgn l * int n) =
sgn k * int (m mod (of_bool (l \<noteq> 0) * n)) + (sgn l * int n) * of_bool ((k = 0 \<longleftrightarrow> m = 0) \<and> sgn k \<noteq> sgn l \<and> \<not> n dvd m)\<close>
by (auto simp add: modulo_int_def sgn_mult abs_mult)
instance proof
fix k :: int show "k div 0 = 0"
by (simp add: divide_int_def)
next
fix k l :: int
assume "l \<noteq> 0"
obtain n m and s t where k: "k = sgn s * int n" and l: "l = sgn t * int m"
by (blast intro: int_sgnE elim: that)
then have "k * l = sgn (s * t) * int (n * m)"
by (simp add: ac_simps sgn_mult)
with k l \<open>l \<noteq> 0\<close> show "k * l div l = k"
by (simp only: divide_int_unfold)
(auto simp add: algebra_simps sgn_mult sgn_1_pos sgn_0_0)
next
fix k l :: int
obtain n m and s t where "k = sgn s * int n" and "l = sgn t * int m"
by (blast intro: int_sgnE elim: that)
then show "k div l * l + k mod l = k"
by (simp add: divide_int_unfold modulo_int_unfold algebra_simps modulo_nat_def of_nat_diff)
qed (auto simp add: sgn_mult mult_sgn_abs abs_eq_iff')
end
subsubsection \<open>Algebraic foundations\<close>
lemma coprime_int_iff [simp]:
"coprime (int m) (int n) \<longleftrightarrow> coprime m n" (is "?P \<longleftrightarrow> ?Q")
proof
assume ?P
show ?Q
proof (rule coprimeI)
fix q
assume "q dvd m" "q dvd n"
then have "int q dvd int m" "int q dvd int n"
by simp_all
with \<open>?P\<close> have "is_unit (int q)"
by (rule coprime_common_divisor)
then show "is_unit q"
by simp
qed
next
assume ?Q
show ?P
proof (rule coprimeI)
fix k
assume "k dvd int m" "k dvd int n"
then have "nat \<bar>k\<bar> dvd m" "nat \<bar>k\<bar> dvd n"
by simp_all
with \<open>?Q\<close> have "is_unit (nat \<bar>k\<bar>)"
by (rule coprime_common_divisor)
then show "is_unit k"
by simp
qed
qed
lemma coprime_abs_left_iff [simp]:
"coprime \<bar>k\<bar> l \<longleftrightarrow> coprime k l" for k l :: int
using coprime_normalize_left_iff [of k l] by simp
lemma coprime_abs_right_iff [simp]:
"coprime k \<bar>l\<bar> \<longleftrightarrow> coprime k l" for k l :: int
using coprime_abs_left_iff [of l k] by (simp add: ac_simps)
lemma coprime_nat_abs_left_iff [simp]:
"coprime (nat \<bar>k\<bar>) n \<longleftrightarrow> coprime k (int n)"
proof -
define m where "m = nat \<bar>k\<bar>"
then have "\<bar>k\<bar> = int m"
by simp
moreover have "coprime k (int n) \<longleftrightarrow> coprime \<bar>k\<bar> (int n)"
by simp
ultimately show ?thesis
by simp
qed
lemma coprime_nat_abs_right_iff [simp]:
"coprime n (nat \<bar>k\<bar>) \<longleftrightarrow> coprime (int n) k"
using coprime_nat_abs_left_iff [of k n] by (simp add: ac_simps)
lemma coprime_common_divisor_int: "coprime a b \<Longrightarrow> x dvd a \<Longrightarrow> x dvd b \<Longrightarrow> \<bar>x\<bar> = 1"
for a b :: int
by (drule coprime_common_divisor [of _ _ x]) simp_all
subsubsection \<open>Basic conversions\<close>
lemma div_abs_eq_div_nat:
"\<bar>k\<bar> div \<bar>l\<bar> = int (nat \<bar>k\<bar> div nat \<bar>l\<bar>)"
by (auto simp add: divide_int_def)
lemma div_eq_div_abs:
\<open>k div l = sgn k * sgn l * (\<bar>k\<bar> div \<bar>l\<bar>)
- of_bool (l \<noteq> 0 \<and> sgn k \<noteq> sgn l \<and> \<not> l dvd k)\<close>
for k l :: int
by (simp add: divide_int_def [of k l] div_abs_eq_div_nat)
lemma div_abs_eq:
\<open>\<bar>k\<bar> div \<bar>l\<bar> = sgn k * sgn l * (k div l + of_bool (sgn k \<noteq> sgn l \<and> \<not> l dvd k))\<close>
for k l :: int
by (simp add: div_eq_div_abs [of k l] ac_simps)
lemma mod_abs_eq_div_nat:
"\<bar>k\<bar> mod \<bar>l\<bar> = int (nat \<bar>k\<bar> mod nat \<bar>l\<bar>)"
by (simp add: modulo_int_def)
lemma mod_eq_mod_abs:
\<open>k mod l = sgn k * (\<bar>k\<bar> mod \<bar>l\<bar>) + l * of_bool (sgn k \<noteq> sgn l \<and> \<not> l dvd k)\<close>
for k l :: int
by (simp add: modulo_int_def [of k l] mod_abs_eq_div_nat)
lemma mod_abs_eq:
\<open>\<bar>k\<bar> mod \<bar>l\<bar> = sgn k * (k mod l - l * of_bool (sgn k \<noteq> sgn l \<and> \<not> l dvd k))\<close>
for k l :: int
by (auto simp: mod_eq_mod_abs [of k l])
lemma div_sgn_abs_cancel:
fixes k l v :: int
assumes "v \<noteq> 0"
shows "(sgn v * \<bar>k\<bar>) div (sgn v * \<bar>l\<bar>) = \<bar>k\<bar> div \<bar>l\<bar>"
using assms by (simp add: sgn_mult abs_mult sgn_0_0
divide_int_def [of "sgn v * \<bar>k\<bar>" "sgn v * \<bar>l\<bar>"] flip: div_abs_eq_div_nat)
lemma div_eq_sgn_abs:
fixes k l v :: int
assumes "sgn k = sgn l"
shows "k div l = \<bar>k\<bar> div \<bar>l\<bar>"
using assms by (auto simp add: div_abs_eq)
lemma div_dvd_sgn_abs:
fixes k l :: int
assumes "l dvd k"
shows "k div l = (sgn k * sgn l) * (\<bar>k\<bar> div \<bar>l\<bar>)"
using assms by (auto simp add: div_abs_eq ac_simps)
lemma div_noneq_sgn_abs:
fixes k l :: int
assumes "l \<noteq> 0"
assumes "sgn k \<noteq> sgn l"
shows "k div l = - (\<bar>k\<bar> div \<bar>l\<bar>) - of_bool (\<not> l dvd k)"
using assms by (auto simp add: div_abs_eq ac_simps sgn_0_0 dest!: sgn_not_eq_imp)
subsubsection \<open>Euclidean division\<close>
instantiation int :: unique_euclidean_ring
begin
definition euclidean_size_int :: "int \<Rightarrow> nat"
where [simp]: "euclidean_size_int = (nat \<circ> abs :: int \<Rightarrow> nat)"
definition division_segment_int :: "int \<Rightarrow> int"
where "division_segment_int k = (if k \<ge> 0 then 1 else - 1)"
lemma division_segment_eq_sgn:
"division_segment k = sgn k" if "k \<noteq> 0" for k :: int
using that by (simp add: division_segment_int_def)
lemma abs_division_segment [simp]:
"\<bar>division_segment k\<bar> = 1" for k :: int
by (simp add: division_segment_int_def)
lemma abs_mod_less:
"\<bar>k mod l\<bar> < \<bar>l\<bar>" if "l \<noteq> 0" for k l :: int
proof -
obtain n m and s t where "k = sgn s * int n" and "l = sgn t * int m"
by (blast intro: int_sgnE elim: that)
with that show ?thesis
by (auto simp add: modulo_int_unfold abs_mult mod_greater_zero_iff_not_dvd
simp flip: right_diff_distrib dest!: sgn_not_eq_imp)
(simp add: sgn_0_0)
qed
lemma sgn_mod:
"sgn (k mod l) = sgn l" if "l \<noteq> 0" "\<not> l dvd k" for k l :: int
proof -
obtain n m and s t where "k = sgn s * int n" and "l = sgn t * int m"
by (blast intro: int_sgnE elim: that)
with that show ?thesis
by (auto simp add: modulo_int_unfold sgn_mult mod_greater_zero_iff_not_dvd
simp flip: right_diff_distrib dest!: sgn_not_eq_imp)
qed
instance proof
fix k l :: int
show "division_segment (k mod l) = division_segment l" if
"l \<noteq> 0" and "\<not> l dvd k"
using that by (simp add: division_segment_eq_sgn dvd_eq_mod_eq_0 sgn_mod)
next
fix l q r :: int
obtain n m and s t
where l: "l = sgn s * int n" and q: "q = sgn t * int m"
by (blast intro: int_sgnE elim: that)
assume \<open>l \<noteq> 0\<close>
with l have "s \<noteq> 0" and "n > 0"
by (simp_all add: sgn_0_0)
assume "division_segment r = division_segment l"
moreover have "r = sgn r * \<bar>r\<bar>"
by (simp add: sgn_mult_abs)
moreover define u where "u = nat \<bar>r\<bar>"
ultimately have "r = sgn l * int u"
using division_segment_eq_sgn \<open>l \<noteq> 0\<close> by (cases "r = 0") simp_all
with l \<open>n > 0\<close> have r: "r = sgn s * int u"
by (simp add: sgn_mult)
assume "euclidean_size r < euclidean_size l"
with l r \<open>s \<noteq> 0\<close> have "u < n"
by (simp add: abs_mult)
show "(q * l + r) div l = q"
proof (cases "q = 0 \<or> r = 0")
case True
then show ?thesis
proof
assume "q = 0"
then show ?thesis
using l r \<open>u < n\<close> by (simp add: divide_int_unfold)
next
assume "r = 0"
from \<open>r = 0\<close> have *: "q * l + r = sgn (t * s) * int (n * m)"
using q l by (simp add: ac_simps sgn_mult)
from \<open>s \<noteq> 0\<close> \<open>n > 0\<close> show ?thesis
by (simp only: *, simp only: * q l divide_int_unfold)
(auto simp add: sgn_mult ac_simps)
qed
next
case False
with q r have "t \<noteq> 0" and "m > 0" and "s \<noteq> 0" and "u > 0"
by (simp_all add: sgn_0_0)
moreover from \<open>0 < m\<close> \<open>u < n\<close> have "u \<le> m * n"
using mult_le_less_imp_less [of 1 m u n] by simp
ultimately have *: "q * l + r = sgn (s * t)
* int (if t < 0 then m * n - u else m * n + u)"
using l q r
by (simp add: sgn_mult algebra_simps of_nat_diff)
have "(m * n - u) div n = m - 1" if "u > 0"
using \<open>0 < m\<close> \<open>u < n\<close> that
by (auto intro: div_nat_eqI simp add: algebra_simps)
moreover have "n dvd m * n - u \<longleftrightarrow> n dvd u"
using \<open>u \<le> m * n\<close> dvd_diffD1 [of n "m * n" u]
by auto
ultimately show ?thesis
using \<open>s \<noteq> 0\<close> \<open>m > 0\<close> \<open>u > 0\<close> \<open>u < n\<close> \<open>u \<le> m * n\<close>
by (simp only: *, simp only: l q divide_int_unfold)
(auto simp add: sgn_mult sgn_0_0 sgn_1_pos algebra_simps dest: dvd_imp_le)
qed
qed (use mult_le_mono2 [of 1] in \<open>auto simp add: division_segment_int_def not_le zero_less_mult_iff mult_less_0_iff abs_mult sgn_mult abs_mod_less sgn_mod nat_mult_distrib\<close>)
end
lemma euclidean_relation_intI [case_names by0 divides euclidean_relation]:
\<open>(k div l, k mod l) = (q, r)\<close>
if by0': \<open>l = 0 \<Longrightarrow> q = 0 \<and> r = k\<close>
and divides': \<open>l \<noteq> 0 \<Longrightarrow> l dvd k \<Longrightarrow> r = 0 \<and> k = q * l\<close>
and euclidean_relation': \<open>l \<noteq> 0 \<Longrightarrow> \<not> l dvd k \<Longrightarrow> sgn r = sgn l
\<and> \<bar>r\<bar> < \<bar>l\<bar> \<and> k = q * l + r\<close> for k l :: int
proof (cases l q r k rule: euclidean_relationI)
case by0
then show ?case
by (rule by0')
next
case divides
then show ?case
by (rule divides')
next
case euclidean_relation
with euclidean_relation' have \<open>sgn r = sgn l\<close> \<open>\<bar>r\<bar> < \<bar>l\<bar>\<close> \<open>k = q * l + r\<close>
by simp_all
from \<open>sgn r = sgn l\<close> \<open>l \<noteq> 0\<close> have \<open>division_segment r = division_segment l\<close>
by (simp add: division_segment_int_def sgn_if split: if_splits)
with \<open>\<bar>r\<bar> < \<bar>l\<bar>\<close> \<open>k = q * l + r\<close>
show ?case
by simp
qed
subsection \<open>Special case: euclidean rings containing the natural numbers\<close>
class unique_euclidean_semiring_with_nat = semidom + semiring_char_0 + unique_euclidean_semiring +
assumes of_nat_div: "of_nat (m div n) = of_nat m div of_nat n"
and division_segment_of_nat [simp]: "division_segment (of_nat n) = 1"
and division_segment_euclidean_size [simp]: "division_segment a * of_nat (euclidean_size a) = a"
begin
lemma division_segment_eq_iff:
"a = b" if "division_segment a = division_segment b"
and "euclidean_size a = euclidean_size b"
using that division_segment_euclidean_size [of a] by simp
lemma euclidean_size_of_nat [simp]:
"euclidean_size (of_nat n) = n"
proof -
have "division_segment (of_nat n) * of_nat (euclidean_size (of_nat n)) = of_nat n"
by (fact division_segment_euclidean_size)
then show ?thesis by simp
qed
lemma of_nat_euclidean_size:
"of_nat (euclidean_size a) = a div division_segment a"
proof -
have "of_nat (euclidean_size a) = division_segment a * of_nat (euclidean_size a) div division_segment a"
by (subst nonzero_mult_div_cancel_left) simp_all
also have "\<dots> = a div division_segment a"
by simp
finally show ?thesis .
qed
lemma division_segment_1 [simp]:
"division_segment 1 = 1"
using division_segment_of_nat [of 1] by simp
lemma division_segment_numeral [simp]:
"division_segment (numeral k) = 1"
using division_segment_of_nat [of "numeral k"] by simp
lemma euclidean_size_1 [simp]:
"euclidean_size 1 = 1"
using euclidean_size_of_nat [of 1] by simp
lemma euclidean_size_numeral [simp]:
"euclidean_size (numeral k) = numeral k"
using euclidean_size_of_nat [of "numeral k"] by simp
lemma of_nat_dvd_iff:
"of_nat m dvd of_nat n \<longleftrightarrow> m dvd n" (is "?P \<longleftrightarrow> ?Q")
proof (cases "m = 0")
case True
then show ?thesis
by simp
next
case False
show ?thesis
proof
assume ?Q
then show ?P
by auto
next
assume ?P
with False have "of_nat n = of_nat n div of_nat m * of_nat m"
by simp
then have "of_nat n = of_nat (n div m * m)"
by (simp add: of_nat_div)
then have "n = n div m * m"
by (simp only: of_nat_eq_iff)
then have "n = m * (n div m)"
by (simp add: ac_simps)
then show ?Q ..
qed
qed
lemma of_nat_mod:
"of_nat (m mod n) = of_nat m mod of_nat n"
proof -
have "of_nat m div of_nat n * of_nat n + of_nat m mod of_nat n = of_nat m"
by (simp add: div_mult_mod_eq)
also have "of_nat m = of_nat (m div n * n + m mod n)"
by simp
finally show ?thesis
by (simp only: of_nat_div of_nat_mult of_nat_add) simp
qed
lemma one_div_two_eq_zero [simp]:
"1 div 2 = 0"
proof -
from of_nat_div [symmetric] have "of_nat 1 div of_nat 2 = of_nat 0"
by (simp only:) simp
then show ?thesis
by simp
qed
lemma one_mod_two_eq_one [simp]:
"1 mod 2 = 1"
proof -
from of_nat_mod [symmetric] have "of_nat 1 mod of_nat 2 = of_nat 1"
by (simp only:) simp
then show ?thesis
by simp
qed
lemma one_mod_2_pow_eq [simp]:
"1 mod (2 ^ n) = of_bool (n > 0)"
proof -
have "1 mod (2 ^ n) = of_nat (1 mod (2 ^ n))"
using of_nat_mod [of 1 "2 ^ n"] by simp
also have "\<dots> = of_bool (n > 0)"
by simp
finally show ?thesis .
qed
lemma one_div_2_pow_eq [simp]:
"1 div (2 ^ n) = of_bool (n = 0)"
using div_mult_mod_eq [of 1 "2 ^ n"] by auto
lemma div_mult2_eq':
\<open>a div (of_nat m * of_nat n) = a div of_nat m div of_nat n\<close>
proof (cases \<open>m = 0 \<or> n = 0\<close>)
case True
then show ?thesis
by auto
next
case False
then have \<open>m > 0\<close> \<open>n > 0\<close>
by simp_all
show ?thesis
proof (cases \<open>of_nat m * of_nat n dvd a\<close>)
case True
then obtain b where \<open>a = (of_nat m * of_nat n) * b\<close> ..
then have \<open>a = of_nat m * (of_nat n * b)\<close>
by (simp add: ac_simps)
then show ?thesis
by simp
next
case False
define q where \<open>q = a div (of_nat m * of_nat n)\<close>
define r where \<open>r = a mod (of_nat m * of_nat n)\<close>
from \<open>m > 0\<close> \<open>n > 0\<close> \<open>\<not> of_nat m * of_nat n dvd a\<close> r_def have "division_segment r = 1"
using division_segment_of_nat [of "m * n"] by (simp add: division_segment_mod)
with division_segment_euclidean_size [of r]
have "of_nat (euclidean_size r) = r"
by simp
have "a mod (of_nat m * of_nat n) div (of_nat m * of_nat n) = 0"
by simp
with \<open>m > 0\<close> \<open>n > 0\<close> r_def have "r div (of_nat m * of_nat n) = 0"
by simp
with \<open>of_nat (euclidean_size r) = r\<close>
have "of_nat (euclidean_size r) div (of_nat m * of_nat n) = 0"
by simp
then have "of_nat (euclidean_size r div (m * n)) = 0"
by (simp add: of_nat_div)
then have "of_nat (euclidean_size r div m div n) = 0"
by (simp add: div_mult2_eq)
with \<open>of_nat (euclidean_size r) = r\<close> have "r div of_nat m div of_nat n = 0"
by (simp add: of_nat_div)
with \<open>m > 0\<close> \<open>n > 0\<close> q_def
have "q = (r div of_nat m + q * of_nat n * of_nat m div of_nat m) div of_nat n"
by simp
moreover have \<open>a = q * (of_nat m * of_nat n) + r\<close>
by (simp add: q_def r_def div_mult_mod_eq)
ultimately show \<open>a div (of_nat m * of_nat n) = a div of_nat m div of_nat n\<close>
using q_def [symmetric] div_plus_div_distrib_dvd_right [of \<open>of_nat m\<close> \<open>q * (of_nat m * of_nat n)\<close> r]
by (simp add: ac_simps)
qed
qed
lemma mod_mult2_eq':
"a mod (of_nat m * of_nat n) = of_nat m * (a div of_nat m mod of_nat n) + a mod of_nat m"
proof -
have "a div (of_nat m * of_nat n) * (of_nat m * of_nat n) + a mod (of_nat m * of_nat n) = a div of_nat m div of_nat n * of_nat n * of_nat m + (a div of_nat m mod of_nat n * of_nat m + a mod of_nat m)"
by (simp add: combine_common_factor div_mult_mod_eq)
moreover have "a div of_nat m div of_nat n * of_nat n * of_nat m = of_nat n * of_nat m * (a div of_nat m div of_nat n)"
by (simp add: ac_simps)
ultimately show ?thesis
by (simp add: div_mult2_eq' mult_commute)
qed
lemma div_mult2_numeral_eq:
"a div numeral k div numeral l = a div numeral (k * l)" (is "?A = ?B")
proof -
have "?A = a div of_nat (numeral k) div of_nat (numeral l)"
by simp
also have "\<dots> = a div (of_nat (numeral k) * of_nat (numeral l))"
by (fact div_mult2_eq' [symmetric])
also have "\<dots> = ?B"
by simp
finally show ?thesis .
qed
lemma numeral_Bit0_div_2:
"numeral (num.Bit0 n) div 2 = numeral n"
proof -
have "numeral (num.Bit0 n) = numeral n + numeral n"
by (simp only: numeral.simps)
also have "\<dots> = numeral n * 2"
by (simp add: mult_2_right)
finally have "numeral (num.Bit0 n) div 2 = numeral n * 2 div 2"
by simp
also have "\<dots> = numeral n"
by (rule nonzero_mult_div_cancel_right) simp
finally show ?thesis .
qed
lemma numeral_Bit1_div_2:
"numeral (num.Bit1 n) div 2 = numeral n"
proof -
have "numeral (num.Bit1 n) = numeral n + numeral n + 1"
by (simp only: numeral.simps)
also have "\<dots> = numeral n * 2 + 1"
by (simp add: mult_2_right)
finally have "numeral (num.Bit1 n) div 2 = (numeral n * 2 + 1) div 2"
by simp
also have "\<dots> = numeral n * 2 div 2 + 1 div 2"
using dvd_triv_right by (rule div_plus_div_distrib_dvd_left)
also have "\<dots> = numeral n * 2 div 2"
by simp
also have "\<dots> = numeral n"
by (rule nonzero_mult_div_cancel_right) simp
finally show ?thesis .
qed
lemma exp_mod_exp:
\<open>2 ^ m mod 2 ^ n = of_bool (m < n) * 2 ^ m\<close>
proof -
have \<open>(2::nat) ^ m mod 2 ^ n = of_bool (m < n) * 2 ^ m\<close> (is \<open>?lhs = ?rhs\<close>)
by (auto simp add: not_less monoid_mult_class.power_add dest!: le_Suc_ex)
then have \<open>of_nat ?lhs = of_nat ?rhs\<close>
by simp
then show ?thesis
by (simp add: of_nat_mod)
qed
lemma mask_mod_exp:
\<open>(2 ^ n - 1) mod 2 ^ m = 2 ^ min m n - 1\<close>
proof -
have \<open>(2 ^ n - 1) mod 2 ^ m = 2 ^ min m n - (1::nat)\<close> (is \<open>?lhs = ?rhs\<close>)
proof (cases \<open>n \<le> m\<close>)
case True
then show ?thesis
by (simp add: Suc_le_lessD)
next
case False
then have \<open>m < n\<close>
by simp
then obtain q where n: \<open>n = Suc q + m\<close>
by (auto dest: less_imp_Suc_add)
then have \<open>min m n = m\<close>
by simp
moreover have \<open>(2::nat) ^ m \<le> 2 * 2 ^ q * 2 ^ m\<close>
using mult_le_mono1 [of 1 \<open>2 * 2 ^ q\<close> \<open>2 ^ m\<close>] by simp
with n have \<open>2 ^ n - 1 = (2 ^ Suc q - 1) * 2 ^ m + (2 ^ m - (1::nat))\<close>
by (simp add: monoid_mult_class.power_add algebra_simps)
ultimately show ?thesis
by (simp only: euclidean_semiring_cancel_class.mod_mult_self3) simp
qed
then have \<open>of_nat ?lhs = of_nat ?rhs\<close>
by simp
then show ?thesis
by (simp add: of_nat_mod of_nat_diff)
qed
lemma of_bool_half_eq_0 [simp]:
\<open>of_bool b div 2 = 0\<close>
by simp
end
class unique_euclidean_ring_with_nat = ring + unique_euclidean_semiring_with_nat
instance nat :: unique_euclidean_semiring_with_nat
by standard (simp_all add: dvd_eq_mod_eq_0)
instance int :: unique_euclidean_ring_with_nat
by standard (auto simp add: divide_int_def division_segment_int_def elim: contrapos_np)
subsection \<open>More on euclidean division on \<^typ>\<open>int\<close>\<close>
subsubsection \<open>Trivial reduction steps\<close>
lemma div_pos_pos_trivial [simp]:
"k div l = 0" if "k \<ge> 0" and "k < l" for k l :: int
using that by (simp add: unique_euclidean_semiring_class.div_eq_0_iff division_segment_int_def)
lemma mod_pos_pos_trivial [simp]:
"k mod l = k" if "k \<ge> 0" and "k < l" for k l :: int
using that by (simp add: mod_eq_self_iff_div_eq_0)
lemma div_neg_neg_trivial [simp]:
"k div l = 0" if "k \<le> 0" and "l < k" for k l :: int
using that by (cases "k = 0") (simp, simp add: unique_euclidean_semiring_class.div_eq_0_iff division_segment_int_def)
lemma mod_neg_neg_trivial [simp]:
"k mod l = k" if "k \<le> 0" and "l < k" for k l :: int
using that by (simp add: mod_eq_self_iff_div_eq_0)
lemma
div_pos_neg_trivial: \<open>k div l = - 1\<close> (is ?Q)
and mod_pos_neg_trivial: \<open>k mod l = k + l\<close> (is ?R)
if \<open>0 < k\<close> and \<open>k + l \<le> 0\<close> for k l :: int
proof -
from that have \<open>l < 0\<close>
by simp
have \<open>(k div l, k mod l) = (- 1, k + l)\<close>
proof (cases l \<open>- 1 :: int\<close> \<open>k + l\<close> k rule: euclidean_relation_intI)
case by0
with \<open>l < 0\<close> show ?case
by simp
next
case divides
from \<open>l dvd k\<close> obtain j where \<open>k = l * j\<close> ..
with \<open>l < 0\<close> \<open>0 < k\<close> have \<open>j < 0\<close>
by (simp add: zero_less_mult_iff)
moreover from \<open>k + l \<le> 0\<close> \<open>k = l * j\<close> have \<open>l * (j + 1) \<le> 0\<close>
by (simp add: algebra_simps)
with \<open>l < 0\<close> have \<open>j + 1 \<ge> 0\<close>
by (simp add: mult_le_0_iff)
with \<open>j < 0\<close> have \<open>j = - 1\<close>
by simp
with \<open>k = l * j\<close> show ?case
by simp
next
case euclidean_relation
with \<open>k + l \<le> 0\<close> have \<open>k + l < 0\<close>
by (auto simp add: less_le add_eq_0_iff)
with \<open>0 < k\<close> show ?case
by simp
qed
then show ?Q and ?R
by simp_all
qed
text \<open>There is neither \<open>div_neg_pos_trivial\<close> nor \<open>mod_neg_pos_trivial\<close>
because \<^term>\<open>0 div l = 0\<close> would supersede it.\<close>
subsubsection \<open>More uniqueness rules\<close>
lemma
fixes a b q r :: int
assumes \<open>a = b * q + r\<close> \<open>0 \<le> r\<close> \<open>r < b\<close>
shows int_div_pos_eq:
\<open>a div b = q\<close> (is ?Q)
and int_mod_pos_eq:
\<open>a mod b = r\<close> (is ?R)
proof -
from assms have \<open>(a div b, a mod b) = (q, r)\<close>
by (cases b q r a rule: euclidean_relation_intI)
(auto simp add: ac_simps dvd_add_left_iff sgn_1_pos le_less dest: zdvd_imp_le)
then show ?Q and ?R
by simp_all
qed
lemma int_div_neg_eq:
\<open>a div b = q\<close> if \<open>a = b * q + r\<close> \<open>r \<le> 0\<close> \<open>b < r\<close> for a b q r :: int
using that int_div_pos_eq [of a \<open>- b\<close> \<open>- q\<close> \<open>- r\<close>] by simp_all
lemma int_mod_neg_eq:
\<open>a mod b = r\<close> if \<open>a = b * q + r\<close> \<open>r \<le> 0\<close> \<open>b < r\<close> for a b q r :: int
using that int_div_neg_eq [of a b q r] by simp
subsubsection \<open>Laws for unary minus\<close>
lemma zmod_zminus1_not_zero:
fixes k l :: int
shows "- k mod l \<noteq> 0 \<Longrightarrow> k mod l \<noteq> 0"
by (simp add: mod_eq_0_iff_dvd)
lemma zmod_zminus2_not_zero:
fixes k l :: int
shows "k mod - l \<noteq> 0 \<Longrightarrow> k mod l \<noteq> 0"
by (simp add: mod_eq_0_iff_dvd)
lemma zdiv_zminus1_eq_if:
\<open>(- a) div b = (if a mod b = 0 then - (a div b) else - (a div b) - 1)\<close>
if \<open>b \<noteq> 0\<close> for a b :: int
using that sgn_not_eq_imp [of b \<open>- a\<close>]
by (cases \<open>a = 0\<close>) (auto simp add: div_eq_div_abs [of \<open>- a\<close> b] div_eq_div_abs [of a b] sgn_eq_0_iff)
lemma zdiv_zminus2_eq_if:
\<open>a div (- b) = (if a mod b = 0 then - (a div b) else - (a div b) - 1)\<close>
if \<open>b \<noteq> 0\<close> for a b :: int
using that by (auto simp add: zdiv_zminus1_eq_if div_minus_right)
lemma zmod_zminus1_eq_if:
\<open>(- a) mod b = (if a mod b = 0 then 0 else b - (a mod b))\<close>
for a b :: int
by (cases \<open>b = 0\<close>)
(auto simp flip: minus_div_mult_eq_mod simp add: zdiv_zminus1_eq_if algebra_simps)
lemma zmod_zminus2_eq_if:
\<open>a mod (- b) = (if a mod b = 0 then 0 else (a mod b) - b)\<close>
for a b :: int
by (auto simp add: zmod_zminus1_eq_if mod_minus_right)
subsubsection \<open>Borders\<close>
lemma pos_mod_bound [simp]:
"k mod l < l" if "l > 0" for k l :: int
proof -
obtain m and s where "k = sgn s * int m"
by (rule int_sgnE)
moreover from that obtain n where "l = sgn 1 * int n"
by (cases l) simp_all
moreover from this that have "n > 0"
by simp
ultimately show ?thesis
by (simp only: modulo_int_unfold)
(auto simp add: mod_greater_zero_iff_not_dvd sgn_1_pos)
qed
lemma neg_mod_bound [simp]:
"l < k mod l" if "l < 0" for k l :: int
proof -
obtain m and s where "k = sgn s * int m"
by (rule int_sgnE)
moreover from that obtain q where "l = sgn (- 1) * int (Suc q)"
by (cases l) simp_all
moreover define n where "n = Suc q"
then have "Suc q = n"
by simp
ultimately show ?thesis
by (simp only: modulo_int_unfold)
(auto simp add: mod_greater_zero_iff_not_dvd sgn_1_neg)
qed
lemma pos_mod_sign [simp]:
"0 \<le> k mod l" if "l > 0" for k l :: int
proof -
obtain m and s where "k = sgn s * int m"
by (rule int_sgnE)
moreover from that obtain n where "l = sgn 1 * int n"
by (cases l) auto
moreover from this that have "n > 0"
by simp
ultimately show ?thesis
by (simp only: modulo_int_unfold) (auto simp add: sgn_1_pos)
qed
lemma neg_mod_sign [simp]:
"k mod l \<le> 0" if "l < 0" for k l :: int
proof -
obtain m and s where "k = sgn s * int m"
by (rule int_sgnE)
moreover from that obtain q where "l = sgn (- 1) * int (Suc q)"
by (cases l) simp_all
moreover define n where "n = Suc q"
then have "Suc q = n"
by simp
moreover have \<open>int (m mod n) \<le> int n\<close>
using \<open>Suc q = n\<close> by simp
then have \<open>sgn s * int (m mod n) \<le> int n\<close>
by (cases s \<open>0::int\<close> rule: linorder_cases) simp_all
ultimately show ?thesis
by (simp only: modulo_int_unfold) auto
qed
subsubsection \<open>Splitting Rules for div and mod\<close>
lemma split_zdiv:
\<open>P (n div k) \<longleftrightarrow>
(k = 0 \<longrightarrow> P 0) \<and>
(0 < k \<longrightarrow> (\<forall>i j. 0 \<le> j \<and> j < k \<and> n = k * i + j \<longrightarrow> P i)) \<and>
(k < 0 \<longrightarrow> (\<forall>i j. k < j \<and> j \<le> 0 \<and> n = k * i + j \<longrightarrow> P i))\<close> (is ?div)
and split_zmod:
\<open>Q (n mod k) \<longleftrightarrow>
(k = 0 \<longrightarrow> Q n) \<and>
(0 < k \<longrightarrow> (\<forall>i j. 0 \<le> j \<and> j < k \<and> n = k * i + j \<longrightarrow> Q j)) \<and>
(k < 0 \<longrightarrow> (\<forall>i j. k < j \<and> j \<le> 0 \<and> n = k * i + j \<longrightarrow> Q j))\<close> (is ?mod)
for n k :: int
proof -
have *: \<open>R (n div k) (n mod k) \<longleftrightarrow>
(k = 0 \<longrightarrow> R 0 n) \<and>
(0 < k \<longrightarrow> (\<forall>i j. 0 \<le> j \<and> j < k \<and> n = k * i + j \<longrightarrow> R i j)) \<and>
(k < 0 \<longrightarrow> (\<forall>i j. k < j \<and> j \<le> 0 \<and> n = k * i + j \<longrightarrow> R i j))\<close> for R
by (cases \<open>k = 0\<close>)
(auto simp add: linorder_class.neq_iff)
from * [of \<open>\<lambda>q _. P q\<close>] show ?div .
from * [of \<open>\<lambda>_ r. Q r\<close>] show ?mod .
qed
text \<open>Enable (lin)arith to deal with \<^const>\<open>divide\<close> and \<^const>\<open>modulo\<close>
when these are applied to some constant that is of the form
\<^term>\<open>numeral k\<close>:\<close>
declare split_zdiv [of _ _ \<open>numeral n\<close>, linarith_split] for n
declare split_zdiv [of _ _ \<open>- numeral n\<close>, linarith_split] for n
declare split_zmod [of _ _ \<open>numeral n\<close>, linarith_split] for n
declare split_zmod [of _ _ \<open>- numeral n\<close>, linarith_split] for n
lemma zdiv_eq_0_iff:
"i div k = 0 \<longleftrightarrow> k = 0 \<or> 0 \<le> i \<and> i < k \<or> i \<le> 0 \<and> k < i" (is "?L = ?R")
for i k :: int
proof
assume ?L
moreover have "?L \<longrightarrow> ?R"
by (rule split_zdiv [THEN iffD2]) simp
ultimately show ?R
by blast
next
assume ?R then show ?L
by auto
qed
lemma zmod_trivial_iff:
fixes i k :: int
shows "i mod k = i \<longleftrightarrow> k = 0 \<or> 0 \<le> i \<and> i < k \<or> i \<le> 0 \<and> k < i"
proof -
have "i mod k = i \<longleftrightarrow> i div k = 0"
using div_mult_mod_eq [of i k] by safe auto
with zdiv_eq_0_iff
show ?thesis
by simp
qed
subsubsection \<open>Algebraic rewrites\<close>
lemma zdiv_zmult2_eq:
\<open>a div (b * c) = (a div b) div c\<close> if \<open>c \<ge> 0\<close> for a b c :: int
proof (cases \<open>b \<ge> 0\<close>)
case True
with that show ?thesis
using div_mult2_eq' [of a \<open>nat b\<close> \<open>nat c\<close>] by simp
next
case False
with that show ?thesis
using div_mult2_eq' [of \<open>- a\<close> \<open>nat (- b)\<close> \<open>nat c\<close>] by simp
qed
lemma zdiv_zmult2_eq':
\<open>k div (l * j) = ((sgn j * k) div l) div \<bar>j\<bar>\<close> for k l j :: int
proof -
have \<open>k div (l * j) = (sgn j * k) div (sgn j * (l * j))\<close>
by (simp add: sgn_0_0)
also have \<open>sgn j * (l * j) = l * \<bar>j\<bar>\<close>
by (simp add: mult.left_commute [of _ l] abs_sgn) (simp add: ac_simps)
also have \<open>(sgn j * k) div (l * \<bar>j\<bar>) = ((sgn j * k) div l) div \<bar>j\<bar>\<close>
by (simp add: zdiv_zmult2_eq)
finally show ?thesis .
qed
lemma zmod_zmult2_eq:
\<open>a mod (b * c) = b * (a div b mod c) + a mod b\<close> if \<open>c \<ge> 0\<close> for a b c :: int
proof (cases \<open>b \<ge> 0\<close>)
case True
with that show ?thesis
using mod_mult2_eq' [of a \<open>nat b\<close> \<open>nat c\<close>] by simp
next
case False
with that show ?thesis
using mod_mult2_eq' [of \<open>- a\<close> \<open>nat (- b)\<close> \<open>nat c\<close>] by simp
qed
lemma half_nonnegative_int_iff [simp]:
\<open>k div 2 \<ge> 0 \<longleftrightarrow> k \<ge> 0\<close> for k :: int
by auto
lemma half_negative_int_iff [simp]:
\<open>k div 2 < 0 \<longleftrightarrow> k < 0\<close> for k :: int
by auto
subsubsection \<open>Distributive laws for conversions.\<close>
lemma zdiv_int:
"int (a div b) = int a div int b"
by (fact of_nat_div)
lemma zmod_int:
"int (a mod b) = int a mod int b"
by (fact of_nat_mod)
lemma nat_div_distrib:
\<open>nat (x div y) = nat x div nat y\<close> if \<open>0 \<le> x\<close>
using that by (simp add: divide_int_def sgn_if)
lemma nat_div_distrib':
\<open>nat (x div y) = nat x div nat y\<close> if \<open>0 \<le> y\<close>
using that by (simp add: divide_int_def sgn_if)
lemma nat_mod_distrib: \<comment> \<open>Fails if y<0: the LHS collapses to (nat z) but the RHS doesn't\<close>
\<open>nat (x mod y) = nat x mod nat y\<close> if \<open>0 \<le> x\<close> \<open>0 \<le> y\<close>
using that by (simp add: modulo_int_def sgn_if)
subsubsection \<open>Monotonicity in the First Argument (Dividend)\<close>
lemma zdiv_mono1:
\<open>a div b \<le> a' div b\<close>
if \<open>a \<le> a'\<close> \<open>0 < b\<close>
for a b b' :: int
proof -
from \<open>a \<le> a'\<close> have \<open>b * (a div b) + a mod b \<le> b * (a' div b) + a' mod b\<close>
by simp
then have \<open>b * (a div b) \<le> (a' mod b - a mod b) + b * (a' div b)\<close>
by (simp add: algebra_simps)
moreover have \<open>a' mod b < b + a mod b\<close>
by (rule less_le_trans [of _ b]) (use \<open>0 < b\<close> in simp_all)
ultimately have \<open>b * (a div b) < b * (1 + a' div b)\<close>
by (simp add: distrib_left)
with \<open>0 < b\<close> have \<open>a div b < 1 + a' div b\<close>
by (simp add: mult_less_cancel_left)
then show ?thesis
by simp
qed
lemma zdiv_mono1_neg:
\<open>a' div b \<le> a div b\<close>
if \<open>a \<le> a'\<close> \<open>b < 0\<close>
for a a' b :: int
using that zdiv_mono1 [of \<open>- a'\<close> \<open>- a\<close> \<open>- b\<close>] by simp
subsubsection \<open>Monotonicity in the Second Argument (Divisor)\<close>
lemma zdiv_mono2:
\<open>a div b \<le> a div b'\<close> if \<open>0 \<le> a\<close> \<open>0 < b'\<close> \<open>b' \<le> b\<close> for a b b' :: int
proof -
define q q' r r' where **: \<open>q = a div b\<close> \<open>q' = a div b'\<close> \<open>r = a mod b\<close> \<open>r' = a mod b'\<close>
then have *: \<open>b * q + r = b' * q' + r'\<close> \<open>0 \<le> b' * q' + r'\<close>
\<open>r' < b'\<close> \<open>0 \<le> r\<close> \<open>0 < b'\<close> \<open>b' \<le> b\<close>
using that by simp_all
have \<open>0 < b' * (q' + 1)\<close>
using * by (simp add: distrib_left)
with * have \<open>0 \<le> q'\<close>
by (simp add: zero_less_mult_iff)
moreover have \<open>b * q = r' - r + b' * q'\<close>
using * by linarith
ultimately have \<open>b * q < b * (q' + 1)\<close>
using mult_right_mono * unfolding distrib_left by fastforce
with * have \<open>q \<le> q'\<close>
by (simp add: mult_less_cancel_left_pos)
with ** show ?thesis
by simp
qed
lemma zdiv_mono2_neg:
\<open>a div b' \<le> a div b\<close> if \<open>a < 0\<close> \<open>0 < b'\<close> \<open>b' \<le> b\<close> for a b b' :: int
proof -
define q q' r r' where **: \<open>q = a div b\<close> \<open>q' = a div b'\<close> \<open>r = a mod b\<close> \<open>r' = a mod b'\<close>
then have *: \<open>b * q + r = b' * q' + r'\<close> \<open>b' * q' + r' < 0\<close>
\<open>r < b\<close> \<open>0 \<le> r'\<close> \<open>0 < b'\<close> \<open>b' \<le> b\<close>
using that by simp_all
have \<open>b' * q' < 0\<close>
using * by linarith
with * have \<open>q' \<le> 0\<close>
by (simp add: mult_less_0_iff)
have \<open>b * q' \<le> b' * q'\<close>
by (simp add: \<open>q' \<le> 0\<close> * mult_right_mono_neg)
then have "b * q' < b * (q + 1)"
using * by (simp add: distrib_left)
then have \<open>q' \<le> q\<close>
using * by (simp add: mult_less_cancel_left)
then show ?thesis
by (simp add: **)
qed
subsubsection \<open>Quotients of Signs\<close>
lemma div_eq_minus1:
\<open>0 < b \<Longrightarrow> - 1 div b = - 1\<close> for b :: int
by (simp add: divide_int_def)
lemma zmod_minus1:
\<open>0 < b \<Longrightarrow> - 1 mod b = b - 1\<close> for b :: int
by (auto simp add: modulo_int_def)
lemma minus_mod_int_eq:
\<open>- k mod l = l - 1 - (k - 1) mod l\<close> if \<open>l \<ge> 0\<close> for k l :: int
proof (cases \<open>l = 0\<close>)
case True
then show ?thesis
by simp
next
case False
with that have \<open>l > 0\<close>
by simp
then show ?thesis
proof (cases \<open>l dvd k\<close>)
case True
then obtain j where \<open>k = l * j\<close> ..
moreover have \<open>(l * j mod l - 1) mod l = l - 1\<close>
using \<open>l > 0\<close> by (simp add: zmod_minus1)
then have \<open>(l * j - 1) mod l = l - 1\<close>
by (simp only: mod_simps)
ultimately show ?thesis
by simp
next
case False
moreover have 1: \<open>0 < k mod l\<close>
using \<open>0 < l\<close> False le_less by fastforce
moreover have 2: \<open>k mod l < 1 + l\<close>
using \<open>0 < l\<close> pos_mod_bound[of l k] by linarith
from 1 2 \<open>l > 0\<close> have \<open>(k mod l - 1) mod l = k mod l - 1\<close>
by (simp add: zmod_trivial_iff)
ultimately show ?thesis
by (simp only: zmod_zminus1_eq_if)
(simp add: mod_eq_0_iff_dvd algebra_simps mod_simps)
qed
qed
lemma div_neg_pos_less0:
\<open>a div b < 0\<close> if \<open>a < 0\<close> \<open>0 < b\<close> for a b :: int
proof -
have "a div b \<le> - 1 div b"
using zdiv_mono1 that by auto
also have "... \<le> -1"
by (simp add: that(2) div_eq_minus1)
finally show ?thesis
by force
qed
lemma div_nonneg_neg_le0:
\<open>a div b \<le> 0\<close> if \<open>0 \<le> a\<close> \<open>b < 0\<close> for a b :: int
using that by (auto dest: zdiv_mono1_neg)
lemma div_nonpos_pos_le0:
\<open>a div b \<le> 0\<close> if \<open>a \<le> 0\<close> \<open>0 < b\<close> for a b :: int
using that by (auto dest: zdiv_mono1)
text\<open>Now for some equivalences of the form \<open>a div b >=< 0 \<longleftrightarrow> \<dots>\<close>
conditional upon the sign of \<open>a\<close> or \<open>b\<close>. There are many more.
They should all be simp rules unless that causes too much search.\<close>
lemma pos_imp_zdiv_nonneg_iff:
\<open>0 \<le> a div b \<longleftrightarrow> 0 \<le> a\<close>
if \<open>0 < b\<close> for a b :: int
proof
assume \<open>0 \<le> a div b\<close>
show \<open>0 \<le> a\<close>
proof (rule ccontr)
assume \<open>\<not> 0 \<le> a\<close>
then have \<open>a < 0\<close>
by simp
then have \<open>a div b < 0\<close>
using that by (rule div_neg_pos_less0)
with \<open>0 \<le> a div b\<close> show False
by simp
qed
next
assume "0 \<le> a"
then have "0 div b \<le> a div b"
using zdiv_mono1 that by blast
then show "0 \<le> a div b"
by auto
qed
lemma neg_imp_zdiv_nonneg_iff:
\<open>0 \<le> a div b \<longleftrightarrow> a \<le> 0\<close> if \<open>b < 0\<close> for a b :: int
using that pos_imp_zdiv_nonneg_iff [of \<open>- b\<close> \<open>- a\<close>] by simp
lemma pos_imp_zdiv_pos_iff:
\<open>0 < (i::int) div k \<longleftrightarrow> k \<le> i\<close> if \<open>0 < k\<close> for i k :: int
using that pos_imp_zdiv_nonneg_iff [of k i] zdiv_eq_0_iff [of i k] by arith
lemma pos_imp_zdiv_neg_iff:
\<open>a div b < 0 \<longleftrightarrow> a < 0\<close> if \<open>0 < b\<close> for a b :: int
\<comment> \<open>But not \<^prop>\<open>a div b \<le> 0 \<longleftrightarrow> a \<le> 0\<close>; consider \<^prop>\<open>a = 1\<close>, \<^prop>\<open>b = 2\<close> when \<^prop>\<open>a div b = 0\<close>.\<close>
using that by (simp add: pos_imp_zdiv_nonneg_iff flip: linorder_not_le)
lemma neg_imp_zdiv_neg_iff:
\<comment> \<open>But not \<^prop>\<open>a div b \<le> 0 \<longleftrightarrow> 0 \<le> a\<close>; consider \<^prop>\<open>a = - 1\<close>, \<^prop>\<open>b = - 2\<close> when \<^prop>\<open>a div b = 0\<close>.\<close>
\<open>a div b < 0 \<longleftrightarrow> 0 < a\<close> if \<open>b < 0\<close> for a b :: int
using that by (simp add: neg_imp_zdiv_nonneg_iff flip: linorder_not_le)
lemma nonneg1_imp_zdiv_pos_iff:
\<open>a div b > 0 \<longleftrightarrow> a \<ge> b \<and> b > 0\<close> if \<open>0 \<le> a\<close> for a b :: int
proof -
have "0 < a div b \<Longrightarrow> b \<le> a"
using div_pos_pos_trivial[of a b] that by arith
moreover have "0 < a div b \<Longrightarrow> b > 0"
using that div_nonneg_neg_le0[of a b] by (cases "b=0"; force)
moreover have "b \<le> a \<and> 0 < b \<Longrightarrow> 0 < a div b"
using int_one_le_iff_zero_less[of "a div b"] zdiv_mono1[of b a b] by simp
ultimately show ?thesis
by blast
qed
lemma zmod_le_nonneg_dividend:
\<open>m mod k \<le> m\<close> if \<open>(m::int) \<ge> 0\<close> for m k :: int
proof -
from that have \<open>m > 0 \<or> m = 0\<close>
by auto
then show ?thesis proof
assume \<open>m = 0\<close> then show ?thesis
by simp
next
assume \<open>m > 0\<close> then show ?thesis
proof (cases k \<open>0::int\<close> rule: linorder_cases)
case less
moreover define l where \<open>l = - k\<close>
ultimately have \<open>l > 0\<close>
by simp
with \<open>m > 0\<close> have \<open>int (nat m mod nat l) \<le> m\<close>
by (simp flip: le_nat_iff)
then have \<open>int (nat m mod nat l) - l \<le> m\<close>
using \<open>l > 0\<close> by simp
with \<open>m > 0\<close> \<open>l > 0\<close> show ?thesis
by (simp add: modulo_int_def l_def flip: le_nat_iff)
qed (simp_all add: modulo_int_def flip: le_nat_iff)
qed
qed
lemma sgn_div_eq_sgn_mult:
\<open>sgn (k div l) = of_bool (k div l \<noteq> 0) * sgn (k * l)\<close>
for k l :: int
proof (cases \<open>k div l = 0\<close>)
case True
then show ?thesis
by simp
next
case False
have \<open>0 \<le> \<bar>k\<bar> div \<bar>l\<bar>\<close>
by (cases \<open>l = 0\<close>) (simp_all add: pos_imp_zdiv_nonneg_iff)
then have \<open>\<bar>k\<bar> div \<bar>l\<bar> \<noteq> 0 \<longleftrightarrow> 0 < \<bar>k\<bar> div \<bar>l\<bar>\<close>
by (simp add: less_le)
also have \<open>\<dots> \<longleftrightarrow> \<bar>k\<bar> \<ge> \<bar>l\<bar>\<close>
using False nonneg1_imp_zdiv_pos_iff by auto
finally have *: \<open>\<bar>k\<bar> div \<bar>l\<bar> \<noteq> 0 \<longleftrightarrow> \<bar>l\<bar> \<le> \<bar>k\<bar>\<close> .
show ?thesis
using \<open>0 \<le> \<bar>k\<bar> div \<bar>l\<bar>\<close> False
by (auto simp add: div_eq_div_abs [of k l] div_eq_sgn_abs [of k l]
sgn_mult sgn_1_pos sgn_1_neg sgn_eq_0_iff nonneg1_imp_zdiv_pos_iff * dest: sgn_not_eq_imp)
qed
subsubsection \<open>Further properties\<close>
lemma div_int_pos_iff:
"k div l \<ge> 0 \<longleftrightarrow> k = 0 \<or> l = 0 \<or> k \<ge> 0 \<and> l \<ge> 0
\<or> k < 0 \<and> l < 0"
for k l :: int
proof (cases "k = 0 \<or> l = 0")
case False
then have *: "k \<noteq> 0" "l \<noteq> 0"
by auto
then have "0 \<le> k div l \<Longrightarrow> \<not> k < 0 \<Longrightarrow> 0 \<le> l"
by (meson neg_imp_zdiv_neg_iff not_le not_less_iff_gr_or_eq)
then show ?thesis
using * by (auto simp add: pos_imp_zdiv_nonneg_iff neg_imp_zdiv_nonneg_iff)
qed auto
lemma mod_int_pos_iff:
\<open>k mod l \<ge> 0 \<longleftrightarrow> l dvd k \<or> l = 0 \<and> k \<ge> 0 \<or> l > 0\<close>
for k l :: int
proof (cases "l > 0")
case False
then show ?thesis
by (simp add: dvd_eq_mod_eq_0) (use neg_mod_sign [of l k] in \<open>auto simp add: le_less not_less\<close>)
qed auto
lemma abs_div:
\<open>\<bar>x div y\<bar> = \<bar>x\<bar> div \<bar>y\<bar>\<close> if \<open>y dvd x\<close> for x y :: int
using that by (cases \<open>y = 0\<close>) (auto simp add: abs_mult)
lemma int_power_div_base: \<^marker>\<open>contributor \<open>Matthias Daum\<close>\<close>
\<open>k ^ m div k = k ^ (m - Suc 0)\<close> if \<open>0 < m\<close> \<open>0 < k\<close> for k :: int
using that by (cases m) simp_all
lemma int_div_less_self: \<^marker>\<open>contributor \<open>Matthias Daum\<close>\<close>
\<open>x div k < x\<close> if \<open>0 < x\<close> \<open>1 < k\<close> for x k :: int
proof -
from that have \<open>nat (x div k) = nat x div nat k\<close>
by (simp add: nat_div_distrib)
also from that have \<open>nat x div nat k < nat x\<close>
by simp
finally show ?thesis
by simp
qed
subsubsection \<open>Computing \<open>div\<close> and \<open>mod\<close> by shifting\<close>
lemma div_pos_geq:
\<open>k div l = (k - l) div l + 1\<close> if \<open>0 < l\<close> \<open>l \<le> k\<close> for k l :: int
proof -
have "k = (k - l) + l" by simp
then obtain j where k: "k = j + l" ..
with that show ?thesis by (simp add: div_add_self2)
qed
lemma mod_pos_geq:
\<open>k mod l = (k - l) mod l\<close> if \<open>0 < l\<close> \<open>l \<le> k\<close> for k l :: int
proof -
have "k = (k - l) + l" by simp
then obtain j where k: "k = j + l" ..
with that show ?thesis by simp
qed
lemma pos_zdiv_mult_2: \<open>(1 + 2 * b) div (2 * a) = b div a\<close> (is ?Q)
and pos_zmod_mult_2: \<open>(1 + 2 * b) mod (2 * a) = 1 + 2 * (b mod a)\<close> (is ?R)
if \<open>0 \<le> a\<close> for a b :: int
proof -
have \<open>((1 + 2 * b) div (2 * a), (1 + 2 * b) mod (2 * a)) = (b div a, 1 + 2 * (b mod a))\<close>
proof (cases \<open>2 * a\<close> \<open>b div a\<close> \<open>1 + 2 * (b mod a)\<close> \<open>1 + 2 * b\<close> rule: euclidean_relation_intI)
case by0
then show ?case
by simp
next
case divides
have \<open>2 dvd (2 * a)\<close>
by simp
then have \<open>2 dvd (1 + 2 * b)\<close>
using \<open>2 * a dvd 1 + 2 * b\<close> by (rule dvd_trans)
then have \<open>2 dvd (1 + b * 2)\<close>
by (simp add: ac_simps)
then have \<open>is_unit (2 :: int)\<close>
by simp
then show ?case
by simp
next
case euclidean_relation
with that have \<open>a > 0\<close>
by simp
moreover have \<open>b mod a < a\<close>
using \<open>a > 0\<close> by simp
then have \<open>1 + 2 * (b mod a) < 2 * a\<close>
by simp
moreover have \<open>2 * (b mod a) + a * (2 * (b div a)) = 2 * (b div a * a + b mod a)\<close>
by (simp only: algebra_simps)
moreover have \<open>0 \<le> 2 * (b mod a)\<close>
using \<open>a > 0\<close> by simp
ultimately show ?case
by (simp add: algebra_simps)
qed
then show ?Q and ?R
by simp_all
qed
lemma neg_zdiv_mult_2: \<open>(1 + 2 * b) div (2 * a) = (b + 1) div a\<close> (is ?Q)
and neg_zmod_mult_2: \<open>(1 + 2 * b) mod (2 * a) = 2 * ((b + 1) mod a) - 1\<close> (is ?R)
if \<open>a \<le> 0\<close> for a b :: int
proof -
have \<open>((1 + 2 * b) div (2 * a), (1 + 2 * b) mod (2 * a)) = ((b + 1) div a, 2 * ((b + 1) mod a) - 1)\<close>
proof (cases \<open>2 * a\<close> \<open>(b + 1) div a\<close> \<open>2 * ((b + 1) mod a) - 1\<close> \<open>1 + 2 * b\<close> rule: euclidean_relation_intI)
case by0
then show ?case
by simp
next
case divides
have \<open>2 dvd (2 * a)\<close>
by simp
then have \<open>2 dvd (1 + 2 * b)\<close>
using \<open>2 * a dvd 1 + 2 * b\<close> by (rule dvd_trans)
then have \<open>2 dvd (1 + b * 2)\<close>
by (simp add: ac_simps)
then have \<open>is_unit (2 :: int)\<close>
by simp
then show ?case
by simp
next
case euclidean_relation
with that have \<open>a < 0\<close>
by simp
moreover have \<open>(b + 1) mod a > a\<close>
using \<open>a < 0\<close> by simp
then have \<open>2 * ((b + 1) mod a) > 1 + 2 * a\<close>
by simp
moreover have \<open>((1 + b) mod a) \<le> 0\<close>
using \<open>a < 0\<close> by simp
then have \<open>2 * ((1 + b) mod a) \<le> 0\<close>
by simp
moreover have \<open>2 * ((1 + b) mod a) + a * (2 * ((1 + b) div a)) =
2 * ((1 + b) div a * a + (1 + b) mod a)\<close>
by (simp only: algebra_simps)
ultimately show ?case
by (simp add: algebra_simps sgn_mult abs_mult)
qed
then show ?Q and ?R
by simp_all
qed
lemma zdiv_numeral_Bit0 [simp]:
\<open>numeral (Num.Bit0 v) div numeral (Num.Bit0 w) =
numeral v div (numeral w :: int)\<close>
unfolding numeral.simps unfolding mult_2 [symmetric]
by (rule div_mult_mult1) simp
lemma zdiv_numeral_Bit1 [simp]:
\<open>numeral (Num.Bit1 v) div numeral (Num.Bit0 w) =
(numeral v div (numeral w :: int))\<close>
unfolding numeral.simps
unfolding mult_2 [symmetric] add.commute [of _ 1]
by (rule pos_zdiv_mult_2) simp
lemma zmod_numeral_Bit0 [simp]:
\<open>numeral (Num.Bit0 v) mod numeral (Num.Bit0 w) =
(2::int) * (numeral v mod numeral w)\<close>
unfolding numeral_Bit0 [of v] numeral_Bit0 [of w]
unfolding mult_2 [symmetric] by (rule mod_mult_mult1)
lemma zmod_numeral_Bit1 [simp]:
\<open>numeral (Num.Bit1 v) mod numeral (Num.Bit0 w) =
2 * (numeral v mod numeral w) + (1::int)\<close>
unfolding numeral_Bit1 [of v] numeral_Bit0 [of w]
unfolding mult_2 [symmetric] add.commute [of _ 1]
by (rule pos_zmod_mult_2) simp
subsection \<open>Generic symbolic computations\<close>
text \<open>
The following type class contains everything necessary to formulate
a division algorithm in ring structures with numerals, restricted
to its positive segments.
\<close>
class unique_euclidean_semiring_with_nat_division = unique_euclidean_semiring_with_nat +
fixes divmod :: \<open>num \<Rightarrow> num \<Rightarrow> 'a \<times> 'a\<close>
and divmod_step :: \<open>'a \<Rightarrow> 'a \<times> 'a \<Rightarrow> 'a \<times> 'a\<close> \<comment> \<open>
These are conceptually definitions but force generated code
to be monomorphic wrt. particular instances of this class which
yields a significant speedup.\<close>
assumes divmod_def: \<open>divmod m n = (numeral m div numeral n, numeral m mod numeral n)\<close>
and divmod_step_def [simp]: \<open>divmod_step l (q, r) =
(if euclidean_size l \<le> euclidean_size r then (2 * q + 1, r - l)
else (2 * q, r))\<close> \<comment> \<open>
This is a formulation of one step (referring to one digit position)
in school-method division: compare the dividend at the current
digit position with the remainder from previous division steps
and evaluate accordingly.\<close>
begin
lemma fst_divmod:
\<open>fst (divmod m n) = numeral m div numeral n\<close>
by (simp add: divmod_def)
lemma snd_divmod:
\<open>snd (divmod m n) = numeral m mod numeral n\<close>
by (simp add: divmod_def)
text \<open>
Following a formulation of school-method division.
If the divisor is smaller than the dividend, terminate.
If not, shift the dividend to the right until termination
occurs and then reiterate single division steps in the
opposite direction.
\<close>
lemma divmod_divmod_step:
\<open>divmod m n = (if m < n then (0, numeral m)
else divmod_step (numeral n) (divmod m (Num.Bit0 n)))\<close>
proof (cases \<open>m < n\<close>)
case True
then show ?thesis
by (simp add: prod_eq_iff fst_divmod snd_divmod flip: of_nat_numeral of_nat_div of_nat_mod)
next
case False
define r s t where \<open>r = (numeral m :: nat)\<close> \<open>s = (numeral n :: nat)\<close> \<open>t = 2 * s\<close>
then have *: \<open>numeral m = of_nat r\<close> \<open>numeral n = of_nat s\<close> \<open>numeral (num.Bit0 n) = of_nat t\<close>
and \<open>\<not> s \<le> r mod s\<close>
by (simp_all add: not_le)
have t: \<open>2 * (r div t) = r div s - r div s mod 2\<close>
\<open>r mod t = s * (r div s mod 2) + r mod s\<close>
by (simp add: Rings.minus_mod_eq_mult_div Groups.mult.commute [of 2] Euclidean_Division.div_mult2_eq \<open>t = 2 * s\<close>)
(use mod_mult2_eq [of r s 2] in \<open>simp add: ac_simps \<open>t = 2 * s\<close>\<close>)
have rs: \<open>r div s mod 2 = 0 \<or> r div s mod 2 = Suc 0\<close>
by auto
from \<open>\<not> s \<le> r mod s\<close> have \<open>s \<le> r mod t \<Longrightarrow>
r div s = Suc (2 * (r div t)) \<and>
r mod s = r mod t - s\<close>
using rs
by (auto simp add: t)
moreover have \<open>r mod t < s \<Longrightarrow>
r div s = 2 * (r div t) \<and>
r mod s = r mod t\<close>
using rs
by (auto simp add: t)
ultimately show ?thesis
by (simp add: divmod_def prod_eq_iff split_def Let_def
not_less mod_eq_0_iff_dvd Rings.mod_eq_0_iff_dvd False not_le *)
(simp add: flip: of_nat_numeral of_nat_mult add.commute [of 1] of_nat_div of_nat_mod of_nat_Suc of_nat_diff)
qed
text \<open>The division rewrite proper -- first, trivial results involving \<open>1\<close>\<close>
lemma divmod_trivial [simp]:
"divmod m Num.One = (numeral m, 0)"
"divmod num.One (num.Bit0 n) = (0, Numeral1)"
"divmod num.One (num.Bit1 n) = (0, Numeral1)"
using divmod_divmod_step [of "Num.One"] by (simp_all add: divmod_def)
text \<open>Division by an even number is a right-shift\<close>
lemma divmod_cancel [simp]:
\<open>divmod (Num.Bit0 m) (Num.Bit0 n) = (case divmod m n of (q, r) \<Rightarrow> (q, 2 * r))\<close> (is ?P)
\<open>divmod (Num.Bit1 m) (Num.Bit0 n) = (case divmod m n of (q, r) \<Rightarrow> (q, 2 * r + 1))\<close> (is ?Q)
proof -
define r s where \<open>r = (numeral m :: nat)\<close> \<open>s = (numeral n :: nat)\<close>
then have *: \<open>numeral m = of_nat r\<close> \<open>numeral n = of_nat s\<close>
\<open>numeral (num.Bit0 m) = of_nat (2 * r)\<close> \<open>numeral (num.Bit0 n) = of_nat (2 * s)\<close>
\<open>numeral (num.Bit1 m) = of_nat (Suc (2 * r))\<close>
by simp_all
have **: \<open>Suc (2 * r) div 2 = r\<close>
by simp
show ?P and ?Q
by (simp_all add: divmod_def *)
(simp_all flip: of_nat_numeral of_nat_div of_nat_mod of_nat_mult add.commute [of 1] of_nat_Suc
add: Euclidean_Division.mod_mult_mult1 div_mult2_eq [of _ 2] mod_mult2_eq [of _ 2] **)
qed
text \<open>The really hard work\<close>
lemma divmod_steps [simp]:
"divmod (num.Bit0 m) (num.Bit1 n) =
(if m \<le> n then (0, numeral (num.Bit0 m))
else divmod_step (numeral (num.Bit1 n))
(divmod (num.Bit0 m)
(num.Bit0 (num.Bit1 n))))"
"divmod (num.Bit1 m) (num.Bit1 n) =
(if m < n then (0, numeral (num.Bit1 m))
else divmod_step (numeral (num.Bit1 n))
(divmod (num.Bit1 m)
(num.Bit0 (num.Bit1 n))))"
by (simp_all add: divmod_divmod_step)
lemmas divmod_algorithm_code = divmod_trivial divmod_cancel divmod_steps
text \<open>Special case: divisibility\<close>
definition divides_aux :: "'a \<times> 'a \<Rightarrow> bool"
where
"divides_aux qr \<longleftrightarrow> snd qr = 0"
lemma divides_aux_eq [simp]:
"divides_aux (q, r) \<longleftrightarrow> r = 0"
by (simp add: divides_aux_def)
lemma dvd_numeral_simp [simp]:
"numeral m dvd numeral n \<longleftrightarrow> divides_aux (divmod n m)"
by (simp add: divmod_def mod_eq_0_iff_dvd)
text \<open>Generic computation of quotient and remainder\<close>
lemma numeral_div_numeral [simp]:
"numeral k div numeral l = fst (divmod k l)"
by (simp add: fst_divmod)
lemma numeral_mod_numeral [simp]:
"numeral k mod numeral l = snd (divmod k l)"
by (simp add: snd_divmod)
lemma one_div_numeral [simp]:
"1 div numeral n = fst (divmod num.One n)"
by (simp add: fst_divmod)
lemma one_mod_numeral [simp]:
"1 mod numeral n = snd (divmod num.One n)"
by (simp add: snd_divmod)
end
instantiation nat :: unique_euclidean_semiring_with_nat_division
begin
definition divmod_nat :: "num \<Rightarrow> num \<Rightarrow> nat \<times> nat"
where
divmod'_nat_def: "divmod_nat m n = (numeral m div numeral n, numeral m mod numeral n)"
definition divmod_step_nat :: "nat \<Rightarrow> nat \<times> nat \<Rightarrow> nat \<times> nat"
where
"divmod_step_nat l qr = (let (q, r) = qr
in if r \<ge> l then (2 * q + 1, r - l)
else (2 * q, r))"
instance
by standard (simp_all add: divmod'_nat_def divmod_step_nat_def)
end
declare divmod_algorithm_code [where ?'a = nat, code]
lemma Suc_0_div_numeral [simp]:
\<open>Suc 0 div numeral Num.One = 1\<close>
\<open>Suc 0 div numeral (Num.Bit0 n) = 0\<close>
\<open>Suc 0 div numeral (Num.Bit1 n) = 0\<close>
by simp_all
lemma Suc_0_mod_numeral [simp]:
\<open>Suc 0 mod numeral Num.One = 0\<close>
\<open>Suc 0 mod numeral (Num.Bit0 n) = 1\<close>
\<open>Suc 0 mod numeral (Num.Bit1 n) = 1\<close>
by simp_all
instantiation int :: unique_euclidean_semiring_with_nat_division
begin
definition divmod_int :: "num \<Rightarrow> num \<Rightarrow> int \<times> int"
where
"divmod_int m n = (numeral m div numeral n, numeral m mod numeral n)"
definition divmod_step_int :: "int \<Rightarrow> int \<times> int \<Rightarrow> int \<times> int"
where
"divmod_step_int l qr = (let (q, r) = qr
in if \<bar>l\<bar> \<le> \<bar>r\<bar> then (2 * q + 1, r - l)
else (2 * q, r))"
instance
by standard (auto simp add: divmod_int_def divmod_step_int_def)
end
declare divmod_algorithm_code [where ?'a = int, code]
context
begin
qualified definition adjust_div :: "int \<times> int \<Rightarrow> int"
where
"adjust_div qr = (let (q, r) = qr in q + of_bool (r \<noteq> 0))"
qualified lemma adjust_div_eq [simp, code]:
"adjust_div (q, r) = q + of_bool (r \<noteq> 0)"
by (simp add: adjust_div_def)
qualified definition adjust_mod :: "num \<Rightarrow> int \<Rightarrow> int"
where
[simp]: "adjust_mod l r = (if r = 0 then 0 else numeral l - r)"
lemma minus_numeral_div_numeral [simp]:
"- numeral m div numeral n = - (adjust_div (divmod m n) :: int)"
proof -
have "int (fst (divmod m n)) = fst (divmod m n)"
by (simp only: fst_divmod divide_int_def) auto
then show ?thesis
by (auto simp add: split_def Let_def adjust_div_def divides_aux_def divide_int_def)
qed
lemma minus_numeral_mod_numeral [simp]:
"- numeral m mod numeral n = adjust_mod n (snd (divmod m n) :: int)"
proof (cases "snd (divmod m n) = (0::int)")
case True
then show ?thesis
by (simp add: mod_eq_0_iff_dvd divides_aux_def)
next
case False
then have "int (snd (divmod m n)) = snd (divmod m n)" if "snd (divmod m n) \<noteq> (0::int)"
by (simp only: snd_divmod modulo_int_def) auto
then show ?thesis
by (simp add: divides_aux_def adjust_div_def)
(simp add: divides_aux_def modulo_int_def)
qed
lemma numeral_div_minus_numeral [simp]:
"numeral m div - numeral n = - (adjust_div (divmod m n) :: int)"
proof -
have "int (fst (divmod m n)) = fst (divmod m n)"
by (simp only: fst_divmod divide_int_def) auto
then show ?thesis
by (auto simp add: split_def Let_def adjust_div_def divides_aux_def divide_int_def)
qed
lemma numeral_mod_minus_numeral [simp]:
"numeral m mod - numeral n = - adjust_mod n (snd (divmod m n) :: int)"
proof (cases "snd (divmod m n) = (0::int)")
case True
then show ?thesis
by (simp add: mod_eq_0_iff_dvd divides_aux_def)
next
case False
then have "int (snd (divmod m n)) = snd (divmod m n)" if "snd (divmod m n) \<noteq> (0::int)"
by (simp only: snd_divmod modulo_int_def) auto
then show ?thesis
by (simp add: divides_aux_def adjust_div_def)
(simp add: divides_aux_def modulo_int_def)
qed
lemma minus_one_div_numeral [simp]:
"- 1 div numeral n = - (adjust_div (divmod Num.One n) :: int)"
using minus_numeral_div_numeral [of Num.One n] by simp
lemma minus_one_mod_numeral [simp]:
"- 1 mod numeral n = adjust_mod n (snd (divmod Num.One n) :: int)"
using minus_numeral_mod_numeral [of Num.One n] by simp
lemma one_div_minus_numeral [simp]:
"1 div - numeral n = - (adjust_div (divmod Num.One n) :: int)"
using numeral_div_minus_numeral [of Num.One n] by simp
lemma one_mod_minus_numeral [simp]:
"1 mod - numeral n = - adjust_mod n (snd (divmod Num.One n) :: int)"
using numeral_mod_minus_numeral [of Num.One n] by simp
end
lemma divmod_BitM_2_eq [simp]:
\<open>divmod (Num.BitM m) (Num.Bit0 Num.One) = (numeral m - 1, (1 :: int))\<close>
by (cases m) simp_all
subsubsection \<open>Computation by simplification\<close>
lemma euclidean_size_nat_less_eq_iff:
\<open>euclidean_size m \<le> euclidean_size n \<longleftrightarrow> m \<le> n\<close> for m n :: nat
by simp
lemma euclidean_size_int_less_eq_iff:
\<open>euclidean_size k \<le> euclidean_size l \<longleftrightarrow> \<bar>k\<bar> \<le> \<bar>l\<bar>\<close> for k l :: int
by auto
simproc_setup numeral_divmod
("0 div 0 :: 'a :: unique_euclidean_semiring_with_nat_division" | "0 mod 0 :: 'a :: unique_euclidean_semiring_with_nat_division" |
"0 div 1 :: 'a :: unique_euclidean_semiring_with_nat_division" | "0 mod 1 :: 'a :: unique_euclidean_semiring_with_nat_division" |
"0 div - 1 :: int" | "0 mod - 1 :: int" |
"0 div numeral b :: 'a :: unique_euclidean_semiring_with_nat_division" | "0 mod numeral b :: 'a :: unique_euclidean_semiring_with_nat_division" |
"0 div - numeral b :: int" | "0 mod - numeral b :: int" |
"1 div 0 :: 'a :: unique_euclidean_semiring_with_nat_division" | "1 mod 0 :: 'a :: unique_euclidean_semiring_with_nat_division" |
"1 div 1 :: 'a :: unique_euclidean_semiring_with_nat_division" | "1 mod 1 :: 'a :: unique_euclidean_semiring_with_nat_division" |
"1 div - 1 :: int" | "1 mod - 1 :: int" |
"1 div numeral b :: 'a :: unique_euclidean_semiring_with_nat_division" | "1 mod numeral b :: 'a :: unique_euclidean_semiring_with_nat_division" |
"1 div - numeral b :: int" |"1 mod - numeral b :: int" |
"- 1 div 0 :: int" | "- 1 mod 0 :: int" | "- 1 div 1 :: int" | "- 1 mod 1 :: int" |
"- 1 div - 1 :: int" | "- 1 mod - 1 :: int" | "- 1 div numeral b :: int" | "- 1 mod numeral b :: int" |
"- 1 div - numeral b :: int" | "- 1 mod - numeral b :: int" |
"numeral a div 0 :: 'a :: unique_euclidean_semiring_with_nat_division" | "numeral a mod 0 :: 'a :: unique_euclidean_semiring_with_nat_division" |
"numeral a div 1 :: 'a :: unique_euclidean_semiring_with_nat_division" | "numeral a mod 1 :: 'a :: unique_euclidean_semiring_with_nat_division" |
"numeral a div - 1 :: int" | "numeral a mod - 1 :: int" |
"numeral a div numeral b :: 'a :: unique_euclidean_semiring_with_nat_division" | "numeral a mod numeral b :: 'a :: unique_euclidean_semiring_with_nat_division" |
"numeral a div - numeral b :: int" | "numeral a mod - numeral b :: int" |
"- numeral a div 0 :: int" | "- numeral a mod 0 :: int" |
"- numeral a div 1 :: int" | "- numeral a mod 1 :: int" |
"- numeral a div - 1 :: int" | "- numeral a mod - 1 :: int" |
"- numeral a div numeral b :: int" | "- numeral a mod numeral b :: int" |
"- numeral a div - numeral b :: int" | "- numeral a mod - numeral b :: int") = \<open>
let
val if_cong = the (Code.get_case_cong \<^theory> \<^const_name>\<open>If\<close>);
fun successful_rewrite ctxt ct =
let
val thm = Simplifier.rewrite ctxt ct
in if Thm.is_reflexive thm then NONE else SOME thm end;
in fn phi =>
let
val simps = Morphism.fact phi (@{thms div_0 mod_0 div_by_0 mod_by_0 div_by_1 mod_by_1
one_div_numeral one_mod_numeral minus_one_div_numeral minus_one_mod_numeral
one_div_minus_numeral one_mod_minus_numeral
numeral_div_numeral numeral_mod_numeral minus_numeral_div_numeral minus_numeral_mod_numeral
numeral_div_minus_numeral numeral_mod_minus_numeral
div_minus_minus mod_minus_minus Euclidean_Division.adjust_div_eq of_bool_eq one_neq_zero
numeral_neq_zero neg_equal_0_iff_equal arith_simps arith_special divmod_trivial
divmod_cancel divmod_steps divmod_step_def fst_conv snd_conv numeral_One
case_prod_beta rel_simps Euclidean_Division.adjust_mod_def div_minus1_right mod_minus1_right
minus_minus numeral_times_numeral mult_zero_right mult_1_right
euclidean_size_nat_less_eq_iff euclidean_size_int_less_eq_iff diff_nat_numeral nat_numeral}
@ [@{lemma "0 = 0 \<longleftrightarrow> True" by simp}]);
fun prepare_simpset ctxt = HOL_ss |> Simplifier.simpset_map ctxt
(Simplifier.add_cong if_cong #> fold Simplifier.add_simp simps)
in fn ctxt => successful_rewrite (Simplifier.put_simpset (prepare_simpset ctxt) ctxt) end
end
\<close> \<comment> \<open>
There is space for improvement here: the calculation itself
could be carried out outside the logic, and a generic simproc
(simplifier setup) for generic calculation would be helpful.
\<close>
subsubsection \<open>Code generation\<close>
context
begin
qualified definition divmod_nat :: "nat \<Rightarrow> nat \<Rightarrow> nat \<times> nat"
where "divmod_nat m n = (m div n, m mod n)"
qualified lemma divmod_nat_if [code]:
"divmod_nat m n = (if n = 0 \<or> m < n then (0, m) else
let (q, r) = divmod_nat (m - n) n in (Suc q, r))"
by (simp add: divmod_nat_def prod_eq_iff case_prod_beta not_less le_div_geq le_mod_geq)
qualified lemma [code]:
"m div n = fst (divmod_nat m n)"
"m mod n = snd (divmod_nat m n)"
by (simp_all add: divmod_nat_def)
end
code_identifier
code_module Euclidean_Division \<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith
end
|
library(testthat)
library(tractR)
test_check('tractR')
|
import Smt
theorem contains : "a".contains 'a' := by
smt
sorry
|
/-
Copyright (c) 2019 Jean Lo. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jean Lo, Yaël Dillies, Moritz Doll
! This file was ported from Lean 3 source module analysis.seminorm
! leanprover-community/mathlib commit 832a8ba8f10f11fea99367c469ff802e69a5b8ec
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Real.Pointwise
import Mathbin.Analysis.Convex.Function
import Mathbin.Analysis.LocallyConvex.Basic
import Mathbin.Analysis.Normed.Group.AddTorsor
/-!
# Seminorms
This file defines seminorms.
A seminorm is a function to the reals which is positive-semidefinite, absolutely homogeneous, and
subadditive. They are closely related to convex sets and a topological vector space is locally
convex if and only if its topology is induced by a family of seminorms.
## Main declarations
For a module over a normed ring:
* `seminorm`: A function to the reals that is positive-semidefinite, absolutely homogeneous, and
subadditive.
* `norm_seminorm 𝕜 E`: The norm on `E` as a seminorm.
## References
* [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966]
## Tags
seminorm, locally convex, LCTVS
-/
open NormedField Set
open BigOperators NNReal Pointwise Topology
variable {R R' 𝕜 𝕜₂ 𝕜₃ 𝕝 E E₂ E₃ F G ι : Type _}
/-- A seminorm on a module over a normed ring is a function to the reals that is positive
semidefinite, positive homogeneous, and subadditive. -/
structure Seminorm (𝕜 : Type _) (E : Type _) [SeminormedRing 𝕜] [AddGroup E] [SMul 𝕜 E] extends
AddGroupSeminorm E where
smul' : ∀ (a : 𝕜) (x : E), to_fun (a • x) = ‖a‖ * to_fun x
#align seminorm Seminorm
attribute [nolint doc_blame] Seminorm.toAddGroupSeminorm
/-- `seminorm_class F 𝕜 E` states that `F` is a type of seminorms on the `𝕜`-module E.
You should extend this class when you extend `seminorm`. -/
class SeminormClass (F : Type _) (𝕜 E : outParam <| Type _) [SeminormedRing 𝕜] [AddGroup E]
[SMul 𝕜 E] extends AddGroupSeminormClass F E ℝ where
map_smul_eq_mul (f : F) (a : 𝕜) (x : E) : f (a • x) = ‖a‖ * f x
#align seminorm_class SeminormClass
export SeminormClass (map_smul_eq_mul)
-- `𝕜` is an `out_param`, so this is a false positive.
attribute [nolint dangerous_instance] SeminormClass.toAddGroupSeminormClass
section Of
/-- Alternative constructor for a `seminorm` on an `add_comm_group E` that is a module over a
`semi_norm_ring 𝕜`. -/
def Seminorm.of [SeminormedRing 𝕜] [AddCommGroup E] [Module 𝕜 E] (f : E → ℝ)
(add_le : ∀ x y : E, f (x + y) ≤ f x + f y) (smul : ∀ (a : 𝕜) (x : E), f (a • x) = ‖a‖ * f x) :
Seminorm 𝕜 E where
toFun := f
map_zero' := by rw [← zero_smul 𝕜 (0 : E), smul, norm_zero, MulZeroClass.zero_mul]
add_le' := add_le
smul' := smul
neg' x := by rw [← neg_one_smul 𝕜, smul, norm_neg, ← smul, one_smul]
#align seminorm.of Seminorm.of
/-- Alternative constructor for a `seminorm` over a normed field `𝕜` that only assumes `f 0 = 0`
and an inequality for the scalar multiplication. -/
def Seminorm.ofSmulLe [NormedField 𝕜] [AddCommGroup E] [Module 𝕜 E] (f : E → ℝ) (map_zero : f 0 = 0)
(add_le : ∀ x y, f (x + y) ≤ f x + f y) (smul_le : ∀ (r : 𝕜) (x), f (r • x) ≤ ‖r‖ * f x) :
Seminorm 𝕜 E :=
Seminorm.of f add_le fun r x =>
by
refine' le_antisymm (smul_le r x) _
by_cases r = 0
· simp [h, map_zero]
rw [← mul_le_mul_left (inv_pos.mpr (norm_pos_iff.mpr h))]
rw [inv_mul_cancel_left₀ (norm_ne_zero_iff.mpr h)]
specialize smul_le r⁻¹ (r • x)
rw [norm_inv] at smul_le
convert smul_le
simp [h]
#align seminorm.of_smul_le Seminorm.ofSmulLe
end Of
namespace Seminorm
section SeminormedRing
variable [SeminormedRing 𝕜]
section AddGroup
variable [AddGroup E]
section SMul
variable [SMul 𝕜 E]
instance seminormClass : SeminormClass (Seminorm 𝕜 E) 𝕜 E
where
coe f := f.toFun
coe_injective' f g h := by cases f <;> cases g <;> congr
map_zero f := f.map_zero'
map_add_le_add f := f.add_le'
map_neg_eq_map f := f.neg'
map_smul_eq_mul f := f.smul'
#align seminorm.seminorm_class Seminorm.seminormClass
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`. -/
instance : CoeFun (Seminorm 𝕜 E) fun _ => E → ℝ :=
FunLike.hasCoeToFun
@[ext]
theorem ext {p q : Seminorm 𝕜 E} (h : ∀ x, (p : E → ℝ) x = q x) : p = q :=
FunLike.ext p q h
#align seminorm.ext Seminorm.ext
instance : Zero (Seminorm 𝕜 E) :=
⟨{ AddGroupSeminorm.hasZero.zero with smul' := fun _ _ => (MulZeroClass.mul_zero _).symm }⟩
@[simp]
theorem coe_zero : ⇑(0 : Seminorm 𝕜 E) = 0 :=
rfl
#align seminorm.coe_zero Seminorm.coe_zero
@[simp]
theorem zero_apply (x : E) : (0 : Seminorm 𝕜 E) x = 0 :=
rfl
#align seminorm.zero_apply Seminorm.zero_apply
instance : Inhabited (Seminorm 𝕜 E) :=
⟨0⟩
variable (p : Seminorm 𝕜 E) (c : 𝕜) (x y : E) (r : ℝ)
/-- Any action on `ℝ` which factors through `ℝ≥0` applies to a seminorm. -/
instance [SMul R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ] : SMul R (Seminorm 𝕜 E)
where smul r p :=
{ r • p.toAddGroupSeminorm with
toFun := fun x => r • p x
smul' := fun _ _ =>
by
simp only [← smul_one_smul ℝ≥0 r (_ : ℝ), NNReal.smul_def, smul_eq_mul]
rw [map_smul_eq_mul, mul_left_comm] }
instance [SMul R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ] [SMul R' ℝ] [SMul R' ℝ≥0]
[IsScalarTower R' ℝ≥0 ℝ] [SMul R R'] [IsScalarTower R R' ℝ] : IsScalarTower R R' (Seminorm 𝕜 E)
where smul_assoc r a p := ext fun x => smul_assoc r a (p x)
theorem coe_smul [SMul R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ] (r : R) (p : Seminorm 𝕜 E) :
⇑(r • p) = r • p :=
rfl
#align seminorm.coe_smul Seminorm.coe_smul
@[simp]
theorem smul_apply [SMul R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ] (r : R) (p : Seminorm 𝕜 E)
(x : E) : (r • p) x = r • p x :=
rfl
#align seminorm.smul_apply Seminorm.smul_apply
instance : Add (Seminorm 𝕜 E)
where add p q :=
{
p.toAddGroupSeminorm +
q.toAddGroupSeminorm with
toFun := fun x => p x + q x
smul' := fun a x => by simp only [map_smul_eq_mul, map_smul_eq_mul, mul_add] }
theorem coe_add (p q : Seminorm 𝕜 E) : ⇑(p + q) = p + q :=
rfl
#align seminorm.coe_add Seminorm.coe_add
@[simp]
theorem add_apply (p q : Seminorm 𝕜 E) (x : E) : (p + q) x = p x + q x :=
rfl
#align seminorm.add_apply Seminorm.add_apply
instance : AddMonoid (Seminorm 𝕜 E) :=
FunLike.coe_injective.AddMonoid _ rfl coe_add fun p n => coe_smul n p
instance : OrderedCancelAddCommMonoid (Seminorm 𝕜 E) :=
FunLike.coe_injective.OrderedCancelAddCommMonoid _ rfl coe_add fun p n => coe_smul n p
instance [Monoid R] [MulAction R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ] :
MulAction R (Seminorm 𝕜 E) :=
FunLike.coe_injective.MulAction _ coe_smul
variable (𝕜 E)
/-- `coe_fn` as an `add_monoid_hom`. Helper definition for showing that `seminorm 𝕜 E` is
a module. -/
@[simps]
def coeFnAddMonoidHom : AddMonoidHom (Seminorm 𝕜 E) (E → ℝ) :=
⟨coeFn, coe_zero, coe_add⟩
#align seminorm.coe_fn_add_monoid_hom Seminorm.coeFnAddMonoidHom
theorem coeFnAddMonoidHom_injective : Function.Injective (coeFnAddMonoidHom 𝕜 E) :=
show @Function.Injective (Seminorm 𝕜 E) (E → ℝ) coeFn from FunLike.coe_injective
#align seminorm.coe_fn_add_monoid_hom_injective Seminorm.coeFnAddMonoidHom_injective
variable {𝕜 E}
instance [Monoid R] [DistribMulAction R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ] :
DistribMulAction R (Seminorm 𝕜 E) :=
(coeFnAddMonoidHom_injective 𝕜 E).DistribMulAction _ coe_smul
instance [Semiring R] [Module R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ] : Module R (Seminorm 𝕜 E) :=
(coeFnAddMonoidHom_injective 𝕜 E).Module R _ coe_smul
instance : Sup (Seminorm 𝕜 E)
where sup p q :=
{
p.toAddGroupSeminorm ⊔ q.toAddGroupSeminorm with
toFun := p ⊔ q
smul' := fun x v =>
(congr_arg₂ max (map_smul_eq_mul p x v) (map_smul_eq_mul q x v)).trans <|
(mul_max_of_nonneg _ _ <| norm_nonneg x).symm }
@[simp]
theorem coe_sup (p q : Seminorm 𝕜 E) : ⇑(p ⊔ q) = p ⊔ q :=
rfl
#align seminorm.coe_sup Seminorm.coe_sup
theorem sup_apply (p q : Seminorm 𝕜 E) (x : E) : (p ⊔ q) x = p x ⊔ q x :=
rfl
#align seminorm.sup_apply Seminorm.sup_apply
theorem smul_sup [SMul R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ] (r : R) (p q : Seminorm 𝕜 E) :
r • (p ⊔ q) = r • p ⊔ r • q :=
have real.smul_max : ∀ x y : ℝ, r • max x y = max (r • x) (r • y) := fun x y => by
simpa only [← smul_eq_mul, ← NNReal.smul_def, smul_one_smul ℝ≥0 r (_ : ℝ)] using
mul_max_of_nonneg x y (r • 1 : ℝ≥0).Prop
ext fun x => real.smul_max _ _
#align seminorm.smul_sup Seminorm.smul_sup
instance : PartialOrder (Seminorm 𝕜 E) :=
PartialOrder.lift _ FunLike.coe_injective
theorem le_def (p q : Seminorm 𝕜 E) : p ≤ q ↔ (p : E → ℝ) ≤ q :=
Iff.rfl
#align seminorm.le_def Seminorm.le_def
theorem lt_def (p q : Seminorm 𝕜 E) : p < q ↔ (p : E → ℝ) < q :=
Iff.rfl
#align seminorm.lt_def Seminorm.lt_def
instance : SemilatticeSup (Seminorm 𝕜 E) :=
Function.Injective.semilatticeSup _ FunLike.coe_injective coe_sup
end SMul
end AddGroup
section Module
variable [SeminormedRing 𝕜₂] [SeminormedRing 𝕜₃]
variable {σ₁₂ : 𝕜 →+* 𝕜₂} [RingHomIsometric σ₁₂]
variable {σ₂₃ : 𝕜₂ →+* 𝕜₃} [RingHomIsometric σ₂₃]
variable {σ₁₃ : 𝕜 →+* 𝕜₃} [RingHomIsometric σ₁₃]
variable [AddCommGroup E] [AddCommGroup E₂] [AddCommGroup E₃]
variable [AddCommGroup F] [AddCommGroup G]
variable [Module 𝕜 E] [Module 𝕜₂ E₂] [Module 𝕜₃ E₃] [Module 𝕜 F] [Module 𝕜 G]
variable [SMul R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ]
/-- Composition of a seminorm with a linear map is a seminorm. -/
def comp (p : Seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) : Seminorm 𝕜 E :=
{
p.toAddGroupSeminorm.comp
f.toAddMonoidHom with
toFun := fun x => p (f x)
smul' := fun _ _ => by rw [map_smulₛₗ, map_smul_eq_mul, RingHomIsometric.is_iso] }
#align seminorm.comp Seminorm.comp
theorem coe_comp (p : Seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) : ⇑(p.comp f) = p ∘ f :=
rfl
#align seminorm.coe_comp Seminorm.coe_comp
@[simp]
theorem comp_apply (p : Seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (x : E) : (p.comp f) x = p (f x) :=
rfl
#align seminorm.comp_apply Seminorm.comp_apply
@[simp]
theorem comp_id (p : Seminorm 𝕜 E) : p.comp LinearMap.id = p :=
ext fun _ => rfl
#align seminorm.comp_id Seminorm.comp_id
@[simp]
theorem comp_zero (p : Seminorm 𝕜₂ E₂) : p.comp (0 : E →ₛₗ[σ₁₂] E₂) = 0 :=
ext fun _ => map_zero p
#align seminorm.comp_zero Seminorm.comp_zero
@[simp]
theorem zero_comp (f : E →ₛₗ[σ₁₂] E₂) : (0 : Seminorm 𝕜₂ E₂).comp f = 0 :=
ext fun _ => rfl
#align seminorm.zero_comp Seminorm.zero_comp
theorem comp_comp [RingHomCompTriple σ₁₂ σ₂₃ σ₁₃] (p : Seminorm 𝕜₃ E₃) (g : E₂ →ₛₗ[σ₂₃] E₃)
(f : E →ₛₗ[σ₁₂] E₂) : p.comp (g.comp f) = (p.comp g).comp f :=
ext fun _ => rfl
#align seminorm.comp_comp Seminorm.comp_comp
theorem add_comp (p q : Seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) :
(p + q).comp f = p.comp f + q.comp f :=
ext fun _ => rfl
#align seminorm.add_comp Seminorm.add_comp
theorem comp_add_le (p : Seminorm 𝕜₂ E₂) (f g : E →ₛₗ[σ₁₂] E₂) :
p.comp (f + g) ≤ p.comp f + p.comp g := fun _ => map_add_le_add p _ _
#align seminorm.comp_add_le Seminorm.comp_add_le
theorem smul_comp (p : Seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (c : R) :
(c • p).comp f = c • p.comp f :=
ext fun _ => rfl
#align seminorm.smul_comp Seminorm.smul_comp
theorem comp_mono {p q : Seminorm 𝕜₂ E₂} (f : E →ₛₗ[σ₁₂] E₂) (hp : p ≤ q) : p.comp f ≤ q.comp f :=
fun _ => hp _
#align seminorm.comp_mono Seminorm.comp_mono
/-- The composition as an `add_monoid_hom`. -/
@[simps]
def pullback (f : E →ₛₗ[σ₁₂] E₂) : Seminorm 𝕜₂ E₂ →+ Seminorm 𝕜 E :=
⟨fun p => p.comp f, zero_comp f, fun p q => add_comp p q f⟩
#align seminorm.pullback Seminorm.pullback
instance : OrderBot (Seminorm 𝕜 E) :=
⟨0, map_nonneg⟩
@[simp]
theorem coe_bot : ⇑(⊥ : Seminorm 𝕜 E) = 0 :=
rfl
#align seminorm.coe_bot Seminorm.coe_bot
theorem bot_eq_zero : (⊥ : Seminorm 𝕜 E) = 0 :=
rfl
#align seminorm.bot_eq_zero Seminorm.bot_eq_zero
theorem smul_le_smul {p q : Seminorm 𝕜 E} {a b : ℝ≥0} (hpq : p ≤ q) (hab : a ≤ b) : a • p ≤ b • q :=
by
simp_rw [le_def, Pi.le_def, coe_smul]
intro x
simp_rw [Pi.smul_apply, NNReal.smul_def, smul_eq_mul]
exact mul_le_mul hab (hpq x) (map_nonneg p x) (NNReal.coe_nonneg b)
#align seminorm.smul_le_smul Seminorm.smul_le_smul
theorem finset_sup_apply (p : ι → Seminorm 𝕜 E) (s : Finset ι) (x : E) :
s.sup p x = ↑(s.sup fun i => ⟨p i x, map_nonneg (p i) x⟩ : ℝ≥0) :=
by
induction' s using Finset.cons_induction_on with a s ha ih
·
rw [Finset.sup_empty, Finset.sup_empty, coe_bot, _root_.bot_eq_zero, Pi.zero_apply,
Nonneg.coe_zero]
·
rw [Finset.sup_cons, Finset.sup_cons, coe_sup, sup_eq_max, Pi.sup_apply, sup_eq_max,
NNReal.coe_max, Subtype.coe_mk, ih]
#align seminorm.finset_sup_apply Seminorm.finset_sup_apply
theorem finset_sup_le_sum (p : ι → Seminorm 𝕜 E) (s : Finset ι) : s.sup p ≤ ∑ i in s, p i := by
classical
refine' finset.sup_le_iff.mpr _
intro i hi
rw [Finset.sum_eq_sum_diff_singleton_add hi, le_add_iff_nonneg_left]
exact bot_le
#align seminorm.finset_sup_le_sum Seminorm.finset_sup_le_sum
theorem finset_sup_apply_le {p : ι → Seminorm 𝕜 E} {s : Finset ι} {x : E} {a : ℝ} (ha : 0 ≤ a)
(h : ∀ i, i ∈ s → p i x ≤ a) : s.sup p x ≤ a :=
by
lift a to ℝ≥0 using ha
rw [finset_sup_apply, NNReal.coe_le_coe]
exact Finset.sup_le h
#align seminorm.finset_sup_apply_le Seminorm.finset_sup_apply_le
theorem finset_sup_apply_lt {p : ι → Seminorm 𝕜 E} {s : Finset ι} {x : E} {a : ℝ} (ha : 0 < a)
(h : ∀ i, i ∈ s → p i x < a) : s.sup p x < a :=
by
lift a to ℝ≥0 using ha.le
rw [finset_sup_apply, NNReal.coe_lt_coe, Finset.sup_lt_iff]
· exact h
· exact nnreal.coe_pos.mpr ha
#align seminorm.finset_sup_apply_lt Seminorm.finset_sup_apply_lt
theorem norm_sub_map_le_sub (p : Seminorm 𝕜 E) (x y : E) : ‖p x - p y‖ ≤ p (x - y) :=
abs_sub_map_le_sub p x y
#align seminorm.norm_sub_map_le_sub Seminorm.norm_sub_map_le_sub
end Module
end SeminormedRing
section SeminormedCommRing
variable [SeminormedRing 𝕜] [SeminormedCommRing 𝕜₂]
variable {σ₁₂ : 𝕜 →+* 𝕜₂} [RingHomIsometric σ₁₂]
variable [AddCommGroup E] [AddCommGroup E₂] [Module 𝕜 E] [Module 𝕜₂ E₂]
theorem comp_smul (p : Seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (c : 𝕜₂) :
p.comp (c • f) = ‖c‖₊ • p.comp f :=
ext fun _ => by
rw [comp_apply, smul_apply, LinearMap.smul_apply, map_smul_eq_mul, NNReal.smul_def, coe_nnnorm,
smul_eq_mul, comp_apply]
#align seminorm.comp_smul Seminorm.comp_smul
theorem comp_smul_apply (p : Seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (c : 𝕜₂) (x : E) :
p.comp (c • f) x = ‖c‖ * p (f x) :=
map_smul_eq_mul p _ _
#align seminorm.comp_smul_apply Seminorm.comp_smul_apply
end SeminormedCommRing
section NormedField
variable [NormedField 𝕜] [AddCommGroup E] [Module 𝕜 E] {p q : Seminorm 𝕜 E} {x : E}
/-- Auxiliary lemma to show that the infimum of seminorms is well-defined. -/
theorem bddBelow_range_add : BddBelow (range fun u => p u + q (x - u)) :=
⟨0, by
rintro _ ⟨x, rfl⟩
dsimp
positivity⟩
#align seminorm.bdd_below_range_add Seminorm.bddBelow_range_add
noncomputable instance : Inf (Seminorm 𝕜 E)
where inf p q :=
{
p.toAddGroupSeminorm ⊓
q.toAddGroupSeminorm with
toFun := fun x => ⨅ u : E, p u + q (x - u)
smul' := by
intro a x
obtain rfl | ha := eq_or_ne a 0
· rw [norm_zero, MulZeroClass.zero_mul, zero_smul]
refine'
cinfᵢ_eq_of_forall_ge_of_forall_gt_exists_lt (fun i => by positivity) fun x hx =>
⟨0, by rwa [map_zero, sub_zero, map_zero, add_zero]⟩
simp_rw [Real.mul_infᵢ_of_nonneg (norm_nonneg a), mul_add, ← map_smul_eq_mul p, ←
map_smul_eq_mul q, smul_sub]
refine'
Function.Surjective.infᵢ_congr ((· • ·) a⁻¹ : E → E)
(fun u => ⟨a • u, inv_smul_smul₀ ha u⟩) fun u => _
rw [smul_inv_smul₀ ha] }
@[simp]
theorem inf_apply (p q : Seminorm 𝕜 E) (x : E) : (p ⊓ q) x = ⨅ u : E, p u + q (x - u) :=
rfl
#align seminorm.inf_apply Seminorm.inf_apply
noncomputable instance : Lattice (Seminorm 𝕜 E) :=
{ Seminorm.semilatticeSup with
inf := (· ⊓ ·)
inf_le_left := fun p q x =>
cinfᵢ_le_of_le bddBelow_range_add x <| by simp only [sub_self, map_zero, add_zero]
inf_le_right := fun p q x =>
cinfᵢ_le_of_le bddBelow_range_add 0 <| by simp only [sub_self, map_zero, zero_add, sub_zero]
le_inf := fun a b c hab hac x =>
le_cinfᵢ fun u => (le_map_add_map_sub a _ _).trans <| add_le_add (hab _) (hac _) }
theorem smul_inf [SMul R ℝ] [SMul R ℝ≥0] [IsScalarTower R ℝ≥0 ℝ] (r : R) (p q : Seminorm 𝕜 E) :
r • (p ⊓ q) = r • p ⊓ r • q := by
ext
simp_rw [smul_apply, inf_apply, smul_apply, ← smul_one_smul ℝ≥0 r (_ : ℝ), NNReal.smul_def,
smul_eq_mul, Real.mul_infᵢ_of_nonneg (Subtype.prop _), mul_add]
#align seminorm.smul_inf Seminorm.smul_inf
section Classical
open Classical
/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:73:14: unsupported tactic `congrm #[[expr «expr⨆ , »((i), _)]] -/
/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:73:14: unsupported tactic `congrm #[[expr «expr⨆ , »((i), _)]] -/
/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:73:14: unsupported tactic `congrm #[[expr «expr⨆ , »((i), _)]] -/
/-- We define the supremum of an arbitrary subset of `seminorm 𝕜 E` as follows:
* if `s` is `bdd_above` *as a set of functions `E → ℝ`* (that is, if `s` is pointwise bounded
above), we take the pointwise supremum of all elements of `s`, and we prove that it is indeed a
seminorm.
* otherwise, we take the zero seminorm `⊥`.
There are two things worth mentionning here:
* First, it is not trivial at first that `s` being bounded above *by a function* implies
being bounded above *as a seminorm*. We show this in `seminorm.bdd_above_iff` by using
that the `Sup s` as defined here is then a bounding seminorm for `s`. So it is important to make
the case disjunction on `bdd_above (coe_fn '' s : set (E → ℝ))` and not `bdd_above s`.
* Since the pointwise `Sup` already gives `0` at points where a family of functions is
not bounded above, one could hope that just using the pointwise `Sup` would work here, without the
need for an additional case disjunction. As discussed on Zulip, this doesn't work because this can
give a function which does *not* satisfy the seminorm axioms (typically sub-additivity).
-/
noncomputable instance : SupSet (Seminorm 𝕜 E)
where supₛ s :=
if h : BddAbove (coeFn '' s : Set (E → ℝ)) then
{ toFun := ⨆ p : s, ((p : Seminorm 𝕜 E) : E → ℝ)
map_zero' := by
rw [supᵢ_apply, ← @Real.csupᵢ_const_zero s]
trace
"./././Mathport/Syntax/Translate/Tactic/Builtin.lean:73:14: unsupported tactic `congrm #[[expr «expr⨆ , »((i), _)]]"
exact map_zero i.1
add_le' := fun x y => by
rcases h with ⟨q, hq⟩
obtain rfl | h := s.eq_empty_or_nonempty
· simp [Real.csupᵢ_empty]
haveI : Nonempty ↥s := h.coe_sort
simp only [supᵢ_apply]
refine'
csupᵢ_le fun i =>
((i : Seminorm 𝕜 E).add_le' x y).trans <|
add_le_add (le_csupᵢ ⟨q x, _⟩ i) (le_csupᵢ ⟨q y, _⟩ i) <;>
rw [mem_upperBounds, forall_range_iff] <;>
exact fun j => hq (mem_image_of_mem _ j.2) _
neg' := fun x => by
simp only [supᵢ_apply]
trace
"./././Mathport/Syntax/Translate/Tactic/Builtin.lean:73:14: unsupported tactic `congrm #[[expr «expr⨆ , »((i), _)]]"
exact i.1.neg' _
smul' := fun a x => by
simp only [supᵢ_apply]
rw [← smul_eq_mul,
Real.smul_supᵢ_of_nonneg (norm_nonneg a) fun i : s => (i : Seminorm 𝕜 E) x]
trace
"./././Mathport/Syntax/Translate/Tactic/Builtin.lean:73:14: unsupported tactic `congrm #[[expr «expr⨆ , »((i), _)]]"
exact i.1.smul' a x }
else ⊥
protected theorem coe_supₛ_eq' {s : Set <| Seminorm 𝕜 E}
(hs : BddAbove (coeFn '' s : Set (E → ℝ))) : coeFn (supₛ s) = ⨆ p : s, p :=
congr_arg _ (dif_pos hs)
#align seminorm.coe_Sup_eq' Seminorm.coe_supₛ_eq'
protected theorem bddAbove_iff {s : Set <| Seminorm 𝕜 E} :
BddAbove s ↔ BddAbove (coeFn '' s : Set (E → ℝ)) :=
⟨fun ⟨q, hq⟩ => ⟨q, ball_image_of_ball fun p hp => hq hp⟩, fun H =>
⟨supₛ s, fun p hp x => by
rw [Seminorm.coe_supₛ_eq' H, supᵢ_apply]
rcases H with ⟨q, hq⟩
exact
le_csupᵢ ⟨q x, forall_range_iff.mpr fun i : s => hq (mem_image_of_mem _ i.2) x⟩ ⟨p, hp⟩⟩⟩
#align seminorm.bdd_above_iff Seminorm.bddAbove_iff
protected theorem coe_supₛ_eq {s : Set <| Seminorm 𝕜 E} (hs : BddAbove s) :
coeFn (supₛ s) = ⨆ p : s, p :=
Seminorm.coe_supₛ_eq' (Seminorm.bddAbove_iff.mp hs)
#align seminorm.coe_Sup_eq Seminorm.coe_supₛ_eq
protected theorem coe_supᵢ_eq {ι : Type _} {p : ι → Seminorm 𝕜 E} (hp : BddAbove (range p)) :
coeFn (⨆ i, p i) = ⨆ i, p i := by
rw [← supₛ_range, Seminorm.coe_supₛ_eq hp] <;> exact supᵢ_range' (coeFn : Seminorm 𝕜 E → E → ℝ) p
#align seminorm.coe_supr_eq Seminorm.coe_supᵢ_eq
private theorem seminorm.is_lub_Sup (s : Set (Seminorm 𝕜 E)) (hs₁ : BddAbove s) (hs₂ : s.Nonempty) :
IsLUB s (supₛ s) :=
by
refine' ⟨fun p hp x => _, fun p hp x => _⟩ <;> haveI : Nonempty ↥s := hs₂.coe_sort <;>
rw [Seminorm.coe_supₛ_eq hs₁, supᵢ_apply]
· rcases hs₁ with ⟨q, hq⟩
exact le_csupᵢ ⟨q x, forall_range_iff.mpr fun i : s => hq i.2 x⟩ ⟨p, hp⟩
· exact csupᵢ_le fun q => hp q.2 x
#align seminorm.seminorm.is_lub_Sup seminorm.seminorm.is_lub_Sup
/-- `seminorm 𝕜 E` is a conditionally complete lattice.
Note that, while `inf`, `sup` and `Sup` have good definitional properties (corresponding to
`seminorm.has_inf`, `seminorm.has_sup` and `seminorm.has_Sup` respectively), `Inf s` is just
defined as the supremum of the lower bounds of `s`, which is not really useful in practice. If you
need to use `Inf` on seminorms, then you should probably provide a more workable definition first,
but this is unlikely to happen so we keep the "bad" definition for now. -/
noncomputable instance : ConditionallyCompleteLattice (Seminorm 𝕜 E) :=
conditionallyCompleteLatticeOfLatticeOfSupₛ (Seminorm 𝕜 E) Seminorm.isLUB_supₛ
end Classical
end NormedField
/-! ### Seminorm ball -/
section SeminormedRing
variable [SeminormedRing 𝕜]
section AddCommGroup
variable [AddCommGroup E]
section SMul
variable [SMul 𝕜 E] (p : Seminorm 𝕜 E)
/-- The ball of radius `r` at `x` with respect to seminorm `p` is the set of elements `y` with
`p (y - x) < r`. -/
def ball (x : E) (r : ℝ) :=
{ y : E | p (y - x) < r }
#align seminorm.ball Seminorm.ball
/-- The closed ball of radius `r` at `x` with respect to seminorm `p` is the set of elements `y`
with `p (y - x) ≤ r`. -/
def closedBall (x : E) (r : ℝ) :=
{ y : E | p (y - x) ≤ r }
#align seminorm.closed_ball Seminorm.closedBall
variable {x y : E} {r : ℝ}
@[simp]
theorem mem_ball : y ∈ ball p x r ↔ p (y - x) < r :=
Iff.rfl
#align seminorm.mem_ball Seminorm.mem_ball
@[simp]
theorem mem_closedBall : y ∈ closedBall p x r ↔ p (y - x) ≤ r :=
Iff.rfl
#align seminorm.mem_closed_ball Seminorm.mem_closedBall
theorem mem_ball_self (hr : 0 < r) : x ∈ ball p x r := by simp [hr]
#align seminorm.mem_ball_self Seminorm.mem_ball_self
theorem mem_closedBall_self (hr : 0 ≤ r) : x ∈ closedBall p x r := by simp [hr]
#align seminorm.mem_closed_ball_self Seminorm.mem_closedBall_self
theorem mem_ball_zero : y ∈ ball p 0 r ↔ p y < r := by rw [mem_ball, sub_zero]
#align seminorm.mem_ball_zero Seminorm.mem_ball_zero
theorem mem_closedBall_zero : y ∈ closedBall p 0 r ↔ p y ≤ r := by rw [mem_closed_ball, sub_zero]
#align seminorm.mem_closed_ball_zero Seminorm.mem_closedBall_zero
theorem ball_zero_eq : ball p 0 r = { y : E | p y < r } :=
Set.ext fun x => p.mem_ball_zero
#align seminorm.ball_zero_eq Seminorm.ball_zero_eq
theorem closedBall_zero_eq : closedBall p 0 r = { y : E | p y ≤ r } :=
Set.ext fun x => p.mem_closedBall_zero
#align seminorm.closed_ball_zero_eq Seminorm.closedBall_zero_eq
theorem ball_subset_closedBall (x r) : ball p x r ⊆ closedBall p x r := fun y (hy : _ < _) => hy.le
#align seminorm.ball_subset_closed_ball Seminorm.ball_subset_closedBall
theorem closedBall_eq_bInter_ball (x r) : closedBall p x r = ⋂ ρ > r, ball p x ρ := by
ext y <;> simp_rw [mem_closed_ball, mem_Inter₂, mem_ball, ← forall_lt_iff_le']
#align seminorm.closed_ball_eq_bInter_ball Seminorm.closedBall_eq_bInter_ball
@[simp]
theorem ball_zero' (x : E) (hr : 0 < r) : ball (0 : Seminorm 𝕜 E) x r = Set.univ :=
by
rw [Set.eq_univ_iff_forall, ball]
simp [hr]
#align seminorm.ball_zero' Seminorm.ball_zero'
@[simp]
theorem closedBall_zero' (x : E) (hr : 0 < r) : closedBall (0 : Seminorm 𝕜 E) x r = Set.univ :=
eq_univ_of_subset (ball_subset_closedBall _ _ _) (ball_zero' x hr)
#align seminorm.closed_ball_zero' Seminorm.closedBall_zero'
theorem ball_smul (p : Seminorm 𝕜 E) {c : NNReal} (hc : 0 < c) (r : ℝ) (x : E) :
(c • p).ball x r = p.ball x (r / c) := by
ext
rw [mem_ball, mem_ball, smul_apply, NNReal.smul_def, smul_eq_mul, mul_comm,
lt_div_iff (nnreal.coe_pos.mpr hc)]
#align seminorm.ball_smul Seminorm.ball_smul
theorem closedBall_smul (p : Seminorm 𝕜 E) {c : NNReal} (hc : 0 < c) (r : ℝ) (x : E) :
(c • p).closedBall x r = p.closedBall x (r / c) :=
by
ext
rw [mem_closed_ball, mem_closed_ball, smul_apply, NNReal.smul_def, smul_eq_mul, mul_comm,
le_div_iff (nnreal.coe_pos.mpr hc)]
#align seminorm.closed_ball_smul Seminorm.closedBall_smul
theorem ball_sup (p : Seminorm 𝕜 E) (q : Seminorm 𝕜 E) (e : E) (r : ℝ) :
ball (p ⊔ q) e r = ball p e r ∩ ball q e r := by
simp_rw [ball, ← Set.setOf_and, coe_sup, Pi.sup_apply, sup_lt_iff]
#align seminorm.ball_sup Seminorm.ball_sup
theorem closedBall_sup (p : Seminorm 𝕜 E) (q : Seminorm 𝕜 E) (e : E) (r : ℝ) :
closedBall (p ⊔ q) e r = closedBall p e r ∩ closedBall q e r := by
simp_rw [closed_ball, ← Set.setOf_and, coe_sup, Pi.sup_apply, sup_le_iff]
#align seminorm.closed_ball_sup Seminorm.closedBall_sup
theorem ball_finset_sup' (p : ι → Seminorm 𝕜 E) (s : Finset ι) (H : s.Nonempty) (e : E) (r : ℝ) :
ball (s.sup' H p) e r = s.inf' H fun i => ball (p i) e r :=
by
induction' H using Finset.Nonempty.cons_induction with a a s ha hs ih
· classical simp
· rw [Finset.sup'_cons hs, Finset.inf'_cons hs, ball_sup, inf_eq_inter, ih]
#align seminorm.ball_finset_sup' Seminorm.ball_finset_sup'
theorem closedBall_finset_sup' (p : ι → Seminorm 𝕜 E) (s : Finset ι) (H : s.Nonempty) (e : E)
(r : ℝ) : closedBall (s.sup' H p) e r = s.inf' H fun i => closedBall (p i) e r :=
by
induction' H using Finset.Nonempty.cons_induction with a a s ha hs ih
· classical simp
· rw [Finset.sup'_cons hs, Finset.inf'_cons hs, closed_ball_sup, inf_eq_inter, ih]
#align seminorm.closed_ball_finset_sup' Seminorm.closedBall_finset_sup'
theorem ball_mono {p : Seminorm 𝕜 E} {r₁ r₂ : ℝ} (h : r₁ ≤ r₂) : p.ball x r₁ ⊆ p.ball x r₂ :=
fun _ (hx : _ < _) => hx.trans_le h
#align seminorm.ball_mono Seminorm.ball_mono
theorem closedBall_mono {p : Seminorm 𝕜 E} {r₁ r₂ : ℝ} (h : r₁ ≤ r₂) :
p.closedBall x r₁ ⊆ p.closedBall x r₂ := fun _ (hx : _ ≤ _) => hx.trans h
#align seminorm.closed_ball_mono Seminorm.closedBall_mono
theorem ball_antitone {p q : Seminorm 𝕜 E} (h : q ≤ p) : p.ball x r ⊆ q.ball x r := fun _ =>
(h _).trans_lt
#align seminorm.ball_antitone Seminorm.ball_antitone
theorem closedBall_antitone {p q : Seminorm 𝕜 E} (h : q ≤ p) :
p.closedBall x r ⊆ q.closedBall x r := fun _ => (h _).trans
#align seminorm.closed_ball_antitone Seminorm.closedBall_antitone
theorem ball_add_ball_subset (p : Seminorm 𝕜 E) (r₁ r₂ : ℝ) (x₁ x₂ : E) :
p.ball (x₁ : E) r₁ + p.ball (x₂ : E) r₂ ⊆ p.ball (x₁ + x₂) (r₁ + r₂) :=
by
rintro x ⟨y₁, y₂, hy₁, hy₂, rfl⟩
rw [mem_ball, add_sub_add_comm]
exact (map_add_le_add p _ _).trans_lt (add_lt_add hy₁ hy₂)
#align seminorm.ball_add_ball_subset Seminorm.ball_add_ball_subset
theorem closedBall_add_closedBall_subset (p : Seminorm 𝕜 E) (r₁ r₂ : ℝ) (x₁ x₂ : E) :
p.closedBall (x₁ : E) r₁ + p.closedBall (x₂ : E) r₂ ⊆ p.closedBall (x₁ + x₂) (r₁ + r₂) :=
by
rintro x ⟨y₁, y₂, hy₁, hy₂, rfl⟩
rw [mem_closed_ball, add_sub_add_comm]
exact (map_add_le_add p _ _).trans (add_le_add hy₁ hy₂)
#align seminorm.closed_ball_add_closed_ball_subset Seminorm.closedBall_add_closedBall_subset
theorem sub_mem_ball (p : Seminorm 𝕜 E) (x₁ x₂ y : E) (r : ℝ) :
x₁ - x₂ ∈ p.ball y r ↔ x₁ ∈ p.ball (x₂ + y) r := by simp_rw [mem_ball, sub_sub]
#align seminorm.sub_mem_ball Seminorm.sub_mem_ball
/-- The image of a ball under addition with a singleton is another ball. -/
theorem vadd_ball (p : Seminorm 𝕜 E) : x +ᵥ p.ball y r = p.ball (x +ᵥ y) r :=
letI := AddGroupSeminorm.toSeminormedAddCommGroup p.to_add_group_seminorm
Metric.vadd_ball x y r
#align seminorm.vadd_ball Seminorm.vadd_ball
/-- The image of a closed ball under addition with a singleton is another closed ball. -/
theorem vadd_closedBall (p : Seminorm 𝕜 E) : x +ᵥ p.closedBall y r = p.closedBall (x +ᵥ y) r :=
letI := AddGroupSeminorm.toSeminormedAddCommGroup p.to_add_group_seminorm
Metric.vadd_closedBall x y r
#align seminorm.vadd_closed_ball Seminorm.vadd_closedBall
end SMul
section Module
variable [Module 𝕜 E]
variable [SeminormedRing 𝕜₂] [AddCommGroup E₂] [Module 𝕜₂ E₂]
variable {σ₁₂ : 𝕜 →+* 𝕜₂} [RingHomIsometric σ₁₂]
theorem ball_comp (p : Seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (x : E) (r : ℝ) :
(p.comp f).ball x r = f ⁻¹' p.ball (f x) r :=
by
ext
simp_rw [ball, mem_preimage, comp_apply, Set.mem_setOf_eq, map_sub]
#align seminorm.ball_comp Seminorm.ball_comp
theorem closedBall_comp (p : Seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (x : E) (r : ℝ) :
(p.comp f).closedBall x r = f ⁻¹' p.closedBall (f x) r :=
by
ext
simp_rw [closed_ball, mem_preimage, comp_apply, Set.mem_setOf_eq, map_sub]
#align seminorm.closed_ball_comp Seminorm.closedBall_comp
variable (p : Seminorm 𝕜 E)
theorem preimage_metric_ball {r : ℝ} : p ⁻¹' Metric.ball 0 r = { x | p x < r } :=
by
ext x
simp only [mem_set_of, mem_preimage, mem_ball_zero_iff, Real.norm_of_nonneg (map_nonneg p _)]
#align seminorm.preimage_metric_ball Seminorm.preimage_metric_ball
theorem preimage_metric_closedBall {r : ℝ} : p ⁻¹' Metric.closedBall 0 r = { x | p x ≤ r } :=
by
ext x
simp only [mem_set_of, mem_preimage, mem_closedBall_zero_iff,
Real.norm_of_nonneg (map_nonneg p _)]
#align seminorm.preimage_metric_closed_ball Seminorm.preimage_metric_closedBall
theorem ball_zero_eq_preimage_ball {r : ℝ} : p.ball 0 r = p ⁻¹' Metric.ball 0 r := by
rw [ball_zero_eq, preimage_metric_ball]
#align seminorm.ball_zero_eq_preimage_ball Seminorm.ball_zero_eq_preimage_ball
theorem closedBall_zero_eq_preimage_closedBall {r : ℝ} :
p.closedBall 0 r = p ⁻¹' Metric.closedBall 0 r := by
rw [closed_ball_zero_eq, preimage_metric_closed_ball]
#align seminorm.closed_ball_zero_eq_preimage_closed_ball Seminorm.closedBall_zero_eq_preimage_closedBall
@[simp]
theorem ball_bot {r : ℝ} (x : E) (hr : 0 < r) : ball (⊥ : Seminorm 𝕜 E) x r = Set.univ :=
ball_zero' x hr
#align seminorm.ball_bot Seminorm.ball_bot
@[simp]
theorem closedBall_bot {r : ℝ} (x : E) (hr : 0 < r) :
closedBall (⊥ : Seminorm 𝕜 E) x r = Set.univ :=
closedBall_zero' x hr
#align seminorm.closed_ball_bot Seminorm.closedBall_bot
/-- Seminorm-balls at the origin are balanced. -/
theorem balanced_ball_zero (r : ℝ) : Balanced 𝕜 (ball p 0 r) :=
by
rintro a ha x ⟨y, hy, hx⟩
rw [mem_ball_zero, ← hx, map_smul_eq_mul]
calc
_ ≤ p y := mul_le_of_le_one_left (map_nonneg p _) ha
_ < r := by rwa [mem_ball_zero] at hy
#align seminorm.balanced_ball_zero Seminorm.balanced_ball_zero
/-- Closed seminorm-balls at the origin are balanced. -/
theorem balanced_closedBall_zero (r : ℝ) : Balanced 𝕜 (closedBall p 0 r) :=
by
rintro a ha x ⟨y, hy, hx⟩
rw [mem_closed_ball_zero, ← hx, map_smul_eq_mul]
calc
_ ≤ p y := mul_le_of_le_one_left (map_nonneg p _) ha
_ ≤ r := by rwa [mem_closed_ball_zero] at hy
#align seminorm.balanced_closed_ball_zero Seminorm.balanced_closedBall_zero
theorem ball_finset_sup_eq_interᵢ (p : ι → Seminorm 𝕜 E) (s : Finset ι) (x : E) {r : ℝ}
(hr : 0 < r) : ball (s.sup p) x r = ⋂ i ∈ s, ball (p i) x r :=
by
lift r to NNReal using hr.le
simp_rw [ball, Inter_set_of, finset_sup_apply, NNReal.coe_lt_coe,
Finset.sup_lt_iff (show ⊥ < r from hr), ← NNReal.coe_lt_coe, Subtype.coe_mk]
#align seminorm.ball_finset_sup_eq_Inter Seminorm.ball_finset_sup_eq_interᵢ
theorem closedBall_finset_sup_eq_interᵢ (p : ι → Seminorm 𝕜 E) (s : Finset ι) (x : E) {r : ℝ}
(hr : 0 ≤ r) : closedBall (s.sup p) x r = ⋂ i ∈ s, closedBall (p i) x r :=
by
lift r to NNReal using hr
simp_rw [closed_ball, Inter_set_of, finset_sup_apply, NNReal.coe_le_coe, Finset.sup_le_iff, ←
NNReal.coe_le_coe, Subtype.coe_mk]
#align seminorm.closed_ball_finset_sup_eq_Inter Seminorm.closedBall_finset_sup_eq_interᵢ
theorem ball_finset_sup (p : ι → Seminorm 𝕜 E) (s : Finset ι) (x : E) {r : ℝ} (hr : 0 < r) :
ball (s.sup p) x r = s.inf fun i => ball (p i) x r :=
by
rw [Finset.inf_eq_infᵢ]
exact ball_finset_sup_eq_Inter _ _ _ hr
#align seminorm.ball_finset_sup Seminorm.ball_finset_sup
theorem closedBall_finset_sup (p : ι → Seminorm 𝕜 E) (s : Finset ι) (x : E) {r : ℝ} (hr : 0 ≤ r) :
closedBall (s.sup p) x r = s.inf fun i => closedBall (p i) x r :=
by
rw [Finset.inf_eq_infᵢ]
exact closed_ball_finset_sup_eq_Inter _ _ _ hr
#align seminorm.closed_ball_finset_sup Seminorm.closedBall_finset_sup
theorem ball_smul_ball (p : Seminorm 𝕜 E) (r₁ r₂ : ℝ) :
Metric.ball (0 : 𝕜) r₁ • p.ball 0 r₂ ⊆ p.ball 0 (r₁ * r₂) :=
by
rw [Set.subset_def]
intro x hx
rw [Set.mem_smul] at hx
rcases hx with ⟨a, y, ha, hy, hx⟩
rw [← hx, mem_ball_zero, map_smul_eq_mul]
exact
mul_lt_mul'' (mem_ball_zero_iff.mp ha) (p.mem_ball_zero.mp hy) (norm_nonneg a) (map_nonneg p y)
#align seminorm.ball_smul_ball Seminorm.ball_smul_ball
theorem closedBall_smul_closedBall (p : Seminorm 𝕜 E) (r₁ r₂ : ℝ) :
Metric.closedBall (0 : 𝕜) r₁ • p.closedBall 0 r₂ ⊆ p.closedBall 0 (r₁ * r₂) :=
by
rw [Set.subset_def]
intro x hx
rw [Set.mem_smul] at hx
rcases hx with ⟨a, y, ha, hy, hx⟩
rw [← hx, mem_closed_ball_zero, map_smul_eq_mul]
rw [mem_closedBall_zero_iff] at ha
exact mul_le_mul ha (p.mem_closed_ball_zero.mp hy) (map_nonneg _ y) ((norm_nonneg a).trans ha)
#align seminorm.closed_ball_smul_closed_ball Seminorm.closedBall_smul_closedBall
@[simp]
theorem ball_eq_emptyset (p : Seminorm 𝕜 E) {x : E} {r : ℝ} (hr : r ≤ 0) : p.ball x r = ∅ :=
by
ext
rw [Seminorm.mem_ball, Set.mem_empty_iff_false, iff_false_iff, not_lt]
exact hr.trans (map_nonneg p _)
#align seminorm.ball_eq_emptyset Seminorm.ball_eq_emptyset
@[simp]
theorem closedBall_eq_emptyset (p : Seminorm 𝕜 E) {x : E} {r : ℝ} (hr : r < 0) :
p.closedBall x r = ∅ := by
ext
rw [Seminorm.mem_closedBall, Set.mem_empty_iff_false, iff_false_iff, not_le]
exact hr.trans_le (map_nonneg _ _)
#align seminorm.closed_ball_eq_emptyset Seminorm.closedBall_eq_emptyset
end Module
end AddCommGroup
end SeminormedRing
section NormedField
variable [NormedField 𝕜] [AddCommGroup E] [Module 𝕜 E] (p : Seminorm 𝕜 E) {A B : Set E} {a : 𝕜}
{r : ℝ} {x : E}
theorem ball_norm_mul_subset {p : Seminorm 𝕜 E} {k : 𝕜} {r : ℝ} :
p.ball 0 (‖k‖ * r) ⊆ k • p.ball 0 r :=
by
rcases eq_or_ne k 0 with (rfl | hk)
· rw [norm_zero, MulZeroClass.zero_mul, ball_eq_emptyset _ le_rfl]
exact empty_subset _
· intro x
rw [Set.mem_smul_set, Seminorm.mem_ball_zero]
refine' fun hx => ⟨k⁻¹ • x, _, _⟩
·
rwa [Seminorm.mem_ball_zero, map_smul_eq_mul, norm_inv, ←
mul_lt_mul_left <| norm_pos_iff.mpr hk, ← mul_assoc, ← div_eq_mul_inv ‖k‖ ‖k‖,
div_self (ne_of_gt <| norm_pos_iff.mpr hk), one_mul]
rw [← smul_assoc, smul_eq_mul, ← div_eq_mul_inv, div_self hk, one_smul]
#align seminorm.ball_norm_mul_subset Seminorm.ball_norm_mul_subset
theorem smul_ball_zero {p : Seminorm 𝕜 E} {k : 𝕜} {r : ℝ} (hk : k ≠ 0) :
k • p.ball 0 r = p.ball 0 (‖k‖ * r) := by
ext
rw [mem_smul_set_iff_inv_smul_mem₀ hk, p.mem_ball_zero, p.mem_ball_zero, map_smul_eq_mul,
norm_inv, ← div_eq_inv_mul, div_lt_iff (norm_pos_iff.2 hk), mul_comm]
#align seminorm.smul_ball_zero Seminorm.smul_ball_zero
theorem smul_closedBall_subset {p : Seminorm 𝕜 E} {k : 𝕜} {r : ℝ} :
k • p.closedBall 0 r ⊆ p.closedBall 0 (‖k‖ * r) :=
by
rintro x ⟨y, hy, h⟩
rw [Seminorm.mem_closedBall_zero, ← h, map_smul_eq_mul]
rw [Seminorm.mem_closedBall_zero] at hy
exact mul_le_mul_of_nonneg_left hy (norm_nonneg _)
#align seminorm.smul_closed_ball_subset Seminorm.smul_closedBall_subset
theorem smul_closedBall_zero {p : Seminorm 𝕜 E} {k : 𝕜} {r : ℝ} (hk : 0 < ‖k‖) :
k • p.closedBall 0 r = p.closedBall 0 (‖k‖ * r) :=
by
refine' subset_antisymm smul_closed_ball_subset _
intro x
rw [Set.mem_smul_set, Seminorm.mem_closedBall_zero]
refine' fun hx => ⟨k⁻¹ • x, _, _⟩
·
rwa [Seminorm.mem_closedBall_zero, map_smul_eq_mul, norm_inv, ← mul_le_mul_left hk, ← mul_assoc,
← div_eq_mul_inv ‖k‖ ‖k‖, div_self (ne_of_gt hk), one_mul]
rw [← smul_assoc, smul_eq_mul, ← div_eq_mul_inv, div_self (norm_pos_iff.mp hk), one_smul]
#align seminorm.smul_closed_ball_zero Seminorm.smul_closedBall_zero
theorem ball_zero_absorbs_ball_zero (p : Seminorm 𝕜 E) {r₁ r₂ : ℝ} (hr₁ : 0 < r₁) :
Absorbs 𝕜 (p.ball 0 r₁) (p.ball 0 r₂) :=
by
rcases exists_pos_lt_mul hr₁ r₂ with ⟨r, hr₀, hr⟩
refine' ⟨r, hr₀, fun a ha x hx => _⟩
rw [smul_ball_zero (norm_pos_iff.1 <| hr₀.trans_le ha), p.mem_ball_zero]
rw [p.mem_ball_zero] at hx
exact hx.trans (hr.trans_le <| mul_le_mul_of_nonneg_right ha hr₁.le)
#align seminorm.ball_zero_absorbs_ball_zero Seminorm.ball_zero_absorbs_ball_zero
/-- Seminorm-balls at the origin are absorbent. -/
protected theorem absorbent_ball_zero (hr : 0 < r) : Absorbent 𝕜 (ball p (0 : E) r) :=
absorbent_iff_forall_absorbs_singleton.2 fun x =>
(p.ball_zero_absorbs_ball_zero hr).mono_right <|
singleton_subset_iff.2 <| p.mem_ball_zero.2 <| lt_add_one _
#align seminorm.absorbent_ball_zero Seminorm.absorbent_ball_zero
/-- Closed seminorm-balls at the origin are absorbent. -/
protected theorem absorbent_closedBall_zero (hr : 0 < r) : Absorbent 𝕜 (closedBall p (0 : E) r) :=
(p.absorbent_ball_zero hr).Subset (p.ball_subset_closedBall _ _)
#align seminorm.absorbent_closed_ball_zero Seminorm.absorbent_closedBall_zero
/-- Seminorm-balls containing the origin are absorbent. -/
protected theorem absorbent_ball (hpr : p x < r) : Absorbent 𝕜 (ball p x r) :=
by
refine' (p.absorbent_ball_zero <| sub_pos.2 hpr).Subset fun y hy => _
rw [p.mem_ball_zero] at hy
exact p.mem_ball.2 ((map_sub_le_add p _ _).trans_lt <| add_lt_of_lt_sub_right hy)
#align seminorm.absorbent_ball Seminorm.absorbent_ball
/-- Seminorm-balls containing the origin are absorbent. -/
protected theorem absorbent_closedBall (hpr : p x < r) : Absorbent 𝕜 (closedBall p x r) :=
by
refine' (p.absorbent_closed_ball_zero <| sub_pos.2 hpr).Subset fun y hy => _
rw [p.mem_closed_ball_zero] at hy
exact p.mem_closed_ball.2 ((map_sub_le_add p _ _).trans <| add_le_of_le_sub_right hy)
#align seminorm.absorbent_closed_ball Seminorm.absorbent_closedBall
theorem symmetric_ball_zero (r : ℝ) (hx : x ∈ ball p 0 r) : -x ∈ ball p 0 r :=
balanced_ball_zero p r (-1) (by rw [norm_neg, norm_one]) ⟨x, hx, by rw [neg_smul, one_smul]⟩
#align seminorm.symmetric_ball_zero Seminorm.symmetric_ball_zero
@[simp]
theorem neg_ball (p : Seminorm 𝕜 E) (r : ℝ) (x : E) : -ball p x r = ball p (-x) r :=
by
ext
rw [mem_neg, mem_ball, mem_ball, ← neg_add', sub_neg_eq_add, map_neg_eq_map]
#align seminorm.neg_ball Seminorm.neg_ball
@[simp]
theorem smul_ball_preimage (p : Seminorm 𝕜 E) (y : E) (r : ℝ) (a : 𝕜) (ha : a ≠ 0) :
(· • ·) a ⁻¹' p.ball y r = p.ball (a⁻¹ • y) (r / ‖a‖) :=
Set.ext fun _ => by
rw [mem_preimage, mem_ball, mem_ball, lt_div_iff (norm_pos_iff.mpr ha), mul_comm, ←
map_smul_eq_mul p, smul_sub, smul_inv_smul₀ ha]
#align seminorm.smul_ball_preimage Seminorm.smul_ball_preimage
end NormedField
section Convex
variable [NormedField 𝕜] [AddCommGroup E] [NormedSpace ℝ 𝕜] [Module 𝕜 E]
section SMul
variable [SMul ℝ E] [IsScalarTower ℝ 𝕜 E] (p : Seminorm 𝕜 E)
/-- A seminorm is convex. Also see `convex_on_norm`. -/
protected theorem convexOn : ConvexOn ℝ univ p :=
by
refine' ⟨convex_univ, fun x _ y _ a b ha hb hab => _⟩
calc
p (a • x + b • y) ≤ p (a • x) + p (b • y) := map_add_le_add p _ _
_ = ‖a • (1 : 𝕜)‖ * p x + ‖b • (1 : 𝕜)‖ * p y := by
rw [← map_smul_eq_mul p, ← map_smul_eq_mul p, smul_one_smul, smul_one_smul]
_ = a * p x + b * p y := by
rw [norm_smul, norm_smul, norm_one, mul_one, mul_one, Real.norm_of_nonneg ha,
Real.norm_of_nonneg hb]
#align seminorm.convex_on Seminorm.convexOn
end SMul
section Module
variable [Module ℝ E] [IsScalarTower ℝ 𝕜 E] (p : Seminorm 𝕜 E) (x : E) (r : ℝ)
/-- Seminorm-balls are convex. -/
theorem convex_ball : Convex ℝ (ball p x r) :=
by
convert(p.convex_on.translate_left (-x)).convex_lt r
ext y
rw [preimage_univ, sep_univ, p.mem_ball, sub_eq_add_neg]
rfl
#align seminorm.convex_ball Seminorm.convex_ball
/-- Closed seminorm-balls are convex. -/
theorem convex_closedBall : Convex ℝ (closedBall p x r) :=
by
rw [closed_ball_eq_bInter_ball]
exact convex_interᵢ₂ fun _ _ => convex_ball _ _ _
#align seminorm.convex_closed_ball Seminorm.convex_closedBall
end Module
end Convex
section RestrictScalars
variable (𝕜) {𝕜' : Type _} [NormedField 𝕜] [SeminormedRing 𝕜'] [NormedAlgebra 𝕜 𝕜']
[NormOneClass 𝕜'] [AddCommGroup E] [Module 𝕜' E] [SMul 𝕜 E] [IsScalarTower 𝕜 𝕜' E]
/-- Reinterpret a seminorm over a field `𝕜'` as a seminorm over a smaller field `𝕜`. This will
typically be used with `is_R_or_C 𝕜'` and `𝕜 = ℝ`. -/
protected def restrictScalars (p : Seminorm 𝕜' E) : Seminorm 𝕜 E :=
{ p with
smul' := fun a x => by rw [← smul_one_smul 𝕜' a x, p.smul', norm_smul, norm_one, mul_one] }
#align seminorm.restrict_scalars Seminorm.restrictScalars
@[simp]
theorem coe_restrictScalars (p : Seminorm 𝕜' E) : (p.restrictScalars 𝕜 : E → ℝ) = p :=
rfl
#align seminorm.coe_restrict_scalars Seminorm.coe_restrictScalars
@[simp]
theorem restrictScalars_ball (p : Seminorm 𝕜' E) : (p.restrictScalars 𝕜).ball = p.ball :=
rfl
#align seminorm.restrict_scalars_ball Seminorm.restrictScalars_ball
@[simp]
theorem restrictScalars_closedBall (p : Seminorm 𝕜' E) :
(p.restrictScalars 𝕜).closedBall = p.closedBall :=
rfl
#align seminorm.restrict_scalars_closed_ball Seminorm.restrictScalars_closedBall
end RestrictScalars
/-! ### Continuity criterions for seminorms -/
section Continuity
variable [NontriviallyNormedField 𝕜] [SeminormedRing 𝕝] [AddCommGroup E] [Module 𝕜 E]
variable [Module 𝕝 E]
theorem continuousAt_zero' [TopologicalSpace E] [ContinuousConstSMul 𝕜 E] {p : Seminorm 𝕜 E} {r : ℝ}
(hr : 0 < r) (hp : p.closedBall 0 r ∈ (𝓝 0 : Filter E)) : ContinuousAt p 0 :=
by
refine' metric.nhds_basis_closed_ball.tendsto_right_iff.mpr _
intro ε hε
rw [map_zero]
suffices p.closed_ball 0 ε ∈ (𝓝 0 : Filter E) by
rwa [Seminorm.closedBall_zero_eq_preimage_closedBall] at this
rcases exists_norm_lt 𝕜 (div_pos hε hr) with ⟨k, hk0, hkε⟩
have hk0' := norm_pos_iff.mp hk0
have := (set_smul_mem_nhds_zero_iff hk0').mpr hp
refine' Filter.mem_of_superset this (smul_set_subset_iff.mpr fun x hx => _)
rw [mem_closed_ball_zero, map_smul_eq_mul, ← div_mul_cancel ε hr.ne.symm]
exact mul_le_mul hkε.le (p.mem_closed_ball_zero.mp hx) (map_nonneg _ _) (div_nonneg hε.le hr.le)
#align seminorm.continuous_at_zero' Seminorm.continuousAt_zero'
theorem continuousAt_zero [TopologicalSpace E] [ContinuousConstSMul 𝕜 E] {p : Seminorm 𝕜 E} {r : ℝ}
(hr : 0 < r) (hp : p.ball 0 r ∈ (𝓝 0 : Filter E)) : ContinuousAt p 0 :=
continuousAt_zero' hr (Filter.mem_of_superset hp <| p.ball_subset_closedBall _ _)
#align seminorm.continuous_at_zero Seminorm.continuousAt_zero
protected theorem uniformContinuous_of_continuousAt_zero [UniformSpace E] [UniformAddGroup E]
{p : Seminorm 𝕝 E} (hp : ContinuousAt p 0) : UniformContinuous p :=
by
have hp : Filter.Tendsto p (𝓝 0) (𝓝 0) := map_zero p ▸ hp
rw [UniformContinuous, uniformity_eq_comap_nhds_zero_swapped,
Metric.uniformity_eq_comap_nhds_zero, Filter.tendsto_comap_iff]
exact
tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds (hp.comp Filter.tendsto_comap)
(fun xy => dist_nonneg) fun xy => p.norm_sub_map_le_sub _ _
#align seminorm.uniform_continuous_of_continuous_at_zero Seminorm.uniformContinuous_of_continuousAt_zero
protected theorem continuous_of_continuousAt_zero [TopologicalSpace E] [TopologicalAddGroup E]
{p : Seminorm 𝕝 E} (hp : ContinuousAt p 0) : Continuous p :=
by
letI := TopologicalAddGroup.toUniformSpace E
haveI : UniformAddGroup E := comm_topologicalAddGroup_is_uniform
exact (Seminorm.uniformContinuous_of_continuousAt_zero hp).Continuous
#align seminorm.continuous_of_continuous_at_zero Seminorm.continuous_of_continuousAt_zero
protected theorem uniformContinuous [UniformSpace E] [UniformAddGroup E] [ContinuousConstSMul 𝕜 E]
{p : Seminorm 𝕜 E} {r : ℝ} (hr : 0 < r) (hp : p.ball 0 r ∈ (𝓝 0 : Filter E)) :
UniformContinuous p :=
Seminorm.uniformContinuous_of_continuousAt_zero (continuousAt_zero hr hp)
#align seminorm.uniform_continuous Seminorm.uniformContinuous
protected theorem uniform_continuous' [UniformSpace E] [UniformAddGroup E] [ContinuousConstSMul 𝕜 E]
{p : Seminorm 𝕜 E} {r : ℝ} (hr : 0 < r) (hp : p.closedBall 0 r ∈ (𝓝 0 : Filter E)) :
UniformContinuous p :=
Seminorm.uniformContinuous_of_continuousAt_zero (continuousAt_zero' hr hp)
#align seminorm.uniform_continuous' Seminorm.uniform_continuous'
protected theorem continuous [TopologicalSpace E] [TopologicalAddGroup E] [ContinuousConstSMul 𝕜 E]
{p : Seminorm 𝕜 E} {r : ℝ} (hr : 0 < r) (hp : p.ball 0 r ∈ (𝓝 0 : Filter E)) : Continuous p :=
Seminorm.continuous_of_continuousAt_zero (continuousAt_zero hr hp)
#align seminorm.continuous Seminorm.continuous
protected theorem continuous' [TopologicalSpace E] [TopologicalAddGroup E] [ContinuousConstSMul 𝕜 E]
{p : Seminorm 𝕜 E} {r : ℝ} (hr : 0 < r) (hp : p.closedBall 0 r ∈ (𝓝 0 : Filter E)) :
Continuous p :=
Seminorm.continuous_of_continuousAt_zero (continuousAt_zero' hr hp)
#align seminorm.continuous' Seminorm.continuous'
theorem continuous_of_le [TopologicalSpace E] [TopologicalAddGroup E] [ContinuousConstSMul 𝕜 E]
{p q : Seminorm 𝕜 E} (hq : Continuous q) (hpq : p ≤ q) : Continuous p :=
by
refine'
Seminorm.continuous one_pos
(Filter.mem_of_superset (IsOpen.mem_nhds _ <| q.mem_ball_self zero_lt_one)
(ball_antitone hpq))
rw [ball_zero_eq]
exact isOpen_lt hq continuous_const
#align seminorm.continuous_of_le Seminorm.continuous_of_le
end Continuity
end Seminorm
/-! ### The norm as a seminorm -/
section normSeminorm
variable (𝕜) (E) [NormedField 𝕜] [SeminormedAddCommGroup E] [NormedSpace 𝕜 E] {r : ℝ}
/-- The norm of a seminormed group as a seminorm. -/
def normSeminorm : Seminorm 𝕜 E :=
{ normAddGroupSeminorm E with smul' := norm_smul }
#align norm_seminorm normSeminorm
@[simp]
theorem coe_normSeminorm : ⇑(normSeminorm 𝕜 E) = norm :=
rfl
#align coe_norm_seminorm coe_normSeminorm
@[simp]
theorem ball_normSeminorm : (normSeminorm 𝕜 E).ball = Metric.ball :=
by
ext (x r y)
simp only [Seminorm.mem_ball, Metric.mem_ball, coe_normSeminorm, dist_eq_norm]
#align ball_norm_seminorm ball_normSeminorm
variable {𝕜 E} {x : E}
/-- Balls at the origin are absorbent. -/
theorem absorbent_ball_zero (hr : 0 < r) : Absorbent 𝕜 (Metric.ball (0 : E) r) :=
by
rw [← ball_normSeminorm 𝕜]
exact (normSeminorm _ _).absorbent_ball_zero hr
#align absorbent_ball_zero absorbent_ball_zero
/-- Balls containing the origin are absorbent. -/
theorem absorbent_ball (hx : ‖x‖ < r) : Absorbent 𝕜 (Metric.ball x r) :=
by
rw [← ball_normSeminorm 𝕜]
exact (normSeminorm _ _).absorbent_ball hx
#align absorbent_ball absorbent_ball
/-- Balls at the origin are balanced. -/
theorem balanced_ball_zero : Balanced 𝕜 (Metric.ball (0 : E) r) :=
by
rw [← ball_normSeminorm 𝕜]
exact (normSeminorm _ _).balanced_ball_zero r
#align balanced_ball_zero balanced_ball_zero
end normSeminorm
-- Guard against import creep.
assert_not_exists balanced_core
|
I need to have several "individual" emails written. I call up Mortgage Brokers to get them to use me. I have a few written already just need them "polished" up or perhaps with your input trash them and start from scratch.
Great day to you !
This is Michael Masdeo from Greenbox Loans. Just a quick follow up to the voicemail I left for you today.
I’m signing up quite a few brokers in your region and wanted to see if what we offer is a good fit for you.
We have various programs, with our most popular being our Bank Statement loan where we take 100% Deposits and we can co-mingle. In addition we have a Stated income program; (no reserves, no ratios), 1 day out of Foreclosure, Foreign National programs, true Jumbo Fall out & a GREAT Rental Survey program.
We currently have around 12 NON-QM programs.
Greenbox was founded based on the concept of ‘out of the box’ underwriting of residential loans. Many originators & brokers come across borrowers that are a fine credit risks but don’t fit many company government guidelines. We provide real lending solutions for our broker partners with an exception minded mentality.
I would love to have a conversation with you and chat a little about how our relationship will be a beneficial one.
Please let me take a look at any loans that have fallen out OR if you would like pricing on an active or soon to be active Non-QM loans. I’d love to take a look!
Check us out in the July issue of the Scotsman Guide!
ON ANYTHING………WE ARE EXCEPTION BASED!
I then attach the 2 files below.
|
lemma infdist_triangle_abs: "\<bar>infdist x A - infdist y A\<bar> \<le> dist x y"
|
[STATEMENT]
lemma sublist_Nil_right [simp]: "sublist xs [] \<longleftrightarrow> xs = []"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sublist xs [] = (xs = [])
[PROOF STEP]
by (cases xs) auto
|
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
⊢ ∀ (i j : ℕ), ∃ k, I ^ k • ⊤ ≤ I ^ i • ⊤ ⊓ I ^ j • ⊤
[PROOFSTEP]
suffices ∀ i j : ℕ, ∃ k, I ^ k ≤ I ^ i ∧ I ^ k ≤ I ^ j by
simpa only [smul_eq_mul, mul_top, Algebra.id.map_eq_id, map_id, le_inf_iff] using this
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
this : ∀ (i j : ℕ), ∃ k, I ^ k ≤ I ^ i ∧ I ^ k ≤ I ^ j
⊢ ∀ (i j : ℕ), ∃ k, I ^ k • ⊤ ≤ I ^ i • ⊤ ⊓ I ^ j • ⊤
[PROOFSTEP]
simpa only [smul_eq_mul, mul_top, Algebra.id.map_eq_id, map_id, le_inf_iff] using this
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
⊢ ∀ (i j : ℕ), ∃ k, I ^ k ≤ I ^ i ∧ I ^ k ≤ I ^ j
[PROOFSTEP]
intro i j
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
i j : ℕ
⊢ ∃ k, I ^ k ≤ I ^ i ∧ I ^ k ≤ I ^ j
[PROOFSTEP]
exact ⟨max i j, pow_le_pow (le_max_left i j), pow_le_pow (le_max_right i j)⟩
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
⊢ ∀ (a : R) (i : ℕ), ∃ j, a • I ^ j • ⊤ ≤ I ^ i • ⊤
[PROOFSTEP]
suffices ∀ (a : R) (i : ℕ), ∃ j : ℕ, a • I ^ j ≤ I ^ i by
simpa only [smul_top_eq_map, Algebra.id.map_eq_id, map_id] using this
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
this : ∀ (a : R) (i : ℕ), ∃ j, a • I ^ j ≤ I ^ i
⊢ ∀ (a : R) (i : ℕ), ∃ j, a • I ^ j • ⊤ ≤ I ^ i • ⊤
[PROOFSTEP]
simpa only [smul_top_eq_map, Algebra.id.map_eq_id, map_id] using this
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
⊢ ∀ (a : R) (i : ℕ), ∃ j, a • I ^ j ≤ I ^ i
[PROOFSTEP]
intro r n
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
r : R
n : ℕ
⊢ ∃ j, r • I ^ j ≤ I ^ n
[PROOFSTEP]
use n
[GOAL]
case h
R : Type u_1
inst✝ : CommRing R
I : Ideal R
r : R
n : ℕ
⊢ r • I ^ n ≤ I ^ n
[PROOFSTEP]
rintro a ⟨x, hx, rfl⟩
[GOAL]
case h.intro.intro
R : Type u_1
inst✝ : CommRing R
I : Ideal R
r : R
n : ℕ
x : R
hx : x ∈ ↑(I ^ n)
⊢ ↑(DistribMulAction.toLinearMap R R r) x ∈ I ^ n
[PROOFSTEP]
exact (I ^ n).smul_mem r hx
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
⊢ ∀ (i : ℕ), ∃ j, ↑(I ^ j • ⊤) * ↑(I ^ j • ⊤) ⊆ ↑(I ^ i • ⊤)
[PROOFSTEP]
suffices ∀ i : ℕ, ∃ j : ℕ, (I ^ j : Set R) * (I ^ j : Set R) ⊆ (I ^ i : Set R) by
simpa only [smul_top_eq_map, Algebra.id.map_eq_id, map_id] using this
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
this : ∀ (i : ℕ), ∃ j, ↑(I ^ j) * ↑(I ^ j) ⊆ ↑(I ^ i)
⊢ ∀ (i : ℕ), ∃ j, ↑(I ^ j • ⊤) * ↑(I ^ j • ⊤) ⊆ ↑(I ^ i • ⊤)
[PROOFSTEP]
simpa only [smul_top_eq_map, Algebra.id.map_eq_id, map_id] using this
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
⊢ ∀ (i : ℕ), ∃ j, ↑(I ^ j) * ↑(I ^ j) ⊆ ↑(I ^ i)
[PROOFSTEP]
intro n
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
n : ℕ
⊢ ∃ j, ↑(I ^ j) * ↑(I ^ j) ⊆ ↑(I ^ n)
[PROOFSTEP]
use n
[GOAL]
case h
R : Type u_1
inst✝ : CommRing R
I : Ideal R
n : ℕ
⊢ ↑(I ^ n) * ↑(I ^ n) ⊆ ↑(I ^ n)
[PROOFSTEP]
rintro a ⟨x, b, _hx, hb, rfl⟩
[GOAL]
case h.intro.intro.intro.intro
R : Type u_1
inst✝ : CommRing R
I : Ideal R
n : ℕ
x b : R
_hx : x ∈ ↑(I ^ n)
hb : b ∈ ↑(I ^ n)
⊢ (fun x x_1 => x * x_1) x b ∈ ↑(I ^ n)
[PROOFSTEP]
exact (I ^ n).smul_mem x hb
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
⊢ ∀ (t : Set R), t ∈ 𝓝 0 ↔ ∃ i, True ∧ ↑(I ^ i) ⊆ t
[PROOFSTEP]
intro U
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
U : Set R
⊢ U ∈ 𝓝 0 ↔ ∃ i, True ∧ ↑(I ^ i) ⊆ U
[PROOFSTEP]
rw [I.ringFilterBasis.toAddGroupFilterBasis.nhds_zero_hasBasis.mem_iff]
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
U : Set R
⊢ (∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ id i ⊆ U) ↔ ∃ i, True ∧ ↑(I ^ i) ⊆ U
[PROOFSTEP]
constructor
[GOAL]
case mp
R : Type u_1
inst✝ : CommRing R
I : Ideal R
U : Set R
⊢ (∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ id i ⊆ U) → ∃ i, True ∧ ↑(I ^ i) ⊆ U
[PROOFSTEP]
rintro ⟨-, ⟨i, rfl⟩, h⟩
[GOAL]
case mp.intro.intro.intro
R : Type u_1
inst✝ : CommRing R
I : Ideal R
U : Set R
i : ℕ
h : id ↑((fun i => toAddSubgroup (I ^ i • ⊤)) i) ⊆ U
⊢ ∃ i, True ∧ ↑(I ^ i) ⊆ U
[PROOFSTEP]
replace h : ↑(I ^ i) ⊆ U := by simpa using h
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
U : Set R
i : ℕ
h : id ↑((fun i => toAddSubgroup (I ^ i • ⊤)) i) ⊆ U
⊢ ↑(I ^ i) ⊆ U
[PROOFSTEP]
simpa using h
[GOAL]
case mp.intro.intro.intro
R : Type u_1
inst✝ : CommRing R
I : Ideal R
U : Set R
i : ℕ
h : ↑(I ^ i) ⊆ U
⊢ ∃ i, True ∧ ↑(I ^ i) ⊆ U
[PROOFSTEP]
exact ⟨i, trivial, h⟩
[GOAL]
case mpr
R : Type u_1
inst✝ : CommRing R
I : Ideal R
U : Set R
⊢ (∃ i, True ∧ ↑(I ^ i) ⊆ U) → ∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ id i ⊆ U
[PROOFSTEP]
rintro ⟨i, -, h⟩
[GOAL]
case mpr.intro.intro
R : Type u_1
inst✝ : CommRing R
I : Ideal R
U : Set R
i : ℕ
h : ↑(I ^ i) ⊆ U
⊢ ∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ id i ⊆ U
[PROOFSTEP]
exact ⟨(I ^ i : Ideal R), ⟨i, by simp⟩, h⟩
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
U : Set R
i : ℕ
h : ↑(I ^ i) ⊆ U
⊢ ↑(I ^ i) = ↑((fun i => toAddSubgroup (I ^ i • ⊤)) i)
[PROOFSTEP]
simp
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
x : R
⊢ HasBasis (𝓝 x) (fun _n => True) fun n => (fun y => x + y) '' ↑(I ^ n)
[PROOFSTEP]
letI := I.adicTopology
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
x : R
this : TopologicalSpace R := adicTopology I
⊢ HasBasis (𝓝 x) (fun _n => True) fun n => (fun y => x + y) '' ↑(I ^ n)
[PROOFSTEP]
have := I.hasBasis_nhds_zero_adic.map fun y => x + y
[GOAL]
R : Type u_1
inst✝ : CommRing R
I : Ideal R
x : R
this✝ : TopologicalSpace R := adicTopology I
this : HasBasis (Filter.map (fun y => x + y) (𝓝 0)) (fun _n => True) fun i => (fun y => x + y) '' ↑(I ^ i)
⊢ HasBasis (𝓝 x) (fun _n => True) fun n => (fun y => x + y) '' ↑(I ^ n)
[PROOFSTEP]
rwa [map_add_left_nhds_zero x] at this
[GOAL]
R : Type u_1
inst✝² : CommRing R
I : Ideal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
m : M
i : ℕ
⊢ ↑(I ^ i • ⊤) = ↑((fun i => toAddSubgroup (I ^ i • ⊤)) i)
[PROOFSTEP]
simp
[GOAL]
R : Type u_1
inst✝² : CommRing R
I : Ideal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
m : M
i : ℕ
a : R
a_in : a ∈ ↑(I ^ i • ⊤)
⊢ a ∈ (fun x => x • m) ⁻¹' ↑(I ^ i • ⊤)
[PROOFSTEP]
replace a_in : a ∈ I ^ i := by simpa [(I ^ i).mul_top] using a_in
[GOAL]
R : Type u_1
inst✝² : CommRing R
I : Ideal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
m : M
i : ℕ
a : R
a_in : a ∈ ↑(I ^ i • ⊤)
⊢ a ∈ I ^ i
[PROOFSTEP]
simpa [(I ^ i).mul_top] using a_in
[GOAL]
R : Type u_1
inst✝² : CommRing R
I : Ideal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
m : M
i : ℕ
a : R
a_in : a ∈ I ^ i
⊢ a ∈ (fun x => x • m) ⁻¹' ↑(I ^ i • ⊤)
[PROOFSTEP]
exact smul_mem_smul a_in mem_top
[GOAL]
R : Type u_1
inst✝² : CommRing R
I : Ideal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
n : ℕ
⊢ OpenAddSubgroup R
[PROOFSTEP]
letI := I.adicTopology
[GOAL]
R : Type u_1
inst✝² : CommRing R
I : Ideal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
n : ℕ
this : TopologicalSpace R := adicTopology I
⊢ OpenAddSubgroup R
[PROOFSTEP]
refine ⟨(I ^ n).toAddSubgroup, ?_⟩
[GOAL]
R : Type u_1
inst✝² : CommRing R
I : Ideal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
n : ℕ
this : TopologicalSpace R := adicTopology I
⊢ IsOpen (toAddSubgroup (I ^ n)).toAddSubmonoid.toAddSubsemigroup.carrier
[PROOFSTEP]
convert (I.adic_basis.toRing_subgroups_basis.openAddSubgroup n).isOpen
[GOAL]
case h.e'_3
R : Type u_1
inst✝² : CommRing R
I : Ideal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
n : ℕ
this : TopologicalSpace R := adicTopology I
⊢ (toAddSubgroup (I ^ n)).toAddSubmonoid.toAddSubsemigroup.carrier =
↑(RingSubgroupsBasis.openAddSubgroup (_ : RingSubgroupsBasis fun i => toAddSubgroup (I ^ i • ⊤)) n)
[PROOFSTEP]
change (I ^ n : Set R) = (I ^ n • (⊤ : Ideal R) : Set R)
[GOAL]
case h.e'_3
R : Type u_1
inst✝² : CommRing R
I : Ideal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
n : ℕ
this : TopologicalSpace R := adicTopology I
⊢ ↑(I ^ n) = ↑(I ^ n • ⊤)
[PROOFSTEP]
simp [smul_top_eq_map, Algebra.id.map_eq_id, map_id, restrictScalars_self]
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
⊢ IsAdic J ↔ (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
[PROOFSTEP]
constructor
[GOAL]
case mp
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
⊢ IsAdic J → (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
[PROOFSTEP]
intro H
[GOAL]
case mp
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H : IsAdic J
⊢ (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
[PROOFSTEP]
change _ = _ at H
[GOAL]
case mp
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H : top = Ideal.adicTopology J
⊢ (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
[PROOFSTEP]
rw [H]
[GOAL]
case mp
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H : top = Ideal.adicTopology J
⊢ (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
[PROOFSTEP]
letI := J.adicTopology
[GOAL]
case mp
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H : top = Ideal.adicTopology J
this : TopologicalSpace R := Ideal.adicTopology J
⊢ (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
[PROOFSTEP]
constructor
[GOAL]
case mp.left
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H : top = Ideal.adicTopology J
this : TopologicalSpace R := Ideal.adicTopology J
⊢ ∀ (n : ℕ), IsOpen ↑(J ^ n)
[PROOFSTEP]
intro n
[GOAL]
case mp.left
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H : top = Ideal.adicTopology J
this : TopologicalSpace R := Ideal.adicTopology J
n : ℕ
⊢ IsOpen ↑(J ^ n)
[PROOFSTEP]
exact (J.openAddSubgroup n).isOpen'
[GOAL]
case mp.right
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H : top = Ideal.adicTopology J
this : TopologicalSpace R := Ideal.adicTopology J
⊢ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
[PROOFSTEP]
intro s hs
[GOAL]
case mp.right
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H : top = Ideal.adicTopology J
this : TopologicalSpace R := Ideal.adicTopology J
s : Set R
hs : s ∈ 𝓝 0
⊢ ∃ n, ↑(J ^ n) ⊆ s
[PROOFSTEP]
simpa using J.hasBasis_nhds_zero_adic.mem_iff.mp hs
[GOAL]
case mpr
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
⊢ ((∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s) → IsAdic J
[PROOFSTEP]
rintro ⟨H₁, H₂⟩
[GOAL]
case mpr.intro
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
⊢ IsAdic J
[PROOFSTEP]
apply TopologicalAddGroup.ext
[GOAL]
case mpr.intro.tg
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
⊢ TopologicalAddGroup R
[PROOFSTEP]
apply @TopologicalRing.to_topologicalAddGroup
[GOAL]
case mpr.intro.tg'
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
⊢ TopologicalAddGroup R
[PROOFSTEP]
apply (RingSubgroupsBasis.toRingFilterBasis _).toAddGroupFilterBasis.isTopologicalAddGroup
[GOAL]
case mpr.intro.h
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
⊢ 𝓝 0 = 𝓝 0
[PROOFSTEP]
ext s
[GOAL]
case mpr.intro.h.a
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
⊢ s ∈ 𝓝 0 ↔ s ∈ 𝓝 0
[PROOFSTEP]
letI := Ideal.adic_basis J
[GOAL]
case mpr.intro.h.a
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
this : SubmodulesRingBasis fun n => J ^ n • ⊤ := Ideal.adic_basis J
⊢ s ∈ 𝓝 0 ↔ s ∈ 𝓝 0
[PROOFSTEP]
rw [J.hasBasis_nhds_zero_adic.mem_iff]
[GOAL]
case mpr.intro.h.a
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
this : SubmodulesRingBasis fun n => J ^ n • ⊤ := Ideal.adic_basis J
⊢ s ∈ 𝓝 0 ↔ ∃ i, True ∧ ↑(J ^ i) ⊆ s
[PROOFSTEP]
constructor
[GOAL]
case mpr.intro.h.a.mp
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
this : SubmodulesRingBasis fun n => J ^ n • ⊤ := Ideal.adic_basis J
⊢ s ∈ 𝓝 0 → ∃ i, True ∧ ↑(J ^ i) ⊆ s
[PROOFSTEP]
intro H
[GOAL]
case mpr.intro.h.a.mpr
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
this : SubmodulesRingBasis fun n => J ^ n • ⊤ := Ideal.adic_basis J
⊢ (∃ i, True ∧ ↑(J ^ i) ⊆ s) → s ∈ 𝓝 0
[PROOFSTEP]
intro H
[GOAL]
case mpr.intro.h.a.mp
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
this : SubmodulesRingBasis fun n => J ^ n • ⊤ := Ideal.adic_basis J
H : s ∈ 𝓝 0
⊢ ∃ i, True ∧ ↑(J ^ i) ⊆ s
[PROOFSTEP]
rcases H₂ s H with ⟨n, h⟩
[GOAL]
case mpr.intro.h.a.mp.intro
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
this : SubmodulesRingBasis fun n => J ^ n • ⊤ := Ideal.adic_basis J
H : s ∈ 𝓝 0
n : ℕ
h : ↑(J ^ n) ⊆ s
⊢ ∃ i, True ∧ ↑(J ^ i) ⊆ s
[PROOFSTEP]
exact ⟨n, trivial, h⟩
[GOAL]
case mpr.intro.h.a.mpr
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
this : SubmodulesRingBasis fun n => J ^ n • ⊤ := Ideal.adic_basis J
H : ∃ i, True ∧ ↑(J ^ i) ⊆ s
⊢ s ∈ 𝓝 0
[PROOFSTEP]
rcases H with ⟨n, -, hn⟩
[GOAL]
case mpr.intro.h.a.mpr.intro.intro
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
this : SubmodulesRingBasis fun n => J ^ n • ⊤ := Ideal.adic_basis J
n : ℕ
hn : ↑(J ^ n) ⊆ s
⊢ s ∈ 𝓝 0
[PROOFSTEP]
rw [mem_nhds_iff]
[GOAL]
case mpr.intro.h.a.mpr.intro.intro
R : Type u_1
inst✝¹ : CommRing R
top : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
H₁ : ∀ (n : ℕ), IsOpen ↑(J ^ n)
H₂ : ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
s : Set R
this : SubmodulesRingBasis fun n => J ^ n • ⊤ := Ideal.adic_basis J
n : ℕ
hn : ↑(J ^ n) ⊆ s
⊢ ∃ t, t ⊆ s ∧ IsOpen t ∧ 0 ∈ t
[PROOFSTEP]
refine' ⟨_, hn, H₁ n, (J ^ n).zero_mem⟩
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : IsAdic J
n : ℕ
hn : 0 < n
⊢ IsAdic (J ^ n)
[PROOFSTEP]
rw [isAdic_iff] at h ⊢
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
n : ℕ
hn : 0 < n
⊢ (∀ (n_1 : ℕ), IsOpen ↑((J ^ n) ^ n_1)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n_1, ↑((J ^ n) ^ n_1) ⊆ s
[PROOFSTEP]
constructor
[GOAL]
case left
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
n : ℕ
hn : 0 < n
⊢ ∀ (n_1 : ℕ), IsOpen ↑((J ^ n) ^ n_1)
[PROOFSTEP]
intro m
[GOAL]
case left
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
n : ℕ
hn : 0 < n
m : ℕ
⊢ IsOpen ↑((J ^ n) ^ m)
[PROOFSTEP]
rw [← pow_mul]
[GOAL]
case left
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
n : ℕ
hn : 0 < n
m : ℕ
⊢ IsOpen ↑(J ^ (n * m))
[PROOFSTEP]
apply h.left
[GOAL]
case right
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
n : ℕ
hn : 0 < n
⊢ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n_1, ↑((J ^ n) ^ n_1) ⊆ s
[PROOFSTEP]
intro V hV
[GOAL]
case right
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
n : ℕ
hn : 0 < n
V : Set R
hV : V ∈ 𝓝 0
⊢ ∃ n_1, ↑((J ^ n) ^ n_1) ⊆ V
[PROOFSTEP]
cases' h.right V hV with m hm
[GOAL]
case right.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
n : ℕ
hn : 0 < n
V : Set R
hV : V ∈ 𝓝 0
m : ℕ
hm : ↑(J ^ m) ⊆ V
⊢ ∃ n_1, ↑((J ^ n) ^ n_1) ⊆ V
[PROOFSTEP]
use m
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
n : ℕ
hn : 0 < n
V : Set R
hV : V ∈ 𝓝 0
m : ℕ
hm : ↑(J ^ m) ⊆ V
⊢ ↑((J ^ n) ^ m) ⊆ V
[PROOFSTEP]
refine' Set.Subset.trans _ hm
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
n : ℕ
hn : 0 < n
V : Set R
hV : V ∈ 𝓝 0
m : ℕ
hm : ↑(J ^ m) ⊆ V
⊢ ↑((J ^ n) ^ m) ⊆ ↑(J ^ m)
[PROOFSTEP]
cases n
[GOAL]
case h.zero
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
V : Set R
hV : V ∈ 𝓝 0
m : ℕ
hm : ↑(J ^ m) ⊆ V
hn : 0 < Nat.zero
⊢ ↑((J ^ Nat.zero) ^ m) ⊆ ↑(J ^ m)
[PROOFSTEP]
exfalso
[GOAL]
case h.zero.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
V : Set R
hV : V ∈ 𝓝 0
m : ℕ
hm : ↑(J ^ m) ⊆ V
hn : 0 < Nat.zero
⊢ False
[PROOFSTEP]
exact Nat.not_succ_le_zero 0 hn
[GOAL]
case h.succ
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
V : Set R
hV : V ∈ 𝓝 0
m : ℕ
hm : ↑(J ^ m) ⊆ V
n✝ : ℕ
hn : 0 < Nat.succ n✝
⊢ ↑((J ^ Nat.succ n✝) ^ m) ⊆ ↑(J ^ m)
[PROOFSTEP]
rw [← pow_mul, Nat.succ_mul]
[GOAL]
case h.succ
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
V : Set R
hV : V ∈ 𝓝 0
m : ℕ
hm : ↑(J ^ m) ⊆ V
n✝ : ℕ
hn : 0 < Nat.succ n✝
⊢ ↑(J ^ (n✝ * m + m)) ⊆ ↑(J ^ m)
[PROOFSTEP]
apply Ideal.pow_le_pow
[GOAL]
case h.succ.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : TopologicalSpace R
inst✝ : TopologicalRing R
J : Ideal R
h : (∀ (n : ℕ), IsOpen ↑(J ^ n)) ∧ ∀ (s : Set R), s ∈ 𝓝 0 → ∃ n, ↑(J ^ n) ⊆ s
V : Set R
hV : V ∈ 𝓝 0
m : ℕ
hm : ↑(J ^ m) ⊆ V
n✝ : ℕ
hn : 0 < Nat.succ n✝
⊢ m ≤ n✝ * m + m
[PROOFSTEP]
apply Nat.le_add_left
[GOAL]
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
⊢ IsAdic ⊥ ↔ DiscreteTopology A
[PROOFSTEP]
rw [isAdic_iff]
[GOAL]
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
⊢ ((∀ (n : ℕ), IsOpen ↑(⊥ ^ n)) ∧ ∀ (s : Set A), s ∈ 𝓝 0 → ∃ n, ↑(⊥ ^ n) ⊆ s) ↔ DiscreteTopology A
[PROOFSTEP]
constructor
[GOAL]
case mp
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
⊢ ((∀ (n : ℕ), IsOpen ↑(⊥ ^ n)) ∧ ∀ (s : Set A), s ∈ 𝓝 0 → ∃ n, ↑(⊥ ^ n) ⊆ s) → DiscreteTopology A
[PROOFSTEP]
rintro ⟨h, _h'⟩
[GOAL]
case mp.intro
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
h : ∀ (n : ℕ), IsOpen ↑(⊥ ^ n)
_h' : ∀ (s : Set A), s ∈ 𝓝 0 → ∃ n, ↑(⊥ ^ n) ⊆ s
⊢ DiscreteTopology A
[PROOFSTEP]
rw [discreteTopology_iff_open_singleton_zero]
[GOAL]
case mp.intro
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
h : ∀ (n : ℕ), IsOpen ↑(⊥ ^ n)
_h' : ∀ (s : Set A), s ∈ 𝓝 0 → ∃ n, ↑(⊥ ^ n) ⊆ s
⊢ IsOpen {0}
[PROOFSTEP]
simpa using h 1
[GOAL]
case mpr
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
⊢ DiscreteTopology A → (∀ (n : ℕ), IsOpen ↑(⊥ ^ n)) ∧ ∀ (s : Set A), s ∈ 𝓝 0 → ∃ n, ↑(⊥ ^ n) ⊆ s
[PROOFSTEP]
intros
[GOAL]
case mpr
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
a✝ : DiscreteTopology A
⊢ (∀ (n : ℕ), IsOpen ↑(⊥ ^ n)) ∧ ∀ (s : Set A), s ∈ 𝓝 0 → ∃ n, ↑(⊥ ^ n) ⊆ s
[PROOFSTEP]
constructor
[GOAL]
case mpr.left
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
a✝ : DiscreteTopology A
⊢ ∀ (n : ℕ), IsOpen ↑(⊥ ^ n)
[PROOFSTEP]
simp
[GOAL]
case mpr.right
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
a✝ : DiscreteTopology A
⊢ ∀ (s : Set A), s ∈ 𝓝 0 → ∃ n, ↑(⊥ ^ n) ⊆ s
[PROOFSTEP]
intro U U_nhds
[GOAL]
case mpr.right
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
a✝ : DiscreteTopology A
U : Set A
U_nhds : U ∈ 𝓝 0
⊢ ∃ n, ↑(⊥ ^ n) ⊆ U
[PROOFSTEP]
use 1
[GOAL]
case h
R : Type u_1
inst✝⁵ : CommRing R
inst✝⁴ : TopologicalSpace R
inst✝³ : TopologicalRing R
A : Type u_2
inst✝² : CommRing A
inst✝¹ : TopologicalSpace A
inst✝ : TopologicalRing A
a✝ : DiscreteTopology A
U : Set A
U_nhds : U ∈ 𝓝 0
⊢ ↑(⊥ ^ 1) ⊆ U
[PROOFSTEP]
simp [mem_of_mem_nhds U_nhds]
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : WithIdeal R
⊢ NonarchimedeanRing R
[PROOFSTEP]
infer_instance
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : WithIdeal R
⊢ TopologicalRing (UniformSpace.Completion R)
[PROOFSTEP]
infer_instance
[GOAL]
R : Type u_1
inst✝³ : CommRing R
inst✝² : WithIdeal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
⊢ TopologicalAddGroup M
[PROOFSTEP]
infer_instance
[GOAL]
R : Type u_1
inst✝³ : CommRing R
inst✝² : WithIdeal R
M : Type u_2
inst✝¹ : AddCommGroup M
inst✝ : Module R M
⊢ ContinuousSMul R M
[PROOFSTEP]
infer_instance
|
program p
print *,1
stop
end program p
|
Ca l’Arbequí is located between the fruit fields in Lleida. If you come during the fruit season, you will have the opportunity to look up everything closely, and if agreed, to participate in the gathering of the fruit.
You can also have access to care for hens and chicks, and participate in collecting honey from beehives.
All activities must be agreed in advance.
|
module Day3 where
open import Data.String as String
open import Data.Maybe
open import Foreign.Haskell using (Unit)
open import Data.List as List hiding (fromMaybe)
open import Data.Nat
open import Data.Nat.DivMod
open import Data.Nat.Properties
import Data.Nat.Show as ℕs
open import Data.Char
open import Data.Vec as Vec renaming (_>>=_ to _VV=_ ; toList to VecToList)
open import Data.Product
open import Relation.Nullary
open import Data.Nat.Properties
open import Data.Bool.Base
open import AocIO
open import AocUtil
open import AocVec
open import Relation.Binary.PropositionalEquality
open import EvenOdd
printUsage : String → IO Unit
printUsage name = printString ("Usage: " String.++ name String.++ " NUMBER\n(NUMBER > 0)")
sqr : (l : ℕ) → Σ[ k ∈ ℕ ] (k ≡ l * l)
sqr l = l * l , refl
first-larger-odd-square : {m : ℕ} → (n : ℕ) → suc m ≡ n → Σ[ k ∈ ℕ ] (n ≤ (k * k) × Odd k)
first-larger-odd-square {m} n n-is-suc = helper 1 m n-is-suc oddOne
where
helper : (m diff : ℕ) → (m + diff) ≡ n → Odd m → Σ[ k ∈ ℕ ] (n ≤ (k * k) × Odd k)
helper m (suc (suc diff)) p m-is-odd with sqr m
... | (m² , m²≡m*m) with n ≤? m²
... | yes n≤m² rewrite m²≡m*m = m , n≤m² , m-is-odd
... | no _ = helper (suc (suc m)) diff rewr-p (oddSuc m-is-odd)
where
rewr-p : suc (suc m + diff) ≡ n
rewr-p with (+-suc m diff) | (+-suc m (suc diff))
... | s | t rewrite (sym s) | t = p
helper m zero p m-is-odd rewrite (+-identityʳ m) with (sqr m)
... | (m² , q) = m , (my-proof n refl) , m-is-odd
where
my-proof : (k : ℕ) → k ≡ n → n ≤ m * m
my-proof k p₁ rewrite sym p₁ with k
... | zero = z≤n
... | suc kk rewrite p with (m≤m+n kk (kk * suc kk))
... | kk≤kk+junk = s≤s kk≤kk+junk
helper zero (suc zero) p ()
helper (suc zero) (suc zero) p m-is-odd rewrite sym p = 3 , (s≤s (s≤s z≤n) , oddSuc oddOne)
helper (suc (suc m)) (suc zero) p m-is-odd = (suc (suc m)) , my-proof n refl , m-is-odd
where
my-proof : (k : ℕ) → k ≡ n → n ≤ suc (suc (m + suc (suc (m + m * suc (suc m)))))
my-proof k p₁ rewrite sym p₁ with k
... | zero = z≤n
-- we replace with p and get an expression 1 + m ≤ suc (suc m + junk)
-- +-comm m 1 turns 1 + m into suc m
-- sym +-suc turns m + suc junk into suc (m + junk) to match the number on the other side
-- finally we cancel suc on both sides and use m ≤ m + junk
... | suc kk rewrite sym p | +-comm m 1 | +-suc m (suc (m + m * suc (suc m))) = s≤s (s≤s (s≤s (m≤m+n m (suc (m + m * suc (suc m))))))
oddness : ∀ {n} → Odd n → ℕ
oddness oddOne = 1
oddness (oddSuc v) = suc (oddness v)
ring-for-square# : {m : ℕ} → (n : ℕ) → suc m ≡ n → Σ[ k ∈ ℕ ] Odd k × ℕ
ring-for-square# zero ()
ring-for-square# (suc n) p with (first-larger-odd-square (suc n) (cong suc refl))
... | k , proj₄ , k-odd = k , k-odd , (oddness k-odd)
ring-corners : {m : ℕ} → Odd m → ℕ × ℕ × ℕ × ℕ × ℕ
ring-corners oddOne = 1 , (1 , (1 , 1 , 1))
ring-corners {(suc (suc n))} (oddSuc _) = (n * n) , ((proj₁ first-corner) , ((proj₁ second-corner) , ((proj₁ third-corner) , (proj₁ fourth-corner))))
where
first-corner : Σ[ k ∈ ℕ ] k ≡ suc ((n * n) + n)
first-corner = suc (n * n + n) , refl
second-corner : Σ[ k ∈ ℕ ] k ≡ suc (suc ((n * n) + n + n))
second-corner = (suc (suc (n * n + n + n))) , refl
third-corner : Σ[ k ∈ ℕ ] k ≡ suc (suc (suc ((n * n) + n + n + n)))
third-corner = suc (suc (suc (n * n + n + n + n))) , refl
fourth-corner : Σ[ k ∈ ℕ ] k ≡ suc (suc (n + suc (suc (n + n * suc (suc n)))))
fourth-corner = sqr (suc (suc n))
ring-length : Σ[ k ∈ ℕ ] k ≡ (2 * (suc (suc n))) + (2 * n)
ring-length = (2 * (suc (suc n)) + 2 * n) , refl
-- proof that fourth-corner = ring-length + prev-fourth-corner
ring-length-proof : {m l : ℕ} → m ≡ suc (suc (n + suc (suc (n + n * suc (suc n))))) → l ≡ (2 * (suc (suc n))) + (2 * n) → l + (n * n) ≡ m
ring-length-proof p q rewrite p | q = cong suc (cong suc my-proof)
where
halp : n + n + (n + n) ≡ n + n + n + n
halp = begin
n + n + (n + n)
≡⟨ sym (+-assoc (n + n) n n) ⟩
n + n + n + n ∎
where
open ≡-Reasoning
halp-again : n * n + (n + n + n + n) ≡ n * n + n + n + n + n
halp-again with +-assoc (n * n) (n + n + n) n
... | p₁ rewrite sym p₁ with +-assoc (n * n) (n + n) n
... | p₂ rewrite sym p₂ with +-assoc (n * n) n n
... | p₃ rewrite sym p₃ = refl
my-proof : n + suc (suc (n + 0)) + (n + (n + 0)) + n * n ≡ n + suc (suc (n + n * suc (suc n)))
my-proof rewrite +-identityʳ n | +-*-suc n (suc n) | +-*-suc n n with +-comm n (suc (suc n)) | +-comm n (suc (suc (n + (n + (n + n * n)))))
... | p₁ | p₂ rewrite p₁ | p₂ with +-comm n (n + n * n) | +-comm n (n + n * n + n) | +-comm n (n * n) | +-comm (n + n + (n + n)) (n * n)
... | p₃ | p₄ | p₅ | p₆ rewrite p₃ | p₄ | p₅ | p₆ | halp | halp-again = cong suc (cong suc refl)
-- Here I'd like a proof that the distance between the corners add up to the length
abs-diff : (n m : ℕ) → ℕ
abs-diff zero m = m
abs-diff (suc n) zero = suc n
abs-diff (suc n) (suc m) = abs-diff n m
min-5 : (a b c d e : ℕ) → ℕ
min-5 a b c d e with a ⊓ b | c ⊓ d
... | min-ab | min-cd with min-ab ⊓ min-cd
... | min-abcd = min-abcd ⊓ e
dist-to-closest-ring-corner : {k : ℕ} → (n : ℕ) → suc k ≡ n → ℕ
dist-to-closest-ring-corner zero ()
dist-to-closest-ring-corner (suc k) p with (ring-for-square# (suc k) p) | (suc k)
... | corner-root , corner-root-odd , ring# | n with ring-corners corner-root-odd
... | c₀ , c₁ , c₂ , c₃ , c₄ with abs-diff n c₀ | abs-diff n c₁ | abs-diff n c₂ | abs-diff n c₃ | abs-diff n c₄
... | n-c₀ | n-c₁ | n-c₂ | n-c₃ | n-c₄ = min-5 n-c₀ n-c₁ n-c₂ n-c₃ n-c₄
dist-to-center : {k : ℕ} → (n : ℕ) → suc k ≡ n → ℕ
dist-to-center zero ()
dist-to-center (suc k) p with (ring-for-square# (suc k) p) | (suc k)
... | corner-root , corner-root-odd , ring# | n with dist-to-closest-ring-corner (suc k) refl
... | dist = abs-diff dist (2 * (pred ring#))
infixr 5 _+++_
_+++_ : String → String → String
_+++_ s1 s2 = s1 String.++ " " String.++ s2
print-corners : {k : ℕ} → (n : ℕ) → suc k ≡ n → IO Unit
print-corners zero ()
print-corners (suc k) p with (ring-for-square# (suc k) p) | (suc k)
... | corner-root , corner-root-odd , ring# | n with ring-corners corner-root-odd
... | c₀ , c₁ , c₂ , c₃ , c₄ with abs-diff n c₀ | abs-diff n c₁ | abs-diff n c₂ | abs-diff n c₃ | abs-diff n c₄
... | n-c₀ | n-c₁ | n-c₂ | n-c₃ | n-c₄ with ℕs.show n-c₀ | ℕs.show n-c₁ | ℕs.show n-c₂ | ℕs.show n-c₃ | ℕs.show n-c₄ | ℕs.show corner-root | ℕs.show ring#
... | s0 | s1 | s2 | s3 | s4 | s5 | s6 = printString (s0 +++ s1 +++ s2 +++ s3 +++ s4 +++ "==" +++ s5 +++ s6)
main : IO Unit
main = mainBuilder main'
where
main' : String → (List String) → IO Unit
main' name (numS ∷ []) with (unsafeParseNat (String.toList numS))
... | 0 = printUsage name
... | (suc n) = printString (ℕs.show (dist-to-center (suc n) (cong suc refl)))
main' name _ = printUsage name
|
lemma primitive_part_const_poly [simp]: "primitive_part [:x:] = [:unit_factor x:]"
|
module Exceptions
import Genie
import HTTP
export ExceptionalResponse, RuntimeException, InternalServerException, NotFoundException, FileExistsException
"""
struct ExceptionalResponse <: Exception
A type of exception which wraps an HTTP Response object.
The thrown exception will propagate until it is caught up the app stack or ultimately by Genie
and the wrapped response is sent to the client.
### Example
If the user is not authenticated, an `ExceptionalResponse` is thrown - if the exception is not caught
in the app's stack, Genie will catch it and return the wrapped `Response` object, forcing an HTTP redirect to the login page.
```julia
isauthenticated() || throw(ExceptionalResponse(redirect(:show_login)))
```
"""
struct ExceptionalResponse <: Exception
response::HTTP.Response
end
Base.show(io::IO, ex::ExceptionalResponse) = print(io, "ExceptionalResponseException: $(ex.response.status) - $(Dict(ex.response.headers))")
###
"""
RuntimeException
Represents an unexpected and unhandled runtime exceptions. An error event will be logged and the
exception will be sent to the client, depending on the environment
(the error stack is dumped by default in dev mode or an error message is displayed in production).
It allows defining custom error message and info, as well as an error code, in addition to the exception object.
# Arguments
- `message::String`
- `info::String`
- `code::Int`
- `ex::Union{Nothing,Exception}`
"""
struct RuntimeException <: Exception
message::String
info::String
code::Int
ex::Union{Nothing,Exception}
end
"""
RuntimeException(message::String, code::Int)
`RuntimeException` constructor using `message` and `code`.
"""
RuntimeException(message::String, code::Int) = RuntimeException(message, "", code, nothing)
"""
RuntimeException(message::String, info::String, code::Int)
`RuntimeException` constructor using `message`, `info` and `code`.
"""
RuntimeException(message::String, info::String, code::Int) = RuntimeException(message, info, code, nothing)
"""
Base.show(io::IO, ex::RuntimeException)
Custom printing of `RuntimeException`
"""
Base.show(io::IO, ex::RuntimeException) = print(io, ex.message)
###
"""
struct InternalServerException <: Exception
Dedicated exception type for server side exceptions. Results in a 500 error by default.
# Arguments
- `message::String`
- `info::String`
- `code::Int`
"""
struct InternalServerException <: Exception
message::String
info::String
code::Int
end
"""
InternalServerException(message::String)
External `InternalServerException` constructor accepting a custome message.
"""
InternalServerException(message::String) = InternalServerException(message, "", 500)
"""
InternalServerException()
External `InternalServerException` using default values.
"""
InternalServerException() = InternalServerException("Internal Server Error")
###
"""
struct NotFoundException <: Exception
Specialized exception representing a not found resources. Results in a 404 response being sent to the client.
# Arguments
- `message::String`
- `info::String`
- `code::Int`
- `resource::String`
"""
struct NotFoundException <: Exception
message::String
info::String
code::Int
resource::String
end
Base.show(io::IO, ex::NotFoundException) = print(io, ex.message)
"""
NotFoundException(resource::String)
External constructor allowing to pass the name of the not found resource.
"""
NotFoundException(resource::String) = NotFoundException("not found", "", 404, resource)
NotFoundException(resource::String, info::String) = NotFoundException("$resource can not be found", info, 404, resource)
"""
NotFoundException()
External constructor using default arguments.
"""
NotFoundException() = NotFoundException("")
###
"""
struct FileExistsException <: Exception
Custom exception type for signaling that the requested file already exists.
"""
struct FileExistsException <: Exception
path::String
end
"""
Base.show(io::IO, ex::FileExistsException)
Custom printing for `FileExistsException`
"""
Base.show(io::IO, ex::FileExistsException) = print(io, "FileExistsException: $(ex.path)")
end
|
SUBROUTINE SMATP (A,LDA,M,N,TEXT)
c SMATP.. Print a matrix.
c Copyright (c) 1996 California Institute of Technology, Pasadena, CA.
c ALL RIGHTS RESERVED.
c Based on Government Sponsored Research NAS7-03001.
c>> 2001-05-25 SMATP Krogh Minor change for making .f90 version.
c>> 1996-07-02 SMATP Krogh Changes to use .C. and C%%.
c>> 1996-03-30 SMATP Krogh Added external statement.
c>> 1996-01-24 SMATP Krogh M77CON instructions for conversion to C.
c>> 1994-10-20 SMATP Krogh Changes to use M77CON
c>> 1994-08-08 SMATP CLL Special treatment for text(1:1) .eq. '0'
c>> 1994-04-20 CLL Making DP & SP codes similar.
C>> 1992-04-22 CLL
C>> 1990-01-23 CLL removed extraneous "60 continue"
C>> 1985-09-20 CLL
C>> 1983-07-05 Kris Stewart For MATH77
C>> 1981-07-23 Kris Stewart Improve portability.
C>> 1969-00-00 C. L. Lawson, JPL, Original code: MOUT/VOUT
C ------------------------------------------------------------------
C A(,) Matrix to be output
C LDA Leading dimension of array A().
C M No. of rows to be printed from A().
C N No. of cols to be printed from A().
c TEXT Character string to be printed as a title.
c First character in TEXT controls line spacing before title on
c an impact printer. For output to be viewed on a screen it is
c safest to always use ' '.
c ' ' = normal single space.
c '0' = double space.
c '1' = page advance.
c '+' = suppress space, i.e., overprint.
C ------------------------------------------------------------------
c Method: If the machine epsilon, is larger than 0.5*10**(-12), we set
c MODE = 1 and print 8 numbers across a line, using a g15.7 format.
c Otherwise we set MODE = 2 and print 6 numbers across a line, using a
c g20.12 format.
C ------------------------------------------------------------------
c--S replaces "?": ?MATP
C ------------------------------------------------------------------
external R1MACH
integer iblock, j1, j2, lda, m, maxcol(2), mode, n, nblock
c%% int i, j; /* Converter doesn't declare these for some reason. */
integer i, j
real a(lda,*), R1MACH
character fmt1(2)*24, fmt2(2)*20, text*(*)
data maxcol/8, 6/
c ------------------------------------------------------------------
c++ CODE for ~.C. is active
data fmt1 /'(/12x,8(4x,a3,i4,4x)/1x)','(/12x,6(6x,a3,i5,6x)/1x)'/
data fmt2 /'(a,i4,4x,1p,8g15.7 )', '(a,i4,4x,1p,6g20.12)'/
if(text(1:1) .eq. '0') then
write(*,'(/1x,a)') text(2:)
else
write(*,'(a)') text
endif
c++ CODE for .C. is inactive
C%% if(text[0] == '0') printf("\n %s\n", &text[1]);
C%% else printf( "%s\n", text );
c++ END
if(R1MACH(3) .gt. 0.5e-12) then
mode = 1
else
mode = 2
endif
nblock=(n+maxcol(mode)-1)/maxcol(mode)
j2 = 0
do 70 iblock = 1,nblock
j1 = j2 + 1
j2 = min(j1+maxcol(mode)-1, n)
c++ CODE for ~.C. is active
write(*,fmt1(mode)) ('COL',j,j=j1,j2)
do 50 i=1,m
write(*,fmt2(mode)) ' ROW',i,(a(i,j),j=j1,j2)
50 continue
c++ CODE for .C. is inactive
C%% printf("\n ");
C%% if (mode == 1) {
C%% for (j = j1; j<= j2; j++) printf(" COL%4i ", j);
C%% printf("\n");
C%% for (i = 1; i <= m; i++){
C%% printf("ROW %4i", i);
C%% for (j=j1; j <= j2; j++)
C%% printf("%15.7g", A(j-1, i-1));
C%% printf("\n");}
C%% }else {
C%% for (j=j1;j<=j2;j++) printf(" COL%5i ", j);
C%% printf("\n");
C%% for (i = 1; i <= m; i++){
C%% printf("ROW %4i", i);
C%% for (j=j1; j <= j2; j++)
C%% printf("%20.12g", A(j-1, i-1));
C%% printf("\n");}
C%% }
c++ END
70 continue
end
|
# Day 20: Trench Map
# Image is permuted for faster iteration
function load(::Day{20}, path)
# function load(path)
lines = readlines(path)
alg = [c == '#' for c in lines[1]]
img = BitMatrix(reduce(hcat, [[c == '#' for c in line] for line in lines[3:end]]))
return alg, img
end
# Part 1 – count pixels in output image
# Offsets defining neighborhood. We need to "read across each column":
const CONV_OFFSETS = [
CartesianIndex(-1, -1),
CartesianIndex(0, -1),
CartesianIndex(1, -1),
CartesianIndex(-1, 0),
CartesianIndex(0, 0),
CartesianIndex(1, 0),
CartesianIndex(-1, 1),
CartesianIndex(0, 1),
CartesianIndex(1, 1),
]
function pad_image(img; px=1, val=false)
h, w = size(img)
padrows = zeros(Bool, px, w)
padcols = zeros(Bool, h + 2 * px, px)
return hcat(padcols, vcat(padrows, img, padrows), padcols)
end
@inline getval(img, I::CartesianIndex, outer) = checkbounds(Bool, img, I) ? img[I] : outer
const POWS = 2 .^ collect(8:-1:0)
@inline neighbors2num(n) = sum(POWS .* n) + 1
function apply_algorithm!(out, img, outer, alg)
@inbounds @simd for I in CartesianIndices(img) # not sure @simd does anything here...
# Index the value of the algorithm `alg` based on the binary number
# that results from the neighboring pixels.
out[I] = alg[neighbors2num([
getval(img, I + offset, outer) for offset in CONV_OFFSETS
])]
end
return out
end
function enhance_n_times(alg, img, n)
img = pad_image(img; px=n)
buff = similar(img)
outer = false
for _ in 1:n
img .= apply_algorithm!(buff, img, outer, alg)
# The "outer values" are flashing if `alg[1] = 1` and `alg[end] = 0`
alg[1] == 1 && (outer = !outer)
end
return img
end
solve1(::Day{20}, data) = sum(enhance_n_times(data..., 2))
# Part 2 – Part 1 with more steps
solve2(::Day{20}, data) = sum(enhance_n_times(data..., 50))
testresult1(::Day{20}) = 35
testresult2(::Day{20}) = 3351
|
# Solutions
## Question 1
> `1`. Using a `for` loop print the types of the variables in each of the
> following iterables:
> `1`. `iterable = (1, 2, 3, 4)`
```python
for variable in (1, 2, 3, 4):
print(type(variable))
```
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
> `2`. `iterable = (1, 2.0, 3, 4.0)`
```python
for variable in (1, 2.0, 3, 4.0):
print(type(variable))
```
<class 'int'>
<class 'float'>
<class 'int'>
<class 'float'>
> `3`. `iterable = (1, "dog", 0, 3, 4.0)`
```python
for variable in (1, "dog", 0, 3, 4.0):
print(type(variable))
```
<class 'int'>
<class 'str'>
<class 'int'>
<class 'int'>
<class 'float'>
## Question 2
> `2`. Consider the following polynomial:
> $$ 3 n ^ 3 - 183n ^ 2 + 3318n - 18757 $$
> `1`. Use the `sympy.isprime` function to find the lowest positive integer value
> of $n$ for which the absolute value of that polynomial is not prime?
Start by defining the cubic:
```python
import sympy as sym
def cubic(n):
"""
Return the value of the absolute value of the cubic for the given value of n
"""
return abs(3 * n ** 3 - 183 * n ** 2 + 3318 * n - 18757)
```
Increment `n` until `cubic(n)` is no longer prime:
```python
n = 1
while sym.isprime(cubic(n)) is True:
n += 1
n
```
47
> `2`. How many **unique** primes up until the first non prime value are there?
> (Hint: the `set` tool might prove useful here.)
```python
primes = [cubic(n_value) for n_value in range(1, n)]
unique_primes = set(primes)
unique_primes
```
{37,
41,
59,
109,
229,
409,
419,
499,
739,
829,
877,
1201,
1531,
1597,
1669,
1823,
1999,
2389,
2749,
2917,
3061,
3271,
3307,
3469,
3491,
3529,
4789,
5441,
6367,
7691,
8221,
10259,
10369,
12829,
13163,
15619,
16421,
20051,
24071,
28499,
33353,
38651}
Let us count them:
```python
len(unique_primes)
```
42
## Question 3
> `3`. Check the following identify for each value of $n\in\{0, 10, 100, 2000\}$:
> $ \sum_{i=0}^n i=\frac{n(n+1)}{2} $
Define a function to check the identity:
```python
def check_identity(n):
"""
Computes lhs and the rhs of the given identity.
"""
lhs = sum(i for i in range(n + 1))
rhs = n * (n + 1) / 2
return lhs == rhs
```
Checks the identify for the given values:
```python
all(check_identity(n) for n in (0, 10, 100, 2000))
```
True
## Question 4
> `4`. Check the following identify for all positive integer values of $n$ less
> than 5000: $ \sum_{i=0}^n i^2=\frac{n(n+1)(2n+1)}{6} $
Define a function to check the identity:
```python
def check_identity(n):
"""
Computes lhs and the rhs of the given identity.
"""
lhs = sum(i ** 2 for i in range(n + 1))
rhs = n * (n + 1) * (2 * n + 1) / 6
return lhs == rhs
```
Checks the identify for the given values:
```python
all(check_identity(n) for n in range(1, 5001))
```
True
## Question 5
> `5`. Repeat the experiment of selecting a random integer between 0 and 10
> until it is even 1000 times (see
> {ref}`repeat_code_while_a_given_condition_holds`). What is the average number
> of times taken to select an even number?
Write a function to repeat the code from
{ref}`repeat_code_while_a_given_condition_holds`:
```python
import random
def count_number_of_selections_until_even(seed):
"""
Repeatedly sample an integer between 0 and 10 for a given random seed.
This function returns the number of selections needed.
"""
random.seed(seed)
selected_integer = random.randint(0, 10)
number_of_selections = 1
while selected_integer % 2 == 1:
selected_integer = random.randint(0, 10)
number_of_selections += 1
return number_of_selections
```
Now use this for 1000 random repetitions (we use each repetition as a seed):
```python
number_of_selections = [
count_number_of_selections_until_even(seed) for seed in range(1000)
]
number_of_selections
```
[1,
1,
1,
3,
2,
2,
4,
2,
3,
4,
2,
2,
2,
1,
3,
2,
4,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2,
1,
2,
1,
1,
1,
3,
2,
1,
1,
2,
1,
1,
2,
3,
1,
1,
1,
1,
1,
2,
3,
1,
3,
2,
2,
1,
4,
1,
3,
1,
1,
4,
3,
1,
2,
2,
3,
3,
1,
2,
3,
2,
1,
2,
2,
3,
1,
2,
3,
3,
1,
3,
1,
1,
1,
1,
4,
1,
11,
1,
1,
1,
3,
4,
3,
1,
7,
1,
1,
3,
2,
3,
1,
1,
3,
1,
6,
1,
5,
2,
4,
1,
1,
1,
5,
2,
1,
5,
1,
2,
2,
1,
1,
1,
4,
1,
1,
1,
4,
2,
1,
2,
2,
1,
3,
1,
7,
2,
1,
2,
2,
2,
1,
2,
1,
2,
1,
2,
1,
1,
2,
1,
3,
2,
1,
1,
3,
2,
2,
2,
4,
1,
1,
2,
1,
1,
1,
2,
1,
1,
4,
2,
1,
8,
1,
4,
3,
1,
3,
1,
3,
2,
4,
1,
3,
7,
3,
1,
2,
2,
4,
2,
2,
2,
1,
2,
1,
4,
2,
1,
1,
1,
2,
1,
3,
1,
2,
1,
1,
1,
1,
1,
1,
1,
4,
1,
1,
1,
1,
2,
1,
1,
1,
4,
2,
3,
5,
5,
2,
2,
1,
1,
1,
1,
1,
1,
1,
2,
2,
1,
3,
3,
3,
2,
1,
2,
1,
1,
1,
1,
3,
1,
1,
1,
2,
2,
1,
2,
1,
2,
2,
1,
1,
3,
1,
2,
1,
2,
1,
2,
2,
1,
1,
1,
2,
4,
2,
1,
4,
5,
2,
1,
1,
1,
1,
1,
1,
1,
2,
6,
1,
1,
1,
1,
1,
1,
5,
1,
1,
2,
1,
2,
4,
4,
1,
1,
1,
1,
1,
1,
1,
1,
2,
1,
1,
1,
2,
4,
1,
1,
2,
1,
1,
2,
1,
1,
2,
2,
1,
3,
1,
1,
2,
3,
2,
2,
1,
2,
1,
1,
3,
2,
1,
1,
2,
9,
3,
1,
1,
1,
4,
2,
1,
2,
5,
1,
3,
4,
1,
1,
1,
3,
2,
2,
2,
1,
1,
1,
1,
4,
1,
3,
2,
2,
1,
5,
1,
2,
4,
1,
2,
1,
1,
1,
4,
1,
1,
1,
3,
2,
3,
4,
1,
4,
2,
5,
3,
10,
3,
1,
3,
1,
1,
1,
3,
3,
4,
2,
1,
1,
1,
2,
1,
1,
2,
1,
1,
1,
3,
1,
3,
4,
2,
1,
1,
1,
2,
1,
1,
1,
1,
1,
3,
1,
1,
2,
2,
3,
2,
1,
1,
2,
1,
3,
1,
5,
1,
1,
1,
2,
1,
1,
4,
3,
1,
3,
2,
1,
1,
3,
1,
3,
1,
1,
5,
2,
3,
1,
3,
1,
1,
2,
1,
1,
1,
1,
3,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
2,
1,
1,
4,
2,
1,
2,
2,
4,
1,
1,
1,
2,
1,
2,
2,
2,
1,
1,
1,
4,
1,
2,
4,
1,
1,
1,
4,
1,
1,
3,
1,
2,
1,
2,
3,
1,
2,
3,
1,
2,
1,
1,
1,
1,
1,
3,
1,
2,
1,
1,
1,
2,
4,
1,
1,
3,
2,
3,
1,
1,
2,
1,
1,
1,
1,
5,
1,
1,
2,
1,
2,
3,
1,
1,
1,
1,
2,
3,
1,
1,
1,
2,
1,
2,
2,
3,
1,
2,
1,
1,
1,
1,
1,
1,
2,
1,
1,
5,
1,
2,
1,
1,
2,
1,
3,
1,
1,
3,
4,
1,
3,
1,
2,
2,
1,
1,
2,
1,
1,
3,
1,
1,
3,
1,
1,
2,
1,
3,
1,
1,
2,
1,
3,
2,
1,
2,
4,
1,
1,
2,
1,
4,
1,
1,
1,
2,
1,
3,
1,
1,
5,
2,
3,
1,
2,
1,
1,
1,
1,
3,
3,
4,
1,
1,
8,
2,
1,
1,
3,
1,
1,
1,
3,
1,
1,
1,
1,
1,
5,
1,
1,
2,
2,
3,
1,
4,
2,
1,
1,
1,
3,
1,
1,
3,
1,
4,
1,
1,
1,
1,
1,
1,
1,
1,
2,
3,
1,
1,
4,
2,
3,
1,
1,
3,
3,
1,
1,
2,
1,
4,
1,
2,
1,
2,
1,
1,
3,
1,
1,
5,
1,
1,
2,
1,
1,
1,
1,
2,
1,
1,
3,
1,
1,
1,
2,
1,
2,
1,
1,
1,
1,
1,
1,
1,
4,
2,
2,
1,
1,
1,
2,
1,
1,
2,
2,
2,
1,
1,
4,
1,
1,
2,
1,
3,
1,
1,
3,
1,
2,
1,
1,
1,
3,
2,
1,
1,
1,
2,
1,
1,
2,
3,
6,
1,
2,
3,
3,
1,
1,
1,
1,
2,
1,
3,
2,
1,
1,
2,
2,
1,
1,
1,
2,
1,
2,
1,
10,
1,
2,
2,
4,
2,
3,
3,
1,
3,
2,
1,
1,
2,
1,
1,
1,
2,
2,
3,
2,
2,
4,
1,
1,
1,
2,
2,
2,
3,
1,
1,
3,
1,
2,
1,
1,
1,
3,
2,
2,
3,
1,
1,
1,
4,
1,
2,
1,
4,
2,
2,
1,
3,
2,
3,
2,
1,
5,
1,
3,
3,
2,
1,
1,
3,
1,
1,
1,
4,
2,
1,
1,
1,
1,
1,
2,
1,
2,
3,
1,
1,
1,
1,
2,
2,
2,
2,
1,
1,
1,
2,
1,
3,
1,
4,
1,
1,
1,
5,
1,
1,
1,
2,
1,
1,
1,
1,
2,
4,
2,
1,
2,
1,
1,
1,
1,
1,
1,
3,
3,
1,
2,
5,
2,
1,
1,
1,
2,
1,
1,
1,
1,
3,
1,
1,
1,
4,
2,
2,
2,
1,
1,
1,
1,
1,
2,
1,
2,
3,
1,
2,
1,
1,
1,
1,
2,
5,
4,
1,
1,
1,
1,
1,
5,
1,
1,
2,
1,
1,
1,
2,
1,
2,
2,
2,
1,
2,
2,
1,
2,
1,
1,
1,
4,
4,
1,
1,
2,
1,
1,
3,
1,
1,
1,
7,
3,
1,
1]
We will use `numpy` which has a `mean` function:
```python
import numpy as np
np.mean(number_of_selections)
```
1.839
|
success rates in solving calculus problems tend to be frequent exploiters of metacongnitive thinking strategies. For more help on writing argumentative statement, Click Here. But here, the essential question that lies with us is that what are the channels and mediums through which this influence is generated and pulled off. Agree or disagree with reasons. Our goal is to provide a safe, fun environment for families.
It is recommended that you use the thesis statement generator tool as a practice writing tool. It is developed considering the topic whether it has a point to be argued about or not. From a large variety of Jumpers for themed parties to all the tables and chairs, we are your one-stop source for Party Rentals. While writing a thesis statement for a research essay you have to strictly take a for or against approach and then justify your argument. Argumentative Thesis Statement Example #1, bad Thesis statement: Population of the world is increasing dramatically.
Therefore it cant be argued. Thesis Statement Professional Builder needs the following information: Topic of persuasive essay, your opinion on this topic, at least three strong reasons supporting your opinion on this topic, at least one strong argument against your opinion on this topic, a possible title for your persuasive. The study was carried out for a model of metacognitive thinking strategies which are self-efficacy, definition, exploration, accommodation, strategy, execution and verification. Thesis Statement Builder also provides a tool to generate a basic outline for your persuasive essay. What type of claim is it?
Most scientists believe that the aborigines come from southeastern Asia from the beginning. And a minority among Pakistanis and Bangladeshis forms, indisputably, the largest number of British jihadists, and the largest number of a..
This is especially the case in societies like Israel (with the ultra-Orthodox and religious Zionists ) where committed religious groups have several times the birth rate of seculars. They believe that a weakening of..
If it is found to be addictive, particularly if tempted to do it alone, it may be a sign of depression or unhappiness. Bulimia and anorexia are rare before the age of ten. You..
|
using Revise
using FwiFlow
using AdFem
using ADCME
using PyPlot
using PyCall
using Statistics
using DelimitedFiles
using ADCMEKit
np = pyimport("numpy")
function visualize_obs(o1)
close("all")
plot((0:NT)*Δt, o1[:, 1:m+1])
xlabel("t")
ylabel("displacement")
end
function layer_model(m, n)
z = zeros(4*n*m)
k = 0
mm = ones(n)
mm[n÷3:end] .= 1.5
for i = 1:n
for j = 1:m
for p = 1:2
for q = 1:2
k += 1
z[k] = mm[i]
end
end
end
end
return z
end
function sin_model(m, n)
end
function visualize_invη(o)
o = o * 1e12
Z = zeros(n, m)
k = 0
for i = 1:n
for j = 1:m
Z[i, j] = mean(o[k+1:k+4])
k += 4
end
end
pcolormesh(Z)
axis("scaled")
xlabel("x")
ylabel("y")
gca().invert_yaxis()
colorbar()
end
|
It’s that time of year again – Open Enrollment from November15th until the end of December. There is a lot of information to sift through and some of it – or maybe a lot of it – can be very confusing.
The good news is that there are organizations providing help to sift through it all and actually end up understanding what provisions you need, what is affordable and, as a result, which coverage and supplements are right for you.
If you are trying to find understandable information and straightforward facts there are places to go to get the information you need. Look through your local newspaper in the Calendar Section for free events. You will find various free seminars on topics such as How to Choose the Right Medicare Coverage; Choosing a Medicare Supplement; Determining What You Will Be Covered For; What is the Difference Between Plans? and more information.
Usually you can find excellent seminars at your local senior citizens center, your local library, your local hospital, your local clinic and your local health department. If a seminar is not listed in your newspaper Calendar Section, take the time to call the organizations just mentioned and find out what type of information or seminars they have planned. You can also go online or call CMS – the Centers For Medicare and Medicaid Services – and they will be able to help sort out the basics for you and tell you if they will be having a seminar or presentation in your area.
Try to remember – especially when you attend a seminar or presentation – that many of these are presented by individual insurance companies that are trying to sell you their product. As a result, it is important to attend a few seminars if possible so that you can compare what several companies have to offer. Too often some companies charge a lot more for the same coverage that other companies charge far less for. If you can go to a seminar presented by an unbiased individual, such as an individual from Medicare or an individual comparing several policies for you, this is the best way to get accurate information for making decisions.
Regardless of what you attend, try to at least attend one seminar or talk to someone you trust who understands Medicare and Medicare Supplements. Take the time to be sure that you choose the coverage that is right for you.
|
||| This module implements a relation between a natural number and a list.
||| The relation witnesses the fact the number is the length of the list.
|||
||| It is meant to be used in a runtime-irrelevant fashion in computations
||| manipulating data indexed over lists where the computation actually only
||| depends on the length of said lists.
|||
||| Instead of writing:
||| ```idris example
||| f0 : (xs : List a) -> P xs
||| ```
|||
||| We would write either of:
||| ```idris example
||| f1 : (n : Nat) -> (0 _ : HasLength xs n) -> P xs
||| f2 : (n : Subset n (HasLength xs)) -> P xs
||| ```
|||
||| See `sucR` for an example where the update to the runtime-relevant Nat is O(1)
||| but the udpate to the list (were we to keep it around) an O(n) traversal.
module Data.List.HasLength
import Data.DPair
import Data.List
%default total
------------------------------------------------------------------------
-- Type
||| Ensure that the list's length is the provided natural number
public export
data HasLength : List a -> Nat -> Type where
Z : HasLength [] Z
S : HasLength xs n -> HasLength (x :: xs) (S n)
------------------------------------------------------------------------
-- Properties
||| The length is unique
export
hasLengthUnique : HasLength xs m -> HasLength xs n -> m === n
hasLengthUnique Z Z = Refl
hasLengthUnique (S p) (S q) = cong S (hasLengthUnique p q)
||| This specification corresponds to the length function
export
hasLength : (xs : List a) -> HasLength xs (length xs)
hasLength [] = Z
hasLength (_ :: xs) = S (hasLength xs)
export
map : (f : a -> b) -> HasLength xs n -> HasLength (map f xs) n
map f Z = Z
map f (S n) = S (map f n)
||| @sucR demonstrates that snoc only increases the lenght by one
||| So performing this operation while carrying the list around would cost O(n)
||| but relying on n together with an erased HasLength proof instead is O(1)
export
sucR : HasLength xs n -> HasLength (snoc xs x) (S n)
sucR Z = S Z
sucR (S n) = S (sucR n)
------------------------------------------------------------------------
-- Views
namespace SubsetView
||| We provide this view as a convenient way to perform nested pattern-matching
||| on values of type `Subset Nat (HasLength xs)`. Functions using this view will
||| be seen as terminating as long as the index list `xs` is left untouched.
||| See e.g. listTerminating below for such a function.
public export
data View : (xs : List a) -> Subset Nat (HasLength xs) -> Type where
Z : View [] (Element Z Z)
S : (p : Subset Nat (HasLength xs)) -> View (x :: xs) (Element (S (fst p)) (S (snd p)))
||| This auxiliary function gets around the limitation of the check ensuring that
||| we do not match on runtime-irrelevant data to produce runtime-relevant data.
viewZ : (0 p : HasLength xs Z) -> View xs (Element Z p)
viewZ Z = Z
||| This auxiliary function gets around the limitation of the check ensuring that
||| we do not match on runtime-irrelevant data to produce runtime-relevant data.
viewS : (n : Nat) -> (0 p : HasLength xs (S n)) -> View xs (Element (S n) p)
viewS n (S p) = S (Element n p)
||| Proof that the view covers all possible cases.
export
view : (p : Subset Nat (HasLength xs)) -> View xs p
view (Element Z p) = viewZ p
view (Element (S n) p) = viewS n p
namespace CurriedView
||| We provide this view as a convenient way to perform nested pattern-matching
||| on pairs of values of type `n : Nat` and `HasLength xs n`. If transformations
||| to the list between recursive calls (e.g. mapping over the list) that prevent
||| it from being a valid termination metric, it is best to take the Nat argument
||| separately from the HasLength proof and the Subset view is not as useful anymore.
||| See e.g. natTerminating below for (a contrived example of) such a function.
public export
data View : (xs : List a) -> (n : Nat) -> HasLength xs n -> Type where
Z : View [] Z Z
S : (n : Nat) -> (0 p : HasLength xs n) -> View (x :: xs) (S n) (S p)
||| Proof that the view covers all possible cases.
export
view : (n : Nat) -> (0 p : HasLength xs n) -> View xs n p
view Z Z = Z
view (S n) (S p) = S n p
------------------------------------------------------------------------
-- Examples
-- /!\ Do NOT re-export these examples
listTerminating : (p : Subset Nat (HasLength xs)) -> HasLength (xs ++ [x]) (S (fst p))
listTerminating p = case view p of
Z => S Z
S p => S (listTerminating p)
data P : List Nat -> Type where
PNil : P []
PCon : P (map f xs) -> P (x :: xs)
covering
notListTerminating : (p : Subset Nat (HasLength xs)) -> P xs
notListTerminating p = case view p of
Z => PNil
S p => PCon (notListTerminating {xs = map id (tail xs)} ({ snd $= map id } p))
natTerminating : (n : Nat) -> (0 p : HasLength xs n) -> P xs
natTerminating n p = case view n p of
Z => PNil
S n p => PCon (natTerminating n (map id p))
|
data Natural = Zero | S Natural
eval : Natural -> Int
eval Zero = 0
eval (S n) = succ (eval n)
fromInt : Int -> Natural
fromInt n = case n <= 0 of
True => Zero
otherwise => S (fromInt (pred n))
|
State Before: K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.253674
R : Type u
M : Type v
inst✝⁴ : Ring R
inst✝³ : AddCommGroup M
inst✝² : Module R M
inst✝¹ : NoZeroSMulDivisors R M
inst✝ : Nontrivial R
⊢ 0 < Module.rank R M ↔ ∃ x, x ≠ 0 State After: K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.253674
R : Type u
M : Type v
inst✝⁴ : Ring R
inst✝³ : AddCommGroup M
inst✝² : Module R M
inst✝¹ : NoZeroSMulDivisors R M
inst✝ : Nontrivial R
⊢ ¬0 < Module.rank R M ↔ ¬∃ x, x ≠ 0 Tactic: rw [← not_iff_not] State Before: K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.253674
R : Type u
M : Type v
inst✝⁴ : Ring R
inst✝³ : AddCommGroup M
inst✝² : Module R M
inst✝¹ : NoZeroSMulDivisors R M
inst✝ : Nontrivial R
⊢ ¬0 < Module.rank R M ↔ ¬∃ x, x ≠ 0 State After: no goals Tactic: simpa using rank_zero_iff_forall_zero
|
module BottomUpMergeSort
import Sortable
%default total
%access private
export
data MergeSort a = MS Int (Lazy (List (List a)))
mrg : Ord a => List a -> List a -> List a
mrg [] ys = ys
mrg xs [] = xs
mrg xs@(x :: xs') ys@(y :: ys') =
if x <= y then x :: mrg xs' ys else y :: mrg xs ys'
addSeg : Ord a => List a -> List (List a) -> Int -> List (List a)
addSeg seg segs size = let size' = assert_total $ size `div` 2
r = assert_total $ size `mod` 2 in
if 0 == r then seg :: segs
else addSeg (mrg seg (head segs {ok = segsNonEmpty}))
(tail segs {ok = segsNonEmpty})
(assert_smaller size size')
where
segsNonEmpty = believe_me "length segs = ceil lg size"
export
Sortable MergeSort where
empty = MS 0 []
add x (MS size segs) = MS (size + 1) (addSeg [x] segs size)
sort (MS size segs) = foldl mrg [] segs
|
It is very apparent that the people who’ve created this has good eyes for art. This is a type of place I would never get tired visiting. This is such a great location.
This is amazing! Love it! Have a great week!
I’ve seen your video and it looks really nice. I’ve read a little more about the museum on my own and it seemed really interesting. I’ve studied a lot about environmentally friendly techniques and I think it’s great that more and more places sharing information about being eco-friendly are built.
That’s so great I love the idea they have of showing us how to take care of our planet!
thank you so much! It’s really amazing that they tell all of that!
This is so awesome- glad you got to go + thanks for sharing your trip with us!
|
Require Import Coq.omega.Omega.
Require Import Coq.Lists.List Coq.Lists.SetoidList Coq.Bool.Bool
Fiat.Common Fiat.Common.List.Operations Fiat.Common.Equality Fiat.Common.List.FlattenList Fiat.Common.LogicFacts.
Unset Implicit Arguments.
Local Notation iffT A B := ((A -> B) * (B -> A))%type.
Section ListFacts.
Lemma map_id :
forall {A: Type} (seq: list A),
(map (fun x => x) seq) = seq.
Proof.
intros A seq; induction seq; simpl; congruence.
Qed.
Lemma app_singleton :
forall {A} (x: A) s,
[x] ++ s = x :: s.
Proof.
reflexivity.
Qed.
Lemma app_eq_nil_iff :
forall {A} s1 s2,
@nil A = s1 ++ s2 <-> ([] = s1 /\ [] = s2).
Proof.
intros; split; intro H.
- symmetry in H; apply app_eq_nil in H; intuition.
- intuition; subst; intuition.
Qed.
Lemma singleton_neq_nil :
forall {A} (a: A),
[a] = [] <-> False.
Proof.
intuition discriminate.
Qed.
Lemma in_nil_iff :
forall {A} (item: A),
List.In item [] <-> False.
Proof.
intuition.
Qed.
Lemma in_not_nil :
forall {A} x seq,
@List.In A x seq -> seq <> nil.
Proof.
intros A x seq in_seq eq_nil.
apply (@in_nil _ x).
subst seq; assumption.
Qed.
Lemma in_seq_false_nil_iff :
forall {A} (seq: list A),
(forall (item: A), (List.In item seq <-> False)) <->
(seq = []).
Proof.
intros.
destruct seq; simpl in *; try tauto.
split; intro H.
pose proof (H a); intuition.
discriminate.
Qed.
Lemma map_map :
forall { A B C } (f: A -> B) (g: B -> C),
forall seq,
List.map g (List.map f seq) = List.map (fun x => g (f x)) seq.
Proof.
intros; induction seq; simpl; f_equal; trivial.
Qed.
Lemma filter_all_true :
forall {A} pred (seq: list A),
(forall x, List.In x seq -> pred x = true) ->
List.filter pred seq = seq.
Proof.
induction seq as [ | head tail IH ]; simpl; trivial.
intros all_true.
rewrite all_true by eauto.
f_equal; intuition.
Qed.
Lemma filter_all_false :
forall {A} seq pred,
(forall item : A, List.In item seq -> pred item = false) ->
List.filter pred seq = [].
Proof.
intros A seq pred all_false; induction seq as [ | head tail IH ]; simpl; trivial.
rewrite (all_false head) by (simpl; eauto).
intuition.
Qed.
Lemma map_filter_all_false :
forall {A} pred seq,
(forall subseq, List.In subseq seq ->
forall (item: A), List.In item subseq ->
pred item = false) ->
(List.map (List.filter pred) seq) = (List.map (fun x => []) seq).
Proof.
intros A pred seq all_false;
induction seq as [ | subseq subseqs IH ] ; simpl; trivial.
f_equal.
specialize (all_false subseq (or_introl eq_refl)).
apply filter_all_false; assumption.
apply IH; firstorder.
Qed.
Lemma foldright_compose :
forall {TInf TOutf TAcc}
(g : TOutf -> TAcc -> TAcc) (f : TInf -> TOutf)
(seq : list TInf) (init : TAcc),
List.fold_right (compose g f) init seq =
List.fold_right g init (List.map f seq).
Proof.
intros;
induction seq;
simpl;
[ | rewrite IHseq ];
reflexivity.
Qed.
Lemma in_map_unproject :
forall {A B} projection seq,
forall item,
@List.In A item seq ->
@List.In B (projection item) (List.map projection seq).
Proof.
intros ? ? ? seq;
induction seq; simpl; intros item in_seq.
trivial.
destruct in_seq;
[ left; f_equal | right ]; intuition.
Qed.
Lemma refold_map :
forall {A B} (f: A -> B) x seq,
f x :: map f seq = map f (x :: seq).
Proof.
simpl; reflexivity.
Qed.
Lemma refold_in :
forall {A} a b l,
@List.In A a (b :: l) <-> List.In a l \/ a = b.
Proof.
intros; simpl; intuition.
Qed.
Lemma app_map_inv :
forall {A B} seq l1 l2 (f: A -> B),
l1 ++ l2 = map f seq ->
exists l1' l2',
seq = l1' ++ l2' /\ l1 = map f l1' /\ l2 = map f l2'.
Proof.
induction seq; simpl; intros.
exists (@nil A); exists (@nil A); simpl.
apply app_eq_nil in H; intuition.
destruct l1.
rewrite app_nil_l in H.
exists (@nil A); exists (a :: seq); simpl; intuition.
rewrite <- app_comm_cons in H.
inversion H.
specialize (IHseq _ _ _ H2).
destruct IHseq as [l1' [l2' (seq_eq_app & l1l1' & l2l2') ] ].
exists (a :: l1'); exists (l2'); subst; intuition.
Qed.
Lemma cons_map_inv :
forall {A B} seq x1 l2 (f: A -> B),
x1 :: l2 = map f seq ->
exists x1' l2',
seq = x1' :: l2' /\ x1 = f x1' /\ l2 = map f l2'.
Proof.
intros * _eq.
destruct seq as [ | x1' l2' ]; simpl in *; try discriminate.
inversion _eq.
exists x1'; exists l2'; subst; intuition.
Qed.
Lemma map_eq_nil_inv :
forall {A B} (f: A -> B) seq,
map f seq = [] -> seq = [].
Proof.
intros; destruct seq; simpl in *; try discriminate; trivial.
Qed.
Lemma filter_app :
forall {A} (f: A -> _) s1 s2,
List.filter f (s1 ++ s2) =
List.filter f s1 ++ List.filter f s2.
Proof.
induction s1; simpl; intros.
- reflexivity.
- destruct (f a); simpl; congruence.
Qed.
Lemma filter_map :
forall {A B} f g seq,
List.filter f (@List.map A B g seq) =
List.map g (List.filter (fun x => f (g x)) seq).
Proof.
induction seq; simpl; intros.
- reflexivity.
- destruct (f (g a)); simpl; [ f_equal | ]; assumption.
Qed.
Lemma filter_true :
forall {A} s,
@filter A (fun _ => true) s = s.
Proof.
induction s; simpl; try rewrite IHs; reflexivity.
Qed.
Lemma filter_false :
forall {A} s,
@filter A (fun _ => false) s = [].
Proof.
induction s; simpl; try rewrite IHs; reflexivity.
Qed.
Lemma filter_flat_map_join_snd :
forall {A B} f s1 s2,
flat_map (filter (fun x : A * B => f (snd x)))
(map (fun a1 : A => map (fun b : B => (a1, b)) s2) s1) =
flat_map (fun a1 : A => map (fun b : B => (a1, b)) (filter f s2)) s1.
Proof.
induction s1; simpl; intros; trivial.
rewrite IHs1; f_equiv.
rewrite filter_map; simpl; reflexivity.
Qed.
Lemma flat_map_empty :
forall {A B} s,
@flat_map A B (fun _ => []) s = [].
Proof.
induction s; firstorder.
Qed.
Lemma filter_commute :
forall {A} f g seq,
@filter A f (filter g seq) = filter g (filter f seq).
Proof.
induction seq; simpl; intros; trivial.
destruct (f a) eqn:eqf; destruct (g a) eqn:eqg;
simpl; rewrite ?eqf, ?eqg, ?IHseq; trivial.
Qed.
Lemma fold_right_id {A} :
forall seq,
@List.fold_right (list A) A (fun elem acc => elem :: acc) [] seq = seq.
Proof.
induction seq; simpl; try rewrite IHseq; congruence.
Qed.
Lemma fold_left_id {A} :
forall seq,
@List.fold_left (list A) A (fun acc elem => elem :: acc) seq [] = rev seq.
Proof.
intros.
rewrite <- fold_left_rev_right.
apply fold_right_id.
Qed.
Lemma In_partition {A}
: forall f (l : list A) a,
List.In a l <-> (List.In a (fst (List.partition f l))
\/ List.In a (snd (List.partition f l))).
Proof.
split; induction l; simpl; intros; intuition; simpl; subst;
first [destruct (f a0); destruct (List.partition f l); simpl in *; intuition
| destruct (f a); destruct (List.partition f l); simpl; intuition].
Qed.
Lemma In_partition_matched {A}
: forall f (l : list A) a,
List.In a (fst (List.partition f l)) ->
f a = true.
Proof.
induction l; simpl; intros; intuition; simpl; subst; eauto.
case_eq (f a); destruct (List.partition f l); simpl; intuition;
rewrite H0 in H; eauto; inversion H; subst; eauto.
Qed.
Lemma In_partition_unmatched {A}
: forall f (l : list A) a,
List.In a (snd (List.partition f l)) ->
f a = false.
Proof.
induction l; simpl; intros; intuition; simpl; subst; eauto.
case_eq (f a); destruct (List.partition f l); simpl; intuition;
rewrite H0 in H; eauto; inversion H; subst; eauto.
Qed.
Lemma nil_in_false :
forall {A} seq,
seq = nil <-> ~ exists (x: A), List.In x seq.
Proof.
split; intro H.
intros [ x in_seq ]; subst; eauto using in_nil.
destruct seq as [ | a ]; trivial.
exfalso; apply H; exists a; simpl; intuition.
Qed.
Lemma In_InA :
forall (A : Type) (l : list A) (eqA : relation A) (x : A),
Equivalence eqA -> List.In x l -> InA eqA x l.
Proof.
induction l; intros; simpl in *.
exfalso; eauto using in_nil.
destruct H0.
apply InA_cons_hd; subst; reflexivity.
apply InA_cons_tl, IHl; trivial.
Qed.
Lemma fold_map :
forall {A B C} seq f g init,
@List.fold_left C A (fun acc x => f acc (g x)) seq init =
@List.fold_left C B (fun acc x => f acc ( x)) (@List.map A B g seq) init.
Proof.
induction seq; simpl; intros; trivial; try rewrite IHseq; intuition.
Qed.
Lemma fold_plus_sym :
forall (seq: list nat) (default: nat),
List.fold_right plus default seq =
List.fold_left plus seq default.
Proof.
intros; rewrite <- fold_left_rev_right.
revert default; induction seq; simpl; eauto; intros.
rewrite fold_right_app; simpl; rewrite <- IHseq.
clear IHseq; revert a default; induction seq;
simpl; intros; auto with arith.
rewrite <- IHseq.
rewrite Plus.plus_comm, <- Plus.plus_assoc; f_equal.
rewrite Plus.plus_comm; reflexivity.
Qed.
Lemma map_snd {A B C} :
forall (f : A -> B) (l : list (C * A)),
List.map f (List.map snd l) =
List.map snd (List.map (fun ca => (fst ca, f (snd ca))) l).
Proof.
intros; repeat rewrite List.map_map; induction l; simpl; eauto.
Qed.
Lemma partition_app {A} :
forall f (l1 l2 : list A),
List.partition f (l1 ++ l2) =
(fst (List.partition f l1) ++ fst (List.partition f l2),
snd (List.partition f l1) ++ snd (List.partition f l2)).
Proof.
induction l1; simpl.
- intros; destruct (List.partition f l2); reflexivity.
- intros; rewrite IHl1; destruct (f a); destruct (List.partition f l1);
simpl; f_equal.
Qed.
Lemma partition_filter_eq {A} :
forall (f : A -> bool) l,
fst (List.partition f l) = List.filter f l.
Proof.
induction l; simpl; eauto.
destruct (List.partition f l); destruct (f a); simpl in *; congruence.
Qed.
Lemma partition_filter_neq {A} :
forall (f : A -> bool) l,
snd (List.partition f l) = List.filter (fun a => negb (f a)) l.
Proof.
induction l; simpl; eauto.
destruct (List.partition f l); destruct (f a); simpl in *; congruence.
Qed.
Lemma filter_app_inv {A}
: forall pred (l l1 l2 : list A),
filter pred l = app l1 l2
-> exists l1' l2', l = app l1' l2'
/\ l1 = filter pred l1'
/\ l2 = filter pred l2'.
Proof.
induction l; simpl; intros.
- destruct l1; simpl in *;
[ destruct l2;
[ eexists nil; eexists nil; intuition
| discriminate]
| discriminate ].
- revert H; case_eq (pred a); intros.
+ destruct l1; simpl in *.
* destruct l2; [ discriminate | ].
injection H0; intros.
apply (IHl [] l2) in H1; destruct_ex; intuition; subst.
eexists []; eexists (_ :: _); intuition; simpl.
rewrite H, H0; reflexivity.
* injection H0; intros.
apply IHl in H1; destruct_ex; subst.
eexists (a0 :: x); eexists x0; intuition.
rewrite H2; reflexivity.
simpl; rewrite H, H1; reflexivity.
+ apply IHl in H0; destruct_ex; subst.
eexists (a :: x); eexists x0; intuition.
rewrite H1; reflexivity.
simpl; rewrite H, H0; reflexivity.
Qed.
Lemma fold_left_sum_acc :
forall {A B} seq m n (f: A -> list B),
m +
fold_left (fun (count : nat) (x : A) => count + length (f x)) seq n =
fold_left (fun (count : nat) (x : A) => count + length (f x)) seq
(n + m).
Proof.
induction seq; simpl; intros; eauto with arith.
rewrite IHseq; f_equal; eauto with arith.
repeat rewrite <- Plus.plus_assoc; f_equal; auto with arith.
Qed.
Lemma length_flat_map :
forall {A B} seq (f: A -> list B),
List.length (flat_map f seq) =
fold_left (fun count (x : A) => count + List.length (f x)) seq 0.
Proof.
simpl; induction seq; simpl; intros; eauto.
rewrite app_length, IHseq; clear.
apply fold_left_sum_acc.
Qed.
Lemma filter_and {A}
: forall (pred1 pred2 : A -> bool) (l : List.list A),
List.filter (fun a => pred1 a && pred2 a) l =
List.filter pred2 (List.filter pred1 l).
Proof.
induction l; simpl; eauto.
case_eq (pred1 a); simpl; intros H; eauto;
case_eq (pred2 a); simpl; intros; rewrite IHl; eauto.
Qed.
Definition ExtensionalEq {A B} f g :=
forall (a: A), @eq B (f a) (g a).
Lemma filter_by_equiv :
forall {A} f g,
ExtensionalEq f g ->
forall seq, @List.filter A f seq = @List.filter A g seq.
Proof.
intros A f g obs seq; unfold ExtensionalEq in obs; induction seq; simpl; try rewrite obs; try rewrite IHseq; trivial.
Qed.
Lemma filter_by_equiv_meta :
forall {A B : Type} (f g : A -> B -> bool),
(forall (a: A), ExtensionalEq (f a) (g a)) ->
(forall (a: A) (seq : list B), filter (f a) seq = filter (g a) seq).
Proof.
intros * equiv *;
rewrite (filter_by_equiv _ _ (equiv _));
reflexivity.
Qed.
Lemma filter_and' :
forall {A} pred1 pred2,
forall (seq: list A),
List.filter (fun x => andb (pred1 x) (pred2 x)) seq =
List.filter pred1 (List.filter pred2 seq).
Proof.
intros;
induction seq;
simpl;
[ | destruct (pred1 a) eqn:eq1;
destruct (pred2 a) eqn:eq2];
simpl;
try rewrite eq1;
try rewrite eq2;
trivial;
f_equal;
trivial.
Qed.
Local Ltac drop_take_t' :=
idtac;
match goal with
| _ => reflexivity
| _ => intro
| _ => progress simpl in *
| [ |- context[drop ?n []] ] => atomic n; destruct n
| [ |- context[take ?n []] ] => atomic n; destruct n
| [ |- context[drop ?n (_::_)] ] => atomic n; destruct n
| [ |- context[take ?n (_::_)] ] => atomic n; destruct n
| [ H : _ |- _ ] => rewrite H
| _ => solve [ eauto with arith ]
| _ => exfalso; omega
end.
Local Ltac drop_take_t := repeat drop_take_t'.
Lemma drop_map {A B n} (f : A -> B) ls
: drop n (map f ls) = map f (drop n ls).
Proof.
revert n; induction ls; drop_take_t.
Qed.
Lemma take_map {A B n} (f : A -> B) ls
: take n (map f ls) = map f (take n ls).
Proof.
revert n; induction ls; drop_take_t.
Qed.
Lemma take_all {A n} {ls : list A} (H : List.length ls <= n) : take n ls = ls.
Proof.
revert n H; induction ls; drop_take_t.
Qed.
Lemma drop_all {A n} {ls : list A} (H : List.length ls <= n) : drop n ls = nil.
Proof.
revert n H; induction ls; drop_take_t.
Qed.
Lemma drop_all_iff {A n} {ls : list A}
: (List.length ls <= n) <-> drop n ls = nil.
Proof.
split; [ apply drop_all | ].
revert n; induction ls; [ simpl; intros; omega | ].
intros [|n]; simpl.
{ intro; discriminate. }
{ intro; auto with arith. }
Qed.
Lemma take_append {A n} {ls ls' : list A}
: take n (ls ++ ls') = take n ls ++ take (n - List.length ls) ls'.
Proof.
revert n ls'; induction ls; drop_take_t.
Qed.
Lemma drop_append {A n} {ls ls' : list A}
: drop n (ls ++ ls') = drop n ls ++ drop (n - List.length ls) ls'.
Proof.
revert n ls'; induction ls; drop_take_t.
Qed.
Lemma fold_right_and_map_impl {A} {init1 init2 : Prop} (H : init1 -> init2) (ls : list A) (f g : A -> Prop) (H' : forall x, f x -> g x)
: fold_right and init1 (map f ls) -> fold_right and init2 (map g ls).
Proof.
induction ls; simpl; trivial; intuition.
Qed.
Lemma f_fold_right_bool_rect {A B T} (f : T -> B) init (ls : list A) a b
: f (fold_right (fun x acc => bool_rect (fun _ => T) (a x) acc (b x)) init ls)
= fold_right (fun x acc => bool_rect (fun _ => B) (f (a x)) acc (b x)) (f init) ls.
Proof.
revert init; induction ls; simpl; trivial; intros.
edestruct b; simpl; trivial.
Qed.
Lemma fold_right_fun {A B C} (f : A -> C -> (B -> C)) (init : B -> C) (x : B) (ls : list A)
: fold_right (fun (a : A) (b : B -> C) x => f a (b x) x) init ls x
= fold_right (B := A) (A := C) (fun a b => f a b x) (init x) ls.
Proof.
induction ls; simpl; trivial.
rewrite IHls; reflexivity.
Qed.
Lemma nth_tl {A} n (ls : list A) a
: nth n (tl ls) a = nth (S n) ls a.
Proof.
destruct ls, n; simpl; reflexivity.
Qed.
Lemma nth_drop {A} x y (ls : list A) a
: nth x (drop y ls) a = nth (x + y) ls a.
Proof.
revert x y; induction ls; simpl; intros.
{ destruct x, y; reflexivity. }
{ destruct y; simpl.
{ destruct x; simpl; repeat (f_equal; []); try reflexivity; omega. }
{ rewrite IHls; destruct x; simpl; repeat (f_equal; []); try reflexivity; omega. } }
Qed.
Lemma nth_error_drop {A} x y (ls : list A)
: nth_error (drop y ls) x = nth_error ls (x + y).
Proof.
revert x y; induction ls; simpl; intros.
{ destruct x, y; reflexivity. }
{ destruct y; simpl.
{ destruct x; simpl; repeat (f_equal; []); try reflexivity; omega. }
{ rewrite IHls; destruct x; simpl; repeat (f_equal; []); try reflexivity.
rewrite NPeano.Nat.add_succ_r; reflexivity. } }
Qed.
Lemma in_map_iffT' {A B}
(f : A -> B) (ls : list A) (y : B)
(eq_dec : forall y', {y = y'} + {y <> y'})
: iffT (In y (map f ls)) { x : A | f x = y /\ In x ls }.
Proof.
split; [ | intros [x H]; apply in_map_iff; exists x; assumption ].
induction ls as [|l ls IHls].
{ simpl; intros []. }
{ simpl.
intro H.
destruct (eq_dec (f l)) as [e|e].
{ exists l; split.
{ clear -e; abstract (subst; reflexivity). }
{ left. reflexivity. } }
{ destruct IHls as [x H'].
{ clear -H e.
abstract (destruct H; congruence). }
{ eexists.
split; [ apply H' | right; apply H' ]. } } }
Defined.
Lemma in_map_iffT {A B}
(eq_dec : forall y y' : B, {y = y'} + {y <> y'})
(f : A -> B) (ls : list A) (y : B)
: iffT (In y (map f ls)) { x : A | f x = y /\ In x ls }.
Proof.
apply in_map_iffT', eq_dec.
Defined.
Lemma in_map_iffT_nat {A}
(f : A -> nat) (ls : list A) (y : nat)
: iffT (In y (map f ls)) { x : A | f x = y /\ In x ls }.
Proof.
apply in_map_iffT, NPeano.Nat.eq_dec.
Defined.
Lemma nth_take_1_drop {A} (ls : list A) n a
: nth n ls a = match take 1 (drop n ls) with
| nil => a
| x::_ => x
end.
Proof.
revert n.
induction ls as [|x xs IHxs]; simpl; intros.
{ destruct n; reflexivity. }
{ destruct n; simpl; trivial; [].
rewrite IHxs; simpl; reflexivity. }
Qed.
Lemma drop_drop {A} x y (ls : list A)
: drop x (drop y ls) = drop (y + x) ls.
Proof.
revert x y.
induction ls as [|l ls IHls].
{ intros [|x] [|y]; reflexivity. }
{ intros x [|y]; simpl.
{ reflexivity. }
{ apply IHls. } }
Defined.
Lemma drop_dropS {A} y (ls : list A)
: drop 1 (drop y ls) = drop (S y) ls.
Proof.
rewrite drop_drop.
rewrite NPeano.Nat.add_1_r.
reflexivity.
Qed.
Lemma map_S_seq {A} (f : nat -> A) x y
: map (fun i => f (S i)) (seq x y) = map f (seq (S x) y).
Proof.
clear; revert x; induction y; intros.
{ reflexivity. }
{ simpl.
rewrite IHy; reflexivity. }
Qed.
Lemma length_drop {A} (n : nat) (ls : list A)
: List.length (List.drop n ls) = List.length ls - n.
Proof.
revert ls; induction n; simpl; intros.
{ auto with arith. }
{ destruct ls; simpl; [ reflexivity | ].
apply IHn. }
Qed.
Lemma drop_non_empty {A} (n : nat) (ls : list A)
(H : ls <> nil)
: List.drop (List.length ls - S n) ls <> nil.
Proof.
intro H'.
apply (f_equal (@List.length _)) in H'.
simpl in H'.
rewrite length_drop in H'.
destruct ls.
{ apply H; reflexivity. }
{ simpl length in H'.
omega. }
Qed.
Lemma drop_S_non_empty {A} (n : nat) (ls : list A)
(H : n < List.length ls)
: List.drop (List.length ls - S n) ls <> nil.
Proof.
intro H'.
apply (f_equal (@List.length _)) in H'.
simpl in H'.
rewrite length_drop in H'.
omega.
Qed.
Lemma seq_S (start len : nat)
: seq (S start) len = map S (seq start len).
Proof.
revert start; induction len; [ reflexivity | ].
simpl in *; intros.
rewrite IHlen; reflexivity.
Qed.
Lemma seq_0 (start len : nat)
: seq start len = map (fun x => start + x) (seq 0 len).
Proof.
revert start; induction len; simpl; intros.
{ reflexivity. }
{ rewrite IHlen; simpl.
rewrite seq_S.
rewrite map_map.
apply f_equal2.
{ omega. }
{ apply map_ext; intro; omega. } }
Qed.
Lemma seq_alt (start len : nat)
: seq start len = match len with
| 0 => nil
| S len' => start :: map S (seq start len')
end.
Proof.
destruct len; simpl.
{ reflexivity. }
{ apply f_equal2.
{ reflexivity. }
{ rewrite seq_S.
reflexivity. } }
Qed.
Lemma In_S_seq {start len x} (Hsmall : start <= x) (H : In (S x) (seq start len))
: In x (seq start len).
Proof.
generalize dependent start; generalize x; induction len; intros; simpl in *.
{ assumption. }
{ destruct H as [H|H].
{ exfalso; omega. }
{ simpl in *.
destruct (lt_eq_lt_dec start x0) as [[H' | H'] | H'];
[ right; apply IHlen; assumption
| left; assumption
| exfalso; omega ]. } }
Qed.
Lemma uniquize_idempotent {A} (beq : A -> A -> bool) (ls : list A)
: uniquize beq (uniquize beq ls) = uniquize beq ls.
Proof.
induction ls as [|x xs IHxs]; simpl; trivial.
destruct (Equality.list_bin beq x (uniquize beq xs)) eqn:H;
simpl;
rewrite ?IHxs, ?H; reflexivity.
Qed.
Lemma uniquize_NoDupA {A} (beq : A -> A -> bool) (ls : list A)
: NoDupA (fun x y => beq y x) (uniquize beq ls).
Proof.
induction ls as [|x xs IHxs]; simpl; [ solve [ constructor ] | ].
destruct (Equality.list_bin beq x (uniquize beq xs)) eqn:H; trivial.
constructor; trivial.
intro H'.
apply Equality.list_inA_lb in H'.
congruence.
Qed.
Lemma uniquize_NoDup {A} (beq : A -> A -> bool) (beq_lb : forall x y, x = y -> beq x y = true) (ls : list A)
: NoDup (uniquize beq ls).
Proof.
eapply NoDupA_NoDup; [ | apply uniquize_NoDupA ].
repeat intro; eauto.
Qed.
Lemma NoDupA_uniquize {A} (beq : A -> A -> bool) (ls : list A) (H : NoDupA (fun x y => beq y x) ls)
: uniquize beq ls = ls.
Proof.
induction ls as [|x xs IHxs]; simpl; [ solve [ constructor ] | ].
inversion H; subst.
rewrite IHxs by assumption; clear IHxs.
destruct (Equality.list_bin beq x xs) eqn:H'; trivial.
exfalso.
apply Equality.list_inA_bl in H'.
tauto.
Qed.
Lemma NoDup_NoDupA {A} (R : relation A) (ls : list A) (R_eq : forall x y, R x y -> x = y) (H : NoDup ls)
: NoDupA R ls.
Proof.
induction ls; [ solve [ constructor ] | ].
inversion H; subst.
constructor; auto.
rewrite InA_alt.
intros [y [H' H'']].
match goal with
| [ H : _ |- _ ] => apply R_eq in H; subst
end.
tauto.
Qed.
Lemma NoDup_uniquize {A} (beq : A -> A -> bool) (beq_bl : forall x y, beq x y = true -> x = y) (ls : list A) (H : NoDup ls)
: uniquize beq ls = ls.
Proof.
apply NoDupA_uniquize, NoDup_NoDupA; trivial; intros.
symmetry; eauto.
Qed.
Lemma uniquize_shorter {A} (ls : list A) beq
: List.length (uniquize beq ls) <= List.length ls.
Proof.
induction ls as [|x xs IHxs]; simpl; trivial.
edestruct @Equality.list_bin; simpl; omega.
Qed.
Lemma uniquize_length {A} (ls : list A) beq
: List.length (uniquize beq ls) = List.length ls
<-> uniquize beq ls = ls.
Proof.
induction ls as [|x xs IHxs]; simpl; try (split; reflexivity).
edestruct @Equality.list_bin; simpl.
{ pose proof (uniquize_shorter xs beq).
split; intro H'.
{ omega. }
{ apply (f_equal (@List.length _)) in H'.
simpl in H'.
omega. } }
{ destruct IHxs.
split; intro;
first [ congruence
| f_equal; auto ]. }
Qed.
Lemma uniquize_In {A} (ls : list A) (beq : A -> A -> bool) x
: In x (uniquize beq ls) -> In x ls.
Proof.
intro H; induction ls as [|y ys IHys]; simpl in *; trivial.
destruct (Equality.list_bin beq y (uniquize beq ys)) eqn:H'.
{ right; eauto with nocore. }
{ destruct H.
{ left; assumption. }
{ right; eauto with nocore. } }
Qed.
Lemma uniquize_In_refl {A} (ls : list A) (beq : A -> A -> bool) x (refl : beq x x = true) (bl : forall x y, beq x y = true -> x = y)
: In x ls -> In x (uniquize beq ls).
Proof.
intro H; induction ls as [|y ys IHys]; simpl in *; trivial.
destruct (Equality.list_bin beq y (uniquize beq ys)) eqn:H';
destruct H; subst;
eauto with nocore.
{ apply Equality.list_in_bl in H'; assumption. }
{ left; reflexivity. }
{ right; eauto with nocore. }
Qed.
Lemma uniquize_In_refl_iff {A} (ls : list A) (beq : A -> A -> bool) x (refl : beq x x = true) (bl : forall x y, beq x y = true -> x = y)
: In x ls <-> In x (uniquize beq ls).
Proof.
split; first [ apply uniquize_In | apply uniquize_In_refl ]; assumption.
Qed.
Lemma fold_right_bool_rect {T} t b init ls' bv
: fold_right (fun (x : T) (acc : bool -> bool)
=> bool_rect
(fun _ => bool -> bool)
(t x)
acc
(b x))
init ls' bv
= fold_right (fun (x : T) (acc : bool)
=> bool_rect
(fun _ => bool)
(t x bv)
acc
(b x)) (init bv) ls'.
Proof.
induction ls' as [|x xs IHxs]; simpl;
[ | destruct (b x); simpl; rewrite ?IHxs ];
reflexivity.
Qed.
Lemma in_up_to {n m} (H : n < m) : List.In n (up_to m).
Proof.
revert n H; induction m; intros n H.
{ exfalso; omega. }
{ simpl.
hnf in H.
apply le_S_n in H.
apply Compare_dec.le_lt_eq_dec in H.
destruct H; subst; [ right; eauto | left; reflexivity ]. }
Qed.
Lemma in_up_to_iff {n m} : (n < m) <-> List.In n (up_to m).
Proof.
revert n; induction m; intros n; simpl.
{ split; intro; exfalso; omega. }
{ simpl.
specialize (IHm n).
destruct IHm.
destruct (lt_eq_lt_dec n m) as [[?|?]|?]; split; intros; try omega; eauto; intuition. }
Qed.
Lemma first_index_helper_first_index_error
{A B} (f : A -> bool)
(rect : option (nat * A) -> B) (ls : list A) (rec : nat * A -> nat * A)
: first_index_helper f rect ls rec
= rect (let idx := first_index_error f ls in
let v := option_rect (fun _ => option A) (nth_error ls) None idx in
option_map
rec
(option_rect
(fun _ => option (nat * A))
(fun v' : A => option_map (fun idx' : nat => (idx', v')) idx)
None
v)).
Proof.
revert B rec rect; induction ls as [|x xs IHxs]; simpl; intros.
{ reflexivity. }
{ destruct (f x).
{ reflexivity. }
{ rewrite !IHxs.
destruct (first_index_error f xs) as [idx|] eqn:Heq;
simpl; [ | reflexivity ].
destruct (nth_error xs idx) eqn:Heq'; simpl; [ | reflexivity ].
rewrite Heq'; simpl.
reflexivity. } }
Qed.
Local Ltac first_index_error_t'
:= idtac;
match goal with
| _ => discriminate
| _ => congruence
| _ => omega
| _ => progress unfold value in *
| [ H : Some _ = Some _ |- _ ] => inversion H; clear H
| _ => progress subst
| [ H : ?x = true |- context[?x] ] => rewrite H
| [ H : and _ _ |- _ ] => destruct H
| [ H : ex _ |- _ ] => destruct H
| [ H : iff _ _ |- _ ] => destruct H
| [ H : ?x = ?x -> ?A |- _ ] => specialize (H eq_refl)
| _ => progress intros
| _ => split
| [ H : context[if ?b then _ else _] |- _ ] => destruct b eqn:?
| [ H : context[option_map _ ?x] |- _ ] => destruct x eqn:?; unfold option_map in H
| _ => solve [ repeat (esplit || eassumption) ]
| [ H : context[nth_error (_::_) ?x] |- _ ] => is_var x; destruct x; simpl nth_error in H
| [ H : S _ < S _ |- _ ] => apply lt_S_n in H
| _ => solve [ eauto with nocore ]
| [ |- context[if ?b then _ else _] ] => destruct b eqn:?
| [ H : ?A -> ?B |- _ ] => let H' := fresh in assert (H' : A) by (assumption || omega); specialize (H H'); clear H'
| [ H : forall n, n < S _ -> _ |- _ ] => pose proof (H 0); specialize (fun n => H (S n))
| _ => progress simpl in *
| [ H : forall x, ?f x = ?f ?y -> _ |- _ ] => specialize (H _ eq_refl)
| [ H : forall x, ?f ?y = ?f x -> _ |- _ ] => specialize (H _ eq_refl)
| [ H : forall n, S n < S _ -> _ |- _ ] => specialize (fun n pf => H n (lt_n_S _ _ pf))
| [ H : nth_error nil ?x = Some _ |- _ ] => is_var x; destruct x
| [ H : forall m x, nth_error (_::_) m = Some _ -> _ |- _ ] => pose proof (H 0); specialize (fun m => H (S m))
| [ H : or _ _ |- _ ] => destruct H
| [ H : forall x, _ = x \/ _ -> _ |- _ ] => pose proof (H _ (or_introl eq_refl)); specialize (fun x pf => H x (or_intror pf))
| [ H : ?x = None |- context[?x] ] => rewrite H
| [ H : S _ = S _ |- _ ] => inversion H; clear H
| [ H : appcontext[first_index_helper] |- _ ] => rewrite first_index_helper_first_index_error in H
| [ |- appcontext[first_index_helper] ] => rewrite first_index_helper_first_index_error
| [ H : option_rect _ _ _ ?v = Some _ |- _ ] => destruct v eqn:?; simpl in H
| [ H : option_rect _ _ _ ?v = None |- _ ] => destruct v eqn:?; simpl in H
end.
Local Ltac first_index_error_t :=
repeat match goal with
| _ => progress first_index_error_t'
| [ H : _ |- _ ] => rewrite H by repeat first_index_error_t'
end.
Lemma first_index_error_Some_correct {A} (P : A -> bool) (n : nat) (ls : list A)
: first_index_error P ls = Some n <-> ((exists elem, nth_error ls n = Some elem /\ P elem = true)
/\ forall m, m < n -> forall elem, nth_error ls m = Some elem -> P elem = false).
Proof.
revert n.
induction ls; simpl; intros.
{ destruct n; first_index_error_t. }
{ specialize (IHls (pred n)).
destruct n; first_index_error_t. }
Qed.
Lemma first_index_error_None_correct {A} (P : A -> bool) (ls : list A)
: first_index_error P ls = None <-> (forall elem, List.In elem ls -> P elem = false).
Proof.
induction ls; simpl; intros.
{ first_index_error_t. }
{ first_index_error_t.
match goal with
| [ H : first_index_error _ _ = Some _ |- _ ] => apply first_index_error_Some_correct in H
end.
first_index_error_t. }
Qed.
Lemma first_index_default_first_index_error
{A} (f : A -> bool)
default
(ls : list A)
: first_index_default f default ls
= option_rect (fun _ => nat) (fun x => x) default (first_index_error f ls).
Proof.
unfold first_index_default.
rewrite first_index_helper_first_index_error; simpl.
destruct (first_index_error f ls) as [n|] eqn:H; simpl; [ | reflexivity ].
destruct (nth_error ls n) eqn:H'; simpl; [ reflexivity | ].
exfalso.
apply first_index_error_Some_correct in H.
repeat (destruct_head and; destruct_head ex).
congruence.
Qed.
Lemma nth_error_In {A} (n : nat) (x : A) (ls : list A)
: nth_error ls n = Some x -> List.In x ls.
Proof.
revert n; induction ls; intros [|n]; simpl in *;
intros; try discriminate; unfold value in *.
{ left; congruence. }
{ right; eauto. }
Qed.
Lemma nth_error_None_long {A} (n : nat) (ls : list A)
: nth_error ls n = None <-> List.length ls <= n.
Proof.
revert n; induction ls;
intros [|n]; try (specialize (IHls n); destruct IHls);
simpl in *; split; intros;
unfold value in *;
try (reflexivity || omega || congruence);
intuition.
Qed.
Lemma nth_error_Some_short {A} (n : nat) (x : A) (ls : list A)
: nth_error ls n = Some x -> n < List.length ls.
Proof.
destruct (le_lt_dec (List.length ls) n) as [H|H];
intro H'; trivial.
apply nth_error_None_long in H; congruence.
Qed.
Lemma nth_error_nth {A} (ls : list A) (n : nat) (y : A)
: nth n ls y = match nth_error ls n with
| Some x => x
| None => y
end.
Proof.
revert n; induction ls; intros [|n]; simpl in *; intros;
try discriminate;
unfold value in *;
eauto.
Qed.
Lemma nth_error_Some_nth {A} (ls : list A) (n : nat) (x : A)
: nth_error ls n = Some x -> forall y, nth n ls y = x.
Proof.
intros H ?; rewrite nth_error_nth, H; reflexivity.
Qed.
Lemma length_up_to n
: List.length (up_to n) = n.
Proof.
induction n; simpl; auto.
Qed.
Lemma filter_out_filter {A} f (ls : list A)
: filter_out f ls = filter (fun x => negb (f x)) ls.
Proof.
induction ls; simpl; trivial; rewrite !IHls; edestruct f; reflexivity.
Qed.
Lemma filter_filter_out {A} f (ls : list A)
: filter f ls = filter_out (fun x => negb (f x)) ls.
Proof.
induction ls; simpl; trivial; rewrite !IHls; edestruct f; reflexivity.
Qed.
Lemma nth'_helper_nth {A} n ls (default : A) offset (H : offset <= n)
: nth'_helper n ls default offset = nth (n - offset) ls default.
Proof.
revert n default offset H.
induction ls as [|x xs IHxs].
{ simpl; intros; destruct (n - offset); reflexivity. }
{ simpl; intros.
destruct (beq_nat n offset) eqn:H';
[ apply beq_nat_true in H'
| apply beq_nat_false in H' ];
subst;
rewrite ?minus_diag; trivial.
destruct (n - offset) eqn:H''.
{ omega. }
{ rewrite IHxs by omega.
f_equal.
omega. } }
Qed.
Lemma nth'_nth {A} n ls (default : A)
: nth' n ls default = nth n ls default.
Proof.
change (nth'_helper n ls default 0 = nth n ls default).
rewrite nth'_helper_nth by omega.
f_equal; omega.
Qed.
Lemma NoDup_filter {A} :
forall (f : A -> bool)
(l : list A),
NoDup l
-> NoDup (filter f l).
Proof.
induction l; simpl.
- constructor.
- case_eq (f a); simpl; intros.
+ inversion H0; constructor; eauto.
subst; unfold not; intros H1;
apply filter_In in H1; intuition.
+ inversion H0; eauto.
Qed.
Lemma eqlistA_app_iff {A} (R : relation A) (x y z : list A)
: SetoidList.eqlistA R (x ++ y) z <-> (exists x' y', (x' ++ y' = z)%list /\ SetoidList.eqlistA R x x' /\ SetoidList.eqlistA R y y').
Proof.
revert z.
induction x as [|x xs IHxs]; simpl; intros z;
split; intro H.
{ eexists nil; eexists z; split; [ reflexivity | ].
split; first [ assumption | constructor ]. }
{ destruct H as [x' [y' [H0 [H1 H2]]]]; subst.
inversion H1; subst; simpl.
assumption. }
{ inversion_clear H.
match goal with
| [ H : SetoidList.eqlistA _ _ _ |- _ ]
=> apply IHxs in H; clear IHxs
end.
repeat match goal with
| [ H : ex _ |- _ ] => destruct H
| [ H : and _ _ |- _ ] => destruct H
| _ => progress subst
end.
eexists (_::_)%list; simpl; eexists.
repeat split; first [ assumption | constructor; assumption ]. }
{ repeat match goal with
| [ H : ex _ |- _ ] => destruct H
| [ H : and _ _ |- _ ] => destruct H
| _ => progress subst
| [ H : SetoidList.eqlistA _ (_::_) _ |- _ ] => inversion H; clear H
| _ => progress simpl
| [ |- SetoidList.eqlistA _ (_::_) (_::_) ] => constructor
| _ => assumption
end.
apply IHxs.
repeat esplit; eassumption. }
Qed.
Lemma eqlistA_eq {A} ls ls'
: @SetoidList.eqlistA A eq ls ls' <-> ls = ls'.
Proof.
split; intro H; subst; try reflexivity.
revert ls' H.
induction ls as [|x xs IHxs]; intros []; intros;
f_equal;
inversion H; subst; trivial; eauto with nocore.
Qed.
Lemma fold_left_orb_true (ls : list bool)
: fold_left orb ls true = true.
Proof.
induction ls; simpl; trivial.
Qed.
Lemma Forall_tails_id {A P} (ls : list A)
(H : Forall_tails P ls)
: P ls.
Proof.
destruct ls; simpl in *; try assumption.
destruct H; assumption.
Defined.
Lemma Forall_tails_app {A P} (ls ls' : list A)
(H : Forall_tails P (ls ++ ls'))
: Forall_tails P ls'.
Proof.
induction ls; simpl in *; trivial.
destruct H; auto.
Defined.
Lemma first_index_default_S_cons {A f k} {x} {xs : list A}
: first_index_default f (S k) (x::xs) = if (f x) then 0 else S (first_index_default f k xs).
Proof.
simpl.
rewrite first_index_default_first_index_error.
rewrite first_index_helper_first_index_error; simpl.
destruct (first_index_error f xs) eqn:H, (f x); trivial; simpl.
apply first_index_error_Some_correct in H.
repeat (destruct_head and; destruct_head ex).
match goal with
| [ H : ?x = Some _ |- context[?x] ] => rewrite H
end.
reflexivity.
Qed.
Definition Forall_ForallT_step
(Forall_ForallT
: forall A P ls,
forall ls' ls'', ls = ls' -> ls = ls''
-> (@Forall A P ls' <-> inhabited (@ForallT A P ls'')))
A P ls
: forall ls' ls'', ls = ls' -> ls = ls'' -> (@Forall A P ls' <-> inhabited (@ForallT A P ls'')).
Proof.
intros ls' ls'' H' H''; split; [ intro H | intros [H] ];
(destruct ls as [|x xs];
[
| specialize (@Forall_ForallT A P xs (tl ls') (tl ls'') (f_equal (@tl _) H') (f_equal (@tl _) H''));
pose proof (proj1' Forall_ForallT);
pose proof (proj2' Forall_ForallT) ]);
clear Forall_ForallT;
simpl in *;
repeat match goal with
| [ H : nil = ?ls |- inhabited (ForallT _ ?ls) ] => clear -H; solve [ repeat first [ constructor | subst ] ]
end;
try solve [ repeat constructor ]; simpl in *.
{ destruct H;
try (exfalso; clear -H'; abstract congruence);
simpl in *;
specialize_by assumption;
destruct_head inhabited;
constructor.
destruct ls'';
try (exfalso; clear -H''; abstract congruence).
simpl in *.
repeat first [ assumption | constructor ].
apply (f_equal (hd x)) in H''.
apply (f_equal (hd x)) in H'.
simpl in *.
clear -H H'' H'.
pose proof (eq_trans (eq_sym H') H'') as H'''; clear H' H''.
subst; assumption. }
{ clear -H'; subst; constructor. }
{ destruct ls';
try (exfalso; clear -H'; abstract congruence);
simpl in *.
destruct ls'';
try (exfalso; clear -H''; abstract congruence);
simpl in *.
destruct_head prod.
specialize_by ltac:(repeat first [ assumption | constructor ]).
repeat first [ assumption | constructor ].
apply (f_equal (hd x)) in H''.
apply (f_equal (hd x)) in H'.
simpl in *.
clear -p H'' H'.
pose proof (eq_trans (eq_sym H') H'') as H'''; clear H' H''.
subst; assumption. }
Defined.
Global Arguments Forall_ForallT_step {_ _ _} _ _ _ _ _ : simpl never.
Fixpoint Forall_ForallT' A P ls {struct ls}
: forall ls' ls'', ls = ls' -> ls = ls'' -> (@Forall A P ls' <-> inhabited (@ForallT A P ls''))
:= @Forall_ForallT_step (@Forall_ForallT') A P ls.
Global Arguments Forall_ForallT' {_ _ _} _ _ _ _.
Definition Forall_ForallT A P ls
: @Forall A P ls <-> inhabited (@ForallT A P ls)
:= @Forall_ForallT' A P ls ls ls eq_refl eq_refl.
Global Arguments Forall_ForallT {_ _ _}.
Lemma step_Forall_ForallT' {A P ls ls' ls'' H' H''}
: @Forall_ForallT' A P ls ls' ls'' H' H'' = @Forall_ForallT_step (@Forall_ForallT') A P ls ls' ls'' H' H''.
Proof.
destruct ls; reflexivity.
Defined.
Fixpoint Forall_ForallT_Forall_eq {A P ls} (x : @Forall A P ls) {struct x}
: proj2' Forall_ForallT (proj1' Forall_ForallT x) = x.
Proof.
unfold Forall_ForallT in *.
destruct x as [|? xs p ps]; simpl in *;
[ | specialize (@Forall_ForallT_Forall_eq A P xs ps) ].
{ reflexivity. }
{ edestruct (@Forall_ForallT');
unfold eq_ind_r.
simpl in *.
match goal with
| [ |- context[match ?f ?x with _ => _ end] ]
=> destruct (f x) eqn:H'
end.
rewrite Forall_ForallT_Forall_eq; reflexivity. }
Qed.
Fixpoint ForallT_Forall_ForallT_eq {A} {P : A -> Prop} ls (x : inhabited (@ForallT A P ls)) {struct ls}
: proj1' Forall_ForallT (proj2' (@Forall_ForallT A P ls) x) = x.
Proof.
unfold Forall_ForallT in *.
destruct ls as [|v vs];
[ clear ForallT_Forall_ForallT_eq | specialize (@ForallT_Forall_ForallT_eq A P vs) ];
simpl in *;
destruct_head inhabited;
destruct_head prod;
destruct_head True.
{ reflexivity. }
{ match goal with
| [ x : _ |- _ ] => specialize (ForallT_Forall_ForallT_eq (inhabits x))
end.
unfold eq_ind_r in *; simpl in *.
edestruct (@Forall_ForallT'); simpl in *.
repeat (rewrite ForallT_Forall_ForallT_eq; simpl).
reflexivity. }
Qed.
Fixpoint ForallT_code A P ls {struct ls} : @ForallT A P ls -> @ForallT A P ls -> Prop
:= match ls return @ForallT A P ls -> @ForallT A P ls -> Prop with
| nil => fun _ _ => True
| x::xs => fun H H' => fst H = fst H' /\ @ForallT_code A P xs (snd H) (snd H')
end.
Global Arguments ForallT_code {A P ls} _ _.
Fixpoint ForallT_encode A P ls {struct ls}
: forall (x y : @ForallT A P ls), x = y -> ForallT_code x y.
Proof.
destruct ls as [|v vs]; simpl; intros x y p.
{ constructor. }
{ specialize (@ForallT_encode A P vs (snd x) (snd y) (f_equal snd p)).
apply (f_equal fst) in p.
split; assumption. }
Defined.
Global Arguments ForallT_encode {A P ls} {_ _} _.
Fixpoint ForallT_decode A P ls {struct ls}
: forall (x y : @ForallT A P ls), ForallT_code x y -> x = y.
Proof.
destruct ls as [|v vs]; simpl; intros x y p.
{ destruct x, y; reflexivity. }
{ apply injective_projections'.
{ apply p. }
{ apply ForallT_decode, p. } }
Defined.
Global Arguments ForallT_decode {A P ls} {_ _} _.
Fixpoint ForallT_endecode A P ls {struct ls}
: forall (x y : @ForallT A P ls) p, @ForallT_encode A P ls x y (ForallT_decode p) = p.
Proof.
destruct ls as [|v vs]; simpl; intros x y p.
{ destruct p; reflexivity. }
{ destruct p as [p0 p1], x, y; simpl in *.
destruct p0; simpl in *.
apply f_equal2;
[ rewrite f_equal_fst_injective_projections'
| rewrite f_equal_snd_injective_projections' ];
eauto. }
Qed.
Fixpoint ForallT_deencode A P ls {struct ls}
: forall (x y : @ForallT A P ls) p, @ForallT_decode A P ls x y (ForallT_encode p) = p.
Proof.
destruct ls as [|v vs]; simpl; intros x y p.
{ destruct p, x; reflexivity. }
{ rewrite ForallT_deencode.
destruct p, x; reflexivity. }
Qed.
Lemma Forall_proof_irrelevance {A P ls} (x y : @Forall A P ls)
(pi : forall a (x y : P a), x = y)
: x = y.
Proof.
rewrite <- (Forall_ForallT_Forall_eq x), <- (Forall_ForallT_Forall_eq y).
apply f_equal.
induction ls as [|v vs IHvs].
{ reflexivity. }
{ unfold Forall_ForallT in *.
revert IHvs.
set (ls := v::vs).
set (ls' := v::vs).
set (ls'' := v::vs).
pose (eq_refl : v::vs = ls) as H.
pose (eq_refl : ls = ls') as H'.
pose (eq_refl : ls = ls'') as H''.
change (v::vs) with ls' in x.
change (v::vs) with ls'' in y.
change
((forall (x0 : Forall P (tl ls')) (y0 : Forall P (tl ls'')),
proj1' (Forall_ForallT' (tl ls') (tl ls'') (f_equal (@tl _) H') (f_equal (@tl _) H'')) x0
= proj1' (Forall_ForallT' (tl ls'') (tl ls'') (f_equal (@tl _) H'') (f_equal (@tl _) H'')) y0)
-> proj1' (Forall_ForallT' ls' ls'' H' H'') x
= proj1' (Forall_ForallT' ls'' ls'' H'' H'') y).
clearbody H H' H'' ls ls' ls''.
intro IHvs.
rewrite !step_Forall_ForallT'.
simpl.
destruct ls, x, y; try congruence.
simpl in *.
erewrite IHvs; clear IHvs.
match goal with
| [ |- match ?e with _ => _ end = match ?e' with _ => _ end ]
=> unify e e'; destruct e
end.
unfold eq_ind_r; simpl.
repeat (f_equal; []).
repeat match goal with
| _ => intro
| _ => progress simpl in *
| _ => progress subst
| _ => solve [ eauto with nocore ]
| [ |- context[f_equal ?f ?H] ]
=> generalize (f_equal f H); clear H
end. }
Qed.
Lemma In_InT {A} (x : A) (ls : list A) (H : InT x ls)
: In x ls.
Proof.
induction ls as [|y ys IHys]; simpl in *; trivial.
destruct H; [ left | right ]; eauto with nocore.
Qed.
Lemma tl_drop {A} (ls : list A) (n : nat)
: tl (List.drop n ls) = List.drop n (tl ls).
Proof.
revert n; induction ls as [|x xs IHxs].
{ intros [|?]; reflexivity. }
{ simpl.
destruct n; simpl; trivial.
rewrite IHxs; destruct xs; trivial; simpl.
apply drop_all; simpl; omega. }
Qed.
Lemma map_ext_in {A B} (f f' : A -> B) (ls : list A)
(H : forall a, List.In a ls -> f a = f' a)
: List.map f ls = List.map f' ls.
Proof.
induction ls; simpl; trivial.
rewrite H, IHls.
{ reflexivity. }
{ intros; apply H; right; assumption. }
{ left; reflexivity. }
Qed.
Lemma list_bin_map {A B} (f : A -> B) (beq : B -> B -> bool) (ls : list A) x
: list_bin beq (f x) (map f ls) = list_bin (fun x y => beq (f x) (f y)) x ls.
Proof.
induction ls; trivial; simpl.
rewrite IHls; reflexivity.
Qed.
Lemma uniquize_map {A B} (f : A -> B) (beq : B -> B -> bool) (ls : list A)
: uniquize beq (map f ls) = map f (uniquize (fun x y => beq (f x) (f y)) ls).
Proof.
induction ls; trivial; simpl.
rewrite !IHls, list_bin_map.
edestruct @list_bin; simpl; reflexivity.
Qed.
Definition list_rect_In {A} (P : list A -> Type)
(ls : list A)
(Hnil : P nil)
(Hcons : forall x xs, In x ls -> P xs -> P (x::xs))
: P ls.
Proof.
induction ls as [|x xs IHxs]; [ assumption | ].
apply Hcons.
{ left; reflexivity. }
{ apply IHxs; intros x' xs' H'.
apply Hcons.
right; exact H'. }
Defined.
Lemma fold_right_and_True_app ls ls'
: fold_right and True (ls ++ ls') <-> (fold_right and True ls /\ fold_right and True ls').
Proof.
revert ls'; induction ls as [|?? IHls]; simpl; intros; try tauto.
rewrite IHls; clear IHls.
tauto.
Qed.
Lemma fold_right_and_True_flatten ls
: fold_right and True (flatten ls) <-> fold_right and True (map (fold_right and True) ls).
Proof.
induction ls as [|?? IHls]; try tauto; simpl.
rewrite <- IHls; clear IHls.
rewrite fold_right_and_True_app; reflexivity.
Qed.
Lemma NoDup_app {A} (ls ls' : list A)
: NoDup (ls ++ ls') -> NoDup ls /\ NoDup ls'.
Proof.
induction ls; simpl; intro H; split; trivial; try constructor;
simpl in *.
{ inversion H; subst.
eauto using in_or_app. }
{ apply IHls.
inversion H; subst; assumption. }
{ apply IHls; inversion H; subst; assumption. }
Qed.
Lemma NoDup_app_in {A} (ls ls' : list A) (x : A) (H : NoDup (ls ++ ls'))
: In x ls' -> In x ls -> False.
Proof.
intros H0 H1.
induction ls as [|?? IHls]; simpl in *; trivial.
destruct H1; inversion H; clear H; subst; eauto.
rewrite in_app_iff in *.
eauto.
Qed.
Lemma NoDup_app_in_iff {A} (ls ls' : list A)
: NoDup (ls ++ ls') <-> (NoDup ls /\ NoDup ls' /\
forall x, In x ls' -> In x ls -> False).
Proof.
induction ls as [|?? IHls]; simpl in *; trivial;
repeat (split || intro);
repeat match goal with
| _ => solve [ constructor ]
| _ => assumption
| _ => progress simpl in *
| _ => progress destruct_head and
| _ => progress destruct_head iff
| _ => progress split_and
| _ => progress subst
| _ => progress specialize_by assumption
| _ => progress specialize_by tauto
| [ H : NoDup (_::_) |- _ ] => inversion H; clear H
| [ |- NoDup (_::_) ] => constructor
| [ H : _ |- _ ] => rewrite in_app_iff in H
| _ => rewrite in_app_iff
| [ H : ~(_ \/ _) |- _ ] => apply Decidable.not_or in H
| _ => progress destruct_head or
| _ => solve [ eauto using eq_refl with nocore ]
| [ |- ~(?A \/ ?B) ] => cut (~A /\ ~B); [ tauto | ]
| [ |- _ /\ _ ] => split
| [ H : ?T, H' : ?T /\ _ -> ?B |- _ ] => specialize (fun X => H' (conj H X))
| _ => progress split_in_context_by or (fun a b : Type => a) (fun a b : Type => b) ltac:(fun H => intuition eauto)
| [ H : forall x, _ -> _ = x -> _ |- _ ] => specialize (fun k => H _ k eq_refl)
end.
Qed.
Lemma NoDup_rev {A} (ls : list A)
: NoDup (rev ls) <-> NoDup ls.
Proof.
induction ls as [|?? IHls]; simpl.
{ split; intro; constructor. }
{ split; intro H.
{ constructor.
{ rewrite in_rev.
rapply @NoDup_app_in; [ eassumption | left; reflexivity ]. }
{ apply NoDup_app in H; apply IHls, H. } }
{ rewrite NoDup_app_in_iff, IHls.
inversion H; clear H; subst.
repeat split; simpl; trivial.
{ repeat constructor; simpl; intro; trivial. }
{ intros; destruct_head or; destruct_head False; subst.
rewrite <- in_rev in *.
eauto with nocore. } } }
Qed.
Lemma uniquize_nonnil {A} beq (ls : list A)
: ls <> nil <-> Operations.List.uniquize beq ls <> nil.
Proof.
induction ls as [|a ls IHls]; simpl.
{ reflexivity. }
{ split; intros H H'.
{ destruct (list_bin beq a (Operations.List.uniquize beq ls)) eqn:Heq.
{ rewrite H' in IHls.
destruct ls; simpl in *; try congruence.
destruct IHls.
specialize_by congruence.
congruence. }
{ congruence. } }
{ congruence. } }
Qed.
Lemma rev_nonnil {A} (ls : list A)
: ls <> nil <-> rev ls <> nil.
Proof.
destruct ls; simpl.
{ reflexivity. }
{ split; intros H H';
apply (f_equal (@List.length _)) in H';
rewrite ?app_length in H';
simpl in *;
omega. }
Qed.
Lemma Forall_tl {A} P (ls : list A)
: List.Forall P ls -> List.Forall P (tl ls).
Proof.
intro H; destruct H; simpl; try constructor; assumption.
Qed.
Lemma Forall_inv_iff {A} P x (xs : list A)
: List.Forall P (x::xs) <-> (P x /\ List.Forall P xs).
Proof.
split; intro H.
{ inversion H; subst; split; assumption. }
{ constructor; apply H. }
Qed.
Lemma app_take_drop {A} (ls : list A) n
: (Operations.List.take n ls ++ Operations.List.drop n ls)%list = ls.
Proof.
revert ls; induction n as [|n IHn]; intros.
{ reflexivity. }
{ destruct ls as [|x xs]; simpl; trivial.
apply f_equal.
apply IHn. }
Qed.
Lemma map_proj1_sig_sig_In {A} (ls : list A)
: List.map (@proj1_sig _ _) (sig_In ls) = ls.
Proof.
induction ls; simpl; f_equal; rewrite map_map; simpl; assumption.
Qed.
Lemma in_sig_uip {A} {P : A -> Prop} (UIP : forall x (p q : P x), p = q)
(ls : list { x : A | P x })
x
: List.In x ls <-> List.In (proj1_sig x) (List.map (@proj1_sig _ _) ls).
Proof.
induction ls as [|y ys IHls]; simpl.
{ reflexivity. }
{ repeat match goal with
| [ |- ?x = ?x \/ _ ] => left; reflexivity
| [ H : ?A |- _ \/ ?A ] => right; assumption
| [ |- exist _ ?x _ = exist _ ?x _ \/ _ ] => left; apply f_equal
| _ => progress subst
| _ => progress simpl in *
| [ H : ?A -> ?B, H' : ?A |- _ ] => specialize (H H')
| [ H : _ <-> _ |- _ ] => destruct H
| [ |- _ <-> _ ] => split
| _ => intro
| [ H : _ \/ _ |- _ ] => destruct H
| [ H : proj1_sig ?x = _ |- _ ] => is_var x; destruct x
| [ |- context[exist _ _ _ = ?x] ] => is_var x; destruct x
| _ => solve [ eauto with nocore ]
end. }
Qed.
Lemma step_rev_up_to {n}
: List.rev (up_to n)
= match n with
| 0 => nil
| S n' => 0::map S (List.rev (up_to n'))
end.
Proof.
induction n; simpl; [ reflexivity | ].
etransitivity; [ rewrite IHn | reflexivity ].
destruct n; simpl; [ reflexivity | ].
rewrite map_app; reflexivity.
Qed.
Lemma map_nth_dep_helper {A B} (f' : nat -> nat) (f : nat -> A -> B) (l : list A) (d : A) (n : nat)
: nth n (map (fun n'a => f (fst n'a) (snd n'a))
(combine (List.map f' (List.rev (up_to (List.length l)))) l))
(f (f' n) d)
= f (f' n) (nth n l d).
Proof.
rewrite <- (map_nth (f (f' n))).
rewrite step_rev_up_to.
revert f' n; induction l as [|x xs IHxs]; intros.
{ destruct n; simpl; reflexivity. }
{ destruct n; simpl; [ reflexivity | ].
specialize (IHxs (fun x => f' (S x))).
rewrite <- IHxs; clear IHxs.
rewrite map_map.
rewrite <- step_rev_up_to.
reflexivity. }
Qed.
Lemma map_nth_dep {A B} (f : nat -> A -> B) (l : list A) (d : A) (n : nat)
: nth n (map (fun n'a => f (fst n'a) (snd n'a))
(combine (List.rev (up_to (List.length l))) l))
(f n d)
= f n (nth n l d).
Proof.
rewrite <- (map_nth_dep_helper (fun x => x)).
rewrite List.map_id; reflexivity.
Qed.
Lemma combine_map_l {A A' B} (g : A -> A') ls ls'
: List.combine (List.map g ls) ls'
= List.map (fun x : A * B => (g (fst x), snd x))
(List.combine ls ls').
Proof.
revert ls'; induction ls as [|l ls IHls];
intros [|l' ls']; simpl; f_equal.
eauto with nocore.
Qed.
Lemma combine_map_r {A B B'} (g : B -> B') ls ls'
: List.combine ls (List.map g ls')
= List.map (fun x : A * B => (fst x, g (snd x)))
(List.combine ls ls').
Proof.
revert ls'; induction ls as [|l ls IHls];
intros [|l' ls']; simpl; f_equal.
eauto with nocore.
Qed.
Section fold_right_beq.
Context {A}
{eq_A : BoolDecR A}
{Abl : BoolDec_bl (@eq A)}
{R}
(f : A -> R)
(x : A)
(base : R).
Lemma fold_right_beq_in_correct ls
: List.fold_right
(fun y else_case => If beq y x Then f y Else else_case)
base
ls
= (if list_bin beq x ls then f x else base).
Proof.
induction ls as [|y ys IHys].
{ simpl; reflexivity. }
{ simpl; rewrite IHys; clear IHys.
destruct (beq y x) eqn:Heq; simpl.
{ apply bl in Heq; subst.
rewrite Bool.orb_true_r; reflexivity. }
{ rewrite Bool.orb_false_r; reflexivity. } }
Qed.
End fold_right_beq.
Section fold_right_beq'.
Context {A}
{eq_A : BoolDecR A}
{Abl : BoolDec_bl (@eq A)}
{Alb : BoolDec_lb (@eq A)}
{R}
(f : A -> R)
(x : A)
(base : R).
Lemma fold_right_beq_in_correct' ls
: List.fold_right
(fun y else_case => If beq x y Then f y Else else_case)
base
ls
= (if list_bin beq x ls then f x else base).
Proof.
induction ls as [|y ys IHys].
{ simpl; reflexivity. }
{ simpl; rewrite IHys; clear IHys.
destruct (beq y x) eqn:Heq; simpl.
{ apply bl in Heq; subst.
rewrite lb by reflexivity.
rewrite Bool.orb_true_r; reflexivity. }
{ destruct (beq x y) eqn:Heq'; simpl.
{ apply bl in Heq'; subst.
rewrite lb in Heq by reflexivity.
congruence. }
{ rewrite Bool.orb_false_r; reflexivity. } } }
Qed.
End fold_right_beq'.
Lemma fold_right_uniquize {A B}
{eq_A : BoolDecR A}
{Abl : BoolDec_bl (@eq A)}
{Alb : BoolDec_lb (@eq A)}
(f : A -> B) ls x base
: List.fold_right
(fun y else_case => If beq x y Then f y Else else_case)
base
(uniquize beq ls)
= List.fold_right
(fun y else_case => If beq x y Then f y Else else_case)
base
ls.
Proof.
rewrite !fold_right_beq_in_correct'.
destruct (list_bin beq x ls) eqn:Heq;
destruct (list_bin beq x (uniquize beq ls)) eqn:Heq';
try reflexivity;
exfalso;
first [ apply (list_in_bl bl) in Heq
| apply (list_in_bl bl) in Heq' ];
first [ rewrite (list_in_lb lb)
in Heq
by (eapply uniquize_In; eassumption)
| rewrite (list_in_lb lb)
in Heq'
by (eapply (uniquize_In_refl _ _ _ (lb eq_refl) bl); assumption) ];
try congruence.
Qed.
Lemma uniquize_nil {A beq} (ls : list A)
: uniquize beq ls = nil <-> ls = nil.
Proof.
induction ls as [|l ls IHls]; simpl.
{ reflexivity. }
{ destruct (Equality.list_bin beq l (uniquize beq ls)) eqn:Heq.
{ apply Equality.list_inA_bl in Heq.
rewrite SetoidList.InA_altdef, Exists_exists in Heq.
destruct_head ex.
destruct_head and.
split; intro H'; try congruence.
rewrite H' in *; simpl in *.
destruct_head False. }
{ split; congruence. } }
Qed.
Lemma uniquize_singleton {A beq}
(bl : forall x y : A, beq x y = true -> x = y)
(lb : forall x y : A, x = y -> beq x y)
(ls : list A) (x : A)
: uniquize beq ls = [x] <-> (forall y, In y ls <-> x = y).
Proof.
induction ls; simpl.
{ intuition (subst; eauto; split_iff; try congruence). }
{ destruct (uniquize beq ls) eqn:Heq.
{ rewrite uniquize_nil in Heq; subst; simpl in *.
clear IHls.
setoid_rewrite or_false.
repeat first [ split
| intro
| progress split_iff
| progress subst
| congruence
| progress f_equal; []
| solve [ eauto ] ]. }
{ repeat match goal with
| [ |- context[Equality.list_bin ?beq ?x ?ls] ]
=> destruct (Equality.list_bin beq x ls) eqn:?
| [ H : Equality.list_bin _ _ _ = true |- _ ]
=> apply (Equality.list_in_bl bl) in H
| _ => progress split_iff
| _ => progress simpl in *
| [ H : orb _ _ = true |- _ ] => apply Bool.orb_true_iff in H
| [ H : orb _ _ = false |- _ ] => apply Bool.orb_false_iff in H
| _ => progress subst
| _ => progress split_and
| [ H : _::_ = _::_ |- _ ] => inversion H; clear H
| _ => progress specialize_by ltac:(exact eq_refl)
| _ => congruence
| [ H : forall y, ?a = y \/ _ -> _ = y |- _ ]
=> pose proof (H _ (or_introl eq_refl)); subst a
| [ H : forall y, ?x = y \/ @?P y -> ?x = y |- _ ]
=> assert (forall y, P y -> x = y)
by (intros; apply H; right; assumption);
clear H
| [ H : forall y, @?P y -> @?P y \/ _ |- _ ]
=> clear H
| [ H : (forall x, @?A x <-> @?B x) -> _,
H' : forall x, @?A x -> @?B x
|- _ ]
=> specialize (fun H'' => H (fun x => conj (H' x) (H'' x)))
| [ H : (forall x, ?a = x -> @?P x) -> _ |- _ ]
=> specialize (fun pf' : P a
=> H (fun x pf => match pf in (_ = y) return P y with
| eq_refl => pf'
end))
| [ H : forall y, In y ?ls -> _ = y,
H' : In ?y' ?ls |- _ ]
=> pose proof (H _ H'); subst y'
| [ |- ?x = ?x \/ _ ] => left; reflexivity
| [ |- ?x::_ = ?x::_ ] => apply f_equal
| [ H : ?x::_ = ?x::_ -> _ |- _ ] => specialize (fun H' => H (f_equal (cons x) H'))
| [ Heq : uniquize ?beq ?ls = _::_, H' : In ?x ?ls -> _ |- _ ]
=> progress specialize_by ltac:(apply (ListFacts.uniquize_In _ beq);
rewrite Heq; first [ left; reflexivity
| right; assumption ])
| _ => progress destruct_head False
| [ Heq : uniquize ?beq ?ls = ?x::_, H' : forall y, In y ?ls -> _ = y |- _ ]
=> let H := fresh in
assert (H : In x ls)
by (apply (ListFacts.uniquize_In _ beq);
rewrite Heq; left; reflexivity);
pose proof (H' _ H); subst x
| [ H : context[beq ?x ?x] |- _ ] => rewrite lb in H by reflexivity
| _ => progress destruct_head or
| _ => split
| _ => intro
end. } }
Qed.
Lemma find_first_index_error {A} {beq : A -> A -> bool} (bl : forall x y, beq x y = true -> x = y)
{B C} (f : A * B -> C) x ls default
: option_rect
(fun _ => C)
(fun idx => nth idx (map f ls) default)
default
(List.first_index_error
(beq x)
(map fst ls))
= option_rect
(fun _ => C)
f
default
(find (fun k => beq x (fst k)) ls).
Proof.
induction ls as [|l ls IHls]; simpl; [ reflexivity | ].
repeat match goal with
| _ => rewrite <- IHls; clear IHls
| _ => reflexivity
| [ |- context[if ?e then _ else _] ] => destruct e eqn:?; simpl
end; [].
rewrite first_index_helper_first_index_error; simpl.
match goal with
| [ |- _ = option_rect _ _ _ ?x ]
=> destruct x eqn:Heq'
end; simpl.
{ apply first_index_error_Some_correct in Heq'.
destruct Heq' as [[? [Heq' ?]] ?].
rewrite Heq'; simpl; reflexivity. }
{ reflexivity. }
Qed.
Lemma map_combine_id {A B} (f : A * A -> B) (ls : list A)
: List.map f (combine ls ls) = List.map (fun x => f (x, x)) ls.
Proof.
induction ls as [|l ls IHls]; simpl; [ | rewrite IHls ]; reflexivity.
Qed.
Lemma length_filter {A} f (ls : list A) : length (filter f ls) <= length ls.
Proof.
induction ls as [|l ls IHls]; simpl.
{ reflexivity. }
{ edestruct f; simpl;
try apply le_n_S;
try apply le_S;
apply IHls. }
Qed.
Lemma length_filter_eq {A f} {ls : list A} (H : length (filter f ls) = length ls)
: filter f ls = ls.
Proof.
induction ls as [|l ls IHls]; simpl in *.
{ reflexivity. }
{ edestruct f; simpl in *;
f_equal;
try apply IHls;
try omega.
{ pose proof (length_filter f ls).
omega. } }
Qed.
Lemma fold_right_andb_true_map_filter {A} (f : A -> bool) (ls : list A)
: fold_right andb true (map f (filter f ls)) = true.
Proof.
induction ls as [|l ls IHls]; simpl.
{ reflexivity. }
{ destruct (f l) eqn:H; simpl; rewrite ?H; simpl; assumption. }
Qed.
End ListFacts.
|
[STATEMENT]
lemma state_rank_range:
"state_rank q n \<in> {None} \<union> Some ` {0..<max_rank}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. state_rank q n \<in> {None} \<union> Some ` {0..<max_rank}
[PROOF STEP]
by (cases "state_rank q n") (simp add: state_rank_upper_bound[of q n])+
|
-- Definition of a graded algebra, with no other operations defined
import algebra.group.basic
import linear_algebra.tensor_product
import linear_algebra.dfinsupp
import tactic.ring
universes u
-- TODO: open_locale only under namespace, never globally
open_locale big_operators
open_locale classical
open finset
-- TODO: should this have a shorter name like graded and places it under a namespace?
class graded_module_components
-- a type for each grade.
-- TODO do we need ℤ or we can simply use ℕ
-- the inductive definition of ℤ is based on ℕ
-- and may add unwanted complexity to proof
(A : ℤ → Type u)
:=
-- (A 0) is the scalar type
-- TODO what does zc stand for?
[zc: comm_ring (A 0)]
-- all the types form commutative vector spaces
-- TODO change to meaningful names
[b: ∀ r, add_comm_monoid (A r)]
[c: ∀ r, module (A 0) (A r)]
attribute [instance] graded_module_components.zc
attribute [instance] graded_module_components.b
attribute [instance] graded_module_components.c
-- namespace graded_module_components
-- -- TODO should always open a section before using variables
-- variables {A : ℤ → Type u}
-- /-- objects are coercible only if they have the same grade-/
-- -- TODO did it work? should we remove it?
-- instance has_coe (r s : ℕ) (h: r = s) : has_coe (A r) (A s) := { coe := by {subst h, exact id}}
-- end graded_module_components
/-- Grade selection maps from objects in G to a finite set of components of substituent grades -/
-- TODO how about place it under namespace graded and name it has_select
class has_grade_select
(A : ℤ → Type u) (G: Type u)
[graded_module_components A]
[add_comm_group G]
[module (A 0) G] :=
-- TODO better find a way to avoid A 0 everywhere
(select : G →ₗ[A 0] (Π₀ r, A r))
/- TODO: check precedence -/
local notation `⟨`:0 g`⟩_`:0 r:100 := has_grade_select.select g r
-- introducing these needs types which restrict the domain of A to `{z // z : ℤ, z %2 == 0}`
-- notation `⟨`:0 g`⟩₊`:0 := has_grade_select.select_even
-- notation `⟨`:0 g`⟩₋`:0 := has_grade_select.select_odd
/-- A module divisible into disjoint graded modules, where the grade selectio
operator is a complete and independent set of projections -/
class graded_module
(A : ℤ → Type u) (G: Type u)
-- TODO: we should avoid the plague of [] parameters, by bundling them?
[graded_module_components A]
[add_comm_group G]
[module (A 0) G]
extends has_grade_select A G :=
(to_fun : ∀{r}, A r →ₗ[A 0] G)
(is_complete : ∀ g : G, ∀ f, f = select g ↔ g = f.sum (λ r, to_fun))
namespace graded_module
variables {A : ℤ → Type u} {G: Type u}
variables [graded_module_components A] [add_comm_group G] [module (A 0) G]
variables [graded_module A G]
/- locally bind the notation above to our A and G -/
-- TODO I have a feeling that this notation would not survive very long
local notation (name := grade_select) `⟨`:0 g`⟩_`:0 r:100 := @has_grade_select.select A G _ _ _ _ g r
/-- convert from r-vectors to multi-vectors -/
instance has_coe (r : ℤ) : has_coe (A r) G := { coe := to_fun }
@[simp]
lemma coe_def {r : ℤ} (v : A r) : (v : G) = to_fun v := rfl
/-- An r-vector has only a single grade
Discussed at https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Expressing.20a.20sum.20with.20finitely.20many.20nonzero.20terms/near/202657281-/
lemma select_coe_is_single {r : ℤ} (v : A r) :
has_grade_select.select (v : G) = dfinsupp.single r v := begin
symmetry,
rw is_complete (v : G) (dfinsupp.single r v),
symmetry,
apply dfinsupp.sum_single_index,
exact linear_map.map_zero _,
end
def is_r_vector (r : ℤ) (a : G) := (⟨a⟩_r : G) = a
/-- Chisholm 6a, ish.
This says A = ⟨A}_r for r-vectors.
Chisholm aditionally wants proof that A != ⟨A}_r for non-rvectors -/
lemma r_grade_of_coe {r : ℤ} (v : A r) : ⟨v⟩_r = v := begin
rw select_coe_is_single,
rw dfinsupp.single_apply,
rw [dif_pos],
refl,
end
/-- to_fun is injective -/
lemma to_fun_inj (r : ℤ) : function.injective (to_fun : A r → G) := begin
intros a b h,
rw ← r_grade_of_coe a,
rw ← r_grade_of_coe b,
simp only [coe_def],
rw h,
apply_instance,
end
/-- Chisholm 6b -/
lemma grade_of_sum (r : ℤ) (a b : G) :
⟨a + b⟩_r = ⟨a⟩_r + ⟨b⟩_r :=
by simp only [dfinsupp.add_apply, linear_map.map_add]
/-- Chisholm 6c -/
lemma grade_smul (r : ℤ) (k : A 0) (a : G) :
⟨k • a⟩_r = k • ⟨a⟩_r :=
by simp only [dfinsupp.smul_apply, linear_map.map_smul]
/-- chisholm 6d. Modifid to use `_s` instead of `_r` on the right, to keep the statement cast-free -/
lemma grade_grade (r s : ℤ) (a : G) : ⟨⟨a⟩_r⟩_s = if r = s then ⟨a⟩_s else 0
:= begin
rw select_coe_is_single,
rw dfinsupp.single_apply,
split_ifs,
{
cases h with s,
simp only [],
},
simp only [eq_self_iff_true],
end
/-- chisholm 6e. The phrasing is made a little awkward by the construction of the finite decomposition of select --/
lemma grade_sum (g : G) : g = (has_grade_select.select g).sum (λ r, (to_fun : A r → G)) := begin
apply (is_complete g (has_grade_select.select g)).1,
refl,
end
end graded_module
|
# Anomaly Detection on the MNIST Dataset
### By Shashank Swaminathan and Chris Lee
## Introduction
Our project was centered around anomaly detection, a method of detecting outliers in a given dataset. It is especially useful in situations where early detection of items differing from the norm is important. For example, in food production facilities, broken conveyor belts could lead to contamination. However, detecting problems early is difficult, as there are not many signs of issues prior to the belt completely breaks. With anomaly detection, the defects could be found earlier on, reducing the risk of contamination.
Anomaly detection can be used in a multitude of scenarios, from finding anomalies in astronomical data to recognition of oddities in medical images. We chose to focus on the image recognition aspect of anomaly detection - specifically on the MNIST dataset. This was for multiple reasons - ease of access to data, the amount of data available, and the relative uniformity of the training data (most arabic numerals look similar to each other, even with moderately bad handwriting). Our goal was to be able to identify if a provided image of a number was anomalous - far off from the standard form of a number.
We approached this problem in two ways, using PCA and Autoencoders. In fact, both methods come from the same angle, and so first we'll address how the overall anomaly detection algorithm works.
## How do we detect anomalies?
A good way to detect anomalies is to simply compare the input image against a "average image" for the given type, i.e. when checking if a given number is a "7", we compare the input image against an average image for a seven. This method is quite useful, but has a significant drawback - we need to know what the input image is trying to represent ahead of time. If the image is already misidentified, then we might improperly identify anomalies when there are none. Even worse, we might miss anomalies. Hence, we look towards the second method, the one that we adopted.
In this method, we will train a model of some kind on a given set of good training images. The model will identify major features within all the images. We'll then use this model to try and recreate a given input image, using those identified major features. The differences between the input image and the recreated image will then represent parts of the image that aren't common to the given dataset - the anomalies in the image. We'll use these anomalies (the loss between the input image and the recreated image) to determine if the image is an anomaly.
Finally, we'll use the assumption that given a set of good training data, the losses between input and recreated images will form a standard distribution. We can then put a threshold at the higher end of this distribution - if the loss between a given input and its recreation is higher than this bar, we'll consider it an anomaly.
There are some points to make about this method:
- First, the type of training data. Since we are training a model to identify key features within the training data, the classes of data we are training on should all be related, so that the key features across images are also similar. Training across a bunch of single digit numbers would satisfy this - since they are all single digits, and of the same style. However, applying this method on inconsistent datasets, like one of cars and cats would definitely not be appropriate.
- The second point is that we are making a pretty big assumption when stating that the losses we'll find will become something like a standard distribution curve. While this was not disproven by the training that we did, it is important to remember that this might not always hold, and that it is a point of caution.
## Implementation of Anomaly Detection Algorithm
Now, we move onto discussing how we implemented the algorithm. Just to reiterate, here are the steps we need to implement for our anomaly detection to succeed:
- Train a model to identify the key features in a set of training images.
- Use this model to reconstruct a set of training images, and find the losses between input images and reconstructed images.
- Find a suitable upper limit on the loss values based on the distribution of losses from training.
- For a given input image, find the loss between input and the recreation. If above the threshold, it is an anomaly.
The first few steps - training a model to identify key features and reconstruct images - fall within the category of **image compression**. In image compression, we identify key features of the input data, and then try to compress the data into a lower dimension by only using these key features. This is essentially the same process as recreating an image from a set of key features. Only here, after determining the key features and stripping it down to a construct of those key features (reducing the image's dimensionality to only these key features), we recreate the image based on the key features (transform the compressed image back to the original dimension).
There are a few methods to do image compression - two common methods are using **Principal Component Analysis (PCA)** and using **Autoencoders**. In PCA, we use the covariance matrix of the data to determine a set of "basis vectors" that represent the input data's key features. Autoencoders are completely different - to be concise, they are unsupervised neural nets that iteratively learn how to compress the given data in the best way possible (reducing the loss of information before and after compression).
PCA is a linear process - it takes the input data, finds the covariance matrix, and then finds a set of key feature vectors such that a linear combination of those vectors can approximate the input data. It does a linear mapping between the data and its key features. This is good as an approximation of the data - it is does the job to a good degree, and is quite fast. However, it is quite poor at identifying non-linear relationships. The more complex the input data, the worse it is at identifying feature relationships. In a situation such as anomaly detection, where misidentified cases can have serious consequences, this may not be useful. It's also important to note here that the PCA method is not one that involves neural networks, and is essentially a linear model.
Autoencoders are a very nonlinear process. They follow the standard mechanisms of an ANN - when used in image processing, they include convolutional layers, pooling layers, ReLU layers, the whole deal. Because they also use gradient descent to optimize its encoding process (the compression process), it can compress data quite well. However, because it is a neural net, it also falls to the trappings of neural nets. One particularly problematic point that shows up while using it in anomaly detection is overfitting. Autoencoders tend to overfit to its input data - which is understandable, given that it is incentivized to reduce losses in compression for its training data. However, overfitting means that the encoder is not only extracting key features, but also common anomalous patterns in the input data, which is troublesome.
Because both have drawbacks, we decided to use both approaches to anomaly detection. First we implemented the PCA approach, and then the Autoencoder approach. Since it is hard to get a good set of 'anomalous data', we don't have an actual accuracy score of how good the detector is. Instead, we were able to provide example cases of the detector in action, for both PCA and Autoencoding.
We didn't put docstrings in our functions since we're already documenting the work using the text option of the notebook. Also, the reason we spend some time discussing the PCA approach in detail, though it is does not involve a neural network, is to provide some basis intuition on what we are doing for anomaly detection. The process we use for PCA will be extended for the Autoencoder process.
### Using PCA
First up, we download our data. Because `sklearn` has a lot of cool PCA-related functions, we used `sklearn` for the PCA method.
```
# from sklearn.datasets import fetch_mldata
# mnist = fetch_mldata('MNIST original')
import matplotlib.pyplot as plt
import numpy as np # we always love numpy
import time
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.metrics import mean_squared_error
from sklearn.datasets import fetch_openml
# Load data from https://www.openml.org/d/554
mnist = fetch_openml('mnist_784', version=1, return_X_y=False)
from sklearn.model_selection import train_test_split
# test_size: what proportion of original data is used for test set
train_img, test_img, train_lbl, test_lbl = train_test_split(mnist.data,
mnist.target,
test_size=1/7.0,
random_state=0)
```
Next, we define the helper functions used for the PCA algorithm:
- First up is the ever-useful image display function, useful for validating if the image data we have makes sense.
- Second is the preprocessing function. Because PCA is a linearly based process, larger base values will scale the losses up, and might skew the results. Hence, we center our data around the mean of the data, and normalize all the values.
- The third function is the actual PCA function. Here, we make use of `sklearn`'s PCA function to create a PCA model for us.
- The fourth function will take a set of input training images, use the PCA model to reconstruct approximations of those images, and then find the losses between each image in the input dataset.
- This is a useful way of inspecting the losses between input images and reconstructed images. We especially use this function to check if the losses appear to fall in a standard distribution curve.
```
def disp_image_pca(image):
# need to reorder the tensor dimensions to work properly with imshow
plt.imshow(image, 'gray')
plt.axis('off')
plt.show()
def preprocess_img_pca(train_img, test_img):
scaler = StandardScaler()# Fit on training set only.
scaler.fit(train_img)# Apply transform to both the training set and the test set.
train_img = scaler.transform(train_img)
test_img = scaler.transform(test_img)
return train_img, test_img
def my_pca(train_img, amt):
mpca = PCA(amt)
mpca.fit(train_img)
return mpca
def get_losses_pca(imgs, pca):
post_encoding = mpca.inverse_transform(mpca.transform(imgs))
losses = []
for i in np.arange(imgs.shape[0]):
losses.append(mean_squared_error(imgs[i,:], post_encoding[i,:]))
return losses
def plot_losses_pca(losses, set_name):
sns.distplot(losses, kde=False)
plt.title("Loss Distribution: " + set_name)
plt.xlabel("Loss Value")
plt.ylabel("Quanitity")
plt.show()
```
Just to inspect the loaded data, we'll use the display image function to see what we're looking at.
```
disp_image_pca(train_img[2,:].reshape(28,28))
```
Now we begin actually training our PCA model. We preprocess our data, creating mean-centered and normalized versions of the training and test datasets. We then train a PCA model on the training images. The way the PCA model works is that it preserves a certain percent of variation within the dataset - here, we've selected for 90% of variance within the dataset. The resultant number of dimensions that it retains after compressions is shown as the output of `mpca.n_components`.
```
n_train_img, n_test_img = preprocess_img_pca(train_img, test_img)
mpca = my_pca(n_train_img, 0.90)
mpca.n_components_
```
With the PCA model trained, it's time to evaluate the losses across the data! We evaluate the losses across both the training and test datasets. This way, we can do three things at once:
- We can see the losses across the training and test sets, between the input and reconstructed images.
- We can see if the losses across the datasets fall into a standard distribution curve (thereby validating our initial assumption).
- We can finally see if the curves for the training and test set are similar - if they are, that means that the PCA model is not overfit for the training set, as compared to the test set.
It is worth pointing out that of the losses graphed, there is a certain amount cut from the graph - losses that were greater than 0.5. This was because there were a small amount of loss values that were significant outliers, enough to warp the graph display. In order to preserve the view of the graph, we select only for the losses within a reasonable range (and ignore the outliers). This is a reasonable choice, since there weren't many outliers to begin with - for example, in the training dataset, there were only around 2000 outliers, as compared to 60000 images.
```
# Training set
all_losses_train = np.array(get_losses_pca(n_train_img, mpca))
plot_losses_pca(all_losses_train[np.where(all_losses_train < 0.5)], "Training Set")
# Testing set
all_losses_test = np.array(get_losses_pca(n_test_img, mpca))
plot_losses_pca(all_losses_test[np.where(all_losses_test < 0.5)], "Test Set")
```
From the above, we can see that all three of the points we were looking for have been found. The losses have been evaluated; the curves do appear to be like standard distribution curves; and the curves between the training and test sets appear to be the same. This means the model has performed as we expected.
From the plot of losses, we can infer a reasonable threshold to consider an input an anomaly. We based our threshold off of z-score analysis, and placed a cutoff at 0.15. With that defined, we can create an 'anomaly identifier' function, that would guess if the image is an anomaly.
```
def is_anomaly_pca(img, pca = mpca, threshold = 0.15):
loss = get_losses_pca(img, mpca)
if (loss[0] > threshold):
print("This is an anomaly with loss: %s" % loss[0])
return loss[0]
```
Though the function is done, we still lack true anomalous data. To help create some, we defined a couple of helper functions that would essentially mash images together and force create an anomalous image. In addition to that, we added a helper function that would plot both the image and the reconstruction, to show the effects of the PCA based analysis.
```
# Combines images from dataset to create anomalies.
# Assumes input images of shape (1, 784)
def make_anomaly_pca(img1, img2):
return np.max((img1, img2), axis=0)
#Plots an input and output of the model
def show_in_out(img, pca_model):
# Plots anomaly
plt.title("Input")
disp_image_pca(img.reshape(28,28))
# Passes image into Model
img = img.reshape(1,img.shape[0])
encoded = pca_model.inverse_transform(pca_model.transform(img))
# Plots output
plt.title("Output")
disp_image_pca(encoded.reshape(28,28))
loss = is_anomaly_pca(img)
if loss < 0.15:
print("Anomaly not detected.")
print(F"LOSS: {loss}")
```
With those defined, we'll now present two examples of anomaly detection using PCA - one where an anomaly was not detected, and one where an anomaly was detected.
#### No Anomaly Detected
Here, the image is clearly very poor - it would almost certainly be considered an actual anomaly. However, the detector did not register this as an anomaly. This could be attributed to multiple things, but we think the most likely explanation is because PCA cannot handle non-linear relationships well, and so was unable to deal with such a messy image well.
```
anomaly_img = make_anomaly_pca(n_test_img[1,:], n_test_img[0,:])
show_in_out(anomaly_img, mpca)
```
#### Anomaly Detected
Here, an anomaly is detected. However, in order to do so, we had to mash multiple images together, and thereby accumulate a bunch of error before getting the final 'anomalous' image. This clearly shows the limitation of PCA - while it can definitely do reconstruction to a certain degree, it fails at identifying anything than the most anomalous images.
```
anomaly_img_1 = make_anomaly_pca(n_test_img[1,:], n_test_img[0,:])
anomaly_img_2 = make_anomaly_pca(n_test_img[2,:], anomaly_img_1)
anomaly_img_3 = make_anomaly_pca(n_test_img[3,:], anomaly_img_2)
anomaly_img_4 = make_anomaly_pca(n_test_img[4,:], anomaly_img_3)
anomaly_img_5 = make_anomaly_pca(n_test_img[5,:], anomaly_img_4)
show_in_out(anomaly_img_5, mpca)
```
With that, we have covered the PCA approach to anomaly detection. Note that this did not involve any neural networks! Instead, we focused on using a linear relationship between image data and variance. However, we also realized that there were quite a few limitations with this method. This in turn motivates the next section - using an Autoencoder.
### Using an Autoencoder
To reiterate what an Autoencoder based approach is, it is a nonlinear process involving reinforcement learning that trains an unsupervised neural network model to encode and decode data to lower dimensions while minizing information loss. We will use this encoding process the same way we did with PCA - to isolate key features of the dataset, and then use the difference between the input and reconstructed image to determine the presence of an anomaly.
In this approach, we will be using PyTorch to do our neural network implementation. Because the model is quite massive, we mount a Google Drive account to the system, in order to save the model parameters for future sessions.
The first step, as always, is to import the necessary libraries and the actual data we will be using.
```
# imports all necessary libraries
!pip install torchviz
import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchviz import make_dot
from torchvision import transforms
from torchvision.utils import save_image
from torchvision.datasets import MNIST
import time
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from google.colab import drive
drive.mount('/content/gdrive')
```
Requirement already satisfied: torchviz in /usr/local/lib/python3.6/dist-packages (0.0.1)
Requirement already satisfied: graphviz in /usr/local/lib/python3.6/dist-packages (from torchviz) (0.10.1)
Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from torchviz) (1.2.0)
Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch->torchviz) (1.16.5)
Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount("/content/gdrive", force_remount=True).
### Helper Functions
The functions below help to visualize different parts of the model. 'to_image' converts an output of the model into an image easily shown using 'disp_model', which uses matplotlib to plot and show an image. 'visualize_network' is a function that shows the structure of the model used.
```
def to_img(x):
"""Converts x into an image compatible with matplotlib"""
x = 0.5 * (x + 1)
x = x.clamp(0, 1)
x = x.view(x.size(0), 1, 28, 28)
return x
def disp_image(image, predicted=None):
plt.imshow(image, 'gray')
plt.axis('off')
plt.show()
def visualize_network(net, device='cuda', image_dims=(1,28,28)):
# Visualize the architecture of the model
# We need to give the net a fake input for this library to visualize the architecture
fake_input = Variable(torch.zeros((1,image_dims[0], image_dims[1], image_dims[2]))).to(device)
outputs = net(fake_input)
# Plot the DAG (Directed Acyclic Graph) of the model
return make_dot(outputs, dict(net.named_parameters()))
```
### Hyperparameters
After some testing, we found that 20 epochs with a batch size of 128 and a learning rate of 0.001, our model became reasonably accurate.
```
epochs = 20
batch_size = 128
learning_rate = 1e-3
```
### Loading the Data
```
img_transform = transforms.Compose([
transforms.ToTensor(), # Transforms data to tensor
transforms.Normalize((.5,), (.5,)) # Normalizes data
])
# Loads data and formats based on transform above
dataset = MNIST('./data', download=True, transform=img_transform)
# Creates a dataloader for pulling random sets of data for training
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
```
### The Model
The model below is an autoencoder, a type of unsupervised learning model. It has two primary parts: the encoder and decoder. The encoder learns non-linear patterns for reducing the dimensionality of the image, and the decoder learns how to convert an encoded image back to a similar image to the original input. The layer structure of the model was based off the code seen here: https://github.com/L1aoXingyu/pytorch-beginner/blob/master/08-AutoEncoder/conv_autoencoder.py.
```
class Autoencoder(nn.Module):
def __init__(self):
super(Autoencoder, self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(1, 16, 3, stride=3, padding=1), # Convolution 1 input, 16 outputs, 3x3 kernel
nn.ReLU(True),
nn.MaxPool2d(2, stride=2), # Maxpooling 2x2 kernel
nn.Conv2d(16, 8, 3, stride=2, padding=1), # Convolution 16 inputs, 8 outputs, 3x3 kernel
nn.ReLU(True),
nn.MaxPool2d(2, stride=1) # Maxpooling 2x2 kernel
)
# The decoder reverses the steps accomplished in the encoder.
self.decoder = nn.Sequential(
nn.ConvTranspose2d(8, 16, 3, stride=2),
nn.ReLU(True),
nn.ConvTranspose2d(16, 8, 5, stride=3, padding=1),
nn.ReLU(True),
nn.ConvTranspose2d(8, 1, 2, stride=2, padding=1),
nn.Tanh()
)
def forward(self, x):
x = self.encoder(x)
x = self.decoder(x)
return x
```
### Training the Model
The model was trained over 20 epochs using a batch size of 128 and learning rate of 0.001. Any more epochs only seemed to overfit the data and only minimally decrease the loss. Because we have no labels, our loss was calculated as the mean squared error between the input and output image of the model. By optimizing this value, the autoencoder could learn to encode and decode the data.
```
def train_model(model, num_epochs, find_loss, model_save='autoencoder.pt'):
batch_loss = []
batch_num = []
curr_batch = 0
print_every = 16
# Attempts to load model from google drive
try:
path = F"/content/gdrive/My Drive/{model_save}"
model.load_state_dict(torch.load(path))
print("Model Loaded")
# If model is not found in drive, model is trained
except:
print("Model Training")
# Iterates through num_epochs epochs
for epoch in range(num_epochs):
# Total loss of a particular batch
running_loss = 0.0
# The start time of an epoch
start_time = time.time()
# Iterates through a batch
for i, data in enumerate(dataloader, 0):
# Loads image and converts is to a variable in graphics memory
img, _ = data
img = Variable(img).cuda()
# ===================forward=====================
# Plugs input into the model and finds loss
output = model(img)
loss = find_loss(output, img)
running_loss += loss.data.item()
# ===================backward====================
# Backpropagates values to tweak weights
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Prints epoch every print_every and appends loss data to list
if (i % print_every) == print_every-1:
print("Epoch {}, Iteration {}\t train_loss: {:.2f} took: {:.2f}s".format(
epoch + 1, i+1, running_loss / print_every, time.time() - start_time))
batch_loss.append(running_loss / print_every)
batch_num.append(curr_batch)
running_loss = 0.0
curr_batch+=1
# ===================log========================
# Prints when epoch is finished
print('\nEpoch [{}/{}], loss:{:.4f}'
.format(epoch+1, num_epochs, loss.data))
# Saves model to
model_save_name = 'autoencoder.pt'
path = F"/content/gdrive/My Drive/{model_save_name}"
torch.save(model.state_dict(), path)
return batch_loss, batch_num
```
```
model = Autoencoder().cuda()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
weight_decay=1e-5)
visualize_network(model)
```
```
batch_loss, batch_num = train_model(model, epochs, criterion)
```
Model Training
Epoch 1, Iteration 16 train_loss: 0.75 took: 0.51s
Epoch 1, Iteration 32 train_loss: 0.67 took: 1.01s
Epoch 1, Iteration 48 train_loss: 0.52 took: 1.49s
Epoch 1, Iteration 64 train_loss: 0.43 took: 1.94s
Epoch 1, Iteration 80 train_loss: 0.40 took: 2.41s
Epoch 1, Iteration 96 train_loss: 0.38 took: 2.89s
Epoch 1, Iteration 112 train_loss: 0.37 took: 3.36s
Epoch 1, Iteration 128 train_loss: 0.36 took: 3.82s
Epoch 1, Iteration 144 train_loss: 0.35 took: 4.31s
Epoch 1, Iteration 160 train_loss: 0.35 took: 4.76s
Epoch 1, Iteration 176 train_loss: 0.34 took: 5.23s
Epoch 1, Iteration 192 train_loss: 0.33 took: 5.71s
Epoch 1, Iteration 208 train_loss: 0.33 took: 6.24s
Epoch 1, Iteration 224 train_loss: 0.33 took: 6.71s
Epoch 1, Iteration 240 train_loss: 0.33 took: 7.19s
Epoch 1, Iteration 256 train_loss: 0.33 took: 7.64s
Epoch 1, Iteration 272 train_loss: 0.32 took: 8.10s
Epoch 1, Iteration 288 train_loss: 0.32 took: 8.59s
Epoch 1, Iteration 304 train_loss: 0.32 took: 9.05s
Epoch 1, Iteration 320 train_loss: 0.32 took: 9.53s
Epoch 1, Iteration 336 train_loss: 0.32 took: 10.00s
Epoch 1, Iteration 352 train_loss: 0.31 took: 10.49s
Epoch 1, Iteration 368 train_loss: 0.31 took: 10.96s
Epoch 1, Iteration 384 train_loss: 0.31 took: 11.42s
Epoch 1, Iteration 400 train_loss: 0.31 took: 11.91s
Epoch 1, Iteration 416 train_loss: 0.31 took: 12.39s
Epoch 1, Iteration 432 train_loss: 0.30 took: 12.84s
Epoch 1, Iteration 448 train_loss: 0.30 took: 13.30s
Epoch 1, Iteration 464 train_loss: 0.29 took: 13.78s
Epoch [1/20], loss:0.2851
Epoch 2, Iteration 16 train_loss: 0.28 took: 0.48s
Epoch 2, Iteration 32 train_loss: 0.26 took: 0.94s
Epoch 2, Iteration 48 train_loss: 0.25 took: 1.41s
Epoch 2, Iteration 64 train_loss: 0.24 took: 1.89s
Epoch 2, Iteration 80 train_loss: 0.23 took: 2.38s
Epoch 2, Iteration 96 train_loss: 0.22 took: 2.84s
Epoch 2, Iteration 112 train_loss: 0.22 took: 3.29s
Epoch 2, Iteration 128 train_loss: 0.22 took: 3.80s
Epoch 2, Iteration 144 train_loss: 0.21 took: 4.29s
Epoch 2, Iteration 160 train_loss: 0.21 took: 4.74s
Epoch 2, Iteration 176 train_loss: 0.20 took: 5.20s
Epoch 2, Iteration 192 train_loss: 0.20 took: 5.66s
Epoch 2, Iteration 208 train_loss: 0.20 took: 6.12s
Epoch 2, Iteration 224 train_loss: 0.20 took: 6.61s
Epoch 2, Iteration 240 train_loss: 0.19 took: 7.09s
Epoch 2, Iteration 256 train_loss: 0.19 took: 7.57s
Epoch 2, Iteration 272 train_loss: 0.19 took: 8.05s
Epoch 2, Iteration 288 train_loss: 0.19 took: 8.51s
Epoch 2, Iteration 304 train_loss: 0.19 took: 8.98s
Epoch 2, Iteration 320 train_loss: 0.19 took: 9.46s
Epoch 2, Iteration 336 train_loss: 0.18 took: 9.94s
Epoch 2, Iteration 352 train_loss: 0.18 took: 10.41s
Epoch 2, Iteration 368 train_loss: 0.18 took: 10.86s
Epoch 2, Iteration 384 train_loss: 0.18 took: 11.32s
Epoch 2, Iteration 400 train_loss: 0.18 took: 11.80s
Epoch 2, Iteration 416 train_loss: 0.18 took: 12.29s
Epoch 2, Iteration 432 train_loss: 0.18 took: 12.77s
Epoch 2, Iteration 448 train_loss: 0.18 took: 13.24s
Epoch 2, Iteration 464 train_loss: 0.18 took: 13.71s
Epoch [2/20], loss:0.1749
Epoch 3, Iteration 16 train_loss: 0.17 took: 0.48s
Epoch 3, Iteration 32 train_loss: 0.17 took: 0.97s
Epoch 3, Iteration 48 train_loss: 0.17 took: 1.44s
Epoch 3, Iteration 64 train_loss: 0.17 took: 1.89s
Epoch 3, Iteration 80 train_loss: 0.17 took: 2.37s
Epoch 3, Iteration 96 train_loss: 0.17 took: 2.82s
Epoch 3, Iteration 112 train_loss: 0.17 took: 3.30s
Epoch 3, Iteration 128 train_loss: 0.17 took: 3.74s
Epoch 3, Iteration 144 train_loss: 0.17 took: 4.21s
Epoch 3, Iteration 160 train_loss: 0.16 took: 4.66s
Epoch 3, Iteration 176 train_loss: 0.16 took: 5.12s
Epoch 3, Iteration 192 train_loss: 0.16 took: 5.56s
Epoch 3, Iteration 208 train_loss: 0.16 took: 6.02s
Epoch 3, Iteration 224 train_loss: 0.16 took: 6.50s
Epoch 3, Iteration 240 train_loss: 0.16 took: 6.96s
Epoch 3, Iteration 256 train_loss: 0.16 took: 7.45s
Epoch 3, Iteration 272 train_loss: 0.16 took: 7.92s
Epoch 3, Iteration 288 train_loss: 0.15 took: 8.41s
Epoch 3, Iteration 304 train_loss: 0.15 took: 8.91s
Epoch 3, Iteration 320 train_loss: 0.15 took: 9.38s
Epoch 3, Iteration 336 train_loss: 0.15 took: 9.85s
Epoch 3, Iteration 352 train_loss: 0.15 took: 10.35s
Epoch 3, Iteration 368 train_loss: 0.15 took: 10.81s
Epoch 3, Iteration 384 train_loss: 0.15 took: 11.29s
Epoch 3, Iteration 400 train_loss: 0.15 took: 11.74s
Epoch 3, Iteration 416 train_loss: 0.15 took: 12.21s
Epoch 3, Iteration 432 train_loss: 0.15 took: 12.68s
Epoch 3, Iteration 448 train_loss: 0.15 took: 13.16s
Epoch 3, Iteration 464 train_loss: 0.15 took: 13.64s
Epoch [3/20], loss:0.1478
Epoch 4, Iteration 16 train_loss: 0.15 took: 0.48s
Epoch 4, Iteration 32 train_loss: 0.15 took: 0.96s
Epoch 4, Iteration 48 train_loss: 0.15 took: 1.43s
Epoch 4, Iteration 64 train_loss: 0.15 took: 1.90s
Epoch 4, Iteration 80 train_loss: 0.15 took: 2.35s
Epoch 4, Iteration 96 train_loss: 0.15 took: 2.85s
Epoch 4, Iteration 112 train_loss: 0.14 took: 3.32s
Epoch 4, Iteration 128 train_loss: 0.15 took: 3.83s
Epoch 4, Iteration 144 train_loss: 0.14 took: 4.30s
Epoch 4, Iteration 160 train_loss: 0.14 took: 4.77s
Epoch 4, Iteration 176 train_loss: 0.14 took: 5.25s
Epoch 4, Iteration 192 train_loss: 0.14 took: 5.72s
Epoch 4, Iteration 208 train_loss: 0.14 took: 6.17s
Epoch 4, Iteration 224 train_loss: 0.14 took: 6.65s
Epoch 4, Iteration 240 train_loss: 0.14 took: 7.12s
Epoch 4, Iteration 256 train_loss: 0.14 took: 7.59s
Epoch 4, Iteration 272 train_loss: 0.15 took: 8.05s
Epoch 4, Iteration 288 train_loss: 0.14 took: 8.50s
Epoch 4, Iteration 304 train_loss: 0.14 took: 8.98s
Epoch 4, Iteration 320 train_loss: 0.14 took: 9.45s
Epoch 4, Iteration 336 train_loss: 0.14 took: 9.93s
Epoch 4, Iteration 352 train_loss: 0.14 took: 10.39s
Epoch 4, Iteration 368 train_loss: 0.14 took: 10.87s
Epoch 4, Iteration 384 train_loss: 0.14 took: 11.35s
Epoch 4, Iteration 400 train_loss: 0.14 took: 11.82s
Epoch 4, Iteration 416 train_loss: 0.14 took: 12.27s
Epoch 4, Iteration 432 train_loss: 0.14 took: 12.74s
Epoch 4, Iteration 448 train_loss: 0.14 took: 13.19s
Epoch 4, Iteration 464 train_loss: 0.14 took: 13.64s
Epoch [4/20], loss:0.1456
Epoch 5, Iteration 16 train_loss: 0.14 took: 0.46s
Epoch 5, Iteration 32 train_loss: 0.14 took: 0.94s
Epoch 5, Iteration 48 train_loss: 0.14 took: 1.44s
Epoch 5, Iteration 64 train_loss: 0.14 took: 1.91s
Epoch 5, Iteration 80 train_loss: 0.14 took: 2.40s
Epoch 5, Iteration 96 train_loss: 0.14 took: 2.87s
Epoch 5, Iteration 112 train_loss: 0.14 took: 3.37s
Epoch 5, Iteration 128 train_loss: 0.14 took: 3.83s
Epoch 5, Iteration 144 train_loss: 0.14 took: 4.31s
Epoch 5, Iteration 160 train_loss: 0.14 took: 4.77s
Epoch 5, Iteration 176 train_loss: 0.14 took: 5.25s
Epoch 5, Iteration 192 train_loss: 0.14 took: 5.73s
Epoch 5, Iteration 208 train_loss: 0.14 took: 6.18s
Epoch 5, Iteration 224 train_loss: 0.14 took: 6.65s
Epoch 5, Iteration 240 train_loss: 0.14 took: 7.10s
Epoch 5, Iteration 256 train_loss: 0.14 took: 7.55s
Epoch 5, Iteration 272 train_loss: 0.14 took: 8.01s
Epoch 5, Iteration 288 train_loss: 0.14 took: 8.51s
Epoch 5, Iteration 304 train_loss: 0.14 took: 8.99s
Epoch 5, Iteration 320 train_loss: 0.14 took: 9.45s
Epoch 5, Iteration 336 train_loss: 0.13 took: 9.90s
Epoch 5, Iteration 352 train_loss: 0.14 took: 10.36s
Epoch 5, Iteration 368 train_loss: 0.14 took: 10.81s
Epoch 5, Iteration 384 train_loss: 0.14 took: 11.27s
Epoch 5, Iteration 400 train_loss: 0.14 took: 11.76s
Epoch 5, Iteration 416 train_loss: 0.14 took: 12.23s
Epoch 5, Iteration 432 train_loss: 0.13 took: 12.70s
Epoch 5, Iteration 448 train_loss: 0.13 took: 13.15s
Epoch 5, Iteration 464 train_loss: 0.14 took: 13.61s
Epoch [5/20], loss:0.1359
Epoch 6, Iteration 16 train_loss: 0.14 took: 0.48s
Epoch 6, Iteration 32 train_loss: 0.14 took: 0.96s
Epoch 6, Iteration 48 train_loss: 0.13 took: 1.42s
Epoch 6, Iteration 64 train_loss: 0.13 took: 1.92s
Epoch 6, Iteration 80 train_loss: 0.14 took: 2.37s
Epoch 6, Iteration 96 train_loss: 0.14 took: 2.84s
Epoch 6, Iteration 112 train_loss: 0.13 took: 3.34s
Epoch 6, Iteration 128 train_loss: 0.13 took: 3.81s
Epoch 6, Iteration 144 train_loss: 0.14 took: 4.29s
Epoch 6, Iteration 160 train_loss: 0.13 took: 4.76s
Epoch 6, Iteration 176 train_loss: 0.13 took: 5.26s
Epoch 6, Iteration 192 train_loss: 0.13 took: 5.73s
Epoch 6, Iteration 208 train_loss: 0.14 took: 6.20s
Epoch 6, Iteration 224 train_loss: 0.13 took: 6.65s
Epoch 6, Iteration 240 train_loss: 0.13 took: 7.13s
Epoch 6, Iteration 256 train_loss: 0.14 took: 7.60s
Epoch 6, Iteration 272 train_loss: 0.13 took: 8.11s
Epoch 6, Iteration 288 train_loss: 0.13 took: 8.59s
Epoch 6, Iteration 304 train_loss: 0.13 took: 9.07s
Epoch 6, Iteration 320 train_loss: 0.13 took: 9.55s
Epoch 6, Iteration 336 train_loss: 0.13 took: 10.03s
Epoch 6, Iteration 352 train_loss: 0.13 took: 10.49s
Epoch 6, Iteration 368 train_loss: 0.13 took: 10.98s
Epoch 6, Iteration 384 train_loss: 0.13 took: 11.49s
Epoch 6, Iteration 400 train_loss: 0.13 took: 11.99s
Epoch 6, Iteration 416 train_loss: 0.13 took: 12.48s
Epoch 6, Iteration 432 train_loss: 0.13 took: 12.95s
Epoch 6, Iteration 448 train_loss: 0.13 took: 13.41s
Epoch 6, Iteration 464 train_loss: 0.13 took: 13.87s
Epoch [6/20], loss:0.1376
Epoch 7, Iteration 16 train_loss: 0.13 took: 0.47s
Epoch 7, Iteration 32 train_loss: 0.13 took: 0.97s
Epoch 7, Iteration 48 train_loss: 0.13 took: 1.42s
Epoch 7, Iteration 64 train_loss: 0.13 took: 1.87s
Epoch 7, Iteration 80 train_loss: 0.13 took: 2.36s
Epoch 7, Iteration 96 train_loss: 0.13 took: 2.84s
Epoch 7, Iteration 112 train_loss: 0.13 took: 3.30s
Epoch 7, Iteration 128 train_loss: 0.13 took: 3.75s
Epoch 7, Iteration 144 train_loss: 0.13 took: 4.28s
Epoch 7, Iteration 160 train_loss: 0.13 took: 4.75s
Epoch 7, Iteration 176 train_loss: 0.13 took: 5.23s
Epoch 7, Iteration 192 train_loss: 0.13 took: 5.70s
Epoch 7, Iteration 208 train_loss: 0.13 took: 6.19s
Epoch 7, Iteration 224 train_loss: 0.13 took: 6.65s
Epoch 7, Iteration 240 train_loss: 0.13 took: 7.13s
Epoch 7, Iteration 256 train_loss: 0.13 took: 7.62s
Epoch 7, Iteration 272 train_loss: 0.13 took: 8.10s
Epoch 7, Iteration 288 train_loss: 0.13 took: 8.56s
Epoch 7, Iteration 304 train_loss: 0.13 took: 9.02s
Epoch 7, Iteration 320 train_loss: 0.13 took: 9.49s
Epoch 7, Iteration 336 train_loss: 0.13 took: 9.97s
Epoch 7, Iteration 352 train_loss: 0.13 took: 10.44s
Epoch 7, Iteration 368 train_loss: 0.13 took: 10.92s
Epoch 7, Iteration 384 train_loss: 0.13 took: 11.40s
Epoch 7, Iteration 400 train_loss: 0.13 took: 11.87s
Epoch 7, Iteration 416 train_loss: 0.13 took: 12.35s
Epoch 7, Iteration 432 train_loss: 0.13 took: 12.84s
Epoch 7, Iteration 448 train_loss: 0.13 took: 13.33s
Epoch 7, Iteration 464 train_loss: 0.13 took: 13.81s
Epoch [7/20], loss:0.1277
Epoch 8, Iteration 16 train_loss: 0.13 took: 0.50s
Epoch 8, Iteration 32 train_loss: 0.13 took: 0.98s
Epoch 8, Iteration 48 train_loss: 0.13 took: 1.44s
Epoch 8, Iteration 64 train_loss: 0.13 took: 1.90s
Epoch 8, Iteration 80 train_loss: 0.13 took: 2.38s
Epoch 8, Iteration 96 train_loss: 0.13 took: 2.86s
Epoch 8, Iteration 112 train_loss: 0.13 took: 3.35s
Epoch 8, Iteration 128 train_loss: 0.13 took: 3.83s
Epoch 8, Iteration 144 train_loss: 0.13 took: 4.30s
Epoch 8, Iteration 160 train_loss: 0.13 took: 4.78s
Epoch 8, Iteration 176 train_loss: 0.13 took: 5.25s
Epoch 8, Iteration 192 train_loss: 0.13 took: 5.71s
Epoch 8, Iteration 208 train_loss: 0.13 took: 6.17s
Epoch 8, Iteration 224 train_loss: 0.13 took: 6.65s
Epoch 8, Iteration 240 train_loss: 0.13 took: 7.11s
Epoch 8, Iteration 256 train_loss: 0.13 took: 7.56s
Epoch 8, Iteration 272 train_loss: 0.13 took: 8.04s
Epoch 8, Iteration 288 train_loss: 0.13 took: 8.49s
Epoch 8, Iteration 304 train_loss: 0.13 took: 8.94s
Epoch 8, Iteration 320 train_loss: 0.13 took: 9.42s
Epoch 8, Iteration 336 train_loss: 0.13 took: 9.91s
Epoch 8, Iteration 352 train_loss: 0.13 took: 10.40s
Epoch 8, Iteration 368 train_loss: 0.13 took: 10.88s
Epoch 8, Iteration 384 train_loss: 0.13 took: 11.35s
Epoch 8, Iteration 400 train_loss: 0.13 took: 11.85s
Epoch 8, Iteration 416 train_loss: 0.13 took: 12.32s
Epoch 8, Iteration 432 train_loss: 0.13 took: 12.80s
Epoch 8, Iteration 448 train_loss: 0.13 took: 13.27s
Epoch 8, Iteration 464 train_loss: 0.13 took: 13.72s
Epoch [8/20], loss:0.1196
Epoch 9, Iteration 16 train_loss: 0.13 took: 0.49s
Epoch 9, Iteration 32 train_loss: 0.13 took: 0.97s
Epoch 9, Iteration 48 train_loss: 0.13 took: 1.43s
Epoch 9, Iteration 64 train_loss: 0.13 took: 1.89s
Epoch 9, Iteration 80 train_loss: 0.13 took: 2.35s
Epoch 9, Iteration 96 train_loss: 0.13 took: 2.79s
Epoch 9, Iteration 112 train_loss: 0.13 took: 3.25s
Epoch 9, Iteration 128 train_loss: 0.13 took: 3.70s
Epoch 9, Iteration 144 train_loss: 0.13 took: 4.18s
Epoch 9, Iteration 160 train_loss: 0.13 took: 4.63s
Epoch 9, Iteration 176 train_loss: 0.13 took: 5.09s
Epoch 9, Iteration 192 train_loss: 0.13 took: 5.54s
Epoch 9, Iteration 208 train_loss: 0.13 took: 6.01s
Epoch 9, Iteration 224 train_loss: 0.13 took: 6.47s
Epoch 9, Iteration 240 train_loss: 0.13 took: 6.94s
Epoch 9, Iteration 256 train_loss: 0.13 took: 7.40s
Epoch 9, Iteration 272 train_loss: 0.13 took: 7.86s
Epoch 9, Iteration 288 train_loss: 0.13 took: 8.32s
Epoch 9, Iteration 304 train_loss: 0.13 took: 8.77s
Epoch 9, Iteration 320 train_loss: 0.13 took: 9.23s
Epoch 9, Iteration 336 train_loss: 0.13 took: 9.67s
Epoch 9, Iteration 352 train_loss: 0.13 took: 10.13s
Epoch 9, Iteration 368 train_loss: 0.12 took: 10.61s
Epoch 9, Iteration 384 train_loss: 0.13 took: 11.07s
Epoch 9, Iteration 400 train_loss: 0.13 took: 11.54s
Epoch 9, Iteration 416 train_loss: 0.13 took: 11.99s
Epoch 9, Iteration 432 train_loss: 0.13 took: 12.47s
Epoch 9, Iteration 448 train_loss: 0.13 took: 12.93s
Epoch 9, Iteration 464 train_loss: 0.12 took: 13.45s
Epoch [9/20], loss:0.1304
Epoch 10, Iteration 16 train_loss: 0.13 took: 0.47s
Epoch 10, Iteration 32 train_loss: 0.13 took: 0.93s
Epoch 10, Iteration 48 train_loss: 0.13 took: 1.38s
Epoch 10, Iteration 64 train_loss: 0.12 took: 1.85s
Epoch 10, Iteration 80 train_loss: 0.12 took: 2.30s
Epoch 10, Iteration 96 train_loss: 0.12 took: 2.79s
Epoch 10, Iteration 112 train_loss: 0.12 took: 3.26s
Epoch 10, Iteration 128 train_loss: 0.13 took: 3.72s
Epoch 10, Iteration 144 train_loss: 0.13 took: 4.21s
Epoch 10, Iteration 160 train_loss: 0.13 took: 4.67s
Epoch 10, Iteration 176 train_loss: 0.13 took: 5.17s
Epoch 10, Iteration 192 train_loss: 0.13 took: 5.65s
Epoch 10, Iteration 208 train_loss: 0.12 took: 6.13s
Epoch 10, Iteration 224 train_loss: 0.13 took: 6.61s
Epoch 10, Iteration 240 train_loss: 0.13 took: 7.10s
Epoch 10, Iteration 256 train_loss: 0.12 took: 7.61s
Epoch 10, Iteration 272 train_loss: 0.12 took: 8.10s
Epoch 10, Iteration 288 train_loss: 0.13 took: 8.59s
Epoch 10, Iteration 304 train_loss: 0.12 took: 9.09s
Epoch 10, Iteration 320 train_loss: 0.13 took: 9.58s
Epoch 10, Iteration 336 train_loss: 0.12 took: 10.05s
Epoch 10, Iteration 352 train_loss: 0.13 took: 10.51s
Epoch 10, Iteration 368 train_loss: 0.13 took: 11.02s
Epoch 10, Iteration 384 train_loss: 0.13 took: 11.51s
Epoch 10, Iteration 400 train_loss: 0.12 took: 12.00s
Epoch 10, Iteration 416 train_loss: 0.12 took: 12.48s
Epoch 10, Iteration 432 train_loss: 0.13 took: 12.96s
Epoch 10, Iteration 448 train_loss: 0.13 took: 13.48s
Epoch 10, Iteration 464 train_loss: 0.12 took: 13.98s
Epoch [10/20], loss:0.1279
Epoch 11, Iteration 16 train_loss: 0.13 took: 0.49s
Epoch 11, Iteration 32 train_loss: 0.12 took: 0.98s
Epoch 11, Iteration 48 train_loss: 0.13 took: 1.46s
Epoch 11, Iteration 64 train_loss: 0.12 took: 1.91s
Epoch 11, Iteration 80 train_loss: 0.13 took: 2.38s
Epoch 11, Iteration 96 train_loss: 0.12 took: 2.87s
Epoch 11, Iteration 112 train_loss: 0.12 took: 3.35s
Epoch 11, Iteration 128 train_loss: 0.12 took: 3.83s
Epoch 11, Iteration 144 train_loss: 0.13 took: 4.31s
Epoch 11, Iteration 160 train_loss: 0.13 took: 4.78s
Epoch 11, Iteration 176 train_loss: 0.12 took: 5.26s
Epoch 11, Iteration 192 train_loss: 0.12 took: 5.76s
Epoch 11, Iteration 208 train_loss: 0.13 took: 6.24s
Epoch 11, Iteration 224 train_loss: 0.12 took: 6.70s
Epoch 11, Iteration 240 train_loss: 0.13 took: 7.18s
Epoch 11, Iteration 256 train_loss: 0.12 took: 7.66s
Epoch 11, Iteration 272 train_loss: 0.12 took: 8.14s
Epoch 11, Iteration 288 train_loss: 0.12 took: 8.62s
Epoch 11, Iteration 304 train_loss: 0.12 took: 9.09s
Epoch 11, Iteration 320 train_loss: 0.12 took: 9.59s
Epoch 11, Iteration 336 train_loss: 0.12 took: 10.04s
Epoch 11, Iteration 352 train_loss: 0.12 took: 10.52s
Epoch 11, Iteration 368 train_loss: 0.12 took: 10.99s
Epoch 11, Iteration 384 train_loss: 0.13 took: 11.48s
Epoch 11, Iteration 400 train_loss: 0.12 took: 11.92s
Epoch 11, Iteration 416 train_loss: 0.12 took: 12.39s
Epoch 11, Iteration 432 train_loss: 0.12 took: 12.86s
Epoch 11, Iteration 448 train_loss: 0.12 took: 13.35s
Epoch 11, Iteration 464 train_loss: 0.12 took: 13.83s
Epoch [11/20], loss:0.1313
Epoch 12, Iteration 16 train_loss: 0.12 took: 0.47s
Epoch 12, Iteration 32 train_loss: 0.12 took: 0.93s
Epoch 12, Iteration 48 train_loss: 0.12 took: 1.39s
Epoch 12, Iteration 64 train_loss: 0.13 took: 1.86s
Epoch 12, Iteration 80 train_loss: 0.13 took: 2.33s
Epoch 12, Iteration 96 train_loss: 0.12 took: 2.82s
Epoch 12, Iteration 112 train_loss: 0.12 took: 3.27s
Epoch 12, Iteration 128 train_loss: 0.12 took: 3.74s
Epoch 12, Iteration 144 train_loss: 0.12 took: 4.19s
Epoch 12, Iteration 160 train_loss: 0.12 took: 4.70s
Epoch 12, Iteration 176 train_loss: 0.12 took: 5.17s
Epoch 12, Iteration 192 train_loss: 0.12 took: 5.66s
Epoch 12, Iteration 208 train_loss: 0.12 took: 6.11s
Epoch 12, Iteration 224 train_loss: 0.12 took: 6.60s
Epoch 12, Iteration 240 train_loss: 0.12 took: 7.07s
Epoch 12, Iteration 256 train_loss: 0.12 took: 7.56s
Epoch 12, Iteration 272 train_loss: 0.12 took: 8.02s
Epoch 12, Iteration 288 train_loss: 0.12 took: 8.49s
Epoch 12, Iteration 304 train_loss: 0.12 took: 8.96s
Epoch 12, Iteration 320 train_loss: 0.12 took: 9.41s
Epoch 12, Iteration 336 train_loss: 0.12 took: 9.88s
Epoch 12, Iteration 352 train_loss: 0.12 took: 10.39s
Epoch 12, Iteration 368 train_loss: 0.12 took: 10.85s
Epoch 12, Iteration 384 train_loss: 0.12 took: 11.30s
Epoch 12, Iteration 400 train_loss: 0.12 took: 11.80s
Epoch 12, Iteration 416 train_loss: 0.12 took: 12.26s
Epoch 12, Iteration 432 train_loss: 0.12 took: 12.75s
Epoch 12, Iteration 448 train_loss: 0.12 took: 13.22s
Epoch 12, Iteration 464 train_loss: 0.12 took: 13.69s
Epoch [12/20], loss:0.1206
Epoch 13, Iteration 16 train_loss: 0.12 took: 0.45s
Epoch 13, Iteration 32 train_loss: 0.12 took: 0.94s
Epoch 13, Iteration 48 train_loss: 0.12 took: 1.50s
Epoch 13, Iteration 64 train_loss: 0.12 took: 2.03s
Epoch 13, Iteration 80 train_loss: 0.12 took: 2.49s
Epoch 13, Iteration 96 train_loss: 0.12 took: 2.98s
Epoch 13, Iteration 112 train_loss: 0.12 took: 3.46s
Epoch 13, Iteration 128 train_loss: 0.12 took: 3.96s
Epoch 13, Iteration 144 train_loss: 0.12 took: 4.45s
Epoch 13, Iteration 160 train_loss: 0.12 took: 4.93s
Epoch 13, Iteration 176 train_loss: 0.12 took: 5.41s
Epoch 13, Iteration 192 train_loss: 0.12 took: 5.86s
Epoch 13, Iteration 208 train_loss: 0.12 took: 6.31s
Epoch 13, Iteration 224 train_loss: 0.12 took: 6.79s
Epoch 13, Iteration 240 train_loss: 0.12 took: 7.26s
Epoch 13, Iteration 256 train_loss: 0.12 took: 7.75s
Epoch 13, Iteration 272 train_loss: 0.12 took: 8.29s
Epoch 13, Iteration 288 train_loss: 0.12 took: 8.76s
Epoch 13, Iteration 304 train_loss: 0.12 took: 9.24s
Epoch 13, Iteration 320 train_loss: 0.12 took: 9.73s
Epoch 13, Iteration 336 train_loss: 0.12 took: 10.21s
Epoch 13, Iteration 352 train_loss: 0.12 took: 10.67s
Epoch 13, Iteration 368 train_loss: 0.12 took: 11.13s
Epoch 13, Iteration 384 train_loss: 0.12 took: 11.57s
Epoch 13, Iteration 400 train_loss: 0.12 took: 12.04s
Epoch 13, Iteration 416 train_loss: 0.12 took: 12.50s
Epoch 13, Iteration 432 train_loss: 0.12 took: 12.99s
Epoch 13, Iteration 448 train_loss: 0.12 took: 13.46s
Epoch 13, Iteration 464 train_loss: 0.12 took: 13.92s
Epoch [13/20], loss:0.1162
Epoch 14, Iteration 16 train_loss: 0.12 took: 0.54s
Epoch 14, Iteration 32 train_loss: 0.12 took: 1.01s
Epoch 14, Iteration 48 train_loss: 0.12 took: 1.48s
Epoch 14, Iteration 64 train_loss: 0.12 took: 1.98s
Epoch 14, Iteration 80 train_loss: 0.12 took: 2.44s
Epoch 14, Iteration 96 train_loss: 0.12 took: 2.92s
Epoch 14, Iteration 112 train_loss: 0.12 took: 3.43s
Epoch 14, Iteration 128 train_loss: 0.12 took: 3.94s
Epoch 14, Iteration 144 train_loss: 0.12 took: 4.42s
Epoch 14, Iteration 160 train_loss: 0.12 took: 4.90s
Epoch 14, Iteration 176 train_loss: 0.12 took: 5.38s
Epoch 14, Iteration 192 train_loss: 0.12 took: 5.85s
Epoch 14, Iteration 208 train_loss: 0.12 took: 6.31s
Epoch 14, Iteration 224 train_loss: 0.12 took: 6.78s
Epoch 14, Iteration 240 train_loss: 0.12 took: 7.22s
Epoch 14, Iteration 256 train_loss: 0.12 took: 7.71s
Epoch 14, Iteration 272 train_loss: 0.12 took: 8.19s
Epoch 14, Iteration 288 train_loss: 0.12 took: 8.66s
Epoch 14, Iteration 304 train_loss: 0.12 took: 9.12s
Epoch 14, Iteration 320 train_loss: 0.12 took: 9.59s
Epoch 14, Iteration 336 train_loss: 0.12 took: 10.03s
Epoch 14, Iteration 352 train_loss: 0.12 took: 10.50s
Epoch 14, Iteration 368 train_loss: 0.12 took: 10.96s
Epoch 14, Iteration 384 train_loss: 0.12 took: 11.42s
Epoch 14, Iteration 400 train_loss: 0.12 took: 11.87s
Epoch 14, Iteration 416 train_loss: 0.12 took: 12.33s
Epoch 14, Iteration 432 train_loss: 0.12 took: 12.80s
Epoch 14, Iteration 448 train_loss: 0.12 took: 13.25s
Epoch 14, Iteration 464 train_loss: 0.12 took: 13.73s
Epoch [14/20], loss:0.1277
Epoch 15, Iteration 16 train_loss: 0.12 took: 0.48s
Epoch 15, Iteration 32 train_loss: 0.12 took: 0.95s
Epoch 15, Iteration 48 train_loss: 0.12 took: 1.39s
Epoch 15, Iteration 64 train_loss: 0.12 took: 1.88s
Epoch 15, Iteration 80 train_loss: 0.12 took: 2.34s
Epoch 15, Iteration 96 train_loss: 0.12 took: 2.82s
Epoch 15, Iteration 112 train_loss: 0.12 took: 3.27s
Epoch 15, Iteration 128 train_loss: 0.12 took: 3.73s
Epoch 15, Iteration 144 train_loss: 0.12 took: 4.18s
Epoch 15, Iteration 160 train_loss: 0.12 took: 4.67s
Epoch 15, Iteration 176 train_loss: 0.12 took: 5.16s
Epoch 15, Iteration 192 train_loss: 0.12 took: 5.63s
Epoch 15, Iteration 208 train_loss: 0.12 took: 6.11s
Epoch 15, Iteration 224 train_loss: 0.12 took: 6.59s
Epoch 15, Iteration 240 train_loss: 0.12 took: 7.10s
Epoch 15, Iteration 256 train_loss: 0.12 took: 7.58s
Epoch 15, Iteration 272 train_loss: 0.12 took: 8.08s
Epoch 15, Iteration 288 train_loss: 0.12 took: 8.56s
Epoch 15, Iteration 304 train_loss: 0.12 took: 9.04s
Epoch 15, Iteration 320 train_loss: 0.12 took: 9.51s
Epoch 15, Iteration 336 train_loss: 0.12 took: 9.99s
Epoch 15, Iteration 352 train_loss: 0.12 took: 10.45s
Epoch 15, Iteration 368 train_loss: 0.12 took: 10.94s
Epoch 15, Iteration 384 train_loss: 0.12 took: 11.41s
Epoch 15, Iteration 400 train_loss: 0.12 took: 11.88s
Epoch 15, Iteration 416 train_loss: 0.12 took: 12.35s
Epoch 15, Iteration 432 train_loss: 0.12 took: 12.83s
Epoch 15, Iteration 448 train_loss: 0.12 took: 13.33s
Epoch 15, Iteration 464 train_loss: 0.12 took: 13.80s
Epoch [15/20], loss:0.1163
Epoch 16, Iteration 16 train_loss: 0.12 took: 0.51s
Epoch 16, Iteration 32 train_loss: 0.12 took: 0.97s
Epoch 16, Iteration 48 train_loss: 0.12 took: 1.48s
Epoch 16, Iteration 64 train_loss: 0.12 took: 1.97s
Epoch 16, Iteration 80 train_loss: 0.12 took: 2.45s
Epoch 16, Iteration 96 train_loss: 0.12 took: 2.92s
Epoch 16, Iteration 112 train_loss: 0.12 took: 3.41s
Epoch 16, Iteration 128 train_loss: 0.12 took: 3.89s
Epoch 16, Iteration 144 train_loss: 0.12 took: 4.36s
Epoch 16, Iteration 160 train_loss: 0.12 took: 4.82s
Epoch 16, Iteration 176 train_loss: 0.12 took: 5.29s
Epoch 16, Iteration 192 train_loss: 0.12 took: 5.78s
Epoch 16, Iteration 208 train_loss: 0.12 took: 6.26s
Epoch 16, Iteration 224 train_loss: 0.12 took: 6.73s
Epoch 16, Iteration 240 train_loss: 0.12 took: 7.20s
Epoch 16, Iteration 256 train_loss: 0.12 took: 7.69s
Epoch 16, Iteration 272 train_loss: 0.12 took: 8.15s
Epoch 16, Iteration 288 train_loss: 0.12 took: 8.62s
Epoch 16, Iteration 304 train_loss: 0.12 took: 9.10s
Epoch 16, Iteration 320 train_loss: 0.12 took: 9.58s
Epoch 16, Iteration 336 train_loss: 0.12 took: 10.04s
Epoch 16, Iteration 352 train_loss: 0.12 took: 10.51s
Epoch 16, Iteration 368 train_loss: 0.12 took: 11.02s
Epoch 16, Iteration 384 train_loss: 0.12 took: 11.50s
Epoch 16, Iteration 400 train_loss: 0.12 took: 11.98s
Epoch 16, Iteration 416 train_loss: 0.12 took: 12.46s
Epoch 16, Iteration 432 train_loss: 0.12 took: 12.93s
Epoch 16, Iteration 448 train_loss: 0.12 took: 13.41s
Epoch 16, Iteration 464 train_loss: 0.12 took: 13.89s
Epoch [16/20], loss:0.1290
Epoch 17, Iteration 16 train_loss: 0.12 took: 0.48s
Epoch 17, Iteration 32 train_loss: 0.12 took: 0.97s
Epoch 17, Iteration 48 train_loss: 0.12 took: 1.46s
Epoch 17, Iteration 64 train_loss: 0.12 took: 1.95s
Epoch 17, Iteration 80 train_loss: 0.12 took: 2.44s
Epoch 17, Iteration 96 train_loss: 0.12 took: 2.89s
Epoch 17, Iteration 112 train_loss: 0.12 took: 3.33s
Epoch 17, Iteration 128 train_loss: 0.12 took: 3.79s
Epoch 17, Iteration 144 train_loss: 0.12 took: 4.24s
Epoch 17, Iteration 160 train_loss: 0.12 took: 4.70s
Epoch 17, Iteration 176 train_loss: 0.12 took: 5.15s
Epoch 17, Iteration 192 train_loss: 0.12 took: 5.64s
Epoch 17, Iteration 208 train_loss: 0.12 took: 6.08s
Epoch 17, Iteration 224 train_loss: 0.12 took: 6.55s
Epoch 17, Iteration 240 train_loss: 0.12 took: 7.05s
Epoch 17, Iteration 256 train_loss: 0.12 took: 7.51s
Epoch 17, Iteration 272 train_loss: 0.12 took: 7.97s
Epoch 17, Iteration 288 train_loss: 0.12 took: 8.42s
Epoch 17, Iteration 304 train_loss: 0.12 took: 8.90s
Epoch 17, Iteration 320 train_loss: 0.12 took: 9.36s
Epoch 17, Iteration 336 train_loss: 0.12 took: 9.82s
Epoch 17, Iteration 352 train_loss: 0.12 took: 10.27s
Epoch 17, Iteration 368 train_loss: 0.12 took: 10.75s
Epoch 17, Iteration 384 train_loss: 0.12 took: 11.21s
Epoch 17, Iteration 400 train_loss: 0.12 took: 11.70s
Epoch 17, Iteration 416 train_loss: 0.12 took: 12.19s
Epoch 17, Iteration 432 train_loss: 0.12 took: 12.68s
Epoch 17, Iteration 448 train_loss: 0.12 took: 13.16s
Epoch 17, Iteration 464 train_loss: 0.12 took: 13.64s
Epoch [17/20], loss:0.1098
Epoch 18, Iteration 16 train_loss: 0.12 took: 0.48s
Epoch 18, Iteration 32 train_loss: 0.12 took: 0.96s
Epoch 18, Iteration 48 train_loss: 0.12 took: 1.43s
Epoch 18, Iteration 64 train_loss: 0.12 took: 1.91s
Epoch 18, Iteration 80 train_loss: 0.12 took: 2.38s
Epoch 18, Iteration 96 train_loss: 0.12 took: 2.86s
Epoch 18, Iteration 112 train_loss: 0.12 took: 3.35s
Epoch 18, Iteration 128 train_loss: 0.12 took: 3.79s
Epoch 18, Iteration 144 train_loss: 0.12 took: 4.27s
Epoch 18, Iteration 160 train_loss: 0.12 took: 4.72s
Epoch 18, Iteration 176 train_loss: 0.12 took: 5.19s
Epoch 18, Iteration 192 train_loss: 0.12 took: 5.64s
Epoch 18, Iteration 208 train_loss: 0.12 took: 6.11s
Epoch 18, Iteration 224 train_loss: 0.12 took: 6.56s
Epoch 18, Iteration 240 train_loss: 0.12 took: 7.01s
Epoch 18, Iteration 256 train_loss: 0.12 took: 7.46s
Epoch 18, Iteration 272 train_loss: 0.12 took: 7.94s
Epoch 18, Iteration 288 train_loss: 0.12 took: 8.40s
Epoch 18, Iteration 304 train_loss: 0.11 took: 8.87s
Epoch 18, Iteration 320 train_loss: 0.12 took: 9.33s
Epoch 18, Iteration 336 train_loss: 0.12 took: 9.78s
Epoch 18, Iteration 352 train_loss: 0.12 took: 10.26s
Epoch 18, Iteration 368 train_loss: 0.11 took: 10.71s
Epoch 18, Iteration 384 train_loss: 0.12 took: 11.19s
Epoch 18, Iteration 400 train_loss: 0.12 took: 11.68s
Epoch 18, Iteration 416 train_loss: 0.12 took: 12.15s
Epoch 18, Iteration 432 train_loss: 0.12 took: 12.63s
Epoch 18, Iteration 448 train_loss: 0.12 took: 13.11s
Epoch 18, Iteration 464 train_loss: 0.12 took: 13.63s
Epoch [18/20], loss:0.1211
Epoch 19, Iteration 16 train_loss: 0.12 took: 0.47s
Epoch 19, Iteration 32 train_loss: 0.12 took: 0.93s
Epoch 19, Iteration 48 train_loss: 0.12 took: 1.39s
Epoch 19, Iteration 64 train_loss: 0.12 took: 1.85s
Epoch 19, Iteration 80 train_loss: 0.12 took: 2.30s
Epoch 19, Iteration 96 train_loss: 0.12 took: 2.76s
Epoch 19, Iteration 112 train_loss: 0.12 took: 3.23s
Epoch 19, Iteration 128 train_loss: 0.12 took: 3.72s
Epoch 19, Iteration 144 train_loss: 0.12 took: 4.20s
Epoch 19, Iteration 160 train_loss: 0.12 took: 4.66s
Epoch 19, Iteration 176 train_loss: 0.12 took: 5.11s
Epoch 19, Iteration 192 train_loss: 0.12 took: 5.57s
Epoch 19, Iteration 208 train_loss: 0.12 took: 6.05s
Epoch 19, Iteration 224 train_loss: 0.12 took: 6.51s
Epoch 19, Iteration 240 train_loss: 0.12 took: 6.97s
Epoch 19, Iteration 256 train_loss: 0.12 took: 7.45s
Epoch 19, Iteration 272 train_loss: 0.11 took: 7.93s
Epoch 19, Iteration 288 train_loss: 0.12 took: 8.40s
Epoch 19, Iteration 304 train_loss: 0.11 took: 8.87s
Epoch 19, Iteration 320 train_loss: 0.12 took: 9.33s
Epoch 19, Iteration 336 train_loss: 0.12 took: 9.81s
Epoch 19, Iteration 352 train_loss: 0.11 took: 10.29s
Epoch 19, Iteration 368 train_loss: 0.12 took: 10.74s
Epoch 19, Iteration 384 train_loss: 0.11 took: 11.22s
Epoch 19, Iteration 400 train_loss: 0.11 took: 11.71s
Epoch 19, Iteration 416 train_loss: 0.12 took: 12.21s
Epoch 19, Iteration 432 train_loss: 0.12 took: 12.67s
Epoch 19, Iteration 448 train_loss: 0.12 took: 13.15s
Epoch 19, Iteration 464 train_loss: 0.11 took: 13.63s
Epoch [19/20], loss:0.1236
Epoch 20, Iteration 16 train_loss: 0.11 took: 0.49s
Epoch 20, Iteration 32 train_loss: 0.11 took: 0.94s
Epoch 20, Iteration 48 train_loss: 0.12 took: 1.42s
Epoch 20, Iteration 64 train_loss: 0.12 took: 1.90s
Epoch 20, Iteration 80 train_loss: 0.12 took: 2.38s
Epoch 20, Iteration 96 train_loss: 0.12 took: 2.87s
Epoch 20, Iteration 112 train_loss: 0.12 took: 3.35s
Epoch 20, Iteration 128 train_loss: 0.12 took: 3.83s
Epoch 20, Iteration 144 train_loss: 0.12 took: 4.32s
Epoch 20, Iteration 160 train_loss: 0.11 took: 4.77s
Epoch 20, Iteration 176 train_loss: 0.11 took: 5.22s
Epoch 20, Iteration 192 train_loss: 0.11 took: 5.72s
Epoch 20, Iteration 208 train_loss: 0.12 took: 6.22s
Epoch 20, Iteration 224 train_loss: 0.12 took: 6.70s
Epoch 20, Iteration 240 train_loss: 0.12 took: 7.16s
Epoch 20, Iteration 256 train_loss: 0.11 took: 7.62s
Epoch 20, Iteration 272 train_loss: 0.11 took: 8.06s
Epoch 20, Iteration 288 train_loss: 0.11 took: 8.52s
Epoch 20, Iteration 304 train_loss: 0.11 took: 8.96s
Epoch 20, Iteration 320 train_loss: 0.11 took: 9.43s
Epoch 20, Iteration 336 train_loss: 0.12 took: 9.90s
Epoch 20, Iteration 352 train_loss: 0.12 took: 10.40s
Epoch 20, Iteration 368 train_loss: 0.12 took: 10.87s
Epoch 20, Iteration 384 train_loss: 0.11 took: 11.35s
Epoch 20, Iteration 400 train_loss: 0.11 took: 11.83s
Epoch 20, Iteration 416 train_loss: 0.12 took: 12.30s
Epoch 20, Iteration 432 train_loss: 0.12 took: 12.77s
Epoch 20, Iteration 448 train_loss: 0.11 took: 13.25s
Epoch 20, Iteration 464 train_loss: 0.12 took: 13.71s
Epoch [20/20], loss:0.1182
```
# Plots Loss over batches
plt.plot(batch_num,batch_loss)
plt.title('Loss of Autoencoder')
plt.legend(['train loss', 'validation loss'])
plt.xlabel('Batch number')
plt.ylabel('Loss')
plt.show()
```
### Anomaly or Not?
To determine, whether an image was an anomaly or not, it was necessary to look at the loss distribution of our non-anomalous dataset, and because it appeared like a relatively normal distribution, we decided that using a point's Z score was an anomaly. Z score can be calculated using:
\begin{align}
\ Z = \frac {x + \mu}{\sigma}
\end{align}
If a Z score of an image is found to be greater than 2.5, then the image is an outlier, which gave resonable accuracy.
```
all_losses = []
# Finds the loss for every image in the database to be plotted as a histogram
for i in range(len(dataset)):
img, _ = dataset[i]
img = Variable(img.unsqueeze(1)).cuda()
output = model(img)
all_losses.append(criterion(output, img).item())
# Plots Loss distribution
sns.distplot(all_losses, kde=False)
plt.title("Loss Distribution")
plt.xlabel("Loss Value")
plt.ylabel("Quanitity")
plt.show()
# Converts list of losses to Float Tensor type
all_losses = torch.FloatTensor(all_losses)
std = all_losses.std().item() # Finds standard deviation
mean = all_losses.mean().item() # Finds mean
# Finds if an image is an anomaly based on its z score value. 2.5 is the threshold.
def is_anomaly(value, z_thresh = 2.5):
zscore = (value-mean)/std # Calculates z score for value
if zscore > z_thresh:
return True
return False
```
### Detecting Anomalies
For detecting anomalies, anomalous images had to be created. Using the function below, images in the dataset are combined to create images which clearly deviated from the rest. The show_in_out function plots an image before and after being passed through the model. It also prints its loss and whether or not it is an anomaly.
```
# Combines images from dataset to create anomalies.
def make_anomaly(img1, img2, img_dim = (28,28)):
# Matrix to store combined image
output = np.ones((img_dim[0]*img_dim[1],1))
# Reshapes images for consistency
img1 = img1.reshape(img_dim[0]*img_dim[1], 1).numpy()
img2 = img2.reshape(img_dim[0]*img_dim[1], 1).numpy()
# Iterates through each pixel and selects largest
for i in range(len(img1)):
output[i] = max([img1[i], img2[i]])
# Converts numpy array to tensor
output = torch.from_numpy(output).type(torch.FloatTensor)
return output
#Plots an input and output of the model
def show_in_out(img, model, loss_func):
# Plots anomaly
plt.title("Input")
disp_image(img.reshape(28,28))
# Passes image into Model
img = img.reshape((1,1,28,28))
img = img.to("cuda")
output = model(Variable(img).cuda())
loss = loss_func(output, img).item()
encoded = to_img(output.cpu().data)
# Plots output
plt.title("Output")
disp_image(encoded.reshape(28,28))
print(F"LOSS: {loss}")
print(F"Outlier: {is_anomaly(loss)}")
```
#### Non Anomalous Image
Below is an image from the dataset, non-anomalous, being passed through the model. The input and output are relatively similar, and the image is not classified as an anomaly.
```
# Pulls image from MNist dataset and displays it
img, label = dataset[1]
show_in_out(img, model, criterion)
```
#### Anomalous Image
Below is an anomalous image created by combining different non-anomalous images. After the image was passed through the model, differences were accentuated leading to a greater loss. As a result, the model was able to predict that the image was an anomaly.
```
img1, label = dataset[1]
img2, label = dataset[2]
img3, label = dataset[10]
# Combines images at index 1, 2 and 10 in the dataset
img = make_anomaly(make_anomaly(img1,img2), img3)
show_in_out(img, model, criterion)
```
#### Anomalous Image Inappropriately Classified.
Below is an image created by combining different non-anomalous images. Though the image is considered an anomaly, the model did not classify the image as an anomaly. This is likely because the image is close enough to a badly drawn zero.
```
img1, label = dataset[1]
img2, label = dataset[10]
# Combines images at index 1 and 10 in the dataset
img = make_anomaly(img1,img2)
show_in_out(img, model, criterion)
```
#### Large Anomaly Appropriately Classified.
Below is generated noise passed, which was passed through the model and classified. The input and output are very different, leading to a large loss and ultimately, a classification as an anomaly.
```
# Generates random noisy image
noisy = np.random.random((1,1,28,28))
# Converts noisy image to tensor
noisy = torch.from_numpy(noisy).type(torch.FloatTensor)
show_in_out(noisy, model, criterion)
```
|
#' Process on multiple cores on one machine
#'
#' Derives from QSys to provide multicore-specific functions
#'
#' @keywords internal
MULTICORE = R6::R6Class("MULTICORE",
inherit = QSys,
public = list(
initialize = function(addr=host("127.0.0.1"), ...) {
super$initialize(addr=addr, ...)
},
submit_jobs = function(n_jobs, ..., log_worker=FALSE, log_file=NULL, verbose=TRUE) {
if (verbose)
message("Starting ", n_jobs, " cores ...")
if (log_worker && is.null(log_file))
log_file = "cmq-%i.log"
for (i in seq_len(n_jobs)) {
if (is.character(log_file))
log_i = sprintf(log_file, i)
else
log_i = NULL
wrapper = function(m, logfile) {
if (is.null(logfile))
logfile = "/dev/null"
fout = file(logfile, open="wt")
sink(file=fout, type="output")
sink(file=fout, type="message")
on.exit({ sink(type="message"); sink(type="output"); close(fout) })
clustermq:::worker(m)
}
p = parallel::mcparallel(quote(wrapper(private$master, log_i)))
private$children[[as.character(p$pid)]] = p
}
private$workers_total = n_jobs
},
cleanup = function(quiet=FALSE, timeout=3) {
success = super$cleanup(quiet=quiet, timeout=timeout)
private$collect_children(wait=success, timeout=timeout)
invisible(success && length(private$children) == 0)
},
finalize = function(quiet=FALSE) {
if (!private$is_cleaned_up) {
private$collect_children(wait=FALSE, timeout=0)
running = names(private$children)
if (length(running) > 0) {
if (!quiet)
warning("Unclean shutdown for PIDs: ",
paste(running, collapse=", "),
immediate.=TRUE)
tools::pskill(running, tools::SIGKILL)
}
private$is_cleaned_up = TRUE
}
}
),
private = list(
collect_children = function(...) {
pids = as.integer(names(private$children))
res = suppressWarnings(parallel::mccollect(pids, ...))
finished = intersect(names(private$children), names(res))
private$children[finished] = NULL
},
children = list()
)
)
|
#include "pch.h"
#include <cassert>
#include <iostream>
#include <unordered_map>
#include <boost/optional.hpp>
#include <boost/signal.hpp>
#include <boost/bind.hpp>
#include <boost/variant.hpp>
namespace tree
{
template<typename Value>
struct Node
{
Value value;
std::list<Node> children;
};
template<typename Value>
struct Root
{
std::list<Node<Value>> children;
};
}
class RadixTree
{
tree::Root<std::string> _root;
public:
void add(std::string add_me)
{
_add_to_children(std::move(add_me), _root.children);
}
private:
void _add_to_children(std::string add_me, std::list<tree::Node<std::string>> &node_children)
{
auto const children_end = node_children.end();
auto child_iter = std::find_if(
node_children.begin(), children_end,
[&add_me](decltype(*node_children.begin()) child)
{
return !child.value.empty() && add_me[0] == child.value[0];
}
);
if (child_iter != children_end)
{
auto &child = *child_iter;
_add(std::move(add_me)/*.substr(1)*/, child);
}
else
node_children.emplace_back(tree::Node<std::string>{std::move(add_me)});
};
void _add(std::string add_me, tree::Node<std::string> &node)
{
auto result = node.value.compare(add_me);
switch (result)
{
case 0:
// todo terminate simbool
// этот узел содержит в себе это значение
break;
case -1://(node.value.size > add_me.size) значит детей нет
{
auto value = node.value;
if (node.value.size() > 1)
{
node.value = value[0];
node.children.emplace_back(tree::Node<std::string>{value.substr(1)});
_add(add_me.substr(1), node.children.back());
}
else
_add_to_children(add_me.substr(1), node.children);
} break;
default:
assert(false);
}
}
};
int main()
{
RadixTree tree;
tree.add("abs");
tree.add("absq");
tree.add("absqs");
tree.add("assqs");
}
|
\appendix
\renewcommand{\thesection}{APPENDIX \Alph{section}}
\section{ - Figures} \label{appendix:A}
\topskip0pt
\vspace*{\fill}
\begin{center}
\includegraphics[width=0.67\textwidth]{{img_src/trajectories_scatter_2000}.png}
\captionof{figure}{The trajectories of 64 particles for 2000 steps of the simulation with dt$= 0.01$ step size.} \label{fig:traj_2000}
\end{center}
\begin{center}
\includegraphics[width=0.67\textwidth]{{img_src/trajectories_scatter_20000}.png}
\captionof{figure}{The trajectories of 64 particles for 20000 steps of the simulation with dt$= 0.01$ step size.} \label{fig:traj_20000}
\end{center}
\vspace*{\fill}
|
open import Nat
open import Prelude
open import core
open import disjointness
module elaboration-generality where
mutual
elaboration-generality-synth : {Γ : tctx} {e : hexp} {τ : htyp} {d : ihexp} {Δ : hctx} →
Γ ⊢ e ⇒ τ ~> d ⊣ Δ →
Γ ⊢ e => τ
elaboration-generality-synth ESConst = SConst
elaboration-generality-synth (ESVar x₁) = SVar x₁
elaboration-generality-synth (ESLam apt ex) with elaboration-generality-synth ex
... | ih = SLam apt ih
elaboration-generality-synth (ESAp dis _ a x₁ x₂ x₃) = SAp dis a x₁ (elaboration-generality-ana x₃)
elaboration-generality-synth ESEHole = SEHole
elaboration-generality-synth (ESNEHole dis ex) = SNEHole (elab-disjoint-new-synth ex dis) (elaboration-generality-synth ex)
elaboration-generality-synth (ESAsc x) = SAsc (elaboration-generality-ana x)
elaboration-generality-ana : {Γ : tctx} {e : hexp} {τ τ' : htyp} {d : ihexp} {Δ : hctx} →
Γ ⊢ e ⇐ τ ~> d :: τ' ⊣ Δ →
Γ ⊢ e <= τ
elaboration-generality-ana (EALam apt m ex) = ALam apt m (elaboration-generality-ana ex)
elaboration-generality-ana (EASubsume x x₁ x₂ x₃) = ASubsume (elaboration-generality-synth x₂) x₃
elaboration-generality-ana EAEHole = ASubsume SEHole TCHole1
elaboration-generality-ana (EANEHole dis x) = ASubsume (SNEHole (elab-disjoint-new-synth x dis) (elaboration-generality-synth x)) TCHole1
|
% !TEX root=../main.tex
\chapter{Methodology}
\renewcommand{\baselinestretch}{\mystretch}
\label{chap:method}
% \setlength{\parindent}{0pt}
\PARstart{T}{his} chapter will introduce the methodology of this project into two main aspects. One is to present pre-processing methods of audio data, including mel-spectrogram feature extraction, denoising method and data augmentation. The second aspect will introduce the architecture of CNN about activation function and different CNN layers. As to training CNN, the loss function and optimizer will be explained in the last section.
\section{Mel-spectrogram Feature}
Spectrograms provide visual representations for people that can analyse the properties of audio data. As presented in Section 2.2, mel-spectrogram is an effective alternative for CNN as the input feature. However, the mel-spectrogram is based on the STFT which processed on discrete Fourier transform (DFT). It is expressed as $X_k=\sum ^{N-1}_{n=0}x_ne^{i2\pi \frac{kn}{N}}$, where $N$ coefficients are considered to represent the frequency value $X_k$. However, only several parts of audio we are interested since calls present a few seconds in most case. Therefore, separating the whole signal into shorter sections allows us to analyse the properties of particular points in time. By applying the window function to each segment, the STFT of signal can be obtained, which is expressed as
\begin{equation}
STFT\{ x_n\}(h,k)=X(h,k)=\sum_{n=0}^{N-1}x_{n+h}w_ne^{i2\pi \frac{kn}{N}}
\end{equation}
where the length of window $h$ should be smaller than $N$. However, the represents of power spectrogram are non-uniform. Therefore, it is tough to extract informative features. By applying logarithm to power spectrogram can make representations more visual which is beneficial to analysis. Fig \ref{fig:powerlog} shows the difference of power spectrogram and spectrogram in the logarithm of example file '5AEF815A.wav'. Features are enhanced by taking the logarithm of the power spectrogram.\par
\begin{figure}[htp]
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.5]{Figs/chap3/power.pdf}
\caption{Power spectrogram}
\end{subfigure}
~
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.5]{Figs/chap3/logpower.pdf}
\caption{Log-scale spectrogram}
\end{subfigure}
\caption{Compare of power spectrogram and log-magnitude spectrogram (example file: 5AEF815A.wav)}
\label{fig:powerlog}
\end{figure}
However, the STFT spectrogram is not the optimal extraction with the characteristic of linearity. By the inspiration of cochlea which can be considered as non-linear filters for the human sounds processing, the perceptual information can be introduced to the model. Specifically, emphasize the part of information which human listeners are sensitive and discriminative. After obtaining the short-time Fourier transform, the logarithm was applied to the magnitude to improve informative details. This process enhances the perceptual sensitive based on logarithmic-axis. Moreover, the frequency domain should be considered as well.
The mel-scale is one way to transform the original linear frequency into mel frequency. The mathematical approximation is
\begin{align}
m&=2595\log_{10}(1+\frac {f}{700})\\
inverse: f&=700(10^{\frac{m}{2595}-1})
\end{align}
Therefore, the corresponding linear frequencies $f_i$ have equal perceptual distance by taking equally spaced mel-frequencies $m_i$. Fig~\ref{fig:melscale} (a) depicts the relationship between linear frequency in horizontal axis and the mel-frequency in vertical. However, other information will be degraded when using specific frequency $f_k$ during sampling the log-spectrogram. In other word, the transformation of mel-scale can be realized by applying filter bank to integrate the energy closed to the sample frequency $f_k$.
\begin{equation}
u_k = \sum_{h=f_{k-1}+1}^{f_{k+1}-1} w_{k,h} |x_h|^2
\end{equation}
where $u_k$ is integrated energy in mel-spectrogram, $w_{k,h}$ is the weighted scalars and $x_h$ is the parts which close to sample frequency $f_k$. For the mel-scale, the weighted scalars are generally triangular function as shown in Fig~\ref{fig:melscale} (b). By combining weighted functions in non-linear spacing with 50\% overlapping, the log-spectrogram can be integrated and weighted.\par
\begin{figure}[htp]
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.35]{Figs/chap3/mel_scale.pdf}
\caption{Mel scale function}
\end{subfigure}
~
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.35]{Figs/chap3/mel_bank.pdf}
\caption{Mel filter bank with 10 mels}
\end{subfigure}
\caption{Transformation of frequency-to-mel and mel filter banks}
\label{fig:melscale}
\end{figure}
By using triangular window above, the mel-spectrogram is obtained as show below. The mel-spectrogram contains more perceptual information which makes the presence of call more obvious. Therefore, using the mel-spectrogram as CNN model input can significant simulate how human make decisions. In addition, the MFCC can be calculated by taking discrete cosine transform (DCT) on log-scale mel-spectrogram. Due to MFCCs are not robust to additive noise, we chose mel-spectrogram as input feature.
\begin{figure}[htp]
\centering
\includegraphics[scale=0.7]{Figs/chap3/mel_spec.pdf}
\caption{Mel spectrogram}
\label{fig:mel_spec}
\end{figure}
\section{Denoising Method}
The acoustic data of this project were recorded in the rainforest which caused complex and capricious environment. Thus, the signals of call presence were covered by large additive noise, resulting in inferior quality of audio. It is essential to apply denoising method to improve the signal noise ratio (SNR). We compared two performance of common denoising method, namely spectral subtraction~\cite{boll1979suppression} and MMSE-LSA estimator~\cite{ephraim1985speech}. First of all, as stated in their study, assume of the received noisy signal is
\begin{equation}
y(t)=x(t)+n(t)
\end{equation}
where $x(t)$ is the desired signal and $n(t)$ is the noise. Thus, the equation above in frequency domain represents as
\begin{align}
Y(\omega)&=X(\omega))+N(\omega)\label{eq:spectrum}
\\
\notag
\end{align}
Only $y(t)$ and $Y(\omega)$ are known values. The objective of the denoising method is to reduce the noise interference without influencing the quality of the informative signal.
\subsection{Spectral Subtraction}
The aim of spectral subtraction is to estimate the power of noise based on the frequency domain $\hat N(\omega)$. Afterwards, the estimated spectrum of desired signal $\hat X(\omega)$ is obtained by
\begin{equation}
\hat X(\omega)=Y(\omega))- \hat N(\omega)
\label{sub-spec}
\end{equation}
Since the additive noise has the flat power along with the whole frequency band, the noise spectrum $\hat N(\omega)$ can be estimated as the expectation of noise spectrum $E\{|N(\omega)| \}$. This can be calculated by averaging parts where only noise recording presents at that time. The estimated noise spectrum can be denoted as
\begin{equation}
\hat N(\omega)=E\{|N(\omega)| \}\cong |\bar N(\omega)|= \frac{1}{K}\sum_{i=0}^{K-1} |\bar N_i(\omega)|
\end{equation}
where $|\bar N_i(\omega)|$ is the i-th amplitude of K frames of noise. Therefore, the desired signal in frequency domain is calculated by the equation~\ref{sub-spec}. Hence, the time-series signal $x(t)$ is the inverse-Fourier transform of $\hat X(\omega)$.\par
The spectral subtraction estimator is a primary and effective method of noise reduction. The algorithm for estimating the noise spectrum is simple, resulting in less computing complexity. However, this approach assumes that the additive noise is wide-band and stationary, which does not always correspond to reality. Therefore, the reconstructed signal has a deviation to the theoretical desired signal in most cases. A large disturbance will be introduced due to the significant variations between estimated noise and actual noise As a consequence, the contributive information is distorted by the disturbance.
\par
Observing the original noisy mel-spectrogram in Fig~\ref{fig:mel_spec}, the presence of call is concentrated on the area of 512$\sim$3000 Hz frequency bands. It is notable that the uniform noise appears at 4096 Hz all the time. Fig~\ref{fig:spec_sub} demonstrates the mel-spectrogram of reconstructed signal after using spectral subtraction estimator. Although the background was suppressed to a large extent, the estimator affects the quality of desired information as well.
\subsection{MMSE Log-Spectral Amplitude Estimator}
As expressed in Eq~\ref{eq:spectrum}, the Fourier transform of noisy signal $Y(\omega)$, desired signal $X(\omega)$ and noise signal $N(\omega)$ can be expressed in complex form, which consists of amplitude spectral and phase spectral. Thus, for the $k$th frequency bin, the observed signal is expressed below:
\begin{align}
Y(\omega_k)&=X(\omega_k)+N(\omega_k)\\
R_k\exp(j\theta_k)&=A_k\exp(j\alpha_k)+N_k
\end{align}
where $R_k$, $A_k$ and $N_k$ are corresponding amplitude spectrums. Due to the noise is assumed as additive white Gaussian noise (AWGN), there is no phase spectrum of noise, resulting in . Hence, if we estimate the amplitude of desired signal $A_k$, the restored signal can be reconstructed by using phase of received signal.
\par
The MMSE-LSA estimator is an improved noise reduction method based on the MMSE short-time spectral amplitude~\cite{ephraim1985speech}. It has large difference of spectral subtraction which estimates the noise spectrum based on average frames. Nevertheless, the objective of MMSE-LSA is to minimise the mean-squared error between the actual log-amplitude of speech signal and log-amplitude of estimated signal, which can be expressed as
\begin{align}
\arg\min_{\hat{A}_k}{\mathbb{E}\left[\left(\log A_k-\log\hat{A}_k\right)^2\vert y(t),0\leq t\leq T\right]}
\end{align}
given the known condition of observed signal $\{ y(t), 0\leq t\leq T\}$. Obviously, the optimal solution for this problem is when the estimated amplitude equal to actual amplitude, leading to zero MMSE error. That is,
\begin{equation}
\hat A_k=\text{exp}\left\{\mathbb{E}\left[\ln A_k | Y_k\right]\right\}
\end{equation}
Based on the Gaussian model assumption, the term $\mathbb{E}\left[\ln A_k | Y_k\right]$ is calculated given by $Y_k$. Let $Z_k=\ln A_k$ and the moment function $\Phi_{Z_k|Y_k}(\mu)$ is
\begin{align}
\Phi_{Z_k|Y_k}(\mu)&=\mathbb{E}\left\{\text{exp}(\mu Z_k) | Y_k\right\} \notag\\
&= \mathbb{E}\left\{A_k^\mu | Y_k\right\} \label{eq:aa}
\end{align}
Thus, the aim is to calculate $\Phi_{Z_k|Y_k}(\mu)$ now and obtain $\mathbb{E}\left[\ln A_k | Y_k\right]$ by taking derivative of moment function at $\mu=0$. The moment function can be obtained from equation \ref{eq:aa}:
\begin{align}
\Phi_{Z_k|Y_k}(\mu)&=\mathbb{E}\left[A_k^\mu\vert Y_k\right] \\
&=\int_0^{\infty}\int_0^{2\pi}a_k^\mu p(a_k,\alpha_k\vert Y_k)d\alpha_k d a_k \\
&= \int_0^{\infty}\int_0^{2\pi}a_k^\mu \frac{p(a_k,\alpha_k,Y_k)}{p(Y_k)}d\alpha_k d a_k \\
&=\frac{ \int_0^{\infty}\int_0^{2\pi}a_k^\mu p(Y_k\vert a_k,\alpha_k) p(a_k,\alpha_k) d\alpha_k d a_k }{ \int_0^{\infty}\int_0^{2\pi} p(Y_k\vert a_k,\alpha_k) p(a_k,\alpha_k) d\alpha_k d a_k }
\end{align}
Since we assumed that each frequency bin confirms to Gaussian distribution, the probability was defined as following:
\begin{align}
p(Y_k\vert a_k,\alpha_k)&=\frac{1}{\pi\lambda_d (k)}\exp\left[ -\frac{1}{\lambda_d (k)}\vert Y_k - a_k e^{j\alpha_k} \vert^2 \right] \\
p(a_k,\alpha_k&)=\frac{1}{\pi\lambda_x (k)}\exp\left[-\frac{a_k^2}{\lambda_x (k)}\right]
\end{align}
where $\lambda_x (k)\triangleq \mathbb{E}\left[\vert X_k \vert ^2\right]=A_k^2 $ and $\lambda_d (k)\triangleq\mathbb{E}\left[\vert D_k \vert ^2\right]$.
Based on the deduction in \cite{ephraim1985speech}, the amplitude of pure speech signal is calculated by
\begin{align}
\hat{A}_k=\frac{\xi_k}{1+\xi_k}\exp\left[\frac{1}{2}\int_{\upsilon_k}^{\infty}\frac{e^{-t}}{t}dt\right]R_k
\label{eq:magni}
\end{align}
and following parameters need to be estimated
\begin{align}
\upsilon_k\triangleq \frac{\xi_k}{1+\xi_k}\gamma_k;\quad
\xi_k\triangleq\frac{\lambda_x (k)}{\lambda_d (k)};\quad
\gamma_k\triangleq\frac{R_k^2}{\lambda_d (k)}
\label{eq:snr}
\end{align}
$\xi_k$ and $\gamma_k$ are considered as \textit{a prior} and \textit{a posterior} SNR respectively. The variance of noise can be updated by the voice activity detection (VAD) to detect the section without the presence of speech. Afterwards, \textit{a prior} SNR can be obtained by decision-directed method. Algorithm \ref{alg:mmse} demonstrates the procedure of MMSE-LSA estimator in Python realisation.\par
\begin{algorithm}
\renewcommand{\algorithmicrequire}{\textbf{Input:}}
\renewcommand{\algorithmicensure}{\textbf{Output:}}
\caption{MMSE-LSA estimator for Python realisation}
\label{alg:mmse}
\begin{algorithmic}[1]
\REQUIRE Noisy signal $y(t)$
\ENSURE Enhanced signal $x(t)$
\STATE Calculate the number of frames $N$ based on sampling frequency $f_s$
\STATE Assume first 6 frames is noise/silence
\FOR {k $\rightarrow$ 6}
\STATE Windowing $y(t)$ in frame length $y(k)$
\STATE FFT: y(k) $\rightarrow$ $Y(\omega_k)$
\STATE Calculate variance of noise power $\lambda_d(k)$
\ENDFOR
\FORALL{frames $k$ in $N$}
\STATE FFT: y(k) $\rightarrow$ $Y(\omega_k)$
\STATE Compute the power of noisy signal $R_k^2$
\STATE Compute and limit a post SNR to avoid overflows $\gamma_k<40 dB$
\STATE Calculate a priori SNR $\xi_k$ based on previous magnitude as shown in Eq.\ref{eq:snr}
\STATE Estimate the magnitude of clean signal $X_k$ based on Eq.\ref{eq:magni}
\ENDFOR
\STATE IFFT: $X(\omega)\rightarrow x(t)$
\STATE \textbf{return} $x(t)$
\end{algorithmic}
\end{algorithm}
Fig \ref{fig:logmmse} shows the mel-spectrogram after applying the MMSE-LSA estimator. Comparing with Fig \ref{fig:mel_spec}, the noise level was reduced to a large extent, presenting in lower magnitude of background. Moreover, the magnitude of call was enhanced, instead of attenuating in Fig \ref{fig:spec_sub}. Thus, the performance for MMSE-LSA method is outstanding than spectral subtraction in theoretically.
\begin{figure}[!htp]
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.5]{Figs/chap3/sub_spec.pdf}
\caption{spectral subtraction}
\label{fig:spec_sub}
\end{subfigure}
~
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.5]{Figs/chap3/logmmse.pdf}
\caption{MMSE-LSA}
\label{fig:logmmse}
\end{subfigure}
\caption{Mel spectrogram by using noise reduction methods}
\label{Fig:denoise}
\end{figure}
\section{Data Augmentation}
For a CNN model, millions of weighted parameters need to be trained in hidden layers, which needs a mass of data to ensure the network fully trained. As to this project, since only 388 calls were collected for training, the data have to augment, avoiding the over-fitting problem. Moreover, it can improve the variation and generalisation of the model. I applied five common and effective augmentation methods to artificially generate data both on positives and negatives as similarly done by \cite{sprengel2016audio}. In addition, all augmentation methods are implemented in the time domain. For each augmentation, I randomly selected one of them to manipulate.
\begin{itemize}[leftmargin=*]
\item \textbf{Time-shift}\\
The audio signal is shifted in time with random position. Representing in the spectral domain is equivalent to vertically splinted the spectrogram into two segments. Time-shift will change the order of these two parts, resulting in sharp changes at joint. However, the model task is to detect the presence of whinny call which has less semantic relations among context. Furthermore, the total information is reserved. With this approach, the network has the ability to handle the irregular spectrogram and detect the call occurred at any time.
\item \textbf{Add noise}\\
Adding background noise is one of the most effective approaches to improve network performance. In section 3.2, I introduced the noise reduction method that enhances the speech region. However, the performance of model would pull down if only the denoised dataset was trained. At this circumstance, the model is biased with less generalisation, presenting in only recognizing noise-free clips. Hence, I added moderately amplitude of noise to the original file, combining with the noise reduced data to train. Moreover, I mixed part of negative samples to positive as well.
\item\textbf{Pitch \& Speed}\\
As different augmentation methods were compared in \cite{schluter2015exploring}, the result showed that the pitch shift is significantly beneficial for improving. The pitch shift will change the frequency of sounds, resulting in vertical shift in the spectrogram. However, a large range of pitch shift will affect the biological features, which is not helpful for training. Time stretch will change the speed of the data. In order to maintain the same length of data, zeros were padded for speeding up and latter parts were removed for slow down mode. I applied a 5\% range of pitch shift and 10\% range of time stretch on raw data.
\item\textbf{Amplitude}\\
Changing amplitude is another way of augmentation. Since the version of data has large environmental noise, raising up the amplitude proved not a beneficial way. Hence, I emphasized to reduce dynamic amplitude with gain in $0.5\sim1.1$.
\end{itemize}
\section{Design of CNN}
\subsection{Activation Functions}
In deep learning, the neuron is the basic unit which mimics the way of human brain transmitting and processing. The artificial neuron is a mathematical model that contains input, computing and output modules. With different connection ways between neurons, the neuronal network can realize a amount of tasks. As to a fully connection, each neuron will receive inputs from previous neurons and forward transmitting the processed result. This can be expressed in mathematical:
\begin{align}
\mathbf z^l &=\sigma(\mathbf w^l \mathbf a^{l-1}+b)
\end{align}
where $\mathbf w$ is the weight at current layer which need to be learned, $\mathbf a$ is the output of last layer, $\mathbf z$ is the neuron output, $\sigma$ is the activation function and $b$ is the scalar bias.
However, there is no activation function for perceptron model, whose final output is linear combinations of the input feature. This leads to a limited capability of network to deal with complex problem. Hence, the non-linearity activation functions are introduced so that the feature representation of DNN is powerful. By setting the number of neurons at each layer, the network can converge to arbitrary functions. Four common non-linear activation functions will be introduced as follows. In addition, Fig \ref{Fig:act} shows the output curves for each functions.
\begin{itemize}[leftmargin=*]
\item \textbf{Sigmoid}\\
The mathematical expression of sigmoid is denoted as
\begin{equation}
\sigma(x)=\frac{1}{1+e^{-x}}
\end{equation}
It is one of the non-linear activation functions. The advantage of sigmoid function that maps the infinite range value in limited range $(0, 1)$, which can be interpreted as the neuron firing rate. Thus, most of binary classification networks used sigmoid as the final output, indicating the positive or negative. However, two main shortcomings make sigmoid function less use in the hidden layer. Firstly, due to the nearly zero slope at large positive and negative regions, gradient vanishing problem appears at the process of back propagation, which makes network refuse to further learn. Moreover, the output of sigmoid is not zero-centred with all positive values. This causes the weight updating always in one direction (positive or negative).
\item \textbf{Tanh}\\
As shown in Fig \ref{fig:sig}, the tanh function has the similarity of the sigmoid function, which can be expressed as
\begin{equation}
\tanh(x)=\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}=2*sigmoid(2x)-1
\end{equation}
Although the tanh solved the zero-centred problem of sigmoid, gradient vanishment is still an issue for tanh during back propagation.
\item \textbf{ReLU \& eLU}\\
ReLU is the short term of rectified linear unit and the expression is denoted as
\begin{equation}
A(x) = max(0,x)
\end{equation}
Although it is simple in mathematics, many of studies prove the outstanding performance of ReLU \cite{maas2013rectifier}. Firstly, the computational cost is quite small (only need to judge the input if is positive). Therefore, it converges faster than tanh and sigmoid function. Additionally, it overcomes the gradient vanishing problem in the positive region. However, the output of ReLU is still not zero-centred. Due to forced rectifying to zero for negatives, the dead ReLU problem appears for some neurons which will never be activated. For solving this problem, leaky ReLU and eLU are introduced, changing the function in negative part.\\
Exponential Linear Units, namely eLU, has all distinctions of ReLU. The negative part is modified into an exponential function, which is robust for noise. The average output of eLU is near zero without dead neuron problem. Thus, it should be outstanding compared with ReLU function, in spite of increasing computation. Nevertheless, few experiments demonstrated that the performance of eLU is better. Hence, I selected ReLU function applied in the design of CNN architecture.
\end{itemize}
\begin{figure}[!htp]
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.5]{Figs/chap3/act1.pdf}
\caption{Sigmoid and tanh}
\label{fig:sig}
\end{subfigure}
~
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.5]{Figs/chap3/act2.pdf}
\caption{ReLU and eLU}
\label{fig:relu}
\end{subfigure}
\caption{Different activation functions output curve}
\label{Fig:act}
\end{figure}
\subsection{Layers of CNN}
The network is designed by a combination of different layers. In general, there are three main layers for CNN architecture, connecting in hierarchical order.
\begin{itemize}[leftmargin=*]
\item\textbf{Convolutional layers}\\
The convolutional layer is the principal layer of CNN, which is used to extract features. It is performed by applying certain size filters to the input, accumulating masked values to get one output. With different weights in filters, the output can learn diverse features. Fig \ref{fig:filter} depicts the operation of filter convolution. For example, applying a $5\times5$ filter to the input will obtain one individual output. However, $5\times5$ size filter can be replaced by using two successive $3\times3$ filters, resulting in the same shape of output. This is the basic operation of VGG Network which makes network deeper.
\begin{figure}[htp]
\centering
\includegraphics[scale=0.5]{Figs/chap3/vggfilter.png}
\caption{visualisation of convolutional filters in VGGNet}
\label{fig:filter}
\end{figure}
\item\textbf{Pooling layers}\\
Pooling layers are normally following with convolutional layers. There are two aims of pooling that one is to reduce the dimension of parameters after convolution. On the other, the extracted features are compressed by selecting significant feature. In this project, maximum pooling layers were used to extract the maximum value in the corresponding region. It is an important procedure to prevent network over-fitting. Meanwhile, the computation speed is accelerated due to reducing feature dimension.
\item\textbf{Fully-Connected (Dense) layers}\\
Fully-connected or dense layers are the final section of the network. It firstly transforms the matrix into vector representation via convolving the matrix of each neuron. With FC layers, all neurons in current layer are connected to the next layer. Hence, features are combined in order to fit the distribution of data. Softmax or sigmoid activation functions are applied at the end as the classification output of the model.
\end{itemize}
\section{Model Training}
\subsection{Loss Functions and Optimizer}
Loss function plays an important role in training network and assists in back propagation. For a time step, the input data will pass through the CNN network and obtain a prediction at the end layer. A loss is generated to measure the divergence between the actual label $y$ and the prediction $\hat y$. As to one epoch, all training samples losses of each time step are summed together to calculate the back propagation step. The expression is
\begin{equation}
\boldsymbol{\mathcal{L}}(\boldsymbol{\theta})=\frac{1}{n}\sum_{i=1}^{n}L\big(y^{(i)},f(\mathbf{x}^{(i)},\boldsymbol{\theta})\big)
\end{equation}
where $\mathbf{x}$ and $\boldsymbol{\theta}$ are training samples and learning features respectively, $f(\cdot)$ represents the model output. There are several different loss functions, dealing with various tasks. Cross entropy (CE) is one of extensively used function with outstanding performance, especially in classification problem \cite{simard2003best}. In our case, the learning problem is a binary classification task which needs model to detect the positives and negatives. Hence, binary cross-entropy was applied for this work. The mathematical expression is shown below,
\begin{equation}
\boldsymbol{\mathcal{L}}=-\frac{1}{n}\sum_{i=1}^{n}\big[y^{(i)}\log(\hat{y}^{(i)})+(1-y^{(i)})\log(1-\hat{y}^{(i)})\big]
\label{eq:loss}
\end{equation}
The former term measures the positive prediction loss and the latter is for negative. Thus, if the true label is positive/negative (1/0) while the prediction is far different from the actual label, a large loss is introduced. Due to only logarithm and summation operation, the gradient can be computed rapidly compared with MSE loss function.
Once we defined the loss function, the optimiser needs to be chose for converging up to global optimum. An outstanding optimiser has the capability of not only fast convergence but also maintaining model recall. Adaptive moment estimation (Adam) optimiser \cite{kingma2014adam} computes both first and second-order moment to gradient descent. Since the mean and uncentered variance of the gradient are estimated, the Adam optimiser can adaptively adjust learning momentum, resulting in fast convergence speed compared with other gradient descent algorithms. As shown in practical experiments \cite{ruder2016overview}, Adam optimiser has an impressive performance. Thus, we apply Adam optimiser to reduce loss in Eq \ref{eq:loss} with default values of $\beta_1$, $\beta_2$ and $\epsilon$. The learning rate was set to $10^{-5}$.
\subsection{Hyperparameter Tuning}
After constructing the network, the model needs to be trained with appropriate parameters. The metrics are significant for evaluating the performance of model, which concentrates on targets of true positives (TP), false positives (FP), true negatives (TN) and false negatives (FN). Based on these targets, four different metrics are used to evaluate the network, namely accuracy, precision, recall and F1 score. Accuracy is the general metric to assess the performance. Precision represents how many true positives were detected among positive predictions, which is the ratio of TP with the summation of TP and FP. Recall evaluates how many positives can be mined by model, which is TP/(TP+FN). F1 score is the weighted combination of recall and precision. Hence, the model can be considered as optimum whichever achieves the expressive accuracy and F1 score.
Even though we use the fixed dataset to train the model, the eventual objective is to reduce generalisation error as much as possible. Thus, tuning network is an important part of training. As to tuning hyperparameters, the validation dataset is applied to evaluate performance during model training. It differs from test dataset that when the model is fine-tuned, the validation set will add to the training set for the final training. By observing metrics of the validation set, the hyperparameters can be tuned. Due to the limited GPUs and the size of dataset, the batch size is set to 16.
\begin{itemize}[leftmargin=*]
\item \textbf{Training Epoch}\\
For one time step, the CNN model will only concentrate on the batch size of data. When all training data are learned forward and updated backwards once, the CNN network is trained for one epoch. Thus, with large training epochs, the model could learn features multiple times. However, the model is insufficiently trained if epoch is too small. Hence, the threshold needs to be determined. By excessively set epoch to make model over-fitting on purpose, the appropriate threshold is easy obtained. Fig \ref{Fig:learning} demonstrates the training and validation loss with 100 epochs. After 50 epochs, the validation loss decreases significantly slowly compared with training loss. The difference between validation and training becomes larger, which caused the over-fitting problem on training data. Therefore, the epoch is set to 50.
\begin{figure}[htp]
\centering
\includegraphics[scale=0.45]{Figs/chap3/e100.pdf}
\caption{Training and validation loss curves of 100 training epochs}
\label{fig:epoch}
\end{figure}
\item \textbf{Learning rate}\\
Learning rate of the optimiser is another parameter that affects the loss. Although a large learning rate can rapidly converge to the optimum, it will result in the zigzag problem, oscillating near the global optimum. Fig \ref{Fig:learning} depicts the loss of learning rate in $10^{-4}$ and $10^{-5}$. The model appears over-fitting problem after 20 epochs in Fig \ref{fig:10-4}, presenting in an increasing trend of validation loss. When reducing learning rate 10 times, the loss slightly falling down without over-fitting. Thus, the learning rate is determined as $10^{-5}$, even if the final loss is large.
\begin{figure}[htp]
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.5]{Figs/chap3/10-4.png}
\caption{learning rate=$10^{-4}$}
\label{fig:10-4}
\end{subfigure}
~
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.5]{Figs/chap3/10-5.png}
\caption{learning rate=$10^{-5}$}
\label{fig:10-5}
\end{subfigure}
\caption{Training and validation loss curves of varying learning rate}
\label{Fig:learning}
\end{figure}
\end{itemize}
\subsection{Hard Negative Mining}
In this project, the negative data consists of other animal calls, environmental sounds and white noise. Since the negative examples are relatively effortless to obtain compared to rare positive calls, the number of negative examples is more than that of positives. Therefore, the variance and quality of negatives have large differences. For example, the white noise is significantly easy to be classified while other animal calls are not. As to further improving the model performance, hard negative mining approach can be applied to model training. Experiments proved this method is effective on objective detection tasks by SVM \cite{felzenszwalb2009object} and region-CNN (R-CNN) \cite{girshick2014rich}. They firstly used random bounding boxes to train the model. The boxes without overlapping with positives are called easy negatives and those with part of targets are difficult to be classified. Subsequently, these hard negatives were selected to form a new hard-negative dataset and retrain the model. After repeating several times, the performance of model is improved to a large extent.
\begin{figure}[!htp]
\hskip-1.5em
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.55]{Figs/chap3/pn.png}
\caption{original data}
\label{fig:pn}
\end{subfigure}
~
\begin{subfigure}[b]{0.5\linewidth}
\centering
\includegraphics[scale=0.55]{Figs/chap3/hnm.png}
\caption{hard negatives}
\label{fig:hn}
\end{subfigure}
\caption{Hard negative mining examples in two-dimension}
\label{Fig:hnm}
\end{figure}
Fig \ref{Fig:hnm} demonstrates the principle of hard negative mining in two-dimensional representation. The negatives with near distance to positives are hard samples to be classified. Thus, the decision boundary is influenced by the easy negatives for first trained. A large amount of negatives are classified as positives. When applying hard negative mining method, only hard samples are selected for the second train. Thus, the decision boundary is more distinct compared with the first training model, resulting in outstanding accuracy. As to this work, the hard negative mining only applied once to train the model totally twice.
|
open import Data.Product using (_×_; _,_)
open import IMP
open import OperationalSemantics
open import Hoare
soundness : ∀{P Q : assn} {c}
→ ⊢[ P ] c [ Q ]
→ ⊨[ P ] c [ Q ]
soundness Skip p Skip = p
soundness Loc p Loc = p
soundness (Comp r r₁) p (Comp z z₁) = soundness r₁ (soundness r p z) z₁
soundness (If r r₁) p (IfTrue x s) = soundness r (p , x) s
soundness (If r r₁) p (IfFalse x s) = soundness r₁ (p , x) s
soundness (While r) p (WhileFalse x₁) = p , x₁
soundness (While r) p (WhileTrue x₁ s s₁) = soundness (While r) (soundness r (p , x₁) s) s₁
soundness (Conseq x₁ r x₂) {s₁} {t} p s = x₂ t (soundness r (x₁ s₁ p) s)
|
#ifndef __DESIGN_H
#define __DESIGN_H
#include <gsl/gsl_matrix.h>
//function prototypes
double distance(double *x,double *y,int D,double p);
double cost(gsl_matrix *data,int Npoints,int D,double p,double lambda);
double diagonalCost(int Npoints,double lambda);
double swap(gsl_matrix *data,int Npoints,int D,double p,double lambda,int i1,int i2, int d);
void swapBack(gsl_matrix *data,int i1,int i2,int d);
//main design sampler prototype
double sample(int Npoints,int D,double p,double lambda,int seed,int maxIterations,gsl_matrix *data,double *costValues);
#endif
|
+ This notebook is part of lecture 17 *Orthogonal matrices and Gram-Scmidt* in the OCW MIT course 18.06 by Prof Gilbert Strang [1]
+ Created by me, Dr Juan H Klopper
+ Head of Acute Care Surgery
+ Groote Schuur Hospital
+ University Cape Town
+ <a href="mailto:[email protected]">Email me with your thoughts, comments, suggestions and corrections</a>
<a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/"></a><br /><span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/InteractiveResource" property="dct:title" rel="dct:type">Linear Algebra OCW MIT18.06</span> <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">IPython notebook [2] study notes by Dr Juan H Klopper</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">Creative Commons Attribution-NonCommercial 4.0 International License</a>.
+ [1] <a href="http://ocw.mit.edu/courses/mathematics/18-06sc-linear-algebra-fall-2011/index.htm">OCW MIT 18.06</a>
+ [2] Fernando Pérez, Brian E. Granger, IPython: A System for Interactive Scientific Computing, Computing in Science and Engineering, vol. 9, no. 3, pp. 21-29, May/June 2007, doi:10.1109/MCSE.2007.53. URL: http://ipython.org
```python
from IPython.core.display import HTML, Image
css_file = 'style.css'
HTML(open(css_file, 'r').read())
```
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<style>
@font-face {
font-family: "Computer Modern";
src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');
}
#notebook_panel { /* main background */
background: #ddd;
color: #000000;
}
/* Formatting for header cells */
.text_cell_render h1 {
font-family: 'Philosopher', sans-serif;
font-weight: 400;
font-size: 2.2em;
line-height: 100%;
color: rgb(0, 80, 120);
margin-bottom: 0.1em;
margin-top: 0.1em;
display: block;
}
.text_cell_render h2 {
font-family: 'Philosopher', serif;
font-weight: 400;
font-size: 1.9em;
line-height: 100%;
color: rgb(200,100,0);
margin-bottom: 0.1em;
margin-top: 0.1em;
display: block;
}
.text_cell_render h3 {
font-family: 'Philosopher', serif;
margin-top:12px;
margin-bottom: 3px;
font-style: italic;
color: rgb(94,127,192);
}
.text_cell_render h4 {
font-family: 'Philosopher', serif;
}
.text_cell_render h5 {
font-family: 'Alegreya Sans', sans-serif;
font-weight: 300;
font-size: 16pt;
color: grey;
font-style: italic;
margin-bottom: .1em;
margin-top: 0.1em;
display: block;
}
.text_cell_render h6 {
font-family: 'PT Mono', sans-serif;
font-weight: 300;
font-size: 10pt;
color: grey;
margin-bottom: 1px;
margin-top: 1px;
}
.CodeMirror{
font-family: "PT Mono";
font-size: 100%;
}
</style>
```python
from sympy import init_printing, symbols, Matrix, sin, cos, sqrt, Rational, GramSchmidt
from warnings import filterwarnings
```
```python
init_printing(use_latex = 'mathjax')
filterwarnings('ignore')
```
```python
theta = symbols('theta')
```
# Orthogonal basis
# Orthogonal matrix
# Gram-Schmidt
## Orthogonal basis
* Here we mean vectors *q*<sub>1</sub>,*q*<sub>2</sub>,...,*q*<sub>n</sub>
* We actually mean orthonormal vectors (for orthogonal or perpendicular and of unit length / normalized)
* Vectors that are orthogonal have a dot product equal to zero
* If they are orthogonal
$$ {q}_{i}^{T}{q}_{j}={0} $$
* If they are not
$$ {q}_{i}^{T}{q}_{j}\neq{0} $$
## Orthogonal matrix
* We can now put these (column) basis vectors into a matrix Q
* This brings about
$$ {Q}^{T}{Q}={I} $$
* In the case of the matrix Q being square the word *orthogonal matrix* is used
* When it is square we can calculate the inverse making
$$ {Q}^{T}={Q}^{-1} $$
* Consider the following permutation matrix with orthonormal column vectors
```python
Q = Matrix([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
Q, Q.transpose()
```
$$\begin{pmatrix}\left[\begin{matrix}0 & 0 & 1\\1 & 0 & 0\\0 & 1 & 0\end{matrix}\right], & \left[\begin{matrix}0 & 1 & 0\\0 & 0 & 1\\1 & 0 & 0\end{matrix}\right]\end{pmatrix}$$
* In this example the transpose also contains orthonormal column vectors
* Multiplication gives the identity matrix
```python
Q.transpose() * Q
```
$$\left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$$
* Consider this example
```python
Q = Matrix([[cos(theta), -sin(theta)], [sin(theta), cos(theta)]])
Q, Q.transpose()
```
$$\begin{pmatrix}\left[\begin{matrix}\cos{\left (\theta \right )} & - \sin{\left (\theta \right )}\\\sin{\left (\theta \right )} & \cos{\left (\theta \right )}\end{matrix}\right], & \left[\begin{matrix}\cos{\left (\theta \right )} & \sin{\left (\theta \right )}\\- \sin{\left (\theta \right )} & \cos{\left (\theta \right )}\end{matrix}\right]\end{pmatrix}$$
* The two column vectors are orthogonal and the length of each column vector is 1
* It is thus an orthogonal matrix
```python
Q.transpose() * Q
```
$$\left[\begin{matrix}\sin^{2}{\left (\theta \right )} + \cos^{2}{\left (\theta \right )} & 0\\0 & \sin^{2}{\left (\theta \right )} + \cos^{2}{\left (\theta \right )}\end{matrix}\right]$$
* The example below certainly has orthogonal column vectors, but they are not of unit length
$$ {Q}=\begin{bmatrix} 1 & 1 \\ 1 & {-1} \end{bmatrix} $$
* Well, we can change them into unit vectors by dividing each component by the length of that vector
$$ \sqrt { { \left( 1 \right) }^{ 2 }+{ \left( 1 \right) }^{ 2 } } =\sqrt { 2 } \\ \sqrt { { \left( 1 \right) }^{ 2 }+{ \left( -1 \right) }^{ 2 } } =\sqrt { 2 } $$
$$ Q=\frac { 1 }{ \sqrt { 2 } } \begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} $$
* As it stands Q<sup>T</sup>Q is not the identity matrix
```python
Q = Matrix([[1, 1], [1, -1]])
Q.transpose() * Q
```
$$\left[\begin{matrix}2 & 0\\0 & 2\end{matrix}\right]$$
* Turning it into an orthogonal matrix
```python
Q = (1 / sqrt(2)) * Matrix([[1, 1], [1, -1]])
Q
```
$$\left[\begin{matrix}\frac{\sqrt{2}}{2} & \frac{\sqrt{2}}{2}\\\frac{\sqrt{2}}{2} & - \frac{\sqrt{2}}{2}\end{matrix}\right]$$
```python
Q.transpose() * Q
```
$$\left[\begin{matrix}1 & 0\\0 & 1\end{matrix}\right]$$
* Consider this example with orthogonal (but not orthonormal) column vectors
```python
Q = Matrix([[1, 1, 1, 1], [1, -1, 1, -1], [1, 1, -1, -1], [1, -1, -1, 1]])
Q
```
$$\left[\begin{matrix}1 & 1 & 1 & 1\\1 & -1 & 1 & -1\\1 & 1 & -1 & -1\\1 & -1 & -1 & 1\end{matrix}\right]$$
* Again, as it stands Q<sup>T</sup>Q is not the identity matrix
```python
Q.transpose() * Q
```
$$\left[\begin{matrix}4 & 0 & 0 & 0\\0 & 4 & 0 & 0\\0 & 0 & 4 & 0\\0 & 0 & 0 & 4\end{matrix}\right]$$
* But turning it into an orthogonal matrix works
```python
Q = Rational(1, 2) * Matrix([[1, 1, 1, 1], [1, -1, 1, -1], [1, 1, -1, -1], [1, -1, -1, 1]])
# Rational() creates a mathematical fraction instead of a decimal
Q
```
$$\left[\begin{matrix}\frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2}\\\frac{1}{2} & - \frac{1}{2} & \frac{1}{2} & - \frac{1}{2}\\\frac{1}{2} & \frac{1}{2} & - \frac{1}{2} & - \frac{1}{2}\\\frac{1}{2} & - \frac{1}{2} & - \frac{1}{2} & \frac{1}{2}\end{matrix}\right]$$
```python
Q.transpose() * Q
```
$$\left[\begin{matrix}1 & 0 & 0 & 0\\0 & 1 & 0 & 0\\0 & 0 & 1 & 0\\0 & 0 & 0 & 1\end{matrix}\right]$$
* Consider this matrix Q with orthogonal column vectors, but that is not square
```python
Q = Rational(1, 3) * Matrix([[1, -2], [2, -1], [2, 2]])
Q
```
$$\left[\begin{matrix}\frac{1}{3} & - \frac{2}{3}\\\frac{2}{3} & - \frac{1}{3}\\\frac{2}{3} & \frac{2}{3}\end{matrix}\right]$$
* We now have a matrix with two column vectors that are normalized and orthogonal to each other and they form a basis for a plane (subspace) in ℝ<sup>3</sup>
* There must be a third column matrix of unit length, orthogonal to the other two so we end up with an orthogonal matrix
```python
Q = Rational(1, 3) * Matrix([[1, -2, 2], [2, -1, -2], [2, 2, 1]])
Q
```
$$\left[\begin{matrix}\frac{1}{3} & - \frac{2}{3} & \frac{2}{3}\\\frac{2}{3} & - \frac{1}{3} & - \frac{2}{3}\\\frac{2}{3} & \frac{2}{3} & \frac{1}{3}\end{matrix}\right]$$
```python
Q.transpose() * Q
```
$$\left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$$
* Let's make use of these matrices with orthonormal columns (which we will always denote with a letter Q) and project them onto their columnspace
* What would the projection matrix be?
$$ Q\underline{x}={b} \\ {P}={Q}{\left({Q}^{T}{Q}\right)}^{-1}{Q}^{T} $$
* Remember, though that for matrices with orthonormal column vectors we have Q<sup>T</sup>Q is the identity matrix and we have
$$ {P}={Q}{Q}^{T} $$
* If additionally, Q is square, then we have independent columns and the columnspace contain the whole space ℝ<sup>n</sup> and the projection matrix is the identity matrix in *n*
* Remember Q<sup>T</sup> = Q<sup>-1</sup> in these cases making it easy to see that we get the identity matrix
* Remember also that the projection matrix is symmetric
* Lastly the projection matrix has the property of squaring it leaves us in the same spot, so here we will have (QQ<sup>T</sup>)<sup>2</sup>=QQ<sup>T</sup>
* All of this has the final consequence that
$$ {Q}^{T}Q\hat{x}={Q}^{T}\underline{b} \\ \hat{x}={Q}^{T}\underline{b} \\ \hat{x}_{i}={q}_{i}^{T}{b} $$
## Gram-Schmidt
* All of the above makes things quite easy, so we should try and create orthogonal matrices
* Good, let's start with two independent vectors **a** and **b** and try and create two orthogonal vectors **A** and **B** and then create two orthonormal vectors
$$ { q }_{ 1 }=\frac { A }{ \left\| A \right\| } \\ { q }_{ 2 }=\frac { B }{ \left\| B \right\| } $$
* We can choose one of them as our initial vector, say **a** = **A**, so we have to get an orthogonal projection (to **a**) for **B**
* This is what we previously called the error vector **e**
$$ \underline{e}=\underline{b}-\underline{p} $$
* Remembering how to get **p** we have the following
$$ B=\underline { b } -\frac { { A }^{ T }\underline { b } }{ { A }^{ T }A } A $$
* Let's do an example
```python
a = Matrix([1, 1, 1])
b = Matrix([1, 0, 2])
a, b
```
$$\begin{pmatrix}\left[\begin{matrix}1\\1\\1\end{matrix}\right], & \left[\begin{matrix}1\\0\\2\end{matrix}\right]\end{pmatrix}$$
```python
A = a
A
```
$$\left[\begin{matrix}1\\1\\1\end{matrix}\right]$$
```python
A.transpose() * b
```
$$\left[\begin{matrix}3\end{matrix}\right]$$
```python
A.transpose() * A
```
$$\left[\begin{matrix}3\end{matrix}\right]$$
```python
B = b - A
B
```
$$\left[\begin{matrix}0\\-1\\1\end{matrix}\right]$$
* Checking that they are perpendicular
```python
A.transpose() * B
```
$$\left[\begin{matrix}0\end{matrix}\right]$$
* Now we have to create Q by turning **A** and **B** into unit vectors and place them in the same matrix
```python
A.normalized() # Easy way no normalize a matrix
```
$$\left[\begin{matrix}\frac{\sqrt{3}}{3}\\\frac{\sqrt{3}}{3}\\\frac{\sqrt{3}}{3}\end{matrix}\right]$$
```python
B.normalized()
```
$$\left[\begin{matrix}0\\- \frac{\sqrt{2}}{2}\\\frac{\sqrt{2}}{2}\end{matrix}\right]$$
```python
Q = Matrix([[sqrt(3) / 3, 0], [sqrt(3) / 3, -sqrt(2) / 2], [sqrt(3) / 3, sqrt(2) / 2]])
Q
```
$$\left[\begin{matrix}\frac{\sqrt{3}}{3} & 0\\\frac{\sqrt{3}}{3} & - \frac{\sqrt{2}}{2}\\\frac{\sqrt{3}}{3} & \frac{\sqrt{2}}{2}\end{matrix}\right]$$
* The columnspace of the original matrix (of two column vectors) and Q are the same
* In python™ we can use the following code
```python
# The column matrices (independant orthogonal column vectors) are entered indivisually inside square bracket []
A = [Matrix([1, 1, 1]), Matrix([1, 0, 2])]
A
```
$$\begin{bmatrix}\left[\begin{matrix}1\\1\\1\end{matrix}\right], & \left[\begin{matrix}1\\0\\2\end{matrix}\right]\end{bmatrix}$$
```python
Q = GramSchmidt(A, True) # The True argument normalizes the columns
Q
```
$$\begin{bmatrix}\left[\begin{matrix}\frac{\sqrt{3}}{3}\\\frac{\sqrt{3}}{3}\\\frac{\sqrt{3}}{3}\end{matrix}\right], & \left[\begin{matrix}0\\- \frac{\sqrt{2}}{2}\\\frac{\sqrt{2}}{2}\end{matrix}\right]\end{bmatrix}$$
## Example problems
### Example problem 1
* Create an orthogonal matrix from the following matrix
$$ \begin{bmatrix} 1 & 2 & 4 \\ 0 & 0 & 5 \\ 0 & 3 & 6 \end{bmatrix} $$
#### Solution
```python
A = [Matrix([1, 0, 0]), Matrix([2, 0, 3]), Matrix([4, 5, 6])]
A
```
$$\begin{bmatrix}\left[\begin{matrix}1\\0\\0\end{matrix}\right], & \left[\begin{matrix}2\\0\\3\end{matrix}\right], & \left[\begin{matrix}4\\5\\6\end{matrix}\right]\end{bmatrix}$$
```python
Q = GramSchmidt(A, True)
Q
```
$$\begin{bmatrix}\left[\begin{matrix}1\\0\\0\end{matrix}\right], & \left[\begin{matrix}0\\0\\1\end{matrix}\right], & \left[\begin{matrix}0\\1\\0\end{matrix}\right]\end{bmatrix}$$
* We can also consider QR-factorization
```python
from sympy.mpmath import matrix, qr
```
```python
A = matrix([[1, 2, 4], [0, 0, 5], [0, 3, 6]])
print(A)
```
[1.0 2.0 4.0]
[0.0 0.0 5.0]
[0.0 3.0 6.0]
```python
Q, R = qr(A)
```
```python
print(Q)
```
[1.0 0.0 0.0]
[0.0 0.0 -1.0]
[0.0 -1.0 0.0]
```python
print(R)
```
[1.0 2.0 4.0]
[0.0 -3.0 -6.0]
[0.0 0.0 -5.0]
```python
```
|
#! /usr/bin/Rscript --vanilla
library("rjson")
args = commandArgs(TRUE)
bugginess = fromJSON(args[2])
values = fromJSON(args[3])
print(cor.test(bugginess, values, method="pearson"))
print(cor.test(bugginess, values, method="kendall"))
# exact flag suppresses a warning
print(cor.test(bugginess, values, method="spearman", exact=FALSE))
|
\chapter{Introductory Material}
\label{chapterlabel1}
Some stuff about things.\cite{example-citation} Some more things.
Inline citation: %\bibentry{example-citation}
% This just dumps some pseudolatin in so you can see some text in place.
\blindtext
|
using Altro
using TrajectoryOptimization
using StaticArrays
using BenchmarkTools
using RobotZoo
using RobotDynamics
using StaticArrays, LinearAlgebra
using ForwardDiff
using Test
using FiniteDiff
using Random
const TO = TrajectoryOptimization
const RD = RobotDynamics
# Test Functions
function Πsoc(x)
v = x[1:end-1]
s = x[end]
a = norm(v)
if a <= -s
return zero(x)
elseif a <= s
return x
elseif a >= abs(s)
x̄ = append!(v, a)
return 0.5*(1 + s/a) * x̄
end
throw(ErrorException("Invalid second-order cone"))
end
function in_soc(x)
v = x[1:end-1]
s = x[end]
a = norm(v)
a <= s
end
function alcost(x,z,μ)
c = push(x, u_bnd)
proj = Πsoc(z - μ .* c)
1/2μ*(proj'proj - z'z)
end
function auglag(f,g, x,z,μ)
# ceq = h(x)
L0 = f(x) #+ y'ceq + 0.5*μ*ceq'ceq
# cones = g(x)
# p = length(cones)
for i = 1:length(z)
L0 += alcost(x[uinds[i]], z[i], μ)
# cone = cones[i]
# proj = Πsoc(z[i] - μ*cones[i])
# Iμ = I * inv(μ)
# pen = proj'proj - z[i]'z[i]
# L0 += 1 / 2μ * pen
end
return L0
end
function DI_objective(Q,R,Qf,xf,dt)
g = Float64[]
h = Float64[]
c = 0.0
for k = 1:N-1
append!(g, -Q*xf)
append!(g, zeros(m))
append!(h, Q.diag)
append!(h, R.diag)
c += 0.5*xf'Q*xf
end
# g .*= dt
# h .*= dtk
# c *= dt
append!(g, -Qf*xf)
# append!(g, zeros(m))
append!(h, Qf.diag)
# append!(h, R.diag)
c += 0.5*xf'Qf*xf
H = Diagonal(h)
return H,g,c
end
function DI_dynamics(x0, N; dt=0.1, gravity::Bool=false)
n = length(x0)
m = n ÷ 2
D = m
NN = N*(n+m)
# Continuous dynamics
Ac = zeros(n,n)
Bc = zeros(n,m)
for i = 1:D
Ac[i,D+i] = 1
Bc[D+i,i] = 1
end
# Euler integration
Ad = I + Ac*dt
Bd = Bc*dt
iA = 1:n
jA = iA
jB = n .+ (1:m)
jA2 = jA .+ (n+m)
A = zeros(N*n, NN)
b = zeros(N*n)
A[iA,jA] .= I(n)
b[iA] .= -x0
iA = iA .+ n
for k = 1:N-1
A[iA,jA] .= Ad
A[iA,jB] .= Bd
A[iA,jA2] .= -I(n)
if gravity
b[iA[D]] = -9.81
end
# Advance inds
iA = iA .+ n
jA = jA .+ (n+m)
jB = jB .+ (n+m)
jA2 = jA2 .+ (n+m)
end
return A,b
end
function DI_cones(::Val{D},N) where D
uinds = SVector{D}(1:D) .+ 2D
qinds = [uinds .+ (k-1)*3D for k = 1:N-1]
end
DI_cones(D,N) = DI_cones(Val(D),N) # WARNING: type unstable
## Setup
D,N = 2,11
n,m = 2D,D
dt = 0.1
tf = (N-1)*dt
x0 = @SVector fill(0., n)
xf = [(@SVector fill(1.,D)); (@SVector fill(0, D))]
Q = Diagonal(@SVector fill(1.0, n)) * dt
R = Diagonal(@SVector fill(1e-1, m)) * dt
Qf = (N-1)*Q * 100
qinds = DI_cones(D,N)
u_bnd = 6.0
# Define batch functions
H_obj,g_obj,c_obj = DI_objective(Q,R,Qf,xf,dt)
Adyn,bdyn = DI_dynamics(x0,N, dt=dt)
di_obj(x) = 0.5*x'H_obj*x + g_obj'x + c_obj
di_dyn(x) = Adyn*x + bdyn
di_soc(x) = [push(x[qi],u_bnd) for qi in qinds]
# Define using ALTRO
model = RobotZoo.DoubleIntegrator(D)
obj = LQRObjective(Q, R, Qf, xf, N)
cons = ConstraintList(n,m,N)
cone = TO.SecondOrderCone()
# cone = TO.Inequality()
u_bnd = 6.0
connorm = NormConstraint(n, m, u_bnd, cone, :control)
add_constraint!(cons, connorm, 1:N-1)
prob = Problem(model, obj, x0, tf, xf=xf, constraints=cons, integration=RD.Euler(model))
solver = Altro.ALSolver(prob, use_static=Val(true))
conSet = TO.get_constraints(solver)
alobj = TO.get_objective(solver)
# Initialization
inds = LinearIndices(zeros(3D,N))
xinds = [SVector{n}(z[1:n]) for z in eachcol(inds)]
uinds = [SVector{m}(z[n+1:end]) for z in eachcol(inds)][1:end-1]
NN = 3D*N-D
P = (N-1)*m
x0 = rand(NN)
z = rand.(length.(di_soc(x0)))
z0 = deepcopy(z)
μ = 2.4
X0 = [x0[xi] for xi in xinds]
U0 = [x0[ui] for ui in uinds]
Z0 = SampledTrajectory(X0,U0, dt=dt)
initial_trajectory!(solver, Z0)
## Test objective and soc constraints
z = deepcopy(z0)
Altro.reset_duals!(conSet)
@test cost(alobj, Z0) ≈ di_obj(x0)
@test conSet[1].vals ≈ di_soc(x0)
# copy multipliers to ALconSet
cval = conSet[1]
for i = 1:N-1
cval.λ[i] .= z[i]
cval.μ[i] .= μ
end
# test augmented Lagrangian value
LA(x) = auglag(di_obj, di_soc, x, z, μ)
@test di_obj(x0) ≈ cost(alobj.obj, Z0) # unconstrained cost
@test cost(solver) ≈ LA(x0)
@test !(cost(solver) ≈ di_obj(x0)) # make sure the AL cost isn't the same as the normal cost
λbar = z .- μ .* di_soc(x0)
statuses = [TO.cone_status(TO.SecondOrderCone(), λ) for λ in λbar]
@test :below ∈ statuses
# E = TO.QuadraticObjective(n,m,N)
E0 = Altro.CostExpansion{Float64}(n,m,N)
E = Altro.get_ilqr(solver).Efull
let solver = solver.ilqr
Altro.cost_expansion!(solver.obj, E, solver.Z)
@test_throws AssertionError Altro.cost_expansion!(solver.obj, E0, solver.Z)
end
# TO.cost_expansion!(E, alobj, Z0)
grad = vcat([e.grad for e in E]...)[1:end-m]
@test grad ≈ FiniteDiff.finite_difference_gradient(LA, x0)
hess_blocks = vcat([[e.xx, e.uu] for e in E]...)
hess = cat(hess_blocks..., dims=(1,2))[1:end-m, 1:end-m]
@test hess ≈ FiniteDiff.finite_difference_hessian(LA, x0) atol=1e-4
@test all(in_soc.(di_soc(x0)))
@test !all(in_soc.(z .- μ*di_soc(x0)))
# Make it go outside the cone
Random.seed!(1)
z = rand.(length.(di_soc(x0)))
z .*= 100
λbar = z .- μ .* di_soc(x0)
statuses = [TO.cone_status(TO.SecondOrderCone(), λ) for λ in λbar]
for i = 1:20
if :outside in statuses && :in in statuses
break
else
z .= rand.(length.(di_soc(x0)))
z .*= 100
λbar .= z .- μ .* di_soc(x0)
statuses .= [TO.cone_status(TO.SecondOrderCone(), λ) for λ in λbar]
end
end
@test :outside ∈ statuses
@test :in ∈ statuses
for i = 1:N-1
cval.λ[i] .= z[i]
cval.μ[i] .= μ
cval.μinv[i] .= inv.(μ)
end
LA(x) = auglag(di_obj, di_soc, x, z, μ)
# E = TO.QuadraticObjective(n,m,N)
# E = Altro.CostExpansion{Float64}(n,m,N)
E = Altro.get_ilqr(solver).Efull
@test LA(x0) ≈ cost(solver, Z0)
Altro.cost_expansion!(alobj, E, Z0)
# TO.cost_expansion!(E, alobj, Z0)
alcon = conSet[1]
grad = vcat([e.grad for e in E]...)[1:end-m]
@test grad ≈ FiniteDiff.finite_difference_gradient(LA, x0) atol=1e-6
[grad FiniteDiff.finite_difference_gradient(LA, x0)]
hess_blocks = vcat([[e.xx, e.uu] for e in E]...)
hess = cat(hess_blocks..., dims=(1,2))[1:end-m, 1:end-m]
@test hess ≈ FiniteDiff.finite_difference_hessian(LA, x0) atol=1e-2
## Solve it
prob = Problem(model, obj, zero(SVector{n}), tf, xf=xf, constraints=cons, integration=RD.Euler(model))
solver = Altro.ALSolver(prob, verbose=0, show_summary=false,
projected_newton=true, penalty_initial=100.0, penalty_scaling=50,
cost_tolerance_intermediate=1e-1)
initial_controls!(solver, [rand(D) for k = 1:N])
solve!(solver)
@test all(abs.(norm.(controls(solver))[[1,2,N-2,N-1]] .- u_bnd) .< 1e-5)
# prob = Problem(model, obj, xf, tf, x0=x0, constraints=cons)
# solver = ALTROSolver(prob, show_summary=true, verbose=2, projected_newton=false)
# @test benchmark_solve!(solver).allocs == 0
# benchmark_solve!(solver)
|
Set Implicit Arguments.
Unset Standard Proposition Elimination Names.
Require Import List.
Require Import list_utils.
Require Import Bool.
Require Import expec.
Require Import util.
Require Import sums_and_averages.
Require Import Rbase.
Arguments length {A}.
Section contents.
Variables (X: Set) (eq_X_dec: forall (x y: X), { x = y } + { x <> y }).
Definition beq_X (x y: X): bool := unsum_bool (eq_X_dec x y).
Lemma counts_0_length_0 (l: list X): (forall i, count (beq_X i) l = 0%nat) -> length l = 0%nat.
Proof with auto.
destruct l; simpl...
intros.
elimtype False.
specialize (H x).
unfold beq_X in H.
destruct (eq_X_dec x x)...
simpl in H.
discriminate.
Qed.
Lemma counts_0_expec_length_0 t:
(forall i, expec (count (beq_X i)) t = 0) -> expec (@length (_:Set)) t = 0.
Proof with auto.
intros.
replace 0 with (INR 0)...
apply expec_constant.
intros.
apply counts_0_length_0.
intros.
apply (expec_0_inv (count (beq_X i))) with t...
Qed.
Lemma exp_list_sum_le (fr: X -> R) (q: list X) (t: ne_tree.T (list X)):
(forall i, In i q -> expec (count (beq_X i)) t <= fr i) ->
(forall i, ~ In i q -> expec (count (beq_X i)) t = 0) ->
expec (@length (_:Set)) t <= Rsum (map fr q).
Proof with auto with real.
induction q in t |- *.
simpl.
intros.
rewrite counts_0_expec_length_0...
simpl.
intros.
rewrite (@expec_ext _ (@length (_:Set)) (fun x => plus (count (beq_X a) x) (count (negb ∘ beq_X a) x)) ).
Focus 2.
intro.
apply length_excl_counts.
rewrite expec_plus.
apply Rle_trans with (fr a + expec (count (fun t0: X => negb (beq_X a t0))) t)...
apply Rplus_le_compat_l.
apply Rle_trans with (expec (@length (_:Set)) (ne_tree.map (filter (fun x: X => negb (beq_X a x))) t)).
rewrite expec_map.
apply expec_le.
intros.
rewrite comp_apply.
rewrite length_filter...
apply IHq...
intros.
rewrite expec_map.
destruct (eq_X_dec a i).
subst.
apply Rle_trans with (expec (count (beq_X i)) t)...
apply expec_le.
intros.
repeat rewrite comp_apply.
apply count_filter_le.
apply Rle_trans with (expec (count (beq_X i)) t).
apply expec_le.
intros.
repeat rewrite comp_apply.
apply count_filter_le.
apply H.
right...
intros.
rewrite expec_map.
destruct (eq_X_dec a i).
subst.
replace 0 with (INR 0)...
apply expec_constant.
intros.
rewrite comp_apply.
apply count_filtered.
intros.
destruct (beq_X i x0)...
apply Rle_antisym.
apply Rle_trans with (expec (count (beq_X i)) t).
apply expec_le.
intros.
rewrite comp_apply.
apply count_filter_le.
rewrite H0...
intro.
destruct H2...
apply expec_nonneg.
Qed.
End contents.
|
A \ac{gpl} is a computer language intended to be used in a wide range of domains. An example is the \gls{cpp} programming language, which can be used in domains that vary from video games to web servers and systems programming. In contrast, a \acf{dsl} is a computer language that was designed to be used in a particular domain. Game Maker Language, \acs{html}, LaTeX and \acs{vhdl} are examples of \acp{dsl}. These languages, when compared to \acp{gpl}, offer a higher level of abstraction from their target domain.
A \ac{dsl} can be implemented using two different strategies: standalone and embedded. Each strategy has its advantages and disadvantages. In the former strategy, the language is built from the ground up, which consists of developing either a compiler or an interpreter. This strategy provides the language designer with a lot design freedom, but requires a cumbersome amount of work. In the latter strategy, the proposed \ac{dsl} is embedded in another language. Therefore, the \ac{dsl} inherits functionality from its host language. This inheritance often is desirable (e.g., a type checker) but sometimes might be undesirable (e.g., type coercion). This strategy frees its designer of building a new compiler.
The semantics of a \acf{edsl} are given by its views (also called backends). Common views are evaluation, pretty printing, compilation, optimization and verification. There are two main techniques for building an \ac{edsl}: deep and shallow embedding.
\section{Deep Embedding}
A deeply \ac{edsl} is represented in its host language as an \ac{adt}, where language constructs are modelled as data constructs. Views are functions that take the \ac{adt} as input and return another \ac{adt} that represents its semantics. An example of a simple deeply \ac{edsl} and its views (pretty printing and evaluation) can be seen on Listing \ref{deep1}.
\begin{lstlisting}[caption=A simple deeply \ac{edsl} and its views,captionpos=b,label=deep1]
:: MyDSL = I Int
| B Bool
| Add MyDSL MyDSL
| Sub MyDSL MyDSL
| And MyDSL MyDSL
| Or MyDSL MyDSL
| Var String
prettyPrint :: MyDSL -> [String]
eval :: MyDSL -> Int
\end{lstlisting}
The biggest advantage of deep embedding is that adding a view to the \ac{dsl} is easy: simply create a function that transforms the \ac{adt}. One disadvantage is that extending the \ac{dsl} might require a lot of work, since new code has to be created for every new construct in all the views. Another disadvantage is its lack of static type safety. As seen on Listing \ref{deep1}, \texttt{MyDSL} allows operations on mixed data types, such as addition on booleans and disjunction on integers.
\acp{gadt} can be used to accomplish static type safety in deeply \acp{edsl}, but \gls{clean} does not support them~\cite{gadts}.
\section{Shallow Embedding}
Building a shallowly \ac{edsl} consists of representing the language constructs directly as its semantics. An example of a simple shallowly \ac{edsl} can be seen on Listing \ref{shallow1}. In this example, the \texttt{Sem} \ac{adt} contains both the evaluation (\texttt{a}) and the pretty printing (\texttt{[String]}) views.
\begin{lstlisting}[caption=A simple shallowly \ac{edsl},captionpos=b,label=shallow1]
:: Sem a = Sem (a, [String])
add :: (Sem a) (Sem a) -> Sem a | + a
and :: (Sem Bool) (Sem Bool) -> Sem Bool
eq :: (Sem a) (Sem a) -> Sem Bool | == a
var :: String -> Sem Int
\end{lstlisting}
One advantage of shallow over deep embedding is that adding a new language construct is easy, given that each construct is just a function. Another advantage is that overloading can be achieved with the use of class constraints. In addition, static type checking is obtained without \acp{gadt}.
The biggest disadvantages of shallow embedding are based on the fact that all views are grouped in the same \ac{adt}. First, there is no separation of concerns. Second, there is computational waste when not all views are necessary. Finally, adding a new view in the semantics becomes increasingly burdensome. Another disadvantage of shallow embedding is that variables still remain unchecked during compilation. Finally, since the language constructs are functions, they can not be inspected as in deeply \acp{edsl}.
\subsection{Shallow Embedding with Type Classes}\label{sec:class_based_edsl}
Type constructor classes can be used to avoid computing all the views of a shallowly \ac{edsl}~\cite{tagless}. A type constructor class containing the language constructs is created and each of the \ac{dsl} views should provide an instance of the class. An example of a class-based shallowly \ac{edsl} can be seen on Listing \ref{shallow2}.
\begin{lstlisting}[caption=A simple class-based shallowly \ac{edsl},captionpos=b,label=shallow2]
:: Print a = P [String]
:: Eval a = E a
class myDSL v where
lit :: t -> v t | toString t
add :: (v t) (v t) -> v t | + t
and :: (v Bool) (v Bool) -> v Bool
eq :: (v t) (v t) -> v Bool | == t
instance myDSL Print where
lit x = P [toString x]
add (P x) (P y) = P (x ++ [" + ":y])
and (P x) (P y) = P (x ++ [" && ":y])
eq (P x) (P y) = P (x ++ [" == ":y])
instance myDSL Eval where
lit x = E x
add (E x) (E y) = E (x + y)
and (E x) (E y) = E (x && y)
eq (E x) (E y) = E (x == y)
\end{lstlisting}
Class-based shallow embedding solves most of the problems previously faced with deep and shallow embedding. The language is statically typed, the views are separated, adding a view is simple, extending the language with a new construct is easy and operators can be overloaded.
Two problems remain. First, language constructs still can not be inspected. This is an inherent property of shallowly \acp{edsl} and unfortunately cannot be eliminated.
Second, variables are still not checked at compile time. Functions can be used to solve this. This solution is not inherent to class-based deep embedding and can be used on regular deep embedding and on shallow embedding as well. Given that function arguments are well-typed in the host language, they can be used to represent typed variables. A variable declaration is defined as a function where its argument represents the variable and the function body represents the remaining of the program. As a result, any usage of the variable in the function body is well typed. In order to avoid constructs that are not variables on the left-hand side of the attribution operator, the types \texttt{Var} and \texttt{Expr} are introduced. In some views, these types are phantom types~\cite{phantom}.
An example of a class-based shallowly \ac{edsl} with compile time variable checks can be seen on Listing \ref{shallow3}. \texttt{Eval} is an example of a view with a phantom type: the type variable \texttt{b}.
\begin{lstlisting}[caption=A simple class-based shallowly \ac{edsl} with compile time variable checks,captionpos=b,label=shallow3]
:: Eval a b = E a
:: In a b = In infixl 0 a b
:: Var = Var
:: Expr = Expr
class expr v where
lit :: t -> v t Expr
(+.) infixl 6 :: (v t p) (v t q) -> v t Expr | + t
class var v where
var :: ((v t Var) -> In t (v a p)) -> v a p
(=.) infixr 3 :: (v t Var) (v t p) -> v t Expr
instance expr Eval where
lit x = E x
(+.) (E a) (E b) = E (a + b)
instance var Eval where
var _ = ...
(=.) _ _ = ...
test1 :: Eval Int Expr
test1 = var \k = 4 In
k =. k +. lit 7
test2 :: Eval Int Expr
test2 = var \k = 4 In
k =. lit True // Compilation error
\end{lstlisting}
As seen in the example above, the variable \texttt{k} can be used after its declaration in a well typed manner. Function \texttt{test1} compiles successfully, as expected. Function \texttt{test2}, in the other hand, does not compile due to a type error. Therefore, compile time check of variables was achieved.
|
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
⊢ x * (y + z) = x * y + x * z
[PROOFSTEP]
have := A.mul.map_add (x ⊗ₜ y) (x ⊗ₜ z)
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
this : ↑A.mul (x ⊗ₜ[R] y + x ⊗ₜ[R] z) = ↑A.mul (x ⊗ₜ[R] y) + ↑A.mul (x ⊗ₜ[R] z)
⊢ x * (y + z) = x * y + x * z
[PROOFSTEP]
convert this
[GOAL]
case h.e'_2
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
this : ↑A.mul (x ⊗ₜ[R] y + x ⊗ₜ[R] z) = ↑A.mul (x ⊗ₜ[R] y) + ↑A.mul (x ⊗ₜ[R] z)
⊢ x * (y + z) = ↑A.mul (x ⊗ₜ[R] y + x ⊗ₜ[R] z)
[PROOFSTEP]
rw [← TensorProduct.tmul_add]
[GOAL]
case h.e'_2
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
this : ↑A.mul (x ⊗ₜ[R] y + x ⊗ₜ[R] z) = ↑A.mul (x ⊗ₜ[R] y) + ↑A.mul (x ⊗ₜ[R] z)
⊢ x * (y + z) = ↑A.mul (x ⊗ₜ[R] (y + z))
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
⊢ (x + y) * z = x * z + y * z
[PROOFSTEP]
have := A.mul.map_add (x ⊗ₜ z) (y ⊗ₜ z)
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
this : ↑A.mul (x ⊗ₜ[R] z + y ⊗ₜ[R] z) = ↑A.mul (x ⊗ₜ[R] z) + ↑A.mul (y ⊗ₜ[R] z)
⊢ (x + y) * z = x * z + y * z
[PROOFSTEP]
convert this
[GOAL]
case h.e'_2
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
this : ↑A.mul (x ⊗ₜ[R] z + y ⊗ₜ[R] z) = ↑A.mul (x ⊗ₜ[R] z) + ↑A.mul (y ⊗ₜ[R] z)
⊢ (x + y) * z = ↑A.mul (x ⊗ₜ[R] z + y ⊗ₜ[R] z)
[PROOFSTEP]
rw [← TensorProduct.add_tmul]
[GOAL]
case h.e'_2
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
this : ↑A.mul (x ⊗ₜ[R] z + y ⊗ₜ[R] z) = ↑A.mul (x ⊗ₜ[R] z) + ↑A.mul (y ⊗ₜ[R] z)
⊢ (x + y) * z = ↑A.mul ((x + y) ⊗ₜ[R] z)
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x : ↑A.X
⊢ ↑A.mul (0 ⊗ₜ[R] x) = 0
[PROOFSTEP]
rw [TensorProduct.zero_tmul, map_zero]
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x : ↑A.X
⊢ ↑A.mul (x ⊗ₜ[R] 0) = 0
[PROOFSTEP]
rw [TensorProduct.tmul_zero, map_zero]
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
⊢ x * y * z = x * (y * z)
[PROOFSTEP]
have := LinearMap.congr_fun A.mul_assoc (x ⊗ₜ y ⊗ₜ z)
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x y z : ↑A.X
this :
↑(CategoryTheory.MonoidalCategory.tensorHom A.mul (𝟙 A.X) ≫ A.mul) ((x ⊗ₜ[R] y) ⊗ₜ[R] z) =
↑((CategoryTheory.MonoidalCategory.associator A.X A.X A.X).hom ≫
CategoryTheory.MonoidalCategory.tensorHom (𝟙 A.X) A.mul ≫ A.mul)
((x ⊗ₜ[R] y) ⊗ₜ[R] z)
⊢ x * y * z = x * (y * z)
[PROOFSTEP]
convert this
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x : ↑A.X
⊢ 1 * x = x
[PROOFSTEP]
have := LinearMap.congr_fun A.one_mul ((1 : R) ⊗ₜ x)
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x : ↑A.X
this :
↑(CategoryTheory.MonoidalCategory.tensorHom A.one (𝟙 A.X) ≫ A.mul) (1 ⊗ₜ[R] x) =
↑(CategoryTheory.MonoidalCategory.leftUnitor A.X).hom (1 ⊗ₜ[R] x)
⊢ 1 * x = x
[PROOFSTEP]
convert this
[GOAL]
case h.e'_3
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x : ↑A.X
this :
↑(CategoryTheory.MonoidalCategory.tensorHom A.one (𝟙 A.X) ≫ A.mul) (1 ⊗ₜ[R] x) =
↑(CategoryTheory.MonoidalCategory.leftUnitor A.X).hom (1 ⊗ₜ[R] x)
⊢ x = ↑(CategoryTheory.MonoidalCategory.leftUnitor A.X).hom (1 ⊗ₜ[R] x)
[PROOFSTEP]
rw [MonoidalCategory.leftUnitor_hom_apply, one_smul]
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x : ↑A.X
⊢ x * 1 = x
[PROOFSTEP]
have := LinearMap.congr_fun A.mul_one (x ⊗ₜ (1 : R))
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x : ↑A.X
this :
↑(CategoryTheory.MonoidalCategory.tensorHom (𝟙 A.X) A.one ≫ A.mul) (x ⊗ₜ[R] 1) =
↑(CategoryTheory.MonoidalCategory.rightUnitor A.X).hom (x ⊗ₜ[R] 1)
⊢ x * 1 = x
[PROOFSTEP]
convert this
[GOAL]
case h.e'_3
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : AddCommGroup ↑A.X := inferInstance
x : ↑A.X
this :
↑(CategoryTheory.MonoidalCategory.tensorHom (𝟙 A.X) A.one ≫ A.mul) (x ⊗ₜ[R] 1) =
↑(CategoryTheory.MonoidalCategory.rightUnitor A.X).hom (x ⊗ₜ[R] 1)
⊢ x = ↑(CategoryTheory.MonoidalCategory.rightUnitor A.X).hom (x ⊗ₜ[R] 1)
[PROOFSTEP]
erw [MonoidalCategory.leftUnitor_hom_apply, one_smul]
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : MonoidalCategory.tensorUnit (ModuleCat R) ⟶ A.X := A.one
x y : R
⊢ OneHom.toFun { toFun := src✝.toFun, map_one' := (_ : AddHom.toFun src✝.toAddHom 1 = AddHom.toFun src✝.toAddHom 1) }
(x * y) =
OneHom.toFun { toFun := src✝.toFun, map_one' := (_ : AddHom.toFun src✝.toAddHom 1 = AddHom.toFun src✝.toAddHom 1) }
x *
OneHom.toFun
{ toFun := src✝.toFun, map_one' := (_ : AddHom.toFun src✝.toAddHom 1 = AddHom.toFun src✝.toAddHom 1) } y
[PROOFSTEP]
have h := LinearMap.congr_fun A.one_mul.symm (x ⊗ₜ A.one y)
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : MonoidalCategory.tensorUnit (ModuleCat R) ⟶ A.X := A.one
x y : R
h :
↑(CategoryTheory.MonoidalCategory.leftUnitor A.X).hom (x ⊗ₜ[R] ↑A.one y) =
↑(CategoryTheory.MonoidalCategory.tensorHom A.one (𝟙 A.X) ≫ A.mul) (x ⊗ₜ[R] ↑A.one y)
⊢ OneHom.toFun { toFun := src✝.toFun, map_one' := (_ : AddHom.toFun src✝.toAddHom 1 = AddHom.toFun src✝.toAddHom 1) }
(x * y) =
OneHom.toFun { toFun := src✝.toFun, map_one' := (_ : AddHom.toFun src✝.toAddHom 1 = AddHom.toFun src✝.toAddHom 1) }
x *
OneHom.toFun
{ toFun := src✝.toFun, map_one' := (_ : AddHom.toFun src✝.toAddHom 1 = AddHom.toFun src✝.toAddHom 1) } y
[PROOFSTEP]
rwa [MonoidalCategory.leftUnitor_hom_apply, ← A.one.map_smul] at h
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : MonoidalCategory.tensorUnit (ModuleCat R) ⟶ A.X := A.one
r : R
a : (fun x => ↑A.X) r
⊢ ↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := src✝.toFun,
map_one' := (_ : AddHom.toFun src✝.toAddHom 1 = AddHom.toFun src✝.toAddHom 1) },
map_mul' :=
(_ :
∀ (x y : R),
↑A.one (x • y) =
↑(CategoryTheory.MonoidalCategory.tensorHom A.one (𝟙 A.X) ≫ A.mul) (x ⊗ₜ[R] ↑A.one y)) },
map_zero' := (_ : ↑A.one 0 = 0),
map_add' :=
(_ :
∀ (x y : ↑(MonoidalCategory.tensorUnit (ModuleCat R))),
AddHom.toFun src✝.toAddHom (x + y) = AddHom.toFun src✝.toAddHom x + AddHom.toFun src✝.toAddHom y) }
r *
a =
a *
↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := src✝.toFun,
map_one' := (_ : AddHom.toFun src✝.toAddHom 1 = AddHom.toFun src✝.toAddHom 1) },
map_mul' :=
(_ :
∀ (x y : R),
↑A.one (x • y) =
↑(CategoryTheory.MonoidalCategory.tensorHom A.one (𝟙 A.X) ≫ A.mul) (x ⊗ₜ[R] ↑A.one y)) },
map_zero' := (_ : ↑A.one 0 = 0),
map_add' :=
(_ :
∀ (x y : ↑(MonoidalCategory.tensorUnit (ModuleCat R))),
AddHom.toFun src✝.toAddHom (x + y) = AddHom.toFun src✝.toAddHom x + AddHom.toFun src✝.toAddHom y) }
r
[PROOFSTEP]
dsimp
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : MonoidalCategory.tensorUnit (ModuleCat R) ⟶ A.X := A.one
r : R
a : (fun x => ↑A.X) r
⊢ AddHom.toFun A.one.toAddHom r * a = a * AddHom.toFun A.one.toAddHom r
[PROOFSTEP]
have h₁ := LinearMap.congr_fun A.one_mul (r ⊗ₜ a)
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : MonoidalCategory.tensorUnit (ModuleCat R) ⟶ A.X := A.one
r : R
a : (fun x => ↑A.X) r
h₁ :
↑(CategoryTheory.MonoidalCategory.tensorHom A.one (𝟙 A.X) ≫ A.mul) (r ⊗ₜ[R] a) =
↑(CategoryTheory.MonoidalCategory.leftUnitor A.X).hom (r ⊗ₜ[R] a)
⊢ AddHom.toFun A.one.toAddHom r * a = a * AddHom.toFun A.one.toAddHom r
[PROOFSTEP]
have h₂ := LinearMap.congr_fun A.mul_one (a ⊗ₜ r)
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
src✝ : MonoidalCategory.tensorUnit (ModuleCat R) ⟶ A.X := A.one
r : R
a : (fun x => ↑A.X) r
h₁ :
↑(CategoryTheory.MonoidalCategory.tensorHom A.one (𝟙 A.X) ≫ A.mul) (r ⊗ₜ[R] a) =
↑(CategoryTheory.MonoidalCategory.leftUnitor A.X).hom (r ⊗ₜ[R] a)
h₂ :
↑(CategoryTheory.MonoidalCategory.tensorHom (𝟙 A.X) A.one ≫ A.mul) (a ⊗ₜ[R] r) =
↑(CategoryTheory.MonoidalCategory.rightUnitor A.X).hom (a ⊗ₜ[R] r)
⊢ AddHom.toFun A.one.toAddHom r * a = a * AddHom.toFun A.one.toAddHom r
[PROOFSTEP]
exact h₁.trans h₂.symm
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
⊢ CategoryTheory.MonoidalCategory.tensorHom (Algebra.linearMap R ↑A) (𝟙 (of R ↑A)) ≫ mul' R ↑A =
(CategoryTheory.MonoidalCategory.leftUnitor (of R ↑A)).hom
[PROOFSTEP]
refine TensorProduct.ext <| LinearMap.ext_ring <| LinearMap.ext fun x => ?_
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x : ↑(of R ↑A)
⊢ ↑(↑(compr₂ (TensorProduct.mk R ↑(MonoidalCategory.tensorUnit (ModuleCat R)) ↑(of R ↑A))
(CategoryTheory.MonoidalCategory.tensorHom (Algebra.linearMap R ↑A) (𝟙 (of R ↑A)) ≫ mul' R ↑A))
1)
x =
↑(↑(compr₂ (TensorProduct.mk R ↑(MonoidalCategory.tensorUnit (ModuleCat R)) ↑(of R ↑A))
(CategoryTheory.MonoidalCategory.leftUnitor (of R ↑A)).hom)
1)
x
[PROOFSTEP]
rw [compr₂_apply, compr₂_apply, CategoryTheory.comp_apply]
-- Porting note : this `dsimp` does nothing
-- dsimp [AlgebraCat.id_apply, TensorProduct.mk_apply, Algebra.linearMap_apply,
-- LinearMap.compr₂_apply, Function.comp_apply, RingHom.map_one,
-- ModuleCat.MonoidalCategory.hom_apply, AlgebraCat.coe_comp,
-- ModuleCat.MonoidalCategory.leftUnitor_hom_apply]
-- Porting note : because `dsimp` is not effective, `rw` needs to be changed to `erw`
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x : ↑(of R ↑A)
⊢ ↑(mul' R ↑A)
(↑(CategoryTheory.MonoidalCategory.tensorHom (Algebra.linearMap R ↑A) (𝟙 (of R ↑A)))
(↑(↑(TensorProduct.mk R ↑(MonoidalCategory.tensorUnit (ModuleCat R)) ↑(of R ↑A)) 1) x)) =
↑(CategoryTheory.MonoidalCategory.leftUnitor (of R ↑A)).hom
(↑(↑(TensorProduct.mk R ↑(MonoidalCategory.tensorUnit (ModuleCat R)) ↑(of R ↑A)) 1) x)
[PROOFSTEP]
erw [LinearMap.mul'_apply, MonoidalCategory.leftUnitor_hom_apply, ← Algebra.smul_def]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x : ↑(of R ↑A)
⊢ (1, x).fst • ↑(𝟙 (of R ↑A)) (1, x).snd = 1 • x
[PROOFSTEP]
rw [id_apply]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
⊢ CategoryTheory.MonoidalCategory.tensorHom (𝟙 (of R ↑A)) (Algebra.linearMap R ↑A) ≫ mul' R ↑A =
(CategoryTheory.MonoidalCategory.rightUnitor (of R ↑A)).hom
[PROOFSTEP]
refine
TensorProduct.ext <|
LinearMap.ext fun x =>
LinearMap.ext_ring
?_
-- Porting note : this `dsimp` does nothing
-- dsimp only [AlgebraCat.id_apply, TensorProduct.mk_apply, Algebra.linearMap_apply,
-- LinearMap.compr₂_apply, Function.comp_apply, ModuleCat.MonoidalCategory.hom_apply,
-- AlgebraCat.coe_comp]
-- Porting note : because `dsimp` is not effective, `rw` needs to be changed to `erw`
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x : ↑(of R ↑A)
⊢ ↑(↑(compr₂ (TensorProduct.mk R ↑(of R ↑A) ↑(MonoidalCategory.tensorUnit (ModuleCat R)))
(CategoryTheory.MonoidalCategory.tensorHom (𝟙 (of R ↑A)) (Algebra.linearMap R ↑A) ≫ mul' R ↑A))
x)
1 =
↑(↑(compr₂ (TensorProduct.mk R ↑(of R ↑A) ↑(MonoidalCategory.tensorUnit (ModuleCat R)))
(CategoryTheory.MonoidalCategory.rightUnitor (of R ↑A)).hom)
x)
1
[PROOFSTEP]
erw [compr₂_apply, compr₂_apply]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x : ↑(of R ↑A)
⊢ ↑(CategoryTheory.MonoidalCategory.tensorHom (𝟙 (of R ↑A)) (Algebra.linearMap R ↑A) ≫ mul' R ↑A)
(↑(↑(TensorProduct.mk R ↑(of R ↑A) ↑(MonoidalCategory.tensorUnit (ModuleCat R))) x) 1) =
↑(CategoryTheory.MonoidalCategory.rightUnitor (of R ↑A)).hom
(↑(↑(TensorProduct.mk R ↑(of R ↑A) ↑(MonoidalCategory.tensorUnit (ModuleCat R))) x) 1)
[PROOFSTEP]
rw [CategoryTheory.comp_apply]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x : ↑(of R ↑A)
⊢ ↑(mul' R ↑A)
(↑(CategoryTheory.MonoidalCategory.tensorHom (𝟙 (of R ↑A)) (Algebra.linearMap R ↑A))
(↑(↑(TensorProduct.mk R ↑(of R ↑A) ↑(MonoidalCategory.tensorUnit (ModuleCat R))) x) 1)) =
↑(CategoryTheory.MonoidalCategory.rightUnitor (of R ↑A)).hom
(↑(↑(TensorProduct.mk R ↑(of R ↑A) ↑(MonoidalCategory.tensorUnit (ModuleCat R))) x) 1)
[PROOFSTEP]
erw [LinearMap.mul'_apply, ModuleCat.MonoidalCategory.rightUnitor_hom_apply, ← Algebra.commutes, ← Algebra.smul_def]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x : ↑(of R ↑A)
⊢ (x, 1).snd • ↑(𝟙 (of R ↑A)) (x, 1).fst = 1 • x
[PROOFSTEP]
rw [id_apply]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
⊢ CategoryTheory.MonoidalCategory.tensorHom (mul' R ↑A) (𝟙 (of R ↑A)) ≫ mul' R ↑A =
(CategoryTheory.MonoidalCategory.associator (of R ↑A) (of R ↑A) (of R ↑A)).hom ≫
CategoryTheory.MonoidalCategory.tensorHom (𝟙 (of R ↑A)) (mul' R ↑A) ≫ mul' R ↑A
[PROOFSTEP]
refine
TensorProduct.ext <|
TensorProduct.ext <|
LinearMap.ext fun x =>
LinearMap.ext fun y =>
LinearMap.ext fun z =>
?_
-- Porting note : this `dsimp` does nothing
-- dsimp only [AlgebraCat.id_apply, TensorProduct.mk_apply, LinearMap.compr₂_apply,
-- Function.comp_apply, ModuleCat.MonoidalCategory.hom_apply, AlgebraCat.coe_comp,
-- MonoidalCategory.associator_hom_apply]
-- Porting note : because `dsimp` is not effective, `rw` needs to be changed to `erw`
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x y z : ↑(of R ↑A)
⊢ ↑(↑(↑(compr₂ (TensorProduct.mk R ↑(of R ↑A) ↑(of R ↑A))
(compr₂
(TensorProduct.mk R ↑(CategoryTheory.MonoidalCategory.tensorObj (of R ↑A) (of R ↑A)) ↑(of R ↑A))
(CategoryTheory.MonoidalCategory.tensorHom (mul' R ↑A) (𝟙 (of R ↑A)) ≫ mul' R ↑A)))
x)
y)
z =
↑(↑(↑(compr₂ (TensorProduct.mk R ↑(of R ↑A) ↑(of R ↑A))
(compr₂
(TensorProduct.mk R ↑(CategoryTheory.MonoidalCategory.tensorObj (of R ↑A) (of R ↑A)) ↑(of R ↑A))
((CategoryTheory.MonoidalCategory.associator (of R ↑A) (of R ↑A) (of R ↑A)).hom ≫
CategoryTheory.MonoidalCategory.tensorHom (𝟙 (of R ↑A)) (mul' R ↑A) ≫ mul' R ↑A)))
x)
y)
z
[PROOFSTEP]
rw [compr₂_apply, compr₂_apply, compr₂_apply, compr₂_apply, CategoryTheory.comp_apply, CategoryTheory.comp_apply,
CategoryTheory.comp_apply]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x y z : ↑(of R ↑A)
⊢ ↑(mul' R ↑A)
(↑(CategoryTheory.MonoidalCategory.tensorHom (mul' R ↑A) (𝟙 (of R ↑A)))
(↑(↑(TensorProduct.mk R ↑(CategoryTheory.MonoidalCategory.tensorObj (of R ↑A) (of R ↑A)) ↑(of R ↑A))
(↑(↑(TensorProduct.mk R ↑(of R ↑A) ↑(of R ↑A)) x) y))
z)) =
↑(mul' R ↑A)
(↑(CategoryTheory.MonoidalCategory.tensorHom (𝟙 (of R ↑A)) (mul' R ↑A))
(↑(CategoryTheory.MonoidalCategory.associator (of R ↑A) (of R ↑A) (of R ↑A)).hom
(↑(↑(TensorProduct.mk R ↑(CategoryTheory.MonoidalCategory.tensorObj (of R ↑A) (of R ↑A)) ↑(of R ↑A))
(↑(↑(TensorProduct.mk R ↑(of R ↑A) ↑(of R ↑A)) x) y))
z)))
[PROOFSTEP]
erw [LinearMap.mul'_apply, LinearMap.mul'_apply]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x y z : ↑(of R ↑A)
⊢ x * y * ↑(𝟙 (of R ↑A)) (↑(↑(TensorProduct.mk R ↑(of R ↑A) ↑(of R ↑A)) x) y, z).snd =
↑(mul' R ↑A)
(↑(CategoryTheory.MonoidalCategory.tensorHom (𝟙 (of R ↑A)) (mul' R ↑A))
(↑(CategoryTheory.MonoidalCategory.associator (of R ↑A) (of R ↑A) (of R ↑A)).hom
(↑(↑(TensorProduct.mk R ↑(CategoryTheory.MonoidalCategory.tensorObj (of R ↑A) (of R ↑A)) ↑(of R ↑A))
(↑(↑(TensorProduct.mk R ↑(of R ↑A) ↑(of R ↑A)) x) y))
z)))
[PROOFSTEP]
rw [id_apply, TensorProduct.mk_apply]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x y z : ↑(of R ↑A)
⊢ x * y * (x ⊗ₜ[R] y, z).snd =
↑(mul' R ↑A)
(↑(CategoryTheory.MonoidalCategory.tensorHom (𝟙 (of R ↑A)) (mul' R ↑A))
(↑(CategoryTheory.MonoidalCategory.associator (of R ↑A) (of R ↑A) (of R ↑A)).hom
(↑(↑(TensorProduct.mk R ↑(CategoryTheory.MonoidalCategory.tensorObj (of R ↑A) (of R ↑A)) ↑(of R ↑A))
(x ⊗ₜ[R] y))
z)))
[PROOFSTEP]
erw [TensorProduct.mk_apply, TensorProduct.mk_apply, id_apply, LinearMap.mul'_apply, LinearMap.mul'_apply]
[GOAL]
R : Type u
inst✝ : CommRing R
A : AlgebraCat R
x y z : ↑(of R ↑A)
⊢ x * y * (x ⊗ₜ[R] y, z).snd = ((x, y).fst, (x, y).snd ⊗ₜ[R] (x ⊗ₜ[R] y, z).snd).fst * ((x, y).snd * (x ⊗ₜ[R] y, z).snd)
[PROOFSTEP]
simp only [LinearMap.mul'_apply, mul_assoc]
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ ((𝟭 (Mon_ (ModuleCat R))).obj A).one ≫
{
toAddHom :=
{ toFun := _root_.id,
map_add' := (_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } =
((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).one
[PROOFSTEP]
ext
[GOAL]
case h
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
x✝ : ↑(MonoidalCategory.tensorUnit (ModuleCat R))
⊢ ↑(((𝟭 (Mon_ (ModuleCat R))).obj A).one ≫
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) })
x✝ =
↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).one x✝
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ ((𝟭 (Mon_ (ModuleCat R))).obj A).mul ≫
{
toAddHom :=
{ toFun := _root_.id,
map_add' := (_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } =
CategoryTheory.MonoidalCategory.tensorHom
{
toAddHom :=
{ toFun := _root_.id,
map_add' := (_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }
{
toAddHom :=
{ toFun := _root_.id,
map_add' := (_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } ≫
((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).mul
[PROOFSTEP]
refine TensorProduct.ext ?_
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ compr₂ (TensorProduct.mk R ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X)
(((𝟭 (Mon_ (ModuleCat R))).obj A).mul ≫
{
toAddHom :=
{ toFun := _root_.id,
map_add' := (_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }) =
compr₂ (TensorProduct.mk R ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X)
(CategoryTheory.MonoidalCategory.tensorHom
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } ≫
((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).mul)
[PROOFSTEP]
dsimp at *
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ compr₂ (TensorProduct.mk R ↑A.X ↑A.X)
(A.mul ≫
{ toAddHom := { toFun := _root_.id, map_add' := (_ : ∀ (x y : ↑A.X), x + y = x + y) },
map_smul' := (_ : ∀ (r : R) (a : ↑A.X), r • a = r • a) }) =
compr₂ (TensorProduct.mk R ↑A.X ↑A.X)
(CategoryTheory.MonoidalCategory.tensorHom
{ toAddHom := { toFun := _root_.id, map_add' := (_ : ∀ (x y : ↑A.X), x + y = x + y) },
map_smul' := (_ : ∀ (r : R) (a : ↑A.X), r • a = r • a) }
{ toAddHom := { toFun := _root_.id, map_add' := (_ : ∀ (x y : ↑A.X), x + y = x + y) },
map_smul' := (_ : ∀ (r : R) (a : ↑A.X), r • a = r • a) } ≫
mul' R ↑A.X)
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ ((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).one ≫
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } =
((𝟭 (Mon_ (ModuleCat R))).obj A).one
[PROOFSTEP]
ext
[GOAL]
case h
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
x✝ : ↑(MonoidalCategory.tensorUnit (ModuleCat R))
⊢ ↑(((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).one ≫
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) })
x✝ =
↑((𝟭 (Mon_ (ModuleCat R))).obj A).one x✝
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ ((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).mul ≫
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } =
CategoryTheory.MonoidalCategory.tensorHom
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } ≫
((𝟭 (Mon_ (ModuleCat R))).obj A).mul
[PROOFSTEP]
refine TensorProduct.ext ?_
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ compr₂
(TensorProduct.mk R ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X
↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X)
(((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).mul ≫
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }) =
compr₂
(TensorProduct.mk R ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X
↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X)
(CategoryTheory.MonoidalCategory.tensorHom
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } ≫
((𝟭 (Mon_ (ModuleCat R))).obj A).mul)
[PROOFSTEP]
dsimp at *
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ compr₂ (TensorProduct.mk R ↑(of R ↑A.X) ↑(of R ↑A.X))
(mul' R ↑A.X ≫
{ toAddHom := { toFun := _root_.id, map_add' := (_ : ∀ (x y : ↑(of R ↑A.X)), x + y = x + y) },
map_smul' := (_ : ∀ (r : R) (a : ↑(of R ↑A.X)), r • a = r • a) }) =
compr₂ (TensorProduct.mk R ↑(of R ↑A.X) ↑(of R ↑A.X))
(CategoryTheory.MonoidalCategory.tensorHom
{ toAddHom := { toFun := _root_.id, map_add' := (_ : ∀ (x y : ↑(of R ↑A.X)), x + y = x + y) },
map_smul' := (_ : ∀ (r : R) (a : ↑(of R ↑A.X)), r • a = r • a) }
{ toAddHom := { toFun := _root_.id, map_add' := (_ : ∀ (x y : ↑(of R ↑A.X)), x + y = x + y) },
map_smul' := (_ : ∀ (r : R) (a : ↑(of R ↑A.X)), r • a = r • a) } ≫
A.mul)
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' := (_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } ≫
Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } =
𝟙 ((𝟭 (Mon_ (ModuleCat R))).obj A)
[PROOFSTEP]
ext
[GOAL]
case w.h
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
x✝ : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X
⊢ ↑(Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } ≫
Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }).hom
x✝ =
↑(𝟙 ((𝟭 (Mon_ (ModuleCat R))).obj A)).hom x✝
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
⊢ Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } ≫
Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' := (_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } =
𝟙 ((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A)
[PROOFSTEP]
ext
[GOAL]
case w.h
R : Type u
inst✝ : CommRing R
A : Mon_ (ModuleCat R)
x✝ : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X
⊢ ↑(Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) } ≫
Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }).hom
x✝ =
↑(𝟙 ((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A)).hom x✝
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : CommRing R
⊢ ∀ {X Y : Mon_ (ModuleCat R)} (f : X ⟶ Y),
(𝟭 (Mon_ (ModuleCat R))).map f ≫
((fun A =>
Iso.mk
(Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) })
(Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }))
Y).hom =
((fun A =>
Iso.mk
(Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (Mon_ (ModuleCat R))).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) })
(Mon_.Hom.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (r : R) (a : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ MonModuleEquivalenceAlgebra.inverse).obj A).X),
_root_.id (x + y) = _root_.id (x + y)) }
(r • a)) }))
X).hom ≫
(functor ⋙ MonModuleEquivalenceAlgebra.inverse).map f
[PROOFSTEP]
aesop_cat
[GOAL]
R : Type u
inst✝ : CommRing R
⊢ ∀ {X Y : AlgebraCat R} (f : X ⟶ Y),
(MonModuleEquivalenceAlgebra.inverse ⋙ functor).map f ≫
((fun A =>
Iso.mk
{
toRingHom :=
{
toMonoidHom :=
{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) },
commutes' :=
(_ :
∀ (r : R),
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) })
(↑(_root_.algebraMap R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) r) =
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) })
(↑(_root_.algebraMap R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) r)) }
{
toRingHom :=
{
toMonoidHom :=
{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) },
commutes' :=
(_ :
∀ (r : R),
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) })
(↑(_root_.algebraMap R ↑((𝟭 (AlgebraCat R)).obj A)) r) =
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) })
(↑(_root_.algebraMap R ↑((𝟭 (AlgebraCat R)).obj A)) r)) })
Y).hom =
((fun A =>
Iso.mk
{
toRingHom :=
{
toMonoidHom :=
{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) },
commutes' :=
(_ :
∀ (r : R),
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) })
(↑(_root_.algebraMap R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) r) =
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) })
(↑(_root_.algebraMap R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) r)) }
{
toRingHom :=
{
toMonoidHom :=
{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) },
commutes' :=
(_ :
∀ (r : R),
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) })
(↑(_root_.algebraMap R ↑((𝟭 (AlgebraCat R)).obj A)) r) =
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) })
(↑(_root_.algebraMap R ↑((𝟭 (AlgebraCat R)).obj A)) r)) })
X).hom ≫
(𝟭 (AlgebraCat R)).map f
[PROOFSTEP]
intros
[GOAL]
R : Type u
inst✝ : CommRing R
X✝ Y✝ : AlgebraCat R
f✝ : X✝ ⟶ Y✝
⊢ (MonModuleEquivalenceAlgebra.inverse ⋙ functor).map f✝ ≫
((fun A =>
Iso.mk
{
toRingHom :=
{
toMonoidHom :=
{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) = x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
(x + y)) },
commutes' :=
(_ :
∀ (r : R),
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) })
(↑(_root_.algebraMap R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) r) =
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) })
(↑(_root_.algebraMap R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) r)) }
{
toRingHom :=
{
toMonoidHom :=
{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) },
commutes' :=
(_ :
∀ (r : R),
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) })
(↑(_root_.algebraMap R ↑((𝟭 (AlgebraCat R)).obj A)) r) =
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) })
(↑(_root_.algebraMap R ↑((𝟭 (AlgebraCat R)).obj A)) r)) })
Y✝).hom =
((fun A =>
Iso.mk
{
toRingHom :=
{
toMonoidHom :=
{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) = x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) (x ⊗ₜ[R] y) =
x * y) })
(x + y)) },
commutes' :=
(_ :
∀ (r : R),
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) })
(↑(_root_.algebraMap R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) r) =
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
0),
map_add' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : ↑(_root_.algebraMap R ↑A) 1 = 1) },
map_mul' :=
(_ :
∀ (x y : ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)),
↑(mul' R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A))
(x ⊗ₜ[R] y) =
x * y) })
(x + y)) })
(↑(_root_.algebraMap R ↑((MonModuleEquivalenceAlgebra.inverse ⋙ functor).obj A)) r)) }
{
toRingHom :=
{
toMonoidHom :=
{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{ toOneHom := { toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) },
commutes' :=
(_ :
∀ (r : R),
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) })
(↑(_root_.algebraMap R ↑((𝟭 (AlgebraCat R)).obj A)) r) =
OneHom.toFun
(↑↑{
toMonoidHom :=
{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) },
map_zero' :=
(_ :
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0 =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id, map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
0),
map_add' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y) =
OneHom.toFun
(↑{
toOneHom :=
{ toFun := _root_.id,
map_one' := (_ : 1 = ↑(_root_.algebraMap R ↑A) 1) },
map_mul' :=
(_ :
∀ (x y : ↑((𝟭 (AlgebraCat R)).obj A)),
x * y = ↑(mul' R ↑((𝟭 (AlgebraCat R)).obj A)) (x ⊗ₜ[R] y)) })
(x + y)) })
(↑(_root_.algebraMap R ↑((𝟭 (AlgebraCat R)).obj A)) r)) })
X✝).hom ≫
(𝟭 (AlgebraCat R)).map f✝
[PROOFSTEP]
rfl
[GOAL]
R : Type u
inst✝ : CommRing R
⊢ ∀ {X Y : Mon_ (ModuleCat R)} (f : X ⟶ Y),
(functor ⋙ forget₂ (AlgebraCat R) (ModuleCat R)).map f ≫
((fun A =>
Iso.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ forget₂ (AlgebraCat R) (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (c : R) (x : ↑((functor ⋙ forget₂ (AlgebraCat R) (ModuleCat R)).obj A)),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ forget₂ (AlgebraCat R) (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) }
(c • x) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ forget₂ (AlgebraCat R) (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) }
(c • x)) }
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((Mon_.forget (ModuleCat R)).obj A)), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (c : R) (x : ↑((Mon_.forget (ModuleCat R)).obj A)),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((Mon_.forget (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) }
(c • x) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((Mon_.forget (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) }
(c • x)) })
Y).hom =
((fun A =>
Iso.mk
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ forget₂ (AlgebraCat R) (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (c : R) (x : ↑((functor ⋙ forget₂ (AlgebraCat R) (ModuleCat R)).obj A)),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ forget₂ (AlgebraCat R) (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) }
(c • x) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((functor ⋙ forget₂ (AlgebraCat R) (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) }
(c • x)) }
{
toAddHom :=
{ toFun := _root_.id,
map_add' :=
(_ : ∀ (x y : ↑((Mon_.forget (ModuleCat R)).obj A)), _root_.id (x + y) = _root_.id (x + y)) },
map_smul' :=
(_ :
∀ (c : R) (x : ↑((Mon_.forget (ModuleCat R)).obj A)),
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((Mon_.forget (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) }
(c • x) =
AddHom.toFun
{ toFun := _root_.id,
map_add' :=
(_ :
∀ (x y : ↑((Mon_.forget (ModuleCat R)).obj A)),
_root_.id (x + y) = _root_.id (x + y)) }
(c • x)) })
X).hom ≫
(Mon_.forget (ModuleCat R)).map f
[PROOFSTEP]
aesop_cat
|
(* This file is generated by Why3's Coq driver *)
(* Beware! Only edit allowed sections below *)
Require Import BuiltIn.
Require BuiltIn.
Require int.Int.
Require int.Abs.
Require int.ComputerDivision.
Require option.Option.
Require list.List.
Require list.Mem.
Require map.Map.
(* Why3 assumption *)
Definition unit := unit.
Axiom qtmark : Type.
Parameter qtmark_WhyType : WhyType qtmark.
Existing Instance qtmark_WhyType.
(* Why3 assumption *)
Inductive array (a:Type) :=
| mk_array : Z -> (map.Map.map Z a) -> array a.
Axiom array_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (array a).
Existing Instance array_WhyType.
Implicit Arguments mk_array [[a]].
(* Why3 assumption *)
Definition elts {a:Type} {a_WT:WhyType a} (v:(array a)): (map.Map.map Z a) :=
match v with
| (mk_array x x1) => x1
end.
(* Why3 assumption *)
Definition length {a:Type} {a_WT:WhyType a} (v:(array a)): Z :=
match v with
| (mk_array x x1) => x
end.
(* Why3 assumption *)
Definition get {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z): a :=
(map.Map.get (elts a1) i).
(* Why3 assumption *)
Definition set {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z) (v:a): (array
a) := (mk_array (length a1) (map.Map.set (elts a1) i v)).
(* Why3 assumption *)
Definition make {a:Type} {a_WT:WhyType a} (n:Z) (v:a): (array a) :=
(mk_array n (map.Map.const v: (map.Map.map Z a))).
Axiom key : Type.
Parameter key_WhyType : WhyType key.
Existing Instance key_WhyType.
Parameter hash: key -> Z.
Axiom hash_nonneg : forall (k:key), (0%Z <= (hash k))%Z.
(* Why3 assumption *)
Definition bucket (k:key) (n:Z): Z := (ZArith.BinInt.Z.rem (hash k) n).
Axiom bucket_bounds : forall (n:Z), (0%Z < n)%Z -> forall (k:key),
(0%Z <= (bucket k n))%Z /\ ((bucket k n) < n)%Z.
(* Why3 assumption *)
Definition in_data {a:Type} {a_WT:WhyType a} (k:key) (v:a) (d:(array
(list (key* a)%type))): Prop := (list.Mem.mem (k, v) (get d (bucket k
(length d)))).
(* Why3 assumption *)
Definition good_data {a:Type} {a_WT:WhyType a} (k:key) (v:a) (m:(map.Map.map
key (option a))) (d:(array (list (key* a)%type))): Prop := ((map.Map.get m
k) = (Init.Datatypes.Some v)) <-> (in_data k v d).
(* Why3 assumption *)
Definition good_hash {a:Type} {a_WT:WhyType a} (d:(array (list (key*
a)%type))) (i:Z): Prop := forall (k:key) (v:a), (list.Mem.mem (k, v) (get d
i)) -> ((bucket k (length d)) = i).
(* Why3 assumption *)
Inductive t
(a:Type) :=
| mk_t : Z -> (array (list (key* a)%type)) -> (map.Map.map key
(option a)) -> t a.
Axiom t_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (t a).
Existing Instance t_WhyType.
Implicit Arguments mk_t [[a]].
(* Why3 assumption *)
Definition view {a:Type} {a_WT:WhyType a} (v:(t a)): (map.Map.map key
(option a)) := match v with
| (mk_t x x1 x2) => x2
end.
(* Why3 assumption *)
Definition data {a:Type} {a_WT:WhyType a} (v:(t a)): (array (list (key*
a)%type)) := match v with
| (mk_t x x1 x2) => x1
end.
(* Why3 assumption *)
Definition size {a:Type} {a_WT:WhyType a} (v:(t a)): Z :=
match v with
| (mk_t x x1 x2) => x
end.
(* Why3 goal *)
Theorem WP_parameter_remove : forall {a:Type} {a_WT:WhyType a}, forall (h:Z)
(h1:(map.Map.map Z (list (key* a)%type))) (h2:(map.Map.map key (option a)))
(k:key), (((0%Z < h)%Z /\ ((forall (i:Z), ((0%Z <= i)%Z /\ (i < h)%Z) ->
(good_hash (mk_array h h1) i)) /\ forall (k1:key) (v:a), (good_data k1 v h2
(mk_array h h1)))) /\ (0%Z <= h)%Z) -> let i := (bucket k h) in
(((0%Z <= i)%Z /\ (i < h)%Z) -> let l := (map.Map.get h1 i) in
forall (result:(option a)),
match result with
| Init.Datatypes.None => forall (v:a), ~ (list.Mem.mem (k, v) l)
| (Init.Datatypes.Some v) => (list.Mem.mem (k, v) l)
end -> ((result = Init.Datatypes.None) -> ((map.Map.get h2
k) = Init.Datatypes.None))).
(* Why3 intros a a_WT h h1 h2 k ((h1,(h2,h3)),h4) i (h5,h6) l result h7 h8. *)
intros a a_WT rho rho1 rho2 k ((h1,(h2,h3)),h4) i (h5,h6) l result h7 h8.
subst i.
subst result.
subst l.
unfold good_data in h3.
generalize (h3 k); clear h3; intro h3.
destruct (Map.get rho2 k); intuition.
generalize (h3 a0); clear h3; intro h3.
generalize (h7 a0); clear h7; intro h7.
intuition.
Qed.
|
Arrangements have been made for a visit to the Dover CGOC at Langdon Battery, Swingate in the afternoon of Wednesday 3rd April. The visit, which is free, will commence promptly at 1430 and last at least 2 hours. There will be ample car parking is available on site however car sharing is desirable. Early booking is recommended, as places are limited to 30. Members will be restricted to bringing one guest.
For those who wish to meet up beforehand for lunch (1230 - 1400), places can be booked at a local pub (food payable at the venue). Please indicate whether or not you want to during the booking process. Confirmation as to the location of the lunch venue will be provided nearer the time of the visit, once numbers have been finalised.
Prior booking for this event and for lunch, if required, is essential. As part of the booking process, which is now open through the RIN website, members and their guests will be required to provide details of their nationality for security purposes.
|
/////////////////////////////////////////////////////////////////////
// = NMatrix
//
// A linear algebra library for scientific computation in Ruby.
// NMatrix is part of SciRuby.
//
// NMatrix was originally inspired by and derived from NArray, by
// Masahiro Tanaka: http://narray.rubyforge.org
//
// == Copyright Information
//
// SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation
// NMatrix is Copyright (c) 2012, Ruby Science Foundation
//
// Please see LICENSE.txt for additional copyright notices.
//
// == Contributing
//
// By contributing source code to SciRuby, you agree to be bound by
// our Contributor Agreement:
//
// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement
//
// == cblas.c
//
// Functions in this file allow us to call CBLAS functions using
// arrays of function pointers, by ensuring that each has the same
// signature.
#ifndef CBLAS_C
# define CBLAS_C
#include <cblas.h>
#include "nmatrix.h"
//extern const enum CBLAS_ORDER;
//extern const enum CBLAS_TRANSPOSE;
inline void cblas_r32gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
if (Order == CblasColMajor) r32gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.r[0], p.A, p.lda, p.B, p.ldb, p.beta.r[0], p.C, p.ldc);
else r32gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.r[0], p.B, p.ldb, p.A, p.lda, p.beta.r[0], p.C, p.ldc);
}
inline void cblas_r32gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
r32gemv(TransA, p.M, p.N, p.alpha.r[0], p.A, p.lda, p.B, p.ldb, p.beta.r[0], p.C, p.ldc);
}
inline void cblas_r64gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
if (Order == CblasColMajor) r64gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.ra[0], p.A, p.lda, p.B, p.ldb, p.beta.ra[0], p.C, p.ldc);
else r64gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.ra[0], p.B, p.ldb, p.A, p.lda, p.beta.ra[0], p.C, p.ldc);
}
inline void cblas_r64gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
r64gemv(TransA, p.M, p.N, p.alpha.ra[0], p.A, p.lda, p.B, p.ldb, p.beta.ra[0], p.C, p.ldc);
}
inline void cblas_r128gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
if (Order == CblasColMajor) r128gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.rat, p.A, p.lda, p.B, p.ldb, p.beta.rat, p.C, p.ldc);
else r128gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.rat, p.B, p.ldb, p.A, p.lda, p.beta.rat, p.C, p.ldc);
}
inline void cblas_r128gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
r128gemv(TransA, p.M, p.N, p.alpha.rat, p.A, p.lda, p.B, p.ldb, p.beta.rat, p.C, p.ldc);
}
inline void cblas_bgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
bgemv(TransA, p.M, p.N, p.alpha.b[0], p.A, p.lda, p.B, p.ldb, p.beta.b[0], p.C, p.ldc);
}
inline void cblas_bgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
if (Order == CblasColMajor) bgemm(TransA, TransB, p.M, p.N, p.K, p.alpha.b[0], p.A, p.lda, p.B, p.ldb, p.beta.b[0], p.C, p.ldc);
else bgemm(TransB, TransA, p.N, p.M, p.K, p.alpha.b[0], p.B, p.ldb, p.A, p.lda, p.beta.b[0], p.C, p.ldc);
}
inline void cblas_i8gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
i8gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);
}
inline void cblas_i8gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
if (Order == CblasColMajor) i8gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);
else i8gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc);
}
inline void cblas_i16gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
i16gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);
}
inline void cblas_i16gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
if (Order == CblasColMajor) i16gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);
else i16gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc);
}
inline void cblas_i32gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
i32gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);
}
inline void cblas_i32gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
if (Order == CblasColMajor) i32gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);
else i32gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc);
}
inline void cblas_i64gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
i64gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);
}
inline void cblas_i64gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
if (Order == CblasColMajor) i64gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);
else i64gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc);
}
inline void cblas_vgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
if (Order == CblasColMajor) vgemm(TransA, TransB, p.M, p.N, p.K, p.alpha.v[0], p.A, p.lda, p.B, p.ldb, p.beta.v[0], p.C, p.ldc);
else vgemm(TransB, TransA, p.N, p.M, p.K, p.alpha.v[0], p.B, p.ldb, p.A, p.lda, p.beta.v[0], p.C, p.ldc);
}
inline void cblas_sgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
cblas_sgemv(Order, TransA, p.M, p.N, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc);
}
inline void cblas_sgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
cblas_sgemm(Order, TransA, TransB, p.M, p.N, p.K, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc);
}
inline void cblas_dgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
cblas_dgemv(Order, TransA, p.M, p.N, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc);
}
inline void cblas_dgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
cblas_dgemm(Order, TransA, TransB, p.M, p.N, p.K, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc);
}
inline void cblas_cgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
cblas_cgemv(Order, TransA, p.M, p.N, &(p.alpha.c), p.A, p.lda, p.B, p.ldb, &(p.beta.c), p.C, p.ldc);
}
inline void cblas_cgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
cblas_cgemm(Order, TransA, TransB, p.M, p.N, p.K, &(p.alpha.c), p.A, p.lda, p.B, p.ldb, &(p.beta.c), p.C, p.ldc);
}
inline void cblas_zgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {
cblas_zgemv(Order, TransA, p.M, p.N, &(p.alpha.z), p.A, p.lda, p.B, p.ldb, &(p.beta.z), p.C, p.ldc);
}
inline void cblas_zgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {
cblas_zgemm(Order, TransA, TransB, p.M, p.N, p.K, &(p.alpha.z), p.A, p.lda, p.B, p.ldb, &(p.beta.z), p.C, p.ldc);
}
#endif
|
import
tactic.induction
tactic.linarith
..semantics
..syntax
open instruction exp val bin_op big_step vm_big_step
lemma example1 :
vm_big_step
([],
[IPush (VNat 10),
IPush (VNat 20),
IOp EqOp,
IBranch 1,
IPush (VNat 1),
IPush (VNat 2),
IPush (VNat 3)],
[])
[VNat 3, VNat 2] :=
begin
repeat { apply RunPush },
apply RunOpInstr,
rw [eval],
apply RunFBranch,
{ rw [at_least, list.length],
apply nat.le_add_left },
repeat { rw [list.drop]},
repeat { apply RunPush },
exact RunEmpty
end
lemma example2 : ¬ ∃ out,
vm_big_step
([], [IPush (VNat 10), IPush (VBool false), IOp EqOp], []) out :=
begin
assume hexists,
cases' hexists,
repeat { cases' h }
end
lemma example3 :
([],
[IPush (VBool false),
IBranch 1,
IBranch 10,
IPush (VNat 2),
IJump 1,
IPush (VNat 2),
IPush (VNat 3),
IOp PlusOp], [])
⟹ᵥₘ [VNat 5] :=
begin
apply RunPush,
apply RunFBranch,
{ rw [at_least, list.length],
linarith },
{ repeat { rw [list.drop] },
apply RunPush,
apply RunJump,
{ rw [at_least, list.length], linarith },
{ repeat { rw [list.drop] },
apply RunPush,
apply RunOpInstr,
exact RunEmpty
}
}
end
lemma example4 :
∀ n, n ≠ 0 →
¬ ∃ out, ([], [IBranch n], [VBool false]) ⟹ᵥₘ out :=
begin
assume n hnz hex,
cases hex with hout hstep,
cases hstep; rename hstep__x → hleast,
cases hleast,
contradiction
end
lemma unbound_var_no_out :
∀ x, ¬ ∃ out, EVar x ⟹ out :=
begin
assume x,
assume hex,
cases hex with hval hstep,
cases hstep
end
lemma test_name_shadow :
ELet "x" (ELet "x" (EVal (VNat 1))
(EOp PlusOp (EVar "x") (EVal (VNat 2))))
(ELet "x" (EVal (VNat 0))
(EOp EqOp (EVar "x") (EVal (VNat 0)))) ⟹ VBool true :=
begin
apply RunLet,
{ apply RunLet,
{ apply RunVal },
{ repeat {rw subst},
apply RunOp,
simp,
exact RunVal,
exact RunVal } },
{ repeat {rw subst},
simp,
apply RunLet,
repeat {apply RunVal},
repeat {rw subst},
simp,
have heq : VBool tt = eval 0 0 EqOp := by refl,
rw heq,
apply RunOp,
exact RunVal,
exact RunVal
}
end
lemma test_ext :
([],
[IPush (VNat 0),
IPush (VNat 1),
IOpenScope "x",
IOpenScope "y",
IPush (VNat 2),
ILookup "x",
ICloseScope,
IOp PlusOp], []) ⟹ᵥₘ [VNat 3] :=
begin
apply RunPush,
apply RunPush,
apply RunOpenScope,
apply RunOpenScope,
apply RunPush,
apply RunLookup,
{ apply bound.btail,
finish,
apply bound.bhead },
apply RunCloseScope,
have h : VNat 3 = eval 1 2 PlusOp := by refl,
rw h,
apply RunOpInstr,
exact RunEmpty
end
|
from typing import Iterable
from itertools import chain, compress
import numpy as np
from models.identifier import Identifier
from models.classifier import Classifier
from lib import trace, matching
from utils.nms import nms
from utils.kalmanfilter import KalmanFilter
class Tracker(object):
def __init__(self,
min_score: float = .2, min_dist: float = .64, max_lost: int = 120,
use_tracking: bool = True, use_refind: bool = True):
self.min_score = min_score
self.min_dist = min_dist
self.max_lost = max_lost
self.use_tracking = use_tracking
self.use_refind = use_refind
self.tracked = []
self.lost = []
self.removed = []
self.motion = KalmanFilter()
self.identifier = Identifier().load()
self.classifier = Classifier().load()
self.frame = 0
def update(self, image: np.ndarray, boxes: np.ndarray, scores: np.ndarray) \
-> Iterable[trace.Trace]:
self.frame += 1
refind, lost = [], []
activated, removed = [], []
# Step 1. Prediction
for track in chain(self.tracked, self.lost):
track.predict()
# Step 2. Selection by score
if scores is None:
scores = np.ones(np.size(boxes, 0), dtype=float)
detections = list(chain(
map(lambda t: trace.Trace(*t, from_det=True), zip(boxes, scores)),
map(lambda t: trace.Trace(*t, from_det=False), zip(boxes, scores))
))
self.classifier.update(image)
detections.extend(map(lambda t: trace.Trace(t.tracking(image), t.track_score, from_det=True),
filter(lambda t: t.is_activated, chain(self.tracked, self.lost))))
rois = np.asarray(list(map(lambda t: t.to_tlbr, detections)), np.float32)
class_scores = self.classifier.predict(rois)
scores = np.concatenate([
np.ones(np.size(boxes, 0), dtype=np.float32),
np.fromiter(map(lambda t: t.score, detections[np.size(boxes, 0):]), dtype=np.float32)
]) * class_scores
# Non-maxima suppression
if len(detections) > 0:
mask = np.zeros(np.size(rois, 0), dtype=np.bool)
mask[list(nms(rois, scores.reshape(-1), threshold=.4))] = True
indices = np.zeros_like(detections, dtype=np.bool)
indices[np.where(mask & (scores >= self.min_score))] = True
detections = list(compress(detections, indices))
scores = scores[indices]
for detection, score in zip(detections, scores):
detection.score = score
predictions = list(filter(lambda t: not t.from_det, detections))
detections = list(filter(lambda t: t.from_det, detections))
# set features
features = self.identifier.extract(image, np.asarray(
list(map(lambda t: t.to_tlbr, detections)), dtype=np.float32)
)
for idx, detection in enumerate(detections):
detection.feature = features[idx]
# Step3. Association for tracked
# matching for tracked target
unconfirmed = list(filter(lambda t: not t.is_activated, self.tracked))
tracked = list(filter(lambda t: t.is_activated, self.tracked))
distance = matching.nearest_distance(tracked, detections, metric='euclidean')
cost = matching.gate_cost(self.motion, distance, tracked, detections)
matches, u_track, u_detection = matching.assignment(cost, threshold=self.min_dist)
for track, det in matches:
tracked[track].update(self.frame, image, detections[det])
# matching for missing targets
detections = list(map(lambda u: detections[u], u_detection))
distance = matching.nearest_distance(self.lost, detections, metric='euclidean')
cost = matching.gate_cost(self.motion, distance, self.lost, detections)
matches, u_lost, u_detection = matching.assignment(cost, threshold=self.min_dist)
for miss, det in matches:
self.lost[miss].reactivate(self.frame, image, detections[det], reassign=not self.use_refind)
refind.append(self.lost[miss])
# remaining tracked
matched_size = len(u_detection)
detections = list(map(lambda u: detections[u], u_detection)) + predictions
u_tracked = list(map(lambda u: tracked[u], u_track))
distance = matching.iou_distance(u_tracked, detections)
matches, u_track, u_detection = matching.assignment(distance, threshold=.8)
for track, det in matches:
u_tracked[track].update(self.frame, image, detections[det], update_feature=True)
for track in map(lambda u: u_tracked[u], u_track):
track.lost()
lost.append(track)
# unconfirmed
detections = list(map(lambda u: detections[u], filter(lambda u: u < matched_size, u_detection)))
distance = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.assignment(distance, threshold=.8)
for track, det in matches:
unconfirmed[track].update(self.frame, image, detections[det], update_feature=True)
for track in map(lambda u: unconfirmed[u], u_unconfirmed):
track.remove()
removed.append(track)
# Step 4. Init new trace
for track in filter(lambda t: t.from_det and t.score >= .6,
map(lambda u: detections[u], u_detection)):
track.activate(self.frame, image, self.motion)
activated.append(track)
# Step 5. Update state
for track in filter(lambda t: self.frame - t.frame > self.max_lost, self.lost):
track.remove()
removed.append(track)
self.tracked = list(chain(
filter(lambda t: t.state == trace.State.Tracked, self.tracked),
activated, refind,
))
self.lost = list(chain(
filter(lambda t: t.state == trace.State.Lost, self.lost),
lost
))
self.removed.extend(removed)
lost_score = self.classifier.predict(
np.asarray(list(map(lambda t: t.to_tlbr, self.lost)), dtype=np.float32)
)
return chain(
filter(lambda t: t.is_activated, self.tracked),
map(lambda it: it[1],
filter(lambda it: lost_score[it[0]] > .3 and self.frame - it[1].frame <= 4,
enumerate(self.lost)))
)
|
module IdrisJvm.System
import public Data.So
import IdrisJvm.IO
import Java.Util
import Java.Math
import Java.Lang
public export
getArgs : JVM_IO (List String)
getArgs = do
argsList <- invokeStatic RuntimeClass "getProgramArgs" (JVM_IO JList)
Iterator.toList !(JList.iterator argsList)
public export
time : JVM_IO Integer
time = believe_me <$> invokeStatic RuntimeClass "time" (JVM_IO BigInteger)
public export
getEnv : String -> JVM_IO (Maybe String)
getEnv = System.getenv
public export
system : String -> JVM_IO Int
system = invokeStatic RuntimeClass "runCommand" (String -> JVM_IO Int)
public export
usleep : (i : Int) -> { auto prf : So (i >= 0 && i <= 1000000) } -> JVM_IO ()
usleep interval = invokeStatic RuntimeClass "usleep" (Int -> JVM_IO ()) interval
public export
exit : Int -> JVM_IO a
exit = believe_me . Java.Lang.System.exit
|
= = = Reaction and R U Tuff Enuff = = =
|
(* Title: CIDR_Split.thy
Authors: Julius Michaelis, Cornelius Diekmann
*)
theory CIDR_Split
imports IP_Address
Prefix_Match
Hs_Compat
begin
section\<open>CIDR Split Motivation (Example for IPv4)\<close>
text\<open>When talking about ranges of IP addresses, we can make the ranges explicit by listing their elements.\<close>
context
begin
private lemma "map (of_nat \<circ> nat) [1 .. 4] = ([1, 2, 3, 4]:: 32 word list)" by eval
private definition ipv4addr_upto :: "32 word \<Rightarrow> 32 word \<Rightarrow> 32 word list" where
"ipv4addr_upto i j \<equiv> map (of_nat \<circ> nat) [int (unat i) .. int (unat j)]"
private lemma ipv4addr_upto: "set (ipv4addr_upto i j) = {i .. j}"
proof -
have int_interval_eq_image: "{int m..int n} = int ` {m..n}" for m n
by (auto intro!: image_eqI [of _ int "nat k" for k])
have helpX:"\<And>f (i::nat) (j::nat). (f \<circ> nat) ` {int i..int j} = f ` {i .. j}"
by (auto simp add: image_comp int_interval_eq_image)
have hlp: \<open>i \<le> word_of_nat (nat xa)\<close> \<open>word_of_nat (nat xa) \<le> j\<close>
if \<open>uint i \<le> xa\<close> \<open>xa \<le> uint j\<close> for xa :: int
proof -
from uint_nonnegative [of i] \<open>uint i \<le> xa\<close>
have \<open>0 \<le> xa\<close> by (rule order_trans)
moreover from \<open>xa \<le> uint j\<close> uint_bounded [of j]
have \<open>xa < 2 ^ 32\<close> by simp
ultimately have xa: \<open>take_bit 32 xa = xa\<close>
by (simp add: take_bit_int_eq_self)
from xa \<open>uint i \<le> xa\<close> show \<open>i \<le> word_of_nat (nat xa)\<close>
by transfer simp
from xa \<open>xa \<le> uint j\<close> show \<open>word_of_nat (nat xa) \<le> j\<close>
by transfer simp
qed
show ?thesis
unfolding ipv4addr_upto_def
apply (rule set_eqI)
apply (auto simp add: hlp)
apply (metis (mono_tags) atLeastAtMost_iff image_iff unat_eq_nat_uint word_less_eq_iff_unsigned word_unat.Rep_inverse)
done
qed
text\<open>The function @{const ipv4addr_upto} gives back a list of all the ips in the list.
This list can be pretty huge! In the following, we will use CIDR notation (e.g. 192.168.0.0/24)
to describe the list more compactly.\<close>
end
section\<open>CIDR Split\<close>
context
begin
private lemma find_SomeD: "find f x = Some y \<Longrightarrow> f y \<and> y \<in> set x"
by(induction x; simp split: if_splits)
(*pfxes needs a dummy parameter. The first parameter is a dummy that we have the 'a::len0 type and
can refer to its length.*)
private definition pfxes :: "'a::len0 itself \<Rightarrow> nat list" where
"pfxes _ = map nat [0..int(len_of TYPE ('a))]"
private lemma "pfxes TYPE(32) = map nat [0 .. 32]" by eval
private definition "largest_contained_prefix (a::('a :: len) word) r = (
let cs = (map (\<lambda>s. PrefixMatch a s) (pfxes TYPE('a)));
\<comment> \<open>anything that is a subset should also be a valid prefix. but try proving that.\<close>
cfs = find (\<lambda>s. valid_prefix s \<and> wordinterval_subset (prefix_to_wordinterval s) r) cs in
cfs)
"
(* The joke is that it is always Some, given that a \<in> r. *)
text\<open>Split off one prefix:\<close>
private definition wordinterval_CIDR_split1
:: "'a::len wordinterval \<Rightarrow> 'a prefix_match option \<times> 'a wordinterval" where
"wordinterval_CIDR_split1 r \<equiv> (
let ma = wordinterval_lowest_element r in
case ma of
None \<Rightarrow> (None, r) |
Some a \<Rightarrow> (case largest_contained_prefix a r of
None \<Rightarrow> (None, r) |
Some m \<Rightarrow> (Some m, wordinterval_setminus r (prefix_to_wordinterval m))))"
private lemma wordinterval_CIDR_split1_innard_helper: fixes a::"'a::len word"
shows "wordinterval_lowest_element r = Some a \<Longrightarrow>
largest_contained_prefix a r \<noteq> None"
proof -
assume a: "wordinterval_lowest_element r = Some a"
have b: "(a,len_of(TYPE('a))) \<in> set (map (Pair a) (pfxes TYPE('a)))"
unfolding pfxes_def set_map set_upto
using Set.image_iff atLeastAtMost_iff int_eq_iff order_refl by metis (*400ms*)
have c: "valid_prefix (PrefixMatch a (len_of(TYPE('a))))" by(simp add: valid_prefix_def pfxm_mask_def)
have "wordinterval_to_set (prefix_to_wordinterval (PrefixMatch a (len_of(TYPE('a))))) = {a}"
unfolding prefix_to_wordinterval_def pfxm_mask_def by simp
moreover have "a \<in> wordinterval_to_set r"
using a wordinterval_lowest_element_set_eq wordinterval_lowest_none_empty
by (metis is_lowest_element_def option.distinct(1))
ultimately have d:
"wordinterval_to_set (prefix_to_wordinterval (PrefixMatch a (LENGTH('a)))) \<subseteq> wordinterval_to_set r"
by simp
show ?thesis
unfolding largest_contained_prefix_def Let_def
using b c d by(auto simp add: find_None_iff)
qed
private lemma r_split1_not_none: fixes r:: "'a::len wordinterval"
shows "\<not> wordinterval_empty r \<Longrightarrow> fst (wordinterval_CIDR_split1 r) \<noteq> None"
unfolding wordinterval_CIDR_split1_def Let_def
by(cases "wordinterval_lowest_element r")
(auto simp add: wordinterval_lowest_none_empty
dest: wordinterval_CIDR_split1_innard_helper)
private lemma largest_contained_prefix_subset:
"largest_contained_prefix a r = Some p \<Longrightarrow> wordinterval_to_set (prefix_to_wordinterval p) \<subseteq> wordinterval_to_set r"
unfolding largest_contained_prefix_def Let_def
by(drule find_SomeD) simp
private lemma wordinterval_CIDR_split1_snd: "wordinterval_CIDR_split1 r = (Some s, u) \<Longrightarrow> u = wordinterval_setminus r (prefix_to_wordinterval s)"
unfolding wordinterval_CIDR_split1_def Let_def by(clarsimp split: option.splits)
private lemma largest_contained_prefix_subset_s1D:
"wordinterval_CIDR_split1 r = (Some s, u) \<Longrightarrow> wordinterval_to_set (prefix_to_wordinterval s) \<subseteq> wordinterval_to_set r"
by(intro largest_contained_prefix_subset[where a = "the (wordinterval_lowest_element r)"])
(simp add: wordinterval_CIDR_split1_def split: option.splits)
private theorem wordinterval_CIDR_split1_preserve: fixes r:: "'a::len wordinterval"
shows "wordinterval_CIDR_split1 r = (Some s, u) \<Longrightarrow> wordinterval_eq (wordinterval_union (prefix_to_wordinterval s) u) r"
proof(unfold wordinterval_eq_set_eq)
assume as: "wordinterval_CIDR_split1 r = (Some s, u)"
have ud: "u = wordinterval_setminus r (prefix_to_wordinterval s)"
using as[THEN wordinterval_CIDR_split1_snd] .
with largest_contained_prefix_subset_s1D[OF as]
show "wordinterval_to_set (wordinterval_union (prefix_to_wordinterval s) u) = wordinterval_to_set r"
unfolding ud by auto
qed
private lemma wordinterval_CIDR_split1_some_r_ne:
"wordinterval_CIDR_split1 r = (Some s, u) \<Longrightarrow> \<not> wordinterval_empty r"
proof(rule ccontr, goal_cases)
case 1
have "wordinterval_lowest_element r = None" unfolding wordinterval_lowest_none_empty using 1(2) unfolding not_not .
then have "wordinterval_CIDR_split1 r = (None, r)" unfolding wordinterval_CIDR_split1_def Let_def by simp
then show False using 1(1) by simp
qed
private lemma wordinterval_CIDR_split1_distinct: fixes r:: "'a::len wordinterval"
shows "wordinterval_CIDR_split1 r = (Some s, u) \<Longrightarrow>
wordinterval_empty (wordinterval_intersection (prefix_to_wordinterval s) u)"
proof(goal_cases)
case 1
have nn: "wordinterval_lowest_element r \<noteq> None"
using wordinterval_CIDR_split1_some_r_ne 1 wordinterval_lowest_none_empty by metis
from 1 have "u = wordinterval_setminus r (prefix_to_wordinterval s)"
by(elim wordinterval_CIDR_split1_snd)
then show ?thesis by simp
qed
private lemma wordinterval_CIDR_split1_distinct2: fixes r:: "'a::len wordinterval"
shows "wordinterval_CIDR_split1 r = (Some s, u) \<Longrightarrow>
wordinterval_empty (wordinterval_intersection (prefix_to_wordinterval s) u)"
by(rule wordinterval_CIDR_split1_distinct[where r = r]) simp
function wordinterval_CIDR_split_prefixmatch
:: "'a::len wordinterval \<Rightarrow> 'a prefix_match list" where
"wordinterval_CIDR_split_prefixmatch rs = (
if
\<not> wordinterval_empty rs
then case wordinterval_CIDR_split1 rs
of (Some s, u) \<Rightarrow> s # wordinterval_CIDR_split_prefixmatch u
| _ \<Rightarrow> []
else
[]
)"
by pat_completeness simp
termination wordinterval_CIDR_split_prefixmatch
proof(relation "measure (card \<circ> wordinterval_to_set)", rule wf_measure, unfold in_measure comp_def, goal_cases)
note vernichter = wordinterval_empty_set_eq wordinterval_intersection_set_eq wordinterval_union_set_eq wordinterval_eq_set_eq
case (1 rs x y x2)
note some = 1(2)[unfolded 1(3), symmetric]
from prefix_never_empty have "wordinterval_to_set (prefix_to_wordinterval x2) \<noteq> {}" unfolding vernichter .
thus ?case
unfolding wordinterval_CIDR_split1_preserve[OF some, unfolded vernichter, symmetric]
unfolding card_Un_disjoint[OF finite finite wordinterval_CIDR_split1_distinct[OF some, unfolded vernichter]]
by auto
qed
private lemma unfold_rsplit_case:
assumes su: "(Some s, u) = wordinterval_CIDR_split1 rs"
shows "(case wordinterval_CIDR_split1 rs of (None, u) \<Rightarrow> []
| (Some s, u) \<Rightarrow> s # wordinterval_CIDR_split_prefixmatch u) = s # wordinterval_CIDR_split_prefixmatch u"
using su by (metis option.simps(5) split_conv)
lemma "wordinterval_CIDR_split_prefixmatch
(RangeUnion (WordInterval (0x40000000) 0x5FEFBBCC) (WordInterval 0x5FEEBB1C 0x7FFFFFFF))
= [PrefixMatch (0x40000000::32 word) 2]" by eval
lemma "length (wordinterval_CIDR_split_prefixmatch (WordInterval 0 (0xFFFFFFFE::32 word))) = 32" by eval
declare wordinterval_CIDR_split_prefixmatch.simps[simp del]
theorem wordinterval_CIDR_split_prefixmatch:
"wordinterval_to_set r = (\<Union>x\<in>set (wordinterval_CIDR_split_prefixmatch r). prefix_to_wordset x)"
proof(induction r rule: wordinterval_CIDR_split_prefixmatch.induct)
case (1 rs)
show ?case proof(cases "wordinterval_empty rs")
case True
thus ?thesis by(simp add: wordinterval_CIDR_split_prefixmatch.simps)
next
case False
obtain x y where s1: "wordinterval_CIDR_split1 rs = (Some x, y)"
using r_split1_not_none[OF False] by(auto simp add: fst_def split: prod.splits)
have mIH: "wordinterval_to_set y = (\<Union>x\<in>set (wordinterval_CIDR_split_prefixmatch y). prefix_to_wordset x)"
using 1[OF False s1[symmetric] refl] .
have *: "wordinterval_to_set rs = prefix_to_wordset x \<union> (\<Union>x\<in>set (wordinterval_CIDR_split_prefixmatch y). prefix_to_wordset x)"
unfolding mIH[symmetric]
proof -
have ud: "y = wordinterval_setminus rs (prefix_to_wordinterval x)"
using wordinterval_CIDR_split1_snd[OF s1] .
have ss: "prefix_to_wordset x \<subseteq> wordinterval_to_set rs"
using largest_contained_prefix_subset_s1D[OF s1] by simp
show "wordinterval_to_set rs = prefix_to_wordset x \<union> wordinterval_to_set y"
unfolding ud using ss by simp blast
qed
show ?thesis
apply(subst wordinterval_CIDR_split_prefixmatch.simps)
apply(unfold if_P[OF False] s1 prod.simps option.simps *) (* WOOOOO simplifier bug (* try making this a simp add: *) *)
apply(simp)
done
qed
qed
lemma wordinterval_CIDR_split_prefixmatch_all_valid_Ball: fixes r:: "'a::len wordinterval"
shows "\<forall>e\<in>set (wordinterval_CIDR_split_prefixmatch r). valid_prefix e \<and> pfxm_length e \<le> LENGTH('a)"
(* The induction is somewhat verbose, so it is less annoying to write the two down at once *)
proof(induction r rule: wordinterval_CIDR_split_prefixmatch.induct)
case 1
case (1 rs)
show ?case proof(cases "wordinterval_empty rs")
case False
obtain x y where s1: "wordinterval_CIDR_split1 rs = (Some x, y)"
using r_split1_not_none[OF False] by(auto simp add: fst_def split: prod.splits)
hence i1: "valid_prefix x"
unfolding wordinterval_CIDR_split1_def Let_def largest_contained_prefix_def
by(auto dest: find_SomeD split: option.splits)
have i2: "pfxm_length x \<le> LENGTH('a)"
using s1 unfolding wordinterval_CIDR_split1_def Let_def largest_contained_prefix_def pfxes_def
by(force split: option.splits dest: find_SomeD simp: nat_le_iff)
have mIH: "\<forall>a\<in>set (wordinterval_CIDR_split_prefixmatch y). valid_prefix a \<and> pfxm_length a \<le> LENGTH('a)"
using 1[OF False s1[symmetric] refl] .
with i1 i2 show ?thesis
apply(subst wordinterval_CIDR_split_prefixmatch.simps)
apply(unfold if_P[OF False] s1 prod.simps option.simps)
apply(simp)
done
qed (simp add: wordinterval_CIDR_split_prefixmatch.simps)
qed
private lemma wordinterval_CIDR_split_prefixmatch_all_valid_less_Ball_hlp:
"x \<in> set [s\<leftarrow>map (PrefixMatch x2) (pfxes TYPE('a::len0)) . valid_prefix s \<and> wordinterval_to_set (prefix_to_wordinterval s) \<subseteq> wordinterval_to_set rs] \<Longrightarrow> pfxm_length x \<le> LENGTH('a)"
by(clarsimp simp: pfxes_def) presburger
text\<open>Since @{const wordinterval_CIDR_split_prefixmatch} only returns valid prefixes, we can safely convert it to CIDR lists\<close>
(* actually, just valid_prefix doesn't mean that the prefix length is sane. Fortunately, wordinterval_CIDR_split_prefixmatch_all_valid_Ball does entail that *)
lemma "valid_prefix (PrefixMatch (0::16 word) 20)" by(simp add: valid_prefix_def)
lemma wordinterval_CIDR_split_disjunct: "a \<in> set (wordinterval_CIDR_split_prefixmatch i) \<Longrightarrow>
b \<in> set (wordinterval_CIDR_split_prefixmatch i) \<Longrightarrow> a \<noteq> b \<Longrightarrow>
prefix_to_wordset a \<inter> prefix_to_wordset b = {}"
proof(induction i rule: wordinterval_CIDR_split_prefixmatch.induct)
case (1 rs)
note IH = 1(1)
have prema: "a \<in> set (wordinterval_CIDR_split_prefixmatch rs)" (is "a \<in> ?os") using 1 by simp
have premb: "b \<in> ?os" using 1 by simp
show ?case proof(cases "wordinterval_empty rs")
case False
obtain x y where s1: "wordinterval_CIDR_split1 rs = (Some x, y)"
using r_split1_not_none[OF False] by(auto simp add: fst_def split: prod.splits)
have mi: "k \<in> set (wordinterval_CIDR_split_prefixmatch y)" (is "k \<in> ?rs")
if p: "k \<noteq> x" "k \<in> ?os" for k using p s1
by(subst (asm) wordinterval_CIDR_split_prefixmatch.simps) (simp only: if_P[OF False] split: prod.splits option.splits; simp)
have a: "k \<in> ?rs \<Longrightarrow> prefix_to_wordset k \<subseteq> wordinterval_to_set y" for k
(* this is actually a quite general statement, might make a lemma out of it *)
unfolding wordinterval_CIDR_split_prefixmatch by blast
have b: "prefix_to_wordset x \<inter> wordinterval_to_set y = {}"
using wordinterval_CIDR_split1_snd[OF s1] by simp
show ?thesis
proof(cases "a = x"; cases "b = x")
assume as: "a = x" "b \<noteq> x"
with a[OF mi[OF as(2) premb]] b
show ?thesis by blast
next
assume as: "a \<noteq> x" "b = x"
with a[OF mi[OF as(1) prema]] b
show ?thesis by blast
next
assume as: "a \<noteq> x" "b \<noteq> x" (* Nothing to do case *)
have i: "a \<in> ?rs" "b \<in> ?rs"
using as mi prema premb by blast+
show "prefix_to_wordset a \<inter> prefix_to_wordset b = {}"
by(rule IH[OF False s1[symmetric] refl i]) (fact 1)
next
assume as: "a = x" "b = x" (* impossible case *)
with 1 have False by simp
thus ?thesis ..
qed
next
case True
hence "wordinterval_CIDR_split_prefixmatch rs = []" by(simp add: wordinterval_CIDR_split_prefixmatch.simps)
thus ?thesis using prema by simp
qed
qed
lemma wordinterval_CIDR_split_distinct: "distinct (wordinterval_CIDR_split_prefixmatch i)"
(* wish this was a corollary *)
proof(induction i rule: wordinterval_CIDR_split_prefixmatch.induct)
case (1 rs)
show ?case proof(cases "wordinterval_empty rs")
case False
obtain x y where s1: "wordinterval_CIDR_split1 rs = (Some x, y)"
using r_split1_not_none[OF False] by(auto simp add: fst_def split: prod.splits)
have mIH: "distinct (wordinterval_CIDR_split_prefixmatch y)"
using 1[OF False s1[symmetric] refl] .
have "prefix_to_wordset x \<inter> wordinterval_to_set y = {}"
using wordinterval_CIDR_split1_snd[OF s1] by simp
hence i1: "x \<notin> set (wordinterval_CIDR_split_prefixmatch y)"
unfolding wordinterval_CIDR_split_prefixmatch using prefix_never_empty[of x, simplified] by blast
show ?thesis
using s1
by(subst wordinterval_CIDR_split_prefixmatch.simps)
(simp add: if_P[OF False] mIH i1 split: option.splits prod.splits)
qed (simp add: wordinterval_CIDR_split_prefixmatch.simps)
qed
lemma wordinterval_CIDR_split_existential:
"x \<in> wordinterval_to_set w \<Longrightarrow> \<exists>s. s \<in> set (wordinterval_CIDR_split_prefixmatch w) \<and> x \<in> prefix_to_wordset s"
using wordinterval_CIDR_split_prefixmatch[symmetric] by fastforce
subsection\<open>Versions for @{const ipset_from_cidr}\<close>
definition cidr_split :: "'i::len wordinterval \<Rightarrow> ('i word \<times> nat) list" where
"cidr_split rs \<equiv> map prefix_match_to_CIDR (wordinterval_CIDR_split_prefixmatch rs)"
corollary cidr_split_prefix:
fixes r :: "'i::len wordinterval"
shows "(\<Union>x\<in>set (cidr_split r). uncurry ipset_from_cidr x) = wordinterval_to_set r"
unfolding wordinterval_CIDR_split_prefixmatch[symmetric] cidr_split_def
apply(simp add: prefix_match_to_CIDR_def2 wordinterval_CIDR_split_prefixmatch)
using prefix_to_wordset_ipset_from_cidr wordinterval_CIDR_split_prefixmatch_all_valid_Ball by blast
corollary cidr_split_prefix_single:
fixes start :: "'i::len word"
shows "(\<Union>x\<in>set (cidr_split (iprange_interval (start, end))). uncurry ipset_from_cidr x) = {start..end}"
unfolding wordinterval_to_set.simps[symmetric]
using cidr_split_prefix iprange_interval.simps by metis
private lemma interval_in_splitD: "xa \<in> foo \<Longrightarrow> prefix_to_wordset xa \<subseteq> \<Union>(prefix_to_wordset ` foo)" by auto
end
end
|
/-
Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bryan Gin-ge Chen, Kevin Lacker
-/
import tactic.ring
/-!
# Identities
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains some "named" commutative ring identities.
-/
variables {R : Type*} [comm_ring R]
{a b x₁ x₂ x₃ x₄ x₅ x₆ x₇ x₈ y₁ y₂ y₃ y₄ y₅ y₆ y₇ y₈ n : R}
/--
Brahmagupta-Fibonacci identity or Diophantus identity, see
<https://en.wikipedia.org/wiki/Brahmagupta%E2%80%93Fibonacci_identity>.
This sign choice here corresponds to the signs obtained by multiplying two complex numbers.
-/
theorem sq_add_sq_mul_sq_add_sq :
(x₁^2 + x₂^2) * (y₁^2 + y₂^2) = (x₁*y₁ - x₂*y₂)^2 + (x₁*y₂ + x₂*y₁)^2 :=
by ring
/--
Brahmagupta's identity, see <https://en.wikipedia.org/wiki/Brahmagupta%27s_identity>
-/
theorem sq_add_mul_sq_mul_sq_add_mul_sq :
(x₁^2 + n*x₂^2) * (y₁^2 + n*y₂^2) = (x₁*y₁ - n*x₂*y₂)^2 + n*(x₁*y₂ + x₂*y₁)^2 :=
by ring
/--
Sophie Germain's identity, see <https://www.cut-the-knot.org/blue/SophieGermainIdentity.shtml>.
-/
theorem pow_four_add_four_mul_pow_four : a^4 + 4*b^4 = ((a - b)^2 + b^2) * ((a + b)^2 + b^2) :=
by ring
/--
Sophie Germain's identity, see <https://www.cut-the-knot.org/blue/SophieGermainIdentity.shtml>.
-/
theorem pow_four_add_four_mul_pow_four' :
a^4 + 4*b^4 = (a^2 - 2*a*b + 2*b^2) * (a^2 + 2*a*b + 2*b^2) :=
by ring
/--
Euler's four-square identity, see <https://en.wikipedia.org/wiki/Euler%27s_four-square_identity>.
This sign choice here corresponds to the signs obtained by multiplying two quaternions.
-/
theorem sum_four_sq_mul_sum_four_sq : (x₁^2 + x₂^2 + x₃^2 + x₄^2) * (y₁^2 + y₂^2 + y₃^2 + y₄^2) =
(x₁*y₁ - x₂*y₂ - x₃*y₃ - x₄*y₄)^2 + (x₁*y₂ + x₂*y₁ + x₃*y₄ - x₄*y₃)^2 +
(x₁*y₃ - x₂*y₄ + x₃*y₁ + x₄*y₂)^2 + (x₁*y₄ + x₂*y₃ - x₃*y₂ + x₄*y₁)^2 :=
by ring
/--
Degen's eight squares identity, see <https://en.wikipedia.org/wiki/Degen%27s_eight-square_identity>.
This sign choice here corresponds to the signs obtained by multiplying two octonions.
-/
theorem sum_eight_sq_mul_sum_eight_sq : (x₁^2 + x₂^2 + x₃^2 + x₄^2 + x₅^2 + x₆^2 + x₇^2 + x₈^2) *
(y₁^2 + y₂^2 + y₃^2 + y₄^2 + y₅^2 + y₆^2 + y₇^2 + y₈^2) =
(x₁*y₁ - x₂*y₂ - x₃*y₃ - x₄*y₄ - x₅*y₅ - x₆*y₆ - x₇*y₇ - x₈*y₈)^2 +
(x₁*y₂ + x₂*y₁ + x₃*y₄ - x₄*y₃ + x₅*y₆ - x₆*y₅ - x₇*y₈ + x₈*y₇)^2 +
(x₁*y₃ - x₂*y₄ + x₃*y₁ + x₄*y₂ + x₅*y₇ + x₆*y₈ - x₇*y₅ - x₈*y₆)^2 +
(x₁*y₄ + x₂*y₃ - x₃*y₂ + x₄*y₁ + x₅*y₈ - x₆*y₇ + x₇*y₆ - x₈*y₅)^2 +
(x₁*y₅ - x₂*y₆ - x₃*y₇ - x₄*y₈ + x₅*y₁ + x₆*y₂ + x₇*y₃ + x₈*y₄)^2 +
(x₁*y₆ + x₂*y₅ - x₃*y₈ + x₄*y₇ - x₅*y₂ + x₆*y₁ - x₇*y₄ + x₈*y₃)^2 +
(x₁*y₇ + x₂*y₈ + x₃*y₅ - x₄*y₆ - x₅*y₃ + x₆*y₄ + x₇*y₁ - x₈*y₂)^2 +
(x₁*y₈ - x₂*y₇ + x₃*y₆ + x₄*y₅ - x₅*y₄ - x₆*y₃ + x₇*y₂ + x₈*y₁)^2 :=
by ring
|
Require Import Omega.
Require Import Bool.
Require Import RelationClasses.
Require Import sflib.
From Paco Require Import paco.
Require Import Axioms.
Require Import Basic.
Require Import DataStructure.
Require Import DenseOrder.
Require Import Language.
Require Import Loc.
Require Import Event.
Require Import Time.
Require Import View.
Require Import Cell.
Require Import Memory.
Require Import TView.
Require Import Local.
Require Import Thread.
Require Import Configuration.
Require Import Trace.
Require Import Behavior.
Require Import Single.
Require Import Mapping.
Set Implicit Arguments.
Module SemiReachable.
Section REACHABLE.
Variable (c0: Configuration.t).
Hypothesis CONFIG_CONSISTENT: forall tid lang st lc
(TID: IdentMap.find tid (Configuration.threads c0) = Some (existT _ lang st, lc)),
Local.promise_consistent lc.
Hypothesis CONFIG_WF: Configuration.wf c0.
Section TID.
Variable (tid: Ident.t).
Inductive semi_reachable lang (th: Thread.t lang): Prop :=
| semi_reachable_intro
c1 st1 lc1
(STEPS: rtc SConfiguration.all_machine_step c0 c1)
(TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))
(TSTEPS: rtc (@Thread.all_step _) (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) th)
(CONSISTENT: Local.promise_consistent (Thread.local th))
.
Hint Constructors semi_reachable.
Inductive semi_reachable_state
(lang: language) (st: @Language.state _ lang): Prop :=
| semi_reachable_stateintro
lc sc mem
(REACHABLE: semi_reachable (Thread.mk _ st lc sc mem))
:
semi_reachable_state _ st
.
Hint Constructors semi_reachable_state.
Inductive step lang: forall (pf: bool) (e: ThreadEvent.t) (th0 th1: Thread.t lang), Prop :=
| step_intro
pf e th0 th1
(STEP: Thread.step pf e th0 th1)
(REACHABLE: semi_reachable_state lang (Thread.state th1))
:
step pf e th0 th1
.
Hint Constructors step.
Inductive opt_step lang: forall (e:ThreadEvent.t) (e1 e2:Thread.t lang), Prop :=
| step_none
e:
opt_step ThreadEvent.silent e e
| step_some
pf e e1 e2
(STEP: step pf e e1 e2):
opt_step e e1 e2
.
Hint Constructors opt_step.
Inductive step_allpf lang (e:ThreadEvent.t) (e1 e2:Thread.t lang): Prop :=
| step_nopf_intro
pf
(STEP: step pf e e1 e2)
.
Hint Constructors step_allpf.
Definition tau_step lang := tau (@step_allpf lang).
Inductive reserve_step lang (e1 e2:Thread.t lang): Prop :=
| reserve_step_intro
pf loc from to
(STEP: step pf (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_add) e1 e2)
.
Hint Constructors reserve_step.
Inductive cancel_step lang (e1 e2:Thread.t lang): Prop :=
| cancel_step_intro
pf loc from to
(STEP: step pf (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_cancel) e1 e2)
.
Hint Constructors cancel_step.
Lemma step_reachable lang pf e (th0 th1: Thread.t lang)
(STEP: Thread.step pf e th0 th1)
(CONSISTENT: Local.promise_consistent (Thread.local th1))
(REACHABLE: semi_reachable th0)
:
(<<STEP: step pf e th0 th1>>) /\
(<<REACHABLE: semi_reachable th1>>).
Proof.
inv REACHABLE.
assert (REACHABLE0: semi_reachable th1).
{ econs; eauto. etrans; eauto. econs 2; [|refl]. econs; eauto. econs; eauto. }
splits; auto. econs; eauto. destruct th1. econs; eauto.
Qed.
Lemma opt_step_reachable lang e (th0 th1: Thread.t lang)
(STEP: Thread.opt_step e th0 th1)
(CONSISTENT: Local.promise_consistent (Thread.local th1))
(REACHABLE: semi_reachable th0)
:
(<<STEP: opt_step e th0 th1>>) /\
(<<REACHABLE: semi_reachable th1>>).
Proof.
inv STEP.
- splits; auto.
- eapply step_reachable in STEP0; eauto. des. splits; eauto.
Qed.
Lemma tau_steps_reachable lang (th0 th1: Thread.t lang)
(STEPS: rtc (@Thread.tau_step _) th0 th1)
(LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))
(MEMORY: Memory.closed (Thread.memory th0))
(SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))
(CONSISTENT: Local.promise_consistent (Thread.local th1))
(REACHABLE: semi_reachable th0)
:
(<<STEP: rtc (@tau_step _) th0 th1>>) /\
(<<REACHABLE: semi_reachable th1>>).
Proof.
revert LOCAL MEMORY SC CONSISTENT REACHABLE. induction STEPS; eauto. i.
inv H. inv TSTEP. exploit Thread.step_future; eauto. i. des.
hexploit PromiseConsistent.rtc_tau_step_promise_consistent; eauto. i.
hexploit step_reachable; eauto. i. des.
hexploit IHSTEPS; eauto. i. des. splits; eauto.
econs; eauto. econs; eauto.
Qed.
Lemma reserve_steps_reachable lang (th0 th1: Thread.t lang)
(STEPS: rtc (@Thread.reserve_step _) th0 th1)
(LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))
(MEMORY: Memory.closed (Thread.memory th0))
(SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))
(CONSISTENT: Local.promise_consistent (Thread.local th1))
(REACHABLE: semi_reachable th0)
:
(<<STEP: rtc (@reserve_step _) th0 th1>>) /\
(<<REACHABLE: semi_reachable th1>>).
Proof.
revert LOCAL MEMORY SC CONSISTENT REACHABLE. induction STEPS; eauto. i.
inv H. exploit Thread.step_future; eauto. i. des.
hexploit PromiseConsistent.rtc_reserve_step_promise_consistent; eauto. i.
hexploit step_reachable; eauto. i. des.
hexploit IHSTEPS; eauto. i. des. splits; eauto.
Qed.
Lemma cancel_steps_reachable lang (th0 th1: Thread.t lang)
(STEPS: rtc (@Thread.cancel_step _) th0 th1)
(LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))
(MEMORY: Memory.closed (Thread.memory th0))
(SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))
(CONSISTENT: Local.promise_consistent (Thread.local th1))
(REACHABLE: semi_reachable th0)
:
(<<STEP: rtc (@cancel_step _) th0 th1>>) /\
(<<REACHABLE: semi_reachable th1>>).
Proof.
revert LOCAL MEMORY SC CONSISTENT REACHABLE. induction STEPS; eauto. i.
inv H. exploit Thread.step_future; eauto. i. des.
hexploit PromiseConsistent.rtc_cancel_step_promise_consistent; eauto. i.
hexploit step_reachable; eauto. i. des.
hexploit IHSTEPS; eauto. i. des. splits; eauto.
Qed.
Definition consistent lang (e1:Thread.t lang): Prop :=
forall mem1 sc1
(CAP: Memory.cap (Thread.memory e1) mem1)
(SC_MAX: Memory.max_concrete_timemap mem1 sc1),
(exists e2 e3,
(<<STEPS: rtc (@tau_step lang) (Thread.mk _ (Thread.state e1) (Thread.local e1) sc1 mem1) e2>>) /\
(<<FAILURE: step true ThreadEvent.failure e2 e3 >>)) \/
(exists e2,
(<<STEPS: rtc (@tau_step lang) (Thread.mk _ (Thread.state e1) (Thread.local e1) sc1 mem1) e2>>) /\
(<<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>))
.
Inductive configuration_step:
forall (e:ThreadEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=
| configuration_step_intro
e tid c1 lang st1 lc1 e2 e3 st4 lc4 sc4 memory4
(TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))
(CANCELS: rtc (@cancel_step _) (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) e2)
(STEP: opt_step e e2 e3)
(RESERVES: rtc (@reserve_step _) e3 (Thread.mk _ st4 lc4 sc4 memory4))
(CONSISTENT: e <> ThreadEvent.failure -> consistent (Thread.mk _ st4 lc4 sc4 memory4)):
configuration_step e tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st4, lc4) (Configuration.threads c1)) sc4 memory4)
.
Hint Constructors configuration_step.
Lemma step_map_reachable lang pf e (th0 th1 fth0: Thread.t lang)
(STEP: Thread.step pf e th0 th1)
(THREAD: thread_map ident_map th0 fth0)
(CONSISTENT: Local.promise_consistent (Thread.local th1))
(REACHABLE: semi_reachable fth0)
(LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))
(MEMORY: Memory.closed (Thread.memory th0))
(SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))
(FLOCAL: Local.wf (Thread.local fth0) (Thread.memory fth0))
(FMEMORY: Memory.closed (Thread.memory fth0))
(FSC: Memory.closed_timemap (Thread.sc fth0) (Thread.memory fth0))
:
exists fpf fe fth1,
(<<STEP: Thread.step fpf fe fth0 fth1>>) /\
(<<EVENT: tevent_map ident_map fe e>>) /\
(<<THREAD: thread_map ident_map th1 fth1>>) /\
(<<REACHABLE: semi_reachable fth1>>) /\
(<<STEP: step pf e th0 th1>>)
.
Proof.
splits; auto.
inv THREAD. destruct th1. ss. hexploit step_map; ss.
{ eapply ident_map_le. }
{ eapply ident_map_bot. }
{ eapply ident_map_eq. }
{ instantiate (1:=fun _ => True). i. eapply ident_map_mappable_evt. }
{ econs; eauto. econs; eauto. }
{ ss. }
{ eauto. }
{ ss. }
{ ss. }
{ ss. }
{ eapply mapping_map_lt_collapsable_unwritable. eapply ident_map_lt. }
{ ss. }
i. des. inv STEP0.
assert (RECHABLE0: semi_reachable (Thread.mk _ state flc1 fsc1 fmem1)).
{ inv REACHABLE.
econs; eauto. etrans; eauto. econs 2; [|refl]. econs; eauto. econs; eauto.
ss. inv LOCAL1. hexploit promise_consistent_map.
{ eapply ident_map_le. }
{ eapply ident_map_eq. }
{ eapply TVIEW. }
{ eapply PROMISES. }
{ ss. }
i. eapply promise_consistent_mon; eauto. refl.
}
esplits; eauto. econs; eauto.
{ eapply mapping_map_lt_collapsable_unwritable; eauto. eapply ident_map_lt. }
Qed.
Lemma tau_steps_map_reachable lang (th0 th1 fth0: Thread.t lang)
(STEPS: rtc (@Thread.tau_step _) th0 th1)
(THREAD: thread_map ident_map th0 fth0)
(CONSISTENT: Local.promise_consistent (Thread.local th1))
(REACHABLE: semi_reachable fth0)
(LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))
(MEMORY: Memory.closed (Thread.memory th0))
(SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))
(FLOCAL: Local.wf (Thread.local fth0) (Thread.memory fth0))
(FMEMORY: Memory.closed (Thread.memory fth0))
(FSC: Memory.closed_timemap (Thread.sc fth0) (Thread.memory fth0))
:
exists fth1,
(<<STEPS: rtc (@Thread.tau_step _) fth0 fth1>>) /\
(<<THREAD: thread_map ident_map th1 fth1>>) /\
(<<REACHABLE: semi_reachable fth1>>) /\
(<<STEPS: rtc (@tau_step _) th0 th1>>)
.
Proof.
revert_until STEPS. revert fth0. induction STEPS; eauto.
{ i. esplits; eauto. }
i. inv H. inv TSTEP. exploit Thread.step_future; eauto. i. des.
hexploit PromiseConsistent.rtc_tau_step_promise_consistent; eauto. i.
hexploit step_map_reachable; eauto. i. des.
exploit Thread.step_future; try apply STEP0; eauto. i. des.
hexploit IHSTEPS; eauto. i. des. exists fth2. splits; auto.
{ eapply tevent_map_same_machine_event in EVENT0.
rewrite <- EVENT0 in EVENT.
econs 2; eauto. econs; eauto. econs; eauto.
}
{ econs 2; eauto. econs; eauto. }
Qed.
Lemma consistent_reachable lang (th0: Thread.t lang)
(CONSISTENT: Thread.consistent th0)
(REACHABLE: semi_reachable th0)
(LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))
(MEMORY: Memory.closed (Thread.memory th0))
(SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))
:
consistent th0.
Proof.
ii.
assert (THREAD: thread_map ident_map (Thread.mk _ (Thread.state th0) (Thread.local th0) sc1 mem1) th0).
{ destruct th0. ss. econs; eauto.
- eapply ident_map_local.
- econs.
+ i. eapply Memory.cap_inv in GET; eauto. des; eauto.
right. exists to, from, msg, msg. splits; ss.
* eapply ident_map_message.
* refl.
+ i. eapply Memory.cap_le in GET; eauto; [|refl].
left. exists fto, ffrom, fto, ffrom. splits; ss; try refl. i. econs; eauto.
- eapply mapping_map_lt_collapsable_unwritable. eapply ident_map_lt.
- eapply ident_map_timemap.
- eapply Memory.max_concrete_timemap_spec; eauto.
eapply Memory.cap_closed_timemap; eauto.
}
assert (FLOCAL: Local.wf (Thread.local th0) mem1).
{ eapply Local.cap_wf; eauto. }
assert (FMEMORY: Memory.closed mem1).
{ eapply Memory.cap_closed; eauto. }
assert (FSC: Memory.closed_timemap sc1 mem1).
{ eapply Memory.max_concrete_timemap_closed; eauto. }
exploit CONSISTENT; eauto. i. des.
{ left. unfold Thread.steps_failure in *. des.
exploit Thread.rtc_tau_step_future; eauto. i. des. ss.
eapply tau_steps_map_reachable in STEPS; eauto.
{ des. exploit Thread.rtc_tau_step_future; eauto. i. des.
eapply step_map_reachable in FAILURE0; eauto.
{ des. esplits; eauto. }
{ inv FAILURE0; inv STEP. inv LOCAL0. inv LOCAL1. ss. }
}
{ inv FAILURE0; inv STEP. inv LOCAL0. inv LOCAL1. ss. }
}
{ right. eapply tau_steps_map_reachable in STEPS; eauto.
{ des. esplits; eauto. }
{ eapply Local.bot_promise_consistent; eauto. }
}
Qed.
Lemma configuration_step_reachable c1 c2 e
(STEP: SConfiguration.step e tid c1 c2)
(REACHABLE: rtc SConfiguration.all_machine_step c0 c1)
(WF: Configuration.wf c1)
:
configuration_step e tid c1 c2.
Proof.
inv STEP.
exploit Thread.rtc_cancel_step_future; eauto; try eapply WF; eauto. i. des. ss.
exploit Thread.opt_step_future; eauto. i. des.
exploit Thread.rtc_reserve_step_future; eauto. i. des. ss.
assert ((<<CONSISTENT4: Local.promise_consistent lc4>>) /\
(<<CONSISTENT3: Local.promise_consistent (Thread.local e3)>>)).
{ destruct (classic (e = ThreadEvent.failure)).
- subst. inv STEP0. inv STEP; inv STEP0. inv LOCAL. inv LOCAL0. ss.
splits; eauto.
eapply PromiseConsistent.rtc_reserve_step_promise_consistent2 in RESERVES; eauto.
- specialize (CONSISTENT H).
eapply PromiseConsistent.consistent_promise_consistent in CONSISTENT; eauto.
splits; eauto.
eapply PromiseConsistent.rtc_reserve_step_promise_consistent; eauto.
}
des.
assert (CONSISTENT2: Local.promise_consistent (Thread.local e2)).
{ inv STEP0; eauto.
eapply PromiseConsistent.step_promise_consistent; eauto. }
assert (CONSISTENT1: Local.promise_consistent lc1).
{ eapply PromiseConsistent.rtc_cancel_step_promise_consistent in CANCELS; eauto. }
eapply cancel_steps_reachable in CANCELS; eauto; try eapply WF; eauto. des.
eapply opt_step_reachable in STEP0; eauto. des.
eapply reserve_steps_reachable in RESERVES; eauto. des.
econs; eauto. i.
eapply consistent_reachable; eauto.
Qed.
End TID.
Section SIMCONFIG.
Inductive sim_state_rel
(tid: Ident.t)
(lang_src lang_tgt: language)
(r: Language.state lang_src -> Language.state lang_tgt -> Prop) :=
| sim_state_rel_intro
(STEP: forall st_src0 st_tgt0 st_tgt1 e
(REL: r st_src0 st_tgt0)
(REACHABLE: semi_reachable_state tid lang_tgt st_tgt1)
(STEP: Language.step lang_tgt e st_tgt0 st_tgt1),
exists st_src1,
(<<STEP: Language.step lang_src e st_src0 st_src1>>) /\
(<<REL: r st_src1 st_tgt1>>))
(TERMINAL: forall st_src st_tgt
(REL: r st_src st_tgt)
(REACHABLE: semi_reachable_state tid lang_tgt st_tgt)
(TERMINAL: Language.is_terminal lang_tgt st_tgt),
Language.is_terminal lang_src st_src)
.
Hint Constructors sim_state_rel.
Lemma eq_sim_state_rel tid lang
:
sim_state_rel tid lang lang eq.
Proof.
econs; i; clarify. eauto.
Qed.
Variable (r: forall (tid: Ident.t) (lang_src lang_tgt: language),
Language.state lang_src -> Language.state lang_tgt -> Prop).
Hypothesis (REL: forall tid lang_src lang_tgt, sim_state_rel tid lang_src lang_tgt (r tid lang_src lang_tgt)).
Inductive sim_statelocal tid:
forall (lcst_src lcst_tgt: (sigT (@Language.state _)) * Local.t), Prop :=
| sim_statelocal_intro
lang_src lang_tgt st_src st_tgt lc
(REL: r tid lang_src lang_tgt st_src st_tgt)
:
sim_statelocal tid (existT _ lang_src st_src, lc) (existT _ lang_tgt st_tgt, lc)
.
Hint Constructors sim_statelocal.
Inductive sim_thread tid lang_src lang_tgt: forall (th_src: Thread.t lang_src) (th_tgt: Thread.t lang_tgt), Prop :=
| sim_thread_intro
st_src st_tgt lc sc mem
(REL: r tid lang_src lang_tgt st_src st_tgt)
:
sim_thread tid (Thread.mk _ st_src lc sc mem) (Thread.mk _ st_tgt lc sc mem)
.
Hint Constructors sim_thread.
Inductive sim_configuration:
forall (c_src c_tgt: Configuration.t), Prop :=
| sim_configuration_intro
ths_src ths_tgt sc mem
(THS: forall tid,
option_rel
(sim_statelocal tid)
(IdentMap.find tid ths_src)
(IdentMap.find tid ths_tgt))
:
sim_configuration (Configuration.mk ths_src sc mem) (Configuration.mk ths_tgt sc mem)
.
Hint Constructors sim_configuration.
Lemma sim_thread_step tid lang_src lang_tgt
(th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt) pf e
(STEP: step tid pf e th_tgt0 th_tgt1)
(SIM: sim_thread tid th_src0 th_tgt0)
:
exists th_src1,
(<<STEP: Thread.step pf e th_src0 th_src1>>) /\
(<<SIM: sim_thread tid th_src1 th_tgt1>>).
Proof.
inv SIM. inv STEP; ss. inv STEP0.
{ inv STEP. ss. esplits; eauto. econs 1; eauto. econs; eauto. }
inv STEP. specialize (REL tid lang_src lang_tgt). inv REL.
exploit STEP; eauto. i. des.
esplits; eauto.
Qed.
Lemma sim_thread_opt_step tid lang_src lang_tgt
(th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt) e
(STEP: opt_step tid e th_tgt0 th_tgt1)
(SIM: sim_thread tid th_src0 th_tgt0)
:
exists th_src1,
(<<STEP: Thread.opt_step e th_src0 th_src1>>) /\
(<<SIM: sim_thread tid th_src1 th_tgt1>>).
Proof.
inv STEP.
- esplits; eauto. econs 1.
- eapply sim_thread_step in SIM; eauto. des. esplits; eauto. econs 2; eauto.
Qed.
Lemma sim_thread_reserve_steps tid lang_src lang_tgt
(th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt)
(STEPS: rtc (@reserve_step tid _) th_tgt0 th_tgt1)
(SIM: sim_thread tid th_src0 th_tgt0)
:
exists th_src1,
(<<STEPS: rtc (@Thread.reserve_step _) th_src0 th_src1>>) /\
(<<SIM: sim_thread tid th_src1 th_tgt1>>).
Proof.
ginduction STEPS; eauto. i. inv H.
eapply sim_thread_step in STEP; eauto. des.
exploit IHSTEPS; eauto. i. des.
exists th_src2; eauto. esplits; eauto. econs; eauto. econs; eauto.
Qed.
Lemma sim_thread_cancel_steps tid lang_src lang_tgt
(th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt)
(STEPS: rtc (@cancel_step tid _) th_tgt0 th_tgt1)
(SIM: sim_thread tid th_src0 th_tgt0)
:
exists th_src1,
(<<STEPS: rtc (@Thread.cancel_step _) th_src0 th_src1>>) /\
(<<SIM: sim_thread tid th_src1 th_tgt1>>).
Proof.
ginduction STEPS; eauto. i. inv H.
eapply sim_thread_step in STEP; eauto. des.
exploit IHSTEPS; eauto. i. des.
exists th_src2; eauto. esplits; eauto. econs; eauto. econs; eauto.
Qed.
Lemma sim_thread_tau_steps tid lang_src lang_tgt
(th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt)
(STEPS: rtc (@tau_step tid _) th_tgt0 th_tgt1)
(SIM: sim_thread tid th_src0 th_tgt0)
:
exists th_src1,
(<<STEPS: rtc (@Thread.tau_step _) th_src0 th_src1>>) /\
(<<SIM: sim_thread tid th_src1 th_tgt1>>).
Proof.
ginduction STEPS; eauto. i. inv H. inv TSTEP.
eapply sim_thread_step in STEP; eauto. des.
exploit IHSTEPS; eauto. i. des.
exists th_src2; eauto. esplits; eauto. econs; eauto. econs; eauto. econs; eauto.
Qed.
Lemma sim_thread_consistent tid lang_src lang_tgt
(th_src: Thread.t lang_src) (th_tgt: Thread.t lang_tgt)
(CONSISTENT: consistent tid th_tgt)
(SIM: sim_thread tid th_src th_tgt)
:
Thread.consistent th_src.
Proof.
inv SIM. ii; ss.
assert (SIM: sim_thread tid (Thread.mk _ st_src lc sc1 mem1) (Thread.mk _ st_tgt lc sc1 mem1)).
{ econs; eauto. }
exploit CONSISTENT; eauto. i; ss. des.
- left. eapply sim_thread_tau_steps in STEPS; eauto. des.
eapply sim_thread_step in FAILURE; eauto. des.
unfold Thread.steps_failure. esplits; eauto.
- right. eapply sim_thread_tau_steps in STEPS; eauto. des.
esplits; eauto. inv SIM0. ss.
Qed.
Lemma sim_configuration_step c_src0 c_tgt0 c_tgt1 e tid
(WF: Configuration.wf c_tgt0)
(STEP: SConfiguration.step e tid c_tgt0 c_tgt1)
(SIM: sim_configuration c_src0 c_tgt0)
(REACHABLE: rtc SConfiguration.all_machine_step c0 c_tgt0)
:
exists c_src1,
(<<STEP: SConfiguration.step e tid c_src0 c_src1>>) /\
(<<SIM: sim_configuration c_src1 c_tgt1>>).
Proof.
eapply configuration_step_reachable in STEP; eauto.
inv STEP. inv SIM. ss.
dup THS. specialize (THS0 tid). setoid_rewrite TID in THS0.
unfold option_rel in THS0. des_ifs. destruct p as [[lang_src st_src] lc_tgt].
inv THS0. eapply inj_pair2 in H4. clarify. eapply inj_pair2 in H0. clarify.
assert (SIM: sim_thread tid (Thread.mk _ st_src lc1 sc mem) (Thread.mk _ st1 lc1 sc mem)) by eauto.
eapply sim_thread_cancel_steps in CANCELS; eauto. des.
eapply sim_thread_opt_step in STEP0; eauto. des.
eapply sim_thread_reserve_steps in RESERVES; eauto. des. destruct th_src2.
esplits.
{ econs; s.
- eauto.
- eapply STEPS.
- eapply STEP.
- eapply STEPS0.
- i. eapply sim_thread_consistent; eauto.
}
{ inv SIM2. ss. econs; eauto. i.
repeat erewrite IdentMap.gsspec. des_ifs.
}
Qed.
Lemma steps_configuration_local_consistent c1
(REACHABLE: rtc SConfiguration.all_machine_step c0 c1)
tid lang st lc
(TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st, lc))
:
Local.promise_consistent lc.
Proof.
eapply Operators_Properties.clos_rt_rt1n_iff in REACHABLE.
eapply Operators_Properties.clos_rt_rtn1_iff in REACHABLE.
revert tid lang st lc TID. induction REACHABLE; eauto.
i. inv H. inv STEP. assert (WF0: Configuration.wf y).
{ eapply Operators_Properties.clos_rt_rtn1_iff in REACHABLE.
eapply Operators_Properties.clos_rt_rt1n_iff in REACHABLE.
eapply SConfiguration.all_machine_steps_future; eauto. }
exploit SConfiguration.step_future; eauto. i. des.
inv STEP0. ss.
erewrite IdentMap.gsspec in TID. des_ifs.
{ eapply inj_pair2 in H0. clarify.
destruct (classic (e0 = ThreadEvent.failure)).
{ inv STEP; ss. inv STEP0; inv STEP. inv LOCAL. inv LOCAL0.
eapply PromiseConsistent.rtc_reserve_step_promise_consistent2 in RESERVES; eauto.
}
{ hexploit PromiseConsistent.consistent_promise_consistent; eauto; try apply WF2; eauto.
ss. inv WF2. ss. eapply WF; eauto.
erewrite IdentMap.gss. eauto.
}
}
{ eapply IHREACHABLE; eauto. }
Qed.
Lemma sim_configuration_terminal c_src c_tgt
(TERMINAL: Configuration.is_terminal c_tgt)
(SIM: sim_configuration c_src c_tgt)
(REACHABLE: rtc SConfiguration.all_machine_step c0 c_tgt)
:
Configuration.is_terminal c_src.
Proof.
ii. inv SIM. ss.
specialize (THS tid). setoid_rewrite FIND in THS.
unfold option_rel in THS. des_ifs. destruct p as [[lang_tgt st_tgt] lc_tgt].
inv THS. eapply inj_pair2 in H4. clarify. eapply inj_pair2 in H0. clarify.
exploit TERMINAL; eauto. i. des.
specialize (REL tid lang lang_tgt). inv REL.
exploit TERMINAL0; eauto.
econs; eauto. econs; eauto. ss.
hexploit steps_configuration_local_consistent.
{ eapply REACHABLE. }
{ ss. eauto. }
{ eauto. }
Qed.
Lemma sim_configuration_behavior c_src c_tgt
(WF: Configuration.wf c_tgt)
(SIM: sim_configuration c_src c_tgt)
(REACHABLE: rtc SConfiguration.all_machine_step c0 c_tgt)
:
behaviors SConfiguration.machine_step c_tgt <1= behaviors SConfiguration.machine_step c_src.
Proof.
intros beh BEH. ginduction BEH; eauto.
- i. econs 1. eapply sim_configuration_terminal; eauto.
- i. dup STEP. inv STEP0. exploit SConfiguration.step_future; eauto. i. des.
eapply sim_configuration_step in STEP1; eauto. des. econs 2.
+ rewrite <- H0. econs; eauto.
+ eapply IHBEH; eauto. etrans; eauto.
- i. dup STEP. inv STEP0. exploit SConfiguration.step_future; eauto. i. des.
eapply sim_configuration_step in STEP1; eauto. des. econs 3.
+ rewrite <- H0. econs; eauto.
- i. dup STEP. inv STEP0. exploit SConfiguration.step_future; eauto. i. des.
eapply sim_configuration_step in STEP1; eauto. des. econs 4.
+ rewrite <- H0. econs; eauto.
+ eapply IHBEH; eauto. etrans; eauto.
Qed.
End SIMCONFIG.
End REACHABLE.
Theorem unreachable_code_transformation syn_src syn_tgt
(r: forall (tid: Ident.t) (lang_src lang_tgt: language),
Language.state lang_src -> Language.state lang_tgt -> Prop)
(REL: forall tid lang_src lang_tgt, sim_state_rel (Configuration.init syn_tgt) tid lang_src lang_tgt (r tid lang_src lang_tgt))
(INIT: sim_configuration r (Configuration.init syn_src) (Configuration.init syn_tgt))
:
behaviors SConfiguration.machine_step (Configuration.init syn_tgt)
<1=
behaviors SConfiguration.machine_step (Configuration.init syn_src).
Proof.
eapply sim_configuration_behavior; eauto.
- i. ss. unfold Threads.init in *. rewrite IdentMap.Facts.map_o in TID.
unfold option_map in *. des_ifs. ii. ss. erewrite Memory.bot_get in *. ss.
- eapply Configuration.init_wf.
- eapply Configuration.init_wf.
Qed.
End SemiReachable.
|
/-
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
set_option aesop.check.all true
@[aesop 50% cases]
inductive FancyAnd (α β : Prop) : Prop
| dummy (p : Empty)
| and (a : α) (b : β)
attribute [aesop safe -51 cases] Empty
example {α β} (h : FancyAnd α β) : α ∧ β := by
aesop
@[aesop safe (cases (patterns := [All _ [], All _ (_ :: _)]))]
inductive All (P : α → Prop) : List α → Prop
| nil : All P []
| cons : P x → All P xs → All P (x :: xs)
@[aesop 99% constructors]
structure MyTrue : Prop
-- Without the patterns on the `cases` rule for `All`, this test would loop
-- since the `constructors` rule would never be applied.
example {P : α → Prop} (h : All P (x :: xs)) : MyTrue := by
aesop
|
import collections
import itertools
from itertools import tee
from math import sqrt
import os
import matplotlib.pyplot as plt
import numpy as np
import sklearn.preprocessing
import scipy
from scipy.stats import spearmanr
import torch
import pygsp
import networkx as nx
import community as louvain
import networkx.algorithms.community as commu
from sklearn import manifold
from tqdm import tqdm
from .diffusion_graph import edges_from_loss_fn, cosine_loss
from .loaders import get_all_pairs_datasets
from .loaders import split_train_test
from .loaders import get_train_test_datasets_labels
from .loaders import get_dataset_from_datapath
from .loaders import get_labels_stats
from .classifiers import features_classification
def connect_parts_labels(recorder, graph, part_a, part_b, labels, label_0, label_1):
recorder.record_balance(min(len(part_a), len(part_b)) / len(graph))
a_to_0 = np.array([label_0]*len(graph))
for node_b in part_b:
a_to_0[node_b] = label_1
a_to_0 = torch.LongTensor(a_to_0)
ratio_errors = (a_to_0 == labels).sum().item()
ratio_errors = ratio_errors / len(graph)
ratio_errors = max(ratio_errors, 1. - ratio_errors)
#print('\n', part_a, ' ============ ', part_b, ' ####### ', ratio_errors*100, '\n')
return ratio_errors * 100.
def stoer_wagner_volume(recorder, graph, labels, params):
assert params.n_way == 2
try:
_, (part_a, part_b) = nx.stoer_wagner(graph)
except nx.exception.NetworkXError:
assert params.n_shot == 1
part_a = nx.node_connected_component(graph, 0)
part_b = nx.node_connected_component(graph, 1)
label_0, label_1 = torch.min(labels).item(), torch.max(labels).item()
assert (labels == label_0).sum().item() * 2 == len(graph)
return connect_parts_labels(recorder, graph, part_a, part_b, labels, label_0, label_1)
def min_cut_volume(recorder, graph, labels, params):
assert params.n_shot == 1 and params.n_way == 2
cut = nx.minimum_edge_cut(graph, 0, 1)
graph.remove_edges_from(cut)
part_a = nx.node_connected_component(graph, 0)
part_b = nx.node_connected_component(graph, 1)
label_0, label_1 = labels[0].item(), labels[1].item()
return connect_parts_labels(recorder, graph, part_a, part_b, labels, label_0, label_1)
def kernighan(recorder, graph, labels, params):
assert params.n_shot == 1 and params.n_way == 2
part_a, part_b = commu.kernighan_lin.kernighan_lin_bisection(graph, max_iter=20)
label_0, label_1 = labels[0].item(), labels[1].item()
return connect_parts_labels(recorder, graph, part_a, part_b, labels, label_0, label_1)
def compute_pure(nodes, colors, labels):
labels = labels.numpy()
colors_to_labels = collections.defaultdict(set)
labels_to_colors = collections.defaultdict(set)
for node in nodes:
colors_to_labels[colors[node]].add(int(labels[node]))
labels_to_colors[int(labels[node])].add(colors[node])
num_confusion = sum([1 for labels in colors_to_labels.values() if len(labels) > 1])
num_splitted = sum([1 for colors in labels_to_colors.values() if len(colors) > 1])
num_good = len(colors_to_labels) - num_confusion
ratio = num_good / (num_good + num_confusion) * 100.
return ratio / 100.
def get_total(bag):
return sum([len(subbag) for subbag in bag.values()])
def compute_entropy(bag):
total = get_total(bag)
freq = [len(subbag)/total for subbag in bag.values()]
freq = np.array(freq)
h = -(freq * np.log2(freq)).sum()
return h
def print_histo(histo, edges):
for histo_bin in zip(edges, edges[1:], histo.tolist()):
print('[%.3f,%.3f]=%.3f'%histo_bin, end=' ')
print('\n')
def compute_communities_entropy(nodes, colors, labels, verbose):
communities = collections.defaultdict(lambda: collections.defaultdict(list))
classes = collections.defaultdict(lambda: collections.defaultdict(list))
for node in nodes:
com, label = colors[node], int(labels[node])
communities[com][label].append(node)
classes[label][com].append(node)
com_entropy = np.array([compute_entropy(com) for com in communities.values()])
cla_entropy = np.array([compute_entropy(cla) for cla in classes.values()])
totals = [get_total(com) for com in communities.values()]
avg_cla_entropy = np.mean(cla_entropy)
avg_com_entropy = np.mean(com_entropy)
w_com_entropy = np.average(com_entropy, weights=totals)
hist_cla_entropy = np.histogram(cla_entropy, bins=5, density=True)
hist_com_entropy = np.histogram(com_entropy, bins=5, density=True)
weights = [total / sum(totals) for total in totals]
histo_w_com_entropy = np.histogram(com_entropy, bins=5, weights=weights, density=True)
if verbose:
print('')
print('Communities %d\n'%len(communities))
print('Entropy per class: ', avg_cla_entropy)
print_histo(*hist_cla_entropy)
print('Entropy per community: ', avg_com_entropy)
print_histo(*hist_com_entropy)
print('Entropy per community, weighted: ', w_com_entropy)
print_histo(*histo_w_com_entropy)
avgs = avg_cla_entropy, avg_com_entropy, w_com_entropy
histos = hist_cla_entropy, hist_com_entropy, histo_w_com_entropy
return [len(communities)] + list(zip(avgs, histos))
def color(dendrogram, node, level):
key = node
for i in range(level+1):
key = dendrogram[level][key]
return key
def louvain_dendrogram(recorder, graph, labels, params, print_details=False):
dendrogram = louvain.generate_dendrogram(graph)
colors = {node: node for node in graph}
infos = []
if print_details:
print('\n', 'Level', ' ', 'Mixed Communities', ' ', 'Splitted Classes', ' ', 'Good Communities', ' ', 'Ratio')
for level in range(len(dendrogram)):
colors = {node: dendrogram[level][color] for node, color in colors.items()}
if params.communities == 'pure':
info = compute_pure(graph.nodes, colors, labels)
elif params.communities == 'entropy':
info = compute_communities_entropy(graph.nodes, colors, labels, verbose=False)
infos.append(info)
return infos
def build_community_graph(params, examples, labels, print_graph=False):
num_neighbors, regular = params.num_neighbors, params.regular
edges = edges_from_loss_fn(examples, cosine_loss, num_neighbors=num_neighbors,
regular=regular,
normalize_weights=True,
substract_mean=True,
exponent=True)
if params.higher_order:
num_nodes = len(set([int(edge[1][0]) for edge in edges]))
adj = np.zeros(shape=(num_nodes, num_nodes))
for w, (a, b) in edges:
adj[a,b] = adj
adj = np.linalg.power(params.alpha * np.eyes(N=num_nodes) + adj, params.kappa)
edges = [(a, b, w) for w, (a, b) in edges]
graph = nx.Graph()
graph.add_weighted_edges_from(edges)
if print_graph:
nx.draw_spring(graph)
plt.show()
return graph
def monitore_volume(recorder, train_set, test_set, train_labels, test_labels, params):
examples = torch.cat([train_set, test_set], dim=0)
labels = torch.cat([train_labels, test_labels], dim=0)
graph = build_community_graph(params, examples, labels)
if params.intersection_measure == 'stoer_wagner':
volume = stoer_wagner_volume(recorder, graph, labels, params)
elif params.intersection_measure == 'minimum_cut':
volume = min_cut_volume(recorder, graph, labels, params)
elif params.intersection_measure == 'kernighan':
volume = kernighan(recorder, graph, labels, params)
elif params.intersection_measure == 'louvain_dendrogram':
infos = louvain_dendrogram(recorder, graph, labels, params)
return infos
else:
raise ValueError
recorder.record_volume_error(volume)
def infos_per_level(graph, labels, params, verbose=True):
dendrogram = louvain.generate_dendrogram(graph)
colors = {node: node for node in graph}
infos = []
for level in range(len(dendrogram)):
colors = {node: dendrogram[level][color] for node, color in colors.items()}
info = compute_communities_entropy(graph.nodes, colors, labels, verbose=verbose)
infos.append(info)
return infos
def get_draw_options(big_graph, bipartite):
w_max = float(np.max([w[2] for w in big_graph.edges.data('weight')]))
colors = [w[2]/w_max for w in big_graph.edges.data('weight')]
edge_labels = {w[:2]:('%.3f'%w[2]) for w in big_graph.edges.data('weight')}
if bipartite is None:
node_color = '#A0CBE2'
else:
node_color = ['#1A4081' if node < bipartite else '#E37373' for node in big_graph]
return {
"node_color": node_color,
"edge_color": colors,
"width": 4,
"edge_cmap": plt.cm.Reds,
"with_labels": True,
}, edge_labels
def print_big_graph(params, mean_pos, edges, avg_degree=20, tsne_pos=False):
bipartite = 64 if '&' in params.dataset else None
edges.sort(key=lambda t: t[2], reverse=True)
max_edges = int(len(mean_pos) * avg_degree)
edges = edges[:max_edges]
big_graph = nx.Graph()
big_graph.add_weighted_edges_from(edges)
options, edge_labels = get_draw_options(big_graph, bipartite)
if tsne_pos:
mean_pos_array = np.concatenate(list(mean_pos.values()), axis=0)
tsne = manifold.TSNE()
print(mean_pos_array)
mean_pos_array = tsne.fit_transform(mean_pos_array)
pos = dict()
for i, key in enumerate(mean_pos):
pos[key] = mean_pos_array[i]
elif bipartite is not None:
part_1 = [node for node in big_graph if node < bipartite]
pos = nx.drawing.layout.bipartite_layout(big_graph, part_1, align='horizontal')
else:
# pos = nx.spring_layout(big_graph)
pos = nx.spectral_layout(big_graph)
nx.draw_networkx_nodes(big_graph, pos=pos, **options)
nx.draw_networkx_labels(big_graph, pos, labels={node:str(node) for node in big_graph})
nx.draw_networkx_edge_labels(big_graph, edge_labels=edge_labels, pos=pos, font_size=8)
name = params.intersection_measure + '_communities_' + str(-params.ladder) + '_' + str(params.num_neighbors)
nx.drawing.nx_agraph.write_dot(big_graph, os.path.join('graphs', name+'.dot'))
plt.savefig(os.path.join('graphs', name+'.pdf'))
plt.clf()
# plt.show()
print('')
def add_class(mean_pos, label, false_label, examples, labels):
if label in mean_pos:
return
class_examples = examples[labels == false_label]
mean_pos[label] = torch.mean(class_examples, dim=0, keepdim=True).numpy()
def monitore_communities(data_path, params, num_repetitions=5):
parts = params.parts if '&' in params.dataset else None
all_pairs = get_all_pairs_datasets(data_path, params.n_way, params.crop, parts)
edges = []
mean_pos = dict()
total_pairs = next(all_pairs)
progress = tqdm(total=total_pairs, leave=True)
for (examples, labels, label_a, label_b, false_a, false_b) in all_pairs:
add_class(mean_pos, label_a, false_a, examples, labels)
add_class(mean_pos, label_b, false_b, examples, labels)
graph = build_community_graph(params, examples, labels)
h_seq = []
for _ in range(num_repetitions):
infos = infos_per_level(graph, labels, params, verbose=False)
ladder = max(len(infos) + params.ladder, 0)
h_seq.append(infos[ladder][-1][0]) # last level
h_avg = float(np.mean(h_seq))
h_max = float(np.log2(params.n_way))
r = h_avg / h_max
r = min(1-1e-3, r) # crop
weight = r # / (1 - r) # similarity score
edges.append((label_a, label_b, weight))
desc = ' '.join([str(label_a), str(label_b), str(weight)])
progress.set_description(desc=desc)
progress.update()
progress.close()
print_big_graph(params, mean_pos, edges)
def monitore_regression(data_path, params, num_repetitions=20):
all_pairs = get_all_pairs_datasets(data_path, params.n_way, params.crop, params.parts)
edges = []
mean_pos = dict()
for (examples, labels, label_a, label_b, false_a, false_b) in all_pairs:
add_class(mean_pos, label_a, false_a, examples, labels)
add_class(mean_pos, label_b, false_b, examples, labels)
acc_seq = []
for _ in range(num_repetitions):
train_test = split_train_test(examples, labels, params.n_shot, params.n_val)
train_set, train_labels, test_set, test_labels = train_test
train_acc, test_acc = features_classification(train_set, train_labels,
test_set, test_labels,
params.n_way, params.classifier,
params.origin_normalization, params)
acc = 100. - test_acc # error monitoring instead of accuracy
acc_seq.append(acc) # last level
acc_avg = float(np.mean(acc_seq))
acc_max = float(100.)
r = acc_avg / acc_max
r = min(1-1e-5, r) # crop
weight = r # / (1 - r) # similarity score
edges.append((label_a, label_b, weight))
print(label_a, label_b, weight, acc_avg)
print_big_graph(params, mean_pos, edges)
def gather_edges(graph, ways):
edges = []
for str_edge in graph.edges.data('weight'):
edge = int(str_edge[0]), int(str_edge[1]), float(str_edge[2])
if edge[0] in ways and edge[1] in ways:
edges.append(edge)
return edges
def get_subgraph_weight(edges):
return sum([edge[2] for edge in edges])
def get_worse_clusters(params, big_graph, data_path):
_, original_labels = get_dataset_from_datapath(data_path)
num_labels, n_sample_per_label = get_labels_stats(original_labels)
combinations_iter = itertools.combinations(list(range(big_graph.number_of_nodes())), params.n_way)
combinations = []
for i, ways in enumerate(combinations_iter):
real_ways = [int(original_labels[i*n_sample_per_label]) for i in ways]
combinations.append((get_subgraph_weight(gather_edges(big_graph, real_ways)), ways))
combinations.sort(key=(lambda t: t[0]), reverse=True)
return combinations
def write_labels(signal, nodes):
for node in nodes:
if nodes[node]['label'] is None:
continue
signal[node] = nodes[node]['label']
def create_signal(nodes, n_way):
num_nodes = len(nodes)
signal = np.full(shape=(num_nodes, n_way), fill_value=(1./n_way))
write_labels(signal, nodes)
return signal
def bhattacharyya_dist(signal, temperature):
sqrt_signal = np.sqrt(signal)
bhattacharyya = np.einsum('ip,jp->ij', sqrt_signal, sqrt_signal)
bhattacharyya = -np.log(np.maximum(bhattacharyya, epsilon_a))
bhattacharyya = scipy.special.softmax(adj * bhattacharyya, axis=1)
return bhattacharyya
def kl_metric(signal, temperature):
eps = 0.001
num_labels = int(signal.shape[1])
signal = np.log(np.maximum(signal, eps))
signal = scipy.special.softmax(signal * temperature, axis=1)
h = np.sum(signal * np.log(num_labels * np.maximum(signal, eps)), axis=1)
num_nodes = int(signal.shape[0])
h_cross = np.zeros(shape=(num_nodes, num_nodes), dtype=np.float32)
for i in range(num_nodes):
for j in range(num_nodes):
h_cross[i,j] = float(h[j])
return h_cross
def graph_mean_shift(graph, n_way, num_iterations_max=1):
signal = create_signal(graph.nodes, n_way)
adj = nx.adjacency_matrix(graph).toarray()
adj = adj + np.eye(N=int(adj.shape[0]))
adj = adj + 1.*(adj != 0.) # from [-1, 1] to [0, 2]
adj_temperature = 1.
adj = scipy.special.softmax(adj * adj_temperature, axis=1)
epsilon = 0.001
metric_temperature = 1.
for _ in range(num_iterations_max):
metric = kl_metric(signal, metric_temperature)
wcoeff = np.maximum(metric, epsilon) * adj
wcoeff = wcoeff / np.sum(wcoeff, axis=1)
signal = wcoeff @ signal
write_labels(signal, graph.nodes)
signal = signal / np.sum(signal, axis=1, keepdims=True)
return signal
def create_graph_mean_shift(params, train_set, train_labels, test_set, test_labels):
examples = torch.cat([train_set, test_set])
labels = torch.cat([train_labels, test_labels])
graph = build_community_graph(params, examples, labels)
for node in graph.nodes:
graph.nodes[node]['label'] = None
num_labels = len(set(train_labels.tolist()))
for node in range(train_labels.shape[0]):
dirac = np.zeros(shape=(num_labels))
label = int(train_labels[node])
dirac[label] = 1.
graph.nodes[node]['label'] = dirac
return graph
def get_acc(predicted, logits, labels, train_set_size, test_set_size, loss):
train_acc = (labels[:train_set_size] == predicted[:train_set_size]).sum()
test_acc = (labels[train_set_size:] == predicted[train_set_size:]).sum()
train_acc *= (100. / train_set_size)
test_acc *= (100. / test_set_size)
if loss:
prob = scipy.special.softmax(logits, axis=1)
epsilon = 0.001
h = - prob * np.log(np.maximum(prob, epsilon))
h = np.sum(h, axis=1)
h = np.mean(h)
return train_acc, test_acc, float(h)
return train_acc, test_acc
def raw_examples_mean_shift(params, train_set, train_labels, test_set, test_labels, loss):
graph = create_graph_mean_shift(params, train_set, train_labels, test_set, test_labels)
with np.printoptions(threshold=np.inf):
signal = graph_mean_shift(graph, params.n_way, num_iterations_max=100)
labels = np.concatenate([train_labels, test_labels])
predicted = np.argmax(signal, axis=1)
train_set_size = int(train_set.shape[0])
test_set_size = int(test_set.shape[0])
return get_acc(predicted, signal, labels, train_set_size, test_set_size, loss)
def get_edges_between(graph, part_a, part_b):
edges = []
for node in part_a:
for other in graph.neighbors(node):
if other in part_b:
edges.append(graph[node][other]['weight'])
return max(sum(edges), 0.)
def meta_graph(graph, colors):
communities = collections.defaultdict(list)
for node, com in colors.items():
communities[com].append(node)
meta = nx.Graph()
for i, com_a in enumerate(communities):
meta.add_node(com_a)
for com_b in list(communities.keys())[:i]:
part_a, part_b = communities[com_a], communities[com_b]
edge = get_edges_between(graph, part_a, part_b)
if edge != 0:
meta.add_edge(com_a, com_b, weight=edge)
return meta
def create_labels_mask_metagraph(graph, colors, labels, n_shot, n_val):
num_communities = len(set(colors.values()))
num_labels = len(set(labels.numpy().tolist()))
histo = np.zeros(shape=(num_communities, num_labels), dtype=np.float32)
mask = [False] * num_communities
for node in range(int(labels.shape[0])):
color = colors[node]
label = labels[node]
histo[color, label] += 1.
if node < n_shot: # training set: we are certain about this measurement
mask[color] = True
histo = histo / np.sum(histo, axis=1, keepdims=True) # no null element guaranteed
return histo, np.array(mask)
def get_examples_predicted(colors, predicted_communities):
predicted = [None] * len(colors)
for node in colors:
color = colors[node]
predicted[node] = predicted_communities[color]
return np.array(predicted)
def thikonov_communities(params, train_set, train_labels, test_set, test_labels, loss):
examples = torch.cat([train_set, test_set])
labels = torch.cat([train_labels, test_labels])
graph = build_community_graph(params, examples, labels)
dendrogram = louvain.generate_dendrogram(graph)
colors = {node: node for node in graph}
max_level = 1 # len(dendrogram)
for level in range(max_level):
colors = {node: dendrogram[level][color] for node, color in colors.items()}
meta = meta_graph(graph, colors)
meta = pygsp.graphs.Graph.from_networkx(meta)
n_shot, n_val = int(train_labels.shape[0]), int(test_labels.shape[0])
com_labels, mask = create_labels_mask_metagraph(meta, colors, labels, n_shot, n_val)
logits_communities = pygsp.learning.regression_tikhonov(meta, np.copy(com_labels), mask, tau=0.)
predicted_communities = np.argmax(logits_communities, axis=1)
predicted = get_examples_predicted(colors, predicted_communities)
return get_acc(predicted, logits_communities, labels.numpy(), n_shot, n_val, loss)
def node_label(node):
if node < 64:
return node
if node < 80:
return node - 64
return node-64-16
def init_plot():
plt.ion()
fig, ax = plt.subplots()
plt.xlim(0, 5)
plt.ylim(0, 50)
sc = ax.scatter([], [], marker='x')
plt.xlabel('Sum of edge weights', fontsize='x-large')
plt.ylabel('Error (%)', fontsize='x-large')
# plt.title('Error as function of edge weights')
fig.canvas.draw_idle()
plt.pause(0.1)
return fig, sc
def add_point(fig, sc, metric, accs):
sc.set_offsets(np.c_[np.array(metric), np.array(accs)])
fig.canvas.draw_idle()
plt.pause(0.05)
def monitore_arena(data_path, params, num_repetitions=10000):
path = os.path.join('graphs', params.dot_name)
dot_graph = nx.drawing.nx_agraph.read_dot(path)
edges = [(int(str_edge[0]), int(str_edge[1]), float(str_edge[2])) for str_edge in dot_graph.edges.data('weight')]
edges.sort(key=lambda t: t[2], reverse=True)
max_edges = len(edges)#//60
edges = edges[:max_edges]
print(edges)
big_graph = nx.Graph()
big_graph.add_weighted_edges_from(edges)
bipartite = 64 if '&' in params.dataset else None
if params.plot:
if bipartite:
part_1 = [node for node in big_graph if node < bipartite]
pos = nx.drawing.layout.bipartite_layout(big_graph, part_1, align='horizontal')
else:
pos = nx.spring_layout(big_graph)
options, edge_labels = get_draw_options(big_graph, bipartite)
nx.draw_networkx_nodes(big_graph, pos=pos, **options)
nx.draw_networkx_edges(big_graph, pos=pos, **options)
nx.draw_networkx_labels(big_graph, pos, labels={node:str(node_label(node)) for node in big_graph})
# nx.draw_networkx_edge_labels(big_graph, edge_labels=edge_labels, pos=pos, font_size=8)
plt.show()
weights = []
accs = []
if params.worse_only:
clusters = get_worse_clusters(params, big_graph, data_path)
progress = tqdm(total=num_repetitions, leave=True)
fig, scs = init_plot()
for repet in range(num_repetitions):
ways = clusters[repet][1] if params.worse_only else None
train_test, ways = get_train_test_datasets_labels(data_path, params.n_way, params.n_shot, params.n_val, ways=ways)
train_set, train_labels, test_set, test_labels = train_test
edges = gather_edges(big_graph, ways)
edges_weights = get_subgraph_weight(edges)
weights.append(edges_weights)
train_acc, test_acc = features_classification(train_set, train_labels,
test_set, test_labels,
params.n_way, 'logistic_regression',
params.origin_normalization, params)
error_rate = 100. - test_acc
accs.append(error_rate) # error rate
if (repet+1) % 100 == 0:
add_point(fig, scs, weights, accs)
desc = ' '.join([str(train_acc), str(ways), str(edges_weights), str(test_acc)])
progress.set_description(desc=desc)
progress.update()
all_results = np.array(list(zip(weights, accs)))
np.savetxt(os.path.join('graphs', 'correlation.txt'), all_results, delimiter=',')
progress.close()
fig.canvas.draw_idle()
fig.savefig(os.path.join('graphs', 'correlation.eps'), format='eps')
plt.pause(10)
# plt.close(fig)
print('mean weight=', np.mean(weights))
print('mean_acc=', 100-np.mean(accs))
for func, func_name in zip([spearmanr, np.corrcoef], ['spearmanr', 'corrcoef']):
corrcoefmatrix = func(weights, accs)
print('weights', ' ', func_name, ' => ', corrcoefmatrix)
|
Formal statement is: lemma int_imp_algebraic_int: assumes "x \<in> \<int>" shows "algebraic_int x" Informal statement is: Every integer is an algebraic integer.
|
" Crazy in Love " was re @-@ recorded by Beyoncé for the film Fifty Shades of Grey ( 2015 ) and used for its trailer which was released on July 24 , 2014 . This slowed @-@ down version was produced by Boots with violin arrangements by Margot , both of whom worked on Beyoncé 's fifth studio album . Margot said , " It inspires me to work on other artists ' songs [ because ] it pushes my boundaries in a direction that I wouldn ’ t necessarily come up with . Obviously I know how ' Crazy in Love ' goes , but I knew there was the possibility her vocals would be different . It 's almost more vulnerable and beautiful this way , because you do do crazy things when you fall in love . To hear the mood reversed and flipped makes it even more powerful . "
|
/-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
! This file was ported from Lean 3 source module data.rbtree.basic
! leanprover-community/mathlib commit 5cb17dd1617d2dc55eb17777c3dcded3306fadb5
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Rbtree.Init
import Mathbin.Logic.IsEmpty
import Mathbin.Tactic.Interactive
universe u
/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/
unsafe def tactic.interactive.blast_disjs : tactic Unit :=
sorry
#align tactic.interactive.blast_disjs tactic.interactive.blast_disjs
namespace Rbnode
variable {α : Type u}
open Color Nat
inductive IsNodeOf : Rbnode α → Rbnode α → α → Rbnode α → Prop
| of_red (l v r) : is_node_of (red_node l v r) l v r
| of_black (l v r) : is_node_of (black_node l v r) l v r
#align rbnode.is_node_of Rbnode.IsNodeOf
def Lift (lt : α → α → Prop) : Option α → Option α → Prop
| some a, some b => lt a b
| _, _ => True
#align rbnode.lift Rbnode.Lift
inductive IsSearchable (lt : α → α → Prop) : Rbnode α → Option α → Option α → Prop
| leaf_s {lo hi} (hlt : Lift lt lo hi) : is_searchable leaf lo hi
|
red_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) :
is_searchable (red_node l v r) lo hi
|
black_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) :
is_searchable (black_node l v r) lo hi
#align rbnode.is_searchable Rbnode.IsSearchable
/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/
unsafe def is_searchable_tactic : tactic Unit :=
sorry
#align rbnode.is_searchable_tactic rbnode.is_searchable_tactic
open Rbnode (Mem)
open IsSearchable
section IsSearchableLemmas
variable {lt : α → α → Prop}
theorem lo_lt_hi {t : Rbnode α} {lt} [IsTrans α lt] :
∀ {lo hi}, IsSearchable lt t lo hi → Lift lt lo hi :=
by
induction t <;> intro lo hi hs
case leaf => cases hs; assumption
all_goals
cases hs
have h₁ := t_ih_lchild hs_hs₁
have h₂ := t_ih_rchild hs_hs₂
cases lo <;> cases hi <;> simp [lift] at *
apply trans_of lt h₁ h₂
#align rbnode.lo_lt_hi Rbnode.lo_lt_hi
/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/
theorem isSearchable_of_isSearchable_of_incomp [IsStrictWeakOrder α lt] {t} :
∀ {lo hi hi'} (hc : ¬lt hi' hi ∧ ¬lt hi hi') (hs : IsSearchable lt t lo (some hi)),
IsSearchable lt t lo (some hi') :=
by
classical
induction t <;> intros <;>
run_tac
is_searchable_tactic
· cases lo <;> simp_all [lift]
apply lt_of_lt_of_incomp
assumption
exact ⟨hc.2, hc.1⟩
all_goals apply t_ih_rchild hc hs_hs₂
#align rbnode.is_searchable_of_is_searchable_of_incomp Rbnode.isSearchable_of_isSearchable_of_incomp
/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/
theorem isSearchable_of_incomp_of_isSearchable [IsStrictWeakOrder α lt] {t} :
∀ {lo lo' hi} (hc : ¬lt lo' lo ∧ ¬lt lo lo') (hs : IsSearchable lt t (some lo) hi),
IsSearchable lt t (some lo') hi :=
by
classical
induction t <;> intros <;>
run_tac
is_searchable_tactic
· cases hi <;> simp_all [lift]
apply lt_of_incomp_of_lt
assumption
assumption
all_goals apply t_ih_lchild hc hs_hs₁
#align rbnode.is_searchable_of_incomp_of_is_searchable Rbnode.isSearchable_of_incomp_of_isSearchable
/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/
theorem isSearchable_some_low_of_isSearchable_of_lt {t} [IsTrans α lt] :
∀ {lo hi lo'} (hlt : lt lo' lo) (hs : IsSearchable lt t (some lo) hi),
IsSearchable lt t (some lo') hi :=
by
induction t <;> intros <;>
run_tac
is_searchable_tactic
· cases hi <;> simp_all [lift]
apply trans_of lt hlt
assumption
all_goals apply t_ih_lchild hlt hs_hs₁
#align rbnode.is_searchable_some_low_of_is_searchable_of_lt Rbnode.isSearchable_some_low_of_isSearchable_of_lt
/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/
theorem isSearchable_none_low_of_isSearchable_some_low {t} :
∀ {y hi} (hlt : IsSearchable lt t (some y) hi), IsSearchable lt t none hi :=
by
induction t <;> intros <;>
run_tac
is_searchable_tactic
· simp [lift]
all_goals apply t_ih_lchild hlt_hs₁
#align rbnode.is_searchable_none_low_of_is_searchable_some_low Rbnode.isSearchable_none_low_of_isSearchable_some_low
/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/
theorem isSearchable_some_high_of_isSearchable_of_lt {t} [IsTrans α lt] :
∀ {lo hi hi'} (hlt : lt hi hi') (hs : IsSearchable lt t lo (some hi)),
IsSearchable lt t lo (some hi') :=
by
induction t <;> intros <;>
run_tac
is_searchable_tactic
· cases lo <;> simp_all [lift]
apply trans_of lt
assumption
assumption
all_goals apply t_ih_rchild hlt hs_hs₂
#align rbnode.is_searchable_some_high_of_is_searchable_of_lt Rbnode.isSearchable_some_high_of_isSearchable_of_lt
/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/
theorem isSearchable_none_high_of_isSearchable_some_high {t} :
∀ {lo y} (hlt : IsSearchable lt t lo (some y)), IsSearchable lt t lo none :=
by
induction t <;> intros <;>
run_tac
is_searchable_tactic
· cases lo <;> simp [lift]
all_goals apply t_ih_rchild hlt_hs₂
#align rbnode.is_searchable_none_high_of_is_searchable_some_high Rbnode.isSearchable_none_high_of_isSearchable_some_high
theorem range [IsStrictWeakOrder α lt] {t : Rbnode α} {x} :
∀ {lo hi}, IsSearchable lt t lo hi → Mem lt x t → Lift lt lo (some x) ∧ Lift lt (some x) hi :=
by
classical
induction t
case leaf => simp [mem]
all_goals
-- red_node and black_node are identical
intro lo hi h₁ h₂
cases h₁
simp only [mem] at h₂
have val_hi : lift lt (some t_val) hi :=
by
apply lo_lt_hi
assumption
have lo_val : lift lt lo (some t_val) :=
by
apply lo_lt_hi
assumption
cases_type*or.1
· have h₃ : lift lt lo (some x) ∧ lift lt (some x) (some t_val) :=
by
apply t_ih_lchild
assumption
assumption
cases' h₃ with lo_x x_val
constructor
show lift lt lo (some x)
· assumption
show lift lt (some x) hi
· cases' hi with hi <;> simp [lift] at *
apply trans_of lt x_val val_hi
· cases h₂
cases' lo with lo <;> cases' hi with hi <;> simp [lift] at *
· apply lt_of_incomp_of_lt _ val_hi
simp [*]
· apply lt_of_lt_of_incomp lo_val
simp [*]
constructor
· apply lt_of_lt_of_incomp lo_val
simp [*]
· apply lt_of_incomp_of_lt _ val_hi
simp [*]
· have h₃ : lift lt (some t_val) (some x) ∧ lift lt (some x) hi :=
by
apply t_ih_rchild
assumption
assumption
cases' h₃ with val_x x_hi
cases' lo with lo <;> cases' hi with hi <;> simp [lift] at *
· assumption
· apply trans_of lt lo_val val_x
constructor
· apply trans_of lt lo_val val_x
· assumption
#align rbnode.range Rbnode.range
theorem lt_of_mem_left [IsStrictWeakOrder α lt] {y : α} {t l r : Rbnode α} :
∀ {lo hi}, IsSearchable lt t lo hi → IsNodeOf t l y r → ∀ {x}, Mem lt x l → lt x y :=
by
intro _ _ hs hn x hm; cases hn <;> cases hs
all_goals exact (range hs_hs₁ hm).2
#align rbnode.lt_of_mem_left Rbnode.lt_of_mem_left
theorem lt_of_mem_right [IsStrictWeakOrder α lt] {y : α} {t l r : Rbnode α} :
∀ {lo hi}, IsSearchable lt t lo hi → IsNodeOf t l y r → ∀ {z}, Mem lt z r → lt y z :=
by
intro _ _ hs hn z hm; cases hn <;> cases hs
all_goals exact (range hs_hs₂ hm).1
#align rbnode.lt_of_mem_right Rbnode.lt_of_mem_right
theorem lt_of_mem_left_right [IsStrictWeakOrder α lt] {y : α} {t l r : Rbnode α} :
∀ {lo hi},
IsSearchable lt t lo hi → IsNodeOf t l y r → ∀ {x z}, Mem lt x l → Mem lt z r → lt x z :=
by
intro _ _ hs hn x z hm₁ hm₂; cases hn <;> cases hs
all_goals
have h₁ := range hs_hs₁ hm₁
have h₂ := range hs_hs₂ hm₂
exact trans_of lt h₁.2 h₂.1
#align rbnode.lt_of_mem_left_right Rbnode.lt_of_mem_left_right
end IsSearchableLemmas
inductive IsRedBlack : Rbnode α → Color → Nat → Prop
| leaf_rb : is_red_black leaf black 0
|
red_rb {v l r n} (rb_l : is_red_black l black n) (rb_r : is_red_black r black n) :
is_red_black (red_node l v r) red n
|
black_rb {v l r n c₁ c₂} (rb_l : is_red_black l c₁ n) (rb_r : is_red_black r c₂ n) :
is_red_black (black_node l v r) black (succ n)
#align rbnode.is_red_black Rbnode.IsRedBlack
open IsRedBlack
theorem depth_min : ∀ {c n} {t : Rbnode α}, IsRedBlack t c n → n ≤ depth min t :=
by
intro c n' t h
induction h
case leaf_rb => exact le_refl _
case red_rb =>
simp [depth]
have : min (depth min h_l) (depth min h_r) ≥ h_n := by apply le_min <;> assumption
apply le_succ_of_le
assumption
case black_rb =>
simp [depth]
apply succ_le_succ
apply le_min <;> assumption
#align rbnode.depth_min Rbnode.depth_min
private def upper : Color → Nat → Nat
| red, n => 2 * n + 1
| black, n => 2 * n
#align rbnode.upper rbnode.upper
private theorem upper_le : ∀ c n, upper c n ≤ 2 * n + 1
| red, n => le_refl _
| black, n => by apply le_succ
#align rbnode.upper_le rbnode.upper_le
theorem depth_max' : ∀ {c n} {t : Rbnode α}, IsRedBlack t c n → depth max t ≤ upper c n :=
by
intro c n' t h
induction h
case leaf_rb => simp [max, depth, upper, Nat.mul_zero]
case
red_rb =>
suffices succ (max (depth max h_l) (depth max h_r)) ≤ 2 * h_n + 1 by simp_all [depth, upper]
apply succ_le_succ
apply max_le <;> assumption
case
black_rb =>
have : depth max h_l ≤ 2 * h_n + 1 := le_trans h_ih_rb_l (upper_le _ _)
have : depth max h_r ≤ 2 * h_n + 1 := le_trans h_ih_rb_r (upper_le _ _)
suffices new : max (depth max h_l) (depth max h_r) + 1 ≤ 2 * h_n + 2 * 1
· simp_all [depth, upper, succ_eq_add_one, Nat.left_distrib]
apply succ_le_succ
apply max_le <;> assumption
#align rbnode.depth_max' Rbnode.depth_max'
theorem depth_max {c n} {t : Rbnode α} (h : IsRedBlack t c n) : depth max t ≤ 2 * n + 1 :=
le_trans (depth_max' h) (upper_le _ _)
#align rbnode.depth_max Rbnode.depth_max
theorem balanced {c n} {t : Rbnode α} (h : IsRedBlack t c n) : depth max t ≤ 2 * depth min t + 1 :=
by
have : 2 * depth min t + 1 ≥ 2 * n + 1 :=
by
apply succ_le_succ
apply Nat.mul_le_mul_left
apply depth_min h
apply le_trans
apply depth_max h
apply this
#align rbnode.balanced Rbnode.balanced
end Rbnode
|
State Before: α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
⊢ IsOpen {a} ↔ 𝓝 a = pure a State After: case mp
α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
⊢ IsOpen {a} → 𝓝 a = pure a
case mpr
α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
⊢ 𝓝 a = pure a → IsOpen {a} Tactic: constructor State Before: case mp
α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
⊢ IsOpen {a} → 𝓝 a = pure a State After: case mp
α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
h : IsOpen {a}
⊢ 𝓝 a = pure a Tactic: intro h State Before: case mp
α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
h : IsOpen {a}
⊢ 𝓝 a = pure a State After: α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
h : IsOpen {a}
⊢ 𝓝 a ≤ pure a Tactic: apply le_antisymm _ (pure_le_nhds a) State Before: α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
h : IsOpen {a}
⊢ 𝓝 a ≤ pure a State After: α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
h : IsOpen {a}
⊢ {a} ∈ 𝓝 a Tactic: rw [le_pure_iff] State Before: α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
h : IsOpen {a}
⊢ {a} ∈ 𝓝 a State After: no goals Tactic: exact h.mem_nhds (mem_singleton a) State Before: case mpr
α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
⊢ 𝓝 a = pure a → IsOpen {a} State After: case mpr
α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
h : 𝓝 a = pure a
⊢ IsOpen {a} Tactic: intro h State Before: case mpr
α : Type u
β : Type v
ι : Sort w
a✝ : α
s s₁ s₂ t : Set α
p p₁ p₂ : α → Prop
inst✝ : TopologicalSpace α
a : α
h : 𝓝 a = pure a
⊢ IsOpen {a} State After: no goals Tactic: simp [isOpen_iff_nhds, h]
|
-- This is an example illustrating a problem with unification when using Category based on Sort, rather than Type.
-- We set up some tactics:
open tactic
open smt_tactic
meta def smt_eblast : tactic unit := using_smt $ try eblast
meta def smt_ematch : tactic unit := using_smt $ intros >> add_lemmas_from_facts >> try ematch
meta def blast : tactic unit := intros >> try dsimp >> try simp >> try smt_eblast
notation `♮` := by abstract { blast }
attribute [reducible] cast
@[reducible] def {u} auto_cast {α β : Type u} {h : α = β} (a : α) := cast h a
@[simp] lemma {u} auto_cast_identity {α : Type u} (a : α) : @auto_cast α α (by smt_ematch) a = a := ♮
notation `⟦` p `⟧` := @auto_cast _ _ (by smt_ematch) p
-- And now a minimal example:
universe variables u v
structure Category :=
(Obj : Sort u)
(Hom : Obj → Obj → Sort v)
(identity : Π X : Obj, Hom X X)
(compose : Π { X Y Z : Obj }, Hom X Y → Hom Y Z → Hom X Z)
(left_identity : ∀ { X Y : Obj } (f : Hom X Y), compose (identity X) f = f)
attribute [simp] Category.left_identity
universe variables u1 v1 u2 v2
structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) :=
(onObjects : C^.Obj → D^.Obj)
(onMorphisms : Π { X Y : C^.Obj },
C^.Hom X Y → D^.Hom (onObjects X) (onObjects Y))
set_option pp.all true
def rewriteMorphism { C : Category.{u1 v1} }
{ D : Category.{u2 v2} }
{ F G : Functor C D }
{ X Y : C^.Obj }
( objectWitness : ∀ X : C^.Obj, F^.onObjects X = G^.onObjects X )
( f : D^.Hom (F^.onObjects X) (F^.onObjects Y) ) : D^.Hom (G^.onObjects X) (G^.onObjects Y) :=
begin
rewrite (objectWitness X) at f,
rewrite (objectWitness Y) at f,
exact f
end
lemma Functors_pointwise_equal
{ C : Category.{u1 v1} }
{ D : Category.{u2 v2} }
{ F G : Functor C D }
( objectWitness : ∀ X : C^.Obj, F^.onObjects X = G^.onObjects X )
( morphismWitness : ∀ X Y : C^.Obj, ∀ f : C^.Hom X Y, rewriteMorphism objectWitness (F^.onMorphisms f) = G^.onMorphisms f ) : F = G :=
begin
induction F with F_onObjects F_onMorphisms,
induction G with G_onObjects G_onMorphisms,
assert h_objects : F_onObjects = G_onObjects, exact funext objectWitness,
subst h_objects,
assert h_morphisms : @F_onMorphisms = @G_onMorphisms,
apply funext, intro X, apply funext, intro Y, apply funext, intro f,
exact morphismWitness X Y f,
subst h_morphisms
end
@[reducible] definition IdentityFunctor ( C: Category ) : Functor C C :=
{
onObjects := id,
onMorphisms := λ _ _ f, f
}
@[reducible] definition FunctorComposition { C D E : Category } ( F : Functor C D ) ( G : Functor D E ) : Functor C E :=
{
onObjects := λ X, G^.onObjects (F^.onObjects X),
onMorphisms := λ _ _ f, G^.onMorphisms (F^.onMorphisms f)
}
definition CategoryOfCategoriesAndFunctors : Category := {
Obj := Category,
Hom := λ C D, Functor C D,
identity := λ C, IdentityFunctor C,
compose := λ _ _ _ F G, FunctorComposition F G,
left_identity := begin
intros,
fapply Functors_pointwise_equal,
intros,
dsimp,
refl,
intros,
dsimp,
refl
end
}
|
Brand new 3 blade Bolly propeller available (worth $2150), The original prop and spinner is still serviceable.
Garmin 296 (colour screen) available, depending on final agreed price.
Ipad (as new), with extra 2 years warranty for use with Oz Runways.
Rotax 912 starts first time every time and she flies beautifully. An easy aircraft to learn to fly and land.
Perfect aircraft for low or high time pilot.
Selling due to new aircraft coming soon.
Full price $30,000 AUD, with everything included.
Make an offer on this excellent aircraft.
|
From Coq Require Import ZArith Reals QArith Qcanon micromega.Lia micromega.Lra.
From BY.Hierarchy Require Import CommutativeMonoid IntegralDomain.
Global Arguments equiv {_ _} _ _ / : assert.
Global Arguments op1 {_ _} _ _ / : assert.
Global Arguments op2 {_ _} _ _ / : assert.
Global Arguments id1 {_ _} / : assert.
Global Arguments id2 {_ _} / : assert.
Global Arguments inv1 {_ _} _ / : assert.
Global Arguments inv2 {_ _} _ / : assert.
Global Arguments left_act {_ _ _} _ _ / : assert.
Global Arguments right_act {_ _ _} _ _ / : assert.
Section nat.
Global Instance Nateq_equiv : Equiv nat := eq.
Global Instance Natadd_op1 : Op1 nat := Nat.add.
Global Instance Natzero_id1 : Id1 nat := O.
Global Arguments Nateq_equiv /.
Global Arguments Natadd_op1 /.
Global Arguments Natzero_id1 /.
Global Instance Nat_commutative_monoid : CommutativeMonoid nat.
Proof. repeat split; repeat red; intros; simpl in *; try lia. Qed.
End nat.
Section Z.
Global Instance Zeq_equiv : Equiv Z := eq.
Global Instance Zadd_op1 : Op1 Z := Z.add.
Global Instance Zzero_id1 : Id1 Z := Z0.
Global Instance Zopp_inv1 : Inv1 Z := Z.opp.
Global Instance Zmult_op2 : Op2 Z := Z.mul.
Global Instance Zone_id2 : Id2 Z := 1%Z.
Global Arguments Zeq_equiv /.
Global Arguments Zadd_op1 /.
Global Arguments Zzero_id1 /.
Global Arguments Zopp_inv1 /.
Global Arguments Zmult_op2 /.
Global Arguments Zone_id2 /.
Global Arguments Z.mul : simpl never.
Global Instance Z_integral_domain : IntegralDomain Z.
Proof. repeat split; repeat red; intros; cbn in *; auto with zarith; nia. Qed.
Global Instance Z_eq_dec : forall x y : Z, Decision (x = y) := Z.eq_dec.
End Z.
Section R.
Global Instance Req_equiv : Equiv R := eq.
Global Instance Rplus_op1 : Op1 R := Rplus.
Global Instance Rzero_id1 : Id1 R := R0.
Global Instance Ropp_inv1 : Inv1 R := Ropp.
Global Instance Rmult_op2 : Op2 R := Rmult.
Global Instance Rone_id2 : Id2 R := R1.
Global Arguments Req_equiv /.
Global Arguments Rplus_op1 /.
Global Arguments Rzero_id1 /.
Global Arguments Ropp_inv1 /.
Global Arguments Rmult_op2 /.
Global Arguments Rone_id2 /.
Global Instance R_integral_domain : IntegralDomain R.
Proof. repeat split; repeat red; simpl in *; intros; nra. Qed.
Global Instance R_eq_dec : RelDecision (=@{R}) := Req_EM_T.
Global Instance Rle_reflexive : Reflexive Rle. red; intros; lra. Qed.
Global Instance Rle_transitive : Transitive Rle. red; intros; lra. Qed.
End R.
Require Import micromega.Lqa.
Section Q.
Local Open Scope Q_scope.
Global Instance Qeq_Equiv : Equiv Q := Qeq.
Global Arguments Qeq_Equiv /.
Global Instance Qadd_op1 : Op1 Q := Qplus.
Global Instance Qzero_id1 : Id1 Q := 0%Q.
Global Instance Qopp_inv1 : Inv1 Q := Qopp.
Global Instance Qmult_op2 : Op2 Q := Qmult.
Global Instance Qone_id2 : Id2 Q := 1%Q.
Global Instance Qinv_inv2 : Inv2 Q := Qinv.
Global Arguments Qadd_op1 /.
Global Arguments Qzero_id1 /.
Global Arguments Qopp_inv1 /.
Global Arguments Qmult_op2 /.
Global Arguments Qone_id2 /.
Global Arguments Qinv_inv2 /.
Global Instance Q_integral_domain : IntegralDomain Q.
Proof. repeat split; repeat intro; cbn in *; nra. Qed.
Global Instance Q_eq_dec : forall x y : Q, Decision (x ≡ y) := Qeq_dec.
End Q.
Section Qc.
Local Open Scope Qc.
Global Instance Qceq_equiv : Equiv Qc := eq.
Global Arguments Qceq_equiv /.
Global Instance Qcplus_op1 : Op1 Qc := Qcplus.
Global Arguments Qcplus_op1 /.
Global Instance Qczero_id1 : Id1 Qc := 0.
Global Arguments Qczero_id1 /.
Global Instance Qcopp_inv1 : Inv1 Qc := Qcopp.
Global Arguments Qcopp_inv1 /.
Global Instance Qcmult_op2 : Op2 Qc := Qcmult.
Global Arguments Qcmult_op2 /.
Global Instance Qcone_id2 : Id2 Qc := 1.
Global Arguments Qcone_id2 /.
Global Instance Qc_integral_domain : IntegralDomain Qc.
Proof.
repeat split; repeat red; intros; cbn in *; try field; try congruence.
inversion H. apply Qcmult_integral. assumption.
Qed.
End Qc.
|
theory Physical_Trace
imports Complex_Main Analysis
Overtaking_Aux
"Affine_Arithmetic/Affine_Code"
"Affine_Arithmetic/Intersection"
begin
section "Auxiliaries"
subsection "singleton"
lemma two_elements_not_singleton:
"x \<in> S \<Longrightarrow> y \<in> S \<Longrightarrow> x \<noteq> y \<Longrightarrow> \<not> is_singleton S"
by (metis is_singleton_def singletonD)
subsection "Strict monotonicity and anti-monotonicity"
definition strict_mono_in :: "('a::order \<Rightarrow> 'b::order) \<Rightarrow> 'a set \<Rightarrow> bool" where
"strict_mono_in f S \<longleftrightarrow> (\<forall>x\<in>S. \<forall>y\<in>S. x < y \<longrightarrow> f x < f y)"
lemma strict_mono_inI[intro]:
assumes "\<And>x y. x \<in> S \<Longrightarrow> y \<in> S \<Longrightarrow> x < y \<Longrightarrow> f x < f y"
shows "strict_mono_in f S"
using assms unfolding strict_mono_in_def by auto
lemma strict_mono_inD:
assumes "strict_mono_in f S"
assumes "x \<in> S"
assumes "y \<in> S"
assumes "x < y"
shows "f x < f y"
using assms unfolding strict_mono_in_def by auto
definition mono_in :: "('a :: order \<Rightarrow> 'b :: order) \<Rightarrow> 'a set \<Rightarrow> bool" where
"mono_in f S \<longleftrightarrow> (\<forall>x\<in>S. \<forall>y\<in>S. x \<le> y \<longrightarrow> f x \<le> f y)"
lemma mono_inI[intro]:
fixes S :: "('a :: order) set"
fixes f :: "'a \<Rightarrow> 'b :: order"
assumes "\<And>x y. x \<in> S \<Longrightarrow> y \<in> S \<Longrightarrow> x \<le> y \<Longrightarrow> f x \<le> f y"
shows "mono_in f S"
using assms unfolding mono_in_def by auto
lemma strict_mono_in_mono_in:
"strict_mono_in f S \<Longrightarrow> mono_in f S"
unfolding strict_mono_in_def mono_in_def by (simp add: le_less)
lemma strict_imp_inj_on:
fixes S :: "'a ::linorder set"
assumes "strict_mono_in f S"
shows "inj_on f S"
unfolding inj_on_def
proof (rule ballI, rule ballI, rule impI, rule ccontr)
fix x y
assume "x \<in> S"
assume "y \<in> S"
assume "f x = f y"
assume "x \<noteq> y"
then consider "x < y" | "x > y" using less_linear by auto
hence "f x \<noteq> f y"
proof (cases)
case 1
hence "f x < f y" using strict_mono_inD[OF assms \<open>x \<in> S\<close> \<open>y \<in> S\<close>] by auto
then show ?thesis by auto
next
case 2
hence "f y < f x" using strict_mono_inD[OF assms \<open>y \<in>S\<close> \<open>x \<in> S\<close>] by auto
then show ?thesis by auto
qed
with \<open>f x = f y\<close> show "False" by auto
qed
definition strict_antimono_in :: "('a::order \<Rightarrow> 'b::order) \<Rightarrow> 'a set \<Rightarrow> bool" where
"strict_antimono_in f S \<longleftrightarrow> (\<forall>x\<in>S. \<forall>y\<in>S. x < y \<longrightarrow> f x > f y)"
definition antimono_in :: "('a :: order \<Rightarrow> 'b :: order) \<Rightarrow> 'a set \<Rightarrow> bool" where
"antimono_in f S \<longleftrightarrow> (\<forall>x\<in>S. \<forall>y\<in>S. x \<le> y \<longrightarrow> f x \<ge> f y)"
lemma strict_antimono_in_antimono_in:
"strict_antimono_in f S \<Longrightarrow> antimono_in f S"
unfolding strict_antimono_in_def antimono_in_def by (simp add:le_less)
\<comment> \<open>A function @{term "f"} is always strictly antimonotonic in a set with single element.\<close>
lemma "strict_antimono_in f {x}"
unfolding strict_antimono_in_def by auto
subsection "Non-boundedness"
lemma bounded_lt: "\<not> bounded {..< (u::real)}"
proof (rule notI, cases "0 \<le> u")
case True
assume "bounded {..<u}"
then obtain a where 0:"\<forall>x \<in> {..<u}. \<bar>x\<bar> \<le> a" unfolding bounded_real by auto
have 1:"0 < a"
proof -
have f1: "(0 \<le> - 1 + a) = (1 \<le> a)"
by auto
have f2: "\<not> (0::real) \<le> - 1"
by auto
have f3: "\<forall>r. r \<in> {..<u} \<longrightarrow> (if r < 0 then - r else r) \<le> a"
by (metis \<open>\<forall>x\<in>{..<u}. \<bar>x\<bar> \<le> a\<close> abs_if_raw)
have f4: "\<forall>r. (r \<in> {..<u} \<longrightarrow> (if r < 0 then - r else r) \<le> a) = (r \<notin> {..<u} \<or> (if r < 0 then - 1 * r else r) \<le> a)"
by auto
have "\<forall>r. (if (r::real) < 0 then - 1 * r else r) = (if 0 \<le> r then r else - 1 * r)"
by simp
then have f5: "\<forall>r. r \<notin> {..<u} \<or> 0 \<le> a + - 1 * (if 0 \<le> r then r else - 1 * r)"
using f4 f3 by fastforce
have f6: "\<forall>x0. a + (if 0 \<le> x0 then - 1 * x0 else x0) = (if 0 \<le> x0 then - 1 * x0 + a else x0 + a)"
by fastforce
have f7: "\<forall>x0. - (1::real) * (if 0 \<le> x0 then x0 else - 1 * x0) = (if 0 \<le> x0 then - 1 * x0 else x0)"
by simp
have "- 1 \<in> {..<u}"
using \<open>0 \<le> u\<close> by auto
then have "1 \<le> a"
using f7 f6 f5 f2 f1 by presburger
then show ?thesis
by auto
qed
with True have "-(a+1) \<in> {..<u}" by auto
with 0 have "abs (-(a+1)) \<le> a" by auto
thus "False" by auto
next
case False
assume "bounded {..<u}"
then obtain a where 0:"\<forall>x \<in> {..<u}. abs x \<le> a" unfolding bounded_real by auto
have "0 \<le> a"
proof (rule ccontr)
assume "\<not> 0 \<le> a"
hence "a < 0" by auto
with 0 have "\<forall>x \<in> {..<u}. abs x < 0" by auto
with abs_ge_zero have "\<forall>x \<in> {..<u}. abs x < 0 \<and> 0 \<le> abs x" by auto
hence "\<forall>x \<in> {..<u}. False" by auto
hence "{..<u} = {}" by (simp add: lessThan_def)
with lessThan_non_empty[of "u"] show "False" by auto
qed
hence "- (a + 1) < 0" by auto
have "-a < u"
proof (rule ccontr)
assume "\<not> -a < u"
hence "-a \<ge> u" by auto
have "u - 1 < u" by auto
with 0 have "abs (u - 1) \<le> a" by auto
with False have "1 - u \<le> a" by auto
hence "1 - a \<le> u" by auto
with \<open>-a \<ge> u\<close> show "False" by auto
qed
hence "- (a + 1) < u" by auto
with 0 have "abs (- (a + 1)) \<le> a" by auto
with \<open>- (a + 1) < 0\<close> have "a + 1 \<le> a" by auto
then show "False" by auto
qed
lemma bounded_leq: "\<not> bounded {..(u::real)}"
proof -
have "{..<u} \<subseteq> {..u}" by auto
with bounded_subset[where S="{..<u}" and T="{..u}"] and bounded_lt
show "\<not> bounded {..u}" by auto
qed
lemma bounded_gt: "\<not> bounded {(l::real)<..}"
unfolding bounded_real
proof (rule notI)
assume "\<exists>a . \<forall>x \<in> {l<..}. abs x \<le> a"
then obtain a where 0: "\<forall>x \<in> {l<..}. abs x \<le> a" by auto
hence "l < a" by (rule ballE[where x="l+1"])(auto)
hence 1: "l < a + 1" by auto
have "0 \<le> a"
proof (rule ccontr)
assume "\<not> 0 \<le> a"
hence "a < 0" by auto
with 0 have "\<forall>x \<in> {l <..}. abs x < 0" by auto
with abs_ge_zero have "\<forall>x \<in> {l <..}. False" by auto
hence "{l<..} = {}" by blast
with greaterThan_non_empty show "False" by auto
qed
from 0 and 1 have 2: "abs (a + 1) \<le> a" by auto
with \<open>0 \<le> a\<close> show "False" by auto
qed
lemma bounded_geq: "\<not> bounded {(l::real)..}"
proof -
have "{l<..} \<subseteq> {l..}" by auto
with bounded_subset[where S="{l<..}" and T="{l..}"] and bounded_gt
show "\<not> bounded {l..}" by auto
qed
subsection "Non-closedness"
lemma closedness_gt_lt:"(l :: real) < u \<Longrightarrow> \<not> closed {l <..< u}"
unfolding closed_limpt
by (auto intro!:islimpt_greaterThanLessThan2)
lemma islimpt_gt_leq:
fixes a b::"'a::{linorder_topology, dense_order}"
assumes "a < b"
shows "a islimpt {a<..b}"
using assms islimpt_greaterThanLessThan1
by (metis islimpt_Un ivl_disj_un_singleton(4))
lemma closedness_gt: "(l ::real) < u \<Longrightarrow> \<not> closed {l <.. u}"
unfolding closed_limpt
using islimpt_gt_leq greaterThanAtMost_iff by blast
lemma islimpt_geq_lt:
fixes a b::"'a::{linorder_topology, dense_order}"
assumes "a < b"
shows "b islimpt {a..<b}"
using assms islimpt_greaterThanLessThan2
by (metis atLeastLessThan_iff greaterThanLessThan_iff islimptE islimptI less_imp_le)
lemma closedness_lt: "(l::real) < u \<Longrightarrow> \<not> closed {l..<u}"
unfolding closed_limpt
using islimpt_geq_lt atLeastLessThan_iff by blast
theorem compact_convex_closed_interval:
fixes domain :: "real set"
assumes compact: "compact domain"
assumes convex: "convex domain"
obtains a b where "domain = {a .. b}"
proof -
from convex have 0: "is_interval domain" by (auto simp add:is_interval_convex_1)
obtain l u where
"domain = {} \<or> domain = UNIV \<or> domain = {..<u} \<or> domain = {..u} \<or> domain = {l<..} \<or> domain = {l..} \<or>
domain = {l<..<u} \<or> domain = {l<..u} \<or> domain = {l..<u} \<or> domain = {l..u}"
using is_real_interval[OF 0] by auto
moreover have "\<not> bounded (UNIV :: real set)" and "\<not> bounded {..<u}" and "\<not> bounded {..u}"
and "\<not> bounded {l<..}" and "\<not> bounded {l..}"
by (auto simp add: bounded_lt bounded_leq bounded_gt bounded_geq)
moreover have "l < u \<Longrightarrow> \<not> closed {l<..<u}" and "l < u \<Longrightarrow> \<not> closed {l<..u}" and
"l < u \<Longrightarrow> \<not> closed {l..<u}"
by (auto simp add:closedness_gt_lt closedness_gt closedness_lt)
ultimately have "domain = {} \<or> domain = {l .. u}" using compact greaterThanLessThan_empty_iff
greaterThanAtMost_empty_iff atLeastLessThan_empty_iff unfolding compact_eq_bounded_closed
by smt
thus ?thesis
by (smt atLeastatMost_empty bot_set_def that)
qed
section "Environment"
text "At the moment, we focus on highway (freeway) scenario first without forks and joints. There
are multiple lanes in one road. The road is characterised with left boundary, right boundary, and
lane boundaries. Left, right, and lane boundaries are formalised as curve in mathematical sense."
\<comment> \<open>A general definition of plane curve; a curve is define by a parametric function — or map in
mathematics parlance. The only requirement is that the function must be continuous; this ensures
that the function is defined everywhere (no hole).\<close>
subsection "Curve"
locale curve =
fixes curve_eq :: "real \<Rightarrow> real2"
fixes domain :: "real set"
assumes convex_domain: "convex domain"
assumes compact_domain: "compact domain"
assumes continuous: "continuous_on domain curve_eq"
begin
\<comment> \<open>convexity of the domain means that domain is an interval\<close>
lemma "is_interval domain"
using convex_domain by (auto simp add: is_interval_convex_1)
\<comment> \<open>in fact, it is a closed interval\<close>
lemma closed_domain:
"closed domain"
using compact_domain by (auto intro:compact_imp_closed)
\<comment> \<open>the domain is path connected too\<close>
lemma path_connected_domain: "path_connected domain"
using convex_domain by (auto intro:convex_imp_path_connected)
lemma bdd_below_domain:
"bdd_below domain"
using compact_domain unfolding compact_eq_bounded_closed
using bounded_imp_bdd_below by auto
lemma bdd_above_domain:
"bdd_above domain"
using compact_domain unfolding compact_eq_bounded_closed
using bounded_imp_bdd_above by auto
definition setX where
"setX \<equiv> fst ` (curve_eq ` domain)"
definition setY where
"setY \<equiv> snd ` (curve_eq ` domain)"
\<comment> \<open>parametric equation for x only.\<close>
definition curve_eq_x :: "real \<Rightarrow> real" where
"curve_eq_x \<equiv> \<lambda>s. fst (curve_eq s)"
lemma setX_alt_def: "setX = curve_eq_x ` domain"
unfolding setX_def curve_eq_x_def by auto
lemma cont_param_x: "continuous_on domain curve_eq_x"
unfolding curve_eq_x_def by (auto intro: continuous_on_fst simp add:continuous)
lemma compact_setX: "compact setX"
unfolding setX_alt_def
by (rule compact_continuous_image)(auto simp add: compact_domain cont_param_x)
lemma path_connected_setX: "path_connected setX"
unfolding setX_alt_def
by (rule path_connected_continuous_image) (auto simp add: cont_param_x path_connected_domain)
lemma interval_setX: "is_interval setX"
unfolding is_interval_path_connected_1
using path_connected_setX by auto
lemma convex_setX: "convex setX"
using is_interval_convex_1 interval_setX by auto
theorem setX_closed_interval_or_empty:
"(\<exists> a b. setX = {a .. b})"
using compact_convex_closed_interval[OF compact_setX convex_setX]
by meson
corollary closed_setX: "closed setX"
using setX_closed_interval_or_empty closed_atLeastAtMost closed_empty
by auto
\<comment> \<open>parametric equation for y only.\<close>
definition curve_eq_y :: "real \<Rightarrow> real" where
"curve_eq_y \<equiv> \<lambda>s. snd (curve_eq s)"
lemma setY_alt_def: "setY = curve_eq_y ` domain"
unfolding setY_def curve_eq_y_def by auto
lemma cont_param_y: "continuous_on domain curve_eq_y"
unfolding curve_eq_y_def by (auto intro:continuous_on_snd simp add:continuous)
lemma "compact setY"
unfolding setY_alt_def
by (rule compact_continuous_image) (auto simp add:compact_domain cont_param_y)
lemma path_connected_setY: "path_connected setY"
unfolding setY_alt_def
by (rule path_connected_continuous_image) (auto simp add: cont_param_y path_connected_domain)
lemma "is_interval setY"
unfolding is_interval_path_connected_1
using path_connected_setY by auto
theorem domain_interval:
"\<exists> a b. domain = {a .. b}"
using compact_convex_closed_interval[OF compact_domain convex_domain] by meson
end
subsection "Simple boundary"
\<comment> \<open>A simple boundary in traffic scenario is a simple curve. That is the parametric function for the
curve is injective (or one-to-one). This ensures that the curve will have no common point. This is
adequate to model highway without forks and joins.\<close>
locale simple_boundary = curve +
assumes simple: "inj_on curve_eq domain"
assumes bij_betw: "bij_betw curve_eq_x domain setX"
begin
lemma curve_eq_x_strict_mono_or_antimono:
assumes "domain \<noteq> {}"
shows "strict_mono_in curve_eq_x domain \<or> strict_antimono_in curve_eq_x domain"
proof -
from domain_interval obtain a b where 0: "domain = {a .. b}" by auto
with assms have "a \<le> b" by auto
from continuous_inj_imp_mono[where f="curve_eq_x" and a="a" and b="b"] cont_param_x bij_betw
have 1: "\<forall>x. a < x \<longrightarrow> x < b \<longrightarrow> curve_eq_x a < curve_eq_x x \<and> curve_eq_x x < curve_eq_x b \<or>
curve_eq_x b < curve_eq_x x \<and> curve_eq_x x < curve_eq_x a"
unfolding bij_betw_def 0 strict_mono_def strict_antimono_in_def strict_mono_in_def by auto
show ?thesis
proof (cases "\<forall>x. a < x \<longrightarrow> x < b \<longrightarrow> curve_eq_x a < curve_eq_x x \<and> curve_eq_x x < curve_eq_x b")
case True
have "strict_mono_in curve_eq_x {a .. b}"
unfolding strict_mono_in_def
proof (rule ballI, rule ballI, rule impI, rule ccontr)
fix x y
assume "x \<in> {a .. b}" "y \<in> {a .. b}"
hence "a \<le> x" by auto
assume "x < y"
assume "\<not> curve_eq_x x < curve_eq_x y"
hence 2:"curve_eq_x y \<le> curve_eq_x x" by auto
have 3: "curve_eq_x a \<le> curve_eq_x y"
proof (cases "y \<noteq> b")
assume "y \<noteq> b"
with \<open>y \<in> {a .. b}\<close> have "y \<in> {a ..< b}" by auto
with True show ?thesis by force
next
case False
hence "y = b" by auto
show ?thesis
proof (cases "a = b")
case True
then show ?thesis using \<open>y = b\<close> by auto
next
case False
with \<open>a \<le> b\<close> have "a < b" by auto
then obtain c where "a < c \<and> c < b" using dense[OF \<open>a < b\<close>] by auto
with True have "curve_eq_x a < curve_eq_x c \<and> curve_eq_x c < curve_eq_x b" by auto
thus ?thesis using \<open>y=b\<close> by auto
qed
qed
have ax_subset: "{a .. x} \<subseteq> {a .. b}"
using \<open>x \<in> {a .. b}\<close> by auto
have 4: "continuous_on {a..x} curve_eq_x"
using continuous_on_subset[OF cont_param_x] ax_subset unfolding 0 by auto
hence "\<exists>z\<ge>a. z \<le> x \<and> curve_eq_x z = curve_eq_x y"
using IVT'[of "curve_eq_x" "a" "curve_eq_x y" "x", OF 3 2 \<open>a \<le> x\<close> 4]
by auto
from this obtain z where 5: "curve_eq_x z = curve_eq_x y" and "z \<in> {a .. x}" by auto
with \<open>x < y\<close> have 6: "z \<noteq> y" by auto
from \<open>z \<in> {a .. x}\<close> have "z \<in> {a .. b}" using ax_subset by auto
with bij_betw 5 6 show "False" unfolding bij_betw_def 0 inj_on_def using \<open>y \<in> {a .. b}\<close>
by auto
qed
from this show ?thesis using 0 by auto
next
case False
with 1 have 2: "\<forall>x. a < x \<longrightarrow> x < b \<longrightarrow> curve_eq_x b < curve_eq_x x \<and> curve_eq_x x < curve_eq_x a"
by smt
have "strict_antimono_in curve_eq_x {a .. b}"
unfolding strict_antimono_in_def
proof (rule ballI, rule ballI, rule impI, rule ccontr)
fix x y
assume "x \<in> {a .. b}" "y \<in> {a .. b}"
hence "a \<le> x" by auto
assume "x < y"
assume "\<not> curve_eq_x y < curve_eq_x x"
hence 3: "curve_eq_x x \<le> curve_eq_x y" by auto
have 4: "curve_eq_x y \<le> curve_eq_x a"
proof (cases "y \<noteq> b")
case True
with \<open>y \<in> {a .. b}\<close> have "y \<in> {a ..< b}" by auto
with 2 show ?thesis by force
next
case False
hence "y = b" by auto
show ?thesis
proof (cases "a = b")
case True
then show ?thesis using \<open>y = b\<close> by auto
next
case False
with \<open>a \<le> b\<close> have "a < b" by auto
then obtain c where "a < c \<and> c < b" using dense[OF \<open>a < b\<close>] by auto
with 2 have "curve_eq_x b < curve_eq_x c \<and> curve_eq_x c < curve_eq_x a" by auto
thus ?thesis using \<open>y=b\<close> by auto
qed
qed
have ax_subset: "{a .. x} \<subseteq> {a .. b}"
using \<open>x \<in> {a .. b}\<close> by auto
have 5: "continuous_on {a..x} curve_eq_x"
using continuous_on_subset[OF cont_param_x] ax_subset unfolding 0 by auto
have "\<exists>z\<ge> a. z \<le> x \<and> curve_eq_x z = curve_eq_x y"
using IVT2'[of "curve_eq_x" "x" "curve_eq_x y" "a", OF 3 4 \<open>a \<le> x\<close> 5] .
then obtain z where "a \<le> z" and "z \<le> x" and "curve_eq_x z = curve_eq_x y" by auto
with bij_betw show "False" unfolding bij_betw_def 0 inj_on_def using ax_subset \<open>y \<in> {a .. b}\<close>
by (smt \<open>x < y\<close> atLeastAtMost_iff)
qed
then show ?thesis unfolding 0 ..
qed
qed
lemma checking_strict_mono:
assumes "domain \<noteq> {}"
assumes "curve_eq_x (Inf domain) < curve_eq_x (Sup domain)"
shows "strict_mono_in curve_eq_x domain"
proof (rule ccontr)
assume "\<not> strict_mono_in curve_eq_x domain"
with curve_eq_x_strict_mono_or_antimono[OF assms(1)] have anti: "strict_antimono_in curve_eq_x domain"
by auto
have "is_singleton domain \<or> \<not> is_singleton domain" by auto
moreover
{ assume "is_singleton domain"
then obtain x where "domain = {x}" unfolding is_singleton_def by auto
hence "Inf domain = Sup domain" by auto
hence "curve_eq_x (Inf domain) = curve_eq_x (Sup domain)" by auto
with assms(2) have "False" by auto }
moreover
{ assume "\<not> is_singleton domain"
with assms(1) obtain a b where domain_eq: "domain = {a .. b}" and "a < b" using domain_interval by force
hence inf_id: "Inf domain = a" and sup_id: "Sup domain = b" by auto
from anti have "curve_eq_x a > curve_eq_x b" unfolding strict_antimono_in_def
using domain_eq \<open>a < b\<close> by auto
with assms(2) have "False" using inf_id sup_id by auto }
ultimately show False by blast
qed
lemma checking_strict_antimono:
assumes "domain \<noteq> {}"
assumes "curve_eq_x (Inf domain) > curve_eq_x (Sup domain)"
shows "strict_antimono_in curve_eq_x domain"
using assms(2)
proof (rule contrapos_pp)
assume "\<not> strict_antimono_in curve_eq_x domain"
with curve_eq_x_strict_mono_or_antimono[OF assms(1)] have mono: "strict_mono_in curve_eq_x domain"
by auto
have "Inf domain \<le> Sup domain" using cInf_le_cSup[OF assms(1) bdd_above_domain bdd_below_domain] .
hence "curve_eq_x (Inf domain) \<le> curve_eq_x (Sup domain)"
using strict_mono_in_mono_in[OF mono] closed_contains_Inf[OF assms(1) bdd_below_domain closed_domain]
closed_contains_Sup[OF assms(1) bdd_above_domain closed_domain] unfolding mono_in_def
by auto
thus "\<not> curve_eq_x (Sup domain) < curve_eq_x (Inf domain)" by auto
qed
lemma impossible_equal_endpoints_value:
assumes "domain \<noteq> {}" and "\<not> is_singleton domain"
shows "curve_eq_x (Inf domain) \<noteq> curve_eq_x (Sup domain)"
proof -
from assms obtain a b where domain_eq: "domain = {a .. b}" and "a < b" using domain_interval by force
hence "Inf domain = a" and "Sup domain = b" by auto
with \<open>a < b\<close> bij_betw show ?thesis unfolding bij_betw_def domain_eq inj_on_def
by (smt atLeastAtMost_iff)
qed
definition inv_curve_x where
"inv_curve_x \<equiv> the_inv_into domain curve_eq_x"
lemma "bij_betw inv_curve_x setX domain"
using bij_betw_the_inv_into[OF bij_betw] unfolding inv_curve_x_def by auto
lemma strict_mono_inverse:
assumes "strict_mono_in curve_eq_x domain"
shows "strict_mono_in inv_curve_x setX"
using assms
by (smt bij_betw bij_betwE bij_betw_the_inv_into f_the_inv_into_f_bij_betw inv_curve_x_def
strict_mono_in_def)
lemma strict_antimono_inverse:
assumes "strict_antimono_in curve_eq_x domain"
shows "strict_antimono_in inv_curve_x setX"
unfolding strict_antimono_in_def
proof (rule ballI, rule ballI, rule impI)
fix x y
assume "x \<in> setX" "y \<in> setX" "x < y"
from this obtain dx dy :: real where "dx = inv_curve_x x" and "dx \<in> domain" and
"dy = inv_curve_x y" and "dy \<in> domain"
by (metis bij_betw bij_betw_imp_inj_on image_eqI inv_curve_x_def setX_alt_def the_inv_into_onto)
hence 0: "curve_eq_x dx = x" and 1: "curve_eq_x dy = y" using f_the_inv_into_f_bij_betw[OF bij_betw]
bij_betw \<open>x \<in> setX\<close> \<open>y \<in> setX\<close> unfolding inv_curve_x_def by auto
have "antimono_in curve_eq_x domain" using strict_antimono_in_antimono_in[OF assms] .
hence "dx > dy" unfolding antimono_in_def using \<open>dx \<in> domain\<close> \<open>dy \<in> domain\<close> 0 1 \<open>x < y\<close>
by fastforce
thus " inv_curve_x y < inv_curve_x x" using \<open>dx = inv_curve_x x\<close> \<open>dy = inv_curve_x y\<close> by simp
qed
lemma image_inverse:
"inv_curve_x ` setX \<subseteq> domain"
using bij_betw unfolding bij_betw_def inv_curve_x_def
using the_inv_into_onto by fastforce
\<comment> \<open>the inverse of parametric curve for x dimension is also continuous\<close>
lemma inv_x_cont: "continuous_on setX inv_curve_x"
using bij_betw
unfolding inv_curve_x_def setX_alt_def bij_betw_def
by (auto intro!: continuous_on_inv_into simp add:cont_param_x compact_domain )
definition f_of_x where
"f_of_x \<equiv> curve_eq_y \<circ> inv_curve_x"
theorem domain_and_range_f_of_x: "f_of_x \<in> setX \<rightarrow> setY"
proof (rule funcsetI)
fix x
assume 0: "x \<in> setX"
hence "f_of_x x = (curve_eq_y (inv_curve_x x))" unfolding f_of_x_def by auto
also have 1: "... = (curve_eq_y (THE y. y \<in> domain \<and> curve_eq_x y = x))" unfolding inv_curve_x_def
the_inv_into_def by auto
also have "... \<in> setY" unfolding setY_def using curve_eq_y_def inv_curve_x_def 0 1
by (metis (no_types, lifting) bij_betw bij_betwE bij_betw_the_inv_into image_eqI)
finally show "f_of_x x \<in> setY" by auto
qed
theorem f_of_x_curve_eq:
assumes "x \<in> setX"
assumes "f_of_x x = y"
shows "\<exists>t \<in> domain. curve_eq t = (x,y)"
proof -
from \<open>x \<in> setX\<close> obtain t where "t \<in> domain \<and> (fst \<circ> curve_eq) t = x"
unfolding setX_def comp_def by auto
from assms have "y \<in> setY" using domain_and_range_f_of_x by auto
from assms(2) have "(snd \<circ> curve_eq) t = y" unfolding f_of_x_def
by (metis \<open>t \<in> domain \<and> (fst \<circ> curve_eq) t = x\<close> bij_betw bij_betw_imp_inj_on comp_def
curve.curve_eq_y_def curve_axioms curve_eq_x_def inv_curve_x_def the_inv_into_f_f)
with \<open>t \<in> domain \<and> (fst \<circ> curve_eq) t = x\<close> show ?thesis by(auto intro:bexI[where x="t"])
qed
theorem curve_eq_f_of_x:
assumes "t \<in> domain"
assumes "curve_eq t = (x,y)"
shows "f_of_x x = y"
using assms
unfolding f_of_x_def comp_def inv_curve_x_def curve_eq_x_def curve_eq_y_def
the_inv_into_def
proof -
have f1: "inj_on (\<lambda>r. fst (curve_eq r)) domain"
using bij_betw bij_betw_imp_inj_on curve.curve_eq_x_def curve_axioms by auto
obtain rr :: "real set \<Rightarrow> (real \<Rightarrow> real) \<Rightarrow> real \<Rightarrow> real" where
"\<forall>x0 x1 x2. (\<exists>v3. x2 = x1 v3 \<and> v3 \<in> x0) = (x2 = x1 (rr x0 x1 x2) \<and> rr x0 x1 x2 \<in> x0)"
by moura
then have f2: "\<forall>r f R. r \<notin> f ` R \<or> r = f (rr R f r) \<and> rr R f r \<in> R"
by (meson imageE)
have f3: "curve_eq_x = (\<lambda>r. fst (curve_eq r))"
by (meson curve.curve_eq_x_def curve_axioms)
then have f4: "the_inv_into domain (\<lambda>r. fst (curve_eq r)) ` curve_eq_x ` domain = domain"
using f1 by simp
then have f5: "t = the_inv_into domain (\<lambda>r. fst (curve_eq r)) (rr (curve_eq_x ` domain) (the_inv_into domain (\<lambda>r. fst (curve_eq r))) t) \<and> rr (curve_eq_x ` domain) (the_inv_into domain (\<lambda>r. fst (curve_eq r))) t \<in> curve_eq_x ` domain"
using f2 assms(1) by presburger
have f6: "\<forall>p r. (\<not> p (r::real) \<or> (\<exists>ra. p ra \<and> ra \<noteq> r)) \<or> The p = r"
by (metis the_equality)
obtain rra :: "real \<Rightarrow> (real \<Rightarrow> bool) \<Rightarrow> real" where
"\<forall>x0 x1. (\<exists>v2. v2 \<in> Collect x1 \<and> v2 \<noteq> x0) = (rra x0 x1 \<in> Collect x1 \<and> rra x0 x1 \<noteq> x0)"
by moura
then have f7: "\<forall>p r. r \<notin> Collect p \<or> rra r p \<in> Collect p \<and> rra r p \<noteq> r \<or> The p = r"
using f6 by simp
have f8: "\<forall>r. (r \<in> {r \<in> domain. fst (curve_eq r) = x}) = (r \<in> domain \<and> fst (curve_eq r) = x)"
by blast
have f9: "\<forall>x0. (x0 \<in> domain \<and> fst (curve_eq x0) = x) = (x0 \<in> domain \<and> fst (curve_eq x0) = x)"
by auto
have f10: "t \<in> {r \<in> domain. fst (curve_eq r) = x}"
by (simp add: assms(1) assms(2))
have f11: "rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x) \<notin> the_inv_into domain (\<lambda>r. fst (curve_eq r)) ` curve_eq_x ` domain \<or> rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x) = the_inv_into domain (\<lambda>r. fst (curve_eq r)) (rr (curve_eq_x ` domain) (the_inv_into domain (\<lambda>r. fst (curve_eq r))) (rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x))) \<and> rr (curve_eq_x ` domain) (the_inv_into domain (\<lambda>r. fst (curve_eq r))) (rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x)) \<in> curve_eq_x ` domain"
using f2 by meson
have "(rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x) \<noteq> the_inv_into domain (\<lambda>r. fst (curve_eq r)) (rr (curve_eq_x ` domain) (the_inv_into domain (\<lambda>r. fst (curve_eq r))) (rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x))) \<or> rr (curve_eq_x ` domain) (the_inv_into domain (\<lambda>r. fst (curve_eq r))) (rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x)) \<notin> curve_eq_x ` domain) \<or> rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x) \<notin> {r \<in> domain. fst (curve_eq r) = x} \<or> rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x) = t"
using f9 f8 f5 f3 f1 assms(2) the_inv_into_f_eq by force
then have "rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x) \<notin> {r \<in> domain. fst (curve_eq r) = x} \<or> rra t (\<lambda>r. r \<in> domain \<and> fst (curve_eq r) = x) = t"
using f11 f4 by blast
then have "(THE r. r \<in> domain \<and> fst (curve_eq r) = x) = t"
using f10 f7 by meson
then show "snd (curve_eq (THE r. r \<in> domain \<and> fst (curve_eq r) = x)) = y"
by (simp add: assms(2))
qed
theorem cont_f_of_x: "continuous_on setX f_of_x"
unfolding f_of_x_def
proof (rule continuous_on_compose)
from inv_x_cont show " continuous_on setX inv_curve_x" by auto
next
have "inv_curve_x ` setX = domain" unfolding inv_curve_x_def
by (metis bij_betw bij_betw_imp_inj_on setX_alt_def the_inv_into_onto)
thus "continuous_on (inv_curve_x ` setX) curve_eq_y" using cont_param_y by auto
qed
lemma param_y_via_f_of_x:
assumes "d \<in> domain"
shows "curve_eq_y d = (f_of_x \<circ> curve_eq_x) d"
unfolding f_of_x_def comp_def using the_inv_into_f_f[of "curve_eq_x" "domain" "d"]
using assms bij_betw unfolding bij_betw_def inv_curve_x_def
by auto
end
subsection "Simple road"
\<comment> \<open>The locale for defining a simple road which consists of single lane only. This locale is
parametrised further with two simple boundaries, for left and right boundary.\<close>
(*
------------------------------ left boundary
DRIVABLE AREA
------------------------------ right boundary
y
|
|
-----> x (global coordinate)
*)
(* TODO: add @{term"common_setX \<noteq> {}"} as one of the assumption in the locale. It simplifies
the theorem inside. *)
locale simple_road = le: simple_boundary curve_left domain + ri: simple_boundary curve_right domain
for curve_left and curve_right and domain +
assumes nonempty: "le.setX \<inter> ri.setX \<noteq> {}"
assumes above': "x \<in> le.setX \<inter> ri.setX \<Longrightarrow> ri.f_of_x x \<noteq> le.f_of_x x"
begin
definition common_setX where
"common_setX \<equiv> le.setX \<inter> ri.setX"
lemma inverse_image_common_left:
"le.inv_curve_x ` common_setX \<subseteq> domain"
using le.image_inverse by (simp add: subset_eq common_setX_def)
lemma inverse_image_common_right:
"ri.inv_curve_x ` common_setX \<subseteq> domain"
using ri.image_inverse by (simp add:subset_eq common_setX_def)
definition between_setY where
"between_setY x \<equiv> {min (ri.f_of_x x) (le.f_of_x x) <..< max (ri.f_of_x x) (le.f_of_x x)}"
lemma convex_common_setX: "convex (common_setX)"
using le.convex_setX ri.convex_setX convex_Int common_setX_def by auto
lemma compact_common_setX: "compact (common_setX)"
using le.compact_setX ri.compact_setX le.closed_setX compact_Int common_setX_def
by auto
theorem common_setX_interval:
"\<exists> a b. common_setX = {a .. b}"
using compact_convex_closed_interval[OF compact_common_setX convex_common_setX] by meson
lemma bdd_below_common:
"bdd_below common_setX"
using compact_common_setX unfolding compact_eq_bounded_closed
using bounded_imp_bdd_below by auto
lemma bdd_above_common:
"bdd_above common_setX"
using compact_common_setX unfolding compact_eq_bounded_closed
using bounded_imp_bdd_above by auto
\<comment> \<open>lower bound and upper bound of @{term "common_setX"}.\<close>
definition lb_x where
"lb_x \<equiv> Inf common_setX"
lemma common_contains_lb:
"lb_x \<in> common_setX"
using compact_common_setX bdd_below_common closed_contains_Inf nonempty
unfolding lb_x_def compact_eq_bounded_closed common_setX_def
by meson
definition ub_x where
"ub_x \<equiv> Sup common_setX"
lemma common_contains_ub:
"ub_x \<in> common_setX"
using compact_common_setX bdd_above_common closed_contains_Sup nonempty
unfolding ub_x_def compact_eq_bounded_closed common_setX_def
by meson
theorem common_setX_interval2:
"common_setX = {lb_x .. ub_x}"
unfolding common_setX_def
using common_setX_interval lb_x_def nonempty ub_x_def
by (metis atLeastatMost_empty' cInf_atLeastAtMost cSup_atLeastAtMost common_setX_def)
lemma lb_x_leq_ub_x:
"lb_x \<le> ub_x"
unfolding lb_x_def ub_x_def using common_setX_def bdd_below_common bdd_above_common
by (auto intro!: cInf_le_cSup simp add: common_setX_def nonempty)
lemma common_setX_closed_segment:
"common_setX = closed_segment lb_x ub_x"
using lb_x_leq_ub_x common_setX_interval2 closed_segment_real by auto
abbreviation open_common_setX where
"open_common_setX \<equiv> common_setX - {lb_x, ub_x}"
lemma open_common_setX_open_segment:
"open_common_setX = open_segment lb_x ub_x"
unfolding open_segment_def using common_setX_closed_segment by auto
lemma lb_x_extreme_point:
"lb_x extreme_point_of common_setX"
unfolding common_setX_closed_segment
using extreme_point_of_segment by auto
lemma ub_x_extreme_point:
"ub_x extreme_point_of common_setX"
unfolding common_setX_closed_segment
using extreme_point_of_segment by auto
lemma convex_open_common_setX: "convex (open_common_setX)"
using lb_x_extreme_point ub_x_extreme_point extreme_point_of_stillconvex convex_common_setX
common_contains_ub common_contains_lb
by (simp add: open_common_setX_open_segment)
definition direction_right :: bool where
"direction_right \<equiv> ri.f_of_x lb_x < le.f_of_x lb_x"
definition direction_left :: bool where
"direction_left \<equiv> ri.f_of_x lb_x > le.f_of_x lb_x"
theorem direction_right_neq_left[simp]:
"\<not> direction_left \<longleftrightarrow> direction_right"
unfolding direction_right_def direction_left_def using above' common_contains_lb common_setX_def
by fastforce
lemma direction_right_cond:
assumes "direction_right"
shows "\<forall>x \<in> common_setX. ri.f_of_x x < le.f_of_x x"
proof (rule ccontr)
assume "\<not> (\<forall>x \<in> common_setX. ri.f_of_x x < le.f_of_x x)"
from this obtain x where "x \<in> common_setX" and "le.f_of_x x \<le> ri.f_of_x x" by fastforce
from \<open>x \<in> common_setX\<close> have "lb_x \<le> x" and "x \<le> ub_x" using common_setX_interval2 by auto
define f where "f \<equiv> \<lambda>x. ri.f_of_x x - le.f_of_x x"
from assms have 0: "f lb_x \<le> 0" unfolding f_def direction_right_def by auto
from \<open>le.f_of_x x \<le> ri.f_of_x x\<close> have 1: "f x \<ge> 0" unfolding f_def by auto
from le.cont_f_of_x and ri.cont_f_of_x have "continuous_on common_setX le.f_of_x" and
"continuous_on common_setX ri.f_of_x" by (auto intro:continuous_on_subset simp add:common_setX_def)
hence cont: "continuous_on common_setX f" unfolding f_def by (auto intro:continuous_on_diff)
from \<open>lb_x \<le> x\<close> and \<open>x \<le> ub_x\<close> have "{lb_x .. x} \<subseteq> common_setX" using common_setX_interval2
by auto
with cont have 2: "continuous_on {lb_x .. x} f" by (auto intro:continuous_on_subset)
from IVT'[where f="f" and a="lb_x" and y="0" and b="x", OF 0 1 \<open>lb_x \<le> x\<close> 2] obtain x' where
"lb_x \<le> x'" and "x' \<le> x" and "f x' = 0" by blast
hence "x' \<in> common_setX" using \<open>x \<le> ub_x\<close> and common_setX_interval2 by auto
with \<open>f x' = 0\<close> and above' show "False" unfolding f_def common_setX_def by auto
qed
lemma direction_left_cond:
assumes "direction_left"
shows "\<forall>x \<in> common_setX. ri.f_of_x x > le.f_of_x x"
proof (rule ccontr)
assume "\<not> (\<forall>x \<in> common_setX. ri.f_of_x x > le.f_of_x x)"
from this obtain x where "x \<in> common_setX" and "le.f_of_x x \<ge> ri.f_of_x x" by fastforce
from \<open>x \<in> common_setX\<close> have "lb_x \<le> x" and "x \<le> ub_x" using common_setX_interval2 by auto
define f where "f \<equiv> \<lambda>x. le.f_of_x x - ri.f_of_x x"
from assms have 0: "f lb_x \<le> 0" unfolding f_def direction_left_def by auto
from \<open>le.f_of_x x \<ge> ri.f_of_x x\<close> have 1: "f x \<ge> 0" unfolding f_def by auto
from le.cont_f_of_x and ri.cont_f_of_x have "continuous_on common_setX le.f_of_x" and
"continuous_on common_setX ri.f_of_x" by (auto intro:continuous_on_subset simp add:common_setX_def)
hence cont: "continuous_on common_setX f" unfolding f_def by (auto intro:continuous_on_diff)
from \<open>lb_x \<le> x\<close> and \<open>x \<le> ub_x\<close> have "{lb_x .. x} \<subseteq> common_setX" using common_setX_interval2
by auto
with cont have 2: "continuous_on {lb_x .. x} f" by (auto intro:continuous_on_subset)
from IVT'[where f="f" and a="lb_x" and y="0" and b="x", OF 0 1 \<open>lb_x \<le> x\<close> 2] obtain x' where
"lb_x \<le> x'" and "x' \<le> x" and "f x' = 0" by blast
hence "x' \<in> common_setX" using \<open>x \<le> ub_x\<close> and common_setX_interval2 by auto
with \<open>f x' = 0\<close> and above' show "False" unfolding f_def using common_setX_def by fastforce
qed
theorem between_setY_right_def:
assumes "direction_right"
assumes "x \<in> common_setX"
shows "between_setY x = {ri.f_of_x x <..< le.f_of_x x}"
using assms unfolding between_setY_def using direction_right_cond[OF assms(1)] by force
theorem between_setY_left_def:
assumes "direction_left"
assumes "x \<in> common_setX"
shows "between_setY x = {le.f_of_x x <..< ri.f_of_x x}"
using assms unfolding between_setY_def using direction_left_cond above' by force
lemma between_setY_nonempty: "x \<in> common_setX \<Longrightarrow> between_setY x \<noteq> {}"
proof (cases direction_right)
case True
assume "x \<in> common_setX"
with direction_right_cond[OF True] have "ri.f_of_x x < le.f_of_x x" by auto
from Rats_dense_in_real[OF this] obtain r where "r \<in> between_setY x"
unfolding between_setY_right_def[OF True \<open>x \<in> common_setX\<close>]
using greaterThanLessThan_iff by blast
thus "between_setY x \<noteq> {}" using ex_in_conv
unfolding between_setY_right_def[OF True \<open>x \<in> common_setX\<close>] by auto
next
case False
hence "direction_left" using direction_right_neq_left by blast
assume "x \<in> common_setX"
with direction_left_cond[OF \<open>direction_left\<close>] have "ri.f_of_x x > le.f_of_x x" by auto
from Rats_dense_in_real[OF this] obtain r where "r \<in> between_setY x"
unfolding between_setY_left_def[OF \<open>direction_left\<close> \<open>x \<in> common_setX\<close>]
using greaterThanLessThan_iff by blast
thus "between_setY x \<noteq> {}" using ex_in_conv
unfolding between_setY_left_def[OF \<open>direction_left\<close> \<open>x \<in> common_setX\<close>] by auto
qed
lemma between_setY_nonempty': "x \<in> open_common_setX \<Longrightarrow> between_setY x \<noteq> {}"
using between_setY_nonempty by auto
definition drivable_area :: "real2 set" where
"drivable_area \<equiv> {(x,y). x \<in> open_common_setX \<and> y \<in> between_setY x}"
lemma drivable_areaI:
assumes "x \<in> open_common_setX"
assumes "y \<in> between_setY x"
shows "(x,y) \<in> drivable_area"
using assms unfolding drivable_area_def by auto
lemma drivable_areaD1: "z \<in> drivable_area \<Longrightarrow> fst z \<in> common_setX"
by (auto simp add:drivable_area_def)
lemma drivable_areaD1' : "z \<in> drivable_area \<Longrightarrow> fst z \<in> open_common_setX"
by (auto simp add:drivable_area_def)
lemma drivable_areaD2: "z \<in> drivable_area \<Longrightarrow> snd z \<in> between_setY (fst z)"
by (auto simp add:drivable_area_def)
lemma drivable_area_alt_def:
"drivable_area = Sigma open_common_setX between_setY"
proof (unfold set_eq_subset, rule conjI, rule_tac [!] subsetI)
fix x
assume "x \<in> drivable_area"
hence 0: "fst x \<in> open_common_setX \<and> snd x \<in> between_setY (fst x)"
unfolding drivable_area_def by auto
have "(fst x, snd x) \<in> Sigma open_common_setX between_setY"
apply (rule SigmaI) using 0 by auto
thus "x \<in> Sigma open_common_setX between_setY"
using surjective_pairing by auto
next
fix x
assume 1: "x \<in> Sigma open_common_setX between_setY"
show "x \<in> drivable_area"
proof (rule SigmaE2[of "fst x" "snd x" "open_common_setX" "between_setY"])
from 1 show "(fst x, snd x) \<in> Sigma open_common_setX between_setY"
using surjective_pairing by auto
next
assume "fst x \<in> open_common_setX" and "snd x \<in> between_setY (fst x)"
thus "x \<in> drivable_area" unfolding drivable_area_def by auto
qed
qed
theorem drivable_area_nonempty: "open_common_setX \<noteq> {} \<Longrightarrow> drivable_area \<noteq> {}"
unfolding drivable_area_alt_def common_setX_def
using Sigma_empty_iff between_setY_nonempty' common_setX_def
by fastforce
lemma fst_path_image:
assumes "fst z1 = fst z2"
defines "g \<equiv> linepath z1 z2"
shows "fst ` (path_image g) = {fst z2}"
proof -
from assms have "\<forall>t \<in> {0 .. 1} . fst (g t) = fst z2"
unfolding linepath_def by auto
thus ?thesis unfolding path_image_def by (simp add: assms linepath_image_01)
qed
lemma snd_path_image:
fixes z1 z2 :: real2
assumes "fst z1 = fst z2"
defines "g \<equiv> linepath z1 z2"
defines "lb \<equiv> min (snd z1) (snd z2)"
defines "ub \<equiv> max (snd z1) (snd z2)"
shows "snd ` (path_image g) \<subseteq> {lb .. ub}"
proof -
have "path_image g = (closed_segment z1 z2)" and "path_image g = closed_segment z2 z1"
unfolding path_image_def g_def using linepath_image_01[of "z1" "z2"] by auto
hence "\<And>x y. (x, y) \<in> path_image g \<Longrightarrow> y \<in> closed_segment (snd z1) (snd z2) \<and>
y \<in> closed_segment (snd z2) (snd z1)"
using closed_segment_PairD surjective_pairing by metis
hence "snd ` (path_image g) \<subseteq> closed_segment (snd z1) (snd z2)" and
"snd ` (path_image g) \<subseteq> closed_segment (snd z2) (snd z1)" by auto
thus ?thesis using closed_segment_eq_real_ivl assms(2)
unfolding lb_def ub_def by smt
qed
lemma snd_path_image':
fixes z1 z2 :: real2
assumes "fst z1 = fst z2"
assumes "z1 \<in> drivable_area" and "z2 \<in> drivable_area"
defines "g \<equiv> linepath z1 z2"
defines "lb \<equiv> min (snd z1) (snd z2)"
defines "ub \<equiv> max (snd z1) (snd z2)"
shows "snd ` (path_image g) \<subseteq> between_setY (fst z2)"
proof (cases "direction_right")
case True
from snd_path_image have "snd ` (path_image g) \<subseteq> {lb .. ub}"
using assms by auto
moreover from assms(2-3) have "ri.f_of_x (fst z1) < snd z1" and "snd z2 < le.f_of_x (fst z2)"
unfolding drivable_area_def using between_setY_right_def[OF True] by auto
moreover from assms(2-3) have "ri.f_of_x (fst z2) < snd z2" and "snd z1 < le.f_of_x (fst z1)"
unfolding drivable_area_def using between_setY_right_def[OF True] by auto
ultimately show ?thesis using assms(1) between_setY_right_def[OF True] unfolding lb_def ub_def
by (smt assms(3) atLeastAtMost_iff drivable_areaD1 greaterThanLessThan_iff subset_eq)
next
case False
from snd_path_image have "snd ` (path_image g) \<subseteq> {lb .. ub}"
using assms by auto
moreover from assms(2-3) have "ri.f_of_x (fst z1) > snd z1"
unfolding drivable_area_def using between_setY_left_def False by fastforce
moreover from assms(2-3) have "snd z2 > le.f_of_x (fst z2)"
unfolding drivable_area_def using between_setY_left_def False by fastforce
moreover from assms(2-3) have "ri.f_of_x (fst z2) > snd z2"
unfolding drivable_area_def using between_setY_left_def False by fastforce
moreover from assms(2-3) have "snd z1 > le.f_of_x (fst z1)"
unfolding drivable_area_def using between_setY_left_def False by fastforce
ultimately show ?thesis using assms(1) between_setY_left_def False unfolding lb_def ub_def
by (smt assms(3) atLeastAtMost_iff direction_right_neq_left drivable_areaD1 greaterThanLessThan_iff subset_eq)
qed
definition midcurve_points :: "real2 set" where
"midcurve_points \<equiv> {(x,y) . x \<in> open_common_setX \<and> y = (le.f_of_x x + ri.f_of_x x) / 2}"
lemma midcurve_pointsI:
assumes "x \<in> open_common_setX"
assumes "y =(le.f_of_x x + ri.f_of_x x) * inverse 2 "
shows "(x, y) \<in> midcurve_points"
unfolding midcurve_points_def using assms by auto
lemma midcurve_points_inside_drivable_area:
"midcurve_points \<subseteq> drivable_area"
proof (rule subsetI, rename_tac "z")
fix z :: real2
assume 0: "z \<in> midcurve_points"
from this obtain x y where 1: "z = (x,y)" by fastforce
with 0 have 2: "x \<in> open_common_setX \<and> y = (le.f_of_x x + ri.f_of_x x) / 2"
unfolding midcurve_points_def by auto
hence "y \<in> between_setY x"
using simple_road.between_setY_nonempty simple_road_axioms between_setY_left_def
between_setY_right_def direction_right_neq_left by fastforce
with 2 have "z \<in> Sigma open_common_setX between_setY" using 1 by auto
thus "z \<in> drivable_area" using drivable_area_alt_def by auto
qed
definition midcurve_fun :: "real \<Rightarrow> real" where
"midcurve_fun x = (le.f_of_x x + ri.f_of_x x) * inverse 2"
lemma midcurve_fun_midcurve_points:
"x \<in> open_common_setX \<Longrightarrow> (x, midcurve_fun x) \<in> midcurve_points"
using mem_Collect_eq midcurve_fun_def midcurve_points_def by auto
lemma midcurve_fun_inside_drivable_area:
"x \<in> open_common_setX \<Longrightarrow> (x, midcurve_fun x) \<in> drivable_area"
using midcurve_fun_midcurve_points midcurve_points_inside_drivable_area
by auto
\<comment> \<open>Use @{term "linepath"} instead.\<close>
definition rep_mid :: "real \<Rightarrow> real \<Rightarrow> real \<Rightarrow> real" where
"rep_mid start end \<equiv> (\<lambda>s. start + (end - start) * s)"
(* TODO: combine these two lemmas to make it more general! *)
lemma image_rep_mid:
assumes "start \<le> end"
shows "(rep_mid start end) ` {0 .. 1} = {start .. end}"
proof -
have "(rep_mid start end) ` {0 .. 1} = closed_segment start end"
unfolding rep_mid_def closed_segment_real_eq by auto
thus ?thesis unfolding closed_segment_eq_real_ivl using assms by auto
qed
lemma image_rep_mid2:
assumes "end \<le> start"
shows "(rep_mid start end) ` {0 .. 1} = {end .. start}"
proof -
have "(rep_mid start end) ` {0 .. 1} = closed_segment start end"
unfolding rep_mid_def closed_segment_real_eq by auto
thus ?thesis unfolding closed_segment_eq_real_ivl using assms by auto
qed
definition mid_path where
"mid_path start end \<equiv> (\<lambda>s. (rep_mid start end s, midcurve_fun (rep_mid start end s)))"
lemma continuous_midcurve:
assumes "start \<in> common_setX" and "end \<in> common_setX"
shows "continuous_on {start .. end} midcurve_fun"
unfolding midcurve_fun_def
(* TODO: the proof for the two subgoals have the same structure. Generalise!*)
proof (rule continuous_on_mult_right, rule continuous_on_add)
from convex_common_setX have "{start .. end} \<subseteq> common_setX"
by (metis assms atLeastAtMost_iff atLeastatMost_subset_iff common_setX_interval)
thus "continuous_on {start .. end} le.f_of_x"
using le.cont_f_of_x assms continuous_on_subset common_setX_def by auto
next
from convex_common_setX have "{start .. end} \<subseteq> common_setX"
by (metis assms atLeastAtMost_iff atLeastatMost_subset_iff common_setX_interval)
thus "continuous_on {start .. end} ri.f_of_x"
using ri.cont_f_of_x assms continuous_on_subset common_setX_def by auto
qed
lemma path_mid_path:
assumes "start \<in> common_setX" and "end \<in> common_setX"
shows "path (mid_path start end)"
unfolding path_def mid_path_def
proof (rule continuous_on_Pair)
show "continuous_on {0..1} (rep_mid start end)"
unfolding rep_mid_def by (auto intro!:continuous_intros)
next
have "continuous_on {0..1} (midcurve_fun \<circ> rep_mid start end)"
proof (rule continuous_on_compose)
show "continuous_on {0 .. 1} (rep_mid start end)" unfolding rep_mid_def
by (auto intro!:continuous_intros)
next
show "continuous_on (rep_mid start end ` {0 .. 1}) midcurve_fun"
proof (cases "start \<le> end")
case True
then show ?thesis unfolding image_rep_mid[OF True] using continuous_midcurve[OF assms] by auto
next
case False
hence 0: "end \<le> start" by auto
then show ?thesis unfolding image_rep_mid2[OF 0] using continuous_midcurve[OF assms(2) assms(1)]
by auto
qed
qed
thus " continuous_on {0..1} (\<lambda>x. midcurve_fun (rep_mid start end x))" unfolding comp_def .
qed
lemma pathstart_mid_path:
fixes left_x right_x :: real
assumes "left_x \<in> common_setX" and "right_x \<in> common_setX"
shows "pathstart (mid_path left_x right_x) = (left_x, midcurve_fun left_x)"
using assms unfolding pathstart_def mid_path_def rep_mid_def by auto
lemma pathfinish_mid_path:
fixes left_x right_x :: real
assumes "left_x \<in> common_setX" and "right_x \<in> common_setX"
shows "pathfinish (mid_path left_x right_x) = (right_x, midcurve_fun right_x)"
using assms unfolding pathfinish_def mid_path_def rep_mid_def by auto
lemma rep_mid_in_common_setX:
assumes "s \<in> {0 .. 1}"
assumes "start \<in> open_common_setX" and "end \<in> open_common_setX"
shows "rep_mid start end s \<in> open_common_setX"
proof (cases "start \<le> end")
case True
hence "rep_mid start end ` {0 .. 1} = {start .. end}"
using image_rep_mid[OF True] by auto
also have "... \<subseteq> open_common_setX" using convex_open_common_setX assms(2 - 3)
by (metis True closed_segment_eq_real_ivl convex_contains_segment)
finally show "rep_mid start end s \<in> open_common_setX" using assms(1) by blast
next
case False
hence False2: "end \<le> start" by auto
hence "rep_mid start end ` {0 .. 1} = {end .. start}"
using image_rep_mid2[OF False2] by auto
also have "... \<subseteq> open_common_setX" using convex_open_common_setX assms(2 - 3)
by (metis False closed_segment_eq_real_ivl convex_contains_segment)
finally show "rep_mid start end s \<in> open_common_setX" using assms(1) by blast
qed
lemma mid_path_in_midcurve_points:
assumes "s \<in> {0 .. 1}"
assumes "start \<in> open_common_setX" and "end \<in> open_common_setX"
shows "mid_path start end s \<in> midcurve_points"
unfolding mid_path_def midcurve_fun_def using rep_mid_in_common_setX assms
by (auto intro: midcurve_pointsI)
lemma mid_path_in_midcurve_points2:
assumes "x1 \<in> open_common_setX" and "x2 \<in> open_common_setX"
shows "mid_path x1 x2 ` {0 .. 1} \<subseteq> midcurve_points"
using assms mid_path_in_midcurve_points
unfolding mid_path_def by auto
lemma path_image_mid_path:
assumes "x1 \<in> open_common_setX" and "x2 \<in> open_common_setX"
shows "path_image (mid_path x1 x2) \<subseteq> drivable_area"
using assms mid_path_in_midcurve_points2 midcurve_points_inside_drivable_area
unfolding path_image_def by auto
theorem path_connected_drivable_area:
"path_connected drivable_area"
unfolding path_connected_def
proof (rule ballI, rule ballI, rename_tac z1 z2)
fix z1 z2
assume z1_d:"z1 \<in> drivable_area" and z2_d:"z2 \<in> drivable_area"
from this obtain x1 y1 x2 y2 where z1: "z1 = (x1, y1)" and z2: "z2 = (x2, y2)"
using drivable_area_def by auto
note z1z2 = z1 z1_d z2 z2_d drivable_areaD1 drivable_areaD1'
show "\<exists>g. path g \<and> path_image g \<subseteq> drivable_area \<and> pathstart g = z1 \<and> pathfinish g = z2"
proof (cases "x1 = x2")
case True
define g where "g \<equiv> linepath z1 z2"
\<comment> \<open>proving first conjunct @{term "path g"}\<close>
hence "path g" unfolding path_def by auto
\<comment> \<open>proving second conjunct @{term "path_image g \<subseteq> drivable_area"}\<close>
moreover have "path_image g \<subseteq> drivable_area"
unfolding drivable_area_def
proof (rule subsetI, rename_tac z, unfold mem_Collect_eq)
fix z
assume 0: "z \<in> path_image g"
from this obtain x y where 1: "z = (x,y)" using prod.exhaust by blast
from fst_path_image[of "z1" "z2"] have "fst ` (path_image g) = {x2}"
unfolding g_def using z1 z2 True by auto
with 0 and 1 have "x = x2" by (metis Domain.DomainI Domain_fst singletonD)
with z2 have 2: "x \<in> open_common_setX" using drivable_areaD1'[OF z2_d] by auto
moreover from snd_path_image'[of "z1" "z2"] have "y \<in> between_setY x"
using z1_d z2_d z1 z2 True 0 1 g_def \<open>x = x2\<close> image_subset_iff by auto
ultimately show "case z of (x,y) \<Rightarrow> x \<in> open_common_setX \<and> y \<in> between_setY x"
using 1 by auto
qed
ultimately show ?thesis using pathstart_linepath pathfinish_linepath g_def
by fastforce
next
case False
define g1 where "g1 \<equiv> linepath z1 (x1, midcurve_fun x1) "
define g2 where "g2 \<equiv> mid_path x1 x2 "
define g3 where "g3 \<equiv> linepath (x2, midcurve_fun x2) z2"
define g where "g \<equiv> (g1 +++ g2) +++ g3"
have "pathfinish g1 = (x1, midcurve_fun x1)" unfolding g1_def by auto
moreover have "pathstart g2 = (x1, midcurve_fun x1)" unfolding g2_def
using pathstart_mid_path[of "x1" "x2"] z1 z1_d z2 z2_d drivable_areaD1 by auto
ultimately have 0: "pathfinish g1 = pathstart g2" by auto
have 1: "path (g1 +++ g2)"
proof (rule path_join_imp)
show "path g1" unfolding g1_def by auto
next
show "path g2" unfolding g2_def using path_mid_path[of "x1" "x2"] using z1z2 by auto
next
show "pathfinish g1 = pathstart g2" unfolding g1_def g2_def
using pathstart_mid_path[of "x1" "x2"] z1z2 by auto
qed
have 2: "path g3" unfolding g3_def by auto
have "pathfinish g2 = (x2, midcurve_fun x2)" unfolding g2_def
using pathfinish_mid_path[of "x1" "x2"] z1z2 by auto
moreover have "pathstart g3 = (x2, midcurve_fun x2)" unfolding g3_def by auto
ultimately have "pathfinish g2 = pathstart g3" by auto
hence "pathfinish (g1 +++ g2) = pathstart g3" by auto
\<comment> \<open>proving first conjunct @{term "path g"}\<close>
hence "path g" unfolding g_def using 1 2 by auto
\<comment> \<open>proving third and fourth conjuncts\<close>
have "pathstart g1 = z1" unfolding g1_def by auto
hence "pathstart g = z1" unfolding g_def g1_def by auto
have "pathfinish g3 = z2" unfolding g3_def by auto
hence "pathfinish g = z2" unfolding g_def g3_def by auto
\<comment> \<open>proving the second conjunct\<close>
have "path_image g \<subseteq> drivable_area"
unfolding drivable_area_def g_def
(* TODO : first and third subgoal has the SAME proof structure. Generalise this! *)
proof (rule subset_path_image_join, rule subset_path_image_join, rule_tac[!] subsetI,
rename_tac[!] z, unfold mem_Collect_eq)
fix z
assume 0: "z \<in> path_image g1"
from this obtain x y where 1: "z = (x, y)" unfolding g1_def by fastforce
from fst_path_image[of "z1" "(x1, midcurve_fun x1)"] have "fst ` (path_image g1) = {x1}"
unfolding g1_def using z1 by auto
with 0 and 1 have "x = x1" by (metis Domain.DomainI Domain_fst singletonD)
with z1 have 2: "x \<in> open_common_setX" using drivable_areaD1'[OF z1_d] by auto
moreover from snd_path_image'[of "z1" "(x1, midcurve_fun x1)"] have "y \<in> between_setY x1"
using z1_d z1 0 1 g1_def \<open>x = x1\<close> image_subset_iff midcurve_fun_inside_drivable_area
calculation by auto
ultimately show "case z of (x,y) \<Rightarrow> x \<in> open_common_setX \<and> y \<in> between_setY x"
using 1 \<open>x = x1\<close> by auto
next
fix z
assume "z \<in> path_image g2"
hence "z \<in> drivable_area" unfolding g2_def
using path_image_mid_path[of "x1" "x2"] using z1z2 by auto
thus "case z of (x,y) \<Rightarrow> x \<in> open_common_setX \<and> y \<in> between_setY x"
unfolding drivable_area_alt_def by auto
next
fix z
assume 0: "z \<in> path_image g3"
then obtain x y where 1:"z = (x, y)" unfolding g3_def by fastforce
from fst_path_image[of "z2" "(x2, midcurve_fun x2)"] have "fst ` (path_image g3) = {x2}"
unfolding g3_def using z2 by auto
with 0 and 1 have "x = x2" by (metis Domain.DomainI Domain_fst singletonD)
with z2 have 2: "x \<in> open_common_setX" using drivable_areaD1'[OF z2_d] by auto
moreover from snd_path_image'[of "z2" "(x2, midcurve_fun x2)"] have "y \<in> between_setY x2"
using z2_d z2 0 1 g3_def \<open>x = x2\<close> image_subset_iff midcurve_fun_inside_drivable_area
by (metis (no_types, lifting) calculation fst_conv snd_conv snd_path_image')
ultimately show "case z of (x,y) \<Rightarrow> x \<in> open_common_setX \<and> y \<in> between_setY x"
using 1 \<open>x=x2\<close> by auto
qed
thus ?thesis using \<open>path g\<close> \<open>pathstart g = z1\<close> \<open>pathfinish g = z2\<close> by auto
qed
qed
end
subsection "A generalised simple road"
lemma det3_nonneg_scaleR3:
"0 < e \<Longrightarrow> det3 0 xr P > 0 \<Longrightarrow> det3 0 xr (e *\<^sub>R (P - xr) + xr) > 0"
by (auto simp add: det3_def' algebra_simps)
lemma det3_nonneg_scaleR3':
"0 < e \<Longrightarrow> det3 0 xr P \<le> 0 \<Longrightarrow> det3 0 xr (e *\<^sub>R (P - xr) + xr) \<le> 0"
by (auto simp add: det3_def' algebra_simps)
lemma det3_nonneg_scaleR4:
assumes "0 < e"
assumes "det3 0 xr P > 0"
shows "det3 0 (xr + e *\<^sub>R xr) (P + e *\<^sub>R xr) > 0"
proof -
from assms(2) have 0: "fst P * snd xr < fst xr * snd P" unfolding det3_def'
by (auto simp add:algebra_simps)
with assms(1) have "e * (fst P * snd xr) < e * (fst xr * snd P)" by auto
with 0 have "fst P * snd xr + e * (fst P * snd xr) < fst xr * snd P + e * (fst xr * snd P)"
by auto
thus ?thesis by (auto simp add:det3_def' algebra_simps)
qed
lemma det3_nonneg_scaleR4':
assumes "0 < e"
assumes "det3 0 xr P \<le> 0"
shows "det3 0 (xr + e *\<^sub>R xr) (P + e *\<^sub>R xr) \<le> 0"
proof -
from assms(2) have 0: "fst P * snd xr \<ge> fst xr * snd P" unfolding det3_def'
by (auto simp add:algebra_simps)
with assms(1) have "e * (fst P * snd xr) \<ge> e * (fst xr * snd P)" by auto
with 0 have "fst P * snd xr + e * (fst P * snd xr) \<ge> fst xr * snd P + e * (fst xr * snd P)"
by auto
thus ?thesis by (auto simp add:det3_def' algebra_simps)
qed
lemma det3_invariant1:
assumes "0 < e"
assumes "det3 p q r > 0"
shows "det3 p q (e *\<^sub>R (r - q) + q) > 0"
using assms
proof -
from assms(2) have "det3 0 (q - p) (r - p) > 0" using det3_translate_origin by auto
hence "det3 0 (q - p) (e *\<^sub>R ((r - p) - (q - p)) + (q - p)) > 0"
using det3_nonneg_scaleR3[OF assms(1), of "q - p" "r - p"] by simp
hence "det3 0 (q - p) (e *\<^sub>R (r - q) + (q - p)) > 0" by (auto simp add: det3_def' algebra_simps)
thus "det3 p q (e *\<^sub>R (r - q) + q) > 0" by (auto simp add:det3_def' algebra_simps)
qed
lemma det3_invariant1':
assumes "0 < e"
assumes "det3 p q r > 0"
shows "det3 (p - e *\<^sub>R (q - p)) q r > 0"
using assms
proof -
from assms(2) have "det3 0 (q - p) (r - p) > 0" using det3_translate_origin by auto
from det3_nonneg_scaleR4[OF assms(1) this] show ?thesis using det3_translate_origin
by (metis (no_types, lifting) NO_MATCH_def add_uminus_conv_diff diff_diff_add diff_minus_eq_add)
qed
lemma det3_invariant2:
assumes "0 < e"
assumes "det3 p q r \<le> 0"
shows "det3 p q (e *\<^sub>R (r - q) + q) \<le> 0"
proof -
from assms(2) have "det3 0 (q - p) (r - p) \<le> 0" using det3_translate_origin by auto
hence "det3 0 (q - p) (e *\<^sub>R ((r - p) - (q - p)) + (q - p)) \<le> 0"
using det3_nonneg_scaleR3'[OF assms(1), of "q - p" "r - p"] by simp
hence "det3 0 (q - p) (e *\<^sub>R (r - q) + (q - p)) \<le> 0" by (auto simp add: det3_def' algebra_simps)
thus "det3 p q (e *\<^sub>R (r - q) + q) \<le> 0" by (auto simp add:det3_def' algebra_simps)
qed
lemma det3_invariant2':
assumes "0 < e"
assumes "det3 p q r \<le> 0"
shows "det3 (p - e *\<^sub>R (q - p)) q r \<le> 0"
using assms
proof -
from assms(2) have "det3 0 (q - p) (r - p) \<le> 0" using det3_translate_origin by auto
from det3_nonneg_scaleR4'[OF assms(1) this] show ?thesis using det3_translate_origin
by (metis (no_types, lifting) NO_MATCH_def add_uminus_conv_diff diff_diff_add diff_minus_eq_add)
qed
theorem ccw_invariant:
assumes "0 < e"
shows "ccw' p q r = ccw' p q (e *\<^sub>R (r - q) + q)"
unfolding ccw'_def
using det3_invariant1[OF assms] det3_invariant2[OF assms]
proof -
have "\<forall>x0 x1 x2. (0 < det3 x2 x1 x0) = (\<not> det3 x2 x1 x0 \<le> 0)"
by linarith
then show "(0 < det3 p q r) = (0 < det3 p q (e *\<^sub>R (r - q) + q))"
by (metis (no_types) \<open>\<And>r q p. 0 < det3 p q r \<Longrightarrow> 0 < det3 p q (e *\<^sub>R (r - q) + q)\<close>
\<open>\<And>r q p. det3 p q r \<le> 0 \<Longrightarrow> det3 p q (e *\<^sub>R (r - q) + q) \<le> 0\<close>)
qed
theorem ccw_invariant':
assumes "0 < e"
shows "ccw' p q r = ccw' (p - e *\<^sub>R (q - p)) q r"
unfolding ccw'_def
using det3_invariant1'[OF assms] det3_invariant2'[OF assms]
by smt
lemma det3_nonneg_scaleR1_eq':
"0 < e \<Longrightarrow> det3 0 (e*\<^sub>Rxr) P < 0 \<longleftrightarrow> det3 0 xr P < 0"
by (auto simp add: det3_def' algebra_simps)
lemma det3_nonneg_scaleR1_eq'':
"0 < e \<Longrightarrow> det3 0 (e*\<^sub>Rxr) P = 0 \<longleftrightarrow> det3 0 xr P = 0"
by (auto simp add: det3_def' algebra_simps)
lemma det3_nonneg_scaleR_segment1':
assumes "det3 x y z < 0"
assumes "0 \<le> a" "a < 1"
shows "det3 ((1 - a) *\<^sub>R x + a *\<^sub>R y) y z < 0"
proof -
from assms have "det3 0 ((1 - a) *\<^sub>R (y - x)) (z - x + (- a) *\<^sub>R (y - x)) < 0"
by (subst det3_nonneg_scaleR1_eq') (auto simp add: det3_def' algebra_simps)
thus ?thesis
by (auto simp: algebra_simps det3_translate_origin)
qed
lemma det3_nonneg_scaleR_segment1'':
assumes "det3 x y z \<noteq> 0"
assumes "0 \<le> a" "a < 1"
shows "det3 ((1 - a) *\<^sub>R x + a *\<^sub>R y) y z \<noteq> 0"
proof -
from assms have "det3 0 ((1 - a) *\<^sub>R (y - x)) (z - x + (- a) *\<^sub>R (y - x)) \<noteq> 0"
by (subst det3_nonneg_scaleR1_eq'') (auto simp add: det3_def' algebra_simps)
thus ?thesis
by (auto simp: algebra_simps det3_translate_origin)
qed
theorem ccw_invariant'':
assumes "0 \<le> e" and "e < 1"
shows "ccw' p q r = ccw' ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r"
unfolding ccw'_def
proof (rule iffI, rule_tac[2] contrapos_np[where Q="\<not> 0 < det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r"])
assume "0 < det3 p q r"
hence "0 \<le> det3 p q r" and "det3 p q r \<noteq> 0" by auto
from det3_nonneg_scaleR_segment1[OF this(1) assms] have "0 \<le> det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r "
by auto
moreover
from det3_nonneg_scaleR_segment1''[OF \<open>det3 p q r \<noteq> 0\<close> assms] have "det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r \<noteq> 0"
by auto
ultimately show "0 < det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r" by auto
next
assume "0 < det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r"
thus "\<not> \<not> 0 < det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r" by auto
next
assume "\<not> 0 < det3 p q r"
hence "det3 p q r \<le> 0" by auto
hence "det3 p q r < 0 \<or> det3 p q r = 0" by auto
moreover
{ assume "det3 p q r < 0"
from det3_nonneg_scaleR_segment1'[OF this assms] have " det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r < 0" .
hence "\<not> 0 < det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r" by auto }
moreover
{ assume "det3 p q r = 0"
with det3_nonneg_scaleR_segment1''[OF _ assms, of "p" "q" "r"] have "det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r = 0"
using assms(1) assms(2) coll_convex det3_rotate by auto
hence "\<not> 0 < det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r" by auto }
ultimately show "\<not> 0 < det3 ((1 - e) *\<^sub>R p + e *\<^sub>R q) q r" by auto
qed
definition line_equation :: "real2 \<Rightarrow> real2 \<Rightarrow> real \<Rightarrow> real" where
"line_equation p1 p2 \<equiv> (\<lambda>x. (snd p2 - snd p1) / (fst p2 - fst p1) * (x - fst p1) + snd p1)"
lemma line_equation_alt_def:
"line_equation p1 p2 \<equiv> (\<lambda>x. (snd p2 - snd p1) / (fst p2 - fst p1) * x - (snd p2 - snd p1) / (fst p2 - fst p1) * fst p1 + snd p1)"
unfolding line_equation_def using right_diff_distrib[of "(snd p2 - snd p1) / (fst p2 - fst p1)" _ "fst p1"]
by auto
lemma
"line_equation p1 p2 (fst p1) = (snd p1)"
unfolding line_equation_def by (auto simp add:algebra_simps)
lemma
assumes "fst p1 \<noteq> fst p2"
shows "line_equation p1 p2 (fst p2) = (snd p2)"
unfolding line_equation_def using assms by (auto simp add:divide_simps)
theorem line_eq_differentiable:
assumes "fst p1 \<noteq> fst p2"
shows "line_equation p1 p2 differentiable at x"
using assms unfolding line_equation_def by (auto intro:derivative_intros)
theorem
assumes "fst p1 \<noteq> fst p2"
shows "((line_equation) p1 p2 has_field_derivative ((snd p2 - snd p1) / (fst p2 - fst p1))) (at x within s)"
proof -
have "fst p2 - fst p1 \<noteq> 0" using assms by auto
hence 0: "line_equation p1 p2 \<equiv> (\<lambda>x. (snd p2 - snd p1) / (fst p2 - fst p1) * x - (snd p2 - snd p1) / (fst p2 - fst p1) * fst p1 + snd p1)"
unfolding line_equation_alt_def by auto
define const :: "real \<Rightarrow> real" where "const \<equiv> \<lambda>x. snd p1 - (snd p2 - snd p1) / (fst p2 - fst p1) * fst p1"
hence cdx: "const differentiable at x" using assms by (auto intro:derivative_intros)
define inner :: "real \<Rightarrow> real" where "inner \<equiv> \<lambda>x. (snd p2 - snd p1) / (fst p2 - fst p1) * x"
hence idx: "inner differentiable at x" using assms by (auto intro:derivative_intros)
have idx':"(inner has_field_derivative (snd p2 - snd p1) / (fst p2 - fst p1)) (at x within s)"
unfolding inner_def using DERIV_cmult_Id[of "(snd p2 - snd p1) / (fst p2 - fst p1)"] by blast
have 1: "line_equation p1 p2 \<equiv> \<lambda>x. inner x + const x" unfolding 0 inner_def const_def
by (auto simp add:algebra_simps)
have "(line_equation p1 p2 has_field_derivative ((snd p2 - snd p1) / (fst p2 - fst p1)) + 0) (at x within s)"
unfolding 1 by (intro Deriv.field_differentiable_add) (auto simp add:idx' const_def)
thus ?thesis by auto
qed
lemma line_equation_closed_segment:
assumes "p \<in> closed_segment p1 p2"
assumes "fst p1 \<noteq> fst p2"
shows "line_equation p1 p2 (fst p) = snd p"
proof -
from assms(1) obtain t where "0 \<le> t" and "t \<le> 1" and "p = (1 -t) *\<^sub>R p1 + t *\<^sub>R p2"
unfolding closed_segment_def by auto
hence "p = p1 + t*\<^sub>R (p2 - p1)" by (auto simp add:algebra_simps)
hence f: "fst p - fst p1 = t * (fst p2 - fst p1)" and
s: "snd p - snd p1 = t * (snd p2 - snd p1)" by (auto simp add:field_simps)
consider "t = 0" | "t \<noteq> 0" by auto
thus ?thesis
proof (cases)
case 1
then show ?thesis unfolding line_equation_def f using s assms(2) by auto
next
case 2
have "(snd p2 - snd p1) / (fst p2 - fst p1) * (fst p - fst p1) = snd p - snd p1" (is "?lhs = ?rhs")
proof -
have "?lhs = (snd p2 - snd p1) / (fst p2 - fst p1) * t * (fst p2 - fst p1)"
using f by auto
also have "... = t * (snd p2 - snd p1)" using assms(2) by auto
also have "... = ?rhs" using s by auto
finally show "?lhs = ?rhs" by auto
qed
then show ?thesis unfolding line_equation_def by auto
qed
qed
locale simple_road2 = le: simple_boundary curve_left domain + ri: simple_boundary curve_right domain
for curve_left and curve_right and domain +
assumes domain_nonempty: "domain \<noteq> {}"
\<comment>\<open>The following assumption can be easily checked with @{thm "simple_boundary.checking_strict_mono"}.\<close>
assumes mono_x_le: "strict_mono_in le.curve_eq_x domain"
and mono_x_ri: "strict_mono_in ri.curve_eq_x domain"
assumes non_intersecting: "\<forall>t\<in>domain. curve_left t \<noteq> curve_right t"
assumes diff_ri:"curve_right differentiable (at_right (Inf domain))"
assumes diff_le: "curve_left differentiable (at_right (Inf domain))"
begin
abbreviation common_setX where
"common_setX \<equiv> le.setX \<inter> ri.setX"
definition left_start_boundary :: "real \<Rightarrow> real2" where
"left_start_boundary \<equiv> (let t_inf = Inf domain; le_inf = curve_left t_inf;
ri_inf = curve_right t_inf; le_x = fst le_inf; ri_x = fst ri_inf
in
if le_x \<le> ri_x then linepath le_inf ri_inf else linepath ri_inf le_inf)"
theorem left_boundary_param_x_strict_mono:
assumes "fst (curve_left (Inf domain)) \<noteq> fst (curve_right (Inf domain))"
shows "strict_mono_in (fst \<circ> left_start_boundary) {0..1}"
unfolding comp_def left_start_boundary_def Let_def
proof (split if_splits, rule conjI, rule_tac[!] impI, rule_tac[!] strict_mono_inI)
fix x y :: real
assume "x \<in> {0..1}" and "y \<in> {0..1}"
assume "x < y"
hence "0 < y - x" by auto
assume "fst (curve_left (Inf domain)) \<le> fst (curve_right (Inf domain))"
with assms have 0: "fst (curve_left (Inf domain)) < fst (curve_right (Inf domain))" by auto
define cli where "cli \<equiv> curve_left (Inf domain)"
define cri where "cri \<equiv> curve_right (Inf domain)"
with cli_def and 0 have "fst cli < fst cri" by auto
have 1: "fst \<circ> (linepath cli cri) = (\<lambda>x. (1 - x) * (fst cli) + x * (fst cri))"
unfolding comp_def linepath_def by auto
have "(fst \<circ> (linepath cli cri)) x < (fst \<circ> (linepath cli cri)) y"
proof -
from \<open>fst cli < fst cri\<close> have "fst cli * (y - x) < fst cri *(y - x)" (is "?lhs1 < ?rhs1")
using \<open>x < y\<close> mult_strict_right_mono by auto
hence "fst cli + ?lhs1 < fst cli + ?rhs1" by linarith
hence "(1 - x) * fst cli + x * fst cri < (1 - y) * fst cli + y * fst cri"
by (auto simp add:algebra_simps)
with 1 show ?thesis by auto
qed
thus "fst (linepath (curve_left (Inf domain)) (curve_right (Inf domain)) x)
< fst (linepath (curve_left (Inf domain)) (curve_right (Inf domain)) y)"
unfolding comp_def cli_def cri_def by auto
next
fix x y :: real
assume "x \<in> {0..1}" and "y \<in> {0..1}"
assume "x < y"
define cli where "cli \<equiv> curve_left (Inf domain)"
define cri where "cri \<equiv> curve_right (Inf domain)"
assume "\<not> fst (curve_left (Inf domain)) \<le> fst (curve_right (Inf domain))"
hence "fst cli > fst cri" unfolding cli_def cri_def by auto
have 2: "fst \<circ> (linepath cri cli) = (\<lambda>x. (1 - x) * (fst cri) + x * (fst cli))"
unfolding comp_def linepath_def by auto
have "(fst \<circ> (linepath cri cli)) x < (fst \<circ> (linepath cri cli)) y"
proof -
from \<open>fst cri < fst cli\<close> have "fst cri * (y - x) < fst cli *(y - x)" (is "?lhs1 < ?rhs1")
using \<open>x < y\<close> mult_strict_right_mono by auto
hence "fst cri + ?lhs1 < fst cri + ?rhs1" by linarith
hence "(1 - x) * fst cri + x * fst cli < (1 - y) * fst cri + y * fst cli"
by (auto simp add:algebra_simps)
with 2 show ?thesis by auto
qed
thus " fst (linepath (curve_right (Inf domain)) (curve_left (Inf domain)) x)
< fst (linepath (curve_right (Inf domain)) (curve_left (Inf domain)) y)"
unfolding comp_def cli_def cri_def by auto
qed
definition right_start_boundary :: "real \<Rightarrow> real2" where
"right_start_boundary \<equiv> (let t_sup = Sup domain; le_sup = curve_left t_sup;
ri_sup = curve_right t_sup; le_x = fst le_sup; ri_x = fst ri_sup
in
if ri_x \<le> le_x then linepath ri_sup le_sup else linepath le_sup ri_sup)"
theorem right_boundary_param_x_strict_mono:
assumes "fst (curve_left (Sup domain)) \<noteq> fst (curve_right (Sup domain))"
shows "strict_mono_in (fst \<circ> right_start_boundary) {0..1}"
unfolding comp_def right_start_boundary_def Let_def
proof (split if_splits, rule conjI, rule_tac[!] impI, rule_tac[!] strict_mono_inI)
fix x y :: real
assume "x \<in> {0..1}" and "y \<in> {0..1}"
assume "x < y"
hence "0 < y - x" by auto
assume "fst (curve_right (Sup domain)) \<le> fst (curve_left (Sup domain))"
with assms have 0: "fst (curve_right (Sup domain)) < fst (curve_left (Sup domain))" by auto
define cls where "cls \<equiv> curve_left (Sup domain)"
define crs where "crs \<equiv> curve_right (Sup domain)"
with cls_def and 0 have "fst crs < fst cls" by auto
have 1: "fst \<circ> (linepath crs cls) = (\<lambda>x. (1 - x) * (fst crs) + x * (fst cls))"
unfolding comp_def linepath_def by auto
have "(fst \<circ> (linepath crs cls)) x < (fst \<circ> (linepath crs cls)) y"
proof -
from \<open>fst crs < fst cls\<close> have "fst crs * (y - x) < fst cls *(y - x)" (is "?lhs1 < ?rhs1")
using \<open>x < y\<close> mult_strict_right_mono by auto
hence "fst cls + ?lhs1 < fst cls + ?rhs1" by linarith
hence "(1 - x) * fst crs + x * fst cls < (1 - y) * fst crs + y * fst cls"
by (auto simp add:algebra_simps)
with 1 show ?thesis by auto
qed
thus "fst (linepath (curve_right (Sup domain)) (curve_left (Sup domain)) x)
< fst (linepath (curve_right (Sup domain)) (curve_left (Sup domain)) y)"
unfolding comp_def cls_def crs_def by auto
next
fix x y :: real
assume "x \<in> {0..1}" and "y \<in> {0..1}"
assume "x < y"
hence "0 < y - x" by auto
define cls where "cls \<equiv> curve_left (Sup domain)"
define crs where "crs \<equiv> curve_right (Sup domain)"
assume "\<not> fst (curve_right (Sup domain)) \<le> fst (curve_left (Sup domain))"
hence "fst crs > fst cls" using cls_def crs_def by auto
have 1: "fst \<circ> (linepath cls crs) = (\<lambda>x. (1 - x) * (fst cls) + x * (fst crs))"
unfolding comp_def linepath_def by auto
have "(fst \<circ> (linepath cls crs)) x < (fst \<circ> (linepath cls crs)) y"
proof -
from \<open>fst crs > fst cls\<close> have "fst crs * (y - x) > fst cls *(y - x)" (is "?lhs1 > ?rhs1")
using \<open>x < y\<close> mult_strict_right_mono by auto
hence "fst crs + ?lhs1 > fst crs + ?rhs1" by linarith
hence "(1 - x) * fst cls + x * fst crs < (1 - y) * fst cls + y * fst crs"
by (auto simp add:algebra_simps)
with 1 show ?thesis by auto
qed
thus "fst (linepath (curve_left (Sup domain)) (curve_right (Sup domain)) x)
< fst (linepath (curve_left (Sup domain)) (curve_right (Sup domain)) y)"
unfolding comp_def cls_def crs_def by auto
qed
theorem domain_inf_sup:
"domain = {Inf domain .. Sup domain}"
proof -
from le.domain_interval obtain a and b where "domain = {a .. b}" by auto
with domain_nonempty have "a \<le> b" by auto
with \<open>domain = {a .. b}\<close> have "Inf domain = a" and "Sup domain = b" by auto
with \<open>domain = {a .. b}\<close> show ?thesis by auto
qed
theorem domain_closed_segment_inf_sup:
"domain = closed_segment (Inf domain) (Sup domain)"
using domain_inf_sup closed_segment_real cInf_le_cSup[OF domain_nonempty le.bdd_above_domain
le.bdd_below_domain] by auto
theorem inf_in_dom:
"Inf domain \<in> domain"
using closed_contains_Inf[OF domain_nonempty le.bdd_below_domain le.closed_domain] by auto
theorem sup_in_dom:
"Sup domain \<in> domain"
using closed_contains_Sup[OF domain_nonempty le.bdd_above_domain le.closed_domain] by auto
definition ri_tangent_at_inf where
"ri_tangent_at_inf \<equiv> vector_derivative curve_right (at_right (Inf domain))"
definition le_tangent_at_inf where
"le_tangent_at_inf \<equiv> vector_derivative curve_left (at_right (Inf domain))"
theorem ri_v_deriv_at_inf:
"(curve_right has_vector_derivative ri_tangent_at_inf) (at_right (Inf domain))"
using diff_ri by (auto simp add: vector_derivative_works ri_tangent_at_inf_def)
theorem le_v_deriv_at_inf:
"(curve_left has_vector_derivative le_tangent_at_inf) (at_right (Inf domain))"
using diff_le by (auto simp add: vector_derivative_works le_tangent_at_inf_def)
\<comment>\<open>The tangent line for the right curve at 0.\<close>
definition cr_tangent_line :: "real2 set" where
"cr_tangent_line \<equiv> {(x, y). \<exists>t>0. (x, y) = curve_right 0 + t *\<^sub>R ri_tangent_at_inf}"
definition cl_tangent_line :: "real2 set" where
"cl_tangent_line \<equiv> {(x, y). \<exists>t>0. (x, y) = curve_left 0 + t *\<^sub>R le_tangent_at_inf}"
theorem cr_tangent_line_nonempty:
"\<exists>x. x \<in> cr_tangent_line"
proof -
obtain x and y where "(x,y) = curve_right 0 + 1 *\<^sub>R ri_tangent_at_inf" using prod.collapse by blast
hence "\<exists>t>0. (x, y) = curve_right 0 + t *\<^sub>R ri_tangent_at_inf"
by (auto intro: exI[where x="1"])
thus ?thesis unfolding cr_tangent_line_def by auto
qed
theorem cl_tangent_line_nonempty:
"\<exists>x. x \<in> cl_tangent_line"
proof -
obtain x and y where "(x,y) = curve_left 0 + 1 *\<^sub>R le_tangent_at_inf" using prod.collapse by blast
hence "\<exists>t>0. (x, y) = curve_left 0 + t *\<^sub>R le_tangent_at_inf"
by (auto intro: exI[where x="1"])
thus ?thesis unfolding cl_tangent_line_def by auto
qed
theorem cr_tangent_line_D1:
assumes "x \<in> cr_tangent_line"
obtains t where "x = curve_right 0 + t *\<^sub>R ri_tangent_at_inf" and "0 < t"
using assms prod.collapse unfolding cr_tangent_line_def by auto
theorem cl_tangent_line_D1:
assumes "x \<in> cl_tangent_line"
obtains t where "x = curve_left 0 + t *\<^sub>R le_tangent_at_inf" and "0 < t"
using assms prod.collapse unfolding cl_tangent_line_def by auto
\<comment>\<open>Basically we can use any point in the tangent line to determine the direction of the simple road.
To be more exact, all points in the direction of the tangent line.\<close>
theorem ri_ccw'_on_tangent_line:
assumes "p1 \<in> cr_tangent_line" and "p2 \<in> cr_tangent_line"
shows "ccw' (curve_left 0) (curve_right 0) p1 = ccw' (curve_left 0) (curve_right 0) p2"
proof -
from assms obtain t1 where "p1 = curve_right 0 + t1 *\<^sub>R ri_tangent_at_inf" and "0 < t1"
using cr_tangent_line_D1 by blast
hence "ri_tangent_at_inf = (1 / t1) *\<^sub>R (p1 - curve_right 0)" by (auto simp add:divide_simps)
moreover
from assms obtain t2 where "p2 = curve_right 0 + t2 *\<^sub>R ri_tangent_at_inf" and "0 < t2"
using cr_tangent_line_D1 by blast
ultimately have *: "p2 = curve_right 0 + (t2 / t1) *\<^sub>R (p1 - curve_right 0)" and "0 < t2 / t1"
using \<open>0 < t1\<close> by (auto simp add:divide_simps)
show ?thesis unfolding *
using ccw_invariant[OF \<open>0 < t2 / t1\<close>, of "curve_left 0" "curve_right 0" "p1"]
by (auto simp add:algebra_simps)
qed
theorem le_ccw'_on_tangent_line:
assumes "p1 \<in> cl_tangent_line" and "p2 \<in> cl_tangent_line"
shows "ccw' p1 (curve_left 0) (curve_right 0) = ccw' p2 (curve_left 0) (curve_right 0)"
proof -
from assms obtain t1 where t1_cond: "p1 = curve_left 0 + t1 *\<^sub>R le_tangent_at_inf" and "0 < t1"
using cl_tangent_line_D1 by blast
hence letai_def: "le_tangent_at_inf = (1 / t1) *\<^sub>R (p1 - curve_left 0)" by (auto simp add:divide_simps)
from assms obtain t2 where t2_cond: "p2 = curve_left 0 + t2 *\<^sub>R le_tangent_at_inf" and "0 < t2"
using cl_tangent_line_D1 by blast
have "t1 < t2 \<or> t1 \<ge> t2 " by auto
moreover
{ assume "t1 < t2"
from t1_cond and t2_cond have "p2 = p1 + (t2 - t1) *\<^sub>R le_tangent_at_inf"
by (auto simp add:algebra_simps)
with letai_def have p2_def: "p2 = p1 + ((t2 - t1) / t1) *\<^sub>R (p1 - curve_left 0)"
by (auto simp add:field_simps)
from \<open>t1 < t2\<close> and \<open>0 < t1\<close> have "0 < (t2 - t1) / t1" by auto
have ?thesis unfolding p2_def
using ccw_invariant'[OF \<open>0 < (t2 - t1) / t1\<close>, of "p1" "curve_left 0" "curve_right 0"]
by (simp add: add_diff_eq diff_diff_eq2 real_vector.scale_right_diff_distrib) }
moreover
{ assume "t1 \<ge> t2"
from t1_cond and t2_cond and letai_def
have "p2 = curve_left 0 + (t2 / t1) *\<^sub>R (p1 - curve_left 0)" and "0 < t2 / t1"
using \<open>0 < t1\<close> \<open>0 < t2\<close> by (auto simp add:divide_simps)
hence *: "p2 = (1 - t2 / t1) *\<^sub>R (curve_left 0) + (t2 / t1) *\<^sub>R p1"
by (smt add.commute add.left_commute diff_add_cancel scaleR_add_left scaleR_add_right scaleR_one)
hence **: "p2 = (1 - t2 / t1) *\<^sub>R (curve_left 0) + (1 - (1 - t2 / t1)) *\<^sub>R p1"
by auto
from \<open>0 < t2 /t1\<close> \<open>t1 \<ge> t2\<close> and \<open>0 < t1\<close> have "0 \<le> 1 - t2 / t1" and "1 - t2 / t1 < 1" by auto
from ccw_invariant''[OF this] have ?thesis using ** by (metis add.commute) }
ultimately show ?thesis by auto
qed
definition direction_right :: bool where
"direction_right \<equiv> (let
inf_dom = Inf domain;
cl_inf = curve_left inf_dom; cr_inf = curve_right inf_dom;
tgt_ri = cr_inf + 1 *\<^sub>R ri_tangent_at_inf;
tgt_le = cl_inf + 1 *\<^sub>R le_tangent_at_inf
in
if min2D cr_inf cl_inf = cr_inf then
ccw' cl_inf cr_inf tgt_ri
else
ccw' tgt_le cl_inf cr_inf)"
definition direction_left :: bool where
"direction_left \<equiv> (let
inf_dom = Inf domain;
cl_inf = curve_left inf_dom; cr_inf = curve_right inf_dom;
tgt_ri = cr_inf + 1 *\<^sub>R ri_tangent_at_inf;
tgt_le = cl_inf + 1 *\<^sub>R le_tangent_at_inf
in
if min2D cr_inf cl_inf = cr_inf then
det3 cl_inf cr_inf tgt_ri < 0
else
det3 tgt_le cl_inf cr_inf < 0)"
definition open_domain :: "real set" where
"open_domain \<equiv> domain - {Inf domain, Sup domain}"
theorem convex_open_domain:
"convex open_domain"
unfolding open_domain_def using le.convex_domain extreme_point_of_stillconvex[of "domain"]
domain_closed_segment_inf_sup inf_in_dom sup_in_dom
by (metis atLeastAtMost_diff_ends convex_real_interval(8) domain_inf_sup)
lemma open_domain_subset_domain:
"t \<in> open_domain \<Longrightarrow> t \<in> domain"
unfolding open_domain_def by auto
definition inside :: "real2 set" where
"inside \<equiv> {(x,y). \<exists>t \<in> open_domain. (x,y) \<in> open_segment (curve_left t) (curve_right t)}"
definition insideP :: "real2 \<Rightarrow> bool" where
"insideP x \<equiv> \<exists>t \<in> open_domain. x \<in> open_segment (curve_left t) (curve_right t)"
theorem insideP_eq:
"(x \<in> inside) = insideP x"
unfolding insideP_def inside_def by auto
theorem insidePI[intro]:
assumes "t \<in> open_domain"
assumes "x \<in> open_segment (curve_left t) (curve_right t)"
shows "insideP x"
using assms unfolding insideP_def by auto
theorem insidePD:
assumes "insideP x"
obtains t where "t \<in> open_domain \<and> x \<in> open_segment (curve_left t) (curve_right t)"
using assms unfolding insideP_def by auto
definition midcurve_eq :: "real \<Rightarrow> real2" where
"midcurve_eq \<equiv> \<lambda>t. (1 / 2) *\<^sub>R (curve_left t + curve_right t)"
theorem midcurve_inside:
assumes "t \<in> open_domain"
shows "midcurve_eq t \<in> inside"
unfolding midcurve_eq_def insideP_eq
proof (intro insidePI, rule assms, unfold in_segment(2), rule conjI)
from assms have "t \<in> domain" using open_domain_subset_domain by auto
with non_intersecting show "curve_left t \<noteq> curve_right t" by auto
next
show "\<exists>u>0. u < 1 \<and> (1 / 2) *\<^sub>R (curve_left t + curve_right t) =
(1 - u) *\<^sub>R curve_left t + u *\<^sub>R curve_right t "
by(rule exI[where x="1/2"]) (auto simp add:algebra_simps)
qed
theorem midcurve_in_open_segment:
assumes "t \<in> open_domain"
shows "midcurve_eq t \<in> open_segment (curve_left t) (curve_right t)"
unfolding midcurve_eq_def in_segment(2)
proof
from assms have "t \<in> domain" unfolding open_domain_def by auto
with non_intersecting show "curve_left t \<noteq> curve_right t" by auto
next
show "\<exists>u>0. u < 1 \<and> (1 / 2) *\<^sub>R (curve_left t + curve_right t) =
(1 - u) *\<^sub>R curve_left t + u *\<^sub>R curve_right t "
by(rule exI[where x="1/2"]) (auto simp add:algebra_simps)
qed
theorem continuous_midcurve_eq:
"continuous_on domain midcurve_eq"
unfolding midcurve_eq_def using le.continuous ri.continuous
by (auto simp add:continuous_intros)
theorem
"path_connected inside"
unfolding path_connected_def
proof (rule ballI, rule ballI, rename_tac z1 z2)
fix z1 z2
assume "z1 \<in> inside" and "z2 \<in> inside"
hence "insideP z1" and inz2: "insideP z2" using insideP_eq by auto
then obtain t1 where "t1 \<in> open_domain" and "z1 \<in> open_segment (curve_left t1) (curve_right t1)"
using insidePD by blast
from inz2 obtain t2 where "t2 \<in> open_domain" and "z2 \<in> open_segment (curve_left t2) (curve_right t2)"
using insidePD by blast
obtain z1' and z2' where "z1' = midcurve_eq t1" and "z2' = midcurve_eq t2" by auto
obtain path1 and path2 where path1_def: "path1 \<equiv> linepath z1 z1'" and
path2_def: "path2 \<equiv> linepath z2' z2" by auto
define path_mid where path_mid_def: "path_mid \<equiv> midcurve_eq \<circ> (linepath t1 t2)"
define path_g where "path_g \<equiv> (path1 +++ path_mid) +++ path2"
have 0: "path (path1 +++ path_mid)"
proof (rule path_join_imp)
from path1_def show "path (path1)" by auto
next
have *: "path_image (linepath t1 t2) = closed_segment t1 t2"
using path_image_linepath by auto
from \<open>t1 \<in> open_domain\<close> and \<open>t2 \<in> open_domain\<close> have "t1 \<in> domain" and "t2 \<in> domain"
unfolding open_domain_def by auto
hence "closed_segment t1 t2 \<subseteq> domain" using closed_segment_subset using le.convex_domain
by auto
hence 2: "continuous_on (path_image (linepath t1 t2)) midcurve_eq" using * continuous_midcurve_eq
by (auto simp add: continuous_on_subset)
thus "path (path_mid)" unfolding path_mid_def
by (auto intro:path_continuous_image)
next
have "pathfinish path1 = z1'" unfolding path1_def by auto
moreover
have "pathstart path_mid = z1'" unfolding path_mid_def comp_def \<open>z1' = midcurve_eq t1\<close>
by (simp add: linepath_def path_defs(2))
ultimately show "pathfinish path1 = pathstart path_mid" by auto
qed
have pg: "path (path_g)"
unfolding path_g_def
proof (rule path_join_imp, rule 0)
show "path path2" using path2_def by auto
next
have "pathfinish (path1 +++ path_mid) = pathfinish path_mid" by auto
also have "... = z2'" unfolding path_mid_def comp_def \<open>z2' = midcurve_eq t2\<close>
by (metis path_defs(3) pathfinish_linepath)
also have "... = pathstart path2" using path2_def by auto
finally show "pathfinish (path1 +++ path_mid) = pathstart path2" by auto
qed
have 1: "path_image path1 \<subseteq> inside"
proof (rule subsetI, unfold insideP_eq, intro insidePI, rule \<open>t1 \<in> open_domain\<close>)
fix x
assume "x \<in> path_image path1"
have *: "path_image path1 = closed_segment z1 z1'" unfolding path1_def by auto
have "z1' \<in> open_segment (curve_left t1) (curve_right t1)" unfolding \<open>z1' = midcurve_eq t1\<close>
using midcurve_in_open_segment[OF \<open>t1 \<in> open_domain\<close>] .
with \<open>z1 \<in> open_segment (curve_left t1) (curve_right t1)\<close> have
"closed_segment z1 z1' \<subseteq> open_segment (curve_left t1) (curve_right t1)"
by (auto simp add:closed_segment_subset)
with * show "x \<in> path_image path1 \<Longrightarrow> x \<in> open_segment (curve_left t1) (curve_right t1)"
by auto
qed
have "closed_segment t1 t2 \<subseteq> open_domain"
using closed_segment_subset[OF \<open>t1 \<in> open_domain\<close> \<open>t2 \<in> open_domain\<close> convex_open_domain] .
hence 2: "path_image path_mid \<subseteq> inside"
unfolding path_mid_def path_image_def sym[OF image_comp] linepath_image_01 using midcurve_inside
by auto
have 3: "path_image path2 \<subseteq> inside"
proof (rule subsetI, unfold insideP_eq, intro insidePI, rule \<open>t2 \<in> open_domain\<close>)
fix x
assume "x \<in> path_image path2"
have *: "path_image path2 = closed_segment z2' z2" unfolding path2_def by auto
have "z2' \<in> open_segment (curve_left t2) (curve_right t2)" unfolding \<open>z2' = midcurve_eq t2\<close>
using midcurve_in_open_segment[OF \<open>t2 \<in> open_domain\<close>] .
with \<open>z2 \<in> open_segment (curve_left t2) (curve_right t2)\<close> have
"closed_segment z2' z2 \<subseteq> open_segment (curve_left t2) (curve_right t2)"
by (auto simp add:closed_segment_subset)
with * show "x \<in> path_image path2 \<Longrightarrow> x \<in> open_segment (curve_left t2) (curve_right t2)"
by auto
qed
from 1 2 3 have pi: "path_image path_g \<subseteq> inside"
unfolding path_g_def by (simp add: subset_path_image_join path_image_join_subset)
have ps: "pathstart path_g = z1" unfolding path_g_def using pathstart_join path1_def by auto
have "pathfinish path_g = z2" unfolding path_g_def using pathfinish_join path2_def by auto
with pg pi ps show
"\<exists>g. path g \<and> path_image g \<subseteq> local.inside \<and> pathstart g = z1 \<and> pathfinish g = z2" by auto
qed
definition le_lb_x :: real where
"le_lb_x \<equiv> le.curve_eq_x (Inf domain)"
theorem le_lb_x_lower_bound:
"t \<in> domain \<Longrightarrow> le_lb_x \<le> le.curve_eq_x t"
using mono_x_le domain_inf_sup unfolding le_lb_x_def strict_mono_in_def by (smt atLeastAtMost_iff)
definition ri_lb_x :: real where
"ri_lb_x \<equiv> ri.curve_eq_x (Inf domain)"
theorem ri_lb_x_lower_bound:
"t \<in> domain \<Longrightarrow> ri_lb_x \<le> ri.curve_eq_x t"
using mono_x_ri domain_inf_sup unfolding ri_lb_x_def strict_mono_in_def by (smt atLeastAtMost_iff)
definition lb_x :: real where
"lb_x \<equiv> min le_lb_x ri_lb_x"
theorem lb_x_lower_bound_le:
"t \<in> domain \<Longrightarrow> lb_x \<le> le.curve_eq_x t"
unfolding lb_x_def min_def using le_lb_x_lower_bound by fastforce
theorem rb_x_lower_bound_ri:
"t \<in> domain \<Longrightarrow> lb_x \<le> ri.curve_eq_x t"
unfolding lb_x_def min_def using ri_lb_x_lower_bound by fastforce
definition le_ub_x :: real where
"le_ub_x \<equiv> le.curve_eq_x (Sup domain)"
theorem le_ub_x_upper_bound:
"t \<in> domain \<Longrightarrow> le.curve_eq_x t \<le> le_ub_x"
using mono_x_le domain_inf_sup unfolding le_ub_x_def strict_mono_in_def by (smt atLeastAtMost_iff)
definition ri_ub_x :: real where
"ri_ub_x \<equiv> ri.curve_eq_x (Sup domain)"
theorem ri_ub_x_upper_bound:
"t \<in> domain \<Longrightarrow> ri.curve_eq_x t \<le> ri_ub_x"
using mono_x_ri domain_inf_sup unfolding ri_ub_x_def strict_mono_in_def by (smt atLeastAtMost_iff)
definition ub_x :: real where
"ub_x \<equiv> max le_ub_x ri_ub_x"
theorem ub_x_upper_bound_le:
"t \<in> domain \<Longrightarrow> le.curve_eq_x t \<le> ub_x"
unfolding ub_x_def max_def using le_ub_x_upper_bound by fastforce
theorem ub_x_upper_bound_ri:
"t \<in> domain \<Longrightarrow> ri.curve_eq_x t \<le> ub_x"
unfolding ub_x_def max_def using ri_ub_x_upper_bound by fastforce
theorem
"lb_x \<le> ub_x"
using inf_in_dom lb_x_def lb_x_lower_bound_le ub_x_def ub_x_upper_bound_le by fastforce
definition union_setX :: "real set" where
"union_setX \<equiv> {lb_x .. ub_x}"
theorem
"common_setX \<subseteq> union_setX"
unfolding union_setX_def
using lb_x_def lb_x_lower_bound_le le.setX_alt_def ub_x_def ub_x_upper_bound_le by auto
(*
definition bounds :: "real \<Rightarrow> (real \<times> real) option" where
"bounds x \<equiv>
(if x \<in> common_setX then Some (ri.f_of_x x, le.f_of_x x)
else if x \<in> union_setX \<and> x > (Sup ri.setX) then
Some (line_equation (curve_left (Sup domain)) (curve_right (Sup domain)) x, le.f_of_x x)
else if x \<in> union_setX \<and> x < (Inf ri.setX) then
Some (line_equation (curve_left (Inf domain)) (curve_right (Inf domain)) x, le.f_of_x x)
else if x \<in> union_setX \<and> x > (Sup le.setX) then
Some (line_equation (curve_left (Sup domain)) (curve_right (Sup domain)) x, ri.f_of_x x)
else if x \<in> union_setX \<and> x < (Inf le.setX) then
Some (line_equation (curve_left (Inf domain)) (curve_right (Inf domain)) x, ri.f_of_x x)
else
None)"
theorem
assumes "direction_right"
assumes "x \<in> common_setX"
shows "ri.f_of_x x < le.f_of_x x"
abbreviation fst_bound :: "real \<Rightarrow> real" where
"fst_bound \<equiv> fst \<circ> (the \<circ> bounds)"
abbreviation snd_bound :: "real \<Rightarrow> real" where
"snd_bound \<equiv> snd \<circ> (the \<circ> bounds)"
definition inside2 :: "real2 set" where
"inside2 \<equiv> {(x, y). x \<in> le.setX \<union> ri.setX \<and>
y \<in> {min (fst_bound x) (snd_bound x) <..< max (fst_bound x) (snd_bound x)}}"
*)
end
(*
subsection "Multilane road"
locale multilane_road = simple_road curve_left curve_right domain
for curve_left and curve_right and domain +
fixes lds :: "(real \<Rightarrow> real2) list" \<comment> \<open>lds is an abbreviation for lane dividers\<close>
assumes lds_nonempty: "lds \<noteq> []"
assumes sb: "ld \<in> set lds \<Longrightarrow> simple_boundary ld domain"
assumes csx: "i < length lds \<Longrightarrow> common_setX = curve.setX (lds ! i) domain"
assumes bw: "i < j \<Longrightarrow> x \<in> curve.setX (lds ! i) domain \<inter> curve.setX (lds ! j) domain \<Longrightarrow>
simple_boundary.f_of_x (lds ! i) domain x < simple_boundary.f_of_x (lds ! j) domain x"
assumes lb:"x \<in> curve.setX (last lds) domain \<inter> le.setX \<Longrightarrow>
simple_boundary.f_of_x (last lds) domain x < le.f_of_x x"
assumes rb:"x \<in> curve.setX (hd lds) domain \<inter> ri.setX \<Longrightarrow>
ri.f_of_x x < simple_boundary.f_of_x (hd lds) domain x"
begin
definition nbr_of_lanes where
"nbr_of_lanes \<equiv> length lds + 1"
\<comment> \<open>In multilane scenario the number of lanes is at least 2.\<close>
lemma "2 \<le> nbr_of_lanes"
unfolding nbr_of_lanes_def using lds_nonempty by (cases lds) (auto)
abbreviation ld_idx where "ld_idx i \<equiv> lds ! i"
\<comment> \<open>Each adjacent lane dividers is a simple road.\<close>
theorem li:
assumes "i < length lds - 1"
shows "simple_road (ld_idx (i + 1)) (ld_idx i) domain"
unfolding simple_road_def
proof (rule conjI, rule_tac[2] conjI, unfold simple_road_axioms_def, rule_tac[3] conjI, rule_tac[4] allI,
rule_tac[4] impI)
show "simple_boundary (ld_idx (i + 1)) domain" using sb[of "ld_idx (i+1)"] using assms by auto
next
show "simple_boundary (ld_idx i) domain" using sb[of "ld_idx i"] using assms by auto
next
fix x
assume "x \<in> curve.setX (ld_idx (i+1)) domain \<inter> curve.setX (ld_idx i) domain"
with bw[of "i" "i+1" "x"]
show "simple_boundary.f_of_x (ld_idx i) domain x < simple_boundary.f_of_x (ld_idx (i + 1)) domain x"
by auto
qed
\<comment> \<open>Last lane dividers with left boundaries is a simple road too.\<close>
theorem lanel:
"simple_road curve_left (last lds) domain"
unfolding simple_road_def
proof (rule conjI, rule_tac[2] conjI, unfold simple_road_axioms_def, rule_tac[3] allI,
rule_tac[3] impI)
show "simple_boundary curve_left domain" using le.simple_boundary_axioms by auto
next
show "simple_boundary (last lds) domain" using sb[of "last lds"] last_in_set[OF lds_nonempty]
by auto
next
fix x
assume "x \<in> le.setX \<inter> curve.setX (last lds) domain"
with lb[of "x"] show " simple_boundary.f_of_x (last lds) domain x < le.f_of_x x" by auto
qed
\<comment> \<open>First lane divider and right boundary is a simple road too.\<close>
theorem lane0:
"simple_road (hd lds) curve_right domain"
unfolding simple_road_def
proof (rule conjI, rule_tac[2] conjI, unfold simple_road_axioms_def, rule_tac[3] allI,
rule_tac[3] impI)
show "simple_boundary (hd lds) domain" using sb[of "hd lds"] hd_in_set[OF lds_nonempty]
by auto
next
show "simple_boundary curve_right domain" using ri.simple_boundary_axioms by auto
next
fix x
assume " x \<in> curve.setX (hd lds) domain \<inter> ri.setX"
with rb[of "x"] show "ri.f_of_x x < simple_boundary.f_of_x (hd lds) domain x" by auto
qed
definition drivable_lane :: "nat \<Rightarrow> real2 set" where
"drivable_lane i \<equiv> (if i = 0 then
simple_road.drivable_area (ld_idx i) curve_right domain
else if 0 < i \<and> i < nbr_of_lanes - 1 then
simple_road.drivable_area (ld_idx i) (ld_idx (i - 1)) domain
else if i = nbr_of_lanes - 1 then
simple_road.drivable_area curve_left (ld_idx (i - 1)) domain
else
undefined)"
interpretation l0: simple_road "(hd lds)" curve_right domain using lane0 .
theorem l0_common_setX:
"l0.common_setX = common_setX"
proof -
from csx[of "0"] have 0: "common_setX = curve.setX (hd lds) domain" using lds_nonempty
hd_conv_nth[OF lds_nonempty] by auto
hence "l0.le.setX \<inter> ri.setX = l0.le.setX" by auto
thus ?thesis using 0 by auto
qed
theorem bw2:
assumes "i \<le> j"
assumes "x \<in> curve.setX (lds ! i) domain \<inter> curve.setX (lds ! j) domain"
shows "simple_boundary.f_of_x (ld_idx i) domain x \<le> simple_boundary.f_of_x (ld_idx j) domain x"
proof (cases "i < j")
case True
then show ?thesis using bw[OF True assms(2)] by auto
next
case False
then show ?thesis using assms by auto
qed
theorem l0_between_setY:
assumes "x \<in> l0.common_setX"
shows "l0.between_setY x \<subseteq> between_setY x"
proof
fix xa
assume "xa \<in> l0.between_setY x"
hence 0: "xa \<in> {(ri.f_of_x x) <..< (l0.le.f_of_x x)}" by auto
from bw2[of "0" "length lds - 1"]
have "simple_boundary.f_of_x (hd lds) domain x \<le> simple_boundary.f_of_x (last lds) domain x"
using hd_conv_nth[OF lds_nonempty] last_conv_nth[OF lds_nonempty] lds_nonempty assms csx
by (metis (no_types, lifting) diff_less inf_left_idem l0_common_setX le0 length_greater_0_conv less_numeral_extra(1))
also have "... < le.f_of_x x" using assms l0_common_setX csx lb
last_conv_nth[OF lds_nonempty]
by (metis (no_types, lifting) diff_less inf.right_idem inf_sup_aci(1) lds_nonempty length_greater_0_conv less_numeral_extra(1))
finally have "l0.le.f_of_x x < le.f_of_x x" by auto
with 0 show "xa \<in> {(ri.f_of_x x) <..< le.f_of_x x}" by auto
qed
interpretation ll: simple_road curve_left "last lds" domain using lanel .
theorem ll_common_setX:
"ll.common_setX = common_setX"
proof -
from csx[of "length lds - 1"] have 0: "common_setX = curve.setX (last lds) domain" using lds_nonempty
last_conv_nth[OF lds_nonempty] by auto
hence "le.setX \<inter> ll.ri.setX = ll.ri.setX" by auto
thus ?thesis using 0 by auto
qed
theorem ll_between_setY:
assumes "x \<in> ll.common_setX"
shows "ll.between_setY x \<subseteq> between_setY x"
proof
fix xa
assume 0: "xa \<in> ll.between_setY x"
from bw2[of "0" "length lds - 1"]
have "simple_boundary.f_of_x (hd lds) domain x \<le> simple_boundary.f_of_x (last lds) domain x"
using hd_conv_nth[OF lds_nonempty] last_conv_nth[OF lds_nonempty] lds_nonempty assms csx
by (metis (no_types, lifting) diff_less inf_left_idem l0_common_setX le0 length_greater_0_conv less_numeral_extra(1))
moreover have "ri.f_of_x x < simple_boundary.f_of_x (hd lds) domain x" using rb[of "x"] assms
l0_common_setX ll_common_setX by auto
ultimately have "ri.f_of_x x < ll.ri.f_of_x x" by auto
with 0 show "xa \<in> between_setY x" by auto
qed
lemma
assumes "i < nbr_of_lanes"
shows "path_connected (drivable_lane i)"
unfolding drivable_lane_def if_splits(1)
proof (rule conjI, rule impI, rule_tac[2] impI, rule_tac[2] conjI, rule_tac[2] impI,
rule_tac[3] impI, rule_tac[3] conjI, rule_tac[3] impI, rule_tac[4] impI)
assume "i = 0"
hence "ld_idx i = hd lds" using hd_conv_nth[OF lds_nonempty] by auto
thus "path_connected (simple_road.drivable_area (ld_idx i) curve_right domain)"
using l0.path_connected_drivable_area by auto
next
assume "0 < i \<and> i < nbr_of_lanes - 1"
hence pos: "0 < i" and valid: "i < length lds" unfolding nbr_of_lanes_def by auto
then interpret li: simple_road "ld_idx i" "ld_idx (i - 1)" domain using li[of "i-1"] by auto
show "path_connected li.drivable_area" using li.path_connected_drivable_area .
next
assume "i = nbr_of_lanes - 1"
hence "i = length lds" unfolding nbr_of_lanes_def by auto
hence "ld_idx (i - 1) = last lds" using last_conv_nth[OF lds_nonempty] by auto
thus "path_connected (simple_road.drivable_area curve_left (ld_idx (i - 1)) domain)"
using ll.path_connected_drivable_area by auto
next
assume "i \<noteq> 0"
assume "\<not> (0 < i \<and> i < nbr_of_lanes - 1)"
hence "0 \<ge> i \<or> i \<ge> nbr_of_lanes - 1" by auto
with \<open>i \<noteq> 0\<close> have 0: "nbr_of_lanes - 1 \<le> i" by auto
assume "i \<noteq> nbr_of_lanes - 1"
with 0 have "nbr_of_lanes - 1 < i" by auto
with assms have "False" by auto
thus "path_connected undefined" by auto
qed
lemma drivable_lane_subseteq_drivable_area:
assumes "i < nbr_of_lanes"
shows "drivable_lane i \<subseteq> drivable_area"
unfolding drivable_lane_def
proof (split if_splits, rule conjI, rule_tac[!] impI)
assume 0:"i = 0"
show "simple_road.drivable_area (ld_idx i) curve_right domain \<subseteq> drivable_area"
proof
fix x
assume "x \<in> simple_road.drivable_area (ld_idx i) curve_right domain"
with 0 have "x \<in> l0.drivable_area" using hd_conv_nth[OF lds_nonempty] by auto
hence 1: "fst x \<in> l0.common_setX" and 2: "snd x \<in> l0.between_setY (fst x)"
using l0.drivable_areaD1 l0.drivable_areaD2 by auto
with l0_common_setX have 3: "fst x \<in> common_setX" by auto
from 1 and 2 have "snd x \<in> between_setY (fst x)" using l0_between_setY[OF 1] by auto
with 3 show "x \<in> drivable_area" unfolding drivable_area_def by auto
qed
next
assume "i \<noteq> 0"
show " (if 0 < i \<and> i < nbr_of_lanes - 1 then simple_road.drivable_area (ld_idx i) (ld_idx (i - 1)) domain
else if i = nbr_of_lanes - 1 then simple_road.drivable_area curve_left (ld_idx (i - 1)) domain else undefined)
\<subseteq> drivable_area"
proof (split if_splits, rule conjI, rule_tac[!] impI)
assume "0 < i \<and> i < nbr_of_lanes - 1"
hence pos: "0 < i" and valid: "i < length lds" unfolding nbr_of_lanes_def by auto
then interpret li: simple_road "ld_idx i" "ld_idx (i - 1)" domain using li[of "i-1"] by auto
show " simple_road.drivable_area (ld_idx i) (ld_idx (i - 1)) domain \<subseteq> drivable_area"
proof
fix x
assume 4: "x \<in> li.drivable_area"
hence 5: "fst x \<in> common_setX" using li.drivable_areaD1 csx valid by blast
have 6: "snd x \<in> li.between_setY (fst x)" using li.drivable_areaD2[OF 4] by auto
have "ri.f_of_x (fst x) < l0.le.f_of_x (fst x)" using rb 5 l0_common_setX by auto
also have "... \<le> li.ri.f_of_x (fst x)" using bw2[of "0" "i-1" "fst x"] pos csx 5 valid
lds_nonempty hd_conv_nth[OF lds_nonempty]
by (metis "4" le0 length_greater_0_conv li.drivable_areaD1)
finally have 7:"ri.f_of_x (fst x) < li.ri.f_of_x (fst x)" by auto
have "ll.ri.f_of_x (fst x) < le.f_of_x (fst x)" using lb 5 ll_common_setX by auto
moreover have "li.le.f_of_x (fst x) \<le> ll.ri.f_of_x (fst x)" using bw2[of "i" "length lds - 1" "fst x"]
valid last_conv_nth[OF lds_nonempty] csx 5 lds_nonempty ll_common_setX
proof -
obtain rr :: real and rra :: real where
f1: "ll.ri.setX = {rr..rra}"
by (meson ll.ri.setX_closed_interval_or_empty)
then obtain rrb :: real and rrc :: real where
f2: "{rrb..rrc} \<inter> {rr..rra} = le.setX \<inter> ll.ri.setX"
using le.setX_closed_interval_or_empty by blast
then have "{rrb..rrc} \<inter> {rr..rra} = li.le.setX"
using csx ll_common_setX valid by blast
then have "li.le.setX \<inter> curve.setX (ld_idx (length lds - 1)) domain = {rrb..rrc} \<inter> {rr..rra}"
using f1 by (metis (no_types) \<open>last lds = ld_idx (length lds - 1)\<close> inf.right_idem)
then have "li.le.setX \<inter> curve.setX (ld_idx (length lds - 1)) domain = le.setX \<inter> ri.setX"
using f2 ll_common_setX by blast
then have f3: "fst x \<in> li.le.setX \<inter> curve.setX (ld_idx (length lds - 1)) domain"
using "5" by blast (* > 1.0 s, timed out *)
have f4: "\<not> length lds \<le> i"
by (metis linorder_not_le valid)
then have f5: "1 = length lds - i - 0 - (length lds - i - 0 - Suc 0)"
by force
{ assume "\<not> i \<le> length lds - 1"
then have "1 \<noteq> length lds - i"
using f4 by (metis (no_types) diff_diff_cancel nat_le_linear)
then have "\<not> length lds - 1 \<le> i"
using f5 by (metis (no_types) One_nat_def cancel_ab_semigroup_add_class.diff_right_commute diff_is_0_eq' diff_zero)
then have "i \<le> length lds - 1"
by (metis nat_le_linear) }
then have "li.le.f_of_x (fst x) + - 1 * simple_boundary.f_of_x (ld_idx (length lds - 1)) domain (fst x) \<le> 0"
using f3 bw2 by force
then show ?thesis
by (simp add: \<open>last lds = ld_idx (length lds - 1)\<close>)
qed
ultimately have 8:"li.le.f_of_x (fst x) < le.f_of_x (fst x)" by auto
with 6 and 7 have "snd x \<in> between_setY (fst x)" by auto
with 5 show "x \<in> drivable_area" unfolding drivable_area_def by auto
qed
next
assume "\<not> (0 < i \<and> i < nbr_of_lanes - 1)"
hence "0 \<ge> i \<or> i \<ge> nbr_of_lanes - 1" by auto
with \<open>i \<noteq> 0\<close> have "i \<ge> nbr_of_lanes - 1" by auto
show "(if i = nbr_of_lanes - 1 then simple_road.drivable_area curve_left (ld_idx (i - 1)) domain else undefined) \<subseteq> drivable_area"
proof (split if_splits, rule conjI, rule_tac[!] impI)
assume "i = nbr_of_lanes - 1"
hence 9: "i = length lds" unfolding nbr_of_lanes_def by auto
show "simple_road.drivable_area curve_left (ld_idx (i - 1)) domain \<subseteq> drivable_area"
proof
fix x
assume "x \<in> simple_road.drivable_area curve_left (ld_idx (i - 1)) domain"
hence "x \<in> ll.drivable_area" using 9 last_conv_nth[OF lds_nonempty] by auto
hence "fst x \<in> common_setX" using ll.drivable_areaD1 ll_common_setX by auto
moreover have "snd x \<in> ll.between_setY (fst x)" using ll.drivable_areaD2 \<open>x \<in> ll.drivable_area\<close>
by auto
hence "snd x \<in> between_setY (fst x)" using ll_between_setY[of "fst x"] \<open>fst x \<in> common_setX\<close>
ll_common_setX by auto
with \<open>fst x \<in> common_setX\<close> show "x \<in> drivable_area" using drivable_areaI[of "fst x" "snd x"]
by auto
qed
next
assume "i \<noteq> nbr_of_lanes - 1"
with \<open>i \<ge> nbr_of_lanes - 1\<close> have "i > nbr_of_lanes - 1" by auto
with assms have "False" by auto
thus "undefined \<subseteq> drivable_area" by auto
qed
qed
qed
definition boundary_points where
"boundary_points i \<equiv> {(x,y). x \<in> curve.setX (lds ! i) domain \<and>
y = simple_boundary.f_of_x (lds ! i) domain x}"
lemma boundary_pointsD1:
assumes "i < length lds"
assumes "x \<in> boundary_points i"
shows "fst x \<in> common_setX"
using assms csx unfolding boundary_points_def by auto
lemma boundary_pointsD2:
assumes "i < length lds"
assumes "x \<in> boundary_points i"
shows "snd x = simple_boundary.f_of_x (lds ! i) domain (fst x)"
using assms unfolding boundary_points_def by auto
theorem boundary_points_subseteq_drivable_area:
assumes "i < length lds"
shows "boundary_points i \<subseteq> drivable_area"
proof
fix x
assume "x \<in> boundary_points i"
with assms have fst: "fst x \<in> common_setX" and snd:"snd x = simple_boundary.f_of_x (lds ! i) domain (fst x)"
using boundary_pointsD1 boundary_pointsD2 by auto
with bw2[of "i" "length lds - 1" "fst x"] assms csx last_conv_nth[OF lds_nonempty]
have "simple_boundary.f_of_x (ld_idx i) domain (fst x) \<le> ll.ri.f_of_x (fst x)"
proof -
have f1: "0 < Suc 0"
by (metis One_nat_def less_numeral_extra(1))
obtain rr :: real and rra :: real where
f2: "ll.ri.setX = {rr..rra}"
using ll.ri.setX_closed_interval_or_empty by blast
then obtain rrb :: real and rrc :: real where
f3: "{rrb..rrc} \<inter> {rr..rra} = le.setX \<inter> ll.ri.setX"
using le.setX_closed_interval_or_empty by blast
then have "{rrb..rrc} \<inter> {rr..rra} = curve.setX (ld_idx i) domain"
using assms csx ll_common_setX by blast
then have "curve.setX (ld_idx i) domain \<inter> curve.setX (ld_idx (length lds - 1)) domain = {rrb..rrc} \<inter> {rr..rra}"
using f2 by (metis (no_types) \<open>last lds = ld_idx (length lds - 1)\<close> inf.right_idem)
then have f4: "fst x \<in> curve.setX (ld_idx i) domain \<inter> curve.setX (ld_idx (length lds - 1)) domain"
using f3 fst ll_common_setX by blast
have f5: "length lds - (length lds - inf i (length lds) - inf 0 (Suc 0)) = i"
using f1 by (metis (no_types) assms diff_diff_cancel diff_zero inf.strict_order_iff less_imp_le_nat)
have "Suc 0 \<le> length lds - inf i (length lds) - inf 0 (Suc 0)"
by (metis One_nat_def assms diff_is_0_eq diff_zero inf.strict_order_iff less_one linorder_not_le)
then show ?thesis
using f5 f4 by (metis (full_types) One_nat_def \<open>\<lbrakk>i \<le> length lds - 1; fst x \<in> curve.setX (ld_idx i) domain \<inter> curve.setX (ld_idx (length lds - 1)) domain\<rbrakk> \<Longrightarrow> simple_boundary.f_of_x (ld_idx i) domain (fst x) \<le> simple_boundary.f_of_x (ld_idx (length lds - 1)) domain (fst x)\<close> \<open>last lds = ld_idx (length lds - 1)\<close> diff_le_mono2)
qed
also have "... < le.f_of_x (fst x)" using lb[of "fst x"] fst ll_common_setX by auto
finally have 1: "simple_boundary.f_of_x (ld_idx i) domain (fst x) < le.f_of_x (fst x)" by auto
with bw2[of "0" "i" "fst x"] assms csx lds_nonempty fst hd_conv_nth[OF lds_nonempty]
have "l0.le.f_of_x (fst x) \<le> simple_boundary.f_of_x (ld_idx i) domain (fst x)" by auto
moreover have "ri.f_of_x (fst x) < l0.le.f_of_x (fst x)" using rb[of "fst x"] fst l0_common_setX
by auto
ultimately have "ri.f_of_x (fst x) < simple_boundary.f_of_x (ld_idx i) domain (fst x)" by auto
with 1 and snd have "snd x \<in> between_setY (fst x)" by auto
with \<open>fst x \<in> common_setX\<close> show "x \<in> drivable_area" using drivable_areaI[of "fst x" "snd x"]
by auto
qed
definition partition_between where
"partition_between x \<equiv> {l0.between_setY x, ll.between_setY x} \<union>
{ran . \<exists>i>0. i < length lds \<and> ran = simple_road.between_setY (ld_idx i) (ld_idx (i-1)) domain x}"
lemma aux_intro:
assumes "x \<in> A \<or> x \<in> B \<or> (\<exists>i. P i \<and> x \<in> C i)"
shows "x \<in> \<Union>({A,B} \<union> {C'. \<exists>i. P i \<and> C' = C i})"
using assms by auto
lemma
assumes "x \<in> common_setX"
shows "partition_on (between_setY x) (partition_between x)"
proof (intro partition_onI)
show "\<Union>partition_between x = between_setY x"
unfolding partition_between_def
proof (rule Set.equalityI, rule_tac[!] subsetI)
fix xa
assume "xa \<in> \<Union>({l0.between_setY x, ll.between_setY x} \<union>
{ran. \<exists>i>0. i < length lds \<and>
ran = {simple_boundary.f_of_x (ld_idx (i - 1)) domain x<..<simple_boundary.f_of_x (ld_idx i) domain x}})"
from this obtain X where "X \<in> partition_between x" and "xa \<in> X" unfolding partition_between_def
using Union_iff by blast
hence "X = l0.between_setY x \<or> X = ll.between_setY x \<or>
X \<in> {ran. \<exists>i>0. i < length lds \<and>
ran = {simple_boundary.f_of_x (ld_idx (i - 1)) domain x<..<simple_boundary.f_of_x (ld_idx i) domain x}}"
unfolding partition_between_def by auto
from this consider \<open>X = l0.between_setY x\<close> | \<open>X = ll.between_setY x\<close> |
\<open>X \<in> {ran. \<exists>i>0. i < length lds \<and>
ran = {simple_boundary.f_of_x (ld_idx (i - 1)) domain x<..<simple_boundary.f_of_x (ld_idx i) domain x}}\<close>
by auto
then show "xa \<in> between_setY x"
proof cases
case 1
then show ?thesis using l0_between_setY assms l0_common_setX \<open>xa \<in> X\<close> by blast
next
case 2
then show ?thesis using ll_between_setY assms ll_common_setX \<open>xa \<in> X\<close> by blast
next
case 3
then obtain i where X_def: "X = {simple_boundary.f_of_x (ld_idx (i-1)) domain x <..<
simple_boundary.f_of_x (ld_idx i) domain x}"
and "i > 0" and "i < length lds" by blast
from this interpret li: simple_road "ld_idx i" "ld_idx (i - 1)" domain using li[of "i-1"]
by auto
have "li.between_setY x \<subseteq> between_setY x"
proof
fix xa
assume "xa \<in> li.between_setY x"
have "li.le.f_of_x x \<le> ll.ri.f_of_x x" using bw2[of "i" "length lds - 1" "x"]
using \<open>i < length lds\<close> csx[of "length lds - 1"] csx[of "i"] lds_nonempty assms
last_conv_nth[OF lds_nonempty] by fastforce
also have "... < le.f_of_x x" using lb[of "x"] using assms ll_common_setX by auto
finally have temp: "li.le.f_of_x x < le.f_of_x x" by auto
have "ri.f_of_x x < l0.le.f_of_x x" using rb[of "x"] assms l0_common_setX by auto
also have "... \<le> li.ri.f_of_x x" using bw2[of "0" "i-1" "x"] \<open>i > 0\<close>
hd_conv_nth[OF lds_nonempty] csx[of "0"] lds_nonempty csx[of "i-1"] \<open>i < length lds\<close>
assms by auto
finally have "ri.f_of_x x < li.ri.f_of_x x" by auto
with temp and \<open>xa \<in> li.between_setY x\<close> show "xa \<in> between_setY x" by auto
qed
with \<open>xa \<in> X\<close> and X_def show ?thesis by auto
qed
next
fix xa
assume "xa \<in> between_setY x"
have "xa \<in> \<Union>({l0.between_setY x, ll.between_setY x} \<union>
{ran. \<exists>i. (0 < i \<and> i < length lds) \<and>
ran = {simple_boundary.f_of_x (ld_idx (i - 1)) domain x<..<simple_boundary.f_of_x (ld_idx i) domain x}})"
proof (intro aux_intro)
qed
lemma
assumes "x \<in> common_setX"
assumes "y \<in> between_setY x"
assumes "i < length_lds \<Longrightarrow> (x, y) \<notin> boundary_points i"
assumes "y \<in> l0.between_setY x \<or> y \<in> ll.between_setY x"
shows "\<exists>i>0. i < length_lds \<and> y \<in> simple_road.between_setY (ld_idx i) (ld_idx (i-1)) domain x"
proof (rule ccontr)
assume "\<not> (\<exists>i>0. i < length_lds \<and> y \<in> simple_road.between_setY (ld_idx i) (ld_idx (i-1)) domain x)"
hence "\<forall>i>0. i < length_lds \<longrightarrow> y \<notin> simple_road.between_setY (ld_idx i) (ld_idx (i-1)) domain x"
by auto
have "y < simple_boundary.f_of_x (ld_idx 0) domain x \<or>
y > simple_boundary.f_of_x (ld_idx (length_lds - 1)) domain x"
proof (rule ccontr)
assume "\<not> (y < simple_boundary.f_of_x (ld_idx 0) domain x \<or>
simple_boundary.f_of_x (ld_idx (length_lds - 1)) domain x < y)"
hence "y \<le> simple_boundary.f_of_x (ld_idx (length_lds - 1)) domain x \<and>
simple_boundary.f_of_x (ld_idx 0) domain x \<le> y" by auto
qed
qed
\<comment> \<open>Drivable area for multilane road\<close>
definition multi_drivable_area :: "real2 set" where
"multi_drivable_area \<equiv>
(\<Union>i < nbr_of_lanes. drivable_lane i) \<union> (\<Union>i < length lds. boundary_points i)"
theorem multi_drivable_area_alt_def:
"multi_drivable_area = drivable_area"
unfolding multi_drivable_area_def
proof (rule Set.equalityI, unfold Un_subset_iff, rule conjI, unfold UN_subset_iff, rule_tac[1-2] ballI)
fix i
assume "i \<in> {..<nbr_of_lanes}"
hence "i < nbr_of_lanes" by auto
with drivable_lane_subseteq_drivable_area[OF this] show "drivable_lane i \<subseteq> drivable_area" by simp
next
fix i
assume "i \<in> {..<length lds}"
hence "i < length lds" by auto
with boundary_points_subseteq_drivable_area show "boundary_points i \<subseteq> drivable_area" by auto
next
show "drivable_area \<subseteq> (\<Union>i < nbr_of_lanes. drivable_lane i) \<union> (\<Union>i < length lds. boundary_points i)"
proof
fix x
assume "x \<in> drivable_area"
hence fst:"fst x \<in> common_setX" and snd:"snd x \<in> between_setY (fst x)" using drivable_areaD1
drivable_areaD2 by auto
qed
qed
end
*)
end
|
/* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "xform.h"
#include "imgfeatures.h"
#include "utils.h"
//#include "cxcore.h"
//#include <highgui.h>
// Universal include for all versions of OpenCV
#include <mrpt/otherlibs/do_opencv_includes.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <time.h>
/************************* Local Function Prototypes *************************/
static __inline struct feature* get_match( struct feature*, int );
int get_matched_features( struct feature*, int, int, struct feature*** );
int calc_min_inliers( int, int, double, double );
struct feature** draw_ransac_sample( struct feature**, int, int, gsl_rng* );
void extract_corresp_pts( struct feature**, int, int, CvPoint2D64f**,
CvPoint2D64f** );
int find_consensus( struct feature**, int, int, CvMat*, ransac_err_fn,
double, struct feature*** );
static __inline void release_mem( CvPoint2D64f*, CvPoint2D64f*,
struct feature** );
/********************** Functions prototyped in xform.h **********************/
/*
Calculates a best-fit image transform from image feature correspondences
using RANSAC.
For more information refer to:
Fischler, M. A. and Bolles, R. C. Random sample consensus: a paradigm for
model fitting with applications to image analysis and automated cartography.
<EM>Communications of the ACM, 24</EM>, 6 (1981), pp. 381--395.
@param features an array of features; only features with a non-NULL match
of type mtype are used in homography computation
@param n number of features in feat
@param mtype determines which of each feature's match fields to use
for model computation; should be one of FEATURE_FWD_MATCH,
FEATURE_BCK_MATCH, or FEATURE_MDL_MATCH; if this is FEATURE_MDL_MATCH,
correspondences are assumed to be between a feature's img_pt field
and its match's mdl_pt field, otherwise correspondences are assumed to
be between the the feature's img_pt field and its match's img_pt field
@param xform_fn pointer to the function used to compute the desired
transformation from feature correspondences
@param m minimum number of correspondences necessary to instantiate the
model computed by xform_fn
@param p_badxform desired probability that the final transformation
returned by RANSAC is corrupted by outliers (i.e. the probability that
no samples of all inliers were drawn)
@param err_fn pointer to the function used to compute a measure of error
between putative correspondences and a computed model
@param err_tol correspondences within this distance of a computed model are
considered as inliers
@param inliers if not NULL, output as an array of pointers to the final
set of inliers
@param n_in if not NULL and \a inliers is not NULL, output as the final
number of inliers
@return Returns a transformation matrix computed using RANSAC or NULL
on error or if an acceptable transform could not be computed.
*/
CvMat* ransac_xform( struct feature* features, int n, int mtype,
ransac_xform_fn xform_fn, int m, double p_badxform,
ransac_err_fn err_fn, double err_tol,
struct feature*** inliers, int* n_in )
{
struct feature** matched, ** sample, ** consensus, ** consensus_max = NULL;
struct ransac_data* rdata;
CvPoint2D64f* pts, * mpts;
CvMat* M = NULL;
gsl_rng* rng;
double p, in_frac = RANSAC_INLIER_FRAC_EST;
int i, nm, in, in_min, in_max = 0, k = 0;
nm = get_matched_features( features, n, mtype, &matched );
if( nm < m )
{
fprintf( stderr, "Warning: not enough matches to compute xform, %s" \
" line %d\n", __FILE__, __LINE__ );
goto end;
}
/* initialize random number generator */
rng = gsl_rng_alloc( gsl_rng_mt19937 );
gsl_rng_set( rng, time(NULL) );
in_min = calc_min_inliers( nm, m, RANSAC_PROB_BAD_SUPP, p_badxform );
p = pow( 1.0 - pow( in_frac, m ), k );
i = 0;
while( p > p_badxform )
{
sample = draw_ransac_sample( matched, nm, m, rng );
extract_corresp_pts( sample, m, mtype, &pts, &mpts );
M = xform_fn( pts, mpts, m );
if( ! M )
goto iteration_end;
in = find_consensus( matched, nm, mtype, M, err_fn, err_tol, &consensus);
if( in > in_max )
{
if( consensus_max )
free( consensus_max );
consensus_max = consensus;
in_max = in;
in_frac = (double)in_max / nm;
}
else
free( consensus );
cvReleaseMat( &M );
iteration_end:
release_mem( pts, mpts, sample );
p = pow( 1.0 - pow( in_frac, m ), ++k );
}
/* calculate final transform based on best consensus set */
if( in_max >= in_min )
{
extract_corresp_pts( consensus_max, in_max, mtype, &pts, &mpts );
M = xform_fn( pts, mpts, in_max );
in = find_consensus( matched, nm, mtype, M, err_fn, err_tol, &consensus);
cvReleaseMat( &M );
release_mem( pts, mpts, consensus_max );
extract_corresp_pts( consensus, in, mtype, &pts, &mpts );
M = xform_fn( pts, mpts, in );
if( inliers )
{
*inliers = consensus;
consensus = NULL;
}
if( n_in )
*n_in = in;
release_mem( pts, mpts, consensus );
}
else if( consensus_max )
{
if( inliers )
*inliers = NULL;
if( n_in )
*n_in = 0;
free( consensus_max );
}
gsl_rng_free( rng );
end:
for( i = 0; i < nm; i++ )
{
rdata = feat_ransac_data( matched[i] );
matched[i]->feature_data = rdata->orig_feat_data;
free( rdata );
}
free( matched );
return M;
}
/*
Calculates a least-squares planar homography from point correspondeces.
@param pts array of points
@param mpts array of corresponding points; each pts[i], i=0..n-1, corresponds
to mpts[i]
@param n number of points in both pts and mpts; must be at least 4
@return Returns the 3 x 3 least-squares planar homography matrix that
transforms points in pts to their corresponding points in mpts or NULL if
fewer than 4 correspondences were provided
*/
CvMat* lsq_homog( CvPoint2D64f* pts, CvPoint2D64f* mpts, int n )
{
CvMat* H, * A, * B, X;
double x[9];
int i;
if( n < 4 )
{
fprintf( stderr, "Warning: too few points in lsq_homog(), %s line %d\n",
__FILE__, __LINE__ );
return NULL;
}
/* set up matrices so we can unstack homography into X; AX = B */
A = cvCreateMat( 2*n, 8, CV_64FC1 );
B = cvCreateMat( 2*n, 1, CV_64FC1 );
X = cvMat( 8, 1, CV_64FC1, x );
H = cvCreateMat(3, 3, CV_64FC1);
cvZero( A );
for( i = 0; i < n; i++ )
{
cvmSet( A, i, 0, pts[i].x );
cvmSet( A, i+n, 3, pts[i].x );
cvmSet( A, i, 1, pts[i].y );
cvmSet( A, i+n, 4, pts[i].y );
cvmSet( A, i, 2, 1.0 );
cvmSet( A, i+n, 5, 1.0 );
cvmSet( A, i, 6, -pts[i].x * mpts[i].x );
cvmSet( A, i, 7, -pts[i].y * mpts[i].x );
cvmSet( A, i+n, 6, -pts[i].x * mpts[i].y );
cvmSet( A, i+n, 7, -pts[i].y * mpts[i].y );
cvmSet( B, i, 0, mpts[i].x );
cvmSet( B, i+n, 0, mpts[i].y );
}
cvSolve( A, B, &X, CV_SVD );
x[8] = 1.0;
X = cvMat( 3, 3, CV_64FC1, x );
cvConvert( &X, H );
cvReleaseMat( &A );
cvReleaseMat( &B );
return H;
}
/*
Calculates the transfer error between a point and its correspondence for
a given homography, i.e. for a point x, it's correspondence x', and
homography H, computes d(x', Hx)^2.
@param pt a point
@param mpt pt's correspondence
@param H a homography matrix
@return Returns the transfer error between pt and mpt given H
*/
double homog_xfer_err( CvPoint2D64f pt, CvPoint2D64f mpt, CvMat* H )
{
CvPoint2D64f xpt = persp_xform_pt( pt, H );
return sqrt( dist_sq_2D( xpt, mpt ) );
}
/*
Performs a perspective transformation on a single point. That is, for a
point (x, y) and a 3 x 3 matrix T this function returns the point
(u, v), where
[x' y' w']^T = T * [x y 1]^T,
and
(u, v) = (x'/w', y'/w').
Note that affine transforms are a subset of perspective transforms.
@param pt a 2D point
@param T a perspective transformation matrix
@return Returns the point (u, v) as above.
*/
CvPoint2D64f persp_xform_pt( CvPoint2D64f pt, CvMat* T )
{
CvMat XY, UV;
double xy[3] = { pt.x, pt.y, 1.0 }, uv[3] = { 0 };
CvPoint2D64f rslt;
cvInitMatHeader( &XY, 3, 1, CV_64FC1, xy, CV_AUTOSTEP );
cvInitMatHeader( &UV, 3, 1, CV_64FC1, uv, CV_AUTOSTEP );
cvMatMul( T, &XY, &UV );
rslt = cvPoint2D64f( uv[0] / uv[2], uv[1] / uv[2] );
return rslt;
}
/************************ Local funciton definitions *************************/
/*
Returns a feature's match according to a specified match type
@param feat feature
@param mtype match type, one of FEATURE_FWD_MATCH, FEATURE_BCK_MATCH, or
FEATURE_MDL_MATCH
@return Returns feat's match corresponding to mtype or NULL for bad mtype
*/
static __inline struct feature* get_match( struct feature* feat, int mtype )
{
if( mtype == FEATURE_MDL_MATCH )
return feat->mdl_match;
if( mtype == FEATURE_BCK_MATCH )
return feat->bck_match;
if( mtype == FEATURE_FWD_MATCH )
return feat->fwd_match;
return NULL;
}
/*
Finds all features with a match of a specified type and stores pointers
to them in an array. Additionally initializes each matched feature's
feature_data field with a ransac_data structure.
@param features array of features
@param n number of features in features
@param mtype match type, one of FEATURE_{FWD,BCK,MDL}_MATCH
@param matched output as an array of pointers to features with a match of
the specified type
@return Returns the number of features output in matched.
*/
int get_matched_features( struct feature* features, int n, int mtype,
struct feature*** matched )
{
struct feature** _matched;
struct ransac_data* rdata;
int i, m = 0;
_matched = calloc( n, sizeof( struct feature* ) );
for( i = 0; i < n; i++ )
if( get_match( features + i, mtype ) )
{
rdata = malloc( sizeof( struct ransac_data ) );
memset( rdata, 0, sizeof( struct ransac_data ) );
rdata->orig_feat_data = features[i].feature_data;
_matched[m] = features + i;
_matched[m]->feature_data = rdata;
m++;
}
*matched = _matched;
return m;
}
/*
Calculates the minimum number of inliers as a function of the number of
putative correspondences. Based on equation (7) in
Chum, O. and Matas, J. Matching with PROSAC -- Progressive Sample Consensus.
In <EM>Conference on Computer Vision and Pattern Recognition (CVPR)</EM>,
(2005), pp. 220--226.
@param n number of putative correspondences
@param m min number of correspondences to compute the model in question
@param p_badsupp prob. that a bad model is supported by a correspondence
@param p_badxform desired prob. that the final transformation returned is bad
@return Returns the minimum number of inliers required to guarantee, based
on p_badsupp, that the probability that the final transformation returned
by RANSAC is less than p_badxform
*/
int calc_min_inliers( int n, int m, double p_badsupp, double p_badxform )
{
double pi, sum;
int i, j;
for( j = m+1; j <= n; j++ )
{
sum = 0;
for( i = j; i <= n; i++ )
{
pi = ( i - m ) * log( p_badsupp ) + ( n - i + m ) * log( 1.0 - p_badsupp ) +
gsl_sf_lnchoose( n - m, i - m );
sum += exp( pi );
}
if( sum < p_badxform )
break;
}
return j;
}
/*
Draws a RANSAC sample from a set of features.
@param features array of pointers to features from which to sample
@param n number of features in features
@param m size of the sample
@param rng random number generator used to sample
@return Returns an array of pointers to the sampled features; the sampled
field of each sampled feature's ransac_data is set to 1
*/
struct feature** draw_ransac_sample( struct feature** features, int n,
int m, gsl_rng* rng )
{
struct feature** sample, * feat;
struct ransac_data* rdata;
int i, x;
for( i = 0; i < n; i++ )
{
rdata = feat_ransac_data( features[i] );
rdata->sampled = 0;
}
sample = calloc( m, sizeof( struct feature* ) );
for( i = 0; i < m; i++ )
{
do
{
x = gsl_rng_uniform_int( rng, n );
feat = features[x];
rdata = feat_ransac_data( feat );
}
while( rdata->sampled );
sample[i] = feat;
rdata->sampled = 1;
}
return sample;
}
/*
Extrancs raw point correspondence locations from a set of features
@param features array of features from which to extract points and match
points; each of these is assumed to have a match of type mtype
@param n number of features
@param mtype match type; if FEATURE_MDL_MATCH correspondences are assumed
to be between each feature's img_pt field and it's match's mdl_pt field,
otherwise, correspondences are assumed to be between img_pt and img_pt
@param pts output as an array of raw point locations from features
@param mpts output as an array of raw point locations from features' matches
*/
void extract_corresp_pts( struct feature** features, int n, int mtype,
CvPoint2D64f** pts, CvPoint2D64f** mpts )
{
struct feature* match;
CvPoint2D64f* _pts, * _mpts;
int i;
_pts = calloc( n, sizeof( CvPoint2D64f ) );
_mpts = calloc( n, sizeof( CvPoint2D64f ) );
if( mtype == FEATURE_MDL_MATCH )
for( i = 0; i < n; i++ )
{
match = get_match( features[i], mtype );
if( ! match )
fatal_error( "feature does not have match of type %d, %s line %d",
mtype, __FILE__, __LINE__ );
_pts[i] = features[i]->img_pt;
_mpts[i] = match->mdl_pt;
}
else
for( i = 0; i < n; i++ )
{
match = get_match( features[i], mtype );
if( ! match )
fatal_error( "feature does not have match of type %d, %s line %d",
mtype, __FILE__, __LINE__ );
_pts[i] = features[i]->img_pt;
_mpts[i] = match->img_pt;
}
*pts = _pts;
*mpts = _mpts;
}
/*
For a given model and error function, finds a consensus from a set of
feature correspondences.
@param features set of pointers to features; every feature is assumed to
have a match of type mtype
@param n number of features in features
@param mtype determines the match field of each feature against which to
measure error; if this is FEATURE_MDL_MATCH, correspondences are assumed
to be between the feature's img_pt field and the match's mdl_pt field;
otherwise matches are assumed to be between img_pt and img_pt
@param M model for which a consensus set is being found
@param err_fn error function used to measure distance from M
@param err_tol correspondences within this distance of M are added to the
consensus set
@param consensus output as an array of pointers to features in the
consensus set
@return Returns the number of points in the consensus set
*/
int find_consensus( struct feature** features, int n, int mtype,
CvMat* M, ransac_err_fn err_fn, double err_tol,
struct feature*** consensus )
{
struct feature** _consensus;
struct feature* match;
CvPoint2D64f pt, mpt;
double err;
int i, in = 0;
_consensus = calloc( n, sizeof( struct feature* ) );
if( mtype == FEATURE_MDL_MATCH )
for( i = 0; i < n; i++ )
{
match = get_match( features[i], mtype );
if( ! match )
fatal_error( "feature does not have match of type %d, %s line %d",
mtype, __FILE__, __LINE__ );
pt = features[i]->img_pt;
mpt = match->mdl_pt;
err = err_fn( pt, mpt, M );
if( err <= err_tol )
_consensus[in++] = features[i];
}
else
for( i = 0; i < n; i++ )
{
match = get_match( features[i], mtype );
if( ! match )
fatal_error( "feature does not have match of type %d, %s line %d",
mtype, __FILE__, __LINE__ );
pt = features[i]->img_pt;
mpt = match->img_pt;
err = err_fn( pt, mpt, M );
if( err <= err_tol )
_consensus[in++] = features[i];
}
*consensus = _consensus;
return in;
}
/*
Releases memory and reduces code size above
@param pts1 an array of points
@param pts2 an array of points
@param features an array of pointers to features; can be NULL
*/
static __inline void release_mem( CvPoint2D64f* pts1, CvPoint2D64f* pts2,
struct feature** features )
{
free( pts1 );
free( pts2 );
if( features )
free( features );
}
|
Our 2018 11+ pass rate was 92%!
We teach the skills and techniques needed, but, over the months, we encourage each child to develop his or her own approach. This will help with lifelong learning well after the 11+ is a distant memory.
THESE ARE THE LAST SPACES FOR THE 2018-9 COURSE.
For all details please complete a registration form and tick 'Year 5 Tutoring'.
11+ Preparation. This is our unique and extremely successful course that will enable your child to gain the academic level and confidence required to achieve their full potential in the 11+.
Tutoring starts in September of Year 5 and is one hour per week in term times only. Teaching is in small groups (5 pupils). Each lesson is one FULL hour of at least 60 minutes.
Throughout the year we assess and report back to you. It is very important that we identify strengths and weaknesses in order to target learning to where your child may need more input. We are always available either after each session or on the phone to discuss progress.
We do not do an ‘Initial Assessment’ because this can often give misleading results. We are more interested in how your child responds to our tutoring and learns over the first few weeks. We can then advise on likely 11 Plus success. We are very honest.
We set weekly homework so that the children can consolidate the skills and knowledge gained from each lesson. It also gives them the chance to work independently and to cover more content. Homework is important but shouldn’t become burdensome.
We offer a very competitive service. Please contact us for current prices. Our fees include textbooks, work books and all other resources and equipment needed in each term. We also provide the essential juice and biscuits to keep that brain working for the hour!
|
// Copyright (c) 2013 Martin Stumpf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#ifndef HPX_OPENCL_LCOS_EVENT_HPP_
#define HPX_OPENCL_LCOS_EVENT_HPP_
#include <hpx/hpx.hpp>
#include <hpx/traits/managed_component_policies.hpp>
#include "../export_definitions.hpp"
#include "zerocopy_buffer.hpp"
#include <boost/atomic.hpp>
#include <boost/detail/atomic_count.hpp>
#include <utility>
namespace hpx {
namespace opencl {
namespace lcos {
template <typename Result,
typename RemoteResult =
typename traits::promise_remote_result<Result>::type>
class event;
}
} // namespace opencl
} // namespace hpx
///////////////////////////////////////////////////////////////////////////////
namespace hpx {
namespace opencl {
namespace lcos {
namespace detail {
///////////////////////////////////////////////////////////////////////////
HPX_OPENCL_EXPORT void unregister_event(hpx::naming::id_type device_id,
hpx::naming::gid_type event_gid);
///////////////////////////////////////////////////////////////////////////
// Zero-copy-Data Function
//
// This function is here for zero-copy of read_to_userbuffer_remote
// Receive a zerocopy_buffer as result of the event.
// De-serialization of the zerocopy_buffer automatically writes
// the data to result_buffer (zerocopy_buffer knows the address of the
// result_buffer's data() member)
// Then set result_buffer as data of this event.
// template <typename T>
// void set_zerocopy_data( hpx::naming::id_type event_id,
// hpx::opencl::lcos::zerocopy_buffer buf )
// {
// typedef hpx::serialization::serialize_buffer<T> buffer_type;
// typedef hpx::lcos::base_lco_with_value<buffer_type> lco_type;
// typedef typename
// hpx::opencl::lcos::event<buffer_type>::shared_state_type
// event_ptr;
//
// // Resolve address of lco
// hpx::naming::address lco_addr = agas::resolve(event_id).get();
//
// // Ensure everything is correct
// HPX_ASSERT(hpx::get_locality() == lco_addr.locality_);
// HPX_ASSERT(traits::component_type_is_compatible<lco_type>::call(lco_addr));
//
// // Get ptr to lco
// auto lco_ptr = hpx::get_lva<lco_type>::call(lco_addr.address_);
//
// // Get ptr to event
// event_ptr event = static_cast<event_ptr>(lco_ptr);
//
// // Trigger the event
// event->set_value(std::move(event->result_buffer));
// }
// // Action declaration
// template <typename T>
// struct set_zerocopy_data_action
// : hpx::actions::make_direct_action<
// void (*)( hpx::naming::id_type,
// hpx::opencl::lcos::zerocopy_buffer), &set_zerocopy_data<T>,
// set_zerocopy_data_action<T>
// >
// {};
///////////////////////////////////////////////////////////////////////////
template <typename Result, typename RemoteResult>
class event_data : public hpx::lcos::detail::future_data<Result> {
private:
typedef hpx::lcos::detail::future_data<Result> parent_type;
typedef typename parent_type::result_type result_type;
public:
typedef typename parent_type::init_no_addref init_no_addref;
event_data() {}
event_data(init_no_addref no_addref) : parent_type(no_addref) {}
~event_data() {
HPX_ASSERT(device_id && event_id);
unregister_event(device_id, event_id.get_gid());
}
void init(hpx::naming::id_type&& device_id_) {
device_id = std::move(device_id_);
}
void set_id(hpx::id_type const& id) { event_id = id; }
public:
hpx::naming::gid_type get_device_gid() const {
HPX_ASSERT(device_id);
return device_id.get_gid();
}
hpx::naming::id_type get_event_id() const {
HPX_ASSERT(event_id);
return event_id;
}
private:
hpx::naming::id_type device_id;
hpx::naming::id_type event_id;
};
///////////////////////////////////////////////////////////////////////////
template <>
class event_data<void, hpx::util::unused_type>
: public hpx::lcos::detail::future_data<void> {
private:
typedef hpx::lcos::detail::future_data<void> parent_type;
typedef parent_type::result_type result_type;
public:
typedef typename parent_type::init_no_addref init_no_addref;
event_data() : is_armed(false) {}
event_data(init_no_addref no_addref)
: is_armed(false), parent_type(no_addref) {}
~event_data() {
HPX_ASSERT(device_id && event_id);
unregister_event(device_id, event_id.get_gid());
}
void init(hpx::naming::id_type&& device_id_) {
device_id = std::move(device_id_);
}
void set_id(hpx::id_type const& id) { event_id = id; }
private:
boost::atomic<bool> is_armed;
HPX_OPENCL_EXPORT void arm();
public:
// Gets called by when_all, wait_all, etc
void execute_deferred(error_code& ec = throws) {
if (!is_armed.exchange(true)) arm();
}
// retrieving the value
result_type* get_result(error_code& ec = throws) {
this->execute_deferred();
return this->parent_type::get_result(ec);
}
// wait for the value
void wait(error_code& ec = throws) {
this->execute_deferred();
this->parent_type::wait(ec);
}
hpx::lcos::future_status wait_until(
hpx::util::steady_clock::time_point const& abs_time,
error_code& ec = throws) {
this->execute_deferred();
return this->parent_type::wait_until(abs_time, ec);
}
public:
hpx::naming::gid_type get_device_gid() const {
HPX_ASSERT(device_id);
return device_id.get_gid();
}
hpx::naming::id_type get_event_id() const {
HPX_ASSERT(event_id);
return event_id;
}
private:
hpx::naming::id_type device_id;
hpx::naming::id_type event_id;
};
} // namespace detail
} // namespace lcos
} // namespace opencl
} // namespace hpx
///////////////////////////////////////////////////////////////////////////////
namespace hpx {
namespace opencl {
namespace lcos {
///////////////////////////////////////////////////////////////////////////
template <typename Result, typename RemoteResult>
class event
: hpx::lcos::detail::promise_base<
Result, RemoteResult, detail::event_data<Result, RemoteResult> > {
typedef hpx::lcos::detail::promise_base<
Result, RemoteResult, detail::event_data<Result, RemoteResult> >
base_type;
public:
typedef typename base_type::shared_state_type shared_state_type;
typedef Result result_type;
/// Construct a new \a event instance. The supplied
/// \a thread will be notified as soon as the result of the
/// operation associated with this future instance has been
/// returned.
///
/// \note The result of the requested operation is expected to
/// be returned as the first parameter using a
/// \a base_lco#set_value action. Any error has to be
/// reported using a \a base_lco::set_exception action. The
/// target for either of these actions has to be this
/// future instance (as it has to be sent along
/// with the action as the continuation parameter).
event(hpx::naming::id_type device_id) : base_type() {
this->shared_state_->init(std::move(device_id));
}
public:
/// Reset the event to allow to restart an asynchronous
/// operation. Allows any subsequent set_data operation to succeed.
void reset() {
this->shared_state_->reset();
this->future_retrieved_ = false;
}
/// \brief Return the global id of this \a future instance
naming::id_type get_event_id() const {
return this->shared_state_->get_event_id();
}
/// Return whether or not the data is available for this
/// \a event.
bool is_ready() const { return this->shared_state_->is_ready(); }
/// Return whether this instance has been properly initialized
using base_type::valid;
using base_type::get_future;
};
///////////////////////////////////////////////////////////////////////////
template <>
class event<void, hpx::util::unused_type>
: hpx::lcos::detail::promise_base<
void, hpx::util::unused_type,
detail::event_data<void, hpx::util::unused_type> > {
typedef hpx::lcos::detail::promise_base<
void, hpx::util::unused_type,
detail::event_data<void, hpx::util::unused_type> >
base_type;
public:
typedef base_type::shared_state_type shared_state_type;
typedef hpx::util::unused_type result_type;
/// Construct a new \a event instance. The supplied
/// \a thread will be notified as soon as the result of the
/// operation associated with this future instance has been
/// returned.
///
/// \note The result of the requested operation is expected to
/// be returned as the first parameter using a
/// \a base_lco#set_value action. Any error has to be
/// reported using a \a base_lco::set_exception action. The
/// target for either of these actions has to be this
/// future instance (as it has to be sent along
/// with the action as the continuation parameter).
event(hpx::naming::id_type device_id) : base_type() {
this->shared_state_->init(std::move(device_id));
}
public:
/// Reset the event to allow to restart an asynchronous
/// operation. Allows any subsequent set_data operation to succeed.
void reset() {
this->shared_state_->reset();
this->future_retrieved_ = false;
}
/// \brief Return the global id of this \a future instance
naming::id_type get_event_id() const {
return this->shared_state_->get_event_id();
}
/// Return whether or not the data is available for this \a event.
bool is_ready() const { return this->shared_state_->is_ready(); }
using base_type::get_future;
};
} // namespace lcos
} // namespace opencl
} // namespace hpx
#endif
|
module SUN_generator
using LinearAlgebra
struct Generator
NC::Int64
generator::Array{Array{ComplexF64,2},1}
function Generator(NC)
return new(NC,make_generators(NC))
end
end
function Base.getindex(g::Generator,i)
return g.generator[i]
end
function Base.length(a::Generator)
return length(a.generator)
end
function lie2matrix!(matrix,g::Generator,a)
matrix .= 0
NC = g.NC
for (i,genmatrix) in enumerate(g.generator)
matrix .+= a[i]*genmatrix
end
return
end
function matrix2lie!(a,g::Generator,A)
for i=1:length(a)
#println("i = $i")
#display(g.generator[i]*g.generator[i])
#println("\t")
#println(tr(g.generator[i]*A)/2)
a[i] = tr(g.generator[i]*A)/2
end
return
end
sigma = []
s = ComplexF64[
0 1
1 0
]
push!(sigma,s)
s = ComplexF64[
0 -im
im 0
]
push!(sigma,s)
s = ComplexF64[
1 0
0 -1
]
push!(sigma,s)
function make_largematrix(σ,i,j,Nc)
λ = zeros(ComplexF64,Nc,Nc)
λ[i,i] = σ[1,1]
λ[i,j] = σ[1,2]
λ[j,i] = σ[2,1]
λ[j,j] = σ[2,2]
return λ
end
function normalization(A)
Norm = sqrt(real(tr(A*A))/2)
#print(" Normalization = √",real(tr(A*A))/2,"= ")
#println("$Norm")
return Norm
end
function make_generators(Nc)
d=["x","y","z"]
#
lams = Array{Complex,2}[]
#
if Nc < 2
error("Invalid Nc=$Nc")
end
#
# off-diagonal part
#println("Off diagonals")
for i=1:Nc
for j=i+1:Nc
for a = 1:2
#println("$(d[a]): i j = $i $j")
A = make_largematrix(sigma[a],i,j,Nc)
#showmat(A)
N=normalization(A)
A = A/N
push!(lams,A)
#println(" ")
end
end
end
#
# diagonal part
#println("diagonals")
for a=1:Nc-1
A = zeros(ComplexF64,Nc,Nc)
for i=1:a
A[i,i] = 1
end
A[a+1,a+1] = -tr(A)
#showmat(A)
N=normalization(A)
A = A/N
push!(lams,A)
#println(" ")
end
return lams
end
end
|
State Before: α : Type u
L L₁ L₂ L₃ L₄ : List (α × Bool)
β : Type v
inst✝ : Group β
f : α → β
x y : FreeGroup α
s : Subgroup β
H : Set.range f ⊆ ↑s
⊢ MonoidHom.range (↑lift f) ≤ s State After: case intro.mk
α : Type u
L✝ L₁ L₂ L₃ L₄ : List (α × Bool)
β : Type v
inst✝ : Group β
f : α → β
x y : FreeGroup α
s : Subgroup β
H : Set.range f ⊆ ↑s
w✝ : FreeGroup α
L : List (α × Bool)
⊢ ↑(↑lift f) (Quot.mk Red.Step L) ∈ s Tactic: rintro _ ⟨⟨L⟩, rfl⟩ State Before: case intro.mk
α : Type u
L✝ L₁ L₂ L₃ L₄ : List (α × Bool)
β : Type v
inst✝ : Group β
f : α → β
x y : FreeGroup α
s : Subgroup β
H : Set.range f ⊆ ↑s
w✝ : FreeGroup α
L : List (α × Bool)
⊢ ↑(↑lift f) (Quot.mk Red.Step L) ∈ s State After: no goals Tactic: exact
List.recOn L s.one_mem fun ⟨x, b⟩ tl ih =>
Bool.recOn b (by simp at ih⊢; exact s.mul_mem (s.inv_mem <| H ⟨x, rfl⟩) ih)
(by simp at ih⊢; exact s.mul_mem (H ⟨x, rfl⟩) ih) State Before: α : Type u
L✝ L₁ L₂ L₃ L₄ : List (α × Bool)
β : Type v
inst✝ : Group β
f : α → β
x✝¹ y : FreeGroup α
s : Subgroup β
H : Set.range f ⊆ ↑s
w✝ : FreeGroup α
L : List (α × Bool)
x✝ : α × Bool
tl : List (α × Bool)
ih : ↑(↑lift f) (Quot.mk Red.Step tl) ∈ s
x : α
b : Bool
⊢ ↑(↑lift f) (Quot.mk Red.Step ((x, false) :: tl)) ∈ s State After: α : Type u
L✝ L₁ L₂ L₃ L₄ : List (α × Bool)
β : Type v
inst✝ : Group β
f : α → β
x✝¹ y : FreeGroup α
s : Subgroup β
H : Set.range f ⊆ ↑s
w✝ : FreeGroup α
L : List (α × Bool)
x✝ : α × Bool
tl : List (α × Bool)
ih : List.prod (List.map (fun x => bif x.snd then f x.fst else (f x.fst)⁻¹) tl) ∈ s
x : α
b : Bool
⊢ (f x)⁻¹ * List.prod (List.map (fun x => bif x.snd then f x.fst else (f x.fst)⁻¹) tl) ∈ s Tactic: simp at ih⊢ State Before: α : Type u
L✝ L₁ L₂ L₃ L₄ : List (α × Bool)
β : Type v
inst✝ : Group β
f : α → β
x✝¹ y : FreeGroup α
s : Subgroup β
H : Set.range f ⊆ ↑s
w✝ : FreeGroup α
L : List (α × Bool)
x✝ : α × Bool
tl : List (α × Bool)
ih : List.prod (List.map (fun x => bif x.snd then f x.fst else (f x.fst)⁻¹) tl) ∈ s
x : α
b : Bool
⊢ (f x)⁻¹ * List.prod (List.map (fun x => bif x.snd then f x.fst else (f x.fst)⁻¹) tl) ∈ s State After: no goals Tactic: exact s.mul_mem (s.inv_mem <| H ⟨x, rfl⟩) ih State Before: α : Type u
L✝ L₁ L₂ L₃ L₄ : List (α × Bool)
β : Type v
inst✝ : Group β
f : α → β
x✝¹ y : FreeGroup α
s : Subgroup β
H : Set.range f ⊆ ↑s
w✝ : FreeGroup α
L : List (α × Bool)
x✝ : α × Bool
tl : List (α × Bool)
ih : ↑(↑lift f) (Quot.mk Red.Step tl) ∈ s
x : α
b : Bool
⊢ ↑(↑lift f) (Quot.mk Red.Step ((x, true) :: tl)) ∈ s State After: α : Type u
L✝ L₁ L₂ L₃ L₄ : List (α × Bool)
β : Type v
inst✝ : Group β
f : α → β
x✝¹ y : FreeGroup α
s : Subgroup β
H : Set.range f ⊆ ↑s
w✝ : FreeGroup α
L : List (α × Bool)
x✝ : α × Bool
tl : List (α × Bool)
ih : List.prod (List.map (fun x => bif x.snd then f x.fst else (f x.fst)⁻¹) tl) ∈ s
x : α
b : Bool
⊢ f x * List.prod (List.map (fun x => bif x.snd then f x.fst else (f x.fst)⁻¹) tl) ∈ s Tactic: simp at ih⊢ State Before: α : Type u
L✝ L₁ L₂ L₃ L₄ : List (α × Bool)
β : Type v
inst✝ : Group β
f : α → β
x✝¹ y : FreeGroup α
s : Subgroup β
H : Set.range f ⊆ ↑s
w✝ : FreeGroup α
L : List (α × Bool)
x✝ : α × Bool
tl : List (α × Bool)
ih : List.prod (List.map (fun x => bif x.snd then f x.fst else (f x.fst)⁻¹) tl) ∈ s
x : α
b : Bool
⊢ f x * List.prod (List.map (fun x => bif x.snd then f x.fst else (f x.fst)⁻¹) tl) ∈ s State After: no goals Tactic: exact s.mul_mem (H ⟨x, rfl⟩) ih
|
A westward moving tropical depression developed in the southwestern Caribbean Sea just west of Bluefields , Nicaragua at 1200 UTC on September 18 . The following day , the depression intensified into a tropical storm at 0600 UTC . The tropical storm made landfall on the Mosquito Coast of Nicaragua at 1400 UTC , with winds of 40 mph ( 65 km / h ) . The cyclone weakened to a tropical depression over land , but reintensified back to tropical storm strength upon entry into the Gulf of Honduras on September 20 . The cyclone 's northwest motion caused it to make a second landfall near the border of Mexico and British Honduras at 0300 UTC on September 21 as a slightly stronger system with winds of 50 mph ( 85 km / h ) ; this would be the storm 's peak intensity . Over the Yucatán Peninsula , the tropical storm re @-@ weakened , but later intensified once again once it reached the Gulf of Mexico . In the Gulf , the storm made a gradual curve northward , before making a final landfall near Lafayette , Louisiana at 0900 UTC on September 24 with winds of 45 mph ( 75 km / h ) and a minimum barometric pressure of 1002 mbar ( hPa ; 29 @.@ 59 inHg ) . Once inland , the tropical cyclone curved eastward and weakened before dissipating the next day , after becoming absorbed by a frontal boundary .
|
(* Title: An example submission to the Archive of Formal Proofs
Author: Gerwin Klein <kleing at cse.unsw.edu.au>, 2004
Maintainer: Gerwin Klein <kleing at cse.unsw.edu.au>
*)
section "An Example Submission"
theory Submission
imports Main
begin
text \<open>
This is an example submission to the Archive of Formal Proofs.
The scope of the archive encompasses examples, textbook-style
proofs, libraries and larger scientific developments.
\<close>
section "Format of a submission"
text \<open>
Submission should be via the web page @{url "https://ci.isabelle.systems/afp-submission/"}.
The tar file submission of the example you are reading is at
@{url "http://isa-afp.org/release/afp-Example-Submission-current.tar.gz"}.
\<close>
section "Proof styles"
text \<open>
We accept proofs in \isakeyword{apply}-script style like the
following.
\<close>
lemma true: "True"
apply blast
done
text \<open>
We encourage structured proofs with comments and
explanations. The Isabelle document preparation tools support
antiquotations like @{thm true}, normal {\LaTeX} commands and BibTeX
citations. See \cite{LNCS2283} and the Isabelle documentation for
more information.
\<close>
lemma very_true: "True"
proof -
\<comment> \<open>a very roundabout way\<close>
fix P have "P \<longrightarrow> True" by blast
\<comment> \<open>to show @{term True}\<close>
thus True by blast
qed
section "The anatomy of a submission"
text \<open>
The directory structure of this example submission is the following
\begin{verbatim}
Example-Submission/
document/
root.tex
root.bib
ROOT
Submission.thy
\end{verbatim}
The document directory contains the {\LaTeX} master file
\texttt{root.tex} and the bibliography \texttt{root.bib}.
The {\LaTeX} part of your
submission should contain title, abstract, author, and any
further documentation
you wish to provide.
\texttt{ROOT} controls which theories should be loaded. If you have
one main theory that depends on all the others, you only need to
include this one. You can also use the \texttt{ROOT} file to control the
order in which theories are read.
The file \texttt{Submission.thy} is the Isabelle theory containing
this text. A usual submission has more than one theory file. You can
devise your own subdirectory structure if you have more theories and
one directory becomes too crowded. You can also build on existing articles
in the AFP by importing them. For example, if you build on theory W in
the article MiniML, the way to import it is:
\begin{verbatim}
theory My_Theory
imports MiniML.W
begin
\end{verbatim}
\<close>
end
|
#include <sstream>
#include <iostream>
#include <boost/property_tree/json_parser.hpp>
#include <gts/json.h>
// ----------------------------------------------------------------------------
template <class container_t>
std::string format_values(const container_t& values)
{
if (values.empty())
return std::string("[]");
std::stringstream stream;
stream << "[ ";
for (const auto& value : values)
stream << "'" << value << "' ,";
stream.seekp(-1, std::ios_base::end);
stream << "]";
return stream.str();
}
// ----------------------------------------------------------------------------
std::string format_ptree(const boost::property_tree::ptree& tree)
{
std::stringstream stream;
boost::property_tree::write_json(stream, tree, true);
return stream.str();
}
// ----------------------------------------------------------------------------
template <class container_t>
boost::property_tree::ptree serialize_by_ptree(const container_t& values)
{
boost::property_tree::ptree tree;
for (const auto& value : values)
tree.put("", value);
return tree;
}
// ----------------------------------------------------------------------------
template <class container_t>
boost::property_tree::ptree serialize_by_gts(const container_t& values)
{
return boost::property_tree::ptree{};
}
// ----------------------------------------------------------------------------
template <class container_t>
void run_sample(const std::string& name, const container_t& values)
{
std::cout << " ------------ " << name << " ------------ " << std::endl;
std::cout << "Values: " << format_values(values) << std::endl;
std::cout << "Serialization (ptree/boost): " << format_ptree(serialize_by_ptree(values)) << std::endl;
std::cout << "Serialization (gts/boost): " << format_ptree(serialize_by_gts(values)) << std::endl;
}
// ----------------------------------------------------------------------------
int main()
{
run_sample("vector<bool>", std::vector<bool>{ true, true, false, false, true });
run_sample("vector<uint32_t>", std::vector<std::uint32_t>{ 456, 789123, 115654, 11 });
run_sample("vector<double>", std::vector<double>{ -0.01, 0.54, 5.65, 9.894, -45.0 });
run_sample("vector<string>", std::vector<std::string>{ "one", "two", "three", "four" });
return 0;
}
|
library(mixtools)
library(animation)
plotClusteringState <- function(data, clustering, components, likelihoods, idx) {
nComponents = length(unique(clustering))
par(mfrow = c(2,1))
plot(data, col = clustering + 1, xlim= c(-4, 4), ylim= c(-4, 4), main = "Cluster Membership Evolution", xlab = "", ylab = "")
for(k in seq_len(nComponents)){
mean = as.numeric(strsplit(components[1, (k - 1) *2 + 1],":")[[1]])
covMat = matrix(as.numeric(strsplit(components[1, k * 2],":")[[1]]),2,2)
ellipse(mu=mean, sigma=covMat, alpha = .005, npoints = 250, col=k)
ellipse(mu=mean, sigma=covMat, alpha = .01, npoints = 250, col=k)
ellipse(mu=mean, sigma=covMat, alpha = .05, npoints = 250, col=k)
ellipse(mu=mean, sigma=covMat, alpha = .10, npoints = 250, col=k)
}
plot(y=likelihoods, x = 1:length(likelihoods), t="l", xlab = "Iteration", ylab = "LogLikelihood", main = "LogLikelihood Evolution")
points(x= idx, y= likelihoods[idx], col="red", cex=1)
points(x= idx, y= likelihoods[idx], col="red", cex=2)
}
dirPath = [RESULT PATH HERE]
data = read.csv(paste0(dirPath, "/data.csv"), header = F)[,-1]
# Final clustering obtained after dpmm
clusteringEveryIteration = read.csv(paste0(dirPath, "/membershipHistory.csv"), header = F)[,-1]
nClusterMax = max(clusteringEveryIteration) + 1
# One line = every components of a given iteration
componentsEveryIterations = read.csv(paste0(dirPath, "/componentsHistory.csv"),
stringsAsFactors = F, header = F,
col.names = paste0("V",seq_len(2*nClusterMax+1)),
fill = TRUE)[,-1]
# likelihoods
likelihoods = read.csv(paste0(dirPath, "/likelihoods.csv"),
stringsAsFactors = F, header = F)[-1,-1]
nIter = length(likelihoods)
colnames(data) <- c("X", "Y")
nIteration = nrow(clusteringEveryIteration)
oopt = ani.options(interval = 0.4)
des = c("Bivariate Gaussian DPMM.\n\n")
saveGIF({
par(mar = c(4, 4, 2, 2))
for (i in 1:nIter) {
print(i)
plotClusteringState(data,
clustering = unlist(clusteringEveryIteration[i,]),
components = componentsEveryIterations[i, ],
likelihoods, i)
ani.pause()
}
}, title = "Evolution of DPMM clustering",
description = des,ani.width = 400, ani.height = 700)
|
MODULE ED_VARS_GLOBAL
USE SF_CONSTANTS
USE ED_SPARSE_MATRIX
USE ED_INPUT_VARS
#ifdef _MPI
USE MPI
USE SF_MPI
#endif
implicit none
!-------------------- H EXPANSION STRUCTURE ----------------------!
type H_operator
complex(8),dimension(:,:,:,:,:,:),allocatable :: O !Replica hamilt
end type H_operator
type(H_operator),dimension(:),allocatable :: Hreplica_basis
real(8),dimension(:),allocatable :: Hreplica_lambda
logical :: Hreplica_status=.false.
!-------------------- EFFECTIVE BATH STRUCTURE ----------------------!
type effective_bath_component
integer :: N_dec
real(8) :: v !spin-keep hyb.
real(8),dimension(:),allocatable :: lambda
end type effective_bath_component
type effective_bath
type(effective_bath_component),dimension(:),allocatable :: item
logical :: status=.false.
end type effective_bath
!-------------------- CUSTOM OBSERVABLE STRUCTURE ----------------------!
type observable
complex(8),dimension(:,:,:),allocatable :: sij
character(len=32) :: o_name
real(8) :: o_value
end type observable
type custom_observables
type(observable),dimension(:),allocatable :: item
complex(8),dimension(:,:,:),allocatable :: Hk
integer :: N_asked
integer :: N_filled
logical :: init=.false.
end type custom_observables
!---------------- SECTOR-TO-FOCK SPACE STRUCTURE -------------------!
type sector_map
integer,dimension(:),allocatable :: map
logical :: status=.false.
end type sector_map
interface map_allocate
module procedure :: map_allocate_scalar
module procedure :: map_allocate_vector
end interface map_allocate
interface map_deallocate
module procedure :: map_deallocate_scalar
module procedure :: map_deallocate_vector
end interface map_deallocate
!------------------ ABTRACT INTERFACES PROCEDURES ------------------!
!SPARSE MATRIX-VECTOR PRODUCTS USED IN ED_MATVEC
!dbleMat*dbleVec
abstract interface
subroutine cc_sparse_HxV(Nloc,v,Hv)
integer :: Nloc
complex(8),dimension(Nloc) :: v
complex(8),dimension(Nloc) :: Hv
end subroutine cc_sparse_HxV
end interface
!-------------- GMATRIX FOR FAST EVALUATION OF GF ------------------!
!note that we use a single Qmatrix here which must be intended as
!component corresponding to the poles.
type GFspectrum
complex(8),dimension(:),allocatable :: weight
complex(8),dimension(:),allocatable :: poles
end type GFspectrum
type GFchannel
type(GFspectrum),dimension(:),allocatable :: channel !N_channel = 2 (c,cdag), 4 (c,cdag,c pm cdag)
end type GFchannel
type GFmatrix
type(GFchannel),dimension(:),allocatable :: state !state_list%size = # of state in the spectrum
end type GFmatrix
interface GFmatrix_allocate
module procedure :: allocate_GFmatrix_Nstate
module procedure :: allocate_GFmatrix_Nchan
module procedure :: allocate_GFmatrix_Nexc
end interface GFmatrix_allocate
!-------------------------- ED VARIABLES --------------------------!
!SIZE OF THE PROBLEM
!=========================================================
integer,save :: Ns !Number of levels per spin
integer,save :: Nsectors !Number of sectors
integer,save :: Ns_orb
integer,save :: Ns_ud
!
integer :: Nlso
!local part of the Hamiltonian
!INTERNAL USE (accessed thru functions)
!=========================================================
complex(8),dimension(:,:,:,:,:,:),allocatable :: impHloc !local hamiltonian [Nlat][Nlat][Nspin][Nspin][Norb][Norb]
!Some maps between sectors and full Hilbert space (pointers)
!PRIVATE:
!=========================================================
integer,allocatable,dimension(:) :: getDim ! [Nsectors]
integer,allocatable,dimension(:,:,:) :: getCsector ! [1/Norb,2,NSectors]
integer,allocatable,dimension(:,:,:) :: getCDGsector ! [1/Norb,2,NSectors]
integer,allocatable,dimension(:,:,:) :: getBathStride
! integer,allocatable,dimension(:,:) :: impIndex
logical,allocatable,dimension(:) :: twin_mask
logical,allocatable,dimension(:) :: sectors_mask
!Effective Bath used in the ED code (this is opaque to user)
!PRIVATE
!=========================================================
type(effective_bath) :: dmft_bath
!Variables for DIAGONALIZATION
!PRIVATE
!=========================================================
type(sparse_matrix_csr) :: spH0d !diagonal part
type(sparse_matrix_csr) :: spH0nd !non-diagonal part
type(sparse_matrix_csr),dimension(:),allocatable :: spH0ups,spH0dws !reduced UP and DW parts
!
procedure(cc_sparse_HxV),pointer :: spHtimesV_p=>null()
!Variables for DIAGONALIZATION
!PRIVATE
!=========================================================
integer,allocatable,dimension(:) :: neigen_sector
!--------------- LATTICE WRAP VARIABLES -----------------!
#if __GFORTRAN__ && __GNUC__ > 8
integer,allocatable,dimension(:,:) :: neigen_sector_ineq
integer,allocatable,dimension(:) :: neigen_total_ineq
#endif
logical :: trim_state_list=.false.
!Partition function
!PRIVATE
!=========================================================
real(8) :: zeta_function
real(8) :: gs_energy
real(8) :: max_exc
!Impurity Green's function and Self-Energies: (Nlat,Nlat,Nspin,Nspin,Norb,Norb,:)
!PRIVATE (now public but accessible thru routine)
!=========================================================
complex(8),allocatable,dimension(:,:,:,:,:,:,:) :: impGmats ![Nlat][Nlat][Nspin][Nspin][Norb][Norb][L]
complex(8),allocatable,dimension(:,:,:,:,:,:,:) :: impGreal ![Nlat][Nlat][Nspin][Nspin][Norb][Norb][L]
!
complex(8),allocatable,dimension(:,:,:,:,:,:,:) :: impG0mats ![Nlat][Nlat][Nspin][Nspin][Norb][Norb][L]
complex(8),allocatable,dimension(:,:,:,:,:,:,:) :: impG0real ![Nlat][Nlat][Nspin][Nspin][Norb][Norb][L]
!
complex(8),allocatable,dimension(:,:,:,:,:,:,:) :: impSmats ![Nlat][Nlat][Nspin][Nspin][Norb][Norb][L]
complex(8),allocatable,dimension(:,:,:,:,:,:,:) :: impSreal ![Nlat][Nlat][Nspin][Nspin][Norb][Norb][L]
!
type(GFmatrix),allocatable,dimension(:,:,:,:,:,:) :: impGmatrix
! !--------------- LATTICE WRAP VARIABLES -----------------!
#if __GFORTRAN__ && __GNUC__ > 8
complex(8),dimension(:,:,:,:,:,:,:,:),allocatable,save :: Smatsii,Srealii ![Nineq][Nlat][Nlat][Nspin][Nspin][Norb][Norb][L]
complex(8),dimension(:,:,:,:,:,:,:,:),allocatable,save :: Gmatsii,Grealii ![Nineq][Nlat][Nlat][Nspin][Nspin][Norb][Norb][L]
complex(8),dimension(:,:,:,:,:,:,:,:),allocatable,save :: G0matsii,G0realii ![Nineq][Nlat][Nlat][Nspin][Nspin][Norb][Norb][L]
complex(8),dimension(:,:,:,:,:,:,:) ,allocatable,save :: imp_density_matrix_ii ![Nineq][Nlat][Nlat][Nspin][Nspin][Norb][Norb]
#endif
! !Spin Susceptibilities
! !=========================================================
! real(8),allocatable,dimension(:,:) :: spinChi_tau
! complex(8),allocatable,dimension(:,:) :: spinChi_w
! complex(8),allocatable,dimension(:,:) :: spinChi_iv
! !Diagonal/Off-diagonal charge-charge Susceptibilities
! !=========================================================
! real(8),allocatable,dimension(:,:,:) :: densChi_tau
! complex(8),allocatable,dimension(:,:,:) :: densChi_w
! complex(8),allocatable,dimension(:,:,:) :: densChi_iv
! !Mixed inter-orbital charge-charge Susceptibilities
! !=========================================================
! real(8),allocatable,dimension(:,:,:) :: densChi_mix_tau
! complex(8),allocatable,dimension(:,:,:) :: densChi_mix_w
! complex(8),allocatable,dimension(:,:,:) :: densChi_mix_iv
! !Total (orbital-sum) Density-density Susceptibilities
! !=========================================================
! real(8),allocatable,dimension(:) :: densChi_tot_tau
! complex(8),allocatable,dimension(:) :: densChi_tot_w
! complex(8),allocatable,dimension(:) :: densChi_tot_iv
! !Pair-Pair Susceptibilities
! !=========================================================
! real(8),allocatable,dimension(:,:) :: pairChi_tau
! complex(8),allocatable,dimension(:,:) :: pairChi_w
! complex(8),allocatable,dimension(:,:) :: pairChi_iv
!Density and double occupancy
!PRIVATE (now public but accessible thru routines)
!=========================================================
real(8),dimension(:,:),allocatable :: ed_dens
real(8),dimension(:,:),allocatable :: ed_dens_up,ed_dens_dw
real(8),dimension(:,:),allocatable :: ed_docc,ed_mag
!--------------- LATTICE WRAP VARIABLES -----------------!
type(custom_observables) :: custom_o
!Local energies and generalized double occupancies
!PRIVATE (now public but accessible thru routine)
!=========================================================
!real(8),dimension(:),allocatable :: ed_Epot,ed_Eint,ed_Ehartree,ed_Eknot
real(8) :: ed_Epot,ed_Eint,ed_Ehartree,ed_Eknot
!real(8),dimension(:),allocatable :: ed_Dust,ed_Dund,ed_Dse,ed_Dph
real(8) :: ed_Dust,ed_Dund,ed_Dse,ed_Dph
! !--------------- LATTICE WRAP VARIABLES -----------------!
real(8),dimension(:,:),allocatable,save :: ddii,eii
! !Impurity operators
! !PRIVATE (now public but accessible thru routine)
! !=========================================================
complex(8),allocatable,dimension(:,:,:,:,:,:) :: imp_density_matrix
#if __GFORTRAN__ && __GNUC__ > 8
!--------------- LATTICE WRAP VARIABLES -----------------!
complex(8),dimension(:,:,:,:,:,:,:,:),allocatable,save :: Smats_ineq,Sreal_ineq ![Nlat][Nspin][Nspin][Norb][Norb][L]
!complex(8),dimension(:,:,:,:,:,:,:,:),allocatable,save :: SAmats_ineq,SAreal_ineq
complex(8),dimension(:,:,:,:,:,:,:,:),allocatable,save :: Gmats_ineq,Greal_ineq
!complex(8),dimension(:,:,:,:,:,:,:,:),allocatable,save :: Fmats_ineq,Freal_ineq
complex(8),dimension(:,:,:,:,:,:,:,:),allocatable,save :: G0mats_ineq,G0real_ineq
!complex(8),dimension(:,:,:,:,:,:,:,:),allocatable,save :: F0mats_ineq,F0real_ineq
!complex(8),dimension(:,:),allocatable,save :: Dmats_ph_ineq,Dreal_ph_ineq
complex(8),dimension(:,:,:,:,:,:,:),allocatable,save :: imp_density_matrix_ineq
real(8),dimension(:,:,:),allocatable,save :: dens_ineq
real(8),dimension(:,:,:),allocatable,save :: docc_ineq
real(8),dimension(:,:,:),allocatable,save :: mag_ineq
!real(8),dimension(:,:,:,:),allocatable,save :: phisc_ineq
real(8),dimension(:,:),allocatable,save :: dd_ineq,e_ineq
real(8),dimension(:,:),allocatable :: Hreplica_lambda_ineq
#endif
!File suffixes for printing fine tuning.
!=========================================================
character(len=32) :: ed_file_suffix="" !suffix string attached to the output files.
character(len=10) :: ineq_site_suffix="_ineq"
integer :: site_indx_padding=4
logical :: Jhflag !spin-exchange and pair-hopping flag.
logical :: offdiag_gf_flag=.false.
!This is the internal Mpi Communicator and variables.
!=========================================================
#ifdef _MPI
integer :: MpiComm_Global=MPI_COMM_NULL
integer :: MpiComm=MPI_COMM_NULL
#endif
integer :: MpiGroup_Global=MPI_GROUP_NULL
integer :: MpiGroup=MPI_GROUP_NULL
logical :: MpiStatus=.false.
logical :: MpiMaster=.true.
integer :: MpiRank=0
integer :: MpiSize=1
integer,allocatable,dimension(:) :: MpiMembers
integer :: mpiQup=0
integer :: mpiRup=0
integer :: mpiQdw=0
integer :: mpiRdw=0
integer :: mpiQ=0
integer :: mpiR=0
integer :: mpiIstart
integer :: mpiIend
integer :: mpiIshift
logical :: mpiAllThreads=.true.
contains
!=========================================================
subroutine map_allocate_scalar(H,N)
type(sector_map) :: H
integer :: N
if(H%status) call map_deallocate_scalar(H)
allocate(H%map(N))
H%status=.true.
end subroutine map_allocate_scalar
!
subroutine map_allocate_vector(H,N)
type(sector_map),dimension(:) :: H
integer,dimension(size(H)) :: N
integer :: i
do i=1,size(H)
call map_allocate_scalar(H(i),N(i))
enddo
end subroutine map_allocate_vector
!=========================================================
subroutine map_deallocate_scalar(H)
type(sector_map) :: H
if(.not.H%status)then
write(*,*) "WARNING map_deallocate_scalar: H is not allocated"
return
endif
if(allocated(H%map))deallocate(H%map)
H%status=.false.
end subroutine map_deallocate_scalar
!
subroutine map_deallocate_vector(H)
type(sector_map),dimension(:) :: H
integer :: i
do i=1,size(H)
call map_deallocate_scalar(H(i))
enddo
end subroutine map_deallocate_vector
!=========================================================
subroutine ed_set_MpiComm(comm)
#ifdef _MPI
integer :: comm,ierr
! call MPI_Comm_dup(Comm,MpiComm_Global,ierr)
! call MPI_Comm_dup(Comm,MpiComm,ierr)
MpiComm_Global = comm
MpiComm = comm
call Mpi_Comm_group(MpiComm_Global,MpiGroup_Global,ierr)
MpiStatus = .true.
MpiSize = get_Size_MPI(MpiComm_Global)
MpiRank = get_Rank_MPI(MpiComm_Global)
MpiMaster = get_Master_MPI(MpiComm_Global)
#else
integer,optional :: comm
#endif
end subroutine ed_set_MpiComm
subroutine ed_del_MpiComm()
#ifdef _MPI
MpiComm_Global = MPI_UNDEFINED
MpiComm = MPI_UNDEFINED
MpiGroup_Global= MPI_GROUP_NULL
MpiStatus = .false.
MpiSize = 1
MpiRank = 0
MpiMaster = .true.
#endif
end subroutine ed_del_MpiComm
!Allocate the channels in GFmatrix structure
subroutine allocate_gfmatrix_Nstate(self,Nstate)
type(GFmatrix) :: self
integer :: Nstate
if(allocated(self%state))deallocate(self%state)
allocate(self%state(Nstate))
end subroutine allocate_gfmatrix_Nstate
subroutine allocate_gfmatrix_Nchan(self,istate,Nchan)
type(GFmatrix) :: self
integer :: istate,Nchan
if(allocated(self%state(istate)%channel))deallocate(self%state(istate)%channel)
allocate(self%state(istate)%channel(Nchan))
end subroutine allocate_gfmatrix_Nchan
!Allocate the Excitations spectrum at a given channel
subroutine allocate_gfmatrix_Nexc(self,istate,ichan,Nexc)
type(GFmatrix) :: self
integer :: istate,ichan
integer :: Nexc
if(allocated(self%state(istate)%channel(ichan)%weight))deallocate(self%state(istate)%channel(ichan)%weight)
if(allocated(self%state(istate)%channel(ichan)%poles))deallocate(self%state(istate)%channel(ichan)%poles)
allocate(self%state(istate)%channel(ichan)%weight(Nexc))
allocate(self%state(istate)%channel(ichan)%poles(Nexc))
end subroutine allocate_gfmatrix_Nexc
END MODULE ED_VARS_GLOBAL
|
[STATEMENT]
lemma gs_inner:
assumes "R\<^sub>b = map ranking P\<^sub>b"
assumes "invar2 A B M ai a" "b = match A a"
shows "gs_inner P\<^sub>a R\<^sub>b M (A, B, a, b) = (A',B',a',b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai+1)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. gs_inner P\<^sub>a R\<^sub>b M (A, B, a, b) = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
[PROOF STEP]
unfolding gs_inner_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. while (\<lambda>(A, B, a, y). M ! y) (\<lambda>(A, B, a, b). let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a))) (A, B, a, b) = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
[PROOF STEP]
proof(rule while_rule2[where P = "\<lambda>(A,B,a,b). invar2 A B M ai a \<and> b = match A a"
and r = "measure (%(A, B, a, b). Pref.var P\<^sub>a A {<ai})"], goal_cases)
[PROOF STATE]
proof (state)
goal (4 subgoals):
1. case (A, B, a, b) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
2. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; case s of (A, B, a, x) \<Rightarrow> M ! x\<rbrakk> \<Longrightarrow> (case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a) \<and> (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
3. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
4. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
case 1
[PROOF STATE]
proof (state)
this:
goal (4 subgoals):
1. case (A, B, a, b) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
2. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; case s of (A, B, a, x) \<Rightarrow> M ! x\<rbrakk> \<Longrightarrow> (case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a) \<and> (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
3. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
4. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. case (A, B, a, b) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
R\<^sub>b = map ranking P\<^sub>b
invar2 A B M ai a
b = match A a
goal (1 subgoal):
1. case (A, B, a, b) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
[PROOF STEP]
unfolding var_def
[PROOF STATE]
proof (prove)
using this:
R\<^sub>b = map ranking P\<^sub>b
invar2 A B M ai a
b = match A a
goal (1 subgoal):
1. case (A, B, a, b) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
case (A, B, a, b) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
goal (3 subgoals):
1. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; case s of (A, B, a, x) \<Rightarrow> M ! x\<rbrakk> \<Longrightarrow> (case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a) \<and> (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
2. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
3. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; case s of (A, B, a, x) \<Rightarrow> M ! x\<rbrakk> \<Longrightarrow> (case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a) \<and> (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
2. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
3. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
case inv: (2 s)
[PROOF STATE]
proof (state)
this:
case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
case s of (A, B, a, x) \<Rightarrow> M ! x
goal (3 subgoals):
1. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; case s of (A, B, a, x) \<Rightarrow> M ! x\<rbrakk> \<Longrightarrow> (case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a) \<and> (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
2. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
3. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
obtain A B a b where s: "s = (A, B, a, b)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>A B a b. s = (A, B, a, b) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using prod_cases4
[PROOF STATE]
proof (prove)
using this:
(\<And>a b c d. ?y = (a, b, c, d) \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
goal (1 subgoal):
1. (\<And>A B a b. s = (A, B, a, b) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
s = (A, B, a, b)
goal (3 subgoals):
1. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; case s of (A, B, a, x) \<Rightarrow> M ! x\<rbrakk> \<Longrightarrow> (case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a) \<and> (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
2. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
3. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
have R: "\<forall>b<n. \<forall>a1<n. \<forall>a2<n. R\<^sub>b ! b ! a1 < R\<^sub>b ! b ! a2 \<longleftrightarrow> P\<^sub>b ! b \<turnstile> a1 < a2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>b<n. \<forall>a1<n. \<forall>a2<n. (R\<^sub>b ! b ! a1 < R\<^sub>b ! b ! a2) = (P\<^sub>b ! b \<turnstile> a1 < a2)
[PROOF STEP]
by (simp add: P\<^sub>b_set \<open>R\<^sub>b = _\<close> length_P\<^sub>b ranking_iff_pref)
[PROOF STATE]
proof (state)
this:
\<forall>b<n. \<forall>a1<n. \<forall>a2<n. (R\<^sub>b ! b ! a1 < R\<^sub>b ! b ! a2) = (P\<^sub>b ! b \<turnstile> a1 < a2)
goal (3 subgoals):
1. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; case s of (A, B, a, x) \<Rightarrow> M ! x\<rbrakk> \<Longrightarrow> (case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a) \<and> (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
2. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
3. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a) \<and> (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
[PROOF STEP]
proof(rule, goal_cases)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
2. (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
[PROOF STEP]
case 1
[PROOF STATE]
proof (state)
this:
goal (2 subgoals):
1. case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
2. (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
[PROOF STEP]
using inv
[PROOF STATE]
proof (prove)
using this:
case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
case s of (A, B, a, x) \<Rightarrow> M ! x
goal (1 subgoal):
1. case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
[PROOF STEP]
apply(simp only: s prod.case Let_def split: if_split)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>invar2 A B M ai a \<and> b = match A a; M ! match A a\<rbrakk> \<Longrightarrow> (R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! (B ! match A a) \<longrightarrow> invar2 (A[B ! match A a := A ! (B ! match A a) + 1]) (B[match A a := a]) M ai (B ! match A a) \<and> P\<^sub>a ! (B ! match A a) ! (A[B ! match A a := A ! (B ! match A a) + 1] ! (B ! match A a)) = match (A[B ! match A a := A ! (B ! match A a) + 1]) (B ! match A a)) \<and> (\<not> R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! (B ! match A a) \<longrightarrow> invar2 (A[a := A ! a + 1]) B M ai a \<and> P\<^sub>a ! a ! (A[a := A ! a + 1] ! a) = match (A[a := A ! a + 1]) a)
[PROOF STEP]
using inner_pres[OF R _ _ refl refl refl refl refl, of A B M ai a b]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>invar2 A B M ai a; M ! b; b = match A a\<rbrakk> \<Longrightarrow> (R\<^sub>b ! match A (B ! b) ! a < R\<^sub>b ! match A (B ! b) ! (B ! b) \<longrightarrow> invar2 (A[B ! b := A ! (B ! b) + 1]) (B[b := a]) M ai (B ! b) \<and> var (A[B ! b := A ! (B ! b) + 1]) {<ai} < var A {<ai}) \<and> (\<not> R\<^sub>b ! match A (B ! b) ! a < R\<^sub>b ! match A (B ! b) ! (B ! b) \<longrightarrow> invar2 (A[a := A ! a + 1]) B M ai a \<and> var (A[a := A ! a + 1]) {<ai} < var A {<ai})
goal (1 subgoal):
1. \<lbrakk>invar2 A B M ai a \<and> b = match A a; M ! match A a\<rbrakk> \<Longrightarrow> (R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! (B ! match A a) \<longrightarrow> invar2 (A[B ! match A a := A ! (B ! match A a) + 1]) (B[match A a := a]) M ai (B ! match A a) \<and> P\<^sub>a ! (B ! match A a) ! (A[B ! match A a := A ! (B ! match A a) + 1] ! (B ! match A a)) = match (A[B ! match A a := A ! (B ! match A a) + 1]) (B ! match A a)) \<and> (\<not> R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! (B ! match A a) \<longrightarrow> invar2 (A[a := A ! a + 1]) B M ai a \<and> P\<^sub>a ! a ! (A[a := A ! a + 1] ! a) = match (A[a := A ! a + 1]) a)
[PROOF STEP]
unfolding invar2_def match_def
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>invAM A ({<ai + 1} - {a}) \<and> ((ran (\<alpha> B M) = {<ai + 1} - {a} \<and> (\<forall>b a. \<alpha> B M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A ! a) = b)) \<and> length B = n \<and> length M = n) \<and> a \<le> ai \<and> ai < n; M ! b; b = P\<^sub>a ! a ! (A ! a)\<rbrakk> \<Longrightarrow> (R\<^sub>b ! (P\<^sub>a ! (B ! b) ! (A ! (B ! b))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! b) ! (A ! (B ! b))) ! (B ! b) \<longrightarrow> (invAM (A[B ! b := A ! (B ! b) + 1]) ({<ai + 1} - {B ! b}) \<and> ((ran (\<alpha> (B[b := a]) M) = {<ai + 1} - {B ! b} \<and> (\<forall>b a. \<alpha> (B[b := a]) M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A[B ! b := A ! (B ! b) + 1] ! a) = b)) \<and> length (B[b := a]) = n \<and> length M = n) \<and> B ! b \<le> ai \<and> ai < n) \<and> var (A[B ! b := A ! (B ! b) + 1]) {<ai} < var A {<ai}) \<and> (\<not> R\<^sub>b ! (P\<^sub>a ! (B ! b) ! (A ! (B ! b))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! b) ! (A ! (B ! b))) ! (B ! b) \<longrightarrow> (invAM (A[a := A ! a + 1]) ({<ai + 1} - {a}) \<and> ((ran (\<alpha> B M) = {<ai + 1} - {a} \<and> (\<forall>b a. \<alpha> B M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A[a := A ! a + 1] ! a) = b)) \<and> length B = n \<and> length M = n) \<and> a \<le> ai \<and> ai < n) \<and> var (A[a := A ! a + 1]) {<ai} < var A {<ai})
goal (1 subgoal):
1. \<lbrakk>(invAM A ({<ai + 1} - {a}) \<and> ((ran (\<alpha> B M) = {<ai + 1} - {a} \<and> (\<forall>b a. \<alpha> B M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A ! a) = b)) \<and> length B = n \<and> length M = n) \<and> a \<le> ai \<and> ai < n) \<and> b = P\<^sub>a ! a ! (A ! a); M ! (P\<^sub>a ! a ! (A ! a))\<rbrakk> \<Longrightarrow> (R\<^sub>b ! (P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A ! (B ! (P\<^sub>a ! a ! (A ! a))))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A ! (B ! (P\<^sub>a ! a ! (A ! a))))) ! (B ! (P\<^sub>a ! a ! (A ! a))) \<longrightarrow> (invAM (A[B ! (P\<^sub>a ! a ! (A ! a)) := A ! (B ! (P\<^sub>a ! a ! (A ! a))) + 1]) ({<ai + 1} - {B ! (P\<^sub>a ! a ! (A ! a))}) \<and> ((ran (\<alpha> (B[P\<^sub>a ! a ! (A ! a) := a]) M) = {<ai + 1} - {B ! (P\<^sub>a ! a ! (A ! a))} \<and> (\<forall>b a. \<alpha> (B[P\<^sub>a ! a ! (A ! a) := a]) M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A[B ! (P\<^sub>a ! a ! (A ! a)) := A ! (B ! (P\<^sub>a ! a ! (A ! a))) + 1] ! a) = b)) \<and> length (B[P\<^sub>a ! a ! (A ! a) := a]) = n \<and> length M = n) \<and> B ! (P\<^sub>a ! a ! (A ! a)) \<le> ai \<and> ai < n) \<and> P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A[B ! (P\<^sub>a ! a ! (A ! a)) := A ! (B ! (P\<^sub>a ! a ! (A ! a))) + 1] ! (B ! (P\<^sub>a ! a ! (A ! a)))) = P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A[B ! (P\<^sub>a ! a ! (A ! a)) := A ! (B ! (P\<^sub>a ! a ! (A ! a))) + 1] ! (B ! (P\<^sub>a ! a ! (A ! a))))) \<and> (\<not> R\<^sub>b ! (P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A ! (B ! (P\<^sub>a ! a ! (A ! a))))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A ! (B ! (P\<^sub>a ! a ! (A ! a))))) ! (B ! (P\<^sub>a ! a ! (A ! a))) \<longrightarrow> (invAM (A[a := A ! a + 1]) ({<ai + 1} - {a}) \<and> ((ran (\<alpha> B M) = {<ai + 1} - {a} \<and> (\<forall>b a. \<alpha> B M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A[a := A ! a + 1] ! a) = b)) \<and> length B = n \<and> length M = n) \<and> a \<le> ai \<and> ai < n) \<and> P\<^sub>a ! a ! (A[a := A ! a + 1] ! a) = P\<^sub>a ! a ! (A[a := A ! a + 1] ! a))
[PROOF STEP]
by presburger
[PROOF STATE]
proof (state)
this:
case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
goal (1 subgoal):
1. (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
[PROOF STEP]
case 2
[PROOF STATE]
proof (state)
this:
goal (1 subgoal):
1. (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
[PROOF STEP]
using inv
[PROOF STATE]
proof (prove)
using this:
case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
case s of (A, B, a, x) \<Rightarrow> M ! x
goal (1 subgoal):
1. (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
[PROOF STEP]
apply(simp only: s prod.case Let_def in_measure split: if_split)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>invar2 A B M ai a \<and> b = match A a; M ! match A a\<rbrakk> \<Longrightarrow> (R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! (B ! match A a) \<longrightarrow> var (A[B ! match A a := A ! (B ! match A a) + 1]) {<ai} < var A {<ai}) \<and> (\<not> R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! (B ! match A a) \<longrightarrow> var (A[a := A ! a + 1]) {<ai} < var A {<ai})
[PROOF STEP]
using inner_pres[OF R _ _ refl refl refl refl refl, of A B M ai a b]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>invar2 A B M ai a; M ! b; b = match A a\<rbrakk> \<Longrightarrow> (R\<^sub>b ! match A (B ! b) ! a < R\<^sub>b ! match A (B ! b) ! (B ! b) \<longrightarrow> invar2 (A[B ! b := A ! (B ! b) + 1]) (B[b := a]) M ai (B ! b) \<and> var (A[B ! b := A ! (B ! b) + 1]) {<ai} < var A {<ai}) \<and> (\<not> R\<^sub>b ! match A (B ! b) ! a < R\<^sub>b ! match A (B ! b) ! (B ! b) \<longrightarrow> invar2 (A[a := A ! a + 1]) B M ai a \<and> var (A[a := A ! a + 1]) {<ai} < var A {<ai})
goal (1 subgoal):
1. \<lbrakk>invar2 A B M ai a \<and> b = match A a; M ! match A a\<rbrakk> \<Longrightarrow> (R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! (B ! match A a) \<longrightarrow> var (A[B ! match A a := A ! (B ! match A a) + 1]) {<ai} < var A {<ai}) \<and> (\<not> R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! match A a) ! (A ! (B ! match A a))) ! (B ! match A a) \<longrightarrow> var (A[a := A ! a + 1]) {<ai} < var A {<ai})
[PROOF STEP]
unfolding invar2_def match_def
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>invAM A ({<ai + 1} - {a}) \<and> ((ran (\<alpha> B M) = {<ai + 1} - {a} \<and> (\<forall>b a. \<alpha> B M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A ! a) = b)) \<and> length B = n \<and> length M = n) \<and> a \<le> ai \<and> ai < n; M ! b; b = P\<^sub>a ! a ! (A ! a)\<rbrakk> \<Longrightarrow> (R\<^sub>b ! (P\<^sub>a ! (B ! b) ! (A ! (B ! b))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! b) ! (A ! (B ! b))) ! (B ! b) \<longrightarrow> (invAM (A[B ! b := A ! (B ! b) + 1]) ({<ai + 1} - {B ! b}) \<and> ((ran (\<alpha> (B[b := a]) M) = {<ai + 1} - {B ! b} \<and> (\<forall>b a. \<alpha> (B[b := a]) M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A[B ! b := A ! (B ! b) + 1] ! a) = b)) \<and> length (B[b := a]) = n \<and> length M = n) \<and> B ! b \<le> ai \<and> ai < n) \<and> var (A[B ! b := A ! (B ! b) + 1]) {<ai} < var A {<ai}) \<and> (\<not> R\<^sub>b ! (P\<^sub>a ! (B ! b) ! (A ! (B ! b))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! b) ! (A ! (B ! b))) ! (B ! b) \<longrightarrow> (invAM (A[a := A ! a + 1]) ({<ai + 1} - {a}) \<and> ((ran (\<alpha> B M) = {<ai + 1} - {a} \<and> (\<forall>b a. \<alpha> B M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A[a := A ! a + 1] ! a) = b)) \<and> length B = n \<and> length M = n) \<and> a \<le> ai \<and> ai < n) \<and> var (A[a := A ! a + 1]) {<ai} < var A {<ai})
goal (1 subgoal):
1. \<lbrakk>(invAM A ({<ai + 1} - {a}) \<and> ((ran (\<alpha> B M) = {<ai + 1} - {a} \<and> (\<forall>b a. \<alpha> B M b = Some a \<longrightarrow> P\<^sub>a ! a ! (A ! a) = b)) \<and> length B = n \<and> length M = n) \<and> a \<le> ai \<and> ai < n) \<and> b = P\<^sub>a ! a ! (A ! a); M ! (P\<^sub>a ! a ! (A ! a))\<rbrakk> \<Longrightarrow> (R\<^sub>b ! (P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A ! (B ! (P\<^sub>a ! a ! (A ! a))))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A ! (B ! (P\<^sub>a ! a ! (A ! a))))) ! (B ! (P\<^sub>a ! a ! (A ! a))) \<longrightarrow> var (A[B ! (P\<^sub>a ! a ! (A ! a)) := A ! (B ! (P\<^sub>a ! a ! (A ! a))) + 1]) {<ai} < var A {<ai}) \<and> (\<not> R\<^sub>b ! (P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A ! (B ! (P\<^sub>a ! a ! (A ! a))))) ! a < R\<^sub>b ! (P\<^sub>a ! (B ! (P\<^sub>a ! a ! (A ! a))) ! (A ! (B ! (P\<^sub>a ! a ! (A ! a))))) ! (B ! (P\<^sub>a ! a ! (A ! a))) \<longrightarrow> var (A[a := A ! a + 1]) {<ai} < var A {<ai})
[PROOF STEP]
by presburger
[PROOF STATE]
proof (state)
this:
(case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
(case case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)) of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a) \<and> (case s of (A, B, a, b) \<Rightarrow> let a' = B ! b; r = R\<^sub>b ! (P\<^sub>a ! a' ! (A ! a')); (A, B, a) = if r ! a < r ! a' then (A[a' := A ! a' + 1], B[b := a], a') else (A[a := A ! a + 1], B, a) in (A, B, a, P\<^sub>a ! a ! (A ! a)), s) \<in> measure (\<lambda>(A, B, a, b). var A {<ai})
goal (2 subgoals):
1. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
2. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
2. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
case 3
[PROOF STATE]
proof (state)
this:
case s_ of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a
\<not> (case s_ of (A, B, a, x) \<Rightarrow> M ! x)
goal (2 subgoals):
1. \<And>s. \<lbrakk>case s of (A, B, a, b) \<Rightarrow> invar2 A B M ai a \<and> b = match A a; \<not> (case s of (A, B, a, x) \<Rightarrow> M ! x)\<rbrakk> \<Longrightarrow> s = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
2. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. s_ = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
[PROOF STEP]
proof (rule, goal_cases)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. s_ = (A', B', a', b') \<Longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
[PROOF STEP]
case 1
[PROOF STATE]
proof (state)
this:
s_ = (A', B', a', b')
goal (1 subgoal):
1. s_ = (A', B', a', b') \<Longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
[PROOF STEP]
by(rule inner_to_outer[OF 3[unfolded 1 prod.case]])
[PROOF STATE]
proof (state)
this:
invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
s_ = (A', B', a', b') \<longrightarrow> invar1 A' (B'[b' := a']) (M[b' := True]) (ai + 1)
goal (1 subgoal):
1. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
case 4
[PROOF STATE]
proof (state)
this:
goal (1 subgoal):
1. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
Wellfounded.wf (measure (\<lambda>(A, B, a, b). var A {<ai}))
goal:
No subgoals!
[PROOF STEP]
qed
|
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9.
Copyright (c) 2021, Oracle and/or its affiliates.
Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl
-}
open import LibraBFT.Base.Types
import LibraBFT.Impl.Consensus.BlockStorage.BlockTree as BlockTree
import LibraBFT.Impl.Consensus.ConsensusTypes.ExecutedBlock as ExecutedBlock
import LibraBFT.Impl.Consensus.ConsensusTypes.Vote as Vote
import LibraBFT.Impl.Consensus.PersistentLivenessStorage as PersistentLivenessStorage
import LibraBFT.Impl.Consensus.StateComputerByteString as SCBS
open import LibraBFT.Impl.OBM.Logging.Logging
open import LibraBFT.Impl.OBM.Rust.RustTypes
open import LibraBFT.ImplShared.Base.Types
open import LibraBFT.ImplShared.Consensus.Types
open import LibraBFT.ImplShared.Util.Crypto
open import LibraBFT.ImplShared.Util.Dijkstra.All
open import Optics.All
open import Util.ByteString
open import Util.Hash
open import Util.KVMap as Map
open import Util.PKCS
open import Util.Prelude
------------------------------------------------------------------------------
open import Data.String as String using (String)
module LibraBFT.Impl.Consensus.BlockStorage.BlockStore where
------------------------------------------------------------------------------
build
: RootInfo → RootMetadata
→ List Block → List QuorumCert → Maybe TimeoutCertificate
→ StateComputer → PersistentLivenessStorage → Usize
→ Either ErrLog BlockStore
executeAndInsertBlockE : BlockStore → Block → Either ErrLog (BlockStore × ExecutedBlock)
executeBlockE
: BlockStore → Block
→ Either ErrLog ExecutedBlock
executeBlockE₀
: BlockStore → Block
→ EitherD ErrLog ExecutedBlock
getBlock : HashValue → BlockStore → Maybe ExecutedBlock
insertSingleQuorumCertE
: BlockStore → QuorumCert
→ Either ErrLog (BlockStore × List InfoLog)
pathFromRoot
: HashValue → BlockStore
→ Either ErrLog (List ExecutedBlock)
pathFromRootM
: HashValue
→ LBFT (Either ErrLog (List ExecutedBlock))
------------------------------------------------------------------------------
new
: PersistentLivenessStorage → RecoveryData → StateComputer → Usize
→ Either ErrLog BlockStore
new storage initialData stateComputer maxPrunedBlocksInMem =
build (initialData ^∙ rdRoot)
(initialData ^∙ rdRootMetadata)
(initialData ^∙ rdBlocks)
(initialData ^∙ rdQuorumCerts)
(initialData ^∙ rdHighestTimeoutCertificate)
stateComputer
storage
maxPrunedBlocksInMem
abstract
-- TODO: convert new to EitherD
new-ed-abs : PersistentLivenessStorage → RecoveryData → StateComputer → Usize
→ EitherD ErrLog BlockStore
new-ed-abs storage initialData stateComputer maxPrunedBlocksInMem = fromEither $
new storage initialData stateComputer maxPrunedBlocksInMem
new-e-abs : PersistentLivenessStorage → RecoveryData → StateComputer → Usize
→ Either ErrLog BlockStore
new-e-abs = new
new-e-abs-≡ : new-e-abs ≡ new
new-e-abs-≡ = refl
build root _rootRootMetadata blocks quorumCerts highestTimeoutCert
stateComputer storage maxPrunedBlocksInMem = do
let (RootInfo∙new rootBlock rootQc rootLi) = root
{- LBFT-OBM-DIFF : OBM does not implement RootMetadata
assert_eq!(
root_qc.certified_block().version(),
root_metadata.version())
assert_eq!(
root_qc.certified_block().executed_state_id(),
root_metadata.accu_hash)
-}
executedRootBlock = ExecutedBlock∙new
rootBlock
(StateComputeResult∙new (stateComputer ^∙ scObmVersion) nothing)
tree ← BlockTree.new executedRootBlock rootQc rootLi maxPrunedBlocksInMem highestTimeoutCert
bs1 ← (foldM) (λ bs b → fst <$> executeAndInsertBlockE bs b)
(BlockStore∙new tree stateComputer storage)
blocks
(foldM) go bs1 quorumCerts
where
go : BlockStore → QuorumCert
→ Either ErrLog BlockStore
go bs qc = case insertSingleQuorumCertE bs qc of λ where
(Left e) → Left e
(Right (bs' , _info)) → Right bs'
------------------------------------------------------------------------------
commitM
: LedgerInfoWithSignatures
→ LBFT (Either ErrLog Unit)
commitM finalityProof = do
bs ← use lBlockStore
maybeSD (bs ^∙ bsRoot) (bail fakeErr) $ λ bsr → do
let blockIdToCommit = finalityProof ^∙ liwsLedgerInfo ∙ liConsensusBlockId
case getBlock blockIdToCommit bs of λ where
nothing →
bail (ErrCBlockNotFound blockIdToCommit)
(just blockToCommit) →
ifD‖ blockToCommit ^∙ ebRound ≤?ℕ bsr ^∙ ebRound ≔
bail fakeErr -- "commit block round lower than root"
‖ otherwise≔ (pathFromRootM blockIdToCommit >>= λ where
(Left e) → bail e
(Right r) → continue blockToCommit r)
where
continue : ExecutedBlock → List ExecutedBlock → LBFT (Either ErrLog Unit)
continue blockToCommit blocksToCommit = do
-- NOTE: Haskell tells the "StateComputer" to commit 'blocksToCommit'.
-- TODO-1: The StateComputer might indicate an epoch change.
-- NO NEED FOR PRUNING: pruneTreeM blockToCommit
--
-- THIS IS WHERE COMMIT IS COMPLETED.
-- To connect to the proof's correctness condition, it will be necessary to
-- send a CommitMsg, which will carry evidence of the CommitRule
-- needed to invoke correctness conditions like ConcCommitsDoNotConflict*.
-- The details of this connection yet have not been settled yet.
-- TODO-1: Once the details are determined, then make the connection.
ok unit
------------------------------------------------------------------------------
rebuildM : RootInfo → RootMetadata → List Block → List QuorumCert → LBFT (Either ErrLog Unit)
rebuildM root rootMetadata blocks quorumCerts = do
-- logEE lEC (here []) $ do
self0 ← use lBlockStore
case build
root rootMetadata blocks quorumCerts
(self0 ^∙ bsHighestTimeoutCert)
(self0 ^∙ bsStateComputer)
(self0 ^∙ bsStorage)
(self0 ^∙ bsInner ∙ btMaxPrunedBlocksInMem) of λ where
(Left e) → bail e
(Right (BlockStore∙new inner _ _)) → do
toRemove ← BlockTree.getAllBlockIdM
PersistentLivenessStorage.pruneTreeM toRemove ∙?∙ λ _ → do
lRoundManager ∙ rmBlockStore ∙ bsInner ∙= inner
self1 ← use lBlockStore
maybeS (self1 ^∙ bsRoot) (bail fakeErr {-bsRootErrL here-}) $ λ bsr → do
ifD self1 ^∙ bsHighestCommitCert ∙ qcCommitInfo ∙ biRound >? bsr ^∙ ebRound
then
(commitM (self1 ^∙ bsHighestCommitCert ∙ qcLedgerInfo) ∙^∙
withErrCtx (here' ("commitM failed" ∷ [])) ∙?∙ λ _ →
ok unit)
else ok unit
where
here' : List String.String → List String.String
here' t =
"BlockStore" ∷ "rebuildM" ∷ t
-- lsRI root : lsRMD rootMetadata : lsBs blocks : lsQCs quorumCerts : t
------------------------------------------------------------------------------
executeAndInsertBlockM : Block → LBFT (Either ErrLog ExecutedBlock)
executeAndInsertBlockM b = do
bs ← use lBlockStore
case⊎D executeAndInsertBlockE bs b of λ where
(Left e) → bail e
(Right (bs' , eb)) → do
lBlockStore ∙= bs'
ok eb
module executeAndInsertBlockE (bs0 : BlockStore) (block : Block) where
VariantFor : ∀ {ℓ} EL → EL-func {ℓ} EL
VariantFor EL = EL ErrLog (BlockStore × ExecutedBlock)
continue step₁ : VariantFor EitherD
continue = step₁
step₂ : ExecutedBlock → VariantFor EitherD
step₃ : ExecutedBlock → VariantFor EitherD
step₄ : ExecutedBlock → VariantFor EitherD
step₀ =
-- NOTE: if the hash is already in our blockstore, then HASH-COLLISION
-- because we have already confirmed the new block is for the expected round
-- and if there is already a block for that round then our expected round
-- should be higher.
maybeSD (getBlock (block ^∙ bId) bs0) continue (pure ∘ (bs0 ,_))
here' : List String.String → List String.String
here' t = "BlockStore" ∷ "executeAndInsertBlockE" {-∷ lsB block-} ∷ t
step₁ =
maybeSD (bs0 ^∙ bsRoot) (LeftD fakeErr) λ bsr →
let btRound = bsr ^∙ ebRound in
ifD btRound ≥?ℕ block ^∙ bRound
then LeftD fakeErr -- block with old round
else step₂ bsr
step₂ _ = do
eb ← case⊎D executeBlockE bs0 block of λ where
(Right res) → RightD res
-- OBM-LBFT-DIFF : This is never thrown in OBM.
-- It is thrown by StateComputer in Rust (but not in OBM).
(Left (ErrECCBlockNotFound parentBlockId)) → do
eitherSD (pathFromRoot parentBlockId bs0) LeftD λ blocksToReexecute →
-- OBM-LBFT-DIFF : OBM StateComputer does NOT have state.
-- If it ever does have state then the following 'forM' will
-- need to change to some sort of 'fold' because 'executeBlockE'
-- would change the state, so the state passed to 'executeBlockE'
-- would no longer be 'bs0'.
case⊎D (forM) blocksToReexecute (executeBlockE bs0 ∘ (_^∙ ebBlock)) of λ where
(Left e) → LeftD e
(Right _) → executeBlockE₀ bs0 block
(Left err) → LeftD err
step₃ eb
step₃ eb = do
bs1 ← withErrCtxD'
(here' [])
-- TODO-1 : use inspect qualified so Agda List singleton can be in scope.
(PersistentLivenessStorage.saveTreeE bs0 (eb ^∙ ebBlock ∷ []) [])
step₄ eb
step₄ eb = do
(bt' , eb') ← BlockTree.insertBlockE eb (bs0 ^∙ bsInner)
pure ((bs0 & bsInner ∙~ bt') , eb')
E : VariantFor Either
E = toEither step₀
D : VariantFor EitherD
D = fromEither E
executeAndInsertBlockE = executeAndInsertBlockE.E
module executeBlockE (bs : BlockStore) (block : Block) where
step₀ = do
case SCBS.compute (bs ^∙ bsStateComputer) block (block ^∙ bParentId) of λ where
(Left e) → Left fakeErr -- (here' e)
(Right stateComputeResult) →
pure (ExecutedBlock∙new block stateComputeResult)
where
here' : List String → List String
here' t = "BlockStore" ∷ "executeBlockE" {-∷ lsB block-} ∷ t
abstract
executeBlockE = executeBlockE.step₀
executeBlockE₀ bs block = fromEither $ executeBlockE bs block
executeBlockE≡ : ∀ {bs block r} → executeBlockE bs block ≡ r → executeBlockE₀ bs block ≡ fromEither r
executeBlockE≡ refl = refl
------------------------------------------------------------------------------
insertSingleQuorumCertM
: QuorumCert
→ LBFT (Either ErrLog Unit)
insertSingleQuorumCertM qc = do
bs ← use lBlockStore
case insertSingleQuorumCertE bs qc of λ where
(Left e) → bail e
(Right (bs' , info)) → do
forM_ info logInfo
lBlockStore ∙= bs'
ok unit
insertSingleQuorumCertE bs qc =
maybeS (getBlock (qc ^∙ qcCertifiedBlock ∙ biId) bs)
(Left (ErrCBlockNotFound
-- (here ["insert QC without having the block in store first"])
(qc ^∙ qcCertifiedBlock ∙ biId)))
(λ executedBlock →
if ExecutedBlock.blockInfo executedBlock /= qc ^∙ qcCertifiedBlock
then Left fakeErr
-- (ErrL (here [ "QC for block has different BlockInfo than EB"
-- , "QC certified BI", show (qc ^∙ qcCertifiedBlock)
-- , "EB BI", show (ExecutedBlock.blockInfo executedBlock)
-- , "EB", show executedBlock ]))
else (do
bs' ← withErrCtx' (here' [])
(PersistentLivenessStorage.saveTreeE bs [] (qc ∷ []))
(bt , output) ← BlockTree.insertQuorumCertE qc (bs' ^∙ bsInner)
pure ((bs' & bsInner ∙~ bt) , output)))
where
here' : List String.String → List String.String
here' t = "BlockStore" ∷ "insertSingleQuorumCertE" ∷ t
------------------------------------------------------------------------------
insertTimeoutCertificateM : TimeoutCertificate → LBFT (Either ErrLog Unit)
insertTimeoutCertificateM tc = do
curTcRound ← maybe {-(Round-} 0 {-)-} (_^∙ tcRound) <$> use (lBlockStore ∙ bsHighestTimeoutCert)
ifD tc ^∙ tcRound ≤?ℕ curTcRound
then ok unit
else
PersistentLivenessStorage.saveHighestTimeoutCertM tc ∙^∙ withErrCtx ("" ∷ []) ∙?∙ λ _ → do
BlockTree.replaceTimeoutCertM tc
ok unit
------------------------------------------------------------------------------
blockExists : HashValue → BlockStore → Bool
blockExists hv bs = Map.kvm-member hv (bs ^∙ bsInner ∙ btIdToBlock)
getBlock hv bs = btGetBlock hv (bs ^∙ bsInner)
getQuorumCertForBlock : HashValue → BlockStore → Maybe QuorumCert
getQuorumCertForBlock hv bs = Map.lookup hv (bs ^∙ bsInner ∙ btIdToQuorumCert)
pathFromRootM hv = pathFromRoot hv <$> use lBlockStore
pathFromRoot hv bs = BlockTree.pathFromRoot hv (bs ^∙ bsInner)
------------------------------------------------------------------------------
syncInfoM : LBFT SyncInfo
syncInfoM =
SyncInfo∙new <$> use (lBlockStore ∙ bsHighestQuorumCert)
<*> use (lBlockStore ∙ bsHighestCommitCert)
<*> use (lBlockStore ∙ bsHighestTimeoutCert)
abstract
syncInfoM-abs = syncInfoM
syncInfoM-abs-≡ : syncInfoM-abs ≡ syncInfoM
syncInfoM-abs-≡ = refl
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.