text
stringlengths 0
3.34M
|
---|
module Control.EffectAlgebra
import public Control.HigherOrder
import public Control.Effect.Misc
||| Structure that dispatches an effect.
public export
interface Monad m => Algebra sig m | m where
constructor MkAlgebra
alg : (f : Functor ctx)
=> ctx ()
-> Handler ctx n m
-> sig n a
-> m (ctx a)
||| Apply an effect within a monadic context that supports it.
public export
send : Inj eff sig => Algebra sig m => eff m a -> m a
send eff = alg {ctx = id} () id (inj eff)
|
[STATEMENT]
lemma mod_ring_finite_field_ops_int: "mod_ring_gen (finite_field_ops_int p) mod_ring_rel p"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. mod_ring_gen (finite_field_ops_int p) mod_ring_rel p
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. mod_ring_gen (finite_field_ops_int p) mod_ring_rel p
[PROOF STEP]
interpret ring_ops "finite_field_ops_int p" mod_ring_rel
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ring_ops (finite_field_ops_int p) mod_ring_rel
[PROOF STEP]
by (rule ring_finite_field_ops_int)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. mod_ring_gen (finite_field_ops_int p) mod_ring_rel p
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. mod_ring_gen (finite_field_ops_int p) mod_ring_rel p
[PROOF STEP]
by (unfold_locales, rule p,
auto simp: finite_field_ops_int_def p mod_ring_rel_def of_int_of_int_mod_ring)
[PROOF STATE]
proof (state)
this:
mod_ring_gen (finite_field_ops_int p) mod_ring_rel p
goal:
No subgoals!
[PROOF STEP]
qed |
\chapter{Preliminaries}\label{ch:2}
We generally aim to introduce notation on a need-to-know basis.
However, there are some notions that permeate the entirety of this work and
thus can suffer no delay.
% \section{\poo{Renate}}
% \poo{Renate} is a very sweet \poo{being}. I love her very much and I enjoy spending time with her.
% She is nice.
% Very very nice.
% She has nice sweaters and socks.
% And sometimes they match.
% I will give her a \poo{kissy} now.
\section{Propositional logic}\label{sec:2-prop-logic}
We will assume a finite set
$\Atoms$ of \emph{propositional atoms},
intended to represent issues that can be
the subject of reasoning, thought or deliberation.
A \emph{literal $l$} is either an atom $p$,
in which case $l$ is a \emph{positive literal},
or its negation $\lnot p$, in which case $l$ is a \emph{negative literal}.
If $l$ is a positive literal $p$ or a negative literal $\lnot p$,
the \emph{dual $\dual{l}$ of $l$} is $\lnot p$ or $p$, respectively.
The \emph{set $\L$ of propositional formulas} is generated from $\Atoms$
using the usual propositional connectives ($\land$, $\lor$, $\lnot$, $\rightarrow$ and $\leftrightarrow$),
as well as the constants $\bot$ and $\top$.
Propositional formulas in $\L$ will be used to represent either
attitudes with respect to the issues in $\Atoms$
assumed to stem from a single agent $i$
and typically denoted by $\phi$,
or $\phi_{i}$ when we need to be explicit about the agent
supplying the attitude,
or information with respect to these issues,
assumed to stem from some authoritative source
and typically denoted by $\mu$.
We will want to be flexible, to a certain degree,
with respect to what sort of attitude a formula
$\phi$, or $\phi_{i}$, actually represents:
the nominal term will be belief, i.e., conviction about what is the case,
but $\phi$ can also encode opinion about what should be the case,
or what is desired to be the case;
in general, we will take $\phi$ to encode some constraint
on the issues in $\Atoms$ the agent is partial to,
and will be explicit when using it with a more concrete meaning.
An \emph{interpretation $w$}
(alternatively, a \emph{truth-value assignment}, or \emph{outcome})
is a function mapping every atom in $\Atoms$ to either \emph{true} or \emph{false},
and typically denoted by $w$ or $v$.
Since an interpretation $w$ is completely determined
by the set of atoms in $\Atoms$ it makes true,
we will identify $w$ with this set of atoms
and, if there is no danger of ambiguity, display $w$
as a word where the letters are the atoms assigned to true.
The \emph{universe $\U$} is the set of all interpretations
for formulas in $\L$.
The models of a propositional formula $\phi$ are the interpretations that satisfy it,
and we write $[\phi]$ for the set of models of $\phi$.
If $\phi_1$ and $\phi_2$ are propositional formulas,
we say that \emph{$\phi_1$ entails $\phi_2$},
written $\phi_1 \models \phi_2$, if $\mods{\phi_1}\subseteq\mods{\phi_2}$,
and that they are \emph{equivalent}, written $\phi_1 \equiv \phi_2$, if $\mods{\phi_1}= \mods{\phi_2}$.
A propositional formula $\phi$ is \emph{consistent} if $[\phi]\neq\emptyset$
and \emph{refutable} if $[\phi]\neq\U$.
The models of $\bot$ and $\top$ are $[\bot]=\emptyset$ and $[\top]=\U$,
i.e., $\bot$ has no model and $\top$ is satisfied by every interpretation in the universe.
A propositional formula is \emph{complete} if it has exactly one model.
Complete formulas are sometimes denoted by $\dot{\phi}$, with the dot suggesting that
$\dot{\phi}$ has one model.
The sets of consistent, refutable and complete formulas are $\L_\cn$, $\L_\rf$ and $\L_\comp$, respectively.
\begin{xmpl}{Propositional formulas and their semantics}{2-propositional-formulas}
The scenario in Example \ref{ex:1-revision-motivation}
can be modeled by using propositional variables
to represent the issues under contention:
that humans use tools ($a$),
that chimpanzees are part of a different species from humans ($b$)
and that chimpanzees use tools ($c$).
Thus, the set of atoms is $\Atoms=\{a,b,c\}$,
with the universe, i.e., the set of all possible interpretations,
being $\U=\{\emptyset,a,b,c,ab,ac,bc,abc\}$.
One of the prevailing beliefs of the primatology community,
circa $1960$, can be taken to be that
humans were the only species capable of using tools,
which we can approximate here with the implication
that if humans use tools and chimpanzees are different from humans,
then there is no way that chimpanzees can use tools,
represented by the propositional formula
$\phi_1 = (a\land b)\rightarrow\lnot c$
whose set of models is $[\phi_1]=\{\emptyset,a,b,c,ab,ac,bc\}$.
Note that the interpretations where $a$ and $c$ are true and $b$ is false,
i.e., the outcome according to which humans and chimpanzees use tools and
chimpanzees are the same species as humans, is written as $ac$.
It is straightforward to see that $\phi_1$ is both consistent and refutable, but not complete.
To $\phi_1$ we can add the common-sense beliefs that
humans use tools and that they are truly different from humans,
i.e., the formula $\phi_2=a\land b$,
with $[\phi_2]=\{ab, abc\}$,
to get a snapshot of the ensemble of ideas
that Jane Goodall eventually proved wrong.
This ensemble can be represented as the
conjunction of the formulas $\phi_1$ and $\phi_2$,
i.e., the propositional formula
$\phi = \phi_1\land\phi_2 = (a\land b)\land ((a\land b)\rightarrow\lnot c)$.
It holds that $[\phi]=\{ab\}$, and hence $\phi$ is complete.
\end{xmpl}
There are certain transformations we will want
to subject propositional formulas to
in order to set limits for belief change operators:
they include replacing literals with their duals,
changing the order of elements in a tuple and renaming atoms.
These transformations are usually done to the syntax of the formulas,
but they also have effects on the semantic level,
and we must dedicate a few paragraphs to charting out these effects.
Thus, if $\phi$ is a propositional formula,
the \emph{dual $\dual{\phi}$ of $\phi$}
is a formula obtained by replacing
every literal $l$ in $\phi$ with its dual $\dual{l}$.
A similar operation can be defined on the semantic side:
if $w$ is an interpretation, the \emph{dual $\dual{w}$ of $w$}
is the complement of $w$, i.e, $\dual{w} = \Atoms\setminus w$.
If $\W$ is a set of interpretations,
the \emph{dual $\dual{\W}$ of $\W$} is the set of interpretations
containing the duals of the interpretations in $\W$,
i.e., $\dual{\W} = \{\dual{w}\mid w\in\W\}$.
\begin{xmpl}{Duals of formulas and their models}{2-duals}
For the set of atoms $\Atoms=\set{a,b,c}$ and
the propositional formula $\phi_1 = (a\land b)\rightarrow\lnot c$,
then the dual of $\phi_1$ is the formula
$\dual{\phi_1} = (\dual{a}\land\dual{b})\rightarrow\dual{\lnot c} = (\lnot a \land \lnot b)\rightarrow c$.
The set of models of $\phi_1$ is $[\phi_1]=\{\emptyset,a,b,c,ab,ac,bc\}$,
with the duals of interpretation $\emptyset$ and $a$ being
$\dual{\emptyset}=abc$ and
$\dual{a} = bc$.
Note that $\dual{[\phi_1]}=\{abc,bc,ac,ab,c,b,a\}$.
\end{xmpl}
In Example \ref{ex:2-duals} it is the case
that models of the dual $\dual{\phi}$ of $\phi$
are exactly the duals of the models of $\phi$.
Though we do not provide a formal proof,
we mention here that this holds more generally.
\begin{prp}{}{2-duals-commute}
If $\phi$ is a propositional formula, then $[\dual{\phi}] = \dual{[\phi]}$.
\end{prp}
We will use the notion of a dual of a formula $\phi$ in
Chapters \ref{ch:4} and \ref{ch:5}, to encode something like
the point of view diametrically opposed to $\phi$.
Throughout it all, Proposition \ref{prop:2-duals-commute}
will repeatedly come in handy.
If $N=\{1,\dots,n\}$ is a set of integers, a \emph{permutation $\perm$ of $N$}
is the familiar notion of a bijective function $\perm\colon N\rightarrow N$.
If $\perm$ is a permutation of $N=\{1,\dots,n\}$, then \emph{the inverse $\perm^{-1}$ of $\perm$}
is the bijection $\perm^{-1}\colon N\rightarrow N$ such that $\sigma^{-1}(\perm(i))=i$,
for any $i\in N$,
i.e., the permutation that reverses $\perm$.
We will typically use permutations in a context in which
$N=\{1,\dots,n\}$ is a set of agents,
each with their own opinion $\phi_{i}$,
and $(\phi_{i})_{1\le i \le n}$ is the $n$-tuple
that contains their opinions.
In this context, $(\phi_{\perm(i)})_{1\le i \le n}$
is the tuple that swaps the order of the agents around.
On occasion we will also want to swap atoms in $\Atoms$ around:
technically, if atoms in $\Atoms$ are indexed by an integer,
e.g., $a_1$, $a_2$, \dots, this can be achieved simply by a permutation of the indices.
But since, for presentation purposes, we usually denote atoms with distinct letters,
we introduce a special notion, called a renaming of the atoms in $\Atoms$.
Formally, a \emph{renaming $\rnm$ of $\Atoms$} is exactly what we expect it to be,
i.e., a bijective function $\rnm\colon\Atoms\rightarrow\Atoms$.
The \emph{inverse $\rnm^{-1}$ of $\rnm$}
is a permutation such that $\rnm^{-1}(\rnm(p))=p$, for any atom $p\in\Atoms$.
If $\phi$ is a propositional formula, the \emph{renaming $\rnm(\phi)$ of $\phi$}
is a formula $\rnm(\phi)$ whose atoms are replaced according to $\rnm$.
On the semantic side,
if $w$ is an interpretation and $\rnm$ is a renaming of $\Atoms$,
the \emph{renaming $\rnm(w)$ of $w$} is an interpretation obtained
by replacing every atom $p$ in $w$ with $\rnm(p)$.
If $\W$ is a set of interpretations, the \emph{renaming $\rnm(\W)$ of $\W$} is
defined as $\rnm(\W)=\{\rnm(w)\mid\w\in\W\}$,
i.e., the set of interpretations whose elements are the renamed interpretations in $\W$.
\begin{xmpl}{Permutations and renamings}{2-renaming}
For the set $N=\{1,2,3,4\}$ of Academy members
in Example \ref{ex:1-merging-motivation},
consider the permutation $\perm$
according to which $\perm(1)=2$, $\perm(2)=3$, $\perm(3)=4$ and $\perm(4)=1$.
If $(\phi_1,\phi_2,\phi_3,\phi_4)$ is a tuple consisting of their opinions,
then applying the permutation $\perm$ to $N$ results in
$(\phi_2,\phi_3,\phi_4,\phi_1)$
If the set of atoms is $\Atoms=\{a,b,c\}$,
consider a renaming $\rnm$ such that
$\rnm(a)=b$,
$\rnm(b)=c$ and
$\rnm(c)=a$.
If $a$, $b$ and $c$
stand for the directors
Alma Har'el, Bong Joon Ho and C\'eline Sciamma, respectively,
from in Example \ref{ex:1-merging-motivation},
then the first Academy member's opinion
can be represented by the propositional formula
$\phi_1 = a\land b$.
Applying the renaming $\rnm$ gives us that
$\rnm(\phi_1)= (\rnm(a)\land\rnm(b)) = (b\land c)$.
On the semantic side,
we have that $[\phi_1] = \{ab,abc\}$ and
$\rnm([\phi_1]) = \{\rnm(ab), \rnm(abc)\}
= \{bc,abc\}$.
\end{xmpl}
In Example \ref{ex:2-renaming} it holds that the set of models
of a renamed formula $\phi$
is the same as the set of renamed models of $\phi$.
This, also, holds more generally.
\begin{prp}{}{2-renamings-commute}
If $\rnm$ is a renaming of the set $\Atoms$ of atoms and
$\phi$ is a propositional formula,
then $[\rnm(\phi)] = \rnm([\phi])$.
\end{prp}
Another thing we will be eminently interested in is
the relationship between a propositional formula and its semantics,
consisting of sets of interpretations:
primarily, the assurance that we can move freely between the two.
This is done through the notion of proxy formulas.
Thus, if $\W = \{w_1, \dots, w_k\}$ is a set of interpretations,
an \emph{$\L$-proxy $\px_\W$ of $\W$}
is a propositional formula such that $[\px_\W]=\{w_1,\dots,w_k\}$.
At the same time,
an \emph{$\L$-antiproxy $\px_{-\W}$ of $\W$} is a propositional formula
$\px_{-\W}$ such that $[\px_{-\W}]=\U\setminus\{w_1,\dots,w_k\}$.
We will want to refer to proxies and antiproxies through various shorthands.
Thus, if there is no danger of ambiguity, we write
$\px_{w_1,\dots,w_k}$, or even more simply, $\px_{1,\dots,k}$,
and $\px_{-w_1,\dots,-w_k}$, or $\px_{-1,\dots,-k}$,
instead of $\px_\W$ and $\px_{-\W}$, respectively.
Intuitively, an $\L$-proxy of a set $\W$ of interpretations
is a propositional formula that encodes, possibly in a compact way,
all the outcomes in $\W$,
while an $\L$-antiproxy is a propositional formula that
encodes the complement of $\W$.
\begin{xmpl}{Proxies and antiproxies}{2-propositional-proxy}
If $\Atoms=\{a,b\}$ is the set of atoms,
an $\L$-proxy of the set of interpretations $\W=\{\emptyset,ab\}$ is the
disjunctive normal form (DNF) formula
$\phi_1 = (\lnot a\land\lnot b)\lor( a \land b)$.
Note, $\phi_1$ is not the only $\L$-proxy of $a$ and $b$;
$\phi_2=a\leftrightarrow b$ works just as well.
An $\L$-antiproxy of $\W$ is a formula whose set of models is
$\U\setminus\W = \{a,b\}$,
examples of which are $\phi_3 = (a\land\lnot b)\lor(\lnot a\land b)$ or $\phi_4 = (a\leftrightarrow\lnot b)$.
\end{xmpl}
As Example \ref{ex:2-propositional-proxy} makes clear,
$\L$-proxies (and $\L$-antiproxies)
of sets of interpretations always exist (e.g., as DNF formulas),
but are not necessarily unique. For our purposes, existence
is much more important than uniqueness.
Since we will typically try to abstract away as much as possible from the syntax
of formulas, non-uniqueness of a proxy formula will usually not be a factor
in the results to follow.
In a multi-agent scenario we assume a set $N=\{1,\dots,n\}$ of $n$ agents.
An \emph{$\L$-profile $\P$} (alternatively, a \emph{propositional profile $\P$})
is an $n$-tuple $\P=(\phi_1,\dots,\phi_n)$ of propositional formulas,
also written as $\P=(\phi_i)_{1\le i \le n}$,
where each formula $\phi_i$ is assumed to correspond to an agent $i$.
The set of all propositional profiles is $\L^n$.
As for the single-agent case, we want to be liberal with respect
to the meaning assigned to $\phi_i$:
it can represent agent $i$'s belief, preference, judgments, goals or knowledge.
The \emph{models $[\P]$ of a propositional profile $\P=(\phi_1,\dots,\phi_n)$}
are the interpretations satisfying all
formulas in $\P$, i.e., $[\P]=\bigcap_{i=1}^n[\phi_i]$.
As for a propositional formula, a propositional profile $\P$ is \emph{consistent}
% and \emph{refutable}
if $[\P]\neq\emptyset$.
% and $[\P]\neq\U$, respectively.
A propositional profile is \emph{complete}
if every formula in it is complete.
The sets of consistent and complete profiles are $\L^n_\cn$ and $\L^n_\comp$, respectively.
If $\P_1=(\phi_{i})_{1\le i \le n}$ and $\P_2=(\phi_{i})_{n+1\le i \le p}$ are profiles,
$\append{\P_1}{\P_2}$ is the profile $\P_1+\P_2=(\phi_i)_{1\le i\le p}$
obtained by appending $\P_2$ to $\P_1$.
If $\phi$ is a formula and there is no danger of ambiguity,
we write $\append{\P}{\phi}$ instead of $\append{\P}{(\phi)}$.
Two profiles $\P_1$ and $\P_2$ are \emph{equivalent}
if there exists a bijection $f\colon\P_1\rightarrow\P_2$ such that,
for any $\phi_i\in\P_1$, it holds that $\phi_i\equiv f(\phi_i)$.
\begin{xmpl}{Propositional profiles}{propositional-profile}
The scenario in Example \ref{ex:1-merging-motivation} can be modeled
by using propositional variables to stand for the best director candidates:
Alma Har'el ($a$),
Bong Joon Ho ($b$)
and
C\'eline Sciamma ($c$).
The opinions of the four Academy members can be represented
by four propositional formulas $\phi_1$, $\phi_2$, $\phi_3$ and $\phi_4$,
with
$\phi_1 = a\land b$,
$\phi_2 = a\land (b\lor c)$,
$\phi_3 = \lnot a\land b\land \lnot c$,
$\phi_4 = \lnot a \land \lnot b \land c$.
The profile consisting of the (opinions of) the first three Academy members
is $\P = (\phi_1,\phi_2,\phi_3)$.
If we append the fourth member, the profile is
$\append{\P}{\phi_4} = (\phi_1,\phi_2,\phi_3, \phi_4)$.
\end{xmpl}
% \section{Fragments}\label{sec:1-fragments}
% At its most general, a fragment $\L_\star$ of propositional logic is a set $\L_\star\subseteq\L$ of propositional formulas.
% But the fragment we will be mainly interested in is instance of a broader class of fragments,
% that can be characterized via a semantical property of their semantics. To that end, we need to introduce
% the notion of a closure operator.
% A \emph{closure operator $\cl$} is a mapping $\cl\colon 2^\U\rightarrow 2^\U$
% that satisfies, for any sets of interpretations $\W$, $\W_1$ and $\W_2$,
% the conditions $\oocl{1-3}$ below:
% \begin{itemize}[leftmargin=3em]
% \item[($\oocl1$)] $\cl(\emptyset)=\emptyset$.
% \item[($\oocl2$)] If $|\W|=1$, then $\cl(\W)=\W$.
% \item[($\oocl3$)] If $\W_1\subseteq \W_2$, then $\cl(\W_1)\subseteq\cl(\W_2)$.
% \end{itemize}
% If $\cl_\star$ is a closure operator and $\W$ is a set of interpretations such that $\cl_\star(\W)=\W$,
% we say that $\W$ is $\star$-closed.
% A set $\L_\star\subseteq\L$ of propositional formulas is a
% \emph{closed fragment of propositional logic} if there exists a closure-operator $\cl_\star$ such that,
% for any formulas $\phi$, $\phi_1$ and $\phi_2$ in $\L_\star$ and set $\W$ of interpretations,
% properties $\oofr{1-3}$ below are satisfied:
% \begin{itemize}
% \item[($\oofr1$)] $\cl_\star([\phi]) = [\phi]$.
% \item[($\oofr2$)] If $\cl_\star(\W)=\W$, then there exists $\phi\in\L_\star$ with $[\phi]=\W$;
% \item[($\oofr3$)] $\phi_1\land\phi_2\in\L_\star$.
% \end{itemize}
% Property $\oofr1$ says that the set of models of any formula $\phi$ in $\L_\star$ is closed under the
% operator $\cl_\star$.
% Property $\oofr2$ says that any $\star$-closed set of interpretations is represented in $\L_\star$
% by some formula $\phi$.
% Property $\oofr3$ says that $\L_\star$ is closed under conjunction.
% Given a closed fragment $\L_\star$ and interpretations $w_1$,\dots,$w_k$,
% an \emph{$\L_\star$-proxy of $w_1$, \dots, $w_k$}
% is a formula $\px^\star_{w_1,\dots,w_k}$ such that
% $[\px^\star_{w_1,\dots,w_k}]=\cl_\horn(\{w_1,\dots,w_k\})$.
% If there is no danger of ambiguity we promptly drop the superscript and write simply $\px_{1,\dots,k}$.
% Note that standard propositional logic $\L$ is a closed fragment (of itself),
% characterized by the identity closure operator $\mathrm{id}({\W})=\W$.
% This allows us to see that the notion of an $\L_\star$-proxy is a
% generalization of the notion of an $\L$-proxy.
% Intuitively, the set of interpretations $\{w_1,\dots,w_k\}$ might not be representable in the fragment $\L_\star$,
% but the set $\cl_\star(\{w_1,\dots,w_k\})$ is the `nearest' set that is.
% Many well-known fragments of propositional logic are captured by this notion, but here we will be
% focused mainly on the Horn fragment.
% A clause is a \emph{Horn clause} if it contains at most one positive literal.
% A propositional formula $\phi$ is a \emph{Horn formula} if it is a conjunction of Horn clauses.
% The \emph{Horn fragment $\L_\horn$} is the set of all Horn formulas.
% The Horn fragment $\L_\horn$ is associated to the operator
% $\cl_\horn$, defined as the fixed point of the function:
% $$
% \bigcap\W = \{ \w_1\cap \w_2 \mid \w_1,\w_2\in \W \}.
% $$
% \begin{xmpl}{}{horn-representability}
% For $\Atoms=\{a,b,c\}$, and interpretations $ab$ and $ac$,
% we have that $\W=\{ab,ac\}$ is not $\horn$-closed, since
% the intersection of interpretations $ab$ and $ac$ (i.e., the interpretation $a$)
% is not in $\W$. However, $\cl_\horn(\W)=\W\cup\{a\}$ is $\horn$-representable,
% with the formula $\phi=(a\land b)\rightarrow\bot$ as a $\horn$-proxy.
% \end{xmpl}
\section{Preferences: preorders, partial and total}\label{sec:2-preferences}
% If $Y$ is a set,
% a binary relation $\le$ on $Y$ is a set $\le\subseteq Y\times Y$,
% i.e., a set of pairs of elements from $Y$.
We will typically use binary relations $\le$ on a set $X$ of alternatives
to encode some kind of preference
(or priority, or plausibility) relation over the elements of $X$,
with
$\le$ being typically referred to as a \emph{preference relation on $X$}
and $x\le x'$ to be read as saying that
\emph{$x$ is at least as good (or important, or plausible) as $x'$ with respect to $\le$}.
If $\le$ is a preference relation on $X$
and $x$ and $x'$ are two alternatives in $X$, then
\emph{$x$ is strictly better than $x'$ with respect to $\le$},
written $x<x'$, if $x\le x'$ and $x'\not\le x$;
\emph{$x$ and $x'$ are indifferent with respect to $\le$},
written $x\approx x'$, if $x\approx x'$ and $x'\approx x$;
finally, \emph{$x$ and $x'$ are incomparable with respect to $\le$}
if $x\not\le x'$ and $x'\not\le x$.
Intuitively, if two alternatives $x$ and $x'$ are indifferent with respect
to a preference order $\le$, this is like saying that there is
nothing to set them apart, and they are equally good.
If $x$ and $x'$ are incomparable with respect to $\le$, this may be
because it is not known how $x$ and $x'$ fare
with respect to each other, or because, for whatever reason,
there is simply no fact of the matter either way.
If $\le$ is a preference order on $X$,
then the \emph{transitive closure $\le^+$ of $\le$} is defined,
for any alternatives $x$ and $x'$ in $X$, as:
\begin{align*}
x\le^+ x' &~\text{if there exist}~x_1,\dots,x_k~\text{in}~X~\text{such that}~x \le x_1 \le\dots\le x_k\le x'.
\end{align*}
Clearly, if $x\le x'$, then it also holds that $x\le^+ x'$, since we can just
take $x_1 = x$ and $x_k = x'$.
Thus, $\le^+$ contains all the comparisons in $\le$, together
with the comparisons inferred using an intermediary chain of comparisons.
If $\le$ is a preorder on $X$,
the \emph{$\le$-minimal elements $\min_\le X$}
and \emph{$\le$-maximal elements $\max_\le X$} of $X$
are defined, respectively, as:
\begin{align*}
\min_\le X &\defeq\{x\in X\mid\text{there is no}~x'\in X~\text{such that}~x'<x\},\\
\max_\le X &\defeq\{x\in X\mid\text{there is no}~x'\in X~\text{such that}~x'>x\}.
\end{align*}
As per our convention regarding the meaning of $\le$,
$x$ being $\le$-minimal in $X$ means that
there is no other element in $X$ strictly better than $x$
and, similarly,
$x$ being $\le$-maximal in $X$ means that
there is no other element in $X$ strictly worse than $x$.
In order to function as a preference over the elements of $X$,
a binary relation $\le$ is expected to satisfy,
for any integer $n$
and alternatives $x$, $x_1$, \dots, $x_{n}$ in $X$,
some selection of the following properties:
\begin{description}
\item[($\oop{1}$)] $x \le x$. \hfill(reflexivity)
\item[($\oop{2}$)] If $x_1\le x_2$ and $x_2\le x_3$, then $x_1\le x_3$. \hfill(transitivity)
\item[($\oop{3}$)] If $x_1\neq x_2$,
then $x_1 \le x_{2}$ or $x_{2} \le x_{1}$. \hfill(totality)
\item[($\oop{\SCON}$)] If $x_1\le\dots\le x_n$, then $x_n\not< x_1$ \hfill(Suzumura consistency)
% \item[($\oop{4}$)] If $x_1\le x_2$ and $x_2\le x_{1}$, then $x_{1} = x_{2}$ \hfill(antisymmetry)
% \item[($\oop{5}$)] $x\not\le x$. \hfill(irreflexivity)
\end{description}
If $\le$ is a binary relation on a set $X$ of alternatives,
then $\le$ is a \emph{preorder on $X$} if $\le$ satisfies properties $\oop{1-2}$,
i.e., if $\le$ is reflexive and transitive.
We write $\PRE_X$ for the set of preorders on $X$.
If $\le$ is a preorder on $X$,
then $\le$ is \emph{total} if it also satisfies property $\oop{3}$,
i.e., if any two distinct alternatives in $X$ are the subject of some comparison
in $X$,
and we write $\TPRE_{X}$ for the set of total preorders on $X$.
Note that the transitive $\le^+$ closure of any preference order $\le$
is, by definition, transitive.
\begin{figure}\centering
\begin{tikzpicture}
\node at (0,-0.75){$\le_1$};
\node at (0,0)(1){$x_1$};
\node at (-0.5,1)(2){$x_2$};
\node at (-0.5,2)(3){$x_3$};
\node at (0.5,1.5)(4){$x_4$};
\node at (0,3)(5){$x_5$};
\path[-latex](1)edge(2)(2)edge(3)(3)edge(5)(1)edge(4)(4)edge(5);
\node at (4,-0.75){$\le_1$};
\node at (4,0)(1){$x_1$};
\node at (4,1)(2){$x_2,x_4$};
\node at (4,2)(4){$x_3$};
\node at (4,3)(5){$x_5$};
\path[-latex](1)edge(2)(2)edge(4)(4)edge(5);
\end{tikzpicture}
\caption{
A partial preorder $\le_1$ and a total preorder $\le_2$ on the
set $X=\{x_1,x_2,x_3,x_4,x_5\}$ of alternatives.
An arrow from $x_i$ to $x_j$ means that $x_i$ is strictly better than
$x_j$, such that better alternatives are depicted lower; if $x_i$ and $x_j$
are separated by a comma, that means they are indifferent;
and if $x_i$ and $x_j$ are drawn apart, then they are incomparable.
In the interest of readability, arrows inferred by transitivity
are ommitted: nonetheless, since both $\le_1$ and $\le_2$ are assumed to be preorders,
then they must be understood to be transitive, even when the corresponding
arrows are absent.
}
\label{fig:2-preorders}
\end{figure}
\begin{xmpl}{Preorders}{2-preorders}
Consider a set of alternatives $X=\{x_1,x_2,x_3,x_4,x_5\}$
and twe preorders, $\le_1$ and $\le_2$, on $X$,
depicted in Figure \ref{fig:2-preorders}.
Of these preorders, $\le_1$ is partial and $\le_2$ is total.
We have that $\min_{\le_1}X = \min_{\le_2}X = \{x_1\}$.
However, if we consider the restriction of $\le_1$ and $\le_2$
to the set $X'=\{x_3,x_4,x_5\}$,
then $\min_{\le_1}X' = \{x_3,x_4\}$
and
$\min_{\le_2}X' = \{x_4\}$.
\end{xmpl}
Note that if $\le$ is a total preorder on $X$,
then the $\le$-minimal elements in $X$ end up being the overall best elements in $X$,
i.e., if $x\in\min_\le X$, then $x\le x'$, for any $x'\in X$.
As Example \ref{ex:2-preorders} illustrates,
this does not hold if $\le$ is a partial preorder.
Preorders are a key ingredient in traditional belief change,
and we will make use of both partial and total preorders on interpretations
(i.e., in which the set of alternatives is the universe $\U$)
in Chapters \ref{ch:3}, \ref{ch:4}, \ref{ch:5} and \ref{ch:6}.
A different type of preference order will be used in Chapter \ref{ch:7},
but we defer definitions for those until we need them.
Property $\oop{\SCON}$,
where `$\SCON$' stands for \emph{Suzumura consistency} \cite{Suzumura76,Suzumura83,BossertS10},
says that it is not possible to form a chain of comparisons
that starts with $x_1$ and ends with $x_n$,
in which every alternative is at least as good as the next one,
but the last one, $x_n$ ends up being strictly better than the first one, $x_1$.
A preference order $\le$ on a set of alternatives $X$ is \emph{Suzumura consistent}
if it satisfies property $\oop{\SCON}$.
Suzumura consistency
is a weakening of the transitivity property $\oop{2}$:
clearly, any relation $\le$ that is transitive
is also Suzumura consistent,
i.e., property $\oop{2}$ implies property $\oop{\SCON}$;
the converse, however, does not hold.
\begin{xmpl}{Suzumura consistency does not imply transitivity}{2-scon-not-trans}
For the set of alternatives $X=\{x_1,x_2,x_3\}$,
take a preference order $\le$ such that
$x_1\le x_2$ and $x_2\le x_3$, but $x_1$ and $x_3$ are incomparable.
Clearly, $\le$ is Suzumura consistent but not transitive.
\end{xmpl}
Suzumura consistency is of interest to us
because the rational choice literature has
identified it as one of the safest fallback options
when some preference information is available that
can be pieced together into a preference order $\le$,
but, for whatever reason, $\le$ is not transitive.
Since transitivity is, in general, a desirable property of any
preference order, it would be good if a transitive order
could be constructed on the back of $\le$,
and the obvious suggestion is to replace $\le$ with its
transitive clousre $\le^+$.
However, there are cases in which the transitive closure would
flatten much preference information that we would like to
see preserved, and thus lead to an undesirable result.
To make this more precise, we can bring in the notion of
an ordering extension.
If $X$ is a set of alternatives
and $\le$ and $\le'$ are binary relations on $X$,
then \emph{$\le'$ extends $\le$ on $X$} if, for any alternatives
$x_{1}$ and $x_{2}$ in $X$, the following properties hold:
\begin{description}
\item[($i$)] if $x_1\le x_2$, then $x_1\le' x_2$;
\item[($ii$)] if $x_1 < x_2$, then $x_{1}<' x_{2}$.
\end{description}
Intuitively, $\le'$ extends $\le$ on $X$ if $\le$ contains all the
comparisons in $\le$ and, additionally,
$\le'$ contains all the strict comparisons of $\le$:
presumably, the strict comparisons are hard won pieces of information
that we would not want to lose.
Furtermore, $\le'$ is an \emph{ordering extension of $\le$ on $X$}
if $\le'$ extends $\le$ and $\le'$ satisfies properties $\oop{1-3}$,
i.e., if $\le'$ is a total preorder on $X$ that extends $\le$.
\begin{figure}
\centering
\begin{tikzpicture}
\node at (0,-0.75){$\le$};
\node at (-0.5,0)(1){$x_1$};
\node at (0.5,0)(2){$x_2$};
\node at (0,1)(3){$x_3$};
\node at (0,2)(4){$x_4$};
\path[-latex] (1)edge(2)(2)edge(3)(3)edge(1)(3)edge(4);
\node at (4,-0.75){$\le^+$};
\node at (4,0.5)(1){$x_1,x_2, x_3$};
\node at (4,2)(4){$x_4$};
\path[-latex] (1)edge(4);
\end{tikzpicture}
\caption{
Preference relation $\le$ that does not admit of an
ordering extension: the transitive closure $\le^+$ of $\le$
does not preserve the strict comparisons of $\le$.
}
\label{fig:2-sc}
\end{figure}
\begin{xmpl}{Ordinal extensions}{2-sc}
Note, first, that $\le_2$ in Example \ref{ex:2-preorders} extends $\le_1$
and, what is more, $\le_2$ is an ordering extension of $\le_1$,
since it preserves all the strict comparisons of $\le_1$.
Consider, now, a set of alternatives $X=\{x_1,x_2,x_3,x_4\}$
and the preference relation $\le$ on $X$ depicted
on the left in Figure \ref{fig:2-sc},
where $x_1<x_2<x_3<x_1$,
$x_2\not<x_1$, $x_3\not< x_2$, $x_1\not< x_3$, and
$x_i<x_4$, for $i\in\{1,2,3\}$.
Note that $\le$ is not transitive, and is thus problematic.
However, the transitive closure $\le^+$ of $\le$,
depicted on the right in Figure \ref{fig:2-sc},
is arguably also problematic, as it flattens the
cycle between $x_1$, $x_2$ and $x_3$ and does not preserve
the strict comparisons in $\le$.
The transitive closure $\le^+$ of $\le$, then,
is not an ordering extension of $\le$.
In fact, it is easy to see that $\le$ does not admit an
ordering extension.
Incidentally, $\le$ is not Suzumura consistent either.
\end{xmpl}
The primary question about ordering extensions concerns their existence:
ideally, we would like the preference relation $\le$ we are working with
to be reflexive and transitive, i.e., a preorder, at the least.
But there are situations, and we will encounter
them in Chapters \ref{ch:6},
where these properties cannot be guaranteed,
and a much weaker relation has to be contended
with. The only hope, in this situation,
is to massage $\le$ into a more manageable format:
if $\le$ can be extended, in a meaningful way, to a total preorder,
then it can still fulfil its assigned role
as the basis for a decision procedure.
We would like to know, then, exactly how weak
$\le$ can be such that it can still guide
a rational decision maker in its choices.
The answer turns out to hinge on Suzumura consistency.
Indeed, ensuring that a preference relation $\le$ is Suzumura consistent
turns out to both a sufficient and a necessary condition
for the possibility of extending
the relation to a total preorder.
\begin{thm}{\cite{Suzumura76}}{2-suzumura-consistency}
If $X$ is a (potentially infinite) set of alternatives
and $\le$ is a binary relation on $X$,
then there exists an ordering extension $\le'$ of $\le$ on $X$
if and only if $\le$ is Suzumura consistent.
\end{thm}
Theorem \ref{thm:2-suzumura-consistency} extends an earlier result
that provided only a sufficient condition for the existence
of an ordering extension
\cite{Szpilrajn30},
and applies to both finite and infinite sets of alternatives,
though in this work we will mainly be concerned
with finite sets of alternatives.
\section{Distances and aggregation functions}\label{sec:2-distances}
The primary devices for generating preorders (either total or partial) on interpretations
we make recourse to in this work are a \emph{dissimilarity function $\dd$ between interpretations},
used to quantify the disagreement between two outcomes,
and an \emph{aggregation function $\agg$},
used to boil down vectors $(x_i)_{1\le i\le n}$ of dissimilarity measures to forms
that can be meaningfully compared to each other.
\subsubsection{Distances}
Formally, a dissimilarity function $\dd$ between interpretations is
a function $\dd\colon\U\times\U\rightarrow\mathbb{R}_{\geq 0}$
expected to satisfy, for any interpretations $w$, $w_1$, $w_2$ and $w_3$,
some subset of the following properties:
\begin{description}[leftmargin=3em]
\item[($\ood{1}$)] $\dd(w,w)=0$. \hfill(identity of indiscernibles)
\item[($\ood{2}$)] If $w_1\neq w_2$, then $\dd(w_1,w_2)>0$. \hfill(non-negativity)
\item[($\ood{3}$)] $\dd(w_1,w_2) = \dd(w_2,w_1)$. \hfill(symmetry)
\item[($\ood{4}$)] $\dd(w_1,w_3) \leq \dd(w_1,w_2) + \dd(w_2,w_3)$. \hfill(triangle inequality)
\end{description}
There is some variation within the literature with respect to what is called how,
but in the spirit of standard references \cite{DezaD16}
we will say that a dissimilarity function $\dd$
is a \emph{quasi-distance} if it satisfies properties $\ood{1-2}$,
a \emph{distance} if it satisfies properties $\ood{1-3}$
and a \emph{metric} if it satisfies properties $\ood{1-4}$.
In general, we will require a dissimilarity measure $\dd$ to satisfy at least properties $\ood{1-2}$:
for revision, update and enforcement a quasi-distance will be enough,
whereas for merging we will require $\dd$ to be a distance.
Intuitively, $\dd(w_1,w_2)$ is supposed to measure how different $w_2$ is from $w_1$,
which, in turn, becomes a proxy for how likely (or plausible, or desirable)
$w_2$ is from the point of view of $w_1$.
Consequently, smaller dissimilarity translates, straightforwardly enough, into a higher degree of similarity
and, implicitly, into a higher degree of likelihood (or plausibility, or desirability)
of $w_2$ relative to $w_1$.
Popular choices of distances between interpretations are the \emph{Hamming distance $\dd_\hamming$}
and the \emph{drastic distance $\dd_\drastic$}, defined, for any interpretations $w_1$ and $w_2$, as:
\begin{center}
\begin{tabular}{cc}
$\dd_\hamming(w_1,w_2)=|w_1\setminus w_2|\cup|w_2\setminus w_1|$,~~~~~~ &
$
\dd_\drastic(w_1,w_2)=
\begin{cases}
0,~\text{if}~w_1=w_2,\\
1,~\text{otherwise}.
\end{cases}
$
\end{tabular}
\end{center}
The Hamming distance $\dd_\hamming$ counts the number of atoms that $w_1$ and $w_2$ differ on,
while the drastic distance is much coarser, keeping track only of whether $w_1$ and $w_2$ are different or not.
Both the Hamming and the drastic distances satisfy all properties $\ood{1-4}$, so technically they are metrics,
though for our purposes we will rarely make use of all these properties.
\begin{xmpl}{Hamming and drastic distances}{2-distances}
For the intepretations $ab$ and $ac$, we have that $\dd_{\hamming}(ab,ac)=2$ and $\dd_{\drastic}(ab,ac)=1$.
\end{xmpl}
\subsubsection{Aggregation functions}
We will need a way of talking about distances not just between individual interpretations,
but also between formulas, or sets of interpretations, and interpretations,
and this will involve the use of an
\emph{aggregation function $\agg$},
which for our purposes
is a function $\agg\colon\mathbb{R}^n\rightarrow\mathbb{R}^m$ that,
for integers $m$ and $n$,
maps $n$-tuples $\vec{x} = (x_i)_{1\le i\le n}$ of real numbers
to $m$-tuples $(x'_i)_{1\le i\le m}$ of real numbers.
This definition is a bit of an overkill, as we will only make use of the cases
when $m=1$ and $m=n$.
In the case when $m=1$, the aggregated value $\agg\vec{x}$
is a vector containing only one value,
in which case we write simply $x$ instead of $(x)$.
What this general definition allows us to do is to use
one single method for comparing the various types of aggregated values
we make use of.
This method relies on
the \emph{the lexicographic order $\le_{\lex}$ on $\mathbb{R}^{n}$},
defined for any integer $n$ and $n$-tuples
$\vec{x} = (x_i)_{1\le i\le n}$ and $\vec{y} = (y_i)_{1\le i\le n}$ in $\mathbb{R}^{n}$,
as follows:
\begin{align*}
\vec{x}\le_{\lex} \vec{y}~&\text{if}~x_1\le y_1,~\text{or}\\
&\text{if}~x_1 = y_1~\text{and}~x_2\le y_2,~\text{or}\\
&\dots\\
&\text{if}~x_1 = y_1,~\dots~,x_{n-1} = y_{n-1}~\text{and}~x_n\le y_n.
\end{align*}
Note that when $n=1$, i.e., the aggregated values of $\agg\vec{x}$ and $\agg\vec{y}$
are $\agg\vec{x}=x_1$ and $\agg\vec{y}=y_1$,
for some real numbers $x_1$ and $y_1$,
then comparing $\agg\vec{x}$ and $\agg\vec{y}$
according to $\le_\lex$ reduces to comparing $x_1$ and $y_1$,
i.e., $\agg\vec{x}\le_\lex\agg\vec{y}$ if $x_1\le y_1$.
In this case, we simply write that $\agg\vec{x}\le\agg\vec{y}$
instead of $\agg\vec{x}\le_{\lex}\agg\vec{y}$.
The concrete aggregation functions of immediate interest are the
$\min$, $\max$, $\leximax$, $\leximin$ and $\ssum$ aggregation functions,
defined, for any $n$-tuple $(x_i)_{1\le i \le n}$ and
permutation $\perm$ of $\{1,\dots, n\}$, as follows:
\begin{align*}
\min(x_i)_{1\le i \le n} &= x_i,~\text{where}~x_i\le x_j,~\text{for any}~x_j~\text{in}~\vec{x},\\
\max(x_i)_{1\le i \le n} &= x_i,~\text{where}~x_i\ge x_j,~\text{for any}~x_j~\text{in}~\vec{x},\\
\leximax(x_i)_{1\le i \le n} &= (x_{\perm(i)})_{1\le i \le n},~\text{where}~x_{\perm(1)}\ge\dots\ge x_{\perm(n)},\\
\leximin(x_i)_{1\le i \le n} &= (x_{\perm(i)})_{1\le i \le n},~\text{where}~x_{\perm(1)}\le\dots\le x_{\perm(n)},\\
\ssum(x_i)_{1\le i \le n} &= x_1+\dots + x_n.
\end{align*}
Intuitively, the $\min$, $\max$, $\leximax$, $\leximin$ and $\ssum$ aggregation functions
return, respectively,
the minimal value in $(x_i)_{1\le i \le n}$,
the maximal value in $(x_i)_{1\le i \le n}$,
$(x_i)_{1\le i \le n}$ ordered in descending order,
$(x_i)_{1\le i \le n}$ ordered in ascending order
and the sum of the values in $(x_i)_{1\le i \le n}$.
\begin{xmpl}{Aggregation functions}{2-agg-fcts}
If $\vec{x}=(1,0,2)$ and $\vec{y}=(1,1,1)$,
we have that
$\min(\vec{x})=0$,
$\max(\vec{x})=2$,
$\leximax(\vec{x})=(2,1,0)$,
$\leximin(\vec{y})=(0,1,2)$
and
$\ssum(\vec{x})=3$.
Thus, it holds that
$\min(\vec{x})<\min(\vec{y})$,
$\max(\vec{y})<\max(\vec{y})$,
$\leximax(\vec{y})<_\lex\leximax(\vec{x})$
$\leximin(\vec{x})<_\lex\leximin(\vec{y})$
and
$\ssum(\vec{x})=\ssum(\vec{y})$.
\end{xmpl}
% Note that when all the values in a vector $(x_i)_{1\le i\le n}$
% are either $0$ or $1$, then
The $\min$ aggregation function is a
ubiquitous presence in belief change, and we will
make use of it in all subsequent chapters.
The other aggregation functions will show up
in Chapter \ref{ch:4}, alongside two other
aggregation functions whose definition is deferred
until needed.
Functions $\leximax$, $\leximin$ and $\ssum$
are also used in merging, and will show up
in Chapters \ref{ch:3} and \ref{ch:5}.
In the context of merging,
it is usually useful that the aggregation functions satisfies
a number of desirable properties.
Before we spell them out, we mention that $\vec{0}$ is the tuple whose entries are
uniformly $0$, i.e., $\vec{0} = (0,\dots,0)$.
The properties we are interested in are,
for any $x_1$, \dots, $x_n$ and $x'_n$ in $\mathbb{R}$,
as follows:
\begin{description}
\item[($\ooa{1}$)] $\agg(x_1) = x_1$. \hfill(identity)
\item[($\ooa{2}$)] $\agg(x_1,\dots,x_m) = \vec{0}$ if and only if $x_i = 0$, for all $1\le i\le m$.\hfill(minimality)
\item[($\ooa{3}$)] If $x_i\le x'_i$,
then $\agg(x_1,\dots,x_i,\dots,x_m)\le_{\lex}\agg(x_1,\dots,x'_i,\dots,x_m)$.\hfill(monotonicity)
\end{description}
It is straightforward to see that the $\leximax$, $\leximin$ and $\ssum$ aggregation
functions all satisfy properties $\ooa{1-3}$.
\subsubsection{Putting dissimilarity and aggregation functions together}
The main thing we want to do with dissimilarity and aggregation functions
is to measure the dissimilarity between a formula $\phi$ and an interpretation $w$.
The idea is to define this measure as the
aggregate value of the dissimilarity between each model of $\phi$ and $w$.
For the following definitions we will assume that $\dd$ is a quasi-distance function,
i.e., that it satisfies at least properties $\ood{1-2}$.
If $\dd$ is a quasi-distance function between interpretations,
$w$ is an interpretation,
$\phi$ is a consistent propositional formula,
and $\agg$ is an aggregation function,
then the \emph{$(\dd,\:\agg)$-induced distance $\dd^\agg(\phi,w)$ from $\phi$ to $w$} is defined as:
$$
\dd^\agg(\phi,w)=\agg(\dd(v,w))_{v\in[\phi]}.
$$
If $\phi$ is inconsistent, i.e., $[\phi]=\emptyset$, then we establish, by convention,
that $\dd(\phi,w)=0$, for any interpretation $w$.
Intuitively, the $(\dd,\:\agg)$-induced distance from $\phi$ to $w$
puts a number on how close $w$ is to $\phi$.
This number is obtained by aggregating the distances
between each model of $\phi$ and $w$
using the quasi-distance function $\dd$
and the aggregation function $\agg$.
This will allow us to compare intepretations with respect to each other,
relative to a formula $\phi$, when needed.
\begin{table}\centering
\begin{tabular}{cccccccc}
\toprule
& $a$ & $ac$ & $\dd^{\min}_{\hamming}(\phi,\bullet)$ & $\dd^{\max}_{\hamming}(\phi,\bullet)$ & $\dd^{\leximax}_{\hamming}(\phi,\bullet)$ &
$\dd^{\leximin}_{\hamming}(\phi,\bullet)$ & $\dd^{\ssum}_{\hamming}(\phi,\bullet)$\\
\midrule
$bc$ & $3$ & $2$ & $2$ & $3$ & $(3,2)$ & $(2,3)$ & $5$\\
\bottomrule
\end{tabular}
\caption{
Hamming distances from each model of $\phi$ to $bc$,
together with the aggregated distance $\dd^{\agg}_{\hamming}(\phi,bc)$,
for the aggregation functions introduced so far.
}
\label{tab:2-aggregation}
\end{table}
\begin{xmpl}{Keeping up with the humans}{2-hamming-drastic-distances}
The scenario in Example \ref{ex:1-update-motivation} can be modeled
using propositional variables to represent
the indicators my smarthome keeps track of:
whether the temperature inside the house is above $15\si{\degree}$ C ($a$),
whether the Wi-Fi is on after $21{:}00$ ($b$),
and whether my friend is online after $21{:}00$ ($c$).
Thus, the set of atoms is $\Atoms=\{a,b,c\}$.
My smarthome is set up to make sure that $a$ is true and that $b$ is not,
which we can represent as the propositional formula $\phi=a\land\lnot b$,
with $[\phi]=\{a,ac\}$. Consider, now, the interpretation $bc$.
We have that
$\dd_\hamming(a,bc) = 3$, since $a$ and $bc$ differ with respect to three atoms,
whereas $\dd_\drastic(a,bc)=1$, since $a$ and $bc$ are different.
The vector of Hamming distances from $\phi$ to $bc$ is
$(\dd_\hamming(v,bc))_{v\in[\phi]}=(\dd_{\hamming}(a,bc),\dd_{\hamming}(ac,bc)) = (3,2)$.
Thus, the distances from $\phi$ to $bc$, using the aggregation functions
introduced so far, are as follows:
$\dd_\hamming^\min(\phi,bc) = 2$,
$\dd_\hamming^\max(\phi,bc) = 3$,
$\dd_\hamming^\leximax(\phi,bc) = (3,2)$,
$\dd_\hamming^\leximin(\phi,bc) = (2,3)$
and
$\dd_\hamming^\ssum(\phi,bc) = 5$.
The distances are also depicted in Table \ref{tab:2-aggregation}.
% If we consider now the interpretation $ab$,
% we have that
% $(\dd_\hamming(a,ab),\dd_\hamming(ac,ab))=(1,2)$,
% with
% $\dd_\hamming^\max(\phi,ab) = 2$,
% $\dd_\hamming^\min(\phi,ab) = 1$,
% $\dd_\hamming^\leximin(\phi,ab) = (1,2)$,
% $\dd_\hamming^\leximax(\phi,ab) = (2,1)$
% and
% $\dd_\hamming^\ssum(\phi,ab) = 3$.
% Consequently, it holds that
% $ab<_\phi^{\hamming,\agg} bc$,
% for every aggregation function $\agg\in\{\min,\max,\leximin,\leximax,\ssum\}$.
\end{xmpl}
We will use $(\dd,\:\agg)$-induced distances virtually throughout the entire thesis,
whenever in need of a constructive way of ranking outcomes relative to a particular formula $\phi$.
In Section \ref{sec:3-merging} we will go even further and define the distance
between a profile $\P=(\phi_i)_{1\le i \le n}$ and an interpretation $w$:
aggregation functions will make another appearance there.
\section{Rational choice, individual and social}\label{sec:2-choice-functions}
Rational choice theory is a vast topic, and our purpose
is not to do it full justice here, beyond mentioning
the basic idea at its core. This idea is that
decision-makers have coherent preferences and
choose the best alternatives from the ones available.
The theoretical part that is of immediate relevance to us
concerns the axioms guiding rational choice functions
and the way in which they tie in with preferences.
We will look at the single-agent and multi-agent cases
separately.
For the purposes of this section, we will
assume a finite set $X$ of alternatives.
The set $2^{X}$ is the set of
subsets of $X$, and, for an integer $k$,
$2_k^{X}$ is the set of subsets of $X$ of size $k$.
\subsubsection{Individual choice}
If $X$ is a set of alternatives,
a \emph{choice function $\cf$} is a function
$\cf\colon 2^X\rightarrow 2^X$
that takes as input a subset $M$ of $X$,
called a \emph{choice set}, or \emph{menu},
and returns a subset $\cf(M)$ of $X$,
called the \emph{chosen alternatives}.
Intuitively, the choice function $\cf$ models
the behavior of an agent confronted with a range
of alternatives, from which some are chosen.
The agent can choose whatever it wants from the choice set,
as long as it does so in a way that respects some basic
standards of rationality.
Traditionally, a rational choice function $\cf$ is expected to satisfy,
for any choice sets $M$, $M_1$ and $M_2$,
the following properties:
\begin{description}
\item[($\ooch{1}$)] $\cf(M)\subseteq M$.
\item[($\ooch{2}$)] If $M\neq\emptyset$, then $\cf(M)\neq\emptyset$.
\item[($\ooch{3}$)] If $M_2\subseteq M_1$, then $\cf(M_1)\cap M_2\subseteq \cf(M_2)$.
\item[($\ooch{4}$)] If $M_2\subseteq M_1$ and $x_1,x_2\in \cf(M_2)$,
then $x_1\in \cf(M_1)$ if and only if $x_2\in \cf(M_1)$.
\end{description}
Property $\ooch{1}$ says that the elements chosen from a choice set $M$
should be, as a matter of fact, elements of $M$, and is intended to be
as uncontroversial as it sounds.
Property $\ooch{2}$ says that if the choice set $M$ is non-empty,
i.e., there is something to choose from,
then the choice $\cf(M)$ is non-empty,
i.e., something is chosen.
Property $\ooch{3}$, sometimes called \emph{property $\alpha$} \cite{Sen69,Sen70},
says that if $M_2\subseteq M_1$,
then any elements chosen from $M_1$ that also happen to be in $M_2$
are also chosen in $M_2$.
Intuitively, the best alternatives in the larger set $M_{1}$ are also the best in
the smaller set $M_{2}$,
or, to adapt an example of Amartya Sen himself \cite{Sen70,Sen17}:
the most subscribed to Youtubers in the world ($M_1$) that happen
to be located in Europe ($M_2$)
must also be among the most subscribed to Youtubers in Europe.
Property $\ooch{4}$, sometimes called \emph{property $\beta$} \cite{Sen69,Sen70},
says that if $M_{2} \subseteq M_{1}$, then
if there are alternatives chosen in $M_2$ that are also chosen in $M_{1}$,
then any alternatives chosen in $M_{2}$ are also chosen in $M_{1}$.
Intuitively, if some of the best alternatives in the smaller set $M_{2}$
also happen to be the best alternatives in the larger set $M_{1}$,
then the best alternatives in $M_{2}$ are the among the best alternatives
in $M_{1}$,
or, using the Youtuber example:
if $x_1$ and $x_2$ are the Youtubers in Europe ($M_1$) with the most subscribers
(which implies that $x_1$ and $x_2$ have an equal number of subscribers),
then $x_1$ is among the most subscried to Youtubers in the world ($M_2$)
if and only if $x_2$ is as well.
\begin{xmpl}{Choosing wisely}{2-choice-props}
Consider the choice sets $M_1=\{x_1,x_2,x_3\}$ and $M_2=\{x_1,x_2\}$,
and an agent whose choice function $\cf$ is such that
$\cf(M_1)=\{x_1\}$ and $\cf(M_2)=\{x_2\}$.
Note that $M_2\subseteq M_1$ but $\cf(M_1)\cap M_2=\{x_1\}$ and $\cf(M_2)=\{x_2\}$,
thereby contradicting property $\ooch{3}$.
The agent is behaving strangely:
when the menu consists of $x_1$, $x_2$ and $x_3$ it chooses $x_1$,
signaling that it thinks $x_1$ is strictly better than $x_2$ and $x_2$,
whereas when the menu is only $x_1$ and $x_2$, it chooses $x_2$,
signaling that it thinks $x_2$ is better than $x_1$.
Consider, now, a different agent, whose choice function $\cf'$
is such that $\cf'(M_1)=\{x_1\}$ and $\cf'(M_2)=\{x_1,x_2\}$.
Property $\ooch{3}$ is satisfied, but property $\ooch{4}$ is not,
since $x_2\notin\cf'(M_1)$.
This agent is also behaving strangely:
when choosing among the elements of $M_2$ it signals that $x_1$ and $x_2$
are equally good, but when choosing among the elements of $M_1$
it signals that $x_1$ is strictly better than $x_2$.
\end{xmpl}
We also mention the following property,
expected to hold for any choice sets $M_1$ and $M_{2}$:
\begin{description}
\item[($\ooch{5}$)] If $M_2\subseteq M_1$ and $\cf(M_1)\cap M_2\neq\emptyset$,
then $\cf(M_2)\subseteq \cf(M_1)\cap M_2$.
\end{description}
Property $\ooch{5}$ says that the elements chosen from the smaller set $M_2$
are also chosen from the larger set $M_1$,
or, using the Youtubers example:
if some of the most subscribed to Youtubers in the world ($M_1$)
are located in Europe ($M_2$),
then the most subscribed to Youtubers in Europe must also be among
the most subscribed to Youtubers in the world.
if it happens that some of the chosen elements in $M_1$ are also in $M_2$.
As such, property $\ooch{5}$ is similar to $\ooch{4}$, but it is stronger than it:
$\ooch{5}$ implies $\ooch{4}$, though it is not implied by it.
However, properties $\ooch{3}$ and $\ooch{4}$ together imply $\ooch{5}$.
We mention property $\ooch{5}$ mainly because of the symmetry it exhibits
with $\ooch{3}$; it will prove more relevant in Chapter \ref{ch:3}.
Example \ref{ex:2-choice-props} already rationalizes a choosing agent's
behavior in terms of alternatives that are good, or best in a certain
range: this suggests that there exists a dimension along which the
agent ranks alternatives, and uses this ranking to guide its choices.
This intuition is formalized through the instrument of a preference
order $\le$ on $X$, as described in Section \ref{sec:2-preferences},
and expected to enjoy a two-way relation with a choice function $\cf$.
Firstly, a preference relation is used by the agent
to determine its choices.
Thus, given a preference order $\le$ on $X$, the
\emph{$\le$-induced choice function $\cf^{\le}$ on $X$}
is defined, for any choice set $M$, as:
\begin{displaymath}
\cf^{\le}(M) \defeq \min_{\le}M.
\end{displaymath}
Intuitively, given a menu $M$ of alternatives in $X$,
the choice over $M$ consists of the best elements of $M$
according to the preference relation $\le$ on $X$.
Conversely, the agent's observed choice behavior
can be used to construct, or reveal, the agent's preference relation on $X$.
Thus, given a choice function $\cf$ on $X$,
the \emph{$\cf$-revealed preference relation $\le^\cf$ on $X$} is defined,
for any $x_1,x_2\in X$, as:
\begin{displaymath}
x_1\le^\cf x_2~\text{if}~x_1\in\cf(\{x_1,x_2\}).
\end{displaymath}
Intuitively, $x_1$ is considered at least as good as $x_2$ in $\le^\cf$
if $x_1$ is chosen when the choice set contains exactly $x_1$ and $x_2$.
If $\le$ is a preference order on a set $X$ and $\cf$ is a choice function,
then $\le$ \emph{represents $\cf$} (alternatively, \emph{$\cf$ is represented by $\le$}),
if, for any choice set $M \subseteq X$, it holds that:
$$
\cf(M) = \min_{\le}M.
$$
In this section, we are interested in choice functions that can be
represented by preference orders $\le$ that are total preorders.
The rationale for this is straightforward:
the properties of a total preorder, though demanding and perhaps unrealistic,
describe an agent who has complete information about
the alternatives it is faced with, and can unfailingly identify
the best alternatives out of any choice set.
What properties does a choice function need to satisfy
in order for it to be represented by a total preorder?
The answer is provided by properties $\ooch{1-4}$.
\begin{thm}{\cite{Sen70}}{2-choice-repr}
If $\cf$ is a choice function on $X$, then
$\cf$ satisfies properties $\ooch{1-4}$ if and only if
there exists a total preorder $\le$ on $X$ that represents $\cf$.
\end{thm}
Intuitively, if $\cf$ is a choice function satisfying properties $\ooch{1-4}$
then the $\cf$-revealed preference relation $\le^\cf$ is exactly the total preorder
that satisfies the conditions in Theorem \ref{thm:2-choice-repr}.
What is more, the $\le^\cf$-induced choice function on $X$ is identical to $\cf$.
Theorem \ref{thm:2-choice-repr} is similar, in many respects,
to the representation results for belief change we will encounter in the
following chapters.
\subsubsection{Social choice}
If $N=\{1,\dots,n\}$ is a set of agents and
$X$ is a set of alternatives,
a \emph{$\TPRE$-profile $\PP$ on $X$}
(alternatively, a \emph{preference profile on $X$}),
also written as $\PP = (\le_i)_{1\le i\le n}$
is an $n$-tuple $\PP=(\le_1,\dots,\le_n)$
of total preorders on $X$.
Each total preorder $\le_i$ in a preference profile $\PP$
is assumed to correspond to an agent $i$ in $N$.
A \emph{social choice function $\scf$}
is a function $\scf\colon\TPRE^n\rightarrow 2^X$,
taking as input a preference profile $\PP$ on $X$
and returning a set $\scf(\PP)$ of alternatives in $X$, called
the \emph{winning alternatives with respect to $\PP$ and $X$}.
A \emph{social welfare function $\swf$}
is a function $\swf\colon\TPRE^n\rightarrow \TPRE$,
taking as input a $\TPRE$-preference profile $\PP$ on $X$
and returning a total preorder $\swf(\PP)$ on $X$.
The model for a social choice function is a voting rule,
i.e., a function that processes preferences submitted by
agents and outputs a set of winning candidated.
The literature on social theory is, of course, rich in
concrete proposals of voting rules and of ways to analyze
them, and in the interest of brevity we defer to some
standard sources for more in-depth material \cite{Zwicker16,BaumeisterR16}.
Here we only introduce a few key notions that have been tweaked to fit in
with the overall tenor of this work and will be referenced later.
The first notion is the specific solution concept of a \emph{weak Condorcet winner}.
Thus, if $X$ is a set of alternatives,
$\PP = (\le_{i})_{1\le i\le n}$ is a preference profile on $X$
and $x_1$ and $x_2$ are alternatives in $X$,
the \emph{support $\supp_{X}(x_1,x_2)$ of $x_1$ over $x_2$ with respect to $\PP$ and $X$} is defined as:
$$
\supp_{X}(x_1,x_2)=\{i\in N\mid x_1\le_{i} x_2\},
$$
i.e., the set of agents in $N$ for whom $x_1$ is at least as good as $x_2$.
Intuitively, we can think of
$x_1$ and $x_2$ as matched up in a head to head election based on the preferences expressed in $\PP$,
and the support of $x_1$ over $x_2$ are the agents in $N$ who see $x_1$ as
at least as good as $x_2$.
If $x^{\ast}$ is an alternative in $X$,
then $x^{\ast}$ is a \emph{weak Condorcet winner with respect to $\PP$ and $X$} if:
$$
|\supp_{X}(x^{\ast},x)|\ge |\supp_{X}(x,x^{\ast})|,~\text{for any}~x\in X.
$$
In other words, $x^{\ast}$ is a weak Condorcet winner
with respect to $\PP$ and $X$ if $x^{\ast}$ is considered
at least as good as any other alternative $x$
by at least as many agents in $N$ as those that consider
$x$ at least as good as $x^{\ast}$.
Intuitively, an alternative $x^{\ast}$ is a weak Condorcet
winner with respect to $\PP$ and $X$
if $x^{\ast}$ is in $X$ and manages to defeat,
or match, every other alternative in $X$ in
a head to head election.
The definition of a (weak) Condorcet winner
is relativized to a set of alternatives $X$
to allow for the possibility of varying $X$
anywhere in between the universal set of alternatives
and a subset of it.
If agents are assumed to have preferences over
the set of all possible alternatives,
then we can restrict those preferences
to a smaller set of alternatives and
ask for the Condorcet winner relative to
the restricted set.
Clearly, a weak Condorcet winner relative to a set $X$ of alternatives
stays a weak Condorcet winner relative to a set $X'\subseteq X$ of alternatives.
The converse, however, is not guaranteed to hold.
\begin{figure}\centering
\begin{minipage}{0.45\textwidth}\centering
\begin{tabular}{ccccc}
\toprule
$1$ & $2$ & $3$ & $4$ & $5$\\
\midrule
$x_1$ & $x_4$ & $x_3$ & $x_2$ & $x_2$\\
$x_2$ & $x_1$ & $x_4$ & $x_3$ & $x_1$\\
$x_3$ & $x_2$ & $x_1$ & $x_4$ & $x_4$\\
$x_4$ & $x_3$ & $x_2$ & $x_1$ & $x_3$\\\bottomrule
\end{tabular}
\caption*{$\PP=(\le_i)_{1\le i \le 5}$ over $X = \{x_1,x_2,x_3,x_4\}$}
\end{minipage}
\begin{minipage}{0.45\textwidth}\centering
\begin{tabular}{ccccc}
\toprule
$1$ & $2$ & $3$ & $4$ & $5$\\
\midrule
$x_1$ & & $x_3$ & $x_2$ & $x_2$\\
$x_2$ & $x_1$ & & $x_3$ & $x_1$\\
$x_3$ & $x_2$ & $x_1$ & & \\
& $x_3$ & $x_2$ & $x_1$ & $x_3$\\
\bottomrule
\end{tabular}
\caption*{$\PP$ restricted to $X' = \{x_1,x_2,x_3\}$}
\end{minipage}
\caption{
On the left, the preference profile $\PP=(\le_i)_{1\le i \le 5}$
over the set of alternatives $X = \{x_1,x_2,x_3,x_4\}$;
on the right, the same preference profile restricted
to the set of alternatives $X'=\{x_1,x_2,x_3\}$.
Higher, in this context, is better, such that for Doctor $1$
alternative $x_1$ is the best, $x_2$ is the second best, and so on.
We obtain that $x_1$ is a Condorcet winner with respect to $\PP$ and $X'$,
but not with respect to $\PP$ and $X$.
}
\label{fig:2-condorcet-winner-expansion}
\end{figure}
\begin{xmpl}{Doctors in need of agreement}{2-condorcet-winner-expansion}
Recall the five doctors in Example \ref{ex:1-choice-motivation}
who have to agree on a common treatment for a novel respiratory disease,
with the alternatives being a cocktail of drugs $a$ and $b$, $a$ alone,
$b$ alone or neither of these two drugs.
If we denote these alternatives by $x_1$, $x_2$, $x_3$ and $x_4$,
respectively, then each doctor can be thought of as having a preference
order $\le_i$, for $i\in\{1,2,3,4,5\}$,
over the (universal) set of alternatives $X = \{x_1,x_2,x_3,x_4\}$,
with these preferences depicted on the left in Figure \ref{fig:2-condorcet-winner-expansion}.
Figure \ref{fig:2-condorcet-winner-expansion} also depicts, on the right,
the same preferences restricted to the set $X' = \{x_1,x_2,x_3\}$
of alternatives and depicted on the right in Figure \ref{fig:2-condorcet-winner-expansion}.
Note that $x_1$ is the only weak Condorcet winner with respect to $\PP$ and $X'$.
Firstly,
it holds that
$\supp_{X'}(x_1,x_2)=\{1,2,3\}$ and
$\supp_{X'}(x_2,x_1)=\{4,5\}$,
which means that (strictly) more agents (strictly) prefer $x_1$ to $x_2$.
Secondly,
it holds that
$\supp_{X'}(x_1,x_3)=\{1,2,5\}$ and
$\supp_{X'}(x_3,x_1)=\{3,4\}$,
which means that (strictly) more agents (strictly) prefer $x_1$ to $x_3$.
Thus, $x_1$ conclusively
defeats every other alternative in $X'$ in a head to head election.
However, alternative $x_1$ ceases to be a weak Condorcet winner
with respect to $\PP$ and $X$:
$x_1$ still defeats $x_2$ and $x_3$ in a head to head election,
since the computations above are not changed;
but $x_1$ is defeated by $x_4$, since
$\supp_{X}(x_1,x_4)=\{1,5\}$ and
$\supp_{X}(x_4,x_1)=\{2,3,4\}$,
i.e., more agents strictly prefer $x_4$ to $x_1$.
What is more, since no alternative manages to defeat,
or even match, all other alternatives
in head to head elections,
there is no weak Condorcet winner with respect to $\PP$ and $X$.
\end{xmpl}
We will use this relativized notion of a Condorcet winner in Section \ref{sec:5-evenhandedness}.
Since we will be concerned with belief merging operators that meet certain
proportionality requirements,
traditionally the preserve of multiwinner elections,
we need a set of tools for thinking about proportionality
in the context of social choice functions.
Proportional representation has been systematically studied in the social choice literature,
notably in the case of Approval-Based Committee (ABC) elections \cite{FaliszewskiSST17}.
An ABC election requires the set of alternatives $X$,
a desired size of the committee $k$,
and a particular type of preference profile.
In an ABC election voters are assumed to partition
the set of alternatives into two sets: the alternatives they approve of,
and the alternatives they do not approve of.
In the context of the framework introduced here, such a preference
order can be modeled by a preorder $\le$ that consists of exactly two levels,
i.e., there are two sets $V$ and $X\setminus V$ such that
$v_1<v_2$ for any $v_1\in V$ and $v_2\in X\setminus V$
and $v\approx v'$ if $x,x'\in V$ or $v.v'\in X\setminus V$.
If a preorder $\le$ on $X$ is of such a type,
we call $\le$ an \emph{approval preference order}.
If an agent $i$ has an approval preference order $\le_i$,
then $V_i$ is \emph{agent $i$'s approval ballot}.
Since an approval ballot is just a set of alternatives from $X$,
the set of all approval ballots is $2^{X}$.
An approval preference order is completely determined by the elements of $V_i$,
so voters need only report their approval ballots for their preference to be
completely specified, and we will base ABC elections on these ballots.
Thus, an \emph{approval profile $\VV$} is a tuple
$\VV=(V_1,\dots,V_n)$, also written as $(V_i)_{1\le i\le n}$,
of approval ballots, with $(2^X)^n$ being the set of all approval profiles of length $n$.
If $X$ is a finite set of alternative and $n$ and $k$ are integers,
an \emph{ABC social choice function $\abc$} is a function
$\abc\colon (2^X)^{n}\rightarrow 2_k^X$,
taking as input an approval profile and returning a set of alternatives,
also called the \emph{winning committees}, of size $k$.
The ABC social choice function of immediate interest to us
is called \emph{Proportional Approval Voting} \cite{Thiele95}.
It is based on the \emph{harmonic function $h$}, which is a function
$h\colon\mathbb{N}\rightarrow\mathbb{R}$,
defined as:
$$
h(\ell) = \sum_{i=1}^{\ell}\frac{1}{i},
$$
with the added convention that $h(0)=0$.
Given an approval profile $\VV=(V_i)_{1\le i\le n}$
and a committee $W\subseteq X$ of size $k$,
the \emph{$\pav$-score of $W$ with respect to $\VV$} is
defined as:
$$
\pav(\VV,W)=\sum_{i=1}^n h(|V_i\cap W|),
$$
where $h$ is the harmonic function.
Given two committees $W_1$ and $W_2$ of size $k$,
the $\pav$-induced preorder on $2_k^{X}$, is defined as:
$$
W_1\ge^{\pav}_{\VV}W_2~\text{if}~\pav(\VV,W_1)\ge\pav(\VV,W_2).
$$
The $\pav$ ABC function $\abc^{\pav}$ applied to the approval profile $\VV$,
for a desired size $k$ of the committee, is defined as:
$$
\abc^{\pav}_k(\VV)=\max_{\ge^{\pav}_{\VV}}\{W\subseteq X\mid |W|=k\},
$$
i.e., it outputs committees of size $k$ that maximize the
$\pav$ score with respect to $\VV$.
\begin{table}\centering
\begin{tabular}{cccccc}
\toprule
$\pav$ & $x_1x_2x_3x_4$ & $x_1x_2x_3x_4$ & $x_1x_2x_3x_4$ & $y_1y_2y_3y_4$ & $\ssum$\\
\midrule
$x_1x_2x_3x_4$ & $h(4)$ & $h(4)$ & $h(4)$ & $h(0)$ & $6.25$\\
$x_1x_2x_3y_1$ & $h(3)$ & $h(3)$ & $h(3)$ & $h(1)$ & $\mathbf{6.5}$\\
$x_1x_2y_1y_2$ & $h(2)$ & $h(2)$ & $h(2)$ & $h(2)$ & $6$\\
$x_1y_2y_2y_3$ & $h(1)$ & $h(1)$ & $h(1)$ & $h(3)$ & $4.83$\\
$y_1y_2y_3y_4$ & $h(0)$ & $h(0)$ & $h(0)$ & $h(4)$ & $2.08$\\
\dots & \dots & \dots & \dots & \dots & \dots \\
\bottomrule
\end{tabular}
\caption{
$\pav$ scores for a selection of committees of size $4$.
when the approval profile is $\VV=(V_i)_{\le i\le 4}$.
an optimal outcome according to the $\abc^\pav$ function
is one that maximizes
the $\pav$-score with respect to the profile $\VV$.
}
\label{tab:2-abc-pav-rule}
\end{table}
\begin{xmpl}{The $\pav$ rule}{ex:abc-pav-rule}
Take a set of candidates $X\cup Y$,
where $X=\{x_1,x_2,x_3,x_4\}$
and
$Y=\{y_1,y_2,y_3,y_4\}$,
and an approval profile $\VV=(V_1,V_2,V_3,V_4)$
with $V_1=V_2=V_3=\{x_1x_2x_3x_4\}$ and $V_4=\{y_1y_2y_3y_4\}$.
Suppose $k=4$, i.e., the task is to choose committees of size $4$.
Intuitively, a proportional outcome would consist of three candidates from $X$
and one from $Y$, to reflect the fact that supporters $X$ outnumber
supporters of $Y$ in the profile $\VV$ by a ratio of $3{:}1$.
Indeed, this is exactly the type of outcome the $\pav$ rule will select.
Table \ref{tab:2-abc-pav-rule} depicts the $\pav$ scores
of a representative sample of possible winning committees.
Note that an optimal outcome according to the $\abc^\pav$ function
is one that maximizes
the $\pav$-score with respect to the profile $\VV$.
In this case, this corresponds to committees consisting of three
alternatives from $X$ and one from $Y$, i.e.,
$\abc_k^\pav(\VV)=\{x_1x_2x_3y_1,x_1x_2x_3y_2,\dots\}$.
\end{xmpl}
The $\pav$ function is known to satisfy a number of desirable proportionality
requirements \cite{AzizBCEFW17}, and will serve as a template
for proportional belief merging operators in Section \ref{sec:5-proportionality}.
|
/-
Copyright (c) 2021 Shing Tak Lam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shing Tak Lam
-/
import topology.homotopy.basic
/-!
# Homotopy equivalences between topological spaces
In this file, we define homotopy equivalences between topological spaces `X` and `Y` as a pair of
functions `f : C(X, Y)` and `g : C(Y, X)` such that `f.comp g` and `g.comp f` are both homotopic
to `id`.
## Main definitions
- `continuous_map.homotopy_equiv` is the type of homotopy equivalences between topological spaces.
## Notation
We introduce the notation `X ≃ₕ Y` for `continuous_map.homotopy_equiv X Y` in the `continuous_map`
locale.
-/
universes u v w
variables {X : Type u} {Y : Type v} {Z : Type w}
variables [topological_space X] [topological_space Y] [topological_space Z]
namespace continuous_map
/--
A homotopy equivalence between topological spaces `X` and `Y` are a pair of functions
`to_fun : C(X, Y)` and `inv_fun : C(Y, X)` such that `to_fun.comp inv_fun` and `inv_fun.comp to_fun`
are both homotopic to `id`.
-/
@[ext]
structure homotopy_equiv (X : Type u) (Y : Type v) [topological_space X] [topological_space Y] :=
(to_fun : C(X, Y))
(inv_fun : C(Y, X))
(left_inv : (inv_fun.comp to_fun).homotopic id)
(right_inv : (to_fun.comp inv_fun).homotopic id)
localized "infix ` ≃ₕ `:25 := continuous_map.homotopy_equiv" in continuous_map
namespace homotopy_equiv
instance : has_coe_to_fun (homotopy_equiv X Y) (λ _, X → Y) := ⟨λ h, h.to_fun⟩
@[simp]
lemma to_fun_eq_coe (h : homotopy_equiv X Y) : (h.to_fun : X → Y) = h := rfl
@[continuity]
lemma continuous (h : homotopy_equiv X Y) : continuous h := h.to_fun.continuous
end homotopy_equiv
end continuous_map
open_locale continuous_map
namespace homeomorph
/--
Any homeomorphism is a homotopy equivalence.
-/
def to_homotopy_equiv (h : X ≃ₜ Y) : X ≃ₕ Y :=
{ to_fun := ⟨h⟩,
inv_fun := ⟨h.symm⟩,
left_inv := by { convert continuous_map.homotopic.refl _, ext, simp },
right_inv := by { convert continuous_map.homotopic.refl _, ext, simp } }
@[simp]
lemma coe_to_homotopy_equiv (h : X ≃ₜ Y) : ⇑(h.to_homotopy_equiv) = h := rfl
end homeomorph
namespace continuous_map
namespace homotopy_equiv
/--
If `X` is homotopy equivalent to `Y`, then `Y` is homotopy equivalent to `X`.
-/
def symm (h : X ≃ₕ Y) : Y ≃ₕ X :=
{ to_fun := h.inv_fun,
inv_fun := h.to_fun,
left_inv := h.right_inv,
right_inv := h.left_inv }
@[simp]
lemma coe_inv_fun (h : homotopy_equiv X Y) : (⇑h.inv_fun : Y → X) = ⇑h.symm := rfl
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : X ≃ₕ Y) : X → Y := h
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.symm_apply (h : X ≃ₕ Y) : Y → X := h.symm
initialize_simps_projections homotopy_equiv (to_fun_to_fun -> apply,
inv_fun_to_fun -> symm_apply, -to_fun, -inv_fun)
/--
Any topological space is homotopy equivalent to itself.
-/
@[simps]
def refl (X : Type u) [topological_space X] : X ≃ₕ X :=
(homeomorph.refl X).to_homotopy_equiv
instance : inhabited (homotopy_equiv unit unit) := ⟨refl unit⟩
/--
If `X` is homotopy equivalent to `Y`, and `Y` is homotopy equivalent to `Z`, then `X` is homotopy
equivalent to `Z`.
-/
@[simps]
def trans (h₁ : X ≃ₕ Y) (h₂ : Y ≃ₕ Z) : X ≃ₕ Z :=
{ to_fun := h₂.to_fun.comp h₁.to_fun,
inv_fun := h₁.inv_fun.comp h₂.inv_fun,
left_inv := begin
refine homotopic.trans _ h₁.left_inv,
change ((h₁.inv_fun.comp h₂.inv_fun).comp (h₂.to_fun.comp h₁.to_fun)) with
h₁.inv_fun.comp ((h₂.inv_fun.comp h₂.to_fun).comp h₁.to_fun),
refine homotopic.hcomp _ (homotopic.refl _),
refine homotopic.trans ((homotopic.refl _).hcomp h₂.left_inv) _,
-- simp,
rw continuous_map.id_comp,
end,
right_inv := begin
refine homotopic.trans _ h₂.right_inv,
change ((h₂.to_fun.comp h₁.to_fun).comp (h₁.inv_fun.comp h₂.inv_fun)) with
h₂.to_fun.comp ((h₁.to_fun.comp h₁.inv_fun).comp h₂.inv_fun),
refine homotopic.hcomp _ (homotopic.refl _),
refine homotopic.trans ((homotopic.refl _).hcomp h₁.right_inv) _,
rw id_comp,
end }
lemma symm_trans (h₁ : X ≃ₕ Y) (h₂ : Y ≃ₕ Z) :
(h₁.trans h₂).symm = h₂.symm.trans h₁.symm := by ext; refl
end homotopy_equiv
end continuous_map
open continuous_map
namespace homeomorph
@[simp]
lemma refl_to_homotopy_equiv (X : Type u) [topological_space X] :
(homeomorph.refl X).to_homotopy_equiv = homotopy_equiv.refl X := rfl
@[simp]
lemma symm_to_homotopy_equiv (h : X ≃ₜ Y) :
h.symm.to_homotopy_equiv = h.to_homotopy_equiv.symm := rfl
@[simp]
lemma trans_to_homotopy_equiv (h₀ : X ≃ₜ Y) (h₁ : Y ≃ₜ Z) :
(h₀.trans h₁).to_homotopy_equiv = h₀.to_homotopy_equiv.trans h₁.to_homotopy_equiv := rfl
end homeomorph
|
(* Title: ZF/Resid/Redex.thy
Author: Ole Rasmussen, University of Cambridge
*)
theory Redex imports ZF begin
consts
redexes :: i
datatype
"redexes" = Var ("n \<in> nat")
| Fun ("t \<in> redexes")
| App ("b \<in> bool","f \<in> redexes", "a \<in> redexes")
consts
Ssub :: "i"
Scomp :: "i"
Sreg :: "i"
abbreviation
Ssub_rel (infixl \<open>\<Longleftarrow>\<close> 70) where
"a \<Longleftarrow> b \<equiv> \<langle>a,b\<rangle> \<in> Ssub"
abbreviation
Scomp_rel (infixl \<open>\<sim>\<close> 70) where
"a \<sim> b \<equiv> \<langle>a,b\<rangle> \<in> Scomp"
abbreviation
"regular(a) \<equiv> a \<in> Sreg"
consts union_aux :: "i\<Rightarrow>i"
primrec (*explicit lambda is required because both arguments of "\<squnion>" vary*)
"union_aux(Var(n)) =
(\<lambda>t \<in> redexes. redexes_case(\<lambda>j. Var(n), \<lambda>x. 0, \<lambda>b x y.0, t))"
"union_aux(Fun(u)) =
(\<lambda>t \<in> redexes. redexes_case(\<lambda>j. 0, \<lambda>y. Fun(union_aux(u)`y),
\<lambda>b y z. 0, t))"
"union_aux(App(b,f,a)) =
(\<lambda>t \<in> redexes.
redexes_case(\<lambda>j. 0, \<lambda>y. 0,
\<lambda>c z u. App(b or c, union_aux(f)`z, union_aux(a)`u), t))"
definition
union (infixl \<open>\<squnion>\<close> 70) where
"u \<squnion> v \<equiv> union_aux(u)`v"
inductive
domains "Ssub" \<subseteq> "redexes*redexes"
intros
Sub_Var: "n \<in> nat \<Longrightarrow> Var(n) \<Longleftarrow> Var(n)"
Sub_Fun: "\<lbrakk>u \<Longleftarrow> v\<rbrakk>\<Longrightarrow> Fun(u) \<Longleftarrow> Fun(v)"
Sub_App1: "\<lbrakk>u1 \<Longleftarrow> v1; u2 \<Longleftarrow> v2; b \<in> bool\<rbrakk>\<Longrightarrow>
App(0,u1,u2) \<Longleftarrow> App(b,v1,v2)"
Sub_App2: "\<lbrakk>u1 \<Longleftarrow> v1; u2 \<Longleftarrow> v2\<rbrakk>\<Longrightarrow> App(1,u1,u2) \<Longleftarrow> App(1,v1,v2)"
type_intros redexes.intros bool_typechecks
inductive
domains "Scomp" \<subseteq> "redexes*redexes"
intros
Comp_Var: "n \<in> nat \<Longrightarrow> Var(n) \<sim> Var(n)"
Comp_Fun: "\<lbrakk>u \<sim> v\<rbrakk>\<Longrightarrow> Fun(u) \<sim> Fun(v)"
Comp_App: "\<lbrakk>u1 \<sim> v1; u2 \<sim> v2; b1 \<in> bool; b2 \<in> bool\<rbrakk>
\<Longrightarrow> App(b1,u1,u2) \<sim> App(b2,v1,v2)"
type_intros redexes.intros bool_typechecks
inductive
domains "Sreg" \<subseteq> redexes
intros
Reg_Var: "n \<in> nat \<Longrightarrow> regular(Var(n))"
Reg_Fun: "\<lbrakk>regular(u)\<rbrakk>\<Longrightarrow> regular(Fun(u))"
Reg_App1: "\<lbrakk>regular(Fun(u)); regular(v)\<rbrakk>\<Longrightarrow>regular(App(1,Fun(u),v))"
Reg_App2: "\<lbrakk>regular(u); regular(v)\<rbrakk>\<Longrightarrow>regular(App(0,u,v))"
type_intros redexes.intros bool_typechecks
declare redexes.intros [simp]
(* ------------------------------------------------------------------------- *)
(* Specialisation of comp-rules *)
(* ------------------------------------------------------------------------- *)
lemmas compD1 [simp] = Scomp.dom_subset [THEN subsetD, THEN SigmaD1]
lemmas compD2 [simp] = Scomp.dom_subset [THEN subsetD, THEN SigmaD2]
lemmas regD [simp] = Sreg.dom_subset [THEN subsetD]
(* ------------------------------------------------------------------------- *)
(* Equality rules for union *)
(* ------------------------------------------------------------------------- *)
lemma union_Var [simp]: "n \<in> nat \<Longrightarrow> Var(n) \<squnion> Var(n)=Var(n)"
by (simp add: union_def)
lemma union_Fun [simp]: "v \<in> redexes \<Longrightarrow> Fun(u) \<squnion> Fun(v) = Fun(u \<squnion> v)"
by (simp add: union_def)
lemma union_App [simp]:
"\<lbrakk>b2 \<in> bool; u2 \<in> redexes; v2 \<in> redexes\<rbrakk>
\<Longrightarrow> App(b1,u1,v1) \<squnion> App(b2,u2,v2)=App(b1 or b2,u1 \<squnion> u2,v1 \<squnion> v2)"
by (simp add: union_def)
lemma or_1_right [simp]: "a or 1 = 1"
by (simp add: or_def cond_def)
lemma or_0_right [simp]: "a \<in> bool \<Longrightarrow> a or 0 = a"
by (simp add: or_def cond_def bool_def, auto)
declare Ssub.intros [simp]
declare bool_typechecks [simp]
declare Sreg.intros [simp]
declare Scomp.intros [simp]
declare Scomp.intros [intro]
inductive_cases [elim!]:
"regular(App(b,f,a))"
"regular(Fun(b))"
"regular(Var(b))"
"Fun(u) \<sim> Fun(t)"
"u \<sim> Fun(t)"
"u \<sim> Var(n)"
"u \<sim> App(b,t,a)"
"Fun(t) \<sim> v"
"App(b,f,a) \<sim> v"
"Var(n) \<sim> u"
(* ------------------------------------------------------------------------- *)
(* comp proofs *)
(* ------------------------------------------------------------------------- *)
lemma comp_refl [simp]: "u \<in> redexes \<Longrightarrow> u \<sim> u"
by (erule redexes.induct, blast+)
lemma comp_sym: "u \<sim> v \<Longrightarrow> v \<sim> u"
by (erule Scomp.induct, blast+)
lemma comp_sym_iff: "u \<sim> v \<longleftrightarrow> v \<sim> u"
by (blast intro: comp_sym)
lemma comp_trans [rule_format]: "u \<sim> v \<Longrightarrow> \<forall>w. v \<sim> w\<longrightarrow>u \<sim> w"
by (erule Scomp.induct, blast+)
(* ------------------------------------------------------------------------- *)
(* union proofs *)
(* ------------------------------------------------------------------------- *)
lemma union_l: "u \<sim> v \<Longrightarrow> u \<Longleftarrow> (u \<squnion> v)"
apply (erule Scomp.induct)
apply (erule_tac [3] boolE, simp_all)
done
lemma union_r: "u \<sim> v \<Longrightarrow> v \<Longleftarrow> (u \<squnion> v)"
apply (erule Scomp.induct)
apply (erule_tac [3] c = b2 in boolE, simp_all)
done
lemma union_sym: "u \<sim> v \<Longrightarrow> u \<squnion> v = v \<squnion> u"
by (erule Scomp.induct, simp_all add: or_commute)
(* ------------------------------------------------------------------------- *)
(* regular proofs *)
(* ------------------------------------------------------------------------- *)
lemma union_preserve_regular [rule_format]:
"u \<sim> v \<Longrightarrow> regular(u) \<longrightarrow> regular(v) \<longrightarrow> regular(u \<squnion> v)"
by (erule Scomp.induct, auto)
end
|
[STATEMENT]
lemma least_min_alg1: "alg B1 B2 s1 s2 \<Longrightarrow> min_alg1 s1 s2 \<subseteq> B1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. alg B1 B2 s1 s2 \<Longrightarrow> min_alg1 s1 s2 \<subseteq> B1
[PROOF STEP]
apply (rule ord_eq_le_trans[OF min_alg1_def])
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. alg B1 B2 s1 s2 \<Longrightarrow> (\<Union>i\<in>Field SucFbd. fst (min_algs s1 s2 i)) \<subseteq> B1
[PROOF STEP]
apply (rule UN_least)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>i. \<lbrakk>alg B1 B2 s1 s2; i \<in> Field SucFbd\<rbrakk> \<Longrightarrow> fst (min_algs s1 s2 i) \<subseteq> B1
[PROOF STEP]
apply (drule least_min_algs)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>i. \<lbrakk>i \<in> Field SucFbd; ?i5 i \<in> Field SucFbd \<longrightarrow> fst (min_algs s1 s2 (?i5 i)) \<subseteq> B1 \<and> snd (min_algs s1 s2 (?i5 i)) \<subseteq> B2\<rbrakk> \<Longrightarrow> fst (min_algs s1 s2 i) \<subseteq> B1
[PROOF STEP]
apply (drule mp)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>i. i \<in> Field SucFbd \<Longrightarrow> ?i5 i \<in> Field SucFbd
2. \<And>i. \<lbrakk>i \<in> Field SucFbd; fst (min_algs s1 s2 (?i5 i)) \<subseteq> B1 \<and> snd (min_algs s1 s2 (?i5 i)) \<subseteq> B2\<rbrakk> \<Longrightarrow> fst (min_algs s1 s2 i) \<subseteq> B1
[PROOF STEP]
apply assumption
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>i. \<lbrakk>i \<in> Field SucFbd; fst (min_algs s1 s2 i) \<subseteq> B1 \<and> snd (min_algs s1 s2 i) \<subseteq> B2\<rbrakk> \<Longrightarrow> fst (min_algs s1 s2 i) \<subseteq> B1
[PROOF STEP]
apply (erule conjE)+
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>i. \<lbrakk>i \<in> Field SucFbd; fst (min_algs s1 s2 i) \<subseteq> B1; snd (min_algs s1 s2 i) \<subseteq> B2\<rbrakk> \<Longrightarrow> fst (min_algs s1 s2 i) \<subseteq> B1
[PROOF STEP]
apply assumption
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
Like almost all alternative clothing styles, grunge was born from a music scene, first making it’s presence known in Seattle in the 90s before taking the world by storm, thanks to a band called Nirvana. Grunge is about as deeply rooted in American style as you can get. But whether you associate it with major ’90s rock bands or the recent hoards of hipsters around the world riffing on Cobain’s style, there’s no mistaking that it has made a comeback with a minimalist twist. |
Does your business have a reverse logistics plan?
The traditional consumption linear supply chain model of the “make, buy, throw away” lifestyle of the 1950’s underwent a societal value shift when governments around the world, recognizing the growing issues with landfills, enacted legislation for waste management.
This resulted in the development of reduce, reuse and recycle programs. Regulations and consumer awareness have businesses adopting reuse and recycling practices and examining the potential value that could be gained from managing product returns.
The same capabilities used in the forward supply chain can’t be leveraged in reverse logistics…reverse logistics requires different processes, technology, capabilities, and expertise. It’s more of a network model.
Reverse supply chain, also referred to as reverse logistics, is the process of planning, implementing and controlling the collection of products and packaging, post-consumer, in order to recover value and optimize potential benefits for the organization. The forward supply chain may use the reverse supply chain to handle problem inventory.
This content is an excerpt from the FITTskills Inventory Management online workshop. Sign up today to learn how to save money and make your business more agile by reducing your amount of idle inventory!
Today’s forward supply chain has grown in complexity with offshoring, outsourcing, strategic procurement and inventory management innovations. This innovative mindset has been applied to an increasingly sophisticated reverse supply chain.
Today’s businesses are obtaining value and changing practices to control what happens to their products after customer/consumer use. Product components or finished products are collected, sorted and returned to suppliers, manufacturers or retailers. Reverse supply chains close the loop with forward supply chains, giving rise to what is now being referred to as circular supply chains.
Effective reverse logistics can also be critically important when organizations need to recall a product. Organizations are obligated to manage product recalls when a product poses an unacceptable risk to consumer health or safety, or fails to comply with legislation, such as labelling. Managing recalls can be costly. A good recall process mitigates risk and maximizes the efficiency of product removal from the market.
Effective product return strategies and programs can result in increased revenues, lower costs, improved profitability and enhanced levels of customer service.
Companies can ensure good customer service and cut the costs associated with product returns by establishing returns policies and strategies.
Suppliers that provide raw materials or components will have products returned because they do not meet the specifications of their customers. Typically, terms of returns of raw materials or components from suppliers are negotiated in procurement contracts.
Reverse logistics involves the process of negotiating, developing and implementing the means for products to be returned for repair, refurbishment, recycling or disposal. In reverse logistics, businesses do not initiate the logistics flow; it is activated by the actions of consumers or other downstream channels.
Organizations must establish a return system that is consistent with business aims in order to optimize resources, manage assets and ultimately ensure profitability.
Organizations must examine the social environment and consider consumer preferences and service expectations. A sustainable return system will include waste reduction strategies, such as redesigned packaging that uses less material and improves on shipping efficiencies, or determining a process that minimizes the number of transit points for return sand identifying returns that can be resold or repurposed.
When an organization accepts a return, it must have a policy for either refunding the price of the product or issuing a credit to be used against future purchases. The policy that is decided on will depend on the organization’s financial status, size, customer and business strategy.
Customers prefer a straight refund, but smaller companies might not be able to provide this, especially if the number of returns in an accounting period is much larger than anticipated.
Where a company is dealing with a large customer, such as a retailer, logging a credit against a future order or making a direct bank transfer are the easiest methods of refunding the cost of the returned products. The actual amounts to be refunded and the refund method must be defined in contracts that are negotiated between companies and the customers they are supplying.
When individual customers must be refunded, the method by which a refund is provided is determined by how the customer paid for the item. Companies may charge a handling or shipping fee. Customers should be informed of this and of the estimated time lag between submitting a product for refund and dispatch of the payment. This lag time will enable the company to examine the product to ensure it was returned legitimately and to process the payment.
Innovations in reverse logistics have some organizations working proactively with customers for asset retirement. These organizations provide opportunities for customers to bring back their old product and receive a payment that can be put towards the purchase of a new product. The retired product can be used for parts or refurbished and resold.
Interested in a broader look at managing your company’s supply chain and logistics to mitigate risks, reduce costs and improve efficiency throughout every stage of your global value chain? Get started with FITTskills Global Value Chain online course today! |
-- -------------------------------------------------------------- [ Parser.idr ]
-- Description : A command line argument parser
-- Copyright : (c) Huw Campbell
-- --------------------------------------------------------------------- [ EOH ]
module Options.Applicative
import public Text.PrettyPrint.WL
import public Options.Applicative.Builder
import public Options.Applicative.Maybe
import public Options.Applicative.Run
import public Options.Applicative.Types
import public Options.Applicative.Usage
import public Control.Lens
%access public export
-- --------------------------------------------------------------------- [ EOF ]
|
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
⊢ FG (↑Subalgebra.toSubmodule (adjoin R (s ∪ t)))
[PROOFSTEP]
rcases fg_def.1 h1 with ⟨p, hp, hp'⟩
[GOAL]
case intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
⊢ FG (↑Subalgebra.toSubmodule (adjoin R (s ∪ t)))
[PROOFSTEP]
rcases fg_def.1 h2 with ⟨q, hq, hq'⟩
[GOAL]
case intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
⊢ FG (↑Subalgebra.toSubmodule (adjoin R (s ∪ t)))
[PROOFSTEP]
refine' fg_def.2 ⟨p * q, hp.mul hq, le_antisymm _ _⟩
[GOAL]
case intro.intro.intro.intro.refine'_1
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
⊢ span R (p * q) ≤ ↑Subalgebra.toSubmodule (adjoin R (s ∪ t))
[PROOFSTEP]
rw [span_le]
[GOAL]
case intro.intro.intro.intro.refine'_1
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
⊢ p * q ⊆ ↑(↑Subalgebra.toSubmodule (adjoin R (s ∪ t)))
[PROOFSTEP]
rintro _ ⟨x, y, hx, hy, rfl⟩
[GOAL]
case intro.intro.intro.intro.refine'_1.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
⊢ (fun x x_1 => x * x_1) x y ∈ ↑(↑Subalgebra.toSubmodule (adjoin R (s ∪ t)))
[PROOFSTEP]
change x * y ∈ adjoin R (s ∪ t)
[GOAL]
case intro.intro.intro.intro.refine'_1.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
⊢ x * y ∈ adjoin R (s ∪ t)
[PROOFSTEP]
refine' Subalgebra.mul_mem _ _ _
[GOAL]
case intro.intro.intro.intro.refine'_1.intro.intro.intro.intro.refine'_1
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
⊢ x ∈ adjoin R (s ∪ t)
[PROOFSTEP]
have : x ∈ Subalgebra.toSubmodule (adjoin R s) := by
rw [← hp']
exact subset_span hx
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
⊢ x ∈ ↑Subalgebra.toSubmodule (adjoin R s)
[PROOFSTEP]
rw [← hp']
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
⊢ x ∈ span R p
[PROOFSTEP]
exact subset_span hx
[GOAL]
case intro.intro.intro.intro.refine'_1.intro.intro.intro.intro.refine'_1
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
this : x ∈ ↑Subalgebra.toSubmodule (adjoin R s)
⊢ x ∈ adjoin R (s ∪ t)
[PROOFSTEP]
exact adjoin_mono (Set.subset_union_left _ _) this
[GOAL]
case intro.intro.intro.intro.refine'_1.intro.intro.intro.intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
⊢ y ∈ adjoin R (s ∪ t)
[PROOFSTEP]
have : y ∈ Subalgebra.toSubmodule (adjoin (adjoin R s) t) :=
by
rw [← hq']
exact subset_span hy
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
⊢ y ∈ ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
[PROOFSTEP]
rw [← hq']
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
⊢ y ∈ span { x // x ∈ adjoin R s } q
[PROOFSTEP]
exact subset_span hy
[GOAL]
case intro.intro.intro.intro.refine'_1.intro.intro.intro.intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
this : y ∈ ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
⊢ y ∈ adjoin R (s ∪ t)
[PROOFSTEP]
change y ∈ adjoin R (s ∪ t)
[GOAL]
case intro.intro.intro.intro.refine'_1.intro.intro.intro.intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
x y : A
hx : x ∈ p
hy : y ∈ q
this : y ∈ ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
⊢ y ∈ adjoin R (s ∪ t)
[PROOFSTEP]
rwa [adjoin_union_eq_adjoin_adjoin]
[GOAL]
case intro.intro.intro.intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
⊢ ↑Subalgebra.toSubmodule (adjoin R (s ∪ t)) ≤ span R (p * q)
[PROOFSTEP]
intro r hr
[GOAL]
case intro.intro.intro.intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
r : A
hr : r ∈ ↑Subalgebra.toSubmodule (adjoin R (s ∪ t))
⊢ r ∈ span R (p * q)
[PROOFSTEP]
change r ∈ adjoin R (s ∪ t) at hr
[GOAL]
case intro.intro.intro.intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
r : A
hr : r ∈ adjoin R (s ∪ t)
⊢ r ∈ span R (p * q)
[PROOFSTEP]
rw [adjoin_union_eq_adjoin_adjoin] at hr
[GOAL]
case intro.intro.intro.intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
r : A
hr : r ∈ Subalgebra.restrictScalars R (adjoin { x // x ∈ adjoin R s } t)
⊢ r ∈ span R (p * q)
[PROOFSTEP]
change r ∈ Subalgebra.toSubmodule (adjoin (adjoin R s) t) at hr
[GOAL]
case intro.intro.intro.intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
r : A
hr : r ∈ ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
⊢ r ∈ span R (p * q)
[PROOFSTEP]
rw [← hq', ← Set.image_id q, Finsupp.mem_span_image_iff_total (adjoin R s)] at hr
[GOAL]
case intro.intro.intro.intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
r : A
hr :
∃ l,
l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q ∧
↑(Finsupp.total A A { x // x ∈ adjoin R s } _root_.id) l = r
⊢ r ∈ span R (p * q)
[PROOFSTEP]
rcases hr with ⟨l, hlq, rfl⟩
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
⊢ ↑(Finsupp.total A A { x // x ∈ adjoin R s } _root_.id) l ∈ span R (p * q)
[PROOFSTEP]
have := @Finsupp.total_apply A A (adjoin R s)
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
⊢ ↑(Finsupp.total A A { x // x ∈ adjoin R s } _root_.id) l ∈ span R (p * q)
[PROOFSTEP]
rw [this, Finsupp.sum]
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
⊢ (Finset.sum l.support fun a => ↑l a • _root_.id a) ∈ span R (p * q)
[PROOFSTEP]
refine' sum_mem _
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
⊢ ∀ (c : A), c ∈ l.support → ↑l c • _root_.id c ∈ span R (p * q)
[PROOFSTEP]
intro z hz
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
⊢ ↑l z • _root_.id z ∈ span R (p * q)
[PROOFSTEP]
change (l z).1 * _ ∈ _
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
⊢ ↑(↑l z) * _root_.id z ∈ span R (p * q)
[PROOFSTEP]
have : (l z).1 ∈ Subalgebra.toSubmodule (adjoin R s) := (l z).2
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
this : ↑(↑l z) ∈ ↑Subalgebra.toSubmodule (adjoin R s)
⊢ ↑(↑l z) * _root_.id z ∈ span R (p * q)
[PROOFSTEP]
rw [← hp', ← Set.image_id p, Finsupp.mem_span_image_iff_total R] at this
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
this : ∃ l_1, l_1 ∈ Finsupp.supported R R p ∧ ↑(Finsupp.total A A R _root_.id) l_1 = ↑(↑l z)
⊢ ↑(↑l z) * _root_.id z ∈ span R (p * q)
[PROOFSTEP]
rcases this with ⟨l2, hlp, hl⟩
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
l2 : A →₀ R
hlp : l2 ∈ Finsupp.supported R R p
hl : ↑(Finsupp.total A A R _root_.id) l2 = ↑(↑l z)
⊢ ↑(↑l z) * _root_.id z ∈ span R (p * q)
[PROOFSTEP]
have := @Finsupp.total_apply A A R
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
l2 : A →₀ R
hlp : l2 ∈ Finsupp.supported R R p
hl : ↑(Finsupp.total A A R _root_.id) l2 = ↑(↑l z)
this :
∀ [inst : Semiring R] [inst_1 : AddCommMonoid A] [inst_2 : Module R A] {v : A → A} (l : A →₀ R),
↑(Finsupp.total A A R v) l = Finsupp.sum l fun i a => a • v i
⊢ ↑(↑l z) * _root_.id z ∈ span R (p * q)
[PROOFSTEP]
rw [this] at hl
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
l2 : A →₀ R
hlp : l2 ∈ Finsupp.supported R R p
hl : (Finsupp.sum l2 fun i a => a • _root_.id i) = ↑(↑l z)
this :
∀ [inst : Semiring R] [inst_1 : AddCommMonoid A] [inst_2 : Module R A] {v : A → A} (l : A →₀ R),
↑(Finsupp.total A A R v) l = Finsupp.sum l fun i a => a • v i
⊢ ↑(↑l z) * _root_.id z ∈ span R (p * q)
[PROOFSTEP]
rw [← hl, Finsupp.sum_mul]
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
l2 : A →₀ R
hlp : l2 ∈ Finsupp.supported R R p
hl : (Finsupp.sum l2 fun i a => a • _root_.id i) = ↑(↑l z)
this :
∀ [inst : Semiring R] [inst_1 : AddCommMonoid A] [inst_2 : Module R A] {v : A → A} (l : A →₀ R),
↑(Finsupp.total A A R v) l = Finsupp.sum l fun i a => a • v i
⊢ (Finsupp.sum l2 fun a c => c • _root_.id a * _root_.id z) ∈ span R (p * q)
[PROOFSTEP]
refine' sum_mem _
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
l2 : A →₀ R
hlp : l2 ∈ Finsupp.supported R R p
hl : (Finsupp.sum l2 fun i a => a • _root_.id i) = ↑(↑l z)
this :
∀ [inst : Semiring R] [inst_1 : AddCommMonoid A] [inst_2 : Module R A] {v : A → A} (l : A →₀ R),
↑(Finsupp.total A A R v) l = Finsupp.sum l fun i a => a • v i
⊢ ∀ (c : A), c ∈ l2.support → (fun a c => c • _root_.id a * _root_.id z) c (↑l2 c) ∈ span R (p * q)
[PROOFSTEP]
intro t ht
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t✝ : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t✝))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t✝)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
l2 : A →₀ R
hlp : l2 ∈ Finsupp.supported R R p
hl : (Finsupp.sum l2 fun i a => a • _root_.id i) = ↑(↑l z)
this :
∀ [inst : Semiring R] [inst_1 : AddCommMonoid A] [inst_2 : Module R A] {v : A → A} (l : A →₀ R),
↑(Finsupp.total A A R v) l = Finsupp.sum l fun i a => a • v i
t : A
ht : t ∈ l2.support
⊢ (fun a c => c • _root_.id a * _root_.id z) t (↑l2 t) ∈ span R (p * q)
[PROOFSTEP]
change _ * _ ∈ _
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t✝ : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t✝))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t✝)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
l2 : A →₀ R
hlp : l2 ∈ Finsupp.supported R R p
hl : (Finsupp.sum l2 fun i a => a • _root_.id i) = ↑(↑l z)
this :
∀ [inst : Semiring R] [inst_1 : AddCommMonoid A] [inst_2 : Module R A] {v : A → A} (l : A →₀ R),
↑(Finsupp.total A A R v) l = Finsupp.sum l fun i a => a • v i
t : A
ht : t ∈ l2.support
⊢ ↑l2 t • _root_.id t * _root_.id z ∈ span R (p * q)
[PROOFSTEP]
rw [smul_mul_assoc]
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t✝ : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t✝))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t✝)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
l2 : A →₀ R
hlp : l2 ∈ Finsupp.supported R R p
hl : (Finsupp.sum l2 fun i a => a • _root_.id i) = ↑(↑l z)
this :
∀ [inst : Semiring R] [inst_1 : AddCommMonoid A] [inst_2 : Module R A] {v : A → A} (l : A →₀ R),
↑(Finsupp.total A A R v) l = Finsupp.sum l fun i a => a • v i
t : A
ht : t ∈ l2.support
⊢ ↑l2 t • (_root_.id t * _root_.id z) ∈ span R (p * q)
[PROOFSTEP]
refine' smul_mem _ _ _
[GOAL]
case intro.intro.intro.intro.refine'_2.intro.intro.intro.intro
R : Type u
A : Type v
B : Type w
inst✝² : CommSemiring R
inst✝¹ : CommSemiring A
inst✝ : Algebra R A
s t✝ : Set A
h1 : FG (↑Subalgebra.toSubmodule (adjoin R s))
h2 : FG (↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t✝))
p : Set A
hp : Set.Finite p
hp' : span R p = ↑Subalgebra.toSubmodule (adjoin R s)
q : Set A
hq : Set.Finite q
hq' : span { x // x ∈ adjoin R s } q = ↑Subalgebra.toSubmodule (adjoin { x // x ∈ adjoin R s } t✝)
l : A →₀ { x // x ∈ adjoin R s }
hlq : l ∈ Finsupp.supported { x // x ∈ adjoin R s } { x // x ∈ adjoin R s } q
this✝ :
∀ [inst : Semiring { x // x ∈ adjoin R s }] [inst_1 : AddCommMonoid A] [inst_2 : Module { x // x ∈ adjoin R s } A]
{v : A → A} (l : A →₀ { x // x ∈ adjoin R s }),
↑(Finsupp.total A A { x // x ∈ adjoin R s } v) l = Finsupp.sum l fun i a => a • v i
z : A
hz : z ∈ l.support
l2 : A →₀ R
hlp : l2 ∈ Finsupp.supported R R p
hl : (Finsupp.sum l2 fun i a => a • _root_.id i) = ↑(↑l z)
this :
∀ [inst : Semiring R] [inst_1 : AddCommMonoid A] [inst_2 : Module R A] {v : A → A} (l : A →₀ R),
↑(Finsupp.total A A R v) l = Finsupp.sum l fun i a => a • v i
t : A
ht : t ∈ l2.support
⊢ _root_.id t * _root_.id z ∈ span R (p * q)
[PROOFSTEP]
exact subset_span ⟨t, z, hlp ht, hlq hz, rfl⟩
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
x✝ : Submodule.FG (↑toSubmodule S)
t : Finset A
ht : span R ↑t = ↑toSubmodule S
x : A
hx : x ∈ ↑toSubmodule S
⊢ x ∈ span R ↑t
[PROOFSTEP]
rw [ht]
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
x✝ : Submodule.FG (↑toSubmodule S)
t : Finset A
ht : span R ↑t = ↑toSubmodule S
x : A
hx : x ∈ ↑toSubmodule S
⊢ x ∈ ↑toSubmodule S
[PROOFSTEP]
exact hx
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
h : Submodule.FG ⊤
s : Finset A
hs : span R ↑s = ⊤
⊢ ↑toSubmodule (Algebra.adjoin R ↑s) = ↑toSubmodule ⊤
[PROOFSTEP]
rw [Algebra.top_toSubmodule, eq_top_iff, ← hs, span_le]
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
h : Submodule.FG ⊤
s : Finset A
hs : span R ↑s = ⊤
⊢ ↑s ⊆ ↑(↑toSubmodule (Algebra.adjoin R ↑s))
[PROOFSTEP]
exact Algebra.subset_adjoin
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
T : Subalgebra R B
hS : FG S
hT : FG T
⊢ FG (Subalgebra.prod S T)
[PROOFSTEP]
obtain ⟨s, hs⟩ := fg_def.1 hS
[GOAL]
case intro
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
T : Subalgebra R B
hS : FG S
hT : FG T
s : Set A
hs : Set.Finite s ∧ Algebra.adjoin R s = S
⊢ FG (Subalgebra.prod S T)
[PROOFSTEP]
obtain ⟨t, ht⟩ := fg_def.1 hT
[GOAL]
case intro.intro
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
T : Subalgebra R B
hS : FG S
hT : FG T
s : Set A
hs : Set.Finite s ∧ Algebra.adjoin R s = S
t : Set B
ht : Set.Finite t ∧ Algebra.adjoin R t = T
⊢ FG (Subalgebra.prod S T)
[PROOFSTEP]
rw [← hs.2, ← ht.2]
[GOAL]
case intro.intro
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
T : Subalgebra R B
hS : FG S
hT : FG T
s : Set A
hs : Set.Finite s ∧ Algebra.adjoin R s = S
t : Set B
ht : Set.Finite t ∧ Algebra.adjoin R t = T
⊢ FG (Subalgebra.prod (Algebra.adjoin R s) (Algebra.adjoin R t))
[PROOFSTEP]
exact
fg_def.2
⟨LinearMap.inl R A B '' (s ∪ {1}) ∪ LinearMap.inr R A B '' (t ∪ {1}),
Set.Finite.union (Set.Finite.image _ (Set.Finite.union hs.1 (Set.finite_singleton _)))
(Set.Finite.image _ (Set.Finite.union ht.1 (Set.finite_singleton _))),
Algebra.adjoin_inl_union_inr_eq_prod R s t⟩
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
f : A →ₐ[R] B
hs✝ : FG S
s : Finset A
hs : Algebra.adjoin R ↑s = S
⊢ Algebra.adjoin R ↑(Finset.image (↑f) s) = Subalgebra.map f S
[PROOFSTEP]
rw [Finset.coe_image, Algebra.adjoin_image, hs]
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
f : A →ₐ[R] B
hf : Function.Injective ↑f
hs✝ : FG (map f S)
s : Finset B
hs : Algebra.adjoin R ↑s = map f S
⊢ map f
(Algebra.adjoin R
↑(Finset.preimage s ↑f
(_ : ∀ (x : A), x ∈ ↑f ⁻¹' ↑s → ∀ (x_2 : A), x_2 ∈ ↑f ⁻¹' ↑s → ↑f x = ↑f x_2 → x = x_2))) =
map f S
[PROOFSTEP]
rw [← Algebra.adjoin_image, Finset.coe_preimage, Set.image_preimage_eq_of_subset, hs]
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
f : A →ₐ[R] B
hf : Function.Injective ↑f
hs✝ : FG (map f S)
s : Finset B
hs : Algebra.adjoin R ↑s = map f S
⊢ ↑s ⊆ Set.range ↑f
[PROOFSTEP]
rw [← AlgHom.coe_range, ← Algebra.adjoin_le_iff, hs, ← Algebra.map_top]
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
f : A →ₐ[R] B
hf : Function.Injective ↑f
hs✝ : FG (map f S)
s : Finset B
hs : Algebra.adjoin R ↑s = map f S
⊢ map f S ≤ map f ⊤
[PROOFSTEP]
exact map_mono le_top
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
h : FG ⊤
⊢ FG S
[PROOFSTEP]
rw [← S.range_val, ← Algebra.map_top]
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
h : FG ⊤
⊢ FG (map (val S) ⊤)
[PROOFSTEP]
exact FG.map _ h
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
h : FG S
⊢ FG (map (val S) ⊤)
[PROOFSTEP]
rw [Algebra.map_top, range_val]
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁴ : CommSemiring R
inst✝³ : Semiring A
inst✝² : Algebra R A
inst✝¹ : Semiring B
inst✝ : Algebra R B
S : Subalgebra R A
h : FG S
⊢ FG S
[PROOFSTEP]
exact h
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁵ : CommSemiring R
inst✝⁴ : Semiring A
inst✝³ : Algebra R A
inst✝² : Semiring B
inst✝¹ : Algebra R B
inst✝ : IsNoetherian R A
P : Subalgebra R A → Prop
base : P ⊥
ih : ∀ (S : Subalgebra R A) (x : A), P S → P (Algebra.adjoin R (insert x ↑S))
S : Subalgebra R A
⊢ P S
[PROOFSTEP]
classical
obtain ⟨t, rfl⟩ := S.fg_of_noetherian
refine' Finset.induction_on t _ _
· simpa using base
intro x t _ h
rw [Finset.coe_insert]
simpa only [Algebra.adjoin_insert_adjoin] using ih _ x h
[GOAL]
R : Type u
A : Type v
B : Type w
inst✝⁵ : CommSemiring R
inst✝⁴ : Semiring A
inst✝³ : Algebra R A
inst✝² : Semiring B
inst✝¹ : Algebra R B
inst✝ : IsNoetherian R A
P : Subalgebra R A → Prop
base : P ⊥
ih : ∀ (S : Subalgebra R A) (x : A), P S → P (Algebra.adjoin R (insert x ↑S))
S : Subalgebra R A
⊢ P S
[PROOFSTEP]
obtain ⟨t, rfl⟩ := S.fg_of_noetherian
[GOAL]
case intro
R : Type u
A : Type v
B : Type w
inst✝⁵ : CommSemiring R
inst✝⁴ : Semiring A
inst✝³ : Algebra R A
inst✝² : Semiring B
inst✝¹ : Algebra R B
inst✝ : IsNoetherian R A
P : Subalgebra R A → Prop
base : P ⊥
ih : ∀ (S : Subalgebra R A) (x : A), P S → P (Algebra.adjoin R (insert x ↑S))
t : Finset A
⊢ P (Algebra.adjoin R ↑t)
[PROOFSTEP]
refine' Finset.induction_on t _ _
[GOAL]
case intro.refine'_1
R : Type u
A : Type v
B : Type w
inst✝⁵ : CommSemiring R
inst✝⁴ : Semiring A
inst✝³ : Algebra R A
inst✝² : Semiring B
inst✝¹ : Algebra R B
inst✝ : IsNoetherian R A
P : Subalgebra R A → Prop
base : P ⊥
ih : ∀ (S : Subalgebra R A) (x : A), P S → P (Algebra.adjoin R (insert x ↑S))
t : Finset A
⊢ P (Algebra.adjoin R ↑∅)
[PROOFSTEP]
simpa using base
[GOAL]
case intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝⁵ : CommSemiring R
inst✝⁴ : Semiring A
inst✝³ : Algebra R A
inst✝² : Semiring B
inst✝¹ : Algebra R B
inst✝ : IsNoetherian R A
P : Subalgebra R A → Prop
base : P ⊥
ih : ∀ (S : Subalgebra R A) (x : A), P S → P (Algebra.adjoin R (insert x ↑S))
t : Finset A
⊢ ∀ ⦃a : A⦄ {s : Finset A}, ¬a ∈ s → P (Algebra.adjoin R ↑s) → P (Algebra.adjoin R ↑(insert a s))
[PROOFSTEP]
intro x t _ h
[GOAL]
case intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝⁵ : CommSemiring R
inst✝⁴ : Semiring A
inst✝³ : Algebra R A
inst✝² : Semiring B
inst✝¹ : Algebra R B
inst✝ : IsNoetherian R A
P : Subalgebra R A → Prop
base : P ⊥
ih : ∀ (S : Subalgebra R A) (x : A), P S → P (Algebra.adjoin R (insert x ↑S))
t✝ : Finset A
x : A
t : Finset A
a✝ : ¬x ∈ t
h : P (Algebra.adjoin R ↑t)
⊢ P (Algebra.adjoin R ↑(insert x t))
[PROOFSTEP]
rw [Finset.coe_insert]
[GOAL]
case intro.refine'_2
R : Type u
A : Type v
B : Type w
inst✝⁵ : CommSemiring R
inst✝⁴ : Semiring A
inst✝³ : Algebra R A
inst✝² : Semiring B
inst✝¹ : Algebra R B
inst✝ : IsNoetherian R A
P : Subalgebra R A → Prop
base : P ⊥
ih : ∀ (S : Subalgebra R A) (x : A), P S → P (Algebra.adjoin R (insert x ↑S))
t✝ : Finset A
x : A
t : Finset A
a✝ : ¬x ∈ t
h : P (Algebra.adjoin R ↑t)
⊢ P (Algebra.adjoin R (insert x ↑t))
[PROOFSTEP]
simpa only [Algebra.adjoin_insert_adjoin] using ih _ x h
|
[STATEMENT]
lemma pgwt_fun: "public_ground_wf_term t \<Longrightarrow> \<exists>f T. t = Fun f T"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. public_ground_wf_term t \<Longrightarrow> \<exists>f T. t = Fun f T
[PROOF STEP]
using pgwt_ground[of t]
[PROOF STATE]
proof (prove)
using this:
public_ground_wf_term t \<Longrightarrow> fv t = {}
goal (1 subgoal):
1. public_ground_wf_term t \<Longrightarrow> \<exists>f T. t = Fun f T
[PROOF STEP]
by (cases t) auto |
-- Monotonia_de_la_multiplicacion_por_no_negativo.lean
-- Monotonía de la multiplicación por no negativo.
-- José A. Alonso Jiménez
-- Sevilla, 22 de agosto de 2020
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que si a, b y c son números reales tales que
-- 0 ≤ c y a ≤ b, entonces a*c ≤ b*c.
-- ----------------------------------------------------------------------
import data.real.basic
variables {a b c : ℝ}
-- 1ª demostración
-- ===============
example
(hc : 0 ≤ c)
(hab : a ≤ b)
: a * c ≤ b * c :=
begin
rw ← sub_nonneg,
have h : b * c - a * c = (b - a) * c,
{ ring },
{ rw h,
apply mul_nonneg,
{ rw sub_nonneg,
exact hab },
{ exact hc }},
end
-- Comentario: Se ha usado el lema
-- + mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b
-- 2ª demostración
-- ===============
example
(hc : 0 ≤ c)
(hab : a ≤ b)
: a * c ≤ b * c :=
begin
have hab' : 0 ≤ b - a,
{ rw ← sub_nonneg at hab,
exact hab, },
have h1 : 0 ≤ (b - a) * c,
{ exact mul_nonneg hab' hc, },
have h2 : (b - a) * c = b * c - a * c,
{ ring, },
have h3 : 0 ≤ b * c - a * c,
{ rw h2 at h1,
exact h1, },
rw sub_nonneg at h3,
exact h3,
end
-- 3ª demostración
-- ===============
example
(hc : 0 ≤ c)
(hab : a ≤ b)
: a * c ≤ b * c :=
begin
have hab' : 0 ≤ b - a,
{ rwa ← sub_nonneg at hab, },
have h1 : 0 ≤ (b - a) * c,
{ exact mul_nonneg hab' hc },
have h2 : (b - a) * c = b * c - a * c,
{ ring, },
have h3 : 0 ≤ b * c - a * c,
{ rwa h2 at h1, },
rwa sub_nonneg at h3,
end
-- Comentario:
-- + La táctica (rwa h at h'), cuando h es una igualdad. sustituye en la
-- hipótesis h' el término izquierdo de h por el derecho y, a
-- continuación, aplica assumption.
-- + La táctica (rwa ← h at h'), cuando h es una igualdad, sustituye en
-- la hipótesis h' el término derecho de h por el izquierdo y, a
-- continuación, aplica assumption.
-- 4ª demostración
-- ===============
example
(hc : 0 ≤ c)
(hab : a ≤ b)
: a * c ≤ b * c :=
begin
rw ← sub_nonneg,
calc 0 ≤ (b - a)*c : mul_nonneg (by rwa sub_nonneg) hc
... = b*c - a*c : by ring,
end
-- 5ª demostración
-- ===============
example
(hc : 0 ≤ c)
(hab : a ≤ b)
: a * c ≤ b * c :=
mul_mono_nonneg hc hab
-- Comentario: Se usa el lema
-- + mul_mono_nonneg : 0 ≤ c → a ≤ b → a * c ≤ b * c
-- 6ª demostración
-- ===============
example
(hc : 0 ≤ c)
(hab : a ≤ b)
: a * c ≤ b * c :=
by nlinarith
-- Comentario:
-- + La táctica nlinarith es una extensión de linarith con un
-- preprocesamiento que permite resolver problemas aritméticos no
-- lineales.
|
Formal statement is: lemma in_support_on: "x \<in> support_on S f \<longleftrightarrow> x \<in> S \<and> f x \<noteq> 0" Informal statement is: $x$ is in the support of $f$ on $S$ if and only if $x$ is in $S$ and $f(x) \neq 0$. |
Require Import Coq.Lists.List.
Require Import Coq.Strings.String.
Require Export SystemFR.Trees.
Require Export SystemFR.Syntax.
Require Export SystemFR.Tactics.
Inductive base_type: nat -> tree -> tree -> Prop :=
| BTNat: forall X, base_type X T_nat T_nat
| BTUnit: forall X, base_type X T_unit T_unit
| BTBool: forall X, base_type X T_bool T_bool
| BTSum:
forall X A B A0 B0,
base_type X A A0 ->
base_type X B B0 ->
base_type X (T_sum A B) (T_sum A0 B0)
| BTProd:
forall X A B A0 B0,
base_type X A A0 ->
base_type X B B0 ->
base_type X (T_prod A B) (T_prod A0 B0)
| BTId:
forall X A,
~(X ∈ pfv A type_var) ->
is_erased_type A ->
base_type X A A
| BTApprox:
forall X A,
(* X ∈ pfv A type_var -> *)
(* We use this rule only when X belongs to pfv A type_var, but this extra assumption is
not needed for the BaseTypeLemmas proofs *)
base_type X A T_top.
#[export]
Hint Constructors base_type: c_base_type.
|
module NeuralSampling
using Reexport
include("Utils.jl")
@reexport using .Utils
include("BoltzmannNetworks.jl")
@reexport using .BoltzmannNetworks
end # module
|
An intimate portrayal of a journalist, photographer, filmmaker Raymond Depardon as he embarks on a tour of his country with his large format still camera. Unseen narrator is his long time collaborator/wife/Sound recordist Claudine Nougaret. It's both journey through time and intimate portrayal of Depardon and his unending curiosity around the world and at home. Depardon's assembled, mostly handheld reportage takes us to various political hotspots around the world since the 60s - Venesuela, Chilé, Czechoslovakia, Congo, Djibouti, South Africa and a lot more. It also illustrates the artist's obsession with the desert with all it represents. We get to see how Depardon and Nougaret hooked up through various stock footage. It's a great doc that avoids being a sentimental nostalgia piece. Great Saturday morning movie it turns out to be. |
#include "logging.h"
#include <iostream> //for std::clog
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
namespace logging = boost::log;
void initLogging() {
// TODO: include function name, see
// http://en.cppreference.com/w/cpp/utility/source_location/function_name
logging::add_common_attributes();
logging::add_console_log (
std::clog,
logging::keywords::format = "[%ThreadID%] [%Severity%]: %Message%"
);
logging::core::get()->set_filter (
logging::trivial::severity >= logging::trivial::info
);
}
void setSeverityLevel(logging::trivial::severity_level level) {
logging::core::get()->set_filter (
logging::trivial::severity >= level
);
}
|
Formal statement is: lemma dependent_biggerset: fixes S :: "'a::euclidean_space set" shows "(finite S \<Longrightarrow> card S > DIM('a)) \<Longrightarrow> dependent S" Informal statement is: If $S$ is a finite set of vectors in $\mathbb{R}^n$ with more than $n$ elements, then $S$ is linearly dependent. |
Require Export D.
Fixpoint remove_all (v:nat) (s:natlist) : natlist :=
FILL_IN_HERE.
|
[STATEMENT]
lemma bis_imp[simp]:
"\<And> c1 c2. c1 \<approx>s c2 \<Longrightarrow> c1 \<approx>01 c2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>c1 c2. c1 \<approx>s c2 \<Longrightarrow> c1 \<approx>01 c2
[PROOF STEP]
using bis_incl
[PROOF STATE]
proof (prove)
using this:
Sbis \<subseteq> ZObis
goal (1 subgoal):
1. \<And>c1 c2. c1 \<approx>s c2 \<Longrightarrow> c1 \<approx>01 c2
[PROOF STEP]
unfolding bis_defs
[PROOF STATE]
proof (prove)
using this:
gfp Sretr \<subseteq> gfp ZOretr
goal (1 subgoal):
1. \<And>c1 c2. (c1, c2) \<in> gfp Sretr \<Longrightarrow> (c1, c2) \<in> gfp ZOretr
[PROOF STEP]
by auto |
(* Title: Models of Dioids
Author: Alasdair Armstrong, Georg Struth, Tjark Weber
Maintainer: Georg Struth <g.struth at sheffield.ac.uk>
Tjark Weber <tjark.weber at it.uu.se>
*)
section \<open>Models of Dioids\<close>
theory Dioid_Models_New
imports Kleene_Algebra.Dioid
HOL.Real
begin
text \<open>In this section we consider some well known models of
dioids. These so far include the powerset dioid over a monoid,
languages, binary relations, sets of traces, sets paths (in a graph),
as well as the min-plus and the max-plus semirings. Most of these
models are taken from an article about Kleene algebras with
domain~\<^cite>\<open>"desharnaismoellerstruth06kad"\<close>.
The advantage of formally linking these models with the abstract
axiomatisations of dioids is that all abstract theorems are
automatically available in all models. It therefore makes sense to
establish models for the strongest possible axiomatisations (whereas
theorems should be proved for the weakest ones).\<close>
subsection \<open>The Powerset Dioid over a Monoid\<close>
text \<open>We assume a multiplicative monoid and define the usual complex
product on sets of elements. We formalise the well known result that
this lifting induces a dioid.\<close>
(* change here! *)
instantiation set :: (semigroup_mult) semigroup_mult
begin
definition times_set :: "'a set \<Rightarrow> 'a set \<Rightarrow> 'a set" where \<comment> \<open>the complex product\<close>
"times_set A B = {u * v | u v. u \<in> A \<and> v \<in> B}"
instance
apply intro_classes
unfolding times_set_def
by (clarsimp, metis (no_types, opaque_lifting) mult.assoc)
end
instantiation set :: (monoid_mult) monoid_mult
begin
definition one_set :: "'a set" where
"one_set = {1}"
instance
apply intro_classes
unfolding one_set_def times_set_def by auto
end (* instantiation and end of change *)
instantiation set :: (monoid_mult) dioid_one_zero
begin
definition zero_set_def:
"0 = {}"
definition plus_set_def:
"A + B = A \<union> B"
instance
proof
fix X Y Z :: "'a set"
show "X + Y + Z = X + (Y + Z)"
by (simp add: Un_assoc plus_set_def)
show "X + Y = Y + X"
by (simp add: Un_commute plus_set_def)
show "(X + Y) \<cdot> Z = X \<cdot> Z + Y \<cdot> Z"
by (auto simp add: plus_set_def times_set_def)
show "1 \<cdot> X = X"
by (simp add: one_set_def times_set_def)
show "X \<cdot> 1 = X"
by (simp add: one_set_def times_set_def)
show "0 + X = X"
by (simp add: plus_set_def zero_set_def)
show "0 \<cdot> X = 0"
by (simp add: times_set_def zero_set_def)
show "X \<cdot> 0 = 0"
by (simp add: times_set_def zero_set_def)
show "X \<subseteq> Y \<longleftrightarrow> X + Y = Y"
by (simp add: plus_set_def subset_Un_eq)
show "X \<subset> Y \<longleftrightarrow> X \<subseteq> Y \<and> X \<noteq> Y"
by (fact psubset_eq)
show "X + X = X"
by (simp add: Un_absorb plus_set_def)
show "X \<cdot> (Y + Z) = X \<cdot> Y + X \<cdot> Z"
by (auto simp add: plus_set_def times_set_def)
qed
end (* instantiation *)
subsection \<open>Language Dioids\<close>
text \<open>Language dioids arise as special cases of the monoidal lifting
because sets of words form free monoids. Moreover, monoids of words
are isomorphic to monoids of lists under append.
To show that languages form dioids it therefore suffices to show that
sets of lists closed under append and multiplication with the empty
word form a (multiplicative) monoid. Isabelle then does the rest of the work
automatically. Infix~\<open>@\<close> denotes word
concatenation.\<close>
instantiation list :: (type) monoid_mult
begin
definition times_list_def:
"xs * ys \<equiv> xs @ ys"
definition one_list_def:
"1 \<equiv> []"
instance proof
fix xs ys zs :: "'a list"
show "xs * ys * zs = xs * (ys * zs)"
by (simp add: times_list_def)
show "1 * xs = xs"
by (simp add: one_list_def times_list_def)
show "xs * 1 = xs"
by (simp add: one_list_def times_list_def)
qed
end (* instantiation *)
text \<open>Languages as sets of lists have already been formalised in
Isabelle in various places. We can now obtain much of their algebra
for free.\<close>
type_synonym 'a lan = "'a list set"
interpretation lan_dioid: dioid_one_zero "(+)" "(\<cdot>)" "1::'a lan" "0" "(\<subseteq>)" "(\<subset>)" ..
subsection \<open>Relation Dioids\<close>
text \<open>We now show that binary relations under union, relational
composition, the identity relation, the empty relation and set
inclusion form dioids. Due to the well developed relation library of
Isabelle this is entirely trivial.\<close>
interpretation rel_dioid: dioid_one_zero "(\<union>)" "(O)" Id "{}" "(\<subseteq>)" "(\<subset>)"
by (unfold_locales, auto)
interpretation rel_monoid: monoid_mult Id "(O)" ..
subsection \<open>Trace Dioids\<close>
text \<open>Traces have been considered, for instance, by
Kozen~\<^cite>\<open>"kozen00hoare"\<close> in the context of Kleene algebras with
tests. Intuitively, a trace is an execution sequence of a labelled
transition system from some state to some other state, in which state
labels and action labels alternate, and which begin and end with a
state label.
Traces generalise words: words can be obtained from traces by
forgetting state labels. Similarly, sets of traces generalise
languages.
In this section we show that sets of traces under union, an
appropriately defined notion of complex product, the set of all traces
of length zero, the empty set of traces and set inclusion form a
dioid.
We first define the notion of trace and the product of traces, which
has been called \emph{fusion product} by Kozen.\<close>
type_synonym ('p, 'a) trace = "'p \<times> ('a \<times> 'p) list"
definition first :: "('p, 'a) trace \<Rightarrow> 'p" where
"first = fst"
lemma first_conv [simp]: "first (p, xs) = p"
by (unfold first_def, simp)
fun last :: "('p, 'a) trace \<Rightarrow> 'p" where
"last (p, []) = p"
| "last (_, xs) = snd (List.last xs)"
lemma last_append [simp]: "last (p, xs @ ys) = last (last (p, xs), ys)"
proof (cases xs)
show "xs = [] \<Longrightarrow> last (p, xs @ ys) = last (last (p, xs), ys)"
by simp
show "\<And>a list. xs = a # list \<Longrightarrow>
last (p, xs @ ys) = last (last (p, xs), ys)"
proof (cases ys)
show "\<And>a list. \<lbrakk>xs = a # list; ys = []\<rbrakk>
\<Longrightarrow> last (p, xs @ ys) = last (last (p, xs), ys)"
by simp
show "\<And>a list aa lista. \<lbrakk>xs = a # list; ys = aa # lista\<rbrakk>
\<Longrightarrow> last (p, xs @ ys) = last (last (p, xs), ys)"
by simp
qed
qed
text \<open>The fusion product is a partial operation. It is undefined if
the last element of the first trace and the first element of the
second trace are different. If these elements are the same, then the
fusion product removes the first element from the second trace and
appends the resulting object to the first trace.\<close>
definition t_fusion :: "('p, 'a) trace \<Rightarrow> ('p, 'a) trace \<Rightarrow> ('p, 'a) trace" where
"t_fusion x y \<equiv> if last x = first y then (fst x, snd x @ snd y) else undefined"
text \<open>We now show that the first element and the last element of a
trace are a left and right unit for that trace and prove some other
auxiliary lemmas.\<close>
lemma t_fusion_leftneutral [simp]: "t_fusion (first x, []) x = x"
by (cases x, simp add: t_fusion_def)
lemma fusion_rightneutral [simp]: "t_fusion x (last x, []) = x"
by (simp add: t_fusion_def)
lemma first_t_fusion [simp]: "last x = first y \<Longrightarrow> first (t_fusion x y) = first x"
by (simp add: first_def t_fusion_def)
lemma last_t_fusion [simp]: "last x = first y \<Longrightarrow> last (t_fusion x y) = last y"
by (simp add: first_def t_fusion_def)
text \<open>Next we show that fusion of traces is associative.\<close>
lemma t_fusion_assoc [simp]:
"\<lbrakk> last x = first y; last y = first z \<rbrakk> \<Longrightarrow> t_fusion x (t_fusion y z) = t_fusion (t_fusion x y) z"
by (cases x, cases y, cases z, simp add: t_fusion_def)
subsection \<open>Sets of Traces\<close>
text \<open>We now lift the fusion product to a complex product on sets of
traces. This operation is total.\<close>
no_notation
times (infixl "\<cdot>" 70)
definition t_prod :: "('p, 'a) trace set \<Rightarrow> ('p, 'a) trace set \<Rightarrow> ('p, 'a) trace set" (infixl "\<cdot>" 70)
where "X \<cdot> Y = {t_fusion u v| u v. u \<in> X \<and> v \<in> Y \<and> last u = first v}"
text \<open>Next we define the empty set of traces and the set of traces
of length zero as the multiplicative unit of the trace dioid.\<close>
definition t_zero :: "('p, 'a) trace set" where
"t_zero \<equiv> {}"
definition t_one :: "('p, 'a) trace set" where
"t_one \<equiv> \<Union>p. {(p, [])}"
text \<open>We now provide elimination rules for trace products.\<close>
lemma t_prod_iff:
"w \<in> X\<cdot>Y \<longleftrightarrow> (\<exists>u v. w = t_fusion u v \<and> u \<in> X \<and> v \<in> Y \<and> last u = first v)"
by (unfold t_prod_def) auto
lemma t_prod_intro [simp, intro]:
"\<lbrakk> u \<in> X; v \<in> Y; last u = first v \<rbrakk> \<Longrightarrow> t_fusion u v \<in> X\<cdot>Y"
by (meson t_prod_iff)
lemma t_prod_elim [elim]:
"w \<in> X\<cdot>Y \<Longrightarrow> \<exists>u v. w = t_fusion u v \<and> u \<in> X \<and> v \<in> Y \<and> last u = first v"
by (meson t_prod_iff)
text \<open>Finally we prove the interpretation statement that sets of traces
under union and the complex product based on trace fusion together
with the empty set of traces and the set of traces of length one forms
a dioid.\<close>
interpretation trace_dioid: dioid_one_zero "(\<union>)" t_prod t_one t_zero "(\<subseteq>)" "(\<subset>)"
apply unfold_locales
apply (auto simp add: t_prod_def t_one_def t_zero_def t_fusion_def)
apply (metis last_append)
apply (metis last_append append_assoc)
done
no_notation
t_prod (infixl "\<cdot>" 70)
subsection \<open>The Path Diod\<close>
text \<open>The next model we consider are sets of paths in a graph. We
consider two variants, one that contains the empty path and one that
doesn't. The former leads to more difficult proofs and a more involved
specification of the complex product. We start with paths that include
the empty path. In this setting, a path is a list of nodes.\<close>
subsection \<open>Path Models with the Empty Path\<close>
type_synonym 'a path = "'a list"
text \<open>Path fusion is defined similarly to trace
fusion. Mathematically it should be a partial operation. The fusion of
two empty paths yields the empty path; the fusion between a non-empty
path and an empty one is undefined; the fusion of two non-empty paths
appends the tail of the second path to the first one.
We need to use a total alternative and make sure that undefined paths
do not contribute to the complex product.\<close>
fun p_fusion :: "'a path \<Rightarrow> 'a path \<Rightarrow> 'a path" where
"p_fusion [] _ = []"
| "p_fusion _ [] = []"
| "p_fusion ps (q # qs) = ps @ qs"
lemma p_fusion_assoc:
"p_fusion ps (p_fusion qs rs) = p_fusion (p_fusion ps qs) rs"
proof (induct rs)
case Nil show ?case
by (metis p_fusion.elims p_fusion.simps(2))
case Cons show ?case
proof (induct qs)
case Nil show ?case
by (metis neq_Nil_conv p_fusion.simps(1) p_fusion.simps(2))
case Cons show ?case
proof -
have "\<forall>ps. ([] = ps \<or> hd ps # tl ps = ps) \<and> ((\<forall>q qs. q # qs \<noteq> ps) \<or> [] \<noteq> ps)"
using list.collapse by fastforce
moreover hence "\<forall>ps q qs. p_fusion ps (q # qs) = ps @ qs \<or> [] = ps"
by (metis p_fusion.simps(3))
ultimately show ?thesis
by (metis (no_types) Cons_eq_appendI append_eq_appendI p_fusion.simps(1) p_fusion.simps(3))
qed
qed
qed
text \<open>This lemma overapproximates the real situation, but it holds
in all cases where path fusion should be defined.\<close>
lemma p_fusion_last:
assumes "List.last ps = hd qs"
and "ps \<noteq> []"
and "qs \<noteq> []"
shows "List.last (p_fusion ps qs) = List.last qs"
by (metis (opaque_lifting, no_types) List.last.simps List.last_append append_Nil2 assms list.sel(1) neq_Nil_conv p_fusion.simps(3))
lemma p_fusion_hd: "\<lbrakk>ps \<noteq> []; qs \<noteq> []\<rbrakk> \<Longrightarrow> hd (p_fusion ps qs) = hd ps"
by (metis list.exhaust p_fusion.simps(3) append_Cons list.sel(1))
lemma nonempty_p_fusion: "\<lbrakk>ps \<noteq> []; qs \<noteq> []\<rbrakk> \<Longrightarrow> p_fusion ps qs \<noteq> []"
by (metis list.exhaust append_Cons p_fusion.simps(3) list.simps(2))
text \<open>We now define a condition that filters out undefined paths in
the complex product.\<close>
abbreviation p_filter :: "'a path \<Rightarrow> 'a path \<Rightarrow> bool" where
"p_filter ps qs \<equiv> ((ps = [] \<and> qs = []) \<or> (ps \<noteq> [] \<and> qs \<noteq> [] \<and> (List.last ps) = hd qs))"
no_notation
times (infixl "\<cdot>" 70)
definition p_prod :: "'a path set \<Rightarrow> 'a path set \<Rightarrow> 'a path set" (infixl "\<cdot>" 70)
where "X \<cdot> Y = {rs . \<exists>ps \<in> X. \<exists>qs \<in> Y. rs = p_fusion ps qs \<and> p_filter ps qs}"
lemma p_prod_iff:
"ps \<in> X \<cdot> Y \<longleftrightarrow> (\<exists>qs rs. ps = p_fusion qs rs \<and> qs \<in> X \<and> rs \<in> Y \<and> p_filter qs rs)"
by (unfold p_prod_def) auto
text \<open>Due to the complexity of the filter condition, proving
properties of complex products can be tedious.\<close>
lemma p_prod_assoc: "(X \<cdot> Y) \<cdot> Z = X \<cdot> (Y \<cdot> Z)"
proof (rule set_eqI)
fix ps
show "ps \<in> (X \<cdot> Y) \<cdot> Z \<longleftrightarrow> ps \<in> X \<cdot> (Y \<cdot> Z)"
proof (cases ps)
case Nil thus ?thesis
by auto (metis nonempty_p_fusion p_prod_iff)+
next
case Cons thus ?thesis
by (auto simp add: p_prod_iff) (metis (opaque_lifting, mono_tags) nonempty_p_fusion p_fusion_assoc p_fusion_hd p_fusion_last)+
qed
qed
text \<open>We now define the multiplicative unit of the path dioid as the
set of all paths of length one, including the empty path, and show the
unit laws with respect to the path product.\<close>
definition p_one :: "'a path set" where
"p_one \<equiv> {p . \<exists>q::'a. p = [q]} \<union> {[]}"
lemma p_prod_onel [simp]: "p_one \<cdot> X = X"
proof (rule set_eqI)
fix ps
show "ps \<in> p_one \<cdot> X \<longleftrightarrow> ps \<in> X"
proof (cases ps)
case Nil thus ?thesis
by (auto simp add: p_one_def p_prod_def, metis nonempty_p_fusion not_Cons_self)
next
case Cons thus ?thesis
by (auto simp add: p_one_def p_prod_def, metis append_Cons append_Nil list.sel(1) neq_Nil_conv p_fusion.simps(3), metis Cons_eq_appendI list.sel(1) last_ConsL list.simps(3) p_fusion.simps(3) self_append_conv2)
qed
qed
lemma p_prod_oner [simp]: "X \<cdot> p_one = X"
proof (rule set_eqI)
fix ps
show "ps \<in> X \<cdot> p_one \<longleftrightarrow> ps \<in> X"
proof (cases ps)
case Nil thus ?thesis
by (auto simp add: p_one_def p_prod_def, metis nonempty_p_fusion not_Cons_self2, metis p_fusion.simps(1))
next
case Cons thus ?thesis
by (auto simp add: p_one_def p_prod_def, metis append_Nil2 neq_Nil_conv p_fusion.simps(3), metis list.sel(1) list.simps(2) p_fusion.simps(3) self_append_conv)
qed
qed
text \<open>Next we show distributivity laws at the powerset level.\<close>
lemma p_prod_distl: "X \<cdot> (Y \<union> Z) = X \<cdot> Y \<union> X \<cdot> Z"
proof (rule set_eqI)
fix ps
show "ps \<in> X \<cdot> (Y \<union> Z) \<longleftrightarrow> ps \<in> X \<cdot> Y \<union> X \<cdot> Z"
by (cases ps) (auto simp add: p_prod_iff)
qed
lemma p_prod_distr: "(X \<union> Y) \<cdot> Z = X \<cdot> Z \<union> Y \<cdot> Z"
proof (rule set_eqI)
fix ps
show "ps \<in> (X \<union> Y) \<cdot> Z \<longleftrightarrow> ps \<in> X \<cdot> Z \<union> Y \<cdot> Z"
by (cases ps) (auto simp add: p_prod_iff)
qed
text \<open>Finally we show that sets of paths under union, the complex
product, the unit set and the empty set form a dioid.\<close>
interpretation path_dioid: dioid_one_zero "(\<union>)" "(\<cdot>)" p_one "{}" "(\<subseteq>)" "(\<subset>)"
proof
fix x y z :: "'a path set"
show "x \<union> y \<union> z = x \<union> (y \<union> z)"
by auto
show "x \<union> y = y \<union> x"
by auto
show "(x \<cdot> y) \<cdot> z = x \<cdot> (y \<cdot> z)"
by (fact p_prod_assoc)
show "(x \<union> y) \<cdot> z = x \<cdot> z \<union> y \<cdot> z"
by (fact p_prod_distr)
show "p_one \<cdot> x = x"
by (fact p_prod_onel)
show "x \<cdot> p_one = x"
by (fact p_prod_oner)
show "{} \<union> x = x"
by auto
show "{} \<cdot> x = {}"
by (metis all_not_in_conv p_prod_iff)
show "x \<cdot> {} = {}"
by (metis all_not_in_conv p_prod_iff)
show "(x \<subseteq> y) = (x \<union> y = y)"
by auto
show "(x \<subset> y) = (x \<subseteq> y \<and> x \<noteq> y)"
by auto
show "x \<union> x = x"
by auto
show "x \<cdot> (y \<union> z) = x \<cdot> y \<union> x \<cdot> z"
by (fact p_prod_distl)
qed
no_notation
p_prod (infixl "\<cdot>" 70)
subsection \<open>Path Models without the Empty Path\<close>
text \<open>We now build a model of paths that does not include the empty
path and therefore leads to a simpler complex product.\<close>
datatype 'a ppath = Node 'a | Cons 'a "'a ppath"
primrec pp_first :: "'a ppath \<Rightarrow> 'a" where
"pp_first (Node x) = x"
| "pp_first (Cons x _) = x"
primrec pp_last :: "'a ppath \<Rightarrow> 'a" where
"pp_last (Node x) = x"
| "pp_last (Cons _ xs) = pp_last xs"
text \<open>The path fusion product (although we define it as a total
funcion) should only be applied when the last element of the first
argument is equal to the first element of the second argument.\<close>
primrec pp_fusion :: "'a ppath \<Rightarrow> 'a ppath \<Rightarrow> 'a ppath" where
"pp_fusion (Node x) ys = ys"
| "pp_fusion (Cons x xs) ys = Cons x (pp_fusion xs ys)"
text \<open>We now go through the same steps as for traces and paths
before, showing that the first and last element of a trace a left or
right unit for that trace and that the fusion product on traces is
associative.\<close>
lemma pp_fusion_leftneutral [simp]: "pp_fusion (Node (pp_first x)) x = x"
by simp
lemma pp_fusion_rightneutral [simp]: "pp_fusion x (Node (pp_last x)) = x"
by (induct x) simp_all
lemma pp_first_pp_fusion [simp]:
"pp_last x = pp_first y \<Longrightarrow> pp_first (pp_fusion x y) = pp_first x"
by (induct x) simp_all
lemma pp_last_pp_fusion [simp]:
"pp_last x = pp_first y \<Longrightarrow> pp_last (pp_fusion x y) = pp_last y"
by (induct x) simp_all
lemma pp_fusion_assoc [simp]:
"\<lbrakk> pp_last x = pp_first y; pp_last y = pp_first z \<rbrakk> \<Longrightarrow> pp_fusion x (pp_fusion y z) = pp_fusion (pp_fusion x y) z"
by (induct x) simp_all
text \<open>We now lift the path fusion product to a complex product on
sets of paths. This operation is total.\<close>
definition pp_prod :: "'a ppath set \<Rightarrow> 'a ppath set \<Rightarrow> 'a ppath set" (infixl "\<cdot>" 70)
where "X\<cdot>Y = {pp_fusion u v| u v. u \<in> X \<and> v \<in> Y \<and> pp_last u = pp_first v}"
text \<open>Next we define the set of paths of length one as the
multiplicative unit of the path dioid.\<close>
definition pp_one :: "'a ppath set" where
"pp_one \<equiv> range Node"
text \<open>We again provide an
elimination rule.\<close>
lemma pp_prod_iff:
"w \<in> X\<cdot>Y \<longleftrightarrow> (\<exists>u v. w = pp_fusion u v \<and> u \<in> X \<and> v \<in> Y \<and> pp_last u = pp_first v)"
by (unfold pp_prod_def) auto
interpretation ppath_dioid: dioid_one_zero "(\<union>)" "(\<cdot>)" pp_one "{}" "(\<subseteq>)" "(\<subset>)"
proof
fix x y z :: "'a ppath set"
show "x \<union> y \<union> z = x \<union> (y \<union> z)"
by auto
show "x \<union> y = y \<union> x"
by auto
show "x \<cdot> y \<cdot> z = x \<cdot> (y \<cdot> z)"
by (auto simp add: pp_prod_def, metis pp_first_pp_fusion pp_fusion_assoc, metis pp_last_pp_fusion)
show "(x \<union> y) \<cdot> z = x \<cdot> z \<union> y \<cdot> z"
by (auto simp add: pp_prod_def)
show "pp_one \<cdot> x = x"
by (auto simp add: pp_one_def pp_prod_def, metis pp_fusion.simps(1) pp_last.simps(1) rangeI)
show "x \<cdot> pp_one = x"
by (auto simp add: pp_one_def pp_prod_def, metis pp_first.simps(1) pp_fusion_rightneutral rangeI)
show "{} \<union> x = x"
by auto
show "{} \<cdot> x = {}"
by (simp add: pp_prod_def)
show "x \<cdot> {} = {}"
by (simp add: pp_prod_def)
show "x \<subseteq> y \<longleftrightarrow> x \<union> y = y"
by auto
show "x \<subset> y \<longleftrightarrow> x \<subseteq> y \<and> x \<noteq> y"
by auto
show "x \<union> x = x"
by auto
show "x \<cdot> (y \<union> z) = x \<cdot> y \<union> x \<cdot> z"
by (auto simp add: pp_prod_def)
qed
no_notation
pp_prod (infixl "\<cdot>" 70)
subsection \<open>The Distributive Lattice Dioid\<close>
text \<open>A bounded distributive lattice is a distributive lattice with
a least and a greatest element. Using Isabelle's lattice theory file
we define a bounded distributive lattice as an axiomatic type class
and show, using a sublocale statement, that every bounded distributive
lattice is a dioid with one and zero.\<close>
class bounded_distributive_lattice = bounded_lattice + distrib_lattice
sublocale bounded_distributive_lattice \<subseteq> dioid_one_zero sup inf top bot less_eq
proof
fix x y z
show "sup (sup x y) z = sup x (sup y z)"
by (fact sup_assoc)
show "sup x y = sup y x"
by (fact sup.commute)
show "inf (inf x y) z = inf x (inf y z)"
by (metis inf.commute inf.left_commute)
show "inf (sup x y) z = sup (inf x z) (inf y z)"
by (fact inf_sup_distrib2)
show "inf top x = x"
by simp
show "inf x top = x"
by simp
show "sup bot x = x"
by simp
show "inf bot x = bot"
by simp
show "inf x bot = bot"
by simp
show "(x \<le> y) = (sup x y = y)"
by (fact le_iff_sup)
show "(x < y) = (x \<le> y \<and> x \<noteq> y)"
by auto
show "sup x x = x"
by simp
show "inf x (sup y z) = sup (inf x y) (inf x z)"
by (fact inf_sup_distrib1)
qed
subsection \<open>The Boolean Dioid\<close>
text \<open>In this section we show that the booleans form a dioid,
because the booleans form a bounded distributive lattice.\<close>
instantiation bool :: bounded_distributive_lattice
begin
instance ..
end (* instantiation *)
interpretation boolean_dioid: dioid_one_zero sup inf True False less_eq less
by (unfold_locales, simp_all add: inf_bool_def sup_bool_def)
subsection \<open>The Max-Plus Dioid\<close>
text \<open>The following dioids have important applications in
combinatorial optimisations, control theory, algorithm design and
computer networks.\<close>
text \<open>A definition of reals extended with~\<open>+\<infinity>\<close> {\em
and}~\<open>-\<infinity>\<close> may be found in {\em
HOL/Library/Extended\_Real.thy}. Alas, we require separate extensions
with either~\<open>+\<infinity>\<close> or~\<open>-\<infinity>\<close>.\<close>
text \<open>The carrier set of the max-plus semiring is the set of real
numbers extended by minus infinity. The operation of addition is
maximum, the operation of multiplication is addition, the additive
unit is minus infinity and the multiplicative unit is zero.\<close>
datatype mreal = mreal real | MInfty \<comment> \<open>minus infinity\<close>
fun mreal_max where
"mreal_max (mreal x) (mreal y) = mreal (max x y)"
| "mreal_max x MInfty = x"
| "mreal_max MInfty y = y"
lemma mreal_max_simp_3 [simp]: "mreal_max MInfty y = y"
by (cases y, simp_all)
fun mreal_plus where
"mreal_plus (mreal x) (mreal y) = mreal (x + y)"
| "mreal_plus _ _ = MInfty"
text \<open>We now show that the max plus-semiring satisfies the axioms of
selective semirings, from which it follows that it satisfies the dioid
axioms.\<close>
instantiation mreal :: selective_semiring
begin
definition zero_mreal_def:
"0 \<equiv> MInfty"
definition one_mreal_def:
"1 \<equiv> mreal 0"
definition plus_mreal_def:
"x + y \<equiv> mreal_max x y"
definition times_mreal_def:
"x * y \<equiv> mreal_plus x y"
definition less_eq_mreal_def:
"(x::mreal) \<le> y \<equiv> x + y = y"
definition less_mreal_def:
"(x::mreal) < y \<equiv> x \<le> y \<and> x \<noteq> y"
instance
proof
fix x y z :: mreal
show "x + y + z = x + (y + z)"
by (cases x, cases y, cases z, simp_all add: plus_mreal_def)
show "x + y = y + x"
by (cases x, cases y, simp_all add: plus_mreal_def)
show "x * y * z = x * (y * z)"
by (cases x, cases y, cases z, simp_all add: times_mreal_def)
show "(x + y) * z = x * z + y * z"
by (cases x, cases y, cases z, simp_all add: plus_mreal_def times_mreal_def)
show "1 * x = x"
by (cases x, simp_all add: one_mreal_def times_mreal_def)
show "x * 1 = x"
by (cases x, simp_all add: one_mreal_def times_mreal_def)
show "0 + x = x"
by (cases x, simp_all add: plus_mreal_def zero_mreal_def)
show "0 * x = 0"
by (cases x, simp_all add: times_mreal_def zero_mreal_def)
show "x * 0 = 0"
by (cases x, simp_all add: times_mreal_def zero_mreal_def)
show "x \<le> y \<longleftrightarrow> x + y = y"
by (metis less_eq_mreal_def)
show "x < y \<longleftrightarrow> x \<le> y \<and> x \<noteq> y"
by (metis less_mreal_def)
show "x + y = x \<or> x + y = y"
by (cases x, cases y, simp_all add: plus_mreal_def, metis linorder_le_cases max.absorb_iff2 max.absorb1)
show "x * (y + z) = x * y + x * z"
by (cases x, cases y, cases z, simp_all add: plus_mreal_def times_mreal_def) qed
end (* instantiation *)
subsection \<open>The Min-Plus Dioid\<close>
text \<open>The min-plus dioid is also known as {\em tropical
semiring}. Here we need to add a positive infinity to the real
numbers. The procedere follows that of max-plus semirings.\<close>
datatype preal = preal real | PInfty \<comment> \<open>plus infinity\<close>
fun preal_min where
"preal_min (preal x) (preal y) = preal (min x y)"
| "preal_min x PInfty = x"
| "preal_min PInfty y = y"
lemma preal_min_simp_3 [simp]: "preal_min PInfty y = y"
by (cases y, simp_all)
fun preal_plus where
"preal_plus (preal x) (preal y) = preal (x + y)"
| "preal_plus _ _ = PInfty"
instantiation preal :: selective_semiring
begin
definition zero_preal_def:
"0 \<equiv> PInfty"
definition one_preal_def:
"1 \<equiv> preal 0"
definition plus_preal_def:
"x + y \<equiv> preal_min x y"
definition times_preal_def:
"x * y \<equiv> preal_plus x y"
definition less_eq_preal_def:
"(x::preal) \<le> y \<equiv> x + y = y"
definition less_preal_def:
"(x::preal) < y \<equiv> x \<le> y \<and> x \<noteq> y"
instance
proof
fix x y z :: preal
show "x + y + z = x + (y + z)"
by (cases x, cases y, cases z, simp_all add: plus_preal_def)
show "x + y = y + x"
by (cases x, cases y, simp_all add: plus_preal_def)
show "x * y * z = x * (y * z)"
by (cases x, cases y, cases z, simp_all add: times_preal_def)
show "(x + y) * z = x * z + y * z"
by (cases x, cases y, cases z, simp_all add: plus_preal_def times_preal_def)
show "1 * x = x"
by (cases x, simp_all add: one_preal_def times_preal_def)
show "x * 1 = x"
by (cases x, simp_all add: one_preal_def times_preal_def)
show "0 + x = x"
by (cases x, simp_all add: plus_preal_def zero_preal_def)
show "0 * x = 0"
by (cases x, simp_all add: times_preal_def zero_preal_def)
show "x * 0 = 0"
by (cases x, simp_all add: times_preal_def zero_preal_def)
show "x \<le> y \<longleftrightarrow> x + y = y"
by (metis less_eq_preal_def)
show "x < y \<longleftrightarrow> x \<le> y \<and> x \<noteq> y"
by (metis less_preal_def)
show "x + y = x \<or> x + y = y"
by (cases x, cases y, simp_all add: plus_preal_def, metis linorder_le_cases min.absorb2 min.absorb_iff1)
show "x * (y + z) = x * y + x * z"
by (cases x, cases y, cases z, simp_all add: plus_preal_def times_preal_def) qed
end (* instantiation *)
text \<open>Variants of min-plus and max-plus semirings can easily be
obtained. Here we formalise the min-plus semiring over the natural
numbers as an example.\<close>
datatype pnat = pnat nat | PInfty \<comment> \<open>plus infinity\<close>
fun pnat_min where
"pnat_min (pnat x) (pnat y) = pnat (min x y)"
| "pnat_min x PInfty = x"
| "pnat_min PInfty x = x"
lemma pnat_min_simp_3 [simp]: "pnat_min PInfty y = y"
by (cases y, simp_all)
fun pnat_plus where
"pnat_plus (pnat x) (pnat y) = pnat (x + y)"
| "pnat_plus _ _ = PInfty"
instantiation pnat :: selective_semiring
begin
definition zero_pnat_def:
"0 \<equiv> PInfty"
definition one_pnat_def:
"1 \<equiv> pnat 0"
definition plus_pnat_def:
"x + y \<equiv> pnat_min x y"
definition times_pnat_def:
"x * y \<equiv> pnat_plus x y"
definition less_eq_pnat_def:
"(x::pnat) \<le> y \<equiv> x + y = y"
definition less_pnat_def:
"(x::pnat) < y \<equiv> x \<le> y \<and> x \<noteq> y"
lemma zero_pnat_top: "(x::pnat) \<le> 1"
by (cases x, simp_all add: less_eq_pnat_def plus_pnat_def one_pnat_def)
instance
proof
fix x y z :: pnat
show "x + y + z = x + (y + z)"
by (cases x, cases y, cases z, simp_all add: plus_pnat_def)
show "x + y = y + x"
by (cases x, cases y, simp_all add: plus_pnat_def)
show "x * y * z = x * (y * z)"
by (cases x, cases y, cases z, simp_all add: times_pnat_def)
show "(x + y) * z = x * z + y * z"
by (cases x, cases y, cases z, simp_all add: plus_pnat_def times_pnat_def)
show "1 * x = x"
by (cases x, simp_all add: one_pnat_def times_pnat_def)
show "x * 1 = x"
by (cases x, simp_all add: one_pnat_def times_pnat_def)
show "0 + x = x"
by (cases x, simp_all add: plus_pnat_def zero_pnat_def)
show "0 * x = 0"
by (cases x, simp_all add: times_pnat_def zero_pnat_def)
show "x * 0 = 0"
by (cases x, simp_all add: times_pnat_def zero_pnat_def)
show "x \<le> y \<longleftrightarrow> x + y = y"
by (metis less_eq_pnat_def)
show "x < y \<longleftrightarrow> x \<le> y \<and> x \<noteq> y"
by (metis less_pnat_def)
show "x + y = x \<or> x + y = y"
by (cases x, cases y, simp_all add: plus_pnat_def, metis linorder_le_cases min.absorb2 min.absorb_iff1)
show "x * (y + z) = x * y + x * z"
by (cases x, cases y, cases z, simp_all add: plus_pnat_def times_pnat_def)
qed
end (* instantiation *)
end
|
(*
* Copyright 2014, General Dynamics C4 Systems
*
* SPDX-License-Identifier: GPL-2.0-only
*)
theory CSpaceInvPre_AI
imports ArchAcc_AI
begin
context begin interpretation Arch .
requalify_consts
table_cap_ref
empty_table
requalify_facts
empty_table_def
end
lemma set_cap_caps_of_state[wp]:
"\<lbrace>\<lambda>s. P ((caps_of_state s) (ptr \<mapsto> cap))\<rbrace> set_cap cap ptr \<lbrace>\<lambda>rv s. P (caps_of_state s)\<rbrace>"
apply (cases ptr)
apply (clarsimp simp add: set_cap_def split_def)
apply (rule hoare_seq_ext [OF _ get_object_sp])
apply (case_tac obj; simp_all split del: if_split cong: if_cong bind_cong)
apply (wpsimp wp: set_object_wp)
apply (fastforce elim!: rsubst[where P=P]
simp: caps_of_state_cte_wp_at cte_wp_at_cases
fun_upd_def[symmetric] wf_cs_upd obj_at_def)
apply (wpsimp wp: set_object_wp)
apply (clarsimp simp: obj_at_def)
apply (safe elim!: rsubst[where P=P];
rule ext; clarsimp simp: caps_of_state_cte_wp_at cte_wp_at_cases)
apply (auto simp: tcb_cap_cases_def split: if_split_asm)
done
lemmas gen_obj_refs_Int_not =
arg_cong [where f=Not, OF gen_obj_refs_Int, simplified, symmetric]
lemma ObjRef_nonempty_ArchRef_empty:
"x \<in> ObjRef ` (obj_refs c) \<Longrightarrow> ArchRef ` arch_gen_refs c = {}"
by (clarsimp simp: obj_ref_not_arch_gen_ref)
lemma ArchRef_nonempty_ObjRef_empty:
"x \<in> ArchRef ` arch_gen_refs c \<Longrightarrow> ObjRef ` (obj_refs c) = {}"
by (clarsimp simp: arch_gen_ref_not_obj_ref)
lemmas gen_obj_ref_arch_cap_simps =
ObjRef_nonempty_ArchRef_empty[where c="ArchObjectCap ac" for ac, simplified]
ArchRef_nonempty_ObjRef_empty[where c="ArchObjectCap ac" for ac, simplified]
obj_ref_not_arch_gen_ref[where cap="ArchObjectCap ac" for ac, simplified]
arch_gen_ref_not_obj_ref[where cap="ArchObjectCap ac" for ac, simplified]
lemma gen_obj_refs_inD:
"x \<in> gen_obj_refs cap \<Longrightarrow> gen_obj_refs cap = {x}"
apply (case_tac cap; clarsimp simp: gen_obj_refs_def dest!:arch_gen_obj_refs_inD)
apply (auto dest: gen_obj_ref_arch_cap_simps simp: arch_gen_obj_refs_inD)
done
lemma gen_obj_refs_distinct_or_equal:
"\<lbrakk> gen_obj_refs cap \<inter> gen_obj_refs cap' \<noteq> {} \<rbrakk>
\<Longrightarrow> gen_obj_refs cap = gen_obj_refs cap'"
by (clarsimp elim!: nonemptyE dest!: gen_obj_refs_inD)
lemma obj_ref_is_gen_obj_ref:
"x \<in> obj_refs cap \<Longrightarrow> ObjRef x \<in> gen_obj_refs cap"
by (simp add: gen_obj_refs_def)
lemma gen_obj_refs_eq:
"(gen_obj_refs cap = gen_obj_refs cap')
= (obj_refs cap = obj_refs cap' \<and> cap_irqs cap = cap_irqs cap'
\<and> arch_gen_refs cap = arch_gen_refs cap')"
apply (simp add: gen_obj_refs_def image_Un[symmetric])
by auto
lemma not_final_another':
"\<lbrakk> \<not> is_final_cap' cap s; fst (get_cap p s) = {(cap, s)};
gen_obj_refs cap \<noteq> {} \<rbrakk>
\<Longrightarrow> \<exists>p' cap'. p' \<noteq> p \<and> fst (get_cap p' s) = {(cap', s)}
\<and> gen_obj_refs cap' = gen_obj_refs cap
\<and> \<not> is_final_cap' cap' s"
apply (simp add: is_final_cap'_def gen_obj_refs_Int_not cong: conj_cong
del: split_paired_Ex split_paired_All)
apply (erule not_singleton_oneE[where p=p])
apply simp
apply (rule_tac x=p' in exI)
apply clarsimp
apply (drule gen_obj_refs_distinct_or_equal)
apply simp
done
lemma not_final_another_caps:
"\<lbrakk> \<not> is_final_cap' cap s; caps_of_state s p = Some cap;
r \<in> gen_obj_refs cap \<rbrakk>
\<Longrightarrow> \<exists>p' cap'. p' \<noteq> p \<and> caps_of_state s p' = Some cap'
\<and> gen_obj_refs cap' = gen_obj_refs cap
\<and> \<not> is_final_cap' cap' s"
apply (clarsimp dest!: caps_of_state_cteD
simp: cte_wp_at_def)
apply (drule(1) not_final_another')
apply clarsimp
apply clarsimp
apply (subgoal_tac "cte_wp_at ((=) cap') (a, b) s")
apply (fastforce simp: cte_wp_at_caps_of_state)
apply (simp add: cte_wp_at_def)
done
lemma wf_cs_ran_nonempty:
"well_formed_cnode_n sz cs \<Longrightarrow> ran cs \<noteq> {}"
apply (clarsimp simp: well_formed_cnode_n_def)
apply (drule_tac f="\<lambda>S. replicate sz False \<in> S" in arg_cong)
apply auto
done
lemma set_cap_obj_at_impossible:
"\<lbrace>\<lambda>s. P (obj_at P' p s) \<and> (\<forall>ko. P' ko \<longrightarrow> caps_of ko = {})\<rbrace>
set_cap cap ptr
\<lbrace>\<lambda>rv s. P (obj_at P' p s)\<rbrace>"
apply (simp add: set_cap_def split_def set_object_def)
apply (wp get_object_wp | wpc)+
apply (clarsimp simp: obj_at_def)
apply (subgoal_tac "\<forall>sz cs. well_formed_cnode_n sz cs \<longrightarrow> \<not> P' (CNode sz cs)")
apply (subgoal_tac "\<forall>tcb. \<not> P' (TCB tcb)")
apply (clarsimp simp: fun_upd_def[symmetric] wf_cs_insert dom_def)
apply auto[1]
apply (auto simp:caps_of_def cap_of_def ran_tcb_cnode_map wf_cs_ran_nonempty)
done
definition
no_cap_to_obj_with_diff_ref :: "cap \<Rightarrow> cslot_ptr set \<Rightarrow> 'z::state_ext state \<Rightarrow> bool"
where
"no_cap_to_obj_with_diff_ref cap S \<equiv>
\<lambda>s. \<forall>p \<in> UNIV - S. \<not> cte_wp_at (\<lambda>c. obj_refs c = obj_refs cap \<and>
\<not> (table_cap_ref c = table_cap_ref cap)) p s"
lemma empty_table_caps_of:
"empty_table S ko \<Longrightarrow> caps_of ko = {}"
by (cases ko, simp_all add: empty_table_def caps_of_def cap_of_def)
context begin interpretation Arch .
lemma free_index_update_test_function_stuff[simp]:
"cap_asid (src_cap\<lparr>free_index := a\<rparr>) = cap_asid src_cap"
"gen_obj_refs (src_cap\<lparr>free_index := a\<rparr>) = gen_obj_refs src_cap"
"vs_cap_ref (src_cap\<lparr>free_index := a\<rparr>) = vs_cap_ref src_cap"
"untyped_range (cap \<lparr>free_index :=a \<rparr>) = untyped_range cap"
"zobj_refs (c\<lparr>free_index:=a\<rparr>) = zobj_refs c"
"obj_refs (c\<lparr>free_index:=a\<rparr>) = obj_refs c"
by (auto simp: cap_asid_def free_index_update_def vs_cap_ref_def
is_cap_simps gen_obj_refs_def
split: cap.splits arch_cap.splits)
end
end
|
[STATEMENT]
lemma d_OUT_ge_point: "f (x, y) \<le> d_OUT f x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. f (x, y) \<le> d_OUT f x
[PROOF STEP]
by(auto simp add: d_OUT_def intro!: nn_integral_ge_point) |
module Prelude where
infixr 90 _∘_
infixr 50 _∧_
infix 20 _⟸⇒_
infixl 3 _from_
_from_ : (A : Set) -> A -> A
A from a = a
_∘_ : {A B C : Set} -> (A -> B) -> (C -> A) -> C -> B
(f ∘ g) x = f (g x)
record _∧_ (A B : Set) : Set where
field
p₁ : A
p₂ : B
open _∧_ public renaming (p₁ to fst; p₂ to snd)
_,_ : {A B : Set} -> A -> B -> A ∧ B
x , y = record { p₁ = x; p₂ = y }
swap : {A B : Set} -> A ∧ B -> B ∧ A
swap p = (snd p , fst p)
_⇐⇒_ : Set -> Set -> Set
A ⇐⇒ B = (A -> B) ∧ (B -> A)
|
Formal statement is: lemma continuous_on_mult_left: fixes c::"'a::real_normed_algebra" shows "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. c * f x)" Informal statement is: If $f$ is a continuous function on a set $S$, then the function $x \mapsto c f(x)$ is also continuous on $S$. |
[STATEMENT]
lemma delete_keys: "map fst (delete k al) = removeAll k (map fst al)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. map fst (delete k al) = removeAll k (map fst al)
[PROOF STEP]
by (simp add: delete_eq removeAll_filter_not_eq filter_map split_def comp_def) |
Formal statement is: lemma dist_commute: "dist x y = dist y x" Informal statement is: The distance between two points is the same as the distance between those points in the opposite order. |
section "2-3 Finger Trees"
theory FingerTree
imports Main
begin
text \<open>
We implement and prove correct 2-3 finger trees as described by Ralf Hinze
and Ross Paterson\<^cite>\<open>"HiPa06"\<close>.
\<close>
text \<open>
This theory is organized as follows:
Section~\ref{sec:datatype} contains the finger-tree datatype, its invariant
and its abstraction function to lists.
The Section~\ref{sec:operations} contains the operations
on finger trees and their correctness lemmas.
Section~\ref{sec:hide_invar} contains a finger tree datatype with implicit
invariant, and, finally, Section~\ref{sec:doc} contains a documentation
of the implemented operations.
\<close>
text_raw \<open>\paragraph{Technical Issues}\<close>
text \<open>
As Isabelle lacks proper support of namespaces, we
try to simulate namespaces by locales.
The problem is, that we define lots of internal functions that
should not be exposed to the user at all.
Moreover, we define some functions with names equal to names
from Isabelle's standard library. These names make perfect sense
in the context of FingerTrees, however, they shall not be exposed
to anyone using this theory indirectly, hiding the standard library
names there.
Our approach puts all functions and lemmas inside the locale
{\em FingerTree\_loc},
and then interprets this locale with the prefix {\em FingerTree}.
This makes all definitions visible outside the locale, with
qualified names. Inside the locale, however, one can use unqualified names.
\<close>
subsection "Datatype definition"
text_raw\<open>\label{sec:datatype}\<close>
locale FingerTreeStruc_loc
text \<open>
Nodes: Non empty 2-3 trees, with all elements stored within the leafs plus a
cached annotation
\<close>
datatype ('e,'a) Node = Tip 'e 'a |
Node2 'a "('e,'a) Node" "('e,'a) Node" |
Node3 'a "('e,'a) Node" "('e,'a) Node" "('e,'a) Node"
text \<open>Digit: one to four ordered Nodes\<close>
datatype ('e,'a) Digit = One "('e,'a) Node" |
Two "('e,'a) Node" "('e,'a) Node" |
Three "('e,'a) Node" "('e,'a) Node" "('e,'a) Node" |
Four "('e,'a) Node" "('e,'a) Node" "('e,'a) Node" "('e,'a) Node"
text \<open>FingerTreeStruc:
The empty tree, a single node or some nodes and a deeper tree\<close>
datatype ('e, 'a) FingerTreeStruc =
Empty |
Single "('e,'a) Node" |
Deep 'a "('e,'a) Digit" "('e,'a) FingerTreeStruc" "('e,'a) Digit"
subsubsection "Invariant"
context FingerTreeStruc_loc
begin
text_raw \<open>\paragraph{Auxiliary functions}\ \\\<close>
text \<open>Readout the cached annotation of a node\<close>
primrec gmn :: "('e,'a::monoid_add) Node \<Rightarrow> 'a" where
"gmn (Tip e a) = a" |
"gmn (Node2 a _ _) = a" |
"gmn (Node3 a _ _ _) = a"
text \<open>The annotation of a digit is computed on the fly\<close>
primrec gmd :: "('e,'a::monoid_add) Digit \<Rightarrow> 'a" where
"gmd (One a) = gmn a" |
"gmd (Two a b) = (gmn a) + (gmn b)"|
"gmd (Three a b c) = (gmn a) + (gmn b) + (gmn c)"|
"gmd (Four a b c d) = (gmn a) + (gmn b) + (gmn c) + (gmn d)"
text \<open>Readout the cached annotation of a finger tree\<close>
primrec gmft :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> 'a" where
"gmft Empty = 0" |
"gmft (Single nd) = gmn nd" |
"gmft (Deep a _ _ _) = a"
text \<open>Depth and cached annotations have to be correct\<close>
fun is_leveln_node :: "nat \<Rightarrow> ('e,'a) Node \<Rightarrow> bool" where
"is_leveln_node 0 (Tip _ _) \<longleftrightarrow> True" |
"is_leveln_node (Suc n) (Node2 _ n1 n2) \<longleftrightarrow>
is_leveln_node n n1 \<and> is_leveln_node n n2" |
"is_leveln_node (Suc n) (Node3 _ n1 n2 n3) \<longleftrightarrow>
is_leveln_node n n1 \<and> is_leveln_node n n2 \<and> is_leveln_node n n3" |
"is_leveln_node _ _ \<longleftrightarrow> False"
primrec is_leveln_digit :: "nat \<Rightarrow> ('e,'a) Digit \<Rightarrow> bool" where
"is_leveln_digit n (One n1) \<longleftrightarrow> is_leveln_node n n1" |
"is_leveln_digit n (Two n1 n2) \<longleftrightarrow> is_leveln_node n n1 \<and>
is_leveln_node n n2" |
"is_leveln_digit n (Three n1 n2 n3) \<longleftrightarrow> is_leveln_node n n1 \<and>
is_leveln_node n n2 \<and> is_leveln_node n n3" |
"is_leveln_digit n (Four n1 n2 n3 n4) \<longleftrightarrow> is_leveln_node n n1 \<and>
is_leveln_node n n2 \<and> is_leveln_node n n3 \<and> is_leveln_node n n4"
primrec is_leveln_ftree :: "nat \<Rightarrow> ('e,'a) FingerTreeStruc \<Rightarrow> bool" where
"is_leveln_ftree n Empty \<longleftrightarrow> True" |
"is_leveln_ftree n (Single nd) \<longleftrightarrow> is_leveln_node n nd" |
"is_leveln_ftree n (Deep _ l t r) \<longleftrightarrow> is_leveln_digit n l \<and>
is_leveln_digit n r \<and> is_leveln_ftree (Suc n) t"
primrec is_measured_node :: "('e,'a::monoid_add) Node \<Rightarrow> bool" where
"is_measured_node (Tip _ _) \<longleftrightarrow> True" |
"is_measured_node (Node2 a n1 n2) \<longleftrightarrow> ((is_measured_node n1) \<and>
(is_measured_node n2)) \<and> (a = (gmn n1) + (gmn n2))" |
"is_measured_node (Node3 a n1 n2 n3) \<longleftrightarrow> ((is_measured_node n1) \<and>
(is_measured_node n2) \<and> (is_measured_node n3)) \<and>
(a = (gmn n1) + (gmn n2) + (gmn n3))"
primrec is_measured_digit :: "('e,'a::monoid_add) Digit \<Rightarrow> bool" where
"is_measured_digit (One a) = is_measured_node a" |
"is_measured_digit (Two a b) =
((is_measured_node a) \<and> (is_measured_node b))"|
"is_measured_digit (Three a b c) =
((is_measured_node a) \<and> (is_measured_node b) \<and> (is_measured_node c))"|
"is_measured_digit (Four a b c d) = ((is_measured_node a) \<and>
(is_measured_node b) \<and> (is_measured_node c) \<and> (is_measured_node d))"
primrec is_measured_ftree :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> bool" where
"is_measured_ftree Empty \<longleftrightarrow> True" |
"is_measured_ftree (Single n1) \<longleftrightarrow> (is_measured_node n1)" |
"is_measured_ftree (Deep a l m r) \<longleftrightarrow> ((is_measured_digit l) \<and>
(is_measured_ftree m) \<and> (is_measured_digit r)) \<and>
(a = ((gmd l) + (gmft m) + (gmd r)))"
text "Structural invariant for finger trees"
definition "ft_invar t == is_leveln_ftree 0 t \<and> is_measured_ftree t"
subsubsection "Abstraction to Lists"
primrec nodeToList :: "('e,'a) Node \<Rightarrow> ('e \<times> 'a) list" where
"nodeToList (Tip e a) = [(e,a)]"|
"nodeToList (Node2 _ a b) = (nodeToList a) @ (nodeToList b)"|
"nodeToList (Node3 _ a b c)
= (nodeToList a) @ (nodeToList b) @ (nodeToList c)"
primrec digitToList :: "('e,'a) Digit \<Rightarrow> ('e \<times> 'a) list" where
"digitToList (One a) = nodeToList a"|
"digitToList (Two a b) = (nodeToList a) @ (nodeToList b)"|
"digitToList (Three a b c)
= (nodeToList a) @ (nodeToList b) @ (nodeToList c)"|
"digitToList (Four a b c d)
= (nodeToList a) @ (nodeToList b) @ (nodeToList c) @ (nodeToList d)"
text "List representation of a finger tree"
primrec toList :: "('e ,'a) FingerTreeStruc \<Rightarrow> ('e \<times> 'a) list" where
"toList Empty = []"|
"toList (Single a) = nodeToList a"|
"toList (Deep _ pr m sf) = (digitToList pr) @ (toList m) @ (digitToList sf)"
lemma nodeToList_empty: "nodeToList nd \<noteq> Nil"
by (induct nd) auto
lemma digitToList_empty: "digitToList d \<noteq> Nil"
by (cases d, auto simp add: nodeToList_empty)
text \<open>Auxiliary lemmas\<close>
lemma gmn_correct:
assumes "is_measured_node nd"
shows "gmn nd = sum_list (map snd (nodeToList nd))"
by (insert assms, induct nd) (auto simp add: add.assoc)
lemma gmd_correct:
assumes "is_measured_digit d"
shows "gmd d = sum_list (map snd (digitToList d))"
by (insert assms, cases d, auto simp add: gmn_correct add.assoc)
lemma gmft_correct: "is_measured_ftree t
\<Longrightarrow> (gmft t) = sum_list (map snd (toList t))"
by (induct t, auto simp add: ft_invar_def gmd_correct gmn_correct add.assoc)
lemma gmft_correct2: "ft_invar t \<Longrightarrow> (gmft t) = sum_list (map snd (toList t))"
by (simp only: ft_invar_def gmft_correct)
subsection \<open>Operations\<close>
text_raw\<open>\label{sec:operations}\<close>
subsubsection \<open>Empty tree\<close>
lemma Empty_correct[simp]:
"toList Empty = []"
"ft_invar Empty"
by (simp_all add: ft_invar_def)
text \<open>Exactly the empty finger tree represents the empty list\<close>
lemma toList_empty: "toList t = [] \<longleftrightarrow> t = Empty"
by (induct t, auto simp add: nodeToList_empty digitToList_empty)
subsubsection \<open>Annotation\<close>
text "Sum of annotations of all elements of a finger tree"
definition annot :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> 'a"
where "annot t = gmft t"
lemma annot_correct:
"ft_invar t \<Longrightarrow> annot t = sum_list (map snd (toList t))"
using gmft_correct
unfolding annot_def
by (simp add: gmft_correct2)
subsubsection \<open>Appending\<close>
text \<open>Auxiliary functions to fill in the annotations\<close>
definition deep:: "('e,'a::monoid_add) Digit \<Rightarrow> ('e,'a) FingerTreeStruc
\<Rightarrow> ('e,'a) Digit \<Rightarrow> ('e, 'a) FingerTreeStruc" where
"deep pr m sf = Deep ((gmd pr) + (gmft m) + (gmd sf)) pr m sf"
definition node2 where
"node2 nd1 nd2 = Node2 ((gmn nd1)+(gmn nd2)) nd1 nd2"
definition node3 where
"node3 nd1 nd2 nd3 = Node3 ((gmn nd1)+(gmn nd2)+(gmn nd3)) nd1 nd2 nd3"
text "Append a node at the left end"
fun nlcons :: "('e,'a::monoid_add) Node \<Rightarrow> ('e,'a) FingerTreeStruc
\<Rightarrow> ('e,'a) FingerTreeStruc"
where
\<comment> \<open>Recursively we append a node, if the digit is full we push down a node3\<close>
"nlcons a Empty = Single a" |
"nlcons a (Single b) = deep (One a) Empty (One b)" |
"nlcons a (Deep _ (One b) m sf) = deep (Two a b) m sf" |
"nlcons a (Deep _ (Two b c) m sf) = deep (Three a b c) m sf" |
"nlcons a (Deep _ (Three b c d) m sf) = deep (Four a b c d) m sf" |
"nlcons a (Deep _ (Four b c d e) m sf)
= deep (Two a b) (nlcons (node3 c d e) m) sf"
text "Append a node at the right end"
fun nrcons :: "('e,'a::monoid_add) FingerTreeStruc
\<Rightarrow> ('e,'a) Node \<Rightarrow> ('e,'a) FingerTreeStruc" where
\<comment> \<open>Recursively we append a node, if the digit is full we push down a node3\<close>
"nrcons Empty a = Single a" |
"nrcons (Single b) a = deep (One b) Empty (One a)" |
"nrcons (Deep _ pr m (One b)) a = deep pr m (Two b a)"|
"nrcons (Deep _ pr m (Two b c)) a = deep pr m (Three b c a)" |
"nrcons (Deep _ pr m (Three b c d)) a = deep pr m (Four b c d a)" |
"nrcons (Deep _ pr m (Four b c d e)) a
= deep pr (nrcons m (node3 b c d)) (Two e a)"
lemma nlcons_invlevel: "\<lbrakk>is_leveln_ftree n t; is_leveln_node n nd\<rbrakk>
\<Longrightarrow> is_leveln_ftree n (nlcons nd t)"
by (induct t arbitrary: n nd rule: nlcons.induct)
(auto simp add: deep_def node3_def)
lemma nlcons_invmeas: "\<lbrakk>is_measured_ftree t; is_measured_node nd\<rbrakk>
\<Longrightarrow> is_measured_ftree (nlcons nd t)"
by (induct t arbitrary: nd rule: nlcons.induct)
(auto simp add: deep_def node3_def)
lemmas nlcons_inv = nlcons_invlevel nlcons_invmeas
lemma nlcons_list: "toList (nlcons a t) = (nodeToList a) @ (toList t)"
apply (induct t arbitrary: a rule: nlcons.induct)
apply (auto simp add: deep_def toList_def node3_def)
done
lemma nrcons_invmeas: "\<lbrakk>is_measured_ftree t; is_measured_node nd\<rbrakk>
\<Longrightarrow> is_measured_ftree (nrcons t nd)"
apply (induct t nd arbitrary: nd rule:nrcons.induct)
apply(auto simp add: deep_def node3_def)
done
lemmas nrcons_inv = nrcons_invlevel nrcons_invmeas
lemma nrcons_list: "toList (nrcons t a) = (toList t) @ (nodeToList a)"
apply (induct t a arbitrary: a rule: nrcons.induct)
apply (auto simp add: deep_def toList_def node3_def)
done
text "Append an element at the left end"
definition lcons :: "('e \<times> 'a::monoid_add)
\<Rightarrow> ('e,'a) FingerTreeStruc \<Rightarrow> ('e,'a) FingerTreeStruc" (infixr "\<lhd>" 65) where
"a \<lhd> t = nlcons (Tip (fst a) (snd a)) t"
lemma lcons_correct:
assumes "ft_invar t"
shows "ft_invar (a \<lhd> t)" and "toList (a \<lhd> t) = a # (toList t)"
using assms
unfolding ft_invar_def
by (simp_all add: lcons_def nlcons_list nlcons_invlevel nlcons_invmeas)
lemma lcons_inv:"ft_invar t \<Longrightarrow> ft_invar (a \<lhd> t)"
by (rule lcons_correct)
lemma lcons_list[simp]: "toList (a \<lhd> t) = a # (toList t)"
by (simp add: lcons_def nlcons_list)
text "Append an element at the right end"
definition rcons
:: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> ('e \<times> 'a) \<Rightarrow> ('e,'a) FingerTreeStruc"
(infixl "\<rhd>" 65) where
"t \<rhd> a = nrcons t (Tip (fst a) (snd a))"
lemma rcons_correct:
assumes "ft_invar t"
shows "ft_invar (t \<rhd> a)" and "toList (t \<rhd> a) = (toList t) @ [a]"
using assms
by (auto simp add: nrcons_inv ft_invar_def rcons_def nrcons_list)
lemma rcons_inv:"ft_invar t \<Longrightarrow> ft_invar (t \<rhd> a)"
by (rule rcons_correct)
lemma rcons_list[simp]: "toList (t \<rhd> a) = (toList t) @ [a]"
by(auto simp add: nrcons_list rcons_def)
subsubsection \<open>Convert list to tree\<close>
primrec toTree :: "('e \<times> 'a::monoid_add) list \<Rightarrow> ('e,'a) FingerTreeStruc" where
"toTree [] = Empty"|
"toTree (a#xs) = a \<lhd> (toTree xs)"
lemma toTree_correct[simp]:
"ft_invar (toTree l)"
"toList (toTree l) = l"
apply (induct l)
apply (simp add: ft_invar_def)
apply simp
apply (simp add: toTree_def lcons_list lcons_inv)
apply (simp add: toTree_def lcons_list lcons_inv)
done
text \<open>
Note that this lemma is a completeness statement of our implementation,
as it can be read as:
,,All lists of elements have a valid representation as a finger tree.''
\<close>
subsubsection \<open>Detaching leftmost/rightmost element\<close>
primrec digitToTree :: "('e,'a::monoid_add) Digit \<Rightarrow> ('e,'a) FingerTreeStruc"
where
"digitToTree (One a) = Single a"|
"digitToTree (Two a b) = deep (One a) Empty (One b)"|
"digitToTree (Three a b c) = deep (Two a b) Empty (One c)"|
"digitToTree (Four a b c d) = deep (Two a b) Empty (Two c d)"
primrec nodeToDigit :: "('e,'a) Node \<Rightarrow> ('e,'a) Digit" where
"nodeToDigit (Tip e a) = One (Tip e a)"|
"nodeToDigit (Node2 _ a b) = Two a b"|
"nodeToDigit (Node3 _ a b c) = Three a b c"
fun nlistToDigit :: "('e,'a) Node list \<Rightarrow> ('e,'a) Digit" where
"nlistToDigit [a] = One a" |
"nlistToDigit [a,b] = Two a b" |
"nlistToDigit [a,b,c] = Three a b c" |
"nlistToDigit [a,b,c,d] = Four a b c d"
primrec digitToNlist :: "('e,'a) Digit \<Rightarrow> ('e,'a) Node list" where
"digitToNlist (One a) = [a]" |
"digitToNlist (Two a b) = [a,b] " |
"digitToNlist (Three a b c) = [a,b,c]" |
"digitToNlist (Four a b c d) = [a,b,c,d]"
text \<open>Auxiliary function to unwrap a Node element\<close>
primrec n_unwrap:: "('e,'a) Node \<Rightarrow> ('e \<times> 'a)" where
"n_unwrap (Tip e a) = (e,a)"|
"n_unwrap (Node2 _ a b) = undefined"|
"n_unwrap (Node3 _ a b c) = undefined"
type_synonym ('e,'a) ViewnRes = "(('e,'a) Node \<times> ('e,'a) FingerTreeStruc) option"
lemma viewnres_cases:
fixes r :: "('e,'a) ViewnRes"
obtains (Nil) "r=None" |
(Cons) a t where "r=Some (a,t)"
by (cases r) auto
lemma viewnres_split:
"P (case_option f1 (case_prod f2) x) =
((x = None \<longrightarrow> P f1) \<and> (\<forall>a b. x = Some (a,b) \<longrightarrow> P (f2 a b)))"
by (auto split: option.split prod.split)
text \<open>Detach the leftmost node. Return @{const None} on empty finger tree.\<close>
fun viewLn :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> ('e,'a) ViewnRes" where
"viewLn Empty = None"|
"viewLn (Single a) = Some (a, Empty)"|
"viewLn (Deep _ (Two a b) m sf) = Some (a, (deep (One b) m sf))"|
"viewLn (Deep _ (Three a b c) m sf) = Some (a, (deep (Two b c) m sf))"|
"viewLn (Deep _ (Four a b c d) m sf) = Some (a, (deep (Three b c d) m sf))"|
"viewLn (Deep _ (One a) m sf) =
(case viewLn m of
None \<Rightarrow> Some (a, (digitToTree sf)) |
Some (b, m2) \<Rightarrow> Some (a, (deep (nodeToDigit b) m2 sf)))"
text \<open>Detach the rightmost node. Return @{const None} on empty finger tree.\<close>
fun viewRn :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> ('e,'a) ViewnRes" where
"viewRn Empty = None" |
"viewRn (Single a) = Some (a, Empty)" |
"viewRn (Deep _ pr m (Two a b)) = Some (b, (deep pr m (One a)))" |
"viewRn (Deep _ pr m (Three a b c)) = Some (c, (deep pr m (Two a b)))" |
"viewRn (Deep _ pr m (Four a b c d)) = Some (d, (deep pr m (Three a b c)))" |
"viewRn (Deep _ pr m (One a)) =
(case viewRn m of
None \<Rightarrow> Some (a, (digitToTree pr))|
Some (b, m2) \<Rightarrow> Some (a, (deep pr m2 (nodeToDigit b))))"
(* TODO: Head, last geht auch in O(1) !!! *)
lemma
digitToTree_inv: "is_leveln_digit n d \<Longrightarrow> is_leveln_ftree n (digitToTree d)"
"is_measured_digit d \<Longrightarrow> is_measured_ftree (digitToTree d)"
apply (cases d,auto simp add: deep_def)
apply (cases d,auto simp add: deep_def)
done
lemma digitToTree_list: "toList (digitToTree d) = digitToList d"
by (cases d) (auto simp add: deep_def)
lemma nodeToDigit_inv:
"is_leveln_node (Suc n) nd \<Longrightarrow> is_leveln_digit n (nodeToDigit nd) "
"is_measured_node nd \<Longrightarrow> is_measured_digit (nodeToDigit nd)"
by (cases nd, auto) (cases nd, auto)
lemma nodeToDigit_list: "digitToList (nodeToDigit nd) = nodeToList nd"
by (cases nd,auto)
lemma viewLn_empty: "t \<noteq> Empty \<longleftrightarrow> (viewLn t) \<noteq> None"
proof (cases t)
case Empty thus ?thesis by simp
next
case (Single Node) thus ?thesis by simp
next
case (Deep a l x r) thus ?thesis
apply(auto)
apply(case_tac l)
apply(auto)
apply(cases "viewLn x")
apply(auto)
done
qed
lemma viewLn_inv: "\<lbrakk>
is_measured_ftree t; is_leveln_ftree n t; viewLn t = Some (nd, s)
\<rbrakk> \<Longrightarrow> is_measured_ftree s \<and> is_measured_node nd \<and>
is_leveln_ftree n s \<and> is_leveln_node n nd"
apply(induct t arbitrary: n nd s rule: viewLn.induct)
apply(simp add: viewLn_empty)
apply(simp)
apply(auto simp add: deep_def)[1]
apply(auto simp add: deep_def)[1]
apply(auto simp add: deep_def)[1]
proof -
fix ux a m sf n nd s
assume av: "\<And>n nd s.
\<lbrakk>is_measured_ftree m; is_leveln_ftree n m; viewLn m = Some (nd, s)\<rbrakk>
\<Longrightarrow> is_measured_ftree s \<and>
is_measured_node nd \<and> is_leveln_ftree n s \<and> is_leveln_node n nd "
" is_measured_ftree (Deep ux (One a) m sf) "
"is_leveln_ftree n (Deep ux (One a) m sf)"
"viewLn (Deep ux (One a) m sf) = Some (nd, s)"
thus "is_measured_ftree s \<and>
is_measured_node nd \<and> is_leveln_ftree n s \<and> is_leveln_node n nd"
proof (cases "viewLn m" rule: viewnres_cases)
case Nil
with av(4) have v1: "nd = a" "s = digitToTree sf"
by auto
from v1 av(2,3) show "is_measured_ftree s \<and>
is_measured_node nd \<and> is_leveln_ftree n s \<and> is_leveln_node n nd"
apply(auto)
apply(auto simp add: digitToTree_inv)
done
next
case (Cons b m2)
with av(4) have v2: "nd = a" "s = (deep (nodeToDigit b) m2 sf)"
apply (auto simp add: deep_def)
done
note myiv = av(1)[of "Suc n" b m2]
from v2 av(2,3) have "is_measured_ftree m \<and> is_leveln_ftree (Suc n) m"
apply(simp)
done
hence bv: "is_measured_ftree m2 \<and>
is_measured_node b \<and> is_leveln_ftree (Suc n) m2 \<and> is_leveln_node (Suc n) b"
using myiv Cons
apply(simp)
done
with av(2,3) v2 show "is_measured_ftree s \<and>
is_measured_node nd \<and> is_leveln_ftree n s \<and> is_leveln_node n nd"
apply(auto simp add: deep_def nodeToDigit_inv)
done
qed
qed
lemma viewLn_list: " viewLn t = Some (nd, s)
\<Longrightarrow> toList t = (nodeToList nd) @ (toList s)"
supply [[simproc del: defined_all]]
apply(induct t arbitrary: nd s rule: viewLn.induct)
apply(simp)
apply(simp)
apply(simp)
apply(simp add: deep_def)
apply(auto simp add: toList_def)[1]
apply(simp)
apply(simp add: deep_def)
apply(auto simp add: toList_def)[1]
apply(simp)
apply(simp add: deep_def)
apply(auto simp add: toList_def)[1]
apply(simp)
subgoal premises prems for a m sf nd s
using prems
proof (cases "viewLn m" rule: viewnres_cases)
case Nil
hence av: "m = Empty" by (metis viewLn_empty)
from av prems
show "nodeToList a @ toList m @ digitToList sf = nodeToList nd @ toList s"
by (auto simp add: digitToTree_list)
next
case (Cons b m2)
with prems have bv: "nd = a" "s = (deep (nodeToDigit b) m2 sf)"
by (auto simp add: deep_def)
with Cons prems
show "nodeToList a @ toList m @ digitToList sf = nodeToList nd @ toList s"
apply(simp)
apply(simp add: deep_def)
apply(simp add: deep_def nodeToDigit_list)
done
qed
done
lemma viewRn_empty: "t \<noteq> Empty \<longleftrightarrow> (viewRn t) \<noteq> None"
proof (cases t)
case Empty thus ?thesis by simp
next
case (Single Node) thus ?thesis by simp
next
case (Deep a l x r) thus ?thesis
apply(auto)
apply(case_tac r)
apply(auto)
apply(cases "viewRn x")
apply(auto)
done
qed
lemma viewRn_inv: "\<lbrakk>
is_measured_ftree t; is_leveln_ftree n t; viewRn t = Some (nd, s)
\<rbrakk> \<Longrightarrow> is_measured_ftree s \<and> is_measured_node nd \<and>
is_leveln_ftree n s \<and> is_leveln_node n nd"
apply(induct t arbitrary: n nd s rule: viewRn.induct)
apply(simp add: viewRn_empty)
apply(simp)
apply(auto simp add: deep_def)[1]
apply(auto simp add: deep_def)[1]
apply(auto simp add: deep_def)[1]
proof -
fix ux a m "pr" n nd s
assume av: "\<And>n nd s.
\<lbrakk>is_measured_ftree m; is_leveln_ftree n m; viewRn m = Some (nd, s)\<rbrakk>
\<Longrightarrow> is_measured_ftree s \<and>
is_measured_node nd \<and> is_leveln_ftree n s \<and> is_leveln_node n nd "
" is_measured_ftree (Deep ux pr m (One a)) "
"is_leveln_ftree n (Deep ux pr m (One a))"
"viewRn (Deep ux pr m (One a)) = Some (nd, s)"
thus "is_measured_ftree s \<and>
is_measured_node nd \<and> is_leveln_ftree n s \<and> is_leveln_node n nd"
proof (cases "viewRn m" rule: viewnres_cases)
case Nil
with av(4) have v1: "nd = a" "s = digitToTree pr"
by auto
from v1 av(2,3) show "is_measured_ftree s \<and>
is_measured_node nd \<and> is_leveln_ftree n s \<and> is_leveln_node n nd"
apply(auto)
apply(auto simp add: digitToTree_inv)
done
next
case (Cons b m2)
with av(4) have v2: "nd = a" "s = (deep pr m2 (nodeToDigit b))"
apply (auto simp add: deep_def)
done
note myiv = av(1)[of "Suc n" b m2]
from v2 av(2,3) have "is_measured_ftree m \<and> is_leveln_ftree (Suc n) m"
apply(simp)
done
hence bv: "is_measured_ftree m2 \<and>
is_measured_node b \<and> is_leveln_ftree (Suc n) m2 \<and> is_leveln_node (Suc n) b"
using myiv Cons
apply(simp)
done
with av(2,3) v2 show "is_measured_ftree s \<and>
is_measured_node nd \<and> is_leveln_ftree n s \<and> is_leveln_node n nd"
apply(auto simp add: deep_def nodeToDigit_inv)
done
qed
qed
lemma viewRn_list: "viewRn t = Some (nd, s)
\<Longrightarrow> toList t = (toList s) @ (nodeToList nd)"
supply [[simproc del: defined_all]]
apply(induct t arbitrary: nd s rule: viewRn.induct)
apply(simp)
apply(simp)
apply(simp)
apply(simp add: deep_def)
apply(auto simp add: toList_def)[1]
apply(simp)
apply(simp add: deep_def)
apply(auto simp add: toList_def)[1]
apply(simp)
apply(simp add: deep_def)
apply(auto simp add: toList_def)[1]
apply(simp)
subgoal premises prems for pr m a nd s
proof (cases "viewRn m" rule: viewnres_cases)
case Nil
from Nil have av: "m = Empty" by (metis viewRn_empty)
from av prems
show "digitToList pr @ toList m @ nodeToList a = toList s @ nodeToList nd"
by (auto simp add: digitToTree_list)
next
case (Cons b m2)
with prems have bv: "nd = a" "s = (deep pr m2 (nodeToDigit b))"
apply(auto simp add: deep_def) done
with Cons prems
show "digitToList pr @ toList m @ nodeToList a = toList s @ nodeToList nd"
apply(simp)
apply(simp add: deep_def)
apply(simp add: deep_def nodeToDigit_list)
done
qed
done
type_synonym ('e,'a) viewres = "(('e \<times>'a) \<times> ('e,'a) FingerTreeStruc) option"
text \<open>Detach the leftmost element. Return @{const None} on empty finger tree.\<close>
definition viewL :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> ('e,'a) viewres"
where
"viewL t = (case viewLn t of
None \<Rightarrow> None |
(Some (a, t2)) \<Rightarrow> Some ((n_unwrap a), t2))"
lemma viewL_correct:
assumes INV: "ft_invar t"
shows
"(t=Empty \<Longrightarrow> viewL t = None)"
"(t\<noteq>Empty \<Longrightarrow> (\<exists>a s. viewL t = Some (a, s) \<and> ft_invar s
\<and> toList t = a # toList s))"
proof -
assume "t=Empty" thus "viewL t = None" by (simp add: viewL_def)
next
assume NE: "t \<noteq> Empty"
from INV have INV': "is_leveln_ftree 0 t" "is_measured_ftree t"
by (simp_all add: ft_invar_def)
from NE have v1: "viewLn t \<noteq> None" by (auto simp add: viewLn_empty)
then obtain nd s where vn: "viewLn t = Some (nd, s)"
by (cases "viewLn t") (auto)
from this obtain a where v1: "viewL t = Some (a, s)"
by (auto simp add: viewL_def)
from INV' vn have
v2: "is_measured_ftree s \<and> is_leveln_ftree 0 s
\<and> is_leveln_node 0 nd \<and> is_measured_node nd"
"toList t = (nodeToList nd) @ (toList s)"
by (auto simp add: viewLn_inv[of t 0 nd s] viewLn_list[of t])
with v1 vn have v3: "nodeToList nd = [a]"
apply (auto simp add: viewL_def )
apply (induct nd)
apply (simp_all (no_asm_use))
done
with v1 v2
show "\<exists>a s. viewL t = Some (a, s) \<and> ft_invar s \<and> toList t = a # toList s"
by (auto simp add: ft_invar_def)
qed
lemma viewL_correct_empty[simp]: "viewL Empty = None"
by (simp add: viewL_def)
lemma viewL_correct_nonEmpty:
assumes "ft_invar t" "t \<noteq> Empty"
obtains a s where
"viewL t = Some (a, s)" "ft_invar s" "toList t = a # toList s"
using assms viewL_correct by blast
text \<open>Detach the rightmost element. Return @{const None} on empty finger tree.\<close>
definition viewR :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> ('e,'a) viewres"
where
"viewR t = (case viewRn t of
None \<Rightarrow> None |
(Some (a, t2)) \<Rightarrow> Some ((n_unwrap a), t2))"
lemma viewR_correct:
assumes INV: "ft_invar t"
shows
"(t = Empty \<Longrightarrow> viewR t = None)"
"(t \<noteq> Empty \<Longrightarrow> (\<exists> a s. viewR t = Some (a, s) \<and> ft_invar s
\<and> toList t = toList s @ [a]))"
proof -
assume "t=Empty" thus "viewR t = None" by (simp add: viewR_def)
next
assume NE: "t \<noteq> Empty"
from INV have INV': "is_leveln_ftree 0 t" "is_measured_ftree t"
unfolding ft_invar_def by simp_all
from NE have v1: "viewRn t \<noteq> None" by (auto simp add: viewRn_empty)
then obtain nd s where vn: "viewRn t = Some (nd, s)"
by (cases "viewRn t") (auto)
from this obtain a where v1: "viewR t = Some (a, s)"
by (auto simp add: viewR_def)
from INV' vn have
v2: "is_measured_ftree s \<and> is_leveln_ftree 0 s
\<and> is_leveln_node 0 nd \<and> is_measured_node nd"
"toList t = (toList s) @ (nodeToList nd)"
by (auto simp add: viewRn_inv[of t 0 nd s] viewRn_list[of t])
with v1 vn have v3: "nodeToList nd = [a]"
apply (auto simp add: viewR_def )
apply (induct nd)
apply (simp_all (no_asm_use))
done
with v1 v2
show "\<exists>a s. viewR t = Some (a, s) \<and> ft_invar s \<and> toList t = toList s @ [a]"
unfolding ft_invar_def by auto
qed
lemma viewR_correct_empty[simp]: "viewR Empty = None"
unfolding viewR_def by simp
text \<open>Finger trees viewed as a double-ended queue. The head and tail functions
here are only
defined for non-empty queues, while the view-functions were also defined for
empty finger trees.\<close>
text "Check for emptiness"
definition isEmpty :: "('e,'a) FingerTreeStruc \<Rightarrow> bool" where
[code del]: "isEmpty t = (t = Empty)"
lemma isEmpty_correct: "isEmpty t \<longleftrightarrow> toList t = []"
unfolding isEmpty_def by (simp add: toList_empty)
\<comment> \<open>Avoid comparison with @{text "(=)"}, and thus unnecessary equality-class
parameter on element types in generated code\<close>
text "Leftmost element"
definition head :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> 'e \<times> 'a" where
"head t = (case viewL t of (Some (a, _)) \<Rightarrow> a)"
text "All but the leftmost element"
definition tail
:: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> ('e,'a) FingerTreeStruc"
where
"tail t = (case viewL t of (Some (_, m)) \<Rightarrow> m)"
lemma tail_correct:
assumes "ft_invar t" "t \<noteq> Empty"
shows "toList (tail t) = tl (toList t)" and "ft_invar (tail t)"
proof -
from assms viewL_correct
obtain a s where
v1:"viewL t = Some (a, s) \<and> ft_invar s \<and> toList t = a # toList s" by blast
hence v2: "tail t = s" by (auto simp add: tail_def)
from v1 have "tl (toList t) = toList s" by simp
with v1 v2 show
"toList (tail t) = tl (toList t)"
"ft_invar (tail t)"
by simp_all
qed
text "Rightmost element"
definition headR :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> 'e \<times> 'a" where
"headR t = (case viewR t of (Some (a, _)) \<Rightarrow> a)"
lemma headR_correct:
assumes "ft_invar t" "t \<noteq> Empty"
shows "headR t = last (toList t)"
proof -
from assms viewR_correct
obtain a s where
v1:"viewR t = Some (a, s) \<and> ft_invar s \<and> toList t = toList s @ [a]" by blast
hence v2: "headR t = a" by (auto simp add: headR_def)
with v1 show ?thesis by auto
qed
text "All but the rightmost element"
definition tailR
:: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> ('e,'a) FingerTreeStruc"
where
"tailR t = (case viewR t of (Some (_, m)) \<Rightarrow> m)"
subsubsection \<open>Concatenation\<close>
primrec lconsNlist :: "('e,'a::monoid_add) Node list
\<Rightarrow> ('e,'a) FingerTreeStruc \<Rightarrow> ('e,'a) FingerTreeStruc" where
"lconsNlist [] t = t" |
"lconsNlist (x#xs) t = nlcons x (lconsNlist xs t)"
primrec rconsNlist :: "('e,'a::monoid_add) FingerTreeStruc
\<Rightarrow> ('e,'a) Node list \<Rightarrow> ('e,'a) FingerTreeStruc" where
"rconsNlist t [] = t" |
"rconsNlist t (x#xs) = rconsNlist (nrcons t x) xs"
fun nodes :: "('e,'a::monoid_add) Node list \<Rightarrow> ('e,'a) Node list" where
"nodes [a, b] = [node2 a b]" |
"nodes [a, b, c] = [node3 a b c]" |
"nodes [a,b,c,d] = [node2 a b, node2 c d]" |
"nodes (a#b#c#xs) = (node3 a b c) # (nodes xs)"
text \<open>Recursively we concatenate two FingerTreeStrucs while we keep the
inner Nodes in a list\<close>
fun app3 :: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> ('e,'a) Node list
\<Rightarrow> ('e,'a) FingerTreeStruc \<Rightarrow> ('e,'a) FingerTreeStruc" where
"app3 Empty xs t = lconsNlist xs t" |
"app3 t xs Empty = rconsNlist t xs" |
"app3 (Single x) xs t = nlcons x (lconsNlist xs t)" |
"app3 t xs (Single x) = nrcons (rconsNlist t xs) x" |
"app3 (Deep _ pr1 m1 sf1) ts (Deep _ pr2 m2 sf2) =
deep pr1 (app3 m1
(nodes ((digitToNlist sf1) @ ts @ (digitToNlist pr2))) m2) sf2"
lemma lconsNlist_inv:
assumes "is_leveln_ftree n t"
and "is_measured_ftree t"
and "\<forall> x\<in>set xs. (is_leveln_node n x \<and> is_measured_node x)"
shows
"is_leveln_ftree n (lconsNlist xs t) \<and> is_measured_ftree (lconsNlist xs t)"
by (insert assms, induct xs, auto simp add: nlcons_invlevel nlcons_invmeas)
lemma rconsNlist_inv:
assumes "is_leveln_ftree n t"
and "is_measured_ftree t"
and "\<forall> x\<in>set xs. (is_leveln_node n x \<and> is_measured_node x)"
shows
"is_leveln_ftree n (rconsNlist t xs) \<and> is_measured_ftree (rconsNlist t xs)"
by (insert assms, induct xs arbitrary: t,
auto simp add: nrcons_invlevel nrcons_invmeas)
lemma nodes_inv:
assumes "\<forall> x \<in> set ts. is_leveln_node n x \<and> is_measured_node x"
and "length ts \<ge> 2"
shows "\<forall> x \<in> set (nodes ts). is_leveln_node (Suc n) x \<and> is_measured_node x"
proof (insert assms, induct ts rule: nodes.induct)
case (1 a b)
thus ?case by (simp add: node2_def)
next
case (2 a b c)
thus ?case by (simp add: node3_def)
next
case (3 a b c d)
thus ?case by (simp add: node2_def)
next
case (4 a b c v vb vc)
thus ?case by (simp add: node3_def)
next
show "\<lbrakk>\<forall>x\<in>set []. is_leveln_node n x \<and> is_measured_node x; 2 \<le> length []\<rbrakk>
\<Longrightarrow> \<forall>x\<in>set (nodes []). is_leveln_node (Suc n) x \<and> is_measured_node x"
by simp
next
show
"\<And>v. \<lbrakk>\<forall>x\<in>set [v]. is_leveln_node n x \<and> is_measured_node x; 2 \<le> length [v]\<rbrakk>
\<Longrightarrow> \<forall>x\<in>set (nodes [v]). is_leveln_node (Suc n) x \<and> is_measured_node x"
by simp
qed
lemma nodes_inv2:
assumes "is_leveln_digit n sf1"
and "is_measured_digit sf1"
and "is_leveln_digit n pr2"
and "is_measured_digit pr2"
and "\<forall> x \<in> set ts. is_leveln_node n x \<and> is_measured_node x"
shows
"\<forall>x\<in>set (nodes (digitToNlist sf1 @ ts @ digitToNlist pr2)).
is_leveln_node (Suc n) x \<and> is_measured_node x"
proof -
have v1:" \<forall>x\<in>set (digitToNlist sf1 @ ts @ digitToNlist pr2).
is_leveln_node n x \<and> is_measured_node x"
using assms
apply (simp add: digitToNlist_def)
apply (cases sf1)
apply (cases pr2)
apply simp_all
apply (cases pr2)
apply (simp_all)
apply (cases pr2)
apply (simp_all)
apply (cases pr2)
apply (simp_all)
done
have v2: "length (digitToNlist sf1 @ ts @ digitToNlist pr2) \<ge> 2"
apply (cases sf1)
apply (cases pr2)
apply simp_all
done
thus ?thesis
using v1 nodes_inv[of "digitToNlist sf1 @ ts @ digitToNlist pr2"]
by blast
qed
lemma app3_inv:
assumes "is_leveln_ftree n t1"
and "is_leveln_ftree n t2"
and "is_measured_ftree t1"
and "is_measured_ftree t2"
and "\<forall> x\<in>set xs. (is_leveln_node n x \<and> is_measured_node x)"
shows "is_leveln_ftree n (app3 t1 xs t2) \<and> is_measured_ftree (app3 t1 xs t2)"
proof (insert assms, induct t1 xs t2 arbitrary: n rule: app3.induct)
case (1 xs t n)
thus ?case using lconsNlist_inv by simp
next
case "2_1"
thus ?case by (simp add: rconsNlist_inv)
next
case "2_2"
thus ?case by (simp add: lconsNlist_inv rconsNlist_inv)
next
case "3_1"
thus ?case by (simp add: lconsNlist_inv nlcons_invlevel nlcons_invmeas )
next
case "3_2"
thus ?case
by (simp only: app3.simps)
(simp add: lconsNlist_inv nlcons_invlevel nlcons_invmeas)
next
case 4
thus ?case
by (simp only: app3.simps)
(simp add: rconsNlist_inv nrcons_invlevel nrcons_invmeas)
next
case (5 uu pr1 m1 sf1 ts uv pr2 m2 sf2 n)
thus ?case
proof -
have v1: "is_leveln_ftree (Suc n) m1"
and v2: "is_leveln_ftree (Suc n) m2"
using "5.prems" by (simp_all add: is_leveln_ftree_def)
have v3: "is_measured_ftree m1"
and v4: "is_measured_ftree m2"
using "5.prems" by (simp_all add: is_measured_ftree_def)
have v5: "is_leveln_digit n sf1"
"is_measured_digit sf1"
"is_leveln_digit n pr2"
"is_measured_digit pr2"
"\<forall>x\<in>set ts. is_leveln_node n x \<and> is_measured_node x"
using "5.prems"
by (simp_all add: is_leveln_ftree_def is_measured_ftree_def)
note v6 = nodes_inv2[OF v5]
note v7 = "5.hyps"[OF v1 v2 v3 v4 v6]
have v8: "is_leveln_digit n sf2"
"is_measured_digit sf2"
"is_leveln_digit n pr1"
"is_measured_digit pr1"
using "5.prems"
by (simp_all add: is_leveln_ftree_def is_measured_ftree_def)
show ?thesis using v7 v8
by (simp add: is_leveln_ftree_def is_measured_ftree_def deep_def)
qed
qed
primrec nlistToList:: "(('e, 'a) Node) list \<Rightarrow> ('e \<times> 'a) list" where
"nlistToList [] = []"|
"nlistToList (x#xs) = (nodeToList x) @ (nlistToList xs)"
lemma nodes_list: "length xs \<ge> 2 \<Longrightarrow> nlistToList (nodes xs) = nlistToList xs"
by (induct xs rule: nodes.induct) (auto simp add: node2_def node3_def)
lemma nlistToList_app:
"nlistToList (xs@ys) = (nlistToList xs) @ (nlistToList ys)"
by (induct xs arbitrary: ys, simp_all)
lemma nlistListLCons: "toList (lconsNlist xs t) = (nlistToList xs) @ (toList t)"
by (induct xs) (auto simp add: nlcons_list)
lemma nlistListRCons: "toList (rconsNlist t xs) = (toList t) @ (nlistToList xs)"
by (induct xs arbitrary: t) (auto simp add: nrcons_list)
lemma app3_list_lem1:
"nlistToList (nodes (digitToNlist sf1 @ ts @ digitToNlist pr2)) =
digitToList sf1 @ nlistToList ts @ digitToList pr2"
proof -
have len1: "length (digitToNlist sf1 @ ts @ digitToNlist pr2) \<ge> 2"
by (cases sf1,cases pr2,simp_all)
have "(nlistToList (digitToNlist sf1 @ ts @ digitToNlist pr2))
= (digitToList sf1 @ nlistToList ts @ digitToList pr2)"
apply (cases sf1, cases pr2)
apply (simp_all add: nlistToList_app)
apply (cases pr2, auto)
apply (cases pr2, auto)
apply (cases pr2, auto)
done
with nodes_list[OF len1] show ?thesis by simp
qed
lemma app3_list:
"toList (app3 t1 xs t2) = (toList t1) @ (nlistToList xs) @ (toList t2)"
apply (induct t1 xs t2 rule: app3.induct)
apply (simp_all add: nlistListLCons nlistListRCons nlcons_list nrcons_list)
apply (simp add: app3_list_lem1 deep_def)
done
definition app
:: "('e,'a::monoid_add) FingerTreeStruc \<Rightarrow> ('e,'a) FingerTreeStruc
\<Rightarrow> ('e,'a) FingerTreeStruc"
where "app t1 t2 = app3 t1 [] t2"
lemma app_inv: "\<lbrakk>ft_invar t1;ft_invar t2\<rbrakk> \<Longrightarrow> ft_invar (app t1 t2)"
by (auto simp add: app3_inv ft_invar_def app_def)
lemma app_list[simp]: "toList (app t1 t2) = (toList t1) @ (toList t2)"
by (simp add: app3_list app_def)
subsubsection "Splitting"
type_synonym ('e,'a) SplitDigit =
"('e,'a) Node list \<times> ('e,'a) Node \<times> ('e,'a) Node list"
type_synonym ('e,'a) SplitTree =
"('e,'a) FingerTreeStruc \<times> ('e,'a) Node \<times> ('e,'a) FingerTreeStruc"
text \<open>Auxiliary functions to create a correct finger tree
even if the left or right digit is empty\<close>
fun deepL :: "('e,'a::monoid_add) Node list \<Rightarrow> ('e,'a) FingerTreeStruc
\<Rightarrow> ('e,'a) Digit \<Rightarrow> ('e,'a) FingerTreeStruc" where
"deepL [] m sf = (case (viewLn m) of None \<Rightarrow> digitToTree sf |
(Some (a, m2)) \<Rightarrow> deep (nodeToDigit a) m2 sf)" |
"deepL pr m sf = deep (nlistToDigit pr) m sf"
fun deepR :: "('e,'a::monoid_add) Digit \<Rightarrow> ('e,'a) FingerTreeStruc
\<Rightarrow> ('e,'a) Node list \<Rightarrow> ('e,'a) FingerTreeStruc" where
"deepR pr m [] = (case (viewRn m) of None \<Rightarrow> digitToTree pr |
(Some (a, m2)) \<Rightarrow> deep pr m2 (nodeToDigit a))" |
"deepR pr m sf = deep pr m (nlistToDigit sf)"
text \<open>Splitting a list of nodes\<close>
fun splitNlist :: "('a::monoid_add \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> ('e,'a) Node list
\<Rightarrow> ('e,'a) SplitDigit" where
"splitNlist p i [a] = ([],a,[])" |
"splitNlist p i (a#b) =
(let i2 = (i + gmn a) in
(if (p i2)
then ([],a,b)
else
(let (l,x,r) = (splitNlist p i2 b) in ((a#l),x,r))))"
text \<open>Splitting a digit by converting it into a list of nodes\<close>
definition splitDigit :: "('a::monoid_add \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> ('e,'a) Digit
\<Rightarrow> ('e,'a) SplitDigit" where
"splitDigit p i d = splitNlist p i (digitToNlist d)"
text \<open>Creating a finger tree from list of nodes\<close>
definition nlistToTree :: "('e,'a::monoid_add) Node list
\<Rightarrow> ('e,'a) FingerTreeStruc" where
"nlistToTree xs = lconsNlist xs Empty"
text \<open>Recursive splitting into a left and right tree and a center node\<close>
fun nsplitTree :: "('a::monoid_add \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> ('e,'a) FingerTreeStruc
\<Rightarrow> ('e,'a) SplitTree" where
"nsplitTree p i Empty = (Empty, Tip undefined undefined, Empty)"
\<comment> \<open>Making the function total\<close> |
"nsplitTree p i (Single ea) = (Empty,ea,Empty)" |
"nsplitTree p i (Deep _ pr m sf) =
(let
vpr = (i + gmd pr);
vm = (vpr + gmft m)
in
if (p vpr) then
(let (l,x,r) = (splitDigit p i pr) in
(nlistToTree l,x,deepL r m sf))
else (if (p vm) then
(let (ml,xs,mr) = (nsplitTree p vpr m);
(l,x,r) = (splitDigit p (vpr + gmft ml) (nodeToDigit xs)) in
(deepR pr ml l,x,deepL r mr sf))
else
(let (l,x,r) = (splitDigit p vm sf) in
(deepR pr m l,x,nlistToTree r))
))"
lemma nlistToTree_inv:
"\<forall> x \<in> set nl. is_measured_node x \<Longrightarrow> is_measured_ftree (nlistToTree nl)"
"\<forall> x \<in> set nl. is_leveln_node n x \<Longrightarrow> is_leveln_ftree n (nlistToTree nl)"
by (unfold nlistToTree_def, induct nl, auto simp add: nlcons_invmeas)
(induct nl, auto simp add: nlcons_invlevel)
lemma nlistToTree_list: "toList (nlistToTree nl) = nlistToList nl"
by (auto simp add: nlistToTree_def nlistListLCons)
lemma deepL_inv:
assumes "is_leveln_ftree (Suc n) m \<and> is_measured_ftree m"
and "is_leveln_digit n sf \<and> is_measured_digit sf"
and "\<forall> x \<in> set pr. (is_measured_node x \<and> is_leveln_node n x) \<and> length pr \<le> 4"
shows "is_leveln_ftree n (deepL pr m sf) \<and> is_measured_ftree (deepL pr m sf)"
apply (insert assms)
apply (induct "pr" m sf rule: deepL.induct)
apply (simp split: viewnres_split)
apply auto[1]
apply (simp_all add: digitToTree_inv deep_def)
proof -
fix m sf Node FingerTreeStruc
assume "is_leveln_ftree (Suc n) m" "is_measured_ftree m"
"is_leveln_digit n sf" "is_measured_digit sf"
"viewLn m = Some (Node, FingerTreeStruc)"
thus "is_leveln_digit n (nodeToDigit Node)
\<and> is_leveln_ftree (Suc n) FingerTreeStruc"
by (simp add: viewLn_inv[of m "Suc n" Node FingerTreeStruc] nodeToDigit_inv)
next
fix m sf Node FingerTreeStruc
assume assms1:
"is_leveln_ftree (Suc n) m" "is_measured_ftree m"
"is_leveln_digit n sf" "is_measured_digit sf"
"viewLn m = Some (Node, FingerTreeStruc)"
thus "is_measured_digit (nodeToDigit Node) \<and> is_measured_ftree FingerTreeStruc"
apply (auto simp only: viewLn_inv[of m "Suc n" Node FingerTreeStruc])
proof -
from assms1 have "is_measured_node Node \<and> is_leveln_node (Suc n) Node"
by (simp add: viewLn_inv[of m "Suc n" Node FingerTreeStruc])
thus "is_measured_digit (nodeToDigit Node)"
by (auto simp add: nodeToDigit_inv)
qed
next
fix v va
assume
"is_measured_node v \<and> is_leveln_node n (v:: ('a,'b) Node) \<and>
length (va::('a, 'b) Node list) \<le> 3 \<and>
(\<forall>x\<in>set va. is_measured_node x \<and> is_leveln_node n x \<and> length va \<le> 3)"
thus "is_leveln_digit n (nlistToDigit (v # va))
\<and> is_measured_digit (nlistToDigit (v # va))"
by(cases "v#va" rule: nlistToDigit.cases,simp_all)
qed
(*corollary deepL_inv':
assumes "is_leveln_ftree (Suc n) m" "is_measured_ftree m"
and "is_leveln_digit n sf" "is_measured_digit sf"
and "\<forall> x \<in> set pr. (is_measured_node x \<and> is_leveln_node n x)" "length pr \<le> 4"
shows "is_leveln_ftree n (deepL pr m sf)" "is_measured_ftree (deepL pr m sf)"
using assms deepL_inv by blast+
*)
lemma nlistToDigit_list:
assumes "1 \<le> length xs \<and> length xs \<le> 4"
shows "digitToList(nlistToDigit xs) = nlistToList xs"
by (insert assms, cases xs rule: nlistToDigit.cases,auto)
lemma deepL_list:
assumes "is_leveln_ftree (Suc n) m \<and> is_measured_ftree m"
and "is_leveln_digit n sf \<and> is_measured_digit sf"
and "\<forall> x \<in> set pr. (is_measured_node x \<and> is_leveln_node n x) \<and> length pr \<le> 4"
shows "toList (deepL pr m sf) = nlistToList pr @ toList m @ digitToList sf"
proof (insert assms, induct "pr" m sf rule: deepL.induct)
case (1 m sf)
thus ?case
proof (auto split: viewnres_split simp add: deep_def)
assume "viewLn m = None"
hence "m = Empty" by (metis viewLn_empty)
hence "toList m = []" by simp
thus "toList (digitToTree sf) = toList m @ digitToList sf"
by (simp add:digitToTree_list)
next
fix nd t
assume "viewLn m = Some (nd, t)"
"is_leveln_ftree (Suc n) m" "is_measured_ftree m"
hence "nodeToList nd @ toList t = toList m" by (metis viewLn_list)
thus "digitToList (nodeToDigit nd) @ toList t = toList m"
by (simp add: nodeToDigit_list)
qed
next
case (2 v va m sf)
thus ?case
apply (unfold deepL.simps)
apply (simp add: deep_def)
apply (simp add: nlistToDigit_list)
done
qed
lemma deepR_inv:
assumes "is_leveln_ftree (Suc n) m \<and> is_measured_ftree m"
and "is_leveln_digit n pr \<and> is_measured_digit pr"
and "\<forall> x \<in> set sf. (is_measured_node x \<and> is_leveln_node n x) \<and> length sf \<le> 4"
shows "is_leveln_ftree n (deepR pr m sf) \<and> is_measured_ftree (deepR pr m sf)"
apply (insert assms)
apply (induct "pr" m sf rule: deepR.induct)
apply (simp split: viewnres_split)
apply auto[1]
apply (simp_all add: digitToTree_inv deep_def)
proof -
fix m "pr" Node FingerTreeStruc
assume "is_leveln_ftree (Suc n) m" "is_measured_ftree m"
"is_leveln_digit n pr" "is_measured_digit pr"
"viewRn m = Some (Node, FingerTreeStruc)"
thus
"is_leveln_digit n (nodeToDigit Node)
\<and> is_leveln_ftree (Suc n) FingerTreeStruc"
by (simp add: viewRn_inv[of m "Suc n" Node FingerTreeStruc] nodeToDigit_inv)
next
fix m "pr" Node FingerTreeStruc
assume assms1:
"is_leveln_ftree (Suc n) m" "is_measured_ftree m"
"is_leveln_digit n pr" "is_measured_digit pr"
"viewRn m = Some (Node, FingerTreeStruc)"
thus "is_measured_ftree FingerTreeStruc \<and> is_measured_digit (nodeToDigit Node)"
apply (auto simp only: viewRn_inv[of m "Suc n" Node FingerTreeStruc])
proof -
from assms1 have "is_measured_node Node \<and> is_leveln_node (Suc n) Node"
by (simp add: viewRn_inv[of m "Suc n" Node FingerTreeStruc])
thus "is_measured_digit (nodeToDigit Node)"
by (auto simp add: nodeToDigit_inv)
qed
next
fix v va
assume
"is_measured_node v \<and> is_leveln_node n (v:: ('a,'b) Node) \<and>
length (va::('a, 'b) Node list) \<le> 3 \<and>
(\<forall>x\<in>set va. is_measured_node x \<and> is_leveln_node n x \<and> length va \<le> 3)"
thus "is_leveln_digit n (nlistToDigit (v # va)) \<and>
is_measured_digit (nlistToDigit (v # va))"
by(cases "v#va" rule: nlistToDigit.cases,simp_all)
qed
lemma deepR_list:
assumes "is_leveln_ftree (Suc n) m \<and> is_measured_ftree m"
and "is_leveln_digit n pr \<and> is_measured_digit pr"
and "\<forall> x \<in> set sf. (is_measured_node x \<and> is_leveln_node n x) \<and> length sf \<le> 4"
shows "toList (deepR pr m sf) = digitToList pr @ toList m @ nlistToList sf"
proof (insert assms, induct "pr" m sf rule: deepR.induct)
case (1 "pr" m)
thus ?case
proof (auto split: viewnres_split simp add: deep_def)
assume "viewRn m = None"
hence "m = Empty" by (metis viewRn_empty)
hence "toList m = []" by simp
thus "toList (digitToTree pr) = digitToList pr @ toList m"
by (simp add:digitToTree_list)
next
fix nd t
assume "viewRn m = Some (nd, t)" "is_leveln_ftree (Suc n) m"
"is_measured_ftree m"
hence "toList t @ nodeToList nd = toList m" by (metis viewRn_list)
thus "toList t @ digitToList (nodeToDigit nd) = toList m"
by (simp add: nodeToDigit_list)
qed
next
case (2 "pr" m v va)
thus ?case
apply (unfold deepR.simps)
apply (simp add: deep_def)
apply (simp add: nlistToDigit_list)
done
qed
primrec gmnl:: "('e, 'a::monoid_add) Node list \<Rightarrow> 'a" where
"gmnl [] = 0"|
"gmnl (x#xs) = gmn x + gmnl xs"
lemma gmnl_correct:
assumes "\<forall> x \<in> set xs. is_measured_node x"
shows "gmnl xs = sum_list (map snd (nlistToList xs))"
by (insert assms, induct xs) (auto simp add: add.assoc gmn_correct)
lemma splitNlist_correct:" \<lbrakk>
\<And>(a::'a) (b::'a). p a \<Longrightarrow> p (a + b);
\<not> p i;
p (i + gmnl (nl ::('e,'a::monoid_add) Node list));
splitNlist p i nl = (l, n, r)
\<rbrakk> \<Longrightarrow>
\<not> p (i + (gmnl l))
\<and>
p (i + (gmnl l) + (gmn n))
\<and>
nl = l @ n # r
"
proof (induct p i nl arbitrary: l n r rule: splitNlist.induct)
case 1 thus ?case by simp
next
case (2 p i a v va l n r) note IV = this
show ?case
proof (cases "p (i + (gmn a))")
case True with IV show ?thesis by simp
next
case False note IV2 = this IV thus ?thesis
proof -
obtain l1 n1 r1 where
v1[simp]: "splitNlist p (i + gmn a) (v # va) = (l1, n1, r1)"
by (cases "splitNlist p (i + gmn a) (v # va)", blast)
note miv = IV2(2)[of "i + gmn a" l1 n1 r1]
have v2:"p (i + gmn a + gmnl (v # va))"
using IV2(5) by (simp add: add.assoc)
note miv2 = miv[OF _ IV2(1) IV2(3) IV2(1) v2 v1]
have v3: "a # l1 = l" "n1 = n" "r1 = r" using IV2 v1 by auto
with miv2 have
v4: "\<not> p (i + gmn a + gmnl l1) \<and>
p (i + gmn a + gmnl l1 + gmn n1) \<and>
v # va = l1 @ n1 # r1"
by auto
with v2 v3 show ?thesis
by (auto simp add: add.assoc)
qed
qed
next
case 3 thus ?case by simp
qed
lemma digitToNlist_inv:
"is_measured_digit d \<Longrightarrow> (\<forall> x \<in> set (digitToNlist d). is_measured_node x)"
"is_leveln_digit n d \<Longrightarrow> (\<forall> x \<in> set (digitToNlist d). is_leveln_node n x)"
by (cases d, auto)(cases d, auto)
lemma gmnl_gmd:
"is_measured_digit d \<Longrightarrow> gmnl (digitToNlist d) = gmd d"
by (cases d, auto simp add: add.assoc)
lemma gmn_gmd:
"is_measured_node nd \<Longrightarrow> gmd (nodeToDigit nd) = gmn nd"
by (auto simp add: nodeToDigit_inv nodeToDigit_list gmn_correct gmd_correct)
lemma splitDigit_inv:
"\<lbrakk>
\<And>(a::'a) (b::'a). p a \<Longrightarrow> p (a + b);
\<not> p i;
is_measured_digit d;
is_leveln_digit n d;
p (i + gmd (d ::('e,'a::monoid_add) Digit));
splitDigit p i d = (l, nd, r)
\<rbrakk> \<Longrightarrow>
\<not> p (i + (gmnl l))
\<and>
p (i + (gmnl l) + (gmn nd))
\<and>
(\<forall> x \<in> set l. (is_measured_node x \<and> is_leveln_node n x))
\<and>
(\<forall> x \<in> set r. (is_measured_node x \<and> is_leveln_node n x))
\<and>
(is_measured_node nd \<and> is_leveln_node n nd )
"
proof -
fix p i d n l nd r
assume assms: "\<And>a b. p a \<Longrightarrow> p (a + b)" "\<not> p i" "is_measured_digit d"
"p (i + gmd d)" "splitDigit p i d = (l, nd, r)"
"is_leveln_digit n d"
from assms(3, 4) have v1: "p (i + gmnl (digitToNlist d))"
by (simp add: gmnl_gmd)
note snc = splitNlist_correct [of p i "digitToNlist d" l nd r]
from assms(5) have v2: "splitNlist p i (digitToNlist d) = (l, nd, r)"
by (simp add: splitDigit_def)
note snc1 = snc[OF assms(1) assms(2) v1 v2]
hence v3: "\<not> p (i + gmnl l) \<and> p (i + gmnl l + gmn nd) \<and>
digitToNlist d = l @ nd # r" by auto
from assms(3,6) have
v4:" \<forall> x \<in> set (digitToNlist d). is_measured_node x"
" \<forall> x \<in> set (digitToNlist d). is_leveln_node n x"
by(auto simp add: digitToNlist_inv)
with v3 have v5: "\<forall> x \<in> set l. (is_measured_node x \<and> is_leveln_node n x)"
"\<forall> x \<in> set r. (is_measured_node x \<and> is_leveln_node n x)"
"is_measured_node nd \<and> is_leveln_node n nd" by auto
with v3 v5 show
"\<not> p (i + gmnl l) \<and> p (i + gmnl l + gmn nd) \<and>
(\<forall>x\<in>set l. is_measured_node x \<and> is_leveln_node n x) \<and>
(\<forall>x\<in>set r. is_measured_node x \<and> is_leveln_node n x) \<and>
is_measured_node nd \<and> is_leveln_node n nd"
by auto
qed
lemma splitDigit_inv':
"\<lbrakk>
splitDigit p i d = (l, nd, r);
is_measured_digit d;
is_leveln_digit n d
\<rbrakk> \<Longrightarrow>
(\<forall> x \<in> set l. (is_measured_node x \<and> is_leveln_node n x))
\<and>
(\<forall> x \<in> set r. (is_measured_node x \<and> is_leveln_node n x))
\<and>
(is_measured_node nd \<and> is_leveln_node n nd )
"
apply (unfold splitDigit_def)
apply (cases d)
apply (auto split: if_split_asm simp add: Let_def)
done
lemma splitDigit_list: "splitDigit p i d = (l,n,r) \<Longrightarrow>
(digitToList d) = (nlistToList l) @ (nodeToList n) @ (nlistToList r)
\<and> length l \<le> 4 \<and> length r \<le> 4"
apply (unfold splitDigit_def)
apply (cases d)
apply (auto split: if_split_asm simp add: Let_def)
done
lemma gmnl_gmft: "\<forall> x \<in> set nl. is_measured_node x \<Longrightarrow>
gmft (nlistToTree nl) = gmnl nl"
by (auto simp add: gmnl_correct[of nl] nlistToTree_list[of nl]
nlistToTree_inv[of nl] gmft_correct[of "nlistToTree nl"])
lemma gmftR_gmnl:
assumes "is_leveln_ftree (Suc n) m \<and> is_measured_ftree m"
and "is_leveln_digit n pr \<and> is_measured_digit pr"
and "\<forall> x \<in> set sf. (is_measured_node x \<and> is_leveln_node n x) \<and> length sf \<le> 4"
shows "gmft (deepR pr m sf) = gmd pr + gmft m + gmnl sf"
proof-
from assms have
v1: "toList (deepR pr m sf) = digitToList pr @ toList m @ nlistToList sf"
by (auto simp add: deepR_list)
from assms have
v2: "is_measured_ftree (deepR pr m sf)"
by (auto simp add: deepR_inv)
with v1 have
v3: "gmft (deepR pr m sf) =
sum_list (map snd (digitToList pr @ toList m @ nlistToList sf))"
by (auto simp add: gmft_correct)
have
v4:"gmd pr + gmft m + gmnl sf =
sum_list (map snd (digitToList pr @ toList m @ nlistToList sf))"
by (auto simp add: gmd_correct gmft_correct gmnl_correct assms add.assoc)
with v3 show ?thesis by simp
qed
lemma nsplitTree_correct: "\<lbrakk>
is_leveln_ftree n (s:: ('e,'a::monoid_add) FingerTreeStruc);
is_measured_ftree s;
\<And>(a::'a) (b::'a). p a \<Longrightarrow> p (a + b);
\<not> p i;
p (i + (gmft s));
(nsplitTree p i s) = (l, nd, r)\<rbrakk>
\<Longrightarrow> (toList s) = (toList l) @ (nodeToList nd) @ (toList r)
\<and>
\<not> p (i + (gmft l))
\<and>
p (i + (gmft l) + (gmn nd))
\<and>
is_leveln_ftree n l
\<and>
is_measured_ftree l
\<and>
is_leveln_ftree n r
\<and>
is_measured_ftree r
\<and>
is_leveln_node n nd
\<and>
is_measured_node nd
"
proof (induct p i s arbitrary: n l nd r rule: nsplitTree.induct)
case 1
thus ?case by auto
next
case 2 thus ?case by auto
next
case (3 p i uu "pr" m sf n l nd r)
thus ?case
proof (cases "p (i + gmd pr)")
case True with 3 show ?thesis
proof -
obtain l1 x r1 where
l1xr1: "splitDigit p i pr = (l1,x,r1)"
by (cases "splitDigit p i pr", blast)
with True 3(7) have
v1: "l = nlistToTree l1" "nd = x" "r = deepL r1 m sf" by auto
from l1xr1 have
v2: "digitToList pr = nlistToList l1 @ nodeToList x @ nlistToList r1"
"length l1 \<le> 4" "length r1 \<le> 4"
by (auto simp add: splitDigit_list)
from 3(2,3) have
pr_m_sf_inv: "is_leveln_digit n pr \<and> is_measured_digit pr"
"is_leveln_ftree (Suc n) m \<and> is_measured_ftree m"
"is_leveln_digit n sf \<and> is_measured_digit sf" by simp_all
with 3(4,5) pr_m_sf_inv(1) True l1xr1
splitDigit_inv[of p i "pr" n l1 x r1] have
l1_x_r1_inv:
"\<not> p (i + (gmnl l1))"
"p (i + (gmnl l1) + (gmn x))"
"\<forall> x \<in> set l1. (is_measured_node x \<and> is_leveln_node n x)"
"\<forall> x \<in> set r1. (is_measured_node x \<and> is_leveln_node n x)"
"is_measured_node x \<and> is_leveln_node n x"
by auto
from v2 v1 l1_x_r1_inv(4) pr_m_sf_inv have
ziel1: "toList (Deep uu pr m sf) = toList l @ nodeToList nd @ toList r"
by (auto simp add: nlistToTree_list deepL_list)
from l1_x_r1_inv(3) v1(1) have
v3: "gmft l = gmnl l1" by (simp add: gmnl_gmft)
with l1_x_r1_inv(1,2) v1 have
ziel2: " \<not> p (i + gmft l)"
"p (i + gmft l + gmn nd)"
by simp_all
from l1_x_r1_inv(3,4,5) v1 v2(3) pr_m_sf_inv have
ziel3: "is_leveln_ftree n l \<and> is_measured_ftree l \<and>
is_leveln_ftree n r \<and> is_measured_ftree r \<and>
is_leveln_node n nd \<and> is_measured_node nd"
by (auto simp add: nlistToTree_inv deepL_inv)
from ziel1 ziel2 ziel3 show ?thesis by simp
qed
next
case False note case1 = this with 3 show ?thesis
proof (cases "p (i + gmd pr + gmft m)")
case False with case1 3 show ?thesis
proof -
obtain l1 x r1 where
l1xr1: "splitDigit p (i + gmd pr + gmft m) sf = (l1,x,r1)"
by (cases "splitDigit p (i + gmd pr + gmft m) sf", blast)
with case1 False 3(7) have
v1: "l = deepR pr m l1" "nd = x" "r = nlistToTree r1" by auto
from l1xr1 have
v2: "digitToList sf = nlistToList l1 @ nodeToList x @ nlistToList r1"
"length l1 \<le> 4" "length r1 \<le> 4"
by (auto simp add: splitDigit_list)
from 3(2,3) have
pr_m_sf_inv: "is_leveln_digit n pr \<and> is_measured_digit pr"
"is_leveln_ftree (Suc n) m \<and> is_measured_ftree m"
"is_leveln_digit n sf \<and> is_measured_digit sf" by simp_all
from 3(3,6) have
v7: "p (i + gmd pr + gmft m + gmd sf)" by (auto simp add: add.assoc)
with pr_m_sf_inv 3(4) pr_m_sf_inv(3) case1 False l1xr1
splitDigit_inv[of p "i + gmd pr + gmft m" sf n l1 x r1]
have l1_x_r1_inv:
"\<not> p (i + gmd pr + gmft m + gmnl l1)"
"p (i + gmd pr + gmft m + gmnl l1 + gmn x)"
"\<forall> x \<in> set l1. (is_measured_node x \<and> is_leveln_node n x)"
"\<forall> x \<in> set r1. (is_measured_node x \<and> is_leveln_node n x)"
"is_measured_node x \<and> is_leveln_node n x"
by auto
from v2 v1 l1_x_r1_inv(3) pr_m_sf_inv have
ziel1: "toList (Deep uu pr m sf) = toList l @ nodeToList nd @ toList r"
by (auto simp add: nlistToTree_list deepR_list)
from l1_x_r1_inv(4) v1(3) have
v3: "gmft r = gmnl r1" by (simp add: gmnl_gmft)
with l1_x_r1_inv(1,2,3) pr_m_sf_inv v1 v2 have
ziel2: " \<not> p (i + gmft l)"
"p (i + gmft l + gmn nd)"
by (auto simp add: gmftR_gmnl add.assoc)
from l1_x_r1_inv(3,4,5) v1 v2(2) pr_m_sf_inv have
ziel3: "is_leveln_ftree n l \<and> is_measured_ftree l \<and>
is_leveln_ftree n r \<and> is_measured_ftree r \<and>
is_leveln_node n nd \<and> is_measured_node nd"
by (auto simp add: nlistToTree_inv deepR_inv)
from ziel1 ziel2 ziel3 show ?thesis by simp
qed
next
case True with case1 3 show ?thesis
proof -
obtain l1 x r1 where
l1_x_r1 :"nsplitTree p (i + gmd pr) m = (l1, x, r1)"
by (cases "nsplitTree p (i + gmd pr) m") blast
from 3(2,3) have
pr_m_sf_inv: "is_leveln_digit n pr \<and> is_measured_digit pr"
"is_leveln_ftree (Suc n) m \<and> is_measured_ftree m"
"is_leveln_digit n sf \<and> is_measured_digit sf" by simp_all
with True case1
"3.hyps"[of "i + gmd pr" "i + gmd pr + gmft m" "Suc n" l1 x r1]
3(4) l1_x_r1
have l1_x_r1_inv:
"\<not> p (i + gmd pr + gmft l1)"
"p (i + gmd pr + gmft l1 + gmn x)"
"is_leveln_ftree (Suc n) l1 \<and> is_measured_ftree l1"
"is_leveln_ftree (Suc n) r1 \<and> is_measured_ftree r1"
"is_leveln_node (Suc n) x \<and> is_measured_node x"
and l1_x_r1_list:
"toList m = toList l1 @ nodeToList x @ toList r1"
by auto
obtain l2 x2 r2 where l2_x2_r2:
"splitDigit p (i + gmd pr + gmft l1) (nodeToDigit x) = (l2,x2,r2)"
by (cases "splitDigit p (i + gmd pr + gmft l1) (nodeToDigit x)",blast)
from l1_x_r1_inv(2,5) have
ndx_inv: "is_leveln_digit n (nodeToDigit x) \<and>
is_measured_digit (nodeToDigit x)"
"p (i + gmd pr + gmft l1 + gmd (nodeToDigit x))"
by (auto simp add: nodeToDigit_inv gmn_gmd)
note spdi = splitDigit_inv[of p "i + gmd pr + gmft l1"
"nodeToDigit x" n l2 x2 r2]
from ndx_inv l1_x_r1_inv(1) l2_x2_r2 3(4) have
l2_x2_r2_inv:"\<not> p (i + gmd pr + gmft l1 + gmnl l2)"
"p (i + gmd pr + gmft l1 + gmnl l2 + gmn x2)"
"\<forall>x\<in>set l2. is_measured_node x \<and> is_leveln_node n x"
"\<forall>x\<in>set r2. is_measured_node x \<and> is_leveln_node n x"
"is_measured_node x2 \<and> is_leveln_node n x2"
by (auto simp add: spdi)
note spdl = splitDigit_list[of p "i + gmd pr + gmft l1"
"nodeToDigit x" l2 x2 r2]
from l2_x2_r2 have
l2_x2_r2_list:
"digitToList (nodeToDigit x) =
nlistToList l2 @ nodeToList x2 @ nlistToList r2"
"length l2 \<le> 4 \<and> length r2 \<le> 4"
by (auto simp add: spdl)
from case1 True 3(7) l1_x_r1 l2_x2_r2 have
l_nd_r:
"l = deepR pr l1 l2"
"nd = x2"
"r = deepL r2 r1 sf"
by auto
note dr1 = deepR_inv[OF l1_x_r1_inv(3) pr_m_sf_inv(1)]
from dr1 l2_x2_r2_inv(3) l2_x2_r2_list(2) l_nd_r have
l_inv: "is_leveln_ftree n l \<and> is_measured_ftree l"
by simp
note dl1 = deepL_inv[OF l1_x_r1_inv(4) pr_m_sf_inv(3)]
from dl1 l2_x2_r2_inv(4) l2_x2_r2_list(2) l_nd_r have
r_inv: "is_leveln_ftree n r \<and> is_measured_ftree r"
by simp
from l2_x2_r2_inv l_nd_r have
nd_inv: "is_leveln_node n nd \<and> is_measured_node nd"
by simp
from l_nd_r(1,2) l2_x2_r2_inv(1,2,3)
l1_x_r1_inv(3) l2_x2_r2_list(2) pr_m_sf_inv(1)
have split_point:
" \<not> p (i + gmft l)"
"p (i + gmft l + gmn nd)"
by (auto simp add: gmftR_gmnl add.assoc)
from l2_x2_r2_list have x_list:
"nodeToList x = nlistToList l2 @ nodeToList x2 @ nlistToList r2"
by (simp add: nodeToDigit_list)
from l1_x_r1_inv(3) pr_m_sf_inv(1)
l2_x2_r2_inv(3) l2_x2_r2_list(2) l_nd_r(1)
have l_list: "toList l = digitToList pr @ toList l1 @ nlistToList l2"
by (auto simp add: deepR_list)
from l1_x_r1_inv(4) pr_m_sf_inv(3) l2_x2_r2_inv(4)
l2_x2_r2_list(2) l_nd_r(3)
have r_list: "toList r = nlistToList r2 @ toList r1 @ digitToList sf"
by (auto simp add: deepL_list)
from x_list l1_x_r1_list l_list r_list l_nd_r
have "toList (Deep uu pr m sf) = toList l @ nodeToList nd @ toList r"
by auto
with split_point l_inv r_inv nd_inv
show ?thesis by simp
qed
qed
qed
qed
text \<open>
A predicate on the elements of a monoid is called {\em monotone},
iff, when it holds for some value $a$, it also holds for all values $a+b$:
\<close>
text \<open>Split a finger tree by a monotone predicate on the annotations, using
a given initial value. Intuitively, the elements are summed up from left to
right, and the split is done when the predicate first holds for the sum.
The predicate must not hold for the initial value of the summation, and must
hold for the sum of all elements.
\<close>
definition splitTree
:: "('a::monoid_add \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> ('e, 'a) FingerTreeStruc
\<Rightarrow> ('e, 'a) FingerTreeStruc \<times> ('e \<times> 'a) \<times> ('e, 'a) FingerTreeStruc"
where
"splitTree p i t = (let (l, x, r) = nsplitTree p i t in (l, (n_unwrap x), r))"
lemma splitTree_invpres:
assumes inv: "ft_invar (s:: ('e,'a::monoid_add) FingerTreeStruc)"
assumes init_ff: "\<not> p i"
assumes sum_tt: "p (i + annot s)"
assumes fmt: "(splitTree p i s) = (l, (e,a), r)"
shows "ft_invar l" and "ft_invar r"
proof -
obtain l1 nd r1 where
l1_nd_r1: "nsplitTree p i s = (l1, nd, r1)"
by (cases "nsplitTree p i s", blast)
with assms have
l0: "l = l1"
"(e,a) = n_unwrap nd"
"r = r1"
by (auto simp add: splitTree_def)
note nsp = nsplitTree_invpres[of 0 s p i l1 nd r1]
from assms have "p (i + gmft s)" by (simp add: ft_invar_def annot_def)
with assms l1_nd_r1 l0 have
v1:
"is_leveln_ftree 0 l \<and> is_measured_ftree l"
"is_leveln_ftree 0 r \<and> is_measured_ftree r"
"is_leveln_node 0 nd \<and> is_measured_node nd"
by (auto simp add: nsp ft_invar_def)
thus "ft_invar l" and "ft_invar r"
by (simp_all add: ft_invar_def annot_def)
qed
lemma splitTree_correct:
assumes inv: "ft_invar (s:: ('e,'a::monoid_add) FingerTreeStruc)"
assumes mono: "\<forall>a b. p a \<longrightarrow> p (a + b)"
assumes init_ff: "\<not> p i"
assumes sum_tt: "p (i + annot s)"
assumes fmt: "(splitTree p i s) = (l, (e,a), r)"
shows "(toList s) = (toList l) @ (e,a) # (toList r)"
and "\<not> p (i + annot l)"
and "p (i + annot l + a)"
and "ft_invar l" and "ft_invar r"
proof -
obtain l1 nd r1 where
l1_nd_r1: "nsplitTree p i s = (l1, nd, r1)"
by (cases "nsplitTree p i s", blast)
with assms have
l0: "l = l1"
"(e,a) = n_unwrap nd"
"r = r1"
by (auto simp add: splitTree_def)
note nsp = nsplitTree_correct[of 0 s p i l1 nd r1]
from assms have "p (i + gmft s)" by (simp add: ft_invar_def annot_def)
with assms l1_nd_r1 l0 have
v1:
"(toList s) = (toList l) @ (nodeToList nd) @ (toList r)"
"\<not> p (i + (gmft l))"
"p (i + (gmft l) + (gmn nd))"
"is_leveln_ftree 0 l \<and> is_measured_ftree l"
"is_leveln_ftree 0 r \<and> is_measured_ftree r"
"is_leveln_node 0 nd \<and> is_measured_node nd"
by (auto simp add: nsp ft_invar_def)
from v1(6) l0(2) have
ndea: "nd = Tip e a"
by (cases nd) auto
hence nd_list_inv: "nodeToList nd = [(e,a)]"
"gmn nd = a" by simp_all
with v1 show "(toList s) = (toList l) @ (e,a) # (toList r)"
and "\<not> p (i + annot l)"
and "p (i + annot l + a)"
and "ft_invar l" and "ft_invar r"
by (simp_all add: ft_invar_def annot_def)
qed
subsubsection \<open>Folding\<close>
fun foldl_node :: "('s \<Rightarrow> 'e \<times> 'a \<Rightarrow> 's) \<Rightarrow> 's \<Rightarrow> ('e,'a) Node \<Rightarrow> 's" where
"foldl_node f \<sigma> (Tip e a) = f \<sigma> (e,a)"|
"foldl_node f \<sigma> (Node2 _ a b) = foldl_node f (foldl_node f \<sigma> a) b"|
"foldl_node f \<sigma> (Node3 _ a b c) =
foldl_node f (foldl_node f (foldl_node f \<sigma> a) b) c"
primrec foldl_digit :: "('s \<Rightarrow> 'e \<times> 'a \<Rightarrow> 's) \<Rightarrow> 's \<Rightarrow> ('e,'a) Digit \<Rightarrow> 's" where
"foldl_digit f \<sigma> (One n1) = foldl_node f \<sigma> n1"|
"foldl_digit f \<sigma> (Two n1 n2) = foldl_node f (foldl_node f \<sigma> n1) n2"|
"foldl_digit f \<sigma> (Three n1 n2 n3) =
foldl_node f (foldl_node f (foldl_node f \<sigma> n1) n2) n3"|
"foldl_digit f \<sigma> (Four n1 n2 n3 n4) =
foldl_node f (foldl_node f (foldl_node f (foldl_node f \<sigma> n1) n2) n3) n4"
primrec foldr_node :: "('e \<times> 'a \<Rightarrow> 's \<Rightarrow> 's) \<Rightarrow> ('e,'a) Node \<Rightarrow> 's \<Rightarrow> 's" where
"foldr_node f (Tip e a) \<sigma> = f (e,a) \<sigma> "|
"foldr_node f (Node2 _ a b) \<sigma> = foldr_node f a (foldr_node f b \<sigma>)"|
"foldr_node f (Node3 _ a b c) \<sigma>
= foldr_node f a (foldr_node f b (foldr_node f c \<sigma>))"
primrec foldr_digit :: "('e \<times> 'a \<Rightarrow> 's \<Rightarrow> 's) \<Rightarrow> ('e,'a) Digit \<Rightarrow> 's \<Rightarrow> 's" where
"foldr_digit f (One n1) \<sigma> = foldr_node f n1 \<sigma>"|
"foldr_digit f (Two n1 n2) \<sigma> = foldr_node f n1 (foldr_node f n2 \<sigma>)"|
"foldr_digit f (Three n1 n2 n3) \<sigma> =
foldr_node f n1 (foldr_node f n2 (foldr_node f n3 \<sigma>))"|
"foldr_digit f (Four n1 n2 n3 n4) \<sigma> =
foldr_node f n1 (foldr_node f n2 (foldr_node f n3 (foldr_node f n4 \<sigma>)))"
lemma foldl_node_correct:
"foldl_node f \<sigma> nd = List.foldl f \<sigma> (nodeToList nd)"
by (induct nd arbitrary: "\<sigma>") (auto simp add: nodeToList_def)
lemma foldl_digit_correct:
"foldl_digit f \<sigma> d = List.foldl f \<sigma> (digitToList d)"
by (induct d arbitrary: "\<sigma>") (auto
simp add: digitToList_def foldl_node_correct)
lemma foldr_digit_correct:
"foldr_digit f d \<sigma> = List.foldr f (digitToList d) \<sigma>"
by (induct d arbitrary: "\<sigma>") (auto
simp add: digitToList_def foldr_node_correct)
text "Fold from left"
primrec foldl :: "('s \<Rightarrow> 'e \<times> 'a \<Rightarrow> 's) \<Rightarrow> 's \<Rightarrow> ('e,'a) FingerTreeStruc \<Rightarrow> 's"
where
"foldl f \<sigma> Empty = \<sigma>"|
"foldl f \<sigma> (Single nd) = foldl_node f \<sigma> nd"|
"foldl f \<sigma> (Deep _ d1 m d2) =
foldl_digit f (foldl f (foldl_digit f \<sigma> d1) m) d2"
lemma foldl_correct:
"foldl f \<sigma> t = List.foldl f \<sigma> (toList t)"
by (induct t arbitrary: "\<sigma>") (auto
simp add: toList_def foldl_node_correct foldl_digit_correct)
text "Fold from right"
primrec foldr :: "('e \<times> 'a \<Rightarrow> 's \<Rightarrow> 's) \<Rightarrow> ('e,'a) FingerTreeStruc \<Rightarrow> 's \<Rightarrow> 's"
where
"foldr f Empty \<sigma> = \<sigma>"|
"foldr f (Single nd) \<sigma> = foldr_node f nd \<sigma>"|
"foldr f (Deep _ d1 m d2) \<sigma>
= foldr_digit f d1 (foldr f m(foldr_digit f d2 \<sigma>))"
lemma foldr_correct:
"foldr f t \<sigma> = List.foldr f (toList t) \<sigma>"
by (induct t arbitrary: "\<sigma>") (auto
simp add: toList_def foldr_node_correct foldr_digit_correct)
subsubsection "Number of elements"
primrec count_node :: "('e, 'a) Node \<Rightarrow> nat" where
"count_node (Tip _ a) = 1" |
"count_node (Node2 _ a b) = count_node a + count_node b" |
"count_node (Node3 _ a b c) = count_node a + count_node b + count_node c"
primrec count_digit :: "('e,'a) Digit \<Rightarrow> nat" where
"count_digit (One a) = count_node a" |
"count_digit (Two a b) = count_node a + count_node b" |
"count_digit (Three a b c) = count_node a + count_node b + count_node c" |
"count_digit (Four a b c d)
= count_node a + count_node b + count_node c + count_node d"
lemma count_node_correct:
"count_node n = length (nodeToList n)"
by (induct n,auto simp add: nodeToList_def count_node_def)
lemma count_digit_correct:
"count_digit d = length (digitToList d)"
by (cases d, auto simp add: digitToList_def count_digit_def count_node_correct)
primrec count :: "('e,'a) FingerTreeStruc \<Rightarrow> nat" where
"count Empty = 0" |
"count (Single a) = count_node a" |
"count (Deep _ pr m sf) = count_digit pr + count m + count_digit sf"
lemma count_correct[simp]:
"count t = length (toList t)"
by (induct t,
auto simp add: toList_def count_def
count_digit_correct count_node_correct)
end
(* Expose finger tree functions as qualified names.
Generate code equations *)
interpretation FingerTreeStruc: FingerTreeStruc_loc .
(* Hide the concrete syntax *)
no_notation FingerTreeStruc.lcons (infixr "\<lhd>" 65)
no_notation FingerTreeStruc.rcons (infixl "\<rhd>" 65)
subsection "Hiding the invariant"
text_raw\<open>\label{sec:hide_invar}\<close>
text \<open>
In this section, we define the datatype of all FingerTrees that fulfill their
invariant, and define the operations to work on this datatype.
The advantage is, that the correctness lemmas do no longer contain
explicit invariant predicates, what makes them more handy to use.
\<close>
subsubsection "Datatype"
typedef (overloaded) ('e, 'a) FingerTree =
"{t :: ('e, 'a::monoid_add) FingerTreeStruc. FingerTreeStruc.ft_invar t}"
proof -
have "Empty \<in> ?FingerTree" by (simp)
then show ?thesis ..
qed
lemma Rep_FingerTree_invar[simp]: "FingerTreeStruc.ft_invar (Rep_FingerTree t)"
using Rep_FingerTree by simp
lemma [simp, code abstype]: "Abs_FingerTree (Rep_FingerTree t) = t"
by (rule Rep_FingerTree_inverse)
typedef (overloaded) ('e,'a) viewres =
"{ r:: (('e \<times> 'a) \<times> ('e,'a::monoid_add) FingerTreeStruc) option .
case r of None \<Rightarrow> True | Some (a,t) \<Rightarrow> FingerTreeStruc.ft_invar t}"
apply (rule_tac x=None in exI)
apply auto
done
lemma [simp, code abstype]: "Abs_viewres (Rep_viewres x) = x"
by (rule Rep_viewres_inverse)
lemma Abs_viewres_inverse_None[simp]:
"Rep_viewres (Abs_viewres None) = None"
by (simp add: Abs_viewres_inverse)
lemma Abs_viewres_inverse_Some:
"FingerTreeStruc.ft_invar t \<Longrightarrow>
Rep_viewres (Abs_viewres (Some (a,t))) = Some (a,t)"
by (auto simp add: Abs_viewres_inverse)
definition [code]: "extract_viewres_isNone r == Rep_viewres r = None"
definition [code]: "extract_viewres_a r ==
case (Rep_viewres r) of Some (a,t) \<Rightarrow> a"
definition "extract_viewres_t r ==
case (Rep_viewres r) of None \<Rightarrow> Abs_FingerTree Empty
| Some (a,t) \<Rightarrow> Abs_FingerTree t"
lemma [code abstract]: "Rep_FingerTree (extract_viewres_t r) =
(case (Rep_viewres r) of None \<Rightarrow> Empty | Some (a,t) \<Rightarrow> t)"
apply (cases r)
apply (auto split: option.split option.split_asm
simp add: extract_viewres_t_def Abs_viewres_inverse_Some)
done
definition "extract_viewres r ==
if extract_viewres_isNone r then None
else Some (extract_viewres_a r, extract_viewres_t r)"
typedef (overloaded) ('e,'a) splitres =
"{ ((l,a,r):: (('e,'a) FingerTreeStruc \<times> ('e \<times> 'a) \<times> ('e,'a::monoid_add) FingerTreeStruc))
| l a r.
FingerTreeStruc.ft_invar l \<and> FingerTreeStruc.ft_invar r}"
apply (rule_tac x="(Empty,undefined,Empty)" in exI)
apply auto
done
lemma [simp, code abstype]: "Abs_splitres (Rep_splitres x) = x"
by (rule Rep_splitres_inverse)
lemma Abs_splitres_inverse:
"FingerTreeStruc.ft_invar r \<Longrightarrow> FingerTreeStruc.ft_invar s \<Longrightarrow>
Rep_splitres (Abs_splitres ((r,a,s))) = (r,a,s)"
by (auto simp add: Abs_splitres_inverse)
definition [code]: "extract_splitres_a r == case (Rep_splitres r) of (l,a,s) \<Rightarrow> a"
definition "extract_splitres_l r == case (Rep_splitres r) of (l,a,r) \<Rightarrow>
Abs_FingerTree l"
lemma [code abstract]: "Rep_FingerTree (extract_splitres_l r) = (case
(Rep_splitres r) of (l,a,r) \<Rightarrow> l)"
apply (cases r)
apply (auto split: option.split option.split_asm
simp add: extract_splitres_l_def Abs_splitres_inverse)
done
definition "extract_splitres_r r == case (Rep_splitres r) of (l,a,r) \<Rightarrow>
Abs_FingerTree r"
lemma [code abstract]: "Rep_FingerTree (extract_splitres_r r) = (case
(Rep_splitres r) of (l,a,r) \<Rightarrow> r)"
apply (cases r)
apply (auto split: option.split option.split_asm
simp add: extract_splitres_r_def Abs_splitres_inverse)
done
definition "extract_splitres r ==
(extract_splitres_l r,
extract_splitres_a r,
extract_splitres_r r)"
subsubsection "Definition of Operations"
locale FingerTree_loc
begin
definition [code]: "toList t == FingerTreeStruc.toList (Rep_FingerTree t)"
definition empty where "empty == Abs_FingerTree FingerTreeStruc.Empty"
lemma [code abstract]: "Rep_FingerTree empty = FingerTreeStruc.Empty"
by (simp add: empty_def)
lemma empty_rep: "t=empty \<longleftrightarrow> Rep_FingerTree t = Empty"
apply (auto simp add: empty_def)
apply (metis Rep_FingerTree_inverse)
done
definition [code]: "annot t == FingerTreeStruc.annot (Rep_FingerTree t)"
definition "toTree t == Abs_FingerTree (FingerTreeStruc.toTree t)"
lemma [code abstract]: "Rep_FingerTree (toTree t) = FingerTreeStruc.toTree t"
by (simp add: toTree_def)
definition "lcons a t ==
Abs_FingerTree (FingerTreeStruc.lcons a (Rep_FingerTree t))"
lemma [code abstract]:
"Rep_FingerTree (lcons a t) = (FingerTreeStruc.lcons a (Rep_FingerTree t))"
by (simp add: lcons_def FingerTreeStruc.lcons_correct)
definition "rcons t a ==
Abs_FingerTree (FingerTreeStruc.rcons (Rep_FingerTree t) a)"
lemma [code abstract]:
"Rep_FingerTree (rcons t a) = (FingerTreeStruc.rcons (Rep_FingerTree t) a)"
by (simp add: rcons_def FingerTreeStruc.rcons_correct)
definition "viewL_aux t ==
Abs_viewres (FingerTreeStruc.viewL (Rep_FingerTree t))"
definition "viewL t == extract_viewres (viewL_aux t)"
lemma [code abstract]:
"Rep_viewres (viewL_aux t) = (FingerTreeStruc.viewL (Rep_FingerTree t))"
apply (cases "(FingerTreeStruc.viewL (Rep_FingerTree t))")
apply (auto simp add: viewL_aux_def )
apply (cases "Rep_FingerTree t = Empty")
apply simp
apply (auto
elim!: FingerTreeStruc.viewL_correct_nonEmpty
[of "Rep_FingerTree t", simplified]
simp add: Abs_viewres_inverse_Some)
done
definition "viewR_aux t ==
Abs_viewres (FingerTreeStruc.viewR (Rep_FingerTree t))"
definition "viewR t == extract_viewres (viewR_aux t)"
lemma [code abstract]:
"Rep_viewres (viewR_aux t) = (FingerTreeStruc.viewR (Rep_FingerTree t))"
apply (cases "(FingerTreeStruc.viewR (Rep_FingerTree t))")
apply (auto simp add: viewR_aux_def )
apply (cases "Rep_FingerTree t = Empty")
apply simp
apply (auto
elim!: FingerTreeStruc.viewR_correct_nonEmpty
[of "Rep_FingerTree t", simplified]
simp add: Abs_viewres_inverse_Some)
done
definition [code]: "isEmpty t == FingerTreeStruc.isEmpty (Rep_FingerTree t)"
definition [code]: "head t = FingerTreeStruc.head (Rep_FingerTree t)"
definition "tail t \<equiv>
if t=empty then
empty
else
Abs_FingerTree (FingerTreeStruc.tail (Rep_FingerTree t))"
\<comment> \<open>Make function total, to allow abstraction\<close>
lemma [code abstract]: "Rep_FingerTree (tail t) =
(if (FingerTreeStruc.isEmpty (Rep_FingerTree t)) then Empty
else FingerTreeStruc.tail (Rep_FingerTree t))"
apply (simp add: tail_def FingerTreeStruc.tail_correct FingerTreeStruc.isEmpty_def empty_rep)
apply (auto simp add: empty_def)
done
definition [code]: "headR t = FingerTreeStruc.headR (Rep_FingerTree t)"
definition "tailR t \<equiv>
if t=empty then
empty
else
Abs_FingerTree (FingerTreeStruc.tailR (Rep_FingerTree t))"
lemma [code abstract]: "Rep_FingerTree (tailR t) =
(if (FingerTreeStruc.isEmpty (Rep_FingerTree t)) then Empty
else FingerTreeStruc.tailR (Rep_FingerTree t))"
apply (simp add: tailR_def FingerTreeStruc.tailR_correct FingerTreeStruc.isEmpty_def empty_rep)
apply (simp add: empty_def)
done
definition "app s t = Abs_FingerTree (
FingerTreeStruc.app (Rep_FingerTree s) (Rep_FingerTree t))"
lemma [code abstract]:
"Rep_FingerTree (app s t) =
FingerTreeStruc.app (Rep_FingerTree s) (Rep_FingerTree t)"
by (simp add: app_def FingerTreeStruc.app_correct)
definition "splitTree_aux p i t == if (\<not>p i \<and> p (i+annot t)) then
Abs_splitres (FingerTreeStruc.splitTree p i (Rep_FingerTree t))
else
Abs_splitres (Empty,undefined,Empty)"
definition "splitTree p i t == extract_splitres (splitTree_aux p i t)"
lemma [code abstract]:
"Rep_splitres (splitTree_aux p i t) = (if (\<not>p i \<and> p (i+annot t)) then
(FingerTreeStruc.splitTree p i (Rep_FingerTree t))
else
(Empty,undefined,Empty))"
using FingerTreeStruc.splitTree_invpres[of "Rep_FingerTree t" p i]
apply (auto simp add: splitTree_aux_def annot_def Abs_splitres_inverse)
apply (cases "FingerTreeStruc.splitTree p i (Rep_FingerTree t)")
apply (force simp add: Abs_FingerTree_inverse Abs_splitres_inverse)
done
definition foldl where
[code]: "foldl f \<sigma> t == FingerTreeStruc.foldl f \<sigma> (Rep_FingerTree t)"
definition foldr where
[code]: "foldr f t \<sigma> == FingerTreeStruc.foldr f (Rep_FingerTree t) \<sigma>"
definition count where
[code]: "count t == FingerTreeStruc.count (Rep_FingerTree t)"
subsubsection "Correctness statements"
lemma empty_correct: "toList t = [] \<longleftrightarrow> t=empty"
apply (unfold toList_def empty_rep)
apply (simp add: FingerTreeStruc.toList_empty)
done
lemma toList_of_empty[simp]: "toList empty = []"
apply (unfold toList_def empty_def)
apply (auto simp add: FingerTreeStruc.toList_empty)
done
lemma annot_correct: "annot t = sum_list (map snd (toList t))"
apply (unfold toList_def annot_def)
apply (simp add: FingerTreeStruc.annot_correct)
done
lemma toTree_correct: "toList (toTree l) = l"
apply (unfold toList_def toTree_def)
apply (simp add: FingerTreeStruc.toTree_correct)
done
lemma lcons_correct: "toList (lcons a t) = a#toList t"
apply (unfold toList_def lcons_def)
apply (simp add: FingerTreeStruc.lcons_correct)
done
lemma rcons_correct: "toList (rcons t a) = toList t@[a]"
apply (unfold toList_def rcons_def)
apply (simp add: FingerTreeStruc.rcons_correct)
done
lemma viewL_correct:
"t = empty \<Longrightarrow> viewL t = None"
"t \<noteq> empty \<Longrightarrow> \<exists>a s. viewL t = Some (a,s) \<and> toList t = a#toList s"
apply (unfold toList_def viewL_def viewL_aux_def
extract_viewres_def extract_viewres_isNone_def
extract_viewres_a_def
extract_viewres_t_def
empty_rep)
apply (simp add: FingerTreeStruc.viewL_correct)
apply (drule FingerTreeStruc.viewL_correct(2)[OF Rep_FingerTree_invar])
apply (auto simp add: Abs_viewres_inverse)
done
lemma viewL_empty[simp]: "viewL empty = None"
using viewL_correct by auto
lemma viewL_nonEmpty:
assumes "t\<noteq>empty"
obtains a s where "viewL t = Some (a,s)" "toList t = a#toList s"
using assms viewL_correct by blast
lemma viewR_correct:
"t = empty \<Longrightarrow> viewR t = None"
"t \<noteq> empty \<Longrightarrow> \<exists>a s. viewR t = Some (a,s) \<and> toList t = toList s@[a]"
apply (unfold toList_def viewR_def viewR_aux_def
extract_viewres_def extract_viewres_isNone_def
extract_viewres_a_def
extract_viewres_t_def
empty_rep)
apply (simp add: FingerTreeStruc.viewR_correct)
apply (drule FingerTreeStruc.viewR_correct(2)[OF Rep_FingerTree_invar])
apply (auto simp add: Abs_viewres_inverse)
done
lemma viewR_empty[simp]: "viewR empty = None"
using viewR_correct by auto
lemma viewR_nonEmpty:
assumes "t\<noteq>empty"
obtains a s where "viewR t = Some (a,s)" "toList t = toList s@[a]"
using assms viewR_correct by blast
lemma isEmpty_correct: "isEmpty t \<longleftrightarrow> t=empty"
apply (unfold toList_def isEmpty_def empty_rep)
apply (simp add: FingerTreeStruc.isEmpty_correct FingerTreeStruc.toList_empty)
done
lemma head_correct: "t\<noteq>empty \<Longrightarrow> head t = hd (toList t)"
apply (unfold toList_def head_def empty_rep)
apply (simp add: FingerTreeStruc.head_correct)
done
lemma tail_correct: "t\<noteq>empty \<Longrightarrow> toList (tail t) = tl (toList t)"
apply (unfold toList_def tail_def empty_rep)
apply (simp add: FingerTreeStruc.tail_correct)
done
lemma headR_correct: "t\<noteq>empty \<Longrightarrow> headR t = last (toList t)"
apply (unfold toList_def headR_def empty_rep)
apply (simp add: FingerTreeStruc.headR_correct)
done
lemma tailR_correct: "t\<noteq>empty \<Longrightarrow> toList (tailR t) = butlast (toList t)"
apply (unfold toList_def tailR_def empty_rep)
apply (simp add: FingerTreeStruc.tailR_correct)
done
lemma app_correct: "toList (app s t) = toList s @ toList t"
apply (unfold toList_def app_def)
apply (simp add: FingerTreeStruc.app_correct)
done
lemma splitTree_correct:
assumes mono: "\<forall>a b. p a \<longrightarrow> p (a + b)"
assumes init_ff: "\<not> p i"
assumes sum_tt: "p (i + annot s)"
assumes fmt: "(splitTree p i s) = (l, (e,a), r)"
shows "(toList s) = (toList l) @ (e,a) # (toList r)"
and "\<not> p (i + annot l)"
and "p (i + annot l + a)"
apply (rule
FingerTreeStruc.splitTree_correctE[
where p=p and s="Rep_FingerTree s",
OF _ mono init_ff sum_tt[unfolded annot_def],
simplified
])
using fmt
apply (unfold toList_def splitTree_aux_def splitTree_def annot_def
extract_splitres_def extract_splitres_l_def
extract_splitres_a_def extract_splitres_r_def) [1]
apply (auto split: if_split_asm prod.split_asm
simp add: init_ff sum_tt[unfolded annot_def] Abs_splitres_inverse) [1]
apply (rule
FingerTreeStruc.splitTree_correctE[
where p=p and s="Rep_FingerTree s",
OF _ mono init_ff sum_tt[unfolded annot_def],
simplified
])
using fmt
apply (unfold toList_def splitTree_aux_def splitTree_def annot_def
extract_splitres_def extract_splitres_l_def
extract_splitres_a_def extract_splitres_r_def) [1]
apply (auto split: if_split_asm prod.split_asm
simp add: init_ff sum_tt[unfolded annot_def] Abs_splitres_inverse) [1]
apply (rule
FingerTreeStruc.splitTree_correctE[
where p=p and s="Rep_FingerTree s",
OF _ mono init_ff sum_tt[unfolded annot_def],
simplified
])
using fmt
apply (unfold toList_def splitTree_aux_def splitTree_def annot_def
extract_splitres_def extract_splitres_l_def
extract_splitres_a_def extract_splitres_r_def) [1]
apply (auto split: if_split_asm prod.split_asm
simp add: init_ff sum_tt[unfolded annot_def] Abs_splitres_inverse) [1]
done
lemma splitTree_correctE:
assumes mono: "\<forall>a b. p a \<longrightarrow> p (a + b)"
assumes init_ff: "\<not> p i"
assumes sum_tt: "p (i + annot s)"
obtains l e a r where
"(splitTree p i s) = (l, (e,a), r)" and
"(toList s) = (toList l) @ (e,a) # (toList r)" and
"\<not> p (i + annot l)" and
"p (i + annot l + a)"
proof -
obtain l e a r where fmt: "(splitTree p i s) = (l, (e,a), r)"
by (cases "(splitTree p i s)") auto
from splitTree_correct[of p, OF assms fmt] fmt
show ?thesis
by (blast intro: that)
qed
lemma foldl_correct: "foldl f \<sigma> t = List.foldl f \<sigma> (toList t)"
apply (unfold toList_def foldl_def)
apply (simp add: FingerTreeStruc.foldl_correct)
done
lemma foldr_correct: "foldr f t \<sigma> = List.foldr f (toList t) \<sigma>"
apply (unfold toList_def foldr_def)
apply (simp add: FingerTreeStruc.foldr_correct)
done
lemma count_correct: "count t = length (toList t)"
apply (unfold toList_def count_def)
apply (simp add: FingerTreeStruc.count_correct)
done
end
interpretation FingerTree: FingerTree_loc .
text_raw\<open>\clearpage\<close>
subsection "Interface Documentation"
text_raw\<open>\label{sec:doc}\<close>
text \<open>
In this section, we list all supported operations on finger trees,
along with a short plaintext documentation and their correctness statements.
\<close>
(*#DOC
fun [no_spec] FingerTree.toList
Convert to list ($O(n)$)
fun FingerTree.empty
The empty finger tree ($O(1)$)
fun FingerTree.annot
Return sum of all annotations ($O(1)$)
fun FingerTree.toTree
Convert list to finger tree ($O(n\log(n))$)
fun FingerTree.lcons
Append element at the left end ($O(\log(n))$, $O(1)$ amortized)
fun FingerTree.rcons
Append element at the right end ($O(\log(n))$, $O(1)$ amortized)
fun FingerTree.viewL
Detach leftmost element ($O(\log(n))$, $O(1)$ amortized)
fun FingerTree.viewR
Detach rightmost element ($O(\log(n))$, $O(1)$ amortized)
fun FingerTree.isEmpty
Check whether tree is empty ($O(1)$)
fun FingerTree.head
Get leftmost element of non-empty tree ($O(\log(n))$)
fun FingerTree.tail
Get all but leftmost element of non-empty tree ($O(\log(n))$)
fun FingerTree.headR
Get rightmost element of non-empty tree ($O(\log(n))$)
fun FingerTree.tailR
Get all but rightmost element of non-empty tree ($O(\log(n))$)
fun FingerTree.app
Concatenate two finger trees ($O(\log(m+n))$)
fun [long_type] FingerTree.splitTree
Split tree by a monotone predicate. ($O(\log(n))$)
A predicate $p$ over the annotations is called monotone, iff, for all
annotations
$a,b$ with $p(a)$, we have already $p(a+b)$.
Splitting is done by specifying a monotone predicate $p$ that does not hold
for the initial value $i$ of the summation, but holds for $i$ plus the sum
of all annotations. The tree is then split at the position where $p$ starts to
hold for the sum of all elements up to that position.
fun [long_type] FingerTree.foldl
Fold with function from left
fun [long_type] FingerTree.foldr
Fold with function from right
fun FingerTree.count
Return the number of elements
*)
text \<open>
\underline{@{term_type "FingerTree.toList"}}\\
Convert to list ($O(n)$)\\
\underline{@{term_type "FingerTree.empty"}}\\
The empty finger tree ($O(1)$)\\
{\bf Spec} \<open>FingerTree.empty_correct\<close>:
@{thm [display] "FingerTree.empty_correct"}
\underline{@{term_type "FingerTree.annot"}}\\
Return sum of all annotations ($O(1)$)\\
{\bf Spec} \<open>FingerTree.annot_correct\<close>:
@{thm [display] "FingerTree.annot_correct"}
\underline{@{term_type "FingerTree.toTree"}}\\
Convert list to finger tree ($O(n\log(n))$)\\
{\bf Spec} \<open>FingerTree.toTree_correct\<close>:
@{thm [display] "FingerTree.toTree_correct"}
\underline{@{term_type "FingerTree.lcons"}}\\
Append element at the left end ($O(\log(n))$, $O(1)$ amortized)\\
{\bf Spec} \<open>FingerTree.lcons_correct\<close>:
@{thm [display] "FingerTree.lcons_correct"}
\underline{@{term_type "FingerTree.rcons"}}\\
Append element at the right end ($O(\log(n))$, $O(1)$ amortized)\\
{\bf Spec} \<open>FingerTree.rcons_correct\<close>:
@{thm [display] "FingerTree.rcons_correct"}
\underline{@{term_type "FingerTree.viewL"}}\\
Detach leftmost element ($O(\log(n))$, $O(1)$ amortized)\\
{\bf Spec} \<open>FingerTree.viewL_correct\<close>:
@{thm [display] "FingerTree.viewL_correct"}
\underline{@{term_type "FingerTree.viewR"}}\\
Detach rightmost element ($O(\log(n))$, $O(1)$ amortized)\\
{\bf Spec} \<open>FingerTree.viewR_correct\<close>:
@{thm [display] "FingerTree.viewR_correct"}
\underline{@{term_type "FingerTree.isEmpty"}}\\
Check whether tree is empty ($O(1)$)\\
{\bf Spec} \<open>FingerTree.isEmpty_correct\<close>:
@{thm [display] "FingerTree.isEmpty_correct"}
\underline{@{term_type "FingerTree.head"}}\\
Get leftmost element of non-empty tree ($O(\log(n))$)\\
{\bf Spec} \<open>FingerTree.head_correct\<close>:
@{thm [display] "FingerTree.head_correct"}
\underline{@{term_type "FingerTree.tail"}}\\
Get all but leftmost element of non-empty tree ($O(\log(n))$)\\
{\bf Spec} \<open>FingerTree.tail_correct\<close>:
@{thm [display] "FingerTree.tail_correct"}
\underline{@{term_type "FingerTree.headR"}}\\
Get rightmost element of non-empty tree ($O(\log(n))$)\\
{\bf Spec} \<open>FingerTree.headR_correct\<close>:
@{thm [display] "FingerTree.headR_correct"}
\underline{@{term_type "FingerTree.tailR"}}\\
Get all but rightmost element of non-empty tree ($O(\log(n))$)\\
{\bf Spec} \<open>FingerTree.tailR_correct\<close>:
@{thm [display] "FingerTree.tailR_correct"}
\underline{@{term_type "FingerTree.app"}}\\
Concatenate two finger trees ($O(\log(m+n))$)\\
{\bf Spec} \<open>FingerTree.app_correct\<close>:
@{thm [display] "FingerTree.app_correct"}
\underline{@{term "FingerTree.splitTree"}}
@{term_type [display] "FingerTree.splitTree"}
Split tree by a monotone predicate. ($O(\log(n))$)
A predicate $p$ over the annotations is called monotone, iff, for all
annotations
$a,b$ with $p(a)$, we have already $p(a+b)$.
Splitting is done by specifying a monotone predicate $p$ that does not hold
for the initial value $i$ of the summation, but holds for $i$ plus the sum
of all annotations. The tree is then split at the position where $p$ starts to
hold for the sum of all elements up to that position.\\
{\bf Spec} \<open>FingerTree.splitTree_correct\<close>:
@{thm [display] "FingerTree.splitTree_correct"}
\underline{@{term "FingerTree.foldl"}}
@{term_type [display] "FingerTree.foldl"}
Fold with function from left\\
{\bf Spec} \<open>FingerTree.foldl_correct\<close>:
@{thm [display] "FingerTree.foldl_correct"}
\underline{@{term "FingerTree.foldr"}}
@{term_type [display] "FingerTree.foldr"}
Fold with function from right\\
{\bf Spec} \<open>FingerTree.foldr_correct\<close>:
@{thm [display] "FingerTree.foldr_correct"}
\underline{@{term_type "FingerTree.count"}}\\
Return the number of elements\\
{\bf Spec} \<open>FingerTree.count_correct\<close>:
@{thm [display] "FingerTree.count_correct"}
\<close>
end
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the 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 file is also distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** An extension of [FSetAVL] (finite sets as balanced binary search trees)
with extra interval-based operations, more efficient than standard
operations. *)
Require Import FSetInterface.
Require FSetAVL.
Require Import Coqlib.
Module Make(X: OrderedType).
Include FSetAVL.Make(X).
Module Raw := MSet.Raw.
Section MEM_BETWEEN.
(** [mem_between above below s] is [true] iff there exists an element of [s]
that belongs to the interval described by the predicates [above] and [below].
Using the monotonicity of [above] and [below], the implementation of
[mem_between] avoids traversing the subtrees of [s] that
lie entirely outside the interval of interest. *)
Variable above_low_bound: elt -> bool.
Variable below_high_bound: elt -> bool.
Fixpoint raw_mem_between (m: Raw.tree) : bool :=
match m with
| Raw.Leaf => false
| Raw.Node _ l x r =>
if above_low_bound x
then if below_high_bound x
then true
else raw_mem_between l
else raw_mem_between r
end.
Definition mem_between (m: t) : bool := raw_mem_between m.(MSet.this).
Hypothesis above_monotone:
forall x1 x2, X.eq x1 x2 \/ X.lt x1 x2 -> above_low_bound x1 = true -> above_low_bound x2 = true.
Hypothesis below_monotone:
forall x1 x2, X.eq x1 x2 \/ X.lt x2 x1 -> below_high_bound x1 = true -> below_high_bound x2 = true.
Lemma raw_mem_between_1:
forall m,
raw_mem_between m = true ->
exists x, Raw.In x m /\ above_low_bound x = true /\ below_high_bound x = true.
Proof.
induction m; simpl; intros.
- discriminate.
- destruct (above_low_bound t1) eqn: LB; [destruct (below_high_bound t1) eqn: HB | idtac].
+ (* in interval *)
exists t1; split; auto. apply Raw.IsRoot. auto.
+ (* above interval *)
exploit IHm1; auto. intros [x' [A B]]. exists x'; split; auto. apply Raw.InLeft; auto.
+ (* below interval *)
exploit IHm2; auto. intros [x' [A B]]. exists x'; split; auto. apply Raw.InRight; auto.
Qed.
Lemma raw_mem_between_2:
forall x m,
Raw.bst m ->
Raw.In x m -> above_low_bound x = true -> below_high_bound x = true ->
raw_mem_between m = true.
Proof.
induction 1; simpl; intros.
- inv H.
- rewrite Raw.In_node_iff in H1.
destruct (above_low_bound x0) eqn: LB; [destruct (below_high_bound x0) eqn: HB | idtac].
+ (* in interval *)
auto.
+ (* above interval *)
assert (X.eq x x0 \/ X.lt x0 x -> False).
{ intros. exploit below_monotone; eauto. congruence. }
intuition.
+ assert (X.eq x x0 \/ X.lt x x0 -> False).
{ intros. exploit above_monotone; eauto. congruence. }
intuition.
Qed.
Theorem mem_between_1:
forall s,
mem_between s = true ->
exists x, In x s /\ above_low_bound x = true /\ below_high_bound x = true.
Proof.
intros. apply raw_mem_between_1. auto.
Qed.
Theorem mem_between_2:
forall x s,
In x s -> above_low_bound x = true -> below_high_bound x = true ->
mem_between s = true.
Proof.
unfold mem_between; intros. apply raw_mem_between_2 with x; auto. apply MSet.is_ok.
Qed.
End MEM_BETWEEN.
Section ELEMENTS_BETWEEN.
(** [elements_between above below s] returns the set of elements of [s]
that belong to the interval [above,below]. *)
Variable above_low_bound: elt -> bool.
Variable below_high_bound: elt -> bool.
Fixpoint raw_elements_between (m: Raw.tree) : Raw.tree :=
match m with
| Raw.Leaf => Raw.Leaf
| Raw.Node _ l x r =>
if above_low_bound x then
if below_high_bound x then
Raw.join (raw_elements_between l) x (raw_elements_between r)
else
raw_elements_between l
else
raw_elements_between r
end.
Remark In_raw_elements_between_1:
forall x m,
Raw.In x (raw_elements_between m) -> Raw.In x m.
Proof.
induction m; simpl; intros.
- inv H.
- rewrite Raw.In_node_iff.
destruct (above_low_bound t1) eqn:LB; [destruct (below_high_bound t1) eqn: RB | idtac]; simpl in H.
+ rewrite Raw.join_spec in H. intuition.
+ left; apply IHm1; auto.
+ right; right; apply IHm2; auto.
Qed.
Lemma raw_elements_between_ok:
forall m, Raw.bst m -> Raw.bst (raw_elements_between m).
Proof.
induction 1; simpl.
- constructor.
- destruct (above_low_bound x) eqn:LB; [destruct (below_high_bound x) eqn: RB | idtac]; simpl.
+ apply Raw.join_ok; auto.
red; intros. apply l0. apply In_raw_elements_between_1; auto.
red; intros. apply g. apply In_raw_elements_between_1; auto.
+ auto.
+ auto.
Qed.
Definition elements_between (s: t) : t :=
@MSet.Mkt (raw_elements_between s.(MSet.this)) (raw_elements_between_ok s.(MSet.this) s.(MSet.is_ok)).
Hypothesis above_monotone:
forall x1 x2, X.eq x1 x2 \/ X.lt x1 x2 -> above_low_bound x1 = true -> above_low_bound x2 = true.
Hypothesis below_monotone:
forall x1 x2, X.eq x1 x2 \/ X.lt x2 x1 -> below_high_bound x1 = true -> below_high_bound x2 = true.
Remark In_raw_elements_between_2:
forall x m,
Raw.In x (raw_elements_between m) -> above_low_bound x = true /\ below_high_bound x = true.
Proof.
induction m; simpl; intros.
- inv H.
- destruct (above_low_bound t1) eqn:LB; [destruct (below_high_bound t1) eqn: RB | idtac]; simpl in H.
+ rewrite Raw.join_spec in H. intuition.
apply above_monotone with t1; auto.
apply below_monotone with t1; auto.
+ auto.
+ auto.
Qed.
Remark In_raw_elements_between_3:
forall x m,
Raw.bst m ->
Raw.In x m -> above_low_bound x = true -> below_high_bound x = true ->
Raw.In x (raw_elements_between m).
Proof.
induction 1; simpl; intros.
- auto.
- rewrite Raw.In_node_iff in H1.
destruct (above_low_bound x0) eqn:LB; [destruct (below_high_bound x0) eqn: RB | idtac].
+ rewrite Raw.join_spec. intuition.
+ assert (X.eq x x0 \/ X.lt x0 x -> False).
{ intros. exploit below_monotone; eauto. congruence. }
intuition. elim H7. apply g. auto.
+ assert (X.eq x x0 \/ X.lt x x0 -> False).
{ intros. exploit above_monotone; eauto. congruence. }
intuition. elim H7. apply l0. auto.
Qed.
Theorem elements_between_iff:
forall x s,
In x (elements_between s) <-> In x s /\ above_low_bound x = true /\ below_high_bound x = true.
Proof.
intros. unfold elements_between, In; simpl. split.
intros. split. apply In_raw_elements_between_1; auto. eapply In_raw_elements_between_2; eauto.
intros [A [B C]]. apply In_raw_elements_between_3; auto. apply MSet.is_ok.
Qed.
End ELEMENTS_BETWEEN.
Section FOR_ALL_BETWEEN.
(** [for_all_between pred above below s] is [true] iff all elements of [s]
in a given variation interval satisfy predicate [pred].
The variation interval is given by two predicates [above] and [below]
which must both hold if the element is part of the interval.
Using the monotonicity of [above] and [below], the implementation of
[for_all_between] avoids traversing the subtrees of [s] that
lie entirely outside the interval of interest. *)
Variable pred: elt -> bool.
Variable above_low_bound: elt -> bool.
Variable below_high_bound: elt -> bool.
Fixpoint raw_for_all_between (m: Raw.tree) : bool :=
match m with
| Raw.Leaf => true
| Raw.Node _ l x r =>
if above_low_bound x
then if below_high_bound x
then raw_for_all_between l && pred x && raw_for_all_between r
else raw_for_all_between l
else raw_for_all_between r
end.
Definition for_all_between (m: t) : bool := raw_for_all_between m.(MSet.this).
Hypothesis pred_compat:
forall x1 x2, X.eq x1 x2 -> pred x1 = pred x2.
Hypothesis above_monotone:
forall x1 x2, X.eq x1 x2 \/ X.lt x1 x2 -> above_low_bound x1 = true -> above_low_bound x2 = true.
Hypothesis below_monotone:
forall x1 x2, X.eq x1 x2 \/ X.lt x2 x1 -> below_high_bound x1 = true -> below_high_bound x2 = true.
Lemma raw_for_all_between_1:
forall x m,
Raw.bst m ->
raw_for_all_between m = true ->
Raw.In x m ->
above_low_bound x = true ->
below_high_bound x = true ->
pred x = true.
Proof.
induction 1; simpl; intros.
- inv H0.
- destruct (above_low_bound x0) eqn: LB; [destruct (below_high_bound x0) eqn: HB | idtac].
+ (* in interval *)
destruct (andb_prop _ _ H1) as [P C]. destruct (andb_prop _ _ P) as [A B]. clear H1 P.
inv H2.
* erewrite pred_compat; eauto.
* apply IHbst1; auto.
* apply IHbst2; auto.
+ (* above interval *)
inv H2.
* assert (below_high_bound x0 = true) by (apply below_monotone with x; auto).
congruence.
* apply IHbst1; auto.
* assert (below_high_bound x0 = true) by (apply below_monotone with x; auto).
congruence.
+ (* below interval *)
inv H2.
* assert (above_low_bound x0 = true) by (apply above_monotone with x; auto).
congruence.
* assert (above_low_bound x0 = true) by (apply above_monotone with x; auto).
congruence.
* apply IHbst2; auto.
Qed.
Lemma raw_for_all_between_2:
forall m,
Raw.bst m ->
(forall x, Raw.In x m -> above_low_bound x = true -> below_high_bound x = true -> pred x = true) ->
raw_for_all_between m = true.
Proof.
induction 1; intros; simpl.
- auto.
- destruct (above_low_bound x) eqn: LB; [destruct (below_high_bound x) eqn: HB | idtac].
+ (* in interval *)
rewrite IHbst1. rewrite (H1 x). rewrite IHbst2. auto.
intros. apply H1; auto. apply Raw.InRight; auto.
apply Raw.IsRoot. reflexivity. auto. auto.
intros. apply H1; auto. apply Raw.InLeft; auto.
+ (* above interval *)
apply IHbst1. intros. apply H1; auto. apply Raw.InLeft; auto.
+ (* below interval *)
apply IHbst2. intros. apply H1; auto. apply Raw.InRight; auto.
Qed.
Theorem for_all_between_iff:
forall s,
for_all_between s = true <-> (forall x, In x s -> above_low_bound x = true -> below_high_bound x = true -> pred x = true).
Proof.
unfold for_all_between; intros; split; intros.
- eapply raw_for_all_between_1; eauto. apply MSet.is_ok.
- apply raw_for_all_between_2; auto. apply MSet.is_ok.
Qed.
End FOR_ALL_BETWEEN.
Section PARTITION_BETWEEN.
Variable above_low_bound: elt -> bool.
Variable below_high_bound: elt -> bool.
Fixpoint raw_partition_between (m: Raw.tree) : Raw.tree * Raw.tree :=
match m with
| Raw.Leaf => (Raw.Leaf, Raw.Leaf)
| Raw.Node _ l x r =>
if above_low_bound x then
if below_high_bound x then
(let (l1, l2) := raw_partition_between l in
let (r1, r2) := raw_partition_between r in
(Raw.join l1 x r1, Raw.concat l2 r2))
else
(let (l1, l2) := raw_partition_between l in
(l1, Raw.join l2 x r))
else
(let (r1, r2) := raw_partition_between r in
(r1, Raw.join l x r2))
end.
Remark In_raw_partition_between_1:
forall x m,
Raw.In x (fst (raw_partition_between m)) -> Raw.In x m.
Proof.
induction m; simpl; intros.
- inv H.
- destruct (raw_partition_between m1) as [l1 l2] eqn:LEQ; simpl in *.
destruct (raw_partition_between m2) as [r1 r2] eqn:REQ; simpl in *.
destruct (above_low_bound t1) eqn:LB; [destruct (below_high_bound t1) eqn: RB | idtac]; simpl in H.
+ rewrite Raw.join_spec in H. rewrite Raw.In_node_iff. intuition.
+ rewrite Raw.In_node_iff. intuition.
+ rewrite Raw.In_node_iff. intuition.
Qed.
Remark In_raw_partition_between_2:
forall x m,
Raw.In x (snd (raw_partition_between m)) -> Raw.In x m.
Proof.
induction m; simpl; intros.
- inv H.
- destruct (raw_partition_between m1) as [l1 l2] eqn:LEQ; simpl in *.
destruct (raw_partition_between m2) as [r1 r2] eqn:REQ; simpl in *.
destruct (above_low_bound t1) eqn:LB; [destruct (below_high_bound t1) eqn: RB | idtac]; simpl in H.
+ rewrite Raw.concat_spec in H. rewrite Raw.In_node_iff. intuition.
+ rewrite Raw.join_spec in H. rewrite Raw.In_node_iff. intuition.
+ rewrite Raw.join_spec in H. rewrite Raw.In_node_iff. intuition.
Qed.
Lemma raw_partition_between_ok:
forall m, Raw.bst m -> Raw.bst (fst (raw_partition_between m)) /\ Raw.bst (snd (raw_partition_between m)).
Proof.
induction 1; simpl.
- split; constructor.
- destruct IHbst1 as [L1 L2]. destruct IHbst2 as [R1 R2].
destruct (raw_partition_between l) as [l1 l2] eqn:LEQ; simpl in *.
destruct (raw_partition_between r) as [r1 r2] eqn:REQ; simpl in *.
destruct (above_low_bound x) eqn:LB; [destruct (below_high_bound x) eqn: RB | idtac]; simpl.
+ split.
apply Raw.join_ok; auto.
red; intros. apply l0. apply In_raw_partition_between_1. rewrite LEQ; auto.
red; intros. apply g. apply In_raw_partition_between_1. rewrite REQ; auto.
apply Raw.concat_ok; auto.
intros. transitivity x.
apply l0. apply In_raw_partition_between_2. rewrite LEQ; auto.
apply g. apply In_raw_partition_between_2. rewrite REQ; auto.
+ split.
auto.
apply Raw.join_ok; auto.
red; intros. apply l0. apply In_raw_partition_between_2. rewrite LEQ; auto.
+ split.
auto.
apply Raw.join_ok; auto.
red; intros. apply g. apply In_raw_partition_between_2. rewrite REQ; auto.
Qed.
Hypothesis above_monotone:
forall x1 x2, X.eq x1 x2 \/ X.lt x1 x2 -> above_low_bound x1 = true -> above_low_bound x2 = true.
Hypothesis below_monotone:
forall x1 x2, X.eq x1 x2 \/ X.lt x2 x1 -> below_high_bound x1 = true -> below_high_bound x2 = true.
Remark In_raw_partition_between_3:
forall x m,
Raw.In x (fst (raw_partition_between m)) -> above_low_bound x = true /\ below_high_bound x = true.
Proof.
induction m; simpl; intros.
- inv H.
- destruct (raw_partition_between m1) as [l1 l2] eqn:LEQ; simpl in *.
destruct (raw_partition_between m2) as [r1 r2] eqn:REQ; simpl in *.
destruct (above_low_bound t1) eqn:LB; [destruct (below_high_bound t1) eqn: RB | idtac]; simpl in H.
+ rewrite Raw.join_spec in H. intuition.
apply above_monotone with t1; auto.
apply below_monotone with t1; auto.
+ auto.
+ auto.
Qed.
Remark In_raw_partition_between_4:
forall x m,
Raw.bst m ->
Raw.In x (snd (raw_partition_between m)) -> above_low_bound x = false \/ below_high_bound x = false.
Proof.
induction 1; simpl; intros.
- inv H.
- destruct (raw_partition_between l) as [l1 l2] eqn:LEQ; simpl in *.
destruct (raw_partition_between r) as [r1 r2] eqn:REQ; simpl in *.
destruct (above_low_bound x0) eqn:LB; [destruct (below_high_bound x0) eqn: RB | idtac]; simpl in H.
+ simpl in H1. rewrite Raw.concat_spec in H1. intuition.
+ assert (forall y, X.eq y x0 \/ X.lt x0 y -> below_high_bound y = false).
{ intros. destruct (below_high_bound y) eqn:E; auto.
assert (below_high_bound x0 = true) by (apply below_monotone with y; auto).
congruence. }
simpl in H1. rewrite Raw.join_spec in H1. intuition.
+ assert (forall y, X.eq y x0 \/ X.lt y x0 -> above_low_bound y = false).
{ intros. destruct (above_low_bound y) eqn:E; auto.
assert (above_low_bound x0 = true) by (apply above_monotone with y; auto).
congruence. }
simpl in H1. rewrite Raw.join_spec in H1. intuition.
Qed.
Remark In_raw_partition_between_5:
forall x m,
Raw.bst m ->
Raw.In x m -> above_low_bound x = true -> below_high_bound x = true ->
Raw.In x (fst (raw_partition_between m)).
Proof.
induction 1; simpl; intros.
- inv H.
- destruct (raw_partition_between l) as [l1 l2] eqn:LEQ; simpl in *.
destruct (raw_partition_between r) as [r1 r2] eqn:REQ; simpl in *.
destruct (above_low_bound x0) eqn:LB; [destruct (below_high_bound x0) eqn: RB | idtac]; simpl in H.
+ simpl. rewrite Raw.join_spec. inv H1.
auto.
right; left; apply IHbst1; auto.
right; right; apply IHbst2; auto.
+ simpl. inv H1.
assert (below_high_bound x0 = true) by (apply below_monotone with x; auto).
congruence.
auto.
assert (below_high_bound x0 = true) by (apply below_monotone with x; auto).
congruence.
+ simpl. inv H1.
assert (above_low_bound x0 = true) by (apply above_monotone with x; auto).
congruence.
assert (above_low_bound x0 = true) by (apply above_monotone with x; auto).
congruence.
eauto.
Qed.
Remark In_raw_partition_between_6:
forall x m,
Raw.bst m ->
Raw.In x m -> above_low_bound x = false \/ below_high_bound x = false ->
Raw.In x (snd (raw_partition_between m)).
Proof.
induction 1; simpl; intros.
- inv H.
- destruct (raw_partition_between l) as [l1 l2] eqn:LEQ; simpl in *.
destruct (raw_partition_between r) as [r1 r2] eqn:REQ; simpl in *.
destruct (above_low_bound x0) eqn:LB; [destruct (below_high_bound x0) eqn: RB | idtac]; simpl in H.
+ simpl. rewrite Raw.concat_spec. inv H1.
assert (below_high_bound x = true) by (apply below_monotone with x0; auto; left; symmetry; auto).
assert (above_low_bound x = true) by (apply above_monotone with x0; auto; left; symmetry; auto).
destruct H2; congruence.
left; apply IHbst1; auto.
right; apply IHbst2; auto.
+ simpl. rewrite Raw.join_spec. inv H1.
auto.
right; left; apply IHbst1; auto.
auto.
+ simpl. rewrite Raw.join_spec. inv H1.
auto.
auto.
right; right; apply IHbst2; auto.
Qed.
Definition partition_between (s: t) : t * t :=
let p := raw_partition_between s.(MSet.this) in
(@MSet.Mkt (fst p) (proj1 (raw_partition_between_ok s.(MSet.this) s.(MSet.is_ok))),
@MSet.Mkt (snd p) (proj2 (raw_partition_between_ok s.(MSet.this) s.(MSet.is_ok)))).
Theorem partition_between_iff_1:
forall x s,
In x (fst (partition_between s)) <->
In x s /\ above_low_bound x = true /\ below_high_bound x = true.
Proof.
intros. unfold partition_between, In; simpl. split.
intros. split. apply In_raw_partition_between_1; auto. eapply In_raw_partition_between_3; eauto.
intros [A [B C]]. apply In_raw_partition_between_5; auto. apply MSet.is_ok.
Qed.
Theorem partition_between_iff_2:
forall x s,
In x (snd (partition_between s)) <->
In x s /\ (above_low_bound x = false \/ below_high_bound x = false).
Proof.
intros. unfold partition_between, In; simpl. split.
intros. split. apply In_raw_partition_between_2; auto. eapply In_raw_partition_between_4; eauto. apply MSet.is_ok.
intros [A B]. apply In_raw_partition_between_6; auto. apply MSet.is_ok.
Qed.
End PARTITION_BETWEEN.
End Make.
|
lemma limpt_sequential_inj: fixes x :: "'a::metric_space" shows "x islimpt S \<longleftrightarrow> (\<exists>f. (\<forall>n::nat. f n \<in> S - {x}) \<and> inj f \<and> (f \<longlongrightarrow> x) sequentially)" (is "?lhs = ?rhs") |
proposition locally_compact: fixes s :: "'a :: metric_space set" shows "locally compact s \<longleftrightarrow> (\<forall>x \<in> s. \<exists>u v. x \<in> u \<and> u \<subseteq> v \<and> v \<subseteq> s \<and> openin (top_of_set s) u \<and> compact v)" (is "?lhs = ?rhs") |
It has been argued that the play 's themes of duplicity and ambivalence are inextricably bound up with Wilde 's homosexuality , and that the play exhibits a " flickering presence @-@ absence of … homosexual desire " . On re @-@ reading the play after his release from prison , Wilde said : " It was extraordinary reading the play over . How I used to toy with that Tiger Life . " As one scholar has put it , the absolute necessity for homosexuals of the period to " need a public mask is a factor contributing to the satire on social disguise . "
|
section \<open>Special constants\<close>
theory Consts
imports
Constructors
Higher_Order_Terms.Nterm
begin
locale special_constants = constructors
locale pre_constants = special_constants +
fixes heads :: "name fset"
begin
definition all_consts :: "name fset" where
"all_consts = heads |\<union>| C"
abbreviation welldefined :: "'a::term \<Rightarrow> bool" where
"welldefined t \<equiv> consts t |\<subseteq>| all_consts"
sublocale welldefined: simple_syntactic_and welldefined
by standard auto
end
declare pre_constants.all_consts_def[code]
locale constants = pre_constants +
assumes disjnt: "fdisjnt heads C"
\<comment> \<open>Conceptually the following assumptions should belong into @{locale constructors}, but I prefer
to keep that one assumption-free.\<close>
assumes distinct_ctr: "distinct all_constructors"
begin
lemma distinct_ctr': "distinct (map as_string all_constructors)"
unfolding distinct_map
using distinct_ctr
by (auto intro: inj_onI dest: name.expand)
end
end |
From Pony Require Import Language LocalMap.
Require Import Coq.FSets.FMapInterface.
Require Import Coq.Structures.Equalities.
Module Context (Map : WSfun).
Export Syntax.
Module LocalMap := LocalMap Map.
Export LocalMap.
Definition context : Type := (LocalMap.t aliasedType ponyType).
Definition sendableCtxt (gamma : context) : context :=
LocalMap.fold_var
(fun var varType sendableMap =>
match varType with
| aType _ b =>
if isSendable b
then LocalMap.addVar var varType sendableMap
else sendableMap
end)
gamma
(LocalMap.empty aliasedType ponyType).
End Context.
Module Typing (Map : WSfun).
Module Program := Program Map.
Export Program.
Module Context := Context Map.
Import Context.
Import Context.LocalMap.
(* Partial function - not defined for @tag@ *)
Definition viewAdapt
(objCap : capability)
(fieldCap : baseCapability)
: option capability :=
match objCap with
| base iso =>
match fieldCap with
| iso => Some (base iso)
| trn => Some (base iso)
| ref => Some (base iso)
| val => Some (base val)
| box => Some (base tag)
| tag => Some (base tag)
end
| base trn =>
match fieldCap with
| iso => Some (base iso)
| trn => Some (base trn)
| ref => Some (base trn)
| val => Some (base val)
| box => Some (base box)
| tag => Some (base tag)
end
| base ref =>
match fieldCap with
| iso => Some (base iso)
| trn => Some (base trn)
| ref => Some (base ref)
| val => Some (base val)
| box => Some (base box)
| tag => Some (base tag)
end
| base val =>
match fieldCap with
| iso => Some (base val)
| trn => Some (base val)
| ref => Some (base val)
| val => Some (base val)
| box => Some (base val)
| tag => Some (base val)
end
| base box =>
match fieldCap with
| iso => Some (base tag)
| trn => Some (base box)
| ref => Some (base box)
| val => Some (base val)
| box => Some (base box)
| tag => Some (base tag)
end
| base tag => None
| isohat =>
match fieldCap with
| iso => Some isohat
| trn => Some isohat
| ref => Some isohat
| val => Some (base val)
| box => Some (base val)
| tag => Some (base tag)
end
| trnhat =>
match fieldCap with
| iso => Some isohat
| trn => Some trnhat
| ref => Some trnhat
| val => Some (base val)
| box => Some (base val)
| tag => Some (base tag)
end
end.
(* Partial function - not defined for @val@, @box@, @tag@ *)
Definition writeAdapt
(objCap : capability)
(fieldCap : baseCapability)
: option capability :=
match objCap with
| base iso =>
match fieldCap with
| iso => Some isohat
| trn => Some (base val)
| ref => Some (base tag)
| val => Some (base val)
| box => Some (base tag)
| tag => Some (base tag)
end
| base trn =>
match fieldCap with
| iso => Some isohat
| trn => Some (base val)
| ref => Some (base box)
| val => Some (base val)
| box => Some (base box)
| tag => Some (base tag)
end
| base ref =>
match fieldCap with
| iso => Some isohat
| trn => Some trnhat
| ref => Some (base ref)
| val => Some (base val)
| box => Some (base box)
| tag => Some (base tag)
end
| base val => None
| base box => None
| base tag => None
| isohat =>
match fieldCap with
| iso => Some isohat
| trn => Some isohat
| ref => Some isohat
| val => Some (base val)
| box => Some (base val)
| tag => Some (base tag)
end
| trnhat =>
match fieldCap with
| iso => Some isohat
| trn => Some trnhat
| ref => Some trnhat
| val => Some (base val)
| box => Some (base box)
| tag => Some (base tag)
end
end.
Inductive safeToWrite : capability -> baseCapability -> Prop :=
(* Write to an @iso@ *)
| safeToWrite_iso_iso : safeToWrite (base iso) iso
| safeToWrite_iso_val : safeToWrite (base iso) val
| safeToWrite_iso_tag : safeToWrite (base iso) tag
(* Write to a @trn@ *)
| safeToWrite_trn_iso : safeToWrite (base trn) iso
| safeToWrite_trn_trn : safeToWrite (base trn) trn
| safeToWrite_trn_val : safeToWrite (base trn) val
| safeToWrite_trn_tag : safeToWrite (base trn) tag
(* Write to a @ref@ *)
| safeToWrite_ref (b : baseCapability) : safeToWrite (base ref) b
(* Write to an @iso^@ *)
| safeToWrite_isohat (b : baseCapability) : safeToWrite isohat b
(* Write to a @trn^@ *)
| safeToWrite_trnhat (b : baseCapability) : safeToWrite trnhat b.
Example safeToWrite_implies_writeAdapt_defined : forall k b, safeToWrite k b -> exists k', writeAdapt k b = Some k'.
Proof.
intros k b stw_k_b.
induction stw_k_b; try (compute; eauto).
(* Solve the three "general" cases, which take any value of b *)
induction b; try (compute; eauto).
induction b; try (compute; eauto).
induction b; try (compute; eauto).
Qed.
Reserved Notation "g |- x : T ==> g'" (at level 9, x at level 50, T at level 50).
Inductive typing { P : program } : context -> cw_encoding -> ponyType -> context -> Prop :=
(* Path rules *)
| path_var (gamma : context) (x : var) (aT : aliasedType)
: VarMapsTo x aT gamma
-> gamma |- (ePath (use x)) : asPonyType aT ==> gamma
| path_temp (gamma : context) (t : temp) (T : ponyType)
: TempMapsTo t T gamma
-> gamma |- (ePath (useTemp t)) : T ==> (removeTemp t gamma)
| path_consume (gamma : context) (x : var) (aT : aliasedType)
: VarMapsTo x aT gamma
-> gamma |- (ePath (consume x)) : hat aT ==> (removeVar x gamma)
| path_field (gamma gamma' : context) (p : path) (s s' : typeId) (k k'' : capability) (k' : baseCapability) (f : fieldId)
: gamma |- (ePath p) : (type s k) ==> gamma'
-> @fieldLookup P s f (aType s' k')
-> viewAdapt k k' = Some k''
-> gamma |- (eFieldOfPath (p, f)) : (type s' k'') ==> gamma'
(* The alias rule *)
| expr_alias (gamma gamma': context) (x : cw_encoding) (s : typeId) (k : capability) (b : baseCapability)
: gamma |- x : (type s k) ==> gamma'
-> (alias k <; base b)
-> gamma |- (eAlias x) : (type s (base b)) ==> gamma'
| expr_vardecl (gamma : context) (x : var) (aT : aliasedType)
: ~ VarIn x gamma
-> gamma |- (eExpr (varDecl x)) : asPonyType aT ==> (addVar x aT gamma)
| expr_localassign (gamma gamma' : context) (x : var) (r : rhs) (aT : aliasedType)
: gamma |- (eAlias (eRhs r)) : asPonyType aT ==> gamma
-> VarMapsTo x aT gamma'
-> gamma |- (eExpr (assign x (aliasOf r))) : hat aT ==> gamma'
| expr_tempassign (gamma gamma' : context) (t : temp) (pf : fieldOfPath) (T : ponyType)
: gamma |- (eFieldOfPath pf) : T ==> gamma'
-> gamma |- (eExpr (tempAssign t pf)) : T ==> (LocalMap.addTemp t T gamma')
| expr_fieldassign (gamma gamma' gamma'' : context) (p p' : path) (f : fieldId) (s s' : typeId) (k k' : capability) (b b' : baseCapability)
: gamma |- (eAlias (ePath p')) : (type s' (base b)) ==> gamma'
-> gamma' |- (ePath p) : (type s k) ==> gamma''
-> @fieldLookup P s f (aType s' b')
-> safeToWrite k b
-> (base b) <; (base b')
-> writeAdapt k b' = Some k'
-> gamma |- (eRhs (fieldAssign (p, f) (aliasOf p'))) : type s' k' ==> gamma''
| expr_funcall (gamma gamma' gamma'' : context) (p : path) (args : list (@aliased path)) (s : typeId) (b : baseCapability)
(mId : methodId) (mArgs : arrayVarMap aliasedType) (returnType : ponyType) (body : expressionSeq)
: @methodLookup P s mId (mDef b mArgs returnType body)
-> typing_list gamma (eAPaths args) (argValues mArgs) gamma'
-> gamma' |- (eAlias (ePath p)) : (type s (base b)) ==> gamma''
-> gamma |- (eRhs (methodCall (aliasOf p) mId args)) : returnType ==> gamma''
| expr_becall (gamma gamma' gamma'' : context) (p : path) (args : list (@aliased path)) (s : typeId)
(bId : behaviourId) (bArgs : arrayVarMap aliasedType) (body : expressionSeq)
: @behaviourLookup P s bId (bDef bArgs body)
-> typing_list gamma (eAPaths args) (argValues bArgs) gamma'
-> gamma' |- (eAlias (ePath p)) : (type s (base tag)) ==> gamma''
-> gamma |- (eRhs (behaviourCall (aliasOf p) bId args)) : (type s (base tag)) ==> gamma''
| expr_classcon (gamma gamma' : context) (args : list (@aliased path)) (c : classId)
(kId : constructorId) (cnArgs : arrayVarMap aliasedType) (body : expressionSeq)
: @constructorLookup P (inl c) kId (cnDef cnArgs body)
-> typing_list gamma (eAPaths args) (argValues cnArgs) gamma'
-> gamma |- (eRhs (constructorCall (inl c) kId args)) : (type (inl c) (base ref)) ==> gamma'
| expr_actorcon (gamma gamma' : context) (args : list (@aliased path)) (a : actorId)
(kId : constructorId) (cnArgs : arrayVarMap aliasedType) (body : expressionSeq)
: @constructorLookup P (inr a) kId (cnDef cnArgs body)
-> typing_list gamma (eAPaths args) (argValues cnArgs) gamma'
-> gamma |- (eRhs (constructorCall (inr a) kId args)) : (type (inr a) (base tag)) ==> gamma'
where "G |- x : T ==> G'" := (typing G x T G')
with
typing_list { P : program } : context -> list cw_encoding -> list ponyType -> context -> Prop :=
| typing_list_nil (gamma : context)
: typing_list gamma nil nil gamma
| typing_list_cons (gamma gamma' gamma'' : context) (x : cw_encoding) (t : ponyType) (lx : list cw_encoding) (lt : list ponyType)
: gamma |- x : t ==> gamma'
-> typing_list gamma' lx lt gamma''
-> typing_list gamma (x :: lx) (t :: lt) gamma''.
Lemma typing_paths_func_on_type_and_outcome :
forall P : program,
forall gamma gamma' gamma'' : context,
forall p : path,
forall T T' : ponyType,
@typing P gamma (ePath p) T gamma'
-> @typing P gamma (ePath p) T' gamma''
-> T = T' /\ gamma' = gamma''.
intros P gamma gamma' gamma'' p T T' p_type_T_gamma' p_type_T'_gamma''.
destruct p as [ x | x | t ].
{ inversion p_type_T_gamma' as [ _gamma0 _x0 aT p_mapsto_aT | | | | | | | | | | | | ].
inversion p_type_T'_gamma'' as [ _gamma1 _x1 aT' p_mapsto_aT' | | | | | | | | | | | | ].
assert (gamma' = gamma'') as ctxts_same by (transitivity gamma; auto).
split.
{ enough (aT = aT') as aTs_equal.
rewrite <- aTs_equal.
reflexivity.
apply VarMapsTo_func with (m:=gamma') (var:=x).
assumption.
rewrite ctxts_same; assumption.
}
{ assumption.
}
}
{ inversion p_type_T_gamma' as [ | | _gamma0 _x0 aT p_mapsto_aT | | | | | | | | | | ].
inversion p_type_T'_gamma'' as [ | | _gamma1 _x1 aT' p_mapsto_aT' | | | | | | | | | | ].
assert (gamma' = gamma'') as ctxts_same by (transitivity (removeVar x gamma); auto).
split.
{ enough (aT = aT') as aTs_equal.
rewrite <- aTs_equal.
reflexivity.
apply VarMapsTo_func with (m:=gamma) (var:=x); assumption.
}
{ reflexivity.
}
}
{ inversion p_type_T_gamma' as [ | _gamma0 _t0 _T0 t_mapsto_T | | | | | | | | | | | ].
inversion p_type_T'_gamma'' as [ | _gamma1 _t1 _T'0 t_mapsto_T' | | | | | | | | | | | ].
split.
{ apply TempMapsTo_func with (m:=gamma) (temp:=t); assumption.
}
{ reflexivity.
}
}
Qed.
Lemma typing_func_on_type_and_outcome :
forall P : program,
forall gamma gamma' gamma'' : context,
forall x : cw_encoding,
forall T T' : ponyType,
@typing P gamma x T gamma'
-> @typing P gamma x T' gamma''
-> T = T' /\ gamma' = gamma''.
Proof.
intros P gamma gamma' gamma'' x T T' x_type_T_gamma' x_type_T'_gamma''.
induction x as [ p | fp | x' IHx' | [] | [] ].
(* Case for paths is shown as a lemma *)
{ apply typing_paths_func_on_type_and_outcome with (P:=P) (p:=p) (gamma:=gamma); assumption.
}
{ inversion x_type_T_gamma' as [ | | | _gamma0 _gamma'0 p1 S1 S1' k1 k1' b1 f1 p1_typed_s1_k1 lookup_s1_f1_is_s1'_k1' viewadapt_k1_b1_k1' | | | | | | | | | ].
inversion x_type_T'_gamma'' as [ | | | _gamma1 _gamma'1 p2 S2 S2' k2 k2' b2 f2 p2_typed_s2_k2 lookup_s2_f2_is_s2'_k2' viewadapt_k2_b2_k2' | | | | | | | | | ].
assert (p1 = p2 /\ f1 = f2) as [ paths_same fields_same ].
{ assert ((p1, f1) = (p2, f2)) as fps_same by (transitivity fp; auto).
now inversion fps_same.
}
assert (type S1 k1 = type S2 k2 /\ gamma' = gamma'') as [ paths_typed_same ctxts_same ].
{ apply typing_paths_func_on_type_and_outcome with (P:=P) (p:=p1) (gamma:=gamma).
assumption.
rewrite paths_same.
assumption.
}
split.
{ assert (S1' = S2' /\ b1 = b2) as [ f_type_ids_same bs_same ].
{ assert (aType S1' b1 = aType S2' b2) as aTypes_same.
{ apply fieldLookup_func with (P:=P) (s:=S1) (f:=f1).
assumption.
rewrite fields_same.
assert (S1 = S2) as type_ids_same by (inversion paths_typed_same; auto).
rewrite type_ids_same.
assumption.
}
now inversion aTypes_same.
}
enough (k1' = k2') as vAs_same.
rewrite f_type_ids_same.
rewrite vAs_same.
reflexivity.
assert (Some k1' = Some k2') as somes_eq.
{ transitivity (viewAdapt k1 b1).
auto.
rewrite bs_same.
assert (k1 = k2) as ks_eq by (inversion paths_typed_same; auto).
rewrite ks_eq.
auto.
}
inversion somes_eq.
reflexivity.
}
{ assumption.
}
}
{ admit. (* TODO *)
}
{ admit. (* TODO *)
}
{ admit. (* TODO *)
}
{ admit. (* TODO *)
}
{ admit. (* TODO *)
}
{ admit. (* TODO *)
}
{ admit. (* TODO *)
}
{ admit. (* TODO *)
}
{ admit. (* TODO *)
}
Admitted. (* TODO: prove this helper lemma (v. obvious) *)
End Typing.
Require Import Coq.MSets.MSetInterface.
Module WFExpressions (Map : WSfun) (SetM : WSetsOn).
Module Typing := Typing Map.
Export Typing.
Import Typing.Context.
Module TempSet := SetM DecidableTemp.
Definition tempSet := TempSet.t.
Definition consumePath (p : path) : tempSet :=
match p with
| useTemp t => TempSet.singleton t
| _ => TempSet.empty
end.
Definition consumeRhs (r : rhs) : tempSet :=
match r with
| rhsPath p => consumePath p
| fieldAssign (p, _) (aliasOf p') => TempSet.union (consumePath p) (consumePath p')
| methodCall (aliasOf rcvr) _ args =>
fold_left
(fun consumed ap =>
match ap with
| aliasOf p => TempSet.union consumed (consumePath p)
end
)
args
(consumePath rcvr)
| behaviourCall (aliasOf rcvr) _ args =>
fold_left
(fun consumed ap =>
match ap with
| aliasOf p => TempSet.union consumed (consumePath p)
end
)
args
(consumePath rcvr)
| constructorCall _ _ args =>
fold_left
(fun consumed ap =>
match ap with
| aliasOf p => TempSet.union consumed (consumePath p)
end
)
args
TempSet.empty
end.
Definition consumeExpr (e : expression) : tempSet :=
match e with
| varDecl _ => TempSet.empty
| assign _ (aliasOf r) => consumeRhs r
| tempAssign _ (p, _) => consumePath p
end.
Inductive well_formed_expr { P : program } : context -> expressionSeq -> ponyType -> Prop :=
| wf_return (gamma gamma' : context) (p : path) (t : ponyType)
: @typing P gamma (ePath p) t gamma'
-> well_formed_expr gamma (final p) t
| wf_vardecl (gamma gamma' : context) (x : var) (E : expressionSeq) (t t' : ponyType)
: @typing P gamma (eExpr (varDecl x)) t' gamma'
-> well_formed_expr gamma' E t
-> well_formed_expr gamma (seq (varDecl x) E) t
| wf_localassign (gamma gamma' : context) (x : var) (arhs : @aliased rhs) (E : expressionSeq) (t t' : ponyType)
: @typing P gamma (eExpr (assign x arhs)) t' gamma'
-> well_formed_expr gamma' E t
-> well_formed_expr gamma (seq (assign x arhs) E) t
| wf_tempassign_final (gamma gamma' : context) (t : temp) (pf : fieldOfPath) (p : path) (T T' : ponyType)
: @typing P gamma (eExpr (tempAssign t pf)) T' gamma'
-> well_formed_expr gamma' (final p) T
-> well_formed_expr gamma (seq (tempAssign t pf) (final p)) T
| wf_tempassign (gamma gamma' : context) (t : temp) (pf : fieldOfPath) (e : expression) (E : expressionSeq) (T T' : ponyType)
: @typing P gamma (eExpr (tempAssign t pf)) T' gamma'
-> TempSet.In t (consumeExpr e)
-> well_formed_expr gamma' (seq e E) T
-> well_formed_expr gamma (seq (tempAssign t pf) (seq e E)) T.
(* For some method arguments, produce the corresponding typing context *)
Definition argsToContext (args : arrayVarMap aliasedType) : context :=
ArrayVarMap.fold
(fun key val ctxt => LocalMap.addVar key val ctxt)
args
(LocalMap.empty aliasedType ponyType).
Definition well_formed_constructor_def { P : program }
(thisType : aliasedType) (kD : constructorDef) : Prop
:= forall args body, kD = cnDef args body
-> exists (t : ponyType),
@well_formed_expr P
(LocalMap.addVar this thisType (argsToContext args))
body
t.
Definition well_formed_method_def { P : program }
(thisTypeId : typeId) (mD : methodDef) : Prop
:= forall rcvrCap args returnType body, mD = mDef rcvrCap args returnType body
-> @well_formed_expr P
(LocalMap.addVar this (aType thisTypeId rcvrCap) (argsToContext args))
body
returnType.
Definition well_formed_behaviour_def { P : program }
(thisTypeId : actorId) (bD : behaviourDef) : Prop
:= forall args body, bD = bDef args body
-> exists (t : ponyType),
@well_formed_expr P
(LocalMap.addVar this (aType (inr thisTypeId) iso) (argsToContext args))
body
t.
Definition well_formed_class { P : program } (c : classId) : Prop :=
(forall k kD, @constructorLookup P (inl c) k kD -> @well_formed_constructor_def P (aType (inl c) ref) kD)
/\
(forall m mD, @methodLookup P (inl c) m mD -> @well_formed_method_def P (inl c) mD).
Definition well_formed_actor { P : program } (a : actorId) : Prop :=
(forall k kD, @constructorLookup P (inr a) k kD -> @well_formed_constructor_def P (aType (inr a) iso) kD)
/\
(forall m mD, @methodLookup P (inr a) m mD -> @well_formed_method_def P (inr a) mD)
/\
(forall b bD, @behaviourLookup P (inr a) b bD -> @well_formed_behaviour_def P a bD).
Definition well_formed_program (P : program) : Prop :=
(forall a : actorId, @well_formed_actor P a)
/\ (forall c : classId, @well_formed_class P c).
End WFExpressions.
|
/-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
! This file was ported from Lean 3 source module field_theory.fixed
! leanprover-community/mathlib commit e7bab9a85e92cf46c02cb4725a7be2f04691e3a7
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Algebra.GroupRingAction.Invariant
import Mathbin.Algebra.Polynomial.GroupRingAction
import Mathbin.FieldTheory.Normal
import Mathbin.FieldTheory.Separable
import Mathbin.FieldTheory.Tower
/-!
# Fixed field under a group action.
This is the basis of the Fundamental Theorem of Galois Theory.
Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`,
the subfield consisting of elements of `F` fixed_points by every element of `G`.
This subfield is then normal and separable, and in addition (TODO) if `G` acts faithfully on `F`
then `finrank (fixed_points G F) F = fintype.card G`.
## Main Definitions
- `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of
`G`, where `G` is a group that acts on `F`.
-/
noncomputable section
open Classical BigOperators
open MulAction Finset FiniteDimensional
universe u v w
variable {M : Type u} [Monoid M]
variable (G : Type u) [Group G]
variable (F : Type v) [Field F] [MulSemiringAction M F] [MulSemiringAction G F] (m : M)
/-- The subfield of F fixed by the field endomorphism `m`. -/
def FixedBy.subfield : Subfield F where
carrier := fixedBy M F m
zero_mem' := smul_zero m
add_mem' x y hx hy := (smul_add m x y).trans <| congr_arg₂ _ hx hy
neg_mem' x hx := (smul_neg m x).trans <| congr_arg _ hx
one_mem' := smul_one m
mul_mem' x y hx hy := (smul_mul' m x y).trans <| congr_arg₂ _ hx hy
inv_mem' x hx := (smul_inv'' m x).trans <| congr_arg _ hx
#align fixed_by.subfield FixedBy.subfield
section InvariantSubfields
variable (M) {F}
/-- A typeclass for subrings invariant under a `mul_semiring_action`. -/
class IsInvariantSubfield (S : Subfield F) : Prop where
smul_mem : ∀ (m : M) {x : F}, x ∈ S → m • x ∈ S
#align is_invariant_subfield IsInvariantSubfield
variable (S : Subfield F)
instance IsInvariantSubfield.toMulSemiringAction [IsInvariantSubfield M S] : MulSemiringAction M S
where
smul m x := ⟨m • x, IsInvariantSubfield.smul_mem m x.2⟩
one_smul s := Subtype.eq <| one_smul M s
mul_smul m₁ m₂ s := Subtype.eq <| mul_smul m₁ m₂ s
smul_add m s₁ s₂ := Subtype.eq <| smul_add m s₁ s₂
smul_zero m := Subtype.eq <| smul_zero m
smul_one m := Subtype.eq <| smul_one m
smul_mul m s₁ s₂ := Subtype.eq <| smul_mul' m s₁ s₂
#align is_invariant_subfield.to_mul_semiring_action IsInvariantSubfield.toMulSemiringAction
instance [IsInvariantSubfield M S] : IsInvariantSubring M S.toSubring
where smul_mem := IsInvariantSubfield.smul_mem
end InvariantSubfields
namespace FixedPoints
variable (M)
-- we use `subfield.copy` so that the underlying set is `fixed_points M F`
/-- The subfield of fixed points by a monoid action. -/
def subfield : Subfield F :=
Subfield.copy (⨅ m : M, FixedBy.subfield F m) (fixedPoints M F)
(by
ext z
simp [fixed_points, FixedBy.subfield, infᵢ, Subfield.mem_infₛ])
#align fixed_points.subfield FixedPoints.subfield
instance : IsInvariantSubfield M (FixedPoints.subfield M F)
where smul_mem g x hx g' := by rw [hx, hx]
instance : SMulCommClass M (FixedPoints.subfield M F) F
where smul_comm m f f' := show m • (↑f * f') = f * m • f' by rw [smul_mul', f.prop m]
instance smul_comm_class' : SMulCommClass (FixedPoints.subfield M F) M F :=
SMulCommClass.symm _ _ _
#align fixed_points.smul_comm_class' FixedPoints.smul_comm_class'
@[simp]
theorem smul (m : M) (x : FixedPoints.subfield M F) : m • x = x :=
Subtype.eq <| x.2 m
#align fixed_points.smul FixedPoints.smul
-- Why is this so slow?
@[simp]
theorem smul_polynomial (m : M) (p : Polynomial (FixedPoints.subfield M F)) : m • p = p :=
Polynomial.induction_on p (fun x => by rw [Polynomial.smul_C, smul])
(fun p q ihp ihq => by rw [smul_add, ihp, ihq]) fun n x ih => by
rw [smul_mul', Polynomial.smul_C, smul, smul_pow', Polynomial.smul_X]
#align fixed_points.smul_polynomial FixedPoints.smul_polynomial
instance : Algebra (FixedPoints.subfield M F) F := by infer_instance
theorem coe_algebraMap :
algebraMap (FixedPoints.subfield M F) F = Subfield.subtype (FixedPoints.subfield M F) :=
rfl
#align fixed_points.coe_algebra_map FixedPoints.coe_algebraMap
theorem linearIndependent_smul_of_linearIndependent {s : Finset F} :
(LinearIndependent (FixedPoints.subfield G F) fun i : (s : Set F) => (i : F)) →
LinearIndependent F fun i : (s : Set F) => MulAction.toFun G F i :=
by
haveI : IsEmpty ((∅ : Finset F) : Set F) := ⟨Subtype.prop⟩
refine' Finset.induction_on s (fun _ => linearIndependent_empty_type) fun a s has ih hs => _
rw [coe_insert] at hs⊢
rw [linearIndependent_insert (mt mem_coe.1 has)] at hs
rw [linearIndependent_insert' (mt mem_coe.1 has)]
refine' ⟨ih hs.1, fun ha => _⟩
rw [Finsupp.mem_span_image_iff_total] at ha
rcases ha with ⟨l, hl, hla⟩
rw [Finsupp.total_apply_of_mem_supported F hl] at hla
suffices ∀ i ∈ s, l i ∈ FixedPoints.subfield G F
by
replace hla := (sum_apply _ _ fun i => l i • to_fun G F i).symm.trans (congr_fun hla 1)
simp_rw [Pi.smul_apply, to_fun_apply, one_smul] at hla
refine' hs.2 (hla ▸ Submodule.sum_mem _ fun c hcs => _)
change (⟨l c, this c hcs⟩ : FixedPoints.subfield G F) • c ∈ _
exact Submodule.smul_mem _ _ (Submodule.subset_span <| mem_coe.2 hcs)
intro i his g
refine'
eq_of_sub_eq_zero
(linearIndependent_iff'.1 (ih hs.1) s.attach (fun i => g • l i - l i) _ ⟨i, his⟩
(mem_attach _ _) :
_)
refine' (@sum_attach _ _ s _ fun i => (g • l i - l i) • MulAction.toFun G F i).trans _
ext g'
dsimp only
conv_lhs =>
rw [sum_apply]
congr
skip
ext
rw [Pi.smul_apply, sub_smul, smul_eq_mul]
rw [sum_sub_distrib, Pi.zero_apply, sub_eq_zero]
conv_lhs =>
congr
skip
ext
rw [to_fun_apply, ← mul_inv_cancel_left g g', mul_smul, ← smul_mul', ← to_fun_apply _ x]
show
(∑ x in s, g • (fun y => l y • MulAction.toFun G F y) x (g⁻¹ * g')) =
∑ x in s, (fun y => l y • MulAction.toFun G F y) x g'
rw [← smul_sum, ← sum_apply _ _ fun y => l y • to_fun G F y, ←
sum_apply _ _ fun y => l y • to_fun G F y]
dsimp only
rw [hla, to_fun_apply, to_fun_apply, smul_smul, mul_inv_cancel_left]
#align fixed_points.linear_independent_smul_of_linear_independent FixedPoints.linearIndependent_smul_of_linearIndependent
section Fintype
variable [Fintype G] (x : F)
/-- `minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/
def minpoly : Polynomial (FixedPoints.subfield G F) :=
(prodXSubSmul G F x).toSubring (FixedPoints.subfield G F).toSubring fun c hc g =>
let ⟨n, hc0, hn⟩ := Polynomial.mem_frange_iff.1 hc
hn.symm ▸ prodXSubSmul.coeff G F x g n
#align fixed_points.minpoly FixedPoints.minpoly
namespace minpoly
theorem monic : (minpoly G F x).Monic :=
by
simp only [minpoly, Polynomial.monic_toSubring]
exact prodXSubSmul.monic G F x
#align fixed_points.minpoly.monic FixedPoints.minpoly.monic
theorem eval₂ :
Polynomial.eval₂ (Subring.subtype <| (FixedPoints.subfield G F).toSubring) x (minpoly G F x) =
0 :=
by
rw [← prodXSubSmul.eval G F x, Polynomial.eval₂_eq_eval_map]
simp only [minpoly, Polynomial.map_toSubring]
#align fixed_points.minpoly.eval₂ FixedPoints.minpoly.eval₂
theorem eval₂' :
Polynomial.eval₂ (Subfield.subtype <| FixedPoints.subfield G F) x (minpoly G F x) = 0 :=
eval₂ G F x
#align fixed_points.minpoly.eval₂' FixedPoints.minpoly.eval₂'
theorem ne_one : minpoly G F x ≠ (1 : Polynomial (FixedPoints.subfield G F)) := fun H =>
have := eval₂ G F x
(one_ne_zero : (1 : F) ≠ 0) <| by rwa [H, Polynomial.eval₂_one] at this
#align fixed_points.minpoly.ne_one FixedPoints.minpoly.ne_one
theorem of_eval₂ (f : Polynomial (FixedPoints.subfield G F))
(hf : Polynomial.eval₂ (Subfield.subtype <| FixedPoints.subfield G F) x f = 0) :
minpoly G F x ∣ f :=
by
erw [← Polynomial.map_dvd_map' (Subfield.subtype <| FixedPoints.subfield G F), minpoly,
Polynomial.map_toSubring _ (Subfield G F).toSubring, prodXSubSmul]
refine'
Fintype.prod_dvd_of_coprime
(Polynomial.pairwise_coprime_X_sub_C <| MulAction.injective_ofQuotientStabilizer G x) fun y =>
QuotientGroup.induction_on y fun g => _
rw [Polynomial.dvd_iff_isRoot, Polynomial.IsRoot.def, MulAction.ofQuotientStabilizer_mk,
Polynomial.eval_smul', ← Subfield.toSubring_subtype_eq_subtype, ←
IsInvariantSubring.coe_subtypeHom' G (FixedPoints.subfield G F).toSubring, ←
MulSemiringActionHom.coe_polynomial, ← MulSemiringActionHom.map_smul, smul_polynomial,
MulSemiringActionHom.coe_polynomial, IsInvariantSubring.coe_subtypeHom', Polynomial.eval_map,
Subfield.toSubring_subtype_eq_subtype, hf, smul_zero]
#align fixed_points.minpoly.of_eval₂ FixedPoints.minpoly.of_eval₂
-- Why is this so slow?
theorem irreducible_aux (f g : Polynomial (FixedPoints.subfield G F)) (hf : f.Monic) (hg : g.Monic)
(hfg : f * g = minpoly G F x) : f = 1 ∨ g = 1 :=
by
have hf2 : f ∣ minpoly G F x := by
rw [← hfg]
exact dvd_mul_right _ _
have hg2 : g ∣ minpoly G F x := by
rw [← hfg]
exact dvd_mul_left _ _
have := eval₂ G F x
rw [← hfg, Polynomial.eval₂_mul, mul_eq_zero] at this
cases this
· right
have hf3 : f = minpoly G F x :=
Polynomial.eq_of_monic_of_associated hf (monic G F x)
(associated_of_dvd_dvd hf2 <| @of_eval₂ G _ F _ _ _ x f this)
rwa [← mul_one (minpoly G F x), hf3, mul_right_inj' (monic G F x).NeZero] at hfg
· left
have hg3 : g = minpoly G F x :=
Polynomial.eq_of_monic_of_associated hg (monic G F x)
(associated_of_dvd_dvd hg2 <| @of_eval₂ G _ F _ _ _ x g this)
rwa [← one_mul (minpoly G F x), hg3, mul_left_inj' (monic G F x).NeZero] at hfg
#align fixed_points.minpoly.irreducible_aux FixedPoints.minpoly.irreducible_aux
theorem irreducible : Irreducible (minpoly G F x) :=
(Polynomial.irreducible_of_monic (monic G F x) (ne_one G F x)).2 (irreducible_aux G F x)
#align fixed_points.minpoly.irreducible FixedPoints.minpoly.irreducible
end minpoly
end Fintype
theorem isIntegral [Finite G] (x : F) : IsIntegral (FixedPoints.subfield G F) x :=
by
cases nonempty_fintype G
exact ⟨minpoly G F x, minpoly.monic G F x, minpoly.eval₂ G F x⟩
#align fixed_points.is_integral FixedPoints.isIntegral
section Fintype
variable [Fintype G] (x : F)
theorem minpoly_eq_minpoly : minpoly G F x = minpoly (FixedPoints.subfield G F) x :=
minpoly.eq_of_irreducible_of_monic (minpoly.irreducible G F x) (minpoly.eval₂ G F x)
(minpoly.monic G F x)
#align fixed_points.minpoly_eq_minpoly FixedPoints.minpoly_eq_minpoly
theorem dim_le_card : Module.rank (FixedPoints.subfield G F) F ≤ Fintype.card G :=
dim_le fun s hs => by
simpa only [dim_fun', Cardinal.mk_coe_finset, Finset.coe_sort_coe, Cardinal.lift_natCast,
Cardinal.natCast_le] using
cardinal_lift_le_dim_of_linear_independent'
(linear_independent_smul_of_linear_independent G F hs)
#align fixed_points.dim_le_card FixedPoints.dim_le_card
end Fintype
section Finite
variable [Finite G]
instance normal : Normal (FixedPoints.subfield G F) F :=
⟨fun x => (isIntegral G F x).IsAlgebraic _, fun x =>
(Polynomial.splits_id_iff_splits _).1 <|
by
cases nonempty_fintype G
rw [← minpoly_eq_minpoly, minpoly, coe_algebra_map, ← Subfield.toSubring_subtype_eq_subtype,
Polynomial.map_toSubring _ (Subfield G F).toSubring, prodXSubSmul]
exact Polynomial.splits_prod _ fun _ _ => Polynomial.splits_X_sub_C _⟩
#align fixed_points.normal FixedPoints.normal
instance separable : IsSeparable (FixedPoints.subfield G F) F :=
⟨isIntegral G F, fun x => by
cases nonempty_fintype G
-- this was a plain rw when we were using unbundled subrings
erw [← minpoly_eq_minpoly, ← Polynomial.separable_map (FixedPoints.subfield G F).Subtype,
minpoly, Polynomial.map_toSubring _ (Subfield G F).toSubring]
exact Polynomial.separable_prod_x_sub_c_iff.2 (injective_of_quotient_stabilizer G x)⟩
#align fixed_points.separable FixedPoints.separable
instance : FiniteDimensional (subfield G F) F :=
by
cases nonempty_fintype G
exact
IsNoetherian.iff_fg.1
(IsNoetherian.iff_dim_lt_aleph0.2 <| (dim_le_card G F).trans_lt <| Cardinal.nat_lt_aleph0 _)
end Finite
theorem finrank_le_card [Fintype G] : finrank (subfield G F) F ≤ Fintype.card G :=
by
rw [← Cardinal.natCast_le, finrank_eq_dim]
apply dim_le_card
#align fixed_points.finrank_le_card FixedPoints.finrank_le_card
end FixedPoints
theorem linearIndependent_toLinearMap (R : Type u) (A : Type v) (B : Type w) [CommSemiring R]
[Ring A] [Algebra R A] [CommRing B] [IsDomain B] [Algebra R B] :
LinearIndependent B (AlgHom.toLinearMap : (A →ₐ[R] B) → A →ₗ[R] B) :=
have : LinearIndependent B (LinearMap.ltoFun R A B ∘ AlgHom.toLinearMap) :=
((linearIndependent_monoidHom A B).comp (coe : (A →ₐ[R] B) → A →* B) fun f g hfg =>
AlgHom.ext <| MonoidHom.ext_iff.1 hfg :
_)
this.of_comp _
#align linear_independent_to_linear_map linearIndependent_toLinearMap
theorem cardinal_mk_algHom (K : Type u) (V : Type v) (W : Type w) [Field K] [Field V] [Algebra K V]
[FiniteDimensional K V] [Field W] [Algebra K W] [FiniteDimensional K W] :
Cardinal.mk (V →ₐ[K] W) ≤ finrank W (V →ₗ[K] W) :=
cardinal_mk_le_finrank_of_linearIndependent <| linearIndependent_toLinearMap K V W
#align cardinal_mk_alg_hom cardinal_mk_algHom
noncomputable instance AlgEquiv.fintype (K : Type u) (V : Type v) [Field K] [Field V] [Algebra K V]
[FiniteDimensional K V] : Fintype (V ≃ₐ[K] V) :=
Fintype.ofEquiv (V →ₐ[K] V) (algEquivEquivAlgHom K V).symm
#align alg_equiv.fintype AlgEquiv.fintype
theorem finrank_algHom (K : Type u) (V : Type v) [Field K] [Field V] [Algebra K V]
[FiniteDimensional K V] : Fintype.card (V →ₐ[K] V) ≤ finrank V (V →ₗ[K] V) :=
fintype_card_le_finrank_of_linearIndependent <| linearIndependent_toLinearMap K V V
#align finrank_alg_hom finrank_algHom
namespace FixedPoints
theorem finrank_eq_card (G : Type u) (F : Type v) [Group G] [Field F] [Fintype G]
[MulSemiringAction G F] [FaithfulSMul G F] :
finrank (FixedPoints.subfield G F) F = Fintype.card G :=
le_antisymm (FixedPoints.finrank_le_card G F) <|
calc
Fintype.card G ≤ Fintype.card (F →ₐ[FixedPoints.subfield G F] F) :=
Fintype.card_le_of_injective _ (MulSemiringAction.toAlgHom_injective _ F)
_ ≤ finrank F (F →ₗ[FixedPoints.subfield G F] F) := (finrank_algHom (fixedPoints G F) F)
_ = finrank (FixedPoints.subfield G F) F := finrank_linear_map' _ _ _
#align fixed_points.finrank_eq_card FixedPoints.finrank_eq_card
/-- `mul_semiring_action.to_alg_hom` is bijective. -/
theorem toAlgHom_bijective (G : Type u) (F : Type v) [Group G] [Field F] [Finite G]
[MulSemiringAction G F] [FaithfulSMul G F] :
Function.Bijective (MulSemiringAction.toAlgHom _ _ : G → F →ₐ[subfield G F] F) :=
by
cases nonempty_fintype G
rw [Fintype.bijective_iff_injective_and_card]
constructor
· exact MulSemiringAction.toAlgHom_injective _ F
· apply le_antisymm
· exact Fintype.card_le_of_injective _ (MulSemiringAction.toAlgHom_injective _ F)
· rw [← finrank_eq_card G F]
exact LE.le.trans_eq (finrank_algHom _ F) (finrank_linear_map' _ _ _)
#align fixed_points.to_alg_hom_bijective FixedPoints.toAlgHom_bijective
/-- Bijection between G and algebra homomorphisms that fix the fixed points -/
def toAlgHomEquiv (G : Type u) (F : Type v) [Group G] [Field F] [Fintype G] [MulSemiringAction G F]
[FaithfulSMul G F] : G ≃ (F →ₐ[FixedPoints.subfield G F] F) :=
Equiv.ofBijective _ (toAlgHom_bijective G F)
#align fixed_points.to_alg_hom_equiv FixedPoints.toAlgHomEquiv
end FixedPoints
|
-- Andreas, 2013-05-02 This ain't a bug, it is a feature.
-- {-# OPTIONS -v scope.name:10 #-}
module _ where
open import Common.Equality
module M where
record R' : Set₁ where
field
X : Set
open M renaming (R' to R)
X : R → Set
X = R.X
-- Nisse:
-- The open directive did not mention the /module/ R, so (I think
-- that) the code above should be rejected.
-- Andreas:
-- NO, it is a feature that projections can also be accessed via
-- the record /type/.
-- Ulf:
-- According to the suggestion in 836, if you rename the module explicitly
-- the code above breaks (test/fail/Issue836.agda).
|
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Data.Maybe.Base where
open import Cubical.Core.Everything
private
variable
ℓ : Level
A B : Type ℓ
data Maybe (A : Type ℓ) : Type ℓ where
nothing : Maybe A
just : A → Maybe A
caseMaybe : (n j : B) → Maybe A → B
caseMaybe n _ nothing = n
caseMaybe _ j (just _) = j
map-Maybe : (A → B) → Maybe A → Maybe B
map-Maybe _ nothing = nothing
map-Maybe f (just x) = just (f x)
rec : B → (A → B) → Maybe A → B
rec n j nothing = n
rec n j (just a) = j a
|
/-
Copyright (c) 2020 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import deprecated.group
/-!
# Unbundled semiring and ring homomorphisms (deprecated)
This file defines structures for unbundled semiring and ring homomorphisms. Though bundled
morphisms are now preferred, the unbundled structures are still occasionally used in mathlib,
and probably will not go away before Lean 4 because Lean 3 often fails to coerce a bundled
homomorphism to a function.
## Main Definitions
`is_semiring_hom` (deprecated), `is_ring_hom` (deprecated)
## Tags
is_semiring_hom, is_ring_hom
-/
universes u v w
variable {α : Type u}
/-- Predicate for semiring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/
structure is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) : Prop :=
(map_zero [] : f 0 = 0)
(map_one [] : f 1 = 1)
(map_add [] : ∀ {x y}, f (x + y) = f x + f y)
(map_mul [] : ∀ {x y}, f (x * y) = f x * f y)
namespace is_semiring_hom
variables {β : Type v} [semiring α] [semiring β]
variables {f : α → β} (hf : is_semiring_hom f) {x y : α}
/-- The identity map is a semiring homomorphism. -/
lemma id : is_semiring_hom (@id α) := by refine {..}; intros; refl
/-- The composition of two semiring homomorphisms is a semiring homomorphism. -/
lemma comp (hf : is_semiring_hom f) {γ} [semiring γ] {g : β → γ} (hg : is_semiring_hom g) :
is_semiring_hom (g ∘ f) :=
{ map_zero := by simpa [map_zero hf] using map_zero hg,
map_one := by simpa [map_one hf] using map_one hg,
map_add := λ x y, by simp [map_add hf, map_add hg],
map_mul := λ x y, by simp [map_mul hf, map_mul hg] }
/-- A semiring homomorphism is an additive monoid homomorphism. -/
lemma to_is_add_monoid_hom (hf : is_semiring_hom f) : is_add_monoid_hom f :=
{ ..‹is_semiring_hom f› }
/-- A semiring homomorphism is a monoid homomorphism. -/
lemma to_is_monoid_hom (hf : is_semiring_hom f) : is_monoid_hom f :=
{ ..‹is_semiring_hom f› }
end is_semiring_hom
/-- Predicate for ring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/
structure is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop :=
(map_one [] : f 1 = 1)
(map_mul [] : ∀ {x y}, f (x * y) = f x * f y)
(map_add [] : ∀ {x y}, f (x + y) = f x + f y)
namespace is_ring_hom
variables {β : Type v} [ring α] [ring β]
/-- A map of rings that is a semiring homomorphism is also a ring homomorphism. -/
lemma of_semiring {f : α → β} (H : is_semiring_hom f) : is_ring_hom f := {..H}
variables {f : α → β} (hf : is_ring_hom f) {x y : α}
/-- Ring homomorphisms map zero to zero. -/
lemma map_zero (hf : is_ring_hom f) : f 0 = 0 :=
calc f 0 = f (0 + 0) - f 0 : by rw [hf.map_add]; simp
... = 0 : by simp
/-- Ring homomorphisms preserve additive inverses. -/
lemma map_neg (hf : is_ring_hom f) : f (-x) = -f x :=
calc f (-x) = f (-x + x) - f x : by rw [hf.map_add]; simp
... = -f x : by simp [hf.map_zero]
/-- Ring homomorphisms preserve subtraction. -/
lemma map_sub (hf : is_ring_hom f) : f (x - y) = f x - f y :=
by simp [sub_eq_add_neg, hf.map_add, hf.map_neg]
/-- The identity map is a ring homomorphism. -/
lemma id : is_ring_hom (@id α) := by refine {..}; intros; refl
/-- The composition of two ring homomorphisms is a ring homomorphism. -/
-- see Note [no instance on morphisms]
lemma comp (hf : is_ring_hom f) {γ} [ring γ] {g : β → γ} (hg : is_ring_hom g) :
is_ring_hom (g ∘ f) :=
{ map_add := λ x y, by simp [map_add hf]; rw map_add hg; refl,
map_mul := λ x y, by simp [map_mul hf]; rw map_mul hg; refl,
map_one := by simp [map_one hf]; exact map_one hg }
/-- A ring homomorphism is also a semiring homomorphism. -/
lemma to_is_semiring_hom (hf : is_ring_hom f) : is_semiring_hom f :=
{ map_zero := map_zero hf, ..‹is_ring_hom f› }
lemma to_is_add_group_hom (hf : is_ring_hom f) : is_add_group_hom f := { map_add := hf.map_add }
end is_ring_hom
variables {β : Type v} {γ : Type w} [rα : semiring α] [rβ : semiring β]
namespace ring_hom
section
include rα rβ
/-- Interpret `f : α → β` with `is_semiring_hom f` as a ring homomorphism. -/
def of {f : α → β} (hf : is_semiring_hom f) : α →+* β :=
{ to_fun := f,
.. monoid_hom.of hf.to_is_monoid_hom,
.. add_monoid_hom.of hf.to_is_add_monoid_hom }
@[simp] lemma coe_of {f : α → β} (hf : is_semiring_hom f) : ⇑(of hf) = f := rfl
lemma to_is_semiring_hom (f : α →+* β) : is_semiring_hom f :=
{ map_zero := f.map_zero,
map_one := f.map_one,
map_add := f.map_add,
map_mul := f.map_mul }
end
lemma to_is_ring_hom {α γ} [ring α] [ring γ] (g : α →+* γ) : is_ring_hom g :=
is_ring_hom.of_semiring g.to_is_semiring_hom
end ring_hom
|
theory IpAddresses
imports IP_Addresses.IP_Address_toString
IP_Addresses.CIDR_Split
"../Common/WordInterval_Lists"
begin
\<comment> \<open>Misc\<close>
(*we dont't have an empty ip space, but a space which only contains the 0 address. We will use the option type to denote the empty space in some functions.*)
lemma "ipset_from_cidr (ipv4addr_of_dotdecimal (0, 0, 0, 0)) 33 = {0}"
by(simp add: ipv4addr_of_dotdecimal.simps ipv4addr_of_nat_def ipset_from_cidr_large_pfxlen)
(*helper we use for spoofing protection specification*)
definition all_but_those_ips :: "('i::len word \<times> nat) list \<Rightarrow> ('i word \<times> nat) list" where
"all_but_those_ips cidrips = cidr_split (wordinterval_invert (l2wi (map ipcidr_to_interval cidrips)))"
lemma all_but_those_ips:
"ipcidr_union_set (set (all_but_those_ips cidrips)) =
UNIV - (\<Union> (ip,n) \<in> set cidrips. ipset_from_cidr ip n)"
apply simp
unfolding ipcidr_union_set_uncurry all_but_those_ips_def
apply(simp add: cidr_split_prefix)
apply(simp add: l2wi)
apply(simp add: ipcidr_to_interval_def)
using ipset_from_cidr_ipcidr_to_interval by blast
section\<open>IPv4 Addresses\<close>
subsection\<open>IPv4 Addresses in IPTables Notation (how we parse it)\<close>
context
notes [[typedef_overloaded]]
begin
datatype 'i ipt_iprange =
\<comment> \<open>Singleton IP Address\<close>
IpAddr "'i::len word"
\<comment> \<open>CIDR notation: addr/xx\<close>
| IpAddrNetmask "'i word" nat
\<comment> \<open>-m iprange --src-range a.b.c.d-e.f.g.h\<close>
| IpAddrRange "'i word" "'i word"
(*the range is inclusive*)
end
fun ipt_iprange_to_set :: "'i::len ipt_iprange \<Rightarrow> 'i word set" where
"ipt_iprange_to_set (IpAddrNetmask base m) = ipset_from_cidr base m" |
"ipt_iprange_to_set (IpAddr ip) = { ip }" |
"ipt_iprange_to_set (IpAddrRange ip1 ip2) = { ip1 .. ip2 }"
text\<open>@{term ipt_iprange_to_set} can only represent an empty set if it is an empty range.\<close>
lemma ipt_iprange_to_set_nonempty: "ipt_iprange_to_set ip = {} \<longleftrightarrow>
(\<exists>ip1 ip2. ip = IpAddrRange ip1 ip2 \<and> ip1 > ip2)"
apply(cases ip)
apply(simp; fail)
apply(simp add: ipset_from_cidr_alt bitmagic_zeroLast_leq_or1Last; fail)
apply(simp add:linorder_not_le; fail)
done
text\<open>maybe this is necessary as code equation?\<close>
context
includes bit_operations_syntax
begin
lemma element_ipt_iprange_to_set[code_unfold]: "(addr::'i::len word) \<in> ipt_iprange_to_set X = (
case X of (IpAddrNetmask pre len) \<Rightarrow>
(pre AND ((mask len) << (len_of (TYPE('i)) - len))) \<le> addr \<and>
addr \<le> pre OR (mask (len_of (TYPE('i)) - len))
| IpAddr ip \<Rightarrow> (addr = ip)
| IpAddrRange ip1 ip2 \<Rightarrow> ip1 \<le> addr \<and> ip2 \<ge> addr)"
apply(cases X)
apply(simp; fail)
apply(simp add: ipset_from_cidr_alt; fail)
apply(simp; fail)
done
end
lemma ipt_iprange_to_set_uncurry_IpAddrNetmask:
"ipt_iprange_to_set (uncurry IpAddrNetmask a) = uncurry ipset_from_cidr a"
by(simp split: uncurry_splits)
text\<open>IP address ranges to \<open>(start, end)\<close> notation\<close>
fun ipt_iprange_to_interval :: "'i::len ipt_iprange \<Rightarrow> ('i word \<times> 'i word)" where
"ipt_iprange_to_interval (IpAddr addr) = (addr, addr)" |
"ipt_iprange_to_interval (IpAddrNetmask pre len) = ipcidr_to_interval (pre, len)" |
"ipt_iprange_to_interval (IpAddrRange ip1 ip2) = (ip1, ip2)"
lemma ipt_iprange_to_interval: "ipt_iprange_to_interval ip = (s,e) \<Longrightarrow> {s .. e} = ipt_iprange_to_set ip"
apply(cases ip)
apply(auto simp add: ipcidr_to_interval)
done
text\<open>A list of IP address ranges to a @{typ "'i::len wordinterval"}.
The nice thing is: the usual set operations are defined on this type.
We can use the existing function @{const l2wi_intersect} if we want the intersection of the supplied list\<close>
lemma "wordinterval_to_set (l2wi_intersect (map ipt_iprange_to_interval ips)) =
(\<Inter> ip \<in> set ips. ipt_iprange_to_set ip)"
apply(simp add: l2wi_intersect)
using ipt_iprange_to_interval by blast
text\<open>We can use @{const l2wi} if we want the union of the supplied list\<close>
lemma "wordinterval_to_set (l2wi (map ipt_iprange_to_interval ips)) = (\<Union> ip \<in> set ips. ipt_iprange_to_set ip)"
apply(simp add: l2wi)
using ipt_iprange_to_interval by blast
text\<open>A list of (negated) IP address to a @{typ "'i::len wordinterval"}.\<close>
definition ipt_iprange_negation_type_to_br_intersect ::
"'i::len ipt_iprange negation_type list \<Rightarrow> 'i wordinterval" where
"ipt_iprange_negation_type_to_br_intersect l = l2wi_negation_type_intersect (NegPos_map ipt_iprange_to_interval l)"
lemma ipt_iprange_negation_type_to_br_intersect: "wordinterval_to_set (ipt_iprange_negation_type_to_br_intersect l) =
(\<Inter> ip \<in> set (getPos l). ipt_iprange_to_set ip) - (\<Union> ip \<in> set (getNeg l). ipt_iprange_to_set ip)"
apply(simp add: ipt_iprange_negation_type_to_br_intersect_def l2wi_negation_type_intersect NegPos_map_simps)
using ipt_iprange_to_interval by blast
text\<open>The @{typ "'i::len wordinterval"} can be translated back into a list of IP ranges.
If a list of intervals is enough, we can use @{const wi2l}.
If we need it in @{typ "'i::len ipt_iprange"}, we can use this function.\<close>
definition wi_2_cidr_ipt_iprange_list :: "'i::len wordinterval \<Rightarrow> 'i ipt_iprange list" where
"wi_2_cidr_ipt_iprange_list r = map (uncurry IpAddrNetmask) (cidr_split r)"
lemma wi_2_cidr_ipt_iprange_list:
"(\<Union> ip \<in> set (wi_2_cidr_ipt_iprange_list r). ipt_iprange_to_set ip) = wordinterval_to_set r"
proof -
have "(\<Union> ip \<in> set (wi_2_cidr_ipt_iprange_list r). ipt_iprange_to_set ip) =
(\<Union>x\<in>set (cidr_split r). uncurry ipset_from_cidr x)"
unfolding wi_2_cidr_ipt_iprange_list_def by force
thus ?thesis using cidr_split_prefix by metis
qed
text\<open>For example, this allows the following transformation\<close>
definition ipt_iprange_compress :: "'i::len ipt_iprange negation_type list \<Rightarrow> 'i ipt_iprange list" where
"ipt_iprange_compress = wi_2_cidr_ipt_iprange_list \<circ> ipt_iprange_negation_type_to_br_intersect"
lemma ipt_iprange_compress: "(\<Union> ip \<in> set (ipt_iprange_compress l). ipt_iprange_to_set ip) =
(\<Inter> ip \<in> set (getPos l). ipt_iprange_to_set ip) - (\<Union> ip \<in> set (getNeg l). ipt_iprange_to_set ip)"
by (metis wi_2_cidr_ipt_iprange_list comp_apply ipt_iprange_compress_def ipt_iprange_negation_type_to_br_intersect)
definition normalized_cidr_ip :: "'i::len ipt_iprange \<Rightarrow> bool" where
"normalized_cidr_ip ip \<equiv> case ip of IpAddrNetmask _ _ \<Rightarrow> True | _ \<Rightarrow> False"
lemma wi_2_cidr_ipt_iprange_list_normalized_IpAddrNetmask:
"\<forall>a'\<in>set (wi_2_cidr_ipt_iprange_list as). normalized_cidr_ip a'"
apply(clarify)
apply(simp add: wi_2_cidr_ipt_iprange_list_def normalized_cidr_ip_def)
by force
lemma ipt_iprange_compress_normalized_IpAddrNetmask:
"\<forall>a'\<in>set (ipt_iprange_compress as). normalized_cidr_ip a'"
by(simp add: ipt_iprange_compress_def wi_2_cidr_ipt_iprange_list_normalized_IpAddrNetmask)
definition ipt_iprange_to_cidr :: "'i::len ipt_iprange \<Rightarrow> ('i word \<times> nat) list" where
"ipt_iprange_to_cidr ips = cidr_split (iprange_interval (ipt_iprange_to_interval ips))"
lemma ipt_ipvange_to_cidr: "ipcidr_union_set (set (ipt_iprange_to_cidr ips)) = (ipt_iprange_to_set ips)"
apply(simp add: ipt_iprange_to_cidr_def)
apply(simp add: ipcidr_union_set_uncurry)
apply(case_tac "(ipt_iprange_to_interval ips)")
apply(simp add: ipt_iprange_to_interval cidr_split_prefix_single)
done
(* actually, these are toString pretty printing helpers*)
definition interval_to_wi_to_ipt_iprange :: "'i::len word \<Rightarrow> 'i word \<Rightarrow> 'i ipt_iprange" where
"interval_to_wi_to_ipt_iprange s e \<equiv>
if s = e
then IpAddr s
else case cidr_split (WordInterval s e) of [(ip,nmask)] \<Rightarrow> IpAddrNetmask ip nmask
| _ \<Rightarrow> IpAddrRange s e"
lemma interval_to_wi_to_ipt_ipv4range: "ipt_iprange_to_set (interval_to_wi_to_ipt_iprange s e) = {s..e}"
proof -
from cidr_split_prefix_single[of s e] have
"cidr_split (WordInterval s e) = [(a, b)] \<Longrightarrow> ipset_from_cidr a b = {s..e}" for a b
by(simp add: iprange_interval.simps)
thus ?thesis
by(simp add: interval_to_wi_to_ipt_iprange_def split: list.split)
qed
fun wi_to_ipt_iprange :: "'i::len wordinterval \<Rightarrow> 'i ipt_iprange list" where
"wi_to_ipt_iprange (WordInterval s e) = (if s > e then [] else
[interval_to_wi_to_ipt_iprange s e])" |
"wi_to_ipt_iprange (RangeUnion a b) = wi_to_ipt_iprange a @ wi_to_ipt_iprange b"
lemma wi_to_ipt_ipv4range: "\<Union>(set (map ipt_iprange_to_set (wi_to_ipt_iprange wi))) = wordinterval_to_set wi"
apply(induction wi)
apply(simp add: interval_to_wi_to_ipt_ipv4range)
apply(simp)
done
end
|
{- This file demonstrates the canonical example of dependent types,
- vectors (implemented as lists) with their lengths encoded at the type level.
- First note that Idris has built-in natural numbers, defined as follows:
data Nat = Z | S Nat
- A Nat is either 0 (Z) or the successor of a Nat, (i.e. N + 1) -}
data Vect : Nat -> Type -> Type where
Nil : Vect Z elem
(::) : (x : elem) -> (xs : Vect len elem) -> Vect (S len) elem
-- Hints for interactive editing
%name Vect xs,ys,zs,ws
{- Let's break this down. We have a type constructor
- Vect : Nat -> Type -> Type
- In Idris, since types are values, type constructors are just functions!
- This type constructor takes a value of type `Nat` and a value of type `Type`
- and constructs the type (Vect N Type) of a length N vector of type Type.
- We also have two term constructors, `Nil` and `(::)`.
- Nil : Vect z elem
- constructs a vector of length `0` with element type `elem` for any type `elem`.
- (::) : (x : elem) -> (xs : Vect len elem) -> Vect (S len) elem
- takes an element and a Vector of length `len`, and returns a vector of
- length `len + 1`. Note that it does so by construction, i.e. this is where
- we *define* how the length of a vector is calculated. -}
v1 : Vect 0 Int
v1 = [] -- [] is a built-in synonym for Nil
v2 : Vect 3 Int
v2 = [1,2,3] -- list syntax is overloaded for any type with constructors Nil, ::
-- The following code will throw a compile-time error
-- v3 : Vect 4 Int
-- v3 : [1,2,3]
{- Crucial to the defintion above is the fact that we can use functions to
- compute types. For example, `Vect (len + 1) elem` uses addition to compute
- the resulting type. We can write functions whose output types are computed
- from their input types.
- Let us write an append function on vectors. -}
append : Vect n a -> Vect m a -> Vect (n + m) a
append xs ys = ?hole
{- Here `?hole` is a hole, which is a valid piece of syntax that Idris can assign
- a type. In the Idris editor mode (see https://atom.io/packages/language-idris),
- the shortcut Ctrl-Alt-t shows the type of the value under the cursor as well
- as the types of all the available values in scope. On the hole above, this yields
0 m : Nat
0 a : Type
0 n : Nat
ys : Vect m a
xs : Vect n a
-------------------------------------
hole : Vect (plus n m) a
- Ctrl-Alt-c on a function argument case splits that argument. Doing so on `xs`:
-}
append2 : Vect n a -> Vect m a -> Vect (n + m) a
append2 [] ys = ?base2 -- base case
append2 (x :: xs) ys = ?rec2 -- recursive case
{- Inspecting ?base2, we see
0 m : Nat
0 a : Type
ys : Vect m a
0 n : Nat
-------------------------------------
base2 : Vect m a
- We require a `Vect m a` and have a `Vect m a`, ys.
- Ctrl-Alt-s searches the types and values in scope for a solution to the program,
- i.e. a term with the type of the hole. Running serach on the two holes above
- automatically generates the following code. -}
append3 : Vect n a -> Vect m a -> Vect (n + m) a
append3 [] ys = ys
append3 (x :: xs) ys = x :: append3 xs ys
{- This is amazing! The compiler just discovered our code for us! Note that all
- this does is replace our usual reasoning "see what fits the type and its
- probably right," and will thus not always yield the correct program. However,
- the extra expressivity of dependent types does often allow correct program
- generation, just via a simple search.
- Let us consider another example: -}
zipWith : (f : a -> b -> c) -> (xs : Vect n a) -> (ys : Vect n b) -> Vect n c
zipWith f xs ys = ?zipWith_rhs
{- Here, both input vectors are guarenteed to be the same length. This gives
- the compiler a lot of useful information to help us write our program.
- First, Ctrl-Alt-c to case split on `xs` yields the following: -}
zipWith2 : (f : a -> b -> c) -> (xs : Vect n a) -> (ys : Vect n b) -> Vect n c
zipWith2 f [] ys = ?zipWith2_rhs_1
zipWith2 f (x :: xs) ys = ?zipWith2_rhs_2
{- Subsequently case splitting again on ys in both the base
- and recursive case only yields the one possibility for each, since in the
- base case `ys` is guarenteed to be `[]` and in the recursive case `ys` is
- guarenteed to be of the form `(y :: ys)`. -}
zipWith3 : (f : a -> b -> c) -> (xs : Vect n a) -> (ys : Vect n b) -> Vect n c
zipWith3 f [] [] = ?zipWith_base
zipWith3 f (x :: xs) (y :: ys) = ?zipWith_rec
{- Searching w/ Ctrl-Alt-s on the two holes above immediately yields the solution! -}
zipWith4 : (f : a -> b -> c) -> (xs : Vect n a) -> (ys : Vect n b) -> Vect n c
zipWith4 f [] [] = []
zipWith4 f (x :: xs) (y :: ys) = f x y :: zipWith4 f xs ys
|
Formal statement is: lemma higher_deriv_compose_linear: fixes z::complex assumes f: "f holomorphic_on T" and S: "open S" and T: "open T" and z: "z \<in> S" and fg: "\<And>w. w \<in> S \<Longrightarrow> u * w \<in> T" shows "(deriv ^^ n) (\<lambda>w. f (u * w)) z = u^n * (deriv ^^ n) f (u * z)" Informal statement is: If $f$ is holomorphic on an open set $T$, and $u$ is a complex number, then the $n$th derivative of $f(u \cdot z)$ is $u^n \cdot f^{(n)}(u \cdot z)$. |
lemma is_unit_smult_iff: "smult c p dvd 1 \<longleftrightarrow> c dvd 1 \<and> p dvd 1" |
[GOAL]
𝕜 : Type u_1
R : Type u_2
inst✝⁵ : IsROrC 𝕜
inst✝⁴ : NormedCommRing R
inst✝³ : NormedAlgebra 𝕜 R
inst✝² : TopologicalRing R
inst✝¹ : CompleteSpace R
inst✝ : T2Space R
r : R
⊢ exp 𝕜 (r • ε) = ↑1 + r • ε
[PROOFSTEP]
rw [eps, ← inr_smul, exp_inr, Nat.cast_one]
|
export PartialRandomization, PartialRandomizationAAFT
"""
PartialRandomization(α = 0.5)
`PartialRandomization` surrogates[^Ortega1998] are similar to [`RandomFourier`](@ref) phase
surrogates, but during the phase randomization step, instead of drawing phases from `[0, 2π]`,
phases are drawn from `[0, 2π]*α`, where `α ∈ [0, 1]`. The authors refers to `α` as the
"degree" of phase randomization, where `α = 0` means `0 %` randomization and
`α = 1` means `100 %` randomization.
[^Ortega1998]: Ortega, Guillermo J.; Louis, Enrique (1998). Smoothness Implies Determinism in Time Series: A Measure Based Approach. Physical Review Letters, 81(20), 4345–4348. doi:10.1103/PhysRevLett.81.4345
"""
struct PartialRandomization{T} <: Surrogate
α::T
function PartialRandomization(α::T) where T <: Real
@assert 0 <= α <= 1
return new{T}(α)
end
end
function surrogenerator(x::AbstractVector, rf::PartialRandomization, rng = Random.default_rng())
forward = plan_rfft(x)
inverse = plan_irfft(forward*x, length(x))
m = mean(x)
𝓕 = forward*(x .- m)
shuffled𝓕 = zero(𝓕)
s = similar(x)
n = length(𝓕)
r = abs.(𝓕)
ϕ = angle.(𝓕)
coeffs = zero(r)
init = (inverse = inverse, m = m, coeffs = coeffs, n = n, r = r,
ϕ = ϕ, shuffled𝓕 = shuffled𝓕)
return SurrogateGenerator(rf, x, s, init, rng)
end
function (sg::SurrogateGenerator{<:PartialRandomization})()
inverse, m, coeffs, n, r, ϕ, shuffled𝓕 =
getfield.(Ref(sg.init),
(:inverse, :m, :coeffs, :n, :r, :ϕ, :shuffled𝓕))
s, rng = sg.s, sg.rng
α = sg.method.α
coeffs .= rand(rng, Uniform(0, 2π), n)
shuffled𝓕 .= r .* exp.(coeffs .* 1im .* α)
s .= inverse * shuffled𝓕 .+ m
return s
end
"""
PartialRandomizationAAFT(α = 0.5)
`PartialRandomizationAAFF` surrogates are similar to [`PartialRandomization`](@ref)
surrogates[^Ortega1998], but adds a rescaling step, so that the surrogate has
the same values as the original time series (analogous to the rescaling done for
[`AAFT`](@ref) surrogates).
Partial randomization surrogates have, to the package authors' knowledge, not been
published in scientific literature.
[^Ortega1998]: Ortega, Guillermo J.; Louis, Enrique (1998). Smoothness Implies Determinism in Time Series: A Measure Based Approach. Physical Review Letters, 81(20), 4345–4348. doi:10.1103/PhysRevLett.81.4345
"""
struct PartialRandomizationAAFT{T} <: Surrogate
α::T
function PartialRandomizationAAFT(α::T) where T <: Real
@assert 0 <= α <= 1
return new{T}(α)
end
end
function surrogenerator(x::AbstractVector, rf::PartialRandomizationAAFT, rng = Random.default_rng())
init = (
gen = surrogenerator(x, PartialRandomization(rf.α), rng),
ix = zeros(Int, length(x)),
x_sorted = sort(x),
)
s = similar(x)
return SurrogateGenerator(rf, x, s, init, rng)
end
function (sg::SurrogateGenerator{<:PartialRandomizationAAFT})()
gen, ix, x_sorted = sg.init.gen, sg.init.ix, sg.init.x_sorted
s = sg.s
# Surrogate starts out as a PartialRandomization surrogate
s .= gen()
# Rescale to obtain a AAFT-like surrogate
sortperm!(ix, s)
s[ix] .= x_sorted
return s
end |
I consider myself one of the luckiest people in the world. So far, my life has been rich in teaching and learning, both personally and professionally. And I would love to have a conversation with you about how can we work together. Click on the following resumes for more details on my work history. I am more than happy to provide references upon request. |
"""
*u16*
"""
import jax.numpy as jnp
from ..._datatype import Datatype
from .._integer import Integer
from ._unsigned import Unsigned
__all__ = ["u16"]
class u16(
jnp.uint16,
Unsigned,
Integer,
Datatype,
):
def __init__(
self,
value: int,
):
super(u16, self).__init__(
self,
value,
)
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov
-/
import order.filter.at_top_bot
import order.filter.pi
/-!
# The cofinite filter
In this file we define
`cofinite`: the filter of sets with finite complement
and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`.
## TODO
Define filters for other cardinalities of the complement.
-/
open set
open_locale classical
variables {α : Type*}
namespace filter
/-- The cofinite filter is the filter of subsets whose complements are finite. -/
def cofinite : filter α :=
{ sets := {s | finite sᶜ},
univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq],
sets_of_superset := assume s t (hs : finite sᶜ) (st: s ⊆ t),
hs.subset $ compl_subset_compl.2 st,
inter_sets := assume s t (hs : finite sᶜ) (ht : finite (tᶜ)),
by simp only [compl_inter, finite.union, ht, hs, mem_set_of_eq] }
@[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ finite sᶜ := iff.rfl
@[simp] lemma eventually_cofinite {p : α → Prop} :
(∀ᶠ x in cofinite, p x) ↔ finite {x | ¬p x} := iff.rfl
lemma has_basis_cofinite : has_basis cofinite (λ s : set α, s.finite) compl :=
⟨λ s, ⟨λ h, ⟨sᶜ, h, (compl_compl s).subset⟩, λ ⟨t, htf, hts⟩, htf.subset $ compl_subset_comm.2 hts⟩⟩
instance cofinite_ne_bot [infinite α] : ne_bot (@cofinite α) :=
has_basis_cofinite.ne_bot_iff.2 $ λ s hs, hs.infinite_compl.nonempty
lemma frequently_cofinite_iff_infinite {p : α → Prop} :
(∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} :=
by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not,
set.infinite]
/-- The coproduct of the cofinite filters on two types is the cofinite filter on their product. -/
lemma coprod_cofinite {β : Type*} :
(cofinite : filter α).coprod (cofinite : filter β) = cofinite :=
begin
ext S,
simp only [mem_coprod_iff, exists_prop, mem_comap, mem_cofinite],
split,
{ rintro ⟨⟨A, hAf, hAS⟩, B, hBf, hBS⟩,
rw [← compl_subset_compl, ← preimage_compl] at hAS hBS,
exact (hAf.prod hBf).subset (subset_inter hAS hBS) },
{ intro hS,
refine ⟨⟨(prod.fst '' Sᶜ)ᶜ, _, _⟩, ⟨(prod.snd '' Sᶜ)ᶜ, _, _⟩⟩,
{ simpa using hS.image prod.fst },
{ simpa [compl_subset_comm] using subset_preimage_image prod.fst Sᶜ },
{ simpa using hS.image prod.snd },
{ simpa [compl_subset_comm] using subset_preimage_image prod.snd Sᶜ } },
end
/-- Finite product of finite sets is finite -/
lemma Coprod_cofinite {δ : Type*} {κ : δ → Type*} [fintype δ] :
filter.Coprod (λ d, (cofinite : filter (κ d))) = cofinite :=
begin
ext S,
rcases compl_surjective S with ⟨S, rfl⟩,
simp_rw [compl_mem_Coprod_iff, mem_cofinite, compl_compl],
split,
{ rintro ⟨t, htf, hsub⟩,
exact (finite.pi htf).subset hsub },
{ exact λ hS, ⟨λ i, function.eval i '' S, λ i, hS.image _, subset_pi_eval_image _ _⟩ }
end
end filter
open filter
lemma set.finite.compl_mem_cofinite {s : set α} (hs : s.finite) : sᶜ ∈ (@cofinite α) :=
mem_cofinite.2 $ (compl_compl s).symm ▸ hs
lemma set.finite.eventually_cofinite_nmem {s : set α} (hs : s.finite) : ∀ᶠ x in cofinite, x ∉ s :=
hs.compl_mem_cofinite
lemma finset.eventually_cofinite_nmem (s : finset α) : ∀ᶠ x in cofinite, x ∉ s :=
s.finite_to_set.eventually_cofinite_nmem
lemma set.infinite_iff_frequently_cofinite {s : set α} :
set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) :=
frequently_cofinite_iff_infinite.symm
lemma filter.eventually_cofinite_ne (x : α) : ∀ᶠ a in cofinite, a ≠ x :=
(set.finite_singleton x).eventually_cofinite_nmem
/-- For natural numbers the filters `cofinite` and `at_top` coincide. -/
lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top :=
begin
ext s,
simp only [mem_cofinite, mem_at_top_sets],
split,
{ assume hs,
use (hs.to_finset.sup id) + 1,
assume b hb,
by_contradiction hbs,
have := hs.to_finset.subset_range_sup_succ (hs.mem_to_finset.2 hbs),
exact not_lt_of_le hb (finset.mem_range.1 this) },
{ rintros ⟨N, hN⟩,
apply (finite_lt_nat N).subset,
assume n hn,
change n < N,
exact lt_of_not_ge (λ hn', hn $ hN n hn') }
end
lemma nat.frequently_at_top_iff_infinite {p : ℕ → Prop} :
(∃ᶠ n in at_top, p n) ↔ set.infinite {n | p n} :=
by simp only [← nat.cofinite_eq_at_top, frequently_cofinite_iff_infinite]
lemma filter.tendsto.exists_within_forall_le {α β : Type*} [linear_order β] {s : set α}
(hs : s.nonempty)
{f : α → β} (hf : filter.tendsto f filter.cofinite filter.at_top) :
∃ a₀ ∈ s, ∀ a ∈ s, f a₀ ≤ f a :=
begin
rcases em (∃ y ∈ s, ∃ x, f y < x) with ⟨y, hys, x, hx⟩|not_all_top,
{ -- the set of points `{y | f y < x}` is nonempty and finite, so we take `min` over this set
have : finite {y | ¬x ≤ f y} := (filter.eventually_cofinite.mp (tendsto_at_top.1 hf x)),
simp only [not_le] at this,
obtain ⟨a₀, ⟨ha₀ : f a₀ < x, ha₀s⟩, others_bigger⟩ :=
exists_min_image _ f (this.inter_of_left s) ⟨y, hx, hys⟩,
refine ⟨a₀, ha₀s, λ a has, (lt_or_le (f a) x).elim _ (le_trans ha₀.le)⟩,
exact λ h, others_bigger a ⟨h, has⟩ },
{ -- in this case, f is constant because all values are at top
push_neg at not_all_top,
obtain ⟨a₀, ha₀s⟩ := hs,
exact ⟨a₀, ha₀s, λ a ha, not_all_top a ha (f a₀)⟩ }
end
lemma filter.tendsto.exists_forall_le {α β : Type*} [nonempty α] [linear_order β]
{f : α → β} (hf : tendsto f cofinite at_top) :
∃ a₀, ∀ a, f a₀ ≤ f a :=
let ⟨a₀, _, ha₀⟩ := hf.exists_within_forall_le univ_nonempty in ⟨a₀, λ a, ha₀ a (mem_univ _)⟩
lemma filter.tendsto.exists_within_forall_ge {α β : Type*} [linear_order β] {s : set α}
(hs : s.nonempty)
{f : α → β} (hf : filter.tendsto f filter.cofinite filter.at_bot) :
∃ a₀ ∈ s, ∀ a ∈ s, f a ≤ f a₀ :=
@filter.tendsto.exists_within_forall_le _ (order_dual β) _ _ hs _ hf
lemma filter.tendsto.exists_forall_ge {α β : Type*} [nonempty α] [linear_order β]
{f : α → β} (hf : tendsto f cofinite at_bot) :
∃ a₀, ∀ a, f a ≤ f a₀ :=
@filter.tendsto.exists_forall_le _ (order_dual β) _ _ _ hf
/-- For an injective function `f`, inverse images of finite sets are finite. -/
lemma function.injective.tendsto_cofinite {α β : Type*} {f : α → β} (hf : function.injective f) :
tendsto f cofinite cofinite :=
λ s h, h.preimage (hf.inj_on _)
|
-- @@stderr --
dtrace: failed to compile script test/unittest/types/err.D_UNKNOWN.dupenum.d: [D_UNKNOWN] line 18: failed to define enumerator 'x': Duplicate member or variable name
|
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import algebra.iterate_hom
import data.polynomial.eval
/-!
# The derivative map on polynomials
## Main definitions
* `polynomial.derivative`: The formal derivative of polynomials, expressed as a linear map.
-/
noncomputable theory
open finset
open_locale big_operators classical
namespace polynomial
universes u v w y z
variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {A : Type z} {a b : R} {n : ℕ}
section derivative
section semiring
variables [semiring R]
/-- `derivative p` is the formal derivative of the polynomial `p` -/
def derivative : polynomial R →ₗ[R] polynomial R :=
{ to_fun := λ p, p.sum (λ n a, C (a * n) * X^(n-1)),
map_add' := λ p q, by rw sum_add_index;
simp only [add_mul, forall_const, ring_hom.map_add,
eq_self_iff_true, zero_mul, ring_hom.map_zero],
map_smul' := λ a p, by dsimp; rw sum_smul_index;
simp only [mul_sum, ← C_mul', mul_assoc, coeff_C_mul, ring_hom.map_mul, forall_const,
zero_mul, ring_hom.map_zero, sum] }
lemma derivative_apply (p : polynomial R) :
derivative p = p.sum (λn a, C (a * n) * X^(n - 1)) := rfl
lemma coeff_derivative (p : polynomial R) (n : ℕ) :
coeff (derivative p) n = coeff p (n + 1) * (n + 1) :=
begin
rw [derivative_apply],
simp only [coeff_X_pow, coeff_sum, coeff_C_mul],
rw [sum, finset.sum_eq_single (n + 1)],
simp only [nat.add_succ_sub_one, add_zero, mul_one, if_true, eq_self_iff_true], norm_cast,
{ assume b, cases b,
{ intros, rw [nat.cast_zero, mul_zero, zero_mul], },
{ intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } },
{ rw [if_pos (add_tsub_cancel_right n 1).symm, mul_one, nat.cast_add, nat.cast_one,
mem_support_iff],
intro h, push_neg at h, simp [h], },
end
@[simp]
lemma derivative_zero : derivative (0 : polynomial R) = 0 :=
derivative.map_zero
@[simp]
lemma iterate_derivative_zero {k : ℕ} : derivative^[k] (0 : polynomial R) = 0 :=
begin
induction k with k ih,
{ simp, },
{ simp [ih], },
end
@[simp]
lemma derivative_monomial (a : R) (n : ℕ) : derivative (monomial n a) = monomial (n - 1) (a * n) :=
by { rw [derivative_apply, sum_monomial_index, C_mul_X_pow_eq_monomial], simp }
lemma derivative_C_mul_X_pow (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) :=
by rw [C_mul_X_pow_eq_monomial, C_mul_X_pow_eq_monomial, derivative_monomial]
@[simp] lemma derivative_X_pow (n : ℕ) :
derivative (X ^ n : polynomial R) = (n : polynomial R) * X ^ (n - 1) :=
by convert derivative_C_mul_X_pow (1 : R) n; simp
@[simp] lemma derivative_C {a : R} : derivative (C a) = 0 :=
by simp [derivative_apply]
@[simp] lemma derivative_X : derivative (X : polynomial R) = 1 :=
(derivative_monomial _ _).trans $ by simp
@[simp] lemma derivative_one : derivative (1 : polynomial R) = 0 :=
derivative_C
@[simp] lemma derivative_bit0 {a : polynomial R} : derivative (bit0 a) = bit0 (derivative a) :=
by simp [bit0]
@[simp] lemma derivative_bit1 {a : polynomial R} : derivative (bit1 a) = bit0 (derivative a) :=
by simp [bit1]
@[simp] lemma derivative_add {f g : polynomial R} :
derivative (f + g) = derivative f + derivative g :=
derivative.map_add f g
@[simp] lemma iterate_derivative_add {f g : polynomial R} {k : ℕ} :
derivative^[k] (f + g) = (derivative^[k] f) + (derivative^[k] g) :=
derivative.to_add_monoid_hom.iterate_map_add _ _ _
@[simp] lemma derivative_neg {R : Type*} [ring R] (f : polynomial R) :
derivative (-f) = - derivative f :=
linear_map.map_neg derivative f
@[simp] lemma iterate_derivative_neg {R : Type*} [ring R] {f : polynomial R} {k : ℕ} :
derivative^[k] (-f) = - (derivative^[k] f) :=
(@derivative R _).to_add_monoid_hom.iterate_map_neg _ _
@[simp] lemma derivative_sub {R : Type*} [ring R] {f g : polynomial R} :
derivative (f - g) = derivative f - derivative g :=
linear_map.map_sub derivative f g
@[simp] lemma iterate_derivative_sub {R : Type*} [ring R] {k : ℕ} {f g : polynomial R} :
derivative^[k] (f - g) = (derivative^[k] f) - (derivative^[k] g) :=
begin
induction k with k ih generalizing f g,
{ simp [nat.iterate], },
{ simp [nat.iterate, ih], }
end
@[simp] lemma derivative_sum {s : finset ι} {f : ι → polynomial R} :
derivative (∑ b in s, f b) = ∑ b in s, derivative (f b) :=
derivative.map_sum
@[simp] lemma derivative_smul (r : R) (p : polynomial R) : derivative (r • p) = r • derivative p :=
derivative.map_smul _ _
@[simp] lemma iterate_derivative_smul (r : R) (p : polynomial R) (k : ℕ) :
derivative^[k] (r • p) = r • (derivative^[k] p) :=
begin
induction k with k ih generalizing p,
{ simp, },
{ simp [ih], },
end
/-- We can't use `derivative_mul` here because
we want to prove this statement also for noncommutative rings.-/
@[simp]
lemma derivative_C_mul (a : R) (p : polynomial R) : derivative (C a * p) = C a * derivative p :=
by convert derivative_smul a p; apply C_mul'
@[simp]
lemma iterate_derivative_C_mul (a : R) (p : polynomial R) (k : ℕ) :
derivative^[k] (C a * p) = C a * (derivative^[k] p) :=
by convert iterate_derivative_smul a p k; apply C_mul'
end semiring
section comm_semiring
variables [comm_semiring R]
lemma derivative_eval (p : polynomial R) (x : R) :
p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) :=
by simp only [derivative_apply, eval_sum, eval_pow, eval_C, eval_X, eval_nat_cast, eval_mul]
@[simp] lemma derivative_mul {f g : polynomial R} :
derivative (f * g) = derivative f * g + f * derivative g :=
calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) :
begin
rw mul_eq_sum_sum,
transitivity, exact derivative_sum,
transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum },
apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm,
transitivity,
{ apply congr_arg, exact monomial_eq_C_mul_X },
exact derivative_C_mul_X_pow _ _
end
... = f.sum (λn a, g.sum (λm b,
(C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) :
sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm,
by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul];
cases n; simp only [nat.succ_sub_succ, pow_zero];
cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.add_succ,
tsub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm]
... = derivative f * g + f * derivative g :
begin
conv { to_rhs, congr,
{ rw [← sum_C_mul_X_eq g] },
{ rw [← sum_C_mul_X_eq f] } },
simp only [sum, sum_add_distrib, finset.mul_sum, finset.sum_mul, derivative_apply]
end
theorem derivative_pow_succ (p : polynomial R) (n : ℕ) :
(p ^ (n + 1)).derivative = (n + 1) * (p ^ n) * p.derivative :=
nat.rec_on n (by rw [pow_one, nat.cast_zero, zero_add, one_mul, pow_zero, one_mul]) $ λ n ih,
by rw [pow_succ', derivative_mul, ih, mul_right_comm, ← add_mul,
add_mul (n.succ : polynomial R), one_mul, pow_succ', mul_assoc, n.cast_succ]
theorem derivative_pow (p : polynomial R) (n : ℕ) :
(p ^ n).derivative = n * (p ^ (n - 1)) * p.derivative :=
nat.cases_on n (by rw [pow_zero, derivative_one, nat.cast_zero, zero_mul, zero_mul]) $ λ n,
by rw [p.derivative_pow_succ n, n.succ_sub_one, n.cast_succ]
lemma derivative_comp (p q : polynomial R) :
(p.comp q).derivative = q.derivative * p.derivative.comp q :=
begin
apply polynomial.induction_on' p,
{ intros p₁ p₂ h₁ h₂, simp [h₁, h₂, mul_add], },
{ intros n r,
simp only [derivative_pow, derivative_mul, monomial_comp, derivative_monomial, derivative_C,
zero_mul, C_eq_nat_cast, zero_add, ring_hom.map_mul],
-- is there a tactic for this? (a multiplicative `abel`):
rw [mul_comm (derivative q)],
simp only [mul_assoc], }
end
@[simp]
theorem derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) :
(p.map f).derivative = p.derivative.map f :=
polynomial.induction_on p
(λ r, by rw [map_C, derivative_C, derivative_C, map_zero])
(λ p q ihp ihq, by rw [map_add, derivative_add, ihp, ihq, derivative_add, map_add])
(λ n r ih, by rw [map_mul, map_C, map_pow, map_X,
derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one,
derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one,
map_mul, map_C, map_mul, map_pow, map_add, map_nat_cast, map_one, map_X])
@[simp]
theorem iterate_derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) (k : ℕ):
polynomial.derivative^[k] (p.map f) = (polynomial.derivative^[k] p).map f :=
begin
induction k with k ih generalizing p,
{ simp, },
{ simp [ih], },
end
/-- Chain rule for formal derivative of polynomials. -/
theorem derivative_eval₂_C (p q : polynomial R) :
(p.eval₂ C q).derivative = p.derivative.eval₂ C q * q.derivative :=
polynomial.induction_on p
(λ r, by rw [eval₂_C, derivative_C, eval₂_zero, zero_mul])
(λ p₁ p₂ ih₁ ih₂, by rw [eval₂_add, derivative_add, ih₁, ih₂, derivative_add, eval₂_add, add_mul])
(λ n r ih, by rw [pow_succ', ← mul_assoc, eval₂_mul, eval₂_X, derivative_mul, ih,
@derivative_mul _ _ _ X, derivative_X, mul_one, eval₂_add, @eval₂_mul _ _ _ _ X, eval₂_X,
add_mul, mul_right_comm])
theorem derivative_prod {s : multiset ι} {f : ι → polynomial R} :
(multiset.map f s).prod.derivative =
(multiset.map (λ i, (multiset.map f (s.erase i)).prod * (f i).derivative) s).sum :=
begin
refine multiset.induction_on s (by simp) (λ i s h, _),
rw [multiset.map_cons, multiset.prod_cons, derivative_mul, multiset.map_cons _ i s,
multiset.sum_cons, multiset.erase_cons_head, mul_comm (f i).derivative],
congr,
rw [h, ← add_monoid_hom.coe_mul_left, (add_monoid_hom.mul_left (f i)).map_multiset_sum _,
add_monoid_hom.coe_mul_left],
simp only [function.comp_app, multiset.map_map],
congr' 1,
refine multiset.map_congr (λ j hj, _),
simp only [function.comp_app],
rw [← mul_assoc, ← multiset.prod_cons, ← multiset.map_cons],
congr' 1,
by_cases hij : i = j,
{ simp [hij, ← multiset.prod_cons, ← multiset.map_cons, multiset.cons_erase hj] },
{ simp [hij] }
end
theorem of_mem_support_derivative {p : polynomial R} {n : ℕ} (h : n ∈ p.derivative.support) :
n + 1 ∈ p.support :=
mem_support_iff.2 $ λ (h1 : p.coeff (n+1) = 0), mem_support_iff.1 h $
show p.derivative.coeff n = 0, by rw [coeff_derivative, h1, zero_mul]
theorem degree_derivative_lt {p : polynomial R} (hp : p ≠ 0) : p.derivative.degree < p.degree :=
(finset.sup_lt_iff $ bot_lt_iff_ne_bot.2 $ mt degree_eq_bot.1 hp).2 $ λ n hp, lt_of_lt_of_le
(with_bot.some_lt_some.2 n.lt_succ_self) $ finset.le_sup $ of_mem_support_derivative hp
theorem nat_degree_derivative_lt {p : polynomial R} (hp : p.derivative ≠ 0) :
p.derivative.nat_degree < p.nat_degree :=
have hp1 : p ≠ 0, from λ h, hp $ by rw [h, derivative_zero],
with_bot.some_lt_some.1 $
begin
rw [nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp, nat_degree,
option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp1],
exact degree_derivative_lt hp1
end
theorem degree_derivative_le {p : polynomial R} : p.derivative.degree ≤ p.degree :=
if H : p = 0 then le_of_eq $ by rw [H, derivative_zero] else le_of_lt $ degree_derivative_lt H
/-- The formal derivative of polynomials, as linear homomorphism. -/
def derivative_lhom (R : Type*) [comm_ring R] : polynomial R →ₗ[R] polynomial R :=
{ to_fun := derivative,
map_add' := λ p q, derivative_add,
map_smul' := λ r p, derivative_smul r p }
@[simp] lemma derivative_lhom_coe {R : Type*} [comm_ring R] :
(polynomial.derivative_lhom R : polynomial R → polynomial R) = polynomial.derivative :=
rfl
@[simp] lemma derivative_cast_nat {n : ℕ} : derivative (n : polynomial R) = 0 :=
begin
rw ← C.map_nat_cast n,
exact derivative_C,
end
@[simp] lemma iterate_derivative_cast_nat_mul {n k : ℕ} {f : polynomial R} :
derivative^[k] (n * f) = n * (derivative^[k] f) :=
begin
induction k with k ih generalizing f,
{ simp [nat.iterate], },
{ simp [nat.iterate, ih], }
end
end comm_semiring
section comm_ring
variables [comm_ring R]
lemma derivative_comp_one_sub_X (p : polynomial R) :
(p.comp (1-X)).derivative = -p.derivative.comp (1-X) :=
by simp [derivative_comp]
@[simp]
lemma iterate_derivative_comp_one_sub_X (p : polynomial R) (k : ℕ) :
derivative^[k] (p.comp (1-X)) = (-1)^k * (derivative^[k] p).comp (1-X) :=
begin
induction k with k ih generalizing p,
{ simp, },
{ simp [ih p.derivative, iterate_derivative_neg, derivative_comp, pow_succ], },
end
end comm_ring
section is_domain
variables [ring R] [is_domain R]
lemma mem_support_derivative [char_zero R] (p : polynomial R) (n : ℕ) :
n ∈ (derivative p).support ↔ n + 1 ∈ p.support :=
suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : R) = 0)) ↔ coeff p (n + 1) ≠ 0,
by simpa only [mem_support_iff, coeff_derivative, ne.def, mul_eq_zero],
by { rw [nat.cast_eq_zero], simp only [nat.succ_ne_zero, or_false] }
@[simp] lemma degree_derivative_eq [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) :
degree (derivative p) = (nat_degree p - 1 : ℕ) :=
begin
have h0 : p ≠ 0,
{ contrapose! hp,
simp [hp] },
apply le_antisymm,
{ rw derivative_apply,
apply le_trans (degree_sum_le _ _) (sup_le (λ n hn, _)),
apply le_trans (degree_C_mul_X_pow_le _ _) (with_bot.coe_le_coe.2 (tsub_le_tsub_right _ _)),
apply le_nat_degree_of_mem_supp _ hn },
{ refine le_sup _,
rw [mem_support_derivative, tsub_add_cancel_of_le, mem_support_iff],
{ show ¬ leading_coeff p = 0,
rw [leading_coeff_eq_zero],
assume h, rw [h, nat_degree_zero] at hp,
exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), },
exact hp }
end
theorem nat_degree_eq_zero_of_derivative_eq_zero
[char_zero R] {f : polynomial R} (h : f.derivative = 0) :
f.nat_degree = 0 :=
begin
by_cases hf : f = 0,
{ exact (congr_arg polynomial.nat_degree hf).trans rfl },
{ rw nat_degree_eq_zero_iff_degree_le_zero,
by_contra absurd,
have f_nat_degree_pos : 0 < f.nat_degree,
{ rwa [not_le, ←nat_degree_pos_iff_degree_pos] at absurd },
let m := f.nat_degree - 1,
have hm : m + 1 = f.nat_degree := tsub_add_cancel_of_le f_nat_degree_pos,
have h2 := coeff_derivative f m,
rw polynomial.ext_iff at h,
rw [h m, coeff_zero, zero_eq_mul] at h2,
cases h2,
{ rw [hm, ←leading_coeff, leading_coeff_eq_zero] at h2,
exact hf h2, },
{ norm_cast at h2 } }
end
end is_domain
end derivative
end polynomial
|
[STATEMENT]
lemma relto_relto_fun_conv: "((a,b) \<in> (relto A B)^^n) = (\<exists> as sel m. relto_fun A B n as sel m (a,b))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ((a, b) \<in> (B\<^sup>* O A O B\<^sup>*) ^^ n) = (\<exists>as sel m. relto_fun A B n as sel m (a, b))
[PROOF STEP]
using relto_fun_into_reltos[of A B n _ _ _ a b] reltos_into_relto_fun[of a b n B A]
[PROOF STATE]
proof (prove)
using this:
relto_fun A B n ?as ?sel ?m (a, b) \<Longrightarrow> (a, b) \<in> (B\<^sup>* O A O B\<^sup>*) ^^ n
(a, b) \<in> (B\<^sup>* O A O B\<^sup>*) ^^ n \<Longrightarrow> \<exists>as sel m. relto_fun A B n as sel m (a, b)
goal (1 subgoal):
1. ((a, b) \<in> (B\<^sup>* O A O B\<^sup>*) ^^ n) = (\<exists>as sel m. relto_fun A B n as sel m (a, b))
[PROOF STEP]
by blast |
-- @@stderr --
dtrace: failed to compile script test/unittest/assocs/err.D_PROTO_ARG.badsig.d: [D_PROTO_ARG] line 24: x[ ] key #2 is incompatible with prototype:
prototype: string
key: int
|
[STATEMENT]
lemma istate_\<Delta>0:
assumes B: "B vl vl1"
shows "\<Delta>0 istate vl istate vl1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Delta>0 istate vl istate vl1
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
B vl vl1
goal (1 subgoal):
1. \<Delta>0 istate vl istate vl1
[PROOF STEP]
unfolding \<Delta>0_def istate_def B_def
[PROOF STATE]
proof (prove)
using this:
BC vl vl1 \<and> corrFrom emptyPost vl1
goal (1 subgoal):
1. PID \<notin> set (postIDs \<lparr>admin = emptyUserID, pendingUReqs = [], userReq = \<lambda>uID. emptyRequestInfo, userIDs = [], user = \<lambda>uID. emptyUser, pass = \<lambda>uID. emptyPass, pendingFReqs = \<lambda>uID. [], friendReq = \<lambda>uID uID'. emptyRequestInfo, friendIDs = \<lambda>uID. [], sentOuterFriendIDs = \<lambda>uID. [], recvOuterFriendIDs = \<lambda>uID. [], postIDs = [], post = \<lambda>papID. emptyPost, owner = \<lambda>pID. emptyUserID, vis = \<lambda>pID. FriendV, pendingSApiReqs = [], sApiReq = \<lambda>aID. emptyRequestInfo, serverApiIDs = [], serverPass = \<lambda>aID. emptyPass, outerPostIDs = \<lambda>aID. [], outerPost = \<lambda>aID papID. emptyPost, outerOwner = \<lambda>aID papID. emptyUserID, outerVis = \<lambda>aID pID. FriendV, pendingCApiReqs = [], cApiReq = \<lambda>aID. emptyRequestInfo, clientApiIDs = [], clientPass = \<lambda>aID. emptyPass, sharedWith = \<lambda>pID. []\<rparr>) \<and> \<lparr>admin = emptyUserID, pendingUReqs = [], userReq = \<lambda>uID. emptyRequestInfo, userIDs = [], user = \<lambda>uID. emptyUser, pass = \<lambda>uID. emptyPass, pendingFReqs = \<lambda>uID. [], friendReq = \<lambda>uID uID'. emptyRequestInfo, friendIDs = \<lambda>uID. [], sentOuterFriendIDs = \<lambda>uID. [], recvOuterFriendIDs = \<lambda>uID. [], postIDs = [], post = \<lambda>papID. emptyPost, owner = \<lambda>pID. emptyUserID, vis = \<lambda>pID. FriendV, pendingSApiReqs = [], sApiReq = \<lambda>aID. emptyRequestInfo, serverApiIDs = [], serverPass = \<lambda>aID. emptyPass, outerPostIDs = \<lambda>aID. [], outerPost = \<lambda>aID papID. emptyPost, outerOwner = \<lambda>aID papID. emptyUserID, outerVis = \<lambda>aID pID. FriendV, pendingCApiReqs = [], cApiReq = \<lambda>aID. emptyRequestInfo, clientApiIDs = [], clientPass = \<lambda>aID. emptyPass, sharedWith = \<lambda>pID. []\<rparr> = \<lparr>admin = emptyUserID, pendingUReqs = [], userReq = \<lambda>uID. emptyRequestInfo, userIDs = [], user = \<lambda>uID. emptyUser, pass = \<lambda>uID. emptyPass, pendingFReqs = \<lambda>uID. [], friendReq = \<lambda>uID uID'. emptyRequestInfo, friendIDs = \<lambda>uID. [], sentOuterFriendIDs = \<lambda>uID. [], recvOuterFriendIDs = \<lambda>uID. [], postIDs = [], post = \<lambda>papID. emptyPost, owner = \<lambda>pID. emptyUserID, vis = \<lambda>pID. FriendV, pendingSApiReqs = [], sApiReq = \<lambda>aID. emptyRequestInfo, serverApiIDs = [], serverPass = \<lambda>aID. emptyPass, outerPostIDs = \<lambda>aID. [], outerPost = \<lambda>aID papID. emptyPost, outerOwner = \<lambda>aID papID. emptyUserID, outerVis = \<lambda>aID pID. FriendV, pendingCApiReqs = [], cApiReq = \<lambda>aID. emptyRequestInfo, clientApiIDs = [], clientPass = \<lambda>aID. emptyPass, sharedWith = \<lambda>pID. []\<rparr> \<and> BC vl vl1 \<and> corrFrom emptyPost vl1
[PROOF STEP]
by auto |
[STATEMENT]
lemma thread_ok_ts_change:
"(\<And>t. ts t = None \<longleftrightarrow> ts' t = None) \<Longrightarrow> thread_ok ts ta \<longleftrightarrow> thread_ok ts' ta"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>t. (ts t = None) = (ts' t = None)) \<Longrightarrow> thread_ok ts ta = thread_ok ts' ta
[PROOF STEP]
by(cases ta)(auto simp add: free_thread_id_iff) |
1995 : Image and Reality of the Israel @-@ Palestine Conflict , Verso ; ISBN 1 @-@ 85984 @-@ 442 @-@ 1
|
Formal statement is: lemma LIM_cong: "a = b \<Longrightarrow> (\<And>x. x \<noteq> b \<Longrightarrow> f x = g x) \<Longrightarrow> l = m \<Longrightarrow> (f \<midarrow>a\<rightarrow> l) \<longleftrightarrow> (g \<midarrow>b\<rightarrow> m)" Informal statement is: If $f$ and $g$ are functions that agree on all points except $b$, and $f(b) = g(b) = l$, then $f$ converges to $l$ at $a$ if and only if $g$ converges to $l$ at $b$. |
(**************************************************************************************************
* Preservation and Progress for STLC with Subtyping *
* Based on original code by: Brian Aydemir & Arthur Charguéraud, March 2007, Coq v8.1
* Modifications by Bruno C. d. S. Oliveira, Shaobo Cui and Baber Rehman, January 2020, Coq v8.7.0 *
***************************************************************************************************)
Set Implicit Arguments.
Require Import TLC.LibLN.
Implicit Types x : var.
Implicit Types X : var.
(* ***********************************************************************)
(** * Description of the Language *)
(** Representation of pre-types *)
Inductive typ : Set :=
| typ_top : typ
| typ_int : typ
| typ_arrow : typ -> typ -> typ.
(** Representation of pre-terms *)
Inductive trm : Set :=
| trm_bvar : nat -> trm
| trm_fvar : var -> trm
| trm_abs : typ -> trm -> trm
| trm_app : trm -> trm -> trm.
(** Opening up a term binder occuring in a term *)
Fixpoint open_ee_rec (k : nat) (f : trm) (e : trm) {struct e} : trm :=
match e with
| trm_bvar i => If k = i then f else (trm_bvar i)
| trm_fvar x => trm_fvar x
| trm_abs V e1 => trm_abs V (open_ee_rec (S k) f e1)
| trm_app e1 e2 => trm_app (open_ee_rec k f e1) (open_ee_rec k f e2)
end.
Definition open_ee t u := open_ee_rec 0 u t.
(** Notation for opening up binders with type or term variables *)
Notation "t 'open_ee_var' x" := (open_ee t (trm_fvar x)) (at level 67).
(** Terms as locally closed pre-terms *)
Inductive term : trm -> Prop :=
| term_var : forall x,
term (trm_fvar x)
| term_abs : forall L V e1,
(forall x, x \notin L -> term (e1 open_ee_var x)) ->
term (trm_abs V e1)
| term_app : forall e1 e2,
term e1 ->
term e2 ->
term (trm_app e1 e2).
(** Binding are mapping type term variables.
[x ~: T] is a typing assumption *)
Notation "x ~: T" := (x ~ T)
(at level 23, left associativity) : env_scope.
(** Environment is an associative list of bindings. *)
Definition env := LibEnv.env typ.
(** A environment E is well-formed if it contains no duplicate bindings *)
Inductive okt : env -> Prop :=
| okt_empty :
okt empty
| okt_typ : forall E x T,
okt E-> x # E -> okt (E & x ~: T).
(** Subtyping relation *)
Inductive sub : typ -> typ -> Prop :=
| sub_top : forall S, sub S typ_top
| sub_int : sub typ_int typ_int
| sub_arrow : forall S1 S2 T1 T2, sub T1 S1 -> sub S2 T2 ->
sub (typ_arrow S1 S2) (typ_arrow T1 T2).
(** Typing relation *)
Inductive typing : env -> trm -> typ -> Prop :=
| typing_var : forall E x T,
okt E ->
binds x T E ->
typing E (trm_fvar x) T
| typing_abs : forall L E V e1 T1,
(forall x, x \notin L ->
typing (E & x ~: V) (e1 open_ee_var x) T1) ->
typing E (trm_abs V e1) (typ_arrow V T1)
| typing_app : forall T1 E e1 e2 T2,
typing E e1 (typ_arrow T1 T2) ->
typing E e2 T1 ->
typing E (trm_app e1 e2) T2
| typing_sub : forall S E e T,
typing E e S ->
sub S T ->
typing E e T.
(** Values *)
Inductive value : trm -> Prop :=
| value_abs : forall V e1, term (trm_abs V e1) ->
value (trm_abs V e1).
(** One-step reduction *)
Inductive red : trm -> trm -> Prop :=
| red_app_1 : forall e1 e1' e2,
term e2 ->
red e1 e1' ->
red (trm_app e1 e2) (trm_app e1' e2)
| red_app_2 : forall e1 e2 e2',
value e1 ->
red e2 e2' ->
red (trm_app e1 e2) (trm_app e1 e2')
| red_abs : forall V e1 v2,
term (trm_abs V e1) ->
value v2 ->
red (trm_app (trm_abs V e1) v2) (open_ee e1 v2).
(** Our goal is to prove preservation and progress *)
Definition preservation := forall E e e' T,
typing E e T ->
red e e' ->
typing E e' T.
Definition progress := forall e T,
typing empty e T ->
value e
\/ exists e', red e e'.
(** Computing free term variables in terms *)
Fixpoint fv_ee (e : trm) {struct e} : vars :=
match e with
| trm_bvar i => \{}
| trm_fvar x => \{x}
| trm_abs V e1 => (fv_ee e1)
| trm_app e1 e2 => (fv_ee e1) \u (fv_ee e2)
end.
(** Substitution for free term variables in terms. *)
Fixpoint subst_ee (z : var) (u : trm) (e : trm) {struct e} : trm :=
match e with
| trm_bvar i => trm_bvar i
| trm_fvar x => If x = z then u else (trm_fvar x)
| trm_abs V e1 => trm_abs V (subst_ee z u e1)
| trm_app e1 e2 => trm_app (subst_ee z u e1) (subst_ee z u e2)
end.
(* ********************************************************************** *)
(** * Tactics *)
(** Constructors as hints. *)
Hint Constructors term ok okt value red.
Hint Resolve
sub_top sub_int sub_arrow
typing_var typing_app typing_sub.
(** Gathering free names already used in the proofs *)
Ltac gather_vars :=
let A := gather_vars_with (fun x : vars => x) in
let B := gather_vars_with (fun x : var => \{x}) in
let D := gather_vars_with (fun x : trm => fv_ee x) in
let F := gather_vars_with (fun x : env => dom x) in
constr:(A \u B \u D \u F).
(** "pick_fresh x" tactic create a fresh variable with name x *)
Ltac pick_fresh x :=
let L := gather_vars in (pick_fresh_gen L x).
(** "apply_fresh T as x" is used to apply inductive rule which
use an universal quantification over a cofinite set *)
Tactic Notation "apply_fresh" constr(T) "as" ident(x) :=
apply_fresh_base T gather_vars x.
Tactic Notation "apply_fresh" "*" constr(T) "as" ident(x) :=
apply_fresh T as x; autos*.
(** These tactics help applying a lemma which conclusion mentions
an environment (E & F) in the particular case when F is empty *)
Ltac get_env :=
match goal with
| |- sub ?E _ _ => E
| |- typing ?E _ _ => E
end.
Tactic Notation "apply_empty_bis" tactic(get_env) constr(lemma) :=
let E := get_env in rewrite <- (concat_empty_r E);
eapply lemma; try rewrite concat_empty_r.
Tactic Notation "apply_empty" constr(F) :=
apply_empty_bis (get_env) F.
Tactic Notation "apply_empty" "*" constr(F) :=
apply_empty F; autos*.
(* ********************************************************************** *)
(** * Properties of Substitutions *)
(* ********************************************************************** *)
(** ** Properties of term substitution in terms *)
Lemma open_ee_rec_term_core : forall e j v u i, i <> j ->
open_ee_rec j v e = open_ee_rec i u (open_ee_rec j v e) ->
e = open_ee_rec i u e.
Proof.
induction e; introv Neq H; simpl in *; inversion H; f_equal*.
case_nat*. case_nat*.
Qed.
Lemma open_ee_rec_term : forall u e,
term e -> forall k, e = open_ee_rec k u e.
Proof.
induction 1; intros; simpl; f_equal*.
unfolds open_ee. pick_fresh x.
apply* (@open_ee_rec_term_core e1 0 (trm_fvar x)).
Qed.
(** Substitution for a fresh name is identity. *)
Lemma subst_ee_fresh : forall x u e,
x \notin fv_ee e -> subst_ee x u e = e.
Proof.
induction e; simpl; intros; f_equal*.
case_var*.
Qed.
(** Substitution distributes on the open operation. *)
Lemma subst_ee_open_ee : forall t1 t2 u x, term u ->
subst_ee x u (open_ee t1 t2) =
open_ee (subst_ee x u t1) (subst_ee x u t2).
Proof.
intros. unfold open_ee. generalize 0.
induction t1; intros; simpls; f_equal*.
case_nat*.
case_var*. rewrite* <- open_ee_rec_term.
Qed.
(** Substitution and open_var for distinct names commute. *)
Lemma subst_ee_open_ee_var : forall x y u e, y <> x -> term u ->
(subst_ee x u e) open_ee_var y = subst_ee x u (e open_ee_var y).
Proof.
introv Neq Wu. rewrite* subst_ee_open_ee.
simpl. case_var*.
Qed.
(** Opening up a body t with a type u is the same as opening
up the abstraction with a fresh name x and then substituting u for x. *)
Lemma subst_ee_intro : forall x u e,
x \notin fv_ee e -> term u ->
open_ee e u = subst_ee x u (e open_ee_var x).
Proof.
introv Fr Wu. rewrite* subst_ee_open_ee.
rewrite* subst_ee_fresh. simpl. case_var*.
Qed.
(** Substitutions preserve local closure. *)
Lemma subst_ee_term : forall e1 Z e2,
term e1 -> term e2 -> term (subst_ee Z e2 e1).
Proof.
induction 1; intros; simpl; auto.
case_var*.
apply_fresh* term_abs as y. rewrite* subst_ee_open_ee_var.
Qed.
Hint Resolve subst_ee_term.
(* ********************************************************************** *)
(** * Relations between well-formed environment and types well-formed
in environments *)
(** If an environment is well-formed, then it does not contain duplicated keys. *)
Lemma ok_from_okt : forall E,
okt E -> ok E.
Proof.
induction 1; auto.
Qed.
Hint Extern 1 (ok _) => apply ok_from_okt.
(* ********************************************************************** *)
(** ** Properties of well-formedness of an environment *)
(** Inversion lemma *)
Lemma okt_push_inv : forall E x T,
okt (E & x ~: T) -> okt E /\ x # E.
Proof.
introv O. inverts O.
false* empty_push_inv.
lets (?&M&?): (eq_push_inv H). subst. autos.
Qed.
(** Through strengthening *)
Lemma okt_strengthen : forall x T (E F:env),
okt (E & x ~: T & F) ->
okt (E & F).
Proof.
introv O. induction F using env_ind.
rewrite concat_empty_r in *. lets*: (okt_push_inv O).
rewrite concat_assoc in *.
apply okt_push_inv in O.
destruct O. apply IHF in H.
apply okt_typ; autos*.
Qed.
(** Automation *)
Hint Immediate okt_strengthen.
(* ********************************************************************** *)
(** ** Regularity of relations *)
(** The subtyping relation is restricted to well-formed objects. *)
(** The typing relation is restricted to well-formed objects. *)
Lemma typing_regular : forall E e T,
typing E e T -> okt E /\ term e.
Proof.
induction 1; try splits*.
pick_fresh y. specializes H0 y. destructs~ H0.
apply okt_push_inv in H0. destruct H0. auto.
apply_fresh* term_abs as y.
specializes H0 y. destructs~ H0.
Qed.
(** The value relation is restricted to well-formed objects. *)
Lemma value_regular : forall t,
value t -> term t.
Proof.
induction 1; autos*.
Qed.
(** The reduction relation is restricted to well-formed objects. *)
Lemma red_regular : forall t t',
red t t' -> term t /\ term t'.
Proof.
induction 1; split; autos* value_regular.
inversions H. pick_fresh y. rewrite* (@subst_ee_intro y).
Qed.
(** Automation *)
Hint Extern 1 (okt ?E) =>
match goal with
| H: typing _ _ _ |- _ => apply (proj31 (typing_regular H))
end.
Hint Extern 1 (term ?e) =>
match goal with
| H: typing _ ?e _ |- _ => apply (proj32 (typing_regular H))
| H: red ?e _ |- _ => apply (proj1 (red_regular H))
| H: red _ ?e |- _ => apply (proj2 (red_regular H))
end.
(* ********************************************************************** *)
(** * Properties of Subtyping *)
(* ********************************************************************** *)
(** Reflexivity (1) *)
Lemma sub_reflexivity : forall T,
sub T T .
Proof.
induction T; eauto.
Qed.
(* ********************************************************************** *)
(** Narrowing and transitivity (3) *)
(*Definition transitivity_on Q := forall S T,
sub S Q -> sub Q T -> sub S T.
Hint Unfold transitivity_on.*)
Require Import Program.Equality.
Lemma sub_transitivity : forall B A C, sub A B -> sub B C -> sub A C.
Proof.
induction B; intros;
generalize H0 H; clear H0; clear H; generalize A; clear A;
intros; dependent destruction H0; auto;
induction A; try (inversion H); eauto.
Qed.
(*Lemma sub_transitivity : forall Q,
transitivity_on Q.
Proof.
induction Q; unfold transitivity_on; intros.
generalize H0 H; clear H0; clear H; generalize S; clear S;
intros; dependent destruction H0; auto;
induction S; try (inversion H); eauto.
Qed.*)
(* ********************************************************************** *)
(** Weakening (5) *)
Lemma typing_weakening : forall E F G e T,
typing (E & G) e T ->
okt (E & F & G) ->
typing (E & F & G) e T.
Proof.
introv Typ. gen F. inductions Typ; introv Ok.
apply* typing_var. apply* binds_weaken.
apply_fresh* typing_abs as x. forwards~ K: (H x).
apply_ih_bind (H0 x); eauto.
apply* typing_app.
apply* typing_sub.
Qed.
(************************************************************************ *)
(** Preservation by Term Substitution (8) *)
Lemma typing_through_subst_ee : forall U E F x T e u,
typing (E & x ~: U & F) e T ->
typing E u U ->
typing (E & F) (subst_ee x u e) T.
Proof.
introv TypT TypU. inductions TypT; introv; simpl.
case_var.
binds_get H0. apply_empty* typing_weakening.
binds_cases H0; apply* typing_var.
apply_fresh* typing_abs as y.
rewrite* subst_ee_open_ee_var.
apply_ih_bind* H0.
apply typing_regular in TypU. destruct TypU. auto.
apply* typing_app.
apply* typing_sub.
Qed.
(* ********************************************************************** *)
(** * Preservation *)
(* ********************************************************************** *)
(** Inversions for Typing (13) *)
Lemma typing_inv_abs : forall E S1 e1 T,
typing E (trm_abs S1 e1) T ->
forall U1 U2, sub T (typ_arrow U1 U2) ->
sub U1 S1
/\ exists S2, exists L, forall x, x \notin L ->
typing (E & x ~: S1) (e1 open_ee_var x) S2 /\ sub S2 U2.
Proof.
introv Typ. gen_eq e: (trm_abs S1 e1). gen S1 e1.
induction Typ; intros S1 b1 EQ U1 U2 Sub; inversions EQ.
inversions* Sub.
apply IHTyp. auto.
eapply sub_transitivity. apply H. auto.
Qed.
(* ********************************************************************** *)
(** Preservation Result (20) *)
Lemma preservation_result : preservation.
Proof.
introv Typ. gen e'. induction Typ; introv Red;
try solve [ inversion Red ].
(* case: app *)
- inversions Red; try solve [ apply* typing_app ].
destruct~ (typing_inv_abs Typ1 (U1:=T1) (U2:=T2)) as [P1 [S2 [L P2]]].
apply* sub_reflexivity.
pick_fresh X. forwards~ K: (P2 X). destruct K.
rewrite* (@subst_ee_intro X).
apply_empty (@typing_through_subst_ee V).
apply* (@typing_sub S2).
autos*.
apply* value_regular.
(* case sub *)
- apply* typing_sub.
Qed.
(* ********************************************************************** *)
(** * Progress *)
(* ********************************************************************** *)
(** Canonical Forms (14) *)
Lemma canonical_form_abs : forall t U1 U2,
value t -> typing empty t (typ_arrow U1 U2) ->
exists V, exists e1, t = trm_abs V e1.
Proof.
introv Val Typ. gen_eq E: (@empty typ).
gen_eq T: (typ_arrow U1 U2). gen U1 U2.
induction Typ; introv EQT EQE;
try solve [ inversion Val | inversion EQT | eauto ].
subst. inversion H. autos*.
Qed.
(* ********************************************************************** *)
(** Progress Result (16) *)
Lemma progress_result : progress.
Proof.
introv Typ. gen_eq E: (@empty typ). lets Typ': Typ.
induction Typ; intros EQ; subst.
left*.
(* case: var *)
false* binds_empty_inv.
(* case: abs *)
left*. apply value_abs. apply* typing_regular.
(* case: app *)
right. destruct* IHTyp1 as [Val1 | [e1' Rede1']].
destruct* IHTyp2 as [Val2 | [e2' Rede2']].
destruct (canonical_form_abs Val1 Typ1) as [S [e3 EQ]].
subst. exists* (open_ee e3 e2). apply red_abs.
apply* typing_regular. auto.
exists (trm_app e1' e2). apply red_app_1. apply* typing_regular.
auto.
(* case: sub *)
autos*.
Qed. |
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: gga_exc *)
$define gga_x_rpw86_params
$include "gga_x_pw86.mpl"
lv_alpha := 0.02178:
lv_beta := 1.15:
lv_muLV := 0.8491/9:
lv_f0 := s ->
+ (1 + lv_muLV*s^2)/(1 + lv_alpha*s^6)
+ lv_alpha*s^6*pw86_f0(s)/(lv_beta + lv_alpha*s^6):
lv_f := x -> lv_f0(X2S*x):
f := (rs, z, xt, xs0, xs1) -> gga_exchange(lv_f, rs, z, xs0, xs1):
|
module Main
import System
countdown : (secs : Nat) -> IO ()
countdown Z = putStrLn "Kaboom"
countdown secs@(S k) = do putStrLn $ show secs
usleep 1000000
countdown k
|
{-# OPTIONS --sized-types --show-implicit #-}
module WrongSizeAssignment where
postulate
Size : Set
_^ : Size -> Size
∞ : Size
{-# BUILTIN SIZE Size #-}
{-# BUILTIN SIZESUC _^ #-}
{-# BUILTIN SIZEINF ∞ #-}
data Empty : Set where
data N : {_ : Size} -> Set where
zero : N {∞}
suc : forall {i} -> N {i ^} -> N {i}
lift : forall {i} -> N {i} -> N {i ^}
lift zero = zero
lift (suc x) = suc (lift x)
f : forall {i} -> N {i ^} -> Empty
f x = f (suc (lift x))
|
function rf=v_lpcla2rf(la)
%V_LPCLA2RF Convert log areas to reflection coefficients RF=(LA)
% Copyright (C) Mike Brookes 1997
% Version: $Id: v_lpcla2rf.m 10865 2018-09-21 17:22:45Z dmb $
%
% VOICEBOX is a MATLAB toolbox for speech processing.
% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You can obtain a copy of the GNU General Public License from
% http://www.gnu.org/copyleft/gpl.html or by writing to
% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[nf,p2]=size(la);
rf=-tanh((la(:,1:p2-1)-la(:,2:p2))/2);
|
-- Copyright 2017, the blau.io contributors
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module API.Web.HTML.HTMLScriptElement
import IdrisScript
%access public export
%default total
record HTMLScriptElement where
constructor New
text : String
htmlScriptElementFromPointer : (ref : JSRef) -> JS_IO $ Maybe HTMLScriptElement
htmlScriptElementFromPointer ref = case !maybeText of
Nothing => pure Nothing
(Just text) => pure $ Just $ New text
where
maybeText : JS_IO $ Maybe String
maybeText = let
getText = jscall "%0.text" (JSRef -> JS_IO JSRef) ref
in
case !(IdrisScript.pack !getText) of
(JSString ** str) => pure $ Just $ fromJS str
_ => pure Nothing
|
[STATEMENT]
lemma smaps_over_singleton:
assumes "k \<in> A" and "vs \<subseteq> B"
shows "{k := vs}. \<in> smaps_over A B"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. { k := vs}. \<in> smaps_over A B
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
k \<in> A
vs \<subseteq> B
goal (1 subgoal):
1. { k := vs}. \<in> smaps_over A B
[PROOF STEP]
unfolding smaps_over_def
[PROOF STATE]
proof (prove)
using this:
k \<in> A
vs \<subseteq> B
goal (1 subgoal):
1. { k := vs}. \<in> {m. sdom m \<subseteq> A \<and> sran m \<subseteq> B}
[PROOF STEP]
by(auto dest: subsetD[OF sdom_singleton]) |
module MoireHamiltonian
using Plots
include("lattice.jl")
include("folding.jl")
include("bilayer.jl")
end
|
[STATEMENT]
lemma istate_\<Delta>0:
assumes B: "B vl vl1"
shows "\<Delta>0 istate vl istate vl1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Delta>0 istate vl istate vl1
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
B vl vl1
goal (1 subgoal):
1. \<Delta>0 istate vl istate vl1
[PROOF STEP]
unfolding \<Delta>0_def istate_def B_def
[PROOF STATE]
proof (prove)
using this:
BC vl vl1 \<and> corrFrom emptyPost vl1
goal (1 subgoal):
1. PID \<notin> set (postIDs \<lparr>admin = emptyUserID, pendingUReqs = [], userReq = \<lambda>uID. emptyRequestInfo, userIDs = [], user = \<lambda>uID. emptyUser, pass = \<lambda>uID. emptyPass, pendingFReqs = \<lambda>uID. [], friendReq = \<lambda>uID uID'. emptyRequestInfo, friendIDs = \<lambda>uID. [], sentOuterFriendIDs = \<lambda>uID. [], recvOuterFriendIDs = \<lambda>uID. [], postIDs = [], post = \<lambda>papID. emptyPost, owner = \<lambda>pID. emptyUserID, vis = \<lambda>pID. FriendV, pendingSApiReqs = [], sApiReq = \<lambda>aID. emptyRequestInfo, serverApiIDs = [], serverPass = \<lambda>aID. emptyPass, outerPostIDs = \<lambda>aID. [], outerPost = \<lambda>aID papID. emptyPost, outerOwner = \<lambda>aID papID. emptyUserID, outerVis = \<lambda>aID pID. FriendV, pendingCApiReqs = [], cApiReq = \<lambda>aID. emptyRequestInfo, clientApiIDs = [], clientPass = \<lambda>aID. emptyPass, sharedWith = \<lambda>pID. []\<rparr>) \<and> \<lparr>admin = emptyUserID, pendingUReqs = [], userReq = \<lambda>uID. emptyRequestInfo, userIDs = [], user = \<lambda>uID. emptyUser, pass = \<lambda>uID. emptyPass, pendingFReqs = \<lambda>uID. [], friendReq = \<lambda>uID uID'. emptyRequestInfo, friendIDs = \<lambda>uID. [], sentOuterFriendIDs = \<lambda>uID. [], recvOuterFriendIDs = \<lambda>uID. [], postIDs = [], post = \<lambda>papID. emptyPost, owner = \<lambda>pID. emptyUserID, vis = \<lambda>pID. FriendV, pendingSApiReqs = [], sApiReq = \<lambda>aID. emptyRequestInfo, serverApiIDs = [], serverPass = \<lambda>aID. emptyPass, outerPostIDs = \<lambda>aID. [], outerPost = \<lambda>aID papID. emptyPost, outerOwner = \<lambda>aID papID. emptyUserID, outerVis = \<lambda>aID pID. FriendV, pendingCApiReqs = [], cApiReq = \<lambda>aID. emptyRequestInfo, clientApiIDs = [], clientPass = \<lambda>aID. emptyPass, sharedWith = \<lambda>pID. []\<rparr> = \<lparr>admin = emptyUserID, pendingUReqs = [], userReq = \<lambda>uID. emptyRequestInfo, userIDs = [], user = \<lambda>uID. emptyUser, pass = \<lambda>uID. emptyPass, pendingFReqs = \<lambda>uID. [], friendReq = \<lambda>uID uID'. emptyRequestInfo, friendIDs = \<lambda>uID. [], sentOuterFriendIDs = \<lambda>uID. [], recvOuterFriendIDs = \<lambda>uID. [], postIDs = [], post = \<lambda>papID. emptyPost, owner = \<lambda>pID. emptyUserID, vis = \<lambda>pID. FriendV, pendingSApiReqs = [], sApiReq = \<lambda>aID. emptyRequestInfo, serverApiIDs = [], serverPass = \<lambda>aID. emptyPass, outerPostIDs = \<lambda>aID. [], outerPost = \<lambda>aID papID. emptyPost, outerOwner = \<lambda>aID papID. emptyUserID, outerVis = \<lambda>aID pID. FriendV, pendingCApiReqs = [], cApiReq = \<lambda>aID. emptyRequestInfo, clientApiIDs = [], clientPass = \<lambda>aID. emptyPass, sharedWith = \<lambda>pID. []\<rparr> \<and> BC vl vl1 \<and> corrFrom emptyPost vl1
[PROOF STEP]
by auto |
Formal statement is: lemmas open_real_greaterThan = open_greaterThan[where 'a=real] Informal statement is: The set of real numbers greater than $a$ is open. |
# Homework 4
This Notebook builds on the DCOPF model introduced in [Notebook 6](https://github.com/east-winds/power-systems-optimization/tree/master/Notebooks) and incorporates some elements of Economic Dispatch introduced in [Notebook 4](https://github.com/east-winds/power-systems-optimization/tree/master/Notebooks).
First, load (or install if necessary) a set of packages you'll need for this assignment...
```julia
using JuMP
using GLPK
using DataFrames
using CSV
using Plots; plotly();
```
## Question 1: Modifying IEEE-14
**A. Increased generation costs**
Copy the IEEE 14 bus system and DCOPF solver function from Notebook 6. In addition, add the following line to the return call of the function:
```julia
status = termination_status(DCOPF)
```
This tells you the solver termination status for the problem: e.g. was an optimal solution found, was the solution infeasible, was it unbounded, etc.
Make the following change to the system:
- Increase the variable cost of Generator 1 to \$30 / MWh
Run the DCOPF and output generation, flows, and prices.
```julia
datadir = joinpath("..","Notebooks","ieee_test_cases")
gens = CSV.read(joinpath(datadir,"Gen14.csv"), DataFrame);
lines = CSV.read(joinpath(datadir,"Tran14.csv"), DataFrame);
loads = CSV.read(joinpath(datadir,"Load14.csv"), DataFrame);
# Rename all columns to lowercase (by convention)
for f in [gens, lines, loads]
rename!(f,lowercase.(names(f)))
end
# create generator ids
gens.id = 1:nrow(gens);
# create line ids
lines.id = 1:nrow(lines);
# add set of rows for reverse direction with same parameters
lines2 = copy(lines)
lines2.f = lines2.fromnode
lines2.fromnode = lines.tonode
lines2.tonode = lines2.f
lines2 = lines2[:,names(lines)]
append!(lines,lines2)
# calculate simple susceptance, ignoring resistance as earlier
lines.b = 1 ./ lines.reactance
# keep only a single time period
loads = loads[:,["connnode","interval-1_load"]]
rename!(loads,"interval-1_load" => "demand");
```
```julia
```
```julia
```
```julia
```
```julia
```
Regarding the above results, answer the following:
- How has generation changed compared to the default system?
- What explains the new prices?
```julia
```
**B. Constrained line**
Make the following changes to the system:
- Increase the variable cost of Generator 1 to \$30 / MWh
- Reduce flow limit on the line connecting 2 and 3 ($l_{23}$) to 70 MW
Run the DCOPF and output generation, flows, and prices.
```julia
```
```julia
```
```julia
```
Regarding the above results, answer the following:
- Which node has the highest price and why?
- What is the difference in prices across $l_{23}$, also known as the congestion rent? How do you interpret this value (what is it's practical meaning?)
```julia
```
**C. Demand increase**
Make the following changes to the system:
- Increase the variable cost of Generator 1 to \$30 / MWh
- Reduce flow limit on the line connecting 2 and 3 ($l_{23}$) to 70 MW
- Increase demands everywhere by 5\%.
```julia
```
Calculate the total available generating capacity:
```julia
```
Calculate the new total demand:
```julia
```
Run the DCOPF and show prices.
```julia
```
**What is happening in this system?**
```julia
```
## Question 2: Linear losses
Up until now, we have ignored transmission losses. A quadratic approximation of losses is given by:
\begin{align}
LOSS_{ij} &\approx \frac{G_{ij}}{BaseMVA} (\theta_i-\theta_j)^2 \\
& \approx \frac{1}{BaseMVA} \frac{R_{ij}}{R_{ij}^2+X_{ij}^2}(\theta_i-\theta_j)^2
\end{align}
where $G$ is the line's conductance, $R$ is the line's resistance and $X$ is the line's reactance. See the `lines` data frame for these parameters.
For our purposes, we will approximate this quadratic via:
$$
LOSS_{ij} \geq \frac{R_{ij}}{BaseMVA} \times (MaxFlow_{ij})^2
\left(\frac{|FLOW_{ij}|}{MaxFlow_{ij}} - 0.165 \right)
$$
where $MaxFlow_{ij}=200 MW$ in this problem. Note the greater than equal sign, as we do not want to have negative losses.
This approximation is based on Fitiwi et al. (2016), "Finding a representative network losses model for large-scale transmission expansion planning with renewable energy sources," *Energy* 101: 343-358, https://doi.org/10.1016/j.energy.2016.02.015.
Note that this is a linear approximation of transmission losses, which are actually a quadratic function of power flows. Fitiwi et al. 2016 and other papers describe piece-wise or segment-wise linear approximations of the quadratic function which provide a tighter lower bound approximation of losses, but we'll use a single linear term for this assignment.
See Jenkins & Sepulveda et al. 2017, "Enhanced decision support for a changing electricity landscape: the GenX configurable electricity resource capacity expansion model", MIT Energy Initiative Working Paper 2017-10 http://bit.ly/GenXModel Section 5.8, for an example of a linear segment-wise approximation of quadratic transmission losses.
**A. Code linear losses**
Reload the original data from Notebook 6 and copy the IEEE 14 bus system and DCOPF solver function from Notebook 6 into a new function `dcopf_ieee_lossy`.
Make the following changes:
- Increase the variable cost of Generator 1 to \$30 / MWh
- Change all transmission line capacities to 200 MW
Implement losses into the supply/demand balance equations. A standard way to implement absolute values in linear programming is by introducing two non-negative auxiliary variables $x^+$, $x^-$ $\geq 0$:
$$
x = x^+ - x^-
$$
and the absolute value can be represented as:
$$
|x| = x^+ + x^-
$$
(You should satisfy yourself that this equality holds.)
It makes the formulation easier if losses are added to the supply/demand balance constraint in each node by splitting losses in half between the receiving and sending end.
Indicate which equations and variables you have added and explain your steps using inline code comments (e.g. `# Comment`).
Run the lossy DCOPF and output generation, flows, losses, and prices.
```julia
```
```julia
```
```julia
```
```julia
```
```julia
```
```julia
```
**B. Interpret results**
Run the same parameters in the lossless OPF from problem 1. How do prices and flows change? What is the largest magnitude difference in prices between the solution with losses and the lossless OPF solution?
```julia
```
## Question 3 - Security contingencies
Power system operators need to ensure that power is delivered reliably even in the event of unexpected outages (**contingencies**). One common contigency that must be planned for is the loss of a transmission line. The security-constrained OPF (SCOPF) run by operators solves for an optimal dispatch that is simultaneously robust (i.e., feasible) to each of the lines failing individually. This is what is known as **N-1 security**, because we assume that at most one component fails in any given scenario.
In this problem, we will not code a full SCOPF, but rather investigate what happens to the feasibility of our problem when we remove transmission lines.
**A. Setup data**
The following code loads the original dataset (with one row per line) and includes a function `format_lines` that converts this to a format that our solver function can use (duplicating rows for both directions, adding susceptance, etc.).
```julia
lines = CSV.read(joinpath(datadir,"Tran14.csv"), DataFrame);
rename!(lines,lowercase.(names(lines)))
function format_lines(lines)
# create line ids
lines.id = 1:nrow(lines);
# add set of rows for reverse direction with same parameters
lines2 = copy(lines)
lines2.f = lines2.fromnode
lines2.fromnode = lines.tonode
lines2.tonode = lines2.f
lines2 = lines2[:,names(lines)]
append!(lines,lines2)
# calculate simple susceptance, ignoring resistance as earlier
lines.b = 1 ./ lines.reactance
return(lines)
end
```
Next:
1. Set the capacity of all lines in the system at 100 MW, except for the line $l_{12}$, which you should set to 200 MW.
2. Create a load dataframe `loads_sens` that increases demands everywhere by 10\%
```julia
```
**B. Loop over line contingencies**
Create a dataframe `status` with the `fromnode` and `tonode` columns of `lines`.
Create a [for loop](https://docs.julialang.org/en/v1/manual/control-flow/#man-loops) that iterates over each line and:
- sets the reactance to be a very high value, 1e9 (i.e., no power will be transmitted)
- creates a version of the dataframe that our solver function can use via `format_lines`
- runs DCOPF
- stores the solution status in a `opf` column in the corresponding row of the `status` dataframe
Show the `status` results.
```julia
```
**3. Interpret results**
Are all of the cases feasible? If not, how many are infeasible?
```julia
```
Pick two cases where the solution gives a different status. (For our purposes, dual infeasible and primal infeasible are the same.) What is happening here?
Given this, do you conclude that the system with the assumed transmission line ratings is secure as-is, or do we need to add more redundancy to the system?
```julia
```
|
[STATEMENT]
lemma unitary_intro: "(UNIV::'s set) = {a} \<Longrightarrow> OFCLASS('s, unitary_class)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. UNIV = {a} \<Longrightarrow> OFCLASS('s, unitary_class)
[PROOF STEP]
apply (intro_classes, auto)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. UNIV = {a} \<Longrightarrow> finite UNIV
2. UNIV = {a} \<Longrightarrow> CARD('s) = Suc 0
[PROOF STEP]
using finite.simps
[PROOF STATE]
proof (prove)
using this:
finite ?a = (?a = {} \<or> (\<exists>A a. ?a = insert a A \<and> finite A))
goal (2 subgoals):
1. UNIV = {a} \<Longrightarrow> finite UNIV
2. UNIV = {a} \<Longrightarrow> CARD('s) = Suc 0
[PROOF STEP]
apply blast
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. UNIV = {a} \<Longrightarrow> CARD('s) = Suc 0
[PROOF STEP]
using card_1_singleton_iff
[PROOF STATE]
proof (prove)
using this:
(card ?A = Suc 0) = (\<exists>x. ?A = {x})
goal (1 subgoal):
1. UNIV = {a} \<Longrightarrow> CARD('s) = Suc 0
[PROOF STEP]
apply blast
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
[STATEMENT]
lemma corec_llist_never_stop: "corec_llist IS_LNIL LHD (\<lambda>_. False) MORE LTL x = unfold_llist IS_LNIL LHD LTL x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. corec_llist IS_LNIL LHD (\<lambda>_. False) MORE LTL x = unfold_llist IS_LNIL LHD LTL x
[PROOF STEP]
by(coinduction arbitrary: x) auto |
/-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.finset.locally_finite
import data.fintype.big_operators
/-!
# Intervals in a pi type
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file shows that (dependent) functions to locally finite orders equipped with the pointwise
order are locally finite and calculates the cardinality of their intervals.
-/
open finset fintype
open_locale big_operators
variables {ι : Type*} {α : ι → Type*}
namespace pi
section locally_finite
variables [decidable_eq ι] [fintype ι] [Π i, decidable_eq (α i)]
[Π i, partial_order (α i)] [Π i, locally_finite_order (α i)]
instance : locally_finite_order (Π i, α i) :=
locally_finite_order.of_Icc _
(λ a b, pi_finset $ λ i, Icc (a i) (b i))
(λ a b x, by simp_rw [mem_pi_finset, mem_Icc, le_def, forall_and_distrib])
variables (a b : Π i, α i)
lemma Icc_eq : Icc a b = pi_finset (λ i, Icc (a i) (b i)) := rfl
lemma card_Icc : (Icc a b).card = ∏ i, (Icc (a i) (b i)).card := card_pi_finset _
lemma card_Ico : (Ico a b).card = (∏ i, (Icc (a i) (b i)).card) - 1 :=
by rw [card_Ico_eq_card_Icc_sub_one, card_Icc]
lemma card_Ioc : (Ioc a b).card = (∏ i, (Icc (a i) (b i)).card) - 1 :=
by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc]
lemma card_Ioo : (Ioo a b).card = (∏ i, (Icc (a i) (b i)).card) - 2 :=
by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc]
end locally_finite
section bounded
variables [decidable_eq ι] [fintype ι] [Π i, decidable_eq (α i)] [Π i, partial_order (α i)]
section bot
variables [Π i, locally_finite_order_bot (α i)] (b : Π i, α i)
instance : locally_finite_order_bot (Π i, α i) :=
locally_finite_order_top.of_Iic _
(λ b, pi_finset $ λ i, Iic (b i))
(λ b x, by simp_rw [mem_pi_finset, mem_Iic, le_def])
lemma card_Iic : (Iic b).card = ∏ i, (Iic (b i)).card := card_pi_finset _
lemma card_Iio : (Iio b).card = (∏ i, (Iic (b i)).card) - 1 :=
by rw [card_Iio_eq_card_Iic_sub_one, card_Iic]
end bot
section top
variables [Π i, locally_finite_order_top (α i)] (a : Π i, α i)
instance : locally_finite_order_top (Π i, α i) :=
locally_finite_order_top.of_Ici _
(λ a, pi_finset $ λ i, Ici (a i))
(λ a x, by simp_rw [mem_pi_finset, mem_Ici, le_def])
lemma card_Ici : (Ici a).card = (∏ i, (Ici (a i)).card) := card_pi_finset _
lemma card_Ioi : (Ioi a).card = (∏ i, (Ici (a i)).card) - 1 :=
by rw [card_Ioi_eq_card_Ici_sub_one, card_Ici]
end top
end bounded
end pi
|
(*-------------------------------------------*
| CSP-Prover on Isabelle2004 |
| August 2004 |
| |
| CSP-Prover on Isabelle2005 |
| October 2005 (modified) |
| |
| CSP-Prover on Isabelle2009-2 |
| October 2010 (modified) |
| |
| Yoshinao Isobe (AIST JAPAN) |
*-------------------------------------------*)
theory CPO_set
imports CPO_prod
begin
(*****************************************************************
1. Bool is CPO for (Isabelle 2011)
2. Sets are CPO.
3.
4.
*****************************************************************)
(**********************************************************
def: bot in bool
**********************************************************)
declare le_bool_def [simp del] (* for Isabelle 2011 *)
(*
instance bool :: bot0
apply (intro_classes)
done
*)
instantiation "set" :: (type) bot0
begin
definition
set_Bot_def : "Bot == {}"
instance ..
end
(*
for Isabelle 2011
instantiation bool :: bot0
begin
definition
bool_Bot_def : "Bot == False"
instance ..
end
*)
(* isabelle 2009-1
defs (overloaded)
bool_Bot_def : "Bot == False"
*)
(*
For Isabelle 2007
instance "set" :: (type) bot0
apply (intro_classes)
done
defs (overloaded)
set_Bot_def : "Bot == {}"
*)
(************************************************************
Bool bot ==> bot (Isabelle 2011)
************************************************************)
(*
for Isabelle 2011
lemma bool_Bot:
"ALL (X::(bool)). Bot <= X"
apply (simp add: bool_Bot_def)
apply (simp add: le_bool_def)
done
*)
(*
lemma set_Bot:
"ALL (X::('a set)). Bot <= X"
apply (simp add: set_Bot_def)
done
*)
(*****************************
bool bot => bot
*****************************)
(*
Isabelle 2011
instance bool :: bot
apply (intro_classes)
apply (simp only: bool_Bot)
done
*)
(************************************************************
Set bot ==> bot
Isabelle 2011
************************************************************)
(*** set Bot ***)
(*
lemma set_Bot:
"ALL (X::('a set)). Bot <= X"
apply (simp add: set_Bot_def)
(* apply (simp add: prod_Bot) Isabelle 2011 *)
done
*)
(************************************************************
Bool : CPO Isabelle 2011
************************************************************)
(*
(* modified when Isabelle 2011 => Isabelle 2012 *)
(*** bool directed decompo ***)
lemma bool_cpo_lm:
"directed (Bs::(bool) set) ==> Bs hasLUB"
apply (simp add: hasLUB_def)
apply (rule_tac x="(EX b:Bs. b)" in exI)
apply (simp add: isLUB_def isUB_def)
apply (simp add: le_bool_def)
by (auto)
(*****************************
Bool : CPO
*****************************)
instance bool :: cpo
apply (intro_classes)
by (simp add: bool_cpo_lm)
*)
(************************************************************
Bool : CPO_BOT
************************************************************)
(*
Isabelle 2011
instance bool :: cpo_bot
by (intro_classes)
*)
(************************************************************
Set : CPO
************************************************************)
lemma set_cpo_lm:
"directed (Xs::('a set) set) ==> Xs hasLUB"
apply (simp add: hasLUB_def)
apply (rule_tac x="Union Xs" in exI)
apply (simp add: isLUB_def isUB_def)
by (auto)
(*****************************
Set : CPO
*****************************)
instance set :: (type) cpo
apply (intro_classes)
by (simp add: set_cpo_lm)
(************************************************************
Set : CPO_BOT
************************************************************)
instance set :: (type) cpo_bot
apply (intro_classes)
apply (simp add: set_Bot_def)
done
(* ============================================================== *)
(* for isabelle 2011
lemma set_cpo:
"directed (Xs::('a set) set) ==> Xs hasLUB"
by (simp add: complete_cpo)
(* because (bool::cpo) and ("fun" :: (type,cpo) cpo) *)
(************************************************************
Set : CPO_bot
************************************************************)
lemma set_bot:
"Bot <= (x::'a set)"
by (simp add: bottom_bot)
(* because (bool::bot) and ("fun" :: (type,bot) bot) *)
(* -------------------------------------------------------- *)
*)
declare le_bool_def [simp] (* for Isabelle 2011 *)
end
|
\section{Introduction}
\begin{description}
\item[Problem]
Nowadays, people, business and every single device becomes a data factory that generates data. Billions of internet users turn the data quality to interesting and important area for researcher.In one hand data quality getting more important in the industry because this valuable process, can help companies to save time,money and let them to increase their efficiency.On the other hand, scientific researchers use clean version of datasets for their discoveries,approach and researches.In this regard,always custom error generator has been wanted by researchers to let them make new datasets out of one dataset,with fully control on amount and type of errors.
\felix{Many machine learning applications today are based on user data. For instance, user add products, their descriptions, and ratings to Amazon. Amazon trains on this user-entered data machine learning models to recommend products and estimate prices. Users are humans and therefore make mistakes. These mistakes can harm machine learning models. Therefore, for data scientists, it is essential to know whether and to which degree their feature representation and models are robust against a wide range of possible user errors.}
\milad{Nowadays, people, business and every single device becomes a data factory that generates data.At the same time, Many machine learning applications are based on user data.For instance, user add products, their descriptions, and ratings to Amazon. Amazon trains on this user-entered data machine learning models to recommend products and estimate prices. Users are humans and therefore make mistakes. These mistakes can harm machine learning models.As result, data quality turns to interesting and important area for researcher.in this regard, it is essential to know whether and to which degree their feature representation and models are robust against a wide range of possible user errors
}
Dirty Fire as first custom error generator that provides user ability to control accuracy and it can provide errors that does not influence the accuracy and even help more by finding the weakness of machine learning models and corresponding feature representations.Dirty fire have ability to make this flow cheaper by adding several type of errors that have more influence on the models.
\item[why interesting?]
Dirty Fire let the user to check the robustness of machine learning models and with cheap operation cost find the weakness of the models.
\item[why hard?]
recursive task that Dirty Fire check each time the effects of the changes on the accuracy are expensive. \felix{not only accuracy: be more general: cost metric}
\milad{calculate the level of robustness of the model against the error and recursively update that, increase the cost metric and control the cost metric as same as efficiency is the main contribution of this paper.}
\vspace{2mm}
\milad{Motivation example:let's assume there is the dataset with the 165 data points and regarding the binary classification we have got the above result(Fig.1)
as we already know from the figure1 TN=50, TP=100, FP=10, FN=5 ,Accuracy=0.9.Dirty Fire can change the data set with the order to balance of TP+TN would remain the same which is mean we have another dataset with the same accuracy or it let's user to generate the error with fully control on confusion matrix }
\vfill
\begin{figure}
\centering
\includegraphics[width=0.3\textwidth]{img/motivation1.png}
\caption{Motivation Example}
\label{figure:Motivation Example}
\end{figure}
\end{description}
\begin{figure*}[ht!]
\centering
\includegraphics[width=0.9\textwidth]{img/demo.pdf}
\caption{Architecture.}
\label{figure:architecture}
\end{figure*}
|
-- Introducción del condicional en Lean
-- ====================================
-- ----------------------------------------------------
-- Ej. 1. (p. 9) Demostrar que
-- P → P
-- ----------------------------------------------------
import tactic
variable (P : Prop)
-- 1ª demostración
example : P → P :=
assume h : P,
show P, from h
-- 2ª demostración
example : P → P :=
assume : P,
show P, from this
-- 3ª demostración
example : P → P :=
assume : P,
show P, from ‹P›
-- 4ª demostración
example : P → P :=
assume h : P, h
-- 5ª demostración
example : P → P :=
λ h, h
-- 6ª demostración
example : P → P :=
-- by library_search
id
-- 7ª demostración
example : P → P :=
begin
intro h,
exact h,
end
-- 8ª demostración
example : P → P :=
begin
intro,
exact ‹P›,
end
-- 9ª demostración
example : P → P :=
begin
intro h,
assumption,
end
-- 10ª demostración
example : P → P :=
begin
intro,
assumption,
end
-- 11ª demostración
example : P → P :=
-- by hint
by tauto
-- 12ª demostración
example : P → P :=
by finish
-- 13ª demostración
example : P → P :=
by simp
|
/-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.natural_isomorphism
import category_theory.eq_to_hom
import data.sigma.basic
import category_theory.pi.basic
/-!
# Disjoint union of categories
We define the category structure on a sigma-type (disjoint union) of categories.
-/
namespace category_theory
namespace sigma
universes w₁ w₂ w₃ v₁ v₂ u₁ u₂
variables {I : Type w₁} {C : I → Type u₁} [Π i, category.{v₁} (C i)]
/--
The type of morphisms of a disjoint union of categories: for `X : C i` and `Y : C j`, a morphism
`(i, X) ⟶ (j, Y)` if `i = j` is just a morphism `X ⟶ Y`, and if `i ≠ j` there are no such morphisms.
-/
inductive sigma_hom : (Σ i, C i) → (Σ i, C i) → Type (max w₁ v₁ u₁)
| mk : Π {i : I} {X Y : C i}, (X ⟶ Y) → sigma_hom ⟨i, X⟩ ⟨i, Y⟩
namespace sigma_hom
/-- The identity morphism on an object. -/
def id : Π (X : Σ i, C i), sigma_hom X X
| ⟨i, X⟩ := mk (𝟙 _)
instance (X : Σ i, C i) : inhabited (sigma_hom X X) := ⟨id X⟩
/-- Composition of sigma homomorphisms. -/
def comp : Π {X Y Z : Σ i, C i}, sigma_hom X Y → sigma_hom Y Z → sigma_hom X Z
| _ _ _ (mk f) (mk g) := mk (f ≫ g)
instance : category_struct (Σ i, C i) :=
{ hom := sigma_hom,
id := id,
comp := λ X Y Z f g, comp f g }
@[simp]
lemma comp_def (i : I) (X Y Z : C i) (f : X ⟶ Y) (g : Y ⟶ Z) :
comp (mk f) (mk g) = mk (f ≫ g) :=
rfl
lemma assoc : ∀ (X Y Z W : Σ i, C i) (f : X ⟶ Y) (g : Y ⟶ Z) (h : Z ⟶ W), (f ≫ g) ≫ h = f ≫ g ≫ h
| _ _ _ _ (mk f) (mk g) (mk h) := congr_arg mk (category.assoc _ _ _)
lemma id_comp : ∀ (X Y : Σ i, C i) (f : X ⟶ Y), 𝟙 X ≫ f = f
| _ _ (mk f) := congr_arg mk (category.id_comp _)
lemma comp_id : ∀ (X Y : Σ i, C i) (f : X ⟶ Y), f ≫ 𝟙 Y = f
| _ _ (mk f) := congr_arg mk (category.comp_id _)
end sigma_hom
instance sigma : category (Σ i, C i) :=
{ id_comp' := sigma_hom.id_comp,
comp_id' := sigma_hom.comp_id,
assoc' := sigma_hom.assoc }
/-- The inclusion functor into the disjoint union of categories. -/
@[simps map]
def incl (i : I) : C i ⥤ Σ i, C i :=
{ obj := λ X, ⟨i, X⟩,
map := λ X Y, sigma_hom.mk }
@[simp] lemma incl_obj {i : I} (X : C i) : (incl i).obj X = ⟨i, X⟩ := rfl
instance (i : I) : full (incl i : C i ⥤ Σ i, C i) :=
{ preimage := λ X Y ⟨f⟩, f,
witness' := λ X Y ⟨f⟩, rfl }.
instance (i : I) : faithful (incl i : C i ⥤ Σ i, C i) := {}.
section
variables {D : Type u₂} [category.{v₂} D] (F : Π i, C i ⥤ D)
/--
To build a natural transformation over the sigma category, it suffices to specify it restricted to
each subcategory.
-/
def nat_trans {F G : (Σ i, C i) ⥤ D} (h : Π (i : I), incl i ⋙ F ⟶ incl i ⋙ G) : F ⟶ G :=
{ app := λ ⟨j, X⟩, (h j).app X,
naturality' := by { rintro ⟨j, X⟩ ⟨_, _⟩ ⟨_, _, Y, f⟩, apply (h j).naturality } }
@[simp]
/-- (Implementation). An auxiliary definition to build the functor `desc`. -/
def desc_map : ∀ (X Y : Σ i, C i), (X ⟶ Y) → ((F X.1).obj X.2 ⟶ (F Y.1).obj Y.2)
| _ _ (sigma_hom.mk g) := (F _).map g
/--
Given a collection of functors `F i : C i ⥤ D`, we can produce a functor `(Σ i, C i) ⥤ D`.
The produced functor `desc F` satisfies: `incl i ⋙ desc F ≅ F i`, i.e. restricted to just the
subcategory `C i`, `desc F` agrees with `F i`, and it is unique (up to natural isomorphism) with
this property.
This witnesses that the sigma-type is the coproduct in Cat.
-/
@[simps obj]
def desc : (Σ i, C i) ⥤ D :=
{ obj := λ X, (F X.1).obj X.2,
map := λ X Y g, desc_map F X Y g,
map_id' := by { rintro ⟨i, X⟩, apply (F i).map_id },
map_comp' := by { rintro ⟨i, X⟩ ⟨_, Y⟩ ⟨_, Z⟩ ⟨i, _, Y, f⟩ ⟨_, _, Z, g⟩, apply (F i).map_comp } }
@[simp]
lemma desc_map_mk {i : I} (X Y : C i) (f : X ⟶ Y) :
(desc F).map (sigma_hom.mk f) = (F i).map f :=
rfl
/--
This shows that when `desc F` is restricted to just the subcategory `C i`, `desc F` agrees with
`F i`.
-/
-- We hand-generate the simp lemmas about this since they come out cleaner.
def incl_desc (i : I) : incl i ⋙ desc F ≅ F i :=
nat_iso.of_components (λ X, iso.refl _) (by tidy)
@[simp]
lemma incl_desc_hom_app (i : I) (X : C i) :
(incl_desc F i).hom.app X = 𝟙 ((F i).obj X) :=
rfl
@[simp]
lemma incl_desc_inv_app (i : I) (X : C i) :
(incl_desc F i).inv.app X = 𝟙 ((F i).obj X) :=
rfl
/--
If `q` when restricted to each subcategory `C i` agrees with `F i`, then `q` is isomorphic to
`desc F`.
-/
def desc_uniq (q : (Σ i, C i) ⥤ D) (h : Π i, incl i ⋙ q ≅ F i) : q ≅ desc F :=
nat_iso.of_components (λ ⟨i, X⟩, (h i).app X) $
by { rintro ⟨i, X⟩ ⟨_, _⟩ ⟨_, _, Y, f⟩, apply (h i).hom.naturality f }
@[simp]
lemma desc_uniq_hom_app (q : (Σ i, C i) ⥤ D) (h : Π i, incl i ⋙ q ≅ F i) (i : I) (X : C i) :
(desc_uniq F q h).hom.app ⟨i, X⟩ = (h i).hom.app X :=
rfl
@[simp]
lemma desc_uniq_inv_app (q : (Σ i, C i) ⥤ D) (h : Π i, incl i ⋙ q ≅ F i) (i : I) (X : C i) :
(desc_uniq F q h).inv.app ⟨i, X⟩ = (h i).inv.app X :=
rfl
/--
If `q₁` and `q₂` when restricted to each subcategory `C i` agree, then `q₁` and `q₂` are isomorphic.
-/
@[simps]
def nat_iso {q₁ q₂ : (Σ i, C i) ⥤ D} (h : Π i, incl i ⋙ q₁ ≅ incl i ⋙ q₂) :
q₁ ≅ q₂ :=
{ hom := nat_trans (λ i, (h i).hom),
inv := nat_trans (λ i, (h i).inv) }
end
section
variables (C) {J : Type w₂} (g : J → I)
/-- A function `J → I` induces a functor `Σ j, C (g j) ⥤ Σ i, C i`. -/
def map : (Σ (j : J), C (g j)) ⥤ (Σ (i : I), C i) :=
desc (λ j, incl (g j))
@[simp] lemma map_obj (j : J) (X : C (g j)) : (sigma.map C g).obj ⟨j, X⟩ = ⟨g j, X⟩ := rfl
@[simp] lemma map_map {j : J} {X Y : C (g j)} (f : X ⟶ Y) :
(sigma.map C g).map (sigma_hom.mk f) = sigma_hom.mk f :=
rfl
/--
The functor `sigma.map C g` restricted to the subcategory `C j` acts as the inclusion of `g j`.
-/
@[simps]
def incl_comp_map (j : J) : incl j ⋙ map C g ≅ incl (g j) := iso.refl _
variable (I)
/-- The functor `sigma.map` applied to the identity function is just the identity functor. -/
@[simps]
def map_id : map C (id : I → I) ≅ 𝟭 (Σ i, C i) :=
nat_iso (λ i, nat_iso.of_components (λ X, iso.refl _) (by tidy))
variables {I} {K : Type w₃}
/-- The functor `sigma.map` applied to a composition is a composition of functors. -/
@[simps]
def map_comp (f : K → J) (g : J → I) : map (C ∘ g) f ⋙ (map C g : _) ≅ map C (g ∘ f) :=
desc_uniq _ _ $ λ k,
(iso_whisker_right (incl_comp_map (C ∘ g) f k) (map C g : _) : _) ≪≫ incl_comp_map _ _ _
end
namespace functor
variables {C}
variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)]
/--
Assemble an `I`-indexed family of functors into a functor between the sigma types.
-/
def sigma (F : Π i, C i ⥤ D i) : (Σ i, C i) ⥤ (Σ i, D i) :=
desc (λ i, F i ⋙ incl i)
end functor
namespace nat_trans
variables {C}
variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)]
variables {F G : Π i, C i ⥤ D i}
/--
Assemble an `I`-indexed family of natural transformations into a single natural transformation.
-/
def sigma (α : Π i, F i ⟶ G i) : functor.sigma F ⟶ functor.sigma G :=
{ app := λ f, sigma_hom.mk ((α f.1).app _),
naturality' :=
begin
rintro ⟨i, X⟩ ⟨_, _⟩ ⟨_, _, Y, f⟩,
change sigma_hom.mk _ = sigma_hom.mk _,
rw (α i).naturality,
end }
end nat_trans
end sigma
end category_theory
|
SUBROUTINE DIJKL2 (DC,NORBS,NMOS,DIJKL,WIJKL,NMECI)
IMPLICIT DOUBLE PRECISION (A-H,O-Z)
************************************************************************
* RELAXATION OF 2-ELECTRONS INTEGRALS IN M.O BASIS.
*
* INPUT
* DC(NORBS,NMOS) : C.I-ACTIVE M.O DERIVATIVES IN M.O BASIS, IN COLUMN.
* NORBS : TOTAL NUMBER OF M.O.
* NMOS : NUMBER OF C.I-ACTIVE M.O.
* DIJKL(I,J,KL) : <I(1),J(1)|K(2),L(2)> WITH
* I OVER ALL M.O.
* J,KL CANONICAL OVER C.I-ACTIVE M.O.
* NMECI : MAX. SIZE OF WIJKL. (NMOS <= NMECI).
* OUTPUT
* WIJKL(I,J,K,L)= d< I(1),J(1) | K(2),L(2) >
* = <dI,J|K,L> + <I,dJ|K,L> + <I,J|dK,L> + <I,J|K,dL>
* WITH I,J,K,L OVER ALL C.I-ACTIVE M.O.
* WRITTEN BY DANIEL LIOTARD
* (NOTE BY JJPS: AS THIS CODE IS HIGHLY EFFICIENT, NO CHANGES WERE MADE)
************************************************************************
DIMENSION DC(NORBS,*),WIJKL(NMECI,NMECI,NMECI,NMECI)
DIMENSION DIJKL(NORBS,NMOS,*)
LOGICAL LIJ,LKL
C
IJ=0
DO 10 I=1,NMOS
DO 10 J=1,I
IJ=IJ+1
LIJ=I.EQ.J
KL=0
DO 10 K=1,I
IF(K.EQ.I) THEN
LL=J
ELSE
LL=K
ENDIF
DO 10 L=1,LL
KL=KL+1
LKL=K.EQ.L
VAL= DOT(DC(1,I),DIJKL(1,J,KL),NORBS)
IF(LIJ.AND.LKL.AND.J.EQ.K) THEN
VAL=VAL*4.D0
ELSE
IF(LIJ) THEN
VAL=VAL*2.D0
ELSE
VAL=VAL+ DOT(DC(1,J),DIJKL(1,I,KL),NORBS)
ENDIF
VAL2= DOT(DC(1,K),DIJKL(1,L,IJ),NORBS)
IF(LKL) THEN
VAL=VAL+VAL2*2.D0
ELSE
VAL=VAL+VAL2+DOT(DC(1,L),DIJKL(1,K,IJ),NORBS)
ENDIF
ENDIF
WIJKL(I,J,K,L)=VAL
WIJKL(I,J,L,K)=VAL
WIJKL(J,I,K,L)=VAL
WIJKL(J,I,L,K)=VAL
WIJKL(K,L,I,J)=VAL
WIJKL(K,L,J,I)=VAL
WIJKL(L,K,I,J)=VAL
10 WIJKL(L,K,J,I)=VAL
RETURN
END
|
{-# OPTIONS --cubical --safe --postfix-projections #-}
module Data.Dyck.Empty where
open import Prelude
open import Data.Nat using (_+_)
open import Data.Vec.Iterated using (Vec; _∷_; []; foldlN; head)
private
variable
n : ℕ
--------------------------------------------------------------------------------
-- Binary trees: definition and associated functions
--------------------------------------------------------------------------------
data Tree (A : Type a) : Type a where
◇ : Tree A
[_] : A → Tree A
_*_ : Tree A → Tree A → Tree A
--------------------------------------------------------------------------------
-- Programs: definition and associated functions
--------------------------------------------------------------------------------
data Prog (A : Type a) : ℕ → Type a where
halt : Prog A 1
push : A → Prog A (1 + n) → Prog A n
pull : Prog A (1 + n) → Prog A (2 + n)
skip : Prog A (1 + n) → Prog A n
--------------------------------------------------------------------------------
-- Conversion from a Prog to a Tree
--------------------------------------------------------------------------------
prog→tree⊙ : Prog A n → Vec (Tree A) n → Tree A
prog→tree⊙ halt (v ∷ []) = v
prog→tree⊙ (push v is) st = prog→tree⊙ is ([ v ] ∷ st)
prog→tree⊙ (pull is) (t₁ ∷ t₂ ∷ st) = prog→tree⊙ is (t₂ * t₁ ∷ st)
prog→tree⊙ (skip is) st = prog→tree⊙ is (◇ ∷ st)
prog→tree : Prog A zero → Tree A
prog→tree ds = prog→tree⊙ ds []
--------------------------------------------------------------------------------
-- Conversion from a Tree to a Prog
--------------------------------------------------------------------------------
tree→prog⊙ : Tree A → Prog A (suc n) → Prog A n
tree→prog⊙ [ x ] = push x
tree→prog⊙ (xs * ys) = tree→prog⊙ xs ∘ tree→prog⊙ ys ∘ pull
tree→prog⊙ ◇ = skip
tree→prog : Tree A → Prog A zero
tree→prog tr = tree→prog⊙ tr halt
--------------------------------------------------------------------------------
-- Proof of isomorphism
--------------------------------------------------------------------------------
tree→prog→tree⊙ : {is : Prog A (1 + n)} {st : Vec (Tree A) n} (e : Tree A) →
prog→tree⊙ (tree→prog⊙ e is) st ≡ prog→tree⊙ is (e ∷ st)
tree→prog→tree⊙ [ x ] = refl
tree→prog→tree⊙ (xs * ys) = tree→prog→tree⊙ xs ; tree→prog→tree⊙ ys
tree→prog→tree⊙ ◇ = refl
prog→tree→prog⊙ : {st : Vec (Tree A) n} (is : Prog A n) →
tree→prog (prog→tree⊙ is st) ≡ foldlN (Prog A) tree→prog⊙ is st
prog→tree→prog⊙ halt = refl
prog→tree→prog⊙ (push i is) = prog→tree→prog⊙ is
prog→tree→prog⊙ (pull is) = prog→tree→prog⊙ is
prog→tree→prog⊙ (skip is) = prog→tree→prog⊙ is
prog-iso : Prog A zero ⇔ Tree A
prog-iso .fun = prog→tree
prog-iso .inv = tree→prog
prog-iso .rightInv = tree→prog→tree⊙
prog-iso .leftInv = prog→tree→prog⊙
|
[STATEMENT]
lemma bij_betw_imp_funcset: "bij_betw f A B \<Longrightarrow> f \<in> A \<rightarrow> B"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. bij_betw f A B \<Longrightarrow> f \<in> A \<rightarrow> B
[PROOF STEP]
by (auto simp add: bij_betw_def) |
Formal statement is: lemma vector_sub_project_orthogonal: fixes b x :: "'a::euclidean_space" shows "b \<bullet> (x - ((b \<bullet> x) / (b \<bullet> b)) *\<^sub>R b) = 0" Informal statement is: The projection of a vector $x$ onto a vector $b$ is orthogonal to $x$. |
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: gga_exc *)
c09x_mu := 0.0617:
c09x_kappa := 1.245:
c09x_alpha := 0.0483:
c09x_f0 := s -> 1 + c09x_mu*s^2*exp(-c09x_alpha*s^2) + c09x_kappa*(1 - exp(-1/2*c09x_alpha*s^2)):
c09x_f := x -> c09x_f0(X2S*x):
f := (rs, z, xt, xs0, xs1) -> gga_exchange(c09x_f, rs, z, xs0, xs1):
|
function p=v_mos2pesq(m)
%V_MOS2PESQ convert MOS speech quality scores to PESQ p=(m)
%Inputs: m is a matrix of MOS scores
%
%Outputs: p is a matrix, the same size as m, of PESQ scores
%
% The PESQ measure is defined in [2]. The mapping function, defined in [3],
% converts raw PESQ scores (which lie in the range -0.5 to 4.5) onto the
% MOS-LQO (Mean Opinion Score - Listening Quality Objective [2]) scale in the
% range 1 to 5. The MOS scale is defined in [1] as
% 5=Excellent, 4=Good, 3=Fair, 2=Poor, 1=Bad.
%
% Refs: [1] ITU-T. Methods for subjective determination of transmission quality.
% Recommendation P.800, Aug. 1996.
% [2] ITU-T. Mean opinion score (MOS) terminology.
% Recommendation P.800.1, July 2006.
% [2] ITU-T. Perceptual evaluation of speech quality (PESQ), an objective
% method for end-to-end speech quality assessment of narrowband telephone
% networks and speech codecs. Recommendation P.862, Feb. 2001.
% [3] ITU-T. Mapping function for transforming P.862 raw result scores to MOS-LQO.
% Recommendation P.862.1, Nov. 2003.
% Copyright (C) Mike Brookes 2012-2013
% Version: $Id: v_mos2pesq.m 10865 2018-09-21 17:22:45Z dmb $
%
% VOICEBOX is a MATLAB toolbox for speech processing.
% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You can obtain a copy of the GNU General Public License from
% http://www.gnu.org/copyleft/gpl.html or by writing to
% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
persistent a b c d
if isempty(a)
a=0.999;
b=4.999-a;
c=-1.4945;
d=4.6607;
end
if nargout>0
p=(log(b./(m-a)-1)-d)/c;
else
if nargin<1 || isempty(m)
pp=linspace(-0.5,4.5,100);
mm=v_pesq2mos(pp);
else
mm=m;
end
p=v_mos2pesq(mm);
plot(mm,p);
ylabel('PESQ (P.862)');
xlabel('Mean Opimion Score (MOS)');
end
|
State Before: R : Type u
S : Type v
T : Type w
a b✝ : R
n : ℕ
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : IsDomain A
inst✝ : IsDomain B
p : A[X]
f : A →+* B
h : map f p ≠ 0
b : B
⊢ Multiset.count b (Multiset.map (↑f) (roots p)) ≤ Multiset.count b (roots (map f p)) State After: R : Type u
S : Type v
T : Type w
a b✝ : R
n : ℕ
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : IsDomain A
inst✝ : IsDomain B
p : A[X]
f : A →+* B
h : map f p ≠ 0
b : B
⊢ Multiset.count b (Multiset.map (↑f) (roots p)) ≤ rootMultiplicity b (map f p) Tactic: rw [count_roots] State Before: R : Type u
S : Type v
T : Type w
a b✝ : R
n : ℕ
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : IsDomain A
inst✝ : IsDomain B
p : A[X]
f : A →+* B
h : map f p ≠ 0
b : B
⊢ Multiset.count b (Multiset.map (↑f) (roots p)) ≤ rootMultiplicity b (map f p) State After: no goals Tactic: apply count_map_roots h |
Formal statement is: lemma residue_add: assumes "open s" "z \<in> s" and f_holo: "f holomorphic_on s - {z}" and g_holo:"g holomorphic_on s - {z}" shows "residue (\<lambda>z. f z + g z) z= residue f z + residue g z" Informal statement is: If $f$ and $g$ are holomorphic functions on a punctured open set $s - \{z\}$, then the residue of $f + g$ at $z$ is the sum of the residues of $f$ and $g$ at $z$. |
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.multiset.finset_ops
import data.multiset.fold
/-!
# Lattice operations on multisets
-/
namespace multiset
variables {α : Type*}
/-! ### sup -/
section sup
-- can be defined with just `[has_bot α]` where some lemmas hold without requiring `[order_bot α]`
variables [semilattice_sup α] [order_bot α]
/-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/
def sup (s : multiset α) : α := s.fold (⊔) ⊥
@[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ :=
fold_zero _ _
@[simp] lemma sup_cons (a : α) (s : multiset α) :
(a ::ₘ s).sup = a ⊔ s.sup :=
fold_cons_left _ _ _ _
@[simp] lemma sup_singleton {a : α} : ({a} : multiset α).sup = a :=
sup_bot_eq
@[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup :=
eq.trans (by simp [sup]) (fold_add _ _ _ _ _)
lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup :=
sup_le.1 le_rfl _ h
lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup :=
sup_le.2 $ assume b hb, le_sup (h hb)
variables [decidable_eq α]
@[simp] lemma sup_dedup (s : multiset α) : (dedup s).sup = s.sup :=
fold_dedup_idem _ _ _
@[simp] lemma sup_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_add]; simp
@[simp] lemma sup_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_add]; simp
@[simp] lemma sup_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).sup = a ⊔ s.sup :=
by rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_cons]; simp
lemma nodup_sup_iff {α : Type*} [decidable_eq α] {m : multiset (multiset α) } :
m.sup.nodup ↔ ∀ (a : multiset α), a ∈ m → a.nodup :=
begin
apply m.induction_on,
{ simp },
{ intros a s h,
simp [h] }
end
end sup
/-! ### inf -/
section inf
-- can be defined with just `[has_top α]` where some lemmas hold without requiring `[order_top α]`
variables [semilattice_inf α] [order_top α]
/-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/
def inf (s : multiset α) : α := s.fold (⊓) ⊤
@[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ :=
fold_zero _ _
@[simp]
@[simp] lemma inf_singleton {a : α} : ({a} : multiset α).inf = a :=
inf_top_eq
@[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf :=
eq.trans (by simp [inf]) (fold_add _ _ _ _ _)
lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a :=
le_inf.1 le_rfl _ h
lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf :=
le_inf.2 $ assume b hb, inf_le (h hb)
variables [decidable_eq α]
@[simp] lemma inf_dedup (s : multiset α) : (dedup s).inf = s.inf :=
fold_dedup_idem _ _ _
@[simp] lemma inf_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_add]; simp
@[simp] lemma inf_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_add]; simp
@[simp] lemma inf_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).inf = a ⊓ s.inf :=
by rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_cons]; simp
end inf
end multiset
|
-- Andreas, AIM XXIII, 2016-04-23
-- Issue 1944
-- Milestone 2.0: overload projection by fields (does not affect matching)
-- {-# OPTIONS -v tc.lhs.split:20 #-}
record R : Set2 where
field out : Set1
r : R
R.out r = Set
s = r
open R r -- fully applied open
open R
open R s
-- Now out is overloaded. It is both a field and a projection.
-- We can still use it in pattern position (since a field does not make sense here).
ok : R
out ok = Set -- out should be highlighted as projection
|
/-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.algebra.pi
import topology.locally_constant.basic
/-!
# Algebraic structure on locally constant functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file puts algebraic structure (`add_group`, etc)
on the type of locally constant functions.
-/
namespace locally_constant
variables {X Y : Type*} [topological_space X]
@[to_additive] instance [has_one Y] : has_one (locally_constant X Y) :=
{ one := const X 1 }
@[simp, to_additive] lemma coe_one [has_one Y] : ⇑(1 : locally_constant X Y) = (1 : X → Y) := rfl
@[to_additive] lemma one_apply [has_one Y] (x : X) : (1 : locally_constant X Y) x = 1 := rfl
@[to_additive] instance [has_inv Y] : has_inv (locally_constant X Y) :=
{ inv := λ f, ⟨f⁻¹ , f.is_locally_constant.inv⟩ }
@[simp, to_additive] lemma coe_inv [has_inv Y] (f : locally_constant X Y) : ⇑(f⁻¹) = f⁻¹ := rfl
@[to_additive]
@[to_additive] instance [has_mul Y] : has_mul (locally_constant X Y) :=
{ mul := λ f g, ⟨f * g, f.is_locally_constant.mul g.is_locally_constant⟩ }
@[simp, to_additive] lemma coe_mul [has_mul Y] (f g : locally_constant X Y) :
⇑(f * g) = f * g :=
rfl
@[to_additive] lemma mul_apply [has_mul Y] (f g : locally_constant X Y) (x : X) :
(f * g) x = f x * g x := rfl
@[to_additive] instance [mul_one_class Y] : mul_one_class (locally_constant X Y) :=
{ one_mul := by { intros, ext, simp only [mul_apply, one_apply, one_mul] },
mul_one := by { intros, ext, simp only [mul_apply, one_apply, mul_one] },
.. locally_constant.has_one,
.. locally_constant.has_mul }
/-- `coe_fn` is a `monoid_hom`. -/
@[to_additive "`coe_fn` is an `add_monoid_hom`.", simps]
def coe_fn_monoid_hom [mul_one_class Y] : locally_constant X Y →* (X → Y) :=
{ to_fun := coe_fn,
map_one' := rfl,
map_mul' := λ _ _, rfl }
/-- The constant-function embedding, as a multiplicative monoid hom. -/
@[to_additive "The constant-function embedding, as an additive monoid hom.", simps]
def const_monoid_hom [mul_one_class Y] : Y →* locally_constant X Y :=
{ to_fun := const X,
map_one' := rfl,
map_mul' := λ _ _, rfl, }
instance [mul_zero_class Y] : mul_zero_class (locally_constant X Y) :=
{ zero_mul := by { intros, ext, simp only [mul_apply, zero_apply, zero_mul] },
mul_zero := by { intros, ext, simp only [mul_apply, zero_apply, mul_zero] },
.. locally_constant.has_zero,
.. locally_constant.has_mul }
instance [mul_zero_one_class Y] : mul_zero_one_class (locally_constant X Y) :=
{ .. locally_constant.mul_zero_class, .. locally_constant.mul_one_class }
section char_fn
variables (Y) [mul_zero_one_class Y] {U V : set X}
/-- Characteristic functions are locally constant functions taking `x : X` to `1` if `x ∈ U`,
where `U` is a clopen set, and `0` otherwise. -/
noncomputable def char_fn (hU : is_clopen U) : locally_constant X Y := indicator 1 hU
lemma coe_char_fn (hU : is_clopen U) : (char_fn Y hU : X → Y) = set.indicator U 1 :=
rfl
lemma char_fn_eq_one [nontrivial Y] (x : X) (hU : is_clopen U) :
char_fn Y hU x = (1 : Y) ↔ x ∈ U := set.indicator_eq_one_iff_mem _
lemma char_fn_eq_zero [nontrivial Y] (x : X) (hU : is_clopen U) :
char_fn Y hU x = (0 : Y) ↔ x ∉ U := set.indicator_eq_zero_iff_not_mem _
lemma char_fn_inj [nontrivial Y] (hU : is_clopen U) (hV : is_clopen V)
(h : char_fn Y hU = char_fn Y hV) : U = V :=
set.indicator_one_inj Y $ coe_inj.mpr h
end char_fn
@[to_additive] instance [has_div Y] : has_div (locally_constant X Y) :=
{ div := λ f g, ⟨f / g, f.is_locally_constant.div g.is_locally_constant⟩ }
@[to_additive] lemma coe_div [has_div Y] (f g : locally_constant X Y) :
⇑(f / g) = f / g := rfl
@[to_additive] lemma div_apply [has_div Y] (f g : locally_constant X Y) (x : X) :
(f / g) x = f x / g x := rfl
@[to_additive] instance [semigroup Y] : semigroup (locally_constant X Y) :=
{ mul_assoc := by { intros, ext, simp only [mul_apply, mul_assoc] },
.. locally_constant.has_mul }
instance [semigroup_with_zero Y] : semigroup_with_zero (locally_constant X Y) :=
{ .. locally_constant.mul_zero_class,
.. locally_constant.semigroup }
@[to_additive] instance [comm_semigroup Y] : comm_semigroup (locally_constant X Y) :=
{ mul_comm := by { intros, ext, simp only [mul_apply, mul_comm] },
.. locally_constant.semigroup }
@[to_additive] instance [monoid Y] : monoid (locally_constant X Y) :=
{ mul := (*),
.. locally_constant.semigroup, .. locally_constant.mul_one_class }
instance [add_monoid_with_one Y] : add_monoid_with_one (locally_constant X Y) :=
{ nat_cast := λ n, const X n,
nat_cast_zero := by ext; simp [nat.cast],
nat_cast_succ := λ _, by ext; simp [nat.cast],
.. locally_constant.add_monoid, .. locally_constant.has_one }
@[to_additive] instance [comm_monoid Y] : comm_monoid (locally_constant X Y) :=
{ .. locally_constant.comm_semigroup, .. locally_constant.monoid }
@[to_additive] instance [group Y] : group (locally_constant X Y) :=
{ mul_left_inv := by { intros, ext, simp only [mul_apply, inv_apply, one_apply, mul_left_inv] },
div_eq_mul_inv := by { intros, ext, simp only [mul_apply, inv_apply, div_apply, div_eq_mul_inv] },
.. locally_constant.monoid, .. locally_constant.has_inv, .. locally_constant.has_div }
@[to_additive] instance [comm_group Y] : comm_group (locally_constant X Y) :=
{ .. locally_constant.comm_monoid, .. locally_constant.group }
instance [distrib Y] : distrib (locally_constant X Y) :=
{ left_distrib := by { intros, ext, simp only [mul_apply, add_apply, mul_add] },
right_distrib := by { intros, ext, simp only [mul_apply, add_apply, add_mul] },
.. locally_constant.has_add, .. locally_constant.has_mul }
instance [non_unital_non_assoc_semiring Y] : non_unital_non_assoc_semiring (locally_constant X Y) :=
{ .. locally_constant.add_comm_monoid, .. locally_constant.has_mul,
.. locally_constant.distrib, .. locally_constant.mul_zero_class }
instance [non_unital_semiring Y] : non_unital_semiring (locally_constant X Y) :=
{ .. locally_constant.semigroup, .. locally_constant.non_unital_non_assoc_semiring }
instance [non_assoc_semiring Y] : non_assoc_semiring (locally_constant X Y) :=
{ .. locally_constant.mul_one_class, .. locally_constant.add_monoid_with_one,
.. locally_constant.non_unital_non_assoc_semiring }
/-- The constant-function embedding, as a ring hom. -/
@[simps] def const_ring_hom [non_assoc_semiring Y] : Y →+* locally_constant X Y :=
{ to_fun := const X,
.. const_monoid_hom,
.. const_add_monoid_hom, }
instance [semiring Y] : semiring (locally_constant X Y) :=
{ .. locally_constant.non_assoc_semiring, .. locally_constant.monoid }
instance [non_unital_comm_semiring Y] : non_unital_comm_semiring (locally_constant X Y) :=
{ .. locally_constant.non_unital_semiring, .. locally_constant.comm_semigroup }
instance [comm_semiring Y] : comm_semiring (locally_constant X Y) :=
{ .. locally_constant.semiring, .. locally_constant.comm_monoid }
instance [non_unital_non_assoc_ring Y] : non_unital_non_assoc_ring (locally_constant X Y) :=
{ .. locally_constant.add_comm_group, .. locally_constant.has_mul,
.. locally_constant.distrib, .. locally_constant.mul_zero_class }
instance [non_unital_ring Y] : non_unital_ring (locally_constant X Y) :=
{ .. locally_constant.semigroup, .. locally_constant.non_unital_non_assoc_ring }
instance [non_assoc_ring Y] : non_assoc_ring (locally_constant X Y) :=
{ .. locally_constant.mul_one_class, .. locally_constant.non_unital_non_assoc_ring }
instance [ring Y] : ring (locally_constant X Y) :=
{ .. locally_constant.semiring, .. locally_constant.add_comm_group }
instance [non_unital_comm_ring Y] : non_unital_comm_ring (locally_constant X Y) :=
{ .. locally_constant.non_unital_comm_semiring, .. locally_constant.non_unital_ring }
instance [comm_ring Y] : comm_ring (locally_constant X Y) :=
{ .. locally_constant.comm_semiring, .. locally_constant.ring }
variables {R : Type*}
instance [has_smul R Y] : has_smul R (locally_constant X Y) :=
{ smul := λ r f,
{ to_fun := r • f,
is_locally_constant := (f.is_locally_constant.comp ((•) r) : _), } }
@[simp] lemma coe_smul [has_smul R Y] (r : R) (f : locally_constant X Y) : ⇑(r • f) = r • f := rfl
lemma smul_apply [has_smul R Y] (r : R) (f : locally_constant X Y) (x : X) :
(r • f) x = r • (f x) :=
rfl
instance [monoid R] [mul_action R Y] : mul_action R (locally_constant X Y) :=
function.injective.mul_action _ coe_injective (λ _ _, rfl)
instance [monoid R] [add_monoid Y] [distrib_mul_action R Y] :
distrib_mul_action R (locally_constant X Y) :=
function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective (λ _ _, rfl)
instance [semiring R] [add_comm_monoid Y] [module R Y] : module R (locally_constant X Y) :=
function.injective.module R coe_fn_add_monoid_hom coe_injective (λ _ _, rfl)
section algebra
variables [comm_semiring R] [semiring Y] [algebra R Y]
instance : algebra R (locally_constant X Y) :=
{ to_ring_hom := const_ring_hom.comp $ algebra_map R Y,
commutes' := by { intros, ext, exact algebra.commutes' _ _, },
smul_def' := by { intros, ext, exact algebra.smul_def' _ _, }, }
@[simp] lemma coe_algebra_map (r : R) :
⇑(algebra_map R (locally_constant X Y) r) = algebra_map R (X → Y) r :=
rfl
end algebra
end locally_constant
|
Suppose $f$ is a holomorphic function on an open set $S$, and $\xi \in S$. If $f$ has a zero of order $n$ at $\xi$, then there exists a holomorphic function $g$ and a positive real number $r$ such that for all $w \in B(\xi, r)$, we have $f(w) - f(\xi) = (w - \xi)^n g(w)$ and $g(w) \neq 0$. |
/-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import algebra.ring.prod
import group_theory.submonoid
import data.equiv.ring
/-!
# Bundled subsemirings
We define bundled subsemirings and some standard constructions: `complete_lattice` structure,
`subtype` and `inclusion` ring homomorphisms, subsemiring `map`, `comap` and range (`srange`) of
a `ring_hom` etc.
-/
open_locale big_operators
universes u v w
variables {R : Type u} {S : Type v} {T : Type w} [semiring R] [semiring S] [semiring T]
(M : submonoid R)
set_option old_structure_cmd true
/-- A subsemiring of a semiring `R` is a subset `s` that is both a multiplicative and an additive
submonoid. -/
structure subsemiring (R : Type u) [semiring R] extends submonoid R, add_submonoid R
/-- Reinterpret a `subsemiring` as a `submonoid`. -/
add_decl_doc subsemiring.to_submonoid
/-- Reinterpret a `subsemiring` as an `add_submonoid`. -/
add_decl_doc subsemiring.to_add_submonoid
namespace subsemiring
instance : set_like (subsemiring R) R :=
⟨subsemiring.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp]
lemma mem_carrier {s : subsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
/-- Two subsemirings are equal if they have the same elements. -/
@[ext] theorem ext {S T : subsemiring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
/-- Copy of a subsemiring with a new `carrier` equal to the old one. Useful to fix definitional
equalities.-/
protected def copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : subsemiring R :=
{ carrier := s,
..S.to_add_submonoid.copy s hs,
..S.to_submonoid.copy s hs }
lemma to_submonoid_injective : function.injective (to_submonoid : subsemiring R → submonoid R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subsemiring R → submonoid R) :=
λ _ _, id
@[mono] lemma to_submonoid_mono : monotone (to_submonoid : subsemiring R → submonoid R) :=
to_submonoid_strict_mono.monotone
lemma to_add_submonoid_injective :
function.injective (to_add_submonoid : subsemiring R → add_submonoid R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono] lemma to_add_submonoid_strict_mono :
strict_mono (to_add_submonoid : subsemiring R → add_submonoid R) := λ _ _, id
@[mono]
lemma to_add_submonoid_mono : monotone (to_add_submonoid : subsemiring R → add_submonoid R) :=
to_add_submonoid_strict_mono.monotone
/-- Construct a `subsemiring R` from a set `s`, a submonoid `sm`, and an additive
submonoid `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/
protected def mk' (s : set R) (sm : submonoid R) (hm : ↑sm = s)
(sa : add_submonoid R) (ha : ↑sa = s) :
subsemiring R :=
{ carrier := s,
zero_mem' := ha ▸ sa.zero_mem,
one_mem' := hm ▸ sm.one_mem,
add_mem' := λ x y, by simpa only [← ha] using sa.add_mem,
mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem }
@[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa = s) :
(subsemiring.mk' s sm hm sa ha : set R) = s := rfl
@[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa = s) {x : R} :
x ∈ subsemiring.mk' s sm hm sa ha ↔ x ∈ s :=
iff.rfl
@[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa = s) :
(subsemiring.mk' s sm hm sa ha).to_submonoid = sm :=
set_like.coe_injective hm.symm
@[simp] lemma mk'_to_add_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa =s) :
(subsemiring.mk' s sm hm sa ha).to_add_submonoid = sa :=
set_like.coe_injective ha.symm
end subsemiring
namespace subsemiring
variables (s : subsemiring R)
/-- A subsemiring contains the semiring's 1. -/
theorem one_mem : (1 : R) ∈ s := s.one_mem'
/-- A subsemiring contains the semiring's 0. -/
theorem zero_mem : (0 : R) ∈ s := s.zero_mem'
/-- A subsemiring is closed under multiplication. -/
theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem'
/-- A subsemiring is closed under addition. -/
theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem'
/-- Product of a list of elements in a `subsemiring` is in the `subsemiring`. -/
lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s :=
s.to_submonoid.list_prod_mem
/-- Sum of a list of elements in a `subsemiring` is in the `subsemiring`. -/
lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s :=
s.to_add_submonoid.list_sum_mem
/-- Product of a multiset of elements in a `subsemiring` of a `comm_semiring`
is in the `subsemiring`. -/
lemma multiset_prod_mem {R} [comm_semiring R] (s : subsemiring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.prod ∈ s :=
s.to_submonoid.multiset_prod_mem m
/-- Sum of a multiset of elements in a `subsemiring` of a `semiring` is
in the `add_subsemiring`. -/
lemma multiset_sum_mem {R} [semiring R] (s : subsemiring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.sum ∈ s :=
s.to_add_submonoid.multiset_sum_mem m
/-- Product of elements of a subsemiring of a `comm_semiring` indexed by a `finset` is in the
subsemiring. -/
lemma prod_mem {R : Type*} [comm_semiring R] (s : subsemiring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∏ i in t, f i ∈ s :=
s.to_submonoid.prod_mem h
/-- Sum of elements in an `subsemiring` of an `semiring` indexed by a `finset`
is in the `add_subsemiring`. -/
lemma sum_mem {R : Type*} [semiring R] (s : subsemiring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∑ i in t, f i ∈ s :=
s.to_add_submonoid.sum_mem h
lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n
lemma nsmul_mem {x : R} (hx : x ∈ s) (n : ℕ) :
n • x ∈ s := s.to_add_submonoid.nsmul_mem hx n
lemma coe_nat_mem (n : ℕ) : (n : R) ∈ s :=
by simp only [← nsmul_one, nsmul_mem, one_mem]
/-- A subsemiring of a semiring inherits a semiring structure -/
instance to_semiring : semiring s :=
{ mul_zero := λ x, subtype.eq $ mul_zero x,
zero_mul := λ x, subtype.eq $ zero_mul x,
right_distrib := λ x y z, subtype.eq $ right_distrib x y z,
left_distrib := λ x y z, subtype.eq $ left_distrib x y z,
.. s.to_submonoid.to_monoid, .. s.to_add_submonoid.to_add_comm_monoid }
@[simp, norm_cast] lemma coe_one : ((1 : s) : R) = (1 : R) := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = (0 : R) := rfl
@[simp, norm_cast] lemma coe_add (x y : s) : ((x + y : s) : R) = (x + y : R) := rfl
@[simp, norm_cast] lemma coe_mul (x y : s) : ((x * y : s) : R) = (x * y : R) := rfl
@[simp, norm_cast] lemma coe_pow (x : s) (n : ℕ) : ((x^n : s) : R) = (x^n : R) :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
instance nontrivial [nontrivial R] : nontrivial s :=
nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H)
instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h,
or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h)
(λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) }
/-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/
instance to_comm_semiring {R} [comm_semiring R] (s : subsemiring R) : comm_semiring s :=
{ mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..s.to_semiring}
/-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/
def subtype : s →+* R :=
{ to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_submonoid.subtype }
@[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl
/-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/
instance to_ordered_semiring {R} [ordered_semiring R] (s : subsemiring R) : ordered_semiring s :=
subtype.coe_injective.ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/
instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] (s : subsemiring R) :
ordered_comm_semiring s :=
subtype.coe_injective.ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/
instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] (s : subsemiring R) :
linear_ordered_semiring s :=
subtype.coe_injective.linear_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl)
/-! Note: currently, there is no `linear_ordered_comm_semiring`. -/
@[simp] lemma mem_to_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_submonoid (s : subsemiring R) : (s.to_submonoid : set R) = s := rfl
@[simp] lemma mem_to_add_submonoid {s : subsemiring R} {x : R} :
x ∈ s.to_add_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_add_submonoid (s : subsemiring R) : (s.to_add_submonoid : set R) = s := rfl
/-- The subsemiring `R` of the semiring `R`. -/
instance : has_top (subsemiring R) :=
⟨{ .. (⊤ : submonoid R), .. (⊤ : add_submonoid R) }⟩
@[simp] lemma mem_top (x : R) : x ∈ (⊤ : subsemiring R) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : subsemiring R) : set R) = set.univ := rfl
/-- The preimage of a subsemiring along a ring homomorphism is a subsemiring. -/
def comap (f : R →+* S) (s : subsemiring S) : subsemiring R :=
{ carrier := f ⁻¹' s,
.. s.to_submonoid.comap (f : R →* S), .. s.to_add_submonoid.comap (f : R →+ S) }
@[simp] lemma coe_comap (s : subsemiring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl
@[simp]
lemma mem_comap {s : subsemiring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl
lemma comap_comap (s : subsemiring T) (g : S →+* T) (f : R →+* S) :
(s.comap g).comap f = s.comap (g.comp f) :=
rfl
/-- The image of a subsemiring along a ring homomorphism is a subsemiring. -/
def map (f : R →+* S) (s : subsemiring R) : subsemiring S :=
{ carrier := f '' s,
.. s.to_submonoid.map (f : R →* S), .. s.to_add_submonoid.map (f : R →+ S) }
@[simp] lemma coe_map (f : R →+* S) (s : subsemiring R) : (s.map f : set S) = f '' s := rfl
@[simp] lemma mem_map {f : R →+* S} {s : subsemiring R} {y : S} :
y ∈ s.map f ↔ ∃ x ∈ s, f x = y :=
set.mem_image_iff_bex
lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) :=
set_like.coe_injective $ set.image_image _ _ _
lemma map_le_iff_le_comap {f : R →+* S} {s : subsemiring R} {t : subsemiring S} :
s.map f ≤ t ↔ s ≤ t.comap f :=
set.image_subset_iff
lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
end subsemiring
namespace ring_hom
variables (g : S →+* T) (f : R →+* S)
/-- The range of a ring homomorphism is a subsemiring. See Note [range copy pattern]. -/
def srange : subsemiring S :=
((⊤ : subsemiring R).map f).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_srange : (f.srange : set S) = set.range f := rfl
@[simp] lemma mem_srange {f : R →+* S} {y : S} : y ∈ f.srange ↔ ∃ x, f x = y :=
iff.rfl
lemma srange_eq_map (f : R →+* S) : f.srange = (⊤ : subsemiring R).map f :=
by { ext, simp }
lemma mem_srange_self (f : R →+* S) (x : R) : f x ∈ f.srange :=
mem_srange.mpr ⟨x, rfl⟩
lemma map_srange : f.srange.map g = (g.comp f).srange :=
by simpa only [srange_eq_map] using (⊤ : subsemiring R).map_map g f
end ring_hom
namespace subsemiring
instance : has_bot (subsemiring R) := ⟨(nat.cast_ring_hom R).srange⟩
instance : inhabited (subsemiring R) := ⟨⊥⟩
lemma coe_bot : ((⊥ : subsemiring R) : set R) = set.range (coe : ℕ → R) :=
(nat.cast_ring_hom R).coe_srange
lemma mem_bot {x : R} : x ∈ (⊥ : subsemiring R) ↔ ∃ n : ℕ, ↑n=x := ring_hom.mem_srange
/-- The inf of two subsemirings is their intersection. -/
instance : has_inf (subsemiring R) :=
⟨λ s t,
{ carrier := s ∩ t,
.. s.to_submonoid ⊓ t.to_submonoid,
.. s.to_add_submonoid ⊓ t.to_add_submonoid }⟩
@[simp] lemma coe_inf (p p' : subsemiring R) : ((p ⊓ p' : subsemiring R) : set R) = p ∩ p' := rfl
@[simp] lemma mem_inf {p p' : subsemiring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
instance : has_Inf (subsemiring R) :=
⟨λ s, subsemiring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subsemiring.to_submonoid t) (by simp)
(⨅ t ∈ s, subsemiring.to_add_submonoid t) (by simp)⟩
@[simp, norm_cast] lemma coe_Inf (S : set (subsemiring R)) :
((Inf S : subsemiring R) : set R) = ⋂ s ∈ S, ↑s := rfl
lemma mem_Inf {S : set (subsemiring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff
@[simp] lemma Inf_to_submonoid (s : set (subsemiring R)) :
(Inf s).to_submonoid = ⨅ t ∈ s, subsemiring.to_submonoid t :=
mk'_to_submonoid _ _
@[simp] lemma Inf_to_add_submonoid (s : set (subsemiring R)) :
(Inf s).to_add_submonoid = ⨅ t ∈ s, subsemiring.to_add_submonoid t :=
mk'_to_add_submonoid _ _
/-- Subsemirings of a semiring form a complete lattice. -/
instance : complete_lattice (subsemiring R) :=
{ bot := (⊥),
bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_nat_mem n,
top := (⊤),
le_top := λ s x hx, trivial,
inf := (⊓),
inf_le_left := λ s t x, and.left,
inf_le_right := λ s t x, and.right,
le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩,
.. complete_lattice_of_Inf (subsemiring R)
(λ s, is_glb.of_image (λ s t,
show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)}
lemma eq_top_iff' (A : subsemiring R) : A = ⊤ ↔ ∀ x : R, x ∈ A :=
eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩
/-- The `subsemiring` generated by a set. -/
def closure (s : set R) : subsemiring R := Inf {S | s ⊆ S}
lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subsemiring R, s ⊆ S → x ∈ S :=
mem_Inf
/-- The subsemiring generated by a set includes the set. -/
@[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx
/-- A subsemiring `S` includes `closure s` if and only if it includes `s`. -/
@[simp]
lemma closure_le {s : set R} {t : subsemiring R} : closure s ≤ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, λ h, Inf_le h⟩
/-- Subsemiring closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ set.subset.trans h subset_closure
lemma closure_eq_of_le {s : set R} {t : subsemiring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) :
closure s = t :=
le_antisymm (closure_le.2 h₁) h₂
end subsemiring
namespace submonoid
/-- The additive closure of a submonoid is a subsemiring. -/
def subsemiring_closure (M : submonoid R) : subsemiring R :=
{ one_mem' := add_submonoid.mem_closure.mpr (λ y hy, hy M.one_mem),
mul_mem' := λ x y, M.mul_mem_add_closure,
..add_submonoid.closure (M : set R)}
lemma subsemiring_closure_coe :
(M.subsemiring_closure : set R) = add_submonoid.closure (M : set R) := rfl
lemma subsemiring_closure_to_add_submonoid :
M.subsemiring_closure.to_add_submonoid = add_submonoid.closure (M : set R) := rfl
/-- The `subsemiring` generated by a multiplicative submonoid coincides with the
`subsemiring.closure` of the submonoid itself . -/
lemma subsemiring_closure_eq_closure : M.subsemiring_closure = subsemiring.closure (M : set R) :=
begin
ext,
refine ⟨λ hx, _, λ hx, (subsemiring.mem_closure.mp hx) M.subsemiring_closure (λ s sM, _)⟩;
rintros - ⟨H1, rfl⟩;
rintros - ⟨H2, rfl⟩,
{ exact add_submonoid.mem_closure.mp hx H1.to_add_submonoid H2 },
{ exact H2 sM }
end
end submonoid
namespace subsemiring
@[simp]
lemma closure_submonoid_closure (s : set R) : closure ↑(submonoid.closure s) = closure s :=
le_antisymm
(closure_le.mpr (λ y hy, (submonoid.mem_closure.mp hy) (closure s).to_submonoid subset_closure))
(closure_mono (submonoid.subset_closure))
/-- The elements of the subsemiring closure of `M` are exactly the elements of the additive closure
of a multiplicative submonoid `M`. -/
lemma coe_closure_eq (s : set R) :
(closure s : set R) = add_submonoid.closure (submonoid.closure s : set R) :=
by simp [← submonoid.subsemiring_closure_to_add_submonoid, submonoid.subsemiring_closure_eq_closure]
lemma mem_closure_iff {s : set R} {x} :
x ∈ closure s ↔ x ∈ add_submonoid.closure (submonoid.closure s : set R) :=
set.ext_iff.mp (coe_closure_eq s) x
@[simp]
lemma closure_add_submonoid_closure {s : set R} : closure ↑(add_submonoid.closure s) = closure s :=
begin
ext x,
refine ⟨λ hx, _, λ hx, closure_mono add_submonoid.subset_closure hx⟩,
rintros - ⟨H, rfl⟩,
rintros - ⟨J, rfl⟩,
refine (add_submonoid.mem_closure.mp (mem_closure_iff.mp hx)) H.to_add_submonoid (λ y hy, _),
refine (submonoid.mem_closure.mp hy) H.to_submonoid (λ z hz, _),
exact (add_submonoid.mem_closure.mp hz) H.to_add_submonoid (λ w hw, J hw),
end
/-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements
of `s`, and is preserved under addition and multiplication, then `p` holds for all elements
of the closure of `s`. -/
@[elab_as_eliminator]
lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1)
(Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd⟩).2 Hs h
lemma mem_closure_iff_exists_list {s : set R} {x} : x ∈ closure s ↔
∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s) ∧ (L.map list.prod).sum = x :=
⟨λ hx, add_submonoid.closure_induction (mem_closure_iff.1 hx)
(λ x hx, suffices ∃ t : list R, (∀ y ∈ t, y ∈ s) ∧ t.prod = x,
from let ⟨t, ht1, ht2⟩ := this in ⟨[t], list.forall_mem_singleton.2 ht1,
by rw [list.map_singleton, list.sum_singleton, ht2]⟩,
submonoid.closure_induction hx
(λ x hx, ⟨[x], list.forall_mem_singleton.2 hx, one_mul x⟩)
⟨[], list.forall_mem_nil _, rfl⟩
(λ x y ⟨t, ht1, ht2⟩ ⟨u, hu1, hu2⟩, ⟨t ++ u, list.forall_mem_append.2 ⟨ht1, hu1⟩,
by rw [list.prod_append, ht2, hu2]⟩))
⟨[], list.forall_mem_nil _, rfl⟩
(λ x y ⟨L, HL1, HL2⟩ ⟨M, HM1, HM2⟩, ⟨L ++ M, list.forall_mem_append.2 ⟨HL1, HM1⟩,
by rw [list.map_append, list.sum_append, HL2, HM2]⟩),
λ ⟨L, HL1, HL2⟩, HL2 ▸ list_sum_mem _ (λ r hr, let ⟨t, ht1, ht2⟩ := list.mem_map.1 hr in
ht2 ▸ list_prod_mem _ (λ y hy, subset_closure $ HL1 t ht1 y hy))⟩
variable (R)
/-- `closure` forms a Galois insertion with the coercion to set. -/
protected def gi : galois_insertion (@closure R _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {R}
/-- Closure of a subsemiring `S` equals `S`. -/
lemma closure_eq (s : subsemiring R) : closure (s : set R) = s := (subsemiring.gi R).l_u_eq s
@[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subsemiring.gi R).gc.l_bot
@[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤
lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t :=
(subsemiring.gi R).gc.l_sup
lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subsemiring.gi R).gc.l_supr
lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t :=
(subsemiring.gi R).gc.l_Sup
lemma map_sup (s t : subsemiring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subsemiring R) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : subsemiring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f :=
(gc_map_comap f).u_inf
lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subsemiring S) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp] lemma map_bot (f : R →+* S) : (⊥ : subsemiring R).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma comap_top (f : R →+* S) : (⊤ : subsemiring S).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- Given `subsemiring`s `s`, `t` of semirings `R`, `S` respectively, `s.prod t` is `s × t`
as a subsemiring of `R × S`. -/
def prod (s : subsemiring R) (t : subsemiring S) : subsemiring (R × S) :=
{ carrier := (s : set R).prod t,
.. s.to_submonoid.prod t.to_submonoid, .. s.to_add_submonoid.prod t.to_add_submonoid}
@[norm_cast]
lemma coe_prod (s : subsemiring R) (t : subsemiring S) :
(s.prod t : set (R × S)) = (s : set R).prod (t : set S) :=
rfl
lemma mem_prod {s : subsemiring R} {t : subsemiring S} {p : R × S} :
p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[mono] lemma prod_mono ⦃s₁ s₂ : subsemiring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subsemiring S⦄
(ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ :=
set.prod_mono hs ht
lemma prod_mono_right (s : subsemiring R) : monotone (λ t : subsemiring S, s.prod t) :=
prod_mono (le_refl s)
lemma prod_mono_left (t : subsemiring S) : monotone (λ s : subsemiring R, s.prod t) :=
λ s₁ s₂ hs, prod_mono hs (le_refl t)
lemma prod_top (s : subsemiring R) :
s.prod (⊤ : subsemiring S) = s.comap (ring_hom.fst R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
lemma top_prod (s : subsemiring S) :
(⊤ : subsemiring R).prod s = s.comap (ring_hom.snd R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp]
lemma top_prod_top : (⊤ : subsemiring R).prod (⊤ : subsemiring S) = ⊤ :=
(top_prod _).trans $ comap_top _
/-- Product of subsemirings is isomorphic to their product as monoids. -/
def prod_equiv (s : subsemiring R) (t : subsemiring S) : s.prod t ≃+* s × t :=
{ map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t }
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S)
{x : R} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩,
let U : subsemiring R := subsemiring.mk' (⋃ i, (S i : set R))
(⨆ i, (S i).to_submonoid) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id))
(⨆ i, (S i).to_add_submonoid) (add_submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)),
suffices : (⨆ i, S i) ≤ U, by simpa using @this x,
exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩),
end
lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) :
((⨆ i, S i : subsemiring R) : set R) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
lemma mem_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : R} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
lemma coe_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set R) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
end subsemiring
namespace ring_hom
variables [semiring T] {s : subsemiring R}
open subsemiring
/-- Restriction of a ring homomorphism to a subsemiring of the domain. -/
def srestrict (f : R →+* S) (s : subsemiring R) : s →+* S := f.comp s.subtype
@[simp] lemma srestrict_apply (f : R →+* S) (x : s) : f.srestrict s x = f x := rfl
/-- Restriction of a ring homomorphism to a subsemiring of the codomain. -/
def cod_srestrict (f : R →+* S) (s : subsemiring S) (h : ∀ x, f x ∈ s) : R →+* s :=
{ to_fun := λ n, ⟨f n, h n⟩,
.. (f : R →* S).cod_mrestrict s.to_submonoid h,
.. (f : R →+ S).cod_mrestrict s.to_add_submonoid h }
/-- Restriction of a ring homomorphism to its range interpreted as a subsemiring.
This is the bundled version of `set.range_factorization`. -/
def srange_restrict (f : R →+* S) : R →+* f.srange :=
f.cod_srestrict f.srange f.mem_srange_self
@[simp] lemma coe_srange_restrict (f : R →+* S) (x : R) :
(f.srange_restrict x : S) = f x :=
rfl
lemma srange_restrict_surjective (f : R →+* S) : function.surjective f.srange_restrict :=
λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_srange.mp hy in ⟨x, subtype.ext hx⟩
lemma srange_top_iff_surjective {f : R →+* S} :
f.srange = (⊤ : subsemiring S) ↔ function.surjective f :=
set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective
/-- The range of a surjective ring homomorphism is the whole of the codomain. -/
lemma srange_top_of_surjective (f : R →+* S) (hf : function.surjective f) :
f.srange = (⊤ : subsemiring S) :=
srange_top_iff_surjective.2 hf
/-- The subsemiring of elements `x : R` such that `f x = g x` -/
def eq_slocus (f g : R →+* S) : subsemiring R :=
{ carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_mlocus g }
/-- If two ring homomorphisms are equal on a set, then they are equal on its subsemiring closure. -/
lemma eq_on_sclosure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_slocus g, from closure_le.2 h
lemma eq_of_eq_on_stop {f g : R →+* S} (h : set.eq_on f g (⊤ : subsemiring R)) :
f = g :=
ext $ λ x, h trivial
lemma eq_of_eq_on_sdense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_stop $ hs ▸ eq_on_sclosure h
lemma sclosure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a ring homomorphism of the subsemiring generated by a set equals
the subsemiring generated by the image of the set. -/
lemma map_sclosure (f : R →+* S) (s : set R) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(sclosure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
end ring_hom
namespace subsemiring
open ring_hom
/-- The ring homomorphism associated to an inclusion of subsemirings. -/
def inclusion {S T : subsemiring R} (h : S ≤ T) : S →* T :=
S.subtype.cod_srestrict _ (λ x, h x.2)
@[simp] lemma srange_subtype (s : subsemiring R) : s.subtype.srange = s :=
set_like.coe_injective $ (coe_srange _).trans subtype.range_coe
@[simp]
lemma range_fst : (fst R S).srange = ⊤ :=
(fst R S).srange_top_of_surjective $ prod.fst_surjective
@[simp]
lemma range_snd : (snd R S).srange = ⊤ :=
(snd R S).srange_top_of_surjective $ prod.snd_surjective
@[simp]
lemma prod_bot_sup_bot_prod (s : subsemiring R) (t : subsemiring S) :
(s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t :=
le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $
assume p hp, prod.fst_mul_snd p ▸ mul_mem _
((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩)
((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩)
end subsemiring
namespace ring_equiv
variables {s t : subsemiring R}
/-- Makes the identity isomorphism from a proof two subsemirings of a multiplicative
monoid are equal. -/
def subsemiring_congr (h : s = t) : s ≃+* t :=
{ map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h }
/-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its
`ring_hom.srange`. -/
def sof_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) :
R ≃+* f.srange :=
{ to_fun := λ x, f.srange_restrict x,
inv_fun := λ x, (g ∘ f.srange.subtype) x,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := ring_hom.mem_srange.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
..f.srange_restrict }
@[simp] lemma sof_left_inverse_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) :
↑(sof_left_inverse h x) = f x := rfl
@[simp] lemma sof_left_inverse_symm_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.srange) :
(sof_left_inverse h).symm x = g x := rfl
end ring_equiv
|
lemma dim_eq_hyperplane: fixes S :: "'n::euclidean_space set" shows "dim S = DIM('n) - 1 \<longleftrightarrow> (\<exists>a. a \<noteq> 0 \<and> span S = {x. a \<bullet> x = 0})" |
State Before: α : Type u_1
β : Type u_2
E : Type ?u.78801
inst✝³ : TopologicalSpace α
inst✝² : CompactSpace α
inst✝¹ : MetricSpace β
inst✝ : NormedAddCommGroup E
f g : C(α, β)
C : ℝ
C0 : 0 < C
⊢ dist f g < C ↔ ∀ (x : α), dist (↑f x) (↑g x) < C State After: α : Type u_1
β : Type u_2
E : Type ?u.78801
inst✝³ : TopologicalSpace α
inst✝² : CompactSpace α
inst✝¹ : MetricSpace β
inst✝ : NormedAddCommGroup E
f g : C(α, β)
C : ℝ
C0 : 0 < C
⊢ (∀ (x : α), dist (↑(mkOfCompact f) x) (↑(mkOfCompact g) x) < C) ↔ ∀ (x : α), dist (↑f x) (↑g x) < C Tactic: rw [← dist_mkOfCompact, dist_lt_iff_of_compact C0] State Before: α : Type u_1
β : Type u_2
E : Type ?u.78801
inst✝³ : TopologicalSpace α
inst✝² : CompactSpace α
inst✝¹ : MetricSpace β
inst✝ : NormedAddCommGroup E
f g : C(α, β)
C : ℝ
C0 : 0 < C
⊢ (∀ (x : α), dist (↑(mkOfCompact f) x) (↑(mkOfCompact g) x) < C) ↔ ∀ (x : α), dist (↑f x) (↑g x) < C State After: no goals Tactic: simp only [mkOfCompact_apply] |
Formal statement is: lemma incseq_Suc_iff: "incseq f \<longleftrightarrow> (\<forall>n. f n \<le> f (Suc n))" Informal statement is: A sequence $f$ is increasing if and only if $f(n) \leq f(n+1)$ for all $n$. |
-- --------------------------------------------------------------- [ Error.idr ]
-- Module : Error.idr
-- Copyright : (c) Jan de Muijnck-Hughes
-- License : see LICENSE
-- --------------------------------------------------------------------- [ EOH ]
module Commons.Options.ArgParse.Error
import Commons.Data.Location
import Commons.Options.ArgParse.Model
import Commons.Options.ArgParse.Lexer
import Commons.Options.ArgParse.Parser
%default total
%access public export
data ArgParseError : Type where
InvalidOption : Arg -> ArgParseError
MalformedOption : ParseError Token -> ArgParseError
(Show Arg) => Show ArgParseError where
show (InvalidOption o) = "Invalid Option " ++ show o
show (MalformedOption (PError (MkParseFail error location rest))) =
unlines [show location, error]
show (MalformedOption (LError (MkLexFail l i))) = unwords [show l, ":\n" <+> i]
show (MalformedOption (FError x)) = unlines ["File Error:", show x]
-- --------------------------------------------------------------------- [ EOF ]
|
Formal statement is: lemma contour_integral_diff: "f1 contour_integrable_on g \<Longrightarrow> f2 contour_integrable_on g \<Longrightarrow> contour_integral g (\<lambda>x. f1 x - f2 x) = contour_integral g f1 - contour_integral g f2" Informal statement is: If $f_1$ and $f_2$ are integrable on a contour $g$, then $f_1 - f_2$ is integrable on $g$ and $\int_g (f_1 - f_2) = \int_g f_1 - \int_g f_2$. |
-- @@stderr --
dtrace: failed to compile script test/unittest/assocs/err.tupoflow.d: Insufficient registers to generate code
|
lemma is_unit_const_poly_iff: "[:c:] dvd 1 \<longleftrightarrow> c dvd 1" for c :: "'a::{comm_semiring_1,semiring_no_zero_divisors}" |
// Distributed under the BSD License, see accompanying LICENSE.txt
// (C) Copyright 2010 John-John Tedro et al.
#ifndef __MC_WORLD_HPP__
#define __MC_WORLD_HPP__
#include <stdlib.h>
#include <limits.h>
#include <string>
#include <queue>
#include <list>
#include "fileutils.hpp"
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/filesystem.hpp>
#include <mc/utils.hpp>
#include <mc/region.hpp>
namespace mc {
namespace fs = boost::filesystem;
class level_info;
class region_iterator;
class iterator_error : public std::exception {
private:
const char* message;
public:
iterator_error(const char* message)
: message(message)
{
}
~iterator_error() throw() { }
const char* what() const throw() {
return message;
}
};
class world {
public:
fs::path world_path;
int min_x, min_z, max_x, max_z;
// the difference between min_* and max_*
int diff_x, diff_z;
// min_* as a point
int min_xp, min_zp;
int chunk_x, chunk_y;
world(fs::path path);
region_iterator get_iterator();
void update(utils::level_coord coord);
};
}
#endif /* __MC_WORLD_HPP__ */
|
Formal statement is: lemma LIMSEQ_subseq_LIMSEQ: "X \<longlonglongrightarrow> L \<Longrightarrow> strict_mono f \<Longrightarrow> (X \<circ> f) \<longlonglongrightarrow> L" Informal statement is: If $X_n$ converges to $L$, and $f$ is a strictly increasing function, then $X_{f(n)}$ converges to $L$. |
Formal statement is: lemma complete_UNIV: "complete (UNIV :: ('a::complete_space) set)" Informal statement is: The set of all elements of a complete space is complete. |
[STATEMENT]
lemma h_diff_le_h_plus: "h_diff i e \<le> h_plus i e"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. h_diff i e \<le> h_plus i e
[PROOF STEP]
by(simp add: h_diff_def) |
1900 Storm Memorial by David W. Moore
|
# code from https://github.com/JuliaGraphics/FreeType.jl/tree/master/gen
using Clang.Generators
# https://github.com/EsotericSoftware/spine-runtimes/releases
const SPINE_VERSION = v"3.8.95"
const spine_runtimes_dir = normpath(@__DIR__, "spine-runtimes-$SPINE_VERSION")
!isdir(spine_runtimes_dir) && throw(string("need ", spine_runtimes_dir))
const spine_include_dir = normpath(spine_runtimes_dir, "spine-c/spine-c/include")
const spine_include_spine_dir = normpath(spine_include_dir, "spine")
((root, dirs, files),) = walkdir(spine_include_spine_dir)
const spine_headers = normpath.(root, filter(x -> endswith(x, ".h"), files))
const headers = spine_headers
const args = vcat(get_default_args(), "-I$spine_include_dir")
const options = load_options(joinpath(@__DIR__, "generator.toml"))
ctx = create_context(headers, args, options)
build!(ctx)
|
[STATEMENT]
lemma complex_eq_if_Re_eq:
assumes "is_real z1" and "is_real z2"
shows "z1 = z2 \<longleftrightarrow> Re z1 = Re z2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (z1 = z2) = (Re z1 = Re z2)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
is_real z1
is_real z2
goal (1 subgoal):
1. (z1 = z2) = (Re z1 = Re z2)
[PROOF STEP]
by (cases z1, cases z2) auto |
Subsets and Splits