text
stringlengths 0
27.1M
| meta
dict |
|---|---|
\documentclass[useAMS,usenatbib,referee]{biom}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{csquotes}
\usepackage[colorlinks=true, citecolor = blue]{hyperref} % hyperlinks
\usepackage{multirow, amssymb, amsmath, graphicx, arydshln, url}
\usepackage[T1]{fontenc}
\usepackage{natbib}
\author{Jonas Moss$^{*}$\email{jonasmgj@math.uio.no} and
Riccardo De Bin$^{**}$\email{debin@math.uio.no}\\
Department of Mathematics, University of Oslo, Moltke Moes vei 35, 0851 Oslo, Norway}
\def\bSig\mathbf{\Sigma}
\newcommand{\VS}{V\&S}
\newcommand{\tr}{\mbox{tr}}
\newtheorem{prop}[theorem]{Proposition}
\newtheorem{lem}[theorem]{Lemma}
\newtheorem{thm}[theorem]{Theorem}
\newtheorem{exampl}[theorem]{Example}
\renewcommand{\sqrt}[1]{(#1)^{1/2}}
\title[Modelling publication bias and \textit{p}-hacking]{Modelling publication bias and \textit{p}-hacking}
\begin{document}
\date{{\it Received Month} 20XX. {\it Revised Month} 20XX. {\it Accepted Month} 20XX.}
\pagerange{\pageref{firstpage}--\pageref{lastpage}}
\volume{XX}
\pubyear{20XX}
\artmonth{Month}
\doi{10.1111/j.1541-0420.2005.00454.x}
\label{firstpage}
\begin{abstract}
Publication bias and \textit{p}-hacking are two well-known phenomena that strongly affect the scientific literature and cause severe problems in meta-analyses. Due to these phenomena, the assumptions of meta-analyses are seriously violated and the results of the studies cannot be trusted. While publication bias is very often captured well by the weighting function selection model, \textit{p}-hacking is much harder to model and no definitive solution has been found yet. In this paper we propose to model both publication bias and \textit{p}-hacking with selection models. We derive some properties for these models, and we compare them formally and through simulations. Finally, two real data examples are used to show how the models work in practice.
\end{abstract}
\begin{keywords}
File drawer problem; Fishing for significance; Meta-analysis; Questionable research practices, Selection bias.
\end{keywords}
\maketitle
\section{Introduction}
Meta-analysis is the quantitative combination of information from different studies. Aggregating information from multiple studies brings higher statistical power, higher accuracy in estimation and greater reproducibility. Unfortunately, it is not always possible to believe in the results of meta-analyses, as some model assumptions may be seriously violated. In particular, a meta-analysis must not be based on a biased selection of studies. Publication bias \citep{sterling1959publication} and \textit{p}-hacking \citep{simmons2011false} are the most common phenomena that violate these assumptions.
Publication bias, also known as the file drawer problem \citep{Rosenthal1979-pm}, denotes the phenomenon when a study with a smaller \textit{p}-value is more likely to be published than a study with a higher \textit{p}-value. Publication bias is a well-known issue, and several approaches have been proposed to tackle it. Two famous examples are the trim-and-fill \citep{duval2000trim} and fail-safe $N$ \citep{becker2005failsafe} methods, but neither of them explicitly model the publication selection mechanism. From a statistical point of view, the most important class of models which are used to deal with publication bias are the selection models. They were first studied by \citet{hedges1984estimation} for $F$-distributed variables with a cutoff at $0.05$, and extended to the setting of $t$-values by \citet{iyengar1988selection}. \citet{hedges1992modeling} proposed a random effects publication bias model with more than one cutoff, while \citet{citkowicz2017parsimonious} used beta distributed weights. Other examples of selection models include the non-parametric approax of \cite{dear1992approach}, the sensitivity analysis of \cite{CopasShi2000}, and the regression methods of \cite{Vevea1995-on}. \citet{mcshane2016adjusting} is an accessible overview of selection models in publication bias.
Publication bias is a well-known problem in several research areas, and therefore various approaches to solve the issue have been also proposed outside the statistical literature. Hailing from economics, PET, PEESE, and PET-PEESE \citep{stanley2014meta} are two models based on linear regression and an approximation of the selection mechanism based on the inverse Mill's ratio. From psychology, the \textit{p}-curve of \citet{simonsohn2014p} is a method that only looks at significant \textit{p}-values and judges whether their distribution shows sign of being produced by studies with insufficient power. The \textit{p}-curve for estimation \citep{simonsohn2014} is a fixed effect selection model with a significance cutoff at $0.05$ estimated by minimizing the Kolmogorov-Smirnov distance \citep{mcshane2016adjusting}. Another method from the psychology literature is \textit{p}-uniform \citep{van2015meta}, which is similar to the \textit{p}-curve. A recent study by \citet{carter2019correcting} compared several approaches and showed that the selection model works better than the others. However, not even the best method works well in every considered scenario. For more information on publication bias we refer to the book by \citet{rothstein2006publication}.
In contrast, \textit{p}-hacking, sometimes also called \emph{questionable research practices} \citep{Sijtsma2016} and \emph{fishing for significance} \citep{Boulesteix2009}, occurs when the authors of a study manipulate results into statistical significance. \textit{p}-hacking can be done at the experimental stage, using for example optional stopping, or at the analysis stage, for instance by changing models or dropping out participants. Examples of \textit{p}-hacking can be found in \citet{simmons2011false}. While publication bias, at least that based on \textit{p}-values, has been shown to be captured well by selection models such as that of \citet{hedges1992modeling}, \textit{p}-hacking is harder to model \citep{carter2019correcting}. The aforementioned \textit{p}-curve approach by \citet{simonsohn2014p} has been used for \textit{p}-hacking as well, but it has been shown to be not reliable \citep{BrunsIoannidis2016}. Here we advocate the selection model approach and propose to use it to model both publication bias and \textit{p}-hacking. We derive some properties for these models and argue they are best handled by Bayesian methods.
The paper is organized as follows: In Section \ref{sect:models} we define the framework and introduce the models, which are also theoretically compared. Further comparisons are presented through simulations in Section \ref{sect:simulations} and examples in Section \ref{sect:examples}. We conclude with some remarks and possible extensions in Section \ref{sect:conclusions}.
\section{Models}\label{sect:models}
\subsection{Framework}
The main ingredient of a meta-analysis is a collection of exchangeable statistics $x_{i}$. Each statistic $x_{i}$ has density $f^{\star}(x_{i}\mid\theta_{i},\eta_{i})$, where $\eta_i$ is a known or unknown nuisance parameter and $\theta_{i}$ is an unknown parameter we wish to make inference on. This paper is about the fact that the true data-generating model $f^{\star}(x_{i}\mid\theta_{i},\eta_{i})$ is often not what it ideally should have been, such as a normal density. It has been transformed into something else by the forces of publication bias and \textit{p}-hacking. Our goal is to understand what it has been transformed into, and how we can estimate $\theta_{i}$ accordingly. The selection function publication bias model \citet{hedges1992modeling} and the soon-to-be introduced \textit{p}-hacking model transform the underlying density $f^{\star}(x_{i}\mid\theta_{i},\eta_{i})$ into a new density $f_{i}(x_{i}\mid\theta_{i},\eta_{i})$. The results of this paper will be presented for normal densities, but they hold for any distribution that satisfies mild conditions (see Section \ref{sect:conclusions} and Web Appendix A). We only require the dependencies on a parameter of interest $\theta_{i}$ and that statistical inference on $\theta_{i}$ is the goal of the analysis.
The parameter $\theta_{i}$ is typically an effect size, such as a standardized mean difference. In a fixed effects meta-analysis, $\theta_{i}=\theta$ for all $i$. In a random effects meta-analysis, $\theta_{i}$ is drawn from an effect size distribution $p(\theta)$ common to all $i$, and the goal of the study is often to make inference on the parameters of the effect size distribution, for example on the mean $\theta_{0}$ and the standard deviation $\tau$ when $\theta_i \sim N(\theta_{0},\tau^2)$. If we marginalize away $\theta_{i}$ we will end up with a density on the form $f(x_{i}\mid \theta_{0},\sigma_{i}^{2}+\tau^{2})$, assuming $x_{i}$ is also from a normal distribution with standard deviation $\sigma_{i}$, i.e., $\eta_i = \sigma_i$. This is possible in our framework, but it turns out that an important property of the publication bias model gets lost, as marginalizing out the $\theta_{i}$s can mask the fact that the selection mechanism in the publication bias has an effect both on the effect size distribution and the individual densities $f_{i}(x_{i}\mid\theta_i, \sigma_i)$. Note that here, and in the rest of the paper, we follow the usual practice of assuming $\sigma_i$ as known \citep{vanHouwelingen2002}.
\subsection{The selection model}\label{subsec:selectionModel}
Before introducing the publication bias and the \textit{p}-hacking models, let us define the \emph{selection model}, of which both models are specific instances. Consider the statistic $x_i$ and its density $f^{\star}(x_{i})$, for the moment without the dependencies on $\theta_{i}$ and $\eta_{i}$. Let the \emph{selection variable} $s$ be a binary stochastic variable that equals $1$ if and only if $x_i$ is observed, for instance if the paper containing $x_i$ has been accepted by an editor. When the selection only depends on $x_i$, the density of our observed statistic is $f_{i}(x_{i}) = p(s=1\mid x_i)/p(s=1)f^{\star}(x_{i})$. This is also known as a \emph{weighted distribution} \citep[][eq. 3.1]{rao1985weighted}, and can be interpreted as a rejection sampling model \citep{von1951various}.
The selection mechanism can depend on other quantities, such as the study-specific parameter $\theta_i$ and the study-specific nuisance parameter $\eta_{i}$. We will see that the selection mechanism can be changed by conditioning on $\theta_i$ in the denominator, which is what we do with the \textit{p}-hacking model in Section \ref{subsect:p-hacking}.
%Now the selection mechanism can change by conditioning on $\theta_i$, which is what we do in the \textit{p}-hacking (Section \ref{subsect:p-hacking}) model below. Both the publication bias model (Section \ref{subsect:publicationBias}) and the \textit{p}-hacking model are selection models.
% Making use of the notational convention $y_H = \{y_j, j\in H\}$, define the \emph{selection model} based on $H$ as
% \begin{equation}
% f_{H}(y)=\frac{p(s=1\mid y)}{p(s=1\mid y_{H^{c})}}p(y)\label{eq:H-selection model},
% \end{equation}
% where $H^c$ is the complement of $H$. It is easy to verify that $f_{H}(y)$ is a density for any $H$. The choice of $H$ strongly affects the form of $f_{H}(y)$, and, in general, $f_{H}(y) \neq f_{G}(y)$ for $H \neq G$.
% \begin{prop}
% \label{prop:Equal selection models}Two selection models based on the same $p(x)$ and $s$ are equal, i.e., $f_{H}(y)=f_{G}(y)$, if and only if $p(s=1\mid y_{H^{c}})=p(s=1\mid y_{G^{c}})$.
% In particular, $f_{H}(y)=p(y)$ if and only if $p(s=1\mid y_{H^{c}})=p(s=1\mid y)$.
% \end{prop}
% \begin{proof}
% Both results follow directly from Equation \eqref{eq:H-selection model}.
% \end{proof}
\subsection{The publication bias model} \label{subsect:publicationBias}
Imagine the publication bias scenario:
\begin{quote}
Alice is an editor who receives a study with a \textit{p}-value $u_i$. She knows her journals will suffer if she publishes many null-results, so she is disinclined to publish studies with large \textit{p}-values. Still, she will publish any result with some \textit{p}-value-dependent probability $w(u_i)$. Every study you will ever read in Alice's journal has survived this selection mechanism, the rest are lost forever.
\end{quote}
In this story, the underlying model $f^{\star}(x_{i}\mid\theta_{i},\eta_{i})$ is transformed into a publication bias model
\vspace{-9mm}
\begin{equation}\label{eq:Publication bias model}
f(x_{i}\mid\theta_{i},\eta_{i})\propto f^{\star}(x_{i}\mid\theta_{i},\eta_{i})w(u_i)
\end{equation}
by the selection probability $w(u_i) \in [0,1]$, which is a probability for each $u_i$. Here $u_i$ is a \textit{p}-value that depends on $x_{i}$ and maybe something else, such as the standard deviation of $x_{i}$, but does not depend on $\theta_{i}$. We can write the model using the selection variable $s$, as $w(u_i) = w(u_i(x_i, \eta_i)) = p(s=1 \mid x_i, \eta_i)$. Note that $w(u_i)$ cannot depend on $\theta_{i}$ since the editor has no way of knowing the parameter $\theta_{i}$; if she did, she would not have to look at the \textit{p}-values at all. The normalizing constant of model \eqref{eq:Publication bias model} is finite for any probability $w(u_i)$, hence $f$ is a \textit{bona fide} density.
An argument against the publication bias scenario is that publication bias does not act only through \textit{p}-values, but also through other features of the study such as language \citep{egger1998meta}
and originality \citep{callaham1998positive}. While this is true, the publication bias scenario seems to completely capture the idea of \textit{p}-value based publication bias. Even if other sources of publication bias exist, maybe acting through $x_{i}$ but not its \textit{p}-value, publication bias based on \textit{p}-values is a universally recognized problem, and a good place to start.
The kind of model sketched here is almost the same as the one of \citet{hedges1992modeling}, with the sole exception that \citet{hedges1992modeling} does not require $w(u_i)$ to be a probability, just that the integral of $f^{\star}(x_{i}\mid\theta_{i},\eta_{i})w(u_i)$ is finite, which can happen without $w(u_i)$ being a probability. We demand that $w(u_i)$ to be a probability since the intuitive publication bias scenario interpretation of the model disappears when $w(u_i)$ is not a probability. %Anyway, there are many choices for $w(u)$ even when we force it to be a probability. Assume $w^{\star}(u)$ is any bounded positive function in $\left[0,1\right]$, and define $w(u)=w^{\star}(u)/\textrm{sup}\{w^{\star}(u)\}$. Then $w(u)$ is a probability for each $u$, and fits right into the publication bias framework. An easy way to generate examples of such functions is to take density functions on $\left[0,1\right]$ and check if they are bounded. For instance, beta densities are bounded whenever both shape parameters are greater than $1$. The beta density is used in the publication bias model of \citet{citkowicz2017parsimonious}, but they do not demand it to be a probability.
Even if we know the underlying $f^{\star}(x_{i}\mid\theta_{i},\eta_{i})$ of model \eqref{eq:Publication bias model}, we will need to decide on what \textit{p}-value to use. Usually, the \textit{p}-value will be approximately a one-sided normal \textit{p}-value, but it might be something
else instead. A one-sided normal \textit{p}-value makes sense because most hypotheses have just one direction that is interesting. For instance, the effect of an antidepressant must be positive for the study to be publishable. A one-sided \textit{p}-value can also be used if the researchers reported a two-sided value, since $p=0.05$ for a two-sided hypothesis corresponds to $p=0.025$ for a one-sided hypothesis. We will use the one-sided normal \textit{p}-value in all examples in this paper.
Provided we know the underlying $f_{i}^{\star}$s and \textit{p}-values $u_i$, we only need to decide on the selection probability to have a fully specified model. \citet{hedges1992modeling} proposes the discrete selection probability
\begin{equation}
w(u_i\mid\rho,\alpha)=\sum_{j=1}^{J}\rho_{j}1_{(\alpha_{j-1},\alpha_{j}]}(u_i),
\end{equation}
where $\alpha$ is a vector with $0=\alpha_{0}<\alpha_{1}<\cdots<\alpha_{J}=1$ and $\rho$ is a non-negative vector with $\rho_{1}=1$. The interpretation of this selection probability is simple: When Alice reads the \textit{p}-value $u_i$, she finds the $j$ with $u_i\in(\alpha_{j-1},\alpha_{j}]$ and accepts the study with probability $\rho_{j}$. Related to this view, \citet{hedges1992modeling} proposed $\alpha_{[1,\dots,J-1]} = (0.001,0.005,0.01,0.05)$, as these \enquote{have particular salience for interpretation} \citep{hedges1992modeling}. In fact, a publication decision often depends on whether a \textit{p}-value crosses the $0.05$-threshold. His reason for using more split points than just $0.05$ is that \enquote{It is probably unreasonable to assume that much is known about the functional form of the weight function} \citep{hedges1992modeling}. While this is true, one may prefer, considering the bias-variance trade-off heuristic, to only use one split point at $0.05$, as done by \citet{iyengar1988selection} in their second weight function. Other reasons to prefer one split are ease of interpretation and presentation. Nevertheless, only using $0.05$ as a threshold for one-sided \textit{p}-values is problematic, as many published results are calculated using a two-sided \textit{p}-value instead. It is useful to add an additional splitting point at $0.025$, as a two-sided \textit{p}-value at that level corresponds to a one-sided \textit{p}-value of $0.05$. In our examples we will use a two-step function selection probability $w(u_i\mid\rho)=1_{[0,0.025)}(u_i)+\rho_{2}1_{[0.025,0.05)}(u_i)+\rho_{3}1_{\left[0.05,1\right]}(u_i)$, where the selection probability when $u_i\in[0,0.025)$ is normalized to $1$ to make the model identifiable. We present models in broad generality in order to allow for an arbitrary number of cutoffs. This possibility is already implemented in the \texttt{R} package associated with this paper, \texttt{publipha} \citep{publipha}.
The following proposition shows the densities of the one-sided normal step function selection probability publication bias models, with fixed effects and with normal random effects, respectively. Here the notation $\phi_{[a,b)}(x\mid\theta,\sigma_i^2)$ indicates a normal truncated to $[a,b)$.
\begin{prop}
\label{prop:One-sided normal discrete probability vector publication bias model-1}
The density of an observation from a fixed effects one-sided normal step function selection probability publication bias model is
\begin{equation}
f(x_{i}\mid\theta,\sigma_{i}) = \sum_{j=1}^{J}\pi_{j}^\star\phi_{[\Phi^{-1}(1-\alpha_{j}),\Phi^{-1}(1-\alpha_{j-1}))}(x_{i}\mid\theta,\sigma_{i}^2),
\end{equation}
where $\pi_{j}^{\star}=\rho_{j}\frac{\Phi(c_{j-1}\mid\theta,\sigma_{i}^2)-\Phi(c_{j}\mid\theta,\sigma_{i}^2)}{\sum_{j=1}^{N}\rho_{j}\left[\Phi(c_{j-1}\mid\theta,\sigma_{i}^2)-\Phi(c_{j}\mid\theta,\sigma_{i}^2)\right]}$ and $c_{j}=\Phi^{-1}(1-\alpha_{j})$.
The density of an observation from the one-sided normal step function selection probability publication bias model with normal random effects and parameters $\sigma_{i},\theta_{0},\tau,$ is
\begin{equation}\label{eq:Random effects, publication bias}
f(x_i\mid\theta_{0},\tau,\sigma_{i})=\sum_{j=1}^{J}\pi_{j}^{\star}(\theta_0,\tau,\sigma_{i})\phi_{[\Phi^{-1}(1-\alpha_{j}),\Phi^{-1}(1-\alpha_{j-1}))}(x\mid\theta_{0},\tau^{2}+\sigma_{i}^{2}),
\end{equation}
where $\pi_{j}^{\star}(\theta_0,\tau,\sigma_{i})=\rho_{j}\frac{\Phi(c_{j-1}\mid\theta_{0},\tau^{2}+\sigma_{i}^{2})-\Phi(c_{j}\mid\theta_{0},\tau^{2}+\sigma_{i}^{2})}{\sum_{j=1}^{J}\rho_{j}\left[\Phi(c_{j-1}\mid\theta_{0},\tau^{2}+\sigma_{i}^{2})-\Phi(c_{j}\mid\theta_{0},\tau^{2}+\sigma_{i}^{2})\right]}$.
\end{prop}
Here $f(x_i\mid\theta_{0},\tau,\sigma_i)$ is not equal to $\int f(x_{i}\mid\theta_{i},\sigma_{i})\phi(\theta_{i}\mid\theta_{0},\tau)d\theta_{i}$, as it might have been expected. See the Web Appendix B for more details.
\subsection{The \textit{p}-hacking model}\label{subsect:p-hacking}
Imagine the \textit{p}-hacking scenario:
\begin{quote}
Bob is an astute researcher who is able to \textit{p}-hack any study to whatever level of significance he wishes. Whenever Bob does his research, he decides on a significance level to reach by drawing an $\alpha$ from a distribution $\omega$. Then he \textit{p}-hacks his study to this $\alpha$-level.
\end{quote}
In this scenario the original density $f^{\star}(x_{i}\mid\theta_{i},\eta_{i}, u_i)$
is transformed into the \textit{p}-hacked density
\begin{equation}\label{eq:p-hacking model}
f(x_{i}\mid\theta_{i},\eta_{i})=\int_{[0,1]}f_\alpha^{\star}(x_{i}\mid\theta_{i},\eta_{i}, u_i)\omega(\alpha\mid u_i, \eta_i)d\alpha,
\end{equation}
where $f_\alpha^{\star}$ is the density $f^{\star}$ truncated so that the \textit{p}-value $u_i\in\left[0,\alpha\right]$, with $\alpha \in [0,1]$. As described in the \textit{p}-hacking scenario, $\alpha$ is drawn from the a density $\omega(\alpha \mid u_i, \eta_i)$, which might depend on covariates. On the other hand, it should not depend on $\theta_{i}$, as the researcher cannot know the true effect size of his study. While publication bias model (\ref{eq:Publication bias model}) is a selection model, the \textit{p}-hacking model (\ref{eq:p-hacking model}) is clearly a mixture model. The publication bias can also be written as a mixture model on the same form as the \textit{p}-hacking model, but then $\omega$ will depend on $\theta_i$, see the Web Appendix B. We stress the fact that the model \eqref{eq:p-hacking model} is not a publication bias model. Although the \textit{p}-hacking model can be written as a selection model \eqref{eq:Publication bias model}, in general the publication probability will depend on the true effect size, which violates an obvious condition for a model to be considered a publication bias model.
Just as the publication bias model requires a choice of $w$, the \textit{p}-hacking model requires a choice of $\omega$. A \textit{p}-hacking scientist is motivated to \textit{p}-hack to the $0.05$ level, maybe to the $0.01$ or $0.025$, but never to a level such as $0.07$ or $0.37$. This motivates the discrete \textit{p}-hacking probability distribution
$$\omega(\alpha\mid\pi)=\sum_{j=1}^{J}\pi_{j}1_{(0,\alpha_{j}]}(\alpha)$$
for some $j$-ary vector $\alpha$ satisfying $0<\alpha_{1}<\alpha_{2}<\cdots<\alpha_{J}=1$,
and $j$-ary vector of probabilities $\pi$. The resulting density is
\[
f(x_{i}\mid\theta_{i},\eta_{i})=\sum_{j=1}^{J}\pi_{j}\left(\int_{u_i\in(0,\alpha_{j}]}f^\star(x_{i}\mid\theta_{i},\eta_{i}, u_i)d\omega(\alpha)\right)^{-1}f^\star(x_{i}\mid\theta_{i},\eta_{i}, u_i)1_{(0,\alpha_{j}]}(u_i).
\]
Using a reasoning entirely analogous to that of Section \ref{subsect:publicationBias}, we suggest to use an $\omega$ only based on the two splitting points $0.025$ and $0.05$, $\omega(u_i\mid\pi) = \pi_11_{[0,0.025]}(u_i) + \pi_{2}1_{(0,0.05]}(u_i) + \pi_{3}1_{(0,1]}(u_i)$, but the model below is presented in broad generality ($J$ cutoffs).
The density of an observation from a fixed effects one-sided normal discrete probability \textit{p}-hacking model is
\begin{eqnarray}
f(x_{i}\mid\theta,\sigma_{i}) & = & \sum_{j=1}^{J}\pi_{j}\phi_{[\Phi^{-1}(1-\alpha_{j}),\Phi^{-1}(1-\alpha_{j-1}))}(x_{i}\mid\theta,\sigma_{i}),
\end{eqnarray}
but there is no closed form for the density of its random effect version.
\subsection{The difference between the models\label{subsec:Selection sets, meta analysis}}
% Things get more complicated when the problem also involve other quantities, such as the study-specific parameter $\theta_i$ or nuisance parameter $\eta_i$, as we need to specify exactly which variables are resampled when $s=0$.
% In our models, $\eta_i$ will never be resampled, leaving us with three options. First, $\theta_i$ and $x_i$ could be resampled when $s = 0$; this is what happens in a publication bias model. Second, only $x_i$ could be resampled when $s=0$, as happens in the \textit{p}-hacking model. Third, if no variable is resampled at all, the underlying model is not modified at all.
The publication bias and the \textit{p}-hacking models are in general not the same, as their selection mechanisms condition on different quantities. Here we show that the selection mechanism can affect the effect size distribution.
In the random effects publication bias model, a completely new study is done whenever the last one failed to be published. In the event that $s=0$ and the study fails to be published, a new effect size $\theta_i$ is sampled from the original effect size distribution $p(\theta_i)$, and then a new $x_i$ from $N(\theta_i,\sigma_i)$. As a consequence, the modified effect size distributed $p^\star(\theta_i\mid \sigma_i)$ will generally not equal the original effect size distribution, as
\[
p^\star(\theta_i\mid \sigma_i)=\int\frac{p(s=1\mid x_i, \sigma_i)}{p(s=1\mid\sigma_i)}f(x_i \mid \theta_i, \sigma _i) p(\theta_i) dx_i\neq p(\theta_i).
\]
The dependence on $\sigma_i$ in $p^\star(\theta_i\mid \sigma_i)$ cannot be removed. In practice, the modified effect size distribution will be skewed towards favourable $\theta_i$s, as the selection mechanism of the publication bias model penalizes studies for which the effect sizes $\theta_i$s come from the least favourable part of the support of $p(\theta_i)$. Even if we somehow knew all the $\theta_i$s corresponding to our sample of $x_i$s, the mean of these $\theta_i$s would be larger than the mean of the underlying effect size distribution. %In effect, the observed effect size distribution cannot be used directly to predict the value of a new draw from the true effect size distribution.
% We care about which variables are resampled when $s=0$ since the effect size distribution $p(\theta)$ can be modified. In particular, when $\theta_i$ and $x_i$ are resampled when $s=0$, the effect size distributed $p^\star(\theta_i)$ is modified along with likelihood $f(x_i\mid \theta_i,\eta_i$:
% \[
% p^\star(\theta_i\mid \sigma_i)=\int\frac{p(s=1\mid x, \sigma_i)}{p(s=1\mid\sigma_i)}f(x_i \mid \theta_i, \sigma _i) p(\theta_i) dx\neq p(\theta_i).
% \]
% When the original effect size distribution is normal $N(\theta_0,\tau)$, the modified effect size distribution will depend on $\sigma_i$ and might be deviate considerably from $N(\theta_0,\tau)$. To in
The \textit{p}-hacking model does not modify the effect size distribution. The \textit{p}-hacker will hack his study all the way to significance, regardless of $\theta_i$. In this case, there will not be a new $\theta_i$ when $s=0$: The \textit{p}-hacker will modify the study until success ($s=1$) given the sampled $\theta_i$. The modified effect size distribution equals the original effect size distribution, that is,
\[
p^\star(\theta_i\mid \sigma_i)=\int\frac{p(s=1\mid x_i, \sigma_i)}{p(s=1\mid \theta_i, \sigma_i)}f(x_i \mid \theta_i, \sigma _i) p(\theta_i)dx_i = p(\theta_i).
\]
The publication bias model defined in Proposition \ref{prop:One-sided normal discrete probability vector publication bias model-1} and the \textit{p}-hacking model are equivalent when $\sigma_{i}$ is constant across studies. This holds both for the fixed and random effects models. To see this, let $\pi$ be any probability vector for the \textit{p}-hacking model and solve the invertible linear system $\pi^{\star}(\rho)=\pi$ for $\rho$. There is no guarantee for the models to be equivalent when $\sigma_{i}$ is not constant across studies.
\section{Simulations}\label{sect:simulations}
We want to answer these three questions about the \textit{p}-hacking and publication bias models: (1) Do they work even in the absence of \textit{p}-hacking and publication bias? Although we know these phenomena are ubiquitous and should always be corrected for, it is still important that the models do not distort the results when there is no publication bias or \textit{p}-hacking. (2) How do they behave in extreme situations, in particular when $n$ is small and the heterogeneity is large? (3) Are the models distinguishable in practice? Does the \textit{p}-hacking model work under the publication bias scenario and vice versa?
\subsection{Settings}
We generate data under three scenarios: (i) With no publication bias nor \textit{p}-hacking, using the normal random effect meta-analysis model. (ii) Under the presence of publication bias, using model \eqref{eq:Random effects, publication bias}. (iii) Under presence of \textit{p}-hacking, using the random effects normal \textit{p}-hacking model. The study-specific variances $\sigma_{i}^{2}$ are sampled uniformly from $\left\{ 20,\ldots80\right\} $. The size of the meta-analyses are $n = 5, 30, 100$, corresponding to small, medium and large meta-analyses, while the means for the effect size distribution are $0, 0.2, 0.8$. The value $\theta_0 = 0$ corresponds to no expected effect, while the positive $\theta_0$s are the cutoff for small and large effect sizes of \citet[][pages 24 -- 27]{cohen1988statistical}. The standard deviations of the random effects distributions are $\tau=0.1$ and $\tau=0.5$. While $\tau = 0.1$ is a reasonable amount of heterogeneity, $\tau=0.5$ is a large amount of heterogeneity that provides a challenge for the models. The probability of acceptance of a paper are simulated to be $1$ if the \textit{p}-value is between $0$ and $0.025$, $0.7$ if the \textit{p}-value is between $0.025$ and $0.05$, and $0.1$ otherwise. For the same intervals, the \textit{p}-hacking probabilities are $0.6$, $0.3$ and $0.1$.
In addition to the classical uncorrected model for meta-analysis, for each parameter combination we estimate the \textit{p}-hacking model and the publication bias model using Bayesian methods. While a frequentist approach is in theory possible, it may lead to poor results if ad-hoc penalizations or bias corrections are not implemented. See \citet[Appendix, 1]{mcshane2016adjusting} and \citet{Moss2019} for further details. All models have normal likelihoods and normal effect size distributions. We use one-sided significance cutoffs at $0.025$ and $0.05$ for both the publication bias and the \textit{p}-hacking models. We use standard normal priors for $\theta_0$, a standard half normal prior for $\tau$, and, in the \textit{p}-hacking model, a uniform Dirichlet prior for $\pi$. For the $\rho$ in the publication bias model we use a a uniform Dirichlet that constrains $\rho_{1}\geq\ldots\geq\rho_{j}$. That is, the publication probability is a decreasing function of the \textit{p}-value.
All of these priors are reasonable. A standard normal for $\theta_0$ is reasonable because we know that $\theta_0$ has a small magnitude in pretty much any meta-analysis, and most are clustered around $0$. A half normal prior for $\tau$ is also reasonable, as $\tau$ is much more likely to be very small than very big. The priors for $\rho$ and $\pi$ are harder to reason about, but a uniform Dirichlet seems like a natural and neutral choice. These are the standard prior of the $\mathtt{R}$ package $\mathtt{publipha}$ \citep{publipha}, which we used for all computations. $\mathtt{publipha}$ uses $\mathtt{STAN}$ \citep{Carpenter2017-cf} to estimate the models, and each estimation uses $8$ chains.
The number of simulations is $N = 100$ for each parameter combination. The code used to run the simulations is available in the Online Supporting Information and in an OSF repository (\url{https://osf.io/tx8qn/}).
\subsection{Results}
\paragraph{No publication bias, no \textit{p}-hacking.} The results under this scenario are reported in Table \ref{tab:Simulation_classical}. When the amount of heterogeneity is reasonable ($\tau = 0.1$) both the \textit{p}-hacking and the publication bias perform well. The publication bias model performs slightly worse than the \textit{p}-hacking model when the mean effect size is large ($\theta_0 = 0.8$) and the number of studies small ($n=5$), but it catches up as $n$ increases. With $\tau = 0.5$, the \textit{p}-hacking model outperforms the publication bias model, with the latter tending to underestimate the mean effect. While increasing $n$ alleviates the problem, there is still a substantial underestimation of $\theta_0$ even in the case of $n = 100$. In contrast, both models seem to estimate $\tau$ pretty well. Obviously, without any publication bias or \textit{p}-hacking, the classical uncorrected model gives good results.
\begin{table}[ht]
\centering
\caption{{\bf No publication bias, no
\textit{p}-hacking.} Posterior means
and standard deviations from the \textit{p}-hacking,
publication bias, and uncorrected models when the data are simulated
from the normal random effects meta-analysis model.}
\label{tab:Simulation_classical}
\begin{tabular}{lllrrrrrr}
\multicolumn{3}{r}{\textbf{True values}} &
\multicolumn{2}{c}{\textbf{\textit{p}-hacking model}} &
\multicolumn{2}{c}{\textbf{Publication bias model}} &
\multicolumn{2}{c}{\textbf{Uncorrected model}}\\$\tau$ & $\theta_0$ & $n$ & \multicolumn{1}{c}{$\widehat{\theta_0}$} & \multicolumn{1}{c}{$\widehat{\tau}$} & \multicolumn{1}{c}{$\widehat{\theta_0}$} & \multicolumn{1}{c}{$\widehat{\tau}$} & \multicolumn{1}{c}{$\widehat{\theta_0}$} & \multicolumn{1}{c}{$\widehat{\tau}$} \\
\hline
\multirow{9}{*}{$0.1$} & \multirow{3}{*}{$0$} & 5 & -0.03 (0.09) & 0.18 (0.07) & -0.06 (0.08) & 0.13 (0.06) & 0.00 (0.09) & 0.19 (0.08) \\
& & 30 & -0.01 (0.03) & 0.08 (0.03) & -0.02 (0.03) & 0.07 (0.03) & 0.00 (0.04) & 0.10 (0.04) \\
& & 100 & -0.01 (0.02) & 0.08 (0.03) & -0.01 (0.02) & 0.07 (0.02) & 0.00 (0.02) & 0.10 (0.03) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.2$} & 5 & 0.12 (0.08) & 0.21 (0.08) & 0.09 (0.07) & 0.17 (0.08) & 0.20 (0.08) & 0.19 (0.08) \\
& & 30 & 0.17 (0.04) & 0.09 (0.04) & 0.15 (0.03) & 0.09 (0.04) & 0.20 (0.03) & 0.10 (0.04) \\
& & 100 & 0.18 (0.02) & 0.09 (0.03) & 0.17 (0.02) & 0.09 (0.03) & 0.20 (0.02) & 0.10 (0.02) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.8$} & 5 & 0.78 (0.08) & 0.21 (0.10) & 0.63 (0.15) & 0.34 (0.14) & 0.79 (0.07) & 0.20 (0.08) \\
& & 30 & 0.80 (0.04) & 0.11 (0.04) & 0.80 (0.04) & 0.11 (0.04) & 0.80 (0.04) & 0.10 (0.04) \\
& & 100 & 0.80 (0.02) & 0.10 (0.03) & 0.80 (0.02) & 0.10 (0.03) & 0.80 (0.02) & 0.09 (0.03) \\
\cline{2-9}
\multirow{9}{*}{$0.5$} & \multirow{3}{*}{$0$} & 5 & -0.03 (0.20) & 0.59 (0.21) & -0.21 (0.17) & 0.53 (0.21) & 0.01 (0.20) & 0.61 (0.20) \\
& & 30 & -0.03 (0.09) & 0.51 (0.08) & -0.14 (0.09) & 0.47 (0.08) & -0.01 (0.09) & 0.51 (0.07) \\
& & 100 & -0.02 (0.05) & 0.50 (0.04) & -0.08 (0.06) & 0.48 (0.04) & 0.00 (0.05) & 0.50 (0.04) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.2$} & 5 & 0.10 (0.22) & 0.57 (0.20) & -0.09 (0.19) & 0.54 (0.19) & 0.16 (0.21) & 0.58 (0.19) \\
& & 30 & 0.15 (0.10) & 0.53 (0.08) & 0.02 (0.10) & 0.51 (0.08) & 0.19 (0.10) & 0.52 (0.08) \\
& & 100 & 0.19 (0.05) & 0.51 (0.04) & 0.11 (0.06) & 0.49 (0.04) & 0.21 (0.05) & 0.50 (0.04) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.8$} & 5 & 0.68 (0.23) & 0.62 (0.21) & 0.35 (0.23) & 0.74 (0.21) & 0.72 (0.21) & 0.59 (0.21) \\
& & 30 & 0.78 (0.10) & 0.52 (0.08) & 0.60 (0.14) & 0.60 (0.08) & 0.80 (0.09) & 0.50 (0.07) \\
& & 100 & 0.79 (0.05) & 0.51 (0.04) & 0.70 (0.07) & 0.55 (0.04) & 0.80 (0.05) & 0.50 (0.04) \\
\hline
\end{tabular}
\end{table}
\paragraph{Publication bias} Overall, the publication bias model outperforms the \textit{p}-hacking model when the data are generated from the publication bias model, but not by much, see Table \ref{tab:Simulation_pb}. When $\tau = 0.5$ the \textit{p}-hacking model tends to overestimates $\theta_0$ while the publication bias model tends to underestimate it. The overestimation of the \textit{p}-hacking model is most extreme when $\theta_0 = 0.2$, but not as strong as the classical uncorrected model. When $\tau = 0.1$, the publication bias and \textit{p}-hacking models produce almost indistinguishable results, ouperforming the uncorrected model (especially if the effect $\theta_0$ is null or small). Just as in the \textit{p}-hacking scenario, both models estimate $\tau$ reasonably well.
\begin{table}[ht]
\centering
\caption{{\bf Publication bias.}
Posterior means and standard deviations from the
\textit{p}-hacking, publication bias, and uncorrected models
when the data are simulated from the publication
bias model with cutoffs at $0.025$ and $0.05$,
with selection probabilities equal to $1$, $0.7$,
and $0.1$ in the intervals $[0, 0.025)$, $[0.025, 0.05)$,
and $[0.5, 1]$.}
\label{tab:Simulation_pb}
\begin{tabular}{lllrrrrrr}
\multicolumn{3}{r}{\textbf{True values}} &
\multicolumn{2}{c}{\textbf{\textit{p}-hacking model}} &
\multicolumn{2}{c}{\textbf{Publication bias model}} &
\multicolumn{2}{c}{\textbf{Uncorrected model}}\\$\tau$ & $\theta_0$ & $n$ & \multicolumn{1}{c}{$\widehat{\theta_0}$} & \multicolumn{1}{c}{$\widehat{\tau}$} & \multicolumn{1}{c}{$\widehat{\theta_0}$} & \multicolumn{1}{c}{$\widehat{\tau}$} & \multicolumn{1}{c}{$\widehat{\theta_0}$} & \multicolumn{1}{c}{$\widehat{\tau}$} \\
\hline
\multirow{9}{*}{$0.1$} & \multirow{3}{*}{$0$} & 5 & -0.01 (0.10) & 0.23 (0.08) & -0.01 (0.07) & 0.18 (0.07) & 0.13 (0.08) & 0.23 (0.10) \\
& & 30 & 0.02 (0.04) & 0.12 (0.05) & 0.01 (0.04) & 0.10 (0.04) & 0.13 (0.04) & 0.16 (0.04) \\
& & 100 & 0.02 (0.03) & 0.12 (0.03) & 0.00 (0.02) & 0.10 (0.03) & 0.13 (0.02) & 0.16 (0.02) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.2$} & 5 & 0.10 (0.15) & 0.30 (0.09) & 0.10 (0.07) & 0.21 (0.08) & 0.32 (0.07) & 0.16 (0.08) \\
& & 30 & 0.22 (0.05) & 0.11 (0.05) & 0.19 (0.05) & 0.09 (0.04) & 0.33 (0.03) & 0.06 (0.03) \\
& & 100 & 0.23 (0.03) & 0.10 (0.04) & 0.20 (0.04) & 0.09 (0.03) & 0.33 (0.01) & 0.04 (0.02) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.8$} & 5 & 0.77 (0.08) & 0.20 (0.08) & 0.62 (0.14) & 0.32 (0.12) & 0.78 (0.07) & 0.19 (0.07) \\
& & 30 & 0.80 (0.03) & 0.10 (0.04) & 0.79 (0.03) & 0.10 (0.04) & 0.80 (0.03) & 0.10 (0.03) \\
& & 100 & 0.80 (0.02) & 0.10 (0.02) & 0.80 (0.02) & 0.10 (0.02) & 0.80 (0.02) & 0.10 (0.02) \\
\cline{2-9}
\multirow{9}{*}{$0.5$} & \multirow{3}{*}{$0$} & 5 & 0.34 (0.21) & 0.53 (0.20) & 0.04 (0.22) & 0.56 (0.18) & 0.42 (0.17) & 0.47 (0.23) \\
& & 30 & 0.36 (0.10) & 0.48 (0.09) & 0.01 (0.19) & 0.50 (0.08) & 0.43 (0.08) & 0.42 (0.09) \\
& & 100 & 0.36 (0.04) & 0.47 (0.04) & -0.01 (0.10) & 0.50 (0.04) & 0.43 (0.04) & 0.42 (0.04) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.2$} & 5 & 0.42 (0.21) & 0.54 (0.22) & 0.12 (0.22) & 0.59 (0.19) & 0.50 (0.18) & 0.46 (0.21) \\
& & 30 & 0.50 (0.07) & 0.44 (0.08) & 0.16 (0.18) & 0.51 (0.09) & 0.56 (0.06) & 0.38 (0.08) \\
& & 100 & 0.51 (0.04) & 0.42 (0.04) & 0.19 (0.10) & 0.50 (0.05) & 0.57 (0.04) & 0.37 (0.04) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.8$} & 5 & 0.81 (0.22) & 0.56 (0.19) & 0.47 (0.27) & 0.71 (0.20) & 0.86 (0.19) & 0.50 (0.17) \\
& & 30 & 0.90 (0.09) & 0.45 (0.08) & 0.64 (0.21) & 0.58 (0.13) & 0.92 (0.08) & 0.42 (0.07) \\
& & 100 & 0.90 (0.04) & 0.45 (0.04) & 0.74 (0.09) & 0.53 (0.06) & 0.92 (0.04) & 0.42 (0.03) \\
\hline
\end{tabular}
\end{table}
\paragraph{\textit{p}-hacking} The simulation results for the \textit{p}-hacking model are in Table \ref{tab:Simulation_ph}. As before, the largest differences are in the most difficult case of $\tau = 0.5$, while the two models tend to agree in the more realistic case of $\tau = 0.1$. When $\tau = 0.5$ the publication bias model severely underestimates $\theta_0$, even getting the sign wrong in some instances. This should not come as a surprise given the interpretation of $\theta_0$ in the publication bias model, but shows that we should be cautious in interpreting the $\theta_0$ estimates. In basically all cases the \textit{p}-hacking model outperforms the uncorrected model, with the latter surprisingly working better than the publication bias model when the effect size $\theta_0$ is large (0.8).
\begin{table}[ht]
\centering
\caption{{\bf \textit{p}-hacking.} Posterior means and
standard deviations from the \textit{p}-hacking,
publication bias, and uncorrected models when the data are simulated
from the \textit{p}-hacking model with cutoffs at
$0.025$ and $0.05$, with \textit{p}-hacking probabilities
equal to $0.6$, $0.3$, and $0.1$ in the intervals
$[0, 0.025)$, $[0.025, 0.05)$, and $[0.5, 1]$}
\label{tab:Simulation_ph}
\begin{tabular}{lllrrrrrr}
\multicolumn{3}{r}{\textbf{True values}} &
\multicolumn{2}{c}{\textbf{\textit{p}-hacking model}} &
\multicolumn{2}{c}{\textbf{Publication bias model}} &
\multicolumn{2}{c}{\textbf{Uncorrected model}}\\$\tau$ & $\theta_0$ & $n$ & \multicolumn{1}{c}{$\widehat{\theta_0}$} & \multicolumn{1}{c}{$\widehat{\tau}$} & \multicolumn{1}{c}{$\widehat{\theta_0}$} & \multicolumn{1}{c}{$\widehat{\tau}$} & \multicolumn{1}{c}{$\widehat{\theta_0}$} & \multicolumn{1}{c}{$\widehat{\tau}$} \\
\hline
\multirow{9}{*}{$0.1$} & \multirow{3}{*}{$0$} & 5 & -0.06 (0.14) & 0.29 (0.07) & 0.04 (0.06) & 0.17 (0.05) & 0.29 (0.06) & 0.16 (0.09) \\
& & 30 & -0.02 (0.08) & 0.13 (0.05) & 0.01 (0.07) & 0.07 (0.03) & 0.29 (0.02) & 0.05 (0.03) \\
& & 100 & 0.00 (0.05) & 0.10 (0.04) & 0.00 (0.05) & 0.05 (0.02) & 0.29 (0.01) & 0.03 (0.02) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.2$} & 5 & 0.12 (0.16) & 0.29 (0.09) & 0.10 (0.06) & 0.21 (0.06) & 0.35 (0.05) & 0.13 (0.04) \\
& & 30 & 0.18 (0.06) & 0.12 (0.05) & 0.15 (0.06) & 0.09 (0.03) & 0.34 (0.02) & 0.04 (0.02) \\
& & 100 & 0.20 (0.04) & 0.09 (0.04) & 0.17 (0.05) & 0.08 (0.03) & 0.34 (0.01) & 0.02 (0.01) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.8$} & 5 & 0.79 (0.08) & 0.18 (0.09) & 0.65 (0.14) & 0.30 (0.13) & 0.79 (0.08) & 0.17 (0.07) \\
& & 30 & 0.80 (0.03) & 0.10 (0.04) & 0.79 (0.03) & 0.10 (0.04) & 0.80 (0.03) & 0.10 (0.04) \\
& & 100 & 0.80 (0.02) & 0.10 (0.02) & 0.80 (0.02) & 0.10 (0.02) & 0.80 (0.02) & 0.10 (0.02) \\
\cline{2-9}
\multirow{9}{*}{$0.5$} & \multirow{3}{*}{$0$} & 5 & 0.08 (0.22) & 0.47 (0.19) & 0.01 (0.12) & 0.37 (0.19) & 0.36 (0.12) & 0.29 (0.18) \\
& & 30 & 0.08 (0.09) & 0.43 (0.08) & -0.24 (0.19) & 0.35 (0.10) & 0.36 (0.05) & 0.24 (0.09) \\
& & 100 & 0.07 (0.06) & 0.44 (0.04) & -0.33 (0.14) & 0.37 (0.06) & 0.37 (0.03) & 0.24 (0.05) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.2$} & 5 & 0.19 (0.24) & 0.50 (0.20) & 0.05 (0.13) & 0.42 (0.22) & 0.43 (0.13) & 0.30 (0.20) \\
& & 30 & 0.24 (0.09) & 0.47 (0.08) & -0.20 (0.19) & 0.46 (0.09) & 0.46 (0.05) & 0.28 (0.08) \\
& & 100 & 0.23 (0.05) & 0.47 (0.04) & -0.27 (0.16) & 0.47 (0.06) & 0.45 (0.03) & 0.29 (0.04) \\
\cdashline{3-9}
& \multirow{3}{*}{$0.8$} & 5 & 0.72 (0.19) & 0.60 (0.19) & 0.35 (0.20) & 0.73 (0.19) & 0.79 (0.15) & 0.51 (0.17) \\
& & 30 & 0.78 (0.09) & 0.52 (0.07) & 0.36 (0.23) & 0.67 (0.11) & 0.83 (0.07) & 0.44 (0.06) \\
& & 100 & 0.80 (0.05) & 0.50 (0.04) & 0.42 (0.20) & 0.65 (0.09) & 0.85 (0.04) & 0.43 (0.03) \\
\hline
\end{tabular}
\end{table}
\section{Examples}\label{sect:examples}
In this section we apply the models on the two meta-analyses of \citet{cuddy2018p} and \citet{anderson2010violent}. As in the simulation study, we use normal models for each effect size with one-sided significance cutoff at $0.025$ and $0.05$ for both models. We use the same priors as we did in the simulation study. To compare the fit of the models we use the leave-one-out cross-validation information criterion (\textsc{LOOIC}) \citep{loo_article}, calculated using the R package $\mathtt{loo}$ \citep{loo}. LOOIC equals $-2\cdot\textsc{elpd}_{\textsc{loo}}$, where $\textsc{elpd}$ is the expected log pointwise predictive density for a new data set and $\textsc{elpd}_\textsc{loo}$ is an estimate of this quantity by leave-one-out cross validation. Just as the \textsc{AIC}, smaller values indicate better model fit. As for the simulation study, the analyses have been done with the $\mathtt{R}$ package $\mathtt{publipha}$ \citep{publipha}, which in turn uses \texttt{STAN} \citep{Carpenter2017-cf}. Each model has been estimated with $8$ chains. The code used to run the examples can be found in the Online Supporting Information and in an OSF repository (\url{https://osf.io/tx8qn/}).
\subsection{Power posing\label{subsec:cuddy2018}}
\citet{cuddy2018p} conducted a meta-analysis of a of power posing, an alleged phenomenon where adopting expansive postures has positive psychological feedback effects. Their meta-analysis is not conventional, but a \textit{p}-curve analysis \citep{simonsohn2014p}. A \textit{p}-curve analysis is not based on estimated effect sizes and standard errors, but directly on \textit{p}-values. The data from \citet{cuddy2018p} can be accessed via the Open Science Framework (\url{https://osf.io/pfh6r/}). Here we only consider studies with outcome \enquote{mean difference}, design \enquote{2 cell}, and test statistic that is either $F$ or $t$. The $F$-statistics are all with $1$ denominator degree of freedom, and the root of these are distributed as the absolute value of a $t$-distributed variable. The $t$-values and the roots of the $F$-statistics are converted to standardized mean differences by using $d = t\sqrt{2/\nu}$, where $\nu$ is the degrees of freedom for the $t$-test. The standardized mean differences are to the left in Figure \ref{fig:cuddy2017}. Note the outlier $x_{12} = 1.72$. As it has a large effect on all the models, we analyze the data both with and without $x_{12}$.
\begin{figure}
\noindent \begin{centering}
\includegraphics[width=0.49\textwidth]{plots/cuddy2018}\includegraphics[width=0.49\textwidth]{plots/cuddy2018_posterior}
\par\end{centering}
\caption{\label{fig:cuddy2017} \textbf{(left)} Effect sizes for the power posing example. The dotted black line is $1.96/\textrm{sd}$ and the dashed black line is $1.64/\textrm{sd}$. The ticks on the right hand side are
the meta-analytic means: $0.48$ is from the uncorrected model, $0.17$ is the mean of the selected effect size distribution under the \textit{p}-hacking model, while $-0.06$ is the mean under the publication bias model. \textbf{(right)} Posterior densities for $\theta_{2}$ in the power posing example. The dashed density belongs to the \textit{p}-hacking model, the dotted density to the publication bias model, and the solid density to the uncorrected model. The point $x_{2}=0.62$ is marked for reference.}
\end{figure}
The estimates of the \textit{p}-hacking model, the publication bias model, and the uncorrected meta-analysis models are in Table \ref{tab:cuddy2018}. According to the LOOIC the corrected models account much better for the data than the uncorrected model. Both the \textit{p}-hacking model and the publication bias models estimate
larger $\tau$s and smaller $\theta_{0}$s than the classical model, with the publication bias model estimating the surprising $\theta_{0}\approx0$. But recall the results of the simulation study, where the publication bias model severely underestimates $\theta_0$ when the \textit{p}-hacking model is true.
The publication bias selection affects not only the observed $x_{i}$s, but also the $\theta_{i}$s. As a consequence, the posterior mean of the selected effect size distribution (this equals $0.37$, is not shown in the table, and equals the average of the posterior means for the $\theta_{i}$s) is much closer to the uncorrected model's estimate than the \textit{p}-hacked estimate. This effect can be most easily understood by looking at a specific $\theta$, for example the $\theta_2$ reported in the right plot of Figure \ref{fig:cuddy2017}, where $x_{2}=0.62$. In this case, the publication bias posterior for is close to the uncorrected posterior even though $\theta_0 \approx 0$. On the other hand, the \textit{p}-hacking model pushes $0.62$ down to $0.17$, towards the meta-analytic mean of $0.18$.
Finally, the surprisingly low value for $\theta_0$ obtained with the publication bias model can be a side effect of the presence of the outlier $x_{12} = 1.72$. Its presence on the right tail of an hypothetical true effect size distribution implies unobserved low and negative effects not reported due to publication bias. When the outlier is removed from the analysis, the estimate of $\theta_{0}$ goes up and agrees with the estimate from the \textit{p}-hacking model, which does not change. Once the outlier is removed, the fit of the publication bias model increases tremenduously, reaching a level close to that of the \textit{p}-hacking model. Moreover, the estimates of $\tau$ are strongly affected by the removal of $x_{12}$. In particular, the estimate of $\tau$ decreases from $0.45$ to $0.09$ in the \textit{p}-hacking model.
%% <<<<< Example table start (\label{tab:cuddy2018)
\input{tables/cuddy2018.tex}
%% example table end >>>>>
In conclusion, the \textit{p}-hacking and publication bias models suggest there is selection bias in these studies. Both models have much better fit than the uncorrected one and it is reasonable to accept their parameter estimates as more realistic. Nonetheless, both models agree on a value of $\theta_{0}$ that is likely to be different from $0$. The results of Table \ref{tab:cuddy2018} supports \citet{cuddy2018p}'s conclusion that there is evidence for some positive effect of power posing. The \textit{p}-hacking model does not suffer the presence of an outlier, and, in contrast to the publication bias model, provides similar results with and without $x_{12}$ in the data.
\subsection{Violent video games\label{subsec:Anderson}}
\citet{anderson2010violent} conducted a large meta-analysis on the effects of violent video games on seven negative outcomes such as aggressive behavior and aggressive cognition. As part of their analysis, they classified some experiments as best practice experiments \citep[for more details, see Table 2 of][]{anderson2010violent}. Suspecting publication bias, \citet{hilgard2017overstated} reanalysed the data using an array of tools to detect and adjust for publication bias. For the outcome variable aggressive cognition, \citet{hilgard2017overstated} noted that \enquote{Application of best-practices criteria seems to emphasize statistical significance, and a knot of experiments just reach statistical significance}. The data can be found on the web \citep{Hilgard2017} and are visualised to the left in Figure \ref{fig:anderson2010}. In the plot, the best practice experiments are represented by solid circles, all other experiments by hollow squares. An outlier $x=1.33$ has been removed from the data set, and excluded from our analyses. Its removal substantially improves the fit for all the models.
In this example we fit the three models (\textit{p}-hacking, publication bias and uncorrected models) to three data subsets (all experiments, only best practice experiments, without best practice experiments). The outcome variable is aggressive behavior. Our the aim is to answer the following: (1) What are the parameter estimates, in each subset, for each model? (2) Which model has the best fit? (3) Do we have a reason to believe the best practice experiments are drawn from a different underlying distribution than the other experiments, as \citet{hilgard2017overstated} and the top left plot of Figure \ref{fig:anderson2010} suggest? (4) Is there a large difference between the posterior for $\theta_{0}$ and the mean posterior for the $\theta_{i}$s, as we saw in the previous example?
%% <<<<< Example table start (\label{tab:anderson2010)
\input{tables/anderson2010.tex}
%% example table end >>>>>
The first three questions can be answered by looking at Table \ref{tab:Anderson2010}. The estimates of $\theta_{0}$ are approximately the same for the publication bias and \textit{p}-hacking models, and roughly half of the uncorrected estimate in all cases. In particular, when all experiments or only the best experiments are considered, there is a noticeable difference. In these two cases, the LOOICs suggest that some \textit{p}-hacking or publication bias is present, as they are smaller than the LOOIC for the uncorrected models. Although the publication bias model seems to work slightly better than the \textit{p}-hacking model, we can state that the two models agree and we have little reason to prefer one to the other. Basically, we can interpret this as converging evidence that the parameter estimates obtained with these two models for $\theta_{0}$ and $\tau$ are in the ballpark of their true values.
Interestingly, when we exclude the experiments not considered best practice by \citet{anderson2010violent}, the differences between the estimates provided by the corrected and uncorrected models reduce and the LOOICs are almost the same. The question is if the differences between best practice and non-best practice studies reflect a different underlying distribution or not. To answer this question, let us take a look at the posterior densities for $\theta_{0}$ when all experiments are included, as reported in the top right plot of Figure \ref{fig:anderson2010}. In this case, the posterior distributions computed with the \textit{p}-hacking and publication bias models are similar (dashed and dotted lines, respectively), which strengthens the agreement seen in Table \ref{tab:Anderson2010}. There is no large difference between the posterior for $\theta_{0}$ and the mean posterior for the $\theta_{i}$s as in the previous example. The answer to question (4) is therefore no.
Back to question (3), we have good reasons to believe the best practice experiments have been drawn from a different underlying distribution than the other experiments if there is negligible overlap between the posteriors for the parameters $\theta_{0}$. The uncorrected model supports this hypothesis (bottom right plot of Figure \ref{fig:anderson2010}), but the \textit{p}-hacking and publication bias models to do not. See the bottom left plot of Figure \ref{fig:anderson2010} for the posteriors for $\theta_0$ in the publication bias model (those obtained with the \textit{p}-hacking model are indistinguishable). In this case, the overlap between the posteriors for the different subsets is not negligible, and there is no evidence against hypotheses of equal $\theta_0$s in both groups. The same conclusion can be reached from Table \ref{tab:Anderson2010} by looking at the posterior standard deviations and posterior means.
\begin{figure}
\includegraphics[width=0.49\textwidth]{plots/anderson2010}
\includegraphics[width=0.49\textwidth]{plots/anderson_posterior}
\includegraphics[width=0.49\textwidth]{plots/anderson_posterior_1}
\includegraphics[width=0.49\textwidth]{plots/anderson_posterior_2}
\caption{\label{fig:anderson2010}Violent video games example with outcome variable aggressive behavior. \textbf{(top-left)} Effect sizes. The dotted black line is $1.96/\textrm{sd}$ and the dashed black line is $1.64/\textrm{sd}$. The ticks on the right hand side are the uncorrected meta-analytical means for each group: $0.29$ for the best practices group, $0.08$ for the rest. The outlier $x=1.33$ has been removed from the plot.
\textbf{(top-right)} Posterior densities for $\theta_{0}$ with all experiments included. The dashed density belongs to the \textit{p}-hacking model, the dotted to the publication bias model, and the solid to the uncorrected model. \textbf{(bottom-left)} Posterior densities for $\theta_{0}$ from the publication bias model. The solid curve is the model with all experiments, the dotted curve the model with the best practice experiments, and the dashed line the model without the best experiments. The posteriors for the \textit{p}-hacking model are similar to this one. \textbf{(bottom-right)} Posterior densities for $\theta_{0}$ (solid line: all experiments; dotted line: best practice experiments only; and dashed line without the best experiments) from the uncorrected meta-analysis model.}
\end{figure}
\section{Concluding remarks}\label{sect:conclusions}
In this paper we studied two models to handle the effect of \textit{p}-hacking and publication bias. Although the \textit{p}-hacking model worked really well in the simulation study, we have to admit that the \textit{p}-hacking scenario described in Section \ref{subsect:p-hacking} is less plausible than the publication bias scenario of Section \ref{subsect:publicationBias}. First, the assumption of Bob's \textit{p}-hacking omnipotence is strong. For while some researchers are able \textit{p}-hackers, most give up at some point. Does truncation actually model \textit{p}-hacking in the wild? Analysing \textit{p}-hacking is hard without serious simplifying assumptions. The model we proposed is interpretable and implementable, and it appears to work well in practice, as one can see in the examples of Section \ref{sect:examples}.
For simplicity of exposition, in this paper we only considered normal densities, but the theory holds more generally. A remaining concern is identifiability, but we show in Web Appendix A that the publication bias and the \textit{p}-hacking models are identifiable under weak conditions on $f$.
We are often interested in understanding and modelling the sources of heterogeneity in a meta-analysis \citep{thompson1994systematic}. A way to do this is to let $\theta_{i}$ linearly depend on covariates, in the meta-analysis context known as moderators. If we extend the one-sided discrete models publication bias and \textit{p}-hacking models to include covariates, we will be able to estimate their effect while keeping the \textit{p}-hacking probability or the selection probability fixed, as done by e.g. \citet{Vevea1995-on} in the publication bias model. Another option is to allow the \textit{p}-hacking probability or the selection probability to depend on covariates themselves. For instance, the difficulty of \textit{p}-hacking is likely to increase with $n$, the sample size of the study. Similarly, the selection probability is also likely to be influenced by $n$; for example when $n$ is large, null-effects are more publishable.
Although the common practice in meta-analysis studies is to treat the standard deviations as nuisance parameter, the actual tests usually contain an estimate of the standard error and this can also influence the selection mechanism. Further modifications to the models can be obtained by allowing for this.
%For example, in the publication bias model, $w_i(u_i)$ may be let depend on the nuisance parameter $\eta_i$ (which can include, e.g., the standard deviation $\sigma_i$) could be incorporated. A possible modification of the \textit{p}-hacking model consists in putting $\theta_i$ inside the Xelection set, which makes the researcher draw new $\theta_i$s every time he attempts a \textit{p}-hack. This could be used to model scenarios where the hypothesis is not known in advance by the researchers.
We saw in the simulations and in Example \ref{subsec:cuddy2018} that the publication bias and the \textit{p}-hacking models can give remarkably different results even with similar priors and the same $\alpha$ vector. A way to react to this situation is to choose the best-fitting model in terms of, for example, LOOIC. To be safe, one can present the results of both models and try to understand the differences between them, as we did in the examples of Section \ref{sect:examples}. In the publication bias model, it is especially important to be aware of the interpretation of $\theta_{0}$ as the mean of the underlying effect size distribution, not the effect size distribution of the observed studies. Therefore, the best response to the question \enquote{Should one use the \textit{p}-hacking and publication bias model?} is probably \enquote{Use both!}
Finally, it would be interesting to model publication bias and \textit{p}-hacking at the same time:
\begin{quote}
Bob \textit{p}-hacks his research to a \textit{p}-value drawn from $\omega$ and sends it to Alice's journal. Alice accepts the paper with probability $w(u_i)$. Every rejected study is lost.
\end{quote}
In this scenario the original density $f^{\star}(x_{i}\mid\theta_{i},\eta_{i})$ is transformed twice: First by \textit{p}-hacking, then by publication bias. The resulting model is
$$
f(x_{i}\mid\theta_{i},\eta_{i})\propto w(u_i)\int_{[0,1]}f_{[0,\alpha]}^{\star}(x_{i}\mid\theta_{i},\eta_{i})d\omega(\alpha).
$$
This is a reasonable model, but its normalizing constant is hard to calculate, even when $\omega$ is discrete and $w$ is a step function. Additional work on this problem is required.
\bibliographystyle{biom}
\bibliography{edited.bib}
\label{lastpage}
\end{document}
|
{
"alphanum_fraction": 0.7205519719,
"author": null,
"avg_line_length": 145.4513064133,
"converted": null,
"ext": "tex",
"file": null,
"hexsha": "19a7c7bb291c90db22b611093d65cfd4f6f75708",
"include": null,
"lang": "TeX",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "38c4e854cb9b6f8675ca384c3031db0d5ff9e642",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "JonasMoss/p-hacking",
"max_forks_repo_path": "MossDebin_firstResub.tex",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "38c4e854cb9b6f8675ca384c3031db0d5ff9e642",
"max_issues_repo_issues_event_max_datetime": "2020-08-06T14:38:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-29T11:31:12.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "JonasMoss/p-hacking",
"max_issues_repo_path": "MossDebin_firstResub.tex",
"max_line_length": 1985,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "38c4e854cb9b6f8675ca384c3031db0d5ff9e642",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "JonasMoss/p-hacking",
"max_stars_repo_path": "MossDebin_firstResub.tex",
"max_stars_repo_stars_event_max_datetime": "2020-08-14T23:18:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-14T23:18:58.000Z",
"num_tokens": 19018,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 61235
}
|
import numpy as np
# import pandas as pd
def read_data():
with open ('input.txt') as f:
data = f.readlines()
return [int(d.strip()) for d in data[0].split(',')]
def write_data(data):
with open('output.txt','w') as f:
for d in data:
f.write(str(d)+'\n')
###
from collections import Counter, defaultdict
def part1():
return solution(80)
def part2():
return solution(256)
def solution(days):
ages = read_data()
ages.sort()
data = defaultdict(int,Counter(ages))
fish = np.zeros((9))
for ii in range(9):
fish[ii] = data[ii]
nums = np.zeros((days))
for ii in range(days):
n = fish[0]
fish = np.roll(fish,-1)
fish[8] = n
fish[6] += n
nums[ii] = sum(fish)
print(nums[17])
print(nums[79])
return nums[-1]
###
print("part 1: {}".format(part1()))
print("part 2: {}".format(part2()))
|
{
"alphanum_fraction": 0.6047619048,
"author": null,
"avg_line_length": 12.5373134328,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "b25a0e45ab80478af8d491d721c1cfb48298f214",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f44e12596e883e6dd55e2373863627a8331f0d32",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ofloveandhate/advent_of_code_2021",
"max_forks_repo_path": "06/solution.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f44e12596e883e6dd55e2373863627a8331f0d32",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ofloveandhate/advent_of_code_2021",
"max_issues_repo_path": "06/solution.py",
"max_line_length": 52,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f44e12596e883e6dd55e2373863627a8331f0d32",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ofloveandhate/advent_of_code_2021",
"max_stars_repo_path": "06/solution.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 251,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 840
}
|
(*
Copyright 2014 Cornell University
This file is part of VPrl (the Verified Nuprl project).
VPrl is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
VPrl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VPrl. If not, see <http://www.gnu.org/licenses/>.
Website: http://nuprl.org/html/verification/
Authors: Abhishek Anand & Vincent Rahli
*)
Require Import type_sys_useful.
Require Import dest_close.
Lemma eq_term_equals_per_tunion_eq_if {p} :
forall (eqa1 eqa2 : per(p)) (eqb1 : per-fam(eqa1)) (eqb2 : per-fam(eqa2)),
eqa1 <=2=> eqa2
-> (forall (a1 a2 : CTerm) (e1 : eqa1 a1 a2) (e2 : eqa2 a1 a2),
(eqb1 a1 a2 e1) <=2=> (eqb2 a1 a2 e2))
-> (per_tunion_eq eqa1 eqb1) <=2=> (per_tunion_eq eqa2 eqb2).
Proof.
introv eqt1 eqt2.
introv; split; intro k; induction k.
- apply @tunion_eq_cl with (t := t); sp.
- dup e as e'; apply eqt1 in e'.
apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := e'); sp; spcast.
apply (eqt2 a1 a2 e e'); auto.
- apply @tunion_eq_cl with (t := t); sp.
- dup e as e'; apply eqt1 in e'.
apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := e'); sp; spcast.
apply (eqt2 a1 a2 e' e); auto.
Qed.
Lemma per_tunion_eq_sym {p} :
forall (eqa : per(p)) eqb t1 t2,
(forall (a1 a2 : CTerm) (e : eqa a1 a2),
term_equality_symmetric (eqb a1 a2 e))
-> per_tunion_eq eqa eqb t1 t2
-> per_tunion_eq eqa eqb t2 t1.
Proof.
introv tesb per.
induction per.
apply @tunion_eq_cl with (t := t); sp.
apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := e); sp.
apply tesb; auto.
Qed.
Lemma per_tunion_eq_trans {p} :
forall (eqa : per(p)) eqb t1 t2 t3,
per_tunion_eq eqa eqb t1 t2
-> per_tunion_eq eqa eqb t2 t3
-> per_tunion_eq eqa eqb t1 t3.
Proof.
introv per1 per2.
apply tunion_eq_cl with (t := t2); sp.
Qed.
Lemma per_tunion_eq_cequiv {p} :
forall lib (eqa : per(p)) eqb t t',
(forall (a1 a2 : CTerm) (e : eqa a1 a2),
term_equality_symmetric (eqb a1 a2 e))
-> (forall (a1 a2 : CTerm) (e : eqa a1 a2),
term_equality_transitive (eqb a1 a2 e))
-> (forall (a1 a2 : CTerm) (e : eqa a1 a2),
term_equality_respecting lib (eqb a1 a2 e))
-> t ~=~(lib) t'
-> per_tunion_eq eqa eqb t t
-> per_tunion_eq eqa eqb t t'.
Proof.
introv tes tet ter ceq per.
revert_dependents t'.
induction per; introv ceq.
apply IHper2; auto.
apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := e); sp.
apply (ter a1 a2 e t2 t'); auto.
apply tet with (t2 := t1); auto.
apply tes; auto.
Qed.
Lemma close_type_system_tunion {p} :
forall lib (ts : cts(p))
T T'
(eq : per)
A A' v v' B B' eqa eqb,
type_system lib ts
-> defines_only_universes lib ts
-> computes_to_valc lib T (mkc_tunion A v B)
-> computes_to_valc lib T' (mkc_tunion A' v' B')
-> close lib ts A A' eqa
-> (forall (a a' : CTerm) (e : eqa a a'),
close lib ts (substc a v B) (substc a' v' B') (eqb a a' e))
-> (forall (a a' : CTerm) (e : eqa a a'),
type_system lib ts ->
defines_only_universes lib ts ->
type_sys_props lib (close lib ts) (substc a v B) (substc a' v' B')
(eqb a a' e))
-> (forall t t' : CTerm,
eq t t' <=> per_tunion_eq eqa eqb t t')
-> per_tunion lib (close lib ts) T T' eq
-> type_sys_props lib (close lib ts) A A' eqa
-> type_sys_props lib (close lib ts) T T' eq.
Proof.
introv X X0 c1 c2 X1 clb recb eqiff per IHX1.
rw @type_sys_props_iff_type_sys_props3.
prove_type_sys_props3 SCase; intros.
+ SCase "uniquely_valued".
dclose_lr;
try (complete (apply defines_only_universes_tunion_L with (T2 := T3) (eq2 := eq') in per; sp));
try (complete (apply defines_only_universes_tunion_R with (T2 := T3) (eq2 := eq') in per; sp)).
SSCase "CL_tunion".
allunfold @per_tunion; exrepd.
generalize (eq_term_equals_type_family lib T T3 eqa0 eqa eqb0 eqb (close lib ts) A v B A' v' B' mkc_tunion); intro i.
repeat (autodimp i hyp; try (complete (introv ee; eqconstr ee; sp))); repnd.
generalize (eq_term_equals_type_family lib T T' eqa1 eqa eqb1 eqb (close lib ts) A v B A' v' B' mkc_tunion); intro j.
repeat (autodimp j hyp; try (complete (introv ee; eqconstr ee; sp))); repnd.
apply eq_term_equals_trans with (eq2 := per_tunion_eq eqa1 eqb1); auto.
apply eq_term_equals_trans with (eq2 := per_tunion_eq eqa0 eqb0); auto;
try (complete (apply eq_term_equals_sym; auto)).
apply eq_term_equals_per_tunion_eq_if; auto.
apply eq_term_equals_trans with (eq2 := eqa); auto.
apply eq_term_equals_sym; auto.
introv.
dup e2 as e3.
rw <- i0 in e3.
apply eq_term_equals_trans with (eq2 := eqb a1 a2 e3); auto.
apply eq_term_equals_sym; auto.
+ SCase "type_symmetric"; repdors; subst; dclose_lr;
apply CL_tunion;
clear per;
allunfold @per_tunion; exrepd;
unfold per_tunion;
exists eqa0 eqb0; sp;
allrw <-; sp.
apply eq_term_equals_trans with (eq2 := eq); auto.
apply eq_term_equals_sym; auto.
+ SCase "type_value_respecting"; repdors; subst;
apply CL_tunion; unfold per_tunion; exists eqa eqb; sp.
duplicate c1 as ct.
apply @cequivc_mkc_tunion with (T' := T3) in ct; sp.
apply @type_family_cequivc
with
(A1 := A)
(v1 := v)
(B1 := B)
(A2 := A'0)
(v2 := v'0)
(B2 := B'0)
(A := A')
(v := v')
(B := B'); sp.
duplicate c2 as ct.
apply @cequivc_mkc_tunion with (T' := T3) in ct; sp.
apply @type_family_cequivc2
with
(A1 := A')
(v1 := v')
(B1 := B')
(A2 := A'0)
(v2 := v'0)
(B2 := B'0)
(A := A)
(v := v)
(B := B); sp.
+ SCase "term_symmetric".
unfold term_equality_symmetric; introv eqts.
onedtsp e pp p0 p1 c t t0 t3 tygs tygt dum.
apply eqiff; apply eqiff in eqts; exrepnd.
apply per_tunion_eq_sym; auto.
introv.
pose proof (recb a1 a2 e0) as h; repeat (autodimp h hyp).
onedtsp x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11; auto.
+ SCase "term_transitive".
unfold term_equality_transitive; sp.
apply eqiff; sp.
assert (eq t1 t2) as eq12 by auto.
assert (eq t2 t3) as eq23 by auto.
rw eqiff in eq12; rw eqiff in eq23; exrepnd.
apply (per_tunion_eq_trans eqa eqb t1 t2 t3); auto.
+ SCase "term_value_respecting".
unfold term_equality_respecting; sp.
apply eqiff; sp.
assert (eq t t) as eqtt by auto.
apply eqiff in eqtt; exrepnd.
apply (per_tunion_eq_cequiv lib eqa eqb t t'); auto;
introv;
pose proof (recb a1 a2 e) as h; repeat (autodimp h hyp);
onedtsp x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11; auto.
+ SCase "type_gsymmetric"; repdors; subst; split; sp; dclose_lr;
apply CL_tunion;
clear per;
allunfold @per_tunion; exrepd.
(* 1 *)
generalize (eq_term_equals_type_family
lib T T3 eqa0 eqa eqb0 eqb (close lib ts)
A v B A' v' B' mkc_tunion); intro i.
repeat (autodimp i hyp; try (complete (introv ee; eqconstr ee; sp))).
repnd.
exists eqa eqb; sp.
apply eq_term_equals_trans with (eq2 := per_tunion_eq eqa0 eqb0); auto.
apply eq_term_equals_per_tunion_eq_if; auto.
apply eq_term_equals_sym; auto.
(* 2 *)
generalize (eq_term_equals_type_family2
lib T3 T eqa0 eqa eqb0 eqb (close lib ts)
A v B A' v' B' mkc_tunion); intro i;
repeat (autodimp i hyp; try (complete (introv ee; eqconstr ee; sp)));
repnd.
exists eqa eqb; sp.
apply eq_term_equals_trans with (eq2 := per_tunion_eq eqa0 eqb0); auto.
apply eq_term_equals_per_tunion_eq_if; auto.
apply eq_term_equals_sym; auto.
+ SCase "type_gtransitive"; sp.
+ SCase "type_mtransitive".
repdors; subst; dclose_lr;
try (move_term_to_top (per_tunion lib (close lib ts) T T4 eq2));
try (move_term_to_top (per_tunion lib (close lib ts) T' T4 eq2)).
(* 1 *)
clear per.
allunfold @per_tunion; exrepd.
generalize (eq_term_equals_type_family2
lib T3 T eqa1 eqa eqb1 eqb (close lib ts)
A v B A' v' B' mkc_tunion); intro i.
repeat (autodimp i hyp; try (complete (introv ee; eqconstr ee; sp))).
repnd.
generalize (type_family_trans2
lib mkc_tunion (close lib ts) T3 T T4 eqa eqb eqa0 eqb0 A v B A' v' B'); intro j.
repeat (autodimp j hyp; try (complete (introv ee; eqconstr ee; sp))).
repnd.
dands; apply CL_tunion; unfold per_tunion; exists eqa eqb; sp; allrw.
eapply eq_term_equals_trans; eauto.
apply eq_term_equals_per_tunion_eq_if; auto.
apply eq_term_equals_sym; auto.
eapply eq_term_equals_trans; eauto.
apply eq_term_equals_per_tunion_eq_if; auto.
apply eq_term_equals_sym; auto.
introv.
apply eq_term_equals_sym; auto.
(* 2 *)
clear per.
allunfold @per_tunion; exrepd.
generalize (eq_term_equals_type_family2
lib T3 T' eqa1 eqa eqb1 eqb (close lib ts)
A' v' B' A v B mkc_tunion); intro i.
repeat (autodimp i hyp;
try (complete (introv ee; eqconstr ee; sp));
try (complete (apply type_sys_props_sym; sp))).
onedtsp uv tys tyt tyst tyvr tes tet tevr tygs tygt dum.
intros.
apply type_sys_props_sym.
apply type_sys_props_eqb_comm; sp.
apply tet with (t2 := a'); sp.
apply tet with (t2 := a); sp.
repnd.
generalize (type_family_trans2
lib mkc_tunion (close lib ts) T3 T' T4 eqa eqb eqa0 eqb0 A' v' B' A v B); intro j.
repeat (autodimp j hyp;
try (complete (introv ee; eqconstr ee; sp));
try (complete (apply type_sys_props_sym; sp))).
onedtsp uv tys tyt tyst tyvr tes tet tevr tygs tygt dum.
intros.
apply type_sys_props_sym.
apply type_sys_props_eqb_comm; sp.
apply tet with (t2 := a'); sp.
apply tet with (t2 := a); sp.
repnd.
dands; apply CL_tunion; unfold per_tunion; exists eqa eqb; sp; allrw.
eapply eq_term_equals_trans; eauto.
apply eq_term_equals_per_tunion_eq_if; auto.
apply eq_term_equals_sym; auto.
eapply eq_term_equals_trans; eauto.
apply eq_term_equals_per_tunion_eq_if; auto.
apply eq_term_equals_sym; auto.
introv.
apply eq_term_equals_sym; auto.
Qed.
|
{
"alphanum_fraction": null,
"author": "vrahli",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/close/close_type_sys_per_tunion.v",
"reason": null,
"repo": "NuprlInCoq",
"save_path": "github-repos/coq/vrahli-NuprlInCoq",
"sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98",
"size": null
}
|
[STATEMENT]
lemma bcontfun\<^sub>N:
fixes f::"('a::topological_space \<Rightarrow> 'b::real_normed_vector)"
shows "eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm(Bcontfun f) else (\<infinity>::ennreal))"
"Norm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm(Bcontfun f) else 0)"
"defect (bcontfun\<^sub>N::(('a \<Rightarrow> 'b) quasinorm)) = 1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>) &&& Norm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm (Bcontfun f) else 0) &&& defect bcontfun\<^sub>N = 1
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)
2. Norm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm (Bcontfun f) else 0)
3. defect bcontfun\<^sub>N = 1
[PROOF STEP]
have *: "quasinorm_on bcontfun 1 (\<lambda>(f::('a \<Rightarrow> 'b)). norm(Bcontfun f))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. quasinorm_on bcontfun 1 (\<lambda>x. ennreal (norm (Bcontfun x)))
[PROOF STEP]
proof (rule quasinorm_onI, auto)
[PROOF STATE]
proof (state)
goal (6 subgoals):
1. \<And>x y. \<lbrakk>x \<in> bcontfun; y \<in> bcontfun\<rbrakk> \<Longrightarrow> x + y \<in> bcontfun
2. \<And>x y. \<lbrakk>x \<in> bcontfun; y \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (x + y))) \<le> ennreal (norm (Bcontfun x)) + ennreal (norm (Bcontfun y))
3. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> c *\<^sub>R x \<in> bcontfun
4. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
5. 0 \<in> bcontfun
6. Bcontfun 0 = 0
[PROOF STEP]
fix f g::"'a \<Rightarrow> 'b"
[PROOF STATE]
proof (state)
goal (6 subgoals):
1. \<And>x y. \<lbrakk>x \<in> bcontfun; y \<in> bcontfun\<rbrakk> \<Longrightarrow> x + y \<in> bcontfun
2. \<And>x y. \<lbrakk>x \<in> bcontfun; y \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (x + y))) \<le> ennreal (norm (Bcontfun x)) + ennreal (norm (Bcontfun y))
3. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> c *\<^sub>R x \<in> bcontfun
4. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
5. 0 \<in> bcontfun
6. Bcontfun 0 = 0
[PROOF STEP]
assume H: "f \<in> bcontfun" "g \<in> bcontfun"
[PROOF STATE]
proof (state)
this:
f \<in> bcontfun
g \<in> bcontfun
goal (6 subgoals):
1. \<And>x y. \<lbrakk>x \<in> bcontfun; y \<in> bcontfun\<rbrakk> \<Longrightarrow> x + y \<in> bcontfun
2. \<And>x y. \<lbrakk>x \<in> bcontfun; y \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (x + y))) \<le> ennreal (norm (Bcontfun x)) + ennreal (norm (Bcontfun y))
3. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> c *\<^sub>R x \<in> bcontfun
4. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
5. 0 \<in> bcontfun
6. Bcontfun 0 = 0
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
f \<in> bcontfun
g \<in> bcontfun
[PROOF STEP]
show "f + g \<in> bcontfun"
[PROOF STATE]
proof (prove)
using this:
f \<in> bcontfun
g \<in> bcontfun
goal (1 subgoal):
1. f + g \<in> bcontfun
[PROOF STEP]
unfolding plus_fun_def
[PROOF STATE]
proof (prove)
using this:
f \<in> bcontfun
g \<in> bcontfun
goal (1 subgoal):
1. (\<lambda>x. f x + g x) \<in> bcontfun
[PROOF STEP]
by (simp add: plus_cont)
[PROOF STATE]
proof (state)
this:
f + g \<in> bcontfun
goal (5 subgoals):
1. \<And>x y. \<lbrakk>x \<in> bcontfun; y \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (x + y))) \<le> ennreal (norm (Bcontfun x)) + ennreal (norm (Bcontfun y))
2. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> c *\<^sub>R x \<in> bcontfun
3. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
4. 0 \<in> bcontfun
5. Bcontfun 0 = 0
[PROOF STEP]
have *: "Bcontfun(f + g) = Bcontfun f + Bcontfun g"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Bcontfun (f + g) = Bcontfun f + Bcontfun g
[PROOF STEP]
using H
[PROOF STATE]
proof (prove)
using this:
f \<in> bcontfun
g \<in> bcontfun
goal (1 subgoal):
1. Bcontfun (f + g) = Bcontfun f + Bcontfun g
[PROOF STEP]
by (auto simp: eq_onp_def plus_fun_def bcontfun_def intro!: plus_bcontfun.abs_eq[symmetric])
[PROOF STATE]
proof (state)
this:
Bcontfun (f + g) = Bcontfun f + Bcontfun g
goal (5 subgoals):
1. \<And>x y. \<lbrakk>x \<in> bcontfun; y \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (x + y))) \<le> ennreal (norm (Bcontfun x)) + ennreal (norm (Bcontfun y))
2. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> c *\<^sub>R x \<in> bcontfun
3. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
4. 0 \<in> bcontfun
5. Bcontfun 0 = 0
[PROOF STEP]
show "ennreal (norm (Bcontfun (f + g))) \<le> ennreal (norm (Bcontfun f)) + ennreal (norm (Bcontfun g))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ennreal (norm (Bcontfun (f + g))) \<le> ennreal (norm (Bcontfun f)) + ennreal (norm (Bcontfun g))
[PROOF STEP]
unfolding *
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ennreal (norm (Bcontfun f + Bcontfun g)) \<le> ennreal (norm (Bcontfun f)) + ennreal (norm (Bcontfun g))
[PROOF STEP]
using ennreal_leI[OF norm_triangle_ineq]
[PROOF STATE]
proof (prove)
using this:
ennreal (norm (?x1 + ?y1)) \<le> ennreal (norm ?x1 + norm ?y1)
goal (1 subgoal):
1. ennreal (norm (Bcontfun f + Bcontfun g)) \<le> ennreal (norm (Bcontfun f)) + ennreal (norm (Bcontfun g))
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
ennreal (norm (Bcontfun (f + g))) \<le> ennreal (norm (Bcontfun f)) + ennreal (norm (Bcontfun g))
goal (4 subgoals):
1. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> c *\<^sub>R x \<in> bcontfun
2. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
3. 0 \<in> bcontfun
4. Bcontfun 0 = 0
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (4 subgoals):
1. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> c *\<^sub>R x \<in> bcontfun
2. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
3. 0 \<in> bcontfun
4. Bcontfun 0 = 0
[PROOF STEP]
fix c::real and f::"'a \<Rightarrow> 'b"
[PROOF STATE]
proof (state)
goal (4 subgoals):
1. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> c *\<^sub>R x \<in> bcontfun
2. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
3. 0 \<in> bcontfun
4. Bcontfun 0 = 0
[PROOF STEP]
assume H: "f \<in> bcontfun"
[PROOF STATE]
proof (state)
this:
f \<in> bcontfun
goal (4 subgoals):
1. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> c *\<^sub>R x \<in> bcontfun
2. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
3. 0 \<in> bcontfun
4. Bcontfun 0 = 0
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
f \<in> bcontfun
[PROOF STEP]
show "c *\<^sub>R f \<in> bcontfun"
[PROOF STATE]
proof (prove)
using this:
f \<in> bcontfun
goal (1 subgoal):
1. c *\<^sub>R f \<in> bcontfun
[PROOF STEP]
unfolding scaleR_fun_def
[PROOF STATE]
proof (prove)
using this:
f \<in> bcontfun
goal (1 subgoal):
1. (\<lambda>x. c *\<^sub>R f x) \<in> bcontfun
[PROOF STEP]
by (simp add: scaleR_cont)
[PROOF STATE]
proof (state)
this:
c *\<^sub>R f \<in> bcontfun
goal (3 subgoals):
1. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
2. 0 \<in> bcontfun
3. Bcontfun 0 = 0
[PROOF STEP]
have *: "Bcontfun(c *\<^sub>R f) = c *\<^sub>R Bcontfun f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Bcontfun (c *\<^sub>R f) = c *\<^sub>R Bcontfun f
[PROOF STEP]
using H
[PROOF STATE]
proof (prove)
using this:
f \<in> bcontfun
goal (1 subgoal):
1. Bcontfun (c *\<^sub>R f) = c *\<^sub>R Bcontfun f
[PROOF STEP]
by (auto simp: eq_onp_def scaleR_fun_def bcontfun_def intro!: scaleR_bcontfun.abs_eq[symmetric])
[PROOF STATE]
proof (state)
this:
Bcontfun (c *\<^sub>R f) = c *\<^sub>R Bcontfun f
goal (3 subgoals):
1. \<And>c x. \<lbrakk>c \<noteq> 0; x \<in> bcontfun\<rbrakk> \<Longrightarrow> ennreal (norm (Bcontfun (c *\<^sub>R x))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun x))
2. 0 \<in> bcontfun
3. Bcontfun 0 = 0
[PROOF STEP]
show "ennreal (norm (Bcontfun (c *\<^sub>R f))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun f))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ennreal (norm (Bcontfun (c *\<^sub>R f))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun f))
[PROOF STEP]
unfolding *
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ennreal (norm (c *\<^sub>R Bcontfun f)) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun f))
[PROOF STEP]
by (simp add: ennreal_mult'')
[PROOF STATE]
proof (state)
this:
ennreal (norm (Bcontfun (c *\<^sub>R f))) \<le> ennreal \<bar>c\<bar> * ennreal (norm (Bcontfun f))
goal (2 subgoals):
1. 0 \<in> bcontfun
2. Bcontfun 0 = 0
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. 0 \<in> bcontfun
2. Bcontfun 0 = 0
[PROOF STEP]
show "(0::'a\<Rightarrow>'b) \<in> bcontfun" "Bcontfun 0 = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 0 \<in> bcontfun &&& Bcontfun 0 = 0
[PROOF STEP]
unfolding zero_fun_def zero_bcontfun_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<lambda>x. 0::'b) \<in> bcontfun &&& Bcontfun (\<lambda>x. 0::'d) = Bcontfun (\<lambda>_. 0::'d)
[PROOF STEP]
by (auto simp add: const_bcontfun)
[PROOF STATE]
proof (state)
this:
0 \<in> bcontfun
Bcontfun 0 = 0
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
quasinorm_on bcontfun 1 (\<lambda>x. ennreal (norm (Bcontfun x)))
goal (3 subgoals):
1. eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)
2. Norm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm (Bcontfun f) else 0)
3. defect bcontfun\<^sub>N = 1
[PROOF STEP]
have **: "quasinorm_on UNIV 1 (\<lambda>(f::'a\<Rightarrow>'b). if f \<in> bcontfun then norm(Bcontfun f) else (\<infinity>::ennreal))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. quasinorm_on UNIV 1 (\<lambda>f. if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)
[PROOF STEP]
by (rule extend_quasinorm[OF *])
[PROOF STATE]
proof (state)
this:
quasinorm_on UNIV 1 (\<lambda>f. if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)
goal (3 subgoals):
1. eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)
2. Norm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm (Bcontfun f) else 0)
3. defect bcontfun\<^sub>N = 1
[PROOF STEP]
show "eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm(Bcontfun f) else (\<infinity>::ennreal))"
"defect (bcontfun\<^sub>N::('a \<Rightarrow> 'b) quasinorm) = 1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>) &&& defect bcontfun\<^sub>N = 1
[PROOF STEP]
using quasinorm_of[OF **]
[PROOF STATE]
proof (prove)
using this:
eNorm (quasinorm_of (1, \<lambda>f. if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)) ?x = (if ?x \<in> bcontfun then ennreal (norm (Bcontfun ?x)) else \<infinity>)
defect (quasinorm_of (1, \<lambda>f. if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)) = 1
goal (1 subgoal):
1. eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>) &&& defect bcontfun\<^sub>N = 1
[PROOF STEP]
unfolding bcontfun\<^sub>N_def
[PROOF STATE]
proof (prove)
using this:
eNorm (quasinorm_of (1, \<lambda>f. if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)) ?x = (if ?x \<in> bcontfun then ennreal (norm (Bcontfun ?x)) else \<infinity>)
defect (quasinorm_of (1, \<lambda>f. if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)) = 1
goal (1 subgoal):
1. eNorm (quasinorm_of (1, \<lambda>f. if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)) f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>) &&& defect (quasinorm_of (1, \<lambda>f. if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)) = 1
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)
defect bcontfun\<^sub>N = 1
goal (1 subgoal):
1. Norm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm (Bcontfun f) else 0)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)
defect bcontfun\<^sub>N = 1
[PROOF STEP]
show "Norm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm(Bcontfun f) else 0)"
[PROOF STATE]
proof (prove)
using this:
eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)
defect bcontfun\<^sub>N = 1
goal (1 subgoal):
1. Norm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm (Bcontfun f) else 0)
[PROOF STEP]
unfolding Norm_def
[PROOF STATE]
proof (prove)
using this:
eNorm bcontfun\<^sub>N f = (if f \<in> bcontfun then ennreal (norm (Bcontfun f)) else \<infinity>)
defect bcontfun\<^sub>N = 1
goal (1 subgoal):
1. enn2real (eNorm bcontfun\<^sub>N f) = (if f \<in> bcontfun then norm (Bcontfun f) else 0)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
Norm bcontfun\<^sub>N f = (if f \<in> bcontfun then norm (Bcontfun f) else 0)
goal:
No subgoals!
[PROOF STEP]
qed
|
{
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": "Lp_Functional_Spaces",
"hexsha": null,
"include": null,
"lang": null,
"length": 45,
"llama_tokens": 6604,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": null
}
|
\chapter{Likelihood functions}
|
{
"alphanum_fraction": 0.7878787879,
"author": null,
"avg_line_length": 8.25,
"converted": null,
"ext": "tex",
"file": null,
"hexsha": "631ddeec531dc6974b3a5628285a6698665b2277",
"include": null,
"lang": "TeX",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "adamdboult/nodeHomePage",
"max_forks_repo_path": "src/pug/theory/statistics/likelihood/00-00-Chapter_name.tex",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93",
"max_issues_repo_issues_event_max_datetime": "2022-01-01T22:16:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-03T12:36:56.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "adamdboult/nodeHomePage",
"max_issues_repo_path": "src/pug/theory/statistics/likelihood/00-00-Chapter_name.tex",
"max_line_length": 30,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "adamdboult/nodeHomePage",
"max_stars_repo_path": "src/pug/theory/statistics/likelihood/00-00-Chapter_name.tex",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 33
}
|
module ReactiveMPModelsAutoregressiveTest
using Test, InteractiveUtils
using Rocket, ReactiveMP, GraphPPL, Distributions
using BenchmarkTools, Random, Plots, Dates, LinearAlgebra, StableRNGs
## Model definition
## -------------------------------------------- ##
@model [ default_factorisation = MeanField() ] function ar_model(n, order)
x = datavar(Vector{Float64}, n)
y = datavar(Float64, n)
γ ~ GammaShapeRate(1.0, 1.0)
θ ~ MvNormalMeanPrecision(zeros(order), diageye(order))
for i in 1:n
y[i] ~ NormalMeanPrecision(dot(x[i], θ), γ)
end
return x, y, θ, γ
end
@model [ default_factorisation = MeanField() ] function lar_model(T::Type{ Multivariate }, n, order, c, stype, τ)
# Parameter priors
γ ~ GammaShapeRate(1.0, 1.0)
θ ~ MvNormalMeanPrecision(zeros(order), diageye(order))
# We create a sequence of random variables for hidden states
x = randomvar(n)
# As well a sequence of observartions
y = datavar(Float64, n)
ct = constvar(c)
# We assume observation noise to be known
cτ = constvar(τ)
# Prior for first state
x0 ~ MvNormalMeanPrecision(zeros(order), diageye(order))
x_prev = x0
# AR process requires extra meta information
meta = ARMeta(Multivariate, order, stype)
for i in 1:n
# Autoregressive node uses structured factorisation assumption between states
x[i] ~ AR(x_prev, θ, γ) where { q = q(y, x)q(γ)q(θ), meta = meta }
y[i] ~ NormalMeanPrecision(dot(ct, x[i]), cτ)
x_prev = x[i]
end
return x, y, θ, γ
end
@model [ default_factorisation = MeanField() ] function lar_model(T::Type{Univariate}, n, order, c, stype, τ)
# Parameter priors
γ ~ GammaShapeRate(1.0, 1.0)
θ ~ NormalMeanPrecision(0.0, 1.0)
# We create a sequence of random variables for hidden states
x = randomvar(n)
# As well a sequence of observartions
y = datavar(Float64, n)
ct = constvar(c)
# We assume observation noise to be known
cτ = constvar(τ)
# Prior for first state
x0 ~ NormalMeanPrecision(0.0, 1.0)
x_prev = x0
# AR process requires extra meta information
meta = ARMeta(Univariate, order, stype)
for i in 1:n
x[i] ~ AR(x_prev, θ, γ) where { q = q(y, x)q(γ)q(θ), meta = meta }
y[i] ~ NormalMeanPrecision(ct * x[i], cτ)
x_prev = x[i]
end
return x, y, θ, γ
end
## -------------------------------------------- ##
## Inference definition
## -------------------------------------------- ##
function ar_inference(inputs, outputs, order, niter)
n = length(outputs)
model, (x, y, θ, γ) = ar_model(n, order, options = (limit_stack_depth = 500, ))
γ_buffer = keep(Marginal)
θ_buffer = keep(Marginal)
fe = keep(Float64)
γ_sub = subscribe!(getmarginal(γ), γ_buffer)
θ_sub = subscribe!(getmarginal(θ), θ_buffer)
f_sub = subscribe!(score(Float64, BetheFreeEnergy(), model), fe)
setmarginal!(γ, GammaShapeRate(1.0, 1.0))
for _ in 1:niter
update!(x, inputs)
update!(y, outputs)
end
unsubscribe!((γ_sub, θ_sub, f_sub))
return γ_buffer, θ_buffer, fe
end
function lar_init_marginals!(::Type{ Multivariate }, order, γ, θ)
setmarginal!(γ, GammaShapeRate(1.0, 1.0))
setmarginal!(θ, MvNormalMeanPrecision(zeros(order), diageye(order)))
end
function lar_init_marginals!(::Type{ Univariate }, order, γ, θ)
setmarginal!(γ, GammaShapeRate(1.0, 1.0))
setmarginal!(θ, NormalMeanPrecision(0.0, 1.0))
end
function lar_inference(data, order, artype, stype, niter, τ)
# We build a full graph based on nber of observatios
n = length(data)
# Depending on the order of AR process `c` is
# either a nber or a vector
c = ReactiveMP.ar_unit(artype, order)
# Note that to run inference for huge model it might be necessary to pass extra
# options = (limit_stack_depth = 100,) to limit stack depth during recursive inference procedure
model, (x, y, θ, γ) = lar_model(artype, n, order, c, stype, τ)
# We are going to keep `γ` and `θ` estimates for all VMP iterations
# But `buffer` only last posterior estimates for a sequence of hidden states `x`
# We also will keep Bethe Free Energy in `fe`
γ_buffer = keep(Marginal)
θ_buffer = keep(Marginal)
x_buffer = buffer(Marginal, n)
fe = keep(Float64)
γsub = subscribe!(getmarginal(γ), γ_buffer)
θsub = subscribe!(getmarginal(θ), θ_buffer)
xsub = subscribe!(getmarginals(x), x_buffer)
fesub = subscribe!(score(Float64, BetheFreeEnergy(), model), fe)
lar_init_marginals!(artype, order, γ, θ)
# We update data several times to perform several VMP iterations
for i in 1:niter
update!(y, data)
end
# It is important to unsubscribe from running observables
unsubscribe!((γsub, θsub, xsub, fesub))
return γ_buffer, θ_buffer, x_buffer, fe
end
@testset "Autoregressive model" begin
@testset "Autoregressive model" begin
## -------------------------------------------- ##
## Data creation
## -------------------------------------------- ##
function ar_ssm(series, order)
inputs = [reverse!(series[1:order])]
outputs = [series[order + 1]]
for x in series[order+2:end]
push!(inputs, vcat(outputs[end], inputs[end])[1:end-1])
push!(outputs, x)
end
return inputs, outputs
end
rng = StableRNG(1234)
series = randn(rng, 1_000)
## -------------------------------------------- ##
## Inference execution and test inference results
for order in 1:5
inputs, outputs = ar_ssm(series, order)
γ_buffer, θ_buffer, fe = ar_inference(inputs, outputs, order, 15)
@test length(γ_buffer) === 15
@test length(θ_buffer) === 15
@test length(fe) === 15
@test last(fe) < first(fe)
@test all(filter(e -> abs(e) > 1e-3, diff(getvalues(fe))) .< 0)
end
## -------------------------------------------- ##
## Form debug output
base_output = joinpath(pwd(), "_output", "models")
mkpath(base_output)
timestamp = Dates.format(now(), "dd-mm-yyyy-HH-MM")
benchmark_output = joinpath(base_output, "ar_model_benchmark_$(timestamp)_v$(VERSION).txt")
## -------------------------------------------- ##
## Create output benchmarks
inputs5, outputs5 = ar_ssm(series, 5)
benchmark = @benchmark ar_inference($inputs5, $outputs5, 5, 15)#
open(benchmark_output, "w") do io
show(io, MIME("text/plain"), benchmark)
versioninfo(io)
end
## -------------------------------------------- ##
end
@testset "Latent autoregressive model" begin
## -------------------------------------------- ##
## Data creation
## -------------------------------------------- ##
# The following coefficients correspond to stable poles
coefs_ar_5 = [ 0.10699399235785655, -0.5237303489793305, 0.3068897071844715, -0.17232255282458891, 0.13323964347539288 ]
function generate_lar_data(rng, n, θ, γ, τ)
order = length(θ)
states = Vector{Vector{Float64}}(undef, n + 3order)
observations = Vector{Float64}(undef, n + 3order)
γ_std = sqrt(inv(γ))
τ_std = sqrt(inv(γ))
states[1] = randn(rng, order)
for i in 2:(n + 3order)
states[i] = vcat(rand(rng, Normal(dot(θ, states[i - 1]), γ_std)), states[i-1][1:end-1])
observations[i] = rand(rng, Normal(states[i][1], τ_std))
end
return states[1+3order:end], observations[1+3order:end]
end
# Seed for reproducibility
rng = StableRNG(123)
# Number of observations in synthetic dataset
n = 500
# AR process parameters
real_γ = 5.0
real_τ = 5.0
real_θ = coefs_ar_5
states, observations = generate_lar_data(rng, n, real_θ, real_γ, real_τ)
## -------------------------------------------- ##
## Inference execution
# AR order 1
γ, θ, xs, fe = lar_inference(observations, 1, Univariate, ARsafe(), 15, real_τ)
@test length(xs) === n
@test length(γ) === 15
@test length(θ) === 15
@test length(fe) === 15
@test abs(last(fe) - 518.9182342) < 0.01
@test all(filter(e -> abs(e) > 1e-3, diff(getvalues(fe))) .< 0)
for i in 1:4
γ, θ, xs, fe = lar_inference(observations, i, Multivariate, ARsafe(), 15, real_τ)
@test length(xs) === n
@test length(γ) === 15
@test length(θ) === 15
@test length(fe) === 15
end
# AR order 5
γ, θ, xs, fe = lar_inference(observations, length(real_θ), Multivariate, ARsafe(), 15, real_τ)
## -------------------------------------------- ##
## Test inference results
@test length(xs) === n
@test length(γ) === 15
@test length(θ) === 15
@test length(fe) === 15
@test abs(last(fe) - 514.66086) < 0.01
@test all(filter(e -> abs(e) > 1e-1, diff(getvalues(fe))) .< 0)
@test (mean(last(γ)) - 3.0std(last(γ)) < real_γ < mean(last(γ)) + 3.0std(last(γ)))
## -------------------------------------------- ##
## Form debug output
base_output = joinpath(pwd(), "_output", "models")
mkpath(base_output)
timestamp = Dates.format(now(), "dd-mm-yyyy-HH-MM")
plot_output = joinpath(base_output, "lar_model_plot_$(timestamp)_v$(VERSION).png")
benchmark_output = joinpath(base_output, "lar_model_benchmark_$(timestamp)_v$(VERSION).txt")
## -------------------------------------------- ##
## Create output plots
p1 = plot(first.(states), label="Hidden state")
p1 = scatter!(p1, observations, label="Observations")
p1 = plot!(p1, first.(mean.(xs)), ribbon = sqrt.(first.(var.(xs))), label="Inferred states", legend = :bottomright)
p2 = plot(mean.(γ), ribbon = std.(γ), label = "Inferred transition precision", legend = :bottomright)
p2 = plot!([ real_γ ], seriestype = :hline, label = "Real transition precision")
p3 = plot(getvalues(fe), label = "Bethe Free Energy")
p = plot(p1, p2, p3, layout = @layout([ a; b c ]))
savefig(p, plot_output)
## -------------------------------------------- ##
## Create output benchmarks
benchmark = @benchmark lar_inference($observations, length($real_θ), Multivariate, ARsafe(), 15, $real_τ) seconds=15
open(benchmark_output, "w") do io
show(io, MIME("text/plain"), benchmark)
versioninfo(io)
end
## -------------------------------------------- ##
end
end
end
|
{
"alphanum_fraction": 0.551393413,
"author": null,
"avg_line_length": 36.1176470588,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "bd4922a74b0c113ecc70e94b36472b911f3c0a57",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2021-11-09T17:19:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-12T18:48:05.000Z",
"max_forks_repo_head_hexsha": "f3e848ab171e0786e3d8eb6a0843dbf6dacc7415",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "HoangMHNguyen/ReactiveMP.jl",
"max_forks_repo_path": "test/models/test_ar.jl",
"max_issues_count": 58,
"max_issues_repo_head_hexsha": "f3e848ab171e0786e3d8eb6a0843dbf6dacc7415",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T08:50:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-17T16:07:47.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "HoangMHNguyen/ReactiveMP.jl",
"max_issues_repo_path": "test/models/test_ar.jl",
"max_line_length": 128,
"max_stars_count": 46,
"max_stars_repo_head_hexsha": "f3e848ab171e0786e3d8eb6a0843dbf6dacc7415",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "HoangMHNguyen/ReactiveMP.jl",
"max_stars_repo_path": "test/models/test_ar.jl",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T15:52:52.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-28T13:18:20.000Z",
"num_tokens": 3073,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 11052
}
|
from azureml.contrib.services.aml_request import AMLRequest, rawhttp
from azureml.contrib.services.aml_response import AMLResponse
from azureml.core.model import Model
import torch
from unet import UNet
from collections import OrderedDict
import numpy as np
from PIL import Image
from torchvision import transforms
import torch as t
from torchvision.transforms import ToPILImage
import io
def init():
global unet
global device
model_path = Model.get_model_path(model_name='brain-segmentation-pytorch')
#model_path = Model.get_model_path(model_name='unet.pt')
print("Loading model from", model_path)
device = torch.device("cpu" if not torch.cuda.is_available() else "cuda:0")
print("Using device", device)
state_dict = torch.load(model_path, map_location=device)
unet = UNet(in_channels=3, out_channels=1)
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[7:]
new_state_dict[name] = v
unet.load_state_dict(new_state_dict)
if torch.cuda.is_available():
unet = unet.to(device)
@rawhttp
def run(request):
if request.method == 'POST':
reqBody = request.get_data(False)
resp = score(reqBody)
headers = {
'Content-Type': 'image/png'
}
return AMLResponse(resp, 200, headers)
if request.method == 'GET':
respBody = str.encode("GET is not supported")
return AMLResponse(respBody, 405)
return AMLResponse("bad request", 500)
def score(data):
input_image = Image.open(io.BytesIO(data))
m, s = np.mean(input_image, axis=(0, 1)), np.std(input_image, axis=(0, 1))
preprocess = transforms.Compose([
transforms.ToTensor(),
])
input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0)
input_batch = input_batch.to(device)
with torch.no_grad():
output = unet(input_batch)
result = torch.round(output[0]).cpu()
print(result)
to_img = ToPILImage()
mask = to_img(result)
imgByteArr = io.BytesIO()
mask.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
return imgByteArr
def test():
init()
with open("TCGA_CS_4944.png", 'rb') as f:
content = f.read()
result = score(content)
with open("TCGA_CS_4944_maskresult.png", "wb") as aaff:
aaff.write(result)
|
{
"alphanum_fraction": 0.6654244306,
"author": null,
"avg_line_length": 25.6914893617,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "8e7bf7baea79ed6468ddffecb44a796822bf04a3",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-09-10T17:34:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-04-01T16:23:51.000Z",
"max_forks_repo_head_hexsha": "f0fa5b15cfad19f6b04bb309a965726c25c39e03",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mkoivi-ms/unet-pytorch-azureml",
"max_forks_repo_path": "model/score.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f0fa5b15cfad19f6b04bb309a965726c25c39e03",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mkoivi-ms/unet-pytorch-azureml",
"max_issues_repo_path": "model/score.py",
"max_line_length": 79,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "f0fa5b15cfad19f6b04bb309a965726c25c39e03",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mkoivi-ms/unet-pytorch-azureml",
"max_stars_repo_path": "model/score.py",
"max_stars_repo_stars_event_max_datetime": "2020-06-28T05:24:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-06T10:15:21.000Z",
"num_tokens": 593,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2415
}
|
import numpy as np
# general-purpose data munging funcs
def deleteCols(df, cols):
df.drop(cols, inplace=True, axis=1)
def renameColAtIdx(df, idx, newName):
df.columns.values[idx] = newName
def stripColNames(df, chars=None):
df.rename(columns=lambda x: x.strip(chars), inplace=True)
def sortColsByName(df):
df.sort_index(axis=1, inplace=True)
def removeEmptyRowsAndCols(df):
df.dropna(axis=0, how='all', inplace=True)
df.dropna(axis=1, how='all', inplace=True)
def removeColsContaining(df, str):
for colName in df.columns.values:
if str in colName:
df.drop(colName, axis=1, inplace=True)
def makeColumnFirst(df, colName):
colNames = list(df.columns.values)
colNames.remove(colName)
colNames.insert(0, colName)
return df[colNames]
def toPrettyCsv(df, path):
# df.to_csv(path, index=False, float_format='%.3f')
df.to_csv(path, float_format='%.3f')
def groupXbyY(X, y):
"""Given an iterable X and a set of labels Y, returns a list whose elements
are all the values of X that share a given label. Only tested with 2D
arrays as X and 1D arrays as Y"""
idxs = [np.where(y == val)[0] for val in np.unique(y).tolist()]
return [X[idx] for idx in idxs]
|
{
"alphanum_fraction": 0.6797124601,
"author": null,
"avg_line_length": 25.04,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "c2f15de48ad5f4878f5007402e9859568a8eb502",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "18d6e8509f2f35719535e1de6c88874ec533cfb9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "icdm-extract/extract",
"max_forks_repo_path": "python/analyze/classify/munge.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "18d6e8509f2f35719535e1de6c88874ec533cfb9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "icdm-extract/extract",
"max_issues_repo_path": "python/analyze/classify/munge.py",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "18d6e8509f2f35719535e1de6c88874ec533cfb9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "icdm-extract/extract",
"max_stars_repo_path": "python/analyze/classify/munge.py",
"max_stars_repo_stars_event_max_datetime": "2019-03-05T01:17:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-05T01:17:05.000Z",
"num_tokens": 341,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1252
}
|
Set Implicit Arguments.
Require Import Morphisms Lia List.
From Undecidability.HOU Require Import calculus.calculus.
Import ListNotations ArsInstances.
(* * Conservativity *)
Section Constants.
(* ** Constant Operations *)
Section ConstantsOfTerm.
Context {X: Const}.
Implicit Types (s t: exp X).
Fixpoint consts s :=
match s with
| var x => nil
| const c => [c]
| lambda s => consts s
| app s t => consts s ++ consts t
end.
Definition Consts S := (flat_map consts S).
Lemma Consts_consts s S:
s ∈ S -> consts s ⊆ Consts S.
Proof.
unfold Consts; eauto using flat_map_in_incl.
Qed.
Lemma Consts_montone S T:
S ⊆ T -> Consts S ⊆ Consts T.
Proof.
unfold Consts; eauto using flat_map_incl.
Qed.
Lemma consts_ren delta s:
consts (ren delta s) = consts s.
Proof.
induction s in delta |-*; cbn; intuition idtac; congruence.
Qed.
Lemma vars_subst_consts x s sigma:
x ∈ vars s -> consts (sigma x) ⊆ consts (sigma • s).
Proof.
intros H % vars_varof; induction H in sigma |-*; cbn; [auto with listdb..|].
rewrite <-IHvarof; cbn; unfold funcomp; now rewrite consts_ren.
Qed.
Lemma consts_subst_in x sigma s:
x ∈ consts (sigma • s) -> x ∈ consts s \/
exists y, y ∈ vars s /\ x ∈ consts (sigma y).
Proof.
induction s in sigma |-*.
- right; exists f; intuition.
- cbn; intuition.
- intros H % IHs; cbn -[vars]; intuition idtac.
destruct H0 as [[]]; cbn -[vars] in *; intuition idtac.
right. exists n. intuition eauto with listdb.
unfold funcomp in H1; now rewrite consts_ren in H1.
- cbn; simplify; intuition idtac.
+ specialize (IHs1 _ H0); intuition idtac.
destruct H as [y]; right; exists y; intuition (auto with datatypes).
+ specialize (IHs2 _ H0); intuition idtac.
destruct H as [y]; right; exists y; intuition (auto with datatypes).
Qed.
Lemma consts_subset_step s t:
s > t -> consts t ⊆ consts s.
Proof.
induction 1; cbn; [|auto with listdb..].
subst. unfold beta.
intros x ? % consts_subst_in; simplify.
destruct H; [tauto|].
destruct H as [[|y] ?]; cbn in *; intuition.
Qed.
Lemma consts_subset_steps s t:
s >* t -> consts t ⊆ consts s.
Proof.
induction 1; firstorder using consts_subset_step.
Qed.
Lemma consts_subst_vars sigma s:
consts (sigma • s) ⊆ consts s ++ Consts (map sigma (vars s)).
Proof.
intros x [|[y]] % consts_subst_in; simplify; intuition idtac.
right; eapply Consts_consts; eauto using in_map.
Qed.
Lemma consts_Lam k s:
consts (Lambda k s) === consts s.
Proof.
induction k; cbn; intuition easy.
Qed.
Lemma consts_AppL S t:
consts (AppL S t) === Consts S ++ consts t.
Proof.
induction S; cbn; [trivial with listdb|].
rewrite IHS; now rewrite app_assoc.
Qed.
Lemma consts_AppR s T:
consts (AppR s T) === consts s ++ Consts T.
Proof.
induction T; cbn; [auto with listdb|].
rewrite IHT.
split; intros c; simplify; intuition.
Qed.
End ConstantsOfTerm.
Section ConstantSubstitution.
Implicit Types (X Y Z : Const).
Fixpoint subst_consts {X Y} (kappa: X -> exp Y) s :=
match s with
| var x => var x
| const c => kappa c
| lambda s => lambda (subst_consts (kappa >> ren shift) s)
| app s t => (subst_consts kappa s) (subst_consts kappa t)
end.
Lemma ren_subst_consts_commute X Y (zeta: X -> exp Y) delta s:
subst_consts (zeta >> ren delta) (ren delta s) = ren delta (subst_consts zeta s).
Proof.
induction s in delta, zeta |-*; cbn; trivial.
- f_equal. rewrite <-IHs. f_equal.
asimpl. reflexivity.
- now rewrite IHs1, IHs2.
Qed.
Lemma subst_consts_comp X Y Z (zeta: X -> exp Y) (kappa: Y -> exp Z) s:
subst_consts kappa (subst_consts zeta s) =
subst_consts (zeta >> subst_consts kappa) s.
Proof.
induction s in zeta, kappa |-*; cbn; trivial.
- f_equal. rewrite IHs. f_equal. fext.
unfold funcomp at 4; unfold funcomp at 4.
intros; rewrite <-ren_subst_consts_commute.
reflexivity.
- now rewrite IHs1, IHs2.
Qed.
Lemma subst_consts_ident Y zeta s:
(forall x: Y, x ∈ consts s -> zeta x = const x) -> subst_consts zeta s = s.
Proof.
intros; induction s in zeta, H |-*; cbn; trivial.
eapply H; cbn; tauto.
rewrite IHs; trivial.
unfold funcomp; now intros x -> % H.
rewrite IHs1, IHs2; trivial.
all: intros; apply H; cbn; simplify; intuition.
Qed.
Lemma subst_const_comm {X Y} (zeta: X -> exp Y) sigma delta s:
(forall x, sigma (delta x) = var x) ->
subst_consts zeta (sigma • s) = (sigma >> subst_consts zeta) • (subst_consts (zeta >> ren delta) s).
Proof.
induction s in zeta, sigma, delta |-*; intros H; cbn.
- reflexivity.
- unfold funcomp; asimpl.
rewrite idSubst_exp; trivial.
intros y; unfold funcomp; cbn.
rewrite H; reflexivity.
- f_equal. erewrite IHs with (delta := 0 .: delta >> shift).
2: intros []; cbn; unfold funcomp; trivial; rewrite H; reflexivity.
f_equal; [| now asimpl].
fext; intros []; cbn; trivial.
unfold funcomp at 2.
now rewrite ren_subst_consts_commute.
- erewrite IHs1, IHs2; eauto.
Qed.
#[export] Instance step_subst_consts X Y:
Proper (Logic.eq ++> step ++> step) (@subst_consts X Y).
Proof.
intros ? zeta -> s t H; induction H in zeta |-*; cbn; [|eauto..].
econstructor; subst; unfold beta.
erewrite subst_const_comm with (delta := shift).
f_equal. fext.
all: intros []; cbn; eauto.
Qed.
#[export] Instance steps_subst_consts X Y:
Proper (Logic.eq ++> star step ++> star step) (@subst_consts X Y).
Proof.
intros ? zeta -> s t H; induction H in zeta |-*; cbn; trivial; rewrite H; eauto.
Qed.
#[export] Instance equiv_subst_consts X Y:
Proper (Logic.eq ++> equiv step ++> equiv step) (@subst_consts X Y).
Proof.
intros ? zeta -> s t [v [H1 H2]] % church_rosser; trivial;
now rewrite H1, H2.
Qed.
Lemma subst_consts_consts X Y (zeta: X -> exp Y) (s: exp X):
consts (subst_consts zeta s) === Consts (map zeta (consts s)).
Proof.
unfold Consts; induction s in zeta |-*; cbn; simplify; [eauto with listdb|eauto with listdb|..].
- rewrite IHs.
unfold funcomp; rewrite <-map_map, !flat_map_concat_map, map_map.
erewrite map_ext with (g := consts); intuition eauto with listdb.
now rewrite consts_ren.
- rewrite IHs1, IHs2, !flat_map_concat_map; simplify.
now rewrite concat_app.
Qed.
Lemma consts_in_subst_consts X Y (kappa: X -> exp Y) c s:
c ∈ consts (subst_consts kappa s) -> exists d, d ∈ consts s /\ c ∈ consts (kappa d).
Proof.
rewrite subst_consts_consts.
unfold Consts; rewrite in_flat_map; intros [e []]; mapinj.
exists x; intuition.
Qed.
Lemma subst_consts_up Y Z (zeta: Y -> exp Z) (sigma: fin -> exp Y):
up (sigma >> subst_consts zeta) = up sigma >> subst_consts (zeta >> ren shift).
Proof.
fext; intros []; cbn; trivial.
unfold funcomp at 1 2.
now rewrite <-ren_subst_consts_commute.
Qed.
Lemma subst_const_comm_id Y zeta sigma (s: exp Y):
subst_consts zeta s = s ->
(sigma >> subst_consts zeta) • s = subst_consts zeta (sigma • s).
Proof.
induction s in zeta, sigma |-*; cbn; [trivial|congruence|..].
- injection 1 as H. f_equal.
rewrite <-IHs; trivial.
now rewrite subst_consts_up.
- injection 1 as H. f_equal; eauto.
Qed.
Lemma typing_constants X n Gamma s A :
Gamma ⊢(n) s : A -> forall c, c ∈ consts s -> ord (ctype X c) <= S n.
Proof.
induction 1; cbn; intuition idtac; subst; trivial.
simplify in H1; intuition.
Qed.
Lemma typing_Consts X c n Gamma S' L:
Gamma ⊢₊(n) S' : L -> c ∈ Consts S' -> ord (ctype X c) <= S n.
Proof.
induction 1; cbn; simplify; intuition eauto using typing_constants.
Qed.
Lemma preservation_consts X Y Gamma s A (zeta: X -> exp Y):
Gamma ⊢ s : A -> (forall x, x ∈ consts s -> Gamma ⊢ zeta x : ctype X x) ->
Gamma ⊢ subst_consts zeta s : A.
Proof.
induction 1 in zeta |-*; cbn; [eauto|eauto|..].
- intros H'. econstructor. eapply IHtyping.
intros; eapply preservation_under_renaming; [eauto|].
intros ?; cbn; eauto.
- intros H'. econstructor.
eapply IHtyping1; intros ??; eapply H'; simplify; intuition idtac.
eapply IHtyping2; intros ??; eapply H'; simplify; intuition idtac.
Qed.
Lemma ordertyping_preservation_consts X Y n Gamma s A (zeta: X -> exp Y):
Gamma ⊢(n) s : A -> (forall x, x ∈ consts s -> Gamma ⊢(n) zeta x : ctype X x) ->
Gamma ⊢(n) subst_consts zeta s : A.
Proof.
induction 1 in zeta |-*; cbn; [eauto|eauto|..].
- intros H'. econstructor. eapply IHordertyping.
intros; eapply ordertyping_preservation_under_renaming; [eauto|].
intros ?; cbn; eauto.
- intros H'. econstructor.
eapply IHordertyping1; intros ??; eapply H'; simplify; intuition idtac.
eapply IHordertyping2; intros ??; eapply H'; simplify; intuition idtac.
Qed.
Lemma subst_consts_Lambda Y Z (zeta: Y -> exp Z) k s:
subst_consts zeta (Lambda k s) = Lambda k (subst_consts (zeta >> ren (plus k)) s).
Proof.
induction k in zeta |-*; cbn; asimpl; trivial.
f_equal. rewrite IHk. f_equal. f_equal.
asimpl. fext; intros x; unfold funcomp; f_equal; fext; intros ?.
unfold shift; simplify; f_equal; lia.
Qed.
Lemma subst_consts_AppL X Y (tau: X -> exp Y) S t:
subst_consts tau (AppL S t) = AppL (map (subst_consts tau) S) (subst_consts tau t).
Proof.
induction S; cbn; congruence.
Qed.
Lemma subst_consts_AppR X Y (tau: X -> exp Y) s T:
subst_consts tau (AppR s T) = AppR (subst_consts tau s) (map (subst_consts tau) T).
Proof.
induction T; cbn; congruence.
Qed.
End ConstantSubstitution.
End Constants.
|
{
"alphanum_fraction": null,
"author": "uds-psl",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/HOU/concon/conservativity_constants.v",
"reason": null,
"repo": "coq-library-undecidability",
"save_path": "github-repos/coq/uds-psl-coq-library-undecidability",
"sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214",
"size": null
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append('build')
import cv2 as cv
import numpy as np
import bing
binger = bing.BING('build/ObjectnessTrainedModel', 2, 8, 2)
img = cv.imread('sample.jpg')
canvas = np.zeros((img.shape[0], img.shape[1]), dtype=np.float32)
bbox = binger.objectness(img)
for b in bbox[:2000]:
x1, y1, x2, y2 = [int(a) for a in b[:4]]
s = b[-1]
canvas[y1:y2, x1:x2] += 1
canvas /= np.max(canvas)
cv.imwrite('sample_result.jpg', canvas * 255)
|
{
"alphanum_fraction": 0.6448412698,
"author": null,
"avg_line_length": 21,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "2c4af865c26cda33e4611d38cd11c24ae21a20b2",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2019-05-16T12:21:21.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-03-09T01:13:32.000Z",
"max_forks_repo_head_hexsha": "cd6abf1bd445e8de9423e0326daf6103f5a56dd6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "pkhdipraja/pybing",
"max_forks_repo_path": "scripts/test_bing.py",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "cd6abf1bd445e8de9423e0326daf6103f5a56dd6",
"max_issues_repo_issues_event_max_datetime": "2021-04-29T20:33:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-08-25T15:18:51.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "pkhdipraja/pybing",
"max_issues_repo_path": "scripts/test_bing.py",
"max_line_length": 65,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "cd6abf1bd445e8de9423e0326daf6103f5a56dd6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "pkhdipraja/pybing",
"max_stars_repo_path": "scripts/test_bing.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-15T09:44:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-29T06:48:33.000Z",
"num_tokens": 171,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 504
}
|
SUBROUTINE HCLPNL ( xllf, yllf, xurf, yurf, iret )
C************************************************************************
C* HCLPNL - GN *
C* *
C* This subroutine will clear a particular sub-region of the screen. *
C* *
C* HCLPNL ( XLLF, YLLF, XURF, YURF, IRET ) *
C* *
C* Input parameters: *
C* XLLF REAL Lower left x ( device coord. ) *
C* YLLF REAL Lower left y ( device coord. ) *
C* XURF REAL Upper right x ( device coord. ) *
C* YURF REAL Upper right y ( device coord. ) *
C* *
C* Output parameters: *
C* IRET INTEGER Return code *
C** *
C* Log: *
C* K. Tyle/GSC 2/97 *
C* S. Maxwell/GSC 6/97 Documentation changes *
C************************************************************************
INCLUDE 'ERROR.PRM'
C
iret = NORMAL
C
RETURN
END
|
{
"alphanum_fraction": 0.4538198404,
"author": null,
"avg_line_length": 31.3214285714,
"converted": null,
"ext": "f",
"file": null,
"hexsha": "a905229a28327cf2445b56dc4d87ad7008ad2da4",
"include": null,
"lang": "FORTRAN",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 27,
"max_forks_repo_forks_event_max_datetime": "2022-03-18T18:23:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-06-06T21:55:14.000Z",
"max_forks_repo_head_hexsha": "e7c477814d7084c87d3313c94e192d13d8341fa1",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "oxelson/gempak",
"max_forks_repo_path": "gempak/source/driver/active/gn/hclpnl.f",
"max_issues_count": 60,
"max_issues_repo_head_hexsha": "e7c477814d7084c87d3313c94e192d13d8341fa1",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T16:22:42.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-11T21:36:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "oxelson/gempak",
"max_issues_repo_path": "gempak/source/driver/active/gn/hclpnl.f",
"max_line_length": 73,
"max_stars_count": 42,
"max_stars_repo_head_hexsha": "e7c477814d7084c87d3313c94e192d13d8341fa1",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "oxelson/gempak",
"max_stars_repo_path": "gempak/source/driver/active/gn/hclpnl.f",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T22:36:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-03T15:26:21.000Z",
"num_tokens": 292,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 877
}
|
(** First step of a splitter refinement; indexed representation, and handle all rules with at most one nonterminal; leave a reflective goal *)
Require Import Coq.Strings.String.
Require Import Fiat.Common.List.ListFacts.
Require Import Fiat.ADTNotation.BuildADT Fiat.ADTNotation.BuildADTSig.
Require Import Fiat.ADT.ComputationalADT.
Require Import Fiat.ADTRefinement.
Require Import Fiat.ADTRefinement.BuildADTRefinements.HoneRepresentation.
Require Import Fiat.Parsers.ParserADTSpecification.
Require Import Fiat.Parsers.Refinement.IndexedAndAtMostOneNonTerminalReflective.
Require Import Fiat.Parsers.StringLike.Core.
Require Import Fiat.Parsers.ContextFreeGrammar.Precompute.
Require Import Fiat.Parsers.BaseTypes.
Require Import Fiat.Parsers.Splitters.RDPList.
Require Import Fiat.Parsers.ContextFreeGrammar.Carriers.
Require Import Fiat.Parsers.ContextFreeGrammar.PreNotations.
Local Open Scope string_scope.
(* TODO: find a better place for this *)
#[global]
Instance match_item_Proper {Char A}
: Proper (eq ==> pointwise_relation _ eq ==> pointwise_relation _ eq ==> eq)
(fun (it : Core.item Char) T NT
=> match it return A with
| Core.Terminal t => T t
| Core.NonTerminal nt => NT nt
end).
Proof.
intros []; repeat intro; subst; auto.
Qed.
#[global]
Instance option_rect_Proper {A P}
: Proper (pointwise_relation _ eq ==> eq ==> eq ==> eq)
(@option_rect A (fun _ => P)).
Proof.
intros ?????? []; repeat intro; subst; simpl; auto.
Qed.
Module opt0.
Definition fst {A B} := Eval compute in @fst A B.
Definition snd {A B} := Eval compute in @snd A B.
End opt0.
Global Arguments opt0.fst : simpl never.
Global Arguments opt0.snd : simpl never.
Module opt2.
Definition id {A} := Eval compute in @id A.
Definition fold_right {A B} := Eval compute in @List.fold_right A B.
Definition uniquize_sig {A} : { v : _ | v = @Operations.List.uniquize A }.
Proof.
eexists.
cbv [Operations.List.uniquize Equality.list_bin orb].
change @List.fold_right with @fold_right.
reflexivity.
Defined.
Definition uniquize {A} := Eval cbv [proj1_sig uniquize_sig] in proj1_sig (@uniquize_sig A).
Definition ret_cases_BoolDecR := Eval compute in ret_cases_BoolDecR.
End opt2.
Module opt3.
Definition fold_right {A B} := Eval compute in @List.fold_right A B.
End opt3.
Module opt.
Definition map {A B} := Eval compute in @List.map A B.
Definition flat_map {A B} := Eval compute in @List.flat_map A B.
Definition up_to := Eval compute in @Operations.List.up_to.
Definition length {A} := Eval compute in @List.length A.
Definition nth {A} := Eval compute in @List.nth A.
Definition id {A} := Eval compute in @id A.
Definition combine {A B} := Eval compute in @List.combine A B.
Definition string_beq := Eval compute in Equality.string_beq.
Definition first_index_default {A} := Eval compute in @Operations.List.first_index_default A.
Definition list_bin_eq := Eval compute in list_bin_eq.
Definition filter_out_eq := Eval compute in filter_out_eq.
Definition find {A} := Eval compute in @List.find A.
Definition leb := Eval compute in Compare_dec.leb.
Definition minus := Eval compute in minus.
Definition drop {A} := Eval compute in @Operations.List.drop A.
Definition andb := Eval compute in andb.
Definition nat_rect {A} := Eval compute in @nat_rect A.
Definition option_rect {A} := Eval compute in @option_rect A.
Definition has_only_terminals {Char} := Eval compute in @has_only_terminals Char.
Definition sumbool_of_bool := Eval compute in Sumbool.sumbool_of_bool.
Local Declare Reduction red_fp := cbv [FromAbstractInterpretationDefinitions.fixedpoint_by_abstract_interpretation Fix.aggregate_state Definitions.prestate Definitions.lattice_data Definitions.state FromAbstractInterpretation.fold_grammar initial_nonterminals_data rdp_list_predata rdp_list_initial_nonterminals_data pregrammar_productions FromAbstractInterpretationDefinitions.fold_constraints FromAbstractInterpretationDefinitions.fold_productions' FromAbstractInterpretationDefinitions.fold_production' FromAbstractInterpretationDefinitions.fold_item' of_nonterminal rdp_list_of_nonterminal default_of_nonterminal Lookup_idx FromAbstractInterpretationDefinitions.fold_constraints_Proper FromAbstractInterpretationDefinitions.fold_constraints_ext FromAbstractInterpretationDefinitions.fold_productions'_ext FromAbstractInterpretationDefinitions.fold_production'_ext FromAbstractInterpretationDefinitions.fold_item'_ext FromAbstractInterpretationDefinitions.fold_constraints_extR FromAbstractInterpretationDefinitions.fold_productions'_extR FromAbstractInterpretationDefinitions.fold_production'_extR FromAbstractInterpretationDefinitions.fold_item'_extR Fix.lookup_state FromAbstractInterpretationDefinitions.fold_constraints_Proper_state_beq FromAbstractInterpretationDefinitions.fold_constraints_ProperR].
Definition lookup_state' {G} compiled_productions :=
Eval red_fp in
@Fix.lookup_state
(@FromAbstractInterpretationDefinitions.fixedpoint_by_abstract_interpretation
Ascii.ascii nat FixedLengthLemmas.length_result_lattice
(@FixedLengthLemmas.length_result_aidata Ascii.ascii) G
compiled_productions).
Definition fold_grammar' pp unix
:= Eval red_fp in
let G := {| pregrammar_productions := pp ; nonterminals_unique := unix |} in
(@FromAbstractInterpretation.fold_grammar
Ascii.ascii nat
FixedLengthLemmas.length_result_lattice
(@FixedLengthLemmas.length_result_aidata Ascii.ascii) G).
Definition lookup_state : FMapPositive.PositiveMap.tree (Definitions.lattice_for nat) -> nat -> Definitions.lattice_for nat.
Proof.
let term := match (eval cbv [lookup_state'] in @lookup_state') with
| fun _ _ => ?term => term
end in
exact term.
Defined.
Definition fold_grammar (pp : list (string * Core.productions Ascii.ascii)) : list (opt.productions (Definitions.lattice_for nat)) -> FMapPositive.PositiveMap.t (Definitions.lattice_for nat).
Proof.
let term := match (eval cbv [fold_grammar'] in (@fold_grammar' pp)) with
| fun _ => ?term => term
end in
exact term.
Defined.
Definition collapse_length_result := Eval compute in FixedLengthLemmas.collapse_length_result.
Definition expanded_fallback_list'_body_sig {G} : { b : _ | b = @expanded_fallback_list'_body G }.
Proof.
eexists.
cbv [id
expanded_fallback_list'_body to_production_opt production_carrier_valid production_carrierT rdp_list_predata default_production_carrierT default_nonterminal_carrierT rdp_list_production_carrier_valid default_production_carrier_valid Lookup_idx FixedLengthLemmas.length_of_any FixedLengthLemmas.length_of_any nonterminals_listT rdp_list_nonterminals_listT nonterminals_length initial_nonterminals_data rdp_list_initial_nonterminals_data is_valid_nonterminal of_nonterminal remove_nonterminal ContextFreeGrammar.Core.Lookup rdp_list_of_nonterminal default_of_nonterminal grammar_of_pregrammar rdp_list_remove_nonterminal Lookup_string list_to_productions rdp_list_is_valid_nonterminal If_Then_Else
opt.compile_productions opt.compile_production opt.compile_item opt.compile_nonterminal opt.nonterminal_names FromAbstractInterpretationDefinitions.compile_item_data_of_abstract_interpretation opt.compile_grammar
pregrammar_nonterminals
opt.on_terminal FromAbstractInterpretationDefinitions.on_terminal FixedLengthLemmas.length_result_aidata].
change (@Fix.lookup_state ?v) with (@lookup_state).
change (FromAbstractInterpretation.fold_grammar G) with (fold_grammar (pregrammar_productions G)).
change @fst with @opt.fst.
change @snd with @opt.snd.
change @List.map with @map.
change @List.length with @length.
change Equality.string_beq with string_beq.
change @Operations.List.first_index_default with @first_index_default.
change RDPList.list_bin_eq with list_bin_eq.
change RDPList.filter_out_eq with filter_out_eq.
change @Operations.List.up_to with @up_to.
change @List.find with @find.
change @List.nth with @nth.
change Compare_dec.leb with leb.
change Datatypes.andb with andb.
change (?x - ?y) with (minus x y).
change @Operations.List.drop with @drop.
change @Datatypes.nat_rect with @nat_rect.
change @Datatypes.option_rect with @option_rect.
change @Sumbool.sumbool_of_bool with sumbool_of_bool.
change @FixedLengthLemmas.collapse_length_result with collapse_length_result.
change @IndexedAndAtMostOneNonTerminalReflective.has_only_terminals with @has_only_terminals.
reflexivity.
Defined.
Definition expanded_fallback_list'_body' (ps : list (String.string * Core.productions Ascii.ascii)) : default_production_carrierT -> ret_cases.
Proof.
let term := constr:(fun H : NoDupR _ _ => proj1_sig (@expanded_fallback_list'_body_sig {| pregrammar_productions := ps |})) in
let term := (eval cbv [proj1_sig expanded_fallback_list'_body_sig pregrammar_productions] in term) in
let term := match term with
| (fun _ => ?term) => term
end in
exact term.
Defined.
Definition expanded_fallback_list'_body (ps : list (String.string * Core.productions Ascii.ascii))
: FMapPositive.PositiveMap.t (Definitions.lattice_for nat) -> default_production_carrierT -> ret_cases.
Proof.
let term := (eval cbv [expanded_fallback_list'_body'] in (@expanded_fallback_list'_body' ps)) in
let fg := lazymatch term with context[fold_grammar ps ?v] => constr:(fold_grammar ps v) end in
let term := match (eval pattern fg in term) with
| ?term _ => term
end in
exact term.
Defined.
Definition ret_cases_to_comp_sig {HSLM G} : { r : _ | r = @ret_cases_to_comp HSLM G }.
Proof.
eexists.
cbv [ret_cases_to_comp to_production rdp_list_predata rdp_list_to_production default_to_production Lookup_idx].
change @Operations.List.drop with @drop.
change @snd with @opt.snd.
change @fst with @opt.fst.
change @List.nth with @nth.
change (?x - ?y) with (minus x y).
change @List.length with @length.
change @List.map with @map.
reflexivity.
Defined.
Definition ret_cases_to_comp {HSLM G}
:= Eval cbv [proj1_sig ret_cases_to_comp_sig] in proj1_sig (@ret_cases_to_comp_sig HSLM G).
Definition premap_expanded_fallback_list'_body (G : pregrammar' Ascii.ascii) : list (nat * (nat * nat)).
Proof.
let term := match (eval cbv [rindexed_spec rindexed_spec' default_production_carrierT default_nonterminal_carrierT expanded_fallback_list' forall_reachable_productions_if_eq] in (fun HSLM HSL => @rindexed_spec HSLM HSL G)) with
| context[List.map (fun x => (x, ?f x)) ?ls] => ls
end in
exact term.
Defined.
Definition Let_In {A B} (x : A) (f : A -> B) := let y := x in f y.
Definition map_expanded_fallback_list'_body (G : pregrammar' Ascii.ascii) fg : list ((nat * (nat * nat)) * ret_cases)
:= map (fun x => (x, @expanded_fallback_list'_body G fg x)) (premap_expanded_fallback_list'_body G).
Local Hint Immediate FromAbstractInterpretationDefinitions.compile_item_data_of_abstract_interpretation : typeclass_instances.
Definition expanded_fallback_list_body (G : pregrammar' Ascii.ascii) : list ((nat * (nat * nat)) * ret_cases)
:= Let_In (opt.compile_grammar G)
(fun compiled_productions
=> Let_In
(fold_grammar G compiled_productions)
(map_expanded_fallback_list'_body G)).
End opt.
Class opt_of {T} (term : T) := mk_opt_of : T.
(*Class do_idtac {T} (x : T) := dummy_idtac : True.
Local Hint Extern 0 (do_idtac ?msg) => idtac "<infomsg>" msg "</infomsg>"; exact I : typeclass_instances.
Local Ltac cidtac term := constr:(_ : do_idtac term).
Local Ltac opt_of_context term :=
match (eval cbv beta iota zeta in term) with
| context G[map snd (opt.id ?ls)]
=> let G' := context G[opt.id (opt.map opt.snd ls)] in
opt_of_context G'
| context G[List.length (opt.id ?ls)]
=> let G' := context G[opt.id (opt.length ls)] in
opt_of_context G'
| context G[minus (opt.id ?x) (opt.id ?y)]
=> let G' := context G[opt.id (opt.minus x y)] in
opt_of_context G'
| context G[Operations.List.up_to (opt.id ?n)]
=> let G' := context G[opt.id (opt.up_to n)] in
opt_of_context G'
| context G[S (opt.id ?n)]
=> let G' := context G[opt.id (S n)] in
opt_of_context G'
| context G[ret (opt.id ?n)]
=> let G' := context G[opt.id (ret n)] in
opt_of_context G'
| context G[pair (opt.id ?x) (opt.id ?y)]
=> let G' := context G[opt.id (pair x y)] in
opt_of_context G'
| context G[cons (opt.id ?x) (opt.id ?y)]
=> let G' := context G[opt.id (cons x y)] in
opt_of_context G'
| context G[Operations.List.uniquize (opt.id ?beq) (opt.id ?ls)]
=> let G' := context G[opt.id (opt.uniquize beq ls)] in
opt_of_context G'
| context G[nth (opt.id ?n) (opt.id ?ls) (opt.id ?d)]
=> let G' := context G[opt.id (opt.nth n ls d)] in
opt_of_context G'
| context G[List.combine (opt.id ?a) (opt.id ?b)]
=> let G' := context G[opt.id (opt.combine a b)] in
opt_of_context G'
| context G[map (opt.id ?f) (opt.id ?ls)]
=> let G' := context G[opt.id (opt.map f ls)] in
let G' := (eval cbv beta in G') in
opt_of_context G'
| context G[flat_map (opt.id ?f) (opt.id ?ls)]
=> let G' := context G[opt.id (opt.flat_map f ls)] in
let G' := (eval cbv beta in G') in
opt_of_context G'
| context G[opt.flat_map (opt.id ?f) ?ls]
=> let G' := context G[opt.flat_map f ls] in
opt_of_context G'
| context G[opt.map (opt.id ?f) ?ls]
=> let G' := context G[opt.map f ls] in
opt_of_context G'
| context G[fun x => opt.id (@?f x)]
=> let G' := context G[opt.id f] in
opt_of_context G'
| context G[flat_map ?f (opt.id ?ls)]
=> let f' := constr:(fun x => _ : opt_of (f (opt.id x))) in
let G' := context G[opt.id (opt.flat_map f' ls)] in
let G' := (eval cbv beta in G') in
opt_of_context G'
| context G[map ?f (opt.id ?ls)]
=> let f' := constr:(fun x => _ : opt_of (f (opt.id x))) in
let G' := context G[opt.id (opt.map f' ls)] in
let G' := (eval cbv beta in G') in
opt_of_context G'
| context G[fold_right ?f (opt.id ?d) (opt.id ?ls)]
=> let f' := constr:(fun x => _ : opt_of (f (opt.id x))) in
let G' := context G[opt.id (opt.fold_right f' d ls)] in
let G' := (eval cbv beta in G') in
opt_of_context G'
| ?term' => term'
end.*)
Class constr_eq {A} {B} (x : A) (y : B) := make_constr_eq : True.
Local Hint Extern 0 (constr_eq ?x ?y) => constr_eq x y; exact I : typeclass_instances.
Local Ltac opt_of term :=
let retv :=
lazymatch (eval cbv beta iota zeta in term) with
| List.map snd (opt.id ?ls)
=> constr:(opt.id (opt.map opt.snd ls))
| List.length (opt.id ?ls)
=> constr:(opt.id (opt.length ls))
| minus (opt.id ?x) (opt.id ?y)
=> constr:(opt.id (opt.minus x y))
| Operations.List.up_to (opt.id ?n)
=> constr:(opt.id (opt.up_to n))
| @fst ?A ?B (opt.id ?n)
=> constr:(opt.id (@opt.fst A B n))
| @snd ?A ?B (opt.id ?n)
=> constr:(opt.id (@opt.snd A B n))
| S (opt.id ?n)
=> constr:(opt.id (S n))
| Core.ret (opt.id ?n)
=> constr:(opt.id (Core.ret n))
| pair (opt.id ?x) (opt.id ?y)
=> constr:(opt.id (pair x y))
| cons (opt.id ?x) (opt.id ?y)
=> constr:(opt.id (cons x y))
| Operations.List.uniquize (opt2.id ?beq) (opt.id ?ls)
=> constr:(opt2.id (opt2.uniquize beq ls))
| Operations.List.uniquize (opt.id ?beq) (opt.id ?ls)
=> constr:(opt2.id (opt2.uniquize beq ls))
| List.nth (opt.id ?n) (opt.id ?ls) (opt.id ?d)
=> constr:(opt.id (opt.nth n ls d))
| List.combine (opt.id ?a) (opt.id ?b)
=> constr:(opt.id (opt.combine a b))
| List.map (fun x : ?T => opt.id ?f) (opt.id ?ls)
=> constr:(opt.id (opt.map (fun x : T => f) ls))
| List.map (opt.id ?f) (opt.id ?ls)
=> constr:(opt.id (opt.map f ls))
| List.flat_map (opt.id ?f) (opt.id ?ls)
=> constr:(opt.id (opt.flat_map f ls))
| opt.flat_map (opt.id ?f) ?ls
=> constr:(opt.flat_map f ls)
| opt.map (opt.id ?f) ?ls
=> constr:(opt.map f ls)
| fun x => opt.id (@?f x)
=> constr:(opt.id f)
| List.flat_map ?f (opt.id ?ls)
=> let f' := constr:(fun x => _ : opt_of (f (opt.id x))) in
let G' := constr:(opt.id (opt.flat_map f' ls)) in
(eval cbv beta in G')
| @List.map ?A ?B ?f (opt.id ?ls)
=> let f' := constr:(fun x => _ : opt_of (f (opt.id x))) in
let G' := constr:(opt.id (@opt.map A B f' ls)) in
let G' := (eval cbv beta in G') in
G'
| List.fold_right orb false (opt.id ?ls)
=> constr:(opt2.fold_right orb false ls)
| List.fold_right orb false (opt2.id ?ls)
=> constr:(opt2.fold_right orb false ls)
| List.fold_right ?f (opt.id ?d) (opt.id ?ls)
=> let f' := constr:(fun x => _ : opt_of (f (opt2.id x))) in
let G' := constr:(opt2.id (opt2.fold_right f' d ls)) in
(eval cbv beta in G')
| List.fold_right ?f (opt.id ?d) (opt2.id ?ls)
=> let f' := constr:(fun x => _ : opt_of (f (opt2.id x))) in
let G' := constr:(opt2.id (opt2.fold_right f' d ls)) in
(eval cbv beta in G')
| opt.id ?f ?x
=> constr:(opt.id (f x))
| opt2.id ?f ?x
=> constr:(opt2.id (f x))
| ?f (opt.id ?x)
=> let f' := opt_of f in
let term' := (eval cbv beta iota zeta in (f' (opt.id x))) in
match constr:(Set) with
| _
=> let dummy := constr:(_ : constr_eq term' (f (opt.id x))) in
term'
| _
=> opt_of term'
end
| ?f (opt2.id ?x)
=> let f' := opt_of f in
let term' := (eval cbv beta iota zeta in (f' (opt2.id x))) in
match constr:(Set) with
| _
=> let dummy := constr:(_ : constr_eq term' (f (opt2.id x))) in
term'
| _
=> opt_of term'
end
| ?f ?x => let f' := opt_of f in
let x' := opt_of x in
let term' := (eval cbv beta iota zeta in (f' x')) in
lazymatch x' with
| opt.id ?x''
=> opt_of term'
| _ => term'
end(*
match term' with
| f x => term'
| ?term'' => opt_of term''
end*)
| (fun x : ?T => ?f)
=> (eval cbv beta iota zeta in (fun x : T => _ : opt_of f))
| if ?b then ?x else ?y
=> let b' := opt_of b in
let x' := opt_of x in
let y' := opt_of y in
constr:(if b' then x' else y')
| ?term'
=> term'
end in
(*let term' := (eval cbv beta iota zeta in term) in
let dummy := match constr:(Set) with
| _ => let dummy := constr:(_ : constr_eq retv term') in constr:(Set)
| _ => cidtac retv
end in*)
retv.
Local Hint Extern 0 (opt_of ?term) => (let x := opt_of term in exact x) : typeclass_instances.
Section IndexedImpl_opt.
Context {HSLM : StringLikeMin Ascii.ascii} {HSL : StringLike Ascii.ascii} {HSI : StringIso Ascii.ascii}
{HSLP : StringLikeProperties Ascii.ascii} {HSIP : StringIsoProperties Ascii.ascii}
{HSEP : StringEqProperties Ascii.ascii}.
Context (G : pregrammar' Ascii.ascii).
Let predata := @rdp_list_predata _ G.
Local Existing Instance predata.
Definition opt_rindexed_spec_sig : { a : ADT (string_rep Ascii.ascii String default_production_carrierT) | a = rindexed_spec G }.
Proof.
eexists.
cbv [rindexed_spec rindexed_spec' default_production_carrierT default_nonterminal_carrierT expanded_fallback_list' forall_reachable_productions_if_eq].
simpl @production_carrierT.
cbv [default_production_carrierT default_nonterminal_carrierT].
lazymatch goal with
| [ |- context g[List.map (fun x => (x, expanded_fallback_list'_body x))?ls] ]
=> idtac;
let G' := context g[opt.id (opt.expanded_fallback_list_body G)] in
change G'
end.
change (@nil ?A) with (opt.id (@nil A)).
do 2 (idtac;
let G := match goal with |- ?G => G end in
let G' := opt_of G in
change G').
unfold ret_cases_to_comp.
reflexivity.
Defined.
Definition opt_rindexed_spec'
:= Eval cbv [proj1_sig opt_rindexed_spec_sig] in proj1_sig opt_rindexed_spec_sig.
Lemma opt_rindexed_spec'_correct
: opt_rindexed_spec' = rindexed_spec G.
Proof.
exact (proj2_sig opt_rindexed_spec_sig).
Qed.
Lemma FirstStep'
: refineADT (string_spec G HSL) opt_rindexed_spec'.
Proof.
rewrite opt_rindexed_spec'_correct.
apply FirstStep_preopt.
Qed.
Local Arguments opt.leb !_ !_.
Local Arguments opt.minus !_ !_.
Definition FirstStep0_sig
: { sp : _ & refineADT (string_spec G HSL) sp }.
Proof.
eexists.
eapply transitivityT; [ apply FirstStep' | ].
unfold opt_rindexed_spec'.
hone method "splits".
{
setoid_rewrite refineEquiv_pick_eq'.
simplify with monad laws.
simpl; subst_body; subst.
eapply refine_under_bind_both; [ | solve [ intros; higher_order_reflexivity ] ].
match goal with
| [ |- ?R ?x ?y ]
=> cut (x = y);
[ let H := fresh in
generalize y;
let y' := fresh in
intros y' H; subst y'; reflexivity
| ]
end.
etransitivity.
{ unfold opt.id, opt2.id.
repeat match goal with
| [ |- opt.length (opt.nth ?n ?ls nil) = _ ]
=> etransitivity;
[ symmetry;
eexact (List.map_nth opt.length ls nil n
: opt.nth _ (opt.map _ _) 0 = opt.length (opt.nth _ _ _))
| ]
| [ |- opt.map (fun x : ?T => opt.minus (opt.length (opt.snd x)) ?v) (pregrammar_productions G) = _ ]
=> transitivity (opt.map (fun x => opt.minus x v) (opt.map opt.length (opt.map opt.snd (pregrammar_productions G))));
[ change @opt.map with @List.map;
rewrite !List.map_map;
reflexivity
| reflexivity ]
| [ |- context[opt.length (opt.map ?f ?ls)] ]
=> replace (opt.length (opt.map f ls)) with (opt.length ls)
by (change @opt.length with @List.length;
change @opt.map with @List.map;
rewrite List.map_length;
reflexivity)
| [ |- context[opt.length (opt.up_to ?n)] ]
=> replace (opt.length (opt.up_to n)) with n
by (change @opt.length with @List.length;
change @opt.up_to with @Operations.List.up_to;
rewrite length_up_to; reflexivity)
| [ |- opt.map opt.length (opt.nth ?n ?ls nil) = _ ]
=> etransitivity;
[ symmetry;
eexact (List.map_nth (opt.map opt.length) ls nil n
: opt.nth _ (opt.map _ _) nil = opt.map opt.length (opt.nth _ _ _))
| ]
(*| [ |- opt.id _ = _ ] => apply f_equal*)
| [ |- ret _ = _ ] => apply f_equal
| [ |- fst _ = _ ] => apply f_equal
| [ |- snd _ = _ ] => apply f_equal
| [ |- opt.fst _ = _ ] => apply f_equal
| [ |- opt.snd _ = _ ] => apply f_equal
| [ |- S _ = _ ] => apply f_equal
| [ |- opt.collapse_length_result _ = _ ] => apply f_equal
| [ |- ret_length_less _ = _ ] => apply f_equal
| [ |- ret_nat _ = _ ] => apply f_equal
| [ |- ret_nat _ = _ ] => eapply (f_equal ret_nat)
| [ |- ret_pick _ = _ ] => eapply (f_equal ret_pick)
| [ |- opt.has_only_terminals _ = _ ] => apply f_equal
| [ |- opt.up_to _ = _ ] => apply f_equal
| [ |- cons _ _ = _ ] => apply f_equal2
| [ |- pair _ _ = _ ] => apply f_equal2
| [ |- cons _ _ = _ ] => eapply (f_equal2 cons)
| [ |- pair _ _ = _ ] => eapply (f_equal2 pair)
| [ |- orb _ _ = _ ] => apply f_equal2
| [ |- andb _ _ = _ ] => apply f_equal2
| [ |- opt.andb _ _ = _ ] => apply f_equal2
| [ |- opt.drop _ _ = _ ] => apply f_equal2
| [ |- opt.leb _ _ = _ ] => apply f_equal2
| [ |- opt.minus _ _ = _ ] => apply f_equal2
| [ |- opt.combine _ _ = _ ] => apply f_equal2
| [ |- opt2.ret_cases_BoolDecR _ _ = _ ] => apply f_equal2
| [ |- EqNat.beq_nat _ _ = _ ] => apply f_equal2
| [ |- opt.nth _ _ _ = _ ] => apply f_equal3
| [ |- 0 = _ ] => reflexivity
| [ |- opt.length (pregrammar_productions G) = _ ] => reflexivity
| [ |- opt.length ?x = _ ] => is_var x; reflexivity
| [ |- opt.map opt.length ?x = _ ] => is_var x; reflexivity
| [ |- nil = _ ] => reflexivity
| [ |- false = _ ] => reflexivity
| [ |- ret_dummy = _ ] => reflexivity
| [ |- invalid = _ ] => reflexivity
| [ |- ?x = _ ] => is_var x; reflexivity
| [ |- opt.map opt.snd (pregrammar_productions G) = _ ] => reflexivity
| [ |- opt.map opt.length (opt.map opt.snd (pregrammar_productions G)) = _ ] => reflexivity
| [ |- opt2.uniquize opt2.ret_cases_BoolDecR _ = _ ] => apply f_equal
| [ |- (If _ Then _ Else _) = _ ] => apply (f_equal3 If_Then_Else)
| [ |- (match _ with true => _ | false => _ end) = _ ]
=> apply (f_equal3 (fun (b : bool) A B => if b then A else B))
| [ |- match ?v with nil => _ | cons x xs => _ end = _ :> ?P ]
=> let T := type of v in
let A := match (eval hnf in T) with list ?A => A end in
etransitivity;
[ refine (@ListMorphisms.list_caset_Proper' A P _ _ _ _ _ _ _ _ _
: _ = match _ with nil => _ | cons x xs => _ end);
[ | intros ?? | ]
| reflexivity ]
| [ |- @opt2.fold_right ?A ?B _ _ _ = _ ]
=> refine (((_ : Proper (pointwise_relation _ _ ==> _ ==> _ ==> eq) (@List.fold_right A B)) : Proper _ (@opt2.fold_right A B)) _ _ _ _ _ _ _ _ _);
[ intros ?? | | ]
| [ |- @opt.map ?A ?B ?f ?v = _ ]
=> not constr_eq v (pregrammar_productions G);
let f' := head f in
not constr_eq f' (@opt.length);
refine (((_ : Proper (pointwise_relation _ _ ==> _ ==> eq) (@List.map A B)) : Proper _ (@opt.map A B)) _ _ _ _ _ _);
[ intro | ]
| [ |- @opt.flat_map ?A ?B _ ?v = _ ]
=> not constr_eq v (pregrammar_productions G);
refine (((_ : Proper (pointwise_relation _ _ ==> _ ==> eq) (@List.flat_map A B)) : Proper _ (@opt.flat_map A B)) _ _ _ _ _ _);
[ intro | ]
| [ |- match ?v with Core.Terminal t => _ | Core.NonTerminal nt => _ end = _ :> ?P ]
=> apply match_item_Proper; [ | intro | intro ]
| [ |- opt.option_rect _ _ _ _ = _ ]
=> eapply (option_rect_Proper : Proper _ (opt.option_rect _));
[ intro | | ]
| _ => progress cbv beta
end.
reflexivity.
reflexivity. }
change orb with Common.opt2.orb.
let d := match goal with d : (nat * (nat * nat))%type |- _ => d end in
change (fst d) with (Common.opt2.fst d);
change (snd d) with (Common.opt2.snd d);
change (fst (Common.opt2.snd d)) with (Common.opt2.fst (Common.opt2.snd d));
change (snd (Common.opt2.snd d)) with (Common.opt2.snd (Common.opt2.snd d)).
change EqNat.beq_nat with Common.opt2.beq_nat.
change andb with Common.opt2.andb.
reflexivity.
}
cbv beta.
apply reflexivityT.
Defined.
Definition opt_rindexed_spec0
:= Eval cbv [projT1 FirstStep0_sig] in projT1 FirstStep0_sig.
Lemma FirstStep0
: refineADT (string_spec G HSL) opt_rindexed_spec0.
Proof.
apply (projT2 FirstStep0_sig).
Qed.
Definition opt_rindexed_spec_method_default : String -> nat * (nat * nat) -> nat -> nat -> Comp (String * list nat).
Proof.
let c := (eval cbv [opt_rindexed_spec0] in opt_rindexed_spec0) in
let c := lazymatch c with
| context[fun r_n d d0 d1 => Bind (opt2.fold_right (@?f r_n d d0 d1) ?init ?ls) (fun a => @?retv r_n d d0 d1 a)]
=> (eval cbv beta in (fun r_n d d0 d1 => Bind (opt2.fold_right (f r_n d d0 d1) init ls) (fun a => retv r_n d d0 d1 a)))
end in
exact c.
Defined.
Section gen.
Context c
(Href : forall str d d0 d1, refine (opt_rindexed_spec_method_default str d d0 d1) (c str d d0 d1)).
Definition FirstStep_sig_gen
: { sp : _ & refineADT (string_spec G HSL) sp }.
Proof.
eexists.
eapply transitivityT; [ apply FirstStep0 | ].
unfold opt_rindexed_spec0.
hone method "splits".
{
setoid_rewrite refineEquiv_pick_eq'.
simplify with monad laws.
simpl; subst_body; subst.
cbv [opt_rindexed_spec_method_default] in Href.
apply Href.
}
cbv beta.
apply reflexivityT.
Defined.
Definition opt_rindexed_spec_gen
:= Eval cbv [projT1 FirstStep_sig_gen] in projT1 FirstStep_sig_gen.
Lemma FirstStep_gen
: refineADT (string_spec G HSL) opt_rindexed_spec_gen.
Proof.
apply (projT2 FirstStep_sig_gen).
Qed.
End gen.
Definition FirstStep_sig
: { sp : _ & refineADT (string_spec G HSL) sp }
:= FirstStep_sig_gen _ (fun _ _ _ _ => reflexivity _).
Definition opt_rindexed_spec
:= Eval cbv [projT1 FirstStep_sig FirstStep_sig_gen opt_rindexed_spec_method_default] in projT1 FirstStep_sig.
Lemma FirstStep
: refineADT (string_spec G HSL) opt_rindexed_spec.
Proof.
apply (projT2 FirstStep_sig).
Qed.
End IndexedImpl_opt.
Declare Reduction opt_red_FirstStep := cbv [opt_rindexed_spec opt.map opt.flat_map opt.up_to opt.length opt.nth opt.id opt.combine opt.expanded_fallback_list'_body opt.minus opt.drop opt.string_beq opt.first_index_default opt.list_bin_eq opt.filter_out_eq opt.find opt.leb opt.andb opt.nat_rect opt.option_rect opt.has_only_terminals opt.sumbool_of_bool opt.collapse_length_result opt.fst opt.snd].
Ltac opt_red_FirstStep :=
cbv [opt_rindexed_spec opt.map opt.flat_map opt.up_to opt.length opt.nth opt.id opt.combine opt.expanded_fallback_list'_body opt.minus opt.drop opt.string_beq opt.first_index_default opt.list_bin_eq opt.filter_out_eq opt.find opt.leb opt.andb opt.nat_rect opt.option_rect opt.has_only_terminals opt.sumbool_of_bool opt.collapse_length_result opt.fst opt.snd].
Section tower.
Context {A B}
(proj : A -> ret_cases)
(r_o : list nat -> Comp B)
(retv : Comp B)
(test : A -> bool)
(test_true : A -> Comp (list nat)).
Fixpoint make_tower base (ls : list A) new_comp old_comp
:= match ls with
| nil => refine (x0 <- new_comp base; r_o x0) retv
-> refine (x0 <- old_comp base; r_o x0) retv
| cons x xs
=> match proj x with
| ret_pick _
=> forall part_retv,
(test x -> refine (test_true x) part_retv)
-> make_tower
base
xs
(fun new_comp' => new_comp (If test x Then part_retv Else new_comp'))
(fun old_comp' => old_comp (If test x Then test_true x Else old_comp'))
| _
=> make_tower
base
xs
(fun new_comp' => new_comp (If test x Then test_true x Else new_comp'))
(fun old_comp' => old_comp (If test x Then test_true x Else old_comp'))
end
end.
Lemma refine_opt2_fold_right' base ls new_comp old_comp
(H : forall base base',
refine base' base
-> refine (x0 <- new_comp base; r_o x0) retv
-> refine (x0 <- old_comp base'; r_o x0) retv)
: make_tower base ls new_comp old_comp.
Proof.
revert base new_comp old_comp H; induction ls as [|x xs IHxs]; simpl; intros.
{ eapply H; [ | eassumption ].
reflexivity. }
{ destruct (proj x); simpl; intros;
apply IHxs; clear IHxs; try intros ?? H';
apply H;
edestruct test; specialize_by (exact eq_refl); simpl;
try setoid_rewrite_hyp'; reflexivity. }
Qed.
Lemma refine_opt2_fold_right base ls
: make_tower base ls (fun x => x) (fun x => x).
Proof.
apply refine_opt2_fold_right'.
intros.
setoid_rewrite_hyp; reflexivity.
Qed.
Fixpoint make_tower_no_unif base (ls : list A) new_comp concl
:= match ls with
| nil => refine (x0 <- new_comp base; r_o x0) retv
-> concl
| cons x xs
=> match proj x with
| ret_pick _
=> forall part_retv,
(test x -> refine (test_true x) part_retv)
-> make_tower_no_unif
base
xs
(fun new_comp' => new_comp (If test x Then part_retv Else new_comp'))
concl
| _
=> make_tower_no_unif
base
xs
(fun new_comp' => new_comp (If test x Then test_true x Else new_comp'))
concl
end
end.
Lemma make_tower_const base ls v v'
(H : refine v' v)
: make_tower base ls (fun _ => v) (fun _ => v').
Proof.
induction ls as [|x xs IHxs]; simpl.
{ rewrite H; intro; assumption. }
{ destruct (proj x); intros; assumption. }
Qed.
Lemma make_tower_no_unif_const base ls v v'
(H : refine v' v)
: make_tower_no_unif base ls (fun _ => v) (refine (x0 <- v'; r_o x0) retv).
Proof.
induction ls as [|x xs IHxs]; simpl.
{ rewrite H; intro; assumption. }
{ destruct (proj x); intros; assumption. }
Qed.
Lemma refine_opt2_fold_right_no_unif base ls
: make_tower_no_unif base ls (fun x => x) (refine (x0 <- opt2.fold_right (fun x else_case => If test x Then test_true x Else else_case) base ls; r_o x0) retv).
Proof.
pose proof (refine_opt2_fold_right base ls) as H.
induction ls as [|x xs IHxs].
{ exact H. }
{ simpl in *.
repeat match goal with
| _ => assumption
| [ |- context[If test ?x Then _ Else _] ] => destruct (test x) eqn:?
| _ => progress simpl in *
| [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?
| _ => apply make_tower_const; reflexivity
| _ => apply make_tower_no_unif_const; first [ reflexivity | assumption ]
| _ => progress intros
| _ => progress specialize_by (exact eq_refl)
| _ => progress specialize_by assumption
| _ => solve [ eauto with nocore ]
end. }
Qed.
End tower.
Section step_tower.
Context {G' : pregrammar' Ascii.ascii}
{HSLM : StringLikeMin Ascii.ascii}
{HSL : StringLike Ascii.ascii}
{HSLP : StringLikeProperties Ascii.ascii}
{HSEP : StringEqProperties Ascii.ascii}.
Let A := (nat * (nat * nat) * ret_cases)%type.
Let B := (@StringLike.String Ascii.ascii HSLM * list nat)%type.
Let proj : A -> ret_cases := @opt0.snd _ _.
Let pre_r_o : String -> list nat -> Comp B
:= fun str => (fun x0 : list nat => ret (str, x0)).
Context (pre_retv : String -> nat * (nat * nat) -> nat -> nat -> Comp (String * list nat)).
Let test_test_true : String -> nat * (nat * nat) -> nat -> nat
-> (A -> bool) * (A -> Comp (list nat)).
Proof.
intros r_o d d0 d1.
lazymatch (eval cbv [opt_rindexed_spec_method_default] in (opt_rindexed_spec_method_default G' r_o d d0 d1)) with
| context[opt2.fold_right
(fun a a0 => If @?test a Then @?test_true a Else a0)
?base
?ls]
=> exact (test, test_true)
end.
Defined.
Let pre_test : String -> nat * (nat * nat) -> nat -> nat -> A -> bool
:= fun r_o d d0 d1 => let '(test, test_true) := test_test_true r_o d d0 d1 in test.
Let pre_test_true : String -> nat * (nat * nat) -> nat -> nat -> A -> Comp (list nat)
:= fun r_o d d0 d1 => let '(test, test_true) := test_test_true r_o d d0 d1 in test_true.
Lemma FirstStep_splits
(H : forall r_o d d0 d1,
refine (x0 <- opt2.fold_right (fun x else_case => If pre_test r_o d d0 d1 x Then pre_test_true r_o d d0 d1 x Else else_case) (ret nil) (opt.expanded_fallback_list_body G'); ret (r_o, x0)) (pre_retv r_o d d0 d1))
res
(Hres : refineADT (opt_rindexed_spec_gen pre_retv) (ComputationalADT.LiftcADT res))
: FullySharpened (@string_spec G' G' eq_refl HSLM HSL).
Proof.
eexists.
eapply transitivityT; [ | exact Hres ].
eapply transitivityT; [ apply (@FirstStep _ _ _ _) | ].
cbv [opt_rindexed_spec opt_rindexed_spec_gen].
hone method "splits".
2:apply reflexivityT.
{
setoid_rewrite General.refineEquiv_pick_eq'.
simplify with monad laws.
simpl; subst_body; subst.
move H at bottom.
cbv beta in H.
apply H.
}
Defined.
End step_tower.
|
{
"alphanum_fraction": null,
"author": "mit-plv",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/Refinement/IndexedAndAtMostOneNonTerminalReflectiveOpt.v",
"reason": null,
"repo": "fiat",
"save_path": "github-repos/coq/mit-plv-fiat",
"sha": "4c78284c3a88db32051bdba79202f40c645ffb7f",
"size": null
}
|
(** * Stlc: The Simply Typed Lambda-Calculus *)
Add LoadPath "~/src/stlc_coq/".
Require Export SfLib.
Module STLC.
(* Types *)
Inductive ty : Type :=
| TBool : ty
| TNat : ty
| TArrow : ty -> ty -> ty.
(* Terms *)
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tzero : tm
| tsucc : tm -> tm
| tiszero : tm -> tm.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif" ].
(* Values *)
Inductive avalue : tm -> Prop :=
| av_abs : forall x T t, avalue (tabs x T t).
Inductive bvalue : tm -> Prop :=
| bv_true : bvalue ttrue
| bv_false : bvalue tfalse.
Inductive nvalue : tm -> Prop :=
| nv_zero : nvalue tzero
| nv_succ : forall t, nvalue t -> nvalue (tsucc t).
Definition value (t:tm) := avalue t \/ bvalue t \/ nvalue t.
Hint Constructors avalue bvalue nvalue.
Hint Unfold value.
Hint Unfold extend.
(* Substitution *)
Reserved Notation "'[' x ':=' s ']' t" (at level 20).
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tabs x' T t1 =>
tabs x' T (if eq_id_dec x x' then t1 else ([x:=s] t1))
| tapp t1 t2 =>
tapp ([x:=s] t1) ([x:=s] t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif ([x:=s] t1) ([x:=s] t2) ([x:=s] t3)
| tzero =>
tzero
| tsucc n =>
tsucc ([x:=s] n)
| tiszero n =>
tiszero ([x:=s] n)
end
where "'[' x ':=' s ']' t" := (subst x s t).
(* Small-Step Semantics *)
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
(* final substitution *)
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
(* reduce the left side *)
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
tapp t1 t2 ==> tapp t1' t2
(* reduce the right side *)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
tapp v1 t2 ==> tapp v1 t2'
(* return first clause if true *)
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
(* return second clause if false *)
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
(* reduce test to a ttrue or tfalse *)
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
(* step body of Succ *)
| ST_Succ : forall t1 t1',
t1 ==> t1' ->
(tsucc t1) ==> (tsucc t1')
(* iszero(O) is true *)
| ST_IszeroZero :
(tiszero tzero) ==> ttrue
(* iszero(S(n)) is false *)
| ST_IszeroSucc : forall t1,
nvalue t1 ->
(tiszero (tsucc t1)) ==> tfalse
(* step body of iszero *)
| ST_Iszero : forall t1 t1',
t1 ==> t1' ->
(tiszero t1) ==> (tiszero t1')
where "t1 '==>' t2" := (step t1 t2).
Notation multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ].
Hint Constructors step.
(* Typing, Contexts *)
Module PartialMap.
Definition partial_map (A:Type) := id -> option A.
Definition empty {A:Type} : partial_map A := (fun _ => None).
Definition extend {A:Type} (Gamma : partial_map A) (x:id) (T : A) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Lemma extend_eq : forall A (ctxt: partial_map A) x T,
(extend ctxt x T) x = Some T.
Proof.
intros. unfold extend. rewrite eq_id. auto.
Qed.
Lemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,
x2 <> x1 ->
(extend ctxt x2 T) x1 = ctxt x1.
Proof.
intros. unfold extend. rewrite neq_id; auto.
Qed.
End PartialMap.
Definition context := partial_map ty.
(* Typing Relation *)
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- tvar x \in T
| T_Abs : forall Gamma x T11 T12 t12,
extend Gamma x T11 |- t12 \in T12 ->
Gamma |- tabs x T11 t12 \in TArrow T11 T12
| T_App : forall T11 T12 Gamma t1 t2,
Gamma |- t1 \in TArrow T11 T12 ->
Gamma |- t2 \in T11 ->
Gamma |- tapp t1 t2 \in T12
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- tif t1 t2 t3 \in T
| T_Zero : forall Gamma,
Gamma |- tzero \in TNat
| T_Succ : forall t1 Gamma,
Gamma |- t1 \in TNat ->
Gamma |- tsucc t1 \in TNat
| T_Iszero : forall t1 Gamma,
Gamma |- t1 \in TNat ->
Gamma |- tiszero t1 \in TBool
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Zero" | Case_aux c "T_Succ"
| Case_aux c "T_Iszero" ].
Hint Constructors has_type.
(* Generation Relation *)
Reserved Notation "Gamma '|-' T '~>' t" (at level 40).
Inductive gens_term : context -> ty -> tm -> Prop :=
| G_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- T ~> tvar x
| G_Abs : forall Gamma x T11 T12 t12,
extend Gamma x T11 |- T12 ~> t12 ->
Gamma |- TArrow T11 T12 ~> tabs x T11 t12
| G_App : forall T11 T12 Gamma t1 t2,
Gamma |- TArrow T11 T12 ~> t1 ->
Gamma |- T11 ~> t2 ->
Gamma |- T12 ~> tapp t1 t2
| G_True : forall Gamma,
Gamma |- TBool ~> ttrue
| G_False : forall Gamma,
Gamma |- TBool ~> tfalse
| G_If : forall t1 t2 t3 T Gamma,
Gamma |- TBool ~> t1 ->
Gamma |- T ~> t2 ->
Gamma |- T ~> t3 ->
Gamma |- T ~> tif t1 t2 t3
| G_Zero : forall Gamma,
Gamma |- TNat ~> tzero
| G_Succ : forall t1 Gamma,
Gamma |- TNat ~> t1 ->
Gamma |- TNat ~> tsucc t1
| G_Iszero : forall t1 Gamma,
Gamma |- TNat ~> t1 ->
Gamma |- TBool ~> tiszero t1
where "Gamma '|-' T '~>' t" := (gens_term Gamma T t).
Tactic Notation "gens_term_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "G_Var" | Case_aux c "G_Abs"
| Case_aux c "G_App" | Case_aux c "G_True"
| Case_aux c "G_False" | Case_aux c "G_If"
| Case_aux c "G_Zero" | Case_aux c "G_Succ"
| Case_aux c "G_Iszero" ].
Hint Constructors gens_term.
(* Typing and Generation tests *)
Definition x := (Id 0).
Definition y := (Id 1).
Definition z := (Id 2).
Hint Unfold x.
Hint Unfold y.
Hint Unfold z.
Example typing_example_1 :
empty |- tabs x TBool (tvar x) \in TArrow TBool TBool.
Proof. auto. Qed.
Example typing_example_2 :
empty |-
(tabs x TBool
(tabs y (TArrow TBool TBool)
(tapp (tvar y) (tapp (tvar y) (tvar x))))) \in
(TArrow TBool (TArrow (TArrow TBool TBool) TBool)).
Proof with auto using extend_eq.
apply T_Abs.
apply T_Abs.
eapply T_App. apply T_Var...
eapply T_App. apply T_Var...
apply T_Var...
Qed.
(* Nat ~> S(S(S(O))) *)
Example typing_example_3 :
empty |-
tsucc (tsucc (tsucc tzero))
\in TNat.
Proof with auto using extend_eq.
auto.
Qed.
(* Nat ~> (\x:nat.S(x)) O *)
Example typing_example_4 :
empty |-
tapp (tabs x TNat (tsucc (tvar x))) (tsucc tzero)
\in TNat.
Proof with auto using extend_eq.
eapply T_App. apply T_Abs. apply T_Succ. apply T_Var...
apply T_Succ. apply T_Zero.
Qed.
Example gen_example_1 :
empty |- TArrow TBool TBool ~> tabs x TBool (tvar x).
Proof.
apply G_Abs. apply G_Var. reflexivity. Qed.
(* (bool->((bool->bool)->bool)) ~> (\x:bool.(\y:bool->bool.(y(y x)))) *)
Example gen_example_2 :
empty |-
(TArrow TBool (TArrow (TArrow TBool TBool) TBool)) ~>
(tabs x TBool
(tabs y (TArrow TBool TBool)
(tapp (tvar y) (tapp (tvar y) (tvar x))))).
Proof with auto using extend_eq.
apply G_Abs. apply G_Abs. eapply G_App. apply G_Var...
eapply G_App. apply G_Var...
apply G_Var...
Qed.
(* thesis page 14 example *)
Example gen_example_3 :
empty |-
(TArrow TBool TBool) ~>
(tapp (tabs x (TArrow TBool TBool) (tvar x)) (tabs y TBool ttrue)).
Proof with auto using extend_eq.
eapply G_App. apply G_Abs. apply G_Var...
apply G_Abs. apply G_True.
Qed.
(* Nat ~> S(S(S(O))) *)
Example gen_example_4 :
empty |-
TNat ~>
tsucc (tsucc (tsucc tzero)).
Proof with auto using extend_eq.
auto.
Qed.
(* Nat ~> (\x:nat.S(x)) O *)
Example gen_example_5 :
empty |-
TNat ~>
tapp (tabs x TNat (tsucc (tvar x))) (tsucc tzero).
Proof with auto using extend_eq.
eapply G_App. apply G_Abs. apply G_Succ. apply G_Var...
apply G_Succ. apply G_Zero.
Qed.
(* Soundness *)
Theorem soundness : forall Gamma t T,
Gamma |- T ~> t ->
Gamma |- t \in T.
Proof.
intros G t T H. induction H.
Case "Gamma |- T ~> tvar".
apply T_Var. rewrite H. reflexivity.
Case "Gamma |- T ~> tabs".
apply T_Abs. apply IHgens_term.
Case "Gamma |- T ~> tapp".
apply (T_App T11).
apply IHgens_term1. apply IHgens_term2.
Case "Gamma |- T ~> ttrue".
apply T_True.
Case "Gamma |- T ~> tfalse".
apply T_False.
Case "Gamma |- T ~> tif".
apply T_If. apply IHgens_term1.
apply IHgens_term2. apply IHgens_term3.
Case "Gamma |- T ~> tzero".
apply T_Zero.
Case "Gamma |- T ~> tsucc".
apply T_Succ. apply IHgens_term.
Case "Gamma |- T ~> tiszero".
apply T_Iszero. apply IHgens_term.
Qed.
(* Completeness *)
Theorem completeness : forall Gamma t T,
Gamma |- t \in T ->
Gamma |- T ~> t.
Proof.
intros G t T H. induction H.
Case "Gamma |- tvar \in T".
apply G_Var. rewrite H. reflexivity.
Case "Gamma |- tabs \in T".
apply G_Abs. apply IHhas_type.
Case "Gamma |- tapp \in T".
apply (G_App T11).
apply IHhas_type1. apply IHhas_type2.
Case "Gamma |- ttrue \in T".
apply G_True.
Case "Gamma |- tfalse \in T".
apply G_False.
Case "Gamma |- tif \in T".
apply G_If. apply IHhas_type1.
apply IHhas_type2. apply IHhas_type3.
Case "Gamma |- tzero \in T".
apply G_Zero.
Case "Gamma |- tsucc \in T".
apply G_Succ. apply IHhas_type.
Case "Gamma |- tiszero \in T".
apply G_Iszero. apply IHhas_type.
Qed.
End STLC.
|
{
"alphanum_fraction": null,
"author": "mulias",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/coq/mulias-type_directed_synthesis/type_directed_synthesis-5403d4be43a9c79ba60c1c75aba9ec11dfd30ec4/Stlc.v",
"reason": null,
"repo": "type_directed_synthesis",
"save_path": "github-repos/coq/mulias-type_directed_synthesis",
"sha": "5403d4be43a9c79ba60c1c75aba9ec11dfd30ec4",
"size": null
}
|
import beluga
import cloudpickle as pickle
import copy
import logging
from math import isclose
import numpy as np
from beluga.numeric.bvp_solvers import BaseAlgorithm, BVPResult
from beluga.numeric.ivp_solvers import Propagator, reconstruct
from beluga.numeric.data_classes.Trajectory import Trajectory
from beluga.utils.logging import logger
from scipy.sparse import coo_matrix, csc_matrix
from scipy.sparse.linalg import splu
from scipy.optimize.slsqp import approx_jacobian
from scipy.optimize import minimize, root, fsolve
scipy_minimize_algorithms = {'Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'COBYLA', 'SLSQP',
'trust-constr', 'dogleg', 'trust-ncg', 'trust-exact', 'trust-krylov'}
scipy_root_algorithms = {'hybr', 'lm', 'broyden1', 'broyden2', 'anderson', 'linearmixing', 'diagbroyden',
'excitingmixing', 'krylov', 'df-sane'}
EPS = np.finfo(float).eps
def estimate_bc_jac(bc, ya, qa, yb, qb, p, ndp, bc0=None):
"""Estimate derivatives of boundary conditions with forward differences.
Returns
-------
dbc_dya : ndarray, shape (n + k, n)
Derivatives with respect to ya. An element (i, j) corresponds to
d bc_i / d ya_j.
dbc_dyb : ndarray, shape (n + k, n)
Derivatives with respect to yb. An element (i, j) corresponds to
d bc_i / d yb_j.
dbc_dp : ndarray with shape (n + k, k) or None
Derivatives with respect to p. An element (i, j) corresponds to
d bc_i / d p_j. If `p` is empty, None is returned.
"""
n = ya.shape[0]
k = p.shape[0]
if bc0 is None:
bc0 = bc(ya, yb, p, ndp,)
dtype = ya.dtype
dbc_dya = np.empty((n, n + k), dtype=dtype)
h = EPS**0.5 * (1 + np.abs(ya))
for i in range(n):
ya_new = ya.copy()
ya_new[i] += h[i]
hi = ya_new[i] - ya[i]
bc_new = bc(ya_new, yb, p, ndp)
dbc_dya[i] = (bc_new - bc0) / hi
dbc_dya = dbc_dya.T
h = EPS**0.5 * (1 + np.abs(yb))
dbc_dyb = np.empty((n, n + k), dtype=dtype)
for i in range(n):
yb_new = yb.copy()
yb_new[i] += h[i]
hi = yb_new[i] - yb[i]
bc_new = bc(ya, yb_new, p)
dbc_dyb[i] = (bc_new - bc0) / hi
dbc_dyb = dbc_dyb.T
if k == 0:
dbc_dp = None
else:
h = EPS**0.5 * (1 + np.abs(p))
dbc_dp = np.empty((k, n + k), dtype=dtype)
for i in range(k):
p_new = p.copy()
p_new[i] += h[i]
hi = p_new[i] - p[i]
bc_new = bc(ya, yb, p_new)
dbc_dp[i] = (bc_new - bc0) / hi
dbc_dp = dbc_dp.T
return dbc_dya, dbc_dyb, dbc_dp
def wrap_functions(fun, bc, fun_jac, bc_jac, aux, k, dtype):
"""Wrap functions for unified usage in the solver."""
fun_jac_p, fun_jac_wrapped, bc_jac_wrapped = None, None, None
if k == 0:
def fun_p(x, y, _):
return np.asarray(fun(x, y), dtype)
def bc_wrapped(ya, yb, _):
return np.asarray(bc(ya, [], [], yb, [], [], _, [], aux), dtype)
if fun_jac is not None:
def fun_jac_p(x, y, _):
return np.asarray(fun_jac(x, y), dtype), None
if bc_jac is not None:
def bc_jac_wrapped(ya, yb, _):
dbc_dya, dbc_dyb = bc_jac(ya, yb)
return (np.asarray(dbc_dya, dtype),
np.asarray(dbc_dyb, dtype), None)
else:
def fun_p(x, y, p):
return np.asarray(fun(x, y, p), dtype)
empty_array = np.array([])
def bc_wrapped(ya, yb, p, ndp):
return np.asarray(bc(ya, empty_array, empty_array, yb, empty_array, empty_array, p, ndp, aux), dtype)
if fun_jac is not None:
def fun_jac_p(x, y, p):
df_dy, df_dp = fun_jac(x, y, p)
return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype)
if bc_jac is not None:
def bc_jac_wrapped(ya, yb, p):
dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p)
return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype),
np.asarray(dbc_dp, dtype))
fun_wrapped = fun_p
if fun_jac is not None:
fun_jac_wrapped = fun_jac_p
return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped
class Shooting(BaseAlgorithm):
r"""
Reduced dimensional shooting algorithm for solving boundary value problems.
Given a system of ordinary differential equations, define the sensitivities as
.. math::
A(\tau) =
\left[\frac{\partial \mathbf{f}}{\partial \mathbf{x}}, \frac{\partial \mathbf{f}}{\partial \mathbf{p}}\right]
Then, the state-transition matrix is defined as the following set of first-order differential equations
.. math::
\begin{aligned}
\Delta_0 &= \left[Id_M, \mathbf{0}\right] \\
\dot{\Delta} &= A(\tau)\Delta
\end{aligned}
Sensitivities of the boundary conditions are
.. math::
\begin{aligned}
M &= \frac{\mathrm{d} \mathbf{\Phi}}{\mathrm{d} \mathbf{x}_0} \\
Q &= \frac{\partial \mathbf{\Phi}}{\partial \mathbf{q}_0}
+ \frac{\partial \mathbf{\Phi}}{\partial \mathbf{q}_f} \\
P_1 &= \frac{\mathrm{d} \mathbf{\Phi}}{\mathrm{d} \mathbf{p}} \\
P_2 &= \frac{\partial \mathbf{\Phi}}{\partial \mathbf{\lambda}}
\end{aligned}
The Jacobian matrix is then the concatenation of these sensitivities
.. math::
J = \left[M, Q, P_1, P_2 \right]
+------------------------+-----------------+-----------------+
| Valid kwargs | Default Value | Valid Values |
+========================+=================+=================+
| algorithm | 'Armijo' | See note below. |
+------------------------+-----------------+-----------------+
| ivp_args | {} | see `ivp_solvers` |
+------------------------+-----------------+-----------------+
| tolerance | 1e-4 | > 0 |
+------------------------+-----------------+-----------------+
| max_error | 100 | > 0 |
+------------------------+-----------------+-----------------+
| max_iterations | 100 | > 0 |
+------------------------+-----------------+-----------------+
| num_arcs | 1 | > 0 |
+------------------------+-----------------+-----------------+
The shooting solver uses 3rd party root-solvers to find numeric solutions. In addition to `Armijo`,
the SciPy solvers `scipy.optimize.root`, `scipy.optimize.minimize`, `scipy.optimize.fsolve` are available.
"""
def __init__(self, *args, **kwargs):
BaseAlgorithm.__init__(self, *args, **kwargs)
self.algorithm = kwargs.get('algorithm', 'Armijo')
self.ivp_args = kwargs.get('ivp_args', dict())
self.tolerance = kwargs.get('tolerance', 1e-4)
self.max_error = kwargs.get('max_error', 100)
self.max_iterations = kwargs.get('max_iterations', 100)
self.num_arcs = kwargs.get('num_arcs', 1)
self.stm_ode_func = None
self.bc_func_ms = None
# Set up the boundary condition function
if self.boundarycondition_function is not None:
self.bc_func_ms = self._bc_func_multiple_shooting(bc_func=self.boundarycondition_function)
@staticmethod
def _wrap_y0(gamma_set, parameters, nondynamical_parameters):
n_odes = len(gamma_set[0].y[0])
n_quads = len(gamma_set[0].q[0])
n_dynparams = len(parameters)
n_nondynparams = len(nondynamical_parameters)
out = np.zeros(len(gamma_set) * n_odes + n_quads + n_dynparams + n_nondynparams)
ii = 0
for trajectory in gamma_set:
for initial_pt in trajectory.y[0]:
out[ii] = initial_pt
ii += 1
for initial_pt in gamma_set[0].q[0]:
out[ii] = initial_pt
ii += 1
for initial_pt in parameters:
out[ii] = initial_pt
ii += 1
for initial_pt in nondynamical_parameters:
out[ii] = initial_pt
ii += 1
return out
@staticmethod
def _unwrap_y0(xx, n_odes, n_quads, n_dynparams, n_arcs):
y0 = np.reshape(xx[:n_odes * n_arcs], (n_arcs, n_odes), order='C')
q0 = xx[n_odes * n_arcs:n_odes * n_arcs + n_quads]
dparams = xx[n_odes * n_arcs + n_quads:n_odes * n_arcs + n_quads + n_dynparams]
dnonparams = xx[n_odes * n_arcs + n_dynparams + n_quads:]
return y0, q0, dparams, dnonparams
@staticmethod
def _make_gammas(derivative_function, quadrature_function, gamma_set, dyn_param,
sol, prop, pool, nquads):
n_arcs = len(gamma_set)
tspan = [None]*n_arcs
y0g = [None]*n_arcs
q0g = [None]*n_arcs
u0g = [None]*n_arcs
for ii in range(len(gamma_set)):
_y0g, _q0g, _u0g = gamma_set[ii](gamma_set[ii].t[0])
tspan[ii] = gamma_set[ii].t
y0g[ii] = _y0g
q0g[ii] = _q0g
u0g[ii] = _u0g
def preload(args):
return prop(derivative_function, quadrature_function, args[0], args[1], args[2],
dyn_param, sol.const)
if pool is not None:
gamma_set_new = pool.map(preload, zip(tspan, y0g, q0g))
else:
gamma_set_new = [preload([T, Y, Q]) for T, Y, Q in zip(tspan, y0g, q0g)]
if n_arcs > 1 and nquads > 0:
for ii in range(n_arcs-1):
qdiff = gamma_set_new[ii].q[-1] - gamma_set_new[ii+1].q[0]
gamma_set_new[ii+1].q += qdiff
return gamma_set_new
@staticmethod
def _make_gammas_parallel(derivative_function, quadrature_function, gamma_set, dyn_param,
sol, prop, pool, nquads):
n_arcs = len(gamma_set)
tspan = [None] * n_arcs
y0g = [None] * n_arcs
q0g = [None] * n_arcs
u0g = [None]*n_arcs
for ii in range(len(gamma_set)):
_y0g, _q0g, _u0g = gamma_set[ii](gamma_set[ii].t[0])
tspan[ii] = gamma_set[ii].t
y0g[ii] = _y0g
q0g[ii] = _q0g
u0g[ii] = _u0g
def preload(args):
return prop(pickle.loads(derivative_function), pickle.loads(quadrature_function), args[0], args[1], args[2], args[3],
dyn_param, sol.const)
if pool is not None:
gamma_set_new = pool.map(preload, zip(tspan, y0g, q0g, u0g))
else:
gamma_set_new = [preload([T, Y, Q, U]) for T, Y, Q, U in zip(tspan, y0g, q0g, u0g)]
if n_arcs > 1 and nquads > 0:
for ii in range(n_arcs - 1):
qdiff = gamma_set_new[ii].q[-1] - gamma_set_new[ii + 1].q[0]
gamma_set_new[ii + 1].q += qdiff
return gamma_set_new
@staticmethod
def _bc_jac(gamma, phi_full, parameters, nondynamical_params, const, quad_func, bc_func, step_size=1e-6):
gamma_orig = copy.deepcopy(gamma)
h = step_size
t0 = gamma_orig.t[0]
y0, q0, u0 = gamma_orig(t0)
n_odes = len(y0)
n_quads = len(q0)
num_arcs = len(gamma_orig)
fx = np.asarray(bc_func(gamma_orig.y[0], [], [], gamma_orig.y[-1], [], [], parameters, nondynamical_params, const))
n_bcs = len(fx)
m = np.zeros((n_bcs, n_odes))
q = np.zeros((n_bcs, n_quads))
p1 = np.zeros((n_bcs, parameters.size))
p2 = np.zeros((n_bcs, nondynamical_params.size))
dx = np.zeros((n_odes + parameters.size))
gamma_orig = copy.deepcopy(gamma)
for jj in range(n_odes):
dx[jj] = dx[jj] + h
dy = np.dot(phi_full, dx)
p = Trajectory(gamma_orig.t, gamma_orig.y + dy)
f = np.asarray(bc_func(p.y[0], [], [], p.y[-1], [], [], parameters, nondynamical_params, const))
m[:, jj] = (f-fx)/h
dx[jj] = dx[jj] - h
# dq = np.zeros(n_quads)
# for ii in range(n_quads):
# dq[ii] = dq[ii] + h
# gamma_set_perturbed = [Trajectory(g.t, g.y, g.q + dq) for g in gamma_orig]
# f = bc_func(gamma_set_perturbed, parameters, nondynamical_params, const)
# q[:, ii] = (f-fx)/h
# dq[ii] = dq[ii] - h
for ii in range(parameters.size):
raise NotImplementedError
gamma_set_perturbed = copy.deepcopy(gamma_orig)
parameters[ii] = parameters[ii] + h
jj = ii + n_odes
dx[jj] = dx[jj] + h
for kk, phi in zip(range(len(gamma_orig)), phi_full_list):
dy = np.dot(phi, dx)
perturbed_trajectory = Trajectory(gamma_orig[kk].t, gamma_orig[kk].y + dy)
if n_quads > 0:
if kk > 0:
perturbed_trajectory = reconstruct(quad_func, perturbed_trajectory,
gamma_set_perturbed[kk-1].q[-1], parameters, const)
else:
perturbed_trajectory = reconstruct(quad_func, perturbed_trajectory, gamma_orig[kk].q[0],
parameters, const)
gamma_set_perturbed[kk] = perturbed_trajectory
f = bc_func(gamma_set_perturbed, parameters, nondynamical_params, const)
p1[:, ii] += (f-fx)/h
dx[jj] = dx[jj] - h
parameters[ii] = parameters[ii] - h
for ii in range(nondynamical_params.size):
nondynamical_params[ii] = nondynamical_params[ii] + h
f = bc_func(gamma_orig, parameters, nondynamical_params, const)
p2[:, ii] = (f-fx)/h
nondynamical_params[ii] = nondynamical_params[ii] - h
jac = np.hstack((m, q, p1, p2))
return jac
@staticmethod
def _bc_func_multiple_shooting(bc_func=None):
def _bc_func(gamma_set, p_d, p_n, _, k, *args):
t0 = gamma_set[0].t[0]
y0, q0, u0 = gamma_set[0](t0)
tf = gamma_set[-1].t[-1]
yf, qf, uf = gamma_set[-1](tf)
bc1 = np.asarray(
[gamma_set[ii].y[-1] - gamma_set[ii + 1].y[0] for ii in range(len(gamma_set) - 1)]).flatten()
if len(q0) > 0:
bc2 = np.asarray(bc_func(y0, q0, yf, qf, p_d, p_n, k)).flatten()
else:
bc2 = np.asarray(bc_func(y0, yf, p_d, p_n, k)).flatten()
bc = np.hstack((bc1, bc2))
return bc
return _bc_func
def make_stmode(self, odefn, n_odes, step_size=1e-6):
xh = np.eye(n_odes)*step_size
def _stmode_fd(_xx, u, p, const):
""" Finite difference version of state transition matrix """
n_params = p.size
phi = _xx[n_odes:].reshape((n_odes, n_odes + n_params))
xx = _xx[0:n_odes] # Just states
fx = np.squeeze([odefn(xx, u, p, const)])
if self.derivative_function_jac is not None:
_df_dy, _df_dp = self.derivative_function_jac(xx, [], p, const)
if n_odes > 1 and len(_df_dp.shape) == 1:
_df_dp = np.array([_df_dp]).T
Z = np.zeros((n_odes, n_params - _df_dp.shape[1]))
ff = np.hstack((_df_dy, _df_dp, Z))
else:
ff = np.empty((n_odes, n_odes+n_params))
for i in range(n_odes):
fxh = odefn(xx + xh[i, :], u, p, const)
ff[:, i] = (fxh-fx) / step_size
for i in range(n_params):
p[i] += step_size
fxh = odefn(xx, u, p, const)
ff[:, i+n_odes] = (fxh - fx) / step_size
p[i] -= step_size
phi_dot = np.dot(np.vstack((ff, np.zeros((n_params, n_params + n_odes)))),
np.vstack((phi, np.hstack((np.zeros((n_params, n_odes)), np.eye(n_params))))))[:n_odes, :]
return np.hstack((fx, np.reshape(phi_dot, (n_odes * (n_odes + n_params)))))
return _stmode_fd
def solve(self, solinit, **kwargs):
"""
Solve a two-point boundary value problem using the shooting method.
:param solinit: An initial guess for a solution to the BVP.
:return: A solution to the BVP.
"""
# Make a copy of sol and format inputs
sol = copy.deepcopy(solinit)
sol.t = np.array(sol.t, dtype=beluga.DTYPE)
sol.y = np.array(sol.y, dtype=beluga.DTYPE)
if np.issubdtype(sol.y.dtype, np.complexfloating):
dtype = complex
else:
dtype = float
sol.q = np.array(sol.q, dtype=beluga.DTYPE)
sol.dynamical_parameters = np.array(sol.dynamical_parameters, dtype=beluga.DTYPE)
sol.nondynamical_parameters = np.array(sol.nondynamical_parameters, dtype=beluga.DTYPE)
# n = sol.y[0].shape[0]
k = sol.dynamical_parameters.shape[0]
# sol.dynamical_parameters = np.hstack((sol.dynamical_parameters, sol.nondynamical_parameters))
# sol.nondynamical_parameters = np.empty((0,))
fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions(
self.derivative_function, self.boundarycondition_function, None, None, sol.const, k, dtype)
pool = kwargs.get('pool', None)
# Extract some info from the guess structure
y0g = sol.y[0, :]
if self.quadrature_function is None or np.isnan(sol.q).all():
q0g = np.array([])
else:
q0g = sol.q[0, :]
parameter_guess = sol.dynamical_parameters
nondynamical_parameter_guess = sol.nondynamical_parameters
# Get some info on the size of the problem
n_odes = y0g.shape[0]
n_quads = q0g.shape[0]
n_dynparams = sol.dynamical_parameters.shape[0]
# n_nondynparams = nondynamical_parameter_guess.shape[0]
# Make the state-transition ode matrix
if self.stm_ode_func is None:
self.stm_ode_func = self.make_stmode(self.derivative_function, y0g.shape[0])
# Set up the boundary condition function
if self.bc_func_ms is None:
self.bc_func_ms = self._bc_func_multiple_shooting(bc_func=self.boundarycondition_function)
# Build each of the separate arcs for multiple shooting. Uses sol's interpolation style
gamma_set = []
t0 = sol.t[0]
tf = sol.t[-1]
tn = np.linspace(t0, tf, self.num_arcs+1)
for trajectory_number in range(self.num_arcs):
y0t, q0t, u0t = sol(tn[trajectory_number])
yft, qft, uft = sol(tn[trajectory_number+1])
t_set = np.hstack((tn[trajectory_number], tn[trajectory_number+1]))
y_set = np.vstack((y0t, yft))
q_set = np.vstack((q0t, qft))
u_set = np.vstack((u0t, uft))
gamma_set.append(Trajectory(t_set, y_set, q_set, u_set))
# Initial state of STM is an identity matrix with an additional column of zeros per parameter
# stm0 = np.hstack((np.eye(n_odes), np.zeros((n_odes, n_dynparams)))).reshape(n_odes*(n_odes + n_dynparams))
# y0stm = np.zeros((len(stm0) + n_odes))
prop = Propagator(**self.ivp_args)
converged = False # Convergence flag
n_iter = 0 # Initialize iteration counter
err = -1
# Set up the initial guess vector
x_init = self._wrap_y0(gamma_set, parameter_guess, nondynamical_parameter_guess)
def quad_wrap(t, xx, p, const):
return self.quadrature_function(t, xx[:n_odes], p, const)
# Pickle the functions for faster execution
if pool is not None:
pick_deriv = pickle.dumps(self.derivative_function)
pick_quad = pickle.dumps(self.quadrature_function)
pick_stm = pickle.dumps(self.stm_ode_func)
pick_quad_stm = pickle.dumps(quad_wrap)
_gamma_maker = self._make_gammas_parallel
else:
pick_deriv = self.derivative_function
pick_quad = self.quadrature_function
pick_stm = self.stm_ode_func
pick_quad_stm = quad_wrap
_gamma_maker = self._make_gammas
# Set up the constraint function
def _constraint_function(xx, deriv_func, quad_func, n_odes, n_quads, n_dynparams, n_arcs, const):
g = copy.deepcopy(gamma_set)
_y, _q, _params, _nonparams = self._unwrap_y0(xx, n_odes, n_quads, n_dynparams, n_arcs)
for ii in range(n_arcs):
g[ii].y[0] = _y[ii]
if n_quads > 0:
g[ii].q[0] = _q
g = _gamma_maker(deriv_func, quad_func, g, _params, sol, prop, pool, n_quads)
return self.bc_func_ms(g, _params, _nonparams, k, const)
def _constraint_function_wrapper(X):
return _constraint_function(X, pick_deriv, pick_quad, n_odes, n_quads, n_dynparams, self.num_arcs,
sol.const)
# Set up the jacobian of the constraint function
def _jacobian_function(xx, deriv_func, quad_func, n_odes, n_quads, n_dynparams, n_arcs):
g = copy.deepcopy(gamma_set)
_y, _q, _params, _nonparams = self._unwrap_y0(xx, n_odes, n_quads, n_dynparams, n_arcs)
n_nondyn = _nonparams.shape[0]
for ii in range(n_arcs):
g[ii].y[0] = _y[ii]
if n_quads > 0:
g[ii].q[0] = _q
phi_full_list = []
for ii in range(n_arcs):
t0 = g[ii].t[0]
_y0g, _q0g, _u0g = g[ii](t0)
tf = g[ii].t[-1]
_yfg, _qfg, _ufg = g[ii](tf)
stm0 = np.hstack((np.eye(n_odes), np.zeros((n_odes, n_dynparams)))).reshape(
n_odes * (n_odes + n_dynparams))
y0stm = np.zeros((len(stm0) + n_odes))
stmf = np.hstack((np.eye(n_odes), np.zeros((n_odes, n_dynparams)))).reshape(
n_odes * (n_odes + n_dynparams))
yfstm = np.zeros((len(stmf) + n_odes))
y0stm[:n_odes] = _y0g
y0stm[n_odes:] = stm0[:]
yfstm[:n_odes] = _yfg
yfstm[n_odes:] = stmf[:]
g[ii].t = np.hstack((t0, tf))
g[ii].y = np.vstack((y0stm, yfstm))
g[ii].q = np.vstack((_q0g, _qfg))
g[ii].u = np.vstack((_u0g, _ufg))
gamma_set_new = _gamma_maker(deriv_func, quad_func, g, _params[:n_dynparams], sol, prop, pool, n_quads)
for ii in range(len(gamma_set_new)):
t_set = gamma_set_new[ii].t
temp = gamma_set_new[ii].y
y_set = temp[:, :n_odes]
q_set = gamma_set_new[ii].q
u_set = gamma_set_new[ii].u
gamma_set_new[ii] = Trajectory(t_set, y_set, q_set, u_set)
phi_temp = np.reshape(temp[:, n_odes:], (len(gamma_set_new[ii].t), n_odes, n_odes + n_dynparams))
phi_full_list.append(np.copy(phi_temp))
dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc_wrapped, gamma_set_new[0].y[0], [], gamma_set_new[-1].y[-1],
[], _params, _nonparams)
if dbc_dp is None:
dbc_dp = np.empty((dbc_dya.shape[0],0))
values = np.empty((0,))
i_jac = np.empty((0,), dtype=int)
j_jac = np.empty((0,), dtype=int)
if n_arcs == 1:
jac = np.hstack((dbc_dya, dbc_dp))
_phi = np.vstack((phi_full_list[-1][-1], np.zeros((n_dynparams, n_odes + n_dynparams))))
jac += np.dot(np.hstack((dbc_dyb, dbc_dp)), _phi)
i_bc = np.repeat(np.arange(0, n_odes + n_dynparams), n_odes + n_dynparams)
j_bc = np.tile(np.arange(n_odes + n_dynparams), n_odes + n_dynparams)
values = np.hstack((values, jac.ravel()))
i_jac = np.hstack((i_jac, i_bc))
j_jac = np.hstack((j_jac, j_bc))
else:
p_jac = np.empty((0,n_dynparams))
for ii in range(n_arcs-1):
jac = np.dot(np.eye(n_odes), phi_full_list[ii][-1])
i_bc = np.repeat(np.arange(n_odes*ii, n_odes*(ii+1)), n_odes)
j_bc = np.tile(np.arange(0, n_odes), n_odes) + n_odes * ii
values = np.hstack((values, jac[:,:n_odes].ravel()))
i_jac = np.hstack((i_jac, i_bc))
j_jac = np.hstack((j_jac, j_bc))
if n_dynparams > 0:
p_jac = np.vstack((p_jac, jac[:, n_odes:]))
jac = -np.eye(n_odes)
i_bc = np.repeat(np.arange(n_odes * ii, n_odes * (ii + 1)), n_odes)
j_bc = np.tile(np.arange(0, n_odes), n_odes) + n_odes * (ii + 1)
values = np.hstack((values, jac.ravel()))
i_jac = np.hstack((i_jac, i_bc))
j_jac = np.hstack((j_jac, j_bc))
if n_dynparams > 0:
values = np.hstack((values, p_jac.ravel()))
i_p = np.repeat(np.arange(0, n_odes*(n_arcs-1)), n_dynparams)
j_p = np.tile(np.arange(0, n_dynparams), n_odes*(n_arcs-1)) + n_odes * n_arcs
i_jac = np.hstack((i_jac, i_p))
j_jac = np.hstack((j_jac, j_p))
jac = dbc_dya
i_bc = np.repeat(np.arange(0, n_odes + n_dynparams), n_odes) + n_odes*(n_arcs - 1)
j_bc = np.tile(np.arange(n_odes), n_odes + n_dynparams)
values = np.hstack((values, jac.ravel()))
i_jac = np.hstack((i_jac, i_bc))
j_jac = np.hstack((j_jac, j_bc))
_phi = np.vstack((phi_full_list[-1][-1], np.zeros((n_dynparams, n_odes + n_dynparams))))
jac = np.dot(np.hstack((dbc_dyb, dbc_dp)), _phi)
jac[:, n_odes:] += dbc_dp
i_bc = np.repeat(np.arange(0, n_odes + n_dynparams), n_odes + n_dynparams) + n_odes * (n_arcs - 1)
j_bc = np.tile(np.arange(n_odes + n_dynparams), n_odes + n_dynparams) + n_odes * (n_arcs - 1)
values = np.hstack((values, jac.ravel()))
i_jac = np.hstack((i_jac, i_bc))
j_jac = np.hstack((j_jac, j_bc))
J = csc_matrix(coo_matrix((values, (i_jac, j_jac))))
return J
def _jacobian_function_wrapper(X):
return approx_jacobian(X, _constraint_function_wrapper, 1e-6)
is_sparse = False
# is_sparse = False
# if n_quads == 0 and self.algorithm.lower() == 'armijo':
# is_sparse = True
# def _jacobian_function_wrapper(X):
# return _jacobian_function(X, pick_stm, pick_quad_stm, n_odes, n_quads, n_dynparams, self.num_arcs)
# elif n_quads == 0:
# def _jacobian_function_wrapper(X):
# return _jacobian_function(X, pick_stm, pick_quad_stm, n_odes, n_quads, n_dynparams, self.num_arcs).toarray()
# else:
# def _jacobian_function_wrapper(X):
# return approx_jacobian(X, _constraint_function_wrapper, 1e-6)
constraint = {'type': 'eq', 'fun': _constraint_function_wrapper, 'jac': _jacobian_function_wrapper}
# Set up the cost function. This should just return 0 unless the specified method cannot handle constraints
def cost(_): return 0
"""
Run the root-solving process
"""
if self.algorithm in scipy_minimize_algorithms:
if not (self.algorithm == 'COBYLA' or self.algorithm == 'SLSQP' or self.algorithm == 'trust-constr'):
def cost(x):
return np.linalg.norm(_constraint_function_wrapper(x)) ** 2
opt = minimize(cost, x_init, method=self.algorithm, tol=self.tolerance, constraints=constraint,
options={'maxiter': self.max_iterations})
err = opt.fun
x_init = opt.x
n_iter = opt.nit
converged = opt.success and isclose(err, 0, abs_tol=self.tolerance)
elif self.algorithm in scipy_root_algorithms:
opt = root(_constraint_function_wrapper, x_init, jac=_jacobian_function_wrapper, method=self.algorithm,
tol=self.tolerance, options={'maxiter': self.max_iterations})
err = opt.fun
x_init = opt.x
n_iter = -1
converged = opt.success
elif self.algorithm.lower() == 'fsolve':
x = fsolve(_constraint_function_wrapper, x_init, fprime=_jacobian_function_wrapper, xtol=self.tolerance)
err = np.linalg.norm(_constraint_function_wrapper(x_init))**2
x_init = x
n_iter = -1
converged = isclose(err, 0, abs_tol=self.tolerance)
elif self.algorithm.lower() == 'armijo':
while not converged and n_iter <= self.max_iterations and err < self.max_error:
residual = _constraint_function_wrapper(x_init)
if any(np.isnan(residual)):
raise RuntimeError("Nan in residual")
err = np.linalg.norm(residual)
jac = _jacobian_function_wrapper(x_init)
try:
if is_sparse:
LU = splu(jac)
dy0 = LU.solve(-residual)
else:
dy0 = np.linalg.solve(jac, -residual)
except np.linalg.LinAlgError as error:
logging.warning(error)
dy0, *_ = np.linalg.lstsq(jac, -residual)
a = 1e-4
reduct = 0.5
ll = 1
r_try = float('Inf')
step = None
while (r_try >= (1-a*ll) * err) and (r_try > self.tolerance) and ll > 0.05:
step = ll*dy0
res_try = _constraint_function_wrapper(x_init + step)
r_try = np.linalg.norm(res_try)
ll *= reduct
x_init += step
err = r_try
n_iter += 1
if err <= self.tolerance:
converged = True
if is_sparse:
logger.debug('BVP Iter {}\tResidual {:13.8E}\tJacobian condition {:13.8E}'
.format(n_iter, err, np.linalg.cond(jac.toarray())))
else:
logger.debug('BVP Iter {}\tResidual {:13.8E}\tJacobian condition {:13.8E}'
.format(n_iter, err, np.linalg.cond(jac)))
else:
raise NotImplementedError('Method \'' + self.algorithm + '\' is not implemented.')
"""
Post symbolic checks and formatting
"""
# Unwrap the solution from the solver to put in a readable format
y, q, parameter_guess, nondynamical_parameter_guess = self._unwrap_y0(x_init, n_odes, n_quads, n_dynparams,
self.num_arcs)
for ii in range(self.num_arcs):
gamma_set[ii].y[0] = y[ii]
if n_quads > 0:
gamma_set[ii].q[0] = q
gamma_set = _gamma_maker(pick_deriv, pick_quad, gamma_set, parameter_guess, sol, prop, pool, n_quads)
if err < self.tolerance and converged:
if n_iter == -1:
message = "Converged in an unknown number of iterations."
else:
message = "Converged in " + str(n_iter) + " iterations."
elif n_iter > self.max_iterations:
message = 'Max iterations exceeded.'
elif err > self.max_error:
message = 'Error exceeded max_error.'
else:
message = 'Solver stopped for unspecified reason'
# Stitch the arcs together to make a single trajectory, removing the boundary points inbetween each arc
t_out = gamma_set[0].t
y_out = gamma_set[0].y
q_out = gamma_set[0].q
u_out = gamma_set[0].u
for ii in range(self.num_arcs - 1):
t_out = np.hstack((t_out, gamma_set[ii + 1].t[1:]))
y_out = np.vstack((y_out, gamma_set[ii + 1].y[1:]))
q_out = np.vstack((q_out, gamma_set[ii + 1].q[1:]))
u_out = np.vstack((u_out, gamma_set[ii + 1].u[1:]))
sol.t = t_out
sol.y = y_out
sol.q = q_out
sol.u = u_out
sol.dynamical_parameters = parameter_guess
sol.nondynamical_parameters = nondynamical_parameter_guess
sol.converged = converged
out = BVPResult(sol=sol, success=converged, message=message,
niter=n_iter)
return out
|
{
"alphanum_fraction": 0.5402645136,
"author": null,
"avg_line_length": 41.49125,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "936485807d36304e59012009443a9cf613d1e9aa",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 12,
"max_forks_repo_forks_event_max_datetime": "2022-03-28T16:44:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-19T04:00:09.000Z",
"max_forks_repo_head_hexsha": "740bda376634945ef51bf1cf946fcbe002e9bc7f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "doublefloyd/beluga",
"max_forks_repo_path": "beluga/numeric/bvp_solvers/Shooting.py",
"max_issues_count": 187,
"max_issues_repo_head_hexsha": "740bda376634945ef51bf1cf946fcbe002e9bc7f",
"max_issues_repo_issues_event_max_datetime": "2021-01-27T15:04:18.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-02-04T20:35:03.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "doublefloyd/beluga",
"max_issues_repo_path": "beluga/numeric/bvp_solvers/Shooting.py",
"max_line_length": 129,
"max_stars_count": 20,
"max_stars_repo_head_hexsha": "740bda376634945ef51bf1cf946fcbe002e9bc7f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "doublefloyd/beluga",
"max_stars_repo_path": "beluga/numeric/bvp_solvers/Shooting.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-28T20:50:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-02T13:09:58.000Z",
"num_tokens": 9009,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 33193
}
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
! This file was ported from Lean 3 source module data.set.basic
! leanprover-community/mathlib commit 75608affb24b4f48699fbcd38f227827f7793771
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Order.SymmDiff
import Mathbin.Logic.Function.Iterate
/-!
# Basic properties of sets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements
have type `X` are thus defined as `set X := X → Prop`. Note that this function need not
be decidable. The definition is in the core library.
This file provides some basic definitions related to sets and functions not present in the core
library, as well as extra lemmas for functions in the core library (empty set, univ, union,
intersection, insert, singleton, set-theoretic difference, complement, and powerset).
Note that a set is a term, not a type. There is a coercion from `set α` to `Type*` sending
`s` to the corresponding subtype `↥s`.
See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean.
## Main definitions
Notation used here:
- `f : α → β` is a function,
- `s : set α` and `s₁ s₂ : set α` are subsets of `α`
- `t : set β` is a subset of `β`.
Definitions in the file:
* `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the
fact that `s` has an element (see the Implementation Notes).
* `subsingleton s : Prop` : the predicate saying that `s` has at most one element.
* `nontrivial s : Prop` : the predicate saying that `s` has at least two distinct elements.
* `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`.
## Notation
* `sᶜ` for the complement of `s`
## Implementation notes
* `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that
the `s.nonempty` dot notation can be used.
* For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`.
## Tags
set, sets, subset, subsets, union, intersection, insert, singleton, complement, powerset
-/
/-! ### Set coercion to a type -/
open Function
universe u v w x
namespace Set
variable {α : Type _} {s t : Set α}
instance : LE (Set α) :=
⟨fun s t => ∀ ⦃x⦄, x ∈ s → x ∈ t⟩
instance : HasSubset (Set α) :=
⟨(· ≤ ·)⟩
instance {α : Type _} : BooleanAlgebra (Set α) :=
{
(inferInstance :
BooleanAlgebra (α →
Prop)) with
sup := fun s t => { x | x ∈ s ∨ x ∈ t }
le := (· ≤ ·)
lt := fun s t => s ⊆ t ∧ ¬t ⊆ s
inf := fun s t => { x | x ∈ s ∧ x ∈ t }
bot := ∅
compl := fun s => { x | x ∉ s }
top := univ
sdiff := fun s t => { x | x ∈ s ∧ x ∉ t } }
instance : HasSSubset (Set α) :=
⟨(· < ·)⟩
instance : Union (Set α) :=
⟨(· ⊔ ·)⟩
instance : Inter (Set α) :=
⟨(· ⊓ ·)⟩
/- warning: set.top_eq_univ -> Set.top_eq_univ is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, Eq.{succ u1} (Set.{u1} α) (Top.top.{u1} (Set.{u1} α) (BooleanAlgebra.toHasTop.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (Set.univ.{u1} α)
but is expected to have type
forall {α : Type.{u1}}, Eq.{succ u1} (Set.{u1} α) (Top.top.{u1} (Set.{u1} α) (BooleanAlgebra.toTop.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (Set.univ.{u1} α)
Case conversion may be inaccurate. Consider using '#align set.top_eq_univ Set.top_eq_univₓ'. -/
@[simp]
theorem top_eq_univ : (⊤ : Set α) = univ :=
rfl
#align set.top_eq_univ Set.top_eq_univ
/- warning: set.bot_eq_empty -> Set.bot_eq_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, Eq.{succ u1} (Set.{u1} α) (Bot.bot.{u1} (Set.{u1} α) (BooleanAlgebra.toHasBot.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}}, Eq.{succ u1} (Set.{u1} α) (Bot.bot.{u1} (Set.{u1} α) (BooleanAlgebra.toBot.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.bot_eq_empty Set.bot_eq_emptyₓ'. -/
@[simp]
theorem bot_eq_empty : (⊥ : Set α) = ∅ :=
rfl
#align set.bot_eq_empty Set.bot_eq_empty
/- warning: set.sup_eq_union -> Set.sup_eq_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, Eq.{succ u1} ((Set.{u1} α) -> (Set.{u1} α) -> (Set.{u1} α)) (Sup.sup.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α))
but is expected to have type
forall {α : Type.{u1}}, Eq.{succ u1} ((Set.{u1} α) -> (Set.{u1} α) -> (Set.{u1} α)) (fun (x._@.Mathlib.Data.Set.Basic._hyg.334 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.336 : Set.{u1} α) => Sup.sup.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) x._@.Mathlib.Data.Set.Basic._hyg.334 x._@.Mathlib.Data.Set.Basic._hyg.336) (fun (x._@.Mathlib.Data.Set.Basic._hyg.349 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.351 : Set.{u1} α) => Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) x._@.Mathlib.Data.Set.Basic._hyg.349 x._@.Mathlib.Data.Set.Basic._hyg.351)
Case conversion may be inaccurate. Consider using '#align set.sup_eq_union Set.sup_eq_unionₓ'. -/
@[simp]
theorem sup_eq_union : ((· ⊔ ·) : Set α → Set α → Set α) = (· ∪ ·) :=
rfl
#align set.sup_eq_union Set.sup_eq_union
/- warning: set.inf_eq_inter -> Set.inf_eq_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, Eq.{succ u1} ((Set.{u1} α) -> (Set.{u1} α) -> (Set.{u1} α)) (Inf.inf.{u1} (Set.{u1} α) (SemilatticeInf.toHasInf.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α))
but is expected to have type
forall {α : Type.{u1}}, Eq.{succ u1} ((Set.{u1} α) -> (Set.{u1} α) -> (Set.{u1} α)) (fun (x._@.Mathlib.Data.Set.Basic._hyg.386 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.388 : Set.{u1} α) => Inf.inf.{u1} (Set.{u1} α) (Lattice.toInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))) x._@.Mathlib.Data.Set.Basic._hyg.386 x._@.Mathlib.Data.Set.Basic._hyg.388) (fun (x._@.Mathlib.Data.Set.Basic._hyg.401 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.403 : Set.{u1} α) => Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) x._@.Mathlib.Data.Set.Basic._hyg.401 x._@.Mathlib.Data.Set.Basic._hyg.403)
Case conversion may be inaccurate. Consider using '#align set.inf_eq_inter Set.inf_eq_interₓ'. -/
@[simp]
theorem inf_eq_inter : ((· ⊓ ·) : Set α → Set α → Set α) = (· ∩ ·) :=
rfl
#align set.inf_eq_inter Set.inf_eq_inter
#print Set.le_eq_subset /-
@[simp]
theorem le_eq_subset : ((· ≤ ·) : Set α → Set α → Prop) = (· ⊆ ·) :=
rfl
#align set.le_eq_subset Set.le_eq_subset
-/
/- warning: set.lt_eq_ssubset -> Set.lt_eq_ssubset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, Eq.{succ u1} ((Set.{u1} α) -> (Set.{u1} α) -> Prop) (LT.lt.{u1} (Set.{u1} α) (Preorder.toLT.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))))) (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α))
but is expected to have type
forall {α : Type.{u1}}, Eq.{succ u1} ((Set.{u1} α) -> (Set.{u1} α) -> Prop) (fun (x._@.Mathlib.Data.Set.Basic._hyg.488 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.490 : Set.{u1} α) => LT.lt.{u1} (Set.{u1} α) (Preorder.toLT.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) x._@.Mathlib.Data.Set.Basic._hyg.488 x._@.Mathlib.Data.Set.Basic._hyg.490) (fun (x._@.Mathlib.Data.Set.Basic._hyg.503 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.505 : Set.{u1} α) => HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) x._@.Mathlib.Data.Set.Basic._hyg.503 x._@.Mathlib.Data.Set.Basic._hyg.505)
Case conversion may be inaccurate. Consider using '#align set.lt_eq_ssubset Set.lt_eq_ssubsetₓ'. -/
@[simp]
theorem lt_eq_ssubset : ((· < ·) : Set α → Set α → Prop) = (· ⊂ ·) :=
rfl
#align set.lt_eq_ssubset Set.lt_eq_ssubset
#print Set.le_iff_subset /-
theorem le_iff_subset : s ≤ t ↔ s ⊆ t :=
Iff.rfl
#align set.le_iff_subset Set.le_iff_subset
-/
/- warning: set.lt_iff_ssubset -> Set.lt_iff_ssubset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (LT.lt.{u1} (Set.{u1} α) (Preorder.toLT.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))))) s t) (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (LT.lt.{u1} (Set.{u1} α) (Preorder.toLT.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) s t) (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.lt_iff_ssubset Set.lt_iff_ssubsetₓ'. -/
theorem lt_iff_ssubset : s < t ↔ s ⊂ t :=
Iff.rfl
#align set.lt_iff_ssubset Set.lt_iff_ssubset
alias le_iff_subset ↔ _root_.has_le.le.subset _root_.has_subset.subset.le
#align has_le.le.subset LE.le.subset
#align has_subset.subset.le HasSubset.Subset.le
/- warning: has_ssubset.ssubset.lt -> HasSSubset.SSubset.lt is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t) -> (LT.lt.{u1} (Set.{u1} α) (Preorder.toLT.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))))) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t) -> (LT.lt.{u1} (Set.{u1} α) (Preorder.toLT.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) s t)
Case conversion may be inaccurate. Consider using '#align has_ssubset.ssubset.lt HasSSubset.SSubset.ltₓ'. -/
alias lt_iff_ssubset ↔ _root_.has_lt.lt.ssubset _root_.has_ssubset.ssubset.lt
#align has_lt.lt.ssubset LT.lt.sSubset
#align has_ssubset.ssubset.lt HasSSubset.SSubset.lt
/-- Coercion from a set to the corresponding subtype. -/
instance {α : Type u} : CoeSort (Set α) (Type u) :=
⟨fun s => { x // x ∈ s }⟩
#print Set.PiSetCoe.canLift /-
instance PiSetCoe.canLift (ι : Type u) (α : ∀ i : ι, Type v) [ne : ∀ i, Nonempty (α i)]
(s : Set ι) : CanLift (∀ i : s, α i) (∀ i, α i) (fun f i => f i) fun _ => True :=
PiSubtype.canLift ι α s
#align set.pi_set_coe.can_lift Set.PiSetCoe.canLift
-/
#print Set.PiSetCoe.canLift' /-
instance PiSetCoe.canLift' (ι : Type u) (α : Type v) [ne : Nonempty α] (s : Set ι) :
CanLift (s → α) (ι → α) (fun f i => f i) fun _ => True :=
PiSetCoe.canLift ι (fun _ => α) s
#align set.pi_set_coe.can_lift' Set.PiSetCoe.canLift'
-/
end Set
section SetCoe
variable {α : Type u}
#print Set.coe_eq_subtype /-
theorem Set.coe_eq_subtype (s : Set α) : ↥s = { x // x ∈ s } :=
rfl
#align set.coe_eq_subtype Set.coe_eq_subtype
-/
#print Set.coe_setOf /-
@[simp]
theorem Set.coe_setOf (p : α → Prop) : ↥{ x | p x } = { x // p x } :=
rfl
#align set.coe_set_of Set.coe_setOf
-/
#print SetCoe.forall /-
@[simp]
theorem SetCoe.forall {s : Set α} {p : s → Prop} : (∀ x : s, p x) ↔ ∀ (x) (h : x ∈ s), p ⟨x, h⟩ :=
Subtype.forall
#align set_coe.forall SetCoe.forall
-/
#print SetCoe.exists /-
@[simp]
theorem SetCoe.exists {s : Set α} {p : s → Prop} :
(∃ x : s, p x) ↔ ∃ (x : _)(h : x ∈ s), p ⟨x, h⟩ :=
Subtype.exists
#align set_coe.exists SetCoe.exists
-/
#print SetCoe.exists' /-
theorem SetCoe.exists' {s : Set α} {p : ∀ x, x ∈ s → Prop} :
(∃ (x : _)(h : x ∈ s), p x h) ↔ ∃ x : s, p x x.2 :=
(@SetCoe.exists _ _ fun x => p x.1 x.2).symm
#align set_coe.exists' SetCoe.exists'
-/
#print SetCoe.forall' /-
theorem SetCoe.forall' {s : Set α} {p : ∀ x, x ∈ s → Prop} :
(∀ (x) (h : x ∈ s), p x h) ↔ ∀ x : s, p x x.2 :=
(@SetCoe.forall _ _ fun x => p x.1 x.2).symm
#align set_coe.forall' SetCoe.forall'
-/
#print set_coe_cast /-
@[simp]
theorem set_coe_cast :
∀ {s t : Set α} (H' : s = t) (H : ↥s = ↥t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩
| s, _, rfl, _, ⟨x, h⟩ => rfl
#align set_coe_cast set_coe_cast
-/
#print SetCoe.ext /-
theorem SetCoe.ext {s : Set α} {a b : s} : (↑a : α) = ↑b → a = b :=
Subtype.eq
#align set_coe.ext SetCoe.ext
-/
#print SetCoe.ext_iff /-
theorem SetCoe.ext_iff {s : Set α} {a b : s} : (↑a : α) = ↑b ↔ a = b :=
Iff.intro SetCoe.ext fun h => h ▸ rfl
#align set_coe.ext_iff SetCoe.ext_iff
-/
end SetCoe
#print Subtype.mem /-
/-- See also `subtype.prop` -/
theorem Subtype.mem {α : Type _} {s : Set α} (p : s) : (p : α) ∈ s :=
p.Prop
#align subtype.mem Subtype.mem
-/
#print Eq.subset /-
/-- Duplicate of `eq.subset'`, which currently has elaboration problems. -/
theorem Eq.subset {α} {s t : Set α} : s = t → s ⊆ t :=
Eq.subset'
#align eq.subset Eq.subset
-/
namespace Set
variable {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a b : α} {s s₁ s₂ t t₁ t₂ u : Set α}
instance : Inhabited (Set α) :=
⟨∅⟩
#print Set.ext /-
@[ext]
theorem ext {a b : Set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b :=
funext fun x => propext (h x)
#align set.ext Set.ext
-/
#print Set.ext_iff /-
theorem ext_iff {s t : Set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t :=
⟨fun h x => by rw [h], ext⟩
#align set.ext_iff Set.ext_iff
-/
#print Set.mem_of_mem_of_subset /-
@[trans]
theorem mem_of_mem_of_subset {x : α} {s t : Set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t :=
h hx
#align set.mem_of_mem_of_subset Set.mem_of_mem_of_subset
-/
#print Set.forall_in_swap /-
theorem forall_in_swap {p : α → β → Prop} : (∀ a ∈ s, ∀ (b), p a b) ↔ ∀ (b), ∀ a ∈ s, p a b := by
tauto
#align set.forall_in_swap Set.forall_in_swap
-/
/-! ### Lemmas about `mem` and `set_of` -/
#print Set.mem_setOf /-
theorem mem_setOf {a : α} {p : α → Prop} : a ∈ { x | p x } ↔ p a :=
Iff.rfl
#align set.mem_set_of Set.mem_setOf
-/
#print Membership.mem.out /-
/-- If `h : a ∈ {x | p x}` then `h.out : p x`. These are definitionally equal, but this can
nevertheless be useful for various reasons, e.g. to apply further projection notation or in an
argument to `simp`. -/
theorem Membership.mem.out {p : α → Prop} {a : α} (h : a ∈ { x | p x }) : p a :=
h
#align has_mem.mem.out Membership.mem.out
-/
#print Set.nmem_setOf_iff /-
theorem nmem_setOf_iff {a : α} {p : α → Prop} : a ∉ { x | p x } ↔ ¬p a :=
Iff.rfl
#align set.nmem_set_of_iff Set.nmem_setOf_iff
-/
#print Set.setOf_mem_eq /-
@[simp]
theorem setOf_mem_eq {s : Set α} : { x | x ∈ s } = s :=
rfl
#align set.set_of_mem_eq Set.setOf_mem_eq
-/
#print Set.setOf_set /-
theorem setOf_set {s : Set α} : setOf s = s :=
rfl
#align set.set_of_set Set.setOf_set
-/
#print Set.setOf_app_iff /-
theorem setOf_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x :=
Iff.rfl
#align set.set_of_app_iff Set.setOf_app_iff
-/
#print Set.mem_def /-
theorem mem_def {a : α} {s : Set α} : a ∈ s ↔ s a :=
Iff.rfl
#align set.mem_def Set.mem_def
-/
#print Set.setOf_bijective /-
theorem setOf_bijective : Bijective (setOf : (α → Prop) → Set α) :=
bijective_id
#align set.set_of_bijective Set.setOf_bijective
-/
#print Set.setOf_subset_setOf /-
@[simp]
theorem setOf_subset_setOf {p q : α → Prop} : { a | p a } ⊆ { a | q a } ↔ ∀ a, p a → q a :=
Iff.rfl
#align set.set_of_subset_set_of Set.setOf_subset_setOf
-/
/- warning: set.set_of_and -> Set.setOf_and is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {p : α -> Prop} {q : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (setOf.{u1} α (fun (a : α) => And (p a) (q a))) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (setOf.{u1} α (fun (a : α) => p a)) (setOf.{u1} α (fun (a : α) => q a)))
but is expected to have type
forall {α : Type.{u1}} {p : α -> Prop} {q : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (setOf.{u1} α (fun (a : α) => And (p a) (q a))) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (setOf.{u1} α (fun (a : α) => p a)) (setOf.{u1} α (fun (a : α) => q a)))
Case conversion may be inaccurate. Consider using '#align set.set_of_and Set.setOf_andₓ'. -/
theorem setOf_and {p q : α → Prop} : { a | p a ∧ q a } = { a | p a } ∩ { a | q a } :=
rfl
#align set.set_of_and Set.setOf_and
/- warning: set.set_of_or -> Set.setOf_or is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {p : α -> Prop} {q : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (setOf.{u1} α (fun (a : α) => Or (p a) (q a))) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (setOf.{u1} α (fun (a : α) => p a)) (setOf.{u1} α (fun (a : α) => q a)))
but is expected to have type
forall {α : Type.{u1}} {p : α -> Prop} {q : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (setOf.{u1} α (fun (a : α) => Or (p a) (q a))) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (setOf.{u1} α (fun (a : α) => p a)) (setOf.{u1} α (fun (a : α) => q a)))
Case conversion may be inaccurate. Consider using '#align set.set_of_or Set.setOf_orₓ'. -/
theorem setOf_or {p q : α → Prop} : { a | p a ∨ q a } = { a | p a } ∪ { a | q a } :=
rfl
#align set.set_of_or Set.setOf_or
/-! ### Subset and strict subset relations -/
instance : IsRefl (Set α) (· ⊆ ·) :=
LE.le.isRefl
instance : IsTrans (Set α) (· ⊆ ·) :=
LE.le.isTrans
instance : IsAntisymm (Set α) (· ⊆ ·) :=
LE.le.isAntisymm
instance : IsIrrefl (Set α) (· ⊂ ·) :=
LT.lt.isIrrefl
instance : IsTrans (Set α) (· ⊂ ·) :=
LT.lt.isTrans
instance : IsAsymm (Set α) (· ⊂ ·) :=
LT.lt.isAsymm
instance : IsNonstrictStrictOrder (Set α) (· ⊆ ·) (· ⊂ ·) :=
⟨fun _ _ => Iff.rfl⟩
#print Set.subset_def /-
-- TODO(Jeremy): write a tactic to unfold specific instances of generic notation?
theorem subset_def : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t :=
rfl
#align set.subset_def Set.subset_def
-/
/- warning: set.ssubset_def -> Set.ssubset_def is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{1} Prop (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{1} Prop (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s)))
Case conversion may be inaccurate. Consider using '#align set.ssubset_def Set.ssubset_defₓ'. -/
theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ ¬t ⊆ s) :=
rfl
#align set.ssubset_def Set.ssubset_def
#print Set.Subset.refl /-
@[refl]
theorem Subset.refl (a : Set α) : a ⊆ a := fun x => id
#align set.subset.refl Set.Subset.refl
-/
#print Set.Subset.rfl /-
theorem Subset.rfl {s : Set α} : s ⊆ s :=
Subset.refl s
#align set.subset.rfl Set.Subset.rfl
-/
#print Set.Subset.trans /-
@[trans]
theorem Subset.trans {a b c : Set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := fun x h => bc <| ab h
#align set.subset.trans Set.Subset.trans
-/
#print Set.mem_of_eq_of_mem /-
@[trans]
theorem mem_of_eq_of_mem {x y : α} {s : Set α} (hx : x = y) (h : y ∈ s) : x ∈ s :=
hx.symm ▸ h
#align set.mem_of_eq_of_mem Set.mem_of_eq_of_mem
-/
#print Set.Subset.antisymm /-
theorem Subset.antisymm {a b : Set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b :=
Set.ext fun x => ⟨@h₁ _, @h₂ _⟩
#align set.subset.antisymm Set.Subset.antisymm
-/
#print Set.Subset.antisymm_iff /-
theorem Subset.antisymm_iff {a b : Set α} : a = b ↔ a ⊆ b ∧ b ⊆ a :=
⟨fun e => ⟨e.Subset, e.symm.Subset⟩, fun ⟨h₁, h₂⟩ => Subset.antisymm h₁ h₂⟩
#align set.subset.antisymm_iff Set.Subset.antisymm_iff
-/
#print Set.eq_of_subset_of_subset /-
-- an alternative name
theorem eq_of_subset_of_subset {a b : Set α} : a ⊆ b → b ⊆ a → a = b :=
Subset.antisymm
#align set.eq_of_subset_of_subset Set.eq_of_subset_of_subset
-/
#print Set.mem_of_subset_of_mem /-
theorem mem_of_subset_of_mem {s₁ s₂ : Set α} {a : α} (h : s₁ ⊆ s₂) : a ∈ s₁ → a ∈ s₂ :=
@h _
#align set.mem_of_subset_of_mem Set.mem_of_subset_of_mem
-/
#print Set.not_mem_subset /-
theorem not_mem_subset (h : s ⊆ t) : a ∉ t → a ∉ s :=
mt <| mem_of_subset_of_mem h
#align set.not_mem_subset Set.not_mem_subset
-/
/- warning: set.not_subset -> Set.not_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t)) (Exists.{succ u1} α (fun (a : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s) => Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t))))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t)) (Exists.{succ u1} α (fun (a : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t))))
Case conversion may be inaccurate. Consider using '#align set.not_subset Set.not_subsetₓ'. -/
theorem not_subset : ¬s ⊆ t ↔ ∃ a ∈ s, a ∉ t := by simp only [subset_def, not_forall]
#align set.not_subset Set.not_subset
/-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/
/- warning: set.eq_or_ssubset_of_subset -> Set.eq_or_ssubset_of_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (Or (Eq.{succ u1} (Set.{u1} α) s t) (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (Or (Eq.{succ u1} (Set.{u1} α) s t) (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.eq_or_ssubset_of_subset Set.eq_or_ssubset_of_subsetₓ'. -/
protected theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t :=
eq_or_lt_of_le h
#align set.eq_or_ssubset_of_subset Set.eq_or_ssubset_of_subset
/- warning: set.exists_of_ssubset -> Set.exists_of_ssubset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t) -> (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t) => Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s))))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t) -> (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s))))
Case conversion may be inaccurate. Consider using '#align set.exists_of_ssubset Set.exists_of_ssubsetₓ'. -/
theorem exists_of_ssubset {s t : Set α} (h : s ⊂ t) : ∃ x ∈ t, x ∉ s :=
not_subset.1 h.2
#align set.exists_of_ssubset Set.exists_of_ssubset
/- warning: set.ssubset_iff_subset_ne -> Set.ssubset_iff_subset_ne is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) (Ne.{succ u1} (Set.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) (Ne.{succ u1} (Set.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.ssubset_iff_subset_ne Set.ssubset_iff_subset_neₓ'. -/
protected theorem ssubset_iff_subset_ne {s t : Set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t :=
@lt_iff_le_and_ne (Set α) _ s t
#align set.ssubset_iff_subset_ne Set.ssubset_iff_subset_ne
/- warning: set.ssubset_iff_of_subset -> Set.ssubset_iff_of_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t) (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t) => Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s)))))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s)))))
Case conversion may be inaccurate. Consider using '#align set.ssubset_iff_of_subset Set.ssubset_iff_of_subsetₓ'. -/
theorem ssubset_iff_of_subset {s t : Set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s :=
⟨exists_of_ssubset, fun ⟨x, hxt, hxs⟩ => ⟨h, fun h => hxs <| h hxt⟩⟩
#align set.ssubset_iff_of_subset Set.ssubset_iff_of_subset
/- warning: set.ssubset_of_ssubset_of_subset -> Set.ssubset_of_ssubset_of_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {s₃ : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₂ s₃) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s₁ s₃)
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {s₃ : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₂ s₃) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s₁ s₃)
Case conversion may be inaccurate. Consider using '#align set.ssubset_of_ssubset_of_subset Set.ssubset_of_ssubset_of_subsetₓ'. -/
protected theorem ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : Set α} (hs₁s₂ : s₁ ⊂ s₂)
(hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ :=
⟨Subset.trans hs₁s₂.1 hs₂s₃, fun hs₃s₁ => hs₁s₂.2 (Subset.trans hs₂s₃ hs₃s₁)⟩
#align set.ssubset_of_ssubset_of_subset Set.ssubset_of_ssubset_of_subset
/- warning: set.ssubset_of_subset_of_ssubset -> Set.ssubset_of_subset_of_ssubset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {s₃ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₁ s₂) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s₂ s₃) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s₁ s₃)
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {s₃ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₁ s₂) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s₂ s₃) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s₁ s₃)
Case conversion may be inaccurate. Consider using '#align set.ssubset_of_subset_of_ssubset Set.ssubset_of_subset_of_ssubsetₓ'. -/
protected theorem ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : Set α} (hs₁s₂ : s₁ ⊆ s₂)
(hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ :=
⟨Subset.trans hs₁s₂ hs₂s₃.1, fun hs₃s₁ => hs₂s₃.2 (Subset.trans hs₃s₁ hs₁s₂)⟩
#align set.ssubset_of_subset_of_ssubset Set.ssubset_of_subset_of_ssubset
#print Set.not_mem_empty /-
theorem not_mem_empty (x : α) : ¬x ∈ (∅ : Set α) :=
id
#align set.not_mem_empty Set.not_mem_empty
-/
#print Set.not_not_mem /-
@[simp]
theorem not_not_mem : ¬a ∉ s ↔ a ∈ s :=
Classical.not_not
#align set.not_not_mem Set.not_not_mem
-/
/-! ### Non-empty sets -/
#print Set.Nonempty /-
/-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def Nonempty (s : Set α) : Prop :=
∃ x, x ∈ s
#align set.nonempty Set.Nonempty
-/
#print Set.nonempty_coe_sort /-
@[simp]
theorem nonempty_coe_sort {s : Set α} : Nonempty ↥s ↔ s.Nonempty :=
nonempty_subtype
#align set.nonempty_coe_sort Set.nonempty_coe_sort
-/
alias nonempty_coe_sort ↔ _ nonempty.coe_sort
#align set.nonempty.coe_sort Set.Nonempty.coe_sort
#print Set.nonempty_def /-
theorem nonempty_def : s.Nonempty ↔ ∃ x, x ∈ s :=
Iff.rfl
#align set.nonempty_def Set.nonempty_def
-/
#print Set.nonempty_of_mem /-
theorem nonempty_of_mem {x} (h : x ∈ s) : s.Nonempty :=
⟨x, h⟩
#align set.nonempty_of_mem Set.nonempty_of_mem
-/
#print Set.Nonempty.not_subset_empty /-
theorem Nonempty.not_subset_empty : s.Nonempty → ¬s ⊆ ∅
| ⟨x, hx⟩, hs => hs hx
#align set.nonempty.not_subset_empty Set.Nonempty.not_subset_empty
-/
#print Set.Nonempty.some /-
/-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis
on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/
protected noncomputable def Nonempty.some (h : s.Nonempty) : α :=
Classical.choose h
#align set.nonempty.some Set.Nonempty.some
-/
#print Set.Nonempty.some_mem /-
protected theorem Nonempty.some_mem (h : s.Nonempty) : h.some ∈ s :=
Classical.choose_spec h
#align set.nonempty.some_mem Set.Nonempty.some_mem
-/
#print Set.Nonempty.mono /-
theorem Nonempty.mono (ht : s ⊆ t) (hs : s.Nonempty) : t.Nonempty :=
hs.imp ht
#align set.nonempty.mono Set.Nonempty.mono
-/
/- warning: set.nonempty_of_not_subset -> Set.nonempty_of_not_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t)) -> (Set.Nonempty.{u1} α (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t)) -> (Set.Nonempty.{u1} α (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.nonempty_of_not_subset Set.nonempty_of_not_subsetₓ'. -/
theorem nonempty_of_not_subset (h : ¬s ⊆ t) : (s \ t).Nonempty :=
let ⟨x, xs, xt⟩ := not_subset.1 h
⟨x, xs, xt⟩
#align set.nonempty_of_not_subset Set.nonempty_of_not_subset
/- warning: set.nonempty_of_ssubset -> Set.nonempty_of_ssubset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t) -> (Set.Nonempty.{u1} α (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t s))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t) -> (Set.Nonempty.{u1} α (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t s))
Case conversion may be inaccurate. Consider using '#align set.nonempty_of_ssubset Set.nonempty_of_ssubsetₓ'. -/
theorem nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).Nonempty :=
nonempty_of_not_subset ht.2
#align set.nonempty_of_ssubset Set.nonempty_of_ssubset
/- warning: set.nonempty.of_diff -> Set.Nonempty.of_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)) -> (Set.Nonempty.{u1} α s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)) -> (Set.Nonempty.{u1} α s)
Case conversion may be inaccurate. Consider using '#align set.nonempty.of_diff Set.Nonempty.of_diffₓ'. -/
theorem Nonempty.of_diff (h : (s \ t).Nonempty) : s.Nonempty :=
h.imp fun _ => And.left
#align set.nonempty.of_diff Set.Nonempty.of_diff
/- warning: set.nonempty_of_ssubset' -> Set.nonempty_of_ssubset' is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t) -> (Set.Nonempty.{u1} α t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t) -> (Set.Nonempty.{u1} α t)
Case conversion may be inaccurate. Consider using '#align set.nonempty_of_ssubset' Set.nonempty_of_ssubset'ₓ'. -/
theorem nonempty_of_ssubset' (ht : s ⊂ t) : t.Nonempty :=
(nonempty_of_ssubset ht).of_diff
#align set.nonempty_of_ssubset' Set.nonempty_of_ssubset'
/- warning: set.nonempty.inl -> Set.Nonempty.inl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α s) -> (Set.Nonempty.{u1} α (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α s) -> (Set.Nonempty.{u1} α (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.nonempty.inl Set.Nonempty.inlₓ'. -/
theorem Nonempty.inl (hs : s.Nonempty) : (s ∪ t).Nonempty :=
hs.imp fun _ => Or.inl
#align set.nonempty.inl Set.Nonempty.inl
/- warning: set.nonempty.inr -> Set.Nonempty.inr is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α t) -> (Set.Nonempty.{u1} α (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α t) -> (Set.Nonempty.{u1} α (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.nonempty.inr Set.Nonempty.inrₓ'. -/
theorem Nonempty.inr (ht : t.Nonempty) : (s ∪ t).Nonempty :=
ht.imp fun _ => Or.inr
#align set.nonempty.inr Set.Nonempty.inr
/- warning: set.union_nonempty -> Set.union_nonempty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)) (Or (Set.Nonempty.{u1} α s) (Set.Nonempty.{u1} α t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)) (Or (Set.Nonempty.{u1} α s) (Set.Nonempty.{u1} α t))
Case conversion may be inaccurate. Consider using '#align set.union_nonempty Set.union_nonemptyₓ'. -/
@[simp]
theorem union_nonempty : (s ∪ t).Nonempty ↔ s.Nonempty ∨ t.Nonempty :=
exists_or
#align set.union_nonempty Set.union_nonempty
/- warning: set.nonempty.left -> Set.Nonempty.left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) -> (Set.Nonempty.{u1} α s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) -> (Set.Nonempty.{u1} α s)
Case conversion may be inaccurate. Consider using '#align set.nonempty.left Set.Nonempty.leftₓ'. -/
theorem Nonempty.left (h : (s ∩ t).Nonempty) : s.Nonempty :=
h.imp fun _ => And.left
#align set.nonempty.left Set.Nonempty.left
/- warning: set.nonempty.right -> Set.Nonempty.right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) -> (Set.Nonempty.{u1} α t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) -> (Set.Nonempty.{u1} α t)
Case conversion may be inaccurate. Consider using '#align set.nonempty.right Set.Nonempty.rightₓ'. -/
theorem Nonempty.right (h : (s ∩ t).Nonempty) : t.Nonempty :=
h.imp fun _ => And.right
#align set.nonempty.right Set.Nonempty.right
/- warning: set.inter_nonempty -> Set.inter_nonempty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) (Exists.{succ u1} α (fun (x : α) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t)))
Case conversion may be inaccurate. Consider using '#align set.inter_nonempty Set.inter_nonemptyₓ'. -/
theorem inter_nonempty : (s ∩ t).Nonempty ↔ ∃ x, x ∈ s ∧ x ∈ t :=
Iff.rfl
#align set.inter_nonempty Set.inter_nonempty
/- warning: set.inter_nonempty_iff_exists_left -> Set.inter_nonempty_iff_exists_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) => Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t)))
Case conversion may be inaccurate. Consider using '#align set.inter_nonempty_iff_exists_left Set.inter_nonempty_iff_exists_leftₓ'. -/
theorem inter_nonempty_iff_exists_left : (s ∩ t).Nonempty ↔ ∃ x ∈ s, x ∈ t := by
simp_rw [inter_nonempty, exists_prop]
#align set.inter_nonempty_iff_exists_left Set.inter_nonempty_iff_exists_left
/- warning: set.inter_nonempty_iff_exists_right -> Set.inter_nonempty_iff_exists_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t) => Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s)))
Case conversion may be inaccurate. Consider using '#align set.inter_nonempty_iff_exists_right Set.inter_nonempty_iff_exists_rightₓ'. -/
theorem inter_nonempty_iff_exists_right : (s ∩ t).Nonempty ↔ ∃ x ∈ t, x ∈ s := by
simp_rw [inter_nonempty, exists_prop, and_comm']
#align set.inter_nonempty_iff_exists_right Set.inter_nonempty_iff_exists_right
#print Set.nonempty_iff_univ_nonempty /-
theorem nonempty_iff_univ_nonempty : Nonempty α ↔ (univ : Set α).Nonempty :=
⟨fun ⟨x⟩ => ⟨x, trivial⟩, fun ⟨x, _⟩ => ⟨x⟩⟩
#align set.nonempty_iff_univ_nonempty Set.nonempty_iff_univ_nonempty
-/
#print Set.univ_nonempty /-
@[simp]
theorem univ_nonempty : ∀ [h : Nonempty α], (univ : Set α).Nonempty
| ⟨x⟩ => ⟨x, trivial⟩
#align set.univ_nonempty Set.univ_nonempty
-/
#print Set.Nonempty.to_subtype /-
theorem Nonempty.to_subtype : s.Nonempty → Nonempty s :=
nonempty_subtype.2
#align set.nonempty.to_subtype Set.Nonempty.to_subtype
-/
#print Set.Nonempty.to_type /-
theorem Nonempty.to_type : s.Nonempty → Nonempty α := fun ⟨x, hx⟩ => ⟨x⟩
#align set.nonempty.to_type Set.Nonempty.to_type
-/
instance [Nonempty α] : Nonempty (Set.univ : Set α) :=
Set.univ_nonempty.to_subtype
#print Set.nonempty_of_nonempty_subtype /-
theorem nonempty_of_nonempty_subtype [Nonempty s] : s.Nonempty :=
nonempty_subtype.mp ‹_›
#align set.nonempty_of_nonempty_subtype Set.nonempty_of_nonempty_subtype
-/
/-! ### Lemmas about the empty set -/
/- warning: set.empty_def -> Set.empty_def is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, Eq.{succ u1} (Set.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)) (setOf.{u1} α (fun (x : α) => False))
but is expected to have type
forall {α : Type.{u1}}, Eq.{succ (succ u1)} Type.{u1} (Set.Elem.{u1} α (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (Set.Elem.{u1} α (setOf.{u1} α (fun (_x : α) => False)))
Case conversion may be inaccurate. Consider using '#align set.empty_def Set.empty_defₓ'. -/
theorem empty_def : (∅ : Set α) = { x | False } :=
rfl
#align set.empty_def Set.empty_def
#print Set.mem_empty_iff_false /-
@[simp]
theorem mem_empty_iff_false (x : α) : x ∈ (∅ : Set α) ↔ False :=
Iff.rfl
#align set.mem_empty_iff_false Set.mem_empty_iff_false
-/
#print Set.setOf_false /-
@[simp]
theorem setOf_false : { a : α | False } = ∅ :=
rfl
#align set.set_of_false Set.setOf_false
-/
#print Set.empty_subset /-
@[simp]
theorem empty_subset (s : Set α) : ∅ ⊆ s :=
fun.
#align set.empty_subset Set.empty_subset
-/
#print Set.subset_empty_iff /-
theorem subset_empty_iff {s : Set α} : s ⊆ ∅ ↔ s = ∅ :=
(Subset.antisymm_iff.trans <| and_iff_left (empty_subset _)).symm
#align set.subset_empty_iff Set.subset_empty_iff
-/
#print Set.eq_empty_iff_forall_not_mem /-
theorem eq_empty_iff_forall_not_mem {s : Set α} : s = ∅ ↔ ∀ x, x ∉ s :=
subset_empty_iff.symm
#align set.eq_empty_iff_forall_not_mem Set.eq_empty_iff_forall_not_mem
-/
#print Set.eq_empty_of_forall_not_mem /-
theorem eq_empty_of_forall_not_mem (h : ∀ x, x ∉ s) : s = ∅ :=
subset_empty_iff.1 h
#align set.eq_empty_of_forall_not_mem Set.eq_empty_of_forall_not_mem
-/
#print Set.eq_empty_of_subset_empty /-
theorem eq_empty_of_subset_empty {s : Set α} : s ⊆ ∅ → s = ∅ :=
subset_empty_iff.1
#align set.eq_empty_of_subset_empty Set.eq_empty_of_subset_empty
-/
#print Set.eq_empty_of_isEmpty /-
theorem eq_empty_of_isEmpty [IsEmpty α] (s : Set α) : s = ∅ :=
eq_empty_of_subset_empty fun x hx => isEmptyElim x
#align set.eq_empty_of_is_empty Set.eq_empty_of_isEmpty
-/
#print Set.uniqueEmpty /-
/-- There is exactly one set of a type that is empty. -/
instance uniqueEmpty [IsEmpty α] : Unique (Set α)
where
default := ∅
uniq := eq_empty_of_isEmpty
#align set.unique_empty Set.uniqueEmpty
-/
#print Set.not_nonempty_iff_eq_empty /-
/-- See also `set.nonempty_iff_ne_empty`. -/
theorem not_nonempty_iff_eq_empty {s : Set α} : ¬s.Nonempty ↔ s = ∅ := by
simp only [Set.Nonempty, eq_empty_iff_forall_not_mem, not_exists]
#align set.not_nonempty_iff_eq_empty Set.not_nonempty_iff_eq_empty
-/
#print Set.nonempty_iff_ne_empty /-
/-- See also `set.not_nonempty_iff_eq_empty`. -/
theorem nonempty_iff_ne_empty : s.Nonempty ↔ s ≠ ∅ :=
not_nonempty_iff_eq_empty.not_right
#align set.nonempty_iff_ne_empty Set.nonempty_iff_ne_empty
-/
alias nonempty_iff_ne_empty ↔ nonempty.ne_empty _
#align set.nonempty.ne_empty Set.Nonempty.ne_empty
#print Set.not_nonempty_empty /-
@[simp]
theorem not_nonempty_empty : ¬(∅ : Set α).Nonempty := fun ⟨x, hx⟩ => hx
#align set.not_nonempty_empty Set.not_nonempty_empty
-/
#print Set.isEmpty_coe_sort /-
@[simp]
theorem isEmpty_coe_sort {s : Set α} : IsEmpty ↥s ↔ s = ∅ :=
not_iff_not.1 <| by simpa using nonempty_iff_ne_empty
#align set.is_empty_coe_sort Set.isEmpty_coe_sort
-/
#print Set.eq_empty_or_nonempty /-
theorem eq_empty_or_nonempty (s : Set α) : s = ∅ ∨ s.Nonempty :=
or_iff_not_imp_left.2 nonempty_iff_ne_empty.2
#align set.eq_empty_or_nonempty Set.eq_empty_or_nonempty
-/
#print Set.subset_eq_empty /-
theorem subset_eq_empty {s t : Set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ :=
subset_empty_iff.1 <| e ▸ h
#align set.subset_eq_empty Set.subset_eq_empty
-/
#print Set.ball_empty_iff /-
theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : Set α), p x) ↔ True :=
iff_true_intro fun x => False.elim
#align set.ball_empty_iff Set.ball_empty_iff
-/
instance (α : Type u) : IsEmpty.{u + 1} (∅ : Set α) :=
⟨fun x => x.2⟩
/- warning: set.empty_ssubset -> Set.empty_ssubset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)) s) (Set.Nonempty.{u1} α s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)) s) (Set.Nonempty.{u1} α s)
Case conversion may be inaccurate. Consider using '#align set.empty_ssubset Set.empty_ssubsetₓ'. -/
@[simp]
theorem empty_ssubset : ∅ ⊂ s ↔ s.Nonempty :=
(@bot_lt_iff_ne_bot (Set α) _ _ _).trans nonempty_iff_ne_empty.symm
#align set.empty_ssubset Set.empty_ssubset
/- warning: set.nonempty.empty_ssubset -> Set.Nonempty.empty_ssubset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, (Set.Nonempty.{u1} α s) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)) s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, (Set.Nonempty.{u1} α s) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)) s)
Case conversion may be inaccurate. Consider using '#align set.nonempty.empty_ssubset Set.Nonempty.empty_ssubsetₓ'. -/
alias empty_ssubset ↔ _ nonempty.empty_ssubset
#align set.nonempty.empty_ssubset Set.Nonempty.empty_ssubset
/-!
### Universal set.
In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`.
Mathematically it is the same as `α` but it has a different type.
-/
#print Set.setOf_true /-
@[simp]
theorem setOf_true : { x : α | True } = univ :=
rfl
#align set.set_of_true Set.setOf_true
-/
#print Set.mem_univ /-
@[simp]
theorem mem_univ (x : α) : x ∈ @univ α :=
trivial
#align set.mem_univ Set.mem_univ
-/
#print Set.univ_eq_empty_iff /-
@[simp]
theorem univ_eq_empty_iff : (univ : Set α) = ∅ ↔ IsEmpty α :=
eq_empty_iff_forall_not_mem.trans
⟨fun H => ⟨fun x => H x trivial⟩, fun H x _ => @IsEmpty.false α H x⟩
#align set.univ_eq_empty_iff Set.univ_eq_empty_iff
-/
#print Set.empty_ne_univ /-
theorem empty_ne_univ [Nonempty α] : (∅ : Set α) ≠ univ := fun e =>
not_isEmpty_of_nonempty α <| univ_eq_empty_iff.1 e.symm
#align set.empty_ne_univ Set.empty_ne_univ
-/
#print Set.subset_univ /-
@[simp]
theorem subset_univ (s : Set α) : s ⊆ univ := fun x H => trivial
#align set.subset_univ Set.subset_univ
-/
#print Set.univ_subset_iff /-
theorem univ_subset_iff {s : Set α} : univ ⊆ s ↔ s = univ :=
@top_le_iff _ _ _ s
#align set.univ_subset_iff Set.univ_subset_iff
-/
alias univ_subset_iff ↔ eq_univ_of_univ_subset _
#align set.eq_univ_of_univ_subset Set.eq_univ_of_univ_subset
#print Set.eq_univ_iff_forall /-
theorem eq_univ_iff_forall {s : Set α} : s = univ ↔ ∀ x, x ∈ s :=
univ_subset_iff.symm.trans <| forall_congr' fun x => imp_iff_right trivial
#align set.eq_univ_iff_forall Set.eq_univ_iff_forall
-/
#print Set.eq_univ_of_forall /-
theorem eq_univ_of_forall {s : Set α} : (∀ x, x ∈ s) → s = univ :=
eq_univ_iff_forall.2
#align set.eq_univ_of_forall Set.eq_univ_of_forall
-/
#print Set.Nonempty.eq_univ /-
theorem Nonempty.eq_univ [Subsingleton α] : s.Nonempty → s = univ :=
by
rintro ⟨x, hx⟩
refine' eq_univ_of_forall fun y => by rwa [Subsingleton.elim y x]
#align set.nonempty.eq_univ Set.Nonempty.eq_univ
-/
#print Set.eq_univ_of_subset /-
theorem eq_univ_of_subset {s t : Set α} (h : s ⊆ t) (hs : s = univ) : t = univ :=
eq_univ_of_univ_subset <| hs ▸ h
#align set.eq_univ_of_subset Set.eq_univ_of_subset
-/
#print Set.exists_mem_of_nonempty /-
theorem exists_mem_of_nonempty (α) : ∀ [Nonempty α], ∃ x : α, x ∈ (univ : Set α)
| ⟨x⟩ => ⟨x, trivial⟩
#align set.exists_mem_of_nonempty Set.exists_mem_of_nonempty
-/
#print Set.ne_univ_iff_exists_not_mem /-
theorem ne_univ_iff_exists_not_mem {α : Type _} (s : Set α) : s ≠ univ ↔ ∃ a, a ∉ s := by
rw [← not_forall, ← eq_univ_iff_forall]
#align set.ne_univ_iff_exists_not_mem Set.ne_univ_iff_exists_not_mem
-/
#print Set.not_subset_iff_exists_mem_not_mem /-
theorem not_subset_iff_exists_mem_not_mem {α : Type _} {s t : Set α} :
¬s ⊆ t ↔ ∃ x, x ∈ s ∧ x ∉ t := by simp [subset_def]
#align set.not_subset_iff_exists_mem_not_mem Set.not_subset_iff_exists_mem_not_mem
-/
#print Set.univ_unique /-
theorem univ_unique [Unique α] : @Set.univ α = {default} :=
Set.ext fun x => iff_of_true trivial <| Subsingleton.elim x default
#align set.univ_unique Set.univ_unique
-/
/- warning: set.ssubset_univ_iff -> Set.ssubset_univ_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s (Set.univ.{u1} α)) (Ne.{succ u1} (Set.{u1} α) s (Set.univ.{u1} α))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s (Set.univ.{u1} α)) (Ne.{succ u1} (Set.{u1} α) s (Set.univ.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.ssubset_univ_iff Set.ssubset_univ_iffₓ'. -/
theorem ssubset_univ_iff : s ⊂ univ ↔ s ≠ univ :=
lt_top_iff_ne_top
#align set.ssubset_univ_iff Set.ssubset_univ_iff
#print Set.nontrivial_of_nonempty /-
instance nontrivial_of_nonempty [Nonempty α] : Nontrivial (Set α) :=
⟨⟨∅, univ, empty_ne_univ⟩⟩
#align set.nontrivial_of_nonempty Set.nontrivial_of_nonempty
-/
/-! ### Lemmas about union -/
/- warning: set.union_def -> Set.union_def is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₁ s₂) (setOf.{u1} α (fun (a : α) => Or (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s₁) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s₂)))
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₁ s₂) (setOf.{u1} α (fun (a : α) => Or (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s₁) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s₂)))
Case conversion may be inaccurate. Consider using '#align set.union_def Set.union_defₓ'. -/
theorem union_def {s₁ s₂ : Set α} : s₁ ∪ s₂ = { a | a ∈ s₁ ∨ a ∈ s₂ } :=
rfl
#align set.union_def Set.union_def
/- warning: set.mem_union_left -> Set.mem_union_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} (b : Set.{u1} α), (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x a) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a b))
but is expected to have type
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} (b : Set.{u1} α), (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x a) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a b))
Case conversion may be inaccurate. Consider using '#align set.mem_union_left Set.mem_union_leftₓ'. -/
theorem mem_union_left {x : α} {a : Set α} (b : Set α) : x ∈ a → x ∈ a ∪ b :=
Or.inl
#align set.mem_union_left Set.mem_union_left
/- warning: set.mem_union_right -> Set.mem_union_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {b : Set.{u1} α} (a : Set.{u1} α), (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x b) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a b))
but is expected to have type
forall {α : Type.{u1}} {x : α} {b : Set.{u1} α} (a : Set.{u1} α), (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x b) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a b))
Case conversion may be inaccurate. Consider using '#align set.mem_union_right Set.mem_union_rightₓ'. -/
theorem mem_union_right {x : α} {b : Set α} (a : Set α) : x ∈ b → x ∈ a ∪ b :=
Or.inr
#align set.mem_union_right Set.mem_union_right
/- warning: set.mem_or_mem_of_mem_union -> Set.mem_or_mem_of_mem_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a b)) -> (Or (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x a) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x b))
but is expected to have type
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a b)) -> (Or (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x a) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x b))
Case conversion may be inaccurate. Consider using '#align set.mem_or_mem_of_mem_union Set.mem_or_mem_of_mem_unionₓ'. -/
theorem mem_or_mem_of_mem_union {x : α} {a b : Set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b :=
H
#align set.mem_or_mem_of_mem_union Set.mem_or_mem_of_mem_union
/- warning: set.mem_union.elim -> Set.MemUnion.elim is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α} {P : Prop}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a b)) -> ((Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x a) -> P) -> ((Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x b) -> P) -> P
but is expected to have type
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α} {P : Prop}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a b)) -> ((Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x a) -> P) -> ((Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x b) -> P) -> P
Case conversion may be inaccurate. Consider using '#align set.mem_union.elim Set.MemUnion.elimₓ'. -/
theorem MemUnion.elim {x : α} {a b : Set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P)
(H₃ : x ∈ b → P) : P :=
Or.elim H₁ H₂ H₃
#align set.mem_union.elim Set.MemUnion.elim
/- warning: set.mem_union -> Set.mem_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (x : α) (a : Set.{u1} α) (b : Set.{u1} α), Iff (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a b)) (Or (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x a) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x b))
but is expected to have type
forall {α : Type.{u1}} (x : α) (a : Set.{u1} α) (b : Set.{u1} α), Iff (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a b)) (Or (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x a) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x b))
Case conversion may be inaccurate. Consider using '#align set.mem_union Set.mem_unionₓ'. -/
@[simp]
theorem mem_union (x : α) (a b : Set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b :=
Iff.rfl
#align set.mem_union Set.mem_union
/- warning: set.union_self -> Set.union_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a a) a
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a a) a
Case conversion may be inaccurate. Consider using '#align set.union_self Set.union_selfₓ'. -/
@[simp]
theorem union_self (a : Set α) : a ∪ a = a :=
ext fun x => or_self_iff _
#align set.union_self Set.union_self
/- warning: set.union_empty -> Set.union_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) a
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) a
Case conversion may be inaccurate. Consider using '#align set.union_empty Set.union_emptyₓ'. -/
@[simp]
theorem union_empty (a : Set α) : a ∪ ∅ = a :=
ext fun x => or_false_iff _
#align set.union_empty Set.union_empty
/- warning: set.empty_union -> Set.empty_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)) a) a
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)) a) a
Case conversion may be inaccurate. Consider using '#align set.empty_union Set.empty_unionₓ'. -/
@[simp]
theorem empty_union (a : Set α) : ∅ ∪ a = a :=
ext fun x => false_or_iff _
#align set.empty_union Set.empty_union
/- warning: set.union_comm -> Set.union_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a b) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) b a)
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a b) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) b a)
Case conversion may be inaccurate. Consider using '#align set.union_comm Set.union_commₓ'. -/
theorem union_comm (a b : Set α) : a ∪ b = b ∪ a :=
ext fun x => or_comm
#align set.union_comm Set.union_comm
/- warning: set.union_assoc -> Set.union_assoc is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α) (c : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a b) c) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) b c))
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α) (c : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a b) c) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) b c))
Case conversion may be inaccurate. Consider using '#align set.union_assoc Set.union_assocₓ'. -/
theorem union_assoc (a b c : Set α) : a ∪ b ∪ c = a ∪ (b ∪ c) :=
ext fun x => or_assoc
#align set.union_assoc Set.union_assoc
/- warning: set.union_is_assoc -> Set.union_isAssoc is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, IsAssociative.{u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α))
but is expected to have type
forall {α : Type.{u1}}, IsAssociative.{u1} (Set.{u1} α) (fun (x._@.Mathlib.Data.Set.Basic._hyg.7936 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.7938 : Set.{u1} α) => Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) x._@.Mathlib.Data.Set.Basic._hyg.7936 x._@.Mathlib.Data.Set.Basic._hyg.7938)
Case conversion may be inaccurate. Consider using '#align set.union_is_assoc Set.union_isAssocₓ'. -/
instance union_isAssoc : IsAssociative (Set α) (· ∪ ·) :=
⟨union_assoc⟩
#align set.union_is_assoc Set.union_isAssoc
/- warning: set.union_is_comm -> Set.union_isComm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, IsCommutative.{u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α))
but is expected to have type
forall {α : Type.{u1}}, IsCommutative.{u1} (Set.{u1} α) (fun (x._@.Mathlib.Data.Set.Basic._hyg.7981 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.7983 : Set.{u1} α) => Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) x._@.Mathlib.Data.Set.Basic._hyg.7981 x._@.Mathlib.Data.Set.Basic._hyg.7983)
Case conversion may be inaccurate. Consider using '#align set.union_is_comm Set.union_isCommₓ'. -/
instance union_isComm : IsCommutative (Set α) (· ∪ ·) :=
⟨union_comm⟩
#align set.union_is_comm Set.union_isComm
/- warning: set.union_left_comm -> Set.union_left_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₃ : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₁ (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₂ s₃)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₂ (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₁ s₃))
but is expected to have type
forall {α : Type.{u1}} (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₃ : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₁ (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₂ s₃)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₂ (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₁ s₃))
Case conversion may be inaccurate. Consider using '#align set.union_left_comm Set.union_left_commₓ'. -/
theorem union_left_comm (s₁ s₂ s₃ : Set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext fun x => or_left_comm
#align set.union_left_comm Set.union_left_comm
/- warning: set.union_right_comm -> Set.union_right_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₃ : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₁ s₂) s₃) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₁ s₃) s₂)
but is expected to have type
forall {α : Type.{u1}} (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₃ : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₁ s₂) s₃) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₁ s₃) s₂)
Case conversion may be inaccurate. Consider using '#align set.union_right_comm Set.union_right_commₓ'. -/
theorem union_right_comm (s₁ s₂ s₃ : Set α) : s₁ ∪ s₂ ∪ s₃ = s₁ ∪ s₃ ∪ s₂ :=
ext fun x => or_right_comm
#align set.union_right_comm Set.union_right_comm
/- warning: set.union_eq_left_iff_subset -> Set.union_eq_left_iff_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s)
Case conversion may be inaccurate. Consider using '#align set.union_eq_left_iff_subset Set.union_eq_left_iff_subsetₓ'. -/
@[simp]
theorem union_eq_left_iff_subset {s t : Set α} : s ∪ t = s ↔ t ⊆ s :=
sup_eq_left
#align set.union_eq_left_iff_subset Set.union_eq_left_iff_subset
/- warning: set.union_eq_right_iff_subset -> Set.union_eq_right_iff_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.union_eq_right_iff_subset Set.union_eq_right_iff_subsetₓ'. -/
@[simp]
theorem union_eq_right_iff_subset {s t : Set α} : s ∪ t = t ↔ s ⊆ t :=
sup_eq_right
#align set.union_eq_right_iff_subset Set.union_eq_right_iff_subset
/- warning: set.union_eq_self_of_subset_left -> Set.union_eq_self_of_subset_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) t)
Case conversion may be inaccurate. Consider using '#align set.union_eq_self_of_subset_left Set.union_eq_self_of_subset_leftₓ'. -/
theorem union_eq_self_of_subset_left {s t : Set α} (h : s ⊆ t) : s ∪ t = t :=
union_eq_right_iff_subset.mpr h
#align set.union_eq_self_of_subset_left Set.union_eq_self_of_subset_left
/- warning: set.union_eq_self_of_subset_right -> Set.union_eq_self_of_subset_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) s)
Case conversion may be inaccurate. Consider using '#align set.union_eq_self_of_subset_right Set.union_eq_self_of_subset_rightₓ'. -/
theorem union_eq_self_of_subset_right {s t : Set α} (h : t ⊆ s) : s ∪ t = s :=
union_eq_left_iff_subset.mpr h
#align set.union_eq_self_of_subset_right Set.union_eq_self_of_subset_right
/- warning: set.subset_union_left -> Set.subset_union_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.subset_union_left Set.subset_union_leftₓ'. -/
@[simp]
theorem subset_union_left (s t : Set α) : s ⊆ s ∪ t := fun x => Or.inl
#align set.subset_union_left Set.subset_union_left
/- warning: set.subset_union_right -> Set.subset_union_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.subset_union_right Set.subset_union_rightₓ'. -/
@[simp]
theorem subset_union_right (s t : Set α) : t ⊆ s ∪ t := fun x => Or.inr
#align set.subset_union_right Set.subset_union_right
/- warning: set.union_subset -> Set.union_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {r : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s r) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t r) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) r)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {r : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s r) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t r) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) r)
Case conversion may be inaccurate. Consider using '#align set.union_subset Set.union_subsetₓ'. -/
theorem union_subset {s t r : Set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := fun x =>
Or.ndrec (@sr _) (@tr _)
#align set.union_subset Set.union_subset
/- warning: set.union_subset_iff -> Set.union_subset_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) u) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s u) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) u) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s u) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.union_subset_iff Set.union_subset_iffₓ'. -/
@[simp]
theorem union_subset_iff {s t u : Set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u :=
(forall_congr' fun x => or_imp).trans forall_and
#align set.union_subset_iff Set.union_subset_iff
/- warning: set.union_subset_union -> Set.union_subset_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t₁ t₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₁ t₁) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₂ t₂))
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t₁ t₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₁ t₁) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₂ t₂))
Case conversion may be inaccurate. Consider using '#align set.union_subset_union Set.union_subset_unionₓ'. -/
theorem union_subset_union {s₁ s₂ t₁ t₂ : Set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) :
s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := fun x => Or.imp (@h₁ _) (@h₂ _)
#align set.union_subset_union Set.union_subset_union
/- warning: set.union_subset_union_left -> Set.union_subset_union_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} (t : Set.{u1} α), (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₁ t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s₂ t))
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} (t : Set.{u1} α), (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₁ t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s₂ t))
Case conversion may be inaccurate. Consider using '#align set.union_subset_union_left Set.union_subset_union_leftₓ'. -/
theorem union_subset_union_left {s₁ s₂ : Set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t :=
union_subset_union h Subset.rfl
#align set.union_subset_union_left Set.union_subset_union_left
/- warning: set.union_subset_union_right -> Set.union_subset_union_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t₁ t₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t₁) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t₂))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t₁ t₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t₁) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t₂))
Case conversion may be inaccurate. Consider using '#align set.union_subset_union_right Set.union_subset_union_rightₓ'. -/
theorem union_subset_union_right (s) {t₁ t₂ : Set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ :=
union_subset_union Subset.rfl h
#align set.union_subset_union_right Set.union_subset_union_right
/- warning: set.subset_union_of_subset_left -> Set.subset_union_of_subset_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (forall (u : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (forall (u : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.subset_union_of_subset_left Set.subset_union_of_subset_leftₓ'. -/
theorem subset_union_of_subset_left {s t : Set α} (h : s ⊆ t) (u : Set α) : s ⊆ t ∪ u :=
Subset.trans h (subset_union_left t u)
#align set.subset_union_of_subset_left Set.subset_union_of_subset_left
/- warning: set.subset_union_of_subset_right -> Set.subset_union_of_subset_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s u) -> (forall (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s u) -> (forall (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.subset_union_of_subset_right Set.subset_union_of_subset_rightₓ'. -/
theorem subset_union_of_subset_right {s u : Set α} (h : s ⊆ u) (t : Set α) : s ⊆ t ∪ u :=
Subset.trans h (subset_union_right t u)
#align set.subset_union_of_subset_right Set.subset_union_of_subset_right
/- warning: set.union_congr_left -> Set.union_congr_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u)) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) u (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (Sup.sup.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) s u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u)) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) u (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (Sup.sup.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) s u))
Case conversion may be inaccurate. Consider using '#align set.union_congr_left Set.union_congr_leftₓ'. -/
theorem union_congr_left (ht : t ⊆ s ∪ u) (hu : u ⊆ s ∪ t) : s ∪ t = s ⊔ u :=
sup_congr_left ht hu
#align set.union_congr_left Set.union_congr_left
/- warning: set.union_congr_right -> Set.union_congr_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u)) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u)) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.union_congr_right Set.union_congr_rightₓ'. -/
theorem union_congr_right (hs : s ⊆ t ∪ u) (ht : t ⊆ s ∪ u) : s ∪ u = t ∪ u :=
sup_congr_right hs ht
#align set.union_congr_right Set.union_congr_right
/- warning: set.union_eq_union_iff_left -> Set.union_eq_union_iff_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) u (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) u (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)))
Case conversion may be inaccurate. Consider using '#align set.union_eq_union_iff_left Set.union_eq_union_iff_leftₓ'. -/
theorem union_eq_union_iff_left : s ∪ t = s ∪ u ↔ t ⊆ s ∪ u ∧ u ⊆ s ∪ t :=
sup_eq_sup_iff_left
#align set.union_eq_union_iff_left Set.union_eq_union_iff_left
/- warning: set.union_eq_union_iff_right -> Set.union_eq_union_iff_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u)))
Case conversion may be inaccurate. Consider using '#align set.union_eq_union_iff_right Set.union_eq_union_iff_rightₓ'. -/
theorem union_eq_union_iff_right : s ∪ u = t ∪ u ↔ s ⊆ t ∪ u ∧ t ⊆ s ∪ u :=
sup_eq_sup_iff_right
#align set.union_eq_union_iff_right Set.union_eq_union_iff_right
/- warning: set.union_empty_iff -> Set.union_empty_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (And (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (Eq.{succ u1} (Set.{u1} α) t (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (And (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (Eq.{succ u1} (Set.{u1} α) t (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))))
Case conversion may be inaccurate. Consider using '#align set.union_empty_iff Set.union_empty_iffₓ'. -/
@[simp]
theorem union_empty_iff {s t : Set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := by
simp only [← subset_empty_iff] <;> exact union_subset_iff
#align set.union_empty_iff Set.union_empty_iff
/- warning: set.union_univ -> Set.union_univ is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s (Set.univ.{u1} α)) (Set.univ.{u1} α)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s (Set.univ.{u1} α)) (Set.univ.{u1} α)
Case conversion may be inaccurate. Consider using '#align set.union_univ Set.union_univₓ'. -/
@[simp]
theorem union_univ {s : Set α} : s ∪ univ = univ :=
sup_top_eq
#align set.union_univ Set.union_univ
/- warning: set.univ_union -> Set.univ_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Set.univ.{u1} α) s) (Set.univ.{u1} α)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Set.univ.{u1} α) s) (Set.univ.{u1} α)
Case conversion may be inaccurate. Consider using '#align set.univ_union Set.univ_unionₓ'. -/
@[simp]
theorem univ_union {s : Set α} : univ ∪ s = univ :=
top_sup_eq
#align set.univ_union Set.univ_union
/-! ### Lemmas about intersection -/
/- warning: set.inter_def -> Set.inter_def is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ s₂) (setOf.{u1} α (fun (a : α) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s₁) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s₂)))
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ s₂) (setOf.{u1} α (fun (a : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s₁) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s₂)))
Case conversion may be inaccurate. Consider using '#align set.inter_def Set.inter_defₓ'. -/
theorem inter_def {s₁ s₂ : Set α} : s₁ ∩ s₂ = { a | a ∈ s₁ ∧ a ∈ s₂ } :=
rfl
#align set.inter_def Set.inter_def
/- warning: set.mem_inter_iff -> Set.mem_inter_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (x : α) (a : Set.{u1} α) (b : Set.{u1} α), Iff (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a b)) (And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x a) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x b))
but is expected to have type
forall {α : Type.{u1}} (x : α) (a : Set.{u1} α) (b : Set.{u1} α), Iff (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a b)) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x a) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x b))
Case conversion may be inaccurate. Consider using '#align set.mem_inter_iff Set.mem_inter_iffₓ'. -/
@[simp]
theorem mem_inter_iff (x : α) (a b : Set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b :=
Iff.rfl
#align set.mem_inter_iff Set.mem_inter_iff
/- warning: set.mem_inter -> Set.mem_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x a) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x b) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a b))
but is expected to have type
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x a) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x b) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a b))
Case conversion may be inaccurate. Consider using '#align set.mem_inter Set.mem_interₓ'. -/
theorem mem_inter {x : α} {a b : Set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b :=
⟨ha, hb⟩
#align set.mem_inter Set.mem_inter
/- warning: set.mem_of_mem_inter_left -> Set.mem_of_mem_inter_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a b)) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x a)
but is expected to have type
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a b)) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x a)
Case conversion may be inaccurate. Consider using '#align set.mem_of_mem_inter_left Set.mem_of_mem_inter_leftₓ'. -/
theorem mem_of_mem_inter_left {x : α} {a b : Set α} (h : x ∈ a ∩ b) : x ∈ a :=
h.left
#align set.mem_of_mem_inter_left Set.mem_of_mem_inter_left
/- warning: set.mem_of_mem_inter_right -> Set.mem_of_mem_inter_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a b)) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x b)
but is expected to have type
forall {α : Type.{u1}} {x : α} {a : Set.{u1} α} {b : Set.{u1} α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a b)) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x b)
Case conversion may be inaccurate. Consider using '#align set.mem_of_mem_inter_right Set.mem_of_mem_inter_rightₓ'. -/
theorem mem_of_mem_inter_right {x : α} {a b : Set α} (h : x ∈ a ∩ b) : x ∈ b :=
h.right
#align set.mem_of_mem_inter_right Set.mem_of_mem_inter_right
/- warning: set.inter_self -> Set.inter_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a a) a
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a a) a
Case conversion may be inaccurate. Consider using '#align set.inter_self Set.inter_selfₓ'. -/
@[simp]
theorem inter_self (a : Set α) : a ∩ a = a :=
ext fun x => and_self_iff _
#align set.inter_self Set.inter_self
/- warning: set.inter_empty -> Set.inter_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.inter_empty Set.inter_emptyₓ'. -/
@[simp]
theorem inter_empty (a : Set α) : a ∩ ∅ = ∅ :=
ext fun x => and_false_iff _
#align set.inter_empty Set.inter_empty
/- warning: set.empty_inter -> Set.empty_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)) a) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)) a) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.empty_inter Set.empty_interₓ'. -/
@[simp]
theorem empty_inter (a : Set α) : ∅ ∩ a = ∅ :=
ext fun x => false_and_iff _
#align set.empty_inter Set.empty_inter
/- warning: set.inter_comm -> Set.inter_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a b) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) b a)
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a b) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) b a)
Case conversion may be inaccurate. Consider using '#align set.inter_comm Set.inter_commₓ'. -/
theorem inter_comm (a b : Set α) : a ∩ b = b ∩ a :=
ext fun x => and_comm
#align set.inter_comm Set.inter_comm
/- warning: set.inter_assoc -> Set.inter_assoc is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α) (c : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a b) c) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) b c))
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α) (c : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a b) c) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) b c))
Case conversion may be inaccurate. Consider using '#align set.inter_assoc Set.inter_assocₓ'. -/
theorem inter_assoc (a b c : Set α) : a ∩ b ∩ c = a ∩ (b ∩ c) :=
ext fun x => and_assoc
#align set.inter_assoc Set.inter_assoc
/- warning: set.inter_is_assoc -> Set.inter_isAssoc is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, IsAssociative.{u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α))
but is expected to have type
forall {α : Type.{u1}}, IsAssociative.{u1} (Set.{u1} α) (fun (x._@.Mathlib.Data.Set.Basic._hyg.9578 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.9580 : Set.{u1} α) => Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) x._@.Mathlib.Data.Set.Basic._hyg.9578 x._@.Mathlib.Data.Set.Basic._hyg.9580)
Case conversion may be inaccurate. Consider using '#align set.inter_is_assoc Set.inter_isAssocₓ'. -/
instance inter_isAssoc : IsAssociative (Set α) (· ∩ ·) :=
⟨inter_assoc⟩
#align set.inter_is_assoc Set.inter_isAssoc
/- warning: set.inter_is_comm -> Set.inter_isComm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, IsCommutative.{u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α))
but is expected to have type
forall {α : Type.{u1}}, IsCommutative.{u1} (Set.{u1} α) (fun (x._@.Mathlib.Data.Set.Basic._hyg.9623 : Set.{u1} α) (x._@.Mathlib.Data.Set.Basic._hyg.9625 : Set.{u1} α) => Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) x._@.Mathlib.Data.Set.Basic._hyg.9623 x._@.Mathlib.Data.Set.Basic._hyg.9625)
Case conversion may be inaccurate. Consider using '#align set.inter_is_comm Set.inter_isCommₓ'. -/
instance inter_isComm : IsCommutative (Set α) (· ∩ ·) :=
⟨inter_comm⟩
#align set.inter_is_comm Set.inter_isComm
/- warning: set.inter_left_comm -> Set.inter_left_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₃ : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₂ s₃)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₂ (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ s₃))
but is expected to have type
forall {α : Type.{u1}} (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₃ : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₂ s₃)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₂ (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ s₃))
Case conversion may be inaccurate. Consider using '#align set.inter_left_comm Set.inter_left_commₓ'. -/
theorem inter_left_comm (s₁ s₂ s₃ : Set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext fun x => and_left_comm
#align set.inter_left_comm Set.inter_left_comm
/- warning: set.inter_right_comm -> Set.inter_right_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₃ : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ s₂) s₃) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ s₃) s₂)
but is expected to have type
forall {α : Type.{u1}} (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₃ : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ s₂) s₃) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ s₃) s₂)
Case conversion may be inaccurate. Consider using '#align set.inter_right_comm Set.inter_right_commₓ'. -/
theorem inter_right_comm (s₁ s₂ s₃ : Set α) : s₁ ∩ s₂ ∩ s₃ = s₁ ∩ s₃ ∩ s₂ :=
ext fun x => and_right_comm
#align set.inter_right_comm Set.inter_right_comm
/- warning: set.inter_subset_left -> Set.inter_subset_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) s
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) s
Case conversion may be inaccurate. Consider using '#align set.inter_subset_left Set.inter_subset_leftₓ'. -/
@[simp]
theorem inter_subset_left (s t : Set α) : s ∩ t ⊆ s := fun x => And.left
#align set.inter_subset_left Set.inter_subset_left
/- warning: set.inter_subset_right -> Set.inter_subset_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) t
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) t
Case conversion may be inaccurate. Consider using '#align set.inter_subset_right Set.inter_subset_rightₓ'. -/
@[simp]
theorem inter_subset_right (s t : Set α) : s ∩ t ⊆ t := fun x => And.right
#align set.inter_subset_right Set.inter_subset_right
/- warning: set.subset_inter -> Set.subset_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {r : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) r s) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) r t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) r (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {r : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) r s) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) r t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) r (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.subset_inter Set.subset_interₓ'. -/
theorem subset_inter {s t r : Set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := fun x h =>
⟨rs h, rt h⟩
#align set.subset_inter Set.subset_inter
/- warning: set.subset_inter_iff -> Set.subset_inter_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {r : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) r (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) r s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) r t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {r : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) r (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) r s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) r t))
Case conversion may be inaccurate. Consider using '#align set.subset_inter_iff Set.subset_inter_iffₓ'. -/
@[simp]
theorem subset_inter_iff {s t r : Set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t :=
(forall_congr' fun x => imp_and).trans forall_and
#align set.subset_inter_iff Set.subset_inter_iff
/- warning: set.inter_eq_left_iff_subset -> Set.inter_eq_left_iff_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.inter_eq_left_iff_subset Set.inter_eq_left_iff_subsetₓ'. -/
@[simp]
theorem inter_eq_left_iff_subset {s t : Set α} : s ∩ t = s ↔ s ⊆ t :=
inf_eq_left
#align set.inter_eq_left_iff_subset Set.inter_eq_left_iff_subset
/- warning: set.inter_eq_right_iff_subset -> Set.inter_eq_right_iff_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s)
Case conversion may be inaccurate. Consider using '#align set.inter_eq_right_iff_subset Set.inter_eq_right_iff_subsetₓ'. -/
@[simp]
theorem inter_eq_right_iff_subset {s t : Set α} : s ∩ t = t ↔ t ⊆ s :=
inf_eq_right
#align set.inter_eq_right_iff_subset Set.inter_eq_right_iff_subset
/- warning: set.inter_eq_self_of_subset_left -> Set.inter_eq_self_of_subset_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) s)
Case conversion may be inaccurate. Consider using '#align set.inter_eq_self_of_subset_left Set.inter_eq_self_of_subset_leftₓ'. -/
theorem inter_eq_self_of_subset_left {s t : Set α} : s ⊆ t → s ∩ t = s :=
inter_eq_left_iff_subset.mpr
#align set.inter_eq_self_of_subset_left Set.inter_eq_self_of_subset_left
/- warning: set.inter_eq_self_of_subset_right -> Set.inter_eq_self_of_subset_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) t)
Case conversion may be inaccurate. Consider using '#align set.inter_eq_self_of_subset_right Set.inter_eq_self_of_subset_rightₓ'. -/
theorem inter_eq_self_of_subset_right {s t : Set α} : t ⊆ s → s ∩ t = t :=
inter_eq_right_iff_subset.mpr
#align set.inter_eq_self_of_subset_right Set.inter_eq_self_of_subset_right
/- warning: set.inter_congr_left -> Set.inter_congr_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) u) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) u) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.inter_congr_left Set.inter_congr_leftₓ'. -/
theorem inter_congr_left (ht : s ∩ u ⊆ t) (hu : s ∩ t ⊆ u) : s ∩ t = s ∩ u :=
inf_congr_left ht hu
#align set.inter_congr_left Set.inter_congr_left
/- warning: set.inter_congr_right -> Set.inter_congr_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u) s) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) t) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u) s) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) t) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.inter_congr_right Set.inter_congr_rightₓ'. -/
theorem inter_congr_right (hs : t ∩ u ⊆ s) (ht : s ∩ u ⊆ t) : s ∩ u = t ∩ u :=
inf_congr_right hs ht
#align set.inter_congr_right Set.inter_congr_right
/- warning: set.inter_eq_inter_iff_left -> Set.inter_eq_inter_iff_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) u))
Case conversion may be inaccurate. Consider using '#align set.inter_eq_inter_iff_left Set.inter_eq_inter_iff_leftₓ'. -/
theorem inter_eq_inter_iff_left : s ∩ t = s ∩ u ↔ s ∩ u ⊆ t ∧ s ∩ t ⊆ u :=
inf_eq_inf_iff_left
#align set.inter_eq_inter_iff_left Set.inter_eq_inter_iff_left
/- warning: set.inter_eq_inter_iff_right -> Set.inter_eq_inter_iff_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u) s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u) s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) t))
Case conversion may be inaccurate. Consider using '#align set.inter_eq_inter_iff_right Set.inter_eq_inter_iff_rightₓ'. -/
theorem inter_eq_inter_iff_right : s ∩ u = t ∩ u ↔ t ∩ u ⊆ s ∧ s ∩ u ⊆ t :=
inf_eq_inf_iff_right
#align set.inter_eq_inter_iff_right Set.inter_eq_inter_iff_right
/- warning: set.inter_univ -> Set.inter_univ is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a (Set.univ.{u1} α)) a
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a (Set.univ.{u1} α)) a
Case conversion may be inaccurate. Consider using '#align set.inter_univ Set.inter_univₓ'. -/
@[simp]
theorem inter_univ (a : Set α) : a ∩ univ = a :=
inf_top_eq
#align set.inter_univ Set.inter_univ
/- warning: set.univ_inter -> Set.univ_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Set.univ.{u1} α) a) a
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Set.univ.{u1} α) a) a
Case conversion may be inaccurate. Consider using '#align set.univ_inter Set.univ_interₓ'. -/
@[simp]
theorem univ_inter (a : Set α) : univ ∩ a = a :=
top_inf_eq
#align set.univ_inter Set.univ_inter
/- warning: set.inter_subset_inter -> Set.inter_subset_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₁ t₁) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₂ t₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ s₂) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t₁ t₂))
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₁ t₁) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₂ t₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ s₂) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t₁ t₂))
Case conversion may be inaccurate. Consider using '#align set.inter_subset_inter Set.inter_subset_interₓ'. -/
theorem inter_subset_inter {s₁ s₂ t₁ t₂ : Set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) :
s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := fun x => And.imp (@h₁ _) (@h₂ _)
#align set.inter_subset_inter Set.inter_subset_inter
/- warning: set.inter_subset_inter_left -> Set.inter_subset_inter_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.inter_subset_inter_left Set.inter_subset_inter_leftₓ'. -/
theorem inter_subset_inter_left {s t : Set α} (u : Set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u :=
inter_subset_inter H Subset.rfl
#align set.inter_subset_inter_left Set.inter_subset_inter_left
/- warning: set.inter_subset_inter_right -> Set.inter_subset_inter_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) u s) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) u t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) u s) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) u t))
Case conversion may be inaccurate. Consider using '#align set.inter_subset_inter_right Set.inter_subset_inter_rightₓ'. -/
theorem inter_subset_inter_right {s t : Set α} (u : Set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t :=
inter_subset_inter Subset.rfl H
#align set.inter_subset_inter_right Set.inter_subset_inter_right
/- warning: set.union_inter_cancel_left -> Set.union_inter_cancel_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) s) s
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) s) s
Case conversion may be inaccurate. Consider using '#align set.union_inter_cancel_left Set.union_inter_cancel_leftₓ'. -/
theorem union_inter_cancel_left {s t : Set α} : (s ∪ t) ∩ s = s :=
inter_eq_self_of_subset_right <| subset_union_left _ _
#align set.union_inter_cancel_left Set.union_inter_cancel_left
/- warning: set.union_inter_cancel_right -> Set.union_inter_cancel_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) t) t
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) t) t
Case conversion may be inaccurate. Consider using '#align set.union_inter_cancel_right Set.union_inter_cancel_rightₓ'. -/
theorem union_inter_cancel_right {s t : Set α} : (s ∪ t) ∩ t = t :=
inter_eq_self_of_subset_right <| subset_union_right _ _
#align set.union_inter_cancel_right Set.union_inter_cancel_right
/-! ### Distributivity laws -/
/- warning: set.inter_distrib_left -> Set.inter_distrib_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.inter_distrib_left Set.inter_distrib_leftₓ'. -/
theorem inter_distrib_left (s t u : Set α) : s ∩ (t ∪ u) = s ∩ t ∪ s ∩ u :=
inf_sup_left
#align set.inter_distrib_left Set.inter_distrib_left
/- warning: set.inter_union_distrib_left -> Set.inter_union_distrib_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.inter_union_distrib_left Set.inter_union_distrib_leftₓ'. -/
theorem inter_union_distrib_left {s t u : Set α} : s ∩ (t ∪ u) = s ∩ t ∪ s ∩ u :=
inf_sup_left
#align set.inter_union_distrib_left Set.inter_union_distrib_left
/- warning: set.inter_distrib_right -> Set.inter_distrib_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.inter_distrib_right Set.inter_distrib_rightₓ'. -/
theorem inter_distrib_right (s t u : Set α) : (s ∪ t) ∩ u = s ∩ u ∪ t ∩ u :=
inf_sup_right
#align set.inter_distrib_right Set.inter_distrib_right
/- warning: set.union_inter_distrib_right -> Set.union_inter_distrib_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.union_inter_distrib_right Set.union_inter_distrib_rightₓ'. -/
theorem union_inter_distrib_right {s t u : Set α} : (s ∪ t) ∩ u = s ∩ u ∪ t ∩ u :=
inf_sup_right
#align set.union_inter_distrib_right Set.union_inter_distrib_right
/- warning: set.union_distrib_left -> Set.union_distrib_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.union_distrib_left Set.union_distrib_leftₓ'. -/
theorem union_distrib_left (s t u : Set α) : s ∪ t ∩ u = (s ∪ t) ∩ (s ∪ u) :=
sup_inf_left
#align set.union_distrib_left Set.union_distrib_left
/- warning: set.union_inter_distrib_left -> Set.union_inter_distrib_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.union_inter_distrib_left Set.union_inter_distrib_leftₓ'. -/
theorem union_inter_distrib_left {s t u : Set α} : s ∪ t ∩ u = (s ∪ t) ∩ (s ∪ u) :=
sup_inf_left
#align set.union_inter_distrib_left Set.union_inter_distrib_left
/- warning: set.union_distrib_right -> Set.union_distrib_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.union_distrib_right Set.union_distrib_rightₓ'. -/
theorem union_distrib_right (s t u : Set α) : s ∩ t ∪ u = (s ∪ u) ∩ (t ∪ u) :=
sup_inf_right
#align set.union_distrib_right Set.union_distrib_right
/- warning: set.inter_union_distrib_right -> Set.inter_union_distrib_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.inter_union_distrib_right Set.inter_union_distrib_rightₓ'. -/
theorem inter_union_distrib_right {s t u : Set α} : s ∩ t ∪ u = (s ∪ u) ∩ (t ∪ u) :=
sup_inf_right
#align set.inter_union_distrib_right Set.inter_union_distrib_right
/- warning: set.union_union_distrib_left -> Set.union_union_distrib_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.union_union_distrib_left Set.union_union_distrib_leftₓ'. -/
theorem union_union_distrib_left (s t u : Set α) : s ∪ (t ∪ u) = s ∪ t ∪ (s ∪ u) :=
sup_sup_distrib_left _ _ _
#align set.union_union_distrib_left Set.union_union_distrib_left
/- warning: set.union_union_distrib_right -> Set.union_union_distrib_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.union_union_distrib_right Set.union_union_distrib_rightₓ'. -/
theorem union_union_distrib_right (s t u : Set α) : s ∪ t ∪ u = s ∪ u ∪ (t ∪ u) :=
sup_sup_distrib_right _ _ _
#align set.union_union_distrib_right Set.union_union_distrib_right
/- warning: set.inter_inter_distrib_left -> Set.inter_inter_distrib_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.inter_inter_distrib_left Set.inter_inter_distrib_leftₓ'. -/
theorem inter_inter_distrib_left (s t u : Set α) : s ∩ (t ∩ u) = s ∩ t ∩ (s ∩ u) :=
inf_inf_distrib_left _ _ _
#align set.inter_inter_distrib_left Set.inter_inter_distrib_left
/- warning: set.inter_inter_distrib_right -> Set.inter_inter_distrib_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.inter_inter_distrib_right Set.inter_inter_distrib_rightₓ'. -/
theorem inter_inter_distrib_right (s t u : Set α) : s ∩ t ∩ u = s ∩ u ∩ (t ∩ u) :=
inf_inf_distrib_right _ _ _
#align set.inter_inter_distrib_right Set.inter_inter_distrib_right
/- warning: set.union_union_union_comm -> Set.union_union_union_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α) (v : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) u v)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t v))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α) (v : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) u v)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t v))
Case conversion may be inaccurate. Consider using '#align set.union_union_union_comm Set.union_union_union_commₓ'. -/
theorem union_union_union_comm (s t u v : Set α) : s ∪ t ∪ (u ∪ v) = s ∪ u ∪ (t ∪ v) :=
sup_sup_sup_comm _ _ _ _
#align set.union_union_union_comm Set.union_union_union_comm
/- warning: set.inter_inter_inter_comm -> Set.inter_inter_inter_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α) (v : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) u v)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t v))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α) (v : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) u v)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t v))
Case conversion may be inaccurate. Consider using '#align set.inter_inter_inter_comm Set.inter_inter_inter_commₓ'. -/
theorem inter_inter_inter_comm (s t u v : Set α) : s ∩ t ∩ (u ∩ v) = s ∩ u ∩ (t ∩ v) :=
inf_inf_inf_comm _ _ _ _
#align set.inter_inter_inter_comm Set.inter_inter_inter_comm
/-!
### Lemmas about `insert`
`insert α s` is the set `{α} ∪ s`.
-/
#print Set.insert_def /-
theorem insert_def (x : α) (s : Set α) : insert x s = { y | y = x ∨ y ∈ s } :=
rfl
#align set.insert_def Set.insert_def
-/
#print Set.subset_insert /-
@[simp]
theorem subset_insert (x : α) (s : Set α) : s ⊆ insert x s := fun y => Or.inr
#align set.subset_insert Set.subset_insert
-/
#print Set.mem_insert /-
theorem mem_insert (x : α) (s : Set α) : x ∈ insert x s :=
Or.inl rfl
#align set.mem_insert Set.mem_insert
-/
#print Set.mem_insert_of_mem /-
theorem mem_insert_of_mem {x : α} {s : Set α} (y : α) : x ∈ s → x ∈ insert y s :=
Or.inr
#align set.mem_insert_of_mem Set.mem_insert_of_mem
-/
#print Set.eq_or_mem_of_mem_insert /-
theorem eq_or_mem_of_mem_insert {x a : α} {s : Set α} : x ∈ insert a s → x = a ∨ x ∈ s :=
id
#align set.eq_or_mem_of_mem_insert Set.eq_or_mem_of_mem_insert
-/
#print Set.mem_of_mem_insert_of_ne /-
theorem mem_of_mem_insert_of_ne : b ∈ insert a s → b ≠ a → b ∈ s :=
Or.resolve_left
#align set.mem_of_mem_insert_of_ne Set.mem_of_mem_insert_of_ne
-/
#print Set.eq_of_not_mem_of_mem_insert /-
theorem eq_of_not_mem_of_mem_insert : b ∈ insert a s → b ∉ s → b = a :=
Or.resolve_right
#align set.eq_of_not_mem_of_mem_insert Set.eq_of_not_mem_of_mem_insert
-/
#print Set.mem_insert_iff /-
@[simp]
theorem mem_insert_iff {x a : α} {s : Set α} : x ∈ insert a s ↔ x = a ∨ x ∈ s :=
Iff.rfl
#align set.mem_insert_iff Set.mem_insert_iff
-/
#print Set.insert_eq_of_mem /-
@[simp]
theorem insert_eq_of_mem {a : α} {s : Set α} (h : a ∈ s) : insert a s = s :=
ext fun x => or_iff_right_of_imp fun e => e.symm ▸ h
#align set.insert_eq_of_mem Set.insert_eq_of_mem
-/
#print Set.ne_insert_of_not_mem /-
theorem ne_insert_of_not_mem {s : Set α} (t : Set α) {a : α} : a ∉ s → s ≠ insert a t :=
mt fun e => e.symm ▸ mem_insert _ _
#align set.ne_insert_of_not_mem Set.ne_insert_of_not_mem
-/
#print Set.insert_eq_self /-
@[simp]
theorem insert_eq_self : insert a s = s ↔ a ∈ s :=
⟨fun h => h ▸ mem_insert _ _, insert_eq_of_mem⟩
#align set.insert_eq_self Set.insert_eq_self
-/
#print Set.insert_ne_self /-
theorem insert_ne_self : insert a s ≠ s ↔ a ∉ s :=
insert_eq_self.Not
#align set.insert_ne_self Set.insert_ne_self
-/
#print Set.insert_subset /-
theorem insert_subset : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by
simp only [subset_def, or_imp, forall_and, forall_eq, mem_insert_iff]
#align set.insert_subset Set.insert_subset
-/
#print Set.insert_subset_insert /-
theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := fun x => Or.imp_right (@h _)
#align set.insert_subset_insert Set.insert_subset_insert
-/
#print Set.insert_subset_insert_iff /-
theorem insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t :=
by
refine' ⟨fun h x hx => _, insert_subset_insert⟩
rcases h (subset_insert _ _ hx) with (rfl | hxt)
exacts[(ha hx).elim, hxt]
#align set.insert_subset_insert_iff Set.insert_subset_insert_iff
-/
#print Set.subset_insert_iff_of_not_mem /-
theorem subset_insert_iff_of_not_mem (ha : a ∉ s) : s ⊆ insert a t ↔ s ⊆ t :=
forall₂_congr fun b hb => or_iff_right <| ne_of_mem_of_not_mem hb ha
#align set.subset_insert_iff_of_not_mem Set.subset_insert_iff_of_not_mem
-/
/- warning: set.ssubset_iff_insert -> Set.ssubset_iff_insert is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s t) (Exists.{succ u1} α (fun (a : α) => Exists.{0} (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)) (fun (H : Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)) => HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) t)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s t) (Exists.{succ u1} α (fun (a : α) => Exists.{0} (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)) (fun (H : Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)) => HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) t)))
Case conversion may be inaccurate. Consider using '#align set.ssubset_iff_insert Set.ssubset_iff_insertₓ'. -/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (a «expr ∉ » s) -/
theorem ssubset_iff_insert {s t : Set α} : s ⊂ t ↔ ∃ (a : _)(_ : a ∉ s), insert a s ⊆ t :=
by
simp only [insert_subset, exists_and_right, ssubset_def, not_subset]
simp only [exists_prop, and_comm']
#align set.ssubset_iff_insert Set.ssubset_iff_insert
/- warning: set.ssubset_insert -> Set.ssubset_insert is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {a : α}, (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {a : α}, (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)) -> (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s))
Case conversion may be inaccurate. Consider using '#align set.ssubset_insert Set.ssubset_insertₓ'. -/
theorem ssubset_insert {s : Set α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff_insert.2 ⟨a, h, Subset.rfl⟩
#align set.ssubset_insert Set.ssubset_insert
#print Set.insert_comm /-
theorem insert_comm (a b : α) (s : Set α) : insert a (insert b s) = insert b (insert a s) :=
ext fun x => or_left_comm
#align set.insert_comm Set.insert_comm
-/
#print Set.insert_idem /-
@[simp]
theorem insert_idem (a : α) (s : Set α) : insert a (insert a s) = insert a s :=
insert_eq_of_mem <| mem_insert _ _
#align set.insert_idem Set.insert_idem
-/
/- warning: set.insert_union -> Set.insert_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) t) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) t) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.insert_union Set.insert_unionₓ'. -/
theorem insert_union : insert a s ∪ t = insert a (s ∪ t) :=
ext fun x => or_assoc
#align set.insert_union Set.insert_union
/- warning: set.union_insert -> Set.union_insert is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a t)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a t)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.union_insert Set.union_insertₓ'. -/
@[simp]
theorem union_insert : s ∪ insert a t = insert a (s ∪ t) :=
ext fun x => or_left_comm
#align set.union_insert Set.union_insert
#print Set.insert_nonempty /-
@[simp]
theorem insert_nonempty (a : α) (s : Set α) : (insert a s).Nonempty :=
⟨a, mem_insert a s⟩
#align set.insert_nonempty Set.insert_nonempty
-/
instance (a : α) (s : Set α) : Nonempty (insert a s : Set α) :=
(insert_nonempty a s).to_subtype
/- warning: set.insert_inter_distrib -> Set.insert_inter_distrib is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : α) (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a t))
but is expected to have type
forall {α : Type.{u1}} (a : α) (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a t))
Case conversion may be inaccurate. Consider using '#align set.insert_inter_distrib Set.insert_inter_distribₓ'. -/
theorem insert_inter_distrib (a : α) (s t : Set α) : insert a (s ∩ t) = insert a s ∩ insert a t :=
ext fun y => or_and_left
#align set.insert_inter_distrib Set.insert_inter_distrib
/- warning: set.insert_union_distrib -> Set.insert_union_distrib is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : α) (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a t))
but is expected to have type
forall {α : Type.{u1}} (a : α) (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a t))
Case conversion may be inaccurate. Consider using '#align set.insert_union_distrib Set.insert_union_distribₓ'. -/
theorem insert_union_distrib (a : α) (s t : Set α) : insert a (s ∪ t) = insert a s ∪ insert a t :=
ext fun _ => or_or_distrib_left _ _ _
#align set.insert_union_distrib Set.insert_union_distrib
#print Set.insert_inj /-
theorem insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b :=
⟨fun h => eq_of_not_mem_of_mem_insert (h.subst <| mem_insert a s) ha, congr_arg _⟩
#align set.insert_inj Set.insert_inj
-/
#print Set.forall_of_forall_insert /-
-- useful in proofs by induction
theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : Set α} (H : ∀ x, x ∈ insert a s → P x)
(x) (h : x ∈ s) : P x :=
H _ (Or.inr h)
#align set.forall_of_forall_insert Set.forall_of_forall_insert
-/
#print Set.forall_insert_of_forall /-
theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : Set α} (H : ∀ x, x ∈ s → P x) (ha : P a)
(x) (h : x ∈ insert a s) : P x :=
h.elim (fun e => e.symm ▸ ha) (H _)
#align set.forall_insert_of_forall Set.forall_insert_of_forall
-/
/- warning: set.bex_insert_iff -> Set.bex_insert_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {P : α -> Prop} {a : α} {s : Set.{u1} α}, Iff (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s)) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s)) => P x))) (Or (P a) (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) => P x))))
but is expected to have type
forall {α : Type.{u1}} {P : α -> Prop} {a : α} {s : Set.{u1} α}, Iff (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s)) (P x))) (Or (P a) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (P x))))
Case conversion may be inaccurate. Consider using '#align set.bex_insert_iff Set.bex_insert_iffₓ'. -/
theorem bex_insert_iff {P : α → Prop} {a : α} {s : Set α} :
(∃ x ∈ insert a s, P x) ↔ P a ∨ ∃ x ∈ s, P x :=
bex_or_left.trans <| or_congr_left bex_eq_left
#align set.bex_insert_iff Set.bex_insert_iff
#print Set.ball_insert_iff /-
theorem ball_insert_iff {P : α → Prop} {a : α} {s : Set α} :
(∀ x ∈ insert a s, P x) ↔ P a ∧ ∀ x ∈ s, P x :=
ball_or_left.trans <| and_congr_left' forall_eq
#align set.ball_insert_iff Set.ball_insert_iff
-/
/-! ### Lemmas about singletons -/
#print Set.singleton_def /-
theorem singleton_def (a : α) : ({a} : Set α) = insert a ∅ :=
(insert_emptyCollection_eq _).symm
#align set.singleton_def Set.singleton_def
-/
#print Set.mem_singleton_iff /-
@[simp]
theorem mem_singleton_iff {a b : α} : a ∈ ({b} : Set α) ↔ a = b :=
Iff.rfl
#align set.mem_singleton_iff Set.mem_singleton_iff
-/
#print Set.setOf_eq_eq_singleton /-
@[simp]
theorem setOf_eq_eq_singleton {a : α} : { n | n = a } = {a} :=
rfl
#align set.set_of_eq_eq_singleton Set.setOf_eq_eq_singleton
-/
#print Set.setOf_eq_eq_singleton' /-
@[simp]
theorem setOf_eq_eq_singleton' {a : α} : { x | a = x } = {a} :=
ext fun x => eq_comm
#align set.set_of_eq_eq_singleton' Set.setOf_eq_eq_singleton'
-/
#print Set.mem_singleton /-
-- TODO: again, annotation needed
@[simp]
theorem mem_singleton (a : α) : a ∈ ({a} : Set α) :=
@rfl _ _
#align set.mem_singleton Set.mem_singleton
-/
#print Set.eq_of_mem_singleton /-
theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : Set α)) : x = y :=
h
#align set.eq_of_mem_singleton Set.eq_of_mem_singleton
-/
#print Set.singleton_eq_singleton_iff /-
@[simp]
theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : Set α) ↔ x = y :=
ext_iff.trans eq_iff_eq_cancel_left
#align set.singleton_eq_singleton_iff Set.singleton_eq_singleton_iff
-/
#print Set.singleton_injective /-
theorem singleton_injective : Injective (singleton : α → Set α) := fun _ _ =>
singleton_eq_singleton_iff.mp
#align set.singleton_injective Set.singleton_injective
-/
#print Set.mem_singleton_of_eq /-
theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : Set α) :=
H
#align set.mem_singleton_of_eq Set.mem_singleton_of_eq
-/
/- warning: set.insert_eq -> Set.insert_eq is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (x : α) (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) x s) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x) s)
but is expected to have type
forall {α : Type.{u1}} (x : α) (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) x s) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x) s)
Case conversion may be inaccurate. Consider using '#align set.insert_eq Set.insert_eqₓ'. -/
theorem insert_eq (x : α) (s : Set α) : insert x s = ({x} : Set α) ∪ s :=
rfl
#align set.insert_eq Set.insert_eq
#print Set.singleton_nonempty /-
@[simp]
theorem singleton_nonempty (a : α) : ({a} : Set α).Nonempty :=
⟨a, rfl⟩
#align set.singleton_nonempty Set.singleton_nonempty
-/
#print Set.singleton_ne_empty /-
@[simp]
theorem singleton_ne_empty (a : α) : ({a} : Set α) ≠ ∅ :=
(singleton_nonempty _).ne_empty
#align set.singleton_ne_empty Set.singleton_ne_empty
-/
/- warning: set.empty_ssubset_singleton -> Set.empty_ssubset_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α}, HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a)
but is expected to have type
forall {α : Type.{u1}} {a : α}, HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a)
Case conversion may be inaccurate. Consider using '#align set.empty_ssubset_singleton Set.empty_ssubset_singletonₓ'. -/
@[simp]
theorem empty_ssubset_singleton : (∅ : Set α) ⊂ {a} :=
(singleton_nonempty _).empty_ssubset
#align set.empty_ssubset_singleton Set.empty_ssubset_singleton
#print Set.singleton_subset_iff /-
@[simp]
theorem singleton_subset_iff {a : α} {s : Set α} : {a} ⊆ s ↔ a ∈ s :=
forall_eq
#align set.singleton_subset_iff Set.singleton_subset_iff
-/
#print Set.set_compr_eq_eq_singleton /-
theorem set_compr_eq_eq_singleton {a : α} : { b | b = a } = {a} :=
rfl
#align set.set_compr_eq_eq_singleton Set.set_compr_eq_eq_singleton
-/
/- warning: set.singleton_union -> Set.singleton_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a) s) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s)
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a) s) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s)
Case conversion may be inaccurate. Consider using '#align set.singleton_union Set.singleton_unionₓ'. -/
@[simp]
theorem singleton_union : {a} ∪ s = insert a s :=
rfl
#align set.singleton_union Set.singleton_union
/- warning: set.union_singleton -> Set.union_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s)
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s)
Case conversion may be inaccurate. Consider using '#align set.union_singleton Set.union_singletonₓ'. -/
@[simp]
theorem union_singleton : s ∪ {a} = insert a s :=
union_comm _ _
#align set.union_singleton Set.union_singleton
/- warning: set.singleton_inter_nonempty -> Set.singleton_inter_nonempty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a) s)) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a) s)) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)
Case conversion may be inaccurate. Consider using '#align set.singleton_inter_nonempty Set.singleton_inter_nonemptyₓ'. -/
@[simp]
theorem singleton_inter_nonempty : ({a} ∩ s).Nonempty ↔ a ∈ s := by
simp only [Set.Nonempty, mem_inter_iff, mem_singleton_iff, exists_eq_left]
#align set.singleton_inter_nonempty Set.singleton_inter_nonempty
/- warning: set.inter_singleton_nonempty -> Set.inter_singleton_nonempty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a))) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a))) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)
Case conversion may be inaccurate. Consider using '#align set.inter_singleton_nonempty Set.inter_singleton_nonemptyₓ'. -/
@[simp]
theorem inter_singleton_nonempty : (s ∩ {a}).Nonempty ↔ a ∈ s := by
rw [inter_comm, singleton_inter_nonempty]
#align set.inter_singleton_nonempty Set.inter_singleton_nonempty
/- warning: set.singleton_inter_eq_empty -> Set.singleton_inter_eq_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a) s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a) s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s))
Case conversion may be inaccurate. Consider using '#align set.singleton_inter_eq_empty Set.singleton_inter_eq_emptyₓ'. -/
@[simp]
theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s :=
not_nonempty_iff_eq_empty.symm.trans singleton_inter_nonempty.Not
#align set.singleton_inter_eq_empty Set.singleton_inter_eq_empty
/- warning: set.inter_singleton_eq_empty -> Set.inter_singleton_eq_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s))
Case conversion may be inaccurate. Consider using '#align set.inter_singleton_eq_empty Set.inter_singleton_eq_emptyₓ'. -/
@[simp]
theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by
rw [inter_comm, singleton_inter_eq_empty]
#align set.inter_singleton_eq_empty Set.inter_singleton_eq_empty
#print Set.nmem_singleton_empty /-
theorem nmem_singleton_empty {s : Set α} : s ∉ ({∅} : Set (Set α)) ↔ s.Nonempty :=
nonempty_iff_ne_empty.symm
#align set.nmem_singleton_empty Set.nmem_singleton_empty
-/
#print Set.uniqueSingleton /-
instance uniqueSingleton (a : α) : Unique ↥({a} : Set α) :=
⟨⟨⟨a, mem_singleton a⟩⟩, fun ⟨x, h⟩ => Subtype.eq h⟩
#align set.unique_singleton Set.uniqueSingleton
-/
#print Set.eq_singleton_iff_unique_mem /-
theorem eq_singleton_iff_unique_mem : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a :=
Subset.antisymm_iff.trans <| and_comm.trans <| and_congr_left' singleton_subset_iff
#align set.eq_singleton_iff_unique_mem Set.eq_singleton_iff_unique_mem
-/
#print Set.eq_singleton_iff_nonempty_unique_mem /-
theorem eq_singleton_iff_nonempty_unique_mem : s = {a} ↔ s.Nonempty ∧ ∀ x ∈ s, x = a :=
eq_singleton_iff_unique_mem.trans <|
and_congr_left fun H => ⟨fun h' => ⟨_, h'⟩, fun ⟨x, h⟩ => H x h ▸ h⟩
#align set.eq_singleton_iff_nonempty_unique_mem Set.eq_singleton_iff_nonempty_unique_mem
-/
#print Set.default_coe_singleton /-
-- while `simp` is capable of proving this, it is not capable of turning the LHS into the RHS.
@[simp]
theorem default_coe_singleton (x : α) : (default : ({x} : Set α)) = ⟨x, rfl⟩ :=
rfl
#align set.default_coe_singleton Set.default_coe_singleton
-/
/-! ### Lemmas about pairs -/
#print Set.pair_eq_singleton /-
@[simp]
theorem pair_eq_singleton (a : α) : ({a, a} : Set α) = {a} :=
union_self _
#align set.pair_eq_singleton Set.pair_eq_singleton
-/
#print Set.pair_comm /-
theorem pair_comm (a b : α) : ({a, b} : Set α) = {b, a} :=
union_comm _ _
#align set.pair_comm Set.pair_comm
-/
#print Set.pair_eq_pair_iff /-
theorem pair_eq_pair_iff {x y z w : α} :
({x, y} : Set α) = {z, w} ↔ x = z ∧ y = w ∨ x = w ∧ y = z :=
by
simp only [Set.Subset.antisymm_iff, Set.insert_subset, Set.mem_insert_iff, Set.mem_singleton_iff,
Set.singleton_subset_iff]
constructor
· tauto
· rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) <;> simp
#align set.pair_eq_pair_iff Set.pair_eq_pair_iff
-/
/-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/
section Sep
variable {p q : α → Prop} {x : α}
#print Set.mem_sep /-
theorem mem_sep (xs : x ∈ s) (px : p x) : x ∈ { x ∈ s | p x } :=
⟨xs, px⟩
#align set.mem_sep Set.mem_sep
-/
/- warning: set.sep_mem_eq -> Set.sep_mem_eq is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t) s) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t))) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.sep_mem_eq Set.sep_mem_eqₓ'. -/
@[simp]
theorem sep_mem_eq : { x ∈ s | x ∈ t } = s ∩ t :=
rfl
#align set.sep_mem_eq Set.sep_mem_eq
#print Set.mem_sep_iff /-
@[simp]
theorem mem_sep_iff : x ∈ { x ∈ s | p x } ↔ x ∈ s ∧ p x :=
Iff.rfl
#align set.mem_sep_iff Set.mem_sep_iff
-/
#print Set.sep_ext_iff /-
theorem sep_ext_iff : { x ∈ s | p x } = { x ∈ s | q x } ↔ ∀ x ∈ s, p x ↔ q x := by
simp_rw [ext_iff, mem_sep_iff, and_congr_right_iff]
#align set.sep_ext_iff Set.sep_ext_iff
-/
#print Set.sep_eq_of_subset /-
theorem sep_eq_of_subset (h : s ⊆ t) : { x ∈ t | x ∈ s } = s :=
inter_eq_self_of_subset_right h
#align set.sep_eq_of_subset Set.sep_eq_of_subset
-/
#print Set.sep_subset /-
@[simp]
theorem sep_subset (s : Set α) (p : α → Prop) : { x ∈ s | p x } ⊆ s := fun x => And.left
#align set.sep_subset Set.sep_subset
-/
#print Set.sep_eq_self_iff_mem_true /-
@[simp]
theorem sep_eq_self_iff_mem_true : { x ∈ s | p x } = s ↔ ∀ x ∈ s, p x := by
simp_rw [ext_iff, mem_sep_iff, and_iff_left_iff_imp]
#align set.sep_eq_self_iff_mem_true Set.sep_eq_self_iff_mem_true
-/
#print Set.sep_eq_empty_iff_mem_false /-
@[simp]
theorem sep_eq_empty_iff_mem_false : { x ∈ s | p x } = ∅ ↔ ∀ x ∈ s, ¬p x := by
simp_rw [ext_iff, mem_sep_iff, mem_empty_iff_false, iff_false_iff, not_and]
#align set.sep_eq_empty_iff_mem_false Set.sep_eq_empty_iff_mem_false
-/
#print Set.sep_true /-
@[simp]
theorem sep_true : { x ∈ s | True } = s :=
inter_univ s
#align set.sep_true Set.sep_true
-/
#print Set.sep_false /-
@[simp]
theorem sep_false : { x ∈ s | False } = ∅ :=
inter_empty s
#align set.sep_false Set.sep_false
-/
#print Set.sep_empty /-
@[simp]
theorem sep_empty (p : α → Prop) : { x ∈ (∅ : Set α) | p x } = ∅ :=
empty_inter p
#align set.sep_empty Set.sep_empty
-/
#print Set.sep_univ /-
@[simp]
theorem sep_univ : { x ∈ (univ : Set α) | p x } = { x | p x } :=
univ_inter p
#align set.sep_univ Set.sep_univ
-/
/- warning: set.sep_union -> Set.sep_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {p : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => p x) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => p x) s) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => p x) t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {p : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (setOf.{u1} α (fun (x : α) => And (Or (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t)) (p x))) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (p x))) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t) (p x))))
Case conversion may be inaccurate. Consider using '#align set.sep_union Set.sep_unionₓ'. -/
@[simp]
theorem sep_union : { x ∈ s ∪ t | p x } = { x ∈ s | p x } ∪ { x ∈ t | p x } :=
union_inter_distrib_right
#align set.sep_union Set.sep_union
/- warning: set.sep_inter -> Set.sep_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {p : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => p x) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => p x) s) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => p x) t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {p : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (setOf.{u1} α (fun (x : α) => And (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t)) (p x))) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (p x))) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t) (p x))))
Case conversion may be inaccurate. Consider using '#align set.sep_inter Set.sep_interₓ'. -/
@[simp]
theorem sep_inter : { x ∈ s ∩ t | p x } = { x ∈ s | p x } ∩ { x ∈ t | p x } :=
inter_inter_distrib_right s t p
#align set.sep_inter Set.sep_inter
/- warning: set.sep_and -> Set.sep_and is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {p : α -> Prop} {q : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => And (p x) (q x)) s) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => p x) s) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => q x) s))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {p : α -> Prop} {q : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (And (p x) (q x)))) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (p x))) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (q x))))
Case conversion may be inaccurate. Consider using '#align set.sep_and Set.sep_andₓ'. -/
@[simp]
theorem sep_and : { x ∈ s | p x ∧ q x } = { x ∈ s | p x } ∩ { x ∈ s | q x } :=
inter_inter_distrib_left s p q
#align set.sep_and Set.sep_and
/- warning: set.sep_or -> Set.sep_or is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {p : α -> Prop} {q : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => Or (p x) (q x)) s) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => p x) s) (Sep.sep.{u1, u1} α (Set.{u1} α) (Set.hasSep.{u1} α) (fun (x : α) => q x) s))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {p : α -> Prop} {q : α -> Prop}, Eq.{succ u1} (Set.{u1} α) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Or (p x) (q x)))) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (p x))) (setOf.{u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (q x))))
Case conversion may be inaccurate. Consider using '#align set.sep_or Set.sep_orₓ'. -/
@[simp]
theorem sep_or : { x ∈ s | p x ∨ q x } = { x ∈ s | p x } ∪ { x ∈ s | q x } :=
inter_union_distrib_left
#align set.sep_or Set.sep_or
#print Set.sep_setOf /-
@[simp]
theorem sep_setOf : { x ∈ { y | p y } | q x } = { x | p x ∧ q x } :=
rfl
#align set.sep_set_of Set.sep_setOf
-/
end Sep
#print Set.subset_singleton_iff /-
@[simp]
theorem subset_singleton_iff {α : Type _} {s : Set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x :=
Iff.rfl
#align set.subset_singleton_iff Set.subset_singleton_iff
-/
#print Set.subset_singleton_iff_eq /-
theorem subset_singleton_iff_eq {s : Set α} {x : α} : s ⊆ {x} ↔ s = ∅ ∨ s = {x} :=
by
obtain rfl | hs := s.eq_empty_or_nonempty
use ⟨fun _ => Or.inl rfl, fun _ => empty_subset _⟩
simp [eq_singleton_iff_nonempty_unique_mem, hs, hs.ne_empty]
#align set.subset_singleton_iff_eq Set.subset_singleton_iff_eq
-/
#print Set.Nonempty.subset_singleton_iff /-
theorem Nonempty.subset_singleton_iff (h : s.Nonempty) : s ⊆ {a} ↔ s = {a} :=
subset_singleton_iff_eq.trans <| or_iff_right h.ne_empty
#align set.nonempty.subset_singleton_iff Set.Nonempty.subset_singleton_iff
-/
/- warning: set.ssubset_singleton_iff -> Set.ssubset_singleton_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)) (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, Iff (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)) (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)))
Case conversion may be inaccurate. Consider using '#align set.ssubset_singleton_iff Set.ssubset_singleton_iffₓ'. -/
theorem ssubset_singleton_iff {s : Set α} {x : α} : s ⊂ {x} ↔ s = ∅ :=
by
rw [ssubset_iff_subset_ne, subset_singleton_iff_eq, or_and_right, and_not_self_iff, or_false_iff,
and_iff_left_iff_imp]
exact fun h => ne_of_eq_of_ne h (singleton_ne_empty _).symm
#align set.ssubset_singleton_iff Set.ssubset_singleton_iff
/- warning: set.eq_empty_of_ssubset_singleton -> Set.eq_empty_of_ssubset_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.hasSsubset.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)) -> (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (HasSSubset.SSubset.{u1} (Set.{u1} α) (Set.instHasSSubsetSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)) -> (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)))
Case conversion may be inaccurate. Consider using '#align set.eq_empty_of_ssubset_singleton Set.eq_empty_of_ssubset_singletonₓ'. -/
theorem eq_empty_of_ssubset_singleton {s : Set α} {x : α} (hs : s ⊂ {x}) : s = ∅ :=
ssubset_singleton_iff.1 hs
#align set.eq_empty_of_ssubset_singleton Set.eq_empty_of_ssubset_singleton
/-! ### Disjointness -/
/- warning: set.disjoint_iff -> Set.disjoint_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)))
Case conversion may be inaccurate. Consider using '#align set.disjoint_iff Set.disjoint_iffₓ'. -/
protected theorem disjoint_iff : Disjoint s t ↔ s ∩ t ⊆ ∅ :=
disjoint_iff_inf_le
#align set.disjoint_iff Set.disjoint_iff
/- warning: set.disjoint_iff_inter_eq_empty -> Set.disjoint_iff_inter_eq_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)))
Case conversion may be inaccurate. Consider using '#align set.disjoint_iff_inter_eq_empty Set.disjoint_iff_inter_eq_emptyₓ'. -/
theorem disjoint_iff_inter_eq_empty : Disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
#align set.disjoint_iff_inter_eq_empty Set.disjoint_iff_inter_eq_empty
/- warning: disjoint.inter_eq -> Disjoint.inter_eq is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)))
Case conversion may be inaccurate. Consider using '#align disjoint.inter_eq Disjoint.inter_eqₓ'. -/
theorem Disjoint.inter_eq : Disjoint s t → s ∩ t = ∅ :=
Disjoint.eq_bot
#align disjoint.inter_eq Disjoint.inter_eq
/- warning: set.disjoint_left -> Set.disjoint_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) (forall {{a : α}}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s) -> (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) (forall {{a : α}}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s) -> (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t)))
Case conversion may be inaccurate. Consider using '#align set.disjoint_left Set.disjoint_leftₓ'. -/
theorem disjoint_left : Disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t :=
disjoint_iff_inf_le.trans <| forall_congr' fun _ => not_and
#align set.disjoint_left Set.disjoint_left
/- warning: set.disjoint_right -> Set.disjoint_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) (forall {{a : α}}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t) -> (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) (forall {{a : α}}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t) -> (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)))
Case conversion may be inaccurate. Consider using '#align set.disjoint_right Set.disjoint_rightₓ'. -/
theorem disjoint_right : Disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [disjoint_comm, disjoint_left]
#align set.disjoint_right Set.disjoint_right
/- warning: set.not_disjoint_iff -> Set.not_disjoint_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Not (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t)) (Exists.{succ u1} α (fun (x : α) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Not (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t)) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t)))
Case conversion may be inaccurate. Consider using '#align set.not_disjoint_iff Set.not_disjoint_iffₓ'. -/
theorem not_disjoint_iff : ¬Disjoint s t ↔ ∃ x, x ∈ s ∧ x ∈ t :=
Set.disjoint_iff.Not.trans <| not_forall.trans <| exists_congr fun x => Classical.not_not
#align set.not_disjoint_iff Set.not_disjoint_iff
/- warning: set.not_disjoint_iff_nonempty_inter -> Set.not_disjoint_iff_nonempty_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Not (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t)) (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Not (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t)) (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.not_disjoint_iff_nonempty_inter Set.not_disjoint_iff_nonempty_interₓ'. -/
theorem not_disjoint_iff_nonempty_inter : ¬Disjoint s t ↔ (s ∩ t).Nonempty :=
not_disjoint_iff
#align set.not_disjoint_iff_nonempty_inter Set.not_disjoint_iff_nonempty_inter
/- warning: set.nonempty.not_disjoint -> Set.Nonempty.not_disjoint is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) -> (Not (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) -> (Not (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t))
Case conversion may be inaccurate. Consider using '#align set.nonempty.not_disjoint Set.Nonempty.not_disjointₓ'. -/
alias not_disjoint_iff_nonempty_inter ↔ _ nonempty.not_disjoint
#align set.nonempty.not_disjoint Set.Nonempty.not_disjoint
/- warning: set.disjoint_or_nonempty_inter -> Set.disjoint_or_nonempty_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Or (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Or (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.disjoint_or_nonempty_inter Set.disjoint_or_nonempty_interₓ'. -/
theorem disjoint_or_nonempty_inter (s t : Set α) : Disjoint s t ∨ (s ∩ t).Nonempty :=
(em _).imp_right not_disjoint_iff_nonempty_inter.mp
#align set.disjoint_or_nonempty_inter Set.disjoint_or_nonempty_inter
/- warning: set.disjoint_iff_forall_ne -> Set.disjoint_iff_forall_ne is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) (forall (x : α), (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (forall (y : α), (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y t) -> (Ne.{succ u1} α x y)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) (forall {{x : α}}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) -> (forall {{y : α}}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) y t) -> (Ne.{succ u1} α x y)))
Case conversion may be inaccurate. Consider using '#align set.disjoint_iff_forall_ne Set.disjoint_iff_forall_neₓ'. -/
theorem disjoint_iff_forall_ne : Disjoint s t ↔ ∀ x ∈ s, ∀ y ∈ t, x ≠ y := by
simp only [Ne.def, disjoint_left, @imp_not_comm _ (_ = _), forall_eq']
#align set.disjoint_iff_forall_ne Set.disjoint_iff_forall_ne
/- warning: disjoint.ne_of_mem -> Disjoint.ne_of_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (forall {x : α} {y : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y t) -> (Ne.{succ u1} α x y))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (forall {{x : α}}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) -> (forall {{hx : α}}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) hx t) -> (Ne.{succ u1} α x hx)))
Case conversion may be inaccurate. Consider using '#align disjoint.ne_of_mem Disjoint.ne_of_memₓ'. -/
theorem Disjoint.ne_of_mem (h : Disjoint s t) {x y} (hx : x ∈ s) (hy : y ∈ t) : x ≠ y :=
disjoint_iff_forall_ne.mp h x hx y hy
#align disjoint.ne_of_mem Disjoint.ne_of_mem
/- warning: set.disjoint_of_subset_left -> Set.disjoint_of_subset_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₁ s₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s₂ t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s₁ t)
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₁ t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) t s₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s₁ s₂)
Case conversion may be inaccurate. Consider using '#align set.disjoint_of_subset_left Set.disjoint_of_subset_leftₓ'. -/
theorem disjoint_of_subset_left (hs : s₁ ⊆ s₂) (h : Disjoint s₂ t) : Disjoint s₁ t :=
h.mono_left hs
#align set.disjoint_of_subset_left Set.disjoint_of_subset_left
/- warning: set.disjoint_of_subset_right -> Set.disjoint_of_subset_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t₁ t₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t₁)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t₁ t₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t₁)
Case conversion may be inaccurate. Consider using '#align set.disjoint_of_subset_right Set.disjoint_of_subset_rightₓ'. -/
theorem disjoint_of_subset_right (ht : t₁ ⊆ t₂) (h : Disjoint s t₂) : Disjoint s t₁ :=
h.mono_right ht
#align set.disjoint_of_subset_right Set.disjoint_of_subset_right
/- warning: set.disjoint_of_subset -> Set.disjoint_of_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t₁ t₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s₂ t₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s₁ t₁)
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t₁ t₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s₂ t₂) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s₁ t₁)
Case conversion may be inaccurate. Consider using '#align set.disjoint_of_subset Set.disjoint_of_subsetₓ'. -/
theorem disjoint_of_subset (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (h : Disjoint s₂ t₂) : Disjoint s₁ t₁ :=
h.mono hs ht
#align set.disjoint_of_subset Set.disjoint_of_subset
/- warning: set.disjoint_union_left -> Set.disjoint_union_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) u) (And (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s u) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) u) (And (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s u) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) t u))
Case conversion may be inaccurate. Consider using '#align set.disjoint_union_left Set.disjoint_union_leftₓ'. -/
@[simp]
theorem disjoint_union_left : Disjoint (s ∪ t) u ↔ Disjoint s u ∧ Disjoint t u :=
disjoint_sup_left
#align set.disjoint_union_left Set.disjoint_union_left
/- warning: set.disjoint_union_right -> Set.disjoint_union_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) (And (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) (And (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s u))
Case conversion may be inaccurate. Consider using '#align set.disjoint_union_right Set.disjoint_union_rightₓ'. -/
@[simp]
theorem disjoint_union_right : Disjoint s (t ∪ u) ↔ Disjoint s t ∧ Disjoint s u :=
disjoint_sup_right
#align set.disjoint_union_right Set.disjoint_union_right
/- warning: set.disjoint_empty -> Set.disjoint_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.disjoint_empty Set.disjoint_emptyₓ'. -/
@[simp]
theorem disjoint_empty (s : Set α) : Disjoint s ∅ :=
disjoint_bot_right
#align set.disjoint_empty Set.disjoint_empty
/- warning: set.empty_disjoint -> Set.empty_disjoint is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)) s
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)) s
Case conversion may be inaccurate. Consider using '#align set.empty_disjoint Set.empty_disjointₓ'. -/
@[simp]
theorem empty_disjoint (s : Set α) : Disjoint ∅ s :=
disjoint_bot_left
#align set.empty_disjoint Set.empty_disjoint
/- warning: set.univ_disjoint -> Set.univ_disjoint is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (Set.univ.{u1} α) s) (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (Set.univ.{u1} α) s) (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)))
Case conversion may be inaccurate. Consider using '#align set.univ_disjoint Set.univ_disjointₓ'. -/
@[simp]
theorem univ_disjoint : Disjoint univ s ↔ s = ∅ :=
top_disjoint
#align set.univ_disjoint Set.univ_disjoint
/- warning: set.disjoint_univ -> Set.disjoint_univ is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (Set.univ.{u1} α)) (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (Set.univ.{u1} α)) (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)))
Case conversion may be inaccurate. Consider using '#align set.disjoint_univ Set.disjoint_univₓ'. -/
@[simp]
theorem disjoint_univ : Disjoint s univ ↔ s = ∅ :=
disjoint_top
#align set.disjoint_univ Set.disjoint_univ
/- warning: set.disjoint_sdiff_left -> Set.disjoint_sdiff_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t s) s
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t s) s
Case conversion may be inaccurate. Consider using '#align set.disjoint_sdiff_left Set.disjoint_sdiff_leftₓ'. -/
theorem disjoint_sdiff_left : Disjoint (t \ s) s :=
disjoint_sdiff_self_left
#align set.disjoint_sdiff_left Set.disjoint_sdiff_left
/- warning: set.disjoint_sdiff_right -> Set.disjoint_sdiff_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t s)
Case conversion may be inaccurate. Consider using '#align set.disjoint_sdiff_right Set.disjoint_sdiff_rightₓ'. -/
theorem disjoint_sdiff_right : Disjoint s (t \ s) :=
disjoint_sdiff_self_right
#align set.disjoint_sdiff_right Set.disjoint_sdiff_right
/- warning: set.disjoint_singleton_left -> Set.disjoint_singleton_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a) s) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a) s) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s))
Case conversion may be inaccurate. Consider using '#align set.disjoint_singleton_left Set.disjoint_singleton_leftₓ'. -/
@[simp]
theorem disjoint_singleton_left : Disjoint {a} s ↔ a ∉ s := by
simp [Set.disjoint_iff, subset_def] <;> exact Iff.rfl
#align set.disjoint_singleton_left Set.disjoint_singleton_left
/- warning: set.disjoint_singleton_right -> Set.disjoint_singleton_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a)) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a)) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s))
Case conversion may be inaccurate. Consider using '#align set.disjoint_singleton_right Set.disjoint_singleton_rightₓ'. -/
@[simp]
theorem disjoint_singleton_right : Disjoint s {a} ↔ a ∉ s :=
disjoint_comm.trans disjoint_singleton_left
#align set.disjoint_singleton_right Set.disjoint_singleton_right
/- warning: set.disjoint_singleton -> Set.disjoint_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {b : α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) b)) (Ne.{succ u1} α a b)
but is expected to have type
forall {α : Type.{u1}} {a : α} {b : α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) b)) (Ne.{succ u1} α a b)
Case conversion may be inaccurate. Consider using '#align set.disjoint_singleton Set.disjoint_singletonₓ'. -/
@[simp]
theorem disjoint_singleton : Disjoint ({a} : Set α) {b} ↔ a ≠ b := by
rw [disjoint_singleton_left, mem_singleton_iff]
#align set.disjoint_singleton Set.disjoint_singleton
/- warning: set.subset_diff -> Set.subset_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t u)) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s u))
Case conversion may be inaccurate. Consider using '#align set.subset_diff Set.subset_diffₓ'. -/
theorem subset_diff : s ⊆ t \ u ↔ s ⊆ t ∧ Disjoint s u :=
le_iff_subset.symm.trans le_sdiff
#align set.subset_diff Set.subset_diff
/-! ### Lemmas about complement -/
/- warning: set.compl_def -> Set.compl_def is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (setOf.{u1} α (fun (x : α) => Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s)))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (setOf.{u1} α (fun (x : α) => Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s)))
Case conversion may be inaccurate. Consider using '#align set.compl_def Set.compl_defₓ'. -/
theorem compl_def (s : Set α) : sᶜ = { x | x ∉ s } :=
rfl
#align set.compl_def Set.compl_def
/- warning: set.mem_compl -> Set.mem_compl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s)) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s)) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s))
Case conversion may be inaccurate. Consider using '#align set.mem_compl Set.mem_complₓ'. -/
theorem mem_compl {s : Set α} {x : α} (h : x ∉ s) : x ∈ sᶜ :=
h
#align set.mem_compl Set.mem_compl
/- warning: set.compl_set_of -> Set.compl_setOf is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (p : α -> Prop), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (setOf.{u1} α (fun (a : α) => p a))) (setOf.{u1} α (fun (a : α) => Not (p a)))
but is expected to have type
forall {α : Type.{u1}} (p : α -> Prop), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (setOf.{u1} α (fun (a : α) => p a))) (setOf.{u1} α (fun (a : α) => Not (p a)))
Case conversion may be inaccurate. Consider using '#align set.compl_set_of Set.compl_setOfₓ'. -/
theorem compl_setOf {α} (p : α → Prop) : { a | p a }ᶜ = { a | ¬p a } :=
rfl
#align set.compl_set_of Set.compl_setOf
/- warning: set.not_mem_of_mem_compl -> Set.not_mem_of_mem_compl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s)) -> (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s)) -> (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s))
Case conversion may be inaccurate. Consider using '#align set.not_mem_of_mem_compl Set.not_mem_of_mem_complₓ'. -/
theorem not_mem_of_mem_compl {s : Set α} {x : α} (h : x ∈ sᶜ) : x ∉ s :=
h
#align set.not_mem_of_mem_compl Set.not_mem_of_mem_compl
/- warning: set.mem_compl_iff -> Set.mem_compl_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (x : α), Iff (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s)) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (x : α), Iff (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s)) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s))
Case conversion may be inaccurate. Consider using '#align set.mem_compl_iff Set.mem_compl_iffₓ'. -/
@[simp]
theorem mem_compl_iff (s : Set α) (x : α) : x ∈ sᶜ ↔ x ∉ s :=
Iff.rfl
#align set.mem_compl_iff Set.mem_compl_iff
/- warning: set.not_mem_compl_iff -> Set.not_mem_compl_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, Iff (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s))) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, Iff (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s))) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s)
Case conversion may be inaccurate. Consider using '#align set.not_mem_compl_iff Set.not_mem_compl_iffₓ'. -/
theorem not_mem_compl_iff {x : α} : x ∉ sᶜ ↔ x ∈ s :=
Classical.not_not
#align set.not_mem_compl_iff Set.not_mem_compl_iff
/- warning: set.inter_compl_self -> Set.inter_compl_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.inter_compl_self Set.inter_compl_selfₓ'. -/
@[simp]
theorem inter_compl_self (s : Set α) : s ∩ sᶜ = ∅ :=
inf_compl_eq_bot
#align set.inter_compl_self Set.inter_compl_self
/- warning: set.compl_inter_self -> Set.compl_inter_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.compl_inter_self Set.compl_inter_selfₓ'. -/
@[simp]
theorem compl_inter_self (s : Set α) : sᶜ ∩ s = ∅ :=
compl_inf_eq_bot
#align set.compl_inter_self Set.compl_inter_self
/- warning: set.compl_empty -> Set.compl_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (Set.univ.{u1} α)
but is expected to have type
forall {α : Type.{u1}}, Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (Set.univ.{u1} α)
Case conversion may be inaccurate. Consider using '#align set.compl_empty Set.compl_emptyₓ'. -/
@[simp]
theorem compl_empty : (∅ : Set α)ᶜ = univ :=
compl_bot
#align set.compl_empty Set.compl_empty
/- warning: set.compl_union -> Set.compl_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t))
Case conversion may be inaccurate. Consider using '#align set.compl_union Set.compl_unionₓ'. -/
@[simp]
theorem compl_union (s t : Set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ :=
compl_sup
#align set.compl_union Set.compl_union
/- warning: set.compl_inter -> Set.compl_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t))
Case conversion may be inaccurate. Consider using '#align set.compl_inter Set.compl_interₓ'. -/
theorem compl_inter (s t : Set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ :=
compl_inf
#align set.compl_inter Set.compl_inter
/- warning: set.compl_univ -> Set.compl_univ is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Set.univ.{u1} α)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}}, Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Set.univ.{u1} α)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.compl_univ Set.compl_univₓ'. -/
@[simp]
theorem compl_univ : (univ : Set α)ᶜ = ∅ :=
compl_top
#align set.compl_univ Set.compl_univ
/- warning: set.compl_empty_iff -> Set.compl_empty_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (Eq.{succ u1} (Set.{u1} α) s (Set.univ.{u1} α))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (Eq.{succ u1} (Set.{u1} α) s (Set.univ.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.compl_empty_iff Set.compl_empty_iffₓ'. -/
@[simp]
theorem compl_empty_iff {s : Set α} : sᶜ = ∅ ↔ s = univ :=
compl_eq_bot
#align set.compl_empty_iff Set.compl_empty_iff
/- warning: set.compl_univ_iff -> Set.compl_univ_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (Set.univ.{u1} α)) (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (Set.univ.{u1} α)) (Eq.{succ u1} (Set.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)))
Case conversion may be inaccurate. Consider using '#align set.compl_univ_iff Set.compl_univ_iffₓ'. -/
@[simp]
theorem compl_univ_iff {s : Set α} : sᶜ = univ ↔ s = ∅ :=
compl_eq_top
#align set.compl_univ_iff Set.compl_univ_iff
/- warning: set.compl_ne_univ -> Set.compl_ne_univ is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Ne.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (Set.univ.{u1} α)) (Set.Nonempty.{u1} α s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Ne.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (Set.univ.{u1} α)) (Set.Nonempty.{u1} α s)
Case conversion may be inaccurate. Consider using '#align set.compl_ne_univ Set.compl_ne_univₓ'. -/
theorem compl_ne_univ : sᶜ ≠ univ ↔ s.Nonempty :=
compl_univ_iff.Not.trans nonempty_iff_ne_empty.symm
#align set.compl_ne_univ Set.compl_ne_univ
/- warning: set.nonempty_compl -> Set.nonempty_compl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s)) (Ne.{succ u1} (Set.{u1} α) s (Set.univ.{u1} α))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s)) (Ne.{succ u1} (Set.{u1} α) s (Set.univ.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.nonempty_compl Set.nonempty_complₓ'. -/
theorem nonempty_compl : sᶜ.Nonempty ↔ s ≠ univ :=
(ne_univ_iff_exists_not_mem s).symm
#align set.nonempty_compl Set.nonempty_compl
/- warning: set.mem_compl_singleton_iff -> Set.mem_compl_singleton_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {x : α}, Iff (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a))) (Ne.{succ u1} α x a)
but is expected to have type
forall {α : Type.{u1}} {a : α} {x : α}, Iff (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a))) (Ne.{succ u1} α x a)
Case conversion may be inaccurate. Consider using '#align set.mem_compl_singleton_iff Set.mem_compl_singleton_iffₓ'. -/
theorem mem_compl_singleton_iff {a x : α} : x ∈ ({a} : Set α)ᶜ ↔ x ≠ a :=
Iff.rfl
#align set.mem_compl_singleton_iff Set.mem_compl_singleton_iff
/- warning: set.compl_singleton_eq -> Set.compl_singleton_eq is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a)) (setOf.{u1} α (fun (x : α) => Ne.{succ u1} α x a))
but is expected to have type
forall {α : Type.{u1}} (a : α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a)) (setOf.{u1} α (fun (x : α) => Ne.{succ u1} α x a))
Case conversion may be inaccurate. Consider using '#align set.compl_singleton_eq Set.compl_singleton_eqₓ'. -/
theorem compl_singleton_eq (a : α) : ({a} : Set α)ᶜ = { x | x ≠ a } :=
rfl
#align set.compl_singleton_eq Set.compl_singleton_eq
/- warning: set.compl_ne_eq_singleton -> Set.compl_ne_eq_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (setOf.{u1} α (fun (x : α) => Ne.{succ u1} α x a))) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a)
but is expected to have type
forall {α : Type.{u1}} (a : α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (setOf.{u1} α (fun (x : α) => Ne.{succ u1} α x a))) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a)
Case conversion may be inaccurate. Consider using '#align set.compl_ne_eq_singleton Set.compl_ne_eq_singletonₓ'. -/
@[simp]
theorem compl_ne_eq_singleton (a : α) : ({ x | x ≠ a } : Set α)ᶜ = {a} :=
compl_compl _
#align set.compl_ne_eq_singleton Set.compl_ne_eq_singleton
/- warning: set.union_eq_compl_compl_inter_compl -> Set.union_eq_compl_compl_inter_compl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t)))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t)))
Case conversion may be inaccurate. Consider using '#align set.union_eq_compl_compl_inter_compl Set.union_eq_compl_compl_inter_complₓ'. -/
theorem union_eq_compl_compl_inter_compl (s t : Set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ :=
ext fun x => or_iff_not_and_not
#align set.union_eq_compl_compl_inter_compl Set.union_eq_compl_compl_inter_compl
/- warning: set.inter_eq_compl_compl_union_compl -> Set.inter_eq_compl_compl_union_compl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t)))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t)))
Case conversion may be inaccurate. Consider using '#align set.inter_eq_compl_compl_union_compl Set.inter_eq_compl_compl_union_complₓ'. -/
theorem inter_eq_compl_compl_union_compl (s t : Set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ :=
ext fun x => and_iff_not_or_not
#align set.inter_eq_compl_compl_union_compl Set.inter_eq_compl_compl_union_compl
/- warning: set.union_compl_self -> Set.union_compl_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s)) (Set.univ.{u1} α)
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s)) (Set.univ.{u1} α)
Case conversion may be inaccurate. Consider using '#align set.union_compl_self Set.union_compl_selfₓ'. -/
@[simp]
theorem union_compl_self (s : Set α) : s ∪ sᶜ = univ :=
eq_univ_iff_forall.2 fun x => em _
#align set.union_compl_self Set.union_compl_self
/- warning: set.compl_union_self -> Set.compl_union_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) s) (Set.univ.{u1} α)
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) s) (Set.univ.{u1} α)
Case conversion may be inaccurate. Consider using '#align set.compl_union_self Set.compl_union_selfₓ'. -/
@[simp]
theorem compl_union_self (s : Set α) : sᶜ ∪ s = univ := by rw [union_comm, union_compl_self]
#align set.compl_union_self Set.compl_union_self
/- warning: set.compl_subset_comm -> Set.compl_subset_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t) s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t) s)
Case conversion may be inaccurate. Consider using '#align set.compl_subset_comm Set.compl_subset_commₓ'. -/
theorem compl_subset_comm : sᶜ ⊆ t ↔ tᶜ ⊆ s :=
@compl_le_iff_compl_le _ s _ _
#align set.compl_subset_comm Set.compl_subset_comm
/- warning: set.subset_compl_comm -> Set.subset_compl_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s))
Case conversion may be inaccurate. Consider using '#align set.subset_compl_comm Set.subset_compl_commₓ'. -/
theorem subset_compl_comm : s ⊆ tᶜ ↔ t ⊆ sᶜ :=
@le_compl_iff_le_compl _ _ _ t
#align set.subset_compl_comm Set.subset_compl_comm
/- warning: set.compl_subset_compl -> Set.compl_subset_compl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s)
Case conversion may be inaccurate. Consider using '#align set.compl_subset_compl Set.compl_subset_complₓ'. -/
@[simp]
theorem compl_subset_compl : sᶜ ⊆ tᶜ ↔ t ⊆ s :=
@compl_le_compl_iff_le (Set α) _ _ _
#align set.compl_subset_compl Set.compl_subset_compl
/- warning: set.subset_compl_iff_disjoint_left -> Set.subset_compl_iff_disjoint_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t)) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) t s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t)) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) t s)
Case conversion may be inaccurate. Consider using '#align set.subset_compl_iff_disjoint_left Set.subset_compl_iff_disjoint_leftₓ'. -/
theorem subset_compl_iff_disjoint_left : s ⊆ tᶜ ↔ Disjoint t s :=
@le_compl_iff_disjoint_left (Set α) _ _ _
#align set.subset_compl_iff_disjoint_left Set.subset_compl_iff_disjoint_left
/- warning: set.subset_compl_iff_disjoint_right -> Set.subset_compl_iff_disjoint_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t)) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t)) (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t)
Case conversion may be inaccurate. Consider using '#align set.subset_compl_iff_disjoint_right Set.subset_compl_iff_disjoint_rightₓ'. -/
theorem subset_compl_iff_disjoint_right : s ⊆ tᶜ ↔ Disjoint s t :=
@le_compl_iff_disjoint_right (Set α) _ _ _
#align set.subset_compl_iff_disjoint_right Set.subset_compl_iff_disjoint_right
/- warning: set.disjoint_compl_left_iff_subset -> Set.disjoint_compl_left_iff_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s)
Case conversion may be inaccurate. Consider using '#align set.disjoint_compl_left_iff_subset Set.disjoint_compl_left_iff_subsetₓ'. -/
theorem disjoint_compl_left_iff_subset : Disjoint (sᶜ) t ↔ t ⊆ s :=
disjoint_compl_left_iff
#align set.disjoint_compl_left_iff_subset Set.disjoint_compl_left_iff_subset
/- warning: set.disjoint_compl_right_iff_subset -> Set.disjoint_compl_right_iff_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.disjoint_compl_right_iff_subset Set.disjoint_compl_right_iff_subsetₓ'. -/
theorem disjoint_compl_right_iff_subset : Disjoint s (tᶜ) ↔ s ⊆ t :=
disjoint_compl_right_iff
#align set.disjoint_compl_right_iff_subset Set.disjoint_compl_right_iff_subset
/- warning: disjoint.subset_compl_right -> Disjoint.subset_compl_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t))
Case conversion may be inaccurate. Consider using '#align disjoint.subset_compl_right Disjoint.subset_compl_rightₓ'. -/
alias subset_compl_iff_disjoint_right ↔ _ _root_.disjoint.subset_compl_right
#align disjoint.subset_compl_right Disjoint.subset_compl_right
/- warning: disjoint.subset_compl_left -> Disjoint.subset_compl_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) t s) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) t s) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t))
Case conversion may be inaccurate. Consider using '#align disjoint.subset_compl_left Disjoint.subset_compl_leftₓ'. -/
alias subset_compl_iff_disjoint_left ↔ _ _root_.disjoint.subset_compl_left
#align disjoint.subset_compl_left Disjoint.subset_compl_left
/- warning: has_subset.subset.disjoint_compl_left -> HasSubset.Subset.disjoint_compl_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) t)
Case conversion may be inaccurate. Consider using '#align has_subset.subset.disjoint_compl_left HasSubset.Subset.disjoint_compl_leftₓ'. -/
alias disjoint_compl_left_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_left
#align has_subset.subset.disjoint_compl_left HasSubset.Subset.disjoint_compl_left
/- warning: has_subset.subset.disjoint_compl_right -> HasSubset.Subset.disjoint_compl_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t))
Case conversion may be inaccurate. Consider using '#align has_subset.subset.disjoint_compl_right HasSubset.Subset.disjoint_compl_rightₓ'. -/
alias disjoint_compl_right_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_right
#align has_subset.subset.disjoint_compl_right HasSubset.Subset.disjoint_compl_right
/- warning: set.subset_union_compl_iff_inter_subset -> Set.subset_union_compl_iff_inter_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) u))) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) u))) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) t)
Case conversion may be inaccurate. Consider using '#align set.subset_union_compl_iff_inter_subset Set.subset_union_compl_iff_inter_subsetₓ'. -/
theorem subset_union_compl_iff_inter_subset {s t u : Set α} : s ⊆ t ∪ uᶜ ↔ s ∩ u ⊆ t :=
(@isCompl_compl _ u _).le_sup_right_iff_inf_left_le
#align set.subset_union_compl_iff_inter_subset Set.subset_union_compl_iff_inter_subset
/- warning: set.compl_subset_iff_union -> Set.compl_subset_iff_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) t) (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (Set.univ.{u1} α))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) t) (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (Set.univ.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.compl_subset_iff_union Set.compl_subset_iff_unionₓ'. -/
theorem compl_subset_iff_union {s t : Set α} : sᶜ ⊆ t ↔ s ∪ t = univ :=
Iff.symm <| eq_univ_iff_forall.trans <| forall_congr' fun a => or_iff_not_imp_left
#align set.compl_subset_iff_union Set.compl_subset_iff_union
/- warning: set.subset_compl_singleton_iff -> Set.subset_compl_singleton_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a))) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a))) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s))
Case conversion may be inaccurate. Consider using '#align set.subset_compl_singleton_iff Set.subset_compl_singleton_iffₓ'. -/
@[simp]
theorem subset_compl_singleton_iff {a : α} {s : Set α} : s ⊆ {a}ᶜ ↔ a ∉ s :=
subset_compl_comm.trans singleton_subset_iff
#align set.subset_compl_singleton_iff Set.subset_compl_singleton_iff
/- warning: set.inter_subset -> Set.inter_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α) (c : Set.{u1} α), Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a b) c) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) b) c))
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α) (c : Set.{u1} α), Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a b) c) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) b) c))
Case conversion may be inaccurate. Consider using '#align set.inter_subset Set.inter_subsetₓ'. -/
theorem inter_subset (a b c : Set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c :=
forall_congr' fun x => and_imp.trans <| imp_congr_right fun _ => imp_iff_not_or
#align set.inter_subset Set.inter_subset
/- warning: set.inter_compl_nonempty_iff -> Set.inter_compl_nonempty_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t))) (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t))) (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.inter_compl_nonempty_iff Set.inter_compl_nonempty_iffₓ'. -/
theorem inter_compl_nonempty_iff {s t : Set α} : (s ∩ tᶜ).Nonempty ↔ ¬s ⊆ t :=
(not_subset.trans <| exists_congr fun x => by simp [mem_compl]).symm
#align set.inter_compl_nonempty_iff Set.inter_compl_nonempty_iff
/-! ### Lemmas about set difference -/
/- warning: set.diff_eq -> Set.diff_eq is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t))
Case conversion may be inaccurate. Consider using '#align set.diff_eq Set.diff_eqₓ'. -/
theorem diff_eq (s t : Set α) : s \ t = s ∩ tᶜ :=
rfl
#align set.diff_eq Set.diff_eq
/- warning: set.mem_diff -> Set.mem_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (x : α), Iff (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)) (And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (x : α), Iff (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t)))
Case conversion may be inaccurate. Consider using '#align set.mem_diff Set.mem_diffₓ'. -/
@[simp]
theorem mem_diff {s t : Set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t :=
Iff.rfl
#align set.mem_diff Set.mem_diff
/- warning: set.mem_diff_of_mem -> Set.mem_diff_of_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {x : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t)) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {x : α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) -> (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t)) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.mem_diff_of_mem Set.mem_diff_of_memₓ'. -/
theorem mem_diff_of_mem {s t : Set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t :=
⟨h1, h2⟩
#align set.mem_diff_of_mem Set.mem_diff_of_mem
/- warning: set.not_mem_diff_of_mem -> Set.not_mem_diff_of_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {x : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t) -> (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {x : α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t) -> (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)))
Case conversion may be inaccurate. Consider using '#align set.not_mem_diff_of_mem Set.not_mem_diff_of_memₓ'. -/
theorem not_mem_diff_of_mem {s t : Set α} {x : α} (hx : x ∈ t) : x ∉ s \ t := fun h => h.2 hx
#align set.not_mem_diff_of_mem Set.not_mem_diff_of_mem
/- warning: set.mem_of_mem_diff -> Set.mem_of_mem_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {x : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {x : α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s)
Case conversion may be inaccurate. Consider using '#align set.mem_of_mem_diff Set.mem_of_mem_diffₓ'. -/
theorem mem_of_mem_diff {s t : Set α} {x : α} (h : x ∈ s \ t) : x ∈ s :=
h.left
#align set.mem_of_mem_diff Set.mem_of_mem_diff
/- warning: set.not_mem_of_mem_diff -> Set.not_mem_of_mem_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {x : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)) -> (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {x : α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)) -> (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x t))
Case conversion may be inaccurate. Consider using '#align set.not_mem_of_mem_diff Set.not_mem_of_mem_diffₓ'. -/
theorem not_mem_of_mem_diff {s t : Set α} {x : α} (h : x ∈ s \ t) : x ∉ t :=
h.right
#align set.not_mem_of_mem_diff Set.not_mem_of_mem_diff
/- warning: set.diff_eq_compl_inter -> Set.diff_eq_compl_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t) s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t) s)
Case conversion may be inaccurate. Consider using '#align set.diff_eq_compl_inter Set.diff_eq_compl_interₓ'. -/
theorem diff_eq_compl_inter {s t : Set α} : s \ t = tᶜ ∩ s := by rw [diff_eq, inter_comm]
#align set.diff_eq_compl_inter Set.diff_eq_compl_inter
/- warning: set.nonempty_diff -> Set.nonempty_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)) (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)) (Not (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.nonempty_diff Set.nonempty_diffₓ'. -/
theorem nonempty_diff {s t : Set α} : (s \ t).Nonempty ↔ ¬s ⊆ t :=
inter_compl_nonempty_iff
#align set.nonempty_diff Set.nonempty_diff
/- warning: set.diff_subset -> Set.diff_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) s
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) s
Case conversion may be inaccurate. Consider using '#align set.diff_subset Set.diff_subsetₓ'. -/
theorem diff_subset (s t : Set α) : s \ t ⊆ s :=
show s \ t ≤ s from sdiff_le
#align set.diff_subset Set.diff_subset
/- warning: set.union_diff_cancel' -> Set.union_diff_cancel' is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t u) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) u s)) u)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t u) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) u s)) u)
Case conversion may be inaccurate. Consider using '#align set.union_diff_cancel' Set.union_diff_cancel'ₓ'. -/
theorem union_diff_cancel' {s t u : Set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ u \ s = u :=
sup_sdiff_cancel' h₁ h₂
#align set.union_diff_cancel' Set.union_diff_cancel'
/- warning: set.union_diff_cancel -> Set.union_diff_cancel is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t s)) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t s)) t)
Case conversion may be inaccurate. Consider using '#align set.union_diff_cancel Set.union_diff_cancelₓ'. -/
theorem union_diff_cancel {s t : Set α} (h : s ⊆ t) : s ∪ t \ s = t :=
sup_sdiff_cancel_right h
#align set.union_diff_cancel Set.union_diff_cancel
/- warning: set.union_diff_cancel_left -> Set.union_diff_cancel_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) s) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) s) t)
Case conversion may be inaccurate. Consider using '#align set.union_diff_cancel_left Set.union_diff_cancel_leftₓ'. -/
theorem union_diff_cancel_left {s t : Set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t :=
Disjoint.sup_sdiff_cancel_left <| disjoint_iff_inf_le.2 h
#align set.union_diff_cancel_left Set.union_diff_cancel_left
/- warning: set.union_diff_cancel_right -> Set.union_diff_cancel_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) t) s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) t) s)
Case conversion may be inaccurate. Consider using '#align set.union_diff_cancel_right Set.union_diff_cancel_rightₓ'. -/
theorem union_diff_cancel_right {s t : Set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s :=
Disjoint.sup_sdiff_cancel_right <| disjoint_iff_inf_le.2 h
#align set.union_diff_cancel_right Set.union_diff_cancel_right
/- warning: set.union_diff_left -> Set.union_diff_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) s) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) s) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t s)
Case conversion may be inaccurate. Consider using '#align set.union_diff_left Set.union_diff_leftₓ'. -/
@[simp]
theorem union_diff_left {s t : Set α} : (s ∪ t) \ s = t \ s :=
sup_sdiff_left_self
#align set.union_diff_left Set.union_diff_left
/- warning: set.union_diff_right -> Set.union_diff_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) t) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) t) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.union_diff_right Set.union_diff_rightₓ'. -/
@[simp]
theorem union_diff_right {s t : Set α} : (s ∪ t) \ t = s \ t :=
sup_sdiff_right_self
#align set.union_diff_right Set.union_diff_right
/- warning: set.union_diff_distrib -> Set.union_diff_distrib is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) u) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s u) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) u) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s u) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.union_diff_distrib Set.union_diff_distribₓ'. -/
theorem union_diff_distrib {s t u : Set α} : (s ∪ t) \ u = s \ u ∪ t \ u :=
sup_sdiff
#align set.union_diff_distrib Set.union_diff_distrib
/- warning: set.inter_diff_assoc -> Set.inter_diff_assoc is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α) (c : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a b) c) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) b c))
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α) (c : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a b) c) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) b c))
Case conversion may be inaccurate. Consider using '#align set.inter_diff_assoc Set.inter_diff_assocₓ'. -/
theorem inter_diff_assoc (a b c : Set α) : (a ∩ b) \ c = a ∩ (b \ c) :=
inf_sdiff_assoc
#align set.inter_diff_assoc Set.inter_diff_assoc
/- warning: set.inter_diff_self -> Set.inter_diff_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) b a)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} (a : Set.{u1} α) (b : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) b a)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.inter_diff_self Set.inter_diff_selfₓ'. -/
@[simp]
theorem inter_diff_self (a b : Set α) : a ∩ (b \ a) = ∅ :=
inf_sdiff_self_right
#align set.inter_diff_self Set.inter_diff_self
/- warning: set.inter_union_diff -> Set.inter_union_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)) s
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)) s
Case conversion may be inaccurate. Consider using '#align set.inter_union_diff Set.inter_union_diffₓ'. -/
@[simp]
theorem inter_union_diff (s t : Set α) : s ∩ t ∪ s \ t = s :=
sup_inf_sdiff s t
#align set.inter_union_diff Set.inter_union_diff
/- warning: set.diff_union_inter -> Set.diff_union_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) s
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) s
Case conversion may be inaccurate. Consider using '#align set.diff_union_inter Set.diff_union_interₓ'. -/
@[simp]
theorem diff_union_inter (s t : Set α) : s \ t ∪ s ∩ t = s :=
by
rw [union_comm]
exact sup_inf_sdiff _ _
#align set.diff_union_inter Set.diff_union_inter
/- warning: set.inter_union_compl -> Set.inter_union_compl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t))) s
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t))) s
Case conversion may be inaccurate. Consider using '#align set.inter_union_compl Set.inter_union_complₓ'. -/
@[simp]
theorem inter_union_compl (s t : Set α) : s ∩ t ∪ s ∩ tᶜ = s :=
inter_union_diff _ _
#align set.inter_union_compl Set.inter_union_compl
/- warning: set.diff_subset_diff -> Set.diff_subset_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t₂ t₁) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s₁ t₁) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s₂ t₂))
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t₁ : Set.{u1} α} {t₂ : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t₂ t₁) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s₁ t₁) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s₂ t₂))
Case conversion may be inaccurate. Consider using '#align set.diff_subset_diff Set.diff_subset_diffₓ'. -/
theorem diff_subset_diff {s₁ s₂ t₁ t₂ : Set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ :=
show s₁ ≤ s₂ → t₂ ≤ t₁ → s₁ \ t₁ ≤ s₂ \ t₂ from sdiff_le_sdiff
#align set.diff_subset_diff Set.diff_subset_diff
/- warning: set.diff_subset_diff_left -> Set.diff_subset_diff_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s₁ t) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s₂ t))
but is expected to have type
forall {α : Type.{u1}} {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s₁ s₂) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s₁ t) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s₂ t))
Case conversion may be inaccurate. Consider using '#align set.diff_subset_diff_left Set.diff_subset_diff_leftₓ'. -/
theorem diff_subset_diff_left {s₁ s₂ t : Set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t :=
sdiff_le_sdiff_right ‹s₁ ≤ s₂›
#align set.diff_subset_diff_left Set.diff_subset_diff_left
/- warning: set.diff_subset_diff_right -> Set.diff_subset_diff_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t u) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s u) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t u) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s u) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.diff_subset_diff_right Set.diff_subset_diff_rightₓ'. -/
theorem diff_subset_diff_right {s t u : Set α} (h : t ⊆ u) : s \ u ⊆ s \ t :=
sdiff_le_sdiff_left ‹t ≤ u›
#align set.diff_subset_diff_right Set.diff_subset_diff_right
/- warning: set.compl_eq_univ_diff -> Set.compl_eq_univ_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Set.univ.{u1} α) s)
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Set.univ.{u1} α) s)
Case conversion may be inaccurate. Consider using '#align set.compl_eq_univ_diff Set.compl_eq_univ_diffₓ'. -/
theorem compl_eq_univ_diff (s : Set α) : sᶜ = univ \ s :=
top_sdiff.symm
#align set.compl_eq_univ_diff Set.compl_eq_univ_diff
/- warning: set.empty_diff -> Set.empty_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)) s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)) s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.empty_diff Set.empty_diffₓ'. -/
@[simp]
theorem empty_diff (s : Set α) : (∅ \ s : Set α) = ∅ :=
bot_sdiff
#align set.empty_diff Set.empty_diff
/- warning: set.diff_eq_empty -> Set.diff_eq_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.diff_eq_empty Set.diff_eq_emptyₓ'. -/
theorem diff_eq_empty {s t : Set α} : s \ t = ∅ ↔ s ⊆ t :=
sdiff_eq_bot_iff
#align set.diff_eq_empty Set.diff_eq_empty
/- warning: set.diff_empty -> Set.diff_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) s
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) s
Case conversion may be inaccurate. Consider using '#align set.diff_empty Set.diff_emptyₓ'. -/
@[simp]
theorem diff_empty {s : Set α} : s \ ∅ = s :=
sdiff_bot
#align set.diff_empty Set.diff_empty
/- warning: set.diff_univ -> Set.diff_univ is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Set.univ.{u1} α)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Set.univ.{u1} α)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.diff_univ Set.diff_univₓ'. -/
@[simp]
theorem diff_univ (s : Set α) : s \ univ = ∅ :=
diff_eq_empty.2 (subset_univ s)
#align set.diff_univ Set.diff_univ
/- warning: set.diff_diff -> Set.diff_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) u) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) u) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.diff_diff Set.diff_diffₓ'. -/
theorem diff_diff {u : Set α} : (s \ t) \ u = s \ (t ∪ u) :=
sdiff_sdiff_left
#align set.diff_diff Set.diff_diff
/- warning: set.diff_diff_comm -> Set.diff_diff_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) u) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s u) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) u) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s u) t)
Case conversion may be inaccurate. Consider using '#align set.diff_diff_comm Set.diff_diff_commₓ'. -/
-- the following statement contains parentheses to help the reader
theorem diff_diff_comm {s t u : Set α} : (s \ t) \ u = (s \ u) \ t :=
sdiff_sdiff_comm
#align set.diff_diff_comm Set.diff_diff_comm
/- warning: set.diff_subset_iff -> Set.diff_subset_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) u) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) u) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.diff_subset_iff Set.diff_subset_iffₓ'. -/
theorem diff_subset_iff {s t u : Set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u :=
show s \ t ≤ u ↔ s ≤ t ∪ u from sdiff_le_iff
#align set.diff_subset_iff Set.diff_subset_iff
/- warning: set.subset_diff_union -> Set.subset_diff_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) t)
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) t)
Case conversion may be inaccurate. Consider using '#align set.subset_diff_union Set.subset_diff_unionₓ'. -/
theorem subset_diff_union (s t : Set α) : s ⊆ s \ t ∪ t :=
show s ≤ s \ t ∪ t from le_sdiff_sup
#align set.subset_diff_union Set.subset_diff_union
/- warning: set.diff_union_of_subset -> Set.diff_union_of_subset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) t) s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s) -> (Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) t) s)
Case conversion may be inaccurate. Consider using '#align set.diff_union_of_subset Set.diff_union_of_subsetₓ'. -/
theorem diff_union_of_subset {s t : Set α} (h : t ⊆ s) : s \ t ∪ t = s :=
Subset.antisymm (union_subset (diff_subset _ _) h) (subset_diff_union _ _)
#align set.diff_union_of_subset Set.diff_union_of_subset
/- warning: set.diff_singleton_subset_iff -> Set.diff_singleton_subset_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) x t))
but is expected to have type
forall {α : Type.{u1}} {x : α} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)) t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) x t))
Case conversion may be inaccurate. Consider using '#align set.diff_singleton_subset_iff Set.diff_singleton_subset_iffₓ'. -/
@[simp]
theorem diff_singleton_subset_iff {x : α} {s t : Set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t :=
by
rw [← union_singleton, union_comm]
apply diff_subset_iff
#align set.diff_singleton_subset_iff Set.diff_singleton_subset_iff
/- warning: set.subset_diff_singleton -> Set.subset_diff_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s)) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))
but is expected to have type
forall {α : Type.{u1}} {x : α} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s)) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)))
Case conversion may be inaccurate. Consider using '#align set.subset_diff_singleton Set.subset_diff_singletonₓ'. -/
theorem subset_diff_singleton {x : α} {s t : Set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} :=
subset_inter h <| subset_compl_comm.1 <| singleton_subset_iff.2 hx
#align set.subset_diff_singleton Set.subset_diff_singleton
/- warning: set.subset_insert_diff_singleton -> Set.subset_insert_diff_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (x : α) (s : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))
but is expected to have type
forall {α : Type.{u1}} (x : α) (s : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)))
Case conversion may be inaccurate. Consider using '#align set.subset_insert_diff_singleton Set.subset_insert_diff_singletonₓ'. -/
theorem subset_insert_diff_singleton (x : α) (s : Set α) : s ⊆ insert x (s \ {x}) := by
rw [← diff_singleton_subset_iff]
#align set.subset_insert_diff_singleton Set.subset_insert_diff_singleton
/- warning: set.diff_subset_comm -> Set.diff_subset_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) u) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s u) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) u) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s u) t)
Case conversion may be inaccurate. Consider using '#align set.diff_subset_comm Set.diff_subset_commₓ'. -/
theorem diff_subset_comm {s t u : Set α} : s \ t ⊆ u ↔ s \ u ⊆ t :=
show s \ t ≤ u ↔ s \ u ≤ t from sdiff_le_comm
#align set.diff_subset_comm Set.diff_subset_comm
/- warning: set.diff_inter -> Set.diff_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.diff_inter Set.diff_interₓ'. -/
theorem diff_inter {s t u : Set α} : s \ (t ∩ u) = s \ t ∪ s \ u :=
sdiff_inf
#align set.diff_inter Set.diff_inter
/- warning: set.diff_inter_diff -> Set.diff_inter_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s u)) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s u)) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.diff_inter_diff Set.diff_inter_diffₓ'. -/
theorem diff_inter_diff {s t u : Set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) :=
sdiff_sup.symm
#align set.diff_inter_diff Set.diff_inter_diff
/- warning: set.diff_compl -> Set.diff_compl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.diff_compl Set.diff_complₓ'. -/
theorem diff_compl : s \ tᶜ = s ∩ t :=
sdiff_compl
#align set.diff_compl Set.diff_compl
/- warning: set.diff_diff_right -> Set.diff_diff_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t u)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t u)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.diff_diff_right Set.diff_diff_rightₓ'. -/
theorem diff_diff_right {s t u : Set α} : s \ (t \ u) = s \ t ∪ s ∩ u :=
sdiff_sdiff_right'
#align set.diff_diff_right Set.diff_diff_right
/- warning: set.insert_diff_of_mem -> Set.insert_diff_of_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {t : Set.{u1} α} (s : Set.{u1} α), (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) t) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t))
but is expected to have type
forall {α : Type.{u1}} {a : α} {t : Set.{u1} α} (s : Set.{u1} α), (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) t) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.insert_diff_of_mem Set.insert_diff_of_memₓ'. -/
@[simp]
theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t :=
by
ext
constructor <;> simp (config := { contextual := true }) [or_imp, h]
#align set.insert_diff_of_mem Set.insert_diff_of_mem
/- warning: set.insert_diff_of_not_mem -> Set.insert_diff_of_not_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {t : Set.{u1} α} (s : Set.{u1} α), (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t)) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) t) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)))
but is expected to have type
forall {α : Type.{u1}} {a : α} {t : Set.{u1} α} (s : Set.{u1} α), (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t)) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) t) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)))
Case conversion may be inaccurate. Consider using '#align set.insert_diff_of_not_mem Set.insert_diff_of_not_memₓ'. -/
theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) := by
classical
ext x
by_cases h' : x ∈ t
· have : x ≠ a := by
intro H
rw [H] at h'
exact h h'
simp [h, h', this]
· simp [h, h']
#align set.insert_diff_of_not_mem Set.insert_diff_of_not_mem
/- warning: set.insert_diff_self_of_not_mem -> Set.insert_diff_self_of_not_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a)) s)
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a)) s)
Case conversion may be inaccurate. Consider using '#align set.insert_diff_self_of_not_mem Set.insert_diff_self_of_not_memₓ'. -/
theorem insert_diff_self_of_not_mem {a : α} {s : Set α} (h : a ∉ s) : insert a s \ {a} = s :=
by
ext
simp [and_iff_left_of_imp fun hx : x ∈ s => show x ≠ a from fun hxa => h <| hxa ▸ hx]
#align set.insert_diff_self_of_not_mem Set.insert_diff_self_of_not_mem
/- warning: set.insert_diff_eq_singleton -> Set.insert_diff_eq_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) s) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) s) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a))
Case conversion may be inaccurate. Consider using '#align set.insert_diff_eq_singleton Set.insert_diff_eq_singletonₓ'. -/
@[simp]
theorem insert_diff_eq_singleton {a : α} {s : Set α} (h : a ∉ s) : insert a s \ s = {a} :=
by
ext
rw [Set.mem_diff, Set.mem_insert_iff, Set.mem_singleton_iff, or_and_right, and_not_self_iff,
or_false_iff, and_iff_left_iff_imp]
rintro rfl
exact h
#align set.insert_diff_eq_singleton Set.insert_diff_eq_singleton
/- warning: set.inter_insert_of_mem -> Set.inter_insert_of_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a t)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a t)) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)))
Case conversion may be inaccurate. Consider using '#align set.inter_insert_of_mem Set.inter_insert_of_memₓ'. -/
theorem inter_insert_of_mem (h : a ∈ s) : s ∩ insert a t = insert a (s ∩ t) := by
rw [insert_inter_distrib, insert_eq_of_mem h]
#align set.inter_insert_of_mem Set.inter_insert_of_mem
/- warning: set.insert_inter_of_mem -> Set.insert_inter_of_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) t) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) t) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)))
Case conversion may be inaccurate. Consider using '#align set.insert_inter_of_mem Set.insert_inter_of_memₓ'. -/
theorem insert_inter_of_mem (h : a ∈ t) : insert a s ∩ t = insert a (s ∩ t) := by
rw [insert_inter_distrib, insert_eq_of_mem h]
#align set.insert_inter_of_mem Set.insert_inter_of_mem
/- warning: set.inter_insert_of_not_mem -> Set.inter_insert_of_not_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a t)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a t)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.inter_insert_of_not_mem Set.inter_insert_of_not_memₓ'. -/
theorem inter_insert_of_not_mem (h : a ∉ s) : s ∩ insert a t = s ∩ t :=
ext fun x => and_congr_right fun hx => or_iff_right <| ne_of_mem_of_not_mem hx h
#align set.inter_insert_of_not_mem Set.inter_insert_of_not_mem
/- warning: set.insert_inter_of_not_mem -> Set.insert_inter_of_not_mem is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t)) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s) t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t)) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s) t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.insert_inter_of_not_mem Set.insert_inter_of_not_memₓ'. -/
theorem insert_inter_of_not_mem (h : a ∉ t) : insert a s ∩ t = s ∩ t :=
ext fun x => and_congr_left fun hx => or_iff_right <| ne_of_mem_of_not_mem hx h
#align set.insert_inter_of_not_mem Set.insert_inter_of_not_mem
/- warning: set.union_diff_self -> Set.union_diff_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t s)) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t s)) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.union_diff_self Set.union_diff_selfₓ'. -/
@[simp]
theorem union_diff_self {s t : Set α} : s ∪ t \ s = s ∪ t :=
sup_sdiff_self _ _
#align set.union_diff_self Set.union_diff_self
/- warning: set.diff_union_self -> Set.diff_union_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.diff_union_self Set.diff_union_selfₓ'. -/
@[simp]
theorem diff_union_self {s t : Set α} : s \ t ∪ t = s ∪ t :=
sdiff_sup_self _ _
#align set.diff_union_self Set.diff_union_self
/- warning: set.diff_inter_self -> Set.diff_inter_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : Set.{u1} α} {b : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) b a) a) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} {a : Set.{u1} α} {b : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) b a) a) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.diff_inter_self Set.diff_inter_selfₓ'. -/
@[simp]
theorem diff_inter_self {a b : Set α} : b \ a ∩ a = ∅ :=
inf_sdiff_self_left
#align set.diff_inter_self Set.diff_inter_self
/- warning: set.diff_inter_self_eq_diff -> Set.diff_inter_self_eq_diff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t s)) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t s)) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.diff_inter_self_eq_diff Set.diff_inter_self_eq_diffₓ'. -/
@[simp]
theorem diff_inter_self_eq_diff {s t : Set α} : s \ (t ∩ s) = s \ t :=
sdiff_inf_self_right _ _
#align set.diff_inter_self_eq_diff Set.diff_inter_self_eq_diff
/- warning: set.diff_self_inter -> Set.diff_self_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.diff_self_inter Set.diff_self_interₓ'. -/
@[simp]
theorem diff_self_inter {s t : Set α} : s \ (s ∩ t) = s \ t :=
sdiff_inf_self_left _ _
#align set.diff_self_inter Set.diff_self_inter
/- warning: set.diff_singleton_eq_self -> Set.diff_singleton_eq_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a)) s)
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a)) s)
Case conversion may be inaccurate. Consider using '#align set.diff_singleton_eq_self Set.diff_singleton_eq_selfₓ'. -/
@[simp]
theorem diff_singleton_eq_self {a : α} {s : Set α} (h : a ∉ s) : s \ {a} = s :=
sdiff_eq_self_iff_disjoint.2 <| by simp [h]
#align set.diff_singleton_eq_self Set.diff_singleton_eq_self
/- warning: set.insert_diff_singleton -> Set.insert_diff_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) a))) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.hasInsert.{u1} α) a s)
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) a))) (Insert.insert.{u1, u1} α (Set.{u1} α) (Set.instInsertSet.{u1} α) a s)
Case conversion may be inaccurate. Consider using '#align set.insert_diff_singleton Set.insert_diff_singletonₓ'. -/
@[simp]
theorem insert_diff_singleton {a : α} {s : Set α} : insert a (s \ {a}) = insert a s := by
simp [insert_eq, union_diff_self, -union_singleton, -singleton_union]
#align set.insert_diff_singleton Set.insert_diff_singleton
/- warning: set.diff_self -> Set.diff_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s s) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))
Case conversion may be inaccurate. Consider using '#align set.diff_self Set.diff_selfₓ'. -/
@[simp]
theorem diff_self {s : Set α} : s \ s = ∅ :=
sdiff_self
#align set.diff_self Set.diff_self
/- warning: set.diff_diff_right_self -> Set.diff_diff_right_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.diff_diff_right_self Set.diff_diff_right_selfₓ'. -/
theorem diff_diff_right_self (s t : Set α) : s \ (s \ t) = s ∩ t :=
sdiff_sdiff_right_self
#align set.diff_diff_right_self Set.diff_diff_right_self
/- warning: set.diff_diff_cancel_left -> Set.diff_diff_cancel_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t s)) s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) -> (Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t s)) s)
Case conversion may be inaccurate. Consider using '#align set.diff_diff_cancel_left Set.diff_diff_cancel_leftₓ'. -/
theorem diff_diff_cancel_left {s t : Set α} (h : s ⊆ t) : t \ (t \ s) = s :=
sdiff_sdiff_eq_self h
#align set.diff_diff_cancel_left Set.diff_diff_cancel_left
/- warning: set.mem_diff_singleton -> Set.mem_diff_singleton is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {x : α} {y : α} {s : Set.{u1} α}, Iff (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) y))) (And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) (Ne.{succ u1} α x y))
but is expected to have type
forall {α : Type.{u1}} {x : α} {y : α} {s : Set.{u1} α}, Iff (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) y))) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Ne.{succ u1} α x y))
Case conversion may be inaccurate. Consider using '#align set.mem_diff_singleton Set.mem_diff_singletonₓ'. -/
theorem mem_diff_singleton {x y : α} {s : Set α} : x ∈ s \ {y} ↔ x ∈ s ∧ x ≠ y :=
Iff.rfl
#align set.mem_diff_singleton Set.mem_diff_singleton
/- warning: set.mem_diff_singleton_empty -> Set.mem_diff_singleton_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} (Set.{u1} α)}, Iff (Membership.Mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.hasMem.{u1} (Set.{u1} α)) s (SDiff.sdiff.{u1} (Set.{u1} (Set.{u1} α)) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} (Set.{u1} α)) (Set.booleanAlgebra.{u1} (Set.{u1} α))) t (Singleton.singleton.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.hasSingleton.{u1} (Set.{u1} α)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))))) (And (Membership.Mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.hasMem.{u1} (Set.{u1} α)) s t) (Set.Nonempty.{u1} α s))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} (Set.{u1} α)}, Iff (Membership.mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.instMembershipSet.{u1} (Set.{u1} α)) s (SDiff.sdiff.{u1} (Set.{u1} (Set.{u1} α)) (Set.instSDiffSet.{u1} (Set.{u1} α)) t (Singleton.singleton.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.instSingletonSet.{u1} (Set.{u1} α)) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))))) (And (Membership.mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.instMembershipSet.{u1} (Set.{u1} α)) s t) (Set.Nonempty.{u1} α s))
Case conversion may be inaccurate. Consider using '#align set.mem_diff_singleton_empty Set.mem_diff_singleton_emptyₓ'. -/
theorem mem_diff_singleton_empty {t : Set (Set α)} : s ∈ t \ {∅} ↔ s ∈ t ∧ s.Nonempty :=
mem_diff_singleton.trans <| and_congr_right' nonempty_iff_ne_empty.symm
#align set.mem_diff_singleton_empty Set.mem_diff_singleton_empty
/- warning: set.union_eq_diff_union_diff_union_inter -> Set.union_eq_diff_union_diff_union_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t s)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t s)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.union_eq_diff_union_diff_union_inter Set.union_eq_diff_union_diff_union_interₓ'. -/
theorem union_eq_diff_union_diff_union_inter (s t : Set α) : s ∪ t = s \ t ∪ t \ s ∪ s ∩ t :=
sup_eq_sdiff_sup_sdiff_sup_inf
#align set.union_eq_diff_union_diff_union_inter Set.union_eq_diff_union_diff_union_inter
/-! ### Symmetric difference -/
/- warning: set.mem_symm_diff -> Set.mem_symmDiff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)) (Or (And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t))) (And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s))))
but is expected to have type
forall {α : Type.{u1}} {a : α} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) s t)) (Or (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t))) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s))))
Case conversion may be inaccurate. Consider using '#align set.mem_symm_diff Set.mem_symmDiffₓ'. -/
theorem mem_symmDiff : a ∈ s ∆ t ↔ a ∈ s ∧ a ∉ t ∨ a ∈ t ∧ a ∉ s :=
Iff.rfl
#align set.mem_symm_diff Set.mem_symmDiff
/- warning: set.symm_diff_def -> Set.symmDiff_def is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t s))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) t s))
Case conversion may be inaccurate. Consider using '#align set.symm_diff_def Set.symmDiff_defₓ'. -/
protected theorem symmDiff_def (s t : Set α) : s ∆ t = s \ t ∪ t \ s :=
rfl
#align set.symm_diff_def Set.symmDiff_def
/- warning: set.symm_diff_subset_union -> Set.symmDiff_subset_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) s t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.symm_diff_subset_union Set.symmDiff_subset_unionₓ'. -/
theorem symmDiff_subset_union : s ∆ t ⊆ s ∪ t :=
@symmDiff_le_sup (Set α) _ _ _
#align set.symm_diff_subset_union Set.symmDiff_subset_union
/- warning: set.symm_diff_eq_empty -> Set.symmDiff_eq_empty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (Eq.{succ u1} (Set.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Eq.{succ u1} (Set.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) s t) (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (Eq.{succ u1} (Set.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.symm_diff_eq_empty Set.symmDiff_eq_emptyₓ'. -/
@[simp]
theorem symmDiff_eq_empty : s ∆ t = ∅ ↔ s = t :=
symmDiff_eq_bot
#align set.symm_diff_eq_empty Set.symmDiff_eq_empty
/- warning: set.symm_diff_nonempty -> Set.symmDiff_nonempty is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)) (Ne.{succ u1} (Set.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α}, Iff (Set.Nonempty.{u1} α (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) s t)) (Ne.{succ u1} (Set.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.symm_diff_nonempty Set.symmDiff_nonemptyₓ'. -/
@[simp]
theorem symmDiff_nonempty : (s ∆ t).Nonempty ↔ s ≠ t :=
nonempty_iff_ne_empty.trans symmDiff_eq_empty.Not
#align set.symm_diff_nonempty Set.symmDiff_nonempty
/- warning: set.inter_symm_diff_distrib_left -> Set.inter_symmDiff_distrib_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t u)) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) t u)) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u))
Case conversion may be inaccurate. Consider using '#align set.inter_symm_diff_distrib_left Set.inter_symmDiff_distrib_leftₓ'. -/
theorem inter_symmDiff_distrib_left (s t u : Set α) : s ∩ t ∆ u = (s ∩ t) ∆ (s ∩ u) :=
inf_symmDiff_distrib_left _ _ _
#align set.inter_symm_diff_distrib_left Set.inter_symmDiff_distrib_left
/- warning: set.inter_symm_diff_distrib_right -> Set.inter_symmDiff_distrib_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) u) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (u : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) s t) u) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align set.inter_symm_diff_distrib_right Set.inter_symmDiff_distrib_rightₓ'. -/
theorem inter_symmDiff_distrib_right (s t u : Set α) : s ∆ t ∩ u = (s ∩ u) ∆ (t ∩ u) :=
inf_symmDiff_distrib_right _ _ _
#align set.inter_symm_diff_distrib_right Set.inter_symmDiff_distrib_right
/- warning: set.subset_symm_diff_union_symm_diff_left -> Set.subset_symmDiff_union_symmDiff_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) u (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s u) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t u)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) u (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) s u) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) t u)))
Case conversion may be inaccurate. Consider using '#align set.subset_symm_diff_union_symm_diff_left Set.subset_symmDiff_union_symmDiff_leftₓ'. -/
theorem subset_symmDiff_union_symmDiff_left (h : Disjoint s t) : u ⊆ s ∆ u ∪ t ∆ u :=
h.le_symmDiff_sup_symmDiff_left
#align set.subset_symm_diff_union_symm_diff_left Set.subset_symmDiff_union_symmDiff_left
/- warning: set.subset_symm_diff_union_symm_diff_right -> Set.subset_symmDiff_union_symmDiff_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) t u) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toHasSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s u)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) t u) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) s t) (symmDiff.{u1} (Set.{u1} α) (SemilatticeSup.toSup.{u1} (Set.{u1} α) (Lattice.toSemilatticeSup.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (Set.instSDiffSet.{u1} α) s u)))
Case conversion may be inaccurate. Consider using '#align set.subset_symm_diff_union_symm_diff_right Set.subset_symmDiff_union_symmDiff_rightₓ'. -/
theorem subset_symmDiff_union_symmDiff_right (h : Disjoint t u) : s ⊆ s ∆ t ∪ s ∆ u :=
h.le_symmDiff_sup_symmDiff_right
#align set.subset_symm_diff_union_symm_diff_right Set.subset_symmDiff_union_symmDiff_right
/-! ### Powerset -/
#print Set.powerset /-
/-- `𝒫 s = set.powerset s` is the set of all subsets of `s`. -/
def powerset (s : Set α) : Set (Set α) :=
{ t | t ⊆ s }
#align set.powerset Set.powerset
-/
#print Set.mem_powerset /-
theorem mem_powerset {x s : Set α} (h : x ⊆ s) : x ∈ 𝒫 s :=
h
#align set.mem_powerset Set.mem_powerset
-/
#print Set.subset_of_mem_powerset /-
theorem subset_of_mem_powerset {x s : Set α} (h : x ∈ 𝒫 s) : x ⊆ s :=
h
#align set.subset_of_mem_powerset Set.subset_of_mem_powerset
-/
#print Set.mem_powerset_iff /-
@[simp]
theorem mem_powerset_iff (x s : Set α) : x ∈ 𝒫 s ↔ x ⊆ s :=
Iff.rfl
#align set.mem_powerset_iff Set.mem_powerset_iff
-/
/- warning: set.powerset_inter -> Set.powerset_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} (Set.{u1} α)) (Set.powerset.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) (Inter.inter.{u1} (Set.{u1} (Set.{u1} α)) (Set.hasInter.{u1} (Set.{u1} α)) (Set.powerset.{u1} α s) (Set.powerset.{u1} α t))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} (Set.{u1} α)) (Set.powerset.{u1} α (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) (Inter.inter.{u1} (Set.{u1} (Set.{u1} α)) (Set.instInterSet.{u1} (Set.{u1} α)) (Set.powerset.{u1} α s) (Set.powerset.{u1} α t))
Case conversion may be inaccurate. Consider using '#align set.powerset_inter Set.powerset_interₓ'. -/
theorem powerset_inter (s t : Set α) : 𝒫(s ∩ t) = 𝒫 s ∩ 𝒫 t :=
ext fun u => subset_inter_iff
#align set.powerset_inter Set.powerset_inter
#print Set.powerset_mono /-
@[simp]
theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t :=
⟨fun h => h (Subset.refl s), fun h u hu => Subset.trans hu h⟩
#align set.powerset_mono Set.powerset_mono
-/
/- warning: set.monotone_powerset -> Set.monotone_powerset is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}}, Monotone.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (PartialOrder.toPreorder.{u1} (Set.{u1} (Set.{u1} α)) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} (Set.{u1} α)) (Lattice.toSemilatticeInf.{u1} (Set.{u1} (Set.{u1} α)) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} (Set.{u1} α)) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} (Set.{u1} α)) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} (Set.{u1} α)) (Set.booleanAlgebra.{u1} (Set.{u1} α)))))))) (Set.powerset.{u1} α)
but is expected to have type
forall {α : Type.{u1}}, Monotone.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (PartialOrder.toPreorder.{u1} (Set.{u1} (Set.{u1} α)) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} (Set.{u1} α)) (Lattice.toSemilatticeInf.{u1} (Set.{u1} (Set.{u1} α)) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} (Set.{u1} α)) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} (Set.{u1} α)) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} (Set.{u1} α)) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} (Set.{u1} α)) (Set.instBooleanAlgebraSet.{u1} (Set.{u1} α))))))))) (Set.powerset.{u1} α)
Case conversion may be inaccurate. Consider using '#align set.monotone_powerset Set.monotone_powersetₓ'. -/
theorem monotone_powerset : Monotone (powerset : Set α → Set (Set α)) := fun s t => powerset_mono.2
#align set.monotone_powerset Set.monotone_powerset
#print Set.powerset_nonempty /-
@[simp]
theorem powerset_nonempty : (𝒫 s).Nonempty :=
⟨∅, empty_subset s⟩
#align set.powerset_nonempty Set.powerset_nonempty
-/
#print Set.powerset_empty /-
@[simp]
theorem powerset_empty : 𝒫(∅ : Set α) = {∅} :=
ext fun s => subset_empty_iff
#align set.powerset_empty Set.powerset_empty
-/
#print Set.powerset_univ /-
@[simp]
theorem powerset_univ : 𝒫(univ : Set α) = univ :=
eq_univ_of_forall subset_univ
#align set.powerset_univ Set.powerset_univ
-/
#print Set.powerset_singleton /-
/-- The powerset of a singleton contains only `∅` and the singleton itself. -/
theorem powerset_singleton (x : α) : 𝒫({x} : Set α) = {∅, {x}} :=
by
ext y
rw [mem_powerset_iff, subset_singleton_iff_eq, mem_insert_iff, mem_singleton_iff]
#align set.powerset_singleton Set.powerset_singleton
-/
/-! ### Sets defined as an if-then-else -/
#print Set.mem_dite_univ_right /-
theorem mem_dite_univ_right (p : Prop) [Decidable p] (t : p → Set α) (x : α) :
(x ∈ if h : p then t h else univ) ↔ ∀ h : p, x ∈ t h := by split_ifs <;> simp [h]
#align set.mem_dite_univ_right Set.mem_dite_univ_right
-/
#print Set.mem_ite_univ_right /-
@[simp]
theorem mem_ite_univ_right (p : Prop) [Decidable p] (t : Set α) (x : α) :
x ∈ ite p t Set.univ ↔ p → x ∈ t :=
mem_dite_univ_right p (fun _ => t) x
#align set.mem_ite_univ_right Set.mem_ite_univ_right
-/
#print Set.mem_dite_univ_left /-
theorem mem_dite_univ_left (p : Prop) [Decidable p] (t : ¬p → Set α) (x : α) :
(x ∈ if h : p then univ else t h) ↔ ∀ h : ¬p, x ∈ t h := by split_ifs <;> simp [h]
#align set.mem_dite_univ_left Set.mem_dite_univ_left
-/
#print Set.mem_ite_univ_left /-
@[simp]
theorem mem_ite_univ_left (p : Prop) [Decidable p] (t : Set α) (x : α) :
x ∈ ite p Set.univ t ↔ ¬p → x ∈ t :=
mem_dite_univ_left p (fun _ => t) x
#align set.mem_ite_univ_left Set.mem_ite_univ_left
-/
#print Set.mem_dite_empty_right /-
theorem mem_dite_empty_right (p : Prop) [Decidable p] (t : p → Set α) (x : α) :
(x ∈ if h : p then t h else ∅) ↔ ∃ h : p, x ∈ t h := by split_ifs <;> simp [h]
#align set.mem_dite_empty_right Set.mem_dite_empty_right
-/
#print Set.mem_ite_empty_right /-
@[simp]
theorem mem_ite_empty_right (p : Prop) [Decidable p] (t : Set α) (x : α) :
x ∈ ite p t ∅ ↔ p ∧ x ∈ t := by split_ifs <;> simp [h]
#align set.mem_ite_empty_right Set.mem_ite_empty_right
-/
#print Set.mem_dite_empty_left /-
theorem mem_dite_empty_left (p : Prop) [Decidable p] (t : ¬p → Set α) (x : α) :
(x ∈ if h : p then ∅ else t h) ↔ ∃ h : ¬p, x ∈ t h := by split_ifs <;> simp [h]
#align set.mem_dite_empty_left Set.mem_dite_empty_left
-/
#print Set.mem_ite_empty_left /-
@[simp]
theorem mem_ite_empty_left (p : Prop) [Decidable p] (t : Set α) (x : α) :
x ∈ ite p ∅ t ↔ ¬p ∧ x ∈ t := by split_ifs <;> simp [h]
#align set.mem_ite_empty_left Set.mem_ite_empty_left
-/
/-! ### If-then-else for sets -/
#print Set.ite /-
/-- `ite` for sets: `set.ite t s s' ∩ t = s ∩ t`, `set.ite t s s' ∩ tᶜ = s' ∩ tᶜ`.
Defined as `s ∩ t ∪ s' \ t`. -/
protected def ite (t s s' : Set α) : Set α :=
s ∩ t ∪ s' \ t
#align set.ite Set.ite
-/
/- warning: set.ite_inter_self -> Set.ite_inter_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Set.ite.{u1} α t s s') t) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Set.ite.{u1} α t s s') t) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.ite_inter_self Set.ite_inter_selfₓ'. -/
@[simp]
theorem ite_inter_self (t s s' : Set α) : t.ite s s' ∩ t = s ∩ t := by
rw [Set.ite, union_inter_distrib_right, diff_inter_self, inter_assoc, inter_self, union_empty]
#align set.ite_inter_self Set.ite_inter_self
/- warning: set.ite_compl -> Set.ite_compl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t) s s') (Set.ite.{u1} α t s' s)
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t) s s') (Set.ite.{u1} α t s' s)
Case conversion may be inaccurate. Consider using '#align set.ite_compl Set.ite_complₓ'. -/
@[simp]
theorem ite_compl (t s s' : Set α) : tᶜ.ite s s' = t.ite s' s := by
rw [Set.ite, Set.ite, diff_compl, union_comm, diff_eq]
#align set.ite_compl Set.ite_compl
/- warning: set.ite_inter_compl_self -> Set.ite_inter_compl_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Set.ite.{u1} α t s s') (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s' (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) t))
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Set.ite.{u1} α t s s') (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s' (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) t))
Case conversion may be inaccurate. Consider using '#align set.ite_inter_compl_self Set.ite_inter_compl_selfₓ'. -/
@[simp]
theorem ite_inter_compl_self (t s s' : Set α) : t.ite s s' ∩ tᶜ = s' ∩ tᶜ := by
rw [← ite_compl, ite_inter_self]
#align set.ite_inter_compl_self Set.ite_inter_compl_self
/- warning: set.ite_diff_self -> Set.ite_diff_self is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Set.ite.{u1} α t s s') t) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s' t)
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) (Set.ite.{u1} α t s s') t) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s' t)
Case conversion may be inaccurate. Consider using '#align set.ite_diff_self Set.ite_diff_selfₓ'. -/
@[simp]
theorem ite_diff_self (t s s' : Set α) : t.ite s s' \ t = s' \ t :=
ite_inter_compl_self t s s'
#align set.ite_diff_self Set.ite_diff_self
#print Set.ite_same /-
@[simp]
theorem ite_same (t s : Set α) : t.ite s s = s :=
inter_union_diff _ _
#align set.ite_same Set.ite_same
-/
/- warning: set.ite_left -> Set.ite_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α s s t) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α s s t) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.ite_left Set.ite_leftₓ'. -/
@[simp]
theorem ite_left (s t : Set α) : s.ite s t = s ∪ t := by simp [Set.ite]
#align set.ite_left Set.ite_left
/- warning: set.ite_right -> Set.ite_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α s t s) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t s)
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α s t s) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t s)
Case conversion may be inaccurate. Consider using '#align set.ite_right Set.ite_rightₓ'. -/
@[simp]
theorem ite_right (s t : Set α) : s.ite t s = t ∩ s := by simp [Set.ite]
#align set.ite_right Set.ite_right
#print Set.ite_empty /-
@[simp]
theorem ite_empty (s s' : Set α) : Set.ite ∅ s s' = s' := by simp [Set.ite]
#align set.ite_empty Set.ite_empty
-/
#print Set.ite_univ /-
@[simp]
theorem ite_univ (s s' : Set α) : Set.ite univ s s' = s := by simp [Set.ite]
#align set.ite_univ Set.ite_univ
-/
/- warning: set.ite_empty_left -> Set.ite_empty_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α t (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α)) s) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t)
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α t (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α)) s) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.ite_empty_left Set.ite_empty_leftₓ'. -/
@[simp]
theorem ite_empty_left (t s : Set α) : t.ite ∅ s = s \ t := by simp [Set.ite]
#align set.ite_empty_left Set.ite_empty_left
/- warning: set.ite_empty_right -> Set.ite_empty_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α t s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α t s (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.instEmptyCollectionSet.{u1} α))) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align set.ite_empty_right Set.ite_empty_rightₓ'. -/
@[simp]
theorem ite_empty_right (t s : Set α) : t.ite s ∅ = s ∩ t := by simp [Set.ite]
#align set.ite_empty_right Set.ite_empty_right
#print Set.ite_mono /-
theorem ite_mono (t : Set α) {s₁ s₁' s₂ s₂' : Set α} (h : s₁ ⊆ s₂) (h' : s₁' ⊆ s₂') :
t.ite s₁ s₁' ⊆ t.ite s₂ s₂' :=
union_subset_union (inter_subset_inter_left _ h) (inter_subset_inter_left _ h')
#align set.ite_mono Set.ite_mono
-/
/- warning: set.ite_subset_union -> Set.ite_subset_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Set.ite.{u1} α t s s') (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s s')
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Set.ite.{u1} α t s s') (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s s')
Case conversion may be inaccurate. Consider using '#align set.ite_subset_union Set.ite_subset_unionₓ'. -/
theorem ite_subset_union (t s s' : Set α) : t.ite s s' ⊆ s ∪ s' :=
union_subset_union (inter_subset_left _ _) (diff_subset _ _)
#align set.ite_subset_union Set.ite_subset_union
/- warning: set.inter_subset_ite -> Set.inter_subset_ite is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s s') (Set.ite.{u1} α t s s')
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s : Set.{u1} α) (s' : Set.{u1} α), HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s s') (Set.ite.{u1} α t s s')
Case conversion may be inaccurate. Consider using '#align set.inter_subset_ite Set.inter_subset_iteₓ'. -/
theorem inter_subset_ite (t s s' : Set α) : s ∩ s' ⊆ t.ite s s' :=
ite_same t (s ∩ s') ▸ ite_mono _ (inter_subset_left _ _) (inter_subset_right _ _)
#align set.inter_subset_ite Set.inter_subset_ite
/- warning: set.ite_inter_inter -> Set.ite_inter_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₁' : Set.{u1} α) (s₂' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α t (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ s₂) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁' s₂')) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Set.ite.{u1} α t s₁ s₁') (Set.ite.{u1} α t s₂ s₂'))
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s₁' : Set.{u1} α) (s₂' : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α t (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ s₂) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁' s₂')) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Set.ite.{u1} α t s₁ s₁') (Set.ite.{u1} α t s₂ s₂'))
Case conversion may be inaccurate. Consider using '#align set.ite_inter_inter Set.ite_inter_interₓ'. -/
theorem ite_inter_inter (t s₁ s₂ s₁' s₂' : Set α) :
t.ite (s₁ ∩ s₂) (s₁' ∩ s₂') = t.ite s₁ s₁' ∩ t.ite s₂ s₂' :=
by
ext x
simp only [Set.ite, Set.mem_inter_iff, Set.mem_diff, Set.mem_union]
itauto
#align set.ite_inter_inter Set.ite_inter_inter
/- warning: set.ite_inter -> Set.ite_inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α t (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ s) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₂ s)) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Set.ite.{u1} α t s₁ s₂) s)
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) (s₁ : Set.{u1} α) (s₂ : Set.{u1} α) (s : Set.{u1} α), Eq.{succ u1} (Set.{u1} α) (Set.ite.{u1} α t (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ s) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₂ s)) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Set.ite.{u1} α t s₁ s₂) s)
Case conversion may be inaccurate. Consider using '#align set.ite_inter Set.ite_interₓ'. -/
theorem ite_inter (t s₁ s₂ s : Set α) : t.ite (s₁ ∩ s) (s₂ ∩ s) = t.ite s₁ s₂ ∩ s := by
rw [ite_inter_inter, ite_same]
#align set.ite_inter Set.ite_inter
/- warning: set.ite_inter_of_inter_eq -> Set.ite_inter_of_inter_eq is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (t : Set.{u1} α) {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {s : Set.{u1} α}, (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ s) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₂ s)) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (Set.ite.{u1} α t s₁ s₂) s) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s₁ s))
but is expected to have type
forall {α : Type.{u1}} (t : Set.{u1} α) {s₁ : Set.{u1} α} {s₂ : Set.{u1} α} {s : Set.{u1} α}, (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ s) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₂ s)) -> (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (Set.ite.{u1} α t s₁ s₂) s) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s₁ s))
Case conversion may be inaccurate. Consider using '#align set.ite_inter_of_inter_eq Set.ite_inter_of_inter_eqₓ'. -/
theorem ite_inter_of_inter_eq (t : Set α) {s₁ s₂ s : Set α} (h : s₁ ∩ s = s₂ ∩ s) :
t.ite s₁ s₂ ∩ s = s₁ ∩ s := by rw [← ite_inter, ← h, ite_same]
#align set.ite_inter_of_inter_eq Set.ite_inter_of_inter_eq
/- warning: set.subset_ite -> Set.subset_ite is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {t : Set.{u1} α} {s : Set.{u1} α} {s' : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) u (Set.ite.{u1} α t s s')) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) u t) s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) u t) s'))
but is expected to have type
forall {α : Type.{u1}} {t : Set.{u1} α} {s : Set.{u1} α} {s' : Set.{u1} α} {u : Set.{u1} α}, Iff (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) u (Set.ite.{u1} α t s s')) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) u t) s) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) u t) s'))
Case conversion may be inaccurate. Consider using '#align set.subset_ite Set.subset_iteₓ'. -/
theorem subset_ite {t s s' u : Set α} : u ⊆ t.ite s s' ↔ u ∩ t ⊆ s ∧ u \ t ⊆ s' :=
by
simp only [subset_def, ← forall_and]
refine' forall_congr' fun x => _
by_cases hx : x ∈ t <;> simp [*, Set.ite]
#align set.subset_ite Set.subset_ite
/-! ### Subsingleton -/
#print Set.Subsingleton /-
/-- A set `s` is a `subsingleton` if it has at most one element. -/
protected def Subsingleton (s : Set α) : Prop :=
∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y
#align set.subsingleton Set.Subsingleton
-/
#print Set.Subsingleton.anti /-
theorem Subsingleton.anti (ht : t.Subsingleton) (hst : s ⊆ t) : s.Subsingleton := fun x hx y hy =>
ht (hst hx) (hst hy)
#align set.subsingleton.anti Set.Subsingleton.anti
-/
#print Set.Subsingleton.eq_singleton_of_mem /-
theorem Subsingleton.eq_singleton_of_mem (hs : s.Subsingleton) {x : α} (hx : x ∈ s) : s = {x} :=
ext fun y => ⟨fun hy => hs hx hy ▸ mem_singleton _, fun hy => (eq_of_mem_singleton hy).symm ▸ hx⟩
#align set.subsingleton.eq_singleton_of_mem Set.Subsingleton.eq_singleton_of_mem
-/
#print Set.subsingleton_empty /-
@[simp]
theorem subsingleton_empty : (∅ : Set α).Subsingleton := fun x => False.elim
#align set.subsingleton_empty Set.subsingleton_empty
-/
#print Set.subsingleton_singleton /-
@[simp]
theorem subsingleton_singleton {a} : ({a} : Set α).Subsingleton := fun x hx y hy =>
(eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl
#align set.subsingleton_singleton Set.subsingleton_singleton
-/
#print Set.subsingleton_of_subset_singleton /-
theorem subsingleton_of_subset_singleton (h : s ⊆ {a}) : s.Subsingleton :=
subsingleton_singleton.anti h
#align set.subsingleton_of_subset_singleton Set.subsingleton_of_subset_singleton
-/
#print Set.subsingleton_of_forall_eq /-
theorem subsingleton_of_forall_eq (a : α) (h : ∀ b ∈ s, b = a) : s.Subsingleton := fun b hb c hc =>
(h _ hb).trans (h _ hc).symm
#align set.subsingleton_of_forall_eq Set.subsingleton_of_forall_eq
-/
#print Set.subsingleton_iff_singleton /-
theorem subsingleton_iff_singleton {x} (hx : x ∈ s) : s.Subsingleton ↔ s = {x} :=
⟨fun h => h.eq_singleton_of_mem hx, fun h => h.symm ▸ subsingleton_singleton⟩
#align set.subsingleton_iff_singleton Set.subsingleton_iff_singleton
-/
#print Set.Subsingleton.eq_empty_or_singleton /-
theorem Subsingleton.eq_empty_or_singleton (hs : s.Subsingleton) : s = ∅ ∨ ∃ x, s = {x} :=
s.eq_empty_or_nonempty.elim Or.inl fun ⟨x, hx⟩ => Or.inr ⟨x, hs.eq_singleton_of_mem hx⟩
#align set.subsingleton.eq_empty_or_singleton Set.Subsingleton.eq_empty_or_singleton
-/
#print Set.Subsingleton.induction_on /-
theorem Subsingleton.induction_on {p : Set α → Prop} (hs : s.Subsingleton) (he : p ∅)
(h₁ : ∀ x, p {x}) : p s :=
by
rcases hs.eq_empty_or_singleton with (rfl | ⟨x, rfl⟩)
exacts[he, h₁ _]
#align set.subsingleton.induction_on Set.Subsingleton.induction_on
-/
#print Set.subsingleton_univ /-
theorem subsingleton_univ [Subsingleton α] : (univ : Set α).Subsingleton := fun x hx y hy =>
Subsingleton.elim x y
#align set.subsingleton_univ Set.subsingleton_univ
-/
#print Set.subsingleton_of_univ_subsingleton /-
theorem subsingleton_of_univ_subsingleton (h : (univ : Set α).Subsingleton) : Subsingleton α :=
⟨fun a b => h (mem_univ a) (mem_univ b)⟩
#align set.subsingleton_of_univ_subsingleton Set.subsingleton_of_univ_subsingleton
-/
#print Set.subsingleton_univ_iff /-
@[simp]
theorem subsingleton_univ_iff : (univ : Set α).Subsingleton ↔ Subsingleton α :=
⟨subsingleton_of_univ_subsingleton, fun h => @subsingleton_univ _ h⟩
#align set.subsingleton_univ_iff Set.subsingleton_univ_iff
-/
#print Set.subsingleton_of_subsingleton /-
theorem subsingleton_of_subsingleton [Subsingleton α] {s : Set α} : Set.Subsingleton s :=
subsingleton_univ.anti (subset_univ s)
#align set.subsingleton_of_subsingleton Set.subsingleton_of_subsingleton
-/
#print Set.subsingleton_isTop /-
theorem subsingleton_isTop (α : Type _) [PartialOrder α] : Set.Subsingleton { x : α | IsTop x } :=
fun x hx y hy => hx.IsMax.eq_of_le (hy x)
#align set.subsingleton_is_top Set.subsingleton_isTop
-/
#print Set.subsingleton_isBot /-
theorem subsingleton_isBot (α : Type _) [PartialOrder α] : Set.Subsingleton { x : α | IsBot x } :=
fun x hx y hy => hx.IsMin.eq_of_ge (hy x)
#align set.subsingleton_is_bot Set.subsingleton_isBot
-/
#print Set.exists_eq_singleton_iff_nonempty_subsingleton /-
theorem exists_eq_singleton_iff_nonempty_subsingleton :
(∃ a : α, s = {a}) ↔ s.Nonempty ∧ s.Subsingleton :=
by
refine' ⟨_, fun h => _⟩
· rintro ⟨a, rfl⟩
exact ⟨singleton_nonempty a, subsingleton_singleton⟩
· exact h.2.eq_empty_or_singleton.resolve_left h.1.ne_empty
#align set.exists_eq_singleton_iff_nonempty_subsingleton Set.exists_eq_singleton_iff_nonempty_subsingleton
-/
#print Set.subsingleton_coe /-
/-- `s`, coerced to a type, is a subsingleton type if and only if `s` is a subsingleton set. -/
@[simp, norm_cast]
theorem subsingleton_coe (s : Set α) : Subsingleton s ↔ s.Subsingleton :=
by
constructor
· refine' fun h => fun a ha b hb => _
exact SetCoe.ext_iff.2 (@Subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩)
· exact fun h => Subsingleton.intro fun a b => SetCoe.ext (h a.property b.property)
#align set.subsingleton_coe Set.subsingleton_coe
-/
#print Set.Subsingleton.coe_sort /-
theorem Subsingleton.coe_sort {s : Set α} : s.Subsingleton → Subsingleton s :=
s.subsingleton_coe.2
#align set.subsingleton.coe_sort Set.Subsingleton.coe_sort
-/
#print Set.subsingleton_coe_of_subsingleton /-
/-- The `coe_sort` of a set `s` in a subsingleton type is a subsingleton.
For the corresponding result for `subtype`, see `subtype.subsingleton`. -/
instance subsingleton_coe_of_subsingleton [Subsingleton α] {s : Set α} : Subsingleton s :=
by
rw [s.subsingleton_coe]
exact subsingleton_of_subsingleton
#align set.subsingleton_coe_of_subsingleton Set.subsingleton_coe_of_subsingleton
-/
/-! ### Nontrivial -/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (x y «expr ∈ » s) -/
#print Set.Nontrivial /-
/-- A set `s` is `nontrivial` if it has at least two distinct elements. -/
protected def Nontrivial (s : Set α) : Prop :=
∃ (x : _)(_ : x ∈ s)(y : _)(_ : y ∈ s), x ≠ y
#align set.nontrivial Set.Nontrivial
-/
#print Set.nontrivial_of_mem_mem_ne /-
theorem nontrivial_of_mem_mem_ne {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : s.Nontrivial :=
⟨x, hx, y, hy, hxy⟩
#align set.nontrivial_of_mem_mem_ne Set.nontrivial_of_mem_mem_ne
-/
#print Set.Nontrivial.choose /-
/-- Extract witnesses from s.nontrivial. This function might be used instead of case analysis on the
argument. Note that it makes a proof depend on the classical.choice axiom. -/
protected noncomputable def Nontrivial.choose (hs : s.Nontrivial) : α × α :=
(hs.some, hs.choose_spec.choose_spec.some)
#align set.nontrivial.some Set.Nontrivial.choose
-/
#print Set.Nontrivial.choose_fst_mem /-
protected theorem Nontrivial.choose_fst_mem (hs : s.Nontrivial) : hs.some.fst ∈ s :=
hs.choose_spec.some
#align set.nontrivial.some_fst_mem Set.Nontrivial.choose_fst_mem
-/
#print Set.Nontrivial.choose_snd_mem /-
protected theorem Nontrivial.choose_snd_mem (hs : s.Nontrivial) : hs.some.snd ∈ s :=
hs.choose_spec.choose_spec.choose_spec.some
#align set.nontrivial.some_snd_mem Set.Nontrivial.choose_snd_mem
-/
#print Set.Nontrivial.choose_fst_ne_choose_snd /-
protected theorem Nontrivial.choose_fst_ne_choose_snd (hs : s.Nontrivial) :
hs.some.fst ≠ hs.some.snd :=
hs.choose_spec.choose_spec.choose_spec.choose_spec
#align set.nontrivial.some_fst_ne_some_snd Set.Nontrivial.choose_fst_ne_choose_snd
-/
#print Set.Nontrivial.mono /-
theorem Nontrivial.mono (hs : s.Nontrivial) (hst : s ⊆ t) : t.Nontrivial :=
let ⟨x, hx, y, hy, hxy⟩ := hs
⟨x, hst hx, y, hst hy, hxy⟩
#align set.nontrivial.mono Set.Nontrivial.mono
-/
#print Set.nontrivial_pair /-
theorem nontrivial_pair {x y} (hxy : x ≠ y) : ({x, y} : Set α).Nontrivial :=
⟨x, mem_insert _ _, y, mem_insert_of_mem _ (mem_singleton _), hxy⟩
#align set.nontrivial_pair Set.nontrivial_pair
-/
#print Set.nontrivial_of_pair_subset /-
theorem nontrivial_of_pair_subset {x y} (hxy : x ≠ y) (h : {x, y} ⊆ s) : s.Nontrivial :=
(nontrivial_pair hxy).mono h
#align set.nontrivial_of_pair_subset Set.nontrivial_of_pair_subset
-/
#print Set.Nontrivial.pair_subset /-
theorem Nontrivial.pair_subset (hs : s.Nontrivial) : ∃ (x y : _)(hab : x ≠ y), {x, y} ⊆ s :=
let ⟨x, hx, y, hy, hxy⟩ := hs
⟨x, y, hxy, insert_subset.2 ⟨hx, singleton_subset_iff.2 hy⟩⟩
#align set.nontrivial.pair_subset Set.Nontrivial.pair_subset
-/
#print Set.nontrivial_iff_pair_subset /-
theorem nontrivial_iff_pair_subset : s.Nontrivial ↔ ∃ (x y : _)(hxy : x ≠ y), {x, y} ⊆ s :=
⟨Nontrivial.pair_subset, fun H =>
let ⟨x, y, hxy, h⟩ := H
nontrivial_of_pair_subset hxy h⟩
#align set.nontrivial_iff_pair_subset Set.nontrivial_iff_pair_subset
-/
/- warning: set.nontrivial_of_exists_ne -> Set.nontrivial_of_exists_ne is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (Exists.{succ u1} α (fun (y : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y s) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y s) => Ne.{succ u1} α y x))) -> (Set.Nontrivial.{u1} α s)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) -> (Exists.{succ u1} α (fun (y : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) y s) (Ne.{succ u1} α y x))) -> (Set.Nontrivial.{u1} α s)
Case conversion may be inaccurate. Consider using '#align set.nontrivial_of_exists_ne Set.nontrivial_of_exists_neₓ'. -/
theorem nontrivial_of_exists_ne {x} (hx : x ∈ s) (h : ∃ y ∈ s, y ≠ x) : s.Nontrivial :=
let ⟨y, hy, hyx⟩ := h
⟨y, hy, x, hx, hyx⟩
#align set.nontrivial_of_exists_ne Set.nontrivial_of_exists_ne
/- warning: set.nontrivial.exists_ne -> Set.Nontrivial.exists_ne is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α}, (Set.Nontrivial.{u1} α s) -> (forall (z : α), Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) => Ne.{succ u1} α x z)))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α}, (Set.Nontrivial.{u1} α s) -> (forall (z : α), Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (Ne.{succ u1} α x z)))
Case conversion may be inaccurate. Consider using '#align set.nontrivial.exists_ne Set.Nontrivial.exists_neₓ'. -/
theorem Nontrivial.exists_ne (hs : s.Nontrivial) (z) : ∃ x ∈ s, x ≠ z :=
by
by_contra H; push_neg at H
rcases hs with ⟨x, hx, y, hy, hxy⟩
rw [H x hx, H y hy] at hxy
exact hxy rfl
#align set.nontrivial.exists_ne Set.Nontrivial.exists_ne
/- warning: set.nontrivial_iff_exists_ne -> Set.nontrivial_iff_exists_ne is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (Iff (Set.Nontrivial.{u1} α s) (Exists.{succ u1} α (fun (y : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y s) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y s) => Ne.{succ u1} α y x))))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {x : α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) -> (Iff (Set.Nontrivial.{u1} α s) (Exists.{succ u1} α (fun (y : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) y s) (Ne.{succ u1} α y x))))
Case conversion may be inaccurate. Consider using '#align set.nontrivial_iff_exists_ne Set.nontrivial_iff_exists_neₓ'. -/
theorem nontrivial_iff_exists_ne {x} (hx : x ∈ s) : s.Nontrivial ↔ ∃ y ∈ s, y ≠ x :=
⟨fun H => H.exists_ne _, nontrivial_of_exists_ne hx⟩
#align set.nontrivial_iff_exists_ne Set.nontrivial_iff_exists_ne
#print Set.nontrivial_of_lt /-
theorem nontrivial_of_lt [Preorder α] {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x < y) :
s.Nontrivial :=
⟨x, hx, y, hy, ne_of_lt hxy⟩
#align set.nontrivial_of_lt Set.nontrivial_of_lt
-/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (x y «expr ∈ » s) -/
#print Set.nontrivial_of_exists_lt /-
theorem nontrivial_of_exists_lt [Preorder α] (H : ∃ (x : _)(_ : x ∈ s)(y : _)(_ : y ∈ s), x < y) :
s.Nontrivial :=
let ⟨x, hx, y, hy, hxy⟩ := H
nontrivial_of_lt hx hy hxy
#align set.nontrivial_of_exists_lt Set.nontrivial_of_exists_lt
-/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (x y «expr ∈ » s) -/
#print Set.Nontrivial.exists_lt /-
theorem Nontrivial.exists_lt [LinearOrder α] (hs : s.Nontrivial) :
∃ (x : _)(_ : x ∈ s)(y : _)(_ : y ∈ s), x < y :=
let ⟨x, hx, y, hy, hxy⟩ := hs
Or.elim (lt_or_gt_of_ne hxy) (fun H => ⟨x, hx, y, hy, H⟩) fun H => ⟨y, hy, x, hx, H⟩
#align set.nontrivial.exists_lt Set.Nontrivial.exists_lt
-/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (x y «expr ∈ » s) -/
#print Set.nontrivial_iff_exists_lt /-
theorem nontrivial_iff_exists_lt [LinearOrder α] :
s.Nontrivial ↔ ∃ (x : _)(_ : x ∈ s)(y : _)(_ : y ∈ s), x < y :=
⟨Nontrivial.exists_lt, nontrivial_of_exists_lt⟩
#align set.nontrivial_iff_exists_lt Set.nontrivial_iff_exists_lt
-/
#print Set.Nontrivial.nonempty /-
protected theorem Nontrivial.nonempty (hs : s.Nontrivial) : s.Nonempty :=
let ⟨x, hx, _⟩ := hs
⟨x, hx⟩
#align set.nontrivial.nonempty Set.Nontrivial.nonempty
-/
#print Set.Nontrivial.ne_empty /-
protected theorem Nontrivial.ne_empty (hs : s.Nontrivial) : s ≠ ∅ :=
hs.Nonempty.ne_empty
#align set.nontrivial.ne_empty Set.Nontrivial.ne_empty
-/
#print Set.Nontrivial.not_subset_empty /-
theorem Nontrivial.not_subset_empty (hs : s.Nontrivial) : ¬s ⊆ ∅ :=
hs.Nonempty.not_subset_empty
#align set.nontrivial.not_subset_empty Set.Nontrivial.not_subset_empty
-/
#print Set.not_nontrivial_empty /-
@[simp]
theorem not_nontrivial_empty : ¬(∅ : Set α).Nontrivial := fun h => h.ne_empty rfl
#align set.not_nontrivial_empty Set.not_nontrivial_empty
-/
#print Set.not_nontrivial_singleton /-
@[simp]
theorem not_nontrivial_singleton {x} : ¬({x} : Set α).Nontrivial := fun H =>
by
rw [nontrivial_iff_exists_ne (mem_singleton x)] at H
exact
let ⟨y, hy, hya⟩ := H
hya (mem_singleton_iff.1 hy)
#align set.not_nontrivial_singleton Set.not_nontrivial_singleton
-/
#print Set.Nontrivial.ne_singleton /-
theorem Nontrivial.ne_singleton {x} (hs : s.Nontrivial) : s ≠ {x} := fun H =>
by
rw [H] at hs
exact not_nontrivial_singleton hs
#align set.nontrivial.ne_singleton Set.Nontrivial.ne_singleton
-/
#print Set.Nontrivial.not_subset_singleton /-
theorem Nontrivial.not_subset_singleton {x} (hs : s.Nontrivial) : ¬s ⊆ {x} :=
(not_congr subset_singleton_iff_eq).2 (not_or_of_not hs.ne_empty hs.ne_singleton)
#align set.nontrivial.not_subset_singleton Set.Nontrivial.not_subset_singleton
-/
#print Set.nontrivial_univ /-
theorem nontrivial_univ [Nontrivial α] : (univ : Set α).Nontrivial :=
let ⟨x, y, hxy⟩ := exists_pair_ne α
⟨x, mem_univ _, y, mem_univ _, hxy⟩
#align set.nontrivial_univ Set.nontrivial_univ
-/
#print Set.nontrivial_of_univ_nontrivial /-
theorem nontrivial_of_univ_nontrivial (h : (univ : Set α).Nontrivial) : Nontrivial α :=
let ⟨x, _, y, _, hxy⟩ := h
⟨⟨x, y, hxy⟩⟩
#align set.nontrivial_of_univ_nontrivial Set.nontrivial_of_univ_nontrivial
-/
#print Set.nontrivial_univ_iff /-
@[simp]
theorem nontrivial_univ_iff : (univ : Set α).Nontrivial ↔ Nontrivial α :=
⟨nontrivial_of_univ_nontrivial, fun h => @nontrivial_univ _ h⟩
#align set.nontrivial_univ_iff Set.nontrivial_univ_iff
-/
#print Set.nontrivial_of_nontrivial /-
theorem nontrivial_of_nontrivial (hs : s.Nontrivial) : Nontrivial α :=
let ⟨x, _, y, _, hxy⟩ := hs
⟨⟨x, y, hxy⟩⟩
#align set.nontrivial_of_nontrivial Set.nontrivial_of_nontrivial
-/
#print Set.nontrivial_coe_sort /-
/-- `s`, coerced to a type, is a nontrivial type if and only if `s` is a nontrivial set. -/
@[simp, norm_cast]
theorem nontrivial_coe_sort {s : Set α} : Nontrivial s ↔ s.Nontrivial := by
simp_rw [← nontrivial_univ_iff, Set.Nontrivial, mem_univ, exists_true_left, SetCoe.exists,
Subtype.mk_eq_mk]
#align set.nontrivial_coe_sort Set.nontrivial_coe_sort
-/
alias nontrivial_coe_sort ↔ _ nontrivial.coe_sort
#align set.nontrivial.coe_sort Set.Nontrivial.coe_sort
#print Set.nontrivial_of_nontrivial_coe /-
/-- A type with a set `s` whose `coe_sort` is a nontrivial type is nontrivial.
For the corresponding result for `subtype`, see `subtype.nontrivial_iff_exists_ne`. -/
theorem nontrivial_of_nontrivial_coe (hs : Nontrivial s) : Nontrivial α :=
nontrivial_of_nontrivial <| nontrivial_coe_sort.1 hs
#align set.nontrivial_of_nontrivial_coe Set.nontrivial_of_nontrivial_coe
-/
#print Set.nontrivial_mono /-
theorem nontrivial_mono {α : Type _} {s t : Set α} (hst : s ⊆ t) (hs : Nontrivial s) :
Nontrivial t :=
Nontrivial.coe_sort <| (nontrivial_coe_sort.1 hs).mono hst
#align set.nontrivial_mono Set.nontrivial_mono
-/
#print Set.not_subsingleton_iff /-
@[simp]
theorem not_subsingleton_iff : ¬s.Subsingleton ↔ s.Nontrivial := by
simp_rw [Set.Subsingleton, Set.Nontrivial, not_forall]
#align set.not_subsingleton_iff Set.not_subsingleton_iff
-/
#print Set.not_nontrivial_iff /-
@[simp]
theorem not_nontrivial_iff : ¬s.Nontrivial ↔ s.Subsingleton :=
Iff.not_left not_subsingleton_iff.symm
#align set.not_nontrivial_iff Set.not_nontrivial_iff
-/
alias not_nontrivial_iff ↔ _ subsingleton.not_nontrivial
#align set.subsingleton.not_nontrivial Set.Subsingleton.not_nontrivial
alias not_subsingleton_iff ↔ _ nontrivial.not_subsingleton
#align set.nontrivial.not_subsingleton Set.Nontrivial.not_subsingleton
#print Set.subsingleton_or_nontrivial /-
protected theorem subsingleton_or_nontrivial (s : Set α) : s.Subsingleton ∨ s.Nontrivial := by
simp [or_iff_not_imp_right]
#align set.subsingleton_or_nontrivial Set.subsingleton_or_nontrivial
-/
#print Set.eq_singleton_or_nontrivial /-
theorem eq_singleton_or_nontrivial (ha : a ∈ s) : s = {a} ∨ s.Nontrivial :=
by
rw [← subsingleton_iff_singleton ha]
exact s.subsingleton_or_nontrivial
#align set.eq_singleton_or_nontrivial Set.eq_singleton_or_nontrivial
-/
#print Set.nontrivial_iff_ne_singleton /-
theorem nontrivial_iff_ne_singleton (ha : a ∈ s) : s.Nontrivial ↔ s ≠ {a} :=
⟨Nontrivial.ne_singleton, (eq_singleton_or_nontrivial ha).resolve_left⟩
#align set.nontrivial_iff_ne_singleton Set.nontrivial_iff_ne_singleton
-/
#print Set.Nonempty.exists_eq_singleton_or_nontrivial /-
theorem Nonempty.exists_eq_singleton_or_nontrivial : s.Nonempty → (∃ a, s = {a}) ∨ s.Nontrivial :=
fun ⟨a, ha⟩ => (eq_singleton_or_nontrivial ha).imp_left <| Exists.intro a
#align set.nonempty.exists_eq_singleton_or_nontrivial Set.Nonempty.exists_eq_singleton_or_nontrivial
-/
#print Set.univ_eq_true_false /-
theorem univ_eq_true_false : univ = ({True, False} : Set Prop) :=
Eq.symm <| eq_univ_of_forall <| Classical.cases (by simp) (by simp)
#align set.univ_eq_true_false Set.univ_eq_true_false
-/
section Preorder
variable [Preorder α] [Preorder β] {f : α → β}
#print Set.monotoneOn_iff_monotone /-
theorem monotoneOn_iff_monotone : MonotoneOn f s ↔ Monotone fun a : s => f a := by
simp [Monotone, MonotoneOn]
#align set.monotone_on_iff_monotone Set.monotoneOn_iff_monotone
-/
#print Set.antitoneOn_iff_antitone /-
theorem antitoneOn_iff_antitone : AntitoneOn f s ↔ Antitone fun a : s => f a := by
simp [Antitone, AntitoneOn]
#align set.antitone_on_iff_antitone Set.antitoneOn_iff_antitone
-/
#print Set.strictMonoOn_iff_strictMono /-
theorem strictMonoOn_iff_strictMono : StrictMonoOn f s ↔ StrictMono fun a : s => f a := by
simp [StrictMono, StrictMonoOn]
#align set.strict_mono_on_iff_strict_mono Set.strictMonoOn_iff_strictMono
-/
#print Set.strictAntiOn_iff_strictAnti /-
theorem strictAntiOn_iff_strictAnti : StrictAntiOn f s ↔ StrictAnti fun a : s => f a := by
simp [StrictAnti, StrictAntiOn]
#align set.strict_anti_on_iff_strict_anti Set.strictAntiOn_iff_strictAnti
-/
variable (f)
/-! ### Monotonicity on singletons -/
#print Set.Subsingleton.monotoneOn /-
protected theorem Subsingleton.monotoneOn (h : s.Subsingleton) : MonotoneOn f s :=
fun a ha b hb _ => (congr_arg _ (h ha hb)).le
#align set.subsingleton.monotone_on Set.Subsingleton.monotoneOn
-/
#print Set.Subsingleton.antitoneOn /-
protected theorem Subsingleton.antitoneOn (h : s.Subsingleton) : AntitoneOn f s :=
fun a ha b hb _ => (congr_arg _ (h hb ha)).le
#align set.subsingleton.antitone_on Set.Subsingleton.antitoneOn
-/
#print Set.Subsingleton.strictMonoOn /-
protected theorem Subsingleton.strictMonoOn (h : s.Subsingleton) : StrictMonoOn f s :=
fun a ha b hb hlt => (hlt.Ne (h ha hb)).elim
#align set.subsingleton.strict_mono_on Set.Subsingleton.strictMonoOn
-/
#print Set.Subsingleton.strictAntiOn /-
protected theorem Subsingleton.strictAntiOn (h : s.Subsingleton) : StrictAntiOn f s :=
fun a ha b hb hlt => (hlt.Ne (h ha hb)).elim
#align set.subsingleton.strict_anti_on Set.Subsingleton.strictAntiOn
-/
#print Set.monotoneOn_singleton /-
@[simp]
theorem monotoneOn_singleton : MonotoneOn f {a} :=
subsingleton_singleton.MonotoneOn f
#align set.monotone_on_singleton Set.monotoneOn_singleton
-/
#print Set.antitoneOn_singleton /-
@[simp]
theorem antitoneOn_singleton : AntitoneOn f {a} :=
subsingleton_singleton.AntitoneOn f
#align set.antitone_on_singleton Set.antitoneOn_singleton
-/
#print Set.strictMonoOn_singleton /-
@[simp]
theorem strictMonoOn_singleton : StrictMonoOn f {a} :=
subsingleton_singleton.StrictMonoOn f
#align set.strict_mono_on_singleton Set.strictMonoOn_singleton
-/
#print Set.strictAntiOn_singleton /-
@[simp]
theorem strictAntiOn_singleton : StrictAntiOn f {a} :=
subsingleton_singleton.StrictAntiOn f
#align set.strict_anti_on_singleton Set.strictAntiOn_singleton
-/
end Preorder
section LinearOrder
variable [LinearOrder α] [LinearOrder β] {f : α → β}
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (a b c «expr ∈ » s) -/
#print Set.not_monotoneOn_not_antitoneOn_iff_exists_le_le /-
/-- A function between linear orders which is neither monotone nor antitone makes a dent upright or
downright. -/
theorem not_monotoneOn_not_antitoneOn_iff_exists_le_le :
¬MonotoneOn f s ∧ ¬AntitoneOn f s ↔
∃ (a : _)(_ : a ∈ s)(b : _)(_ : b ∈ s)(c : _)(_ : c ∈ s),
a ≤ b ∧ b ≤ c ∧ (f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) :=
by
simp [monotone_on_iff_monotone, antitone_on_iff_antitone, and_assoc', exists_and_left,
not_monotone_not_antitone_iff_exists_le_le, @and_left_comm (_ ∈ s)]
#align set.not_monotone_on_not_antitone_on_iff_exists_le_le Set.not_monotoneOn_not_antitoneOn_iff_exists_le_le
-/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (a b c «expr ∈ » s) -/
#print Set.not_monotoneOn_not_antitoneOn_iff_exists_lt_lt /-
/-- A function between linear orders which is neither monotone nor antitone makes a dent upright or
downright. -/
theorem not_monotoneOn_not_antitoneOn_iff_exists_lt_lt :
¬MonotoneOn f s ∧ ¬AntitoneOn f s ↔
∃ (a : _)(_ : a ∈ s)(b : _)(_ : b ∈ s)(c : _)(_ : c ∈ s),
a < b ∧ b < c ∧ (f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) :=
by
simp [monotone_on_iff_monotone, antitone_on_iff_antitone, and_assoc', exists_and_left,
not_monotone_not_antitone_iff_exists_lt_lt, @and_left_comm (_ ∈ s)]
#align set.not_monotone_on_not_antitone_on_iff_exists_lt_lt Set.not_monotoneOn_not_antitoneOn_iff_exists_lt_lt
-/
end LinearOrder
end Set
open Set
namespace Function
variable {ι : Sort _} {α : Type _} {β : Type _} {f : α → β}
/- warning: function.injective.nonempty_apply_iff -> Function.Injective.nonempty_apply_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {f : (Set.{u1} α) -> (Set.{u2} β)}, (Function.Injective.{succ u1, succ u2} (Set.{u1} α) (Set.{u2} β) f) -> (Eq.{succ u2} (Set.{u2} β) (f (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) (EmptyCollection.emptyCollection.{u2} (Set.{u2} β) (Set.hasEmptyc.{u2} β))) -> (forall {s : Set.{u1} α}, Iff (Set.Nonempty.{u2} β (f s)) (Set.Nonempty.{u1} α s))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {f : (Set.{u2} α) -> (Set.{u1} β)}, (Function.Injective.{succ u2, succ u1} (Set.{u2} α) (Set.{u1} β) f) -> (Eq.{succ u1} (Set.{u1} β) (f (EmptyCollection.emptyCollection.{u2} (Set.{u2} α) (Set.instEmptyCollectionSet.{u2} α))) (EmptyCollection.emptyCollection.{u1} (Set.{u1} β) (Set.instEmptyCollectionSet.{u1} β))) -> (forall {s : Set.{u2} α}, Iff (Set.Nonempty.{u1} β (f s)) (Set.Nonempty.{u2} α s))
Case conversion may be inaccurate. Consider using '#align function.injective.nonempty_apply_iff Function.Injective.nonempty_apply_iffₓ'. -/
theorem Injective.nonempty_apply_iff {f : Set α → Set β} (hf : Injective f) (h2 : f ∅ = ∅)
{s : Set α} : (f s).Nonempty ↔ s.Nonempty := by
rw [nonempty_iff_ne_empty, ← h2, nonempty_iff_ne_empty, hf.ne_iff]
#align function.injective.nonempty_apply_iff Function.Injective.nonempty_apply_iff
end Function
open Function
namespace Set
/-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/
section Inclusion
variable {α : Type _} {s t u : Set α}
#print Set.inclusion /-
/-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/
def inclusion (h : s ⊆ t) : s → t := fun x : s => (⟨x, h x.2⟩ : t)
#align set.inclusion Set.inclusion
-/
#print Set.inclusion_self /-
@[simp]
theorem inclusion_self (x : s) : inclusion Subset.rfl x = x :=
by
cases x
rfl
#align set.inclusion_self Set.inclusion_self
-/
#print Set.inclusion_eq_id /-
theorem inclusion_eq_id (h : s ⊆ s) : inclusion h = id :=
funext inclusion_self
#align set.inclusion_eq_id Set.inclusion_eq_id
-/
#print Set.inclusion_mk /-
@[simp]
theorem inclusion_mk {h : s ⊆ t} (a : α) (ha : a ∈ s) : inclusion h ⟨a, ha⟩ = ⟨a, h ha⟩ :=
rfl
#align set.inclusion_mk Set.inclusion_mk
-/
#print Set.inclusion_right /-
theorem inclusion_right (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) : inclusion h ⟨x, m⟩ = x :=
by
cases x
rfl
#align set.inclusion_right Set.inclusion_right
-/
#print Set.inclusion_inclusion /-
@[simp]
theorem inclusion_inclusion (hst : s ⊆ t) (htu : t ⊆ u) (x : s) :
inclusion htu (inclusion hst x) = inclusion (hst.trans htu) x :=
by
cases x
rfl
#align set.inclusion_inclusion Set.inclusion_inclusion
-/
#print Set.inclusion_comp_inclusion /-
@[simp]
theorem inclusion_comp_inclusion {α} {s t u : Set α} (hst : s ⊆ t) (htu : t ⊆ u) :
inclusion htu ∘ inclusion hst = inclusion (hst.trans htu) :=
funext (inclusion_inclusion hst htu)
#align set.inclusion_comp_inclusion Set.inclusion_comp_inclusion
-/
#print Set.coe_inclusion /-
@[simp]
theorem coe_inclusion (h : s ⊆ t) (x : s) : (inclusion h x : α) = (x : α) :=
rfl
#align set.coe_inclusion Set.coe_inclusion
-/
#print Set.inclusion_injective /-
theorem inclusion_injective (h : s ⊆ t) : Injective (inclusion h)
| ⟨_, _⟩, ⟨_, _⟩ => Subtype.ext_iff_val.2 ∘ Subtype.ext_iff_val.1
#align set.inclusion_injective Set.inclusion_injective
-/
#print Set.eq_of_inclusion_surjective /-
theorem eq_of_inclusion_surjective {s t : Set α} {h : s ⊆ t}
(h_surj : Function.Surjective (inclusion h)) : s = t :=
by
refine' Set.Subset.antisymm h fun x hx => _
obtain ⟨y, hy⟩ := h_surj ⟨x, hx⟩
exact mem_of_eq_of_mem (congr_arg coe hy).symm y.prop
#align set.eq_of_inclusion_surjective Set.eq_of_inclusion_surjective
-/
end Inclusion
end Set
namespace Subsingleton
variable {α : Type _} [Subsingleton α]
#print Subsingleton.eq_univ_of_nonempty /-
theorem eq_univ_of_nonempty {s : Set α} : s.Nonempty → s = univ := fun ⟨x, hx⟩ =>
eq_univ_of_forall fun y => Subsingleton.elim x y ▸ hx
#align subsingleton.eq_univ_of_nonempty Subsingleton.eq_univ_of_nonempty
-/
#print Subsingleton.set_cases /-
@[elab_as_elim]
theorem set_cases {p : Set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s :=
s.eq_empty_or_nonempty.elim (fun h => h.symm ▸ h0) fun h => (eq_univ_of_nonempty h).symm ▸ h1
#align subsingleton.set_cases Subsingleton.set_cases
-/
#print Subsingleton.mem_iff_nonempty /-
theorem mem_iff_nonempty {α : Type _} [Subsingleton α] {s : Set α} {x : α} : x ∈ s ↔ s.Nonempty :=
⟨fun hx => ⟨x, hx⟩, fun ⟨y, hy⟩ => Subsingleton.elim y x ▸ hy⟩
#align subsingleton.mem_iff_nonempty Subsingleton.mem_iff_nonempty
-/
end Subsingleton
/-! ### Decidability instances for sets -/
namespace Set
variable {α : Type u} (s t : Set α) (a : α)
/- warning: set.decidable_sdiff -> Set.decidableSdiff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (a : α) [_inst_1 : Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)] [_inst_2 : Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t)], Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (a : α) [_inst_1 : Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)] [_inst_2 : Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t)], Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.decidable_sdiff Set.decidableSdiffₓ'. -/
instance decidableSdiff [Decidable (a ∈ s)] [Decidable (a ∈ t)] : Decidable (a ∈ s \ t) :=
(by infer_instance : Decidable (a ∈ s ∧ a ∉ t))
#align set.decidable_sdiff Set.decidableSdiff
/- warning: set.decidable_inter -> Set.decidableInter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (a : α) [_inst_1 : Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)] [_inst_2 : Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t)], Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (a : α) [_inst_1 : Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)] [_inst_2 : Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t)], Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.decidable_inter Set.decidableInterₓ'. -/
instance decidableInter [Decidable (a ∈ s)] [Decidable (a ∈ t)] : Decidable (a ∈ s ∩ t) :=
(by infer_instance : Decidable (a ∈ s ∧ a ∈ t))
#align set.decidable_inter Set.decidableInter
/- warning: set.decidable_union -> Set.decidableUnion is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (a : α) [_inst_1 : Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)] [_inst_2 : Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t)], Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (t : Set.{u1} α) (a : α) [_inst_1 : Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)] [_inst_2 : Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t)], Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t))
Case conversion may be inaccurate. Consider using '#align set.decidable_union Set.decidableUnionₓ'. -/
instance decidableUnion [Decidable (a ∈ s)] [Decidable (a ∈ t)] : Decidable (a ∈ s ∪ t) :=
(by infer_instance : Decidable (a ∈ s ∨ a ∈ t))
#align set.decidable_union Set.decidableUnion
/- warning: set.decidable_compl -> Set.decidableCompl is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (s : Set.{u1} α) (a : α) [_inst_1 : Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a s)], Decidable (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s))
but is expected to have type
forall {α : Type.{u1}} (s : Set.{u1} α) (a : α) [_inst_1 : Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a s)], Decidable (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) s))
Case conversion may be inaccurate. Consider using '#align set.decidable_compl Set.decidableComplₓ'. -/
instance decidableCompl [Decidable (a ∈ s)] : Decidable (a ∈ sᶜ) :=
(by infer_instance : Decidable (a ∉ s))
#align set.decidable_compl Set.decidableCompl
#print Set.decidableEmptyset /-
instance decidableEmptyset : DecidablePred (· ∈ (∅ : Set α)) := fun _ => Decidable.isFalse (by simp)
#align set.decidable_emptyset Set.decidableEmptyset
-/
#print Set.decidableUniv /-
instance decidableUniv : DecidablePred (· ∈ (Set.univ : Set α)) := fun _ =>
Decidable.isTrue (by simp)
#align set.decidable_univ Set.decidableUniv
-/
#print Set.decidableSetOf /-
instance decidableSetOf (p : α → Prop) [Decidable (p a)] : Decidable (a ∈ { a | p a }) := by
assumption
#align set.decidable_set_of Set.decidableSetOf
-/
end Set
/-! ### Monotone lemmas for sets -/
section Monotone
variable {α β : Type _}
/- warning: monotone.inter -> Monotone.inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)}, (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) f) -> (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) g) -> (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (fun (x : β) => Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (f x) (g x)))
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)}, (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) f) -> (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) g) -> (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (fun (x : β) => Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (f x) (g x)))
Case conversion may be inaccurate. Consider using '#align monotone.inter Monotone.interₓ'. -/
theorem Monotone.inter [Preorder β] {f g : β → Set α} (hf : Monotone f) (hg : Monotone g) :
Monotone fun x => f x ∩ g x :=
hf.inf hg
#align monotone.inter Monotone.inter
/- warning: monotone_on.inter -> MonotoneOn.inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)} {s : Set.{u2} β}, (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) f s) -> (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) g s) -> (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (fun (x : β) => Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (f x) (g x)) s)
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)} {s : Set.{u2} β}, (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) f s) -> (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) g s) -> (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (fun (x : β) => Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (f x) (g x)) s)
Case conversion may be inaccurate. Consider using '#align monotone_on.inter MonotoneOn.interₓ'. -/
theorem MonotoneOn.inter [Preorder β] {f g : β → Set α} {s : Set β} (hf : MonotoneOn f s)
(hg : MonotoneOn g s) : MonotoneOn (fun x => f x ∩ g x) s :=
hf.inf hg
#align monotone_on.inter MonotoneOn.inter
/- warning: antitone.inter -> Antitone.inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)}, (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) f) -> (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) g) -> (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (fun (x : β) => Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (f x) (g x)))
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)}, (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) f) -> (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) g) -> (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (fun (x : β) => Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (f x) (g x)))
Case conversion may be inaccurate. Consider using '#align antitone.inter Antitone.interₓ'. -/
theorem Antitone.inter [Preorder β] {f g : β → Set α} (hf : Antitone f) (hg : Antitone g) :
Antitone fun x => f x ∩ g x :=
hf.inf hg
#align antitone.inter Antitone.inter
/- warning: antitone_on.inter -> AntitoneOn.inter is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)} {s : Set.{u2} β}, (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) f s) -> (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) g s) -> (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (fun (x : β) => Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (f x) (g x)) s)
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)} {s : Set.{u2} β}, (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) f s) -> (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) g s) -> (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (fun (x : β) => Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) (f x) (g x)) s)
Case conversion may be inaccurate. Consider using '#align antitone_on.inter AntitoneOn.interₓ'. -/
theorem AntitoneOn.inter [Preorder β] {f g : β → Set α} {s : Set β} (hf : AntitoneOn f s)
(hg : AntitoneOn g s) : AntitoneOn (fun x => f x ∩ g x) s :=
hf.inf hg
#align antitone_on.inter AntitoneOn.inter
/- warning: monotone.union -> Monotone.union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)}, (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) f) -> (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) g) -> (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (fun (x : β) => Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (f x) (g x)))
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)}, (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) f) -> (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) g) -> (Monotone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (fun (x : β) => Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (f x) (g x)))
Case conversion may be inaccurate. Consider using '#align monotone.union Monotone.unionₓ'. -/
theorem Monotone.union [Preorder β] {f g : β → Set α} (hf : Monotone f) (hg : Monotone g) :
Monotone fun x => f x ∪ g x :=
hf.sup hg
#align monotone.union Monotone.union
/- warning: monotone_on.union -> MonotoneOn.union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)} {s : Set.{u2} β}, (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) f s) -> (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) g s) -> (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (fun (x : β) => Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (f x) (g x)) s)
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)} {s : Set.{u2} β}, (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) f s) -> (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) g s) -> (MonotoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (fun (x : β) => Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (f x) (g x)) s)
Case conversion may be inaccurate. Consider using '#align monotone_on.union MonotoneOn.unionₓ'. -/
theorem MonotoneOn.union [Preorder β] {f g : β → Set α} {s : Set β} (hf : MonotoneOn f s)
(hg : MonotoneOn g s) : MonotoneOn (fun x => f x ∪ g x) s :=
hf.sup hg
#align monotone_on.union MonotoneOn.union
/- warning: antitone.union -> Antitone.union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)}, (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) f) -> (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) g) -> (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (fun (x : β) => Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (f x) (g x)))
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)}, (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) f) -> (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) g) -> (Antitone.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (fun (x : β) => Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (f x) (g x)))
Case conversion may be inaccurate. Consider using '#align antitone.union Antitone.unionₓ'. -/
theorem Antitone.union [Preorder β] {f g : β → Set α} (hf : Antitone f) (hg : Antitone g) :
Antitone fun x => f x ∪ g x :=
hf.sup hg
#align antitone.union Antitone.union
/- warning: antitone_on.union -> AntitoneOn.union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)} {s : Set.{u2} β}, (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) f s) -> (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) g s) -> (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (fun (x : β) => Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) (f x) (g x)) s)
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u2} β] {f : β -> (Set.{u1} α)} {g : β -> (Set.{u1} α)} {s : Set.{u2} β}, (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) f s) -> (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) g s) -> (AntitoneOn.{u2, u1} β (Set.{u1} α) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (fun (x : β) => Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) (f x) (g x)) s)
Case conversion may be inaccurate. Consider using '#align antitone_on.union AntitoneOn.unionₓ'. -/
theorem AntitoneOn.union [Preorder β] {f g : β → Set α} {s : Set β} (hf : AntitoneOn f s)
(hg : AntitoneOn g s) : AntitoneOn (fun x => f x ∪ g x) s :=
hf.sup hg
#align antitone_on.union AntitoneOn.union
namespace Set
/- warning: set.monotone_set_of -> Set.monotone_setOf is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u1} α] {p : α -> β -> Prop}, (forall (b : β), Monotone.{u1, 0} α Prop _inst_1 (PartialOrder.toPreorder.{0} Prop Prop.partialOrder) (fun (a : α) => p a b)) -> (Monotone.{u1, u2} α (Set.{u2} β) _inst_1 (PartialOrder.toPreorder.{u2} (Set.{u2} β) (SemilatticeInf.toPartialOrder.{u2} (Set.{u2} β) (Lattice.toSemilatticeInf.{u2} (Set.{u2} β) (GeneralizedCoheytingAlgebra.toLattice.{u2} (Set.{u2} β) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u2} (Set.{u2} β) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u2} (Set.{u2} β) (Set.booleanAlgebra.{u2} β))))))) (fun (a : α) => setOf.{u2} β (fun (b : β) => p a b)))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Preorder.{u2} α] {p : α -> β -> Prop}, (forall (b : β), Monotone.{u2, 0} α Prop _inst_1 (PartialOrder.toPreorder.{0} Prop Prop.partialOrder) (fun (a : α) => p a b)) -> (Monotone.{u2, u1} α (Set.{u1} β) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} β) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} β) (Lattice.toSemilatticeInf.{u1} (Set.{u1} β) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} β) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} β) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} β) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} β) (Set.instBooleanAlgebraSet.{u1} β)))))))) (fun (a : α) => setOf.{u1} β (fun (b : β) => p a b)))
Case conversion may be inaccurate. Consider using '#align set.monotone_set_of Set.monotone_setOfₓ'. -/
theorem monotone_setOf [Preorder α] {p : α → β → Prop} (hp : ∀ b, Monotone fun a => p a b) :
Monotone fun a => { b | p a b } := fun a a' h b => hp b h
#align set.monotone_set_of Set.monotone_setOf
/- warning: set.antitone_set_of -> Set.antitone_setOf is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u1} α] {p : α -> β -> Prop}, (forall (b : β), Antitone.{u1, 0} α Prop _inst_1 (PartialOrder.toPreorder.{0} Prop Prop.partialOrder) (fun (a : α) => p a b)) -> (Antitone.{u1, u2} α (Set.{u2} β) _inst_1 (PartialOrder.toPreorder.{u2} (Set.{u2} β) (SemilatticeInf.toPartialOrder.{u2} (Set.{u2} β) (Lattice.toSemilatticeInf.{u2} (Set.{u2} β) (GeneralizedCoheytingAlgebra.toLattice.{u2} (Set.{u2} β) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u2} (Set.{u2} β) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u2} (Set.{u2} β) (Set.booleanAlgebra.{u2} β))))))) (fun (a : α) => setOf.{u2} β (fun (b : β) => p a b)))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Preorder.{u2} α] {p : α -> β -> Prop}, (forall (b : β), Antitone.{u2, 0} α Prop _inst_1 (PartialOrder.toPreorder.{0} Prop Prop.partialOrder) (fun (a : α) => p a b)) -> (Antitone.{u2, u1} α (Set.{u1} β) _inst_1 (PartialOrder.toPreorder.{u1} (Set.{u1} β) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} β) (Lattice.toSemilatticeInf.{u1} (Set.{u1} β) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} β) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} β) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} β) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} β) (Set.instBooleanAlgebraSet.{u1} β)))))))) (fun (a : α) => setOf.{u1} β (fun (b : β) => p a b)))
Case conversion may be inaccurate. Consider using '#align set.antitone_set_of Set.antitone_setOfₓ'. -/
theorem antitone_setOf [Preorder α] {p : α → β → Prop} (hp : ∀ b, Antitone fun a => p a b) :
Antitone fun a => { b | p a b } := fun a a' h b => hp b h
#align set.antitone_set_of Set.antitone_setOf
/- warning: set.antitone_bforall -> Set.antitone_bforall is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {P : α -> Prop}, Antitone.{u1, 0} (Set.{u1} α) Prop (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))))))) (PartialOrder.toPreorder.{0} Prop Prop.partialOrder) (fun (s : Set.{u1} α) => forall (x : α), (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (P x))
but is expected to have type
forall {α : Type.{u1}} {P : α -> Prop}, Antitone.{u1, 0} (Set.{u1} α) Prop (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)))))))) (PartialOrder.toPreorder.{0} Prop Prop.partialOrder) (fun (s : Set.{u1} α) => forall (x : α), (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) -> (P x))
Case conversion may be inaccurate. Consider using '#align set.antitone_bforall Set.antitone_bforallₓ'. -/
/-- Quantifying over a set is antitone in the set -/
theorem antitone_bforall {P : α → Prop} : Antitone fun s : Set α => ∀ x ∈ s, P x :=
fun s t hst h x hx => h x <| hst hx
#align set.antitone_bforall Set.antitone_bforall
end Set
end Monotone
/-! ### Disjoint sets -/
variable {α β : Type _} {s t u : Set α} {f : α → β}
namespace Disjoint
/- warning: disjoint.union_left -> Disjoint.union_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s u) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) t u) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) u)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s u) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) t u) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) u)
Case conversion may be inaccurate. Consider using '#align disjoint.union_left Disjoint.union_leftₓ'. -/
theorem union_left (hs : Disjoint s u) (ht : Disjoint t u) : Disjoint (s ∪ t) u :=
hs.sup_left ht
#align disjoint.union_left Disjoint.union_left
/- warning: disjoint.union_right -> Disjoint.union_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s u) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s u) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align disjoint.union_right Disjoint.union_rightₓ'. -/
theorem union_right (ht : Disjoint s t) (hu : Disjoint s u) : Disjoint s (t ∪ u) :=
ht.sup_right hu
#align disjoint.union_right Disjoint.union_right
/- warning: disjoint.inter_left -> Disjoint.inter_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s u) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s u) t)
Case conversion may be inaccurate. Consider using '#align disjoint.inter_left Disjoint.inter_leftₓ'. -/
theorem inter_left (u : Set α) (h : Disjoint s t) : Disjoint (s ∩ u) t :=
h.inf_left u
#align disjoint.inter_left Disjoint.inter_left
/- warning: disjoint.inter_left' -> Disjoint.inter_left' is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) u s) t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) u s) t)
Case conversion may be inaccurate. Consider using '#align disjoint.inter_left' Disjoint.inter_left'ₓ'. -/
theorem inter_left' (u : Set α) (h : Disjoint s t) : Disjoint (u ∩ s) t :=
h.inf_left' _
#align disjoint.inter_left' Disjoint.inter_left'
/- warning: disjoint.inter_right -> Disjoint.inter_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) t u))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) t u))
Case conversion may be inaccurate. Consider using '#align disjoint.inter_right Disjoint.inter_rightₓ'. -/
theorem inter_right (u : Set α) (h : Disjoint s t) : Disjoint s (t ∩ u) :=
h.inf_right _
#align disjoint.inter_right Disjoint.inter_right
/- warning: disjoint.inter_right' -> Disjoint.inter_right' is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) u t))
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} (u : Set.{u1} α), (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) u t))
Case conversion may be inaccurate. Consider using '#align disjoint.inter_right' Disjoint.inter_right'ₓ'. -/
theorem inter_right' (u : Set α) (h : Disjoint s t) : Disjoint s (u ∩ t) :=
h.inf_right' _
#align disjoint.inter_right' Disjoint.inter_right'
/- warning: disjoint.subset_left_of_subset_union -> Disjoint.subset_left_of_subset_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s u) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s u) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t)
Case conversion may be inaccurate. Consider using '#align disjoint.subset_left_of_subset_union Disjoint.subset_left_of_subset_unionₓ'. -/
theorem subset_left_of_subset_union (h : s ⊆ t ∪ u) (hac : Disjoint s u) : s ⊆ t :=
hac.left_le_of_le_sup_right h
#align disjoint.subset_left_of_subset_union Disjoint.subset_left_of_subset_union
/- warning: disjoint.subset_right_of_subset_union -> Disjoint.subset_right_of_subset_union is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (GeneralizedBooleanAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s u)
but is expected to have type
forall {α : Type.{u1}} {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) -> (Disjoint.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (SemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (Lattice.toSemilatticeInf.{u1} (Set.{u1} α) (GeneralizedCoheytingAlgebra.toLattice.{u1} (Set.{u1} α) (CoheytingAlgebra.toGeneralizedCoheytingAlgebra.{u1} (Set.{u1} α) (BiheytingAlgebra.toCoheytingAlgebra.{u1} (Set.{u1} α) (BooleanAlgebra.toBiheytingAlgebra.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))))))))) (BooleanAlgebra.toBoundedOrder.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α))) s t) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s u)
Case conversion may be inaccurate. Consider using '#align disjoint.subset_right_of_subset_union Disjoint.subset_right_of_subset_unionₓ'. -/
theorem subset_right_of_subset_union (h : s ⊆ t ∪ u) (hab : Disjoint s t) : s ⊆ u :=
hab.left_le_of_le_sup_left h
#align disjoint.subset_right_of_subset_union Disjoint.subset_right_of_subset_union
end Disjoint
|
{
"alphanum_fraction": null,
"author": "leanprover-community",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Data/Set/Basic.lean",
"reason": null,
"repo": "mathlib3port",
"save_path": "github-repos/lean/leanprover-community-mathlib3port",
"sha": "62505aa236c58c8559783b16d33e30df3daa54f4",
"size": null
}
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
# The following code is adapted from colour_predict_hint.py of this exercise.
OUTPUT_TEMPLATE = (
'The score of the selected model is: {model_score:g}'
)
def main():
monthly_data_labelled = pd.read_csv(sys.argv[1])
monthly_data_unlabelled = pd.read_csv(sys.argv[2])
# The following codes are inspired from https://zhuanlan.zhihu.com/p/89464360 (Chinese Version).
X = monthly_data_labelled.iloc[:, 1:] # First two colums are needed.
y = monthly_data_labelled.iloc[:,0] # The column of label (i.e. first column) is needed.
# The following codes are adapted from my previous assignment.
from sklearn.model_selection import train_test_split
X_train, X_valid, y_train, y_valid = train_test_split(X, y)
# The following codes are adapted from https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html .
# The following codes are also adapted from https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html and https://www.datacamp.com/community/tutorials/random-forests-classifier-python .
from sklearn.preprocessing import FunctionTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.naive_bayes import GaussianNB
model_bayes = make_pipeline(
StandardScaler(),
GaussianNB()
)
X_train, X_valid, y_train, y_valid = train_test_split(X, y)
model_bayes.fit(X_train, y_train)
model_bayes_accuracy = model_bayes.score(X_valid, y_valid, sample_weight = None)
# print('The accuracy score of model_bayes is %g.' % model_bayes_accuracy)
# AVG = 0.635172
from sklearn.neighbors import KNeighborsClassifier
model_knn = make_pipeline(
StandardScaler(),
KNeighborsClassifier(n_neighbors = 8)
)
X_train, X_valid, y_train, y_valid = train_test_split(X, y)
model_knn.fit(X_train, y_train)
model_knn_accuracy = model_knn.score(X_valid, y_valid, sample_weight = None)
# print('The accuracy score of model_knn is %g.' % model_knn_accuracy)
# AVG = 0.671724
from sklearn.ensemble import RandomForestClassifier
model = make_pipeline(
StandardScaler(),
RandomForestClassifier(n_estimators = 100)
)
X_train, X_valid, y_train, y_valid = train_test_split(X, y)
model.fit(X_train, y_train)
model_score = model.score(X_valid, y_valid, sample_weight = None)
# AVG = 0.731034
# All the above values of AVG are calcuted after 10 executions.
print(OUTPUT_TEMPLATE.format(
model_score = model.score(X_valid, y_valid)
))
# The following code is inspired from https://zhuanlan.zhihu.com/p/89464360 (Chinese Version).
data = monthly_data_unlabelled.iloc[:, 1:] # The column of city (i.e. second column) is needed.
predictions = model.predict(data)
# The following code is copied from the instruction.
pd.Series(predictions).to_csv(sys.argv[3], index = False, header = False)
# df = pd.DataFrame({'truth': y_valid, 'prediction': model.predict(X_valid)})
# print(df[df['truth'] != df['prediction']])
# The above two lines of comment are for the answers.txt .
if __name__ == '__main__':
main()
|
{
"alphanum_fraction": 0.7184610796,
"author": null,
"avg_line_length": 40.3975903614,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "80a2ebdead09322b68b1a48a15d2543c94a46bf8",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e4e3b749557466b9001a403ddd14c7d7c5254fc0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "zeyongj/Computational-Data-Science",
"max_forks_repo_path": "Exercise 8/weather_city.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e4e3b749557466b9001a403ddd14c7d7c5254fc0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "zeyongj/Computational-Data-Science",
"max_issues_repo_path": "Exercise 8/weather_city.py",
"max_line_length": 225,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e4e3b749557466b9001a403ddd14c7d7c5254fc0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "zeyongj/Computational-Data-Science",
"max_stars_repo_path": "Exercise 8/weather_city.py",
"max_stars_repo_stars_event_max_datetime": "2021-08-31T07:42:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-31T07:42:27.000Z",
"num_tokens": 811,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3353
}
|
from collections import OrderedDict
import os
import numpy as np
import torch
import random
import string
import random
import time
import cv2
from pathlib import Path
TUTILS_DEBUG = True
TUTILS_INFO = True
TUTILS_WARNING = True
def p(*s,end="\n", **kargs ):
if TUTILS_INFO:
print("[Trans Info] ", s, kargs, end="")
print("", end=end)
def w(*s,end="\n", **kargs ):
if TUTILS_WARNING or TUTILS_DEBUG:
print("[Trans Warning] ", s, kargs, end="")
print("", end=end)
def d(*s,end="\n", **kargs ):
if TUTILS_DEBUG:
print("[Trans Debug] ", s, kargs, end="")
print("", end=end)
def tfuncname(func):
def run(*argv, **kargs):
print("--------------------------------------------")
print("[Trans Utils] Function Name: ", end=" ")
print(func.__name__)
ret = func(*argv, **kargs)
# if argv:
# ret = func(*argv)
# else:
# ret = func()
return ret
return run
# @tfuncname
def tt():
# print("[Trans Utils] ", end="")
pass
def time_now():
tt()
return time.strftime("%Y%m%d-%H%M%S", time.localtime())
def generate_random_str(n):
tt()
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, n))
return ran_str
def generate_name():
tt()
return time_now() + generate_random_str(6)
# def write_image_np(image, filename):
# tt()
# cv2.imwrite("wc_" + generate_random_str(5)+'-'+ time_now() +".jpg", image.astype(np.uint8))
# pass
def tdir(*dir_paths):
def checkslash(name):
if name.startswith("/"):
name = name[1:]
return checkslash(name)
else:
return name
names = [dir_paths[0]]
for name in dir_paths[1:]:
names.append(checkslash(name))
dir_path = os.path.join(*names)
d(dir_path)
if not os.path.exists(dir_path):
d("Create Dir Path: ", dir_path)
os.makedirs(dir_path)
return dir_path
def tfilename(*filenames):
def checkslash(name):
if name.startswith("/"):
name = name[1:]
return checkslash(name)
else:
return name
names = [filenames[0]]
for name in filenames[1:]:
names.append(checkslash(name))
filename = os.path.join(*names)
d(filename)
parent, name = os.path.split(filename)
if not os.path.exists(parent):
os.makedirs(parent)
return filename
def texists(*filenames):
path = os.path.join(*filenames)
return os.path.exists(path)
def ttsave(state, path, configs=None):
path = tdir("trans_torch_models", path, generate_name())
if configs is not None:
assert type(configs) is dict
config_path = tfilename(path, "configs.json")
with open(config_path, "wb+") as f:
config_js = json.dumps(configs)
f.write(config_js)
torch.save(state, tfilename(path, "model.pkl"))
def add_total(tuple1, tuple2):
l = list()
for i, item in enumerate(tuple1):
l.append(tuple1[i] + tuple2[i])
return tuple(l)
if __name__ == "__main__":
# tt()
# tfilename("dasd", "/dasdsa", "/dsad")
tdir("dasd", "/dsadads", "/dsdas")
|
{
"alphanum_fraction": 0.5794712286,
"author": null,
"avg_line_length": 24.9224806202,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "4ab442d9d76249698c042466d861b80d71e34970",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-06-18T12:13:21.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-18T12:13:21.000Z",
"max_forks_repo_head_hexsha": "fed8e6c8d79f854a1cebcfd5c37297a163846208",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "transcendentsky/py_tutorials",
"max_forks_repo_path": "tutils.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fed8e6c8d79f854a1cebcfd5c37297a163846208",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "transcendentsky/py_tutorials",
"max_issues_repo_path": "tutils.py",
"max_line_length": 97,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fed8e6c8d79f854a1cebcfd5c37297a163846208",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "transcendentsky/py_tutorials",
"max_stars_repo_path": "tutils.py",
"max_stars_repo_stars_event_max_datetime": "2018-06-18T12:09:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-18T12:09:33.000Z",
"num_tokens": 824,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3215
}
|
// Copyright (c) 2014-2018 The Bitcoin Core developers
// Copyright (c) 2017-2020 The LitecoinZ Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key_io.h>
#include <base58.h>
#include <bech32.h>
#include <script/script.h>
#include <util/strencodings.h>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
#include <assert.h>
#include <string.h>
#include <algorithm>
namespace
{
class DestinationEncoder : public boost::static_visitor<std::string>
{
private:
const CChainParams& m_params;
public:
explicit DestinationEncoder(const CChainParams& params) : m_params(params) {}
std::string operator()(const PKHash& id) const
{
std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
data.insert(data.end(), id.begin(), id.end());
return EncodeBase58Check(data);
}
std::string operator()(const ScriptHash& id) const
{
std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
data.insert(data.end(), id.begin(), id.end());
return EncodeBase58Check(data);
}
std::string operator()(const WitnessV0KeyHash& id) const
{
std::vector<unsigned char> data = {0};
data.reserve(33);
ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
return bech32::Encode(m_params.Bech32HRP(), data);
}
std::string operator()(const WitnessV0ScriptHash& id) const
{
std::vector<unsigned char> data = {0};
data.reserve(53);
ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
return bech32::Encode(m_params.Bech32HRP(), data);
}
std::string operator()(const WitnessUnknown& id) const
{
if (id.version < 1 || id.version > 16 || id.length < 2 || id.length > 40) {
return {};
}
std::vector<unsigned char> data = {(unsigned char)id.version};
data.reserve(1 + (id.length * 8 + 4) / 5);
ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.program, id.program + id.length);
return bech32::Encode(m_params.Bech32HRP(), data);
}
std::string operator()(const CNoDestination& no) const { return {}; }
};
CTxDestination DecodeDestination(const std::string& str, const CChainParams& params)
{
std::vector<unsigned char> data;
uint160 hash;
if (DecodeBase58Check(str, data)) {
// base58-encoded Bitcoin addresses.
// Public-key-hash-addresses have version 0 (or 111 testnet).
// The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
const std::vector<unsigned char>& pubkey_prefix = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
if (data.size() == hash.size() + pubkey_prefix.size() && std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {
std::copy(data.begin() + pubkey_prefix.size(), data.end(), hash.begin());
return PKHash(hash);
}
// Script-hash-addresses have version 5 (or 196 testnet).
// The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
const std::vector<unsigned char>& script_prefix = params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
if (data.size() == hash.size() + script_prefix.size() && std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) {
std::copy(data.begin() + script_prefix.size(), data.end(), hash.begin());
return ScriptHash(hash);
}
}
data.clear();
auto bech = bech32::Decode(str);
if (bech.second.size() > 0 && bech.first == params.Bech32HRP()) {
// Bech32 decoding
int version = bech.second[0]; // The first 5 bit symbol is the witness version (0-16)
// The rest of the symbols are converted witness program bytes.
data.reserve(((bech.second.size() - 1) * 5) / 8);
if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, bech.second.begin() + 1, bech.second.end())) {
if (version == 0) {
{
WitnessV0KeyHash keyid;
if (data.size() == keyid.size()) {
std::copy(data.begin(), data.end(), keyid.begin());
return keyid;
}
}
{
WitnessV0ScriptHash scriptid;
if (data.size() == scriptid.size()) {
std::copy(data.begin(), data.end(), scriptid.begin());
return scriptid;
}
}
return CNoDestination();
}
if (version > 16 || data.size() < 2 || data.size() > 40) {
return CNoDestination();
}
WitnessUnknown unk;
unk.version = version;
std::copy(data.begin(), data.end(), unk.program);
unk.length = data.size();
return unk;
}
}
return CNoDestination();
}
class PaymentAddressEncoder : public boost::static_visitor<std::string>
{
private:
const CChainParams& m_params;
public:
PaymentAddressEncoder(const CChainParams& params) : m_params(params) {}
std::string operator()(const libzcash::SproutPaymentAddress& zaddr) const
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << zaddr;
std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SPROUT_PAYMENT_ADDRESS);
data.insert(data.end(), ss.begin(), ss.end());
return EncodeBase58Check(data);
}
std::string operator()(const libzcash::SaplingPaymentAddress& zaddr) const
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << zaddr;
// ConvertBits requires unsigned char, but CDataStream uses char
std::vector<unsigned char> seraddr(ss.begin(), ss.end());
std::vector<unsigned char> data;
// See calculation comment below
data.reserve((seraddr.size() * 8 + 4) / 5);
ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, seraddr.begin(), seraddr.end());
return bech32::Encode(m_params.Bech32HRP(CChainParams::SAPLING_PAYMENT_ADDRESS), data);
}
std::string operator()(const libzcash::InvalidEncoding& no) const { return {}; }
};
class ViewingKeyEncoder : public boost::static_visitor<std::string>
{
private:
const CChainParams& m_params;
public:
ViewingKeyEncoder(const CChainParams& params) : m_params(params) {}
std::string operator()(const libzcash::SproutViewingKey& vk) const
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << vk;
std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SPROUT_VIEWING_KEY);
data.insert(data.end(), ss.begin(), ss.end());
std::string ret = EncodeBase58Check(data);
memory_cleanse(data.data(), data.size());
return ret;
}
std::string operator()(const libzcash::SaplingExtendedFullViewingKey& extfvk) const
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << extfvk;
// ConvertBits requires unsigned char, but CDataStream uses char
std::vector<unsigned char> serkey(ss.begin(), ss.end());
std::vector<unsigned char> data;
// See calculation comment below
data.reserve((serkey.size() * 8 + 4) / 5);
ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, serkey.begin(), serkey.end());
std::string ret = bech32::Encode(m_params.Bech32HRP(CChainParams::SAPLING_EXTENDED_FVK), data);
memory_cleanse(serkey.data(), serkey.size());
memory_cleanse(data.data(), data.size());
return ret;
}
std::string operator()(const libzcash::InvalidEncoding& no) const { return {}; }
};
class SpendingKeyEncoder : public boost::static_visitor<std::string>
{
private:
const CChainParams& m_params;
public:
SpendingKeyEncoder(const CChainParams& params) : m_params(params) {}
std::string operator()(const libzcash::SproutSpendingKey& zkey) const
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << zkey;
std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SPROUT_SPENDING_KEY);
data.insert(data.end(), ss.begin(), ss.end());
std::string ret = EncodeBase58Check(data);
memory_cleanse(data.data(), data.size());
return ret;
}
std::string operator()(const libzcash::SaplingExtendedSpendingKey& zkey) const
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << zkey;
// ConvertBits requires unsigned char, but CDataStream uses char
std::vector<unsigned char> serkey(ss.begin(), ss.end());
std::vector<unsigned char> data;
// See calculation comment below
data.reserve((serkey.size() * 8 + 4) / 5);
ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, serkey.begin(), serkey.end());
std::string ret = bech32::Encode(m_params.Bech32HRP(CChainParams::SAPLING_EXTENDED_SPEND_KEY), data);
memory_cleanse(serkey.data(), serkey.size());
memory_cleanse(data.data(), data.size());
return ret;
}
std::string operator()(const libzcash::InvalidEncoding& no) const { return {}; }
};
// Sizes of SaplingPaymentAddress, SaplingExtendedFullViewingKey, and
// SaplingExtendedSpendingKey after ConvertBits<8, 5, true>(). The calculations
// below take the regular serialized size in bytes, convert to bits, and then
// perform ceiling division to get the number of 5-bit clusters.
const size_t ConvertedSaplingPaymentAddressSize = ((32 + 11) * 8 + 4) / 5;
const size_t ConvertedSaplingExtendedFullViewingKeySize = (ZIP32_XFVK_SIZE * 8 + 4) / 5;
const size_t ConvertedSaplingExtendedSpendingKeySize = (ZIP32_XSK_SIZE * 8 + 4) / 5;
} // namespace
CKey DecodeSecret(const std::string& str)
{
CKey key;
std::vector<unsigned char> data;
if (DecodeBase58Check(str, data)) {
const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);
if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&
std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {
bool compressed = data.size() == 33 + privkey_prefix.size();
key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);
}
}
if (!data.empty()) {
memory_cleanse(data.data(), data.size());
}
return key;
}
std::string EncodeSecret(const CKey& key)
{
assert(key.IsValid());
std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);
data.insert(data.end(), key.begin(), key.end());
if (key.IsCompressed()) {
data.push_back(1);
}
std::string ret = EncodeBase58Check(data);
memory_cleanse(data.data(), data.size());
return ret;
}
CExtPubKey DecodeExtPubKey(const std::string& str)
{
CExtPubKey key;
std::vector<unsigned char> data;
if (DecodeBase58Check(str, data)) {
const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
key.Decode(data.data() + prefix.size());
}
}
return key;
}
std::string EncodeExtPubKey(const CExtPubKey& key)
{
std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
size_t size = data.size();
data.resize(size + BIP32_EXTKEY_SIZE);
key.Encode(data.data() + size);
std::string ret = EncodeBase58Check(data);
return ret;
}
CExtKey DecodeExtKey(const std::string& str)
{
CExtKey key;
std::vector<unsigned char> data;
if (DecodeBase58Check(str, data)) {
const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
key.Decode(data.data() + prefix.size());
}
}
return key;
}
std::string EncodeExtKey(const CExtKey& key)
{
std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
size_t size = data.size();
data.resize(size + BIP32_EXTKEY_SIZE);
key.Encode(data.data() + size);
std::string ret = EncodeBase58Check(data);
memory_cleanse(data.data(), data.size());
return ret;
}
std::string EncodeDestination(const CTxDestination& dest)
{
return boost::apply_visitor(DestinationEncoder(Params()), dest);
}
CTxDestination DecodeDestination(const std::string& str)
{
return DecodeDestination(str, Params());
}
bool IsValidDestinationString(const std::string& str, const CChainParams& params)
{
return IsValidDestination(DecodeDestination(str, params));
}
bool IsValidDestinationString(const std::string& str)
{
return IsValidDestinationString(str, Params());
}
std::string EncodePaymentAddress(const libzcash::PaymentAddress& address)
{
return boost::apply_visitor(PaymentAddressEncoder(Params()), address);
}
template<typename T1, typename T2, typename T3>
T1 DecodeAny(
const std::string& str,
std::pair<CChainParams::Base58Type, size_t> sprout,
std::pair<CChainParams::Bech32Type, size_t> sapling)
{
std::vector<unsigned char> data;
if (DecodeBase58Check(str, data)) {
const std::vector<unsigned char>& prefix = Params().Base58Prefix(sprout.first);
if ((data.size() == sprout.second + prefix.size()) &&
std::equal(prefix.begin(), prefix.end(), data.begin())) {
CSerializeData serialized(data.begin() + prefix.size(), data.end());
CDataStream ss(serialized, SER_NETWORK, PROTOCOL_VERSION);
T2 ret;
ss >> ret;
memory_cleanse(serialized.data(), serialized.size());
memory_cleanse(data.data(), data.size());
return ret;
}
}
data.clear();
auto bech = bech32::Decode(str, 1023);
if (bech.first == Params().Bech32HRP(sapling.first) &&
bech.second.size() == sapling.second) {
// Bech32 decoding
data.reserve((bech.second.size() * 5) / 8);
if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, bech.second.begin(), bech.second.end())) {
CDataStream ss(data, SER_NETWORK, PROTOCOL_VERSION);
T3 ret;
ss >> ret;
memory_cleanse(data.data(), data.size());
return ret;
}
}
memory_cleanse(data.data(), data.size());
return libzcash::InvalidEncoding();
}
libzcash::PaymentAddress DecodePaymentAddress(const std::string& str)
{
return DecodeAny<libzcash::PaymentAddress,
libzcash::SproutPaymentAddress,
libzcash::SaplingPaymentAddress>(
str,
std::make_pair(CChainParams::SPROUT_PAYMENT_ADDRESS, libzcash::SerializedSproutPaymentAddressSize),
std::make_pair(CChainParams::SAPLING_PAYMENT_ADDRESS, ConvertedSaplingPaymentAddressSize)
);
}
bool IsValidPaymentAddressString(const std::string& str) {
return IsValidPaymentAddress(DecodePaymentAddress(str));
}
std::string EncodeViewingKey(const libzcash::ViewingKey& vk)
{
return boost::apply_visitor(ViewingKeyEncoder(Params()), vk);
}
libzcash::ViewingKey DecodeViewingKey(const std::string& str)
{
return DecodeAny<libzcash::ViewingKey,
libzcash::SproutViewingKey,
libzcash::SaplingExtendedFullViewingKey>(
str,
std::make_pair(CChainParams::SPROUT_VIEWING_KEY, libzcash::SerializedSproutViewingKeySize),
std::make_pair(CChainParams::SAPLING_EXTENDED_FVK, ConvertedSaplingExtendedFullViewingKeySize)
);
}
std::string EncodeSpendingKey(const libzcash::SpendingKey& sk)
{
return boost::apply_visitor(SpendingKeyEncoder(Params()), sk);
}
libzcash::SpendingKey DecodeSpendingKey(const std::string& str)
{
return DecodeAny<libzcash::SpendingKey,
libzcash::SproutSpendingKey,
libzcash::SaplingExtendedSpendingKey>(
str,
std::make_pair(CChainParams::SPROUT_SPENDING_KEY, libzcash::SerializedSproutSpendingKeySize),
std::make_pair(CChainParams::SAPLING_EXTENDED_SPEND_KEY, ConvertedSaplingExtendedSpendingKeySize)
);
}
|
{
"alphanum_fraction": 0.6434357875,
"author": null,
"avg_line_length": 38.1545454545,
"converted": null,
"ext": "cpp",
"file": null,
"hexsha": "1b5b4a4174f9aa7fa2307d43167e910e9e348cec",
"include": null,
"lang": "C++",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b793b04a717416726a7b1013b21b07fb35dbc4a2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kaboela/litecoinz",
"max_forks_repo_path": "src/key_io.cpp",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "b793b04a717416726a7b1013b21b07fb35dbc4a2",
"max_issues_repo_issues_event_max_datetime": "2021-05-09T18:53:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-04-04T11:24:26.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "kaboela/litecoinz",
"max_issues_repo_path": "src/key_io.cpp",
"max_line_length": 136,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "b793b04a717416726a7b1013b21b07fb35dbc4a2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kaboela/litecoinz",
"max_stars_repo_path": "src/key_io.cpp",
"max_stars_repo_stars_event_max_datetime": "2021-09-28T08:39:52.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-05T16:30:36.000Z",
"num_tokens": 4129,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 16788
}
|
# -*- coding: utf-8 -*-
"""
>>> from pycm import *
>>> import os
>>> import json
>>> import numpy as np
>>> y_test = np.array([600, 200, 200, 200, 200, 200, 200, 200, 500, 500, 500, 200, 200, 200, 200, 200, 200, 200, 200, 200])
>>> y_pred = np.array([100, 200, 200, 100, 100, 200, 200, 200, 100, 200, 500, 100, 100, 100, 100, 100, 100, 100, 500, 200])
>>> cm=ConfusionMatrix(y_test, y_pred)
>>> save_stat=cm.save_stat("test",address=False)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_stat("test_filtered",address=False,overall_param=["Kappa","Scott PI"],class_param=["TPR","TNR","ACC","AUC"])
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_stat("test_summary",address=False,summary=True)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_stat("test_filtered2",address=False,overall_param=["Kappa","Scott PI"],class_param=["TPR","TNR","ACC","AUC"],class_name=["L1","L2"])
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_stat("test_filtered3",address=False,overall_param=["Kappa","Scott PI"],class_param=["TPR","TNR","ACC","AUC"],class_name=[])
>>> save_stat=={'Status': True, 'Message': None}
True
>>> large_cm = ConfusionMatrix(list(range(20)),list(range(20)))
>>> save_stat = large_cm.save_stat("test_large",address=False)
>>> save_stat == {'Status': True, 'Message': None}
True
>>> save_stat=cm.save_stat("/asdasd,qweqwe.eo/",address=True)
>>> save_stat=={'Status': False, 'Message': "[Errno 2] No such file or directory: '/asdasd,qweqwe.eo/.pycm'"}
True
>>> save_stat=cm.save_html("test",address=False)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_normalized",address=False,normalize=True)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_alt",address=False,normalize=True,alt_link=True)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_summary",address=False,summary=True)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_filtered",address=False,overall_param=["Kappa","Scott PI"],class_param=["TPR","TNR","ACC","AUC"])
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_filtered2",address=False,overall_param=["Kappa","Scott PI"],class_param=["TPR","TNR","ACC","AUC"],class_name=[100])
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_filtered3",address=False,overall_param=["Kappa","Scott PI"],class_param=["TPR","TNR","ACC","AUC"],class_name=[],color=(-2,-2,-2))
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_filtered4",address=False,overall_param=["Kappa","Scott PI"],class_param=[],class_name=[100],color={})
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_filtered5",address=False,overall_param=[],class_param=["TPR","TNR","ACC","AUC"],class_name=[100])
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_colored",address=False,color=(130,100,200))
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("test_colored2",address=False,color="Beige")
>>> save_stat=={'Status': True, 'Message': None}
True
>>> long_name_cm = ConfusionMatrix(matrix={'SVM-Classifier':{'SVM-Classifier':25,'NN-Classifier':2},'NN-Classifier':{'SVM-Classifier':3,'NN-Classifier':50}})
>>> save_stat=long_name_cm.save_html("test_long_name",address=False,color="Pink")
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_html("/asdasd,qweqwe.eo/",address=True)
>>> save_stat=={'Status': False, 'Message': "[Errno 2] No such file or directory: '/asdasd,qweqwe.eo/.html'"}
True
>>> save_stat=cm.save_csv("test",address=False)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_csv("test_normalized",address=False,normalize=True)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_csv("test_summary",address=False,summary=True,matrix_save=False)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_csv("test_filtered",address=False,class_param=["TPR","TNR","ACC","AUC"])
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_csv("test_filtered2",address=False,class_param=["TPR","TNR","ACC","AUC"],class_name=[100],matrix_save=False)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_csv("test_filtered3",address=False,class_param=["TPR","TNR","ACC","AUC"],class_name=[],matrix_save=False)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_csv("test_filtered4",address=False,class_param=[],class_name=[100],matrix_save=False)
>>> save_stat=={'Status': True, 'Message': None}
True
>>> save_stat=cm.save_csv("/asdasd,qweqwe.eo/",address=True)
>>> save_stat=={'Status': False, 'Message': "[Errno 2] No such file or directory: '/asdasd,qweqwe.eo/.csv'"}
True
>>> save_obj=cm.save_obj("test",address=False)
>>> save_obj=={'Status': True, 'Message': None}
True
>>> save_obj=cm.save_obj("test_stat",address=False,save_stat=True)
>>> save_obj=={'Status': True, 'Message': None}
True
>>> save_obj=cm.save_obj("test_no_vectors",address=False,save_vector=False)
>>> save_obj=={'Status': True, 'Message': None}
True
>>> cm_file=ConfusionMatrix(file=open("test.obj","r"))
>>> print(cm_file)
Predict 100 200 500 600
Actual
100 0 0 0 0
<BLANKLINE>
200 9 6 1 0
<BLANKLINE>
500 1 1 1 0
<BLANKLINE>
600 1 0 0 0
<BLANKLINE>
<BLANKLINE>
<BLANKLINE>
<BLANKLINE>
<BLANKLINE>
Overall Statistics :
<BLANKLINE>
95% CI (0.14096,0.55904)
ACC Macro 0.675
AUNP None
AUNU None
Bennett S 0.13333
CBA 0.17708
Chi-Squared None
Chi-Squared DF 9
Conditional Entropy 1.23579
Cramer V None
Cross Entropy 1.70995
F1 Macro 0.23043
F1 Micro 0.35
Gwet AC1 0.19505
Hamming Loss 0.65
Joint Entropy 2.11997
KL Divergence None
Kappa 0.07801
Kappa 95% CI (-0.2185,0.37453)
Kappa No Prevalence -0.3
Kappa Standard Error 0.15128
Kappa Unbiased -0.12554
Lambda A 0.0
Lambda B 0.0
Mutual Information 0.10088
NIR 0.8
Overall ACC 0.35
Overall CEN 0.3648
Overall J (0.60294,0.15074)
Overall MCC 0.12642
Overall MCEN 0.37463
Overall RACC 0.295
Overall RACCU 0.4225
P-Value 1.0
PPV Macro None
PPV Micro 0.35
Pearson C None
Phi-Squared None
RCI 0.11409
RR 5.0
Reference Entropy 0.88418
Response Entropy 1.33667
SOA1(Landis & Koch) Slight
SOA2(Fleiss) Poor
SOA3(Altman) Poor
SOA4(Cicchetti) Poor
SOA5(Cramer) None
SOA6(Matthews) Negligible
Scott PI -0.12554
Standard Error 0.10665
TPR Macro None
TPR Micro 0.35
Zero-one Loss 13
<BLANKLINE>
Class Statistics :
<BLANKLINE>
Classes 100 200 500 600
ACC(Accuracy) 0.45 0.45 0.85 0.95
AGF(Adjusted F-score) 0.0 0.33642 0.56659 0.0
AGM(Adjusted geometric mean) None 0.56694 0.7352 0
AM(Difference between automatic and manual classification) 11 -9 -1 -1
AUC(Area under the ROC curve) None 0.5625 0.63725 0.5
AUCI(AUC value interpretation) None Poor Fair Poor
AUPR(Area under the PR curve) None 0.61607 0.41667 None
BCD(Bray-Curtis dissimilarity) 0.275 0.225 0.025 0.025
BM(Informedness or bookmaker informedness) None 0.125 0.27451 0.0
CEN(Confusion entropy) 0.33496 0.35708 0.53895 0.0
DOR(Diagnostic odds ratio) None 1.8 8.0 None
DP(Discriminant power) None 0.14074 0.4979 None
DPI(Discriminant power interpretation) None Poor Poor None
ERR(Error rate) 0.55 0.55 0.15 0.05
F0.5(F0.5 score) 0.0 0.68182 0.45455 0.0
F1(F1 score - harmonic mean of precision and sensitivity) 0.0 0.52174 0.4 0.0
F2(F2 score) 0.0 0.42254 0.35714 0.0
FDR(False discovery rate) 1.0 0.14286 0.5 None
FN(False negative/miss/type 2 error) 0 10 2 1
FNR(Miss rate or false negative rate) None 0.625 0.66667 1.0
FOR(False omission rate) 0.0 0.76923 0.11111 0.05
FP(False positive/type 1 error/false alarm) 11 1 1 0
FPR(Fall-out or false positive rate) 0.55 0.25 0.05882 0.0
G(G-measure geometric mean of precision and sensitivity) None 0.56695 0.40825 None
GI(Gini index) None 0.125 0.27451 0.0
GM(G-mean geometric mean of specificity and sensitivity) None 0.53033 0.56011 0.0
IBA(Index of balanced accuracy) None 0.17578 0.12303 0.0
IS(Information score) None 0.09954 1.73697 None
J(Jaccard index) 0.0 0.35294 0.25 0.0
LS(Lift score) None 1.07143 3.33333 None
MCC(Matthews correlation coefficient) None 0.10483 0.32673 None
MCCI(Matthews correlation coefficient interpretation) None Negligible Weak None
MCEN(Modified confusion entropy) 0.33496 0.37394 0.58028 0.0
MK(Markedness) 0.0 0.08791 0.38889 None
N(Condition negative) 20 4 17 19
NLR(Negative likelihood ratio) None 0.83333 0.70833 1.0
NLRI(Negative likelihood ratio interpretation) None Negligible Negligible Negligible
NPV(Negative predictive value) 1.0 0.23077 0.88889 0.95
OC(Overlap coefficient) None 0.85714 0.5 None
OOC(Otsuka-Ochiai coefficient) None 0.56695 0.40825 None
OP(Optimized precision) None 0.11667 0.37308 -0.05
P(Condition positive or support) 0 16 3 1
PLR(Positive likelihood ratio) None 1.5 5.66667 None
PLRI(Positive likelihood ratio interpretation) None Poor Fair None
POP(Population) 20 20 20 20
PPV(Precision or positive predictive value) 0.0 0.85714 0.5 None
PRE(Prevalence) 0.0 0.8 0.15 0.05
Q(Yule Q - coefficient of colligation) None 0.28571 0.77778 None
RACC(Random accuracy) 0.0 0.28 0.015 0.0
RACCU(Random accuracy unbiased) 0.07563 0.33062 0.01562 0.00063
TN(True negative/correct rejection) 9 3 16 19
TNR(Specificity or true negative rate) 0.45 0.75 0.94118 1.0
TON(Test outcome negative) 9 13 18 20
TOP(Test outcome positive) 11 7 2 0
TP(True positive/hit) 0 6 1 0
TPR(Sensitivity, recall, hit rate, or true positive rate) None 0.375 0.33333 0.0
Y(Youden index) None 0.125 0.27451 0.0
dInd(Distance index) None 0.67315 0.66926 1.0
sInd(Similarity index) None 0.52401 0.52676 0.29289
<BLANKLINE>
>>> cm_stat_file=ConfusionMatrix(file=open("test_stat.obj","r"))
>>> cm_no_vectors_file=ConfusionMatrix(file=open("test_no_vectors.obj","r"))
>>> cm_stat_file==cm_file
True
>>> cm_no_vectors_file==cm_file
True
>>> cm_no_vectors_dict = json.load(open("test_no_vectors.obj","r"))
>>> cm_no_vectors_dict["Actual-Vector"] == None
True
>>> cm_no_vectors_dict["Predict-Vector"] == None
True
>>> cm_stat_dict = json.load(open("test_stat.obj","r"))
>>> cm_stat_dict["Class-Stat"]["MCC"] != None
True
>>> cm_stat_dict["Overall-Stat"]["Overall MCC"] != None
True
>>> def activation(i):
... if i<0.7:
... return 1
... else:
... return 0
>>> cm_6 = ConfusionMatrix([0,0,1,0],[0.87,0.34,0.9,0.12],threshold=activation)
>>> save_obj=cm_6.save_obj("test2",address=False)
>>> save_obj=={'Status': True, 'Message': None}
True
>>> cm_file_2=ConfusionMatrix(file=open("test2.obj","r"))
>>> cm_file_2.print_matrix()
Predict 0 1
Actual
0 1 2
1 1 0
>>> y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]
>>> y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]
>>> cm = ConfusionMatrix(y_actu, y_pred, sample_weight=[2, 2, 2, 2, 3, 1, 1, 2, 2, 1, 1, 2])
>>> save_obj=cm.save_obj("test3",address=False)
>>> save_obj=={'Status': True, 'Message': None}
True
>>> cm_file_3=ConfusionMatrix(file=open("test3.obj","r"))
>>> cm = ConfusionMatrix(y_actu, y_pred, sample_weight=np.array([2, 2, 2, 2, 3, 1, 1, 2, 2, 1, 1, 2]))
>>> save_obj=cm.save_obj("test3_np",address=False)
>>> save_obj=={'Status': True, 'Message': None}
True
>>> cm_file_3_np=ConfusionMatrix(file=open("test3_np.obj","r"))
>>> cm_file_3_np == cm_file_3
True
>>> cm_file_3.print_matrix()
Predict 0 1 2
Actual
0 6 0 0
1 0 1 2
2 4 2 6
<BLANKLINE>
>>> cm_file_3.stat()
Overall Statistics :
<BLANKLINE>
95% CI (0.41134,0.82675)
ACC Macro 0.74603
AUNP 0.7
AUNU 0.70556
Bennett S 0.42857
CBA 0.47778
Chi-Squared 10.44167
Chi-Squared DF 4
Conditional Entropy 0.96498
Cramer V 0.49861
Cross Entropy 1.50249
F1 Macro 0.56111
F1 Micro 0.61905
Gwet AC1 0.45277
Hamming Loss 0.38095
Joint Entropy 2.34377
KL Divergence 0.1237
Kappa 0.3913
Kappa 95% CI (0.05943,0.72318)
Kappa No Prevalence 0.2381
Kappa Standard Error 0.16932
Kappa Unbiased 0.37313
Lambda A 0.22222
Lambda B 0.36364
Mutual Information 0.47618
NIR 0.57143
Overall ACC 0.61905
Overall CEN 0.43947
Overall J (1.22857,0.40952)
Overall MCC 0.41558
Overall MCEN 0.50059
Overall RACC 0.37415
Overall RACCU 0.39229
P-Value 0.41709
PPV Macro 0.56111
PPV Micro 0.61905
Pearson C 0.57628
Phi-Squared 0.49722
RCI 0.34536
RR 7.0
Reference Entropy 1.37878
Response Entropy 1.44117
SOA1(Landis & Koch) Fair
SOA2(Fleiss) Poor
SOA3(Altman) Fair
SOA4(Cicchetti) Poor
SOA5(Cramer) Relatively Strong
SOA6(Matthews) Weak
Scott PI 0.37313
Standard Error 0.10597
TPR Macro 0.61111
TPR Micro 0.61905
Zero-one Loss 8
<BLANKLINE>
Class Statistics :
<BLANKLINE>
Classes 0 1 2
ACC(Accuracy) 0.80952 0.80952 0.61905
AGF(Adjusted F-score) 0.90694 0.54433 0.55442
AGM(Adjusted geometric mean) 0.80509 0.70336 0.66986
AM(Difference between automatic and manual classification) 4 0 -4
AUC(Area under the ROC curve) 0.86667 0.61111 0.63889
AUCI(AUC value interpretation) Very Good Fair Fair
AUPR(Area under the PR curve) 0.8 0.33333 0.625
BCD(Bray-Curtis dissimilarity) 0.09524 0.0 0.09524
BM(Informedness or bookmaker informedness) 0.73333 0.22222 0.27778
CEN(Confusion entropy) 0.25 0.52832 0.56439
DOR(Diagnostic odds ratio) None 4.0 3.5
DP(Discriminant power) None 0.33193 0.29996
DPI(Discriminant power interpretation) None Poor Poor
ERR(Error rate) 0.19048 0.19048 0.38095
F0.5(F0.5 score) 0.65217 0.33333 0.68182
F1(F1 score - harmonic mean of precision and sensitivity) 0.75 0.33333 0.6
F2(F2 score) 0.88235 0.33333 0.53571
FDR(False discovery rate) 0.4 0.66667 0.25
FN(False negative/miss/type 2 error) 0 2 6
FNR(Miss rate or false negative rate) 0.0 0.66667 0.5
FOR(False omission rate) 0.0 0.11111 0.46154
FP(False positive/type 1 error/false alarm) 4 2 2
FPR(Fall-out or false positive rate) 0.26667 0.11111 0.22222
G(G-measure geometric mean of precision and sensitivity) 0.7746 0.33333 0.61237
GI(Gini index) 0.73333 0.22222 0.27778
GM(G-mean geometric mean of specificity and sensitivity) 0.85635 0.54433 0.62361
IBA(Index of balanced accuracy) 0.92889 0.13169 0.28086
IS(Information score) 1.07039 1.22239 0.39232
J(Jaccard index) 0.6 0.2 0.42857
LS(Lift score) 2.1 2.33333 1.3125
MCC(Matthews correlation coefficient) 0.66332 0.22222 0.28307
MCCI(Matthews correlation coefficient interpretation) Moderate Negligible Negligible
MCEN(Modified confusion entropy) 0.26439 0.52877 0.65924
MK(Markedness) 0.6 0.22222 0.28846
N(Condition negative) 15 18 9
NLR(Negative likelihood ratio) 0.0 0.75 0.64286
NLRI(Negative likelihood ratio interpretation) Good Negligible Negligible
NPV(Negative predictive value) 1.0 0.88889 0.53846
OC(Overlap coefficient) 1.0 0.33333 0.75
OOC(Otsuka-Ochiai coefficient) 0.7746 0.33333 0.61237
OP(Optimized precision) 0.65568 0.35498 0.40166
P(Condition positive or support) 6 3 12
PLR(Positive likelihood ratio) 3.75 3.0 2.25
PLRI(Positive likelihood ratio interpretation) Poor Poor Poor
POP(Population) 21 21 21
PPV(Precision or positive predictive value) 0.6 0.33333 0.75
PRE(Prevalence) 0.28571 0.14286 0.57143
Q(Yule Q - coefficient of colligation) None 0.6 0.55556
RACC(Random accuracy) 0.13605 0.02041 0.21769
RACCU(Random accuracy unbiased) 0.14512 0.02041 0.22676
TN(True negative/correct rejection) 11 16 7
TNR(Specificity or true negative rate) 0.73333 0.88889 0.77778
TON(Test outcome negative) 11 18 13
TOP(Test outcome positive) 10 3 8
TP(True positive/hit) 6 1 6
TPR(Sensitivity, recall, hit rate, or true positive rate) 1.0 0.33333 0.5
Y(Youden index) 0.73333 0.22222 0.27778
dInd(Distance index) 0.26667 0.67586 0.54716
sInd(Similarity index) 0.81144 0.52209 0.6131
>>> cm = ConfusionMatrix(matrix={1:{1:13182,2:30516},2:{1:5108,2:295593}},transpose=True) # Verified Case
>>> save_obj = cm.save_obj("test4",address=False)
>>> save_obj=={'Status': True, 'Message': None}
True
>>> save_obj = cm.save_obj("/asdasd,qweqwe.eo/",address=False)
>>> save_obj=={'Status': False, 'Message': "[Errno 2] No such file or directory: '/asdasd,qweqwe.eo/.obj'"}
True
>>> cm_file=ConfusionMatrix(file=open("test4.obj","r"))
>>> cm_file.DP[1]
0.770700985610517
>>> cm_file.Y[1]
0.627145631592811
>>> cm_file.BM[1]
0.627145631592811
>>> cm_file.transpose
True
>>> cm.matrix == cm_file.matrix
True
>>> cm.normalized_matrix == cm_file.normalized_matrix
True
>>> json.dump({"Actual-Vector": None, "Digit": 5, "Predict-Vector": None, "Matrix": {"0": {"0": 3, "1": 0, "2": 2}, "1": {"0": 0, "1": 1, "2": 1}, "2": {"0": 0, "1": 2, "2": 3}}, "Transpose": True,"Sample-Weight": None},open("test5.obj","w"))
>>> cm_file=ConfusionMatrix(file=open("test5.obj","r"))
>>> cm_file.transpose
True
>>> cm_file.matrix == {"0": {"0": 3, "1": 0, "2": 2}, "1": {"0": 0, "1": 1, "2": 1}, "2": {"0": 0, "1": 2, "2": 3}}
True
>>> json.dump({"Actual-Vector": None, "Digit": 5, "Predict-Vector": None, "Matrix": {"0": {"0": 3, "1": 0, "2": 2}, "1": {"0": 0, "1": 1, "2": 1}, "2": {"0": 0, "1": 2, "2": 3}}},open("test6.obj","w"))
>>> cm_file=ConfusionMatrix(file=open("test6.obj","r"))
>>> cm_file.weights
>>> cm_file.transpose
False
>>> cm_file.matrix == {'1': {'1': 1, '2': 1, '0': 0}, '2': {'1': 2, '2': 3, '0': 0}, '0': {'1': 0, '2': 2, '0': 3}}
True
>>> json.dump({"Actual-Vector": ['1', '1', '2', '2', '2', '2', '2', '0', '0', '0', '0', '0'], "Digit": 5, "Predict-Vector": ['1', '2', '1', '1', '2', '2', '2', '2', '2', '0', '0', '0'], "Matrix": {"0": {"0": 3, "1": 0, "2": 2}, "1": {"0": 0, "1": 1, "2": 1}, "2": {"0": 0, "1": 2, "2": 3}}},open("test7.obj","w"))
>>> cm_file=ConfusionMatrix(file=open("test7.obj","r"))
>>> cm_file.weights
>>> cm_file.transpose
False
>>> cm_file.matrix == {'1': {'1': 1, '2': 1, '0': 0}, '2': {'1': 2, '2': 3, '0': 0}, '0': {'1': 0, '2': 2, '0': 3}}
True
>>> cm_file.actual_vector == ['1', '1', '2', '2', '2', '2', '2', '0', '0', '0', '0', '0']
True
>>> cm_file.predict_vector == ['1', '2', '1', '1', '2', '2', '2', '2', '2', '0', '0', '0']
True
>>> cm_comp1 = ConfusionMatrix(matrix={0:{0:2,1:50,2:6},1:{0:5,1:50,2:3},2:{0:1,1:7,2:50}})
>>> cm_comp2 = ConfusionMatrix(matrix={0:{0:50,1:2,2:6},1:{0:50,1:5,2:3},2:{0:1,1:55,2:2}})
>>> cp = Compare({"model1":cm_comp1,"model2":cm_comp2})
>>> save_report = cp.save_report("test",address=False)
>>> save_report == {'Status': True, 'Message': None}
True
>>> save_report = cp.save_report("/asdasd,qweqwe.eo/",address=False)
>>> save_report == {'Status': False, 'Message': "[Errno 2] No such file or directory: '/asdasd,qweqwe.eo/.comp'"}
True
>>> os.remove("test.csv")
>>> os.remove("test_matrix.csv")
>>> os.remove("test_normalized.csv")
>>> os.remove("test_normalized_matrix.csv")
>>> os.remove("test.obj")
>>> os.remove("test_stat.obj")
>>> os.remove("test_no_vectors.obj")
>>> os.remove("test.html")
>>> os.remove("test_normalized.html")
>>> os.remove("test_filtered.html")
>>> os.remove("test_filtered.csv")
>>> os.remove("test_filtered_matrix.csv")
>>> os.remove("test_filtered.pycm")
>>> os.remove("test_large.pycm")
>>> os.remove("test_summary.pycm")
>>> os.remove("test_filtered2.html")
>>> os.remove("test_filtered3.html")
>>> os.remove("test_filtered4.html")
>>> os.remove("test_filtered5.html")
>>> os.remove("test_long_name.html")
>>> os.remove("test_alt.html")
>>> os.remove("test_summary.html")
>>> os.remove("test_colored.html")
>>> os.remove("test_colored2.html")
>>> os.remove("test_filtered2.csv")
>>> os.remove("test_filtered3.csv")
>>> os.remove("test_filtered4.csv")
>>> os.remove("test_summary.csv")
>>> os.remove("test_filtered2.pycm")
>>> os.remove("test_filtered3.pycm")
>>> os.remove("test2.obj")
>>> os.remove("test3.obj")
>>> os.remove("test3_np.obj")
>>> os.remove("test4.obj")
>>> os.remove("test5.obj")
>>> os.remove("test6.obj")
>>> os.remove("test7.obj")
>>> os.remove("test.pycm")
>>> os.remove("test.comp")
"""
|
{
"alphanum_fraction": 0.3923435457,
"author": null,
"avg_line_length": 69.8134920635,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "0a1bfa92caaec4fa605865e63129300af71d8dd9",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f7e2a68b50cdf01492c889fc7a01763ea628c967",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "robinsonkwame/pycm",
"max_forks_repo_path": "Test/output_test.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f7e2a68b50cdf01492c889fc7a01763ea628c967",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "robinsonkwame/pycm",
"max_issues_repo_path": "Test/output_test.py",
"max_line_length": 313,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f7e2a68b50cdf01492c889fc7a01763ea628c967",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "robinsonkwame/pycm",
"max_stars_repo_path": "Test/output_test.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7914,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 35186
}
|
# Copyright 2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# 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.
import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import cv2 as cv
import numpy as np
class ExponentialMovingAverage():
def __init__(self, decay):
self.decay = decay
self.shadow_variable = nn.NdArray()
def register(self, val):
self.shadow_variable.copy_from(val)
def __call__(self, variable):
self.shadow_variable.copy_from(
self.decay * self.shadow_variable + (1.0 - self.decay) * variable)
return self.shadow_variable.data
def save_img(out_path, img):
img = np.clip(img*255.0, 0, 255).astype(np.uint8)
cv.imwrite(out_path, img[:, :, ::-1])
def deprocess(image):
# [-1, 1] => [0, 1]
return (image + 1) / 2
def warp_by_flow(data, flow):
"""
Warp by flow implementation equivalent to TF's tfa.image.dense_image_warp()
"""
flow = -flow[:, :, :, ::-
1] # Flow direction changed and it's channel's order is reversed
warp_data = F.warp_by_flow(F.transpose(data, (0, 3, 1, 2)), F.transpose(
flow, (0, 3, 1, 2))) # Apply NNabla's Warping after converting NHWC ==> NCHW format
warp_data = F.transpose(warp_data, (0, 2, 3, 1)) # NCHW ==> NHWC format
return warp_data
def space_to_depth(input):
"""
Apply space-to-depth transform
input : nn.Variable of shape (B, H*4, W*4, 3)
output : nn.Variable of shape (B, H, W, 3*4*4)
"""
batch, height, width, depth = input.shape
output = F.reshape(
input, (batch, height/4, 4, width/4, 4, depth), inplace=False)
output = F.reshape(F.transpose(output, (0, 1, 3, 2, 4, 5)),
(batch, height/4, width/4, -1), inplace=False)
return output
def space_to_depth_disc(input, t_batch, inplace=False):
if input.ndim == 4:
batch, height, width, depth = input.shape
if input.ndim == 5:
batch, f, height, width, depth = input.shape
output = F.reshape(
input, (t_batch, 3, height, width, depth), inplace=inplace)
output = F.reshape(F.transpose(output, (0, 2, 3, 4, 1)),
(t_batch, height, width, 3*3), inplace=False)
return output
def upscale_four(inputs, scope='upscale_four'):
"""
Mimic the tensorflow bilinear-upscaling for a fix ratio of 4.
"""
with nn.parameter_scope(scope):
b, h, w, c = inputs.shape
p_inputs = F.concatenate(
inputs, inputs[:, -1:, :, :], axis=1) # pad bottom
p_inputs = F.concatenate(
p_inputs, p_inputs[:, :, -1:, :], axis=2) # pad right
hi_res_bin = [
[
inputs, # top-left
p_inputs[:, :-1, 1:, :] # top-right
],
[
p_inputs[:, 1:, :-1, :], # bottom-left
p_inputs[:, 1:, 1:, :] # bottom-right
]
]
hi_res_array = []
for hi in range(4):
for wj in range(4):
hi_res_array.append(
hi_res_bin[0][0] *
(1.0 - 0.25 * hi) * (1.0 - 0.25 * wj)
+ hi_res_bin[0][1] * (1.0 - 0.25 * hi) * (0.25 * wj)
+ hi_res_bin[1][0] * (0.25 * hi) * (1.0 - 0.25 * wj)
+ hi_res_bin[1][1] * (0.25 * hi) * (0.25 * wj)
)
hi_res = F.stack(*hi_res_array, axis=3) # shape (b,h,w,16,c)
hi_res_reshape = F.reshape(hi_res, (b, h, w, 4, 4, c))
hi_res_reshape = F.transpose(hi_res_reshape, (0, 1, 3, 2, 4, 5))
hi_res_reshape = F.reshape(hi_res_reshape, (b, h*4, w*4, c))
return hi_res_reshape
def bicubic_four(inputs, scope='bicubic_four'):
"""
Equivalent to tf.image.resize_bicubic( inputs, (h*4, w*4) ) for a fix ratio of 4 FOR API <=1.13
For API 2.0, tf.image.resize_bicubic will be different, old version is tf.compat.v1.image.resize_bicubic
**Parallel Catmull-Rom Spline Interpolation Algorithm for Image Zooming Based on CUDA*[Wu et. al.]**
"""
with nn.parameter_scope(scope):
b, h, w, c = inputs.shape
p_inputs = F.concatenate(
inputs[:, :1, :, :], inputs, axis=1) # pad top
p_inputs = F.concatenate(
p_inputs[:, :, :1, :], p_inputs, axis=2) # pad left
p_inputs = F.concatenate(
p_inputs, p_inputs[:, -1:, :, :], p_inputs[:, -1:, :, :], axis=1) # pad bottom
p_inputs = F.concatenate(
p_inputs, p_inputs[:, :, -1:, :], p_inputs[:, :, -1:, :], axis=2) # pad right
hi_res_bin = [p_inputs[:, bi:bi+h, :, :] for bi in range(4)]
r = 0.75
mat = np.float32([[0, 1, 0, 0], [-r, 0, r, 0],
[2*r, r-3, 3-2*r, -r], [-r, 2-r, r-2, r]])
weights = [np.float32([1.0, t, t*t, t*t*t]).dot(mat)
for t in [0.0, 0.25, 0.5, 0.75]]
hi_res_array = [] # [hi_res_bin[1]]
for hi in range(4):
cur_wei = weights[hi]
cur_data = cur_wei[0] * hi_res_bin[0] + cur_wei[1] * hi_res_bin[1] + \
cur_wei[2] * hi_res_bin[2] + cur_wei[3] * hi_res_bin[3]
hi_res_array.append(cur_data)
hi_res_y = F.stack(*hi_res_array, axis=2) # shape (b,h,4,w,c)
hi_res_y = F.reshape(hi_res_y, (b, h*4, w+3, c))
hi_res_bin = [hi_res_y[:, :, bj:bj+w, :] for bj in range(4)]
hi_res_array = [] # [hi_res_bin[1]]
for hj in range(4):
cur_wei = weights[hj]
cur_data = cur_wei[0] * hi_res_bin[0] + cur_wei[1] * hi_res_bin[1] + \
cur_wei[2] * hi_res_bin[2] + cur_wei[3] * hi_res_bin[3]
hi_res_array.append(cur_data)
hi_res = F.stack(*hi_res_array, axis=3) # shape (b,h*4,w,4,c)
hi_res = F.reshape(hi_res, (b, h*4, w*4, c))
return hi_res
|
{
"alphanum_fraction": 0.5571362301,
"author": null,
"avg_line_length": 37.1666666667,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "cdc4829448c54ddb4ce23db0a831e882d4778d27",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 76,
"max_forks_repo_forks_event_max_datetime": "2022-03-28T05:58:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-22T22:00:00.000Z",
"max_forks_repo_head_hexsha": "db9e5ad850303c158773aeb275e5c3821b4a3935",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "AaratiAkkapeddi/nnabla-examples",
"max_forks_repo_path": "video-superresolution/tecogan/utils/utils.py",
"max_issues_count": 36,
"max_issues_repo_head_hexsha": "db9e5ad850303c158773aeb275e5c3821b4a3935",
"max_issues_repo_issues_event_max_datetime": "2022-03-12T00:53:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-11T23:26:20.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "AaratiAkkapeddi/nnabla-examples",
"max_issues_repo_path": "video-superresolution/tecogan/utils/utils.py",
"max_line_length": 108,
"max_stars_count": 228,
"max_stars_repo_head_hexsha": "db9e5ad850303c158773aeb275e5c3821b4a3935",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "AaratiAkkapeddi/nnabla-examples",
"max_stars_repo_path": "video-superresolution/tecogan/utils/utils.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-23T12:40:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-11-20T06:05:56.000Z",
"num_tokens": 1960,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 6467
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test to find CNN accuracy, precision, and recall
By: Austin Schwinn, Jérémie Blanchard, and Oussama Bouldjedri.
MLDM Master's Year 2
Fall Semester 2017
"""
import sys
import argparse
import numpy as np
from PIL import Image
import requests
from io import BytesIO
import matplotlib.pyplot as plt
import cv2
import pandas as pd
import os
import xml.etree.ElementTree as ET
from keras.preprocessing import image
from keras.models import load_model
from keras.applications.inception_v3 import preprocess_input
#%%
'''
Classes=["areoplane","bycicle","bird","boat","bottle","bus","car","cat","chair",
"cow","digningtable","dog","horse","motorbike","person","pottedplant","sheep",
"sofa","train","TVmonitor"]
'''
#Set arguments
target_size = (299, 299) #fixed size for InceptionV3 architecture
threshold = .5
Classes = os.listdir('D:/GD/MLDM/Computer_Vision_Project/cnn5/data/training')
model = 'D:/GD/MLDM/Computer_Vision_Project/github/cvp_cnn_sigmoid_10_10.model'
model = load_model(model)
test_dir = 'D:/GD/MLDM/Computer_Vision_Project/Data/test_VOC2007/JPEGImages/'
test_ann_dir = "D:/GD/MLDM/Computer_Vision_Project/Data/test_VOC2007/Annotations2/"
#%%
def predict(model, img, target_size):
"""Run model prediction on image
Args:
model: keras model
img: PIL format image
target_size: (w,h) tuple
Returns:
list of predicted labels and their probabilities
"""
if img.size != target_size:
img = img.resize(target_size)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
return preds[0]
#%%
def plot_preds(image, preds):
"""Displays image and the top-n predicted probabilities in a bar graph
Args:
image: PIL image
preds: list of predicted labels and their probabilities
"""
plt.imshow(image)
plt.axis('off')
plt.figure()
labels = ("cat", "dog")
plt.barh([0, 1], preds, alpha=0.5)
plt.yticks([0, 1], labels)
plt.xlabel('Probability')
plt.xlim(0,1.01)
plt.tight_layout()
plt.show()
#%%
#Get all test images
test_imgs = os.listdir(test_dir)
test_anns = os.listdir(test_ann_dir)
pred_class = pd.DataFrame(index=Classes)
true_class = pd.DataFrame(index=Classes)
#Iterate and get prediction and correct class tables
for img_name in test_imgs:
img_name = img_name[:-4]
#Ensure we have correct label values
if (img_name+'.xml') in test_anns:
#Load image
img = Image.open(test_dir+img_name+'.jpg')
#Predict labels
preds = predict(model, img, target_size)
#Percent of total prediction by each object type
percent_pred = []
for i in preds:
percent_pred = percent_pred + [(i/np.sum(preds))]
#combine percents with labels
percent_pred = pd.DataFrame(percent_pred, index=Classes, columns=[img_name])
pred_class = pred_class.join(percent_pred)
print(img_name)
#Get correct labels
tree = ET.parse(test_ann_dir + img_name + '.xml')
root = tree.getroot()
class_names = []
for child in root:
if child.tag == "object":
obj_name = child.find("name").text
if obj_name not in class_names:
class_names += [obj_name]
#Create one hot encoding
one_hot = pd.DataFrame(np.repeat(0,20),index=Classes,columns=[img_name])
for class_name in class_names:
one_hot.loc[class_name,img_name] = 1
true_class = true_class.join(one_hot)
#%%%
#pred_class_backup = pred_class.copy()
pred_class = pred_class_backup.copy()
#%%
pred_class.iloc[0:20,0:20]
true_class.iloc[0:20,0:20]
#%%
#Perfect of total prediction by class
for col in pred_class.columns:
col_sum = pred_class.loc[:,col].sum()
for row in pred_class.index:
pred_val = pred_class.loc[row,col].astype('float64')
pred_class.loc[row,col] = pred_val/col_sum
'''
if pred_val == 0:
pred_class.loc[row,col] = 0
else:
pred_class.loc[row,col] = pred_val/col_sum
'''
#%%
results = pd.DataFrame(columns=['tp','fn','tn','fn','acc','prec',
'rec'])
for i in range(1,15,1):
#pred_class_backup2 = pred_class.copy()
pred_class = pred_class_backup2.copy()
#Use threshold to create binary classifications
threshold = i/100
print(threshold)
for col in pred_class.columns:
for row in pred_class.index:
if pred_class.loc[row,col] >= threshold:
#if pred_class.loc[row,col] != 0:
pred_class.loc[row,col] = 1
else:
pred_class.loc[row,col] = 0
pred_class = pred_class.astype('int')
#Compare predictions vs true labels
tp = 0
fp = 0
tn = 0
fn = 0
for y in pred_class.index:
for x in pred_class.columns:
true_val = true_class.loc[y,x]
pred_val = pred_class.loc[y,x]
if ((true_val==1) & (pred_val==1)):
tp += 1
elif ((true_val==0) & (pred_val==1)):
fp += 1
elif ((true_val==1) & (pred_val==0)):
fn += 1
elif ((true_val==0) & (pred_val==0)):
tn += 1
#Store results
results.loc[threshold,'tp'] = tp
results.loc[threshold,'fp'] = fp
results.loc[threshold,'tn'] = tn
results.loc[threshold,'fn'] = fn
results.loc[threshold,'acc'] = ((tp+tn)/(tp+fp+tn+fn))
results.loc[threshold,'prec'] = (tp/(tp+fp))
results.loc[threshold,'rec'] = (tp/(tp+fn))
print(tp)
print(fp)
print(tn)
print(fn)
#Accuracy, precision, recall
print((tp+tn)/(tp+fp+tn+fn))
print(tp/(tp+fp))
print(tp/(tp+fn))
print('#######################################')
results.to_csv('NN_results.csv')
#%%
'''
if __name__=="__main__":
a = argparse.ArgumentParser()
a.add_argument("--image", help="path to image")
a.add_argument("--image_url", help="url to image")
a.add_argument("--model")
args = a.parse_args()
if args.image is None and args.image_url is None:
a.print_help()
sys.exit(1)
model = load_model(args.model)
if args.image is not None:
img = Image.open(args.image)
preds = predict(model, img, target_size)
print(preds)
print()
#objs = os.listdir('/home/dell1/Desktop/cnn5/data/training')
objs=Classes
#print("objects are",objs)
#Percent of total prediction by each object type
percent_pred = []
for i in preds:
percent_pred = percent_pred + [(i/np.sum(preds))]
print(percent_pred)
print()
print()
#combine percents with labels
#percent_pred = pd.DataFrame(percent_pred[0], index=objs)
result=np.column_stack((percent_pred,objs))
print(result)
print()
print(result[np.lexsort(np.fliplr(result).T)])
#plot_preds(img, preds)
#ind=np.argmax(preds)
#print("there is a probability of ",preds[ind]*100)
#print(" this object is from the class",Classes[ind])
#orig = cv2.imread(args.image)
#(imagenetID, label, prob) =
#label=Classes[ind]
#prob=preds[ind]*100
#cv2.putText(orig, "Label: {}, {:.2f}%".format(label, prob),
#(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
#cv2.imshow("Classification", orig)
#cv2.waitKey(0)
if args.image_url is not None:
response = requests.get(args.image_url)
img = Image.open(BytesIO(response.content))
preds = predict(model, img, target_size)
plot_preds(img, preds)
'''
|
{
"alphanum_fraction": 0.6173811983,
"author": null,
"avg_line_length": 29.0037453184,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "366052ebf7aa0948aad5d6a7bc6cc146b248c4fc",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f34d32c987237291335d880db544ca986d16c507",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "amschwinn/computer_vision_project",
"max_forks_repo_path": "Training Scripts/NN_test.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f34d32c987237291335d880db544ca986d16c507",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "amschwinn/computer_vision_project",
"max_issues_repo_path": "Training Scripts/NN_test.py",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f34d32c987237291335d880db544ca986d16c507",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "amschwinn/computer_vision_project",
"max_stars_repo_path": "Training Scripts/NN_test.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2040,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 7744
}
|
#!/usr/bin/python
'''
Note:
The repeated use of CvBridge (instead of using make_image_msg and get_image_msg in the classes)
is intentional, to avoid the use of a global cvbridge, and to avoid reinstantiating a CvBrige for each use.
'''
import rospy
import numpy as np
from os import path
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image, CameraInfo
from mil_ros_tools import wait_for_param
import message_filters
from image_geometry import PinholeCameraModel
def get_parameter_range(parameter_root):
'''
ex: parameter_root='/vision/buoy/red'
this will then fetch /vision/buoy/red/hsv_low and hsv_high
'''
low_param, high_param = parameter_root + \
'/hsv_low', parameter_root + '/hsv_high'
rospy.logwarn(
"Blocking -- waiting for parameters {} and {}".format(low_param, high_param))
wait_for_param(low_param)
wait_for_param(high_param)
low = rospy.get_param(low_param)
high = rospy.get_param(high_param)
rospy.loginfo("Got {} and {}".format(low_param, high_param))
return np.array([low, high]).transpose()
def make_image_msg(cv_image, encoding='bgr8'):
'''Take a cv image, and produce a ROS image message'''
bridge = CvBridge()
image_message = bridge.cv2_to_imgmsg(cv_image, encoding)
return image_message
def get_image_msg(ros_image, encoding='bgr8'):
'''Take a ros image message, and yield an opencv image'''
bridge = CvBridge()
cv_image = bridge.imgmsg_to_cv2(ros_image, desired_encoding=encoding)
return cv_image
class Image_Publisher(object):
def __init__(self, topic, encoding="bgr8", queue_size=1):
'''Create an essentially normal publisher, that will publish images without conversion hassle'''
self.bridge = CvBridge()
self.encoding = encoding
self.im_pub = rospy.Publisher(topic, Image, queue_size=queue_size)
def publish(self, cv_image):
try:
image_message = self.bridge.cv2_to_imgmsg(cv_image, self.encoding)
self.im_pub.publish(image_message)
except CvBridgeError, e:
# Intentionally absorb CvBridge Errors
rospy.logerr(e)
class Image_Subscriber(object):
def __init__(self, topic, callback=None, encoding="bgr8", queue_size=1):
'''Calls $callback on each image every time a new image is published on $topic
Assumes topic of type "sensor_msgs/Image"
This behaves like a conventional subscriber, except handling the additional image conversion
'''
if callback is None:
def callback(im):
return setattr(self, 'last_image', im)
self.encoding = encoding
self.camera_info = None
self.last_image_header = None
self.last_image_time = None
self.last_image = None
self.im_sub = rospy.Subscriber(
topic, Image, self.convert, queue_size=queue_size)
root_topic, image_subtopic = path.split(rospy.remap_name(topic))
self.info_sub = rospy.Subscriber(
root_topic + '/camera_info', CameraInfo, self.info_cb, queue_size=queue_size)
self.bridge = CvBridge()
self.callback = callback
def wait_for_camera_info(self, timeout=10):
'''
Blocks until camera info has been received.
Note: 'timeout' is in seconds.
'''
rospy.logwarn(
"Blocking -- waiting at most %d seconds for camera info." % timeout)
timeout = rospy.Duration(timeout)
rospy.sleep(.1) # Make sure we don't have negative time
start_time = rospy.Time.now()
while (rospy.Time.now() - start_time < timeout) and (not rospy.is_shutdown()):
if self.camera_info is not None:
rospy.loginfo("Camera info found!")
return self.camera_info
rospy.sleep(.2)
rospy.logerr("Camera info not found.")
raise Exception("Camera info not found.")
def wait_for_camera_model(self, **kwargs):
info_msg = self.wait_for_camera_info(**kwargs)
model = PinholeCameraModel()
model.fromCameraInfo(info_msg)
return model
def info_cb(self, msg):
"""The path trick here is a hack"""
self.info_sub.unregister()
self.camera_info = msg
def convert(self, data):
self.last_image_header = data.header
self.last_image_time = data.header.stamp
try:
image = self.bridge.imgmsg_to_cv2(
data, desired_encoding=self.encoding)
self.callback(image)
except CvBridgeError, e:
# Intentionally absorb CvBridge Errors
rospy.logerr(e)
class StereoImageSubscriber(object):
'''
Abstraction to subscribe to two image topics (ex: left and right camera) and
receive callbacks for synchronized images (already converted to numpy arrays).
Also contains a helper function to block until the camera info messages for both
cameras are received.
'''
def __init__(self, left_image_topic, right_image_topic, callback=None, slop=None, encoding="bgr8", queue_size=10):
'''
Contruct a StereoImageSubscriber
@param left_image_topic: ROS topic to subscribe for the left camera
ex: /camera/front/left/image_rect_color
@param right_image_topic: ROS topic to subscribe to for the right camera
ex: /camera/front/right/image_rect_color
@param callback: Function with signature foo(left_img, right_img) to call when a synchronized pair is ready.
If left as None, the latest synced images are stored as self.last_image_left and self.last_image_right
@param slop: Maximum time in seconds between left and right images to be considered synced.
If left as None, will only consider synced if left and right images have exact same header time.
@param encoding: String to pass to CvBridge to encode ROS image message to numpy array
@param queue_size: Integer, the number of images to store in a buffer for each camera to find synced images
'''
if callback is None: # Set default callback to just set image_left and image_right
def callback(image_left, image_right):
setattr(self, 'last_image_left', image_left)
setattr(self, 'last_image_right', image_right)
self.bridge = CvBridge()
self.encoding = encoding
self.callback = callback
self.camera_info_left = None
self.camera_info_right = None
self.last_image_left = None
self.last_image_time_left = None
self.last_image_right = None
self.last_image_time_right = None
# Subscribe to image and camera info topics for both cameras
root_topic_left, image_subtopic_left = path.split(left_image_topic)
self._info_sub_left = rospy.Subscriber(
root_topic_left + '/camera_info', CameraInfo,
lambda info: setattr(self, 'camera_info_left', info), queue_size=queue_size)
image_sub_left = message_filters.Subscriber(left_image_topic, Image)
root_topic_right, image_subtopic_right = path.split(right_image_topic)
self._info_sub_right = rospy.Subscriber(
root_topic_right + '/camera_info', CameraInfo,
lambda info: setattr(self, 'camera_info_right', info), queue_size=queue_size)
image_sub_right = message_filters.Subscriber(right_image_topic, Image)
# Use message_filters library to set up synchronized subscriber to both image topics
if slop is None:
self._image_sub = message_filters.TimeSynchronizer([image_sub_left, image_sub_right], queue_size)
else:
self._image_sub = message_filters.ApproximateTimeSynchronizer([image_sub_left, image_sub_right],
queue_size, slop)
self._image_sub.registerCallback(self._image_callback)
def wait_for_camera_info(self, timeout=10, unregister=True):
'''
Blocks until camera info has been received.
@param timeout: Time in seconds to wait before throwing exception if camera info is not received
@param unregister: Boolean, if True will unsubscribe to camera info after receiving initial info message,
so self.camera_info_left and self.camera_info_right will not be updated
@return: Tuple(camera_info_left, camera_info_right) camera info for each camera if received before timeout
@raise Exception: if camera info for both cameras is not received within timeout
'''
timeout = rospy.Time.now() + rospy.Duration(timeout)
while (rospy.Time.now() < timeout) and (not rospy.is_shutdown()):
if self.camera_info_left is not None and self.camera_info_right is not None:
if unregister:
self._info_sub_left.unregister()
self._info_sub_right.unregister()
return self.camera_info_left, self.camera_info_right
rospy.sleep(0.05)
if self.camera_info_left is not None and self.camera_info_right is not None:
if unregister:
self._info_sub_left.unregister()
self._info_sub_right.unregister()
return self.camera_info_left, self.camera_info_right
raise Exception("Camera info not found.")
def _image_callback(self, left_img, right_img):
'''
Internal wrapper around image callback. Updates
latest timestamps and converts ROS image messages
to numpy arrays (for use with OpenCV, etc) before
calling user defined callback.
@param left_img: the synchronized image from the left camera
@param right_img: the synchronized image from the right camera
'''
try:
self.last_image_time_left = left_img.header.stamp
self.last_image_time_right = right_img.header.stamp
img_left = self.bridge.imgmsg_to_cv2(
left_img, desired_encoding=self.encoding)
img_right = self.bridge.imgmsg_to_cv2(
right_img, desired_encoding=self.encoding)
self.callback(img_left, img_right)
except CvBridgeError, e:
# Intentionally absorb CvBridge Errors
rospy.logerr(e)
|
{
"alphanum_fraction": 0.6675289834,
"author": null,
"avg_line_length": 43.6694560669,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "4d3d01bf36e2121ab2560058a1dd5a33c85cc95c",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 24,
"max_forks_repo_forks_event_max_datetime": "2022-03-06T10:56:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-16T00:29:45.000Z",
"max_forks_repo_head_hexsha": "0952376fe74fb84d1db2bbe89d014db57550183e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Burtt/mil_common",
"max_forks_repo_path": "utils/mil_tools/mil_ros_tools/image_helpers.py",
"max_issues_count": 325,
"max_issues_repo_head_hexsha": "0952376fe74fb84d1db2bbe89d014db57550183e",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T00:38:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-11T14:13:56.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Burtt/mil_common",
"max_issues_repo_path": "utils/mil_tools/mil_ros_tools/image_helpers.py",
"max_line_length": 118,
"max_stars_count": 27,
"max_stars_repo_head_hexsha": "0952376fe74fb84d1db2bbe89d014db57550183e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Burtt/mil_common",
"max_stars_repo_path": "utils/mil_tools/mil_ros_tools/image_helpers.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T17:49:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-17T21:54:09.000Z",
"num_tokens": 2162,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 10437
}
|
{-|
Copyright : (C) 2019, Google Inc.
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <christiaan.baaij@gmail.com>
-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-- {-# OPTIONS_GHC -ddump-splices #-}
module Clash.Class.AutoReg.Instances where
import Clash.Class.AutoReg.Internal
import Clash.CPP (maxTupleSize)
import Data.Complex (Complex)
import Data.Ord (Down)
import Data.Ratio (Ratio)
deriveAutoReg ''Complex
deriveAutoReg ''Down
deriveAutoReg ''Ratio
-- | __N.B.__: The documentation only shows instances up to /3/-tuples. By
-- default, instances up to and including /12/-tuples will exist. If the flag
-- @large-tuples@ is set instances up to the GHC imposed limit will exist. The
-- GHC imposed limit is either 62 or 64 depending on the GHC version.
deriveAutoRegTuples [2..maxTupleSize]
|
{
"alphanum_fraction": 0.6734258271,
"author": null,
"avg_line_length": 32.3103448276,
"converted": null,
"ext": "hs",
"file": null,
"hexsha": "910b2bf1ad47edd6eb784d8684bcdfdcb134bc35",
"include": null,
"lang": "Haskell",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 135,
"max_forks_repo_forks_event_max_datetime": "2022-03-17T17:02:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-20T09:09:45.000Z",
"max_forks_repo_head_hexsha": "6791bc99f97a531eca481635ca87eb1bb2bf14b6",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "oliverbunting/clash-compiler",
"max_forks_repo_path": "clash-prelude/src/Clash/Class/AutoReg/Instances.hs",
"max_issues_count": 1197,
"max_issues_repo_head_hexsha": "6791bc99f97a531eca481635ca87eb1bb2bf14b6",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T11:53:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-03-11T08:49:27.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "oliverbunting/clash-compiler",
"max_issues_repo_path": "clash-prelude/src/Clash/Class/AutoReg/Instances.hs",
"max_line_length": 78,
"max_stars_count": 1151,
"max_stars_repo_head_hexsha": "6791bc99f97a531eca481635ca87eb1bb2bf14b6",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "oliverbunting/clash-compiler",
"max_stars_repo_path": "clash-prelude/src/Clash/Class/AutoReg/Instances.hs",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T04:19:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-13T18:48:16.000Z",
"num_tokens": 244,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 937
}
|
! Fortran code for computing response spectra.
! Originial version is writting by: Leonardo Ramirez-Guzman
! The code base is tailored for F2py.
!
subroutine max_osc_response(acc, npts, dt, period, csi, max_disp, &
max_vel, max_acc)
implicit none
integer, intent(in) :: npts
real, intent(in) :: acc(npts)
real :: a(npts), v(npts), d(npts)
real, intent(in) :: dt, period, csi
real, intent(out) :: max_disp, max_vel, max_acc
integer :: i=1
real, parameter :: PI = 3.14159265359
real :: w, ww, csicsi, dcsiw, rcsi, csircs, wd, ueskdt, dcsiew, um2csi, e, &
s, c0, ca, cb, cc, cd, cap, cbp, ccp, cdp
d(1) = 0.
v(1) = 0.
w = (2*PI)/period
ww = w ** 2
csicsi = csi ** 2
dcsiw = 2. * csi * w
rcsi = sqrt(1-csicsi)
csircs = csi/rcsi
wd = w * rcsi
ueskdt = -1/(ww*dt)
dcsiew = 2 * csi / w
um2csi = (1.-2*csicsi)/wd
e=exp(-w*dt*csi)
s=sin(wd*dt)
c0=cos(wd*dt)
a(1) = -ww*d(1)-dcsiw*v(1)
ca = e * (csircs*s+c0)
cb = e * s/wd
cc = (e*((um2csi-csircs*dt)*s -(dcsiew+dt)*c0)+dcsiew)*ueskdt
cd = (e*(-um2csi*s+dcsiew*c0)+dt-dcsiew)*ueskdt
cap = -cb * ww
cbp = e * (c0-csircs*s)
ccp = (e*((w*dt/rcsi+csircs)*s+c0)-1.)*ueskdt
cdp = (1.-ca)*ueskdt
do i=2,npts
d(i) = ca*d(i-1)+cb*v(i-1)+cc*acc(i-1)+cd*acc(i)
v(i) = cap*d(i-1)+cbp*v(i-1)+ccp*acc(i-1)+cdp*acc(i)
a(i) = -ww*d(i)-dcsiw*v(i)
end do
max_disp = 0
max_vel = 0
max_acc = 0
do i=1,npts
if (abs(a(i)) .gt. max_acc) then
max_acc = abs(a(i))
end if
end do
do i=1,npts
if (abs(v(i)) .gt. max_vel) then
max_vel = abs(v(i))
end if
end do
do i=1,npts
if (abs(d(i)) .gt. max_disp) then
max_disp = abs(d(i))
end if
end do
end subroutine max_osc_response
subroutine calc_response(acc, npts, dt, periods, n_prds,csi, max_disps, &
max_vels, max_accs)
implicit none
integer, intent(in) :: npts, n_prds
real, intent(in) :: acc(npts)
real, intent(in) :: dt, csi
real, intent(in) :: periods(n_prds)
real, intent(out) :: max_disps(n_prds), max_vels(n_prds), max_accs(n_prds)
integer :: i=1
do i=1,n_prds
call max_osc_response(acc, npts, dt, periods(i), csi, max_disps(i),&
max_vels(i), max_accs(i))
end do
end subroutine calc_response
|
{
"alphanum_fraction": 0.5533223954,
"author": null,
"avg_line_length": 25.1340206186,
"converted": null,
"ext": "f95",
"file": null,
"hexsha": "a729ded4fccd7ae7e800fae9a3f79c3035a11854",
"include": null,
"lang": "FORTRAN",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "7947e2cc6e10be37664054ed63fa2aa836717f99",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Naeemkh/tsprocess",
"max_forks_repo_path": "tsprocess/fsc/rsp.f95",
"max_issues_count": 40,
"max_issues_repo_head_hexsha": "7947e2cc6e10be37664054ed63fa2aa836717f99",
"max_issues_repo_issues_event_max_datetime": "2020-09-13T20:37:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-16T15:08:39.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Naeemkh/ts-process",
"max_issues_repo_path": "tsprocess/fsc/rsp.f95",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7947e2cc6e10be37664054ed63fa2aa836717f99",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Naeemkh/ts-process",
"max_stars_repo_path": "tsprocess/fsc/rsp.f95",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 951,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 2438
}
|
using DiffEqFlux, Flux
abstract type AffineSystem <: Ode end
""" dxdt = Ax + Bu + ν
AffineOde """
struct AffineOde{FU,F2} <: AffineSystem
state_dim::Int
input_dim::Int
paramsum::Int
index_dict::Dict{String,UnitRange{Int}}
σ_u::FU
initial_params::F2
function AffineOde(
state_dim::Integer,
input_dim::Integer;
initW = Flux.glorot_uniform,
initb = Flux.zeros,
σ_u = identity,
)
# compute indices
i = 1
index_dict = Dict{String,UnitRange{Int}}()
index_dict["A"] = i:i+state_dim*state_dim-1
i += state_dim * state_dim
index_dict["B"] = i:i+input_dim*state_dim-1
i += input_dim * state_dim
index_dict["ν"] = i:i+state_dim-1
i += state_dim
# initialize initial parameters
initial_params() = vcat(
vec(initW(state_dim, state_dim)),
vec(initW(state_dim, input_dim)),
vec(initb(state_dim)),
)
new{typeof(σ_u),typeof(initial_params)}(
state_dim,
input_dim,
i - 1,
index_dict,
σ_u,
initial_params,
)
end
end
function unpack_params(f::AffineOde, p)
A = reshape(view(p, f.index_dict["A"]), f.state_dim, f.state_dim)
B = reshape(view(p, f.index_dict["B"]), f.state_dim, f.input_dim)
ν = view(p, f.index_dict["ν"])
return A, B, ν
end
function (f::AffineOde)(xu, p)
x, u = extract_inputs(f, xu)
A, B, ν = unpack_params(f, p)
return A * x .+ B * f.σ_u.(u) .+ ν
end
""" dxdt = Ax + Bu
LinearOde """
struct LinearOde{FU,F2} <: AffineSystem
state_dim::Int
input_dim::Int
paramsum::Int
index_dict::Dict{String,UnitRange{Int}}
σ_u::FU
initial_params::F2
function LinearOde(
state_dim::Integer,
input_dim::Integer;
initW = Flux.glorot_uniform,
σ_u = identity,
)
# compute indices
i = 1
index_dict = Dict{String,UnitRange{Int}}()
index_dict["A"] = i:i+state_dim*state_dim-1
i += state_dim * state_dim
index_dict["B"] = i:i+input_dim*state_dim-1
i += input_dim * state_dim
# initialize initial parameters
initial_params() =
vcat(vec(initW(state_dim, state_dim)), vec(initW(state_dim, input_dim)))
new{typeof(σ_u),typeof(initial_params)}(
state_dim,
input_dim,
i - 1,
index_dict,
σ_u,
initial_params,
)
end
end
function unpack_params(f::LinearOde, p)
A = reshape(view(p, f.index_dict["A"]), f.state_dim, f.state_dim)
B = reshape(view(p, f.index_dict["B"]), f.state_dim, f.input_dim)
ν = zeros(f.state_dim)
return A, B, ν
end
function (f::LinearOde)(xu, p)
x, u = extract_inputs(f, xu)
A = reshape(view(p, f.index_dict["A"]), f.state_dim, f.state_dim)
B = reshape(view(p, f.index_dict["B"]), f.state_dim, f.input_dim)
return A * x .+ B * f.σ_u.(u)
end
|
{
"alphanum_fraction": 0.5725090431,
"author": null,
"avg_line_length": 26.6754385965,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "7014484ae0361629c0d34c4ad96728bc9df47af9",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "a7c70bd2ec374dfbbbf55b80ff1a551d5f8e9e2d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syanga/ISSNeuralODE",
"max_forks_repo_path": "src/dynamics/affine.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a7c70bd2ec374dfbbbf55b80ff1a551d5f8e9e2d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "syanga/ISSNeuralODE",
"max_issues_repo_path": "src/dynamics/affine.jl",
"max_line_length": 84,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a7c70bd2ec374dfbbbf55b80ff1a551d5f8e9e2d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syanga/ISSNeuralODE",
"max_stars_repo_path": "src/dynamics/affine.jl",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 881,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 3041
}
|
"""
Structures and functions for the EXPLICIT POMDPs.jl interface of the Pricing MDP
"""
"""
Enumerates all states for MDP
"""
function generate_states(pp::PMDPProblem)::AbstractArray{<:State}
c_it = Iterators.product([0:cᵣ for cᵣ in pp.c₀]...)
s_it = Iterators.product(c_it, 1:selling_period_end(pp), 1:(n_products(pp)+1)) # +1 for empty_product
states = [State(SVector(args[1]...), args[2], args[3]) for args in s_it]
end
function stateindices(pp::PMDPProblem)::LinearIndices
C_sizes = pp.c₀ .+ 1 # +1 for 0 capacity
T_size = selling_period_end(pp) # timestep starts at t=1 and goes up to t=T
prd_sizes = n_products(pp)+1 # +1 for empty product
LinearIndices((C_sizes..., T_size, prd_sizes))
end
"""
m = PMDPe(edges, products, λ)
PMDP for explicit interface
"""
struct PMDPe <: PMDP{State, Action}
pp::PMDPProblem
empty_product::Product
empty_product_id::Int64
statelinearindices::LinearIndices # ONLY FOR EXPLICIT, replaces need for states array
# stage_statelinearindices::LinearIndices
function PMDPe(pp::PMDPProblem)
sli = stateindices(pp)
return new(pp, empty_product(pp), n_products(pp)+1, sli)
end
end
"""
Works only for un-empty product
"""
function sale_prob(budget_distributions::AbstractArray{<:Distribution}, s::State, a::Action)
# cdf is probabulity that the sample from distribution is below or equal (≤) the asking price a
# we want probability that sample is below the asking price (<).
# This is only issue with discrete distributions, for those, I will subtract ϵ from a.
1-cdf(budget_distributions[s.iₚ], a-ϵ)
end
function next_states(m::PMDP, s::State, new_c::AbstractArray{<:Number})::Array{State}
sps = [State(new_c, s.t+1, iₚ) for iₚ in 1:n_products(m)+1] # +1 for empty_product
end
function POMDPs.transition(m::PMDPe, s::State, a::Action)
# --- Request arrival probs
product_request_probs = demand(m)[s.t].p
# NEXT STATES
# if s.t == selling_period_end(m)
# sps = [s]
# probs = [1.]
if sale_impossible(m, s, a)
sps = next_states(m, s, s.c)
probs = product_request_probs
else # sale possible
prob_sale = sale_prob(budgets(m), s, a)
# sufficient capacity for sale and non-empty request
sps_nosale = next_states(m, s, s.c)
probs_nosale = product_request_probs .* (1-prob_sale)
sps_sale = next_states(m, s, s.c-product(m, s))
probs_sale = product_request_probs .* prob_sale
sps = vcat(sps_nosale, sps_sale)
probs = vcat(probs_nosale, probs_sale)
end
@assert sum(probs) ≈ 1.
return SparseCat(sps, probs)
end
function POMDPs.reward(m::PMDPe, s::State, a::Action, sp::State)
if objective(m) == :revenue
s.c==sp.c ? 0. : a
elseif objective(m) == :utilization
s.c==sp.c ? 0. : sum(product(m, s))
end
end
function POMDPs.stateindex(m::PMDPe, s::State)
ci = CartesianIndex((s.c .+ 1)..., s.t, s.iₚ) # +1 for capacity because capaciteus go from 0..c₀
m.statelinearindices[ci]
end
POMDPs.actionindex(m::PMDP, a::Action) = findfirst(isequal(a), actions(m))
POMDPs.states(m::PMDP) = generate_states(pp(m))
"""
--------------------- FINITE HORIZON -----------------------------
"""
function generate_stage_states(pp::PMDPProblem, t::Timestep)::AbstractArray{<:State}
c_it = Iterators.product([0:cᵣ for cᵣ in pp.c₀]...)
s_it = Iterators.product(c_it, 1:(n_products(pp)+1)) # +1 for empty_product
states = [State(SVector(args[1]...), t, args[2]) for args in s_it]
end
function stage_stateindices(pp::PMDPProblem, t::Int64)::LinearIndices
C_sizes = pp.c₀ .+ 1 # +1 for 0 capacity
prd_sizes = n_products(pp)+1 # +1 for empty product
LinearIndices((C_sizes..., prd_sizes))
end
function FiniteHorizonPOMDPs.stage_states(mdp::PMDP, epoch::Int64)::Array{State}
return generate_stage_states(pp(mdp), epoch)
end
function FiniteHorizonPOMDPs.stage_stateindex(mdp::PMDP, s::State, epoch::Int64)
i = findfirst(sp -> sp.c==s.c && sp.iₚ==s.iₚ, generate_stage_states(pp(mdp), epoch))
stage_stateindices(pp(mdp), epoch)[i]
# findfirst(isequal(s), generate_states(pp(mdp), epoch))
end
function FiniteHorizonPOMDPs.stage_stateindex(mdp::PMDP, s::State)
FiniteHorizonPOMDPs.stage_stateindex(mdp, s, FiniteHorizonPOMDPs.stage(s))
end
FiniteHorizonPOMDPs.stage(s::State)= s.t
FiniteHorizonPOMDPs.HorizonLength(::Type{<:PMDP}) = FiniteHorizon()
FiniteHorizonPOMDPs.horizon(mdp::PMDP) = selling_period_end(mdp)
|
{
"alphanum_fraction": 0.6478902954,
"author": null,
"avg_line_length": 34.1007194245,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "75834024487645d99ef0e53eeb2b4edf185daa0d",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "894ea362dc93b7ed3d27693b5530caa50e7c3383",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "BoZenKhaa/PricingMDP.jl",
"max_forks_repo_path": "src/PMDPs/src/PMDP/PMDPe.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "894ea362dc93b7ed3d27693b5530caa50e7c3383",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "BoZenKhaa/PricingMDP.jl",
"max_issues_repo_path": "src/PMDPs/src/PMDP/PMDPe.jl",
"max_line_length": 106,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "894ea362dc93b7ed3d27693b5530caa50e7c3383",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "BoZenKhaa/PricingMDP.jl",
"max_stars_repo_path": "src/PMDPs/src/PMDP/PMDPe.jl",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1416,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 4740
}
|
import numpy as np
from scipy.optimize import minimize
import scipy.io as sio
from scipy.sparse import csc_matrix
from scipy.sparse import eye as sparseid
from numba import njit, prange
import h5py
rm = [] # Radon transform matrix
rm_transp = [] # Transposed Radon transform matrix
y = [] # projection values
cov_matrix = [] # Covariance matrix for likelihood function
inv_cov_matrix = [] # Inverse matrix for covariance matrix
N = 0 # Number of elements per one axe
# For Gaussian priors
c_prior_1 = 0
c_prior_2 = 0
c_bound = 0
# For log-transformation
c = 0
# For Cauchy priors
gamma = 0
# Initializes Radon transform matrix from the .mat-file and also prints size of matrix in bytes
# Input params:
# filename - name of .mat-file with RT matrix with format "filename.mat"
def set_rt_matrix(filename):
global rm
#rm = sio.loadmat(filename)['rm']
f = h5py.File(filename, 'r')
rm = csc_matrix((f["rm"]["data"], f["rm"]["ir"], f["rm"]["jc"]))
global rm_transp
rm_transp = csc_matrix.transpose(rm)
print("Size of Radon transform matrix: ", rm.data.nbytes/1024/1024, " MB")
f.close()
# Initializes projection values from the binary file, prints signal-to-noise ratio and optionally prints projections values and shape of array
# Input params:
# filename - name of binary file with projection values
# M - number of projections per one direction
# K - number of directions
# p - will projection values and its shape be printed or not
# sigma_noise - standard deviation value of noise (required for signal-to-noise ratio calculation)
def set_projections(filename, M, K, p = 0, sigma_noise = 1):
proj = []
with open(filename) as f:
for line in f:
proj.append([float(x) for x in line.split()])
proj = np.reshape(proj, (1, M*K))
if (p != 0):
print(proj.shape)
print(proj)
print("SNR = ", np.mean(proj)/sigma_noise)
global y
y = proj
# ========== FIRST ORDER DIFFERENCES GAUSSIAN PRIORS ==========
# First order Gaussian priors calculation in parallel loop and sum with likelihood value.
# Function is called from gaussian_logpost_1 function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood value
# x - current value of x vector
# Output params:
# res - real value equal to sum of priors values and likelihood
@njit(parallel=True)
def add_gaussian_priors_1(cur_res, x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
t = (x[i + N*j + N**2*k] - x[(i-1) + N*j + N**2*k])**2
t += (x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k])**2
t += (x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)])**2
res += c_prior_1 * t
else: #boundary point
t = x[i + N*j + N**2*k]**2
res += c_bound * t
return res
# Log-posterior function calculation with first order Gaussian priors.
# Function is called from get_MAP_gaussian_1 function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
# Output params:
# res - real value equals to log_posterior function value
def gaussian_logpost_1(x):
# likelihood:
res = 0
yAx = y - rm.dot(x) # (y-Ax)
yAx_transp = np.transpose(yAx)
t = np.matmul(inv_cov_matrix, yAx_transp) #s^-1(y-Ax)
res = 1/2 * np.matmul(yAx, t)
# priors
res = add_gaussian_priors_1(res,x)
return res
# First order Gaussian priors derivatives calculation in parallel loop.
# Function is called from gaussian_logpost_gradient_1 function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood derivative value
# x - current value of x vector
# Output params:
# res - vector of sums of prior derivatives values and likelihood derivatives values
@njit(parallel=True)
def add_gaussian_gradient_priors_1(cur_res,x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
t = 2*(x[i + N*j + N**2*k] - x[(i-1) + N*j + N**2*k])
t += 2*(x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k])
t += 2*(x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)])
if (i+1 < N-1):
t -= 2*(x[(i+1) + N*j + N**2*k] - x[i + N*j + N**2*k])
if (j+1 < N-1):
t -= 2*(x[i + N*(j+1) + N**2*k] - x[i + N*j + N**2*k])
if (k+1 < N-1):
t -= 2*(x[i + N*j + N**2*(k+1)] - x[i + N*j + N**2*k])
res[i+N*j+N**2*k] += c_prior_1 * t
else:
#res[i + N*j + N**2*k] += c_bound*2*x[i + N*j + N**2*k]
t = 2*c_bound*x[i + N*j + N**2*k]
if (i == 0 and j > 0 and j < N-1 and k > 0 and k < N-1): #back plane without edges
t -= c_prior_1 * 2*(x[(i+1) + N*j + N**2*k] - x[i + N*j + N**2*k])
if (j == 0 and i > 0 and i < N-1 and k > 0 and k < N-1): #left plane without edges
t -= c_prior_1 * 2*(x[i + N*(j+1) + N**2*k] - x[i + N*j + N**2*k])
if (k == 0 and i > 0 and i < N-1 and j > 0 and j < N-1): #bottom plane without edges
t -= c_prior_1 * 2*(x[i + N*j + N**2*(k+1)] - x[i + N*j + N**2*k])
res[i + N*j + N**2*k] += t
return res
# Gaussian first order log-posterior function calculation.
# Function is called from get_MAP_gaussian_1 function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
def gaussian_logpost_gradient_1(x):
#likelihood derivative
yAx = y - rm.dot(x) # (y-Ax)
yAx = np.transpose(yAx)
syAX = np.matmul(inv_cov_matrix, yAx)
res = -rm_transp.dot(syAX)
res = add_gaussian_gradient_priors_1(res,x)
return res
# Maximum a posteriori with first order Gaussian priors calculation
# Input params:
# N_elem - N
# M - number of projections per one direction
# K - number of directions
# sigma - standard deviation value for the likelihood
# sigma_priors - standard deviation value for priors inside the domain
# sigma_bound - standard deviation value for priors for boundary voxels
# isPos = 0 - boolean value: unknown must be positive (isPos=1) or not
# Output params:
# x - optimization problem solution
# success - bool value indicates of successful convergence
def get_MAP_gaussian_1(N_elem, M, K, sigma, sigma_priors, sigma_bound, isPos = 0):
if (rm == []):
print("One have to initialize Radon transform matrix. Use setRTmatrix function")
return 1
if (y == []):
print("One have to initialize projection values. Use setProjections function")
return 2
global N
N = N_elem
init = np.ones(N**3)
global cov_matrix
cov_matrix = sigma**2 * np.eye(M*K)
global inv_cov_matrix
inv_cov_matrix = np.linalg.inv(cov_matrix)
global c_prior_1
c_prior_1 = 1/(sigma_priors**2)
global c_bound
c_bound = 1/(sigma_bound**2)
if(isPos == 0):
bound_conds=None
else:
bound_conds = []
for i in range(N**3):
bound_conds.append((0, None))
res = minimize(gaussian_logpost_1, init, method='L-BFGS-B', jac=gaussian_logpost_gradient_1, bounds=bound_conds, options={'disp': True, 'maxfun': 500000, 'maxiter': 500000})
return res.x, res.success
# ========== FIRST ORDER DIFFERENCES GAUSSIAN PRIORS WITH LOG-TRANSFORMATION ==========
# Gaussian priors with log-transform calculation in parallel loop and sum with likelihood value.
# Function is called from gaussian_logpost_log function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood value
# x - current value of x vector
# Output params:
# res - real value equal to sum of priors values and likelihood
@njit(parallel=True)
def add_gaussian_priors_1_log(cur_res, x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
t = (np.log(x[i+N*j+N**2*k] + c) - np.log(x[(i-1)+N*j+N**2*k] + c))**2
t += (np.log(x[i+N*j+N**2*k] + c) - np.log(x[i+N*(j-1)+N**2*k] + c))**2
t += (np.log(x[i+N*j+N**2*k] + c) - np.log(x[i+N*j+N**2*(k-1)] + c))**2
res += c_prior_1 * t
else: #boundary point
#t = np.log(x[i + N*j + N**2*k]+c)**2
t = x[i + N*j + N**2*k]**2
res += c_bound * t
return res
# Log-posterior function calculation with log-transformed Gaussian priors.
# Function is called from get_MAP_gaussian_log function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
# Output params:
# res - real value equals to log_posterior function value
def gaussian_logpost_1_log(x):
# likelihood:
res = 0
yAx = y - rm.dot(x) # (y-Ax)
yAx_transp = np.transpose(yAx)
t = np.matmul(inv_cov_matrix, yAx_transp) #s^-1(y-Ax)
res = 1/2 * np.matmul(yAx, t)
# priors
res = add_gaussian_priors_1_log(res,x)
return res
# Gaussian log-transformed priors derivatives calculation in parallel loop.
# Function is called from gaussian_logpost_gradient function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood derivative value
# x - current value of x vector
# Output params:
# res - vector of sums of prior derivatives values and likelihood derivatives values
@njit(parallel=True)
def add_gaussian_gradient_priors_1_log(cur_res,x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
t = 2 * (np.log(x[i+N*j+N**2*k] + c) - np.log(x[(i-1)+N*j+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
t += 2 * (np.log(x[i+N*j+N**2*k] + c) - np.log(x[i+N*(j-1)+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
t += 2 * (np.log(x[i+N*j+N**2*k] + c) - np.log(x[i+N*j+N**2*(k-1)] + c)) / (x[i+N*j+N**2*k] + c)
if (i+1 < N-1):
t -= 2 * (np.log(x[(i+1)+N*j+N**2*k] + c) - np.log(x[i+N*j+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
if (j+1 < N-1):
t -= 2 * (np.log(x[i+N*(j+1)+N**2*k] + c) - np.log(x[i+N*j+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
if (k+1 < N-1):
t -= 2 * (np.log(x[i+N*j+N**2*(k+1)] + c) - np.log(x[i+N*j+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
res[i+N*j+N**2*k] += c_prior_1 * t
else:
#t = c_bound * 2 * np.log(x[i+N*j+N**2*k] + c) / (x[i+N*j+N**2*k] + c)
t = c_bound * 2 * x[i+N*j+N**2*k]
if (i == 0 and j > 0 and j < N-1 and k > 0 and k < N-1): #back plane without edges
t -= c_prior_1 * 2*( np.log(x[(i+1) + N*j + N**2*k] + c) - np.log(x[i + N*j + N**2*k] + c) ) / (x[i+N*j+N**2*k] + c)
if (j == 0 and i > 0 and i < N-1 and k > 0 and k < N-1): #left plane without edges
t -= c_prior_1 * 2*( np.log(x[i + N*(j+1) + N**2*k] + c) - np.log(x[i + N*j + N**2*k] + c) ) / (x[i+N*j+N**2*k] + c)
if (k == 0 and i > 0 and i < N-1 and j > 0 and j < N-1): #bottom plane without edges
t -= c_prior_1 * 2*( np.log(x[i + N*j + N**2*(k+1)] + c) - np.log(x[i + N*j + N**2*k] + c) ) / (x[i+N*j+N**2*k] + c)
res[i + N*j + N**2*k] += t
return res
# Gaussian log-posterior gradient calculation.
# Function is called from get_MAP_gaussian_log function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
def gaussian_logpost_gradient_1_log(x):
#likelihood derivative
yAx = y - rm.dot(x) # (y-Ax)
yAx = np.transpose(yAx)
syAX = np.matmul(inv_cov_matrix, yAx)
res = -rm_transp.dot(syAX)
res = add_gaussian_gradient_priors_1_log(res,x)
return res
# Maximum a posteriori with Gaussian log-transformed priors calculation
# Input params:
# N_elem - N
# M - number of projections per one direction
# K - number of directions
# c_log - constant in logarithm to avoid zero value as its argument
# sigma - standard deviation value for likelihood
# sigma_priors - standard deviation value for priors inside the domain
# sigma_bound - standard deviation value for priors for boundary voxels
# Output params:
# x - optimization problem solution
# success - bool value indicates of successful convergence
def get_MAP_gaussian_1_log(N_elem, M, K, c_log, sigma, sigma_priors, sigma_bound):
if (rm == []):
print("One have to initialize Radon transform matrix. Use setRTmatrix function")
return 1
if (y == []):
print("One have to initialize projection values. Use setProjections function")
return 2
global N
N = N_elem
init = np.ones(N**3)
global cov_matrix
cov_matrix = sigma**2 * np.eye(M*K)
global inv_cov_matrix
inv_cov_matrix = np.linalg.inv(cov_matrix)
global c_prior_1
c_prior_1 = 1/(sigma_priors**2)
global c_bound
c_bound = 1/(sigma_bound**2)
global c
c = c_log
bound_conds = []
for i in range(N**3):
bound_conds.append((0, None))
res = minimize(gaussian_logpost_1_log, init, method='L-BFGS-B', jac=gaussian_logpost_gradient_1_log, bounds=bound_conds, options={'disp': True, 'maxfun': 500000, 'maxiter': 500000})
return res.x, res.success
# ========== SECOND ORDER DIFFERENCES GAUSSIAN PRIORS ==========
# Second order diffrenences Gaussian priors calculation in parallel loop and sum with likelihood value.
# Function is called from gaussian_logpost_2 function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood value
# x - current value of x vector
# Outputt params:
# res - real value equal to sum of priors values and likelihood
@njit(parallel=True)
def add_gaussian_priors_2(cur_res, x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
t = (x[(i+1) + N*j + N**2*k] - 2*x[i + N*j + N**2*k] + x[(i-1) + N*j + N**2*k])**2
t += (x[i + N*(j+1) + N**2*k] - 2*x[i + N*j + N**2*k] + x[i + N*(j-1) + N**2*k])**2
t += (x[i + N*j + N**2*(k+1)] - 2*x[i + N*j + N**2*k] + x[i + N*j + N**2*(k-1)])**2
res += c_prior_2 * t
else: #boundary point
t = x[i + N*j + N**2*k]**2
res += c_bound * t
return res
# Log-posterior function calculation with second order Gaussian priors.
# Function is called from get_MAP_gaussian_2 function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
# Output params:
# res - real value equals to log_posterior function value
def gaussian_logpost_2(x):
# likelihood:
res = 0
yAx = y - rm.dot(x) # (y-Ax)
yAx_transp = np.transpose(yAx)
t = np.matmul(inv_cov_matrix, yAx_transp) #s^-1(y-Ax)
res = 1/2 * np.matmul(yAx, t)
# priors
res = add_gaussian_priors_2(res,x)
return res
# Second order Gaussian priors derivatives calculation in parallel loop.
# Function is called from gaussian_logpost_gradient_2 function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood derivative value
# x - current value of x vector
# Output params:
# res - vector of sums of prior derivatives values and likelihood derivatives values
@njit(parallel=True)
def add_gaussian_gradient_priors_2(cur_res,x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
t = -4*(x[(i+1) + N*j + N**2*k] - 2*x[i + N*j + N**2*k] + x[(i-1) + N*j + N**2*k])
t += -4*(x[i + N*(j+1) + N**2*k] - 2*x[i + N*j + N**2*k] + x[i + N*(j-1) + N**2*k])
t += -4*(x[i + N*j + N**2*(k+1)] - 2*x[i + N*j + N**2*k] + x[i + N*j + N**2*(k-1)])
if (i+1 < N-1):
t += 2*(x[(i+2) + N*j + N**2*k] - 2 * x[(i+1) + N*j + N**2*k] + x[i + N*j + N**2*k])
if (j+1 < N-1):
t += 2*(x[i + N*(j+2) + N**2*k] - 2 * x[i + N*(j+1) + N**2*k] + x[i + N*j + N**2*k])
if (k+1 < N-1):
t += 2*(x[i + N*j + N**2*(k+2)] - 2 * x[i + N*j + N**2*(k+1)] + x[i + N*j + N**2*k])
if (i-1 > 0):
t += 2*(x[i + N*j + N**2*k] - 2 * x[(i-1) + N*j + N**2*k] + x[(i-2) + N*j + N**2*k])
if (j-1 > 0):
t += 2*(x[i + N*j + N**2*k] - 2 * x[i + N*(j-1) + N**2*k] + x[i + N*(j-1) + N**2*k])
if (k-1 > 0):
t += 2*(x[i + N*j + N**2*k] - 2 * x[i + N*j + N**2*(k-1)] + x[i + N*j + N**2*(k-2)])
res[i+N*j+N**2*k] += c_prior_2 * t
else:
#res[i + N*j + N**2*k] += c_bound*2*x[i + N*j + N**2*k]
t = c_bound*2*x[i + N*j + N**2*k]
if (i == 0 and j > 0 and j < N-1 and k > 0 and k < N-1): # back plane without edges
t += c_prior_2 * 2*(x[(i+2) + N*j + N**2*k] - 2 * x[(i+1) + N*j + N**2*k] + x[i + N*j + N**2*k])
if (i == N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # front plane without edges
t += c_prior_2 * 2*(x[i + N*j + N**2*k] - 2 * x[(i-1) + N*j + N**2*k] + x[(i-2) + N*j + N**2*k])
if (j == 0 and i > 0 and i < N-1 and k > 0 and k < N-1): # left plane without edges
t += c_prior_2 * 2*(x[i + N*(j+2) + N**2*k] - 2 * x[i + N*(j+1) + N**2*k] + x[i + N*j + N**2*k])
if (j == N-1 and i > 0 and i < N-1 and k > 0 and k < N-1): # right plane without edges
t += c_prior_2 * 2*(x[i + N*j + N**2*k] - 2 * x[i + N*(j-1) + N**2*k] + x[i + N*(j-2) + N**2*k])
if (k == 0 and i > 0 and i < N-1 and j > 0 and j < N-1): # bottom plane without edges
t += c_prior_2 * 2*(x[i + N*j + N**2*(k+2)] - 2 * x[i + N*j + N**2*(k+1)] + x[i + N*j + N**2*k])
if (k == N-1 and i > 0 and i < N-1 and j > 0 and j < N-1): # top plane without edges
t += c_prior_2 * 2*(x[i + N*j + N**2*k] - 2 * x[i + N*j + N**2*(k-1)] + x[i + N*j + N**2*(k-2)])
res[i+N*j+N**2*k] += t
return res
# Second order Gaussian log-posterior function calculation.
# Function is called from get_MAP_gaussian_2 function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
def gaussian_logpost_gradient_2(x):
#likelihood derivative
yAx = y - rm.dot(x) # (y-Ax)
yAx = np.transpose(yAx)
syAX = np.matmul(inv_cov_matrix, yAx)
res = -rm_transp.dot(syAX)
res = add_gaussian_gradient_priors_2(res,x)
return res
# Maximum a posteriori with second order Gaussian priors calculation
# Input params:
# N_elem - N
# M - number of projections per one direction
# K - number of directions
# sigma - standard deviation value for likelihood
# sigma_priors - standard deviation value for priors inside the domain
# sigma_bound - standard deviation value for priors for boundary voxels
# isPos = 0 - boolean value: unknown must be positive (isPos=1) or not
# Output params:
# x - optimization problem solution
# success - bool value indicates of successful convergence
def get_MAP_gaussian_2(N_elem, M, K, sigma, sigma_priors, sigma_bound, isPos=0):
if (rm == []):
print("One have to initialize Radon transform matrix. Use setRTmatrix function")
return 1
if (y == []):
print("One have to initialize projection values. Use setProjections function")
return 2
global N
N = N_elem
init = np.ones(N**3)
global cov_matrix
cov_matrix = sigma**2 * np.eye(M*K)
global inv_cov_matrix
inv_cov_matrix = np.linalg.inv(cov_matrix)
global c_prior_2
c_prior_2 = 1/(sigma_priors**2)
global c_bound
c_bound = 1/(sigma_bound**2)
if(isPos == 0):
bounds_conds=None
else:
bound_conds = []
for i in range(N**3):
bound_conds.append((0, None))
res = minimize(gaussian_logpost_2, init, method='L-BFGS-B', jac=gaussian_logpost_gradient_2, bounds=bound_conds, options={'disp': True, 'maxfun': 500000, 'maxiter': 500000})
return res.x, res.success
# ========== SECOND ORDER DIFFERENCES GAUSSIAN PRIORS WITH LOG-TRANSFORM ==========
# Second order diffrenences Gaussian priors with log transform calculation in parallel loop and sum with likelihood value.
# Function is called from gaussian_logpost_2_log function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood value
# x - current value of x vector
# Output params:
# res - real value equal to sum of priors values and likelihood
@njit(parallel=True)
def add_gaussian_priors_2_log(cur_res, x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
t = ( np.log(x[(i+1) + N*j + N**2*k]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[(i-1) + N*j + N**2*k]+c) )**2
t += ( np.log(x[i + N*(j+1) + N**2*k]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[i + N*(j-1) + N**2*k]+c) )**2
t += ( np.log(x[i + N*j + N**2*(k+1)]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[i + N*j + N**2*(k-1)]+c) )**2
res += c_prior_2 * t
else: #boundary point
#t = np.log(x[i + N*j + N**2*k]+c)**2
t = x[i+N*j+N**2*k]**2
res += c_bound * t
return res
# Log-posterior function calculation with second order log-transformed Gaussian priors.
# Function is called from get_MAP_gaussian_2_log function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
# Output params:
# res - real value equals to log_posterior function value
def gaussian_logpost_2_log(x):
# likelihood:
res = 0
yAx = y - rm.dot(x) # (y-Ax)
yAx_transp = np.transpose(yAx)
t = np.matmul(inv_cov_matrix, yAx_transp) #s^-1(y-Ax)
res = 1/2 * np.matmul(yAx, t)
# priors
res = add_gaussian_priors_2_log(res,x)
return res
# Second order log-transformed Gaussian priors derivatives calculation in parallel loop.
# Function is called from gaussian_logpost_gradient function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood derivative value
# x - current value of x vector
# Output params:
# res - vector of sums of prior derivatives values and likelihood derivatives values
@njit(parallel=True)
def add_gaussian_gradient_priors_2_log(cur_res,x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
t = -4/(x[i+N*j+N**2*k]+c) * ( np.log(x[(i+1) + N*j + N**2*k]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[(i-1) + N*j + N**2*k]+c) )
t += -4/(x[i+N*j+N**2*k]+c) * ( np.log(x[i + N*(j+1) + N**2*k]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[i + N*(j-1) + N**2*k]+c) )
t += -4/(x[i+N*j+N**2*k]+c) * ( np.log(x[i + N*j + N**2*(k+1)]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[i + N*j + N**2*(k-1)]+c) )
if (i+1 < N-1):
t += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[(i+2) + N*j + N**2*k]+c) - 2*np.log(x[(i+1) + N*j + N**2*k]+c) + np.log(x[i + N*j + N**2*k]+c) )
if (j+1 < N-1):
t += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[i + N*(j+2) + N**2*k]+c) - 2*np.log(x[i + N*(j+1) + N**2*k]+c) + np.log(x[i + N*j + N**2*k]+c) )
if (k+1 < N-1):
t += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[i + N*j + N**2*(k+2)]+c) - 2*np.log(x[i + N*j + N**2*(k+1)]+c) + np.log(x[i + N*j + N**2*k]+c) )
if (i-1 > 0):
t += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[i + N*j + N**2*k]+c) - 2*np.log(x[(i-1) + N*j + N**2*k]+c) + np.log(x[(i-2) + N*j + N**2*k]+c) )
if (j-1 > 0):
t += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[i + N*j + N**2*k]+c) - 2*np.log(x[i + N*(j-1) + N**2*k]+c) + np.log(x[i + N*(j-2) + N**2*k]+c) )
if (k-1 > 0):
t += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[i + N*j + N**2*k]+c) - 2*np.log(x[i + N*j + N**2*(k-1)]+c) + np.log(x[i + N*j + N**2*(k-2)]+c) )
res[i+N*j+N**2*k] += c_prior_2 * t
else:
#t = 2 * c_bound * np.log(x[i + N*j + N**2*k]+c) / (x[i + N*j + N**2*k]+c)
t = 2 * c_bound * x[i+N*j+N**2*k]
if (i == 0 and j > 0 and j < N-1 and k > 0 and k < N-1): # back plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[(i+2) + N*j + N**2*k]+c) - 2 * np.log(x[(i+1) + N*j + N**2*k]+c) + np.log(x[i + N*j + N**2*k]+c))
if (i == N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # front plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*j + N**2*k]+c) - 2 * np.log(x[(i-1) + N*j + N**2*k]+c) + np.log(x[(i-2) + N*j + N**2*k]+c))
if (j == 0 and i > 0 and i < N-1 and k > 0 and k < N-1): # left plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*(j+2) + N**2*k]+c) - 2 * np.log(x[i + N*(j+1) + N**2*k]+c) + np.log(x[i + N*j + N**2*k]+c))
if (j == N-1 and i > 0 and i < N-1 and k > 0 and k < N-1): # right plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*j + N**2*k]+c) - 2 * np.log(x[i + N*(j-1) + N**2*k]+c) + np.log(x[i + N*(j-2) + N**2*k]+c))
if (k == 0 and i > 0 and i < N-1 and j > 0 and j < N-1): # bottom plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*j + N**2*(k+2)]+c) - 2 * np.log(x[i + N*j + N**2*(k+1)]+c) + np.log(x[i + N*j + N**2*k]+c))
if (k == N-1 and i > 0 and i < N-1 and j > 0 and j < N-1): # top plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*j + N**2*k]+c) - 2 * np.log(x[i + N*j + N**2*(k-1)]+c) + np.log(x[i + N*j + N**2*(k-2)]+c))
res[i+N*j+N**2*k] += t
return res
# Second order log-transformed Gaussian log-posterior function calculation.
# Function is called from getMAP_gaussian function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
def gaussian_logpost_gradient_2_log(x):
#likelihood derivative
yAx = y - rm.dot(x) # (y-Ax)
yAx = np.transpose(yAx)
syAX = np.matmul(inv_cov_matrix, yAx)
res = -rm_transp.dot(syAX)
res = add_gaussian_gradient_priors_2_log(res,x)
return res
# Maximum a posteriori with second order log-transformed Gaussian priors calculation
# Input params:
# N_elem - N
# M - number of projections per one direction
# K - number of directions
# c_log - constant in logarithm to avoid zero value as its argument
# sigma - standard deviation value for likelihood
# sigma_priors - standard deviation value for priors inside the domain
# sigma_bound - standard deviation value for priors for boundary voxels
# Output params:
# x - optimization problem solution
# success - bool value indicates of successful convergence
def get_MAP_gaussian_2_log(N_elem, M, K, c_log, sigma, sigma_priors, sigma_bound):
if (rm == []):
print("One have to initialize Radon transform matrix. Use setRTmatrix function")
return 1
if (y == []):
print("One have to initialize projection values. Use setProjections function")
return 2
global N
N = N_elem
init = np.ones(N**3)
global cov_matrix
cov_matrix = sigma**2 * np.eye(M*K)
global inv_cov_matrix
inv_cov_matrix = np.linalg.inv(cov_matrix)
global c_prior_2
c_prior_2 = 1/(sigma_priors**2)
global c_bound
c_bound = 1/(sigma_bound**2)
global c
c = c_log
bound_conds = []
for i in range(N**3):
bound_conds.append((0, None))
res = minimize(gaussian_logpost_2_log, init, method='L-BFGS-B', jac=gaussian_logpost_gradient_2_log, bounds=bound_conds, options={'disp': True, 'maxfun': 500000, 'maxiter': 500000})
return res.x, res.success
# ========== BOTH ORDER DIFFERENCES GAUSSIAN PRIORS ==========
# Both order diffrenences Gaussian priors calculation in parallel loop and sum with likelihood value.
# Function is called from gaussian_logpost_2 function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood value
# x - current value of x vector
# Outputt params:
# res - real value equal to sum of priors values and likelihood
@njit(parallel=True)
def add_gaussian_priors_1_2(cur_res, x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
#first order:
t_1 = (x[i + N*j + N**2*k] - x[(i-1) + N*j + N**2*k])**2
t_1 += (x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k])**2
t_1 += (x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)])**2
#second order:
t_2 = (x[(i+1) + N*j + N**2*k] - 2*x[i + N*j + N**2*k] + x[(i-1) + N*j + N**2*k])**2
t_2 += (x[i + N*(j+1) + N**2*k] - 2*x[i + N*j + N**2*k] + x[i + N*(j-1) + N**2*k])**2
t_2 += (x[i + N*j + N**2*(k+1)] - 2*x[i + N*j + N**2*k] + x[i + N*j + N**2*(k-1)])**2
res += c_prior_1 * t_1 + c_prior_2 * t_2
else: #boundary point
t = x[i + N*j + N**2*k]**2
res += c_bound * t
return res
# Log-posterior function calculation with first and second order Gaussian priors.
# Function is called from get_MAP_gaussian_1_2 function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
# Output params:
# res - real value equals to log_posterior function value
def gaussian_logpost_1_2(x):
# likelihood:
res = 0
yAx = y - rm.dot(x) # (y-Ax)
yAx_transp = np.transpose(yAx)
t = np.matmul(inv_cov_matrix, yAx_transp) #s^-1(y-Ax)
res = 1/2 * np.matmul(yAx, t)
# priors
res = add_gaussian_priors_1_2(res,x)
return res
# Both order Gaussian priors derivatives calculation in parallel loop.
# Function is called from gaussian_logpost_gradient function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood derivative value
# x - current value of x vector
# Output params:
# res - vector of sums of prior derivatives values and likelihood derivatives values
@njit(parallel=True)
def add_gaussian_gradient_priors_1_2(cur_res,x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
#first order
t_1 = 2*(x[i + N*j + N**2*k] - x[(i-1) + N*j + N**2*k])
t_1 += 2*(x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k])
t_1 += 2*(x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)])
if (i+1 < N-1):
t_1 -= 2*(x[(i+1) + N*j + N**2*k] - x[i + N*j + N**2*k])
if (j+1 < N-1):
t_1 -= 2*(x[i + N*(j+1) + N**2*k] - x[i + N*j + N**2*k])
if (k+1 < N-1):
t_1 -= 2*(x[i + N*j + N**2*(k+1)] - x[i + N*j + N**2*k])
#second order
t_2 = -4*(x[(i+1) + N*j + N**2*k] - 2*x[i + N*j + N**2*k] + x[(i-1) + N*j + N**2*k])
t_2 += -4*(x[i + N*(j+1) + N**2*k] - 2*x[i + N*j + N**2*k] + x[i + N*(j-1) + N**2*k])
t_2 += -4*(x[i + N*j + N**2*(k+1)] - 2*x[i + N*j + N**2*k] + x[i + N*j + N**2*(k-1)])
if (i+1 < N-1):
t_2 += 2*(x[(i+2) + N*j + N**2*k] - 2 * x[(i+1) + N*j + N**2*k] + x[i + N*j + N**2*k])
if (j+1 < N-1):
t_2 += 2*(x[i + N*(j+2) + N**2*k] - 2 * x[i + N*(j+1) + N**2*k] + x[i + N*j + N**2*k])
if (k+1 < N-1):
t_2 += 2*(x[i + N*j + N**2*(k+2)] - 2 * x[i + N*j + N**2*(k+1)] + x[i + N*j + N**2*k])
if (i-1 > 0):
t_2 += 2*(x[i + N*j + N**2*k] - 2 * x[(i-1) + N*j + N**2*k] + x[(i-2) + N*j + N**2*k])
if (j-1 > 0):
t_2 += 2*(x[i + N*j + N**2*k] - 2 * x[i + N*(j-1) + N**2*k] + x[i + N*(j-1) + N**2*k])
if (k-1 > 0):
t_2 += 2*(x[i + N*j + N**2*k] - 2 * x[i + N*j + N**2*(k-1)] + x[i + N*j + N**2*(k-2)])
res[i+N*j+N**2*k] += c_prior_1 * t_1 + c_prior_2 * t_2
else:
# first order
t = 2*c_bound*x[i + N*j + N**2*k]
if (i == 0 and j > 0 and j < N-1 and k > 0 and k < N-1): #back plane without edges
t -= c_prior_1 * 2*(x[(i+1) + N*j + N**2*k] - x[i + N*j + N**2*k])
if (j == 0 and i > 0 and i < N-1 and k > 0 and k < N-1): #left plane without edges
t -= c_prior_1 * 2*(x[i + N*(j+1) + N**2*k] - x[i + N*j + N**2*k])
if (k == 0 and i > 0 and i < N-1 and j > 0 and j < N-1): #bottom plane without edges
t -= c_prior_1 * 2*(x[i + N*j + N**2*(k+1)] - x[i + N*j + N**2*k])
#second order
if (i == 0 and j > 0 and j < N-1 and k > 0 and k < N-1): # back plane without edges
t += c_prior_2 * 2*(x[(i+2) + N*j + N**2*k] - 2 * x[(i+1) + N*j + N**2*k] + x[i + N*j + N**2*k])
if (i == N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # front plane without edges
t += c_prior_2 * 2*(x[i + N*j + N**2*k] - 2 * x[(i-1) + N*j + N**2*k] + x[(i-2) + N*j + N**2*k])
if (j == 0 and i > 0 and i < N-1 and k > 0 and k < N-1): # left plane without edges
t += c_prior_2 * 2*(x[i + N*(j+2) + N**2*k] - 2 * x[i + N*(j+1) + N**2*k] + x[i + N*j + N**2*k])
if (j == N-1 and i > 0 and i < N-1 and k > 0 and k < N-1): # right plane without edges
t += c_prior_2 * 2*(x[i + N*j + N**2*k] - 2 * x[i + N*(j-1) + N**2*k] + x[i + N*(j-2) + N**2*k])
if (k == 0 and i > 0 and i < N-1 and j > 0 and j < N-1): # bottom plane without edges
t += c_prior_2 * 2*(x[i + N*j + N**2*(k+2)] - 2 * x[i + N*j + N**2*(k+1)] + x[i + N*j + N**2*k])
if (k == N-1 and i > 0 and i < N-1 and j > 0 and j < N-1): # top plane without edges
t += c_prior_2 * 2*(x[i + N*j + N**2*k] - 2 * x[i + N*j + N**2*(k-1)] + x[i + N*j + N**2*(k-2)])
res[i + N*j + N**2*k] += t
return res
# Both order Gaussian log-posterior function calculation.
# Function is called from get_MAP_gaussian_1_2 function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
def gaussian_logpost_gradient_1_2(x):
#likelihood derivative
yAx = y - rm.dot(x) # (y-Ax)
yAx = np.transpose(yAx)
syAX = np.matmul(inv_cov_matrix, yAx)
res = -rm_transp.dot(syAX)
res = add_gaussian_gradient_priors_1_2(res,x)
return res
# Maximum a posteriori with first and second order Gaussian priors calculation
# Input params:
# N_elem - N
# M - number of projections per one direction
# K - number of directions
# sigma - standard deviation value for likelihood
# sigma_priors_1 - standard deviation value for the first order priors inside the domain
# sigma_priors_2 - standard deviation value for the second order priors inside the domain
# sigma_bound - standard deviation value for priors for boundary voxels
# isPos = 0 - boolean value: unknown must be positive (isPos=1) or not
# Output params:
# x - optimization problem solution
# success - bool value indicates of successful convergence
def get_MAP_gaussian_1_2(N_elem, M, K, sigma, sigma_priors_1, sigma_priors_2, sigma_bound, isPos=0):
if (rm == []):
print("One have to initialize Radon transform matrix. Use setRTmatrix function")
return 1
if (y == []):
print("One have to initialize projection values. Use setProjections function")
return 2
global N
N = N_elem
init = np.ones(N**3)
global cov_matrix
cov_matrix = sigma**2 * np.eye(M*K)
global inv_cov_matrix
inv_cov_matrix = np.linalg.inv(cov_matrix)
global c_prior_1
c_prior_1 = 1/(sigma_priors_1**2)
global c_prior_2
c_prior_2 = 1/(sigma_priors_2**2)
global c_bound
c_bound = 1/(sigma_bound**2)
if(isPos == 0):
bounds_conds = None
else:
bound_conds = []
for i in range(N**3):
bound_conds.append((0, None))
res = minimize(gaussian_logpost_1_2, init, method='L-BFGS-B', jac=gaussian_logpost_gradient_1_2, bounds=bound_conds, options={'disp': True, 'maxfun': 500000, 'maxiter': 500000})
return res.x, res.success
# ========== BOTH ORDER DIFFERENCES GAUSSIAN PRIORS WITH LOG-TRANSFORM ==========
# Both order diffrenences Gaussian priors calculation in parallel loop and sum with likelihood value.
# Function is called from gaussian_logpost_2 function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood value
# x - current value of x vector
# Outputt params:
# res - real value equal to sum of priors values and likelihood
@njit(parallel=True)
def add_gaussian_priors_1_2_log(cur_res, x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
#first order:
t_1 = (np.log(x[i+N*j+N**2*k] + c) - np.log(x[(i-1)+N*j+N**2*k] + c))**2
t_1 += (np.log(x[i+N*j+N**2*k] + c) - np.log(x[i+N*(j-1)+N**2*k] + c))**2
t_1 += (np.log(x[i+N*j+N**2*k] + c) - np.log(x[i+N*j+N**2*(k-1)] + c))**2
#second order:
t_2 = (np.log(x[(i+1) + N*j + N**2*k]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[(i-1) + N*j + N**2*k]+c))**2
t_2 += (np.log(x[i + N*(j+1) + N**2*k]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[i + N*(j-1) + N**2*k]+c))**2
t_2 += (np.log(x[i + N*j + N**2*(k+1)]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[i + N*j + N**2*(k-1)]+c))**2
res += c_prior_1 * t_1 + c_prior_2 * t_2
else: #boundary point
#t = np.log(x[i + N*j + N**2*k]+c)**2
t = x[i + N*j + N**2*k]**2
res += c_bound * t
return res
# Log-posterior function calculation with first and second order log-transformed Gaussian priors.
# Function is called from get_MAP_gaussian_1_2 function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
# Output params:
# res - real value equals to log_posterior function value
def gaussian_logpost_1_2_log(x):
# likelihood:
res = 0
yAx = y - rm.dot(x) # (y-Ax)
yAx_transp = np.transpose(yAx)
t = np.matmul(inv_cov_matrix, yAx_transp) #s^-1(y-Ax)
res = 1/2 * np.matmul(yAx, t)
# priors
res = add_gaussian_priors_1_2_log(res,x)
return res
# Both order Gaussian log-transformed priors derivatives calculation in parallel loop.
# Function is called from gaussian_logpost_gradient function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood derivative value
# x - current value of x vector
# Output params:
# res - vector of sums of prior derivatives values and likelihood derivatives values
@njit(parallel=True)
def add_gaussian_gradient_priors_1_2_log(cur_res,x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
#first order
t_1 = 2 * (np.log(x[i+N*j+N**2*k] + c) - np.log(x[(i-1)+N*j+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
t_1 += 2 * (np.log(x[i+N*j+N**2*k] + c) - np.log(x[i+N*(j-1)+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
t_1 += 2 * (np.log(x[i+N*j+N**2*k] + c) - np.log(x[i+N*j+N**2*(k-1)] + c)) / (x[i+N*j+N**2*k] + c)
if (i+1 < N-1):
t_1 -= 2 * (np.log(x[(i+1)+N*j+N**2*k] + c) - np.log(x[i+N*j+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
if (j+1 < N-1):
t_1 -= 2 * (np.log(x[i+N*(j+1)+N**2*k] + c) - np.log(x[i+N*j+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
if (k+1 < N-1):
t_1 -= 2 * (np.log(x[i+N*j+N**2*(k+1)] + c) - np.log(x[i+N*j+N**2*k] + c)) / (x[i+N*j+N**2*k] + c)
#second order
t_2 = -4/(x[i+N*j+N**2*k]+c) * ( np.log(x[(i+1) + N*j + N**2*k]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[(i-1) + N*j + N**2*k]+c) )
t_2 += -4/(x[i+N*j+N**2*k]+c) * ( np.log(x[i + N*(j+1) + N**2*k]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[i + N*(j-1) + N**2*k]+c) )
t_2 += -4/(x[i+N*j+N**2*k]+c) * ( np.log(x[i + N*j + N**2*(k+1)]+c) - 2*np.log(x[i + N*j + N**2*k]+c) + np.log(x[i + N*j + N**2*(k-1)]+c) )
if (i+1 < N-1):
t_2 += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[(i+2) + N*j + N**2*k]+c) - 2*np.log(x[(i+1) + N*j + N**2*k]+c) + np.log(x[i + N*j + N**2*k]+c) )
if (j+1 < N-1):
t_2 += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[i + N*(j+2) + N**2*k]+c) - 2*np.log(x[i + N*(j+1) + N**2*k]+c) + np.log(x[i + N*j + N**2*k]+c) )
if (k+1 < N-1):
t_2 += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[i + N*j + N**2*(k+2)]+c) - 2*np.log(x[i + N*j + N**2*(k+1)]+c) + np.log(x[i + N*j + N**2*k]+c) )
if (i-1 > 0):
t_2 += 2/(x[i+N*j+N**2*k]+c)*( np.log(x[i + N*j + N**2*k]+c) - 2 * np.log(x[(i-1) + N*j + N**2*k]+c) + np.log(x[(i-2) + N*j + N**2*k]+c))
if (j-1 > 0):
t_2 += 2/(x[i+N*j+N**2*k]+c)*(np.log(x[i + N*j + N**2*k]+c) - 2 * np.log(x[i + N*(j-1) + N**2*k]+c) + np.log(x[i + N*(j-2) + N**2*k]+c))
if (k-1 > 0):
t_2 += 2/(x[i+N*j+N**2*k]+c)*(np.log(x[i + N*j + N**2*k]+c) - 2 * np.log(x[i + N*j + N**2*(k-1)]+c) + np.log(x[i + N*j + N**2*(k-2)]+c))
res[i+N*j+N**2*k] += c_prior_1 * t_1 + c_prior_2 * t_2
else:
# first order
#t = 2 * c_bound * np.log(x[i+N*j+N**2*k] + c) / (x[i+N*j+N**2*k] + c)
t = 2 * c_bound * x[i + N*j + N**2*k]
if (i == 0 and j > 0 and j < N-1 and k > 0 and k < N-1): #back plane without edges
t -= c_prior_1 * 2*(np.log(x[(i+1) + N*j + N**2*k] + c) - np.log(x[i + N*j + N**2*k] +c )) / (x[i+N*j+N**2*k] + c)
if (j == 0 and i > 0 and i < N-1 and k > 0 and k < N-1): #left plane without edges
t -= c_prior_1 * 2*(np.log(x[i + N*(j+1) + N**2*k] + c) - np.log(x[i + N*j + N**2*k] +c )) / (x[i+N*j+N**2*k] + c)
if (k == 0 and i > 0 and i < N-1 and j > 0 and j < N-1): #bottom plane without edges
t -= c_prior_1 * 2*(np.log(x[i + N*j + N**2*(k+1)] + c) - np.log(x[i + N*j + N**2*k] +c )) / (x[i+N*j+N**2*k] + c)
# second order
if (i == 0 and j > 0 and j < N-1 and k > 0 and k < N-1): # back plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[(i+2) + N*j + N**2*k]+c) - 2 * np.log(x[(i+1) + N*j + N**2*k]+c) + np.log(x[i + N*j + N**2*k]+c))
if (i == N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # front plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*j + N**2*k]+c) - 2 * np.log(x[(i-1) + N*j + N**2*k]+c) + np.log(x[(i-2) + N*j + N**2*k]+c))
if (j == 0 and i > 0 and i < N-1 and k > 0 and k < N-1): # left plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*(j+2) + N**2*k]+c) - 2 * np.log(x[i + N*(j+1) + N**2*k]+c) + np.log(x[i + N*j + N**2*k]+c))
if (j == N-1 and i > 0 and i < N-1 and k > 0 and k < N-1): # right plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*j + N**2*k]+c) - 2 * np.log(x[i + N*(j-1) + N**2*k]+c) + np.log(x[i + N*(j-2) + N**2*k]+c))
if (k == 0 and i > 0 and i < N-1 and j > 0 and j < N-1): # bottom plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*j + N**2*(k+2)]+c) - 2 * np.log(x[i + N*j + N**2*(k+1)]+c) + np.log(x[i + N*j + N**2*k]+c))
if (k == N-1 and i > 0 and i < N-1 and j > 0 and j < N-1): # top plane without edges
t += c_prior_2 * 2/(x[i + N*j + N**2*k]+c)*(np.log(x[i + N*j + N**2*k]+c) - 2 * np.log(x[i + N*j + N**2*(k-1)]+c) + np.log(x[i + N*j + N**2*(k-2)]+c))
res[i + N*j + N**2*k] += t
return res
# Both order Gaussian log-posterior function calculation.
# Function is called from getMAP_gaussian function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
def gaussian_logpost_gradient_1_2_log(x):
#likelihood derivative
yAx = y - rm.dot(x) # (y-Ax)
yAx = np.transpose(yAx)
syAX = np.matmul(inv_cov_matrix, yAx)
res = -rm_transp.dot(syAX)
res = add_gaussian_gradient_priors_1_2_log(res,x)
return res
# Maximum a posteriori with first and second order Gaussian log-transformed priors calculation
# Input params:
# N_elem - N
# M - number of projections per one direction
# K - number of directions
# c_log - constant in logarithm to avoid zero value as its argument
# sigma - standard deviation value for likelihood
# sigma_priors_1 - standard deviation value for the first order priors inside the domain
# sigma_priors_2 - standard deviation value for the second order priors inside the domain
# sigma_bound - standard deviation value for priors for boundary voxels
# Output params:
# x - optimization problem solution
# success - bool value indicates of successful convergence
def get_MAP_gaussian_1_2_log(N_elem, M, K, c_log, sigma, sigma_priors_1, sigma_priors_2, sigma_bound):
if (rm == []):
print("One have to initialize Radon transform matrix. Use setRTmatrix function")
return 1
if (y == []):
print("One have to initialize projection values. Use setProjections function")
return 2
global N
N = N_elem
init = np.ones(N**3)
global cov_matrix
cov_matrix = sigma**2 * np.eye(M*K)
global inv_cov_matrix
inv_cov_matrix = np.linalg.inv(cov_matrix)
global c_prior_1
c_prior_1 = 1/(sigma_priors_1**2)
global c_prior_2
c_prior_2 = 1/(sigma_priors_2**2)
global c_bound
c_bound = 1/(sigma_bound**2)
global c
c = c_log
bound_conds = []
for i in range(N**3):
bound_conds.append((0, None))
res = minimize(gaussian_logpost_1_2_log, init, method='L-BFGS-B', jac=gaussian_logpost_gradient_1_2_log, bounds=bound_conds, options={'disp': True, 'maxfun': 500000, 'maxiter': 500000})
return res.x, res.success
# ========== CAUCHY PRIORS ==========
# Cauchy priors calculation in parallel loop and sum with likelihood value.
# Function is called from cauchy_logpost function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood value
# x - current value of x vector
# Outputt params:
# res - real value equal to sum of priors values and likelihood
@njit(parallel=True)
def add_cauchy_priors(cur_res, x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
#res -= np.log(gamma/((x[i + N*j + N**2*k] - x[i-1 + N*j + N**2*k])**2 + gamma**2) * gamma/((x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k])**2 + gamma**2) * gamma/((x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)])**2 + gamma**2))
res -= np.log(gamma/((x[i + N*j + N**2*k] - x[i-1 + N*j + N**2*k])**2 + (x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k])**2 + (x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)])**2 + gamma**2)**2)
else:
res -= np.log(gamma/((x[i + N*j + N**2*k])**2 + gamma**2))
return res
# Log-posterior function calculation with Cauchy priors.
# Function is called from get_MAP_cauchy function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
# Output params:
# res - real value equals to log_posterior function value
def cauchy_logpost(x):
# likelihood:
res = 0
yAx = y - rm.dot(x) # (y-Ax)
yAx_transp = np.transpose(yAx)
t = np.matmul(inv_cov_matrix, yAx_transp) #s^-1(y-Ax)
res = 1/2 * np.matmul(yAx, t)
# priors
res = add_cauchy_priors(res, x)
return res
# Cauchy priors derivatives calculation in parallel loop and sum with likelihood.
# Function is called from cauchy_logpost_gradient function. Shouldn't be called from another functions
# Input params:
# cur_res - previously calculated likelihood derivative value
# x - current value of x vector
# Output params:
# res - vector of sums of prior derivatives values and likelihood derivatives values
@njit(parallel=True)
def add_cauchy_gradient_priors(cur_res,x):
res = cur_res
for k in prange(N):
for j in range(N):
for i in range(N):
# boundary point or not
if (i > 0 and i < N-1 and j > 0 and j < N-1 and k > 0 and k < N-1): # inside of domain
#t = 2*(x[i + N*j + N**2*k] - x[i-1 + N*j + N**2*k])/((x[i + N*j + N**2*k] - x[i-1 + N*j + N**2*k])**2 + gamma**2)
#t += 2*(x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k])/((x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k])**2 + gamma**2)
#t += 2*(x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)])/((x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)])**2 + gamma**2)
t = 4*((x[i + N*j + N**2*k] - x[i-1 + N*j + N**2*k]) + (x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k]) + (x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)]))/((x[i + N*j + N**2*k] - x[i-1 + N*j + N**2*k])**2 + (x[i + N*j + N**2*k] - x[i + N*(j-1) + N**2*k])**2 + (x[i + N*j + N**2*k] - x[i + N*j + N**2*(k-1)])**2 + gamma**2)
if (i+1 < N-1):
#t -= 2*(x[i+1 + N*j + N**2*k] - x[i + N*j + N**2*k])/((x[i+1 + N*j + N**2*k] - x[i + N*j + N**2*k])**2 + gamma**2)
t -= 4*(x[i+1 + N*j + N**2*k] - x[i + N*j + N**2*k])/((x[i+1 + N*j + N**2*k] - x[i+1 + N*(j-1) + N**2*k])**2 + (x[i+1 + N*j + N**2*k] - x[i+1 + N*j + N**2*(k-1)])**2 + (x[i+1 + N*j + N**2*k] - x[i + N*j + N**2*k])**2 + gamma**2)
if (j+1 < N-1):
#t -= 2*(x[i + N*(j+1) + N**2*k] - x[i + N*j + N**2*k])/((x[i + N*(j+1) + N**2*k] - x[i + N*j + N**2*k])**2 + gamma**2)
t -= 4*(x[i + N*(j+1) + N**2*k] - x[i + N*j + N**2*k])/((x[i + N*(j+1) + N**2*k] - x[i-1 + N*(j+1) + N**2*k])**2 + (x[i + N*(j+1) + N**2*k] - x[i + N*(j+1) + N**2*(k-1)])**2 + (x[i + N*(j+1) + N**2*k] - x[i + N*j + N**2*k])**2 + gamma**2)
if (k+1 < N-1):
#t -= 2*(x[i + N*j + N**2*(k+1)] - x[i + N*j + N**2*k])/((x[i + N*j + N**2*(k+1)] - x[i + N*j + N**2*k])**2 + gamma**2)
t -= 4*(x[i + N*j + N**2*(k+1)] - x[i + N*j + N**2*k])/((x[i + N*j + N**2*(k+1)] - x[i-1 + N*j + N**2*(k+1)])**2 + (x[i + N*j + N**2*(k+1)] - x[i + N*(j-1) + N**2*(k+1)])**2 + (x[i + N*j + N**2*(k+1)] - x[i + N*j + N**2*k])**2 + gamma**2)
res[i + N*j + N**2*k] += t
else:
res[i + N*j + N**2*k] += 2*x[i + N*j + N**2*k]/(x[i + N*j + N**2*k]**2+gamma**2)
return res
# Cauchy log-posterior function calculation.
# Function is called from get_MAP_cauchy function. Shouldn't be called from another functions
# Input params:
# x - current value of x vector
def cauchy_logpost_gradient(x):
#likelihood derivative
yAx = y - rm.dot(x) # (y-Ax)
yAx = np.transpose(yAx)
syAX = np.matmul(inv_cov_matrix, yAx)
res = -rm_transp.dot(syAX)
res = add_cauchy_gradient_priors(res,x)
return res
# Maximum a posteriori with Gaussian priors calculation
# Input params:
# N_elem - N
# M - number of projections per one direction
# K - number of directions
# sigma - standard deviation value for likelihood
# h - discretization step
# lmbd - lambda value for Cauchy priors
def get_MAP_cauchy(N_elem, M, K, sigma, h, lmbd):
if (rm == []):
print("One have to initialize Radon transform matrix. Use setRTmatrix function")
return 1
if (y == []):
print("One have to initialize projection values. Use setProjections function")
return 2
global gamma
gamma = h*lmbd
global N
N = N_elem
global cov_matrix
cov_matrix = sigma * np.eye(M*K)
global inv_cov_matrix
inv_cov_matrix = np.linalg.inv(cov_matrix)
init = np.ones(N**3)
res = minimize(cauchy_logpost, init, method='L-BFGS-B', jac=cauchy_logpost_gradient, options={'disp': True})
return res.x
|
{
"alphanum_fraction": 0.5023892905,
"author": null,
"avg_line_length": 48.7937710438,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "faeb87b94d209b43eeb6d40182b28c5c6a20a979",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f4f924dd452405800e3e4bb17d01215f3fd32bec",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Irogerd/3d_reconstruction",
"max_forks_repo_path": "reconstruction.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f4f924dd452405800e3e4bb17d01215f3fd32bec",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Irogerd/3d_reconstruction",
"max_issues_repo_path": "reconstruction.py",
"max_line_length": 342,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f4f924dd452405800e3e4bb17d01215f3fd32bec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Irogerd/3d_reconstruction",
"max_stars_repo_path": "reconstruction.py",
"max_stars_repo_stars_event_max_datetime": "2020-12-09T13:59:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-09T13:59:35.000Z",
"num_tokens": 19022,
"path": null,
"reason": "import numpy,import scipy,from scipy,from numba",
"repo": null,
"save_path": null,
"sha": null,
"size": 57967
}
|
C
C
*$ 2) High-Level Map System Routines Access Catalogue, Stack and Data
* ------------------------------------------------------------------
C
C
*+ map_enqdef
subroutine map_enqdef(imap,status)
C ----------------------------------
C
C Enquire the default map
C
C Returned:
C Default map
integer imap
C Status word
integer status
C
C The current value of the default map is returned
C
*-
include 'mapcat_cat.inc'
C
if (status.ne.0) return
imap = default_map
call mapcat_err(status,'map_enqdef',' ')
end
|
{
"alphanum_fraction": 0.519524618,
"author": null,
"avg_line_length": 19.6333333333,
"converted": null,
"ext": "f",
"file": null,
"hexsha": "2576c6ed8cdd8e653803060c80f65f1c27a1fb24",
"include": null,
"lang": "FORTRAN",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "efb611d7f80a3d14dc55e46cd01e8a622f6fd294",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "CavendishAstrophysics/anmap",
"max_forks_repo_path": "mapcat/map_enqdef.f",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "efb611d7f80a3d14dc55e46cd01e8a622f6fd294",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "CavendishAstrophysics/anmap",
"max_issues_repo_path": "mapcat/map_enqdef.f",
"max_line_length": 69,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "efb611d7f80a3d14dc55e46cd01e8a622f6fd294",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "CavendishAstrophysics/anmap",
"max_stars_repo_path": "mapcat/map_enqdef.f",
"max_stars_repo_stars_event_max_datetime": "2015-09-01T12:40:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-01T12:40:45.000Z",
"num_tokens": 146,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 589
}
|
import logging
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from .base import *
from .column_selection import FEATURE_PATTERN, TARGET_PATTERN, get_columns_by_pattern
logger = logging.getLogger(__name__)
# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, output_size)
def forward(self, x):
out = self.fc1(x)
out = self.relu1(out)
out = self.fc2(out)
return out
class Model(RandomBatchFit,
ParallelTransform,
metaclass=PipelineModule):
"""Make predictions"""
def __init__(self, feature_pattern=FEATURE_PATTERN, target_pattern=TARGET_PATTERN):
# Initialize parameters for random batch fit
RandomBatchFit.__init__(
self,
batch_size=10_00,
seq_size=1,
n_epochs=100,
)
self.feature_pattern = feature_pattern
self.target_pattern = target_pattern
self.model = None
self.feature_names = None
self.target_names = None
self._last_metrics_print = None
self._last_metrics_print_val = None
def partial_transform(self, dataset: pd.DataFrame):
# Convert features to torch
features = self._to_torch(dataset[self.feature_names].values)
# Make predictions
with torch.no_grad():
pred = self.model.eval()(features).detach().numpy()
# Add predictions to dataframe
dataset[self.prediction_names] = pred
return dataset
def reset_transform(self):
pass
def _to_torch(self, arr):
return torch.from_numpy(arr.astype(np.float32)).to(self.device)
def _need_init_model(self):
return self.model is None
def _reset_init_model(self):
self.model = None
def _init_model(self, columns):
self.feature_names = get_columns_by_pattern(columns, self.feature_pattern) # Column names to get features from
self.target_names = get_columns_by_pattern(columns, self.target_pattern) # Column names to get target from
self.prediction_names = ['pred_' + i for i in self.target_names] # Column names to store prediction
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Create model and put it to device
self.model = NeuralNet(
input_size=len(self.feature_names),
hidden_size=len(self.feature_names),
output_size=len(self.target_names),
).to(self.device)
self.optimizer = torch.optim.Adam(self.model.parameters(),
lr=0.001,
weight_decay=0.01)
def partial_fit(self, dataset: pd.DataFrame):
assert isinstance(dataset, pd.DataFrame)
if self._need_init_model():
self._init_model(dataset.columns)
features = self._to_torch(dataset[self.feature_names].values)
target = self._to_torch(dataset[self.target_names].values)
pred = self.model.train()(features)
loss = ((target - pred) ** 2).sum() # Compute loss for gradient calculation
if self._last_metrics_print is None or \
datetime.now() > self._last_metrics_print + timedelta(seconds=2):
self._last_metrics_print = datetime.now()
# TODO: Make proper overfit detection and stop criterion
# Compute and print score
with torch.no_grad():
y_test_pred = self.model.eval()(features).detach().numpy()
y_test_true = target.detach().numpy()
score = ((y_test_pred - y_test_true) ** 2).mean()
improvement = 0
if self._last_metrics_print_val is not None:
improvement = (score / self._last_metrics_print_val) - 1
logger.info("train MSE: {}; Change: {:+.0f}%".format(float('{:.3g}'.format(score)), improvement * 100))
self._last_metrics_print_val = score
# Recompute gradient
self.optimizer.zero_grad()
loss.backward()
# Adjust model parameters
self.optimizer.step()
def reset_fit(self):
# Reset everything before next fit attempt
self._reset_init_model()
self._last_metrics_print = None
self._last_metrics_print_val = None
|
{
"alphanum_fraction": 0.6329741379,
"author": null,
"avg_line_length": 35.6923076923,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "3ff05e3227999003e14cfbbbf7a65dd2e6fa681a",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0a8232d3596b7d871af116c05776921817c77fb7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "artefom/jane_street_kaggle",
"max_forks_repo_path": "jane_street_kaggle/model.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0a8232d3596b7d871af116c05776921817c77fb7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "artefom/jane_street_kaggle",
"max_issues_repo_path": "jane_street_kaggle/model.py",
"max_line_length": 119,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0a8232d3596b7d871af116c05776921817c77fb7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "artefom/jane_street_kaggle",
"max_stars_repo_path": "jane_street_kaggle/model.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 970,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4640
}
|
PROGRAM test_timer
!
! This program tests the timer class.
!
! Record of revisions:
! Date Programmer Description of change
! ==== ========== =====================
! 12/27/06 S. J. Chapman Original code
!
USE timer_class ! Import timer class
IMPLICIT NONE
! Declare local variables
INTEGER :: i, j ! Loop index
INTEGER :: k ! Scratch variable
TYPE(timer) :: t ! Timer object
! Reset the timer
CALL t%start_timer()
! Waste some time
DO i = 1, 10000
DO j = 1, 10000
k = i + j
END DO
END DO
! Get the elapsed time
WRITE (*,'(A,F8.3,A)') 'Time =', t%elapsed_time(), ' s'
END PROGRAM test_timer
|
{
"alphanum_fraction": 0.5065616798,
"author": null,
"avg_line_length": 23.8125,
"converted": null,
"ext": "f90",
"file": null,
"hexsha": "c67afc1ff830af136c176147f27a23f11752a253",
"include": null,
"lang": "FORTRAN",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-08-05T06:36:55.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-11T02:36:25.000Z",
"max_forks_repo_head_hexsha": "3d4a91aacd957361aff5873054edf35c586e8a55",
"max_forks_repo_licenses": [
"AFL-3.0"
],
"max_forks_repo_name": "yangyang14641/FortranLearning",
"max_forks_repo_path": "Fortran952003ForScientistsandEngineers3rdStephenJChapman/chap16/test_timer.f90",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d4a91aacd957361aff5873054edf35c586e8a55",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"AFL-3.0"
],
"max_issues_repo_name": "yangyang14641/FortranLearning",
"max_issues_repo_path": "Fortran952003ForScientistsandEngineers3rdStephenJChapman/chap16/test_timer.f90",
"max_line_length": 60,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "3d4a91aacd957361aff5873054edf35c586e8a55",
"max_stars_repo_licenses": [
"AFL-3.0"
],
"max_stars_repo_name": "yangyang14641/FortranLearning",
"max_stars_repo_path": "Fortran952003ForScientistsandEngineers3rdStephenJChapman/chap16/test_timer.f90",
"max_stars_repo_stars_event_max_datetime": "2021-08-05T07:58:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-12T02:18:29.000Z",
"num_tokens": 192,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 762
}
|
import pandas as pd
import numpy as np
def stratified_sample_df(df, col, n_samples,sampled='stratified',random_state=1):
# n = min(n_samples, df[col].value_counts().min())
# df_ = df.groupby(col).apply(lambda x: x.sample(n))
# df_.index = df_.index.droplevel(0)
#df.sample(n=n_samples, weights=col, random_state=1).reset_index(drop=True)
if(sampled=='stratified'):
df_=df.groupby(col, group_keys=False).apply(lambda x: x.sample(int(np.rint(n_samples*len(x)/len(df))))).sample(frac=1,random_state=random_state).reset_index(drop=True)
elif(sampled=='equal'):
df_=df.groupby(col, group_keys=False).apply(lambda x: x.sample(int(n_samples/2))).sample(frac=1,random_state=random_state).reset_index(drop=True)
return df_
# def data_collector(file_names,language,is_train=False,sample_ratio=0.5,type_train='baseline',sampled='stratified',take_ratio=False):
# if(is_train!=True):
# df_test=[]
# for file in file_names:
# lang_temp=file.split('/')[-1][:-12]
# if(lang_temp==language):
# df_test.append(pd.read_csv(file))
# df_test=pd.concat(df_test,axis=0)
# return df_test
# else:
# if(type_train=='baseline'):
# df_test=[]
# print(file_names)
# for file in file_names:
# lang_temp=file.split('/')[-1][:-12]
# if(lang_temp==language):
# temp=pd.read_csv(file)
# df_test.append(temp)
# df_test=pd.concat(df_test,axis=0)
# return df_test
# if(type_train=='zero_shot'):
# df_test=[]
# for file in file_names:
# lang_temp=file.split('/')[-1][:-12]
# if(lang_temp=='English'):
# temp=pd.read_csv(file)
# if(take_ratio==True):
# n_samples=int(len(temp)*sample_ratio/100)
# else:
# n_samples=sample_ratio
# if(n_samples==0):
# n_samples+=1
# temp_sample=stratified_sample_df(temp, 'label', n_samples,sampled)
# df_test.append(temp_sample)
# df_test=pd.concat(df_test,axis=0)
# return df_test
# if(type_train=='all_but_one'):
# df_test=[]
# for file in file_names:
# lang_temp=file.split('/')[-1][:-12]
# if(lang_temp!=language):
# temp=pd.read_csv(file)
# if(take_ratio==True):
# n_samples=int(len(temp)*sample_ratio/100)
# else:
# n_samples=sample_ratio
# if(n_samples==0):
# n_samples+=1
# temp_sample=stratified_sample_df(temp, 'label', n_samples,sampled)
# df_test.append(temp_sample)
# df_test=pd.concat(df_test,axis=0)
# return df_test
# if(type_train=='all'):
# df_test=[]
# for file in file_names:
# temp=pd.read_csv(file)
# df_test.append(temp)
# df_test=pd.concat(df_test,axis=0)
# return df_test
# if(type_train=='all_multitask'):
# df_test=[]
# for file in file_names:
# temp=pd.read_csv(file)
# df_test.append(temp)
# df_test=pd.concat(df_test,axis=0)
# return df_test
# if(type_train=='all_multitask_own'):
# df_test=[]
# for file in file_names:
# temp=pd.read_csv(file)
# df_test.append(temp)
# df_test=pd.concat(df_test,axis=0)
# return df_test
###### data collection taking all at a time
def data_collector(file_names,params,is_train):
if(params['csv_file']=='*_full.csv'):
index=12
elif(params['csv_file']=='*_translated.csv'):
index=23
elif(params['csv_file']=='*_full_target.csv'):
index = 19
elif(params['csv_file']=='*_translated_target.csv'):
index = 30
sample_ratio=params['sample_ratio']
type_train=params['how_train']
sampled=params['samp_strategy']
take_ratio=params['take_ratio']
language=params['language']
if(is_train!=True):
df_test=[]
for file in file_names:
lang_temp=file.split('/')[-1][:-index]
if(lang_temp==language):
df_test.append(pd.read_csv(file))
df_test=pd.concat(df_test,axis=0)
return df_test
else:
if(type_train=='baseline'):
df_test=[]
for file in file_names:
lang_temp=file.split('/')[-1][:-index]
print(lang_temp)
if(lang_temp==language):
temp=pd.read_csv(file)
df_test.append(temp)
df_test=pd.concat(df_test,axis=0)
if(type_train=='zero_shot'):
df_test=[]
for file in file_names:
lang_temp=file.split('/')[-1][:-index]
if(lang_temp=='English'):
temp=pd.read_csv(file)
df_test.append(temp)
df_test=pd.concat(df_test,axis=0)
if(type_train=='all_but_one'):
df_test=[]
for file in file_names:
lang_temp=file.split('/')[-1][:-index]
if(lang_temp!=language):
temp=pd.read_csv(file)
df_test.append(temp)
df_test=pd.concat(df_test,axis=0)
if(take_ratio==True):
n_samples=int(len(df_test)*sample_ratio/100)
else:
n_samples=sample_ratio
if(n_samples==0):
n_samples+=1
df_test=stratified_sample_df(df_test, 'label', n_samples,sampled,params['random_seed'])
return df_test
def data_collector_target(file_names,params,is_train):
df_test=[]
for file in file_names:
temp=pd.read_csv(file)
df_test.append(temp)
df_test=pd.concat(df_test,axis=0)
return df_test
|
{
"alphanum_fraction": 0.5311948677,
"author": null,
"avg_line_length": 36.0404624277,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "251671167b5deb2c3848a44bb2301f6eb92dfd8d",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2022-03-04T08:30:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-04T17:21:27.000Z",
"max_forks_repo_head_hexsha": "dafb16e86e3b7d777afb73bf94dd5c6b7f69a627",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SaiSakethAluru/DE-LIMIT",
"max_forks_repo_path": "CNN_GRU/bert_codes/data_extractor.py",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "dafb16e86e3b7d777afb73bf94dd5c6b7f69a627",
"max_issues_repo_issues_event_max_datetime": "2021-02-08T04:12:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-04-15T19:09:00.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SaiSakethAluru/DE-LIMIT",
"max_issues_repo_path": "CNN_GRU/bert_codes/data_extractor.py",
"max_line_length": 175,
"max_stars_count": 51,
"max_stars_repo_head_hexsha": "dafb16e86e3b7d777afb73bf94dd5c6b7f69a627",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SaiSakethAluru/DE-LIMIT",
"max_stars_repo_path": "CNN_GRU/bert_codes/data_extractor.py",
"max_stars_repo_stars_event_max_datetime": "2021-03-01T10:36:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-14T06:05:17.000Z",
"num_tokens": 1362,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 6235
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#ifdef GSL_FOUND
#include <gsl/gsl_integration.h>
#endif
#include "core_allvars.h"
#include "core_init.h"
#include "core_mymalloc.h"
#include "core_cool_func.h"
/* These functions do not need to be exposed externally */
double integrand_time_to_present(const double a, void *param);
void set_units(struct params *run_params);
void read_snap_list(const int ThisTask, struct params *run_params);
double time_to_present(const double z, struct params *run_params);
#ifdef HDF5
#include "io/io_save_hdf5.h"
#endif
void init(const int ThisTask, struct params *run_params)
{
run_params->Age = mymalloc(ABSOLUTEMAXSNAPS*sizeof(run_params->Age[0]));
set_units(run_params);
read_snap_list(ThisTask, run_params);
//Hack to fix deltaT for snapshot 0
//This way, galsnapnum = -1 will not segfault.
run_params->Age[0] = time_to_present(1000.0, run_params);//lookback time from z=1000
run_params->Age++;
for(int i = 0; i < run_params->Snaplistlen; i++) {
run_params->ZZ[i] = 1 / run_params->AA[i] - 1;
run_params->Age[i] = time_to_present(run_params->ZZ[i], run_params);
}
run_params->a0 = 1.0 / (1.0 + run_params->Reionization_z0);
run_params->ar = 1.0 / (1.0 + run_params->Reionization_zr);
read_cooling_functions();
if(ThisTask == 0) {
printf("cooling functions read\n\n");
}
#if 0
#ifdef HDF5
if(HDF5Output) {
calc_hdf5_props();
}
#endif
#endif
}
void set_units(struct params *run_params)
{
run_params->UnitTime_in_s = run_params->UnitLength_in_cm / run_params->UnitVelocity_in_cm_per_s;
run_params->UnitTime_in_Megayears = run_params->UnitTime_in_s / SEC_PER_MEGAYEAR;
run_params->G = GRAVITY / pow(run_params->UnitLength_in_cm, 3) * run_params->UnitMass_in_g * pow(run_params->UnitTime_in_s, 2);
run_params->UnitDensity_in_cgs = run_params->UnitMass_in_g / pow(run_params->UnitLength_in_cm, 3);
run_params->UnitPressure_in_cgs = run_params->UnitMass_in_g / run_params->UnitLength_in_cm / pow(run_params->UnitTime_in_s, 2);
run_params->UnitCoolingRate_in_cgs = run_params->UnitPressure_in_cgs / run_params->UnitTime_in_s;
run_params->UnitEnergy_in_cgs = run_params->UnitMass_in_g * pow(run_params->UnitLength_in_cm, 2) / pow(run_params->UnitTime_in_s, 2);
run_params->EnergySNcode = run_params->EnergySN / run_params->UnitEnergy_in_cgs * run_params->Hubble_h;
run_params->EtaSNcode = run_params->EtaSN * (run_params->UnitMass_in_g / SOLAR_MASS) / run_params->Hubble_h;
// convert some physical input parameters to internal units
run_params->Hubble = HUBBLE * run_params->UnitTime_in_s;
// compute a few quantitites
run_params->RhoCrit = 3.0 * run_params->Hubble * run_params->Hubble / (8 * M_PI * run_params->G);
}
void read_snap_list(const int ThisTask, struct params *run_params)
{
char fname[MAX_STRING_LEN+1];
snprintf(fname, MAX_STRING_LEN, "%s", run_params->FileWithSnapList);
FILE *fd = fopen(fname, "r");
if(fd == NULL) {
printf("can't read output list in file '%s'\n", fname);
ABORT(0);
}
run_params->Snaplistlen = 0;
do {
if(fscanf(fd, " %lg ", &(run_params->AA[run_params->Snaplistlen])) == 1) {
run_params->Snaplistlen++;
} else {
break;
}
} while(run_params->Snaplistlen < run_params->MAXSNAPS);
fclose(fd);
if(ThisTask == 0) {
printf("found %d defined times in snaplist\n", run_params->Snaplistlen);
}
}
double time_to_present(const double z, struct params *run_params)
{
const double end_limit = 1.0;
const double start_limit = 1.0/(1 + z);
double result=0.0;
#ifdef GSL_FOUND
#define WORKSIZE 1000
gsl_function F;
gsl_integration_workspace *workspace;
double abserr;
workspace = gsl_integration_workspace_alloc(WORKSIZE);
F.function = &integrand_time_to_present;
F.params = run_params;
gsl_integration_qag(&F, start_limit, end_limit, 1.0 / run_params->Hubble,
1.0e-9, WORKSIZE, GSL_INTEG_GAUSS21, workspace, &result, &abserr);
gsl_integration_workspace_free(workspace);
#undef WORKSIZE
#else
/* Do not have GSL - let's integrate numerically ourselves */
const double step = 1e-7;
const int64_t nsteps = (end_limit - start_limit)/step;
result = 0.0;
const double y0 = integrand_time_to_present(start_limit + 0*step, run_params);
const double yn = integrand_time_to_present(start_limit + nsteps*step, run_params);
for(int64_t i=1; i<nsteps; i++) {
result += integrand_time_to_present(start_limit + i*step, run_params);
}
result = (step*0.5)*(y0 + yn + 2.0*result);
#endif
/* convert into Myrs/h (I think -> MS 23/6/2018) */
const double time = 1.0 / run_params->Hubble * result;
// return time to present as a function of redshift
return time;
}
double integrand_time_to_present(const double a, void *param)
{
const struct params *run_params = (struct params *) param;
return 1.0 / sqrt(run_params->Omega / a + (1.0 - run_params->Omega - run_params->OmegaLambda) + run_params->OmegaLambda * a * a);
}
|
{
"alphanum_fraction": 0.689810471,
"author": null,
"avg_line_length": 31.1637426901,
"converted": null,
"ext": "c",
"file": null,
"hexsha": "c12b90728245858026c266c7cddd3ef1905a4120",
"include": null,
"lang": "C",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "de7040b9eee3c437fc129828bb64bd835be64ae2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "manodeep/lfs_sage",
"max_forks_repo_path": "src/core_init.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "de7040b9eee3c437fc129828bb64bd835be64ae2",
"max_issues_repo_issues_event_max_datetime": "2021-06-23T02:16:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-02-13T10:57:27.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "manodeep/lfs_sage",
"max_issues_repo_path": "src/core_init.c",
"max_line_length": 137,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "de7040b9eee3c437fc129828bb64bd835be64ae2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "manodeep/lfs_sage",
"max_stars_repo_path": "src/core_init.c",
"max_stars_repo_stars_event_max_datetime": "2021-04-22T03:19:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-22T03:19:14.000Z",
"num_tokens": 1506,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 5329
}
|
"""
AdaptiveExtrapolationD
This module is implementing an
adaptive extrapolation of the explicit midpoint rule according to Deuflhard.
"""
module AdaptiveExtrapolationD
"""
(Δ,Δx,statisitic) = (mySolver::solver)(f::Function, x₀::Vector{T}, t₀::S, tEnd::S; <options>)
where {T<:Number,S<:AbstractFloat}
Computes the grid function `xΔ` on the grid `Δ` approximating the solution of the initial value problem
x′ = f(t,x), x(t₀) = x₀
on the interval `[t₀,tEnd]` (or `[tEnd,t₀]` if `tEnd < t₀`). The integrator is the extrapolated explicit midpoint rule.
The algorithm adaptively controls stepsize and extrapolation order in the line of thought of Deuflhard.
Note that `solver` is a callable instance of the `struct solver`.
***
## Initialize `solver`
solver(N::Integer, sequence::String)
Initializes and returns the an instance of `solver`.
`N ≧ 1` is the maximal order of extrapolation. `sequence` specifies the subdividing sequence
used. The options are
* `Harmonic`, that is `1, 2, 3, 4, 5, 6,...`
* `Romberg`, that is `1, 2, 4, 8, 16, 32,...`
* `Bulirsch`, that is `1, 2, 3, 4, 6, 8,... `
The structure contains all quantities for the adaptive extrapolation of the the explicit
midpoint rule for all orders in `1:N` that can be tabulated before the actual computation .
These are the *subdividing sequence* and the *weights* for the extrapolation based on the first barycentric formula.
***
## Options
The following options can be passed as keyword arguments.
* `tol::S > 0` is tolerance used for accuracy check. Default is `1e-3`.
* `relativeScaling::Vector{S}` and `absoluteScaling::Vector{S}` are vectors of the same length as `x₀`
containing no negative elements.
Default (in every component) is `relativeScaling[i] = 1.0` and `absoluteScaling[i] = 1e-3`.
The accuracy check is passed iff the estimated error satisfies in every component:
|relativeError[i]| ≦ relativeScaling[i]⋅tol & |absoluteError[i]| ≦ absoluteScaling[i]⋅tol
* `firstGuessStepsize::S` is the length of the first step. Its modulus must be greater than
`eps(S)` Default is `1e-3`.
* `maximalSteplength::S > 0` is the maximal absolute stepsize used for the integration. Default is `Inf`.
* `minimalStepsizeScaling::S` and `maximalStepsizeScaling::S` are safety factors for the stepsize
selection. Default are `0.25` and `4.0`. The new stepsize satisfies:
0 ≦ minimalStepsizeScaling ≦ newStepsize / oldStepsize ≦ maximalStepsizeScaling
* `safetyStepsizeSelection::S>0`. Use `safetyStepsizeSelection⋅tol` instead of `tol`. Default is `0.25`.
* `minimumOrder::Int64 ≧ 1` and `maximumOrder::Int64 ≦ N` are the minimal and maximal order of extrapolation for the integration (`N` is the number that has been passed to the constructor). Default are `1` and `N`.
* `firstGuessOrder::Int64` is the extrapolation order for the first step. It must satisfy
`minimumOrder ≦ firstGuessOrder ≦ maximumOrder`. Default is `round(Int64,(maximumOrder-minimumOrder)/2)`.
* `maximumReduction::Int64` is the upper bound of the number of successive reductions allowed per step.
Exceeding this boundary leads to ending the integration prematurely (`Δ[end] ≠ tEnd`). Default is `10`.
* `maximumSteps::Int64 ≧ 0` is the maximal length of the array `Δ`. Exceeding this boundary leads to
ending the integration prematurely (`Δ[end] ≠ tEnd`). Default is `10 000`.
* `rescaleWeights::Bool` If `true` Lagrange interpolation is used otherwise the frist barycentric fromula. Default is `false`
* `detailedStatistics::Bool` flag for the content of `statisitic`. Default is `false`
+ `true`: `statisitic[:,i]` contains [extrapolation order; stepsize; number of `f`-evaluations;
number of reductions] for the ith step.
+ `false`: `statisitic` contains [total number of evaluations of the right side `f`, total number of reductions].
"""
struct solver
"""
The structure contains all quantities for the adaptive extrapolation of the the explicit
midpoint rule that can be tabulated before the acutal computation.
These are for all orders in `1:N` (`N` is provided the constructor):
The subdividing sequence, the weights and scaling used for
the extrapolation based on the first barycentric formula.
"""
subdividingSequence::Array{BigInt,1}
# weights and scaling factors for extrapolation operators
ω::Array{Rational{BigInt},2}
ρ::Array{Rational{BigInt},1}
# weights and scaling factors for internal extrapolation operators (used for error estimate)
ω2::Array{Rational{BigInt},2}
ρ2::Array{Rational{BigInt},1}
# constructor
function solver(N::Integer, sequence::String)
# check input and initialize subdividing sequence subdividingSequence for barycentric weights
if N < 0
error("Order of extrapolation must not be negative. But I got N = $N")
end
if sequence == "Harmonic"
subdividingSequence = [BigInt(n+1) for n = 0:N]
elseif sequence == "Romberg"
subdividingSequence = [BigInt(2)^n for n = 0:N]
elseif sequence == "Bulirsch"
subdividingSequence = [n==0 ? BigInt(1) : (isodd(n) ? BigInt(2)^Int64(n/2+0.5) : 3*BigInt(2^Int64(n/2-1))) for n = 0:N]
else
error("Name of subdividing sequence must be ''Harmonic'', ''Romberg'' or ''Bulirsch''. But I got ''$sequence''")
end
# compute nodes corresponding to the subdividing sequence subdividingSequence
nodes = BigInt(1).// subdividingSequence.^2
# compute barycentric weights for internal extrapolation operators
ω2 = zeros(Rational{BigInt},N,N)
ω2[1,:] = ones(Rational{BigInt},1,N)
for n = 2:N
distance = nodes[2:n] .- nodes[n+1]
ω2[1:(n-1),n] = ω2[1:n-1,n-1] .// distance
ω2[n,n] = 1 // prod(-distance)
end
# compute barycentric weights for extrapolation operators
ω = zeros(Rational{BigInt},N+1,N+1)
for n = 1:N
ω[n+1,(n+1):(N+1)] = ω2[n,n:N] // (nodes[n+1]-nodes[1])
ω[1,n] = 1 // prod(nodes[1].-nodes[2:n])
end
ω[1,N+1] = 1 // prod(nodes[1].-nodes[2:N+1])
#rescale barycentric weights to obtain weights of 1. barycentric formula
for m = 1:(N+1)
ω[1:m,m] = - ω[1:m,m] .// nodes[1:m]
if 2 <= m
ω2[1:m-1,m-1] = - ω2[1:m-1,m-1] .// nodes[2:m]
end
end
# compute scaling factors for internal extrapolation operators
ρ2 = ones(Rational{BigInt},N)
ρ2[1] = -nodes[2]
for n = 1:(N-1)
ρ2[n+1] = -ρ2[n]*nodes[n+2]
end
# compute scaling factors for extrapolation operators
ρ = -nodes[1]*[BigInt(1); ρ2]
# initialize structure
new(subdividingSequence,ω,ρ,ω2,ρ2)
end
end
function (mySolver::solver)(
f::Function, x₀::Vector{T}, t₀::S, tEnd::S;
tol::S = parse(S,"1e-3"),
relativeScaling::Vector{S} =ones(S,size(x₀)),
absoluteScaling::Vector{S} = fill(parse(S,"1e-3"),size(x₀)),
firstGuessStepsize::S = parse(S,"1e-3"),
maximalSteplength::S = parse(S,"Inf"),
minimalStepsizeScaling::S = parse(S,"0.02"),
maximalStepsizeScaling::S = parse(S,"4"),
safetyStepsizeSelection::S = parse(S,"0.25"),
minimumOrder::Int64 = 1,
maximumOrder::Int64 = length(mySolver.subdividingSequence)-1,
firstGuessOrder = round(Int64,(maximumOrder-minimumOrder)/2),
maximumReduction::Int64 = 10,
maximumSteps::Int64 = 10000,
rescaleWeights::Bool = false,
detailedStatistics::Bool = false,
kwargs...
)where {T<:Number,S<:AbstractFloat}
# initialize
# 1. constants
d = length(x₀) # systems dimension
if 1<= minimumOrder <= maximumOrder <= length(mySolver.ρ)-1
n_ex, N_ex = minimumOrder, maximumOrder
else
error("Minimal and maximal order must satisfy: 1 ≦ minimumOrder ≦ maximumOrder ≦ $(length(mySolver.ρ)-1)!")
end
if length(relativeScaling) == length(absoluteScaling) == d
if all(el->el>=zero(S),relativeScaling ) && all(el->el>=zero(S),absoluteScaling)
σᵣ, σₐ = relativeScaling, absoluteScaling # scaling factors for the error estimate
else
error("All elements of relativeScaling and absoluteScaling must be non-negative!")
end
else
error("relativeScaling and absoluteScaling must be vectors of length $(d)!")
end
if zero(S) <= minimalStepsizeScaling <= maximalStepsizeScaling
p1, p2 = minimalStepsizeScaling, maximalStepsizeScaling
else
error("Minimal and maximal stepsize scaling must satisfy: 0.0 <= minimalStepsizeScaling <= maximalStepsizeScaling!")
end
# 2. arrays
if maximumSteps >= 0
Δ = zeros(S, maximumSteps + 1) # time grid
xΔ = zeros(T, d, maximumSteps + 1) # solution
else
error("maximumSteps must not be negative!")
end
X = zeros(T, d, N_ex + 1) # storage for the internal discretisations obtained by the explicit midpoint rule
λ = zeros(S, N_ex - n_ex +1) # storage for scaling factors of stepsize. λ[k] contains the scalar for extr. order (k + n_ex - 1)
τ_opt =zeros(S, N_ex - n_ex +1) # storage for optimal stepsize. τ_opt[k] contains the stepsize for extr. order (k + n_ex - 1)
s = [2*sum(Int64.(mySolver.subdividingSequence[1:n+1])) - n for n in n_ex:N_ex] # s[k] is the number of stages for extrapolation order (k + n_ex - 1)
statistics = detailedStatistics ? zeros(S,4,maximumSteps) : zeros(Int64,2)
# 3. initialization for integration loop
Δ[1], xΔ[:,1] = t₀, x₀ # store inital values
tRest = tEnd - Δ[1] # remaining size of the interval
if maximalSteplength > zero(S)
maximalSteplength = min(abs(tRest),maximalSteplength)
else
error("maximalSteplength must be positive!")
end
if abs(firstGuessStepsize) > eps(S)
τ = flipsign(min(abs(firstGuessStepsize),maximalSteplength),tRest) # stepsize for first step, accomodate backward integration
else
error("Absolute value of firstGuessStepsize must be greater than eps($S) = $(eps(S))!")
end
if n_ex <= firstGuessOrder <= N_ex
m = firstGuessOrder # extrapolation order for first step
else
error("firstGuessOrder must be between $n_ex and $(N_ex)!")
end
counterStep = 1
counterReduction = 0
counterEvaluation = 0
converged = false
finished = maximumSteps == 0
x_n = ones(T,d) # storage for the latest solution
ϵ_n = zero(S) # storage for the latest error estimate
if safetyStepsizeSelection > 0
tol = safetyStepsizeSelection*tol # the tolerance for accuracy checks
else
error("safetyStepsizeSelection must be positive!")
end
# integration loop
while !finished
# the nth step: the approximation for the time t₀ + τ is saved in xΔ[n+1].
# check if the computation must be aborted
if counterStep > maximumSteps
println("Not finished. Exceeded maximal number of steps ($maximumSteps)")
return (Δ[1:counterStep], xΔ[:,1:counterStep], detailedStatistics ? statistics[:,1:counterStep-1] : statistics)
end
if counterReduction > maximumReduction
println("Not finished. Too many reductions in step number $(counterStep)!")
return (Δ[1:counterStep], xΔ[:,1:counterStep], detailedStatistics ? statistics[:,1:counterStep-1] : statistics)
end
if abs(τ) <= eps(S)
println("Stepsize is becoming too small in step $(counterStep)!")
return (Δ[1:counterStep], xΔ[:,1:counterStep], detailedStatistics ? statistics[:,1:counterStep-1] : statistics)
end
# preperations for current step:
n_win, N_win = max(n_ex, m - 1), min(N_ex, m + 1) # order window
n = n_win # start with smalles order in the order window
# compute all necessary internal approximations:
f₀ = f(t₀,x₀) # the information for the Euler step
counterEvaluation = counterEvaluation + 1
for i = 0:n
X[:,i+1] = explicitMidpointRule(t₀,x₀,f₀,f,τ,2*Int64(mySolver.subdividingSequence[i+1]))
counterEvaluation = counterEvaluation + 2*Int64(mySolver.subdividingSequence[i+1]) - 1
end
# compute all information relating to an extrapolation order ≦ n_win:
for i = n_ex : n
if rescaleWeights
# rescaling weights is equivalent to Lagrange interpolation
x_i= X[:, 1:(i+1)]*T.(broadcast(*,mySolver.ω,mySolver.ρ')[1:(i+1),(i+1)]) # discretisation of order i
xx_i = X[:, 2:(i+1)]*T.(broadcast(*,mySolver.ω2,mySolver.ρ2')[1:i, i]) # its internal counterpart
else
x_i = T.(mySolver.ρ[i+1])*(X[:, 1:(i+1)]*T.(mySolver.ω[1:(i+1), (i+1)]))
xx_i = T.(mySolver.ρ2[i])*(X[:, 2:(i+1)]*T.(mySolver.ω2[1:i, i]))
end
σ = max.(σₐ, σᵣ.*abs.(x_i)) # scaling for error estimate
ϵ_i = sqrt(sum((abs.(x_i-xx_i)./σ).^2)/d) # scaled mean square norm of the estimated error
λ[i-n_ex+1] = min(p2, max(p1, (tol/ϵ_i)^(1/(2i+1)))) # factor for optimal stepsize, including safety scaling
if i == n
x_n, ϵ_n = x_i, ϵ_i # save solution and error for the current order n
end
end
# check if soltution with for n in the order window can be accepted
while n <= N_win
if ϵ_n <= tol
# accept order n
converged = true
break
elseif ϵ_n <= tol^(s[n-n_ex+1]/s[N_win-n_ex+1])
# reject order n but pass convergence monitor
n = n + 1
# compute x_n, λ_n and ϵ_n for new n:
X[:,n+1] = explicitMidpointRule(t₀,x₀,f₀,f,τ,2*Int64.(mySolver.subdividingSequence[n+1]))
counterEvaluation = counterEvaluation + 2Int64(mySolver.subdividingSequence[n+1]) - 1
if rescaleWeights
# rescaling weights is equivalent to Lagrange interpolation
x_n= X[:, 1:(n+1)]*T.(broadcast(*,mySolver.ω,mySolver.ρ')[1:(n+1),(n+1)])
xx_n = X[:, 2:(n+1)]*T.(broadcast(*,mySolver.ω2,mySolver.ρ2')[1:n, n])
else
x_n = T.(mySolver.ρ[n+1])*(X[:, 1:(n+1)]*T.(mySolver.ω[1:(n+1), (n+1)])) # approximation of extrapolation order n
xx_n = T.(mySolver.ρ2[n])*(X[:, 2:(n+1)]*T.(mySolver.ω2[1:n, n])) # and its internal counterpart
end
σ = max.(σₐ, σᵣ.*abs.(x_n)) # scaling for error estimate
ϵ_n = sqrt(sum((abs.(x_n-xx_n)./σ).^2)/d) # scaled mean square norm of the estimated error
λ[n-n_ex+1] = min(p2,max(p1,(tol/ϵ_n)^(1/(2n+1)))) # factor for optimal stepsize, including safety scaling
else
# reject order n and not pass convergence monitor
break
end
end
if converged
# step is accepted, save x_n for the time t₀ + τ and update statistics
Δ[counterStep+1] = t₀ + τ
xΔ[:, counterStep+1] = x_n
tRest = tEnd - Δ[counterStep+1]
maximalSteplength = min(abs(tRest),maximalSteplength)
if detailedStatistics
statistics[:,counterStep] = [n, τ, counterEvaluation, counterReduction]
else
statistics = statistics + [counterEvaluation,counterReduction]
end
# check if tEnd is already reached
if abs(tRest) < eps(S)
finished = true
else
# preperations for the next step:
t₀, x₀ = Δ[counterStep+1], xΔ[:, counterStep+1] # new inital data
## compute optimal order m and stepsize τ for the next step acc. Deuflhard
# first compute the optimal extrapolation order
temp = (n_ex:n) .- n_ex .+ 1 # index range of computed quantities
τ_opt[temp] = min.(abs(τ)*λ[temp], maximalSteplength) # safety boundary for τ_opt
ω = s[temp]./(τ_opt[temp]) # work per step
m = argmin(ω) + n_ex - 1 # optimal order
# check if we may increase m
if m == n < N_win
# compute scaling for order m+1, including safety scaling
λ[n-n_ex+2] = min(p2, max(p1, (tol^(s[n-n_ex+1]/s[n-n_ex+2])/ϵ_n)^(1/(2n+1))))
# check if work dereases from order m to m+1
if ω[end] > s[n-n_ex+2]/(τ_opt[n-n_ex+2] = min(abs(τ)*λ[n-n_ex+2], maximalSteplength))
m = m + 1
end
end
τ = flipsign(τ_opt[m-n_ex+1],τ) # accomodate backward integration
counterStep = counterStep + 1
converged = false
counterEvaluation = 0
counterReduction = 0
fill!(λ,zero(S))
fill!(τ_opt,zero(S))
end
else
counterReduction = counterReduction + 1
# compute reduced stepsize τ for order m. Use latest error estimate ϵ_n if estimate of order m is not available
if n < m
λ[m-n_ex+1] = min(p2,max(p1,(tol^(s[n-n_ex+1]/s[m-n_ex+1])/ϵ_n)^(1/(2n+1))))
end
τ_opt[m-n_ex+1] = min(abs(τ)*λ[m-n_ex+1],maximalSteplength) # safety boundary for τ_opt
τ = flipsign(τ_opt[m-n_ex+1],τ) # accomodate backward integration
end
end # integration loop
return (Δ[1:counterStep+1], xΔ[:,1:counterStep+1], detailedStatistics ? statistics[:,1:counterStep] : statistics)
end
"""
explicitMidpointRule(t₀,x₀,f₀,f,τ,N)
Computes the value ``x_\\Delta(t_0 + \\tau)`` recursively. Here ``x_\\Delta`` is the grid-function generated
by the explicit midpoint rule on the equidistant grid `[t₀ + n/N*τ for n = 0:N]`
with the initial data `(t₀,x₀)` and the right side `f`.
In the starting step `f₀` is used instead of `f(t₀,x₀)`.
"""
function explicitMidpointRule(t₀::S,x₀::Vector{T},f₀::Vector{T},f::Function,τ::S,N) where{S<:AbstractFloat, T<:Number}
τ_n = τ/N
x = x₀ + τ_n*f₀
for i = 0:N-2
temp = x
x = x₀+2*τ_n*f(t₀+(i+1)*τ_n,x)
x₀ = temp
end
return x
end
export solver
end # module AdaptiveExtrapolationD
|
{
"alphanum_fraction": 0.6167438854,
"author": null,
"avg_line_length": 45.9455445545,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "3bc7f8ec5d023f17edf9ed266fca0db369075f8f",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ad4b97fb0c5c568574abcd9b378f5ae5d6958105",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "AlthausKonstantin/Extrapolation",
"max_forks_repo_path": "Solver/adaptive-extrapolation-Deuflhard.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad4b97fb0c5c568574abcd9b378f5ae5d6958105",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "AlthausKonstantin/Extrapolation",
"max_issues_repo_path": "Solver/adaptive-extrapolation-Deuflhard.jl",
"max_line_length": 214,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ad4b97fb0c5c568574abcd9b378f5ae5d6958105",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AlthausKonstantin/Extrapolation",
"max_stars_repo_path": "Solver/adaptive-extrapolation-Deuflhard.jl",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5291,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 18562
}
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
# @author Simon Heybrock, Neil Vaytet
import re
from copy import deepcopy
from contextlib import contextmanager
import uuid
import warnings
import numpy as np
import scipp as sc
import os
@contextmanager
def run_mantid_alg(alg, *args, **kwargs):
try:
from mantid import simpleapi as mantid
from mantid.api import AnalysisDataService
except ImportError:
raise ImportError(
"Mantid Python API was not found, please install Mantid framework "
"as detailed in the installation instructions ("
"https://scipp.github.io/scippneutron/getting-started/"
"installation.html)")
# Deal with multiple calls to this function, which may have conflicting
# names in the global AnalysisDataService by using uuid.
ws_name = f'scipp.run_mantid_alg.{uuid.uuid4()}'
# Deal with non-standard ways to define the prefix of output workspaces
if alg == 'Fit':
kwargs['Output'] = ws_name
elif alg == 'LoadDiffCal':
kwargs['WorkspaceName'] = ws_name
else:
kwargs['OutputWorkspace'] = ws_name
ws = getattr(mantid, alg)(*args, **kwargs)
try:
yield ws
finally:
for name in AnalysisDataService.Instance().getObjectNames():
if name.startswith(ws_name):
mantid.DeleteWorkspace(name)
def get_pos(pos):
return None if pos is None else sc.vector(
value=[pos.X(), pos.Y(), pos.Z()], unit=sc.units.m)
def make_run(ws):
return sc.scalar(deepcopy(ws.run()))
additional_unit_mapping = {
" ": sc.units.one,
"none": sc.units.one,
}
def make_variables_from_run_logs(ws):
for property_name in ws.run().keys():
units_string = ws.run()[property_name].units
try:
unit = additional_unit_mapping.get(units_string, sc.Unit(units_string))
except RuntimeError: # TODO catch UnitError once exposed from C++
# Parsing unit string failed
unit = None
values = deepcopy(ws.run()[property_name].value)
if units_string and unit is None:
warnings.warn(f"Workspace run log '{property_name}' "
f"has unrecognised units: '{units_string}'")
if unit is None:
unit = sc.units.one
try:
times = deepcopy(ws.run()[property_name].times)
is_time_series = True
dimension_label = "time"
except AttributeError:
times = None
is_time_series = False
dimension_label = property_name
if np.isscalar(values):
property_data = sc.scalar(values, unit=unit)
else:
property_data = sc.Variable(values=values,
unit=unit,
dims=[dimension_label])
if is_time_series:
# If property has timestamps, create a DataArray
data_array = sc.DataArray(data=property_data,
coords={
dimension_label:
sc.Variable(dims=[dimension_label],
values=times)
})
yield property_name, sc.scalar(data_array)
elif not np.isscalar(values):
# If property is multi-valued, create a wrapper single
# value variable. This prevents interference with
# global dimensions for for output Dataset.
yield property_name, sc.scalar(property_data)
else:
yield property_name, property_data
def make_mantid_sample(ws):
return sc.scalar(deepcopy(ws.sample()))
def make_sample_ub(ws):
# B matrix transforms the h,k,l triplet into a Cartesian system
# https://docs.mantidproject.org/nightly/concepts/Lattice.html
return sc.matrix(value=ws.sample().getOrientedLattice().getUB(),
unit=sc.units.angstrom**-1)
def make_sample_u(ws):
# U matrix rotation for sample alignment
# https://docs.mantidproject.org/nightly/concepts/Lattice.html
return sc.matrix(value=ws.sample().getOrientedLattice().getU())
def make_component_info(ws):
component_info = ws.componentInfo()
if component_info.hasSource():
sourcePos = component_info.sourcePosition()
else:
sourcePos = None
if component_info.hasSample():
samplePos = component_info.samplePosition()
else:
samplePos = None
return get_pos(sourcePos), get_pos(samplePos)
def make_detector_info(ws, spectrum_dim):
det_info = ws.detectorInfo()
# det -> spec mapping
nDet = det_info.size()
spectrum = np.empty(shape=(nDet, ), dtype=np.int32)
has_spectrum = np.full((nDet, ), False)
spec_info = ws.spectrumInfo()
for i, spec in enumerate(spec_info):
spec_def = spec.spectrumDefinition
for j in range(len(spec_def)):
det, time = spec_def[j]
if time != 0:
raise RuntimeError(
"Conversion of Mantid Workspace with scanning instrument "
"not supported yet.")
spectrum[det] = i
has_spectrum[det] = True
# Store only information about detectors with data (a spectrum). The rest
# mostly just gets in the way and including it in the default converter
# is probably not required.
spectrum = sc.array(dims=['detector'], values=spectrum[has_spectrum])
detector = sc.array(dims=['detector'], values=det_info.detectorIDs()[has_spectrum])
# May want to include more information here, such as detector positions,
# but for now this is not necessary.
return sc.scalar(sc.Dataset(coords={'detector': detector, spectrum_dim: spectrum}))
def md_dimension(mantid_dim, index):
# Look for q dimensions
patterns = ["^q.*{0}$".format(coord) for coord in ['x', 'y', 'z']]
q_dims = ['Q_x', 'Q_y', 'Q_z']
pattern_result = zip(patterns, q_dims)
if mantid_dim.getMDFrame().isQ():
for pattern, result in pattern_result:
if re.search(pattern, mantid_dim.name, re.IGNORECASE):
return result
# Look for common/known mantid dimensions
patterns = ["DeltaE", "T"]
dims = ['energy_transfer', 'temperature']
pattern_result = zip(patterns, dims)
for pattern, result in pattern_result:
if re.search(pattern, mantid_dim.name, re.IGNORECASE):
return result
# Look for common spacial dimensions
patterns = ["^{0}$".format(coord) for coord in ['x', 'y', 'z']]
dims = ['x', 'y', 'z']
pattern_result = zip(patterns, dims)
for pattern, result in pattern_result:
if re.search(pattern, mantid_dim.name, re.IGNORECASE):
return result
raise ValueError(
"Cannot infer scipp dimension from input mantid dimension {}".format(
mantid_dim.name()))
def md_unit(frame):
known_md_units = {
"Angstrom^-1": sc.units.dimensionless / sc.units.angstrom,
"r.l.u": sc.units.dimensionless,
"T": sc.units.K,
"DeltaE": sc.units.meV
}
if frame.getUnitLabel().ascii() in known_md_units:
return known_md_units[frame.getUnitLabel().ascii()]
else:
return sc.units.dimensionless
def validate_and_get_unit(unit, allow_empty=False):
if hasattr(unit, 'unitID'):
if unit.unitID() == 'Label':
unit = unit.name()
else:
unit = unit.unitID()
known_units = {
"DeltaE": ['energy_transfer', sc.units.meV],
"TOF": ['tof', sc.units.us],
"Wavelength": ['wavelength', sc.units.angstrom],
"Energy": ['energy', sc.units.meV],
"dSpacing": ['dspacing', sc.units.angstrom],
"MomentumTransfer": ['Q', sc.units.dimensionless / sc.units.angstrom],
"QSquared":
['Q^2', sc.units.dimensionless / (sc.units.angstrom * sc.units.angstrom)],
"Spectrum": ['spectrum', sc.units.dimensionless],
"Empty": ['empty', sc.units.dimensionless],
"Counts": ['counts', sc.units.counts]
}
if unit not in known_units.keys():
return [str(unit), sc.units.dimensionless]
else:
return known_units[unit]
def _to_spherical(pos, output):
output["r"] = sc.sqrt(sc.dot(pos, pos))
output["t"] = sc.acos(pos.fields.z / output["r"].data)
signed_phi = sc.atan2(y=pos.fields.y, x=pos.fields.x)
abs_phi = sc.abs(signed_phi)
output["p-delta"] = (np.pi *
sc.units.rad) - abs_phi # angular delta (magnitude) from pole
output['p-sign'] = signed_phi # weighted sign of phi
return output
def _rot_from_vectors(vec1, vec2):
a = sc.vector(value=vec1.value / np.linalg.norm(vec1.value))
b = sc.vector(value=vec2.value / np.linalg.norm(vec2.value))
c = sc.vector(value=np.cross(a.value, b.value))
angle = sc.acos(sc.dot(a, b)).value
return sc.matrix(value=sc.geometry.rotation_matrix_from_quaternion_coeffs(
list(c.value * np.sin(angle / 2)) + [np.cos(angle / 2)]))
def get_detector_pos(ws, spectrum_dim):
nHist = ws.getNumberHistograms()
pos = np.zeros([nHist, 3])
spec_info = ws.spectrumInfo()
for i in range(nHist):
if spec_info.hasDetectors(i):
p = spec_info.position(i)
pos[i, 0] = p.X()
pos[i, 1] = p.Y()
pos[i, 2] = p.Z()
else:
pos[i, :] = [np.nan, np.nan, np.nan]
return sc.vectors(dims=[spectrum_dim], values=pos, unit=sc.units.m)
def get_detector_properties(ws,
source_pos,
sample_pos,
spectrum_dim,
advanced_geometry=False):
if not advanced_geometry:
return (get_detector_pos(ws, spectrum_dim), None, None)
spec_info = ws.spectrumInfo()
det_info = ws.detectorInfo()
comp_info = ws.componentInfo()
nspec = len(spec_info)
det_rot = np.zeros([nspec, 3, 3])
det_bbox = np.zeros([nspec, 3])
if sample_pos is not None and source_pos is not None:
total_detectors = spec_info.detectorCount()
act_beam = (sample_pos - source_pos)
rot = _rot_from_vectors(act_beam, sc.vector(value=[0, 0, 1]))
inv_rot = _rot_from_vectors(sc.vector(value=[0, 0, 1]), act_beam)
pos_d = sc.Dataset()
# Create empty to hold position info for all spectra detectors
pos_d["x"] = sc.zeros(dims=["detector"],
shape=[total_detectors],
unit=sc.units.m)
pos_d["y"] = sc.zeros_like(pos_d["x"])
pos_d["z"] = sc.zeros_like(pos_d["x"])
pos_d.coords[spectrum_dim] = sc.array(dims=["detector"],
values=np.empty(total_detectors))
spectrum_values = pos_d.coords[spectrum_dim].values
x_values = pos_d["x"].values
y_values = pos_d["y"].values
z_values = pos_d["z"].values
idx = 0
for i, spec in enumerate(spec_info):
if spec.hasDetectors:
definition = spec_info.getSpectrumDefinition(i)
n_dets = len(definition)
quats = []
bboxes = []
for j in range(n_dets):
det_idx = definition[j][0]
p = det_info.position(det_idx)
r = det_info.rotation(det_idx)
spectrum_values[idx] = i
x_values[idx] = p.X()
y_values[idx] = p.Y()
z_values[idx] = p.Z()
idx += 1
quats.append(np.array([r.imagI(), r.imagJ(), r.imagK(), r.real()]))
if comp_info.hasValidShape(det_idx):
s = comp_info.shape(det_idx)
bboxes.append(s.getBoundingBox().width())
det_rot[i, :] = sc.geometry.rotation_matrix_from_quaternion_coeffs(
np.mean(quats, axis=0))
det_bbox[i, :] = np.sum(bboxes, axis=0)
rot_pos = rot * sc.geometry.position(pos_d["x"].data, pos_d["y"].data,
pos_d["z"].data)
_to_spherical(rot_pos, pos_d)
averaged = sc.groupby(pos_d,
spectrum_dim,
bins=sc.Variable(dims=[spectrum_dim],
values=np.arange(
-0.5,
len(spec_info) + 0.5,
1.0))).mean("detector")
sign = averaged["p-sign"].data / sc.abs(averaged["p-sign"].data)
averaged["p"] = sign * ((np.pi * sc.units.rad) - averaged["p-delta"].data)
averaged["x"] = averaged["r"].data * sc.sin(averaged["t"].data) * sc.cos(
averaged["p"].data)
averaged["y"] = averaged["r"].data * sc.sin(averaged["t"].data) * sc.sin(
averaged["p"].data)
averaged["z"] = averaged["r"].data * sc.cos(averaged["t"].data)
pos = sc.geometry.position(averaged["x"].data, averaged["y"].data,
averaged["z"].data)
return (inv_rot * pos, sc.matrices(dims=[spectrum_dim], values=det_rot),
sc.vectors(dims=[spectrum_dim], values=det_bbox, unit=sc.units.m))
else:
pos = np.zeros([nspec, 3])
for i, spec in enumerate(spec_info):
if spec.hasDetectors:
definition = spec_info.getSpectrumDefinition(i)
n_dets = len(definition)
vec3s = []
quats = []
bboxes = []
for j in range(n_dets):
det_idx = definition[j][0]
p = det_info.position(det_idx)
r = det_info.rotation(det_idx)
vec3s.append([p.X(), p.Y(), p.Z()])
quats.append(np.array([r.imagI(), r.imagJ(), r.imagK(), r.real()]))
if comp_info.hasValidShape(det_idx):
s = comp_info.shape(det_idx)
bboxes.append(s.getBoundingBox().width())
pos[i, :] = np.mean(vec3s, axis=0)
det_rot[i, :] = sc.geometry.rotation_matrix_from_quaternion_coeffs(
np.mean(quats, axis=0))
det_bbox[i, :] = np.sum(bboxes, axis=0)
else:
pos[i, :] = [np.nan, np.nan, np.nan]
det_rot[i, :] = [np.nan, np.nan, np.nan, np.nan]
det_bbox[i, :] = [np.nan, np.nan, np.nan]
return (sc.vectors(dims=[spectrum_dim], values=pos, unit=sc.units.m),
sc.matrices(dims=[spectrum_dim], values=det_rot),
sc.vectors(
dims=[spectrum_dim],
values=det_bbox,
unit=sc.units.m,
))
def _get_dtype_from_values(values, coerce_floats_to_ints):
if coerce_floats_to_ints and np.all(np.mod(values, 1.0) == 0.0):
dtype = sc.dtype.int32
elif hasattr(values, 'dtype'):
dtype = values.dtype
else:
if len(values) > 0:
dtype = type(values[0])
if dtype is str:
dtype = sc.dtype.string
elif dtype is int:
dtype = sc.dtype.int64
elif dtype is float:
dtype = sc.dtype.float64
else:
raise RuntimeError("Cannot handle the dtype that this "
"workspace has on Axis 1.")
else:
raise RuntimeError("Axis 1 of this workspace has no values. "
"Cannot determine dtype.")
return dtype
def init_spec_axis(ws):
axis = ws.getAxis(1)
dim, unit = validate_and_get_unit(axis.getUnit())
values = axis.extractValues()
dtype = _get_dtype_from_values(values, dim == 'spectrum')
return dim, sc.Variable(dims=[dim], values=values, unit=unit, dtype=dtype)
def set_bin_masks(bin_masks, dim, index, masked_bins):
for masked_bin in masked_bins:
bin_masks['spectrum', index][dim, masked_bin].value = True
def _convert_MatrixWorkspace_info(ws, advanced_geometry=False, load_run_logs=True):
from mantid.kernel import DeltaEModeType
common_bins = ws.isCommonBins()
dim, unit = validate_and_get_unit(ws.getAxis(0).getUnit())
source_pos, sample_pos = make_component_info(ws)
spec_dim, spec_coord = init_spec_axis(ws)
pos, rot, shp = get_detector_properties(ws,
source_pos,
sample_pos,
spec_dim,
advanced_geometry=advanced_geometry)
coords = {spec_dim: spec_coord}
# possible x - coord
if not ws.id() == 'MaskWorkspace':
if common_bins:
coords[dim] = sc.Variable(dims=[dim], values=ws.readX(0), unit=unit)
else:
coords[dim] = sc.Variable(dims=[spec_dim, dim],
values=ws.extractX(),
unit=unit)
info = {
"coords": coords,
"masks": {},
"attrs": {
"sample": make_mantid_sample(ws),
"instrument_name":
sc.scalar(ws.componentInfo().name(ws.componentInfo().root()))
},
}
if load_run_logs:
for run_log_name, run_log_variable in make_variables_from_run_logs(ws):
info["attrs"][run_log_name] = run_log_variable
if advanced_geometry:
info["coords"]["detector_info"] = make_detector_info(ws, spec_dim)
if not np.all(np.isnan(pos.values)):
info["coords"].update({"position": pos})
if rot is not None and shp is not None and not np.all(np.isnan(pos.values)):
info["attrs"].update({"rotation": rot, "shape": shp})
if source_pos is not None:
info["coords"]["source_position"] = source_pos
if sample_pos is not None:
info["coords"]["sample_position"] = sample_pos
if ws.detectorInfo().hasMaskedDetectors():
spectrum_info = ws.spectrumInfo()
mask = np.array(
[spectrum_info.isMasked(i) for i in range(ws.getNumberHistograms())])
info["masks"][spec_dim] = sc.Variable(dims=[spec_dim], values=mask)
if ws.getEMode() == DeltaEModeType.Direct:
info["coords"]["incident_energy"] = _extract_einitial(ws)
elif ws.getEMode() == DeltaEModeType.Indirect:
info["coords"]["final_energy"] = _extract_efinal(ws, spec_dim)
if ws.sample().hasOrientedLattice():
info["attrs"].update({
"sample_ub": make_sample_ub(ws),
"sample_u": make_sample_u(ws)
})
return info
def convert_monitors_ws(ws, converter, **ignored):
spec_dim, spec_coord = init_spec_axis(ws)
spec_info = ws.spectrumInfo()
comp_info = ws.componentInfo()
monitors = []
spec_indices = ((ws.getIndexFromSpectrumNumber(int(i)), i)
for i in spec_coord.values)
for index, number in spec_indices:
definition = spec_info.getSpectrumDefinition(index)
if not definition.size() == 1:
raise RuntimeError("Cannot deal with grouped monitor detectors")
det_index = definition[0][0] # Ignore time index
# We only ExtractSpectra for compatibility with
# existing convert_Workspace2D_to_dataarray. This could instead be
# refactored if found to be slow
with run_mantid_alg('ExtractSpectra',
InputWorkspace=ws,
WorkspaceIndexList=[index]) as monitor_ws:
# Run logs are already loaded in the data workspace
single_monitor = converter(monitor_ws, load_run_logs=False)
# Storing sample_position as a coord of monitors means that monitor
# data cannot be combined with scattered data even after conversion
# to wavelength, d-spacing, etc. because conversions of monitors do
# not use the sample position.
# But keep it as an attr in case a user needs it.
single_monitor.attrs['sample_position'] = single_monitor.coords.pop(
'sample_position')
# Remove redundant information that is duplicated from workspace
# We get this extra information from the generic converter reuse
if 'detector_info' in single_monitor.coords:
del single_monitor.coords['detector_info']
del single_monitor.attrs['sample']
name = comp_info.name(det_index)
if not comp_info.uniqueName(name):
name = f'{name}_{number}'
monitors.append((name, single_monitor))
return monitors
def convert_Workspace2D_to_data_array(ws,
load_run_logs=True,
advanced_geometry=False,
**ignored):
dim, unit = validate_and_get_unit(ws.getAxis(0).getUnit())
spec_dim, spec_coord = init_spec_axis(ws)
coords_labs_data = _convert_MatrixWorkspace_info(
ws, advanced_geometry=advanced_geometry, load_run_logs=load_run_logs)
_, data_unit = validate_and_get_unit(ws.YUnit(), allow_empty=True)
if ws.id() == 'MaskWorkspace':
coords_labs_data["data"] = sc.Variable(dims=[spec_dim],
unit=data_unit,
values=ws.extractY().flatten(),
dtype=sc.dtype.bool)
else:
stddev2 = ws.extractE()
np.multiply(stddev2, stddev2, out=stddev2) # much faster than np.power
coords_labs_data["data"] = sc.Variable(dims=[spec_dim, dim],
unit=data_unit,
values=ws.extractY(),
variances=stddev2)
array = sc.DataArray(**coords_labs_data)
if ws.hasAnyMaskedBins():
bin_mask = sc.zeros(dims=array.dims, shape=array.shape, dtype=sc.dtype.bool)
for i in range(ws.getNumberHistograms()):
# maskedBinsIndices throws instead of returning empty list
if ws.hasMaskedBins(i):
set_bin_masks(bin_mask, dim, i, ws.maskedBinsIndices(i))
common_mask = sc.all(bin_mask, spec_dim)
if sc.identical(common_mask, sc.any(bin_mask, spec_dim)):
array.masks["bin"] = common_mask
else:
array.masks["bin"] = bin_mask
# Avoid creating dimensions that are not required since this mostly an
# artifact of inflexible data structures and gets in the way when working
# with scipp.
if len(spec_coord.values) == 1:
if 'position' in array.coords:
array.coords['position'] = array.coords['position'][spec_dim, 0]
array = array[spec_dim, 0].copy()
return array
def convert_EventWorkspace_to_data_array(ws,
load_pulse_times=True,
advanced_geometry=False,
load_run_logs=True,
**ignored):
from mantid.api import EventType
dim, unit = validate_and_get_unit(ws.getAxis(0).getUnit())
spec_dim, spec_coord = init_spec_axis(ws)
nHist = ws.getNumberHistograms()
_, data_unit = validate_and_get_unit(ws.YUnit(), allow_empty=True)
n_event = ws.getNumberEvents()
coord = sc.zeros(dims=['event'], shape=[n_event], unit=unit, dtype=sc.dtype.float64)
weights = sc.ones(dims=['event'],
shape=[n_event],
unit=data_unit,
dtype=sc.dtype.float32,
with_variances=True)
pulse_times = sc.empty(
dims=['event'], shape=[n_event], dtype=sc.dtype.datetime64,
unit=sc.units.ns) if load_pulse_times else None
evtp = ws.getSpectrum(0).getEventType()
contains_weighted_events = ((evtp == EventType.WEIGHTED)
or (evtp == EventType.WEIGHTED_NOTIME))
begins = sc.zeros(dims=[spec_dim, dim], shape=[nHist, 1], dtype=sc.dtype.int64)
ends = begins.copy()
current = 0
for i in range(nHist):
sp = ws.getSpectrum(i)
size = sp.getNumberEvents()
coord['event', current:current + size].values = sp.getTofs()
if load_pulse_times:
pulse_times['event',
current:current + size].values = sp.getPulseTimesAsNumpy()
if contains_weighted_events:
weights['event', current:current + size].values = sp.getWeights()
weights['event', current:current + size].variances = sp.getWeightErrors()
begins.values[i] = current
ends.values[i] = current + size
current += size
proto_events = {'data': weights, 'coords': {dim: coord}}
if load_pulse_times:
proto_events["coords"]["pulse_time"] = pulse_times
events = sc.DataArray(**proto_events)
coords_labs_data = _convert_MatrixWorkspace_info(
ws, advanced_geometry=advanced_geometry, load_run_logs=load_run_logs)
# For now we ignore potential finer bin edges to avoid creating too many
# bins. Use just a single bin along dim and use extents given by workspace
# edges.
# TODO If there are events outside edges this might create bins with
# events that are not within bin bounds. Consider using `bin` instead
# of `bins`?
edges = coords_labs_data['coords'][dim]
# Using range slice of thickness 1 to avoid transposing 2-D coords
coords_labs_data['coords'][dim] = sc.concatenate(edges[dim, :1], edges[dim, -1:],
dim)
coords_labs_data["data"] = sc.bins(begin=begins, end=ends, dim='event', data=events)
return sc.DataArray(**coords_labs_data)
def convert_MDHistoWorkspace_to_data_array(md_histo, **ignored):
ndims = md_histo.getNumDims()
coords = dict()
dims_used = []
for i in range(ndims):
dim = md_histo.getDimension(i)
frame = dim.getMDFrame()
sc_dim = md_dimension(dim, i)
coords[sc_dim] = sc.Variable(dims=[sc_dim],
values=np.linspace(dim.getMinimum(),
dim.getMaximum(),
dim.getNBins()),
unit=md_unit(frame))
dims_used.append(sc_dim)
data = sc.Variable(dims=dims_used,
values=md_histo.getSignalArray(),
variances=md_histo.getErrorSquaredArray(),
unit=sc.units.counts)
nevents = sc.Variable(dims=dims_used, values=md_histo.getNumEventsArray())
return sc.DataArray(coords=coords, data=data, attrs={'nevents': nevents})
def convert_TableWorkspace_to_dataset(ws, error_connection=None, **ignored):
"""
Converts from a Mantid TableWorkspace to a scipp dataset. It is possible
to assign a column as the error for another column, in which case a
the data from the two columns will be represented by a single scipp
variable with variance. This is done using the error_connection Keyword
argument. The error is transformed to variance in this converter.
Parameters
----------
ws : Mantid TableWorkspace
Mantid TableWorkspace to be converted into scipp dataset
Keyword arguments
-----------------
error_connection : Dict
Dict with data column names as keys to names of their error column
"""
# Extract information from workspace
n_columns = ws.columnCount()
columnNames = ws.getColumnNames() # list of names matching each column
columnTypes = ws.columnTypes() # list of types matching each column
# Types available in TableWorkspace that can not be loaded into scipp
blacklist_types = []
# Types for which the transformation from error to variance will fail
blacklist_variance_types = ["str"]
dataset = sc.Dataset()
for i in range(n_columns):
if columnTypes[i] in blacklist_types:
continue # skips loading data of this type
data_name = columnNames[i]
if error_connection is None:
dataset[data_name] = sc.Variable(dims=['row'], values=ws.column(i))
elif data_name in error_connection:
# This data has error availble
error_name = error_connection[data_name]
error_index = columnNames.index(error_name)
if columnTypes[error_index] in blacklist_variance_types:
# Raise error to avoid numpy square error for strings
raise RuntimeError("Variance can not have type string. \n" +
"Data: " + str(data_name) + "\n" + "Variance: " +
str(error_name) + "\n")
variance = np.array(ws.column(error_name))**2
dataset[data_name] = sc.Variable(dims=['row'],
values=np.array(ws.column(i)),
variances=variance)
elif data_name not in error_connection.values():
# This data is not an error for another dataset, and has no error
dataset[data_name] = sc.Variable(dims=['row'], values=ws.column(i))
return dataset
def convert_WorkspaceGroup_to_dataarray_dict(group_workspace, **kwargs):
workspace_dict = {}
for i in range(group_workspace.getNumberOfEntries()):
workspace = group_workspace.getItem(i)
workspace_name = workspace.name().replace(f'{group_workspace.name()}',
'').strip('_')
workspace_dict[workspace_name] = from_mantid(workspace, **kwargs)
return workspace_dict
def from_mantid(workspace, **kwargs):
"""Convert Mantid workspace to a scipp data array or dataset.
:param workspace: Mantid workspace to convert.
"""
scipp_obj = None # This is either a Dataset or DataArray
monitor_ws = None
workspaces_to_delete = []
w_id = workspace.id()
if (w_id == 'Workspace2D' or w_id == 'RebinnedOutput' or w_id == 'MaskWorkspace'):
n_monitor = 0
spec_info = workspace.spectrumInfo()
for i in range(len(spec_info)):
if spec_info.hasDetectors(i) and spec_info.isMonitor(i):
n_monitor += 1
# If there are *only* monitors we do not move them to an attribute
if n_monitor > 0 and n_monitor < len(spec_info):
import mantid.simpleapi as mantid
workspace, monitor_ws = mantid.ExtractMonitors(workspace)
workspaces_to_delete.append(workspace)
workspaces_to_delete.append(monitor_ws)
scipp_obj = convert_Workspace2D_to_data_array(workspace, **kwargs)
elif w_id == 'EventWorkspace':
scipp_obj = convert_EventWorkspace_to_data_array(workspace, **kwargs)
elif w_id == 'TableWorkspace':
scipp_obj = convert_TableWorkspace_to_dataset(workspace, **kwargs)
elif w_id == 'MDHistoWorkspace':
scipp_obj = convert_MDHistoWorkspace_to_data_array(workspace, **kwargs)
elif w_id == 'WorkspaceGroup':
scipp_obj = convert_WorkspaceGroup_to_dataarray_dict(workspace, **kwargs)
if scipp_obj is None:
raise RuntimeError('Unsupported workspace type {}'.format(w_id))
# TODO Is there ever a case where a Workspace2D has a separate monitor
# workspace? This is not handled by ExtractMonitors above, I think.
if monitor_ws is None:
if hasattr(workspace, 'getMonitorWorkspace'):
try:
monitor_ws = workspace.getMonitorWorkspace()
except RuntimeError:
# Have to try/fail here. No inspect method on Mantid for this.
pass
if monitor_ws is not None:
if monitor_ws.id() == 'MaskWorkspace' or monitor_ws.id() == 'Workspace2D':
converter = convert_Workspace2D_to_data_array
elif monitor_ws.id() == 'EventWorkspace':
converter = convert_EventWorkspace_to_data_array
monitors = convert_monitors_ws(monitor_ws, converter, **kwargs)
for name, monitor in monitors:
scipp_obj.attrs[name] = sc.scalar(monitor)
for ws in workspaces_to_delete:
mantid.DeleteWorkspace(ws)
return scipp_obj
def load(filename="",
load_pulse_times=True,
instrument_filename=None,
error_connection=None,
mantid_alg='Load',
mantid_args=None,
advanced_geometry=False):
"""
Wrapper function to provide a load method for a Nexus file, hiding mantid
specific code from the scipp interface. All other keyword arguments not
specified in the parameters below are passed on to the mantid.Load
function.
Example of use:
.. highlight:: python
.. code-block:: python
from scipp.neutron import load
d = sc.Dataset()
d["sample"] = load(filename='PG3_4844_event.nxs',
load_pulse_times=False,
mantid_args={'BankName': 'bank184',
'LoadMonitors': True})
See also the neutron-data tutorial.
Note that this function requires mantid to be installed and available in
the same Python environment as scipp.
:param str filename: The name of the Nexus/HDF file to be loaded.
:param bool load_pulse_times: Read the pulse times if True.
:param str instrument_filename: If specified, over-write the instrument
definition in the final Dataset with the
geometry contained in the file.
:param str mantid_alg: Mantid algorithm to use for loading. Default is
`Load`.
:param dict mantid_args: Dict of keyword arguments to forward to Mantid.
:param bool advanced_geometry: If True, load the full detector geometry
including shapes and rotations. The
positions of grouped detectors are
spherically averaged. If False,
load only the detector position, and return
the cartesian average of the grouped
detector positions.
:raises: If the Mantid workspace type returned by the Mantid loader is not
either EventWorkspace or Workspace2D.
:return: A Dataset containing the neutron event/histogram data and the
instrument geometry.
:rtype: Dataset
"""
if mantid_args is None:
mantid_args = {}
_check_file_path(str(filename), mantid_alg)
with run_mantid_alg(mantid_alg, str(filename), **mantid_args) as loaded:
# Determine what Load has provided us
from mantid.api import Workspace
if isinstance(loaded, Workspace):
# A single workspace
data_ws = loaded
else:
# Separate data and monitor workspaces
data_ws = loaded.OutputWorkspace
if instrument_filename is not None:
import mantid.simpleapi as mantid
mantid.LoadInstrument(data_ws,
FileName=instrument_filename,
RewriteSpectraMap=True)
return from_mantid(data_ws,
load_pulse_times=load_pulse_times,
error_connection=error_connection,
advanced_geometry=advanced_geometry)
def _is_mantid_loadable(filename):
from mantid.api import FileFinder
if FileFinder.getFullPath(filename):
return True
else:
try:
# findRuns throws rather than return empty so need try-catch
FileFinder.findRuns(filename)
return True
except Exception:
return False
def _check_file_path(filename, mantid_alg):
from mantid.api import AlgorithmManager, FrameworkManager, FileProperty
FrameworkManager.Instance()
alg = AlgorithmManager.createUnmanaged(mantid_alg)
filename_property = [
prop for prop in alg.getProperties() if isinstance(prop, FileProperty)
]
# Only with FileProperty can Mantid take fuzzy matches to filenames and run numbers
# If the top level Load algorithm is requested (has no properties of its own)
# we know that it's child algorithm uses FileProperty. If the child algorithm
# is called directly we attempt to find FileProperty. Otherwise paths should be
# absolute
if filename_property or mantid_alg == 'Load':
if not _is_mantid_loadable(filename):
raise ValueError(
f"Mantid cannot find {filename} and therefore will not load it."
) from None
else:
if not os.path.isfile(filename):
raise ValueError(
f"Cannot find file {filename} and therefore will not load it.")
def validate_dim_and_get_mantid_string(unit_dim):
known_units = {
'energy_transfer': "DeltaE",
'tof': "TOF",
'wavelength': "Wavelength",
'energy': "Energy",
'dspacing': "dSpacing",
'Q': "MomentumTransfer",
'Q^2': "QSquared",
}
user_k = str(unit_dim).casefold()
known_units = {k.casefold(): v for k, v in known_units.items()}
if user_k not in known_units:
raise RuntimeError("Axis unit not currently supported."
"Possible values are: {}, "
"got '{}'. ".format([k for k in known_units.keys()],
unit_dim))
else:
return known_units[user_k]
def to_mantid(data, dim, instrument_file=None):
"""
Convert data to a Mantid workspace.
The Mantid layout expect the spectra to be the Outer-most dimension,
i.e. y.shape[0]. If that is not the case you might have to transpose
your data to fit that, otherwise it will not be aligned correctly in the
Mantid workspace.
:param data: Data to be converted.
:param dim: Coord to use for Mantid's first axis (X).
:param instrument_file: Instrument file that will be
loaded into the workspace
:returns: Workspace containing converted data. The concrete workspace type
may differ depending on the content of `data`.
"""
if not isinstance(data, sc.DataArray):
raise RuntimeError(
"Currently only data arrays can be converted to a Mantid workspace")
try:
import mantid.simpleapi as mantid
except ImportError:
raise ImportError(
"Mantid Python API was not found, please install Mantid framework "
"as detailed in the installation instructions (https://scipp."
"github.io/getting-started/installation.html)")
x = data.coords[dim].values
y = data.values
e = data.variances
assert (len(y.shape) == 2 or len(y.shape) == 1), \
"Currently can only handle 2D data."
e = np.sqrt(e) if e is not None else np.sqrt(y)
# Convert a single array (e.g. single spectra) into 2d format
if len(y.shape) == 1:
y = np.array([y])
if len(e.shape) == 1:
e = np.array([e])
unitX = validate_dim_and_get_mantid_string(dim)
nspec = y.shape[0]
if len(x.shape) == 1:
# SCIPP is using a 1:n spectra coord mapping, Mantid needs
# a 1:1 mapping so expand this out
x = np.broadcast_to(x, shape=(nspec, len(x)))
nbins = x.shape[1]
nitems = y.shape[1]
ws = mantid.WorkspaceFactory.create("Workspace2D",
NVectors=nspec,
XLength=nbins,
YLength=nitems)
if data.unit != sc.units.counts:
ws.setDistribution(True)
for i in range(nspec):
ws.setX(i, x[i])
ws.setY(i, y[i])
ws.setE(i, e[i])
# Set X-Axis unit
ws.getAxis(0).setUnit(unitX)
if instrument_file is not None:
mantid.LoadInstrument(ws, FileName=instrument_file, RewriteSpectraMap=True)
return ws
def _table_to_data_array(table, key, value, stddev):
stddevs = table[stddev].values
dim = 'parameter'
coord = table[key].data.copy().rename_dims({'row': dim})
return sc.DataArray(data=sc.Variable(dims=[dim],
values=table[value].values,
variances=stddevs * stddevs),
coords={dim: coord})
def _fit_workspace(ws, mantid_args):
"""
Performs a fit on the workspace.
:param ws: The workspace on which the fit will be performed
:returns: Dataset containing all of Fit's outputs
"""
with run_mantid_alg('Fit', InputWorkspace=ws, **mantid_args,
CreateOutput=True) as fit:
# This is assuming that all parameters are dimensionless. If this is
# not the case we should use a dataset with a scalar variable per
# parameter instead. Or better, a dict of scalar variables?
parameters = convert_TableWorkspace_to_dataset(fit.OutputParameters)
parameters = _table_to_data_array(parameters,
key='Name',
value='Value',
stddev='Error')
out = convert_Workspace2D_to_data_array(fit.OutputWorkspace)
data = sc.Dataset()
data['data'] = out['empty', 0]
data['calculated'] = out['empty', 1]
data['diff'] = out['empty', 2]
parameters.coords['status'] = sc.scalar(fit.OutputStatus)
parameters.coords['chi^2/d.o.f.'] = sc.scalar(fit.OutputChi2overDoF)
parameters.coords['function'] = sc.scalar(str(fit.Function))
parameters.coords['cost_function'] = sc.scalar(fit.CostFunction)
return parameters, data
def fit(data, mantid_args):
if len(data.dims) != 1 or 'WorkspaceIndex' in mantid_args:
raise RuntimeError("Only 1D fitting is supported. Use scipp slicing and do not"
"provide a WorkspaceIndex.")
dim = data.dims[0]
ws = to_mantid(data, dim)
mantid_args['workspace_index'] = 0
return _fit_workspace(ws, mantid_args)
def _try_except(op, possible_except, failure, **kwargs):
try:
return op(**kwargs)
except possible_except:
return failure
def _get_instrument_efixed(workspace):
inst = workspace.getInstrument()
if inst.hasParameter('Efixed'):
return inst.getNumberParameter('EFixed')[0]
if inst.hasParameter('analyser'):
analyser_name = inst.getStringParameter('analyser')[0]
analyser_comp = inst.getComponentByName(analyser_name)
if analyser_comp is not None and analyser_comp.hasParameter('Efixed'):
return analyser_comp.getNumberParameter('EFixed')[0]
return None
def _extract_einitial(ws):
if ws.run().hasProperty("Ei"):
ei = ws.run().getProperty("Ei").value
elif ws.run().hasProperty('EnergyRequest'):
ei = ws.run().getProperty('EnergyRequest').value[-1]
else:
ei = 0
return sc.scalar(ei, unit=sc.Unit("meV"))
def _extract_efinal(ws, spec_dim):
detInfo = ws.detectorInfo()
specInfo = ws.spectrumInfo()
ef = np.empty(shape=(specInfo.size(), ), dtype=float)
ef[:] = np.nan
analyser_ef = _get_instrument_efixed(workspace=ws)
ids = detInfo.detectorIDs()
for spec_index in range(len(specInfo)):
detector_ef = None
if specInfo.hasDetectors(spec_index):
# Just like mantid, we only take the first entry of the group.
det_index = specInfo.getSpectrumDefinition(spec_index)[0][0]
detector_ef = _try_except(op=ws.getEFixed,
possible_except=RuntimeError,
failure=None,
detId=int(ids[det_index]))
detector_ef = detector_ef if detector_ef is not None else analyser_ef
if not detector_ef:
continue # Cannot assign an Ef. May or may not be an error
# - i.e. a diffraction detector, monitor etc.
ef[spec_index] = detector_ef
return sc.Variable(dims=[spec_dim], values=ef, unit=sc.Unit("meV"))
|
{
"alphanum_fraction": 0.591924456,
"author": null,
"avg_line_length": 39.912,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "890f803787012e72b70dbae9cf35ad9e6fdbe070",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "20283e7b8f8772776978c539f8664f889d1fbded",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "arm61/scippneutron",
"max_forks_repo_path": "python/src/scippneutron/mantid.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "20283e7b8f8772776978c539f8664f889d1fbded",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "arm61/scippneutron",
"max_issues_repo_path": "python/src/scippneutron/mantid.py",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "20283e7b8f8772776978c539f8664f889d1fbded",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "arm61/scippneutron",
"max_stars_repo_path": "python/src/scippneutron/mantid.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9836,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 44901
}
|
[STATEMENT]
lemma integral_bigo:
fixes f g g' :: "real \<Rightarrow> real"
assumes "f \<in> O(g')" and "filterlim g at_top at_top"
assumes "\<And>a' x. a \<le> a' \<Longrightarrow> a' \<le> x \<Longrightarrow> f integrable_on {a'..x}"
assumes deriv: "\<And>x. x \<ge> a \<Longrightarrow> (g has_field_derivative g' x) (at x within {a..})"
assumes cont: "continuous_on {a..} g'"
assumes nonneg: "\<And>x. x \<ge> a \<Longrightarrow> g' x \<ge> 0"
shows "(\<lambda>x. integral {a..x} f) \<in> O(g)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
note [continuous_intros] = continuous_on_subset[OF cont]
[PROOF STATE]
proof (state)
this:
?t \<subseteq> {a..} \<Longrightarrow> continuous_on ?t g'
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
from landau_o.bigE[OF assms(1)]
[PROOF STATE]
proof (chain)
picking this:
(\<And>c. \<lbrakk>0 < c; \<forall>\<^sub>F x in at_top. norm (f x) \<le> c * norm (g' x)\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
[PROOF STEP]
obtain c b where c: "c > 0" and b: "\<And>x. x \<ge> b \<Longrightarrow> norm (f x) \<le> c * norm (g' x)"
[PROOF STATE]
proof (prove)
using this:
(\<And>c. \<lbrakk>0 < c; \<forall>\<^sub>F x in at_top. norm (f x) \<le> c * norm (g' x)\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
goal (1 subgoal):
1. (\<And>c b. \<lbrakk>0 < c; \<And>x. b \<le> x \<Longrightarrow> norm (f x) \<le> c * norm (g' x)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
unfolding eventually_at_top_linorder
[PROOF STATE]
proof (prove)
using this:
(\<And>c. \<lbrakk>0 < c; \<exists>N. \<forall>n\<ge>N. norm (f n) \<le> c * norm (g' n)\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
goal (1 subgoal):
1. (\<And>c b. \<lbrakk>0 < c; \<And>x. b \<le> x \<Longrightarrow> norm (f x) \<le> c * norm (g' x)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by metis
[PROOF STATE]
proof (state)
this:
0 < c
b \<le> ?x \<Longrightarrow> norm (f ?x) \<le> c * norm (g' ?x)
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
define c' where "c' = c / 2"
[PROOF STATE]
proof (state)
this:
c' = c / 2
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
define b' where "b' = max a b"
[PROOF STATE]
proof (state)
this:
b' = max a b
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
define D where "D = norm (integral {a..b'} f)"
[PROOF STATE]
proof (state)
this:
D = norm (integral {a..b'} f)
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
have "filterlim (\<lambda>x. c * g x) at_top at_top"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. LIM x at_top. c * g x :> at_top
[PROOF STEP]
using c
[PROOF STATE]
proof (prove)
using this:
0 < c
goal (1 subgoal):
1. LIM x at_top. c * g x :> at_top
[PROOF STEP]
by (intro filterlim_tendsto_pos_mult_at_top[OF tendsto_const] assms)
[PROOF STATE]
proof (state)
this:
LIM x at_top. c * g x :> at_top
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
hence "eventually (\<lambda>x. c * g x \<ge> D - c * g b') at_top"
[PROOF STATE]
proof (prove)
using this:
LIM x at_top. c * g x :> at_top
goal (1 subgoal):
1. \<forall>\<^sub>F x in at_top. D - c * g b' \<le> c * g x
[PROOF STEP]
by (auto simp: filterlim_at_top)
[PROOF STATE]
proof (state)
this:
\<forall>\<^sub>F x in at_top. D - c * g b' \<le> c * g x
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
hence "eventually (\<lambda>x. norm (integral {a..x} f) \<le> 2 * c * norm (g x)) at_top"
[PROOF STATE]
proof (prove)
using this:
\<forall>\<^sub>F x in at_top. D - c * g b' \<le> c * g x
goal (1 subgoal):
1. \<forall>\<^sub>F x in at_top. norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
using eventually_ge_at_top[of b']
[PROOF STATE]
proof (prove)
using this:
\<forall>\<^sub>F x in at_top. D - c * g b' \<le> c * g x
eventually ((\<le>) b') at_top
goal (1 subgoal):
1. \<forall>\<^sub>F x in at_top. norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
proof eventually_elim
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
case (elim x)
[PROOF STATE]
proof (state)
this:
D - c * g b' \<le> c * g x
b' \<le> x
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
have b': "a \<le> b'" "b \<le> b'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. a \<le> b' &&& b \<le> b'
[PROOF STEP]
by (auto simp: b'_def)
[PROOF STATE]
proof (state)
this:
a \<le> b'
b \<le> b'
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
from elim b'
[PROOF STATE]
proof (chain)
picking this:
D - c * g b' \<le> c * g x
b' \<le> x
a \<le> b'
b \<le> b'
[PROOF STEP]
have integrable: "(\<lambda>x. \<bar>g' x\<bar>) integrable_on {b'..x}"
[PROOF STATE]
proof (prove)
using this:
D - c * g b' \<le> c * g x
b' \<le> x
a \<le> b'
b \<le> b'
goal (1 subgoal):
1. (\<lambda>x. \<bar>g' x\<bar>) integrable_on {b'..x}
[PROOF STEP]
by (intro integrable_continuous_real continuous_intros) auto
[PROOF STATE]
proof (state)
this:
(\<lambda>x. \<bar>g' x\<bar>) integrable_on {b'..x}
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
have "integral {a..x} f = integral {a..b'} f + integral {b'..x} f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. integral {a..x} f = integral {a..b'} f + integral {b'..x} f
[PROOF STEP]
using elim b'
[PROOF STATE]
proof (prove)
using this:
D - c * g b' \<le> c * g x
b' \<le> x
a \<le> b'
b \<le> b'
goal (1 subgoal):
1. integral {a..x} f = integral {a..b'} f + integral {b'..x} f
[PROOF STEP]
by (intro Henstock_Kurzweil_Integration.integral_combine [symmetric] assms) auto
[PROOF STATE]
proof (state)
this:
integral {a..x} f = integral {a..b'} f + integral {b'..x} f
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
integral {a..x} f = integral {a..b'} f + integral {b'..x} f
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
have "norm \<dots> \<le> D + norm (integral {b'..x} f)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. norm (integral {a..b'} f + integral {b'..x} f) \<le> D + norm (integral {b'..x} f)
[PROOF STEP]
unfolding D_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. norm (integral {a..b'} f + integral {b'..x} f) \<le> norm (integral {a..b'} f) + norm (integral {b'..x} f)
[PROOF STEP]
by (rule norm_triangle_ineq)
[PROOF STATE]
proof (state)
this:
norm (integral {a..b'} f + integral {b'..x} f) \<le> D + norm (integral {b'..x} f)
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
norm (integral {a..b'} f + integral {b'..x} f) \<le> D + norm (integral {b'..x} f)
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
have "norm (integral {b'..x} f) \<le> integral {b'..x} (\<lambda>x. c * norm (g' x))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. norm (integral {b'..x} f) \<le> integral {b'..x} (\<lambda>x. c * norm (g' x))
[PROOF STEP]
using b' elim assms c integrable
[PROOF STATE]
proof (prove)
using this:
a \<le> b'
b \<le> b'
D - c * g b' \<le> c * g x
b' \<le> x
f \<in> O(g')
filterlim g at_top at_top
\<lbrakk>a \<le> ?a'; ?a' \<le> ?x\<rbrakk> \<Longrightarrow> f integrable_on {?a'..?x}
a \<le> ?x \<Longrightarrow> (g has_real_derivative g' ?x) (at ?x within {a..})
continuous_on {a..} g'
a \<le> ?x \<Longrightarrow> 0 \<le> g' ?x
0 < c
(\<lambda>x. \<bar>g' x\<bar>) integrable_on {b'..x}
goal (1 subgoal):
1. norm (integral {b'..x} f) \<le> integral {b'..x} (\<lambda>x. c * norm (g' x))
[PROOF STEP]
by (intro integral_norm_bound_integral b assms) auto
[PROOF STATE]
proof (state)
this:
norm (integral {b'..x} f) \<le> integral {b'..x} (\<lambda>x. c * norm (g' x))
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
norm (integral {b'..x} f) \<le> integral {b'..x} (\<lambda>x. c * norm (g' x))
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
have "\<dots> = c * integral {b'..x} (\<lambda>x. \<bar>g' x\<bar>)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. integral {b'..x} (\<lambda>x. c * norm (g' x)) = c * integral {b'..x} (\<lambda>x. \<bar>g' x\<bar>)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
integral {b'..x} (\<lambda>x. c * norm (g' x)) = c * integral {b'..x} (\<lambda>x. \<bar>g' x\<bar>)
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
integral {b'..x} (\<lambda>x. c * norm (g' x)) = c * integral {b'..x} (\<lambda>x. \<bar>g' x\<bar>)
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
have "integral {b'..x} (\<lambda>x. \<bar>g' x\<bar>) = integral {b'..x} g'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. integral {b'..x} (\<lambda>x. \<bar>g' x\<bar>) = integral {b'..x} g'
[PROOF STEP]
using assms b'
[PROOF STATE]
proof (prove)
using this:
f \<in> O(g')
filterlim g at_top at_top
\<lbrakk>a \<le> ?a'; ?a' \<le> ?x\<rbrakk> \<Longrightarrow> f integrable_on {?a'..?x}
a \<le> ?x \<Longrightarrow> (g has_real_derivative g' ?x) (at ?x within {a..})
continuous_on {a..} g'
a \<le> ?x \<Longrightarrow> 0 \<le> g' ?x
a \<le> b'
b \<le> b'
goal (1 subgoal):
1. integral {b'..x} (\<lambda>x. \<bar>g' x\<bar>) = integral {b'..x} g'
[PROOF STEP]
by (intro integral_cong) auto
[PROOF STATE]
proof (state)
this:
integral {b'..x} (\<lambda>x. \<bar>g' x\<bar>) = integral {b'..x} g'
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
integral {b'..x} (\<lambda>x. \<bar>g' x\<bar>) = integral {b'..x} g'
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
have "(g' has_integral (g x - g b')) {b'..x}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (g' has_integral g x - g b') {b'..x}
[PROOF STEP]
using b' elim
[PROOF STATE]
proof (prove)
using this:
a \<le> b'
b \<le> b'
D - c * g b' \<le> c * g x
b' \<le> x
goal (1 subgoal):
1. (g' has_integral g x - g b') {b'..x}
[PROOF STEP]
by (intro fundamental_theorem_of_calculus)
(auto simp flip: has_real_derivative_iff_has_vector_derivative
intro!: DERIV_subset[OF deriv])
[PROOF STATE]
proof (state)
this:
(g' has_integral g x - g b') {b'..x}
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
hence "integral {b'..x} g' = g x - g b'"
[PROOF STATE]
proof (prove)
using this:
(g' has_integral g x - g b') {b'..x}
goal (1 subgoal):
1. integral {b'..x} g' = g x - g b'
[PROOF STEP]
by (simp add: has_integral_iff)
[PROOF STATE]
proof (state)
this:
integral {b'..x} g' = g x - g b'
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
integral {b'..x} g' = g x - g b'
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
have "D + c * (g x - g b') \<le> 2 * c * g x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. D + c * (g x - g b') \<le> 2 * c * g x
[PROOF STEP]
using elim
[PROOF STATE]
proof (prove)
using this:
D - c * g b' \<le> c * g x
b' \<le> x
goal (1 subgoal):
1. D + c * (g x - g b') \<le> 2 * c * g x
[PROOF STEP]
by (simp add: field_simps c'_def)
[PROOF STATE]
proof (state)
this:
D + c * (g x - g b') \<le> 2 * c * g x
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
D + c * (g x - g b') \<le> 2 * c * g x
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
have "\<dots> \<le> 2 * c * norm (g x)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 2 * c * g x \<le> 2 * c * norm (g x)
[PROOF STEP]
using c
[PROOF STATE]
proof (prove)
using this:
0 < c
goal (1 subgoal):
1. 2 * c * g x \<le> 2 * c * norm (g x)
[PROOF STEP]
by (intro mult_left_mono) auto
[PROOF STATE]
proof (state)
this:
2 * c * g x \<le> 2 * c * norm (g x)
goal (1 subgoal):
1. \<And>x. \<lbrakk>D - c * g b' \<le> c * g x; b' \<le> x\<rbrakk> \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
(\<And>x y. x \<le> y \<Longrightarrow> D + x \<le> D + y) \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
(\<And>x y. x \<le> y \<Longrightarrow> D + x \<le> D + y) \<Longrightarrow> norm (integral {a..x} f) \<le> 2 * c * norm (g x)
goal (1 subgoal):
1. norm (integral {a..x} f) \<le> 2 * c * norm (g x)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
norm (integral {a..x} f) \<le> 2 * c * norm (g x)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<forall>\<^sub>F x in at_top. norm (integral {a..x} f) \<le> 2 * c * norm (g x)
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
\<forall>\<^sub>F x in at_top. norm (integral {a..x} f) \<le> 2 * c * norm (g x)
goal (1 subgoal):
1. (\<lambda>x. integral {a..x} f) \<in> O(g)
[PROOF STEP]
by (rule bigoI)
[PROOF STATE]
proof (state)
this:
(\<lambda>x. integral {a..x} f) \<in> O(g)
goal:
No subgoals!
[PROOF STEP]
qed
|
{
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": "Prime_Number_Theorem_Prime_Number_Theorem_Library",
"hexsha": null,
"include": null,
"lang": null,
"length": 62,
"llama_tokens": 7108,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": null
}
|
#
# Author: Yijun Zhang
#
import cv2
import math
import numpy as np
import skvideo.io as sv
cap = sv.VideoCapture('czy1.mp4')
out = sv.VideoWriter('czy_other.mp4', 'H264', 30.0, (640, 480), True)
print out.open()
ret, frame2 = cap.read()
current_frame = frame2
## extract background
fgbg = cv2.createBackgroundSubtractorKNN()
while True:
ret, frame = cap.read()
# The rgb structure is different in cv and scikit-video, thus reconstructing
b, g, r = cv2.split(frame)
ori_frame = frame
ori_frame = cv2.merge([r, g, b])
cv2.imshow('frame', ori_frame) ## the frame we get from the camera
# Edge Enhancement
b, g, r = cv2.split(frame)
b_gray = cv2.GaussianBlur(b, (5, 5), 0)
b_edged = cv2.Canny(b_gray, 35, 125)
g_gray = cv2.GaussianBlur(g, (5, 5), 0)
g_edged = cv2.Canny(g_gray, 35, 125)
r_gray = cv2.GaussianBlur(r, (5, 5), 0)
r_edged = cv2.Canny(r_gray, 35, 125)
edge_frame = cv2.merge([b + 0.1*b_edged, g + 0.1*g_edged, r + 0.1*r_edged])
b, g, r = cv2.split(frame)
## using equalizehist to adjust the constrast of the image
b = cv2.equalizeHist(b)
g = cv2.equalizeHist(g)
r = cv2.equalizeHist(r)
frame = cv2.merge([b, g, r])
fmask = fgbg.apply(frame)
# denosing the area of motion
th = cv2.threshold(fmask.copy(), 244, 255, cv2.THRESH_BINARY)[1]
th = cv2.erode(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2)
dilated = cv2.dilate(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (8, 3)), iterations=2)
# if it is a stationary video, define the number
nonzeroNum = np.count_nonzero(dilated)
if nonzeroNum == 0:
min_x1 = 1
max_x1 = 1
min_y1 = 2
max_y1 = 2
else:
x1, y1 = np.nonzero(dilated)
min_x1 = x1.min()+1
max_x1 = x1.max()+1
min_y1 = y1.min()+2
max_y1 = y1.max()+2
# compute the minimal rect of motion area
c = np.array([[max_y1,min_x1],[max_y1,max_x1],[min_y1,min_x1],[min_y1,max_x1]])
rect = cv2.minAreaRect(c)
box = np.int0(cv2.boxPoints(rect))
## fill the motion area
cv2.drawContours(dilated, [box], -1, (0, 255, 0), 3)
image1 = cv2.fillPoly(dilated, [box], (255, 255, 255));
## extract the motion area
b, g, r = cv2.split(frame)
res_b = b*(image1/255)
res_g = g*(image1/255)
res_r = r*(image1/255)
## merge the image
result = cv2.merge([res_r, res_g, res_b])
realresult = cv2.merge([res_b, res_g, res_r])
frame = cv2.merge([r, g, b])
cv2.imshow('result', result)
out.write(realresult)
k = cv2.waitKey(30) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
cap.release()
|
{
"alphanum_fraction": 0.6122672508,
"author": null,
"avg_line_length": 26.8529411765,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "165af07aded3a5cac04f7161a25d64acbeb15beb",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2022-01-11T05:54:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-31T08:03:21.000Z",
"max_forks_repo_head_hexsha": "c3010369e26c254d49742c58c6e5766f5713a12f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dendisuhubdy/Fall-Detection",
"max_forks_repo_path": "Preprocessing/preproc.py",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "c3010369e26c254d49742c58c6e5766f5713a12f",
"max_issues_repo_issues_event_max_datetime": "2020-09-21T07:01:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-13T01:36:23.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dendisuhubdy/Fall-Detection",
"max_issues_repo_path": "Preprocessing/preproc.py",
"max_line_length": 96,
"max_stars_count": 57,
"max_stars_repo_head_hexsha": "c3010369e26c254d49742c58c6e5766f5713a12f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dendisuhubdy/Fall-Detection",
"max_stars_repo_path": "Preprocessing/preproc.py",
"max_stars_repo_stars_event_max_datetime": "2021-11-24T09:52:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-11T15:03:18.000Z",
"num_tokens": 942,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2739
}
|
(*
#####################################################
### PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY ###
#####################################################
*)
Require Import Coq.Strings.Ascii.
Require Import Coq.Lists.List.
Import ListNotations.
Open Scope char_scope.
Definition rule := (ascii * list ascii) % type.
Structure grammar := {
grammar_vars : list ascii;
grammar_terminals : list ascii;
grammar_rules : list rule;
grammar_start : ascii;
}.
Definition g1 := {|
grammar_vars := ["C"];
grammar_terminals := ["{"; "}"];
grammar_start := "C";
grammar_rules := [
("C", ["{"; "C"; "}"]);
("C", ["C"; "C"]);
("C", [])
];
|}.
Inductive Yield (G:grammar) : list ascii -> list ascii -> Prop :=
| yield_def:
forall u v w A w1 w2,
In (A, w) (grammar_rules G) ->
w1 = u ++ [A] ++ v ->
w2 = u ++ w ++ v ->
Yield G w1 w2.
Inductive Derivation (G:grammar): list (list ascii) -> Prop :=
| derivation_nil:
Derivation G [[grammar_start G]]
| derivation_cons:
forall u v ws,
Derivation G (u :: ws) ->
Yield G u v ->
Derivation G (v :: u :: ws).
Inductive Accept (G:grammar) : list ascii -> Prop :=
| accept_def:
forall w ws,
Derivation G (w::ws) ->
Forall (fun c => List.In c (grammar_terminals G)) w ->
Accept G w.
|
{
"alphanum_fraction": null,
"author": "mansi0312",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/coq/mansi0312-CS420/CS420-d949dc7ba204b990a4bfe3b616916437f50b0230/Hw5Util.v",
"reason": null,
"repo": "CS420",
"save_path": "github-repos/coq/mansi0312-CS420",
"sha": "d949dc7ba204b990a4bfe3b616916437f50b0230",
"size": null
}
|
import datetime
#import dill
import numpy as np
import pandas as pd
import time
from imblearn.over_sampling import SMOTE
from sklearn.decomposition import PCA
from sklearn.feature_selection import RFE
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import plotly.graph_objects as go
from src.models.performance_metrics import show_results
from src.utils import pca
class ModelLogisticRegression:
# Hyperparameters with GridSearchCV
# https://www.dezyre.com/recipes/optimize-hyper-parameters-of-logistic-regression-model-using-grid-search-in-python
# https://towardsdatascience.com/logistic-regression-model-tuning-with-scikit-learn-part-1-425142e01af5
def __init__(self):
self.version = 'logistic_regression__' + datetime.datetime.today().strftime("%Y%m%d")
self.global_config = {
'show_plot': True,
'save_plot': True
}
self.vardict = self.get_model_vardict()
self.scaler = StandardScaler()
self.impute_missing_variables = dict()
self.sampling = None # 'SMOTE'
self.dimension_reduction = None # PCA(n_components=4)
self.feature_selection = 'Recursive Feature Elimination'
self.feature_selection_n = 11
# https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html
# ?highlight=logistic#sklearn.linear_model.LogisticRegression.decision_function
self.model_config = {
'penalty': 'l2',
'solver': 'liblinear',
'C': 10,
'max_iter': 10000,
'random_state': 0,
'verbose': 1
}
self.model = LogisticRegression(**self.model_config)
self.time_for_training = 0
def get_model_vardict(self):
vardict = dict()
# Target
vardict["target"] = "result"
# Numerical
vardict["numerical"] = [
"nb_characters_german",
"nb_characters_english",
"nb_words_german",
"nb_words_english",
"levenshtein_distance_german_english",
"previous_score",
"previous_score_other_language",
"previous_levenshtein_distance_guess_answer",
"previous_question_time",
"previous_write_it_again_german",
"previous_write_it_again_english",
"past_occurrences_same_language",
"past_successes_same_language",
"past_fails_same_language",
"past_occurrences_any_language",
"past_successes_any_language",
"past_fails_any_language",
"week_number",
"day_week",
"hour",
"nb_words_session",
"difficulty_category",
]
# Difference in time
vardict["diff_time"] = [
"days_since_last_occurrence_same_language",
"days_since_last_occurrence_any_language",
"days_since_last_success_same_language",
"days_since_last_success_any_language",
"days_since_first_occur_same_language",
"days_since_first_occur_any_language",
]
# Boolean
vardict["boolean"] = [
"previous_result",
"previous_correct_article",
"previous_only_missed_uppercase",
"previous_write_it_again_not_null",
"is_noun",
"is_verb",
"previous_confused_with_another_word",
"previous_confused_with_an_unknown_word",
]
# Categorical
vardict["categorical"] = [
"language_asked",
"previous_language_asked",
]
# vardict['all'] = vardict['numerical'] + vardict['diff_time'] + vardict['boolean'] + vardict['categorical']
return vardict
def preprocessing_training(self, dataset):
dataset = self.preprocessing_training_numerical(dataset)
dataset = self.preprocessing_training_diff_time(dataset)
dataset = self.preprocessing_training_boolean(dataset)
dataset = self.preprocessing_training_categorical(dataset)
self.vardict["preprocessed"] = (
self.vardict["numerical"]
+ self.vardict["diff_time"]
+ self.vardict["dummy_boolean"]
+ self.vardict["dummy_categorical"]
)
if self.sampling in ['SMOTE']:
dataset = self.apply_sampling(dataset)
if self.scaler:
dataset[self.vardict["preprocessed"]] = self.scaler.fit_transform(dataset[self.vardict["preprocessed"]])
if self.dimension_reduction:
dataset = self.apply_dimension_reduction_training(dataset)
else:
self.vardict['transformed'] = self.vardict['preprocessed']
if self.feature_selection in ['Recursive Feature Elimination']:
self.vardict["into_model"] = self.apply_feature_selection(dataset)
else:
self.vardict["into_model"] = self.vardict["transformed"]
return dataset
def apply_dimension_reduction_training(self, dataset):
if not self.scaler:
raise ValueError("Scaling must be applied before PCA")
X_train = dataset[self.vardict["preprocessed"]]
y_train = dataset[self.vardict["target"]]
X_embedded_pca = self.dimension_reduction.fit_transform(X_train)
X_train_pca = pd.DataFrame(
data=X_embedded_pca,
columns=["component_{:02d}".format(x + 1) for x in range(X_embedded_pca.shape[1])],
)
self.vardict['transformed'] = X_train_pca.columns.tolist()
dataset = pd.concat([X_train_pca, y_train], axis=1)
if self.global_config['show_plot']:
pca.show_components(
dataset, component_a=1, component_b=2,
model_name=self.version,
show_plot=self.global_config['show_plot'],
save_plot=self.global_config['save_plot'],
)
pca.plot_explained_variance(pca.explained_variance(X_train_pca), model_name=self.version)
pca.plot_feature_components(
feature_components=self.dimension_reduction.components_,
feature_names=self.vardict["preprocessed"],
n_components=X_train_pca.shape[1],
model_name=self.version
)
return dataset
def apply_feature_selection(self, dataset):
X_train = dataset[self.vardict["transformed"]]
y_train = dataset[self.vardict["target"]]
if self.feature_selection == 'Recursive Feature Elimination':
logreg = LogisticRegression(**self.model_config)
rfe = RFE(estimator=logreg, n_features_to_select=self.feature_selection_n, verbose=0)
rfe = rfe.fit(X_train, y_train)
if self.global_config['show_plot']:
print("\n ----------")
print(" Recursive Feature Elimination")
print(" ----------")
for i_ranking in range(max(rfe.ranking_)):
for feature in [
var
for var, ranking in zip(self.vardict["preprocessed"], rfe.ranking_)
if ranking == i_ranking
]:
print("{:2d}. {}".format(i_ranking, feature))
if i_ranking == 1:
print("\n ---------- \n")
return [
var for var, support in zip(self.vardict["preprocessed"], rfe.support_) if support
]
def apply_sampling(self, dataset):
if self.sampling == 'SMOTE':
os = SMOTE(
random_state=0
)
n_dataset = len(dataset)
prop_dataset = np.mean(dataset[self.vardict["target"]])
X_train = dataset[self.vardict["preprocessed"]]
y_train = dataset[[self.vardict["target"]]]
X_train_os, y_train_os = os.fit_sample(X_train, y_train)
dataset = pd.concat([X_train_os, y_train_os], axis=1)
# we can Check the numbers of our data
print("SMOTE - datapoints - {:5d} -> {:5d}".format(
n_dataset, len(dataset)
))
print("SMOTE - proportion - {:0.3f} -> {:0.3f}".format(
prop_dataset, np.mean(dataset[self.vardict["target"]])
))
return dataset
def preprocessing_training_numerical(self, dataset):
dataset["previous_levenshtein_distance_guess_answer"].fillna(-1, inplace=True)
self.impute_missing_variables["previous_levenshtein_distance_guess_answer"] = -1
dataset["previous_question_time"].fillna(-1, inplace=True)
self.impute_missing_variables["previous_question_time"] = -1
dataset["previous_write_it_again_german"].fillna(-1, inplace=True)
self.impute_missing_variables["previous_write_it_again_german"] = -1
dataset["previous_write_it_again_english"].fillna(-1, inplace=True)
self.impute_missing_variables["previous_write_it_again_english"] = -1
return dataset
def preprocessing_training_diff_time(self, dataset):
dataset["days_since_last_occurrence_same_language"].fillna(-1, inplace=True)
self.impute_missing_variables["days_since_last_occurrence_same_language"] = -1
dataset["days_since_last_occurrence_any_language"].fillna(-1, inplace=True)
self.impute_missing_variables["days_since_last_occurrence_any_language"] = -1
dataset["days_since_last_success_same_language"].fillna(-1, inplace=True)
self.impute_missing_variables["days_since_last_success_same_language"] = -1
dataset["days_since_last_success_any_language"].fillna(-1, inplace=True)
self.impute_missing_variables["days_since_last_success_any_language"] = -1
dataset["days_since_first_occur_same_language"].fillna(-1, inplace=True)
self.impute_missing_variables["days_since_first_occur_same_language"] = -1
dataset["days_since_first_occur_any_language"].fillna(-1, inplace=True)
self.impute_missing_variables["days_since_first_occur_any_language"] = -1
return dataset
def preprocessing_training_boolean(self, dataset):
# Possibility: label encoding. But IMO does not make sense for LogReg
# Possibility: have an ordered label encoding
# https://towardsdatascience.com/logistic-regression-model-tuning-with-scikit-learn-part-1-425142e01af5
# Transform to dummies
self.vardict["dummy_boolean"] = []
for i_var_boolean in self.vardict["boolean"]:
# possible improvement: pandas.get_dummies(drop_first=False)
i_dummy_boolean = pd.get_dummies(
dataset[i_var_boolean],
prefix=i_var_boolean,
prefix_sep="__",
dummy_na=True,
)
del dataset[i_var_boolean]
self.vardict["dummy_boolean"] = (
self.vardict["dummy_boolean"] + i_dummy_boolean.columns.tolist()
)
dataset = pd.concat([dataset, i_dummy_boolean], axis=1)
return dataset
def preprocessing_training_categorical(self, dataset):
# Transform to dummies
self.vardict["dummy_categorical"] = []
for i_var_categorical in self.vardict["categorical"]:
# possible improvement: pandas.get_dummies(drop_first=False)
i_dummy_categorical = pd.get_dummies(
dataset[i_var_categorical],
prefix=i_var_categorical,
prefix_sep="__",
dummy_na=True,
)
del dataset[i_var_categorical]
self.vardict["dummy_categorical"] = (
self.vardict["dummy_categorical"] + i_dummy_categorical.columns.tolist()
)
dataset = pd.concat([dataset, i_dummy_categorical], axis=1)
return dataset
# def hyperparameter_search(self):
def train(self, dataset):
X_train = dataset[self.vardict["into_model"]]
y_train = dataset[self.vardict["target"]]
start = time.time()
self.model.fit(X_train, y_train)
end = time.time()
self.time_for_training = end - start
def preprocessing_inference(self, dataset):
dataset = self.preprocessing_inference_numerical(dataset)
dataset = self.preprocessing_inference_diff_time(dataset)
dataset = self.preprocessing_inference_boolean(dataset)
dataset = self.preprocessing_inference_categorical(dataset)
if self.scaler:
dataset[self.vardict["preprocessed"]] = self.scaler.transform(dataset[self.vardict["preprocessed"]])
#with open(f"data/{self.version}__data_test.pkl", "wb") as file:
# dill.dump(dataset, file)
if self.dimension_reduction:
dataset = self.apply_dimension_reduction_inference(dataset)
return dataset
def apply_dimension_reduction_inference(self, dataset):
X_inference = dataset[self.vardict["preprocessed"]]
X_embedded_pca = self.dimension_reduction.transform(X_inference)
X_inference_pca = pd.DataFrame(
data=X_embedded_pca,
columns=self.vardict["transformed"],
)
return X_inference_pca
def preprocessing_inference_numerical(self, dataset):
list_var_numerical = set(self.impute_missing_variables.keys()).intersection(self.vardict["numerical"])
for i_var_numerical in list_var_numerical:
dataset[i_var_numerical].fillna(self.impute_missing_variables[i_var_numerical], inplace=True)
return dataset
def preprocessing_inference_diff_time(self, dataset):
list_var_diff_time = set(self.impute_missing_variables.keys()).intersection(self.vardict["diff_time"])
for i_var_diff_time in list_var_diff_time:
dataset[i_var_diff_time].fillna(self.impute_missing_variables[i_var_diff_time], inplace=True)
return dataset
def preprocessing_inference_boolean(self, dataset):
for i_var_boolean in self.vardict["boolean"]:
# possible improvement: pandas.get_dummies(drop_first=False)
i_dummy_boolean = pd.get_dummies(
dataset[i_var_boolean],
prefix=i_var_boolean,
prefix_sep="__",
dummy_na=True,
)
del dataset[i_var_boolean]
i_dummy_boolean_inference = i_dummy_boolean.columns.tolist()
i_dummy_boolean_training = [x for x in self.vardict["dummy_boolean"] if x.split("__")[0] == i_var_boolean]
i_common_dummy_boolean = list(set(i_dummy_boolean_training).intersection(i_dummy_boolean_inference))
i_missing_dummy_boolean = list(set(i_dummy_boolean_training) - set(i_dummy_boolean_inference))
i_extra_dummy_boolean = list(set(i_dummy_boolean_inference) - set(i_dummy_boolean_training))
print(
"Preprocessing inference - {:40} - {:2d} missing categories".format(
i_var_boolean, len(i_extra_dummy_boolean)
)
)
i_dummy_boolean = i_dummy_boolean[i_common_dummy_boolean]
for i_var_missing_dummy_boolean in i_missing_dummy_boolean:
i_dummy_boolean[i_var_missing_dummy_boolean] = 0
dataset = pd.concat([dataset, i_dummy_boolean], axis=1)
return dataset
def preprocessing_inference_categorical(self, dataset):
for i_var_categorical in self.vardict["categorical"]:
# possible improvement: pandas.get_dummies(drop_first=False)
i_dummy_categorical = pd.get_dummies(
dataset[i_var_categorical],
prefix=i_var_categorical,
prefix_sep="__",
dummy_na=True,
)
del dataset[i_var_categorical]
i_dummy_categorical_inference = i_dummy_categorical.columns.tolist()
i_dummy_categorical_training = [x for x in self.vardict["dummy_categorical"] if x.split("__")[0] == i_var_categorical]
i_common_dummy_categorical = list(set(i_dummy_categorical_training).intersection(i_dummy_categorical_inference))
i_missing_dummy_categorical = list(set(i_dummy_categorical_training) - set(i_dummy_categorical_inference))
i_extra_dummy_categorical = list(set(i_dummy_categorical_inference) - set(i_dummy_categorical_training))
print(
"Preprocessing inference - {:40} - {:2d} missing categories".format(
i_var_categorical, len(i_extra_dummy_categorical)
)
)
i_dummy_categorical = i_dummy_categorical[i_common_dummy_categorical]
for i_var_missing_dummy_categorical in i_missing_dummy_categorical:
i_dummy_categorical[i_var_missing_dummy_categorical] = 0
dataset = pd.concat([dataset, i_dummy_categorical], axis=1)
return dataset
def predict(self, dataset, target_present=False):
X_valid = dataset[self.vardict["into_model"]].copy()
predictions = X_valid.copy()
predictions["y_pred"] = self.model.predict(X_valid)
predictions["y_proba"] = [x[1] for x in self.model.predict_proba(X_valid)]
if target_present:
predictions["y_true"] = dataset[self.vardict["target"]].copy()
return predictions
def plot_coefficients(self):
model_coef = pd.DataFrame()
model_coef["var"] = self.vardict["into_model"]
model_coef["coef"] = self.model.coef_.tolist()[0]
model_coef.sort_values("coef", ascending=True, inplace=True)
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=model_coef["coef"].values.tolist(),
y=model_coef["var"].values.tolist(),
marker=dict(color="crimson", size=12),
mode="markers",
name="Coefficients",
)
)
fig.add_trace(
go.Scatter(
x=[0] * len(model_coef),
y=model_coef["var"].values.tolist(),
mode="lines",
line=dict(color="black", dash="dash"),
showlegend=False,
)
)
fig.update_layout(
title="Coefficients of {}".format(self.version),
xaxis_title="Coefficients",
yaxis_title="Variables",
)
if self.global_config['show_plot']:
fig.show()
if self.global_config['save_plot']:
fig.write_html(f"data/figures/{self.version}_coefficients.html")
def predict_and_show_results(self, dataset_valid, save_folder="data/processed"):
y_valid = dataset_valid[self.vardict["target"]].copy()
dataset_valid = self.preprocessing_inference(dataset_valid)
predictions = self.predict(dataset=dataset_valid, target_present=False)
predictions["y_true"] = y_valid.values.tolist()
show_results(
predictions,
model_name=self.version,
show_plot=self.global_config['show_plot'],
save_plot=self.global_config['save_plot'],
save_folder=save_folder,
)
|
{
"alphanum_fraction": 0.6307716065,
"author": null,
"avg_line_length": 35.8431734317,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "dd6e53d31a44424db536be49bc55f2bd3e3bd92f",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c287a65d6e0d5e75732f0481aa50a6fd1c713d45",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Blitzy29/vocabulary_learning",
"max_forks_repo_path": "src/models/logistic_regression.py",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "c287a65d6e0d5e75732f0481aa50a6fd1c713d45",
"max_issues_repo_issues_event_max_datetime": "2022-01-13T03:39:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-09-08T03:03:08.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Blitzy29/vocabulary_learning",
"max_issues_repo_path": "src/models/logistic_regression.py",
"max_line_length": 130,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c287a65d6e0d5e75732f0481aa50a6fd1c713d45",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Blitzy29/vocabulary_learning",
"max_stars_repo_path": "src/models/logistic_regression.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3986,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 19427
}
|
import numpy as np
import cv2
import Tkinter as Tk
from tkFileDialog import askopenfilename
root = Tk.Tk()
root.withdraw()
filepath = askopenfilename(initialdir = r'D:\02TestData\ImgData')
path = r'D:\1612vision\Lg\LGSample_blue\Mapping_Image\testImage\310x310_F7_center_13000x15800y_min2000max30000.bmp'
img = cv2.imread(filepath,0)
print np.shape(img)
#Z = img.reshape((-1,1)) #
Z = img.ravel() # Flatten Array with sam n-dim
print np.shape(img)
Z2 = img.ravel() # Convert to Flatten Array
# convert to np.float32
Z = np.float32(Z)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 3
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()] # center position of each chips
res2 = res.reshape((img.shape))
outputpath = r'D:\02TestData\ImgData\output_kMean.png'
cv2.imwrite(outputpath,res2)
cv2.imshow('res2',res2)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
{
"alphanum_fraction": 0.7552897884,
"author": null,
"avg_line_length": 26.512195122,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "9ec5ed05aeba9c74604adf492278d12816f5d7e9",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e5f21197b5d91c15af40dd4c8d6aaa229e60cb4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "pimier15/Cs_Util_Tool",
"max_forks_repo_path": "Py/Util_Tool/Statistic_Tool/Statistic_Tool/KMean.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e5f21197b5d91c15af40dd4c8d6aaa229e60cb4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "pimier15/Cs_Util_Tool",
"max_issues_repo_path": "Py/Util_Tool/Statistic_Tool/Statistic_Tool/KMean.py",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e5f21197b5d91c15af40dd4c8d6aaa229e60cb4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "pimier15/Cs_Util_Tool",
"max_stars_repo_path": "Py/Util_Tool/Statistic_Tool/Statistic_Tool/KMean.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 325,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1087
}
|
import glob
import io
import os
import sys
from statsmodels.compat.testing import SkipTest, example
try:
import pytest
import jupyter_client
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
except ImportError:
raise SkipTest('Required packages not available')
KNOWN_FAILURES = ['distributed_estimation']
if os.name == 'nt':
KNOWN_FAILURES += ['mixed_lm_example']
kernels = jupyter_client.kernelspec.find_kernel_specs()
kernel_name = 'python%s' % sys.version_info.major
head, _ = os.path.split(__file__)
NOTEBOOK_DIR = os.path.abspath(os.path.join(head, '..', '..', '..', 'examples', 'notebooks'))
nbs = sorted(glob.glob(os.path.join(NOTEBOOK_DIR, '*.ipynb')))
ids = list(map(lambda p: os.path.split(p)[-1], nbs))
@pytest.fixture(params=nbs, ids=ids)
def notebook(request):
return request.param
if not nbs:
raise SkipTest('No notebooks found so not tests run')
@example
def test_notebook(notebook):
fullfile = os.path.abspath(notebook)
_, filename = os.path.split(fullfile)
filename, _ = os.path.splitext(notebook)
for known_fail in KNOWN_FAILURES:
if filename == known_fail:
raise SkipTest('{0} is known to fail'.format(filename))
with io.open(fullfile, encoding='utf-8') as f:
nb = nbformat.read(fullfile, as_version=4)
ep = ExecutePreprocessor(allow_errors=False,
timeout=20,
kernel_name=kernel_name)
ep.preprocess(nb, {'metadata': {'path': NOTEBOOK_DIR}})
|
{
"alphanum_fraction": 0.6797427653,
"author": null,
"avg_line_length": 27.7678571429,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "58f269bcd8a3e3d8230286f8993da49340b8d51a",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 28,
"max_forks_repo_forks_event_max_datetime": "2021-07-03T00:09:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-01T20:02:25.000Z",
"max_forks_repo_head_hexsha": "c99558b287735eb5f0c1e561866e1501e41fecbe",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "krasnars/statsmodels",
"max_forks_repo_path": "statsmodels/examples/tests/test_notebooks.py",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "c99558b287735eb5f0c1e561866e1501e41fecbe",
"max_issues_repo_issues_event_max_datetime": "2019-04-12T22:29:01.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-08-28T16:59:03.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "krasnars/statsmodels",
"max_issues_repo_path": "statsmodels/examples/tests/test_notebooks.py",
"max_line_length": 93,
"max_stars_count": 20,
"max_stars_repo_head_hexsha": "ec3b6d02c96cd9c8f4b993434f0bbae4b3e91a21",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dieterv77/statsmodels",
"max_stars_repo_path": "statsmodels/examples/tests/test_notebooks.py",
"max_stars_repo_stars_event_max_datetime": "2022-01-24T01:24:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-28T21:52:59.000Z",
"num_tokens": 363,
"path": null,
"reason": "from statsmodels",
"repo": null,
"save_path": null,
"sha": null,
"size": 1555
}
|
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 17 20:04:03 2019
@author: Wenbin Yao
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
#define the global variable
UnitX = 0.5 #every segment's length
UnitTime = 0.00278 #unit time
K = 180 #total round
Vf = 100 #free speed
DensityMax = 160
rk = 800 #for every time, on ramp flow is 800 veh/h
beta = 0.1 #off ramp coefficient
DensityIni = 20 #every segment's initial density
class Segment:
# define a class of segment.
kt = 0 #document the time of round
QoutNext_k2 = 0 #the flow of next segment at the time kt.
Density_k1 = 0 #the density of time kt - 1
Density_k2 = 0 #the density of time kt
Velocity = 0 #the speed of the segment at the time kt
SegOrd = 0 #the order of segment
QoutLast_k1 = 0 # last segment's flow at the time kt - 1
Qout_k1 = 0 # flow of time kt - 1
Qout_k2 = 0 #flow of time kt
def __init__(self , DensityNextSeg_k2 , Density_k1 , kt , SegOrd , QoutLast_k1 , Qout_k1):
self.DensityNextSeg_k2 = DensityNextSeg_k2
self.Density_k1 = Density_k1
self.kt = kt
self.SegOrd = SegOrd
self.QoutLast_k1 = QoutLast_k1
self.Qout_k1 = Qout_k1
def GetParameter(self):
if self.SegOrd == 0 or self.SegOrd == 2 or self.SegOrd == 3 or self.SegOrd == 5:
#get the parameter of the segment that we need, which is the order 1,3,4,6. there is no ramp.
temp = self.Density_k1 + UnitTime / UnitX * (self.QoutLast_k1 - self.Qout_k1) #get next time density
if temp > 160:
self.Density_k2 = 160
elif temp < 0:
self.Density_k2 = 0
else:
self.Density_k2 = temp
# get Qout at time kt
if self.Density_k2 <= 80:
QDemand = self.Density_k2 * Vf * (1 - self.Density_k2 / DensityMax)
elif self.Density_k2 > 80:
QDemand = 4000
if self.DensityNextSeg_k2 <= 80:
QCapNextSeg = 4000
elif self.DensityNextSeg_k2 > 80:
QCapNextSeg = self.DensityNextSeg_k2 * Vf * (1 - self.DensityNextSeg_k2 / DensityMax)
self.Qout_k2 = min(QDemand , QCapNextSeg)
#fet velocity
if self.Density_k2 < 0.0000000001:
self.Velocity = 0
else:
self.Velocity = self.Qout_k2 / self.Density_k2
elif self.SegOrd == 1:
#get the parameter of the segment that we need, which is the order 2. there is off ramp.
temp = self.Density_k1 + UnitTime / UnitX * (self.QoutLast_k1 - self.Qout_k1 - beta * self.QoutLast_k1) #get next time density
if temp > 160:
self.Density_k2 = 160
elif temp < 0:
self.Density_k2 = 0
else:
self.Density_k2 = temp
# get Qout at time kt
if self.Density_k2 <= 80:
QDemand = self.Density_k2 * Vf * (1 - self.Density_k2 / DensityMax)
elif self.Density_k2 > 80:
QDemand = 4000
if self.DensityNextSeg_k2 <= 80:
QCapNextSeg = 4000
elif self.DensityNextSeg_k2 > 80:
QCapNextSeg = self.DensityNextSeg_k2 * Vf * (1 - self.DensityNextSeg_k2 / DensityMax)
self.Qout_k2 = min(QDemand , QCapNextSeg)
#get velocity
if self.Density_k2 < 0.0000000001:
self.Velocity = 0
else:
self.Velocity = self.Qout_k2 / self.Density_k2
elif self.SegOrd == 4:
# get the parameter of the segment that we need, which is the order 4. there is on ramp.
temp = self.Density_k1 + UnitTime / UnitX * (self.QoutLast_k1 - self.Qout_k1 + rk ) #get next time density
if temp > 160:
self.Density_k2 = 160
elif temp < 0:
self.Density_k2 = 0
else:
self.Density_k2 = temp
# get Qout at time kt
if self.Density_k2 <= 80:
QDemand = self.Density_k2 * Vf * (1 - self.Density_k2 / DensityMax)
elif self.Density_k2 > 80:
QDemand = 4000
if self.DensityNextSeg_k2 <= 80:
QCapNextSeg = 4000
elif self.DensityNextSeg_k2 > 80:
QCapNextSeg = self.DensityNextSeg_k2 * Vf * (1 - self.DensityNextSeg_k2 / DensityMax)
self.Qout_k2 = min(QDemand , QCapNextSeg)
#get velocity
if self.Density_k2 < 0.0000000001:
self.Velocity = 0
else:
self.Velocity = self.Qout_k2 / self.Density_k2
else:
print("There is no such segment, please check the order of segment!")
def Time(kt , SegmentListLasttime):
'''
calculate the traffic flow of kt time
input:kt:time ; SegmentListLasttime:a list of cevery segment last time
'''
if kt == 1: # first time of evolution of the link
SegmentList = [0 for j in range(6)] # new a list to store the segment 1-6 of this time
for i in range(6):
j = 5 - i
if j == 5:
SegmentTemp = Segment(0 , 20 , kt , j , 1750 , 1750)
SegmentTemp.GetParameter()
SegmentList[j] = SegmentTemp
elif j == 0:
SegmentTemp = Segment(SegmentList[j + 1].Density_k2 , 20 , kt , j , 4000 , 1750)
SegmentTemp.GetParameter()
SegmentList[j] = SegmentTemp
else:
SegmentTemp = Segment(SegmentList[j + 1].Density_k2 , 20 , kt , j , 1750 , 1750)
SegmentTemp.GetParameter()
SegmentList[j] = SegmentTemp
return SegmentList
elif kt > 1 and kt <= 100:
SegmentList = [0 for j in range(6)] #new a list to store the segment1-6 of this time
for i in range(6):
j = 5 - i
if j == 5:
SegmentTemp = Segment(0 , SegmentListLasttime[j].Density_k2 , kt , j , \
SegmentListLasttime[j - 1].Qout_k2 , SegmentListLasttime[j].Qout_k2)
SegmentTemp.GetParameter()
SegmentList[j] = SegmentTemp
elif j == 0:
SegmentTemp = Segment(SegmentList[j + 1].Density_k2 , SegmentListLasttime[j].Density_k2 , kt , j , \
4000 , SegmentListLasttime[j].Qout_k2)
SegmentTemp.GetParameter()
SegmentList[j] = SegmentTemp
else:
SegmentTemp = Segment(SegmentList[j + 1].Density_k2 , SegmentListLasttime[j].Density_k2 , kt , j , \
SegmentListLasttime[j - 1].Qout_k2 , SegmentListLasttime[j].Qout_k2)
SegmentTemp.GetParameter()
SegmentList[j] = SegmentTemp
return SegmentList
elif kt > 100 and kt <= 180:
SegmentList = [0 for j in range(6)] #new a list to store the segment1-6 of this time
for i in range(6):
j = 5 - i
if j == 5:
SegmentTemp = Segment(0 , SegmentListLasttime[j].Density_k2 , kt , j , \
SegmentListLasttime[j - 1].Qout_k2 , SegmentListLasttime[j].Qout_k2)
SegmentTemp.GetParameter()
SegmentList[j] = SegmentTemp
elif j == 0:
SegmentTemp = Segment(SegmentList[j + 1].Density_k2 , SegmentListLasttime[j].Density_k2 , kt , j , \
2000 , SegmentListLasttime[j].Qout_k2)
SegmentTemp.GetParameter()
SegmentList[j] = SegmentTemp
else:
SegmentTemp = Segment(SegmentList[j + 1].Density_k2 , SegmentListLasttime[j].Density_k2 , kt , j , \
SegmentListLasttime[j - 1].Qout_k2 , SegmentListLasttime[j].Qout_k2)
SegmentTemp.GetParameter()
SegmentList[j] = SegmentTemp
return SegmentList
else:
print("Time restricted to 0-180, other time still not support!")
return None
def TimeSpacePlot(SegmentTimeseries):
# 3-dimensional time-space plots for the speed and density
SpeedList = [] # store every segment's speed over time
DensityList = [] # store every segment's density over time
for i in range(6):
tempspeed = [] #store segment's flow over time
tempdensity = [] #same func with above
for ti in range(1 , K + 1):
tempspeed.append(SegmentTimeseries[ti][i].Velocity)
tempdensity.append(SegmentTimeseries[ti][i].Density_k2)
SpeedList.append(tempspeed)
DensityList.append(tempdensity)
# plot 3-dimensional time-space plots for the speed
TimeList = np.linspace(1, 180 , 180) #X轴数据
SegmentList = [0 for j in range(180)]
SpeedList2 = SpeedList[0]
DensityList2 = DensityList[0]
# new a figure and set it into 3d
plt.rcParams['savefig.dpi'] = 300 #图片像素
fig = plt.figure()
ax = fig.gca(projection='3d')
# set figure information
ax.set_title(" 3-dimensional time-space plots for the speed ")
ax.set_xlabel("Time(Unit)")
ax.set_ylabel("Segment(start from 0)")
ax.set_zlabel("Speed(km/h)")
for i in range(5):
TimeList = np.append(TimeList , np.linspace(1, 180 , 180))
SegmentList = np.append(SegmentList , [(i + 1) for j in range(180)])
SpeedList2 = np.append(SpeedList2 , SpeedList[i + 1])
DensityList2 = np.append(DensityList2 , DensityList[i + 1])
surf = ax.plot_trisurf(TimeList, SegmentList , SpeedList2 , cmap=cm.jet, linewidth=0.2)
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.savefig('速度三维时空图.png')
plt.show()
plt.rcParams['savefig.dpi'] = 300 #图片像素
fig = plt.figure()
ax = fig.gca(projection='3d')
# set figure information
ax.set_title("3-dimensional time-space plots for the density ")
ax.set_xlabel("Time(Unit)")
ax.set_ylabel("Segment(start from 0)")
ax.set_zlabel("Density(veh/km)")
surf = ax.plot_trisurf(TimeList, SegmentList , DensityList2 , cmap=cm.jet, linewidth=0.2)
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.savefig('密度三维时空图.png')
plt.show()
def FlowDensityPlot(SegmentTimeseries):
# plot of Flow and Density diagram over time
FlowList = [] # store every segment's flow over time
DensityList = [] # store every segment's density over time
for i in range(6):
tempflow = [] #store segment's flow over time
tempdensity = [] #same func with above
for ti in range(1 , K + 1):
tempflow.append(SegmentTimeseries[ti][i].Qout_k2)
tempdensity.append(SegmentTimeseries[ti][i].Density_k2)
FlowList.append(tempflow)
DensityList.append(tempdensity)
#plot
plt.rcParams['savefig.dpi'] = 300 #图片像素
plt.figure(figsize=(8,4))
x = np.linspace(1, 180 , 180)#X轴数据
for i in range(6):
plt.plot(x , FlowList[i] , label = "Segment" + str(i) , linewidth=2)#将$包围的内容渲染为数学公式
plt.xlabel("Time(Unit)")
plt.ylabel("Flow(veh/hour)")
plt.title("Line chart of flow changing with time")
# plt.ylim(-1.5,1.5)
plt.legend()#显示左下角的图例
plt.savefig('流量随时间变化折线图.png')
plt.show()
#plot density changing with time
for i in range(6):
plt.plot(x , DensityList[i] , label = "Segment" + str(i) , linewidth=2)#将$包围的内容渲染为数学公式
plt.xlabel("Time(Unit)")
plt.ylabel("Density(veh/km)")
plt.title("Line chart of density changing with time")
# plt.ylim(-1.5,1.5)
plt.legend()#显示左下角的图例
plt.savefig('密度随时间变化折线图.png')
plt.show()
if __name__ == "__main__":
SegmentTimeseries = [] #set a list to store every time's segment list
SegmentTimeseries.append(None)
SegmentListLasttime = None #initialize the SegmentListLasttime
for ti in range(1 , K + 1):
SegmentTimeseries.append( Time(ti , SegmentListLasttime) )
SegmentListLasttime = SegmentTimeseries[ti] #update SegmenntLasttime
# Test blow result is right
print("Time 1 segment 0 : Qout: " , SegmentTimeseries[1][0].Qout_k2 , " veh/hour")
print("Time 2 segment 0 : Density: " , SegmentTimeseries[2][0].Density_k2 , " veh/km")
print("Time 50 segment 5 : Qout: " , SegmentTimeseries[50][5].Qout_k2 , " veh/hour")
print("Time 180 segment 3 : Qout: " , SegmentTimeseries[180][3].Qout_k2 , " veh/hour")
print("Time 180 segment 4 : Qout: " , SegmentTimeseries[180][4].Qout_k2 , " veh/hour")
# plot Flow and Density diagram over time
FlowDensityPlot(SegmentTimeseries)
# 3-dimensional time-space plots for the speed and density
TimeSpacePlot(SegmentTimeseries)
|
{
"alphanum_fraction": 0.5834028673,
"author": null,
"avg_line_length": 43.9433333333,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "0010c33b0b8b1242b7c9930c25b815ca5a7964c5",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 21,
"max_forks_repo_forks_event_max_datetime": "2022-01-30T03:46:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-03-19T00:44:35.000Z",
"max_forks_repo_head_hexsha": "9607219b8d057ab896ecae5326daadd7dcfb6112",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "RobinYaoWenbin/python-",
"max_forks_repo_path": "FreewayTrafficModelingSurveillanceandContral/Homework_LWR.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9607219b8d057ab896ecae5326daadd7dcfb6112",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "RobinYaoWenbin/python-",
"max_issues_repo_path": "FreewayTrafficModelingSurveillanceandContral/Homework_LWR.py",
"max_line_length": 139,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "9607219b8d057ab896ecae5326daadd7dcfb6112",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "RobinYaoWenbin/python-",
"max_stars_repo_path": "FreewayTrafficModelingSurveillanceandContral/Homework_LWR.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-20T07:44:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-28T03:25:03.000Z",
"num_tokens": 3680,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 13183
}
|
from functools import reduce
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import display
from scipy.stats import linregress
class CovidDataViz(object):
"""
A class to make plots from processed COVID-19 and World Bank data.
"""
def __init__(self, path='../data/processed'):
self.path = path
self.data = dict()
self.data['Confirmed'] = pd.read_csv(f'{path}/confirmed_cases.csv')
self.data['Confirmed chg'] = pd.read_csv(f'{path}/confirmed_cases_daily_change.csv')
self.data['Confirmed t0'] = pd.read_csv(f'{path}/confirmed_cases_since_t0.csv')
self.data['Recovered'] = pd.read_csv(f'{path}/recovered_cases.csv')
self.data['Dead'] = pd.read_csv(f'{path}/dead_cases.csv')
self.data['Active'] = pd.read_csv(f'{path}/active_cases.csv')
self.data['Mortality'] = pd.read_csv(f'{path}/mortality_rate.csv')
self.data['Coordinates'] = pd.read_csv(f'{path}/coordinates.csv')
self.data['Continents'] = pd.read_csv(f'{path}/continents.csv')
self.data['Ctry to cont'] = pd.read_csv(f'{path}/country_to_continent.csv')
self.data['Country stats'] = pd.read_csv(f'{path}/country_stats.csv')
self.data['World bank'] = pd.read_csv(f'{path}/world_bank.csv')
for _, df in self.data.items():
if 'Date' in df.columns:
df['Date'] = pd.to_datetime(df['Date'])
self.all_countries = sorted(set(self.data['Coordinates']['Country']))
self.all_continents = sorted(set(self.data['Continents']['Continent']))
def list_highest_mortality(self, n=10):
"""
Generate a list of countries with the highest moratlity rate.
Notes
-----
mortality = dead / confirmed.
"""
df = self._sort_ctry_stats(stat_name='Mortality', n=n)
return df
def get_country_ts(self, country):
"""
Extract country level cases time series.
"""
dfs = [self.data['Confirmed'][['Date', country]],
self.data['Recovered'][['Date', country]],
self.data['Dead'][['Date', country]],
self.data['Active'][['Date', country]]]
df = reduce(lambda x, y: pd.merge(x, y, on='Date', how='outer'), dfs)
df.columns = ['Date', 'Confirmed', 'Recovered', 'Dead', 'Active']
return df
def get_continent_ts(self, continent):
"""
Get continent level cases time series.
"""
cont = self.data['Continents'].copy()
cont = cont[cont['Continent'] == continent]
cont = pd.merge(self.data['Coordinates'], cont, on='Country')
countries = sorted(list(cont['Country']))
cases = ['Confirmed', 'Recovered', 'Dead', 'Active']
dfs = []
for c in cases:
tmp = self.data[c][countries].sum(axis=1)
tmp.name = c
tmp = tmp.to_frame()
tmp['Date'] = self.data[c]['Date']
dfs.append(tmp)
df = reduce(lambda x, y: pd.merge(x, y, on='Date', how='outer'), dfs)
df = df[['Date'] + cases]
return df
def get_world_ts(self):
"""
Get world level cases time series.
"""
cases = ['Confirmed', 'Recovered', 'Dead', 'Active']
dfs = []
for case in cases:
tmp = self.data[case].drop('Date', axis=1).sum(axis=1)
tmp.name = case
tmp = tmp.to_frame()
tmp['Date'] = self.data[case]['Date']
dfs.append(tmp)
df = reduce(lambda x, y: pd.merge(x, y, on='Date', how='outer'), dfs)
return df
def get_highest_mortality(self, n_countries, min_cases=1000):
"""
List countries with highest moratlity rate.
"""
df = self.data['Country stats']
df = df[df['Confirmed'] > min_cases]
df = df.sort_values('Mortality', ascending=False).copy()
df = df.reset_index(drop=True)
df = df.head(n_countries)
df = df[['Country', 'Mortality']]
return df
def get_most_cases(self, case_type, n=10):
"""
Get n countries with most cases.
"""
df = self._sort_ctry_stats(stat_name=case_type, n=n)
return df
def plot_world_cases(self):
"""
Create world cases line plot.
"""
df = self.get_world_ts()
self.plot_ts(df=df, title='World')
def plot_country_cases(self, country):
"""
Create individual country cases line plot.
"""
df = self.get_country_ts(country=country)
self.plot_ts(df, country)
def plot_continent_cases(self, continent):
"""
Create continent cases line plot.
"""
df = self.get_continent_ts(continent=continent)
self.plot_ts(df, continent)
def plot_ts(self, df, title):
"""
Draw individuall time series as a line plot.
Inputs
------
df : pd.DataFrame
A dataframe with a `Date` column and cases data.
"""
cols = sorted(df.drop('Date', axis=1).columns)
plt.figure()
for col in cols:
plt.plot(df['Date'], df[col], label=col)
plt.xlim(df['Date'].min(), df['Date'].max())
plt.ylim(0)
plt.title(f'{title}')
plt.ylabel('Cases')
plt.legend(loc='best')
plt.savefig(f'../img/{title.lower()}_cases.png')
plt.tight_layout()
def plot_highest_country_stats(self, statistic, n=10):
"""
Bar plot of countries with the most cases of a certain type.
"""
df = self.get_most_cases(case_type=statistic)
plt.figure()
plt.bar(df['Country'], df[statistic])
plt.xticks(rotation=90)
plt.title(f'{statistic}')
if statistic == 'Mortality':
plt.ylabel('Moratlity Rate (%)')
else:
plt.ylabel('Cases')
plt.tight_layout()
plt.savefig(f'../img/{statistic.lower()}_cases_most.png')
plt.show()
def plot_growth(self, countries, periods, steps=50, save=False):
"""
Plot growth curves, log scale.
Inputs
------
countries : list
List of countries
periods : list of ints
Doubling periods for growth curves.
steps : int
Number of data points to use.
"""
countries = sorted(countries)
# Extract mean and use as starting point for
# exponential growth curves.
a = self.data['Confirmed t0'].mean(axis=1)[0]
b = 2
# List of growth curves
growth = list()
for period in periods:
g = exp_growth(a=a,
b=b,
t=np.arange(steps),
tau=period)
g = np.log(g)
growth.append(list(g))
for g,p in zip(growth, periods):
# Draw growth curves
plt.plot(range(steps), g,
c='black',
linestyle='dashed',
alpha=1/2)
if p == 1:
s = f'Double every day'
else:
s = f'Double every {str(p)} days'
# Draw text outside
plt.text(x=steps,
y=g[steps - 1],
s=s,
alpha=3/4,
horizontalalignment='left',
verticalalignment='center',
rotation_mode='anchor')
# Draw country level data
plot_df = self.data['Confirmed t0'][countries].head(steps)
for c in countries:
plt.plot(range(len(plot_df)), np.log(plot_df[c]), label=c)
plt.xlim(0, steps-1)
plt.legend(loc='best')
plt.ylabel('Confirmed cases, log scale')
plt.xlabel('Days since 100 cases')
plt.tight_layout()
if save:
plt.savefig('../img/growth_plot.png')
plt.show()
def plot_country_cases_chg(self, country, n=7):
"""
Plot country level change in cases with n day moving average.
"""
df = self.data['Confirmed chg'][['Date', country]].copy()
df = df.rename(columns={country: 'New cases'})
plt.plot(df['Date'], df['New cases'],
label='New cases', alpha=1/2)
plt.fill_between(df['Date'], y1=0, y2=df['New cases'], alpha=1/4)
plt.plot(df['Date'], df['New cases'].rolling(n).mean(),
label=f'{n} day average', c='black')
plt.xlim(df['Date'].min(), df['Date'].max())
plt.ylim(0)
plt.title(f'{country}')
plt.ylabel('Daily new cases')
plt.legend(loc='best')
plt.tight_layout()
plt.savefig(f'../img/{country.lower()}_cases_chg.png')
plt.show()
def plot_with_slope(self, x, y):
"""
Create scatter plot with regression line and
greyed out R squared.
"""
X = self.data['World bank'][x]
Y = self.data['World bank'][y]
X_reg = np.linspace(np.min(X), np.max(X), 1000)
# Estimate Y = aX +b
a, b, c, p, _ = linregress(X, Y)
# Get r squared
r = c * c
Y_reg = a * X_reg + b
label_reg = f'y = {round(a, 4)}x + {round(b, 4)}'
text_reg = r'$R^{2}$' + f'={round(r, 2)}'# + '\n' + r'$p$-value' + f'={round(p, 2)}'
plt.figure(figsize=(5,5))
plt.scatter(x=X, y=Y, s=4, alpha=2/3)
plt.plot(X_reg, Y_reg,
linewidth=1,
color='black',
label=label_reg)
plt.text(x=(np.min(X) + np.max(X))/2,
y=(np.min(Y) + np.max(Y))/2,
s=text_reg,
alpha=1/4,
fontsize=30,
verticalalignment='center',
horizontalalignment='center')
plt.xlabel(f'{x}')
plt.ylabel(f'{y}')
# plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
def _sort_ctry_stats(self, stat_name, min_cases=5000, n=10):
"""
Sort the dataframe of country statistics using a cutoff
of `min_cases` and return top `n` countries.
"""
df = self.data['Country stats'].copy()
df['Has min cases'] = df['Confirmed'] > min_cases
df = df[df['Has min cases'] == True]
df = df.sort_values(stat_name, ascending=False)
df = df.reset_index(drop=True)
df = df[['Country', stat_name]]
df = df.head(n)
return df
def show_corr_mat(self):
"""
Display colourfull correlation matrix of cases with socioeconomic factors.
"""
C = self.data['World bank'].corr()
C = C.style.background_gradient(cmap='coolwarm')
C = C.set_precision(2)
C = C.set_table_attributes('style="font-size: 13px"')
display(C)
def exp_growth(a, b, t, tau):
"""
Calculate exponential growth.
Parameters
----------
a : int
Initial value.
b : int
Growth factor.
t : int
Time.
tau : int
Time required for increase by factor of b.
Notes
-----
See https://en.wikipedia.org/wiki/Exponential_growth
for details.
"""
return a * np.power(b, t / tau)
|
{
"alphanum_fraction": 0.5119228818,
"author": null,
"avg_line_length": 27,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "85aa4a86be8407a7339bdd81ecf7f914f76953e0",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-06-17T15:53:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-17T15:53:18.000Z",
"max_forks_repo_head_hexsha": "0976f5790a34281e89e0be35dab3265c71e8a091",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jrderek/Data-Analytics-works",
"max_forks_repo_path": "Data-Analytics-Projects-in-python-main/COVID19/visualizations/covid_data_viz.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0976f5790a34281e89e0be35dab3265c71e8a091",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jrderek/Data-Analytics-works",
"max_issues_repo_path": "Data-Analytics-Projects-in-python-main/COVID19/visualizations/covid_data_viz.py",
"max_line_length": 100,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "0976f5790a34281e89e0be35dab3265c71e8a091",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jrderek/Data-Analytics-works",
"max_stars_repo_path": "Data-Analytics-Projects-in-python-main/COVID19/visualizations/covid_data_viz.py",
"max_stars_repo_stars_event_max_datetime": "2022-02-07T14:26:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-13T07:06:40.000Z",
"num_tokens": 2741,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 11826
}
|
import tensorflow as tf
import numpy as np
import datetime as dt
def get_batch(X, Xn, size):
a = np.random.choice(len(X), size, replace=False)
return X[a], Xn[a]
# A denoising autoencoder is pretty much the same architecture as a normal autoencoder. The input is noised up,
# and cost function tries to denoise it by minimizing the construction error from denoised input to clean output.
class Autoencoder:
def __init__(self, input_dim, hidden_dim, epoch=1000, batch_size=50, learning_rate=0.001):
self.epoch = epoch
self.batch_size = batch_size
self.learning_rate = learning_rate
self.x = tf.placeholder(dtype=tf.float32, shape=[None, input_dim], name='x')
self.x_noised = tf.placeholder(dtype=tf.float32, shape=[None, input_dim], name='x_noised')
with tf.name_scope('encode'):
weights = tf.Variable(tf.random_normal([input_dim, hidden_dim], dtype=tf.float32), name='weights')
biases = tf.Variable(tf.zeros([hidden_dim]), name='biases')
encoded = tf.nn.sigmoid(tf.matmul(self.x_noised, weights) + biases, name='encoded')
with tf.name_scope('decode'):
weights = tf.Variable(tf.random_normal([hidden_dim, input_dim], dtype=tf.float32), name='weights')
biases = tf.Variable(tf.zeros([input_dim]), name='biases')
decoded = tf.matmul(encoded, weights) + biases
self.encoded = encoded
self.decoded = decoded
self.loss = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(self.x, self.decoded))))
self.loss_summ = tf.summary.scalar('loss', self.loss)
self.train_op = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.loss)
self.saver = tf.train.Saver()
def add_noise(self, data):
noise_type = 'mask-0.2'
if noise_type == 'gaussian':
n = np.random.normal(0, 0.1, np.shape(data))
return data + n
if 'mask' in noise_type:
frac = float(noise_type.split('-')[1])
temp = np.copy(data)
for i in temp:
n = np.random.choice(len(i), round(frac * len(i)), replace=False)
i[n] = 0
return temp
def train(self, data):
data_noised = self.add_noise(data)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
# Create a directory everytime so that tensorboard displays each job individually
now = dt.datetime.now()
currentDir = "./logs/" + now.strftime("%Y%m%d-%H%M%S") + "/"
writer = tf.summary.FileWriter(currentDir, graph=sess.graph)
tf.train.write_graph(sess.graph_def, "./logs/", 'graph.pbtxt')
for i in range(self.epoch):
for j in range(np.shape(data)[0] // self.batch_size):
batch_data, batch_data_noised = get_batch(data, data_noised, self.batch_size)
l, _, l_summ = sess.run([self.loss, self.train_op, self.loss_summ], feed_dict={self.x: batch_data,
self.x_noised: batch_data_noised})
if i % 100 == 0:
print('epoch {0}: loss = {1}'.format(i, l))
self.saver.save(sess, './model.ckpt')
writer.add_summary(summary=l_summ, global_step=i)
writer.flush()
self.saver.save(sess, './model.ckpt')
writer.close()
def test(self, data):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
hidden, reconstructed = sess.run([self.encoded, self.decoded], feed_dict={self.x: data})
print('input', data)
print('compressed', hidden)
print('reconstructed', reconstructed)
return reconstructed
def get_params(self):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
weights, biases = sess.run([self.weights1, self.biases1])
return weights, biases
def encode(self, data):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.saver.restore(sess, './model.ckpt')
# hidden are the embeddings
hidden = sess.run(self.encoded, feed_dict={self.x: data, self.x_noised: data})
return hidden
def decode(self, encoding):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.saver.restore(sess, './model.ckpt')
reconstructed = sess.run(self.decoded, feed_dict={self.encoded: encoding})
img = np.reshape(reconstructed, (32, 32))
return img
|
{
"alphanum_fraction": 0.5973673214,
"author": null,
"avg_line_length": 45.580952381,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "264c6e0345da8a7ad846fd5b57931c7102110bd6",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "cde9a548cb30e0e7844d7fb45e8fea29ed58eedb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chdamianos/TensorFlow-Book",
"max_forks_repo_path": "Chapter 7 Autoencoders/autoencoder_noise_DC.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cde9a548cb30e0e7844d7fb45e8fea29ed58eedb",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "chdamianos/TensorFlow-Book",
"max_issues_repo_path": "Chapter 7 Autoencoders/autoencoder_noise_DC.py",
"max_line_length": 118,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cde9a548cb30e0e7844d7fb45e8fea29ed58eedb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chdamianos/TensorFlow-Book",
"max_stars_repo_path": "Chapter 7 Autoencoders/autoencoder_noise_DC.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1069,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4786
}
|
run.year <- 2017
post.season.fram.db <- "./fram db/Final pre and post databases/FramVS2-PSC-Coho-Backwards-thru2016.mdb"
post.season.run.name <- ""
post.season.tamm <- "./fram db/TAMM_Files_Postseason/.xlsx"
post.season.tamm.fishery.ref <- "./data/TammFisheryQueetsRef.csv"
post.season.tamm.esc.ref <- "./data/TammEscQueetsRef.csv"
pre.season.fram.db <- "./fram db/Final pre and post databases/US_PFMC_NOF_FinalCohoFRAM_MultiYr.mdb"
pre.season.run.name <- "bkCoho1731"
pre.season.tamm <- "./fram db/TAMM_Files_Preseason/Coho1731_Final_wSht1Mtrx.xlsx"
pre.season.tamm.fishery.ref <- "./data/TammFisheryFullRef.csv"
pre.season.tamm.esc.ref <- "./data/TammEscFullRef.csv"
|
{
"alphanum_fraction": 0.7441520468,
"author": null,
"avg_line_length": 48.8571428571,
"converted": null,
"ext": "r",
"file": null,
"hexsha": "688077c12c1204a7e2238ac773d13e2bfcd35d72",
"include": null,
"lang": "R",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "14309790ecb30118757dc890fcb5d6e5c85db3f8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "methiess/PSC-FRAM-Admin",
"max_forks_repo_path": "config/2017_report_config.r",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "14309790ecb30118757dc890fcb5d6e5c85db3f8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "methiess/PSC-FRAM-Admin",
"max_issues_repo_path": "config/2017_report_config.r",
"max_line_length": 104,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "14309790ecb30118757dc890fcb5d6e5c85db3f8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "methiess/PSC-FRAM-Admin",
"max_stars_repo_path": "config/2017_report_config.r",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 222,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 684
}
|
import json
import urllib
import numpy as np
API = 'http://ec2-52-11-11-89.us-west-2.compute.amazonaws.com/challenge17/api.py'
def get_blocked_videos(api=API):
api_url = '{}?action=get_blocked'.format(api)
req = urllib.request.Request(api_url)
response = urllib.request.urlopen(req)
return json.loads(response.read())
def interpolated_prec_rec(prec, rec):
"""Interpolated AP - VOCdevkit from VOC 2011.
"""
mprec = np.hstack([[0], prec, [0]])
mrec = np.hstack([[0], rec, [1]])
for i in range(len(mprec) - 1)[::-1]:
mprec[i] = max(mprec[i], mprec[i + 1])
idx = np.where(mrec[1::] != mrec[0:-1])[0] + 1
ap = np.sum((mrec[idx] - mrec[idx - 1]) * mprec[idx])
return ap
def segment_iou(target_segment, candidate_segments):
"""Compute the temporal intersection over union between a
target segment and all the test segments.
Parameters
----------
target_segment : 1d array
Temporal target segment containing [starting, ending] times.
candidate_segments : 2d array
Temporal candidate segments containing N x [starting, ending] times.
Outputs
-------
tiou : 1d array
Temporal intersection over union score of the N's candidate segments.
"""
tt1 = np.maximum(target_segment[0], candidate_segments[:, 0])
tt2 = np.minimum(target_segment[1], candidate_segments[:, 1])
# Intersection including Non-negative overlap score.
segments_intersection = (tt2 - tt1).clip(0)
# Segment union.
segments_union = (candidate_segments[:, 1] - candidate_segments[:, 0]) \
+ (target_segment[1] - target_segment[0]) - segments_intersection
# Compute overlap as the ratio of the intersection
# over union of two segments.
tIoU = segments_intersection.astype(float) / segments_union
return tIoU
def wrapper_segment_iou(target_segments, candidate_segments):
"""Compute intersection over union btw segments
Parameters
----------
target_segments : ndarray
2-dim array in format [m x 2:=[init, end]]
candidate_segments : ndarray
2-dim array in format [n x 2:=[init, end]]
Outputs
-------
tiou : ndarray
2-dim array [n x m] with IOU ratio.
Note: It assumes that candidate-segments are more scarce that target-segments
"""
if candidate_segments.ndim != 2 or target_segments.ndim != 2:
raise ValueError('Dimension of arguments is incorrect')
n, m = candidate_segments.shape[0], target_segments.shape[0]
tiou = np.empty((n, m))
for i in range(m):
tiou[:, i] = segment_iou(target_segments[i,:], candidate_segments)
return tiou
|
{
"alphanum_fraction": 0.6609022556,
"author": null,
"avg_line_length": 35,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "07a9327cab4874e558cf500bdd8709544610d005",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1eebaf3e4b358a940e21f37d387de23503d5bda0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Lechatelia/video_detection_tools",
"max_forks_repo_path": "evaluation/activitynet/Evaluation/utils.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1eebaf3e4b358a940e21f37d387de23503d5bda0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Lechatelia/video_detection_tools",
"max_issues_repo_path": "evaluation/activitynet/Evaluation/utils.py",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1eebaf3e4b358a940e21f37d387de23503d5bda0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Lechatelia/video_detection_tools",
"max_stars_repo_path": "evaluation/activitynet/Evaluation/utils.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 680,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2660
}
|
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2015-2018 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
"""
Module exports :class:'DostEtAl2004'
"""
import numpy as np
# standard acceleration of gravity in m/s**2
from scipy.constants import g
from openquake.hazardlib.gsim.base import GMPE, CoeffsTable
from openquake.hazardlib import const
from openquake.hazardlib.imt import PGA, PGV
class DostEtAl2004(GMPE):
"""
Implements the GMPE of Dost et al. (2004) for PGA and PGV from
induced seismicity earthquakes in the Netherlands
Dost, B., van Eck, T. and Haak, H. (2004) Scaling of peak ground
acceleration and peak ground velocity recorded in the Netherlands.
Bollettino di Geofisica Teorica ed Applicata. 45(3), 153 - 168
"""
#: The GMPE is derived from induced earthquakes
DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.INDUCED
#: Supported intensity measure types are peak ground acceleration
#: and peak ground velocity
DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([
PGA,
PGV
])
#: Supported intensity measure component is the average horizontal
DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.GMRotD100
#: Supported standard deviation types is total.
DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([
const.StdDev.TOTAL
])
#: No required site parameters
REQUIRES_SITES_PARAMETERS = set(())
#: Required rupture parameters are magnitude (ML is used)
REQUIRES_RUPTURE_PARAMETERS = set(('mag', ))
#: Required distance measure is hypocentral distance
REQUIRES_DISTANCES = set(('rhypo',))
#: GMPE not tested against independent implementation so raise
#: not verified warning
non_verified = True
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
C = self.COEFFS[imt]
imean = (self._compute_magnitude_term(C, rup.mag) +
self._compute_distance_term(C, dists.rhypo))
# Convert mean from cm/s and cm/s/s
if isinstance(imt, PGA):
mean = np.log((10.0 ** (imean)) / g)
else:
mean = np.log(10.0 ** imean)
stddevs = self._get_stddevs(C, len(dists.rhypo), stddev_types)
return mean, stddevs
def _compute_magnitude_term(self, C, mag):
"""
Returns the magnitude scaling term
"""
return C["c0"] + (C["c1"] * mag)
def _compute_distance_term(self, C, rhypo):
"""
Returns the distance scaling term
"""
return (C["c2"] * rhypo) + (C["c3"] * np.log10(rhypo))
def _get_stddevs(self, C, num_sites, stddev_types):
"""
Returns the total standard deviation
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(
np.log(10.0 ** C["sigma"]) + np.zeros(num_sites))
return stddevs
COEFFS = CoeffsTable(sa_damping=5, table="""
IMT c0 c1 c2 c3 sigma
pgv -1.53 0.74 -0.00139 -1.33 0.33
pga -1.41 0.57 -0.00139 -1.33 0.33
""")
class DostEtAl2004BommerAdaptation(DostEtAl2004):
"""
Adaptation of the GMPE for application to higher magnitudes proposed
by Bommer et al. (2013)
"""
#: Supported standard deviation types is total.
DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([
const.StdDev.TOTAL,
const.StdDev.INTER_EVENT,
const.StdDev.INTRA_EVENT
])
def _compute_magnitude_term(self, C, mag):
"""
Returns the magnitude scaling term
"""
return C["c0"] + (C["c1"] * mag) + (C["c1e"] * ((mag - 4.5) ** 2.0))
def _get_stddevs(self, C, num_sites, stddev_types):
"""
Returns the the total, inter-event and intra-event standard deviation
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(
np.log(10.0 ** C["sigma"]) + np.zeros(num_sites))
if stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(
np.log(10.0 ** C["tau"]) + np.zeros(num_sites))
if stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(
np.log(10.0 ** C["phi"]) + np.zeros(num_sites))
return stddevs
COEFFS = CoeffsTable(sa_damping=5, table="""
IMT c0 c1 c1e c2 c3 tau phi sigma
pgv -1.3972 0.7105 -0.0829 -0.00139 -1.33 0.1476 0.2952 0.33
pga -1.6090 0.6140 -0.1116 -0.00139 -1.33 0.1476 0.2952 0.33
""")
|
{
"alphanum_fraction": 0.6292845843,
"author": null,
"avg_line_length": 35.55625,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "98e2653399608039a59579d013cba58bca985ad3",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z",
"max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "gfzriesgos/shakyground-lfs",
"max_forks_repo_path": "openquake/hazardlib/gsim/dost_2004.py",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b",
"max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "gfzriesgos/shakyground-lfs",
"max_issues_repo_path": "openquake/hazardlib/gsim/dost_2004.py",
"max_line_length": 77,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "gfzriesgos/shakyground-lfs",
"max_stars_repo_path": "openquake/hazardlib/gsim/dost_2004.py",
"max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z",
"num_tokens": 1548,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 5689
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import rospy
import sys
import time
from numpy import *
import roslib.packages
from sensor_msgs.msg import *
from geometry_msgs.msg import *
cnow = time.ctime()
cnvtime = time.strptime(cnow)
ex_time = time.strftime("%Y%m%d %H%M",cnvtime)
file_path = roslib.packages.get_pkg_dir('sobit_test') + "/output/state/"
out_file = open(file_path + 'out_state' + ex_time + '.txt', 'w') #書き込みモードでオープン
first_flag = True
first_sec = 0
def callback(enc):
global first_flag,first_sec
print enc
if first_flag == True:
first_sec = enc.header.stamp.secs
first_flag = False
in_state = str(enc.position[2])
in_time_sec = str(enc.header.stamp.secs)
in_time_sec2 = str(enc.header.stamp.secs - first_sec)
in_time_nsec = str(enc.header.stamp.nsecs)
in_time = in_time_sec + '.' + in_time_nsec
print in_state
print in_time_sec
print in_time_nsec
print in_time
#out_file.write("enc_state:")
out_file.write(in_state)
#out_file.write("\tsec:")
#out_file.write(in_time_sec)
#out_file.write("\tnsec:")
#out_file.write(in_time_nsec)
out_file.write("\t")
out_file.write(in_time)
out_file.write("\n")
if __name__ == '__main__':
rospy.init_node('joint_test')
print "[enc_state]"
out_file.write("enc_state")
out_file.write("\ttime\n")
sub = rospy.Subscriber('/sobit_enc', JointState, callback)
rospy.spin()
print "exit"
out_file.close()
|
{
"alphanum_fraction": 0.7225806452,
"author": null,
"avg_line_length": 21.796875,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "764f6ff60eca3c040e765171dc01b1851fbc74c3",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "81a228390e1726653d54f33afb3fbb1c1fdb5b24",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Choi-Laboratory/sobit_blue",
"max_forks_repo_path": "sobit_test/src/out_state_test.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "81a228390e1726653d54f33afb3fbb1c1fdb5b24",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Choi-Laboratory/sobit_blue",
"max_issues_repo_path": "sobit_test/src/out_state_test.py",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "81a228390e1726653d54f33afb3fbb1c1fdb5b24",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Choi-Laboratory/sobit_blue",
"max_stars_repo_path": "sobit_test/src/out_state_test.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 399,
"path": null,
"reason": "from numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1395
}
|
import numpy as np
import math
import keras
from game2048.agents import ExpectiMaxAgent as TestAgent
from game2048.expectimax import board_to_move
import random
from game2048.game import Game
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten,BatchNormalization,Input
from keras.layers import Conv2D, MaxPooling2D,concatenate,Activation
from keras.optimizers import SGD,Adam
from keras.utils import to_categorical
from keras.models import load_model
from keras import regularizers
from keras.utils import plot_model
from collections import namedtuple
epoch_size=20000000
batch_size=64
capacity=40000
test_size=1000
DEEP=128
flag=5000
# 生成数据
#生成100张图片,每张图片100*100大小,是3通道的。
modelpath='./k_model/CNN_old_158.h5'
Guide = namedtuple('Guide',('state','action'))
max_d=16
class Guides:
def __init__(self,capacity):
self.capacity=capacity
self.memory=[]
self.position=0
def push(self,*args):
###save a transiton###
if len(self.memory)<self.capacity:
self.memory.append(None)
self.memory[self.position]=Guide(*args)
self.position=(self.position+1)%self.capacity
def sample(self,batch_size):
return random.sample(self.memory,batch_size)
def ready(self,batch_size):
return len(self.memory)>batch_size
def _len_(self):
return len(self.memory)
class ModelWrapper:
def __init__(self,model,capacity):
self.model=model
self.memory=Guides(capacity)
self.capacity=capacity
self.training_step=0
self.refresh=0
def predict(self,board):
p=board.reshape(-1)
data_1=np.zeros((len(p)))
for i in range(len(p)):
if p[i]!=0:
tmp=int(math.log(p[i],2))
data_1[i]=tmp
board=np.reshape(data_1,(4,4))
board = to_categorical(board,max_d)
return self.model.predict(np.expand_dims(board,axis=0))
def move(self,game):
ohe_board=game.board
suggest=board_to_move(game.board)
direction=self.predict(game.board).argmax()
game.move(direction)
a=random.randint(0,9)
# if(ohe_board.max()>=128 or a>=7):
self.memory.push(ohe_board,suggest)
# print(game.board)
return game
def onehot(self,x,shape):
p=x.reshape(-1)
data_1=np.zeros((len(p)))
for i in range(len(p)):
if p[i]!=0:
tmp=int(math.log(p[i],2))
data_1[i]=tmp
data=np.reshape(data_1,shape)
data=to_categorical(data,max_d)
return data
def train(self,batch,game):
from game2048.game import Game
#if(self.training_step<10):
if self.memory.ready(test_size) and self.refresh%batch_size==1:
guides=self.memory.sample(batch)
X=[]
Y=[]
for guide in guides:
X.append(guide.state)
ohe_action=[0]*4
ohe_action[guide.action]=1
Y.append(ohe_action)
X=self.onehot(np.array(X),(batch_size,4,4))
loss,acc=self.model.train_on_batch(np.array(X), np.array(Y))
# for test############
if(self.training_step%500==1):
guides=self.memory.sample(test_size)
x_test=[]
y_test=[]
for guide in guides:
x_test.append(guide.state)
ohe_action=[0]*4
ohe_action[guide.action]=1
y_test.append(ohe_action)
x_test=self.onehot(np.array(x_test),(test_size,4,4))
print(type(x_test))
score= model.evaluate(x_test, y_test, verbose=1)
with open('oldtrainvalue.txt','a') as f:
f.write("\nmyagent")
f.write("loss"+str(score[0]))
f.write("accuracy"+str(score[1]))
#end test################################
# if (self.memory._len_==20000-1):
# self.memory=Guides(capacity)
self.training_step+=1
game=self.move(game)
self.refresh+=1
return game
else:
game=self.move(game)
self.refresh+=1
return game
# model= load_model(modelpath)
# print("load_model"+modelpath)
inputs=Input((4,4,max_d))
conv=inputs
conv21=(Conv2D(DEEP, (2, 1), kernel_initializer='he_uniform')(conv))
conv12=(Conv2D(DEEP, (1, 2), kernel_initializer='he_uniform')(conv))
conv22=(Conv2D(DEEP, (2, 2), kernel_initializer='he_uniform')(conv))
conv33=(Conv2D(DEEP, (3, 3), kernel_initializer='he_uniform')(conv))
conv44=(Conv2D(DEEP, (4, 4), kernel_initializer='he_uniform')(conv))
hidden=concatenate([Flatten()(conv21), Flatten()(conv12), Flatten()(conv22), Flatten()(conv33), Flatten()(conv44)])
x = BatchNormalization()(hidden)
x = Activation('relu')(x)
print(type(x))
# for width in [512,128]:
# x=Dense(256, activation='relu')(x)
# x=BatchNormalization()(x)
# x=Activation('relu')
x=Dense(1024, kernel_initializer='he_uniform',activation='relu')(x)
x=BatchNormalization()(x)
x=Dense(128, kernel_initializer='he_uniform',activation='relu')(x)
x=BatchNormalization()(x)
outputs=Dense(4,activation='softmax',kernel_regularizer=regularizers.l2(0.01),activity_regularizer=regularizers.l1(0.001))(x)
# outputs=np.argmax()
model=Model(inputs,outputs)
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
M1=ModelWrapper(model,capacity)
game = Game(4, 2048)
while M1.training_step<epoch_size:
# print(game.board)
if(game.board.max()<=2048 and game.board.min()==0):
game=M1.train(batch_size,game)
else:
game = Game(4, 2048)
game=M1.train(batch_size,game)
print("new game",str(game.board.max()))
if(M1.training_step==flag):
model.save("./k_model/CNN_old_16_"+str(round(M1.training_step/10000)+200)+".h5")
flag+=5000
with open('oldtrainvalue.txt','a') as f:
f.write("\nnewmodel")
f.write("\n./k_model/CNN_old_16_"+str(round(M1.training_step/10000)+200)+".h5")
# print("M1.training_step",M1.training_step)
# model.summary()
# model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
# model.fit(x_train, y_train, batch_size=batch_size, epochs=epoch_size,shuffle=True,verbose=2,validation_split=0.3)
# model.train_on_batch(np.array(x_train), np.array(y_train))
# print(np.shape(x_train))
# print(np.argmax(model.predict(np.reshape(x_test[0],(1,4,4,5)))))
# score= model.evaluate(x_test, y_test, verbose=1)
# print(score)
# print('loss:',score[0])
# print('accuracy:',score[1])
|
{
"alphanum_fraction": 0.6933027673,
"author": null,
"avg_line_length": 31.4793814433,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "9ead8512f30754580cad1634ec3a6685c4859e05",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bf46c209e0ae3af41554a47889634f7ed7630016",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "mingsjtu/2048-api",
"max_forks_repo_path": "online_train.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bf46c209e0ae3af41554a47889634f7ed7630016",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "mingsjtu/2048-api",
"max_issues_repo_path": "online_train.py",
"max_line_length": 126,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "bf46c209e0ae3af41554a47889634f7ed7630016",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "mingsjtu/2048-api",
"max_stars_repo_path": "online_train.py",
"max_stars_repo_stars_event_max_datetime": "2019-09-04T05:28:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-04T05:28:03.000Z",
"num_tokens": 1706,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 6107
}
|
(*-------------------------------------------*
| CSP-Prover on Isabelle2005 |
| February 2006 |
| April 2006 (modified) |
| March 2007 (modified) |
| |
| Yoshinao Isobe (AIST JAPAN) |
*-------------------------------------------*)
theory FNF_F_sf_seq
imports FNF_F_sf_induct FNF_F_sf_ext
begin
(* The following simplification rules are deleted in this theory file *)
(* because they unexpectly rewrite UnionT and InterT. *)
(* disj_not1: (~ P | Q) = (P --> Q) *)
declare disj_not1 [simp del]
(* The following simplification rules are deleted in this theory file *)
(* P (if Q then x else y) = ((Q --> P x) & (~ Q --> P y)) *)
(* Isabelle 2017: split_if --> if_split *)
declare if_split [split del]
(*****************************************************************
1. full sequentialization for Sequential composition (P1 ;; P2)
2.
3.
*****************************************************************)
(*============================================================*
| |
| Seq_compo P ;; Q |
| |
*============================================================*)
definition
Pfun_Seq_compo :: "('p,'a) proc => (('p,'a) proc => ('p,'a) proc)"
where
Pfun_Seq_compo_def :
"Pfun_Seq_compo P2 == (%P1. P1 ;; P2)"
definition
SP_step_Seq_compo ::
"('p,'a) proc => ('a set => ('a => ('p,'a) proc) => ('p,'a) proc =>
('a => ('p,'a) proc) => ('p,'a) proc)"
where
SP_step_Seq_compo_def :
"SP_step_Seq_compo P2 == (%Y1 Pf1 Q1 SPf.
(if (Q1 = SKIP)
then (((? x:Y1 -> SPf x) [+] STOP) [>seq P2)
else if (Q1 = DIV)
then (((? x:Y1 -> SPf x) [+] STOP) [>seq SDIV)
else ((? x:Y1 -> SPf x) [+] STOP)))"
definition
fsfF_Seq_compo :: "('p,'a) proc => ('p,'a) proc => ('p,'a) proc"
("(1_ /;;seq _)" [79,78] 78)
where
fsfF_Seq_compo_def :
"fsfF_Seq_compo == (%P1 P2.
(fsfF_induct1 (Pfun_Seq_compo P2)
(SP_step_Seq_compo P2) P1))"
(*************************************************************
function fsfF fsfF -> fsfF
*************************************************************)
lemma fsfF_Seq_compo_in:
"[| P1 : fsfF_proc ; P2 : fsfF_proc |]
==> P1 ;;seq P2 : fsfF_proc"
apply (simp add: fsfF_Seq_compo_def)
apply (rule fsfF_induct1_in)
apply (simp_all add: SP_step_Seq_compo_def)
apply (simp split: if_split)
apply (intro conjI impI)
apply (rule fsfF_Timeout_in)
apply (simp_all add: fsfF_proc.intros)
apply (rule fsfF_Timeout_in)
apply (simp_all add: fsfF_proc.intros)
done
(*------------------------------------------------------------*
| syntactical transformation to fsfF |
*------------------------------------------------------------*)
lemma cspF_fsfF_Seq_compo_eqF:
"P1 ;; P2 =F P1 ;;seq P2"
apply (simp add: fsfF_Seq_compo_def)
apply (rule cspF_rw_right)
apply (rule cspF_fsfF_induct1_eqF[THEN cspF_sym])
apply (simp_all add: Pfun_Seq_compo_def SP_step_Seq_compo_def)
apply (erule disjE)
(* SKIP *)
apply (simp)
apply (rule cspF_rw_left)
apply (rule cspF_SKIP_DIV_Seq_compo_step_resolve)
apply (rule cspF_rw_right)
apply (rule cspF_fsfF_Timeout_eqF[THEN cspF_sym])
apply (rule cspF_decompo)
apply (rule cspF_decompo)
apply (rule cspF_rw_right)
apply (rule cspF_unit)
apply (rule cspF_reflex)
apply (rule cspF_reflex)
apply (rule cspF_reflex)
apply (erule disjE)
(* DIV *)
apply (simp)
apply (rule cspF_rw_left)
apply (rule cspF_SKIP_DIV_Seq_compo_step_resolve)
apply (rule cspF_rw_right)
apply (rule cspF_fsfF_Timeout_eqF[THEN cspF_sym])
apply (rule cspF_rw_left)
apply (rule cspF_Ext_choice_SKIP_or_DIV_resolve)
apply (simp)
apply (rule cspF_decompo)
apply (rule cspF_decompo)
apply (rule cspF_rw_right)
apply (rule cspF_unit)
apply (rule cspF_reflex)
apply (rule cspF_reflex)
apply (rule cspF_SDIV_eqF)
(* STOP *)
apply (simp)
apply (rule cspF_rw_left)
apply (rule cspF_decompo)
apply (rule cspF_unit)
apply (rule cspF_reflex)
apply (rule cspF_rw_left)
apply (rule cspF_step)
apply (rule cspF_rw_right)
apply (rule cspF_unit)
apply (rule cspF_reflex)
(* congruence *)
apply (rule cspF_rw_left,
(simp
| rule cspF_IF_split[THEN cspF_sym]
| rule cspF_fsfF_Timeout_eqF[THEN cspF_sym]
| rule cspF_decompo
| rule cspF_reflex)+ ,
rule cspF_rw_right,
(simp
| rule cspF_IF_split[THEN cspF_sym]
| rule cspF_fsfF_Timeout_eqF[THEN cspF_sym]
| rule cspF_decompo
| rule cspF_reflex)+)+
done
(****************** to add them again ******************)
declare if_split [split]
declare disj_not1 [simp]
end
|
{
"alphanum_fraction": null,
"author": "yoshinao-isobe",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/isabelle/yoshinao-isobe-CSP-Prover/CSP-Prover-806fbe330d7e23279675a2eb351e398cb8a6e0a8/FNF_F/FNF_F_sf_seq.thy",
"reason": null,
"repo": "CSP-Prover",
"save_path": "github-repos/isabelle/yoshinao-isobe-CSP-Prover",
"sha": "806fbe330d7e23279675a2eb351e398cb8a6e0a8",
"size": null
}
|
import pandas as pd
import numpy as np
import os
import pathlib as path
def load(p: path.Path):
raw_data = np.loadtxt(str(p.absolute()),delimiter=',')
label = raw_data[:, 0].astype(int)
data = raw_data[:, 1:]
# print(label[:5], data[:5, :10])
return label, data
def loadd(p: path.Path):
data = []
label = []
with open(str(p.absolute()), 'r') as f:
for line in f.readlines():
a = line.split(',')
label.append(int(a[0]))
data.append(np.array(a[1:]).astype(float))
return label, data
def join_path(data_dir, name):
p = os.path.join(data_dir, name)
p_train = os.path.join(p, f"{name}_TRAIN")
p_test = os.path.join(p, f"{name}_TEST")
return path.Path(p_train), path.Path(p_test)
def load_ucr(data_dir, name):
train_path, test_path = join_path(data_dir, name)
train_label, train_data = load(train_path)
test_label, test_data = load(test_path)
return train_data, train_label, test_data, test_label
def load_ucrd(data_dir, name):
train_path, test_path = join_path(data_dir, name)
train_label, train_data = loadd(train_path)
test_label, test_data = loadd(test_path)
return train_data, train_label, test_data, test_label
if __name__ == "__main__":
p = path.Path('../data/ucr2015_d/50words/50words_TEST')
loadd(p)
|
{
"alphanum_fraction": 0.6506291636,
"author": null,
"avg_line_length": 27.02,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "0d90737195ada2948cffb1f09b87849ac5a399d3",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "17d80a0e02ecce081ae4d4c1c3c3d779a844ceec",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "actcwlf/gdtw_exp",
"max_forks_repo_path": "auxiliary/dataset.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "17d80a0e02ecce081ae4d4c1c3c3d779a844ceec",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "actcwlf/gdtw_exp",
"max_issues_repo_path": "auxiliary/dataset.py",
"max_line_length": 59,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "17d80a0e02ecce081ae4d4c1c3c3d779a844ceec",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "actcwlf/gdtw_exp",
"max_stars_repo_path": "auxiliary/dataset.py",
"max_stars_repo_stars_event_max_datetime": "2021-06-07T03:32:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-19T11:06:27.000Z",
"num_tokens": 363,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1351
}
|
"""
Copyright 2013 Steven Diamond, Eric Chu
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.
"""
import math
import numpy as np
import cvxpy as cvx
from cvxpy.tests.base_test import BaseTest
class TestNonlinearAtoms(BaseTest):
""" Unit tests for the nonlinear atoms module. """
def setUp(self) -> None:
self.x = cvx.Variable(2, name='x')
self.y = cvx.Variable(2, name='y')
self.A = cvx.Variable((2, 2), name='A')
self.B = cvx.Variable((2, 2), name='B')
self.C = cvx.Variable((3, 2), name='C')
def test_log_problem(self) -> None:
# Log in objective.
obj = cvx.Maximize(cvx.sum(cvx.log(self.x)))
constr = [self.x <= [1, math.e]]
p = cvx.Problem(obj, constr)
result = p.solve(solver=cvx.ECOS)
self.assertAlmostEqual(result, 1)
self.assertItemsAlmostEqual(self.x.value, [1, math.e])
# Log in constraint.
obj = cvx.Minimize(cvx.sum(self.x))
constr = [cvx.log(self.x) >= 0, self.x <= [1, 1]]
p = cvx.Problem(obj, constr)
result = p.solve(solver=cvx.ECOS)
self.assertAlmostEqual(result, 2)
self.assertItemsAlmostEqual(self.x.value, [1, 1])
# Index into log.
obj = cvx.Maximize(cvx.log(self.x)[1])
constr = [self.x <= [1, math.e]]
p = cvx.Problem(obj, constr)
result = p.solve(solver=cvx.ECOS)
self.assertAlmostEqual(result, 1)
# Scalar log.
obj = cvx.Maximize(cvx.log(self.x[1]))
constr = [self.x <= [1, math.e]]
p = cvx.Problem(obj, constr)
result = p.solve(solver=cvx.ECOS)
self.assertAlmostEqual(result, 1)
def test_entr(self) -> None:
"""Test the entr atom.
"""
self.assertEqual(cvx.entr(0).value, 0)
assert np.isneginf(cvx.entr(-1).value)
def test_kl_div(self) -> None:
"""Test a problem with kl_div.
"""
kK = 50
kSeed = 10
prng = np.random.RandomState(kSeed)
# Generate a random reference distribution
npSPriors = prng.uniform(0.0, 1.0, kK)
npSPriors = npSPriors / sum(npSPriors)
# Reference distribution
p_refProb = cvx.Parameter(kK, nonneg=True)
# Distribution to be estimated
v_prob = cvx.Variable(kK)
objkl = cvx.sum(cvx.kl_div(v_prob, p_refProb))
constrs = [cvx.sum(v_prob) == 1]
klprob = cvx.Problem(cvx.Minimize(objkl), constrs)
p_refProb.value = npSPriors
klprob.solve(solver=cvx.SCS, verbose=True)
self.assertItemsAlmostEqual(v_prob.value, npSPriors, places=3)
klprob.solve(solver=cvx.ECOS, verbose=True)
self.assertItemsAlmostEqual(v_prob.value, npSPriors)
def test_rel_entr(self) -> None:
"""Test a problem with rel_entr.
"""
kK = 50
kSeed = 10
prng = np.random.RandomState(kSeed)
# Generate a random reference distribution
npSPriors = prng.uniform(0.0, 1.0, kK)
npSPriors = npSPriors / sum(npSPriors)
# Reference distribution
p_refProb = cvx.Parameter(kK, nonneg=True)
# Distribution to be estimated
v_prob = cvx.Variable(kK)
obj_rel_entr = cvx.sum(cvx.rel_entr(v_prob, p_refProb))
constrs = [cvx.sum(v_prob) == 1]
rel_entr_prob = cvx.Problem(cvx.Minimize(obj_rel_entr), constrs)
p_refProb.value = npSPriors
rel_entr_prob.solve(solver=cvx.SCS, verbose=True)
self.assertItemsAlmostEqual(v_prob.value, npSPriors, places=3)
rel_entr_prob.solve(solver=cvx.ECOS, verbose=True)
self.assertItemsAlmostEqual(v_prob.value, npSPriors)
def test_difference_kl_div_rel_entr(self) -> None:
"""A test showing the difference between kl_div and rel_entr
"""
x = cvx.Variable()
y = cvx.Variable()
kl_div_prob = cvx.Problem(cvx.Minimize(cvx.kl_div(x, y)), constraints=[x + y <= 1])
kl_div_prob.solve(solver=cvx.ECOS)
self.assertItemsAlmostEqual(x.value, y.value)
self.assertItemsAlmostEqual(kl_div_prob.value, 0)
rel_entr_prob = cvx.Problem(cvx.Minimize(cvx.rel_entr(x, y)), constraints=[x + y <= 1])
rel_entr_prob.solve(solver=cvx.ECOS)
"""
Reference solution computed by passing the following command to Wolfram Alpha:
minimize x*log(x/y) subject to {x + y <= 1, 0 <= x, 0 <= y}
"""
self.assertItemsAlmostEqual(x.value, 0.2178117, places=4)
self.assertItemsAlmostEqual(y.value, 0.7821882, places=4)
self.assertItemsAlmostEqual(rel_entr_prob.value, -0.278464)
def test_entr_prob(self) -> None:
"""Test a problem with entr.
"""
for n in [5, 10, 25]:
print(n)
x = cvx.Variable(n)
obj = cvx.Maximize(cvx.sum(cvx.entr(x)))
p = cvx.Problem(obj, [cvx.sum(x) == 1])
p.solve(solver=cvx.ECOS, verbose=True)
self.assertItemsAlmostEqual(x.value, n*[1./n])
p.solve(solver=cvx.SCS, verbose=True)
self.assertItemsAlmostEqual(x.value, n*[1./n], places=3)
def test_exp(self) -> None:
"""Test a problem with exp.
"""
for n in [5, 10, 25]:
print(n)
x = cvx.Variable(n)
obj = cvx.Minimize(cvx.sum(cvx.exp(x)))
p = cvx.Problem(obj, [cvx.sum(x) == 1])
p.solve(solver=cvx.SCS, verbose=True)
self.assertItemsAlmostEqual(x.value, n*[1./n], places=3)
p.solve(solver=cvx.ECOS, verbose=True)
self.assertItemsAlmostEqual(x.value, n*[1./n])
def test_log(self) -> None:
"""Test a problem with log.
"""
for n in [5, 10, 25]:
print(n)
x = cvx.Variable(n)
obj = cvx.Maximize(cvx.sum(cvx.log(x)))
p = cvx.Problem(obj, [cvx.sum(x) == 1])
p.solve(solver=cvx.ECOS, verbose=True)
self.assertItemsAlmostEqual(x.value, n*[1./n])
p.solve(solver=cvx.SCS, verbose=True)
self.assertItemsAlmostEqual(x.value, n*[1./n], places=2)
|
{
"alphanum_fraction": 0.6027811366,
"author": null,
"avg_line_length": 36.1530054645,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "a3783311e25e699a26776b3840b4e95d17cfcfcd",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 765,
"max_forks_repo_forks_event_max_datetime": "2021-04-20T00:50:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-02T19:29:39.000Z",
"max_forks_repo_head_hexsha": "a43aed7447b87f6d0fbc6f71ae5c7b84183f3369",
"max_forks_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_forks_repo_name": "phschiele/cvxpy",
"max_forks_repo_path": "cvxpy/tests/test_nonlinear_atoms.py",
"max_issues_count": 1138,
"max_issues_repo_head_hexsha": "fd1c225b0cdf541618e292cae1a4c7ea25ddc934",
"max_issues_repo_issues_event_max_datetime": "2021-04-18T23:37:31.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-01T19:40:14.000Z",
"max_issues_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_issues_repo_name": "QiuWJX/cvxpy",
"max_issues_repo_path": "cvxpy/tests/test_nonlinear_atoms.py",
"max_line_length": 95,
"max_stars_count": 3285,
"max_stars_repo_head_hexsha": "fd1c225b0cdf541618e292cae1a4c7ea25ddc934",
"max_stars_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_stars_repo_name": "QiuWJX/cvxpy",
"max_stars_repo_path": "cvxpy/tests/test_nonlinear_atoms.py",
"max_stars_repo_stars_event_max_datetime": "2021-04-19T14:51:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-03T04:02:29.000Z",
"num_tokens": 1797,
"path": null,
"reason": "import numpy,import cvxpy,from cvxpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 6616
}
|
/**
* Copyright (C) 2017 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/pipeline/resume_token.h"
#include <boost/optional/optional_io.hpp>
#include <limits>
#include "mongo/bson/bsonmisc.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/pipeline/document_source_change_stream_gen.h"
#include "mongo/db/pipeline/value_comparator.h"
#include "mongo/db/storage/key_string.h"
#include "mongo/util/hex.h"
namespace mongo {
constexpr StringData ResumeToken::kDataFieldName;
constexpr StringData ResumeToken::kTypeBitsFieldName;
bool ResumeTokenData::operator==(const ResumeTokenData& other) const {
return clusterTime == other.clusterTime && version == other.version &&
fromInvalidate == other.fromInvalidate &&
(Value::compare(this->documentKey, other.documentKey, nullptr) == 0) && uuid == other.uuid;
}
std::ostream& operator<<(std::ostream& out, const ResumeTokenData& tokenData) {
out << "{clusterTime: " << tokenData.clusterTime.toString()
<< ", version: " << tokenData.version << ", applyOpsIndex" << tokenData.applyOpsIndex;
if (tokenData.version > 0) {
out << ", fromInvalidate: " << (tokenData.fromInvalidate ? "0" : "1");
}
return out << ", documentKey: " << tokenData.documentKey << ", uuid: " << tokenData.uuid << "}";
}
ResumeToken::ResumeToken(const Document& resumeDoc) {
auto dataVal = resumeDoc[kDataFieldName];
uassert(40647,
str::stream()
<< "Bad resume token: _data of missing or of wrong type. Expected string, got "
<< resumeDoc.toString(),
dataVal.getType() == BSONType::String);
_hexKeyString = dataVal.getString();
_typeBits = resumeDoc[kTypeBitsFieldName];
uassert(40648,
str::stream() << "Bad resume token: _typeBits of wrong type " << resumeDoc.toString(),
_typeBits.missing() || (_typeBits.getType() == BSONType::BinData &&
_typeBits.getBinData().type == BinDataGeneral));
}
// We encode the resume token as a KeyString with the sequence:
// clusterTime, version, applyOpsIndex, fromInvalidate, uuid, documentKey
// Only the clusterTime, version, applyOpsIndex, and fromInvalidate are required.
ResumeToken::ResumeToken(const ResumeTokenData& data) {
BSONObjBuilder builder;
builder.append("", data.clusterTime);
builder.append("", data.version);
builder.appendNumber("", data.applyOpsIndex);
if (data.version >= 1) {
builder.appendBool("", data.fromInvalidate);
}
uassert(50788,
"Unexpected resume token with a documentKey but no UUID",
data.uuid || data.documentKey.missing());
if (data.uuid) {
data.uuid->appendToBuilder(&builder, "");
}
data.documentKey.addToBsonObj(&builder, "");
auto keyObj = builder.obj();
KeyString encodedToken(KeyString::Version::V1, keyObj, Ordering::make(BSONObj()));
_hexKeyString = toHex(encodedToken.getBuffer(), encodedToken.getSize());
const auto& typeBits = encodedToken.getTypeBits();
if (!typeBits.isAllZeros())
_typeBits = Value(
BSONBinData(typeBits.getBuffer(), typeBits.getSize(), BinDataType::BinDataGeneral));
}
bool ResumeToken::operator==(const ResumeToken& other) const {
// '_hexKeyString' is enough to determine equality. The type bits are used to unambiguously
// re-construct the original data, but we do not expect any two resume tokens to have the same
// data and different type bits, since that would imply they have (1) the same timestamp and (2)
// the same documentKey (possibly different types). This should not be possible because
// documents with the same documentKey should be on the same shard and therefore should have
// different timestamps.
return _hexKeyString == other._hexKeyString;
}
ResumeTokenData ResumeToken::getData() const {
KeyString::TypeBits typeBits(KeyString::Version::V1);
if (!_typeBits.missing()) {
BSONBinData typeBitsBinData = _typeBits.getBinData();
BufReader typeBitsReader(typeBitsBinData.data, typeBitsBinData.length);
typeBits.resetFromBuffer(&typeBitsReader);
}
uassert(ErrorCodes::FailedToParse,
"resume token string was not a valid hex string",
isValidHex(_hexKeyString));
BufBuilder hexDecodeBuf; // Keep this in scope until we've decoded the bytes.
fromHexString(_hexKeyString, &hexDecodeBuf);
BSONBinData keyStringBinData =
BSONBinData(hexDecodeBuf.buf(), hexDecodeBuf.len(), BinDataType::BinDataGeneral);
auto internalBson = KeyString::toBsonSafe(static_cast<const char*>(keyStringBinData.data),
keyStringBinData.length,
Ordering::make(BSONObj()),
typeBits);
BSONObjIterator i(internalBson);
ResumeTokenData result;
uassert(40649, "invalid empty resume token", i.more());
result.clusterTime = i.next().timestamp();
// Next comes the resume token version.
uassert(50796, "Resume Token does not contain version", i.more());
auto versionElt = i.next();
uassert(50854,
"Invalid resume token: wrong type for version",
versionElt.type() == BSONType::NumberInt);
result.version = versionElt.numberInt();
uassert(50795,
"Invalid Resume Token: only supports version 0 or 1",
result.version == 0 || result.version == 1);
// Next comes the applyOps index.
uassert(50793, "Resume Token does not contain applyOpsIndex", i.more());
auto applyOpsElt = i.next();
uassert(50855,
"Resume Token applyOpsIndex is not an integer",
applyOpsElt.type() == BSONType::NumberInt);
const int applyOpsInd = applyOpsElt.numberInt();
uassert(50794, "Invalid Resume Token: applyOpsIndex should be non-negative", applyOpsInd >= 0);
result.applyOpsIndex = applyOpsInd;
if (result.version >= 1) {
// The 'fromInvalidate' bool was added in version 1 resume tokens. We don't expect to see it
// on version 0 tokens. After this bool, the remaining fields should be the same.
uassert(50872, "Resume Token does not contain fromInvalidate", i.more());
auto fromInvalidate = i.next();
uassert(50870,
"Resume Token fromInvalidate is not a boolean.",
fromInvalidate.type() == BSONType::Bool);
result.fromInvalidate = ResumeTokenData::FromInvalidate(fromInvalidate.boolean());
}
// The UUID and documentKey are not required.
if (!i.more()) {
return result;
}
// The UUID comes first, then the documentKey.
result.uuid = uassertStatusOK(UUID::parse(i.next()));
if (i.more()) {
result.documentKey = Value(i.next());
}
uassert(40646, "invalid oversized resume token", !i.more());
return result;
}
Document ResumeToken::toDocument() const {
return Document{{kDataFieldName, _hexKeyString}, {kTypeBitsFieldName, _typeBits}};
}
ResumeToken ResumeToken::parse(const Document& resumeDoc) {
return ResumeToken(resumeDoc);
}
} // namespace mongo
|
{
"alphanum_fraction": 0.6772188327,
"author": null,
"avg_line_length": 44.3214285714,
"converted": null,
"ext": "cpp",
"file": null,
"hexsha": "626ae556d186bf9f911ee16f93ed59cd1ae65c0e",
"include": null,
"lang": "C++",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "70d4944c235bcdf7fbbc63971099563d2af72956",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "danx0r/mongo",
"max_forks_repo_path": "src/mongo/db/pipeline/resume_token.cpp",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "70d4944c235bcdf7fbbc63971099563d2af72956",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "danx0r/mongo",
"max_issues_repo_path": "src/mongo/db/pipeline/resume_token.cpp",
"max_line_length": 100,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "70d4944c235bcdf7fbbc63971099563d2af72956",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "danx0r/mongo",
"max_stars_repo_path": "src/mongo/db/pipeline/resume_token.cpp",
"max_stars_repo_stars_event_max_datetime": "2019-01-16T12:59:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-16T12:59:12.000Z",
"num_tokens": 1991,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 8687
}
|
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as pl
import bluebell as bb
import bluebell.plot as bbplot
from scipy.interpolate import interp2d
from scipy.optimize import curve_fit
def show_mu_C(name, mu, C):
print(''.join(['%20s']+['%16.8f']*5) % (name, mu[0], mu[1], C[0,0], C[0,1], C[1,1]))
pl.style.use('paper.mpl')
np.random.seed(44882244)
t = np.sort(np.random.uniform(low=-3, high=3, size=10))
def lorentz(t, p):
return p[0]/(1+(t/p[1])**2)
x = np.array([1., 1.])
sigma = np.random.uniform(low=0.02, high=0.2, size=len(t))
y = lorentz(t, x) + sigma*np.random.randn(len(t))
def chi2(p):
return np.sum((lorentz(t, p) - y)**2/sigma**2)
p0 = np.array([0.95, 1.05])
ps = [p0, p0+np.array([0.1, 0]), p0+np.array([0, 0.1])]
zs = [chi2(p) for p in ps]
a, b, c, d = 1.0, 2.0, 0.5, 0.5
s = np.array(ps)
z = np.array(zs)
for i in range(20):
s = s[np.argsort(z)]
z = z[np.argsort(z)]
s0 = np.mean(s[:-1], axis=0)
# reflect
si = s0 + a*(s0 - s[-1])
zi = chi2(si)
ps.append(si + 0)
zs.append(zi + 0)
if zi < z[-1]:
z[-1] = zi + 0
s[-1] = si + 0
if zi < z[0]:
# expand
si = s0 + b*(si - s0)
zi = chi2(si)
ps.append(si + 0)
zs.append(zi + 0)
# better than reflect
if zi < z[-1]:
z[-1] = zi + 0
s[-1] = si + 0
continue
# contract
si = s0 + c*(s[-1] - s0)
zi = chi2(si)
ps.append(si + 0)
zs.append(zi + 0)
if zi < z[-1]:
z[-1] = zi + 0
s[-1] = si + 0
continue
# no shrink
print("WARNING: shouldn't have to shrink, stopping NM")
break
# shrink
s[1:] = s[:1] + d*(s[1:]-s[:1])
# NM uncertainty
P = (s[None,:,:]+s[:,None,:])/2
NM_a0 = chi2(P[0,0])
NM_a = np.array([2*chi2(P[0,i]) - (chi2(P[i,i])+3*chi2(P[0,0]))/2 for i in range(1,3)])
NM_b = np.array([[2*(chi2(P[i,j])+chi2(P[0,0])-chi2(P[0,i])-chi2(P[0,j]))
for i in range(1,3)] for j in range(1,3)])
NM_Q = (s[1:]-s[0]).T
NM_x = np.linalg.lstsq(-NM_b, NM_a, rcond=None)[0]
NM_p = s[0] + NM_Q@NM_x
NM_C = NM_Q@np.linalg.inv(NM_b)@NM_Q.T
show_mu_C('NM Hessian', NM_p, NM_C)
ps = np.array(ps)
zs = np.array([chi2(ppppp) for ppppp in ps])
popt = ps[np.argmin(zs)]
mu, C = bb.estimate(ps, zs, sigma_inner=0.25, sigma_outer=3.0)
show_mu_C('bluebell', mu, C)
def func(t, *p):
global i
i += 1
return lorentz(t, p)
i = 0
# let's find the true optimum ...
ropt, rcov, info, msg, ierr = \
curve_fit(func, t, y, p0=p0, sigma=sigma, absolute_sigma=True,
ftol=1e-10, xtol=1e-10, full_output=True)
# ... then solve to the same precision as the Nelder-Mead solution
xmin = ropt
chi2min = np.sum(info['fvec']**2)
show_mu_C('curve_fit', ropt, rcov)
i = 0
ropt, rcov, info, msg, ierr = \
curve_fit(func, t, y, p0=p0, sigma=sigma, absolute_sigma=True,
full_output=True,
ftol=1e-6, # chi2(popt)-chi2min,
xtol=1e-4) # np.min(np.abs(popt-xmin)))
show_mu_C('curve_fit', ropt, rcov)
import emcee
def lnprob(p):
if np.any(p <= 0):
return -np.inf
else:
return -0.5*chi2(p)
D = 2
W = 10
S = emcee.EnsembleSampler(W, D, lnprob)
pos = 1 + 0.1*np.random.randn(W, D)
while np.any(pos <= 0):
pos[pos <= 0] = 1 + 0.1*np.random.randn(*pos[pos <= 0].shape)
pos, prob, state = S.run_mcmc(pos, 2000)
S.reset()
pos, prob, state = S.run_mcmc(pos, 2000)
show_mu_C('emcee', np.mean(S.flatchain, axis=0), np.cov(S.flatchain.T))
pl.hist2d(*S.flatchain.T, cmap='gray_r', bins=30);
pl.plot(*ps.T, 'o', label=r"$\bm{x}$")
bbplot.cov_ellipse(NM_p, NM_C, fc='none', ec='C0', lw=1.5)
pl.plot([np.nan, np.nan], [np.nan, np.nan], c='C0', ls='-', label='NM')
I = (0.25**2 < zs-np.min(zs)) & (zs-np.min(zs) < 3.0**2)
pp = ps[np.argmin(zs)] + (ps[I]-ps[np.argmin(zs)])/np.sqrt(zs[I]-np.min(zs))[:,None]
pl.plot(*pp.T, 's', label=r"$\bm{x}'$")
bbplot.cov_ellipse(mu, C, fc='none', ec='C1', lw=1.5)
pl.plot([np.nan, np.nan], [np.nan, np.nan], c='C1', ls='-', label='MVBE')
bbplot.cov_ellipse(ropt, rcov, fc='none', ec='C2', lw=1.5)
pl.plot([np.nan, np.nan], [np.nan, np.nan], c='C2', ls='-', label=r"$\texttt{curve\_fit}$")
I = np.abs(S.flatlnprobability.max()-S.flatlnprobability-0.5)<0.2
pl.tricontour(*S.flatchain[I].T, S.flatlnprobability[I],
[np.max(S.flatlnprobability)-0.5],
colors='C3', linestyles='solid');
pl.plot([np.nan, np.nan], [np.nan, np.nan], c='C3', ls='-', label='MCMC')
pl.xlabel(r"$A$")
pl.ylabel(r"$\Gamma$")
pl.axis([0.9, 1.4, 0.7, 1.25])
pl.legend(borderpad=0.2, labelspacing=0.2, handlelength=1.2,
handletextpad=0.4, columnspacing=0.2, loc='upper right', bbox_to_anchor=(1.01,1.01))
pl.savefig('6-lorentzian.pdf')
|
{
"alphanum_fraction": 0.5575569358,
"author": null,
"avg_line_length": 26.6850828729,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "ecc31824b9209d95e43678e442177644863de2a7",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "fb7f4571bcad91702b2ed1363593b0497fd466bc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "warrickball/bluebell",
"max_forks_repo_path": "paper/figures/6-lorentzian.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fb7f4571bcad91702b2ed1363593b0497fd466bc",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "warrickball/bluebell",
"max_issues_repo_path": "paper/figures/6-lorentzian.py",
"max_line_length": 94,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fb7f4571bcad91702b2ed1363593b0497fd466bc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "warrickball/bluebell",
"max_stars_repo_path": "paper/figures/6-lorentzian.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1854,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4830
}
|
# -*- coding: utf-8 -*-
import random
import logging
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from tests.test_base import BaseTest
from mabwiser.mab import MAB, LearningPolicy, NeighborhoodPolicy
from mabwiser.simulator import Simulator
logging.disable(logging.CRITICAL)
class ExampleTest(BaseTest):
def test_popularity(self):
list_of_arms = ['Arm1', 'Arm2']
decisions = ['Arm1', 'Arm1', 'Arm2', 'Arm1']
rewards = [20, 17, 25, 9]
mab = MAB(list_of_arms, LearningPolicy.Popularity())
mab.fit(decisions, rewards)
mab.predict()
self.assertEqual("Arm2", mab.predict())
self.assertDictEqual({'Arm1': 0.38016528925619836, 'Arm2': 0.6198347107438016},
mab.predict_expectations())
def test_random(self):
arm, mab = self.predict(arms=[1, 2],
decisions=[1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1],
rewards=[10, 17, 22, 9, 4, 0, 7, 8, 20, 9, 50, 5, 7, 12, 10],
learning_policy=LearningPolicy.Random(),
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arm, 1)
layout_partial = [1, 2, 1, 2]
revenue_partial = [0, 12, 7, 19]
mab.partial_fit(decisions=layout_partial, rewards=revenue_partial)
mab.add_arm(3)
self.assertTrue(3 in mab.arms)
self.assertTrue(3 in mab._imp.arm_to_expectation.keys())
def test_greedy15(self):
arm, mab = self.predict(arms=[1, 2],
decisions=[1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1],
rewards=[10, 17, 22, 9, 4, 0, 7, 8, 20, 9, 50, 5, 7, 12, 10],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0.15),
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arm, 2)
layout_partial = [1, 2, 1, 2]
revenue_partial = [0, 12, 7, 19]
mab.partial_fit(decisions=layout_partial, rewards=revenue_partial)
mab.add_arm(3)
self.assertTrue(3 in mab.arms)
self.assertTrue(3 in mab._imp.arm_to_expectation.keys())
def test_linucb(self):
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
test_df_revenue = pd.Series([7, 13])
# Scale the data
scaler = StandardScaler()
train = scaler.fit_transform(np.asarray(train_df[['age', 'click_rate', 'subscriber']], dtype='float64'))
test = scaler.transform(np.asarray(test_df, dtype='float64'))
arms, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=train_df['ad'],
rewards=train_df['revenues'],
learning_policy=LearningPolicy.LinUCB(alpha=1.25),
context_history=train,
contexts=test,
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arms, [5, 2])
mab.partial_fit(decisions=arms, rewards=test_df_revenue, contexts=test)
mab.add_arm(6)
self.assertTrue(6 in mab.arms)
self.assertTrue(6 in mab._imp.arm_to_expectation.keys())
def test_softmax(self):
arm, mab = self.predict(arms=[1, 2],
decisions=[1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1],
rewards=[10, 17, 22, 9, 4, 0, 7, 8, 20, 9, 50, 5, 7, 12, 10],
learning_policy=LearningPolicy.Softmax(tau=1),
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arm, 2)
layout_partial = [1, 2, 1, 2]
revenue_partial = [0, 12, 7, 19]
mab.partial_fit(decisions=layout_partial, rewards=revenue_partial)
mab.add_arm(3)
self.assertTrue(3 in mab.arms)
self.assertTrue(3 in mab._imp.arm_to_expectation.keys())
def test_lints(self):
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
test_df_revenue = pd.Series([7, 13])
# Scale the data
scaler = StandardScaler()
train = scaler.fit_transform(np.asarray(train_df[['age', 'click_rate', 'subscriber']], dtype='float64'))
test = scaler.transform(np.asarray(test_df, dtype='float64'))
arms, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=train_df['ad'],
rewards=train_df['revenues'],
learning_policy=LearningPolicy.LinTS(alpha=1.5),
context_history=train,
contexts=test,
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arms, [5, 2])
mab.partial_fit(decisions=arms, rewards=test_df_revenue, contexts=test)
mab.add_arm(6)
self.assertTrue(6 in mab.arms)
self.assertTrue(6 in mab._imp.arm_to_expectation.keys())
def test_ts(self):
dec_to_threshold = {1: 10, 2: 20}
def binarize(dec, value):
return value >= dec_to_threshold[dec]
arm, mab = self.predict(arms=[1, 2],
decisions=[1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1],
rewards=[10, 17, 22, 9, 4, 0, 7, 8, 20, 9, 50, 5, 7, 12, 10],
learning_policy=LearningPolicy.ThompsonSampling(binarizer=binarize),
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arm, 1)
layout_partial = [1, 2, 1, 2]
revenue_partial = [0, 12, 7, 19]
mab.partial_fit(decisions=layout_partial, rewards=revenue_partial)
# Updating of the model with new arm
def binary_func2(decision, reward):
if decision == 3:
return 1 if reward > 15 else 0
else:
return 1 if reward > 10 else 0
mab.add_arm(3, binary_func2)
self.assertTrue(3 in mab.arms)
self.assertTrue(3 in mab._imp.arm_to_expectation.keys())
def test_ts_binary(self):
arm, mab = self.predict(arms=[1, 2],
decisions=[1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1],
rewards=[1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1],
learning_policy=LearningPolicy.ThompsonSampling(),
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arm, 1)
layout_partial = [1, 2, 1, 2]
revenue_partial = [0, 1, 0, 1]
mab.partial_fit(decisions=layout_partial, rewards=revenue_partial)
mab.add_arm(3)
self.assertTrue(3 in mab.arms)
self.assertTrue(3 in mab._imp.arm_to_expectation.keys())
def test_ucb1(self):
arm, mab = self.predict(arms=[1, 2],
decisions=[1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1],
rewards=[10, 17, 22, 9, 4, 0, 7, 8, 20, 9, 50, 5, 7, 12, 10],
learning_policy=LearningPolicy.UCB1(alpha=1.25),
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arm, 2)
layout_partial = [1, 2, 1, 2]
revenue_partial = [0, 12, 7, 19]
mab.partial_fit(decisions=layout_partial, rewards=revenue_partial)
mab.add_arm(3)
self.assertTrue(3 in mab.arms)
self.assertTrue(3 in mab._imp.arm_to_expectation.keys())
def test_ts_series(self):
df = pd.DataFrame({'layouts': [1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1],
'revenues': [10, 17, 22, 9, 4, 0, 7, 8, 20, 9, 50, 5, 7, 12, 10]})
arm, mab = self.predict(arms=[1, 2],
decisions=df['layouts'],
rewards=df['revenues'],
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0.15),
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arm, 2)
def test_ts_numpy(self):
arm, mab = self.predict(arms=[1, 2],
decisions=np.array([1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1]),
rewards=np.array([10, 17, 22, 9, 4, 0, 7, 8, 20, 9, 50, 5, 7, 12, 10]),
learning_policy=LearningPolicy.EpsilonGreedy(epsilon=0.15),
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arm, 2)
def test_approximate(self):
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
test_df_revenue = pd.Series([7, 13])
# Scale the data
scaler = StandardScaler()
train = scaler.fit_transform(np.asarray(train_df[['age', 'click_rate', 'subscriber']], dtype='float64'))
test = scaler.transform(np.asarray(test_df, dtype='float64'))
arms, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=train_df['ad'],
rewards=train_df['revenues'],
learning_policy=LearningPolicy.UCB1(alpha=1.25),
neighborhood_policy=NeighborhoodPolicy.LSHNearest(n_tables=5, n_dimensions=5),
context_history=train,
contexts=test,
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arms, [1, 4])
mab.partial_fit(decisions=arms, rewards=test_df_revenue, contexts=test)
mab.add_arm(6)
self.assertTrue(6 in mab.arms)
self.assertTrue(6 in mab._imp.arm_to_expectation.keys())
def test_radius(self):
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
test_df_revenue = pd.Series([7, 13])
# Scale the data
scaler = StandardScaler()
train = scaler.fit_transform(np.asarray(train_df[['age', 'click_rate', 'subscriber']], dtype='float64'))
test = scaler.transform(np.asarray(test_df, dtype='float64'))
arms, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=train_df['ad'],
rewards=train_df['revenues'],
learning_policy=LearningPolicy.UCB1(alpha=1.25),
neighborhood_policy=NeighborhoodPolicy.Radius(radius=5),
context_history=train,
contexts=test,
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arms, [4, 4])
mab.partial_fit(decisions=arms, rewards=test_df_revenue, contexts=test)
mab.add_arm(6)
self.assertTrue(6 in mab.arms)
self.assertTrue(6 in mab._imp.arm_to_expectation.keys())
def test_nearest(self):
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
test_df_revenue = pd.Series([7, 13])
# Scale the data
scaler = StandardScaler()
train = scaler.fit_transform(np.asarray(train_df[['age', 'click_rate', 'subscriber']], dtype='float64'))
test = scaler.transform(np.asarray(test_df, dtype='float64'))
arms, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=train_df['ad'],
rewards=train_df['revenues'],
learning_policy=LearningPolicy.UCB1(alpha=1.25),
neighborhood_policy=NeighborhoodPolicy.KNearest(k=5),
context_history=train,
contexts=test,
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arms, [5, 1])
mab.partial_fit(decisions=arms, rewards=test_df_revenue, contexts=test)
mab.add_arm(6)
self.assertTrue(6 in mab.arms)
self.assertTrue(6 in mab._imp.arm_to_expectation.keys())
def test_linucb_radius(self):
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
# Scale the data
scaler = StandardScaler()
train = scaler.fit_transform(np.asarray(train_df[['age', 'click_rate', 'subscriber']], dtype='float64'))
test = scaler.transform(np.asarray(test_df, dtype='float64'))
arms, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=train_df['ad'],
rewards=train_df['revenues'],
learning_policy=LearningPolicy.LinUCB(alpha=1.25),
neighborhood_policy=NeighborhoodPolicy.Radius(radius=1),
context_history=train,
contexts=test,
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arms, [1, 2])
def test_linucb_knearest(self):
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
# Scale the data
scaler = StandardScaler()
train = scaler.fit_transform(np.asarray(train_df[['age', 'click_rate', 'subscriber']], dtype='float64'))
test = scaler.transform(np.asarray(test_df, dtype='float64'))
arms, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=train_df['ad'],
rewards=train_df['revenues'],
learning_policy=LearningPolicy.LinUCB(alpha=1.25),
neighborhood_policy=NeighborhoodPolicy.KNearest(k=4),
context_history=train,
contexts=test,
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arms, [1, 2])
def test_lints_radius(self):
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
# Scale the data
scaler = StandardScaler()
train = scaler.fit_transform(np.asarray(train_df[['age', 'click_rate', 'subscriber']], dtype='float64'))
test = scaler.transform(np.asarray(test_df, dtype='float64'))
arms, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=train_df['ad'],
rewards=train_df['revenues'],
learning_policy=LearningPolicy.LinTS(alpha=0.5),
neighborhood_policy=NeighborhoodPolicy.Radius(radius=1),
context_history=train,
contexts=test,
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arms, [1, 2])
def test_lints_knearest(self):
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
# Scale the data
scaler = StandardScaler()
train = scaler.fit_transform(np.asarray(train_df[['age', 'click_rate', 'subscriber']], dtype='float64'))
test = scaler.transform(np.asarray(test_df, dtype='float64'))
arms, mab = self.predict(arms=[1, 2, 3, 4, 5],
decisions=train_df['ad'],
rewards=train_df['revenues'],
learning_policy=LearningPolicy.LinTS(alpha=1),
neighborhood_policy=NeighborhoodPolicy.KNearest(k=4),
context_history=train,
contexts=test,
seed=123456,
num_run=1,
is_predict=True)
self.assertEqual(arms, [1, 2])
def test_simulator_contextual(self):
size = 100
decisions = [random.randint(0, 2) for _ in range(size)]
rewards = [random.randint(0, 1000) for _ in range(size)]
contexts = [[random.random() for _ in range(50)] for _ in range(size)]
def binarize(decision, reward):
if decision == 0:
return reward <= 50
else:
return reward >= 220
n_jobs = 1
contextual_mabs = [('Random', MAB([0, 1], LearningPolicy.Random(), NeighborhoodPolicy.Radius(10),
n_jobs=n_jobs)),
('UCB1', MAB([0, 1], LearningPolicy.UCB1(1), NeighborhoodPolicy.Radius(10), n_jobs=n_jobs)),
('ThompsonSampling', MAB([0, 1], LearningPolicy.ThompsonSampling(binarize),
NeighborhoodPolicy.Radius(10), n_jobs=n_jobs)),
('EpsilonGreedy', MAB([0, 1], LearningPolicy.EpsilonGreedy(epsilon=.15),
NeighborhoodPolicy.Radius(10), n_jobs=n_jobs)),
('Softmax', MAB([0, 1], LearningPolicy.Softmax(), NeighborhoodPolicy.Radius(10),
n_jobs=n_jobs))]
sim = Simulator(contextual_mabs, decisions, rewards, contexts,
scaler=StandardScaler(), test_size=0.5, is_ordered=False, batch_size=0, seed=123456)
sim.run()
self.assertTrue(sim.bandit_to_confusion_matrices)
self.assertTrue(sim.bandit_to_predictions)
def test_simulator_context_free(self):
size = 100
decisions = [random.randint(0, 2) for _ in range(size)]
rewards = [random.randint(0, 1000) for _ in range(size)]
def binarize(decision, reward):
if decision == 0:
return reward <= 50
else:
return reward >= 220
n_jobs = 1
context_free_mabs = [('Random', MAB([0, 1], LearningPolicy.Random(), n_jobs=n_jobs)),
('UCB1', MAB([0, 1], LearningPolicy.UCB1(1), n_jobs=n_jobs)),
('ThompsonSampling', MAB([0, 1], LearningPolicy.ThompsonSampling(binarize),
n_jobs=n_jobs)),
('EpsilonGreedy', MAB([0, 1], LearningPolicy.EpsilonGreedy(epsilon=.15), n_jobs=n_jobs)),
('Softmax', MAB([0, 1], LearningPolicy.Softmax(), n_jobs=n_jobs))]
sim = Simulator(context_free_mabs, decisions, rewards, contexts=None,
scaler=None, test_size=0.5, is_ordered=False, batch_size=1, seed=123456)
sim.run()
self.assertTrue(sim.bandit_to_confusion_matrices)
self.assertTrue(sim.bandit_to_predictions)
def test_simulator_mixed(self):
size = 100
decisions = [random.randint(0, 2) for _ in range(size)]
rewards = [random.randint(0, 1000) for _ in range(size)]
contexts = [[random.random() for _ in range(50)] for _ in range(size)]
n_jobs = 1
mixed = [('RandomRadius', MAB([0, 1], LearningPolicy.Random(), NeighborhoodPolicy.Radius(10), n_jobs=n_jobs)),
('Random', MAB([0, 1], LearningPolicy.Random(), n_jobs=n_jobs))]
sim = Simulator(mixed, decisions, rewards, contexts,
scaler=StandardScaler(), test_size=0.5, is_ordered=False, batch_size=0, seed=123456)
sim.run()
self.assertTrue(sim.bandit_to_confusion_matrices)
self.assertTrue(sim.bandit_to_predictions)
def test_simulator_hyper_parameter(self):
size = 100
decisions = [random.randint(0, 2) for _ in range(size)]
rewards = [random.randint(0, 1000) for _ in range(size)]
contexts = [[random.random() for _ in range(50)] for _ in range(size)]
n_jobs = 1
hyper_parameter_tuning = []
for radius in range(6, 10):
hyper_parameter_tuning.append(('Radius' + str(radius),
MAB([0, 1], LearningPolicy.UCB1(1), NeighborhoodPolicy.Radius(radius),
n_jobs=n_jobs)))
sim = Simulator(hyper_parameter_tuning, decisions, rewards, contexts,
scaler=StandardScaler(), test_size=0.5, is_ordered=False, batch_size=0, seed=123456,
is_quick=True)
sim.run()
self.assertTrue(sim.bandit_to_confusion_matrices)
self.assertTrue(sim.bandit_to_predictions)
def test_treebandit(self):
# Arms
ads = [1, 2, 3, 4, 5]
# Historical data of ad decisions with corresponding revenues and context information
train_df = pd.DataFrame({'ad': [1, 1, 1, 2, 4, 5, 3, 3, 2, 1, 4, 5, 3, 2, 5],
'revenues': [10, 17, 22, 9, 4, 20, 7, 8, 20, 9, 50, 5, 7, 12, 10],
'age': [22, 27, 39, 48, 21, 20, 19, 37, 52, 26, 18, 42, 55, 57, 38],
'click_rate': [0.2, 0.6, 0.99, 0.68, 0.15, 0.23, 0.75, 0.17,
0.33, 0.65, 0.56, 0.22, 0.19, 0.11, 0.83],
'subscriber': [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]}
)
# Test data to for new prediction
test_df = pd.DataFrame({'age': [37, 52], 'click_rate': [0.5, 0.6], 'subscriber': [0, 1]})
test_df_revenue = pd.Series([7, 13])
# Scale the training and test data
scaler = StandardScaler()
train = scaler.fit_transform(train_df[['age', 'click_rate', 'subscriber']].values.astype('float64'))
test = scaler.transform(test_df.values.astype('float64'))
# TreeBandit contextual policy with DecisionTreeClassifier's default tree parameters
# and ucb1 learning with alpha of 1.25
treebandit = MAB(arms=ads,
learning_policy=LearningPolicy.UCB1(alpha=1.25),
neighborhood_policy=NeighborhoodPolicy.TreeBandit())
# Learn from previous ads shown and revenues generated
treebandit.fit(decisions=train_df['ad'], rewards=train_df['revenues'], contexts=train)
# Predict the next best ad to show
prediction = treebandit.predict(test)
# Expectation of each ad based on learning from past ad revenues
expectations = treebandit.predict_expectations(test)
# Results
# print("TreeBandit: ", prediction, " ", expectations)
assert (prediction == [4, 4])
# Online update of model
treebandit.partial_fit(decisions=prediction, rewards=test_df_revenue, contexts=test)
# Updating of the model with new arm
treebandit.add_arm(6)
|
{
"alphanum_fraction": 0.4699289503,
"author": null,
"avg_line_length": 46.6236391913,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "86150640ba5d0b649e014a11b803a3e6b56e3935",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "805326a99213f94a6e813530cebf0c8a0f96a2d1",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "jaywonchung/mabwiser",
"max_forks_repo_path": "tests/test_examples.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "805326a99213f94a6e813530cebf0c8a0f96a2d1",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "jaywonchung/mabwiser",
"max_issues_repo_path": "tests/test_examples.py",
"max_line_length": 119,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "805326a99213f94a6e813530cebf0c8a0f96a2d1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jaywonchung/mabwiser",
"max_stars_repo_path": "tests/test_examples.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8628,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 29979
}
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UMB-CS114-2015F: Introduction to Programming in Java
% Copyright 2015 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/UMB-CS114-2015F
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def \topDirectory {../..}
\def \texDirectory {\topDirectory/src/main/tex}
\documentclass[10pt, compress]{beamer}
\usepackage{\texDirectory/template/style/directives}
\input{\texDirectory/template/config}
\usepackage{\texDirectory/template/style/beamerthemeUmassLecture}
\doc{number}{9}
%\setbeamertemplate{footline}[text line]{}
\begin{document}
\prepareCover
\section{Course Administration}
\begin{slide}
\begin{itemize}
\item[] Midterm exam to be held Ocober 21, 2015 at 5:30 PM.
\end{itemize}
\end{slide}
\begin{slide}
\begin{block}{Overview}
\begin{itemize}
\item[] Branches
\item[] One-Dimensional Arrays
\end{itemize}
\end{block}
\end{slide}
\section{Branches}
\begin{slide}
\begin{block}{Objective}
Write a program \texttt{FindP.java} that takes a String as command-line argument and checks if it contains the letter \texttt{p} (case insensitive). Do not use method \texttt{String.contains()}.
\end{block}
\end{slide}
\begin{slide}
\begin{block}{FindP.java (v1)}
\begin{minted}[fontsize=\small,tabsize=8, linenos, firstnumber=1]{java}
public class FindP {
public static void main(String[] args) {
String phrase = args[0].toLowerCase();
char letter = 'p';
boolean found = false;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == letter)
found = true;
}
if (found)
System.out.println("Found some '" + letter "'.");
else
System.out.println("No '"+ letter +"' found.");
}
}
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Result}
\begin{minted}[fontsize=\small,tabsize=8]{text}
$ java FindP Hello
No 'p' Found.
$ java FindP Pejman
Found Some 'p'.
\end{minted}
\end{block}
\begin{block}{Question}
How is the for loop executed?
\end{block}
\end{slide}
\begin{slide}
\begin{block}{FindP.java (v2)}
\begin{minted}[fontsize=\small,tabsize=8, linenos, firstnumber=1]{java}
public class FindP {
public static void main(String[] args) {
String phrase = args[0].toLowerCase();
char letter = 'p';
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == letter)
System.out.print(letter);
else
System.out.print("-");
}
}
}
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Result}
\begin{minted}[fontsize=\small,tabsize=8]{text}
$ java FindP Happy
--pp-
$ java FindP Pejman
p-----
\end{minted}
\end{block}
\begin{block}{Problem Statement}
There are as many loop iterations as \texttt{phrase.length()}. Are they really required?
\end{block}
\end{slide}
\begin{slide}
\begin{block}{\texttt{break} Statement}
\texttt{break} statement immediately terminates the loop.
Control flow will return to the statement after the loop.
\end{block}
\end{slide}
\begin{slide}
\begin{block}{FindP.java (v3)}
\begin{minted}[fontsize=\small,tabsize=8, linenos, firstnumber=3]{java}
String phrase = args[0].toLowerCase();
char letter = 'p';
boolean found = false;
for (int i = 0; i < phrase.length(); i++)
if (phrase.charAt(i) == letter) {
found = true;
break;
}
if (found)
System.out.println("Found some '" + letter "'.");
else
System.out.println("No '"+ letter +"' found.");
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{FindP.java (v4)}
\begin{minted}[fontsize=\small,tabsize=8, linenos, firstnumber=1]{java}
String phrase = args[0].toLowerCase();
char letter = 'p';
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == letter) {
System.out.print(letter);
break;
}
else
System.out.print("-");
}
\end{minted}
\end{block}
\begin{block}{Result}
\begin{minted}[fontsize=\small,tabsize=8]{text}
$ java FindP Happy
--p
$ java FindP Pejman
p
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Note}
Unconditional branches can be avoided to enhance code readability.
\end{block}
\begin{block}{FindP.java (v5)}
\begin{minted}[fontsize=\small, tabsize=8, linenos, firstnumber=1]{java}
String phrase = args[0].toLowerCase();
char letter = 'p';
boolean found = false;
int i = 0;
while (!found && i < phrase.length())
if (phrase.charAt(i++) == letter)
found = true;
System.out.println(found ? "Found" : "Not Found");
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{\texttt{continue} Statement}
The \texttt{continue} statement skips \emph{current iteration} of the loop.
Control flow will immediately skip to the end the loop's body.
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Objective}
Write a program \texttt{CountP.java} that takes a String as command-line argument and prints number of 'p' letters it contains.
Comparison is case insensitive.
\end{block}
\end{slide}
\begin{slide}
\begin{block}{CountP.java (v1)}
\begin{minted}[fontsize=\small,tabsize=8, linenos, firstnumber=1]{java}
public class CountP {
public static void main(String[] args) {
String phrase = args[0].toLowerCase();
char letter = 'p';
int counter = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) != letter)
continue;
counter++;
}
System.out.printf("Found %d 'P'(s)\n", counter);
}
}
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Note}
Unconditional branches can be avoided to enhance code readability.
\end{block}
\begin{block}{CountP.java (v2)}
\begin{minted}[fontsize=\small,tabsize=8, linenos, firstnumber=3]{java}
String phrase = args[0].toLowerCase();
char letter = 'p';
int counter = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == letter)
counter++;
}
System.out.printf("Found %d 'P'(s)\n", counter);
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{\texttt{return} statement}
Exits from the current method.
Control flow returns to where the method was invoked.
\texttt{return} statement will be discussed later.
\end{block}
\end{slide}
\section{One-Dimensional Arrays}
\begin{slide}
\begin{block}{Objective}
Write a program \texttt{RandomCard.java} that randomly selects a card from a standard 52-card deck and prints its name.
\end{block}
\end{slide}
\begin{slide}
\begin{block}{\texttt{RandomCard.java} (v1)}
\begin{minted}[fontsize=\small,tabsize=8, linenos, firstnumber=1]{java}
public class RandomCard {
public static void main(String[] args) {
int numCard = 52;
int randNum = Math.floor(Math.random() * numCard);
switch (randNum) {
case 0: cardName = "Ace of Spades"; break;
case 1: cardName = "Two of Spades"; break;
// Seriously?
\end{minted}
\begin{minted}[fontsize=\small,tabsize=8, linenos, firstnumber=57]{java}
case 50: cardName = "Queen of Hearts"; break;
case 51: cardName = "King of Hearts"; break;
}
}
}
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Advice from a Fellow Programmer}
Never repeat yourself!
\end{block}
\begin{block}{Problem Statment}
Simple program ends up in 60 lines of code.
\end{block}
\begin{block}{Proposed Solution}
Separate suits and ranks.
\end{block}
\end{slide}
\begin{slide}
\begin{block}{\texttt{RandomCard.java} (v2) (Page 1)}
\begin{minted}[fontsize=\small, tabsize=8, linenos, firstnumber=1]{java}
public class RandomCard {
public static void main(String[] args) {
int numCard = 52;
int randNum = Math.floor(Math.random() * numCard);
suitNum = randNum / 13;
switch (suitNum) {
case 0: suitName = "Spades"; break;
case 1: suitName = "Diamonds"; break;
case 2: suidName = "Clubs"; break;
case 3: suitName = "Hearts"; break;
}
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{\texttt{RandomCard.java} (v2) (Page 2)}
\begin{minted}[fontsize=\small, tabsize=8, linenos, firstnumber=12]{java}
switch cardNum = numCard % 13;
switch (cardNum) {
case 0: cardName = "Ace"; break;
case 1: cardName = "Two"; break;
// Not cool!
\end{minted}
\begin{minted}[fontsize=\small, tabsize=8, linenos, firstnumber=26]{java}
case 11: cardName = "Queen"; break;
case 12: cardName = "King"; break;
}
System.out.println(cardName + " of " + suitName);
}
}
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Problem Statement}
\begin{itemize}
\item[] Access to names of values and suits are limited.
\item[] Same code should be executed every time name of card is needed.
\item[] Solution is not expandable.
\end{itemize}
\end{block}
\begin{block}{Clues}
\begin{itemize}
\item[] All cases assign string literals to one single variable.
\item[] Name of $13^{th}$ card numbers for every suit is ``King".
\end{itemize}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Proposed Solution}
Define an ordered collection of card names and get name of a card by calling its position in collection.
\begin{minted}[fontsize=\small,tabsize=8]{java}
String[] SuitNames = {
"Spades", "Diamonds", "Clubs", "Hearts"
};
String[] CardNames = {
"Ace", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Soldier", "Queen", "King"
};
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Definition}
\begin{itemize}
\item[] Array is a data structure that holds a \texttt{fixed} number of elements of a \texttt{single} type.
\item[] Each array element is identified by its \texttt{numerical index}.
\item[] An array is stored based on position of its \texttt{first} element.
\item[] First element of an array has index 0.
\end{itemize}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Sample Usage}
\begin{minted}[fontsize=\small,tabsize=8]{java}
int[] primes;
primes = new int[4];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
for (int i = 0; i < 4; i++)
System.out.printf("Prime %d is %d\n", i + 1, primes[i]);
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{\texttt{RandomCard.java} (v3)}
\begin{minted}[fontsize=\small, tabsize=8, linenos, firstnumber=5]{java}
String[] SuitNames = {
"Spades", "Diamonds", "Clubs", "Hearts"
};
String[] CardNames = {
"Ace", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Soldier", "Queen", "King"
};
suitNum = randNum / 13;
cardNum = randNum % 13;
suitName = suitNames[suitNum];
cardName = cardNames[cardNum];
System.out.println(cardName + " of " + suitName);
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Advantages}
\begin{itemize}
\item[] Data is more organized.
\item[] Code reuse is now possible.
\item[] Solution is expandable.
\end{itemize}
\end{block}
\begin{block}{Disadvantages}
\begin{itemize}
\item[] Once declared, size of array is fixed.
\item[] Insertion and deletion are not possible.
\end{itemize}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Objective}
Write a program \texttt{PrimeNumber.java} that prints all first 1000 prime numbers.
\end{block}
\end{slide}
\begin{slide}
\begin{block}{\texttt{PrimeNumber.java} (v1)}
\begin{minted}[fontsize=\small,tabsize=8, linenos, firstnumber=3]{java}
int counter = 0;
int number = 2;
boolean definitelyNotPrime;
while (counter < 1000) {
definitelyNotPrime = false;
for (int i = 2; i < number / 2; i++)
if (number % i == 0) {
definitelyNotPrime = true;
break;
}
if (!definitelyNotPrime)
System.out.printf("%4d: %d\n", ++counter, number);
number++;
}
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Problem Statement}
\begin{itemize}
\item[] To check if number $N$ is prime, it suffices to check whether it is devisible by at least one prime number less than or equal to $\frac{N}{2}$.
\item[] It is not necessary to check all numbers less than $\frac{N}{2}$.
\item[] What if we are asked to print $1^{st}$, $3^{rd}$, $5^{th}$, ... prime numbers, after printing all first 1000 prime numbers?
\end{itemize}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Objective}
Write a program \texttt{PrimeNumber.java} that first prints all first 1000 prime numbers then prints $500^{th}$ prime number.
\end{block}
\end{slide}
\begin{slide}
\begin{block}{\texttt{PrimeNumber.java} (v2)}
\begin{minted}[fontsize=\small, tabsize=8, linenos, firstnumber=3]{java}
int[] primeNumbers = new int[1000];
int counter = 0;
int number = 2;
boolean definitelyNotPrime;
while (counter < primeNumbers.length) {
definitelyNotPrime = false;
for (int i = 0; i < counter && !definitelyNotPrime; i++)
if (number % primeNumbers[i] == 0)
definitelyNotPrime = true;
if (!definitelyNotPrime) {
primeNumbers[counter++] = number;
System.out.printf("%4d: %d\n", counter, number);
}
number++;
}
System.out.printf("%4d: %d\n", 500, primeNumbers[499]);
\end{minted}
\end{block}
\end{slide}
\begin{slide}
\begin{block}{Remember}
\begin{itemize}
\item[] Array is the most useful data structure that significantly organizes your code.
\item[] Arrays hold a \texttt{fixed} number of elements of a \texttt{single} type.
\end{itemize}
\end{block}
\end{slide}
\plain{}{Keep Calm\\and\\Practice}
\end{document}
|
{
"alphanum_fraction": 0.6187788256,
"author": null,
"avg_line_length": 29.2293762575,
"converted": null,
"ext": "tex",
"file": null,
"hexsha": "d6eb10d395d094e04b5cdf77f4c723dc9196475b",
"include": null,
"lang": "TeX",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2cb102460bcbfbfff9f1a6b20791d777ef2af159",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ghorbanzade/UMB-CS114-2015F",
"max_forks_repo_path": "src/main/tex/slides/ls09.tex",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2cb102460bcbfbfff9f1a6b20791d777ef2af159",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ghorbanzade/UMB-CS114-2015F",
"max_issues_repo_path": "src/main/tex/slides/ls09.tex",
"max_line_length": 196,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2cb102460bcbfbfff9f1a6b20791d777ef2af159",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ghorbanzade/UMB-CS114-2015F",
"max_stars_repo_path": "src/main/tex/slides/ls09.tex",
"max_stars_repo_stars_event_max_datetime": "2020-05-03T18:41:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-03T18:41:41.000Z",
"num_tokens": 4434,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 14527
}
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Correctness proof for constant propagation (processor-dependent part). *)
Require Import Coqlib.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import Globalenvs.
Require Import Events.
Require Import Op.
Require Import Registers.
Require Import RTL.
Require Import ConstpropOp.
Require Import Constprop.
(** * Correctness of the static analysis *)
Section ANALYSIS.
Variable ge: genv.
Variable sp: val.
(** We first show that the dataflow analysis is correct with respect
to the dynamic semantics: the approximations (sets of values)
of a register at a program point predicted by the static analysis
are a superset of the values actually encountered during concrete
executions. We formalize this correspondence between run-time values and
compile-time approximations by the following predicate. *)
Definition val_match_approx (a: approx) (v: val) : Prop :=
match a with
| Unknown => True
| I p => v = Vint p
| F p => v = Vfloat p
| G symb ofs => v = symbol_address ge symb ofs
| S ofs => v = Val.add sp (Vint ofs)
| _ => False
end.
Inductive val_list_match_approx: list approx -> list val -> Prop :=
| vlma_nil:
val_list_match_approx nil nil
| vlma_cons:
forall a al v vl,
val_match_approx a v ->
val_list_match_approx al vl ->
val_list_match_approx (a :: al) (v :: vl).
Ltac SimplVMA :=
match goal with
| H: (val_match_approx (I _) ?v) |- _ =>
simpl in H; (try subst v); SimplVMA
| H: (val_match_approx (F _) ?v) |- _ =>
simpl in H; (try subst v); SimplVMA
| H: (val_match_approx (G _ _) ?v) |- _ =>
simpl in H; (try subst v); SimplVMA
| H: (val_match_approx (S _) ?v) |- _ =>
simpl in H; (try subst v); SimplVMA
| _ =>
idtac
end.
Ltac InvVLMA :=
match goal with
| H: (val_list_match_approx nil ?vl) |- _ =>
inv H
| H: (val_list_match_approx (?a :: ?al) ?vl) |- _ =>
inv H; SimplVMA; InvVLMA
| _ =>
idtac
end.
(** We then show that [eval_static_operation] is a correct abstract
interpretations of [eval_operation]: if the concrete arguments match
the given approximations, the concrete results match the
approximations returned by [eval_static_operation]. *)
Lemma eval_static_condition_correct:
forall cond al vl m b,
val_list_match_approx al vl ->
eval_static_condition cond al = Some b ->
eval_condition cond vl m = Some b.
Proof.
intros until b.
unfold eval_static_condition.
case (eval_static_condition_match cond al); intros;
InvVLMA; simpl; congruence.
Qed.
Remark shift_symbol_address:
forall symb ofs n,
symbol_address ge symb (Int.add ofs n) = Val.add (symbol_address ge symb ofs) (Vint n).
Proof.
unfold symbol_address; intros. destruct (Genv.find_symbol ge symb); auto.
Qed.
Lemma eval_static_addressing_correct:
forall addr al vl v,
val_list_match_approx al vl ->
eval_addressing ge sp addr vl = Some v ->
val_match_approx (eval_static_addressing addr al) v.
Proof.
intros until v. unfold eval_static_addressing.
case (eval_static_addressing_match addr al); intros;
InvVLMA; simpl in *; FuncInv; try subst v; auto.
rewrite shift_symbol_address; auto.
rewrite Val.add_assoc. auto.
repeat rewrite shift_symbol_address. auto.
fold (Val.add (Vint n1) (symbol_address ge id ofs)).
repeat rewrite shift_symbol_address. repeat rewrite Val.add_assoc. rewrite Val.add_permut. auto.
repeat rewrite Val.add_assoc. decEq; simpl. rewrite Int.add_assoc. auto.
fold (Val.add (Vint n1) (Val.add sp (Vint ofs))).
rewrite Val.add_assoc. rewrite Val.add_permut. rewrite Val.add_assoc.
simpl. rewrite Int.add_assoc; auto.
rewrite shift_symbol_address. auto.
rewrite Val.add_assoc. auto.
rewrite shift_symbol_address. auto.
rewrite shift_symbol_address. rewrite Int.mul_commut; auto.
Qed.
Lemma eval_static_operation_correct:
forall op al vl m v,
val_list_match_approx al vl ->
eval_operation ge sp op vl m = Some v ->
val_match_approx (eval_static_operation op al) v.
Proof.
intros until v.
unfold eval_static_operation.
case (eval_static_operation_match op al); intros;
InvVLMA; simpl in *; FuncInv; try subst v; auto.
destruct (propagate_float_constants tt); simpl; auto.
rewrite Int.sub_add_opp. rewrite shift_symbol_address. rewrite Val.sub_add_opp. auto.
destruct (Int.eq n2 Int.zero). inv H0.
destruct (Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone); inv H0; simpl; auto.
destruct (Int.eq n2 Int.zero); inv H0; simpl; auto.
destruct (Int.eq n2 Int.zero). inv H0.
destruct (Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone); inv H0; simpl; auto.
destruct (Int.eq n2 Int.zero); inv H0; simpl; auto.
destruct (Int.ltu n2 Int.iwordsize); simpl; auto.
destruct (Int.ltu n Int.iwordsize); simpl; auto.
destruct (Int.ltu n2 Int.iwordsize); simpl; auto.
destruct (Int.ltu n Int.iwordsize); simpl; auto.
destruct (Int.ltu n (Int.repr 31)); inv H0. simpl; auto.
destruct (Int.ltu n2 Int.iwordsize); simpl; auto.
destruct (Int.ltu n Int.iwordsize); simpl; auto.
destruct (Int.ltu n Int.iwordsize); simpl; auto.
eapply eval_static_addressing_correct; eauto.
unfold eval_static_intoffloat.
destruct (Float.intoffloat n1) eqn:?; simpl in H0; inv H0.
simpl; auto.
destruct (propagate_float_constants tt); simpl; auto.
unfold eval_static_condition_val. destruct (eval_static_condition c vl0) as [b|] eqn:?.
rewrite (eval_static_condition_correct _ _ _ m _ H Heqo).
destruct b; simpl; auto.
simpl; auto.
Qed.
(** * Correctness of strength reduction *)
(** We now show that strength reduction over operators and addressing
modes preserve semantics: the strength-reduced operations and
addressings evaluate to the same values as the original ones if the
actual arguments match the static approximations used for strength
reduction. *)
Section STRENGTH_REDUCTION.
Variable app: D.t.
Variable rs: regset.
Variable m: mem.
Hypothesis MATCH: forall r, val_match_approx (approx_reg app r) rs#r.
Ltac InvApproxRegs :=
match goal with
| [ H: _ :: _ = _ :: _ |- _ ] =>
injection H; clear H; intros; InvApproxRegs
| [ H: ?v = approx_reg app ?r |- _ ] =>
generalize (MATCH r); rewrite <- H; clear H; intro; InvApproxRegs
| _ => idtac
end.
Lemma cond_strength_reduction_correct:
forall cond args vl,
vl = approx_regs app args ->
let (cond', args') := cond_strength_reduction cond args vl in
eval_condition cond' rs##args' m = eval_condition cond rs##args m.
Proof.
intros until vl. unfold cond_strength_reduction.
case (cond_strength_reduction_match cond args vl); simpl; intros; InvApproxRegs; SimplVMA.
rewrite H0. apply Val.swap_cmp_bool.
rewrite H. auto.
rewrite H0. apply Val.swap_cmpu_bool.
rewrite H. auto.
auto.
Qed.
Lemma addr_strength_reduction_correct:
forall addr args vl,
vl = approx_regs app args ->
let (addr', args') := addr_strength_reduction addr args vl in
eval_addressing ge sp addr' rs##args' = eval_addressing ge sp addr rs##args.
Proof.
intros until vl. unfold addr_strength_reduction.
destruct (addr_strength_reduction_match addr args vl); simpl; intros; InvApproxRegs; SimplVMA.
rewrite shift_symbol_address; congruence.
rewrite H. rewrite Val.add_assoc; auto.
rewrite H; rewrite H0. repeat rewrite shift_symbol_address. auto.
rewrite H; rewrite H0. rewrite Int.add_assoc. rewrite Int.add_permut. repeat rewrite shift_symbol_address.
rewrite Val.add_assoc. rewrite Val.add_permut. auto.
rewrite H; rewrite H0. repeat rewrite Val.add_assoc. rewrite Int.add_assoc. auto.
rewrite H; rewrite H0. repeat rewrite Val.add_assoc. rewrite Val.add_permut.
rewrite Int.add_assoc. auto.
rewrite H0. rewrite shift_symbol_address. repeat rewrite Val.add_assoc.
decEq; decEq. apply Val.add_commut.
rewrite H. rewrite shift_symbol_address. repeat rewrite Val.add_assoc.
rewrite (Val.add_permut (rs#r1)). decEq; decEq. apply Val.add_commut.
rewrite H0. rewrite Val.add_assoc. rewrite Val.add_permut. auto.
rewrite H. rewrite Val.add_assoc. auto.
rewrite H; rewrite H0. rewrite Int.add_assoc. repeat rewrite shift_symbol_address. auto.
rewrite H0. rewrite shift_symbol_address. rewrite Val.add_assoc. decEq; decEq. apply Val.add_commut.
rewrite H. auto.
rewrite H. rewrite shift_symbol_address. auto.
rewrite H. rewrite shift_symbol_address. rewrite Int.mul_commut; auto.
auto.
Qed.
Lemma make_addimm_correct:
forall n r,
let (op, args) := make_addimm n r in
exists v, eval_operation ge sp op rs##args m = Some v /\ Val.lessdef (Val.add rs#r (Vint n)) v.
Proof.
intros. unfold make_addimm.
predSpec Int.eq Int.eq_spec n Int.zero; intros.
subst. exists (rs#r); split; auto. destruct (rs#r); simpl; auto; rewrite Int.add_zero; auto.
exists (Val.add rs#r (Vint n)); auto.
Qed.
Lemma make_shlimm_correct:
forall n r1,
let (op, args) := make_shlimm n r1 in
exists v, eval_operation ge sp op rs##args m = Some v /\ Val.lessdef (Val.shl rs#r1 (Vint n)) v.
Proof.
intros; unfold make_shlimm.
predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.
exists (rs#r1); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.shl_zero. auto.
econstructor; split. simpl. eauto. auto.
Qed.
Lemma make_shrimm_correct:
forall n r1,
let (op, args) := make_shrimm n r1 in
exists v, eval_operation ge sp op rs##args m = Some v /\ Val.lessdef (Val.shr rs#r1 (Vint n)) v.
Proof.
intros; unfold make_shrimm.
predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.
exists (rs#r1); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.shr_zero. auto.
econstructor; split; eauto. simpl. auto.
Qed.
Lemma make_shruimm_correct:
forall n r1,
let (op, args) := make_shruimm n r1 in
exists v, eval_operation ge sp op rs##args m = Some v /\ Val.lessdef (Val.shru rs#r1 (Vint n)) v.
Proof.
intros; unfold make_shruimm.
predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.
exists (rs#r1); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.shru_zero. auto.
econstructor; split; eauto. simpl. congruence.
Qed.
Lemma make_mulimm_correct:
forall n r1,
let (op, args) := make_mulimm n r1 in
exists v, eval_operation ge sp op rs##args m = Some v /\ Val.lessdef (Val.mul rs#r1 (Vint n)) v.
Proof.
intros; unfold make_mulimm.
predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.
exists (Vint Int.zero); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.mul_zero; auto.
predSpec Int.eq Int.eq_spec n Int.one; intros. subst.
exists (rs#r1); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.mul_one; auto.
destruct (Int.is_power2 n) eqn:?; intros.
rewrite (Val.mul_pow2 rs#r1 _ _ Heqo). apply make_shlimm_correct; auto.
econstructor; split; eauto. auto.
Qed.
Lemma make_divimm_correct:
forall n r1 r2 v,
Val.divs rs#r1 rs#r2 = Some v ->
rs#r2 = Vint n ->
let (op, args) := make_divimm n r1 r2 in
exists w, eval_operation ge sp op rs##args m = Some w /\ Val.lessdef v w.
Proof.
intros; unfold make_divimm.
destruct (Int.is_power2 n) eqn:?.
destruct (Int.ltu i (Int.repr 31)) eqn:?.
exists v; split; auto. simpl. eapply Val.divs_pow2; eauto. congruence.
exists v; auto.
exists v; auto.
Qed.
Lemma make_divuimm_correct:
forall n r1 r2 v,
Val.divu rs#r1 rs#r2 = Some v ->
rs#r2 = Vint n ->
let (op, args) := make_divuimm n r1 r2 in
exists w, eval_operation ge sp op rs##args m = Some w /\ Val.lessdef v w.
Proof.
intros; unfold make_divuimm.
destruct (Int.is_power2 n) eqn:?.
replace v with (Val.shru rs#r1 (Vint i)).
eapply make_shruimm_correct; eauto.
eapply Val.divu_pow2; eauto. congruence.
exists v; auto.
Qed.
Lemma make_moduimm_correct:
forall n r1 r2 v,
Val.modu rs#r1 rs#r2 = Some v ->
rs#r2 = Vint n ->
let (op, args) := make_moduimm n r1 r2 in
exists w, eval_operation ge sp op rs##args m = Some w /\ Val.lessdef v w.
Proof.
intros; unfold make_moduimm.
destruct (Int.is_power2 n) eqn:?.
exists v; split; auto. simpl. decEq. eapply Val.modu_pow2; eauto. congruence.
exists v; auto.
Qed.
Lemma make_andimm_correct:
forall n r,
let (op, args) := make_andimm n r in
exists v, eval_operation ge sp op rs##args m = Some v /\ Val.lessdef (Val.and rs#r (Vint n)) v.
Proof.
intros; unfold make_andimm.
predSpec Int.eq Int.eq_spec n Int.zero; intros.
subst n. exists (Vint Int.zero); split; auto. destruct (rs#r); simpl; auto. rewrite Int.and_zero; auto.
predSpec Int.eq Int.eq_spec n Int.mone; intros.
subst n. exists (rs#r); split; auto. destruct (rs#r); simpl; auto. rewrite Int.and_mone; auto.
econstructor; split; eauto. auto.
Qed.
Lemma make_orimm_correct:
forall n r,
let (op, args) := make_orimm n r in
exists v, eval_operation ge sp op rs##args m = Some v /\ Val.lessdef (Val.or rs#r (Vint n)) v.
Proof.
intros; unfold make_orimm.
predSpec Int.eq Int.eq_spec n Int.zero; intros.
subst n. exists (rs#r); split; auto. destruct (rs#r); simpl; auto. rewrite Int.or_zero; auto.
predSpec Int.eq Int.eq_spec n Int.mone; intros.
subst n. exists (Vint Int.mone); split; auto. destruct (rs#r); simpl; auto. rewrite Int.or_mone; auto.
econstructor; split; eauto. auto.
Qed.
Lemma make_xorimm_correct:
forall n r,
let (op, args) := make_xorimm n r in
exists v, eval_operation ge sp op rs##args m = Some v /\ Val.lessdef (Val.xor rs#r (Vint n)) v.
Proof.
intros; unfold make_xorimm.
predSpec Int.eq Int.eq_spec n Int.zero; intros.
subst n. exists (rs#r); split; auto. destruct (rs#r); simpl; auto. rewrite Int.xor_zero; auto.
econstructor; split; eauto. auto.
Qed.
Lemma op_strength_reduction_correct:
forall op args vl v,
vl = approx_regs app args ->
eval_operation ge sp op rs##args m = Some v ->
let (op', args') := op_strength_reduction op args vl in
exists w, eval_operation ge sp op' rs##args' m = Some w /\ Val.lessdef v w.
Proof.
intros until v; unfold op_strength_reduction;
case (op_strength_reduction_match op args vl); simpl; intros.
(* sub *)
InvApproxRegs. SimplVMA. inv H0; rewrite H. rewrite Val.sub_add_opp. apply make_addimm_correct; auto.
(* mul *)
InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_mulimm_correct; auto.
(* divs *)
assert (rs#r2 = Vint n2). clear H0. InvApproxRegs; SimplVMA; auto.
apply make_divimm_correct; auto.
(* divu *)
assert (rs#r2 = Vint n2). clear H0. InvApproxRegs; SimplVMA; auto.
apply make_divuimm_correct; auto.
(* modu *)
assert (rs#r2 = Vint n2). clear H0. InvApproxRegs; SimplVMA; auto.
apply make_moduimm_correct; auto.
(* and *)
InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_andimm_correct; auto.
(* or *)
InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_orimm_correct; auto.
(* xor *)
InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_xorimm_correct; auto.
(* shl *)
InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_shlimm_correct; auto.
(* shr *)
InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_shrimm_correct; auto.
(* shru *)
InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_shruimm_correct; auto.
(* lea *)
generalize (addr_strength_reduction_correct addr args0 vl0 H).
destruct (addr_strength_reduction addr args0 vl0) as [addr' args'].
intro EQ. exists v; split; auto. simpl. congruence.
(* cond *)
generalize (cond_strength_reduction_correct c args0 vl0 H).
destruct (cond_strength_reduction c args0 vl0) as [c' args']; intros.
rewrite <- H1 in H0; auto. econstructor; split; eauto.
(* default *)
exists v; auto.
Qed.
End STRENGTH_REDUCTION.
End ANALYSIS.
|
{
"alphanum_fraction": null,
"author": "academic-archive",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/coq/academic-archive-pldi14-veristack/pldi14-veristack-9edcd8752ae2e1e6377bfb33589a377cc39c04ca/qcompcert/ia32/ConstpropOpproof.v",
"reason": null,
"repo": "pldi14-veristack",
"save_path": "github-repos/coq/academic-archive-pldi14-veristack",
"sha": "9edcd8752ae2e1e6377bfb33589a377cc39c04ca",
"size": null
}
|
import copy
import numpy as np
from nltk.translate.bleu_score import corpus_bleu
from nltk.tokenize import word_tokenize
def rouge_helper_prepare_results(m, p, r, f):
return '\t{}:\t{}: {:5.2f}\t{}: {:5.2f}\t{}: {:5.2f}'.format(m, 'P', 100.0 * p, 'R', 100.0 * r, 'F1', 100.0 * f)
def remove_sub_strings(predicted_txt, tokens=['ᐛ ', ' ✬', '<unk>']):
"""
remove the list of strings (tokens) from predicted_txt
"""
for token in tokens:
predicted_txt = predicted_txt.replace(token, "")
return predicted_txt
def remove_sub_strings_chinese(predicted_txt, tokens=['ᐛ', '✬', '<unk>']):
"""
remove the list of strings (tokens) from predicted_txt
"""
for token in tokens:
predicted_txt = predicted_txt.replace(token, "")
return predicted_txt
def translation_paraphrase_evaluation_english_tagpa(sources, hypos, refs, print_scores=True, max_n=4, rouge_alpha=0.5, rouge_weight_factor=1.2, rouge_stemming=True):
"""
to evalute generated paraphrase or translations with BlEU and ROUGE scores.
Nothing should be tokenized here.
:param sources: source sentence to start with. e.g. ['Young woman with sheep on straw covered floor .', 'A man who is walking across the street .']
:param hypos: generated hypotheses. should share the same shape with sources. (each source, generate one list of hypothesis sentence.) e.g. ['Young woman with sheep on straw covered floor .', 'a little girl with sheep on straw covered floor .'] for 'Young woman with sheep on straw covered floor .'
:param refs: list of list of sentences. For each source, given a list of possible references. e.g. [['Young woman with sheep on straw covered floor .', 'Young woman on the floor .'] ['A man who is walking across the street now.', 'A man walking across the street.']]
:return: a dictionary of scores.
"""
import rouge # pip install git+https://github.com/Mohan-Zhang-u/py-rouge.git
sources_refs = [[sentence] for sentence in sources] # we use source as the reference to compute a negative score, in order to measure the diversity of paraphrasing.
metrics_dict = {}
for aggregator in ['Avg', 'Best']:
apply_avg = aggregator == 'Avg'
apply_best = aggregator == 'Best'
evaluator = rouge.Rouge(metrics=['rouge-n', 'rouge-l', 'rouge-w'],
max_n=max_n,
apply_avg=apply_avg,
apply_best=apply_best,
alpha=rouge_alpha, # Default F1_score
weight_factor=rouge_weight_factor,
stemming=rouge_stemming)
compare_dict = {'hypos':hypos, 'sources':sources, 'sources_refs_diversity_negative': hypos}
for key in compare_dict:
if key == 'sources_refs_diversity_negative':
scores = evaluator.get_scores(compare_dict[key], sources_refs)
else:
scores = evaluator.get_scores(compare_dict[key], refs)
metrics_dict[key+'_rouge_'+aggregator] = scores
if print_scores:
print('Evaluation with {} with {}'.format(key, aggregator))
for metric, results in sorted(scores.items(), key=lambda x: x[0]):
if not apply_avg and not apply_best: # value is a type of list as we evaluate each summary vs each reference
for hypothesis_id, results_per_ref in enumerate(results):
nb_references = len(results_per_ref['p'])
for reference_id in range(nb_references):
print('\tHypothesis #{} & Reference #{}: '.format(hypothesis_id, reference_id))
print('\t' + rouge_helper_prepare_results(metric,results_per_ref['p'][reference_id], results_per_ref['r'][reference_id], results_per_ref['f'][reference_id]))
print()
else:
print(rouge_helper_prepare_results(metric, results['p'], results['r'], results['f']))
print()
bleu_sources = []
for source in sources:
bleu_sources.append(word_tokenize(source))
bleu_hypos = []
for hypo in hypos:
bleu_hypos.append(word_tokenize(hypo))
bleu_refs = copy.deepcopy(refs)
for sub_ref in bleu_refs:
for i in range(len(sub_ref)):
sub_ref[i] = word_tokenize(sub_ref[i])
for sources_ref in sources_refs:
for i in range(len(sources_ref)):
sources_ref[i] = word_tokenize(sources_ref[i])
# metrics_dict["bleu_no_weights"] = corpus_bleu(refs, hypos)
metrics_dict["bleu_1"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(1, 0, 0, 0))
metrics_dict["bleu_2"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(0.5, 0.5, 0, 0))
metrics_dict["bleu_3"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(0.33, 0.33, 0.34, 0))
metrics_dict["bleu_4"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(0.25, 0.25, 0.25, 0.25))
metrics_dict["source_sentence_bleu_1"] = corpus_bleu(bleu_refs, bleu_sources, weights=(1, 0, 0, 0))
metrics_dict["source_sentence_bleu_2"] = corpus_bleu(bleu_refs, bleu_sources, weights=(0.5, 0.5, 0, 0))
metrics_dict["source_sentence_bleu_3"] = corpus_bleu(bleu_refs, bleu_sources, weights=(0.33, 0.33, 0.34, 0))
metrics_dict["source_sentence_bleu_4"] = corpus_bleu(bleu_refs, bleu_sources, weights=(0.25, 0.25, 0.25, 0.25))
metrics_dict["sources_as_refs_diversity_negative_bleu_1"] = corpus_bleu(sources_refs, bleu_hypos, weights=(1, 0, 0, 0))
metrics_dict["sources_as_refs_diversity_negative_bleu_2"] = corpus_bleu(sources_refs, bleu_hypos, weights=(0.5, 0.5, 0, 0))
metrics_dict["sources_as_refs_diversity_negative_bleu_3"] = corpus_bleu(sources_refs, bleu_hypos, weights=(0.33, 0.33, 0.34, 0))
metrics_dict["sources_as_refs_diversity_negative_bleu_4"] = corpus_bleu(sources_refs, bleu_hypos, weights=(0.25, 0.25, 0.25, 0.25))
if print_scores:
for sc in ["bleu_1", "bleu_2", "bleu_3", "bleu_4", "source_sentence_bleu_1", "source_sentence_bleu_2", "source_sentence_bleu_3", "source_sentence_bleu_4", "sources_as_refs_diversity_negative_bleu_1", "sources_as_refs_diversity_negative_bleu_2", "sources_as_refs_diversity_negative_bleu_3", "sources_as_refs_diversity_negative_bleu_4"]:
print(sc,"(percents):", round(metrics_dict[sc], 4) * 100)
return metrics_dict
def translation_paraphrase_evaluation(sources, hypos, refs, sentence_preproce_function=None, print_scores=True, max_n=4, rouge_alpha=0.5, rouge_weight_factor=1.2, rouge_stemming=True, hypo_style='first'):
"""
to evalute generated paraphrase or translations with BlEU and ROUGE scores.
Nothing should be tokenized here.
:param sources: source sentence to start with. e.g. sources = ['Young woman with sheep on straw covered floor.', 'A man who is walking across the street.', 'A brightly lit kitchen with lots of natural light.']
:param hypos: generated hypotheses. should share the same shape with sources. (each source, generate one list of hypothesis sentence.) e.g. [['A child places his hands on the head and neck of a sheep while another sheep looks at his face.', 'A person petting the head of a cute fluffy sheep.', 'A child is petting a sheep while another sheep watches.', 'A woman kneeling to pet animals while others wait. '], ['A busy intersection with an ice cream truck driving by.', 'a man walks behind an ice cream truck ', 'A man is crossing a street near an icecream truck.', 'The man is walking behind the concession bus.'], ['A modern kitchen in white with stainless steel lights.', 'A kitchen filled with lots of white counter space.', 'A KITCHEN IN THE ROOM WITH WHITE APPLIANCES ', 'A modern home kitchen and sitting area looking out towards the back yard']]
:param refs: list of list of sentences. For each source, given a list of possible references. e.g. [['A woman standing next to a sheep in a pen .<unk>', 'A woman standing next to a sheep on a farm .<unk>', 'A woman standing next to a sheep in a barn .<unk>', 'A woman standing next to a sheep in a field .<unk>', 'A woman standing next to a sheep in a barn<unk>'], ['A man crossing the street in front of a store .<unk>', 'A man crossing the street in a city .<unk>', 'A person crossing the street in a city .<unk>', 'A man crossing the street in the middle of a city<unk>', 'A man crossing the street in the middle of a city street<unk>'], ['a kitchen with a stove a microwave and a sink<unk>', 'a kitchen with a stove a sink and a microwave<unk>', 'a kitchen with a stove a sink and a refrigerator<unk>', 'A kitchen with a sink , stove , microwave and window .<unk>', 'a kitchen with a stove a sink and a window<unk>']]
:param hypo_style: how to evaluate the generated hypotheses. Pick the first? Choose the one with best evalution score? Average the scores on all hypotheses? Should be one of ['first', 'best', 'average']
:param sentence_preproce_function: a function that will be applied to all sentences in sources, hypos, refs
:return: a dictionary of scores.
"""
import rouge # pip install git+https://github.com/Mohan-Zhang-u/py-rouge.git
assert(isinstance(sources, list))
assert(isinstance(sources[0], str))
assert(isinstance(hypos, list))
assert(isinstance(hypos[0], list))
assert(isinstance(hypos[0][0], str))
assert(isinstance(refs, list))
assert(isinstance(refs[0], list))
assert(isinstance(refs[0][0], str))
if hypo_style == 'first':
hypos = [hypo[0] for hypo in hypos]
else:
raise NotImplementedError
# apply sentence_preproce_function, e.g. remove_tokens
if sentence_preproce_function is not None:
sources = [sentence_preproce_function(source) for source in sources]
if hypo_style == 'first':
hypos = [sentence_preproce_function(hypo) for hypo in hypos]
else:
raise NotImplementedError
hypos = [[sentence_preproce_function(hypo) for hypo in hypo_list] for hypo_list in hypos]
refs = [[sentence_preproce_function(ref) for ref in refs_list] for refs_list in refs]
sources_refs = [[sentence] for sentence in sources] # we use source as the reference to compute a negative score, in order to measure the diversity of paraphrasing.
metrics_dict = {}
for aggregator in ['Avg', 'Best']:
apply_avg = aggregator == 'Avg'
apply_best = aggregator == 'Best'
evaluator = rouge.Rouge(metrics=['rouge-n', 'rouge-l', 'rouge-w'],
max_n=max_n,
apply_avg=apply_avg,
apply_best=apply_best,
alpha=rouge_alpha, # Default F1_score
weight_factor=rouge_weight_factor,
stemming=rouge_stemming)
compare_dict = {'hypos':hypos, 'sources':sources, 'sources_refs_diversity_negative': hypos}
for key in compare_dict:
if key == 'sources_refs_diversity_negative':
scores = evaluator.get_scores(compare_dict[key], sources_refs)
else:
scores = evaluator.get_scores(compare_dict[key], refs)
metrics_dict[key+'_rouge_'+aggregator] = scores
if print_scores:
print('Evaluation with {} with {}'.format(key, aggregator))
for metric, results in sorted(scores.items(), key=lambda x: x[0]):
if not apply_avg and not apply_best: # value is a type of list as we evaluate each summary vs each reference
for hypothesis_id, results_per_ref in enumerate(results):
nb_references = len(results_per_ref['p'])
for reference_id in range(nb_references):
print('\tHypothesis #{} & Reference #{}: '.format(hypothesis_id, reference_id))
print('\t' + rouge_helper_prepare_results(metric,results_per_ref['p'][reference_id], results_per_ref['r'][reference_id], results_per_ref['f'][reference_id]))
print()
else:
print(rouge_helper_prepare_results(metric, results['p'], results['r'], results['f']))
print()
bleu_sources = []
for source in sources:
bleu_sources.append(word_tokenize(source))
bleu_hypos = []
if hypo_style == 'first':
for hypo in hypos:
bleu_hypos.append(word_tokenize(hypo))
else:
raise NotImplementedError
bleu_hypos = copy.deepcopy(hypos)
for sub_hypo in bleu_hypos:
for i in range(len(sub_hypo)):
sub_hypo[i] = word_tokenize(sub_hypo[i])
bleu_refs = copy.deepcopy(refs)
for sub_ref in bleu_refs:
for i in range(len(sub_ref)):
sub_ref[i] = word_tokenize(sub_ref[i])
for sources_ref in sources_refs:
for i in range(len(sources_ref)):
sources_ref[i] = word_tokenize(sources_ref[i])
# print(corpus_bleu(bleu_refs, bleu_hypos, weights=(1, 0, 0, 0)))
# return
metrics_dict["bleu_1"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(1, 0, 0, 0))
metrics_dict["bleu_2"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(0.5, 0.5, 0, 0))
metrics_dict["bleu_3"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(0.33, 0.33, 0.34, 0))
metrics_dict["bleu_4"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(0.25, 0.25, 0.25, 0.25))
metrics_dict["source_sentence_bleu_1"] = corpus_bleu(bleu_refs, bleu_sources, weights=(1, 0, 0, 0))
metrics_dict["source_sentence_bleu_2"] = corpus_bleu(bleu_refs, bleu_sources, weights=(0.5, 0.5, 0, 0))
metrics_dict["source_sentence_bleu_3"] = corpus_bleu(bleu_refs, bleu_sources, weights=(0.33, 0.33, 0.34, 0))
metrics_dict["source_sentence_bleu_4"] = corpus_bleu(bleu_refs, bleu_sources, weights=(0.25, 0.25, 0.25, 0.25))
metrics_dict["sources_as_refs_diversity_negative_bleu_1"] = corpus_bleu(sources_refs, bleu_hypos, weights=(1, 0, 0, 0))
metrics_dict["sources_as_refs_diversity_negative_bleu_2"] = corpus_bleu(sources_refs, bleu_hypos, weights=(0.5, 0.5, 0, 0))
metrics_dict["sources_as_refs_diversity_negative_bleu_3"] = corpus_bleu(sources_refs, bleu_hypos, weights=(0.33, 0.33, 0.34, 0))
metrics_dict["sources_as_refs_diversity_negative_bleu_4"] = corpus_bleu(sources_refs, bleu_hypos, weights=(0.25, 0.25, 0.25, 0.25))
if print_scores:
for sc in ["bleu_1", "bleu_2", "bleu_3", "bleu_4", "source_sentence_bleu_1", "source_sentence_bleu_2", "source_sentence_bleu_3", "source_sentence_bleu_4", "sources_as_refs_diversity_negative_bleu_1", "sources_as_refs_diversity_negative_bleu_2", "sources_as_refs_diversity_negative_bleu_3", "sources_as_refs_diversity_negative_bleu_4"]:
print(sc,"(percents):", round(metrics_dict[sc], 4) * 100)
return metrics_dict
def translation_paraphrase_evaluation_chinese(sources, hypos, refs, sentence_preproce_function=None, print_scores=True, max_n=4, rouge_alpha=0.5, rouge_weight_factor=1.2, rouge_stemming=True, hypo_style='first', word_segmentor='character'):
"""
to evalute generated paraphrase or translations with BlEU and ROUGE scores.
Nothing should be tokenized here.
:param sources: source sentence to start with.
:param hypos: generated hypotheses. should share the same shape with sources. (each source, generate one list of hypothesis sentence.)
:param refs: list of list of sentences. For each source, given a list of possible references.
:param hypo_style: how to evaluate the generated hypotheses. Pick the first? Choose the one with best evalution score? Average the scores on all hypotheses? Should be one of ['first', 'best', 'average']
:param sentence_preproce_function: a function that will be applied to all sentences in sources, hypos, refs
:param word_segmentor: 'character' means seperate each character to be a word, 'hanlp' means an hanlp chinese tokenizer.
:return: a dictionary of scores.
"""
import rouge # pip install git+https://github.com/Mohan-Zhang-u/py-rouge.git
assert(isinstance(sources, list))
assert(isinstance(sources[0], str))
assert(isinstance(hypos, list))
assert(isinstance(hypos[0], list))
assert(isinstance(hypos[0][0], str))
assert(isinstance(refs, list))
assert(isinstance(refs[0], list))
assert(isinstance(refs[0][0], str))
# apply sentence_preproce_function, e.g. remove_tokens
if sentence_preproce_function is not None:
sources = [sentence_preproce_function(source) for source in sources]
hypos = [[sentence_preproce_function(hypo) for hypo in hypo_list] for hypo_list in hypos]
refs = [[sentence_preproce_function(ref) for ref in refs_list] for refs_list in refs]
sources_refs = [[sentence] for sentence in sources] # we use source as the reference to compute a negative score, in order to measure the diversity of paraphrasing.
metrics_dict = {}
# tokenize chinese sentences.
if word_segmentor == 'character':
sources = [' '.join(source) for source in sources]
refs = [[' '.join(ref) for ref in ref_list] for ref_list in refs]
sources_refs = [[' '.join(ref) for ref in ref_list] for ref_list in sources_refs]
hypos = [[' '.join(hypo) for hypo in hypo_list] for hypo_list in hypos]
def word_tokenize(sentence):
return sentence.split(' ')
bleu_sources = []
for source in sources:
bleu_sources.append(word_tokenize(source))
bleu_hypos = copy.deepcopy(hypos)
for sub_hypo in bleu_hypos:
for i in range(len(sub_hypo)):
sub_hypo[i] = word_tokenize(sub_hypo[i])
bleu_refs = copy.deepcopy(refs)
for sub_ref in bleu_refs:
for i in range(len(sub_ref)):
sub_ref[i] = word_tokenize(sub_ref[i])
bleu_sources_refs = copy.deepcopy(sources_refs)
for sources_ref in bleu_sources_refs:
for i in range(len(sources_ref)):
sources_ref[i] = word_tokenize(sources_ref[i])
elif word_segmentor == 'hanlp':
import hanlp
word_tokenize = hanlp.load('LARGE_ALBERT_BASE')
bleu_sources = []
for source in sources:
bleu_sources.append(word_tokenize(source))
bleu_hypos = copy.deepcopy(hypos)
for sub_hypo in bleu_hypos:
for i in range(len(sub_hypo)):
sub_hypo[i] = word_tokenize(sub_hypo[i])
bleu_refs = copy.deepcopy(refs)
for sub_ref in bleu_refs:
for i in range(len(sub_ref)):
sub_ref[i] = word_tokenize(sub_ref[i])
bleu_sources_refs = copy.deepcopy(sources_refs)
for bleu_sources_ref in bleu_sources_refs:
for i in range(len(bleu_sources_ref)):
bleu_sources_ref[i] = word_tokenize(bleu_sources_ref[i])
sources = [' '.join(source) for source in bleu_sources]
refs = [[' '.join(ref) for ref in ref_list] for ref_list in bleu_refs]
sources_refs = [[' '.join(ref) for ref in ref_list] for ref_list in bleu_sources_refs]
hypos = [[' '.join(hypo) for hypo in hypo_list] for hypo_list in bleu_hypos]
if hypo_style == 'first':
hypos = [hypo[0] for hypo in hypos]
bleu_hypos = [hypo[0] for hypo in bleu_hypos]
else:
raise NotImplementedError
for aggregator in ['Avg', 'Best']:
apply_avg = aggregator == 'Avg'
apply_best = aggregator == 'Best'
evaluator = rouge.Rouge(metrics=['rouge-n', 'rouge-l', 'rouge-w'],
max_n=max_n,
apply_avg=apply_avg,
apply_best=apply_best,
alpha=rouge_alpha, # Default F1_score
weight_factor=rouge_weight_factor,
stemming=rouge_stemming,
language='chinese')
compare_dict = {'hypos':hypos, 'sources':sources, 'sources_refs_diversity_negative': hypos}
for key in compare_dict:
if key == 'sources_refs_diversity_negative':
scores = evaluator.get_scores(compare_dict[key], sources_refs)
else:
scores = evaluator.get_scores(compare_dict[key], refs)
metrics_dict[key+'_rouge_'+aggregator] = scores
if print_scores:
print('Evaluation with {} with {}'.format(key, aggregator))
for metric, results in sorted(scores.items(), key=lambda x: x[0]):
if not apply_avg and not apply_best: # value is a type of list as we evaluate each summary vs each reference
for hypothesis_id, results_per_ref in enumerate(results):
nb_references = len(results_per_ref['p'])
for reference_id in range(nb_references):
print('\tHypothesis #{} & Reference #{}: '.format(hypothesis_id, reference_id))
print('\t' + rouge_helper_prepare_results(metric,results_per_ref['p'][reference_id], results_per_ref['r'][reference_id], results_per_ref['f'][reference_id]))
print()
else:
print(rouge_helper_prepare_results(metric, results['p'], results['r'], results['f']))
print()
metrics_dict["bleu_1"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(1, 0, 0, 0))
metrics_dict["bleu_2"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(0.5, 0.5, 0, 0))
metrics_dict["bleu_3"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(0.33, 0.33, 0.34, 0))
metrics_dict["bleu_4"] = corpus_bleu(bleu_refs, bleu_hypos, weights=(0.25, 0.25, 0.25, 0.25))
metrics_dict["source_sentence_bleu_1"] = corpus_bleu(bleu_refs, bleu_sources, weights=(1, 0, 0, 0))
metrics_dict["source_sentence_bleu_2"] = corpus_bleu(bleu_refs, bleu_sources, weights=(0.5, 0.5, 0, 0))
metrics_dict["source_sentence_bleu_3"] = corpus_bleu(bleu_refs, bleu_sources, weights=(0.33, 0.33, 0.34, 0))
metrics_dict["source_sentence_bleu_4"] = corpus_bleu(bleu_refs, bleu_sources, weights=(0.25, 0.25, 0.25, 0.25))
metrics_dict["sources_as_refs_diversity_negative_bleu_1"] = corpus_bleu(bleu_sources_refs, bleu_hypos, weights=(1, 0, 0, 0))
metrics_dict["sources_as_refs_diversity_negative_bleu_2"] = corpus_bleu(bleu_sources_refs, bleu_hypos, weights=(0.5, 0.5, 0, 0))
metrics_dict["sources_as_refs_diversity_negative_bleu_3"] = corpus_bleu(bleu_sources_refs, bleu_hypos, weights=(0.33, 0.33, 0.34, 0))
metrics_dict["sources_as_refs_diversity_negative_bleu_4"] = corpus_bleu(bleu_sources_refs, bleu_hypos, weights=(0.25, 0.25, 0.25, 0.25))
if print_scores:
for sc in ["bleu_1", "bleu_2", "bleu_3", "bleu_4", "source_sentence_bleu_1", "source_sentence_bleu_2", "source_sentence_bleu_3", "source_sentence_bleu_4", "sources_as_refs_diversity_negative_bleu_1", "sources_as_refs_diversity_negative_bleu_2", "sources_as_refs_diversity_negative_bleu_3", "sources_as_refs_diversity_negative_bleu_4"]:
print(sc,"(percents):", round(metrics_dict[sc], 4) * 100)
return metrics_dict
|
{
"alphanum_fraction": 0.6627772791,
"author": null,
"avg_line_length": 61.2486910995,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "f3d3ed53dcdf19420dbac4d784ee70499ac7a559",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2020-09-22T03:19:14.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-09-04T05:07:10.000Z",
"max_forks_repo_head_hexsha": "4c6a657b6a03d953a97c6e0f2b252c8aead6aa2b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Mohan-Zhang-u/mzutils",
"max_forks_repo_path": "mzutils/nlp_tasks/nlp_metrics.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4c6a657b6a03d953a97c6e0f2b252c8aead6aa2b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Mohan-Zhang-u/mzutils",
"max_issues_repo_path": "mzutils/nlp_tasks/nlp_metrics.py",
"max_line_length": 925,
"max_stars_count": 132,
"max_stars_repo_head_hexsha": "4c6a657b6a03d953a97c6e0f2b252c8aead6aa2b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Mohan-Zhang-u/mzutils",
"max_stars_repo_path": "mzutils/nlp_tasks/nlp_metrics.py",
"max_stars_repo_stars_event_max_datetime": "2021-05-27T19:49:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-25T13:32:12.000Z",
"num_tokens": 6102,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 23397
}
|
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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.
"""Computes Approximation error.
"""
import os
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import tensorflow.compat.v1 as tf
def w_star(d, F, V): # pylint: disable=invalid-name
r"""Best d-dimensional linear model.
Args:
d: int, top d projection of the left singular vectors.
F: S \times S matrix, left singular vectors.
V: S \times 1 matrix, values of the states.
Returns:
weight vector: array of size d
"""
return np.linalg.pinv(F[:, :d]) @ V
def approx_error(d, F, V): # pylint: disable=invalid-name
r"""Computes the approximation error for a d-dimensional linear model.
Features from the SR in a noiseless setting.
If the parameter reward_function is None, we use the environment's reward. If
the parameter reward_function is a non-None vector, we use those rewards
instead.
Args:
d: int, top d projection of the left singular vectors
F: S \times S matrix, left singular vectors
V: S \times 1 matrix, targets
Returns:
approximation error: Float.
"""
return np.mean((F[:, :d] @ w_star(d, F, V) - V)**2)
approx_error_vec = np.vectorize(approx_error, excluded=[1, 2])
def plot_approx_error_rewards(base_dir, k_range, data, rewards, num_states,
gamma, env_name):
"""Plot estimation error vs dimnension."""
plt.subplots(1, 1, figsize=(7, 5))
colors = sns.color_palette('colorblind')
idx = -1
for reward_type in rewards:
idx += 1
plt.plot(
k_range,
data[reward_type],
'o',
color=colors[idx],
linewidth=3,
markevery=34,
ls='-',
ms=8)
plt.xlabel('Number of features', fontsize='xx-large')
plt.ylabel('Approximation error', fontsize='xx-large')
# plt.legend(rewards, fontsize='xx-large')
plt.title(
'S={}, MDP={}, gamma={}'.format(num_states, env_name, gamma),
fontsize='xx-large')
xticks = np.arange(0, len(k_range), 50)
xticks[0] = 1
plt.xticks(ticks=xticks)
plt.tick_params(length=0.1, width=0.1, labelsize='x-large')
plt.gca().spines['right'].set_visible(False)
plt.gca().spines['top'].set_visible(False)
pdf_file = os.path.join(base_dir,
f'{env_name}_approx_error_compare_rewards.pdf')
with tf.io.gfile.GFile(pdf_file, 'w') as f:
plt.savefig(f, format='pdf', dpi=300, bbox_inches='tight')
plt.clf()
plt.close('all')
def plot_singular_values(base_dir, data):
"""Plot singular values for all policies."""
plt.subplots(1, 1, figsize=(8, 6))
num_policies, num_states = data.shape
dimension = np.arange(1, num_states+1)
epsilons = np.linspace(0, 1, num_policies)
for i in range(num_policies):
plt.plot(
dimension, data[i], lw=3, label=f'epsilon {epsilons[i]:.1f}')
plt.xlabel('Index', fontsize=24)
plt.ylabel('Singular Value', fontsize=24)
plt.yscale('log')
plt.legend(fontsize=18, loc=7)
pdf_file = os.path.join(base_dir, 'singular_value.pdf')
with tf.io.gfile.GFile(pdf_file, 'w') as f:
plt.savefig(f, format='pdf', dpi=300, bbox_inches='tight')
plt.clf()
plt.close('all')
|
{
"alphanum_fraction": 0.676819407,
"author": null,
"avg_line_length": 31.7094017094,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "dfb454725e87898537082b69b2c7f34286bff0a6",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T07:20:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-30T07:20:29.000Z",
"max_forks_repo_head_hexsha": "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "gunpowder78/google-research",
"max_forks_repo_path": "generalization_representations_rl_aistats22/minigrid/approximation_error.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "gunpowder78/google-research",
"max_issues_repo_path": "generalization_representations_rl_aistats22/minigrid/approximation_error.py",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "gunpowder78/google-research",
"max_stars_repo_path": "generalization_representations_rl_aistats22/minigrid/approximation_error.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-19T04:26:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-19T04:26:12.000Z",
"num_tokens": 1002,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3710
}
|
include("euler/euler.jl")
using .Numbers: get_digits
function compute(n::Float64)::Int
bouncy = 0
i = 1
while bouncy / i < n
i += 1
digits = get_digits(i)
sorted_digits = sort(digits)
if !(digits == sorted_digits || digits == reverse(sorted_digits)) bouncy += 1 end
end
return i
end
|
{
"alphanum_fraction": 0.5982142857,
"author": null,
"avg_line_length": 22.4,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "96e413ac6405af5ca7f5bf2a095564edafdd8d94",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "99a0201b5d5f147eab77fc52d9db8995045cded0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Dynortice/Project-Euler",
"max_forks_repo_path": "problems/0112/compute.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "99a0201b5d5f147eab77fc52d9db8995045cded0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Dynortice/Project-Euler",
"max_issues_repo_path": "problems/0112/compute.jl",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "99a0201b5d5f147eab77fc52d9db8995045cded0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Dynortice/Project-Euler",
"max_stars_repo_path": "problems/0112/compute.jl",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 97,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 336
}
|
#****************************************************************************
# Molecular Dynamics Potentials (MDP)
# CESMIX-MIT Project
#
# Contributing authors: Ngoc-Cuong Nguyen (cuongng@mit.edu, exapde@gmail.com)
#****************************************************************************
function mdp(app)
# create exec folder if it does not exist
bindir = "exec";
cd(app.sourcepath);
if isdir(bindir) == 0
mkdir(bindir);
end
cd(app.currentdir);
# preprocess input data
app, config = Preprocessing.preprocessing(app);
# generate code
Gencode.gencode(app); # Generate C++ code
# compile C++ source code
# cd(app.sourcepath * "C++/Main");
# Gencode.compile(app);
cd(app.sourcepath * bindir);
if isfile("CMakeCache.txt")
rm("CMakeCache.txt", force=true);
end
if app.platform == "gpu"
if isfile("libcpuCore.a") && isfile("libgpuCore.a") && isfile("gpuMDP")
run(Gencode.string2cmd("cmake -D MDP_POTENTIALS=ON -D MDP_CUDA=ON ../Installation"));
else
run(Gencode.string2cmd("cmake -D MDP_POTENTIALS=ON -D MDP_CORES=ON -D MDP_EXECUTABLES=ON -D MDP_CUDA=ON ../Installation"));
end
elseif app.platform == "cpu"
if isfile("libcpuCore.a") && isfile("cpuMDP")
run(Gencode.string2cmd("cmake -D MDP_POTENTIALS=ON ../Installation"));
else
run(Gencode.string2cmd("cmake -D MDP_POTENTIALS=ON -D MDP_CORES=ON -D MDP_EXECUTABLES=ON ../Installation"));
end
end
run(Gencode.string2cmd("cmake --build ."));
# run code
#Gencode.runcode(app);
if app.platform == "cpu"
run(Gencode.string2cmd("./cpuMDP " * app.appname * " out"));
else app.platform == "gpu"
run(Gencode.string2cmd("./gpuMDP " * app.appname * " out"));
end
cd(app.currentdir);
if app.training > 0
filename = app.sourcepath * "C++/Main/coefficients.bin";
tmp = reinterpret(Float64,read(filename));
app.coeff = reshape(tmp, 1, length(tmp));
end
return app, config
end
|
{
"alphanum_fraction": 0.5986973948,
"author": null,
"avg_line_length": 31.1875,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "1a40998fa452197aa604c88a33813c21dfb4b770",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "746e4f4aead5911ddeda77b0d2c117e3b70cc5c4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cesmix-mit/MDP",
"max_forks_repo_path": "src/Julia/Postprocessing/mdp.jl",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "746e4f4aead5911ddeda77b0d2c117e3b70cc5c4",
"max_issues_repo_issues_event_max_datetime": "2022-01-24T16:11:07.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-01-24T16:11:07.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "cesmix-mit/MDP",
"max_issues_repo_path": "src/Julia/Postprocessing/mdp.jl",
"max_line_length": 131,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "746e4f4aead5911ddeda77b0d2c117e3b70cc5c4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "cesmix-mit/MDP",
"max_stars_repo_path": "src/Julia/Postprocessing/mdp.jl",
"max_stars_repo_stars_event_max_datetime": "2021-09-15T03:09:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-15T03:09:46.000Z",
"num_tokens": 545,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 1996
}
|
"""
@author: David Diaz Vico
@license: MIT
"""
import numpy as np
from sacred import Experiment, Ingredient
from sklearn.model_selection import cross_validate, PredefinedSplit
def experiment(dataset, estimator):
"""Prepare a Scikit-learn experiment as a Sacred experiment.
Prepare a Scikit-learn experiment indicating a dataset and an estimator and
return it as a Sacred experiment.
Parameters
----------
dataset : function
Dataset fetch function. Might receive any argument. Must return a Bunch
with data, target (might be None), inner_cv (might be None) and outer_cv
(might be None).
estimator : function
Estimator initialization function. Must receive at least X, y and cv,
all of which can be None, and might receive any other argument. Must
return an initialized sklearn-compatible estimator.
Returns
-------
experiment : Experiment
Sacred experiment, ready to be run.
"""
_dataset = Ingredient('dataset')
dataset = _dataset.capture(dataset)
_estimator = Ingredient('estimator')
estimator = _estimator.capture(estimator)
experiment = Experiment(ingredients=(_dataset, _estimator))
@experiment.automain
def run(cross_validate=cross_validate, return_estimator=False):
"""Run the experiment.
Run the experiment.
Parameters
----------
cross_validate : function, default=cross_validate
Function to evaluate metrics by cross-validation. Must receive the
estimator, X, y (migth be None) and cv (migth be None). Must return
a dictionary with the cross-validation score and maybe other info,
like a list of fitted estimators.
return_estimator : boolean, default False
Whether to return the estimator or estimators fitted.
"""
data = dataset()
for a in ('target', 'data_test', 'target_test', 'inner_cv', 'outer_cv'):
if a not in data:
data[a] = None
if hasattr(data.inner_cv, '__iter__'):
X = np.array([]).reshape((0, *data.inner_cv[0][0].shape[1:]))
y = np.array([]).reshape((0, *data.inner_cv[0][1].shape[1:]))
cv = []
for i, (X_, y_, X_test_, y_test_) in enumerate(data.inner_cv):
X = np.concatenate((X, X_, X_test_))
y = np.concatenate((y, y_, y_test_))
cv = cv + [-1]*len(X_) + [i]*len(X_test_)
e = estimator(X=X, y=y, cv=PredefinedSplit(cv))
e.fit(X, y=y)
e.fit = e.best_estimator_.fit
else:
e = estimator(X=data.data, y=data.target, cv=data.inner_cv)
if data.data_test is not None:
e.fit(data.data, y=data.target)
scores = {'test_score': e.score(data.data_test, y=data.target_test)}
if return_estimator:
scores['estimator'] = e
else:
if hasattr(data.outer_cv, '__iter__'):
scores = {'test_score': []}
estimators = []
for X, y, X_test, y_test in data.outer_cv:
e.fit(X, y=y)
if return_estimator:
estimators.append(e)
scores['test_score'].append(e.score(X_test, y=y_test))
if return_estimator:
scores['estimator'] = estimators
else:
scores = cross_validate(e, data.data, y=data.target,
cv=data.outer_cv,
return_estimator=return_estimator)
if return_estimator:
scores['estimator'] = e
experiment.info.update(scores)
return experiment
|
{
"alphanum_fraction": 0.5642802156,
"author": null,
"avg_line_length": 38.97,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "60605759e7ca596a4af31f8a1a2e7eace6144ef7",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "df50d30124340e13bc961d816603fda7431f6063",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "daviddiazvico/scikit-sacred",
"max_forks_repo_path": "sksacred/__init__.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df50d30124340e13bc961d816603fda7431f6063",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "daviddiazvico/scikit-sacred",
"max_issues_repo_path": "sksacred/__init__.py",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df50d30124340e13bc961d816603fda7431f6063",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "daviddiazvico/scikit-sacred",
"max_stars_repo_path": "sksacred/__init__.py",
"max_stars_repo_stars_event_max_datetime": "2018-11-10T17:34:52.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-10T17:34:52.000Z",
"num_tokens": 811,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3897
}
|
\lab{Conjugate-Gradient}{Conjugate-Gradient}
\objective{Learn about the Conjugate-Gradient Algorithm and its Uses}
\section*{Descent Algorithms and the Conjugate-Gradient Method}
There are many possibilities for solving a linear system of equations, each method with its own set of pros and cons. In this lab, we
will explore the \emph{Conjugate-Gradient algorithm}, which is a method for solving large systems of equations where other methods,
such as Cholesky factorization and simple Gaussian elimination, are unsuitable. This algorithm, however, works equally well for
optimizing convex quadratic functions, and it can even be extended to more general classes of optimization problems.
The type of linear system that Conjugate-Gradient can solve involves a matrix with special structure.
Given a symmetric positive-definite $n\times n$ matrix $Q$ and an $n$-vector $b$, we wish to find the $n$-vector $x$ satisfying
\[
Qx = b.
\]
A unique solution exists because positive-definiteness implies invertibility.
For our purposes here, it is useful to recast this problem as an equivalent optimization problem:
\[
\min_{x} f(x) := \frac{1}{2}x^TQx - b^Tx + c.
\]
Note that $\nabla f(x) = Qx - b$, so that minimizing $f(x)$ is the same as solving
\[
0 = \nabla f(x) = Qx - b,
\]
which is our original linear system.
So how do we go about minimizing the quadratic objective function $f$? Line Search methods belonging to the class called
\emph{descent algorithms} use the following strategy: start with an initial guess $x_0$, identify a direction from
this particular point along which the objective function decreases (called a \emph{descent direction}), and perform a line search to
find a new point $x_1$ satisfying $f(x_1) < f(x_0)$. Continue iteratively to produce a sequence of points $\{x_0, x_1, x_2, \ldots \}$
that (hopefully) converges to the true minimizer.
One obvious candidate for the descent direction from some point $x_i$ is simply
$-\nabla f(x_i)$, since this vector points in the direction of steepest decrease. This procedure is known as the Method of Steepest
Descent. Steepest descent, however, can be very inefficient for certain problems: depending on the geometry
of the objective function, the sequence of points can ``zig-zag" back and forth without making appreciable progress toward the true
minimizer. In contrast, the Conjugate-Gradient algorithm ensures that the true global minimizer is reached in at most $n$ steps. See
Figure \ref{basis:steepVsConj} for an illustration of this contrast.
To understand why this is the case and how the algorithm chooses each descent direction, we next discuss the idea of vector conjugacy.
\begin{figure}
\centering
\includegraphics[width=\textwidth]{steepVsConj.pdf}
\caption{Paths traced by Steepest Descent (blue) and Conjugate-Gradient (green). Notice the
zig-zagging nature of the Steepest Descent path, as opposed to the direct Conjugate-Gradient path,
which finds the minimizer in 2 steps.}
\label{basis:steepVsConj}
\end{figure}
\section*{Conjugacy}
Consider again our symmetric positive definite $n \times n$ matrix $Q$. Two vectors $x, y \in \mathbb{R}^n$ are said to be \emph{conjugate}
with respect to $Q$ if $x^TQy = 0$. A set of vectors $\{x_0, x_1, \ldots, x_m\}$ is said to be conjugate if each pair of vectors are conjugate
to each other. Note that if $Q = I$, then conjugacy is the same as orthogonality. Thus, the notion of conjugacy is in some ways a generalization
of orthogonality. It turns out that a conjugate set of vectors is linearly independent, and a conjugate basis--which can be constructed in a manner
analogous to the Gram-Schmidt orthogonalization process--can be used to diagonalize the matrix $Q$.
These are some of the theoretical reasons behind the effectiveness of the Conjugate-Gradient algorithm.
%Take this section out? Add more to it?
\section*{The Algorithm}
If we are given a set of $n$ $Q$-conjugate vectors, we can simply choose these as our direction vectors and follow the basic descent algorithm.
Convergence to the minimizer in at most $n$ steps is guaranteed because each iteration in the algorithm minimizes the objective function
over an expanding affine subspace of dimension equal to the iteration number. Thus, at the $n$-th iteration, we have minimized the function over all of
$\mathbb{R}^n$.
Unfortunately, we are not often given a set of conjugate vectors in advance, so how do we produce such a set? As mentioned earlier, a
Gram-Schmidt process could be used, and the set of eigenvectors also works, but both of these options are computationally expensive.
Built into the algorithm is a way to determine a new conjugate direction based only on the previous direction, which means less memory usage and
faster computation. We have stated the details of Conjugate-Gradient in Algorithm \ref{alg:conjgrad}.
\begin{algorithm}
\begin{algorithmic}[1]
\Procedure{Conjugate-Gradient Algorithm}{}
\State \textrm{Choose initial point } $x_0$.
\State $r_0 \gets Qx_0 - b, d_0 \gets -r_0, k \gets 0$.
\While{$r_k \neq 0$}
\State $\alpha_k \gets \frac{r_k^Tr_k}{d_k^TQd_k}$.
\State $x_{k+1} \gets x_k + \alpha_kd_k$.
\State $r_{k+1} \gets r_k + \alpha_kQd_k$.
\State $\beta_{k+1} \gets \frac{r_{k+1}^Tr_{k+1}}{r_k^Tr_k}$.
\State $d_{k+1} \gets -r_{k+1} + \beta_{k+1}d_k$.
\State $k \gets k+1$.
\EndWhile
\EndProcedure
\end{algorithmic}
\caption{Conjugate-Gradient Algorithm}
\label{alg:conjgrad}
\end{algorithm}
Note that the points $x_i$ are the successive approximations to the minimizer, the vectors $d_i$ are the conjugate descent
directions, and the vectors $r_i$, which actually correspond to the steepest descent directions, are used in determining the conjugate directions.
The constants $\alpha_i$ and $\beta_i$ are used, respectively, in the line search, and in ensuring the $Q$-conjugacy of the descent directions.
The most numerically expensive computation in the algorithm is matrix-vector multiplication.
Notice, however, that each iteration of the algorithm only requires one distinct matrix-vector multiplication, $Qd_k$. The rest of the
operations are simply vector-vector multiplication, addition, and scalar multiplication. This makes for a very fast algorithm.
As noted earlier, Conjugate-Gradient is especially preferred when $Q$ is large and sparse. In this case, it may be possible to
design a specialized sub-routine that performs matrix-vector multiplication by $Q$, by taking advantage of its sparseness. Doing so may
lead to further speed-ups in the overall algorithm.
We now have an algorithm that can solve certain $n \times n$ linear systems and minimize quadratic functions on $\mathbb{R}^n$ in at most $n$ steps,
and sometimes fewer, depending on the spectrum of the matrix $Q$. Further improvements on convergence may be obtained by preconditioning the matrix,
but we do not go into detail here.
\begin{problem}
Implement the basic Conjugate-Gradient algorithm presented above.
Write a function \li{conjugateGradient()} that accepts a vector $b$, an initial
guess $x_0$, a symmetric positive-definite matrix $Q$, and a default tolerance of .0001 as inputs.
Continue the algorithm until $\|r_k\|$ is less than the tolerance.
Return the solution $x^*$ to the linear system $Qx = b$.
\end{problem}
\section*{Example}
We now work through an example that demonstrates the usage of the Conjugate-Gradient algorithm. We assume that we have already written
the specified function in the above problem.
We must first generate a symmetric positive-definite matrix $Q$. This can be done by generating a random matrix $A$ and setting $Q = A^TA$.
So long as $A$ is of full column rank, the matrix $Q$ will be symmetric positive-definite.
\begin{lstlisting}
>>> import numpy as np
>>> from scipy import linalg as la
>>> # initialize the desired dimension of the space
>>> n = 10
>>> # generate Q, b
>>> A = np.random.random((n,n))
>>> Q = A.T.dot(A)
>>> b = np.random.random(n)
\end{lstlisting}
At this point, check to make sure that $Q$ is nonsingular by examining its determinant (use \li{scipy.linalg.det()}).
Provided that the determinant is nonzero, we proceed by writing a function that performs matrix-vector multiplication by $Q$ (we
will not take advantage of sparseness just now), randomly selecting a starting point (Conjugate-Gradient is not sensitive to the location of
the starting point), obtaining the answer using our function, and checking it with the answer obtained by \li{scipy.linalg.solve()}.
\begin{lstlisting}
>>> # generate random starting point
>>> x0 = np.random.random(n)
>>> # find the solution
>>> x = conjugateGradient(b, x0, mult)
>>> # compare to the answer obtained by SciPy
>>> print np.allclose(x, la.solve(Q,b))
\end{lstlisting}
The output of the print statement should be \li{True}.
Time the performance of your algorithm and of \li{scipy.linalg.solve()} on inputs of size 100.
\section*{Application: Least Squares and Linear Regression}
The Conjugate-Gradient method can be used to solve linear least squares problems, which are ubiquitous in applied science.
Recall that a least squares problem can be formulated as an optimization problem:
\[
\min_x \|Ax - b\|_2,
\]
where $A$ is an $m \times n$ matrix with full column rank, $x \in \mathbb{R}^n$, and $b \in \mathbb{R}^m$. The solution can
be calculated analytically, and is given by
\[
x^* = (A^TA)^{-1}A^Tb,
\]
or in other words, the minimizer solves the linear system
\[
A^TAx = A^Tb.
\]
Since $A$ has full column rank, we know that $A^TA$ is an $n \times n$ matrix of rank $n$, which means it is invertible. We can
therefore conclude that $A^TA$ is symmetric positive-definite, so we may use Conjugate-Gradient to solve the linear system
and obtain the least squares solution.
Linear least squares is the mathematical underpinning of linear regression, which is a very common technique in many scientific fields.
In a typical linear regression problem, we have a set of real-valued data points \{$y_1,\ldots, y_m\}$, where each
$y_i$ is paired with a corresponding set of predictor variables $\{x_{i,1}, x_{i,2}, \ldots, x_{i,n}\}$ with $n < m$.
The linear regression model posits that
\[
y_i = \beta_0 + \beta_1x_{i,1} + \beta_2x_{i,2} + \cdots + \beta_nx_{i,n} + \epsilon_i
\]
for $i = 1, 2, \ldots, m$. The real numbers $\beta_0,\ldots,\beta_n$ are known as the parameters of the model, and the
$\epsilon_i$ are independent normally-distributed error terms. Our task is to calculate the parameters that best fit the data.
This can be accomplished by posing the problem in terms of linear least squares: Define
\[
b = [y_1, \ldots, y_m]^T,
\]
\[
A =
\begin{bmatrix}
1 & x_{1,1} & x_{1,2} & \cdots & x_{1,n}\\
1 & x_{2,1} & x_{2,2} & \cdots & x_{2,n}\\
\vdots & \vdots & \vdots & \ddots & \vdots\\
1 & x_{m,1} & x_{m,2} & \cdots & x_{m,n}
\end{bmatrix},
\]
and
\[
x = [\beta_0, \beta_1,\ldots, \beta_n]^T.
\]
Now use Conjugate-Gradient to solve the system
\[
A^TAx = A^Tb.
\]
The solution $x^* = [\beta_0^*, \beta_1^*, \ldots, \beta_n^*]^T$ gives the parameters that best fit the data.
These values can be understood as defining the hyperplane that best fits the data. See Figure \ref{fig:linregression}.
\begin{figure}
\centering
\includegraphics[width=\textwidth]{linregression.pdf}
\caption{Solving the Linear Regression problem results in a best-fit hyperplane.}
\label{fig:linregression}
\end{figure}
\begin{problem}
Using your Conjugate-Gradient function, solve the linear regression problem specified by the data contained in the file
\texttt{linregression.txt}. This is a whitespace-delimited text file formatted so that the $i$-th row consists of
$y_i, x_{i,1}, \ldots, x_{i,n}$. Use the function \li{numpy.loadtxt()} to load in the data. Report your solution.
\end{problem}
\section*{Non-linear Conjugate-Gradient Algorithms}
The algorithm presented above is only valid for certain linear systems and quadratic functions, but the basic strategy may be adapted
to minimize more general convex or non-linear functions. There are multiple ways to modify the algorithm, and they all involve getting
rid of $Q$, since there is no such $Q$ for non-quadratic functions. Generally speaking, we need to find new formulas for $\alpha_k$,
$r_k$, and $\beta_k$.
The scalar $\alpha_k$ is simply the result of performing a line-search in the given direction $d_k$, so we may define
\[
\alpha_k = \underset{x}{\arg\min}f(x_k + \alpha d_k).
\]
The vector $r_k$ in the original algorithm was really just the gradient of the objective
function, and so we may define
\[
r_k = \nabla f(x_k).
\]
There are various ways to define the constants $\beta_k$ in this more general setting, and the
right choice will depend on the nature of the objective function. A well-known formula, due to Fletcher and Reeves, is
\[
\beta_{k+1} = \frac{\nabla f_{k+1}^T \nabla f_{k+1}}{\nabla f_{k}^T \nabla f_{k}}.
\]
Making these adjustments is not difficult, but we will opt instead to use built-in functions in Python. In particular,
the SciPy module \li{scipy.optimize} provides a function \li{fmin_cg()}, which uses a non-linear Conjugate-Gradient method
to minimize general functions. Using this function is easy -- we only need to pass to it the objective function and an
initial guess.
\section*{Application: Logistic Regression}
Logistic regression is an important technique in statistical analysis and classification. The core problem in
logistic regression involves an optimization that we can tackle using nonlinear Conjugate-Gradient.
As in linear regression, we have a set of data points $y_i$ together with predictor variables
$x_{i,1}, x_{i,2}, \ldots, x_{i,n}$ for $i = 1, \ldots, m$. However, the $y_i$ are binary data points --
that is, they are either $0$ or $1$. Furthermore, instead of having a linear relationship between the
data points and the response variables, we assume the following probabilistic relationship:
\[
\mathbb{P}(y_i = 1 \, | \, x_{i,1}, \ldots, x_{i,n}) = p_i,
\]
where
\[
p_i = \frac{1}{1+\exp(-(\beta_0 + \beta_1x_{i,1} + \cdots + \beta_nx_{i,n}))}.
\]
The parameters of the model are the real numbers $\beta_0, \beta_1,\ldots, \beta_n$.
Observe that we have $p_i \in (0, 1)$ regardless of the values of the predictor variables and parameters.
The probability of observing the data points $y_i$ under this model, assuming they are independent, is given by
the expression
\[
\prod_{i=1}^m p_i^{y_i}(1-p_i)^{1-y_i}.
\]
We seek to choose the parameters $\beta_0, \ldots, \beta_n$ that maximize this probability.
To this end, define the \emph{likelihood function} $L:\mathbb{R}^{n+1} \rightarrow \mathbb{R}$ by
\[
L(\beta_0, \ldots, \beta_n) = \prod_{i=1}^m p_i^{y_i}(1-p_i)^{1-y_i}.
\]
We can now state our core problem as follows:
\[
\max_{(\beta_0,\ldots,\beta_n)}L(\beta_0, \ldots, \beta_n).
\]
Maximizing this function can be problematic for numerical reasons. By taking the logarithm of the likelihood,
we have a more suitable objective function whose maximizer agrees with that of the original likelihood function,
since the logarithm is strictly monotone increasing. Thus, we define the \emph{log-likelihood function}
$l : \mathbb{R}^{n+1} \rightarrow \mathbb{R}$ by $l = \log \circ L$.
Finally, we multiply by $-1$ to turn our problem into minimization. The final statement of the problem is:
\[
\min_{(\beta_0,\ldots,\beta_n)}-l(\beta_0, \ldots, \beta_n).
\]
A few lines of calculation reveal that
\begin{align*}
l(\beta_0,\ldots,\beta_n) = &-\sum_{i=1}^{m}\log(1+\exp(-(\beta_0 + \beta_1x_{i,1} + \cdots +\beta_nx_{i,n}))) +\\
&\sum_{i=1}^m y_i(\beta_0 + \beta_1x_{i,1} + \cdots + \beta_nx_{i,n}).
\end{align*}
The values for the parameters that we obtain are known collectively as the \emph{maximum likelihood estimate}.
Let's work through a simple example. We will deal with just one predictor variable, and therefore two parameters.
The data is given in Table \ref{table:data}.
This is obviously just toy data with no meaning, but one can think of the $y_i$ data points as indicating, for example, the
presence of absence of a particular disease in subject $i$, with $x_i$ being the subject's weight, or age, or something
of the sort.
\begin{table}
\caption{Data for Logistic Regression Example}
\centering
\begin{tabular}{c c}
\hline\hline
$y$ & $x$\\
\hline
0 & 1 \\
0 & 2 \\
0 & 3 \\
0 & 4 \\
1 & 5 \\
0 & 6 \\
1 & 7 \\
0 & 8 \\
1 & 9 \\
1 & 10\\
\hline
\end{tabular}
\label{table:data}
\end{table}
In the code below we initialize our data.
\begin{lstlisting}
>>> y = np.array([0, 0, 0, 0, 1, 0, 1, 0, 1, 1])
>>> x = np.ones((10, 2))
>>> x[:,1] = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
\end{lstlisting}
Although we have just one predictor variable, we initialized \li{x} with two columns,
the first of which consists entirely of ones, and the second of which contains the values of the
predictor variable. This extra column of ones corresponds to the parameter $\beta_0$, which, as you
will note, is not multiplied by any of the predictor variables in the log-likelihood function.
We next need to write a Python function that returns the value of our objective function for any value of the parameters,
$(\beta_0, \beta_1)$.
\begin{lstlisting}
>>> def objective(b):
... #Return -1*l(b[0], b[1]), where l is the log likelihood.
... return (np.log(1+np.exp(x.dot(b))) - y*(x.dot(b))).sum()
\end{lstlisting}
Finally, we minimize the objective function using \li{fmin_cg()}.
\begin{lstlisting}
>>> guess = np.array([1., 1.])
>>> b = fmin_cg(objective, guess)
Optimization terminated successfully.
Current function value: 4.310122
Iterations: 13
Function evaluations: 128
Gradient evaluations: 32
>>> print b
[-4.35776886 0.66220658]
\end{lstlisting}
We can visualize our answer by plotting the data together with the function
\[
\phi(x) = \frac{1}{1 + \exp(-\beta_0 - \beta_1x)},
\]
using the values $\beta_0, \beta_1$ that we obtained from the minimization.
\begin{lstlisting}
>>> dom = np.linspace(0, 11, 100)
>>> plt.plot(x, y, 'o')
>>> plt.plot(dom, 1./(1+np.exp(-b[0]-b[1]*dom)))
>>> plt.show()
\end{lstlisting}
Using this procedure, we obtain the plot in Figure \ref{conj:logreg}. Note that the graph of $\phi$, known as a \emph{sigmoidal curve},
gives the probability of $y$ taking the value $1$ at a particular value of $x$. Observe that as $x$ increases,
this probability approaches $1$. This is reflected in the data.
\begin{figure}
\centering
\includegraphics[width=\textwidth]{logreg.pdf}
\caption{Data from the logistic regression example together with the calculated
sigmoidal curve.}
\label{conj:logreg}
\end{figure}
\begin{problem}
Following along with the example given above, find the maximum likelihood estimate of the parameters for
the logistic regression data in the file \texttt{logregression.txt}. This is a whitespace-delimited text file
formatted so that the $i$-th row consists of $y_i, x_{i,1}, x_{i,2}, x_{i,3}.$ Since there are three
predictor variables, there are four parameters in the model. Report the calculated values.
You should be able to use much of the code above unchanged. In particular, the function \li{objective()} does
not need any changes. You simply need to set your variables \li{y} and \li{x} appropriately, and
choose a new initial guess (an array of length four). Note that \li{x} should be an $m \times 4$ array whose first
column consists entirely of ones, whose second column contains the values in the second column of the data file,
and so forth.
\end{problem}
Logistic regression can become a bit more tricky when some of the predictor variables take on binary or categorical
values. In such situations, the data requires a bit of pre-processing before running the minimization.
The values of the parameters that we obtain can be useful in analyzing relationships
between the predictor variables and the $y_i$ data points. They can also be used to classify or predict values of new
data points.
%should I give the Polak-Ribi\`{e}, Fletcher-Reeves, and Hestenes-Stiefel formulas? Maybe in the exercises? Should I
%include a discussion of when each choice is appropriate?
|
{
"alphanum_fraction": 0.7398941171,
"author": null,
"avg_line_length": 51.1670886076,
"converted": null,
"ext": "tex",
"file": null,
"hexsha": "3e9c446d51decdb780c2b633e3c289a7e688aaef",
"include": null,
"lang": "TeX",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z",
"max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173",
"max_forks_repo_licenses": [
"CC-BY-3.0"
],
"max_forks_repo_name": "joshualy/numerical_computing",
"max_forks_repo_path": "Vol2B/ConjugateGradient/ConjugateGradient.tex",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-3.0"
],
"max_issues_repo_name": "joshualy/numerical_computing",
"max_issues_repo_path": "Vol2B/ConjugateGradient/ConjugateGradient.tex",
"max_line_length": 151,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173",
"max_stars_repo_licenses": [
"CC-BY-3.0"
],
"max_stars_repo_name": "joshualy/numerical_computing",
"max_stars_repo_path": "Vol2B/ConjugateGradient/ConjugateGradient.tex",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5642,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 20211
}
|
#!/usr/bin/env python
from matplotlib import use as mpl_use
mpl_use('Agg')
import matplotlib.pyplot as plt
import torch
from multiprocessing import cpu_count
import torch.optim as optim
import torch.nn.functional as F
import torch.multiprocessing as mp
import numpy as np
from torch.autograd import Variable
import pyximport
pyximport.install()
from deep_cfNA.bed_utils import data_generator, prediction_generator
from utils.progress import progress
from utils.model import Deep_cfNA, calculate_metrics
import time
## SET
torch.set_num_threads(cpu_count())
N_PADDED=True
def validate(test_bed, fa, model_file):
'''
run validation by a feature generator
'''
model = Deep_cfNA()
model.load_state_dict(torch.load(model_file))
model.eval()
print('Loaded model: ', model_file)
pred_Y = []
Y = []
for X, lines in prediction_generator(test_bed, fa, batch_size = 500, N_padded=N_PADDED):
X = tensor_convertor(X)
pred = model(X)
pred_Y.extend(pred.reshape(-1).numpy())
y = [line.split('\t')[-1] for line in lines]
Y.extend(y)
loss = F.binary_cross_entropy(torch.Tensor(pred_Y), torch.Tensor(y))
calculate_metrics(Y, pred_Y, loss.item())
def tensor_convertor(X, y=None):
X = torch.Tensor([x.transpose() for x in X])
if y is not None:
X.requires_grad_()
y = torch.Tensor(y)
return X, y
else:
return X
def deep_train(data_iterator, model, epoch=0, steps=500):
'''
training for one epoch
'''
optimizer = optim.Adam(model.parameters(),
lr = 0.001)
print('Start training epoch %i.....' %epoch)
losses = []
for step in range(steps):
start = time.time()
optimizer.zero_grad()
# get data
X, y = next(data_iterator)
X, y = tensor_convertor(X, y=y)
assert X.shape==(data_iterator.batch_size,5, 400) or \
X.shape==(data_iterator.batch_size + 1,5,400), \
X.shape
#get prediction (forward)
pred_y = model(X)
pred_y = pred_y.view(-1)
assert sum(pred_y != pred_y).item() == 0, pred_y
loss = F.binary_cross_entropy(pred_y, y)
losses.append(loss)
# update gradient
loss.backward()
optimizer.step()
end = time.time()
status = '%i/%i step\tloss:%.3f\tused: %.3fs' \
%(step, steps, loss.item(), end-start)
progress(steps, step, epoch + 1, status)
calculate_metrics(y, pred_y, epoch + 1, loss.item())
return losses
def plot_loss(losses, steps, epoch):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(losses)
ax.vlines(x = steps*np.arange(1, epoch),
ymin = min(losses),
ymax = max(losses))
ax.set_xlabel('Iteration')
ax.set_ylabel('Loss (cross entropy)')
fig.savefig('loss.png')
def train(RNA_bed, DNA_bed, fa):
'''
control training
'''
model = Deep_cfNA()
model.train()
model.initialize_weight()
batch_size = 500
epochs = 40
steps = 10000
losses = [10000]
epoch = 0
l = 0
while epoch < epochs or l > losses[-1]:
data_iterator = data_generator(RNA_bed, DNA_bed, fa,
batch_size=batch_size,
N_padded = N_PADDED,
seed = epoch)
l = deep_train(data_iterator, model, epoch + 1, steps = steps)
losses.extend(l)
epoch += 1
# output result
plot_loss(losses[1:], steps, epochs)
return model
def main():
work_dir = '/stor/work/Lambowitz/cdw2854/cell_Free_nucleotides/tgirt_map/classifier'
DNA_bed = work_dir + '/train_DNA.bed'
RNA_bed = work_dir + '/train_RNA.bed'
test_bed = work_dir + '/test.bed'
fa = '/stor/work/Lambowitz/ref/hg19/genome/hg19_genome.fa'
model_file = work_dir + '/pytorch_cfNA.pt'
model = train(RNA_bed, DNA_bed, fa)
if model_file:
torch.save(model.state_dict(), model_file)
print('Saved: ', model_file)
if __name__ == '__main__':
main()
|
{
"alphanum_fraction": 0.6014302741,
"author": null,
"avg_line_length": 26.7197452229,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "1ef7056a9be56fe2be268b172a622ec9e4608f71",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "fa6975b01485320f84ed54f08b90a035972fdf14",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "wckdouglas/deep_cfNA",
"max_forks_repo_path": "pytorch/pytorch_cfNA.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fa6975b01485320f84ed54f08b90a035972fdf14",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "wckdouglas/deep_cfNA",
"max_issues_repo_path": "pytorch/pytorch_cfNA.py",
"max_line_length": 92,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fa6975b01485320f84ed54f08b90a035972fdf14",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "wckdouglas/deep_cfNA",
"max_stars_repo_path": "pytorch/pytorch_cfNA.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1045,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4195
}
|
from __future__ import print_function
import deepchem as dc
import numpy as np
import tensorflow as tf
from sklearn.metrics import accuracy_score
# Load the data.
tasks, datasets, transformers = dc.molnet.load_toxcast()
(train_dataset, valid_dataset, test_dataset) = datasets
x = train_dataset.X
y = train_dataset.y
w = train_dataset.w
n_features = x.shape[1]
n_molecules = y.shape[0]
n_tasks = y.shape[1]
# Toxcast has data on 6874 molecules and 617 tasks. However, the data is very
# sparse: most tasks do not include data for most molecules. It also is very
# unbalanced: there are many more negatives than positives. For each task,
# create a list of alternating postives and negatives so each batch will have
# equal numbers of both.
task_molecules = []
for i in range(n_tasks):
positives = [j for j in range(n_molecules) if w[j, i] > 0 and y[j, i] == 1]
negatives = [j for j in range(n_molecules) if w[j, i] > 0 and y[j, i] == 0]
np.random.shuffle(positives)
np.random.shuffle(negatives)
mols = sum((list(x) for x in zip(positives, negatives)), [])
task_molecules.append(mols)
# Create the model to train. We use a simple fully connected network with
# one hidden layer.
model = dc.models.MultitaskClassifier(
1, n_features, layer_sizes=[1000], dropouts=[0.0])
model.build()
# Define a MetaLearner describing the learning problem.
class ToxcastLearner(dc.metalearning.MetaLearner):
def __init__(self):
self.n_training_tasks = int(n_tasks * 0.8)
self.batch_size = 10
self.batch_start = [0] * n_tasks
self.set_task_index(0)
@property
def loss(self):
return model.loss
def set_task_index(self, index):
self.task = index
def select_task(self):
self.set_task_index((self.task + 1) % self.n_training_tasks)
def get_batch(self):
task = self.task
start = self.batch_start[task]
mols = task_molecules[task][start:start + self.batch_size]
labels = np.zeros((self.batch_size, 1, 2))
labels[np.arange(self.batch_size), 0, y[mols, task].astype(np.int64)] = 1
weights = np.ones((self.batch_size, 1))
feed_dict = {}
feed_dict[model.features[0].out_tensor] = x[mols, :]
feed_dict[model.labels[0].out_tensor] = labels
feed_dict[model.task_weights[0].out_tensor] = weights
if start + 2 * self.batch_size > len(task_molecules[task]):
self.batch_start[task] = 0
else:
self.batch_start[task] += self.batch_size
return feed_dict
# Run meta-learning on 80% of the tasks.
n_epochs = 20
learner = ToxcastLearner()
maml = dc.metalearning.MAML(learner)
steps = n_epochs * learner.n_training_tasks // maml.meta_batch_size
maml.fit(steps)
# Validate on the remaining tasks.
def compute_scores(optimize):
maml.restore()
y_true = []
y_pred = []
losses = []
with model._get_tf("Graph").as_default():
prediction = tf.nn.softmax(model.outputs[0].out_tensor)
for task in range(learner.n_training_tasks, n_tasks):
learner.set_task_index(task)
if optimize:
maml.train_on_current_task()
feed_dict = learner.get_batch()
y_true.append(feed_dict[model.labels[0].out_tensor][:, 0, 0])
y_pred.append(maml._session.run(prediction, feed_dict=feed_dict)[:, 0, 0])
losses.append(maml._session.run(model.loss, feed_dict=feed_dict))
y_true = np.concatenate(y_true)
y_pred = np.concatenate(y_pred)
print()
print('Cross entropy loss:', np.mean(losses))
print('Prediction accuracy:', accuracy_score(y_true, y_pred > 0.5))
print('ROC AUC:', dc.metrics.roc_auc_score(y_true, y_pred))
print()
print('Before fine tuning:')
compute_scores(False)
print('After fine tuning:')
compute_scores(True)
|
{
"alphanum_fraction": 0.711753477,
"author": null,
"avg_line_length": 30.8151260504,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "1623e3084a9c9730f0655d4f8477668b898b5c0c",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-05-19T14:22:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-19T14:22:32.000Z",
"max_forks_repo_head_hexsha": "94809d39b5cee0c1ba178a1936dbf9a95b5eaad7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "abiricz/deepchem",
"max_forks_repo_path": "examples/low_data/toxcast_maml.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "94809d39b5cee0c1ba178a1936dbf9a95b5eaad7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "abiricz/deepchem",
"max_issues_repo_path": "examples/low_data/toxcast_maml.py",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "94809d39b5cee0c1ba178a1936dbf9a95b5eaad7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "abiricz/deepchem",
"max_stars_repo_path": "examples/low_data/toxcast_maml.py",
"max_stars_repo_stars_event_max_datetime": "2019-07-26T16:50:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-07-26T16:50:32.000Z",
"num_tokens": 999,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3667
}
|
import os
from typing import Dict, List
import numpy as np
import torch
import pickle
from overrides import overrides
from datasets.document_dataset_base import DocumentDatasetBase
from services.arguments.ocr_quality_arguments_service import OCRQualityArgumentsService
from services.log_service import LogService
from services.process.word2vec_process_service import Word2VecProcessService
class Word2VecDataset(DocumentDatasetBase):
def __init__(
self,
arguments_service: OCRQualityArgumentsService,
process_service: Word2VecProcessService,
log_service: LogService,
**kwargs):
super().__init__()
self._arguments_service = arguments_service
self._log_service = log_service
self._process_service = process_service
self._text_corpus = process_service.get_text_corpus(ocr_output_type=self._arguments_service.ocr_output_type)
self._log_service.log_debug(f'Loaded {self._text_corpus.length} entries in word2vec dataset')
def __len__(self):
return self._text_corpus.length
def __getitem__(self, id):
return id
def use_collate_function(self) -> bool:
return True
def collate_function(self, ids):
skip_gram_entries = self._text_corpus.get_entries(ids)
batch_size = len(ids)
target_tokens = [x.target_token for x in skip_gram_entries]
context_tokens_lists = [x.context_tokens for x in skip_gram_entries]
lengths = [len(sequence) for sequence in context_tokens_lists]
max_length = max(lengths)
padded_contexts = np.zeros((batch_size, max_length), dtype=np.int64)
for i, l in enumerate(lengths):
padded_contexts[i][0:l] = context_tokens_lists[i][0:l]
return (
torch.from_numpy(padded_contexts).long().to(self._arguments_service.device),
torch.LongTensor(target_tokens).to(self._arguments_service.device))
def get_indices_per_document(self) -> Dict[int, List[int]]:
return self._text_corpus.get_indices_per_document()
|
{
"alphanum_fraction": 0.723709369,
"author": null,
"avg_line_length": 35.4576271186,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "1c5db524d5517468ee1f6a60ecbedaa4b2a8006f",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "d4d7bf0addf5ff98b7182c00ff716e79c97e050e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ktodorov/historical-ocr",
"max_forks_repo_path": "datasets/word2vec_dataset.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d4d7bf0addf5ff98b7182c00ff716e79c97e050e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ktodorov/historical-ocr",
"max_issues_repo_path": "datasets/word2vec_dataset.py",
"max_line_length": 116,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d4d7bf0addf5ff98b7182c00ff716e79c97e050e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ktodorov/historical-ocr",
"max_stars_repo_path": "datasets/word2vec_dataset.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 436,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2092
}
|
"""
Create multiple viewers from the same script
"""
import numpy as np
from skimage import data
import napari
with napari.gui_qt():
# add the image
photographer = data.camera()
viewer_a = napari.view_image(photographer, name='photographer')
# add the image in a new viewer window
astronaut = data.astronaut()
# Also view_path, view_shapes, view_points, view_labels etc.
viewer_b = napari.view_image(astronaut, name='astronaut')
|
{
"alphanum_fraction": 0.7223427332,
"author": null,
"avg_line_length": 24.2631578947,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "70b2c63213206cab4d884fc829134c9615060de8",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "102a7e8f845893c874d2b86f9371d41130100b89",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Zac-HD/napari",
"max_forks_repo_path": "examples/multiple_viewers.py",
"max_issues_count": 17,
"max_issues_repo_head_hexsha": "102a7e8f845893c874d2b86f9371d41130100b89",
"max_issues_repo_issues_event_max_datetime": "2021-02-02T19:10:19.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-11T21:02:03.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Zac-HD/napari",
"max_issues_repo_path": "examples/multiple_viewers.py",
"max_line_length": 67,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "102a7e8f845893c874d2b86f9371d41130100b89",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Zac-HD/napari",
"max_stars_repo_path": "examples/multiple_viewers.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-01T19:38:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-01T19:38:06.000Z",
"num_tokens": 112,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 461
}
|
"""This file can be used to create a new python file that will return
the dictionary of Lebedev quadratures."""
import numpy as np
import sys
def createdict():
"""Create a dictionary based on the quadrature files stored in data/"""
orders = [
3,
5,
7,
9,
11,
13,
15,
17,
19,
21,
23,
25,
27,
29,
31,
35,
41,
47,
53,
59,
65,
71,
77,
83,
89,
95,
101,
107,
113,
119,
125,
131,
]
D = dict()
for order in orders:
xyzw = np.loadtxt("data/" + str(order) + "_lebedev.txt", delimiter=",")
xyzw[:, 3] = xyzw[:, 3] / sum(xyzw[:, 3]) * 4 * np.pi
D[order] = xyzw
return D
def writedict():
"""Dump a dictionary to a python file and add a function definition
first. That way, we can read the dictionary later from that file without
using the files in data/"""
d = createdict()
np.set_printoptions(threshold=sys.maxsize)
np.set_printoptions(precision=15)
with open("writtendict.py", "w") as f:
mystring = (
"from numpy import array\n"
"def lebedevdictionary():\n"
"\treturn (" + str(d) + ")"
)
print(mystring, file=f)
|
{
"alphanum_fraction": 0.4842857143,
"author": null,
"avg_line_length": 20.5882352941,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "34cfdbc1d789c6b36efe8bb479ac085391fb5eca",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-12-19T21:12:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-19T21:12:59.000Z",
"max_forks_repo_head_hexsha": "b54a823db595cc84717954fa84a9fb0d2f52e7b1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ScSteffen/neuralEntropyComparison",
"max_forks_repo_path": "ext/steffensCode/ext/sphericalquadpy/lebedev/createxyzwdict.py",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "b54a823db595cc84717954fa84a9fb0d2f52e7b1",
"max_issues_repo_issues_event_max_datetime": "2019-04-09T08:38:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-04-09T08:38:21.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ScSteffen/neuralEntropyComparison",
"max_issues_repo_path": "ext/steffensCode/ext/sphericalquadpy/lebedev/createxyzwdict.py",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0646547cc69e27de7ce36f4b519d4f420ef443e7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "camminady/sphericalquadpy",
"max_stars_repo_path": "sphericalquadpy/lebedev/createxyzwdict.py",
"max_stars_repo_stars_event_max_datetime": "2020-11-15T23:47:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-15T23:47:48.000Z",
"num_tokens": 397,
"path": null,
"reason": "import numpy,from numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1400
}
|
import numpy
import data_algebra
from data_algebra.data_ops import *
import data_algebra.test_util
def test_simple_expr_1():
d_orig = data_algebra.default_data_model.pd.DataFrame({"x": [1.0, 2.0, -3.0, 4.0]})
d = d_orig.copy()
ops = describe_table(d, table_name="d").extend(
{
"z": "x + 1",
"sin_x": "x.sin()", # triggers numpy path
"xm": "-x",
"xs": "2 * (x-2).sign()",
}
)
expect = data_algebra.default_data_model.pd.DataFrame({"x": [1.0, 2.0, -3.0, 4.0]})
expect["z"] = expect["x"] + 1
expect["sin_x"] = numpy.sin(expect["x"])
expect["xm"] = -expect["x"]
expect["xs"] = 2 * numpy.sign(d["x"] - 2)
data_algebra.test_util.check_transform(ops=ops, data=d, expect=expect)
assert d.equals(d_orig)
|
{
"alphanum_fraction": 0.5684340321,
"author": null,
"avg_line_length": 27.0333333333,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "cde7c83fd7dcca10996340f09dd92f48894a05eb",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-02-08T19:22:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-08-28T12:23:11.000Z",
"max_forks_repo_head_hexsha": "3d6002ddf8231d310e03537a0435df0554b62234",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "WinVector/data_algebra",
"max_forks_repo_path": "tests/test_simple_expr.py",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3d6002ddf8231d310e03537a0435df0554b62234",
"max_issues_repo_issues_event_max_datetime": "2019-09-08T01:43:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-02T23:13:29.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "WinVector/data_algebra",
"max_issues_repo_path": "tests/test_simple_expr.py",
"max_line_length": 87,
"max_stars_count": 37,
"max_stars_repo_head_hexsha": "3d6002ddf8231d310e03537a0435df0554b62234",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "WinVector/data_algebra",
"max_stars_repo_path": "tests/test_simple_expr.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T21:18:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-28T08:16:48.000Z",
"num_tokens": 259,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 811
}
|
[STATEMENT]
lemma vector_space_pair_with[explicit_ab_group_add]:
"vector_space_pair s1 s2 \<longleftrightarrow> vector_space_pair_on_with UNIV UNIV (+) (-) uminus 0 s1 (+) (-) uminus 0 s2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. vector_space_pair s1 s2 = vector_space_pair_on_with UNIV UNIV (+) (-) uminus (0::'b) s1 (+) (-) uminus (0::'c) s2
[PROOF STEP]
by (auto simp: module_pair_on_with_def explicit_ab_group_add
vector_space_pair_on_with_def vector_space_pair_def module_on_with_def vector_space_on_with_def)
|
{
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": 1,
"llama_tokens": 217,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": null
}
|
#!/usr/bin/env python
# coding: utf-8
# In[Load Packages]:
# Basic code for Artificial Neural Network for tensorflow lite
# September 2021
# adapted from Alzahra Hamdan (August 2021)
# load tensorflow and keras
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import models, layers, optimizers, initializers, Sequential
from tensorflow.keras.layers.experimental import preprocessing
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error, roc_curve, auc
from sklearn.model_selection import cross_val_score, KFold, StratifiedKFold
from sklearn.inspection import permutation_importance
from sklearn.metrics import precision_recall_curve, f1_score
#helper libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from json import JSONEncoder
# Make numpy printouts easier to read.
#import tflite_runtime.interpreter as tflite
np.set_printoptions(precision=3, suppress=True)
print(tf.__version__)
# In[Define StratifiedKFold ]:
# Define the cross-validator object for regression, which inherits from
# StratifiedKFold, overwritting the split method
#code source: https://colab.research.google.com/drive/1KnXujsQDvLZOgCRg_iis036cwffwZM2_?usp=sharing#scrollTo=2q_q9w8Jpmwd
# &https://github.com/scikit-learn/scikit-learn/issues/4757
random_seed=4242
random.set_seed = random_seed
class StratifiedKFoldReg(StratifiedKFold):
"""
This class generate cross-validation partitions
for regression setups, such that these partitions
resemble the original sample distribution of the
target variable.
"""
def split(self, X, y, groups=None):
n_samples = len(y)
# Number of labels to discretize our target variable,
# into bins of quasi equal size
n_labels = int(np.round(n_samples/self.n_splits))
# Assign a label to each bin of n_splits points
y_labels_sorted = np.concatenate([np.repeat(ii, self.n_splits) for ii in range(n_labels)])
# Get number of points that would fall
# out of the equally-sized bins
mod = np.mod(n_samples, self.n_splits)
# Find unique idxs of first unique label's ocurrence
_, labels_idx = np.unique(y_labels_sorted, return_index=True)
# sample randomly the label idxs to which assign the
# the mod points
rand_label_ix = np.random.choice(labels_idx, mod, replace=False)
# insert these at the beginning of the corresponding bin
y_labels_sorted = np.insert(y_labels_sorted, rand_label_ix, y_labels_sorted[rand_label_ix])
# find each element of y to which label corresponds in the sorted
# array of labels
map_labels_y = dict()
for ix, label in zip(np.argsort(y), y_labels_sorted):
map_labels_y[ix] = label
# put labels according to the given y order then
y_labels = np.array([map_labels_y[ii] for ii in range(n_samples)])
return super().split(X, y_labels, groups)
# In[Import dataset]:
#load data
raw_dataset = pd.read_csv('merged_datasets_for_simeval.csv')
dataset = raw_dataset.copy()
dataset.drop(['dofv', 'ID', 'Study_ID', 'Model_number', 'lin_model'], axis = 1, inplace=True)
dataset.head()
#split features and labels
x = dataset.copy()
Y = x.pop('residual')
X = x.values
# In[Create 3 layer ANN model]:
layer = tf.keras.layers.Normalization(axis=1)
layer.adapt(X)
def create_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Input(shape=X.shape),
layer,
tf.keras.layers.Dense(48, activation='relu'),
tf.keras.layers.Dense(24, activation='relu'),
tf.keras.layers.Dense(12, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(1)
])
model.compile(optimizer=optimizers.RMSprop(learning_rate=0.00007), loss='mse')
return model
# Create a basic model instance
model = create_model()
# Display the model's architecture
model.summary()
# In[Run Kfold Cross validation ]:
# Set up empty vectors for outputs
loss_per_fold = [] #to store test loss value in each fold
Train_loss_per_fold = [] #to store training loss value in each fold
predicted_y = np.array([]) #to store predicted residual value from each CV fold
true_y = np.array([]) #to store true residual value from each CV fold
num_folds = 10
# cross validated stratification to keep ratios same across each split
cv_stratified = StratifiedKFoldReg(n_splits=num_folds, shuffle=True, random_state=10)
fold_no = 1
for ii, (train_index, test_index) in enumerate(cv_stratified.split(X, Y)):
Y_train, Y_test = Y[train_index], Y[test_index]
X_train, X_test = X[train_index], X[test_index]
# Fit data to model
history = model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=200, verbose=0)
#to store values for plotting global predicted vs. true residual values
test_predictions = model.predict(X_test).flatten()
predicted_y = np.append(predicted_y, test_predictions)
y_test_array = Y_test.values
true_y = np.append(true_y, y_test_array)
# Print fold_no during training
print('------------------------------------------------------------------------')
print(f'Training for fold {fold_no} ...')
print('------------------------------------------------------------------------')
# Generate generalization metrics
scores = model.evaluate(X_test, Y_test, verbose=0)
print(f'Score for fold {fold_no}: {model.metrics_names} of {scores}')
scores_training = model.evaluate(X_train, Y_train, verbose=0)
print(f'Training Score for fold {fold_no}: {model.metrics_names} of {scores_training}')
loss_per_fold.append(scores)
Train_loss_per_fold.append(scores_training)
# Generate a print
print('------------------------------------------------------------------------')
print(f'Training for fold {fold_no} ...')
test_labels = Y_test.to_list()
test_labels = [round(num, 2) for num in test_labels]
print(test_labels) #to have a look at the true residual values for test dataset
# Increase fold number
fold_no = fold_no + 1
# In[Summarise output]:
print('----------------------- Influential Individual Summary ---------------------------------------')
print('4 hidden layers (Nodes: 64, 32, 24, 12)')
print(f'learning rate: 0.00007, number of epochs: 200')
print(f'Average scores for all {fold_no} folds:')
print(f'Testing Loss: {np.mean(loss_per_fold): 0.4f} ({min(loss_per_fold):0.4f}-{max(loss_per_fold):0.4f})')
print(f'Training Loss: {np.mean(Train_loss_per_fold): 0.4f} ({min(Train_loss_per_fold):0.4f}-{max(Train_loss_per_fold):0.4f})')
print('----------------------------------------------------------------------------------------------')
# In[Plot prediction]:
# a = plt.axes(aspect='equal')
# plt.scatter(predicted_y, true_y)
# plt.xlabel('Predictions [residual]')
# plt.ylabel('True Values [residual]')
# lims = [-5, 20]
# plt.xlim(lims)
# plt.ylim(lims)
# prediction_plot = plt.plot(lims, lims)
# In[permutation importance]:
feature_name = ['Model_subjects', 'Model_observations',
'Obsi_Obs_Subj', 'Covariate_relations', 'Max_cov', 'Max_CWRESi', 'Median_CWRESi',
'Max_EBEij_omegaj', 'OFVRatio', 'mean_ETC_omega']
r = permutation_importance(model, X, y,
n_repeats=30,
random_state=0, scoring='neg_mean_squared_error')
for i in r.importances_mean.argsort()[::-1]:
if r.importances_mean[i] - 2 * r.importances_std[i] > 0:
print(f"{feature_name[i]:<10}"
f"{r.importances_mean[i]:.3f}"
f" +/- {r.importances_std[i]:.3f}")
# In[Save model and convert to tflite]:
# Save model and convert to tflite
# tf.saved_model.save(ANN5,'path/ML_CDD_simeval/ml-devel/outlier')
# tflite_model = tf.lite.TFLiteConverter.from_saved_model('path/ML_CDD_simeval/ml-devel/outlier').convert()
# with open('path/ML_CDD_simeval/ml-devel/outlier/outliers.tflite', 'wb') as f:
# f.write(tflite_model)
# convert directly
tflite_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
with open('path/ML_CDD_simeval/ml-devel/outlier/outliers_test.tflite', 'wb') as f:
f.write(tflite_model)
# In[Test tensorflow model]:
model.save('ml-devel/outlier/SC_testing' )
#%%
# read in tensorflow model and test
new_model = tf.keras.models.load_model('ml-devel/outlier/SC_testing')
new_model.summary()
#%%
raw_data = pd.read_csv('merged_datasets_for_simeval.csv')
rawdat1 = raw_data.copy()
is_test1 = rawdat1['Model_number']=='PRZrun4'
rawdat1 = rawdat1[is_test1]
rawdat1.drop(['dofv', 'ID', 'Study_ID', 'Model_number', 'lin_model', 'residual'],
axis = 1,
inplace = True)
# print(rawdat1.head())
test1 = new_model.predict(rawdat1)
print(test1)
#rawdat2 = rawdat1.copy
#rawdat2 = rawdat1.astype(np.float32)
# print(rawdat1.head())
# read in tensorflow model and test
#test2 = new_model.predict(rawdat2)
#print(test2)
#%%
# # code from: https://pynative.com/python-serialize-numpy-ndarray-into-json/
# class NumpyArrayEncoder(JSONEncoder):
# def default(self, obj):
# if isinstance(obj, np.ndarray):
# return obj.tolist()
# return JSONEncoder.default(self, obj)
# # load trained outlier model
# model = tf.keras.models.load_model('path/ML_CDD_simeval/outlier')
# # set up empty arrays
# out_conf = ()
# out_wt = ()
# # get NN configuration and weights
# for layer in model.layers:
# print(f'config out: {layer.get_config()}')
# print('------------------------------------------')
# print(f'weights: {layer.get_weights()}')
# print('------------------------------------------')
# out_conf = np.append(out_conf, layer.get_config())
# out_wt = np.append(out_wt, layer.get_weights())
# first_layer_weights = model.layers[0].get_weights()[0]
# print('first layer weights: {first_layer_weights}')
#%%
# convert to json and save
# outlier_conf = {'array':out_conf}
# OutlierMod = json.dumps(outlier_conf, cls=NumpyArrayEncoder)
# with open("OutlierMod.json", "w") as json_file:
# json_file.write(OutlierMod)
# print('Saved model to disk')
# convert to json and save
# out_wt = out_wt.astype(np.float32)
# outlier_wts = {'array':out_wt}
# OutlierWts = json.dumps(outlier_wts, cls=NumpyArrayEncoder)
# with open("OutlierWts.json", "w") as json_file:
# json_file.write(OutlierWts)
# print('Saved weights to disk')
# outlier_mod = out_conf.to_json()
# with open("outlier_mod.json", "w") as json_file:
# json_file.write(outlier_mod)
# print('Saved model to disk')
# outlier_wts = out_wt.to_json()
# with open("outlier_wts.json", "w") as json_file:
# json_file.write(outlier_wts)
# print('Saved weights to disk')
#%%
# # serialize model to JSON
# outlier_mod = model.to_json()
# with open("outlier_mod.json", "w") as json_file:
# json_file.write(outlier_mod)
# # serialize weights to HDF5
# model.save_weights("outlier_mod_wt.h5")
# print("Saved model to disk")
|
{
"alphanum_fraction": 0.6708169115,
"author": null,
"avg_line_length": 33.0295857988,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "c6fb742cd8b3de429badaff422c543f2aff0d225",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "6c97bd71b58aee0deac207fce41c3e001786e779",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "pharmpy/ml-devel",
"max_forks_repo_path": "outlier/SC_testing/Simeval_ANN_test.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6c97bd71b58aee0deac207fce41c3e001786e779",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "pharmpy/ml-devel",
"max_issues_repo_path": "outlier/SC_testing/Simeval_ANN_test.py",
"max_line_length": 127,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6c97bd71b58aee0deac207fce41c3e001786e779",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "pharmpy/ml-devel",
"max_stars_repo_path": "outlier/SC_testing/Simeval_ANN_test.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2824,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 11164
}
|
# Mass Maps From Mass-Luminosity Inference Posterior
In this notebook we start to explore the potential of using a mass-luminosity relation posterior to refine mass maps.
Content:
- [Math](#Math)
- [Imports, Constants, Utils, Data](#Imports,-Constants,-Utils,-Data)
- [Probability Functions](#Probability-Functions)
- [Results](#Results)
- [Discussion](#Discussion)
### Math
Infering mass from mass-luminosity relation posterior ...
\begin{align}
P(M|L_{obs},z,\sigma_L^{obs}) &= \iint P(M|\alpha, S, L_{obs}, z)P(\alpha, S|L_{obs},z,\sigma_L^{obs})\ d\alpha dS\\
&\propto \iiint P(L_{obs}| L,\sigma_L^{obs})P(L|M,\alpha,S,z)P(M|z)P(\alpha, S|L_{obs},z,\sigma_L^{obs})\ dLd\alpha dS\\
&\approx \frac{P(M|z)}{n_{\alpha,S}}\sum_{\alpha,S \sim P(\alpha, S|L_{obs},z,\sigma_L^{obs})}\left( \frac{1}{n_L}\sum_{L\sim P(L|M,\alpha,S,z)}P(L_{obs}|L,\sigma_L^{obs})\right)\\
&= \frac{P(M|z)}{n_{\alpha,S}}\sum_{\alpha,S \sim P(\alpha, S|L_{obs},z,\sigma_L^{obs})}f(M;\alpha,S,z)\\
\end{align}
Refine for individual halo ...
\begin{align}
P(M_k|L_{obs},z,\sigma_L^{obs}) &= \iint P(M_k|\alpha, S, L_{obs\ k}, z_k)P(\alpha, S|L_{obs},z,\sigma_L^{obs})\ d\alpha dS\\
&\propto \iiint P(L_{obs\ k}| L_k,\sigma_L^{obs})P(L_k|M_k,\alpha,S,z_k)P(M_k|z_k)P(\alpha, S|L_{obs},z,\sigma_L^{obs})\ dLd\alpha dS\\
&\approx \frac{P(M_k|z_k)}{n_{\alpha,S}}\sum_{\alpha,S \sim P(\alpha, S|L_{obs},z,\sigma_L^{obs})}\left( \frac{1}{n_L}\sum_{L\sim P(L_k|M_k,\alpha,S,z_k)}P(L_{obs\ k}|L_k,\sigma_L^{obs})\right)\\
&=\frac{P(M_k|z_k)}{n_{\alpha,S}}\sum_{\alpha,S \sim P(\alpha, S|L_{obs},z,\sigma_L^{obs})}f(M_k;\alpha,S,z_k)\\
\end{align}
Can also factor it more conventionally for MCMC ...
\begin{align}
\underbrace{P(M_k|L_{obs},z,\sigma_L^{obs})}_{posterior}
&\propto \underbrace{P(M_k|z_k)}_{prior}\underbrace{\iiint P(L_{obs\ k}| L_k,\sigma_L^{obs})P(L_k|M_k,\alpha,S,z_k)P(\alpha, S|L_{obs},z,\sigma_L^{obs})\ dLd\alpha dS}_{likelihood}\\
\end{align}
In the code we have the following naming convention:
- p1 for $P(M|z)$
- p2 for $P(\alpha, S|L_{obs},z,\sigma_L^{obs})$
- p3 for $P(L_k|M_k,\alpha,S,z_k)$
- p4 for $P(L_{obs\ k}|L_k, \sigma^{obs}_L)$
We use the terms **eval** and **samp** to help distinguish between evaluating a distribution and sampling from it.
### Imports, Constants, Utils, Data
```python
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
from bigmali.grid import Grid
from bigmali.prior import TinkerPrior
from bigmali.hyperparameter import get
import numpy as np
from scipy.stats import lognorm
from numpy.random import normal
#globals that functions rely on
grid = Grid()
prior = TinkerPrior(grid)
a_seed = get()[:-1]
S_seed = get()[-1]
mass_points = prior.fetch(grid.snap(0)).mass[2:-2] # cut edges
tmp = np.loadtxt('/Users/user/Code/PanglossNotebooks/MassLuminosityProject/SummerResearch/mass_mapping.txt')
z_data = tmp[:,0]
lobs_data = tmp[:,1]
mass_data = tmp[:,2]
ra_data = tmp[:,3]
dec_data = tmp[:,4]
sigobs = 0.05
def fast_lognormal(mu, sigma, x):
return (1/(x * sigma * np.sqrt(2 * np.pi))) * np.exp(- 0.5 * (np.log(x) - np.log(mu)) ** 2 / sigma ** 2)
```
### Probability Functions
```python
def p1_eval(zk):
return prior.fetch(grid.snap(zk)).prob[2:-2]
def p2_samp(nas=100):
"""
a is fixed on hyperseed,
S is normal distribution centered at hyperseed.
"""
return normal(S_seed, S_seed / 10, size=nas)
def p3_samp(mk, a, S, zk, nl=100):
mu_lum = np.exp(a[0]) * ((mk / a[2]) ** a[1]) * ((1 + zk) ** (a[3]))
return lognorm(S, scale=mu_lum).rvs(nl)
def p4_eval(lobsk, lk, sigobs):
return fast_lognormal(lk, sigobs, lobsk)
def f(a, S, zk, lobsk, nl=100):
ans = []
for mk in mass_points:
tot = 0
for x in p3_samp(mk, a, S, zk, nl):
tot += p4_eval(lobsk, x, sigobs)
ans.append(tot / nl)
return ans
def mass_dist(ind=1, nas=10, nl=100):
lobsk = lobs_data[ind]
zk = z_data[ind]
tot = np.zeros(len(mass_points))
for S in p2_samp(nas):
tot += f(a_seed, S, zk, lobsk, nl)
prop = p1_eval(zk) * tot / nas
return prop / np.trapz(prop, x=mass_points)
```
### Results
```python
plt.subplot(3,3,1)
dist = p1_eval(zk)
plt.plot(mass_points, dist)
plt.gca().set_xscale('log')
plt.gca().set_yscale('log')
plt.ylim([10**-25, 10])
plt.xlim([mass_points.min(), mass_points.max()])
plt.title('Prior')
plt.xlabel(r'Mass $(M_\odot)$')
plt.ylabel('Density')
for ind in range(2,9):
plt.subplot(3,3,ind)
dist = mass_dist(ind)
plt.plot(mass_points, dist, alpha=0.6, linewidth=2)
plt.xlim([mass_points.min(), mass_points.max()])
plt.gca().set_xscale('log')
plt.gca().set_yscale('log')
plt.ylim([10**-25, 10])
plt.gca().axvline(mass_data[ind], color='red', linewidth=2, alpha=0.6)
plt.title('Mass Distribution')
plt.xlabel(r'Mass $(M_\odot)$')
plt.ylabel('Density')
# most massive
ind = np.argmax(mass_data)
plt.subplot(3,3,9)
dist = mass_dist(ind)
plt.plot(mass_points, dist, alpha=0.6, linewidth=2)
plt.gca().set_xscale('log')
plt.gca().set_yscale('log')
plt.xlim([mass_points.min(), mass_points.max()])
plt.ylim([10**-25, 10])
plt.gca().axvline(mass_data[ind], color='red', linewidth=2, alpha=0.6)
plt.title('Mass Distribution')
plt.xlabel(r'Mass $(M_\odot)$')
plt.ylabel('Density')
# plt.tight_layout()
plt.gcf().set_size_inches((10,6))
```
### Turning into Probabilistic Catalogue
```python
index = range(2,9) + [np.argmax(mass_data)]
plt.title('Simple Sketch of Field of View')
plt.scatter(ra_data[index], dec_data[index] , s=np.log(mass_data[index]), alpha=0.6)
plt.xlabel('ra')
plt.ylabel('dec');
```
Need to build graphic:
- Make grid that will correspond to pixels
- map ra-dec window to grid
- snap objects onto grid and accumulate mass in each bin of the grid
- plot the grayscale image
# Discussion
- While this is a simple toy model, the consistency between then predicted mass distribution and true mass is encouraging.
- The noise in the mass distribution plots is interesting. The noise increases for masses that are further away than the truth. A similar effect may also exist in bigmali, could it lead to a failure mode?
- In order to build probabilistic mass maps we will need to be able to sample from the mass distributions. One way to do this would be fitting a normal distribution and drawing from that distribution. This will also mitigate the influence of the noise for masses far from the true mass.
|
{
"alphanum_fraction": 0.903767575,
"author": null,
"avg_line_length": 293.2169811321,
"converted": true,
"ext": "ipynb",
"file": null,
"hexsha": "c9c84f045d7357dc237216cb26b7bb1889131558",
"include": null,
"lang": "Jupyter Notebook",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "719a3b9a5d0e121f0e9bc2a92a968abf7719790f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "davidthomas5412/PanglossNotebooks",
"max_forks_repo_path": "MassLuminosityProject/SummerResearch/MassMapsFromMassLuminosity_20170626.ipynb",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "719a3b9a5d0e121f0e9bc2a92a968abf7719790f",
"max_issues_repo_issues_event_max_datetime": "2017-01-21T02:16:27.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-12-13T02:05:57.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "davidthomas5412/PanglossNotebooks",
"max_issues_repo_path": "MassLuminosityProject/SummerResearch/MassMapsFromMassLuminosity_20170626.ipynb",
"max_line_length": 68576,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "719a3b9a5d0e121f0e9bc2a92a968abf7719790f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "davidthomas5412/PanglossNotebooks",
"max_stars_repo_path": "MassLuminosityProject/SummerResearch/MassMapsFromMassLuminosity_20170626.ipynb",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2138,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 93243
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # S_EllipsoidTestWaitingTimes [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=S_EllipsoidTestWaitingTimes&codeLang=Python)
# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ExerExpiid).
# ## Prepare the environment
# +
import os
import os.path as path
import sys
sys.path.append(path.abspath('../../functions-legacy'))
from numpy import where, diff, linspace
from scipy.io import loadmat
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
plt.style.use('seaborn')
from CONFIG import GLOBAL_DB, TEMPORARY_DB
from ARPM_utils import save_plot, struct_to_dict, date_mtop, time_mtop
from autocorrelation import autocorrelation
from TradeQuoteProcessing import TradeQuoteProcessing
from InvarianceTestEllipsoid import InvarianceTestEllipsoid
# -
# ## Upload the database
try:
db = loadmat(os.path.join(GLOBAL_DB, 'db_US_10yr_Future_quotes_and_trades'), squeeze_me=True)
except FileNotFoundError:
db = loadmat(os.path.join(TEMPORARY_DB, 'db_US_10yr_Future_quotes_and_trades'), squeeze_me=True)
# ## Process the time series, refining the raw data coming from the database
# +
quotes = struct_to_dict(db['quotes'])
trades = struct_to_dict(db['trades'])
dates_quotes = quotes.time_names #
t = quotes.time # time vector of quotes
p_bid = quotes.bid # bid prices
p_ask = quotes.ask # ask prices
q_bid = quotes.bsiz # bid volumes
q_ask = quotes.asiz # ask volumes
dates_trades = trades.time_names #
t_k = trades.time # time vector of trades
p_last = trades.price # last transaction prices
delta_q = trades.siz # flow of traded contracts' volumes
delta_sgn = trades.aggress # trade sign flow
match = trades.mtch # match events: - the "1" value indicates the "start of a match event" while zeros indicates the "continuation of a match event"
# - the db is ordered such that the start of a match event is in the last column corresponding to that event
t, _, _, _, _, _, t_k, *_= TradeQuoteProcessing(t, dates_quotes, q_ask, p_ask, q_bid, p_bid, t_k, dates_trades,
p_last, delta_q, delta_sgn, match)
t = t.flatten()
t_k = t_k.flatten()
# -
# ## Compute the gaps between subsequent events
# +
k_0 = where(t_k >= t[0])[0][0] # index of the first trade within the time window
k_1 = where(t_k <= t[-1])[0][-1] # index of the last trade within the time window_, _, _, h, m, s = datevec(t_k(k_0:k_1))
ms = (date_mtop(t_k[k_1]) - date_mtop(t_k[k_0])).seconds + (date_mtop(t_k[k_1]) - date_mtop(t_k[k_0])).microseconds / 1000
t_ms = linspace(t_k[k_0],t_k[k_1], int(ms)).reshape(1,-1)
t_ms = [time_mtop(i) for i in t_k[k_0:k_1+1]]
t_ms = [3600*i.hour+60*i.minute+i.second+i.microsecond/1e6 for i in t_ms]
delta_t_k = diff(t_ms).reshape(1,-1)
# -
# ## Compute autocorrelations at different lags
# +
lag_ = 10
acf = autocorrelation(delta_t_k, lag_)
# -
# ## Plot the results of the IID test
# +
lag = 10 # lag to be printed
ell_scale = 2 # ellipsoid radius coefficient
fit = 2
# position settings
pos = {}
pos[1]= [.2, .45, .3866, .43] # scatter plot
pos[2]= [.274, .12, .239, .2157] # epsi
pos[3]= [.07, .45, .1337, .43] # epsi_lagged
pos[4]= [.63, .45, .3366, .43] # autocorrelation
pos[5]= [.06, .235, .11, .1] # leg
f = figure(figsize=(12,6))
InvarianceTestEllipsoid(delta_t_k, acf[0,1:], lag_, fit, ell_scale, pos,
'Invariance test on High Frequency waiting times $\Delta$ $t_{\kappa}$', [-5, 0]);
# save_plot(ax=plt.gca(), extension='png', scriptname=os.path.basename('.')[:-3], count=plt.get_fignums()[-1])
|
{
"alphanum_fraction": 0.6892230576,
"author": null,
"avg_line_length": 33.5294117647,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "857ec3e8d453b84c667b15295a1392e1a6b82ec5",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2022-02-09T17:49:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-08-13T22:02:17.000Z",
"max_forks_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dpopadic/arpmRes",
"max_forks_repo_path": "scripts/sources/S_EllipsoidTestWaitingTimes.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dpopadic/arpmRes",
"max_issues_repo_path": "scripts/sources/S_EllipsoidTestWaitingTimes.py",
"max_line_length": 225,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dpopadic/arpmRes",
"max_stars_repo_path": "scripts/sources/S_EllipsoidTestWaitingTimes.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T08:20:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-10T13:24:30.000Z",
"num_tokens": 1192,
"path": null,
"reason": "from numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3990
}
|
import os
import shutil
import pickle as pkl
import argparse
import tensorflow as tf
from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from sklearn.preprocessing import MinMaxScaler, scale
IMAGE_SIZE = 50
def log(x):
return tf.log(x + 1e-8)
def xavier_init(size):
in_dim = size[0]
xavier_stddev = 1. / tf.sqrt(in_dim / 2.)
return tf.random_normal(shape=size, stddev=xavier_stddev)
def sample_eps(m, n):
return np.random.uniform(-1., 1., size=[m, n])
def GANloss(D_real,D_fake):
D_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_real, labels=tf.ones_like(D_real)))
D_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake, labels=tf.zeros_like(D_fake)))
D_loss = D_loss_real + D_loss_fake
G_adv = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake, labels=tf.ones_like(D_fake)))
return D_loss,G_adv
def bias_variable(shape, name=None):
initial = tf.constant(0.0, shape=shape)
if name is None:
return tf.Variable(initial)
else:
return tf.get_variable(name, initializer=initial)
def weight_variable_xavier_initialized(shape, constant=1, name=None):
stddev = constant * np.sqrt(2.0 / (shape[2] + shape[3]))
return weight_variable(shape, stddev=stddev, name=name)
def weight_selu(shape, transpose=False,name=None):
if transpose:
stddev = np.sqrt(1.0 / (shape[0] * shape[1]*shape[2]))
else:
stddev = np.sqrt(1.0 / (shape[0] * shape[1]*shape[3]))
return weight_variable(shape, stddev=stddev, name=name)
def weight_variable(shape, stddev=0.02, name=None):
initial = tf.random_normal(shape, stddev=stddev)
if name is None:
return tf.Variable(initial)
else:
return tf.get_variable(name, initializer=initial)
def conv2d_transpose_strided(x, W, b, output_shape=None):
conv = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, 2, 2, 1], padding="SAME")
return tf.nn.bias_add(conv, b)
def conv2d(x, W,filter_size=5,strides=(1,2,2,1)):
return tf.nn.conv2d(x, W, strides=strides, padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
def conv1d(x,W,strides=1,act='relu'):
conv = tf.nn.conv1d(x,W,stride=strides,padding='SAME')
if act=='selu':
h = selu(conv)
else:
h = tf.nn.relu(conv)
return h
def bn(x,is_training,name):
return batch_norm(x, decay=0.9, center=True, scale=True,updates_collections=None,is_training=is_training,
reuse=None,
trainable=True,
scope=name)
def batch_norm_custom(x, n_out, phase_train, scope='bn', decay=0.99, eps=1e-5,reuse=None):
with tf.variable_scope(scope) as scope:
beta = tf.get_variable(name='beta', shape=[n_out], initializer=tf.constant_initializer(0.0)
, trainable=True)
gamma = tf.get_variable(name='gamma', shape=[n_out], initializer=tf.random_normal_initializer(1.0, 0.02),
trainable=True)
batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], name='moments')
ema = tf.train.ExponentialMovingAverage(decay=decay)
def mean_var_with_update():
ema_apply_op = ema.apply([batch_mean, batch_var])
with tf.control_dependencies([ema_apply_op]):
return tf.identity(batch_mean), tf.identity(batch_var)
mean, var = tf.cond(phase_train,
mean_var_with_update,
lambda: (ema.average(batch_mean), ema.average(batch_var)))
normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, eps)
return normed
def lrelu(x, leak=0.2, name="lrelu"):
with tf.variable_scope(name):
f1 = 0.5 * (1 + leak)
f2 = 0.5 * (1 - leak)
return f1 * x + f2 * abs(x)
def selu(x,name="selu"):
with tf.variable_scope(name):
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))
def filter_output(samples):
s = []
for _label in samples:
mask = np.where(_label<=np.median(_label),0,1)
_label = mask*_label
mask2 = np.where(_label>np.percentile(_label,99),1,0)
p = np.percentile(_label,99)
_label[np.where(mask2)] = p
s.append(_label)
return s
def separable_conv2d_util(X,filter_sizes,names,depth_multiplier=1,strides=[1,1,1,1]):
zz = filter_sizes[:2]
in_channels = filter_sizes[2]
out_channels = filter_sizes[3]
dm = depth_multiplier
wconv1_dw = weight_variable_xavier_initialized([zz[0],zz[1],in_channels,dm],name=names[0])
wconv1_pw = weight_variable_xavier_initialized([1,1,in_channels*dm,out_channels],name=names[1])
b_conv1 = bias_variable([out_channels],name=names[2])
h = tf.nn.separable_conv2d(X,wconv1_dw,wconv1_pw,strides,padding='SAME') + b_conv1
return h
def concat(tensors, axis, *args, **kwargs):
return tf.concat(tensors, axis, *args, **kwargs)
def conv_cond_concat(x, y):
"""Concatenate conditioning vector on feature map axis."""
x_shapes = x.get_shape()
y_shapes = y.get_shape()
return concat([x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])], 3)
def plot_save(samples,figsize=(4,4),wspace=0.05,hspace=0.05,cmap='gray',resize=False):
fig = plt.figure(figsize=figsize)
gs = gridspec.GridSpec(figsize[0], figsize[1])
gs.update(wspace=wspace, hspace=hspace)
for i, sample in enumerate(samples):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
if(resize):
sample = imresize(sample,(128,128))
plt.imshow(sample, cmap=cmap)
title="{:.2f}".format(np.linalg.norm(sample))
# ax.text(16, 16, title,fontsize=8,
# bbox={'facecolor':'white', 'alpha':0.9, 'pad':1})
return fig
def plot_line(samples,gt,bar=True):
# plt.rcParams["figure.figsize"] = (10,20)
if bar :
fig = plt.figure(figsize=(20, 20))
else:
fig = plt.figure(figsize=(20, 20))
#
width=0.35
params = ['stopping_mult', 'radiation_mult', 'ablation_cv', 'Vi',
'conduction_mult', 'shape_model_initial_velocity_amplitude',
'shape_model_initial_velocities:(1, 0)',
'shape_model_initial_velocities:(1, 1)',
'shape_model_initial_velocities:(2, 0)',
'shape_model_initial_velocities:(2, 1)',
'shape_model_initial_velocities:(2, 2)']
ind = np.arange(len(params))
for i, sample in enumerate(samples):
ax = plt.subplot(10,10,i+1)
ax.set_xticklabels([])
ax.set_yticklabels([])
if bar:
ax.barh(ind,gt[i,:],width,color='red')
ax.barh(ind+width,sample,width, color='blue')
# plt.yticks(ind ,params,rotation=30)
# ax.legend(['GT', 'Pred'])
else:
plt.plot(gt[i,:])
plt.plot(sample,'r.-')
return fig
def plot(samples,immax=None,immin=None):
# plt.rcParams["figure.figsize"] = (10,10)
IMAGE_SIZE = 64
fig = plt.figure(figsize=(20, 20))
gs = gridspec.GridSpec(10, 10)
gs.update(wspace=0.05, hspace=0.05)
for i, sample in enumerate(samples):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
if immax is not None:
plt.imshow(sample.reshape(IMAGE_SIZE, IMAGE_SIZE), cmap='winter',vmax=immax[i],vmin=immin[i])
return fig
def test_imgs_plot(fdir,batch,data_dict):
i = batch
samples = data_dict['samples']
samples_x = data_dict['samples_x']
y_sca_test = data_dict['y_sca']
y_img_test = data_dict['y_img']
x_test_mb = data_dict['x']
nTest = x_test_mb.shape[0]
idx = np.random.choice(range(4),1)
y_sca_test_mb = y_sca_test[-nTest:,:]
y_img_test_ = y_img_test[-nTest:,:16384]
y_img_test_mb = y_img_test_.reshape(-1,64,64,4)[:,:,:,idx].reshape(-1,4096)
samples_y_sca = samples[:,16384:]
samples_y_img = samples[:,:16384].reshape(-1,64,64,4)
samples_y_img_plot = samples_y_img[:,:,:,idx]
fig = plot_line(samples_y_sca,y_sca_test_mb,bar=False)
plt.savefig('{}/y_sca_{}.png'
.format(fdir,str(i).zfill(3)), bbox_inches='tight')
plt.close()
fig = plot(samples_y_img_plot,immax=np.max(y_img_test_mb,axis=1),immin=np.min(y_img_test_mb,axis=1))
plt.savefig('{}/y_img_{}_{}.png'
.format(fdir,str(i).zfill(3),str(idx)), bbox_inches='tight')
plt.close()
fig = plot_line(samples_x,x_test_mb,bar=False)
plt.savefig('{}/x_{}.png'
.format(fdir,str(i).zfill(3)), bbox_inches='tight')
plt.close()
return
|
{
"alphanum_fraction": 0.6439045743,
"author": null,
"avg_line_length": 35.4186046512,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "db9fbf0ddbbc9207c256faa5661ef3ee0911e866",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2021-12-18T20:16:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-26T18:58:34.000Z",
"max_forks_repo_head_hexsha": "0268da48b7110acb2e844b5a405d0ec2d38fa8a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rreece/macc",
"max_forks_repo_path": "utils.py",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "0268da48b7110acb2e844b5a405d0ec2d38fa8a6",
"max_issues_repo_issues_event_max_datetime": "2020-03-03T09:33:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-01-24T14:24:52.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "rreece/macc",
"max_issues_repo_path": "utils.py",
"max_line_length": 118,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "0268da48b7110acb2e844b5a405d0ec2d38fa8a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rreece/macc",
"max_stars_repo_path": "utils.py",
"max_stars_repo_stars_event_max_datetime": "2021-12-18T20:16:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-26T18:59:11.000Z",
"num_tokens": 2546,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 9138
}
|
import os
import pickle
import random
import numpy as np
from tqdm import tqdm
import tensorflow as tf
import tensorflow_probability as tfp
from models.gazeflow import Glow
class GazeFlow:
def __init__(self, hparams):
self.hparams = hparams
self.input_shape = [
self.hparams.images_width,
self.hparams.images_height,
self.hparams.images_channel,
]
self.condition_shape = self.hparams.condition_shape
self.glow = Glow(hparams.K, hparams.L, hparams.conditional, hparams.width,
hparams.skip_type, condition_shape=self.condition_shape)
self.setup_checkpoint((os.path.join(
self.hparams.checkpoint_path, self.hparams.checkpoint_path_specific)))
# self.check_model()
def check_model(self):
# self.glow.build(tuple([None] + self.input_shape))
x = tf.keras.Input(self.input_shape)
cond = tf.keras.Input(self.condition_shape)
z, ldj, zaux, ll = self.glow(x, cond=cond, inverse=False)
self.z_shape = list(z.shape)
self.zaux_shape = list(zaux.shape)
self.z_dims = np.prod(z.shape[1:])
self.zaux_dims = np.prod(zaux.shape[1:])
# summarize
print("z_f's shape : {}".format(self.z_shape))
print("log_det_jacobian's shape: {}".format(ldj.shape))
print("z_aux's shape : {}".format(self.zaux_shape))
self.glow.summary()
def setup_checkpoint(self, checkpoint_path):
print("checkpoint will be load at {}".format(checkpoint_path))
ckpt = tf.train.Checkpoint(
step=tf.Variable(0), model=self.glow
)
ckpt_manager = tf.train.CheckpointManager(
ckpt, checkpoint_path, max_to_keep=7)
if ckpt_manager.latest_checkpoint:
ckpt.restore(ckpt_manager.latest_checkpoint)
print("Latest checkpoint has been restored !")
self.ckpt = ckpt
|
{
"alphanum_fraction": 0.635443038,
"author": null,
"avg_line_length": 34.0517241379,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "c2fe563cb4fab74bfa502062d912a2a58b01d7fd",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-01-02T10:32:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-08-20T14:40:01.000Z",
"max_forks_repo_head_hexsha": "ca6b7d548571f85af84bdec77292758ab5d36449",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ackness/GazeFlow",
"max_forks_repo_path": "models/model.py",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "ca6b7d548571f85af84bdec77292758ab5d36449",
"max_issues_repo_issues_event_max_datetime": "2022-02-12T11:26:28.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-12T11:26:20.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ackness/GazeFlow",
"max_issues_repo_path": "models/model.py",
"max_line_length": 82,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "ca6b7d548571f85af84bdec77292758ab5d36449",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ackness/GazeFlow",
"max_stars_repo_path": "models/model.py",
"max_stars_repo_stars_event_max_datetime": "2022-02-07T08:26:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-29T12:00:20.000Z",
"num_tokens": 445,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1975
}
|
//=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "smtk/attribute/PythonRule.h"
#include "smtk/attribute/Definition.h"
#include "smtk/common/CompilerInformation.h"
#include "smtk/common/PythonInterpreter.h"
#include "smtk/io/Logger.h"
SMTK_THIRDPARTY_PRE_INCLUDE
//force to use filesystem version 3
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem.hpp>
#define PUGIXML_HEADER_ONLY
// NOLINTNEXTLINE(bugprone-suspicious-include)
#include "pugixml/src/pugixml.cpp"
#include <pybind11/embed.h>
SMTK_THIRDPARTY_POST_INCLUDE
#include <exception>
namespace smtk
{
namespace attribute
{
bool PythonRule::operator()(
const Attribute::ConstPtr& attribute,
const smtk::resource::PersistentObject::ConstPtr& object) const
{
// Initialize SMTK's embedded interpreter. This will locate SMTK's Python
// bindings and ensure that they can be imported.
smtk::common::PythonInterpreter::instance().initialize();
// Import all associated source files.
for (std::string sourceFile : m_sourceFiles)
{
// If the source file is described as a relative path, attempt to find it
// relative to the location of the attribute resource.
if (!boost::filesystem::path(sourceFile).is_absolute())
{
sourceFile =
(boost::filesystem::path(attribute->resource()->location()).parent_path() / sourceFile)
.string();
}
if (
!boost::filesystem::is_regular_file(boost::filesystem::path(sourceFile)) &&
!boost::filesystem::is_symlink(boost::filesystem::path(sourceFile)))
{
smtkWarningMacro(
smtk::io::Logger::instance(),
"Could not locate Python source file \"" << sourceFile << "\".");
}
else if (!smtk::common::PythonInterpreter::instance().loadPythonSourceFile(sourceFile))
{
smtkWarningMacro(
smtk::io::Logger::instance(),
"Could not load Python source file \"" << sourceFile << "\".");
}
}
// The inputs to our Python function will be the input attribute and object.
auto locals = pybind11::dict();
pybind11::module module = pybind11::module::import("smtk.attribute");
locals["attribute"] = attribute;
locals["object"] = object;
// We assume that the final Python function described in m_functionString
// is the function we want to call, so we determine its name.
std::string functionName;
auto functionNameStart = m_functionString.rfind("def ");
if (functionNameStart != std::string::npos)
{
functionNameStart += 4;
functionName = m_functionString.substr(
functionNameStart,
m_functionString.find_first_of('(', functionNameStart) - functionNameStart);
}
if (functionName.empty())
{
// If we cannot find the call function, we log the Python function and treat
// this rule as an all-pass filter.
smtkErrorMacro(
smtk::io::Logger::instance(),
"Could not determine Python function to call from the following:\n\n"
<< m_functionString);
return true;
}
// We append a single line to execute the Python function and assign its return
// value to a variable we can extract.
std::stringstream s;
s << m_functionString << "\n";
s << "returnValue = " << functionName << "(attribute, object)";
try
{
pybind11::exec(s.str().c_str(), pybind11::globals(), locals);
}
catch (std::exception& e)
{
// If something went wrong with the Python execution, we log the Python
// function and the error and treat this rule as an all-pass filter.
s << "\n\n" << e.what();
smtk::io::Logger::instance().addRecord(
smtk::io::Logger::ERROR,
"PythonRule for definition \"" + attribute->definition()->type() +
"\" encountered an error:\n" + s.str());
return true;
}
return locals["returnValue"].cast<bool>();
}
const PythonRule& PythonRule::operator>>(nlohmann::json& json) const
{
// There are a handful of reserved characters in json. Since our json files
// do not need to be human-readable, one workaround is to encode our Python
// string into something more digestible. Luckily, Python has routines to do
// just this.
json["SourceFiles"] = m_sourceFiles;
auto locals = pybind11::dict();
locals["functionStr"] = m_functionString;
const char* encode = R"python(
import base64
returnValue = base64.b64encode(functionStr.encode('ascii')))python";
try
{
pybind11::exec(encode, pybind11::globals(), locals);
json["Function"] = locals["returnValue"].cast<std::string>();
}
catch (std::exception&)
{
}
return *this;
}
PythonRule& PythonRule::operator<<(const nlohmann::json& json)
{
// See the explanation in operator>>() above.
m_sourceFiles = json["SourceFiles"].get<std::vector<std::string>>();
auto locals = pybind11::dict();
locals["b64encodedStr"] = json["Function"].get<std::string>();
const char* decode = R"python(
import base64
returnValue = base64.b64decode(b64encodedStr).decode('ascii'))python";
try
{
pybind11::exec(decode, pybind11::globals(), locals);
m_functionString = locals["returnValue"].cast<std::string>();
}
catch (std::exception&)
{
}
return *this;
}
const PythonRule& PythonRule::operator>>(pugi::xml_node& node) const
{
if (!m_sourceFiles.empty())
{
pugi::xml_node subnode = node.append_child("SourceFiles");
for (const auto& sourceFile : m_sourceFiles)
{
subnode.append_child("SourceFile").text().set(sourceFile.c_str());
}
}
// There are a handful of reserved characters in XML. We avoid complications
// between these reserved characters and Python syntax by treating our Python
// input as CDATA, which the parser ignores.
node.append_child(pugi::node_cdata).set_value(m_functionString.c_str());
return *this;
}
PythonRule& PythonRule::operator<<(const pugi::xml_node& node)
{
m_sourceFiles.clear();
pugi::xml_node subnode = node.child("SourceFiles");
if (subnode)
{
for (pugi::xml_node child = subnode.child("SourceFile"); child;
child = child.next_sibling("SourceFile"))
{
m_sourceFiles.emplace_back(child.text().get());
}
}
// See the explanation in operator>>() above.
m_functionString = node.text().data().value();
return *this;
}
} // namespace attribute
} // namespace smtk
|
{
"alphanum_fraction": 0.671475804,
"author": null,
"avg_line_length": 30.2454545455,
"converted": null,
"ext": "cxx",
"file": null,
"hexsha": "873b924a640a39132a9a9b64b42934fa37a6e530",
"include": null,
"lang": "C++",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 27,
"max_forks_repo_forks_event_max_datetime": "2021-12-23T01:05:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-04T14:17:51.000Z",
"max_forks_repo_head_hexsha": "0069ea37f8f71a440b8f10a157b84a56ca004551",
"max_forks_repo_licenses": [
"BSD-3-Clause-Clear"
],
"max_forks_repo_name": "jcfr/SMTK",
"max_forks_repo_path": "smtk/attribute/PythonRule.cxx",
"max_issues_count": 127,
"max_issues_repo_head_hexsha": "0069ea37f8f71a440b8f10a157b84a56ca004551",
"max_issues_repo_issues_event_max_datetime": "2021-08-19T17:34:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-15T20:55:45.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Clear"
],
"max_issues_repo_name": "jcfr/SMTK",
"max_issues_repo_path": "smtk/attribute/PythonRule.cxx",
"max_line_length": 95,
"max_stars_count": 40,
"max_stars_repo_head_hexsha": "0069ea37f8f71a440b8f10a157b84a56ca004551",
"max_stars_repo_licenses": [
"BSD-3-Clause-Clear"
],
"max_stars_repo_name": "jcfr/SMTK",
"max_stars_repo_path": "smtk/attribute/PythonRule.cxx",
"max_stars_repo_stars_event_max_datetime": "2022-01-06T13:13:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-02-21T19:55:54.000Z",
"num_tokens": 1624,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 6654
}
|
import scipy as sp
import numpy as np
from scipy import sparse
import matplotlib.pyplot as plt
from features import (
team_answer_estimation,
create_test_prediction,
)
from utils import (
add_dim,
)
class ProbaRegression:
def __init__(
self,
init_weights=None,
epochs=1e4,
lr=1e1,
bs=1e4,
tol=1e-4,
viz=True,
axis=None,
fig=None
) -> None:
self.w = init_weights
self.epochs = int(epochs)
self.lr = lr
self.bs = int(bs)
self.tol = tol
self.viz = viz
if self.viz:
self.axis = axis
self.fig = fig
self.axis.set_xlabel('epoch')
self.axis.set_ylabel('metric')
def fit(self, X, y):
if self.w is None:
self.w = np.random.normal(size=X.shape[1])
if self.viz:
losses = []
for i in range(self.epochs):
idx = np.random.choice(X.shape[0], self.bs)
x_batch, y_batch_gt = X[idx], y[idx]
y_batch_pred = self.sigmoid(x_batch @ self.w)
grad = x_batch.T @ (y_batch_pred - y_batch_gt) / self.bs
self.w -= self.lr * grad
if self.viz:
self.axis.clear()
losses.append(self.log_loss(y_batch_gt, y_batch_pred))
self.axis.plot(losses, label='log_loss')
self.fig.canvas.draw()
plt.grid(True)
def predict_proba(self, X):
positive_preds = self.sigmoid(X @ self.w).T
return np.column_stack([(1. - positive_preds), positive_preds])
@staticmethod
def mae(y, p):
return np.abs(y - p).mean()
@staticmethod
def log_loss(y, p):
return -np.mean(y * np.log(p) + (1. - y) * np.log(1. - p))
@staticmethod
def sigmoid(x):
return np.exp(-np.logaddexp(0, -x))
class EM:
def __init__(
self,
dataset,
X, y, player_to_idx,
epochs_em,
epochs_pr,
viz=True,
) -> None:
axes1d = [None, None]
self.viz = viz
if self.viz:
self.fig, axes1d = plt.subplots(2, 1, figsize=(8, 4))
self.axis = axes1d[1]
self.axis.set_xlabel('epoch')
self.axis.set_ylabel('correlation')
self.pr = ProbaRegression(
init_weights=None,
epochs=epochs_pr,
viz=viz,
axis=axes1d[0],
fig=self.fig,
)
self.X = add_dim(X)
self.y = y
self.dataset = dataset
self.player_to_idx = player_to_idx
self.epochs = int(epochs_em)
def fit(self, test_on=None):
self.spearman, self.kendall = [], []
# initial M step
self.pr.fit(self.X, self.y)
for i in range(self.epochs):
#decrease lr
self.pr.lr /= 1.2
#proba if each player answered on each question
M_step_pred = self.pr.predict_proba(self.X)
# E step;
#team will answer on question estimation based on prev prediction
team_success = team_answer_estimation(self.dataset, self.player_to_idx, M_step_pred)
z = (M_step_pred[..., 1] / team_success).clip(0, 1)
z[self.y == 0] = 0.
# M step;
self.pr.fit(self.X, z)
if test_on is not None:
rating_pred, rating_gt = create_test_prediction(
dataset=test_on,
player_to_idx=self.player_to_idx,
model=self.pr,
n_features=self.X.shape[1],
)
spearman = [
sp.stats.spearmanr(rating_gt[i], rating_pred[i]).correlation
for i in range(len(rating_pred))
]
kendall = [
sp.stats.kendalltau(rating_gt[i], rating_pred[i]).correlation
for i in range(len(rating_pred))
]
self.spearman.append(np.nanmean(spearman))
self.kendall.append(np.nanmean(kendall))
if self.viz:
self.axis.clear()
self.axis.plot(self.spearman, label='spearman')
self.axis.plot(self.kendall, label='kendall')
self.fig.canvas.draw()
plt.grid(True)
plt.legend();
|
{
"alphanum_fraction": 0.4705395907,
"author": null,
"avg_line_length": 27.3276836158,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "af3d386415f4c661dd42a07a5a1e82ee8fd19425",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-08-31T08:47:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-08-31T08:47:24.000Z",
"max_forks_repo_head_hexsha": "a81bfd874ab80eb8c7eaad8a4acf723f327f2f50",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Ilyabasharov/made_mail.ru",
"max_forks_repo_path": "2_term/made_2021_ml_adv/homeworks/2/models.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a81bfd874ab80eb8c7eaad8a4acf723f327f2f50",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Ilyabasharov/made_mail.ru",
"max_issues_repo_path": "2_term/made_2021_ml_adv/homeworks/2/models.py",
"max_line_length": 96,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "a81bfd874ab80eb8c7eaad8a4acf723f327f2f50",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Ilyabasharov/made_mail.ru",
"max_stars_repo_path": "2_term/made_2021_ml_adv/homeworks/2/models.py",
"max_stars_repo_stars_event_max_datetime": "2020-02-15T06:20:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-15T06:20:30.000Z",
"num_tokens": 1078,
"path": null,
"reason": "import numpy,import scipy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4837
}
|
#####################################################################
# Description: Calculates the time statistics of the network devices
#####################################################################
import json
import csv
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
id = 8448 # the ID of the device that its time statistics will be calculated
other_ids = [8449, 8450] # the IDs of the other devices in the network
message_generation_interval = []
time_sessions_started = []
session_duration = []
def get_message_generation_interval():
filename = '../logs/msg_creation_timestamps_' + str(id) + '.txt'
with open(filename) as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
for row in csvreader:
message_generation_interval.append(float(row[1]))
def get_session_times():
filename = '../logs/sessions_' + str(id) + '.json'
for i in range(0, len(other_ids)):
time_sessions_started.append([])
with open(filename) as json_file:
session_data = json.load(json_file)['sessions']
for session in session_data:
if (len(session['messages_received']) == 0 and len(session['messages_sent']) == 0):
continue
session_duration.append(session['duration_msec'])
paired_device_index = other_ids.index(int(session['paired_device']))
time_sessions_started[paired_device_index].append(session['started_at'])
if __name__== "__main__":
print('********** DEVICE %d **********' % id)
get_message_generation_interval()
get_session_times()
print('Messages generated: %d' % len(message_generation_interval))
message_generation_interval = np.array(message_generation_interval)
interval_mean = np.mean(message_generation_interval)
interval_std = np.std(message_generation_interval)
interval_min = np.amin(message_generation_interval)
interval_max = np.amax(message_generation_interval)
print('----- Message generation interval -----')
print('mean= %.2f sec' % interval_mean)
print('std= %.2f sec' % interval_std)
print('min= %.2f sec' % interval_min)
print('max= %.2f sec' % interval_max)
print('---------------------------------------\n\n')
session_duration = np.array(session_duration)
duration_mean = np.mean(session_duration)
duration_std = np.std(session_duration)
duration_min = np.amin(session_duration)
duration_max = np.amax(session_duration)
print('----- Session duration -----')
print('mean= %.2f msec' % duration_mean)
print('std= %.2f msec' % duration_std)
print('min= %.2f msec' % duration_min)
print('max= %.2f msec' % duration_max)
print('----------------------------\n\n')
fig = plt.figure()
sns.set(color_codes=True)
plt.hist(x=message_generation_interval, rwidth=0.9, color='#607c8e', bins=12)
plt.xlabel('Message generation interval (sec)')
plt.ylabel('Frequency')
plt.title('Device %d' % id)
fig.savefig('message_gen_' + str(id) + '.eps', bbox_inches='tight', dpi=1000)
plt.show()
fig = plt.figure()
sns.set(color_codes=True)
plt.hist(x=session_duration, rwidth=0.9, color='#607c8e', bins=15)
plt.xlabel('Session duration (msec)')
plt.ylabel('Frequency')
plt.title('Device %d' % id)
fig.savefig('session_duration_' + str(id) + '.eps', bbox_inches='tight', dpi=1000)
plt.show()
fig = plt.figure()
sns.set(color_codes=True)
for i in range(0, len(other_ids)):
x = np.array(time_sessions_started[i])
y = np.array([i/2+1] * len(time_sessions_started[i]))
plt.scatter(x=x, y=y, label=other_ids[i], edgecolors='k')
plt.xlabel('Time (sec)')
plt.yticks([])
plt.title('Device %d' % id)
plt.legend(title='Paired device')
fig.savefig('session_times_' + str(id) + '.eps', bbox_inches='tight', dpi=1000)
plt.show()
|
{
"alphanum_fraction": 0.6326164875,
"author": null,
"avg_line_length": 33.6724137931,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "54ec9c3f6ca7cd0d4dc7287cc37c2cf0338d90c9",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ad371281f93ade85fc5abfa3709482a71b2db19a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "AlexDelitzas/adhoc-network-message-service",
"max_forks_repo_path": "data_statistics/time_statistics.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad371281f93ade85fc5abfa3709482a71b2db19a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "AlexDelitzas/adhoc-network-message-service",
"max_issues_repo_path": "data_statistics/time_statistics.py",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ad371281f93ade85fc5abfa3709482a71b2db19a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AlexDelitzas/adhoc-network-message-service",
"max_stars_repo_path": "data_statistics/time_statistics.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 908,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3906
}
|
#!/usr/bin/env python3
import argparse
import random
import numpy as np
from tqdm import tqdm
import torch
from data import train_selector, test_selector1, load_images
from neural_net import Ensemble
np.random.seed(0)
torch.manual_seed(0)
parser = argparse.ArgumentParser(description="Siamese network training on CPU")
parser.add_argument('--columns', metavar="n", type=int, nargs=None,
help="number of neural columns, default: 28", default=28)
parser.add_argument('--channels', metavar="n", type=int, nargs=None,
help="number of hidden CNN channels in columns, default: 14", default=14)
parser.add_argument('--classes-per-col', metavar="n", type=int, nargs=None,
help="number of classes per columnm default: 16", default=16)
args = vars(parser.parse_args())
# load validation data
class_images = load_images(test_selector1, max_per_class=32)
validation = [
torch.cat(class_images[i], dim=0)
for i in range(4)
]
# load main training set
class_images = load_images(train_selector, max_per_class=256)
print("number of classes:", len(class_images))
# a function to generate processed batch
def random_batch(net: torch.nn.Module, class_indices: list) -> torch.Tensor:
inp = torch.cat([
random.choice(class_images[j]) for j in class_indices
], dim=0)
return net(inp)
# ensemble of neural columns
classes_per_model = args["classes_per_col"]
dim = int(np.ceil(np.log(classes_per_model)))
ensemble = Ensemble(
n_columns=args["columns"], column_dim=dim, channels=args["channels"])
nets = ensemble.columns
optimizers = [
torch.optim.Adam(net.parameters(), lr=0.01)
for net in nets
]
# choose a random set of classes for each network
class_sets = [
np.random.permutation(len(class_images))[:classes_per_model]
for _ in nets
]
# this distance function will be handy for the loss function
def distance(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
diff = x.unsqueeze(0) - y.unsqueeze(1)
return diff.abs().mean(dim=2)
# where we will store the best validated ensemble
filename = "ensemble_{columns}_{channels}_{col_dim}".format(
columns=ensemble.num_columns(),
channels=ensemble.channels(),
col_dim=ensemble.column_dim()
)
print("model's weights will be stored in", filename)
# training parameters
max_dist = 5.0
best_loss = np.inf
iterations_per_epoch = 10
# training loop
print("end training with CTRL-C whenever you see fit")
for epoch in range(1000):
progress_bar = tqdm(range(iterations_per_epoch), total=iterations_per_epoch)
for _ in progress_bar:
for net, class_set, optimizer in zip(nets, class_sets, optimizers):
# batch of one random image for each class
batch1 = random_batch(net, class_set)
batch2 = random_batch(net, class_set)
# distance loss
dist = distance(batch1, batch2)
class_indices = list(range(len(class_set)))
intra_dist = dist[class_indices, class_indices].mean()
inter_dist = dist.clamp(max=max_dist).mean()
loss = intra_dist + max_dist - inter_dist
# optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
# validation
all_classes = list(range(len(class_images)))
with torch.no_grad():
batch1 = random_batch(ensemble, all_classes)
batch2 = random_batch(ensemble, all_classes)
dist = distance(batch1, batch2)
intra_dist = dist[all_classes, all_classes].mean()
inter_dist = dist.clamp(max=max_dist).mean()
loss = (intra_dist + max_dist - inter_dist).item()
if loss < best_loss:
best_loss = loss
torch.save(ensemble.state_dict(), filename)
print("[epoch %i] best loss = %f" % (epoch, best_loss))
|
{
"alphanum_fraction": 0.6921862668,
"author": null,
"avg_line_length": 33.6371681416,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "e2002b3c0ca056128ff91805300f0b86946e7938",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1662536a756aae48323d71cba8163c439297664b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "rom1mouret/inplastic",
"max_forks_repo_path": "train_model.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1662536a756aae48323d71cba8163c439297664b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "rom1mouret/inplastic",
"max_issues_repo_path": "train_model.py",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1662536a756aae48323d71cba8163c439297664b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "rom1mouret/inplastic",
"max_stars_repo_path": "train_model.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 880,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3801
}
|
import numpy as np
from sklearn.neighbors import KernelDensity
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
def gaussian_kernel(x, y, h):
return 1/(2*np.pi*h*h)**0.5 * np.exp(-((x-y)**2).sum(axis=-1)/2/h/h)
class NaiveKDE():
def __init__(self, kernel_func=gaussian_kernel, bandwidth=1):
self.kernel_func = kernel_func
self.h = bandwidth
def fit(self, data):
data = np.asarray(data)
assert np.ndim(data) <= 2
if np.ndim(data) == 1:
data = data[:, None]
self.data = data[None, :, :] # 1 X N X K
def evaluate(self, x):
x = np.asarray(x)
if np.ndim(x) == 1:
x = x[:, None]
assert x.shape[-1] == self.data.shape[-1]
if np.ndim(x) <= 1:
x_num = 1
else:
x_num = x.shape[0]
return ((self.kernel_func(x.reshape(x_num, 1, -1), self.data, self.h))).mean(axis=-1)# M X 1 X K
def main():
np.random.seed(0)
data = np.random.randn(1000)
kde = NaiveKDE(gaussian_kernel, bandwidth=0.5)
kde.fit(data)
x = np.arange(-10, 10, step=0.1)
p = kde.evaluate(x)
plt.plot(x, p, label='naive kde(h=0.5)')
plt.hist(data, density=True)
gaussian = multivariate_normal(0, 1)
plt.plot(x, gaussian.pdf(x), label='true')
plt.legend(loc='upper left')
plt.show()
print("-")
if __name__ == '__main__':
main()
|
{
"alphanum_fraction": 0.5640495868,
"author": null,
"avg_line_length": 27.3962264151,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "d333dcb9b349852dcf8cd0ec925f8f373d196052",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "03533c4e7499126a1aa214b69656430c3836e609",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zhanglei1172/automl",
"max_forks_repo_path": "base/kde/toy_kde.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "03533c4e7499126a1aa214b69656430c3836e609",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zhanglei1172/automl",
"max_issues_repo_path": "base/kde/toy_kde.py",
"max_line_length": 104,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "03533c4e7499126a1aa214b69656430c3836e609",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zhanglei1172/automl",
"max_stars_repo_path": "base/kde/toy_kde.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 425,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1452
}
|
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 27 15:27:51 2021
@author: aschauer
"""
import os
import logging
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from cv_results_database import get_cv_results_as_df
import plotting_utils as pu
import scoring_utils as scu
from sklearn.metrics import r2_score, mean_squared_error
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
sns.set_color_codes(palette='deep')
sc = get_cv_results_as_df()
sc = sc.loc[sc['gap_type']=='LOWO']
sc = sc.rename(columns={'bias': 'BIAS'})
methods_used = [
'SingleStation_best_correlated_mean_ratio',
'Inverse distance squared',
'matiu vertical weighted_min_corr_-1.0',
'Elastic Net Regression',
'RandomForest_V3.5',
'SWE2HS_Snow17_shifted_dates']
plot_data = sc.loc[sc['fill_method'].isin(methods_used)].copy()
plot_data.replace(to_replace={'fill_method':pu.METHOD_NAMES}, inplace=True)
def calculate_scores(df):
scores = {}
for climate_metric in ['HSavg','HSmax','dHS1']:
data = (df.loc[:,[f'{climate_metric}_true',f'{climate_metric}_pred']]
.copy()
.dropna())
scores[f'r2_{climate_metric}'] = r2_score(data[f'{climate_metric}_true'], data[f'{climate_metric}_pred'])
scores[f'rmse_{climate_metric}'] = np.sqrt(mean_squared_error(data[f'{climate_metric}_true'], data[f'{climate_metric}_pred']))
scores[f'MAAPE_{climate_metric}'] = scu._maape_score(data[f'{climate_metric}_true'], data[f'{climate_metric}_pred'])
scores[f'bias_{climate_metric}'] = scu._bias_score(data[f'{climate_metric}_true'], data[f'{climate_metric}_pred'])
return pd.Series(scores)
grouped_scores = (plot_data.groupby(['fill_method','station_grid'])
.apply(calculate_scores)
.reset_index()
)
for metric in ['rmse','r2','MAAPE','bias']:
for clim_indi in ['HSavg', 'HSmax', 'dHS1']:
sns.barplot(data=grouped_scores,
x='fill_method',
y=f'{metric}_{clim_indi}',
order=[pu.METHOD_NAMES[m] for m in methods_used],
hue = 'station_grid',
hue_order = ['full', 'only_target_stations'],
palette=['C1', 'C0']
)
plt.show()
|
{
"alphanum_fraction": 0.6462845011,
"author": null,
"avg_line_length": 33.1690140845,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "2a1a82659edb70b88c5f2e6047770eac55713eea",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e0763f77369f85fec6fd5d84a4da0b4aa95f862b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "joAschauer/evaluating_methods_for_reconstructing_large_gaps_in_historic_snow_depth_time_series",
"max_forks_repo_path": "src/cv_evaluate_climate_metrics.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e0763f77369f85fec6fd5d84a4da0b4aa95f862b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "joAschauer/evaluating_methods_for_reconstructing_large_gaps_in_historic_snow_depth_time_series",
"max_issues_repo_path": "src/cv_evaluate_climate_metrics.py",
"max_line_length": 134,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e0763f77369f85fec6fd5d84a4da0b4aa95f862b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "joAschauer/evaluating_methods_for_reconstructing_large_gaps_in_historic_snow_depth_time_series",
"max_stars_repo_path": "src/cv_evaluate_climate_metrics.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 578,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2355
}
|
import cv2
import numpy as np
import argparse
frameWidth = 640
frameHeight = 480
# For figures
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image")
args = vars(ap.parse_args())
# For videos
# cap = cv2.VideoCapture(0)
# cap.set(3, frameWidth)
# cap.set(4, frameHeight)
def empty(a):
pass
cv2.namedWindow("Parameters")
cv2.resizeWindow("Parameters",640,240)
cv2.createTrackbar("Threshold1","Parameters",23,255,empty)
cv2.createTrackbar("Threshold2","Parameters",20,255,empty)
cv2.createTrackbar("Area","Parameters",5000,30000,empty)
def stackImages(scale,imgArray):
rows = len(imgArray)
cols = len(imgArray[0])
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
for x in range ( 0, rows):
for y in range(0, cols):
if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
else:
imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
imageBlank = np.zeros((height, width, 3), np.uint8)
hor = [imageBlank]*rows
hor_con = [imageBlank]*rows
for x in range(0, rows):
hor[x] = np.hstack(imgArray[x])
ver = np.vstack(hor)
else:
for x in range(0, rows):
if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
else:
imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
hor= np.hstack(imgArray)
ver = hor
return ver
def getContours(img,imgContour):
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
areaMin = cv2.getTrackbarPos("Area", "Parameters")
if area > areaMin:
cv2.drawContours(imgContour, cnt, -1, (255, 0, 255), 7)
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
# print(len(approx))
x , y , w, h = cv2.boundingRect(approx)
cv2.rectangle(imgContour, (x , y ), (x + w , y + h ), (0, 255, 0), 5)
cv2.putText(imgContour, "Points: " + str(len(approx)), (x + w + 20, y + 20), cv2.FONT_HERSHEY_COMPLEX, .7,
(0, 255, 0), 2)
cv2.putText(imgContour, "Area: " + str(int(area)), (x + w + 20, y + 45), cv2.FONT_HERSHEY_COMPLEX, 0.7,
(0, 255, 0), 2)
while True:
# success, img = cap.read()
# img = cv2.imread(args["image"])
# imgContour = img.copy()
# imgBlur = cv2.GaussianBlur(img, (7, 7), 1)
# imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)
threshold1 = cv2.getTrackbarPos("Threshold1", "Parameters")
threshold2 = cv2.getTrackbarPos("Threshold2", "Parameters")
# imgCanny = cv2.Canny(imgGray,threshold1,threshold2)
# kernel = np.ones((5, 5))
# imgDil = cv2.dilate(imgCanny, kernel, iterations=1)
# getContours(imgDil,imgContour)
# imgStack = stackImages(0.3,([img,imgCanny],
# [imgDil,imgContour]))
lower = [80, 140, 180]
# upper = [143, 203, 239]
upper = [133, 193, 229]
# create NumPy arrays from the boundaries
lower = np.array(lower, dtype = "uint8")
upper = np.array(upper, dtype = "uint8")
# image = cv2.imread('figures/raw-chocolate.jpg')
capWebcam = cv2.VideoCapture('../figures/convey.mp4')
ret, image = capWebcam.read()
# print("heyyyyyy ", ret)
# if ret:
# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(image, lower, upper)
# output = cv2.bitwise_and(image, image, mask = mask)
maskContour = output.copy()
imgBlur = cv2.GaussianBlur(image, (7, 7), 1)
# imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)
imgCanny = cv2.Canny(imgBlur,threshold1,threshold2)
kernel = np.ones((5, 5))
imgDil = cv2.dilate(imgCanny, kernel, iterations=1)
# maskBlur = cv2.GaussianBlur(mask, (7, 7), 1)
# maskGray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
# threshold1 = cv2.getTrackbarPos("Threshold1", "Parameters")
# threshold2 = cv2.getTrackbarPos("Threshold2", "Parameters")
maskCanny = cv2.Canny(mask,threshold1,threshold2)
kernel = np.ones((5, 5))
maskDil = cv2.dilate(maskCanny, kernel, iterations=1)
getContours(maskDil, maskContour)
# getContours(mask, maskContour) #maybe works
# getContours(maskContour, imgDil)
maskStack = stackImages(0.3,([mask,maskCanny],
[maskDil,maskContour]))
# output = cv2.bitwise_and(image, image, mask = mask)
# # show the images
# cv2.imshow("images", np.hstack([mask, maskCanny]))
# cv2.waitKey(0)
cv2.imshow("Result", maskStack)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# else:
# print("boooo")
# break
|
{
"alphanum_fraction": 0.6017308046,
"author": null,
"avg_line_length": 36.2066666667,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "1bac210b97d768a7b43a3816352c4f50354b55ec",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "295cd8c5b7c256b6ae339ba25967e9c4b57ee146",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "aishao18/akrivis",
"max_forks_repo_path": "color/works/color_contour.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "295cd8c5b7c256b6ae339ba25967e9c4b57ee146",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "aishao18/akrivis",
"max_issues_repo_path": "color/works/color_contour.py",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "295cd8c5b7c256b6ae339ba25967e9c4b57ee146",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "aishao18/akrivis",
"max_stars_repo_path": "color/works/color_contour.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1655,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 5431
}
|
import tensorflow as tf
import numpy as np
from scipy import special
from nb_vae import NegativeBinomialVAE
class NegativeBinomialVAEb(NegativeBinomialVAE):
def _log_likelihood(self, h_r, h_p):
temp = tf.exp(-tf.multiply(tf.exp(h_r), tf.log(tf.exp(h_p) + 1)))
temp = tf.clip_by_value(temp, 1e-5, 1 - 1e-5)
ll = tf.multiply(self.input_ph, tf.log(1 - temp))
ll += tf.multiply(1 - self.input_ph, tf.log(temp))
return ll
def get_predictive_rate(self, h_r, h_p, test_data):
l_prime = 1 - np.power(special.expit(-h_p), np.exp(h_r))
return l_prime
|
{
"alphanum_fraction": 0.6489533011,
"author": null,
"avg_line_length": 20.0322580645,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "aa092ad105718ddeda5327ac7ffc9f28452ba5b1",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-06-30T03:08:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-31T06:00:52.000Z",
"max_forks_repo_head_hexsha": "d546f56e0b3ed39ea3d1421ae929e5f3cbe3c3dd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ethanhezhao/NBVAE",
"max_forks_repo_path": "nb_vae_b.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d546f56e0b3ed39ea3d1421ae929e5f3cbe3c3dd",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ethanhezhao/NBVAE",
"max_issues_repo_path": "nb_vae_b.py",
"max_line_length": 73,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "d546f56e0b3ed39ea3d1421ae929e5f3cbe3c3dd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ethanhezhao/NBVAE",
"max_stars_repo_path": "nb_vae_b.py",
"max_stars_repo_stars_event_max_datetime": "2021-12-17T06:04:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-29T04:07:22.000Z",
"num_tokens": 180,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 621
}
|
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This script extracts smaller images from the 1000x1000 dataset images
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import cleaner
from imageio import imread
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import pathlib
import os
def save_image(path, image, satellite):
if satellite == 'sen2':
#rescaled = (255.0/image.max() * (image-image.min())).astype(np.uint8)
img = Image.fromarray(image,'RGB')
img.save(path+'.png')
elif satellite == 'sen1':
#rescaled = (255.0/image.max() * (image-image.min())).astype(np.uint8)
img = Image.fromarray(image)
img.save(path+'.png')
windows = False
s2_path = '/Users/alessandrosebastianelli/Desktop/downloader_tool/code/dataset/sen2/*'
s1_path = '/Users/alessandrosebastianelli/Desktop/downloader_tool/code/dataset/sen1/*'
preview_path = '/Users/alessandrosebastianelli/Desktop/downloader_tool/code/dataset_patch/preview/'
date_names = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
fig, axes = plt.subplots(nrows = 2, ncols = 12, figsize = (40, 10))
s2_file_generator = cleaner.find(s2_path, windows)
s2_locations = cleaner.get_loactions(s2_path, windows)
s2_locations_genenerator = iter(cleaner.split_by_locations(s2_file_generator, s2_locations))
s1_file_generator = cleaner.find(s1_path, windows)
s1_locations = cleaner.get_loactions(s1_path, windows)
s1_locations_genenerator = iter(cleaner.split_by_locations(s1_file_generator, s1_locations))
l = 0
if len(s2_locations) < len(s1_locations):
l = len(s2_locations)
else:
l = len(s1_locations)
image = np.ones((1000,1000))
patch_x = 0
patch_y = 0
patch_size = 256
patch_num = 333
counter = 0
patch = np.ones((patch_size, patch_size))
# Iterate on scene
for i in range(0,l):
# Get S1 and S2 scene
s2_scene = next(s2_locations_genenerator)
s1_scene = next(s1_locations_genenerator)
print('> S2 - Scene: %s' % (s2_locations[i]))
print('> S1 - Scene: %s' % (s1_locations[i]))
print('> Scene %d of %d' % (i, l))
if s2_locations[i] == s1_locations[i]:
counter = 0
print('> Same')
for h in range(0, (1000//patch_size)):
for w in range(0, (1000//patch_size)):
print(' * Patch %d of %d' % (patch_num, 9*l))
date_generator = iter(cleaner.split_by_date(s2_scene, date_names))
for j in range(len(list(cleaner.split_by_date(s2_scene, date_names)))):
date = next(date_generator)
try:
image = imread(date[0])
patch = image[patch_y:patch_y+patch_size, patch_x:patch_x+patch_size, :]
path = date[0].replace('dataset','dataset_patch')
path = path.replace(s2_locations[i],'patch_'+ str(patch_num))
name = '_patch' + str(counter)
path = path.replace('.png',name)
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_image(path, patch, 'sen2')
os.rmdir(path)
#print(path)
except Exception:
print("Something may have gone wrong")
pass
axes[0,j].imshow(patch)
axes[0,j].set_title(date_names[j], fontsize=20)
image = np.ones((1000,1000))
patch = np.ones((patch_size, patch_size))
date_generator = iter(cleaner.split_by_date(s1_scene, date_names))
for j in range(len(list(cleaner.split_by_date(s1_scene, date_names)))):
date = next(date_generator)
try:
image = imread(date[0])
patch = image[patch_y:patch_y+patch_size, patch_x:patch_x+patch_size]
path = date[0].replace('dataset','dataset_patch')
path = path.replace(s1_locations[i],'patch_'+ str(patch_num))
name = '_patch' + str(counter)
path = path.replace('.png',name)
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_image(path, patch, 'sen1')
os.rmdir(path)
#print(path)
except Exception:
print("Something may have gone wrong")
pass
axes[1,j].imshow(patch, cmap = 'gray')
axes[1,j].set_title(date_names[j], fontsize=20)
image = np.ones((1000,1000))
patch = np.ones((patch_size, patch_size))
counter = counter+1
fig.tight_layout()
fig.savefig(preview_path+"patch_"+str(patch_num)+'.png')
patch_x = w*patch_size
patch_y = h*patch_size
patch_num = patch_num + 1
else:
print('> Not Same')
|
{
"alphanum_fraction": 0.5401099943,
"author": null,
"avg_line_length": 37.9352517986,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "3154e3cdf7ee92e3b1b1eda40eda3e52371b4003",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "51b785dc0555fbdd34aa37e0c8d7876c573244bf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-20-00065",
"max_forks_repo_path": "src/patch_extractor.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "51b785dc0555fbdd34aa37e0c8d7876c573244bf",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-20-00065",
"max_issues_repo_path": "src/patch_extractor.py",
"max_line_length": 99,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "51b785dc0555fbdd34aa37e0c8d7876c573244bf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Sebbyraft/SentinelDataDownloaderTool",
"max_stars_repo_path": "src/patch_extractor.py",
"max_stars_repo_stars_event_max_datetime": "2022-02-24T03:21:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-15T07:40:07.000Z",
"num_tokens": 1187,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 5273
}
|
# code was based on https://github.com/swz30/MPRNet
# Users should be careful about adopting these functions in any commercial matters.
# https://github.com/swz30/MPRNet/blob/main/LICENSE.md
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from ...modules.init import kaiming_normal_, constant_
from .builder import GENERATORS
def conv(in_channels, out_channels, kernel_size, bias_attr=False, stride=1):
return nn.Conv2D(in_channels,
out_channels,
kernel_size,
padding=(kernel_size // 2),
bias_attr=bias_attr,
stride=stride)
## Channel Attention Layer
class CALayer(nn.Layer):
def __init__(self, channel, reduction=16, bias_attr=False):
super(CALayer, self).__init__()
# global average pooling: feature --> point
self.avg_pool = nn.AdaptiveAvgPool2D(1)
# feature channel downscale and upscale --> channel weight
self.conv_du = nn.Sequential(
nn.Conv2D(channel,
channel // reduction,
1,
padding=0,
bias_attr=bias_attr), nn.ReLU(),
nn.Conv2D(channel // reduction,
channel,
1,
padding=0,
bias_attr=bias_attr), nn.Sigmoid())
def forward(self, x):
y = self.avg_pool(x)
y = self.conv_du(y)
return x * y
## Channel Attention Block (CAB)
class CAB(nn.Layer):
def __init__(self, n_feat, kernel_size, reduction, bias_attr, act):
super(CAB, self).__init__()
modules_body = []
modules_body.append(
conv(n_feat, n_feat, kernel_size, bias_attr=bias_attr))
modules_body.append(act)
modules_body.append(
conv(n_feat, n_feat, kernel_size, bias_attr=bias_attr))
self.CA = CALayer(n_feat, reduction, bias_attr=bias_attr)
self.body = nn.Sequential(*modules_body)
def forward(self, x):
res = self.body(x)
res = self.CA(res)
res += x
return res
##---------- Resizing Modules ----------
class DownSample(nn.Layer):
def __init__(self, in_channels, s_factor):
super(DownSample, self).__init__()
self.down = nn.Sequential(
nn.Upsample(scale_factor=0.5, mode='bilinear', align_corners=False),
nn.Conv2D(in_channels,
in_channels + s_factor,
1,
stride=1,
padding=0,
bias_attr=False))
def forward(self, x):
x = self.down(x)
return x
class UpSample(nn.Layer):
def __init__(self, in_channels, s_factor):
super(UpSample, self).__init__()
self.up = nn.Sequential(
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
nn.Conv2D(in_channels + s_factor,
in_channels,
1,
stride=1,
padding=0,
bias_attr=False))
def forward(self, x):
x = self.up(x)
return x
class SkipUpSample(nn.Layer):
def __init__(self, in_channels, s_factor):
super(SkipUpSample, self).__init__()
self.up = nn.Sequential(
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
nn.Conv2D(in_channels + s_factor,
in_channels,
1,
stride=1,
padding=0,
bias_attr=False))
def forward(self, x, y):
x = self.up(x)
x = x + y
return x
##########################################################################
## U-Net
class Encoder(nn.Layer):
def __init__(self, n_feat, kernel_size, reduction, act, bias_attr,
scale_unetfeats, csff):
super(Encoder, self).__init__()
self.encoder_level1 = [
CAB(n_feat, kernel_size, reduction, bias_attr=bias_attr, act=act)
for _ in range(2)
]
self.encoder_level2 = [
CAB(n_feat + scale_unetfeats,
kernel_size,
reduction,
bias_attr=bias_attr,
act=act) for _ in range(2)
]
self.encoder_level3 = [
CAB(n_feat + (scale_unetfeats * 2),
kernel_size,
reduction,
bias_attr=bias_attr,
act=act) for _ in range(2)
]
self.encoder_level1 = nn.Sequential(*self.encoder_level1)
self.encoder_level2 = nn.Sequential(*self.encoder_level2)
self.encoder_level3 = nn.Sequential(*self.encoder_level3)
self.down12 = DownSample(n_feat, scale_unetfeats)
self.down23 = DownSample(n_feat + scale_unetfeats, scale_unetfeats)
# Cross Stage Feature Fusion (CSFF)
if csff:
self.csff_enc1 = nn.Conv2D(n_feat,
n_feat,
kernel_size=1,
bias_attr=bias_attr)
self.csff_enc2 = nn.Conv2D(n_feat + scale_unetfeats,
n_feat + scale_unetfeats,
kernel_size=1,
bias_attr=bias_attr)
self.csff_enc3 = nn.Conv2D(n_feat + (scale_unetfeats * 2),
n_feat + (scale_unetfeats * 2),
kernel_size=1,
bias_attr=bias_attr)
self.csff_dec1 = nn.Conv2D(n_feat,
n_feat,
kernel_size=1,
bias_attr=bias_attr)
self.csff_dec2 = nn.Conv2D(n_feat + scale_unetfeats,
n_feat + scale_unetfeats,
kernel_size=1,
bias_attr=bias_attr)
self.csff_dec3 = nn.Conv2D(n_feat + (scale_unetfeats * 2),
n_feat + (scale_unetfeats * 2),
kernel_size=1,
bias_attr=bias_attr)
def forward(self, x, encoder_outs=None, decoder_outs=None):
enc1 = self.encoder_level1(x)
if (encoder_outs is not None) and (decoder_outs is not None):
enc1 = enc1 + self.csff_enc1(encoder_outs[0]) + self.csff_dec1(
decoder_outs[0])
x = self.down12(enc1)
enc2 = self.encoder_level2(x)
if (encoder_outs is not None) and (decoder_outs is not None):
enc2 = enc2 + self.csff_enc2(encoder_outs[1]) + self.csff_dec2(
decoder_outs[1])
x = self.down23(enc2)
enc3 = self.encoder_level3(x)
if (encoder_outs is not None) and (decoder_outs is not None):
enc3 = enc3 + self.csff_enc3(encoder_outs[2]) + self.csff_dec3(
decoder_outs[2])
return [enc1, enc2, enc3]
class Decoder(nn.Layer):
def __init__(self, n_feat, kernel_size, reduction, act, bias_attr,
scale_unetfeats):
super(Decoder, self).__init__()
self.decoder_level1 = [
CAB(n_feat, kernel_size, reduction, bias_attr=bias_attr, act=act)
for _ in range(2)
]
self.decoder_level2 = [
CAB(n_feat + scale_unetfeats,
kernel_size,
reduction,
bias_attr=bias_attr,
act=act) for _ in range(2)
]
self.decoder_level3 = [
CAB(n_feat + (scale_unetfeats * 2),
kernel_size,
reduction,
bias_attr=bias_attr,
act=act) for _ in range(2)
]
self.decoder_level1 = nn.Sequential(*self.decoder_level1)
self.decoder_level2 = nn.Sequential(*self.decoder_level2)
self.decoder_level3 = nn.Sequential(*self.decoder_level3)
self.skip_attn1 = CAB(n_feat,
kernel_size,
reduction,
bias_attr=bias_attr,
act=act)
self.skip_attn2 = CAB(n_feat + scale_unetfeats,
kernel_size,
reduction,
bias_attr=bias_attr,
act=act)
self.up21 = SkipUpSample(n_feat, scale_unetfeats)
self.up32 = SkipUpSample(n_feat + scale_unetfeats, scale_unetfeats)
def forward(self, outs):
enc1, enc2, enc3 = outs
dec3 = self.decoder_level3(enc3)
x = self.up32(dec3, self.skip_attn2(enc2))
dec2 = self.decoder_level2(x)
x = self.up21(dec2, self.skip_attn1(enc1))
dec1 = self.decoder_level1(x)
return [dec1, dec2, dec3]
## Original Resolution Block (ORB)
class ORB(nn.Layer):
def __init__(self, n_feat, kernel_size, reduction, act, bias_attr, num_cab):
super(ORB, self).__init__()
modules_body = []
modules_body = [
CAB(n_feat, kernel_size, reduction, bias_attr=bias_attr, act=act)
for _ in range(num_cab)
]
modules_body.append(conv(n_feat, n_feat, kernel_size))
self.body = nn.Sequential(*modules_body)
def forward(self, x):
res = self.body(x)
res += x
return res
class ORSNet(nn.Layer):
def __init__(self, n_feat, scale_orsnetfeats, kernel_size, reduction, act,
bias_attr, scale_unetfeats, num_cab):
super(ORSNet, self).__init__()
self.orb1 = ORB(n_feat + scale_orsnetfeats, kernel_size, reduction, act,
bias_attr, num_cab)
self.orb2 = ORB(n_feat + scale_orsnetfeats, kernel_size, reduction, act,
bias_attr, num_cab)
self.orb3 = ORB(n_feat + scale_orsnetfeats, kernel_size, reduction, act,
bias_attr, num_cab)
self.up_enc1 = UpSample(n_feat, scale_unetfeats)
self.up_dec1 = UpSample(n_feat, scale_unetfeats)
self.up_enc2 = nn.Sequential(
UpSample(n_feat + scale_unetfeats, scale_unetfeats),
UpSample(n_feat, scale_unetfeats))
self.up_dec2 = nn.Sequential(
UpSample(n_feat + scale_unetfeats, scale_unetfeats),
UpSample(n_feat, scale_unetfeats))
self.conv_enc1 = nn.Conv2D(n_feat,
n_feat + scale_orsnetfeats,
kernel_size=1,
bias_attr=bias_attr)
self.conv_enc2 = nn.Conv2D(n_feat,
n_feat + scale_orsnetfeats,
kernel_size=1,
bias_attr=bias_attr)
self.conv_enc3 = nn.Conv2D(n_feat,
n_feat + scale_orsnetfeats,
kernel_size=1,
bias_attr=bias_attr)
self.conv_dec1 = nn.Conv2D(n_feat,
n_feat + scale_orsnetfeats,
kernel_size=1,
bias_attr=bias_attr)
self.conv_dec2 = nn.Conv2D(n_feat,
n_feat + scale_orsnetfeats,
kernel_size=1,
bias_attr=bias_attr)
self.conv_dec3 = nn.Conv2D(n_feat,
n_feat + scale_orsnetfeats,
kernel_size=1,
bias_attr=bias_attr)
def forward(self, x, encoder_outs, decoder_outs):
x = self.orb1(x)
x = x + self.conv_enc1(encoder_outs[0]) + self.conv_dec1(
decoder_outs[0])
x = self.orb2(x)
x = x + self.conv_enc2(self.up_enc1(encoder_outs[1])) + self.conv_dec2(
self.up_dec1(decoder_outs[1]))
x = self.orb3(x)
x = x + self.conv_enc3(self.up_enc2(encoder_outs[2])) + self.conv_dec3(
self.up_dec2(decoder_outs[2]))
return x
# Supervised Attention Module
class SAM(nn.Layer):
def __init__(self, n_feat, kernel_size, bias_attr):
super(SAM, self).__init__()
self.conv1 = conv(n_feat, n_feat, kernel_size, bias_attr=bias_attr)
self.conv2 = conv(n_feat, 3, kernel_size, bias_attr=bias_attr)
self.conv3 = conv(3, n_feat, kernel_size, bias_attr=bias_attr)
def forward(self, x, x_img):
x1 = self.conv1(x)
img = self.conv2(x) + x_img
x2 = F.sigmoid(self.conv3(img))
x1 = x1 * x2
x1 = x1 + x
return x1, img
@GENERATORS.register()
class MPRNet(nn.Layer):
def __init__(self,
in_c=3,
out_c=3,
n_feat=96,
scale_unetfeats=48,
scale_orsnetfeats=32,
num_cab=8,
kernel_size=3,
reduction=4,
bias_attr=False):
super(MPRNet, self).__init__()
act = nn.PReLU()
self.shallow_feat1 = nn.Sequential(
conv(in_c, n_feat, kernel_size, bias_attr=bias_attr),
CAB(n_feat, kernel_size, reduction, bias_attr=bias_attr, act=act))
self.shallow_feat2 = nn.Sequential(
conv(in_c, n_feat, kernel_size, bias_attr=bias_attr),
CAB(n_feat, kernel_size, reduction, bias_attr=bias_attr, act=act))
self.shallow_feat3 = nn.Sequential(
conv(in_c, n_feat, kernel_size, bias_attr=bias_attr),
CAB(n_feat, kernel_size, reduction, bias_attr=bias_attr, act=act))
# Cross Stage Feature Fusion (CSFF)
self.stage1_encoder = Encoder(n_feat,
kernel_size,
reduction,
act,
bias_attr,
scale_unetfeats,
csff=False)
self.stage1_decoder = Decoder(n_feat, kernel_size, reduction, act,
bias_attr, scale_unetfeats)
self.stage2_encoder = Encoder(n_feat,
kernel_size,
reduction,
act,
bias_attr,
scale_unetfeats,
csff=True)
self.stage2_decoder = Decoder(n_feat, kernel_size, reduction, act,
bias_attr, scale_unetfeats)
self.stage3_orsnet = ORSNet(n_feat, scale_orsnetfeats, kernel_size,
reduction, act, bias_attr, scale_unetfeats,
num_cab)
self.sam12 = SAM(n_feat, kernel_size=1, bias_attr=bias_attr)
self.sam23 = SAM(n_feat, kernel_size=1, bias_attr=bias_attr)
self.concat12 = conv(n_feat * 2,
n_feat,
kernel_size,
bias_attr=bias_attr)
self.concat23 = conv(n_feat * 2,
n_feat + scale_orsnetfeats,
kernel_size,
bias_attr=bias_attr)
self.tail = conv(n_feat + scale_orsnetfeats,
out_c,
kernel_size,
bias_attr=bias_attr)
def forward(self, x3_img):
# Original-resolution Image for Stage 3
H = x3_img.shape[2]
W = x3_img.shape[3]
# Multi-Patch Hierarchy: Split Image into four non-overlapping patches
# Two Patches for Stage 2
x2top_img = x3_img[:, :, 0:int(H / 2), :]
x2bot_img = x3_img[:, :, int(H / 2):H, :]
# Four Patches for Stage 1
x1ltop_img = x2top_img[:, :, :, 0:int(W / 2)]
x1rtop_img = x2top_img[:, :, :, int(W / 2):W]
x1lbot_img = x2bot_img[:, :, :, 0:int(W / 2)]
x1rbot_img = x2bot_img[:, :, :, int(W / 2):W]
##-------------------------------------------
##-------------- Stage 1---------------------
##-------------------------------------------
## Compute Shallow Features
x1ltop = self.shallow_feat1(x1ltop_img)
x1rtop = self.shallow_feat1(x1rtop_img)
x1lbot = self.shallow_feat1(x1lbot_img)
x1rbot = self.shallow_feat1(x1rbot_img)
## Process features of all 4 patches with Encoder of Stage 1
feat1_ltop = self.stage1_encoder(x1ltop)
feat1_rtop = self.stage1_encoder(x1rtop)
feat1_lbot = self.stage1_encoder(x1lbot)
feat1_rbot = self.stage1_encoder(x1rbot)
## Concat deep features
feat1_top = [
paddle.concat((k, v), 3) for k, v in zip(feat1_ltop, feat1_rtop)
]
feat1_bot = [
paddle.concat((k, v), 3) for k, v in zip(feat1_lbot, feat1_rbot)
]
## Pass features through Decoder of Stage 1
res1_top = self.stage1_decoder(feat1_top)
res1_bot = self.stage1_decoder(feat1_bot)
## Apply Supervised Attention Module (SAM)
x2top_samfeats, stage1_img_top = self.sam12(res1_top[0], x2top_img)
x2bot_samfeats, stage1_img_bot = self.sam12(res1_bot[0], x2bot_img)
## Output image at Stage 1
stage1_img = paddle.concat([stage1_img_top, stage1_img_bot], 2)
##-------------------------------------------
##-------------- Stage 2---------------------
##-------------------------------------------
## Compute Shallow Features
x2top = self.shallow_feat2(x2top_img)
x2bot = self.shallow_feat2(x2bot_img)
## Concatenate SAM features of Stage 1 with shallow features of Stage 2
x2top_cat = self.concat12(paddle.concat([x2top, x2top_samfeats], 1))
x2bot_cat = self.concat12(paddle.concat([x2bot, x2bot_samfeats], 1))
## Process features of both patches with Encoder of Stage 2
feat2_top = self.stage2_encoder(x2top_cat, feat1_top, res1_top)
feat2_bot = self.stage2_encoder(x2bot_cat, feat1_bot, res1_bot)
## Concat deep features
feat2 = [paddle.concat((k, v), 2) for k, v in zip(feat2_top, feat2_bot)]
## Pass features through Decoder of Stage 2
res2 = self.stage2_decoder(feat2)
## Apply SAM
x3_samfeats, stage2_img = self.sam23(res2[0], x3_img)
##-------------------------------------------
##-------------- Stage 3---------------------
##-------------------------------------------
## Compute Shallow Features
x3 = self.shallow_feat3(x3_img)
## Concatenate SAM features of Stage 2 with shallow features of Stage 3
x3_cat = self.concat23(paddle.concat([x3, x3_samfeats], 1))
x3_cat = self.stage3_orsnet(x3_cat, feat2, res2)
stage3_img = self.tail(x3_cat)
return [stage3_img + x3_img, stage2_img, stage1_img]
|
{
"alphanum_fraction": 0.515240449,
"author": null,
"avg_line_length": 37.7126213592,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "9be802a19b437805a3ca0e988b9591d37dceda8f",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T11:40:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-28T02:07:31.000Z",
"max_forks_repo_head_hexsha": "b4ff90f0c92c4d8dcaa8e25267151b82fc7aa268",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "pcwuyu/PaddleGAN",
"max_forks_repo_path": "ppgan/models/generators/mpr.py",
"max_issues_count": 38,
"max_issues_repo_head_hexsha": "b4ff90f0c92c4d8dcaa8e25267151b82fc7aa268",
"max_issues_repo_issues_event_max_datetime": "2021-12-24T06:09:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-10-14T12:55:45.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "pcwuyu/PaddleGAN",
"max_issues_repo_path": "ppgan/models/generators/mpr.py",
"max_line_length": 83,
"max_stars_count": 40,
"max_stars_repo_head_hexsha": "b4ff90f0c92c4d8dcaa8e25267151b82fc7aa268",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "pcwuyu/PaddleGAN",
"max_stars_repo_path": "ppgan/models/generators/mpr.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T09:54:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-28T02:07:28.000Z",
"num_tokens": 4468,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 19422
}
|
SUBROUTINE SWAP_STRING(ISTAT)
!=======================================================================
! LATEST CORRECTION BY
!
! PURPOSE
! Swap strings in the slave file
!
! PROGRAMMED BY: bjorn.melhus@akersolutions.com
! CREATED......: 10.05.2021
!=======================================================================
use cfast
use clist
implicit none
integer istat
INTEGER ISWAP_FAST,ipar
CHARACTER*4 CEXT_SWAP,CNUM
CHARACTER*136 FNAME,THIS,THAT,FNEW
!
! Master files
DO ISWAP_FAST=1,SLAVE%NSWAP
! Extract the slave file e.g ".fst"
CEXT_SWAP=SLAVE%CSWAP(ISWAP_FAST)(len(trim(SLAVE%CSWAP(ISWAP_FAST)))-3:)
!
FNAME=trim(SLAVE%CSWAP(ISWAP_FAST))
!
! Update the slave files with new references to the slave files
!
THIS=TRIM(SLAVE%CSWAP_STR_FROM(ISWAP_FAST))
DO IPAR=1,NPARA
WRITE(CNUM,'(I4)') IPAR
FNEW=SLAVE%CSWAP(ISWAP_FAST)(1:len(trim(SLAVE%CSWAP(ISWAP_FAST)))-4)// &
'_'//CANA//'_'//trim(adjustl(CNUM))//CEXT_SWAP
THAT=TRIM(SLAVE%CSWAP_STR_TO(IPAR,ISWAP_FAST))
! Hack the file...i.e. take the file FNAME and replace THIS with THAT
! and call the new file FNEW.
! Make a quick and dirty solution.... bet that FNEW already exists...
! i.e. just replace strings in the file FNEW.
CALL FILEHACK(trim(FNEW),trim(THIS),trim(THAT),trim(FNEW))
ENDDO
ENDDO
!
RETURN
END
|
{
"alphanum_fraction": 0.5400898012,
"author": null,
"avg_line_length": 36.2558139535,
"converted": null,
"ext": "f90",
"file": null,
"hexsha": "10aaaeb3ce49e6b23c390dab6f17284c599038ac",
"include": null,
"lang": "FORTRAN",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "d1b137a2d2ebfbbce2e42fff25220771e28bdfa2",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Ry8ics/Faster",
"max_forks_repo_path": "Faster/src/swap_string.f90",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d1b137a2d2ebfbbce2e42fff25220771e28bdfa2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Ry8ics/Faster",
"max_issues_repo_path": "Faster/src/swap_string.f90",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d1b137a2d2ebfbbce2e42fff25220771e28bdfa2",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Ry8ics/Faster",
"max_stars_repo_path": "Faster/src/swap_string.f90",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 445,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 1559
}
|
import logging
import cmapPy.pandasGEXpress.setup_GCToo_logger as setup_logger
import numpy
logger = logging.getLogger(setup_logger.LOGGER_NAME)
def fast_cov(x, y=None):
"""calculate the covariance matrix for the columns of x (MxN), or optionally, the covariance matrix between the
columns of x and and the columns of y (MxP). (In the language of statistics, the columns are variables, the rows
are observations).
Args:
x (numpy array-like) MxN in shape
y (numpy array-like) MxP in shape
returns (numpy array-like) array of the covariance values
for defaults (y=None), shape is NxN
if y is provided, shape is NxP
"""
validate_x_y(x, y)
if y is None:
y = x
mean_x = numpy.mean(x, axis=0)
mean_y = numpy.mean(y, axis=0)
mean_centered_x = x - mean_x
mean_centered_y = y - mean_y
dotprod = numpy.dot(mean_centered_x.T, mean_centered_y)
denom = x.shape[0] - 1
return dotprod / denom
def validate_x_y(x, y):
error_msg = ""
if not hasattr(x, "shape"):
error_msg += "x needs to be numpy array-like but it does not have \"shape\" attribute - type(x): {}\n".format(type(x))
if y is not None:
if not hasattr(y, "shape"):
error_msg += "y needs to be numpy array-like but it does not have \"shape\" attribute - type(y): {}\n".format(type(y))
elif x.shape[0] != y.shape[0]:
error_msg += "the number of rows in the x and y matrices must be the same".format(x.shape, y.shape)
if error_msg != "":
raise CmapPyMathFastCovInvalidInputXY(error_msg)
class CmapPyMathFastCovInvalidInputAxis(Exception):
pass
class CmapPyMathFastCovInvalidInputXY(Exception):
pass
|
{
"alphanum_fraction": 0.6519524618,
"author": null,
"avg_line_length": 29.45,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "955caadc08cb09e1a9a39a771c2927cfb8a6101c",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "580b0d656892e72f58047666a94e2769ddf63b3f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "RCBiczok/cmapPy",
"max_forks_repo_path": "cmapPy/math/fast_cov.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "580b0d656892e72f58047666a94e2769ddf63b3f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "RCBiczok/cmapPy",
"max_issues_repo_path": "cmapPy/math/fast_cov.py",
"max_line_length": 131,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "580b0d656892e72f58047666a94e2769ddf63b3f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "RCBiczok/cmapPy",
"max_stars_repo_path": "cmapPy/math/fast_cov.py",
"max_stars_repo_stars_event_max_datetime": "2019-12-15T06:33:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-15T06:33:53.000Z",
"num_tokens": 468,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1767
}
|
[STATEMENT]
lemma dg_Funct_is_arrI:
assumes "\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>m \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>m\<^bsub>\<alpha>\<^esub> \<BB>"
shows "ntcf_arrow \<NN> : cf_map \<FF> \<mapsto>\<^bsub>dg_Funct \<alpha> \<AA> \<BB>\<^esub> cf_map \<GG>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ntcf_arrow \<NN> : cf_map \<FF> \<mapsto>\<^bsub>dg_Funct \<alpha> \<AA> \<BB>\<^esub> cf_map \<GG>
[PROOF STEP]
proof(intro is_arrI, unfold dg_Funct_components(1,2))
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. ntcf_arrow \<NN> \<in>\<^sub>\<circ> tm_ntcf_arrows \<alpha> \<AA> \<BB>
2. dg_Funct \<alpha> \<AA> \<BB>\<lparr>Dom\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<FF>
3. dg_Funct \<alpha> \<AA> \<BB>\<lparr>Cod\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<GG>
[PROOF STEP]
interpret is_tm_ntcf \<alpha> \<AA> \<BB> \<FF> \<GG> \<NN>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>m \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>m\<^bsub>\<alpha>\<^esub> \<BB>
[PROOF STEP]
by (rule assms)
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. ntcf_arrow \<NN> \<in>\<^sub>\<circ> tm_ntcf_arrows \<alpha> \<AA> \<BB>
2. dg_Funct \<alpha> \<AA> \<BB>\<lparr>Dom\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<FF>
3. dg_Funct \<alpha> \<AA> \<BB>\<lparr>Cod\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<GG>
[PROOF STEP]
from assms
[PROOF STATE]
proof (chain)
picking this:
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>m \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>m\<^bsub>\<alpha>\<^esub> \<BB>
[PROOF STEP]
show "ntcf_arrow \<NN> \<in>\<^sub>\<circ> tm_ntcf_arrows \<alpha> \<AA> \<BB>"
[PROOF STATE]
proof (prove)
using this:
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>m \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>m\<^bsub>\<alpha>\<^esub> \<BB>
goal (1 subgoal):
1. ntcf_arrow \<NN> \<in>\<^sub>\<circ> tm_ntcf_arrows \<alpha> \<AA> \<BB>
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
ntcf_arrow \<NN> \<in>\<^sub>\<circ> tm_ntcf_arrows \<alpha> \<AA> \<BB>
goal (2 subgoals):
1. dg_Funct \<alpha> \<AA> \<BB>\<lparr>Dom\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<FF>
2. dg_Funct \<alpha> \<AA> \<BB>\<lparr>Cod\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<GG>
[PROOF STEP]
from assms
[PROOF STATE]
proof (chain)
picking this:
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>m \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>m\<^bsub>\<alpha>\<^esub> \<BB>
[PROOF STEP]
show
"dg_Funct \<alpha> \<AA> \<BB>\<lparr>Dom\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<FF>"
"dg_Funct \<alpha> \<AA> \<BB>\<lparr>Cod\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<GG>"
[PROOF STATE]
proof (prove)
using this:
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>m \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>m\<^bsub>\<alpha>\<^esub> \<BB>
goal (1 subgoal):
1. dg_Funct \<alpha> \<AA> \<BB>\<lparr>Dom\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<FF> &&& dg_Funct \<alpha> \<AA> \<BB>\<lparr>Cod\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<GG>
[PROOF STEP]
by (cs_concl cs_shallow cs_simp: dg_FUNCT_cs_simps)+
[PROOF STATE]
proof (state)
this:
dg_Funct \<alpha> \<AA> \<BB>\<lparr>Dom\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<FF>
dg_Funct \<alpha> \<AA> \<BB>\<lparr>Cod\<rparr>\<lparr>ntcf_arrow \<NN>\<rparr> = cf_map \<GG>
goal:
No subgoals!
[PROOF STEP]
qed
|
{
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": "CZH_Elementary_Categories_czh_ecategories_CZH_DG_FUNCT",
"hexsha": null,
"include": null,
"lang": null,
"length": 10,
"llama_tokens": 1688,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": null
}
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2014 Jonathan F. Donges
# Author: Jonathan F. Donges <donges@pik-potsdam.de>
# URL: <http://www.pik-potsdam.de/members/donges/software>
"""
Performs recurrence analysis of an ensemble of time series generated by the
COPRA algorithm corresponding to a single proxy record.
This script provides analyses for this publication:
J.F. Donges, R.V. Donner, N. Marwan, S.F.M. Breitenbach, K. Rehfeld, and J. Kurths,
Nonlinear regime shifts in Holocene Asian monsoon variability: Potential impacts on cultural change and migratory patterns,
Climate of the Past 11, 709-741 (2015),
DOI: 10.5194/cp-11-709-2015
For the COPRA algorithm refer to:
S.F.M. Breitenbach et al. (2012),
COnstructing Proxy Records from Age models (COPRA),
Climate of the Past 8, 1765–1779, doi: 10.5194/cp-8-1765-2012.
"""
#
# Imports
#
import cPickle
# Import np for fast numerics
import numpy as np
# Import progress bar for easy progress bar handling
import progressbar
# Import class for recurrence network analysis
from pyunicorn.timeseries import RecurrenceNetwork
#
# Settings
#
# Name of data directory
DATA_DIR = "../../data/copra_ensemble_data/"
# Give filename
FILENAME = "dongge_realisations.txt"
# Give name of record
NAME = "DONGGE"
# Specify symbol used for commenting in data file
COMMENT_SYMBOL = "%"
# Settings for the time dependent recurrence plot
# Window length [a] / [ka]
T_TIME = 750.
# Step size [a] / [ka]
DELTA_TIME = 50.
# Settings for the embedding
DIM = 3 # embedding dimension
DELAY = 185. # embedding delay in units of [a] / [ka]
# Settings for the recurrence plot
METRIC = "supremum"
RR = 0.05
# Settings for significance testing
# Ensemble size
N_ENSEMBLE = 100
# Choose whether whole embedded state vectors or the scalar time series should be shuffled (Different null-hypothesis!)
SHUFFLE_EMBEDDED = True
# Settings for detrending
DETREND = True
DETRENDING_WINDOW_SIZE = 1000. # measured in [a] / [ka]
#
# Functions
#
def detrend_time_series(data, window_size):
"""
"""
# Get length of data array
n = data.shape[0]
# Initialize a local copy of data array
detrended_data = np.empty(n)
# Detrend data
for j in xrange(n):
# Get distance of sample from boundaries of time series
dist = min(j, n - 1 - j)
if window_size / 2 > dist:
half_size = dist
else:
half_size = window_size / 2
detrended_data[j] = data[j] - data[j - half_size:j + half_size + 1].mean()
return detrended_data
#
# The main script
#
print "Analyzing ensemble of time series generated by COPRA"
print "----------------------------------------------------"
#
# Import data
#
print "Loading data..."
# Load data
data = np.loadtxt(DATA_DIR + FILENAME, comments=COMMENT_SYMBOL).transpose()
print "Mean sampling time:", np.diff(data[0,:]).mean()
print "STD sampling time:", np.diff(data[0,:]).std()
# Take only every fourth data point, reduces time-resolution of COPRA records
# Also, look at smaller number of 100 COPRA realizations
time = data[0, ::4]
values = data[1:101, ::4]
# Remove NaNs
is_not_nan = np.all(np.logical_not(np.isnan(values)), axis=0)
time = time[is_not_nan]
values = values[:, is_not_nan]
# Get time series properties
average_sampling_time = np.diff(time).mean()
n_realizations = values.shape[0]
if DETREND:
# Detrend data!
print "Detrending data..."
for i in xrange(n_realizations):
values[i,:] = detrend_time_series(data=values[i,:], window_size=DETRENDING_WINDOW_SIZE / average_sampling_time)
#
# Print some statistics
#
print "Average sampling time:"
print NAME, ": (", np.diff(time).mean(), "pm", np.diff(time).std(), ") a"
#
# Analyze time dependent recurrence networks by moving a window over the time series
#
# Create dictionary of symbols for each windowed measure to be calculated
symbols = {"Transitivity": "$\mathcal{T}$",
"Average path length": "$\mathcal{L}$"}
#symbols = {"Average path length": "$\mathcal{L}$",
# "n.s.i. average path length": "$\mathcal{L}^*$",
# "Clustering": "$\mathcal{C}$",
# "n.s.i. clustering": "$\mathcal{C}^*$"}
#symbols = {"Determinism": "$DET$",
# "Laminarity": "$LAM$",
# "Mean diagonal line length": "$L_{mean}$",
# "Trapping time": "$TT$",
# "Diagonal line entropy": "$ENTR$",
# "Autocorrelation": "$ACF(1)$",
# "Mean": "Mean",
# "Standard deviation": "STD"}
# Get window and step size in units of samples
T = int(T_TIME / average_sampling_time)
delta = int(DELTA_TIME / average_sampling_time)
# Get embedding delay in units of samples
TAU = int(DELAY / average_sampling_time)
# Get length of time series
t_max = len(time)
# Get required time series length before embedding to achive window length T
# in the recurrence plot
T_embedded = T + (DIM - 1) * TAU
# Get number of steps
t_steps = int((t_max - T_embedded) / float(delta) + 1)
print "Length of dust record:", t_max
print "Size of moving window:", T
print "Step size:", delta
print "Number of steps for moving window:", t_steps
print "Embedding dimension:", DIM
print "Embedding delay:", TAU
print "Prescribed link density / recurrence rate:", RR
# Initialize
step_sequence = np.zeros(t_steps, dtype=int)
results = {}
surrogate_results = {}
for measure in symbols.keys():
results[measure] = np.zeros((n_realizations,t_steps))
surrogate_results[measure] = np.zeros((n_realizations,N_ENSEMBLE))
print "Analysing time series realizations..."
# Initialize progress bar
progress = progressbar.ProgressBar().start()
# Run analysis for each realization separately
for i in xrange(n_realizations):
# Loop over moving windows
for j in xrange(t_steps):
# Get time series section for current window
time_series = values[i,j * delta:j * delta + T_embedded]
step_sequence[j] = j * delta + T_embedded / 2
# Prepare recurrence network from original data
rec_net = RecurrenceNetwork(time_series.copy(), dim=DIM, tau=TAU,
metric=METRIC, normalize=False,
silence_level=2, recurrence_rate=RR)
# Calculations for original recurrence network
results["Transitivity"][i,j] = rec_net.transitivity()
results["Average path length"][i,j] = rec_net.average_path_length()
#results["Assortativity"][i,j] = rec_net.assortativity()
#results["Diameter"][i,j] = rec_net.diameter()
# Calculate RQA measures
#local_result["Determinism"][j] = rec_net.determinism()
#local_result["Laminarity"][j] = rec_net.laminarity()
#local_result["Mean diagonal line length"][j] = rec_net.average_diaglength()
#local_result["Trapping time"][j] = rec_net.trapping_time()
#local_result["Diagonal line entropy"][j] = rec_net.diag_entropy()
#local_result["Autocorrelation"][j] = autocorrelation(time_series,
# lag=1)
#local_result["Mean"][j] = time_series.mean()
#local_result["Standard deviation"][j] = time_series.std()
#
# Calculate significance levels for network measures
#
# Create a copy of time series realization for generating surrogates from
surrogate_data = values[i,:].copy()
if SHUFFLE_EMBEDDED:
# Get embedding of full time series
surrogate_embedding = rec_net.embed_time_series(surrogate_data, DIM,
TAU)
for j in xrange(N_ENSEMBLE):
if SHUFFLE_EMBEDDED:
# Shuffle embedded time series along time axis, that is,
# whole embedded state vectors are
# shuffled around.
permuted_indices = np.random.permutation(surrogate_embedding.shape[0])
# Use the first T state vectors from the shuffled and embedded
# time series as a surrogate for one window
surrogate_series = surrogate_embedding[permuted_indices[:T],:]
# Prepare recurrence network from surrogate data for shuffled
# embedded time series
rec_net = RecurrenceNetwork(surrogate_series.copy(), metric=METRIC,
normalize=False, silence_level=2,
recurrence_rate=RR)
else:
# Shuffle dust time series
permuted_indices = np.random.permutation(surrogate_data.shape[0])
# Use the first T_embedded states from the shuffled dust time
# series as a surrogate for one window
surrogate_series = surrogate_data[permuted_indices[:T_embedded]]
# Prepare recurrence network from surrogate data for shuffled
# time series
rec_net = RecurrenceNetwork(surrogate_series.copy(), dim=DIM,
tau=TAU, metric=METRIC,
normalize=False, silence_level=2,
recurrence_rate=RR)
# Calculate measures for surrogate network
surrogate_results["Average path length"][i,j] = rec_net.average_path_length()
surrogate_results["Transitivity"][i,j] = rec_net.transitivity()
#surrogate_results["Assortativity"][i,j] = rec_net.assortativity()
#surrogate_results["Diameter"][i,j] = rec_net.diameter()
#surrogate_result["Determinism"][i,j] = rec_net.determinism()
#surrogate_result["Laminarity"][i,j] = rec_net.laminarity()
# Calculate RQA measures
#local_surrogate_result["Determinism"][j] = rec_net.determinism()
#local_surrogate_result["Laminarity"][j] = rec_net.laminarity()
#local_surrogate_result["Mean diagonal line length"][j] = rec_net.average_diaglength()
#local_surrogate_result["Trapping time"][j] = rec_net.trapping_time()
#local_surrogate_result["Diagonal line entropy"][j] = rec_net.diag_entropy()
#local_surrogate_result["Autocorrelation"][j] = autocorrelation(data, lag=1)
#local_surrogate_result["Mean"][j] = data.mean()
#local_surrogate_result["Standard deviation"][j] = data.std()
# Update progress bar every step
progress.update(int(100 * i / float(n_realizations)))
# Terminate progress bar
progress.finish()
#
# Save results
#
print "Saving results..."
# Initialize storage dictionary
storage = {}
# Store parameters
storage["FILENAME"] = FILENAME
storage["NAME"] = NAME
storage["T_TIME"] = T_TIME
storage["DELTA_TIME"] = DELTA_TIME
storage["DETRENDING_WINDOW_SIZE"] = DETRENDING_WINDOW_SIZE
storage["DIM"] = DIM
storage["TAU"] = TAU
storage["METRIC"] = METRIC
storage["RR"] = RR
storage["N_ENSEMBLE"] = N_ENSEMBLE
storage["SHUFFLE_EMBEDDED"] = SHUFFLE_EMBEDDED
# Store symbols
storage["symbols"] = symbols
# Store raw input data
storage["time"] = time
storage["values"] = values
# Store axes
storage["step_sequence"] = step_sequence
# Store results
storage["results"] = results
storage["surrogate_results"] = surrogate_results
# Save to file
filename = "results_copra_ensemble_DIM_" + str(DIM) + "_TAU_" + str(TAU) + "_M_" + str(N_ENSEMBLE) + "_DETREND_" + str(DETREND) + "_" + NAME + ".pickle"
file = open(filename, 'w')
cPickle.dump(storage, file)
file.close()
|
{
"alphanum_fraction": 0.6560915924,
"author": null,
"avg_line_length": 31.6952908587,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "c04e00833334a76795e9250c806a5436b613a879",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2020-10-03T12:19:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-05-25T02:51:59.000Z",
"max_forks_repo_head_hexsha": "a0980b62759eb6ac1d31d9e128423463e3cdf9de",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "pik-copan/pyregimeshifts",
"max_forks_repo_path": "scripts/copra_ensembles_analysis/recurrence_analysis_copra_ensemble_single_record.py",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "a0980b62759eb6ac1d31d9e128423463e3cdf9de",
"max_issues_repo_issues_event_max_datetime": "2019-06-27T12:01:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-06-27T12:00:19.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "pik-copan/pyregimeshifts",
"max_issues_repo_path": "scripts/copra_ensembles_analysis/recurrence_analysis_copra_ensemble_single_record.py",
"max_line_length": 152,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "a0980b62759eb6ac1d31d9e128423463e3cdf9de",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "pik-copan/pyregimeshifts",
"max_stars_repo_path": "scripts/copra_ensembles_analysis/recurrence_analysis_copra_ensemble_single_record.py",
"max_stars_repo_stars_event_max_datetime": "2021-08-14T03:23:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-23T19:38:43.000Z",
"num_tokens": 2886,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 11442
}
|
import cv2
import numpy as np
import math
import scipy.ndimage
def frequest(im, orientim, kernel_size, minWaveLength, maxWaveLength):
#bir parmak izi resminin kucuk bir blogu iCindeki sırt frekansini tahmin etme işlevi
#bir tepe frekansi bulunamazsa veya min ve maks ile belirlenen sinirlar dahilinde bulunamazsa, dalga boyu frekansı sıfır olarak ayarlanır
rows, cols = np.shape(im) #fotografin y ve x boyut bilgileri alinir.
cosorient = np.cos(2*orientim) #blok içindeki ortalama yönelimi bulduktan sonra açıyı yeniden yapılandırmadan once
sinorient = np.sin(2*orientim) #iki katina çıkan açıların sinüslerinin ve kosinüslerinin ortalamasını alarak yapılır
block_orient = math.atan2(sinorient,cosorient)/2
rotim = scipy.ndimage.rotate(im,block_orient/np.pi*180 + 90,axes=(1,0),reshape = False,order = 3,mode = 'nearest') #goruntu blogu sırtlar dikey olacak sekilde dondurulur
cropsze = int(np.fix(rows/np.sqrt(2))) #döndürülen görüntünün geçersiz bölge içermemesi için goruntu kirpilir
offset = int(np.fix((rows-cropsze)/2))
rotim = rotim[offset:offset+cropsze][:,offset:offset+cropsze]
ridge_sum = np.sum(rotim, axis = 0) #sirtlardaki gri değerlerin yansımasını elde etmek için sutunlar toplanir
dilation = scipy.ndimage.grey_dilation(ridge_sum, kernel_size, structure=np.ones(kernel_size))
ridge_noise = np.abs(dilation - ridge_sum); peak_thresh = 2;
maxpts = (ridge_noise < peak_thresh) & (ridge_sum > np.mean(ridge_sum))
maxind = np.where(maxpts)
_, no_of_peaks = np.shape(maxind)
if(no_of_peaks<2):
freq_block = np.zeros(im.shape)
else:
waveLength = (maxind[0][-1] - maxind[0][0])/(no_of_peaks - 1) #birinci ve son zirveler arasındaki mesafe (Tepe sayısı-1) 'e bolunerek
if waveLength>=minWaveLength and waveLength<=maxWaveLength: #sirtlarin uzamsal frekansi belirlenir
freq_block = 1/np.double(waveLength) * np.ones(im.shape)
else: #hic bir tepe algılanmazsa veya dalga boyu izin verilen sınırların dışındaysa
freq_block = np.zeros(im.shape) #frekans görüntüsü 0 olarak ayarlanır
return(freq_block)
def ridge_freq(im, mask, orient, block_size, kernel_size, minWaveLength, maxWaveLength): # Parmak izi görüntüsü boyunca parmak izi sırt frekansını tahmin etmek icin fonk.
rows,cols = im.shape
freq = np.zeros((rows,cols)) #sifir ile yeni bir dizi olarak döner
for row in range(0, rows - block_size, block_size):
for col in range(0, cols - block_size, block_size):
image_block = im[row:row + block_size][:, col:col + block_size] #her bir sütun ve satır icin
angle_block = orient[row // block_size][col // block_size] #resim ve aci bloklar olusturulur
if angle_block:
freq[row:row + block_size][:, col:col + block_size] = frequest(image_block, angle_block, kernel_size, minWaveLength, maxWaveLength)
freq = freq*mask #frekansı mask ile carpilir
freq_1d = np.reshape(freq,(1,rows*cols)) #frekans dizisine verilerini değiştirmeden yeniden sekillendirme
ind = np.where(freq_1d>0) #freq_1d in sifirdan buyuk oldugu yerler ind içine yazilir
ind = np.array(ind) #ind diziye çevrilir
ind = ind[1,:] #ind arrayın birden küçük değerleri kesilir
non_zero_elems_in_freq = freq_1d[0][ind]
medianfreq = np.median(non_zero_elems_in_freq) * mask #medyan degeri
return medianfreq
|
{
"alphanum_fraction": 0.7283372365,
"author": null,
"avg_line_length": 66.9803921569,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "35fba72956ada341642635dcef4fe65a04478c66",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "12876ef8f727f991ec5549ebcbe92fa142d0cb88",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "fatiihbulbul/fingerprint-feature-extraction",
"max_forks_repo_path": "moduls/frekans.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "12876ef8f727f991ec5549ebcbe92fa142d0cb88",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "fatiihbulbul/fingerprint-feature-extraction",
"max_issues_repo_path": "moduls/frekans.py",
"max_line_length": 173,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "12876ef8f727f991ec5549ebcbe92fa142d0cb88",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "fatiihbulbul/fingerprint-feature-extraction",
"max_stars_repo_path": "moduls/frekans.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1112,
"path": null,
"reason": "import numpy,import scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3416
}
|
using CreditApprovalStub
using Test
@testset "CreditApprovalStub.jl" begin
# stubs
check_background_success(first_name, last_name) = true
check_background_failure(first_name, last_name) = false
# testing
let first_name = "John", last_name = "Doe", email = "jdoe@julia-is-awesome.com"
@test open_account(first_name, last_name, email, checker = check_background_success) == :success
@test open_account(first_name, last_name, email, checker = check_background_failure) == :failure
end
end
|
{
"alphanum_fraction": 0.7791164659,
"author": null,
"avg_line_length": 29.2941176471,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "8f6a09c67484184c41859d12116a9dc267137ff1",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 33,
"max_forks_repo_forks_event_max_datetime": "2022-01-24T07:38:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-14T05:17:17.000Z",
"max_forks_repo_head_hexsha": "ee95448d05c63db8de3a5e9e27c9351cb6cc0e88",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Moelf/Hands-on-Design-Patterns-and-Best-Practices-with-Julia",
"max_forks_repo_path": "Chapter09/CreditApprovalStub/test/runtests.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ee95448d05c63db8de3a5e9e27c9351cb6cc0e88",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Moelf/Hands-on-Design-Patterns-and-Best-Practices-with-Julia",
"max_issues_repo_path": "Chapter09/CreditApprovalStub/test/runtests.jl",
"max_line_length": 100,
"max_stars_count": 167,
"max_stars_repo_head_hexsha": "ee95448d05c63db8de3a5e9e27c9351cb6cc0e88",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Moelf/Hands-on-Design-Patterns-and-Best-Practices-with-Julia",
"max_stars_repo_path": "Chapter09/CreditApprovalStub/test/runtests.jl",
"max_stars_repo_stars_event_max_datetime": "2022-03-28T09:33:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-07T14:38:43.000Z",
"num_tokens": 127,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 498
}
|
From Test Require Import tactic.
Section FOFProblem.
Variable Universe : Set.
Variable UniverseElement : Universe.
Variable wd_ : Universe -> Universe -> Prop.
Variable col_ : Universe -> Universe -> Universe -> Prop.
Variable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)).
Variable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)).
Variable col_triv_3 : (forall A B : Universe, col_ A B B).
Variable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)).
Variable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\ (col_ P Q A /\ (col_ P Q B /\ col_ P Q C))) -> col_ A B C)).
Theorem pipo_6 : (forall A B T P : Universe, ((wd_ A B /\ (col_ A B P /\ (col_ A B T /\ col_ T P A))) -> col_ T P B)).
Proof.
time tac.
Qed.
End FOFProblem.
|
{
"alphanum_fraction": null,
"author": "janicicpredrag",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/coq/janicicpredrag-Larus/Larus-a095ca588fbb0e4a64a26d92946485bbf85e1e08/benchmarks/coq-problems/col-trans/col_trans_0616.v",
"reason": null,
"repo": "Larus",
"save_path": "github-repos/coq/janicicpredrag-Larus",
"sha": "a095ca588fbb0e4a64a26d92946485bbf85e1e08",
"size": null
}
|
import itertools
import numpy as np
import matplotlib.pyplot as plt
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
#plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
def convertDir2Deg(d):
if d == 'N':
return 0
elif d == 'NNE':
return 22.5
elif d == 'NE':
return 45
elif d == 'ENE':
return 67.5
elif d == 'E':
return 90
elif d == 'ESE':
return 112.5
elif d == 'SE':
return 135
elif d == 'SSE':
return 157.5
elif d == 'S':
return 180
elif d == 'SSW':
return 202.5
elif d == 'SW':
return 225
elif d == 'WSW':
return 247.5
elif d == 'W':
return 270.0
elif d == 'WNW':
return 292.5
elif d == 'NW':
return 315
elif d == 'NNW':
return 337.5
else:
raise
|
{
"alphanum_fraction": 0.5586436909,
"author": null,
"avg_line_length": 26.4558823529,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "768e1903fb88a5833224b7c3677ac58bac1f58e8",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0964e042599bb41d2c523a3f05075775449b7d14",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tiombo/Projet-Final",
"max_forks_repo_path": "projet2/helpers.py",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "0964e042599bb41d2c523a3f05075775449b7d14",
"max_issues_repo_issues_event_max_datetime": "2021-08-23T20:43:45.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-27T22:31:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tiombo/Projet-Final",
"max_issues_repo_path": "projet2/helpers.py",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0964e042599bb41d2c523a3f05075775449b7d14",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tiombo/Projet-Final",
"max_stars_repo_path": "projet2/helpers.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 493,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1799
}
|
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.constants import golden
mpl.rc("text", usetex=True)
mpl.rc("font", family="serif")
x = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1])
t = np.array([1.15, 0.84, 0.39, 0.14, 0, 0.56, 1.16, 1.05, 1.45, 2.39, 1.86])
def f(x):
return 1 + np.sin(-(3/2) * np.pi * x) + (1/3) * np.sin(5 * np.pi * x)
M = 3
N = len(x)
X = np.zeros((N, M+1))
for m in range(M+1):
X[:, m] = x**m
beta = np.linalg.inv(X.T @ X) @ X.T @ t
h = np.poly1d(np.flip(beta, 0))
x_ = np.linspace(0.219, 0.421, 250)
t_ = h(x_)
xs = np.array([0.28, 0.38])
fig = plt.figure(figsize=(6,6/golden))
ax = fig.add_subplot()
ax.plot(x_, t_,
color = "turquoise",
linewidth = 1,
zorder = 1
)
ax.scatter(xs, h(xs),
edgecolors = "magenta",
c = "None",
s = 12.5,
marker = "o",
zorder = 2
)
ax.set_xticks(xs)
ax.set_xticklabels(["$x_i$", "$x_j$"])
ax.set_xlim(0.22, 0.42)
ax.set_yticks(h(xs))
ax.set_yticklabels(["$h(x_i, \mathbf{w})$", "$h(x_j, \mathbf{w})$"])
ax.set_ylim(0.12, 0.32)
plt.tight_layout()
#plt.savefig("poly_reg.svg")
plt.show()
|
{
"alphanum_fraction": 0.5725456125,
"author": null,
"avg_line_length": 18.564516129,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "352450113ee6df437dd1da7b3707d1eab5e98b0d",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "9b570d83887eb2d6f92cfaa927a1adf136124a90",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cookieblues/cookieblues.github.io",
"max_forks_repo_path": "extra/bsmalea-notes-2/prob_linreg_example.py",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "9b570d83887eb2d6f92cfaa927a1adf136124a90",
"max_issues_repo_issues_event_max_datetime": "2020-12-10T15:15:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-30T14:58:30.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "cookieblues/cookieblues.github.io",
"max_issues_repo_path": "extra/bsmalea-notes-2/prob_linreg_example.py",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9b570d83887eb2d6f92cfaa927a1adf136124a90",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "cookieblues/cookieblues.github.io",
"max_stars_repo_path": "extra/bsmalea-notes-2/prob_linreg_example.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 489,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1151
}
|
from __future__ import absolute_import, print_function, division
import zipfile
import os
import shutil
import warnings
import glob
import itertools
from six.moves import urllib
import numpy as np
from scipy.io import loadmat
from natsort import natsorted
import dill
from pkg_resources import resource_string
from PIL import Image
from boltons.fileutils import mkdir_p
from tqdm import tqdm
from .datasets import FileStimuli, Stimuli, FixationTrains, Fixations, read_hdf5
from .utils import TemporaryDirectory, filter_files, run_matlab_cmd, download_and_check, download_file_from_google_drive, check_file_hash
from .generics import progressinfo
def create_memory_stimuli(filenames):
"""
Create a `Stimuli`-class from a list of filenames by reading the them
"""
tmp_stimuli = FileStimuli(filenames)
stimuli = list(tmp_stimuli.stimuli) # Read all stimuli
return Stimuli(stimuli)
def create_stimuli(stimuli_location, filenames, location=None):
"""
Create a Stimuli class of stimuli.
Parameters
----------
@type stimuli_location: string
@param stimuli_location: the base path where the stimuli are located.
If `location` is provided, this directory will
be copied to `location` (see below).
@type filenames: list of strings
@param filenames: lists the filenames of the stimuli to include in the dataset.
Filenames have to be relative to `stimuli_location`.
@type location: string or `None`
@param location: If provided, the function will copy the filenames to
`location` and return a `FileStimuli`-object for the
copied files. Otherwise a `Stimuli`-object is returned.
@returns: `Stimuli` or `FileStimuli` object depending on `location`.
"""
if location is not None:
shutil.copytree(stimuli_location,
location)
filenames = [os.path.join(location, f) for f in filenames]
return FileStimuli(filenames)
else:
filenames = [os.path.join(stimuli_location, f) for f in filenames]
return create_memory_stimuli(filenames)
def _load(filename):
"""attempt to load hdf5 file and fallback to pickle files if present"""
if os.path.isfile(filename):
return read_hdf5(filename)
stem, ext = os.path.splitext(filename)
pydat_filename = stem+'.pydat'
return dill.load(open(pydat_filename, 'rb'))
def get_toronto(location=None):
"""
Loads or downloads and caches the Toronto dataset. The dataset
consists of 120 color images of outdoor and indoor scenes
of size 681x511px and the fixations of 20 subjects under
free viewing conditions with 4 seconds presentation time.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. warning::
At the moment, the subjects stated in the FixationTrains object
will not be correct, as they are difficult to infer from the
published data (the data per subject is not stated in image dimensions)
.. seealso::
Neil Bruce, John K. Tsotsos. Attention based on information maximization [JoV 2007]
`http://www-sop.inria.fr/members/Neil.Bruce/#SOURCECODE
"""
if location:
location = os.path.join(location, 'toronto')
if os.path.exists(location):
stimuli = _load(os.path.join(location, 'stimuli.hdf5'))
fixations = _load(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
os.makedirs(location)
with TemporaryDirectory() as temp_dir:
src = 'http://www-sop.inria.fr/members/Neil.Bruce/eyetrackingdata.zip'
target = os.path.join(temp_dir, 'eyetrackingdata.zip')
md5_sum = '38d5c02217060d4d2d1a4649cc632af1'
download_and_check(src, target, md5_sum)
z = zipfile.ZipFile(target)
print('Extracting')
z.extractall(temp_dir)
# Stimuli
stimuli_src_location = os.path.join(temp_dir, 'eyetrackingdata', 'fixdens', 'Original Image Set')
stimuli_target_location = os.path.join(location, 'stimuli') if location else None
stimuli_filenames = ['{}.jpg'.format(i) for i in range(1, 121)]
stimuli = create_stimuli(stimuli_src_location, stimuli_filenames, stimuli_target_location)
points = loadmat(os.path.join(temp_dir, 'eyetrackingdata', 'fixdens', 'origfixdata.mat'))['white']
ts = []
xs = []
ys = []
ns = []
subjects = []
for n in range(len(stimuli.stimuli)):
_ys, _xs = np.nonzero(points[0, n])
xs.extend([[x] for x in _xs])
ys.extend([[y] for y in _ys])
ns.extend([n for x in _xs])
ts.extend([[0] for x in _xs])
subjects.extend([0 for x in _xs])
fixations = FixationTrains.from_fixation_trains(xs, ys, ts, ns, subjects)
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
fixations.to_hdf5(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
def get_toronto_with_subjects(location=None):
"""
Loads or downloads and caches the Toronto dataset. The dataset
consists of 120 color images of outdoor and indoor scenes
of size 681x511px and the fixations of 20 subjects under
free viewing conditions with 4 seconds presentation time.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. warning::
This function uses the positions as given per subject in the toronto
dataset. Unfortunately, these positions do not seem to be pixel positions
as the fixations are not located as in the file `origfixdata.mat'.
The code is still in the package as a template for fixing this issue.
.. seealso::
Neil Bruce, John K. Tsotsos. Attention based on information maximization [JoV 2007]
`http://www-sop.inria.fr/members/Neil.Bruce/#SOURCECODE
"""
warnings.warn('This function reports wrong fixation positions! See docstring for details.')
if location:
location = os.path.join(location, 'toronto')
os.makedirs(location)
with TemporaryDirectory() as temp_dir:
src = 'http://www-sop.inria.fr/members/Neil.Bruce/eyetrackingdata.zip'
target = os.path.join(temp_dir, 'eyetrackingdata.zip')
md5_sum = '38d5c02217060d4d2d1a4649cc632af1'
download_and_check(src, target, md5_sum)
z = zipfile.ZipFile(target)
print('Extracting')
z.extractall(temp_dir)
# Stimuli
stimuli_src_location = os.path.join(temp_dir, 'eyetrackingdata', 'fixdens', 'Original Image Set')
stimuli_target_location = os.path.join(location, 'stimuli') if location else None
stimuli_filenames = ['{}.jpg'.format(i) for i in range(1, 121)]
stimuli = create_stimuli(stimuli_src_location, stimuli_filenames, stimuli_target_location)
print("Getting fixations")
raw_path = os.path.join(temp_dir, 'eyetrackingdata', 'fixdens', 'Raw')
subjects = os.listdir(raw_path)
train_xs = []
train_ys = []
train_ts = []
train_ns = []
train_subjects = []
subjects = [s for s in subjects if s != 'processed']
subjects = sorted(subjects)
for subject_nr, subject in enumerate(subjects):
print("Doing subject", subject)
for n, image in enumerate(stimuli_filenames):
imagename = os.path.splitext(os.path.split(image)[-1])[0]
content = open(os.path.join(raw_path, subject, imagename+'.fix')).read()
content = content.replace('\r', '')
if 'No fixations' in content:
print("No fixations for {}, skipping".format(image))
continue
subject_fixations = content.split('Fixation Listing')[1].split('\n\n')[1].split('Average')[0]
_xs = []
_ys = []
_ts = []
for line in subject_fixations.split('\n'):
if not line:
continue
parts = line.split()
parts = [p.replace(',', '') for p in parts]
_xs.append(int(parts[1]))
_ys.append(int(parts[2]))
_ts.append(float(parts[3]))
_xs = np.array(_xs, dtype=np.float)
_ys = np.array(_ys, dtype=np.float)
_ts = np.array(_ts, dtype=np.float)
xs = []
ys = []
ts = []
for i in range(len(_xs)):
if _xs[i] > 680:
continue
if _ys[i] > 510:
continue
xs.append(_xs[i])
ys.append(_ys[i])
ts.append(_ts[i])
train_xs.append(xs)
train_ys.append(ys)
train_ts.append(ts)
train_ns.append(n)
train_subjects.append(subject_nr)
fixations = FixationTrains.from_fixation_trains(train_xs, train_ys, train_ts, train_ns, train_subjects)
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
fixations.to_hdf5(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
def _get_mit1003(dataset_name, location=None, include_initial_fixation=False, only_1024_by_768=False):
"""
.. seealso::
Tilke Judd, Krista Ehinger, Fredo Durand, Antonio Torralba. Learning to Predict where Humans Look [ICCV 2009]
http://people.csail.mit.edu/tjudd/WherePeopleLook/index.html
"""
if include_initial_fixation:
first_fixation = 0
else:
first_fixation = 1
if location:
location = os.path.join(location, dataset_name)
if os.path.exists(location):
stimuli = _load(os.path.join(location, 'stimuli.hdf5'))
fixations = _load(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
os.makedirs(location)
with TemporaryDirectory(cleanup=True) as temp_dir:
download_and_check('http://people.csail.mit.edu/tjudd/WherePeopleLook/ALLSTIMULI.zip',
os.path.join(temp_dir, 'ALLSTIMULI.zip'),
'0d7df8b954ecba69b6796e77b9afe4b6')
download_and_check('http://people.csail.mit.edu/tjudd/WherePeopleLook/DATA.zip',
os.path.join(temp_dir, 'DATA.zip'),
'ea19d74ad0a0144428c53e9d75c2d71c')
download_and_check('http://people.csail.mit.edu/tjudd/WherePeopleLook/Code/DatabaseCode.zip',
os.path.join(temp_dir, 'DatabaseCode.zip'),
'd8e5e2b6ec827f4115ddbff59b0bdf1d')
# Stimuli
print('Creating stimuli')
f = zipfile.ZipFile(os.path.join(temp_dir, 'ALLSTIMULI.zip'))
namelist = f.namelist()
namelist = filter_files(namelist, ['.svn', '__MACOSX', '.DS_Store'])
f.extractall(temp_dir, namelist)
stimuli_src_location = os.path.join(temp_dir, 'ALLSTIMULI')
stimuli_target_location = os.path.join(location, 'stimuli') if location else None
images = glob.glob(os.path.join(stimuli_src_location, '*.jpeg'))
images = [os.path.split(img)[1] for img in images]
stimuli_filenames = natsorted(images)
if only_1024_by_768:
def check_size(f):
img = Image.open(os.path.join(stimuli_src_location, f))
return img.size == (1024, 768)
stimuli_filenames = [s for s in stimuli_filenames if check_size(s)]
stimuli = create_stimuli(stimuli_src_location, stimuli_filenames, stimuli_target_location)
# FixationTrains
print('Creating fixations')
f = zipfile.ZipFile(os.path.join(temp_dir, 'DATA.zip'))
namelist = f.namelist()
namelist = filter_files(namelist, ['.svn', '__MACOSX', '.DS_Store'])
f.extractall(temp_dir, namelist)
f = zipfile.ZipFile(os.path.join(temp_dir, 'DatabaseCode.zip'))
namelist = f.namelist()
namelist = filter_files(namelist, ['.svn', '__MACOSX', '.DS_Store'])
f.extractall(temp_dir, namelist)
subjects = glob.glob(os.path.join(temp_dir, 'DATA', '*'))
# Exclude files
subjects = [s for s in subjects if not os.path.splitext(s)[1]]
subjects = [os.path.basename(s) for s in subjects]
subjects = sorted(subjects)
with open(os.path.join(temp_dir, 'extract_fixations.m'), 'wb') as f:
f.write(resource_string(__name__, 'scripts/{}'.format('extract_fixations.m')))
cmds = []
# It is vital _not_ to store the extracted fixations in the main
# directory where matlab is running, as matlab will check the timestamp
# of all files in this directory very often. This leads to heavy
# performance penalties and would make matlab run for more than an
# hour.
out_path = 'extracted'
os.makedirs(os.path.join(temp_dir, out_path))
total_cmd_count = len(stimuli_filenames) * len(subjects)
for n, stimulus in enumerate(stimuli_filenames):
for subject_id, subject in enumerate(subjects):
subject_path = os.path.join('DATA', subject)
outfile = '{0}_{1}.mat'.format(stimulus, subject)
outfile = os.path.join(out_path, outfile)
cmds.append("fprintf('%d/%d\\n', {}, {});".format(n*len(subjects)+subject_id, total_cmd_count))
cmds.append("extract_fixations('{0}', '{1}', '{2}');".format(stimulus, subject_path, outfile))
print('Running original code to extract fixations. This can take some minutes.')
print('Warning: In the IPython Notebook, the output is shown on the console instead of the notebook.')
with open(os.path.join(temp_dir, 'extract_all_fixations.m'), 'w') as f:
for cmd in cmds:
f.write('{}\n'.format(cmd))
run_matlab_cmd('extract_all_fixations;', cwd=temp_dir)
xs = []
ys = []
ts = []
ns = []
train_subjects = []
for n, stimulus in enumerate(stimuli_filenames):
stimulus_size = stimuli.sizes[n]
for subject_id, subject in enumerate(subjects):
subject_name = os.path.split(subject)[-1]
outfile = '{0}_{1}.mat'.format(stimulus, subject_name)
mat_data = loadmat(os.path.join(temp_dir, out_path, outfile))
fix_data = mat_data['fixations']
starts = mat_data['starts']
x = []
y = []
t = []
# if first_fixation == 1 the first fixation is skipped, as done
# by Judd.
for i in range(first_fixation, fix_data.shape[0]):
if fix_data[i, 0] < 0 or fix_data[i, 1] < 0:
continue
if fix_data[i, 0] >= stimulus_size[1] or fix_data[i, 1] >= stimulus_size[0]:
continue
x.append(fix_data[i, 0])
y.append(fix_data[i, 1])
t.append(starts[0, i]/240.0) # Eye Tracker rate = 240Hz
xs.append(x)
ys.append(y)
ts.append(t)
ns.append(n)
train_subjects.append(subject_id)
fixations = FixationTrains.from_fixation_trains(xs, ys, ts, ns, train_subjects)
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
fixations.to_hdf5(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
def get_mit1003(location=None):
"""
Loads or downloads and caches the MIT1003 dataset. The dataset
consists of 1003 natural indoor and outdoor scenes of
sizes: max dim: 1024px, other dim: 405-1024px
and the fixations of 15 subjects under
free viewing conditions with 3 seconds presentation time.
All fixations outside of the image are discarded. This includes
blinks.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. note::
This code needs a working matlab or octave installation as the original
matlab code by Judd et al. is used to extract the fixation from the
eyetracking data.
The first fixation of each fixation train is discarded as stated in the
paper (Judd et al. 2009).
.. seealso::
Tilke Judd, Krista Ehinger, Fredo Durand, Antonio Torralba. Learning to Predict where Humans Look [ICCV 2009]
http://people.csail.mit.edu/tjudd/WherePeopleLook/index.html
"""
return _get_mit1003('MIT1003', location=location, include_initial_fixation=False)
def get_mit1003_with_initial_fixation(location=None):
"""
Loads or downloads and caches the MIT1003 dataset. The dataset
consists of 1003 natural indoor and outdoor scenes of
sizes: max dim: 1024px, other dim: 405-1024px
and the fixations of 15 subjects under
free viewing conditions with 3 seconds presentation time.
All fixations outside of the image are discarded. This includes
blinks.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. note::
This code needs a working matlab or octave installation as the original
matlab code by Judd et al. is used to extract the fixation from the
eyetracking data.
Unlike in the original paper (Judd et al. 2009), in this version of
the MIT1003 dataset the first fixation of each scanpath
is *not* discarded. See `get_mit1003` if you want to use
the dataset as suggested by Judd.
.. seealso::
Tilke Judd, Krista Ehinger, Fredo Durand, Antonio Torralba. Learning to Predict where Humans Look [ICCV 2009]
http://people.csail.mit.edu/tjudd/WherePeopleLook/index.html
"""
return _get_mit1003('MIT1003_initial_fix', location=location, include_initial_fixation=True)
def get_mit1003_onesize(location=None):
"""
Loads or downloads and caches the subset of the MIT1003 dataset
used in "How close are we to understanding image-based
saliency" (http://arxiv.org/abs/1409.7686) and
"Deep Gaze I: Boosting Saliency Prediction with Feature Maps Trained
on ImageNet" (http://arxiv.org/abs/1411.1045).
The dataset conists of 463 natural indoor and outdoor scenes of
size 1024 x 768 px and the fixations of 15 subjects under
free viewing conditions with 3 seconds presentation time.
All fixations outside of the image are discarded. This includes
blinks.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. note::
This code needs a working matlab or octave installation as the original
matlab code by Judd et al. is used to extract the fixation from the
eyetracking data.
The first fixation of each fixation train is discarded as stated in the
paper (Judd et al. 2009).
.. seealso::
Tilke Judd, Krista Ehinger, Fredo Durand, Antonio Torralba. Learning to Predict where Humans Look [ICCV 2009]
http://people.csail.mit.edu/tjudd/WherePeopleLook/index.html
"""
return _get_mit1003('MIT1003_onesize', location=location, include_initial_fixation=False, only_1024_by_768=True)
def get_mit300(location=None):
"""
Loads or downloads and caches the MIT300 test stimuli for
the MIT saliency benchmark. The dataset
consists of 300 stimuli
and the fixations of 40 subjects under
free viewing conditions with 3 seconds presentation time.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli
.. seealso::
Zoya Bylinskii and Tilke Judd and Ali Borji and Laurent Itti and Fr{\'e}do Durand and Aude Oliva and Antonio Torralba. MIT Saliency Benchmark
http://saliency.mit.edu
"""
if location:
location = os.path.join(location, 'MIT300')
if os.path.exists(location):
stimuli = _load(os.path.join(location, 'stimuli.hdf5'))
return stimuli
os.makedirs(location)
with TemporaryDirectory(cleanup=True) as temp_dir:
download_and_check('http://saliency.mit.edu/BenchmarkIMAGES.zip',
os.path.join(temp_dir, 'BenchmarkIMAGES.zip'),
'03ed32bdf5e4289950cd28df89451260')
# Stimuli
print('Creating stimuli')
f = zipfile.ZipFile(os.path.join(temp_dir, 'BenchmarkIMAGES.zip'))
namelist = f.namelist()
namelist = filter_files(namelist, ['.svn', '__MACOSX', '.DS_Store'])
f.extractall(temp_dir, namelist)
stimuli_src_location = os.path.join(temp_dir, 'BenchmarkIMAGES')
stimuli_target_location = os.path.join(location, 'stimuli') if location else None
images = glob.glob(os.path.join(stimuli_src_location, '*.jpg'))
images = [os.path.split(img)[1] for img in images]
stimuli_filenames = natsorted(images)
stimuli = create_stimuli(stimuli_src_location, stimuli_filenames, stimuli_target_location)
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
return stimuli
def get_cat2000_test(location=None):
"""
Loads or downloads and caches the CAT2000 test dataset. The dataset
consists of 1003 natural indoor and outdoor scenes of
sizes: max dim: 1024px, other dim: 405-1024px
and the fixations of 15 subjects under
free viewing conditions with 3 seconds presentation time.
All fixations outside of the image are discarded. This includes
blinks.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. note::
This code needs a working matlab or octave installation as the original
matlab code by Judd et al. is used to extract the fixation from the
eyetracking data.
The first fixation of each fixation train is discarded as stated in the
paper (Judd et al. 2009).
.. seealso::
Tilke Judd, Krista Ehinger, Fredo Durand, Antonio Torralba. Learning to Predict where Humans Look [ICCV 2009]
http://people.csail.mit.edu/tjudd/WherePeopleLook/index.html
"""
if location:
location = os.path.join(location, 'CAT2000_test')
if os.path.exists(location):
stimuli = _load(os.path.join(location, 'stimuli.hdf5'))
return stimuli
os.makedirs(location)
with TemporaryDirectory(cleanup=True) as temp_dir:
download_and_check('http://saliency.mit.edu/testSet.zip',
os.path.join(temp_dir, 'testSet.zip'),
'bd2ad31a0c4f02616b735eed2051b903')
# Stimuli
print('Creating stimuli')
f = zipfile.ZipFile(os.path.join(temp_dir, 'testSet.zip'))
f.extractall(temp_dir)
stimuli_src_location = os.path.join(temp_dir, 'Stimuli')
stimuli_target_location = os.path.join(location, 'Stimuli') if location else None
images = glob.glob(os.path.join(stimuli_src_location, '**', '*.jpg'))
images = [os.path.relpath(img, start=stimuli_src_location) for img in images]
stimuli_filenames = natsorted(images)
stimuli = create_stimuli(stimuli_src_location, stimuli_filenames, stimuli_target_location)
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
return stimuli
def get_cat2000_train(location=None, include_initial_fixation=True):
name = 'CAT2000_train'
if not include_initial_fixation:
name += '_without_initial_fixation'
return _get_cat2000_train(name=name, location=location, include_initial_fixation=include_initial_fixation)
def _get_cat2000_train(name, location, include_initial_fixation):
"""
Loads or downloads and caches the CAT2000 dataset. The dataset
consists of 1003 natural indoor and outdoor scenes of
sizes: max dim: 1024px, other dim: 405-1024px
and the fixations of 15 subjects under
free viewing conditions with 3 seconds presentation time.
All fixations outside of the image are discarded. This includes
blinks.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. note::
This code needs a working matlab or octave installation as the original
matlab code by Judd et al. is used to extract the fixation from the
eyetracking data.
The first fixation of each fixation train is discarded as stated in the
paper (Judd et al. 2009).
.. seealso::
Tilke Judd, Krista Ehinger, Fredo Durand, Antonio Torralba. Learning to Predict where Humans Look [ICCV 2009]
http://people.csail.mit.edu/tjudd/WherePeopleLook/index.html
"""
if include_initial_fixation:
first_fixation = 0
else:
first_fixation = 1
if location:
location = os.path.join(location, name)
if os.path.exists(location):
stimuli = _load(os.path.join(location, 'stimuli.hdf5'))
fixations = _load(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
os.makedirs(location)
with TemporaryDirectory(cleanup=True) as temp_dir:
download_and_check('http://saliency.mit.edu/trainSet.zip',
os.path.join(temp_dir, 'trainSet.zip'),
'56ad5c77e6c8f72ed9ef2901628d6e48')
# Stimuli
print('Creating stimuli')
f = zipfile.ZipFile(os.path.join(temp_dir, 'trainSet.zip'))
f.extractall(temp_dir)
stimuli_src_location = os.path.join(temp_dir, 'trainSet', 'Stimuli')
stimuli_target_location = os.path.join(location, 'Stimuli') if location else None
images = glob.glob(os.path.join(stimuli_src_location, '**', '*.jpg'))
images = [os.path.relpath(img, start=stimuli_src_location) for img in images]
stimuli_filenames = natsorted(images)
stimuli = create_stimuli(stimuli_src_location, stimuli_filenames, stimuli_target_location)
# FixationTrains
print('Creating fixations')
with open(os.path.join(temp_dir, 'load_cat2000.m'), 'wb') as f:
f.write(resource_string(__name__, 'scripts/{}'.format('load_cat2000.m')))
cmds = []
# It is vital _not_ to store the extracted fixations in the main
# directory where matlab is running, as matlab will check the timestamp
# of all files in this directory very often. This leads to heavy
# performance penalties and would make matlab run for more than an
# hour.
out_path = 'extracted'
os.makedirs(os.path.join(temp_dir, out_path))
run_matlab_cmd('load_cat2000;', cwd=temp_dir)
print('Extracting fixations. This can take some minutes.')
print('Warning: In the IPython Notebook, the output is shown on the console instead of the notebook.')
#run_matlab_cmd('extract_all_fixations;', cwd=temp_dir)
#
xs = []
ys = []
ts = []
ns = []
train_subjects = []
subject_dict = {}
files = natsorted(glob.glob(os.path.join(temp_dir, out_path, '*.mat')))
for f in progressinfo(files):
mat_data = loadmat(f)
fix_data = mat_data['data']
name = mat_data['name'][0]
n = int(os.path.basename(f).split('fix', 1)[1].split('_')[0]) - 1
stimulus_size = stimuli.sizes[n]
_, _, subject = name.split('.eye')[0].split('-')
if subject not in subject_dict:
subject_dict[subject] = len(subject_dict)
subject_id = subject_dict[subject]
x = []
y = []
t = []
for i in range(first_fixation, fix_data.shape[0]): # Skip first fixation like Judd does via first_fixation=1
if fix_data[i, 0] < 0 or fix_data[i, 1] < 0:
continue
if fix_data[i, 0] >= stimulus_size[1] or fix_data[i, 1] >= stimulus_size[0]:
continue
if any(np.isnan(fix_data[i])): # skip invalid data
continue
x.append(fix_data[i, 0])
y.append(fix_data[i, 1])
t.append(len(x)) # Eye Tracker rate = 240Hz
xs.append(x)
ys.append(y)
ts.append(t)
ns.append(n)
train_subjects.append(subject_id)
fixations = FixationTrains.from_fixation_trains(xs, ys, ts, ns, train_subjects)
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
fixations.to_hdf5(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
def get_iSUN(location=None):
"""
Loads or downloads and caches the iSUN dataset.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `iSUN` of
location and read from there, if already present.
@return: Training stimuli, validation stimuli, testing stimuli, training fixation trains, validation fixation trains
.. seealso::
P. Xu, K. A. Ehinger, Y. Zhang, A. Finkelstein, S. R. Kulkarni, and J. Xiao.: TurkerGaze: Crowdsourcing Saliency with Webcam based Eye Tracking
http://lsun.cs.princeton.edu/
http://vision.princeton.edu/projects/2014/iSUN/
"""
if location:
location = os.path.join(location, 'iSUN')
if os.path.exists(location):
stimuli_training = _load(os.path.join(location, 'stimuli_training.hdf5'))
stimuli_validation = _load(os.path.join(location, 'stimuli_validation.hdf5'))
stimuli_testing = _load(os.path.join(location, 'stimuli_testing.hdf5'))
fixations_training = _load(os.path.join(location, 'fixations_training.hdf5'))
fixations_validation = _load(os.path.join(location, 'fixations_validation.hdf5'))
return stimuli_training, stimuli_validation, stimuli_testing, fixations_training, fixations_validation
os.makedirs(location)
with TemporaryDirectory(cleanup=True) as temp_dir:
download_and_check('http://lsun.cs.princeton.edu/challenge/2015/eyetracking/data/training.mat',
os.path.join(temp_dir, 'training.mat'),
'5a8b15134b17c7a3f69b087845db1363')
download_and_check('http://lsun.cs.princeton.edu/challenge/2015/eyetracking/data/validation.mat',
os.path.join(temp_dir, 'validation.mat'),
'f68e9b011576e48d2460b883854fd86c')
download_and_check('http://lsun.cs.princeton.edu/challenge/2015/eyetracking/data/testing.mat',
os.path.join(temp_dir, 'testing.mat'),
'be008ef0330467dcb9c9cd9cc96a8546')
download_and_check('http://lsun.cs.princeton.edu/challenge/2015/eyetracking/data/fixation.zip',
os.path.join(temp_dir, 'fixation.zip'),
'aadc15784e1b0023cda4536335b7839c')
download_and_check('http://lsun.cs.princeton.edu/challenge/2015/eyetracking/data/image.zip',
os.path.join(temp_dir, 'image.zip'),
'0a3af01c5307f1d44f5dd309f71ea963')
# Stimuli
print('Creating stimuli')
f = zipfile.ZipFile(os.path.join(temp_dir, 'image.zip'))
namelist = f.namelist()
namelist = filter_files(namelist, ['.DS_Store'])
f.extractall(temp_dir, namelist)
def get_stimuli_names(name):
data_file = os.path.join(temp_dir, '{}.mat'.format(name))
data = loadmat(data_file)[name]
stimuli_names = [d[0] for d in data['image'][:, 0]]
stimuli_names = ['{}.jpg'.format(n) for n in stimuli_names]
return stimuli_names
stimulis = []
stimuli_src_location = os.path.join(temp_dir, 'images')
for name in ['training', 'validation', 'testing']:
print("Creating {} stimuli".format(name))
stimuli_target_location = os.path.join(location, 'stimuli_{}'.format(name)) if location else None
images = get_stimuli_names(name)
stimulis.append(create_stimuli(stimuli_src_location, images, stimuli_target_location))
# FixationTrains
print('Creating fixations')
def get_fixations(name):
data_file = os.path.join(temp_dir,'{}.mat'.format(name))
data = loadmat(data_file)[name]
gaze = data['gaze'][:, 0]
ns = []
train_xs = []
train_ys = []
train_ts = []
train_subjects = []
for n in range(len(gaze)):
fixation_trains = gaze[n]['fixation'][0, :]
for train in fixation_trains:
xs = train[:, 0]
ys = train[:, 1]
ns.append(n)
train_xs.append(xs)
train_ys.append(ys)
train_ts.append(range(len(xs)))
train_subjects.append(0)
fixations = FixationTrains.from_fixation_trains(train_xs, train_ys, train_ts, ns, train_subjects)
return fixations
fixations = []
for name in ['training', 'validation']:
print("Creating {} fixations".format(name))
fixations.append(get_fixations(name))
if location:
stimulis[0].to_hdf5(os.path.join(location, 'stimuli_training.hdf5'))
stimulis[1].to_hdf5(os.path.join(location, 'stimuli_validation.hdf5'))
stimulis[2].to_hdf5(os.path.join(location, 'stimuli_test.hdf5'))
fixations[0].to_hdf5(os.path.join(location, 'fixations_training.hdf5'))
fixations[1].to_hdf5(os.path.join(location, 'fixations_validation.hdf5'))
return stimulis + fixations
def get_iSUN_training(location=None):
"""
@return: Training stimuli, training fixation trains
See `get_iSUN` for more information"""
training_stimuli, validation_stimuli, test_stimuli, training_fixations, validation_fixations = get_iSUN(location=location)
return training_stimuli, training_fixations
def get_iSUN_validation(location=None):
"""
@return: validation stimuli, validation fixation trains
See `get_iSUN` for more information"""
training_stimuli, validation_stimuli, test_stimuli, training_fixations, validation_fixations = get_iSUN(location=location)
return validation_stimuli, validation_fixations
def get_iSUN_testing(location=None):
"""
@return: testing stimuli
See `get_iSUN` for more information"""
training_stimuli, validation_stimuli, test_stimuli, training_fixations, validation_fixations = get_iSUN(location=location)
return test_stimuli
def _get_SALICON_obsolete(data_type, stimuli_url, stimuli_hash, fixation_url, fixation_hash, location):
"""Obsolete code for loading from the SALICON json files. The URLs don't exist anymore and the LSUN challenge uses simpler mat files"""
from salicon.salicon import SALICON
with TemporaryDirectory(cleanup=True) as temp_dir:
download_and_check(stimuli_url,
os.path.join(temp_dir, 'stimuli.zip'),
stimuli_hash)
if fixation_url is not None:
download_and_check(fixation_url,
os.path.join(temp_dir, 'fixations.json'),
fixation_hash)
# Stimuli
annFile = os.path.join(temp_dir, 'fixations.json')
salicon = SALICON(annFile)
# get all images
imgIds = salicon.getImgIds()
images = salicon.loadImgs(imgIds)
print('Creating stimuli')
f = zipfile.ZipFile(os.path.join(temp_dir, 'stimuli.zip'))
namelist = f.namelist()
f.extractall(temp_dir, namelist)
del f
stimuli_src_location = os.path.join(temp_dir, data_type)
stimuli_target_location = os.path.join(location, 'stimuli') if location else None
filenames = [img['file_name'] for img in images]
stimuli = create_stimuli(stimuli_src_location, filenames, stimuli_target_location)
if fixation_url is not None:
# FixationTrains
print('Creating fixations')
ns = []
train_xs = []
train_ys = []
train_ts = []
train_subjects = []
for n, imgId in progressinfo(enumerate(imgIds)):
annIds = salicon.getAnnIds(imgIds=imgId)
anns = salicon.loadAnns(annIds)
for ann in anns:
fs = ann['fixations']
# SALICON annotations are 1-indexed, not 0-indexed.
xs = np.array([f[1]-1 for f in fs])
ys = np.array([f[0]-1 for f in fs])
ns.append(np.ones(len(xs), dtype=int)*n)
train_xs.append(xs)
train_ys.append(ys)
train_ts.append(range(len(xs)))
train_subjects.append(np.ones(len(xs), dtype=int)*ann['worker_id'])
xs = np.hstack(train_xs)
ys = np.hstack(train_ys)
ts = np.hstack(train_ts)
ns = np.hstack(ns)
subjects = np.hstack(train_subjects)
fixations = Fixations.FixationsWithoutHistory(xs, ys, ts, ns, subjects)
else:
fixations = None
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
if fixations is not None:
fixations.to_hdf5(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
def get_SALICON(edition='2015', fixation_type='mouse', location=None):
"""
Loads or downloads and caches the SALICON dataset as used in the LSUN challenge prior to 2017.
For memory reasons no fixation trains are provided.
@type edition: string, defaults to '2015'
@param edition: whether to provide the original SALICON dataset from 2015 or the update from 2017
@type fixation_type: string, defaults to 'mouse'
@param fixation_type: whether to use the mouse gaze postion ('mouse')
or the inferred fixations ('fixations').
For more details see the SALICON challenge homepage (below).
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `SALICON` of
location and read from there, if already present.
@return: Training stimuli, validation stimuli, testing stimuli, training fixation trains, validation fixation trains
.. seealso::
Ming Jiang, Shengsheng Huang, Juanyong Duan*, Qi Zhao: SALICON: Saliency in Context, CVPR 2015
http://salicon.net/
.. note:
prior to version 0.2.0 of pysaliency the data was stored in a way that allowed
accessing the subject ids. This is not possible anymore and each scanpath on
each image is just assigned an auto-incrementing id.
"""
if edition not in ['2015', '2017']:
raise ValueError('edition has to be \'2015\' or \'2017\', not \'{}\''.format(edition))
if fixation_type not in ['mouse', 'fixations']:
raise ValueError('fixation_type has to be \'mouse\' or \'fixations\', not \'{}\''.format(fixation_type))
name = _get_SALICON_name(edition=edition, fixation_type=fixation_type)
stimuli_train, stimuli_val, stimuli_test = _get_SALICON_stimuli(
location=location, name='SALICON', edition=edition, fixation_type=fixation_type)
fixations_train, fixations_val = _get_SALICON_fixations(
location=location, name=name, edition=edition, fixation_type=fixation_type)
return stimuli_train, stimuli_val, stimuli_test, fixations_train, fixations_val
def _get_SALICON_name(edition='2015', fixation_type='mouse'):
if edition not in ['2015', '2017']:
raise ValueError('edition has to be \'2015\' or \'2017\', not \'{}\''.format(edition))
if fixation_type not in ['mouse', 'fixations']:
raise ValueError('fixation_type has to be \'mouse\' or \'fixations\', not \'{}\''.format(fixation_type))
if edition == '2015':
if fixation_type == 'mouse':
name = 'SALICON'
elif fixation_type == 'fixations':
name = 'SALICON2015_fixations'
elif edition == '2017':
if fixation_type == 'mouse':
name = 'SALICON2017_mouse'
elif fixation_type == 'fixations':
name = 'SALICON2017_fixations'
return name
def _get_SALICON_stimuli(location, name, edition='2015', fixation_type='mouse'):
if edition not in ['2015', '2017']:
raise ValueError('edition has to be \'2015\' or \'2017\', not \'{}\''.format(edition))
if fixation_type not in ['mouse', 'fixations']:
raise ValueError('fixation_type has to be \'mouse\' or \'fixations\', not \'{}\''.format(fixation_type))
if location:
location = os.path.join(location, name)
if os.path.exists(location):
if all(os.path.exists(os.path.join(location, filename)) for filename in ['stimuli_train.hdf5', 'stimuli_val.hdf5', 'stimuli_test.hdf5']):
stimuli_train = read_hdf5(os.path.join(location, 'stimuli_train.hdf5'))
stimuli_val = read_hdf5(os.path.join(location, 'stimuli_val.hdf5'))
stimuli_test = read_hdf5(os.path.join(location, 'stimuli_test.hdf5'))
return stimuli_train, stimuli_val, stimuli_test
os.makedirs(location, exist_ok=True)
with TemporaryDirectory(cleanup=True) as temp_dir:
stimuli_file = os.path.join(temp_dir, 'stimuli.zip')
download_and_check(
'http://lsun.cs.princeton.edu/challenge/2015/eyetracking_salicon/data/image.zip',
stimuli_file,
'856e451461b8c164f556ebef96dad1a2'
)
print("Extracting stimuli")
f = zipfile.ZipFile(stimuli_file)
f.extractall(temp_dir)
stimuli_train = create_stimuli(
stimuli_location = os.path.join(temp_dir, 'images'),
filenames = [os.path.basename(f) for f in sorted(glob.glob(os.path.join(temp_dir, 'images', 'COCO_train*')))],
location=os.path.join(location, 'stimuli', 'train') if location else None
)
stimuli_val = create_stimuli(
stimuli_location = os.path.join(temp_dir, 'images'),
filenames = [os.path.basename(f) for f in sorted(glob.glob(os.path.join(temp_dir, 'images', 'COCO_val*')))],
location=os.path.join(location, 'stimuli', 'val') if location else None
)
stimuli_test = create_stimuli(
stimuli_location = os.path.join(temp_dir, 'images'),
filenames = [os.path.basename(f) for f in sorted(glob.glob(os.path.join(temp_dir, 'images', 'COCO_test*')))],
location=os.path.join(location, 'stimuli', 'test') if location else None
)
if location is not None:
stimuli_train.to_hdf5(os.path.join(location, 'stimuli_train.hdf5'))
stimuli_val.to_hdf5(os.path.join(location, 'stimuli_val.hdf5'))
stimuli_test.to_hdf5(os.path.join(location, 'stimuli_test.hdf5'))
return stimuli_train, stimuli_val, stimuli_test
def _get_SALICON_fixations(location, name, edition='2015', fixation_type='mouse'):
if edition not in ['2015', '2017']:
raise ValueError('edition has to be \'2015\' or \'2017\', not \'{}\''.format(edition))
if fixation_type not in ['mouse', 'fixations']:
raise ValueError('fixation_type has to be \'mouse\' or \'fixations\', not \'{}\''.format(fixation_type))
if location:
location = os.path.join(location, name)
if os.path.exists(location):
if all(os.path.exists(os.path.join(location, filename)) for filename in ['fixations_train.hdf5', 'fixations_val.hdf5']):
fixations_train = read_hdf5(os.path.join(location, 'fixations_train.hdf5'))
fixations_val = read_hdf5(os.path.join(location, 'fixations_val.hdf5'))
return fixations_train, fixations_val
os.makedirs(location, exist_ok=True)
with TemporaryDirectory(cleanup=True) as temp_dir:
fixations_file = os.path.join(temp_dir, 'fixations.zip')
if edition == '2015':
download_file_from_google_drive('0B2hsWbciDVedWHFiMUVVWFRZTE0', fixations_file)
check_file_hash(fixations_file, '9a22db9d718200fb90252e5010c004c4')
elif edition == '2017':
download_file_from_google_drive('0B2hsWbciDVedS1lBZHprdXFoZkU', fixations_file)
check_file_hash(fixations_file, '462b70f4f9e8ea446ac628e46cea8d3d')
f = zipfile.ZipFile(fixations_file)
f.extractall(os.path.join(temp_dir, 'fixations'))
fixations = []
if fixation_type == 'mouse':
fixation_attr = 'location'
elif fixation_type == 'fixations':
fixation_attr = 'fixations'
for dataset in ['train', 'val']:
ns = []
train_xs = []
train_ys = []
train_ts = []
train_subjects = []
subject_id = 0
data_files = list(sorted(glob.glob(os.path.join(temp_dir, 'fixations', dataset, '*.mat'))))
for n, filename in enumerate(tqdm(data_files)):
fixation_data = loadmat(filename)
for subject_data in fixation_data['gaze'].flatten():
train_xs.append(subject_data[fixation_attr][:, 0] - 1) # matlab: one-based indexing
train_ys.append(subject_data[fixation_attr][:, 1] - 1)
if fixation_type == 'mouse':
train_ts.append(subject_data['timestamp'].flatten())
elif fixation_type == 'fixations':
train_ts.append(range(len(train_xs[-1])))
train_subjects.append(np.ones(len(train_xs[-1]), dtype=int)*subject_id)
ns.append(np.ones(len(train_xs[-1]), dtype=int)*n)
subject_id += 1
xs = np.hstack(train_xs)
ys = np.hstack(train_ys)
ts = np.hstack(train_ts)
subjects = np.hstack(train_subjects)
ns = np.hstack(ns)
fixations.append(Fixations.FixationsWithoutHistory(xs, ys, ts, ns, subjects))
fixations_train, fixations_val = fixations
if location is not None:
fixations_train.to_hdf5(os.path.join(location, 'fixations_train.hdf5'))
fixations_val.to_hdf5(os.path.join(location, 'fixations_val.hdf5'))
return fixations_train, fixations_val
def get_SALICON_train(edition='2015', fixation_type='mouse', location=None):
"""
Loads or downloads and caches the SALICON training dataset. See `get_SALICON` for more details.
"""
if location:
name = _get_SALICON_name(edition=edition, fixation_type=fixation_type)
if os.path.exists(os.path.join(location, name)):
stimuli = _load(os.path.join(location, 'SALICON', 'stimuli_train.hdf5'))
fixations = _load(os.path.join(location, name, 'fixations_train.hdf5'))
return stimuli, fixations
stimuli_train, stimuli_val, stimuli_test, fixations_train, fixations_val = get_SALICON(location=location, edition=edition, fixation_type=fixation_type)
return stimuli_train, fixations_train
def get_SALICON_val(edition='2015', fixation_type='mouse', location=None):
"""
Loads or downloads and caches the SALICON validation dataset. See `get_SALICON` for more details.
"""
if location:
name = _get_SALICON_name(edition=edition, fixation_type=fixation_type)
if os.path.exists(os.path.join(location, name)):
stimuli = _load(os.path.join(location, 'SALICON', 'stimuli_val.hdf5'))
fixations = _load(os.path.join(location, name, 'fixations_val.hdf5'))
return stimuli, fixations
stimuli_train, stimuli_val, stimuli_test, fixations_train, fixations_val = get_SALICON(location=location, edition=edition, fixation_type=fixation_type)
return stimuli_val, stimuli_val
def get_SALICON_test(edition='2015', fixation_type='mouse', location=None):
"""
Loads or downloads and caches the SALICON test dataset. See `get_SALICON` for more details.
"""
if location:
name = _get_SALICON_name(edition=edition, fixation_type=fixation_type)
if os.path.exists(os.path.join(location, name)):
stimuli = _load(os.path.join('SALICON', 'stimuli_test.hdf5'))
return stimuli
stimuli_train, stimuli_val, stimuli_test, fixations_train, fixations_val = get_SALICON(location=location, edition=edition, fixation_type=fixation_type)
return stimuli_test
def _get_koehler_fixations(data, task, n_stimuli):
tasks = {'freeviewing': 'freeview',
'objectsearch': 'objsearch',
'saliencysearch': 'salview'}
task = tasks[task]
data_x = data['{}_x'.format(task)]
data_y = data['{}_y'.format(task)]
# Load Fixation Data
xs = []
ys = []
ts = []
ns = []
subjects = []
subject_ids = range(data_x.shape[0])
for n, subject_id in tqdm(list(itertools.product(range(n_stimuli), subject_ids))):
x = data_x[subject_id, n, :] - 1
y = data_y[subject_id, n, :] - 1
inds = np.logical_not(np.isnan(x))
x = x[inds]
y = y[inds]
xs.append(x)
ys.append(y)
ts.append(range(len(x)))
ns.append(n)
subjects.append(subject_id)
return FixationTrains.from_fixation_trains(xs, ys, ts, ns, subjects)
def get_koehler(location=None, datafile=None):
"""
Loads or or extracts and caches the Koehler dataset. The dataset
consists of 800 color images of outdoor and indoor scenes
of size 405x405px and the fixations for three different tasks:
free viewing, object search and saliency search.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `koehler` of
location and read from there, if already present.
@return: stimuli, fixations_freeviewing, fixations_objectsearch, fixations_saliencysearch
.. note:: As this dataset is only after filling a download form, pysaliency
cannot download it for you. Instead you have to download the file
`PublicData.zip` and provide it to this function via the `datafile`
keyword argument on the first call.
.. seealso::
Kathryn Koehler, Fei Guo, Sheng Zhang, Miguel P. Eckstein. What Do Saliency Models Predict? [JoV 2014]
http://www.journalofvision.org/content/14/3/14.full
https://labs.psych.ucsb.edu/eckstein/miguel/research_pages/saliencydata.html
"""
if location:
location = os.path.join(location, 'Koehler')
if os.path.exists(location):
stimuli = _load(os.path.join(location, 'stimuli.hdf5'))
fixations_freeviewing = _load(os.path.join(location, 'fixations_freeviewing.hdf5'))
fixations_objectsearch = _load(os.path.join(location, 'fixations_objectsearch.hdf5'))
fixations_saliencysearch = _load(os.path.join(location, 'fixations_saliencysearch.hdf5'))
return stimuli, fixations_freeviewing, fixations_objectsearch, fixations_saliencysearch
mkdir_p(location)
if not datafile:
raise ValueError('The Koehler dataset is not freely available! You have to '
'request the data file from the authors and provide it to '
'this function via the datafile argument')
with TemporaryDirectory() as temp_dir:
z = zipfile.ZipFile(datafile)
print('Extracting')
z.extractall(temp_dir)
# Stimuli
stimuli_src_location = os.path.join(temp_dir, 'Images')
stimuli_target_location = os.path.join(location, 'stimuli') if location else None
stimuli_filenames = ['image_r_{}.jpg'.format(i) for i in range(1, 801)]
stimuli = create_stimuli(stimuli_src_location, stimuli_filenames, stimuli_target_location)
# Fixations
data = loadmat(os.path.join(temp_dir, 'ObserverData.mat'))
fs = []
for task in ['freeviewing', 'objectsearch', 'saliencysearch']:
fs.append(_get_koehler_fixations(data, task, len(stimuli)))
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
fs[0].to_hdf5(os.path.join(location, 'fixations_freeviewing.hdf5'))
fs[1].to_hdf5(os.path.join(location, 'fixations_objectsearch.hdf5'))
fs[2].to_hdf5(os.path.join(location, 'fixations_saliencysearch.hdf5'))
return [stimuli] + fs
def _load_FIGRIM_data(filename, stimuli_indices, stimulus_type):
data = loadmat(filename)['allImages'].flatten()
xs = []
ys = []
ts = []
ns = []
train_subjects = []
which_times = []
which_time_names = ['enc', 'rec', 'rec2']
stimulus_types = []
responses = []
for stimulus_data in data:
n = stimuli_indices[stimulus_data['filename'][0]]
category = stimulus_data['category'][0] # TODO: use
for subject, subject_data in enumerate(stimulus_data['userdata'].flatten()):
if not subject_data['trial']:
# No data for this subject and this stimulus
continue
for which_time in which_time_names:
fixations = subject_data['fixations'][0, 0][which_time]
if not len(fixations):
continue
#if len(fixations) and which_time != 'enc':
# print("Problem:", n, subject_name, which_time)
subject_response = subject_data['SDT'][0][which_time_names.index(which_time)]
xs.append(fixations[:, 0])
ys.append(fixations[:, 1])
ts.append(np.arange(len(xs[-1])))
ns.append(n)
train_subjects.append(subject)
which_times.append(which_time_names.index(which_time))
stimulus_types.append(stimulus_type)
responses.append(subject_response)
return xs, ys, ts, ns, train_subjects, which_times, stimulus_types, responses
def get_FIGRIM(location=None):
"""
Loads or downloads and caches the FIGRIM dataset. The dataset
consists of >2700 scenes of sizes 1000x1000px
and the fixations of subjects while doing a repetition
recognition task with 3 seconds presentation time.
subject responses etc are included.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. note::
This dataset comes with additional annotations:
- stimulus_type: 0=filler, 1=target
- which_time: 0=encoding, 1=first recognition, 2=second recognition
- response: 1=hit, 2=false alarm, 3=miss, 4=correct rejection
.. seealso::
Bylinskii, Zoya and Isola, Phillip and Bainbridge, Constance and Torralba, Antonio and Oliva, Aude. Intrinsic and Extrinsic Effects on Image Memorability [Vision research 2015]
http://figrim.mit.edu/index_eyetracking.html
"""
if location:
location = os.path.join(location, 'FIGRIM')
if os.path.exists(location):
stimuli = _load(os.path.join(location, 'stimuli.hdf5'))
fixations = _load(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
os.makedirs(location)
with TemporaryDirectory(cleanup=True) as temp_dir:
download_and_check('http://figrim.mit.edu/Fillers.zip',
os.path.join(temp_dir, 'Fillers.zip'),
'dc0bc9561b5bc90e158ec32074dd1060')
download_and_check('http://figrim.mit.edu/Targets.zip',
os.path.join(temp_dir, 'Targets.zip'),
'2ad3a42ebc377efe4b39064405568201')
download_and_check('https://github.com/cvzoya/figrim/blob/master/targetData/allImages_release.mat?raw=True',
os.path.join(temp_dir, 'allImages_release.mat'),
'c72843b05e95ab27594c1d11c849c897')
download_and_check('https://github.com/cvzoya/figrim/blob/master/fillerData/allImages_fillers.mat?raw=True',
os.path.join(temp_dir, 'allImages_fillers.mat'),
'ce4f8b4961005d62f7a21191a64cab5e')
# Stimuli
mkdir_p(os.path.join(temp_dir, 'stimuli'))
print('Creating stimuli')
f = zipfile.ZipFile(os.path.join(temp_dir, 'Fillers.zip'))
f.extractall(os.path.join(temp_dir, 'stimuli'))
f = zipfile.ZipFile(os.path.join(temp_dir, 'Targets.zip'))
f.extractall(os.path.join(temp_dir, 'stimuli'))
stimuli_src_location = os.path.join(temp_dir, 'stimuli')
stimuli_target_location = os.path.join(location, 'Stimuli') if location else None
images = glob.glob(os.path.join(stimuli_src_location, '**', '**', '*.jpg'))
images = [os.path.relpath(img, start=stimuli_src_location) for img in images]
stimuli_filenames = natsorted(images)
stimuli = create_stimuli(stimuli_src_location, stimuli_filenames, stimuli_target_location)
stimuli_basenames = [os.path.basename(filename) for filename in stimuli_filenames]
stimulus_indices = {s: stimuli_basenames.index(s) for s in stimuli_basenames}
# FixationTrains
print('Creating fixations')
print('Fillers...')
(xs_filler,
ys_filler,
ts_filler,
ns_filler,
train_subjects_filler,
which_times_filler,
stimulus_types_filler,
responses_filler) = _load_FIGRIM_data(os.path.join(temp_dir, 'allImages_fillers.mat'), stimulus_indices, stimulus_type=0)
print("Targets...")
(xs_target,
ys_target,
ts_target,
ns_target,
train_subjects_target,
which_times_target,
stimulus_types_target,
responses_target) = _load_FIGRIM_data(os.path.join(temp_dir, 'allImages_release.mat'), stimulus_indices, stimulus_type=0)
print("Finalizing...")
xs = xs_filler + xs_target
ys = ys_filler + ys_target
ts = ts_filler + ts_target
ns = ns_filler + ns_target
train_subjects = train_subjects_filler + train_subjects_target
which_times = which_times_filler + which_times_target
stimulus_types = stimulus_types_filler + stimulus_types_target
responses = responses_filler + responses_target
fixations = FixationTrains.from_fixation_trains(
xs, ys, ts, ns, train_subjects,
attributes={
'which_time': which_times,
'stimulus_type': stimulus_types,
'response': responses
})
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
fixations.to_hdf5(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
def get_OSIE(location=None):
"""
Loads or downloads and caches the OSIE dataset. The dataset
consists of 700 images of size 800x600px
and the fixations of 15 subjects while doing a
freeviewing task with 3 seconds presentation time.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. seealso::
Juan Xu, Ming Jiang, Shuo Wang, Mohan Kankanhalli, Qi Zhao. Predicting Human Gaze Beyond Pixels [JoV 2014]
http://www-users.cs.umn.edu/~qzhao/predicting.html
"""
if location:
location = os.path.join(location, 'OSIE')
if os.path.exists(location):
stimuli = _load(os.path.join(location, 'stimuli.hdf5'))
fixations = _load(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
os.makedirs(location)
with TemporaryDirectory(cleanup=True) as temp_dir:
stimuli_src_location = os.path.join(temp_dir, 'stimuli')
mkdir_p(stimuli_src_location)
images = []
for i in tqdm(list(range(700))):
filename = '{}.jpg'.format(i+1001)
target_name = os.path.join(stimuli_src_location, filename)
urllib.request.urlretrieve(
'https://github.com/NUS-VIP/predicting-human-gaze-beyond-pixels/raw/master/data/stimuli/'+filename,
target_name)
images.append(filename)
download_and_check('https://github.com/NUS-VIP/predicting-human-gaze-beyond-pixels/blob/master/data/eye/fixations.mat?raw=true',
os.path.join(temp_dir, 'fixations.mat'),
'8efdf6fe66f38b6e70f854c7ff45aa70')
# Stimuli
print('Creating stimuli')
stimuli_target_location = os.path.join(location, 'Stimuli') if location else None
stimuli = create_stimuli(stimuli_src_location, images, stimuli_target_location)
stimulus_indices = {s: images.index(s) for s in images}
# FixationTrains
print('Creating fixations')
data = loadmat(os.path.join(temp_dir, 'fixations.mat'))['fixations'].flatten()
xs = []
ys = []
ts = []
ns = []
train_subjects = []
for stimulus_data in data:
stimulus_data = stimulus_data[0, 0]
n = stimulus_indices[stimulus_data['img'][0]]
for subject, subject_data in enumerate(stimulus_data['subjects'].flatten()):
fixations = subject_data[0, 0]
if not len(fixations['fix_x'].flatten()):
continue
xs.append(fixations['fix_x'].flatten())
ys.append(fixations['fix_y'].flatten())
ts.append(np.arange(len(xs[-1])))
ns.append(n)
train_subjects.append(subject)
fixations = FixationTrains.from_fixation_trains(xs, ys, ts, ns, train_subjects)
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
fixations.to_hdf5(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
def get_NUSEF_public(location=None):
"""
Loads or downloads and caches the part of the NUSEF dataset,
for which the stimuli are public. The dataset
consists of 758 images of size 1024x700px
and the fixations of 25 subjects while doing a
freeviewing task with 5 seconds presentation time.
Part of the stimuli from NUSEF are available only
under a special license and only upon request. This
function returns only the 444 images which are
available public (and the corresponding fixations).
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `toronto` of
location and read from there, if already present.
@return: Stimuli, FixationTrains
.. seealso::
Subramanian Ramanathan, Harish Katti, Nicu Sebe, Mohan Kankanhalli, Tat-Seng Chua. An eye fixation database for saliency detection in images [ECCV 2010]
http://mmas.comp.nus.edu.sg/NUSEF.html
"""
if location:
location = os.path.join(location, 'NUSEF_public')
if os.path.exists(location):
stimuli = _load(os.path.join(location, 'stimuli.hdf5'))
fixations = _load(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
os.makedirs(location)
with TemporaryDirectory(cleanup=True) as temp_dir:
download_and_check('http://mmas.comp.nus.edu.sg/NUSEF_database.zip',
os.path.join(temp_dir, 'NUSEF_database.zip'),
'429a78ad92184e8a4b37419988d98953')
# Stimuli
print('Creating stimuli')
f = zipfile.ZipFile(os.path.join(temp_dir, 'NUSEF_database.zip'))
f.extractall(temp_dir)
stimuli_src_location = os.path.join(temp_dir, 'NUSEF_database', 'stimuli')
images = glob.glob(os.path.join(stimuli_src_location, '*.jpg'))
images = [os.path.relpath(img, start=stimuli_src_location) for img in images]
stimuli_filenames = sorted(images)
stimuli_target_location = os.path.join(location, 'Stimuli') if location else None
stimuli = create_stimuli(stimuli_src_location, stimuli_filenames, stimuli_target_location)
stimuli_basenames = [os.path.basename(f) for f in stimuli_filenames]
stimuli_indices = {s: stimuli_basenames.index(s) for s in stimuli_basenames}
# FixationTrains
print('Creating fixations')
xs = []
ys = []
ts = []
ns = []
train_subjects = []
scale_x = 1024 / 260
scale_y = 768 / 280
fix_location = os.path.join(temp_dir, 'NUSEF_database', 'fix_data')
for sub_dir in tqdm(os.listdir(fix_location)):
if not sub_dir+'.jpg' in stimuli_indices:
# one of the non public images
continue
n = stimuli_indices[sub_dir+'.jpg']
for subject_data in glob.glob(os.path.join(fix_location, sub_dir, '*.fix')):
data = open(subject_data).read().replace('\r\n', '\n')
data = data.split('COLS=', 1)[1]
data = data.split('[Fix Segment Summary')[0]
lines = data.split('\n')[1:]
lines = [l for l in lines if l]
x = []
y = []
t = []
for line in lines:
(_,
seg_no,
fix_no,
pln_no,
start_time,
fix_dur,
interfix_dur,
interfix_deg,
hor_pos,
ver_pos,
pupil_diam,
eye_scn_dist,
no_of_flags,
fix_loss,
interfix_loss) = line.split()
x.append(float(hor_pos)*scale_x)
y.append(float(ver_pos)*scale_y)
t.append(float(start_time.split(':')[-1]))
xs.append(x)
ys.append(y)
ts.append(t)
ns.append(n)
train_subjects.append(0)
fixations = FixationTrains.from_fixation_trains(xs, ys, ts, ns, train_subjects)
if location:
stimuli.to_hdf5(os.path.join(location, 'stimuli.hdf5'))
fixations.to_hdf5(os.path.join(location, 'fixations.hdf5'))
return stimuli, fixations
|
{
"alphanum_fraction": 0.6289094547,
"author": null,
"avg_line_length": 42.0829800121,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "12dd5740b714efd00010135e4ddd301afc2172a3",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "55b5f7b4808075ba9cab7d31a27ff215fbc28642",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "BigHeartDB/pysaliency",
"max_forks_repo_path": "pysaliency/external_datasets.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "55b5f7b4808075ba9cab7d31a27ff215fbc28642",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "BigHeartDB/pysaliency",
"max_issues_repo_path": "pysaliency/external_datasets.py",
"max_line_length": 184,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "55b5f7b4808075ba9cab7d31a27ff215fbc28642",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "BigHeartDB/pysaliency",
"max_stars_repo_path": "pysaliency/external_datasets.py",
"max_stars_repo_stars_event_max_datetime": "2021-04-12T10:52:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-12T10:52:46.000Z",
"num_tokens": 16388,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 69479
}
|
import torch
import numpy as np
def align_loss(x, y, alpha=2):
return (x - y).norm(p=2, dim=1).pow(alpha).mean()
def uniform_loss(x, t=2):
return torch.pdist(x, p=2).pow(2).mul(-t).exp().mean().log()
def CCA_loss(H1, H2, outdim_size, use_all_singular_values=False):
r1 = 1e-3
r2 = 1e-3
eps = 1e-9
H1, H2 = H1.t(), H2.t()
o1 = o2 = H1.size(0)
m = H1.size(1)
H1bar = H1 - H1.mean(dim=1).unsqueeze(dim=1)
H2bar = H2 - H2.mean(dim=1).unsqueeze(dim=1)
SigmaHat12 = (1.0 / (m - 1)) * torch.matmul(H1bar, H2bar.t())
SigmaHat11 = (1.0 / (m - 1)) * torch.matmul(H1bar, H1bar.t()) + r1 * torch.eye(o1, device=H1.device)
SigmaHat22 = (1.0 / (m - 1)) * torch.matmul(H2bar, H2bar.t()) + r2 * torch.eye(o2, device=H1.device)
# Calculating the root inverse of covariance matrices by using eigen decomposition
[D1, V1] = torch.symeig(SigmaHat11, eigenvectors=True)
[D2, V2] = torch.symeig(SigmaHat22, eigenvectors=True)
# Added to increase stability
posInd1 = torch.gt(D1, eps).nonzero(as_tuple=False)[:, 0]
D1 = D1[posInd1]
V1 = V1[:, posInd1]
posInd2 = torch.gt(D2, eps).nonzero(as_tuple=False)[:, 0]
D2 = D2[posInd2]
V2 = V2[:, posInd2]
SigmaHat11RootInv = torch.matmul(torch.matmul(V1, torch.diag(D1 ** -0.5)), V1.t())
SigmaHat22RootInv = torch.matmul(torch.matmul(V2, torch.diag(D2 ** -0.5)), V2.t())
Tval = torch.matmul(torch.matmul(SigmaHat11RootInv, SigmaHat12), SigmaHat22RootInv)
if use_all_singular_values:
# all singular values are used to calculate the correlation
tmp = torch.matmul(Tval.t(), Tval)
corr = torch.trace(torch.sqrt(tmp))
# assert torch.isnan(corr).item() == 0
else:
# just the top outdim_size singular values are used
trace_TT = torch.matmul(Tval.t(), Tval)
trace_TT = torch.add(trace_TT, (torch.eye(trace_TT.shape[0])*r1).to(H1.device)) # regularization for more stability
U, V = torch.symeig(trace_TT, eigenvectors=True)
U = torch.where(U>eps, U, (torch.ones(U.shape)*eps).to(H1.device))
U = U.topk(outdim_size)[0]
corr = torch.sum(torch.sqrt(U))
return - corr
class HardNegtive_loss(torch.nn.Module):
def __init__(self, tau_plus=0.1, beta=1.0, temperature=0.5, alpha=256, estimator='hard'):
super(HardNegtive_loss, self).__init__()
self.tau_plus = tau_plus
self.beta = beta
self.temperature = temperature
self.estimator = estimator
self.alpha = alpha
def get_negative_mask(self, batch_size):
negative_mask = torch.ones((batch_size, 2 * batch_size), dtype=bool)
for i in range(batch_size):
negative_mask[i, i] = 0
negative_mask[i, i + batch_size] = 0
negative_mask = torch.cat((negative_mask, negative_mask), 0)
return negative_mask
def forward(self, out_1, out_2):
# normalization
batch_size, c = out_1.shape
#out_1 = F.normalize(out_1, dim=1)
#out_2 = F.normalize(out_2, dim=1)
# neg score
out = torch.cat([out_1, out_2], dim=0)
neg = torch.exp(torch.mm(out, out.t().contiguous()) / self.temperature)
# old_neg = neg.clone()
mask = self.get_negative_mask(batch_size).cuda()
neg = neg.masked_select(mask).view(2 * batch_size, -1)
# pos score
pos = torch.exp(torch.sum(out_1 * out_2, dim=-1) / self.temperature)
pos = torch.cat([pos, pos], dim=0)
# negative samples similarity scoring
if self.estimator == 'hard':
N = batch_size * 2 - 2
imp = (self.beta * neg.log()).exp()
reweight_neg = (imp * neg).sum(dim=-1) / imp.mean(dim=-1)
Ng = (-self.tau_plus * N * pos + reweight_neg) / (1 - self.tau_plus)
# constrain (optional)
Ng = torch.clamp(Ng, min=N * np.e ** (-1 / self.temperature))
elif self.estimator == 'easy':
Ng = neg.sum(dim=-1)
else:
raise Exception('Invalid estimator selected. Please use any of [hard, easy]')
# contrastive loss
loss = (- torch.log(pos / (pos + Ng))).mean()
# eqco
#print(batch_size, Ng.shape)
#loss = (- torch.log(pos / (pos + self.alpha / Ng.shape[0] * Ng))).mean()
return loss
|
{
"alphanum_fraction": 0.599448149,
"author": null,
"avg_line_length": 36.2416666667,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "000705a9e45e8ca912d80344cd3aa76fa9fcdcb4",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "896da9f436b90b8eb6609e981ea0ba8f495be278",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "yusin2it/SARoptical_fusion",
"max_forks_repo_path": "utils/losses.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "896da9f436b90b8eb6609e981ea0ba8f495be278",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "yusin2it/SARoptical_fusion",
"max_issues_repo_path": "utils/losses.py",
"max_line_length": 123,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "896da9f436b90b8eb6609e981ea0ba8f495be278",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "yusin2it/SARoptical_fusion",
"max_stars_repo_path": "utils/losses.py",
"max_stars_repo_stars_event_max_datetime": "2022-02-25T13:29:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-25T13:29:49.000Z",
"num_tokens": 1310,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4349
}
|
[STATEMENT]
lemma mtx_nonzero_bid_eq:
assumes "R\<subseteq>Id"
assumes "(a, a') \<in> Id \<rightarrow> R"
shows "mtx_nonzero a = mtx_nonzero a'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. mtx_nonzero a = mtx_nonzero a'
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
R \<subseteq> Id
(a, a') \<in> Id \<rightarrow> R
goal (1 subgoal):
1. mtx_nonzero a = mtx_nonzero a'
[PROOF STEP]
apply (clarsimp simp: mtx_nonzero_def)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>R \<subseteq> Id; (a, a') \<in> Id \<rightarrow> R\<rbrakk> \<Longrightarrow> {(i, j). a (i, j) \<noteq> (0::'a)} = {(i, j). a' (i, j) \<noteq> (0::'a)}
[PROOF STEP]
apply (metis fun_relE2 pair_in_Id_conv subsetCE)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
|
{
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": "Refine_Imperative_HOL_IICF_Impl_IICF_Array_Matrix",
"hexsha": null,
"include": null,
"lang": null,
"length": 4,
"llama_tokens": 361,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": null
}
|
import numpy as np
import unittest
from numpy.testing import *
from src.tabular.policies import TabularQPolicy, Qdict2array
from src.tabular.TD import QLearning
from src.envs.dummy_envs import *
class TestQLearning(unittest.TestCase):
def setUp(self):
self.env = ChainEnv(6)
self.env_multi = GridEnv(n=3, multi_discrete_action=True,
goal_reward=1)
self.model = QLearning(TabularQPolicy, self.env)
self.model_multi = QLearning(TabularQPolicy, self.env_multi)
def test_Q_learning(self):
self.model.learn(2000)
targetQ = np.array([[.95, .96],
[.95, .97],
[.96, .98],
[.97, .99],
[.98, 1.0],
[0.0, 0.0]])
assert_array_almost_equal(targetQ, Qdict2array(self.model.get_parameters()['Q']))
def test_predict(self):
# Check that predicts does not use softmax but greedy policy by default
self.model.learn(2000)
targetQ = np.array([[.95, .96],
[.95, .97],
[.96, .98],
[.97, .99],
[.98, 1.0],
[0.0, 0.0]])
for i in range(100):
assert_equal(self.model.predict(0)[0], 1)
def test_Q_learning_multi(self):
"""
Test Q learning with multi-discrete action and state space.
"""
self.model_multi.learn(8000)
targetQ = np.array([[.97, .97, .96, .96],
[.98, .98, .96, .97],
[.98, .99, .97, .98],
[.98, .98, .97, .96],
[.99, .99, .97, .97],
[.99, 1.0, .98, .98],
[.99, .98, .98, .97],
[1.0, .99, .98, .98],
[0.0, 0.0, 0.0, 0.0]])
assert_array_almost_equal(targetQ, Qdict2array(self.model_multi.get_parameters()['Q']), decimal=4)
class TestTabularQPolicy(unittest.TestCase):
def setUp(self):
self.env = GridEnv(n=3, multi_discrete_action=True,
goal_reward=1)
self.policy = TabularQPolicy(self.env.observation_space, self.env.action_space)
def test(self):
# Update the Q values
s = [(0, 0), (0, 0)]
a = [(0, 1), (0, 0)]
vals = [1, 2]
self.policy.update_Q(s, a, vals)
# Check the probability distribution and the sampling are right
denominator = 2 * np.exp(0) + np.exp(1) + np.exp(2)
target = [np.exp(2) / denominator, np.exp(1) / denominator, 1/denominator, 1/denominator]
assert_almost_equal(target, self.policy.proba_step((0, 0)))
counter = np.array([0] * 4)
for i in range(10000):
a = self.policy.step((0, 0), deterministic=False)
for i, action_tuple in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]):
if tuple(a) == action_tuple:
counter[i] += 1
assert_allclose(target, counter / np.sum(counter), atol=0.01)
# Change temperature and repeat the test
self.policy.temperature = 10
denominator = 2 * np.exp(0) + np.exp(0.1) + np.exp(0.2)
target = [np.exp(0.2) / denominator, np.exp(0.1) / denominator, 1 / denominator, 1 / denominator]
assert_almost_equal(target, self.policy.proba_step((0, 0)))
counter = np.array([0] * 4)
for i in range(10000):
a = self.policy.step((0, 0), deterministic=False)
for i, action_tuple in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]):
if tuple(a) == action_tuple:
counter[i] += 1
assert_allclose(target, counter / np.sum(counter), atol=0.01)
if __name__ == '__main__':
unittest.main()
|
{
"alphanum_fraction": 0.5025342119,
"author": null,
"avg_line_length": 38.6862745098,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "417d38f25ba028d47a7473d1a3a03960e389e1ad",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T15:53:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-11-17T03:20:00.000Z",
"max_forks_repo_head_hexsha": "027957e4a26a36f6501c4f0e5e73cb9d78a53e66",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jainraj/CISR_NeurIPS20",
"max_forks_repo_path": "src/tabular/test.py",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "027957e4a26a36f6501c4f0e5e73cb9d78a53e66",
"max_issues_repo_issues_event_max_datetime": "2021-12-22T14:30:59.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-23T12:07:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jainraj/CISR_NeurIPS20",
"max_issues_repo_path": "src/tabular/test.py",
"max_line_length": 106,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "027957e4a26a36f6501c4f0e5e73cb9d78a53e66",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jainraj/CISR_NeurIPS20",
"max_stars_repo_path": "src/tabular/test.py",
"max_stars_repo_stars_event_max_datetime": "2022-02-16T08:08:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-04T14:44:16.000Z",
"num_tokens": 1028,
"path": null,
"reason": "import numpy,from numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 3946
}
|
import matplotlib.pyplot as plt
from plotters.line_plotter import LinesPlotter
import numpy as np
# lee un resultado que contiene tres campos
plotter = LinesPlotter.load_data('examples/data_small.npy',
['reward', 'steps', 'end_state'])
# grafica el campo reward asignando la etiqueta reward label a la grafica
# al calcular average grafica std dev tambien
fig, ax = plotter.get_var_line_plot(
['reward'], 'average', label='reward label', window_size=2)
fig.legend()
plt.tight_layout()
plt.show()
|
{
"alphanum_fraction": 0.7148148148,
"author": null,
"avg_line_length": 31.7647058824,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "77b2a279a6b3a968055ed9c788298df2cbd34dad",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "37eb36f09f4c56641f73db795d1d97bea58ce161",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jonaths/q_policy_plotter",
"max_forks_repo_path": "sample_load_data.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "37eb36f09f4c56641f73db795d1d97bea58ce161",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jonaths/q_policy_plotter",
"max_issues_repo_path": "sample_load_data.py",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "37eb36f09f4c56641f73db795d1d97bea58ce161",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jonaths/q_policy_plotter",
"max_stars_repo_path": "sample_load_data.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 124,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 540
}
|
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal4.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Derive Show for lst.
Derive Arbitrary for lst.
Instance Dec_Eq_lst : Dec_Eq lst.
Proof. dec_eq. Qed.
Lemma conj6eqsynthconj1 : forall (lv0 : natural), (@eq natural (Succ lv0) (Succ lv0)).
Admitted.
QuickChick conj6eqsynthconj1.
|
{
"alphanum_fraction": null,
"author": "yalhessi",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal4_theorem0_39_lem/lfindconj6eqsynthconj1.v",
"reason": null,
"repo": "lemmaranker",
"save_path": "github-repos/coq/yalhessi-lemmaranker",
"sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a",
"size": null
}
|
export AbstractHook,
ComposedHook,
EmptyHook,
StepsPerEpisode,
RewardsPerEpisode,
TotalRewardPerEpisode,
TotalBatchRewardPerEpisode,
CumulativeReward,
TimePerStep,
DoEveryNEpisode,
DoEveryNStep
"""
A hook is called at different stage duiring a [`run`](@ref) to allow users to inject customized runtime logic.
By default, a `AbstractHook` will do nothing. One can override the behavior by implementing the following methods:
- `(hook::YourHook)(::PreActStage, agent, env, obs, action)`, note that there's an extra argument of `action`.
- `(hook::YourHook)(::PostActStage, agent, env, obs)`
- `(hook::YourHook)(::PreEpisodeStage, agent, env, obs)`
- `(hook::YourHook)(::PostEpisodeStage, agent, env, obs)`
"""
abstract type AbstractHook end
(hook::AbstractHook)(args...) = nothing
# https://github.com/JuliaLang/julia/issues/14919
# function (f::Function)(stage::T, args...;kw...) where T<: AbstractStage end
#####
# ComposedHook
#####
"""
ComposedHook(hooks::AbstractHook...)
Compose different hooks into a single hook.
"""
struct ComposedHook{T<:Tuple} <: AbstractHook
hooks::T
ComposedHook(hooks...) = new{typeof(hooks)}(hooks)
end
function (hook::ComposedHook)(stage::AbstractStage, args...; kw...)
for h in hook.hooks
h(stage, args...; kw...)
end
end
Base.getindex(hook::ComposedHook, inds...) = getindex(hook.hooks, inds...)
#####
# EmptyHook
#####
"""
Do nothing
"""
struct EmptyHook <: AbstractHook end
const EMPTY_HOOK = EmptyHook()
#####
# StepsPerEpisode
#####
"""
StepsPerEpisode(; steps = Int[], count = 0, tag = "TRAINING")
Store steps of each episode in the field of `steps`.
"""
Base.@kwdef mutable struct StepsPerEpisode <: AbstractHook
steps::Vector{Int} = Int[]
count::Int = 0
tag::String = "TRAINING"
end
function (hook::StepsPerEpisode)(::PostActStage, args...)
hook.count += 1
end
function (hook::StepsPerEpisode)(
::Union{PostEpisodeStage,PostExperimentStage},
agent,
env,
obs,
)
push!(hook.steps, hook.count)
hook.count = 0
@debug hook.tag STEPS_PER_EPISODE = hook.steps[end]
end
#####
# RewardsPerEpisode
#####
"""
RewardsPerEpisode(; rewards = Vector{Vector{Float64}}(), tag = "TRAINING")
Store each reward of each step in every episode in the field of `rewards`.
"""
Base.@kwdef mutable struct RewardsPerEpisode <: AbstractHook
rewards::Vector{Vector{Float64}} = Vector{Vector{Float64}}()
tag::String = "TRAINING"
end
function (hook::RewardsPerEpisode)(::PreEpisodeStage, agent, env, obs)
push!(hook.rewards, [])
end
function (hook::RewardsPerEpisode)(::PostActStage, agent, env, obs)
push!(hook.rewards[end], get_reward(obs))
end
function (hook::RewardsPerEpisode)(::PostEpisodeStage, agent, env, obs)
@debug hook.tag REWARDS_PER_EPISODE = hook.rewards[end]
end
#####
# TotalRewardPerEpisode
#####
"""
TotalRewardPerEpisode(; rewards = Float64[], reward = 0.0, tag = "TRAINING")
Store the total rewards of each episode in the field of `rewards`.
"""
Base.@kwdef mutable struct TotalRewardPerEpisode <: AbstractHook
rewards::Vector{Float64} = Float64[]
reward::Float64 = 0.0
tag::String = "TRAINING"
end
function (hook::TotalRewardPerEpisode)(::PostActStage, agent, env, obs)
hook.reward += get_reward(obs)
end
function (hook::TotalRewardPerEpisode)(
::Union{PostEpisodeStage,PostExperimentStage},
agent,
env,
obs,
)
push!(hook.rewards, hook.reward)
hook.reward = 0
@debug hook.tag REWARD_PER_EPISODE = hook.rewards[end]
end
#####
# TotalBatchRewardPerEpisode
#####
struct TotalBatchRewardPerEpisode <: AbstractHook
rewards::Vector{Vector{Float64}}
reward::Vector{Float64}
tag::String
end
"""
TotalBatchRewardPerEpisode(batch_size::Int;tag="TRAINING")
Similar to [`TotalRewardPerEpisode`](@ref), but will record total rewards per episode in [`BatchObs`](@ref).
"""
function TotalBatchRewardPerEpisode(batch_size::Int; tag = "TRAINING")
TotalBatchRewardPerEpisode([Float64[] for _ in 1:batch_size], zeros(batch_size), tag)
end
function (hook::TotalBatchRewardPerEpisode)(::PostActStage, agent, env, obs::BatchObs)
for i in 1:length(obs)
hook.reward[i] += get_reward(obs[i])
if get_terminal(obs[i])
push!(hook.rewards[i], hook.reward[i])
hook.reward[i] = 0.0
end
end
end
#####
# CumulativeReward
#####
"""
CumulativeReward(rewards::Vector{Float64} = [0.0], tag::String = "TRAINING")
Store cumulative rewards since the beginning to the field of `rewards`.
"""
Base.@kwdef struct CumulativeReward <: AbstractHook
rewards::Vector{Float64} = [0.0]
tag::String = "TRAINING"
end
function (hook::CumulativeReward)(::PostActStage, agent, env, obs)
push!(hook.rewards, get_reward(obs) + hook.rewards[end])
@debug hook.tag CUMULATIVE_REWARD = hook.rewards[end]
end
#####
# TimePerStep
#####
"""
TimePerStep(;max_steps=100)
TimePerStep(times::CircularArrayBuffer{Float64}, t::UInt64)
Store time cost of the latest `max_steps` in the `times` field.
"""
mutable struct TimePerStep <: AbstractHook
times::CircularArrayBuffer{Float64,1}
t::UInt64
end
TimePerStep(; max_steps = 100) =
TimePerStep(CircularArrayBuffer{Float64}(max_steps), time_ns())
function (hook::TimePerStep)(::PostActStage, agent, env, obs)
push!(hook.times, (time_ns() - hook.t) / 1e9)
hook.t = time_ns()
end
"""
DoEveryNStep(f; n=1, t=0)
Execute `f(agent, env, obs)` every `n` step.
`t` is a counter of steps.
"""
Base.@kwdef mutable struct DoEveryNStep{F} <: AbstractHook
f::F
n::Int = 1
t::Int = 0
end
DoEveryNStep(f, n = 1, t = 0) = DoEveryNStep(f, n, t)
function (hook::DoEveryNStep)(::PostActStage, agent, env, obs)
hook.t += 1
if hook.t % hook.n == 0
hook.f(hook.t, agent, env, obs)
end
end
"""
DoEveryNEpisode(f; n=1, t=0)
Execute `f(agent, env, obs)` every `n` episode.
`t` is a counter of steps.
"""
Base.@kwdef mutable struct DoEveryNEpisode{F} <: AbstractHook
f::F
n::Int = 1
t::Int = 0
end
DoEveryNEpisode(f, n = 1, t = 0) = DoEveryNEpisode(f, n, t)
function (hook::DoEveryNEpisode)(::PostEpisodeStage, agent, env, obs)
hook.t += 1
if hook.t % hook.n == 0
hook.f(hook.t, agent, env, obs)
end
end
|
{
"alphanum_fraction": 0.6744186047,
"author": null,
"avg_line_length": 24.4054054054,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "1df46eae4d3ffaa725fc5482d145ec3992249502",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "3fb0a9d56b5ed00d95148b556059045dac7d9cff",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "felixchalumeau/ReinforcementLearningCore.jl",
"max_forks_repo_path": "src/core/hooks.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3fb0a9d56b5ed00d95148b556059045dac7d9cff",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "felixchalumeau/ReinforcementLearningCore.jl",
"max_issues_repo_path": "src/core/hooks.jl",
"max_line_length": 114,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3fb0a9d56b5ed00d95148b556059045dac7d9cff",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "felixchalumeau/ReinforcementLearningCore.jl",
"max_stars_repo_path": "src/core/hooks.jl",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1812,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 6321
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.